Stop paying the multimodal tax. Your AI agent keeps every image it has seen but only sends the ones it needs: lighter chats, no endless reconnecting, no starting over. Works with Codex, Claude Code, Cline, Gemini CLI, OpenCode, WorkBuddy and more. Install once, forget it.
TypeScript ai-agentsai-imageclaude-codeclaude-code-pluginclinecodexcodex-plugincomputer-usecontext-engineeringcontext-managementdeveloper-toolsgemini-cliimage-generationmcpmultimodalmultimodal-aiopencodeqwen-codetoken-optimizationvision-language-model
fix(proxy): propagate HTTP cancellation and stream failures
lin-cocod7584aedcbaf
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.tsindex 86675d2..d02908b 100644--- a/plugin/src/proxy.ts+++ b/plugin/src/proxy.ts@@ -716,7 +716,11 @@ async function main(): Promise<void> {// thinking after the changed history (thinkingRejected) moves on to the next one (see ClaudeAttempt), the last being// the original as Claude Code built it; the statistics say which went out (the panel shows a fallback).type Attempt = { body: Buffer | null; report: Json | null; edited: boolean } & Partial<Pick<ClaudeAttempt, "history" | "sent" | "made" | "sure">>;- const send = (attempts: Attempt[], at = 0): void => { connectUpstream(viaOf(upstream), upstream).then((socket) => {+ const send = (attempts: Attempt[], at = 0): void => {+ if (res.destroyed) return;+ connectUpstream(viaOf(upstream), upstream).then((socket) => {+ // The client can cancel while CONNECT/TLS is still in progress.+ if (res.destroyed) { socket.destroy(); return; }const attempt = attempts[at];const outgoing = forwardHeaders(req.headers, upstream);if (attempt.body) outgoing["content-length"] = String(attempt.body.length);@@ -732,7 +736,7 @@ async function main(): Promise<void> {if (at < attempts.length - 1 && status === 400) {const parts: Buffer[] = [];answer.on("data", (chunk: Buffer) => parts.push(chunk));- answer.on("error", (error) => finish(String(error)));+ answer.on("error", (error) => { finish(String(error)); res.destroy(error); });answer.on("end", () => {const raw = Buffer.concat(parts);const text = decodeBody(raw, answer.headers["content-encoding"] as string | undefined)?.toString("utf8") ?? "";@@ -774,16 +778,22 @@ async function main(): Promise<void> {}finish();});- answer.on("error", (error) => finish(String(error)));+ // A partial response cannot be ended as if it were complete: propagate the broken stream to Codex.+ answer.on("error", (error) => { finish(String(error)); res.destroy(error); });+ });+ outbound.on("error", (error) => { if (!res.destroyed) { if (!res.headersSent) res.writeHead(502); res.end(); } finish(String(error)); });+ // Log once, and release the upstream stream when the client no longer consumes it.+ res.on("close", () => {+ if (!res.writableFinished) outbound.destroy();+ finish(res.writableFinished ? undefined : "client closed before the response ended");});- outbound.on("error", (error) => { if (!res.headersSent) res.writeHead(502); res.end(); finish(String(error)); });- // Codex may drop the connection mid-stream; still log the request once.- res.on("close", () => finish(res.writableFinished ? undefined : "client closed before the response ended"));if (attempt.body) outbound.end(attempt.body);else { collect(); req.pipe(outbound); }}, (error) => {- res.writeHead(502, { "content-type": "text/plain" });- res.end(`codex-attachment-manager proxy: cannot reach ${upstream}`);+ if (!res.destroyed) {+ res.writeHead(502, { "content-type": "text/plain" });+ res.end(`codex-attachment-manager proxy: cannot reach ${upstream}`);+ }finish(String(error));}); };if (!rewrite && !claudeRewrite) { send([{ body: null, report: null, edited: false }]); return; }diff --git a/spike/src/proxy-http-fixture.ts b/spike/src/proxy-http-fixture.tsnew file mode 100644index 0000000..84d0512--- /dev/null+++ b/spike/src/proxy-http-fixture.ts@@ -0,0 +1,14 @@+// A test-only transport: run the real engine against a plaintext loopback upstream.+// No credentials, real conversations, external TLS connections, or production hooks are used.+import net from "node:net";+import tls from "node:tls";+import { fileURLToPath } from "node:url";++const upstreamPort = Number(process.env.CAM_TEST_UPSTREAM_PORT);+if (!upstreamPort) throw new Error("missing synthetic upstream port");+// The proxy uses http.request over an already-connected TLS socket. A plain local socket exercises the same HTTP+// lifecycle; only the TLS handshake is replaced, in this isolated child process.+tls.connect = ((_options: unknown, callback: () => void) => net.connect(upstreamPort, "127.0.0.1", callback)) as typeof tls.connect;+const script = fileURLToPath(new URL("../../plugin/src/proxy.ts", import.meta.url));+process.argv = [process.execPath, script, "--stay", "--port", process.env.CAM_TEST_PROXY_PORT!];+await import(script);diff --git a/spike/src/proxy-http.test.ts b/spike/src/proxy-http.test.tsnew file mode 100644index 0000000..4d3587e--- /dev/null+++ b/spike/src/proxy-http.test.ts@@ -0,0 +1,117 @@+// Real loopback HTTP tests for the engine's cancellation and broken-response handling.+// The child fixture replaces only the outbound TLS handshake; no remote service or model is contacted.+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdtempSync, rmSync } from "node:fs";+import http from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test, { type TestContext } from "node:test";+import { fileURLToPath } from "node:url";++async function bounded<T>(promise: Promise<T>, message: string, ms = 2000): Promise<T> {+ let timer: NodeJS.Timeout;+ try {+ return await Promise.race([promise, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); })]);+ } finally { clearTimeout(timer!); }+}++async function fixture(t: TestContext, handler: http.RequestListener) {+ const root = mkdtempSync(join(tmpdir(), "cam-http-lifecycle-"));+ const upstream = http.createServer(handler);+ await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));+ const upstreamPort = (upstream.address() as { port: number }).port;+ const reservation = http.createServer();+ await new Promise<void>((resolve) => reservation.listen(0, "127.0.0.1", resolve));+ const port = (reservation.address() as { port: number }).port;+ await new Promise<void>((resolve) => reservation.close(() => resolve()));+ const child = spawn(process.execPath, [fileURLToPath(new URL("./proxy-http-fixture.ts", import.meta.url))], {+ env: { ...process.env, CAM_DATA_DIR: root, CAM_TEST_PROXY_PORT: String(port), CAM_TEST_UPSTREAM_PORT: String(upstreamPort), NO_PROXY: "*", no_proxy: "*" },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ child.stderr.on("data", (chunk) => { output += chunk; });+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));+ t.after(async () => {+ child.kill();+ await bounded(exited, "synthetic engine did not exit");+ upstream.closeAllConnections();+ await new Promise<void>((resolve) => upstream.close(() => resolve()));+ rmSync(root, { recursive: true, force: true });+ });+ await bounded(new Promise<void>((resolve, reject) => {+ child.on("error", reject);+ child.on("exit", (code) => reject(new Error(`synthetic engine exited (${code}): ${output}`)));+ child.stdout.on("data", (chunk) => {+ output += chunk;+ if (output.includes(`http://127.0.0.1:${port}/`)) resolve();+ });+ }), "synthetic engine did not start", 10000);+ return { port };+}++function request(port: number) {+ const body = JSON.stringify({ input: [] });+ const client = http.request({ hostname: "127.0.0.1", port, path: "/backend-api/codex/responses", method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) } });+ // A cancelled stream is allowed to surface as a reset. Individual tests assert its observable lifecycle.+ client.on("error", () => {});+ client.end(body);+ return client;+}++test("HTTP client cancellation closes the upstream response", async (t) => {+ let upstreamClosed!: () => void;+ const closed = new Promise<void>((resolve) => { upstreamClosed = resolve; });+ const { port } = await fixture(t, (req, res) => {+ req.resume();+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.write("data: synthetic\n\n");+ res.once("close", upstreamClosed);+ });+ const client = request(port);+ t.after(() => client.destroy());+ await bounded(new Promise<void>((resolve) => {+ client.once("response", (response) => {+ response.once("data", () => { response.destroy(); client.destroy(); resolve(); });+ });+ }), "client did not receive synthetic data");+ await bounded(closed, "upstream stayed open after client cancellation");+});++test("a truncated upstream HTTP response closes the client stream", async (t) => {+ let drop!: () => void;+ const { port } = await fixture(t, (req, res) => {+ req.resume();+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.write("data: incomplete\n\n");+ drop = () => res.destroy();+ });+ const client = request(port);+ t.after(() => client.destroy());+ await bounded(new Promise<void>((resolve) => {+ client.once("response", (response) => {+ response.on("error", () => {});+ response.once("close", resolve);+ response.once("data", () => drop());+ });+ }), "client hung after the upstream response broke");+});++test("a complete HTTP response keeps its status, headers, and bytes", async (t) => {+ const expected = Buffer.from([0, 255, 10, 128, 42]);+ const { port } = await fixture(t, (req, res) => {+ req.resume();+ res.writeHead(201, { "content-type": "application/octet-stream", "x-synthetic": "unchanged" });+ res.end(expected);+ });+ const client = request(port);+ const result = await bounded(new Promise<{ status: number; header: unknown; body: Buffer }>((resolve, reject) => {+ client.once("response", (response) => {+ const chunks: Buffer[] = [];+ response.on("data", (chunk) => chunks.push(chunk));+ response.on("error", reject);+ response.on("end", () => resolve({ status: response.statusCode!, header: response.headers["x-synthetic"], body: Buffer.concat(chunks) }));+ });+ }), "complete response did not finish");+ assert.deepEqual(result, { status: 201, header: "unchanged", body: expected });+});