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 ThreadId,
13 type OrchestrationV2ExecutionNode,
14 type OrchestrationV2RunStatus,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import { usageLimitBlockedRun } from "@t3tools/shared/orchestrationV2ThreadError";
18import { describe, expect, it } from "vite-plus/test";
19
20import { v2Projection } from "./orchestrationV2TestFixtures.ts";
21import {
22 deriveReportedModelSelection,
23 deriveLatestThreadRun,
24 deriveProviderSubagentStatus,
25 deriveResumableRunId,
26 deriveRunlessWorkStartedAt,
27 deriveThreadActivityRun,
28 deriveThreadRuntime,
29 isBackgroundWorkStopPending,
30 presentPendingBackgroundWork,
31 presentProviderGoal,
32 presentRunStop,
33 threadRuntimeHasInterruptibleRun,
34} from "./threadExecution.ts";
35
36const now = DateTime.makeUnsafe("2026-07-28T10:00:00.000Z");
37
38function run(id: string, ordinal: number, status: OrchestrationV2RunStatus) {
39 return {
40 id: RunId.make(id),
41 threadId: v2Projection.thread.id,
42 ordinal,
43 providerInstanceId: v2Projection.thread.providerInstanceId,
44 modelSelection: v2Projection.thread.modelSelection,
45 providerThreadId: null,
46 userMessageId: MessageId.make(`message-${id}`),
47 rootNodeId: null,
48 activeAttemptId: null,
49 status,
50 requestedAt: now,
51 startedAt: status === "queued" ? null : now,
52 completedAt: null,
53 checkpointId: null,
54 contextHandoffId: null,
55 };
56}
57
58describe("thread execution presentation", () => {
59 it("derives the current root failure without inheriting errors from children or previous runs", () => {
60 const failed = { ...run("limited", 1, "failed"), rootNodeId: NodeId.make("root") };
61 const item = {
62 id: TurnItemId.make("limit-error"),
63 threadId: v2Projection.thread.id,
64 runId: failed.id,
65 nodeId: failed.rootNodeId,
66 providerThreadId: null,
67 providerTurnId: null,
68 nativeItemRef: null,
69 parentItemId: null,
70 ordinal: 1,
71 type: "error" as const,
72 status: "failed" as const,
73 title: "Usage limit reached",
74 startedAt: now,
75 completedAt: now,
76 updatedAt: now,
77 failure: {
78 class: "usage_limit" as const,
79 message: "Plan limit reached",
80 code: "usageLimitExceeded",
81 retryable: null,
82 },
83 };
84 const projection = { ...v2Projection, runs: [failed], turnItems: [item] };
85 expect(deriveThreadRuntime(projection)).toMatchObject({
86 lastError: "Plan limit reached",
87 lastErrorClass: "usage_limit",
88 });
89 expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(failed.id);
90 expect(
91 deriveThreadRuntime({
92 ...projection,
93 turnItems: [{ ...item, nodeId: NodeId.make("child") }],
94 }),
95 ).toMatchObject({ lastError: null, lastErrorClass: null });
96 expect(
97 deriveThreadRuntime({
98 ...projection,
99 runs: [{ ...failed, rootNodeId: NodeId.make("new-root") }],
100 }),
101 ).toMatchObject({ lastError: null, lastErrorClass: null });
102 expect(
103 deriveThreadRuntime({ ...projection, runs: [failed, run("new", 2, "running")] }),
104 ).toMatchObject({ status: "running", lastError: null, lastErrorClass: null });
105 });
106
107 // regression: #15029 working timers no longer reset on every background wake
108 it("counts a wake run's activity from the start of the work it continues", () => {
109 const workStartedAt = DateTime.makeUnsafe("2026-07-28T09:20:00.000Z");
110 const wake = { ...run("wake", 2, "running"), workStartedAt };
111 expect(
112 deriveThreadRuntime({ ...v2Projection, runs: [run("prompt", 1, "completed"), wake] })
113 ?.activityStartedAt,
114 ).toBe("2026-07-28T09:20:00.000Z");
115 expect(
116 deriveThreadRuntime({ ...v2Projection, runs: [run("prompt", 1, "running")] })
117 ?.activityStartedAt,
118 ).toBe("2026-07-28T10:00:00.000Z");
119 });
120
121 it("keeps a subscription limit visible while later messages stay queued", () => {
122 const failed = {
123 ...run("limited", 1, "failed"),
124 rootNodeId: NodeId.make("root"),
125 completedAt: now,
126 };
127 const queued = run("queued", 2, "queued");
128 const item = {
129 id: TurnItemId.make("limit-error"),
130 threadId: v2Projection.thread.id,
131 runId: failed.id,
132 nodeId: failed.rootNodeId,
133 providerThreadId: null,
134 providerTurnId: null,
135 nativeItemRef: null,
136 parentItemId: null,
137 ordinal: 1,
138 type: "error" as const,
139 status: "failed" as const,
140 title: "Usage limit reached",
141 startedAt: now,
142 completedAt: now,
143 updatedAt: now,
144 failure: {
145 class: "usage_limit" as const,
146 message: "Plan limit reached",
147 code: "usageLimitExceeded",
148 retryable: null,
149 },
150 };
151 const projection = { ...v2Projection, runs: [failed, queued], turnItems: [item] };
152
153 expect(deriveLatestThreadRun(projection)?.runId).toBe(failed.id);
154 expect(deriveThreadActivityRun(projection)?.runId).toBe(failed.id);
155 expect(deriveThreadRuntime(projection)).toMatchObject({
156 status: "failed",
157 lastError: "Plan limit reached",
158 lastErrorClass: "usage_limit",
159 });
160 expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(failed.id);
161 const cancelledQueued = {
162 ...run("cancelled-queued", 3, "cancelled"),
163 startedAt: null,
164 completedAt: now,
165 };
166 expect(
167 usageLimitBlockedRun([failed, queued, cancelledQueued], projection.turnItems, null)?.id,
168 ).toBe(failed.id);
169 expect(
170 deriveThreadRuntime({ ...projection, runs: [failed, queued, cancelledQueued] }),
171 ).toMatchObject({ status: "failed", lastErrorClass: "usage_limit" });
172 const providerError = {
173 ...projection,
174 turnItems: [{ ...item, failure: { ...item.failure, class: "provider_error" as const } }],
175 };
176 expect(deriveThreadRuntime(providerError)).toMatchObject({
177 status: "queued",
178 lastErrorClass: null,
179 });
180 expect(deriveResumableRunId(providerError, deriveThreadRuntime(providerError))).toBeNull();
181 });
182
183 it("keeps live activity attached to an executing run when a newer run is queued", () => {
184 const runningRun = run("run-running", 1, "running");
185 const queuedRun = run("run-queued", 2, "queued");
186 const projection = { ...v2Projection, runs: [queuedRun, runningRun], updatedAt: now };
187
188 expect(deriveLatestThreadRun(projection)?.runId).toBe(queuedRun.id);
189 expect(deriveThreadActivityRun(projection)).toMatchObject({
190 runId: runningRun.id,
191 status: "running",
192 });
193
194 const runtime = deriveThreadRuntime(projection);
195 expect(runtime).toMatchObject({
196 status: "running",
197 activeRunId: runningRun.id,
198 });
199 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
200 });
201
202 it("marks an open run whose provider turn already ended", () => {
203 const attemptId = RunAttemptId.make("attempt-open");
204 const openRun = { ...run("run-open", 1, "running"), activeAttemptId: attemptId };
205 const providerTurn = (status: "running" | "failed") => ({
206 id: ProviderTurnId.make("provider-turn-open"),
207 providerThreadId: ProviderThreadId.make("provider-thread-open"),
208 nodeId: NodeId.make("node-open"),
209 runAttemptId: attemptId,
210 nativeTurnRef: null,
211 ordinal: 1,
212 status,
213 startedAt: now,
214 completedAt: status === "running" ? null : now,
215 });
216 const projection = (status: "running" | "failed") => ({
217 ...v2Projection,
218 runs: [openRun],
219 providerTurns: [providerTurn(status)],
220 updatedAt: now,
221 });
222
223 expect(deriveThreadActivityRun(projection("running"))?.turnEnded).toBeUndefined();
224 expect(deriveThreadActivityRun(projection("failed"))).toMatchObject({
225 status: "running",
226 turnEnded: true,
227 });
228 });
229
230 it("presents a held queue as the stopped run instead of queued work", () => {
231 const interrupted = { ...run("run-interrupted", 1, "interrupted"), completedAt: now };
232 const held = { ...run("run-held", 2, "queued"), queueHeld: true };
233 const projection = { ...v2Projection, runs: [interrupted, held], updatedAt: now };
234
235 expect(deriveLatestThreadRun(projection)?.runId).toBe(interrupted.id);
236 expect(deriveThreadActivityRun(projection)?.runId).toBe(interrupted.id);
237 expect(deriveThreadRuntime(projection)).toMatchObject({
238 status: "interrupted",
239 activeRunId: null,
240 });
241 expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(interrupted.id);
242
243 const resumed = { ...projection, runs: [interrupted, { ...held, queueHeld: false }] };
244 expect(deriveThreadRuntime(resumed)).toMatchObject({ status: "queued" });
245
246 const onlyHeld = {
247 ...projection,
248 runs: [held],
249 thread: { ...projection.thread, activeProviderThreadId: null },
250 };
251 expect(deriveLatestThreadRun(onlyHeld)).toBeNull();
252 expect(deriveThreadRuntime(onlyHeld)).toBeNull();
253 });
254
255 it("does not expose a queued-only run as interruptible", () => {
256 const queuedRun = run("run-queued", 1, "queued");
257 const projection = { ...v2Projection, runs: [queuedRun], updatedAt: now };
258
259 expect(deriveThreadActivityRun(projection)).toMatchObject({
260 runId: queuedRun.id,
261 status: "queued",
262 });
263
264 const runtime = deriveThreadRuntime(projection);
265 expect(runtime).toMatchObject({
266 status: "queued",
267 activeRunId: null,
268 });
269 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
270 });
271});
272
273describe("presentRunStop", () => {
274 const signal = (type: "run_interrupt_request" | "run_interrupt_result", runId: RunId) => ({
275 id: TurnItemId.make(`${type}:${runId}`),
276 threadId: v2Projection.thread.id,
277 runId,
278 nodeId: null,
279 providerThreadId: null,
280 providerTurnId: null,
281 nativeItemRef: null,
282 parentItemId: null,
283 ordinal: 1,
284 status: type === "run_interrupt_result" ? ("interrupted" as const) : ("completed" as const),
285 title: "Interrupt",
286 startedAt: now,
287 completedAt: now,
288 updatedAt: now,
289 type,
290 message: "Stopped by user",
291 });
292 const running = run("run-stopping", 1, "running");
293 const request = signal("run_interrupt_request", running.id);
294
295 it.each([
296 { name: "no Stop", runs: [running], turnItems: [], state: null },
297 {
298 name: "a Stop the agent is winding down",
299 runs: [running],
300 turnItems: [request],
301 state: "stopping",
302 },
303 {
304 name: "a Stop the provider never confirmed",
305 runs: [running],
306 turnItems: [{ ...request, unresponsiveAt: now }],
307 state: "unresponsive",
308 },
309 {
310 name: "a Stop that ended the run",
311 runs: [running],
312 turnItems: [request, signal("run_interrupt_result", running.id)],
313 state: null,
314 },
315 {
316 name: "a settled run's background work still stopping",
317 runs: [{ ...running, status: "completed" as const, completedAt: now }],
318 turnItems: [request],
319 state: null,
320 },
321 {
322 name: "a settled run whose background work ignored Stop",
323 runs: [{ ...running, status: "completed" as const, completedAt: now }],
324 turnItems: [{ ...request, unresponsiveAt: now }],
325 state: "unresponsive",
326 },
327 {
328 name: "a settled run whose background work ignored Stop, with a queued follow-up",
329 runs: [
330 { ...running, status: "completed" as const, completedAt: now },
331 run("run-queued", 2, "queued"),
332 ],
333 turnItems: [{ ...request, unresponsiveAt: now }],
334 state: "unresponsive",
335 },
336 ])("presents $name", ({ runs, turnItems, state }) => {
337 expect(presentRunStop({ runs, turnItems })?.state ?? null).toBe(state);
338 });
339});
340
341describe("deriveRunlessWorkStartedAt", () => {
342 const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z");
343 const rootTurn = (
344 status: OrchestrationV2ExecutionNode["status"],
345 startedAt = now,
346 ): OrchestrationV2ExecutionNode => ({
347 id: NodeId.make("child-root"),
348 threadId: v2Projection.thread.id,
349 runId: null,
350 parentNodeId: null,
351 rootNodeId: NodeId.make("child-root"),
352 kind: "root_turn",
353 status,
354 countsForRun: false,
355 providerThreadId: null,
356 providerTurnId: null,
357 nativeItemRef: null,
358 runtimeRequestId: null,
359 checkpointScopeId: null,
360 startedAt,
361 completedAt: null,
362 });
363
364 const nativeChild = {
365 ...v2Projection,
366 thread: {
367 ...v2Projection.thread,
368 creationSource: "provider" as const,
369 lineage: {
370 parentThreadId: ThreadId.make("parent"),
371 relationshipToParent: "subagent" as const,
372 rootThreadId: ThreadId.make("parent"),
373 },
374 },
375 };
376
377 it("times a provider-native subagent from its runless root turn while it works", () => {
378 const projection = { ...nativeChild, nodes: [rootTurn("running", later)] };
379 expect(deriveRunlessWorkStartedAt(projection)).toBe("2026-07-28T10:05:00.000Z");
380 expect(deriveThreadRuntime(projection)).toBeNull();
381 });
382
383 it("ignores root turns that belong to a run, and threads the provider does not run", () => {
384 const owned = { ...rootTurn("running"), runId: RunId.make("run-1") };
385 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [owned] })).toBeNull();
386 expect(
387 deriveRunlessWorkStartedAt({ ...v2Projection, nodes: [rootTurn("running")] }),
388 ).toBeNull();
389 });
390});
391
392describe("deriveProviderSubagentStatus", () => {
393 const root = {
394 id: NodeId.make("child-root"),
395 threadId: v2Projection.thread.id,
396 runId: null,
397 parentNodeId: null,
398 rootNodeId: NodeId.make("child-root"),
399 kind: "root_turn" as const,
400 status: "completed" as const,
401 countsForRun: false,
402 providerThreadId: null,
403 providerTurnId: null,
404 nativeItemRef: null,
405 runtimeRequestId: null,
406 checkpointScopeId: null,
407 startedAt: now,
408 completedAt: now,
409 };
410 const child = (creationSource: "provider" | "mcp") => ({
411 ...v2Projection,
412 thread: {
413 ...v2Projection.thread,
414 creationSource,
415 lineage: {
416 parentThreadId: ThreadId.make("parent"),
417 relationshipToParent: "subagent" as const,
418 rootThreadId: ThreadId.make("parent"),
419 },
420 },
421 nodes: [root],
422 });
423
424 it("leaves T3 delegated tasks and ordinary threads alone", () => {
425 expect(deriveProviderSubagentStatus(child("mcp"))).toBeNull();
426 expect(deriveProviderSubagentStatus({ ...v2Projection, nodes: [root] })).toBeNull();
427 });
428});
429
430describe("provider-reported model selection", () => {
431 const selected = v2Projection.thread.modelSelection;
432 const reported = { ...selected, options: [{ id: "reasoningEffort", value: "default" }] };
433 const providerThread = {
434 id: ProviderThreadId.make("active"),
435 driver: ProviderDriverKind.make("codex"),
436 providerInstanceId: selected.instanceId,
437 providerSessionId: ProviderSessionId.make("session"),
438 appThreadId: v2Projection.thread.id,
439 ownerNodeId: null,
440 nativeThreadRef: null,
441 nativeConversationHeadRef: null,
442 status: "idle" as const,
443 firstRunOrdinal: null,
444 lastRunOrdinal: null,
445 handoffIds: [],
446 forkedFrom: null,
447 createdAt: now,
448 updatedAt: now,
449 nativeMetadata: { modelSelection: reported },
450 };
451 const projection = {
452 ...v2Projection,
453 thread: { ...v2Projection.thread, activeProviderThreadId: providerThread.id },
454 providerThreads: [providerThread],
455 };
456
457 it("reads only the active provider thread's reported selection", () => {
458 expect(deriveReportedModelSelection(projection)).toBe(reported);
459 expect(
460 deriveReportedModelSelection({
461 ...projection,
462 thread: { ...projection.thread, activeProviderThreadId: null },
463 }),
464 ).toBeNull();
465 expect(
466 deriveReportedModelSelection({
467 ...projection,
468 providerThreads: [
469 { ...providerThread, providerInstanceId: ProviderInstanceId.make("other") },
470 ],
471 }),
472 ).toBeNull();
473 });
474});
475
476describe("isBackgroundWorkStopPending", () => {
477 const tasks = [{ taskId: "dev-server" }];
478 const sent = { threadKey: "env:thread", taskIds: ["dev-server"], retryAt: null };
479 const accepted = { ...sent, retryAt: 10_000 };
480
481 it("stays pending after acceptance while a stopped task is still listed", () => {
482 expect(isBackgroundWorkStopPending(sent, "env:thread", tasks, false)).toBe(true);
483 expect(isBackgroundWorkStopPending(accepted, "env:thread", tasks, false)).toBe(true);
484 });
485
486 it("ends once the stopped tasks leave, even if new work starts", () => {
487 expect(isBackgroundWorkStopPending(accepted, "env:thread", [], false)).toBe(false);
488 expect(isBackgroundWorkStopPending(accepted, "env:thread", [{ taskId: "next" }], false)).toBe(
489 false,
490 );
491 });
492
493 it("allows retry at the deadline even if a stopped task remains", () => {
494 const request = { ...accepted, retryAt: 10_000 };
495 expect(isBackgroundWorkStopPending(request, "env:thread", tasks, false)).toBe(true);
496 expect(isBackgroundWorkStopPending(request, "env:thread", tasks, true)).toBe(false);
497 });
498
499 it("only applies to the thread that sent the Stop", () => {
500 expect(isBackgroundWorkStopPending(null, "env:thread", tasks, false)).toBe(false);
501 expect(isBackgroundWorkStopPending(sent, "env:other", tasks, false)).toBe(false);
502 });
503});
504
505describe("presentProviderGoal", () => {
506 it("rolls token counts that round to 1000k over to 1m", () => {
507 const usage = (tokensUsed: number) =>
508 presentProviderGoal(
509 { objective: "Ship the feature", status: "active", tokensUsed, tokenBudget: 2_000_000 },
510 true,
511 ).usage;
512 expect(usage(999_499)).toBe("999k / 2m tokens");
513 expect(usage(999_500)).toBe("1m / 2m tokens");
514 expect(usage(999_999)).toBe("1m / 2m tokens");
515 expect(usage(1_000_000)).toBe("1m / 2m tokens");
516 expect(
517 presentProviderGoal(
518 {
519 objective: "Ship the feature",
520 status: "paused",
521 tokensUsed: 999_500,
522 tokenBudget: 999_500,
523 },
524 false,
525 ).usage,
526 ).toBe("1m / 1m tokens");
527 });
528});
529
530describe("presentPendingBackgroundWork", () => {
531 it("names a command by its script, not the shell that wraps it", () => {
532 const presentation = presentPendingBackgroundWork([
533 {
534 taskId: "call_1",
535 kind: "command",
536 description: `/bin/zsh -lc "mv a.ts b.ts\ncat > b.ts <<'EOF'\nexport {};\nEOF"`,
537 },
538 ]);
539 expect(presentation?.items[0]?.label).toBe("mv a.ts b.ts\ncat > b.ts <<'EOF'\nexport {};\nEOF");
540 });
541});