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 workEntryIndicatesToolFailure,
27 workEntryDisplayIndicatesToolFailure,
28 workEntryIndicatesToolSuccess,
29} from "./session-logic";
30import { makeThreadProjectionFixture } from "./test-fixtures";
31import type { ChatMessage } from "./types";
32
33describe("V2 session presentation", () => {
34 it("uses run status as the settlement boundary", () => {
35 const runId = RunId.make("run-1");
36 expect(
37 isLatestRunSettled(
38 {
39 runId,
40 status: "completed",
41 startedAt: "2026-06-20T00:00:00.000Z",
42 completedAt: "2026-06-20T00:01:00.000Z",
43 },
44 null,
45 ),
46 ).toBe(true);
47 expect(
48 isLatestRunSettled(
49 { runId, status: "running", startedAt: null, completedAt: null },
50 { status: "running", activeRunId: runId },
51 ),
52 ).toBe(false);
53 expect(
54 isLatestRunSettled(
55 { runId, status: "queued", startedAt: null, completedAt: null },
56 { status: "running", activeRunId: RunId.make("run-active") },
57 ),
58 ).toBe(false);
59 });
60
61 it("labels provider retry progress, delay, recovery, and exhaustion", () => {
62 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
63 const retryItem = {
64 id: TurnItemId.make("item-provider-retry"),
65 threadId: ThreadId.make("thread-provider-retry"),
66 runId: RunId.make("run-provider-retry"),
67 nodeId: null,
68 providerThreadId: null,
69 providerTurnId: null,
70 nativeItemRef: null,
71 parentItemId: null,
72 ordinal: 1,
73 status: "running" as const,
74 title: "Provider retry",
75 startedAt: now,
76 completedAt: null,
77 updatedAt: now,
78 type: "error" as const,
79 failure: {
80 class: "provider_error" as const,
81 message: "Claude API overloaded.",
82 code: "api_error_529",
83 retryable: true,
84 },
85 retry: {
86 attempt: 2,
87 maxAttempts: 10,
88 retryDelayMs: 1_500,
89 },
90 } satisfies Extract<OrchestrationV2TurnItem, { readonly type: "error" }>;
91
92 expect(providerErrorPresentation(retryItem)).toEqual({
93 label: "Retrying provider (2/10)",
94 detail: "Claude API overloaded. Retrying in 1.5s.",
95 });
96 expect(
97 providerErrorPresentation({
98 ...retryItem,
99 status: "completed",
100 completedAt: now,
101 }),
102 ).toMatchObject({ label: "Provider recovered (2/10 retries)" });
103 expect(
104 providerErrorPresentation({
105 ...retryItem,
106 status: "failed",
107 retry: { ...retryItem.retry, attempt: 10 },
108 completedAt: now,
109 }),
110 ).toMatchObject({ label: "Provider error after 10/10 retries" });
111 });
112
113 it("selects the latest proposed plan for a run", () => {
114 const runId = RunId.make("run-1");
115 const planId = PlanId.make("plan-1");
116 const nodeId = NodeId.make("node-plan");
117 const now = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");
118 const baseProjection = makeThreadProjectionFixture();
119 const plan = findLatestProposedPlan(
120 {
121 ...baseProjection,
122 plans: [
123 {
124 id: planId,
125 threadId: baseProjection.thread.id,
126 nodeId,
127 kind: "proposed_plan" as const,
128 markdown: "Plan",
129 status: "active" as const,
130 runId,
131 },
132 ],
133 turnItems: [
134 {
135 id: TurnItemId.make("item-plan"),
136 threadId: baseProjection.thread.id,
137 nodeId,
138 providerThreadId: null,
139 providerTurnId: null,
140 nativeItemRef: null,
141 parentItemId: null,
142 ordinal: 0,
143 status: "completed" as const,
144 title: null,
145 startedAt: now,
146 completedAt: now,
147 updatedAt: now,
148 type: "proposed_plan" as const,
149 planId,
150 markdown: "Plan",
151 streaming: false,
152 runId,
153 },
154 ],
155 updatedAt: now,
156 },
157 runId,
158 );
159 expect(plan?.planMarkdown).toBe("Plan");
160 });
161
162 it("assigns run rollback to the turn-start message instead of a later steer", () => {
163 const runId = RunId.make("run-steered");
164 const turnStartMessageId = MessageId.make("message-turn-start");
165 const steerMessageId = MessageId.make("message-steer");
166 const assistantMessageId = MessageId.make("message-assistant");
167 const messages: ChatMessage[] = [
168 {
169 id: turnStartMessageId,
170 role: "user",
171 text: "Start",
172 runId,
173 inputIntent: "turn_start",
174 streaming: false,
175 createdAt: "2026-06-20T00:00:00.000Z",
176 updatedAt: "2026-06-20T00:00:00.000Z",
177 },
178 {
179 id: steerMessageId,
180 role: "user",
181 text: "Steer",
182 runId,
183 inputIntent: "steer",
184 streaming: false,
185 createdAt: "2026-06-20T00:00:01.000Z",
186 updatedAt: "2026-06-20T00:00:01.000Z",
187 },
188 {
189 id: assistantMessageId,
190 role: "assistant",
191 text: "Done",
192 runId,
193 streaming: false,
194 createdAt: "2026-06-20T00:00:02.000Z",
195 updatedAt: "2026-06-20T00:00:02.000Z",
196 },
197 ];
198 const timelineEntries: TimelineEntry[] = messages.map(
199 (message): TimelineEntry => ({
200 id: message.id,
201 kind: "message",
202 createdAt: message.createdAt,
203 message,
204 }),
205 );
206
207 const targets = deriveRevertTurnCountByUserMessageId({
208 timelineEntries,
209 checkpoints: [
210 {
211 runId,
212 checkpointTurnCount: 1,
213 checkpointRef: "checkpoint-run-1" as never,
214 status: "ready",
215 files: [],
216 assistantMessageId,
217 completedAt: "2026-06-20T00:00:03.000Z",
218 },
219 ],
220 });
221
222 expect([...targets]).toEqual([[turnStartMessageId, 0]]);
223 expect(targets.has(steerMessageId)).toBe(false);
224 });
225
226 it("uses visible turn item order and keeps provider errors in the work log", () => {
227 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
228 const threadId = ThreadId.make("thread-visible");
229 const runId = RunId.make("run-visible");
230 const base = (id: string, ordinal: number) => ({
231 id: TurnItemId.make(id),
232 threadId,
233 runId,
234 nodeId: null,
235 providerThreadId: null,
236 providerTurnId: null,
237 nativeItemRef: null,
238 parentItemId: null,
239 ordinal,
240 status: "completed" as const,
241 title: null,
242 startedAt: now,
243 completedAt: now,
244 updatedAt: now,
245 });
246 const userItem = {
247 ...base("item-user", 0),
248 type: "user_message" as const,
249 messageId: MessageId.make("message-user"),
250 inputIntent: "turn_start" as const,
251 text: "Start",
252 attachments: [],
253 createdBy: "user" as const,
254 creationSource: "web" as const,
255 } satisfies OrchestrationV2TurnItem;
256 const requestItem = {
257 ...base("item-interrupt-request", 1),
258 type: "run_interrupt_request" as const,
259 message: "Stopping",
260 } satisfies OrchestrationV2TurnItem;
261 const commandItem = {
262 ...base("item-command", 2),
263 type: "command_execution" as const,
264 input: "sleep 1",
265 output: "done",
266 exitCode: 0,
267 } satisfies OrchestrationV2TurnItem;
268 const resultItem = {
269 ...base("item-interrupt-result", 3),
270 type: "run_interrupt_result" as const,
271 message: "Stopped",
272 } satisfies OrchestrationV2TurnItem;
273 const todoItem = {
274 ...base("item-todo", 4),
275 type: "todo_list" as const,
276 planId: PlanId.make("plan-visible"),
277 explanation: "Keep task detail in the Tasks panel",
278 steps: [
279 { id: "step-1", text: "First", status: "completed" as const },
280 { id: "step-2", text: "Second", status: "pending" as const },
281 ],
282 } satisfies OrchestrationV2TurnItem;
283 const errorItem = {
284 ...base("item-error", 5),
285 status: "failed" as const,
286 type: "error" as const,
287 failure: {
288 class: "validation_error" as const,
289 message: "Invalid reasoning effort.",
290 code: "invalid_request",
291 retryable: false,
292 },
293 } satisfies OrchestrationV2TurnItem;
294 const threadCreatedItem = {
295 ...base("item-thread-created", 6),
296 type: "thread_created" as const,
297 title: "Follow-up thread",
298 targetThreadId: ThreadId.make("thread-follow-up"),
299 targetRunId: RunId.make("run-follow-up"),
300 targetProviderInstanceId: ProviderInstanceId.make("claude-default"),
301 targetModel: "claude-sonnet-4-6",
302 } satisfies OrchestrationV2TurnItem;
303 const workspacePreparationItem = {
304 ...base("item-workspace-preparation", 7),
305 type: "command_execution" as const,
306 title: "Workspace ready",
307 input: "Preparing workspace",
308 output: "Workspace preparation completed.",
309 exitCode: 0,
310 } satisfies OrchestrationV2TurnItem;
311 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
312 userItem,
313 requestItem,
314 commandItem,
315 resultItem,
316 todoItem,
317 errorItem,
318 threadCreatedItem,
319 workspacePreparationItem,
320 ].map((item, position) => ({
321 position,
322 visibility: "local" as const,
323 sourceThreadId: threadId,
324 sourceItemId: item.id,
325 item,
326 }));
327
328 const entries = deriveTimelineEntriesFromVisibleTurnItems({
329 visibleTurnItems,
330 optimisticMessages: [],
331 });
332
333 expect(entries.map((entry) => [entry.kind, entry.id])).toEqual([
334 ["message", userItem.messageId],
335 ["event", requestItem.id],
336 ["work", commandItem.id],
337 ["event", resultItem.id],
338 ["turn-plan", todoItem.id],
339 ["work", errorItem.id],
340 ["event", threadCreatedItem.id],
341 ]);
342 const commandEntry = entries[2];
343 const userEntry = entries[0];
344 expect(userEntry?.kind).toBe("message");
345 if (userEntry?.kind === "message") {
346 expect(userEntry.projectedItem).toBe(visibleTurnItems[0]);
347 expect(userEntry.message.inputIntent).toBe("turn_start");
348 expect(userEntry.message.createdBy).toBe("user");
349 expect(userEntry.message.creationSource).toBe("web");
350 }
351 expect(commandEntry?.kind).toBe("work");
352 if (commandEntry?.kind === "work") {
353 expect(commandEntry.entry.projectedItem).toBe(visibleTurnItems[2]);
354 expect(commandEntry.entry.structuredPayload).toBe(commandItem);
355 }
356 const todoEntry = entries[4];
357 expect(todoEntry?.kind).toBe("turn-plan");
358 if (todoEntry?.kind === "turn-plan") {
359 expect(todoEntry.turnPlan.id).toBe("turn-plan:plan-visible");
360 expect(todoEntry.turnPlan.plan.explanation).toBe("Keep task detail in the Tasks panel");
361 expect(todoEntry.turnPlan.plan.steps).toEqual([
362 { step: "First", status: "completed" },
363 { step: "Second", status: "pending" },
364 ]);
365 }
366 const errorEntry = entries[5];
367 expect(errorEntry?.kind).toBe("work");
368 if (errorEntry?.kind === "work") {
369 expect(errorEntry.entry.projectedItem).toBe(visibleTurnItems[5]);
370 expect(errorEntry.entry.label).toBe("Provider error");
371 expect(errorEntry.entry.detail).toBe("Invalid reasoning effort.");
372 expect(errorEntry.entry.tone).toBe("info");
373 expect(errorEntry.entry.toolLifecycleStatus).toBe("failed");
374 }
375 const threadCreatedEntry = entries[6];
376 expect(threadCreatedEntry?.kind).toBe("event");
377 if (threadCreatedEntry?.kind === "event") {
378 expect(threadCreatedEntry.projectedItem.item.type).toBe("thread_created");
379 }
380 });
381
382 it("keeps failed tool items tool-toned so groups still summarize", () => {
383 const failedCommand = {
384 id: TurnItemId.make("item-failed-command"),
385 threadId: ThreadId.make("thread-1"),
386 runId: RunId.make("run-1"),
387 nodeId: null,
388 providerThreadId: null,
389 providerTurnId: null,
390 nativeItemRef: null,
391 parentItemId: null,
392 ordinal: 0,
393 status: "failed" as const,
394 title: null,
395 startedAt: null,
396 completedAt: null,
397 updatedAt: DateTime.nowUnsafe(),
398 type: "command_execution" as const,
399 input: "ssh host true",
400 output: "connection refused",
401 exitCode: 255,
402 } satisfies OrchestrationV2TurnItem;
403 const entries = deriveTimelineEntriesFromVisibleTurnItems({
404 visibleTurnItems: [
405 {
406 position: 0,
407 visibility: "local" as const,
408 sourceThreadId: ThreadId.make("thread-1"),
409 sourceItemId: failedCommand.id,
410 item: failedCommand,
411 } as never,
412 ],
413 optimisticMessages: [],
414 });
415 const entry = entries[0];
416 expect(entry?.kind).toBe("work");
417 if (entry?.kind === "work") {
418 // An exit-code failure is still an ordinary tool row: the failed
419 // lifecycle status carries the marker, and an "error" tone here would
420 // knock the whole group out of the "Ran N commands" summary.
421 expect(entry.entry.tone).toBe("tool");
422 expect(entry.entry.toolLifecycleStatus).toBe("failed");
423 }
424 });
425
426 it("waits for a dispatched turn item before adding queued input to the timeline", () => {
427 const projection = makeThreadProjectionFixture();
428 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
429 const runId = RunId.make("run-dispatched-queued");
430 const messageId = MessageId.make("message-dispatched-queued");
431 const optimisticMessage = {
432 id: messageId,
433 role: "user" as const,
434 text: "Queued input",
435 runId: null,
436 inputIntent: "queued_turn" as const,
437 streaming: false,
438 createdAt: DateTime.formatIso(now),
439 updatedAt: DateTime.formatIso(now),
440 };
441
442 expect(
443 deriveTimelineEntriesFromVisibleTurnItems({
444 visibleTurnItems: [],
445 optimisticMessages: [optimisticMessage],
446 }),
447 ).toEqual([]);
448
449 const dispatchedItem = {
450 id: TurnItemId.make("item-dispatched-queued"),
451 threadId: projection.thread.id,
452 runId,
453 nodeId: null,
454 providerThreadId: null,
455 providerTurnId: null,
456 nativeItemRef: null,
457 parentItemId: null,
458 ordinal: 200,
459 status: "completed" as const,
460 title: null,
461 startedAt: now,
462 completedAt: now,
463 updatedAt: now,
464 type: "user_message" as const,
465 messageId,
466 inputIntent: "turn_start" as const,
467 text: "Queued input",
468 attachments: [],
469 createdBy: "user" as const,
470 creationSource: "web" as const,
471 } satisfies OrchestrationV2TurnItem;
472 const promotedEntries = deriveTimelineEntriesFromVisibleTurnItems({
473 visibleTurnItems: [
474 {
475 position: 0,
476 visibility: "local",
477 sourceThreadId: projection.thread.id,
478 sourceItemId: dispatchedItem.id,
479 item: dispatchedItem,
480 },
481 ],
482 optimisticMessages: [optimisticMessage],
483 });
484 expect(promotedEntries.map((entry) => entry.id)).toEqual([messageId]);
485 expect(promotedEntries[0]?.kind).toBe("message");
486 if (promotedEntries[0]?.kind === "message") {
487 expect(promotedEntries[0].message.inputIntent).toBe("turn_start");
488 }
489 });
490
491 it("anchors feedback before later committed turns without reordering canonical history", () => {
492 const threadId = ThreadId.make("thread-feedback-order");
493 const messageItem = (input: {
494 readonly id: string;
495 readonly role: "user" | "assistant";
496 readonly createdAt: string;
497 readonly ordinal: number;
498 }): OrchestrationV2TurnItem => {
499 const timestamp = DateTime.makeUnsafe(input.createdAt);
500 const common = {
501 id: TurnItemId.make(`item-${input.id}`),
502 threadId,
503 runId: RunId.make(`run-${input.ordinal}`),
504 nodeId: null,
505 providerThreadId: null,
506 providerTurnId: null,
507 nativeItemRef: null,
508 parentItemId: null,
509 ordinal: input.ordinal,
510 status: "completed" as const,
511 title: null,
512 startedAt: timestamp,
513 completedAt: timestamp,
514 updatedAt: timestamp,
515 messageId: MessageId.make(input.id),
516 text: input.id,
517 };
518 return input.role === "user"
519 ? {
520 ...common,
521 type: "user_message",
522 inputIntent: "turn_start",
523 attachments: [],
524 createdBy: "user",
525 creationSource: "web",
526 }
527 : { ...common, type: "assistant_message", streaming: false };
528 };
529 const canonicalItems = [
530 messageItem({ id: "old-user", role: "user", createdAt: "2026-08-29T00:00:01Z", ordinal: 1 }),
531 messageItem({
532 id: "old-assistant",
533 role: "assistant",
534 createdAt: "2026-08-29T00:00:02Z",
535 ordinal: 2,
536 }),
537 messageItem({
538 id: "later-user",
539 role: "user",
540 createdAt: "2026-08-29T00:00:05Z",
541 ordinal: 3,
542 }),
543 messageItem({
544 id: "later-assistant",
545 role: "assistant",
546 createdAt: "2026-08-29T00:00:04Z",
547 ordinal: 4,
548 }),
549 ];
550 const visibleTurnItems = canonicalItems.map((item, position) => ({
551 position,
552 visibility: "local" as const,
553 sourceThreadId: threadId,
554 sourceItemId: item.id,
555 item,
556 }));
557 const feedback = (id: string, role: "user" | "assistant"): ChatMessage => ({
558 id: MessageId.make(id),
559 role,
560 text: id,
561 runId: null,
562 streaming: false,
563 createdAt: "2026-08-29T00:00:03Z",
564 updatedAt: "2026-08-29T00:00:03Z",
565 });
566 const entries = deriveTimelineEntriesFromVisibleTurnItems({
567 visibleTurnItems,
568 anchoredMessages: [
569 feedback("feedback-user", "user"),
570 feedback("feedback-assistant", "assistant"),
571 feedback("later-user", "user"),
572 ],
573 optimisticMessages: [
574 { ...feedback("optimistic-user", "user"), createdAt: "2026-08-29T00:00:00Z" },
575 ],
576 });
577
578 expect(entries.map((entry) => entry.id)).toEqual([
579 "old-user",
580 "old-assistant",
581 "feedback-user",
582 "feedback-assistant",
583 "later-user",
584 "later-assistant",
585 "optimistic-user",
586 ]);
587 expect(
588 entries
589 .filter((entry) => entry.id.startsWith("feedback-"))
590 .every((entry) => entry.kind === "message" && entry.projectedItem === undefined),
591 ).toBe(true);
592 });
593
594 it("uses projected plan status and file contents in timeline entries", () => {
595 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
596 const threadId = ThreadId.make("thread-timeline-artifacts");
597 const runId = RunId.make("run-timeline-artifacts");
598 const nodeId = NodeId.make("node-timeline-artifacts");
599 const planId = PlanId.make("plan-timeline-artifacts");
600 const base = {
601 threadId,
602 runId,
603 nodeId,
604 providerThreadId: null,
605 providerTurnId: null,
606 nativeItemRef: null,
607 parentItemId: null,
608 status: "completed" as const,
609 title: null,
610 startedAt: now,
611 completedAt: now,
612 updatedAt: now,
613 };
614 const planItem = {
615 ...base,
616 id: TurnItemId.make("item-proposed-plan"),
617 ordinal: 0,
618 type: "proposed_plan" as const,
619 planId,
620 markdown: "Finished plan",
621 streaming: false,
622 } satisfies OrchestrationV2TurnItem;
623 const fileItem = {
624 ...base,
625 id: TurnItemId.make("item-file-change"),
626 ordinal: 1,
627 type: "file_change" as const,
628 fileName: "src/example.ts",
629 newStr: "export const answer = 42;\n",
630 } satisfies OrchestrationV2TurnItem;
631 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
632 planItem,
633 fileItem,
634 ].map((item, position) => ({
635 position,
636 visibility: "local",
637 sourceThreadId: threadId,
638 sourceItemId: item.id,
639 item,
640 }));
641
642 const entries = deriveTimelineEntriesFromVisibleTurnItems({
643 visibleTurnItems,
644 optimisticMessages: [],
645 plans: [
646 {
647 id: planId,
648 threadId,
649 runId,
650 nodeId,
651 kind: "proposed_plan",
652 markdown: "",
653 status: "completed",
654 detailInTurnItem: true,
655 },
656 ],
657 });
658
659 expect(entries[0]?.kind).toBe("proposed-plan");
660 if (entries[0]?.kind === "proposed-plan") {
661 expect(entries[0].proposedPlan.status).toBe("completed");
662 expect(entries[0].proposedPlan.planMarkdown).toBe("Finished plan");
663 }
664 expect(entries[1]?.kind).toBe("work");
665 if (entries[1]?.kind === "work") {
666 expect(entries[1].entry.detail).toBe(fileItem.newStr);
667 }
668 });
669
670 it("resolves attempt identity through V2 execution nodes", () => {
671 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
672 const threadId = ThreadId.make("thread-attempts");
673 const runId = RunId.make("run-steered");
674 const supersededRootNodeId = NodeId.make("node-attempt-1-root");
675 const supersededChildNodeId = NodeId.make("node-attempt-1-child");
676 const activeRootNodeId = NodeId.make("node-attempt-2-root");
677 const supersededAttemptId = RunAttemptId.make("attempt-1");
678 const activeAttemptId = RunAttemptId.make("attempt-2");
679 const providerInstanceId = ProviderInstanceId.make("codex-default");
680 const providerThreadId = ProviderThreadId.make("provider-thread-attempts");
681 const attempts: ReadonlyArray<OrchestrationV2RunAttempt> = [
682 {
683 id: supersededAttemptId,
684 runId,
685 attemptOrdinal: 1,
686 rootNodeId: supersededRootNodeId,
687 providerInstanceId,
688 providerThreadId,
689 providerTurnId: null,
690 reason: "initial",
691 status: "superseded",
692 startedAt: now,
693 completedAt: now,
694 },
695 {
696 id: activeAttemptId,
697 runId,
698 attemptOrdinal: 2,
699 rootNodeId: activeRootNodeId,
700 providerInstanceId,
701 providerThreadId,
702 providerTurnId: null,
703 reason: "steering_restart",
704 status: "running",
705 startedAt: now,
706 completedAt: null,
707 },
708 ];
709 const node = (
710 id: OrchestrationV2ExecutionNode["id"],
711 rootNodeId: OrchestrationV2ExecutionNode["rootNodeId"],
712 parentNodeId: OrchestrationV2ExecutionNode["parentNodeId"],
713 ): OrchestrationV2ExecutionNode => ({
714 id,
715 threadId,
716 runId,
717 parentNodeId,
718 rootNodeId,
719 kind: id === rootNodeId ? "root_turn" : "assistant_message",
720 status: "running",
721 countsForRun: true,
722 providerThreadId,
723 providerTurnId: null,
724 nativeItemRef: null,
725 runtimeRequestId: null,
726 checkpointScopeId: null,
727 startedAt: now,
728 completedAt: null,
729 });
730 const nodes = [
731 node(supersededRootNodeId, supersededRootNodeId, null),
732 node(supersededChildNodeId, supersededRootNodeId, supersededRootNodeId),
733 node(activeRootNodeId, activeRootNodeId, null),
734 ];
735 const assistantItem = (
736 id: string,
737 messageId: string,
738 nodeId: NodeId,
739 text: string,
740 ordinal: number,
741 ): OrchestrationV2TurnItem => ({
742 id: TurnItemId.make(id),
743 threadId,
744 runId,
745 nodeId,
746 providerThreadId,
747 providerTurnId: null,
748 nativeItemRef: null,
749 parentItemId: null,
750 ordinal,
751 status: "running",
752 title: null,
753 startedAt: now,
754 completedAt: null,
755 updatedAt: now,
756 type: "assistant_message",
757 messageId: MessageId.make(messageId),
758 text,
759 streaming: true,
760 });
761 const items = [
762 assistantItem(
763 "item-superseded",
764 "message-superseded",
765 supersededChildNodeId,
766 "Partial old response",
767 0,
768 ),
769 assistantItem("item-active", "message-active", activeRootNodeId, "Current response", 1),
770 ];
771 const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = items.map(
772 (item, position) => ({
773 position,
774 visibility: "local",
775 sourceThreadId: threadId,
776 sourceItemId: item.id,
777 item,
778 }),
779 );
780
781 const entries = deriveTimelineEntriesFromVisibleTurnItems({
782 visibleTurnItems,
783 optimisticMessages: [],
784 attempts,
785 nodes,
786 });
787
788 expect(entries.map((entry) => [entry.attempt?.id, entry.attempt?.status])).toEqual([
789 [supersededAttemptId, "superseded"],
790 [activeAttemptId, "running"],
791 ]);
792 });
793});
794
795describe("work-log failure policy (#7999/#7893)", () => {
796 const toolEntry = (overrides: Record<string, unknown>) =>
797 ({
798 id: "entry-1",
799 createdAt: "2026-08-27T00:00:00.000Z",
800 label: "Ran command",
801 tone: "tool",
802 ...overrides,
803 }) as never;
804
805 it("flags success-status rows whose output text reports a failure", () => {
806 expect(
807 workEntryIndicatesToolFailure(
808 toolEntry({ toolLifecycleStatus: "completed", detail: "bash: foo: command not found" }),
809 ),
810 ).toBe(true);
811 expect(
812 workEntryIndicatesToolFailure(
813 toolEntry({ toolLifecycleStatus: "completed", detail: "<exited with exit code 2>" }),
814 ),
815 ).toBe(true);
816 });
817
818 it("keeps the rendered row calm when only the command mentions failure text", () => {
819 const entry = toolEntry({
820 toolLifecycleStatus: "completed",
821 command: "rg 'command not found' src/",
822 });
823 expect(workEntryIndicatesToolFailure(entry)).toBe(true);
824 expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);
825 });
826
827 it("does not call a clean completed row failed", () => {
828 const entry = toolEntry({ toolLifecycleStatus: "completed", detail: "3 files changed" });
829 expect(workEntryIndicatesToolFailure(entry)).toBe(false);
830 expect(workEntryIndicatesToolSuccess(entry)).toBe(true);
831 });
832
833 it("recovered failure text no longer counts as success", () => {
834 const entry = toolEntry({ toolLifecycleStatus: "completed", detail: "ENOENT: no such file" });
835 expect(workEntryIndicatesToolSuccess(entry)).toBe(false);
836 });
837});