Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(images): prevent oversized tool images from breaking sessions
vastsaeb608fd2edc6
diff --git a/apps/desktop/electron/main/browser-cdp.ts b/apps/desktop/electron/main/browser-cdp.tsindex e0ceb46ab..267f7d827 100644--- a/apps/desktop/electron/main/browser-cdp.ts+++ b/apps/desktop/electron/main/browser-cdp.ts@@ -39,6 +39,7 @@ export const BROWSER_CDP_ALLOWLIST = new Set([const MAX_EVALUATE_CHARS = 64 * 1024;const MAX_CONSOLE_MESSAGES = 100;const SCREENSHOT_MAX_WIDTH = 1280;+const SCREENSHOT_MAX_HEIGHT = 2048;export type BrowserConsoleMessage = {type: string;@@ -236,7 +237,11 @@ export class BrowserCdp {const size = metrics.cssContentSize ?? metrics.contentSize ?? { width: 0, height: 0 };const width = Math.max(1, Number(size.width) || 1);const height = Math.max(1, Number(size.height) || 1);- const scale = width > SCREENSHOT_MAX_WIDTH ? SCREENSHOT_MAX_WIDTH / width : 1;+ const scale = Math.min(+ 1,+ SCREENSHOT_MAX_WIDTH / width,+ SCREENSHOT_MAX_HEIGHT / height,+ );clip = { x: 0, y: 0, width, height, scale };}const result = (await wc.debugger.sendCommand("Page.captureScreenshot", {diff --git a/apps/desktop/test/browser-capture-resize.test.mjs b/apps/desktop/test/browser-capture-resize.test.mjsindex d103a6521..006bded79 100644--- a/apps/desktop/test/browser-capture-resize.test.mjs+++ b/apps/desktop/test/browser-capture-resize.test.mjs@@ -28,6 +28,7 @@ const electron = `data:text/javascript,${encodeURIComponent(`id: WebContentsView.instances.length + 1,url: "", destroyed: false, viewport: { width: 0, height: 0 },captures: [],+ layoutSize: { width: 800, height: 6000 },async loadURL(url) {this.emit("did-start-navigation", {}, url, false, true);this.url = url;@@ -52,7 +53,7 @@ const electron = `data:text/javascript,${encodeURIComponent(`detach() { this.attached = false; },async sendCommand(method, params) {if (method === "Page.getLayoutMetrics") {- return { cssContentSize: { width: wc.viewport.width, height: 6000 } };+ return { cssContentSize: { ...wc.layoutSize } };}if (method !== "Page.captureScreenshot") return {};const savedViewport = { ...wc.viewport };@@ -116,6 +117,28 @@ function paintedBounds(view) {};}+test("full-page screenshot scales both dimensions to provider-safe limits", async (t) => {+ const { host, wc } = await harness(t);+ for (const [layoutSize, expectedScale] of [+ [{ width: 800, height: 6000 }, 2048 / 6000],+ [{ width: 4000, height: 6000 }, 1280 / 4000],+ ]) {+ wc.layoutSize = layoutSize;+ const started = once(wc, "capture-start");+ const capture = host.screenshot({ fullPage: true });+ await started;+ assert.deepEqual(wc.captures.at(-1).params.clip, {+ x: 0,+ y: 0,+ width: layoutSize.width,+ height: layoutSize.height,+ scale: expectedScale,+ });+ wc.captures.at(-1).resolve();+ await capture;+ }+});+for (const raw of [false, true]) {test(`${raw ? "raw CDP" : "browser screenshot"} stays inside the relocated panel before capture finishes`, async (t) => {const { host, wc, view } = await harness(t);diff --git a/apps/desktop/test/tool-result-images.test.mjs b/apps/desktop/test/tool-result-images.test.mjsnew file mode 100644index 000000000..25aaccda1--- /dev/null+++ b/apps/desktop/test/tool-result-images.test.mjs@@ -0,0 +1,32 @@+import assert from "node:assert/strict";+import test from "node:test";++const { normalizeToolResultImages } = await import(+ new URL(+ "../../../packages/agent-runtime/node_modules/@earendil-works/pi-coding-agent/dist/utils/tool-result-images.js",+ import.meta.url,+ ),+);++test("omits a tool image from persistent history when resizing fails", async () => {+ const image = {+ type: "image",+ data: Buffer.from("not a valid PNG").toString("base64"),+ mimeType: "image/png",+ };+ const content = [+ { type: "text", text: "Screenshot saved at /tmp/screenshot.png" },+ image,+ ];++ const normalized = await normalizeToolResultImages(content, { autoResizeImages: true });++ assert.deepEqual(normalized, [+ { type: "text", text: "Screenshot saved at /tmp/screenshot.png" },+ {+ type: "text",+ text: "[Image omitted: could not be resized below the inline image size limit.]",+ },+ ]);+ assert.equal(normalized.some((block) => block.type === "image"), false);+});diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex b8c8e9a07..c2e5edbf1 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -4682,21 +4682,27 @@ window; opening a normal panel afterward must still work.- **Preconditions**: Isolated Electron profile and a local responsive pagetaller than the visible browser viewport. No provider account is needed.-- **Steps**: Start a full-page screenshot and keep it pending while resizing- the browser hole twice. Repeat with raw `Page.captureScreenshot`. While a- capture is pending, maximize, restore, enter fullscreen, and leave fullscreen- so the panel moves or changes size. Also queue overlapping captures, switch- resource tabs, hide and restore a captured page, fail a capture, close a tab- with a queued capture, and recreate a destroyed guest.-- **Expected**: During capture, the native guest follows the panel's current- position and remains clipped within its bounds; it never covers the- conversation. Its capture-time viewport stays stable until completion, then- `innerWidth`/`innerHeight` match the latest requested bounds. Captures on one- page serialize without blocking a sibling page. Failed capture releases- resize handling. Hiding or closing a page cannot expose it or redirect its- queued capture to another page. A destroyed guest leaves no orphan native- view when it is recreated or disposed. No screenshot is repeated to repair- layout.+- **Steps**: Start a full-page screenshot for pages taller than 2048px and+ verify proportional scaling to at most 1280×2048 output pixels. Keep one+ capture pending while resizing the browser hole twice. Repeat with raw+ `Page.captureScreenshot`, which retains caller-supplied capture settings.+ While a capture is pending, maximize, restore, enter fullscreen, and leave+ fullscreen so the panel moves or changes size. Also queue overlapping+ captures, switch resource tabs, hide and restore a captured page, fail a+ capture, close a tab with a queued capture, and recreate a destroyed guest.+- **Expected**: Full-page Browser captures are proportionally bounded to+ 1280×2048; viewport captures are unchanged. During capture, the native guest+ follows the panel's current position and remains clipped within its bounds;+ it never covers the conversation. Its capture-time viewport stays stable+ until completion, then `innerWidth`/`innerHeight` match the latest requested+ bounds. Captures on one page serialize without blocking a sibling page.+ Failed capture releases resize handling. Hiding or closing a page cannot+ expose it or redirect its queued capture to another page. A destroyed guest+ leaves no orphan native view when it is recreated or disposed. No screenshot+ is repeated to repair layout.+- **Image failure recovery**: If a full-page image cannot be normalized, the tool+ result keeps its screenshot path/text and replaces the image with an omission+ message; the failed image is absent from later model requests.- **Timeout recovery**: When either screenshot API does not complete within30 seconds, it fails with `TIMEOUT`, detaches the stalled CDP session, andreleases the page queue; the next capture reattaches and can run.diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 42e4ab3ce..024d37f0b 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -846,6 +846,10 @@ session never takes focus; if it cannot become visible, `reveal()` fails with`UNAVAILABLE`. The bundled Browser agent tool calls `reveal()` before eachoperation. `BrowserPreview` remains the live-reloading workspace-file preview.+Full-page `screenshot` captures are proportionally scaled to no more than+1280×2048 output pixels. Viewport screenshots and raw `Page.captureScreenshot`+CDP calls retain their existing dimensions.+Screenshot captures, including raw `Page.captureScreenshot` CDP calls, have a30-second host-side deadline. A capture that exceeds it fails with `TIMEOUT`;the host detaches the stalled CDP session and releases that page's capturediff --git a/packages/agent-runtime/scripts/bundle-assets.test.mjs b/packages/agent-runtime/scripts/bundle-assets.test.mjsnew file mode 100644index 000000000..a4ddff600--- /dev/null+++ b/packages/agent-runtime/scripts/bundle-assets.test.mjs@@ -0,0 +1,78 @@+import { once } from "node:events";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { deflateSync } from "node:zlib";+import { Worker } from "node:worker_threads";+import { expect, it } from "vitest";+import { bundleAgentRuntime } from "./bundle.mjs";++function crc32(bytes) {+ let crc = 0xffffffff;+ for (const byte of bytes) {+ crc ^= byte;+ for (let bit = 0; bit < 8; bit += 1) {+ crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);+ }+ }+ return (crc ^ 0xffffffff) >>> 0;+}++function pngChunk(type, data) {+ const name = Buffer.from(type);+ const body = Buffer.concat([name, data]);+ const length = Buffer.alloc(4);+ length.writeUInt32BE(data.length);+ const checksum = Buffer.alloc(4);+ checksum.writeUInt32BE(crc32(body));+ return Buffer.concat([length, body, checksum]);+}++function onePixelPng() {+ const header = Buffer.alloc(13);+ header.writeUInt32BE(1, 0);+ header.writeUInt32BE(1, 4);+ header.set([8, 6, 0, 0, 0], 8);+ return Buffer.concat([+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),+ pngChunk("IHDR", header),+ pngChunk("IDAT", deflateSync(Buffer.from([0, 255, 0, 0, 255]))),+ pngChunk("IEND", Buffer.alloc(0)),+ ]);+}++it("bundles a runnable image-resize worker and its Photon WASM asset", async () => {+ const root = await mkdtemp(join(tmpdir(), "pi-runtime-image-resize-"));+ const bundle = join(root, "bundle");++ try {+ await bundleAgentRuntime(bundle);++ const workerPath = join(bundle, "chunks", "image-resize-worker.js");+ const wasm = await readFile(join(bundle, "chunks", "photon_rs_bg.wasm"));+ expect(wasm.byteLength).toBeGreaterThan(8);++ const worker = new Worker(workerPath);+ try {+ const responsePromise = once(worker, "message");+ const inputBytes = new Uint8Array(onePixelPng());+ worker.postMessage(+ {+ inputBytes,+ mimeType: "image/png",+ options: { maxWidth: 2_000, maxHeight: 2_000, maxBytes: 4.5 * 1024 * 1024 },+ },+ [inputBytes.buffer],+ );+ const [response] = await responsePromise;+ expect(response).toMatchObject({+ type: "pi:image-resize-response",+ result: { mimeType: "image/png", width: 1, height: 1, wasResized: false },+ });+ } finally {+ await worker.terminate();+ }+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/packages/agent-runtime/scripts/bundle.mjs b/packages/agent-runtime/scripts/bundle.mjsindex d00b526cd..8de9dad94 100644--- a/packages/agent-runtime/scripts/bundle.mjs+++ b/packages/agent-runtime/scripts/bundle.mjs@@ -1,13 +1,45 @@import { build } from "esbuild";+import { createRequire } from "node:module";import { randomUUID } from "node:crypto";-import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";+import { copyFile, mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";import { dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";const packageRoot = fileURLToPath(new URL("../", import.meta.url));const outputDir = join(packageRoot, "dist-bundle");++const resizeWorkerBanner = [+ "import { createRequire as __piCreateRequire } from 'node:module';",+ "import { fileURLToPath as __piFileURLToPath } from 'node:url';",+ "import { dirname as __piDirname } from 'node:path';",+ "const require = __piCreateRequire(import.meta.url);",+ "const __dirname = __piDirname(__piFileURLToPath(import.meta.url));",+].join(" ");const banner = "import { createRequire as __piCreateRequire } from 'node:module'; const require = __piCreateRequire(import.meta.url);";+async function bundleImageResizeAssets(directory) {+ const codingAgentEntry = fileURLToPath(+ import.meta.resolve("@earendil-works/pi-coding-agent"),+ );+ const codingAgentRequire = createRequire(codingAgentEntry);+ const photonEntry = codingAgentRequire.resolve("@silvia-odwyer/photon-node");+ const chunksDirectory = join(directory, "chunks");+ await mkdir(chunksDirectory, { recursive: true });+ await build({+ entryPoints: [join(dirname(codingAgentEntry), "utils/image-resize-worker.js")],+ bundle: true,+ platform: "node",+ format: "esm",+ minify: true,+ outfile: join(chunksDirectory, "image-resize-worker.js"),+ banner: { js: resizeWorkerBanner },+ });+ await copyFile(+ join(dirname(photonEntry), "photon_rs_bg.wasm"),+ join(chunksDirectory, "photon_rs_bg.wasm"),+ );+}+export async function writeBundlePackageManifest(directory) {await writeFile(join(directory, "package.json"),@@ -35,6 +67,8 @@ export async function bundleAgentRuntime(outputDir = join(packageRoot, "dist-bundefine: { PI_BUNDLED_NODE: "true" },banner: { js: banner },});++ await bundleImageResizeAssets(stagingDir);await writeBundlePackageManifest(stagingDir);try {diff --git a/patches/@[email protected] b/patches/@[email protected]index bd0b8a327..49e27f5d9 100644--- a/patches/@[email protected]+++ b/patches/@[email protected]@@ -1,5 +1,5 @@diff --git a/dist/core/agent-session.js b/dist/core/agent-session.js-index c5ad719..63f78d1 100644+index c5ad71905832cac59341cff04729260936dfba77..63f78d1464e21638ba569b0c24fd1723c56d3b54 100644--- a/dist/core/agent-session.js+++ b/dist/core/agent-session.js@@ -69,10 +69,10 @@ function withoutDeletedHeaders(headers) {@@ -93,7 +93,7 @@ index c5ad719..63f78d1 100644return {tokens: estimate.tokens,diff --git a/dist/core/bug-report.js b/dist/core/bug-report.js-index bc4af31..24a4f8e 100644+index bc4af31b57f4a8696a68d4f2a529a26669955382..24a4f8e28624523112cac6c73464e93fb650f03a 100644--- a/dist/core/bug-report.js+++ b/dist/core/bug-report.js@@ -232,12 +232,12 @@ Numbered list, as specific as the transcript allows.@@ -121,7 +121,7 @@ index bc4af31..24a4f8e 100644const prompt = [messages.length < options.messages.lengthdiff --git a/dist/core/compaction/branch-summarization.d.ts b/dist/core/compaction/branch-summarization.d.ts-index 12cb88e..6ff7356 100644+index 12cb88ef5398b2365d5823597b7ccf063af567d6..6ff73567bbd5289b8b3f2fb82f923a5b5dc7860e 100644--- a/dist/core/compaction/branch-summarization.d.ts+++ b/dist/core/compaction/branch-summarization.d.ts@@ -6,7 +6,7 @@@@ -143,7 +143,7 @@ index 12cb88e..6ff7356 100644* Generate a summary of abandoned branch entries.*diff --git a/dist/core/compaction/branch-summarization.js b/dist/core/compaction/branch-summarization.js-index 3f98859..b68f7ad 100644+index 3f98859ddbc6de3b6075c08557fe396a61d1814e..b68f7adb1fd2145a6a0d1e74af05065d25c7925b 100644--- a/dist/core/compaction/branch-summarization.js+++ b/dist/core/compaction/branch-summarization.js@@ -95,7 +95,7 @@ function getMessageFromEntry(entry) {@@ -174,7 +174,7 @@ index 3f98859..b68f7ad 100644return { summary: "No content to summarize" };}diff --git a/dist/core/compaction/compaction.d.ts b/dist/core/compaction/compaction.d.ts-index 04416da..fdf79d9 100644+index 04416da43184fce4dc2fc33afeb920e2edddedc9..fdf79d9f200e78178aa46020341c7295024734a5 100644--- a/dist/core/compaction/compaction.d.ts+++ b/dist/core/compaction/compaction.d.ts@@ -6,7 +6,7 @@@@ -229,7 +229,7 @@ index 04416da..fdf79d9 100644* Generate summaries for compaction using prepared data.* Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.diff --git a/dist/core/compaction/compaction.js b/dist/core/compaction/compaction.js-index e4992e8..0797ad5 100644+index e4992e8d2bff8aa6d2a4b044c9cf571d9e7f2fa2..0797ad50e267863a32adf27cbc2d7037e07dcb21 100644--- a/dist/core/compaction/compaction.js+++ b/dist/core/compaction/compaction.js@@ -4,8 +4,10 @@@@ -424,7 +424,7 @@ index e4992e8..0797ad5 100644if (!firstKeptEntry?.id)return undefined;diff --git a/dist/core/compaction/utils.js b/dist/core/compaction/utils.js-index 92ee18e..ef4df76 100644+index 92ee18e6a99c46dd5fc6b249a6cf670938f5f963..ef4df7671fc2a2b778ede9e485eb03fc49ebc3a8 100644--- a/dist/core/compaction/utils.js+++ b/dist/core/compaction/utils.js@@ -2,6 +2,7 @@@@ -467,3 +467,21 @@ index 92ee18e..ef4df76 100644}else if (msg.role === "toolResult") {const content = contentText(msg.content, "");+diff --git a/dist/utils/tool-result-images.js b/dist/utils/tool-result-images.js+index 37d8a2474d425e6ac8648745c02d1a247244cbd3..b194f69e3d5073a4c5177a0dfb2b67104eec5814 100644+--- a/dist/utils/tool-result-images.js++++ b/dist/utils/tool-result-images.js+@@ -27,10 +27,9 @@ export async function normalizeToolResultImages(content, options) {+ resizeOptions: options?.resizeOptions,+ });+ if (!processed.ok) {+- // Unlike `read`, keep the original block. The tool already produced this image and the+- // failure may just be an unavailable image backend, so passing it through preserves the+- // behavior tools have today instead of silently deleting their output.+- normalized.push(block);++ // A failed resize must not leave an unprocessable image in persistent history.++ normalized.push({ type: "text", text: processed.message });++ changed = true;+ continue;+ }+ if (processed.data === block.data && processed.mimeType === block.mimeType && processed.hints.length === 0) {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a70af1457..1ac3e20d5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -207,7 +207,7 @@ overrides:patchedDependencies:'@earendil-works/[email protected]': a2c96619d0f9a1d643a6c6a555ba6a7fb533147336c181f7d3b7f847be33a6eb'@earendil-works/[email protected]': 2aa7a30fca930a08ebdff65f82d2fc47aeb1cd941d34aae2e50e13b309ef2705- '@earendil-works/[email protected]': a2878f6aa1d66afa239d6be4252403a73df48b702b3e582aaae04bd90bf3d354+ '@earendil-works/[email protected]': 73b8776451352deeaa307306b1aaa3a22e2c2cfd6e06c802fcd390409912f60aimporters:@@ -432,7 +432,7 @@ importers:version: 1.1.0(patch_hash=2aa7a30fca930a08ebdff65f82d2fc47aeb1cd941d34aae2e50e13b309ef2705)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-coding-agent':specifier: 1.1.0- version: 1.1.0(patch_hash=a2878f6aa1d66afa239d6be4252403a73df48b702b3e582aaae04bd90bf3d354)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])+ version: 1.1.0(patch_hash=73b8776451352deeaa307306b1aaa3a22e2c2cfd6e06c802fcd390409912f60a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])'@pi-desktop/shared':specifier: workspace:*version: link:../shared@@ -5304,7 +5304,7 @@ snapshots:dependencies:quickjs-wasi: 3.6.2- '@earendil-works/[email protected](patch_hash=a2878f6aa1d66afa239d6be4252403a73df48b702b3e582aaae04bd90bf3d354)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':+ '@earendil-works/[email protected](patch_hash=73b8776451352deeaa307306b1aaa3a22e2c2cfd6e06c802fcd390409912f60a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':dependencies:'@earendil-works/chord': 1.1.0'@earendil-works/pi-agent-core': 1.1.0(patch_hash=a2c96619d0f9a1d643a6c6a555ba6a7fb533147336c181f7d3b7f847be33a6eb)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])