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

RestartBackgroundNote.test.ts

224 lines8.0 KB

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 isRestartNoteContinuation,
15 pendingRestartCancelledBackgroundWork,
16 restartCancelledBackgroundWorkNote,
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;
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​
88it("bounds the note so it cannot crowd out the turn's context", () => {
89 const work = Array.from({ length: 25 }, (_, index) => ({
90 kind: "shell" as const,
91 label: `sleep ${index}`,
92 }));
93 const note = restartCancelledBackgroundWorkNote(work);
94 assert.lengthOf(note.split("\n"), 12);
95 assert.isTrue(note.endsWith("- and 15 more"));
96 const command = cancelledTurnItemWork({
97 type: "command_execution",
98 input: "x".repeat(10_000),
99 title: null,
100 } as never);
101 assert.isAtMost(command?.label.length ?? 0, 160);
102});
103​
104it("bounds roster task labels including a long task id", () => {
105 const work = cancelledRosterTaskWork({
106 kind: "command",
107 taskId: "t".repeat(400),
108 description: "d".repeat(400),
109 });
110 assert.equal(work.kind, "shell");
111 assert.lengthOf(work.label, 160);
112 const idOnly = cancelledRosterTaskWork({ kind: "background_task", taskId: "t".repeat(400) });
113 assert.lengthOf(idOnly.label, 160);
114});
115​
116it("keeps separate cancelled tasks that share a kind and label", () => {
117 const first = { kind: "shell" as const, label: "sleep 20", id: "item-1" };
118 const second = { kind: "shell" as const, label: "sleep 20", id: "item-2" };
119 const merged = mergeRestartCancelledBackgroundWork([first], [second, first]);
120 assert.deepEqual(merged, [first, second]);
121 const legacy = { kind: "shell" as const, label: "sleep 20" };
122 assert.lengthOf(mergeRestartCancelledBackgroundWork([legacy], [legacy]), 1);
123});
124​
125it("does not repeat the note when a steer restarts the run on a new attempt", () => {
126 const root = run(1, claudeThread, { restartCancelledBackgroundWork: lost });
127 const steered = run(2, claudeThread, {
128 activeAttemptId: RunAttemptId.make("attempt:2b"),
129 });
130 const firstAttempt = RunAttemptId.make("attempt:2a");
131 const pending = (runAttemptIds: ReadonlyArray<RunAttemptId>, delivered: boolean) =>
132 pendingRestartCancelledBackgroundWork({
133 runs: [root, steered],
134 providerTurns: [
135 turnFor(root),
136 ...(delivered
137 ? [
138 {
139 runAttemptId: firstAttempt,
140 providerThreadId: claudeThread,
141 status: "completed" as const,
142 },
143 ]
144 : []),
145 ],
146 compactionMessageIds: new Set(),
147 run: steered,
148 attempts: runAttemptIds.map((id) => ({ id, runId: steered.id })),
149 });
150​
151 assert.deepEqual(pending([firstAttempt, RunAttemptId.make("attempt:2b")], true), []);
152 assert.deepEqual(pending([firstAttempt, RunAttemptId.make("attempt:2b")], false), lost);
153});
154​
155it("counts a prompted mid-turn or chained continuation as delivering the note", () => {
156 const cut = run(1, claudeThread, { status: "cancelled", restartCancelledBackgroundWork: lost });
157 const cutTurn = { ...turnFor(cut), status: "cancelled" as const };
158 const continuation = run(2, claudeThread, { restartContinuationOfRunId: cut.id });
159 assert.isTrue(isRestartNoteContinuation(continuation, [cut, continuation], [cutTurn], []));
160 assert.isFalse(
161 isRestartNoteContinuation(
162 continuation,
163 [{ ...cut, restartCancelledBackgroundWork: [] }, continuation],
164 [cutTurn],
165 [],
166 ),
167 );
168 const later = run(3, claudeThread);
169 const pending = (delivered: boolean) =>
170 pendingRestartCancelledBackgroundWork({
171 runs: [cut, continuation, later],
172 providerTurns: [cutTurn, ...(delivered ? [turnFor(continuation)] : [])],
173 compactionMessageIds: new Set(),
174 run: later,
175 attempts: [{ id: later.activeAttemptId!, runId: later.id }],
176 });
177 assert.deepEqual(pending(true), []);
178 assert.deepEqual(pending(false), lost);
179​
180 const unstarted = { ...continuation, status: "cancelled" as const };
181 const chained = run(3, claudeThread, { restartContinuationOfRunId: unstarted.id });
182 assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], [cutTurn], []), {
183 work: lost,
184 settled: false,
185 });
186 assert.isTrue(isRestartNoteContinuation(chained, [cut, unstarted, chained], [cutTurn], []));
187 for (const status of ["running", "cancelled"] as const) {
188 const turns = [cutTurn, { ...turnFor(unstarted), status }];
189 assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], turns, []), {
190 work: lost,
191 settled: false,
192 });
193 assert.deepEqual(
194 pendingRestartCancelledBackgroundWork({
195 runs: [cut, unstarted, later],
196 providerTurns: turns,
197 compactionMessageIds: new Set(),
198 run: later,
199 attempts: [{ id: later.activeAttemptId!, runId: later.id }],
200 }),
201 lost,
202 );
203 }
204​
205 const steered = { ...unstarted, activeAttemptId: RunAttemptId.make("attempt:replacement") };
206 const attempts = [{ id: unstarted.activeAttemptId!, runId: steered.id }];
207 const turns = [
208 cutTurn,
209 turnFor(unstarted),
210 { ...turnFor(steered), status: "cancelled" as const },
211 ];
212 assert.deepEqual(restartContinuationNote(steered, [cut, steered], turns, attempts).work, []);
213 assert.isFalse(isRestartNoteContinuation(chained, [cut, steered, chained], turns, attempts));
214 assert.deepEqual(
215 pendingRestartCancelledBackgroundWork({
216 runs: [cut, steered, later],
217 providerTurns: turns,
218 compactionMessageIds: new Set(),
219 run: later,
220 attempts,
221 }),
222 [],
223 );
224});