Skip to content

simandebvu/synapse

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

56 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Synapse · Chrome AI Accessibility Workspace

Synapse is a Vite + React + TypeScript application that turns complex content into accessible experiences using Chrome's built-in AI APIs. The application provides interactive demos and practical implementations of Chrome's Rewriter, Translator, and Prompt APIs with robust error handling, streaming support, and production-ready service wrappers.

Prerequisites

  • Node.js 18+ (LTS recommended) and npm 9+
  • Chrome Canary/Dev 130+ with the Chrome Built-in AI origin trial enabled
  • Valid Origin Trial token configured in .env (VITE_CHROME_AI_ORIGIN_TRIAL_TOKEN)
  • chrome://flags/#optimization-guide-on-device-model set to Enabled

Setup

  1. Install dependencies
    npm install
  2. Create environment file
    cp .env.example .env
  3. Configure Chrome AI origin trial
    • Request a token from Chrome Origin Trials
    • Paste the token into .env under VITE_CHROME_AI_ORIGIN_TRIAL_TOKEN
  4. Run the dev server
    npm run dev
  5. Open in Chrome Canary/Dev at the printed URL (default http://localhost:5173). Ensure the origin trial flag remains enabled and the token is valid for the local domain.

User Documentation

Features

Chrome AI API Integrations

  • Rewriter API: Text simplification with reading level control, tone adjustment (formal/casual), length modification, and streaming support
  • Translator API: Multi-language translation (20+ languages) with automatic language detection and format preservation
  • Prompt API: Conversational AI with temperature control, system prompts, and streaming responses
  • Writing Tools: Comprehensive writing assistance powered by Prompt and Rewriter APIs:
    • Proofread: Grammar, spelling, and punctuation correction with detailed change tracking
    • Tone Adjustment: Transform text tone (professional, casual, friendly, confident)
    • Summarize: Create concise summaries of long-form content
    • Expand: Elaborate and add detail to brief text
    • Key Points: Extract 3-7 main ideas with importance classification
    • Suggestions: Get actionable writing improvement recommendations
  • Future-Ready API Detection: Graceful detection for upcoming Writer API (Chrome 137+) and Proofreader API (Chrome 137+)
  • Service Layer: Production-ready wrappers with error handling, retry logic, content validation, and sanitization

UI Components

  • Text Input Panel: Smart textarea with character counting, validation, paste handling, keyboard shortcuts (⌘↵ to submit, ⌘K to clear), and example content loader
  • File Upload System: Drag-and-drop file upload with support for TXT, PDF, and DOCX formats
    • Automatic text extraction with progress indicators
    • File content validation (magic number verification)

Accessibility

  • Skip navigation link and consistent page landmarks keep keyboard users oriented.
  • Global focus indicators respect system high-contrast preferences while remaining visible in all themes.
  • Theme toggle offers light, dark, system, and high-contrast palettes; preferences persist across sessions.
  • Menus, drawers, and pickers support full keyboard navigation, roving focus, and Escape to close.
  • File uploads, format selectors, and example loaders expose ARIA labels, status messaging, and focus management for assistive tech.
    • Duplicate file detection
    • Retry logic for failed extractions
    • Dynamic timeout scaling based on file size
  • URL Content Extraction: Extract and process article content from web pages
    • Powered by Mozilla Readability for clean article extraction
    • Removes ads, navigation, and clutter
    • Extracts article metadata (title, author, reading time)
    • Content sanitization with DOMPurify
    • CORS-aware with helpful error messages
  • Workspace Page: Interactive text processing interface with real-time status indicators and four input modes:
    • Text Input: Direct text entry with example content
    • File Upload: Process TXT, PDF, and DOCX files
    • URL Extraction: Extract article content from web pages
    • Writing Tools: Six writing assistance tools with before/after preview
  • Demos Hub: Centralized testing interface for all Chrome AI APIs with feature descriptions and browser compatibility checks
  • Status Indicators: Visual feedback for API availability, processing state, and elapsed time tracking

Developer Experience

  • Comprehensive Error Handling: Type-safe error guards for Rewriter, Translator, and Prompt APIs
  • React Hooks: useRewriter, useTranslator, usePrompt, useWritingTools, useTextInput, useFileUpload, and useContentExtraction for state management
  • Browser Compatibility: Automatic detection and user-friendly warnings for unsupported browsers
  • Capability Detection: Runtime checks for all 6 Chrome AI APIs with graceful degradation:
    • Prompt API (Gemini Nano) - Chrome 130+
    • Rewriter API - Chrome 130+
    • Translator API - Chrome 130+
    • Language Detector API - Chrome 130+
    • Writer API - Chrome 137+ (experimental, future-ready)
    • Proofreader API - Chrome 137+ (experimental, future-ready)
  • File Processing: Secure local PDF.js worker, content validation, and robust extraction pipeline

Testing Infrastructure

  • Unit Tests (Vitest): 68+ tests covering error handling, utilities, and business logic
    • Comprehensive RewriterError serialization tests (circular refs, binary data, security)
    • 100% coverage for critical error handling paths
    • Performance verified (100k properties in 18ms)
  • Component Tests (Vitest + React Testing Library): 150+ tests for UI components
    • URLInput, ExtractedContent, ComparisonView, FormatSection
    • Loading states, accessibility, user interactions
    • All UI components (LoadingSpinner, ProgressBar, Skeleton, SuccessMessage)
  • Integration Tests: 15+ tests verifying component interactions and state management
  • E2E Tests (Playwright): 50+ user journey tests
    • Smoke tests for critical app functionality
    • Workspace flows (text input, file upload, URL extraction)
    • Demos page (Rewriter, Translator journeys)
    • Preferences and settings persistence
  • Test Helpers: Reusable utilities for navigation, Chrome AI mocking, accessibility verification
  • Coverage: 70%+ code coverage with comprehensive edge case testing

Run tests:

npm test                # Unit + component tests
npm run test:ui         # Interactive test UI
npm run test:coverage   # Generate coverage report
npm run test:e2e        # E2E tests
npm run test:e2e:ui     # E2E interactive mode

Tooling & Architecture

  • Vite + React (TypeScript): Fast HMR, first-class ESM support with strict TypeScript configuration
  • Tailwind CSS: Utility-first styling with custom theme tokens for typography, color, and elevation
  • React Router v7: Root layout with workspace, demos, preferences routes, and 404 handling
  • Error handling: AppErrorBoundary, route error boundary, and global window listeners pipe through shared reportError utility
  • Local storage: Namespaced helpers (createLocalStorageNamespace) and preferencesStorage wrapper
  • Chrome AI readiness: Origin trial token support via <meta> tag with comprehensive capability detection

For diagrams and deeper explanations of each layer, read docs/architecture.md.

Project Structure

src/
  components/
    common/        # Shared UI primitives (Logo, BrowserCompatibilityBanner)
    errors/        # React error boundary implementation
    input/         # Text input & file upload components
                   # TextInputPanel, CharacterCounter, FileUploadDropzone,
                   # FileList, FileExtractionProgress, etc.
    layout/        # Header, footer, and layout shell
    ui/            # Reusable UI components (ProgressBar, LoadingSpinner, etc.)
  config/          # Navigation and global settings
  constants/       # Example content and shared constants
  hooks/           # React hooks (useRewriter, useTranslator, usePrompt,
                   # useWritingTools, useTextInput, useFileUpload, useContentExtraction)
  lib/
    chrome-ai/     # Chrome AI service wrappers and utilities
      errors/      # Type-safe error definitions and guards
      services/    # RewriterService, TranslatorService, PromptService, WritingToolsService
      utils/       # Content chunking, validation, sanitization, retry logic
      capabilities.ts  # Runtime API detection for all 6 Chrome AI APIs
    errors/        # Reporting + global handlers
    storage/       # Local storage namespace utilities
    utils/         # File processing (extraction, validation) and text utilities
  pages/           # Route-level surfaces (home, workspace, demos, preferences, 404)
  routes/          # Router + error boundary composition

Demo Pages

Access interactive demos at /demos:

  • Rewriter API Demo (/demos/rewriter): Test text simplification with various options
  • Translator API Demo (/demos/translator): Translate between 20+ languages with streaming
  • Prompt API Demo (/demos/prompt): Conversational AI with advanced configuration

Each demo includes:

  • Real-time API status indicators
  • Streaming response visualization
  • Error handling demonstrations
  • Browser compatibility checks
  • Comprehensive diagnostics

Developer Workflow

Use the npm scripts below while iterating. Build and lint commands should pass before you open a pull request.

  • npm run dev – Start Vite dev server.
  • npm run build – Type-check and build for production.
  • npm run preview – Preview the production build locally.
  • npm run lint – Run ESLint on the project.

API Usage Examples

Rewriter Service

import { RewriterService } from '@/lib/chrome-ai/services'

const rewriter = new RewriterService()
await rewriter.initialize()

// Simplify text to a specific reading level with contextual prompts
const simplified = await rewriter.simplify(text, {
  readingLevel: 'high-school',
  context: 'Audience: product managers evaluating a new launch.',
  technicalTerms: ['OAuth 2.0', 'API gateway'],
  onProgress: (current, total) => console.log(`Processed chunk ${current}/${total}`)
})

// Generate progressive simplifications (adult → high-school → middle-school → elementary)
const stages = await rewriter.simplifyProgressively(text, {
  context: 'Highlight accessibility benefits for executive decision makers.',
  technicalTerms: ['LLM', 'zero-shot classification'],
  onStageComplete: ({ readingLevel }) => console.log(`Completed ${readingLevel} pass`)
})

console.log(stages.map((stage) => stage.readingLevel))

Translator Service

import { TranslatorService } from '@/lib/chrome-ai/services'

const translator = new TranslatorService()
await translator.initialize('en', 'es')

// Translate with streaming
for await (const chunk of translator.translateStream(text)) {
  console.log(chunk) // Partial translation
}

Prompt Service

import { PromptService } from '@/lib/chrome-ai/services'

const prompt = new PromptService({
  temperature: 0.7,
  topK: 40
})
await prompt.initialize()

// Conversational AI with system prompt
const response = await prompt.prompt({
  userMessage: 'Explain quantum computing',
  systemPrompt: 'You are a helpful science tutor'
})

Writing Tools Service

import { WritingToolsService } from '@/lib/chrome-ai/services'

const service = new WritingToolsService({
  enableRetry: true,
  enableValidation: true
})
await service.initialize()

// Proofread: Fix grammar, spelling, and punctuation
const proofreadResult = await service.proofread('Their are many erors here.')
console.log(proofreadResult.corrected) // "There are many errors here."
console.log(proofreadResult.statistics) // { errorsFound: 2, wordsChanged: 2, ... }

// Adjust Tone: Transform text to match audience
const adjusted = await service.adjustTone(
  'Send me that report now!',
  'professional'
)
console.log(adjusted.adjusted) // "I would appreciate receiving the report at your earliest convenience."

// Summarize: Create concise summaries
const summary = await service.summarize(longArticle)

// Expand: Add detail and elaboration
const expanded = await service.expand('AI is changing the world.')
console.log(expanded.expanded) // Detailed, elaborated version

// Extract Key Points: Identify main ideas (NEW!)
const keyPoints = await service.extractKeyPoints(longArticle)
keyPoints.forEach(kp => {
  console.log(`[${kp.importance}] ${kp.point}`)
})
// Output:
// [primary] Rising global temperatures causing ice cap melting
// [secondary] Renewable energy offers sustainable solution

// Get Writing Suggestions: Actionable feedback (NEW!)
const suggestions = await service.getWritingSuggestions(draftText)
suggestions.forEach(s => {
  console.log(`[${s.category} - ${s.priority}]`)
  console.log(`Issue: ${s.issue}`)
  console.log(`Suggestion: ${s.suggestion}`)
})

service.destroy()

Writing Tools Hook

import { useWritingTools } from '@/hooks/useWritingTools'

const writingTools = useWritingTools(true) // auto-initialize

// Select a tool
writingTools.selectTool('key-points')

// Process text
await writingTools.process(articleText)

// Access results
if (Array.isArray(writingTools.result)) {
  writingTools.result.forEach(kp => {
    console.log(kp.point) // KeyPoint objects
  })
}

File Upload Hook

import { useFileUpload } from '@/hooks/useFileUpload'

const fileUpload = useFileUpload({
  onExtractionComplete: (text, file) => {
    console.log(`Extracted ${text.length} characters from ${file.file.name}`)
  },
  onExtractionError: (error, file) => {
    console.error(`Failed to extract text from ${file.file.name}:`, error)
  }
})

// Add files (supports TXT, PDF, DOCX)
fileUpload.addFiles(files)

// Process all pending files (with automatic retry)
await fileUpload.processFiles()

// Get all extracted text
const allText = fileUpload.getAllExtractedText()

Content Extraction Hook

import { useContentExtraction } from '@/hooks/useContentExtraction'

const { extract, content, error, isLoading, clear } = useContentExtraction()

// Extract content from a URL
await extract('https://example.com/article')

// Access extracted content
if (content) {
  console.log('Title:', content.title)
  console.log('Author:', content.byline)
  console.log('Content:', content.textContent)
  console.log('Reading time:', content.readingTime)
}

// Clear extracted content
clear()

Chrome AI API Detection

Synapse includes intelligent capability detection for all Chrome AI APIs with graceful degradation:

import {
  detectChromeAiCapabilities,
  detectChromeAiAvailabilityStatus
} from '@/lib/chrome-ai/capabilities'

// Quick synchronous check for API presence
const capabilities = detectChromeAiCapabilities()
console.log(capabilities)
// {
//   available: true,
//   prompt: true,
//   rewriter: true,
//   translator: true,
//   languageDetector: true,
//   writer: false,      // Chrome 137+ required
//   proofreader: false  // Chrome 137+ required
// }

// Detailed async check for API readiness
const status = await detectChromeAiAvailabilityStatus()
console.log(status)
// {
//   prompt: 'available',      // Ready to use
//   rewriter: 'available',    // Ready to use
//   translator: 'downloadable', // Model needs download
//   languageDetector: 'available',
//   writer: 'unavailable',    // Not supported yet
//   proofreader: 'unavailable' // Not supported yet
// }

Future-Ready Design

The system is designed to gracefully adopt new APIs as they become available:

  • Current (Chrome 130-136): Writing tools use Prompt + Rewriter APIs
  • Future (Chrome 137+): System will automatically detect Writer and Proofreader APIs
  • No Breaking Changes: Existing implementations continue to work
  • Progressive Enhancement: New APIs can be adopted without refactoring

Browser Requirements

  • Chrome 130+ (Chrome Canary or Dev channel recommended)
  • Chrome AI flags enabled: Navigate to chrome://flags and enable:
    • #optimization-guide-on-device-model → "Enabled BypassPerfRequirement"
    • #prompt-api-for-gemini-nano → "Enabled"
    • #translation-api → "Enabled"
    • #rewriter-api → "Enabled"
  • AI model downloaded: ~2GB download occurs automatically on first use via chrome://components
  • Optional (Chrome 137+): For experimental Writer/Proofreader APIs:
    • #writer-api → "Enabled"

For detailed setup instructions and troubleshooting, visit /setup/origin-trial after starting the application.

File Upload Configuration

Security Features

  • Local PDF.js Worker: Worker runs locally (no CDN) to prevent MITM attacks
  • Content Validation: Magic number verification for all file types
    • PDF: Validates %PDF- header
    • DOCX: Validates ZIP signature
    • TXT: Validates UTF-8 encoding
  • File Size Limits: 10MB maximum per file
  • Duplicate Detection: Prevents uploading the same file twice

Configuration Options

Set VITE_PDFJS_WORKER_URL in .env to customize the PDF.js worker location:

# Use local worker (default, most secure)
VITE_PDFJS_WORKER_URL=

# Or use custom CDN
VITE_PDFJS_WORKER_URL=https://your-cdn.com/pdf.worker.min.mjs

Supported File Formats

  • TXT (.txt) - Plain text files up to 10MB
  • PDF (.pdf) - PDF documents with text extraction
  • DOCX (.docx) - Microsoft Word documents

Performance

  • Dynamic Timeouts: Scales with file size (5s base + 2s per MB)
  • Retry Logic: Automatic retry (up to 2 times) for transient failures
  • Progress Tracking: Real-time progress indicators for large files

URL Extraction Notes

The URL extraction feature uses Mozilla Readability to extract clean article content from web pages. Note:

  • CORS Limitations: Some websites block cross-origin requests. For development, you can:
    • Use a CORS proxy service
    • Install a browser extension that enables CORS
    • Run Chrome with --disable-web-security flag (development only)
  • Supported Sites: Works best with article-based content (blogs, news sites, documentation)
  • Content Sanitization: All extracted HTML is sanitized with DOMPurify to prevent XSS attacks

Privacy & Data Handling

Synapse is designed with privacy-first principles:

Client-Side Only Processing

  • All text processing happens locally using Chrome's built-in AI APIs
  • No data is sent to external servers (we don't have any!)
  • Chrome AI models (Gemini Nano) run entirely on your device
  • Your content never leaves your browser

Data Storage

  • Only localStorage is used for storing preferences
  • No cookies, no analytics, no tracking
  • All stored data is prefixed with synapse for easy identification
  • You can export or delete your data at any time via the Data & Privacy page (/data)

What Data is Stored Locally

  • User Preferences: Format selections, language choices, reading level, theme settings
  • Favorite Languages: Language pairs marked for quick access
  • Privacy Settings: Record of privacy notice acknowledgment

External Requests

Synapse makes external requests only in these scenarios:

  1. URL Content Extraction (Optional Feature)

    • When you explicitly provide a URL to extract content
    • Your browser makes a direct request to that website
    • The target site sees your IP address
    • No intermediary servers involved
    • Privacy disclosure shown before extraction
  2. PDF Standard Fonts (Optional, Disabled by Default)

    • When enabled, standard fonts load from jsDelivr CDN
    • Only triggered during PDF file processing
    • Can be disabled in Data & Privacy settings
    • Default: Disabled for privacy

Your Privacy Rights

  • Export Your Data: Download all preferences as JSON (/data)
  • Clear Your Data: Delete all stored preferences and settings
  • Review What's Stored: View detailed breakdown of stored data
  • Read Privacy Policy: Full disclosure at /privacy

Example Export Data:

{
  "version": "1.0",
  "exportDate": "2025-10-27T18:30:00.000Z",
  "data": {
    "synapse.preferences:theme": "dark",
    "synapse.preferences:reading-level": "high-school",
    "synapse.preferences:target-language": "es",
    "synapse.preferences:use-external-pdf-fonts": false,
    "synapse.translator:favorites": ["en", "es", "fr", "de"],
    "synapse.privacy:notice-accepted": "true"
  }
}

### Privacy Tools
- Navigate to **Data & Privacy** (`/data`) to manage your stored data
- All privacy controls are accessible from the footer
- Privacy banner shown on first visit with clear explanation

### GDPR & CCPA Compliance
Because Synapse doesn't collect any personal data, we exceed GDPR and CCPA requirements:
- No data to process, so no data processing agreements needed
- No data to breach, so no data breach risk
- No tracking or profiling
- Complete data sovereignty for users

### Verification
You can verify our privacy claims by:
- Inspecting the source code (fully open source)
- Monitoring network requests in browser DevTools
- Checking localStorage in DevTools Application tab
- Reviewing the privacy policy at `/privacy`

## Next Steps

- Expand Workspace page with multi-API processing pipelines
- Add Summarizer and Language Detector API integrations
- Implement Writer & Proofreader API demos
- Integrate state management (Zustand) for cross-component state
- Add visual regression testing (Percy/Chromatic)

## Additional Documentation
- [`docs/architecture.md`](docs/architecture.md) – Layer breakdown, data flow, and diagrams.
- [`docs/chrome-ai-apis.md`](docs/chrome-ai-apis.md) – Chrome AI service contracts, initialization steps, and troubleshooting.
- [`docs/adr`](docs/adr) – Architecture decision records for foundational choices.

About

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •