// The conversation of a session, as research mockups session-ux-v1 (boards A, B, C, E): each turn is the user's message
// (a bubble on the right: its time, Copy and Reuse on hover; a long one folds), then the agent's work, then its answer.
// The work (tool calls, the agent's words between them, closed decisions, mode changes) is one quiet line per tool call,
// runs of the same kind grouped ("Read 3 files"), each opening in place on what it did (an edit's changed lines, a
// command's input and output, the image a read looked at, the screenshot or video a tool's output shows in Markdown). A turn that completed folds its work behind one line, "Worked for 2m 14s · 9 actions ·
// 2 files +18 −6", opened on a click; a running, interrupted or failed one stays open. The running turn says "Working
// for 0:42" and keeps its last thought in view. The answer (the agent's last words after its last tool call) is plain
// Markdown, its code blocks with Wrap and Copy; under it the files the turn changed (Review opens the session's
// changes) and Copy, its time and how long it took (always on the last turn, on hover before). Notices, messages
// between sessions, commits and unfinished turn ends stay in view.
// The timeline's rows: an open decision shows on the row of the tool call it asks about (or on its own row),
// its options there (bridge#194); a compaction is one working row, "Compacting for 12s", then a quiet "Compacted"
// (bridge#195); a scheduled task's prompt is a compact row naming its task, the prompt a click away (bridge#198), and a
// message Bridge itself sent the agent (`from: 'bridge'`) a quiet notice row naming Bridge, not the user's bubble; the
// running turn's working line names its newest tool call (bridge#199); a tool call's change counts open the session's
// changes on that file (bridge#200). Child sessions (bridge#212 S3, ./children.tsx): the children a turn delegated are
// a group of cards after its work, in view when it folds, their `delegate_session` rows hidden; Bridge's message with
// their results or questions is one block linking each child; a child's task (and a follow-up, a message from another
// session) shows without Bridge's block, under whom it came from; a child's question or result waiting in the queue
// names its child.
import * as React from 'react';
import Markdown, { defaultUrlTransform, type Components } from 'react-markdown';
import remarkGfm from 'remark-gfm';
import {
  Button,
  Icon,
  ScreenLink,
  Tooltip,
  TooltipContent,
  TooltipTrigger,
  cn,
  copyText,
  type ScreenLinkProps,
  formatDate,
} from '@bridge/ui';
import {
  AttachedImages,
  MarkdownMedia,
  MediaOrigins,
  MediaWorkspace,
  markdownImages,
  mediaUrl,
  outputMedia,
  viewedImage,
  type Attached,
} from '@bridgebrew/session-ui/media';
import { oneLine } from '@bridgebrew/session-ui/one-line';
import { cutText } from '../text.ts';
import type { PluginComponent } from '../views/library.ts';
import type { ViewComponentRenderer, ViewTools } from './views/view.tsx';
import { useMediaOrigins } from './media-origins.tsx';
import { ViewLine } from './views.tsx';
import { answerSummary, isQuestion, type Answer, type Asked, type Question } from '../answers.ts';
import { DecisionQuestions } from './decision-questions.tsx';
import { Elapsed, Spinner, duration } from './elapsed.tsx';
import {
  ChildCards,
  ChildrenMessage,
  LineageContext,
  TaskFrom,
  cardsByTurn,
  hiddenCalls,
  sameCards,
  taskOf,
  type Delegation,
  type Lineage,
} from './children.tsx';
import { SubagentCards, sameSubagents, subagentsByTurn, type SubagentCard } from './subagents.tsx';

export { Spinner };

/** Whether a mode change's `options` (`{ plan?, auto? }`, where a decision's are a list) holds `option`. */
const optionOn = (options: unknown, option: 'plan' | 'auto') =>
  typeof options === 'object' &&
  options !== null &&
  Object.entries(options).some(([key, value]) => key === option && value === true);

/** A child's question a `user/message` of Bridge's delivers: the child, its decision, the text asking it. */
export interface ChildQuestion {
  session: string;
  decision: string;
  text: string;
}
/** The questions decision `event` asks (the harness contract's `questions`), none for an old driver's. */
const questionsAsked = (event: Stored) =>
  event.type === 'decision/asked' && event.questions?.length
    ? (event.questions as Question[])
    : undefined;
/** Decision `event` as `answers.ts` reads it. */
const askedOf = (event: Stored): Asked => ({
  title: event.title,
  options: event.options,
  kind: event.kind === 'question' || event.kind === 'approval' ? event.kind : undefined,
  questions: questionsAsked(event),
});

export interface Stored {
  seq: number;
  time?: string;
  type: string;
  id?: string;
  sha?: string;
  files?: string[];
  request?: string;
  question?: string;
  to?: string;
  /** A peer line's sender; on a `user/message`, `'bridge'` when Bridge itself sent it (not the user). */
  from?: string;
  verdict?: string;
  by?: string;
  text?: string;
  title?: string;
  /** A `view` line (research-036): its program, and the view it patched. */
  program?: string;
  base?: number;
  /** A frozen view's answers by query, and when it was frozen; a dynamic view has no snapshot and `dynamic: true`. */
  snapshot?: Record<string, unknown>;
  at?: string;
  dynamic?: boolean;
  /** A `view_frozen` line (research-036 P5): the view it freezes. */
  view?: number;
  /** The plugin components the view calls, as declared when it was shown (research-036 P2). */
  components?: PluginComponent[];
  kind?: string;
  status?: string;
  reason?: string;
  message?: string;
  interrupted?: boolean;
  input?: unknown;
  output?: unknown;
  options?: { id: string; label: string; kind?: string; scope?: string }[];
  option?: string | null;
  expiresAt?: string;
  mode?: string;
  effort?: string;
  name?: string;
  auto?: boolean;
  changes?: Change[];
  usage?: Usage;
  attachments?: Attached[];
  /** A `decision/asked` line's tool call (its `id`), when the agent said which call it asks about. */
  tool?: string;
  /** A `user/message` a scheduled task sent: its task. */
  scheduled?: { id: string; title: string };
  /** A `user/message` of Bridge's delivering children's results: their delegations (`delegations.ts`). */
  delegations?: string[];
  /** A `user/message` of Bridge's delivering children's questions: each child, its decision, the text asking it; a
   *  `decision/asked`'s questions (the harness contract's, `questionsAsked`). */
  questions?: ChildQuestion[] | Question[];
  /** A `decision/answered`'s answers to its questions (`option` null then). */
  answers?: { question: string; options?: string[]; text?: string }[];
  /** A `user/message` of Bridge's another session's agent sent: that session. */
  sender?: string;
  /** A `user/message` put into a running turn (bridge#212 S6): drawn where it entered the turn, among its work. */
  steered?: boolean;
  /** A line of a sub-agent of the session's agent (bridge#212 S8, ./subagents.tsx): its id; on a `subagent` line, the
   *  sub-agent it tells. */
  subagent?: string;
  /** A `subagent` line's agent kind, its task, and whether its harness can stop it. */
  agent?: string;
  prompt?: string;
  stoppable?: boolean;
}
export interface Change {
  path: string;
  added: number;
  removed: number;
  lines: string[];
  more?: number;
}
interface Usage {
  used?: number | undefined;
  size?: number | undefined;
}
export interface LiveEvent {
  type: string;
  id?: string;
  title?: string;
  kind?: string;
  text?: string;
  status?: string;
  input?: unknown;
  output?: unknown;
  changes?: Change[];
  entries?: { content: string; status: string }[];
  used?: number;
  size?: number;
  /** A `view/draft` event's program so far (research-036 streaming). */
  program?: string;
  /** The sub-agent that emits it (bridge#212 S8). */
  subagent?: string;
}
/** The running turn's in-flight part, as the server's accumulator. */
export interface Live {
  seq: number;
  text: string;
  thought: string;
  tools: Record<string, LiveEvent>;
  plan: { content: string; status: string }[];
  usage?: Usage | null;
  decisions: LiveEvent[];
  /** A view whose program the agent is still writing (research-036 streaming). */
  view?: { id: string; title?: string; program: string };
  /** Its sub-agents' pending text and thought, by sub-agent (bridge#212 S8). */
  subagents?: Record<string, { text: string; thought: string }>;
}

const verdicts = { ok: 'OK', wait: 'Wait', no: 'No' } as const;
const toolIcons: Record<string, string> = {
  read: 'eye',
  edit: 'pen-line',
  delete: 'trash',
  move: 'move',
  search: 'search',
  execute: 'terminal',
  think: 'brain',
  fetch: 'globe',
  compact: 'minimize-2',
};

/** A tool input or output as text, cut for display (the full one stays in the history). */
const shown = (value: unknown) => {
  const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
  return text.length > 4000 ? `${cutText(text, 4000)}\n… [truncated]` : text;
};
const clock = (iso?: string) =>
  iso ? formatDate(iso, { hour: 'numeric', minute: '2-digit' }) : '';
const fullDate = (iso?: string) =>
  iso ? formatDate(iso, { dateStyle: 'full', timeStyle: 'short' }) : undefined;
const between = (from?: string, to?: string) =>
  from && to ? Date.parse(to) - Date.parse(from) : undefined;

/** A copy button: the icon turns to a check for a second. */
function CopyButton({
  text,
  label = 'Copy',
  className,
}: {
  text: () => string;
  label?: string;
  className?: string;
}) {
  const [done, setDone] = React.useState<'Copied' | 'Copy failed'>();
  React.useEffect(() => {
    if (!done) return;
    const timer = setTimeout(() => setDone(undefined), 1200);
    return () => clearTimeout(timer);
  }, [done]);
  return (
    <Tooltip>
      <TooltipTrigger
        render={
          <Button
            size="icon-sm"
            aria-label={done ?? label}
            className={cn(
              'text-muted',
              done === 'Copied' && 'text-success',
              done === 'Copy failed' && 'text-destructive',
              className,
            )}
            onClick={() =>
              void copyText(text()).then(
                () => setDone('Copied'),
                () => setDone('Copy failed'),
              )
            }
          />
        }
      >
        <Icon
          name={done === 'Copied' ? 'check' : done === 'Copy failed' ? 'x' : 'copy'}
          size={14}
        />
      </TooltipTrigger>
      <TooltipContent>{done ?? label}</TooltipContent>
    </Tooltip>
  );
}

/** A fenced code block: its language, Wrap and Copy in a header. */
function CodeBlock({ children }: { children?: React.ReactNode }) {
  const [wrap, setWrap] = React.useState(false);
  const body = React.useRef<HTMLPreElement>(null);
  const child = React.Children.toArray(children)[0];
  const language = React.isValidElement<{ className?: string }>(child)
    ? /language-([\w+-]+)/.exec(child.props.className ?? '')?.[1]
    : undefined;
  return (
    <div
      data-code
      className="overflow-hidden rounded-default border border-border-subtle bg-hover/60"
    >
      <div className="flex h-8 items-center gap-0.5 border-b border-border-subtle pl-3 pr-1 text-xs text-muted">
        <span>{language ?? 'text'}</span>
        <span className="flex-1" />
        <Tooltip>
          <TooltipTrigger
            render={
              <Button
                size="icon-sm"
                aria-label="Wrap lines"
                aria-pressed={wrap}
                className={cn('text-muted', wrap && 'text-foreground')}
                onClick={() => setWrap((was) => !was)}
              />
            }
          >
            <Icon name="text-wrap" size={14} />
          </TooltipTrigger>
          <TooltipContent>Wrap lines</TooltipContent>
        </Tooltip>
        <CopyButton text={() => body.current?.textContent ?? ''} label="Copy code" />
      </div>
      <pre
        ref={body}
        className={cn(
          'overflow-x-auto p-3 font-mono text-xs leading-relaxed [&_code]:bg-transparent [&_code]:p-0 [&_code]:text-xs',
          wrap && 'whitespace-pre-wrap break-words',
        )}
      >
        {children}
      </pre>
    </div>
  );
}

/** Open in editor from the conversation (bridge-plugins#253): an agent's link to a file of the session's folder opens it
 *  in the code editor (`label`: `Open in VS Code on mac-mini`), at its line; none on a phone, nor without an editor. */
export interface FileOpener {
  folder: string;
  label: string;
  open: (target: FileTarget) => void;
  /** About to be used (a link pointed at, focused): the editor read again. */
  refresh?: () => void;
  /** Not available from this page (another computer): the link says so (`label`), and `open` only explains. */
  unavailable?: boolean;
}
export interface FileTarget {
  path: string;
  line?: number;
  column?: number;
}
const FileLinks = React.createContext<FileOpener | null>(null);
/** The file a link names inside `folder`: an absolute path, its position after it (`a.ts:12`, `a.ts:12:3`) or in its
 *  fragment (`a.ts#L12`, `#L12C3`), a Windows one too (`C:\\w\\a.ts:12`); none for any other link (a page of this Bridge,
 *  a file elsewhere). */
export const fileTarget = (href: string, folder: string): FileTarget | undefined => {
  const [raw = '', fragment = ''] = href.split('#', 2);
  let path: string;
  try {
    // A Windows path (`C:\\w\\a.ts`) read with `/`, as its folder: Windows takes either.
    path = decodeURI(raw).replaceAll('\\', '/');
  } catch {
    return undefined;
  }
  const base = folder.replaceAll('\\', '/').replace(/\/$/, '');
  const at = /:(\d+)(?::(\d+))?$/.exec(path) ?? /^L(\d+)(?:C(\d+))?$/.exec(fragment);
  if (at?.index !== undefined && at.input === path) path = path.slice(0, at.index);
  if (!path.startsWith(`${base}/`) || path.split('/').includes('..')) return undefined;
  return { path, ...(at && { line: Number(at[1]) }), ...(at?.[2] && { column: Number(at[2]) }) };
};

/** Markdown in the chat's type, GitHub's flavour (tables, bare URLs as links): no raw HTML (react-markdown escapes it),
 *  external links in a new tab, local images and videos shown (`media.tsx`). */
const markdown: Components = {
  p: ({ node: _node, ...props }) => <p className="leading-relaxed" {...props} />,
  h1: ({ node: _node, ...props }) => <h3 className="text-base font-semibold" {...props} />,
  h2: ({ node: _node, ...props }) => <h4 className="text-base font-semibold" {...props} />,
  h3: ({ node: _node, ...props }) => <h5 className="text-sm font-semibold" {...props} />,
  ul: ({ node: _node, ...props }) => <ul className="list-disc space-y-1 pl-5" {...props} />,
  ol: ({ node: _node, ...props }) => <ol className="list-decimal space-y-1 pl-5" {...props} />,
  blockquote: ({ node: _node, ...props }) => (
    <blockquote className="border-l-2 border-border pl-3 text-secondary" {...props} />
  ),
  // A link of this Bridge stays an anchor without a target, which the shell's link rule follows (research-048: a plain
  // click here, ⌘ or a middle click beside, ⌥ on a new desk); another opens in a new tab, which gets no `opener`.
  a: function Link({ node: _node, ...props }) {
    const opener = React.useContext(FileLinks);
    const file = opener && props.href ? fileTarget(props.href, opener.folder) : undefined;
    if (opener && file)
      return (
        <a
          {...props}
          className="text-accent underline-offset-2 hover:underline"
          title={opener.label}
          aria-disabled={opener.unavailable || undefined}
          data-open-in-editor
          onPointerEnter={opener.refresh}
          onFocus={opener.refresh}
          onClick={(event) => {
            event.preventDefault();
            opener.open(file);
          }}
        />
      );
    let internal = false;
    if (typeof location !== 'undefined' && props.href) {
      try {
        internal = new URL(props.href, location.href).origin === location.origin;
      } catch {
        /* Leave malformed links to the browser. */
      }
    }
    return (
      <a
        className="text-accent underline-offset-2 hover:underline"
        target={internal ? undefined : '_blank'}
        rel={internal ? undefined : 'noopener noreferrer'}
        {...props}
      />
    );
  },
  table: ({ node: _node, ...props }) => (
    <div className="overflow-x-auto">
      <table className="w-full border-collapse text-[13px]" {...props} />
    </div>
  ),
  th: ({ node: _node, ...props }) => (
    <th className="border border-border-subtle px-2 py-1 text-left font-semibold" {...props} />
  ),
  td: ({ node: _node, ...props }) => (
    <td className="border border-border-subtle px-2 py-1" {...props} />
  ),
  hr: () => <hr className="border-border" />,
  code: ({ node: _node, ...props }) => (
    <code className="rounded-sm bg-hover px-1 py-px font-mono text-[0.85em]" {...props} />
  ),
  pre: ({ node: _node, children }) => <CodeBlock>{children}</CodeBlock>,
  img: ({ src, alt }) => (
    <MarkdownMedia
      {...(typeof src === 'string' ? { src } : {})}
      {...(alt === undefined ? {} : { alt })}
    />
  ),
};
const remarkPlugins = [remarkGfm];
// A link to a Windows path (`C:\\w\\a.ts`) is kept: react-markdown's filter reads `C:` as a scheme and drops it, and
// Open in editor reads it (`fileTarget`); a link to no file of the session stays inert (`c:` opens nothing).
const urlTransform = (url: string, key: string) =>
  key === 'href' && /^[a-z]:[\\/]/i.test(url) ? url : mediaUrl(url, key, defaultUrlTransform);
/** The blinking caret after a streaming reply's last block (a pseudo-element: no text). */
const caret =
  "[&>:last-child]:after:ml-0.5 [&>:last-child]:after:inline-block [&>:last-child]:after:h-[1em] [&>:last-child]:after:w-[0.45em] [&>:last-child]:after:translate-y-[0.15em] [&>:last-child]:after:animate-pulse [&>:last-child]:after:rounded-[1px] [&>:last-child]:after:bg-foreground [&>:last-child]:after:content-['']";
// Memoized: a streamed delta parses the running reply's Markdown again, never the earlier ones'.
const Reply = React.memo(function Reply({
  text,
  streaming = false,
  quiet = false,
}: {
  text: string;
  streaming?: boolean;
  quiet?: boolean;
}) {
  return (
    <div
      className={cn(
        'flex flex-col break-words',
        quiet ? 'gap-2 text-[13px] text-secondary' : 'gap-3 text-sm text-foreground',
        streaming && caret,
      )}
    >
      <Markdown remarkPlugins={remarkPlugins} components={markdown} urlTransform={urlTransform}>
        {text}
      </Markdown>
    </div>
  );
});

/** Time left until `expiresAt` in its last minute, ticking each second: "expires in 42 s"; nothing before. */
const Countdown = ({ expiresAt }: { expiresAt: string }) => {
  const [now, setNow] = React.useState(Date.now);
  React.useEffect(() => {
    const timer = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(timer);
  }, []);
  const left = Math.ceil((Date.parse(expiresAt) - now) / 1000);
  if (left > 60) return null;
  const text = left <= 0 ? 'expiring…' : `expires in ${left} s`;
  return (
    <span
      data-countdown
      className={cn(
        'text-xs tabular-nums',
        left <= 10 ? 'font-medium text-destructive' : 'text-muted',
      )}
    >
      {text}
    </span>
  );
};

/** Added and removed line counts, in the diff colours. */
const Counts = ({ added, removed }: { added: number; removed: number }) => (
  <span className="shrink-0 font-mono text-xs">
    {added > 0 && <span className="text-success">+{added}</span>}
    {added > 0 && removed > 0 && ' '}
    {removed > 0 && <span className="text-destructive">−{removed}</span>}
  </span>
);
const sum = (changes: Change[]) =>
  changes.reduce(
    (total, each) => ({ added: total.added + each.added, removed: total.removed + each.removed }),
    { added: 0, removed: 0 },
  );

/** One tool call as the conversation knows it: its call line, its result line, its live state. */
interface Tool {
  call: Stored;
  result?: Stored | undefined;
  live?: LiveEvent | undefined;
}
const statusOf = ({ result, live }: Tool) => result?.status ?? live?.status ?? 'pending';
const isDone = (tool: Tool) => !['pending', 'running'].includes(statusOf(tool));
const changesOf = ({ result, live }: Tool) => result?.changes ?? live?.changes ?? [];

/** The verb of a run of `count` tool calls of kind `kind`, done or not. */
const runLabel = (kind: string, count: number, done: boolean) => {
  const [doing, did, what] = (
    {
      read: ['Reading', 'Read', 'files'],
      edit: ['Editing', 'Edited', 'files'],
      delete: ['Deleting', 'Deleted', 'files'],
      move: ['Moving', 'Moved', 'files'],
      search: ['Running', 'Ran', 'searches'],
      execute: ['Running', 'Ran', 'commands'],
      fetch: ['Fetching', 'Fetched', 'pages'],
      think: ['Thinking', 'Thought', 'times'],
      compact: ['Compacting', 'Compacted', 'times'],
    } as Record<string, [string, string, string]>
  )[kind] ?? ['Using', 'Used', 'tools'];
  return `${done ? did : doing} ${count} ${what}`;
};

/** What a tool call did, opened under its line: its edits' changed lines, else its input and output. */
function ToolDetails({
  tool,
  relative,
  onOpenChange,
}: {
  tool: Tool;
  relative: (path: string) => string;
  onOpenChange?: ((path: string) => void) | undefined;
}) {
  const changes = changesOf(tool);
  const output = tool.result?.output ?? tool.live?.output;
  const input = tool.call.input;
  // An image the agent looked at shows, not its path again and its bytes.
  const image = viewedImage(tool.call.kind, input);
  if (image)
    return (
      <div data-who="tool-image" className="ml-[22px] mt-1 mb-2">
        <MarkdownMedia src={image} />
      </div>
    );
  // A screenshot or a video a tool made shows, not its JSON and its image's bytes.
  const media = outputMedia(output);
  if (media.length)
    return (
      <div data-who="tool-image" className="ml-[22px] mt-1 mb-2 flex flex-wrap gap-2">
        {media.map((path) => (
          <MarkdownMedia key={path} src={path} />
        ))}
      </div>
    );
  if (changes.length) {
    return (
      <div className="ml-[22px] mt-1 mb-2 grid gap-2">
        {changes.map((change, index) => (
          <div
            key={index}
            className="overflow-hidden rounded-default border border-border-subtle bg-hover/40 text-xs"
          >
            <div className="flex h-7 items-center gap-2 border-b border-border-subtle bg-surface px-2.5 text-muted">
              <span className="min-w-0 truncate font-mono text-secondary">
                {relative(change.path)}
              </span>
              <Counts added={change.added} removed={change.removed} />
              {onOpenChange && (
                <Button
                  size="sm"
                  className="ml-auto h-6 gap-1 px-1.5 text-xs text-muted"
                  onClick={() => onOpenChange(change.path)}
                >
                  Open in Changes
                  <Icon name="arrow-up-right" size={12} />
                </Button>
              )}
            </div>
            <div className="max-h-72 overflow-auto py-1 font-mono leading-relaxed">
              {change.lines.map((line, at) => (
                <div
                  key={at}
                  className={cn(
                    'whitespace-pre px-2.5',
                    line[0] === '+'
                      ? 'bg-success-subtle text-success'
                      : line[0] === '-'
                        ? 'bg-destructive-subtle text-destructive'
                        : 'text-muted',
                  )}
                >
                  {line || ' '}
                </div>
              ))}
            </div>
            {change.more ? (
              <p className="border-t border-border-subtle px-2.5 py-1 text-muted">
                {change.more} more changed line{change.more === 1 ? '' : 's'}
              </p>
            ) : null}
          </div>
        ))}
      </div>
    );
  }
  const command =
    tool.call.kind === 'execute' &&
    input &&
    typeof input === 'object' &&
    typeof (input as { command?: unknown }).command === 'string'
      ? (input as { command: string }).command
      : undefined;
  return (
    <div className="ml-[22px] mt-1 mb-2 overflow-hidden rounded-default border border-border-subtle bg-hover/40 text-xs">
      {command !== undefined ? (
        <div className="flex min-h-7 items-center gap-2 border-b border-border-subtle bg-surface px-2.5 py-1">
          <span className="min-w-0 flex-1 whitespace-pre-wrap break-all font-mono text-secondary">
            $ {command}
          </span>
          <CopyButton text={() => command} label="Copy command" />
        </div>
      ) : (
        input !== undefined && (
          <div className="border-b border-border-subtle">
            <p className="px-2.5 pt-1.5 text-[11px] font-medium text-muted">Input</p>
            <pre className="max-h-40 overflow-auto whitespace-pre-wrap break-all px-2.5 pb-2 pt-1 font-mono text-secondary">
              {shown(input)}
            </pre>
          </div>
        )
      )}
      {output !== undefined ? (
        <div className="relative">
          {command === undefined && (
            <p className="px-2.5 pt-1.5 text-[11px] font-medium text-muted">Output</p>
          )}
          <pre className="max-h-60 overflow-auto whitespace-pre-wrap break-all px-2.5 py-2 font-mono text-secondary">
            {shown(output)}
          </pre>
        </div>
      ) : (
        <p className="px-2.5 py-1.5 text-muted">No output</p>
      )}
    </div>
  );
}

/** A tool call's title for its line: absolute paths inside the project made relative, Markdown backticks dropped. */
const titleOf = (tool: Tool, relative: (text: string) => string) =>
  relative((tool.call.title ?? '').replace(/`/g, '')) || tool.call.kind || 'Tool';

/** The same tool call, as drawn: its call, result and live state are the same objects. */
const sameTool = (a: Tool, b: Tool) =>
  a.call === b.call && a.result === b.result && a.live === b.live;

/** A tool call's change counts: a button opening the session's changes on its (first) file, when they open. */
function ChangeCounts({ changes, env }: { changes: Change[]; env: TurnEnv }) {
  const counts = sum(changes);
  const open = env.onOpenChange;
  if (!open || !changes[0]) return <Counts {...counts} />;
  const path = changes[0].path;
  const label = `Open ${env.relative(path)} in Changes`;
  return (
    <Tooltip>
      <TooltipTrigger
        render={
          <button
            type="button"
            aria-label={label}
            data-who="tool-changes"
            className="relative z-10 -my-0.5 shrink-0 cursor-pointer rounded-control-inner border-0 bg-transparent px-1 py-0.5 font-[inherit] hover:bg-active"
            onClick={() => open(path)}
          />
        }
      >
        <Counts {...counts} />
      </TooltipTrigger>
      <TooltipContent>{label}</TooltipContent>
    </Tooltip>
  );
}

/** One tool call's line; it opens on its details when it has any, and shows the decision open on it (`decision`) with
 *  its options. Drawn again only when its tool or its decision changed. */
const ToolLine = React.memo(
  function ToolLine({
    tool,
    env,
    shown,
    decision,
  }: {
    tool: Tool;
    env: TurnEnv;
    shown?: Set<string> | undefined;
    decision?: Stored | undefined;
  }) {
    const { relative } = env;
    const [open, setOpen] = React.useState(false);
    const status = statusOf(tool);
    const changes = changesOf(tool);
    const took = between(tool.call.time, tool.result?.time);
    const failed = status === 'failed';
    const running = !isDone(tool);
    const compaction = tool.call.kind === 'compact';
    // An image the turn's answer already shows (Codex's Markdown after its view) does not show twice: its line stays shut.
    const image = viewedImage(tool.call.kind, tool.call.input);
    const openable =
      !(image && shown?.has(image)) &&
      (changes.length > 0 ||
        tool.call.input !== undefined ||
        (tool.result?.output ?? tool.live?.output) !== undefined);
    const title = titleOf(tool, relative);
    const line = (
      <>
        {running ? (
          <Spinner label="Running" className="text-accent" />
        ) : (
          <Icon name={toolIcons[tool.call.kind ?? ''] ?? 'wrench'} size={14} className="shrink-0" />
        )}
        <span
          className={cn(
            'min-w-0 truncate',
            tool.call.kind === 'execute' && 'font-mono text-[12.5px]',
            running && 'text-secondary',
          )}
        >
          {/* A compaction reads as work: how long it runs, then a quiet "Compacted". */}
          {!compaction ? (
            title
          ) : running ? (
            <>
              Compacting for <Elapsed since={tool.call.time} short />
            </>
          ) : failed ? (
            'Compaction failed'
          ) : (
            'Compacted'
          )}
        </span>
        {changes.length > 0 && <ChangeCounts changes={changes} env={env} />}
        {failed && !compaction && <span className="shrink-0 text-xs">· failed</span>}
        {status === 'ended' && <span className="shrink-0 text-xs">· no outcome</span>}
        <span className="ml-auto flex shrink-0 items-center gap-1.5">
          {took !== undefined && (
            <span className="text-xs tabular-nums opacity-0 transition-opacity group-hover/line:opacity-100">
              {duration(took)}
            </span>
          )}
          {openable && (
            <Icon
              name="chevron-right"
              size={14}
              className={cn(
                'opacity-0 transition group-hover/line:opacity-100',
                open && 'rotate-90 opacity-100',
              )}
            />
          )}
        </span>
      </>
    );
    const classes = cn(
      'group/line -mx-1.5 flex border-0 bg-transparent font-[inherit] min-h-[26px] w-[calc(100%+12px)] items-center gap-2 rounded-control px-1.5 text-left text-[13px]',
      failed ? 'text-destructive' : decision ? 'text-secondary' : 'text-muted',
      openable && 'cursor-pointer hover:bg-hover hover:text-secondary',
    );
    // Change counts that open the changes are a button of their own: the line's toggle lies under the line, not around
    // it (a button holds no button).
    const nested = openable && changes.length > 0 && !!env.onOpenChange;
    return (
      <div data-who="tool" data-status={status}>
        {openable && !nested ? (
          <button
            type="button"
            aria-expanded={open}
            className={classes}
            onClick={() => setOpen((was) => !was)}
          >
            {line}
          </button>
        ) : (
          <div className={cn(classes, nested && 'relative')}>
            {nested && (
              <button
                type="button"
                aria-expanded={open}
                aria-label={title}
                className="absolute inset-0 cursor-pointer rounded-control border-0 bg-transparent p-0"
                onClick={() => setOpen((was) => !was)}
              />
            )}
            {line}
          </div>
        )}
        {open && <ToolDetails tool={tool} relative={relative} onOpenChange={env.onOpenChange} />}
        {decision && <PendingDecision event={decision} env={env} title={title} />}
      </div>
    );
  },
  (a, b) =>
    sameTool(a.tool, b.tool) && a.env === b.env && a.shown === b.shown && a.decision === b.decision,
);

/** A run of tool calls of one kind: one line ("Read 3 files"), opening on theirs, and open while a decision waits on
 *  one of them (`decisions`, by position), shown on its line. Drawn again only when one changed. */
const ToolRun = React.memo(
  function ToolRun({
    tools,
    env,
    shown,
    decisions,
  }: {
    tools: Tool[];
    env: TurnEnv;
    shown?: Set<string> | undefined;
    decisions: (Stored | undefined)[];
  }) {
    const { relative } = env;
    const [opened, setOpen] = React.useState(false);
    const open = opened || decisions.some(Boolean);
    const kind = tools[0]!.call.kind ?? '';
    const done = tools.every(isDone);
    const failed = tools.filter((tool) => statusOf(tool) === 'failed').length;
    const counts = sum(tools.flatMap(changesOf));
    return (
      <div data-who="tool-run">
        <button
          type="button"
          aria-expanded={open}
          className="group/line -mx-1.5 flex min-h-[26px] w-[calc(100%+12px)] cursor-pointer border-0 bg-transparent font-[inherit] items-center gap-2 rounded-control px-1.5 text-left text-[13px] text-muted hover:bg-hover hover:text-secondary"
          onClick={() => setOpen((was) => !was)}
        >
          {done ? (
            <Icon name={toolIcons[kind] ?? 'wrench'} size={14} className="shrink-0" />
          ) : (
            <Spinner label="Running" className="text-accent" />
          )}
          <span className="shrink-0 text-secondary">{runLabel(kind, tools.length, done)}</span>
          <span className="min-w-0 truncate text-muted/80">
            {tools
              .map((tool) =>
                titleOf(tool, relative).replace(
                  /^(Read|Edit|Write|Search|Fetch|grep|Grep|Glob)\s+/,
                  '',
                ),
              )
              .join(', ')}
          </span>
          {(counts.added > 0 || counts.removed > 0) && <Counts {...counts} />}
          {failed > 0 && (
            <span className="shrink-0 text-xs text-destructive">· {failed} failed</span>
          )}
          <Icon
            name="chevron-right"
            size={14}
            className={cn(
              'ml-auto shrink-0 opacity-0 transition group-hover/line:opacity-100',
              open && 'rotate-90 opacity-100',
            )}
          />
        </button>
        {open && (
          <div className="ml-[7px] flex flex-col border-l border-border-subtle pl-[14px]">
            {tools.map((tool, i) => (
              <ToolLine
                key={tool.call.seq}
                tool={tool}
                env={env}
                shown={shown}
                decision={decisions[i]}
              />
            ))}
          </div>
        )}
      </div>
    );
  },
  (a, b) =>
    a.env === b.env &&
    a.shown === b.shown &&
    a.tools.length === b.tools.length &&
    a.tools.every((tool, i) => sameTool(tool, b.tools[i]!) && a.decisions[i] === b.decisions[i]),
);

/** A turn as the conversation shows it. */
interface Turn {
  key: number;
  start?: Stored;
  user?: Stored;
  /** Work and system lines, in order. */
  items: Stored[];
  /** The answer: the agent's last words after its last tool call or decision (a turn that ended). */
  answer: Stored[];
  end?: Stored;
  /** The history's page starts inside it (its start on an older page): a turn still, its start unknown. */
  partial?: true;
}
/** Lines that stay in view when a turn's work folds. */
const visible = (event: Stored) =>
  event.type === 'notice' ||
  event.type.startsWith('peer/') ||
  event.type === 'commit' ||
  event.type === 'view' ||
  (event.type === 'turn/end' && event.reason !== 'completed');

/** The events as turns (lines outside any turn, commits and messages between sessions, are turns of their own);
 *  `cut`: older lines remain, so lines before the first `turn/start` are the end of a turn whose start is older. */
export const turnsOf = (events: Stored[], cut = false): Turn[] => {
  const turns: Turn[] = [];
  let turn: Turn | undefined;
  if (cut && events[0] && events[0].type !== 'turn/start') {
    turn = { key: events[0].seq, items: [], answer: [], partial: true };
    turns.push(turn);
  }
  for (const event of events) {
    if (event.type === 'turn/start') {
      turn = { key: event.seq, start: event, items: [], answer: [] };
      turns.push(turn);
    } else if (!turn) {
      // An answer to a decision a cut turn left open (bridge#201), written after its end: drawn with its decision.
      const ended = turns.at(-1);
      if (
        event.type === 'decision/answered' &&
        ended?.end &&
        ended.items.some((each) => each.type === 'decision/asked' && each.id === event.id)
      )
        ended.items.push(event);
      else turns.push({ key: event.seq, items: [event], answer: [] });
    } else if (event.type === 'user/message' && !event.steered && !turn.user && !turn.items.length)
      turn.user = event;
    else if (event.type === 'turn/end') {
      turn.end = event;
      // The answer: the agent's words after its last other line of work.
      let at = turn.items.length;
      // Lines drawn with another one (a tool's result, a decision's answer) do not end the answer: a tool still open at the
      // turn's end gets its result after the agent's last words.
      // Navigation links can follow useful answer text. Keep the calls in the work,
      // but do not let them move that text behind the completed turn's fold.
      const quiet = (line: Stored) =>
        line.type === 'assistant/message' ||
        line.type === 'tool/result' ||
        line.type === 'decision/answered' ||
        visible(line) ||
        (line.type === 'tool/call' &&
          /^(?:mcp__bridge__|bridge · )?bridge_link(?:\s|$)/.test(line.title ?? ''));
      while (at > 0 && quiet(turn.items[at - 1]!)) at--;
      const tail = turn.items.slice(at);
      turn.answer = tail.filter((each) => each.type === 'assistant/message');
      turn.items = [
        ...turn.items.slice(0, at),
        ...tail.filter((each) => each.type !== 'assistant/message'),
      ];
      if (event.reason !== 'completed') turn.items.push(event);
      turn = undefined;
    } else turn.items.push(event);
  }
  return turns;
};

export interface ConversationProps {
  events: Stored[];
  live: Live | null;
  /** The ids of the decisions a turn Bridge cut left open (the session's `openDecisions`, bridge#201): open on the last
   *  turn, answered from its rows. */
  left?: readonly string[];
  /** Older lines than `events` remain (the history comes in pages): the first lines may end a turn begun earlier. */
  cut?: boolean;
  /** The project's folder: paths inside it show relative. */
  folder?: string | undefined;
  /** The workspace's slug: the host serves the images and videos the agent shows from there. */
  workspace?: string;
  /** Puts `text` in the composer. */
  onReuse: (text: string) => void;
  /** Opens the session's changes. */
  onReview: () => void;
  /** The routes a view the agent showed reads and writes (research-036). */
  viewTools?: ViewTools;
  /** Draws a plugin component a view calls, through its plugin (research-036 P2). */
  renderComponent?: ViewComponentRenderer | undefined;
  /** Answers open decision `event` with `option` (`null`: dismissed), from its row; without it, the row offers none. */
  onAnswer?: ((event: Stored, option: Answer) => Promise<void>) | undefined;
  /** Hears whether the row of the open decision `seq` is in view, `undefined` once it is no longer drawn: the composer
   *  points to a row out of view. */
  onDecisionShown?: ((seq: number, shown: boolean | undefined) => void) | undefined;
  /** Opens the session's changes on `path` (a tool call's change counts); without it, the counts open nothing. */
  onOpenChange?: ((path: string) => void) | undefined;
  /** The session's lineage (./children.tsx): its children's cards, its parent; without it, none drawn. */
  lineage?: Lineage | undefined;
  /** Its links to files of its folder open in the code editor (none: plain links). */
  openFile?: FileOpener | undefined;
}

/** No child delegated in a turn: the same array each render. */
const NO_CARDS: readonly Delegation[] = [];
/** No sub-agent started in a turn: the same array each render. */
const NO_SUBAGENTS: readonly SubagentCard[] = [];
/** `live` without its sub-agents' tool calls (theirs show in their own view), the same object while it has none. */
const ownLive = (live: Live | null): Live | null => {
  if (!live || !Object.values(live.tools).some((each) => each.subagent !== undefined)) return live;
  return {
    ...live,
    tools: Object.fromEntries(
      Object.entries(live.tools).filter(([, each]) => each.subagent === undefined),
    ),
  };
};
/** No decision left open by a cut turn: the same array each render, so no turn draws again for it. */
export const NO_DECISIONS: readonly string[] = [];

/** The decisions of the last turn by `seq`, with their answer, and which are still open: the running turn's (`live`), or
 *  those a turn Bridge cut left open (`left`, their ids, bridge#201). */
export const decisionsOf = (
  events: Stored[],
  live: Live | null,
  left: readonly string[] = NO_DECISIONS,
) => {
  const answers = new Map<number, Stored>();
  const askedNow = new Map<string, number>();
  for (const each of events) {
    if (each.type === 'turn/start') askedNow.clear();
    else if (each.type === 'decision/asked') askedNow.set(each.id ?? '', each.seq);
    else if (each.type === 'decision/answered' && askedNow.has(each.id ?? ''))
      answers.set(askedNow.get(each.id ?? '')!, each);
  }
  const isOpen = (event: Stored) =>
    !answers.has(event.seq) &&
    askedNow.get(event.id ?? '') === event.seq &&
    (!!live?.decisions.some((each) => each.id === event.id) || left.includes(event.id ?? ''));
  const open = events.filter((event) => event.type === 'decision/asked' && isOpen(event));
  return { answers, isOpen, open };
};

export function Conversation({
  events,
  live,
  left = NO_DECISIONS,
  cut = false,
  folder,
  workspace,
  onReuse,
  onReview,
  viewTools,
  renderComponent,
  onAnswer,
  onDecisionShown,
  onOpenChange,
  lineage,
  openFile,
}: ConversationProps) {
  /** Turns opened or folded by the user, by key: otherwise a completed turn is folded. */
  const [unfolded, setUnfolded] = React.useState<Record<number, boolean>>({});
  const onFold = React.useCallback(
    (key: number, open: boolean) => setUnfolded((was) => ({ ...was, [key]: open })),
    [],
  );
  const origins = useMediaOrigins();
  // The callers' handlers, called at their latest: a new one each render redraws no turn.
  const handlers = React.useRef({ onReuse, onReview, onAnswer, onDecisionShown, onOpenChange });
  React.useLayoutEffect(() => {
    handlers.current = { onReuse, onReview, onAnswer, onDecisionShown, onOpenChange };
  });
  const answers = !!onAnswer;
  const opens = !!onOpenChange;
  const env = React.useMemo<TurnEnv>(
    () => ({
      relative: (text: string) =>
        folder ? text.split(`${folder.replace(/[\\/]$/, '')}/`).join('') : text,
      onReuse: (text) => handlers.current.onReuse(text),
      onReview: () => handlers.current.onReview(),
      onAnswer: answers
        ? (event, option) => handlers.current.onAnswer?.(event, option) ?? Promise.resolve()
        : undefined,
      onDecisionShown: (seq, shown) => handlers.current.onDecisionShown?.(seq, shown),
      onOpenChange: opens ? (path) => handlers.current.onOpenChange?.(path) : undefined,
      viewTools,
      renderComponent,
    }),
    [folder, viewTools, renderComponent, answers, opens],
  );
  // Drawn from the stored lines only: a streamed delta or a tool's live update reuses them, and redraws only the
  // running turn (`TurnView`, memoized).
  const { turns, results, frozenOf } = React.useMemo(() => {
    const frozenOf = new Map<number, Stored>();
    for (const each of events)
      if (each.type === 'view_frozen' && typeof each.view === 'number')
        frozenOf.set(each.view, each);
    return {
      // A sub-agent's lines are its own view's (bridge#212 S8): its card stands for them here.
      turns: turnsOf(
        events.some((each) => each.subagent !== undefined)
          ? events.filter((each) => each.subagent === undefined)
          : events,
        cut,
      ),
      results: new Map(
        events.filter((each) => each.type === 'tool/result').map((each) => [each.id, each]),
      ),
      frozenOf,
    };
  }, [events, cut]);
  const subagents = React.useMemo(() => subagentsByTurn(turns, events), [turns, events]);
  // The same opener while its folder and label stay: a new one would redraw every link at each streamed delta.
  const openNow = React.useRef(openFile);
  openNow.current = openFile;
  const opener = React.useMemo(
    () =>
      openFile?.folder && openFile.label
        ? {
            folder: openFile.folder,
            label: openFile.label,
            open: (target: FileTarget) => openNow.current?.open(target),
            refresh: () => openNow.current?.refresh?.(),
            ...(openFile.unavailable && { unavailable: true }),
          }
        : null,
    [openFile?.folder, openFile?.label, openFile?.unavailable],
  );
  const shownLive = React.useMemo(() => ownLive(live), [live]);
  const last = turns.findLast((turn) => turn.start || turn.partial);
  // Each turn's children (bridge#212): the delegations its calls made, else those made while it was the last started.
  const delegations = lineage?.delegations ?? NO_CARDS;
  const cards = React.useMemo(
    () => cardsByTurn(turns, delegations, results, cut),
    [turns, delegations, results, cut],
  );
  return (
    <LineageContext.Provider value={lineage ?? null}>
      <FileLinks.Provider value={opener}>
      <MediaWorkspace.Provider value={workspace}>
        <MediaOrigins.Provider value={origins}>
          <ol
            aria-label="Conversation"
            className="mx-auto box-border flex w-full max-w-[816px] flex-col px-7 pb-6 pt-6"
          >
            {turns.map((turn) => (
              <TurnView
                key={turn.key}
                turn={turn}
                results={results}
                frozenOf={frozenOf}
                live={turn === last ? shownLive : null}
                left={turn === last ? left : NO_DECISIONS}
                isLast={turn === last}
                unfolded={unfolded[turn.key]}
                onFold={onFold}
                env={env}
                cards={cards.get(turn.key) ?? NO_CARDS}
                subagents={subagents.get(turn.key) ?? NO_SUBAGENTS}
              />
            ))}
          </ol>
        </MediaOrigins.Provider>
      </MediaWorkspace.Provider>
      </FileLinks.Provider>
    </LineageContext.Provider>
  );
}

/** What every turn draws with, the same object while its inputs stay. */
interface TurnEnv {
  relative: (text: string) => string;
  onReuse: (text: string) => void;
  onReview: () => void;
  onAnswer: ((event: Stored, option: Answer) => Promise<void>) | undefined;
  onDecisionShown: (seq: number, shown: boolean | undefined) => void;
  onOpenChange: ((path: string) => void) | undefined;
  viewTools?: ViewTools | undefined;
  renderComponent?: ViewComponentRenderer | undefined;
}
interface TurnProps {
  turn: Turn;
  /** Every `tool/result` by its tool's id, and every `view_frozen` by the view it freezes (a later turn's too). */
  results: Map<string | undefined, Stored>;
  frozenOf: Map<number, Stored>;
  /** The running turn's in-flight part: the last turn's only (null for the others). */
  live: Live | null;
  /** The decisions a cut turn left open: the last turn's only. */
  left: readonly string[];
  isLast: boolean;
  /** Opened (true) or folded (false) by the user. */
  unfolded: boolean | undefined;
  onFold: (key: number, open: boolean) => void;
  env: TurnEnv;
  /** The children the turn delegated (./children.tsx): their cards, their calls' rows hidden. */
  cards: readonly Delegation[];
  /** The sub-agents its agent started (./subagents.tsx): their cards, the calls that started them hidden. */
  subagents: readonly SubagentCard[];
}
const sameLines = (a: Stored[], b: Stored[]) =>
  a === b || (a.length === b.length && a.every((line, i) => line === b[i]));
/** A turn draws again only when what it shows changed: its lines (the same objects), its tools' results, its views'
 *  freezing, the live part (the last turn's), its fold. */
const sameTurn = (a: TurnProps, b: TurnProps) =>
  a.live === b.live &&
  a.left === b.left &&
  a.isLast === b.isLast &&
  a.unfolded === b.unfolded &&
  a.onFold === b.onFold &&
  a.env === b.env &&
  sameCards(a.cards, b.cards) &&
  sameSubagents(a.subagents, b.subagents) &&
  (a.turn === b.turn ||
    (a.turn.key === b.turn.key &&
      a.turn.start === b.turn.start &&
      a.turn.partial === b.turn.partial &&
      a.turn.user === b.turn.user &&
      a.turn.end === b.turn.end &&
      sameLines(a.turn.items, b.turn.items) &&
      sameLines(a.turn.answer, b.turn.answer))) &&
  b.turn.items.every(
    (line) =>
      (line.type !== 'tool/call' ||
        a.results === b.results ||
        a.results.get(line.id) === b.results.get(line.id)) &&
      (line.type !== 'view' ||
        a.frozenOf === b.frozenOf ||
        a.frozenOf.get(line.seq) === b.frozenOf.get(line.seq)),
  );

/** One turn of the conversation (or a line outside any turn). */
const TurnView = React.memo(function TurnView({
  turn,
  results,
  frozenOf,
  live,
  left,
  isLast,
  unfolded,
  onFold,
  env,
  cards,
  subagents,
}: TurnProps) {
  const { relative, onReuse, onReview, viewTools, renderComponent } = env;
  // A child's `delegate_session` call is its card (bridge#212): its row and its result are not drawn; so is the call
  // that started a sub-agent (S8).
  const hidden = hiddenCalls(turn.items, cards, results);
  for (const each of subagents) if (each.tool !== undefined) hidden.add(each.tool);
  const items = hidden.size
    ? turn.items.filter(
        (each) =>
          !((each.type === 'tool/call' || each.type === 'tool/result') && hidden.has(each.id)),
      )
    : turn.items;
  // Its decisions: asked and answered in the turn (the open ones, the last turn's, with the live part or left by a cut).
  const { answers, isOpen } = decisionsOf(turn.items, live, left);
  // An open decision about one of the turn's tool calls shows on that call's row, by the call's id.
  const calls = new Set(turn.items.flatMap((each) => (each.type === 'tool/call' ? [each.id] : [])));
  const pendingOn = new Map<string, Stored>();
  for (const each of turn.items)
    if (each.type === 'decision/asked' && each.tool && calls.has(each.tool) && isOpen(each))
      pendingOn.set(each.tool, each);
  /** The view the agent is writing, drawn after the running turn's text (research-036 streaming). */
  const draftView =
    live?.view && viewTools ? (
      <ViewLine
        seq={live.seq}
        program={live.view.program}
        {...(live.view.title !== undefined && { title: live.view.title })}
        streaming
        dynamic
        tools={viewTools}
        renderComponent={renderComponent}
        onAssistant={onReuse}
      />
    ) : null;
  /** The images the turn's words show (Markdown), whose tool lines stay shut: the same set while its words stay. */
  const words = [...turn.items, ...turn.answer]
    .flatMap((each) => (each.type === 'assistant/message' && each.text ? [each.text] : []))
    .join('\n');
  const shown = React.useMemo(() => markdownImages(words), [words]);

  const decisionLine = (event: Stored) => {
    const answered = answers.get(event.seq);
    const state = isOpen(event)
      ? 'open'
      : !answered || answered.reason === 'expired'
        ? 'expired'
        : 'answered';
    if (state === 'open')
      // On its tool call's row, else on its own.
      return pendingOn.get(event.tool ?? '') === event ? null : (
        <PendingDecision key={event.seq} event={event} env={env} />
      );
    const outcome =
      state === 'expired'
        ? 'Expired'
        : answered!.answers?.length
          ? answerSummary(askedOf(event), { answers: answered!.answers })
          : answered!.option == null
            ? 'Dismissed'
            : (event.options?.find((option) => option.id === answered!.option)?.label ??
              answered!.option);
    const allowed =
      state === 'answered' &&
      event.options?.find((option) => option.id === answered!.option)?.kind === 'allow';
    return (
      <p
        key={event.seq}
        data-who="decision"
        data-state={state}
        className="flex min-h-[26px] min-w-0 items-center gap-2 text-[13px] text-muted"
      >
        <Icon
          name={allowed ? 'shield-check' : 'shield-x'}
          size={14}
          className={cn('shrink-0', allowed && 'text-success')}
        />
        <span data-title className="truncate">
          {event.title}
        </span>
        <span aria-hidden="true">·</span>
        <span data-outcome className="max-w-[60%] shrink-0 truncate font-medium text-secondary">
          {outcome}
        </span>
      </p>
    );
  };
  const systemLine = (event: Stored, who: string, content: React.ReactNode) => (
    <p key={event.seq} data-who={who} className="py-1 text-center text-xs text-muted">
      {content}
    </p>
  );
  const peerLine = (event: Stored) => {
    if (event.type === 'peer/answer') {
      const verdict =
        event.by === 'user'
          ? event.verdict === 'no'
            ? 'Stop'
            : 'Force continue'
          : (verdicts[event.verdict as keyof typeof verdicts] ?? event.verdict);
      return systemLine(
        event,
        'peer',
        `${event.question ? `Answer to “${oneLine(event.question, 80)}”` : 'Answer'}: ${verdict}${event.text ? ` · ${event.text}` : ''} (${event.by === 'user' ? "by you, in its agent's place" : 'by its agent'})`,
      );
    }
    const asking = event.kind === 'ask';
    const sent = event.type === 'peer/sent';
    return (
      <div
        key={event.seq}
        data-who="peer"
        className="my-1 rounded-dialog border border-border p-3 text-sm"
      >
        <p className="text-xs font-medium text-muted">
          {sent
            ? `${asking ? 'Asked' : 'Told'} ${event.title}`
            : `${asking ? 'Question' : 'Note'} from ${event.title}`}
        </p>
        <p className="mt-0.5 whitespace-pre-wrap text-foreground">{event.text}</p>
      </div>
    );
  };
  /** A line that is not a tool call. */
  // A `view_frozen` line names a view it freezes (research-036 P5); the view line itself is drawn, with its snapshot.
  const lineOf = (event: Stored, quiet: boolean) => {
    if (event.type === 'assistant/message') {
      return (
        <div
          key={event.seq}
          data-who="assistant"
          data-interrupted={event.interrupted || undefined}
          className={quiet ? 'my-1.5' : undefined}
        >
          <Reply text={event.text ?? ''} quiet={quiet} />
          {event.interrupted && (
            <span className="mt-1 block text-xs italic text-muted"> (interrupted)</span>
          )}
        </div>
      );
    }
    if (event.type === 'decision/asked') return decisionLine(event);
    if (event.type === 'notice') return systemLine(event, 'notice', event.text);
    // Every version of a view stays where it is in the session (research-036 P5).
    if (event.type === 'view' && event.program && viewTools) {
      const frozen = frozenOf.get(event.seq);
      const snapshot = event.snapshot ?? frozen?.snapshot;
      const at = event.at ?? frozen?.at;
      return (
        <ViewLine
          key={event.seq}
          seq={event.seq}
          program={event.program}
          components={event.components}
          renderComponent={renderComponent}
          tools={viewTools}
          onAssistant={onReuse}
          snapshot={snapshot}
          at={at}
          dynamic={event.dynamic === true}
          {...(event.title !== undefined && { title: event.title })}
          {...(event.base !== undefined && { base: event.base })}
        />
      );
    }
    if (event.type === 'mode/changed')
      return (
        <p
          key={event.seq}
          data-who="mode"
          className="flex min-h-[26px] items-center gap-2 text-[13px] text-muted"
        >
          <Icon name="shield" size={14} />
          Permissions: {event.name ?? event.mode}
          {optionOn(event.options, 'plan') && ' · Plan'}
          {optionOn(event.options, 'auto') && ' · Auto'}
        </p>
      );
    if (event.type === 'effort/changed')
      return (
        <p
          key={event.seq}
          data-who="effort"
          className="flex min-h-[26px] items-center gap-2 text-[13px] text-muted"
        >
          <Icon name="brain" size={14} />
          Reasoning: {event.name ?? event.effort}
        </p>
      );
    if (event.type.startsWith('peer/')) return peerLine(event);
    if (event.type === 'commit')
      return systemLine(
        event,
        'commit',
        `Committed ${event.sha?.slice(0, 7)}: ${event.message?.split('\n')[0]} (${event.files?.length ?? 0} file${event.files?.length === 1 ? '' : 's'})`,
      );
    if (event.type === 'turn/end' && event.reason !== 'completed')
      return systemLine(
        event,
        'end',
        `Turn ${event.reason}${event.message ? `: ${event.message}` : ''}`,
      );
    return null;
  };
  /** A message as its turn shows it: the user's, a scheduled task's, Bridge's (its children's results and questions,
   *  another session's words). */
  const messageOf = (event: Stored) =>
    event.from === 'bridge' ? (
      event.delegations?.length || event.questions?.length ? (
        <ChildrenMessage
          time={event.time}
          text={event.text ?? ''}
          delegations={event.delegations}
          questions={event.questions as ChildQuestion[] | undefined}
        />
      ) : (
        <BridgeMessage event={event} />
      )
    ) : event.scheduled ? (
      <AutomationMessage event={event} />
    ) : (
      <UserMessage event={event} onReuse={onReuse} />
    );
  /** A message steered into a running turn (bridge#212 S6): in place, saying so. */
  const steeredLine = (event: Stored) => (
    <div key={event.seq} data-steered={event.seq} className="my-2 flex flex-col">
      {messageOf(event)}
      <span className="self-end text-[11px] text-muted">Sent into the running turn</span>
    </div>
  );
  /** A turn's work: tool calls in runs, the rest line by line. */
  const work = (items: Stored[], quiet: boolean, shown?: Set<string>) => {
    const out: React.ReactNode[] = [];
    let run: Tool[] = [];
    const flush = () => {
      // A decision on a call keeps its run as it is (its rows keep their state): the run opens on it.
      const decisions = run.map((tool) => pendingOn.get(tool.call.id ?? ''));
      if (run.length > 1)
        out.push(
          <ToolRun
            key={run[0]!.call.seq}
            tools={run}
            env={env}
            shown={shown}
            decisions={decisions}
          />,
        );
      else if (run.length === 1)
        out.push(
          <ToolLine
            key={run[0]!.call.seq}
            tool={run[0]!}
            env={env}
            shown={shown}
            decision={decisions[0]}
          />,
        );
      run = [];
    };
    for (const event of items) {
      // A message steered into the turn, where it entered it.
      if (event.type === 'user/message' && event.steered) {
        flush();
        out.push(steeredLine(event));
        continue;
      }
      if (event.type === 'tool/call') {
        const tool: Tool = {
          call: event,
          result: results.get(event.id),
          live: live?.tools[event.id ?? ''],
        };
        if (run.length && (run[0]!.call.kind ?? '') !== (event.kind ?? '')) flush();
        run.push(tool);
        continue;
      }
      if (
        event.type === 'tool/result' ||
        event.type === 'decision/answered' ||
        event.type === 'user/message'
      )
        continue;
      flush();
      const line = lineOf(event, quiet);
      if (line) out.push(line);
    }
    flush();
    return out;
  };

  if (!turn.start && !turn.partial)
    return (
      <li key={turn.key} className="list-none">
        {work(items, false)}
      </li>
    );
  const running = isLast && !turn.end && !!live;
  // A compaction is not an action of the agent's.
  const tools = items.filter((each) => each.type === 'tool/call' && each.kind !== 'compact');
  /** What the running turn does now: its newest tool call. */
  const newest = running ? items.findLast((each) => each.type === 'tool/call') : undefined;
  const workItems = items.filter((each) => !visible(each));
  const kept = items.filter(visible);
  const hasWork = workItems.length > 0 || running;
  const foldable = !!turn.end && turn.end.reason === 'completed' && workItems.length > 0;
  const open = !foldable || (unfolded ?? false);
  const changes = tools.flatMap((call) =>
    results.get(call.id)?.status === 'failed' ? [] : (results.get(call.id)?.changes ?? []),
  );
  const byFile = new Map<string, { added: number; removed: number }>();
  for (const change of changes) {
    const was = byFile.get(change.path) ?? { added: 0, removed: 0 };
    byFile.set(change.path, {
      added: was.added + change.added,
      removed: was.removed + change.removed,
    });
  }
  const total = sum(changes);
  const took = between(turn.start?.time, turn.end?.time);
  const answerText = turn.answer.map((each) => each.text ?? '').join('\n\n');
  return (
    <li
      key={turn.key}
      data-turn={turn.key}
      data-partial={turn.partial}
      className="group/turn mb-6 flex list-none flex-col"
    >
      {turn.user && messageOf(turn.user)}
      {hasWork && (
        <div className="mt-3 flex flex-col">
          {foldable ? (
            <button
              type="button"
              aria-expanded={open}
              data-who="fold"
              className="group/fold mb-2 flex h-8 cursor-pointer items-center gap-2 border-0 border-b border-border-subtle bg-transparent p-0 text-left font-[inherit] text-[13px] text-muted hover:text-secondary"
              onClick={() => onFold(turn.key, !open)}
            >
              <Icon
                name="chevron-right"
                size={14}
                className={cn('shrink-0 transition-transform', open && 'rotate-90')}
              />
              <span>{took !== undefined ? `Worked for ${duration(took)}` : 'Worked'}</span>
              <span className="flex min-w-0 items-center gap-2 truncate text-xs text-muted/80">
                {tools.length > 0 && (
                  <span>
                    {tools.length} action{tools.length === 1 ? '' : 's'}
                  </span>
                )}
                {byFile.size > 0 && (
                  <>
                    <span aria-hidden="true">·</span>
                    <span>
                      {byFile.size} file{byFile.size === 1 ? '' : 's'}
                    </span>
                    <Counts {...total} />
                  </>
                )}
              </span>
              <span
                title={fullDate(turn.start?.time)}
                className="ml-auto shrink-0 text-xs tabular-nums opacity-0 transition-opacity group-hover/fold:opacity-100"
              >
                {clock(turn.start?.time)}
                {turn.end?.time ? ` → ${clock(turn.end.time)}` : ''}
              </span>
            </button>
          ) : (
            running && (
              <div
                data-who="working"
                className="mb-2 flex h-8 items-center gap-2 border-b border-border-subtle text-[13px] text-secondary"
              >
                <Spinner label="Working" className="text-accent" />
                <span className="shrink-0">
                  Working for <Elapsed since={turn.start?.time} />
                </span>
                {newest && (
                  <>
                    <span aria-hidden="true" className="text-muted">
                      ·
                    </span>
                    <span
                      data-who="activity"
                      className={cn(
                        'min-w-0 truncate text-muted',
                        newest.kind === 'execute' && 'font-mono text-[12.5px]',
                      )}
                    >
                      {newest.kind === 'compact'
                        ? 'Compacting context'
                        : titleOf({ call: newest }, relative)}
                    </span>
                  </>
                )}
                {tools.length > 0 && (
                  <span className="ml-auto shrink-0 text-xs text-muted">
                    {tools.length} action{tools.length === 1 ? '' : 's'}
                  </span>
                )}
              </div>
            )
          )}
          {open && work(workItems, true, shown)}
          {/* Folded, the messages steered into it stay in view (bridge#212 S6). */}
          {!open &&
            workItems
              .filter((each) => each.type === 'user/message' && each.steered)
              .map(steeredLine)}
          {running && live?.thought && <Thought text={live.thought} answered={!!live.text} />}
        </div>
      )}
      {/* The children it delegated, in view whether its work is folded or not. */}
      <ChildCards delegations={cards} />
      <SubagentCards cards={subagents} results={results} running={running} />
      {kept.filter((event) => event.type !== 'turn/end').map((event) => lineOf(event, false))}
      {turn.answer.length > 0 && (
        <div className="mt-2 flex flex-col gap-3">
          {turn.answer.map((event) => lineOf(event, false))}
        </div>
      )}
      {kept.filter((event) => event.type === 'turn/end').map((event) => lineOf(event, false))}
      {running && live?.text && (
        <div data-who="assistant" aria-busy="true" className="mt-2">
          <Reply text={live.text} streaming />
        </div>
      )}
      {running && draftView}
      {turn.end && byFile.size > 0 && (
        <div
          data-who="files"
          className="mt-3 overflow-hidden rounded-dialog border border-border-subtle"
        >
          <div className="flex h-9 items-center gap-2 border-b border-border-subtle bg-surface pl-3 pr-1.5 text-[12.5px] text-secondary">
            <Icon name="files" size={14} className="text-muted" />
            {byFile.size} file{byFile.size === 1 ? '' : 's'} changed <Counts {...total} />
            <span className="flex-1" />
            <Button size="sm" onClick={onReview}>
              Review changes
            </Button>
          </div>
          {[...byFile].map(([path, counts]) => (
            <div
              key={path}
              className="flex h-7 items-center gap-2 px-3 text-[12.5px] text-secondary"
            >
              <Icon name="pen-line" size={13} className="shrink-0 text-muted" />
              <span className="min-w-0 truncate font-mono text-xs">{relative(path)}</span>
              <span className="flex-1" />
              <Counts {...counts} />
            </div>
          ))}
        </div>
      )}
      {turn.end && (turn.answer.length > 0 || took !== undefined) && (
        <div
          data-who="actions"
          className={cn(
            'mt-2 flex items-center gap-0.5 text-xs text-muted transition-opacity',
            !isLast && 'opacity-0 group-hover/turn:opacity-100 focus-within:opacity-100',
          )}
        >
          {turn.answer.length > 0 && <CopyButton text={() => answerText} label="Copy answer" />}
          {turn.answer.length > 0 && <span className="mx-1.5 h-3.5 w-px bg-border" />}
          <span className="tabular-nums" title={fullDate(turn.end.time)}>
            {[clock(turn.end.time), took !== undefined && duration(took)]
              .filter(Boolean)
              .join(' · ')}
          </span>
        </div>
      )}
    </li>
  );
}, sameTurn);

/** The label of open decision `event`: a question when its driver says so (or it asks questions, or none of its options
 *  allows or denies), else a permission. */
/** The option Enter picks: the first that allows this request only, never a lasting grant (`scope: 'always'`, plugins#171). */
const primaryAllow = (options: Stored['options']) =>
  options?.find((option) => option.kind === 'allow' && option.scope !== 'always');
const decisionLabel = (event: Stored) => {
  const asked = askedOf(event);
  return (
    asked.kind !== undefined || asked.questions
      ? isQuestion(asked)
      : !event.options?.some((option) => option.kind === 'allow' || option.kind === 'deny')
  )
    ? 'Answer needed'
    : 'Permission needed';
};

/** An open decision in the timeline: what is asked, its countdown, Dismiss and its options (the allow one focused when
 *  nothing else is); Escape picks its deny option. On its tool call's row (`title`: that call's, which the decision's
 *  repeats only for a screen reader when they are the same), else on its own. Says whether it is in view
 *  (`onDecisionShown`): drawn, it is taken as in view until the browser says otherwise. */
const PendingDecision = React.memo(function PendingDecision({
  event,
  env: { relative, onAnswer, onDecisionShown },
  title,
}: {
  event: Stored;
  env: TurnEnv;
  title?: string;
}) {
  const [busy, setBusy] = React.useState(false);
  const section = React.useRef<HTMLElement>(null);
  const actions = React.useRef<HTMLDivElement>(null);
  const primary = React.useRef<HTMLButtonElement>(null);
  React.useEffect(() => {
    const active = document.activeElement;
    if (!active || active === document.body) primary.current?.focus({ preventScroll: true });
  }, [event.seq]);
  React.useLayoutEffect(() => {
    // In view: its options all in view (its title alone at the bottom is not).
    const element = actions.current ?? section.current;
    onDecisionShown(event.seq, true);
    const observer =
      element && typeof IntersectionObserver !== 'undefined'
        ? new IntersectionObserver(
            ([entry]) => {
              if (entry)
                onDecisionShown(event.seq, entry.isIntersecting && entry.intersectionRatio >= 0.99);
            },
            { threshold: [0, 1] },
          )
        : undefined;
    if (element) observer?.observe(element);
    return () => {
      observer?.disconnect();
      onDecisionShown(event.seq, undefined);
    };
  }, [event.seq, onDecisionShown]);
  const answer = (option: Answer) => {
    if (!onAnswer) return;
    setBusy(true);
    onAnswer(event, option)
      .finally(() => setBusy(false))
      .catch((cause: unknown) => console.error('sessions: the answer failed', cause));
  };
  const asked = relative(event.title ?? '');
  const deny = event.options?.find((option) => option.kind === 'deny');
  const allow = primaryAllow(event.options);
  const label = decisionLabel(event);
  // A question is read whole (its options mean nothing without it); a permission's title says what the agent wants, two lines at most.
  const question = label === 'Answer needed';
  // Its questions (an agent's question tool), each drawn with its own words: no title above them.
  const questions = questionsAsked(event);
  return (
    <section
      ref={section}
      aria-label={label}
      data-who="decision"
      data-state="open"
      data-decision-row={event.seq}
      className={cn(
        'my-1 rounded-default border border-warning/40 bg-warning-subtle px-3 pb-2.5 pt-2 text-[13px]',
        title !== undefined && 'ml-[22px]',
      )}
      onKeyDown={(keyEvent) => {
        if (keyEvent.key === 'Escape' && deny && !busy && onAnswer) {
          keyEvent.preventDefault();
          answer(deny.id);
        }
      }}
    >
      <div className="flex min-w-0 items-center gap-2">
        <span className="size-1.5 shrink-0 rounded-full bg-warning" />
        <span className="shrink-0 font-medium text-warning-text">{label}</span>
        {!question && (
          <span
            data-title
            className={cn(
              'line-clamp-2 min-w-0 break-words text-secondary',
              title !== undefined && asked === title && 'sr-only',
            )}
          >
            {asked}
          </span>
        )}
        <span className="flex-1" />
        {event.expiresAt && <Countdown expiresAt={event.expiresAt} />}
      </div>
      {question && !questions && (
        <p data-title className="mt-1 whitespace-pre-wrap break-words text-foreground">
          {asked}
        </p>
      )}
      {questions && !onAnswer && (
        <ul data-title className="mt-1 list-none p-0 text-foreground">
          {questions.map((each) => (
            <li key={each.id} className="whitespace-pre-wrap break-words">
              {each.header ? `${each.header}: ` : ''}
              {each.question}
            </li>
          ))}
        </ul>
      )}
      {questions && onAnswer && (
        <div ref={actions}>
          <DecisionQuestions
            questions={questions}
            busy={busy}
            onAnswer={answer}
            primary={primary}
            draft={event.id}
          />
        </div>
      )}
      {onAnswer && !questions && (
        <div ref={actions} className="mt-2 flex flex-wrap items-center justify-end gap-2">
          <span className="mr-auto hidden text-xs text-muted sm:inline">
            {allow && '↵ allow'}
            {allow && deny && ' · '}
            {deny && 'Esc deny'}
          </span>
          <Button size="sm" variant="ghost" disabled={busy} onClick={() => answer(null)}>
            Dismiss
          </Button>
          {event.options?.map((option) => (
            <Button
              key={option.id}
              ref={option === allow ? primary : undefined}
              data-primary={option === allow || undefined}
              data-option
              data-lasting={(option.kind === 'allow' && option.scope === 'always') || undefined}
              size="sm"
              variant={option === allow ? 'primary' : 'outline'}
              disabled={busy}
              onClick={() => answer(option.id)}
            >
              {option.label}
            </Button>
          ))}
        </div>
      )}
    </section>
  );
});

/** The running turn's thought: its last paragraph in view, all of it on a click. */
function Thought({ text, answered }: { text: string; answered: boolean }) {
  const [all, setAll] = React.useState(false);
  const paragraphs = text
    .split(/\n\s*\n/)
    .map((each) => each.trim())
    .filter(Boolean);
  return (
    <button
      type="button"
      aria-expanded={all}
      className="my-1.5 flex cursor-pointer gap-2 font-[inherit] rounded-default border border-border-subtle bg-surface px-3 py-2 text-left text-[13px] text-secondary"
      onClick={() => setAll((was) => !was)}
    >
      <Icon name="brain" size={14} className="mt-0.5 shrink-0 text-muted" />
      <span className="sr-only">{answered ? 'Thought' : 'Thinking'}</span>
      <span
        data-who="thought"
        className={cn('min-w-0 whitespace-pre-wrap', !all && 'line-clamp-3')}
      >
        {all ? text : (paragraphs.at(-1) ?? text)}
      </span>
    </button>
  );
}

/** The user's message: its images (`AttachedImages`), then a bubble, folded past about ten lines; its time, Copy and
 *  Reuse on hover. */
/** A message's text cut around the mentions the composer writes (plugins#239): `@session:<id>`, `@path` with a `/`
 *  or a `.` in it (`@someone`, `@README` stay text), and `@"path"` for one with a blank; the punctuation after one is
 *  the text's. */
export const mentionParts = (text: string) => {
  const parts: (string | { kind: 'file' | 'session'; value: string })[] = [];
  let at = 0;
  for (const found of text.matchAll(/(?<=^|\s)@(?:"([^"\n]+)"|(\S+?))(?=[.,;:!?)]*(?:\s|$))/g)) {
    const quoted = found[1];
    const value = quoted ?? found[2]!;
    const session = quoted ? undefined : /^session:([\w-]+)$/.exec(value)?.[1];
    if (!quoted && !session && !/[/.]/.test(value)) continue;
    if (found.index > at) parts.push(text.slice(at, found.index));
    parts.push(session ? { kind: 'session', value: session } : { kind: 'file', value });
    at = found.index + found[0].length;
  }
  if (at < text.length) parts.push(text.slice(at));
  return parts;
};

/** A message's text, its mentions as chips. */
function MentionText({ text }: { text: string }) {
  return mentionParts(text).map((part, index) =>
    typeof part === 'string' ? (
      part
    ) : (
      <span
        key={index}
        data-mention={part.kind}
        title={part.kind === 'session' ? `Session ${part.value}` : part.value}
        className="inline-flex max-w-full items-center gap-1 rounded-control bg-surface px-1 align-bottom text-[13px]"
      >
        <Icon
          name={part.kind === 'session' ? 'message-square' : 'file'}
          size={12}
          className="shrink-0 text-muted"
        />
        <span className="truncate">{part.value}</span>
      </span>
    ),
  );
}

const UserMessage = React.memo(function UserMessage({
  event,
  onReuse,
}: {
  event: Stored;
  onReuse: (text: string) => void;
}) {
  const [full, setFull] = React.useState(false);
  const [long, setLong] = React.useState(false);
  const bubble = React.useRef<HTMLDivElement>(null);
  React.useLayoutEffect(() => {
    const element = bubble.current;
    if (element) setLong(element.scrollHeight > element.clientHeight + 4);
  }, [event.text]);
  // A child's task (bridge#212): its prompt, without Bridge's block before it, under whom it came from.
  const task = taskOf(event.text);
  const text = task?.text ?? event.text;
  return (
    <div className="group/user flex flex-col items-end pl-12">
      {task && <TaskFrom kind={task.kind} role={task.role} sender={event.sender} />}
      {event.attachments?.length ? (
        <div className="flex w-full justify-end">
          <AttachedImages images={event.attachments} />
        </div>
      ) : null}
      {event.text ? (
        <div
          data-who="user"
          ref={bubble}
          className={cn(
            'relative max-w-full whitespace-pre-wrap break-words rounded-2xl rounded-br-md bg-accent-subtle px-4 py-2 text-sm text-foreground',
            !full && 'max-h-60 overflow-hidden',
          )}
        >
          <MentionText text={text ?? ''} />
        </div>
      ) : null}
      {long && (
        <Button size="sm" className="mt-1 text-muted" onClick={() => setFull((was) => !was)}>
          {full ? 'Show less' : 'Show full message'}
        </Button>
      )}
      <div className="mt-0.5 flex items-center gap-0.5 text-xs text-muted opacity-0 transition-opacity focus-within:opacity-100 group-hover/user:opacity-100">
        <span className="mr-1 tabular-nums" title={fullDate(event.time)}>
          {clock(event.time)}
        </span>
        <CopyButton text={() => text ?? ''} label="Copy message" />
        <Tooltip>
          <TooltipTrigger
            render={
              <Button
                size="icon-sm"
                aria-label="Reuse"
                className="text-muted"
                onClick={() => onReuse(text ?? '')}
              />
            }
          >
            <Icon name="corner-down-left" size={14} />
          </TooltipTrigger>
          <TooltipContent>Reuse: put it back in the composer</TooltipContent>
        </Tooltip>
      </div>
    </div>
  );
});

/** A message Bridge itself sent the agent (what became of a change it asked for, a cut turn's continuation): a quiet
 *  notice row naming Bridge, never the user's bubble. */
function BridgeMessage({ event }: { event: Stored }) {
  // A follow-up from the parent, a message from another session (bridge#212): whom from, then its text.
  const task = taskOf(event.text);
  if (task)
    return (
      <div data-who="bridge" title={fullDate(event.time)} className="flex flex-col py-1">
        <TaskFrom kind={task.kind} sender={event.sender} />
        <p className="min-w-0 whitespace-pre-wrap break-words text-sm text-secondary">
          {task.text}
        </p>
      </div>
    );
  return (
    <p
      data-who="bridge"
      title={fullDate(event.time)}
      className="flex items-start gap-1.5 py-1 text-xs text-muted"
    >
      <Icon name="bell" size={12} className="mt-0.5 shrink-0" />
      <span className="shrink-0 font-medium text-secondary">Bridge</span>
      <span className="min-w-0 break-words">{event.text}</span>
    </p>
  );
}

/** A prompt a scheduled task sent: one compact row naming its task, the prompt on a click; its time and Copy on hover. */
const AutomationMessage = React.memo(function AutomationMessage({ event }: { event: Stored }) {
  const [open, setOpen] = React.useState(false);
  const body = React.useId();
  return (
    <div className="group/user flex flex-col items-end pl-12">
      <div
        data-who="automation"
        className={cn(
          'min-w-0 max-w-full overflow-hidden rounded-2xl rounded-br-md border border-border-subtle bg-surface text-sm',
          open && 'w-full',
        )}
      >
        <button
          type="button"
          aria-expanded={open}
          aria-controls={body}
          className="flex w-full min-w-0 cursor-pointer items-center gap-2 border-0 bg-transparent px-3.5 py-2 text-left font-[inherit] text-secondary hover:text-foreground"
          onClick={() => setOpen((was) => !was)}
        >
          <Icon name="alarm-clock" size={14} className="shrink-0 text-muted" />
          <span className="shrink-0 text-muted">Scheduled task</span>
          <span data-title className="min-w-0 flex-1 truncate text-foreground">
            {event.scheduled?.title}
          </span>
          <Icon
            name="chevron-down"
            size={14}
            className={cn('shrink-0 text-muted transition-transform', open && 'rotate-180')}
          />
        </button>
        {open && (
          <div
            id={body}
            data-who="automation-prompt"
            className="max-h-96 overflow-auto whitespace-pre-wrap break-words border-t border-border-subtle px-3.5 py-2.5 text-foreground"
          >
            {event.text}
          </div>
        )}
      </div>
      <div className="mt-0.5 flex items-center gap-0.5 text-xs text-muted opacity-0 transition-opacity focus-within:opacity-100 group-hover/user:opacity-100">
        <span className="mr-1 tabular-nums" title={fullDate(event.time)}>
          {clock(event.time)}
        </span>
        <CopyButton text={() => event.text ?? ''} label="Copy prompt" />
      </div>
    </div>
  );
});

/** The running turn's plan above the composer: its progress on one line, the steps on a click. */
export function Tasks({ plan }: { plan: { content: string; status: string }[] }) {
  const [open, setOpen] = React.useState(false);
  // A cancelled step (ACP's newer schema) is dropped from the progress: neither current nor counted.
  const steps = plan.filter((entry) => entry.status !== 'cancelled');
  const done = steps.filter((entry) => entry.status === 'completed').length;
  const current =
    steps.find((entry) => entry.status === 'in_progress') ??
    steps.find((entry) => entry.status !== 'completed');
  return (
    <div
      data-who="plan"
      className="mx-3 rounded-t-dialog border border-b-0 border-border bg-surface text-[12.5px]"
    >
      <button
        type="button"
        aria-expanded={open}
        className="flex h-9 w-full cursor-pointer items-center gap-2 border-0 bg-transparent px-3 text-left font-[inherit] text-secondary"
        onClick={() => setOpen((was) => !was)}
      >
        <Icon name="list-checks" size={14} className="shrink-0 text-muted" />
        <span className="shrink-0">
          Tasks · {Math.min(done + 1, steps.length)} of {steps.length}
        </span>
        <span className="flex w-28 shrink-0 gap-0.5" aria-hidden="true">
          {steps.map((entry, index) => (
            <span
              key={index}
              className={cn(
                'h-1 flex-1 rounded-full',
                entry.status === 'completed'
                  ? 'bg-success'
                  : entry.status === 'in_progress'
                    ? 'bg-accent'
                    : 'bg-border',
              )}
            />
          ))}
        </span>
        <span className="min-w-0 truncate text-foreground">{current?.content}</span>
        <Icon
          name="chevron-up"
          size={14}
          className={cn('ml-auto shrink-0 text-muted transition-transform', open && 'rotate-180')}
        />
      </button>
      {open && (
        <ol aria-label="Plan" className="grid max-h-56 gap-1.5 overflow-auto px-3 pb-3">
          {plan.map((entry, index) => (
            <li key={index} data-status={entry.status} className="flex items-center gap-2 text-sm">
              {entry.status === 'completed' ? (
                <span className="flex size-4 shrink-0 items-center justify-center rounded-full bg-success text-success-foreground">
                  <Icon name="check" size={11} strokeWidth={3} />
                </span>
              ) : entry.status === 'in_progress' ? (
                <Spinner
                  label="In progress"
                  className="size-4 items-center justify-center text-accent"
                />
              ) : entry.status === 'cancelled' ? (
                <span className="flex size-4 shrink-0 items-center justify-center text-muted">
                  <Icon name="x" size={12} />
                </span>
              ) : (
                <span className="size-4 shrink-0 rounded-full border-[1.5px] border-muted" />
              )}
              <span
                className={
                  entry.status === 'completed' || entry.status === 'cancelled'
                    ? 'text-muted line-through'
                    : 'text-foreground'
                }
              >
                {entry.content}
              </span>
            </li>
          ))}
        </ol>
      )}
    </div>
  );
}

/** An open decision, docked on the composer. Its row in the timeline (`onRow`, out of view) holds its options: the dock
 *  only points to it, Show scrolling there. Else (its row not drawn: its turn begun on an older page) what is asked, its
 *  options (the allow one focused when nothing else is), Dismiss, and its countdown; Escape picks its deny option. */
export function DecisionDock({
  event,
  busy,
  more = 0,
  relative = (text) => text,
  onAnswer,
  onRow = false,
}: {
  event: Stored;
  busy: boolean;
  more?: number;
  relative?: (text: string) => string;
  onAnswer: (option: Answer) => void;
  onRow?: boolean;
}) {
  const primary = React.useRef<HTMLButtonElement>(null);
  React.useEffect(() => {
    const active = document.activeElement;
    if (!onRow && (!active || active === document.body)) primary.current?.focus();
  }, [event.seq, onRow]);
  if (onRow)
    return (
      <section
        aria-label="Waiting above"
        data-who="decision-pointer"
        className="flex h-9 items-center gap-2 rounded-t-dialog border border-b-0 border-warning/50 bg-warning-subtle pl-3.5 pr-1.5 text-[12.5px]"
      >
        <span className="size-1.5 shrink-0 rounded-full bg-warning" />
        <span className="shrink-0 font-semibold text-warning-text">{decisionLabel(event)}</span>
        <span className="min-w-0 truncate font-mono text-xs text-secondary">
          {relative(event.title ?? '')}
        </span>
        {more > 0 && <span className="shrink-0 text-xs text-muted">+{more} more</span>}
        <span className="flex-1" />
        <Button
          size="sm"
          className="shrink-0 gap-1"
          onClick={() => {
            const row = document.querySelector<HTMLElement>(`[data-decision-row="${event.seq}"]`);
            row?.scrollIntoView?.({ block: 'center', behavior: 'smooth' });
            // Its allow option, else its first one (a question's) that is not a lasting grant (plugins#171).
            (
              row?.querySelector<HTMLElement>('[data-primary]') ??
              row?.querySelector<HTMLElement>('[data-option]:not([data-lasting])')
            )?.focus({ preventScroll: true });
          }}
        >
          Show
          <Icon name="arrow-up" size={13} />
        </Button>
      </section>
    );
  const deny = event.options?.find((option) => option.kind === 'deny');
  const allow = primaryAllow(event.options);
  const questions = questionsAsked(event);
  if (questions)
    return (
      <section
        aria-label={decisionLabel(event)}
        data-who="decision-dock"
        className="max-h-[50vh] overflow-y-auto rounded-t-dialog border border-b-0 border-warning/50 bg-warning-subtle px-3.5 pb-3 pt-2.5 text-[13px]"
      >
        <div className="flex items-center gap-2 text-[12.5px]">
          <span className="size-1.5 shrink-0 rounded-full bg-warning" />
          <span className="font-semibold text-warning-text">{decisionLabel(event)}</span>
          {more > 0 && <span className="text-xs text-muted">+{more} more waiting</span>}
          <span className="flex-1" />
          {event.expiresAt && <Countdown expiresAt={event.expiresAt} />}
        </div>
        <DecisionQuestions
          questions={questions}
          busy={busy}
          onAnswer={onAnswer}
          primary={primary}
          draft={event.id}
        />
      </section>
    );
  return (
    <section
      aria-label={decisionLabel(event)}
      data-who="decision-dock"
      className="rounded-t-dialog border border-b-0 border-warning/50 bg-warning-subtle px-3.5 pb-3 pt-2.5"
      onKeyDown={(keyEvent) => {
        if (keyEvent.key === 'Escape' && deny && !busy) {
          keyEvent.preventDefault();
          onAnswer(deny.id);
        }
      }}
    >
      <div className="flex items-center gap-2 text-[12.5px]">
        <span className="size-1.5 shrink-0 rounded-full bg-warning" />
        <span className="font-semibold text-warning-text">{decisionLabel(event)}</span>
        {more > 0 && <span className="text-xs text-muted">+{more} more waiting</span>}
        <span className="flex-1" />
        {event.expiresAt && <Countdown expiresAt={event.expiresAt} />}
      </div>
      <p
        data-title
        className="mt-1.5 break-words rounded-default border border-border-subtle bg-surface px-2.5 py-1.5 font-mono text-xs text-foreground"
      >
        {relative(event.title ?? '')}
      </p>
      <div className="mt-2.5 flex flex-wrap items-center justify-end gap-2">
        <span className="mr-auto hidden text-xs text-muted sm:inline">
          {allow && '↵ allow'}
          {allow && deny && ' · '}
          {deny && 'Esc deny'}
        </span>
        <Button variant="ghost" disabled={busy} onClick={() => onAnswer(null)}>
          Dismiss
        </Button>
        {event.options?.map((option) => (
          <Button
            key={option.id}
            ref={option === allow ? primary : undefined}
            variant={option === allow ? 'primary' : 'outline'}
            disabled={busy}
            onClick={() => onAnswer(option.id)}
          >
            {option.label}
          </Button>
        ))}
      </div>
    </section>
  );
}

/** A message in a session's queue: the user's, or a scheduled task's run (`scheduled`, its task). */
export interface QueuedItem {
  id: string;
  text: string;
  at: string;
  attachments?: unknown[];
  scheduled?: { id: string; title: string };
  from?: 'bridge';
  /** A child's results waiting (bridge#212): their delegations. */
  delegations?: string[];
  /** A child's questions waiting: the child asking each. */
  questions?: { session: string }[];
}
/** A note another session left for this one's next turn (its inbox): who, and where a click on its name goes. */
export interface QueuedNote {
  from: string;
  title: string;
  text: string;
  at: string;
  to: ScreenLinkProps['to'];
}

/** Who sent a waiting message, before its text: you, Bridge, a scheduled task, or another session (a link to it). */
function Sender({ item, note }: { item?: QueuedItem; note?: QueuedNote }) {
  if (note)
    return (
      <span data-sender="session" className="flex min-w-0 max-w-[40%] shrink-0 items-center gap-1">
        <span className="shrink-0 text-muted">From</span>
        <ScreenLink
          to={note.to}
          className="truncate text-secondary underline-offset-2 hover:text-foreground hover:underline"
        >
          {note.title || 'New chat'}
        </ScreenLink>
      </span>
    );
  if (item?.from === 'bridge' && (item.questions?.length || item.delegations?.length))
    return <ChildSender item={item} />;
  if (item?.from === 'bridge')
    return (
      <span data-sender="bridge" className="shrink-0 text-muted">
        Bridge
      </span>
    );
  if (item?.scheduled)
    return (
      <span
        data-sender="scheduled"
        className="flex min-w-0 max-w-[40%] shrink-0 items-center gap-1 text-muted"
      >
        <span className="shrink-0">Scheduled task</span>
        <span className="truncate text-secondary">{item.scheduled.title}</span>
      </span>
    );
  return (
    <span data-sender="you" className="shrink-0 text-muted">
      You
    </span>
  );
}

/** Who a child's question or result waiting in its parent's queue is from (bridge#212): that child, a link to it. */
function ChildSender({ item }: { item: QueuedItem }) {
  const lineage = React.useContext(LineageContext);
  const asking = item.questions?.[0]?.session;
  const child =
    asking ??
    lineage?.delegations.find((each) => each.id === item.delegations?.[0])?.child ??
    undefined;
  const title = (child && lineage?.sessions.get(child)?.title) || 'a child session';
  return (
    <span data-sender="child" className="flex min-w-0 max-w-[40%] shrink-0 items-center gap-1">
      <span className="shrink-0 text-muted">{asking ? 'Question from' : 'Result from'}</span>
      {child && lineage ? (
        <ScreenLink
          to={lineage.to(child)}
          className="truncate text-secondary underline-offset-2 hover:text-foreground hover:underline"
        >
          {title}
        </ScreenLink>
      ) : (
        <span className="truncate text-secondary">{title}</span>
      )}
    </span>
  );
}

/** Messages waiting for this session's next turn, above the composer, each saying who sent it: the notes other sessions
 *  left (read at the start of its next turn, by its agent alone), then the queue (each sent as a turn of its own after
 *  the running one): Send now (into the running turn when its harness steers, else it stops the turn), Edit (back to
 *  the composer), Remove. */
export function Queued({
  items,
  notes = [],
  steers = false,
  onSend,
  onEdit,
  onRemove,
}: {
  items: QueuedItem[];
  notes?: QueuedNote[];
  /** The session's harness steers a running turn (bridge#212 S6): Send now puts the message into it. */
  steers?: boolean;
  onSend: (item: string) => void;
  onEdit: (item: { id: string; text: string }) => void;
  onRemove: (item: string) => void;
}) {
  const count = notes.length + items.length;
  if (!count) return null;
  const counted = (index: number) =>
    index === 0 && <span className="shrink-0 text-muted">{count} queued</span>;
  return (
    <section
      aria-label="Queued messages"
      data-who="queue"
      className="mx-3 rounded-t-dialog border border-b-0 border-border bg-surface py-1 text-[12.5px]"
    >
      {notes.map((note, index) => (
        <div
          key={note.at + note.from}
          data-note={note.from}
          title="Its agent reads it at the start of its next turn"
          className="flex h-8 items-center gap-2 pl-3 pr-1.5 text-secondary"
        >
          <Icon name="mail" size={14} className="shrink-0 text-muted" />
          {counted(index)}
          <Sender note={note} />
          <span className="min-w-0 flex-1 truncate text-foreground">{oneLine(note.text, 200)}</span>
        </div>
      ))}
      {items.map((item, index) => (
        <div
          key={item.id}
          data-queued={item.id}
          className="flex h-8 items-center gap-2 pl-3 pr-1.5 text-secondary"
        >
          <Icon
            name={item.scheduled ? 'alarm-clock' : 'list-plus'}
            size={14}
            className="shrink-0 text-muted"
          />
          {counted(notes.length + index)}
          <Sender item={item} />
          <span className="min-w-0 flex-1 truncate text-foreground">{oneLine(item.text, 200)}</span>
          {item.attachments?.length ? (
            <span className="flex shrink-0 items-center gap-1 text-muted">
              <Icon name="image" size={13} />
              {item.attachments.length}
            </span>
          ) : null}
          <Button
            size="sm"
            onClick={() => onSend(item.id)}
            title={
              steers
                ? 'Send this into the running turn now'
                : 'Stop the running turn and send this now'
            }
          >
            Send now
          </Button>
          <Tooltip>
            <TooltipTrigger
              render={
                <Button
                  size="icon-sm"
                  aria-label="Edit"
                  className="text-muted"
                  onClick={() => onEdit(item)}
                />
              }
            >
              <Icon name="square-pen" size={14} />
            </TooltipTrigger>
            <TooltipContent>Edit: back to the composer</TooltipContent>
          </Tooltip>
          <Tooltip>
            <TooltipTrigger
              render={
                <Button
                  size="icon-sm"
                  aria-label="Remove"
                  className="text-muted"
                  onClick={() => onRemove(item.id)}
                />
              }
            >
              <Icon name="x" size={14} />
            </TooltipTrigger>
            <TooltipContent>Remove</TooltipContent>
          </Tooltip>
        </div>
      ))}
    </section>
  );
}
