@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 5,186 lines 173 KB
Raw
1 import { ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts";
2 import {
3 CheckpointRef,
4 NodeId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 ProviderTurnId,
8 RunAttemptId,
9 TurnItemId,
10 RuntimeRequestId,
11 type OrchestrationV2ProjectedTurnItem,
12 type OrchestrationV2TurnItem,
13 } from "@t3tools/contracts";
14 import * as DateTime from "effect/DateTime";
15 import {
16 deriveTimelineEntriesFromVisibleTurnItems,
17 deriveTimelineEntriesFromVisibleTurnItemsWithState,
18 workEntryDisplayIndicatesToolFailure,
19 type TimelineEntry,
20 } from "../../session-logic";
21 import {
22 makeStreamingTimelineFixture,
23 makeStreamingWorkTimelineFixture,
24 withStreamedText,
25 } from "../../test-fixtures";
26 import type { TurnDiffSummary } from "../../types";
27 import { describe, expect, it } from "vite-plus/test";
28 import { MessageId, RunId } from "@t3tools/contracts";
29 import {
30 computeStableMessagesTimelineRows,
31 deriveMessagesTimelineRows,
32 timelineTurnFoldRunIdsByEntryId,
33 liveAnswerPreview,
34 deriveMessagesTimelineRowsWithState,
35 isTimelineMinimapTurnVisible,
36 resolveAssistantMessageCopyState,
37 type MessagesTimelineRow,
38 workEntryDisplayLabel,
39 workEntryReadOutput,
40 } from "./MessagesTimeline.logic";
41 import { workEntryIconName } from "./TimelineWorkEntryRow.logic";
42
43 describe("resolveAssistantMessageCopyState", () => {
44 it("copies the rendered representation of Codex directives", () => {
45 expect(
46 resolveAssistantMessageCopyState({
47 showCopyButton: true,
48 text: [
49 'Created :codex-file-citation{path="outputs/report.xlsx" purpose="output"}.',
50 "",
51 '::artifact-template{skill_name="artifact-template-hello-world" skill_directory="/Users/test/.codex/skills/artifact-template-hello-world" display_name="Hello World" artifact_kind="document"}',
52 ].join("\n"),
53 streaming: false,
54 }),
55 ).toEqual({
56 text: "Created [report.xlsx](<outputs/report.xlsx>).\n\nHello World (Document template)",
57 visible: true,
58 });
59 });
60 });
61
62 describe("deriveMessagesTimelineRows", () => {
63 it.each([
64 ["html-render", "reply-run", true],
65 ["mcp-app", "reply-run", true],
66 ["html-render", "other-run", false],
67 ["html-render", null, false],
68 [null, null, false],
69 ] as const)("suppresses the empty fallback for %s in %s: %s", (kind, renderRun, expected) => {
70 const at = "2026-11-06T00:00:00Z";
71 const runId = RunId.make("reply-run");
72 const renderBase = {
73 id: "render",
74 createdAt: at,
75 runId: renderRun ? RunId.make(renderRun) : null,
76 };
77 const embedded: TimelineEntry[] =
78 kind === "html-render"
79 ? [
80 {
81 ...renderBase,
82 kind,
83 htmlRender: { attachmentId: "preview", title: "Preview", height: 420 },
84 },
85 ]
86 : kind === "mcp-app"
87 ? [
88 {
89 ...renderBase,
90 kind,
91 sourceThreadId: ThreadId.make("thread"),
92 itemId: TurnItemId.make("app"),
93 revision: "1",
94 mcpApp: {
95 attachmentId: "app",
96 server: "weather",
97 tool: "weather",
98 resourceUri: "ui://weather",
99 },
100 },
101 ]
102 : [];
103 const rows = deriveMessagesTimelineRows({
104 timelineEntries: [
105 ...embedded,
106 {
107 kind: "message",
108 id: "reply",
109 createdAt: at,
110 message: {
111 id: MessageId.make("reply"),
112 role: "assistant",
113 runId,
114 text: "",
115 streaming: false,
116 createdAt: at,
117 updatedAt: at,
118 },
119 },
120 ],
121 latestRun: null,
122 isWorking: false,
123 activeTurnStartedAt: null,
124 turnDiffSummaries: [],
125 supportsConversationRollback: false,
126 });
127 const reply = rows.find((row) => row.kind === "message" && row.id === "reply");
128 expect(reply).toMatchObject({ suppressEmptyResponse: expected });
129 });
130
131 it.each(["alone", "before tool", "before commentary and tool"])(
132 "keeps an unfinished task update static %s",
133 (placement) => {
134 const runId = RunId.make("task-update-run");
135 const at = "2026-11-06T00:00:00Z";
136 const tasks: TimelineEntry = {
137 kind: "work",
138 id: "tasks",
139 createdAt: at,
140 entry: {
141 id: "tasks",
142 runId,
143 createdAt: at,
144 itemType: "todo_list",
145 tone: "info",
146 label: "Tasks 0/1 · Inspect the captures",
147 toolLifecycleStatus: "inProgress",
148 },
149 };
150 const commentary: TimelineEntry = {
151 kind: "message",
152 id: "commentary",
153 createdAt: at,
154 message: {
155 id: MessageId.make("commentary"),
156 role: "assistant",
157 text: "Checking the rendering.",
158 runId,
159 streaming: false,
160 createdAt: at,
161 updatedAt: at,
162 },
163 };
164 const tool: TimelineEntry = {
165 kind: "work",
166 id: "tool",
167 createdAt: at,
168 entry: {
169 id: "tool",
170 runId,
171 createdAt: at,
172 label: "Running sed",
173 command: "sed",
174 tone: "tool",
175 toolLifecycleStatus: "inProgress",
176 },
177 };
178 const rows = deriveMessagesTimelineRows({
179 timelineEntries: [
180 tasks,
181 ...(placement === "before commentary and tool" ? [commentary] : []),
182 ...(placement === "alone" ? [] : [tool]),
183 ],
184 runningRunId: runId,
185 isWorking: true,
186 activeTurnStartedAt: at,
187 turnDiffSummaries: [],
188 supportsConversationRollback: false,
189 });
190 expect(rows.find((row) => row.id === "tasks")).toMatchObject({
191 kind: "work",
192 groupedEntries: [tasks.entry],
193 });
194 expect(rows.filter((row) => row.kind === "work-live" && row.active)).toEqual(
195 placement === "alone" ? [] : [expect.objectContaining({ entry: tool.entry })],
196 );
197 },
198 );
199
200 it("stops stranded thinking after a steer and follows the next thought or tool", () => {
201 const runId = RunId.make("steered-run");
202 const at = "2026-10-01T06:19:10Z";
203 const thought = (id: string): TimelineEntry => ({
204 kind: "work",
205 id,
206 createdAt: at,
207 entry: {
208 id,
209 runId,
210 createdAt: at,
211 label: "Thinking",
212 tone: "thinking",
213 itemType: "reasoning",
214 detail: id,
215 toolLifecycleStatus: "inProgress",
216 },
217 });
218 const steer: TimelineEntry = {
219 kind: "message",
220 id: "steer",
221 createdAt: at,
222 message: {
223 id: MessageId.make("steer"),
224 role: "user",
225 text: "Also evaluate speed",
226 runId,
227 inputIntent: "steer",
228 streaming: false,
229 createdAt: at,
230 updatedAt: at,
231 },
232 };
233 const first = thought("first-thought");
234 const next = thought("next-thought");
235 const tool: TimelineEntry = {
236 kind: "work",
237 id: "tool",
238 createdAt: at,
239 entry: {
240 id: "tool",
241 runId,
242 createdAt: at,
243 label: "Running cat",
244 tone: "tool",
245 command: "cat file",
246 toolLifecycleStatus: "inProgress",
247 },
248 };
249 const rows = (timelineEntries: ReadonlyArray<TimelineEntry>) =>
250 deriveMessagesTimelineRows({
251 timelineEntries,
252 runningRunId: runId,
253 isWorking: true,
254 activeTurnStartedAt: at,
255 turnDiffSummaries: [],
256 supportsConversationRollback: false,
257 });
258 expect(rows([first]).find((row) => row.kind === "work-live")).toMatchObject({
259 active: true,
260 entry: { id: "first-thought" },
261 });
262 const afterSteer = rows([first, steer]);
263 expect(afterSteer.some((row) => row.kind === "work-live")).toBe(false);
264 expect(afterSteer.at(-1)?.kind).toBe("thinking");
265 expect(afterSteer.find((row) => row.kind === "work")).toMatchObject({
266 groupedEntries: [{ id: "first-thought", toolLifecycleStatus: "completed" }],
267 });
268 for (const entries of [
269 [first, steer, next],
270 [first, next],
271 [first, steer, next, tool],
272 ]) {
273 const live = rows(entries).filter((row) => row.kind === "work-live" && row.active);
274 expect(live).toHaveLength(1);
275 expect(live[0]).toMatchObject({ entry: { id: entries.at(-1)!.id } });
276 }
277 expect(first.kind === "work" && first.entry.toolLifecycleStatus).toBe("inProgress");
278 });
279
280 it("recovers the failed Sky call stored as a generic js integration", () => {
281 const fixture = makeStreamingTimelineFixture();
282 const source = fixture.visibleTurnItems.find((row) => row.item.type === "dynamic_tool")!;
283 if (source.item.type !== "dynamic_tool") throw new Error("Expected tool fixture");
284 const item = {
285 ...source.item,
286 type: "dynamic_tool" as const,
287 status: "failed" as const,
288 title: "js",
289 toolName: "node_repl.js",
290 toolSource: { key: "mcp:node_repl", name: "node repl", kind: "integration" as const },
291 input: {
292 title: "Restrict the breakpoint to Git actions",
293 code: "await sky.type_text({app:'T3 Code (Nightly)',text:'debug(ga.run)'});",
294 },
295 };
296 const entries = deriveTimelineEntriesFromVisibleTurnItems({
297 visibleTurnItems: [{ ...source, item }],
298 optimisticMessages: [],
299 });
300 const entry = entries.find((row) => row.kind === "work");
301 expect(entry?.kind === "work" && workEntryDisplayLabel(entry.entry, undefined)).toBe(
302 "Restrict the breakpoint to Git actions",
303 );
304 expect(entry?.kind === "work" && entry.entry).toMatchObject({
305 toolSurface: "computer",
306 toolSource: { key: "computer-use", kind: "computer" },
307 });
308 });
309
310 it.each(["waiting", "completed"] as const)(
311 "groups approval and user-input requests with commands without expanding them when %s",
312 (status) => {
313 const fixture = makeStreamingTimelineFixture();
314 const source = fixture.visibleTurnItems[0]!;
315 const common = {
316 ...source.item,
317 threadId: fixture.threadId,
318 runId: fixture.runId,
319 nodeId: null,
320 providerThreadId: null,
321 providerTurnId: null,
322 nativeItemRef: null,
323 parentItemId: null,
324 status,
325 };
326 const items: OrchestrationV2ProjectedTurnItem["item"][] = [
327 {
328 ...common,
329 id: TurnItemId.make("command"),
330 type: "command_execution",
331 input: "pwd",
332 output: "",
333 },
334 {
335 ...common,
336 id: TurnItemId.make("approval"),
337 type: "approval_request",
338 requestId: RuntimeRequestId.make("approval-request"),
339 requestKind: "command",
340 prompt: "Allow pwd?",
341 },
342 {
343 ...common,
344 id: TurnItemId.make("input"),
345 type: "user_input_request",
346 requestId: RuntimeRequestId.make("input-request"),
347 questions: [],
348 },
349 ];
350 const entries = deriveTimelineEntriesFromVisibleTurnItems({
351 visibleTurnItems: items.map((item, position) => ({
352 ...source,
353 item,
354 position,
355 sourceItemId: item.id,
356 })),
357 optimisticMessages: [],
358 });
359 expect(entries.map((entry) => entry.kind)).toEqual(["work", "work", "work"]);
360 const rows = deriveMessagesTimelineRows({
361 timelineEntries: entries,
362 isWorking: status === "waiting",
363 runningRunId: fixture.runId,
364 activeTurnStartedAt: fixture.time(0),
365 turnDiffSummaries: [],
366 supportsConversationRollback: false,
367 });
368 const workRows = rows.filter((row) => row.kind === "work-toggle" || row.kind === "work-live");
369 expect(workRows).toHaveLength(1);
370 expect(workRows[0]).toMatchObject({ expanded: false });
371 const expandedRows = deriveMessagesTimelineRows({
372 timelineEntries: entries,
373 isWorking: status === "waiting",
374 runningRunId: fixture.runId,
375 activeTurnStartedAt: fixture.time(0),
376 turnDiffSummaries: [],
377 supportsConversationRollback: false,
378 expandedWorkGroupIds: new Set([workRows[0]!.groupId]),
379 });
380 const expanded = expandedRows.find((row) => row.kind === "work" && row.isExpandedToolGroup);
381 expect(
382 expanded?.kind === "work" && expanded.groupedEntries.map((entry) => entry.itemType),
383 ).toEqual(["command_execution", "approval_request", "user_input_request"]);
384 expect(rows.some((row) => row.kind === "event")).toBe(false);
385 expect(workRows[0]).not.toMatchObject({ expanded: true });
386 expect(workRows[0]).not.toMatchObject({ isExpandedToolGroup: true });
387 const pendingRows = deriveMessagesTimelineRows({
388 timelineEntries: entries,
389 pendingApprovalRequestIds: new Set([RuntimeRequestId.make("approval-request")]),
390 isWorking: status === "waiting",
391 runningRunId: fixture.runId,
392 activeTurnStartedAt: fixture.time(0),
393 turnDiffSummaries: [],
394 supportsConversationRollback: false,
395 });
396 expect(pendingRows.filter((row) => row.kind === "work")).toContainEqual(
397 expect.objectContaining({
398 groupedEntries: [expect.objectContaining({ itemType: "approval_request" })],
399 isExpandedToolGroup: false,
400 }),
401 );
402 expect(
403 pendingRows
404 .filter((row) => row.kind === "work-live")
405 .flatMap((row) => row.groupedEntries)
406 .some((entry) => entry.itemType === "approval_request"),
407 ).toBe(false);
408 const approvalOnlyRows = deriveMessagesTimelineRows({
409 timelineEntries: entries.slice(1, 2),
410 pendingApprovalRequestIds: new Set([RuntimeRequestId.make("approval-request")]),
411 isWorking: status === "waiting",
412 runningRunId: fixture.runId,
413 activeTurnStartedAt: fixture.time(0),
414 turnDiffSummaries: [],
415 supportsConversationRollback: false,
416 });
417 expect(approvalOnlyRows.some((row) => row.kind === "thinking")).toBe(false);
418 },
419 );
420
421 it.each(["running", "completed", "superseded"] as const)(
422 "keeps system notices visible as non-failing warnings through %s work",
423 (state) => {
424 const fixture = makeStreamingTimelineFixture();
425 const message =
426 "Claude changed its safety mode.\nReview the active permission settings before continuing.";
427 const source: OrchestrationV2ProjectedTurnItem = {
428 ...fixture.visibleTurnItems[0]!,
429 sourceItemId: TurnItemId.make("safety-notice"),
430 item: {
431 id: TurnItemId.make("safety-notice"),
432 threadId: fixture.threadId,
433 runId: fixture.runId,
434 nodeId: null,
435 providerThreadId: null,
436 providerTurnId: null,
437 nativeItemRef: null,
438 parentItemId: null,
439 ordinal: 1,
440 startedAt: DateTime.makeUnsafe(fixture.time(1)),
441 completedAt: DateTime.makeUnsafe(fixture.time(1)),
442 updatedAt: DateTime.makeUnsafe(fixture.time(1)),
443 type: "system_notice",
444 message,
445 title: message,
446 status: "completed",
447 },
448 };
449 const [notice] = deriveTimelineEntriesFromVisibleTurnItems({
450 visibleTurnItems: [source],
451 optimisticMessages: [],
452 });
453 if (notice?.kind !== "work") throw new Error("Expected a notice work entry");
454 expect(notice.entry.projectedItem).toBe(source);
455 expect(notice.entry.sourceActivityKind).toBe("runtime.warning");
456 expect(workEntryDisplayLabel(notice.entry, undefined)).toBe(message);
457 expect(workEntryDisplayIndicatesToolFailure(notice.entry)).toBe(false);
458 const rows = deriveMessagesTimelineRows({
459 timelineEntries: [
460 {
461 ...notice,
462 ...(state === "superseded"
463 ? {
464 attempt: {
465 id: "old-attempt" as never,
466 runId: fixture.runId,
467 status: "superseded" as const,
468 attemptOrdinal: 0,
469 rootNodeId: "old-root" as never,
470 completedAt: null,
471 },
472 }
473 : {}),
474 },
475 {
476 id: "nearby-tool",
477 kind: "work",
478 createdAt: notice.createdAt,
479 entry: {
480 id: "nearby-tool",
481 runId: fixture.runId,
482 createdAt: notice.createdAt,
483 label: "Ran command",
484 tone: "tool",
485 toolLifecycleStatus: "completed",
486 },
487 },
488 {
489 id: "terminal-message",
490 kind: "message",
491 createdAt: notice.createdAt,
492 message: {
493 id: MessageId.make("terminal-message"),
494 runId: fixture.runId,
495 role: "assistant",
496 text: "Continuing with the selected settings.",
497 createdAt: notice.createdAt,
498 updatedAt: notice.createdAt,
499 streaming: state === "running",
500 },
501 },
502 ],
503 isWorking: state === "running",
504 activeTurnStartedAt: notice.createdAt,
505 latestRun: {
506 runId: fixture.runId,
507 status: state === "running" ? "running" : "completed",
508 startedAt: notice.createdAt,
509 completedAt: state === "running" ? null : notice.createdAt,
510 },
511 turnDiffSummaries: [],
512 supportsConversationRollback: false,
513 });
514 const row = rows.find(
515 (row) => row.kind === "work" && row.groupedEntries.includes(notice.entry),
516 );
517 expect(row).toMatchObject({ kind: "work", groupedEntries: [notice.entry] });
518 },
519 );
520
521 it.each(["info", "warning", "error", undefined] as const)(
522 "renders %s notices with compatible severity",
523 (level) => {
524 const fixture = makeStreamingTimelineFixture();
525 const message = "TPS 227.1 tok/s · TTFT 3.4s";
526 const id = TurnItemId.make("info-notice");
527 const [notice] = deriveTimelineEntriesFromVisibleTurnItems({
528 visibleTurnItems: [
529 {
530 ...fixture.visibleTurnItems[0]!,
531 sourceItemId: id,
532 item: {
533 id,
534 threadId: fixture.threadId,
535 runId: fixture.runId,
536 nodeId: null,
537 providerThreadId: null,
538 providerTurnId: null,
539 nativeItemRef: null,
540 parentItemId: null,
541 ordinal: 1,
542 startedAt: DateTime.makeUnsafe(fixture.time(1)),
543 completedAt: DateTime.makeUnsafe(fixture.time(1)),
544 updatedAt: DateTime.makeUnsafe(fixture.time(1)),
545 type: "system_notice",
546 message,
547 ...(level === undefined ? {} : { level }),
548 title: message,
549 status: "completed",
550 },
551 },
552 ],
553 optimisticMessages: [],
554 });
555 if (notice?.kind !== "work") throw new Error("Expected a notice work entry");
556 expect(notice.entry.sourceActivityKind).toBe(
557 level === "info" ? undefined : "runtime.warning",
558 );
559 expect(workEntryIconName(notice.entry)).toBe(level === "info" ? "zap" : "circle-alert");
560 expect(workEntryDisplayLabel(notice.entry, undefined)).toBe(message);
561 },
562 );
563
564 it.each([false, true])(
565 "gives live compaction the activity slot and restores Thinking (runless: %s)",
566 (runless) => {
567 const fixture = makeStreamingTimelineFixture();
568 const last = fixture.visibleTurnItems.at(-1)!;
569 if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
570 const compact = {
571 ...last,
572 item: {
573 ...last.item,
574 type: "compaction" as const,
575 status: "running" as const,
576 driver: null,
577 beforeTokenCount: 899_000,
578 },
579 };
580 const input = {
581 isWorking: true,
582 runningRunId: fixture.runId,
583 activeTurnStartedAt: fixture.time(5),
584 turnDiffSummaries: [],
585 supportsConversationRollback: false,
586 };
587 const runningEntries = deriveTimelineEntriesFromVisibleTurnItems({
588 visibleTurnItems: [...fixture.visibleTurnItems.slice(0, -1), compact],
589 optimisticMessages: [],
590 });
591 const runningRows = deriveMessagesTimelineRows({
592 ...input,
593 runningRunId: runless ? null : fixture.runId,
594 runlessWorkActive: runless,
595 timelineEntries: runless
596 ? runningEntries.map((entry) =>
597 entry.kind === "work" ? { ...entry, entry: { ...entry.entry, runId: null } } : entry,
598 )
599 : runningEntries,
600 });
601 expect(runningRows.find((row) => row.kind === "context-compaction")).toMatchObject({
602 active: true,
603 label: "Compacting context",
604 });
605 expect(runningRows.some((row) => row.kind === "thinking")).toBe(false);
606
607 const completedRows = deriveMessagesTimelineRows({
608 ...input,
609 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
610 visibleTurnItems: [
611 ...fixture.visibleTurnItems.slice(0, -1),
612 {
613 ...compact,
614 item: { ...compact.item, status: "completed", afterTokenCount: 19_000 },
615 },
616 ],
617 optimisticMessages: [],
618 }),
619 });
620 expect(completedRows.find((row) => row.kind === "context-compaction")).toMatchObject({
621 active: false,
622 label: "Context compacted 899K → 19K tokens",
623 tokenCounts: { before: "899K", after: "19K" },
624 });
625 expect(completedRows.at(-1)?.kind).toBe("thinking");
626
627 const settledRows = deriveMessagesTimelineRows({
628 ...input,
629 isWorking: false,
630 timelineEntries: runningEntries,
631 });
632 expect(settledRows.find((row) => row.kind === "context-compaction")).toMatchObject({
633 active: false,
634 });
635 const stable = computeStableMessagesTimelineRows(runningRows, {
636 result: [],
637 byId: new Map(),
638 });
639 expect(computeStableMessagesTimelineRows(settledRows, stable).result).toEqual(settledRows);
640 },
641 );
642
643 it("shows each compaction trigger as one live status, then a reasoned token divider", () => {
644 const fixture = makeStreamingTimelineFixture();
645 const [history0, history1, history2, liveUser, , liveAssistant] = fixture.visibleTurnItems;
646 if (liveUser?.item.type !== "user_message" || liveAssistant?.item.type !== "assistant_message")
647 throw new Error("Expected live fixture items");
648 const compactPrompt = (idleCompaction: "beforeCacheExpires" | "onReturn" | undefined) => ({
649 ...liveUser,
650 item: { ...liveUser.item, text: "/compact", idleCompaction },
651 });
652 const compaction = {
653 ...liveAssistant,
654 item: {
655 ...liveAssistant.item,
656 type: "compaction" as const,
657 driver: null,
658 beforeTokenCount: 899_000,
659 },
660 };
661 const rowsFor = (visibleTurnItems: OrchestrationV2ProjectedTurnItem[], isWorking = true) =>
662 deriveMessagesTimelineRows({
663 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
664 visibleTurnItems: [history0!, history1!, history2!, ...visibleTurnItems],
665 optimisticMessages: [],
666 }),
667 isWorking,
668 runningRunId: fixture.runId,
669 latestRun: {
670 runId: fixture.runId,
671 status: isWorking ? "running" : "completed",
672 startedAt: fixture.time(5),
673 completedAt: isWorking ? null : fixture.time(9),
674 },
675 activeTurnStartedAt: fixture.time(5),
676 turnDiffSummaries: [],
677 supportsConversationRollback: false,
678 });
679
680 // Only compacting on return holds a sent message back, so only it speaks through the working
681 // row; the others keep their live divider.
682 for (const [reason, live, title] of [
683 [
684 "beforeCacheExpires",
685 {
686 kind: "context-compaction",
687 active: true,
688 label: "Compacting before the cache expires…",
689 },
690 "Auto-compacted before cache expiry",
691 ],
692 ["onReturn", { kind: "working", compacting: true }, "Context compacted before sending"],
693 [undefined, { kind: "context-compaction", active: true }, undefined],
694 ] as const) {
695 const prompt = compactPrompt(reason);
696 for (const rows of [rowsFor([prompt]), rowsFor([prompt, compaction])]) {
697 const liveRows = rows.slice(
698 rows.findIndex((row) => row.id.includes("history-assistant")) + 1,
699 );
700 expect(liveRows).toMatchObject([live]);
701 }
702 const completed = rowsFor(
703 [
704 prompt,
705 {
706 ...compaction,
707 item: { ...compaction.item, status: "completed", afterTokenCount: 19_000 },
708 },
709 ],
710 false,
711 );
712 const liveRows = completed.slice(
713 completed.findIndex((row) => row.id.includes("history-assistant")) + 1,
714 );
715 expect(liveRows).toMatchObject([
716 {
717 kind: "context-compaction",
718 active: false,
719 tokenCounts: { before: "899K", after: "19K" },
720 },
721 ]);
722 expect(liveRows[0]?.kind === "context-compaction" ? liveRows[0].title : null).toBe(title);
723 const terminalCompaction = {
724 ...compaction,
725 item: { ...compaction.item, status: "completed" as const, afterTokenCount: 19_000 },
726 };
727 const finishingRows = rowsFor([prompt, terminalCompaction]);
728 const finishingLiveRows = finishingRows.slice(
729 finishingRows.findIndex((row) => row.id.includes("history-assistant")) + 1,
730 );
731 expect(finishingLiveRows).toEqual(liveRows);
732 const continuingRows = rowsFor([
733 prompt,
734 terminalCompaction,
735 { ...liveAssistant, item: { ...liveAssistant.item, id: TurnItemId.make("continued") } },
736 ]);
737 expect(continuingRows.filter((row) => row.kind === "context-compaction")).toHaveLength(1);
738 expect(continuingRows.filter((row) => row.kind === "working")).toMatchObject([
739 { kind: "working" },
740 ]);
741 expect(continuingRows.some((row) => row.kind === "working" && row.compacting)).toBe(false);
742 const retries = rowsFor(
743 [
744 prompt,
745 {
746 ...compaction,
747 item: { ...compaction.item, status: "failed", summary: "retry needed" },
748 },
749 {
750 ...compaction,
751 item: {
752 ...compaction.item,
753 id: TurnItemId.make("retry-compaction"),
754 status: "completed",
755 },
756 },
757 ],
758 false,
759 ).filter((row) => row.kind === "context-compaction");
760 expect(retries).toHaveLength(2);
761 expect(retries[0]).toMatchObject({ failed: true, failure: "retry needed" });
762 expect(new Set(retries.map((row) => row.id)).size).toBe(2);
763 const stable = computeStableMessagesTimelineRows(retries, { result: [], byId: new Map() });
764 expect(computeStableMessagesTimelineRows(retries, stable).result).toEqual(retries);
765 }
766 });
767
768 it.each(["/compact", "Continue"])(
769 "keeps a completed compaction divider visible while other settled work folds for %s",
770 (promptText) => {
771 const fixture = makeStreamingTimelineFixture();
772 const [, , , liveUser, liveWork, liveAssistant] = fixture.visibleTurnItems;
773 if (
774 liveUser?.item.type !== "user_message" ||
775 liveAssistant?.item.type !== "assistant_message" ||
776 !liveWork
777 )
778 throw new Error("Expected live fixture items");
779 const rows = deriveMessagesTimelineRows({
780 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
781 visibleTurnItems: [
782 { ...liveUser, item: { ...liveUser.item, text: promptText } },
783 liveWork,
784 {
785 ...liveAssistant,
786 item: {
787 ...liveAssistant.item,
788 type: "compaction",
789 driver: null,
790 status: "completed",
791 beforeTokenCount: 100_000,
792 afterTokenCount: 20_000,
793 },
794 },
795 ],
796 optimisticMessages: [],
797 }),
798 isWorking: false,
799 latestRun: {
800 runId: fixture.runId,
801 status: "completed",
802 startedAt: fixture.time(5),
803 completedAt: fixture.time(8),
804 },
805 turnDiffSummaries: [],
806 supportsConversationRollback: false,
807 });
808 expect(rows.filter((row) => row.kind === "turn-fold")).toHaveLength(1);
809 expect(rows.some((row) => row.kind === "work")).toBe(false);
810 expect(rows.filter((row) => row.kind === "context-compaction")).toMatchObject([
811 { active: false, tokenCounts: { before: "100K", after: "20K" } },
812 ]);
813 if (promptText === "/compact") {
814 expect(rows.some((row) => row.kind === "message")).toBe(false);
815 }
816 },
817 );
818
819 it("keeps only the latest compaction divider visible when a turn that compacted twice folds", () => {
820 const fixture = makeStreamingTimelineFixture();
821 const [, , , liveUser, liveWork, liveAssistant] = fixture.visibleTurnItems;
822 if (liveUser?.item.type !== "user_message" || liveAssistant?.item.type !== "assistant_message")
823 throw new Error("Expected live fixture items");
824 if (!liveWork) throw new Error("Expected live work");
825 const assistantItem = liveAssistant.item;
826 const compaction = (id: string, position: number, before: number, after: number) => ({
827 ...liveAssistant,
828 position,
829 sourceItemId: TurnItemId.make(id),
830 item: {
831 ...assistantItem,
832 id: TurnItemId.make(id),
833 type: "compaction" as const,
834 driver: null,
835 status: "completed" as const,
836 beforeTokenCount: before,
837 afterTokenCount: after,
838 },
839 });
840 const timelineEntries = deriveTimelineEntriesFromVisibleTurnItems({
841 visibleTurnItems: [
842 liveUser,
843 compaction("first-compaction", 4, 100_000, 20_000),
844 { ...liveWork, position: 5 },
845 compaction("second-compaction", 6, 90_000, 30_000),
846 ],
847 optimisticMessages: [],
848 });
849 const rowsFor = (expandedRunIds?: ReadonlySet<RunId>) =>
850 deriveMessagesTimelineRows({
851 timelineEntries,
852 isWorking: false,
853 latestRun: {
854 runId: fixture.runId,
855 status: "completed",
856 startedAt: fixture.time(5),
857 completedAt: fixture.time(8),
858 },
859 turnDiffSummaries: [],
860 supportsConversationRollback: false,
861 ...(expandedRunIds ? { expandedRunIds } : {}),
862 });
863 const collapsed = rowsFor();
864 expect(collapsed.filter((row) => row.kind === "turn-fold")).toHaveLength(1);
865 expect(collapsed.some((row) => row.kind === "work")).toBe(false);
866 expect(collapsed.filter((row) => row.kind === "context-compaction")).toMatchObject([
867 { tokenCounts: { before: "90K", after: "30K" } },
868 ]);
869 const expanded = rowsFor(new Set([fixture.runId]));
870 expect(expanded.filter((row) => row.kind === "context-compaction")).toMatchObject([
871 { tokenCounts: { before: "100K", after: "20K" } },
872 { tokenCounts: { before: "90K", after: "30K" } },
873 ]);
874 });
875
876 it("folds an answered compact-on-return question into its compaction row", () => {
877 const fixture = makeStreamingTimelineFixture();
878 const [history0, history1, history2, liveUser, liveWork, liveAssistant] =
879 fixture.visibleTurnItems;
880 if (liveWork?.item.type !== "dynamic_tool" || liveAssistant?.item.type !== "assistant_message")
881 throw new Error("Expected live fixture items");
882 const { toolName: _toolName, input: _input, output: _output, ...workBase } = liveWork.item;
883 const question =
884 "This session is 1h 5m old and uses 412,000 tokens. Compact it before continuing?";
885 const requestId = RuntimeRequestId.make("resume-compaction");
886 const answered = {
887 ...liveWork,
888 item: {
889 ...workBase,
890 type: "user_input_request" as const,
891 requestId,
892 questions: [],
893 questionAnswer: {
894 requestId,
895 questionTextById: { resume: question },
896 answers: { resume: "Compact and continue" },
897 attachmentsByQuestionId: {},
898 },
899 },
900 };
901 const assistantItem = liveAssistant.item;
902 // The answer can come long after the turn starts; the row times the compaction itself.
903 const compactionStartedAt = DateTime.makeUnsafe(fixture.time(65));
904 const compactionAt = (status: "running" | "completed") => ({
905 ...liveAssistant,
906 item: {
907 ...assistantItem,
908 type: "compaction" as const,
909 status,
910 driver: null,
911 startedAt: compactionStartedAt,
912 },
913 });
914 const rowsFor = (status: "running" | "completed", laterCompaction = false) =>
915 deriveMessagesTimelineRows({
916 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
917 visibleTurnItems: [
918 history0!,
919 history1!,
920 history2!,
921 liveUser!,
922 answered,
923 compactionAt(laterCompaction ? "completed" : status),
924 ...(laterCompaction
925 ? [
926 {
927 ...compactionAt(status),
928 item: {
929 ...compactionAt(status).item,
930 id: TurnItemId.make("later-compaction"),
931 },
932 },
933 ]
934 : []),
935 ],
936 optimisticMessages: [],
937 }),
938 isWorking: status === "running",
939 runningRunId: fixture.runId,
940 activeTurnStartedAt: fixture.time(5),
941 turnDiffSummaries: [],
942 supportsConversationRollback: false,
943 });
944 const liveRows = (status: "running" | "completed") => {
945 const rows = rowsFor(status);
946 return rows.slice(rows.findIndex((row) => row.id.includes("live-user")) + 1);
947 };
948 expect(liveRows("running")).toMatchObject([
949 { kind: "working", compacting: true, createdAt: DateTime.formatIso(compactionStartedAt) },
950 ]);
951 expect(liveRows("completed")).toMatchObject([
952 { kind: "context-compaction", title: "Context compacted after 1h 5m idle" },
953 ]);
954 const laterRows = rowsFor("running", true);
955 const dividers = laterRows.filter((row) => row.kind === "context-compaction");
956 expect(dividers).toHaveLength(2);
957 expect(dividers[0]).toMatchObject({
958 title: "Context compacted after 1h 5m idle",
959 active: false,
960 });
961 expect(dividers[1]).toMatchObject({ active: true });
962 expect(dividers[1]).not.toHaveProperty("title");
963 expect(laterRows.some((row) => row.kind === "working" && row.compacting !== undefined)).toBe(
964 false,
965 );
966 });
967
968 it("shows a skipped compaction as stopped, without a separate interrupted divider", () => {
969 const fixture = makeStreamingTimelineFixture();
970 const [history0, history1, history2, liveUser, , liveAssistant] = fixture.visibleTurnItems;
971 if (liveUser?.item.type !== "user_message" || liveAssistant?.item.type !== "assistant_message")
972 throw new Error("Expected live fixture items");
973 const prompt = {
974 ...liveUser,
975 item: { ...liveUser.item, text: "/compact", idleCompaction: "onReturn" as const },
976 };
977 const compaction = {
978 ...liveAssistant,
979 item: {
980 ...liveAssistant.item,
981 type: "compaction" as const,
982 status: "interrupted" as const,
983 driver: null,
984 },
985 };
986 const interruptResult = {
987 ...liveAssistant,
988 item: {
989 ...liveAssistant.item,
990 id: TurnItemId.make("interrupt-result"),
991 type: "run_interrupt_result" as const,
992 status: "interrupted" as const,
993 message: "Skipped compaction to send a queued message",
994 },
995 };
996 const liveRowsFor = (visibleTurnItems: OrchestrationV2ProjectedTurnItem[]) => {
997 const rows = deriveMessagesTimelineRows({
998 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
999 visibleTurnItems: [history0!, history1!, history2!, ...visibleTurnItems],
1000 optimisticMessages: [],
1001 }),
1002 isWorking: false,
1003 latestRun: {
1004 runId: fixture.runId,
1005 status: "interrupted",
1006 startedAt: fixture.time(5),
1007 completedAt: fixture.time(9),
1008 },
1009 turnDiffSummaries: [],
1010 supportsConversationRollback: false,
1011 });
1012 return rows.slice(rows.findIndex((row) => row.id.includes("history-assistant")) + 1);
1013 };
1014
1015 expect(liveRowsFor([prompt, compaction, interruptResult])).toMatchObject([
1016 { kind: "context-compaction", label: "Context compaction stopped" },
1017 ]);
1018 // Stopped before the provider started: no compaction row says so, so the interrupt stays.
1019 expect(liveRowsFor([prompt, interruptResult]).map((row) => row.id)).toContain(
1020 "interrupt-result",
1021 );
1022 });
1023
1024 it("only enables assistant copy for the terminal assistant message in a turn", () => {
1025 const rows = deriveMessagesTimelineRows({
1026 timelineEntries: [
1027 {
1028 id: "user-1-entry",
1029 kind: "message",
1030 createdAt: "2026-01-01T00:00:00Z",
1031 message: {
1032 id: "user-1" as never,
1033 role: "user",
1034 text: "Write a poem",
1035 runId: null,
1036 createdAt: "2026-01-01T00:00:00Z",
1037 updatedAt: "2026-01-01T00:00:00Z",
1038 streaming: false,
1039 },
1040 },
1041 {
1042 id: "assistant-thought-entry",
1043 kind: "message",
1044 createdAt: "2026-01-01T00:00:10Z",
1045 message: {
1046 id: "assistant-thought" as never,
1047 role: "assistant",
1048 text: "I should ground this first.",
1049 runId: "turn-1" as never,
1050 createdAt: "2026-01-01T00:00:10Z",
1051 updatedAt: "2026-01-01T00:00:11Z",
1052 streaming: false,
1053 },
1054 },
1055 {
1056 id: "assistant-final-entry",
1057 kind: "message",
1058 createdAt: "2026-01-01T00:00:20Z",
1059 message: {
1060 id: "assistant-final" as never,
1061 role: "assistant",
1062 text: "Here is the poem.",
1063 runId: "turn-1" as never,
1064 createdAt: "2026-01-01T00:00:20Z",
1065 updatedAt: "2026-01-01T00:00:30Z",
1066 streaming: false,
1067 },
1068 },
1069 ],
1070 expandedRunIds: new Set(["turn-1" as never]),
1071 isWorking: false,
1072 activeTurnStartedAt: null,
1073 turnDiffSummaries: [],
1074 supportsConversationRollback: false,
1075 });
1076
1077 const assistantRows = rows.filter(
1078 (row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
1079 row.kind === "message" && row.message.role === "assistant",
1080 );
1081
1082 expect(assistantRows).toHaveLength(2);
1083 expect(assistantRows[0]?.showAssistantCopyButton).toBe(false);
1084 expect(assistantRows[1]?.showAssistantCopyButton).toBe(true);
1085 });
1086
1087 it("projects assistant diffs and rewinds the first visible run to thread start after a rewind", () => {
1088 const assistantTurnDiffSummary = {
1089 runId: "turn-1" as never,
1090 completedAt: "2026-01-01T00:00:30Z",
1091 assistantMessageId: "assistant-1" as never,
1092 checkpointTurnCount: 2,
1093 checkpointRef: "checkpoint-1" as never,
1094 status: "ready" as const,
1095 files: [{ path: "src/index.ts", kind: "modified", additions: 3, deletions: 1 }],
1096 };
1097
1098 const rows = deriveMessagesTimelineRows({
1099 timelineEntries: [
1100 {
1101 id: "user-entry",
1102 kind: "message",
1103 createdAt: "2026-01-01T00:00:00Z",
1104 message: {
1105 id: "user-1" as never,
1106 role: "user",
1107 text: "Do the thing",
1108 runId: "turn-1" as never,
1109 inputIntent: "turn_start",
1110 createdAt: "2026-01-01T00:00:00Z",
1111 updatedAt: "2026-01-01T00:00:00Z",
1112 streaming: false,
1113 },
1114 },
1115 {
1116 id: "assistant-entry",
1117 kind: "message",
1118 createdAt: "2026-01-01T00:00:20Z",
1119 message: {
1120 id: "assistant-1" as never,
1121 role: "assistant",
1122 text: "Done",
1123 runId: "turn-1" as never,
1124 createdAt: "2026-01-01T00:00:20Z",
1125 updatedAt: "2026-01-01T00:00:30Z",
1126 streaming: false,
1127 },
1128 },
1129 ],
1130 isWorking: false,
1131 activeTurnStartedAt: null,
1132 turnDiffSummaries: [assistantTurnDiffSummary],
1133 supportsConversationRollback: true,
1134 threadStartCheckpointAvailable: true,
1135 });
1136
1137 const userRow = rows.find(
1138 (row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
1139 row.kind === "message" && row.message.role === "user",
1140 );
1141 const assistantRow = rows.find(
1142 (row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
1143 row.kind === "message" && row.message.role === "assistant",
1144 );
1145
1146 expect(userRow?.revertTurnCount).toBe(0);
1147 expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
1148 });
1149
1150 it("folds the first assistant message and settled work before the terminal response", () => {
1151 const timelineEntries = [
1152 {
1153 id: "user-entry",
1154 kind: "message" as const,
1155 createdAt: "2026-01-01T00:00:00Z",
1156 message: {
1157 id: "user-1" as never,
1158 role: "user" as const,
1159 text: "Build it",
1160 runId: null,
1161 createdAt: "2026-01-01T00:00:00Z",
1162 updatedAt: "2026-01-01T00:00:00Z",
1163 streaming: false,
1164 },
1165 },
1166 {
1167 id: "assistant-first-entry",
1168 kind: "message" as const,
1169 createdAt: "2026-01-01T00:00:05Z",
1170 message: {
1171 id: "assistant-first" as never,
1172 role: "assistant" as const,
1173 text: "Synthetic deployment checklist\n1. Confirm the deployment is ready.",
1174 runId: "turn-1" as never,
1175 createdAt: "2026-01-01T00:00:05Z",
1176 updatedAt: "2026-01-01T00:00:06Z",
1177 streaming: false,
1178 },
1179 },
1180 {
1181 id: "work-entry-1",
1182 kind: "work" as const,
1183 createdAt: "2026-01-01T00:00:08Z",
1184 entry: {
1185 id: "work-1",
1186 createdAt: "2026-01-01T00:00:08Z",
1187 runId: "turn-1" as never,
1188 label: "Ran command",
1189 tone: "tool" as const,
1190 },
1191 },
1192 {
1193 id: "assistant-final-entry",
1194 kind: "message" as const,
1195 createdAt: "2026-01-01T00:00:20Z",
1196 message: {
1197 id: "assistant-final" as never,
1198 role: "assistant" as const,
1199 text: "Done",
1200 runId: "turn-1" as never,
1201 createdAt: "2026-01-01T00:00:20Z",
1202 updatedAt: "2026-01-01T00:00:22Z",
1203 streaming: false,
1204 },
1205 },
1206 ];
1207
1208 const collapsedRows = deriveMessagesTimelineRows({
1209 timelineEntries,
1210 isWorking: false,
1211 activeTurnStartedAt: null,
1212 turnDiffSummaries: [],
1213 supportsConversationRollback: false,
1214 });
1215
1216 const foldRow = collapsedRows.find(
1217 (row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> =>
1218 row.kind === "turn-fold",
1219 );
1220 expect(foldRow?.runId).toBe("turn-1");
1221 expect(foldRow?.expanded).toBe(false);
1222 expect(foldRow?.label).toBe("Worked for 22s");
1223 expect(collapsedRows.map((row) => row.id)).toEqual([
1224 "user-entry",
1225 "turn-fold:turn-1",
1226 "assistant-final-entry",
1227 ]);
1228
1229 const expandedRows = deriveMessagesTimelineRows({
1230 timelineEntries,
1231 expandedRunIds: new Set(["turn-1" as never]),
1232 isWorking: false,
1233 activeTurnStartedAt: null,
1234 turnDiffSummaries: [],
1235 supportsConversationRollback: false,
1236 });
1237
1238 expect(expandedRows.map((row) => row.id)).toEqual([
1239 "user-entry",
1240 "turn-fold:turn-1",
1241 "assistant-first-entry",
1242 "work-entry-1",
1243 "assistant-final-entry",
1244 ]);
1245 expect(
1246 expandedRows.find((row) => row.kind === "turn-fold" && row.expanded === true),
1247 ).toBeDefined();
1248 });
1249
1250 it.each([1, 2, 3])("folds %i completed activities after the terminal response", (count) => {
1251 const runId = RunId.make("turn-1");
1252 const timelineEntries = [
1253 {
1254 id: "work-entry-before-text",
1255 kind: "work" as const,
1256 createdAt: "2026-01-01T00:00:01Z",
1257 entry: {
1258 id: "work-before-text",
1259 createdAt: "2026-01-01T00:00:01Z",
1260 runId,
1261 label: "Status updated",
1262 tone: "info" as const,
1263 },
1264 },
1265 {
1266 id: "assistant-final-entry",
1267 kind: "message" as const,
1268 createdAt: "2026-01-01T00:00:05Z",
1269 message: {
1270 id: "assistant-final" as never,
1271 role: "assistant" as const,
1272 text: "CI is re-running. Waiting.",
1273 runId,
1274 createdAt: "2026-01-01T00:00:05Z",
1275 updatedAt: "2026-01-01T00:00:06Z",
1276 streaming: false,
1277 },
1278 },
1279 ...Array.from({ length: count }, (_, index) => ({
1280 id: `work-entry-after-text-${index}`,
1281 kind: "work" as const,
1282 createdAt: `2026-01-01T00:00:0${index + 7}Z`,
1283 entry: {
1284 id: `work-after-text-${index}`,
1285 createdAt: `2026-01-01T00:00:0${index + 7}Z`,
1286 runId,
1287 label: "Ran command",
1288 tone: "tool" as const,
1289 itemType: "command_execution" as const,
1290 toolLifecycleStatus: "completed" as const,
1291 },
1292 })),
1293 ];
1294
1295 const input = {
1296 latestRun: {
1297 runId,
1298 status: "completed" as const,
1299 startedAt: "2026-01-01T00:00:00Z",
1300 completedAt: "2026-01-01T00:00:10Z",
1301 },
1302 isWorking: false,
1303 activeTurnStartedAt: null,
1304 turnDiffSummaries: [],
1305 supportsConversationRollback: false,
1306 };
1307 const rows = deriveMessagesTimelineRows({ ...input, timelineEntries });
1308
1309 expect(rows.map((row) => row.id)).toEqual(["turn-fold:turn-1", "assistant-final-entry"]);
1310 const expanded = deriveMessagesTimelineRows({
1311 ...input,
1312 timelineEntries,
1313 expandedRunIds: new Set([runId]),
1314 });
1315 expect(
1316 expanded.some(
1317 (row) =>
1318 row.id === "work-entry-after-text-0" ||
1319 (row.kind === "work-toggle" &&
1320 row.id === "work-toggle:work-entry-after-text-0" &&
1321 row.hiddenCount === count),
1322 ),
1323 ).toBe(true);
1324
1325 const failedEntries = timelineEntries.map((entry) =>
1326 entry.kind === "work" && entry.id === "work-entry-after-text-0"
1327 ? { ...entry, entry: { ...entry.entry, toolLifecycleStatus: "failed" as const } }
1328 : entry,
1329 );
1330 const failedRows = deriveMessagesTimelineRows({ ...input, timelineEntries: failedEntries });
1331 expect(failedRows.some((row) => row.id === "work-entry-after-text-0")).toBe(true);
1332
1333 const pendingEntries = timelineEntries.map((entry) =>
1334 entry.kind === "work" && entry.id === "work-entry-after-text-0"
1335 ? { ...entry, entry: { ...entry.entry, toolLifecycleStatus: "inProgress" as const } }
1336 : entry,
1337 );
1338 const pendingRows = deriveMessagesTimelineRows({
1339 ...input,
1340 timelineEntries: pendingEntries,
1341 latestRun: { ...input.latestRun, status: "running", completedAt: null },
1342 isWorking: true,
1343 activeTurnStartedAt: input.latestRun.startedAt,
1344 });
1345 expect(
1346 pendingRows.some((row) => row.kind === "work-live" && row.entry.id === "work-after-text-0"),
1347 ).toBe(true);
1348 });
1349
1350 it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => {
1351 const rows = deriveMessagesTimelineRows({
1352 timelineEntries: [
1353 {
1354 id: "user-entry",
1355 kind: "message",
1356 createdAt: "2026-01-01T00:00:00Z",
1357 message: {
1358 id: "user-1" as never,
1359 role: "user" as const,
1360 text: "do it once more",
1361 runId: null,
1362 createdAt: "2026-01-01T00:00:00Z",
1363 updatedAt: "2026-01-01T00:00:00Z",
1364 streaming: false,
1365 },
1366 },
1367 {
1368 id: "work-entry-before-message",
1369 kind: "work",
1370 createdAt: "2026-01-01T00:00:07Z",
1371 entry: {
1372 id: "work-before-message",
1373 createdAt: "2026-01-01T00:00:07Z",
1374 runId: "turn-1" as never,
1375 label: "Status updated",
1376 tone: "info" as const,
1377 },
1378 },
1379 {
1380 id: "assistant-commentary-entry",
1381 kind: "message",
1382 createdAt: "2026-01-01T00:00:09Z",
1383 message: {
1384 id: "assistant-commentary" as never,
1385 role: "assistant" as const,
1386 text: "Kicking off call 1.",
1387 runId: "turn-1" as never,
1388 createdAt: "2026-01-01T00:00:09Z",
1389 updatedAt: "2026-01-01T00:00:09Z",
1390 streaming: false,
1391 },
1392 },
1393 {
1394 id: "work-entry-1",
1395 kind: "work",
1396 createdAt: "2026-01-01T00:00:12Z",
1397 entry: {
1398 id: "work-1",
1399 createdAt: "2026-01-01T00:00:12Z",
1400 runId: "turn-1" as never,
1401 label: "Ran command",
1402 tone: "tool" as const,
1403 },
1404 },
1405 {
1406 id: "steer-user-entry",
1407 kind: "message",
1408 createdAt: "2026-01-01T00:00:14Z",
1409 message: {
1410 id: "user-2" as never,
1411 role: "user" as const,
1412 text: "actually do 15",
1413 runId: null,
1414 createdAt: "2026-01-01T00:00:14Z",
1415 updatedAt: "2026-01-01T00:00:14Z",
1416 streaming: false,
1417 },
1418 },
1419 {
1420 id: "assistant-next-turn-entry",
1421 kind: "message",
1422 createdAt: "2026-01-01T00:00:17Z",
1423 message: {
1424 id: "assistant-next" as never,
1425 role: "assistant" as const,
1426 text: "One down — adjusting.",
1427 runId: "turn-2" as never,
1428 createdAt: "2026-01-01T00:00:17Z",
1429 updatedAt: "2026-01-01T00:00:17Z",
1430 streaming: true,
1431 },
1432 },
1433 ],
1434 latestRun: {
1435 runId: "turn-2" as never,
1436 status: "running",
1437 startedAt: "2026-01-01T00:00:14Z",
1438 completedAt: null,
1439 },
1440 isWorking: true,
1441 activeTurnStartedAt: "2026-01-01T00:00:14Z",
1442 turnDiffSummaries: [],
1443 supportsConversationRollback: false,
1444 });
1445
1446 const foldRow = rows.find(
1447 (row): row is Extract<(typeof rows)[number], { kind: "turn-fold" }> =>
1448 row.kind === "turn-fold",
1449 );
1450 expect(foldRow?.runId).toBe("turn-1");
1451 expect(foldRow?.label).toBe("Worked for 12s");
1452 });
1453
1454 it("uses latest-turn timings and the stopped label for an interrupted latest turn", () => {
1455 const rows = deriveMessagesTimelineRows({
1456 timelineEntries: [
1457 {
1458 id: "work-entry-1",
1459 kind: "work",
1460 createdAt: "2026-01-01T00:00:05Z",
1461 entry: {
1462 id: "work-1",
1463 createdAt: "2026-01-01T00:00:05Z",
1464 runId: "turn-1" as never,
1465 label: "Ran command",
1466 tone: "tool" as const,
1467 },
1468 },
1469 ],
1470 latestRun: {
1471 runId: "turn-1" as never,
1472 status: "interrupted",
1473 startedAt: "2026-01-01T00:00:00Z",
1474 completedAt: "2026-01-01T00:00:47Z",
1475 },
1476 isWorking: false,
1477 activeTurnStartedAt: null,
1478 turnDiffSummaries: [],
1479 supportsConversationRollback: false,
1480 });
1481
1482 expect(rows).toEqual([
1483 expect.objectContaining({
1484 kind: "turn-fold",
1485 runId: "turn-1",
1486 label: "You stopped after 47s",
1487 expanded: false,
1488 }),
1489 ]);
1490 });
1491
1492 it.each(["steer", "promoted_queued_to_steer"] as const)(
1493 "keeps the duration header at the initiating prompt when %s arrives before output",
1494 (inputIntent) => {
1495 const runId = RunId.make("steered-run");
1496 const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString();
1497 const prompt = (id: string, second: number, intent: "turn_start" | typeof inputIntent) => ({
1498 kind: "message" as const,
1499 id,
1500 createdAt: time(second),
1501 message: {
1502 id: MessageId.make(id),
1503 role: "user" as const,
1504 text: id,
1505 runId,
1506 inputIntent: intent,
1507 createdAt: time(second),
1508 updatedAt: time(second),
1509 streaming: false,
1510 },
1511 });
1512 const entries = [prompt("initial-prompt", 0, "turn_start"), prompt("steer", 5, inputIntent)];
1513 const work = {
1514 kind: "work" as const,
1515 id: "work",
1516 createdAt: time(8),
1517 entry: {
1518 id: "work",
1519 createdAt: time(8),
1520 runId,
1521 label: "Ran command",
1522 tone: "tool" as const,
1523 },
1524 };
1525 const final = {
1526 kind: "message" as const,
1527 id: "final",
1528 createdAt: time(20),
1529 message: {
1530 id: MessageId.make("final"),
1531 role: "assistant" as const,
1532 text: "Done",
1533 runId,
1534 createdAt: time(20),
1535 updatedAt: time(20),
1536 streaming: false,
1537 },
1538 };
1539 for (const isWorking of [true, false]) {
1540 for (const expanded of [true, false]) {
1541 const rows = deriveMessagesTimelineRows({
1542 timelineEntries: [...entries, work, final],
1543 latestRun: {
1544 runId,
1545 status: isWorking ? "running" : "completed",
1546 startedAt: time(0),
1547 completedAt: isWorking ? null : time(20),
1548 },
1549 isWorking,
1550 activeTurnStartedAt: time(0),
1551 expandedRunIds: expanded ? new Set([runId]) : new Set(),
1552 turnDiffSummaries: [],
1553 supportsConversationRollback: false,
1554 });
1555 expect(rows.slice(0, 3).map((row) => row.id)).toEqual([
1556 "initial-prompt",
1557 isWorking ? "working-indicator-row" : `turn-fold:${runId}`,
1558 "steer",
1559 ]);
1560 expect(rows[1]?.createdAt).toBe(time(0));
1561 if (!isWorking) expect(rows[1]).toMatchObject({ label: "Worked for 20s", expanded });
1562 expect(rows.some((row) => row.id === "final")).toBe(true);
1563 expect(rows.some((row) => row.id === "work")).toBe(isWorking || expanded);
1564 }
1565 }
1566 },
1567 );
1568
1569 it("splits a settled turn's work at each steer and keeps the total time on top", () => {
1570 const runId = RunId.make("steered-run");
1571 const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString();
1572 const message = (
1573 id: string,
1574 second: number,
1575 role: "user" | "assistant",
1576 inputIntent?: "turn_start" | "steer",
1577 ): TimelineEntry => ({
1578 kind: "message",
1579 id,
1580 createdAt: time(second),
1581 message: {
1582 id: MessageId.make(id),
1583 role,
1584 text: id,
1585 runId,
1586 ...(inputIntent ? { inputIntent } : {}),
1587 createdAt: time(second),
1588 updatedAt: time(second),
1589 streaming: false,
1590 },
1591 });
1592 const work = (id: string, second: number): TimelineEntry => ({
1593 kind: "work",
1594 id,
1595 createdAt: time(second),
1596 entry: { id, createdAt: time(second), runId, label: "Ran command", tone: "tool" },
1597 });
1598 const rows = (expandedRunIds: ReadonlySet<RunId>) =>
1599 deriveMessagesTimelineRows({
1600 timelineEntries: [
1601 message("prompt", 0, "user", "turn_start"),
1602 work("work-before-steer", 4),
1603 message("steer", 10, "user", "steer"),
1604 work("work-after-steer", 15),
1605 message("final", 30, "assistant"),
1606 {
1607 kind: "event",
1608 id: "late-subagent",
1609 createdAt: time(50),
1610 projectedItem: { item: { type: "subagent", status: "completed", runId } } as never,
1611 },
1612 ],
1613 // A later wake run is the latest, so this turn's times come from its entries.
1614 latestRun: {
1615 runId: RunId.make("wake-run"),
1616 status: "completed",
1617 startedAt: time(55),
1618 completedAt: time(58),
1619 },
1620 isWorking: false,
1621 expandedRunIds,
1622 turnDiffSummaries: [],
1623 supportsConversationRollback: false,
1624 });
1625
1626 const segmentKey = RunId.make(`${runId}:steer:steer`);
1627 const collapsed = rows(new Set());
1628 expect(collapsed.map((row) => row.id)).toEqual([
1629 "prompt",
1630 `turn-fold:${runId}`,
1631 "steer",
1632 `turn-fold:${segmentKey}`,
1633 "final",
1634 "late-subagent",
1635 ]);
1636 expect(collapsed[1]).toMatchObject({ label: "Worked for 30s" });
1637 expect(collapsed[3]).toMatchObject({ label: "Continued for 20s", createdAt: time(10) });
1638
1639 expect(rows(new Set([segmentKey])).map((row) => row.id)).toEqual([
1640 "prompt",
1641 `turn-fold:${runId}`,
1642 "steer",
1643 `turn-fold:${segmentKey}`,
1644 "work-after-steer",
1645 "final",
1646 "late-subagent",
1647 ]);
1648 });
1649
1650 it("stacks back-to-back steers as one burst with a single steer label", () => {
1651 const runId = RunId.make("double-steer-run");
1652 const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString();
1653 const message = (
1654 id: string,
1655 second: number,
1656 role: "user" | "assistant",
1657 inputIntent?: "turn_start" | "steer",
1658 ): TimelineEntry => ({
1659 kind: "message",
1660 id,
1661 createdAt: time(second),
1662 message: {
1663 id: MessageId.make(id),
1664 role,
1665 text: id,
1666 runId,
1667 ...(inputIntent ? { inputIntent } : {}),
1668 createdAt: time(second),
1669 updatedAt: time(second),
1670 streaming: false,
1671 },
1672 });
1673 const prompt = message("prompt", 0, "user", "turn_start");
1674 const work: TimelineEntry = {
1675 kind: "work",
1676 id: "work",
1677 createdAt: time(4),
1678 entry: { id: "work", createdAt: time(4), runId, label: "Ran command", tone: "tool" },
1679 };
1680 const firstSteer = message("first-steer", 10, "user", "steer");
1681 const deriveRows = (timelineEntries: TimelineEntry[]) =>
1682 deriveMessagesTimelineRows({
1683 timelineEntries,
1684 latestRun: { runId, status: "completed", startedAt: time(0), completedAt: time(30) },
1685 isWorking: false,
1686 expandedRunIds: new Set(),
1687 turnDiffSummaries: [],
1688 supportsConversationRollback: false,
1689 });
1690 // The second steer arrives while the first message object is reused, as live updates do.
1691 const before = computeStableMessagesTimelineRows(deriveRows([prompt, work, firstSteer]), {
1692 result: [],
1693 byId: new Map(),
1694 });
1695 const rows = computeStableMessagesTimelineRows(
1696 deriveRows([
1697 prompt,
1698 work,
1699 firstSteer,
1700 message("second-steer", 12, "user", "steer"),
1701 message("final", 30, "assistant"),
1702 ]),
1703 before,
1704 ).result;
1705
1706 const byId = new Map(rows.map((row) => [row.id, row]));
1707 expect(byId.get("prompt")).not.toHaveProperty("groupedWithNext");
1708 expect(byId.get("first-steer")).toMatchObject({
1709 groupedWithNext: true,
1710 groupedWithPrevious: false,
1711 continuesSteer: false,
1712 });
1713 expect(byId.get("second-steer")).toMatchObject({
1714 groupedWithNext: false,
1715 groupedWithPrevious: true,
1716 continuesSteer: true,
1717 });
1718 });
1719
1720 it("keeps the previous turn folded while a newly sent message awaits its turn", () => {
1721 const rows = deriveMessagesTimelineRows({
1722 timelineEntries: [
1723 {
1724 id: "work-entry-1",
1725 kind: "work",
1726 createdAt: "2026-01-01T00:00:05Z",
1727 entry: {
1728 id: "work-1",
1729 createdAt: "2026-01-01T00:00:05Z",
1730 runId: "turn-1" as never,
1731 label: "Ran command",
1732 tone: "tool" as const,
1733 },
1734 },
1735 {
1736 id: "assistant-final-entry",
1737 kind: "message",
1738 createdAt: "2026-01-01T00:00:20Z",
1739 message: {
1740 id: "assistant-final" as never,
1741 role: "assistant",
1742 text: "Done",
1743 runId: "turn-1" as never,
1744 createdAt: "2026-01-01T00:00:20Z",
1745 updatedAt: "2026-01-01T00:00:22Z",
1746 streaming: false,
1747 },
1748 },
1749 {
1750 id: "user-followup-entry",
1751 kind: "message",
1752 createdAt: "2026-01-01T00:01:00Z",
1753 message: {
1754 id: "user-followup" as never,
1755 role: "user",
1756 text: "yooo",
1757 runId: null,
1758 createdAt: "2026-01-01T00:01:00Z",
1759 updatedAt: "2026-01-01T00:01:00Z",
1760 streaming: false,
1761 },
1762 },
1763 ],
1764 latestRun: {
1765 runId: "turn-1" as never,
1766 status: "completed",
1767 startedAt: "2026-01-01T00:00:00Z",
1768 completedAt: "2026-01-01T00:00:22Z",
1769 },
1770 isWorking: true,
1771 activeTurnStartedAt: "2026-01-01T00:01:00Z",
1772 turnDiffSummaries: [],
1773 supportsConversationRollback: false,
1774 });
1775
1776 expect(rows.map((row) => row.id)).toEqual([
1777 "turn-fold:turn-1",
1778 "assistant-final-entry",
1779 "user-followup-entry",
1780 "working-indicator-row",
1781 "live-activity-row",
1782 ]);
1783 const finalRow = rows.find((row) => row.id === "assistant-final-entry");
1784 expect(finalRow?.kind === "message" && finalRow.showAssistantMeta).toBe(true);
1785 expect(rows.at(-1)).toMatchObject({ kind: "thinking" });
1786 });
1787
1788 it("does not show Thinking once the open run's provider turn has ended", () => {
1789 const input = {
1790 timelineEntries: [
1791 {
1792 id: "user-entry",
1793 kind: "message" as const,
1794 createdAt: "2026-01-01T00:00:00Z",
1795 message: {
1796 id: "user" as never,
1797 role: "user" as const,
1798 text: "Take over the queue",
1799 runId: "turn-1" as never,
1800 createdAt: "2026-01-01T00:00:00Z",
1801 updatedAt: "2026-01-01T00:00:00Z",
1802 streaming: false,
1803 },
1804 },
1805 ],
1806 latestRun: {
1807 runId: "turn-1" as never,
1808 status: "running" as const,
1809 startedAt: "2026-01-01T00:00:00Z",
1810 completedAt: null,
1811 },
1812 isWorking: true,
1813 activeTurnStartedAt: "2026-01-01T00:00:00Z",
1814 turnDiffSummaries: [],
1815 supportsConversationRollback: false,
1816 };
1817
1818 expect(deriveMessagesTimelineRows(input).at(-1)?.kind).toBe("thinking");
1819 const ended = deriveMessagesTimelineRows({
1820 ...input,
1821 latestRun: { ...input.latestRun, turnEnded: true },
1822 });
1823 expect(ended.some((row) => row.kind === "thinking")).toBe(false);
1824 });
1825
1826 it("keeps a promptless restart in one active visual response", () => {
1827 const rows = deriveMessagesTimelineRows({
1828 timelineEntries: [
1829 {
1830 id: "user-entry",
1831 kind: "message",
1832 createdAt: "2026-01-01T00:00:00Z",
1833 message: {
1834 id: "user-1" as never,
1835 role: "user",
1836 text: "keep going",
1837 runId: null,
1838 createdAt: "2026-01-01T00:00:00Z",
1839 updatedAt: "2026-01-01T00:00:00Z",
1840 streaming: false,
1841 },
1842 },
1843 {
1844 id: "old-work-entry",
1845 kind: "work",
1846 createdAt: "2026-01-01T00:00:05Z",
1847 entry: {
1848 id: "old-work",
1849 createdAt: "2026-01-01T00:00:05Z",
1850 runId: "turn-before-restart" as never,
1851 label: "Searched files",
1852 command: "rg restart",
1853 tone: "tool" as const,
1854 toolLifecycleStatus: "completed" as const,
1855 },
1856 },
1857 {
1858 id: "old-stale-work-entry",
1859 kind: "work",
1860 createdAt: "2026-01-01T00:00:06Z",
1861 entry: {
1862 id: "old-stale-work",
1863 createdAt: "2026-01-01T00:00:06Z",
1864 runId: "turn-before-restart" as never,
1865 label: "Running stale command",
1866 command: "rg stale",
1867 tone: "tool" as const,
1868 toolLifecycleStatus: "inProgress" as const,
1869 },
1870 },
1871 {
1872 id: "old-commentary-entry",
1873 kind: "message",
1874 createdAt: "2026-01-01T00:00:08Z",
1875 message: {
1876 id: "old-commentary" as never,
1877 role: "assistant",
1878 text: "the server restarted, continuing here.",
1879 runId: "turn-before-restart" as never,
1880 createdAt: "2026-01-01T00:00:08Z",
1881 updatedAt: "2026-01-01T00:00:08Z",
1882 streaming: false,
1883 },
1884 },
1885 {
1886 id: "new-work-entry",
1887 kind: "work",
1888 createdAt: "2026-01-01T00:01:05Z",
1889 entry: {
1890 id: "new-work",
1891 createdAt: "2026-01-01T00:01:05Z",
1892 runId: "turn-after-restart" as never,
1893 label: "Running tests",
1894 command: "vp test run",
1895 tone: "tool" as const,
1896 toolLifecycleStatus: "inProgress" as const,
1897 },
1898 },
1899 ],
1900 latestRun: {
1901 runId: "turn-after-restart" as never,
1902 status: "running",
1903 startedAt: "2026-01-01T00:01:00Z",
1904 completedAt: null,
1905 },
1906 isWorking: true,
1907 activeTurnStartedAt: "2026-01-01T00:01:00Z",
1908 turnDiffSummaries: [],
1909 supportsConversationRollback: false,
1910 });
1911
1912 expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
1913 expect(rows.filter((row) => row.id === "working-indicator-row")).toHaveLength(1);
1914 expect(rows.findIndex((row) => row.id === "working-indicator-row")).toBeLessThan(
1915 rows.findIndex((row) => row.id === "old-work-entry"),
1916 );
1917 expect(rows.find((row) => row.id === "working-indicator-row")).toMatchObject({
1918 createdAt: "2026-01-01T00:01:00Z",
1919 });
1920 expect(rows.find((row) => row.id === "old-commentary-entry")).toMatchObject({
1921 showAssistantMeta: false,
1922 showAssistantCopyButton: false,
1923 assistantCopyStreaming: true,
1924 });
1925 expect(rows.filter((row) => row.kind === "work-live" && row.active)).toEqual([
1926 expect.objectContaining({ entry: expect.objectContaining({ id: "new-work" }) }),
1927 ]);
1928 expect(rows.some((row) => row.kind === "thinking")).toBe(false);
1929 });
1930
1931 it("carries the latest thought on the live row while a later tool runs", () => {
1932 type WorkEntry = Extract<
1933 Parameters<typeof deriveMessagesTimelineRows>[0]["timelineEntries"][number],
1934 { kind: "work" }
1935 >;
1936 const work = (
1937 id: string,
1938 at: string,
1939 fields: Omit<WorkEntry["entry"], "id" | "createdAt" | "runId" | "label">,
1940 ): WorkEntry => ({
1941 id: `${id}-entry`,
1942 kind: "work",
1943 createdAt: at,
1944 entry: { id, createdAt: at, runId: "turn-1" as never, label: id, ...fields },
1945 });
1946 const rows = deriveMessagesTimelineRows({
1947 timelineEntries: [
1948 work("old-thought", "2026-01-01T00:00:01Z", {
1949 itemType: "reasoning",
1950 detail: "First idea.",
1951 tone: "thinking" as const,
1952 toolLifecycleStatus: "completed" as const,
1953 }),
1954 work("new-thought", "2026-01-01T00:00:02Z", {
1955 itemType: "reasoning",
1956 detail: "Found the cause.",
1957 tone: "thinking" as const,
1958 toolLifecycleStatus: "completed" as const,
1959 }),
1960 work("running-command", "2026-01-01T00:00:03Z", {
1961 command: "rg cause",
1962 requestKind: "command",
1963 tone: "tool" as const,
1964 toolLifecycleStatus: "inProgress" as const,
1965 }),
1966 ],
1967 latestRun: {
1968 runId: "turn-1" as never,
1969 status: "running",
1970 startedAt: "2026-01-01T00:00:00Z",
1971 completedAt: null,
1972 },
1973 isWorking: true,
1974 activeTurnStartedAt: "2026-01-01T00:00:00Z",
1975 turnDiffSummaries: [],
1976 supportsConversationRollback: false,
1977 });
1978
1979 expect(rows.find((row) => row.kind === "work-live")).toMatchObject({
1980 entry: { id: "running-command" },
1981 thought: { id: "new-thought" },
1982 });
1983 });
1984
1985 it("keeps an actually running tool in the shared activity row", () => {
1986 const rows = deriveMessagesTimelineRows({
1987 timelineEntries: [
1988 {
1989 id: "running-command-entry",
1990 kind: "work",
1991 createdAt: "2026-01-01T00:00:05Z",
1992 entry: {
1993 id: "running-command",
1994 createdAt: "2026-01-01T00:00:05Z",
1995 runId: "turn-1" as never,
1996 label: "Running rg",
1997 command: "rg toolCall",
1998 requestKind: "command",
1999 tone: "tool" as const,
2000 toolLifecycleStatus: "inProgress" as const,
2001 },
2002 },
2003 {
2004 id: "completed-edit-entry",
2005 kind: "work",
2006 createdAt: "2026-01-01T00:00:06Z",
2007 entry: {
2008 id: "completed-edit",
2009 createdAt: "2026-01-01T00:00:06Z",
2010 runId: "turn-1" as never,
2011 label: "Edited files",
2012 requestKind: "file-change",
2013 changedFiles: ["src/one.ts", "src/two.ts"],
2014 tone: "tool" as const,
2015 toolLifecycleStatus: "completed" as const,
2016 },
2017 },
2018 {
2019 id: "completed-command-entry",
2020 kind: "work",
2021 createdAt: "2026-01-01T00:00:07Z",
2022 entry: {
2023 id: "completed-command",
2024 createdAt: "2026-01-01T00:00:07Z",
2025 runId: "turn-1" as never,
2026 label: "Ran tests",
2027 command: "vp test run",
2028 requestKind: "command",
2029 tone: "tool" as const,
2030 toolLifecycleStatus: "completed" as const,
2031 },
2032 },
2033 ],
2034 latestRun: {
2035 runId: "turn-1" as never,
2036 status: "running",
2037 startedAt: "2026-01-01T00:00:00Z",
2038 completedAt: null,
2039 },
2040 isWorking: true,
2041 activeTurnStartedAt: "2026-01-01T00:00:00Z",
2042 turnDiffSummaries: [],
2043 supportsConversationRollback: false,
2044 });
2045
2046 expect(rows.map((row) => row.kind)).toEqual(["working", "work-live"]);
2047 expect(rows.some((row) => row.kind === "thinking")).toBe(false);
2048 expect(rows.find((row) => row.kind === "work-live")).toMatchObject({
2049 entry: { id: "running-command" },
2050 active: true,
2051 groupedEntries: [
2052 { id: "running-command" },
2053 { id: "completed-edit" },
2054 { id: "completed-command" },
2055 ],
2056 });
2057 });
2058
2059 it("folds each run of a provider-native subagent thread like a normal turn", () => {
2060 const threadId = ThreadId.make("subagent-child");
2061 const rootNodeId = NodeId.make("task-root");
2062 const at = (second: number) =>
2063 DateTime.makeUnsafe(new Date(Date.UTC(2026, 8, 25, 22, 51, second)).toISOString());
2064 const base = (id: string, ordinal: number, second: number, endSecond = second) => ({
2065 id: TurnItemId.make(id),
2066 threadId,
2067 runId: null,
2068 nodeId: rootNodeId,
2069 providerThreadId: null,
2070 providerTurnId: null,
2071 nativeItemRef: null,
2072 parentItemId: null,
2073 ordinal,
2074 status: "completed" as const,
2075 title: null,
2076 startedAt: at(second),
2077 completedAt: at(endSecond),
2078 updatedAt: at(endSecond),
2079 });
2080 const prompt = (id: string, ordinal: number, second: number) => ({
2081 ...base(id, ordinal, second),
2082 type: "user_message" as const,
2083 messageId: MessageId.make(id),
2084 text: `Prompt ${id}`,
2085 attachments: [],
2086 inputIntent: "turn_start" as const,
2087 createdBy: "agent" as const,
2088 creationSource: "provider" as const,
2089 });
2090 const answer = (id: string, ordinal: number, second: number) => ({
2091 ...base(id, ordinal, second),
2092 type: "assistant_message" as const,
2093 messageId: MessageId.make(id),
2094 text: `Answer ${id}`,
2095 streaming: false,
2096 });
2097 type ResumeState = "running" | "completed" | "failed";
2098 const items = (resume: ResumeState) =>
2099 [
2100 prompt("launch", 1, 0),
2101 { ...base("launch-ls", 2, 4), type: "command_execution" as const, input: "ls src" },
2102 {
2103 ...base("launch-thinking", 3, 8),
2104 type: "reasoning" as const,
2105 title: "Thinking",
2106 text: "Not there.",
2107 streaming: false,
2108 },
2109 answer("launch-answer", 4, 8),
2110 prompt("resume", 5, 72),
2111 {
2112 ...base("resume-ls", 6, 77),
2113 type: "command_execution" as const,
2114 input: "ls src",
2115 status: resume === "running" ? ("running" as const) : ("completed" as const),
2116 completedAt: resume === "running" ? null : at(77),
2117 },
2118 ...(resume === "failed"
2119 ? [
2120 {
2121 ...base("resume-error", 7, 80),
2122 type: "error" as const,
2123 status: "failed" as const,
2124 failure: {
2125 class: "provider_error" as const,
2126 message: "Subagent failed",
2127 code: null,
2128 retryable: null,
2129 },
2130 },
2131 ]
2132 : []),
2133 ...(resume === "running" ? [] : [answer("resume-answer", 8, 80)]),
2134 ].map((item, position) => ({
2135 position,
2136 visibility: "local" as const,
2137 sourceThreadId: threadId,
2138 sourceItemId: item.id,
2139 item,
2140 }));
2141 const rows = (input: {
2142 resume: ResumeState;
2143 working: boolean;
2144 expandedRunIds?: ReadonlySet<RunId>;
2145 }) =>
2146 deriveMessagesTimelineRows({
2147 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
2148 visibleTurnItems: items(input.resume),
2149 optimisticMessages: [],
2150 }),
2151 latestRun: null,
2152 isWorking: input.working,
2153 runlessWorkActive: input.working,
2154 ...(input.expandedRunIds === undefined ? {} : { expandedRunIds: input.expandedRunIds }),
2155 activeTurnStartedAt: input.working ? DateTime.formatIso(at(72)) : null,
2156 turnDiffSummaries: [],
2157 supportsConversationRollback: false,
2158 });
2159 const shape = (timeline: ReadonlyArray<MessagesTimelineRow>) =>
2160 timeline.map((row) =>
2161 row.kind === "turn-fold"
2162 ? `fold:${row.label}`
2163 : row.kind === "message"
2164 ? `${row.message.role}:${row.message.id}`
2165 : row.kind,
2166 );
2167
2168 const settled = rows({ resume: "completed", working: false });
2169 expect(shape(settled)).toEqual([
2170 "user:launch",
2171 "fold:Worked for 8s",
2172 "assistant:launch-answer",
2173 "user:resume",
2174 "fold:Worked for 8s",
2175 "assistant:resume-answer",
2176 ]);
2177
2178 const launchFold = settled.find((row) => row.kind === "turn-fold");
2179 if (launchFold?.kind !== "turn-fold") throw new Error("Expected the launch fold");
2180 const expanded = rows({
2181 resume: "completed",
2182 working: false,
2183 expandedRunIds: new Set([launchFold.runId]),
2184 });
2185 expect(shape(expanded)).toEqual([
2186 "user:launch",
2187 "fold:Worked for 8s",
2188 "work-toggle",
2189 "assistant:launch-answer",
2190 "user:resume",
2191 "fold:Worked for 8s",
2192 "assistant:resume-answer",
2193 ]);
2194
2195 expect(shape(rows({ resume: "running", working: true }))).toEqual([
2196 "user:launch",
2197 "fold:Worked for 8s",
2198 "assistant:launch-answer",
2199 "user:resume",
2200 "working",
2201 "work-live",
2202 ]);
2203
2204 expect(shape(rows({ resume: "failed", working: false }))).toEqual([
2205 "user:launch",
2206 "fold:Worked for 8s",
2207 "assistant:launch-answer",
2208 "user:resume",
2209 "work",
2210 "work",
2211 "assistant:resume-answer",
2212 ]);
2213 });
2214
2215 it("keeps answered questions in their own row outside tool groups and turn folds", () => {
2216 const threadId = ThreadId.make("answered-question-thread");
2217 const runId = RunId.make("answered-question-run");
2218 const requestId = RuntimeRequestId.make("scope-question");
2219 const at = (second: number) =>
2220 DateTime.makeUnsafe(new Date(Date.UTC(2026, 9, 17, 12, 0, second)).toISOString());
2221 const base = (id: string, ordinal: number, second: number) => ({
2222 id: TurnItemId.make(id),
2223 threadId,
2224 runId,
2225 nodeId: null,
2226 providerThreadId: null,
2227 providerTurnId: null,
2228 nativeItemRef: null,
2229 parentItemId: null,
2230 ordinal,
2231 status: "completed" as const,
2232 title: null,
2233 startedAt: at(second),
2234 completedAt: at(second),
2235 updatedAt: at(second),
2236 });
2237 const command = (id: string, ordinal: number, second: number) => ({
2238 ...base(id, ordinal, second),
2239 type: "command_execution" as const,
2240 input: `cat ${id}`,
2241 });
2242 const items = (settled: boolean) =>
2243 [
2244 {
2245 ...base("prompt", 0, 0),
2246 type: "user_message" as const,
2247 messageId: MessageId.make("prompt"),
2248 text: "Pick a repository",
2249 attachments: [],
2250 inputIntent: "turn_start" as const,
2251 createdBy: "user" as const,
2252 creationSource: "web" as const,
2253 },
2254 command("before", 1, 1),
2255 {
2256 ...base("question", 2, 2),
2257 type: "user_input_request" as const,
2258 requestId,
2259 questions: [],
2260 questionAnswer: {
2261 requestId,
2262 questionTextById: { scope: "Which repository?" },
2263 answers: { scope: "The private one" },
2264 attachmentsByQuestionId: {},
2265 },
2266 },
2267 command("after", 3, 3),
2268 settled
2269 ? {
2270 ...base("answer", 4, 5),
2271 type: "assistant_message" as const,
2272 messageId: MessageId.make("answer"),
2273 text: "Done",
2274 streaming: false,
2275 }
2276 : { ...command("running", 4, 4), status: "running" as const, completedAt: null },
2277 ].map((item, position) => ({
2278 position,
2279 visibility: "local" as const,
2280 sourceThreadId: threadId,
2281 sourceItemId: item.id,
2282 item,
2283 }));
2284 const rows = (settled: boolean, expandedRunIds?: ReadonlySet<RunId>) =>
2285 deriveMessagesTimelineRows({
2286 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
2287 visibleTurnItems: items(settled),
2288 optimisticMessages: [],
2289 }),
2290 latestRun: {
2291 runId,
2292 status: settled ? "completed" : "running",
2293 startedAt: DateTime.formatIso(at(0)),
2294 completedAt: settled ? DateTime.formatIso(at(5)) : null,
2295 },
2296 runningRunId: settled ? null : runId,
2297 isWorking: !settled,
2298 activeTurnStartedAt: settled ? null : DateTime.formatIso(at(0)),
2299 ...(expandedRunIds === undefined ? {} : { expandedRunIds }),
2300 turnDiffSummaries: [],
2301 supportsConversationRollback: false,
2302 });
2303 const shape = (timeline: ReadonlyArray<MessagesTimelineRow>) =>
2304 timeline.map((row) =>
2305 row.kind === "turn-fold"
2306 ? "fold"
2307 : row.kind === "message"
2308 ? `${row.message.role}:${row.message.id}`
2309 : row.kind === "work" || row.kind === "work-live"
2310 ? `${row.kind}:${row.groupedEntries.map((entry) => entry.id).join(" + ")}`
2311 : row.kind,
2312 );
2313
2314 expect(shape(rows(true))).toEqual(["user:prompt", "fold", "work:question", "assistant:answer"]);
2315 expect(shape(rows(true, new Set([runId])))).toEqual([
2316 "user:prompt",
2317 "fold",
2318 "work:before",
2319 "work:question",
2320 "work:after",
2321 "assistant:answer",
2322 ]);
2323 expect(shape(rows(false))).toEqual([
2324 "user:prompt",
2325 "working",
2326 "work:before",
2327 "work:question",
2328 "work-live:after + running",
2329 ]);
2330 });
2331
2332 it("shows images the agent viewed outside their collapsed tool group", () => {
2333 const threadId = ThreadId.make("viewed-images-thread");
2334 const runId = RunId.make("viewed-images-run");
2335 const at = (second: number) =>
2336 DateTime.makeUnsafe(new Date(Date.UTC(2026, 10, 4, 12, 0, second)).toISOString());
2337 const base = (id: string, ordinal: number) => ({
2338 id: TurnItemId.make(id),
2339 threadId,
2340 runId,
2341 nodeId: null,
2342 providerThreadId: null,
2343 providerTurnId: null,
2344 nativeItemRef: null,
2345 parentItemId: null,
2346 ordinal,
2347 status: "completed" as const,
2348 title: null,
2349 startedAt: at(ordinal),
2350 completedAt: at(ordinal),
2351 updatedAt: at(ordinal),
2352 });
2353 const read = (id: string, ordinal: number, filePath: string) => ({
2354 ...base(id, ordinal),
2355 type: "dynamic_tool" as const,
2356 toolName: "Read",
2357 // The Claude adapter tags reads of image files.
2358 ...(filePath.endsWith(".png") ? { viewedImagePath: filePath } : {}),
2359 input: { file_path: filePath },
2360 });
2361 const items = (settled: boolean) =>
2362 [
2363 {
2364 ...base("prompt", 0),
2365 type: "user_message" as const,
2366 messageId: MessageId.make("prompt"),
2367 text: "Show me the mockups",
2368 attachments: [],
2369 inputIntent: "turn_start" as const,
2370 createdBy: "user" as const,
2371 creationSource: "web" as const,
2372 },
2373 read("read-sidebar", 1, "/repo/docs/sidebar.png"),
2374 read("read-notes", 2, "/repo/docs/notes.md"),
2375 read("read-sidebar-again", 3, "/repo/docs/sidebar.png"),
2376 read("read-topbar", 4, "/repo/docs/topbar.png"),
2377 settled
2378 ? {
2379 ...base("answer", 5),
2380 type: "assistant_message" as const,
2381 messageId: MessageId.make("answer"),
2382 text: "Here are both layouts",
2383 streaming: false,
2384 }
2385 : {
2386 ...base("ask-again", 5),
2387 status: "waiting" as const,
2388 completedAt: null,
2389 type: "user_input_request" as const,
2390 requestId: RuntimeRequestId.make("layout-question"),
2391 questions: [],
2392 },
2393 ].map((item, position) => ({
2394 position,
2395 visibility: "local" as const,
2396 sourceThreadId: threadId,
2397 sourceItemId: item.id,
2398 item,
2399 }));
2400 const viewedImages = (settled: boolean, expandedRunIds?: ReadonlySet<RunId>) => {
2401 const rows = deriveMessagesTimelineRows({
2402 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
2403 visibleTurnItems: items(settled),
2404 optimisticMessages: [],
2405 }),
2406 latestRun: {
2407 runId,
2408 status: settled ? "completed" : "running",
2409 startedAt: DateTime.formatIso(at(0)),
2410 completedAt: settled ? DateTime.formatIso(at(5)) : null,
2411 },
2412 runningRunId: settled ? null : runId,
2413 isWorking: !settled,
2414 activeTurnStartedAt: settled ? null : DateTime.formatIso(at(0)),
2415 ...(expandedRunIds === undefined ? {} : { expandedRunIds }),
2416 turnDiffSummaries: [],
2417 supportsConversationRollback: false,
2418 });
2419 return rows.flatMap((row, index) =>
2420 row.kind === "viewed-images" ? [{ after: rows[index - 1]?.kind, paths: row.paths }] : [],
2421 );
2422 };
2423 const paths = ["/repo/docs/sidebar.png", "/repo/docs/topbar.png"];
2424
2425 expect(viewedImages(false)).toEqual([{ after: "work-live", paths }]);
2426 // A settled turn's fold keeps hiding its work, images included, until it is opened.
2427 expect(viewedImages(true)).toEqual([]);
2428 expect(viewedImages(true, new Set([runId]))).toEqual([{ after: "work-toggle", paths }]);
2429 });
2430
2431 it("keeps imported V1 turns folded once the thread's first V2 run starts", () => {
2432 const at = (second: number) => `2026-01-01T00:00:${String(second).padStart(2, "0")}Z`;
2433 const message = (
2434 id: string,
2435 role: "user" | "assistant",
2436 second: number,
2437 runId: string | null = null,
2438 ) => ({
2439 id,
2440 kind: "message" as const,
2441 createdAt: at(second),
2442 message: {
2443 id: id as never,
2444 role,
2445 text: id,
2446 runId: runId as never,
2447 createdAt: at(second),
2448 updatedAt: at(second),
2449 streaming: false,
2450 },
2451 });
2452 const rows = (tail: ReadonlyArray<ReturnType<typeof message>>) =>
2453 deriveMessagesTimelineRows({
2454 timelineEntries: [
2455 message("imported-prompt", "user", 0),
2456 message("imported-update", "assistant", 4),
2457 {
2458 id: "imported-command",
2459 kind: "work",
2460 createdAt: at(5),
2461 entry: {
2462 id: "imported-command",
2463 createdAt: at(5),
2464 runId: null,
2465 label: "Ran git",
2466 command: "git status",
2467 requestKind: "command",
2468 tone: "tool" as const,
2469 toolLifecycleStatus: "completed" as const,
2470 },
2471 },
2472 message("imported-answer", "assistant", 8),
2473 ...tail,
2474 ],
2475 latestRun: {
2476 runId: "run-1" as never,
2477 status: "running",
2478 startedAt: at(20),
2479 completedAt: null,
2480 },
2481 isWorking: true,
2482 activeTurnStartedAt: at(20),
2483 turnDiffSummaries: [],
2484 supportsConversationRollback: false,
2485 }).map((row) =>
2486 row.kind === "message" ? `${row.message.role}:${row.message.id}` : row.kind,
2487 );
2488
2489 expect(rows([message("new-prompt", "user", 20, "run-1")]).slice(0, 4)).toEqual([
2490 "user:imported-prompt",
2491 "turn-fold",
2492 "assistant:imported-answer",
2493 "user:new-prompt",
2494 ]);
2495 const withoutPrompt = rows([]);
2496 expect(withoutPrompt).toContain("turn-fold");
2497 expect(withoutPrompt).not.toContain("assistant:imported-update");
2498
2499 const timelineEntries = [
2500 message("imported-prompt", "user", 0),
2501 message("imported-update", "assistant", 4),
2502 message("imported-answer", "assistant", 8),
2503 ];
2504 const foldInput = { timelineEntries, latestRun: null, isWorking: false };
2505 const foldRunIds = timelineTurnFoldRunIdsByEntryId(foldInput);
2506 const foldRunId = foldRunIds.get("imported-update") ?? null;
2507 expect(foldRunId).not.toBeNull();
2508 const foldRow = deriveMessagesTimelineRows({
2509 ...foldInput,
2510 turnDiffSummaries: [],
2511 supportsConversationRollback: false,
2512 }).find((row) => row.kind === "turn-fold");
2513 expect(foldRow?.kind === "turn-fold" ? foldRow.runId : null).toBe(foldRunId);
2514 expect(foldRunIds.get("imported-answer") ?? null).toBeNull();
2515 const expanded = deriveMessagesTimelineRows({
2516 ...foldInput,
2517 expandedRunIds: new Set([foldRunId!]),
2518 turnDiffSummaries: [],
2519 supportsConversationRollback: false,
2520 });
2521 expect(
2522 expanded.some((row) => row.kind === "message" && row.message.id === "imported-update"),
2523 ).toBe(true);
2524 });
2525
2526 it("does not treat runless entries as live work on a thread with runs", () => {
2527 const rows = deriveMessagesTimelineRows({
2528 timelineEntries: [
2529 {
2530 id: "runless-command-entry",
2531 kind: "work",
2532 createdAt: "2026-01-01T00:00:05Z",
2533 entry: {
2534 id: "runless-command",
2535 createdAt: "2026-01-01T00:00:05Z",
2536 runId: null,
2537 label: "Running git",
2538 command: "git status",
2539 requestKind: "command",
2540 tone: "tool" as const,
2541 toolLifecycleStatus: "inProgress" as const,
2542 },
2543 },
2544 ],
2545 latestRun: {
2546 runId: "turn-1" as never,
2547 status: "running",
2548 startedAt: "2026-01-01T00:00:00Z",
2549 completedAt: null,
2550 },
2551 isWorking: true,
2552 activeTurnStartedAt: "2026-01-01T00:00:00Z",
2553 turnDiffSummaries: [],
2554 supportsConversationRollback: false,
2555 });
2556
2557 expect(rows.some((row) => row.kind === "work-live")).toBe(false);
2558 expect(rows.at(-1)?.kind).toBe("thinking");
2559 });
2560
2561 it("keeps separated in-progress tool runs visible", () => {
2562 const rows = deriveMessagesTimelineRows({
2563 timelineEntries: [
2564 {
2565 id: "first-running-entry",
2566 kind: "work",
2567 createdAt: "2026-01-01T00:00:05Z",
2568 entry: {
2569 id: "first-running",
2570 createdAt: "2026-01-01T00:00:05Z",
2571 runId: "turn-1" as never,
2572 label: "Running first command",
2573 command: "rg first",
2574 requestKind: "command",
2575 tone: "tool" as const,
2576 toolLifecycleStatus: "inProgress" as const,
2577 },
2578 },
2579 {
2580 id: "assistant-commentary-entry",
2581 kind: "message",
2582 createdAt: "2026-01-01T00:00:06Z",
2583 message: {
2584 id: "assistant-commentary" as never,
2585 role: "assistant",
2586 text: "Starting another command.",
2587 runId: "turn-1" as never,
2588 createdAt: "2026-01-01T00:00:06Z",
2589 updatedAt: "2026-01-01T00:00:06Z",
2590 streaming: false,
2591 },
2592 },
2593 {
2594 id: "second-running-entry",
2595 kind: "work",
2596 createdAt: "2026-01-01T00:00:07Z",
2597 entry: {
2598 id: "second-running",
2599 createdAt: "2026-01-01T00:00:07Z",
2600 runId: "turn-1" as never,
2601 label: "Running second command",
2602 command: "rg second",
2603 requestKind: "command",
2604 tone: "tool" as const,
2605 toolLifecycleStatus: "inProgress" as const,
2606 },
2607 },
2608 ],
2609 latestRun: {
2610 runId: "turn-1" as never,
2611 status: "running",
2612 startedAt: "2026-01-01T00:00:00Z",
2613 completedAt: null,
2614 },
2615 isWorking: true,
2616 activeTurnStartedAt: "2026-01-01T00:00:00Z",
2617 turnDiffSummaries: [],
2618 supportsConversationRollback: false,
2619 });
2620
2621 expect(rows.map((row) => row.kind)).toEqual(["working", "work-live", "message", "work-live"]);
2622 expect(rows.filter((row) => row.kind === "work-live").map((row) => row.entry.id)).toEqual([
2623 "first-running",
2624 "second-running",
2625 ]);
2626 });
2627
2628 it("does not revive stale in-progress tools before a fresh send has a turn id", () => {
2629 const rows = deriveMessagesTimelineRows({
2630 timelineEntries: [
2631 {
2632 id: "stale-running-entry",
2633 kind: "work",
2634 createdAt: "2026-01-01T00:00:05Z",
2635 entry: {
2636 id: "stale-running",
2637 createdAt: "2026-01-01T00:00:05Z",
2638 runId: "turn-1" as never,
2639 label: "Running stale command",
2640 command: "rg stale",
2641 requestKind: "command",
2642 tone: "tool" as const,
2643 toolLifecycleStatus: "inProgress" as const,
2644 },
2645 },
2646 {
2647 id: "user-followup-entry",
2648 kind: "message",
2649 createdAt: "2026-01-01T00:01:00Z",
2650 message: {
2651 id: "user-followup" as never,
2652 role: "user",
2653 text: "continue",
2654 runId: null,
2655 createdAt: "2026-01-01T00:01:00Z",
2656 updatedAt: "2026-01-01T00:01:00Z",
2657 streaming: false,
2658 },
2659 },
2660 ],
2661 latestRun: null,
2662 isWorking: true,
2663 activeTurnStartedAt: "2026-01-01T00:01:00Z",
2664 turnDiffSummaries: [],
2665 supportsConversationRollback: false,
2666 });
2667
2668 expect(rows.some((row) => row.kind === "work-live")).toBe(false);
2669 });
2670
2671 it.each([
2672 ["inProgress", true],
2673 ["completed", false],
2674 ["failed", null],
2675 ] as const)(
2676 "respects the %s lifecycle of trailing task progress",
2677 (toolLifecycleStatus, active) => {
2678 const runId = RunId.make("turn-task-progress");
2679 const rows = deriveMessagesTimelineRows({
2680 timelineEntries: [
2681 {
2682 id: "task-progress-entry",
2683 kind: "work",
2684 createdAt: "2026-01-01T00:00:05Z",
2685 entry: {
2686 id: "task-progress",
2687 createdAt: "2026-01-01T00:00:05Z",
2688 runId,
2689 label: "Task progress",
2690 tone: "thinking",
2691 sourceActivityKind: "task.progress",
2692 ...(toolLifecycleStatus ? { toolLifecycleStatus } : {}),
2693 },
2694 },
2695 ],
2696 latestRun: {
2697 runId,
2698 status: "running",
2699 startedAt: "2026-01-01T00:00:00Z",
2700 completedAt: null,
2701 },
2702 isWorking: true,
2703 activeTurnStartedAt: "2026-01-01T00:00:00Z",
2704 turnDiffSummaries: [],
2705 supportsConversationRollback: false,
2706 });
2707
2708 const workLiveRow = rows.find((row) => row.kind === "work-live");
2709 if (active === null) {
2710 expect(workLiveRow).toBeUndefined();
2711 expect(rows.at(-1)).toMatchObject({ kind: "thinking", id: "live-activity-row" });
2712 } else {
2713 expect(workLiveRow).toMatchObject({ active });
2714 }
2715 },
2716 );
2717
2718 it("reuses one activity row for initial thinking and the latest tool", () => {
2719 const deriveRows = (
2720 toolLifecycleStatus: "inProgress" | "completed" | "failed" | "declined" | null,
2721 expandedWorkGroupIds?: ReadonlySet<string>,
2722 ) =>
2723 deriveMessagesTimelineRows({
2724 ...(expandedWorkGroupIds ? { expandedWorkGroupIds } : {}),
2725 timelineEntries:
2726 toolLifecycleStatus === null
2727 ? []
2728 : [
2729 {
2730 id: "latest-command-entry",
2731 kind: "work",
2732 createdAt: "2026-01-01T00:00:05Z",
2733 entry: {
2734 id: "latest-command",
2735 createdAt: "2026-01-01T00:00:05Z",
2736 runId: "turn-1" as never,
2737 label: toolLifecycleStatus === "inProgress" ? "Running rg" : "Ran rg",
2738 command: "rg toolCall",
2739 requestKind: "command",
2740 tone: "tool" as const,
2741 toolLifecycleStatus,
2742 ...(toolLifecycleStatus === "inProgress" ? { detail: "exit code 1" } : {}),
2743 },
2744 },
2745 ],
2746 latestRun: {
2747 runId: "turn-1" as never,
2748 status: "running",
2749 startedAt: "2026-01-01T00:00:00Z",
2750 completedAt: null,
2751 },
2752 isWorking: true,
2753 activeTurnStartedAt: "2026-01-01T00:00:00Z",
2754 turnDiffSummaries: [],
2755 supportsConversationRollback: false,
2756 });
2757
2758 const initialRows = deriveRows(null);
2759 const runningRows = deriveRows("inProgress");
2760 const completedRows = deriveRows("completed");
2761 const failedRows = deriveRows("failed");
2762 const declinedRows = deriveRows("declined");
2763 const initialActivityRow = initialRows.find((row) => row.id === "live-activity-row");
2764 const runningActivityRow = runningRows.find((row) => row.id === "live-activity-row");
2765 const completedActivityRow = completedRows.find((row) => row.id === "live-activity-row");
2766
2767 expect(initialActivityRow).toMatchObject({ kind: "thinking" });
2768 expect(runningActivityRow).toMatchObject({ kind: "work-live", active: true });
2769 expect(completedActivityRow).toMatchObject({ kind: "work-live", active: true });
2770 expect(failedRows.some((row) => row.kind === "work-live")).toBe(false);
2771 expect(failedRows.at(-1)).toMatchObject({ kind: "thinking", id: "live-activity-row" });
2772 const failedThinkingRow = failedRows.at(-1);
2773 const failedGroupId =
2774 failedThinkingRow?.kind === "thinking" ? failedThinkingRow.groupId : undefined;
2775 expect(failedGroupId).toBeDefined();
2776 const expandedFailedRows = deriveRows("failed", new Set([failedGroupId!]));
2777 expect(expandedFailedRows.slice(-2)).toMatchObject([
2778 { kind: "thinking", id: "live-activity-row", expanded: true },
2779 {
2780 kind: "work",
2781 isExpandedToolGroup: true,
2782 groupedEntries: [{ id: "latest-command" }],
2783 },
2784 ]);
2785 expect(declinedRows.find((row) => row.kind === "work-live")).toMatchObject({ active: false });
2786 expect(declinedRows.at(-1)).toMatchObject({ kind: "thinking", id: "live-activity-row" });
2787 expect(initialRows.filter((row) => row.id === "live-activity-row")).toHaveLength(1);
2788 expect(runningRows.filter((row) => row.id === "live-activity-row")).toHaveLength(1);
2789 expect(completedRows.filter((row) => row.id === "live-activity-row")).toHaveLength(1);
2790 expect(failedRows.filter((row) => row.id === "live-activity-row")).toHaveLength(1);
2791 expect(declinedRows.filter((row) => row.id === "live-activity-row")).toHaveLength(1);
2792 });
2793
2794 it("does not fold the session's running turn when latestRun regresses", () => {
2795 const rows = deriveMessagesTimelineRows({
2796 timelineEntries: [
2797 {
2798 id: "previous-work-entry",
2799 kind: "work",
2800 createdAt: "2026-01-01T00:00:05Z",
2801 entry: {
2802 id: "previous-work",
2803 createdAt: "2026-01-01T00:00:05Z",
2804 runId: "turn-1" as never,
2805 label: "Read files",
2806 tone: "tool" as const,
2807 },
2808 },
2809 {
2810 id: "user-followup-entry",
2811 kind: "message",
2812 createdAt: "2026-01-01T00:01:00Z",
2813 message: {
2814 id: "user-followup" as never,
2815 role: "user",
2816 text: "continue",
2817 runId: null,
2818 createdAt: "2026-01-01T00:01:00Z",
2819 updatedAt: "2026-01-01T00:01:00Z",
2820 streaming: false,
2821 },
2822 },
2823 {
2824 id: "running-work-entry",
2825 kind: "work",
2826 createdAt: "2026-01-01T00:01:05Z",
2827 entry: {
2828 id: "running-work",
2829 createdAt: "2026-01-01T00:01:05Z",
2830 runId: "turn-2" as never,
2831 label: "Searched files",
2832 tone: "tool" as const,
2833 },
2834 },
2835 ],
2836 latestRun: {
2837 runId: "turn-1" as never,
2838 status: "completed",
2839 startedAt: "2026-01-01T00:00:00Z",
2840 completedAt: "2026-01-01T00:00:25Z",
2841 },
2842 runningRunId: "turn-2" as never,
2843 isWorking: true,
2844 activeTurnStartedAt: "2026-01-01T00:01:00Z",
2845 turnDiffSummaries: [],
2846 supportsConversationRollback: false,
2847 });
2848
2849 expect(rows.filter((row) => row.kind === "turn-fold").map((row) => row.runId)).toEqual([
2850 "turn-1",
2851 ]);
2852 expect(rows.map((row) => row.id)).toContain("live-activity-row");
2853 });
2854
2855 it.each([
2856 ["the later success is hidden", ["failed", "completed", "info"], false],
2857 ["the later success is visible", ["failed", "info", "completed"], false],
2858 ["an error-toned entry recovers", ["error", "info", "completed"], false],
2859 ["the final failure is hidden", ["completed", "failed", "info"], true],
2860 ["the final failure is visible", ["failed", "info", "failed"], true],
2861 ["the only failure is visible", ["completed", "info", "failed"], true],
2862 ] as const)(
2863 "uses the final tool call for mixed work groups when %s",
2864 (_, statuses, hasFailure) => {
2865 const timelineEntries = statuses.map((status, index) => {
2866 const id = `work-${index}`;
2867 const createdAt = `2026-01-01T00:00:0${index}Z`;
2868
2869 return {
2870 id: `work-entry-${index}`,
2871 kind: "work" as const,
2872 createdAt,
2873 entry:
2874 status === "info"
2875 ? { id, createdAt, label: "Status updated", tone: "info" as const }
2876 : status === "error"
2877 ? { id, createdAt, label: "Command failed", tone: "error" as const }
2878 : {
2879 id,
2880 createdAt,
2881 label: "Ran command",
2882 tone: "tool" as const,
2883 toolLifecycleStatus: status,
2884 },
2885 };
2886 });
2887
2888 const rows = deriveMessagesTimelineRows({
2889 timelineEntries,
2890 isWorking: false,
2891 activeTurnStartedAt: null,
2892 turnDiffSummaries: [],
2893 supportsConversationRollback: false,
2894 });
2895
2896 expect(rows.find((row) => row.kind === "work-toggle")).toMatchObject({
2897 hiddenCount: statuses.some((status) => status === "error") ? 2 : 3,
2898 summary: statuses.some((status) => status === "error")
2899 ? "Received 1 update and used 1 tool"
2900 : "Used 2 tools and received 1 update",
2901 hasFailure,
2902 });
2903 if (statuses.some((status) => status === "error")) {
2904 expect(rows[0]).toMatchObject({
2905 kind: "work",
2906 groupedEntries: [{ tone: "error", label: "Command failed" }],
2907 });
2908 }
2909 },
2910 );
2911 });
2912
2913 describe("v2 run and attempt history", () => {
2914 it("folds settled-turn commentary and work behind a Worked-for row", () => {
2915 const timelineEntries = [
2916 {
2917 id: "user-entry",
2918 kind: "message" as const,
2919 createdAt: "2026-01-01T00:00:00Z",
2920 message: {
2921 id: "user-1" as never,
2922 role: "user" as const,
2923 text: "Build it",
2924 runId: null,
2925 createdAt: "2026-01-01T00:00:00Z",
2926 updatedAt: "2026-01-01T00:00:00Z",
2927 streaming: false,
2928 },
2929 },
2930 {
2931 id: "assistant-thought-entry",
2932 kind: "message" as const,
2933 createdAt: "2026-01-01T00:00:05Z",
2934 message: {
2935 id: "assistant-thought" as never,
2936 role: "assistant" as const,
2937 text: "Looking around first.",
2938 runId: "turn-1" as never,
2939 createdAt: "2026-01-01T00:00:05Z",
2940 updatedAt: "2026-01-01T00:00:06Z",
2941 streaming: false,
2942 },
2943 },
2944 {
2945 id: "work-entry-1",
2946 kind: "work" as const,
2947 createdAt: "2026-01-01T00:00:08Z",
2948 entry: {
2949 id: "work-1",
2950 createdAt: "2026-01-01T00:00:08Z",
2951 runId: "turn-1" as never,
2952 label: "Ran command",
2953 tone: "tool" as const,
2954 },
2955 },
2956 {
2957 id: "provider-recovered-entry",
2958 kind: "work" as const,
2959 createdAt: "2026-01-01T00:00:09Z",
2960 entry: {
2961 id: "provider-recovered",
2962 createdAt: "2026-01-01T00:00:09Z",
2963 runId: "turn-1" as never,
2964 label: "Provider recovered (2/5 retries)",
2965 tone: "info" as const,
2966 itemType: "error" as const,
2967 toolLifecycleStatus: "completed" as const,
2968 },
2969 },
2970 {
2971 id: "thread-created-entry",
2972 kind: "event" as const,
2973 createdAt: "2026-01-01T00:00:10Z",
2974 projectedItem: {
2975 item: {
2976 type: "thread_created",
2977 },
2978 } as never,
2979 },
2980 {
2981 id: "assistant-final-entry",
2982 kind: "message" as const,
2983 createdAt: "2026-01-01T00:00:20Z",
2984 message: {
2985 id: "assistant-final" as never,
2986 role: "assistant" as const,
2987 text: "Done",
2988 runId: "turn-1" as never,
2989 createdAt: "2026-01-01T00:00:20Z",
2990 updatedAt: "2026-01-01T00:00:22Z",
2991 streaming: false,
2992 },
2993 },
2994 ];
2995
2996 const collapsedRows = deriveMessagesTimelineRows({
2997 timelineEntries,
2998 isWorking: false,
2999 turnDiffSummaries: [],
3000 supportsConversationRollback: false,
3001 });
3002
3003 const foldRow = collapsedRows.find(
3004 (row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> =>
3005 row.kind === "turn-fold",
3006 );
3007 expect(foldRow?.runId).toBe("turn-1");
3008 expect(foldRow?.expanded).toBe(false);
3009 expect(foldRow?.label).toBe("Worked for 22s");
3010 expect(collapsedRows.map((row) => row.id)).toEqual([
3011 "user-entry",
3012 "turn-fold:turn-1",
3013 "thread-created-entry",
3014 "assistant-final-entry",
3015 ]);
3016
3017 const expandedRows = deriveMessagesTimelineRows({
3018 timelineEntries,
3019 expandedRunIds: new Set(["turn-1" as never]),
3020 isWorking: false,
3021 turnDiffSummaries: [],
3022 supportsConversationRollback: false,
3023 });
3024
3025 expect(expandedRows.map((row) => row.id)).toEqual([
3026 "user-entry",
3027 "turn-fold:turn-1",
3028 "assistant-thought-entry",
3029 "work-toggle:work-entry-1",
3030 "thread-created-entry",
3031 "assistant-final-entry",
3032 ]);
3033 expect(
3034 expandedRows.find((row) => row.kind === "turn-fold" && row.expanded === true),
3035 ).toBeDefined();
3036 const openedActivity = deriveMessagesTimelineRows({
3037 timelineEntries,
3038 expandedRunIds: new Set(["turn-1" as never]),
3039 expandedWorkGroupIds: new Set(["work-group:work-entry-1"]),
3040 isWorking: false,
3041 turnDiffSummaries: [],
3042 supportsConversationRollback: false,
3043 });
3044 const expandedWork = openedActivity.find((row) => row.kind === "work");
3045 expect(expandedWork?.kind === "work" ? expandedWork.groupedEntries : []).toEqual([
3046 expect.objectContaining({ id: "work-1" }),
3047 expect.objectContaining({ id: "provider-recovered" }),
3048 ]);
3049 });
3050 it("hides tool calls or everything but the final answer", () => {
3051 const runId = RunId.make("turn-1");
3052 const at = (second: number) => `2026-01-01T00:00:${String(second).padStart(2, "0")}Z`;
3053 const message = (
3054 id: string,
3055 role: "user" | "assistant",
3056 second: number,
3057 inputIntent?: "steer",
3058 ): TimelineEntry => ({
3059 id,
3060 kind: "message",
3061 createdAt: at(second),
3062 message: {
3063 id: MessageId.make(id),
3064 role,
3065 text: id,
3066 runId: role === "user" ? null : runId,
3067 createdAt: at(second),
3068 updatedAt: at(second),
3069 streaming: false,
3070 ...(inputIntent ? { inputIntent } : {}),
3071 },
3072 });
3073 const command = (
3074 id: string,
3075 status: "completed" | "failed",
3076 second: number,
3077 ): TimelineEntry => ({
3078 id,
3079 kind: "work",
3080 createdAt: at(second),
3081 entry: {
3082 id,
3083 createdAt: at(second),
3084 runId,
3085 label: "Ran command",
3086 tone: "tool",
3087 itemType: "command_execution",
3088 toolLifecycleStatus: status,
3089 },
3090 });
3091 const [user, step, passed, failed, final] = [
3092 message("user", "user", 0),
3093 message("step", "assistant", 5),
3094 command("passed", "completed", 8),
3095 command("failed", "failed", 9),
3096 message("final", "assistant", 20),
3097 ];
3098 const running = { runId, status: "running" as const, startedAt: at(0), completedAt: null };
3099 const ended = { ...running, turnEnded: true };
3100 const rows = (
3101 timelineEntries: ReadonlyArray<TimelineEntry>,
3102 toolCallVisibility: "hideSuccessful" | "hideAll" | "zen",
3103 latestRun?: typeof ended | typeof running,
3104 ) =>
3105 deriveMessagesTimelineRows({
3106 timelineEntries,
3107 expandedRunIds: new Set([runId]),
3108 isWorking: latestRun !== undefined,
3109 ...(latestRun ? { latestRun } : {}),
3110 turnDiffSummaries: [],
3111 supportsConversationRollback: false,
3112 toolCallVisibility,
3113 }).map((row) => row.id);
3114
3115 const turn = [user, step, passed, failed, final];
3116 expect(rows(turn, "hideSuccessful")).toEqual([
3117 "user",
3118 "turn-fold:turn-1",
3119 "step",
3120 "failed",
3121 "final",
3122 ]);
3123 expect(rows([user, failed, final], "hideAll")).toEqual(["user", "final"]);
3124 expect(rows(turn, "zen")).toEqual(["user", "final"]);
3125 const [steer, answer] = [
3126 message("steer", "user", 4, "steer"),
3127 message("answer", "assistant", 7),
3128 ];
3129 expect(rows([user, steer, answer, final], "zen")).toEqual(["user", "steer", "answer", "final"]);
3130 expect(rows([user, steer, step, passed, final], "zen")).toEqual(["user", "steer", "final"]);
3131 expect(rows([user, steer, answer, step], "zen", running)).toEqual([
3132 "user",
3133 "working-indicator-row",
3134 "steer",
3135 "answer",
3136 "live-activity-row",
3137 ]);
3138 expect(rows([user, step, passed], "zen", running)).toEqual([
3139 "user",
3140 "working-indicator-row",
3141 "live-activity-row",
3142 ]);
3143 expect(liveAnswerPreview([user, step, passed])).toBe("step");
3144 expect(rows(turn, "zen", ended)).toEqual(["user", "final"]);
3145 const followUp = message("follow-up", "user", 30);
3146 expect(rows([...turn, followUp], "zen", ended)).toEqual([
3147 "user",
3148 "final",
3149 "follow-up",
3150 "working-indicator-row",
3151 ]);
3152 const wake: TimelineEntry = {
3153 id: "wake",
3154 kind: "work",
3155 createdAt: at(30),
3156 entry: {
3157 id: "wake",
3158 createdAt: at(30),
3159 runId: RunId.make("wake"),
3160 label: "Task finished",
3161 tone: "info",
3162 itemType: "notification",
3163 },
3164 };
3165 expect(rows([user, final, wake], "zen", { ...running, runId: RunId.make("wake") })).toEqual([
3166 "user",
3167 "final",
3168 "wake",
3169 "working-indicator-row",
3170 "live-activity-row",
3171 ]);
3172 });
3173 it("collapses only output from a superseded V2 attempt within the active logical run", () => {
3174 const runId = "run-steered" as never;
3175 const supersededAttemptId = "attempt-1" as never;
3176 const activeAttemptId = "attempt-2" as never;
3177 const supersededAttempt = {
3178 id: supersededAttemptId,
3179 runId,
3180 attemptOrdinal: 1,
3181 rootNodeId: "node-attempt-1" as never,
3182 status: "superseded" as const,
3183 completedAt: null,
3184 };
3185 const activeAttempt = {
3186 id: activeAttemptId,
3187 runId,
3188 attemptOrdinal: 2,
3189 rootNodeId: "node-attempt-2" as never,
3190 status: "running" as const,
3191 completedAt: null,
3192 };
3193 const timelineEntries = [
3194 {
3195 id: "context-handoff-entry",
3196 kind: "event" as const,
3197 createdAt: "2026-01-01T00:00:00Z",
3198 attempt: supersededAttempt,
3199 projectedItem: {
3200 item: { type: "handoff", runId },
3201 } as never,
3202 },
3203 {
3204 id: "initial-user-entry",
3205 kind: "message" as const,
3206 createdAt: "2026-01-01T00:00:00Z",
3207 attempt: supersededAttempt,
3208 message: {
3209 id: "initial-user" as never,
3210 role: "user" as const,
3211 text: "Build it",
3212 runId,
3213 inputIntent: "turn_start" as const,
3214 createdAt: "2026-01-01T00:00:00Z",
3215 updatedAt: "2026-01-01T00:00:00Z",
3216 streaming: false,
3217 },
3218 },
3219 {
3220 id: "superseded-assistant-entry",
3221 kind: "message" as const,
3222 createdAt: "2026-01-01T00:00:02Z",
3223 attempt: supersededAttempt,
3224 message: {
3225 id: "superseded-assistant" as never,
3226 role: "assistant" as const,
3227 text: "Partial old response",
3228 runId,
3229 createdAt: "2026-01-01T00:00:02Z",
3230 updatedAt: "2026-01-01T00:00:03Z",
3231 streaming: false,
3232 },
3233 },
3234 {
3235 id: "superseded-work-entry",
3236 kind: "work" as const,
3237 createdAt: "2026-01-01T00:00:04Z",
3238 attempt: supersededAttempt,
3239 entry: {
3240 id: "superseded-work",
3241 createdAt: "2026-01-01T00:00:04Z",
3242 runId,
3243 label: "Old command",
3244 tone: "tool" as const,
3245 projectedItem: {
3246 sourceItemId: "old-work-anchor",
3247 item: {
3248 type: "command_execution",
3249 deferredWork: { cursor: "old-work", itemCount: 200, lastOrdinal: 200 },
3250 },
3251 } as never,
3252 },
3253 },
3254 {
3255 id: "superseded-thread-created-entry",
3256 kind: "event" as const,
3257 createdAt: "2026-01-01T00:00:04.500Z",
3258 attempt: supersededAttempt,
3259 projectedItem: {
3260 item: {
3261 type: "thread_created",
3262 },
3263 } as never,
3264 },
3265 {
3266 id: "steer-user-entry",
3267 kind: "message" as const,
3268 createdAt: "2026-01-01T00:00:05Z",
3269 attempt: activeAttempt,
3270 message: {
3271 id: "steer-user" as never,
3272 role: "user" as const,
3273 text: "Change direction",
3274 runId,
3275 inputIntent: "steer" as const,
3276 createdAt: "2026-01-01T00:00:05Z",
3277 updatedAt: "2026-01-01T00:00:05Z",
3278 streaming: false,
3279 },
3280 },
3281 {
3282 id: "active-assistant-entry",
3283 kind: "message" as const,
3284 createdAt: "2026-01-01T00:00:06Z",
3285 attempt: activeAttempt,
3286 message: {
3287 id: "active-assistant" as never,
3288 role: "assistant" as const,
3289 text: "Current response",
3290 runId,
3291 createdAt: "2026-01-01T00:00:06Z",
3292 updatedAt: "2026-01-01T00:00:07Z",
3293 streaming: true,
3294 },
3295 },
3296 ];
3297 const common = {
3298 timelineEntries,
3299 latestRun: {
3300 runId,
3301 status: "running" as const,
3302 startedAt: "2026-01-01T00:00:00Z",
3303 completedAt: null,
3304 },
3305 isWorking: false,
3306 turnDiffSummaries: [],
3307 supportsConversationRollback: false,
3308 };
3309
3310 const collapsedRows = deriveMessagesTimelineRows(common);
3311 expect(collapsedRows.map((row) => row.id)).toEqual([
3312 "context-handoff-entry",
3313 "initial-user-entry",
3314 `attempt-fold:${supersededAttemptId}`,
3315 "superseded-thread-created-entry",
3316 "steer-user-entry",
3317 "active-assistant-entry",
3318 ]);
3319 expect(collapsedRows.find((row) => row.kind === "attempt-fold")).toMatchObject({
3320 attemptId: supersededAttemptId,
3321 runId,
3322 label: "Superseded attempt",
3323 expanded: false,
3324 deferredWorkItemIds: ["old-work-anchor"],
3325 });
3326
3327 const expandedRows = deriveMessagesTimelineRows({
3328 ...common,
3329 expandedAttemptIds: new Set([supersededAttemptId]),
3330 });
3331 expect(expandedRows.map((row) => row.id)).toEqual([
3332 "context-handoff-entry",
3333 "initial-user-entry",
3334 `attempt-fold:${supersededAttemptId}`,
3335 "superseded-assistant-entry",
3336 "superseded-work-entry",
3337 "superseded-thread-created-entry",
3338 "steer-user-entry",
3339 "active-assistant-entry",
3340 ]);
3341 const settledRows = deriveMessagesTimelineRows({
3342 ...common,
3343 latestRun: { ...common.latestRun, status: "completed", completedAt: "2026-01-01T00:00:08Z" },
3344 timelineEntries: timelineEntries.map((entry) =>
3345 entry.kind === "message" && entry.id === "active-assistant-entry"
3346 ? { ...entry, message: { ...entry.message, streaming: false } }
3347 : entry,
3348 ),
3349 expandedRunIds: new Set([runId]),
3350 });
3351 expect(settledRows.find((row) => row.kind === "attempt-fold")).toMatchObject({
3352 deferredWorkItemIds: ["old-work-anchor"],
3353 });
3354 expect(
3355 settledRows
3356 .filter((row) => row.kind === "turn-fold")
3357 .flatMap((row) => row.deferredWorkItemIds ?? []),
3358 ).not.toContain("old-work-anchor");
3359 const deferredTailRows = deriveMessagesTimelineRows({
3360 ...common,
3361 timelineEntries: [
3362 timelineEntries[0]!,
3363 timelineEntries[2]!,
3364 timelineEntries[1]!,
3365 ...timelineEntries.slice(3),
3366 ].map((entry) => ({
3367 ...entry,
3368 attempt:
3369 entry.attempt.id === supersededAttemptId
3370 ? { ...entry.attempt, completedAt: DateTime.makeUnsafe("2026-01-01T00:00:08Z") }
3371 : entry.attempt,
3372 ...(entry.id === "superseded-assistant-entry"
3373 ? {
3374 projectedItem: {
3375 item: {
3376 type: "assistant_message",
3377 ordinal: 2,
3378 status: "completed",
3379 completedAt: DateTime.makeUnsafe("2026-01-01T00:00:03Z"),
3380 },
3381 } as never,
3382 }
3383 : {}),
3384 })),
3385 });
3386 expect(deferredTailRows.some((row) => row.kind === "attempt-fold")).toBe(true);
3387 });
3388
3389 describe("a steer that supersedes an attempt", () => {
3390 const runId = RunId.make("run-steered");
3391 const at = (second: number) => `2026-01-01T00:00:${String(second).padStart(2, "0")}Z`;
3392 const supersededAttempt = {
3393 id: RunAttemptId.make("attempt-1"),
3394 runId,
3395 attemptOrdinal: 1,
3396 rootNodeId: NodeId.make("node-attempt-1"),
3397 status: "superseded" as const,
3398 completedAt: DateTime.makeUnsafe(at(10)),
3399 };
3400 const nextAttempt = {
3401 id: RunAttemptId.make("attempt-2"),
3402 runId,
3403 attemptOrdinal: 2,
3404 rootNodeId: NodeId.make("node-attempt-2"),
3405 status: "completed" as const,
3406 completedAt: DateTime.makeUnsafe(at(14)),
3407 };
3408 const assistantEntry = (
3409 id: string,
3410 attempt: typeof supersededAttempt | typeof nextAttempt,
3411 completedSecond: number,
3412 phase?: "commentary" | "partial_answer" | "final_answer",
3413 ): TimelineEntry => ({
3414 id,
3415 kind: "message",
3416 createdAt: at(2),
3417 attempt,
3418 message: {
3419 id: MessageId.make(id),
3420 role: "assistant",
3421 text: `${id} text`,
3422 runId,
3423 createdAt: at(2),
3424 updatedAt: at(completedSecond),
3425 streaming: false,
3426 },
3427 projectedItem: {
3428 item: {
3429 type: "assistant_message",
3430 ...(phase === undefined ? {} : { phase }),
3431 status: "completed",
3432 completedAt: DateTime.makeUnsafe(at(completedSecond)),
3433 },
3434 } as never,
3435 });
3436 const rowsFor = (
3437 replyCompletedSecond: number,
3438 runStatus: "running" | "completed" = "completed",
3439 toolCallVisibility: "showAll" | "zen" = "showAll",
3440 phase?: "commentary" | "partial_answer" | "final_answer",
3441 nativeSteer = false,
3442 ) =>
3443 deriveMessagesTimelineRows({
3444 toolCallVisibility,
3445 timelineEntries: (
3446 [
3447 {
3448 id: "initial-user-entry",
3449 kind: "message",
3450 createdAt: at(0),
3451 attempt: supersededAttempt,
3452 message: {
3453 id: MessageId.make("initial-user"),
3454 role: "user",
3455 text: "Build it",
3456 runId,
3457 inputIntent: "turn_start",
3458 createdAt: at(0),
3459 updatedAt: at(0),
3460 streaming: false,
3461 },
3462 },
3463 {
3464 id: "old-work-entry",
3465 kind: "work",
3466 createdAt: at(1),
3467 attempt: supersededAttempt,
3468 entry: { id: "old-work", createdAt: at(1), runId, label: "Read", tone: "tool" },
3469 },
3470 assistantEntry("status-entry", supersededAttempt, 1, "commentary"),
3471 assistantEntry("old-reply-entry", supersededAttempt, replyCompletedSecond, phase),
3472 {
3473 id: "steer-user-entry",
3474 kind: "message",
3475 createdAt: at(10),
3476 attempt: nextAttempt,
3477 message: {
3478 id: MessageId.make("steer-user"),
3479 role: "user",
3480 text: "What are you working on?",
3481 runId,
3482 inputIntent: "steer",
3483 createdAt: at(10),
3484 updatedAt: at(10),
3485 streaming: false,
3486 },
3487 },
3488 assistantEntry("new-reply-entry", nextAttempt, 14),
3489 ] satisfies ReadonlyArray<TimelineEntry>
3490 ).map((entry) => (nativeSteer ? { ...entry, attempt: nextAttempt } : entry)),
3491 latestRun: {
3492 runId,
3493 status: runStatus,
3494 startedAt: at(0),
3495 completedAt: runStatus === "completed" ? at(14) : null,
3496 },
3497 isWorking: false,
3498 turnDiffSummaries: [],
3499 supportsConversationRollback: false,
3500 });
3501
3502 it.each([
3503 ["final_answer", 4, true],
3504 ["final_answer", 11, true],
3505 ["commentary", 4, false],
3506 ["commentary", 11, false],
3507 ["partial_answer", 11, false],
3508 [undefined, 4, true],
3509 [undefined, 11, false],
3510 ] as const)(
3511 "retains phase %s ending at %s only when it is a final reply: %s",
3512 (phase, completedSecond, retained) => {
3513 for (const runStatus of ["running", "completed"] as const) {
3514 for (const visibility of ["showAll", "zen"] as const) {
3515 const rows = rowsFor(completedSecond, runStatus, visibility, phase);
3516 expect(rows.some((row) => row.id === "old-reply-entry")).toBe(retained);
3517 if (phase !== undefined && runStatus === "completed") {
3518 const nativeRows = rowsFor(completedSecond, runStatus, visibility, phase, true);
3519 expect(nativeRows.some((row) => row.id === "old-reply-entry")).toBe(retained);
3520 expect(nativeRows.some((row) => row.id === "status-entry")).toBe(false);
3521 }
3522 if (runStatus === "completed") {
3523 expect(rows.some((row) => row.id === "status-entry")).toBe(false);
3524 }
3525 }
3526 }
3527 },
3528 );
3529 });
3530
3531 it("hides the interruption request while keeping intervening work and the result", () => {
3532 const runId = "turn-1" as never;
3533 const interruptEvent = (type: "run_interrupt_request" | "run_interrupt_result") => ({
3534 position: type === "run_interrupt_request" ? 0 : 2,
3535 visibility: "local" as const,
3536 sourceThreadId: "thread-1" as never,
3537 sourceItemId: `item-${type}` as never,
3538 item: {
3539 id: `item-${type}`,
3540 threadId: "thread-1",
3541 runId,
3542 nodeId: null,
3543 providerThreadId: null,
3544 providerTurnId: null,
3545 nativeItemRef: null,
3546 parentItemId: null,
3547 ordinal: type === "run_interrupt_request" ? 0 : 2,
3548 status: "completed",
3549 title: null,
3550 startedAt: null,
3551 completedAt: null,
3552 updatedAt: {},
3553 type,
3554 message: type === "run_interrupt_request" ? "Stopping" : "Stopped",
3555 },
3556 });
3557 const rows = deriveMessagesTimelineRows({
3558 timelineEntries: [
3559 {
3560 id: "interrupt-request",
3561 kind: "event",
3562 createdAt: "2026-01-01T00:00:01Z",
3563 projectedItem: interruptEvent("run_interrupt_request") as never,
3564 },
3565 {
3566 id: "work-entry",
3567 kind: "work",
3568 createdAt: "2026-01-01T00:00:02Z",
3569 entry: {
3570 id: "work-1",
3571 createdAt: "2026-01-01T00:00:02Z",
3572 runId,
3573 label: "Finishing tool output",
3574 tone: "tool",
3575 },
3576 },
3577 {
3578 id: "interrupt-result",
3579 kind: "event",
3580 createdAt: "2026-01-01T00:00:03Z",
3581 projectedItem: interruptEvent("run_interrupt_result") as never,
3582 },
3583 ],
3584 latestRun: {
3585 runId,
3586 status: "interrupted",
3587 startedAt: "2026-01-01T00:00:00Z",
3588 completedAt: "2026-01-01T00:00:03Z",
3589 },
3590 isWorking: false,
3591 turnDiffSummaries: [],
3592 supportsConversationRollback: false,
3593 });
3594
3595 expect(rows.map((row) => row.id)).toEqual(["work-entry", "interrupt-result"]);
3596 expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
3597
3598 const stoppedRows = deriveMessagesTimelineRows({
3599 timelineEntries: [
3600 {
3601 id: "stopped-command-entry",
3602 kind: "work",
3603 createdAt: "2026-01-01T00:00:01Z",
3604 entry: {
3605 id: "stopped-command",
3606 createdAt: "2026-01-01T00:00:01Z",
3607 runId,
3608 label: "Ran command",
3609 tone: "tool",
3610 itemType: "command_execution",
3611 command: "/bin/bash -lc 'sleep 90 && echo slept'",
3612 toolLifecycleStatus: "stopped",
3613 },
3614 },
3615 {
3616 id: "interrupt-result",
3617 kind: "event",
3618 createdAt: "2026-01-01T00:00:03Z",
3619 projectedItem: interruptEvent("run_interrupt_result") as never,
3620 },
3621 ],
3622 latestRun: {
3623 runId,
3624 status: "interrupted",
3625 startedAt: "2026-01-01T00:00:00Z",
3626 completedAt: "2026-01-01T00:00:03Z",
3627 },
3628 isWorking: false,
3629 turnDiffSummaries: [],
3630 supportsConversationRollback: false,
3631 });
3632 expect(stoppedRows.map((row) => row.id)).toEqual(["stopped-command-entry", "interrupt-result"]);
3633 expect(stoppedRows[0]).toMatchObject({
3634 kind: "work",
3635 displayLabel: "sleep 90 && echo slept",
3636 });
3637 });
3638 });
3639
3640 it.each([
3641 [undefined, ["first"]],
3642 [["first"], ["second"]],
3643 [["first"], []],
3644 [
3645 ["first", "second"],
3646 ["second", "first"],
3647 ],
3648 [undefined, []],
3649 ] as const)("keeps deferred fold anchors current from %j to %j", (before, after) => {
3650 const row: Extract<MessagesTimelineRow, { kind: "turn-fold" }> = {
3651 kind: "turn-fold",
3652 id: "fold",
3653 runId: RunId.make("run"),
3654 createdAt: "2026-01-01T00:00:00Z",
3655 label: "Worked for 1m",
3656 expanded: true,
3657 ...(before === undefined ? {} : { deferredWorkItemIds: before }),
3658 };
3659 const previous = computeStableMessagesTimelineRows([row], { result: [], byId: new Map() });
3660 const nextRow = { ...row, deferredWorkItemIds: after };
3661 const next = computeStableMessagesTimelineRows([nextRow], previous);
3662 const fold = next.result[0];
3663 expect(fold?.kind === "turn-fold" ? (fold.deferredWorkItemIds ?? []) : null).toEqual(after);
3664 expect(
3665 computeStableMessagesTimelineRows([{ ...nextRow, deferredWorkItemIds: [...after] }], next),
3666 ).toBe(next);
3667 });
3668
3669 describe("streaming v2 row projection", () => {
3670 function fixture(text = "") {
3671 const source = makeStreamingTimelineFixture(text);
3672 const timelineInput = { visibleTurnItems: source.visibleTurnItems, optimisticMessages: [] };
3673 const timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(timelineInput);
3674 const input = {
3675 timelineEntries: timeline.entries,
3676 latestRun: {
3677 runId: source.runId,
3678 status: "running" as const,
3679 startedAt: source.time(5),
3680 completedAt: null,
3681 },
3682 runningRunId: source.runId,
3683 isWorking: true,
3684 activeTurnStartedAt: source.time(5),
3685 turnDiffSummaries: [
3686 {
3687 runId: source.historyRunId,
3688 checkpointTurnCount: 1,
3689 checkpointRef: CheckpointRef.make("refs/t3/checkpoints/history"),
3690 status: "ready",
3691 files: [],
3692 assistantMessageId: MessageId.make("history-assistant"),
3693 completedAt: source.time(4),
3694 },
3695 ] satisfies ReadonlyArray<TurnDiffSummary>,
3696 supportsConversationRollback: true,
3697 } satisfies Parameters<typeof deriveMessagesTimelineRows>[0];
3698 return { ...source, timelineInput, timeline, input };
3699 }
3700
3701 function updateText(items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>, text: string) {
3702 return items.map((row) =>
3703 row.item.type === "assistant_message" && row.item.streaming
3704 ? {
3705 ...row,
3706 item: { ...row.item, text, updatedAt: DateTime.makeUnsafe("2026-09-04T00:00:08.000Z") },
3707 }
3708 : row,
3709 );
3710 }
3711
3712 it.each([
3713 ["", "Now visible"],
3714 [" \n", "Now visible"],
3715 ["Visible", ""],
3716 ["", " \t\n"],
3717 ["Visible", "★ Insight\nKeep these line breaks"],
3718 ])("keeps row parity and history identity from %j to %j", (before, after) => {
3719 const initial = fixture(before);
3720 const previous = deriveMessagesTimelineRowsWithState({
3721 ...initial.input,
3722 availableRevertTurnCounts: new Set([0]),
3723 pendingApprovalRequestIds: new Set<RuntimeRequestId>(),
3724 });
3725 Object.freeze(previous.rows);
3726 for (const row of previous.rows) Object.freeze(row);
3727 const timelineInput = {
3728 ...initial.timelineInput,
3729 visibleTurnItems: updateText(initial.visibleTurnItems, after),
3730 };
3731 const timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(
3732 timelineInput,
3733 initial.timeline,
3734 );
3735 const input = {
3736 ...initial.input,
3737 timelineEntries: timeline.entries,
3738 latestRun: { ...initial.input.latestRun },
3739 turnDiffSummaries: initial.input.turnDiffSummaries.map((summary) => ({ ...summary })),
3740 availableRevertTurnCounts: new Set([0]),
3741 pendingApprovalRequestIds: new Set<RuntimeRequestId>(),
3742 };
3743 const next = deriveMessagesTimelineRowsWithState(input, previous);
3744 expect(next.rows).toEqual(
3745 deriveMessagesTimelineRows({
3746 ...input,
3747 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems(timelineInput),
3748 }),
3749 );
3750 for (const [index, row] of previous.rows.entries()) {
3751 if (
3752 (row.kind === "message" || row.kind === "assistant-meta") &&
3753 row.message.id === "live-assistant"
3754 ) {
3755 expect(next.rows[index]).toMatchObject({ message: { text: after } });
3756 expect(next.rows[index]).toHaveProperty(
3757 "projectedItem",
3758 timelineInput.visibleTurnItems.at(-1),
3759 );
3760 expect(row.message.text).toBe(before);
3761 } else {
3762 expect(next.rows[index]).toBe(row);
3763 }
3764 }
3765 });
3766
3767 it.each(["file", "image", "handoff", "streaming-image"] as const)(
3768 "keeps history references with %s previews through the v2 materializer",
3769 (kind) => {
3770 const initial = fixture("Partial");
3771 const image = {
3772 type: "image" as const,
3773 id: "image",
3774 name: "image.png",
3775 mimeType: "image/png",
3776 sizeBytes: 42,
3777 };
3778 const file = {
3779 type: "file" as const,
3780 id: "file",
3781 name: "file.txt",
3782 mimeType: "text/plain",
3783 sizeBytes: 8,
3784 };
3785 const timelineInput = {
3786 ...initial.timelineInput,
3787 visibleTurnItems: initial.visibleTurnItems.map((row, index) =>
3788 (row.item.type === "user_message" && index === 0) ||
3789 (row.item.type === "assistant_message" &&
3790 row.item.streaming &&
3791 kind === "streaming-image")
3792 ? {
3793 ...row,
3794 item: { ...row.item, attachments: kind === "file" ? [file] : [image, file] },
3795 }
3796 : row,
3797 ),
3798 attachmentUrlById: new Map([
3799 [image.id, kind === "handoff" ? "blob:handoff" : "https://server.test/image"],
3800 ]),
3801 };
3802 const timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(timelineInput);
3803 const input = { ...initial.input, timelineEntries: timeline.entries };
3804 const previous = deriveMessagesTimelineRowsWithState(input);
3805 const nextTimelineInput = {
3806 ...timelineInput,
3807 visibleTurnItems: updateText(timelineInput.visibleTurnItems, "Next token"),
3808 attachmentUrlById: new Map(timelineInput.attachmentUrlById),
3809 };
3810 const nextTimeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(
3811 nextTimelineInput,
3812 timeline,
3813 );
3814 const nextInput = { ...input, timelineEntries: nextTimeline.entries };
3815 const next = deriveMessagesTimelineRowsWithState(nextInput, previous);
3816 expect(next.rows).toEqual(deriveMessagesTimelineRows(nextInput));
3817 for (const [index, row] of previous.rows.entries()) {
3818 if (
3819 (row.kind === "message" || row.kind === "assistant-meta") &&
3820 row.message.id === "live-assistant"
3821 )
3822 continue;
3823 expect(next.rows[index]).toBe(row);
3824 }
3825 const renewedInput = {
3826 ...nextTimelineInput,
3827 attachmentUrlById: new Map([[image.id, "https://renewed.test/image"]]),
3828 };
3829 const renewedTimeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(
3830 renewedInput,
3831 nextTimeline,
3832 );
3833 const renewedRowsInput = { ...input, timelineEntries: renewedTimeline.entries };
3834 const renewed = deriveMessagesTimelineRowsWithState(renewedRowsInput, next);
3835 expect(renewed.rows).toEqual(deriveMessagesTimelineRows(renewedRowsInput));
3836 if (kind !== "file") {
3837 expect(renewed.rows.find((row) => row.id === "history-user")).toMatchObject({
3838 message: { attachments: [{ previewUrl: "https://renewed.test/image" }, file] },
3839 });
3840 }
3841 },
3842 );
3843
3844 it("rebuilds for completion, late failure, metadata, expansion, and older history", () => {
3845 const initial = fixture("Partial");
3846 let timeline = initial.timeline;
3847 let timelineInput = initial.timelineInput;
3848 let input: Parameters<typeof deriveMessagesTimelineRows>[0] = initial.input;
3849 let projection = deriveMessagesTimelineRowsWithState(input);
3850 const check = (changes: Partial<typeof input> = {}) => {
3851 const previous = projection;
3852 timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(timelineInput, timeline);
3853 input = { ...input, ...changes, timelineEntries: timeline.entries };
3854 projection = deriveMessagesTimelineRowsWithState(input, previous);
3855 expect(projection.rows).toEqual(
3856 deriveMessagesTimelineRows({
3857 ...input,
3858 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems(timelineInput),
3859 }),
3860 );
3861 expect(previous.rows).toEqual(deriveMessagesTimelineRows(previous.input));
3862 };
3863 timelineInput = {
3864 ...timelineInput,
3865 visibleTurnItems: timelineInput.visibleTurnItems.map((row) =>
3866 row.item.type === "assistant_message" && row.item.streaming
3867 ? {
3868 ...row,
3869 item: {
3870 ...row.item,
3871 streaming: false,
3872 status: "completed",
3873 text: "Complete",
3874 updatedAt: DateTime.makeUnsafe(initial.time(9)),
3875 },
3876 }
3877 : row,
3878 ),
3879 };
3880 check({
3881 latestRun: { ...initial.input.latestRun, status: "completed", completedAt: initial.time(9) },
3882 runningRunId: null,
3883 isWorking: false,
3884 });
3885 const lateFailure = initial.visibleTurnItems[1]!;
3886 timelineInput = {
3887 ...timelineInput,
3888 visibleTurnItems: [
3889 ...timelineInput.visibleTurnItems,
3890 {
3891 ...lateFailure,
3892 position: 6,
3893 sourceItemId: TurnItemId.make("late-failure"),
3894 item: {
3895 ...lateFailure.item,
3896 id: TurnItemId.make("late-failure"),
3897 runId: initial.runId,
3898 ordinal: 10,
3899 startedAt: DateTime.makeUnsafe(initial.time(10)),
3900 },
3901 },
3902 ],
3903 };
3904 check();
3905 timelineInput = {
3906 ...timelineInput,
3907 visibleTurnItems: timelineInput.visibleTurnItems.map((row) =>
3908 row.item.type === "assistant_message" && row.item.messageId === "live-assistant"
3909 ? {
3910 ...row,
3911 item: {
3912 ...row.item,
3913 text: "Corrected final text",
3914 updatedAt: DateTime.makeUnsafe(initial.time(11)),
3915 },
3916 }
3917 : row,
3918 ),
3919 };
3920 check();
3921 check({
3922 latestRun: {
3923 ...initial.input.latestRun,
3924 status: "interrupted",
3925 completedAt: initial.time(12),
3926 },
3927 });
3928 check({ expandedRunIds: new Set([initial.historyRunId, initial.runId]) });
3929 const group = projection.rows.find((row) => row.kind === "work-toggle");
3930 check({ expandedWorkGroupIds: new Set(group ? [group.groupId] : []) });
3931 const first = initial.visibleTurnItems[0]!;
3932 if (first.item.type !== "user_message") throw new Error("Expected user fixture");
3933 timelineInput = {
3934 ...timelineInput,
3935 visibleTurnItems: [
3936 {
3937 ...first,
3938 sourceItemId: TurnItemId.make("older-user-item"),
3939 item: {
3940 ...first.item,
3941 id: TurnItemId.make("older-user-item"),
3942 messageId: MessageId.make("older-user"),
3943 startedAt: DateTime.makeUnsafe(initial.time(-60)),
3944 },
3945 },
3946 ...timelineInput.visibleTurnItems,
3947 ].map((row, position) => ({ ...row, position })),
3948 };
3949 check();
3950 check({ supportsConversationRollback: false });
3951 check({
3952 turnDiffSummaries: initial.input.turnDiffSummaries.map((summary) => ({
3953 ...summary,
3954 status: "stale" as const,
3955 })),
3956 });
3957 });
3958
3959 it.each(["reasoning", "proposed_plan"] as const)(
3960 "keeps every row not holding streaming %s text when it changes",
3961 (kind) => {
3962 const source = makeStreamingWorkTimelineFixture(kind);
3963 const rowsInput = (timelineEntries: ReadonlyArray<TimelineEntry>) => ({
3964 timelineEntries,
3965 latestRun: {
3966 runId: source.runId,
3967 status: "running" as const,
3968 startedAt: source.time(5),
3969 completedAt: null,
3970 },
3971 runningRunId: source.runId,
3972 isWorking: true,
3973 activeTurnStartedAt: source.time(5),
3974 turnDiffSummaries: [],
3975 supportsConversationRollback: true,
3976 });
3977 let timelineInput = {
3978 visibleTurnItems: withStreamedText(
3979 source.visibleTurnItems,
3980 source.streamingItemId,
3981 "Let",
3982 source.time(20),
3983 ),
3984 optimisticMessages: [],
3985 };
3986 let timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(timelineInput);
3987 let projection = deriveMessagesTimelineRowsWithState(rowsInput(timeline.entries));
3988 for (const [step, text] of ["Let me", "Let me check the tests"].entries()) {
3989 timelineInput = {
3990 visibleTurnItems: withStreamedText(
3991 timelineInput.visibleTurnItems,
3992 source.streamingItemId,
3993 text,
3994 source.time(21 + step),
3995 ),
3996 optimisticMessages: [],
3997 };
3998 const previous = projection;
3999 timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(timelineInput, timeline);
4000 projection = deriveMessagesTimelineRowsWithState(rowsInput(timeline.entries), previous);
4001 expect(projection.rows).toEqual(
4002 deriveMessagesTimelineRows(
4003 rowsInput(deriveTimelineEntriesFromVisibleTurnItems(timelineInput)),
4004 ),
4005 );
4006 expect(projection.rows).toHaveLength(previous.rows.length);
4007 for (const [index, row] of previous.rows.entries()) {
4008 const holdsItem =
4009 row.id === source.streamingItemId ||
4010 ((row.kind === "work" || row.kind === "work-live") &&
4011 row.groupedEntries.some((entry) => entry.id === source.streamingItemId));
4012 if (!holdsItem) expect(projection.rows[index]).toBe(row);
4013 }
4014 }
4015 },
4016 );
4017
4018 it.each(["reasoning", "proposed_plan"] as const)(
4019 "matches a full derivation when streaming %s text turns blank or completes",
4020 (kind) => {
4021 const source = makeStreamingWorkTimelineFixture(kind);
4022 const rowsInput = (timelineEntries: ReadonlyArray<TimelineEntry>) => ({
4023 timelineEntries,
4024 latestRun: {
4025 runId: source.runId,
4026 status: "running" as const,
4027 startedAt: source.time(5),
4028 completedAt: null,
4029 },
4030 runningRunId: source.runId,
4031 isWorking: true,
4032 activeTurnStartedAt: source.time(5),
4033 turnDiffSummaries: [],
4034 supportsConversationRollback: true,
4035 });
4036 let visibleTurnItems = source.visibleTurnItems;
4037 let timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState({
4038 visibleTurnItems,
4039 optimisticMessages: [],
4040 });
4041 let projection = deriveMessagesTimelineRowsWithState(rowsInput(timeline.entries));
4042 const steps = [
4043 ...["Let", " ", "Let me"].map(
4044 (text, step) => (rows: typeof visibleTurnItems) =>
4045 withStreamedText(rows, source.streamingItemId, text, source.time(20 + step)),
4046 ),
4047 (rows: typeof visibleTurnItems) =>
4048 rows.map((row) =>
4049 row.item.id === source.streamingItemId &&
4050 (row.item.type === "reasoning" || row.item.type === "proposed_plan")
4051 ? {
4052 ...row,
4053 item: {
4054 ...row.item,
4055 status: "completed" as const,
4056 streaming: false,
4057 completedAt: DateTime.makeUnsafe(source.time(30)),
4058 updatedAt: DateTime.makeUnsafe(source.time(30)),
4059 },
4060 }
4061 : row,
4062 ),
4063 ];
4064 for (const step of steps) {
4065 visibleTurnItems = step(visibleTurnItems);
4066 const timelineInput = { visibleTurnItems, optimisticMessages: [] };
4067 timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(timelineInput, timeline);
4068 expect(timeline.entries).toEqual(deriveTimelineEntriesFromVisibleTurnItems(timelineInput));
4069 projection = deriveMessagesTimelineRowsWithState(rowsInput(timeline.entries), projection);
4070 expect(projection.rows).toEqual(
4071 deriveMessagesTimelineRows(
4072 rowsInput(deriveTimelineEntriesFromVisibleTurnItems(timelineInput)),
4073 ),
4074 );
4075 }
4076 },
4077 );
4078
4079 it.each([
4080 "expanded live group",
4081 "expanded live group followed by a hidden tool",
4082 "thinking superseded by a running tool",
4083 "settled turn",
4084 ] as const)("matches a full derivation when streaming thinking sits in a %s", (scenario) => {
4085 const source = makeStreamingWorkTimelineFixture("reasoning");
4086 const running = scenario !== "settled turn";
4087 const hiddenTool = scenario === "expanded live group followed by a hidden tool";
4088 const rowsInput = (
4089 timelineEntries: ReadonlyArray<TimelineEntry>,
4090 expandedWorkGroupIds?: ReadonlySet<string>,
4091 ) => ({
4092 timelineEntries,
4093 latestRun: {
4094 runId: source.runId,
4095 status: running ? ("running" as const) : ("completed" as const),
4096 startedAt: source.time(5),
4097 completedAt: running ? null : source.time(40),
4098 },
4099 runningRunId: running ? source.runId : null,
4100 isWorking: running,
4101 activeTurnStartedAt: source.time(5),
4102 turnDiffSummaries: [],
4103 supportsConversationRollback: true,
4104 ...(expandedWorkGroupIds ? { expandedWorkGroupIds } : {}),
4105 ...(running ? {} : { expandedRunIds: new Set([source.runId]) }),
4106 ...(hiddenTool ? { toolCallVisibility: "hideAll" as const } : {}),
4107 });
4108 const tool = source.visibleTurnItems.find((row) => row.item.id === "live-work")!;
4109 const laterTool = (status: "running" | "completed") => ({
4110 ...tool,
4111 position: source.visibleTurnItems.length,
4112 sourceItemId: TurnItemId.make("live-later-tool"),
4113 item: {
4114 ...tool.item,
4115 id: TurnItemId.make("live-later-tool"),
4116 ordinal: 8,
4117 status,
4118 ...(status === "running" ? { completedAt: null } : {}),
4119 },
4120 });
4121 let visibleTurnItems =
4122 scenario === "thinking superseded by a running tool" || hiddenTool
4123 ? [...source.visibleTurnItems, laterTool(hiddenTool ? "completed" : "running")]
4124 : // Alone in a settled group, the thought's text becomes the group summary.
4125 source.visibleTurnItems.filter((row) => running || row !== tool);
4126 visibleTurnItems = withStreamedText(
4127 visibleTurnItems,
4128 source.streamingItemId,
4129 "Let",
4130 source.time(20),
4131 );
4132 let timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState({
4133 visibleTurnItems,
4134 optimisticMessages: [],
4135 });
4136 const liveRow = deriveMessagesTimelineRows(rowsInput(timeline.entries)).find(
4137 (row) => row.kind === "work-live",
4138 );
4139 const expanded =
4140 scenario.startsWith("expanded live group") && liveRow?.kind === "work-live"
4141 ? new Set([liveRow.groupId])
4142 : undefined;
4143 let projection = deriveMessagesTimelineRowsWithState(rowsInput(timeline.entries, expanded));
4144 for (const [step, text] of ["Let me", "Let me check the tests"].entries()) {
4145 visibleTurnItems = withStreamedText(
4146 visibleTurnItems,
4147 source.streamingItemId,
4148 text,
4149 source.time(21 + step),
4150 );
4151 const timelineInput = { visibleTurnItems, optimisticMessages: [] };
4152 const previous = projection;
4153 timeline = deriveTimelineEntriesFromVisibleTurnItemsWithState(timelineInput, timeline);
4154 projection = deriveMessagesTimelineRowsWithState(
4155 rowsInput(timeline.entries, expanded),
4156 previous,
4157 );
4158 expect(projection.rows).toEqual(
4159 deriveMessagesTimelineRows(
4160 rowsInput(deriveTimelineEntriesFromVisibleTurnItems(timelineInput), expanded),
4161 ),
4162 );
4163 if (!running) continue;
4164 for (const [index, row] of previous.rows.entries()) {
4165 const holdsItem =
4166 (row.kind === "work" || row.kind === "work-live") &&
4167 row.groupedEntries.some((entry) => entry.id === source.streamingItemId);
4168 if (!holdsItem) expect(projection.rows[index]).toBe(row);
4169 }
4170 }
4171 });
4172 });
4173
4174 describe("linked timeline resources", () => {
4175 const runId = RunId.make("resource-run");
4176 const event = (id: string, type: "subagent" | "thread_created", eventRunId = runId) => ({
4177 id,
4178 kind: "event" as const,
4179 createdAt: "2026-09-08T10:00:02Z",
4180 projectedItem: { item: { id, type, runId: eventRunId } } as OrchestrationV2ProjectedTurnItem,
4181 });
4182 const common = { isWorking: false, turnDiffSummaries: [], supportsConversationRollback: false };
4183
4184 it("groups adjacent subagents without merging across a resource or run boundary", () => {
4185 const rows = deriveMessagesTimelineRows({
4186 ...common,
4187 timelineEntries: [
4188 event("a", "subagent"),
4189 event("b", "subagent"),
4190 event("c", "thread_created"),
4191 event("d", "subagent"),
4192 event("e", "subagent", RunId.make("other-run")),
4193 ],
4194 expandedRunIds: new Set([runId, RunId.make("other-run")]),
4195 });
4196 expect(rows.map((row) => row.id)).toEqual([
4197 "turn-fold:resource-run",
4198 "a",
4199 "c",
4200 "d",
4201 "turn-fold:other-run",
4202 "e",
4203 ]);
4204 expect(rows[1]).toMatchObject({ subagents: [{ item: { id: "a" } }, { item: { id: "b" } }] });
4205 });
4206
4207 it.each([
4208 { status: "completed", envelope: "direct", role: "general" },
4209 { status: "completed", envelope: "structured", role: "general" },
4210 { status: "completed", envelope: "text", role: "general" },
4211 { status: "completed", envelope: "structured", role: "research" },
4212 { status: "running", envelope: "direct", role: "general" },
4213 { status: "running", envelope: "direct", role: "research" },
4214 ] as const)(
4215 "matches $status $role delegation calls by child identity with $envelope output",
4216 ({ status, envelope, role }) => {
4217 const child = (id: string) => {
4218 const entry = event(id, "subagent");
4219 return {
4220 ...entry,
4221 projectedItem: {
4222 item: {
4223 ...entry.projectedItem.item,
4224 origin: "app_owned",
4225 subagentId: id,
4226 prompt:
4227 role === "general" ? id : `Act as the ${role} sub-agent for this task.\n\n${id}`,
4228 childThreadId: null,
4229 },
4230 } as OrchestrationV2ProjectedTurnItem,
4231 };
4232 };
4233 const delegation = (id: string, taskId: string, failed = false): TimelineEntry => ({
4234 id,
4235 kind: "work",
4236 createdAt: "2026-09-08T10:00:02Z",
4237 entry: {
4238 id,
4239 runId,
4240 createdAt: "2026-09-08T10:00:02Z",
4241 label: "Delegated a child task",
4242 tone: failed ? "error" : "tool",
4243 itemType: "dynamic_tool",
4244 toolLifecycleStatus: failed
4245 ? "failed"
4246 : status === "running"
4247 ? "inProgress"
4248 : "completed",
4249 projectedItem: {
4250 item: {
4251 id,
4252 runId,
4253 type: "dynamic_tool",
4254 status: failed ? "failed" : status,
4255 toolName: "t3-code.delegate_task",
4256 input: { task: taskId === "b" ? "a" : taskId, role },
4257 ...(status === "completed"
4258 ? {
4259 output:
4260 envelope === "structured"
4261 ? { content: JSON.stringify({ taskId }), structuredContent: { taskId } }
4262 : envelope === "text"
4263 ? { content: [{ type: "text", text: JSON.stringify({ taskId }) }] }
4264 : { taskId },
4265 }
4266 : {}),
4267 },
4268 } as OrchestrationV2ProjectedTurnItem,
4269 },
4270 });
4271 const rows = deriveMessagesTimelineRows({
4272 ...common,
4273 isWorking: status === "running",
4274 runningRunId: status === "running" ? runId : null,
4275 timelineEntries: [
4276 child("a"),
4277 delegation("delegate-a", "a"),
4278 ...(status === "completed" ? [child("b")] : []),
4279 delegation("delegate-b", "b"),
4280 delegation("unmatched", "other-child"),
4281 child("c"),
4282 delegation("failed", "c", true),
4283 child("d"),
4284 ],
4285 expandedRunIds: new Set([runId]),
4286 });
4287 if (status === "completed") {
4288 expect(rows.find((row) => row.id === "a")).toMatchObject({
4289 subagents: [{ item: { id: "a" } }, { item: { id: "b" } }],
4290 });
4291 expect(rows.some((row) => row.id === "b")).toBe(false);
4292 } else {
4293 expect(rows.find((row) => row.id === "a")).toBeDefined();
4294 expect(rows.find((row) => row.id === "b")).toBeUndefined();
4295 }
4296 expect(rows.find((row) => row.id === "c")).toBeDefined();
4297 expect(rows.find((row) => row.id === "d")).toBeDefined();
4298 const visibleTools = rows.flatMap((row) =>
4299 row.kind === "work" || row.kind === "work-live"
4300 ? row.groupedEntries.map((entry) => entry.id)
4301 : [],
4302 );
4303 expect(visibleTools).toContain("unmatched");
4304 expect(visibleTools).toContain("failed");
4305 expect(visibleTools.includes("delegate-a")).toBe(status === "running");
4306 expect(visibleTools.includes("delegate-b")).toBe(status === "running");
4307 },
4308 );
4309
4310 it("keeps created-chat summaries after the final answer and folds only their timeline rows", () => {
4311 const timelineEntries = [
4312 {
4313 kind: "message" as const,
4314 id: "intro",
4315 createdAt: "2026-09-08T10:00:00Z",
4316 message: {
4317 id: MessageId.make("intro"),
4318 role: "assistant" as const,
4319 text: "Creating the chat",
4320 runId,
4321 streaming: false,
4322 createdAt: "2026-09-08T10:00:00Z",
4323 updatedAt: "2026-09-08T10:00:00Z",
4324 },
4325 },
4326 event("created", "thread_created"),
4327 {
4328 kind: "message" as const,
4329 id: "final",
4330 createdAt: "2026-09-08T10:00:04Z",
4331 message: {
4332 id: MessageId.make("final"),
4333 role: "assistant" as const,
4334 text: "Chat is ready",
4335 runId,
4336 streaming: false,
4337 createdAt: "2026-09-08T10:00:04Z",
4338 updatedAt: "2026-09-08T10:00:04Z",
4339 },
4340 },
4341 ];
4342 const collapsed = deriveMessagesTimelineRows({ ...common, timelineEntries });
4343 expect(collapsed.map((row) => row.id)).toEqual([
4344 "turn-fold:resource-run",
4345 "final",
4346 "summary:created",
4347 "assistant-meta:final",
4348 ]);
4349 expect(collapsed.find((row) => row.id === "summary:created")).toMatchObject({
4350 resourceSummary: true,
4351 });
4352 const expanded = deriveMessagesTimelineRows({
4353 ...common,
4354 timelineEntries,
4355 expandedRunIds: new Set([runId]),
4356 });
4357 expect(expanded.map((row) => row.id)).toEqual([
4358 "turn-fold:resource-run",
4359 "intro",
4360 "created",
4361 "final",
4362 "summary:created",
4363 "assistant-meta:final",
4364 ]);
4365 });
4366
4367 it("shows a created chat after a steer only when that steer's segment is open", () => {
4368 const message = (id: string, role: "user" | "assistant", second: number) => ({
4369 kind: "message" as const,
4370 id,
4371 createdAt: `2026-09-08T10:00:0${second}Z`,
4372 message: {
4373 id: MessageId.make(id),
4374 role,
4375 text: id,
4376 runId,
4377 ...(role === "user" ? { inputIntent: "steer" as const } : {}),
4378 streaming: false,
4379 createdAt: `2026-09-08T10:00:0${second}Z`,
4380 updatedAt: `2026-09-08T10:00:0${second}Z`,
4381 },
4382 });
4383 const timelineEntries = [
4384 message("intro", "assistant", 0),
4385 message("steer", "user", 1),
4386 event("created", "thread_created"),
4387 message("after-steer", "assistant", 3),
4388 message("final", "assistant", 4),
4389 ];
4390 const segmentKey = RunId.make(`${runId}:steer:steer`);
4391 const rowIds = (expanded: RunId[]) =>
4392 deriveMessagesTimelineRows({
4393 ...common,
4394 timelineEntries,
4395 expandedRunIds: new Set(expanded),
4396 }).map((row) => row.id);
4397 expect(rowIds([runId])).not.toContain("created");
4398 expect(rowIds([segmentKey])).toEqual([
4399 `turn-fold:${runId}`,
4400 "steer",
4401 `turn-fold:${segmentKey}`,
4402 "created",
4403 "after-steer",
4404 "final",
4405 "summary:created",
4406 "assistant-meta:final",
4407 ]);
4408 });
4409 });
4410
4411 it.each([true, false])(
4412 "keeps completed responses folded across notification wakes, working=%s",
4413 (isWorking) => {
4414 const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString();
4415 const work = (id: string, run: string, second: number, notification = false) => ({
4416 kind: "work" as const,
4417 id,
4418 createdAt: time(second),
4419 entry: {
4420 id,
4421 runId: RunId.make(run),
4422 createdAt: time(second),
4423 label: id,
4424 tone: "info" as const,
4425 ...(notification ? { itemType: "notification" as const } : {}),
4426 },
4427 });
4428 const answer = (id: string, run: string, second: number) => ({
4429 kind: "message" as const,
4430 id,
4431 createdAt: time(second),
4432 message: {
4433 id: MessageId.make(id),
4434 role: "assistant" as const,
4435 text: id,
4436 runId: RunId.make(run),
4437 createdAt: time(second),
4438 updatedAt: time(second),
4439 streaming: false,
4440 },
4441 });
4442 const rows = deriveMessagesTimelineRows({
4443 timelineEntries: [
4444 work("launch-tools", "initial", 1),
4445 answer("launched", "initial", 5),
4446 work("notification-a", "wake-a", 20, true),
4447 work("read-a", "wake-a", 21),
4448 answer("ack-a", "wake-a", 25),
4449 work("notification-b", "wake-b", 40, true),
4450 work("read-b", "wake-b", 41),
4451 ...(!isWorking ? [answer("ack-b", "wake-b", 45)] : []),
4452 ],
4453 latestRun: {
4454 runId: RunId.make("wake-b"),
4455 status: isWorking ? "running" : "completed",
4456 startedAt: time(40),
4457 completedAt: isWorking ? null : time(45),
4458 },
4459 isWorking,
4460 activeTurnStartedAt: time(40),
4461 turnDiffSummaries: [],
4462 supportsConversationRollback: false,
4463 });
4464 const ids = rows.map((row) => row.id);
4465 expect(ids).toContain("turn-fold:initial");
4466 expect(ids).not.toContain("launch-tools");
4467 expect(ids).toContain("turn-fold:wake-a");
4468 expect(ids.indexOf("notification-a")).toBeLessThan(ids.indexOf("turn-fold:wake-a"));
4469 expect(ids.indexOf("turn-fold:wake-a")).toBeLessThan(ids.indexOf("ack-a"));
4470 const boundary = isWorking ? "working-indicator-row" : "turn-fold:wake-b";
4471 expect(ids).toContain(boundary);
4472 expect(ids.indexOf("notification-b")).toBeLessThan(ids.indexOf(boundary));
4473 if (isWorking) expect(rows.find((row) => row.id === boundary)?.createdAt).toBe(time(40));
4474 },
4475 );
4476
4477 it("keeps the working header in place across worktree setup handoff", () => {
4478 const snapshot: WorktreeSetupSnapshot = {
4479 threadId: ThreadId.make("thread-setup"),
4480 phase: "running",
4481 startedAt: "2026-01-01T00:00:00Z",
4482 endedAt: null,
4483 branch: "feature",
4484 baseRef: "main",
4485 worktreePath: null,
4486 setupScript: null,
4487 stages: [],
4488 error: null,
4489 sequence: 3,
4490 };
4491 const userEntry = {
4492 id: "user-entry",
4493 kind: "message",
4494 createdAt: "2026-01-01T00:00:00Z",
4495 message: {
4496 id: "user-1" as never,
4497 role: "user",
4498 text: "Build it",
4499 runId: null,
4500 createdAt: "2026-01-01T00:00:00Z",
4501 updatedAt: "2026-01-01T00:00:00Z",
4502 streaming: false,
4503 },
4504 } as const;
4505 const assistantEntry = {
4506 id: "assistant-entry",
4507 kind: "message",
4508 createdAt: "2026-01-01T00:00:30Z",
4509 message: {
4510 id: "assistant-1" as never,
4511 role: "assistant",
4512 text: "On it",
4513 runId: "turn-1" as never,
4514 createdAt: "2026-01-01T00:00:30Z",
4515 updatedAt: "2026-01-01T00:00:30Z",
4516 streaming: true,
4517 },
4518 } as const;
4519 const withoutMessages = deriveMessagesTimelineRows({
4520 timelineEntries: [],
4521 isWorking: true,
4522 activeTurnStartedAt: "2026-01-01T00:00:00Z",
4523 turnDiffSummaries: [],
4524 supportsConversationRollback: false,
4525 worktreeSetup: snapshot,
4526 });
4527 expect(withoutMessages).toEqual([
4528 { kind: "working", id: "working-indicator-row", createdAt: snapshot.startedAt },
4529 {
4530 kind: "worktree-setup",
4531 id: "worktree-setup-row",
4532 createdAt: "2026-01-01T00:00:00Z",
4533 snapshot,
4534 embedded: false,
4535 },
4536 ]);
4537
4538 const withMessages = deriveMessagesTimelineRows({
4539 timelineEntries: [userEntry, assistantEntry],
4540 isWorking: true,
4541 activeTurnStartedAt: "2026-01-01T00:00:00Z",
4542 turnDiffSummaries: [],
4543 supportsConversationRollback: false,
4544 worktreeSetup: { ...snapshot, phase: "failed" },
4545 });
4546 expect(withMessages.map((row) => row.kind)).toEqual([
4547 "message",
4548 "worktree-setup",
4549 "working",
4550 "message",
4551 "thinking",
4552 ]);
4553
4554 const stage = (id: "agent" | "setup-script", status: "done" | "running") =>
4555 ({
4556 id,
4557 status,
4558 startedAt: "2026-01-01T00:00:10Z",
4559 endedAt: status === "done" ? "2026-01-01T00:00:11Z" : null,
4560 percent: null,
4561 detail: null,
4562 tail: [],
4563 }) as const;
4564 const asyncSnapshot: WorktreeSetupSnapshot = {
4565 ...snapshot,
4566 stages: [stage("setup-script", "running"), stage("agent", "done")],
4567 };
4568 const liveTurn = {
4569 runId: "turn-1" as never,
4570 status: "running",
4571 startedAt: "2026-01-01T00:00:11Z",
4572 completedAt: null,
4573 } as const;
4574 const asyncRows = deriveMessagesTimelineRows({
4575 timelineEntries: [userEntry],
4576 latestRun: liveTurn,
4577 isWorking: true,
4578 activeTurnStartedAt: "2026-01-01T00:00:00Z",
4579 turnDiffSummaries: [],
4580 supportsConversationRollback: false,
4581 worktreeSetup: asyncSnapshot,
4582 });
4583 expect(asyncRows.map((row) => row.kind)).toEqual(["message", "working", "thinking"]);
4584
4585 const handoffRows = deriveMessagesTimelineRows({
4586 timelineEntries: [userEntry],
4587 isWorking: true,
4588 activeTurnStartedAt: "2026-01-01T00:00:00Z",
4589 turnDiffSummaries: [],
4590 supportsConversationRollback: false,
4591 worktreeSetup: asyncSnapshot,
4592 });
4593 expect(handoffRows.map((row) => row.kind)).toEqual(["message", "working", "worktree-setup"]);
4594 expect(handoffRows[2]).toMatchObject({ kind: "worktree-setup", embedded: false });
4595
4596 const settledRows = deriveMessagesTimelineRows({
4597 timelineEntries: [userEntry],
4598 isWorking: true,
4599 activeTurnStartedAt: "2026-01-01T00:00:00Z",
4600 turnDiffSummaries: [],
4601 supportsConversationRollback: false,
4602 worktreeSetup: {
4603 ...snapshot,
4604 phase: "done",
4605 stages: [stage("setup-script", "done"), stage("agent", "done")],
4606 },
4607 });
4608 expect(settledRows.map((row) => row.kind)).toEqual(["message", "working", "worktree-setup"]);
4609
4610 const finishedRows = deriveMessagesTimelineRows({
4611 timelineEntries: [userEntry],
4612 latestRun: liveTurn,
4613 isWorking: true,
4614 activeTurnStartedAt: "2026-01-01T00:00:00Z",
4615 turnDiffSummaries: [],
4616 supportsConversationRollback: false,
4617 worktreeSetup: {
4618 ...asyncSnapshot,
4619 stages: [stage("setup-script", "done"), stage("agent", "done")],
4620 },
4621 });
4622 expect(finishedRows.map((row) => row.kind)).toEqual(["message", "working", "thinking"]);
4623 });
4624
4625 describe("failed turn transcript", () => {
4626 it.each([
4627 { position: "historical", failureClass: "provider_error" },
4628 { position: "historical", failureClass: "usage_limit" },
4629 { position: "latest", failureClass: "usage_limit" },
4630 ] as const)(
4631 "keeps $position $failureClass failures visible with preceding work grouped appropriately",
4632 ({ position, failureClass }) => {
4633 const isLatest = position === "latest";
4634 const commands = isLatest ? ["pwd", "ls", "false"] : ["pwd"];
4635 const runId = RunId.make("failed-run");
4636 const threadId = ThreadId.make("failed-thread");
4637 const at = DateTime.makeUnsafe("2026-09-20T12:00:00Z");
4638 const base = {
4639 threadId,
4640 runId,
4641 nodeId: null,
4642 providerThreadId: null,
4643 providerTurnId: null,
4644 nativeItemRef: null,
4645 parentItemId: null,
4646 ordinal: 0,
4647 title: null,
4648 startedAt: at,
4649 completedAt: at,
4650 updatedAt: at,
4651 };
4652 const items: OrchestrationV2ProjectedTurnItem[] = [
4653 {
4654 position: 0,
4655 visibility: "local",
4656 sourceThreadId: threadId,
4657 sourceItemId: TurnItemId.make("user"),
4658 item: {
4659 ...base,
4660 id: TurnItemId.make("user"),
4661 type: "user_message",
4662 status: "completed",
4663 messageId: MessageId.make("user"),
4664 createdBy: "user",
4665 creationSource: "web",
4666 inputIntent: "turn_start",
4667 text: "Build it",
4668 attachments: [],
4669 },
4670 },
4671 ...commands.map((input, index): OrchestrationV2ProjectedTurnItem => ({
4672 position: index + 1,
4673 visibility: "local",
4674 sourceThreadId: threadId,
4675 sourceItemId: TurnItemId.make(index === 0 ? "command" : `command-${index}`),
4676 item: {
4677 ...base,
4678 id: TurnItemId.make(index === 0 ? "command" : `command-${index}`),
4679 ordinal: index + 1,
4680 type: "command_execution",
4681 status: "completed",
4682 input,
4683 output: "",
4684 exitCode: 0,
4685 },
4686 })),
4687 {
4688 position: commands.length + 1,
4689 visibility: "local",
4690 sourceThreadId: threadId,
4691 sourceItemId: TurnItemId.make("failure"),
4692 item: {
4693 ...base,
4694 id: TurnItemId.make("failure"),
4695 type: "error",
4696 status: "failed",
4697 failure: {
4698 class: failureClass,
4699 message: "The provider stopped this turn.\nRetry later.",
4700 code: null,
4701 retryable: true,
4702 },
4703 },
4704 },
4705 ];
4706 const rows = deriveMessagesTimelineRows({
4707 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
4708 visibleTurnItems: items,
4709 optimisticMessages: [],
4710 }).map((entry) =>
4711 isLatest
4712 ? entry
4713 : {
4714 ...entry,
4715 attempt: {
4716 id: RunAttemptId.make("superseded-attempt"),
4717 runId,
4718 attemptOrdinal: 1,
4719 rootNodeId: NodeId.make("superseded-root"),
4720 status: "superseded" as const,
4721 completedAt: null,
4722 },
4723 },
4724 ),
4725 latestRun: {
4726 runId: isLatest ? runId : RunId.make("newer-run"),
4727 status: isLatest ? "failed" : "completed",
4728 startedAt: DateTime.formatIso(at),
4729 completedAt: DateTime.formatIso(at),
4730 },
4731 isWorking: false,
4732 turnDiffSummaries: [],
4733 supportsConversationRollback: false,
4734 });
4735 expect(rows.some((row) => row.kind === "turn-fold" || row.kind === "attempt-fold")).toBe(
4736 false,
4737 );
4738 const work = rows.flatMap((row) => (row.kind === "work" ? row.groupedEntries : []));
4739 expect(rows.find((row) => row.kind === "work-toggle")).toEqual(
4740 isLatest ? expect.objectContaining({ hiddenCount: 3, expanded: false }) : undefined,
4741 );
4742 expect(work.map((entry) => entry.id)).toEqual(
4743 isLatest ? ["failure"] : ["command", "failure"],
4744 );
4745 expect(work.at(-1)?.detail).toBe("The provider stopped this turn.\nRetry later.");
4746 expect(work.at(-1)?.createdAt).toBe("2026-09-20T12:00:00.000Z");
4747 if (isLatest) return;
4748 const entriesWithoutTools = deriveTimelineEntriesFromVisibleTurnItems({
4749 visibleTurnItems: items.filter((row) => row.item.type !== "command_execution"),
4750 optimisticMessages: [],
4751 });
4752 entriesWithoutTools.splice(1, 0, {
4753 kind: "message",
4754 id: "assistant-before-failure",
4755 createdAt: DateTime.formatIso(at),
4756 message: {
4757 id: MessageId.make("assistant-before-failure"),
4758 role: "assistant",
4759 runId,
4760 text: "Checking the workspace.",
4761 createdAt: DateTime.formatIso(at),
4762 updatedAt: DateTime.formatIso(at),
4763 streaming: false,
4764 },
4765 });
4766 const compactRows = deriveMessagesTimelineRows({
4767 timelineEntries: entriesWithoutTools,
4768 isWorking: false,
4769 turnDiffSummaries: [],
4770 supportsConversationRollback: false,
4771 });
4772 expect(compactRows.map((row) => row.kind)).toEqual([
4773 "message",
4774 "message",
4775 "work",
4776 "assistant-meta",
4777 ]);
4778 expect(compactRows[1]).toMatchObject({ showAssistantMeta: false });
4779 expect(compactRows.at(-1)).toMatchObject({
4780 kind: "assistant-meta",
4781 showAssistantCopyButton: true,
4782 message: { id: "assistant-before-failure" },
4783 });
4784 },
4785 );
4786 });
4787
4788 describe("live subagents after their parent turn settles", () => {
4789 const runId = RunId.make("parent-run");
4790 const threadId = ThreadId.make("parent-thread");
4791 const providerTurnId = ProviderTurnId.make("parent-provider-turn");
4792 const at = (second: number) =>
4793 DateTime.makeUnsafe(`2026-10-06T10:00:${String(second).padStart(2, "0")}Z`);
4794 const base = (id: string, second: number) => ({
4795 id: TurnItemId.make(id),
4796 threadId,
4797 runId,
4798 nodeId: null,
4799 providerThreadId: null,
4800 providerTurnId,
4801 nativeItemRef: null,
4802 parentItemId: null,
4803 ordinal: second,
4804 title: null,
4805 startedAt: at(second),
4806 completedAt: at(second),
4807 updatedAt: at(second),
4808 });
4809 const projected = (item: OrchestrationV2TurnItem): OrchestrationV2ProjectedTurnItem => ({
4810 position: item.ordinal,
4811 visibility: "local",
4812 sourceThreadId: threadId,
4813 sourceItemId: item.id,
4814 item,
4815 });
4816 const child = (
4817 id: string,
4818 second: number,
4819 status: OrchestrationV2TurnItem["status"],
4820 origin: "app_owned" | "provider_native" = "app_owned",
4821 ): OrchestrationV2TurnItem => ({
4822 ...base(id, second),
4823 status,
4824 completedAt: status === "running" ? null : at(second),
4825 type: "subagent",
4826 subagentId: NodeId.make(id),
4827 origin,
4828 driver: ProviderDriverKind.make("codex"),
4829 providerInstanceId: ProviderInstanceId.make("codex"),
4830 childThreadId: origin === "app_owned" ? ThreadId.make(`${id}-thread`) : null,
4831 prompt: `Inspect ${id}`,
4832 result: null,
4833 });
4834 const rowsFor = (children: ReadonlyArray<OrchestrationV2TurnItem>) =>
4835 deriveMessagesTimelineRows({
4836 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
4837 visibleTurnItems: (
4838 [
4839 {
4840 ...base("user", 0),
4841 status: "completed",
4842 type: "user_message",
4843 messageId: MessageId.make("user"),
4844 createdBy: "user",
4845 creationSource: "web",
4846 inputIntent: "turn_start",
4847 text: "Delegate the review",
4848 attachments: [],
4849 },
4850 {
4851 ...base("reasoning", 1),
4852 status: "completed",
4853 type: "reasoning",
4854 text: "Two children can split this.",
4855 streaming: false,
4856 },
4857 {
4858 ...base("command", 2),
4859 status: "completed",
4860 type: "command_execution",
4861 input: "pwd",
4862 output: "/repo",
4863 exitCode: 0,
4864 },
4865 ...children,
4866 {
4867 ...base("assistant", 8),
4868 status: "completed",
4869 type: "assistant_message",
4870 messageId: MessageId.make("assistant"),
4871 text: "Both children are running.",
4872 streaming: false,
4873 },
4874 ] satisfies OrchestrationV2TurnItem[]
4875 ).map(projected),
4876 optimisticMessages: [],
4877 }),
4878 latestRun: {
4879 runId,
4880 status: "completed",
4881 startedAt: DateTime.formatIso(at(0)),
4882 completedAt: DateTime.formatIso(at(8)),
4883 },
4884 isWorking: false,
4885 turnDiffSummaries: [],
4886 supportsConversationRollback: false,
4887 });
4888
4889 it.each(["app_owned", "provider_native"] as const)(
4890 "keeps a running %s child visible while the rest of the settled turn folds",
4891 (origin) => {
4892 const rows = rowsFor([child("child", 3, "running", origin)]);
4893 expect(rows.map((row) => row.id)).toEqual([
4894 "user",
4895 `turn-fold:${runId}`,
4896 "child",
4897 "assistant",
4898 ]);
4899 },
4900 );
4901
4902 it("keeps a launch batch visible while any member is still running", () => {
4903 const rows = rowsFor([child("done", 3, "completed"), child("live", 4, "running")]);
4904 expect(rows.map((row) => row.id)).toEqual(["user", `turn-fold:${runId}`, "done", "assistant"]);
4905 expect(rows.find((row) => row.id === "done")).toMatchObject({
4906 subagents: [{ item: { id: "done" } }, { item: { id: "live" } }],
4907 });
4908 });
4909
4910 it("keeps a running child visible when a steer supersedes its attempt", () => {
4911 const attempt = {
4912 id: RunAttemptId.make("superseded-attempt"),
4913 runId,
4914 attemptOrdinal: 1,
4915 rootNodeId: NodeId.make("superseded-root"),
4916 status: "superseded" as const,
4917 completedAt: null,
4918 };
4919 const entries = deriveTimelineEntriesFromVisibleTurnItems({
4920 visibleTurnItems: (
4921 [
4922 {
4923 ...base("command", 2),
4924 status: "completed",
4925 type: "command_execution",
4926 input: "pwd",
4927 output: "/repo",
4928 exitCode: 0,
4929 },
4930 child("child", 3, "running"),
4931 ] satisfies OrchestrationV2TurnItem[]
4932 ).map(projected),
4933 optimisticMessages: [],
4934 }).map((entry) => ({ ...entry, attempt }));
4935 const rows = deriveMessagesTimelineRows({
4936 timelineEntries: entries,
4937 latestRun: {
4938 runId,
4939 status: "running",
4940 startedAt: DateTime.formatIso(at(0)),
4941 completedAt: null,
4942 },
4943 isWorking: false,
4944 turnDiffSummaries: [],
4945 supportsConversationRollback: false,
4946 });
4947 expect(rows.map((row) => row.id)).toEqual([`attempt-fold:${attempt.id}`, "child"]);
4948 });
4949 });
4950
4951 describe("parent run waiting on foreground subagents", () => {
4952 const runId = RunId.make("parent-run");
4953 const threadId = ThreadId.make("parent-thread");
4954 const at = (second: number) =>
4955 DateTime.makeUnsafe(`2026-10-06T10:00:${String(second).padStart(2, "0")}Z`);
4956 const base = (id: string, second: number) => ({
4957 id: TurnItemId.make(id),
4958 threadId,
4959 runId,
4960 nodeId: null,
4961 providerThreadId: null,
4962 providerTurnId: ProviderTurnId.make("parent-provider-turn"),
4963 nativeItemRef: null,
4964 parentItemId: null,
4965 ordinal: second,
4966 title: null,
4967 startedAt: at(second),
4968 completedAt: at(second),
4969 updatedAt: at(second),
4970 });
4971 const child = (id: string, second: number): OrchestrationV2TurnItem => ({
4972 ...base(id, second),
4973 status: "running",
4974 completedAt: null,
4975 type: "subagent",
4976 subagentId: NodeId.make(id),
4977 origin: "provider_native",
4978 driver: ProviderDriverKind.make("opencode"),
4979 providerInstanceId: ProviderInstanceId.make("opencode"),
4980 childThreadId: null,
4981 prompt: `Read ${id}`,
4982 result: null,
4983 });
4984
4985 const liveRow = (later: ReadonlyArray<OrchestrationV2TurnItem>, toolCallVisibility?: "hideAll") =>
4986 deriveMessagesTimelineRows({
4987 timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
4988 visibleTurnItems: (
4989 [
4990 {
4991 ...base("user", 0),
4992 status: "completed",
4993 type: "user_message",
4994 messageId: MessageId.make("user"),
4995 createdBy: "user",
4996 creationSource: "web",
4997 inputIntent: "turn_start",
4998 text: "Research these in parallel",
4999 attachments: [],
5000 },
Showing first 5,000 of 5,186 lines. View raw