Skip to content

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

fix(images): preserve RPC failures and image format compatibility

Jacka0ab265fa4d6
diff --git a/docs/spec/03-runtime/21-image-generation.md b/docs/spec/03-runtime/21-image-generation.md
index 831a9fa8b..09896f474 100644
--- a/docs/spec/03-runtime/21-image-generation.md
+++ b/docs/spec/03-runtime/21-image-generation.md
@@ -51,6 +51,11 @@ explicit path prefix is retained. Generation uses `POST images/generations` with
the prompt, model and `n: 1`. No browser mask editor is included. A configured
service may implement generation without editing; its error is reported without
silently switching to generation or another model.
+For exact DALL-E 2/3 model IDs, generation requests explicitly ask for
+`response_format: b64_json`; the same form field is used for DALL-E edits where
+supported. GPT Image and unknown compatible model IDs omit that parameter.
+Editing retains binary multipart uploads (`image` for one reference, `image[]`
+for multiple), with the transport generating the Content-Type boundary.
Each batch snapshots the binding and provider before dispatch, uses two workers,
and returns results in input order. Each output has a 180-second request budget.
@@ -72,6 +77,10 @@ Each result records index, status (`succeeded`, `failed`, `cancelled`), successf
path/MIME type or a safe error code. New files get unique names in session scratch;
editing never overwrites its source. The tool result and transcript retain file
references, not Base64. Existing bounded image reads and file viewers serve previews.
+Thrown local-tool errors preserve stable `errorCode` values across the real
+sidecar RPC boundary, independently of ordinary structured tool-result failures.
+Existing RPC code, message and data are retained; arbitrary Error properties
+are not serialized. The sidecar receiver exposes the code alongside its data.
Successful images and per-item failures render even when only part of a batch
completed. Missing configuration returns a structured error and a Settings → Models
navigation action. The same references render after session reload/restart.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 964130016..f06ef8899 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -27,6 +27,12 @@
- **Conversation selection:** The selected image provider/model is absent from
default and Composer candidates. Other providers retain same-ID models. An
existing session pinned to the image binding is rejected before inference.
+- **Transport contracts:** Real stdio reverse RPC retains a thrown local image
+ error's stable code in the production ParentHostProxy. Local HTTP tests check
+ single/multiple binary multipart fields and boundaries, DALL-E `b64_json`
+ requests, GPT Image parameter omission, bounded responses, and rejection of
+ more than four references before I/O. These are protocol tests, not official
+ provider account/live compatibility certification.
- **Status:** Automated in `node scripts/e2e-image-chat.mjs`; optional screenshots
use `PI_IMAGE_CHAT_EVIDENCE_DIR`. The images are deterministic raster fixtures,
not evidence of real-model quality or provider compatibility.
diff --git a/packages/agent-runtime/src/image-generation/index.ts b/packages/agent-runtime/src/image-generation/index.ts
index bf1ffb694..7d437411e 100644
--- a/packages/agent-runtime/src/image-generation/index.ts
+++ b/packages/agent-runtime/src/image-generation/index.ts
@@ -46,12 +46,17 @@ export async function generateOneImage(
const headers = new Headers(endpoint.headers);
headers.set("Content-Type", "application/json");
if (endpoint.apiKey) headers.set("Authorization", `Bearer ${endpoint.apiKey}`);
- let body: BodyInit = JSON.stringify({ model: endpoint.modelId, prompt, n: 1 });
+ const responseFormat = /^dall-e-[23]$/i.test(endpoint.modelId) ? "b64_json" : undefined;
+ let body: BodyInit = JSON.stringify({
+ model: endpoint.modelId, prompt, n: 1,
+ ...(responseFormat ? { response_format: responseFormat } : {}),
+ });
if (images.length) {
const form = new FormData();
form.set("model", endpoint.modelId);
form.set("prompt", prompt);
form.set("n", "1");
+ if (responseFormat) form.set("response_format", responseFormat);
images.forEach((image, index) =>
form.append(
images.length === 1 ? "image" : "image[]",
diff --git a/packages/agent-runtime/src/image-generation/openai-images-contract.test.ts b/packages/agent-runtime/src/image-generation/openai-images-contract.test.ts
new file mode 100644
index 000000000..477f59f03
--- /dev/null
+++ b/packages/agent-runtime/src/image-generation/openai-images-contract.test.ts
@@ -0,0 +1,91 @@
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { afterEach, expect, it } from "vitest";
+import { generateImageBatch, generateOneImage, type ImageEditInput } from "./index.js";
+
+const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9mQAAAAASUVORK5CYII=", "base64");
+const input: ImageEditInput = { bytes: png, mimeType: "image/png", extension: "png" };
+const servers: ReturnType<typeof createServer>[] = [];
+afterEach(async () => { await Promise.all(servers.splice(0).map(server => new Promise<void>((resolve) => server.close(() => resolve())))); });
+
+async function fixture() {
+ const requests: Array<{ path: string; body: Record<string, unknown> | FormData; type: string }> = [];
+ const failures: unknown[] = [];
+ const server = createServer(async (req, res) => {
+ try {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
+ const raw = Buffer.concat(chunks);
+ const type = String(req.headers["content-type"]);
+ const body = type.startsWith("multipart/form-data")
+ ? await new Request("http://localhost", { method: "POST", headers: { "content-type": type }, body: raw }).formData()
+ : JSON.parse(raw.toString());
+ requests.push({ path: req.url ?? "", body, type });
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ data: [{ b64_json: png.toString("base64") }] }));
+ } catch (error) { failures.push(error); res.writeHead(400); res.end(); }
+ });
+ 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`;
+ return { requests, failures, call: (modelId: string, images: ImageEditInput[] = []) => generateOneImage({ baseUrl, modelId }, "A cup", new AbortController().signal, fetch, images) };
+}
+
+it("requests b64_json for DALL-E without sending response_format to GPT Image", async () => {
+ const f = await fixture();
+ for (const model of ["dall-e-2", "dall-e-3", "gpt-image-1.5", "gpt-image-2.5"]) {
+ expect((await f.call(model)).bytes).toEqual(png);
+ const request = f.requests.at(-1)!;
+ expect(request.path).toBe("/v1/images/generations");
+ expect(request.body).toEqual({ model, prompt: "A cup", n: 1, ...(model.startsWith("dall-e-") ? { response_format: "b64_json" } : {}) });
+ }
+ expect(f.failures).toEqual([]);
+});
+
+it("sends real multipart edits with boundary, binary files and model-specific response format", async () => {
+ const f = await fixture();
+ for (const [model, images] of [["gpt-image-1.5", [input]], ["gpt-image-2.5", [input, input]], ["gpt-image-2.5", [input, input, input, input]], ["dall-e-2", [input]]] as const) {
+ expect((await f.call(model, [...images])).bytes).toEqual(png);
+ const request = f.requests.at(-1)!;
+ expect(request.path).toBe("/v1/images/edits");
+ expect(request.type).toMatch(/^multipart\/form-data; boundary=/);
+ expect(request.body).toBeInstanceOf(FormData);
+ const form = request.body as FormData;
+ expect(form.get("model")).toBe(model);
+ expect(form.get("prompt")).toBe("A cup");
+ expect(form.get("n")).toBe("1");
+ expect(form.get("response_format")).toBe(model === "dall-e-2" ? "b64_json" : null);
+ const files = form.getAll(images.length === 1 ? "image" : "image[]");
+ expect(files).toHaveLength(images.length);
+ for (const file of files) {
+ expect(file).toBeInstanceOf(Blob);
+ expect((file as Blob).type).toBe("image/png");
+ expect(Buffer.from(await (file as Blob).arrayBuffer())).toEqual(png);
+ }
+ }
+ expect(f.failures).toEqual([]);
+});
+
+it("rejects more than four reference images before reading files or sending HTTP", async () => {
+ let reads = 0, requests = 0;
+ await expect(generateImageBatch({
+ input: { items: [{ prompt: "cup", images: ["1.png", "2.png", "3.png", "4.png", "5.png"] }] },
+ endpoint: { baseUrl: "https://example.invalid", modelId: "gpt-image-2.5" },
+ signal: new AbortController().signal,
+ loadImages: async () => { reads++; return [input]; },
+ fetchImpl: async () => { requests++; return new Response(); },
+ save: async () => "unused",
+ })).rejects.toMatchObject({ errorCode: "INVALID_ARGUMENT" });
+ expect({ reads, requests }).toEqual({ reads: 0, requests: 0 });
+});
+
+it("does not leak provider error bodies and bounds JSON before decoding", async () => {
+ for (const status of [401, 403, 429, 500]) {
+ await expect(generateOneImage({ baseUrl: "https://example.invalid", modelId: "gpt-image-2.5" }, "cup", new AbortController().signal,
+ async () => new Response("private upstream token", { status }),
+ )).rejects.toMatchObject({ errorCode: [401, 403].includes(status) ? "IMAGE_AUTH_FAILED" : `IMAGE_HTTP_${status}` });
+ }
+ await expect(generateOneImage({ baseUrl: "https://example.invalid", modelId: "gpt-image-2.5" }, "cup", new AbortController().signal,
+ async () => new Response("", { headers: { "content-length": "999999999" } }),
+ )).rejects.toMatchObject({ errorCode: "IMAGE_TOO_LARGE" });
+});
diff --git a/packages/agent-runtime/src/parent-host-proxy.test.ts b/packages/agent-runtime/src/parent-host-proxy.test.ts
index 45e19f645..839295dcd 100644
--- a/packages/agent-runtime/src/parent-host-proxy.test.ts
+++ b/packages/agent-runtime/src/parent-host-proxy.test.ts
@@ -14,6 +14,21 @@ describe("ParentHostProxy RPC deadlines", () => {
vi.restoreAllMocks();
});
+ it("exposes the stable error code received from the host", async () => {
+ const stdout = stubStdout();
+ const proxy = new ParentHostProxy();
+ try {
+ const pending = proxy.call("tools.execute", { toolName: "GenerateImages" });
+ const request = JSON.parse(String(stdout.mock.calls.at(-1)?.[0]));
+ proxy.handleParentMessage({ id: request.id, error: {
+ code: -32000, message: "Denied", data: { errorCode: "PERMISSION_DENIED" },
+ } });
+ await expect(pending).rejects.toMatchObject({
+ code: -32000, errorCode: "PERMISSION_DENIED", data: { errorCode: "PERMISSION_DENIED" },
+ });
+ } finally { await proxy.dispose(); stdout.mockRestore(); }
+ });
+
it("honors a per-call timeout", async () => {
vi.useFakeTimers();
const stdout = stubStdout();
diff --git a/packages/agent-runtime/src/parent-host-proxy.ts b/packages/agent-runtime/src/parent-host-proxy.ts
index 167a3575f..f44991993 100644
--- a/packages/agent-runtime/src/parent-host-proxy.ts
+++ b/packages/agent-runtime/src/parent-host-proxy.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { rpcTimeoutMs } from "@pi-desktop/shared";
+import { rpcErrorFromWire, rpcTimeoutMs } from "@pi-desktop/shared";
export type ParentHostCloseHandler = (error: Error) => void;
@@ -62,9 +62,7 @@ export class ParentHostProxy {
this.pending.delete(String(msg.id));
if (pending.timer) clearTimeout(pending.timer);
if (msg.error) {
- const err = new Error(msg.error.message) as Error & { data?: unknown };
- err.data = msg.error.data;
- pending.reject(err);
+ pending.reject(rpcErrorFromWire(msg.error));
} else {
pending.resolve(msg.result);
}
diff --git a/packages/host-runtime/src/agent-sidecar.ts b/packages/host-runtime/src/agent-sidecar.ts
index 3b35323ef..f27168052 100644
--- a/packages/host-runtime/src/agent-sidecar.ts
+++ b/packages/host-runtime/src/agent-sidecar.ts
@@ -1,6 +1,6 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { randomUUID } from "node:crypto";
-import { DEFAULT_RPC_TIMEOUT_MS, IMAGE_BATCH_TIMEOUT_MS, imageGenerationPrompts, readNdjsonLines, rpcTimeoutMs } from "@pi-desktop/shared";
+import { DEFAULT_RPC_TIMEOUT_MS, IMAGE_BATCH_TIMEOUT_MS, imageGenerationPrompts, readNdjsonLines, rpcTimeoutMs, rpcErrorFromWire, rpcErrorToWire } from "@pi-desktop/shared";
import type { ProcessExitHandler, StderrHandler } from "./host-process.js";
// stderr lines kept per sidecar so an unexpected exit can be reported with the
@@ -567,16 +567,12 @@ export class AgentSidecar {
this.writeToChild(
JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
);
- } catch (e: any) {
+ } catch (e: unknown) {
this.writeToChild(
JSON.stringify({
jsonrpc: "2.0",
id: msg.id,
- error: {
- code: e?.code ?? -32000,
- message: e instanceof Error ? e.message : String(e),
- data: e?.data,
- },
+ error: rpcErrorToWire(e),
}) + "\n",
);
}
@@ -589,13 +585,7 @@ export class AgentSidecar {
this.pending.delete(String(msg.id));
if (pending.timer) clearTimeout(pending.timer);
if (msg.error) {
- const err = new Error(msg.error.message) as Error & {
- code?: number;
- data?: unknown;
- };
- err.code = msg.error.code;
- err.data = msg.error.data;
- pending.reject(err);
+ pending.reject(rpcErrorFromWire(msg.error));
} else {
pending.resolve(msg.result);
}
diff --git a/packages/host-runtime/src/image-generation-bridge.test.ts b/packages/host-runtime/src/image-generation-bridge.test.ts
index d35ac2b58..7eeb8e8cc 100644
--- a/packages/host-runtime/src/image-generation-bridge.test.ts
+++ b/packages/host-runtime/src/image-generation-bridge.test.ts
@@ -10,9 +10,9 @@ const sidecars: AgentSidecar[] = [];
afterEach(async () => {
await Promise.all(sidecars.splice(0).map((sidecar) => sidecar.dispose()));
});
-function harness(allowed = true) {
+function harness(allowed = true, childSource = child, esm = false) {
const sidecar = new AgentSidecar({
- launch: { command: process.execPath, args: ["-e", child] },
+ launch: { command: process.execPath, args: [...(esm ? ["--input-type=module"] : []), "-e", childSource] },
onStderr: () => {},
});
sidecars.push(sidecar);
@@ -50,6 +50,42 @@ it("authorizes image calls through the host before executing the local handler",
expect(calls).toEqual(["tools.execute", "generated"]);
});
+it("preserves stable local error codes through real reverse RPC", async () => {
+ const { sidecar, execute } = harness();
+ sidecar.setLocalTool("GenerateImages", async () => {
+ throw Object.assign(new Error("Image request failed"), {
+ errorCode: "IMAGE_TIMEOUT", data: { retryable: false }, secret: "must-not-cross",
+ });
+ });
+ await expect(execute()).rejects.toMatchObject({
+ code: -32000, errorCode: "IMAGE_TIMEOUT",
+ data: { errorCode: "IMAGE_TIMEOUT", retryable: false },
+ });
+});
+
+it("delivers stable error codes to the production ParentHostProxy in a real child", async () => {
+ const receiverUrl = new URL("../../agent-runtime/src/parent-host-proxy.ts", import.meta.url).href;
+ const source = `
+ import { createInterface } from 'node:readline';
+ const { ParentHostProxy } = await import(${JSON.stringify(receiverUrl)});
+ const proxy = new ParentHostProxy();
+ createInterface({input:process.stdin}).on('line', async line => {
+ const message = JSON.parse(line);
+ if (proxy.handleParentMessage(message)) return;
+ try {
+ const result = await proxy.call(message.params.method, message.params.params);
+ console.log(JSON.stringify({id:message.id,result}));
+ } catch (error) {
+ console.log(JSON.stringify({id:message.id,result:{code:error.code,errorCode:error.errorCode,data:error.data}}));
+ }
+ });`;
+ const { sidecar, execute } = harness(true, source, true);
+ sidecar.setLocalTool("GenerateImages", async () => {
+ throw Object.assign(new Error("limited"), { errorCode: "IMAGE_HTTP_429" });
+ });
+ expect(await execute()).toEqual({ code: -32000, errorCode: "IMAGE_HTTP_429", data: { errorCode: "IMAGE_HTTP_429" } });
+});
+
it("denied and Plan calls never reach the image service", async () => {
const { sidecar, execute } = harness(false);
const generate = vi.fn().mockResolvedValue({ ok: true, content: "image" });
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index bf6fc44b9..6d4a8b34b 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1,6 +1,7 @@
export * from "./activation.js";
export * from "./protocol.js";
export * from "./errors.js";
+export * from "./rpc-error.js";
export * from "./certificate-errors.js";
export * from "./types.js";
export * from "./transcript-truncation.js";
diff --git a/packages/shared/src/rpc-error.test.ts b/packages/shared/src/rpc-error.test.ts
new file mode 100644
index 000000000..005faea76
--- /dev/null
+++ b/packages/shared/src/rpc-error.test.ts
@@ -0,0 +1,23 @@
+import { expect, it } from "vitest";
+import { rpcErrorFromWire, rpcErrorToWire } from "./rpc-error.js";
+
+it("retains stable codes and existing metadata without copying private properties", () => {
+ const wire = rpcErrorToWire(Object.assign(new Error("Denied"), {
+ code: -32602, errorCode: "PERMISSION_DENIED", data: { retryable: false },
+ apiKey: "private-test-key",
+ }));
+ expect(wire).toEqual({ code: -32602, message: "Denied", data: { retryable: false, errorCode: "PERMISSION_DENIED" } });
+ expect(JSON.stringify(wire)).not.toContain("private-test-key");
+ expect(rpcErrorFromWire(wire)).toMatchObject({ code: -32602, errorCode: "PERMISSION_DENIED", data: wire.data });
+});
+
+it("keeps an existing nested code authoritative and preserves legacy data", () => {
+ const existing = { errorCode: "HOST_OVERLOADED", retryAfterMs: 100 };
+ expect(rpcErrorToWire(Object.assign(new Error("busy"), { errorCode: "GENERIC", data: existing })).data).toEqual(existing);
+ for (const data of [null, "legacy", [1, 2]]) {
+ const wire = rpcErrorToWire(Object.assign(new Error("failed"), { data, errorCode: "IMAGE_FAILED" }));
+ expect(wire.data).toEqual(data);
+ expect(rpcErrorFromWire(wire).errorCode).toBe("IMAGE_FAILED");
+ }
+ expect(rpcErrorToWire(new Error("ordinary"))).toEqual({ code: -32000, message: "ordinary", data: undefined });
+});
diff --git a/packages/shared/src/rpc-error.ts b/packages/shared/src/rpc-error.ts
new file mode 100644
index 000000000..a14158f8e
--- /dev/null
+++ b/packages/shared/src/rpc-error.ts
@@ -0,0 +1,42 @@
+export type RpcErrorValue = {
+ code: number;
+ message: string;
+ data?: unknown;
+ errorCode?: string;
+};
+
+function record(value: unknown): Record<string, unknown> | undefined {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown> : undefined;
+}
+
+function stableCode(error: Record<string, unknown> | undefined): string | undefined {
+ const nested = record(error?.data)?.errorCode;
+ return typeof nested === "string" ? nested
+ : typeof error?.errorCode === "string" ? error.errorCode : undefined;
+}
+
+/** Preserve wire data and copy only established fields, not arbitrary Error properties. */
+export function rpcErrorToWire(error: unknown): RpcErrorValue {
+ const value = record(error);
+ const errorCode = stableCode(value);
+ const data = value?.data;
+ return {
+ code: typeof value?.code === "number" ? value.code : -32000,
+ message: error instanceof Error ? error.message : String(error),
+ data: errorCode && (data === undefined || record(data))
+ ? { ...record(data), errorCode } : data,
+ // Legacy scalar/array data keeps its shape, with an additive error code.
+ ...(errorCode && data !== undefined && !record(data) ? { errorCode } : {}),
+ };
+}
+
+export function rpcErrorFromWire(value: RpcErrorValue): Error & {
+ code: number; data?: unknown; errorCode?: string;
+} {
+ const errorCode = stableCode(value);
+ return Object.assign(new Error(value.message), {
+ code: value.code, data: value.data,
+ ...(errorCode ? { errorCode } : {}),
+ });
+}