Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

perf(desktop): read only session metadata where the transcript is unused

zszz3211cae52a495
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.ts
index fb2bd6cab..0215cc68b 100644
--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts
+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts
@@ -606,7 +606,7 @@ export function registerWorkspaceIpc({
errorCode: ErrorCodes.INVALID_ARGUMENT,
});
}
- const session = (await host.call("session.get", { id: sessionId })) as {
+ const session = (await host.call("session.get", { id: sessionId, messageLimit: 1 })) as {
session?: unknown;
};
if (!session.session) {
@@ -656,7 +656,7 @@ handleWithEvent(
errorCode: ErrorCodes.INVALID_ARGUMENT,
});
}
- const session = (await host.call("session.get", { id: sessionId })) as {
+ const session = (await host.call("session.get", { id: sessionId, messageLimit: 1 })) as {
session?: unknown;
};
if (!session.session) {
diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.ts
index 1cf337707..730c3bc26 100644
--- a/apps/desktop/electron/main/runtime/host.ts
+++ b/apps/desktop/electron/main/runtime/host.ts
@@ -246,7 +246,7 @@ export function createHostRuntime({
modelId?: string;
thinkingLevel?: string;
};
- }>("session.get", { id: q.sessionId });
+ }>("session.get", { id: q.sessionId, messageLimit: 1 });
const session = detail?.session;
if (session?.mode === "agent" || session?.mode === "plan" || session?.mode === "goal") {
sessionMode = session.mode;
diff --git a/apps/desktop/electron/main/runtime/plans.ts b/apps/desktop/electron/main/runtime/plans.ts
index ce264e3fb..50c41babc 100644
--- a/apps/desktop/electron/main/runtime/plans.ts
+++ b/apps/desktop/electron/main/runtime/plans.ts
@@ -450,7 +450,7 @@ async function dispatchApprovedPlan(rawExecution: unknown): Promise<void> {
const [settings, sessionResult] = await Promise.all([
runtimeState.host.call("settings.get"),
- runtimeState.host.call<{ session?: any }>("session.get", { id: execution.sessionId }),
+ runtimeState.host.call<{ session?: any }>("session.get", { id: execution.sessionId, messageLimit: 1 }),
]);
if (!sessionResult.session) {
throw Object.assign(new Error("Session not found"), {
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index 2f25754fe..f6a40058f 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -380,7 +380,7 @@ export function createSidecarRuntime({
if (!host) return null;
const res = await host.call<{
session: { projectPath?: string; worktree?: unknown } | null;
- }>("session.get", { id: sessionId });
+ }>("session.get", { id: sessionId, messageLimit: 1 });
if (res?.session?.worktree) {
const location = await host.call<{ path?: string }>("worktree.location", { sessionId });
return location.path?.trim() || null;
diff --git a/apps/desktop/electron/main/services/image-generation-service.ts b/apps/desktop/electron/main/services/image-generation-service.ts
index 691abb0e4..b991ff452 100644
--- a/apps/desktop/electron/main/services/image-generation-service.ts
+++ b/apps/desktop/electron/main/services/image-generation-service.ts
@@ -99,6 +99,7 @@ export function createImageGenerationTool(options: {
signal.throwIfAborted();
const { session } = await host.call<{ session?: { projectPath?: string } }>("session.get", {
id: sessionId,
+ messageLimit: 1,
});
if (!session) return failure("SESSION_NOT_FOUND", "The image session no longer exists.");
const operations: ImageOperationMetadata[] = [];
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index 213917c63..447e6c2f6 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -699,7 +699,7 @@ export function createPluginServices({
const host = getHost();
if (!host) throw new Error("Browser preview host is unavailable.");
const res = await host.call<{ session: { projectPath?: string; worktree?: unknown } | null }>(
- "session.get", { id: sessionId },
+ "session.get", { id: sessionId, messageLimit: 1 },
);
if (!res?.session) throw new Error("Browser preview session is unavailable.");
if (res.session.worktree) {
diff --git a/apps/desktop/test/browser-preview-tool.test.mjs b/apps/desktop/test/browser-preview-tool.test.mjs
index 4f196a261..06b43aee7 100644
--- a/apps/desktop/test/browser-preview-tool.test.mjs
+++ b/apps/desktop/test/browser-preview-tool.test.mjs
@@ -66,7 +66,8 @@ test("main serves BrowserPreview from its originating session workspace", async
assert.match(handler, /browserHost\.previewFile\(\)/);
const services = await readFile(new URL("../electron/main/services/plugin-services.ts", import.meta.url), "utf8");
const roots = services.slice(services.indexOf("getFileRoots: async"), services.indexOf("getScratchDir:"));
- assert.match(roots, /"session\.get", \{ id: sessionId \}/);
+ // Roots need project/worktree metadata only, never the transcript.
+ assert.match(roots, /"session\.get", \{ id: sessionId, messageLimit: 1 \}/);
assert.match(roots, /res\.session\.worktree/);
assert.match(roots, /"worktree\.location", \{ sessionId \}/);
assert.match(roots, /return \[path, join\(dataDir, "scratch", sessionId\)\]/);
diff --git a/apps/desktop/test/composer-paste-files.test.mjs b/apps/desktop/test/composer-paste-files.test.mjs
index 72622d8d6..f4a61dbc3 100644
--- a/apps/desktop/test/composer-paste-files.test.mjs
+++ b/apps/desktop/test/composer-paste-files.test.mjs
@@ -106,7 +106,9 @@ test("paste IPC is a typed renderer-to-main bridge", () => {
assert.match(api, /recordClipboardPaste: \(text: string\)/);
assert.match(api, /IPC\.invoke\.clipboardRecordPaste/);
assert.match(api, /IPC\.invoke\.composerImportFiles/);
- assert.match(main, /host\.call\("session\.get", \{ id: sessionId \}\)/);
+ // The session check needs metadata only; an unbounded read loads the whole transcript.
+ assert.equal(main.match(/host\.call\("session\.get", \{ id: sessionId, messageLimit: 1 \}\)/g)?.length, 2);
+ assert.doesNotMatch(main, /host\.call\("session\.get", \{ id: sessionId \}\)/);
assert.match(main, /saveComposerPasteFiles\(dataDir, sessionId, files\)/);
assert.match(main, /recordPastedClipboardFiles\(files\)/);
assert.match(main, /assertMainWindowSender\(event\)/);
diff --git a/apps/desktop/test/image-generation.test.mjs b/apps/desktop/test/image-generation.test.mjs
index fd5223297..cb8cbadf2 100644
--- a/apps/desktop/test/image-generation.test.mjs
+++ b/apps/desktop/test/image-generation.test.mjs
@@ -33,8 +33,10 @@ test("configure, batch generate, edit a result, replace binding, clear; files su
defaultProviderId: "chat-provider",
imageGeneration: { providerId: "image-provider", modelId: "image-one" },
};
+ const sessionReads = [];
const host = {
- call: async (method) => {
+ call: async (method, params) => {
+ if (method === "session.get") sessionReads.push(params);
if (method === "settings.get") return structuredClone(settings);
if (method === "providers.get")
return {
@@ -63,6 +65,9 @@ test("configure, batch generate, edit a result, replace binding, clear; files su
const batch = await call({ items: [{ prompt: "cover", count: 2 }, { prompt: "icon" }] });
assert.equal(batch.ok, true);
assert.equal(batch.content.results.length, 3);
+ // Only session metadata is needed; never pull the whole transcript.
+ assert.ok(sessionReads.length > 0);
+ for (const params of sessionReads) assert.deepEqual(params, { id: "session", messageLimit: 1 });
for (const image of batch.content.results) assert.deepEqual(await readFile(image.path), png);
assert.ok(
requests.every(
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index f7347948c..1412658a7 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13,6 +13,16 @@ old read. The caller receives history while the session cache keeps the newer
snapshot. Coverage: `full-transcript-refresh-race.test.mjs` plus existing
session-runtime update regressions. No provider execution is required.
+### E2E-SESSION-metadata-reads-skip-transcript
+
+Seed real host-core with a ~40 MB transcript beside a short session. A
+`messageLimit: 1` `session.get` must return the same project, worktree, mode
+and model metadata as an unbounded read. Then launch the built desktop app on
+that data and drive composer paste and Browser navigate through the real
+preload IPC on both sessions: the long session may not add half an unbounded
+read's time to either call. Coverage: `pnpm test:e2e:session-metadata-reads`
+(`scripts/e2e-session-metadata-reads.mjs`). No provider execution is required.
+
### E2E-SESSION-rejected-stop-state
Reject a remote Stop at the API boundary: the production session slice keeps
diff --git a/package.json b/package.json
index ed2916eb2..086803a80 100644
--- a/package.json
+++ b/package.json
@@ -73,6 +73,7 @@
"test:e2e:window-surface": "node scripts/e2e-window-surface.mjs",
"test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs",
"test:e2e:browser-local-files": "node scripts/e2e-browser-local-file-access.mjs",
+ "test:e2e:session-metadata-reads": "node scripts/e2e-session-metadata-reads.mjs",
"test:e2e:browser-background": "node scripts/e2e-browser-background.mjs",
"test:e2e:work-panel-drag": "node scripts/e2e-work-panel-drag.mjs",
"test:e2e:work-panel-tab-close": "node scripts/e2e-work-panel-tab-close.mjs",
diff --git a/packages/host-runtime/src/host-ports.test.ts b/packages/host-runtime/src/host-ports.test.ts
index 58110d459..7e5d534fb 100644
--- a/packages/host-runtime/src/host-ports.test.ts
+++ b/packages/host-runtime/src/host-ports.test.ts
@@ -56,6 +56,19 @@ describe("host ports", () => {
expect(await createHostSessionPort(() => null).get("s1")).toBeNull();
});
+ it("bounds the transcript read for metadata lookups but not for history pages", async () => {
+ const calls: Array<Record<string, unknown> | undefined> = [];
+ const port = createHostSessionPort(() => ({
+ async call<T>(_method: string, params?: Record<string, unknown>) {
+ calls.push(params);
+ return { session: { id: "s1", messages: [] } } as T;
+ },
+ }));
+ await port.get("s1");
+ await port.history("s1", { limit: 10 });
+ expect(calls).toEqual([{ id: "s1", messageLimit: 1 }, { id: "s1" }]);
+ });
+
it("round-trips queue records through the host-core RPC shape", async () => {
const calls: Array<{ method: string; params: Record<string, unknown> }> = [];
const store = createHostQueueStore(() => ({
diff --git a/packages/host-runtime/src/host-ports.ts b/packages/host-runtime/src/host-ports.ts
index a7919c96f..5aa5cc7bb 100644
--- a/packages/host-runtime/src/host-ports.ts
+++ b/packages/host-runtime/src/host-ports.ts
@@ -82,15 +82,19 @@ export function toRacpItem(message: UiMessage): RacpItemSummary {
/** Session metadata and transcript pages straight from host `session.get`. */
export function createHostSessionPort(getHost: () => HostRpc | null): SessionPort {
- async function fetchSession(sessionId: string): Promise<HostSessionRecord | null> {
+ // `messageLimit` bounds the transcript read; metadata lookups need no messages.
+ async function fetchSession(sessionId: string, messageLimit?: number): Promise<HostSessionRecord | null> {
const host = getHost();
if (!host) return null;
- const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", { id: sessionId });
+ const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", {
+ id: sessionId,
+ ...(messageLimit === undefined ? {} : { messageLimit }),
+ });
return result.session ?? null;
}
return {
async get(sessionId) {
- const record = await fetchSession(sessionId);
+ const record = await fetchSession(sessionId, 1);
return record ? toSessionSummary(record) : null;
},
async history(sessionId, { limit, beforeItemId }) {
diff --git a/packages/host-runtime/src/plan-dispatch.ts b/packages/host-runtime/src/plan-dispatch.ts
index b5b0521b9..1c4008c31 100644
--- a/packages/host-runtime/src/plan-dispatch.ts
+++ b/packages/host-runtime/src/plan-dispatch.ts
@@ -128,7 +128,7 @@ export class PlanExecutionDispatcher {
claimed = true;
const [settings, sessionResult] = await Promise.all([
host.call<Record<string, unknown>>("settings.get"),
- host.call<{ session?: Record<string, unknown> | null }>("session.get", { id: execution.sessionId }),
+ host.call<{ session?: Record<string, unknown> | null }>("session.get", { id: execution.sessionId, messageLimit: 1 }),
]);
if (!sessionResult.session) {
throw Object.assign(new Error("Session not found"), { errorCode: ErrorCodes.NOT_FOUND });
diff --git a/scripts/e2e-session-metadata-reads.mjs b/scripts/e2e-session-metadata-reads.mjs
new file mode 100644
index 000000000..2f6099bfd
--- /dev/null
+++ b/scripts/e2e-session-metadata-reads.mjs
@@ -0,0 +1,246 @@
+#!/usr/bin/env node
+/**
+ * E2E-SESSION-metadata-reads-skip-transcript — main-process lookups that only
+ * need a session's metadata (Browser file roots, composer paste/import) must
+ * not read the whole transcript through host-core `session.get`.
+ *
+ * 1. Seeds a real host-core with a session whose transcript is ~40 MB and
+ * measures an unbounded `session.get` against a `messageLimit: 1` read,
+ * asserting the bounded read carries the same metadata.
+ * 2. Launches the built desktop app on that data with a throwaway profile and
+ * drives the real preload IPC from the renderer over CDP: composer paste
+ * and Browser navigate on the long session must succeed and stay well under
+ * the unbounded read time.
+ *
+ * Requires a desktop build (`pnpm --filter @pi-desktop/desktop build`) and a
+ * host-core binary (target/{debug,release} or PI_DESKTOP_HOST_BIN).
+ */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdir, mkdtemp, readFile, realpath, rm } from "node:fs/promises";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+import { assertDesktopBuild, repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+import { createSession } from "./e2e/session.mjs";
+
+const MESSAGE_COUNT = 320;
+const MESSAGE_BYTES = 128 * 1024;
+const METADATA_KEYS = ["id", "projectPath", "worktree", "mode", "modelId", "providerId", "thinkingLevel", "remoteWorkspace"];
+
+const root = repositoryRoot();
+const { appDir } = assertDesktopBuild(root);
+const { electronBinary } = resolveElectronBinary(root);
+const hostBinary = resolveHostBinary();
+// host-core canonicalizes project paths (macOS /var -> /private/var).
+const scratch = await realpath(await mkdtemp(join(tmpdir(), "pi-session-metadata-reads-")));
+const dataDir = join(scratch, "data");
+const workspace = join(scratch, "workspace");
+await mkdir(workspace, { recursive: true });
+
+const median = (values) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)];
+const timed = async (fn) => {
+ const start = performance.now();
+ const value = await fn();
+ return { value, ms: performance.now() - start };
+};
+
+let app = null;
+let server = null;
+try {
+ // --- 1. host-core contract on a long transcript ---------------------------
+ const host = new Host(hostBinary, dataDir, { quiet: true });
+ await host.start();
+ const session = await createSession(host, workspace, "Long transcript");
+ const control = await createSession(host, workspace, "Short transcript");
+ // Quotes and newlines make the transcript cost JSON escaping, like real tool output.
+ const filler = 'line "quoted" \\ text\n'.repeat(MESSAGE_BYTES / 24);
+ for (let index = 0; index < MESSAGE_COUNT; index += 1) {
+ await host.call("session.appendMessage", {
+ sessionId: session.id,
+ message: {
+ id: `m${index}`,
+ role: index % 2 === 0 ? "user" : "assistant",
+ content: `${index} ${filler}`,
+ createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),
+ status: "complete",
+ },
+ });
+ }
+ const fullRuns = [];
+ const boundedRuns = [];
+ let full;
+ let bounded;
+ for (let run = 0; run < 3; run += 1) {
+ const a = await timed(() => host.call("session.get", { id: session.id }));
+ const b = await timed(() => host.call("session.get", { id: session.id, messageLimit: 1 }));
+ fullRuns.push(a.ms);
+ boundedRuns.push(b.ms);
+ full = a.value.session;
+ bounded = b.value.session;
+ }
+ assert.equal(full.messages.length, MESSAGE_COUNT);
+ assert.ok(bounded.messages.length <= 1, "bounded read returned the transcript");
+ for (const key of METADATA_KEYS) {
+ assert.deepEqual(bounded[key], full[key], `bounded session.get changed ${key}`);
+ }
+ assert.equal(bounded.projectPath, workspace);
+ const fullMs = median(fullRuns);
+ console.log(`host session.get: full ${fullMs.toFixed(1)}ms, messageLimit:1 ${median(boundedRuns).toFixed(1)}ms`);
+ await host.stop();
+
+ // --- 2. real desktop IPC on the same data ---------------------------------
+ server = createServer((_request, response) => {
+ response.setHeader("Content-Type", "text/html");
+ response.end("<!doctype html><title>metadata-reads</title><p>ok</p>");
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const pageUrl = `http://127.0.0.1:${server.address().port}/`;
+
+ const env = { ...process.env, PI_DESKTOP_DATA_DIR: dataDir, PI_DESKTOP_HOST_BIN: hostBinary, ELECTRON_RENDERER_URL: "" };
+ delete env.ELECTRON_RUN_AS_NODE;
+ delete env.NODE_OPTIONS;
+ app = spawn(
+ electronBinary,
+ [".", `--user-data-dir=${join(scratch, "profile")}`, "--remote-debugging-port=0"],
+ { cwd: appDir, env, stdio: ["ignore", "pipe", "pipe"] },
+ );
+ let output = "";
+ const debuggerUrl = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`no DevTools endpoint\n${output.slice(-2000)}`)), 60_000);
+ const onData = (chunk) => {
+ output += chunk;
+ const match = /DevTools listening on (ws:\/\/[^\s]+)/.exec(output);
+ if (match) {
+ clearTimeout(timer);
+ resolve(match[1]);
+ }
+ };
+ app.stdout.on("data", onData);
+ app.stderr.on("data", onData);
+ app.once("exit", (code) => reject(new Error(`app exited ${code}\n${output.slice(-2000)}`)));
+ });
+ const { port } = new URL(debuggerUrl);
+
+ let page = null;
+ for (let attempt = 0; attempt < 120 && !page; attempt += 1) {
+ const targets = await fetch(`http://127.0.0.1:${port}/json/list`).then((r) => r.json());
+ // The main window loads index.html without a `surface` query (launcher,
+ // overlays and voice widgets add one).
+ page = targets.find((target) => target.type === "page" && /renderer\/index\.html$/.test(target.url));
+ if (!page) await delay(250);
+ }
+ assert.ok(page, "desktop renderer page not found");
+
+ const socket = new WebSocket(page.webSocketDebuggerUrl);
+ await new Promise((resolve, reject) => {
+ socket.addEventListener("open", resolve, { once: true });
+ socket.addEventListener("error", reject, { once: true });
+ });
+ let nextId = 0;
+ const pending = new Map();
+ socket.addEventListener("message", (event) => {
+ const message = JSON.parse(event.data);
+ pending.get(message.id)?.(message);
+ pending.delete(message.id);
+ });
+ const evaluate = async (expression) => {
+ const id = (nextId += 1);
+ const reply = await new Promise((resolve) => {
+ pending.set(id, resolve);
+ socket.send(JSON.stringify({ id, method: "Runtime.evaluate", params: { expression, awaitPromise: true, returnByValue: true } }));
+ });
+ if (reply.result?.exceptionDetails) throw new Error(reply.result.exceptionDetails.exception?.description ?? "evaluate failed");
+ return reply.result.result.value;
+ };
+ // Runs one preload IPC call in the renderer (main replies with an
+ // `{ ok, data | error }` envelope) and reports its round-trip time.
+ const invoke = (channel, payload) =>
+ evaluate(`(async () => {
+ const start = performance.now();
+ try {
+ const reply = await window.piDesktop.invoke(${JSON.stringify(channel)}, ${JSON.stringify(payload)});
+ const ms = performance.now() - start;
+ return reply.ok ? { ok: true, value: reply.data, ms } : { ok: false, error: reply.error?.message, ms };
+ } catch (error) {
+ return { ok: false, error: String(error?.message ?? error), ms: performance.now() - start };
+ }
+ })()`);
+ const retry = async (channel, payload) => {
+ let last;
+ for (let attempt = 0; attempt < 120; attempt += 1) {
+ last = await invoke(channel, payload);
+ if (last.ok) return last;
+ await delay(250);
+ }
+ throw new Error(`${channel} kept failing: ${last?.error}`);
+ };
+
+ const pastePayload = (sessionId, index) => ({
+ sessionId,
+ files: [{ name: `note-${index}.txt`, mimeType: "text/plain", data: `paste ${index}` }],
+ });
+ // ArrayBuffer data is built in the renderer; JSON cannot carry it.
+ const paste = (sessionId, index) =>
+ evaluate(`(async () => {
+ const payload = ${JSON.stringify(pastePayload(sessionId, index))};
+ payload.files = payload.files.map((file) => ({ ...file, data: new TextEncoder().encode(file.data).buffer }));
+ const start = performance.now();
+ try {
+ const reply = await window.piDesktop.invoke("pi-desktop/composer/pasteFiles", payload);
+ const ms = performance.now() - start;
+ return reply.ok ? { ok: true, value: reply.data, ms } : { ok: false, error: reply.error?.message, ms };
+ } catch (error) {
+ return { ok: false, error: String(error?.message ?? error), ms: performance.now() - start };
+ }
+ })()`);
+
+ let warm;
+ for (let attempt = 0; attempt < 120; attempt += 1) {
+ warm = await paste(session.id, "warm");
+ if (warm.ok) break;
+ await delay(250);
+ }
+ assert.ok(warm?.ok, `composer paste failed: ${warm?.error}`);
+ await retry("pi-desktop/browser/navigate", { url: pageUrl, sessionId: session.id });
+
+ // Each operation runs on the long and the short session; only the
+ // transcript size differs, so the gap is what the session lookup costs.
+ const measure = async (sessionId) => {
+ const pasteRuns = [];
+ const navigateRuns = [];
+ for (let index = 0; index < 5; index += 1) {
+ const pasted = await paste(sessionId, index);
+ assert.ok(pasted.ok, `composer paste failed: ${pasted.error}`);
+ const [file] = pasted.value.files;
+ assert.equal(await readFile(file.path, "utf8"), `paste ${index}`);
+ pasteRuns.push(pasted.ms);
+ const navigated = await retry("pi-desktop/browser/navigate", { url: `${pageUrl}?s=${sessionId}&n=${index}`, sessionId });
+ assert.ok(String(navigated.value?.url ?? "").startsWith(pageUrl), `navigate returned ${JSON.stringify(navigated.value)}`);
+ navigateRuns.push(navigated.ms);
+ }
+ return { paste: median(pasteRuns), navigate: median(navigateRuns) };
+ };
+ const shortRun = await measure(control.id);
+ const longRun = await measure(session.id);
+ console.log(
+ `desktop IPC median — paste: short ${shortRun.paste.toFixed(1)}ms / long ${longRun.paste.toFixed(1)}ms; ` +
+ `browser navigate: short ${shortRun.navigate.toFixed(1)}ms / long ${longRun.navigate.toFixed(1)}ms`,
+ );
+ // An unbounded transcript read would add at least `fullMs` to each long-session call.
+ for (const [name, gap] of [["paste", longRun.paste - shortRun.paste], ["navigate", longRun.navigate - shortRun.navigate]]) {
+ assert.ok(gap < fullMs / 2, `${name} on the long session costs ${gap.toFixed(1)}ms more; full read is ${fullMs.toFixed(1)}ms`);
+ }
+ socket.close();
+ console.log("PASS session metadata reads skip the transcript");
+} finally {
+ if (app && app.exitCode === null) {
+ app.kill("SIGTERM");
+ await Promise.race([new Promise((resolve) => app.once("exit", resolve)), delay(10_000)]);
+ if (app.exitCode === null) app.kill("SIGKILL");
+ }
+ server?.close();
+ await rm(scratch, { recursive: true, force: true, maxRetries: 3 });
+}