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