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

threadExecution.test.ts

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