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

threadExecution.test.ts

746 lines24.8 KB

1import {
2 TurnItemId,
3 NodeId,
4 MessageId,
5 ProviderInstanceId,
6 ProviderThreadId,
7 ProviderSessionId,
8 ProviderDriverKind,
9 ProviderTurnId,
10 RunAttemptId,
11 RunId,
12 ThreadId,
13 type OrchestrationV2ExecutionNode,
14 type OrchestrationV2RunStatus,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import { usageLimitBlockedRun } from "@t3tools/shared/orchestrationV2ThreadError";
18import { describe, expect, it } from "vite-plus/test";
19​
20import { v2Projection } from "./orchestrationV2TestFixtures.ts";
21import {
22 presentPendingBackgroundWork,
23 presentProviderGoal,
24 deriveReportedModelSelection,
25 deriveLatestThreadRun,
26 deriveProviderSubagentStatus,
27 formatModelSelectionEffort,
28 formatProviderSubagentStatus,
29 deriveRunlessWorkStartedAt,
30 deriveThreadActivityRun,
31 deriveThreadRuntime,
32 threadRuntimeHasInterruptibleRun,
33} from "./threadExecution.ts";
34import { threadRuntimeCanArchive, type ThreadRuntimeSummary } from "./models.ts";
35​
36const now = DateTime.makeUnsafe("2026-07-28T10:00:00.000Z");
37​
38function run(id: string, ordinal: number, status: OrchestrationV2RunStatus) {
39 return {
40 id: RunId.make(id),
41 threadId: v2Projection.thread.id,
42 ordinal,
43 providerInstanceId: v2Projection.thread.providerInstanceId,
44 modelSelection: v2Projection.thread.modelSelection,
45 providerThreadId: null,
46 userMessageId: MessageId.make(`message-${id}`),
47 rootNodeId: null,
48 activeAttemptId: null,
49 status,
50 requestedAt: now,
51 startedAt: status === "queued" ? null : now,
52 completedAt: null,
53 checkpointId: null,
54 contextHandoffId: null,
55 };
57​
58describe("thread execution presentation", () => {
59 it("derives the current root failure without inheriting errors from children or previous runs", () => {
60 const failed = { ...run("limited", 1, "failed"), rootNodeId: NodeId.make("root") };
61 const item = {
62 id: TurnItemId.make("limit-error"),
63 threadId: v2Projection.thread.id,
64 runId: failed.id,
65 nodeId: failed.rootNodeId,
66 providerThreadId: null,
67 providerTurnId: null,
68 nativeItemRef: null,
69 parentItemId: null,
70 ordinal: 1,
71 type: "error" as const,
72 status: "failed" as const,
73 title: "Usage limit reached",
74 startedAt: now,
75 completedAt: now,
76 updatedAt: now,
77 failure: {
78 class: "usage_limit" as const,
79 message: "Plan limit reached",
80 code: "usageLimitExceeded",
81 retryable: null,
82 },
83 };
84 const projection = { ...v2Projection, runs: [failed], turnItems: [item] };
85 expect(deriveThreadRuntime(projection)).toMatchObject({
86 lastError: "Plan limit reached",
87 lastErrorClass: "usage_limit",
88 });
89 expect(
90 deriveThreadRuntime({
91 ...projection,
92 turnItems: [{ ...item, nodeId: NodeId.make("child") }],
93 }),
94 ).toMatchObject({ lastError: null, lastErrorClass: null });
95 expect(
96 deriveThreadRuntime({
97 ...projection,
98 runs: [{ ...failed, rootNodeId: NodeId.make("new-root") }],
99 }),
100 ).toMatchObject({ lastError: null, lastErrorClass: null });
101 expect(
102 deriveThreadRuntime({ ...projection, runs: [failed, run("new", 2, "running")] }),
103 ).toMatchObject({ status: "running", lastError: null, lastErrorClass: null });
104 });
105​
106 it("counts a wake run's activity from the start of the work it continues", () => {
107 const workStartedAt = DateTime.makeUnsafe("2026-07-28T09:20:00.000Z");
108 const wake = { ...run("wake", 2, "running"), workStartedAt };
109 expect(
110 deriveThreadRuntime({ ...v2Projection, runs: [run("prompt", 1, "completed"), wake] })
111 ?.activityStartedAt,
112 ).toBe("2026-07-28T09:20:00.000Z");
113 expect(
114 deriveThreadRuntime({ ...v2Projection, runs: [run("prompt", 1, "running")] })
115 ?.activityStartedAt,
116 ).toBe("2026-07-28T10:00:00.000Z");
117 });
118​
119 it("keeps a subscription limit visible while later messages stay queued", () => {
120 const failed = {
121 ...run("limited", 1, "failed"),
122 rootNodeId: NodeId.make("root"),
123 completedAt: now,
124 };
125 const queued = run("queued", 2, "queued");
126 const item = {
127 id: TurnItemId.make("limit-error"),
128 threadId: v2Projection.thread.id,
129 runId: failed.id,
130 nodeId: failed.rootNodeId,
131 providerThreadId: null,
132 providerTurnId: null,
133 nativeItemRef: null,
134 parentItemId: null,
135 ordinal: 1,
136 type: "error" as const,
137 status: "failed" as const,
138 title: "Usage limit reached",
139 startedAt: now,
140 completedAt: now,
141 updatedAt: now,
142 failure: {
143 class: "usage_limit" as const,
144 message: "Plan limit reached",
145 code: "usageLimitExceeded",
146 retryable: null,
147 },
148 };
149 const projection = { ...v2Projection, runs: [failed, queued], turnItems: [item] };
150​
151 expect(deriveLatestThreadRun(projection)?.runId).toBe(failed.id);
152 expect(deriveThreadActivityRun(projection)?.runId).toBe(failed.id);
153 expect(deriveThreadRuntime(projection)).toMatchObject({
154 status: "failed",
155 lastError: "Plan limit reached",
156 lastErrorClass: "usage_limit",
157 });
158 const cancelledQueued = {
159 ...run("cancelled-queued", 3, "cancelled"),
160 startedAt: null,
161 completedAt: now,
162 };
163 expect(
164 usageLimitBlockedRun([failed, queued, cancelledQueued], projection.turnItems, null)?.id,
165 ).toBe(failed.id);
166 expect(
167 deriveThreadRuntime({ ...projection, runs: [failed, queued, cancelledQueued] }),
168 ).toMatchObject({ status: "failed", lastErrorClass: "usage_limit" });
169 expect(
170 deriveThreadRuntime({
171 ...projection,
172 turnItems: [{ ...item, failure: { ...item.failure, class: "provider_error" as const } }],
173 }),
174 ).toMatchObject({ status: "queued", lastErrorClass: null });
175 });
176​
177 it("keeps live activity attached to an executing run when a newer run is queued", () => {
178 const runningRun = run("run-running", 1, "running");
179 const queuedRun = run("run-queued", 2, "queued");
180 const projection = { ...v2Projection, runs: [queuedRun, runningRun], updatedAt: now };
181​
182 expect(deriveLatestThreadRun(projection)?.runId).toBe(queuedRun.id);
183 expect(deriveThreadActivityRun(projection)).toMatchObject({
184 runId: runningRun.id,
185 status: "running",
186 });
187​
188 const runtime = deriveThreadRuntime(projection);
189 expect(runtime).toMatchObject({
190 status: "running",
191 activeRunId: runningRun.id,
192 });
193 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
194 });
195​
196 it("marks an open run whose provider turn already ended", () => {
197 const attemptId = RunAttemptId.make("attempt-open");
198 const openRun = { ...run("run-open", 1, "running"), activeAttemptId: attemptId };
199 const providerTurn = (status: "running" | "failed") => ({
200 id: ProviderTurnId.make("provider-turn-open"),
201 providerThreadId: ProviderThreadId.make("provider-thread-open"),
202 nodeId: NodeId.make("node-open"),
203 runAttemptId: attemptId,
204 nativeTurnRef: null,
205 ordinal: 1,
206 status,
207 startedAt: now,
208 completedAt: status === "running" ? null : now,
209 });
210 const projection = (status: "running" | "failed") => ({
211 ...v2Projection,
212 runs: [openRun],
213 providerTurns: [providerTurn(status)],
214 updatedAt: now,
215 });
216​
217 expect(deriveThreadActivityRun(projection("running"))?.turnEnded).toBeUndefined();
218 expect(deriveThreadActivityRun(projection("failed"))).toMatchObject({
219 status: "running",
220 turnEnded: true,
221 });
222 });
223​
224 it("presents a held queue as the stopped run instead of queued work", () => {
225 const interrupted = { ...run("run-interrupted", 1, "interrupted"), completedAt: now };
226 const held = { ...run("run-held", 2, "queued"), queueHeld: true };
227 const projection = { ...v2Projection, runs: [interrupted, held], updatedAt: now };
228​
229 expect(deriveLatestThreadRun(projection)?.runId).toBe(interrupted.id);
230 expect(deriveThreadActivityRun(projection)?.runId).toBe(interrupted.id);
231 expect(deriveThreadRuntime(projection)).toMatchObject({
232 status: "interrupted",
233 activeRunId: null,
234 });
235​
236 const resumed = { ...projection, runs: [interrupted, { ...held, queueHeld: false }] };
237 expect(deriveThreadRuntime(resumed)).toMatchObject({ status: "queued" });
238​
239 const onlyHeld = {
240 ...projection,
241 runs: [held],
242 thread: { ...projection.thread, activeProviderThreadId: null },
243 };
244 expect(deriveLatestThreadRun(onlyHeld)).toBeNull();
245 expect(deriveThreadRuntime(onlyHeld)).toBeNull();
246 });
247​
248 it("does not expose a queued-only run as interruptible", () => {
249 const queuedRun = run("run-queued", 1, "queued");
250 const projection = { ...v2Projection, runs: [queuedRun], updatedAt: now };
251​
252 expect(deriveThreadActivityRun(projection)).toMatchObject({
253 runId: queuedRun.id,
254 status: "queued",
255 });
256​
257 const runtime = deriveThreadRuntime(projection);
258 expect(runtime).toMatchObject({
259 status: "queued",
260 activeRunId: null,
261 });
262 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
263 });
264​
265 it("keeps checkpoint-wait activity visible without exposing a non-functional interrupt", () => {
266 const waitingRun = run("run-waiting", 1, "waiting");
267 const projection = { ...v2Projection, runs: [waitingRun], updatedAt: now };
268​
269 expect(deriveThreadActivityRun(projection)).toMatchObject({
270 runId: waitingRun.id,
271 status: "waiting",
272 });
273​
274 const runtime = deriveThreadRuntime(projection);
275 expect(runtime).toMatchObject({
276 status: "waiting",
277 activeRunId: null,
278 });
279 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
280 });
281​
282 it("does not expose a stale active run after the runtime parks at idle", () => {
283 const runtime = {
284 status: "idle" as const,
285 activeRunId: RunId.make("run-stale"),
286 providerInstanceId: v2Projection.thread.providerInstanceId,
287 providerName: null,
288 lastError: null,
289 updatedAt: DateTime.formatIso(now),
290 };
291​
292 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
293 });
294​
295 it.each(["preparing", "starting"] as const)("keeps an active %s run interruptible", (status) => {
296 const runtime = {
297 status,
298 activeRunId: RunId.make(`run-${status}`),
299 providerInstanceId: v2Projection.thread.providerInstanceId,
300 providerName: null,
301 lastError: null,
302 updatedAt: DateTime.formatIso(now),
303 };
304​
305 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
306 });
307});
308​
309describe("deriveRunlessWorkStartedAt", () => {
310 const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z");
311 const rootTurn = (
312 status: OrchestrationV2ExecutionNode["status"],
313 startedAt = now,
314 ): OrchestrationV2ExecutionNode => ({
315 id: NodeId.make("child-root"),
316 threadId: v2Projection.thread.id,
317 runId: null,
318 parentNodeId: null,
319 rootNodeId: NodeId.make("child-root"),
320 kind: "root_turn",
321 status,
322 countsForRun: false,
323 providerThreadId: null,
324 providerTurnId: null,
325 nativeItemRef: null,
326 runtimeRequestId: null,
327 checkpointScopeId: null,
328 startedAt,
329 completedAt: null,
330 });
331​
332 const nativeChild = {
333 ...v2Projection,
334 thread: {
335 ...v2Projection.thread,
336 creationSource: "provider" as const,
337 lineage: {
338 parentThreadId: ThreadId.make("parent"),
339 relationshipToParent: "subagent" as const,
340 rootThreadId: ThreadId.make("parent"),
341 },
342 },
343 };
344​
345 it("times a provider-native subagent from its runless root turn while it works", () => {
346 const projection = { ...nativeChild, nodes: [rootTurn("running", later)] };
347 expect(deriveRunlessWorkStartedAt(projection)).toBe("2026-07-28T10:05:00.000Z");
348 expect(deriveThreadRuntime(projection)).toBeNull();
349 });
350​
351 it.each(["completed", "cancelled", "failed", "interrupted", "idle"] as const)(
352 "is idle once the subagent is %s",
353 (status) => {
354 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [rootTurn(status)] })).toBe(null);
355 },
356 );
357​
358 it("ignores root turns that belong to a run, and threads the provider does not run", () => {
359 const owned = { ...rootTurn("running"), runId: RunId.make("run-1") };
360 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [owned] })).toBeNull();
361 expect(
362 deriveRunlessWorkStartedAt({ ...v2Projection, nodes: [rootTurn("running")] }),
363 ).toBeNull();
364 });
365});
366​
367describe("deriveProviderSubagentStatus", () => {
368 const root = {
369 id: NodeId.make("child-root"),
370 threadId: v2Projection.thread.id,
371 runId: null,
372 parentNodeId: null,
373 rootNodeId: NodeId.make("child-root"),
374 kind: "root_turn" as const,
375 status: "completed" as const,
376 countsForRun: false,
377 providerThreadId: null,
378 providerTurnId: null,
379 nativeItemRef: null,
380 runtimeRequestId: null,
381 checkpointScopeId: null,
382 startedAt: now,
383 completedAt: now,
384 };
385 const child = (creationSource: "provider" | "mcp") => ({
386 ...v2Projection,
387 thread: {
388 ...v2Projection.thread,
389 creationSource,
390 lineage: {
391 parentThreadId: ThreadId.make("parent"),
392 relationshipToParent: "subagent" as const,
393 rootThreadId: ThreadId.make("parent"),
394 },
395 },
396 nodes: [root],
397 });
398​
399 it("reports the provider's own subagent from its runless root turn", () => {
400 expect(deriveProviderSubagentStatus(child("provider"))).toEqual({
401 status: "completed",
402 startedAt: "2026-07-28T10:00:00.000Z",
403 completedAt: "2026-07-28T10:00:00.000Z",
404 });
405 });
406​
407 it("says how long the subagent has worked, or took", () => {
408 const startedAt = "2026-07-28T10:00:00.000Z";
409 const at = (iso: string) => Date.parse(iso);
410 expect(
411 formatProviderSubagentStatus(
412 { status: "running", startedAt, completedAt: null },
413 at("2026-07-28T10:01:05.400Z"),
414 ),
415 ).toBe("Working 1m 5s");
416 expect(
417 formatProviderSubagentStatus(
418 { status: "completed", startedAt, completedAt: "2026-07-28T10:00:34.000Z" },
419 at("2026-07-28T11:00:00.000Z"),
420 ),
421 ).toBe("Completed in 34s");
422 expect(
423 formatProviderSubagentStatus(
424 { status: "cancelled", startedAt, completedAt: "2026-07-28T10:00:34.000Z" },
425 0,
426 ),
427 ).toBe("Cancelled");
428 expect(formatProviderSubagentStatus(null, 0)).toBe("Starting");
429 });
430​
431 it("leaves T3 delegated tasks and ordinary threads alone", () => {
432 expect(deriveProviderSubagentStatus(child("mcp"))).toBeNull();
433 expect(deriveProviderSubagentStatus({ ...v2Projection, nodes: [root] })).toBeNull();
434 });
435});
436​
437describe("formatModelSelectionEffort", () => {
438 const instanceId = ProviderInstanceId.make("claudeAgent");
439 const selection = (options?: ReadonlyArray<{ id: string; value: string }>) => ({
440 instanceId,
441 model: "claude-sonnet-5",
442 ...(options === undefined ? {} : { options }),
443 });
444 const catalog = (descriptor: { currentValue?: string }) => [
445 {
446 slug: "claude-sonnet-5",
447 name: "Claude Sonnet 5",
448 isCustom: false,
449 capabilities: {
450 optionDescriptors: [
451 {
452 id: "effort",
453 label: "Reasoning",
454 type: "select" as const,
455 options: [
456 { id: "medium", label: "Medium" },
457 { id: "high", label: "High", isDefault: true },
458 { id: "xhigh", label: "Extra High" },
459 ],
460 ...descriptor,
461 },
462 ],
463 },
464 },
465 ];
466​
467 it("shows the model's default effort when the user never picked one", () => {
468 expect(formatModelSelectionEffort(selection(), catalog({}))).toBe("High");
469 });
470​
471 it("names a stored effort the way the catalog does", () => {
472 expect(
473 formatModelSelectionEffort(selection([{ id: "effort", value: "xhigh" }]), catalog({})),
474 ).toBe("Extra High");
475 });
476​
477 it("uses the descriptor's current value over the default", () => {
478 expect(formatModelSelectionEffort(selection(), catalog({ currentValue: "medium" }))).toBe(
479 "Medium",
480 );
481 });
482​
483 it("shows nothing for a model the catalog does not describe", () => {
484 expect(formatModelSelectionEffort(selection([{ id: "effort", value: "high" }]))).toBeNull();
485 expect(
486 formatModelSelectionEffort(
487 { ...selection(), model: "claude-haiku-4-5" },
488 catalog({ currentValue: "medium" }),
489 ),
490 ).toBeNull();
491 });
492});
493​
494describe("threadRuntimeCanArchive", () => {
495 const runtime = (
496 status: ThreadRuntimeSummary["status"],
497 activeRunId: ThreadRuntimeSummary["activeRunId"],
498 ): ThreadRuntimeSummary => ({
499 status,
500 activeRunId,
501 providerInstanceId: v2Projection.thread.providerInstanceId,
502 providerName: null,
503 lastError: null,
504 updatedAt: DateTime.formatIso(now),
505 });
506​
507 it.each(["preparing", "starting", "running"] as const)(
508 "blocks archive while a provider is %s",
509 (status) => {
510 expect(threadRuntimeCanArchive(runtime(status, RunId.make(`run-${status}`)))).toBe(false);
511 },
512 );
513​
514 it("only blocks a queued runtime when a provider run remains attached", () => {
515 expect(threadRuntimeCanArchive(runtime("queued", RunId.make("run-queued")))).toBe(false);
516 expect(threadRuntimeCanArchive(runtime("queued", null))).toBe(true);
517 });
518​
519 it("allows waiting and idle threads", () => {
520 expect(threadRuntimeCanArchive(runtime("waiting", RunId.make("run-finished")))).toBe(true);
521 expect(threadRuntimeCanArchive(runtime("idle", null))).toBe(true);
522 });
523});
524​
525describe("presentPendingBackgroundWork", () => {
526 it.each(["Subagent:", "Subagent: "])(
527 "falls back to the subagent noun when %s has no display name",
528 (description) => {
529 const presentation = presentPendingBackgroundWork([
530 { taskId: "unnamed", kind: "subagent", description },
531 ]);
532​
533 expect(presentation?.title).toBe("Waiting on a subagent");
534 expect(presentation?.items[0]?.label).toBe("subagent");
535 },
536 );
537​
538 it.each([
539 "/root/luna_window_properties",
540 "Subagent: /root/luna_window_properties",
541 "/root/parent/luna_window_properties",
542 ])("uses the subagent display name for %s", (description) => {
543 const childThreadId = ThreadId.make("thread:luna");
544 const presentation = presentPendingBackgroundWork([
545 { taskId: "luna", kind: "subagent", description, childThreadId },
546 ]);
547​
548 expect(presentation).toEqual({
549 title: "Waiting on subagent Luna Window Properties",
550 items: [{ taskId: "luna", kind: "subagent", label: "Luna Window Properties", childThreadId }],
551 waiting: true,
552 });
553 });
554​
555 it("formats subagent names in a mixed roster and preserves command descriptions", () => {
556 const presentation = presentPendingBackgroundWork([
557 { taskId: "cmd", kind: "command", description: "/root/run_tests" },
558 { taskId: "luna", kind: "subagent", description: "/root/luna_window_properties" },
559 { taskId: "review", kind: "subagent", description: "Review src/math.ts" },
560 ]);
561​
562 expect(presentation?.title).toBe("Waiting on 2 subagents and 1 command");
563 expect(presentation?.items.map((item) => item.label)).toEqual([
564 "Luna Window Properties",
565 "Review src/math.ts",
566 "/root/run_tests",
567 ]);
568 });
569​
570 it("names a single piece of work by kind", () => {
571 expect(
572 presentPendingBackgroundWork([
573 { taskId: "a", kind: "subagent", description: "Review src/math.ts" },
574 ])?.title,
575 ).toBe("Waiting on subagent Review src/math.ts");
576 expect(presentPendingBackgroundWork([{ taskId: "a", kind: "monitor" }])?.title).toBe(
577 "Waiting on a monitor",
578 );
579 expect(presentPendingBackgroundWork([])).toBeNull();
580 });
581​
582 it("says only commands are running, not waited on", () => {
583 expect(
584 presentPendingBackgroundWork([
585 { taskId: "dev", kind: "command", description: "Start the shared dev server" },
586 ]),
587 ).toMatchObject({ title: "Running: Start the shared dev server", waiting: false });
588 expect(presentPendingBackgroundWork([{ taskId: "a", kind: "command" }])).toMatchObject({
589 title: "Running a command",
590 waiting: false,
591 });
592 expect(
593 presentPendingBackgroundWork([
594 { taskId: "a", kind: "command", description: "vp run dev" },
595 { taskId: "b", kind: "command", description: "tailscale serve" },
596 ]),
597 ).toMatchObject({ title: "Running 2 commands", waiting: false });
598 expect(
599 presentPendingBackgroundWork([
600 { taskId: "a", kind: "command", description: "vp run dev" },
601 { taskId: "b", kind: "monitor", description: "Watch PR checks" },
602 ]),
603 ).toMatchObject({ title: "Waiting on 1 command and 1 monitor", waiting: true });
604 });
605​
606 it("groups work by kind, subagents first, and keeps each name", () => {
607 const presentation = presentPendingBackgroundWork([
608 { taskId: "cmd", kind: "command", description: "npm test" },
609 {
610 taskId: "b",
611 kind: "subagent",
612 description: "Write tests",
613 childThreadId: ThreadId.make("thread:b"),
614 },
615 { taskId: "a", kind: "subagent", description: "Review src/math.ts" },
616 ]);
617 expect(presentation?.title).toBe("Waiting on 2 subagents and 1 command");
618 expect(presentation?.items.map((item) => [item.kind, item.label, item.childThreadId])).toEqual([
619 ["subagent", "Write tests", "thread:b"],
620 ["subagent", "Review src/math.ts", undefined],
621 ["command", "npm test", undefined],
622 ]);
623 });
624​
625 it("names generic work, including rosters from servers that predate kinds", () => {
626 expect(
627 presentPendingBackgroundWork([
628 { taskId: "bash", kind: "command", description: "Background sleep" },
629 { taskId: "watch", kind: "monitor" },
630 { taskId: "other", kind: "background_task" },
631 ])?.title,
632 ).toBe("Waiting on 1 command, 1 monitor and 1 background task");
633 expect(presentPendingBackgroundWork([{ taskId: "old", kind: "background_task" }])?.title).toBe(
634 "Waiting on a background task",
635 );
636 });
637});
638​
639describe("provider-reported model selection", () => {
640 const selected = v2Projection.thread.modelSelection;
641 const reported = { ...selected, options: [{ id: "reasoningEffort", value: "default" }] };
642 const providerThread = {
643 id: ProviderThreadId.make("active"),
644 driver: ProviderDriverKind.make("codex"),
645 providerInstanceId: selected.instanceId,
646 providerSessionId: ProviderSessionId.make("session"),
647 appThreadId: v2Projection.thread.id,
648 ownerNodeId: null,
649 nativeThreadRef: null,
650 nativeConversationHeadRef: null,
651 status: "idle" as const,
652 firstRunOrdinal: null,
653 lastRunOrdinal: null,
654 handoffIds: [],
655 forkedFrom: null,
656 createdAt: now,
657 updatedAt: now,
658 nativeMetadata: { modelSelection: reported },
659 };
660 const projection = {
661 ...v2Projection,
662 thread: { ...v2Projection.thread, activeProviderThreadId: providerThread.id },
663 providerThreads: [providerThread],
664 };
665​
666 it("reads only the active provider thread's reported selection", () => {
667 expect(deriveReportedModelSelection(projection)).toBe(reported);
668 expect(
669 deriveReportedModelSelection({
670 ...projection,
671 thread: { ...projection.thread, activeProviderThreadId: null },
672 }),
673 ).toBeNull();
674 expect(
675 deriveReportedModelSelection({
676 ...projection,
677 providerThreads: [
678 { ...providerThread, providerInstanceId: ProviderInstanceId.make("other") },
679 ],
680 }),
681 ).toBeNull();
682 });
683​
684 it("shows the reported default in a subagent's effort label", () => {
685 const models = [
686 {
687 slug: selected.model,
688 name: selected.model,
689 isCustom: false,
690 capabilities: {
691 optionDescriptors: [
692 {
693 id: "variant",
694 label: "Reasoning",
695 type: "select" as const,
696 options: [{ id: "high", label: "High" }],
697 },
698 ],
699 },
700 },
701 ];
702 const variantReport = { ...selected, options: [{ id: "variant", value: "default" }] };
703 expect(formatModelSelectionEffort(selected, models, variantReport)).toBe("Default");
704 expect(formatModelSelectionEffort(selected, models)).toBe("Unknown");
705 });
706});
707​
708describe("presentProviderGoal", () => {
709 it("summarizes Codex accounting and offers resume once the goal stops short", () => {
710 expect(
711 presentProviderGoal(
712 {
713 objective: "Ship the feature",
714 status: "paused",
715 tokensUsed: 12_400,
716 tokenBudget: 50_000,
717 timeUsedSeconds: 245,
718 },
719 false,
720 ),
721 ).toEqual({
722 title: "Goal paused",
723 objective: "Ship the feature",
724 usage: "12k / 50k tokens · 4m 5s",
725 canResume: true,
726 });
727 });
728​
729 it("counts Claude evaluator checks and never offers resume", () => {
730 expect(
731 presentProviderGoal({ objective: "All tests pass", status: "active", checks: 1 }, true),
732 ).toEqual({
733 title: "Pursuing goal",
734 objective: "All tests pass",
735 usage: "1 check",
736 canResume: false,
737 });
738 expect(
739 presentProviderGoal({ objective: "All tests pass", status: "complete", checks: 0 }, false)
740 .usage,
741 ).toBeNull();
742 expect(
743 presentProviderGoal({ objective: "All tests pass", status: "active" }, false).title,
744 ).toBe("Goal set");
745 });
746});