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