Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RestartBackgroundNote.test.ts

331 lines12.1 KB

1import { assert, it } from "@effect/vitest";
2import {
3 MessageId,
4 NodeId,
5 ProviderThreadId,
6 RunAttemptId,
7 RunId,
8 type OrchestrationV2Run,
9 type OrchestrationV2Subagent,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12​
13import {
14 cancelledRosterTaskWork,
15 cancelledTurnItemWork,
16 isAwaitedWork,
17 isRestartNoteContinuation,
18 pendingRestartCancelledBackgroundWork,
19 pendingStoppedDelegatedTasks,
20 restartContinuationNote,
21 stoppedDelegatedTasksNote,
22 mergeRestartCancelledBackgroundWork,
23} from "./RestartBackgroundNote.ts";
24​
25const claudeThread = ProviderThreadId.make("provider-thread:claude");
26const codexThread = ProviderThreadId.make("provider-thread:codex");
27const lost = [{ kind: "subagent" as const, label: "Background subagent test" }];
28​
29function run(
30 ordinal: number,
31 providerThreadId: ProviderThreadId,
32 extra: Partial<OrchestrationV2Run> = {},
33): OrchestrationV2Run {
34 return {
35 id: RunId.make(`run:${ordinal}`),
36 ordinal,
37 providerThreadId,
38 userMessageId: MessageId.make(`message:${ordinal}`),
39 activeAttemptId: RunAttemptId.make(`attempt:${ordinal}`),
40 status: "completed",
41 ...extra,
42 } as OrchestrationV2Run;
44​
45const turnFor = (source: OrchestrationV2Run) => ({
46 runAttemptId: source.activeAttemptId,
47 providerThreadId: source.providerThreadId!,
48 status: "completed" as const,
49});
50​
51it("keeps the note for the provider thread that lost the work across a provider switch", () => {
52 const root = run(1, claudeThread, { restartCancelledBackgroundWork: lost });
53 const onCodex = run(2, codexThread);
54 const backOnClaude = run(3, claudeThread);
55 const pending = (target: OrchestrationV2Run, runs: ReadonlyArray<OrchestrationV2Run>) =>
56 pendingRestartCancelledBackgroundWork({
57 runs,
58 providerTurns: runs.filter((source) => source.id !== target.id).map(turnFor),
59 compactionMessageIds: () => new Set(),
60 run: target,
61 attempts: [{ id: target.activeAttemptId!, runId: target.id }],
62 });
63​
64 assert.deepEqual(pending(onCodex, [root, onCodex]), []);
65 assert.deepEqual(pending(backOnClaude, [root, onCodex, backOnClaude]), lost);
66 const later = run(4, claudeThread);
67 assert.deepEqual(pending(later, [root, onCodex, backOnClaude, later]), []);
68});
69​
70it("delivers a resumed queued run's note even after a higher-ordinal run", () => {
71 const ranFirst = run(3, claudeThread, {
72 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
73 });
74 const resumed = run(2, claudeThread, {
75 completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z"),
76 restartCancelledBackgroundWork: lost,
77 });
78 const next = run(4, claudeThread);
79 const runs = [resumed, ranFirst, next];
80 assert.deepEqual(
81 pendingRestartCancelledBackgroundWork({
82 runs,
83 providerTurns: [resumed, ranFirst].map(turnFor),
84 compactionMessageIds: () => new Set(),
85 run: next,
86 attempts: [{ id: next.activeAttemptId!, runId: next.id }],
87 }),
88 lost,
89 );
90});
91​
92// regression: #19750 wake threads whose subagents' background work a restart cut
93it("names a lost subagent by the id the agent resumes it with", () => {
94 const ownShell = cancelledRosterTaskWork({
95 kind: "command",
96 taskId: "shell-1",
97 description: "sleep 150",
98 parentTaskId: "agent-1",
99 });
100 assert.deepEqual(ownShell, {
101 kind: "subagent",
102 label: "sleep 150 (subagent agent-1)",
103 id: "agent-1",
104 });
105 assert.isTrue(isAwaitedWork(ownShell));
106 const long = cancelledRosterTaskWork({
107 kind: "command",
108 taskId: "shell-1",
109 description: "d".repeat(400),
110 parentTaskId: "agent-1",
111 }).label;
112 assert.lengthOf(long, 160);
113 assert.isTrue(long.endsWith("(subagent agent-1)"));
114 const longId = cancelledRosterTaskWork({
115 kind: "command",
116 taskId: "shell-1",
117 parentTaskId: "a".repeat(400),
118 }).label;
119 assert.lengthOf(longId, 160);
120 assert.isTrue(
121 cancelledRosterTaskWork({
122 kind: "command",
123 taskId: "shell-1",
124 description: `${"d".repeat(158)}πŸš€ deploy`,
125 }).label.isWellFormed(),
126 );
127 assert.isFalse(isAwaitedWork(cancelledRosterTaskWork({ kind: "command", taskId: "shell-2" })));
128 assert.isTrue(
129 isAwaitedWork(cancelledRosterTaskWork({ kind: "command", taskId: "tests", awaited: true })),
130 );
131 assert.isFalse(isAwaitedWork(cancelledRosterTaskWork({ kind: "monitor", taskId: "watchdog" })));
132 assert.isTrue(
133 isAwaitedWork(cancelledRosterTaskWork({ kind: "monitor", taskId: "ci", awaited: true })),
134 );
135 const codexCommand = { id: "item-2", type: "command_execution", input: "sleep 180" };
136 assert.isFalse(isAwaitedWork(cancelledTurnItemWork(codexCommand as never)!));
137 assert.isTrue(
138 isAwaitedWork(cancelledTurnItemWork({ ...codexCommand, completionWake: "always" } as never)!),
139 );
140 assert.equal(
141 cancelledTurnItemWork({
142 id: "item-1",
143 type: "subagent",
144 origin: "provider_native",
145 title: "Review",
146 nativeItemRef: { driver: "claudeAgent", nativeId: "agent-1", strength: "strong" },
147 } as never)?.label,
148 "Review (id agent-1; resume it with SendMessage to 'agent-1')",
149 );
150 assert.equal(
151 cancelledTurnItemWork(
152 {
153 id: "item-2",
154 type: "subagent",
155 origin: "provider_native",
156 title: "Audit",
157 nativeItemRef: { driver: "codex", nativeId: "call_1:agent", strength: "strong" },
158 } as never,
159 "agent-thread",
160 )?.label,
161 "Audit (id agent-thread)",
162 );
163 assert.equal(
164 cancelledTurnItemWork({
165 id: "item-3",
166 type: "subagent",
167 origin: "provider_native",
168 title: "Lost",
169 nativeItemRef: { driver: "claudeAgent", nativeId: null, strength: "strong" },
170 } as never)?.label,
171 "Lost",
172 );
173});
174​
175it("keeps separate cancelled tasks that share a kind and label", () => {
176 const first = { kind: "shell" as const, label: "sleep 20", id: "item-1" };
177 const second = { kind: "shell" as const, label: "sleep 20", id: "item-2" };
178 const merged = mergeRestartCancelledBackgroundWork([first], [second, first]);
179 assert.deepEqual(merged, [first, second]);
180 const legacy = { kind: "shell" as const, label: "sleep 20" };
181 assert.lengthOf(mergeRestartCancelledBackgroundWork([legacy], [legacy]), 1);
182});
183​
184it("does not repeat the note when a steer restarts the run on a new attempt", () => {
185 const root = run(1, claudeThread, { restartCancelledBackgroundWork: lost });
186 const steered = run(2, claudeThread, {
187 activeAttemptId: RunAttemptId.make("attempt:2b"),
188 });
189 const firstAttempt = RunAttemptId.make("attempt:2a");
190 const pending = (runAttemptIds: ReadonlyArray<RunAttemptId>, delivered: boolean) =>
191 pendingRestartCancelledBackgroundWork({
192 runs: [root, steered],
193 providerTurns: [
194 turnFor(root),
195 ...(delivered
196 ? [
197 {
198 runAttemptId: firstAttempt,
199 providerThreadId: claudeThread,
200 status: "completed" as const,
201 },
202 ]
203 : []),
204 ],
205 compactionMessageIds: () => new Set(),
206 run: steered,
207 attempts: runAttemptIds.map((id) => ({ id, runId: steered.id })),
208 });
209​
210 assert.deepEqual(pending([firstAttempt, RunAttemptId.make("attempt:2b")], true), []);
211 assert.deepEqual(pending([firstAttempt, RunAttemptId.make("attempt:2b")], false), lost);
212});
213​
214it("counts a prompted mid-turn or chained continuation as delivering the note", () => {
215 const cut = run(1, claudeThread, { status: "cancelled", restartCancelledBackgroundWork: lost });
216 const cutTurn = { ...turnFor(cut), status: "cancelled" as const };
217 const continuation = run(2, claudeThread, { restartContinuationOfRunId: cut.id });
218 assert.isTrue(isRestartNoteContinuation(continuation, [cut, continuation], [cutTurn], []));
219 assert.isFalse(
220 isRestartNoteContinuation(
221 continuation,
222 [{ ...cut, restartCancelledBackgroundWork: [] }, continuation],
223 [cutTurn],
224 [],
225 ),
226 );
227 const later = run(3, claudeThread);
228 const pending = (delivered: boolean) =>
229 pendingRestartCancelledBackgroundWork({
230 runs: [cut, continuation, later],
231 providerTurns: [cutTurn, ...(delivered ? [turnFor(continuation)] : [])],
232 compactionMessageIds: () => new Set(),
233 run: later,
234 attempts: [{ id: later.activeAttemptId!, runId: later.id }],
235 });
236 assert.deepEqual(pending(true), []);
237 assert.deepEqual(pending(false), lost);
238​
239 const unstarted = { ...continuation, status: "cancelled" as const };
240 const chained = run(3, claudeThread, { restartContinuationOfRunId: unstarted.id });
241 assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], [cutTurn], []), {
242 work: lost,
243 settled: false,
244 });
245 assert.isTrue(isRestartNoteContinuation(chained, [cut, unstarted, chained], [cutTurn], []));
246 for (const status of ["running", "cancelled"] as const) {
247 const turns = [cutTurn, { ...turnFor(unstarted), status }];
248 assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], turns, []), {
249 work: lost,
250 settled: false,
251 });
252 assert.deepEqual(
253 pendingRestartCancelledBackgroundWork({
254 runs: [cut, unstarted, later],
255 providerTurns: turns,
256 compactionMessageIds: () => new Set(),
257 run: later,
258 attempts: [{ id: later.activeAttemptId!, runId: later.id }],
259 }),
260 lost,
261 );
262 }
263​
264 const steered = { ...unstarted, activeAttemptId: RunAttemptId.make("attempt:replacement") };
265 const attempts = [{ id: unstarted.activeAttemptId!, runId: steered.id }];
266 const turns = [
267 cutTurn,
268 turnFor(unstarted),
269 { ...turnFor(steered), status: "cancelled" as const },
270 ];
271 assert.deepEqual(restartContinuationNote(steered, [cut, steered], turns, attempts).work, []);
272 assert.isFalse(isRestartNoteContinuation(chained, [cut, steered, chained], turns, attempts));
273 assert.deepEqual(
274 pendingRestartCancelledBackgroundWork({
275 runs: [cut, steered, later],
276 providerTurns: turns,
277 compactionMessageIds: () => new Set(),
278 run: later,
279 attempts,
280 }),
281 [],
282 );
283});
284​
285// regression: #34401 Stop interrupted a parent's delegated tasks without telling its agent
286it("tells the next completed turn about delegated tasks its Stop interrupted, once", () => {
287 const at = (minute: number) => DateTime.makeUnsafe(`2026-10-03T10:0${minute}:00.000Z`);
288 const spawning = run(1, claudeThread, {
289 requestedAt: at(0),
290 delegatedCompletion: { disposition: "stopped", nextGeneration: 1, delivery: null },
291 });
292 const task = (id: string, extra: Partial<OrchestrationV2Subagent> = {}) =>
293 ({
294 id: NodeId.make(id),
295 runId: spawning.id,
296 origin: "app_owned",
297 prompt: `Run ${id}.`,
298 title: null,
299 status: "interrupted",
300 completionDelivery: { state: "disposed", observedByRunId: null },
301 completedAt: at(1),
302 ...extra,
303 }) as OrchestrationV2Subagent;
304 const stopped = task("stopped", { title: "Build A" });
305 const subagents = [
306 stopped,
307 task("cancelled", { cancelledRunId: RunId.make("run:child") }),
308 task("finished", { status: "completed" }),
309 task("delivered", { completionDelivery: { state: "delivered", observedByRunId: null } }),
310 ];
311 const pending = (runs: ReadonlyArray<OrchestrationV2Run>, providerThreadId = claudeThread) =>
312 pendingStoppedDelegatedTasks({
313 providerThreadId,
314 runs,
315 providerTurns: runs.map(turnFor),
316 attempts: runs.map((source) => ({ id: source.activeAttemptId!, runId: source.id })),
317 subagents,
318 compactionMessageIds: new Set(),
319 });
320​
321 assert.deepEqual(pending([spawning]), [stopped]);
322 // A /clear turn starts a fresh provider thread that never saw the stopped tasks.
323 assert.deepEqual(pending([spawning], codexThread), []);
324 assert.equal(stoppedDelegatedTasksNote([stopped]).split("\n")[1], "- Build A (task stopped)");
325 // Requested while the task was still settling, so its turn start could not see it.
326 const racing = run(2, claudeThread, { requestedAt: at(0), startedAt: at(2) });
327 assert.deepEqual(pending([spawning, racing]), [stopped]);
328 assert.deepEqual(pending([spawning, racing, run(3, claudeThread, { requestedAt: at(2) })]), []);
329 // A fresh-context turn on another provider thread never carried the note.
330 assert.deepEqual(pending([spawning, run(3, codexThread, { requestedAt: at(2) })]), [stopped]);
331});