Open History to see the last commit
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 };
61}
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 };
81}
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(
419 deriveThreadActivityRun({ ...starting, providerSessions: [] })?.providerStartingLabel,
420 ).toBe("Starting");
421 expect(
422 deriveThreadActivityRun({
423 ...starting,
424 providerTurns: [
425 {
426 id: ProviderTurnId.make("provider-turn-starting"),
427 providerThreadId: ProviderThreadId.make("provider-thread-starting"),
428 nodeId: NodeId.make("node-starting"),
429 runAttemptId: attemptId,
430 nativeTurnRef: null,
431 ordinal: 1,
432 status: "running",
433 startedAt: now,
434 completedAt: null,
435 },
436 ],
437 })?.providerStartingLabel,
438 ).toBeUndefined();
439 });
440
441 it("presents a held queue as the stopped run instead of queued work", () => {
442 const interrupted = { ...run("run-interrupted", 1, "interrupted"), completedAt: now };
443 const held = { ...run("run-held", 2, "queued"), queueHeld: true };
444 const projection = { ...v2Projection, runs: [interrupted, held], updatedAt: now };
445
446 expect(deriveLatestThreadRun(projection)?.runId).toBe(interrupted.id);
447 expect(deriveThreadActivityRun(projection)?.runId).toBe(interrupted.id);
448 expect(deriveThreadRuntime(projection)).toMatchObject({
449 status: "interrupted",
450 activeRunId: null,
451 });
452 expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(interrupted.id);
453
454 const resumed = { ...projection, runs: [interrupted, { ...held, queueHeld: false }] };
455 expect(deriveThreadRuntime(resumed)).toMatchObject({ status: "queued" });
456
457 const onlyHeld = {
458 ...projection,
459 runs: [held],
460 thread: { ...projection.thread, activeProviderThreadId: null },
461 };
462 expect(deriveLatestThreadRun(onlyHeld)).toBeNull();
463 expect(deriveThreadRuntime(onlyHeld)).toBeNull();
464 });
465
466 it.each([
467 { name: "no requests", requests: [], runId: "run-stopped", held: false, expected: true },
468 {
469 name: "a pending request",
470 requests: [request("approval", "pending")],
471 runId: "run-stopped",
472 held: false,
473 expected: false,
474 },
475 {
476 name: "only a resolved request",
477 requests: [request("approval", "resolved")],
478 runId: "run-stopped",
479 held: false,
480 expected: true,
481 },
482 {
483 name: "a held queue behind a blocked continuation",
484 requests: [request("approval", "pending")],
485 runId: "run-stopped",
486 held: true,
487 expected: false,
488 },
489 {
490 name: "a held queue with no run to continue",
491 requests: [request("approval", "pending")],
492 runId: null,
493 held: true,
494 expected: true,
495 },
496 { name: "nothing to resume", requests: [], runId: null, held: false, expected: false },
497 ])("decides whether Resume can start with $name", ({ requests, runId, held, expected }) => {
498 expect(
499 canResumeThread(
500 { runtimeRequests: requests },
501 runId === null ? null : RunId.make(runId),
502 held,
503 ),
504 ).toBe(expected);
505 });
506
507 it("does not expose a queued-only run as interruptible", () => {
508 const queuedRun = run("run-queued", 1, "queued");
509 const projection = { ...v2Projection, runs: [queuedRun], updatedAt: now };
510
511 expect(deriveThreadActivityRun(projection)).toMatchObject({
512 runId: queuedRun.id,
513 status: "queued",
514 });
515
516 const runtime = deriveThreadRuntime(projection);
517 expect(runtime).toMatchObject({
518 status: "queued",
519 activeRunId: null,
520 });
521 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
522 });
523});
524
525describe("presentRunStop", () => {
526 const signal = (type: "run_interrupt_request" | "run_interrupt_result", runId: RunId) => ({
527 id: TurnItemId.make(`${type}:${runId}`),
528 threadId: v2Projection.thread.id,
529 runId,
530 nodeId: null,
531 providerThreadId: null,
532 providerTurnId: null,
533 nativeItemRef: null,
534 parentItemId: null,
535 ordinal: 1,
536 status: type === "run_interrupt_result" ? ("interrupted" as const) : ("completed" as const),
537 title: "Interrupt",
538 startedAt: now,
539 completedAt: now,
540 updatedAt: now,
541 type,
542 message: "Stopped by user",
543 });
544 const running = run("run-stopping", 1, "running");
545 const request = signal("run_interrupt_request", running.id);
546
547 it.each([
548 { name: "no Stop", runs: [running], turnItems: [], state: null },
549 {
550 name: "a Stop the agent is winding down",
551 runs: [running],
552 turnItems: [request],
553 state: "stopping",
554 },
555 {
556 name: "a Stop the provider never confirmed",
557 runs: [running],
558 turnItems: [{ ...request, unresponsiveAt: now }],
559 state: "unresponsive",
560 },
561 {
562 name: "a Stop that ended the run",
563 runs: [running],
564 turnItems: [request, signal("run_interrupt_result", running.id)],
565 state: null,
566 },
567 {
568 name: "a settled run's background work still stopping",
569 runs: [{ ...running, status: "completed" as const, completedAt: now }],
570 turnItems: [request],
571 state: null,
572 },
573 {
574 name: "a settled run whose background work ignored Stop",
575 runs: [{ ...running, status: "completed" as const, completedAt: now }],
576 turnItems: [{ ...request, unresponsiveAt: now }],
577 state: "unresponsive",
578 },
579 {
580 name: "a settled run whose background work ignored Stop, with a queued follow-up",
581 runs: [
582 { ...running, status: "completed" as const, completedAt: now },
583 run("run-queued", 2, "queued"),
584 ],
585 turnItems: [{ ...request, unresponsiveAt: now }],
586 state: "unresponsive",
587 },
588 ])("presents $name", ({ runs, turnItems, state }) => {
589 expect(presentRunStop({ runs, turnItems })?.state ?? null).toBe(state);
590 });
591});
592
593describe("deriveRunlessWorkStartedAt", () => {
594 const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z");
595 const rootTurn = (
596 status: OrchestrationV2ExecutionNode["status"],
597 startedAt = now,
598 ): OrchestrationV2ExecutionNode => ({
599 id: NodeId.make("child-root"),
600 threadId: v2Projection.thread.id,
601 runId: null,
602 parentNodeId: null,
603 rootNodeId: NodeId.make("child-root"),
604 kind: "root_turn",
605 status,
606 countsForRun: false,
607 providerThreadId: null,
608 providerTurnId: null,
609 nativeItemRef: null,
610 runtimeRequestId: null,
611 checkpointScopeId: null,
612 startedAt,
613 completedAt: null,
614 });
615
616 const nativeChild = {
617 ...v2Projection,
618 thread: {
619 ...v2Projection.thread,
620 creationSource: "provider" as const,
621 lineage: {
622 parentThreadId: ThreadId.make("parent"),
623 relationshipToParent: "subagent" as const,
624 rootThreadId: ThreadId.make("parent"),
625 },
626 },
627 };
628
629 it("times a provider-native subagent from its runless root turn while it works", () => {
630 const projection = {
631 ...nativeChild,
632 thread: {
633 ...nativeChild.thread,
634 activeProviderThreadId: ProviderThreadId.make("native-child"),
635 },
636 nodes: [rootTurn("running", later)],
637 };
638 expect(deriveRunlessWorkStartedAt(projection)).toBe("2026-07-28T10:05:00.000Z");
639 expect(deriveThreadRuntime(projection)).toBeNull();
640 });
641
642 it("ignores root turns that belong to a run, and threads the provider does not run", () => {
643 const owned = { ...rootTurn("running"), runId: RunId.make("run-1") };
644 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [owned] })).toBeNull();
645 expect(
646 deriveRunlessWorkStartedAt({ ...v2Projection, nodes: [rootTurn("running")] }),
647 ).toBeNull();
648 });
649});
650
651describe("deriveProviderSubagentStatus", () => {
652 const root = {
653 id: NodeId.make("child-root"),
654 threadId: v2Projection.thread.id,
655 runId: null,
656 parentNodeId: null,
657 rootNodeId: NodeId.make("child-root"),
658 kind: "root_turn" as const,
659 status: "completed" as const,
660 countsForRun: false,
661 providerThreadId: null,
662 providerTurnId: null,
663 nativeItemRef: null,
664 runtimeRequestId: null,
665 checkpointScopeId: null,
666 startedAt: now,
667 completedAt: now,
668 };
669 const child = (creationSource: "provider" | "mcp") => ({
670 ...v2Projection,
671 thread: {
672 ...v2Projection.thread,
673 creationSource,
674 lineage: {
675 parentThreadId: ThreadId.make("parent"),
676 relationshipToParent: "subagent" as const,
677 rootThreadId: ThreadId.make("parent"),
678 },
679 },
680 nodes: [root],
681 });
682
683 it("leaves T3 delegated tasks and ordinary threads alone", () => {
684 expect(deriveProviderSubagentStatus(child("mcp"))).toBeNull();
685 expect(deriveProviderSubagentStatus({ ...v2Projection, nodes: [root] })).toBeNull();
686 });
687});
688
689describe("provider-reported model selection", () => {
690 const selected = v2Projection.thread.modelSelection;
691 const reported = { ...selected, options: [{ id: "reasoningEffort", value: "default" }] };
692 const providerThread = {
693 id: ProviderThreadId.make("active"),
694 driver: ProviderDriverKind.make("codex"),
695 providerInstanceId: selected.instanceId,
696 providerSessionId: ProviderSessionId.make("session"),
697 appThreadId: v2Projection.thread.id,
698 ownerNodeId: null,
699 nativeThreadRef: null,
700 nativeConversationHeadRef: null,
701 status: "idle" as const,
702 firstRunOrdinal: null,
703 lastRunOrdinal: null,
704 handoffIds: [],
705 forkedFrom: null,
706 createdAt: now,
707 updatedAt: now,
708 nativeMetadata: { modelSelection: reported },
709 };
710 const projection = {
711 ...v2Projection,
712 thread: { ...v2Projection.thread, activeProviderThreadId: providerThread.id },
713 providerThreads: [providerThread],
714 };
715
716 it("reads only the active provider thread's reported selection", () => {
717 expect(deriveReportedModelSelection(projection)).toBe(reported);
718 expect(
719 deriveReportedModelSelection({
720 ...projection,
721 thread: { ...projection.thread, activeProviderThreadId: null },
722 }),
723 ).toBeNull();
724 expect(
725 deriveReportedModelSelection({
726 ...projection,
727 providerThreads: [
728 { ...providerThread, providerInstanceId: ProviderInstanceId.make("other") },
729 ],
730 }),
731 ).toBeNull();
732 });
733});
734
735describe("formatModelSelectionEffort", () => {
736 it("labels an old Ultracode effort by the effort it runs at", () => {
737 const models = [
738 {
739 slug: "claude-opus-5-5",
740 name: "Claude Opus 5.5",
741 isCustom: false,
742 capabilities: createModelCapabilities({
743 optionDescriptors: [
744 {
745 id: "effort",
746 label: "Reasoning",
747 type: "select",
748 options: [
749 { id: "high", label: "High", isDefault: true },
750 { id: "xhigh", label: "Extra High" },
751 ],
752 },
753 { id: "ultracode", label: "Ultracode", type: "boolean" },
754 ],
755 }),
756 },
757 ];
758 const selection = createModelSelection(
759 ProviderInstanceId.make("claudeAgent"),
760 "claude-opus-5-5",
761 [{ id: "effort", value: "ultracode" }],
762 );
763
764 expect(formatModelSelectionEffort(selection, models)).toBe("Extra High");
765 });
766
767 it("reads ACP thought_level and role: reasoning controls for cataloged and uncataloged models", () => {
768 const models = [
769 {
770 slug: "gemini-4-neon",
771 name: "Gemini 4 Neon",
772 isCustom: false,
773 capabilities: createModelCapabilities({
774 optionDescriptors: [
775 {
776 id: "thought_level",
777 label: "Thinking",
778 type: "select",
779 role: "reasoning",
780 options: [
781 { id: "medium", label: "Medium", isDefault: true },
782 { id: "high", label: "High" },
783 ],
784 },
785 ],
786 }),
787 },
788 {
789 slug: "acp-custom-agent",
790 name: "ACP Custom Agent",
791 isCustom: false,
792 capabilities: createModelCapabilities({
793 optionDescriptors: [
794 {
795 id: "custom_thinking_mode",
796 label: "Thinking",
797 type: "select",
798 role: "reasoning",
799 options: [{ id: "deep", label: "Deep" }],
800 },
801 ],
802 }),
803 },
804 ];
805 const antigravitySelection = createModelSelection(
806 ProviderInstanceId.make("antigravity"),
807 "gemini-4-neon",
808 [{ id: "thought_level", value: "high" }],
809 );
810 const customSelection = createModelSelection(
811 ProviderInstanceId.make("acpRegistry"),
812 "acp-custom-agent",
813 [{ id: "custom_thinking_mode", value: "deep" }],
814 );
815 const uncatalogedSelection = createModelSelection(
816 ProviderInstanceId.make("antigravity"),
817 "gemini-4-neon-preview",
818 [{ id: "thought_level", value: "high" }],
819 );
820
821 expect(formatModelSelectionEffort(antigravitySelection, models)).toBe("High");
822 expect(formatModelSelectionEffort(customSelection, models)).toBe("Deep");
823 expect(
824 formatSubagentEffort({
825 modelSlug: "gemini-4-neon-preview",
826 modelSelection: uncatalogedSelection,
827 provider: { driver: ProviderDriverKind.make("antigravity"), models },
828 }),
829 ).toBe("high");
830 expect(
831 readSelectedEffortValue(customSelection, models[1]?.capabilities?.optionDescriptors),
832 ).toBe("deep");
833 });
834});
835
836describe("isBackgroundWorkStopPending", () => {
837 const tasks = [{ taskId: "dev-server" }];
838 const sent = { threadKey: "env:thread", taskIds: ["dev-server"], retryAt: null };
839 const accepted = { ...sent, retryAt: 10_000 };
840
841 it("stays pending after acceptance while a stopped task is still listed", () => {
842 expect(isBackgroundWorkStopPending(sent, "env:thread", tasks, false)).toBe(true);
843 expect(isBackgroundWorkStopPending(accepted, "env:thread", tasks, false)).toBe(true);
844 });
845
846 it("ends once the stopped tasks leave, even if new work starts", () => {
847 expect(isBackgroundWorkStopPending(accepted, "env:thread", [], false)).toBe(false);
848 expect(isBackgroundWorkStopPending(accepted, "env:thread", [{ taskId: "next" }], false)).toBe(
849 false,
850 );
851 });
852
853 it("allows retry at the deadline even if a stopped task remains", () => {
854 const request = { ...accepted, retryAt: 10_000 };
855 expect(isBackgroundWorkStopPending(request, "env:thread", tasks, false)).toBe(true);
856 expect(isBackgroundWorkStopPending(request, "env:thread", tasks, true)).toBe(false);
857 });
858
859 it("only applies to the thread that sent the Stop", () => {
860 expect(isBackgroundWorkStopPending(null, "env:thread", tasks, false)).toBe(false);
861 expect(isBackgroundWorkStopPending(sent, "env:other", tasks, false)).toBe(false);
862 });
863});
864
865describe("presentProviderGoal", () => {
866 it("rolls token counts that round to 1000k over to 1m", () => {
867 const usage = (tokensUsed: number) =>
868 presentProviderGoal(
869 { objective: "Ship the feature", status: "active", tokensUsed, tokenBudget: 2_000_000 },
870 true,
871 ).usage;
872 expect(usage(999_499)).toBe("999k / 2m tokens");
873 expect(usage(999_500)).toBe("1m / 2m tokens");
874 expect(usage(999_999)).toBe("1m / 2m tokens");
875 expect(usage(1_000_000)).toBe("1m / 2m tokens");
876 expect(
877 presentProviderGoal(
878 {
879 objective: "Ship the feature",
880 status: "paused",
881 tokensUsed: 999_500,
882 tokenBudget: 999_500,
883 },
884 false,
885 ).usage,
886 ).toBe("1m / 1m tokens");
887 });
888});
889
890describe("presentPendingBackgroundWork", () => {
891 it("names a command by its script, not the shell that wraps it", () => {
892 const presentation = presentPendingBackgroundWork([
893 {
894 taskId: "call_1",
895 kind: "command",
896 description: `/bin/zsh -lc "mv a.ts b.ts\ncat > b.ts <<'EOF'\nexport {};\nEOF"`,
897 },
898 ]);
899 expect(presentation?.items[0]?.label).toBe("mv a.ts b.ts\ncat > b.ts <<'EOF'\nexport {};\nEOF");
900 });
901});