Skip to content

A local plugin for image-heavy chats in Codex, Claude Code and other agents: earlier images stop going out with every message, and the model fetches the one it needs by its ID, also after compaction.

fix(proxy): abort pending upstream connections on cancellation

lin-cocoab2a418f7832
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index d02908b..a90959f 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -94,14 +94,18 @@ export function macProxy(scutil: string): string | null {
return null;
}
-function connectUpstream(via: { host: string; port: number } | null, upstream = UPSTREAM_HOST): Promise<tls.TLSSocket> {
+function connectUpstream(via: { host: string; port: number } | null, upstream = UPSTREAM_HOST, signal?: AbortSignal): Promise<tls.TLSSocket> {
const startTls = (socket?: net.Socket) => new Promise<tls.TLSSocket>((ok, fail) => {
- const secure = tls.connect({ socket, host: socket ? undefined : upstream, port: 443, servername: upstream, ALPNProtocols: ["http/1.1"] }, () => ok(secure));
- secure.once("error", fail);
+ const cleanup = () => signal?.removeEventListener("abort", abort);
+ const secure = tls.connect({ socket, host: socket ? undefined : upstream, port: 443, servername: upstream, ALPNProtocols: ["http/1.1"] }, () => { cleanup(); ok(secure); });
+ const abort = () => { cleanup(); secure.destroy(); socket?.destroy(); fail(new Error("upstream connection cancelled")); };
+ secure.once("error", (error) => { cleanup(); fail(error); });
+ signal?.addEventListener("abort", abort, { once: true });
+ if (signal?.aborted) abort();
});
if (!via) return startTls();
return new Promise((ok, fail) => {
- const socket = net.connect(via.port, via.host, () => socket.write(`CONNECT ${upstream}:443 HTTP/1.1\r\nHost: ${upstream}:443\r\n\r\n`));
+ const socket = net.connect({ port: via.port, host: via.host, signal }, () => socket.write(`CONNECT ${upstream}:443 HTTP/1.1\r\nHost: ${upstream}:443\r\n\r\n`));
let buffered = Buffer.alloc(0);
const onData = (chunk: Buffer) => {
buffered = Buffer.concat([buffered, chunk]);
@@ -716,9 +720,13 @@ 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 connecting = new AbortController();
+ res.once("close", () => {
+ if (!res.writableFinished) { connecting.abort(); finish("client closed before the response ended"); }
+ });
const send = (attempts: Attempt[], at = 0): void => {
if (res.destroyed) return;
- connectUpstream(viaOf(upstream), upstream).then((socket) => {
+ connectUpstream(viaOf(upstream), upstream, connecting.signal).then((socket) => {
// The client can cancel while CONNECT/TLS is still in progress.
if (res.destroyed) { socket.destroy(); return; }
const attempt = attempts[at];
diff --git a/spike/src/proxy-http-fixture.ts b/spike/src/proxy-http-fixture.ts
index 84d0512..5cfadb0 100644
--- a/spike/src/proxy-http-fixture.ts
+++ b/spike/src/proxy-http-fixture.ts
@@ -8,7 +8,10 @@ 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;
+tls.connect = ((_options: unknown, callback: () => void) => net.connect(upstreamPort, "127.0.0.1", () => {
+ const delay = Number(process.env.CAM_TEST_CONNECT_DELAY ?? 0);
+ if (delay) setTimeout(callback, delay).unref(); else 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.ts
index 4d3587e..9eedd28 100644
--- a/spike/src/proxy-http.test.ts
+++ b/spike/src/proxy-http.test.ts
@@ -16,7 +16,7 @@ async function bounded<T>(promise: Promise<T>, message: string, ms = 2000): Prom
} finally { clearTimeout(timer!); }
}
-async function fixture(t: TestContext, handler: http.RequestListener) {
+async function fixture(t: TestContext, handler: http.RequestListener, connectDelay = 0) {
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));
@@ -26,7 +26,7 @@ async function fixture(t: TestContext, handler: http.RequestListener) {
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: "*" },
+ env: { ...process.env, CAM_DATA_DIR: root, CAM_TEST_PROXY_PORT: String(port), CAM_TEST_UPSTREAM_PORT: String(upstreamPort), CAM_TEST_CONNECT_DELAY: String(connectDelay), NO_PROXY: "*", no_proxy: "*" },
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
@@ -47,7 +47,7 @@ async function fixture(t: TestContext, handler: http.RequestListener) {
if (output.includes(`http://127.0.0.1:${port}/`)) resolve();
});
}), "synthetic engine did not start", 10000);
- return { port };
+ return { port, upstream };
}
function request(port: number) {
@@ -59,6 +59,17 @@ function request(port: number) {
return client;
}
+test("HTTP cancellation during the upstream handshake closes the pending socket", async (t) => {
+ const { port, upstream } = await fixture(t, () => assert.fail("cancelled request must not reach the upstream"), 10000);
+ const connected = new Promise<import("node:net").Socket>((resolve) => upstream.once("connection", resolve));
+ const client = request(port);
+ t.after(() => client.destroy());
+ const socket = await bounded(connected, "synthetic handshake did not start");
+ const closed = new Promise<void>((resolve) => socket.once("close", () => resolve()));
+ client.destroy();
+ await bounded(closed, "pending upstream socket stayed open after cancellation");
+});
+
test("HTTP client cancellation closes the upstream response", async (t) => {
let upstreamClosed!: () => void;
const closed = new Promise<void>((resolve) => { upstreamClosed = resolve; });