Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Merge #7785: WebSocket live updates for direct browsers
milind-soni7a6d13c2b4c2
diff --cc CONTRIBUTING.mdindex 3db75c54fe,c8f2e4b307..e009c693aa--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@@ -78,9 -78,9 +78,9 @@@ packages built from different commits u| `server/contracts.ts` | The driver SPI and canonical runtime event types. The whole architecture in one file — read it first. || `server/drivers/` | One file per provider (Claude, Codex, Grok, cloud computer). Adding a provider = one file + one registration line in `builtIn.ts`. || `server/harness/` | Registry (configs → live instances, unknown → shadow) and the fan-in event bus. |- | `server/index.ts` | The HTTP + SSE API the app talks to. |+ | `server/index.ts` | The HTTP API and the live event feed shared by WebSocket and SSE clients. || `server/testing/` | Test fakes: an in-memory driver, plus scripted fake `claude` / `codex` CLIs. |- | `src/` | The React chat app. No transports of its own — HTTP commands out, one SSE stream in. |-| `src/` | The React chat app. Direct browsers send commands over HTTP and receive live chat updates over a paired WebSocket. |++| `src/` | The React chat app. Commands go out over HTTP; live updates come in over one stream (a paired direct browser's WebSocket, else SSE). || `electron/` | Desktop shell: dictation, screen capture, local computer-use daemon. macOS-specific code lives here, gated. || `dist-server/` | **Build output.** Never hand-edit, never include in PRs — it's regenerated by `pnpm build:server` at release time. |diff --cc docs/verification/README.mdindex d56c231b70,5ed3557ecd..46a12ab9bd--- a/docs/verification/README.md+++ b/docs/verification/README.md@@@ -45,6 -45,7 +45,7 @@@ Use only mapped, tested commands- [The headless command line](headless-cli.md)- [Chat turns](chat-turns.md)-- [Browser WebSocket delivery, replay, and SSE fallback](websocket-browser.md)++- [Browser WebSocket delivery and the SSE fallback](websocket-browser.md)- [OpenAI reply readout](openai-readout.md)- [Conversation context compaction](context-compaction.md)- [Work summaries and engine hooks](digests.md)diff --cc docs/verification/websocket-browser.mdindex 0000000000,e34e86f71f..760069b160mode 000000,100644..100644--- a/docs/verification/websocket-browser.md+++ b/docs/verification/websocket-browser.md@@@ -1,0 -1,28 +1,20 @@@+ # Browser WebSocket delivery+-Direct browser chat requires a paired or signed-in browser session, including on-localhost. A WebSocket becomes live after a valid hello. After three seconds-visible and online without a hello, or after a disconnect, the browser retries-over WebSocket with backoff and resumes from its last committed cursor. A proxy-blocking WebSocket upgrades prevents live chat delivery until the socket can-connect. Desktop and encrypted phone relay clients keep their existing transports.++A paired or signed-in direct browser receives live chat updates over a WebSocket++on `/api/events`; commands still go over HTTP. The socket becomes live after a++valid hello. After three seconds visible and online without a hello, or after a++disconnect, the browser reconnects with backoff and resumes from its last++committed cursor.+-Build and run the isolated browser check:++The event stream (SSE) on the same path stays the fallback. A browser whose first++socket never says hello (a proxy that blocks upgrades, or a browser this server++keeps on the event stream, such as one on this computer that is not paired)++switches to the event stream for the rest of the page's life. A browser whose++socket has worked before switches after three failed handshakes in a row.++Desktop and encrypted phone relay clients keep their existing transports.+-```sh-pnpm build-OMB_CDP_CHROME=/usr/bin/chromium node scripts/verify-websocket-browser.ts-```--The check pairs Chromium with a disposable fake-engine server serving `dist`.-It opens the root URL without a transport query and sends `probe0`, `probe1`,-and `probe2` through the real composer. It checks a WebSocket reply, closes the socket during the second reply, and temporarily blocks socket-creation before the third reply to verify WebSocket retries without SSE. Every prompt must appear-once in storage. Stored reply paragraphs must appear once and in order in the-rendered message.--The server authorization, heartbeat and revocation check is separate:++The server authorization, heartbeat and revocation check:++ ```sh+ OMB_CDP_CHROME=/usr/bin/chromium node scripts/verify-websocket-feed.ts+ ```diff --cc server/index.tsindex 1084c9aaaf,253cc8fce8..947e1ba7ae--- a/server/index.ts+++ b/server/index.ts@@@ -302,8 -302,8 +302,8 @@@ import { CONSENT_RULE, continuedOriginimport { decideRoomPost, emptyRoomPostBudget, type RoomPostAttempt, type RoomPostBudget } from "./room-post-budget.ts";import { messagePages, pageMessage, pageSize, slimMessage } from "./host/message-pages.ts"; import { SUGGESTION_MAX_AGE_MS, suggestedSelection } from "./host/suggested-selection.ts"; import { otherProviderSelection } from "./checker-model.ts"; import { checkWorkFile, createCheckWork } from "./host/check-work.ts";import { coordinateResultMessage, createAsksActingPerson, createTeammatePrompts } from "./host/teammate-prompts.ts"; import { createPersonalReach } from "./host/personal-reach.ts"; import { createMausBotOwnChat } from "./host/mausbot-own-chat.ts"; import { moveMemoryLayer } from "./memory-move.ts";-import { createQueuedReason } from "./host/queued-reason.ts";+import { createQueuedReason } from "./host/queued-reason.ts"; import { roomReasonFor } from "./host/room-queued-reason.ts";- import { ReplayBuffer } from "./host/sse-replay.ts";+ import { ReplayBuffer, type ReplayFrame } from "./host/sse-replay.ts";import {mentionedBots,roomResponders,@@@ -14408,64 -14423,71 +14412,30 @@@ const handleRequest = async (req: Incomreturn run ? json(res, 200, { run }) : json(res, 404, { error: "no such active run" });}- if (path === "/api/calendar-calls" && method === "GET") {- return json(res, 200, { calls: calendarCalls!.list() });- }- if (path === "/api/calendar-calls" && method === "POST") {- try {- const body = await readBody(req);- const conflict = calendarAudienceConflict(body);- if (conflict) return json(res, 400, { error: conflict });- return json(res, 201, { call: calendarCalls!.create(body) });- } catch (error) {- throw Object.assign(error instanceof Error ? error : new Error(String(error)), { status: 400 });- }- }- const calendarCallRoomMatch = path.match(/^\/api\/calendar-calls\/([\w-]+)\/room$/);- if (calendarCallRoomMatch && method === "POST") {- const call = calendarCalls!.get(calendarCallRoomMatch[1]);- if (!call) return json(res, 404, { error: "no such scheduled call" });- if (call.botIds.length < 2) {- return json(res, 400, { error: "single-bot events open that bot's chat directly" });- }- const group = ensureCalendarCallRoom(call);- return json(res, 200, { group: { ...personRooms.groupForAuth(auth, publicGroupState(group)), messages: store.messagesFor(group.threadId) } });- }- const calendarCallMatch = path.match(/^\/api\/calendar-calls\/([\w-]+)$/);- if (calendarCallMatch && method === "PATCH") {- if (!calendarCalls!.get(calendarCallMatch[1])) return json(res, 404, { error: "no such scheduled call" });- try {- const body = await readBody(req);- const conflict = calendarAudienceConflict(body);- if (conflict) return json(res, 400, { error: conflict });- return json(res, 200, { call: calendarCalls!.update(calendarCallMatch[1], body) });- } catch (error) {- throw Object.assign(error instanceof Error ? error : new Error(String(error)), { status: 400 });- }- }- if (calendarCallMatch && method === "DELETE") {- return calendarCalls!.remove(calendarCallMatch[1])- ? json(res, 200, { ok: true })- : json(res, 404, { error: "no such scheduled call" });- }-if (method === "GET" && path === "/api/events") {const pushKey = phoneKey(auth);- const client: SseClient = {- res, ...streamView(auth, viewer), ...(pushKey ? { pushKey } : {}),- screens: url.searchParams.get("screens") !== "off", threadFrames: url.searchParams.get("frames") === "thread", appWindow: url.searchParams.get("window") === "1",- backpressured: false,- // A comment frame keeps intermediaries from idling the connection; a data frame resets EventSource's own liveness watchdog. Heartbeats carry no id.- close: openSseHeartbeat(res, {- everyMs: SSE_HEARTBEAT_MS,- live: () => !client.sessionId || sessions.isLive(client.sessionId),- onClose: () => sseClients.delete(client),- }),- };- if (auth.kind === "session") client.sessionId = auth.session.id;- res.writeHead(200, {- "content-type": "text/event-stream",- "cache-control": "no-cache",- connection: "keep-alive",- // Honoured by nginx-compatible reverse proxies; harmless elsewhere.- "x-accel-buffering": "no",- });-- // EventSource reconnects with a newer Last-Event-ID while the URL keeps an older ?since=: prefer the header, or the stale query replays forever.- const since =- cursorSeq(req.headers["last-event-id"]) ??- cursorSeq(url.searchParams.get("since") ?? undefined);- // A cursor that fell off the buffer gets no partial replay: it would leave a permanent hole.- const resumed =- since !== null &&- since <= lastSeq &&- replayBuffer.covers(since, lastSeq) && botFrames.resumable(since, threadFramesFor(client)) &&- // A replay is judged by today's audience and cannot withdraw what an audience change hid: snapshot instead.- !(viewer.kind === "member" && audienceChangedAt > 0 && since <= audienceChangedAt);- res.write(- `data: ${JSON.stringify({- kind: "hello",- cursor: `${STREAM_ID}:${lastSeq}`,- resumed,- } satisfies ServerFrame)}\n\n`,- );- if (resumed) {- for (const buffered of replayBuffer) {- if (buffered.seq <= since || !wants(client, buffered.kind, buffered.frames) || (buffered.payload && !teamOwners.reaches(client.ask, buffered.payload)) || !streamFor(client, buffered.person)) continue;- const frame = CLOUD_TEAM && buffered.kind === "config" && buffered.clientFrame !== null && buffered.payload- ? teamConfigFrame(client, buffered.seq, buffered.payload)- : buffered.payload- ? memberFrame(client, buffered.seq, buffered.payload, client.admin ? buffered.frame : buffered.clientFrame)- : client.admin- ? buffered.frame- : buffered.clientFrame;- if (frame) res.write(frame);- }- }-- sseClients.add(client);- req.socket.setTimeout(0);- req.on("close", client.close);- return;+ let active: SseClient | undefined;+ return openEventFeed(req, res, auth, writer => {+ const client: SseClient = {+ ...writer, ...streamView(auth, viewer), ...(pushKey ? { pushKey } : {}),+ sessionId: auth.kind === "session" ? auth.session.id : undefined,+ screens: url.searchParams.get("screens") !== "off", threadFrames: url.searchParams.get("frames") === "thread", appWindow: url.searchParams.get("window") === "1",+ };+ active = client;+ const since = cursorSeq(req.headers["last-event-id"]) ?? cursorSeq(url.searchParams.get("since") ?? undefined);+ const resumed = since !== null && since <= lastSeq && replayBuffer.covers(since, lastSeq)+ && botFrames.resumable(since, threadFramesFor(client))+ && !(viewer.kind === "member" && audienceChangedAt > 0 && since <= audienceChangedAt);+ if (!client.send("hello", JSON.stringify({ kind: "hello", cursor: `${STREAM_ID}:${lastSeq}`, resumed } satisfies ServerFrame))) return;+ if (resumed) {+ for (const buffered of replayBuffer) {+ if (buffered.seq <= since) continue;+ const json = streamJson(client, buffered);+ if (json !== null && !client.send(buffered.kind, json, `${STREAM_ID}:${buffered.seq}`)) return;+ }+ }+ sseClients.add(client);+ }, () => { if (active) sseClients.delete(active); });}if (method === "GET" && path === "/api/bot-defaults") {diff --cc src/lib/live-events.test.tsindex 2bba8a4b51,8e6ca21d6e..a1bf1172ef--- a/src/lib/live-events.test.ts+++ b/src/lib/live-events.test.ts@@@ -527,3 -528,183 +528,214 @@@ describe("the live connection's phase,stop();});});++ describe("the WebSocket feed", () => {+ function socketHarness() {+ const h = harness();+ const sockets: FakeEventSource[] = [];+ const platform = { ...h.platform, createWebSocket: (url: string) => {+ const socket = new FakeEventSource(url);+ sockets.push(socket);+ return socket;+ } };+ return { ...h, sockets, platform };+ }++ it("requires hello, bounds a silent upgrade and ignores its late callbacks", () => {+ const h = socketHarness();+ const onOpen = vi.fn();+ const onFrame = vi.fn();+ const stop = openLiveEvents({ onFrame, onOpen, onSnapshotRequired: async () => true }, h.platform);+ const socket = h.sockets[0]!;+ const late = socket.onmessage!;+ socket.message({ kind: "ping" });+ expect(onOpen).not.toHaveBeenCalled();+ vi.advanceTimersByTime(3_000);+ expect(socket.close).toHaveBeenCalledOnce();+ expect(h.sources).toHaveLength(0);+ late({ data: JSON.stringify({ kind: "message" }), lastEventId: "lost:2" });+ expect(onFrame).not.toHaveBeenCalled();+ stop();+ });++ it("reconnects repeatedly over WebSocket from the committed cursor", async () => {+ const h = socketHarness();+ const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, h.platform);+ h.sockets[0]!.message({ kind: "hello", cursor: "epoch:1", resumed: false });+ await Promise.resolve();+ h.sockets[0]!.message({ kind: "bot" }, "epoch:2");+ const error = h.sockets[0]!.onerror!;+ error(); error();+ vi.advanceTimersByTime(500);+ expect(h.sockets).toHaveLength(2);+ expect(h.sockets[1]!.url).toContain("since=epoch%3A2");+ h.sockets[1]!.message({ kind: "hello", cursor: "epoch:2", resumed: true });+ h.sockets[1]!.error();+ expect(h.sources).toHaveLength(0);+ vi.advanceTimersByTime(1_000);+ expect(h.sockets).toHaveLength(3);+ expect(h.sockets[2]!.url).toContain("since=epoch%3A2");+ expect(h.sources).toHaveLength(0);+ stop();+ });++ it("resumes the remaining hello budget after a hidden or offline interval", () => {+ const h = socketHarness();+ const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, { ...h.platform, now: Date.now });+ vi.advanceTimersByTime(2_000);+ h.setVisible(false);+ h.documentTarget.emit("visibilitychange");+ vi.advanceTimersByTime(60_000);+ h.setOnline(false);+ h.windowTarget.emit("offline");+ h.setVisible(true);+ h.documentTarget.emit("visibilitychange");+ vi.advanceTimersByTime(60_000);+ h.setOnline(true);+ h.windowTarget.emit("online");+ vi.advanceTimersByTime(999);+ expect(h.sockets).toHaveLength(1);+ expect(h.sources).toHaveLength(0);+ vi.advanceTimersByTime(1);+ expect(h.sockets[0]!.close).toHaveBeenCalledOnce();+ expect(h.sources).toHaveLength(0);+ stop();+ });++ it("clears the handshake timer after hello and releases all timers on close", async () => {+ const h = socketHarness();+ const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, h.platform);+ expect(vi.getTimerCount()).toBe(2);+ h.sockets[0]!.message({ kind: "hello", cursor: "epoch:1", resumed: false });+ await Promise.resolve();+ expect(vi.getTimerCount()).toBe(1);+ stop();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("keeps snapshot failure separate from transport failure", async () => {+ const h = socketHarness();+ const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => false }, h.platform);+ h.sockets[0]!.message({ kind: "hello", cursor: "epoch:1", resumed: false });+ await Promise.resolve();+ vi.advanceTimersByTime(500);+ expect(h.sockets).toHaveLength(2);+ expect(h.sources).toHaveLength(0);+ expect(h.sockets[1]!.url).not.toContain("since=");+ stop();+ });+ it("does not commit a snapshot that completes after socket loss", async () => {+ const h = socketHarness();+ let finish: (loaded: boolean) => void = () => {};+ const snapshot = new Promise<boolean>((resolve) => { finish = resolve; });+ const opened = vi.fn();+ const stop = openLiveEvents({ onFrame: vi.fn(), onOpen: opened, onSnapshotRequired: () => snapshot }, h.platform);+ h.sockets[0]!.open();+ expect(opened).not.toHaveBeenCalled();+ h.sockets[0]!.message({ kind: "hello", cursor: "epoch:4", resumed: false });+ h.sockets[0]!.message({ kind: "bot" }, "epoch:5");+ h.sockets[0]!.error();+ finish(true);+ await Promise.resolve();+ vi.advanceTimersByTime(500);+ expect(h.sockets[1]!.url).not.toContain("since=");+ stop();+ });+- it("retries WebSocket when construction fails", () => {++ it("falls back to the event stream when the socket cannot be made", () => {+ const h = harness();+ const socket = vi.fn(() => { throw new Error("unsupported"); });+ const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, {+ ...h.platform, createWebSocket: socket,+ });+ vi.advanceTimersByTime(500);- expect(socket).toHaveBeenCalledTimes(2);- expect(h.sources).toHaveLength(0);++ expect(socket).toHaveBeenCalledTimes(1);++ expect(h.sources).toHaveLength(1);++ stop();++ });++++ it("falls back to the event stream for good when the first socket never says hello, as behind a proxy that blocks upgrades", () => {++ const h = socketHarness();++ const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, h.platform);++ h.sockets[0]!.error();++ vi.advanceTimersByTime(500);++ expect(h.sockets).toHaveLength(1);++ expect(h.sources).toHaveLength(1);++ h.sources[0]!.error();++ vi.advanceTimersByTime(1_000);++ expect(h.sockets).toHaveLength(1);++ expect(h.sources).toHaveLength(2);++ stop();++ });++++ it("falls back to the event stream after a socket that worked fails its handshake three times in a row", async () => {++ const h = socketHarness();++ const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, h.platform);++ h.sockets[0]!.message({ kind: "hello", cursor: "epoch:1", resumed: false });++ await Promise.resolve();++ h.sockets[0]!.error();++ for (let attempt = 1; attempt <= 3; attempt++) {++ vi.advanceTimersByTime(10_000);++ expect(h.sockets).toHaveLength(attempt + 1);++ h.sockets[attempt]!.error();++ }++ vi.advanceTimersByTime(10_000);++ expect(h.sockets).toHaveLength(4);++ expect(h.sources).toHaveLength(1);+ stop();+ });++ });++ describe("browser transport selection", () => {+ function browser(search = "", desktop = false) {+ const sockets: FakeEventSource[] = [];+ const streams: FakeEventSource[] = [];+ vi.stubGlobal("window", Object.assign(new FakeTarget(), {+ location: new URL(`https://example.test/${search}`),+ ...(desktop ? { ogb: { platform: "linux" } } : {}),+ }));+ vi.stubGlobal("WebSocket", class extends FakeEventSource {+ constructor(url: URL) { super(url.href); sockets.push(this); }+ });+ vi.stubGlobal("EventSource", class extends FakeEventSource {+ constructor(url: string) { super(url); streams.push(this); }+ });+ const open = () => openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, {+ isVisible: () => true, isOnline: () => true, documentTarget: new FakeTarget(),+ });+ return { sockets, streams, open };+ }++ it.each(["", "?liveTransport=auto", "?liveTransport=sse"])("uses WebSocket for a direct browser at /%s", (search) => {+ const h = browser(search);+ const stop = h.open();+ expect(h.sockets).toHaveLength(1);+ expect(h.sockets[0]!.url).toContain("wss://example.test/api/events?");+ expect(h.streams).toHaveLength(0);+ stop();+ expect(h.sockets[0]!.close).toHaveBeenCalledOnce();+ });++ it.each([+ { search: "", desktop: true },+ { search: "?liveTransport=auto", desktop: true },+ ])("keeps SSE for $search with desktop=$desktop", ({ search, desktop }) => {+ const h = browser(search, desktop);+ const stop = h.open();+ expect(h.sockets).toHaveLength(0);+ expect(h.streams).toHaveLength(1);+ stop();+ });++ it("keeps the relay link ahead of direct browser transports", () => {+ const h = browser();+ const fetch = vi.fn(async () => new Response("", { headers: { "content-type": "text/event-stream" } }));+ setRelayLink({ fetch, close: vi.fn() });+ const stop = h.open();+ expect(fetch).toHaveBeenCalledWith(expect.stringContaining("/api/events?"), expect.any(Object));+ expect(h.sockets).toHaveLength(0);+ expect(h.streams).toHaveLength(0);+ stop();+ });+ });diff --cc src/lib/live-events.tsindex 86b5793c57,ae8ba1a8eb..6aa9a595d2--- a/src/lib/live-events.ts+++ b/src/lib/live-events.ts@@@ -229,6 -221,10 +233,24 @@@ export function openLiveEventsconst retryMaxMs = Math.max(retryMinMs, handlers.retryMaxMs ?? LIVE_EVENTS_RETRY_MAX_MS);const staleCheckMs = Math.min(10_000, Math.max(250, staleMs / 2));- const socketFeed = Boolean(platform.createWebSocket);- const createSource = platform.createWebSocket ?? platform.createEventSource;++ // A direct browser tries the socket first. One that never says hello (a proxy that blocks upgrades, or a browser this++ // server keeps on the event stream, such as an unpaired one on this computer) falls back to the event stream for good:++ // at once if no socket ever opened here, else after three in a row.++ let socketFeed = Boolean(platform.createWebSocket);++ let socketWorked = false;++ let socketMisses = 0;++ let sourceIsSocket = false;++ const createSource = (url: string) => (sourceIsSocket && platform.createWebSocket ? platform.createWebSocket(url) : platform.createEventSource(url));++ const socketMissed = () => {++ if (!sourceIsSocket || helloReceived) return;++ socketMisses += 1;++ if (socketMisses >= (socketWorked ? 3 : 1)) {++ socketFeed = false;++ retryAttempt = 0;++ }++ };+ let helloReceived = false;+ let helloBudget = 3_000;let stopped = false;let source: LiveEventSourceLike | null = null;let sourceScreens = screensWanted();@@@ -281,28 -281,49 +307,52 @@@const connectionLost = (current: LiveEventSourceLike) => {if (stopped || source !== current) return;++ socketMissed();closeSource();handlers.onError?.();scheduleReconnect();};+ const updateHelloDeadline = () => {- if (!source || helloReceived || !socketFeed) return;++ if (!source || helloReceived || !sourceIsSocket) return;+ if (holdReason(platform)) {+ if (helloTimer !== undefined) {+ helloBudget = Math.max(0, helloBudget - (platform.now() - helloStartedAt));+ clearTimeout(helloTimer);+ helloTimer = undefined;+ }+ } else if (helloTimer === undefined) {+ const current = source;+ helloStartedAt = platform.now();+ helloTimer = setTimeout(() => {+ helloTimer = undefined;+ if (!holdReason(platform)) connectionLost(current);+ }, helloBudget);+ }+ };+connect = () => {if (!stopped && !source) livePhaseNow = (!platform.isOnline() ? "offline" : cloudAsleep() ? "asleep" : null) ?? "opening";if (stopped || source || !platform.isOnline() || cloudAsleep()) return;let current: LiveEventSourceLike;try {sourceScreens = screensWanted();- current = platform.createEventSource(liveEventsUrl({ since: cursor, screens: sourceScreens }));+ helloReceived = false;+ helloBudget = 3_000;++ sourceIsSocket = socketFeed;+ current = createSource(liveEventsUrl({ since: cursor, screens: sourceScreens }));} catch {++ socketMissed();handlers.onError?.();scheduleReconnect();return;}source = current;+ updateHelloDeadline();lastHeardAt = platform.now();current.onopen = () => {- if (stopped || source !== current) return;- if (stopped || source !== current || socketFeed) return;++ if (stopped || source !== current || sourceIsSocket) return;lastHeardAt = platform.now();livePhaseNow = "open";handlers.onOpen?.();@@@ -315,6 -336,8 +365,8 @@@const frame = parseLiveFrame(event.data);if (!frame) return;- if (socketFeed && !helloReceived && frame.kind !== "hello") return;++ if (sourceIsSocket && !helloReceived && frame.kind !== "hello") return;+if (isLivePing(frame)) {// An open event only proves a handshake; a ping proves the stream stayed usable.retryAttempt = 0;@@@ -322,6 -345,14 +374,16 @@@}if (frame.kind === "hello") {- if (socketFeed && !helloReceived) {++ if (sourceIsSocket && !helloReceived) {+ if (typeof frame.resumed !== "boolean" || typeof frame.cursor !== "string") return;+ helloReceived = true;++ socketWorked = true;++ socketMisses = 0;+ clearTimeout(helloTimer);+ helloTimer = undefined;+ livePhaseNow = "open";+ handlers.onOpen?.();+ }// Replay frames follow `resumed:true`: advancing to hello's cursor now could skip one if the socket dies mid-replay.if (frame.resumed === false) {const generation = ++snapshotGeneration;@@@ -394,6 -425,7 +456,7 @@@const recover = () => {// Background tabs suspend timers and network delivery: recover once on wake.if (stopped || !platform.isOnline() || !platform.isVisible() || cloudAsleep()) return;- if (source && socketFeed && !helloReceived) return;++ if (source && sourceIsSocket && !helloReceived) return;if (!source || shouldReconnectLiveEvents(lastHeardAt, platform.now(), staleMs)) {reconnectNow(source !== null);}