Open History to see the last commit
1import {
2 MessageId,
3 NodeId,
4 PlanId,
5 ProviderInstanceId,
6 ProviderThreadId,
7 RunAttemptId,
8 RunId,
9 ThreadId,
10 TurnItemId,
11 type OrchestrationV2ProjectedTurnItem,
12 type OrchestrationV2ExecutionNode,
13 type OrchestrationV2RunAttempt,
14 type OrchestrationV2TurnItem,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import { describe, expect, it } from "vite-plus/test";
18
19import {
20 deriveTimelineEntriesFromVisibleTurnItems,
21 deriveRevertTurnCountByUserMessageId,
22 findLatestProposedPlan,
23 isLatestRunSettled,
24 providerErrorPresentation,
25 type TimelineEntry,
26} from "./session-logic";
27import { makeThreadProjectionFixture } from "./test-fixtures";
28import type { ChatMessage } from "./types";
29
30describe("V2 session presentation", () => {
31 it("uses run status as the settlement boundary", () => {
32 const runId = RunId.make("run-1");
33 expect(
34 isLatestRunSettled(
35 {
36 runId,
37 status: "completed",
38 startedAt: "2026-06-20T00:00:00.000Z",
39 completedAt: "2026-06-20T00:01:00.000Z",
40 },
41 null,
42 ),
43 ).toBe(true);
44 expect(
45 isLatestRunSettled(
46 { runId, status: "running", startedAt: null, completedAt: null },
47 { status: "running", activeRunId: runId },
48 ),
49 ).toBe(false);
50 expect(
51 isLatestRunSettled(
52 { runId, status: "queued", startedAt: null, completedAt: null },
53 { status: "running", activeRunId: RunId.make("run-active") },
54 ),
55 ).toBe(false);
56 });
57
58 it("labels provider retry progress, delay, recovery, and exhaustion", () => {
59 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
60 const retryItem = {
61 id: TurnItemId.make("item-provider-retry"),
62 threadId: ThreadId.make("thread-provider-retry"),
63 runId: RunId.make("run-provider-retry"),
64 nodeId: null,
65 providerThreadId: null,
66 providerTurnId: null,
67 nativeItemRef: null,
68 parentItemId: null,
69 ordinal: 1,
70 status: "running" as const,
71 title: "Provider retry",
72 startedAt: now,
73 completedAt: null,
74 updatedAt: now,
75 type: "error" as const,
76 failure: {
77 class: "provider_error" as const,
78 message: "Claude API overloaded.",
79 code: "api_error_529",
80 retryable: true,
81 },
82 retry: {
83 attempt: 2,
84 maxAttempts: 10,
85 retryDelayMs: 1_500,
86 },
87 } satisfies Extract<OrchestrationV2TurnItem, { readonly type: "error" }>;
88
89 expect(providerErrorPresentation(retryItem)).toEqual({
90 label: "Retrying provider (2/10)",
91 detail: "Claude API overloaded. Retrying in 1.5s.",
92 });
93 expect(
94 providerErrorPresentation({
95 ...retryItem,
96 status: "completed",
97 completedAt: now,
98 }),
99 ).toMatchObject({ label: "Provider recovered (2/10 retries)" });
100 expect(
101 providerErrorPresentation({
102 ...retryItem,
103 status: "failed",
104 retry: { ...retryItem.retry, attempt: 10 },
105 completedAt: now,
106 }),
107 ).toMatchObject({ label: "Provider error after 10/10 retries" });
108 });
109
110 it("selects the latest proposed plan for a run", () => {
111 const runId = RunId.make("run-1");
112 const planId = PlanId.make("plan-1");
113 const nodeId = NodeId.make("node-plan");
114 const now = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");
115 const baseProjection = makeThreadProjectionFixture();
116 const plan = findLatestProposedPlan(
117 {
118 ...baseProjection,
119 plans: [
120 {
121 id: planId,
122 threadId: baseProjection.thread.id,
123 nodeId,
124 kind: "proposed_plan" as const,
125 markdown: "Plan",
126 status: "active" as const,
127 runId,
128 },
129 ],
130 turnItems: [
131 {
132 id: TurnItemId.make("item-plan"),
133 threadId: baseProjection.thread.id,
134 nodeId,
135 providerThreadId: null,
136 providerTurnId: null,
137 nativeItemRef: null,
138 parentItemId: null,
139 ordinal: 0,
140 status: "completed" as const,
141 title: null,
142 startedAt: now,
143 completedAt: now,
144 updatedAt: now,
145 type: "proposed_plan" as const,
146 planId,
147 markdown: "Plan",
148 streaming: false,
149 runId,
150 },
151 ],
152 updatedAt: now,
153 },
154 runId,
155 );
156 expect(plan?.planMarkdown).toBe("Plan");
157 });
158
159 it("assigns run rollback to the turn-start message instead of a later steer", () => {
160 const runId = RunId.make("run-steered");
161 const turnStartMessageId = MessageId.make("message-turn-start");
162 const steerMessageId = MessageId.make("message-steer");
163 const assistantMessageId = MessageId.make("message-assistant");
164 const messages: ChatMessage[] = [
165 {
166 id: turnStartMessageId,
167 role: "user",
168 text: "Start",
169 runId,
170 inputIntent: "turn_start",
171 streaming: false,
172 createdAt: "2026-06-20T00:00:00.000Z",
173 updatedAt: "2026-06-20T00:00:00.000Z",
174 },
175 {
176 id: steerMessageId,
177 role: "user",
178 text: "Steer",
179 runId,
180 inputIntent: "steer",
181 streaming: false,
182 createdAt: "2026-06-20T00:00:01.000Z",
183 updatedAt: "2026-06-20T00:00:01.000Z",
184 },
185 {
186 id: assistantMessageId,
187 role: "assistant",
188 text: "Done",
189 runId,
190 streaming: false,
191 createdAt: "2026-06-20T00:00:02.000Z",
192 updatedAt: "2026-06-20T00:00:02.000Z",
193 },
194 ];
195 const timelineEntries: TimelineEntry[] = messages.map(
196 (message): TimelineEntry => ({
197 id: message.id,
198 kind: "message",
199 createdAt: message.createdAt,
200 message,
201 }),
202 );
203
204 const targets = deriveRevertTurnCountByUserMessageId({
205 timelineEntries,
206 checkpoints: [
207 {
208 runId,
209 checkpointTurnCount: 1,
210 checkpointRef: "checkpoint-run-1" as never,
211 status: "ready",
212 files: [],
213 assistantMessageId,
214 completedAt: "2026-06-20T00:00:03.000Z",
215 },
216 ],
217 });
218
219 expect([...targets]).toEqual([[turnStartMessageId, 0]]);
220 expect(targets.has(steerMessageId)).toBe(false);
221 });
222
223 it("uses visible turn item order and keeps lifecycle resource entries standalone", () => {
224 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
225 const threadId = ThreadId.make("thread-visible");
226 const runId = RunId.make("run-visible");
227 const base = (id: string, ordinal: number) => ({
228 id: TurnItemId.make(id),
229 threadId,
230 runId,
231 nodeId: null,
232 providerThreadId: null,
233 providerTurnId: null,
234 nativeItemRef: null,
235 parentItemId: null,
236 ordinal,
237 status: "completed" as const,
238 title: null,
239 startedAt: now,
240 completedAt: now,
241 updatedAt: now,
242 });
243 const userItem = {
244 ...base("item-user", 0),
245 type: "user_message" as const,
246 messageId: MessageId.make("message-user"),
247 inputIntent: "turn_start" as const,
248 text: "Start",
249 attachments: [],
250 createdBy: "user" as const,
251 creationSource: "web" as const,
252 } satisfies OrchestrationV2TurnItem;
253 const requestItem = {
254 ...base("item-interrupt-request", 1),
255 type: "run_interrupt_request" as const,
256 message: "Stopping",
257 } satisfies OrchestrationV2TurnItem;
258 const commandItem = {
259 ...base("item-command", 2),
260 type: "command_execution" as const,
261 input: "sleep 1",
262 output: "done",
263 exitCode: 0,
264 } satisfies OrchestrationV2TurnItem;
265 const resultItem = {
266 ...base("item-interrupt-result", 3),
267 type: "run_interrupt_result" as const,
268 message: "Stopped",
269 } satisfies OrchestrationV2TurnItem;
270 const todoItem = {
271 ...base("item-todo", 4),
272 type: "todo_list" as const,
273 planId: PlanId.make("plan-visible"),
274 explanation: "Keep task detail in the Tasks panel",
275 steps: [
276 { id: "step-1", text: "First", status: "completed" as const },
277 { id: "step-2", text: "Second", status: "pending" as const },
278 ],
279 } satisfies OrchestrationV2TurnItem;
280 const errorItem = {
281 ...base("item-error", 5),
282 status: "failed" as const,
283 type: "error" as const,
284 failure: {
285 class: "validation_error" as const,
286 message: "Invalid reasoning effort.",
287 code: "invalid_request",
288 retryable: false,
289 },
290 } satisfies OrchestrationV2TurnItem;
291 const threadCreatedItem = {
292 ...base("item-thread-created", 6),
293 type: "thread_created" as const,
294 title: "Follow-up thread",
295 targetThreadId: ThreadId.make("thread-follow-up"),
296 targetRunId: RunId.make("run-follow-up"),
297 targetProviderInstanceId: ProviderInstanceId.make("claude-default"),
298 targetModel: "claude-sonnet-4-6",
299 } satisfies OrchestrationV2TurnItem;
300 const workspacePreparationItem = {
301 ...base("item-workspace-preparation", 7),
302 type: "command_execution" as const,
303 title: "Workspace ready",
304 input: "Preparing workspace",
305 output: "Workspace preparation completed.",
306 exitCode: 0,
307 } satisfies OrchestrationV2TurnItem;
308 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
309 userItem,
310 requestItem,
311 commandItem,
312 resultItem,
313 todoItem,
314 errorItem,
315 threadCreatedItem,
316 workspacePreparationItem,
317 ].map((item, position) => ({
318 position,
319 visibility: "local" as const,
320 sourceThreadId: threadId,
321 sourceItemId: item.id,
322 item,
323 }));
324
325 const entries = deriveTimelineEntriesFromVisibleTurnItems({
326 visibleTurnItems,
327 optimisticMessages: [],
328 });
329
330 expect(entries.map((entry) => [entry.kind, entry.id])).toEqual([
331 ["message", userItem.messageId],
332 ["event", requestItem.id],
333 ["work", commandItem.id],
334 ["event", resultItem.id],
335 ["work", todoItem.id],
336 ["event", errorItem.id],
337 ["event", threadCreatedItem.id],
338 ]);
339 const commandEntry = entries[2];
340 const userEntry = entries[0];
341 expect(userEntry?.kind).toBe("message");
342 if (userEntry?.kind === "message") {
343 expect(userEntry.projectedItem).toBe(visibleTurnItems[0]);
344 expect(userEntry.message.inputIntent).toBe("turn_start");
345 expect(userEntry.message.createdBy).toBe("user");
346 expect(userEntry.message.creationSource).toBe("web");
347 }
348 expect(commandEntry?.kind).toBe("work");
349 if (commandEntry?.kind === "work") {
350 expect(commandEntry.entry.projectedItem).toBe(visibleTurnItems[2]);
351 expect(commandEntry.entry.structuredPayload).toBe(commandItem);
352 }
353 const todoEntry = entries[4];
354 expect(todoEntry?.kind).toBe("work");
355 if (todoEntry?.kind === "work") {
356 expect(todoEntry.entry.label).toBe("Updated tasks");
357 expect(todoEntry.entry.detail).toBe("1/2 completed");
358 }
359 const errorEntry = entries[5];
360 expect(errorEntry?.kind).toBe("event");
361 if (errorEntry?.kind === "event") {
362 expect(errorEntry.projectedItem).toBe(visibleTurnItems[5]);
363 expect(errorEntry.projectedItem.item.type).toBe("error");
364 if (errorEntry.projectedItem.item.type === "error") {
365 expect(errorEntry.projectedItem.item.failure.message).toBe("Invalid reasoning effort.");
366 }
367 }
368 const threadCreatedEntry = entries[6];
369 expect(threadCreatedEntry?.kind).toBe("event");
370 if (threadCreatedEntry?.kind === "event") {
371 expect(threadCreatedEntry.projectedItem.item.type).toBe("thread_created");
372 }
373 });
374
375 it("waits for a dispatched turn item before adding queued input to the timeline", () => {
376 const projection = makeThreadProjectionFixture();
377 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
378 const runId = RunId.make("run-dispatched-queued");
379 const messageId = MessageId.make("message-dispatched-queued");
380 const optimisticMessage = {
381 id: messageId,
382 role: "user" as const,
383 text: "Queued input",
384 runId: null,
385 inputIntent: "queued_turn" as const,
386 streaming: false,
387 createdAt: DateTime.formatIso(now),
388 updatedAt: DateTime.formatIso(now),
389 };
390
391 expect(
392 deriveTimelineEntriesFromVisibleTurnItems({
393 visibleTurnItems: [],
394 optimisticMessages: [optimisticMessage],
395 }),
396 ).toEqual([]);
397
398 const dispatchedItem = {
399 id: TurnItemId.make("item-dispatched-queued"),
400 threadId: projection.thread.id,
401 runId,
402 nodeId: null,
403 providerThreadId: null,
404 providerTurnId: null,
405 nativeItemRef: null,
406 parentItemId: null,
407 ordinal: 200,
408 status: "completed" as const,
409 title: null,
410 startedAt: now,
411 completedAt: now,
412 updatedAt: now,
413 type: "user_message" as const,
414 messageId,
415 inputIntent: "turn_start" as const,
416 text: "Queued input",
417 attachments: [],
418 createdBy: "user" as const,
419 creationSource: "web" as const,
420 } satisfies OrchestrationV2TurnItem;
421 const promotedEntries = deriveTimelineEntriesFromVisibleTurnItems({
422 visibleTurnItems: [
423 {
424 position: 0,
425 visibility: "local",
426 sourceThreadId: projection.thread.id,
427 sourceItemId: dispatchedItem.id,
428 item: dispatchedItem,
429 },
430 ],
431 optimisticMessages: [optimisticMessage],
432 });
433 expect(promotedEntries.map((entry) => entry.id)).toEqual([messageId]);
434 expect(promotedEntries[0]?.kind).toBe("message");
435 if (promotedEntries[0]?.kind === "message") {
436 expect(promotedEntries[0].message.inputIntent).toBe("turn_start");
437 }
438 });
439
440 it("uses projected plan status and file contents in timeline entries", () => {
441 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
442 const threadId = ThreadId.make("thread-timeline-artifacts");
443 const runId = RunId.make("run-timeline-artifacts");
444 const nodeId = NodeId.make("node-timeline-artifacts");
445 const planId = PlanId.make("plan-timeline-artifacts");
446 const base = {
447 threadId,
448 runId,
449 nodeId,
450 providerThreadId: null,
451 providerTurnId: null,
452 nativeItemRef: null,
453 parentItemId: null,
454 status: "completed" as const,
455 title: null,
456 startedAt: now,
457 completedAt: now,
458 updatedAt: now,
459 };
460 const planItem = {
461 ...base,
462 id: TurnItemId.make("item-proposed-plan"),
463 ordinal: 0,
464 type: "proposed_plan" as const,
465 planId,
466 markdown: "Finished plan",
467 streaming: false,
468 } satisfies OrchestrationV2TurnItem;
469 const fileItem = {
470 ...base,
471 id: TurnItemId.make("item-file-change"),
472 ordinal: 1,
473 type: "file_change" as const,
474 fileName: "src/example.ts",
475 newStr: "export const answer = 42;\n",
476 } satisfies OrchestrationV2TurnItem;
477 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
478 planItem,
479 fileItem,
480 ].map((item, position) => ({
481 position,
482 visibility: "local",
483 sourceThreadId: threadId,
484 sourceItemId: item.id,
485 item,
486 }));
487
488 const entries = deriveTimelineEntriesFromVisibleTurnItems({
489 visibleTurnItems,
490 optimisticMessages: [],
491 plans: [
492 {
493 id: planId,
494 threadId,
495 runId,
496 nodeId,
497 kind: "proposed_plan",
498 markdown: planItem.markdown,
499 status: "completed",
500 },
501 ],
502 });
503
504 expect(entries[0]?.kind).toBe("proposed-plan");
505 if (entries[0]?.kind === "proposed-plan") {
506 expect(entries[0].proposedPlan.status).toBe("completed");
507 }
508 expect(entries[1]?.kind).toBe("work");
509 if (entries[1]?.kind === "work") {
510 expect(entries[1].entry.detail).toBe(fileItem.newStr);
511 }
512 });
513
514 it("resolves attempt identity through V2 execution nodes", () => {
515 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
516 const threadId = ThreadId.make("thread-attempts");
517 const runId = RunId.make("run-steered");
518 const supersededRootNodeId = NodeId.make("node-attempt-1-root");
519 const supersededChildNodeId = NodeId.make("node-attempt-1-child");
520 const activeRootNodeId = NodeId.make("node-attempt-2-root");
521 const supersededAttemptId = RunAttemptId.make("attempt-1");
522 const activeAttemptId = RunAttemptId.make("attempt-2");
523 const providerInstanceId = ProviderInstanceId.make("codex-default");
524 const providerThreadId = ProviderThreadId.make("provider-thread-attempts");
525 const attempts: ReadonlyArray<OrchestrationV2RunAttempt> = [
526 {
527 id: supersededAttemptId,
528 runId,
529 attemptOrdinal: 1,
530 rootNodeId: supersededRootNodeId,
531 providerInstanceId,
532 providerThreadId,
533 providerTurnId: null,
534 reason: "initial",
535 status: "superseded",
536 startedAt: now,
537 completedAt: now,
538 },
539 {
540 id: activeAttemptId,
541 runId,
542 attemptOrdinal: 2,
543 rootNodeId: activeRootNodeId,
544 providerInstanceId,
545 providerThreadId,
546 providerTurnId: null,
547 reason: "steering_restart",
548 status: "running",
549 startedAt: now,
550 completedAt: null,
551 },
552 ];
553 const node = (
554 id: OrchestrationV2ExecutionNode["id"],
555 rootNodeId: OrchestrationV2ExecutionNode["rootNodeId"],
556 parentNodeId: OrchestrationV2ExecutionNode["parentNodeId"],
557 ): OrchestrationV2ExecutionNode => ({
558 id,
559 threadId,
560 runId,
561 parentNodeId,
562 rootNodeId,
563 kind: id === rootNodeId ? "root_turn" : "assistant_message",
564 status: "running",
565 countsForRun: true,
566 providerThreadId,
567 providerTurnId: null,
568 nativeItemRef: null,
569 runtimeRequestId: null,
570 checkpointScopeId: null,
571 startedAt: now,
572 completedAt: null,
573 });
574 const nodes = [
575 node(supersededRootNodeId, supersededRootNodeId, null),
576 node(supersededChildNodeId, supersededRootNodeId, supersededRootNodeId),
577 node(activeRootNodeId, activeRootNodeId, null),
578 ];
579 const assistantItem = (
580 id: string,
581 messageId: string,
582 nodeId: NodeId,
583 text: string,
584 ordinal: number,
585 ): OrchestrationV2TurnItem => ({
586 id: TurnItemId.make(id),
587 threadId,
588 runId,
589 nodeId,
590 providerThreadId,
591 providerTurnId: null,
592 nativeItemRef: null,
593 parentItemId: null,
594 ordinal,
595 status: "running",
596 title: null,
597 startedAt: now,
598 completedAt: null,
599 updatedAt: now,
600 type: "assistant_message",
601 messageId: MessageId.make(messageId),
602 text,
603 streaming: true,
604 });
605 const items = [
606 assistantItem(
607 "item-superseded",
608 "message-superseded",
609 supersededChildNodeId,
610 "Partial old response",
611 0,
612 ),
613 assistantItem("item-active", "message-active", activeRootNodeId, "Current response", 1),
614 ];
615 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = items.map(
616 (item, position) => ({
617 position,
618 visibility: "local",
619 sourceThreadId: threadId,
620 sourceItemId: item.id,
621 item,
622 }),
623 );
624
625 const entries = deriveTimelineEntriesFromVisibleTurnItems({
626 visibleTurnItems,
627 optimisticMessages: [],
628 attempts,
629 nodes,
630 });
631
632 expect(entries.map((entry) => [entry.attempt?.id, entry.attempt?.status])).toEqual([
633 [supersededAttemptId, "superseded"],
634 [activeAttemptId, "running"],
635 ]);
636 });
637});