sailfork / t3code-github / apps/ web/ src/ components/ chat/ MessagesTimeline.logic.test.ts

import { ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts";
import {
  CheckpointRef,
  NodeId,
  ProviderDriverKind,
  ProviderInstanceId,
  ProviderTurnId,
  RunAttemptId,
  TurnItemId,
  RuntimeRequestId,
  type OrchestrationV2ProjectedTurnItem,
  type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import {
  deriveTimelineEntriesFromVisibleTurnItems,
  deriveTimelineEntriesFromVisibleTurnItemsWithState,
  workEntryDisplayIndicatesToolFailure,
  type TimelineEntry,
} from "../../session-logic";
import { makeStreamingTimelineFixture } from "../../test-fixtures";
import type { TurnDiffSummary } from "../../types";
import { describe, expect, it } from "vite-plus/test";
import { EnvironmentId, MessageId, RunId } from "@t3tools/contracts";
import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
import {
  computeStableMessagesTimelineRows,
  deriveMessagesTimelineRows,
  timelineTurnFoldRunIdsByEntryId,
  liveAnswerPreview,
  deriveMessagesTimelineRowsWithState,
  shouldCollapseUserMessage,
  resolveAssistantMessageCopyState,
  type MessagesTimelineRow,
  workEntryDisplayLabel,
} from "./MessagesTimeline.logic";

describe("resolveAssistantMessageCopyState", () => {
  it("copies the rendered representation of Codex directives", () => {
    expect(
      resolveAssistantMessageCopyState({
        showCopyButton: true,
        text: [
          'Created :codex-file-citation{path="outputs/report.xlsx" purpose="output"}.',
          "",
          '::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"}',
        ].join("\n"),
        streaming: false,
      }),
    ).toEqual({
      text: "Created [report.xlsx](<outputs/report.xlsx>).\n\nHello World (Document template)",
      visible: true,
    });
  });
});

describe("deriveMessagesTimelineRows", () => {
  it.each(["alone", "before tool", "before commentary and tool"])(
    "keeps an unfinished task update static %s",
    (placement) => {
      const runId = RunId.make("task-update-run");
      const at = "2026-11-06T00:00:00Z";
      const tasks: TimelineEntry = {
        kind: "work",
        id: "tasks",
        createdAt: at,
        entry: {
          id: "tasks",
          runId,
          createdAt: at,
          itemType: "todo_list",
          tone: "info",
          label: "Tasks 0/1 · Inspect the captures",
          toolLifecycleStatus: "inProgress",
        },
      };
      const commentary: TimelineEntry = {
        kind: "message",
        id: "commentary",
        createdAt: at,
        message: {
          id: MessageId.make("commentary"),
          role: "assistant",
          text: "Checking the rendering.",
          runId,
          streaming: false,
          createdAt: at,
          updatedAt: at,
        },
      };
      const tool: TimelineEntry = {
        kind: "work",
        id: "tool",
        createdAt: at,
        entry: {
          id: "tool",
          runId,
          createdAt: at,
          label: "Running sed",
          command: "sed",
          tone: "tool",
          toolLifecycleStatus: "inProgress",
        },
      };
      const rows = deriveMessagesTimelineRows({
        timelineEntries: [
          tasks,
          ...(placement === "before commentary and tool" ? [commentary] : []),
          ...(placement === "alone" ? [] : [tool]),
        ],
        runningRunId: runId,
        isWorking: true,
        activeTurnStartedAt: at,
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
      expect(rows.find((row) => row.id === "tasks")).toMatchObject({
        kind: "work",
        groupedEntries: [tasks.entry],
      });
      expect(rows.filter((row) => row.kind === "work-live" && row.active)).toEqual(
        placement === "alone" ? [] : [expect.objectContaining({ entry: tool.entry })],
      );
    },
  );

  it("stops stranded thinking after a steer and follows the next thought or tool", () => {
    const runId = RunId.make("steered-run");
    const at = "2026-10-01T06:19:10Z";
    const thought = (id: string): TimelineEntry => ({
      kind: "work",
      id,
      createdAt: at,
      entry: {
        id,
        runId,
        createdAt: at,
        label: "Thinking",
        tone: "thinking",
        itemType: "reasoning",
        detail: id,
        toolLifecycleStatus: "inProgress",
      },
    });
    const steer: TimelineEntry = {
      kind: "message",
      id: "steer",
      createdAt: at,
      message: {
        id: MessageId.make("steer"),
        role: "user",
        text: "Also evaluate speed",
        runId,
        inputIntent: "steer",
        streaming: false,
        createdAt: at,
        updatedAt: at,
      },
    };
    const first = thought("first-thought");
    const next = thought("next-thought");
    const tool: TimelineEntry = {
      kind: "work",
      id: "tool",
      createdAt: at,
      entry: {
        id: "tool",
        runId,
        createdAt: at,
        label: "Running cat",
        tone: "tool",
        command: "cat file",
        toolLifecycleStatus: "inProgress",
      },
    };
    const rows = (timelineEntries: ReadonlyArray<TimelineEntry>) =>
      deriveMessagesTimelineRows({
        timelineEntries,
        runningRunId: runId,
        isWorking: true,
        activeTurnStartedAt: at,
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
    expect(rows([first]).find((row) => row.kind === "work-live")).toMatchObject({
      active: true,
      entry: { id: "first-thought" },
    });
    const afterSteer = rows([first, steer]);
    expect(afterSteer.some((row) => row.kind === "work-live")).toBe(false);
    expect(afterSteer.at(-1)?.kind).toBe("thinking");
    expect(afterSteer.find((row) => row.kind === "work")).toMatchObject({
      groupedEntries: [{ id: "first-thought", toolLifecycleStatus: "completed" }],
    });
    for (const entries of [
      [first, steer, next],
      [first, next],
      [first, steer, next, tool],
    ]) {
      const live = rows(entries).filter((row) => row.kind === "work-live" && row.active);
      expect(live).toHaveLength(1);
      expect(live[0]).toMatchObject({ entry: { id: entries.at(-1)!.id } });
    }
    expect(first.kind === "work" && first.entry.toolLifecycleStatus).toBe("inProgress");
  });

  it("recovers the failed Sky call stored as a generic js integration", () => {
    const fixture = makeStreamingTimelineFixture();
    const source = fixture.visibleTurnItems.find((row) => row.item.type === "dynamic_tool")!;
    if (source.item.type !== "dynamic_tool") throw new Error("Expected tool fixture");
    const item = {
      ...source.item,
      type: "dynamic_tool" as const,
      status: "failed" as const,
      title: "js",
      toolName: "node_repl.js",
      toolSource: { key: "mcp:node_repl", name: "node repl", kind: "integration" as const },
      input: {
        title: "Restrict the breakpoint to Git actions",
        code: "await sky.type_text({app:'T3 Code (Nightly)',text:'debug(ga.run)'});",
      },
    };
    const entries = deriveTimelineEntriesFromVisibleTurnItems({
      visibleTurnItems: [{ ...source, item }],
      optimisticMessages: [],
    });
    const entry = entries.find((row) => row.kind === "work");
    expect(entry?.kind === "work" && workEntryDisplayLabel(entry.entry, undefined)).toBe(
      "Restrict the breakpoint to Git actions",
    );
    expect(entry?.kind === "work" && entry.entry).toMatchObject({
      toolSurface: "computer",
      toolSource: { key: "computer-use", kind: "computer" },
    });
  });

  it.each(["waiting", "completed"] as const)(
    "groups approval and user-input requests with commands without expanding them when %s",
    (status) => {
      const fixture = makeStreamingTimelineFixture();
      const source = fixture.visibleTurnItems[0]!;
      const common = {
        ...source.item,
        threadId: fixture.threadId,
        runId: fixture.runId,
        nodeId: null,
        providerThreadId: null,
        providerTurnId: null,
        nativeItemRef: null,
        parentItemId: null,
        status,
      };
      const items: OrchestrationV2ProjectedTurnItem["item"][] = [
        {
          ...common,
          id: TurnItemId.make("command"),
          type: "command_execution",
          input: "pwd",
          output: "",
        },
        {
          ...common,
          id: TurnItemId.make("approval"),
          type: "approval_request",
          requestId: RuntimeRequestId.make("approval-request"),
          requestKind: "command",
          prompt: "Allow pwd?",
        },
        {
          ...common,
          id: TurnItemId.make("input"),
          type: "user_input_request",
          requestId: RuntimeRequestId.make("input-request"),
          questions: [],
        },
      ];
      const entries = deriveTimelineEntriesFromVisibleTurnItems({
        visibleTurnItems: items.map((item, position) => ({
          ...source,
          item,
          position,
          sourceItemId: item.id,
        })),
        optimisticMessages: [],
      });
      expect(entries.map((entry) => entry.kind)).toEqual(["work", "work", "work"]);
      const rows = deriveMessagesTimelineRows({
        timelineEntries: entries,
        isWorking: status === "waiting",
        runningRunId: fixture.runId,
        activeTurnStartedAt: fixture.time(0),
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
      const workRows = rows.filter((row) => row.kind === "work-toggle" || row.kind === "work-live");
      expect(workRows).toHaveLength(1);
      expect(workRows[0]).toMatchObject({ expanded: false });
      const expandedRows = deriveMessagesTimelineRows({
        timelineEntries: entries,
        isWorking: status === "waiting",
        runningRunId: fixture.runId,
        activeTurnStartedAt: fixture.time(0),
        turnDiffSummaries: [],
        supportsConversationRollback: false,
        expandedWorkGroupIds: new Set([workRows[0]!.groupId]),
      });
      const expanded = expandedRows.find((row) => row.kind === "work" && row.isExpandedToolGroup);
      expect(
        expanded?.kind === "work" && expanded.groupedEntries.map((entry) => entry.itemType),
      ).toEqual(["command_execution", "approval_request", "user_input_request"]);
      expect(rows.some((row) => row.kind === "event")).toBe(false);
      expect(workRows[0]).not.toMatchObject({ expanded: true });
      expect(workRows[0]).not.toMatchObject({ isExpandedToolGroup: true });
      const pendingRows = deriveMessagesTimelineRows({
        timelineEntries: entries,
        pendingApprovalRequestIds: new Set([RuntimeRequestId.make("approval-request")]),
        isWorking: status === "waiting",
        runningRunId: fixture.runId,
        activeTurnStartedAt: fixture.time(0),
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
      expect(pendingRows.filter((row) => row.kind === "work")).toContainEqual(
        expect.objectContaining({
          groupedEntries: [expect.objectContaining({ itemType: "approval_request" })],
          isExpandedToolGroup: false,
        }),
      );
      expect(
        pendingRows
          .filter((row) => row.kind === "work-live")
          .flatMap((row) => row.groupedEntries)
          .some((entry) => entry.itemType === "approval_request"),
      ).toBe(false);
      const approvalOnlyRows = deriveMessagesTimelineRows({
        timelineEntries: entries.slice(1, 2),
        pendingApprovalRequestIds: new Set([RuntimeRequestId.make("approval-request")]),
        isWorking: status === "waiting",
        runningRunId: fixture.runId,
        activeTurnStartedAt: fixture.time(0),
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
      expect(approvalOnlyRows.some((row) => row.kind === "thinking")).toBe(false);
    },
  );

  it.each(["running", "completed", "superseded"] as const)(
    "keeps system notices visible as non-failing warnings through %s work",
    (state) => {
      const fixture = makeStreamingTimelineFixture();
      const message =
        "Claude changed its safety mode.\nReview the active permission settings before continuing.";
      const source: OrchestrationV2ProjectedTurnItem = {
        ...fixture.visibleTurnItems[0]!,
        sourceItemId: TurnItemId.make("safety-notice"),
        item: {
          id: TurnItemId.make("safety-notice"),
          threadId: fixture.threadId,
          runId: fixture.runId,
          nodeId: null,
          providerThreadId: null,
          providerTurnId: null,
          nativeItemRef: null,
          parentItemId: null,
          ordinal: 1,
          startedAt: DateTime.makeUnsafe(fixture.time(1)),
          completedAt: DateTime.makeUnsafe(fixture.time(1)),
          updatedAt: DateTime.makeUnsafe(fixture.time(1)),
          type: "system_notice",
          message,
          title: message,
          status: "completed",
        },
      };
      const [notice] = deriveTimelineEntriesFromVisibleTurnItems({
        visibleTurnItems: [source],
        optimisticMessages: [],
      });
      if (notice?.kind !== "work") throw new Error("Expected a notice work entry");
      expect(notice.entry.projectedItem).toBe(source);
      expect(notice.entry.sourceActivityKind).toBe("runtime.warning");
      expect(workEntryDisplayLabel(notice.entry, undefined)).toBe(message);
      expect(workEntryDisplayIndicatesToolFailure(notice.entry)).toBe(false);
      const rows = deriveMessagesTimelineRows({
        timelineEntries: [
          {
            ...notice,
            ...(state === "superseded"
              ? {
                  attempt: {
                    id: "old-attempt" as never,
                    runId: fixture.runId,
                    status: "superseded" as const,
                    attemptOrdinal: 0,
                    rootNodeId: "old-root" as never,
                    completedAt: null,
                  },
                }
              : {}),
          },
          {
            id: "nearby-tool",
            kind: "work",
            createdAt: notice.createdAt,
            entry: {
              id: "nearby-tool",
              runId: fixture.runId,
              createdAt: notice.createdAt,
              label: "Ran command",
              tone: "tool",
              toolLifecycleStatus: "completed",
            },
          },
          {
            id: "terminal-message",
            kind: "message",
            createdAt: notice.createdAt,
            message: {
              id: MessageId.make("terminal-message"),
              runId: fixture.runId,
              role: "assistant",
              text: "Continuing with the selected settings.",
              createdAt: notice.createdAt,
              updatedAt: notice.createdAt,
              streaming: state === "running",
            },
          },
        ],
        isWorking: state === "running",
        activeTurnStartedAt: notice.createdAt,
        latestRun: {
          runId: fixture.runId,
          status: state === "running" ? "running" : "completed",
          startedAt: notice.createdAt,
          completedAt: state === "running" ? null : notice.createdAt,
        },
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
      const row = rows.find(
        (row) => row.kind === "work" && row.groupedEntries.includes(notice.entry),
      );
      expect(row).toMatchObject({ kind: "work", groupedEntries: [notice.entry] });
    },
  );

  it.each([false, true])(
    "gives live compaction the activity slot and restores Thinking (runless: %s)",
    (runless) => {
      const fixture = makeStreamingTimelineFixture();
      const last = fixture.visibleTurnItems.at(-1)!;
      if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
      const compact = {
        ...last,
        item: {
          ...last.item,
          type: "compaction" as const,
          status: "running" as const,
          driver: null,
          beforeTokenCount: 899_000,
        },
      };
      const input = {
        isWorking: true,
        runningRunId: fixture.runId,
        activeTurnStartedAt: fixture.time(5),
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      };
      const runningEntries = deriveTimelineEntriesFromVisibleTurnItems({
        visibleTurnItems: [...fixture.visibleTurnItems.slice(0, -1), compact],
        optimisticMessages: [],
      });
      const runningRows = deriveMessagesTimelineRows({
        ...input,
        runningRunId: runless ? null : fixture.runId,
        runlessWorkActive: runless,
        timelineEntries: runless
          ? runningEntries.map((entry) =>
              entry.kind === "work" ? { ...entry, entry: { ...entry.entry, runId: null } } : entry,
            )
          : runningEntries,
      });
      expect(runningRows.find((row) => row.kind === "context-compaction")).toMatchObject({
        active: true,
        label: "Compacting context",
      });
      expect(runningRows.some((row) => row.kind === "thinking")).toBe(false);

      const completedRows = deriveMessagesTimelineRows({
        ...input,
        timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
          visibleTurnItems: [
            ...fixture.visibleTurnItems.slice(0, -1),
            {
              ...compact,
              item: { ...compact.item, status: "completed", afterTokenCount: 19_000 },
            },
          ],
          optimisticMessages: [],
        }),
      });
      expect(completedRows.find((row) => row.kind === "context-compaction")).toMatchObject({
        active: false,
        label: "Context compacted 899K → 19K tokens",
        tokenCounts: { before: "899K", after: "19K" },
      });
      expect(completedRows.at(-1)?.kind).toBe("thinking");

      const settledRows = deriveMessagesTimelineRows({
        ...input,
        isWorking: false,
        timelineEntries: runningEntries,
      });
      expect(settledRows.find((row) => row.kind === "context-compaction")).toMatchObject({
        active: false,
      });
      const stable = computeStableMessagesTimelineRows(runningRows, {
        result: [],
        byId: new Map(),
      });
      expect(computeStableMessagesTimelineRows(settledRows, stable).result).toEqual(settledRows);
    },
  );

  it("shows each compaction trigger as one live status, then a reasoned token divider", () => {
    const fixture = makeStreamingTimelineFixture();
    const [history0, history1, history2, liveUser, , liveAssistant] = fixture.visibleTurnItems;
    if (liveUser?.item.type !== "user_message" || liveAssistant?.item.type !== "assistant_message")
      throw new Error("Expected live fixture items");
    const compactPrompt = (idleCompaction: "beforeCacheExpires" | "onReturn" | undefined) => ({
      ...liveUser,
      item: { ...liveUser.item, text: "/compact", idleCompaction },
    });
    const compaction = {
      ...liveAssistant,
      item: {
        ...liveAssistant.item,
        type: "compaction" as const,
        driver: null,
        beforeTokenCount: 899_000,
      },
    };
    const rowsFor = (visibleTurnItems: OrchestrationV2ProjectedTurnItem[], isWorking = true) =>
      deriveMessagesTimelineRows({
        timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
          visibleTurnItems: [history0!, history1!, history2!, ...visibleTurnItems],
          optimisticMessages: [],
        }),
        isWorking,
        runningRunId: fixture.runId,
        latestRun: {
          runId: fixture.runId,
          status: isWorking ? "running" : "completed",
          startedAt: fixture.time(5),
          completedAt: isWorking ? null : fixture.time(9),
        },
        activeTurnStartedAt: fixture.time(5),
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });

    // Only compacting on return holds a sent message back, so only it speaks through the working
    // row; the others keep their live divider.
    for (const [reason, live, title] of [
      [
        "beforeCacheExpires",
        {
          kind: "context-compaction",
          active: true,
          label: "Compacting before the cache expires…",
        },
        "Context automatically compacted before cache expiry",
      ],
      ["onReturn", { kind: "working", compacting: true }, "Context compacted before sending"],
      [undefined, { kind: "context-compaction", active: true }, undefined],
    ] as const) {
      const prompt = compactPrompt(reason);
      for (const rows of [rowsFor([prompt]), rowsFor([prompt, compaction])]) {
        const liveRows = rows.slice(
          rows.findIndex((row) => row.id.includes("history-assistant")) + 1,
        );
        expect(liveRows).toMatchObject([live]);
      }
      const completed = rowsFor(
        [
          prompt,
          {
            ...compaction,
            item: { ...compaction.item, status: "completed", afterTokenCount: 19_000 },
          },
        ],
        false,
      );
      const liveRows = completed.slice(
        completed.findIndex((row) => row.id.includes("history-assistant")) + 1,
      );
      expect(liveRows).toMatchObject([
        {
          kind: "context-compaction",
          active: false,
          tokenCounts: { before: "899K", after: "19K" },
        },
      ]);
      expect(liveRows[0]?.kind === "context-compaction" ? liveRows[0].title : null).toBe(title);
      const terminalCompaction = {
        ...compaction,
        item: { ...compaction.item, status: "completed" as const, afterTokenCount: 19_000 },
      };
      const finishingRows = rowsFor([prompt, terminalCompaction]);
      const finishingLiveRows = finishingRows.slice(
        finishingRows.findIndex((row) => row.id.includes("history-assistant")) + 1,
      );
      expect(finishingLiveRows).toEqual(liveRows);
      const continuingRows = rowsFor([
        prompt,
        terminalCompaction,
        { ...liveAssistant, item: { ...liveAssistant.item, id: TurnItemId.make("continued") } },
      ]);
      expect(continuingRows.filter((row) => row.kind === "context-compaction")).toHaveLength(1);
      expect(continuingRows.filter((row) => row.kind === "working")).toMatchObject([
        { kind: "working" },
      ]);
      expect(continuingRows.some((row) => row.kind === "working" && row.compacting)).toBe(false);
      const retries = rowsFor(
        [
          prompt,
          {
            ...compaction,
            item: { ...compaction.item, status: "failed", summary: "retry needed" },
          },
          {
            ...compaction,
            item: {
              ...compaction.item,
              id: TurnItemId.make("retry-compaction"),
              status: "completed",
            },
          },
        ],
        false,
      ).filter((row) => row.kind === "context-compaction");
      expect(retries).toHaveLength(2);
      expect(retries[0]).toMatchObject({ failed: true, failure: "retry needed" });
      expect(new Set(retries.map((row) => row.id)).size).toBe(2);
      const stable = computeStableMessagesTimelineRows(retries, { result: [], byId: new Map() });
      expect(computeStableMessagesTimelineRows(retries, stable).result).toEqual(retries);
    }
  });

  it.each(["/compact", "Continue"])(
    "keeps a completed compaction divider visible while other settled work folds for %s",
    (promptText) => {
      const fixture = makeStreamingTimelineFixture();
      const [, , , liveUser, liveWork, liveAssistant] = fixture.visibleTurnItems;
      if (
        liveUser?.item.type !== "user_message" ||
        liveAssistant?.item.type !== "assistant_message" ||
        !liveWork
      )
        throw new Error("Expected live fixture items");
      const rows = deriveMessagesTimelineRows({
        timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
          visibleTurnItems: [
            { ...liveUser, item: { ...liveUser.item, text: promptText } },
            liveWork,
            {
              ...liveAssistant,
              item: {
                ...liveAssistant.item,
                type: "compaction",
                driver: null,
                status: "completed",
                beforeTokenCount: 100_000,
                afterTokenCount: 20_000,
              },
            },
          ],
          optimisticMessages: [],
        }),
        isWorking: false,
        latestRun: {
          runId: fixture.runId,
          status: "completed",
          startedAt: fixture.time(5),
          completedAt: fixture.time(8),
        },
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
      expect(rows.filter((row) => row.kind === "turn-fold")).toHaveLength(1);
      expect(rows.some((row) => row.kind === "work")).toBe(false);
      expect(rows.filter((row) => row.kind === "context-compaction")).toMatchObject([
        { active: false, tokenCounts: { before: "100K", after: "20K" } },
      ]);
      if (promptText === "/compact") {
        expect(rows.some((row) => row.kind === "message")).toBe(false);
      }
    },
  );

  it("folds an answered compact-on-return question into its compaction row", () => {
    const fixture = makeStreamingTimelineFixture();
    const [history0, history1, history2, liveUser, liveWork, liveAssistant] =
      fixture.visibleTurnItems;
    if (liveWork?.item.type !== "dynamic_tool" || liveAssistant?.item.type !== "assistant_message")
      throw new Error("Expected live fixture items");
    const { toolName: _toolName, input: _input, output: _output, ...workBase } = liveWork.item;
    const question =
      "This session is 1h 5m old and uses 412,000 tokens. Compact it before continuing?";
    const requestId = RuntimeRequestId.make("resume-compaction");
    const answered = {
      ...liveWork,
      item: {
        ...workBase,
        type: "user_input_request" as const,
        requestId,
        questions: [],
        questionAnswer: {
          requestId,
          questionTextById: { resume: question },
          answers: { resume: "Compact and continue" },
          attachmentsByQuestionId: {},
        },
      },
    };
    const assistantItem = liveAssistant.item;
    // The answer can come long after the turn starts; the row times the compaction itself.
    const compactionStartedAt = DateTime.makeUnsafe(fixture.time(65));
    const compactionAt = (status: "running" | "completed") => ({
      ...liveAssistant,
      item: {
        ...assistantItem,
        type: "compaction" as const,
        status,
        driver: null,
        startedAt: compactionStartedAt,
      },
    });
    const rowsFor = (status: "running" | "completed", laterCompaction = false) =>
      deriveMessagesTimelineRows({
        timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
          visibleTurnItems: [
            history0!,
            history1!,
            history2!,
            liveUser!,
            answered,
            compactionAt(laterCompaction ? "completed" : status),
            ...(laterCompaction
              ? [
                  {
                    ...compactionAt(status),
                    item: {
                      ...compactionAt(status).item,
                      id: TurnItemId.make("later-compaction"),
                    },
                  },
                ]
              : []),
          ],
          optimisticMessages: [],
        }),
        isWorking: status === "running",
        runningRunId: fixture.runId,
        activeTurnStartedAt: fixture.time(5),
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
    const liveRows = (status: "running" | "completed") => {
      const rows = rowsFor(status);
      return rows.slice(rows.findIndex((row) => row.id.includes("live-user")) + 1);
    };
    expect(liveRows("running")).toMatchObject([
      { kind: "working", compacting: true, createdAt: DateTime.formatIso(compactionStartedAt) },
    ]);
    expect(liveRows("completed")).toMatchObject([
      { kind: "context-compaction", title: "Context compacted after 1h 5m idle" },
    ]);
    const laterRows = rowsFor("running", true);
    const dividers = laterRows.filter((row) => row.kind === "context-compaction");
    expect(dividers).toHaveLength(2);
    expect(dividers[0]).toMatchObject({
      title: "Context compacted after 1h 5m idle",
      active: false,
    });
    expect(dividers[1]).toMatchObject({ active: true });
    expect(dividers[1]).not.toHaveProperty("title");
    expect(laterRows.some((row) => row.kind === "working" && row.compacting !== undefined)).toBe(
      false,
    );
  });

  it("shows a skipped compaction as stopped, without a separate interrupted divider", () => {
    const fixture = makeStreamingTimelineFixture();
    const [history0, history1, history2, liveUser, , liveAssistant] = fixture.visibleTurnItems;
    if (liveUser?.item.type !== "user_message" || liveAssistant?.item.type !== "assistant_message")
      throw new Error("Expected live fixture items");
    const prompt = {
      ...liveUser,
      item: { ...liveUser.item, text: "/compact", idleCompaction: "onReturn" as const },
    };
    const compaction = {
      ...liveAssistant,
      item: {
        ...liveAssistant.item,
        type: "compaction" as const,
        status: "interrupted" as const,
        driver: null,
      },
    };
    const interruptResult = {
      ...liveAssistant,
      item: {
        ...liveAssistant.item,
        id: TurnItemId.make("interrupt-result"),
        type: "run_interrupt_result" as const,
        status: "interrupted" as const,
        message: "Skipped compaction to send a queued message",
      },
    };
    const liveRowsFor = (visibleTurnItems: OrchestrationV2ProjectedTurnItem[]) => {
      const rows = deriveMessagesTimelineRows({
        timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
          visibleTurnItems: [history0!, history1!, history2!, ...visibleTurnItems],
          optimisticMessages: [],
        }),
        isWorking: false,
        latestRun: {
          runId: fixture.runId,
          status: "interrupted",
          startedAt: fixture.time(5),
          completedAt: fixture.time(9),
        },
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
      return rows.slice(rows.findIndex((row) => row.id.includes("history-assistant")) + 1);
    };

    expect(liveRowsFor([prompt, compaction, interruptResult])).toMatchObject([
      { kind: "context-compaction", label: "Context compaction stopped" },
    ]);
    // Stopped before the provider started: no compaction row says so, so the interrupt stays.
    expect(liveRowsFor([prompt, interruptResult]).map((row) => row.id)).toContain(
      "interrupt-result",
    );
  });

  it("only enables assistant copy for the terminal assistant message in a turn", () => {
    const rows = deriveMessagesTimelineRows({
      timelineEntries: [
        {
          id: "user-1-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:00Z",
          message: {
            id: "user-1" as never,
            role: "user",
            text: "Write a poem",
            runId: null,
            createdAt: "2026-01-01T00:00:00Z",
            updatedAt: "2026-01-01T00:00:00Z",
            streaming: false,
          },
        },
        {
          id: "assistant-thought-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:10Z",
          message: {
            id: "assistant-thought" as never,
            role: "assistant",
            text: "I should ground this first.",
            runId: "turn-1" as never,
            createdAt: "2026-01-01T00:00:10Z",
            updatedAt: "2026-01-01T00:00:11Z",
            streaming: false,
          },
        },
        {
          id: "assistant-final-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:20Z",
          message: {
            id: "assistant-final" as never,
            role: "assistant",
            text: "Here is the poem.",
            runId: "turn-1" as never,
            createdAt: "2026-01-01T00:00:20Z",
            updatedAt: "2026-01-01T00:00:30Z",
            streaming: false,
          },
        },
      ],
      expandedRunIds: new Set(["turn-1" as never]),
      isWorking: false,
      activeTurnStartedAt: null,
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    });

    const assistantRows = rows.filter(
      (row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
        row.kind === "message" && row.message.role === "assistant",
    );

    expect(assistantRows).toHaveLength(2);
    expect(assistantRows[0]?.showAssistantCopyButton).toBe(false);
    expect(assistantRows[1]?.showAssistantCopyButton).toBe(true);
  });

  it("projects assistant diffs and rewinds the first visible run to thread start after a rewind", () => {
    const assistantTurnDiffSummary = {
      runId: "turn-1" as never,
      completedAt: "2026-01-01T00:00:30Z",
      assistantMessageId: "assistant-1" as never,
      checkpointTurnCount: 2,
      checkpointRef: "checkpoint-1" as never,
      status: "ready" as const,
      files: [{ path: "src/index.ts", kind: "modified", additions: 3, deletions: 1 }],
    };

    const rows = deriveMessagesTimelineRows({
      timelineEntries: [
        {
          id: "user-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:00Z",
          message: {
            id: "user-1" as never,
            role: "user",
            text: "Do the thing",
            runId: "turn-1" as never,
            inputIntent: "turn_start",
            createdAt: "2026-01-01T00:00:00Z",
            updatedAt: "2026-01-01T00:00:00Z",
            streaming: false,
          },
        },
        {
          id: "assistant-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:20Z",
          message: {
            id: "assistant-1" as never,
            role: "assistant",
            text: "Done",
            runId: "turn-1" as never,
            createdAt: "2026-01-01T00:00:20Z",
            updatedAt: "2026-01-01T00:00:30Z",
            streaming: false,
          },
        },
      ],
      isWorking: false,
      activeTurnStartedAt: null,
      turnDiffSummaries: [assistantTurnDiffSummary],
      supportsConversationRollback: true,
      threadStartCheckpointReady: true,
    });

    const userRow = rows.find(
      (row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
        row.kind === "message" && row.message.role === "user",
    );
    const assistantRow = rows.find(
      (row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
        row.kind === "message" && row.message.role === "assistant",
    );

    expect(userRow?.revertTurnCount).toBe(0);
    expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
  });

  it("folds the first assistant message and settled work before the terminal response", () => {
    const timelineEntries = [
      {
        id: "user-entry",
        kind: "message" as const,
        createdAt: "2026-01-01T00:00:00Z",
        message: {
          id: "user-1" as never,
          role: "user" as const,
          text: "Build it",
          runId: null,
          createdAt: "2026-01-01T00:00:00Z",
          updatedAt: "2026-01-01T00:00:00Z",
          streaming: false,
        },
      },
      {
        id: "assistant-first-entry",
        kind: "message" as const,
        createdAt: "2026-01-01T00:00:05Z",
        message: {
          id: "assistant-first" as never,
          role: "assistant" as const,
          text: "Synthetic deployment checklist\n1. Confirm the deployment is ready.",
          runId: "turn-1" as never,
          createdAt: "2026-01-01T00:00:05Z",
          updatedAt: "2026-01-01T00:00:06Z",
          streaming: false,
        },
      },
      {
        id: "work-entry-1",
        kind: "work" as const,
        createdAt: "2026-01-01T00:00:08Z",
        entry: {
          id: "work-1",
          createdAt: "2026-01-01T00:00:08Z",
          runId: "turn-1" as never,
          label: "Ran command",
          tone: "tool" as const,
        },
      },
      {
        id: "assistant-final-entry",
        kind: "message" as const,
        createdAt: "2026-01-01T00:00:20Z",
        message: {
          id: "assistant-final" as never,
          role: "assistant" as const,
          text: "Done",
          runId: "turn-1" as never,
          createdAt: "2026-01-01T00:00:20Z",
          updatedAt: "2026-01-01T00:00:22Z",
          streaming: false,
        },
      },
    ];

    const collapsedRows = deriveMessagesTimelineRows({
      timelineEntries,
      isWorking: false,
      activeTurnStartedAt: null,
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    });

    const foldRow = collapsedRows.find(
      (row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> =>
        row.kind === "turn-fold",
    );
    expect(foldRow?.runId).toBe("turn-1");
    expect(foldRow?.expanded).toBe(false);
    expect(foldRow?.label).toBe("Worked for 22s");
    expect(collapsedRows.map((row) => row.id)).toEqual([
      "user-entry",
      "turn-fold:turn-1",
      "assistant-final-entry",
    ]);

    const expandedRows = deriveMessagesTimelineRows({
      timelineEntries,
      expandedRunIds: new Set(["turn-1" as never]),
      isWorking: false,
      activeTurnStartedAt: null,
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    });

    expect(expandedRows.map((row) => row.id)).toEqual([
      "user-entry",
      "turn-fold:turn-1",
      "assistant-first-entry",
      "work-entry-1",
      "assistant-final-entry",
    ]);
    expect(
      expandedRows.find((row) => row.kind === "turn-fold" && row.expanded === true),
    ).toBeDefined();
  });

  it.each([1, 2, 3])("folds %i completed activities after the terminal response", (count) => {
    const runId = RunId.make("turn-1");
    const timelineEntries = [
      {
        id: "work-entry-before-text",
        kind: "work" as const,
        createdAt: "2026-01-01T00:00:01Z",
        entry: {
          id: "work-before-text",
          createdAt: "2026-01-01T00:00:01Z",
          runId,
          label: "Status updated",
          tone: "info" as const,
        },
      },
      {
        id: "assistant-final-entry",
        kind: "message" as const,
        createdAt: "2026-01-01T00:00:05Z",
        message: {
          id: "assistant-final" as never,
          role: "assistant" as const,
          text: "CI is re-running. Waiting.",
          runId,
          createdAt: "2026-01-01T00:00:05Z",
          updatedAt: "2026-01-01T00:00:06Z",
          streaming: false,
        },
      },
      ...Array.from({ length: count }, (_, index) => ({
        id: `work-entry-after-text-${index}`,
        kind: "work" as const,
        createdAt: `2026-01-01T00:00:0${index + 7}Z`,
        entry: {
          id: `work-after-text-${index}`,
          createdAt: `2026-01-01T00:00:0${index + 7}Z`,
          runId,
          label: "Ran command",
          tone: "tool" as const,
          itemType: "command_execution" as const,
          toolLifecycleStatus: "completed" as const,
        },
      })),
    ];

    const input = {
      latestRun: {
        runId,
        status: "completed" as const,
        startedAt: "2026-01-01T00:00:00Z",
        completedAt: "2026-01-01T00:00:10Z",
      },
      isWorking: false,
      activeTurnStartedAt: null,
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    };
    const rows = deriveMessagesTimelineRows({ ...input, timelineEntries });

    expect(rows.map((row) => row.id)).toEqual(["turn-fold:turn-1", "assistant-final-entry"]);
    const expanded = deriveMessagesTimelineRows({
      ...input,
      timelineEntries,
      expandedRunIds: new Set([runId]),
    });
    expect(
      expanded.some(
        (row) =>
          row.id === "work-entry-after-text-0" ||
          (row.kind === "work-toggle" &&
            row.id === "work-toggle:work-entry-after-text-0" &&
            row.hiddenCount === count),
      ),
    ).toBe(true);

    const failedEntries = timelineEntries.map((entry) =>
      entry.kind === "work" && entry.id === "work-entry-after-text-0"
        ? { ...entry, entry: { ...entry.entry, toolLifecycleStatus: "failed" as const } }
        : entry,
    );
    const failedRows = deriveMessagesTimelineRows({ ...input, timelineEntries: failedEntries });
    expect(failedRows.some((row) => row.id === "work-entry-after-text-0")).toBe(true);

    const pendingEntries = timelineEntries.map((entry) =>
      entry.kind === "work" && entry.id === "work-entry-after-text-0"
        ? { ...entry, entry: { ...entry.entry, toolLifecycleStatus: "inProgress" as const } }
        : entry,
    );
    const pendingRows = deriveMessagesTimelineRows({
      ...input,
      timelineEntries: pendingEntries,
      latestRun: { ...input.latestRun, status: "running", completedAt: null },
      isWorking: true,
      activeTurnStartedAt: input.latestRun.startedAt,
    });
    expect(
      pendingRows.some((row) => row.kind === "work-live" && row.entry.id === "work-after-text-0"),
    ).toBe(true);
  });

  it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => {
    const rows = deriveMessagesTimelineRows({
      timelineEntries: [
        {
          id: "user-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:00Z",
          message: {
            id: "user-1" as never,
            role: "user" as const,
            text: "do it once more",
            runId: null,
            createdAt: "2026-01-01T00:00:00Z",
            updatedAt: "2026-01-01T00:00:00Z",
            streaming: false,
          },
        },
        {
          id: "work-entry-before-message",
          kind: "work",
          createdAt: "2026-01-01T00:00:07Z",
          entry: {
            id: "work-before-message",
            createdAt: "2026-01-01T00:00:07Z",
            runId: "turn-1" as never,
            label: "Status updated",
            tone: "info" as const,
          },
        },
        {
          id: "assistant-commentary-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:09Z",
          message: {
            id: "assistant-commentary" as never,
            role: "assistant" as const,
            text: "Kicking off call 1.",
            runId: "turn-1" as never,
            createdAt: "2026-01-01T00:00:09Z",
            updatedAt: "2026-01-01T00:00:09Z",
            streaming: false,
          },
        },
        {
          id: "work-entry-1",
          kind: "work",
          createdAt: "2026-01-01T00:00:12Z",
          entry: {
            id: "work-1",
            createdAt: "2026-01-01T00:00:12Z",
            runId: "turn-1" as never,
            label: "Ran command",
            tone: "tool" as const,
          },
        },
        {
          id: "steer-user-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:14Z",
          message: {
            id: "user-2" as never,
            role: "user" as const,
            text: "actually do 15",
            runId: null,
            createdAt: "2026-01-01T00:00:14Z",
            updatedAt: "2026-01-01T00:00:14Z",
            streaming: false,
          },
        },
        {
          id: "assistant-next-turn-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:17Z",
          message: {
            id: "assistant-next" as never,
            role: "assistant" as const,
            text: "One down — adjusting.",
            runId: "turn-2" as never,
            createdAt: "2026-01-01T00:00:17Z",
            updatedAt: "2026-01-01T00:00:17Z",
            streaming: true,
          },
        },
      ],
      latestRun: {
        runId: "turn-2" as never,
        status: "running",
        startedAt: "2026-01-01T00:00:14Z",
        completedAt: null,
      },
      isWorking: true,
      activeTurnStartedAt: "2026-01-01T00:00:14Z",
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    });

    const foldRow = rows.find(
      (row): row is Extract<(typeof rows)[number], { kind: "turn-fold" }> =>
        row.kind === "turn-fold",
    );
    expect(foldRow?.runId).toBe("turn-1");
    expect(foldRow?.label).toBe("Worked for 12s");
  });

  it("uses latest-turn timings and the stopped label for an interrupted latest turn", () => {
    const rows = deriveMessagesTimelineRows({
      timelineEntries: [
        {
          id: "work-entry-1",
          kind: "work",
          createdAt: "2026-01-01T00:00:05Z",
          entry: {
            id: "work-1",
            createdAt: "2026-01-01T00:00:05Z",
            runId: "turn-1" as never,
            label: "Ran command",
            tone: "tool" as const,
          },
        },
      ],
      latestRun: {
        runId: "turn-1" as never,
        status: "interrupted",
        startedAt: "2026-01-01T00:00:00Z",
        completedAt: "2026-01-01T00:00:47Z",
      },
      isWorking: false,
      activeTurnStartedAt: null,
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    });

    expect(rows).toEqual([
      expect.objectContaining({
        kind: "turn-fold",
        runId: "turn-1",
        label: "You stopped after 47s",
        expanded: false,
      }),
    ]);
  });

  it.each(["steer", "promoted_queued_to_steer"] as const)(
    "keeps the duration header at the initiating prompt when %s arrives before output",
    (inputIntent) => {
      const runId = RunId.make("steered-run");
      const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString();
      const prompt = (id: string, second: number, intent: "turn_start" | typeof inputIntent) => ({
        kind: "message" as const,
        id,
        createdAt: time(second),
        message: {
          id: MessageId.make(id),
          role: "user" as const,
          text: id,
          runId,
          inputIntent: intent,
          createdAt: time(second),
          updatedAt: time(second),
          streaming: false,
        },
      });
      const entries = [prompt("initial-prompt", 0, "turn_start"), prompt("steer", 5, inputIntent)];
      const work = {
        kind: "work" as const,
        id: "work",
        createdAt: time(8),
        entry: {
          id: "work",
          createdAt: time(8),
          runId,
          label: "Ran command",
          tone: "tool" as const,
        },
      };
      const final = {
        kind: "message" as const,
        id: "final",
        createdAt: time(20),
        message: {
          id: MessageId.make("final"),
          role: "assistant" as const,
          text: "Done",
          runId,
          createdAt: time(20),
          updatedAt: time(20),
          streaming: false,
        },
      };
      for (const isWorking of [true, false]) {
        for (const expanded of [true, false]) {
          const rows = deriveMessagesTimelineRows({
            timelineEntries: [...entries, work, final],
            latestRun: {
              runId,
              status: isWorking ? "running" : "completed",
              startedAt: time(0),
              completedAt: isWorking ? null : time(20),
            },
            isWorking,
            activeTurnStartedAt: time(0),
            expandedRunIds: expanded ? new Set([runId]) : new Set(),
            turnDiffSummaries: [],
            supportsConversationRollback: false,
          });
          expect(rows.slice(0, 3).map((row) => row.id)).toEqual([
            "initial-prompt",
            isWorking ? "working-indicator-row" : `turn-fold:${runId}`,
            "steer",
          ]);
          expect(rows[1]?.createdAt).toBe(time(0));
          if (!isWorking) expect(rows[1]).toMatchObject({ label: "Worked for 20s", expanded });
          expect(rows.some((row) => row.id === "final")).toBe(true);
          expect(rows.some((row) => row.id === "work")).toBe(isWorking || expanded);
        }
      }
    },
  );

  it("splits a settled turn's work at each steer and keeps the total time on top", () => {
    const runId = RunId.make("steered-run");
    const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString();
    const message = (
      id: string,
      second: number,
      role: "user" | "assistant",
      inputIntent?: "turn_start" | "steer",
    ): TimelineEntry => ({
      kind: "message",
      id,
      createdAt: time(second),
      message: {
        id: MessageId.make(id),
        role,
        text: id,
        runId,
        ...(inputIntent ? { inputIntent } : {}),
        createdAt: time(second),
        updatedAt: time(second),
        streaming: false,
      },
    });
    const work = (id: string, second: number): TimelineEntry => ({
      kind: "work",
      id,
      createdAt: time(second),
      entry: { id, createdAt: time(second), runId, label: "Ran command", tone: "tool" },
    });
    const rows = (expandedRunIds: ReadonlySet<RunId>) =>
      deriveMessagesTimelineRows({
        timelineEntries: [
          message("prompt", 0, "user", "turn_start"),
          work("work-before-steer", 4),
          message("steer", 10, "user", "steer"),
          work("work-after-steer", 15),
          message("final", 30, "assistant"),
        ],
        latestRun: { runId, status: "completed", startedAt: time(0), completedAt: time(30) },
        isWorking: false,
        expandedRunIds,
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });

    const segmentKey = RunId.make(`${runId}:steer:steer`);
    const collapsed = rows(new Set());
    expect(collapsed.map((row) => row.id)).toEqual([
      "prompt",
      `turn-fold:${runId}`,
      "steer",
      `turn-fold:${segmentKey}`,
      "final",
    ]);
    expect(collapsed[1]).toMatchObject({ label: "Worked for 30s" });
    expect(collapsed[3]).toMatchObject({ label: "Continued for 20s", createdAt: time(10) });

    expect(rows(new Set([segmentKey])).map((row) => row.id)).toEqual([
      "prompt",
      `turn-fold:${runId}`,
      "steer",
      `turn-fold:${segmentKey}`,
      "work-after-steer",
      "final",
    ]);
  });

  it("stacks back-to-back steers as one burst with a single steer label", () => {
    const runId = RunId.make("double-steer-run");
    const time = (second: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, second)).toISOString();
    const message = (
      id: string,
      second: number,
      role: "user" | "assistant",
      inputIntent?: "turn_start" | "steer",
    ): TimelineEntry => ({
      kind: "message",
      id,
      createdAt: time(second),
      message: {
        id: MessageId.make(id),
        role,
        text: id,
        runId,
        ...(inputIntent ? { inputIntent } : {}),
        createdAt: time(second),
        updatedAt: time(second),
        streaming: false,
      },
    });
    const prompt = message("prompt", 0, "user", "turn_start");
    const work: TimelineEntry = {
      kind: "work",
      id: "work",
      createdAt: time(4),
      entry: { id: "work", createdAt: time(4), runId, label: "Ran command", tone: "tool" },
    };
    const firstSteer = message("first-steer", 10, "user", "steer");
    const deriveRows = (timelineEntries: TimelineEntry[]) =>
      deriveMessagesTimelineRows({
        timelineEntries,
        latestRun: { runId, status: "completed", startedAt: time(0), completedAt: time(30) },
        isWorking: false,
        expandedRunIds: new Set(),
        turnDiffSummaries: [],
        supportsConversationRollback: false,
      });
    // The second steer arrives while the first message object is reused, as live updates do.
    const before = computeStableMessagesTimelineRows(deriveRows([prompt, work, firstSteer]), {
      result: [],
      byId: new Map(),
    });
    const rows = computeStableMessagesTimelineRows(
      deriveRows([
        prompt,
        work,
        firstSteer,
        message("second-steer", 12, "user", "steer"),
        message("final", 30, "assistant"),
      ]),
      before,
    ).result;

    const byId = new Map(rows.map((row) => [row.id, row]));
    expect(byId.get("prompt")).not.toHaveProperty("groupedWithNext");
    expect(byId.get("first-steer")).toMatchObject({
      groupedWithNext: true,
      groupedWithPrevious: false,
      continuesSteer: false,
    });
    expect(byId.get("second-steer")).toMatchObject({
      groupedWithNext: false,
      groupedWithPrevious: true,
      continuesSteer: true,
    });
  });

  it("keeps the previous turn folded while a newly sent message awaits its turn", () => {
    const rows = deriveMessagesTimelineRows({
      timelineEntries: [
        {
          id: "work-entry-1",
          kind: "work",
          createdAt: "2026-01-01T00:00:05Z",
          entry: {
            id: "work-1",
            createdAt: "2026-01-01T00:00:05Z",
            runId: "turn-1" as never,
            label: "Ran command",
            tone: "tool" as const,
          },
        },
        {
          id: "assistant-final-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:20Z",
          message: {
            id: "assistant-final" as never,
            role: "assistant",
            text: "Done",
            runId: "turn-1" as never,
            createdAt: "2026-01-01T00:00:20Z",
            updatedAt: "2026-01-01T00:00:22Z",
            streaming: false,
          },
        },
        {
          id: "user-followup-entry",
          kind: "message",
          createdAt: "2026-01-01T00:01:00Z",
          message: {
            id: "user-followup" as never,
            role: "user",
            text: "yooo",
            runId: null,
            createdAt: "2026-01-01T00:01:00Z",
            updatedAt: "2026-01-01T00:01:00Z",
            streaming: false,
          },
        },
      ],
      latestRun: {
        runId: "turn-1" as never,
        status: "completed",
        startedAt: "2026-01-01T00:00:00Z",
        completedAt: "2026-01-01T00:00:22Z",
      },
      isWorking: true,
      activeTurnStartedAt: "2026-01-01T00:01:00Z",
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    });

    expect(rows.map((row) => row.id)).toEqual([
      "turn-fold:turn-1",
      "assistant-final-entry",
      "user-followup-entry",
      "working-indicator-row",
      "live-activity-row",
    ]);
    const finalRow = rows.find((row) => row.id === "assistant-final-entry");
    expect(finalRow?.kind === "message" && finalRow.showAssistantMeta).toBe(true);
    expect(rows.at(-1)).toMatchObject({ kind: "thinking" });
  });

  it("does not show Thinking once the open run's provider turn has ended", () => {
    const input = {
      timelineEntries: [
        {
          id: "user-entry",
          kind: "message" as const,
          createdAt: "2026-01-01T00:00:00Z",
          message: {
            id: "user" as never,
            role: "user" as const,
            text: "Take over the queue",
            runId: "turn-1" as never,
            createdAt: "2026-01-01T00:00:00Z",
            updatedAt: "2026-01-01T00:00:00Z",
            streaming: false,
          },
        },
      ],
      latestRun: {
        runId: "turn-1" as never,
        status: "running" as const,
        startedAt: "2026-01-01T00:00:00Z",
        completedAt: null,
      },
      isWorking: true,
      activeTurnStartedAt: "2026-01-01T00:00:00Z",
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    };

    expect(deriveMessagesTimelineRows(input).at(-1)?.kind).toBe("thinking");
    const ended = deriveMessagesTimelineRows({
      ...input,
      latestRun: { ...input.latestRun, turnEnded: true },
    });
    expect(ended.some((row) => row.kind === "thinking")).toBe(false);
  });

  it("keeps a promptless restart in one active visual response", () => {
    const rows = deriveMessagesTimelineRows({
      timelineEntries: [
        {
          id: "user-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:00Z",
          message: {
            id: "user-1" as never,
            role: "user",
            text: "keep going",
            runId: null,
            createdAt: "2026-01-01T00:00:00Z",
            updatedAt: "2026-01-01T00:00:00Z",
            streaming: false,
          },
        },
        {
          id: "old-work-entry",
          kind: "work",
          createdAt: "2026-01-01T00:00:05Z",
          entry: {
            id: "old-work",
            createdAt: "2026-01-01T00:00:05Z",
            runId: "turn-before-restart" as never,
            label: "Searched files",
            command: "rg restart",
            tone: "tool" as const,
            toolLifecycleStatus: "completed" as const,
          },
        },
        {
          id: "old-stale-work-entry",
          kind: "work",
          createdAt: "2026-01-01T00:00:06Z",
          entry: {
            id: "old-stale-work",
            createdAt: "2026-01-01T00:00:06Z",
            runId: "turn-before-restart" as never,
            label: "Running stale command",
            command: "rg stale",
            tone: "tool" as const,
            toolLifecycleStatus: "inProgress" as const,
          },
        },
        {
          id: "old-commentary-entry",
          kind: "message",
          createdAt: "2026-01-01T00:00:08Z",
          message: {
            id: "old-commentary" as never,
            role: "assistant",
            text: "the server restarted, continuing here.",
            runId: "turn-before-restart" as never,
            createdAt: "2026-01-01T00:00:08Z",
            updatedAt: "2026-01-01T00:00:08Z",
            streaming: false,
          },
        },
        {
          id: "new-work-entry",
          kind: "work",
          createdAt: "2026-01-01T00:01:05Z",
          entry: {
            id: "new-work",
            createdAt: "2026-01-01T00:01:05Z",
            runId: "turn-after-restart" as never,
            label: "Running tests",
            command: "vp test run",
            tone: "tool" as const,
            toolLifecycleStatus: "inProgress" as const,
          },
        },
      ],
      latestRun: {
        runId: "turn-after-restart" as never,
        status: "running",
        startedAt: "2026-01-01T00:01:00Z",
        completedAt: null,
      },
      isWorking: true,
      activeTurnStartedAt: "2026-01-01T00:01:00Z",
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    });

    expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
    expect(rows.filter((row) => row.id === "working-indicator-row")).toHaveLength(1);
    expect(rows.findIndex((row) => row.id === "working-indicator-row")).toBeLessThan(
      rows.findIndex((row) => row.id === "old-work-entry"),
    );
    expect(rows.find((row) => row.id === "working-indicator-row")).toMatchObject({
      createdAt: "2026-01-01T00:01:00Z",
    });
    expect(rows.find((row) => row.id === "old-commentary-entry")).toMatchObject({
      showAssistantMeta: false,
      showAssistantCopyButton: false,
      assistantCopyStreaming: true,
    });
    expect(rows.filter((row) => row.kind === "work-live" && row.active)).toEqual([
      expect.objectContaining({ entry: expect.objectContaining({ id: "new-work" }) }),
    ]);
    expect(rows.some((row) => row.kind === "thinking")).toBe(false);
  });

  it("carries the latest thought on the live row while a later tool runs", () => {
    type WorkEntry = Extract<
      Parameters<typeof deriveMessagesTimelineRows>[0]["timelineEntries"][number],
      { kind: "work" }
    >;
    const work = (
      id: string,
      at: string,
      fields: Omit<WorkEntry["entry"], "id" | "createdAt" | "runId" | "label">,
    ): WorkEntry => ({
      id: `${id}-entry`,
      kind: "work",
      createdAt: at,
      entry: { id, createdAt: at, runId: "turn-1" as never, label: id, ...fields },
    });
    const rows = deriveMessagesTimelineRows({
      timelineEntries: [
        work("old-thought", "2026-01-01T00:00:01Z", {
          itemType: "reasoning",
          detail: "First idea.",
          tone: "thinking" as const,
          toolLifecycleStatus: "completed" as const,
        }),
        work("new-thought", "2026-01-01T00:00:02Z", {
          itemType: "reasoning",
          detail: "Found the cause.",
          tone: "thinking" as const,
          toolLifecycleStatus: "completed" as const,
        }),
        work("running-command", "2026-01-01T00:00:03Z", {
          command: "rg cause",
          requestKind: "command",
          tone: "tool" as const,
          toolLifecycleStatus: "inProgress" as const,
        }),
      ],
      latestRun: {
        runId: "turn-1" as never,
        status: "running",
        startedAt: "2026-01-01T00:00:00Z",
        completedAt: null,
      },
      isWorking: true,
      activeTurnStartedAt: "2026-01-01T00:00:00Z",
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    });

    expect(rows.find((row) => row.kind === "work-live")).toMatchObject({
      entry: { id: "running-command" },
      thought: { id: "new-thought" },
    });
  });

  it("keeps an actually running tool in the shared activity row", () => {
    const rows = deriveMessagesTimelineRows({
      timelineEntries: [
        {
          id: "running-command-entry",
          kind: "work",
          createdAt: "2026-01-01T00:00:05Z",
          entry: {
            id: "running-command",
            createdAt: "2026-01-01T00:00:05Z",
            runId: "turn-1" as never,
            label: "Running rg",
            command: "rg toolCall",
            requestKind: "command",
            tone: "tool" as const,
            toolLifecycleStatus: "inProgress" as const,
          },
        },
        {
          id: "completed-edit-entry",
          kind: "work",
          createdAt: "2026-01-01T00:00:06Z",
          entry: {
            id: "completed-edit",
            createdAt: "2026-01-01T00:00:06Z",
            runId: "turn-1" as never,
            label: "Edited files",
            requestKind: "file-change",
            changedFiles: ["src/one.ts", "src/two.ts"],
            tone: "tool" as const,
            toolLifecycleStatus: "completed" as const,
          },
        },
        {
          id: "completed-command-entry",
          kind: "work",
          createdAt: "2026-01-01T00:00:07Z",
          entry: {
            id: "completed-command",
            createdAt: "2026-01-01T00:00:07Z",
            runId: "turn-1" as never,
            label: "Ran tests",
            command: "vp test run",
            requestKind: "command",
            tone: "tool" as const,
            toolLifecycleStatus: "completed" as const,
          },
        },
      ],
      latestRun: {
        runId: "turn-1" as never,
        status: "running",
        startedAt: "2026-01-01T00:00:00Z",
        completedAt: null,
      },
      isWorking: true,
      activeTurnStartedAt: "2026-01-01T00:00:00Z",
      turnDiffSummaries: [],
      supportsConversationRollback: false,
    });

    expect(rows.map((row) => row.kind)).toEqual(["working", "work-live"]);
    expect(rows.some((row) => row.kind === "thinking")).toBe(false);
    expect(rows.find((row) => row.kind === "work-live")).toMatchObject({
      entry: { id: "running-command" },
      active: true,
      groupedEntries: [
        { id: "running-command" },
        { id: "completed-edit" },
        { id: "completed-command" },
      ],
    });
  });

  it("folds each run of a provider-native subagent thread like a normal turn", () => {
    const threadId = ThreadId.make("subagent-child");
    const rootNodeId = NodeId.make("task-root");
    const at = (second: number) =>
      DateTime.makeUnsafe(new Date(Date.UTC(2026, 8, 25, 22, 51, second)).toISOString());
    const base = (id: string, ordinal: number, second: number, endSecond = second) => ({
      id: TurnItemId.make(id),
      threadId,
      runId: null,
      nodeId: rootNodeId,
      providerThreadId: null,
      providerTurnId: null,
      nativeItemRef: null,
      parentItemId: null,
      ordinal,
      status: "completed" as const,
      title: null,
      startedAt: at(second),
      completedAt: at(endSecond),
      updatedAt: at(endSecond),
    });
    const prompt = (id: string, ordinal: number, second: number) => ({
      ...base(id, ordinal, second),
      type: "user_message" as const,
      messageId: MessageId.make(id),
      text: `Prompt ${id}`,
      attachments: [],
      inputIntent: "turn_start" as const,
      createdBy: "agent" as const,
      creationSource: "provider" as const,
    });
    const answer = (id: string, ordinal: number, second: number) => ({
      ...base(id, ordinal, second),
      type: "assistant_message" as const,
      messageId: MessageId.make(id),
      text: `Answer ${id}`,
      streaming: false,
    });
    type ResumeState = "running" | "completed" | "failed";
    const items = (resume: ResumeState) =>
      [
        prompt("launch", 1, 0),