# Filevine Document Viewer Plugin

A Chrome/Edge browser extension for browsing, downloading, and viewing Filevine documents with specialized viewers (starting with DICOM radiology images).

## ✨ Features

### Document Management
- Browse and search Filevine projects and documents
- Download files with progress tracking
- Specialized viewers for medical imaging (DICOM)
- Forensic watermarking with Echomark integration

### Custom Field Management
- **AI Section Builder** - Generate custom field configurations from plain text requirements using Claude AI
- **Manual Field Creator** - Create individual custom fields with full control
- Auto-populate org and project type IDs
- Load and select from existing custom sections
- Support for all 36 Filevine field types

### AI-Powered Workflow
The AI Section Builder uses Claude 4.5 Sonnet to:
- Analyze plain text requirements
- Design appropriate field configurations
- Select optimal field types automatically
- Organize fields with section headers
- Create all fields sequentially in Filevine

See [AI_SECTION_BUILDER.md](docs/AI_SECTION_BUILDER.md) for detailed usage guide.

## 🚀 Quick Start

### Load as Unpacked Extension

1. Open Chrome/Edge and navigate to `chrome://extensions`
2. Enable "Developer mode" (toggle in top-right)
3. Click "Load unpacked"
4. Select this `filevine-plugin` directory
5. Navigate to Filevine and log in
6. Click the extension icon to start browsing files

### Development with Cursor

This project is designed for iterative development with AI coding tools:

```bash
# Open in Cursor
cursor /path/to/filevine-plugin

# Key files to start with:
# 1. src/background/auth.js - Authentication flow
# 2. src/content/extractor.js - Token extraction from page
# 3. src/popup/popup.js - UI controller
# 4. src/viewers/dicom/viewer.html - DICOM viewer
```

## 📁 Project Structure

```
filevine-plugin/
├── manifest.json           # Chrome extension manifest (MV3)
├── package.json            # Node dependencies (minimal)
├── docs/
│   └── DESIGN.md           # Full design document
├── src/
│   ├── background/         # Service worker (runs in background)
│   │   ├── index.js        # Entry point, message routing
│   │   ├── auth.js         # Token management & validation
│   │   ├── api.js          # Filevine API client
│   │   └── downloads.js    # Download queue & IndexedDB storage
│   ├── content/            # Content scripts (injected into Filevine pages)
│   │   ├── index.js        # Entry point
│   │   ├── detector.js     # Session/page change detection
│   │   └── extractor.js    # Token extraction from page context
│   ├── popup/              # Extension popup UI
│   │   ├── popup.html
│   │   ├── popup.css
│   │   └── popup.js
│   ├── viewers/            # File viewer plugins
│   │   ├── registry.js     # Viewer registration
│   │   └── dicom/          # DICOM viewer
│   │       └── viewer.html
│   └── lib/                # Shared utilities
│       └── constants.js    # API URLs, message types, etc.
└── public/
    └── icons/              # Extension icons (create these)
```

## 🔑 Authentication

This extension uses a **hybrid authentication approach**:

1. **Content script** detects when you're logged into Filevine
2. **Extracts tokens** from the page (localStorage, network intercept)
3. **Sends to background** service worker for API calls
4. **All API calls** happen from background (avoids CORS issues)

### Critical Filevine API Requirements

From our implementation guide (discovered through testing):

| Requirement | Correct | Wrong |
|------------|---------|-------|
| Base URL | `api.filevineapp.com/fv-app/v2` | `api.filevine.io/v2` |
| User ID | Numeric from `GetUserOrgsWithToken` | UUID from JWT `sub` |
| Endpoints | PascalCase (`/Projects`) | lowercase (`/projects`) |
| Headers | All 3 `x-fv-*` headers required | Missing any header |

## 🛠️ Development Phases

### Phase 1: Foundation ✅ (Current)
- [x] Project scaffold
- [x] Manifest with permissions
- [x] Content script session detection
- [x] Background worker with auth flow
- [x] Basic popup UI

### Phase 2: File Browser
- [ ] Test with real Filevine session
- [ ] Project listing pagination
- [ ] Document tree navigation
- [ ] File type icons and metadata

### Phase 3: Downloads
- [ ] Download queue with progress
- [ ] IndexedDB file storage
- [ ] Resume interrupted downloads
- [ ] Bulk download support

### Phase 4: DICOM Viewer
- [ ] Integrate cornerstone.js
- [ ] Window/level controls
- [ ] Zoom, pan, rotate
- [ ] Measurement tools
- [ ] Multi-frame support

### Phase 5: Polish & Pilot
- [ ] Error handling improvements
- [ ] User preferences
- [ ] Performance optimization
- [ ] Customer pilot deployment

## 🧪 Testing

### Manual Testing Checklist

1. **Authentication**
   - [ ] Opens popup when disconnected → shows "Open Filevine to connect"
   - [ ] Detects session when navigating to Filevine
   - [ ] Shows "Connected" status after detection
   - [ ] Handles session expiry gracefully

2. **Project Browser**
   - [ ] Lists accessible projects
   - [ ] Search filters projects
   - [ ] Clicking project shows documents

3. **Downloads**
   - [ ] Download button starts download
   - [ ] Progress shows in downloads panel
   - [ ] File opens in appropriate viewer

### Debug Tips

```javascript
// In Chrome DevTools console on Filevine page:
chrome.runtime.sendMessage({ type: 'get_auth_state' }, console.log);

// Check background service worker logs:
// chrome://extensions → Filevine Viewer → "service worker" link
```

## 📝 Next Steps for Cursor

When working on this project in Cursor, here are good prompts to try:

**Auth debugging:**
> "The token extraction isn't working. Add more console logging to src/content/extractor.js and list all the localStorage keys it finds"

**API testing:**
> "Add a test button to the popup that calls the Projects endpoint and logs the response"

**DICOM viewer:**
> "Integrate cornerstone.js into the DICOM viewer. Add npm install commands needed and update viewer.html"

**Error handling:**
> "Add better error messages when API calls fail. Show user-friendly messages in the popup"

## 📚 Resources

- [Filevine API Docs](https://developer.filevine.io/docs/v2-ca/)
- [Chrome Extension MV3 Docs](https://developer.chrome.com/docs/extensions/mv3/)
- [Cornerstone.js (DICOM rendering)](https://cornerstonejs.org/)
- [OHIF Viewer (alternative DICOM viewer)](https://ohif.org/)

## ⚠️ Known Limitations

1. **Token extraction** may not work on all Filevine page configurations
2. **DICOM viewer** is a placeholder - needs cornerstone.js integration
3. **No offline support** yet
4. **Single-user** - doesn't handle multiple Filevine accounts

## 📄 License

Internal use only. Not licensed for distribution.
