Open History to see the last commit
1import {
2 EnvironmentId,
3 MessageId,
4 NodeId,
5 ProviderSessionId,
6 RunId,
7 RuntimeRequestId,
8 TurnItemId,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import { describe, expect, it } from "vite-plus/test";
12
13import {
14 InvalidScopedProjectRefCollectionKeyError,
15 InvalidScopedThreadKeyError,
16 parseProjectRefCollectionKey,
17 parseThreadKey,
18} from "./entities.ts";
19import { presentThreadShell } from "./models.ts";
20import { v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
21import { deriveLatestThreadRun, deriveThreadRuntime } from "./threadExecution.ts";
22import { derivePendingThreadRequests } from "./threadRequests.ts";
23
24const environmentId = EnvironmentId.make("environment-v2");
25
26describe("scoped entity keys", () => {
27 it("preserves an invalid thread key as structured error data", () => {
28 const key = "missing-thread-key-separator";
29 let error: unknown;
30
31 try {
32 parseThreadKey(key);
33 } catch (cause) {
34 error = cause;
35 }
36
37 expect(error).toEqual(new InvalidScopedThreadKeyError({ key }));
38 });
39
40 it("preserves malformed project reference collection input and its cause", () => {
41 const key = "not-json";
42 let error: unknown;
43
44 try {
45 parseProjectRefCollectionKey(key);
46 } catch (cause) {
47 error = cause;
48 }
49
50 expect(error).toBeInstanceOf(InvalidScopedProjectRefCollectionKeyError);
51 expect(error).toMatchObject({ key, cause: expect.anything() });
52 });
53
54 it("rejects invalid project reference collection shapes", () => {
55 const key = JSON.stringify([["environment-1"]]);
56
57 expect(() => parseProjectRefCollectionKey(key)).toThrowError(
58 InvalidScopedProjectRefCollectionKeyError,
59 );
60 });
61});
62
63describe("V2 client presentation", () => {
64 it("presents shell timestamps and status without constructing V1 state", () => {
65 const shell = presentThreadShell(environmentId, v2ThreadShell);
66 expect(shell.environmentId).toBe(environmentId);
67 expect(shell.createdAt).toBe("2026-06-20T00:00:00.000Z");
68 expect(shell.runtime).toBeNull();
69 expect(shell.source).toBe(v2ThreadShell);
70 });
71
72 it("presents provider errors carried by failed thread shells", () => {
73 const runId = RunId.make("run-failed");
74 const shell = presentThreadShell(environmentId, {
75 ...v2ThreadShell,
76 latestRunId: runId,
77 status: "failed",
78 lastError: "provider process exited",
79 });
80
81 expect(shell.runtime).toMatchObject({
82 status: "failed",
83 lastError: "provider process exited",
84 });
85 });
86
87 it("preserves shell run timestamps for sidebar activity clocks", () => {
88 const runId = RunId.make("run-working-clock");
89 const requestedAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
90 const startedAt = DateTime.makeUnsafe("2026-06-20T01:00:02.000Z");
91 const shell = presentThreadShell(environmentId, {
92 ...v2ThreadShell,
93 latestRunId: runId,
94 latestRunRequestedAt: requestedAt,
95 latestRunStartedAt: startedAt,
96 latestRunCompletedAt: null,
97 activeRunId: runId,
98 status: "running",
99 updatedAt: DateTime.makeUnsafe("2026-06-20T01:04:45.000Z"),
100 });
101
102 expect(shell.latestRun).toMatchObject({
103 runId,
104 status: "running",
105 requestedAt: "2026-06-20T01:00:00.000Z",
106 startedAt: "2026-06-20T01:00:02.000Z",
107 completedAt: null,
108 });
109 });
110
111 it("parks presented runtime at idle when a settled shell has pending background tasks", () => {
112 const runId = RunId.make("run-completed");
113 const shell = presentThreadShell(environmentId, {
114 ...v2ThreadShell,
115 latestRunId: runId,
116 activeRunId: null,
117 status: "completed",
118 pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
119 });
120
121 expect(shell.latestRun).toMatchObject({ runId, status: "completed" });
122 expect(shell.runtime).toMatchObject({
123 status: "idle",
124 activeRunId: null,
125 });
126 expect(shell.pendingBackgroundTasks).toEqual([{ taskId: "bg-1", description: "sleep 20" }]);
127 });
128
129 it("keeps terminal runtime completed when there are no pending background tasks", () => {
130 const runId = RunId.make("run-completed");
131 const shell = presentThreadShell(environmentId, {
132 ...v2ThreadShell,
133 latestRunId: runId,
134 activeRunId: null,
135 status: "completed",
136 pendingBackgroundTasks: [],
137 });
138
139 expect(shell.latestRun).toMatchObject({ runId, status: "completed" });
140 expect(shell.runtime).toMatchObject({
141 status: "completed",
142 activeRunId: null,
143 });
144 });
145
146 it("keeps runtime running when there is no background roster", () => {
147 const runId = RunId.make("run-running");
148 const shell = presentThreadShell(environmentId, {
149 ...v2ThreadShell,
150 latestRunId: runId,
151 activeRunId: runId,
152 status: "running",
153 pendingBackgroundTasks: [],
154 });
155
156 expect(shell.latestRun).toMatchObject({ runId, status: "running" });
157 expect(shell.runtime).toMatchObject({
158 status: "running",
159 activeRunId: runId,
160 });
161 });
162
163 it("keeps an older active run visible over a newer cancelled run", () => {
164 const activeRunId = RunId.make("run-active");
165 const cancelledRunId = RunId.make("run-cancelled");
166 const shell = presentThreadShell(environmentId, {
167 ...v2ThreadShell,
168 latestRunId: cancelledRunId,
169 latestRunStartedAt: null,
170 latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:05:00.000Z"),
171 activeRunId,
172 activityRunStatus: "running",
173 status: "cancelled",
174 pendingBackgroundTasks: [],
175 });
176
177 expect(shell.latestRun).toMatchObject({ runId: cancelledRunId, status: "cancelled" });
178 expect(shell.runtime).toMatchObject({
179 status: "running",
180 activeRunId,
181 });
182 });
183
184 it("keeps an older waiting run visible over a newer cancelled run", () => {
185 const shell = presentThreadShell(environmentId, {
186 ...v2ThreadShell,
187 latestRunId: RunId.make("run-cancelled"),
188 activeRunId: null,
189 activityRunStatus: "waiting",
190 status: "cancelled",
191 pendingBackgroundTasks: [],
192 });
193
194 expect(shell.runtime).toMatchObject({ status: "waiting", activeRunId: null });
195 });
196
197 it("keeps a post-settlement background roster ahead of activity status", () => {
198 const activeRunId = RunId.make("run-active");
199 const shell = presentThreadShell(environmentId, {
200 ...v2ThreadShell,
201 latestRunId: RunId.make("run-cancelled"),
202 activeRunId,
203 activityRunStatus: "running",
204 status: "cancelled",
205 pendingBackgroundTasks: [{ taskId: "bg-activity", description: "background work" }],
206 });
207
208 expect(shell.runtime).toMatchObject({ status: "idle", activeRunId });
209 });
210
211 it("parks runtime idle over stale shell running when the roster is nonempty", () => {
212 const runId = RunId.make("run-stale-running");
213 const shell = presentThreadShell(environmentId, {
214 ...v2ThreadShell,
215 latestRunId: runId,
216 activeRunId: runId,
217 // Stale: server already projected a post-settlement roster, but shell
218 // status still says running (packaged orchestrator-v2 bug).
219 status: "running",
220 pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
221 });
222
223 expect(shell.latestRun).toMatchObject({ runId, status: "running" });
224 expect(shell.runtime).toMatchObject({
225 status: "idle",
226 activeRunId: runId,
227 });
228 expect(shell.pendingBackgroundTasks).toEqual([{ taskId: "bg-1", description: "sleep 20" }]);
229 });
230
231 it("parks runtime idle over stale checkpoint waiting when the roster is nonempty", () => {
232 const runId = RunId.make("run-stale-waiting");
233 const shell = presentThreadShell(environmentId, {
234 ...v2ThreadShell,
235 latestRunId: runId,
236 activeRunId: runId,
237 // Stale: checkpoint-oriented waiting masks post-settlement background work.
238 status: "waiting",
239 pendingBackgroundTasks: [{ taskId: "bg-2", description: "background bash" }],
240 });
241
242 expect(shell.latestRun).toMatchObject({ runId, status: "waiting" });
243 expect(shell.runtime).toMatchObject({
244 status: "idle",
245 activeRunId: runId,
246 });
247 expect(shell.pendingBackgroundTasks).toEqual([
248 { taskId: "bg-2", description: "background bash" },
249 ]);
250 });
251
252 it("derives execution summaries without wrapping or copying the projection", () => {
253 const runId = RunId.make("run-1");
254 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
255 const projection = {
256 ...v2Projection,
257 runs: [
258 {
259 id: runId,
260 threadId: v2Projection.thread.id,
261 ordinal: 1,
262 providerInstanceId: v2Projection.thread.providerInstanceId,
263 modelSelection: v2Projection.thread.modelSelection,
264 providerThreadId: null,
265 userMessageId: MessageId.make("message-user"),
266 rootNodeId: null,
267 activeAttemptId: null,
268 status: "running" as const,
269 requestedAt: now,
270 startedAt: now,
271 completedAt: null,
272 checkpointId: null,
273 contextHandoffId: null,
274 },
275 ],
276 messages: [
277 {
278 id: MessageId.make("message-user"),
279 threadId: v2Projection.thread.id,
280 runId,
281 nodeId: null,
282 role: "user" as const,
283 text: "Hello",
284 attachments: [],
285 streaming: false,
286 createdBy: "user" as const,
287 creationSource: "web" as const,
288 createdAt: now,
289 updatedAt: now,
290 },
291 ],
292 updatedAt: now,
293 };
294
295 expect(deriveLatestThreadRun(projection)).toMatchObject({
296 runId,
297 status: "running",
298 requestedAt: "2026-06-20T01:00:00.000Z",
299 assistantMessageId: null,
300 });
301 expect(deriveThreadRuntime(projection)).toMatchObject({
302 status: "running",
303 activeRunId: runId,
304 providerInstanceId: projection.thread.providerInstanceId,
305 });
306 });
307
308 it("parks waiting runtime for a post-settlement roster without hiding active running work", () => {
309 const runId = RunId.make("run-background-presentation");
310 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
311 const run = {
312 id: runId,
313 threadId: v2Projection.thread.id,
314 ordinal: 1,
315 providerInstanceId: v2Projection.thread.providerInstanceId,
316 modelSelection: v2Projection.thread.modelSelection,
317 providerThreadId: null,
318 userMessageId: MessageId.make("message-background-presentation"),
319 rootNodeId: null,
320 activeAttemptId: null,
321 status: "waiting" as const,
322 requestedAt: now,
323 startedAt: now,
324 completedAt: null,
325 checkpointId: null,
326 contextHandoffId: null,
327 };
328 const backgroundItem = {
329 id: TurnItemId.make("item-background-command"),
330 threadId: v2Projection.thread.id,
331 runId,
332 nodeId: null,
333 providerThreadId: null,
334 providerTurnId: null,
335 nativeItemRef: null,
336 parentItemId: null,
337 ordinal: 0,
338 status: "running" as const,
339 title: "Background command",
340 startedAt: now,
341 completedAt: null,
342 updatedAt: now,
343 type: "command_execution" as const,
344 input: "sleep 20",
345 };
346
347 expect(
348 deriveThreadRuntime({
349 ...v2Projection,
350 runs: [run],
351 turnItems: [backgroundItem],
352 }),
353 ).toMatchObject({
354 status: "idle",
355 activeRunId: null,
356 });
357 expect(
358 deriveThreadRuntime({
359 ...v2Projection,
360 runs: [{ ...run, status: "running" as const }],
361 turnItems: [backgroundItem],
362 }),
363 ).toMatchObject({
364 status: "running",
365 activeRunId: runId,
366 });
367 });
368
369 it("joins pending request entities to their native turn-item display data", () => {
370 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
371 const requestId = RuntimeRequestId.make("request-approval");
372 const item = {
373 id: TurnItemId.make("item-approval"),
374 threadId: v2Projection.thread.id,
375 runId: null,
376 nodeId: NodeId.make("node-root"),
377 providerThreadId: null,
378 providerTurnId: null,
379 nativeItemRef: null,
380 parentItemId: null,
381 ordinal: 0,
382 status: "completed" as const,
383 title: null,
384 startedAt: now,
385 completedAt: now,
386 updatedAt: now,
387 type: "approval_request" as const,
388 requestId,
389 requestKind: "command" as const,
390 prompt: "Allow command?",
391 };
392 const projection = {
393 ...v2Projection,
394 runtimeRequests: [
395 {
396 id: requestId,
397 nodeId: NodeId.make("node-root"),
398 providerTurnId: null,
399 nativeRequestRef: null,
400 kind: "command" as const,
401 status: "pending" as const,
402 responseCapability: {
403 type: "not_resumable" as const,
404 reason: "provider disconnected",
405 },
406 createdAt: now,
407 resolvedAt: null,
408 },
409 ],
410 turnItems: [item],
411 updatedAt: now,
412 };
413
414 expect(derivePendingThreadRequests(projection).approvals).toEqual([
415 {
416 requestId,
417 requestKind: "command",
418 createdAt: "2026-06-20T01:00:00.000Z",
419 detail: "Allow command?",
420 responseCapability: "not_resumable",
421 },
422 ]);
423 expect(derivePendingThreadRequests(projection).userInputs).toEqual([]);
424 });
425
426 it("preserves structured-question selection mode and defaults legacy payloads", () => {
427 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
428 const multiRequestId = RuntimeRequestId.make("request-multi-select");
429 const legacyRequestId = RuntimeRequestId.make("request-legacy-single-select");
430 const runtimeRequests = [multiRequestId, legacyRequestId].map((id) => ({
431 id,
432 nodeId: NodeId.make(`node-${id}`),
433 providerTurnId: null,
434 nativeRequestRef: null,
435 kind: "user_input" as const,
436 status: "pending" as const,
437 responseCapability: {
438 type: "live" as const,
439 providerSessionId: ProviderSessionId.make("provider-session-questions"),
440 },
441 createdAt: now,
442 resolvedAt: null,
443 }));
444 const common = {
445 threadId: v2Projection.thread.id,
446 runId: null,
447 providerThreadId: null,
448 providerTurnId: null,
449 nativeItemRef: null,
450 parentItemId: null,
451 ordinal: 0,
452 status: "completed" as const,
453 title: null,
454 startedAt: now,
455 completedAt: now,
456 updatedAt: now,
457 type: "user_input_request" as const,
458 };
459 const projection = {
460 ...v2Projection,
461 runtimeRequests,
462 turnItems: [
463 {
464 ...common,
465 id: TurnItemId.make("item-multi-select"),
466 nodeId: NodeId.make("node-request-multi-select"),
467 requestId: multiRequestId,
468 questions: [
469 {
470 id: "regions",
471 header: "Regions",
472 question: "Which regions?",
473 options: [
474 { label: "US", description: "United States" },
475 { label: "EU", description: "European Union" },
476 ],
477 multiSelect: true,
478 },
479 ],
480 },
481 {
482 ...common,
483 id: TurnItemId.make("item-legacy-single-select"),
484 nodeId: NodeId.make("node-request-legacy-single-select"),
485 requestId: legacyRequestId,
486 questions: [
487 {
488 id: "target",
489 header: "Target",
490 question: "Which target?",
491 options: [{ label: "Staging", description: "Staging environment" }],
492 },
493 ],
494 },
495 ],
496 updatedAt: now,
497 };
498
499 expect(
500 derivePendingThreadRequests(projection).userInputs.map((input) => ({
501 requestId: input.requestId,
502 multiSelect: input.questions[0]?.multiSelect,
503 })),
504 ).toEqual([
505 { requestId: multiRequestId, multiSelect: true },
506 { requestId: legacyRequestId, multiSelect: false },
507 ]);
508 });
509});