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

threadExecution.test.ts

490 lines15.9 KB

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