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