Skip to content

Commit f117fc3

Browse files
committed
fix(agents): settle aborted runs through after-turn so agent_end fires
1 parent 9eee618 commit f117fc3

5 files changed

Lines changed: 172 additions & 13 deletions

File tree

‎src/agents/embedded-agent-runner/run/attempt-after-turn.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,11 +180,18 @@ export async function completeEmbeddedAttemptAfterTurn(
180180
!state.beforeAgentFinalizeRevisionReason
181181
) {
182182
const lifecycleForAgentEnd = input.readLifecycleState();
183+
// Abort outranks failure in terminal-outcome precedence: teardown races can
184+
// stamp an AbortError into promptError, and surfacing it as `error` would
185+
// make agent_end consumers treat a user abort as an errored completion.
186+
const agentEndError =
187+
state.promptError && !lifecycleForAgentEnd.aborted
188+
? formatErrorMessage(state.promptError)
189+
: undefined;
183190
runAgentEndSideEffects({
184191
event: {
185192
messages: state.messagesSnapshot,
186193
success: !lifecycleForAgentEnd.aborted && !state.promptError,
187-
error: state.promptError ? formatErrorMessage(state.promptError) : undefined,
194+
error: agentEndError,
188195
durationMs: Date.now() - runtime.promptStartedAt,
189196
},
190197
ctx: buildEmbeddedAgentEndContext({

‎src/agents/embedded-agent-runner/run/attempt-phase-lifecycle.test.ts‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
22

33
const hoisted = vi.hoisted(() => ({
44
runAgentEndSideEffects: vi.fn(),
5+
shouldWaitForCompletionRequiredAsyncTasks: vi.fn((): boolean => false),
6+
waitForCompletionRequiredAsyncTasks: vi.fn(),
57
}));
68

79
vi.mock("../../harness/agent-end-side-effects.js", () => ({
@@ -10,13 +12,19 @@ vi.mock("../../harness/agent-end-side-effects.js", () => ({
1012
vi.mock("./agent-end-context.js", () => ({
1113
buildEmbeddedAgentEndContext: () => ({}),
1214
}));
15+
vi.mock("./attempt.async-tasks.js", () => ({
16+
shouldWaitForCompletionRequiredAsyncTasks: hoisted.shouldWaitForCompletionRequiredAsyncTasks,
17+
waitForCompletionRequiredAsyncTasks: hoisted.waitForCompletionRequiredAsyncTasks,
18+
}));
1319

1420
import { completeEmbeddedAttemptAfterTurn } from "./attempt-after-turn.js";
1521
import { settleEmbeddedAttemptStream } from "./attempt-stream-settle.js";
1622

1723
describe("embedded attempt phase lifecycle state", () => {
1824
beforeEach(() => {
1925
hoisted.runAgentEndSideEffects.mockReset();
26+
hoisted.shouldWaitForCompletionRequiredAsyncTasks.mockReset().mockReturnValue(false);
27+
hoisted.waitForCompletionRequiredAsyncTasks.mockReset();
2028
});
2129

2230
it("re-reads compaction timeout state after the retry wait", async () => {
@@ -95,6 +103,135 @@ describe("embedded attempt phase lifecycle state", () => {
95103
expect(removeTrailingEntries).toHaveBeenCalledOnce();
96104
});
97105

106+
it("settles a user-aborted run whose async-task wait throws AbortError", async () => {
107+
const abortError = Object.assign(new Error("This operation was aborted"), {
108+
name: "AbortError",
109+
});
110+
hoisted.shouldWaitForCompletionRequiredAsyncTasks.mockReturnValue(true);
111+
hoisted.waitForCompletionRequiredAsyncTasks
112+
.mockRejectedValueOnce(abortError)
113+
.mockResolvedValueOnce({ timedOutRunIds: ["exec-run-1"] });
114+
const messages: never[] = [];
115+
const sessionManager = {
116+
appendCustomEntry: vi.fn(),
117+
buildSessionContext: () => ({ messages }),
118+
getEntries: () => [],
119+
removeTrailingEntries: vi.fn(() => 0),
120+
};
121+
const activeSession = {
122+
agent: { state: { messages } },
123+
isCompacting: false,
124+
isStreaming: false,
125+
messages,
126+
sessionId: "session-1",
127+
};
128+
129+
const result = await settleEmbeddedAttemptStream({
130+
attempt: {
131+
runId: "run-1",
132+
sessionId: "session-1",
133+
sessionKey: "agent:main:main",
134+
sessionFile: "/tmp/session.jsonl",
135+
provider: "test",
136+
modelId: "model",
137+
model: { api: "openai-responses" },
138+
} as never,
139+
activeSession: activeSession as never,
140+
sessionManager: sessionManager as never,
141+
sessionLockController: {} as never,
142+
withOwnedSessionWriteLock: async (operation) => await operation(),
143+
subscription: {
144+
toolMetas: [{ toolName: "exec", asyncStarted: true }],
145+
waitForCompactionRetry: async () => {},
146+
isCompactionInFlight: () => false,
147+
getCompactionCount: () => 0,
148+
getCurrentAttemptAssistant: () => undefined,
149+
getUsageTotals: () => undefined,
150+
getLastAssistantUsage: () => undefined,
151+
} as never,
152+
state: {
153+
promptError: null,
154+
promptErrorSource: null,
155+
yieldAborted: false,
156+
sessionIdUsed: "session-1",
157+
},
158+
readLifecycleState: () => ({
159+
aborted: true,
160+
timedOut: false,
161+
timedOutDuringCompaction: false,
162+
}),
163+
markTimedOutDuringCompaction: () => {},
164+
runAbortDeadlineAtMs: Date.now() + 60_000,
165+
runAbortSignal: AbortSignal.abort(),
166+
isProbeSession: true,
167+
abortable: async (promise) => await promise,
168+
prePromptMessageCount: 0,
169+
toolSearchTargetTranscriptProjections: [],
170+
cache: {
171+
observabilityEnabled: false,
172+
changesForTurn: null,
173+
retention: undefined,
174+
},
175+
shouldFlushForContextEngine: false,
176+
});
177+
178+
// The aborted run settles instead of unwinding the lane task, and its
179+
// unfinished async tasks are not reclassified as a timeout failure.
180+
expect(result.promptError).toBeNull();
181+
expect(hoisted.waitForCompletionRequiredAsyncTasks).toHaveBeenCalledTimes(2);
182+
});
183+
184+
it("emits an abort-classified agent_end event when a teardown error races the abort", async () => {
185+
const abortError = Object.assign(new Error("This operation was aborted"), {
186+
name: "AbortError",
187+
});
188+
await completeEmbeddedAttemptAfterTurn({
189+
attempt: {
190+
runId: "run-1",
191+
sessionId: "session-1",
192+
sessionFile: "/tmp/session.jsonl",
193+
} as never,
194+
activeSession: {} as never,
195+
sessionManager: { appendCustomEntry: vi.fn() } as never,
196+
sessionLockController: {} as never,
197+
withOwnedSessionWriteLock: async (operation) => await operation(),
198+
state: {
199+
promptError: abortError,
200+
yieldAborted: false,
201+
sessionIdUsed: "session-1",
202+
messagesSnapshot: [],
203+
prePromptMessageCount: 0,
204+
contextEngineAfterTurnCheckpoint: null,
205+
compactionOccurredThisAttempt: false,
206+
},
207+
readLifecycleState: () => ({
208+
aborted: true,
209+
timedOut: false,
210+
idleTimedOut: false,
211+
timedOutDuringCompaction: false,
212+
}),
213+
runtime: {
214+
effectiveWorkspace: "/tmp/workspace",
215+
agentDir: "/tmp/agent",
216+
sessionAgentId: "main",
217+
resolveActiveContextEnginePluginId: () => undefined,
218+
shouldRecordCompletedBootstrapTurn: false,
219+
cacheTrace: null,
220+
anthropicPayloadLogger: null,
221+
hookAgentId: "main",
222+
diagnosticTrace: { traceId: "trace-1", spanId: "span-1" } as never,
223+
skillWorkshopAvailable: true,
224+
hookRunner: null,
225+
promptStartedAt: Date.now(),
226+
},
227+
});
228+
229+
expect(hoisted.runAgentEndSideEffects).toHaveBeenCalledTimes(1);
230+
const event = hoisted.runAgentEndSideEffects.mock.calls[0]?.[0]?.event;
231+
expect(event).toMatchObject({ success: false });
232+
expect(event?.error).toBeUndefined();
233+
});
234+
98235
it("re-reads abort state inside the post-turn session write", async () => {
99236
let aborted = false;
100237
await completeEmbeddedAttemptAfterTurn({

‎src/agents/embedded-agent-runner/run/attempt-stream-finalize.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/** Settles the provider stream and completes the post-turn lifecycle phase. */
2+
import { isRunnerAbortError } from "../abort.js";
23
import { completeEmbeddedAttemptAfterTurn } from "./attempt-after-turn.js";
34
import { settleEmbeddedAttemptStream } from "./attempt-stream-settle.js";
45

@@ -70,7 +71,16 @@ export async function finalizeEmbeddedAttemptStreamPhase(input: {
7071
if (input.repairedRejectedThinkingReplay && !rewoundBeforeAgentFinalizeRevision) {
7172
activeSession.agent.state.messages = sessionManager.buildSessionContext().messages;
7273
}
73-
await sessionLockController.releaseForPrompt();
74+
try {
75+
await sessionLockController.releaseForPrompt();
76+
} catch (err) {
77+
// An aborted attempt never submits another prompt, so a submission-blocked
78+
// release is expected teardown noise. Rethrowing would skip settle and
79+
// after-turn, silently starving every agent_end consumer for aborted runs.
80+
if (!input.settle.readLifecycleState().aborted || !isRunnerAbortError(err)) {
81+
throw err;
82+
}
83+
}
7484

7585
const currentState = input.getState();
7686
const streamSettleState = {

‎src/agents/embedded-agent-runner/run/attempt-stream-settle.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,12 @@ export async function settleEmbeddedAttemptStream(input: {
144144
abortSignal: input.runAbortSignal,
145145
});
146146
} catch (err) {
147-
if (!input.readLifecycleState().timedOut || !isRunnerAbortError(err)) {
147+
// Timeouts AND user aborts must still settle so the attempt reaches
148+
// after-turn (transcript flush, agent-end side effects). Rethrowing here
149+
// unwinds the whole lane task and silently starves every agent_end
150+
// consumer for aborted runs.
151+
const lifecycle = input.readLifecycleState();
152+
if ((!lifecycle.timedOut && !lifecycle.aborted) || !isRunnerAbortError(err)) {
148153
throw err;
149154
}
150155
asyncTaskWait = await waitForCompletionRequiredAsyncTasks({
@@ -153,7 +158,9 @@ export async function settleEmbeddedAttemptStream(input: {
153158
deadlineAtMs: Date.now(),
154159
});
155160
}
156-
if (asyncTaskWait.timedOutRunIds.length > 0) {
161+
// An aborted run legitimately leaves async tasks unfinished; stamping a
162+
// timeout failure here would reclassify the abort as an errored completion.
163+
if (asyncTaskWait.timedOutRunIds.length > 0 && !input.readLifecycleState().aborted) {
157164
promptError = new Error(
158165
`Timed out waiting for async task completion: ${asyncTaskWait.timedOutRunIds.join(", ")}`,
159166
);

‎src/agents/embedded-agent-runner/run/attempt.abort-race.test.ts‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
2-
import { findAgentRunTerminalOutcome } from "../../agent-run-terminal-outcome.js";
2+
import { buildAgentRunTerminalOutcomeFromAttempt } from "../../agent-run-terminal-outcome.js";
33
import {
44
cleanupTempPaths,
55
createContextEngineAttemptRunner,
@@ -89,16 +89,14 @@ describe("runEmbeddedAttempt abort races", () => {
8989
},
9090
});
9191

92-
const error = await attempt.catch((caught: unknown) => caught);
92+
// The abort-blocked prompt release no longer unwinds the attempt: the run
93+
// settles so after-turn side effects still fire, and the run-budget
94+
// timeout attribution survives on the resolved terminal.
95+
const result = await attempt;
9396

94-
expect(error).toMatchObject({
95-
message: "attempt aborted before prompt submission",
96-
});
97-
expect(findAgentRunTerminalOutcome(error)).toMatchObject({
98-
reason: "hard_timeout",
97+
expect(result.terminal).toMatchObject({ kind: "timeout" });
98+
expect(buildAgentRunTerminalOutcomeFromAttempt({ terminal: result.terminal })).toMatchObject({
9999
status: "timeout",
100-
timeoutPhase: "provider",
101-
providerStarted: true,
102100
});
103101
});
104102
});

0 commit comments

Comments
 (0)