chat-relay/docs/background-script.md
BinaryBeastMaster 25abcd2974 Initial commit
2025-05-10 15:09:23 -07:00

2.9 KiB

Background Script Architecture (background.js)

This document explains the structure and behavior of the background.js script, which acts as the coordination layer between the browser, content scripts, and the external WebSocket relay server.


🧩 Overview

The background script performs five key functions:

  1. Connects to a central WebSocket relay server.
  2. Handles incoming SEND_CHAT_MESSAGE commands.
  3. Determines the best tab to route each command to.
  4. Forwards commands to content.js.
  5. Relays back any errors to the server.

⚙️ WebSocket Lifecycle

Startup

Connection Events

  • onopen: Connection established
  • onmessage: Handle relay command (e.g., SEND_CHAT_MESSAGE)
  • onclose: Clean up, schedule reconnect
  • onerror: Logged but not retried directly

🔄 Message Flow

sequenceDiagram
    participant Server
    participant Background
    participant ContentScript

    Server->>Background: SEND_CHAT_MESSAGE (requestId)
    Background->>ContentScript: Forward command with requestId
    ContentScript-->>Background: ACK or Error
    Background-->>Server: CHAT_RESPONSE or CHAT_RESPONSE_ERROR

📌 State


🔧 Command Handling


🛡️ Error Handling

  • If no tab found or failure: sends CHAT_RESPONSE_ERROR
  • If chrome.runtime.lastError: fallback and log
  • All retry logic is bounded and observable

🧠 Debugger Coordination

Maintains a debuggerAttachedTabs map keyed by tabId, storing:

{
  providerName,
  patterns,
  isFetchEnabled,
  isAttached,
  lastKnownRequestId
}

Used to route debugger data back to correct content script or relay logic.


✅ Summary

background.js is the broker between remote commands and browser tabs. It ensures reliability via health checks, dynamic tab discovery, request tracking, and robust error handling.