Open History to see the last commit
1import {
2 EnvironmentId,
3 MessageId,
4 NodeId,
5 ProviderDriverKind,
6 ProviderSessionId,
7 ProviderThreadId,
8 RunId,
9 RuntimeRequestId,
10 TurnItemId,
11} from "@t3tools/contracts";
12import * as DateTime from "effect/DateTime";
13import { describe, expect, it } from "vite-plus/test";
14
15import { presentThreadShell, resolveThreadWorkingStartedAt } from "./models.ts";
16import { v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
17import { deriveLatestThreadRun, deriveThreadRuntime } from "./threadExecution.ts";
18import { isThreadWorking } from "./threadInbox.ts";
19import { derivePendingThreadRequests } from "./threadRequests.ts";
20import { canSnooze, effectiveSnoozed } from "./threadSettled.ts";
21
22const environmentId = EnvironmentId.make("environment-v2");
23
24describe("V2 client presentation", () => {
25 it("an async question blocks snooze and wakes a snoozed thread", () => {
26 const runId = RunId.make("run-async-question");
27 const running = {
28 ...v2ThreadShell,
29 snoozedAt: DateTime.makeUnsafe("2026-06-19T23:59:00.000Z"),
30 snoozedUntil: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),
31 latestRunId: runId,
32 activeRunId: runId,
33 status: "running" as const,
34 pendingRuntimeRequest: {
35 id: RuntimeRequestId.make("request-async-question"),
36 kind: "user_input" as const,
37 createdAt: v2ThreadShell.updatedAt,
38 blocking: false,
39 },
40 };
41 const active = presentThreadShell(environmentId, running);
42 expect(canSnooze(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false);
43 expect(effectiveSnoozed(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false);
44 });
45
46 it("moves a running thread with any question out of Working", () => {
47 for (const capability of [{ blocking: false }, { blocking: true }, {}]) {
48 const shell = presentThreadShell(environmentId, {
49 ...v2ThreadShell,
50 latestRunId: RunId.make("run-blocking-question"),
51 activeRunId: RunId.make("run-blocking-question"),
52 status: "running",
53 pendingRuntimeRequest: {
54 id: RuntimeRequestId.make("request-blocking-question"),
55 kind: "user_input",
56 createdAt: v2ThreadShell.updatedAt,
57 ...capability,
58 },
59 });
60 expect(shell.hasPendingUserInput).toBe(true);
61 expect(isThreadWorking(shell)).toBe(false);
62 }
63 });
64
65 it("parks a thread that never ran at idle while a pull request watch holds it", () => {
66 const watch = {
67 taskId: "pull-request-watch:github.com/acme/app#1",
68 kind: "monitor" as const,
69 awaited: true as const,
70 };
71 const watched = presentThreadShell(environmentId, {
72 ...v2ThreadShell,
73 latestRunId: null,
74 activeProviderThreadId: null,
75 activeRunId: null,
76 status: "idle",
77 pendingBackgroundTasks: [watch],
78 });
79 expect(watched.runtime).toMatchObject({ status: "idle", activeRunId: null });
80 expect(
81 presentThreadShell(environmentId, {
82 ...v2ThreadShell,
83 latestRunId: null,
84 activeProviderThreadId: null,
85 status: "idle",
86 pendingBackgroundTasks: [],
87 }).runtime,
88 ).toBeNull();
89 });
90
91 it.each([
92 { kinds: ["command"], expected: "completed" },
93 { kinds: ["command", "subagent"], expected: "idle" },
94 { kinds: ["background_task"], expected: "idle" },
95 ] as const)("presents a completed shell with $kinds as $expected", ({ kinds, expected }) => {
96 const pendingBackgroundTasks = kinds.map((kind, index) => ({
97 taskId: `bg-${index}`,
98 kind,
99 }));
100 const shell = presentThreadShell(environmentId, {
101 ...v2ThreadShell,
102 latestRunId: RunId.make("run-completed"),
103 activeRunId: null,
104 status: "completed",
105 pendingBackgroundTasks,
106 });
107
108 expect(shell.latestRun?.status).toBe("completed");
109 expect(shell.runtime).toMatchObject({ status: expected, activeRunId: null });
110 expect(shell.pendingBackgroundTasks).toEqual(pendingBackgroundTasks);
111 });
112
113 it.each(["running", "waiting"] as const)(
114 "preserves shell %s while only commands remain in the roster",
115 (status) => {
116 const runId = RunId.make("run-command");
117 const shell = presentThreadShell(environmentId, {
118 ...v2ThreadShell,
119 latestRunId: runId,
120 activeRunId: runId,
121 status,
122 pendingBackgroundTasks: [{ taskId: "dev-server", kind: "command" }],
123 });
124
125 expect(shell.latestRun?.status).toBe(status);
126 expect(shell.runtime).toMatchObject({ status, activeRunId: runId });
127 expect(shell.pendingBackgroundTasks).toEqual([{ taskId: "dev-server", kind: "command" }]);
128 },
129 );
130
131 it("keeps a failed latest run failed while background tasks are still pending", () => {
132 const shell = presentThreadShell(environmentId, {
133 ...v2ThreadShell,
134 latestRunId: RunId.make("run-failed"),
135 activeRunId: null,
136 status: "failed",
137 lastError: "Provider turn failed",
138 pendingBackgroundTasks: [
139 { taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
140 ],
141 });
142
143 expect(shell.runtime).toMatchObject({ status: "failed", lastError: "Provider turn failed" });
144 expect(shell.pendingBackgroundTasks).toHaveLength(1);
145 });
146
147 it("keeps an older active run visible over a newer cancelled run", () => {
148 const activeRunId = RunId.make("run-active");
149 const cancelledRunId = RunId.make("run-cancelled");
150 const shell = presentThreadShell(environmentId, {
151 ...v2ThreadShell,
152 latestRunId: cancelledRunId,
153 latestRunStartedAt: null,
154 latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:05:00.000Z"),
155 activeRunId,
156 activityRunStatus: "running",
157 status: "cancelled",
158 pendingBackgroundTasks: [],
159 });
160
161 expect(shell.latestRun).toMatchObject({ runId: cancelledRunId, status: "cancelled" });
162 expect(shell.runtime).toMatchObject({
163 status: "running",
164 activeRunId,
165 });
166 });
167
168 it("keeps a post-settlement background roster ahead of activity status", () => {
169 const activeRunId = RunId.make("run-active");
170 const shell = presentThreadShell(environmentId, {
171 ...v2ThreadShell,
172 latestRunId: RunId.make("run-cancelled"),
173 activeRunId,
174 activityRunStatus: "running",
175 status: "cancelled",
176 pendingBackgroundTasks: [
177 { taskId: "bg-activity", description: "background work", kind: "background_task" },
178 ],
179 });
180
181 expect(shell.runtime).toMatchObject({ status: "idle", activeRunId });
182 });
183
184 it("parks runtime idle over stale shell running when the roster is nonempty", () => {
185 const runId = RunId.make("run-stale-running");
186 const shell = presentThreadShell(environmentId, {
187 ...v2ThreadShell,
188 latestRunId: runId,
189 activeRunId: runId,
190 status: "running",
191 pendingBackgroundTasks: [
192 { taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
193 ],
194 });
195
196 expect(shell.latestRun).toMatchObject({ runId, status: "running" });
197 expect(shell.runtime).toMatchObject({
198 status: "idle",
199 activeRunId: runId,
200 });
201 expect(shell.pendingBackgroundTasks).toEqual([
202 { taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
203 ]);
204 });
205
206 it("derives execution summaries without wrapping or copying the projection", () => {
207 const runId = RunId.make("run-1");
208 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
209 const projection = {
210 ...v2Projection,
211 runs: [
212 {
213 id: runId,
214 threadId: v2Projection.thread.id,
215 ordinal: 1,
216 providerInstanceId: v2Projection.thread.providerInstanceId,
217 modelSelection: v2Projection.thread.modelSelection,
218 providerThreadId: null,
219 userMessageId: MessageId.make("message-user"),
220 rootNodeId: null,
221 activeAttemptId: null,
222 status: "running" as const,
223 requestedAt: now,
224 startedAt: now,
225 completedAt: null,
226 checkpointId: null,
227 contextHandoffId: null,
228 },
229 ],
230 messages: [
231 {
232 id: MessageId.make("message-user"),
233 threadId: v2Projection.thread.id,
234 runId,
235 nodeId: null,
236 role: "user" as const,
237 text: "Hello",
238 attachments: [],
239 streaming: false,
240 createdBy: "user" as const,
241 creationSource: "web" as const,
242 createdAt: now,
243 updatedAt: now,
244 },
245 ],
246 updatedAt: now,
247 };
248
249 expect(deriveLatestThreadRun(projection)).toMatchObject({
250 runId,
251 status: "running",
252 requestedAt: "2026-06-20T01:00:00.000Z",
253 assistantMessageId: null,
254 });
255 expect(deriveThreadRuntime(projection)).toMatchObject({
256 status: "running",
257 activeRunId: runId,
258 providerInstanceId: projection.thread.providerInstanceId,
259 });
260 for (const status of ["queued", "cancelled"] as const) {
261 const later = DateTime.add(now, { hours: 1 });
262 const latest = {
263 ...projection.runs[0]!,
264 id: RunId.make("newer-run"),
265 ordinal: 2,
266 status,
267 requestedAt: later,
268 startedAt: null,
269 completedAt: status === "cancelled" ? later : null,
270 };
271 const detail = { ...projection, runs: [...projection.runs, latest], updatedAt: later };
272 const shell = presentThreadShell(environmentId, {
273 ...v2ThreadShell,
274 latestRunId: latest.id,
275 latestRunStartedAt: null,
276 latestRunRequestedAt: later,
277 latestRunCompletedAt: latest.completedAt,
278 status,
279 activeRunId: runId,
280 activityRunStatus: "running",
281 activityRunStartedAt: now,
282 updatedAt: later,
283 });
284 expect(resolveThreadWorkingStartedAt(shell)).toBe(DateTime.formatIso(now));
285 expect(
286 resolveThreadWorkingStartedAt({
287 latestRun: deriveLatestThreadRun(detail),
288 runtime: deriveThreadRuntime(detail),
289 }),
290 ).toBe(resolveThreadWorkingStartedAt(shell));
291 const stopped = {
292 ...detail,
293 runs: detail.runs.map((run) => ({
294 ...run,
295 status: "completed" as const,
296 completedAt: later,
297 })),
298 };
299 expect(
300 resolveThreadWorkingStartedAt({
301 latestRun: deriveLatestThreadRun(stopped),
302 runtime: deriveThreadRuntime(stopped),
303 }),
304 ).toBeNull();
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-subagent"),
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 review",
340 startedAt: now,
341 completedAt: null,
342 updatedAt: now,
343 type: "subagent" as const,
344 subagentId: NodeId.make("subagent-review"),
345 origin: "provider_native" as const,
346 driver: ProviderDriverKind.make("codex"),
347 providerInstanceId: v2Projection.thread.providerInstanceId,
348 childThreadId: null,
349 prompt: "Review the changes",
350 result: null,
351 };
352
353 expect(
354 deriveThreadRuntime({
355 ...v2Projection,
356 runs: [run],
357 turnItems: [backgroundItem],
358 }),
359 ).toMatchObject({
360 status: "idle",
361 activeRunId: null,
362 });
363 expect(
364 deriveThreadRuntime({
365 ...v2Projection,
366 runs: [{ ...run, status: "running" as const }],
367 turnItems: [backgroundItem],
368 }),
369 ).toMatchObject({
370 status: "running",
371 activeRunId: runId,
372 });
373 expect(
374 deriveThreadRuntime({
375 ...v2Projection,
376 runs: [{ ...run, status: "failed" as const, completedAt: now }],
377 turnItems: [backgroundItem],
378 }),
379 ).toMatchObject({ status: "failed", activeRunId: null });
380 const commandItem = {
381 ...backgroundItem,
382 id: TurnItemId.make("item-background-command"),
383 type: "command_execution" as const,
384 input: "npm run dev",
385 };
386 expect(
387 deriveThreadRuntime({ ...v2Projection, runs: [run], turnItems: [commandItem] }),
388 ).toMatchObject({ status: "waiting", activeRunId: null });
389
390 for (const [turnItems, status] of [
391 [[commandItem], "completed"],
392 [[backgroundItem], "idle"],
393 [[commandItem, backgroundItem], "idle"],
394 ] as const) {
395 expect(
396 deriveThreadRuntime({
397 ...v2Projection,
398 runs: [{ ...run, status: "completed", completedAt: now }],
399 turnItems,
400 }),
401 ).toMatchObject({ status, activeRunId: null });
402 }
403
404 for (const held of [{ kind: "monitor", awaited: true }, { kind: "background_task" }] as const) {
405 const providerThread = {
406 id: ProviderThreadId.make("provider-thread-background"),
407 driver: ProviderDriverKind.make("claudeCode"),
408 providerInstanceId: v2Projection.thread.providerInstanceId,
409 providerSessionId: null,
410 appThreadId: v2Projection.thread.id,
411 ownerNodeId: null,
412 nativeThreadRef: null,
413 nativeConversationHeadRef: null,
414 status: "idle" as const,
415 firstRunOrdinal: 1,
416 lastRunOrdinal: 1,
417 handoffIds: [],
418 forkedFrom: null,
419 pendingBackgroundTasks: [{ taskId: "background-task", ...held }],
420 createdAt: now,
421 updatedAt: now,
422 };
423 for (const status of ["completed", "failed"] as const) {
424 expect(
425 deriveThreadRuntime({
426 ...v2Projection,
427 runs: [{ ...run, status, completedAt: now }],
428 providerThreads: [providerThread],
429 }),
430 ).toMatchObject({ status: status === "failed" ? "failed" : "idle", activeRunId: null });
431 }
432 }
433 });
434
435 it("joins pending request entities to their native turn-item display data", () => {
436 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
437 const requestId = RuntimeRequestId.make("request-approval");
438 const item = {
439 id: TurnItemId.make("item-approval"),
440 threadId: v2Projection.thread.id,
441 runId: null,
442 nodeId: NodeId.make("node-root"),
443 providerThreadId: null,
444 providerTurnId: null,
445 nativeItemRef: null,
446 parentItemId: null,
447 ordinal: 0,
448 status: "completed" as const,
449 title: null,
450 startedAt: now,
451 completedAt: now,
452 updatedAt: now,
453 type: "approval_request" as const,
454 requestId,
455 requestKind: "command" as const,
456 prompt: "Allow command?",
457 };
458 const projection = {
459 ...v2Projection,
460 runtimeRequests: [
461 {
462 id: requestId,
463 nodeId: NodeId.make("node-root"),
464 providerTurnId: null,
465 nativeRequestRef: null,
466 kind: "command" as const,
467 status: "pending" as const,
468 responseCapability: {
469 type: "not_resumable" as const,
470 reason: "provider disconnected",
471 },
472 createdAt: now,
473 resolvedAt: null,
474 },
475 ],
476 turnItems: [item],
477 updatedAt: now,
478 };
479
480 expect(derivePendingThreadRequests(projection).approvals).toEqual([
481 {
482 requestId,
483 requestKind: "command",
484 createdAt: "2026-06-20T01:00:00.000Z",
485 detail: "Allow command?",
486 responseCapability: "not_resumable",
487 },
488 ]);
489 expect(derivePendingThreadRequests(projection).userInputs).toEqual([]);
490 });
491
492 it("preserves structured-question selection mode and defaults legacy payloads", () => {
493 const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
494 const multiRequestId = RuntimeRequestId.make("request-multi-select");
495 const legacyRequestId = RuntimeRequestId.make("request-legacy-single-select");
496 const runtimeRequests = [multiRequestId, legacyRequestId].map((id) => ({
497 id,
498 nodeId: NodeId.make(`node-${id}`),
499 providerTurnId: null,
500 nativeRequestRef: null,
501 kind: "user_input" as const,
502 status: "pending" as const,
503 responseCapability: {
504 type: "live" as const,
505 providerSessionId: ProviderSessionId.make("provider-session-questions"),
506 },
507 createdAt: now,
508 resolvedAt: null,
509 }));
510 const common = {
511 threadId: v2Projection.thread.id,
512 runId: null,
513 providerThreadId: null,
514 providerTurnId: null,
515 nativeItemRef: null,
516 parentItemId: null,
517 ordinal: 0,
518 status: "completed" as const,
519 title: null,
520 startedAt: now,
521 completedAt: now,
522 updatedAt: now,
523 type: "user_input_request" as const,
524 };
525 const projection = {
526 ...v2Projection,
527 runtimeRequests,
528 turnItems: [
529 {
530 ...common,
531 id: TurnItemId.make("item-multi-select"),
532 nodeId: NodeId.make("node-request-multi-select"),
533 requestId: multiRequestId,
534 questions: [
535 {
536 id: "regions",
537 header: "Regions",
538 question: "Which regions?",
539 options: [
540 { label: "US", description: "United States" },
541 { label: "EU", description: "European Union" },
542 ],
543 multiSelect: true,
544 },
545 ],
546 },
547 {
548 ...common,
549 id: TurnItemId.make("item-legacy-single-select"),
550 nodeId: NodeId.make("node-request-legacy-single-select"),
551 requestId: legacyRequestId,
552 questions: [
553 {
554 id: "target",
555 header: "Target",
556 question: "Which target?",
557 options: [{ label: "Staging", description: "Staging environment" }],
558 },
559 ],
560 },
561 ],
562 updatedAt: now,
563 };
564
565 expect(
566 derivePendingThreadRequests(projection).userInputs.map((input) => ({
567 requestId: input.requestId,
568 multiSelect: input.questions[0]?.multiSelect,
569 })),
570 ).toEqual([
571 { requestId: multiRequestId, multiSelect: true },
572 { requestId: legacyRequestId, multiSelect: false },
573 ]);
574 });
575});