# KoalaSync AI Onboarding (AI_INIT.md) Welcome to the KoalaSync project. This file is the primary entry point for any developer or AI agent working on this codebase. It defines the architecture, non-negotiables, and workflows required to maintain the stability and security of the system. > [!IMPORTANT] > **Privacy & Data Sovereignty**: KoalaSync follows a strict **Zero-External-Requests Policy**: The extension and website must not make requests to any third-party domains (Google Fonts, CDNs, etc.). All assets (fonts, icons, scripts) must be self-hosted or use system defaults. > - **Font Stack**: Use a modern system font stack (e.g., -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif) to maintain a premium look without external dependencies. Prohibit the use of `@import` or `` for external font services. > > [!IMPORTANT] > **Communication Standard**: Be concise, concrete, and professional. Match the user's language when practical, explain risky changes before making them, and report exactly what was changed and verified. Do not use joke protocols or intentionally broken language in contributor-facing work. --- ## 1. Project Overview KoalaSync is a specialized tool for **synchronized video playback** across multiple remote peers. It supports YouTube, Twitch, and native HTML5 video elements. - **Users**: Friends or groups wanting to watch synchronized content together. - **Workflow**: A user creates a room, shares an invitation link, and all peers in that room are synchronized via a Node.js relay server. - **Identity**: Users are identified by a unique hex `peerId` combined with a customizable `username`. ## 2. Repository Structure - `extension/`: Browser Extension (Chrome & Firefox, Manifest V3). Contains background service worker, content scripts, and popup UI. - `server/`: Node.js Relay Server using Socket.IO (WebSocket-only). - `website/`: **Landing Page** & Invitation Bridge (Marketing, Tutorials, and Downloads). - **`build.cjs`**: Static site compiler using the repository's build dependencies. Translates `template.html` + `locales/*.json` → `www/`, generates the sitemap, and minifies HTML/CSS/JS. - **`www/` is auto-generated**: Never edit files in `www/` directly. Always edit source files (`template.html`, `style.css`, `styles/*.css`, `app.js`, `lang-init.js`, `locales/*.json`) and run `node website/build.cjs` to regenerate. `style.css` is the development manifest; `style.legacy.css` is an unloaded, byte-identical migration reference. Production creates page-specific and render-priority CSS bundles from `styles/*.css`; CSS/JS are output as `.min.*` files and stale generated assets are removed on each build. - `shared/`: **Single Source of Truth** for protocol constants, event names, blacklist data, and generated usernames. - `scripts/`: Development utilities (e.g., `build-extension.cjs`). - `docker-compose.yml`: Root-level orchestration for the relay server. > [!IMPORTANT] > **Single Source of Truth**: `shared/constants.js`, `shared/blacklist.js`, and `shared/names.js` are the master shared files. They must be synchronized to the `extension/shared/` directory using `node scripts/build-extension.cjs`. > - **Extension Modules** (`background.js`, `popup.js`) import directly from `./shared/constants.js`. > - **Content Scripts** (`content.js`) use a **marker-injected synchronous copy** of the constants. The build script automatically replaces the marked blocks — no manual mirroring needed. ## 3. Mandatory Reading Before touching any code, you MUST read the following documents in order: 1. [../README.md](../README.md) – User, developer, and self-hosting overview. 2. [README.md](README.md) – Documentation map by role. 3. [ARCHITECTURE.md](ARCHITECTURE.md) – Detailed communication flows, Dual Heartbeat, and two-phase sync protocol. 4. [../extension/README.md](../extension/README.md) – Extension components, tab structure, and loading process. 5. [SYNC_GUIDE.md](SYNC_GUIDE.md) – Protocol constants and synchronization requirements. ## 4. The "Vanilla JS Mirror" Pattern To avoid boot-time race conditions in Manifest V3 without a bundler, the following architectural trade-off is enforced: - **Synchronous Execution**: `content.js` MUST execute synchronously to catch early media events. - **Automated Injection**: The build script (`node scripts/build-extension.cjs`) automatically injects `EVENTS`, `HEARTBEAT_INTERVAL`, and episode utility functions into `content.js` using marker-based replacement (see `../scripts/README.md` for marker details). - **Maintenance**: After modifying any root `shared/` file, run the build script. No manual mirroring is required. ## 5. File Responsibility Map | File | Responsibility | |:-----|:---------------| | `background.js` | WebSocket client, state orchestrator, event router, session persistence | | `content.js` | Video element detection, media control, event origin detection (loop prevention) | | `popup.js` | UI rendering, user input handling, peer display, invitation link generation | | `bridge.js` | Landing page ↔ extension communication for invitation join flow | | `episode-utils.js` | Shared episode parsing, imported by background and injected into content | | `title-privacy.js` | Tab/media title privacy normalization and sanitization | | `page-api-seek-overrides.js` | Page-level seek bridge for site-specific player APIs | | `server/index.js` | Room management, message relay, rate limiting, authentication, peer lifecycle | ## 6. Design Guidelines The popup UI follows a strict design system. Do not modify these variables or the layout structure without explicit approval. - **Font**: System font stack. **MANDATORY**: No external CDNs or Google Fonts to ensure 100% privacy. - **Popup Width**: Fixed at `320px`. - **Tab Structure**: Must maintain the visible **Room**, **Sync**, **Settings**, and **Status** tabs. The hidden **Dev** tab is available only for developer diagnostics. - **Appearance modes**: Preserve `system`, `light`, and `dark` behavior and the Eucalyptus, Cyber, and Graphite palettes. - **CSS variables**: Use the semantic tokens defined in `popup.html` (`--bg`, `--card`, `--accent`, `--text`, `--text-muted`, `--success`, `--warning`, and `--error`). Do not hard-code the retired indigo/slate palette or bypass palette-specific token overrides. ## 7. Non-Negotiables (Core Logic) The following features are critical and must not be removed or fundamentally altered: - **Two-Phase Force Sync**: The `Prepare` → `ACK` → `Execute` flow ensures all peers are buffered before playback resumes. - **Episode Auto-Sync**: Ensures series binges stay perfectly synced. A lobby initiates during title transitions, freezing peers until everyone is ready. - **Host Control Mode**: In `host-only` rooms, only the host and promoted controllers may initiate room-moving playback events. Both client-side UX and server-side gates must remain intact. - **Dual Heartbeat**: - **Background Heartbeat (1m)**: Ensures session persistence even without a video element. - **Content Heartbeat (15s)**: Transmits current video metadata (time, title). - **Dead Peer Pruning**: Server "Reaper" disconnects peers after 5 minutes of total silence (no heartbeats or events). - **Deduplication**: Server kills old sockets if a user re-joins with the same `peerId` to prevent ghosts. - **Platform Specifics**: Specialized click-logic for YouTube (`.ytp-play-button`) and Twitch. - **pollSeekReady()**: Polling mechanism that checks `video.readyState` before acknowledging sync. - **SW Keep-alive**: Use of `chrome.alarms` to prevent the Manifest V3 Service Worker from suspending. - **Diagnostics**: The visible **Status** tab provides real-time access to connection state, ping, logs, history, and underlying `