diff --git a/apps/pi-extension/server/annotate-fixed-port.test.ts b/apps/pi-extension/server/annotate-fixed-port.test.ts new file mode 100644 index 0000000000..0f88c2a702 --- /dev/null +++ b/apps/pi-extension/server/annotate-fixed-port.test.ts @@ -0,0 +1,95 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { createTestEnvironment } from "../../../tests/helpers/environment.ts"; +import { closeServer, occupyConsecutivePorts } from "../../../tests/helpers/ports.ts"; +import { startServerWithSelfPreemption } from "../plannotator-browser.ts"; +import { startAnnotateServer } from "./serverAnnotate.ts"; + +// A local Pi with PLANNOTATOR_PORT set binds every review on ONE port, and an +// annotate session also attaches the agent terminal's WebSocket server to its +// http server. That WebSocket server re-emits every http server "error" as +// its own, so attaching it BEFORE listen turned the first EADDRINUSE of a +// second annotate session into an unhandled "error" event that killed the +// whole Pi process, before the port-in-use retry and the self-preemption that +// takes the port over could run. (Remote mode never crashed: the agent +// terminal is off there.) + +const envKeys = [ + "PLANNOTATOR_PORT", + "PLANNOTATOR_REMOTE", + "PLANNOTATOR_DATA_DIR", + "PLANNOTATOR_AGENT_TERMINAL_REMOTE", +] as const; +const environment = createTestEnvironment(envKeys, "plannotator-pi-annotate-fixed-port-"); + +afterEach(() => environment.restore()); + +async function reserveFreePort(): Promise { + const { start, servers } = await occupyConsecutivePorts(1); + await closeServer(servers[0]!); + return start; +} + +function annotateOptions(name: string) { + return { + markdown: `# ${name}`, + filePath: `${name}.md`, + htmlContent: "", + mode: "annotate" as const, + agentCwd: "/tmp/plannotator-agent-cwd", + }; +} + +describe("Pi annotate on a fixed local port", () => { + test("a busy port fails startup with the port-in-use error instead of crashing", async () => { + environment.reset(); + process.env.PLANNOTATOR_REMOTE = "0"; + process.env.PLANNOTATOR_DATA_DIR = environment.makeTempDir(); + process.env.PLANNOTATOR_PORT = String(await reserveFreePort()); + + const first = await startAnnotateServer(annotateOptions("first")); + try { + const plan = await fetch(`${first.url}/api/plan`).then((res) => res.json()); + // The agent terminal (the WebSocket server) is what used to crash. + expect(plan.agentTerminal.enabled).toBe(true); + + await expect(startAnnotateServer(annotateOptions("second"))).rejects.toThrow( + `Port ${process.env.PLANNOTATOR_PORT} in use`, + ); + + // The open session is untouched by the failed start. + const again = await fetch(`${first.url}/api/plan`).then((res) => res.json()); + expect(again.plan).toBe("# first"); + } finally { + first.stop(); + } + }, 15_000); + + test("a second annotate session takes the port over through self-preemption", async () => { + environment.reset(); + process.env.PLANNOTATOR_REMOTE = "0"; + process.env.PLANNOTATOR_DATA_DIR = environment.makeTempDir(); + const port = await reserveFreePort(); + process.env.PLANNOTATOR_PORT = String(port); + + const first = await startAnnotateServer(annotateOptions("first")); + let stoppedFirst = 0; + const second = await startServerWithSelfPreemption( + () => startAnnotateServer(annotateOptions("second")), + () => { + stoppedFirst++; + first.stop(); + return true; + }, + ); + try { + expect(stoppedFirst).toBe(1); + expect(second.port).toBe(port); + const plan = await fetch(`${second.url}/api/plan`).then((res) => res.json()); + expect(plan.plan).toBe("# second"); + expect(plan.agentTerminal.enabled).toBe(true); + } finally { + second.stop(); + first.stop(); + } + }, 15_000); +}); diff --git a/apps/pi-extension/server/serverAnnotate.ts b/apps/pi-extension/server/serverAnnotate.ts index 21c4649d2d..9c9da5e9bd 100644 --- a/apps/pi-extension/server/serverAnnotate.ts +++ b/apps/pi-extension/server/serverAnnotate.ts @@ -1371,15 +1371,57 @@ export async function startAnnotateServer(options: { await html(req, res, options.htmlContent, isRemoteSession()); } }); - const agentTerminal = await createNodeAgentTerminalBridge({ - enabled: supportsAnnotateAgentTerminalMode(options.mode || "annotate"), - cwd: options.agentCwd ?? process.cwd(), - server, - }); - agentTerminalCapability = agentTerminal.capability; + // Startup failures must not leave anything behind in the long-lived Pi + // process: every step guarded so the original error is what propagates. + // File browser watchers are process-wide (other open sessions own some), + // so only a failure after this server may have served requests closes them. + const disposeFailedStart = (extra: Array<() => void> = []) => { + for (const dispose of [ + () => { + clientLease.cancel(); + clientLease.closeSessions(); + }, + () => aiRuntime?.dispose(), + ...extra, + ]) { + try { + dispose(); + } catch { + // startup failure cleanup: best effort + } + } + server.close(); + (server as { closeAllConnections?: () => void }).closeAllConnections?.(); + }; - const { port, portSource } = await listenOnPort(server); + let listened: Awaited>; + try { + listened = await listenOnPort(server); + } catch (error) { + disposeFailedStart(); + throw error; + } + const { port, portSource } = listened; boundPort = port; + + // Attach the agent terminal only once the port is ours. Its WebSocket + // server re-emits every http server "error" as its own and has no handler + // for it, so attached before listen, a busy fixed port (PLANNOTATOR_PORT in + // a local session) turned the first EADDRINUSE into an unhandled "error" + // that killed the whole Pi process before the port-in-use retry and the + // self-preemption that takes the port over could run. + let agentTerminal: Awaited>; + try { + agentTerminal = await createNodeAgentTerminalBridge({ + enabled: supportsAnnotateAgentTerminalMode(options.mode || "annotate"), + cwd: options.agentCwd ?? process.cwd(), + server, + }); + } catch (error) { + disposeFailedStart(); + throw error; + } + agentTerminalCapability = agentTerminal.capability; // Remote sessions serve the app page compressed (#1617); start gzip (what // browsers ask for over plain http) now so the first load does not wait. if (isRemoteSession()) prewarmAppHtml(options.htmlContent, likelyAppHtmlEncoding(false)); @@ -1412,23 +1454,7 @@ export async function startAnnotateServer(options: { } catch (error) { // Same disposal set the normal stop() runs, each step guarded so // the original startup error is what propagates. - for (const dispose of [ - () => closeAllFileBrowserWatchers(), - () => { - clientLease.cancel(); - clientLease.closeSessions(); - }, - () => aiRuntime?.dispose(), - () => agentTerminal.dispose(), - ]) { - try { - dispose(); - } catch { - // startup failure cleanup: best effort - } - } - server.close(); - (server as { closeAllConnections?: () => void }).closeAllConnections?.(); + disposeFailedStart([() => closeAllFileBrowserWatchers(), () => agentTerminal.dispose()]); throw error; } }