Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 MessageId,
4 ProviderThreadId,
5 RunAttemptId,
6 RunId,
7 type OrchestrationV2Run,
8} from "@t3tools/contracts";
9import * as DateTime from "effect/DateTime";
10
11import {
12 cancelledRosterTaskWork,
13 cancelledTurnItemWork,
14 isAwaitedWork,
15 isRestartNoteContinuation,
16 pendingRestartCancelledBackgroundWork,
17 restartCancelledBackgroundWorkNote,
18 restartContinuationNote,
19 mergeRestartCancelledBackgroundWork,
20} from "./RestartBackgroundNote.ts";
21
22const claudeThread = ProviderThreadId.make("provider-thread:claude");
23const codexThread = ProviderThreadId.make("provider-thread:codex");
24const lost = [{ kind: "subagent" as const, label: "Background subagent test" }];
25
26function run(
27 ordinal: number,
28 providerThreadId: ProviderThreadId,
29 extra: Partial<OrchestrationV2Run> = {},
30): OrchestrationV2Run {
31 return {
32 id: RunId.make(`run:${ordinal}`),
33 ordinal,
34 providerThreadId,
35 userMessageId: MessageId.make(`message:${ordinal}`),
36 activeAttemptId: RunAttemptId.make(`attempt:${ordinal}`),
37 status: "completed",
38 ...extra,
39 } as OrchestrationV2Run;
40}
41
42const turnFor = (source: OrchestrationV2Run) => ({
43 runAttemptId: source.activeAttemptId,
44 providerThreadId: source.providerThreadId!,
45 status: "completed" as const,
46});
47
48it("keeps the note for the provider thread that lost the work across a provider switch", () => {
49 const root = run(1, claudeThread, { restartCancelledBackgroundWork: lost });
50 const onCodex = run(2, codexThread);
51 const backOnClaude = run(3, claudeThread);
52 const pending = (target: OrchestrationV2Run, runs: ReadonlyArray<OrchestrationV2Run>) =>
53 pendingRestartCancelledBackgroundWork({
54 runs,
55 providerTurns: runs.filter((source) => source.id !== target.id).map(turnFor),
56 compactionMessageIds: new Set(),
57 run: target,
58 attempts: [{ id: target.activeAttemptId!, runId: target.id }],
59 });
60
61 assert.deepEqual(pending(onCodex, [root, onCodex]), []);
62 assert.deepEqual(pending(backOnClaude, [root, onCodex, backOnClaude]), lost);
63 const later = run(4, claudeThread);
64 assert.deepEqual(pending(later, [root, onCodex, backOnClaude, later]), []);
65});
66
67it("delivers a resumed queued run's note even after a higher-ordinal run", () => {
68 const ranFirst = run(3, claudeThread, {
69 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
70 });
71 const resumed = run(2, claudeThread, {
72 completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z"),
73 restartCancelledBackgroundWork: lost,
74 });
75 const next = run(4, claudeThread);
76 const runs = [resumed, ranFirst, next];
77 assert.deepEqual(
78 pendingRestartCancelledBackgroundWork({
79 runs,
80 providerTurns: [resumed, ranFirst].map(turnFor),
81 compactionMessageIds: new Set(),
82 run: next,
83 attempts: [{ id: next.activeAttemptId!, runId: next.id }],
84 }),
85 lost,
86 );
87});
88
89it("bounds the note so it cannot crowd out the turn's context", () => {
90 const work = Array.from({ length: 25 }, (_, index) => ({
91 kind: "shell" as const,
92 label: `sleep ${index}`,
93 }));
94 const note = restartCancelledBackgroundWorkNote(work);
95 assert.lengthOf(note.split("\n"), 12);
96 assert.isTrue(note.endsWith("- and 15 more"));
97 const command = cancelledTurnItemWork({
98 type: "command_execution",
99 input: "x".repeat(10_000),
100 title: null,
101 } as never);
102 assert.isAtMost(command?.label.length ?? 0, 160);
103});
104
105it("bounds roster task labels including a long task id", () => {
106 const work = cancelledRosterTaskWork({
107 kind: "command",
108 taskId: "t".repeat(400),
109 description: "d".repeat(400),
110 });
111 assert.equal(work.kind, "shell");
112 assert.lengthOf(work.label, 160);
113 const idOnly = cancelledRosterTaskWork({ kind: "background_task", taskId: "t".repeat(400) });
114 assert.lengthOf(idOnly.label, 160);
115});
116
117it("names a lost subagent by the id the agent resumes it with", () => {
118 const ownShell = cancelledRosterTaskWork({
119 kind: "command",
120 taskId: "shell-1",
121 description: "sleep 150",
122 parentTaskId: "agent-1",
123 });
124 // The agent waits on the subagent, which waits on its shell.
125 assert.deepEqual(ownShell, {
126 kind: "subagent",
127 label: "sleep 150 (subagent agent-1)",
128 id: "agent-1",
129 });
130 assert.isTrue(isAwaitedWork(ownShell));
131 const long = cancelledRosterTaskWork({
132 kind: "command",
133 taskId: "shell-1",
134 description: "d".repeat(400),
135 parentTaskId: "agent-1",
136 }).label;
137 assert.lengthOf(long, 160);
138 assert.isTrue(long.endsWith("(subagent agent-1)"));
139 const longId = cancelledRosterTaskWork({
140 kind: "command",
141 taskId: "shell-1",
142 parentTaskId: "a".repeat(400),
143 }).label;
144 assert.lengthOf(longId, 160);
145 assert.isFalse(isAwaitedWork(cancelledRosterTaskWork({ kind: "command", taskId: "shell-2" })));
146 assert.equal(
147 cancelledTurnItemWork({
148 id: "item-1",
149 type: "subagent",
150 origin: "provider_native",
151 title: "Review",
152 nativeItemRef: { driver: "claudeAgent", nativeId: "agent-1", strength: "strong" },
153 } as never)?.label,
154 "Review (id agent-1)",
155 );
156});
157
158it("keeps separate cancelled tasks that share a kind and label", () => {
159 const first = { kind: "shell" as const, label: "sleep 20", id: "item-1" };
160 const second = { kind: "shell" as const, label: "sleep 20", id: "item-2" };
161 const merged = mergeRestartCancelledBackgroundWork([first], [second, first]);
162 assert.deepEqual(merged, [first, second]);
163 const legacy = { kind: "shell" as const, label: "sleep 20" };
164 assert.lengthOf(mergeRestartCancelledBackgroundWork([legacy], [legacy]), 1);
165});
166
167it("does not repeat the note when a steer restarts the run on a new attempt", () => {
168 const root = run(1, claudeThread, { restartCancelledBackgroundWork: lost });
169 const steered = run(2, claudeThread, {
170 activeAttemptId: RunAttemptId.make("attempt:2b"),
171 });
172 const firstAttempt = RunAttemptId.make("attempt:2a");
173 const pending = (runAttemptIds: ReadonlyArray<RunAttemptId>, delivered: boolean) =>
174 pendingRestartCancelledBackgroundWork({
175 runs: [root, steered],
176 providerTurns: [
177 turnFor(root),
178 ...(delivered
179 ? [
180 {
181 runAttemptId: firstAttempt,
182 providerThreadId: claudeThread,
183 status: "completed" as const,
184 },
185 ]
186 : []),
187 ],
188 compactionMessageIds: new Set(),
189 run: steered,
190 attempts: runAttemptIds.map((id) => ({ id, runId: steered.id })),
191 });
192
193 assert.deepEqual(pending([firstAttempt, RunAttemptId.make("attempt:2b")], true), []);
194 assert.deepEqual(pending([firstAttempt, RunAttemptId.make("attempt:2b")], false), lost);
195});
196
197it("counts a prompted mid-turn or chained continuation as delivering the note", () => {
198 const cut = run(1, claudeThread, { status: "cancelled", restartCancelledBackgroundWork: lost });
199 const cutTurn = { ...turnFor(cut), status: "cancelled" as const };
200 const continuation = run(2, claudeThread, { restartContinuationOfRunId: cut.id });
201 assert.isTrue(isRestartNoteContinuation(continuation, [cut, continuation], [cutTurn], []));
202 assert.isFalse(
203 isRestartNoteContinuation(
204 continuation,
205 [{ ...cut, restartCancelledBackgroundWork: [] }, continuation],
206 [cutTurn],
207 [],
208 ),
209 );
210 const later = run(3, claudeThread);
211 const pending = (delivered: boolean) =>
212 pendingRestartCancelledBackgroundWork({
213 runs: [cut, continuation, later],
214 providerTurns: [cutTurn, ...(delivered ? [turnFor(continuation)] : [])],
215 compactionMessageIds: new Set(),
216 run: later,
217 attempts: [{ id: later.activeAttemptId!, runId: later.id }],
218 });
219 assert.deepEqual(pending(true), []);
220 assert.deepEqual(pending(false), lost);
221
222 const unstarted = { ...continuation, status: "cancelled" as const };
223 const chained = run(3, claudeThread, { restartContinuationOfRunId: unstarted.id });
224 assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], [cutTurn], []), {
225 work: lost,
226 settled: false,
227 });
228 assert.isTrue(isRestartNoteContinuation(chained, [cut, unstarted, chained], [cutTurn], []));
229 for (const status of ["running", "cancelled"] as const) {
230 const turns = [cutTurn, { ...turnFor(unstarted), status }];
231 assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], turns, []), {
232 work: lost,
233 settled: false,
234 });
235 assert.deepEqual(
236 pendingRestartCancelledBackgroundWork({
237 runs: [cut, unstarted, later],
238 providerTurns: turns,
239 compactionMessageIds: new Set(),
240 run: later,
241 attempts: [{ id: later.activeAttemptId!, runId: later.id }],
242 }),
243 lost,
244 );
245 }
246
247 const steered = { ...unstarted, activeAttemptId: RunAttemptId.make("attempt:replacement") };
248 const attempts = [{ id: unstarted.activeAttemptId!, runId: steered.id }];
249 const turns = [
250 cutTurn,
251 turnFor(unstarted),
252 { ...turnFor(steered), status: "cancelled" as const },
253 ];
254 assert.deepEqual(restartContinuationNote(steered, [cut, steered], turns, attempts).work, []);
255 assert.isFalse(isRestartNoteContinuation(chained, [cut, steered, chained], turns, attempts));
256 assert.deepEqual(
257 pendingRestartCancelledBackgroundWork({
258 runs: [cut, steered, later],
259 providerTurns: turns,
260 compactionMessageIds: new Set(),
261 run: later,
262 attempts,
263 }),
264 [],
265 );
266});