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(agentic-ide): a pane that cannot connect now retries instead of dying
Ruben Lütke8c184c8efb83
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 2bf37ea10e..2616751a03 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -1150,6 +1150,16 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:"""await ws.accept()if not credentials_valid(ws.scope):+ # Logged because from the pane's side a refused handshake and a terminal+ # that will not start look identical — both are a red pane — and until+ # this line the whole failure path wrote nothing anywhere, so a grid of+ # dead panes could not be explained after the fact. Expected once per+ # socket on WebKit engines, which withhold the session cookie from a WS+ # handshake (BUG-065); the client answers by proving the session over+ # plain HTTP and retrying with a one-time ticket.+ log.warning(+ "Agentic IDE: refused an unauthorized terminal socket for %r", name+ )await ws.close(code=4401, reason="unauthorized")return@@ -1188,6 +1198,16 @@ async def agentic_pty(ws: WebSocket, name: str) -> None:name, cols, rows, on_output, on_exit, workspace_id=pane_workspace)except SessionError as exc:+ # The reason used to travel to the browser and nowhere else, where it+ # ended up as a tooltip on a red badge. A spawn that fails for every+ # pane at once is exactly when nobody is hovering — so it is recorded+ # here as well, with the pane and the workspace it was resolved against.+ log.warning(+ "Agentic IDE: %r could not attach (workspace=%s): %s",+ name,+ pane_workspace or "front",+ exc,+ )await ws.send_json({"t": "error", "message": str(exc)})await ws.close(code=4404, reason="attach failed")returndiff --git a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.tsnew file mode 100644index 0000000000..6c1d466bfa--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.test.ts@@ -0,0 +1,214 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { openPaneSocket } from "./paneSocket";++/** Minimal WebSocket stand-in, mirroring the one in __tests__/ws.test.ts. */+class MockWebSocket {+ static OPEN = 1;+ static CLOSED = 3;+ static last: MockWebSocket | null = null;+ static opened: MockWebSocket[] = [];++ readyState = MockWebSocket.OPEN;+ url: string;+ private listeners: Record<string, Array<(ev: unknown) => void>> = {};++ constructor(url: string) {+ this.url = url;+ MockWebSocket.last = this;+ MockWebSocket.opened.push(this);+ }++ addEventListener(type: string, fn: (ev: never) => void) {+ (this.listeners[type] ??= []).push(fn as (ev: unknown) => void);+ }++ send = vi.fn();++ close = vi.fn(() => {+ this.readyState = MockWebSocket.CLOSED;+ });++ fire(type: string, ev: unknown = {}) {+ (this.listeners[type] ?? []).forEach((fn) => fn(ev));+ }++ /** Server frame, as the pane protocol sends it. */+ deliver(payload: unknown) {+ this.fire("message", { data: JSON.stringify(payload) });+ }++ /** Close from the server side, with a code. */+ dropped(code: number) {+ this.readyState = MockWebSocket.CLOSED;+ this.fire("close", { code });+ }+}++function handlers() {+ return {+ onOpen: vi.fn(),+ onOutput: vi.fn(),+ onReady: vi.fn(),+ onExit: vi.fn(),+ onTrouble: vi.fn(),+ };+}++describe("openPaneSocket", () => {+ const originalWs = globalThis.WebSocket;+ const originalFetch = globalThis.fetch;++ beforeEach(() => {+ (globalThis as unknown as { WebSocket: unknown }).WebSocket = MockWebSocket;+ (globalThis as unknown as { window: unknown }).window = globalThis;+ (window as unknown as { location: unknown }).location = {+ protocol: "http:",+ host: "localhost:5173",+ };+ MockWebSocket.last = null;+ MockWebSocket.opened = [];+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ (globalThis as unknown as { WebSocket: unknown }).WebSocket = originalWs;+ (globalThis as unknown as { fetch: unknown }).fetch = originalFetch;+ });++ it("addresses the pane by size and by the workspace holding it", () => {+ const socket = openPaneSocket(+ { name: "Mika", cols: 120, rows: 40, workspaceId: "ide_abc" },+ handlers(),+ );+ // The workspace id is not decoration: the front workspace can change while+ // this socket is alive, and the server resolves a pane without one against+ // whichever is showing — which is a different folder's pane.+ expect(MockWebSocket.last!.url).toBe(+ "ws://localhost:5173/api/agentic-ide/pty/Mika?cols=120&rows=40&workspace=ide_abc",+ );+ socket.close();+ });++ it("mints a one-time ticket and retries a rejected handshake (BUG-065)", async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ ticket: "one-time-abc", expires_in: 60 }),+ });+ (globalThis as unknown as { fetch: unknown }).fetch = fetchMock;+ const cb = handlers();+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);+ const first = MockWebSocket.last;++ first!.dropped(4401);+ await vi.advanceTimersByTimeAsync(500);++ expect(fetchMock).toHaveBeenCalledWith(+ "/api/ui/ws-ticket",+ expect.objectContaining({ method: "POST", credentials: "same-origin" }),+ );+ expect(MockWebSocket.last).not.toBe(first);+ expect(MockWebSocket.last!.url).toContain("ticket=one-time-abc");+ // A retry is under way, so the pane is not dead — saying so would put a+ // red "error" on a terminal that is about to work.+ expect(cb.onTrouble).toHaveBeenLastCalledWith(expect.any(String), true);+ socket.close();+ });++ it("gives up when the pane is no longer part of the open workspace", async () => {+ const cb = handlers();+ const socket = openPaneSocket({ name: "Ghost", cols: 80, rows: 24 }, cb);+ const first = MockWebSocket.last;++ // 4404 is the server saying the pane does not exist here. Retrying cannot+ // change that answer, so the pane reports honestly and stops.+ first!.dropped(4404);+ await vi.advanceTimersByTimeAsync(10_000);++ expect(MockWebSocket.opened).toHaveLength(1);+ expect(cb.onTrouble).toHaveBeenLastCalledWith(expect.any(String), false);+ socket.close();+ });++ it("re-joins a running agent after the connection drops", async () => {+ const cb = handlers();+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);+ MockWebSocket.last!.fire("open");+ MockWebSocket.last!.deliver({ t: "ready", resumed: false, reattached: false });+ expect(cb.onReady).toHaveBeenCalledTimes(1);++ // The agent outlives its viewer by design — the server keeps the PTY and+ // replays the screen to the next one. A dropped socket therefore means+ // "reconnect", not "the agent died".+ MockWebSocket.last!.dropped(1006);+ await vi.advanceTimersByTimeAsync(500);++ expect(MockWebSocket.opened).toHaveLength(2);+ expect(cb.onExit).not.toHaveBeenCalled();+ socket.close();+ });++ it("stops retrying once the attempt budget is spent", async () => {+ const cb = handlers();+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);++ for (let i = 0; i < 12; i += 1) {+ MockWebSocket.last!.dropped(1006);+ await vi.advanceTimersByTimeAsync(20_000);+ }++ // Bounded: a backend that is genuinely gone must not be hammered forever,+ // and the pane must end up saying so rather than spinning silently.+ expect(cb.onTrouble).toHaveBeenLastCalledWith(expect.any(String), false);+ const attempts = MockWebSocket.opened.length;+ MockWebSocket.last!.dropped(1006);+ await vi.advanceTimersByTimeAsync(20_000);+ expect(MockWebSocket.opened).toHaveLength(attempts);+ socket.close();+ });++ it("treats an agent exit as final, not as a dropped connection", async () => {+ const cb = handlers();+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);+ MockWebSocket.last!.fire("open");+ MockWebSocket.last!.deliver({ t: "ready", resumed: true, reattached: false });+ MockWebSocket.last!.deliver({ t: "exit", code: 0 });++ MockWebSocket.last!.dropped(1000);+ await vi.advanceTimersByTimeAsync(20_000);++ expect(cb.onExit).toHaveBeenCalledWith(0);+ expect(MockWebSocket.opened).toHaveLength(1);+ socket.close();+ });++ it("does not reconnect after the pane closes its socket", async () => {+ const cb = handlers();+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);+ socket.close();++ MockWebSocket.last!.dropped(1006);+ await vi.advanceTimersByTimeAsync(20_000);++ expect(MockWebSocket.opened).toHaveLength(1);+ expect(cb.onTrouble).not.toHaveBeenCalled();+ });++ it("passes output through and only sends while the socket is open", () => {+ const cb = handlers();+ const socket = openPaneSocket({ name: "Mika", cols: 80, rows: 24 }, cb);+ MockWebSocket.last!.fire("open");+ MockWebSocket.last!.deliver({ t: "o", d: "hello" });+ expect(cb.onOutput).toHaveBeenCalledWith("hello");++ socket.send({ t: "i", d: "ls\r" });+ expect(MockWebSocket.last!.send).toHaveBeenCalledWith(+ JSON.stringify({ t: "i", d: "ls\r" }),+ );++ MockWebSocket.last!.readyState = MockWebSocket.CLOSED;+ socket.send({ t: "i", d: "ignored" });+ expect(MockWebSocket.last!.send).toHaveBeenCalledTimes(1);+ socket.close();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.tsnew file mode 100644index 0000000000..88e103876b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/paneSocket.ts@@ -0,0 +1,261 @@+/**+ * The socket that carries one Agentic-IDE pane: keystrokes out, the agent's+ * screen back.+ *+ * It exists as its own module because a pane's connection is the one place+ * where "the agent is broken" and "the wire is broken" get confused. The+ * server keeps a pane's agent running across viewers on purpose — a socket+ * that goes away means the VIEWER left, never that the work stopped, and the+ * next socket is handed the replay buffer that redraws the screen. A pane that+ * connected once and then gave up therefore reports a dead terminal while the+ * agent behind it is alive and still working.+ *+ * Two failure modes are handled here rather than in the component:+ *+ * - **A rejected handshake (4401).** WebKit engines (WKWebView on macOS,+ * WebKitGTK on Linux) do not attach the HttpOnly session cookie to a+ * WebSocket handshake — BUG-065 — so a perfectly healthy session is turned+ * away. Every other socket in the app already answers this by proving the+ * session over plain HTTP and reconnecting with a one-time ticket; a pane+ * that skipped it simply could not open a terminal on those platforms.+ * - **A dropped connection.** A backend restart, a reload, a moment of+ * unreachability. One failed attempt used to be final, which is why a+ * whole grid of panes could go red at once and stay that way.+ *+ * Both are bounded: a pane never hammers a backend that is genuinely gone, and+ * whatever it ends up believing, it says out loud.+ */++import { mintWsTicket } from "@/lib/ws";++/** Server close code: the handshake credential was missing or invalid. */+const CLOSE_UNAUTHORIZED = 4401;+/** Server close code: no such pane in the addressed workspace. */+const CLOSE_NO_SUCH_PANE = 4404;++const MIN_BACKOFF = 500;+const MAX_BACKOFF = 8_000;++/**+ * Consecutive failed attempts before a pane declares itself unreachable.+ * Eight covers the ~20 s a backend restart takes to answer again, and stops+ * well short of retrying at a dead server for the rest of the session.+ */+const MAX_ATTEMPTS = 8;++/**+ * Consecutive 4401s that still count as a transient authorization hiccup.+ * Beyond this, fresh tickets are evidently not unlocking the socket and the+ * ordinary backoff takes over instead of minting on a 500 ms loop forever.+ */+const MAX_TICKET_RETRIES = 3;++export interface PaneSocketOptions {+ /** Call-sign of the pane, as the server knows it. */+ name: string;+ cols: number;+ rows: number;+ /**+ * The workspace this pane belongs to. Several can be open and the front one+ * changes while sockets are alive: without it the server resolves the pane+ * against whichever workspace happens to be showing, which is a pane in a+ * different folder.+ */+ workspaceId?: string | null;+}++export interface PaneSocketHandlers {+ /** The socket is up; the pane may send its measured size. */+ onOpen?: () => void;+ onOutput: (text: string) => void;+ /** The agent is attached — freshly started, resumed, or re-joined. */+ onReady: (info: { resumed: boolean; reattached: boolean }) => void;+ /** The agent itself finished. Final: nothing reconnects after this. */+ onExit: (code: number) => void;+ /**+ * The pane could not be reached. ``retrying`` is true while another attempt+ * is already scheduled — the pane is not dead yet, and painting it red would+ * be wrong.+ */+ onTrouble: (message: string, retrying: boolean) => void;+}++export interface PaneSocket {+ send(payload: unknown): void;+ close(): void;+}++function paneUrl(opts: PaneSocketOptions, ticket: string | null): string {+ const proto = window.location.protocol === "https:" ? "wss" : "ws";+ const query = new URLSearchParams({+ cols: String(opts.cols),+ rows: String(opts.rows),+ });+ if (opts.workspaceId) query.set("workspace", opts.workspaceId);+ if (ticket) query.set("ticket", ticket);+ return `${proto}://${window.location.host}/api/agentic-ide/pty/${encodeURIComponent(+ opts.name,+ )}?${query.toString()}`;+}++export function openPaneSocket(+ opts: PaneSocketOptions,+ handlers: PaneSocketHandlers,+): PaneSocket {+ let ws: WebSocket | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;+ /** Set once nothing further should happen on this pane, for any reason. */+ let stopped = false;+ /** The agent reported its own exit — a later close is not a lost wire. */+ let agentExited = false;+ let attempts = 0;+ let ticketRetries = 0;+ let pendingTicket: string | null = null;++ const schedule = (delay: number) => {+ if (timer !== null || stopped) return;+ timer = setTimeout(() => {+ timer = null;+ if (!stopped) open();+ }, delay);+ };++ const giveUp = (message: string) => {+ stopped = true;+ handlers.onTrouble(message, false);+ };++ const retryLater = (message: string) => {+ attempts += 1;+ if (attempts > MAX_ATTEMPTS) {+ giveUp(message);+ return;+ }+ handlers.onTrouble(message, true);+ schedule(Math.min(MAX_BACKOFF, MIN_BACKOFF * 2 ** (attempts - 1)));+ };++ const authRetry = async (): Promise<void> => {+ ticketRetries += 1;+ // The cookie IS sent on plain HTTP, so this proves the session even on the+ // engines that withhold it from the handshake.+ const ticket = await mintWsTicket();+ if (stopped) return;+ if (ticket) pendingTicket = ticket;+ if (ticket !== null && ticketRetries <= MAX_TICKET_RETRIES) {+ handlers.onTrouble("Authorizing the terminal…", true);+ // Fixed short delay: the very next attempt carries a fresh credential,+ // so escalating the backoff would only postpone a working terminal.+ schedule(MIN_BACKOFF);+ return;+ }+ retryLater("Terminal authorization failed — retrying.");+ };++ const handleDrop = (code: number) => {+ if (code === CLOSE_NO_SUCH_PANE) {+ // The server is not saying "not right now", it is saying "not here".+ // No number of retries turns that into a terminal.+ giveUp("This terminal is no longer part of the open workspace.");+ return;+ }+ if (code === CLOSE_UNAUTHORIZED) {+ void authRetry();+ return;+ }+ retryLater(+ attempts === 0 && ws === null+ ? "Could not reach the terminal — retrying."+ : `Terminal connection lost (code ${code || "?"}) — reconnecting.`,+ );+ };++ function open(): void {+ const ticket = pendingTicket;+ pendingTicket = null;+ let socket: WebSocket;+ try {+ socket = new WebSocket(paneUrl(opts, ticket));+ } catch {+ retryLater("Could not reach the terminal — retrying.");+ return;+ }+ ws = socket;+ // One verdict per attempt: a socket that both errors and closes must not+ // be counted twice, or the attempt budget burns down at double speed.+ let settled = false;++ socket.addEventListener("open", () => {+ attempts = 0;+ handlers.onOpen?.();+ });++ socket.addEventListener("message", (ev) => {+ let msg: { t?: string; d?: string; code?: number; message?: string; resumed?: boolean; reattached?: boolean };+ try {+ msg = JSON.parse((ev as MessageEvent).data as string);+ } catch {+ return;+ }+ if (msg.t === "o") {+ handlers.onOutput(msg.d ?? "");+ } else if (msg.t === "ready") {+ // A live handshake also clears the auth streak: whatever credential+ // this attempt used, it worked.+ ticketRetries = 0;+ attempts = 0;+ handlers.onReady({+ resumed: Boolean(msg.resumed),+ reattached: Boolean(msg.reattached),+ });+ } else if (msg.t === "exit") {+ agentExited = true;+ handlers.onExit(msg.code ?? 0);+ } else if (msg.t === "error") {+ // The server refused the attach and is about to close; the close code+ // decides whether that is worth another attempt.+ handlers.onTrouble(msg.message ?? "The terminal could not be started.", true);+ }+ });++ socket.addEventListener("close", (ev) => {+ if (settled) return;+ settled = true;+ if (stopped || agentExited) return;+ handleDrop((ev as CloseEvent).code);+ });++ socket.addEventListener("error", () => {+ // The spec guarantees a close after an error; closing explicitly keeps+ // the two paths from diverging on engines that are less strict.+ try {+ socket.close();+ } catch {+ /* already gone */+ }+ });+ }++ open();++ return {+ send(payload: unknown): void {+ if (ws && ws.readyState === WebSocket.OPEN) {+ ws.send(typeof payload === "string" ? payload : JSON.stringify(payload));+ }+ },+ close(): void {+ stopped = true;+ if (timer !== null) {+ clearTimeout(timer);+ timer = null;+ }+ try {+ ws?.close();+ } catch {+ /* already gone */+ }+ ws = null;+ },+ };+}diff --git a/tests/unit/web/test_agentic_ide_pty_socket.py b/tests/unit/web/test_agentic_ide_pty_socket.pynew file mode 100644index 0000000000..338c7c8275--- /dev/null+++ b/tests/unit/web/test_agentic_ide_pty_socket.py@@ -0,0 +1,112 @@+"""The pane socket must never fail silently.++A terminal that will not start shows up in the UI as a red badge whose reason+lives in a tooltip. When a whole grid of panes fails at once — a restart caught+mid-flight, a handshake the engine would not authorize — nobody is hovering,+and until these lines existed the backend wrote nothing at all: no log entry+for a refused socket, none for a refused attach. The incident could then only+be reconstructed by *absence* (a session started, no PTY ever spawned).++So the contract pinned here is diagnostic, not cosmetic: every socket that is+turned away leaves a record naming the pane and the reason.+"""+from __future__ import annotations++import logging+from pathlib import Path+from typing import Any++import pytest++from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.session import Registry+from jarvis.ui.web import agentic_ide_routes as routes+from tests.fakes.fake_pty_manager import FakePtyManager++[email protected](autouse=True)+def _isolated_stores(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep the resume snapshot and recents out of the developer's own profile."""+ from jarvis.agentic_ide import recents, resume_store++ store = tmp_path / "store"+ store.mkdir()+ monkeypatch.setattr(resume_store, "_store_path", lambda: store / "last.json")+ monkeypatch.setattr(recents, "remember", lambda *a, **k: None)++[email protected](autouse=True)+def _agents_installed(monkeypatch: pytest.MonkeyPatch) -> None:+ """Both coding CLIs count as on PATH — never ask what this machine has (AP-23)."""+ monkeypatch.setattr(session_mod, "agent_argv", lambda agent: ("/usr/bin/" + agent,))+++class FakeWebSocket:+ """Enough of a Starlette WebSocket for the pane endpoint."""++ def __init__(self, **query: str) -> None:+ self.scope: dict[str, Any] = {"type": "websocket"}+ self.query_params = dict(query)+ self.accepted = False+ self.sent: list[dict[str, Any]] = []+ self.closed: tuple[int, str] | None = None++ async def accept(self) -> None:+ self.accepted = True++ async def send_json(self, payload: dict[str, Any]) -> None:+ self.sent.append(payload)++ async def close(self, code: int = 1000, reason: str = "") -> None:+ self.closed = (code, reason)+++def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:+ instance = Registry(pty_manager=FakePtyManager())+ monkeypatch.setattr(routes, "get_registry", lambda: instance)+ return instance+++async def test_refused_handshake_is_recorded_not_only_closed(+ registry: Registry,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ """An unauthorized socket names the pane in the log.++ This is the WebKit case (BUG-065): the engine withholds the session cookie+ from the handshake, so a healthy session is turned away. The client retries+ with a one-time ticket — but if that ever stops working, the only evidence+ that a pane was refused rather than broken is this line.+ """+ monkeypatch.setattr(routes, "credentials_valid", lambda scope: False)+ ws = FakeWebSocket(cols="80", rows="24")++ with caplog.at_level(logging.WARNING, logger=routes.__name__):+ await routes.agentic_pty(ws, "Mika")++ assert ws.closed == (4401, "unauthorized")+ assert any("Mika" in record.getMessage() for record in caplog.records)+++async def test_failed_attach_is_recorded_with_pane_and_reason(+ registry: Registry,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ """A refused attach says which pane and why — in the log, not only on screen."""+ monkeypatch.setattr(routes, "credentials_valid", lambda scope: True)+ ws = FakeWebSocket(cols="80", rows="24")++ # No workspace is open, which is exactly what a pane reconnecting across a+ # backend restart runs into.+ with caplog.at_level(logging.WARNING, logger=routes.__name__):+ await routes.agentic_pty(ws, "Mika")++ assert ws.closed == (4404, "attach failed")+ assert ws.sent and ws.sent[0]["t"] == "error"+ logged = " ".join(record.getMessage() for record in caplog.records)+ assert "Mika" in logged+ # The reason itself, not just the fact that something failed.+ assert "session" in logged.lower()