Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(frontend): recover the live socket on WebKit via one-time WS tickets (BUG-065)
Ruben Lütke735f4d069a68
diff --git a/jarvis/ui/web/frontend/src/__tests__/ws.test.ts b/jarvis/ui/web/frontend/src/__tests__/ws.test.tsindex b1f24815d5..2de40dbfe0 100644--- a/jarvis/ui/web/frontend/src/__tests__/ws.test.ts+++ b/jarvis/ui/web/frontend/src/__tests__/ws.test.ts@@ -119,4 +119,101 @@ describe("WSClient", () => {vi.useRealTimers();}});++ // 4401 = the boundary rejected the handshake credential. WebKit engines do+ // not attach the HttpOnly session cookie to WS handshakes (BUG-065), so the+ // client must prove its session over plain HTTP and retry with the ticket.+ describe("4401 one-time-ticket retry (WebKit cookie-less handshake)", () => {+ const originalFetch = globalThis.fetch;++ afterEach(() => {+ (globalThis as any).fetch = originalFetch;+ });++ it("mints a ticket, reports authRetryPending, and reconnects with ?ticket=", async () => {+ vi.useFakeTimers();+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ ticket: "one-time-abc", expires_in: 60 }),+ });+ (globalThis as any).fetch = fetchMock;+ try {+ const onClose = vi.fn();+ const client = new WSClient({ onClose });+ client.connect();+ const first = MockWebSocket.last;++ first!.fire("close", { code: 4401 });+ await vi.advanceTimersByTimeAsync(500);++ expect(fetchMock).toHaveBeenCalledWith(+ "/api/ui/ws-ticket",+ expect.objectContaining({ method: "POST", credentials: "same-origin" }),+ );+ expect(onClose).toHaveBeenCalledWith(4401, { authRetryPending: true });+ expect(MockWebSocket.last).not.toBe(first);+ expect(MockWebSocket.last!.url).toBe(+ "ws://localhost:5173/ws?ticket=one-time-abc",+ );++ // The ticket is single-use: a later ordinary close reconnects bare.+ MockWebSocket.last!.fire("close", { code: 1013 });+ await vi.advanceTimersByTimeAsync(500);+ expect(MockWebSocket.last!.url).toBe("ws://localhost:5173/ws");+ client.close();+ } finally {+ vi.useRealTimers();+ }+ });++ it("stops fast-retrying after persistent 4401s and reports honest offline", async () => {+ vi.useFakeTimers();+ (globalThis as any).fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ ticket: "one-time-abc", expires_in: 60 }),+ });+ try {+ const onClose = vi.fn();+ const client = new WSClient({ onClose });+ client.connect();++ // Three consecutive 4401s stay within the fast-retry budget...+ for (let i = 0; i < 3; i += 1) {+ MockWebSocket.last!.fire("close", { code: 4401 });+ await vi.advanceTimersByTimeAsync(500);+ expect(onClose).toHaveBeenLastCalledWith(4401, { authRetryPending: true });+ }+ // ...the fourth means fresh tickets are not unlocking the socket:+ // report the honest offline state (escalating backoff takes over).+ MockWebSocket.last!.fire("close", { code: 4401 });+ await vi.advanceTimersByTimeAsync(0);+ expect(onClose).toHaveBeenLastCalledWith(4401, { authRetryPending: false });+ client.close();+ } finally {+ vi.useRealTimers();+ }+ });++ it("reports a dead session honestly when the mint fails", async () => {+ vi.useFakeTimers();+ (globalThis as any).fetch = vi.fn().mockResolvedValue({ ok: false });+ try {+ const onClose = vi.fn();+ const client = new WSClient({ onClose });+ client.connect();+ const first = MockWebSocket.last;++ first!.fire("close", { code: 4401 });+ await vi.advanceTimersByTimeAsync(500);++ expect(onClose).toHaveBeenCalledWith(4401, { authRetryPending: false });+ // Falls back to the normal reconnect path, without a ticket.+ expect(MockWebSocket.last).not.toBe(first);+ expect(MockWebSocket.last!.url).toBe("ws://localhost:5173/ws");+ client.close();+ } finally {+ vi.useRealTimers();+ }+ });+ });});diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsxindex 0f5b06deec..9911385e78 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx@@ -5,7 +5,7 @@* useWebSocket → WSClient → store path (via a MockWebSocket) and asserts that a* VoiceBootStatus frame flips `voiceReady` in the store.*/-import { cleanup, render } from "@testing-library/react";+import { cleanup, render, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -196,4 +196,34 @@ describe("useWebSocket connection state (welcome-gated + warming)", () => {MockWebSocket.last!.fire("close", { code: 1006 });expect(useEventStore.getState().wsWarming).toBe(false);});++ // 4401 = credential rejected at the handshake. On WebKit engines this is+ // the normal cookie-less handshake (BUG-065): while the client re-proves+ // its session via the one-time ticket, the UI must keep the "starting"+ // state instead of flashing OFFLINE; a failed mint (dead session) must+ // still surface the honest offline state.+ it("keeps warming through a 4401 ticket retry, drops it when the mint fails", async () => {+ const originalFetch = globalThis.fetch;+ try {+ (globalThis as unknown as { fetch: unknown }).fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ ticket: "one-time-abc", expires_in: 60 }),+ });+ render(<Harness />);+ await Promise.resolve();++ useEventStore.setState({ wsWarming: false });+ MockWebSocket.last!.fire("close", { code: 4401 });+ await waitFor(() => expect(useEventStore.getState().wsWarming).toBe(true));+ expect(useEventStore.getState().connected).toBe(false);++ (globalThis as unknown as { fetch: unknown }).fetch = vi+ .fn()+ .mockResolvedValue({ ok: false });+ MockWebSocket.last!.fire("close", { code: 4401 });+ await waitFor(() => expect(useEventStore.getState().wsWarming).toBe(false));+ } finally {+ (globalThis as unknown as { fetch: unknown }).fetch = originalFetch;+ }+ });});diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.tsindex 6e259d1b32..f5c9aafab2 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts@@ -52,9 +52,14 @@ export function useWebSocket(): void {// socket open must NOT mark connected — the fast-boot bootstrap also// opens then closes with 1013 without ever sending a welcome frame.onOpen: () => {},- onClose: (code) => {+ onClose: (code, info) => {// 1013 = bootstrap "try again later" → backend still warming, not down.- setWarming(code === 1013);+ // A 4401 with a successful ticket mint (WebKit cookie-less handshake,+ // BUG-065) is equally transient: the next attempt already carries a+ // fresh credential, so keep the "starting" state instead of flashing+ // OFFLINE. A 4401 whose mint failed means the session is dead — that+ // one falls through to the honest offline state.+ setWarming(code === 1013 || Boolean(info?.authRetryPending));setConnected(false);},onMessage: (raw) => {diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.tsindex 0f8cae89dd..2b390be8b7 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts@@ -31,6 +31,15 @@ describe("realtime audio client", () => {expect(buildAudioSocketUrl()).toBe("ws://localhost:47821/ws/audio");});+ it("carries a one-time handshake ticket when one was minted (BUG-065)", () => {+ // The long-lived session token must still never appear in a socket URL;+ // only the consumable short-TTL ticket may ride along for WebKit engines.+ expect(buildAudioSocketUrl("one-time-abc")).toBe(+ "wss://app.example/ws/audio?ticket=one-time-abc",+ );+ expect(buildAudioSocketUrl(null)).toBe("wss://app.example/ws/audio");+ });+it("rejects browser microphone capture outside a secure context", () => {vi.stubGlobal("window", { isSecureContext: false });diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsindex b42c311d2b..00f1e34d88 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -2,12 +2,14 @@// JSON-only WSClient: this socket carries raw mono PCM16 in both directions.import { LevelMeter } from "./levelMeter";+import { mintWsTicket } from "./ws";import pcmWorkletUrl from "./pcm-worklet.ts?worker&url";-export function buildAudioSocketUrl(): string {+export function buildAudioSocketUrl(ticket?: string | null): string {const proto = window.location.protocol === "https:" ? "wss" : "ws";const host = window.location.host;- return `${proto}://${host}/ws/audio`;+ const base = `${proto}://${host}/ws/audio`;+ return ticket ? `${base}?ticket=${encodeURIComponent(ticket)}` : base;}export type RealtimeStatusPayload = Record<string, unknown>;@@ -252,7 +254,12 @@ export class RealtimeAudioClient {this.captureSink.connect(this.ctx.destination);this.playbackNode.connect(this.ctx.destination);- this.ws = new WebSocket(buildAudioSocketUrl());+ // Proactive one-time ticket: WebKit engines do not attach the HttpOnly+ // session cookie to a WS handshake (BUG-065). Minting over plain HTTP+ // first works on every engine; on a mint failure (e.g. older backend)+ // fall back to the cookie-only handshake, which Chromium still accepts.+ const ticket = await mintWsTicket();+ this.ws = new WebSocket(buildAudioSocketUrl(ticket));this.ws.binaryType = "arraybuffer";this.captureNode.port.onmessage = (event) => {const data = event.data as ArrayBuffer | { type?: string; rms?: number };diff --git a/jarvis/ui/web/frontend/src/lib/ws.ts b/jarvis/ui/web/frontend/src/lib/ws.tsindex ab43022fb2..23fb4c0ac1 100644--- a/jarvis/ui/web/frontend/src/lib/ws.ts+++ b/jarvis/ui/web/frontend/src/lib/ws.ts@@ -1,6 +1,10 @@/*** WebSocket client with exponential-backoff reconnect (500ms → 10s cap).- * Ping/Pong every 30s. Authentication uses the same-origin HttpOnly cookie.+ * Ping/Pong every 30s. Authentication uses the same-origin HttpOnly cookie —+ * with a one-time-ticket fallback for WebKit engines (Safari/WKWebView on+ * macOS, WebKitGTK on Linux), which do not attach HttpOnly cookies to a+ * WebSocket handshake: a 4401 close triggers a ticket mint over plain HTTP+ * (where the cookie IS sent) and a fast reconnect carrying `?ticket=`.** Aside from the singleton onMessage callback (used by useWebSocket for the* Zustand store), additional consumers can attach via subscribe() — needed by@@ -9,11 +13,48 @@export type WSHandler = (data: unknown) => void;+export interface WSCloseInfo {+ /** True while the client is about to retry a 4401 with a fresh ticket. */+ authRetryPending: boolean;+}+export interface WSClientOptions {url?: string;onMessage?: WSHandler;onOpen?: () => void;- onClose?: (code?: number) => void;+ onClose?: (code?: number, info?: WSCloseInfo) => void;+}++/** Server close code: credential missing/invalid (readable since BUG-065). */+const WS_CLOSE_UNAUTHORIZED = 4401;++/**+ * Consecutive 4401 closes that still count as a transient auth retry. Beyond+ * this the ticket flow is evidently not unlocking the socket (server-side+ * regression, revoked session mid-mint, ...) — report the honest offline+ * state and fall back to the escalating backoff instead of hammering the+ * mint endpoint every 500 ms forever.+ */+const MAX_FAST_AUTH_RETRIES = 3;++/**+ * Mint a one-time WebSocket ticket over cookie-authenticated HTTP.+ * Returns null when the session itself is dead (401) or the fetch fails.+ */+export async function mintWsTicket(): Promise<string | null> {+ try {+ const response = await fetch("/api/ui/ws-ticket", {+ method: "POST",+ cache: "no-store",+ credentials: "same-origin",+ });+ if (!response.ok) return null;+ const data: unknown = await response.json();+ const ticket = (data as { ticket?: unknown }).ticket;+ return typeof ticket === "string" && ticket.length > 0 ? ticket : null;+ } catch {+ return null;+ }}const MIN_BACKOFF = 500;@@ -27,10 +68,12 @@ export class WSClient {private reconnectTimer: ReturnType<typeof setTimeout> | null = null;private stopped = false;private lastCloseCode: number | undefined;+ private pendingTicket: string | null = null;+ private authRetryStreak = 0;private readonly url: string;private readonly onMessage?: WSHandler;private readonly onOpen?: () => void;- private readonly onClose?: (code?: number) => void;+ private readonly onClose?: (code?: number, info?: WSCloseInfo) => void;private readonly extraSubscribers = new Set<WSHandler>();constructor(opts: WSClientOptions = {}) {@@ -52,8 +95,14 @@ export class WSClient {}private openSocket(): void {+ // A pending ticket is single-use: consume it for exactly this attempt.+ const ticket = this.pendingTicket;+ this.pendingTicket = null;+ const target = ticket+ ? `${this.url}${this.url.includes("?") ? "&" : "?"}ticket=${encodeURIComponent(ticket)}`+ : this.url;try {- this.ws = new WebSocket(this.url);+ this.ws = new WebSocket(target);} catch {this.scheduleReconnect();return;@@ -66,6 +115,9 @@ export class WSClient {});this.ws.addEventListener("message", (ev) => {+ // Any real frame proves the handshake credential worked — the auth+ // retry streak only counts UNINTERRUPTED 4401 rejections.+ this.authRetryStreak = 0;if (ev.data === "pong") return;try {const parsed = JSON.parse(ev.data);@@ -85,6 +137,16 @@ export class WSClient {this.ws.addEventListener("close", (ev) => {this.stopPing();this.lastCloseCode = (ev as CloseEvent).code;+ if (this.lastCloseCode === WS_CLOSE_UNAUTHORIZED && !this.stopped) {+ // WebKit engines drop the HttpOnly session cookie from WS handshakes,+ // so the boundary answers 4401 even though the session is healthy.+ // Prove the session over plain HTTP instead and retry with the+ // one-time ticket. onClose is deferred until the mint settles so the+ // UI can distinguish "authenticating, retry imminent" from a dead+ // session (mint failed → honest offline).+ void this.handleAuthReject();+ return;+ }this.onClose?.(this.lastCloseCode);if (!this.stopped) this.scheduleReconnect();});@@ -94,6 +156,30 @@ export class WSClient {});}+ private async handleAuthReject(): Promise<void> {+ this.authRetryStreak += 1;+ const ticket = await mintWsTicket();+ if (this.stopped) return;+ if (ticket) this.pendingTicket = ticket;+ const retrying = ticket !== null && this.authRetryStreak <= MAX_FAST_AUTH_RETRIES;+ this.onClose?.(this.lastCloseCode, { authRetryPending: retrying });+ if (retrying) {+ // Fixed short retry, like the 1013 warming path: the very next attempt+ // carries a fresh credential, so backoff escalation would only delay it.+ if (this.reconnectTimer) return;+ this.reconnectTimer = setTimeout(() => {+ this.reconnectTimer = null;+ this.openSocket();+ }, MIN_BACKOFF);+ return;+ }+ // The session is gone, the backend vanished mid-mint, or fresh tickets+ // keep getting rejected: report the close honestly and fall back to the+ // escalating reconnect (a still-minted ticket rides along regardless —+ // it is the only path back to a live socket if the server recovers).+ this.scheduleReconnect();+ }+private startPing(): void {this.stopPing();this.pingTimer = setInterval(() => {