# DICOM Viewer Debugging Guide

## Recent Changes (2026-01-13)

### Enhanced Error Handling & Logging

I've added comprehensive logging throughout the viewer initialization process to help diagnose why the viewer isn't displaying images. Here's what was added:

### Files Modified:

1. **[lib-loader.js](src/viewers/dicom/lib-loader.js)**
   - Added early logging to track script execution
   - Logs viewer path and lib path
   - Already had try-catch for library loading failures

2. **[viewport.js](src/viewers/dicom/viewport.js)**
   - Added console log when script loads
   - Added console log when Viewport class is defined
   - Confirms the class is available globally

3. **[viewport-manager.js](src/viewers/dicom/viewport-manager.js)**
   - Added console log when script loads
   - Added console log when ViewportManager class is defined
   - Confirms the class is available globally

4. **[viewer.js](src/viewers/dicom/viewer.js)**
   - Added logging at script load time
   - Added logging in DicomViewer constructor
   - Added checks for Viewport and ViewportManager class availability in setupUI()
   - Added detailed logging during ViewportManager initialization
   - Wrapped DicomViewer instantiation in try-catch
   - Added logging for DOMContentLoaded event

## How to Diagnose Issues

### Step 1: Open Developer Console

1. Open the DICOM viewer (the tab with the black screen)
2. Press **F12** or **Cmd+Option+I** (Mac) to open Developer Tools
3. Click on the **Console** tab

### Step 2: Expected Console Log Sequence

If everything is working correctly, you should see these logs in order:

```
[lib-loader.js] Script executing...
[lib-loader.js] IIFE starting...
[lib-loader.js] Viewer path: chrome-extension://[id]/src/viewers/dicom/
[lib-loader.js] Lib path: chrome-extension://[id]/src/viewers/dicom/lib/
[DICOM Viewer] Starting sequential library loading...
[DICOM Viewer] Loading 1/5: dicomParser.min.js...
[DICOM Viewer] ✓ Loaded: dicomParser.min.js
[DICOM Viewer] Loading 2/5: cornerstone.min.js...
[DICOM Viewer] ✓ Loaded: cornerstone.min.js
[DICOM Viewer] Loading 3/5: cornerstoneMath.min.js...
[DICOM Viewer] ✓ Loaded: cornerstoneMath.min.js
[DICOM Viewer] Loading 4/5: cornerstoneTools.min.js...
[DICOM Viewer] ✓ Loaded: cornerstoneTools.min.js
[DICOM Viewer] Loading 5/5: cornerstoneWADOImageLoader.min.js...
[DICOM Viewer] ✓ Loaded: cornerstoneWADOImageLoader.min.js
[DICOM Viewer] ✓ All libraries loaded successfully
[DICOM Viewer] ✓ All required globals verified
[DICOM Viewer] Loading viewport classes...
[viewport.js] Script loading...
[viewport.js] ✓ Viewport class defined and available globally
[DICOM Viewer] ✓ Viewport.js loaded
[viewport-manager.js] Script loading...
[viewport-manager.js] ✓ ViewportManager class defined and available globally
[DICOM Viewer] ✓ ViewportManager.js loaded
[DICOM Viewer] Loading viewer.js...
[DICOM Viewer] Script loaded, document.readyState: loading (or complete)
[DICOM Viewer] ✓ Viewer.js loaded
[DICOM Viewer] DOMContentLoaded event fired, creating DicomViewer...
[DICOM Viewer] DicomViewer constructor called
[DICOM Viewer] dicom-libraries-loaded event received
[DICOM Viewer] Initializing Cornerstone...
[DICOM Viewer] ✓ All libraries verified as loaded
[DICOM Viewer] Configuring WADO Image Loader...
[DICOM Viewer] Worker path: chrome-extension://[id]/src/viewers/dicom/lib/cornerstoneWADOImageLoaderWebWorker.js
[DICOM Viewer] Codec path: chrome-extension://[id]/src/viewers/dicom/lib/
[DICOM Viewer] ✓ WADO Image Loader configured
[DICOM Viewer] Configuring cornerstoneTools external dependencies...
[DICOM Viewer] ✓ External dependencies configured
[DICOM Viewer] ⚠️  Skipping cornerstoneTools due to v6 incompatibility
[DICOM Viewer] setupUI() starting...
[DICOM Viewer] ✓ Viewport class available
[DICOM Viewer] ✓ ViewportManager class available
[DICOM Viewer] ✓ Grid container found: [object HTMLDivElement]
[DICOM Viewer] Creating ViewportManager...
[DICOM Viewer] ✓ ViewportManager instance created
[DICOM Viewer] Setting initial layout to 1x1...
[ViewportManager] Setting layout: 1x1
[ViewportManager] Creating 1 viewports...
[ViewportManager] Creating viewport 0
[ViewportManager] ✓ Viewport 0 created
[ViewportManager] ✓ Layout set to 1x1
[DICOM Viewer] ✓ ViewportManager initialized with 1x1 layout
[DICOM Viewer] Loading series: [seriesId]
[DICOM Viewer] Series contains 22 images
[ViewportManager] Loading series into viewport 0
[Viewport 0] Loading series: [seriesId] - Images: 22
[Viewport 0] Loading image 1 / 22 - docId: [docId]
```

### Step 3: Identify Where It Stops

Find the **LAST** log message you see. This tells us exactly where the failure occurs:

#### If you see NO logs at all:
- **Problem**: lib-loader.js isn't executing
- **Cause**: Script not loading or blocked by Content Security Policy
- **Fix**: Check Network tab for failed script loads

#### If logs stop at "Loading [n]/5: [library].js":
- **Problem**: A Cornerstone library failed to load
- **Cause**: Library file missing or path incorrect
- **Fix**: Check that all library files exist in `src/viewers/dicom/lib/`

#### If logs stop at "Viewport class not loaded":
- **Problem**: viewport.js didn't load or define the class
- **Cause**: Script error in viewport.js or loading order issue
- **Fix**: Check for JavaScript errors in Console

#### If logs stop at "ViewportManager class not loaded":
- **Problem**: viewport-manager.js didn't load or define the class
- **Cause**: Script error in viewport-manager.js or loading order issue
- **Fix**: Check for JavaScript errors in Console

#### If logs stop at "Grid container not found":
- **Problem**: HTML structure doesn't have viewport-grid element
- **Cause**: viewer.html not updated correctly
- **Fix**: Check that viewer.html has `<div id="viewport-grid">` element

#### If logs stop at "Creating viewport 0":
- **Problem**: Viewport creation failing
- **Cause**: Cornerstone.enable() failing or canvas creation issue
- **Fix**: Check for Cornerstone-related errors

#### If logs stop at "Loading series":
- **Problem**: Series data not found or invalid
- **Cause**: GET_SERIES message failing or series not in IndexedDB
- **Fix**: Check background script logs for GET_SERIES response

#### If you see error messages:
- **Look for**: Red error messages with "FATAL" or stack traces
- **These tell you**: Exactly what went wrong and where
- **Share these**: With me so I can fix the specific issue

## Common Issues & Solutions

### Issue 1: Blank Screen, No Console Logs

**Symptoms**: Viewer opens but is completely blank, no console logs at all

**Diagnosis**:
- Open Developer Console (F12)
- Check Console tab
- Check Network tab for failed script loads

**Solutions**:
1. Clear browser cache and reload
2. Check that manifest.json includes all viewer files in `web_accessible_resources`
3. Check Content Security Policy isn't blocking scripts

### Issue 2: "Viewport class not loaded" Error

**Symptoms**: Error message says viewport.js didn't load

**Diagnosis**:
- Check if you see `[viewport.js] Script loading...` in console
- Check Network tab for viewport.js load status

**Solutions**:
1. Verify viewport.js exists at `src/viewers/dicom/viewport.js`
2. Check for syntax errors in viewport.js
3. Reload the extension

### Issue 3: "Grid container not found" Error

**Symptoms**: Error says viewport-grid element doesn't exist

**Diagnosis**:
- Inspect HTML structure
- Look for `<div id="viewport-grid">`

**Solutions**:
1. Re-apply the viewer.html changes from VIEWER_HTML_CHANGES.md
2. Verify the HTML structure matches the expected layout

### Issue 4: Folder Browser Not Showing

**Symptoms**: 📁 button doesn't appear

**Diagnosis**:
- Check if projectId is present in URL params
- Look for log: "Folder browser toggle button shown"

**Solutions**:
1. Verify projectId is in the viewer URL: `?seriesId=xxx&projectId=123`
2. Check that loadProjectFoldersInBackground() is being called
3. Look for errors in folder loading

### Issue 5: Images Download But Don't Display

**Symptoms**: Background script shows files downloading, but viewport stays black

**Diagnosis**:
- Check Viewport loading logs
- Look for Cornerstone errors

**Solutions**:
1. Verify Cornerstone libraries loaded successfully
2. Check if viewport.loadImage() is being called
3. Look for DICOM parsing errors

## Next Steps

1. **Open the viewer and get console logs**
   - This is the MOST IMPORTANT step
   - Without console logs, we're debugging blind

2. **Share the console output**
   - Copy ALL console messages
   - Include both info and error messages
   - Share the last message you see before it stops

3. **Check for error messages**
   - Look for red error messages
   - Copy the full error including stack trace

4. **Test with a simple series**
   - Try loading a small series (1-5 images)
   - See if the same issue occurs

## Architecture Reference

```
viewer.html
    │
    ├── lib-loader.js (loads libraries sequentially)
    │   ├── dicomParser.min.js
    │   ├── cornerstone.min.js
    │   ├── cornerstoneMath.min.js
    │   ├── cornerstoneTools.min.js
    │   ├── cornerstoneWADOImageLoader.min.js
    │   ├── viewport.js (defines Viewport class)
    │   ├── viewport-manager.js (defines ViewportManager class)
    │   └── viewer.js (defines DicomViewer class)
    │
    └── DicomViewer (main controller)
        └── ViewportManager (manages grid)
            └── Viewport[] (individual canvases)
```

## File Locations

- Main HTML: [src/viewers/dicom/viewer.html](src/viewers/dicom/viewer.html)
- Script Loader: [src/viewers/dicom/lib-loader.js](src/viewers/dicom/lib-loader.js)
- Viewport Class: [src/viewers/dicom/viewport.js](src/viewers/dicom/viewport.js)
- Viewport Manager: [src/viewers/dicom/viewport-manager.js](src/viewers/dicom/viewport-manager.js)
- Main Viewer: [src/viewers/dicom/viewer.js](src/viewers/dicom/viewer.js)

## Contact

If you're still stuck after checking console logs:
1. Copy the ENTIRE console output
2. Note the LAST log message you see
3. Copy any error messages (in red)
4. Share these with me so I can diagnose the specific issue

The enhanced logging will show us exactly where initialization is failing.
