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

threadExecution.test.ts

392 lines12.5 KB

1import {
2 TurnItemId,
3 NodeId,
4 MessageId,
5 ProviderInstanceId,
6 RunId,
7 ThreadId,
8 type OrchestrationV2ExecutionNode,
9 type OrchestrationV2RunStatus,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import { describe, expect, it } from "vite-plus/test";
13​
14import { v2Projection } from "./orchestrationV2TestFixtures.ts";
15import {
16 deriveLatestThreadRun,
17 deriveProviderSubagentStatus,
18 formatModelSelectionEffort,
19 formatProviderSubagentStatus,
20 deriveRunlessWorkStartedAt,
21 deriveThreadActivityRun,
22 deriveThreadRuntime,
23 threadRuntimeHasInterruptibleRun,
24} from "./threadExecution.ts";
25import { threadRuntimeCanArchive, type ThreadRuntimeSummary } from "./models.ts";
26​
27const now = DateTime.makeUnsafe("2026-07-28T10:00:00.000Z");
28​
29function run(id: string, ordinal: number, status: OrchestrationV2RunStatus) {
30 return {
31 id: RunId.make(id),
32 threadId: v2Projection.thread.id,
33 ordinal,
34 providerInstanceId: v2Projection.thread.providerInstanceId,
35 modelSelection: v2Projection.thread.modelSelection,
36 providerThreadId: null,
37 userMessageId: MessageId.make(`message-${id}`),
38 rootNodeId: null,
39 activeAttemptId: null,
40 status,
41 requestedAt: now,
42 startedAt: status === "queued" ? null : now,
43 completedAt: null,
44 checkpointId: null,
45 contextHandoffId: null,
46 };
48​
49describe("thread execution presentation", () => {
50 it("derives the current root failure without inheriting errors from children or previous runs", () => {
51 const failed = { ...run("limited", 1, "failed"), rootNodeId: NodeId.make("root") };
52 const item = {
53 id: TurnItemId.make("limit-error"),
54 threadId: v2Projection.thread.id,
55 runId: failed.id,
56 nodeId: failed.rootNodeId,
57 providerThreadId: null,
58 providerTurnId: null,
59 nativeItemRef: null,
60 parentItemId: null,
61 ordinal: 1,
62 type: "error" as const,
63 status: "failed" as const,
64 title: "Usage limit reached",
65 startedAt: now,
66 completedAt: now,
67 updatedAt: now,
68 failure: {
69 class: "usage_limit" as const,
70 message: "Plan limit reached",
71 code: "usageLimitExceeded",
72 retryable: null,
73 },
74 };
75 const projection = { ...v2Projection, runs: [failed], turnItems: [item] };
76 expect(deriveThreadRuntime(projection)).toMatchObject({
77 lastError: "Plan limit reached",
78 lastErrorClass: "usage_limit",
79 });
80 expect(
81 deriveThreadRuntime({
82 ...projection,
83 turnItems: [{ ...item, nodeId: NodeId.make("child") }],
84 }),
85 ).toMatchObject({ lastError: null, lastErrorClass: null });
86 expect(
87 deriveThreadRuntime({
88 ...projection,
89 runs: [{ ...failed, rootNodeId: NodeId.make("new-root") }],
90 }),
91 ).toMatchObject({ lastError: null, lastErrorClass: null });
92 expect(
93 deriveThreadRuntime({ ...projection, runs: [failed, run("new", 2, "running")] }),
94 ).toMatchObject({ status: "running", lastError: null, lastErrorClass: null });
95 });
96​
97 it("keeps live activity attached to an executing run when a newer run is queued", () => {
98 const runningRun = run("run-running", 1, "running");
99 const queuedRun = run("run-queued", 2, "queued");
100 const projection = { ...v2Projection, runs: [queuedRun, runningRun], updatedAt: now };
101​
102 expect(deriveLatestThreadRun(projection)?.runId).toBe(queuedRun.id);
103 expect(deriveThreadActivityRun(projection)).toMatchObject({
104 runId: runningRun.id,
105 status: "running",
106 });
107​
108 const runtime = deriveThreadRuntime(projection);
109 expect(runtime).toMatchObject({
110 status: "running",
111 activeRunId: runningRun.id,
112 });
113 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
114 });
115​
116 it("does not expose a queued-only run as interruptible", () => {
117 const queuedRun = run("run-queued", 1, "queued");
118 const projection = { ...v2Projection, runs: [queuedRun], updatedAt: now };
119​
120 expect(deriveThreadActivityRun(projection)).toMatchObject({
121 runId: queuedRun.id,
122 status: "queued",
123 });
124​
125 const runtime = deriveThreadRuntime(projection);
126 expect(runtime).toMatchObject({
127 status: "queued",
128 activeRunId: null,
129 });
130 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
131 });
132​
133 it("keeps checkpoint-wait activity visible without exposing a non-functional interrupt", () => {
134 const waitingRun = run("run-waiting", 1, "waiting");
135 const projection = { ...v2Projection, runs: [waitingRun], updatedAt: now };
136​
137 expect(deriveThreadActivityRun(projection)).toMatchObject({
138 runId: waitingRun.id,
139 status: "waiting",
140 });
141​
142 const runtime = deriveThreadRuntime(projection);
143 expect(runtime).toMatchObject({
144 status: "waiting",
145 activeRunId: null,
146 });
147 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
148 });
149​
150 it("does not expose a stale active run after the runtime parks at idle", () => {
151 const runtime = {
152 status: "idle" as const,
153 activeRunId: RunId.make("run-stale"),
154 providerInstanceId: v2Projection.thread.providerInstanceId,
155 providerName: null,
156 lastError: null,
157 updatedAt: DateTime.formatIso(now),
158 };
159​
160 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
161 });
162​
163 it.each(["preparing", "starting"] as const)("keeps an active %s run interruptible", (status) => {
164 const runtime = {
165 status,
166 activeRunId: RunId.make(`run-${status}`),
167 providerInstanceId: v2Projection.thread.providerInstanceId,
168 providerName: null,
169 lastError: null,
170 updatedAt: DateTime.formatIso(now),
171 };
172​
173 expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
174 });
175});
176​
177describe("deriveRunlessWorkStartedAt", () => {
178 const later = DateTime.makeUnsafe("2026-07-28T10:05:00.000Z");
179 const rootTurn = (
180 status: OrchestrationV2ExecutionNode["status"],
181 startedAt = now,
182 ): OrchestrationV2ExecutionNode => ({
183 id: NodeId.make("child-root"),
184 threadId: v2Projection.thread.id,
185 runId: null,
186 parentNodeId: null,
187 rootNodeId: NodeId.make("child-root"),
188 kind: "root_turn",
189 status,
190 countsForRun: false,
191 providerThreadId: null,
192 providerTurnId: null,
193 nativeItemRef: null,
194 runtimeRequestId: null,
195 checkpointScopeId: null,
196 startedAt,
197 completedAt: null,
198 });
199​
200 const nativeChild = {
201 ...v2Projection,
202 thread: {
203 ...v2Projection.thread,
204 creationSource: "provider" as const,
205 lineage: {
206 parentThreadId: ThreadId.make("parent"),
207 relationshipToParent: "subagent" as const,
208 rootThreadId: ThreadId.make("parent"),
209 },
210 },
211 };
212​
213 it("times a provider-native subagent from its runless root turn while it works", () => {
214 const projection = { ...nativeChild, nodes: [rootTurn("running", later)] };
215 expect(deriveRunlessWorkStartedAt(projection)).toBe("2026-07-28T10:05:00.000Z");
216 // The subagent has no run, so it stays unstoppable and unqueueable.
217 expect(deriveThreadRuntime(projection)).toBeNull();
218 });
219​
220 it.each(["completed", "cancelled", "failed", "interrupted", "idle"] as const)(
221 "is idle once the subagent is %s",
222 (status) => {
223 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [rootTurn(status)] })).toBe(null);
224 },
225 );
226​
227 it("ignores root turns that belong to a run, and threads the provider does not run", () => {
228 const owned = { ...rootTurn("running"), runId: RunId.make("run-1") };
229 expect(deriveRunlessWorkStartedAt({ ...nativeChild, nodes: [owned] })).toBeNull();
230 expect(
231 deriveRunlessWorkStartedAt({ ...v2Projection, nodes: [rootTurn("running")] }),
232 ).toBeNull();
233 });
234});
235​
236describe("deriveProviderSubagentStatus", () => {
237 const root = {
238 id: NodeId.make("child-root"),
239 threadId: v2Projection.thread.id,
240 runId: null,
241 parentNodeId: null,
242 rootNodeId: NodeId.make("child-root"),
243 kind: "root_turn" as const,
244 status: "completed" as const,
245 countsForRun: false,
246 providerThreadId: null,
247 providerTurnId: null,
248 nativeItemRef: null,
249 runtimeRequestId: null,
250 checkpointScopeId: null,
251 startedAt: now,
252 completedAt: now,
253 };
254 const child = (creationSource: "provider" | "mcp") => ({
255 ...v2Projection,
256 thread: {
257 ...v2Projection.thread,
258 creationSource,
259 lineage: {
260 parentThreadId: ThreadId.make("parent"),
261 relationshipToParent: "subagent" as const,
262 rootThreadId: ThreadId.make("parent"),
263 },
264 },
265 nodes: [root],
266 });
267​
268 it("reports the provider's own subagent from its runless root turn", () => {
269 expect(deriveProviderSubagentStatus(child("provider"))).toEqual({
270 status: "completed",
271 startedAt: "2026-07-28T10:00:00.000Z",
272 completedAt: "2026-07-28T10:00:00.000Z",
273 });
274 });
275​
276 it("says how long the subagent has worked, or took", () => {
277 const startedAt = "2026-07-28T10:00:00.000Z";
278 const at = (iso: string) => Date.parse(iso);
279 expect(
280 formatProviderSubagentStatus(
281 { status: "running", startedAt, completedAt: null },
282 at("2026-07-28T10:01:05.400Z"),
283 ),
284 ).toBe("Working 1m 5s");
285 expect(
286 formatProviderSubagentStatus(
287 { status: "completed", startedAt, completedAt: "2026-07-28T10:00:34.000Z" },
288 at("2026-07-28T11:00:00.000Z"),
289 ),
290 ).toBe("Completed in 34s");
291 expect(
292 formatProviderSubagentStatus(
293 { status: "cancelled", startedAt, completedAt: "2026-07-28T10:00:34.000Z" },
294 0,
295 ),
296 ).toBe("Cancelled");
297 expect(formatProviderSubagentStatus(null, 0)).toBe("Starting");
298 });
299​
300 it("leaves T3 delegated tasks and ordinary threads alone", () => {
301 expect(deriveProviderSubagentStatus(child("mcp"))).toBeNull();
302 expect(deriveProviderSubagentStatus({ ...v2Projection, nodes: [root] })).toBeNull();
303 });
304});
305​
306describe("formatModelSelectionEffort", () => {
307 const instanceId = ProviderInstanceId.make("claudeAgent");
308 const selection = (options?: ReadonlyArray<{ id: string; value: string }>) => ({
309 instanceId,
310 model: "claude-sonnet-5",
311 ...(options === undefined ? {} : { options }),
312 });
313 const catalog = (descriptor: { currentValue?: string }) => [
314 {
315 slug: "claude-sonnet-5",
316 name: "Claude Sonnet 5",
317 isCustom: false,
318 capabilities: {
319 optionDescriptors: [
320 {
321 id: "effort",
322 label: "Reasoning",
323 type: "select" as const,
324 options: [
325 { id: "medium", label: "Medium" },
326 { id: "high", label: "High", isDefault: true },
327 { id: "xhigh", label: "Extra High" },
328 ],
329 ...descriptor,
330 },
331 ],
332 },
333 },
334 ];
335​
336 it("shows the model's default effort when the user never picked one", () => {
337 expect(formatModelSelectionEffort(selection(), catalog({}))).toBe("High");
338 });
339​
340 it("names a stored effort the way the catalog does", () => {
341 expect(
342 formatModelSelectionEffort(selection([{ id: "effort", value: "xhigh" }]), catalog({})),
343 ).toBe("Extra High");
344 });
345​
346 it("uses the descriptor's current value over the default", () => {
347 expect(formatModelSelectionEffort(selection(), catalog({ currentValue: "medium" }))).toBe(
348 "Medium",
349 );
350 });
351​
352 it("shows nothing for a model the catalog does not describe", () => {
353 expect(formatModelSelectionEffort(selection([{ id: "effort", value: "high" }]))).toBeNull();
354 expect(
355 formatModelSelectionEffort(
356 { ...selection(), model: "claude-haiku-4-5" },
357 catalog({ currentValue: "medium" }),
358 ),
359 ).toBeNull();
360 });
361});
362​
363describe("threadRuntimeCanArchive", () => {
364 const runtime = (
365 status: ThreadRuntimeSummary["status"],
366 activeRunId: ThreadRuntimeSummary["activeRunId"],
367 ): ThreadRuntimeSummary => ({
368 status,
369 activeRunId,
370 providerInstanceId: v2Projection.thread.providerInstanceId,
371 providerName: null,
372 lastError: null,
373 updatedAt: DateTime.formatIso(now),
374 });
375​
376 it.each(["preparing", "starting", "running"] as const)(
377 "blocks archive while a provider is %s",
378 (status) => {
379 expect(threadRuntimeCanArchive(runtime(status, RunId.make(`run-${status}`)))).toBe(false);
380 },
381 );
382​
383 it("only blocks a queued runtime when a provider run remains attached", () => {
384 expect(threadRuntimeCanArchive(runtime("queued", RunId.make("run-queued")))).toBe(false);
385 expect(threadRuntimeCanArchive(runtime("queued", null))).toBe(true);
386 });
387​
388 it("allows waiting and idle threads", () => {
389 expect(threadRuntimeCanArchive(runtime("waiting", RunId.make("run-finished")))).toBe(true);
390 expect(threadRuntimeCanArchive(runtime("idle", null))).toBe(true);
391 });
392});