Multiplayer agent harness for work.
fix: confirm stopped runs and soften collapsed prompts (#1137)
Joshua France361a6c0095dc
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex bbfb60c0b..4fc1d2959 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -199,7 +199,9 @@ export function createChatSurface(ctx: ConvCtx,dependencies: { fetchTranscript?: typeof fetchTranscript; openSession?: typeof openSession } = {},): ChatSurface {- const runSlot = createRunSlot();+ const runSlot = createRunSlot((message) => {+ ctx.composer.state.error = message;+ });const transcriptViewport = createTranscriptViewport();const transcriptFetcher = dependencies.fetchTranscript ?? fetchTranscript;const sessionOpener = dependencies.openSession ?? openSession;@@ -586,21 +588,21 @@ export function createChatSurface(}async function stopLiveRun(): Promise<void> {- if (!hasLiveRun(runSlot)) {- requestStop(runSlot);- return;- }+ if (runSlot.stopGeneration === runSlot.generation) return;const agent = chatState.agent;- const revealUnstoppedRun = (): void => {- runSlot.unreachedAbort = true;- if (agent && agent === chatState.agent && !agent.state.isStreaming) void refreshTranscriptFromEntries(agent);- };+ const generation = runSlot.generation;+ requestStop(runSlot);+ drawActiveChat();+ if (!hasLiveRun(runSlot)) return;try {- const outcome = await signalLiveRun(runSlot, "abort", undefined, { threadRef: chatState.threadRef });- if (!outcome.ok) revealUnstoppedRun();+ await signalLiveRun(runSlot, "abort", undefined, { threadRef: chatState.threadRef });} catch (err) {- revealUnstoppedRun();+ if (generation !== runSlot.generation || runSlot.stopGeneration !== generation || agent !== chatState.agent)+ return;+ runSlot.stopGeneration = null;throw err;+ } finally {+ if (agent === chatState.agent) drawActiveChat();}}@@ -709,7 +711,7 @@ export function createChatSurface(const generation = ++transcriptRefreshGeneration;const last = agent.state.messages[agent.state.messages.length - 1] as { stopReason?: string } | undefined;if (last?.stopReason === "error") return drawActiveChat(agent);- if (last?.stopReason === "aborted" && !runSlot.unreachedAbort) return drawActiveChat(agent);+ if (last?.stopReason === "aborted") return drawActiveChat(agent);try {const anchor = chatState.transcriptAnchorSeq;const page = await transcriptFetcher(sessionId, anchor !== null ? { sinceSeq: anchor } : undefined);@@ -738,7 +740,6 @@ export function createChatSurface(return;if (refreshedInherited) chatState.inheritedMessages = entriesToMessages(refreshedInherited, transcriptModel());agent.state.messages = messages;- runSlot.unreachedAbort = false;const rawEarlier = page.earlierEntries ?? 0;chatState.earlierCount = currentEarlierCount(chatState.forkSession ?? {}, rawEarlier);chatState.transcriptAnchorSeq = rawEarlier > 0 ? (page.entries?.[0]?.seq ?? null) : null;@@ -1227,6 +1228,7 @@ export function createChatSurface(if (activePendingApprovals().length) return "Needs your approval";if (agent.state.isStreaming || chatState.resolvingApprovals.size > 0) {const work = chatState.liveWork ?? { status: "thinking", activity: [] };+ if (runSlot.stopGeneration === runSlot.generation) return "Stopping…";const summary = liveWorkSummary(work);if (!summary) return "Thinking…";return summary.detail ? `${summary.label}: ${summary.detail}` : summary.label;@@ -2138,7 +2140,8 @@ export function createChatSurface(if (!agent.state.isStreaming && chatState.resolvingApprovals.size === 0) return nothing;const work = chatState.liveWork ?? { status: "thinking", activity: [] };if (work.status !== "thinking" && work.status !== "working") return nothing;- const summary = liveWorkSummary(work);+ const stopping = runSlot.stopGeneration === runSlot.generation;+ const summary = stopping ? null : liveWorkSummary(work);const expandable = Boolean(summary?.detail);const expanded = expandable && liveWorkExpanded;let title = "";@@ -2155,7 +2158,7 @@ export function createChatSurface(>${summary ? html`<span class="tool-icon">${icon(summary.icon, 15)}</span>` : nothing}<span class="live-work-label"- >${summary ? summary.label : sheenLabel(`Thinking${usedToolsSuffix(work)}`, true)}</span+ >${summary ? summary.label : sheenLabel(stopping ? "Stopping…" : `Thinking${usedToolsSuffix(work)}`, true)}</span>${summary?.detail ? html`<span class="live-work-detail">${summary.detail}</span>` : nothing}${expandable ? html`<span class="live-work-toggle">${icon(ChevronRight, 14)}</span>` : nothing}@@ -2713,6 +2716,7 @@ export function createChatSurface(channelName: chatState.contextName,}),stopLiveRun,+ isStopping: () => runSlot.stopGeneration === runSlot.generation,currentTurnOptions,newChat,teardown: teardownActiveChat,diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.tsindex ea50412af..24f21a0b4 100644--- a/plugins/web-ui/src/composer.ts+++ b/plugins/web-ui/src/composer.ts@@ -732,7 +732,14 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}const canQueue = Boolean(composerState.draft.trim() || composerState.attachments.length);return html`- <button class="stop-btn" type="button" aria-label="Stop" ${tip("Stop")} @click=${() => stopStreaming(agent)}>+ <button+ class="stop-btn"+ type="button"+ aria-label="Stop"+ ${tip("Stop")}+ ?disabled=${ctx.chat.isStopping()}+ @click=${() => stopStreaming(agent)}+ >${icon(Square, 16)}</button><button@@ -1286,8 +1293,12 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}function stopStreaming(agent: Agent): void {- void ctx.chat.stopLiveRun().catch((e) => swallow("web-ui: abort signal", e));- agent.abort();+ composerState.error = "";+ void ctx.chat.stopLiveRun().catch(() => {+ if (agent !== ctx.chat.state.agent) return;+ composerState.error = "Could not request stop. Try again.";+ ctx.chat.drawActiveChat(agent);+ });}let failedQueueSend: { threadRef: string; text: string; filesKey: string; idempotencyKey: string } | null = null;@@ -1420,7 +1431,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {: undefined;try {const outcome = await ctx.chat.signalLiveRun("steer", queued.text);- if (!outcome.ok) recoverEndedRunSteer(agent, queued.text, outcome);+ if (!outcome.ok) await recoverEndedRunSteer(agent, queued.text, outcome);} catch (err) {if (steerSessionId && (await verifySteerDelivered(steerSessionId, queued.text, sentAt, undefined, sinceSeq))) {composerState.error = "";@@ -1435,50 +1446,19 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}}- // The run ended before the steer landed (the client believed it was still live).- // Core either replayed the text as a fresh turn (`replayed`) or never stored it.- // Either way the message must not silently vanish: detach from the stale stream,- // then attach to the replay run — or resend the text as an ordinary prompt.- function recoverEndedRunSteer(agent: Agent, text: string, outcome: { replayed?: boolean }): void {- agent.abort();- if (outcome.replayed) {- const last = agent.state.messages[agent.state.messages.length - 1] as- { role?: string; content?: unknown; steered?: boolean } | undefined;- // It is now an ordinary user turn in the transcript, not a mid-run steer.- if (last?.role === "user" && last.content === text && last.steered) delete last.steered;- ctx.chat.drawActiveChat(agent);- attachWhenIdle(agent, 0);- return;- }+ async function recoverEndedRunSteer(agent: Agent, text: string, outcome: { replayed?: boolean }): Promise<void> {const last = agent.state.messages[agent.state.messages.length - 1] as- { role?: string; content?: unknown } | undefined;- if (last?.role === "user" && last.content === text) agent.state.messages.pop();- composerState.draft = text;- ctx.chat.drawActiveChat(agent);- resendWhenIdle(agent, text, 0);- }-- function attachWhenIdle(agent: Agent, attempt: number): void {- if (agent !== ctx.chat.state.agent) return;- if (agent.state.isStreaming) {- if (attempt < 20) window.setTimeout(() => attachWhenIdle(agent, attempt + 1), 250);- return;+ { role?: string; content?: unknown; steered?: boolean } | undefined;+ if (last?.role === "user" && last.content === text) {+ if (outcome.replayed) delete last.steered;+ else agent.state.messages.pop();}- ctx.chat.resumeIfIdle();- }-- function resendWhenIdle(agent: Agent, text: string, attempt: number): void {+ if (!outcome.replayed) composerState.draft = text;+ ctx.chat.drawActiveChat(agent);+ await agent.waitForIdle();if (agent !== ctx.chat.state.agent) return;- if (agent.state.isStreaming) {- if (attempt < 20) window.setTimeout(() => resendWhenIdle(agent, text, attempt + 1), 250);- else {- composerState.error =- "Could not deliver the message. The running task ended mid-send. It is back in the composer.";- ctx.chat.drawActiveChat(agent);- }- return;- }- if (composerState.draft === text) void sendPrompt(agent);+ if (outcome.replayed) ctx.chat.resumeIfIdle();+ else if (composerState.draft === text) await sendPrompt(agent);}async function sendPrompt(agent: Agent): Promise<void> {@@ -1504,6 +1484,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {ctx.chat.drawActiveChat(agent);clearComposerDom(agent);try {+ if (ctx.chat.state.normalStreamFn) agent.streamFn = ctx.chat.state.normalStreamFn;await agent.prompt(userSendMessage(text, attachments.length ? attachments : undefined));restoreBlockedSend(agent, sentFromThread, text, attachments);restoreFailedAttachments(agent, text, attachments);diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.tsindex 8709c30c6..e602f4551 100644--- a/plugins/web-ui/src/conv-types.ts+++ b/plugins/web-ui/src/conv-types.ts@@ -40,6 +40,7 @@ export interface ConvCtx extends ConvHost {interface ChatState {pins: import("./core-bridge").SessionPin[];agent: Agent | null;+ normalStreamFn: Agent["streamFn"] | null;host: HTMLElement | null;threadRef: string | null;sessionId: string | null;@@ -65,6 +66,7 @@ export interface ChatSurface {hasLiveRun(): boolean;signalLiveRun(kind: "abort" | "steer", text?: string): Promise<import("./core-bridge").SignalOutcome>;stopLiveRun(): Promise<void>;+ isStopping(): boolean;currentTurnOptions(): TurnOptions;newChat(context?: { scopeId: string; name: string | null }): string;teardown(): void;diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 8e73349d0..38dcc2a73 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -27,6 +27,8 @@ const POLL_RETRY_MAX_MS = 5_000;export const RUN_IDLE_MS = 6 * 60_000;const STALE_GRACE_MS = 10 * 60_000;const SSE_OPEN_TIMEOUT_MS = 4_000;+const SSE_SILENCE_MS = 30_000;+const RUN_REQUEST_TIMEOUT_MS = 15_000;let now: () => number = () => Date.now();export function setClock(fn: () => number): void {@@ -693,16 +695,15 @@ export interface RunSlot {runId: string | null;generation: number;stopGeneration: number | null;- unreachedAbort: boolean;+ onStopError?: (message: string) => void;}-export function createRunSlot(): RunSlot {- return { runId: null, generation: 0, stopGeneration: null, unreachedAbort: false };+export function createRunSlot(onStopError?: (message: string) => void): RunSlot {+ return { runId: null, generation: 0, stopGeneration: null, onStopError };}function beginSubmit(slot: RunSlot | undefined): number {if (!slot) return 0;- slot.unreachedAbort = false;return ++slot.generation;}@@ -745,6 +746,7 @@ export async function signalLiveRun(try {await api(runPath(run.runId, "/signal"), {method: "POST",+ signal: kind === "abort" ? AbortSignal.timeout(RUN_REQUEST_TIMEOUT_MS) : undefined,body: JSON.stringify({ kind, ...(text !== undefined ? { text } : {}), ...steerContext }),});return { ok: true };@@ -1172,16 +1174,13 @@ async function followRun(): Promise<void> {try {if (slot && slot.stopGeneration === gen) {- slot.stopGeneration = null;slot.runId = runId;- try {- const outcome = await signalLiveRun(slot, "abort", undefined, { threadRef: null });- if (!outcome.ok) slot.unreachedAbort = true;- } catch (e) {- slot.unreachedAbort = true;- swallow("web-ui: stop requested before the run id arrived", e);- }- return abortStream(stream, partial);+ void signalLiveRun(slot, "abort", undefined, { threadRef: null }).catch(() => {+ if (slot.generation !== gen || slot.stopGeneration !== gen) return;+ slot.stopGeneration = null;+ slot.onStopError?.("Could not request stop. Try again.");+ notify?.();+ });}if (signal?.aborted) return abortStream(stream, partial);if (slot) slot.runId = runId;@@ -1326,9 +1325,13 @@ export async function pollRun(if (signal?.aborted) return abortStream(stream, partial);let run: RunPoll;try {- run = await api<RunPoll>(runPath(runId, ""));+ const timeout = AbortSignal.timeout(RUN_REQUEST_TIMEOUT_MS);+ run = await api<RunPoll>(runPath(runId, ""), {+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,+ });consecutiveFailures = 0;} catch (e) {+ if (signal?.aborted) return abortStream(stream, partial);if (e instanceof ApiError && e.status >= 400 && e.status < 500) return fail(stream, partial, e.message);consecutiveFailures++;if (now() - st.lastProgressAt > RUN_IDLE_MS)@@ -1418,30 +1421,37 @@ function streamRunViaSse(if (typeof EventSource === "undefined") return resolve("fallback");let settled = false;let established = false;+ let silenceTimer: ReturnType<typeof setTimeout> | undefined;const es = new EventSource(withBase(runPath(runId, "/events")));const settle = (outcome: "done" | "fallback"): void => {if (settled) return;settled = true;clearTimeout(openTimer);+ clearTimeout(silenceTimer);signal?.removeEventListener("abort", onAbort);es.close();resolve(outcome);};+ const received = (): void => {+ established = true;+ clearTimeout(silenceTimer);+ silenceTimer = setTimeout(() => settle("fallback"), SSE_SILENCE_MS);+ };const onAbort = (): void => {abortStream(stream, partial);settle("done");};- signal?.addEventListener("abort", onAbort);- if (signal?.aborted) return onAbort();const openTimer = setTimeout(() => {if (!established) settle("fallback");}, SSE_OPEN_TIMEOUT_MS);+ signal?.addEventListener("abort", onAbort);+ if (signal?.aborted) return onAbort();es.onopen = (): void => {- established = true;+ received();};es.addEventListener("partial", (e: MessageEvent) => {- established = true;+ received();try {const d = JSON.parse(e.data) as { partial?: string };if (typeof d.partial === "string" && d.partial.length > st.acc.length) {@@ -1453,7 +1463,7 @@ function streamRunViaSse(}});es.addEventListener("activity", (e: MessageEvent) => {- established = true;+ received();try {const d = JSON.parse(e.data) as { activity?: unknown[]; startedAt?: number | null };const work = (partial as AssistantWork).work;@@ -1467,11 +1477,11 @@ function streamRunViaSse(}});es.addEventListener("alive", () => {- established = true;+ received();st.lastProgressAt = now();});es.addEventListener("stale", (e: MessageEvent) => {- established = true;+ received();try {const d = JSON.parse(e.data) as { stale?: boolean };const stale = d.stale === true;@@ -1484,7 +1494,7 @@ function streamRunViaSse(}});es.addEventListener("done", (e: MessageEvent) => {- established = true;+ received();try {applyRun(stream, partial, st, JSON.parse(e.data) as RunPoll, notify);settle("done");diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex b76880ef0..6fd5293a4 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -1776,8 +1776,19 @@ a.chat-row-open {display: flow-root;}.message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded):not(.pin-fits) .user-bubble > .pin-content {+ position: relative;max-height: var(--pin-clamp, 320px);overflow: hidden;+ mask-image: linear-gradient(to bottom, #000 calc(100% - 18px), transparent);+}+.message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded):not(.pin-fits) .user-bubble > .pin-content::after {+ content: "";+ position: absolute;+ inset: auto 0 0;+ height: 18px;+ backdrop-filter: blur(2px);+ mask-image: linear-gradient(to bottom, transparent, #000);+ pointer-events: none;}.message-stack .user-row.pin-expanded .user-bubble > .pin-content {max-height: var(--pin-expanded-max);diff --git a/plugins/web-ui/test/attachment-limits.test.ts b/plugins/web-ui/test/attachment-limits.test.tsindex 91da8bda9..70720ba3e 100644--- a/plugins/web-ui/test/attachment-limits.test.ts+++ b/plugins/web-ui/test/attachment-limits.test.ts@@ -221,16 +221,13 @@ test("Stop pressed before the run id arrives still stops core's run", () => {assert.match(composer, /void ctx\.chat\.stopLiveRun\(\)\.catch/);const followRun = bridge.slice(bridge.indexOf("async function followRun"), bridge.indexOf("function runPath"));assert.match(followRun, /if \(slot && slot\.stopGeneration === gen\) \{/);- assert.match(followRun, /await signalLiveRun\(slot, "abort", undefined, \{ threadRef: null \}\);/);- assert.match(followRun, /slot\.unreachedAbort = true;/);+ assert.match(followRun, /void signalLiveRun\(slot, "abort", undefined, \{ threadRef: null \}\)/);+ assert.match(followRun, /notify\?\.\(\);/);});-test("the aborted-refresh guard yields when the abort never reached core", () => {+test("confirmed aborted output is preserved during transcript refresh", () => {assert.match(chat, /if \(last\?\.stopReason === "error"\) return drawActiveChat\(agent\);/);- assert.match(- chat,- /if \(last\?\.stopReason === "aborted" && !runSlot\.unreachedAbort\) return drawActiveChat\(agent\);/,- );+ assert.match(chat, /if \(last\?\.stopReason === "aborted"\) return drawActiveChat\(agent\);/);});test("verifySteerDelivered only trusts a steered entry newer than the baseline it was given", async () => {diff --git a/plugins/web-ui/test/chat-elevation.test.ts b/plugins/web-ui/test/chat-elevation.test.tsindex 0995004b3..3108c617a 100644--- a/plugins/web-ui/test/chat-elevation.test.ts+++ b/plugins/web-ui/test/chat-elevation.test.ts@@ -6,7 +6,7 @@ const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");test("transcript edges do not blur or mask the response", () => {assert.doesNotMatch(css, /\.chat-scroll::(?:before|after)/);- assert.doesNotMatch(css, /\.message-stack \.user-row[^{}]*::after/);+ assert.doesNotMatch(css, /\.message-stack \.user-row[^{}]* > \.user-bubble::(?:before|after)/);assert.doesNotMatch(css, /--chat-edge-fade/);});diff --git a/plugins/web-ui/test/composer-source.test.ts b/plugins/web-ui/test/composer-source.test.tsindex 276e5409e..f35fac603 100644--- a/plugins/web-ui/test/composer-source.test.ts+++ b/plugins/web-ui/test/composer-source.test.ts@@ -67,18 +67,6 @@ test("a mid-turn submit queues — attachments cannot ride a queued message andassert.doesNotMatch(composer, /attachments stay for your next message/);});-test("a steer whose run already ended is recovered, never silently dropped", () => {- // steerQueued must inspect the signal outcome and route a failed steer through recovery.- assert.match(composer, /const outcome = await ctx\.chat\.signalLiveRun\("steer", queued\.text\);/);- assert.match(composer, /if \(!outcome\.ok\) recoverEndedRunSteer\(agent, queued\.text, outcome\);/);- // Replayed by core → detach from the stale stream and attach to the fresh run.- assert.match(composer, /function recoverEndedRunSteer\(/);- assert.match(composer, /attachWhenIdle\(agent, 0\);/);- // Not stored anywhere → the text goes back through a normal send.- assert.match(composer, /resendWhenIdle\(agent, text, 0\);/);- assert.match(composer, /if \(composerState\.draft === text\) void sendPrompt\(agent\);/);-});-test("scope runtime defaults include effort and fast mode", () => {assert.match(composer, /effortLevel: composerState\.effortLevel/);assert.match(composer, /fastMode: fastOn/);diff --git a/plugins/web-ui/test/pinned-composer-polish.test.ts b/plugins/web-ui/test/pinned-composer-polish.test.tsindex 47142a92a..bea367b94 100644--- a/plugins/web-ui/test/pinned-composer-polish.test.ts+++ b/plugins/web-ui/test/pinned-composer-polish.test.ts@@ -44,3 +44,15 @@ test("queued cards tuck beneath the next card just as the queue tucks beneath thassert.match(strip, /margin: 0 auto -10px;/);assert.match(stacked, /margin-top: -10px;/);});++test("only collapsed overflowing prompt content gets the soft cutoff", () => {+ const selector =+ ".message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded):not(.pin-fits) .user-bubble > .pin-content";+ const rule = css.slice(css.indexOf(`${selector} {`)).split("}")[0] ?? "";+ const overlay = css.slice(css.indexOf(`${selector}::after {`)).split("}")[0] ?? "";+ assert.match(rule, /position: relative;/);+ assert.match(rule, /mask-image: linear-gradient\(to bottom, #000 calc\(100% - 18px\), transparent\);/);+ assert.match(overlay, /height: 18px;/);+ assert.match(overlay, /backdrop-filter: blur\(2px\);/);+ assert.match(overlay, /pointer-events: none;/);+});diff --git a/plugins/web-ui/test/post-reply-recovery.test.ts b/plugins/web-ui/test/post-reply-recovery.test.tsindex 4db634173..349dc59b9 100644--- a/plugins/web-ui/test/post-reply-recovery.test.ts+++ b/plugins/web-ui/test/post-reply-recovery.test.ts@@ -385,6 +385,61 @@ test("post replies remain visible in new and continuing conversations", async (tassert.equal(count("Second confirmed reply"), 1);assert.equal(count("Replies sent."), 0);});+ for (const edited of [false, true]) {+ await t.test(+ `delayed ended-run steer ${edited ? "preserves a newer draft" : "resends after completion"}`,+ async (sub) => {+ sub.after(() => {+ intercept = undefined;+ });+ await mount();+ const agent = conv!.state.agent!;+ let oldRunLive = true;+ let signalled = false;+ let resends = 0;+ intercept = (path) => {+ if (path.includes("/api/runs/active"))+ return Promise.resolve(+ Response.json({+ runId: oldRunLive ? "r1" : null,+ run: oldRunLive ? { status: "running" } : null,+ queued: [],+ }),+ );+ if (path === "/api/runs/queued/withdraw") return Promise.resolve(Response.json({ withdrawn: true }));+ if (path === "/api/runs/r1/signal") {+ signalled = true;+ return Promise.resolve(Response.json({ reason: "terminal", replayed: false }, { status: 409 }));+ }+ if (path === "/api/turn") {+ resends++;+ return Promise.resolve(Response.json({ reply: "Follow-up received" }));+ }+ };+ const before = FakeEventSource.instances.length;+ conv!.resumeIfIdle();+ await until(() => FakeEventSource.instances.length > before);+ const turn = agent.waitForIdle();+ const run = FakeEventSource.instances.findLast((es) => es.url === "/api/runs/r1/events")!;+ run.onopen?.();+ conv!.composer.setQueuedRuns(row.threadRef, [{ runId: "queued", text: "Follow-up question" }]);+ conv!.drawActiveChat(agent);+ host.querySelector<HTMLButtonElement>(".queued-steer")!.click();+ await until(() => signalled && conv!.composer.state.draft === "Follow-up question");+ if (edited) conv!.composer.state.draft = "New draft";+ await new Promise((resolve) => setTimeout(resolve, 5_200));+ assert.equal(resends, 0);+ oldRunLive = false;+ run.emit("done", { status: "done", result: { status: "ok", reply: "Original answer" } });+ await turn;+ if (!edited) await until(() => resends === 1);+ await settle();+ assert.equal(resends, edited ? 0 : 1);+ if (edited) assert.equal(conv!.composer.state.draft, "New draft");+ intercept = undefined;+ },+ );+ }if (conv) {disposeConversation(conv);conv = undefined;diff --git a/plugins/web-ui/test/queue-by-default.test.ts b/plugins/web-ui/test/queue-by-default.test.tsindex 57fceeb84..f17a4cd5c 100644--- a/plugins/web-ui/test/queue-by-default.test.ts+++ b/plugins/web-ui/test/queue-by-default.test.ts@@ -113,7 +113,7 @@ test("Steer withdraws the queued run before it signals, and only then shows the);assert.match(fn,- /if \(!outcome\.ok\) recoverEndedRunSteer\(agent, queued\.text, outcome\);/,+ /if \(!outcome\.ok\) await recoverEndedRunSteer\(agent, queued\.text, outcome\);/,"a steer the run outlived is recovered (replayed run followed, or resent as its own turn)",);assert.match(fn, /if \(!\(await withdrawRun\(queued\.runId\)\)\) return ctx\.chat\.drawActiveChat\(agent\);/);diff --git a/plugins/web-ui/test/run-connection.test.ts b/plugins/web-ui/test/run-connection.test.tsnew file mode 100644index 000000000..36eecd14c--- /dev/null+++ b/plugins/web-ui/test/run-connection.test.ts@@ -0,0 +1,118 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { makeRunResumeStreamFn } from "../src/core-bridge.ts";+import type { Api, Context, Model } from "@earendil-works/pi-ai";++const model = { id: "m", api: "anthropic", provider: "anthropic" } as unknown as Model<Api>;+const flush = async () => {+ for (let i = 0; i < 30; i++) await Promise.resolve();+};++class FakeEventSource extends EventTarget {+ static current: FakeEventSource;+ onopen?: () => void;+ onerror?: () => void;+ closed = false;+ constructor() {+ super();+ FakeEventSource.current = this;+ }+ close() {+ this.closed = true;+ }+}++for (const heartbeat of [false, true]) {+ test(`a silent established stream falls back to polling${heartbeat ? " after its last heartbeat" : ""}`, async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const original = Object.getOwnPropertyDescriptor(globalThis, "EventSource");+ Object.defineProperty(globalThis, "EventSource", { configurable: true, value: FakeEventSource });+ t.after(() => {+ if (original) Object.defineProperty(globalThis, "EventSource", original);+ else Reflect.deleteProperty(globalThis, "EventSource");+ });+ let polls = 0;+ t.mock.method(globalThis, "fetch", async () => {+ polls++;+ return Response.json({ status: "done", result: { status: "ok", stopped: true } });+ });+ const stream = await makeRunResumeStreamFn("r")(model, {} as Context, {});+ await flush();+ const es = FakeEventSource.current;+ es.onopen?.();+ if (heartbeat) {+ t.mock.timers.tick(20_000);+ es.dispatchEvent(new Event("alive"));+ t.mock.timers.tick(20_000);+ await flush();+ assert.equal(polls, 0);+ }+ t.mock.timers.tick(30_000);+ await flush();+ assert.equal(polls, 1);+ assert.equal(es.closed, true);+ assert.equal((await stream.result()).stopReason, "aborted");+ t.mock.timers.tick(60_000);+ assert.equal(polls, 1);+ });+}++test("a stalled poll times out and retries without losing the run", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const timeout = new AbortController();+ t.mock.method(AbortSignal, "timeout", (ms: number) => {+ assert.equal(ms, 15_000);+ return timeout.signal;+ });+ let polls = 0;+ let requestSignal: AbortSignal | null | undefined;+ t.mock.method(globalThis, "fetch", async (_url: unknown, init?: RequestInit) => {+ polls++;+ if (polls > 1) return Response.json({ status: "done", result: { status: "ok", reply: "done" } });+ requestSignal = init?.signal;+ return new Promise<Response>((_, reject) =>+ requestSignal?.addEventListener("abort", () => reject(requestSignal?.reason)),+ );+ });+ const stream = await makeRunResumeStreamFn("r")(model, {} as Context, {});+ await flush();+ assert.ok(requestSignal, "poll requests must be bounded");+ timeout.abort(new DOMException("timed out", "TimeoutError"));+ await flush();+ t.mock.timers.tick(5_000);+ await flush();+ assert.equal(polls, 2);+ assert.equal((await stream.result()).stopReason, "stop");+});++for (const terminal of [true, false]) {+ test(`${terminal ? "terminal completion" : "detaching"} cancels the connection watchdog`, async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const original = Object.getOwnPropertyDescriptor(globalThis, "EventSource");+ Object.defineProperty(globalThis, "EventSource", { configurable: true, value: FakeEventSource });+ t.after(() => {+ if (original) Object.defineProperty(globalThis, "EventSource", original);+ else Reflect.deleteProperty(globalThis, "EventSource");+ });+ let polls = 0;+ t.mock.method(globalThis, "fetch", async () => {+ polls++;+ return Response.json({ status: "done", result: { status: "ok" } });+ });+ const controller = new AbortController();+ const stream = await makeRunResumeStreamFn("r")(model, {} as Context, { signal: controller.signal });+ await flush();+ const es = FakeEventSource.current;+ es.onopen?.();+ if (terminal) {+ const event = new Event("done");+ Object.assign(event, { data: JSON.stringify({ status: "done", result: { status: "ok" } }) });+ es.dispatchEvent(event);+ } else controller.abort();+ await stream.result();+ t.mock.timers.tick(60_000);+ await flush();+ assert.equal(es.closed, true);+ assert.equal(polls, 0);+ });+}diff --git a/plugins/web-ui/test/steer-recovery-source.test.ts b/plugins/web-ui/test/steer-recovery-source.test.tsindex 42c5d4fca..b5a83ad57 100644--- a/plugins/web-ui/test/steer-recovery-source.test.ts+++ b/plugins/web-ui/test/steer-recovery-source.test.ts@@ -49,7 +49,7 @@ test("a queued steer the run outlived settles every way: replay followed, endedconst at = composer.indexOf("async function steerQueued");assert.ok(at >= 0);const body = composer.slice(at, composer.indexOf("function recoverEndedRunSteer", at));- assert.match(body, /if \(!outcome\.ok\) recoverEndedRunSteer\(agent, queued\.text, outcome\);/);+ assert.match(body, /if \(!outcome\.ok\) await recoverEndedRunSteer\(agent, queued\.text, outcome\);/);assert.match(body,/if \(!\(await enqueueTurn\(agent, threadRef, queued\.text\)\)\) composerState\.draft = queued\.text;/,diff --git a/plugins/web-ui/test/sticky-prompt-occlusion.test.ts b/plugins/web-ui/test/sticky-prompt-occlusion.test.tsindex 011e705bb..ea16edace 100644--- a/plugins/web-ui/test/sticky-prompt-occlusion.test.ts+++ b/plugins/web-ui/test/sticky-prompt-occlusion.test.ts@@ -7,7 +7,12 @@ test("the transcript clips at its own edges — no fade at the topbar or the comassert.doesNotMatch(css, /\.chat-scroll::(before|after)/);});-test("no transcript surface dissolves content into the background", () => {- assert.doesNotMatch(css, /linear-gradient\(\s*to (top|bottom),\s*var\(--background\)/s);- assert.doesNotMatch(css, /mask-image:/);+test("transcript containers and assistant responses remain unmasked", () => {+ const surfaces = /\.(?:chat-scroll|message-stack|assistant-row|assistant-body)(?:[.:][\w-]+)*\s*(?:,|$)/;+ const rules = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].filter((rule) => surfaces.test(rule[1]));+ assert.ok(rules.length > 0);+ for (const [, selector, declarations] of rules) {+ assert.doesNotMatch(declarations, /(?:mask-image|backdrop-filter):/, selector.trim());+ assert.doesNotMatch(declarations, /linear-gradient\(\s*to (top|bottom),\s*var\(--background\)/s, selector.trim());+ }});diff --git a/plugins/web-ui/test/stop-confirmation.test.ts b/plugins/web-ui/test/stop-confirmation.test.tsnew file mode 100644index 000000000..08f8f0529--- /dev/null+++ b/plugins/web-ui/test/stop-confirmation.test.ts@@ -0,0 +1,112 @@+import { test, afterEach } from "node:test";+import assert from "node:assert/strict";+import { setTimeout as sleep } from "node:timers/promises";+import { makeRunResumeStreamFn, createRunSlot, requestStop, type AssistantWork } from "../src/core-bridge.ts";+import type { Api, Model, Context } from "@earendil-works/pi-ai";++const fetch = globalThis.fetch;+afterEach(() => {+ globalThis.fetch = fetch;+});+const model = { id: "m", api: "anthropic", provider: "anthropic" } as unknown as Model<Api>;++test("stop before run discovery follows the run until server confirmation", async () => {+ const slot = createRunSlot();+ const terminal = Promise.withResolvers<Response>();+ const signalled = Promise.withResolvers<void>();+ globalThis.fetch = (async (url: string) => {+ if (url.endsWith("/signal")) {+ signalled.resolve();+ return new Response("{}");+ }+ return terminal.promise;+ }) as typeof globalThis.fetch;+ let requested = false;+ const fn = makeRunResumeStreamFn(+ "slow-read",+ undefined,+ () => {+ if (!requested) {+ requested = true;+ requestStop(slot);+ }+ },+ slot,+ );+ const stream = await fn(model, {} as Context, {});+ let settled = false;+ const result = stream.result().then((value) => {+ settled = true;+ return value as AssistantWork;+ });+ await signalled.promise;+ await sleep(30);+ const premature = settled;+ terminal.resolve(+ new Response(JSON.stringify({ status: "done", result: { status: "ok", stopped: true, reply: "" } })),+ );+ const final = await result;+ assert.equal(premature, false, "Stopped requires server confirmation");+ assert.equal(final.stopReason, "aborted");+ await sleep(0);+ assert.equal(slot.stopGeneration, null);+});++for (const status of [404, 409, 500]) {+ test(`stop discovery with HTTP ${status} never invents a stopped result`, async () => {+ const errors: string[] = [];+ const slot = createRunSlot((message) => errors.push(message));+ globalThis.fetch = (async (url: string) => {+ if (url.endsWith("/signal")) return new Response("{}", { status });+ return new Response(JSON.stringify({ status: "done", result: { status: "ok", reply: "completed normally" } }));+ }) as typeof globalThis.fetch;+ let requested = false;+ const fn = makeRunResumeStreamFn(+ "run",+ undefined,+ () => {+ if (!requested) {+ requested = true;+ requestStop(slot);+ }+ },+ slot,+ );+ const stream = await fn(model, {} as Context, {});+ const final = await stream.result();+ assert.equal(final.stopReason, "stop");+ assert.deepEqual(errors, status === 500 ? ["Could not request stop. Try again."] : []);+ await sleep(0);+ assert.equal(slot.stopGeneration, null);+ });+}++test("a stalled stop acknowledgment cannot delay confirmation or report a late error", async () => {+ const errors: string[] = [];+ const slot = createRunSlot((message) => errors.push(message));+ const signalReply = Promise.withResolvers<Response>();+ globalThis.fetch = (async (url: string) => {+ if (url.endsWith("/signal")) return signalReply.promise;+ return new Response(JSON.stringify({ status: "done", result: { status: "ok", stopped: true } }));+ }) as typeof globalThis.fetch;+ let requested = false;+ const fn = makeRunResumeStreamFn(+ "run",+ undefined,+ () => {+ if (!requested) {+ requested = true;+ requestStop(slot);+ }+ },+ slot,+ );+ const stream = await fn(model, {} as Context, {});+ const result = stream.result();+ const first = await Promise.race([result, sleep(100).then(() => null)]);+ signalReply.reject(new TypeError("late transport failure"));+ await result;+ await sleep(0);+ assert.equal(first?.stopReason, "aborted");+ assert.deepEqual(errors, []);+});diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex 7fad31911..03b4d361e 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -948,7 +948,10 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):const tc = ref.current;if (!tc) return text("[error] no active tool context");await recordCall(callId, { tool: "read", path: params.path });- const { content, sourceScopeId, shared } = await tc.read(params.path);+ const signal = ref.abortSignal;+ signal?.throwIfAborted();+ const { content, sourceScopeId, shared } = await tc.read(params.path, signal);+ signal?.throwIfAborted();return recordResult(callId,{diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex 38af52265..3206e0f55 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -1,3 +1,4 @@+import { withAbort } from "../util/async.ts";import type { RuntimeRequest, RuntimeResult } from "../harness/runtime-types.ts";import { readContextFile } from "../resolution/context-files.ts";import { contextMemory, type TurnContext } from "../resolution/turn-context.ts";@@ -211,7 +212,7 @@ export interface ToolContext extends SurfaceToolDeps {computerStatus(sandboxId?: string): Promise<ComputerStatus>;restartComputer(sandboxId?: string): Promise<void>;migrateComputer(to: string): Promise<{ from: string; to: string }>;- read(path: string): Promise<ReadResult>;+ read(path: string, signal?: AbortSignal): Promise<ReadResult>;write(path: string, data?: string, share?: ShareDirective[]): Promise<WriteResult>;publish(input: PublishInput): Promise<PublishResult>;createPlayground(input: { title: string; html: string }): Promise<PlaygroundArtifact>;@@ -808,17 +809,18 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {});},- async read(path: string): Promise<ReadResult> {+ async read(path: string, signal?: AbortSignal): Promise<ReadResult> {+ signal?.throwIfAborted();if (path === MEMORY_FILE && deps.memory && deps.memoryScopeId) {if (!deps.memoryAccess?.read.includes(deps.memoryScopeId)) {throw new Error("memory recall is not enabled for this conversation; use the `memory` tool when enabled");}- const content = await deps.memory.read(deps.memoryScopeId);+ const content = await withAbort(() => deps.memory!.read(deps.memoryScopeId!), signal);if (content) return { content, sourceScopeId: deps.memoryScopeId };}const sharedFile = deps.context- ? await deps.context.readFile(path)- : await readContextFile(path, deps.grantedHandles, deps.workspace, deps.files);+ ? await withAbort(() => deps.context!.readFile(path), signal)+ : await withAbort(() => readContextFile(path, deps.grantedHandles, deps.workspace, deps.files), signal);if (sharedFile && "error" in sharedFile) return { content: sharedFile.error, sourceScopeId: null };if (sharedFile) {const { grant: granted, bytes } = sharedFile;@@ -837,7 +839,9 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {const materializedPath = deps.sharedMaterializeDir? `${deps.sharedMaterializeDir}/${name}`: granted.handlePath;+ signal?.throwIfAborted();await deps.sandbox.writeFileBytes(handle, materializedPath, bytes);+ signal?.throwIfAborted();return {content:`[binary file materialized into the sandbox at ${materializedPath} (${bytes.length} bytes) — ` +@@ -849,12 +853,13 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {if (path.startsWith("shared/open-")) return { content: null, sourceScopeId: null };const skillDir = skillTreeDirFor(path);if (skillDir && deps.ensureSkillTree) await deps.ensureSkillTree(skillDir);+ signal?.throwIfAborted();const handle = await deps.provision();return timed("file_op", async () => {- const direct = await deps.sandbox.readFile(handle, path);+ const direct = await withAbort(() => deps.sandbox.readFile(handle, path), signal);if (direct !== null) return { content: direct, sourceScopeId: writableScopeId };for (const mount of fallbackMounts) {- const v = await deps.sandbox.readFile(handle, join(mount.mountPath, path));+ const v = await withAbort(() => deps.sandbox.readFile(handle, join(mount.mountPath, path)), signal);if (v !== null) return { content: v, sourceScopeId: mount.scopeId };}return { content: null, sourceScopeId: null };diff --git a/src/util/async.ts b/src/util/async.tsindex 067cbb266..6479fec0b 100644--- a/src/util/async.ts+++ b/src/util/async.ts@@ -37,3 +37,24 @@ export function createKeyedQueue<K = string>(): <T>(key: K, fn: () => Promise<T>return run;};}++export async function withAbort<T>(start: () => Promise<T>, signal?: AbortSignal): Promise<T> {+ if (!signal) return start();+ signal.throwIfAborted();+ let onAbort!: () => void;+ const cancelled = new Promise<never>((_, reject) => {+ onAbort = () => reject(signal.reason);+ signal.addEventListener("abort", onAbort, { once: true });+ });+ try {+ const operation = Promise.resolve().then(() => {+ signal.throwIfAborted();+ return start();+ });+ const value = await Promise.race([operation, cancelled]);+ signal.throwIfAborted();+ return value;+ } finally {+ signal.removeEventListener("abort", onAbort);+ }+}diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.tsindex 1017a49eb..d2925c5c4 100644--- a/test/agent-tools.test.ts+++ b/test/agent-tools.test.ts@@ -3207,3 +3207,31 @@ test("surface messages use Markdown and only Slack tools teach Slack mentions",else assert.doesNotMatch(text, /Slack|<@U…>|<!subteam/);}});++test("read passes turn cancellation through and cannot record a late success", async () => {+ const controller = new AbortController();+ const started = Promise.withResolvers<void>();+ const pending = Promise.withResolvers<{ content: string; sourceScopeId: string }>();+ const emitted: Emitted[] = [];+ const context = fakeToolContext();+ let received: AbortSignal | undefined;+ context.read = async (_path, signal) => {+ received = signal;+ started.resolve();+ return pending.promise;+ };+ const read = createAgentTools({+ current: context,+ abortSignal: controller.signal,+ emit: (e) => {+ emitted.push(e as Emitted);+ },+ }).find((t) => t.name === "read");+ const result = call(read, { path: "notes.md" });+ await started.promise;+ controller.abort();+ pending.resolve({ content: "late data", sourceScopeId: "personal:U1" });+ await assert.rejects(result, { name: "AbortError" });+ assert.equal(received, controller.signal);+ assert.equal(emitted.filter((e) => e.type === "tool_result").length, 0);+});diff --git a/test/read-cancellation.test.ts b/test/read-cancellation.test.tsnew file mode 100644index 000000000..0cda452ad--- /dev/null+++ b/test/read-cancellation.test.ts@@ -0,0 +1,135 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { setTimeout as sleep } from "node:timers/promises";+import { createToolContext, type ToolContextDeps } from "../src/tools/primitives.ts";+import type { Sandbox } from "../src/sandbox/sandbox.ts";+import { scopeId } from "../src/types.ts";++function setup(overrides: Partial<ToolContextDeps> = {}) {+ const pending = Promise.withResolvers<string | null>();+ const started = Promise.withResolvers<void>();+ let reads = 0;+ const tc = createToolContext({+ sandbox: {+ readFile: async () => {+ reads++;+ started.resolve();+ return pending.promise;+ },+ } as unknown as Sandbox,+ provision: async () => ({ id: "h", rootDir: "/workspace" }),+ layers: [+ { scopeId: scopeId("personal", "U1"), mountPath: "", mode: "rw" },+ { scopeId: scopeId("org", "o"), mountPath: "global", mode: "ro" },+ ],+ commandPolicy: () => ({ mode: "denylist", rules: [] }),+ authorizeCommand: () => false,+ grantedHandles: [],+ workspace: {} as never,+ deploy: {} as never,+ acl: {} as never,+ createdBy: "U1",+ ...overrides,+ });+ return { tc, pending, started, reads: () => reads };+}++test("cancelled file reads settle before IO and do not start fallback reads", async () => {+ const { tc, pending, started, reads } = setup();+ const controller = new AbortController();+ let settled = false;+ const result = tc+ .read("notes.md", controller.signal)+ .then(+ (value) => ({ value }),+ (error) => ({ error }),+ )+ .finally(() => {+ settled = true;+ });+ await started.promise;+ controller.abort();+ await sleep(30);+ const promptly = settled;+ pending.resolve(null);+ const outcome = await result;+ await sleep(10);+ assert.equal(promptly, true);+ assert.ok("error" in outcome && outcome.error.name === "AbortError");+ assert.equal(reads(), 1);+});++test("already cancelled reads never start IO", async () => {+ const { tc, pending, reads } = setup();+ pending.resolve("data");+ await assert.rejects(tc.read("notes.md", AbortSignal.abort()), { name: "AbortError" });+ assert.equal(reads(), 0);+});++test("cancel during a shared read does not materialize late binary data", async () => {+ const pending = Promise.withResolvers<Uint8Array | null>();+ const started = Promise.withResolvers<void>();+ let writes = 0;+ const { tc } = setup({+ grantedHandles: [+ {+ handlePath: "shared/file.bin",+ ownerPath: "file.bin",+ ownerScopeId: scopeId("personal", "U2"),+ permission: "read",+ },+ ],+ workspace: {+ readBytes: async () => {+ started.resolve();+ return pending.promise;+ },+ } as unknown as ToolContextDeps["workspace"],+ sandbox: {+ writeFileBytes: async () => {+ writes++;+ },+ } as unknown as Sandbox,+ });+ const controller = new AbortController();+ const result = tc.read("shared/file.bin", controller.signal);+ await started.promise;+ controller.abort();+ await assert.rejects(result, { name: "AbortError" });+ pending.resolve(new Uint8Array([255, 254, 0]));+ await sleep(0);+ assert.equal(writes, 0);+});++test("cancellation drains an in-flight materialization instead of abandoning writes", async () => {+ const writing = Promise.withResolvers<void>();+ const finish = Promise.withResolvers<void>();+ const { tc } = setup({+ grantedHandles: [+ {+ handlePath: "shared/file.bin",+ ownerPath: "file.bin",+ ownerScopeId: scopeId("personal", "U2"),+ permission: "read",+ },+ ],+ workspace: { readBytes: async () => new Uint8Array([255, 254, 0]) } as unknown as ToolContextDeps["workspace"],+ sandbox: {+ writeFileBytes: async () => {+ writing.resolve();+ await finish.promise;+ },+ } as unknown as Sandbox,+ });+ const controller = new AbortController();+ let settled = false;+ const result = tc.read("shared/file.bin", controller.signal).finally(() => {+ settled = true;+ });+ await writing.promise;+ controller.abort();+ await sleep(10);+ assert.equal(settled, false);+ finish.resolve();+ await assert.rejects(result, { name: "AbortError" });+});diff --git a/test/util-async.test.ts b/test/util-async.test.tsindex 3f2098f8c..0999c28ec 100644--- a/test/util-async.test.ts+++ b/test/util-async.test.ts@@ -98,3 +98,40 @@ test("createKeyedQueue ops queued at drain time are not lost to the cleanup raceassert.equal(await second, "ok");assert.deepEqual(order, ["first", "second"]);});++test("withAbort cleans listeners after resolution, rejection, and cancellation", async () => {+ const { withAbort } = await import("../src/util/async.ts");+ const { default: EventEmitter } = await import("node:events");+ const controller = new AbortController();+ assert.equal(await withAbort(async () => "ok", controller.signal), "ok");+ assert.equal(EventEmitter.getEventListeners(controller.signal, "abort").length, 0);+ await assert.rejects(+ withAbort(async () => {+ throw new Error("read failed");+ }, controller.signal),+ /read failed/,+ );+ assert.equal(EventEmitter.getEventListeners(controller.signal, "abort").length, 0);+ const pending = Promise.withResolvers<string>();+ const result = withAbort(() => pending.promise, controller.signal);+ await Promise.resolve();+ controller.abort();+ await assert.rejects(result, { name: "AbortError" });+ assert.equal(EventEmitter.getEventListeners(controller.signal, "abort").length, 0);+ pending.reject(new Error("late IO failure"));+ await sleep(0);+});++test("withAbort skips an already cancelled operation and preserves the reason", async () => {+ const { withAbort } = await import("../src/util/async.ts");+ const reason = new Error("cancelled");+ let called = false;+ await assert.rejects(+ withAbort(async () => {+ called = true;+ }, AbortSignal.abort(reason)),+ (error) => error === reason,+ );+ assert.equal(called, false);+ assert.equal(await withAbort(async () => 42), 42);+});