Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(cli): a dropped response body cannot end the command

lmliheng8ba92f074eb6
diff --git a/changelog/unreleased/2026-11-11-cli-discarded-body-cancel.md b/changelog/unreleased/2026-11-11-cli-discarded-body-cancel.md
new file mode 100644
index 00000000..022f4262
--- /dev/null
+++ b/changelog/unreleased/2026-11-11-cli-discarded-body-cancel.md
@@ -0,0 +1,18 @@
+# A dropped response body no longer ends the whole command
+
+- **Date:** 2026-11-11
+- **Type:** fix
+- **Scope:** `cli`
+- **Breaking:** no
+
+[中文版](2026-11-11-cli-discarded-body-cancel.zh.md)
+
+Five places in the CLI let go of a response body nobody was going to read with `void res.body?.cancel()`: an empty `request()` answer, the `401` token refresh, both halves of the `human_required` retry, and every readiness probe `penguin server` fires while waiting for the listener. `cancel()` rejects whenever the stream is already errored — a connection that died mid-body, a body a timeout had already aborted — and the CLI installs no `unhandledRejection` handler, so Node's default ends the process for it. A command that only meant to drop a body would die instead, on its own rejection, with nothing in the message to say which.
+
+They all go through one `discardBody(res)` now, which swallows that rejection. The server's own drop sites (`model-balance`, `plugin-download`, `theme-download`, `proxy-probe`) have always done exactly this, and so does the CLI's SSE reader; these five were the outliers.
+
+The window is narrow — the drop follows the headers almost immediately, so the stream has to error in between — but it is not empty: the `401` path reads the token file, and the `human_required` retry reads a clone of the body, both between the response arriving and the drop.
+
+## Verification
+
+`test/discard-body.test.ts` (new, 4 cases) and one case in `test/serve.test.ts` pin the drop sites by counting what actually reaches the process: an errored body, a cleanly cancelled one, a bodyless response, `request()` on a `content-length: 0` answer whose body errored, and a readiness probe whose body was left errored — each resolves and leaves an `unhandledRejection` listener with nothing. Reverted to the old form, two of them go red with exactly that escape in hand.
diff --git a/changelog/unreleased/2026-11-11-cli-discarded-body-cancel.zh.md b/changelog/unreleased/2026-11-11-cli-discarded-body-cancel.zh.md
new file mode 100644
index 00000000..056aadcc
--- /dev/null
+++ b/changelog/unreleased/2026-11-11-cli-discarded-body-cancel.zh.md
@@ -0,0 +1,26 @@
+# 被丢掉的响应体不再让整条命令崩掉
+
+- **日期:** 2026-11-11
+- **类型:** 修复
+- **范围:** `cli`
+- **破坏性变更:** 否
+
+[English](2026-11-11-cli-discarded-body-cancel.md)
+
+CLI 里有五处这样丢掉一个没人会读的响应体:`request()` 的空答复、`401` 后的换 token、`human_required` 重试的
+两半,以及 `penguin server` 等监听器时每一下就绪探测。`cancel()` 在流**已经出错**时自己会拒绝 —— 连接中途
+断掉、响应体已被超时中止 —— 而 CLI 没有装 `unhandledRejection` 处理,Node 的默认行为就此结束整个进程:
+一条只想把响应体丢掉的命令,会死在自己的拒绝上,报错里还看不出是哪里。
+
+这五处现在都走一个 `discardBody(res)`,把这个拒绝吞掉。服务端自己的丢弃点(`model-balance`、
+`plugin-download`、`theme-download`、`proxy-probe`)一直是这么写的,CLI 的 SSE 读取器也是;漏掉的正是这五处。
+
+窗口很窄 —— 丢弃紧跟响应头,流要在这一瞬间已经出错 —— 但不是空的:`401` 那条在响应到达与丢弃之间读一次
+token 文件,`human_required` 重试那条在中间读一次克隆体。
+
+## 验证
+
+`test/discard-body.test.ts`(新增,4 条)与 `test/serve.test.ts` 里的一条,按「真正到进程的东西」来钉这些
+丢弃点:出错的身体、正常取消的身体、没有身体的响应、`content-length: 0` 且身体已出错的 `request()`、以及
+身体被留成出错状态的就绪探测 —— 它们都正常返回,而 `unhandledRejection` 监听器手里一条都没有。退回改前的
+写法,其中两条正以这条逃逸变红。
diff --git a/packages/cli/src/client.ts b/packages/cli/src/client.ts
index fd1b0959..783aa13c 100644
--- a/packages/cli/src/client.ts
+++ b/packages/cli/src/client.ts
@@ -245,6 +245,18 @@ export class ApiError extends Error {
}
}
+/**
+ * Lets go of a response body nobody is going to read. `cancel()` itself rejects whenever the
+ * stream is already errored — a connection that died mid-body, a probe the readiness timeout
+ * aborted — and the CLI installs no unhandled-rejection handler, so Node's default ends the
+ * process for it: a command that only meant to drop a body would die instead of carrying on.
+ * The server's own drop sites (model-balance, plugin-download, theme-download, proxy-probe)
+ * all swallow this already; the SSE reader below does the same for its reader.
+ */
+export function discardBody(res: Response): void {
+ void res.body?.cancel().catch(() => undefined);
+}
+
export class ServerClient {
private token: string | null;
private tokenSource: TokenSource;
@@ -287,7 +299,7 @@ export class ServerClient {
});
if (!res.ok) throw await this.toError(res);
if (res.status === 204 || res.headers.get("content-length") === "0") {
- void res.body?.cancel();
+ discardBody(res);
return undefined as T;
}
const text = await res.text();
@@ -310,7 +322,7 @@ export class ServerClient {
if (this.tokenSource === "env" || !this.conn.loopback) return res;
const fresh = readTokenFile(this.conn.root);
if (fresh === null || fresh === this.token) return res;
- void res.body?.cancel();
+ discardBody(res);
this.token = fresh;
this.tokenSource = "file";
const headers = { ...(init.headers as Record<string, string>), ...this.headers() };
@@ -339,10 +351,10 @@ export class ServerClient {
}
const retried = await fetch(`${this.conn.baseUrl}${apiPath}`, { ...init, headers });
if (retried.status === 401) {
- void retried.body?.cancel();
+ discardBody(retried);
return refused;
}
- void refused.body?.cancel();
+ discardBody(refused);
return retried;
}
diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts
index 427b2a5e..ca6f0162 100644
--- a/packages/cli/src/commands/serve.ts
+++ b/packages/cli/src/commands/serve.ts
@@ -31,6 +31,7 @@ import path from "node:path";
import { DEFAULT_SERVER_PORT, SERVER_RESTART_EXIT_CODE, resolveRoot } from "@adelie/core";
import { liveServerLock } from "@adelie/server/lock";
import type { Command } from "commander";
+import { discardBody } from "../client.js";
import type { Messages, WebProbeFailureKind } from "../i18n.js";
import { registerResetPasswordCommand } from "./reset-password.js";
import { registerStatusCommand } from "./server-status.js";
@@ -317,7 +318,7 @@ export async function waitForReady(
// (127.0.0.1 is reserved for previews); the probe only needs to know the port answers,
// so treat that 302 as ready rather than chasing it to a name that may resolve to ::1.
const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(1000) });
- void res.body?.cancel();
+ discardBody(res);
return { ready: true };
} catch (error) {
// The service isn't listening yet (or this probe timed out): retain the reason and keep polling.
diff --git a/packages/cli/test/discard-body.test.ts b/packages/cli/test/discard-body.test.ts
new file mode 100644
index 00000000..3b1b3dec
--- /dev/null
+++ b/packages/cli/test/discard-body.test.ts
@@ -0,0 +1,94 @@
+/**
+ * Discarding a response body nobody reads. `cancel()` rejects whenever the stream is already
+ * errored — a connection that died mid-body, a probe the readiness timeout aborted — and the
+ * CLI installs no unhandled-rejection handler, so Node's default ends the process for it: a
+ * command that only meant to drop a body dies instead. These pin that the drop sites swallow
+ * it, measured by counting what actually reaches the process.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ServerClient, discardBody, resolveConnection } from "../src/client.js";
+import { getMessages } from "../src/i18n.js";
+
+const t = getMessages("en");
+
+const ENV_KEYS = ["ADELIE_API_URL", "ADELIE_API_TOKEN", "PENGUIN_HOME", "ADELIE_PROJECT_ID"];
+const saved = new Map<string, string | undefined>();
+
+beforeEach(() => {
+ for (const key of ENV_KEYS) {
+ saved.set(key, process.env[key]);
+ delete process.env[key];
+ }
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const [key, value] of saved) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+/** A response whose body is already errored, as a dropped connection or an aborted probe leaves it. */
+function erroredResponse(status = 200, headers: Record<string, string> = {}): Response {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.error(new Error("terminated"));
+ },
+ });
+ return new Response(body, { status, headers });
+}
+
+/**
+ * What reaches the process as an unhandled rejection while `run` is in flight. Node reports
+ * one on a later turn than the one that rejected, so the guard waits two turns before reading.
+ */
+async function rejectionsDuring(run: () => void | Promise<unknown>): Promise<unknown[]> {
+ const seen: unknown[] = [];
+ const onRejection = (reason: unknown) => seen.push(reason);
+ process.on("unhandledRejection", onRejection);
+ try {
+ await run();
+ await new Promise((resolve) => setImmediate(resolve));
+ await new Promise((resolve) => setImmediate(resolve));
+ return seen;
+ } finally {
+ process.off("unhandledRejection", onRejection);
+ }
+}
+
+describe("discardBody", () => {
+ it("drops an errored body without letting its rejection escape", async () => {
+ const seen = await rejectionsDuring(() => discardBody(erroredResponse()));
+ expect(seen).toEqual([]);
+ });
+
+ it("drops a body that cancels cleanly too", async () => {
+ const seen = await rejectionsDuring(() =>
+ discardBody(new Response(new Blob(["x"]), { status: 200 })),
+ );
+ expect(seen).toEqual([]);
+ });
+
+ it("is a no-op for a bodyless response", async () => {
+ const seen = await rejectionsDuring(() => discardBody(new Response(null, { status: 204 })));
+ expect(seen).toEqual([]);
+ });
+});
+
+describe("a dropped body on the request paths", () => {
+ it("request() on an empty answer still resolves when the body errored", async () => {
+ const client = new ServerClient(
+ await resolveConnection({ server: "http://127.0.0.1:7002" }, t),
+ t,
+ );
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(erroredResponse(200, { "content-length": "0" }));
+
+ const seen = await rejectionsDuring(async () => {
+ await expect(client.request("POST", "/api/sessions/x/abort")).resolves.toBeUndefined();
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(seen).toEqual([]);
+ });
+});
diff --git a/packages/cli/test/serve.test.ts b/packages/cli/test/serve.test.ts
index 653cd21a..f1aa4342 100644
--- a/packages/cli/test/serve.test.ts
+++ b/packages/cli/test/serve.test.ts
@@ -151,6 +151,32 @@ describe("readiness probe diagnostics", () => {
});
});
+ it("reports ready for a probe whose body was left errored, without a stray rejection", async () => {
+ // The 1s AbortSignal on each probe produces exactly this: headers arrived, then the
+ // connection died (or the timeout fired) before anyone read the body, so the stream is
+ // errored and its cancel() rejects. A CLI with no unhandled-rejection handler would die.
+ const errored = new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.error(new Error("The operation was aborted due to timeout"));
+ },
+ }),
+ { status: 200 },
+ );
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(errored);
+ const seen: unknown[] = [];
+ const onRejection = (reason: unknown) => seen.push(reason);
+ process.on("unhandledRejection", onRejection);
+ try {
+ await expect(waitForReady("http://127.0.0.1:7364/", 0, 0)).resolves.toEqual({ ready: true });
+ await new Promise((resolve) => setImmediate(resolve));
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(seen).toEqual([]);
+ } finally {
+ process.off("unhandledRejection", onRejection);
+ }
+ });
+
it("retains the nested undici error from the last failed probe", async () => {
const cause = Object.assign(new Error("Connect Timeout Error"), {
code: "UND_ERR_CONNECT_TIMEOUT",