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

SubagentProjection.test.ts

753 lines24.6 KB

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