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

session-logic.test.ts

430 lines13.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 type TimelineEntry,
25} from "./session-logic";
26import { makeThreadProjectionFixture } from "./test-fixtures";
27import type { ChatMessage } from "./types";
28​
29describe("V2 session presentation", () => {
30 it("uses run status as the settlement boundary", () => {
31 const runId = RunId.make("run-1");
32 expect(
33 isLatestRunSettled(
34 {
35 runId,
36 status: "completed",
37 startedAt: "2026-06-20T00:00:00.000Z",
38 completedAt: "2026-06-20T00:01:00.000Z",
39 },
40 null,
41 ),
42 ).toBe(true);
43 expect(
44 isLatestRunSettled(
45 { runId, status: "running", startedAt: null, completedAt: null },
46 { status: "running", activeRunId: runId },
47 ),
48 ).toBe(false);
49 });
50​
51 it("selects the latest proposed plan for a run", () => {
52 const runId = RunId.make("run-1");
53 const planId = PlanId.make("plan-1");
54 const nodeId = NodeId.make("node-plan");
55 const now = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");
56 const baseProjection = makeThreadProjectionFixture();
57 const plan = findLatestProposedPlan(
58 {
59 ...baseProjection,
60 plans: [
61 {
62 id: planId,
63 threadId: baseProjection.thread.id,
64 nodeId,
65 kind: "proposed_plan" as const,
66 markdown: "Plan",
67 status: "active" as const,
68 runId,
69 },
70 ],
71 turnItems: [
72 {
73 id: TurnItemId.make("item-plan"),
74 threadId: baseProjection.thread.id,
75 nodeId,
76 providerThreadId: null,
77 providerTurnId: null,
78 nativeItemRef: null,
79 parentItemId: null,
80 ordinal: 0,
81 status: "completed" as const,
82 title: null,
83 startedAt: now,
84 completedAt: now,
85 updatedAt: now,
86 type: "proposed_plan" as const,
87 planId,
88 markdown: "Plan",
89 streaming: false,
90 runId,
91 },
92 ],
93 updatedAt: now,
94 },
95 runId,
96 );
97 expect(plan?.planMarkdown).toBe("Plan");
98 });
99​
100 it("assigns run rollback to the turn-start message instead of a later steer", () => {
101 const runId = RunId.make("run-steered");
102 const turnStartMessageId = MessageId.make("message-turn-start");
103 const steerMessageId = MessageId.make("message-steer");
104 const assistantMessageId = MessageId.make("message-assistant");
105 const messages: ChatMessage[] = [
106 {
107 id: turnStartMessageId,
108 role: "user",
109 text: "Start",
110 runId,
111 inputIntent: "turn_start",
112 streaming: false,
113 createdAt: "2026-06-20T00:00:00.000Z",
114 updatedAt: "2026-06-20T00:00:00.000Z",
115 },
116 {
117 id: steerMessageId,
118 role: "user",
119 text: "Steer",
120 runId,
121 inputIntent: "steer",
122 streaming: false,
123 createdAt: "2026-06-20T00:00:01.000Z",
124 updatedAt: "2026-06-20T00:00:01.000Z",
125 },
126 {
127 id: assistantMessageId,
128 role: "assistant",
129 text: "Done",
130 runId,
131 streaming: false,
132 createdAt: "2026-06-20T00:00:02.000Z",
133 updatedAt: "2026-06-20T00:00:02.000Z",
134 },
135 ];
136 const timelineEntries: TimelineEntry[] = messages.map(
137 (message): TimelineEntry => ({
138 id: message.id,
139 kind: "message",
140 createdAt: message.createdAt,
141 message,
142 }),
143 );
144​
145 const targets = deriveRevertTurnCountByUserMessageId({
146 timelineEntries,
147 checkpoints: [
148 {
149 runId,
150 checkpointTurnCount: 1,
151 checkpointRef: "checkpoint-run-1" as never,
152 status: "ready",
153 files: [],
154 assistantMessageId,
155 completedAt: "2026-06-20T00:00:03.000Z",
156 },
157 ],
158 });
159​
160 expect([...targets]).toEqual([[turnStartMessageId, 0]]);
161 expect(targets.has(steerMessageId)).toBe(false);
162 });
163​
164 it("uses visible turn item order and keeps lifecycle resource entries standalone", () => {
165 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
166 const threadId = ThreadId.make("thread-visible");
167 const runId = RunId.make("run-visible");
168 const base = (id: string, ordinal: number) => ({
169 id: TurnItemId.make(id),
170 threadId,
171 runId,
172 nodeId: null,
173 providerThreadId: null,
174 providerTurnId: null,
175 nativeItemRef: null,
176 parentItemId: null,
177 ordinal,
178 status: "completed" as const,
179 title: null,
180 startedAt: now,
181 completedAt: now,
182 updatedAt: now,
183 });
184 const userItem = {
185 ...base("item-user", 0),
186 type: "user_message" as const,
187 messageId: MessageId.make("message-user"),
188 inputIntent: "turn_start" as const,
189 text: "Start",
190 attachments: [],
191 createdBy: "user" as const,
192 creationSource: "web" as const,
193 } satisfies OrchestrationV2TurnItem;
194 const requestItem = {
195 ...base("item-interrupt-request", 1),
196 type: "run_interrupt_request" as const,
197 message: "Stopping",
198 } satisfies OrchestrationV2TurnItem;
199 const commandItem = {
200 ...base("item-command", 2),
201 type: "command_execution" as const,
202 input: "sleep 1",
203 output: "done",
204 exitCode: 0,
205 } satisfies OrchestrationV2TurnItem;
206 const resultItem = {
207 ...base("item-interrupt-result", 3),
208 type: "run_interrupt_result" as const,
209 message: "Stopped",
210 } satisfies OrchestrationV2TurnItem;
211 const todoItem = {
212 ...base("item-todo", 4),
213 type: "todo_list" as const,
214 planId: PlanId.make("plan-visible"),
215 explanation: "Keep task detail in the Tasks panel",
216 steps: [
217 { id: "step-1", text: "First", status: "completed" as const },
218 { id: "step-2", text: "Second", status: "pending" as const },
219 ],
220 } satisfies OrchestrationV2TurnItem;
221 const errorItem = {
222 ...base("item-error", 5),
223 status: "failed" as const,
224 type: "error" as const,
225 failure: {
226 class: "validation_error" as const,
227 message: "Invalid reasoning effort.",
228 code: "invalid_request",
229 retryable: false,
230 },
231 } satisfies OrchestrationV2TurnItem;
232 const threadCreatedItem = {
233 ...base("item-thread-created", 6),
234 type: "thread_created" as const,
235 title: "Follow-up thread",
236 targetThreadId: ThreadId.make("thread-follow-up"),
237 targetRunId: RunId.make("run-follow-up"),
238 targetProviderInstanceId: ProviderInstanceId.make("claude-default"),
239 targetModel: "claude-sonnet-4-6",
240 } satisfies OrchestrationV2TurnItem;
241 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
242 userItem,
243 requestItem,
244 commandItem,
245 resultItem,
246 todoItem,
247 errorItem,
248 threadCreatedItem,
249 ].map((item, position) => ({
250 position,
251 visibility: "local" as const,
252 sourceThreadId: threadId,
253 sourceItemId: item.id,
254 item,
255 }));
256​
257 const entries = deriveTimelineEntriesFromVisibleTurnItems({
258 visibleTurnItems,
259 optimisticMessages: [],
260 });
261​
262 expect(entries.map((entry) => [entry.kind, entry.id])).toEqual([
263 ["message", userItem.messageId],
264 ["event", requestItem.id],
265 ["work", commandItem.id],
266 ["event", resultItem.id],
267 ["work", todoItem.id],
268 ["event", errorItem.id],
269 ["event", threadCreatedItem.id],
270 ]);
271 const commandEntry = entries[2];
272 const userEntry = entries[0];
273 expect(userEntry?.kind).toBe("message");
274 if (userEntry?.kind === "message") {
275 expect(userEntry.projectedItem).toBe(visibleTurnItems[0]);
276 expect(userEntry.message.inputIntent).toBe("turn_start");
277 expect(userEntry.message.createdBy).toBe("user");
278 expect(userEntry.message.creationSource).toBe("web");
279 }
280 expect(commandEntry?.kind).toBe("work");
281 if (commandEntry?.kind === "work") {
282 expect(commandEntry.entry.projectedItem).toBe(visibleTurnItems[2]);
283 expect(commandEntry.entry.structuredPayload).toBe(commandItem);
284 }
285 const todoEntry = entries[4];
286 expect(todoEntry?.kind).toBe("work");
287 if (todoEntry?.kind === "work") {
288 expect(todoEntry.entry.label).toBe("Updated tasks");
289 expect(todoEntry.entry.detail).toBe("1/2 completed");
290 }
291 const errorEntry = entries[5];
292 expect(errorEntry?.kind).toBe("event");
293 if (errorEntry?.kind === "event") {
294 expect(errorEntry.projectedItem).toBe(visibleTurnItems[5]);
295 expect(errorEntry.projectedItem.item.type).toBe("error");
296 if (errorEntry.projectedItem.item.type === "error") {
297 expect(errorEntry.projectedItem.item.failure.message).toBe("Invalid reasoning effort.");
298 }
299 }
300 const threadCreatedEntry = entries[6];
301 expect(threadCreatedEntry?.kind).toBe("event");
302 if (threadCreatedEntry?.kind === "event") {
303 expect(threadCreatedEntry.projectedItem.item.type).toBe("thread_created");
304 }
305 });
306​
307 it("resolves attempt identity through V2 execution nodes", () => {
308 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
309 const threadId = ThreadId.make("thread-attempts");
310 const runId = RunId.make("run-steered");
311 const supersededRootNodeId = NodeId.make("node-attempt-1-root");
312 const supersededChildNodeId = NodeId.make("node-attempt-1-child");
313 const activeRootNodeId = NodeId.make("node-attempt-2-root");
314 const supersededAttemptId = RunAttemptId.make("attempt-1");
315 const activeAttemptId = RunAttemptId.make("attempt-2");
316 const providerInstanceId = ProviderInstanceId.make("codex-default");
317 const providerThreadId = ProviderThreadId.make("provider-thread-attempts");
318 const attempts: ReadonlyArray<OrchestrationV2RunAttempt> = [
319 {
320 id: supersededAttemptId,
321 runId,
322 attemptOrdinal: 1,
323 rootNodeId: supersededRootNodeId,
324 providerInstanceId,
325 providerThreadId,
326 providerTurnId: null,
327 reason: "initial",
328 status: "superseded",
329 startedAt: now,
330 completedAt: now,
331 },
332 {
333 id: activeAttemptId,
334 runId,
335 attemptOrdinal: 2,
336 rootNodeId: activeRootNodeId,
337 providerInstanceId,
338 providerThreadId,
339 providerTurnId: null,
340 reason: "steering_restart",
341 status: "running",
342 startedAt: now,
343 completedAt: null,
344 },
345 ];
346 const node = (
347 id: OrchestrationV2ExecutionNode["id"],
348 rootNodeId: OrchestrationV2ExecutionNode["rootNodeId"],
349 parentNodeId: OrchestrationV2ExecutionNode["parentNodeId"],
350 ): OrchestrationV2ExecutionNode => ({
351 id,
352 threadId,
353 runId,
354 parentNodeId,
355 rootNodeId,
356 kind: id === rootNodeId ? "root_turn" : "assistant_message",
357 status: "running",
358 countsForRun: true,
359 providerThreadId,
360 providerTurnId: null,
361 nativeItemRef: null,
362 runtimeRequestId: null,
363 checkpointScopeId: null,
364 startedAt: now,
365 completedAt: null,
366 });
367 const nodes = [
368 node(supersededRootNodeId, supersededRootNodeId, null),
369 node(supersededChildNodeId, supersededRootNodeId, supersededRootNodeId),
370 node(activeRootNodeId, activeRootNodeId, null),
371 ];
372 const assistantItem = (
373 id: string,
374 messageId: string,
375 nodeId: NodeId,
376 text: string,
377 ordinal: number,
378 ): OrchestrationV2TurnItem => ({
379 id: TurnItemId.make(id),
380 threadId,
381 runId,
382 nodeId,
383 providerThreadId,
384 providerTurnId: null,
385 nativeItemRef: null,
386 parentItemId: null,
387 ordinal,
388 status: "running",
389 title: null,
390 startedAt: now,
391 completedAt: null,
392 updatedAt: now,
393 type: "assistant_message",
394 messageId: MessageId.make(messageId),
395 text,
396 streaming: true,
397 });
398 const items = [
399 assistantItem(
400 "item-superseded",
401 "message-superseded",
402 supersededChildNodeId,
403 "Partial old response",
404 0,
405 ),
406 assistantItem("item-active", "message-active", activeRootNodeId, "Current response", 1),
407 ];
408 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = items.map(
409 (item, position) => ({
410 position,
411 visibility: "local",
412 sourceThreadId: threadId,
413 sourceItemId: item.id,
414 item,
415 }),
416 );
417​
418 const entries = deriveTimelineEntriesFromVisibleTurnItems({
419 visibleTurnItems,
420 optimisticMessages: [],
421 attempts,
422 nodes,
423 });
424​
425 expect(entries.map((entry) => [entry.attempt?.id, entry.attempt?.status])).toEqual([
426 [supersededAttemptId, "superseded"],
427 [activeAttemptId, "running"],
428 ]);
429 });
430});