diff --git a/controlplane/src/index.ts b/controlplane/src/index.ts index 6f1cc471..e041e6c0 100644 --- a/controlplane/src/index.ts +++ b/controlplane/src/index.ts @@ -1,7 +1,7 @@ // Copyright 2026 Rob Macrae. All rights reserved. // SPDX-License-Identifier: LicenseRef-Proprietary -// REVISION: controlplane-v30-background-processes -console.log(`[controlplane] REVISION: controlplane-v30-background-processes loaded at ${new Date().toISOString()}`); +// REVISION: controlplane-v31-session-liveness +console.log(`[controlplane] REVISION: controlplane-v31-session-liveness loaded at ${new Date().toISOString()}`); /** * OrcaBot Control Plane - Cloudflare Worker Entry Point @@ -25,6 +25,7 @@ import * as dashboards from './dashboards/handler'; import * as sessions from './sessions/handler'; import { nearestFlyRegion } from './sessions/handler'; import * as backgroundProcesses from './sessions/background-processes'; +import { getSessionLiveness } from './sessions/liveness'; import * as recipes from './recipes/handler'; import * as schedules from './schedules/handler'; import * as subagents from './subagents/handler'; @@ -3124,6 +3125,14 @@ async function handleRequest(request: Request, env: EnvWithBindings, ctx: Pick { + let ctx: TestContext; + const owner = createTestUser({ id: 'user-1' }); + const viewer = createTestUser({ id: 'user-2', email: 'viewer@example.com' }); + const stranger = createTestUser({ id: 'user-3', email: 'stranger@example.com' }); + const mockSandbox = createMockSandboxServer(); + let ptysReply: () => Response; + let asked: string[]; + + beforeAll(() => mockSandbox.server.listen({ onUnhandledRequest: 'error' })); + afterEach(() => { mockSandbox.reset(); mockSandbox.server.resetHandlers(); }); + afterAll(() => mockSandbox.server.close()); + + async function setup(opts: { status?: string; rowSandbox?: string; currentSandbox?: string } = {}) { + const dashboard = await seedDashboard(ctx.db, owner.id); + await ctx.db.prepare(`INSERT INTO dashboard_members (dashboard_id, user_id, role, added_at) VALUES (?, ?, 'viewer', ?)`) + .bind(dashboard.id, viewer.id, new Date().toISOString()).run(); + const item = await seedDashboardItem(ctx.db, dashboard.id, { type: 'terminal' }); + await seedSession(ctx.db, dashboard.id, item.id, { + id: 's-1', sandboxSessionId: opts.rowSandbox ?? 'sbx-1', ownerUserId: owner.id, status: opts.status ?? 'active', + }); + await ctx.db.prepare(`UPDATE sessions SET pty_id = 'pty-1' WHERE id = 's-1'`).run(); + await ctx.db.prepare(` + INSERT INTO dashboard_sandboxes (dashboard_id, sandbox_session_id, sandbox_machine_id, applied_secret_names, created_at) + VALUES (?, ?, '', '[]', ?) + `).bind(dashboard.id, opts.currentSandbox ?? 'sbx-1', new Date().toISOString()).run(); + } + + async function check(userId = owner.id) { + const res = await getSessionLiveness(ctx.env, 's-1', userId); + return { status: res.status, body: await res.json() as { alive: boolean | null; reason: string; revision: string } }; + } + + beforeEach(async () => { + ctx = await createTestContext(); + for (const u of [owner, viewer, stranger]) await seedUser(ctx.db, u); + asked = []; + ptysReply = () => HttpResponse.json({ ptys: [{ id: 'pty-other' }, { id: 'pty-1' }] }); + mockSandbox.server.use( + http.get(`${ctx.env.SANDBOX_URL}/sessions/:id/ptys`, ({ params }) => { + asked.push(String(params.id)); + return ptysReply(); + }), + ); + }); + + it('alive when the sandbox still lists the PTY', async () => { + await setup(); + const { status, body } = await check(); + expect(status).toBe(200); + expect(body.alive).toBe(true); + expect(body.revision).toBe('session-liveness-v1-before-restart'); + expect(asked).toEqual(['sbx-1']); + }); + + it('any member may ask; others get 404', async () => { + await setup(); + expect((await check(viewer.id)).body.alive).toBe(true); + expect((await check(stranger.id)).status).toBe(404); + }); + + it('not alive once the PTY has exited', async () => { + await setup(); + ptysReply = () => HttpResponse.json({ ptys: [{ id: 'pty-other' }] }); + expect((await check()).body).toMatchObject({ alive: false, reason: 'pty exited' }); + }); + + it('not alive when the sandbox lost the session', async () => { + await setup(); + ptysReply = () => new HttpResponse('no such session', { status: 404 }); + expect((await check()).body).toMatchObject({ alive: false, reason: 'sandbox session gone' }); + }); + + it('not alive when the dashboard has moved to another sandbox session, without asking the old one', async () => { + await setup({ rowSandbox: 'sbx-old', currentSandbox: 'sbx-new' }); + expect((await check()).body).toMatchObject({ alive: false, reason: 'sandbox session replaced' }); + expect(asked).toEqual([]); + }); + + it('not alive when the session was stopped', async () => { + await setup({ status: 'stopped' }); + expect((await check()).body.alive).toBe(false); + expect(asked).toEqual([]); + }); + + it("unknown (null), never false, when the sandbox can't answer", async () => { + await setup(); + ptysReply = () => new HttpResponse('boom', { status: 500 }); + expect((await check()).body.alive).toBeNull(); + ptysReply = () => HttpResponse.error(); + expect((await check()).body.alive).toBeNull(); + }); +}); diff --git a/controlplane/src/sessions/liveness.ts b/controlplane/src/sessions/liveness.ts new file mode 100644 index 00000000..5a82f467 --- /dev/null +++ b/controlplane/src/sessions/liveness.ts @@ -0,0 +1,84 @@ +// Copyright 2026 Rob Macrae. All rights reserved. +// SPDX-License-Identifier: LicenseRef-Proprietary + +// REVISION: session-liveness-v1-before-restart +export const sessionLivenessRevision = "session-liveness-v1-before-restart"; +console.log(`[session-liveness] REVISION: ${sessionLivenessRevision} loaded at ${new Date().toISOString()}`); + +/** + * Is a terminal's process still running on the sandbox? + * + * The dashboard page used to replace a terminal whenever its WebSocket gave up (10 + * failed reconnects) or a reconnect showed no output for 8s. A backgrounded browser tab + * (Safari suspends its sockets and timers) trips both while the terminal is fine, and + * replacing it kills the running process: on 2026-11-24 a PokerBench game's engine + * terminal was restarted four times and three agent terminals once each, all healthy. + * Now the page asks here first and only replaces a terminal whose process is gone; + * a live one it just reconnects to. + * + * GET /sessions/:id/alive → { alive: true | false | null, reason, revision } + * + * The sandbox drops a PTY from its session's list when the process exits (the hub's + * onStop), so "listed" means running. null = couldn't tell (sandbox unreachable or + * erroring): the caller must not destroy anything on null. + */ + +import type { Env } from '../types'; +import { sandboxFetch } from '../sandbox/fetch'; + +type Liveness = { alive: boolean | null; reason: string }; + +function reply(l: Liveness): Response { + return Response.json({ ...l, revision: sessionLivenessRevision }); +} + +export async function getSessionLiveness(env: Env, sessionId: string, userId: string): Promise { + const session = await env.DB.prepare( + `SELECT dashboard_id, pty_id, status, sandbox_session_id, sandbox_machine_id FROM sessions WHERE id = ?`, + ).bind(sessionId).first<{ + dashboard_id: string; pty_id: string; status: string; sandbox_session_id: string; sandbox_machine_id: string; + }>(); + // Anyone who can see the dashboard may ask; it reveals nothing but running or not. + const member = session && await env.DB.prepare( + `SELECT role FROM dashboard_members WHERE dashboard_id = ? AND user_id = ?`, + ).bind(session.dashboard_id, userId).first<{ role: string }>(); + if (!session || !member) { + return Response.json({ error: 'E79205: Session not found or no access' }, { status: 404 }); + } + if (session.status === 'stopped' || session.status === 'error') return reply({ alive: false, reason: `session ${session.status}` }); + if (!session.pty_id) return reply({ alive: false, reason: 'no pty' }); + + // The dashboard's current VM session. If the dashboard has moved on (VM replaced or its + // session recreated), this terminal's PTY went with the old one. + const sandbox = await env.DB.prepare( + `SELECT sandbox_session_id, sandbox_machine_id FROM dashboard_sandboxes WHERE dashboard_id = ?`, + ).bind(session.dashboard_id).first<{ sandbox_session_id: string; sandbox_machine_id: string | null }>(); + if (!sandbox?.sandbox_session_id) return reply({ alive: false, reason: 'no sandbox' }); + if (sandbox.sandbox_session_id !== session.sandbox_session_id) return reply({ alive: false, reason: 'sandbox session replaced' }); + const machineId = sandbox.sandbox_machine_id || ''; + if (machineId && session.sandbox_machine_id && machineId !== session.sandbox_machine_id) { + return reply({ alive: false, reason: 'machine replaced' }); + } + + let res: Response; + try { + res = await sandboxFetch(env, `/sessions/${session.sandbox_session_id}/ptys`, { + machineId: machineId || undefined, + timeoutMs: 5_000, + retries: 0, + }); + } catch (e) { + console.warn(`[session-liveness] E79206: sandbox unreachable for session ${sessionId}:`, e); + return reply({ alive: null, reason: 'sandbox unreachable' }); + } + if (res.status === 404) return reply({ alive: false, reason: 'sandbox session gone' }); + if (!res.ok) return reply({ alive: null, reason: `sandbox ${res.status}` }); + let body: { ptys?: Array<{ id?: string }> }; + try { + body = await res.json(); + } catch { + return reply({ alive: null, reason: 'bad sandbox reply' }); + } + const alive = (body.ptys || []).some((p) => p.id === session.pty_id); + return reply({ alive, reason: alive ? 'running' : 'pty exited' }); +} diff --git a/frontend/src/components/blocks/TerminalBlock.test.tsx b/frontend/src/components/blocks/TerminalBlock.test.tsx index 4b6cb43f..c95cd5e4 100644 --- a/frontend/src/components/blocks/TerminalBlock.test.tsx +++ b/frontend/src/components/blocks/TerminalBlock.test.tsx @@ -1,6 +1,7 @@ +// REVISION: terminal-block-tests-v2-liveness-before-restart import * as React from "react"; -import { describe, it, expect, beforeEach, vi } from "vitest"; -import { render, screen } from "@testing-library/react"; +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { render, screen, waitFor, act, cleanup } from "@testing-library/react"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactFlowProvider } from "@xyflow/react"; import { TerminalBlock } from "./TerminalBlock"; @@ -29,13 +30,30 @@ vi.mock("@/components/terminal", async () => { }; }); +const livenessMock = vi.fn(); +vi.mock("@/lib/api/cloudflare/session-liveness", () => ({ + getSessionLiveness: (...args: unknown[]) => livenessMock(...args), +})); + +const stopSessionMock = vi.fn(); +const createSessionMock = vi.fn(); +vi.mock("@/lib/api/cloudflare", async () => { + const actual = await vi.importActual("@/lib/api/cloudflare"); + return { + ...actual, + stopSession: (...args: unknown[]) => stopSessionMock(...args), + createSession: (...args: unknown[]) => createSessionMock(...args), + applySessionSecrets: vi.fn(async () => undefined), + }; +}); + vi.mock("./BlockWrapper", () => ({ BlockWrapper: ({ children }: { children: React.ReactNode }) => (
{children}
), })); -function renderTerminal(sessionOwnerId: string, viewerId: string) { +function renderTerminal(sessionOwnerId: string, viewerId: string, connectionState = "connected", reconnect = vi.fn()) { const queryClient = new QueryClient(); useAuthStore.setState({ user: { @@ -50,7 +68,7 @@ function renderTerminal(sessionOwnerId: string, viewerId: string) { useTerminalMock.mockReturnValue([ { - connectionState: "connected", + connectionState, turnTaking: { controller: sessionOwnerId, controllerName: "Owner", @@ -71,7 +89,7 @@ function renderTerminal(sessionOwnerId: string, viewerId: string) { requestControl: vi.fn(), grantControl: vi.fn(), revokeControl: vi.fn(), - reconnect: vi.fn(), + reconnect, }, ]); @@ -121,6 +139,7 @@ describe("TerminalBlock owner controls", () => { beforeEach(() => { useTerminalMock.mockReset(); }); + afterEach(() => cleanup()); it("does not show view-only messaging for the owner", () => { renderTerminal("owner-1", "owner-1"); @@ -132,3 +151,59 @@ describe("TerminalBlock owner controls", () => { expect(screen.getAllByText("View-only session").length).toBeGreaterThan(0); }); }); + +// A dropped connection isn't a dead terminal: the page asks the sandbox before replacing +// it (2026-11-24: a backgrounded Safari tab restarted healthy PokerBench terminals). +describe("TerminalBlock recovery after a lost connection", () => { + let hidden = false; + beforeEach(() => { + useTerminalMock.mockReset(); + livenessMock.mockReset(); + stopSessionMock.mockReset(); + createSessionMock.mockReset(); + createSessionMock.mockReturnValue(new Promise(() => {})); + hidden = false; + vi.spyOn(document, "visibilityState", "get").mockImplementation(() => (hidden ? "hidden" : "visible")); + }); + afterEach(() => { cleanup(); vi.restoreAllMocks(); }); + + it("reconnects to a terminal that is still running, without restarting it", async () => { + livenessMock.mockResolvedValue(true); + const reconnect = vi.fn(); + renderTerminal("owner-1", "owner-1", "failed", reconnect); + await waitFor(() => expect(reconnect).toHaveBeenCalledTimes(1), { timeout: 5000 }); + expect(livenessMock).toHaveBeenCalledWith("session-1"); + expect(stopSessionMock).not.toHaveBeenCalled(); + expect(createSessionMock).not.toHaveBeenCalled(); + }); + + it("starts a fresh session when the terminal's process is gone", async () => { + livenessMock.mockResolvedValue(false); + const reconnect = vi.fn(); + renderTerminal("owner-1", "owner-1", "failed", reconnect); + await waitFor(() => expect(stopSessionMock).toHaveBeenCalledWith("session-1"), { timeout: 5000 }); + await waitFor(() => expect(createSessionMock).toHaveBeenCalled()); + expect(reconnect).not.toHaveBeenCalled(); + }); + + it("never restarts when it can't tell", async () => { + livenessMock.mockResolvedValue(null); + const reconnect = vi.fn(); + renderTerminal("owner-1", "owner-1", "failed", reconnect); + await waitFor(() => expect(reconnect).toHaveBeenCalledTimes(1), { timeout: 5000 }); + expect(stopSessionMock).not.toHaveBeenCalled(); + }); + + it("decides nothing while the tab is hidden", async () => { + hidden = true; + livenessMock.mockResolvedValue(true); + const reconnect = vi.fn(); + renderTerminal("owner-1", "owner-1", "failed", reconnect); + await act(async () => { await new Promise((r) => setTimeout(r, 50)); }); + expect(livenessMock).not.toHaveBeenCalled(); + hidden = false; + act(() => { document.dispatchEvent(new Event("visibilitychange")); }); + await waitFor(() => expect(reconnect).toHaveBeenCalledTimes(1), { timeout: 5000 }); + expect(stopSessionMock).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/components/blocks/TerminalBlock.tsx b/frontend/src/components/blocks/TerminalBlock.tsx index 3c8823fd..1c672d84 100644 --- a/frontend/src/components/blocks/TerminalBlock.tsx +++ b/frontend/src/components/blocks/TerminalBlock.tsx @@ -3,8 +3,8 @@ "use client"; -// REVISION: terminal-block-v17-antigravity -const TERMINAL_BLOCK_REVISION = "terminal-block-v17-antigravity"; +// REVISION: terminal-block-v18-liveness-before-restart +const TERMINAL_BLOCK_REVISION = "terminal-block-v18-liveness-before-restart"; console.log(`[TerminalBlock] REVISION: ${TERMINAL_BLOCK_REVISION} loaded at ${new Date().toISOString()}`); @@ -49,6 +49,7 @@ import { import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { toast } from "sonner"; import { listBackgroundProcesses, stopBackgroundProcesses, type BackgroundProcess } from "@/lib/api/cloudflare/background-processes"; +import { getSessionLiveness } from "@/lib/api/cloudflare/session-liveness"; import { RestartBackgroundDialog } from "./RestartBackgroundDialog"; import { cn } from "@/lib/utils"; import { trackEvent } from "@/lib/analytics"; @@ -2492,6 +2493,45 @@ export function TerminalBlock({ } }, [data.dashboardId, isReady, session, actualItemId, stopSession, markSessionStopped, upsertDashboardSession]); + // A dropped connection isn't a dead terminal. A backgrounded tab (Safari suspends its + // sockets and timers) loses its WebSocket while the terminal runs on, and replacing it + // then kills what was running (2026-11-24: a PokerBench engine terminal restarted four + // times, three agent terminals once each, all healthy). So the automatic paths ask the + // sandbox first and only replace a terminal whose process is gone; a running one they + // reconnect to. Nothing is decided while the tab is hidden. + // REVISION: terminal-block-v18-liveness-before-restart + const sessionIdRef = React.useRef(session?.id); + sessionIdRef.current = session?.id; + const terminalActionsRef = React.useRef(terminalActions); + terminalActionsRef.current = terminalActions; + const recoverTerminal = React.useCallback(async (why: string, reconnectIfAlive: boolean) => { + const sid = sessionIdRef.current; + if (!sid) return; + if (typeof document !== "undefined" && document.visibilityState === "hidden") { + console.log(`[TerminalBlock] ${why}: tab hidden, deciding when it's visible again`); + await new Promise((resolve) => { + const onVisible = () => { + if (document.visibilityState === "hidden") return; + document.removeEventListener("visibilitychange", onVisible); + resolve(); + }; + document.addEventListener("visibilitychange", onVisible); + }); + } + if (sessionIdRef.current !== sid) return; + const alive = await getSessionLiveness(sid); + if (sessionIdRef.current !== sid) return; + if (alive === false) { + console.log(`[TerminalBlock] ${why}: terminal's process is gone, starting a fresh session`); + terminalRef.current?.write("\x1b[90mReconnecting to a fresh session...\x1b[0m\r\n"); + void handleReopen(); + return; + } + // Running, or unknown (never destroy on unknown): keep the terminal. + console.log(`[TerminalBlock] ${why}: terminal ${alive ? "still running" : "status unknown"}, ${reconnectIfAlive ? "reconnecting" : "leaving it"} (not restarting)`); + if (reconnectIfAlive) terminalActionsRef.current.reconnect(); + }, [handleReopen]); + // A restart the user asked for (menu, "restart to apply", Reopen): first ask about // background processes the terminal started that a restart won't stop (daemons, // servers), if there are any. Automatic restarts (crash loop, watchdog) call @@ -2580,10 +2620,12 @@ export function TerminalBlock({ const autoReopenAttemptedRef = React.useRef(false); React.useEffect(() => { - if (isConnected) { + // Any new (re)connect attempt re-arms recovery, so a reconnect to a running terminal + // that fails again is checked again (not only after a successful connect). + if (isConnected || connectionState === "connecting" || connectionState === "reconnecting") { autoReopenAttemptedRef.current = false; } - }, [isConnected, session?.id]); + }, [isConnected, connectionState, session?.id]); // Fast-fail loop guard: if a freshly-restarted session dies again within a few // seconds (e.g. a boot command that exits immediately — bad flag, missing @@ -2632,8 +2674,14 @@ export function TerminalBlock({ } console.log(`[TerminalBlock] Auto-restart: isFailed=${isFailed} isDisconnected=${isDisconnected} ptyClosed=${ptyClosed} sessionExpired=${sessionExpired} sessionStatus=${session.status}`); - terminalRef.current?.write("\x1b[90mReconnecting to a fresh session...\x1b[0m\r\n"); - void handleReopen(); + if (ptyClosed || sessionExpired) { + // The sandbox said so: the process exited, or the sandbox lost the session. + terminalRef.current?.write("\x1b[90mReconnecting to a fresh session...\x1b[0m\r\n"); + void handleReopen(); + return; + } + // Only the connection was lost: replace the terminal only if its process is gone. + void recoverTerminal("connection lost", true); }, [ session, isOwner, @@ -2643,10 +2691,13 @@ export function TerminalBlock({ sessionExpired, isCreatingSession, handleReopen, + recoverTerminal, ]); // Post-reconnect liveness watchdog: if no PTY output arrives within 8s - // after a WebSocket reconnection, auto-restart the session. + // after a WebSocket reconnection, check the terminal is still running (a quiet + // terminal, e.g. one waiting on a long command, prints nothing and is fine) and + // replace it only if its process is gone. // Only triggers on reconnect (reconnecting→connected), not initial connect. React.useEffect(() => { const wasReconnecting = prevConnectionStateRef.current === "reconnecting"; @@ -2674,9 +2725,8 @@ export function TerminalBlock({ reconnectWatchdogRef.current = setTimeout(() => { reconnectWatchdogRef.current = null; if (lastPtyOutputTimeRef.current < reconnectTime) { - console.log(`[TerminalBlock] Watchdog: no PTY output in 8s post-reconnect, auto-restarting`); - terminalRef.current?.write("\x1b[33mSession unresponsive after reconnect, restarting...\x1b[0m\r\n"); - void handleReopen(); + console.log(`[TerminalBlock] Watchdog: no PTY output in 8s post-reconnect, checking the terminal is running`); + void recoverTerminal("quiet after reconnect", false); } else { console.log(`[TerminalBlock] Watchdog: PTY output received, session is alive`); } @@ -2688,7 +2738,7 @@ export function TerminalBlock({ reconnectWatchdogRef.current = null; } }; - }, [connectionState, isOwner, session, handleReopen]); + }, [connectionState, isOwner, session, recoverTerminal]); React.useEffect(() => { if (!isConnected) { diff --git a/frontend/src/lib/api/cloudflare/session-liveness.ts b/frontend/src/lib/api/cloudflare/session-liveness.ts new file mode 100644 index 00000000..65c1cd4b --- /dev/null +++ b/frontend/src/lib/api/cloudflare/session-liveness.ts @@ -0,0 +1,35 @@ +// Copyright 2026 Rob Macrae. All rights reserved. +// SPDX-License-Identifier: LicenseRef-Proprietary + +// REVISION: session-liveness-api-v1-before-restart +const MODULE_REVISION = "session-liveness-api-v1-before-restart"; +console.log(`[session-liveness-api] REVISION: ${MODULE_REVISION} loaded at ${new Date().toISOString()}`); + +import { API } from "@/config/env"; +import { apiGet, ApiError } from "../client"; + +/** + * Is this terminal's process still running on the sandbox? Asked before the page + * replaces a terminal whose connection dropped: a backgrounded tab loses its socket + * while the terminal is fine, and replacing it kills what was running. + * + * true = running (reconnect to it); false = gone (replace it); null = couldn't tell + * (offline, control plane or sandbox not answering): never replace on null. Never throws. + */ +export async function getSessionLiveness(sessionId: string, timeoutMs = 8000): Promise { + console.log(`[getSessionLiveness] called at ${new Date().toISOString()} (${sessionId})`); + try { + const res = await Promise.race([ + apiGet<{ alive?: boolean | null; reason?: string }>(`${API.cloudflare.base}/sessions/${sessionId}/alive`), + new Promise((resolve) => setTimeout(() => resolve(null), timeoutMs)), + ]); + if (!res) return null; + console.log(`[getSessionLiveness] ${sessionId}: alive=${res.alive} (${res.reason ?? ""})`); + return typeof res.alive === "boolean" ? res.alive : null; + } catch (e) { + // 404: the session row is gone (deleted), so nothing of it is running. + if (e instanceof ApiError && e.status === 404) return false; + console.warn("[getSessionLiveness] couldn't tell", e); + return null; + } +}