# Troubleshooting Guide

> **Purpose**: Capture problems and solutions to avoid re-solving.  
> **Last Updated**: 2025-01-12 20:00 UTC

## Index by Symptom

| Symptom | Cause | Solution |
|---------|-------|----------|
| "Not authenticated" errors | Token extraction failed | Check content script logs, verify Filevine page loaded |
| API returns 404 | Wrong endpoint casing | Use PascalCase (`/Projects` not `/projects`) |
| API returns 401 | Wrong user ID format | Use numeric ID from GetUserOrgsWithToken, not JWT sub |
| Token extraction fails | Page structure changed | Try multiple extraction methods, check storage keys |
| Downloads fail | Wrong API client or endpoint | Use web API client for cookie-based auth, verify endpoint |
| Extension doesn't detect session | Content script not injected | Reload Filevine page, check manifest permissions |
| Background worker stops | Browser terminated it | Normal behavior, re-initializes on next message |
| "Cannot use import statement" | ES6 modules in content script | Use bundled version (index.bundle.js) |
| Projects not loading | Wrong API client or endpoint | Use web API client with `/projectHub/search` endpoint |
| Documents not loading | Missing folderID or wrong endpoint | Fetch folder tree first, use `/docs/project/{id}` endpoint |
| User ID is "unknown" | Wrong extraction method | Extract from `ownerID` in `/api/orgs` response |

---

## Problem: API Returns 404 Errors

**Symptom**: API calls return 404 Not Found errors

**Root Cause**: Filevine API requires PascalCase endpoints, not lowercase REST conventions.

**Solution**:
```javascript
// Wrong
GET /projects/12345

// Correct
GET /Projects/12345
```

**How to Diagnose**:
1. Check network tab in DevTools
2. Verify endpoint URL matches PascalCase pattern
3. Check `src/lib/constants.js` for correct endpoint definitions

**Prevention**: Always use constants from `src/lib/constants.js` instead of hardcoding endpoints.

**Date Found**: 2025-01-12  
**Related**: ADR-005, `SERVICES.md#filevineclient`

---

## Problem: API Returns 401 Unauthorized

**Symptom**: API calls return 401 even with valid access token

**Root Cause**: Using UUID from JWT `sub` claim instead of numeric user ID required by API.

**Solution**:
```javascript
// Wrong - using JWT sub claim
const userId = jwtClaims.sub;  // UUID format

// Correct - get numeric ID from API
const response = await fetch('/utils/GetUserOrgsWithToken', ...);
const userId = String(response.user.userId.native);  // Numeric string
```

**How to Diagnose**:
1. Check `x-fv-userid` header value in network requests
2. Verify it's numeric, not UUID format
3. Check AuthManager.processTokens() implementation

**Prevention**: Always call GetUserOrgsWithToken to get numeric user ID.

**Date Found**: 2025-01-12  
**Related**: ADR-004, `SERVICES.md#authmanager`

---

## Problem: Token Extraction Fails

**Symptom**: Extension shows "Disconnected" even when logged into Filevine

**Root Cause**: Token extraction methods fail due to page structure variations or security policies.

**Solution**:
1. Check content script console logs (DevTools on Filevine page)
2. Verify content script is injected (check `chrome://extensions` → service worker)
3. Try manual extraction:
   ```javascript
   // In Filevine page console
   localStorage.getItem('fv_access_token')
   // or
   Object.keys(localStorage).filter(k => k.includes('token'))
   ```
4. Check if network interception is working (look for "Network interception active" log)

**How to Diagnose**:
1. Open DevTools on Filevine page
2. Check Console for `[Filevine Plugin]` logs
3. Verify TokenExtractor tried all methods
4. Check if tokens exist in storage

**Workaround**: If extraction fails, user may need to refresh Filevine page or log out/in.

**Date Found**: 2025-01-12  
**Related**: ADR-008, `SERVICES.md#tokenextractor`

---

## Problem: Downloads Fail with Network Error

**Symptom**: Downloads start but fail with network errors

**Root Cause**: S3 presigned URLs expire, or network issues accessing S3.

**Solution**:
1. Check download error in DownloadManager logs
2. Verify presigned URL is still valid (expires after ~1 hour)
3. Re-request download URL if expired:
   ```javascript
   // DownloadManager will automatically get new URL
   await downloadManager.queueDownload({ docId, ... });
   ```

**How to Diagnose**:
1. Check background service worker logs
2. Verify S3 URL in network tab
3. Check if URL has expired (expiresAt timestamp)

**Prevention**: DownloadManager should handle expired URLs and re-request.

**Date Found**: 2025-01-12  
**Related**: `SERVICES.md#downloadmanager`

---

## Problem: Extension Doesn't Detect Filevine Session

**Symptom**: Extension shows "Disconnected" when user is logged into Filevine

**Root Cause**: Content script not injected, or page URL doesn't match manifest patterns.

**Solution**:
1. Verify manifest.json has correct host_permissions:
   ```json
   "host_permissions": ["https://*.filevineapp.com/*"]
   ```
2. Reload Filevine page (content script injects on page load)
3. Check if content script is running:
   ```javascript
   // In Filevine page console
   console.log('[Filevine Plugin] Content script loaded');
   ```
4. Reload extension in `chrome://extensions`

**How to Diagnose**:
1. Check `chrome://extensions` → Filevine Viewer → "service worker" logs
2. Check Filevine page console for content script logs
3. Verify page URL matches `*.filevineapp.com`

**Date Found**: 2025-01-12  
**Related**: `SERVICES.md#contentscript`, `manifest.json`

---

## Problem: Background Service Worker Terminated

**Symptom**: Extension stops responding, then works again after user action

**Root Cause**: Chrome terminates idle service workers to save resources. Normal MV3 behavior.

**Solution**: No action needed - service worker re-initializes automatically on next message.

**How to Diagnose**:
1. Check service worker status in `chrome://extensions`
2. Look for "Service worker inactive" message
3. Send any message (e.g., open popup) to reactivate

**Prevention**: This is expected behavior. Extension handles re-initialization automatically.

**Date Found**: 2025-01-12  
**Related**: ADR-006, `SERVICES.md#backgroundservice`

---

## Problem: IndexedDB Storage Errors

**Symptom**: Downloads complete but files can't be retrieved

**Root Cause**: IndexedDB transaction errors, database not initialized, or storage quota exceeded.

**Solution**:
1. Check browser storage quota:
   ```javascript
   navigator.storage.estimate().then(estimate => console.log(estimate));
   ```
2. Clear old files:
   ```javascript
   await downloadManager.clearAllFiles();
   ```
3. Re-initialize database:
   ```javascript
   await downloadManager.initializeDb();
   ```

**How to Diagnose**:
1. Check background service worker logs for IndexedDB errors
2. Verify database exists in DevTools → Application → IndexedDB
3. Check storage quota usage

**Prevention**: Implement auto-cleanup of old files, check quota before downloads.

**Date Found**: 2025-01-12  
**Related**: ADR-002, `SERVICES.md#downloadmanager`

---

## Problem: Rate Limiting Errors (429)

**Symptom**: API calls return 429 Too Many Requests

**Root Cause**: Exceeded Filevine API rate limits (100/min burst, 600/hr sustained).

**Solution**:
1. FilevineClient automatically retries with backoff
2. Wait for rate limit window to reset
3. Reduce request frequency if possible

**How to Diagnose**:
1. Check network tab for 429 responses
2. Look for Retry-After header
3. Check FilevineClient rate limiting implementation

**Prevention**: Rate limiting is implemented in FilevineClient, but may need tuning.

**Date Found**: 2025-01-12  
**Related**: ADR-009, `SERVICES.md#filevineclient`

---

## Problem: DICOM Viewer Shows Placeholder

**Symptom**: DICOM files open but show placeholder instead of image

**Root Cause**: DICOM viewer not fully implemented - needs cornerstone.js integration.

**Solution**:
1. Install cornerstone.js:
   ```bash
   npm install cornerstone-core cornerstone-wado-image-loader
   ```
2. Integrate into `src/viewers/dicom/viewer.html`
3. Implement DICOM parsing and rendering

**How to Diagnose**:
1. Check viewer.html - shows placeholder message
2. Verify DICOM file loads (check network tab)
3. Check console for rendering errors

**Status**: Expected - DICOM viewer is placeholder for future implementation.

**Date Found**: 2025-01-12  
**Related**: `src/viewers/dicom/viewer.html`, `README.md#phase-4`

---

## Problem: Content Script ES6 Module Error

**Symptom**: `Uncaught SyntaxError: Cannot use import statement outside a module` in content script

**Root Cause**: Chrome MV3 content scripts don't support ES6 modules (neither static nor dynamic imports).

**Solution**:
1. Bundle all content script dependencies into a single file
2. Use `index.bundle.js` instead of `index.js` in manifest.json
3. Don't use `import` statements in content scripts

**How to Diagnose**:
1. Check console for SyntaxError
2. Verify manifest.json points to bundled file
3. Check that bundled file doesn't use `import` statements

**Prevention**: Always bundle content scripts, use webpack or similar bundler.

**Date Found**: 2025-01-12  
**Related**: `manifest.json`, `src/content/index.bundle.js`

---

## Problem: Content Security Policy Violation

**Symptom**: `Executing inline script violates the following Content Security Policy directive`

**Root Cause**: CSP blocks inline scripts. Network interception script must be in separate file.

**Solution**:
1. Move interception code to separate file (`interception.js`)
2. Add file to `web_accessible_resources` in manifest.json
3. Inject via `<script src="...">` tag, not inline

**How to Diagnose**:
1. Check console for CSP error
2. Verify script is in web_accessible_resources
3. Check injection method (should use `<script src>`)

**Prevention**: Never use inline scripts in content scripts.

**Date Found**: 2025-01-12  
**Related**: `src/content/interception.js`, `manifest.json`

---

## Problem: Projects Not Loading

**Symptom**: Projects list is empty in popup UI

**Root Cause**: Using wrong API client (external API needs Bearer tokens) or wrong endpoint.

**Solution**:
1. Use `webApiClient` when using cookie-based auth
2. Use correct endpoint: `POST /api/projectHub/search`
3. Use correct request body format (with `orgID`, `query`, `skip`, `take`, etc.)

**How to Diagnose**:
1. Check background console for API errors
2. Verify `usingWebApi` flag in auth state
3. Check Network tab for actual endpoint used by Filevine
4. Verify response format (`response.data.hits` for projects)

**Prevention**: Always check auth method and use appropriate API client.

**Date Found**: 2025-01-12  
**Related**: `src/background/web-api-client.js`, `src/background/index.js`

---

## Problem: Documents Not Loading

**Symptom**: Documents list is empty when selecting a project

**Root Cause**: Wrong endpoint or missing `folderID` parameter.

**Solution**:
1. First fetch folder tree: `POST /api/projects/{projectId}/limitedProjectFolderTree`
2. Extract `projectRootFolderID` from response (`data.index.projectRootFolderID`)
3. Use correct endpoint: `POST /api/docs/project/{projectId}` (not `/projects/{id}/Docs`)
4. Include `folderID` in request body

**How to Diagnose**:
1. Check background console for 404 errors
2. Verify folder tree is fetched first
3. Check that `folderID` is included in documents request
4. Verify endpoint URL matches Filevine's actual endpoint

**Prevention**: Always fetch folder tree first, use correct endpoint format.

**Date Found**: 2025-01-12  
**Related**: `src/background/web-api-client.js`

---

## Problem: User ID is "unknown" After Cookie Auth

**Symptom**: User ID shows as "unknown" after cookie-based authentication

**Root Cause**: Wrong extraction method - user ID is in `ownerID` field, not directly in response.

**Solution**:
1. Call `/api/orgs` endpoint (fallback if `/api/currentuser/setting/uiSettings` doesn't have user info)
2. Extract `userId` from `response.ownerID` field
3. Convert to string if needed

**How to Diagnose**:
1. Check auth state - `userId` should be numeric string
2. Verify `/api/orgs` response structure
3. Check extraction logic in `auth.js`

**Prevention**: Always verify response structure before extracting fields.

**Date Found**: 2025-01-12  
**Related**: `src/background/auth.js`

---

## Problem: Downloads Fail with "Client not authenticated"

**Symptom**: Downloads fail with error "Client not authenticated. Call setCredentials first."

**Root Cause**: Download manager using wrong API client (external API needs Bearer tokens, but using cookie-based auth).

**Solution**:
1. Check auth state to determine which API client to use
2. Use `webApiClient` when `usingWebApi` is true
3. Use `filevineClient` when using Bearer tokens

**How to Diagnose**:
1. Check download error message
2. Verify auth state (`usingWebApi` flag)
3. Check which API client is being used in `downloads.js`

**Prevention**: Always check auth method before making API calls.

**Date Found**: 2025-01-12  
**Related**: `src/background/downloads.js`, `src/background/web-api-client.js`

---

## Adding a New Troubleshooting Entry

1. Use template above
2. Include symptom, root cause, solution, diagnosis steps
3. Link to related services and ADRs
4. Add to index table at top
5. Include date found and related documentation
