sailfork / t3code-github / apps/ mobile/ src/ lib/ threadActivity.ts

import type {
  ThreadPendingApproval,
  ThreadPendingUserInput,
} from "@t3tools/client-runtime/state/thread-requests";
import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation";
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display";
import { isLiveSubagentTurnItem } from "@t3tools/client-runtime/state/subagentRuntime";
import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
import {
  turnItemDetailRevision,
  turnItemHasDetail,
  turnItemNeedsDetailFetch,
} from "@t3tools/client-runtime/work-log/item-detail";
import {
  commandDisplayText,
  commandProgramName,
} from "@t3tools/client-runtime/work-log/command-label";
import {
  contextCompactionLabel,
  liveThoughtLine,
  toolItemForDisplay,
  workEntryDisplayIndicatesToolFailure,
  liveActivityToolStatus,
  toolGroupAction,
  resolveWorkEntryToolPresentation,
  summarizeToolGroup,
  toolGroupSummaryKind,
  type ToolGroupSummaryKind,
  type WorkLogPresentationEntry,
  type WorkLogToolLifecycleStatus,
  workEntryHiddenByToolCallVisibility,
} from "@t3tools/client-runtime/work-log/presentation";
import type { ToolCallVisibility } from "@t3tools/contracts/settings";
import {
  resolveT3McpToolDefinition,
  resolveT3McpToolPresentation,
  type T3McpToolLogo,
  type T3McpToolPresentation,
} from "@t3tools/shared/t3McpToolPresentation";
import type {
  ChatAttachment,
  MessageId,
  OrchestrationV2Actor,
  OrchestrationV2CreationSource,
  OrchestrationV2ExecutionNode,
  OrchestrationMessageContext,
  OrchestrationV2ProjectedTurnItem,
  OrchestrationV2RunAttempt,
  OrchestrationV2RunStatus,
  OrchestrationV2TurnItem,
  OrchestrationV2UserMessageInputIntent,
  RunAttemptId,
  ScheduledTaskId,
  TurnItemId,
} from "@t3tools/contracts";
import { idleCompactionOf, isCompactionCommandMessage, RunId, ThreadId } from "@t3tools/contracts";
import {
  classifyToolActivity,
  collectToolFilePaths,
  dynamicToolTitle,
  isJavaScriptReplTool,
  formatReadToolLabel,
  formatSearchToolLabel,
} from "@t3tools/shared/toolActivity";
import { claudeResumeCompactionAge } from "@t3tools/shared/claudeCompaction";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import { truncate } from "@t3tools/shared/String";
import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
import type { McpAppReference } from "@t3tools/shared/mcpApp";
import {
  compactDynamicToolOutput,
  htmlRenderFromToolItem,
  mcpAppFromToolItem,
} from "@t3tools/shared/toolOutput";
import * as DateTime from "effect/DateTime";
import {
  IDLE_COMPACTION_TITLES,
  IDLE_COMPACTING_LABELS,
} from "@t3tools/client-runtime/user-message";

export type PendingApproval = ThreadPendingApproval;
export type PendingUserInput = ThreadPendingUserInput;

export interface ThreadFeedActivity {
  readonly id: string;
  readonly createdAt: string;
  readonly runId: RunId | null;
  readonly attemptId: RunAttemptId | null;
  readonly summary: string;
  readonly detail: string | null;
  readonly canExpand: boolean;
  readonly fetchesDetail: boolean;
  readonly getFullDetail: () => string | null;
  readonly getCopyText: () => string;
  readonly icon:
    | "agent"
    | "alert"
    | "browser"
    | "computer"
    | "code"
    | "check"
    | "command"
    | "edit"
    | "eye"
    | "globe"
    | "search"
    | "stop"
    | "hammer"
    | "lock"
    | "message"
    | "warning"
    | "wrench"
    | "zap";
  readonly logo: T3McpToolLogo | null;
  readonly toolLike: boolean;
  readonly prominent: boolean;
  readonly status: "success" | "failure" | "neutral" | null;
  readonly lifecycleStatus: WorkLogToolLifecycleStatus;
  readonly workEntry: WorkLogPresentationEntry;
  readonly groupedToolDetail?: boolean;
  readonly live?: boolean;
  /** Lone calls carry the group header's label and id until a second call joins. */
  readonly groupStandIn?: { readonly groupId: string; readonly label: string };
  readonly projectedItem: OrchestrationV2ProjectedTurnItem;
}

export interface ThreadFeedMessage {
  readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
  readonly id: MessageId;
  readonly role: "user" | "assistant";
  readonly text: string;
  readonly attachments: ReadonlyArray<ChatAttachment>;
  readonly runId: RunId | null;
  readonly streaming: boolean;
  readonly inputIntent?: OrchestrationV2UserMessageInputIntent;
  readonly createdBy?: OrchestrationV2Actor;
  readonly creationSource?: OrchestrationV2CreationSource;
  readonly scheduledTaskId?: ScheduledTaskId;
  readonly senderThreadId?: ThreadId;
  readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
  readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
  readonly sourceThreadId: ThreadId;
  readonly createdAt: string;
  readonly updatedAt: string;
  readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
  readonly checkpointSummary?: ThreadCheckpointSummary;
}

export interface LocalThreadMessage {
  readonly id: MessageId;
  readonly role: string;
  readonly text: string;
  readonly context?: OrchestrationMessageContext | undefined;
  readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
  readonly streaming: boolean;
  readonly createdAt: string;
  readonly updatedAt: string;
}

type RawThreadFeedEntry =
  | {
      readonly type: "message";
      readonly id: string;
      readonly createdAt: string;
      readonly message: ThreadFeedMessage;
    }
  | {
      readonly type: "activity";
      readonly id: string;
      readonly createdAt: string;
      readonly runId: RunId | null;
      readonly activity: ThreadFeedActivity;
    }
  | {
      readonly type: "html-render";
      readonly id: string;
      readonly createdAt: string;
      readonly runId: RunId | null;
      readonly render: HtmlRenderReference;
    }
  | {
      readonly type: "mcp-app";
      readonly id: string;
      readonly createdAt: string;
      readonly runId: RunId | null;
      /** The thread and item that own the app; a fork's inherited app is its source's. */
      readonly sourceThreadId: ThreadId;
      readonly itemId: TurnItemId;
      readonly revision: string;
      readonly app: McpAppReference;
    };

export type ThreadFeedEntry = ThreadFeedEntryContent & {
  readonly continuesWorkLog?: boolean;
  readonly checkpointSummary?: ThreadCheckpointSummary;
};

type ThreadFeedEntryContent =
  | Extract<RawThreadFeedEntry, { type: "message" | "html-render" | "mcp-app" }>
  | {
      readonly type: "activity-group";
      readonly id: string;
      readonly createdAt: string;
      readonly runId: RunId | null;
      readonly activities: ReadonlyArray<ThreadFeedActivity>;
    }
  | {
      readonly type: "work-toggle";
      readonly id: string;
      readonly createdAt: string;
      readonly runId: RunId | null;
      readonly groupId: string;
      readonly hiddenCount: number;
      readonly expanded: boolean;
      readonly summary: string;
      readonly summaryKind: ToolGroupSummaryKind;
      readonly toolSurface?: WorkLogPresentationEntry["toolSurface"];
      readonly toolIcon?: WorkLogPresentationEntry["toolIcon"];
      readonly summaryToolIcon?: "browser" | "device" | "t3-code" | "pull-request";
      readonly hasFailure: boolean;
      readonly live: boolean;
      readonly shimmer: boolean;
      readonly thought?: string;
    }
  | {
      readonly type: "run-fold";
      readonly deferredWorkItemIds?: ReadonlyArray<string>;
      readonly id: string;
      readonly createdAt: string;
      readonly runId: RunId;
      readonly label: string;
      readonly expanded: boolean;
    }
  | {
      readonly type: "thinking";
      readonly id: string;
      readonly createdAt: string;
      readonly runId: RunId | null;
      readonly label?: string;
    };

export interface ThreadFeedLatestRun {
  readonly runId: RunId;
  readonly status: OrchestrationV2RunStatus;
  readonly startedAt: string | null;
  readonly completedAt: string | null;
  readonly turnEnded?: boolean;
}

/** Long Android headers can ANR despite one-line display; cap labels only, preserving expanded and copied text. */
const WORK_LOG_LABEL_MAX_LENGTH = 200;

function compactWorkEntryText(value: string): string {
  return truncate(value.replace(/\s+/gu, " "), WORK_LOG_LABEL_MAX_LENGTH);
}

export function workEntryRowLabel(entry: WorkLogPresentationEntry, expanded = false): string {
  if (entry.itemType === "fork") return entry.label;
  if (expanded && entry.itemType === "reasoning")
    return entry.toolLifecycleStatus === "inProgress" ? "Thinking" : "Thought";
  const presentation = resolveWorkEntryToolPresentation(entry);
  if (presentation) return presentation.displayName;
  if (entry.command?.trim()) return compactWorkEntryText(commandDisplayText(entry.command));
  const action = toolGroupAction(entry);
  const isToolRead = action === "read" && entry.itemType === "dynamic_tool";
  if (action === "code-search" || action === "search") {
    const toolData =
      entry.toolData !== null &&
      typeof entry.toolData === "object" &&
      !Array.isArray(entry.toolData)
        ? (entry.toolData as Record<string, unknown>)
        : undefined;
    const searchLabel =
      entry.itemType === "file_search" ? entry.label : formatSearchToolLabel(toolData);
    if (searchLabel) return searchLabel;
  }
  if (isToolRead) {
    const [firstPath] = entry.changedFiles ?? collectToolFilePaths(entry.toolData);
    if (firstPath) {
      return formatReadToolLabel(firstPath, Math.max(0, (entry.changedFiles?.length ?? 1) - 1));
    }
    if (!expanded) return "Read file";
  }
  const preview =
    entry.command ??
    (isToolRead || (!expanded && (action === "code-search" || action === "search"))
      ? null
      : entry.detail) ??
    (entry.changedFiles?.length
      ? entry.changedFiles.length === 1
        ? entry.changedFiles[0]!
        : `${entry.changedFiles[0]!} +${entry.changedFiles.length - 1} more`
      : null);
  if (expanded) return preview?.trim() ? truncate(preview, WORK_LOG_LABEL_MAX_LENGTH) : entry.label;
  return preview ? compactWorkEntryText(preview) || entry.label : entry.label;
}

type ThreadFeedActivityGroup = Extract<ThreadFeedEntry, { readonly type: "activity-group" }>;

// Immutable source rows let retained history keep its identities while the active item streams.
const projectedEntriesCache = new WeakMap<
  OrchestrationV2ProjectedTurnItem,
  {
    readonly attemptId: RunAttemptId | null;
    readonly entry: RawThreadFeedEntry;
  }
>();
const localMessageEntriesCache = new WeakMap<
  LocalThreadMessage,
  Extract<RawThreadFeedEntry, { readonly type: "message" }>
>();
const activityGroupsCache = new WeakMap<ThreadFeedActivity, ThreadFeedActivityGroup>();
const failedActivityGroupsCache = new WeakMap<
  ThreadFeedActivityGroup,
  ReadonlyArray<ThreadFeedActivityGroup>
>();
const presentedActivityGroupsCache = new WeakMap<
  ThreadFeedActivityGroup,
  {
    readonly activeRunId: RunId | null;
    readonly isWorking: boolean;
    readonly activeTail: boolean;
    readonly rows: ReadonlyArray<ThreadFeedEntry>;
  }
>();
const runFoldRowsCache = new WeakMap<
  ThreadFeedEntry,
  Extract<ThreadFeedEntry, { readonly type: "run-fold" }>
>();
let cachedThinkingRow: Extract<ThreadFeedEntry, { readonly type: "thinking" }> | null = null;

export function isContextCompactionActivityGroup(entry: ThreadFeedActivityGroup): boolean {
  return (
    entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "compaction"
  );
}

export function threadFeedCompactionLabels(feed: ReadonlyArray<ThreadFeedEntry>) {
  const labelsByRunId = new Map<RunId, { title: string; compacting: string }>();
  const labelsByEntryId = new Map<string, { title: string; compacting: string }>();
  const pendingResumeAgeByRunId = new Map<RunId, string>();
  for (const entry of feed) {
    const reason = entry.type === "message" ? idleCompactionOf(entry.message) : undefined;
    if (entry.type === "message" && entry.message.runId !== null && reason !== undefined) {
      labelsByRunId.set(entry.message.runId, {
        title: IDLE_COMPACTION_TITLES[reason],
        compacting: IDLE_COMPACTING_LABELS[reason],
      });
    } else if (entry.type === "activity-group" && entry.runId !== null) {
      if (isContextCompactionActivityGroup(entry)) {
        const age = pendingResumeAgeByRunId.get(entry.runId);
        const labels =
          labelsByRunId.get(entry.runId) ??
          (age === undefined
            ? undefined
            : {
                title: `Context compacted after ${age} idle`,
                compacting: "Compacting…",
              });
        if (labels) labelsByEntryId.set(entry.id, labels);
        pendingResumeAgeByRunId.delete(entry.runId);
      }
      for (const activity of entry.activities) {
        const age = activity.workEntry.questionAnswer
          ? claudeResumeCompactionAge(activity.workEntry.questionAnswer)
          : null;
        if (age !== null) pendingResumeAgeByRunId.set(entry.runId, age);
      }
    }
  }
  return labelsByEntryId;
}

function isResumeCompactionAnswerGroup(entry: ThreadFeedActivityGroup): boolean {
  return entry.activities.every((activity) => {
    const answer = activity.workEntry.questionAnswer;
    return answer !== undefined && claudeResumeCompactionAge(answer) !== null;
  });
}

export function isContextHandoffActivityGroup(entry: ThreadFeedActivityGroup): boolean {
  return (
    entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "handoff"
  );
}

export function isSecretRequestActivityGroup(entry: ThreadFeedActivityGroup): boolean {
  return (
    entry.activities.length === 1 &&
    entry.activities[0]?.projectedItem.item.type === "secret_request"
  );
}

export function isLinkRequestActivityGroup(entry: ThreadFeedActivityGroup): boolean {
  return (
    entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "link_request"
  );
}

function isUserInputActivityGroup(entry: ThreadFeedActivityGroup): boolean {
  return entry.activities.some((activity) => activity.workEntry.questionAnswer !== undefined);
}

function capitalizePhrase(value: string): string {
  const trimmed = value.trim();
  return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
}

function memoizeValue<T>(build: () => T): () => T {
  let value: T;
  let initialized = false;
  return () => {
    if (!initialized) {
      value = build();
      initialized = true;
    }
    return value;
  };
}

function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
  return (
    item.type === "reasoning" ||
    item.type === "command_execution" ||
    item.type === "file_change" ||
    item.type === "file_search" ||
    item.type === "web_search" ||
    item.type === "approval_request" ||
    item.type === "user_input_request" ||
    item.type === "dynamic_tool" ||
    item.type === "subagent"
  );
}

function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
  return (
    item.type === "fork" ||
    item.type === "thread_created" ||
    item.type === "system_notice" ||
    item.type === "proposed_plan" ||
    item.type === "secret_request" ||
    item.type === "link_request"
  );
}

function itemStatus(item: OrchestrationV2TurnItem): ThreadFeedActivity["status"] {
  if (item.type === "notification") return item.outcome === "failed" ? "failure" : null;
  if (item.type === "error") {
    if (item.status === "failed")
      return item.failure.class === "usage_limit" ? "neutral" : "failure";
    return item.status === "completed" ? "success" : "neutral";
  }
  if (!itemIsToolLike(item)) return null;
  if (item.status === "failed") return "failure";
  return item.status === "completed" ? "success" : "neutral";
}

function itemLifecycleStatus(item: OrchestrationV2TurnItem): WorkLogToolLifecycleStatus {
  switch (item.status) {
    case "pending":
    case "running":
    case "waiting":
      return "inProgress";
    case "idle":
      return "idle";
    case "completed":
      return "completed";
    case "failed":
      return "failed";
    case "cancelled":
    case "interrupted":
      return "stopped";
  }
}

function itemWorkLogTone(item: OrchestrationV2TurnItem): WorkLogPresentationEntry["tone"] {
  if (item.type === "error") return "info";
  if (item.type === "reasoning") return "thinking";
  switch (item.type) {
    case "command_execution":
    case "file_change":
    case "file_search":
    case "web_search":
    case "dynamic_tool":
    case "subagent":
      return "tool";
    default:
      return "info";
  }
}

function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
  if (item.type === "notification") {
    const source = item.source;
    switch (source.kind) {
      case "subagent":
      case "delegated_task":
        return "hammer";
      case "command":
        return "command";
      case "monitor":
        return "eye";
      case "background_task":
      case "system":
        return "zap";
      default:
        source satisfies never;
        return "zap";
    }
  }
  if (item.type === "dynamic_tool") {
    const classified = classifyToolActivity({
      itemType: "dynamic_tool_call",
      data: { toolName: item.toolName ?? undefined, input: item.input },
    });
    if (classified === "read") {
      return "eye";
    }
    if (classified === "search") return "search";
  }
  switch (item.type) {
    case "reasoning":
      return "agent";
    case "command_execution":
      return "command";
    case "file_change":
      return "edit";
    case "file_search":
      return "search";
    case "web_search":
      return "globe";
    case "approval_request":
      return item.requestKind === "permission" ? "lock" : "message";
    case "user_input_request":
    case "user_message":
    case "assistant_message":
      return "message";
    case "dynamic_tool":
      return isJavaScriptReplTool(item.toolName) ? "code" : "wrench";
    case "subagent":
      return "hammer";
    case "run_interrupt_request":
    case "run_interrupt_result":
      return "stop";
    case "system_notice":
      return "warning";
    case "error":
      return item.failure.class === "usage_limit"
        ? item.status === "completed"
          ? "check"
          : "warning"
        : "alert";
    case "checkpoint":
    case "proposed_plan":
    case "todo_list":
      return "check";
    case "compaction":
    case "handoff":
    case "fork":
    case "thread_created":
      return "zap";
    case "secret_request":
      return "lock";
    case "link_request":
      return "globe";
  }
}

function itemToolPresentation(item: OrchestrationV2TurnItem): T3McpToolPresentation | null {
  if (item.type !== "dynamic_tool") {
    return null;
  }
  return (
    resolveT3McpToolPresentation(item.toolName, item.input) ??
    resolveT3McpToolPresentation(item.title, item.input)
  );
}

function itemSummary(
  item: OrchestrationV2TurnItem,
  toolPresentation: T3McpToolPresentation | null = null,
): string {
  if (item.type === "notification") return item.summary;
  if (item.type === "system_notice") return item.message;
  if (item.type === "compaction") return contextCompactionLabel(item);
  const title =
    (item.type === "dynamic_tool"
      ? dynamicToolTitle(item.toolName, item.input, item.title)
      : undefined) ?? item.title?.trim();
  if (item.type === "subagent") return formatSubagentDisplayTitle(title || "Subagent");
  if (title) return toolPresentation?.displayName ?? capitalizePhrase(title);
  switch (item.type) {
    case "reasoning":
      return "Thinking";
    case "command_execution":
      return "Command";
    case "file_change":
      return item.changes !== undefined && item.changes.length > 1
        ? `Changed ${item.changes.length} files`
        : `Changed ${item.fileName}`;
    case "file_search":
      return item.title?.trim() || formatSearchToolLabel(item) || "Searched files";
    case "web_search":
      return "Searched the web";
    case "approval_request":
      return "Approval requested";
    case "user_input_request":
      return "Input requested";
    case "checkpoint":
      return "Checkpoint captured";
    case "run_interrupt_request":
      return "Interrupt requested";
    case "run_interrupt_result":
      return "Run interrupted";
    case "error":
      return item.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error";
    case "handoff":
      return "Context handed off";
    case "fork":
      return "Thread forked";
    case "thread_created":
      return "Thread created";
    case "secret_request":
      return item.label;
    case "link_request":
      return `Link ${item.label ?? item.url ?? "an environment"}`;
    case "dynamic_tool": {
      const classified = classifyToolActivity({
        itemType: "dynamic_tool_call",
        data: { toolName: item.toolName ?? undefined, input: item.input },
      });
      if (classified === "read") {
        const [path] = collectToolFilePaths({ input: item.input });
        return formatReadToolLabel(path ?? "");
      }
      if (classified === "search") {
        return formatSearchToolLabel({ input: item.input }) ?? item.toolName ?? "Tool call";
      }
      return toolPresentation?.displayName ?? item.toolName ?? "Tool call";
    }
    case "proposed_plan":
      return "Proposed plan";
    case "todo_list":
      return "Plan updated";
    case "user_message":
      return "User message";
    case "assistant_message":
      return "Assistant message";
  }
}

function itemPreview(item: OrchestrationV2TurnItem): string | null {
  switch (item.type) {
    case "reasoning":
      return item.text || null;
    case "command_execution":
      return item.input || null;
    case "file_change":
      return item.fileName;
    case "file_search":
      return item.pattern ?? null;
    case "web_search":
      return item.patterns?.join(", ") ?? null;
    case "approval_request":
      return item.prompt ?? null;
    case "user_input_request":
      return item.questions.map((question) => question.question).join(" · ") || null;
    case "checkpoint":
      return item.files.length === 1
        ? (item.files[0]?.path ?? null)
        : `${item.files.length} changed files`;
    case "run_interrupt_request":
    case "run_interrupt_result":
    case "system_notice":
      return item.message || null;
    case "error":
      return item.failure.message;
    case "compaction":
    case "handoff":
      return item.summary ?? null;
    case "fork":
    case "thread_created":
      return item.targetThreadId;
    case "secret_request":
    case "link_request":
      return item.reason || null;
    case "subagent":
      return item.result ?? item.progress ?? item.prompt;
    case "dynamic_tool":
      return null;
    case "notification":
      return item.detail ?? null;
    case "proposed_plan":
      return item.markdown || null;
    case "todo_list":
      return `${item.steps.filter((step) => step.status === "completed").length}/${item.steps.length} completed`;
    case "user_message":
    case "assistant_message":
      return item.text || null;
  }
}

function toWorkLogEntry(
  item: OrchestrationV2TurnItem,
  createdAt: string,
  summary: string,
  detail: string | null,
): WorkLogPresentationEntry {
  const title = item.title?.trim() || null;
  const common = {
    ...extractToolActivityPresentation(item),
    id: item.id,
    createdAt,
    label: summary,
    tone: itemWorkLogTone(item),
    itemType: item.type,
    toolLifecycleStatus: itemLifecycleStatus(item),
    structuredPayload: item,
    ...(item.type === "user_input_request" && item.questionAnswer
      ? { questionAnswer: item.questionAnswer }
      : {}),
  } as const;

  switch (item.type) {
    case "reasoning":
      return { ...common, ...(item.text ? { detail: item.text } : {}) };
    case "command_execution":
      return {
        ...common,
        command: item.input,
        rawCommand: item.input,
        toolTitle: title ?? "Command",
        toolData: item,
      };
    case "file_change":
      return {
        ...common,
        changedFiles: item.changes?.map((change) => change.path) ?? [item.fileName],
        toolTitle: title ?? "File change",
        toolData: item,
      };
    case "file_search":
      return {
        ...common,
        ...(item.pattern ? { detail: item.pattern } : {}),
        toolTitle: title ?? "File search",
        toolData: item,
      };
    case "web_search":
      return {
        ...common,
        ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
        toolTitle: title ?? "Web search",
        toolData: item,
      };
    case "checkpoint":
      return { ...common, changedFiles: item.files.map((file) => file.path), toolData: item };
    case "approval_request":
      return {
        ...common,
        ...(item.prompt ? { detail: item.prompt } : {}),
        requestKind: item.requestKind,
        toolData: item,
      };
    case "dynamic_tool":
      return {
        ...common,
        toolTitle: title ?? item.toolName ?? "Tool",
        toolData: { input: item.input, output: item.output },
      };
    default:
      return { ...common, ...(detail ? { detail } : {}), toolData: item };
  }
}

export function formatItemFullDetail(
  row: OrchestrationV2ProjectedTurnItem,
  item: OrchestrationV2TurnItem,
): string {
  return JSON.stringify(
    {
      visibility: row.visibility,
      sourceThreadId: row.sourceThreadId,
      sourceItemId: row.sourceItemId,
      item: toolItemForDisplay(item),
    },
    null,
    2,
  );
}

function toFeedActivity(
  row: OrchestrationV2ProjectedTurnItem,
  attemptId: RunAttemptId | null,
): ThreadFeedActivity {
  const item = row.item;
  const toolPresentation = itemToolPresentation(item);
  const summary = itemSummary(item, toolPresentation);
  const detail = item.type === "notification" ? null : itemPreview(item);
  const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
  const workEntry = toWorkLogEntry(item, createdAt, summary, detail);
  const readPaths =
    item.type === "dynamic_tool" && toolGroupAction(workEntry) === "read"
      ? collectToolFilePaths(item)
      : null;
  const getFullDetail = memoizeValue(() =>
    item.type === "proposed_plan"
      ? item.markdown
      : readPaths
        ? readPaths.join("\n") || null
        : item.type === "notification"
          ? item.detail?.trim() || null
          : formatItemFullDetail(row, item),
  );
  const getCopyText = memoizeValue(() =>
    item.type === "proposed_plan"
      ? `${item.markdown.trimEnd()}\n`
      : [summary, detail, getFullDetail()]
          .filter(
            (value, index, values): value is string =>
              Boolean(value) && values.indexOf(value) === index,
          )
          .join("\n"),
  );
  return {
    id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
    createdAt,
    runId: item.runId,
    attemptId,
    summary,
    detail,
    canExpand:
      !(item.type === "error" && item.status === "failed") &&
      (readPaths
        ? readPaths.length > 0 || turnItemNeedsDetailFetch(item)
        : turnItemHasDetail(item) || workEntry.questionAnswer !== undefined),
    fetchesDetail: turnItemNeedsDetailFetch(item),
    getFullDetail,
    getCopyText,
    icon: workEntry.toolSurface ?? itemIcon(item),
    logo: toolPresentation?.logo ?? null,
    toolLike: itemIsToolLike(item),
    prominent: itemIsProminent(item) || (item.type === "error" && item.status === "failed"),
    status:
      item.type === "error" && item.failure.class === "usage_limit"
        ? itemStatus(item)
        : workEntryDisplayIndicatesToolFailure(workEntry)
          ? "failure"
          : itemStatus(item),
    lifecycleStatus: itemLifecycleStatus(item),
    workEntry,
    projectedItem: row,
  };
}

function singleToolCallLabel(activity: ThreadFeedActivity, expanded: boolean): string {
  if (activity.workEntry.itemType === "reasoning")
    return expanded
      ? "Thought"
      : compactWorkEntryText(activity.workEntry.detail ?? "") || "Thought";
  const presentation = resolveWorkEntryToolPresentation(activity.workEntry, "completed");
  if (presentation) return presentation.displayName;
  const command = activity.workEntry.command?.trim();
  return command ? truncate(command, WORK_LOG_LABEL_MAX_LENGTH) : activity.summary;
}

function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
  return (
    entry.type === "message" &&
    entry.message.text.trim().length === 0 &&
    entry.message.attachments.length === 0
  );
}

/**
 * `onRestart` hears each entry after which no group is open, with the grouped
 * length so far: the entries before it group the same whatever follows.
 */
function groupAdjacentActivities(
  entries: ReadonlyArray<RawThreadFeedEntry>,
  childrenByRun: ReadonlyMap<RunId, ReadonlySet<string>>,
  onRestart?: (entryIndex: number, groupedLength: number) => void,
): ThreadFeedEntry[] {
  const grouped: ThreadFeedEntry[] = [];
  let firstActivityEntry: Extract<RawThreadFeedEntry, { readonly type: "activity" }> | null = null;
  let openGroupActivities: ThreadFeedActivity[] = [];
  const flushGroup = () => {
    if (firstActivityEntry === null) return;
    const cached = activityGroupsCache.get(firstActivityEntry.activity);
    if (
      cached &&
      cached.activities.length === openGroupActivities.length &&
      cached.activities.every((activity, index) => activity === openGroupActivities[index])
    ) {
      grouped.push(cached);
    } else {
      const group: ThreadFeedActivityGroup = {
        type: "activity-group",
        id: firstActivityEntry.id,
        createdAt: firstActivityEntry.createdAt,
        runId: firstActivityEntry.runId,
        activities: openGroupActivities,
      };
      activityGroupsCache.set(firstActivityEntry.activity, group);
      grouped.push(group);
    }
    firstActivityEntry = null;
    openGroupActivities = [];
  };

  for (let entryIndex = 0; entryIndex < entries.length; entryIndex += 1) {
    const entry = entries[entryIndex]!;
    if (entry.type === "activity") {
      const item = entry.activity.projectedItem.item;
      if (
        item.type === "dynamic_tool" &&
        item.runId !== null &&
        (item.status === "running" || item.status === "completed") &&
        resolveT3McpToolDefinition(item.toolName)?.summaryAction === "delegate" &&
        !workEntryDisplayIndicatesToolFailure(entry.activity.workEntry)
      ) {
        const output = compactDynamicToolOutput(item.output);
        if (
          !output?.isError &&
          output?.taskId !== undefined &&
          childrenByRun.get(item.runId)?.has(output.taskId)
        )
          continue;
      }
    }
    if (isEmptyMessage(entry)) {
      continue;
    }

    if (entry.type !== "activity") {
      flushGroup();
      grouped.push(entry);
      onRestart?.(entryIndex, grouped.length);
      continue;
    }

    const isStandaloneActivity =
      entry.activity.workEntry.questionAnswer !== undefined ||
      entry.activity.projectedItem.item.type === "compaction" ||
      entry.activity.projectedItem.item.type === "handoff" ||
      entry.activity.projectedItem.item.type === "notification";
    if (
      isStandaloneActivity ||
      entry.activity.prominent ||
      (entry.activity.projectedItem.item.type === "subagent") !==
        (firstActivityEntry?.activity.projectedItem.item.type === "subagent") ||
      firstActivityEntry?.runId !== entry.runId ||
      (entry.activity.projectedItem.item.type === "subagent" &&
        firstActivityEntry?.activity.projectedItem.item.providerTurnId !==
          entry.activity.projectedItem.item.providerTurnId) ||
      (entry.activity.projectedItem.item.type !== "subagent" &&
        firstActivityEntry?.activity.attemptId !== entry.activity.attemptId)
    ) {
      flushGroup();
    }
    firstActivityEntry ??= entry;
    openGroupActivities.push(entry.activity);
    if (isStandaloneActivity || entry.activity.prominent) {
      flushGroup();
    }
  }
  flushGroup();
  return grouped;
}

function computeElapsedMs(startIso: string, endIso: string): number | null {
  const start = Date.parse(startIso);
  const end = Date.parse(endIso);
  return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
}

function maxIsoTimestamp(left: string | null, right: string | null): string | null {
  if (left === null) return right;
  if (right === null) return left;
  return Date.parse(right) > Date.parse(left) ? right : left;
}

function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null {
  return threadFeedRunIsUnsettled(latestRun) ? latestRun.runId : null;
}

export function threadFeedRunIsUnsettled(
  run: ThreadFeedLatestRun | null,
): run is ThreadFeedLatestRun {
  if (run === null || run.status === "queued") return false;
  return (
    run.completedAt === null ||
    run.status === "preparing" ||
    run.status === "starting" ||
    run.status === "running" ||
    run.status === "waiting"
  );
}

function threadFeedActivityIsVisible(
  activity: Pick<ThreadFeedActivity, "prominent" | "status" | "toolLike"> &
    Partial<Pick<ThreadFeedActivity, "lifecycleStatus">>,
): boolean {
  return (
    activity.prominent ||
    activity.lifecycleStatus === "stopped" ||
    activity.lifecycleStatus === "declined" ||
    activity.lifecycleStatus === "idle" ||
    !(activity.toolLike && activity.status === "neutral")
  );
}

interface ThreadFeedRunFold {
  readonly deferredWorkItemIds?: ReadonlyArray<string>;
  readonly runId: RunId;
  readonly createdAt: string;
  readonly hiddenEntryIds: ReadonlySet<string>;
  readonly label: string;
}

export function failedFeedRunIds(
  feed: ReadonlyArray<ThreadFeedEntry>,
  latestRun: ThreadFeedLatestRun | null,
) {
  const failed = new Set<RunId>();
  if (latestRun?.status === "failed") failed.add(latestRun.runId);
  for (const entry of feed) {
    if (entry.type !== "activity-group") continue;
    for (const activity of entry.activities) {
      const item = activity.projectedItem.item;
      if (
        item.type === "error" &&
        item.status === "failed" &&
        item.parentItemId === null &&
        item.runId !== null
      )
        failed.add(item.runId);
    }
  }
  return failed;
}

/**
 * The key a run fold uses for the message `entryId`: its run, or for an
 * imported message with no run, the runless key of the user message before
 * it. Null for user messages, which never fold.
 */
export function messageFoldRunId(
  feed: ReadonlyArray<ThreadFeedEntry>,
  entryId: string,
): RunId | null {
  let runlessKey: RunId | null = null;
  for (const entry of feed) {
    if (entry.type !== "message") continue;
    if (entry.message.role === "user") {
      if (entry.id === entryId) return null;
      runlessKey = entry.message.runId == null ? RunId.make(`runless:${entry.id}`) : null;
    } else if (entry.id === entryId) {
      return entry.message.runId ?? runlessKey;
    }
  }
  return null;
}

function deriveThreadFeedRunFolds(
  feed: ReadonlyArray<ThreadFeedEntry>,
  latestRun: ThreadFeedLatestRun | null,
  runlessWorkActive: boolean,
  feedFailedRunIds: ReadonlySet<RunId>,
): ReadonlyMap<string, ThreadFeedRunFold> {
  const terminalAssistantMessageIdByRun = new Map<RunId, string>();
  const interruptedRunIds = new Set<RunId>();
  const failedRunIds = new Set(feedFailedRunIds);
  const promptIndexByRunId = new Map<RunId, number>();
  for (const [index, entry] of feed.entries()) {
    if (
      entry.type !== "message" ||
      entry.message.role !== "user" ||
      entry.message.inputIntent === "steer" ||
      entry.message.inputIntent === "promoted_queued_to_steer"
    ) {
      continue;
    }
    const runId = entry.message.runId;
    if (runId != null && !promptIndexByRunId.has(runId)) promptIndexByRunId.set(runId, index);
  }
  const groupsByRunId = new Map<
    RunId,
    { entries: ThreadFeedEntry[]; startBoundary: string | null }
  >();
  let runlessKey: RunId | null = null;
  let responseKey: RunId | null = null;
  let pendingUserBoundary: string | null = null;
  for (const [index, entry] of feed.entries()) {
    if (entry.type === "message" && entry.message.role === "user") {
      pendingUserBoundary = entry.message.createdAt;
      runlessKey = entry.message.runId == null ? RunId.make(`runless:${entry.id}`) : null;
      responseKey = entry.message.runId ?? runlessKey;
      continue;
    }
    const ownRunId =
      entry.type === "message" && entry.message.role === "assistant"
        ? (entry.message.runId ?? runlessKey)
        : entry.type === "activity-group" ||
            entry.type === "html-render" ||
            entry.type === "mcp-app"
          ? (entry.runId ?? runlessKey)
          : null;
    if (!ownRunId) continue;
    // Resumed subagents keep their original turn position and fold, leaving later run folds under their own prompts.
    const runId =
      responseKey !== null && (promptIndexByRunId.get(ownRunId) ?? -1) > index
        ? responseKey
        : ownRunId;
    let group = groupsByRunId.get(runId);
    if (!group) {
      group = { entries: [], startBoundary: pendingUserBoundary };
      pendingUserBoundary = null;
      groupsByRunId.set(runId, group);
    }
    group.entries.push(entry);
    if (entry.type === "message") {
      terminalAssistantMessageIdByRun.set(runId, entry.id);
    }
    if (entry.type !== "activity-group") continue;
    for (const activity of entry.activities) {
      const item = activity.projectedItem.item;
      if (item.type === "run_interrupt_result") interruptedRunIds.add(runId);
      if (
        runId === runlessKey &&
        item.type === "error" &&
        item.status === "failed" &&
        item.parentItemId === null
      ) {
        failedRunIds.add(runId);
      }
    }
  }

  const activeRunId = unsettledRunId(latestRun);
  const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();
  for (const [runId, group] of groupsByRunId) {
    if (
      runId === activeRunId ||
      (runlessWorkActive && runId === runlessKey) ||
      interruptedRunIds.has(runId) ||
      failedRunIds.has(runId) ||
      group.entries.some((entry) => entry.type === "message" && entry.message.streaming)
    ) {
      continue;
    }
    const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
    const hiddenEntryIds = new Set(
      group.entries
        .filter(
          (entry) =>
            entry.id !== terminalAssistantId &&
            entry.type !== "html-render" &&
            entry.type !== "mcp-app" &&
            !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) &&
            !(
              entry.type === "activity-group" &&
              entry.activities.some(
                (activity) =>
                  activity.prominent ||
                  activity.workEntry.questionAnswer !== undefined ||
                  activity.projectedItem.item.type === "notification" ||
                  activity.projectedItem.item.type === "handoff" ||
                  // A child still working outlives its settled launching run;
                  // its group stays visible while any member is live.
                  isLiveSubagentTurnItem(activity.projectedItem.item),
              )
            ),
        )
        .map((entry) => entry.id),
    );
    const firstEntry = group.entries[0];
    const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
    const lastEntry = group.entries.at(-1);
    if (!firstHiddenEntry || !firstEntry || !lastEntry) continue;
    const hidesNonCompactionWork = group.entries.some(
      (entry) =>
        hiddenEntryIds.has(entry.id) &&
        !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)),
    );
    if (!hidesNonCompactionWork) continue;
    const terminalEntry = terminalAssistantId
      ? group.entries.find((entry) => entry.id === terminalAssistantId)
      : null;
    const latestRunMatches = latestRun?.runId === runId;
    const lastEntryEnd =
      lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
    const elapsedMs =
      latestRunMatches && latestRun.startedAt && latestRun.completedAt
        ? computeElapsedMs(latestRun.startedAt, latestRun.completedAt)
        : computeElapsedMs(
            group.startBoundary ?? firstEntry.createdAt,
            maxIsoTimestamp(
              terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
              lastEntryEnd,
            ) ?? lastEntryEnd,
          );
    const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
    const interrupted =
      latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
    const deferredWorkItemIds = group.entries.flatMap((entry) =>
      entry.type === "activity-group"
        ? entry.activities.flatMap((activity) =>
            activity.projectedItem.item.deferredWork
              ? [String(activity.projectedItem.sourceItemId)]
              : [],
          )
        : [],
    );
    foldsByAnchorId.set(firstHiddenEntry.id, {
      ...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}),
      runId,
      createdAt: firstHiddenEntry.createdAt,
      hiddenEntryIds,
      label: interrupted
        ? duration
          ? `You stopped after ${duration}`
          : "You stopped this response"
        : duration
          ? `Worked for ${duration}`
          : "Worked",
    });
  }
  const covered = new Set(
    [...foldsByAnchorId.values()].flatMap((fold) => [...fold.hiddenEntryIds]),
  );
  for (const entry of feed) {
    if (entry.type !== "activity-group" || covered.has(entry.id)) continue;
    const deferredWorkItemIds = entry.activities.flatMap((activity) =>
      activity.projectedItem.item.deferredWork ? [String(activity.projectedItem.sourceItemId)] : [],
    );
    if (deferredWorkItemIds.length === 0) continue;
    foldsByAnchorId.set(entry.id, {
      runId: RunId.make(`deferred-work:${entry.id}`),
      createdAt: entry.createdAt,
      hiddenEntryIds: new Set([entry.id]),
      label: "Earlier work",
      deferredWorkItemIds,
    });
  }
  return foldsByAnchorId;
}

const supersededReasoningGroups = new WeakMap<ThreadFeedActivityGroup, ThreadFeedActivityGroup>();
const trailingReasoningGroups = new WeakMap<ThreadFeedActivityGroup, ThreadFeedActivityGroup>();

function settleSupersededReasoning(
  entry: Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" | "thinking" }>,
  tail: boolean,
) {
  if (entry.type !== "activity-group") return entry;
  const cache = tail ? trailingReasoningGroups : supersededReasoningGroups;
  const cached = cache.get(entry);
  if (cached) return cached;
  const activities = entry.activities.map((activity, index) =>
    activity.workEntry.itemType === "reasoning" &&
    activity.lifecycleStatus === "inProgress" &&
    (!tail || index < entry.activities.length - 1)
      ? {
          ...activity,
          lifecycleStatus: "completed" as const,
          status: "success" as const,
          workEntry: { ...activity.workEntry, toolLifecycleStatus: "completed" as const },
        }
      : activity,
  );
  const settled = activities.some((activity, index) => activity !== entry.activities[index])
    ? { ...entry, activities }
    : entry;
  cache.set(entry, settled);
  return settled;
}

interface ThreadFeedPresentationBuild {
  readonly feed: ReadonlyArray<ThreadFeedEntry>;
  readonly latestRun: ThreadFeedLatestRun | null;
  readonly expandedRunIds: ReadonlySet<RunId>;
  readonly expandedWorkGroupIds: ReadonlySet<string>;
  readonly activeWorkStartedAt: string | null;
  readonly runlessWorkActive: boolean;
  readonly display: ThreadFeedDisplay;
  readonly rows: ReadonlyArray<ThreadFeedEntry>;
  /** Feed entry `entry` is a user message whose rows start at `rowsLength`. */
  readonly restarts: ReadonlyArray<{ readonly entry: number; readonly rowsLength: number }>;
  /** Where each run's entries begin, so a reused prefix never shares a run with the rest. */
  readonly firstEntryByRun: ReadonlyMap<RunId, number>;
}

function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLatestRun | null) {
  return (
    left === right ||
    (left !== null &&
      right !== null &&
      left.runId === right.runId &&
      left.status === right.status &&
      left.startedAt === right.startedAt &&
      left.completedAt === right.completedAt &&
      left.turnEnded === right.turnEnded)
  );
}

function feedEntryRunId(entry: ThreadFeedEntry): RunId | null {
  return entry.type === "message" ? (entry.message.runId ?? null) : entry.runId;
}

function isUserMessageEntry(entry: ThreadFeedEntry | undefined): boolean {
  return entry?.type === "message" && entry.message.role === "user";
}

/**
 * A user message starts every fold and is never hidden or grouped, so the
 * rows before it depend only on the entries before it, their runs, and the
 * shared inputs. Returns the user message entry to restart from, or null to
 * present the whole feed.
 */
function presentationRestart(
  previous: ThreadFeedPresentationBuild | null,
  feed: ReadonlyArray<ThreadFeedEntry>,
  latestRun: ThreadFeedLatestRun | null,
  expandedRunIds: ReadonlySet<RunId>,
  expandedWorkGroupIds: ReadonlySet<string>,
  activeWorkStartedAt: string | null,
  runlessWorkActive: boolean,
  display: ThreadFeedDisplay,
): { readonly entry: number; readonly rowsLength: number; readonly index: number } | null {
  if (
    previous === null ||
    !latestRunsEqual(previous.latestRun, latestRun) ||
    previous.activeWorkStartedAt !== activeWorkStartedAt ||
    previous.runlessWorkActive !== runlessWorkActive ||
    previous.display.toolCallVisibility !== display.toolCallVisibility ||
    previous.display.revealedMessageId !== display.revealedMessageId ||
    !setsEqual(previous.expandedRunIds, expandedRunIds) ||
    !setsEqual(previous.expandedWorkGroupIds, expandedWorkGroupIds)
  ) {
    return null;
  }
  const firstChanged = firstChangedIndex(previous.feed, feed);
  let index = previous.restarts.length - 1;
  while (index >= 0 && previous.restarts[index]!.entry > firstChanged) index -= 1;
  const restart = previous.restarts[index];
  if (restart === undefined || !isUserMessageEntry(feed[restart.entry])) return null;
  for (let entryIndex = restart.entry; entryIndex < feed.length; entryIndex += 1) {
    const runId = feedEntryRunId(feed[entryIndex]!);
    const firstEntry = runId === null ? undefined : previous.firstEntryByRun.get(runId);
    if (firstEntry !== undefined && firstEntry < restart.entry) return null;
  }
  return { ...restart, index };
}

const visibleActivityGroups = new WeakMap<
  ThreadFeedActivityGroup,
  { readonly visibility: ToolCallVisibility; readonly group: ThreadFeedActivityGroup | null }
>();

function zenKeepsActivity(activity: ThreadFeedActivity): boolean {
  const item = activity.projectedItem.item;
  return (
    activity.prominent ||
    activity.workEntry.questionAnswer !== undefined ||
    item.type === "compaction" ||
    item.type === "handoff" ||
    item.type === "notification" ||
    (item.type === "error" && item.status !== "completed")
  );
}

function activityGroupForVisibility(
  entry: ThreadFeedActivityGroup,
  visibility: ToolCallVisibility,
): ThreadFeedActivityGroup | null {
  const cached = visibleActivityGroups.get(entry);
  if (cached?.visibility === visibility) return cached.group;
  const activities = entry.activities.filter((activity) =>
    visibility === "zen"
      ? zenKeepsActivity(activity)
      : !workEntryHiddenByToolCallVisibility(activity.workEntry, visibility),
  );
  const group =
    activities.length === 0
      ? null
      : activities.length === entry.activities.length
        ? entry
        : { ...entry, activities };
  visibleActivityGroups.set(entry, { visibility, group });
  return group;
}

function isSteerMessage(message: ThreadFeedMessage): boolean {
  return (
    message.role === "user" &&
    (message.inputIntent === "steer" || message.inputIntent === "promoted_queued_to_steer")
  );
}

function startsResponse(entry: ThreadFeedEntry): boolean {
  return (
    (entry.type === "message" && entry.message.role === "user" && !isSteerMessage(entry.message)) ||
    (entry.type === "activity-group" &&
      entry.activities.some((activity) => activity.projectedItem.item.type === "notification"))
  );
}

function zenAnswerMessageIds(
  feed: ReadonlyArray<ThreadFeedEntry>,
  start: number,
  answering: boolean,
  answeringRunId: RunId | null,
): ReadonlySet<MessageId> {
  const replies: Array<{ readonly message: ThreadFeedMessage; readonly index: number }> = [];
  const lastReplyByResponse = new Map<string, MessageId>();
  const steerAnswers = new Set<MessageId>();
  let userMessages = 0;
  let awaitingReply = false;
  let candidate: MessageId | null = null;
  let answeringFrom = answering ? start : feed.length;
  for (let index = start; index < feed.length; index += 1) {
    const entry = feed[index]!;
    if (
      entry.type === "activity-group" &&
      entry.activities.every((activity) => activity.workEntry.itemType === "reasoning")
    ) {
      continue;
    }
    const reply =
      entry.type === "message" && entry.message.role === "assistant" ? entry.message : null;
    if (candidate !== null && reply !== null) steerAnswers.add(candidate);
    candidate = null;
    if (answering && startsResponse(entry)) answeringFrom = index + 1;
    if (entry.type === "message" && entry.message.role === "user") {
      userMessages += 1;
      awaitingReply = isSteerMessage(entry.message);
    } else if (reply !== null) {
      replies.push({ message: reply, index });
      lastReplyByResponse.set(reply.runId ?? `runless:${userMessages}`, reply.id);
      if (awaitingReply) {
        candidate = reply.id;
        awaitingReply = false;
      }
    }
  }
  const terminal = new Set(lastReplyByResponse.values());
  return new Set(
    replies
      .filter(
        ({ message, index }) =>
          steerAnswers.has(message.id) ||
          (terminal.has(message.id) &&
            index < answeringFrom &&
            (answeringRunId === null || message.runId !== answeringRunId)),
      )
      .map(({ message }) => message.id),
  );
}

function liveAnswerPreview(feed: ReadonlyArray<ThreadFeedEntry>): string | null {
  for (let index = feed.length - 1; index >= 0; index -= 1) {
    const entry = feed[index]!;
    if (startsResponse(entry)) return null;
    const texts =
      entry.type === "message"
        ? entry.message.role === "assistant"
          ? [entry.message.text]
          : []
        : entry.type === "activity-group"
          ? entry.activities
              .filter((activity) => activity.workEntry.itemType === "reasoning")
              .map((activity) => activity.workEntry.detail ?? "")
          : [];
    for (let textIndex = texts.length - 1; textIndex >= 0; textIndex -= 1) {
      const line = compactWorkEntryText(liveThoughtLine(texts[textIndex]!));
      if (line !== "") return line;
    }
  }
  return null;
}

export interface ThreadFeedDisplay {
  readonly toolCallVisibility: ToolCallVisibility;
  readonly revealedMessageId: MessageId | null;
}

const DEFAULT_THREAD_FEED_DISPLAY: ThreadFeedDisplay = {
  toolCallVisibility: "showAll",
  revealedMessageId: null,
};

export function deriveThreadFeedPresentation(
  feed: ReadonlyArray<ThreadFeedEntry>,
  latestRun: ThreadFeedLatestRun | null,
  expandedRunIds: ReadonlySet<RunId>,
  expandedWorkGroupIds: ReadonlySet<string> = new Set(),
  activeWorkStartedAt: string | null = null,
  runlessWorkActive = false,
  cache?: ThreadFeedCache,
  display: ThreadFeedDisplay = DEFAULT_THREAD_FEED_DISPLAY,
): ThreadFeedEntry[] {
  const previous = cache?.presentation ?? null;
  const restart = presentationRestart(
    previous,
    feed,
    latestRun,
    expandedRunIds,
    expandedWorkGroupIds,
    activeWorkStartedAt,
    runlessWorkActive,
    display,
  );
  const start = restart?.entry ?? 0;
  const result: ThreadFeedEntry[] =
    restart === null ? [] : previous!.rows.slice(0, restart.rowsLength);
  const restarts = restart === null ? [] : previous!.restarts.slice(0, restart.index);
  const firstEntryByRun = new Map<RunId, number>();
  if (restart !== null) {
    for (const [runId, entry] of previous!.firstEntryByRun) {
      if (entry < start) firstEntryByRun.set(runId, entry);
    }
  }
  const tailStart = result.length;
  const lastEntryByRun = new Map<RunId, number>();

  const retainedFeed: Array<
    Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" | "thinking" }>
  > = [];
  const retainedFeedIndices: number[] = [];
  const { toolCallVisibility, revealedMessageId } = display;
  const isWorking = activeWorkStartedAt !== null && latestRun?.status !== "preparing";
  const activeRunId = unsettledRunId(latestRun);
  const zen = toolCallVisibility === "zen";
  const answering = isWorking && latestRun?.turnEnded !== true;
  const zenAnswerIds = zen
    ? zenAnswerMessageIds(feed, start, answering, answering ? activeRunId : null)
    : null;
  for (let index = start; index < feed.length; index += 1) {
    let entry = feed[index]!;
    if (entry.type === "run-fold" || entry.type === "work-toggle" || entry.type === "thinking")
      continue;
    const runId = feedEntryRunId(entry);
    if (runId !== null) {
      if (!firstEntryByRun.has(runId)) firstEntryByRun.set(runId, index);
      lastEntryByRun.set(runId, index);
    }
    if (entry.type === "activity-group" && toolCallVisibility !== "showAll") {
      const shown = activityGroupForVisibility(entry, toolCallVisibility);
      if (shown === null) continue;
      entry = shown;
    } else if (
      zenAnswerIds !== null &&
      entry.type === "message" &&
      entry.message.role === "assistant" &&
      entry.message.id !== revealedMessageId &&
      !zenAnswerIds.has(entry.message.id)
    ) {
      continue;
    }
    retainedFeed.push(entry);
    retainedFeedIndices.push(index);
  }
  const sourceFeed = retainedFeed.map((entry, index) =>
    settleSupersededReasoning(entry, index === retainedFeed.length - 1),
  );
  const failedRunIds = failedFeedRunIds(sourceFeed, latestRun);
  const activeTailGroup = sourceFeed.at(-1);
  // A bare `/compact` turn is the compaction itself: its compaction row stands in for the prompt
  // and the live activity row. An answered "compact before continuing?" question folds into the
  // compaction it asked for.
  const compactionCommandRunIds = new Set<RunId>();
  const compactionItemRunIds = new Set<RunId>();
  for (const entry of feed) {
    if (
      entry.type === "message" &&
      entry.message.runId !== null &&
      isCompactionCommandMessage(entry.message)
    ) {
      compactionCommandRunIds.add(entry.message.runId);
    } else if (
      entry.type === "activity-group" &&
      entry.runId !== null &&
      isContextCompactionActivityGroup(entry)
    ) {
      compactionItemRunIds.add(entry.runId);
    }
  }
  const foldsByAnchorId = zen
    ? new Map<string, ThreadFeedRunFold>()
    : deriveThreadFeedRunFolds(sourceFeed, latestRun, isWorking && runlessWorkActive, failedRunIds);
  const collapsedEntryIds = new Set<string>();
  for (const fold of foldsByAnchorId.values()) {
    if (!expandedRunIds.has(fold.runId)) {
      for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
    }
  }
  for (let sourceIndex = 0; sourceIndex < sourceFeed.length; sourceIndex += 1) {
    const entry = sourceFeed[sourceIndex]!;
    const feedIndex = retainedFeedIndices[sourceIndex]!;
    if (isUserMessageEntry(entry)) {
      restarts.push({ entry: feedIndex, rowsLength: result.length });
    }
    const isActiveTailGroup =
      isWorking &&
      (activeRunId !== null || runlessWorkActive) &&
      entry.type === "activity-group" &&
      activeTailGroup?.type === "activity-group" &&
      activeTailGroup.id === entry.id &&
      entry.runId === activeRunId;
    const fold = foldsByAnchorId.get(entry.id);
    if (fold) {
      const expanded = expandedRunIds.has(fold.runId);
      let row = runFoldRowsCache.get(entry);
      if (
        !row ||
        row.runId !== fold.runId ||
        row.createdAt !== fold.createdAt ||
        row.label !== fold.label ||
        row.expanded !== expanded ||
        row.deferredWorkItemIds?.join("|") !== fold.deferredWorkItemIds?.join("|")
      ) {
        row = {
          type: "run-fold",
          id: `run-fold:${fold.runId}`,
          ...(fold.deferredWorkItemIds ? { deferredWorkItemIds: fold.deferredWorkItemIds } : {}),
          createdAt: fold.createdAt,
          runId: fold.runId,
          label: fold.label,
          expanded,
        };
        runFoldRowsCache.set(entry, row);
      }
      result.push(row);
    }
    if (
      (entry.type === "message" &&
        entry.message.runId !== null &&
        compactionItemRunIds.has(entry.message.runId) &&
        isCompactionCommandMessage(entry.message)) ||
      (entry.type === "activity-group" &&
        entry.runId !== null &&
        compactionItemRunIds.has(entry.runId) &&
        isResumeCompactionAnswerGroup(entry))
    ) {
      continue;
    }
    if (!collapsedEntryIds.has(entry.id)) {
      if (
        entry.type === "activity-group" &&
        entry.runId !== null &&
        failedRunIds.has(entry.runId)
      ) {
        let rows = failedActivityGroupsCache.get(entry);
        if (!rows) {
          rows =
            entry.activities.length === 1
              ? [entry]
              : entry.activities.map((activity) => ({
                  type: "activity-group" as const,
                  id: activity.id,
                  createdAt: activity.createdAt,
                  runId: activity.runId,
                  activities: [activity],
                }));
          failedActivityGroupsCache.set(entry, rows);
        }
        result.push(...rows);
        continue;
      }
      appendPresentedFeedEntry(
        result,
        entry,
        expandedWorkGroupIds,
        activeRunId,
        isWorking,
        isActiveTailGroup,
      );
    }
  }
  if (
    isWorking &&
    activeWorkStartedAt !== null &&
    latestRun?.turnEnded !== true &&
    (activeRunId === null || !compactionCommandRunIds.has(activeRunId)) &&
    !result.some(
      (row) =>
        row.id === LIVE_ACTIVITY_ROW_ID ||
        (row.type === "activity-group" &&
          isContextCompactionActivityGroup(row) &&
          row.runId === activeRunId &&
          row.activities[0]?.projectedItem.item.status === "running"),
    )
  ) {
    result.push(
      thinkingRow(activeWorkStartedAt, activeRunId, zen ? liveAnswerPreview(feed) : null),
    );
  }
  const checkpointByRunId = new Map<RunId, ThreadCheckpointSummary>();
  for (const entry of sourceFeed) {
    if (entry.type === "message" && entry.message.checkpointSummary) {
      checkpointByRunId.set(entry.message.checkpointSummary.runId, entry.message.checkpointSummary);
    }
  }
  const workRowByRunId = new Map<RunId, number>();
  for (let index = tailStart; index < result.length; index += 1) {
    const row = result[index]!;
    if (
      (row.type === "run-fold" || row.type === "work-toggle") &&
      row.runId !== null &&
      checkpointByRunId.has(row.runId) &&
      (row.type === "run-fold" || !workRowByRunId.has(row.runId))
    ) {
      workRowByRunId.set(row.runId, index);
    }
  }
  for (const [runId, index] of workRowByRunId) {
    result[index] = { ...result[index]!, checkpointSummary: checkpointByRunId.get(runId)! };
  }
  for (let index = tailStart; index < result.length; index += 1) {
    const row = result[index]!;
    if (
      row.type !== "message" ||
      !row.message.checkpointSummary ||
      !workRowByRunId.has(row.message.checkpointSummary.runId)
    )
      continue;
    const message = { ...row.message };
    delete message.checkpointSummary;
    result[index] = { ...row, message };
  }
  // Reused rows are final: the user message after them never continues a work log.
  for (let index = tailStart; index < result.length; index += 1) {
    const row = result[index]!;
    if (!isWorkLogFeedRow(row) || !isWorkLogFeedRow(result[index + 1])) continue;
    let continued = continuedWorkLogRows.get(row);
    if (!continued) {
      continued = { ...row, continuesWorkLog: true };
      continuedWorkLogRows.set(row, continued);
    }
    result[index] = continued;
  }
  // A run that crosses a user message made the rows before it from entries
  // after it, so a later build cannot restart there even once those entries
  // are gone. Only runs of this build's own entries can cross its restarts.
  const crossings = Array.from({ length: feed.length - start + 1 }, () => 0);
  for (const [runId, last] of lastEntryByRun) {
    const first = firstEntryByRun.get(runId)!;
    if (first >= last) continue;
    crossings[first - start + 1]! += 1;
    crossings[last - start + 1]! -= 1;
  }
  let crossingRuns = 0;
  let crossingIndex = 0;
  const cleanRestarts = restarts.filter((candidate) => {
    if (candidate.entry < start) return true;
    while (crossingIndex <= candidate.entry - start) {
      crossingRuns += crossings[crossingIndex]!;
      crossingIndex += 1;
    }
    return crossingRuns === 0;
  });
  if (cache) {
    cache.presentation = {
      feed,
      latestRun,
      expandedRunIds,
      expandedWorkGroupIds,
      activeWorkStartedAt,
      runlessWorkActive,
      display,
      rows: result,
      restarts: cleanRestarts,
      firstEntryByRun,
    };
  }
  return result;
}

const continuedWorkLogRows = new WeakMap<ThreadFeedEntry, ThreadFeedEntry>();

function isWorkLogFeedRow(row: ThreadFeedEntry | undefined): boolean {
  return (
    row !== undefined &&
    (row.type === "work-toggle" ||
      row.type === "thinking" ||
      (row.type === "activity-group" &&
        !isContextCompactionActivityGroup(row) &&
        !isContextHandoffActivityGroup(row) &&
        row.activities.every(
          (activity) =>
            !activity.prominent &&
            activity.projectedItem.item.type !== "notification" &&
            activity.projectedItem.item.type !== "subagent",
        )))
  );
}

const LIVE_ACTIVITY_ROW_ID = "live-activity-row";

function thinkingRow(createdAt: string, runId: RunId | null, label: string | null) {
  if (
    cachedThinkingRow?.createdAt !== createdAt ||
    cachedThinkingRow.runId !== runId ||
    (cachedThinkingRow.label ?? null) !== label
  ) {
    cachedThinkingRow = {
      type: "thinking",
      id: LIVE_ACTIVITY_ROW_ID,
      createdAt,
      runId,
      ...(label === null ? {} : { label }),
    };
  }
  return cachedThinkingRow;
}

function appendPresentedFeedEntry(
  result: ThreadFeedEntry[],
  entry: Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" | "thinking" }>,
  expandedWorkGroupIds: ReadonlySet<string>,
  activeRunId: RunId | null,
  isWorking: boolean,
  activeTail: boolean,
): void {
  if (entry.type !== "activity-group") {
    result.push(entry);
    return;
  }
  if (
    isContextCompactionActivityGroup(entry) ||
    isContextHandoffActivityGroup(entry) ||
    isUserInputActivityGroup(entry) ||
    entry.activities[0]?.projectedItem.item.type === "subagent"
  ) {
    result.push(entry);
    return;
  }

  let cached = presentedActivityGroupsCache.get(entry);
  if (
    !cached ||
    cached.activeRunId !== activeRunId ||
    cached.isWorking !== isWorking ||
    cached.activeTail !== activeTail ||
    cached.rows.some(
      (row) => row.type === "work-toggle" && expandedWorkGroupIds.has(row.groupId) !== row.expanded,
    )
  ) {
    const rows: ThreadFeedEntry[] = [];
    appendActivityGroupRows(rows, entry, expandedWorkGroupIds, activeRunId, isWorking, activeTail);
    cached = { activeRunId, isWorking, activeTail, rows };
    presentedActivityGroupsCache.set(entry, cached);
  }
  for (const row of cached.rows) {
    result.push(row);
  }
}

function appendActivityGroupRows(
  result: ThreadFeedEntry[],
  entry: ThreadFeedActivityGroup,
  expandedWorkGroupIds: ReadonlySet<string>,
  activeRunId: RunId | null,
  isWorking: boolean,
  activeTail: boolean,
): void {
  const groupAnchorIdByActivityId = new Map<string, string>();
  let groupAnchorId: string | null = null;
  for (const activity of entry.activities) {
    const item = activity.projectedItem.item;
    if (activity.prominent || (item.type === "error" && item.status === "failed")) {
      groupAnchorId = null;
      continue;
    }
    groupAnchorId ??= activity.id;
    groupAnchorIdByActivityId.set(activity.id, groupAnchorId);
  }
  const activities = entry.activities.filter(
    (activity) =>
      threadFeedActivityIsVisible(activity) ||
      (isWorking && activity.lifecycleStatus === "inProgress" && activity.runId === activeRunId),
  );
  if (activities.length === 0) {
    return;
  }

  let groupableRun: ThreadFeedActivity[] = [];
  const flushGroupableRun = (isTrailingRun: boolean) => {
    if (groupableRun.length === 0) return;
    appendToolGroupRows(
      result,
      entry,
      groupableRun,