Skip to content

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

fix(agent-runtime): validate large image base64 without regex recursion

zszz37120625b9ef4
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7a36ba428..9e70527b3 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -18656,10 +18656,14 @@ the latest destination. These assertions measure work counts, not device FPS.
the test settings API to verify recovery. Generate same-prompt variants and
distinct images; confirm each result appears once in the conversation gallery
while the assistant confirms completion in text. Edit a generated image,
- inspect partial failures, then restart the host/session. Attempt the tool in a
- durable Plan session and verify no HTTP request occurs.
+ inspect partial failures, then restart the host/session. Return a
+ multi-megabyte `b64_json` image (well above 5.5M base64 characters, below
+ the image size cap). Attempt the tool in a durable Plan session and verify no
+ HTTP request occurs.
- **Expected:** One image binding persists without changing the chat default;
generated files, edit sources and transcript references survive restart.
+ The large image is saved byte-for-byte instead of failing with
+ `IMAGE_REQUEST_FAILED` (#2128).
Each successful image appears once in its result card instead of being
repeated as a Markdown embed; unconfigured errors navigate to Models settings.
- **Specs:** 03-runtime/21-image-generation; 03-runtime/13-model-catalog-and-selection.
diff --git a/packages/agent-runtime/src/image-generation/openai-images.test.ts b/packages/agent-runtime/src/image-generation/openai-images.test.ts
new file mode 100644
index 000000000..9fe8c206d
--- /dev/null
+++ b/packages/agent-runtime/src/image-generation/openai-images.test.ts
@@ -0,0 +1,61 @@
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { afterEach, describe, expect, it } from "vitest";
+import { decodeImageBase64 } from "./openai-images.js";
+import { generateTestImage } from "./test-fixture.js";
+
+const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9mQAAAAASUVORK5CYII=", "base64");
+
+/** A PNG-signed payload whose base64 is well past the size that overflowed the old validator (#2128). */
+function largePng(): Buffer {
+ return Buffer.concat([png, Buffer.alloc(6 * 1024 * 1024, 0x5a)]);
+}
+
+const servers: ReturnType<typeof createServer>[] = [];
+afterEach(async () => { await Promise.all(servers.splice(0).map(server => new Promise<void>((resolve) => server.close(() => resolve())))); });
+
+describe("decodeImageBase64", () => {
+ it("decodes a large payload without overflowing the stack (#2128)", () => {
+ const bytes = largePng();
+ const encoded = bytes.toString("base64");
+ expect(encoded.length).toBeGreaterThan(8_000_000);
+ expect(Buffer.from(decodeImageBase64(encoded)).equals(bytes)).toBe(true);
+ });
+
+ it.each(["QUJD", "QUJDRA==", "QUJDREU="])("accepts padded base64 %s", (data) => {
+ expect(Buffer.from(decodeImageBase64(data))).toEqual(Buffer.from(data, "base64"));
+ });
+
+ it.each([
+ "", // empty payload
+ "QQ", // unpadded short quantum
+ "QUI", // unpadded short quantum
+ "QUJD!A==", // character outside the alphabet
+ "QU=DRA==", // padding before the end
+ "QUJ===", // three padding characters
+ "Q===", // three padding characters in one quantum
+ "QUJDR", // incomplete quantum
+ "QUJD RA==", // whitespace
+ "QUJD-A==", // base64url alphabet
+ "====", // padding only
+ ])("rejects malformed base64 %s", (data) => {
+ expect(() => decodeImageBase64(data)).toThrow(expect.objectContaining({ errorCode: "IMAGE_INVALID_RESPONSE" }));
+ });
+});
+
+it("saves a large b64_json image returned by an OpenAI Images endpoint (#2128)", async () => {
+ const bytes = largePng();
+ const server = createServer(async (req, res) => {
+ for await (const _chunk of req) { /* drain the request body */ }
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ data: [{ b64_json: bytes.toString("base64") }] }));
+ });
+ servers.push(server);
+ await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
+ const baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`;
+
+ const image = await generateTestImage({ baseUrl, modelId: "gpt-image-1.5" }, "A cup", new AbortController().signal);
+
+ expect(image.mimeType).toBe("image/png");
+ expect(Buffer.from(image.bytes).equals(bytes)).toBe(true);
+});
diff --git a/packages/agent-runtime/src/image-generation/openai-images.ts b/packages/agent-runtime/src/image-generation/openai-images.ts
index cd70dd709..0554dd633 100644
--- a/packages/agent-runtime/src/image-generation/openai-images.ts
+++ b/packages/agent-runtime/src/image-generation/openai-images.ts
@@ -144,7 +144,10 @@ export function openAIImagesAdapter(
export function decodeImageBase64(data: string): Uint8Array {
if (data.length > Math.ceil(MAX_IMAGE_BYTES / 3) * 4) throw imageError("IMAGE_TOO_LARGE");
- if (!data.length || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data))
+ // Whole quanta of the standard alphabet with at most two trailing `=`. The
+ // length check stands in for a repeated 4-char group, which V8 matches
+ // recursively and overflows the stack on multi-megabyte images (#2128).
+ if (!data.length || data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(data))
throw imageError("IMAGE_INVALID_RESPONSE");
return Buffer.from(data, "base64");
}
diff --git a/scripts/e2e-image-generation.mjs b/scripts/e2e-image-generation.mjs
index efaf9d1bc..1c8688a0b 100644
--- a/scripts/e2e-image-generation.mjs
+++ b/scripts/e2e-image-generation.mjs
@@ -18,14 +18,17 @@ const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9mQAAAAASUVORK5CYII=",
"base64",
);
+// A PNG-signed payload whose base64 (~8.4M chars) overflowed the old validator (#2128).
+const largePng = Buffer.concat([png, Buffer.alloc(6 * 1024 * 1024, 0x5a)]);
+const LARGE_PROMPT = "large upscale";
let requests = 0;
const server = createServer(async (request, response) => {
- for await (const _chunk of request) {
- /* Drain the bounded fixture request. */
- }
+ const chunks = [];
+ for await (const chunk of request) chunks.push(chunk);
requests++;
+ const image = Buffer.concat(chunks).includes(LARGE_PROMPT) ? largePng : png;
response.setHeader("Content-Type", "application/json");
- response.end(JSON.stringify({ data: [{ b64_json: png.toString("base64") }] }));
+ response.end(JSON.stringify({ data: [{ b64_json: image.toString("base64") }] }));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
// Only the LLM edge is simulated; reverse RPC, authorization and execution are real.
@@ -85,6 +88,10 @@ try {
const edited = await execute(session.id, [{ prompt: "green background", images: [source] }]);
assert.equal(edited.ok, true, JSON.stringify(edited));
assert.notEqual(edited.content.results[0].path, source);
+ const large = await execute(session.id, [{ prompt: LARGE_PROMPT }]);
+ assert.equal(large.ok, true, JSON.stringify(large).slice(0, 2000));
+ assert.equal(large.content.results[0].status, "succeeded", JSON.stringify(large.content.results[0]));
+ assert.ok((await readFile(large.content.results[0].path)).equals(largePng));
await host.call("session.appendMessage", {
sessionId: session.id,
message: {
@@ -104,7 +111,7 @@ try {
});
const denied = await execute(plan.id, [{ prompt: "must not run" }]);
assert.equal(denied.ok, false);
- assert.equal(requests, 4);
+ assert.equal(requests, 5);
await host.restart();
const restored = await host.call("settings.get");
assert.deepEqual(restored.imageGeneration, binding);
@@ -117,7 +124,7 @@ try {
(await execute(session.id, [{ prompt: "unset" }])).errorCode,
"IMAGE_NOT_CONFIGURED",
);
- assert.equal(requests, 4);
+ assert.equal(requests, 5);
console.log(
JSON.stringify({
ok: true,
@@ -125,6 +132,7 @@ try {
scenarios: [
"batch-generation",
"edit-result",
+ "large-image-result",
"host-plan-denial",
"settings-and-transcript-restart",
"clear-binding",