> ## Documentation Index
> Fetch the complete documentation index at: https://docs.olis-ai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Chrome Extension

> Browser integration for quick access to Olis features

## Overview

The Olis Chrome Extension provides seamless browser integration, allowing users to access Olis features directly from their browser while browsing the web.

## Technology Stack

<CardGroup cols={2}>
  <Card title="Manifest V3" icon="chrome">
    Latest Chrome extension API
  </Card>

  <Card title="TypeScript" icon="code">
    Type-safe extension development
  </Card>

  <Card title="Webpack" icon="cube">
    Module bundling and optimization
  </Card>

  <Card title="React" icon="react">
    UI components for popup and options
  </Card>
</CardGroup>

## Project Structure

```bash theme={null}
apps/chrome-extension/
├── src/
│   ├── background/        # Service worker
│   ├── content/           # Content scripts
│   ├── popup/             # Extension popup UI
│   ├── options/           # Options page
│   └── shared/            # Shared utilities
├── public/
│   ├── manifest.json      # Extension manifest
│   └── icons/             # Extension icons
└── dist/                  # Build output
```

## Development Setup

<Steps>
  <Step title="Navigate to the extension directory">
    ```bash theme={null}
    cd apps/chrome-extension
    ```
  </Step>

  <Step title="Install dependencies">
    ```bash theme={null}
    pnpm install
    ```
  </Step>

  <Step title="Build the extension">
    ```bash theme={null}
    pnpm run build
    ```

    This creates a production build in the `dist/` directory.

    For development with hot reload:

    ```bash theme={null}
    pnpm run watch
    ```
  </Step>

  <Step title="Load in Chrome">
    1. Open Chrome and navigate to `chrome://extensions/`
    2. Enable "Developer mode" (toggle in top right)
    3. Click "Load unpacked"
    4. Select the `apps/chrome-extension/dist` directory
  </Step>
</Steps>

## Features

### Context Menu Integration

Right-click on selected text to:

* Ask Olis about the selection
* Search with Olis
* Add to knowledge base
* Summarize content

```typescript theme={null}
// Example: Register context menu
chrome.contextMenus.create({
  id: "ask-olis",
  title: "Ask Olis: \"%s\"",
  contexts: ["selection"]
})
```

### Page Content Extraction

Automatically extract relevant content from web pages:

* Article text
* Page metadata
* Links and references
* Code snippets

### Quick Access Popup

<CardGroup cols={2}>
  <Card title="Search" icon="magnifying-glass">
    Quick search interface accessible via browser action
  </Card>

  <Card title="Chat" icon="message">
    Mini chat window for quick questions
  </Card>

  <Card title="History" icon="clock">
    Recent queries and results
  </Card>

  <Card title="Settings" icon="gear">
    Extension configuration
  </Card>
</CardGroup>

## Manifest Configuration

```json theme={null}
{
  "manifest_version": 3,
  "name": "Olis",
  "version": "0.1.0",
  "description": "Your AI assistant in the browser",

  "permissions": [
    "activeTab",
    "contextMenus",
    "storage"
  ],

  "host_permissions": [
    "http://localhost:8000/*"
  ],

  "background": {
    "service_worker": "background.js"
  },

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "css": ["content.css"]
    }
  ],

  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icons/icon16.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    }
  }
}
```

## Communication Architecture

```mermaid theme={null}
graph LR
    Content[Content Script] -->|Message| Background[Service Worker]
    Background -->|API Call| Server[API Server]
    Server -->|Response| Background
    Background -->|Message| Content
    Popup[Popup UI] -->|Message| Background
    Background -->|State| Popup
```

### Message Passing

```typescript theme={null}
// From content script to background
chrome.runtime.sendMessage({
  type: 'ASK_OLIS',
  payload: { query: 'What is this page about?' }
}, (response) => {
  console.log('Response:', response)
})

// In background service worker
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'ASK_OLIS') {
    handleQuery(message.payload).then(sendResponse)
    return true // Async response
  }
})
```

## Storage Management

Use Chrome's storage API for persistence:

```typescript theme={null}
// Save data
chrome.storage.local.set({ apiKey: 'your-key' })

// Retrieve data
chrome.storage.local.get(['apiKey'], (result) => {
  console.log('API Key:', result.apiKey)
})

// Sync across devices
chrome.storage.sync.set({ preferences: {...} })
```

## Building for Production

<Steps>
  <Step title="Build the extension">
    ```bash theme={null}
    pnpm run build
    ```
  </Step>

  <Step title="Test the build">
    1. Load the extension from `dist/` directory
    2. Test all features thoroughly
    3. Check console for errors
    4. Verify on different websites
  </Step>

  <Step title="Create a package">
    ```bash theme={null}
    cd dist
    zip -r olis-extension.zip .
    ```

    Or use a packaging script:

    ```bash theme={null}
    pnpm run package
    ```
  </Step>

  <Step title="Prepare for submission">
    * Create promotional images (1280x800, 640x400)
    * Write detailed description
    * Prepare privacy policy
    * Create demo video (optional)
  </Step>
</Steps>

## Publishing to Chrome Web Store

<Steps>
  <Step title="Register as a developer">
    Visit [Chrome Web Store Developer Dashboard](https://chrome.google.com/webstore/devconsole) and pay the \$5 registration fee.
  </Step>

  <Step title="Upload your extension">
    1. Click "New Item"
    2. Upload the ZIP file
    3. Fill in store listing details
    4. Add screenshots and promotional images
  </Step>

  <Step title="Submit for review">
    Review can take a few days to a week. You'll be notified via email.
  </Step>
</Steps>

## Best Practices

<CardGroup cols={2}>
  <Card title="Performance" icon="gauge">
    * Minimize content script impact
    * Use event-driven architecture
    * Lazy load resources
    * Cache API responses
  </Card>

  <Card title="Security" icon="shield">
    * Validate all input
    * Use HTTPS for API calls
    * Follow CSP guidelines
    * Handle sensitive data carefully
  </Card>

  <Card title="UX" icon="sparkles">
    * Fast, responsive UI
    * Clear error messages
    * Intuitive interactions
    * Keyboard shortcuts
  </Card>

  <Card title="Compatibility" icon="check">
    * Test on multiple websites
    * Handle edge cases
    * Graceful degradation
    * Cross-browser support
  </Card>
</CardGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Extension Not Loading">
    **Problem**: Extension doesn't appear in Chrome

    **Solution**:

    1. Check manifest.json for errors
    2. Verify all files referenced exist
    3. Look for errors in chrome://extensions/
    4. Reload the extension
  </Accordion>

  <Accordion title="Content Script Not Injecting">
    **Problem**: Content script doesn't run on pages

    **Solution**:

    ```json theme={null}
    // Check manifest matches
    "content_scripts": [{
      "matches": ["<all_urls>"],  // Or specific patterns
      "js": ["content.js"],
      "run_at": "document_idle"   // Timing matters
    }]
    ```
  </Accordion>

  <Accordion title="API Calls Failing">
    **Problem**: Cannot reach API server

    **Solution**:

    1. Check host\_permissions in manifest:
       ```json theme={null}
       "host_permissions": ["http://localhost:8000/*"]
       ```
    2. Verify CORS is configured on server
    3. Check network tab in DevTools
    4. Test API endpoint directly
  </Accordion>

  <Accordion title="Build Errors">
    **Problem**: Webpack build fails

    **Solution**:

    ```bash theme={null}
    # Clean and reinstall
    rm -rf node_modules dist
    pnpm install
    pnpm run build

    # Check for TypeScript errors
    pnpm run type-check
    ```
  </Accordion>
</AccordionGroup>

## Testing

### Manual Testing

<Steps>
  <Step title="Load the extension">
    Load unpacked extension from `dist/` directory
  </Step>

  <Step title="Test on various websites">
    * News articles
    * Documentation sites
    * Social media
    * Web apps
  </Step>

  <Step title="Test all features">
    * Context menu items
    * Popup functionality
    * Content extraction
    * API communication
  </Step>

  <Step title="Check console">
    Look for errors in:

    * Extension popup console
    * Background service worker console
    * Page console (for content scripts)
  </Step>
</Steps>

### Automated Testing

```typescript theme={null}
// Example: Jest test for background script
import { handleQuery } from '../background/handlers'

describe('Background handlers', () => {
  test('handleQuery returns response', async () => {
    const response = await handleQuery({ query: 'test' })
    expect(response).toHaveProperty('answer')
  })
})
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Desktop Client" icon="desktop" href="/apps/electron-client">
    Explore the desktop application
  </Card>

  <Card title="API Server" icon="server" href="/apps/api-server">
    Learn about the backend API
  </Card>
</CardGroup>
