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

main
ts 675 lines 22.1 KB
Raw
1 import { assert, it } from "@effect/vitest";
2 import {
3 CommandId,
4 EnvironmentId,
5 type ModelSelection,
6 NodeId,
7 RunId,
8 RunAttemptId,
9 MessageId,
10 EventId,
11 TurnItemId,
12 type OrchestrationV2Run,
13 type OrchestrationV2TurnItem,
14 type OrchestrationV2AppThread,
15 ProjectId,
16 ProviderInstanceId,
17 ProviderThreadId,
18 ThreadId,
19 } from "@t3tools/contracts";
20 import * as DateTime from "effect/DateTime";
21 import * as Effect from "effect/Effect";
22 import * as Layer from "effect/Layer";
23
24 import {
25 makeSubagentChildThread,
26 delegatedTaskProgress,
27 subagentResultForRun,
28 makeSubagentConversationArtifacts,
29 endOrphanedNativeSubagent,
30 endRunlessRootTurns,
31 PROVIDER_STOP_REASON_SIGNAL,
32 } from "@t3tools/provider-core/server/subagentProjection";
33 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
34
35 import * as SqlitePersistence from "../persistence/Sqlite.ts";
36 import * as ProjectionStore from "./ProjectionStore.ts";
37 import { resolveAutoSettlementAt } from "./ThreadSettlementService.ts";
38
39 const parentThreadId = ThreadId.make("thread:subagent-snoozed-parent");
40 const childThreadId = ThreadId.make("thread:subagent-awake-child");
41 const parentProviderInstanceId = ProviderInstanceId.make("codex");
42 const childProviderInstanceId = ProviderInstanceId.make("claude");
43 const parentModelSelection = {
44 instanceId: parentProviderInstanceId,
45 model: "gpt-5.4",
46 } satisfies ModelSelection;
47 const childModelSelection = {
48 instanceId: childProviderInstanceId,
49 model: "claude-opus-4-1",
50 } satisfies ModelSelection;
51 const parentCreatedAt = DateTime.makeUnsafe("2026-07-24T09:00:00.000Z");
52 const snoozedAt = DateTime.makeUnsafe("2026-07-24T09:05:00.000Z");
53 const snoozedUntil = DateTime.makeUnsafe("2026-07-25T09:00:00.000Z");
54 const childCreatedAt = DateTime.makeUnsafe("2026-07-24T09:10:00.000Z");
55
56 function makeParentThread(): OrchestrationV2AppThread {
57 return {
58 createdBy: "user",
59 creationSource: "web",
60 id: parentThreadId,
61 projectId: ProjectId.make("project:subagent-snooze"),
62 title: "Snoozed parent",
63 providerInstanceId: parentProviderInstanceId,
64 modelSelection: parentModelSelection,
65 runtimeMode: "full-access",
66 interactionMode: "plan",
67 branch: "feature/source",
68 worktreePath: "/tmp/source-worktree",
69 activeProviderThreadId: ProviderThreadId.make("provider-thread:subagent-snoozed-parent"),
70 lineage: {
71 parentThreadId: null,
72 relationshipToParent: null,
73 rootThreadId: parentThreadId,
74 },
75 forkedFrom: null,
76 createdAt: parentCreatedAt,
77 updatedAt: snoozedAt,
78 archivedAt: null,
79 settledOverride: null,
80 settledAt: null,
81 lastVisitedAt: null,
82 snoozedUntil,
83 snoozedAt,
84 deletedAt: null,
85 historyOrigin: "v1_import",
86 };
87 }
88
89 it("resets a subagent child's snooze, title job and remote delegation but keeps its workspace", () => {
90 const parentThread: OrchestrationV2AppThread = {
91 ...makeParentThread(),
92 titleRegeneration: { requestId: CommandId.make("command:parent-title"), startedAt: snoozedAt },
93 delegatedFrom: {
94 environmentId: EnvironmentId.make("linked-environment"),
95 threadId: ThreadId.make("linked-parent"),
96 title: "Linked parent",
97 },
98 };
99 const childProviderThreadId = ProviderThreadId.make("provider-thread:subagent-awake-child");
100 const parentNodeId = NodeId.make("node:subagent-parent");
101 const childThread = makeSubagentChildThread({
102 parentThread,
103 childThreadId,
104 parentNodeId,
105 activeProviderThreadId: childProviderThreadId,
106 providerInstanceId: childProviderInstanceId,
107 modelSelection: childModelSelection,
108 title: "Awake child",
109 now: childCreatedAt,
110 createdBy: "agent",
111 creationSource: "provider",
112 });
113
114 assert.isNull(childThread.snoozedUntil);
115 assert.isNull(childThread.snoozedAt);
116 assert.isNull(childThread.titleRegeneration);
117 assert.isUndefined(childThread.delegatedFrom);
118 assert.equal(childThread.projectId, parentThread.projectId);
119 assert.equal(childThread.runtimeMode, parentThread.runtimeMode);
120 assert.equal(childThread.interactionMode, parentThread.interactionMode);
121 assert.equal(childThread.branch, parentThread.branch);
122 assert.equal(childThread.worktreePath, parentThread.worktreePath);
123 assert.equal(childThread.providerInstanceId, childProviderInstanceId);
124 assert.deepEqual(childThread.modelSelection, childModelSelection);
125 assert.equal(childThread.activeProviderThreadId, childProviderThreadId);
126 assert.isUndefined(childThread.historyOrigin);
127 assert.deepEqual(childThread.lineage, {
128 parentThreadId,
129 relationshipToParent: "subagent",
130 rootThreadId: parentThreadId,
131 });
132 assert.deepEqual(childThread.forkedFrom, {
133 type: "node",
134 nodeId: parentNodeId,
135 });
136 });
137
138 it.effect.each(["provider", "mcp"] as const)(
139 "a %s child does not inherit parent settlement protections and settles once its parent settles",
140 (creationSource) =>
141 Effect.gen(function* () {
142 const store = yield* ProjectionStore.ProjectionStoreV2;
143 const parentThread = {
144 ...makeParentThread(),
145 pinnedAt: parentCreatedAt,
146 pinOrderKey: "a0",
147 autoSettleDisabledAt: parentCreatedAt,
148 };
149 const childThread = makeSubagentChildThread({
150 parentThread,
151 childThreadId,
152 parentNodeId: NodeId.make("node:subagent-parent"),
153 activeProviderThreadId: null,
154 providerInstanceId: childProviderInstanceId,
155 modelSelection: childModelSelection,
156 title: "Child",
157 now: childCreatedAt,
158 createdBy: "agent",
159 creationSource,
160 });
161
162 assert.equal(parentThread.pinnedAt, parentCreatedAt);
163 assert.equal(parentThread.pinOrderKey, "a0");
164 assert.isNull(childThread.pinnedAt);
165 assert.isNull(childThread.pinOrderKey);
166 assert.isNull(childThread.autoSettleDisabledAt);
167
168 for (const thread of [parentThread, childThread]) {
169 yield* store.apply({
170 id: EventId.make(`event:${thread.id}`),
171 type: "thread.created",
172 threadId: thread.id,
173 occurredAt: thread.createdAt,
174 payload: thread,
175 });
176 }
177 const savedParent = yield* store.getThread(parentThreadId);
178 assert.deepEqual(savedParent.pinnedAt, parentCreatedAt);
179 assert.equal(savedParent.pinOrderKey, "a0");
180 assert.deepEqual(savedParent.autoSettleDisabledAt, parentCreatedAt);
181 // A subagent child waits for its parent, so settle the pinned parent first.
182 assert.deepEqual(yield* store.getSettlementCandidates(), []);
183 yield* store.apply({
184 id: EventId.make(`event:${parentThreadId}:settled`),
185 type: "thread.settled",
186 threadId: parentThreadId,
187 occurredAt: childCreatedAt,
188 payload: {
189 ...savedParent,
190 settledOverride: "settled",
191 settledAt: childCreatedAt,
192 pinnedAt: null,
193 pinOrderKey: null,
194 },
195 });
196 const candidates = yield* store.getSettlementCandidates();
197 assert.deepEqual(
198 candidates.map((candidate) => candidate.id),
199 [childThreadId],
200 );
201 const settledAt = resolveAutoSettlementAt({
202 thread: candidates[0]!,
203 pullRequest: null,
204 nowMs: DateTime.toEpochMillis(DateTime.add(childCreatedAt, { days: 4 })),
205 autoSettleAfterDays: 3,
206 autoSettleOnMerge: false,
207 });
208 assert.equal(settledAt && DateTime.formatIso(settledAt), DateTime.formatIso(childCreatedAt));
209 }).pipe(
210 Effect.provide(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory))),
211 ),
212 );
213
214 function taskFixture() {
215 const projection = ProjectionStore.emptyProjection({
216 type: "thread.created",
217 id: EventId.make("task-fixture"),
218 threadId: parentThreadId,
219 occurredAt: parentCreatedAt,
220 payload: makeParentThread(),
221 });
222 const run: OrchestrationV2Run = {
223 id: RunId.make("initial"),
224 threadId: parentThreadId,
225 ordinal: 1,
226 providerInstanceId: parentProviderInstanceId,
227 modelSelection: parentModelSelection,
228 providerThreadId: null,
229 userMessageId: MessageId.make("prompt"),
230 rootNodeId: NodeId.make("root"),
231 activeAttemptId: RunAttemptId.make("attempt"),
232 status: "completed",
233 requestedAt: parentCreatedAt,
234 startedAt: parentCreatedAt,
235 completedAt: childCreatedAt,
236 checkpointId: null,
237 contextHandoffId: null,
238 };
239 return { projection: { ...projection, runs: [run] }, run };
240 }
241
242 it("reports the run that ended last, not the highest ordinal", () => {
243 const { projection, run } = taskFixture();
244 const ended = (ordinal: number, completedAt: string): OrchestrationV2Run => ({
245 ...run,
246 id: RunId.make(`run:${ordinal}`),
247 ordinal,
248 completedAt: DateTime.makeUnsafe(completedAt),
249 });
250 const progress = delegatedTaskProgress({
251 ...projection,
252 runs: [
253 { ...run, status: "cancelled" },
254 ended(4, "2026-07-24T10:00:00.000Z"),
255 ended(2, "2026-07-24T10:05:00.000Z"),
256 ended(3, "2026-07-24T10:10:00.000Z"),
257 ],
258 });
259 assert.equal(progress.state, "result_available");
260 assert.equal(progress.resultRun?.ordinal, 3);
261 });
262
263 it("waits for nested work and retains the report across monitor acknowledgements", () => {
264 const { projection, run } = taskFixture();
265 assert.equal(
266 delegatedTaskProgress({ ...projection, subagents: [{ status: "running" }] }).state,
267 "waiting_for_children",
268 );
269 assert.equal(
270 delegatedTaskProgress({ ...projection, subagents: [{ status: "completed" }] }).state,
271 "result_available",
272 );
273 assert.equal(
274 delegatedTaskProgress({ ...projection, subagents: [{ status: "idle" }] }).state,
275 "result_available",
276 );
277 for (const state of ["pending", "claimed"] as const) {
278 assert.equal(
279 delegatedTaskProgress({
280 ...projection,
281 subagents: [{ status: "idle", completionDelivery: { state, observedByRunId: null } }],
282 }).state,
283 "result_available",
284 );
285 assert.equal(
286 delegatedTaskProgress({
287 ...projection,
288 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
289 }).state,
290 "waiting_for_children",
291 );
292 }
293 for (const state of ["acknowledged", "delivered", "disposed"] as const) {
294 assert.equal(
295 delegatedTaskProgress({
296 ...projection,
297 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
298 }).state,
299 "result_available",
300 );
301 }
302 for (const [awaited, state] of [
303 [true, "waiting_for_children"],
304 [false, "result_available"],
305 ] as const) {
306 assert.equal(
307 delegatedTaskProgress({
308 ...projection,
309 providerThreads: [
310 {
311 pendingBackgroundTasks: [
312 { taskId: "background-audit", kind: "command", ...(awaited ? { awaited } : {}) },
313 { taskId: "log-watcher", kind: "monitor" },
314 ],
315 },
316 ],
317 }).state,
318 state,
319 );
320 }
321 const pending = {
322 ...run,
323 id: RunId.make("followup"),
324 ordinal: 2,
325 status: "queued" as const,
326 startedAt: null,
327 };
328 assert.equal(delegatedTaskProgress({ ...projection, runs: [run, pending] }).state, "working");
329 const cancelled = { ...run, status: "cancelled" as const };
330 const held = delegatedTaskProgress({
331 ...projection,
332 runs: [cancelled, { ...pending, queueHeld: true }],
333 });
334 assert.equal(held.state, "result_available");
335 assert.equal(held.resultRun?.id, cancelled.id);
336 const report = { ...pending, status: "completed" as const, startedAt: parentCreatedAt };
337 const monitor = { ...report, id: RunId.make("monitor"), ordinal: 3 };
338 const artifacts = makeSubagentConversationArtifacts({
339 messageId: MessageId.make("monitor-message"),
340 turnItemId: TurnItemId.make("monitor-item"),
341 threadId: parentThreadId,
342 rootNodeId: NodeId.make("root"),
343 providerThreadId: null,
344 providerTurnId: null,
345 nativeItemRef: null,
346 role: "user",
347 text: "Monitor update",
348 ordinal: 3,
349 now: childCreatedAt,
350 });
351 const progress = delegatedTaskProgress({
352 ...projection,
353 runs: [run, report, monitor],
354 messages: [
355 {
356 ...artifacts.message,
357 runId: monitor.id,
358 notification: {
359 source: { kind: "monitor" },
360 outcome: "updated",
361 summary: "Monitor update",
362 },
363 },
364 ],
365 });
366 assert.equal(progress.state, "result_available");
367 assert.equal(progress.resultRun?.id, report.id);
368 const ended = { ...report, id: RunId.make("monitor-ended"), ordinal: 4 };
369 const afterMonitorEnded = delegatedTaskProgress({
370 ...projection,
371 runs: [run, report, monitor, ended],
372 messages: [
373 {
374 ...artifacts.message,
375 runId: monitor.id,
376 notification: {
377 source: { kind: "monitor" },
378 outcome: "updated",
379 summary: "Monitor update",
380 },
381 },
382 {
383 ...artifacts.message,
384 runId: ended.id,
385 notification: {
386 source: { kind: "monitor" },
387 outcome: "completed",
388 summary: 'Monitor "ticks" finished',
389 },
390 },
391 ],
392 });
393 assert.equal(afterMonitorEnded.resultRun?.id, ended.id);
394 });
395
396 it("keeps the report when a run queued behind it ends without assistant text", () => {
397 const { projection, run } = taskFixture();
398 const report = makeSubagentConversationArtifacts({
399 messageId: MessageId.make("report"),
400 turnItemId: TurnItemId.make("report"),
401 threadId: parentThreadId,
402 rootNodeId: NodeId.make("root"),
403 providerThreadId: null,
404 providerTurnId: null,
405 nativeItemRef: null,
406 role: "assistant",
407 text: "REPORT-OK",
408 ordinal: 1,
409 now: childCreatedAt,
410 });
411 const queued: OrchestrationV2Run = {
412 ...run,
413 id: RunId.make("queued-after-report"),
414 ordinal: 2,
415 userMessageId: MessageId.make("queued-message"),
416 startedAt: DateTime.makeUnsafe("2026-07-24T10:00:00.000Z"),
417 completedAt: DateTime.makeUnsafe("2026-07-24T10:00:01.000Z"),
418 };
419 for (const notification of [
420 undefined,
421 {
422 source: { kind: "command" as const },
423 outcome: "completed" as const,
424 summary: "1 command finished",
425 },
426 ]) {
427 const child = {
428 ...projection,
429 runs: [run, queued],
430 messages: [
431 { ...report.message, runId: run.id },
432 {
433 ...report.message,
434 id: MessageId.make("queued-message"),
435 runId: queued.id,
436 role: "user" as const,
437 text: "ACK-SILENT",
438 ...(notification ? { notification } : {}),
439 },
440 ],
441 turnItems: [{ ...report.turnItem, runId: run.id }],
442 };
443 const progress = delegatedTaskProgress(child);
444 assert.equal(progress.state, "result_available");
445 assert.equal(subagentResultForRun(child, progress.resultRun!).text, "REPORT-OK");
446 // Another task's run, or one that did not complete, keeps its own outcome.
447 for (const other of [
448 { ...queued, delegatedTaskId: NodeId.make("follow-up") },
449 { ...queued, status: "interrupted" as const },
450 ]) {
451 assert.notInclude(
452 subagentResultForRun({ ...child, runs: [run, other] }, other).text,
453 "REPORT-OK",
454 );
455 }
456 }
457 });
458
459 it("exposes the provider failure rather than a progress message from the failed run", () => {
460 const { projection, run } = taskFixture();
461 const failedRun = { ...run, status: "failed" as const };
462 const artifacts = makeSubagentConversationArtifacts({
463 messageId: MessageId.make("progress"),
464 turnItemId: TurnItemId.make("error"),
465 threadId: parentThreadId,
466 rootNodeId: NodeId.make("root"),
467 providerThreadId: null,
468 providerTurnId: null,
469 nativeItemRef: null,
470 role: "assistant",
471 text: "Starting the audit.",
472 ordinal: 1,
473 now: childCreatedAt,
474 });
475 if (artifacts.turnItem.type !== "assistant_message") throw new Error("Expected assistant item");
476 const failure = {
477 class: "unknown" as const,
478 message: "You've hit your usage limit. Try again Sep 14 at 7:20 PM.",
479 code: null,
480 retryable: false,
481 };
482 const result = subagentResultForRun(
483 {
484 ...projection,
485 messages: [{ ...artifacts.message, runId: run.id }],
486 turnItems: [{ ...artifacts.turnItem, type: "error", runId: run.id, failure }],
487 },
488 failedRun,
489 );
490 assert.equal(result.text, failure.message);
491 assert.equal(result.turnItemId, artifacts.turnItem.id);
492 assert.isNull(result.messageId);
493 });
494
495 it("reports a provider's stop reason for a completed run without an assistant result", () => {
496 const { projection, run } = taskFixture();
497 const notice = {
498 id: IdAllocator.derive.runSignalTurnItem({
499 runId: run.id,
500 signal: PROVIDER_STOP_REASON_SIGNAL,
501 }),
502 threadId: parentThreadId,
503 runId: run.id,
504 nodeId: NodeId.make("root"),
505 providerThreadId: null,
506 providerTurnId: null,
507 nativeItemRef: null,
508 parentItemId: null,
509 ordinal: 98,
510 status: "completed",
511 title: "Stopped by the provider",
512 startedAt: childCreatedAt,
513 completedAt: childCreatedAt,
514 updatedAt: childCreatedAt,
515 type: "system_notice",
516 level: "warning",
517 message: "sessionStart hook (user): Plugin guard blocked this session.",
518 } satisfies OrchestrationV2TurnItem;
519 assert.equal(
520 subagentResultForRun({ ...projection, turnItems: [notice] }, run).text,
521 `Child task completed without an assistant result.\n\n${notice.message}`,
522 );
523 });
524
525 it("keeps the final report of a run that failed after its turn ended", () => {
526 const { projection, run } = taskFixture();
527 const failedRun = { ...run, status: "failed" as const };
528 const artifacts = makeSubagentConversationArtifacts({
529 messageId: MessageId.make("report"),
530 turnItemId: TurnItemId.make("report"),
531 threadId: parentThreadId,
532 rootNodeId: NodeId.make("root"),
533 providerThreadId: null,
534 providerTurnId: null,
535 nativeItemRef: null,
536 role: "assistant",
537 text: "Review complete: no blocking issues.",
538 ordinal: 1,
539 now: childCreatedAt,
540 });
541 if (artifacts.turnItem.type !== "assistant_message") throw new Error("Expected assistant item");
542 const failure = {
543 class: "unknown" as const,
544 message: "Connection failed repeatedly",
545 code: null,
546 retryable: false,
547 };
548 const result = subagentResultForRun(
549 {
550 ...projection,
551 messages: [{ ...artifacts.message, runId: run.id }],
552 turnItems: [
553 { ...artifacts.turnItem, runId: run.id },
554 {
555 ...artifacts.turnItem,
556 id: TurnItemId.make("error"),
557 ordinal: 2,
558 type: "error",
559 runId: run.id,
560 failure,
561 },
562 ],
563 },
564 failedRun,
565 );
566 assert.include(result.text, failure.message);
567 assert.include(result.text, "Review complete: no blocking issues.");
568 });
569
570 it("orders a task's assistant messages by turn item, not by timestamps", () => {
571 const { projection, run } = taskFixture();
572 const at = DateTime.makeUnsafe("2026-07-24T10:05:00.000Z");
573 const message = (id: string, text: string, ordinal: number) => {
574 const artifacts = makeSubagentConversationArtifacts({
575 messageId: MessageId.make(id),
576 turnItemId: TurnItemId.make(id),
577 threadId: parentThreadId,
578 rootNodeId: NodeId.make("root"),
579 providerThreadId: null,
580 providerTurnId: null,
581 nativeItemRef: null,
582 role: "assistant",
583 text,
584 ordinal,
585 now: at,
586 });
587 return {
588 message: { ...artifacts.message, runId: run.id },
589 turnItem: { ...artifacts.turnItem, runId: run.id },
590 };
591 };
592 const progress = message("progress", "Starting step 0.", 1);
593 const report = message("report", "All steps passed.", 2);
594 const result = subagentResultForRun(
595 {
596 ...projection,
597 messages: [progress.message, report.message],
598 turnItems: [report.turnItem, progress.turnItem],
599 },
600 run,
601 );
602 assert.equal(result.text, "All steps passed.");
603 assert.equal(result.messageId, report.message.id);
604 assert.equal(result.turnItemId, report.turnItem.id);
605 const reported = { runAttemptId: run.activeAttemptId, ordinal: 1, model: "gpt-5.4-mini" };
606 assert.equal(
607 subagentResultForRun(
608 { ...projection, messages: [report.message], providerTurns: [reported as never] },
609 run,
610 ).text,
611 "Requested model gpt-5.4; the provider reported running gpt-5.4-mini.\n\nAll steps passed.",
612 );
613 });
614
615 it.effect("ends an orphaned native subagent's node when only its record already ended", () =>
616 Effect.gen(function* () {
617 const id = NodeId.make("node:orphaned-native-subagent");
618 const subagent = { id, origin: "provider_native", status: "running", runId: null };
619 const events = yield* endOrphanedNativeSubagent({
620 projection: {
621 subagents: [subagent],
622 nodes: [{ id, status: "running", runId: null }],
623 turnItems: [],
624 } as never,
625 subagentId: id,
626 status: "cancelled",
627 now: yield* DateTime.now,
628 emitted: [
629 { type: "subagent.updated", payload: { ...subagent, status: "cancelled" } },
630 ] as never,
631 allocateEventId: () => Effect.succeed(EventId.make("event:orphaned-native-subagent")),
632 });
633 assert.deepEqual(
634 events.map((event) => [event.type, event.type === "node.updated" && event.payload.status]),
635 [["node.updated", "cancelled"]],
636 );
637 }),
638 );
639
640 it.effect("ends a runless root turn's items when its node already ended", () =>
641 Effect.gen(function* () {
642 const root = {
643 id: NodeId.make("node:runless-root"),
644 kind: "root_turn",
645 status: "running",
646 runId: null,
647 };
648 const item = (id: string) => ({ id, nodeId: root.id, runId: null, status: "running" });
649 const events = yield* endRunlessRootTurns({
650 threadId: childThreadId,
651 providerInstanceId: parentProviderInstanceId,
652 projection: {
653 nodes: [root],
654 providerTurns: [],
655 turnItems: [item("turn-item:command"), item("turn-item:reasoning")],
656 } as never,
657 status: "cancelled",
658 now: yield* DateTime.now,
659 emitted: [
660 {
661 type: "turn-item.updated",
662 payload: { ...item("turn-item:command"), status: "cancelled" },
663 },
664 { type: "node.updated", payload: { ...root, status: "cancelled" } },
665 ] as never,
666 allocateEventId: () => Effect.succeed(EventId.make("event:runless-root")),
667 });
668 assert.deepEqual(
669 events.map(
670 (event) => `${event.type} ${event.type === "turn-item.updated" && event.payload.id}`,
671 ),
672 ["turn-item.updated turn-item:reasoning"],
673 );
674 }),
675 );