Modern Vue.js browser extension for AI-powered translation with comprehensive cross-platform support. Built with a modular architecture and advanced state management, it seamlessly operates across:
- Browsers: Full compatibility with Chrome and Firefox using Manifest V3.
- Platforms: Robust support for Desktop, Mobile (Android), and ChromeOS.
- Environments: Optimized for both Standard Desktop and Touch-First interfaces.
- Architecture: AI-powered core with 18+ specialized modules and robust error handling.
- Architecture - This file - Complete system overview and integration guide
- Messaging System - Race-condition-free inter-component communication with intelligent timeout management and Unified Translation Service integration
- Translation System - Unified Translation Service architecture with centralized coordination, duplicate prevention, and intelligent result routing
- Provider Implementation Guide - Complete guide for implementing translation providers with BaseProvider, RateLimitManager, and Circuit Breaker
- Markdown Rendering - Shared preview pipeline, SafeMarkdownPreview boundary, and extraction ownership
- Error Management - Centralized error handling and context safety
- Testing Strategy - Guidelines and roadmap for unit and integration testing
- Storage Manager - Unified storage API with caching and events
- Logging System - Structured logging with performance optimization
- Memory Garbage Collector - Advanced memory management system with Critical Protection for essential resources
- Proxy System - Extension-only proxy system with Strategy Pattern for accessing geo-restricted translation services
- Toast Integration System - Comprehensive Vue Sonner toast integration with actionable notifications and event-driven architecture
- Vite Build System - Modular bundling, manual chunking, and warning suppression filters
- CSS Architecture - Modern principled CSS with Grid layout, containment, safe variable functions, and future-proof SCSS patterns
- CSS Variables Guide - Comprehensive guide for using and extending CSS variables
- Component-Adjacent SCSS - Rules for managing component-specific styles
- Element Detection Service - Centralized element detection system with optimized DOM queries and caching
- Language Detection - Hierarchical language and direction detection system with provider feedback loop
- Localization - Guide for internationalization and locale management
- Stats Manager - System for tracking usage statistics and analytics
- Translation Provider Logic - Detailed waterfall logic for provider selection
- Smart Handler Registration System - Dynamic feature lifecycle management with exclusion logic
- Windows Manager Integration - Guide for the event-driven integration with the UI Host
- Text Actions System - Copy/paste/TTS functionality with Vue integration
- TTS System - Advanced Text-to-Speech with stateful Play/Pause/Resume controls
- Text Selection System - Static import system, site handler registry, professional editor support with drag detection
- Selection Coordinator - Pub/Sub model for selection events between managers (Windows, FAB, TTS)
- UI Host System - Centralized Shadow DOM UI management
- Whole Page Translation System - Recursive translation of web pages with dynamic batching
- Select Element System - System for selecting and translating DOM elements
- Screen Capture System - Interactive area capture with Tesseract.js OCR engine
- Subtitle Translation System - Standalone tool for translating
.srtsubtitle files with format preservation and progressive batching - Mouse Hover System - High-performance "zero-click" translation with word/sentence/container detection
- Options Page Documentation - Guide for configuration hub and settings application logic
- Optimization Levels - Strategy for balancing speed vs. cost in translations
- IFrame Support System - Streamlined iframe functionality with essential components and Vue integration
- Mobile Support System - Centralized Bottom Sheet architecture for mobile browsers with gesture support
- Desktop FAB System - Floating action menu for quick access to translation features on desktop
- Video Tutorials - Introduction and feature overview
- API Key Tutorial - Step-by-step API configuration
- Screenshots - Interface screenshots and architectural diagrams
- Store Assets - Chrome and Firefox store promotional materials
- New Developers: Start with Architecture → Messaging System
- Feature Development: Smart Handler Registration → Translation System
- Translation Features: Translation System → Provider Implementation Guide
- Provider Development: Provider Implementation Guide → Provider System
- UI Development: Windows Manager Integration → Text Actions
- Error Handling: Error Management → Logging System
For behavior-level guarantees, refer to the contract documents rather than inferring from this overview:
- Translation System and Architecture Diagrams — runtime flow, provider execution, conversation, identity/fragment, and terminal-state diagrams.
- Feature Contracts — per-mode (popup, sidepanel, selection, field, whole-page, PDF, subtitle, hover) mutation/timeout/revert guarantees.
- Provider Contract — result/error/retry/health/stats/circuit ownership.
- Conversation Contract — AI stage/commit/discard and recovery exclusion.
- Identity & Fragment Contract — logical identity and fragment aggregation.
- Storage Operations: Storage Manager
View System Architecture Diagram
┌─────────────────────────────────────────────────────────────────┐
│ FRONTEND LAYER │
│ Vue Apps (Popup/Sidepanel/Options) → Components → Composables │
│ Pinia Stores → State Management → Reactive Data │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ MESSAGING LAYER │
│ useMessaging → UnifiedMessaging → MessageHandler → Direct │
│ Cross-Frame Communication → Window Management │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ BACKGROUND LAYER │
│ Service Worker → Message Handlers → Translation Engine │
│ Feature Loader → System Managers → Cross-Browser Support │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ CORE SYSTEMS │
│ Translation engine: Feature → UnifiedTranslationService → UnifiedModeCoordinator → TranslationEngine → ProviderCoordinator → QueueManager → Provider → ProviderRequestEngine → validation → UnifiedResultDispatcher → feature consumer │
│ Provider infra: RateLimitManager (provider health + circuit) and ApiKeyManager (key failover) wrap ProviderRequestEngine; BaseAIProvider owns structured AI recovery. No automatic cross-provider fallback. │
│ For full routing, identity/fragment, conversation, and terminal-state diagrams, see architecture/DIAGRAMS.md │
│ Storage Manager → Error Handler → Logger System → Unified TTS System → Windows Manager → Memory Garbage Collector → Toast Integration System │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ CONTENT LAYER │
│ Content Scripts → Smart Feature Management → UI Host System │
│ Feature-Based Registration → Dynamic Handler Lifecycle │
│ Principled Text Selection → Element Selection → Text Field Icons → Context Integration → Toast Notifications │
└─────────────────────────────────────────────────────────────────┘
View detailed project structure
src/
├── apps/ # Vue Applications (Entry Points)
│ ├── popup/ # PopupApp.vue + components
│ │ ├── PopupApp.vue # Main popup application
│ │ └── components/ # Popup-specific components
│ ├── sidepanel/ # SidepanelApp.vue + components
│ │ ├── SidepanelApp.vue # Main sidepanel application
│ │ ├── SidepanelLayout.vue # Layout wrapper
│ │ └── components/ # Sidepanel components
│ ├── options/ # OptionsApp.vue + tabs
│ │ ├── OptionsApp.vue # Main options application
│ │ ├── OptionsLayout.vue # Layout wrapper
│ │ ├── OptionsSidebar.vue # Options sidebar
│ │ ├── About.vue # About page
│ │ ├── components/ # Options components
│ │ └── tabs/ # Configuration tabs
│ └── content/ # ContentApp.vue (UI Host)
│ └── components/ # Content UI components
│ ├── pdf/ # PdfApp.vue - Standalone PDF translation UI
│ │ └── PdfApp.vue
│ └── subtitle/ # SubtitleApp.vue - Standalone subtitle (.srt) translation UI
│ └── SubtitleApp.vue
│
├── app/ # Per-app bundle/entry layer (Vite entry points)
│ ├── main.js
│ └── main/ # popup.js, sidepanel.js, options.js, pdf.js, subtitle.js
│
├── components/ # Vue Components (Preserved Structure)
│ ├── base/ # Base UI components
│ ├── shared/ # Shared components
│ │ ├── LanguageSelector.vue # Language selection
│ │ ├── ProviderSelector.vue # Provider selection
│ │ ├── TranslationDisplay.vue # Translation display
│ │ ├── TranslationInputField.vue # Input field
│ │ ├── UnifiedTranslationInput.vue # Unified input
│ │ └── TTSButton.vue # TTS controls
│ ├── feature/ # Feature-specific components
│ │ └── api-settings/ # API configuration
│ ├── layout/ # Layout components
│ ├── popup/ # Popup components
│ └── content/ # Content script components
│
├── composables/ # Vue Composables (Reorganized)
│ ├── core/ # useExtensionAPI, useBrowserAPI
│ │ ├── useDirectMessage.js # Direct messaging
│ │ └── useExtensionAPI.js # Extension API wrapper
│ ├── ui/ # UI composables
│ │ └── useUI.js # UI state management
│ └── shared/ # Other shared composables
│ ├── useClipboard.js # Clipboard operations
│ ├── useErrorHandler.js # Error handling
│ ├── useI18n.js # Internationalization
│ ├── useLanguages.js # Language management
│ └── useUnifiedI18n.js # Unified i18n
│
├── features/ # Feature-Based Organization
│ ├── translation/
│ │ ├── core/ # TranslationEngine, ProviderFactory, StreamingManager
│ │ │ └── translation-engine.js # Translation coordination
│ │ ├── ir/ # Translation Pipeline Foundation (request manifest, execution router, outcome contracts)
│ │ ├── handlers/ # handleTranslate.js, handleTranslationResult.js
│ │ ├── stores/ # translation.js store
│ │ ├── composables/ # useTranslation, useTranslationModes
│ │ ├── providers/ # Provider system (see below)
│ │ │ ├── ProviderFactory.js # Provider factory
│ │ │ ├── ProviderRegistry.js # Provider registration
│ │ │ ├── BaseProvider.js # Base provider class
│ │ │ └── implementations/ # Google, OpenAI, DeepSeek, etc.
│ │ ├── services/ # Unified Translation Service integration
│ │ └── utils/ # Translation utilities
│ ├── tts/ # UNIFIED TTS SYSTEM
│ │ ├── handlers/ # TTS background handlers
│ │ ├── composables/ # useTTSSmart.js - SINGLE SOURCE OF TRUTH
│ │ └── core/ # TTSGlobalManager - exclusive playback coordination
│ ├── screen-capture/
│ │ ├── handlers/ # Background capture handlers
│ │ ├── stores/ # ocrStore.js
│ │ ├── composables/ # useScreenCapture
│ │ ├── managers/ # Capture managers
│ │ └── utils/ # Image processing
│ ├── element-selection/
│ │ ├── managers/ # SelectElementManager
│ │ ├── handlers/ # SelectElementHandler
│ │ └── utils/ # Selection utilities
│ ├── text-selection/
│ │ └── handlers/ # TextSelectionHandler
│ ├── text-field-interaction/
│ │ ├── managers/ # TextFieldIconManager
│ │ └── handlers/ # TextFieldIconHandler
│ ├── mouse-hover/
│ │ ├── HoverTranslationManager.js # Central orchestrator
│ │ ├── HoverTextDetector.js # Intelligence engine
│ │ └── components/ # Hover-specific components
│ ├── shortcuts/
│ │ └── handlers/ # ShortcutHandler
│ ├── exclusion/
│ │ ├── core/ # ExclusionChecker
│ │ └── composables/ # useExclusionChecker
│ ├── text-actions/
│ │ ├── composables/ # useCopyAction, usePasteAction
│ │ └── components/ # ActionToolbar, CopyButton
│ ├── windows/
│ │ ├── managers/ # WindowsManager (business logic)
│ │ ├── handlers/ # WindowsManagerHandler
│ │ ├── components/ # TranslationWindow
│ │ ├── composables/ # useWindowsManager
│ │ └── managers/ # Position, animation, theme managers
│ ├── iframe-support/
│ │ ├── managers/ # IFrameManager (core functionality)
│ │ ├── composables/ # useIFrameSupport, useIFrameDetection (simplified)
│ │ └── README.md # Streamlined documentation
│ ├── notifications/ # Toast Integration System
│ │ ├── NotificationSystem.js # Main notification manager
│ │ ├── handlers/ # Event handlers
│ │ ├── types/ # Notification types
│ │ └── index.js # Notification exports
│ ├── history/
│ │ ├── stores/ # history.js store
│ │ ├── composables/ # useHistory
│ │ ├── components/ # History components
│ │ └── storage/ # History storage logic
│ └── settings/
│ ├── stores/ # settings.js store
│ ├── composables/ # Settings composables
│ └── storage/ # Settings storage
│
├── shared/ # Shared Systems (Moved from top-level)
│ ├── messaging/ # Unified Messaging system
│ │ ├── core/ # MessagingCore, UnifiedMessaging, MessageHandler
│ │ ├── composables/ # useMessaging
│ │ └── toast/ # Toast Integration System
│ │ ├── ToastIntegration.js # Main toast controller
│ │ ├── ToastEventHandler.js # Event interception
│ │ ├── ToastElementDetector.js # Element detection
│ │ ├── constants.js # Toast configuration
│ │ └── index.js # Toast exports
│ ├── storage/ # Storage management
│ │ ├── core/ # StorageCore, SecureStorage
│ │ └── composables/ # useStorage, useStorageItem
│ ├── error-management/ # Error handling
│ │ ├── ErrorHandler.js # Main error handler
│ │ ├── ErrorMatcher.js # Error matching
│ │ └── ErrorMessages.js # Error messages
│ ├── logging/ # Logging system
│ │ ├── logger.js # Main logger
│ │ └── logConstants.js # Log constants
│ ├── services/ # Shared Services
│ │ ├── ElementDetectionConfig.js # Centralized selector configuration
│ │ └── ElementDetectionService.js # Optimized element detection with caching
│ └── config/ # Configuration
│ └── config.js # Application config
│
├── core/ # Core Infrastructure
│ ├── background/ # Service worker & lifecycle
│ │ ├── index.js # Background entry point
│ │ ├── feature-loader.js # Feature loading
│ │ ├── handlers/ # Background message handlers
│ │ └── listeners/ # Event listeners
│ ├── content-scripts/ # Content script entry (Smart Loading)
│ │ ├── index-main.js # Main content script
│ │ ├── index-iframe.js # IFrame content script
│ │ ├── ContentScriptCore.js # Core loading logic
│ │ └── chunks/ # Lazy-loaded feature chunks
│ ├── services/ # Core Services
│ │ └── translation/ # Unified Translation Service
│ │ ├── UnifiedTranslationService.js # Central translation coordinator
│ │ ├── UnifiedModeCoordinator.js # Unified Mode selection coordination
│ │ ├── UnifiedResultDispatcher.js # Intelligent result routing
│ │ └── TranslationRequestTracker.js # Request lifecycle management
│ ├── memory/ # Memory Garbage Collector System with Critical Protection
│ │ ├── MemoryManager.js # Core memory management with critical resource support
│ │ ├── ResourceTracker.js # Resource tracking mixin with critical protection
│ │ ├── SmartCache.js # TTL-based caching
│ │ ├── GlobalCleanup.js # Lifecycle cleanup hooks
│ │ ├── MemoryMonitor.js # Memory usage monitoring
│ │ └── index.js # Module exports
│ ├── managers/ # Core managers
│ │ ├── core/ # LifecycleManager
│ │ ├── content/ # FeatureManager, TextSelectionManager
│ │ ├── browser-specific/ # Browser-specific managers
│ │ └── context-menu.js # Context menu management
│ ├── helpers.js # Core helper functions
│ ├── validation.js # Data validation
│ ├── extensionContext.js # Extension context management
│ └── tabPermissions.js # Tab permissions
│
├── utils/ # Pure Utilities (Simplified)
│ ├── browser/ # Browser compatibility
│ ├── dom/ # DOM utilities
│ ├── text/ # Text processing utilities
│ ├── ui/ # UI utilities
│ ├── i18n/ # Internationalization utils
│ ├── rendering/ # Rendering utilities
│ └── UtilsFactory.js # Lazy loading utility factory
│
└── assets/ # Static assets
├── icons/ # Application icons
├── fonts/ # Extension fonts
└── styles/ # Global styles
├── global.scss # Global styles
├── variables.scss # CSS variables
└── _api-settings-common.scss # API settings styles
View Content Script Architecture details
The content script implements an intelligent, interaction-based loading system that dramatically reduces memory usage and improves page load performance.
Loading Strategy:
Content Script Entry (index-main.js)
↓ (Ultra-minimal footprint - ~5KB)
ContentScriptCore (Dynamic Import)
↓ (Smart categorization via MainFeatureLoader)
Feature Categories:
├── CRITICAL: [messaging, extensionContext] - Load immediately
├── ESSENTIAL: [contentMessageHandler] - Load after 400ms
├── LAZY_UI: [vue, textSelection, mouseHover] - Load after 2.5s or on demand
├── INTERACTIVE: [windowsManager, selectElement, pageTranslation, screenCapture] - Load on user interaction
└── ON_DEMAND: [shortcut, textFieldIcon] - Load after 4s or on demand
Smart Loading Features:
- Feature Categorization: Features grouped by priority and loading strategy
- Interaction Detection: Monitors user actions via
InteractionCoordinatorto trigger preloading - Dynamic Imports: Code splitting with lazy-loaded chunks via
lazy-features.js - Memory Optimization: Significant memory reduction through selective loading
- Idle Deadline Loading: Uses
requestIdleCallbackfor lower priority categories (LAZY_UI,ON_DEMAND) - Delay Ownership:
startIntelligentLoading()owns all stage delays exactly once;loadFeature()only delegates, dedupes, and logs
Key Components:
- index-main.js: Ultra-minimal entry point with initial architecture loading
- ContentScriptCore.js: Core instance managing base infrastructure
- MainFeatureLoader.js: The brain coordinating prioritized loading stages
- InteractionCoordinator.js: Gatekeeper monitoring user events for interactive triggers
- lazy-features.js: Actual dynamic import executor and feature registry
Loading Flow:
- Critical Phase: Load core infrastructure (Messaging, Context) immediately
- Essential Phase: Load core communication handlers after 400ms
- Lazy UI Phase: Load Vue and selection detection after 2.5s (uses Idle Deadline)
- Interactive Phase: Load heavy features (Windows, Selection, Screen Capture) on user interaction
- On-Demand Phase: Load optional features (Shortcuts, Icons) after 4s (uses Idle Deadline)
View Performance Optimization details
The project has undergone significant performance improvements through advanced optimization techniques:
Memory Optimization:
- Memory Reduction: 20-30% improvement through intelligent lazy loading
- Smart Loading: Features load only when needed
- Garbage Collection: Advanced memory management with Critical Protection
- Resource Tracking: Automatic cleanup and memory management
Loading Performance:
- Feature Loading: Categorized loading with delays
- Interaction Detection: Preload based on user actions
- Dynamic Imports: On-demand module loading
Architecture Benefits:
- Lazy Loading: Features, languages, and utilities load on demand
- Event-Driven: Decoupled architecture with efficient messaging
- Caching: Intelligent caching strategies at multiple levels
- Cleanup: Automatic resource cleanup and memory management
- Advanced Code Splitting: Sophisticated bundle splitting with lazy loading
- Smart Loading System: Interaction-based feature loading
- Memory Management: Garbage collection with Critical Protection
- Caching Strategies: Multi-level caching for optimal performance
- Resource Optimization: Efficient resource usage and cleanup
View Shared Systems Architecture details
Toast Integration System
The toast integration system provides an event-driven architecture for managing actionable notifications. It uses a controller-based approach to handle toast display, event interception, and smart element detection to prevent interference with other extension features.
The system is built on four primary components:
- ToastIntegration: Central controller for all notification operations.
- ToastEventHandler: Manages interaction interceptions and callback execution.
- ToastElementDetector: Handles smart exclusion and detection of toast elements.
- Constants: Centralized configuration for selectors and behavior.
For detailed technical specifications, implementation examples, and event flow diagrams, refer to the Toast Integration System Documentation.
Messaging System
The extension uses a unified messaging architecture that ensures reliable, race-condition-free communication between background scripts, content scripts, and Vue-based UI components.
- Intelligent Timeout Management: Operations are assigned specific timeouts based on their complexity (e.g., settings operations have shorter timeouts than AI-powered translations).
- Context Isolation: Messages are filtered by context (Popup, Sidepanel, Options, Content) to prevent cross-component interference.
- Action-Based Routing: A centralized handler system routes requests based on standardized actions defined in the system core.
- Streaming Coordination: Large data operations, such as element-by-element translations, use a specialized coordination layer for progressive updates.
- UnifiedMessaging: The primary engine for sending messages with built-in error handling and timeout logic.
- MessageHandler: A robust listener system for registering and executing action-specific logic.
- useMessaging: A Vue composable that provides a reactive interface for component-level communication.
For implementation guides, code examples, and the complete list of message actions, refer to the Messaging System Documentation.
View Translation Service details
The Unified Translation Service is the central nerve center for all translation operations. It decouples the translation request from the source context (Popup, Sidepanel, Content Script), providing a unified path for processing and routing results.
The system is built on three specialized services that handle different stages of the translation lifecycle:
- UnifiedTranslationService (Coordinator): The primary entry point that manages the end-to-end translation flow.
- TranslationRequestTracker (Lifecycle): Prevents duplicate requests and tracks active operations using unique
messageIdsignatures. - UnifiedResultDispatcher (Distribution): Intelligently routes results back to the correct tab or component based on the translation mode (Field, Select Element, or Standard).
Translation Pipeline Foundation: Project A introduced the Translation Pipeline Foundation, an execution foundation under src/features/translation/ir/ providing terminal execution routing, an observational validation foundation, and diagnostics preservation across execution boundaries. Runtime production and adoption of TranslationOutcome remain intentionally deferred to the future Translation Outcome Adoption initiative.
handleTranslate.js: The single background handler that initializes and delegates to the service.handleTranslationResult.js: Processes incoming results from providers and hands them back to the dispatcher.
For detailed information on implementation, message formats, and streaming logic, refer to the Translation System Guide. For the selection strategy and waterfall logic, see the Translation Provider Logic.
View Background Service details
Modern Manifest V3 service worker with dynamic feature loading:
// Background service entry point
import { LifecycleManager } from '@/managers/core/LifecycleManager.js'
import { FeatureLoader } from '@/background/feature-loader.js'
const lifecycleManager = new LifecycleManager()
const featureLoader = new FeatureLoader()
lifecycleManager.initialize()Handlers are organized by feature category for maintainability:
Translation Operations:
handleTranslate.js- Main translation processor (ALL translation requests)handleTranslateText.js- Direct text translationhandleRevertTranslation.js- Translation reversal
Vue Integration:
handleGetExtensionInfo.js- Extension metadata for Vue appshandleTestProviderConnection.js- Provider connectivity testinghandleSaveProviderConfig.js- Provider configuration storagehandleCaptureScreenArea.js- Screen capture integration
Element Selection:
handleActivateSelectElementMode.js- Element selection activationhandleSetSelectElementState.js- State managementhandleGetSelectElementState.js- State retrieval
Screen Capture:
handleStartFullScreenCapture.js- Full screen capturehandleProcessAreaCaptureImage.js- Area capture processinghandlePreviewConfirmed.js- Capture confirmation
Sidepanel & UI:
handleOpenSidePanel.js- Sidepanel openinghandleTriggerSidebarFromContent.js- Content script triggers
System Management:
handlePing.js- Health checkshandleBackgroundReloadExtension.js- Extension reloadinghandleExtensionLifecycle.js- Lifecycle management
export class FeatureLoader {
async loadTTSManager() {
const hasOffscreen = typeof browser.offscreen?.hasDocument === "function"
if (hasOffscreen) {
// Chrome: Use offscreen documents
const { OffscreenTTSManager } = await import("@/core/managers/browser-specific/tts/TTSChrome.js")
return new OffscreenTTSManager()
} else {
// Firefox: Use background page audio
const { BackgroundTTSManager } = await import("@/core/managers/browser-specific/tts/TTSFirefox.js")
return new BackgroundTTSManager()
}
}
}View Provider System details
The provider system operates through a structured pipeline that ensures consistent results regardless of the underlying translation engine:
- ProviderCoordinator: The central hub for orchestration. It handles language normalization, bilingual logic, and result cleaning.
- TranslationEngine: Manages the lifecycle of translation requests and coordinates with the provider factory.
- Provider Factory: Dynamically instantiates the appropriate provider based on the resolution logic.
- Base Classes (BaseAI / BaseTranslate): Provide common logic for AI-based (JSON mode, prompt injection) and traditional (batching, character limits) providers.
- Modular Utilities: Specialized engines for API execution, response parsing, and text processing.
The architecture includes several mission-critical features to ensure high availability:
- Multi-API Key Failover: Supports multiple keys per provider with automatic rotation and health-based promotion.
- Circuit Breaker: Automatically disables unstable providers or those with exhausted quotas for a cooling period to prevent UI lag.
- RateLimitManager: Governs request throttling and prioritization based on user interaction levels.
- Unified Response Contract: Enforces a strict data format for all providers to ensure system-wide stability and prevent runtime errors.
- Structured Response Handling:
AIResponseParserreports whether structured-response recovery is required;BaseAIProviderowns the recovery strategy. Structured recovery is one provider-local pass that is selective when invalid request units are safely mapped, otherwise uses full sequential recovery. This is distinct from Multi-API Key Failover and provider/key failover. See Translation Provider Logic for execution policy.
For a comprehensive guide on implementing new providers, capability gating, and technical specifications, see the Provider Implementation Guide. To understand how providers are selected for different features, refer to the Translation Provider Logic.
View Vue.js State Management details
The extension uses Pinia for reactive state management across all Vue applications:
Core Stores:
// Global settings store (Pinia setup store)
import { useSettingsStore } from '@/features/settings/stores/settings.js'
const settings = useSettingsStore()
await settings.loadSettings() // merge persisted settings from storage
await settings.updateSettingAndPersist('THEME', 'dark')
await settings.resetSettings() // restore canonical persisted defaultsFeature-Specific Stores:
// Translation state
import { useTranslationStore } from '@/features/translation/stores/translation.js'
const translation = useTranslationStore()
translation.setResult(translatedText)
// History management
import { useHistoryStore } from '@/features/history/stores/history.js'
const history = useHistoryStore()
await history.addEntry(originalText, translatedText)
// Provider management
import { useProvidersStore } from '@/store/modules/providers.js'
const providers = useProvidersStore()
const activeProvider = providers.getActiveProvider()The settings store is a Pinia setup store. It delegates its default values to getPersistedDefaultSettings(), which is the single authority for the persisted settings schema. Components and features never import settingsDefaults.js directly; only the settings store, InstallHandler, and migrations consume the builder.
CONFIG owns default values; getPersistedDefaultSettings() in src/shared/config/settingsDefaults.js owns persisted key membership and drives fresh install, reset, import defaults, and migration fill. The store handles load (merge persisted settings into reactive state), save (persist to browser.storage), and reset (restore canonical persisted defaults).
Vue Component → Pinia Store → Storage Manager → browser.storage
↓ ↓ ↓
Reactive UI → Computed → Event System → Cross-Tab Sync
View Cross-System Integration details
The extension utilizes a consistent set of patterns to ensure seamless communication between the UI and backend systems:
- Vue Component Integration: Components leverage dedicated composables (e.g.,
useUnifiedTranslation) to trigger backend actions while remaining decoupled from messaging logic. - System Communication Flow: Follows a strict path from Vue Component → Composable → Messaging System → Background Handler → Service Provider, with reactive updates flowing back via Pinia stores.
- Unified Error Handling: All modules integrate with the
ErrorHandlerto provide consistent user feedback and prevent "Extension context invalidated" crashes. - Reactive Storage: State management via Pinia automatically synchronizes with
StorageManager, ensuring data persistence and cross-context consistency. - Structured Logging: Scoped loggers provide granular visibility into system behavior across all extension contexts.
- Cross-Context Communication: Standardized messaging protocols facilitate secure interaction between Popups, Sidepanels, and Content Scripts.
For implementation details and code examples, refer to the following system guides:
View Vue.js Development details
- Composable-First Logic: All business logic and side effects are extracted into reusable composables (e.g.,
useMessaging,useErrorHandler) to maintain clean, declarative components. - State Persistence: Features utilize Pinia stores with automatic synchronization to browser storage via the
StorageManager. - Component Isolation: Clear separation between Base UI (stateless), Shared Feature (context-agnostic), and Page-Specific (popup/sidepanel) components.
- Event-Driven UI: In-page elements (Windows, FAB) are managed via a central
PageEventBuswithin a Shadow DOM host to ensure complete CSS and JS isolation.
- Base Components: Pure, stateless UI elements that communicate solely via props and events.
- Shared Components: Reusable feature-specific components that encapsulate common logic (e.g.,
TranslationDisplay). - Layout Components: Manage structural concerns and responsive positioning across different extension contexts.
Markdown rendering for TranslationDisplay and history previews is centralized in src/shared/utils/text/markdownPreview.js. Providers must emit Markdown or plain text only and must not own final HTML shaping.
For detailed information on UI hosting and in-page integration, refer to the following guides:
View Essential Files details
Vue Application Entry Points
src/apps/popup/PopupApp.vue- Main popup applicationsrc/apps/sidepanel/SidepanelApp.vue- Sidepanel applicationsrc/apps/options/OptionsApp.vue- Options page applicationsrc/apps/content/ContentApp.vue- In-page UI Host (Shadow DOM)src/apps/pdf/PdfApp.vue- Standalone PDF translation applicationsrc/apps/subtitle/SubtitleApp.vue- Standalone subtitle (.srt) translation application
Core System Files
src/shared/messaging/core/UnifiedMessaging.js- Core messaging with timeout managementsrc/shared/messaging/core/UnifiedTranslationCoordinator.js- Translation coordinationsrc/shared/messaging/core/MessageActions.js- Message type definitionssrc/shared/messaging/core/MessageFormat.js- Message format utilitiessrc/shared/messaging/composables/useMessaging.js- Vue messaging integrationsrc/core/background/index.js- Background service worker entrysrc/core/background/feature-loader.js- Feature loading systemsrc/core/managers/core/LifecycleManager.js- Central message router
Unified Translation Service
src/core/services/translation/UnifiedTranslationService.js- Central translation coordinatorsrc/core/services/translation/UnifiedModeCoordinator.js- Unified Mode selection coordinationsrc/core/services/translation/UnifiedResultDispatcher.js- Intelligent result routingsrc/core/services/translation/TranslationRequestTracker.js- Request lifecycle managementsrc/features/translation/handlers/handleTranslate.js- Translation request handlersrc/features/translation/handlers/handleTranslationResult.js- Translation result processor
src/features/translation/ir/RequestUnitManifest.js- Request unit manifestsrc/features/translation/ir/TerminalExecutionRouter.js- Terminal execution routingsrc/features/translation/ir/TranslationOperation.js- Execution lifecyclesrc/features/translation/ir/TranslationOutcome.js- Immutable outcome contractsrc/features/translation/ir/TranslationUnit.js- Unit disposition contract
Legacy note:
TranslationResultDispatcher.js(src/core/services/translation/) still exists in-tree but has no runtime consumer; result routing is now performed byUnifiedResultDispatcher.js(see the Unified Translation Service section above).
Provider System
src/features/translation/providers/ProviderFactory.js- Provider factory and managementsrc/features/translation/providers/BaseProvider.js- Base provider interfacesrc/features/translation/providers/- All translation provider implementations
State Management
src/features/settings/stores/settings.js- Global settings storesrc/store/modules/translation.js- Translation state managementsrc/shared/storage/core/StorageCore.js- Centralized storage system
Core Systems
src/shared/logging/logger.js- Unified logging systemsrc/core/extensionContext.js- Extension context managementsrc/shared/error-management/ErrorHandler.js- Centralized error handling
Key Composables
src/features/translation/composables/useUnifiedTranslation.js- Unified translation logic for popup and sidepanelsrc/composables/shared/useErrorHandler.js- Error handling composablesrc/features/text-actions/composables/useTextActions.js- Text action functionality
Shared Components
src/components/shared/TranslationDisplay.vue- Translation result displaysrc/components/shared/SafeMarkdownPreview.vue- Controlled markdown HTML boundary for sanitized preview outputsrc/components/shared/TranslationInputField.vue- Translation inputsrc/components/shared/actions/ActionToolbar.vue- Action toolbarsrc/components/shared/LanguageSelector.vue- Language selectionsrc/components/shared/ProviderSelector.vue- Provider selection
Background Handlers
src/features/translation/handlers/handleTranslate.js- Main translation handler (integrated with UnifiedTranslationService)src/core/background/handlers/translation/handleTranslationResult.js- Translation result processingsrc/core/background/handlers/vue-integration/- Vue-specific handlerssrc/features/tts/handlers/- Text-to-speech handlerssrc/features/element-selection/handlers/- Element selection handlers
View Smart Handler Registration details
The smart handler registration system provides dynamic feature lifecycle management by only registering handlers when they are required by user settings and site-specific exclusion rules. This prevents unnecessary resource consumption and ensures features can be toggled in real-time without a page refresh.
- InteractionCoordinator: Acts as the gatekeeper for all content script events, managing lightweight global listeners and triggering feature loading only when a valid interaction occurs.
- FeatureManager: The central orchestrator for handler lifecycles, ensuring that deactivated features clean up their DOM elements and listeners while invalidating the lazy-loading cache.
- Lazy Feature Loading: Heavy feature modules are only imported dynamically upon interaction (e.g., selection or shortcut), keeping the initial content script overhead minimal.
- Forced Utility Loading: A specialized pattern that allows critical operations, such as translation reversal via the Escape key, to load even if the parent feature is disabled.
- ExclusionChecker: A real-time validation layer that cross-references active URLs against user-defined exclusion lists to gate feature activation.
For detailed information on the interaction gatekeeper, feature-to-setting mapping, and memory-safe deactivation patterns, refer to the Smart Handler Registration System Documentation.
View Windows Manager details
The windows manager system coordinates the display and interaction of translation icons and windows. It follows a decoupled, event-driven architecture that separates business logic from UI rendering, ensuring performance and maintainability.
- Facade Architecture: The main
WindowsManageracts as a headless controller that delegates specialized tasks to sub-managers for display logic, dismissal rules, and event coordination. - Vue UI Host: All UI elements (windows, icons, tooltips) are rendered within a centralized Vue.js application hosted inside a secure Shadow DOM.
- Event-Driven Communication: Communication between the logic layer and the UI layer is strictly managed via the
PageEventBus, eliminating direct DOM manipulation. - Pin and Dock System: Supports persistent window states, including edge-snapping (docking) and dismissal protection (pinning).
- Smart In-place Updates: Existing windows are updated atomically when new selections occur, reducing UI flicker and preventing redundant DOM creation.
For a complete guide on modularization patterns, event payload structures, and the docking breakaway logic, refer to the Windows Manager Integration Guide.
View UI Host details
The UI host system is a centralized architectural component that manages all in-page user interface elements through a single Vue.js application. It operates within a secure Shadow DOM to ensure complete isolation from the host webpage's styles and scripts.
- Centralized UI Host:
ContentApp.vueserves as the root container for all in-page elements, including translation windows, icons, and notifications. - Shadow DOM Isolation: Provides a sandbox environment that prevents host page CSS from leaking into the extension UI and ensures the extension's styles do not affect the website.
- Event-Driven UI: The host remains passive, reacting to commands from headless logic managers (like WindowsManager) via the
PageEventBus. - Selection Coordinator Integration: Synchronizes selection state across different UI modules (FAB, Windows, TTS) through a Pub/Sub model.
- Unified Notification System: Integrates with the
NotificationManagerto provide consistent, actionable toast notifications across the extension.
For detailed information on communication patterns, notification types, and the CSS isolation strategy, refer to the UI Host System Documentation.
View Text Actions details
The text actions system provides a unified interface for copy, paste, and TTS (Text-to-Speech) operations throughout the extension. It utilizes reusable Vue components and stateful composables to ensure consistent behavior across different UI modules.
- Unified Interaction Layer: Centralizes all text-related actions into a single architectural pattern, reducing redundancy in individual features.
- Shared Action Components: Provides standardized UI elements such as
ActionToolbar,CopyButton, and the smartTTSButtonfor consistent user feedback. - Stateful Composables: The
useTextActionscomposable coordinates complex workflows, such as pasting text followed by an immediate translation request. - TTS Integration: Directly leverages the
useTTSSmartsystem to provide advanced playback controls and status indicators within action toolbars. - Notification Support: Automatically triggers success or error toasts for clipboard operations to provide immediate feedback.
For a complete guide on component properties, composable options, and CSS customization, refer to the Text Actions System Documentation.
View TTS System details
The TTS (Text-to-Speech) system is a unified, stateful audio architecture designed for high-quality neural voice playback. It eliminates redundant implementations by centering all audio logic around a single source of truth that coordinates playback across all extension contexts.
- Unified Composable:
useTTSSmart.jsserves as the single entry point for all UI components, managing five distinct playback states (idle, loading, playing, paused, error). - Global Coordination:
TTSGlobalManagerenforces exclusive playback, ensuring only one audio stream is active at a time across all tabs and internal windows. - Multi-Engine Dispatcher: A central router that selects between Microsoft Edge (neural) and Google TTS based on language support, user preference, and service health.
- Owner-Aware Cleanup: A specialized logic that identifies the initiator of an audio stream, allowing the system to stop audio on window closure only if that window was the owner.
- Circuit Breaker: Protects user reputation and system stability by temporarily disabling failing engines after repeated errors.
For detailed information on the multi-tiered language detection, voice mapping logic, and browser-specific implementations (Offscreen vs. Direct), refer to the TTS System Documentation.
View Whole Page Translation details
The whole page translation system handles the recursive translation of all text content within a web page. It uses a modular architecture built around the domtranslator library to provide a high-performance, fault-tolerant experience.
- PageTranslationManager: The central orchestrator that coordinates the lifecycle of page translation, delegating specialized tasks to modular sub-managers.
- PageTranslationScheduler: A dynamic batching engine that implements optimization-aware scheduling, adjusting chunk sizes and concurrency based on the active provider's performance level.
- PageTranslationBridge: Serves as the communication layer between the extension and the translation library, handling node detection and visibility data.
- Modular Filtering: Specialized engines for different scrolling patterns (Fluid vs. On-Stop) to optimize API request frequency.
- Smart Purge Strategy: A memory-safe policy that ejects distant nodes from the translation queue during long scrolls to prevent RAM exhaustion.
For a complete breakdown of the 10-part system architecture, technical flows, and advanced scheduling logic, refer to the Whole Page Translation System Documentation.
View Text Selection details
The text selection system handles the detection and processing of text selection across standard web pages and complex professional editors. It follows a simplified architecture designed for performance and reliability across different browser environments.
- Selectionchange-Only Strategy: Utilizes the native
selectionchangeevent as the single source of truth for all selection scenarios, eliminating complex drag-detection logic. - SelectionManager: Centralizes the processing of selection data, coordinate calculation, and synchronization with UI components.
- Selection Coordinator: A decoupled Pub/Sub architecture that synchronizes selection states across the TTS, FAB, and translation windows.
- Decoupled Text Field Logic: Separates standard page selection from interactive text fields (INPUT, TEXTAREA) and professional editors (Google Docs, Notion) through the
text-field-interactionmodule. - IFrame Propagation: Ensures selection events are correctly captured and bubbled from nested frames to the top-level UI.
For detailed information on site-specific handlers, the event flow diagram, and performance optimizations, refer to the Text Selection System Documentation.
View Select Element details
The select element system provides an interactive mode for translating specific DOM elements with high precision. It uses a decoupled architecture to separate selection logic from the heavy-lifting of translation orchestration and DOM re-insertion.
- SelectElementManager: The central controller for the mode's lifecycle, managing activation, deactivation, and event coordination across frames.
- DomTranslatorAdapter: The content-side orchestrator that assigns temporary UIDs to text nodes and prepares the context-enriched JSON payload for the provider.
- Optimized JSON Handler: A background service that manages "Smart Logical Block Batching" to group text nodes by block-level parents, preserving semantic context and reducing token overhead.
- Resilient Mapping: A 1:1 node UID system ensures robust result re-insertion, even when streaming results arrive asynchronously.
- Hover Original Preview: Integration with the shared
HoverPreviewManagerallows users to view original text via surgical tooltips.
For a comprehensive guide on implementation details, abbreviated protocols, and streaming logic, refer to the Select Element System Documentation.
View Subtitle Translation details
The subtitle translation system is a standalone, robust tool designed to translate .srt subtitle files into any target language. It operates independently from page-level translation features to efficiently handle large file volumes while strictly preserving formatting, timestamps, and style tags.
- Standalone UI Application: Hosted in
SubtitleApp.vue, providing a premium, glassmorphic interface with drag-and-drop file support, dynamic ETA, and a live preview viewer. - SubtitleTranslationCoordinator: The central background orchestrator that manages the entire job lifecycle, from parsing to serialization, ensuring process stability with 5-minute batch timeouts.
- Progressive Batching: Uses
SubtitleBatchPlannerto intelligently chunk subtitle cues based on the active provider's character and item limits, optimizing API payloads. - Format Protection (TextProtector): A specialized adapter (
SubtitleTextProtector) that shields HTML tags (e.g.,<i>,<b>) and structural braces from the translation engine, preventing file corruption. - Unified Provider Integration: Seamlessly delegates the actual translation requests to the
UnifiedModeCoordinator, leveraging the extension's existing provider hierarchy and rate limiting while maintaining a decoupled orchestration flow. - Validation and Integrity: The
SubtitleValidationServiceensures translation results align perfectly with the original cues before re-injecting formatting tokens.
For a comprehensive breakdown of the background orchestration, parsing adapters, protection mechanisms, and UI integration, refer to the Subtitle Translation System Documentation.
View Screen Capture details
The screen capture system enables visual text extraction from images, videos, and complex webpage layouts. It utilizes a privacy-focused architecture where all OCR (Optical Character Recognition) processing is executed locally within the browser.
- ScreenSelector: An interactive content-layer overlay that manages area selection and implements a two-frame transparency logic to ensure the selection UI is hidden during tab capture.
- Background Orchestrator: Coordinates the capture-to-recognition lifecycle, managing the transition from raw image data to extracted text.
- OCREngine: A specialized wrapper for Tesseract.js that utilizes local assets and smart core selection (WASM/SIMD) for high-performance recognition without network dependency.
- Offscreen Processing: In Chrome, heavy OCR computations are offloaded to an offscreen document to maintain background responsiveness and comply with Manifest V3 limitations.
- Offline Model Caching: Uses IndexedDB for model persistence, allowing the system to perform recognition entirely offline after initial language downloads.
For detailed information on the capture lifecycle, Tesseract.js configuration, and the two-frame transparency pattern, refer to the Screen Capture System Documentation.
View Mouse on Hover details
The mouse on hover system provides a high-performance, "zero-click" translation experience by detecting text under the cursor and showing a tooltip. It is designed to be extremely responsive while maintaining 60fps performance through intelligent caching.
- HoverTranslationManager: The central orchestrator that manages event listening, trigger conditions (hover delay, modifier keys), and coordination with the UI.
- HoverTextDetector: A specialized engine that uses browser range APIs for high-precision detection of words, sentences, or containers.
- Rectangle Cache: An optimization layer that stores the bounding box of the detected text, skipping expensive DOM lookups as long as the mouse remains within the same area.
- Shadow DOM Tooltip: Renders the translation within an isolated UI Host component (
MouseHoverTooltip.vue), using smart positioning to avoid viewport clipping. - Modifier Key Integration: Supports instant translation when pressing Ctrl/Alt/Shift while hovering over text.
For detailed information on detection scopes, performance benchmarks, and positioning logic, refer to the Mouse on Hover System Documentation.
View Language Detection details
The language detection system is a centralized architecture for identifying language codes and text direction (RTL/LTR). It follows a "Detection Inheritance" philosophy, prioritizing verified results from translation providers to ensure accuracy across the extension.
- LanguageDetectionService: The central orchestrator (Brain) that manages detection requests and maintains a session-level cache of verified results.
- Hierarchical Priority Flow: Implements a multi-layered strategy that checks for inherited metadata before falling back to deterministic script markers, statistical browser APIs, and heuristic defaults.
- Provider Feedback Loop: Verified detections from AI or traditional translation engines are ingested and shared with other modules like TTS and the UI layer.
- Unified Direction Management: Combines language-code matching with strong-character Unicode analysis (Majority Voting) to determine the correct text direction for mixed-content strings.
- Trust Filter: A context-aware validation layer that prevents false positives on short strings by cross-referencing with the user's active UI and target languages.
For a complete guide on Unicode markers, script analysis thresholds, and UI integration patterns, refer to the Language Detection System Documentation.
View Mobile Support details
The mobile support system provides a touch-optimized translation experience through a centralized bottom sheet architecture. It replaces desktop-specific UI elements with ergonomic, thumb-friendly interfaces when touch capabilities or mobile environments are detected.
- In-Page Bottom Sheet: A multi-state container (Peek, Full) hosted within the Shadow DOM UI Host to ensure isolation from website styles.
- Mobile Store: A centralized Pinia store that coordinates visibility, navigation views, and selection data across the mobile interface.
- Gesture Engine: A decoupled logic layer for high-performance touch interactions, including snapping and swipe-to-dismiss functionality.
- Viewport Awareness: Integration with the Visual Viewport API to handle layout adjustments during virtual keyboard interactions.
For detailed information on gesture implementation, multi-view navigation, and touch-first design principles, refer to the Mobile Support Guide.
View Desktop FAB details
The Desktop FAB (Floating Action Button) is an autonomous UI module that provides high-access entry points for translation features. It operates within the Shadow DOM UI Host to ensure visual consistency and isolation across all web environments.
- Autonomous Module: Functions independently of the main extension popup, ensuring core features remain accessible.
- Selection Coordinator Integration: Uses the
useFabSelectionlogic to react to global selection events and trigger translation badges. - Smart TTS Controller: Directly integrates with the unified
useTTSSmartsystem for owner-aware audio playback and status management. - Persistent State: Utilizes the StorageManager to remember its vertical position and preferred side (left/right) across browsing sessions.
- Resource Management: Employs the ResourceTracker pattern to handle event listener cleanup and memory safety.
For detailed information on the radial badge system, gesture logic, and state-aware menu behavior, refer to the Desktop FAB System Guide.
View IFrame Support details
Streamlined iframe support system that provides essential iframe functionality while maintaining compatibility with existing Vue.js, ResourceTracker, Error Management, and Smart Messaging systems. The system has been simplified to include only actively used components. See IFrame Support Documentation for complete details.
Key Features:
- Essential Frame Management: IFrameManager for frame registration and tracking
- ResourceTracker Integration: Automatic memory management and cleanup for iframe resources
- Vue Composables: Simple reactive iframe detection and positioning utilities
- Frame Registry: Robust frame registration with corruption protection
- SelectElement Support: Fixed to work properly in iframes with immediate UI deactivation
Core Components:
IFrameManager.js: Core iframe management extending ResourceTrackerFrameRegistry.js: Frame registration and mapping system (via WindowsManager)useIFrameSupport.js: Simplified Vue composables for iframe functionality
System Flow:
Content Script Detection → IFrameManager → Frame Registration
↓
ResourceTracker Cleanup → Unified Messaging Integration
↓
Vue UI Host → Event-Based Communication → SelectElement Support
Integration Benefits:
- Zero Memory Leaks: Full ResourceTracker integration
- Immediate UI Feedback: SelectElement deactivates instantly in iframes
- Clean Logging: Debug-level multi-frame context messages
- Error Handling: Centralized error management with ExtensionContextManager
- Lightweight: Only essential components, ~80% less code than original implementation
View Storage Manager details
The storage manager system provides a unified interface for browser storage with an integrated caching layer. It ensures efficient data access and reactive state synchronization across different extension contexts.
- Intelligent Caching: Reduces the frequency of expensive
browser.storageAPI calls by maintaining an in-memory cache with automatic synchronization. - Reactive Composables: Offers
useStorageanduseStorageItemhooks for Vue components, allowing them to react instantly to storage changes. - Event System: Emits internal events upon data updates, enabling cross-component synchronization without manual polling.
- Memory Safety: Integrates with the
ResourceTrackerto ensure storage listeners are correctly cleaned up when components unmount.
For detailed information on storage schemas, caching policies, and reactive usage patterns, refer to the Storage Manager Documentation.
View Error Management details
The error management system provides a centralized, context-aware framework for handling exceptions throughout the extension. It focuses on maintaining system stability and providing user-friendly feedback during failures.
- Context Safety:
ExtensionContextManagermonitors the validity of the extension's runtime context, preventing "Extension context invalidated" errors from crashing content scripts. - Error routing:
ErrorHandlerprocesses caught exceptions, categorizing them by severity and type (Network, Auth, UI, System). Retry, circuit-breaker, failover, and structured-recovery scheduling are not performed here — they are owned byQueueManager(retry),RateLimitManager(provider health + circuit),ProviderRequestEngine/ApiKeyManager(API-key failover), andBaseAIProvider(structured AI recovery). See contracts/PROVIDER_CONTRACT.md for the ownership and retry policy. - Localized Feedback: Translates technical error codes into user-friendly notifications via the integrated toast system.
For detailed information on error classification, context validation patterns, and reporting protocols, refer to the Error Management Documentation.
View AI Conversation details
AI primary translations may participate in an in-memory conversation context via the TranslationSessionManager:
- Accepted primary → stage / validate → commit (at most once).
- Structured recovery → no conversation commit (the structured recovery pass does not persist a conversation candidate).
- Timeout / cancel / failure → discard (no commit); late settlement cannot commit after terminal state.
This is transient, in-memory history only. For the authoritative stage/commit/discard semantics and recovery exclusion, see Conversation Contract.
See also Architecture Diagrams for the AI conversation lifecycle.
View Identity & Fragments details
Structured Select Element and PDF flows use explicit logical identity and fragment aggregation rather than naive keying. Runtime enforcement of identity precedence, duplicate suppression, and fragment assembly is owned by OptimizedJsonHandler (request-local, no global cache).
Identity follows the precedence uid ?? cellId ?? i ?? id ?? blockId (nullish-coalesced; 0 is valid). Full rules — including V2/V3 fragment handling and request-local dedup — live in the Identity & Fragment Contract, shown from Architecture Diagrams.
View Translation Modes
Current user-facing translation modes:
- Selection Window · Inline Selection · Select Element · Field · Popup · Sidepanel · Whole Page · PDF · Subtitle
Per-mode mutation/timeout/revert guarantees are defined in the Feature Contracts.
View Logging details
The logging system provides a structured, component-based interface for monitoring extension behavior. It is designed for high performance and environment awareness, ensuring minimal overhead in production.
- Scoped Loggers: Uses a component-based organization (UI, Messaging, Background, etc.) to allow for granular level control and filtering.
- Level Gating: Implements strict level-checking (Debug, Info, Warn, Error) to prevent unnecessary log processing in production environments.
- Lazy Evaluation: Optimizes performance by only executing complex log string building if the active log level permits.
- Single Interface: Centralizes all logging activity through the
getScopedLoggerutility to maintain consistency across the codebase.
For detailed information on log constants, level configuration, and debugging best practices, refer to the Logging System Documentation.
View Stats Manager details
The stats manager system is a centralized, high-precision framework for tracking API usage and network payload weights. It provides absolute transparency for cost monitoring and quota management, especially for AI-based translation providers.
- Dual-Metric Tracking: Separates Original Text Length from actual Network Payload Weight to provide a clear view of API overhead.
- Golden Chain Compliance: Integrates with Providers and Orchestrators to ensure every network request is explicitly recorded at the point of execution.
- Session-Based Isolation: Uses unique session IDs to isolate statistics for different operations, such as Select Element vs. Whole Page Translation.
- Unified Reporting: Centralizes the aggregation and formatting of usage summaries, providing consistent logs and debugging tables.
For detailed information on explicit reporting flows, delta extraction, and dual-metric logic, refer to the Stats Manager Documentation.
View Performance details
- Unified Messaging: Eliminated race conditions and reduced complexity by 50% using action-specific timeouts.
- Resource Management: Lazy loading of providers and components to minimize initial memory footprint.
- State Management: Efficient, reactive synchronization with Pinia and optimized storage caching.
- Context Stability: Centralized error management and context validation to prevent runtime failures.
For detailed information on multi-tiered optimizations, caching strategies, and resource lifecycle management, refer to the Optimization Levels Documentation.
View Development Guide details
- Create provider class extending
BaseProvider - Register in
ProviderFactory - Add configuration to settings store
- Test with
TranslationEnginefollowing the Testing Strategy
- Create handler in appropriate
handlers/directory - Register in
LifecycleManager - Add corresponding action to
MessageActions.js - Test with
useMessagingcomposable following the Testing Strategy
- Use browser DevTools extension debugging
- Use Vitest UI for visual debugging:
pnpm test:ui(see Testing Strategy) - Check
[Messaging]logs in console - Verify message format with
MessageFormat.validate()
View Development Workflow details
- Plan: Identify which systems are involved (Vue components, stores, background handlers, etc.)
- Design: Create composables for business logic, components for UI
- Implement: Follow the integration patterns outlined above
- Test: Verify cross-browser compatibility and follow the Testing Strategy
- Document: Update relevant documentation files
- Identify: Use logging system to trace the issue across systems
- Isolate: Determine if it's Vue-specific, background-specific, or cross-system
- Fix: Apply fix using appropriate error handling patterns
- Verify: Test in all supported browsers following the Testing Strategy
- Review: Understand impact across all integrated systems
- Plan: Update multiple systems coherently
- Migrate: Use composables and stores to isolate changes
- Validate: Ensure all documentation remains accurate and aligns with Testing Strategy