mirror of
https://github.com/BinaryBeastMaster/chat-relay.git
synced 2026-10-20 11:34:42 +00:00
2.9 KiB
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:
- Connects to a central WebSocket relay server.
- Handles incoming
SEND_CHAT_MESSAGEcommands. - Determines the best tab to route each command to.
- Forwards commands to
content.js. - Relays back any errors to the server.
⚙️ WebSocket Lifecycle
Startup
- Load settings via
loadSettingsAndConnect() - Check health endpoint:
/health - If OK, start
attemptWebSocketConnection()
Connection Events
onopen: Connection establishedonmessage: Handle relay command (e.g.,SEND_CHAT_MESSAGE)onclose: Clean up, schedule reconnectonerror: 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
relaySocket: Active WebSocketactiveTabId: Last successful tablastRequestId: For current messageprocessingRequest: Concurrency flagpendingRequests: Queue for future
🔧 Command Handling
- Incoming message:
onmessage - If type is
SEND_CHAT_MESSAGE, it clearspendingRequests, updates globals, and forwards to content forwardCommandToContentScript()pings known tab or scans for valid tab (chatgpt.com,aistudio, etc.)- Sets
lastKnownRequestIdindebuggerAttachedTabs
🛡️ 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.