Skip to content

Commit 5620ea7

Browse files
steipetePeter Steinberger
andauthored
fix(tui): canonical terminal outcomes, cancellation, and error privacy (#117044)
* fix(tui): preserve canonical terminal and queued cancellation outcomes * refactor(tui): unify terminal projection without growing production code * fix(tui): respect authoritative abort facts and sanitize structured errors * fix(tui): surface canonical error-only terminal outcomes * fix(tui): retain queued turn fences and canonical terminal reasons * fix(tui): preserve transitive queue fences and trusted terminal ownership * fix(tui): follow canceled queue ancestry through bounded maintenance waits * fix(tui): preserve canonical safe terminal outcomes and cancel queued turns * fix(agents): redact every lifecycle error at its producer * test(agents): keep terminal lifecycle fixtures fully typed --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 10b7a33 commit 5620ea7

4 files changed

Lines changed: 906 additions & 183 deletions

File tree

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { buildAgentRunTerminalOutcome } from "../agent-run-terminal-outcome.js";
3+
import { createAgentCommandLifecycle } from "./lifecycle.js";
4+
5+
const emitAgentEvent = vi.hoisted(() => vi.fn());
6+
7+
vi.mock("../../infra/agent-events.js", () => ({ emitAgentEvent }));
8+
vi.mock("../../logging/subsystem.js", () => ({
9+
createSubsystemLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
10+
}));
11+
12+
describe("createAgentCommandLifecycle", () => {
13+
it.each(["finishing", "end", "error"] as const)(
14+
"preserves only canonical terminal facts on %s events",
15+
(phase) => {
16+
emitAgentEvent.mockClear();
17+
const secret = ["sk", "abcdefghijklmnopqrstuv"].join("-");
18+
const metadata = {
19+
aborted: true,
20+
stopReason: "timeout",
21+
timeoutPhase: "provider",
22+
providerStarted: true,
23+
livenessState: "blocked",
24+
yielded: true,
25+
replayInvalid: true,
26+
error: { message: `Authorization: Bearer ${secret}`, nested: { secret } },
27+
unsafeMetadata: { credential: secret },
28+
};
29+
const lifecycle = createAgentCommandLifecycle({
30+
runId: "terminal-owner",
31+
lifecycleGeneration: () => "test-generation",
32+
startedAt: 100,
33+
state: {
34+
currentTurnUserMessagePersisted: true,
35+
lifecycleFinishing: false,
36+
lifecycleEnded: false,
37+
},
38+
});
39+
const terminal = {
40+
metadata,
41+
outcome: buildAgentRunTerminalOutcome({ status: "timeout", ...metadata }),
42+
};
43+
44+
if (phase === "finishing") {
45+
lifecycle.emitFinishing(terminal);
46+
} else if (phase === "end") {
47+
lifecycle.emitEnd(terminal);
48+
} else {
49+
lifecycle.emitResultError(
50+
{
51+
payloads: [],
52+
meta: {
53+
durationMs: 0,
54+
error: { kind: "retry_limit", message: "internal provider diagnostic" },
55+
},
56+
},
57+
true,
58+
terminal,
59+
);
60+
}
61+
62+
expect(emitAgentEvent).toHaveBeenCalledWith(
63+
expect.objectContaining({
64+
runId: "terminal-owner",
65+
stream: "lifecycle",
66+
data: expect.objectContaining({
67+
phase,
68+
aborted: true,
69+
stopReason: "timeout",
70+
timeoutPhase: "provider",
71+
providerStarted: true,
72+
livenessState: "blocked",
73+
yielded: true,
74+
replayInvalid: true,
75+
...(phase === "error" ? { fallbackExhaustedFailure: true } : {}),
76+
}),
77+
}),
78+
);
79+
expect(JSON.stringify(emitAgentEvent.mock.calls[0]?.[0])).not.toContain(secret);
80+
expect(emitAgentEvent.mock.calls[0]?.[0]?.data).not.toHaveProperty("unsafeMetadata");
81+
},
82+
);
83+
84+
it.each(["lifecycle callback", "fallback payload", "post-turn error"] as const)(
85+
"redacts credentials from a %s before publishing the lifecycle event",
86+
(source) => {
87+
emitAgentEvent.mockClear();
88+
const secret = ["sk", "abcdefghijklmnopqrstuv"].join("-");
89+
const error = `The provider failed. Authorization: Bearer ${secret}`;
90+
const state = {
91+
currentTurnUserMessagePersisted: true,
92+
lifecycleFinishing: false,
93+
lifecycleEnded: false,
94+
...(source === "lifecycle callback" ? { lifecycleError: error } : {}),
95+
};
96+
const lifecycle = createAgentCommandLifecycle({
97+
runId: "secret-safe-terminal-owner",
98+
lifecycleGeneration: () => "test-generation",
99+
startedAt: 100,
100+
state,
101+
});
102+
const terminal = {
103+
metadata: {},
104+
outcome: buildAgentRunTerminalOutcome({ status: "error", stopReason: "error" }),
105+
};
106+
107+
if (source === "post-turn error") {
108+
lifecycle.emitPostTurnError(new Error(error));
109+
} else {
110+
lifecycle.emitResultError(
111+
{
112+
payloads: source === "fallback payload" ? [{ isError: true, text: error }] : [],
113+
meta: { durationMs: 0 },
114+
},
115+
source === "fallback payload",
116+
terminal,
117+
);
118+
}
119+
120+
const event = emitAgentEvent.mock.calls[0]?.[0];
121+
expect(event.data.error).toContain("The provider failed.");
122+
expect(event.data.error).toContain("Authorization: Bearer");
123+
expect(JSON.stringify(event)).not.toContain(secret);
124+
},
125+
);
126+
127+
it.each(["finishing", "end", "error"] as const)(
128+
"rejects malformed canonical metadata on %s events",
129+
(phase) => {
130+
emitAgentEvent.mockClear();
131+
const secret = ["sk", "abcdefghijklmnopqrstuv"].join("-");
132+
const malicious = { authorization: `Bearer ${secret}`, nested: { secret } };
133+
const lifecycle = createAgentCommandLifecycle({
134+
runId: "malformed-terminal-owner",
135+
lifecycleGeneration: () => "test-generation",
136+
startedAt: 100,
137+
state: {
138+
currentTurnUserMessagePersisted: true,
139+
lifecycleFinishing: false,
140+
lifecycleEnded: false,
141+
},
142+
});
143+
const terminal = {
144+
metadata: {
145+
aborted: malicious,
146+
stopReason: malicious,
147+
yielded: malicious,
148+
timeoutPhase: malicious,
149+
providerStarted: malicious,
150+
livenessState: malicious,
151+
replayInvalid: malicious,
152+
error: malicious,
153+
unknownMetadata: malicious,
154+
},
155+
outcome: buildAgentRunTerminalOutcome({ status: "error", stopReason: "error" }),
156+
};
157+
158+
if (phase === "finishing") {
159+
lifecycle.emitFinishing(terminal);
160+
} else if (phase === "end") {
161+
lifecycle.emitEnd(terminal);
162+
} else {
163+
lifecycle.emitResultError({ payloads: [], meta: { durationMs: 0 } }, false, terminal);
164+
}
165+
166+
const event = emitAgentEvent.mock.calls[0]?.[0];
167+
expect(event.data).toMatchObject({ phase, aborted: false, stopReason: "error" });
168+
expect(JSON.stringify(event)).not.toContain(secret);
169+
for (const field of [
170+
"yielded",
171+
"timeoutPhase",
172+
"providerStarted",
173+
"livenessState",
174+
"replayInvalid",
175+
"unknownMetadata",
176+
]) {
177+
expect(event.data).not.toHaveProperty(field);
178+
}
179+
},
180+
);
181+
});

‎src/agents/command/lifecycle.ts‎

Lines changed: 34 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { emitAgentEvent } from "../../infra/agent-events.js";
2+
import { formatErrorMessage } from "../../infra/errors.js";
23
import { createSubsystemLogger } from "../../logging/subsystem.js";
34
import {
45
buildAgentRunTerminalOutcome,
@@ -84,6 +85,35 @@ export function createAgentCommandLifecycle(params: {
8485
)?.text
8586
: undefined) ??
8687
(runResult.meta.error ? "Agent run failed" : undefined);
88+
const emitTerminalPhase = (
89+
phase: "finishing" | "end" | "error",
90+
terminal: EmbeddedAgentRunEntryTerminal,
91+
error?: string,
92+
fallbackExhausted?: boolean,
93+
) => {
94+
const { aborted, yielded, replayInvalid } = terminal.metadata;
95+
const { stopReason, livenessState, timeoutPhase, providerStarted } = terminal.outcome;
96+
emitAgentEvent({
97+
runId: params.runId,
98+
lifecycleGeneration: params.lifecycleGeneration(),
99+
stream: "lifecycle",
100+
data: {
101+
phase,
102+
startedAt: params.startedAt,
103+
endedAt: Date.now(),
104+
aborted: typeof aborted === "boolean" ? aborted : false,
105+
stopReason,
106+
...(yielded === true ? { yielded } : {}),
107+
...(replayInvalid === true ? { replayInvalid } : {}),
108+
...(livenessState ? { livenessState } : {}),
109+
...(timeoutPhase ? { timeoutPhase } : {}),
110+
...(providerStarted !== undefined ? { providerStarted } : {}),
111+
...(error ? { error: formatErrorMessage(error) } : {}),
112+
...(fallbackExhausted ? { fallbackExhaustedFailure: true } : {}),
113+
...resolveAgentRunAbortLifecycleFields(params.abortSignal),
114+
},
115+
});
116+
};
87117

88118
return {
89119
emitFinishing(terminal: EmbeddedAgentRunEntryTerminal) {
@@ -96,19 +126,7 @@ export function createAgentCommandLifecycle(params: {
96126
}
97127
lifecycleFinishingEmitted = true;
98128
params.state.lifecycleFinishing = true;
99-
emitAgentEvent({
100-
runId: params.runId,
101-
lifecycleGeneration: params.lifecycleGeneration(),
102-
stream: "lifecycle",
103-
data: {
104-
phase: "finishing",
105-
startedAt: params.startedAt,
106-
endedAt: Date.now(),
107-
aborted: terminal.metadata.aborted ?? false,
108-
stopReason: terminal.outcome.stopReason,
109-
...resolveAgentRunAbortLifecycleFields(params.abortSignal),
110-
},
111-
});
129+
emitTerminalPhase("finishing", terminal);
112130
},
113131
emitEnd(terminal: EmbeddedAgentRunEntryTerminal) {
114132
if (params.state.lifecycleEnded) {
@@ -120,19 +138,7 @@ export function createAgentCommandLifecycle(params: {
120138
if (logLevel) {
121139
log[logLevel](`[agent] run ${params.runId} ended with stopReason=${stopReason}`);
122140
}
123-
emitAgentEvent({
124-
runId: params.runId,
125-
lifecycleGeneration: params.lifecycleGeneration(),
126-
stream: "lifecycle",
127-
data: {
128-
phase: "end",
129-
startedAt: params.startedAt,
130-
endedAt: Date.now(),
131-
aborted: terminal.metadata.aborted ?? false,
132-
stopReason,
133-
...resolveAgentRunAbortLifecycleFields(params.abortSignal),
134-
},
135-
});
141+
emitTerminalPhase("end", terminal);
136142
},
137143
resolveResultError,
138144
emitResultError(
@@ -147,19 +153,7 @@ export function createAgentCommandLifecycle(params: {
147153
const error =
148154
resolveResultError(runResult, fallbackExhausted) ??
149155
(fallbackExhausted ? "All model fallback candidates failed" : "Agent run failed");
150-
emitAgentEvent({
151-
runId: params.runId,
152-
lifecycleGeneration: params.lifecycleGeneration(),
153-
stream: "lifecycle",
154-
data: {
155-
phase: "error",
156-
startedAt: params.startedAt,
157-
endedAt: Date.now(),
158-
error,
159-
...terminal.metadata,
160-
...(fallbackExhausted ? { fallbackExhaustedFailure: true } : {}),
161-
},
162-
});
156+
emitTerminalPhase("error", terminal, error, fallbackExhausted);
163157
},
164158
emitPostTurnError(error: unknown) {
165159
if (params.state.lifecycleEnded) {
@@ -174,7 +168,7 @@ export function createAgentCommandLifecycle(params: {
174168
phase: "error",
175169
startedAt: params.startedAt,
176170
endedAt: Date.now(),
177-
error: error instanceof Error ? error.message : "Agent run failed",
171+
error: formatErrorMessage(error),
178172
...resolveAgentRunErrorLifecycleFields(error, params.abortSignal),
179173
},
180174
});

0 commit comments

Comments
 (0)