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