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

threadExecution.test.ts

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