// A single, reused WebSocket connection to /connect, mirroring // android/.../data/transport/PipelinesClient.kt: requests are serialized, each // carries a client-generated stable id, replies are matched by id, and an // unsolicited envelope is surfaced as a DOM-free `frame` event (the app folds the // frames it cares about) rather than misattributed to a request. There is no // authentication of any kind. // // DOM-free on purpose: the browser app and the Node smoke test share this exact // module, so the smoke test exercises the real client, not a re-implementation. import { Protocol } from "./protocol.js"; /** A server `type:"error"` reply, surfaced with the server's own text. */ export class ProtocolError extends Error { constructor(message) { super(message); this.name = "ProtocolError"; } } /** No live WebSocket connection is available for the request. */ export class NotConnectedError extends Error { constructor(message = "Not connected to the Pipelines server") { super(message); this.name = "NotConnectedError"; } } const IDLE = "idle"; const CONNECTING = "connecting"; const CONNECTED = "connected"; const DISCONNECTED = "disconnected"; const NORMAL_CLOSURE = 1000; export class PipelinesClient extends EventTarget { #WebSocketImpl; #backoffBaseMs; #backoffMaxMs; #requestTimeoutMs; #random; #ws = null; #endpoint = null; #manualClose = false; #attempt = 0; #seq = 0; #pending = new Map(); // id -> { resolve, reject, timer } #queue = Promise.resolve(); #reconnectTimer = null; #state = { kind: IDLE, attempt: 0, reason: "", retrying: false }; constructor({ WebSocketImpl = globalThis.WebSocket, backoffBaseMs = 1000, backoffMaxMs = 30000, requestTimeoutMs = 30000, random = Math.random, } = {}) { super(); if (typeof WebSocketImpl !== "function") { throw new Error("No WebSocket implementation available"); } this.#WebSocketImpl = WebSocketImpl; this.#backoffBaseMs = backoffBaseMs; this.#backoffMaxMs = backoffMaxMs; this.#requestTimeoutMs = requestTimeoutMs; this.#random = random; } get state() { return { ...this.#state }; } #setState(next) { this.#state = next; this.dispatchEvent(new CustomEvent("state", { detail: this.state })); } /** Opens (or re-opens) the connection to a validated server URL. */ connect(validated) { if (!validated || !validated.valid) { throw new Error("server URL is not valid"); } this.#endpoint = validated.wsUrl; this.#manualClose = false; this.#attempt = 0; this.#clearReconnect(); this.#open(); } /** Explicit user disconnect: stops reconnection and closes the socket. */ disconnect() { this.#manualClose = true; this.#clearReconnect(); const socket = this.#ws; this.#ws = null; try { socket?.close(NORMAL_CLOSURE, "client closing"); } catch { /* already closed */ } this.#failPending("Disconnected"); this.#setState({ kind: IDLE, attempt: 0, reason: "", retrying: false }); } /** * Sends one request and awaits the reply with the matching id. Serialized by a * promise chain so concurrent screens cannot interleave frames. */ async call(request) { const run = this.#queue.then(() => this.#doCall(request)); // Keep the chain alive even when a call rejects. this.#queue = run.then( () => undefined, () => undefined, ); return run; } /** * Sends one request without awaiting a reply, returning the generated id * (mirrors the Android `PipelinesClient.sendOnly`). Used for the run-event * watch: `subscribe` may never be acknowledged, so registering a pending entry * would leave it to time out, and `unsubscribe` has nothing to read back. * * The send is synchronous so back-to-back frames (`unsubscribe` then * `subscribe`) keep their order on the wire; the id is still available so a * server that does ack (or refuses) has its reply surface as an unsolicited * `frame` event with that id. A call before the socket is connected is refused * with `NotConnectedError`, exactly like `call`. */ sendOnly(request) { const socket = this.#ws; if (!socket || this.#state.kind !== CONNECTED) throw new NotConnectedError(); const id = `web-${++this.#seq}`; socket.send(JSON.stringify({ ...request, id })); return id; } async #doCall(request) { const socket = this.#ws; if (!socket || this.#state.kind !== CONNECTED) throw new NotConnectedError(); const id = `web-${++this.#seq}`; const payload = JSON.stringify({ ...request, id }); const reply = new Promise((resolve, reject) => { const timer = setTimeout(() => { this.#pending.delete(id); reject(new Error(`request timed out after ${this.#requestTimeoutMs}ms`)); }, this.#requestTimeoutMs); this.#pending.set(id, { resolve, reject, timer }); }); try { socket.send(payload); const response = await reply; if (response.type === Protocol.ERROR) { throw new ProtocolError((response.error || "").trim() || "server error"); } return response; } finally { const entry = this.#pending.get(id); if (entry) { clearTimeout(entry.timer); this.#pending.delete(id); } } } #open() { const current = this.#endpoint; if (!current) return; this.#attempt += 1; this.#setState({ kind: CONNECTING, attempt: this.#attempt, reason: "", retrying: false, }); const socket = new this.#WebSocketImpl(current); const superseded = this.#ws; this.#ws = socket; // Replace the current socket, then close the one it superseded (mirrors // PipelinesClient.openLocked). Its callbacks are ignored from then on, so a // failure the old socket reports late can neither clear the new socket nor // schedule a reconnect that would undo it. A request already sent on the old // socket cannot receive a reply from the replacement, so fail it now rather // than leaving a view waiting for the ordinary request timeout. if (superseded) { this.#failPending("Connection replaced"); try { superseded.close(NORMAL_CLOSURE, "superseded"); } catch { /* already closed */ } } socket.onopen = () => { if (this.#ws !== socket) return; this.#attempt = 0; this.#setState({ kind: CONNECTED, attempt: 0, reason: "", retrying: false }); }; socket.onmessage = (event) => { if (this.#ws !== socket) return; this.#onMessage(event.data); }; socket.onclose = (event) => { if (this.#ws !== socket) return; this.#handleClosed(`Connection closed (${event.code ?? "?"})`); }; socket.onerror = () => { // Browsers withhold detail here; onclose carries the outcome. }; } #onMessage(data) { if (typeof data !== "string") return; // the server is text-only let message; try { message = JSON.parse(data); } catch { return; // malformed frame: never misattribute it to a request } const entry = message.id ? this.#pending.get(message.id) : null; if (entry) { this.#pending.delete(message.id); clearTimeout(entry.timer); entry.resolve(message); return; } // No pending request matches: the envelope is unsolicited — the connection's // initial `pipeline_list`, or a server push such as a `chat_event` frame or a // `run_event` — and is surfaced as a DOM-free `frame` event for a view to fold; // with no listener it is simply dropped. It is never misattributed to a // request, which is still matched by id. this.dispatchEvent(new CustomEvent("frame", { detail: message })); } #failPending(reason) { for (const [id, entry] of this.#pending) { this.#pending.delete(id); clearTimeout(entry.timer); entry.reject(new Error(reason)); } } #handleClosed(reason) { this.#ws = null; this.#failPending(reason); if (this.#manualClose) { this.#setState({ kind: IDLE, attempt: 0, reason: "", retrying: false }); return; } this.#scheduleReconnect(reason); } #scheduleReconnect(reason) { if (this.#reconnectTimer) return; this.#setState({ kind: DISCONNECTED, attempt: this.#attempt, reason, retrying: true, }); const shift = Math.min(Math.max(this.#attempt - 1, 0), 6); const backoff = Math.min(this.#backoffBaseMs << shift, this.#backoffMaxMs); const jitter = Math.floor(this.#random() * 400); this.#reconnectTimer = setTimeout(() => { this.#reconnectTimer = null; if (!this.#manualClose && this.#endpoint) this.#open(); }, backoff + jitter); } #clearReconnect() { if (this.#reconnectTimer) { clearTimeout(this.#reconnectTimer); this.#reconnectTimer = null; } } }