Skip to content

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

fix(amsp): 取消的消息流当场停住,缓冲区里的事件不再交付

lmliheng73942f9f35e0
diff --git a/changelog/unreleased/2026-10-28-amsp-cancel-buffered-events.md b/changelog/unreleased/2026-10-28-amsp-cancel-buffered-events.md
new file mode 100644
index 00000000..2029f2ff
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-amsp-cancel-buffered-events.md
@@ -0,0 +1,43 @@
+# A cancelled AMSP stream stops at once, buffered events included
+
+- **Date:** 2026-10-28
+- **Type:** fix
+- **Scope:** `amsp`
+- **Breaking:** no
+
+[中文](2026-10-28-amsp-cancel-buffered-events.zh.md)
+
+Ported from PenguinHarness `ca7114a2` (`#1326`).
+
+`readSse`/`sseData` only looked at the abort signal after pulling a chunk from the network. A caller
+that aborts from its own loop body — the loop runs while the generator is suspended at `yield` — was
+therefore not seen until the next chunk arrived, and everything already parsed out of the current
+chunk was still dispatched. A `[DONE]` buffered behind the last event ended the read quietly, so
+`AgentClient` reported a run the caller had cancelled as `completed`, and the events after the abort
+reached the caller anyway.
+
+The signal is now checked right after each event is dispatched. The next read rejects with the
+caller's own abort reason before another buffered event is handled, and `AgentClient` checks the
+signal once more where its read loop ends without an error: a cancelled run is never reported as one
+that completed. No constructor, wire record, on-disk format or endpoint changes; a stream that is
+read to its end behaves exactly as before.
+
+## Details
+
+- `packages/amsp/src/sse.ts`: after `yield event`, `if (signal?.aborted) throw signal.reason` —
+ the check next to `reader.read()` cannot see an abort that happens while the generator is
+ suspended, which is exactly when a caller's loop body runs.
+- `packages/amsp/src/client.ts`: `AgentRun.#drive` checks `control.signal.aborted` after the read
+ loop, before `collector.result()` — the buffered `[DONE]` ends the loop with no error at all, so
+ the existing `catch` never saw it.
+- `packages/amsp/test/sse.test.ts`: two abort cases (an abort between two events of one chunk, and
+ one before a buffered `[DONE]`), plus a contract guard for an abort after the event at the end of
+ the body.
+- `packages/amsp/test/client.test.ts`: a run whose chunk carries `run.done` + `[DONE]`, aborted in
+ the loop body — the iteration and `result()` both reject with `signal.reason`.
+
+## Compatibility
+
+- No dependency, API, wire-protocol or stored-data change. A run whose signal aborts after the
+ stream finished normally is still not undone by it; only a cancellation that lands before the
+ stream ends now takes precedence over the outcome it happened to reach.
diff --git a/changelog/unreleased/2026-10-28-amsp-cancel-buffered-events.zh.md b/changelog/unreleased/2026-10-28-amsp-cancel-buffered-events.zh.md
new file mode 100644
index 00000000..efd64f83
--- /dev/null
+++ b/changelog/unreleased/2026-10-28-amsp-cancel-buffered-events.zh.md
@@ -0,0 +1,35 @@
+# 取消的 AMSP 消息流当场停住,缓存的事件也不再交付
+
+- **Date:** 2026-10-28
+- **Type:** fix
+- **Scope:** `amsp`
+- **Breaking:** no
+
+[English](2026-10-28-amsp-cancel-buffered-events.md)
+
+移植自 PenguinHarness `ca7114a2`(`#1326`)。
+
+`readSse`/`sseData` 只在从网络拉到一个数据块之后才看 abort 信号。于是在自己循环体里取消的调用方
+(循环体正好在生成器挂在 `yield` 时运行)要等到下一个数据块到达才被发现,而当前数据块里已经解析出来的事件
+照样交付。跟在最后一条事件后面的 `[DONE]` 会把这次读取平静地结束掉 —— 于是 `AgentClient` 把调用方已经取消的
+run 报成 `completed`,取消之后的那些事件也还是送到了调用方手上。
+
+现在每交付一条事件之后立刻检查信号。下一次读取会在处理下一个缓存事件之前,用调用方自己的取消原因抛出去;
+`AgentClient` 在它的读取循环无错结束时再检查一次信号:取消的 run 永远不会被报成完成。构造参数、线上记录、
+磁盘格式与端点都没变;读到结尾的流与以前完全一致。
+
+## 细节
+
+- `packages/amsp/src/sse.ts`:`yield event` 之后 `if (signal?.aborted) throw signal.reason` ——
+ 挨着 `reader.read()` 的那次检查看不到生成器挂起期间发生的取消,而调用方的循环体恰好在那一刻运行。
+- `packages/amsp/src/client.ts`:`AgentRun.#drive` 在读取循环之后、`collector.result()` 之前检查
+ `control.signal.aborted` —— 缓存的 `[DONE]` 让循环不带任何错误地结束,既有的 `catch` 根本看不到它。
+- `packages/amsp/test/sse.test.ts`:两条取消用例(同一数据块两条事件之间取消、缓存 `[DONE]` 之前取消),
+ 外加一条契约守卫:正文最后一条事件交付之后取消,下一次读取仍要抛。
+- `packages/amsp/test/client.test.ts`:一个数据块里同时带 `run.done` 与 `[DONE]`,在循环体里取消 ——
+ 迭代与 `result()` 都以 `signal.reason` 拒绝。
+
+## 兼容性
+
+- 不改依赖、接口、线上协议与已存数据。流正常结束之后才发生的取消仍不会撤销已完成的 run;
+ 只有落在流结束之前的取消,现在优先于它恰好走到的那个结果。
diff --git a/packages/amsp/src/client.ts b/packages/amsp/src/client.ts
index bfcfc095..7d3c883b 100644
--- a/packages/amsp/src/client.ts
+++ b/packages/amsp/src/client.ts
@@ -273,6 +273,10 @@ class AgentRun implements Run {
});
}
}
+ // The loop can end without an error although the caller aborted: a `[DONE]` already parsed
+ // out of the chunk it was reading ends the loop normally. A cancelled run is not one that
+ // completed, so it rejects here rather than with the outcome it happened to reach.
+ if (control.signal.aborted) throw control.signal.reason;
const result = collector.result();
this.#end({ ok: true });
return result;
diff --git a/packages/amsp/src/sse.ts b/packages/amsp/src/sse.ts
index 238545b0..704aac65 100644
--- a/packages/amsp/src/sse.ts
+++ b/packages/amsp/src/sse.ts
@@ -10,7 +10,9 @@
* character anywhere. An event is dispatched at the blank line that closes it; one the body ends
* in the middle of is dropped, since its data may be cut short. Comment lines (`: keep-alive`)
* and every field but `data` are skipped. The body is read to its end, or cancelled — the
- * connection closed — when the caller stops iterating early.
+ * connection closed — when the caller stops iterating early. Once the signal aborts, the read
+ * rejects with its reason before another event is dispatched, even one already buffered in the
+ * chunk being parsed.
*
* `[DONE]` is AMSP's end-of-stream marker; it is yielded like any other data, so a caller stops
* there.
@@ -22,7 +24,8 @@ export function readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<string
/**
* {@link readSse}, cancellable: once `signal` aborts, the body is cancelled and the read rejects
* with the signal's reason, whether or not the `fetch` that produced the body honours the signal
- * itself.
+ * itself. An abort between two events of the same chunk is seen at the next read, so the events
+ * after it — a buffered `[DONE]` included — are not dispatched.
*/
export async function* sseData(
body: ReadableStream<Uint8Array>,
@@ -77,6 +80,12 @@ export async function* sseData(
const event = data.join("\n");
data = null;
yield event;
+ // The signal is checked after `read()` above, which misses an abort that happens
+ // while this generator is suspended at `yield` — the caller's loop body runs in
+ // between. The rest of the chunk is already parsed, so without this check the
+ // events after the abort (a buffered `[DONE]` included) are still delivered, and a
+ // cancelled run reads as one that completed.
+ if (signal?.aborted) throw signal.reason;
}
continue;
}
diff --git a/packages/amsp/test/client.test.ts b/packages/amsp/test/client.test.ts
index 85951747..ac9b3a86 100644
--- a/packages/amsp/test/client.test.ts
+++ b/packages/amsp/test/client.test.ts
@@ -48,6 +48,9 @@
* - Aborting the signal mid-stream closes the connection and rejects with the signal's AbortError,
* whether the fetch errors the body itself or leaves it to the reader.
* - The iteration stops at once when the signal aborts, and events not yet read are dropped.
+ * - A signal that aborts between two events of one chunk rejects the run with the abort reason,
+ * even when the next event buffered behind it is `[DONE]`: a cancelled run is never reported as
+ * completed.
* - A signal that aborts as the response arrives rejects without waiting for the stream; one
* aborted before the run sends nothing.
* - run.abort() asks the server to abort and the stream ends with run.done aborted; on a run that
@@ -677,6 +680,29 @@ describe("aborting", () => {
expect(seen).toEqual(["run.started", "request.started", "text.delta"]);
});
+ // One chunk carries both the last event and `[DONE]`, and the caller aborts in between: the
+ // buffered `[DONE]` used to end the read quietly, so the run resolved `completed`.
+ it("rejects a run aborted before a buffered [DONE] instead of reporting it completed", async () => {
+ const served = fake.stream("POST", RUNS, [frame(started) + frame(runDone()) + DONE, never()]);
+ const controller = new AbortController();
+ const run = client.run({ input: "hi", signal: controller.signal });
+
+ const seen: string[] = [];
+ const iteration = (async () => {
+ for await (const event of run) {
+ seen.push(event.type);
+ if (event.type === "run.done") controller.abort();
+ }
+ })();
+
+ const error = await iteration.catch((err: unknown) => err);
+
+ expect(error).toBe(controller.signal.reason);
+ expect(seen).toEqual(["run.started", "run.done"]);
+ await expect(run.result()).rejects.toBe(controller.signal.reason);
+ expect(served.closed).toBe(true);
+ });
+
it("drops the events not yet read when the signal aborts while the reader lags behind", async () => {
fake.stream("POST", RUNS, [...PLAIN.slice(0, 4).map(frame), never()]);
const controller = new AbortController();
diff --git a/packages/amsp/test/sse.test.ts b/packages/amsp/test/sse.test.ts
index 6668c8ac..49352664 100644
--- a/packages/amsp/test/sse.test.ts
+++ b/packages/amsp/test/sse.test.ts
@@ -10,9 +10,14 @@
* events that arrived.
* - Given a caller that stops after the first event, the body is cancelled: the connection
* closes rather than being read on.
+ * - Given an abort between two events of one chunk, the next read rejects with the abort reason
+ * and the events buffered behind it are not dispatched, a buffered `[DONE]` included.
+ * - Given an abort after the last event of the body was dispatched, the next read rejects rather
+ * than completing.
*/
import { describe, expect, it } from "vitest";
import { readSse } from "../src/index.js";
+import { sseData } from "../src/sse.js";
const encoder = new TextEncoder();
@@ -117,4 +122,46 @@ describe("readSse", () => {
}
expect(cancelled).toBe(true);
});
+
+ // The caller's loop body runs while the generator is suspended at `yield`, so an abort there
+ // arrives without a read to notice it: the rest of the chunk is already parsed and must not be
+ // dispatched.
+ it("rejects an abort between events without delivering the rest of the chunk", async () => {
+ const control = new AbortController();
+ const reason = new Error("Stopped by the caller");
+ const events = sseData(body("data: first\n\ndata: second\n\n"), control.signal);
+ try {
+ expect((await events.next()).value).toBe("first");
+ control.abort(reason);
+ await expect(events.next()).rejects.toBe(reason);
+ } finally {
+ await events.return(undefined);
+ }
+ });
+
+ it("rejects an abort on a buffered [DONE] rather than ending the read", async () => {
+ const control = new AbortController();
+ const reason = new Error("Stopped before DONE");
+ const events = sseData(body("data: keep\n\ndata: [DONE]\n\n"), control.signal);
+ try {
+ expect((await events.next()).value).toBe("keep");
+ control.abort(reason);
+ await expect(events.next()).rejects.toBe(reason);
+ } finally {
+ await events.return(undefined);
+ }
+ });
+
+ it("rejects an abort after the event at the end of the body instead of completing", async () => {
+ const control = new AbortController();
+ const reason = new Error("Stopped at EOF");
+ const events = sseData(body("data: final\n\n"), control.signal);
+ try {
+ expect((await events.next()).value).toBe("final");
+ control.abort(reason);
+ await expect(events.next()).rejects.toBe(reason);
+ } finally {
+ await events.return(undefined);
+ }
+ });
});