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("does not expose a queued-only run as interruptible", () => {
177 const queuedRun = run("run-queued", 1, "queued");
178 const projection = { ...v2Projection, runs: [queuedRun], updatedAt: now };
179
180 expect(deriveThreadActivityRun(projection)).toMatchObject({
181 runId: queuedRun.id,
182 status: "queued",
183 });
184
185 const runtime = deriveThreadRuntime(projection);
186 expect(runtime).toMatchObject({
187 status: "queued",
188 activeRunId: null,
189 });
190 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
191 });
192
193 it("keeps checkpoint-wait activity visible without exposing a non-functional interrupt", () => {
194 const waitingRun = run("run-waiting", 1, "waiting");
195 const projection = { ...v2Projection, runs: [waitingRun], updatedAt: now };
196
197 expect(deriveThreadActivityRun(projection)).toMatchObject({
198 runId: waitingRun.id,
199 status: "waiting",
200 });
201
202 const runtime = deriveThreadRuntime(projection);
203 expect(runtime).toMatchObject({
204 status: "waiting",
205 activeRunId: null,
206 });
207 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
208 });
209
210 it("does not expose a stale active run after the runtime parks at idle", () => {
211 const runtime = {
212 status: "idle" as const,
213 activeRunId: RunId.make("run-stale"),
214 providerInstanceId: v2Projection.thread.providerInstanceId,
215 providerName: null,
216 lastError: null,
217 updatedAt: DateTime.formatIso(now),
218 };
219
220 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
221 });
222
223 it.each(["preparing", "starting"] as const)("keeps an active %s run interruptible", (status) => {
224 const runtime = {
225 status,
226 activeRunId: RunId.make(`run-${status}`),
227 providerInstanceId: v2Projection.thread.providerInstanceId,
228 providerName: null,
229 lastError: null,
230 updatedAt: DateTime.formatIso(now),
231 };
232
233 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
234 });
235});
236
237describe("deriveRunlessWorkStartedAt", () => {
238 const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z");
239 const rootTurn = (
240 status: OrchestrationV2ExecutionNode["status"],
241 startedAt = now,
242 ): OrchestrationV2ExecutionNode => ({
243 id: NodeId.make("child-root"),
244 threadId: v2Projection.thread.id,
245 runId: null,
246 parentNodeId: null,
247 rootNodeId: NodeId.make("child-root"),
248 kind: "root_turn",
249 status,
250 countsForRun: false,
251 providerThreadId: null,
252 providerTurnId: null,
253 nativeItemRef: null,
254 runtimeRequestId: null,
255 checkpointScopeId: null,
256 startedAt,
257 completedAt: null,
258 });
259
260 const nativeChild = {
261 ...v2Projection,
262 thread: {
263 ...v2Projection.thread,
264 creationSource: "provider" as const,
265 lineage: {
266 parentThreadId: ThreadId.make("parent"),
267 relationshipToParent: "subagent" as const,
268 rootThreadId: ThreadId.make("parent"),
269 },
270 },
271 };
272
273 it("times a provider-native subagent from its runless root turn while it works", () => {
274 const projection = { ...nativeChild, nodes: [rootTurn("running", later)] };
275 expect(deriveRunlessWorkStartedAt(projection)).toBe("2026-07-28T10:05:00.000Z");
276 // The subagent has no run, so it stays unstoppable and unqueueable.
277 expect(deriveThreadRuntime(projection)).toBeNull();
278 });
279
280 it.each(["completed", "cancelled", "failed", "interrupted", "idle"] as const)(
281 "is idle once the subagent is %s",
282 (status) => {
283 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [rootTurn(status)] })).toBe(null);
284 },
285 );
286
287 it("ignores root turns that belong to a run, and threads the provider does not run", () => {
288 const owned = { ...rootTurn("running"), runId: RunId.make("run-1") };
289 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [owned] })).toBeNull();
290 expect(
291 deriveRunlessWorkStartedAt({ ...v2Projection, nodes: [rootTurn("running")] }),
292 ).toBeNull();
293 });
294});
295
296describe("deriveProviderSubagentStatus", () => {
297 const root = {
298 id: NodeId.make("child-root"),
299 threadId: v2Projection.thread.id,
300 runId: null,
301 parentNodeId: null,
302 rootNodeId: NodeId.make("child-root"),
303 kind: "root_turn" as const,
304 status: "completed" as const,
305 countsForRun: false,
306 providerThreadId: null,
307 providerTurnId: null,
308 nativeItemRef: null,
309 runtimeRequestId: null,
310 checkpointScopeId: null,
311 startedAt: now,
312 completedAt: now,
313 };
314 const child = (creationSource: "provider" | "mcp") => ({
315 ...v2Projection,
316 thread: {
317 ...v2Projection.thread,
318 creationSource,
319 lineage: {
320 parentThreadId: ThreadId.make("parent"),
321 relationshipToParent: "subagent" as const,
322 rootThreadId: ThreadId.make("parent"),
323 },
324 },
325 nodes: [root],
326 });
327
328 it("reports the provider's own subagent from its runless root turn", () => {
329 expect(deriveProviderSubagentStatus(child("provider"))).toEqual({
330 status: "completed",
331 startedAt: "2026-07-28T10:00:00.000Z",
332 completedAt: "2026-07-28T10:00:00.000Z",
333 });
334 });
335
336 it("says how long the subagent has worked, or took", () => {
337 const startedAt = "2026-07-28T10:00:00.000Z";
338 const at = (iso: string) => Date.parse(iso);
339 expect(
340 formatProviderSubagentStatus(
341 { status: "running", startedAt, completedAt: null },
342 at("2026-07-28T10:01:05.400Z"),
343 ),
344 ).toBe("Working 1m 5s");
345 expect(
346 formatProviderSubagentStatus(
347 { status: "completed", startedAt, completedAt: "2026-07-28T10:00:34.000Z" },
348 at("2026-07-28T11:00:00.000Z"),
349 ),
350 ).toBe("Completed in 34s");
351 expect(
352 formatProviderSubagentStatus(
353 { status: "cancelled", startedAt, completedAt: "2026-07-28T10:00:34.000Z" },
354 0,
355 ),
356 ).toBe("Cancelled");
357 expect(formatProviderSubagentStatus(null, 0)).toBe("Starting");
358 });
359
360 it("leaves T3 delegated tasks and ordinary threads alone", () => {
361 expect(deriveProviderSubagentStatus(child("mcp"))).toBeNull();
362 expect(deriveProviderSubagentStatus({ ...v2Projection, nodes: [root] })).toBeNull();
363 });
364});
365
366describe("formatModelSelectionEffort", () => {
367 const instanceId = ProviderInstanceId.make("claudeAgent");
368 const selection = (options?: ReadonlyArray<{ id: string; value: string }>) => ({
369 instanceId,
370 model: "claude-sonnet-5",
371 ...(options === undefined ? {} : { options }),
372 });
373 const catalog = (descriptor: { currentValue?: string }) => [
374 {
375 slug: "claude-sonnet-5",
376 name: "Claude Sonnet 5",
377 isCustom: false,
378 capabilities: {
379 optionDescriptors: [
380 {
381 id: "effort",
382 label: "Reasoning",
383 type: "select" as const,
384 options: [
385 { id: "medium", label: "Medium" },
386 { id: "high", label: "High", isDefault: true },
387 { id: "xhigh", label: "Extra High" },
388 ],
389 ...descriptor,
390 },
391 ],
392 },
393 },
394 ];
395
396 it("shows the model's default effort when the user never picked one", () => {
397 expect(formatModelSelectionEffort(selection(), catalog({}))).toBe("High");
398 });
399
400 it("names a stored effort the way the catalog does", () => {
401 expect(
402 formatModelSelectionEffort(selection([{ id: "effort", value: "xhigh" }]), catalog({})),
403 ).toBe("Extra High");
404 });
405
406 it("uses the descriptor's current value over the default", () => {
407 expect(formatModelSelectionEffort(selection(), catalog({ currentValue: "medium" }))).toBe(
408 "Medium",
409 );
410 });
411
412 it("shows nothing for a model the catalog does not describe", () => {
413 expect(formatModelSelectionEffort(selection([{ id: "effort", value: "high" }]))).toBeNull();
414 expect(
415 formatModelSelectionEffort(
416 { ...selection(), model: "claude-haiku-4-5" },
417 catalog({ currentValue: "medium" }),
418 ),
419 ).toBeNull();
420 });
421});
422
423describe("threadRuntimeCanArchive", () => {
424 const runtime = (
425 status: ThreadRuntimeSummary["status"],
426 activeRunId: ThreadRuntimeSummary["activeRunId"],
427 ): ThreadRuntimeSummary => ({
428 status,
429 activeRunId,
430 providerInstanceId: v2Projection.thread.providerInstanceId,
431 providerName: null,
432 lastError: null,
433 updatedAt: DateTime.formatIso(now),
434 });
435
436 it.each(["preparing", "starting", "running"] as const)(
437 "blocks archive while a provider is %s",
438 (status) => {
439 expect(threadRuntimeCanArchive(runtime(status, RunId.make(`run-${status}`)))).toBe(false);
440 },
441 );
442
443 it("only blocks a queued runtime when a provider run remains attached", () => {
444 expect(threadRuntimeCanArchive(runtime("queued", RunId.make("run-queued")))).toBe(false);
445 expect(threadRuntimeCanArchive(runtime("queued", null))).toBe(true);
446 });
447
448 it("allows waiting and idle threads", () => {
449 expect(threadRuntimeCanArchive(runtime("waiting", RunId.make("run-finished")))).toBe(true);
450 expect(threadRuntimeCanArchive(runtime("idle", null))).toBe(true);
451 });
452});
453
454describe("presentPendingBackgroundWork", () => {
455 it("names a single piece of work by kind", () => {
456 expect(
457 presentPendingBackgroundWork([
458 { taskId: "a", kind: "subagent", description: "Review src/math.ts" },
459 ])?.title,
460 ).toBe("Waiting on subagent Review src/math.ts");
461 expect(presentPendingBackgroundWork([{ taskId: "a", kind: "command" }])?.title).toBe(
462 "Waiting on a command",
463 );
464 expect(presentPendingBackgroundWork([])).toBeNull();
465 });
466
467 it("groups work by kind, subagents first, and keeps each name", () => {
468 const presentation = presentPendingBackgroundWork([
469 { taskId: "cmd", kind: "command", description: "npm test" },
470 {
471 taskId: "b",
472 kind: "subagent",
473 description: "Write tests",
474 childThreadId: ThreadId.make("thread:b"),
475 },
476 { taskId: "a", kind: "subagent", description: "Review src/math.ts" },
477 ]);
478 expect(presentation?.title).toBe("Waiting on 2 subagents and 1 command");
479 expect(presentation?.items.map((item) => [item.kind, item.label, item.childThreadId])).toEqual([
480 ["subagent", "Write tests", "thread:b"],
481 ["subagent", "Review src/math.ts", undefined],
482 ["command", "npm test", undefined],
483 ]);
484 });
485
486 it("names generic work, including rosters from servers that predate kinds", () => {
487 expect(
488 presentPendingBackgroundWork([
489 { taskId: "bash", kind: "command", description: "Background sleep" },
490 { taskId: "watch", kind: "monitor" },
491 { taskId: "other", kind: "background_task" },
492 ])?.title,
493 ).toBe("Waiting on 1 command, 1 monitor and 1 background task");
494 expect(presentPendingBackgroundWork([{ taskId: "old", kind: "background_task" }])?.title).toBe(
495 "Waiting on a background task",
496 );
497 });
498});