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

threadExecution.test.ts

963 lines32.8 KB

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