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

threadExecution.test.ts

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