diff options
| author | Igor Soarez <igor@soarez.org> | 2026-11-20 16:38:11 +0200 |
|---|---|---|
| committer | Igor Soarez <igor@soarez.org> | 2026-11-20 16:38:11 +0200 |
| commit | 31eee500cd9c570c960bbb9a50209c0c21c1b716 (patch) | |
| tree | 68c3fd9a7a093493b821552a76f8b55e84a41591 | |
| parent | 7658ed71898c7daca2661c7d15ffe03c8608c865 (diff) | |
server.close() refuses new connections but leaves open the ones busy at
that moment, such as the extension posting a result. When the owner pi
reloaded, Chrome sent the extension's next /next on such a connection,
and the stopped bridge answered it, and every poll after it, for good.
Commands went to the new owner, which never heard from Chrome: "not
polling (last seen never)" until the extension was reloaded. Seen
2026-11-20 with lsof: Chrome connected to a pi that no longer listened.
stop() now closes every connection once the final answers are written,
so the extension reconnects to whoever owns the port next.
bridge-handover.test.mjs covers a connection busy at the stop and one
opened before it; both reached the stopped bridge before this change.
| -rw-r--r-- | extensions/chrome-profile-bridge/index.ts | 9 | ||||
| -rw-r--r-- | package.json | 2 | ||||
| -rw-r--r-- | test-suite/unit/bridge-handover.test.mjs | 142 | ||||
| -rw-r--r-- | test-suite/unit/grant-scope.test.mjs | 2 |
4 files changed, 152 insertions, 3 deletions
diff --git a/extensions/chrome-profile-bridge/index.ts b/extensions/chrome-profile-bridge/index.ts index 2cbd5da..aefdb89 100644 --- a/extensions/chrome-profile-bridge/index.ts +++ b/extensions/chrome-profile-bridge/index.ts @@ -604,7 +604,14 @@ class ChromeProfileBridge { this.queue = []; for (const waiter of this.waiters) waiter(undefined); this.waiters = []; - this.server?.close(); + // close() refuses new connections but leaves open the ones that are busy at this moment, and + // Chrome sends the extension's next /next on such a connection once it goes idle. The stopped + // bridge then answered those polls forever, while commands waited in the new owner, which never + // heard from Chrome (2026-11-20). Drop them all, after the answers above are written, so the + // extension reconnects to whoever owns the port next. + const server = this.server; + server?.close(); + if (server) setImmediate(() => server.closeAllConnections()); this.server = undefined; this.mode = undefined; } diff --git a/package.json b/package.json index 4995d3c..d75ef59 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "pi-chrome", "version": "0.15.57", "scripts": { - "test": "node test-suite/unit/csp-eval.test.mjs && node test-suite/unit/automation-target.test.mjs && node test-suite/unit/session-cleanup.test.mjs && node test-suite/unit/background-policy.test.mjs && node test-suite/unit/input-reliability.test.mjs && node test-suite/unit/chrome-command.test.mjs && node test-suite/unit/bridge-resilience.test.mjs && node test-suite/unit/cdp-passthrough.test.mjs && node test-suite/unit/type-evidence.test.mjs && node test-suite/unit/hidden-input.test.mjs && node test-suite/unit/console-capture.test.mjs && node test-suite/unit/prompt-section.test.mjs && node test-suite/unit/upload-guard.test.mjs && node test-suite/unit/grant-scope.test.mjs && node test-suite/unit/leave-site-prompt.test.mjs && node test-suite/unit/user-window.test.mjs && node test-suite/unit/overlay.test.mjs && node test-suite/unit/sandboxed-snapshot.test.mjs", + "test": "node test-suite/unit/csp-eval.test.mjs && node test-suite/unit/automation-target.test.mjs && node test-suite/unit/session-cleanup.test.mjs && node test-suite/unit/background-policy.test.mjs && node test-suite/unit/input-reliability.test.mjs && node test-suite/unit/chrome-command.test.mjs && node test-suite/unit/bridge-resilience.test.mjs && node test-suite/unit/cdp-passthrough.test.mjs && node test-suite/unit/type-evidence.test.mjs && node test-suite/unit/hidden-input.test.mjs && node test-suite/unit/console-capture.test.mjs && node test-suite/unit/prompt-section.test.mjs && node test-suite/unit/upload-guard.test.mjs && node test-suite/unit/grant-scope.test.mjs && node test-suite/unit/leave-site-prompt.test.mjs && node test-suite/unit/user-window.test.mjs && node test-suite/unit/overlay.test.mjs && node test-suite/unit/sandboxed-snapshot.test.mjs && node test-suite/unit/bridge-handover.test.mjs", "version": "node scripts/sync-manifest-version.js", "prepublishOnly": "node scripts/sync-manifest-version.js" }, diff --git a/test-suite/unit/bridge-handover.test.mjs b/test-suite/unit/bridge-handover.test.mjs new file mode 100644 index 0000000..2e138e8 --- /dev/null +++ b/test-suite/unit/bridge-handover.test.mjs @@ -0,0 +1,142 @@ +// When the pi session that owns the bridge port reloads, the Chrome extension must reach the new +// owner. Chrome keeps the extension's long-poll connection alive and sends the next /next on it at +// once, so the connection never goes idle. server.close() alone leaves it open, and the stopped +// bridge kept answering polls on it while commands waited in the new owner, which never heard +// from Chrome ("not polling (last seen never)") until the extension was reloaded. Measured +// 2026-11-20 with lsof: Chrome connected to the reloaded owner's process, which no longer listened. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import http from "node:http"; +import net from "node:net"; +import vm from "node:vm"; +import { createRequire, stripTypeScriptTypes } from "node:module"; +import { test } from "node:test"; + +const indexUrl = new URL("../../extensions/chrome-profile-bridge/index.ts", import.meta.url); +const stubbed = stripTypeScriptTypes(fs.readFileSync(indexUrl, "utf8"), { mode: "transform" }) + .replace(/^import \{ Text \} from "@earendil-works\/pi-tui";$/m, "const Text = class {};") + .replace(/^import \{ Type \} from "typebox";$/m, "const Type = new Proxy({}, { get: () => (value = {}) => value });") + .replace(/^import \{([^}]*)\} from "(node:[^"]+)";$/gm, (_m, names, mod) => `const {${names.replace(/\btype\s+\w+\s*,?/g, "")}} = require("${mod}");`) + .replace(/^export default function/m, "module.exports.default = function"); + +const freePort = () => new Promise((resolve) => { + const s = net.createServer().listen(0, "127.0.0.1", () => { const { port } = s.address(); s.close(() => resolve(port)); }); +}); + +// One pi process: each runtime is a fresh evaluation of the module in one shared context. +function piProcess(port) { + const fakeProcess = Object.create(process, { env: { value: { PI_CHROME_BRIDGE_PORT: String(port) } } }); + const context = vm.createContext({ process: fakeProcess, console, Buffer, URL, AbortController, fetch, setTimeout, clearTimeout, setInterval, clearInterval, setImmediate }); + const load = () => { + const module = { exports: {} }; + vm.runInContext(`(function (module, exports, require, __dirname) {\n${stubbed}\n})`, context)(module, module.exports, createRequire(indexUrl), new URL(".", indexUrl).pathname); + const handlers = {}; + let active = []; + module.exports.default({ + on: (name, fn) => { handlers[name] = fn; }, registerTool() {}, registerEntryRenderer() {}, appendEntry() {}, registerCommand() {}, + getActiveTools: () => active, setActiveTools: (tools) => { active = tools; }, + }); + const ctx = { cwd: process.cwd(), ui: { setStatus() {}, notify() {}, theme: { fg: (_c, t) => t } } }; + return { + start: () => handlers.session_start({ type: "session_start" }, ctx), + stop: (reason) => handlers.session_shutdown({ type: "session_shutdown", reason }), + }; + }; + return { load }; +} + +// The extension's poll loop, on one kept-alive connection as Chrome uses it. +function fakeExtension(port) { + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); + let running = true; + const request = (method, path, body) => new Promise((resolve, reject) => { + const req = http.request({ host: "127.0.0.1", port, method, path, agent, headers: { origin: "chrome-extension://test", "content-type": "application/json" } }, (res) => { + let data = ""; res.on("data", (c) => { data += c; }); res.on("end", () => resolve(data)); + }); + req.on("error", reject); + req.end(body); + }); + (async () => { + while (running) { + try { + const payload = JSON.parse(await request("GET", "/next?name=test")); + if (payload.type === "command") await request("POST", "/result", JSON.stringify({ id: payload.command.id, ok: true, result: { pong: true } })); + } catch { await new Promise((r) => setTimeout(r, 100)); } + } + })(); + return { stop() { running = false; agent.destroy(); } }; +} + +// Another pi session's request, on a fresh connection, as sendViaOwner makes it. +async function command(port) { + const res = await fetch(`http://127.0.0.1:${port}/command`, { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body: JSON.stringify({ action: "tab.version", params: {}, timeoutMs: 3000 }) }); + return res.json(); +} + +test("after the owner reloads, the extension's kept-alive poll reaches the new owner", { timeout: 20_000 }, async (t) => { + const port = await freePort(); + const pi = piProcess(port); + let runtime = pi.load(); + await runtime.start(); + const extension = fakeExtension(port); + t.after(async () => { extension.stop(); await runtime.stop("quit"); }); + await new Promise((r) => setTimeout(r, 200)); + assert.deepEqual(await command(port), { ok: true, result: { pong: true } }, "before the reload"); + + await runtime.stop("reload"); + runtime = pi.load(); + await runtime.start(); + + const after = await command(port); + assert.deepEqual(after, { ok: true, result: { pong: true } }, `after the reload: ${JSON.stringify(after)}`); +}); + +// Chrome also opens connections ahead of need (preconnect) and keeps spares. One opened before the +// owner stopped must not reach the stopped bridge afterwards. +test("a connection opened before the owner stopped does not reach the stopped bridge", { timeout: 20_000 }, async (t) => { + const port = await freePort(); + const pi = piProcess(port); + const runtime = pi.load(); + await runtime.start(); + const spare = net.connect(port, "127.0.0.1"); + await new Promise((r) => spare.once("connect", r)); + t.after(() => spare.destroy()); + + await runtime.stop("reload"); + const answer = await new Promise((resolve) => { + let data = ""; + spare.on("data", (c) => { data += c; }); + spare.on("close", () => resolve(data)); + spare.on("error", () => resolve(data)); + spare.write("GET /status HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); + setTimeout(() => resolve(data), 1000); + }); + assert.doesNotMatch(answer, /200 OK/, `the stopped bridge answered: ${answer.split("\r\n")[0]}`); +}); + +// The case Chrome hit: the extension is posting a result when the owner stops. Node's +// server.close() closes only connections idle at that moment, so this one stays open, goes idle +// once the stopped bridge answers, and Chrome sends its next /next on it. +test("a connection busy when the owner stopped does not reach the stopped bridge afterwards", { timeout: 20_000 }, async (t) => { + const port = await freePort(); + const pi = piProcess(port); + const runtime = pi.load(); + await runtime.start(); + const socket = net.connect(port, "127.0.0.1"); + await new Promise((r) => socket.once("connect", r)); + t.after(() => socket.destroy()); + let data = ""; + socket.on("data", (c) => { data += c; }); + const body = JSON.stringify({ id: "x", ok: true, result: {} }); + // Headers now, body after the stop: the request is in flight while the owner stops. + socket.write(`POST /result HTTP/1.1\r\nHost: 127.0.0.1\r\nOrigin: chrome-extension://test\r\nContent-Type: application/json\r\nContent-Length: ${body.length}\r\n\r\n`); + await new Promise((r) => setTimeout(r, 100)); + await runtime.stop("reload"); + socket.write(body); + await new Promise((r) => setTimeout(r, 200)); + const first = data; + data = ""; + socket.write("GET /status HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); + await new Promise((r) => setTimeout(r, 500)); + assert.doesNotMatch(data, /200 OK/, `after answering ${first.split("\r\n")[0] || "nothing"}, the stopped bridge answered the next request too: ${data.split("\r\n")[0]}`); +}); diff --git a/test-suite/unit/grant-scope.test.mjs b/test-suite/unit/grant-scope.test.mjs index 7717131..fd67508 100644 --- a/test-suite/unit/grant-scope.test.mjs +++ b/test-suite/unit/grant-scope.test.mjs @@ -21,7 +21,7 @@ function piProcess(env) { const fakeProcess = Object.create(process, { env: { value: { ...env, PI_CHROME_BRIDGE_PORT: "0" } } }); const context = vm.createContext({ process: fakeProcess, console, Buffer, URL, AbortController, fetch, - setTimeout, clearTimeout, setInterval, clearInterval, + setTimeout, clearTimeout, setInterval, clearInterval, setImmediate, }); let runtime; // A grant an earlier runtime left on globalThis, e.g. a build that saved the env grant there. |
