# Changelog

> **Purpose**: Track all significant changes, fixes, and improvements to the Filevine Document Viewer Extension.
> **Last Updated**: 2025-01-13

---

## 2025-01-13: DICOM Folder Browser with Collapsible Tree & Smart Filtering

### Major Features

#### 1. Interactive Folder Browser in DICOM Viewer
- **Added**: Folder browser sidebar in DICOM viewer with hierarchical folder tree
- **Added**: Collapsible/expandable folders with ▶/▼ icons
- **Added**: File count display for each folder showing number of DICOM files
- **Modified**: `src/viewers/dicom/viewer.js` - Added folder browser UI components and navigation
- **Modified**: `src/viewers/dicom/viewer.html` - Added folder browser sidebar HTML structure
- **Added**: Helper methods: `hasChildren()`, `getChildFolders()`, `toggleFolderCollapse()`

**Why**: Users needed an easy way to browse and load different DICOM series from within the viewer, rather than downloading each series separately from the sidebar.

**Impact**:
- Users can now browse all DICOM folders in a project from within the viewer
- Quick switching between different DICOM series
- Visual hierarchy makes it easy to understand folder structure

#### 2. Smart Folder Filtering
- **Added**: `filterFoldersWithDicomFiles()` method in `src/background/downloads.js`
- **Modified**: Folder tree now filters out empty folders and folders without DICOM files
- **Added**: Parent folder retention - keeps parent folders if any descendant contains DICOM files

**Why**: Project folder structures can be large with many non-DICOM folders. Showing only relevant folders reduces clutter and improves usability.

**Impact**:
- Cleaner UI with only DICOM-relevant folders shown
- Faster loading since fewer folders to process
- Example: If project has 98 folders but only 6 contain DICOM files, only ~8-10 folders shown (6 with files + 2-4 parent folders)

#### 3. Background Folder Tree Loading
- **Modified**: `src/viewers/dicom/viewer.js` - Moved folder tree loading to background after initial image loads
- **Added**: `loadProjectFoldersInBackground()` method
- **Modified**: Initialization flow to load initial file/series first, then folder tree asynchronously

**Why**: Large folder trees can take several seconds to fetch. Users shouldn't have to wait to see their initial image.

**Impact**:
- DICOM viewer opens immediately with initial image
- Folder browser populates in background
- Toggle button appears immediately so users know feature exists

#### 4. Two-Step Folder Tree API Pattern
- **Modified**: `src/background/downloads.js` - Implemented two-call pattern for folder tree fetching
- **Added**: First call with `descendantFolderIDs: []` to get root folders
- **Added**: Second call with all folder IDs to get complete tree

**Why**: Filevine's folder tree API requires explicit folder IDs to return descendants. Empty array only returns first level.

**Impact**:
- Successfully retrieves complete folder hierarchy (e.g., 26 root folders → 98 total folders)
- Proper parent-child relationships maintained

#### 5. Batch Document Fetching
- **Added**: `fetchDocumentsForFolders()` method in `src/background/downloads.js`
- **Modified**: Fetches documents for each folder in batches of 5 to avoid overwhelming API
- **Added**: Document metadata storage: docId, filename, size, uploadedBy, uploadedAt
- **Added**: DICOM file filtering by `.dcm` extension

**Why**: Need to know which folders contain DICOM files for filtering and to display accurate file counts.

**Impact**:
- Accurate file counts shown in folder browser
- Only DICOM files included
- API-friendly batching prevents rate limiting

#### 6. Enhanced Error Handling
- **Added**: Validation for `docId` in `getFile()` method
- **Added**: Document structure logging for debugging
- **Added**: Warnings for documents missing IDs
- **Added**: Fallback checks for multiple document ID property names: `docId`, `documentID`, `documentId`, `id`

**Why**: API responses can have inconsistent property names, causing undefined docIds and IndexedDB errors.

**Impact**:
- Prevents `DataError: Failed to execute 'get' on 'IDBObjectStore'` errors
- More robust document loading with multiple property name fallbacks
- Better debugging with detailed logging

### Technical Details

**Folder Tree Structure**:
```javascript
{
  folderId: number,
  folderName: string,
  folderPath: string[],  // Full path array
  files: Array<{
    docId: number,
    filename: string,
    size: number,
    uploadedBy: string,
    uploadedAt: string
  }>,
  depth: number  // 0 for root, 1+ for nested
}
```

**UI Components**:
- Folder browser sidebar (280px wide, collapsible)
- Folder items with expand/collapse icons
- File count badges
- Visual indentation (16px per depth level)
- Hover effects and active folder highlighting

### Files Modified

- `src/viewers/dicom/viewer.js` - Folder browser UI, collapse/expand logic, background loading
- `src/viewers/dicom/viewer.html` - Folder browser sidebar structure
- `src/background/downloads.js` - Folder tree fetching, document fetching, filtering logic
- `src/background/web-api-client.js` - Document fetching with folderID parameter
- `HOW_TO_USE_DICOM_VIEWER.md` - Updated documentation with folder browser guide

### Known Issues

None currently identified.

---

## 2025-01-12: Cookie-Based Authentication & Web App API Integration

### Major Changes

#### 1. Cookie-Based Authentication Implementation
- **Added**: `src/background/cookie-interceptor.js` - Intercepts ASP.NET Application Cookies from Filevine
- **Added**: `src/background/web-api-client.js` - New API client for Filevine's web app API (`product.filevineapp.com/api`)
- **Modified**: `src/background/auth.js` - Added `processCookieAuth()` method to handle cookie-based authentication
- **Modified**: `src/background/index.js` - Routes API calls to appropriate client based on auth method

**Why**: Filevine's web app uses HTTP-only cookies, not Bearer tokens. Discovered during testing that token extraction wasn't working, so pivoted to cookie-based auth.

**Impact**: 
- Projects now load successfully
- Documents now load successfully
- Downloads use correct API client based on auth method

#### 2. Content Script Bundling Fix
- **Created**: `src/content/index.bundle.js` - Bundled version of content script without ES6 modules
- **Created**: `src/content/interception.js` - Network interception script injected into page context
- **Modified**: `manifest.json` - Updated content script entry to use bundled version, added web_accessible_resources

**Why**: Chrome MV3 content scripts don't support ES6 modules (static or dynamic imports). Had to bundle all dependencies into a single file.

**Impact**: Content script now loads and executes correctly.

#### 3. Projects Loading Fix
- **Modified**: `src/background/web-api-client.js` - Implemented `getProjects()` using POST to `/projectHub/search`
- **Modified**: `src/popup/popup.js` - Fixed project list rendering to use `hits` array from response

**Why**: Filevine's web app API uses different endpoints and request/response formats than the external API.

**Impact**: Projects now display in popup UI.

#### 4. Documents Loading Fix
- **Modified**: `src/background/web-api-client.js` - Implemented `getProjectDocuments()` with correct endpoint `/docs/project/{projectId}`
- **Added**: Folder tree fetching to get `projectRootFolderID` before fetching documents
- **Modified**: `src/popup/popup.js` - Updated document rendering to handle Filevine API field names (`id`, `filename`, `size`)

**Why**: Documents endpoint requires `folderID` parameter, which must be fetched from folder tree endpoint first.

**Impact**: Documents now load when selecting a project.

#### 5. Download Functionality Update
- **Modified**: `src/background/downloads.js` - Updated to use web API client when using cookie-based auth
- **Added**: `src/background/web-api-client.js` - Added `getDocumentDownloadUrl()` method with multiple endpoint fallbacks

**Why**: Downloads were failing because they tried to use external API client (needs Bearer tokens) instead of web API client (uses cookies).

**Impact**: Downloads now use correct API client (pending endpoint verification).

#### 6. Icon Updates
- **Added**: `public/icons/icon16.png`, `icon48.png`, `icon128.png` - Converted from `filevine_logo.jpeg`
- **Modified**: `manifest.json` - Updated icon paths

**Why**: User requested to use Filevine logo as extension icon.

**Impact**: Extension now displays Filevine logo instead of default icon.

### Bug Fixes

1. **Content Script Module Error**: Fixed `Uncaught SyntaxError: Cannot use import statement outside a module` by bundling content script
2. **CSP Violation**: Fixed Content Security Policy violation by moving interception script to separate file and injecting via `<script src>`
3. **Projects Not Loading**: Fixed by implementing web API client and correct endpoint (`/projectHub/search`)
4. **Documents Not Loading**: Fixed by using correct endpoint (`/docs/project/{projectId}`) and fetching folder ID first
5. **User ID Extraction**: Fixed by extracting `userId` from `ownerID` field in `/api/orgs` response
6. **Icon Format**: Fixed icon conversion issue (was creating JPEG files with PNG extensions)

### API Endpoint Discoveries

During testing, discovered the following Filevine web app API endpoints:

- **Projects**: `POST /api/projectHub/search` (not `/Projects` like external API)
- **Folder Tree**: `POST /api/projects/{projectId}/limitedProjectFolderTree`
- **Documents**: `POST /api/docs/project/{projectId}` (not `/projects/{id}/Docs`)
- **User Info**: `GET /api/currentuser/setting/uiSettings` or `/api/orgs`

### Files Changed

**New Files**:
- `src/background/cookie-interceptor.js`
- `src/background/web-api-client.js`
- `src/content/index.bundle.js`
- `src/content/interception.js`
- `public/icons/icon16.png`
- `public/icons/icon48.png`
- `public/icons/icon128.png`

**Modified Files**:
- `src/background/auth.js`
- `src/background/index.js`
- `src/background/downloads.js`
- `src/popup/popup.js`
- `manifest.json`

### Testing Status

- ✅ Projects loading
- ✅ Documents loading
- ⏳ Downloads (pending endpoint verification)
- ✅ Cookie interception working
- ✅ Web API client authentication working

### Known Issues

1. **Download Endpoint**: Download URL endpoint not yet verified - code tries multiple patterns but needs Network tab verification
2. **WebSocket Tokens**: WebSocket tokens are for discussions, not main API - correctly skipped now

### Next Steps

1. Verify download endpoint from Network tab when user clicks download in Filevine
2. Test download functionality end-to-end
3. Implement Phase 2 features (pagination, document tree navigation, etc.)

---

## 2025-01-12: Initial Documentation Setup

### Major Changes

#### Documentation Structure Created
- **Created**: `.ai/ARCHITECTURE.md` - System architecture overview
- **Created**: `.ai/SERVICES.md` - Complete service catalog (10 services)
- **Created**: `.ai/DATA_FLOW.md` - Data flow diagrams (5 flows)
- **Created**: `.ai/DECISIONS.md` - Architecture Decision Records (10 ADRs)
- **Created**: `.ai/CURRENT_TASK.md` - Active work context
- **Created**: `.ai/TROUBLESHOOTING.md` - Known issues and solutions
- **Created**: `AI_System_Prompt.md` - High-level system instructions
- **Updated**: `AI_INSTRUCTIONS.md` - Master documentation map

**Why**: Following documentation-first development principles to enable effective AI collaboration.

**Impact**: All services, flows, and decisions are now documented and discoverable.

---

## Format

Each entry follows this structure:

```markdown
## YYYY-MM-DD: Feature Name

### Major Changes
- **Added**: New files/features
- **Modified**: Changed files/features
- **Removed**: Deleted files/features

**Why**: Explanation of why change was made

**Impact**: What this change affects

### Bug Fixes
1. **Issue Name**: Description and fix

### Files Changed
- List of files

### Testing Status
- What's been tested

### Known Issues
- Any remaining issues

### Next Steps
- What's next
```
