Open History to see the last commit
1import {
2 TurnItemId,
3 NodeId,
4 MessageId,
5 ProviderInstanceId,
6 RunId,
7 ThreadId,
8 type OrchestrationV2ExecutionNode,
9 type OrchestrationV2RunStatus,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import { usageLimitBlockedRun } from "@t3tools/shared/orchestrationV2ThreadError";
13import { describe, expect, it } from "vite-plus/test";
14
15import { v2Projection } from "./orchestrationV2TestFixtures.ts";
16import {
17 presentPendingBackgroundWork,
18 deriveLatestThreadRun,
19 deriveProviderSubagentStatus,
20 formatModelSelectionEffort,
21 formatProviderSubagentStatus,
22 deriveRunlessWorkStartedAt,
23 deriveThreadActivityRun,
24 deriveThreadRuntime,
25 threadRuntimeHasInterruptibleRun,
26} from "./threadExecution.ts";
27import { threadRuntimeCanArchive, type ThreadRuntimeSummary } from "./models.ts";
28
29const now = DateTime.makeUnsafe("2026-07-28T10:00:00.000Z");
30
31function run(id: string, ordinal: number, status: OrchestrationV2RunStatus) {
32 return {
33 id: RunId.make(id),
34 threadId: v2Projection.thread.id,
35 ordinal,
36 providerInstanceId: v2Projection.thread.providerInstanceId,
37 modelSelection: v2Projection.thread.modelSelection,
38 providerThreadId: null,
39 userMessageId: MessageId.make(`message-${id}`),
40 rootNodeId: null,
41 activeAttemptId: null,
42 status,
43 requestedAt: now,
44 startedAt: status === "queued" ? null : now,
45 completedAt: null,
46 checkpointId: null,
47 contextHandoffId: null,
48 };
49}
50
51describe("thread execution presentation", () => {
52 it("derives the current root failure without inheriting errors from children or previous runs", () => {
53 const failed = { ...run("limited", 1, "failed"), rootNodeId: NodeId.make("root") };
54 const item = {
55 id: TurnItemId.make("limit-error"),
56 threadId: v2Projection.thread.id,
57 runId: failed.id,
58 nodeId: failed.rootNodeId,
59 providerThreadId: null,
60 providerTurnId: null,
61 nativeItemRef: null,
62 parentItemId: null,
63 ordinal: 1,
64 type: "error" as const,
65 status: "failed" as const,
66 title: "Usage limit reached",
67 startedAt: now,
68 completedAt: now,
69 updatedAt: now,
70 failure: {
71 class: "usage_limit" as const,
72 message: "Plan limit reached",
73 code: "usageLimitExceeded",
74 retryable: null,
75 },
76 };
77 const projection = { ...v2Projection, runs: [failed], turnItems: [item] };
78 expect(deriveThreadRuntime(projection)).toMatchObject({
79 lastError: "Plan limit reached",
80 lastErrorClass: "usage_limit",
81 });
82 expect(
83 deriveThreadRuntime({
84 ...projection,
85 turnItems: [{ ...item, nodeId: NodeId.make("child") }],
86 }),
87 ).toMatchObject({ lastError: null, lastErrorClass: null });
88 expect(
89 deriveThreadRuntime({
90 ...projection,
91 runs: [{ ...failed, rootNodeId: NodeId.make("new-root") }],
92 }),
93 ).toMatchObject({ lastError: null, lastErrorClass: null });
94 expect(
95 deriveThreadRuntime({ ...projection, runs: [failed, run("new", 2, "running")] }),
96 ).toMatchObject({ status: "running", lastError: null, lastErrorClass: null });
97 });
98
99 it("keeps a subscription limit visible while later messages stay queued", () => {
100 const failed = {
101 ...run("limited", 1, "failed"),
102 rootNodeId: NodeId.make("root"),
103 completedAt: now,
104 };
105 const queued = run("queued", 2, "queued");
106 const item = {
107 id: TurnItemId.make("limit-error"),
108 threadId: v2Projection.thread.id,
109 runId: failed.id,
110 nodeId: failed.rootNodeId,
111 providerThreadId: null,
112 providerTurnId: null,
113 nativeItemRef: null,
114 parentItemId: null,
115 ordinal: 1,
116 type: "error" as const,
117 status: "failed" as const,
118 title: "Usage limit reached",
119 startedAt: now,
120 completedAt: now,
121 updatedAt: now,
122 failure: {
123 class: "usage_limit" as const,
124 message: "Plan limit reached",
125 code: "usageLimitExceeded",
126 retryable: null,
127 },
128 };
129 const projection = { ...v2Projection, runs: [failed, queued], turnItems: [item] };
130
131 expect(deriveLatestThreadRun(projection)?.runId).toBe(failed.id);
132 expect(deriveThreadActivityRun(projection)?.runId).toBe(failed.id);
133 expect(deriveThreadRuntime(projection)).toMatchObject({
134 status: "failed",
135 lastError: "Plan limit reached",
136 lastErrorClass: "usage_limit",
137 });
138 const cancelledQueued = {
139 ...run("cancelled-queued", 3, "cancelled"),
140 startedAt: null,
141 completedAt: now,
142 };
143 expect(
144 usageLimitBlockedRun([failed, queued, cancelledQueued], projection.turnItems, null)?.id,
145 ).toBe(failed.id);
146 expect(
147 deriveThreadRuntime({ ...projection, runs: [failed, queued, cancelledQueued] }),
148 ).toMatchObject({ status: "failed", lastErrorClass: "usage_limit" });
149 expect(
150 deriveThreadRuntime({
151 ...projection,
152 turnItems: [{ ...item, failure: { ...item.failure, class: "provider_error" as const } }],
153 }),
154 ).toMatchObject({ status: "queued", lastErrorClass: null });
155 });
156
157 it("keeps live activity attached to an executing run when a newer run is queued", () => {
158 const runningRun = run("run-running", 1, "running");
159 const queuedRun = run("run-queued", 2, "queued");
160 const projection = { ...v2Projection, runs: [queuedRun, runningRun], updatedAt: now };
161
162 expect(deriveLatestThreadRun(projection)?.runId).toBe(queuedRun.id);
163 expect(deriveThreadActivityRun(projection)).toMatchObject({
164 runId: runningRun.id,
165 status: "running",
166 });
167
168 const runtime = deriveThreadRuntime(projection);
169 expect(runtime).toMatchObject({
170 status: "running",
171 activeRunId: runningRun.id,
172 });
173 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
174 });
175
176 it("presents a held queue as the stopped run instead of queued work", () => {
177 const interrupted = { ...run("run-interrupted", 1, "interrupted"), completedAt: now };
178 const held = { ...run("run-held", 2, "queued"), queueHeld: true };
179 const projection = { ...v2Projection, runs: [interrupted, held], updatedAt: now };
180
181 expect(deriveLatestThreadRun(projection)?.runId).toBe(interrupted.id);
182 expect(deriveThreadActivityRun(projection)?.runId).toBe(interrupted.id);
183 expect(deriveThreadRuntime(projection)).toMatchObject({
184 status: "interrupted",
185 activeRunId: null,
186 });
187
188 // Resuming clears the hold, and the run reads as queued until it starts.
189 const resumed = { ...projection, runs: [interrupted, { ...held, queueHeld: false }] };
190 expect(deriveThreadRuntime(resumed)).toMatchObject({ status: "queued" });
191
192 // Recovery can hold a first message before any run executed; it is not work.
193 const onlyHeld = {
194 ...projection,
195 runs: [held],
196 thread: { ...projection.thread, activeProviderThreadId: null },
197 };
198 expect(deriveLatestThreadRun(onlyHeld)).toBeNull();
199 expect(deriveThreadRuntime(onlyHeld)).toBeNull();
200 });
201
202 it("does not expose a queued-only run as interruptible", () => {
203 const queuedRun = run("run-queued", 1, "queued");
204 const projection = { ...v2Projection, runs: [queuedRun], updatedAt: now };
205
206 expect(deriveThreadActivityRun(projection)).toMatchObject({
207 runId: queuedRun.id,
208 status: "queued",
209 });
210
211 const runtime = deriveThreadRuntime(projection);
212 expect(runtime).toMatchObject({
213 status: "queued",
214 activeRunId: null,
215 });
216 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
217 });
218
219 it("keeps checkpoint-wait activity visible without exposing a non-functional interrupt", () => {
220 const waitingRun = run("run-waiting", 1, "waiting");
221 const projection = { ...v2Projection, runs: [waitingRun], updatedAt: now };
222
223 expect(deriveThreadActivityRun(projection)).toMatchObject({
224 runId: waitingRun.id,
225 status: "waiting",
226 });
227
228 const runtime = deriveThreadRuntime(projection);
229 expect(runtime).toMatchObject({
230 status: "waiting",
231 activeRunId: null,
232 });
233 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
234 });
235
236 it("does not expose a stale active run after the runtime parks at idle", () => {
237 const runtime = {
238 status: "idle" as const,
239 activeRunId: RunId.make("run-stale"),
240 providerInstanceId: v2Projection.thread.providerInstanceId,
241 providerName: null,
242 lastError: null,
243 updatedAt: DateTime.formatIso(now),
244 };
245
246 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
247 });
248
249 it.each(["preparing", "starting"] as const)("keeps an active %s run interruptible", (status) => {
250 const runtime = {
251 status,
252 activeRunId: RunId.make(`run-${status}`),
253 providerInstanceId: v2Projection.thread.providerInstanceId,
254 providerName: null,
255 lastError: null,
256 updatedAt: DateTime.formatIso(now),
257 };
258
259 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
260 });
261});
262
263describe("deriveRunlessWorkStartedAt", () => {
264 const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z");
265 const rootTurn = (
266 status: OrchestrationV2ExecutionNode["status"],
267 startedAt = now,
268 ): OrchestrationV2ExecutionNode => ({
269 id: NodeId.make("child-root"),
270 threadId: v2Projection.thread.id,
271 runId: null,
272 parentNodeId: null,
273 rootNodeId: NodeId.make("child-root"),
274 kind: "root_turn",
275 status,
276 countsForRun: false,
277 providerThreadId: null,
278 providerTurnId: null,
279 nativeItemRef: null,
280 runtimeRequestId: null,
281 checkpointScopeId: null,
282 startedAt,
283 completedAt: null,
284 });
285
286 const nativeChild = {
287 ...v2Projection,
288 thread: {
289 ...v2Projection.thread,
290 creationSource: "provider" as const,
291 lineage: {
292 parentThreadId: ThreadId.make("parent"),
293 relationshipToParent: "subagent" as const,
294 rootThreadId: ThreadId.make("parent"),
295 },
296 },
297 };
298
299 it("times a provider-native subagent from its runless root turn while it works", () => {
300 const projection = { ...nativeChild, nodes: [rootTurn("running", later)] };
301 expect(deriveRunlessWorkStartedAt(projection)).toBe("2026-07-28T10:05:00.000Z");
302 // The subagent has no run, so it stays unstoppable and unqueueable.
303 expect(deriveThreadRuntime(projection)).toBeNull();
304 });
305
306 it.each(["completed", "cancelled", "failed", "interrupted", "idle"] as const)(
307 "is idle once the subagent is %s",
308 (status) => {
309 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [rootTurn(status)] })).toBe(null);
310 },
311 );
312
313 it("ignores root turns that belong to a run, and threads the provider does not run", () => {
314 const owned = { ...rootTurn("running"), runId: RunId.make("run-1") };
315 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [owned] })).toBeNull();
316 expect(
317 deriveRunlessWorkStartedAt({ ...v2Projection, nodes: [rootTurn("running")] }),
318 ).toBeNull();
319 });
320});
321
322describe("deriveProviderSubagentStatus", () => {
323 const root = {
324 id: NodeId.make("child-root"),
325 threadId: v2Projection.thread.id,
326 runId: null,
327 parentNodeId: null,
328 rootNodeId: NodeId.make("child-root"),
329 kind: "root_turn" as const,
330 status: "completed" as const,
331 countsForRun: false,
332 providerThreadId: null,
333 providerTurnId: null,
334 nativeItemRef: null,
335 runtimeRequestId: null,
336 checkpointScopeId: null,
337 startedAt: now,
338 completedAt: now,
339 };
340 const child = (creationSource: "provider" | "mcp") => ({
341 ...v2Projection,
342 thread: {
343 ...v2Projection.thread,
344 creationSource,
345 lineage: {
346 parentThreadId: ThreadId.make("parent"),
347 relationshipToParent: "subagent" as const,
348 rootThreadId: ThreadId.make("parent"),
349 },
350 },
351 nodes: [root],
352 });
353
354 it("reports the provider's own subagent from its runless root turn", () => {
355 expect(deriveProviderSubagentStatus(child("provider"))).toEqual({
356 status: "completed",
357 startedAt: "2026-07-28T10:00:00.000Z",
358 completedAt: "2026-07-28T10:00:00.000Z",
359 });
360 });
361
362 it("says how long the subagent has worked, or took", () => {
363 const startedAt = "2026-07-28T10:00:00.000Z";
364 const at = (iso: string) => Date.parse(iso);
365 expect(
366 formatProviderSubagentStatus(
367 { status: "running", startedAt, completedAt: null },
368 at("2026-07-28T10:01:05.400Z"),
369 ),
370 ).toBe("Working 1m 5s");
371 expect(
372 formatProviderSubagentStatus(
373 { status: "completed", startedAt, completedAt: "2026-07-28T10:00:34.000Z" },
374 at("2026-07-28T11:00:00.000Z"),
375 ),
376 ).toBe("Completed in 34s");
377 expect(
378 formatProviderSubagentStatus(
379 { status: "cancelled", startedAt, completedAt: "2026-07-28T10:00:34.000Z" },
380 0,
381 ),
382 ).toBe("Cancelled");
383 expect(formatProviderSubagentStatus(null, 0)).toBe("Starting");
384 });
385
386 it("leaves T3 delegated tasks and ordinary threads alone", () => {
387 expect(deriveProviderSubagentStatus(child("mcp"))).toBeNull();
388 expect(deriveProviderSubagentStatus({ ...v2Projection, nodes: [root] })).toBeNull();
389 });
390});
391
392describe("formatModelSelectionEffort", () => {
393 const instanceId = ProviderInstanceId.make("claudeAgent");
394 const selection = (options?: ReadonlyArray<{ id: string; value: string }>) => ({
395 instanceId,
396 model: "claude-sonnet-5",
397 ...(options === undefined ? {} : { options }),
398 });
399 const catalog = (descriptor: { currentValue?: string }) => [
400 {
401 slug: "claude-sonnet-5",
402 name: "Claude Sonnet 5",
403 isCustom: false,
404 capabilities: {
405 optionDescriptors: [
406 {
407 id: "effort",
408 label: "Reasoning",
409 type: "select" as const,
410 options: [
411 { id: "medium", label: "Medium" },
412 { id: "high", label: "High", isDefault: true },
413 { id: "xhigh", label: "Extra High" },
414 ],
415 ...descriptor,
416 },
417 ],
418 },
419 },
420 ];
421
422 it("shows the model's default effort when the user never picked one", () => {
423 expect(formatModelSelectionEffort(selection(), catalog({}))).toBe("High");
424 });
425
426 it("names a stored effort the way the catalog does", () => {
427 expect(
428 formatModelSelectionEffort(selection([{ id: "effort", value: "xhigh" }]), catalog({})),
429 ).toBe("Extra High");
430 });
431
432 it("uses the descriptor's current value over the default", () => {
433 expect(formatModelSelectionEffort(selection(), catalog({ currentValue: "medium" }))).toBe(
434 "Medium",
435 );
436 });
437
438 it("shows nothing for a model the catalog does not describe", () => {
439 expect(formatModelSelectionEffort(selection([{ id: "effort", value: "high" }]))).toBeNull();
440 expect(
441 formatModelSelectionEffort(
442 { ...selection(), model: "claude-haiku-4-5" },
443 catalog({ currentValue: "medium" }),
444 ),
445 ).toBeNull();
446 });
447});
448
449describe("threadRuntimeCanArchive", () => {
450 const runtime = (
451 status: ThreadRuntimeSummary["status"],
452 activeRunId: ThreadRuntimeSummary["activeRunId"],
453 ): ThreadRuntimeSummary => ({
454 status,
455 activeRunId,
456 providerInstanceId: v2Projection.thread.providerInstanceId,
457 providerName: null,
458 lastError: null,
459 updatedAt: DateTime.formatIso(now),
460 });
461
462 it.each(["preparing", "starting", "running"] as const)(
463 "blocks archive while a provider is %s",
464 (status) => {
465 expect(threadRuntimeCanArchive(runtime(status, RunId.make(`run-${status}`)))).toBe(false);
466 },
467 );
468
469 it("only blocks a queued runtime when a provider run remains attached", () => {
470 expect(threadRuntimeCanArchive(runtime("queued", RunId.make("run-queued")))).toBe(false);
471 expect(threadRuntimeCanArchive(runtime("queued", null))).toBe(true);
472 });
473
474 it("allows waiting and idle threads", () => {
475 expect(threadRuntimeCanArchive(runtime("waiting", RunId.make("run-finished")))).toBe(true);
476 expect(threadRuntimeCanArchive(runtime("idle", null))).toBe(true);
477 });
478});
479
480describe("presentPendingBackgroundWork", () => {
481 it("names a single piece of work by kind", () => {
482 expect(
483 presentPendingBackgroundWork([
484 { taskId: "a", kind: "subagent", description: "Review src/math.ts" },
485 ])?.title,
486 ).toBe("Waiting on subagent Review src/math.ts");
487 expect(presentPendingBackgroundWork([{ taskId: "a", kind: "command" }])?.title).toBe(
488 "Waiting on a command",
489 );
490 expect(presentPendingBackgroundWork([])).toBeNull();
491 });
492
493 it("groups work by kind, subagents first, and keeps each name", () => {
494 const presentation = presentPendingBackgroundWork([
495 { taskId: "cmd", kind: "command", description: "npm test" },
496 {
497 taskId: "b",
498 kind: "subagent",
499 description: "Write tests",
500 childThreadId: ThreadId.make("thread:b"),
501 },
502 { taskId: "a", kind: "subagent", description: "Review src/math.ts" },
503 ]);
504 expect(presentation?.title).toBe("Waiting on 2 subagents and 1 command");
505 expect(presentation?.items.map((item) => [item.kind, item.label, item.childThreadId])).toEqual([
506 ["subagent", "Write tests", "thread:b"],
507 ["subagent", "Review src/math.ts", undefined],
508 ["command", "npm test", undefined],
509 ]);
510 });
511
512 it("names generic work, including rosters from servers that predate kinds", () => {
513 expect(
514 presentPendingBackgroundWork([
515 { taskId: "bash", kind: "command", description: "Background sleep" },
516 { taskId: "watch", kind: "monitor" },
517 { taskId: "other", kind: "background_task" },
518 ])?.title,
519 ).toBe("Waiting on 1 command, 1 monitor and 1 background task");
520 expect(presentPendingBackgroundWork([{ taskId: "old", kind: "background_task" }])?.title).toBe(
521 "Waiting on a background task",
522 );
523 });
524});