@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 831 lines 28.2 KB
Raw
1 import {
2 TurnItemId,
3 NodeId,
4 MessageId,
5 ProviderInstanceId,
6 ProviderThreadId,
7 ProviderSessionId,
8 ProviderDriverKind,
9 ProviderTurnId,
10 RunAttemptId,
11 RunId,
12 RuntimeRequestId,
13 ThreadId,
14 type OrchestrationV2ExecutionNode,
15 type OrchestrationV2RunStatus,
16 type OrchestrationV2RuntimeRequest,
17 } from "@t3tools/contracts";
18 import * as DateTime from "effect/DateTime";
19 import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model";
20 import { usageLimitBlockedRun } from "@t3tools/shared/orchestrationV2ThreadError";
21 import { describe, expect, it } from "vite-plus/test";
22
23 import { v2Projection } from "./orchestrationV2TestFixtures.ts";
24 import {
25 canResumeThread,
26 deriveReportedModelSelection,
27 deriveLatestThreadRun,
28 deriveProviderSubagentStatus,
29 deriveProviderExtensionStatuses,
30 deriveResumableRunId,
31 deriveRunlessWorkStartedAt,
32 deriveThreadActivityRun,
33 deriveThreadRuntime,
34 formatModelSelectionEffort,
35 isBackgroundWorkStopPending,
36 presentPendingBackgroundWork,
37 presentProviderGoal,
38 presentRunStop,
39 threadRuntimeHasInterruptibleRun,
40 } from "./threadExecution.ts";
41
42 const now = DateTime.makeUnsafe("2026-07-28T10:00:00.000Z");
43
44 function request(
45 id: string,
46 status: OrchestrationV2RuntimeRequest["status"],
47 ): OrchestrationV2RuntimeRequest {
48 return {
49 id: RuntimeRequestId.make(id),
50 nodeId: NodeId.make(`node-${id}`),
51 providerTurnId: null,
52 nativeRequestRef: null,
53 kind: "command",
54 status,
55 responseCapability: { type: "not_resumable", reason: "Session ended." },
56 createdAt: now,
57 resolvedAt: status === "pending" ? null : now,
58 };
59 }
60
61 function run(id: string, ordinal: number, status: OrchestrationV2RunStatus) {
62 return {
63 id: RunId.make(id),
64 threadId: v2Projection.thread.id,
65 ordinal,
66 providerInstanceId: v2Projection.thread.providerInstanceId,
67 modelSelection: v2Projection.thread.modelSelection,
68 providerThreadId: null,
69 userMessageId: MessageId.make(`message-${id}`),
70 rootNodeId: null,
71 activeAttemptId: null,
72 status,
73 requestedAt: now,
74 startedAt: status === "queued" ? null : now,
75 completedAt: null,
76 checkpointId: null,
77 contextHandoffId: null,
78 };
79 }
80
81 describe("thread execution presentation", () => {
82 it("shows extension statuses only from the selected provider's current live session", () => {
83 const instanceId = v2Projection.thread.modelSelection.instanceId;
84 const providerThreadId = ProviderThreadId.make("native-status-thread");
85 const sessionId = ProviderSessionId.make("native-status-session");
86 const statuses = [{ key: "watch", text: "Watching" }];
87 const projection = {
88 thread: { ...v2Projection.thread, activeProviderThreadId: providerThreadId },
89 providerThreads: [
90 { id: providerThreadId, providerSessionId: sessionId, providerInstanceId: instanceId },
91 ],
92 providerSessions: [
93 {
94 id: sessionId,
95 providerInstanceId: instanceId,
96 status: "ready" as const,
97 extensionStatuses: statuses,
98 },
99 ],
100 };
101 expect(deriveProviderExtensionStatuses(projection)).toEqual(statuses);
102 expect(
103 deriveProviderExtensionStatuses({
104 ...projection,
105 providerSessions: [
106 ...projection.providerSessions,
107 {
108 ...projection.providerSessions[0]!,
109 id: ProviderSessionId.make("unrelated"),
110 extensionStatuses: [{ key: "wrong", text: "Wrong session" }],
111 },
112 ],
113 }),
114 ).toEqual(statuses);
115 expect(
116 deriveProviderExtensionStatuses({
117 ...projection,
118 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" }],
119 }),
120 ).toEqual([]);
121 expect(
122 deriveProviderExtensionStatuses({
123 ...projection,
124 providerSessions: [{ ...projection.providerSessions[0]!, status: "error" }],
125 }),
126 ).toEqual(statuses);
127 expect(
128 deriveProviderExtensionStatuses({
129 ...projection,
130 providerSessions: [
131 { ...projection.providerSessions[0]!, status: "error", extensionStatuses: [] },
132 ],
133 }),
134 ).toEqual([]);
135 expect(
136 deriveProviderExtensionStatuses({
137 ...projection,
138 providerSessions: [{ ...projection.providerSessions[0]!, extensionStatuses: undefined }],
139 }),
140 ).toEqual([]);
141 expect(
142 deriveProviderExtensionStatuses({
143 ...projection,
144 thread: {
145 ...projection.thread,
146 modelSelection: { instanceId: ProviderInstanceId.make("other"), model: "default" },
147 },
148 }),
149 ).toEqual([]);
150 expect(deriveProviderExtensionStatuses(null)).toEqual([]);
151 });
152
153 it("derives the current root failure without inheriting errors from children or previous runs", () => {
154 const failed = { ...run("limited", 1, "failed"), rootNodeId: NodeId.make("root") };
155 const item = {
156 id: TurnItemId.make("limit-error"),
157 threadId: v2Projection.thread.id,
158 runId: failed.id,
159 nodeId: failed.rootNodeId,
160 providerThreadId: null,
161 providerTurnId: null,
162 nativeItemRef: null,
163 parentItemId: null,
164 ordinal: 1,
165 type: "error" as const,
166 status: "failed" as const,
167 title: "Usage limit reached",
168 startedAt: now,
169 completedAt: now,
170 updatedAt: now,
171 failure: {
172 class: "usage_limit" as const,
173 message: "Plan limit reached",
174 code: "usageLimitExceeded",
175 retryable: null,
176 },
177 };
178 const projection = { ...v2Projection, runs: [failed], turnItems: [item] };
179 expect(deriveThreadRuntime(projection)).toMatchObject({
180 lastError: "Plan limit reached",
181 lastErrorClass: "usage_limit",
182 lastErrorSource: "limit-error@2026-07-28T10:00:00.000Z",
183 });
184 // A retried run fails again through the same item, so only its failure time tells it apart.
185 const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z");
186 const source = (input: Partial<Parameters<typeof deriveThreadRuntime>[0]>) =>
187 deriveThreadRuntime({ ...projection, ...input })?.lastErrorSource;
188 expect(source({ turnItems: [{ ...item, completedAt: later, updatedAt: later }] })).toBe(
189 "limit-error@2026-07-28T10:05:00.000Z",
190 );
191 expect(source({ turnItems: [{ ...item, updatedAt: later }] })).toBe(
192 "limit-error@2026-07-28T10:00:00.000Z",
193 );
194 const session = (lastError: string) => ({
195 id: ProviderSessionId.make("failed-session"),
196 driver: ProviderDriverKind.make("pi"),
197 providerInstanceId: v2Projection.thread.providerInstanceId,
198 status: "error" as const,
199 cwd: "/repo",
200 model: null,
201 capabilities: {} as never,
202 createdAt: now,
203 updatedAt: later,
204 lastError,
205 });
206 // A session that repeats the failure keeps its source, whatever the session's own updates.
207 expect(source({ providerSessions: [session("Plan limit reached")] })).toBe(
208 "limit-error@2026-07-28T10:00:00.000Z",
209 );
210 // Otherwise a session error belongs to the latest ended run, kept while a newer run starts.
211 const ended = { ...failed, completedAt: now };
212 const starting = [ended, run("next", 2, "starting")];
213 expect(source({ runs: [ended], providerSessions: [session("Session failed")] })).toBe(
214 "limited@2026-07-28T10:00:00.000Z",
215 );
216 expect(source({ runs: starting, providerSessions: [session("Session failed")] })).toBe(
217 "limited@2026-07-28T10:00:00.000Z",
218 );
219 expect(source({ runs: starting, providerSessions: [session("Plan limit reached")] })).toBe(
220 "limit-error@2026-07-28T10:00:00.000Z",
221 );
222 expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(failed.id);
223 expect(
224 deriveThreadRuntime({
225 ...projection,
226 turnItems: [{ ...item, nodeId: NodeId.make("child") }],
227 }),
228 ).toMatchObject({ lastError: null, lastErrorClass: null });
229 expect(
230 deriveThreadRuntime({
231 ...projection,
232 runs: [{ ...failed, rootNodeId: NodeId.make("new-root") }],
233 }),
234 ).toMatchObject({ lastError: null, lastErrorClass: null });
235 expect(
236 deriveThreadRuntime({ ...projection, runs: [failed, run("new", 2, "running")] }),
237 ).toMatchObject({ status: "running", lastError: null, lastErrorClass: null });
238 });
239
240 it.each([
241 {
242 name: "a provider without native resume",
243 nativeResume: false,
244 delivered: true,
245 resumes: false,
246 },
247 { name: "an undelivered message", nativeResume: false, delivered: false, resumes: true },
248 { name: "a provider with native resume", nativeResume: true, delivered: true, resumes: true },
249 {
250 name: "a session from an older server",
251 nativeResume: undefined,
252 delivered: true,
253 resumes: true,
254 },
255 ])("offers to resume an interrupted run on $name", ({ nativeResume, delivered, resumes }) => {
256 const providerThreadId = ProviderThreadId.make("stopped-thread");
257 const sessionId = ProviderSessionId.make("stopped-session");
258 const attemptId = RunAttemptId.make("stopped-attempt");
259 const stopped = { ...run("stopped", 1, "interrupted"), providerThreadId };
260 const projection = {
261 ...v2Projection,
262 runs: [stopped],
263 attempts: [{ id: attemptId, runId: stopped.id, attemptOrdinal: 1, reason: "initial" }],
264 providerTurns: delivered ? [{ runAttemptId: attemptId }] : [],
265 providerThreads: [{ id: providerThreadId, providerSessionId: sessionId }],
266 providerSessions: [
267 { id: sessionId, capabilities: { turns: { supportsNativeResume: nativeResume } } },
268 ],
269 } as unknown as typeof v2Projection;
270 expect(deriveResumableRunId(projection, null)).toBe(resumes ? stopped.id : null);
271 });
272
273 // regression: #15029 working timers no longer reset on every background wake
274 it("counts a wake run's activity from the start of the work it continues", () => {
275 const workStartedAt = DateTime.makeUnsafe("2026-07-28T09:20:00.000Z");
276 const wake = { ...run("wake", 2, "running"), workStartedAt };
277 expect(
278 deriveThreadRuntime({ ...v2Projection, runs: [run("prompt", 1, "completed"), wake] })
279 ?.activityStartedAt,
280 ).toBe("2026-07-28T09:20:00.000Z");
281 expect(
282 deriveThreadRuntime({ ...v2Projection, runs: [run("prompt", 1, "running")] })
283 ?.activityStartedAt,
284 ).toBe("2026-07-28T10:00:00.000Z");
285 });
286
287 it("keeps a subscription limit visible while later messages stay queued", () => {
288 const failed = {
289 ...run("limited", 1, "failed"),
290 rootNodeId: NodeId.make("root"),
291 completedAt: now,
292 };
293 const queued = run("queued", 2, "queued");
294 const item = {
295 id: TurnItemId.make("limit-error"),
296 threadId: v2Projection.thread.id,
297 runId: failed.id,
298 nodeId: failed.rootNodeId,
299 providerThreadId: null,
300 providerTurnId: null,
301 nativeItemRef: null,
302 parentItemId: null,
303 ordinal: 1,
304 type: "error" as const,
305 status: "failed" as const,
306 title: "Usage limit reached",
307 startedAt: now,
308 completedAt: now,
309 updatedAt: now,
310 failure: {
311 class: "usage_limit" as const,
312 message: "Plan limit reached",
313 code: "usageLimitExceeded",
314 retryable: null,
315 },
316 };
317 const projection = { ...v2Projection, runs: [failed, queued], turnItems: [item] };
318
319 expect(deriveLatestThreadRun(projection)?.runId).toBe(failed.id);
320 expect(deriveThreadActivityRun(projection)?.runId).toBe(failed.id);
321 expect(deriveThreadRuntime(projection)).toMatchObject({
322 status: "failed",
323 lastError: "Plan limit reached",
324 lastErrorClass: "usage_limit",
325 });
326 expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(failed.id);
327 const cancelledQueued = {
328 ...run("cancelled-queued", 3, "cancelled"),
329 startedAt: null,
330 completedAt: now,
331 };
332 expect(
333 usageLimitBlockedRun([failed, queued, cancelledQueued], projection.turnItems, null)?.id,
334 ).toBe(failed.id);
335 expect(
336 deriveThreadRuntime({ ...projection, runs: [failed, queued, cancelledQueued] }),
337 ).toMatchObject({ status: "failed", lastErrorClass: "usage_limit" });
338 const providerError = {
339 ...projection,
340 turnItems: [{ ...item, failure: { ...item.failure, class: "provider_error" as const } }],
341 };
342 expect(deriveThreadRuntime(providerError)).toMatchObject({
343 status: "queued",
344 lastErrorClass: null,
345 });
346 expect(deriveResumableRunId(providerError, deriveThreadRuntime(providerError))).toBeNull();
347 });
348
349 it("keeps live activity attached to an executing run when a newer run is queued", () => {
350 const runningRun = run("run-running", 1, "running");
351 const queuedRun = run("run-queued", 2, "queued");
352 const projection = { ...v2Projection, runs: [queuedRun, runningRun], updatedAt: now };
353
354 expect(deriveLatestThreadRun(projection)?.runId).toBe(queuedRun.id);
355 expect(deriveThreadActivityRun(projection)).toMatchObject({
356 runId: runningRun.id,
357 status: "running",
358 });
359
360 const runtime = deriveThreadRuntime(projection);
361 expect(runtime).toMatchObject({
362 status: "running",
363 activeRunId: runningRun.id,
364 });
365 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
366 });
367
368 it("marks an open run whose provider turn already ended", () => {
369 const attemptId = RunAttemptId.make("attempt-open");
370 const openRun = { ...run("run-open", 1, "running"), activeAttemptId: attemptId };
371 const providerTurn = (status: "running" | "failed") => ({
372 id: ProviderTurnId.make("provider-turn-open"),
373 providerThreadId: ProviderThreadId.make("provider-thread-open"),
374 nodeId: NodeId.make("node-open"),
375 runAttemptId: attemptId,
376 nativeTurnRef: null,
377 ordinal: 1,
378 status,
379 startedAt: now,
380 completedAt: status === "running" ? null : now,
381 });
382 const projection = (status: "running" | "failed") => ({
383 ...v2Projection,
384 runs: [openRun],
385 providerTurns: [providerTurn(status)],
386 updatedAt: now,
387 });
388
389 expect(deriveThreadActivityRun(projection("running"))?.turnEnded).toBeUndefined();
390 expect(deriveThreadActivityRun(projection("failed"))).toMatchObject({
391 status: "running",
392 turnEnded: true,
393 });
394 });
395
396 // The server marks a run running before the provider opens, which can take minutes.
397 it("labels an open run whose provider has not started a turn", () => {
398 const attemptId = RunAttemptId.make("attempt-starting");
399 const openRun = { ...run("run-starting", 1, "running"), activeAttemptId: attemptId };
400 const session = {
401 id: ProviderSessionId.make("session-starting"),
402 driver: ProviderDriverKind.make("claudeAgent"),
403 providerInstanceId: openRun.providerInstanceId,
404 status: "starting" as const,
405 cwd: "/repo",
406 model: null,
407 // The label reads only the driver.
408 capabilities: {} as never,
409 createdAt: now,
410 updatedAt: now,
411 lastError: null,
412 };
413 const starting = { ...v2Projection, runs: [openRun], providerSessions: [session] };
414
415 expect(deriveThreadActivityRun(starting)?.providerStartingLabel).toBe("Starting Claude");
416 expect(
417 deriveThreadActivityRun({ ...starting, providerSessions: [] })?.providerStartingLabel,
418 ).toBe("Starting");
419 expect(
420 deriveThreadActivityRun({
421 ...starting,
422 providerTurns: [
423 {
424 id: ProviderTurnId.make("provider-turn-starting"),
425 providerThreadId: ProviderThreadId.make("provider-thread-starting"),
426 nodeId: NodeId.make("node-starting"),
427 runAttemptId: attemptId,
428 nativeTurnRef: null,
429 ordinal: 1,
430 status: "running",
431 startedAt: now,
432 completedAt: null,
433 },
434 ],
435 })?.providerStartingLabel,
436 ).toBeUndefined();
437 });
438
439 it("presents a held queue as the stopped run instead of queued work", () => {
440 const interrupted = { ...run("run-interrupted", 1, "interrupted"), completedAt: now };
441 const held = { ...run("run-held", 2, "queued"), queueHeld: true };
442 const projection = { ...v2Projection, runs: [interrupted, held], updatedAt: now };
443
444 expect(deriveLatestThreadRun(projection)?.runId).toBe(interrupted.id);
445 expect(deriveThreadActivityRun(projection)?.runId).toBe(interrupted.id);
446 expect(deriveThreadRuntime(projection)).toMatchObject({
447 status: "interrupted",
448 activeRunId: null,
449 });
450 expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(interrupted.id);
451
452 const resumed = { ...projection, runs: [interrupted, { ...held, queueHeld: false }] };
453 expect(deriveThreadRuntime(resumed)).toMatchObject({ status: "queued" });
454
455 const onlyHeld = {
456 ...projection,
457 runs: [held],
458 thread: { ...projection.thread, activeProviderThreadId: null },
459 };
460 expect(deriveLatestThreadRun(onlyHeld)).toBeNull();
461 expect(deriveThreadRuntime(onlyHeld)).toBeNull();
462 });
463
464 it.each([
465 { name: "no requests", requests: [], runId: "run-stopped", held: false, expected: true },
466 {
467 name: "a pending request",
468 requests: [request("approval", "pending")],
469 runId: "run-stopped",
470 held: false,
471 expected: false,
472 },
473 {
474 name: "only a resolved request",
475 requests: [request("approval", "resolved")],
476 runId: "run-stopped",
477 held: false,
478 expected: true,
479 },
480 {
481 name: "a held queue behind a blocked continuation",
482 requests: [request("approval", "pending")],
483 runId: "run-stopped",
484 held: true,
485 expected: false,
486 },
487 {
488 name: "a held queue with no run to continue",
489 requests: [request("approval", "pending")],
490 runId: null,
491 held: true,
492 expected: true,
493 },
494 { name: "nothing to resume", requests: [], runId: null, held: false, expected: false },
495 ])("decides whether Resume can start with $name", ({ requests, runId, held, expected }) => {
496 expect(
497 canResumeThread(
498 { runtimeRequests: requests },
499 runId === null ? null : RunId.make(runId),
500 held,
501 ),
502 ).toBe(expected);
503 });
504
505 it("does not expose a queued-only run as interruptible", () => {
506 const queuedRun = run("run-queued", 1, "queued");
507 const projection = { ...v2Projection, runs: [queuedRun], updatedAt: now };
508
509 expect(deriveThreadActivityRun(projection)).toMatchObject({
510 runId: queuedRun.id,
511 status: "queued",
512 });
513
514 const runtime = deriveThreadRuntime(projection);
515 expect(runtime).toMatchObject({
516 status: "queued",
517 activeRunId: null,
518 });
519 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
520 });
521 });
522
523 describe("presentRunStop", () => {
524 const signal = (type: "run_interrupt_request" | "run_interrupt_result", runId: RunId) => ({
525 id: TurnItemId.make(`${type}:${runId}`),
526 threadId: v2Projection.thread.id,
527 runId,
528 nodeId: null,
529 providerThreadId: null,
530 providerTurnId: null,
531 nativeItemRef: null,
532 parentItemId: null,
533 ordinal: 1,
534 status: type === "run_interrupt_result" ? ("interrupted" as const) : ("completed" as const),
535 title: "Interrupt",
536 startedAt: now,
537 completedAt: now,
538 updatedAt: now,
539 type,
540 message: "Stopped by user",
541 });
542 const running = run("run-stopping", 1, "running");
543 const request = signal("run_interrupt_request", running.id);
544
545 it.each([
546 { name: "no Stop", runs: [running], turnItems: [], state: null },
547 {
548 name: "a Stop the agent is winding down",
549 runs: [running],
550 turnItems: [request],
551 state: "stopping",
552 },
553 {
554 name: "a Stop the provider never confirmed",
555 runs: [running],
556 turnItems: [{ ...request, unresponsiveAt: now }],
557 state: "unresponsive",
558 },
559 {
560 name: "a Stop that ended the run",
561 runs: [running],
562 turnItems: [request, signal("run_interrupt_result", running.id)],
563 state: null,
564 },
565 {
566 name: "a settled run's background work still stopping",
567 runs: [{ ...running, status: "completed" as const, completedAt: now }],
568 turnItems: [request],
569 state: null,
570 },
571 {
572 name: "a settled run whose background work ignored Stop",
573 runs: [{ ...running, status: "completed" as const, completedAt: now }],
574 turnItems: [{ ...request, unresponsiveAt: now }],
575 state: "unresponsive",
576 },
577 {
578 name: "a settled run whose background work ignored Stop, with a queued follow-up",
579 runs: [
580 { ...running, status: "completed" as const, completedAt: now },
581 run("run-queued", 2, "queued"),
582 ],
583 turnItems: [{ ...request, unresponsiveAt: now }],
584 state: "unresponsive",
585 },
586 ])("presents $name", ({ runs, turnItems, state }) => {
587 expect(presentRunStop({ runs, turnItems })?.state ?? null).toBe(state);
588 });
589 });
590
591 describe("deriveRunlessWorkStartedAt", () => {
592 const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z");
593 const rootTurn = (
594 status: OrchestrationV2ExecutionNode["status"],
595 startedAt = now,
596 ): OrchestrationV2ExecutionNode => ({
597 id: NodeId.make("child-root"),
598 threadId: v2Projection.thread.id,
599 runId: null,
600 parentNodeId: null,
601 rootNodeId: NodeId.make("child-root"),
602 kind: "root_turn",
603 status,
604 countsForRun: false,
605 providerThreadId: null,
606 providerTurnId: null,
607 nativeItemRef: null,
608 runtimeRequestId: null,
609 checkpointScopeId: null,
610 startedAt,
611 completedAt: null,
612 });
613
614 const nativeChild = {
615 ...v2Projection,
616 thread: {
617 ...v2Projection.thread,
618 creationSource: "provider" as const,
619 lineage: {
620 parentThreadId: ThreadId.make("parent"),
621 relationshipToParent: "subagent" as const,
622 rootThreadId: ThreadId.make("parent"),
623 },
624 },
625 };
626
627 it("times a provider-native subagent from its runless root turn while it works", () => {
628 const projection = {
629 ...nativeChild,
630 thread: {
631 ...nativeChild.thread,
632 activeProviderThreadId: ProviderThreadId.make("native-child"),
633 },
634 nodes: [rootTurn("running", later)],
635 };
636 expect(deriveRunlessWorkStartedAt(projection)).toBe("2026-07-28T10:05:00.000Z");
637 expect(deriveThreadRuntime(projection)).toBeNull();
638 });
639
640 it("ignores root turns that belong to a run, and threads the provider does not run", () => {
641 const owned = { ...rootTurn("running"), runId: RunId.make("run-1") };
642 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [owned] })).toBeNull();
643 expect(
644 deriveRunlessWorkStartedAt({ ...v2Projection, nodes: [rootTurn("running")] }),
645 ).toBeNull();
646 });
647 });
648
649 describe("deriveProviderSubagentStatus", () => {
650 const root = {
651 id: NodeId.make("child-root"),
652 threadId: v2Projection.thread.id,
653 runId: null,
654 parentNodeId: null,
655 rootNodeId: NodeId.make("child-root"),
656 kind: "root_turn" as const,
657 status: "completed" as const,
658 countsForRun: false,
659 providerThreadId: null,
660 providerTurnId: null,
661 nativeItemRef: null,
662 runtimeRequestId: null,
663 checkpointScopeId: null,
664 startedAt: now,
665 completedAt: now,
666 };
667 const child = (creationSource: "provider" | "mcp") => ({
668 ...v2Projection,
669 thread: {
670 ...v2Projection.thread,
671 creationSource,
672 lineage: {
673 parentThreadId: ThreadId.make("parent"),
674 relationshipToParent: "subagent" as const,
675 rootThreadId: ThreadId.make("parent"),
676 },
677 },
678 nodes: [root],
679 });
680
681 it("leaves T3 delegated tasks and ordinary threads alone", () => {
682 expect(deriveProviderSubagentStatus(child("mcp"))).toBeNull();
683 expect(deriveProviderSubagentStatus({ ...v2Projection, nodes: [root] })).toBeNull();
684 });
685 });
686
687 describe("provider-reported model selection", () => {
688 const selected = v2Projection.thread.modelSelection;
689 const reported = { ...selected, options: [{ id: "reasoningEffort", value: "default" }] };
690 const providerThread = {
691 id: ProviderThreadId.make("active"),
692 driver: ProviderDriverKind.make("codex"),
693 providerInstanceId: selected.instanceId,
694 providerSessionId: ProviderSessionId.make("session"),
695 appThreadId: v2Projection.thread.id,
696 ownerNodeId: null,
697 nativeThreadRef: null,
698 nativeConversationHeadRef: null,
699 status: "idle" as const,
700 firstRunOrdinal: null,
701 lastRunOrdinal: null,
702 handoffIds: [],
703 forkedFrom: null,
704 createdAt: now,
705 updatedAt: now,
706 nativeMetadata: { modelSelection: reported },
707 };
708 const projection = {
709 ...v2Projection,
710 thread: { ...v2Projection.thread, activeProviderThreadId: providerThread.id },
711 providerThreads: [providerThread],
712 };
713
714 it("reads only the active provider thread's reported selection", () => {
715 expect(deriveReportedModelSelection(projection)).toBe(reported);
716 expect(
717 deriveReportedModelSelection({
718 ...projection,
719 thread: { ...projection.thread, activeProviderThreadId: null },
720 }),
721 ).toBeNull();
722 expect(
723 deriveReportedModelSelection({
724 ...projection,
725 providerThreads: [
726 { ...providerThread, providerInstanceId: ProviderInstanceId.make("other") },
727 ],
728 }),
729 ).toBeNull();
730 });
731 });
732
733 describe("formatModelSelectionEffort", () => {
734 it("labels an old Ultracode effort by the effort it runs at", () => {
735 const models = [
736 {
737 slug: "claude-opus-5-5",
738 name: "Claude Opus 5.5",
739 isCustom: false,
740 capabilities: createModelCapabilities({
741 optionDescriptors: [
742 {
743 id: "effort",
744 label: "Reasoning",
745 type: "select",
746 options: [
747 { id: "high", label: "High", isDefault: true },
748 { id: "xhigh", label: "Extra High" },
749 ],
750 },
751 { id: "ultracode", label: "Ultracode", type: "boolean" },
752 ],
753 }),
754 },
755 ];
756 const selection = createModelSelection(
757 ProviderInstanceId.make("claudeAgent"),
758 "claude-opus-5-5",
759 [{ id: "effort", value: "ultracode" }],
760 );
761
762 expect(formatModelSelectionEffort(selection, models)).toBe("Extra High");
763 });
764 });
765
766 describe("isBackgroundWorkStopPending", () => {
767 const tasks = [{ taskId: "dev-server" }];
768 const sent = { threadKey: "env:thread", taskIds: ["dev-server"], retryAt: null };
769 const accepted = { ...sent, retryAt: 10_000 };
770
771 it("stays pending after acceptance while a stopped task is still listed", () => {
772 expect(isBackgroundWorkStopPending(sent, "env:thread", tasks, false)).toBe(true);
773 expect(isBackgroundWorkStopPending(accepted, "env:thread", tasks, false)).toBe(true);
774 });
775
776 it("ends once the stopped tasks leave, even if new work starts", () => {
777 expect(isBackgroundWorkStopPending(accepted, "env:thread", [], false)).toBe(false);
778 expect(isBackgroundWorkStopPending(accepted, "env:thread", [{ taskId: "next" }], false)).toBe(
779 false,
780 );
781 });
782
783 it("allows retry at the deadline even if a stopped task remains", () => {
784 const request = { ...accepted, retryAt: 10_000 };
785 expect(isBackgroundWorkStopPending(request, "env:thread", tasks, false)).toBe(true);
786 expect(isBackgroundWorkStopPending(request, "env:thread", tasks, true)).toBe(false);
787 });
788
789 it("only applies to the thread that sent the Stop", () => {
790 expect(isBackgroundWorkStopPending(null, "env:thread", tasks, false)).toBe(false);
791 expect(isBackgroundWorkStopPending(sent, "env:other", tasks, false)).toBe(false);
792 });
793 });
794
795 describe("presentProviderGoal", () => {
796 it("rolls token counts that round to 1000k over to 1m", () => {
797 const usage = (tokensUsed: number) =>
798 presentProviderGoal(
799 { objective: "Ship the feature", status: "active", tokensUsed, tokenBudget: 2_000_000 },
800 true,
801 ).usage;
802 expect(usage(999_499)).toBe("999k / 2m tokens");
803 expect(usage(999_500)).toBe("1m / 2m tokens");
804 expect(usage(999_999)).toBe("1m / 2m tokens");
805 expect(usage(1_000_000)).toBe("1m / 2m tokens");
806 expect(
807 presentProviderGoal(
808 {
809 objective: "Ship the feature",
810 status: "paused",
811 tokensUsed: 999_500,
812 tokenBudget: 999_500,
813 },
814 false,
815 ).usage,
816 ).toBe("1m / 1m tokens");
817 });
818 });
819
820 describe("presentPendingBackgroundWork", () => {
821 it("names a command by its script, not the shell that wraps it", () => {
822 const presentation = presentPendingBackgroundWork([
823 {
824 taskId: "call_1",
825 kind: "command",
826 description: `/bin/zsh -lc "mv a.ts b.ts\ncat > b.ts <<'EOF'\nexport {};\nEOF"`,
827 },
828 ]);
829 expect(presentation?.items[0]?.label).toBe("mv a.ts b.ts\ncat > b.ts <<'EOF'\nexport {};\nEOF");
830 });
831 });