Skip to content

Commit aad3bbe

Browse files
Lellansinobviyus
andauthored
fix: abort HTTP gateway turns on client disconnect (#54388) (thanks @Lellansin)
* fix: abort in-flight HTTP requests on client disconnect Abort running agent commands when the HTTP client disconnects for both /v1/chat/completions and /v1/responses endpoints. - Listen on res "close" instead of req "close" (the request body is already consumed so IncomingMessage auto-destroys before we get here). - Non-streaming: guard with !signal.aborted so the abort fires on genuine disconnects; a spurious abort after sendJson is harmless. - Streaming: guard with !closed so normal res.end() completions do not abort post-turn work still in flight. - Skip error logging and response writes when the signal is already aborted. Made-with: Cursor * fix: correct event listener name and improve error handling in HTTP requests Updated the event listener for client disconnects to use the correct name and enhanced error handling logic. The changes ensure that abort signals are properly checked before logging errors and returning responses, preventing unnecessary operations on aborted requests. Made-with: Cursor * fix: use correct 'close' event name for non-streaming disconnect handler * fix: watch socket close for HTTP aborts --------- Co-authored-by: 冰森 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent e8fb140 commit aad3bbe

5 files changed

Lines changed: 289 additions & 10 deletions

File tree

‎src/gateway/http-common.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,3 +106,35 @@ export function setSseHeaders(res: ServerResponse) {
106106
res.setHeader("Connection", "keep-alive");
107107
res.flushHeaders?.();
108108
}
109+
110+
export function watchClientDisconnect(
111+
req: IncomingMessage,
112+
res: ServerResponse,
113+
abortController: AbortController,
114+
onDisconnect?: () => void,
115+
) {
116+
const sockets = Array.from(
117+
new Set(
118+
[req.socket, res.socket].filter(
119+
(socket): socket is NonNullable<typeof socket> => socket !== null,
120+
),
121+
),
122+
);
123+
if (sockets.length === 0) {
124+
return () => {};
125+
}
126+
const handleClose = () => {
127+
onDisconnect?.();
128+
if (!abortController.signal.aborted) {
129+
abortController.abort();
130+
}
131+
};
132+
for (const socket of sockets) {
133+
socket.on("close", handleClose);
134+
}
135+
return () => {
136+
for (const socket of sockets) {
137+
socket.off("close", handleClose);
138+
}
139+
};
140+
}

‎src/gateway/openai-http.test.ts‎

Lines changed: 107 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from "node:fs/promises";
2+
import http from "node:http";
23
import path from "node:path";
3-
import { afterAll, beforeAll, describe, expect, it } from "vitest";
4+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
45
import { HISTORY_CONTEXT_MARKER } from "../auto-reply/reply/history.js";
56
import { CURRENT_MESSAGE_MARKER } from "../auto-reply/reply/mentions.js";
67
import { emitAgentEvent } from "../infra/agent-events.js";
@@ -881,4 +882,109 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
881882
await server.close({ reason: "openai token auth owner test done" });
882883
}
883884
});
885+
886+
it("aborts agent command when streaming client disconnects", { timeout: 15_000 }, async () => {
887+
const port = enabledPort;
888+
let serverAbortSignal: AbortSignal | undefined;
889+
890+
agentCommand.mockClear();
891+
agentCommand.mockImplementationOnce(
892+
(opts: unknown) =>
893+
new Promise<undefined>((resolve) => {
894+
const signal = (opts as { abortSignal?: AbortSignal } | undefined)?.abortSignal;
895+
serverAbortSignal = signal;
896+
if (signal?.aborted) {
897+
resolve(undefined);
898+
return;
899+
}
900+
signal?.addEventListener("abort", () => resolve(undefined), { once: true });
901+
}),
902+
);
903+
904+
const clientReq = http.request({
905+
hostname: "127.0.0.1",
906+
port,
907+
path: "/v1/chat/completions",
908+
method: "POST",
909+
headers: {
910+
"content-type": "application/json",
911+
authorization: "Bearer secret",
912+
},
913+
});
914+
clientReq.on("error", () => {});
915+
clientReq.end(
916+
JSON.stringify({
917+
stream: true,
918+
model: "openclaw",
919+
messages: [{ role: "user", content: "hi" }],
920+
}),
921+
);
922+
923+
await vi.waitFor(() => {
924+
expect(agentCommand).toHaveBeenCalledTimes(1);
925+
});
926+
927+
clientReq.destroy();
928+
929+
await vi.waitFor(
930+
() => {
931+
expect(serverAbortSignal?.aborted).toBe(true);
932+
},
933+
{ timeout: 5_000, interval: 50 },
934+
);
935+
});
936+
937+
it(
938+
"aborts agent command when non-streaming client disconnects",
939+
{ timeout: 15_000 },
940+
async () => {
941+
const port = enabledPort;
942+
let serverAbortSignal: AbortSignal | undefined;
943+
944+
agentCommand.mockClear();
945+
agentCommand.mockImplementationOnce(
946+
(opts: unknown) =>
947+
new Promise<undefined>((resolve) => {
948+
const signal = (opts as { abortSignal?: AbortSignal } | undefined)?.abortSignal;
949+
serverAbortSignal = signal;
950+
if (signal?.aborted) {
951+
resolve(undefined);
952+
return;
953+
}
954+
signal?.addEventListener("abort", () => resolve(undefined), { once: true });
955+
}),
956+
);
957+
958+
const clientReq = http.request({
959+
hostname: "127.0.0.1",
960+
port,
961+
path: "/v1/chat/completions",
962+
method: "POST",
963+
headers: {
964+
"content-type": "application/json",
965+
authorization: "Bearer secret",
966+
},
967+
});
968+
clientReq.on("error", () => {});
969+
clientReq.end(
970+
JSON.stringify({
971+
model: "openclaw",
972+
messages: [{ role: "user", content: "hi" }],
973+
}),
974+
);
975+
976+
await vi.waitFor(() => {
977+
expect(agentCommand).toHaveBeenCalledTimes(1);
978+
});
979+
980+
clientReq.destroy();
981+
982+
await vi.waitFor(
983+
() => {
984+
expect(serverAbortSignal?.aborted).toBe(true);
985+
},
986+
{ timeout: 5_000, interval: 50 },
987+
);
988+
},
989+
);
884990
});

‎src/gateway/openai-http.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
} from "./agent-prompt.js";
2626
import type { AuthRateLimiter } from "./auth-rate-limit.js";
2727
import type { ResolvedGatewayAuth } from "./auth.js";
28-
import { sendJson, setSseHeaders, writeDone } from "./http-common.js";
28+
import { sendJson, setSseHeaders, watchClientDisconnect, writeDone } from "./http-common.js";
2929
import { handleGatewayPostJsonEndpoint } from "./http-endpoint-helpers.js";
3030
import {
3131
resolveGatewayRequestContext,
@@ -112,6 +112,7 @@ function buildAgentCommandInput(params: {
112112
runId: string;
113113
messageChannel: string;
114114
senderIsOwner: boolean;
115+
abortSignal?: AbortSignal;
115116
}) {
116117
return {
117118
message: params.prompt.message,
@@ -125,6 +126,7 @@ function buildAgentCommandInput(params: {
125126
bestEffortDeliver: false as const,
126127
senderIsOwner: params.senderIsOwner,
127128
allowModelOverride: true as const,
129+
abortSignal: params.abortSignal,
128130
};
129131
}
130132

@@ -493,6 +495,7 @@ export async function handleOpenAiHttpRequest(
493495

494496
const runId = `chatcmpl_${randomUUID()}`;
495497
const deps = createDefaultDeps();
498+
const abortController = new AbortController();
496499
const commandInput = buildAgentCommandInput({
497500
prompt: {
498501
message: prompt.message,
@@ -503,13 +506,19 @@ export async function handleOpenAiHttpRequest(
503506
sessionKey,
504507
runId,
505508
messageChannel,
509+
abortSignal: abortController.signal,
506510
senderIsOwner,
507511
});
508512

509513
if (!stream) {
514+
const stopWatchingDisconnect = watchClientDisconnect(req, res, abortController);
510515
try {
511516
const result = await agentCommandFromIngress(commandInput, defaultRuntime, deps);
512517

518+
if (abortController.signal.aborted) {
519+
return true;
520+
}
521+
513522
const content = resolveAgentResponseText(result);
514523

515524
sendJson(res, 200, {
@@ -527,10 +536,15 @@ export async function handleOpenAiHttpRequest(
527536
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
528537
});
529538
} catch (err) {
539+
if (abortController.signal.aborted) {
540+
return true;
541+
}
530542
logWarn(`openai-compat: chat completion failed: ${String(err)}`);
531543
sendJson(res, 500, {
532544
error: { message: "internal error", type: "api_error" },
533545
});
546+
} finally {
547+
stopWatchingDisconnect();
534548
}
535549
return true;
536550
}
@@ -540,6 +554,7 @@ export async function handleOpenAiHttpRequest(
540554
let wroteRole = false;
541555
let sawAssistantDelta = false;
542556
let closed = false;
557+
let stopWatchingDisconnect = () => {};
543558

544559
const unsubscribe = onAgentEvent((evt) => {
545560
if (evt.runId !== runId) {
@@ -574,14 +589,15 @@ export async function handleOpenAiHttpRequest(
574589
const phase = evt.data?.phase;
575590
if (phase === "end" || phase === "error") {
576591
closed = true;
592+
stopWatchingDisconnect();
577593
unsubscribe();
578594
writeDone(res);
579595
res.end();
580596
}
581597
}
582598
});
583599

584-
req.on("close", () => {
600+
stopWatchingDisconnect = watchClientDisconnect(req, res, abortController, () => {
585601
closed = true;
586602
unsubscribe();
587603
});
@@ -611,10 +627,10 @@ export async function handleOpenAiHttpRequest(
611627
});
612628
}
613629
} catch (err) {
614-
logWarn(`openai-compat: streaming chat completion failed: ${String(err)}`);
615-
if (closed) {
630+
if (closed || abortController.signal.aborted) {
616631
return;
617632
}
633+
logWarn(`openai-compat: streaming chat completion failed: ${String(err)}`);
618634
writeAssistantContentChunk(res, {
619635
runId,
620636
model,
@@ -629,6 +645,7 @@ export async function handleOpenAiHttpRequest(
629645
} finally {
630646
if (!closed) {
631647
closed = true;
648+
stopWatchingDisconnect();
632649
unsubscribe();
633650
writeDone(res);
634651
res.end();

‎src/gateway/openresponses-http.test.ts‎

Lines changed: 107 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from "node:fs/promises";
2+
import http from "node:http";
23
import path from "node:path";
3-
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
4+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
45
import { HISTORY_CONTEXT_MARKER } from "../auto-reply/reply/history.js";
56
import { CURRENT_MESSAGE_MARKER } from "../auto-reply/reply/mentions.js";
67
import { emitAgentEvent } from "../infra/agent-events.js";
@@ -1169,4 +1170,109 @@ describe("OpenResponses HTTP API (e2e)", () => {
11691170
await capServer.close({ reason: "responses url cap hardening test done" });
11701171
}
11711172
});
1173+
1174+
it("aborts agent command when streaming client disconnects", { timeout: 15_000 }, async () => {
1175+
const port = enabledPort;
1176+
let serverAbortSignal: AbortSignal | undefined;
1177+
1178+
agentCommand.mockClear();
1179+
agentCommand.mockImplementationOnce(
1180+
(opts: unknown) =>
1181+
new Promise<undefined>((resolve) => {
1182+
const signal = (opts as { abortSignal?: AbortSignal } | undefined)?.abortSignal;
1183+
serverAbortSignal = signal;
1184+
if (signal?.aborted) {
1185+
resolve(undefined);
1186+
return;
1187+
}
1188+
signal?.addEventListener("abort", () => resolve(undefined), { once: true });
1189+
}),
1190+
);
1191+
1192+
const clientReq = http.request({
1193+
hostname: "127.0.0.1",
1194+
port,
1195+
path: "/v1/responses",
1196+
method: "POST",
1197+
headers: {
1198+
"content-type": "application/json",
1199+
authorization: "Bearer secret",
1200+
},
1201+
});
1202+
clientReq.on("error", () => {});
1203+
clientReq.end(
1204+
JSON.stringify({
1205+
stream: true,
1206+
model: "openclaw",
1207+
input: "hi",
1208+
}),
1209+
);
1210+
1211+
await vi.waitFor(() => {
1212+
expect(agentCommand).toHaveBeenCalledTimes(1);
1213+
});
1214+
1215+
clientReq.destroy();
1216+
1217+
await vi.waitFor(
1218+
() => {
1219+
expect(serverAbortSignal?.aborted).toBe(true);
1220+
},
1221+
{ timeout: 5_000, interval: 50 },
1222+
);
1223+
});
1224+
1225+
it(
1226+
"aborts agent command when non-streaming client disconnects",
1227+
{ timeout: 15_000 },
1228+
async () => {
1229+
const port = enabledPort;
1230+
let serverAbortSignal: AbortSignal | undefined;
1231+
1232+
agentCommand.mockClear();
1233+
agentCommand.mockImplementationOnce(
1234+
(opts: unknown) =>
1235+
new Promise<undefined>((resolve) => {
1236+
const signal = (opts as { abortSignal?: AbortSignal } | undefined)?.abortSignal;
1237+
serverAbortSignal = signal;
1238+
if (signal?.aborted) {
1239+
resolve(undefined);
1240+
return;
1241+
}
1242+
signal?.addEventListener("abort", () => resolve(undefined), { once: true });
1243+
}),
1244+
);
1245+
1246+
const clientReq = http.request({
1247+
hostname: "127.0.0.1",
1248+
port,
1249+
path: "/v1/responses",
1250+
method: "POST",
1251+
headers: {
1252+
"content-type": "application/json",
1253+
authorization: "Bearer secret",
1254+
},
1255+
});
1256+
clientReq.on("error", () => {});
1257+
clientReq.end(
1258+
JSON.stringify({
1259+
model: "openclaw",
1260+
input: "hi",
1261+
}),
1262+
);
1263+
1264+
await vi.waitFor(() => {
1265+
expect(agentCommand).toHaveBeenCalledTimes(1);
1266+
});
1267+
1268+
clientReq.destroy();
1269+
1270+
await vi.waitFor(
1271+
() => {
1272+
expect(serverAbortSignal?.aborted).toBe(true);
1273+
},
1274+
{ timeout: 5_000, interval: 50 },
1275+
);
1276+
},
1277+
);
11721278
});

0 commit comments

Comments
 (0)