The best way to control Claude Code, Codex and more from any computer or phone

main
ts 279 lines 9.71 KB
Raw
1 import { assert, it } from "@effect/vitest";
2 import {
3 MessageId,
4 ProviderThreadId,
5 RunAttemptId,
6 RunId,
7 type OrchestrationV2Run,
8 } from "@t3tools/contracts";
9 import * as DateTime from "effect/DateTime";
10
11 import {
12 cancelledRosterTaskWork,
13 cancelledTurnItemWork,
14 isAwaitedWork,
15 isRestartNoteContinuation,
16 pendingRestartCancelledBackgroundWork,
17 restartContinuationNote,
18 mergeRestartCancelledBackgroundWork,
19 } from "./RestartBackgroundNote.ts";
20
21 const claudeThread = ProviderThreadId.make("provider-thread:claude");
22 const codexThread = ProviderThreadId.make("provider-thread:codex");
23 const lost = [{ kind: "subagent" as const, label: "Background subagent test" }];
24
25 function 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
41 const turnFor = (source: OrchestrationV2Run) => ({
42 runAttemptId: source.activeAttemptId,
43 providerThreadId: source.providerThreadId!,
44 status: "completed" as const,
45 });
46
47 it("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
66 it("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
89 it("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 const codexCommand = { id: "item-2", type: "command_execution", input: "sleep 180" };
132 assert.isFalse(isAwaitedWork(cancelledTurnItemWork(codexCommand as never)!));
133 assert.isTrue(
134 isAwaitedWork(cancelledTurnItemWork({ ...codexCommand, completionWake: "always" } as never)!),
135 );
136 assert.equal(
137 cancelledTurnItemWork({
138 id: "item-1",
139 type: "subagent",
140 origin: "provider_native",
141 title: "Review",
142 nativeItemRef: { driver: "claudeAgent", nativeId: "agent-1", strength: "strong" },
143 } as never)?.label,
144 "Review (id agent-1; resume it with SendMessage to 'agent-1')",
145 );
146 assert.equal(
147 cancelledTurnItemWork(
148 {
149 id: "item-2",
150 type: "subagent",
151 origin: "provider_native",
152 title: "Audit",
153 nativeItemRef: { driver: "codex", nativeId: "call_1:agent", strength: "strong" },
154 } as never,
155 "agent-thread",
156 )?.label,
157 "Audit (id agent-thread)",
158 );
159 assert.equal(
160 cancelledTurnItemWork({
161 id: "item-3",
162 type: "subagent",
163 origin: "provider_native",
164 title: "Lost",
165 nativeItemRef: { driver: "claudeAgent", nativeId: null, strength: "strong" },
166 } as never)?.label,
167 "Lost",
168 );
169 });
170
171 it("keeps separate cancelled tasks that share a kind and label", () => {
172 const first = { kind: "shell" as const, label: "sleep 20", id: "item-1" };
173 const second = { kind: "shell" as const, label: "sleep 20", id: "item-2" };
174 const merged = mergeRestartCancelledBackgroundWork([first], [second, first]);
175 assert.deepEqual(merged, [first, second]);
176 const legacy = { kind: "shell" as const, label: "sleep 20" };
177 assert.lengthOf(mergeRestartCancelledBackgroundWork([legacy], [legacy]), 1);
178 });
179
180 it("does not repeat the note when a steer restarts the run on a new attempt", () => {
181 const root = run(1, claudeThread, { restartCancelledBackgroundWork: lost });
182 const steered = run(2, claudeThread, {
183 activeAttemptId: RunAttemptId.make("attempt:2b"),
184 });
185 const firstAttempt = RunAttemptId.make("attempt:2a");
186 const pending = (runAttemptIds: ReadonlyArray<RunAttemptId>, delivered: boolean) =>
187 pendingRestartCancelledBackgroundWork({
188 runs: [root, steered],
189 providerTurns: [
190 turnFor(root),
191 ...(delivered
192 ? [
193 {
194 runAttemptId: firstAttempt,
195 providerThreadId: claudeThread,
196 status: "completed" as const,
197 },
198 ]
199 : []),
200 ],
201 compactionMessageIds: () => new Set(),
202 run: steered,
203 attempts: runAttemptIds.map((id) => ({ id, runId: steered.id })),
204 });
205
206 assert.deepEqual(pending([firstAttempt, RunAttemptId.make("attempt:2b")], true), []);
207 assert.deepEqual(pending([firstAttempt, RunAttemptId.make("attempt:2b")], false), lost);
208 });
209
210 it("counts a prompted mid-turn or chained continuation as delivering the note", () => {
211 const cut = run(1, claudeThread, { status: "cancelled", restartCancelledBackgroundWork: lost });
212 const cutTurn = { ...turnFor(cut), status: "cancelled" as const };
213 const continuation = run(2, claudeThread, { restartContinuationOfRunId: cut.id });
214 assert.isTrue(isRestartNoteContinuation(continuation, [cut, continuation], [cutTurn], []));
215 assert.isFalse(
216 isRestartNoteContinuation(
217 continuation,
218 [{ ...cut, restartCancelledBackgroundWork: [] }, continuation],
219 [cutTurn],
220 [],
221 ),
222 );
223 const later = run(3, claudeThread);
224 const pending = (delivered: boolean) =>
225 pendingRestartCancelledBackgroundWork({
226 runs: [cut, continuation, later],
227 providerTurns: [cutTurn, ...(delivered ? [turnFor(continuation)] : [])],
228 compactionMessageIds: () => new Set(),
229 run: later,
230 attempts: [{ id: later.activeAttemptId!, runId: later.id }],
231 });
232 assert.deepEqual(pending(true), []);
233 assert.deepEqual(pending(false), lost);
234
235 const unstarted = { ...continuation, status: "cancelled" as const };
236 const chained = run(3, claudeThread, { restartContinuationOfRunId: unstarted.id });
237 assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], [cutTurn], []), {
238 work: lost,
239 settled: false,
240 });
241 assert.isTrue(isRestartNoteContinuation(chained, [cut, unstarted, chained], [cutTurn], []));
242 for (const status of ["running", "cancelled"] as const) {
243 const turns = [cutTurn, { ...turnFor(unstarted), status }];
244 assert.deepEqual(restartContinuationNote(unstarted, [cut, unstarted], turns, []), {
245 work: lost,
246 settled: false,
247 });
248 assert.deepEqual(
249 pendingRestartCancelledBackgroundWork({
250 runs: [cut, unstarted, later],
251 providerTurns: turns,
252 compactionMessageIds: () => new Set(),
253 run: later,
254 attempts: [{ id: later.activeAttemptId!, runId: later.id }],
255 }),
256 lost,
257 );
258 }
259
260 const steered = { ...unstarted, activeAttemptId: RunAttemptId.make("attempt:replacement") };
261 const attempts = [{ id: unstarted.activeAttemptId!, runId: steered.id }];
262 const turns = [
263 cutTurn,
264 turnFor(unstarted),
265 { ...turnFor(steered), status: "cancelled" as const },
266 ];
267 assert.deepEqual(restartContinuationNote(steered, [cut, steered], turns, attempts).work, []);
268 assert.isFalse(isRestartNoteContinuation(chained, [cut, steered, chained], turns, attempts));
269 assert.deepEqual(
270 pendingRestartCancelledBackgroundWork({
271 runs: [cut, steered, later],
272 providerTurns: turns,
273 compactionMessageIds: () => new Set(),
274 run: later,
275 attempts,
276 }),
277 [],
278 );
279 });