Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions controlplane/src/index.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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';
Expand Down Expand Up @@ -3124,6 +3125,14 @@ async function handleRequest(request: Request, env: EnvWithBindings, ctx: Pick<E
}
}

// GET /sessions/:id/alive - Is the terminal's process still running? The page asks
// before replacing a terminal whose connection dropped. REVISION: controlplane-v31-session-liveness
if (segments[0] === 'sessions' && segments.length === 3 && segments[2] === 'alive' && method === 'GET') {
const authError = requireAuth(auth);
if (authError) return authError;
return getSessionLiveness(env, segments[1], auth.user!.id);
}

// WebSocket /sessions/:id/ptys/:ptyId/ws - Terminal streaming (proxied)
if (segments[0] === 'sessions' && segments.length === 5 && segments[2] === 'ptys' && segments[4] === 'ws' && method === 'GET') {
const wsOrigin = request.headers.get('Origin') || '';
Expand Down
106 changes: 106 additions & 0 deletions controlplane/src/sessions/liveness.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// REVISION: session-liveness-tests-v1
/**
* GET /sessions/:id/alive: the page asks before replacing a terminal whose connection
* dropped, and must only get `false` when the process is really gone.
*/

import { describe, it, expect, beforeEach, beforeAll, afterAll, afterEach } from 'vitest';
import { http, HttpResponse } from 'msw';
import { createTestContext, seedUser, seedDashboard, seedDashboardItem, seedSession, createTestUser } from '../../tests/helpers';
import { createMockSandboxServer } from '../../tests/mocks/sandbox';
import { getSessionLiveness } from './liveness';
import type { TestContext } from '../../tests/helpers';

describe('session liveness', () => {
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();
});
});
84 changes: 84 additions & 0 deletions controlplane/src/sessions/liveness.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
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' });
}
85 changes: 80 additions & 5 deletions frontend/src/components/blocks/TerminalBlock.test.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<typeof import("@/lib/api/cloudflare")>("@/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 }) => (
<div data-testid="block-wrapper">{children}</div>
),
}));

function renderTerminal(sessionOwnerId: string, viewerId: string) {
function renderTerminal(sessionOwnerId: string, viewerId: string, connectionState = "connected", reconnect = vi.fn()) {
const queryClient = new QueryClient();
useAuthStore.setState({
user: {
Expand All @@ -50,7 +68,7 @@ function renderTerminal(sessionOwnerId: string, viewerId: string) {

useTerminalMock.mockReturnValue([
{
connectionState: "connected",
connectionState,
turnTaking: {
controller: sessionOwnerId,
controllerName: "Owner",
Expand All @@ -71,7 +89,7 @@ function renderTerminal(sessionOwnerId: string, viewerId: string) {
requestControl: vi.fn(),
grantControl: vi.fn(),
revokeControl: vi.fn(),
reconnect: vi.fn(),
reconnect,
},
]);

Expand Down Expand Up @@ -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");
Expand All @@ -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();
});
});
Loading
Loading