repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

refactor(firefox-bidi): deslop runtime state and launch seam

2f77384feb6995e0fb056b286175094524a3bfd2

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

- debugLog takes a thunk: execute no longer reads settings files per
  call when PI_FIREFOX_DEBUG is unset
- firefoxBinary + assertBinaryAvailable collapse into
  resolveFirefoxBinary with one shared FIREFOX_ACCESS mode
- lastById cross-call seed capped via trimById (most recent 500 ids)

Changed files (3)

extensions/firefox-bidi/__tests__/lib.test.ts

Modified
10 10 parseScreencastSettings,
11 11 resolveScreencastDestinations,
12 12 runBatch,
13 + trimById,
13 14 } from "../lib.ts";
15 16 const res = (id: number, result: unknown) => ({ id, type: "success", result });
341 342 assert.deepEqual(ledger.intercepts, ["i2"]);
342 343 assert.deepEqual(ledger.preloadScripts, []);
347 +test("trimById passes small maps through unchanged", () => {
348 + const byId = new Map([
349 + [1, res(1, { a: 1 })],
350 + [2, res(2, { b: 2 })],
351 + ]);
352 + assert.equal(trimById(byId, 500), byId);
353 +});
355 +test("trimById keeps the most recent keep ids by frame id", () => {
356 + const byId = new Map<number, ReturnType<typeof res>>();
357 + for (let id = 1; id <= 600; id++) byId.set(id, res(id, { n: id }));
358 + const trimmed = trimById(byId, 500);
359 + assert.equal(trimmed.size, 500);
360 + assert.equal(trimmed.has(100), false);
361 + assert.equal(trimmed.get(101)?.id, 101);
362 + assert.equal(trimmed.get(600)?.id, 600);
363 +});

extensions/firefox-bidi/index.ts

Modified
27 27 parseScreencastSettings,
28 28 resolveScreencastDestinations,
29 29 runBatch,
30 + trimById,
30 31 } from "./lib.ts";
32 33 // ── state (one browser per Pi session) ──────────────────────────────────────
65 66 let browser: Browser | null = null;
66 -// Previous batch's responses by frame id, so {{N.result.path}} works across calls.
67 +// Previous batches' responses by frame id, so {{N.result.path}} works across
68 +// calls; capped to the most recent BY_ID_KEEP frames.
67 69 let lastById = new Map<number, BidiResponse>();
68 70 const EVENT_CAP = 200;
69 71 const CONNECT_TIMEOUT = 10_000;
70 72 const DEFAULT_FRAME_TIMEOUT = 30_000;
73 +const BY_ID_KEEP = 500;
72 75 const SKILL_PATH = fileURLToPath(
73 76 new URL("./skills/firefox-bidi/SKILL.md", import.meta.url),
76 79 // ── binary resolution + opt-in file diagnostics ─────────────────────────────
81 +const FIREFOX_ACCESS =
82 + process.platform === "win32" ? fsConstants.F_OK : fsConstants.X_OK;
78 84 function resolveOnPath(name: string): string | undefined {
79 85 const extensions = process.platform === "win32" ? [".exe", ".cmd", ""] : [""];
80 86 for (const dir of (process.env.PATH ?? "").split(delimiter)) {
82 88 for (const ext of extensions) {
83 89 const candidate = join(dir, name + ext);
84 90 try {
85 - accessSync(
86 - candidate,
87 - process.platform === "win32" ? fsConstants.F_OK : fsConstants.X_OK,
88 - );
91 + accessSync(candidate, FIREFOX_ACCESS);
89 92 if (statSync(candidate).isFile()) return candidate;
90 93 } catch {
91 94 // Keep searching PATH.
95 98 return undefined;
98 -function firefoxBinary(): string {
99 - return process.env.FIREFOX_BIN ?? resolveOnPath("firefox") ?? "firefox";
102 -function assertBinaryAvailable(bin: string): void {
103 - try {
104 - accessSync(
105 - bin,
106 - process.platform === "win32" ? fsConstants.F_OK : fsConstants.X_OK,
107 - );
108 - } catch {
109 - throw new Error(
110 - `firefox not found: ${bin} — set FIREFOX_BIN or install Firefox on PATH`,
111 - );
101 +function resolveFirefoxBinary(): string {
102 + const env = process.env.FIREFOX_BIN;
103 + if (env) {
104 + try {
105 + accessSync(env, FIREFOX_ACCESS);
106 + return env;
107 + } catch {
108 + throw new Error(
109 + `firefox not found: ${env} — set FIREFOX_BIN or install Firefox on PATH`,
110 + );
113 + // PATH hits are already verified by resolveOnPath; the miss gets the same
114 + // friendly error as an unusable FIREFOX_BIN
115 + const hit = resolveOnPath("firefox");
116 + if (!hit)
117 + throw new Error(
118 + "firefox not found: firefox — set FIREFOX_BIN or install Firefox on PATH",
119 + );
120 + return hit;
115 -function debugLog(line: string): void {
123 +function debugLog(line: string | (() => string)): void {
116 124 if (!process.env.PI_FIREFOX_DEBUG) return;
125 + const text = typeof line === "function" ? line() : line;
117 126 void appendFile(
118 127 join(tmpdir(), "pi-firefox-bidi-debug.log"),
119 - `${new Date().toISOString()} ${line}\n`,
128 + `${new Date().toISOString()} ${text}\n`,
120 129 ).catch(() => {});
205 214 access?: boolean;
206 215 prefs?: string[];
207 216 }): Promise<Browser> {
208 - const bin = firefoxBinary();
209 - assertBinaryAvailable(bin);
217 + const bin = resolveFirefoxBinary();
210 218 const profileDir = await mkdtemp(join(tmpdir(), "pi-firefox-"));
211 219 const spoolDir = await mkdtemp(join(tmpdir(), "pi-firefox-spool-"));
212 220 if (opts.prefs?.length) {
412 420 await resolveScreencastDestinations(params.frames, () =>
413 421 configuredScreencastDir(ctx.cwd),
415 - debugLog(`cwd=${ctx.cwd} cfg=${configuredScreencastDir(ctx.cwd)}`);
423 + debugLog(
424 + () => `cwd=${ctx.cwd} cfg=${configuredScreencastDir(ctx.cwd)}`,
425 + );
416 426 if (params.launch?.access && browser?.access === false)
417 427 await teardown();
418 428 if (!browser?.child.pid) {
481 491 const events = b.events.slice(-EVENT_CAP);
482 - lastById = byId;
492 + lastById = trimById(byId, BY_ID_KEEP);
483 493 const text = assemblePayload(
485 495 sessionId: b.sessionId,

extensions/firefox-bidi/lib.ts

Modified
261 261 frame.params.destinationFolder = dir;
266 +// Cross-call {{N.result.path}} seeds grow without bound over a session;
267 +// keep only the most recent `keep` frame ids (id order == send order).
268 +export function trimById(
269 + byId: Map<number, BidiResponse>,
270 + keep: number,
271 +): Map<number, BidiResponse> {
272 + if (byId.size <= keep) return byId;
273 + const keepIds = new Set(
274 + [...byId.keys()].sort((a, b) => b - a).slice(0, keep),
275 + );
276 + return new Map([...byId].filter(([id]) => keepIds.has(id)));