aboutsummaryrefslogtreecommitdiff
path: root/test-suite
diff options
context:
space:
mode:
authorIgor Soarez <igor@soarez.org>2026-11-20 16:38:11 +0200
committerIgor Soarez <igor@soarez.org>2026-11-20 16:38:11 +0200
commit31eee500cd9c570c960bbb9a50209c0c21c1b716 (patch)
tree68c3fd9a7a093493b821552a76f8b55e84a41591 /test-suite
parent7658ed71898c7daca2661c7d15ffe03c8608c865 (diff)
extension: a stopped bridge drops its open connectionsHEADmaster
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.
Diffstat (limited to 'test-suite')
-rw-r--r--test-suite/unit/bridge-handover.test.mjs142
-rw-r--r--test-suite/unit/grant-scope.test.mjs2
2 files changed, 143 insertions, 1 deletions
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.