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

session-logic.test.ts

628 lines19.0 KB

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 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
301 userItem,
302 requestItem,
303 commandItem,
304 resultItem,
305 todoItem,
306 errorItem,
307 threadCreatedItem,
308 ].map((item, position) => ({
309 position,
310 visibility: "local" as const,
311 sourceThreadId: threadId,
312 sourceItemId: item.id,
313 item,
314 }));
315​
316 const entries = deriveTimelineEntriesFromVisibleTurnItems({
317 visibleTurnItems,
318 optimisticMessages: [],
319 });
320​
321 expect(entries.map((entry) => [entry.kind, entry.id])).toEqual([
322 ["message", userItem.messageId],
323 ["event", requestItem.id],
324 ["work", commandItem.id],
325 ["event", resultItem.id],
326 ["work", todoItem.id],
327 ["event", errorItem.id],
328 ["event", threadCreatedItem.id],
329 ]);
330 const commandEntry = entries[2];
331 const userEntry = entries[0];
332 expect(userEntry?.kind).toBe("message");
333 if (userEntry?.kind === "message") {
334 expect(userEntry.projectedItem).toBe(visibleTurnItems[0]);
335 expect(userEntry.message.inputIntent).toBe("turn_start");
336 expect(userEntry.message.createdBy).toBe("user");
337 expect(userEntry.message.creationSource).toBe("web");
338 }
339 expect(commandEntry?.kind).toBe("work");
340 if (commandEntry?.kind === "work") {
341 expect(commandEntry.entry.projectedItem).toBe(visibleTurnItems[2]);
342 expect(commandEntry.entry.structuredPayload).toBe(commandItem);
343 }
344 const todoEntry = entries[4];
345 expect(todoEntry?.kind).toBe("work");
346 if (todoEntry?.kind === "work") {
347 expect(todoEntry.entry.label).toBe("Updated tasks");
348 expect(todoEntry.entry.detail).toBe("1/2 completed");
349 }
350 const errorEntry = entries[5];
351 expect(errorEntry?.kind).toBe("event");
352 if (errorEntry?.kind === "event") {
353 expect(errorEntry.projectedItem).toBe(visibleTurnItems[5]);
354 expect(errorEntry.projectedItem.item.type).toBe("error");
355 if (errorEntry.projectedItem.item.type === "error") {
356 expect(errorEntry.projectedItem.item.failure.message).toBe("Invalid reasoning effort.");
357 }
358 }
359 const threadCreatedEntry = entries[6];
360 expect(threadCreatedEntry?.kind).toBe("event");
361 if (threadCreatedEntry?.kind === "event") {
362 expect(threadCreatedEntry.projectedItem.item.type).toBe("thread_created");
363 }
364 });
365​
366 it("waits for a dispatched turn item before adding queued input to the timeline", () => {
367 const projection = makeThreadProjectionFixture();
368 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
369 const runId = RunId.make("run-dispatched-queued");
370 const messageId = MessageId.make("message-dispatched-queued");
371 const optimisticMessage = {
372 id: messageId,
373 role: "user" as const,
374 text: "Queued input",
375 runId: null,
376 inputIntent: "queued_turn" as const,
377 streaming: false,
378 createdAt: DateTime.formatIso(now),
379 updatedAt: DateTime.formatIso(now),
380 };
381​
382 expect(
383 deriveTimelineEntriesFromVisibleTurnItems({
384 visibleTurnItems: [],
385 optimisticMessages: [optimisticMessage],
386 }),
387 ).toEqual([]);
388​
389 const dispatchedItem = {
390 id: TurnItemId.make("item-dispatched-queued"),
391 threadId: projection.thread.id,
392 runId,
393 nodeId: null,
394 providerThreadId: null,
395 providerTurnId: null,
396 nativeItemRef: null,
397 parentItemId: null,
398 ordinal: 200,
399 status: "completed" as const,
400 title: null,
401 startedAt: now,
402 completedAt: now,
403 updatedAt: now,
404 type: "user_message" as const,
405 messageId,
406 inputIntent: "turn_start" as const,
407 text: "Queued input",
408 attachments: [],
409 createdBy: "user" as const,
410 creationSource: "web" as const,
411 } satisfies OrchestrationV2TurnItem;
412 const promotedEntries = deriveTimelineEntriesFromVisibleTurnItems({
413 visibleTurnItems: [
414 {
415 position: 0,
416 visibility: "local",
417 sourceThreadId: projection.thread.id,
418 sourceItemId: dispatchedItem.id,
419 item: dispatchedItem,
420 },
421 ],
422 optimisticMessages: [optimisticMessage],
423 });
424 expect(promotedEntries.map((entry) => entry.id)).toEqual([messageId]);
425 expect(promotedEntries[0]?.kind).toBe("message");
426 if (promotedEntries[0]?.kind === "message") {
427 expect(promotedEntries[0].message.inputIntent).toBe("turn_start");
428 }
429 });
430​
431 it("uses projected plan status and file contents in timeline entries", () => {
432 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
433 const threadId = ThreadId.make("thread-timeline-artifacts");
434 const runId = RunId.make("run-timeline-artifacts");
435 const nodeId = NodeId.make("node-timeline-artifacts");
436 const planId = PlanId.make("plan-timeline-artifacts");
437 const base = {
438 threadId,
439 runId,
440 nodeId,
441 providerThreadId: null,
442 providerTurnId: null,
443 nativeItemRef: null,
444 parentItemId: null,
445 status: "completed" as const,
446 title: null,
447 startedAt: now,
448 completedAt: now,
449 updatedAt: now,
450 };
451 const planItem = {
452 ...base,
453 id: TurnItemId.make("item-proposed-plan"),
454 ordinal: 0,
455 type: "proposed_plan" as const,
456 planId,
457 markdown: "Finished plan",
458 streaming: false,
459 } satisfies OrchestrationV2TurnItem;
460 const fileItem = {
461 ...base,
462 id: TurnItemId.make("item-file-change"),
463 ordinal: 1,
464 type: "file_change" as const,
465 fileName: "src/example.ts",
466 newStr: "export const answer = 42;\n",
467 } satisfies OrchestrationV2TurnItem;
468 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
469 planItem,
470 fileItem,
471 ].map((item, position) => ({
472 position,
473 visibility: "local",
474 sourceThreadId: threadId,
475 sourceItemId: item.id,
476 item,
477 }));
478​
479 const entries = deriveTimelineEntriesFromVisibleTurnItems({
480 visibleTurnItems,
481 optimisticMessages: [],
482 plans: [
483 {
484 id: planId,
485 threadId,
486 runId,
487 nodeId,
488 kind: "proposed_plan",
489 markdown: planItem.markdown,
490 status: "completed",
491 },
492 ],
493 });
494​
495 expect(entries[0]?.kind).toBe("proposed-plan");
496 if (entries[0]?.kind === "proposed-plan") {
497 expect(entries[0].proposedPlan.status).toBe("completed");
498 }
499 expect(entries[1]?.kind).toBe("work");
500 if (entries[1]?.kind === "work") {
501 expect(entries[1].entry.detail).toBe(fileItem.newStr);
502 }
503 });
504​
505 it("resolves attempt identity through V2 execution nodes", () => {
506 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
507 const threadId = ThreadId.make("thread-attempts");
508 const runId = RunId.make("run-steered");
509 const supersededRootNodeId = NodeId.make("node-attempt-1-root");
510 const supersededChildNodeId = NodeId.make("node-attempt-1-child");
511 const activeRootNodeId = NodeId.make("node-attempt-2-root");
512 const supersededAttemptId = RunAttemptId.make("attempt-1");
513 const activeAttemptId = RunAttemptId.make("attempt-2");
514 const providerInstanceId = ProviderInstanceId.make("codex-default");
515 const providerThreadId = ProviderThreadId.make("provider-thread-attempts");
516 const attempts: ReadonlyArray<OrchestrationV2RunAttempt> = [
517 {
518 id: supersededAttemptId,
519 runId,
520 attemptOrdinal: 1,
521 rootNodeId: supersededRootNodeId,
522 providerInstanceId,
523 providerThreadId,
524 providerTurnId: null,
525 reason: "initial",
526 status: "superseded",
527 startedAt: now,
528 completedAt: now,
529 },
530 {
531 id: activeAttemptId,
532 runId,
533 attemptOrdinal: 2,
534 rootNodeId: activeRootNodeId,
535 providerInstanceId,
536 providerThreadId,
537 providerTurnId: null,
538 reason: "steering_restart",
539 status: "running",
540 startedAt: now,
541 completedAt: null,
542 },
543 ];
544 const node = (
545 id: OrchestrationV2ExecutionNode["id"],
546 rootNodeId: OrchestrationV2ExecutionNode["rootNodeId"],
547 parentNodeId: OrchestrationV2ExecutionNode["parentNodeId"],
548 ): OrchestrationV2ExecutionNode => ({
549 id,
550 threadId,
551 runId,
552 parentNodeId,
553 rootNodeId,
554 kind: id === rootNodeId ? "root_turn" : "assistant_message",
555 status: "running",
556 countsForRun: true,
557 providerThreadId,
558 providerTurnId: null,
559 nativeItemRef: null,
560 runtimeRequestId: null,
561 checkpointScopeId: null,
562 startedAt: now,
563 completedAt: null,
564 });
565 const nodes = [
566 node(supersededRootNodeId, supersededRootNodeId, null),
567 node(supersededChildNodeId, supersededRootNodeId, supersededRootNodeId),
568 node(activeRootNodeId, activeRootNodeId, null),
569 ];
570 const assistantItem = (
571 id: string,
572 messageId: string,
573 nodeId: NodeId,
574 text: string,
575 ordinal: number,
576 ): OrchestrationV2TurnItem => ({
577 id: TurnItemId.make(id),
578 threadId,
579 runId,
580 nodeId,
581 providerThreadId,
582 providerTurnId: null,
583 nativeItemRef: null,
584 parentItemId: null,
585 ordinal,
586 status: "running",
587 title: null,
588 startedAt: now,
589 completedAt: null,
590 updatedAt: now,
591 type: "assistant_message",
592 messageId: MessageId.make(messageId),
593 text,
594 streaming: true,
595 });
596 const items = [
597 assistantItem(
598 "item-superseded",
599 "message-superseded",
600 supersededChildNodeId,
601 "Partial old response",
602 0,
603 ),
604 assistantItem("item-active", "message-active", activeRootNodeId, "Current response", 1),
605 ];
606 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = items.map(
607 (item, position) => ({
608 position,
609 visibility: "local",
610 sourceThreadId: threadId,
611 sourceItemId: item.id,
612 item,
613 }),
614 );
615​
616 const entries = deriveTimelineEntriesFromVisibleTurnItems({
617 visibleTurnItems,
618 optimisticMessages: [],
619 attempts,
620 nodes,
621 });
622​
623 expect(entries.map((entry) => [entry.attempt?.id, entry.attempt?.status])).toEqual([
624 [supersededAttemptId, "superseded"],
625 [activeAttemptId, "running"],
626 ]);
627 });
628});