Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

172 KB
Raw Blame
// oxlint-disable ok/no-raw-error-toast -- pre-rule backlog: toasts here show raw error text; delete this line once the file maps each failure to written copy. See https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-raw-error-toast
// oxlint-disable ok/no-physical-direction-utility -- pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-physical-direction-utility

import { deriveAgentPosture } from '@inkeep/open-knowledge-core/acp/agent-posture';
import {
  type AttachmentPart,
  exitStderrWindow,
  type QueuedMessage,
  type SessionConfigOption,
  type ThreadAuthMethod,
  type ThreadExitDiagnosis,
  type ThreadFailureDetail,
  type ThreadInfo,
} from '@inkeep/open-knowledge-core/acp/thread-protocol';
import { plural } from '@lingui/core/macro';
import { Plural, useLingui } from '@lingui/react/macro';
import {
  ArrowUp,
  Check,
  ChevronDown,
  ChevronRight,
  CircleCheck,
  Download,
  FileText,
  FolderInput,
  Globe,
  History,
  Link2,
  ListPlus,
  MousePointer2,
  Plus,
  RotateCcw,
  Search,
  Settings2,
  Share2,
  ShieldAlert,
  Shuffle,
  Sparkles,
  Square,
  SquarePen,
  Terminal as TerminalIcon,
  Trash2,
  TriangleAlert,
  Wrench,
  X,
  Zap,
} from 'lucide-react';
import {
  type ComponentProps,
  Fragment,
  type ReactNode,
  type RefObject,
  use,
  useEffect,
  useEffectEvent,
  useId,
  useRef,
  useState,
} from 'react';
import { toast } from 'sonner';
import {
  type CommentDocTally,
  composeCommentBatchInstruction,
  QueuedCommentsChip,
  toCommentBatchItem,
  useSelectedCommentCount,
  useSelectedCommentDocs,
} from '@/comments/comment-chips';
import { subscribeSendInThread } from '@/comments/open-chat-send';
import { dispatchComments, subscribeCommentPosted } from '@/comments/store';
import {
  ComposerAddMenu,
  ComposerCommandsMenuItem,
  ComposerCommentsMenuItem,
  ComposerFilesMenuItem,
  ComposerMentionMenuItem,
  ComposerTooltipProvider,
} from '@/components/ComposerAddMenu';
import { ComposerContextChips } from '@/components/ComposerContextChips';
import { CopyButton } from '@/components/CopyButton';
import { isExternalFileDrag } from '@/components/file-tree-adapter';
import { focusComposerInputOnCardPointer } from '@/components/focus-composer-on-card-pointer';
import { subscribeToSignInTerminalExits } from '@/components/handoff/sign-in-terminal-events';
import {
  requestTerminalCommandLaunch,
  requestTerminalLaunch,
} from '@/components/handoff/terminal-launch-events';
import { useOptionalPageList } from '@/components/PageListContext';
import { ReportBugDialog } from '@/components/ReportBugDialog';
import { RotatingComposerPlaceholder } from '@/components/RotatingComposerPlaceholder';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
  useMessageScroller,
} from '@/components/ui/message-scroller';
import { Progress } from '@/components/ui/progress';
import { Skeleton } from '@/components/ui/skeleton';
import { Spinner } from '@/components/ui/spinner';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { WorkingAvatar } from '@/components/WorkingAvatar';
import {
  ComposerMentionInput,
  type ComposerMentionInputHandle,
} from '@/editor/ComposerMentionInput';
import type { MentionRecency } from '@/editor/composer-mention/composer-mention';
import { useDocumentContext } from '@/editor/DocumentContext';
import { agentDisplayName } from '@/lib/acp/agent-display';
import {
  agentSettingsKey,
  rememberAgentConfigOption,
  rememberAgentContextWindow,
  rememberAgentMode,
} from '@/lib/acp/agent-settings-store';
import { configValueHint, resolveDefaultOptionLabel } from '@/lib/acp/config-value-hints';
import { exitSummary } from '@/lib/acp/exit-summary';
import { terminalLaunchAvailable, useHarnessTerminalCli } from '@/lib/acp/harness-terminal-cli';
import {
  type AttachmentRefusal,
  attachmentBudgetKb,
  collectAllFiles,
  collectImageFiles,
  describeAttachmentRefusals,
  describeImageError,
  embeddedAttachmentBytes,
  fileToAttachment,
  isAttachmentRefusal,
  logAttachmentRejection,
  MAX_TOTAL_ATTACHMENT_BYTES,
  rejectedPart,
  totalEmbeddedAttachmentBytes,
} from '@/lib/acp/image-attachment';
import { computeDiffRows } from '@/lib/acp/inline-diff';
import { launchAgentThread } from '@/lib/acp/launch-agent-thread';
import { contextChoicesForModel, useModelCandidates } from '@/lib/acp/model-candidates';
import { formatShellCommand, revealHiddenCharacters } from '@/lib/acp/shell-command-format';
import { parseSignInOutput, shortenUrl } from '@/lib/acp/sign-in-output';
import { renderTerminalText } from '@/lib/acp/terminal-text';
import { thoughtPreview } from '@/lib/acp/thought-preview';
import { threadAttachmentPaths } from '@/lib/acp/thread-attachment-paths';
import {
  getAgentThreadClient,
  ThreadContextWindowError,
  ThreadResumeError,
  ThreadRetryError,
  useAgentThread,
  useAgentThreadModel,
} from '@/lib/acp/thread-client';
import {
  flushStagedThreadDraft,
  flushStagedThreadDraftContent,
  registerThreadDraftReader,
  subscribeStagedThreadDraft,
  subscribeStagedThreadDraftContent,
} from '@/lib/acp/thread-draft-staging';
import {
  type PermissionOutcome,
  type RenderedItem,
  type RenderedPermission,
  type RenderedTerminal,
  type RenderedToolCall,
  resolvePermissionOutcome,
  threadHasUserMessage,
} from '@/lib/acp/thread-event-model';
import {
  describeToolCall,
  describeToolPurpose,
  type ToolCallGlyph,
  toolRunKey,
  toolRunLabel,
} from '@/lib/acp/tool-call-display';
import { adjacentToolRuns, type ToolRun } from '@/lib/acp/tool-call-groups';
import { toolFailureHint } from '@/lib/acp/tool-failure-hint';
import {
  jsonMarkdown,
  looksLikeMarkdown,
  prettyJson,
  type ToolOutputMode,
  toolOutputMode,
} from '@/lib/acp/tool-output-format';
import { useBugReport } from '@/lib/bug-report-capture';
import { docNameFromHash, filePathToDocName, hashFromDocName } from '@/lib/doc-hash';
import { dispatchExternalLinkClick } from '@/lib/external-link';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';
import { formatToolList, formatUnitList } from '@/lib/tool-list-format';
import { useWorkspace } from '@/lib/use-workspace';
import { cn } from '@/lib/utils';
import { AgentMarkdown } from './AgentMarkdown';
import { AgentNoticeAnnouncer } from './AgentNoticeAnnouncer';
import { buildDocPathResolver, setDocPathResolver } from './doc-path-links';
import { DocPathResolverReadyContext } from './doc-path-links-context';
import {
  decideFollowNavigation,
  type FollowNavState,
  INITIAL_FOLLOW_NAV_STATE,
  latestFollowTarget,
  loadFollowFilePref,
  saveFollowFilePref,
} from './follow-file';
import { MentionRecencyContext } from './mention-recency-context';
import { type ImagePreview, ImagePreviewContext, PendingImageStrip } from './PendingImageStrip';
import { PlanChecklist } from './PlanChecklist';
import { appendPresenceWrite, latestAgentWrite, type PresenceWrite } from './presence-follow';
import { RegisteredAgentIcon } from './RegisteredAgentIcon';
import { ReferenceRulesContext } from './reference-links-context';
import {
  clickableAuthMethods,
  isThreadResumable,
  manualAuthMethods,
  type ThreadAuthActionKind,
  type ThreadAuthOffer,
  type ThreadAuthOfferWithoutSignIn,
  terminalAuthMethods,
  threadAuthHistoryOffer,
  threadAuthOffer,
  threadAuthOfferWithoutSignInMethods,
} from './thread-auth-offer';
import { transcriptItemId } from './transcript-item-id';
import { type ResendTarget, UserMessageActions, UserMessageEditor } from './UserMessageActions';
import { useDelayedInstallStatus } from './use-delayed-install-status';
import { useMinutesSince } from './use-minutes-since';
import { useReferenceRules } from './use-reference-rules';
import { activeToolKind, useThinkingLine, workingStatusText } from './working-status';

const CANCEL_STALL_MS = 10_000;

const COMPLETION_CHECK_MS = 1_400;

const TOOL_ICONS: Record<ToolCallGlyph, typeof Wrench> = {
  read: FileText,
  edit: SquarePen,
  delete: Trash2,
  move: FolderInput,
  search: Search,
  execute: TerminalIcon,
  think: Sparkles,
  fetch: Globe,
  switch_mode: Shuffle,
  check: CircleCheck,
  link: Link2,
  history: History,
  share: Share2,
  install: Download,
  settings: Settings2,
  restore: RotateCcw,
  other: Wrench,
};

function errorText(err: unknown): string {
  return err instanceof Error ? err.message : String(err);
}

function isAgentExitedError(err: unknown): boolean {
  return err instanceof Error && 'code' in err && err.code === 'agent-exited';
}

function isRetryFailureShownInThread(err: unknown): boolean {
  return err instanceof ThreadRetryError && err.code === 'spawn-failed';
}

const RETRYABLE_FAILURE_REASONS: ReadonlySet<ThreadFailureDetail['reason']> = new Set([
  'connect',
  'session-setup',
  'auth-required',
]);

function isRetryableFailure(failure: ThreadFailureDetail): boolean {
  return RETRYABLE_FAILURE_REASONS.has(failure.reason);
}

const ROOT_CAUSE_PATTERN =
  /^\s*(?:npm\s+(?:error|ERR!)\s+\S|error:\s*\S|Error:\s*\S|fatal:\s*\S|panic:\s*\S)/;
function extractRootCauseLine(machineDetail: string): string | null {
  const lines = machineDetail.split('\n');
  for (let i = 0; i < lines.length; i += 1) {
    const line = lines[i]?.trim() ?? '';
    if (line !== '' && ROOT_CAUSE_PATTERN.test(line)) return line;
  }
  return null;
}

const STDERR_ERROR_PATTERN = /^\s*(?:npm\s+(?:error|ERR!)|error:|Error:|fatal:|panic:)/;
const STDERR_WARN_PATTERN = /^\s*(?:npm\s+warn|warning:|warn:)/;
function highlightStderr(machineDetail: string): ReactNode {
  const lines = machineDetail.split('\n');
  return lines.map((line, i) => {
    const key = `${i}:${line.slice(0, 32)}`;
    const cls = STDERR_ERROR_PATTERN.test(line)
      ? 'text-destructive'
      : STDERR_WARN_PATTERN.test(line)
        ? 'text-warning'
        : '';
    return (
      <span key={key} className={cls}>
        {line}
        {i < lines.length - 1 ? '\n' : ''}
      </span>
    );
  });
}

function isSignInWaitingStatus(status: ThreadInfo['status']): boolean {
  return status === 'auth_required' || status === 'authenticating';
}

interface StrandedMessage {
  readonly messageId: string;
  readonly text: string;
  readonly attachments: readonly AttachmentPart[];
  readonly foldedIndex: number;
}

function latestSignInNoticeIndex(items: readonly RenderedItem[]): number {
  for (let index = items.length - 1; index >= 0; index -= 1) {
    const item = items[index];
    if (
      item?.kind === 'notice' &&
      item.superseded !== true &&
      item.failure?.reason === 'auth-required'
    ) {
      return index;
    }
  }
  return -1;
}

function latestOfferNoticeIndex(
  items: readonly RenderedItem[],
  offerKind: ThreadAuthOfferWithoutSignIn['kind'],
): number {
  for (let index = items.length - 1; index >= 0; index -= 1) {
    const item = items[index];
    if (item?.kind !== 'notice' || item.superseded === true) continue;
    const reason = item.failure?.reason;
    if (reason === 'auth-required') return index;
    if (reason === 'exited' && offerKind === 'new-chat') return index;
  }
  return -1;
}

function latestCrashExit(items: readonly RenderedItem[]): ThreadExitDiagnosis | null {
  for (let index = items.length - 1; index >= 0; index -= 1) {
    const item = items[index];
    if (item?.kind !== 'notice' || item.superseded === true) continue;
    if (item.failure?.reason === 'exited' && item.failure.exit !== undefined) {
      return item.failure.exit;
    }
  }
  return null;
}

function strandedMessageBeforeSignIn(items: readonly RenderedItem[]): StrandedMessage | null {
  const noticeIndex = latestSignInNoticeIndex(items);
  if (noticeIndex === -1) return null;
  for (let index = noticeIndex - 1; index >= 0; index -= 1) {
    const item = items[index];
    if (item?.kind !== 'message' || item.role !== 'user') continue;
    let foldedIndex = 0;
    for (let before = 0; before < index; before += 1) {
      const earlier = items[before];
      if (earlier?.kind === 'notice' && earlier.superseded === true) continue;
      foldedIndex += 1;
    }
    return {
      messageId: item.messageId,
      text: item.text,
      attachments: item.attachments ?? [],
      foldedIndex,
    };
  }
  return null;
}

function latestTerminalAuthMethod(items: readonly RenderedItem[]): ThreadAuthMethod | null {
  const noticeIndex = latestSignInNoticeIndex(items);
  const item = noticeIndex === -1 ? undefined : items[noticeIndex];
  const methods = item?.kind === 'notice' ? (item.failure?.authMethods ?? []) : [];
  return terminalAuthMethods(methods)[0] ?? null;
}

function isStartingStatus(status: ThreadInfo['status']): boolean {
  return status === 'installing' || status === 'spawning' || isSignInWaitingStatus(status);
}

function nextStartOutcome(
  status: ThreadInfo['status'],
  previous: ThreadInfo['status'],
  announced: 'ready' | 'failed' | null,
): 'ready' | 'failed' | null {
  if (isStartingStatus(previous)) {
    if (status === 'ready') return 'ready';
    if (status === 'error' || status === 'exited') return 'failed';
  }
  switch (status) {
    case 'installing':
    case 'spawning':
    case 'auth_required':
    case 'authenticating':
      return null;
    case 'ready':
      return announced;
    case 'error':
    case 'exited':
      return announced === 'failed' ? 'failed' : null;
    case 'running':
    case 'awaiting_permission':
      return null;
    default: {
      const exhaustive: never = status;
      void exhaustive;
      return null;
    }
  }
}

function composerInstruction(handle: ComposerMentionInputHandle | null): string {
  return handle?.getContent().instruction.trim() ?? '';
}

export function ThreadView({
  info,
  active = true,
}: {
  info: ThreadInfo;
  active?: boolean;
}): ReactNode {
  const { t } = useLingui();
  const state = useAgentThread(info.threadId);
  const client = getAgentThreadClient();
  const workspace = useWorkspace();
  const composerRef = useRef<ComposerMentionInputHandle>(null);
  const [pendingAttachments, setPendingAttachments] = useState<readonly AttachmentPart[]>([]);
  const [imagePreview, setImagePreview] = useState<ImagePreview | null>(null);
  const [expandedToolRuns, setExpandedToolRuns] = useState<ReadonlySet<string>>(
    () => new Set<string>(),
  );
  const openImagePreview = (preview: ImagePreview) => setImagePreview(preview);
  const [pendingUploads, setPendingUploads] = useState<
    readonly { readonly id: string; readonly name: string; readonly mimeType: string }[]
  >([]);
  const [dragActive, setDragActive] = useState(false);
  const [dropNotice, setDropNotice] = useState<{ text: string; id: number } | null>(null);
  const dropNoticeIdRef = useRef(0);
  const attachmentsRef = useRef<readonly AttachmentPart[]>([]);
  const attachmentsGenerationRef = useRef(0);
  const commitPendingAttachments = (next: readonly AttachmentPart[], generation: number): void => {
    if (generation !== attachmentsGenerationRef.current) return;
    attachmentsRef.current = next;
    setPendingAttachments(next);
  };
  const clearPendingAttachments = (): void => {
    attachmentsGenerationRef.current += 1;
    attachmentsRef.current = [];
    setPendingAttachments([]);
    setPendingUploads([]);
  };
  useEffect(() => {
    if (dropNotice === null) return;
    const timer = setTimeout(() => setDropNotice(null), 4000);
    return () => clearTimeout(timer);
  }, [dropNotice]);
  const imagesAccepted = info.promptCapabilities?.image === true;
  const uploadsPending = pendingUploads.length > 0;
  const composerText = (): string => composerInstruction(composerRef.current);
  const composerAttachments = (): readonly AttachmentPart[] => {
    const chips = composerRef.current?.getContent().attachments ?? [];
    return [...chips, ...pendingAttachments];
  };
  const ingestFiles = async (files: readonly File[]): Promise<void> => {
    const absPathOf =
      typeof window !== 'undefined' && window.okDesktop
        ? window.okDesktop.getPathForFile
        : undefined;
    const workspaceContentDir = workspace?.contentDir;
    const pathSeparator = workspace?.pathSeparator;
    const accepted: File[] = [];
    let rejectedImageCount = 0;
    for (const file of files) {
      const isImage = (file.type || '').startsWith('image/');
      if (isImage && !imagesAccepted) {
        rejectedImageCount += 1;
        logAttachmentRejection('agent-chat', file, { kind: 'images-not-accepted' });
      } else {
        accepted.push(file);
      }
    }
    if (rejectedImageCount > 0) {
      const agentName = agentDisplayName(info.agent.name);
      toast.error(t`${agentName} doesn't accept image attachments.`);
    }
    if (accepted.length === 0) return;
    const placeholders = accepted.map((file) => ({
      id: `${file.name}:${file.size}:${file.lastModified ?? 0}:${Math.random().toString(36).slice(2, 8)}`,
      name: file.name || 'attachment',
      mimeType: file.type || '',
    }));
    const generation = attachmentsGenerationRef.current;
    const report = (message: string): void => {
      if (generation === attachmentsGenerationRef.current) toast.error(message);
    };
    setPendingUploads((previous) => [...previous, ...placeholders]);
    const refusals: AttachmentRefusal[] = [];
    let tooLargeTotalCount = 0;
    for (let i = 0; i < accepted.length; i += 1) {
      const file = accepted[i];
      const placeholderId = placeholders[i]?.id;
      if (file === undefined || placeholderId === undefined) continue;
      try {
        const outcome = await fileToAttachment(file, {
          absPathOf,
          workspaceContentDir,
          pathSeparator,
          imageBudgetBytes:
            MAX_TOTAL_ATTACHMENT_BYTES - totalEmbeddedAttachmentBytes(attachmentsRef.current),
        });
        setPendingUploads((previous) => previous.filter((p) => p.id !== placeholderId));
        if (outcome.ok) {
          const current = attachmentsRef.current;
          if (
            totalEmbeddedAttachmentBytes(current) + embeddedAttachmentBytes(outcome.part) >
            MAX_TOTAL_ATTACHMENT_BYTES
          ) {
            tooLargeTotalCount += 1;
            logAttachmentRejection('agent-chat', rejectedPart(outcome.part), {
              kind: 'total-too-large',
              limitBytes: MAX_TOTAL_ATTACHMENT_BYTES,
            });
          } else {
            commitPendingAttachments([...current, outcome.part], generation);
          }
        } else {
          logAttachmentRejection('agent-chat', file, outcome.error);
          if (isAttachmentRefusal(outcome.error)) refusals.push(outcome.error);
          else report(describeImageError(outcome.error));
        }
      } catch (err) {
        setPendingUploads((previous) => previous.filter((p) => p.id !== placeholderId));
        const fileName = file.name || 'attachment';
        console.error('[ingestFiles] failed to read attachment', fileName, err);
        report(t`Couldn't read ${fileName}.`);
      }
    }
    const notices = describeAttachmentRefusals(refusals);
    if (tooLargeTotalCount > 0) {
      const budgetKb = attachmentBudgetKb();
      notices.push(
        t`${plural(tooLargeTotalCount, {
          one: `Skipped # file — attachments can't total more than ${budgetKb} KB per message.`,
          other: `Skipped # files — attachments can't total more than ${budgetKb} KB per message.`,
        })}`,
      );
    }
    if (notices.length > 0 && generation === attachmentsGenerationRef.current) {
      dropNoticeIdRef.current += 1;
      setDropNotice({ text: notices.join(' '), id: dropNoticeIdRef.current });
    }
  };
  const removePendingAttachment = (index: number): void => {
    commitPendingAttachments(
      attachmentsRef.current.filter((_, i) => i !== index),
      attachmentsGenerationRef.current,
    );
  };
  const [followFile, setFollowFile] = useState(loadFollowFilePref);
  const scrollApiRef = useRef<ReturnType<typeof useMessageScroller> | null>(null);
  const initialSeqRef = useRef<number | null>(null);
  const followNavRef = useRef<FollowNavState>(INITIAL_FOLLOW_NAV_STATE);
  const prevTurnActiveRef = useRef(false);

  useEffect(() => {
    return registerThreadDraftReader(info.threadId, () => ({
      text: composerInstruction(composerRef.current),
      doc: composerRef.current?.getDoc() ?? null,
      attachments: attachmentsRef.current,
      uploadsPending,
    }));
  }, [info.threadId, uploadsPending]);

  useEffect(() => {
    const stopStaging = subscribeStagedThreadDraft(info.threadId, (text) => {
      return composerRef.current?.appendText(text) ?? false;
    });
    const stopStagingContent = subscribeStagedThreadDraftContent(info.threadId, (content) => {
      const accepted = composerRef.current?.setDoc(content.doc) ?? false;
      if (accepted && content.attachments.length > 0) {
        attachmentsRef.current = [...attachmentsRef.current, ...content.attachments];
        setPendingAttachments(attachmentsRef.current);
      }
      return accepted;
    });
    return () => {
      stopStagingContent();
      stopStaging();
    };
  }, [info.threadId]);

  useEffect(() => {
    if (info.promptCapabilities == null || imagesAccepted) return;
    const kept = pendingAttachments.filter((part) => part.kind !== 'image');
    if (kept.length === pendingAttachments.length) return;
    attachmentsRef.current = kept;
    setPendingAttachments(kept);
    const agentName = agentDisplayName(info.agent.name);
    toast.error(t`${agentName} doesn't accept image attachments.`);
  }, [info.promptCapabilities, imagesAccepted, pendingAttachments, info.agent.name, t]);

  const model = useAgentThreadModel(info.threadId);
  const status = info.status;
  const agentName = agentDisplayName(info.agent.name);
  const archived = info.archived === true;
  const turnActive = model?.turnActive === true && !archived;
  const thinkingLine = useThinkingLine(turnActive);
  const [resumePending, setResumePending] = useState(false);
  const [newChatPending, setNewChatPending] = useState(false);
  const [resumeError, setResumeError] = useState<ThreadResumeError | null>(null);
  const displayedStartStatus = useDelayedInstallStatus(status);
  const [startState, setStartState] = useState<{
    seen: ThreadInfo['status'];
    outcome: 'ready' | 'failed' | null;
  }>({ seen: status, outcome: null });
  if (startState.seen !== status) {
    setStartState({
      seen: status,
      outcome: nextStartOutcome(status, startState.seen, startState.outcome),
    });
  }
  const startOutcome = startState.outcome;
  const startStatusMessage =
    displayedStartStatus === 'installing'
      ? t`Installing ${agentName}…`
      : displayedStartStatus === 'spawning'
        ? t`Starting ${agentName}…`
        : startOutcome === 'ready'
          ? t`${agentName} is ready`
          : startOutcome === 'failed'
            ? t`${agentName} couldn't start`
            : '';
  const [startRegionMounted, setStartRegionMounted] = useState(false);
  useEffect(() => {
    setStartRegionMounted(true);
  }, []);
  const announcedStartStatus = startRegionMounted ? startStatusMessage : '';
  const hasRecoverablePromptFailure =
    !archived &&
    status === 'error' &&
    (model?.items ?? []).some(
      (item) =>
        item.kind === 'notice' && item.superseded !== true && item.failure?.reason === 'prompt',
    );
  const resumable = isThreadResumable(info);
  const canPrompt = archived
    ? !resumePending && resumable
    : (status === 'ready' || hasRecoverablePromptFailure) && !turnActive;
  const signingIn = status === 'authenticating';
  const awaitingSignIn = isSignInWaitingStatus(status);
  const canRetry = !archived && (status === 'error' || awaitingSignIn);
  const terminalCli = useHarnessTerminalCli(info.agent.id);
  const terminalAvailable = terminalLaunchAvailable();
  const [retryPending, setRetryPending] = useState(false);
  const [retryFailure, setRetryFailure] = useState<string | null>(null);
  const retryAttemptRef = useRef(0);
  const leftFailedSinceRetryRef = useRef(false);
  const [revertedPositions, setRevertedPositions] = useState<ReadonlySet<number>>(new Set());
  const canQueue = !archived && turnActive;
  const pageList = useOptionalPageList();
  const pages =
    pageList !== null && !pageList.loading && pageList.pages.size > 0 ? pageList.pages : null;
  const docPathResolver = pages === null ? null : buildDocPathResolver({ workspace, pages });
  setDocPathResolver(docPathResolver);
  const resolverReady = docPathResolver !== null;
  const referenceRules = useReferenceRules();
  const transcriptFollowTarget = model !== null ? latestFollowTarget(model.items, workspace) : null;

  const { systemProvider, activeDocName } = useDocumentContext();
  const [presenceWrites, setPresenceWrites] = useState<ReadonlyArray<PresenceWrite>>([]);
  useEffect(() => {
    if (!turnActive) {
      setPresenceWrites([]);
      return;
    }
    const awareness: unknown = systemProvider?.awareness;
    const observe = () => {
      const write = latestAgentWrite(awareness, Date.now());
      if (write !== null) setPresenceWrites((previous) => appendPresenceWrite(previous, write));
    };
    observe();
    const listenable =
      typeof awareness === 'object' &&
      awareness !== null &&
      typeof (awareness as { on?: unknown }).on === 'function' &&
      typeof (awareness as { off?: unknown }).off === 'function'
        ? (awareness as {
            on(event: 'change', handler: () => void): void;
            off(event: 'change', handler: () => void): void;
          })
        : null;
    listenable?.on('change', observe);
    return () => listenable?.off('change', observe);
  }, [turnActive, systemProvider]);

  const followTarget =
    transcriptFollowTarget ??
    (presenceWrites.length > 0 ? (presenceWrites[presenceWrites.length - 1]?.doc ?? null) : null);
  const lastSeq = state?.lastSeq ?? null;
  const [cancelPending, setCancelPending] = useState(false);
  const [cancelStalled, setCancelStalled] = useState(false);
  const stalledMinutes = useMinutesSince(info.stalledSince);
  const [planApprovalPending, setPlanApprovalPending] = useState(false);

  useEffect(() => {
    if (!turnActive) {
      setCancelPending(false);
      setCancelStalled(false);
    }
  }, [turnActive]);

  useEffect(() => {
    if (turnActive) setPlanApprovalPending(false);
  }, [turnActive]);

  useEffect(() => {
    if (!cancelPending || !turnActive) return;
    const timer = setTimeout(() => setCancelStalled(true), CANCEL_STALL_MS);
    return () => clearTimeout(timer);
  }, [cancelPending, turnActive]);

  const requestCancel = (): void => {
    const rescued = [
      ...(info.steer !== undefined ? [info.steer.content] : []),
      ...(info.queue ?? []).map((message) => message.content),
    ];
    if (rescued.length > 0) {
      composerRef.current?.appendText(rescued.join('\n\n'));
    }
    client.cancel(info.threadId);
    setCancelPending(true);
  };

  const requestSteer = (): void => {
    if (uploadsPending) return;
    const text = composerText();
    const attachments = composerAttachments();
    if (text === '' && attachments.length === 0) return;
    client.steer(info.threadId, text, attachments.length > 0 ? attachments : undefined);
    composerRef.current?.clear();
    clearPendingAttachments();
    scrollApiRef.current?.scrollToEnd();
  };

  useEffect(() => {
    if (lastSeq !== null && initialSeqRef.current === null) initialSeqRef.current = lastSeq;
  }, [lastSeq]);

  useEffect(() => {
    if (canRetry) return;
    leftFailedSinceRetryRef.current = true;
    setRetryPending(false);
    setRetryFailure(null);
  }, [canRetry]);

  useEffect(() => {
    if (turnActive && !prevTurnActiveRef.current) {
      followNavRef.current = { ...followNavRef.current, yielded: false, reArmed: true };
    }
    prevTurnActiveRef.current = turnActive;
  }, [turnActive]);

  useEffect(() => {
    if (!active || !followFile || followTarget === null || !turnActive) return;
    if (initialSeqRef.current === null || lastSeq === null || lastSeq <= initialSeqRef.current) {
      return;
    }
    if (isOverlayLayerOpen()) return;
    const currentDoc = docNameFromHash(window.location.hash);
    const decision = decideFollowNavigation(followTarget, currentDoc, followNavRef.current);
    followNavRef.current = decision.state;
    if (decision.navigateTo !== null) {
      window.location.assign(hashFromDocName(decision.navigateTo));
    }
  }, [active, followFile, followTarget, turnActive, lastSeq]);

  const toggleFollow = (): void => {
    const next = !followFile;
    setFollowFile(next);
    saveFollowFilePref(next);
    if (next) {
      followNavRef.current = INITIAL_FOLLOW_NAV_STATE;
    }
  };

  const [failedPrompt, setFailedPrompt] = useState<string | null>(null);

  const selectedCommentCount = useSelectedCommentCount();
  const selectedCommentDocs = useSelectedCommentDocs();
  const [commentsAttached, setCommentsAttached] = useState(true);
  const hasQueuedComments = selectedCommentCount > 0 && commentsAttached;
  useEffect(() => subscribeCommentPosted(() => setCommentsAttached(true)), []);

  const resumeThreadNow = (
    text?: string,
    failureText: string | null = null,
    attachments?: readonly AttachmentPart[],
  ): Promise<boolean> => {
    setResumePending(true);
    setResumeError(null);
    setFailedPrompt(null);
    scrollApiRef.current?.scrollToEnd();
    return client
      .resumeThread(info.threadId, text, attachments)
      .then(() => true)
      .catch((err) => {
        setResumeError(
          err instanceof ThreadResumeError
            ? err
            : new ThreadResumeError('internal', err instanceof Error ? err.message : String(err)),
        );
        setFailedPrompt(failureText);
        return false;
      })
      .finally(() => setResumePending(false));
  };

  const sendText = (
    text: string,
    failureText: string | null = text,
    attachments: readonly AttachmentPart[] = [],
  ): Promise<boolean> => {
    const parts = attachments.length > 0 ? attachments : undefined;
    if (!archived) {
      client.prompt(info.threadId, text, parts);
      scrollApiRef.current?.scrollToEnd();
      return Promise.resolve(true);
    }
    return resumeThreadNow(text, failureText, parts);
  };

  const resendMessage = async (
    text: string,
    target: ResendTarget,
    attachments: readonly AttachmentPart[],
  ): Promise<boolean> => {
    if (target.kind === 'this-thread') {
      return sendText(text, null, attachments);
    }
    const outcome = await launchAgentThread(
      { source: target.agent.source, id: target.agent.id },
      text,
      null,
      null,
      null,
      attachments,
    );
    if (outcome === 'deduped') {
      toast.error(t`Already starting a chat with this agent — try again in a moment.`);
    }
    return outcome === 'started';
  };

  const submit = (): void => {
    if (uploadsPending) return;
    const text = composerText();
    const attachments = composerAttachments();
    if (!(canPrompt || canQueue)) return;
    if (hasQueuedComments) {
      submitQueuedComments(text).catch((err) => {
        console.warn('[acp] queued-comment send rejected unexpectedly', err);
      });
      return;
    }
    if (text === '' && attachments.length === 0) return;
    void sendText(text, text, attachments);
    composerRef.current?.clear();
    clearPendingAttachments();
  };

  const submitQueuedComments = async (
    instruction: string,
    threadIds?: readonly string[],
  ): Promise<void> => {
    const queuedBehindTurn = canQueue;
    const shipped = await dispatchComments({
      threadIds,
      resolve: !queuedBehindTurn,
      compose: (items) =>
        sendText(
          composeCommentBatchInstruction(
            items.map((item) => toCommentBatchItem(item.payload)),
            instruction,
          ),
          null,
        ),
    });
    if (shipped.length === 0) return;
    if (queuedBehindTurn) {
      toast.info(
        t`Your comments are waiting behind the running turn — they stay queued until the agent picks the message up.`,
      );
    }
    composerRef.current?.clear();
    setCommentsAttached(true);
  };

  const sendCommentsFromPanel = useEffectEvent((threadIds?: readonly string[]) => {
    if (!(canPrompt || canQueue)) return;
    submitQueuedComments(composerText(), threadIds).catch((err) => {
      console.warn('[acp] panel comment send rejected unexpectedly', err);
    });
  });

  useEffect(() => {
    return subscribeSendInThread((sendTo, threadIds) => {
      if (sendTo !== info.threadId) return;
      sendCommentsFromPanel(threadIds);
    });
  }, [info.threadId]);

  const retryThread = (): void => {
    const stranded =
      awaitingSignIn && model !== null ? strandedMessageBeforeSignIn(model.items) : null;
    retryAttemptRef.current += 1;
    const attempt = retryAttemptRef.current;
    leftFailedSinceRetryRef.current = false;
    setRetryPending(true);
    setRetryFailure(null);
    void client
      .retryThread(info.threadId)
      .then((next) => {
        if (stranded === null || next.status !== 'ready') return;
        setRevertedPositions((prev) => new Set(prev).add(stranded.foldedIndex));
        void sendText(stranded.text, stranded.text, stranded.attachments);
      })
      .catch((err: unknown) => {
        if (isRetryFailureShownInThread(err)) return;
        if (attempt !== retryAttemptRef.current || leftFailedSinceRetryRef.current) return;
        setRetryFailure(errorText(err));
      })
      .finally(() => setRetryPending(false));
  };

  const retryAfterSignInTerminal = useEffectEvent(() => {
    if (!awaitingSignIn || retryPending) return;
    retryThread();
  });
  useEffect(
    () =>
      subscribeToSignInTerminalExits((threadId) => {
        if (threadId === info.threadId) retryAfterSignInTerminal();
      }),
    [info.threadId],
  );

  const authenticateThread = async (methodId: string): Promise<void> => {
    await client.authenticateThread(info.threadId, methodId);
  };

  const startFreshThread = (): void => {
    if (newChatPending) return;
    const bannerBeforeNewChat = resumeError;
    const promptBeforeNewChat = failedPrompt;
    const draftText = composerText();
    setNewChatPending(true);
    setResumeError(null);
    setFailedPrompt(null);
    void launchAgentThread(
      { source: info.agent.source, id: info.agent.id },
      promptBeforeNewChat,
      null,
      null,
      promptBeforeNewChat === null && draftText !== '' ? draftText : null,
    )
      .then((outcome) => {
        if (outcome === 'started') return;
        if (outcome === 'deduped') {
          toast.error(t`Already starting a chat with this agent — try again in a moment.`);
        }
        setResumeError((current) => current ?? bannerBeforeNewChat);
        setFailedPrompt((current) => current ?? promptBeforeNewChat);
      })
      .finally(() => setNewChatPending(false));
  };

  const runningAuthAction: ThreadAuthActionKind | null = resumePending
    ? 'resume'
    : retryPending
      ? 'retry'
      : newChatPending
        ? 'new-chat'
        : null;
  const authActionAnnouncement = (kind: ThreadAuthActionKind): string => {
    switch (kind) {
      case 'resume':
        return t`Resuming the chat`;
      case 'retry':
        return t`Retrying`;
      case 'new-chat':
        return t`Starting ${agentName}…`;
      case 'terminal-sign-in':
        return '';
      default: {
        const exhaustive: never = kind;
        void exhaustive;
        return '';
      }
    }
  };
  const runAuthAction = (kind: ThreadAuthActionKind): void => {
    switch (kind) {
      case 'resume':
        void resumeThreadNow();
        return;
      case 'retry':
        retryThread();
        return;
      case 'new-chat':
        startFreshThread();
        return;
      case 'terminal-sign-in': {
        const method =
          terminalAvailable && model !== null ? latestTerminalAuthMethod(model.items) : null;
        if (method !== null) {
          void client
            .terminalAuthLaunch(info.threadId, method.id)
            .then((launch) => {
              requestTerminalCommandLaunch({
                label: method.name,
                command: launch,
                signInThreadId: info.threadId,
              });
            })
            .catch((err: unknown) => {
              toast.error(t`Sign-in failed: ${errorText(err)}`);
            });
        } else if (terminalCli !== null) {
          requestTerminalLaunch('', terminalCli, { signInThreadId: info.threadId });
        }
        return;
      }
      default: {
        const exhaustive: never = kind;
        void exhaustive;
      }
    }
  };

  const foldedEntries =
    model === null
      ? []
      : model.items.flatMap((item, modelIndex) =>
          item.kind !== 'notice' || item.superseded !== true ? [{ item, modelIndex }] : [],
        );
  const foldedItems = foldedEntries.map((entry) => entry.item);
  const visibleEntries = foldedEntries.filter((_, index) => !revertedPositions.has(index));
  const visibleItems = visibleEntries.map((entry) => entry.item);
  const toolRunByIndex = new Map<number, { runId: string; run: ToolRun; isHead: boolean }>();
  for (const run of adjacentToolRuns(visibleItems, (item) =>
    item.kind === 'tool_call' && item.status === 'completed' ? toolRunKey(item) : null,
  )) {
    const head = visibleItems[run.start];
    if (head?.kind !== 'tool_call') continue;
    for (let offset = 0; offset < run.size; offset += 1) {
      toolRunByIndex.set(run.start + offset, {
        runId: head.toolCallId,
        run,
        isHead: offset === 0,
      });
    }
  }
  const agentNotices =
    model === null
      ? []
      : model.items.flatMap((item) =>
          item.kind === 'agent_notice' ? [{ seq: item.seq, text: item.text }] : [],
        );
  let retryNoticeIndex = -1;
  if (canRetry) {
    for (let index = visibleItems.length - 1; index >= 0; index -= 1) {
      const item = visibleItems[index];
      if (item?.kind === 'notice' && item.failure !== null && isRetryableFailure(item.failure)) {
        retryNoticeIndex = index;
        break;
      }
    }
  }
  const authHistoryOffer = threadAuthHistoryOffer(agentName);
  const authOffer: ThreadAuthOfferWithoutSignIn = threadAuthOfferWithoutSignInMethods({
    archived,
    resumable,
    status,
    agentName,
    terminalCli,
  });
  const authOfferNoticeIndex =
    authOffer.actionLabel === null ? -1 : latestOfferNoticeIndex(visibleItems, authOffer.kind);
  let restoreNoticeIndex = -1;
  if (!archived && status !== 'exited') {
    for (let index = visibleItems.length - 1; index >= 0; index -= 1) {
      const item = visibleItems[index];
      if (item?.kind !== 'notice') continue;
      const reason = item.failure?.reason;
      if (reason === 'prompt' || (reason === 'auth-required' && canPrompt)) {
        restoreNoticeIndex = index;
        break;
      }
    }
  }
  const restoreFailedPromptToComposer = (visibleNoticeIndex: number): void => {
    const foldedNoticeIndex = mapVisibleToFolded(visibleNoticeIndex);
    if (foldedNoticeIndex === -1) return;
    for (let index = foldedNoticeIndex - 1; index >= 0; index -= 1) {
      const item = foldedItems[index];
      if (item?.kind === 'message' && item.role === 'user') {
        if (item.text !== '') {
          composerRef.current?.appendText(item.text);
          scrollApiRef.current?.scrollToEnd();
        }
        setRevertedPositions((prev) => {
          const next = new Set(prev);
          next.add(index);
          next.add(foldedNoticeIndex);
          return next;
        });
        return;
      }
    }
  };
  const mapVisibleToFolded = (target: number): number => {
    let seen = -1;
    for (let index = 0; index < foldedItems.length; index += 1) {
      if (revertedPositions.has(index)) continue;
      seen += 1;
      if (seen === target) return index;
    }
    return -1;
  };

  let lastUserTurnIndex = -1;
  for (let index = visibleItems.length - 1; index >= 0; index -= 1) {
    const item = visibleItems[index];
    if (item?.kind === 'message' && item.role === 'user') {
      lastUserTurnIndex = index;
      break;
    }
  }

  const resumeFailureMessage = !archived
    ? ''
    : !resumable
      ? t`${agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue.`
      : resumeError !== null
        ? t`Couldn't resume this chat: ${resumeError.message}`
        : '';

  const newChatOfferInTranscript = authOffer.kind === 'new-chat' && authOfferNoticeIndex !== -1;
  const crashExit = archived || startOutcome === 'failed' ? null : latestCrashExit(visibleItems);
  const crashHeadline = t`${agentName} stopped unexpectedly.`;
  const crashAnnouncement = crashExit === null ? '' : `${crashHeadline} ${exitSummary(crashExit)}`;

  const items = visibleItems;
  const mentionRecency: MentionRecency = {
    currentDocName: activeDocName,
    recentPaths: threadAttachmentPaths(items),
  };
  const signInNoticeIndex = awaitingSignIn && !archived ? latestSignInNoticeIndex(items) : -1;
  const signInNotice = signInNoticeIndex === -1 ? undefined : items[signInNoticeIndex];
  const authPrompt: ThreadFailureDetail | null =
    signInNotice?.kind === 'notice' ? signInNotice.failure : null;

  return (
    <MentionRecencyContext value={mentionRecency}>
      <ImagePreviewContext.Provider value={openImagePreview}>
        <ImagePreviewDialog
          preview={imagePreview}
          onOpenChange={(open) => !open && setImagePreview(null)}
        />
        <div // oxlint-disable-line jsx-a11y/no-static-element-interactions -- drop-target — keyboard/AT users have the + picker button in the composer; drop is a pointer-only affordance.
          className="relative flex min-h-0 flex-1 flex-col text-gray-800 dark:text-gray-200"
          data-agent-thread-root=""
          onDragEnter={(event) => {
            if (isExternalFileDrag(event)) {
              event.preventDefault();
              setDragActive(true);
            }
          }}
          onDragOver={(event) => {
            if (isExternalFileDrag(event)) {
              event.preventDefault();
              event.dataTransfer.dropEffect = 'copy';
              setDragActive(true);
            }
          }}
          onDragLeave={(event) => {
            const next = event.relatedTarget;
            if (next instanceof Node && event.currentTarget.contains(next)) return;
            setDragActive(false);
          }}
          onDrop={(event) => {
            if (!isExternalFileDrag(event)) return;
            event.preventDefault();
            setDragActive(false);
            const files = collectAllFiles(event.dataTransfer);
            if (files.length === 0) {
              dropNoticeIdRef.current += 1;
              setDropNotice({
                text: t`Folders and empty files can't be attached — drop the files themselves.`,
                id: dropNoticeIdRef.current,
              });
              return;
            }
            void ingestFiles(files);
          }}
        >
          <DocPathResolverReadyContext value={resolverReady}>
            <ReferenceRulesContext value={referenceRules}>
              <ThreadHeader info={info} followFile={followFile} onToggleFollow={toggleFollow} />
              <AgentNoticeAnnouncer
                notices={agentNotices}
                agentName={agentName}
                replayThroughSeq={state?.replayThroughSeq ?? Number.POSITIVE_INFINITY}
              />
              {model !== null && model.plan.length > 0 ? (
                <PlanChecklist
                  plan={model.plan}
                  approval={
                    canPrompt && !archived && !planApprovalPending
                      ? {
                          onApprove: () => {
                            setPlanApprovalPending(true);
                            void sendText('Approve. Please proceed with the plan.');
                          },
                          onAskChanges: () => {
                            const prefix = t`In the plan above, please `;
                            const composer = composerRef.current;
                            if (
                              composer !== null &&
                              !composer.getContent().instruction.endsWith(prefix)
                            ) {
                              composer.appendText(prefix);
                            }
                            composer?.focusEnd();
                          },
                          onReject: () => {
                            setPlanApprovalPending(true);
                            void sendText('Reject. Please stop and do not proceed with this plan.');
                          },
                        }
                      : undefined
                  }
                />
              ) : null}
              {authPrompt !== null || model === null || visibleItems.length === 0 ? (
                <div
                  className="min-h-0 flex-1 overflow-y-auto px-3 py-2 subtle-scrollbar scroll-fade-mask"
                  data-testid="agent-thread-transcript"
                >
                  {authPrompt !== null ? (
                    <div className="flex min-h-full items-center justify-center">
                      <ThreadAuthPrompt
                        failure={authPrompt}
                        offer={threadAuthOffer({
                          authMethods: authPrompt.authMethods ?? [],
                          agentName,
                          terminalCli,
                          terminalAvailable,
                        })}
                        agent={info.agent}
                        agentName={agentName}
                        signingIn={signingIn}
                        signInOutput={info.signInOutput}
                        showRetry={canRetry}
                        retryPending={retryPending}
                        onRetry={retryThread}
                        onAuthAction={runAuthAction}
                        runningAuthAction={runningAuthAction}
                        onAuthenticate={authenticateThread}
                      />
                    </div>
                  ) : (
                    <ThreadEmptyState
                      status={status}
                      displayedStartStatus={displayedStartStatus}
                      justSettled={startOutcome === 'ready'}
                      archived={archived}
                      agent={info.agent}
                      authOffer={authOffer}
                      onAuthAction={runAuthAction}
                      runningAuthAction={runningAuthAction}
                    />
                  )}
                </div>
              ) : (
                <MessageScrollerProvider autoScroll defaultScrollPosition="last-anchor">
                  <ScrollToEndBridge apiRef={scrollApiRef} />
                  <MessageScroller className="min-h-0 flex-1">
                    <MessageScrollerViewport
                      aria-label={t`Agent transcript`}
                      className="px-3 py-2 subtle-scrollbar scroll-fade-mask"
                      data-testid="agent-thread-transcript"
                    >
                      <MessageScrollerContent className="gap-2 [&>[data-tool-call]+[data-tool-call]]:-mt-1">
                        {visibleEntries.map(({ item, modelIndex }, index) => {
                          const id = transcriptItemId(item, modelIndex);
                          const group = toolRunByIndex.get(index);
                          const collapsed =
                            group !== undefined && !expandedToolRuns.has(group.runId);
                          if (collapsed && !group.isHead) return null;
                          if (collapsed && group.isHead) {
                            const runId = group.runId;
                            return (
                              <MessageScrollerItem
                                key={id}
                                messageId={id}
                                className="flex flex-col"
                                data-tool-call=""
                              >
                                <ToolCallGroupRow
                                  calls={visibleItems
                                    .slice(group.run.start, group.run.start + group.run.size)
                                    .filter(
                                      (candidate): candidate is RenderedToolCall =>
                                        candidate.kind === 'tool_call',
                                    )}
                                  onExpand={() =>
                                    setExpandedToolRuns((previous) => new Set(previous).add(runId))
                                  }
                                />
                              </MessageScrollerItem>
                            );
                          }
                          return (
                            <MessageScrollerItem
                              key={id}
                              messageId={id}
                              className="flex flex-col"
                              scrollAnchor={item.kind === 'message' && item.role === 'user'}
                              data-tool-call={item.kind === 'tool_call' ? '' : undefined}
                            >
                              <ThreadItem
                                item={item}
                                threadId={info.threadId}
                                agent={info.agent}
                                actionable={!archived && status !== 'exited' && status !== 'error'}
                                streaming={turnActive && index === visibleItems.length - 1}
                                terminals={model.terminals}
                                permissionsByToolCall={model.permissionsByToolCall}
                                showRetry={index === retryNoticeIndex}
                                retryPending={retryPending}
                                onRetry={retryThread}
                                showRestore={index === restoreNoticeIndex}
                                onRestore={() => restoreFailedPromptToComposer(index)}
                                authOffer={
                                  index === authOfferNoticeIndex ? authOffer : authHistoryOffer
                                }
                                onAuthAction={runAuthAction}
                                runningAuthAction={runningAuthAction}
                                onResend={resendMessage}
                                canSendHere={canPrompt || canQueue}
                                isLatestUserTurn={index === lastUserTurnIndex}
                              />
                            </MessageScrollerItem>
                          );
                        })}
                        {turnActive ? (
                          status === 'awaiting_permission' ? (
                            <div
                              className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm shimmer"
                              data-testid="agent-thread-awaiting-permission"
                            >
                              <span>{t`Waiting for your approval`}</span>
                            </div>
                          ) : (
                            <WorkingAvatar
                              status={workingStatusText(activeToolKind(model.items), thinkingLine)}
                              className="px-1 py-1"
                              testId="agent-thread-working"
                            />
                          )
                        ) : status === 'installing' || status === 'spawning' ? (
                          <div
                            className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm"
                            data-testid="agent-thread-starting"
                          >
                            <Spinner className="size-3.5" aria-hidden="true" />
                            <span className="shimmer">{startStatusMessage}</span>
                          </div>
                        ) : null}
                      </MessageScrollerContent>
                    </MessageScrollerViewport>
                    <MessageScrollerButton direction="end" />
                  </MessageScroller>
                </MessageScrollerProvider>
              )}
              <div role="status" aria-live="polite" data-testid="agent-thread-drop-notice">
                {dropNotice !== null ? (
                  <div
                    key={dropNotice.id}
                    className="border-t bg-muted/40 px-3 py-1.5 text-muted-foreground text-xs"
                  >
                    {dropNotice.text}
                  </div>
                ) : uploadsPending ? (
                  <p className="sr-only">
                    <Plural
                      value={pendingUploads.length}
                      one="Uploading # attachment"
                      other="Uploading # attachments"
                    />
                  </p>
                ) : null}
              </div>
              <div role="status" aria-live="polite" data-testid="agent-thread-stalled-region">
                {info.stalledSince !== undefined &&
                turnActive &&
                !cancelPending &&
                !cancelStalled ? (
                  <div
                    className="flex items-center gap-2 border-warning/30 border-t bg-warning/5 px-3 py-1.5 text-warning text-xs"
                    data-testid="agent-thread-stalled"
                  >
                    <span className="flex-1">
                      {t`Nothing from ${agentName} for ${plural(stalledMinutes, {
                        one: '# minute',
                        other: '# minutes',
                      })}. If it looks stuck, Stop and try again.`}
                    </span>
                  </div>
                ) : null}
              </div>
              {info.steer !== undefined && !archived ? (
                <div
                  className="flex items-center gap-2 border-t bg-muted/40 px-3 py-1.5 text-muted-foreground text-xs"
                  data-testid="agent-thread-steer-pending"
                >
                  <Spinner className="size-3.5 shrink-0" aria-hidden="true" />
                  <span className="shrink-0">{t`Steering — waiting for the current run to stop…`}</span>
                  <span className="min-w-0 flex-1 truncate text-foreground/80">
                    {info.steer.content}
                  </span>
                </div>
              ) : null}
              {cancelStalled && turnActive ? (
                <div
                  className="flex items-center gap-2 border-warning/30 border-t bg-warning/5 px-3 py-1.5 text-warning text-xs"
                  data-testid="agent-thread-cancel-stalled"
                >
                  <span className="flex-1">
                    {t`The agent isn't stopping. Force stop closes this chat and quits the agent.`}
                  </span>
                  <Button
                    type="button"
                    size="sm"
                    variant="destructive"
                    className="h-6 text-xs"
                    onClick={() => client.closeThread(info.threadId)}
                    data-testid="agent-thread-force-stop"
                  >
                    {t`Force stop`}
                  </Button>
                </div>
              ) : null}
              <span
                className="sr-only"
                role="status"
                aria-live="polite"
                data-testid="agent-thread-auth-status"
              >
                {runningAuthAction === null ? '' : authActionAnnouncement(runningAuthAction)}
              </span>
              <span
                className="sr-only"
                role="status"
                aria-live="polite"
                data-testid="agent-thread-resume-status"
              >
                {resumeFailureMessage}
              </span>
              <span
                className="sr-only"
                role="status"
                aria-live="polite"
                aria-atomic="true"
                data-testid="agent-thread-start-status"
              >
                {announcedStartStatus}
              </span>
              <span
                className="sr-only"
                role="status"
                aria-live="polite"
                aria-atomic="true"
                data-testid="agent-thread-crash-status"
              >
                {crashAnnouncement}
              </span>
              {retryFailure !== null && canRetry && !retryPending ? (
                <RetryFailedNotice key={retryFailure} agentName={agentName} detail={retryFailure} />
              ) : null}
              {resumeFailureMessage !== '' && !newChatOfferInTranscript ? (
                <div
                  className="flex items-center gap-2 border-warning/30 border-t bg-warning/5 px-3 py-1.5 text-warning text-xs"
                  data-testid="agent-thread-resume-failed"
                >
                  <span className="flex-1">{resumeFailureMessage}</span>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    className="h-6 shrink-0 text-xs"
                    disabled={runningAuthAction !== null}
                    aria-busy={runningAuthAction === 'new-chat'}
                    onClick={startFreshThread}
                    data-testid="agent-thread-resume-fallback-new"
                  >
                    {runningAuthAction === 'new-chat' ? (
                      <Spinner className="size-3" aria-hidden="true" />
                    ) : null}
                    {t`New chat with ${agentName}`}
                  </Button>
                </div>
              ) : null}
              <ThreadComposer
                info={info}
                hasStartedWork={threadHasUserMessage({ items })}
                onNewChat={startFreshThread}
                composerRef={composerRef}
                onComposerReady={() => {
                  flushStagedThreadDraft(info.threadId);
                  flushStagedThreadDraftContent(info.threadId);
                }}
                mentionRecency={mentionRecency}
                onSubmit={submit}
                canPrompt={canPrompt}
                canQueue={canQueue}
                turnActive={turnActive}
                cancelPending={cancelPending}
                onCancel={requestCancel}
                onSteer={requestSteer}
                status={status}
                archived={archived}
                resumePending={resumePending}
                usage={model?.tokenUsage ?? null}
                selectedCommentCount={selectedCommentCount}
                selectedCommentDocs={selectedCommentDocs}
                hasQueuedComments={hasQueuedComments}
                onAttachComments={() => setCommentsAttached(true)}
                onDismissComments={() => setCommentsAttached(false)}
                pendingAttachments={pendingAttachments}
                pendingUploads={pendingUploads}
                imagesAccepted={imagesAccepted}
                onIngestImageFiles={ingestFiles}
                onIngestAllFiles={ingestFiles}
                onRemovePendingAttachment={removePendingAttachment}
              />
              {dragActive ? <ChatPanelDropOverlay onDismiss={() => setDragActive(false)} /> : null}
            </ReferenceRulesContext>
          </DocPathResolverReadyContext>
        </div>
      </ImagePreviewContext.Provider>
    </MentionRecencyContext>
  );
}

function PermissionPostureBadge({ info }: { info: ThreadInfo }): ReactNode {
  const { t } = useLingui();
  if (deriveAgentPosture(info.agent.id, info.modes) !== 'autonomous') return null;
  const label = t`${info.agent.name} acts without asking — OpenKnowledge can't add permission prompts for it`;
  const focusRing =
    'inline-flex rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50';
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <span
          // oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- a status indicator whose detail lives in its tooltip must be focusable or keyboard users can never surface it — same rationale as the tooltip-on-disabled-button span wrapper.
          tabIndex={0}
          role="img"
          aria-label={label}
          className={focusRing}
        >
          <span className="inline-flex shrink-0 text-warning" data-testid="agent-thread-posture">
            <ShieldAlert className="size-3.5" aria-hidden="true" />
          </span>
        </span>
      </TooltipTrigger>
      <TooltipContent side="bottom" className="max-w-64">
        {label}
      </TooltipContent>
    </Tooltip>
  );
}

function ThreadHeader({
  info,
  followFile,
  onToggleFollow,
}: {
  info: ThreadInfo;
  followFile: boolean;
  onToggleFollow: () => void;
}): ReactNode {
  const { t } = useLingui();
  return (
    <div className="flex items-center gap-2 px-3 pb-1.5 pt-0">
      <span className="min-w-0 truncate font-medium text-1sm">{info.title}</span>
      {info.agent.version !== undefined && info.agent.version !== '' ? (
        <span
          className="shrink-0 text-[10px] text-muted-foreground tabular-nums"
          title={t`${info.agent.name} version ${info.agent.version}`}
          data-testid="agent-thread-agent-version"
        >
          {info.agent.version}
        </span>
      ) : null}
      <div className="ml-auto flex shrink-0 items-center gap-1.5">
        <PermissionPostureBadge info={info} />
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              type="button"
              variant="ghost"
              size="icon-xs"
              className={cn(
                'rounded-md',
                followFile
                  ? 'bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary'
                  : 'text-muted-foreground',
              )}
              aria-pressed={followFile}
              aria-label={t`Follow the agent's edits`}
              onClick={onToggleFollow}
              data-testid="agent-thread-follow-toggle"
            >
              <MousePointer2 className="size-3.5" aria-hidden="true" />
            </Button>
          </TooltipTrigger>
          <TooltipContent side="bottom">
            {followFile ? t`Following the agent's edits` : t`Follow the agent's edits`}
          </TooltipContent>
        </Tooltip>
      </div>
    </div>
  );
}

type SelectConfigOption = Extract<SessionConfigOption, { type: 'select' }>;
type BooleanConfigOption = Extract<SessionConfigOption, { type: 'boolean' }>;

function currentSelectEntry(
  option: SelectConfigOption,
): { value: string; name: string } | undefined {
  for (const entry of option.options) {
    if ('value' in entry) {
      if (entry.value === option.currentValue) return entry;
      continue;
    }
    const current = entry.options.find((candidate) => candidate.value === option.currentValue);
    if (current !== undefined) return current;
  }
  return undefined;
}

function humanizeValueId(id: string): string {
  const spaced = id
    .replace(/[_-]+/g, ' ')
    .replace(/([a-z])([A-Z])/g, '$1 $2')
    .trim();
  return spaced.charAt(0).toUpperCase() + spaced.slice(1);
}

function selectOptionName(option: SelectConfigOption): string {
  return currentSelectEntry(option)?.name ?? humanizeValueId(option.currentValue);
}

function selectOptionHeaderText(option: SelectConfigOption): string {
  const entry = currentSelectEntry(option);
  if (entry === undefined) return humanizeValueId(option.currentValue);
  return resolveDefaultOptionLabel(option) ?? entry.name;
}

function selectOptionSummary(agentId: string, option: SelectConfigOption): string {
  const entry = currentSelectEntry(option);
  if (entry === undefined) return humanizeValueId(option.currentValue);
  return configValueHint(agentId, option.id, entry.value) ?? selectOptionHeaderText(option);
}

function hasSelectValues(option: SelectConfigOption): boolean {
  return option.options.some((entry) => ('value' in entry ? true : entry.options.length > 0));
}

function flattenSelectValues(option: SelectConfigOption): Array<{ id: string; name: string }> {
  const flat: Array<{ id: string; name: string }> = [];
  for (const entry of option.options) {
    if ('value' in entry) flat.push({ id: entry.value, name: entry.name });
    else for (const grouped of entry.options) flat.push({ id: grouped.value, name: grouped.name });
  }
  return flat;
}

interface ModeSurface {
  configId: string | null;
  currentId: string;
  currentName: string;
  values: ReadonlyArray<{ id: string; name: string }>;
}

function deriveModeSurface(info: ThreadInfo): ModeSurface | null {
  const modeOption = (info.configOptions ?? []).find(
    (option): option is SelectConfigOption =>
      option.type === 'select' && option.category === 'mode' && hasSelectValues(option),
  );
  if (modeOption !== undefined) {
    return {
      configId: modeOption.id,
      currentId: modeOption.currentValue,
      currentName: selectOptionName(modeOption),
      values: flattenSelectValues(modeOption),
    };
  }
  const modes = info.modes;
  if (modes != null && modes.availableModes.length > 1) {
    return {
      configId: null,
      currentId: modes.currentModeId,
      currentName:
        modes.availableModes.find((mode) => mode.id === modes.currentModeId)?.name ??
        humanizeValueId(modes.currentModeId),
      values: modes.availableModes.map((mode) => ({ id: mode.id, name: mode.name })),
    };
  }
  return null;
}

function AgentSettingsPopover({
  info,
  hasStartedWork,
  onNewChat,
  onReportProblem,
  triggerRef,
}: {
  info: ThreadInfo;
  hasStartedWork: boolean;
  onNewChat: () => void;
  onReportProblem?: () => void;
  triggerRef?: RefObject<HTMLButtonElement | null>;
}): ReactNode {
  const { i18n, t } = useLingui();
  const reasonId = useId();
  const client = getAgentThreadClient();
  const settingsKey = agentSettingsKey(info.agent);
  const modelCandidates = useModelCandidates(info.agent.id);
  const selectedModel =
    (info.configOptions ?? []).find(
      (option) => option.type === 'select' && option.category === 'model',
    )?.currentValue ?? null;
  const contextChoices = contextChoicesForModel(
    modelCandidates,
    typeof selectedModel === 'string' ? selectedModel : null,
  );
  const currentContextWindow = info.contextWindow ?? null;
  const canChangeContextWindow = info.archived !== true && !hasStartedWork;
  const applyConfig = (option: SessionConfigOption, value: string | boolean): void => {
    client.setConfigOption(info.threadId, option.id, value);
    rememberAgentConfigOption(settingsKey, option.id, value);
  };
  const configOptions = (info.configOptions ?? []).filter(
    (option) => option.type === 'boolean' || hasSelectValues(option),
  );
  const modeSurface = deriveModeSurface(info);
  const showLegacyModes = modeSurface !== null && modeSurface.configId === null;
  if (configOptions.length === 0 && !showLegacyModes) {
    const settled =
      info.status === 'ready' ||
      info.status === 'running' ||
      info.status === 'awaiting_permission' ||
      info.status === 'exited';
    const reason = settled
      ? t`${info.agent.name} doesn't offer any settings to adjust`
      : t`${info.agent.name} hasn't reported its settings yet`;
    const tone: AgentSettingsTone = onReportProblem === undefined ? 'disabled' : 'muted';
    const trigger = (
      <AgentSettingsTrigger
        ref={triggerRef}
        label={t`Agent settings`}
        tone={tone}
        className="max-w-48 gap-1"
        aria-describedby={tone === 'disabled' ? reasonId : undefined}
      >
        <span className={cn('truncate', AGENT_SETTINGS_TONE_TEXT[tone])}>{t`Settings`}</span>
      </AgentSettingsTrigger>
    );
    if (onReportProblem !== undefined) {
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger>
          <DropdownMenuContent
            align="end"
            className="w-60"
            data-bug-report-launcher=""
            data-testid="agent-thread-settings-popover"
          >
            <DropdownMenuLabel className="font-normal text-muted-foreground">
              {reason}
            </DropdownMenuLabel>
            <ReportProblemItem onSelect={onReportProblem} />
          </DropdownMenuContent>
        </DropdownMenu>
      );
    }
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <span className="inline-flex cursor-not-allowed">
            {trigger}
            <span id={reasonId} className="sr-only">
              {reason}
            </span>
          </span>
        </TooltipTrigger>
        <TooltipContent side="bottom">{reason}</TooltipContent>
      </Tooltip>
    );
  }

  const legacyModeName = showLegacyModes ? modeSurface.currentName : undefined;

  const effortSelect = configOptions.find(
    (option): option is SelectConfigOption =>
      option.type === 'select' && option.category === 'thought_level',
  );
  const primarySelect =
    configOptions.find(
      (option): option is SelectConfigOption =>
        option.type === 'select' && option.category === 'model',
    ) ?? configOptions.find((option): option is SelectConfigOption => option.type === 'select');
  const fastToggle = configOptions.find(
    (option): option is BooleanConfigOption =>
      option.type === 'boolean' && option.category === 'model_config' && /fast/i.test(option.id),
  );
  const triggerText =
    primarySelect !== undefined
      ? selectOptionHeaderText(primarySelect)
      : (legacyModeName ?? t`Settings`);
  const effortText =
    effortSelect !== undefined && effortSelect !== primarySelect
      ? selectOptionHeaderText(effortSelect)
      : null;
  const fastOn = fastToggle?.currentValue === true;
  const readOnlyShellOn = info.chatGrants?.includes('read_only_shell') === true;
  const headerSummary = formatUnitList(
    [
      triggerText,
      fastOn ? t`Fast` : null,
      effortText,
      readOnlyShellOn ? t`Read-only allowed` : null,
    ].filter((part): part is string => part !== null),
    i18n.locale,
  );
  const settingsLabel =
    info.archived === true
      ? t`Agent settings — ${headerSummary} — changes apply when you pick this conversation back up`
      : t`Agent settings — ${headerSummary}`;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <AgentSettingsTrigger
          ref={triggerRef}
          label={settingsLabel}
          className="min-w-0 max-w-sm shrink gap-1.5"
        >
          <span className="min-w-0 truncate">{triggerText}</span>
          {fastOn ? (
            <span className="shrink-0 text-muted-foreground" data-testid="agent-thread-fast">
              {t`Fast`}
            </span>
          ) : null}
          {effortText !== null ? (
            <span className="shrink-0 text-muted-foreground" data-testid="agent-thread-effort">
              {effortText}
            </span>
          ) : null}
          {readOnlyShellOn ? (
            <span
              className="shrink-0 text-muted-foreground"
              data-testid="agent-thread-read-only-shell"
            >
              {t`Read-only allowed`}
            </span>
          ) : null}
        </AgentSettingsTrigger>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        align="end"
        className="w-60"
        data-bug-report-launcher=""
        data-testid="agent-thread-settings-popover"
      >
        {info.archived === true ? (
          <DropdownMenuLabel
            className="font-normal text-muted-foreground"
            data-testid="agent-thread-settings-archived-hint"
          >
            {t`Applies when you pick this conversation back up`}
          </DropdownMenuLabel>
        ) : null}
        {configOptions.map((option) =>
          option.type === 'select' ? (
            <ConfigSelectSub
              key={option.id}
              agentId={info.agent.id}
              option={option}
              onSelect={(value) => applyConfig(option, value)}
            />
          ) : (
            <ConfigBooleanItem
              key={option.id}
              option={option}
              onCheckedChange={(value) => applyConfig(option, value)}
            />
          ),
        )}
        <ContextWindowSub
          choices={contextChoices}
          currentTokens={currentContextWindow}
          canApply={canChangeContextWindow}
          onSelect={(tokens) => {
            void client.setContextWindow(info.threadId, tokens).then(
              () => rememberAgentContextWindow(settingsKey, tokens),
              (err: unknown) => {
                const code = err instanceof ThreadContextWindowError ? err.code : null;
                if (code === 'spawn-failed') {
                  toast.error(
                    t`${info.agent.name} couldn't restart on that context window. Use Try again to bring it back.`,
                  );
                  return;
                }
                if (code === 'timeout') {
                  toast.error(
                    t`${info.agent.name} didn't confirm the context window change. Check the conversation before picking again.`,
                  );
                  return;
                }
                toast.error(t`${info.agent.name} kept its current context window.`);
              },
            );
          }}
          onNewChat={onNewChat}
        />
        {showLegacyModes ? (
          <ConfigSelectSub
            agentId={info.agent.id}
            option={{
              id: 'legacy-mode',
              name: t`Agent mode`,
              category: 'mode',
              type: 'select',
              currentValue: modeSurface.currentId,
              options: modeSurface.values.map((mode) => ({ value: mode.id, name: mode.name })),
            }}
            onSelect={(modeId) => {
              client.setMode(info.threadId, modeId);
              rememberAgentMode(settingsKey, modeId);
            }}
          />
        ) : null}
        {info.chatGrants?.includes('read_only_shell') ? (
          <DropdownMenuItem
            onSelect={() => client.setChatGrant(info.threadId, 'read_only_shell', false)}
            data-testid="agent-thread-settings-read-only-shell"
          >
            <span className="flex min-w-0 flex-col">
              <span>{t`Ask again before read-only commands`}</span>
              <span className="text-muted-foreground text-xs">{t`They run without asking while this chat is open`}</span>
            </span>
          </DropdownMenuItem>
        ) : null}
        {onReportProblem !== undefined ? <ReportProblemItem onSelect={onReportProblem} /> : null}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

type AgentSettingsTone = 'normal' | 'muted' | 'disabled';

const AGENT_SETTINGS_TONE_TEXT: Record<AgentSettingsTone, string | undefined> = {
  normal: undefined,
  muted: 'text-muted-foreground',
  disabled: 'text-muted-foreground/50',
};

function AgentSettingsTrigger({
  ref,
  label,
  tone = 'normal',
  className,
  children,
  ...buttonProps
}: ComponentProps<typeof Button> & { label: string; tone?: AgentSettingsTone }): ReactNode {
  return (
    <Button
      {...buttonProps}
      ref={ref}
      type="button"
      variant="ghost"
      className={cn('h-7 rounded-md pl-1.5 pr-1! text-xs', className)}
      aria-label={label}
      aria-disabled={tone === 'disabled' || undefined}
      data-testid="agent-thread-settings"
    >
      {children}
      <ChevronDown
        className={cn('size-3.5', AGENT_SETTINGS_TONE_TEXT[tone])}
        data-icon="inline-end"
        aria-hidden="true"
      />
    </Button>
  );
}

function ReportProblemItem({ onSelect }: { onSelect: () => void }): ReactNode {
  const { t } = useLingui();
  return (
    <>
      <DropdownMenuSeparator />
      <DropdownMenuItem onSelect={onSelect} data-testid="agent-thread-report-problem">
        {t`Report a problem with this chat…`}
      </DropdownMenuItem>
    </>
  );
}

function ContextWindowSub({
  choices,
  currentTokens,
  canApply,
  onSelect,
  onNewChat,
}: {
  choices: readonly number[];
  currentTokens: number | null;
  canApply: boolean;
  onSelect: (tokens: number) => void;
  onNewChat: () => void;
}): ReactNode {
  const { t } = useLingui();
  if (choices.length < 2) return null;
  const summary = currentTokens === null ? t`Default` : formatContextTokens(currentTokens);
  const contextWindowLabel = t`Context window`;
  return (
    <DropdownMenuSub>
      <DropdownMenuSubTrigger className="gap-2" data-testid="agent-thread-context-window">
        <span className="min-w-0 truncate" title={contextWindowLabel}>
          {contextWindowLabel}
        </span>
        <span
          className="min-w-16 flex-1 truncate text-end text-1sm text-muted-foreground"
          title={summary}
        >
          {summary}
        </span>
      </DropdownMenuSubTrigger>
      <DropdownMenuSubContent className="max-w-72 overscroll-contain">
        <DropdownMenuLabel>{t`Context window`}</DropdownMenuLabel>
        {canApply ? (
          <DropdownMenuRadioGroup
            value={currentTokens === null ? undefined : String(currentTokens)}
            onValueChange={(next) => onSelect(Number(next))}
          >
            {choices.map((tokens) => (
              <DropdownMenuRadioItem
                key={tokens}
                value={String(tokens)}
                data-testid={`agent-thread-context-window-${tokens}`}
              >
                {formatContextTokens(tokens)}
              </DropdownMenuRadioItem>
            ))}
          </DropdownMenuRadioGroup>
        ) : (
          <>
            <DropdownMenuLabel
              className="font-normal text-muted-foreground"
              data-testid="agent-thread-context-window-locked"
            >
              {t`This conversation keeps the window it started with. A new chat can use a different one.`}
            </DropdownMenuLabel>
            <DropdownMenuItem
              onSelect={onNewChat}
              data-testid="agent-thread-context-window-new-chat"
            >
              {t`New chat with a different window`}
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuSubContent>
    </DropdownMenuSub>
  );
}

function formatContextTokens(tokens: number): string {
  if (tokens >= 1_000_000) {
    const millions = tokens / 1_000_000;
    return `${Number.isInteger(millions) ? millions : millions.toFixed(1)}M`;
  }
  if (tokens >= 1_000) return `${Math.round(tokens / 1_000)}K`;
  return String(tokens);
}

function ConfigSelectSub({
  agentId,
  option,
  onSelect,
}: {
  agentId: string;
  option: SelectConfigOption;
  onSelect: (valueId: string) => void;
}): ReactNode {
  const withHint = <E extends { value: string; name: string; description?: string | null }>(
    entry: E,
  ): E =>
    entry.description
      ? entry
      : { ...entry, description: configValueHint(agentId, option.id, entry.value) ?? undefined };
  const entries: ReadonlyArray<(typeof option.options)[number]> = option.options;
  const flat = entries.filter(
    (entry): entry is Extract<(typeof entries)[number], { value: string }> => 'value' in entry,
  );
  const groups = entries.filter(
    (entry): entry is Extract<(typeof entries)[number], { group: string }> => 'group' in entry,
  );
  return (
    <DropdownMenuSub>
      <DropdownMenuSubTrigger className="gap-2" data-testid={`agent-thread-config-${option.id}`}>
        <span className="min-w-0 truncate" title={option.name}>
          {option.name}
        </span>
        <span
          className="min-w-16 flex-1 truncate text-end text-1sm text-muted-foreground"
          title={selectOptionSummary(agentId, option)}
        >
          {selectOptionSummary(agentId, option)}
        </span>
      </DropdownMenuSubTrigger>
      <DropdownMenuSubContent className="max-h-[min(22rem,var(--radix-dropdown-menu-content-available-height))] max-w-72 overscroll-contain">
        <DropdownMenuLabel>{option.name}</DropdownMenuLabel>
        <DropdownMenuRadioGroup value={option.currentValue} onValueChange={onSelect}>
          {flat.map((entry) => (
            <ConfigRadioItem key={entry.value} entry={withHint(entry)} />
          ))}
          {groups.map((group) => (
            <Fragment key={group.group}>
              {group.name !== option.name ? (
                <DropdownMenuLabel className="font-normal text-muted-foreground">
                  {group.name}
                </DropdownMenuLabel>
              ) : null}
              {group.options.map((entry) => (
                <ConfigRadioItem key={entry.value} entry={withHint(entry)} />
              ))}
            </Fragment>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuSubContent>
    </DropdownMenuSub>
  );
}

function ConfigRadioItem({
  entry,
}: {
  entry: { value: string; name: string; description?: string | null };
}): ReactNode {
  return (
    <DropdownMenuRadioItem
      value={entry.value}
      className="items-start"
      data-testid={`agent-thread-config-option-${entry.value}`}
    >
      <div className="flex min-w-0 flex-col">
        <span className="truncate">{entry.name}</span>
        {entry.description ? (
          <span className="line-clamp-2 text-1sm text-muted-foreground">{entry.description}</span>
        ) : null}
      </div>
    </DropdownMenuRadioItem>
  );
}

function ConfigBooleanItem({
  option,
  onCheckedChange,
}: {
  option: Extract<SessionConfigOption, { type: 'boolean' }>;
  onCheckedChange: (value: boolean) => void;
}): ReactNode {
  return (
    <DropdownMenuCheckboxItem
      checked={option.currentValue}
      onCheckedChange={onCheckedChange}
      onSelect={(event) => event.preventDefault()}
      className="items-start justify-between gap-4 pr-2 [&_[data-slot=dropdown-menu-checkbox-item-indicator]]:hidden"
      data-testid={`agent-thread-config-${option.id}`}
    >
      <div className="flex min-w-0 flex-col">
        <span>{option.name}</span>
        {option.description ? (
          <span className="text-1sm text-muted-foreground">{option.description}</span>
        ) : null}
      </div>
      <Switch
        checked={option.currentValue}
        size="sm"
        aria-hidden="true"
        tabIndex={-1}
        className="pointer-events-none mt-0.5"
      />
    </DropdownMenuCheckboxItem>
  );
}

function ThreadTranscriptSkeleton(): ReactNode {
  const { t } = useLingui();
  const [announced, setAnnounced] = useState('');
  useEffect(() => {
    setAnnounced(t`Loading the chat`);
  }, [t]);
  return (
    <div className="flex flex-col gap-6 pt-2">
      <div aria-live="polite" className="sr-only" role="status">
        {announced}
      </div>
      <div aria-hidden="true" className="flex flex-col gap-6">
        <div className="flex justify-end">
          <Skeleton className="h-12 w-3/5 rounded-2xl rounded-br-xs" />
        </div>
        <div className="flex flex-col gap-2">
          <Skeleton className="h-3.5 w-11/12" />
          <Skeleton className="h-3.5 w-4/5" />
          <Skeleton className="h-3.5 w-2/3" />
        </div>
        <div className="flex justify-end">
          <Skeleton className="h-8 w-2/5 rounded-2xl rounded-br-xs" />
        </div>
        <div className="flex flex-col gap-2">
          <Skeleton className="h-3.5 w-5/6" />
          <Skeleton className="h-3.5 w-3/4" />
        </div>
      </div>
    </div>
  );
}

function ThreadAuthOfferButton({
  offer,
  runningAuthAction,
  onAction,
}: {
  offer: ThreadAuthOfferWithoutSignIn;
  runningAuthAction: ThreadAuthActionKind | null;
  onAction: (kind: ThreadAuthActionKind) => void;
}): ReactNode {
  if (offer.actionLabel === null) return null;
  const busy = runningAuthAction === offer.kind;
  return (
    <Button
      type="button"
      variant="outline"
      size="sm"
      className="h-6 text-xs"
      disabled={runningAuthAction !== null}
      aria-busy={busy}
      onClick={() => onAction(offer.kind)}
      data-testid="agent-thread-auth-action"
      data-auth-offer-kind={offer.kind}
    >
      {busy ? <Spinner className="size-3" aria-hidden="true" /> : null}
      {offer.actionLabel}
    </Button>
  );
}

function ThreadEmptyState({
  status,
  displayedStartStatus,
  justSettled,
  archived,
  agent,
  authOffer,
  onAuthAction,
  runningAuthAction,
}: {
  status: ThreadInfo['status'];
  displayedStartStatus: ThreadInfo['status'];
  justSettled: boolean;
  archived: boolean;
  agent: ThreadInfo['agent'];
  authOffer: ThreadAuthOfferWithoutSignIn;
  onAuthAction: (kind: ThreadAuthActionKind) => void;
  runningAuthAction: ThreadAuthActionKind | null;
}): ReactNode {
  const { t } = useLingui();
  const agentName = agentDisplayName(agent.name);
  const [showSettle, setShowSettle] = useState(justSettled);
  const [previousJustSettled, setPreviousJustSettled] = useState(justSettled);
  if (previousJustSettled !== justSettled) {
    setPreviousJustSettled(justSettled);
    if (justSettled) setShowSettle(true);
  }

  if (archived) {
    return <ThreadTranscriptSkeleton />;
  }

  if (status === 'ready') {
    return (
      <div className="flex h-full items-center justify-center px-6">
        <div
          className={cn('flex items-center gap-2.5', showSettle && 'animate-agent-ready-settle')}
          data-testid="agent-thread-ready"
          onAnimationEnd={(event) => {
            if (event.target === event.currentTarget) setShowSettle(false);
          }}
        >
          <RegisteredAgentIcon agentId={agent.id} iconUrl={agent.iconUrl} className="size-6" />
          <p className="text-foreground/70 text-center text-base">{t`What should we work on?`}</p>
        </div>
      </div>
    );
  }

  if (authOffer.actionLabel !== null) {
    const waitingOnSignIn = isSignInWaitingStatus(status);
    return (
      <div
        className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center"
        data-testid="agent-thread-auth-offer"
      >
        <RegisteredAgentIcon
          agentId={agent.id}
          iconUrl={agent.iconUrl}
          className={cn('size-12', !waitingOnSignIn && 'opacity-25 grayscale')}
        />
        <p className="text-muted-foreground text-sm">{authOffer.headline}</p>
        <ThreadAuthOfferButton
          offer={authOffer}
          runningAuthAction={runningAuthAction}
          onAction={onAuthAction}
        />
      </div>
    );
  }

  const loadingMessage =
    displayedStartStatus === 'installing'
      ? t`Installing ${agentName}…`
      : displayedStartStatus === 'spawning'
        ? t`Starting ${agentName}…`
        : status === 'authenticating'
          ? t`Signing in to ${agentName}…`
          : t`Connecting to ${agentName}…`;
  return (
    <div
      className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center"
      data-testid="agent-thread-starting-empty-state"
    >
      <RegisteredAgentIcon
        agentId={agent.id}
        iconUrl={agent.iconUrl}
        className="size-8 animate-agent-mark-breathe opacity-25 grayscale motion-reduce:animate-none"
      />
      <p className="shimmer-subtle text-sm">{loadingMessage}</p>
    </div>
  );
}

function ScrollToEndBridge({
  apiRef,
}: {
  apiRef: RefObject<ReturnType<typeof useMessageScroller> | null>;
}): null {
  const api = useMessageScroller();
  useEffect(() => {
    apiRef.current = api;
    return () => {
      apiRef.current = null;
    };
  }, [api, apiRef]);
  return null;
}

function ThreadItem({
  item,
  threadId,
  agent,
  actionable,
  streaming,
  terminals,
  permissionsByToolCall,
  showRetry,
  retryPending,
  onRetry,
  showRestore,
  onRestore,
  authOffer,
  onAuthAction,
  runningAuthAction,
  onResend,
  canSendHere,
  isLatestUserTurn,
}: {
  item: RenderedItem;
  threadId: string;
  agent: ThreadInfo['agent'];
  actionable: boolean;
  streaming: boolean;
  terminals: Record<string, RenderedTerminal>;
  permissionsByToolCall: Record<string, RenderedPermission>;
  showRetry: boolean;
  retryPending: boolean;
  onRetry: () => void;
  showRestore: boolean;
  onRestore: () => void;
  authOffer: ThreadAuthOfferWithoutSignIn;
  onAuthAction: (kind: ThreadAuthActionKind) => void;
  runningAuthAction: ThreadAuthActionKind | null;
  onResend: (
    text: string,
    target: ResendTarget,
    attachments: readonly AttachmentPart[],
  ) => Promise<boolean>;
  canSendHere: boolean;
  isLatestUserTurn: boolean;
}): ReactNode {
  switch (item.kind) {
    case 'message':
      return (
        <MessageBubble
          item={item}
          streaming={streaming}
          agent={agent}
          onResend={onResend}
          canSendHere={canSendHere}
          isLatestUserTurn={isLatestUserTurn}
        />
      );
    case 'tool_call':
      return (
        <ToolCallCard
          call={item}
          terminals={terminals}
          permission={permissionsByToolCall[item.toolCallId]}
        />
      );
    case 'permission':
      return item.mergedIntoToolCall && item.resolved !== null ? null : (
        <PermissionPrompt item={item} threadId={threadId} actionable={actionable} />
      );
    case 'runtime_consent':
      return <RuntimeConsentPrompt item={item} threadId={threadId} />;
    case 'pi_bridge':
      return <PiBridgeConsentPrompt item={item} threadId={threadId} />;
    case 'notice':
      return (
        <ThreadNotice
          item={item}
          agentName={agentDisplayName(agent.name)}
          showRetry={showRetry}
          retryPending={retryPending}
          onRetry={onRetry}
          showRestore={showRestore}
          onRestore={onRestore}
          authOffer={authOffer}
          onAuthAction={onAuthAction}
          runningAuthAction={runningAuthAction}
        />
      );
    case 'agent_notice':
      return <AgentNoticeCard item={item} />;
    case 'browser_unavailable':
      return <BrowserUnavailableNotice item={item} />;
  }
}

function BrowserUnavailableNotice({
  item,
}: {
  item: Extract<RenderedItem, { kind: 'browser_unavailable' }>;
}): ReactNode {
  const { t } = useLingui();
  return (
    <div
      role="note"
      className="rounded-md border border-border bg-muted/40 px-2 py-1.5 text-muted-foreground text-xs"
      data-testid="agent-thread-browser-unavailable"
    >
      {item.reason === 'no-node'
        ? t`The browser isn't available in this chat because no Node.js install that can start it was found. Install Node.js, then start a new chat.`
        : t`The browser isn't available in this chat because it couldn't be set up. OpenKnowledge's log has the details.`}
    </div>
  );
}

function AgentNoticeCard({
  item,
}: {
  item: Extract<RenderedItem, { kind: 'agent_notice' }>;
}): ReactNode {
  const { t } = useLingui();
  return (
    <div
      role="note"
      className="rounded-md border border-warning/40 px-2 py-1.5 text-xs"
      data-testid="agent-thread-agent-notice"
    >
      <p className="flex items-center gap-1.5 font-medium text-warning">
        <TriangleAlert aria-hidden="true" className="size-3.5 shrink-0" />
        {t`Warning`}
      </p>
      <div className="mt-1 wrap-break-word text-foreground">
        <AgentMarkdown text={item.text} />
      </div>
    </div>
  );
}

function ThoughtBlock({
  item,
  streaming,
}: {
  item: Extract<RenderedItem, { kind: 'message' }>;
  streaming: boolean;
}): ReactNode {
  const { t } = useLingui();
  const [open, setOpen] = useState(false);
  return (
    <div data-testid="agent-thread-thought">
      <Button
        type="button"
        variant="ghost"
        size="sm"
        className="h-auto w-full justify-start gap-1 px-0 py-0.5 text-[10px] text-muted-foreground uppercase tracking-wide hover:bg-transparent"
        onClick={() => setOpen((value) => !value)}
        aria-expanded={open}
        data-testid="agent-thread-thought-toggle"
      >
        {open ? (
          <ChevronDown className="size-3" aria-hidden="true" />
        ) : (
          <ChevronRight className="size-3" aria-hidden="true" />
        )}
        {t`Thinking`}
        {open ? null : (
          <span className="min-w-0 flex-1 truncate text-left font-normal text-xs normal-case italic tracking-normal">
            {thoughtPreview(item.text, streaming)}
          </span>
        )}
      </Button>
      {open ? (
        <div className="px-1 text-muted-foreground text-xs italic **:font-normal! **:text-xs!">
          <AgentMarkdown text={item.text} />
        </div>
      ) : null}
    </div>
  );
}

function SignInOutput({ output }: { output?: string[] }): ReactNode {
  const { t } = useLingui();
  const [copied, setCopied] = useState(false);
  useEffect(() => {
    if (!copied) return;
    const timer = setTimeout(() => setCopied(false), COMPLETION_CHECK_MS);
    return () => clearTimeout(timer);
  }, [copied]);
  const parsed = output === undefined || output.length === 0 ? null : parseSignInOutput(output);
  const empty =
    parsed === null ||
    (parsed.code === undefined && parsed.url === undefined && parsed.lines.length === 0);

  const copyCode = (value: string): void => {
    void navigator.clipboard
      ?.writeText(value)
      .then(() => setCopied(true))
      .catch(() => {});
  };

  const liveRegion = (
    <div className="sr-only" role="status" aria-live="polite">
      {copied ? t`Code copied` : ''}
    </div>
  );
  if (empty) return liveRegion;
  const { code, url, lines } = parsed;

  return (
    <div
      className="mt-1 flex flex-col items-center gap-1.5"
      data-testid="agent-thread-sign-in-output"
    >
      {liveRegion}
      {code !== undefined ? (
        <Button
          type="button"
          variant="outline"
          className="h-auto w-full select-text py-1.5 font-mono text-base tracking-[0.2em]"
          onClick={() => copyCode(code)}
          aria-label={t`Copy the code ${code}`}
          data-testid="agent-thread-sign-in-code"
        >
          {copied ? <Check className="size-3.5" aria-hidden="true" /> : null}
          {code}
        </Button>
      ) : null}
      {url !== undefined ? (
        <a
          href={url}
          target="_blank"
          rel="noreferrer"
          className="text-muted-foreground text-xs underline underline-offset-2 hover:text-foreground"
          onClick={(e) => dispatchExternalLinkClick(e, url)}
          onAuxClick={(e) => dispatchExternalLinkClick(e, url)}
          data-testid="agent-thread-sign-in-url"
        >
          {shortenUrl(url)}
        </a>
      ) : null}
      {lines.length > 0 ? (
        <p className="select-text text-muted-foreground text-xs">{lines.join(' ')}</p>
      ) : null}
    </div>
  );
}

function ThreadAuthPrompt({
  failure,
  offer,
  agent,
  agentName,
  signingIn,
  signInOutput,
  showRetry,
  retryPending,
  onRetry,
  onAuthenticate,
  onAuthAction,
  runningAuthAction,
}: {
  failure: ThreadFailureDetail;
  offer: ThreadAuthOffer;
  agent: ThreadInfo['agent'];
  agentName: string;
  signingIn: boolean;
  signInOutput?: string[];
  showRetry: boolean;
  retryPending: boolean;
  onRetry: () => void;
  onAuthenticate: (methodId: string) => Promise<void>;
  onAuthAction: (kind: ThreadAuthActionKind) => void;
  runningAuthAction: ThreadAuthActionKind | null;
}): ReactNode {
  const { t } = useLingui();
  const [showDetail, setShowDetail] = useState(false);
  const [authPending, setAuthPending] = useState<string | null>(null);
  const authMethods = failure.authMethods ?? [];
  const signInMethods = clickableAuthMethods(authMethods);
  const manualMethods = manualAuthMethods(authMethods);
  const agentMessage = failure.agentMessage ?? '';
  const machineDetail = failure.machineDetail ?? '';
  const framedRetry =
    showRetry &&
    machineDetail === '' &&
    !signingIn &&
    (signInMethods.length > 0 || manualMethods.length > 0);
  const signIn = (methodId: string): void => {
    setAuthPending(methodId);
    void onAuthenticate(methodId)
      .catch((err: unknown) => {
        if (isAgentExitedError(err)) return;
        toast.error(t`Sign-in failed: ${errorText(err)}`);
      })
      .finally(() => setAuthPending(null));
  };
  return (
    <div
      className="mx-auto flex w-full max-w-72 flex-col items-center gap-4 px-2 py-6 text-center"
      data-testid="agent-thread-notice"
    >
      <RegisteredAgentIcon agentId={agent.id} iconUrl={agent.iconUrl} className="size-12" />
      <div className="sr-only" role="status" aria-live="polite">
        {signingIn ? t`Signing in to ${agentName}` : ''}
      </div>
      <div className="flex flex-col gap-1">
        {signingIn ? (
          <>
            <p className="shimmer font-medium text-sm">{t`Signing in to ${agentName}…`}</p>
            <SignInOutput output={signInOutput} />
          </>
        ) : (
          <>
            <p className="font-medium text-foreground text-sm">{offer.headline}</p>
            {agentMessage !== '' ? (
              <p className="text-muted-foreground text-1sm">{agentMessage}</p>
            ) : null}
          </>
        )}
      </div>
      {!signingIn && signInMethods.length > 0 ? (
        <div className="flex w-full flex-col gap-1.5">
          {signInMethods.map((method, index) => (
            <Button
              key={method.id}
              type="button"
              size="sm"
              variant={index === 0 ? 'default' : 'outline-mono'}
              className="w-full"
              disabled={authPending !== null}
              onClick={() => signIn(method.id)}
              data-testid="agent-thread-auth-method"
              data-auth-method-id={method.id}
            >
              {authPending === method.id ? (
                <Spinner className="size-3.5" aria-hidden="true" />
              ) : null}
              {signInMethods.length === 1 ? t`Sign in with ${method.name}` : method.name}
            </Button>
          ))}
        </div>
      ) : null}
      {!signingIn && signInMethods.length === 0 && offer.kind === 'terminal-sign-in' ? (
        <ThreadAuthOfferButton
          offer={offer}
          runningAuthAction={runningAuthAction}
          onAction={onAuthAction}
        />
      ) : null}
      {!signingIn && manualMethods.length > 0 ? (
        <ul className="flex flex-col gap-1 text-muted-foreground text-xs">
          {manualMethods.map((method) => (
            <li key={method.id} data-testid="agent-thread-auth-manual">
              {method.description !== undefined && method.description !== ''
                ? `${method.name} — ${method.description}`
                : method.name}
            </li>
          ))}
        </ul>
      ) : null}
      {showRetry || machineDetail !== '' ? (
        <div className={cn('flex items-center', framedRetry ? 'gap-1.5' : 'gap-3')}>
          {framedRetry ? (
            <span className="text-muted-foreground text-xs">{t`Already signed in?`}</span>
          ) : null}
          {showRetry ? (
            <Button
              type="button"
              variant="link-muted"
              size="xs"
              className="h-auto p-0"
              disabled={retryPending}
              onClick={onRetry}
              data-testid="agent-thread-retry"
            >
              {retryPending ? (
                <>
                  <Spinner className="size-3" aria-hidden="true" />
                  {t`Retrying…`}
                </>
              ) : (
                t`Try again`
              )}
            </Button>
          ) : null}
          {machineDetail !== '' ? (
            <Button
              type="button"
              variant="link-muted"
              size="xs"
              className="h-auto p-0"
              onClick={() => setShowDetail((open) => !open)}
              aria-expanded={showDetail}
              data-testid="agent-thread-notice-details-toggle"
            >
              {showDetail ? t`Hide details` : t`Show details`}
            </Button>
          ) : null}
        </div>
      ) : null}
      {showDetail && machineDetail !== '' ? (
        <pre
          className="w-full overflow-x-auto whitespace-pre-wrap rounded-md bg-muted/50 p-2 text-left font-mono text-[10px] text-muted-foreground"
          data-testid="agent-thread-notice-details"
        >
          {machineDetail}
        </pre>
      ) : null}
    </div>
  );
}

function RetryFailedNotice({
  agentName,
  detail,
}: {
  agentName: string;
  detail: string;
}): ReactNode {
  const { t } = useLingui();
  const [showDetail, setShowDetail] = useState(false);
  return (
    <div
      className="flex flex-col gap-1 border-destructive/30 border-t bg-destructive/5 px-3 py-1.5 text-destructive text-xs"
      data-testid="agent-thread-retry-failed"
    >
      <div className="flex items-center gap-2">
        <span className="flex-1" role="alert" data-testid="agent-thread-retry-failed-headline">
          {t`Couldn't restart ${agentName}.`}
        </span>
        {detail !== '' ? (
          <Button
            type="button"
            variant="ghost"
            size="sm"
            className="h-auto shrink-0 p-0 text-[11px] underline hover:bg-transparent"
            onClick={() => setShowDetail((open) => !open)}
            aria-expanded={showDetail}
            data-testid="agent-thread-retry-failed-details-toggle"
          >
            {showDetail ? t`Hide details` : t`Show details`}
          </Button>
        ) : null}
      </div>
      {showDetail && detail !== '' ? (
        <pre
          className="overflow-x-auto whitespace-pre-wrap font-mono text-[10px] opacity-70"
          data-testid="agent-thread-retry-failed-details"
        >
          {detail}
        </pre>
      ) : null}
    </div>
  );
}

function ThreadNotice({
  item,
  agentName,
  showRetry,
  retryPending,
  onRetry,
  showRestore,
  onRestore,
  authOffer,
  onAuthAction,
  runningAuthAction,
}: {
  item: Extract<RenderedItem, { kind: 'notice' }>;
  agentName: string;
  showRetry: boolean;
  retryPending: boolean;
  onRetry: () => void;
  showRestore: boolean;
  onRestore: () => void;
  authOffer: ThreadAuthOfferWithoutSignIn;
  onAuthAction: (kind: ThreadAuthActionKind) => void;
  runningAuthAction: ThreadAuthActionKind | null;
}): ReactNode {
  const { t } = useLingui();
  const [showDetail, setShowDetail] = useState(false);
  const failure = item.failure;
  const failureHeadline = (reason: ThreadFailureDetail['reason']): string => {
    switch (reason) {
      case 'auth-required':
        return authOffer.headline;
      case 'connect':
        return t`${agentName} couldn't start.`;
      case 'session-setup':
        return t`${agentName} couldn't start a conversation.`;
      case 'prompt':
        return t`Your message didn't reach ${agentName}.`;
      case 'exited':
        return t`${agentName} stopped unexpectedly.`;
      default: {
        const exhaustive: never = reason;
        return String(exhaustive);
      }
    }
  };
  const headline = failure === null ? null : failureHeadline(failure.reason);
  const rootCauseLine =
    failure?.machineDetail !== undefined && failure.machineDetail !== ''
      ? extractRootCauseLine(
          failure.reason === 'exited'
            ? exitStderrWindow(failure.machineDetail)
            : failure.machineDetail,
        )
      : null;
  return (
    <div
      className={cn(
        'rounded-md border px-2 py-1.5 text-xs',
        item.tone === 'error'
          ? 'border-destructive/30 bg-destructive/5 text-destructive'
          : 'border-warning/30 bg-warning/5 text-warning',
      )}
      data-testid="agent-thread-notice"
      data-notice-attempts={item.attempts}
    >
      {failure === null ? (
        item.text
      ) : (
        <>
          <p>
            {headline}
            {item.attempts > 1 ? (
              <span className="ml-1.5 opacity-70" data-testid="agent-thread-notice-attempts">
                {t`(${plural(item.attempts, { one: '# attempt', other: '# attempts' })})`}
              </span>
            ) : null}
          </p>
          {failure.agentMessage !== undefined && failure.agentMessage !== '' ? (
            <p className="mt-1 opacity-80">{failure.agentMessage}</p>
          ) : null}
          {failure.reason === 'exited' && failure.exit !== undefined ? (
            <p className="mt-1 opacity-80" data-testid="agent-thread-notice-exit-summary">
              {exitSummary(failure.exit)}
            </p>
          ) : null}
          {rootCauseLine !== null ? (
            <p
              className="mt-1 overflow-x-auto whitespace-pre-wrap break-all font-mono text-[11px]"
              data-testid="agent-thread-notice-root-cause"
            >
              {rootCauseLine}
            </p>
          ) : null}
          {failure.machineDetail !== undefined && failure.machineDetail !== '' ? (
            <>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="mt-1 h-auto p-0 text-[11px] underline hover:bg-transparent"
                onClick={() => setShowDetail((open) => !open)}
                aria-expanded={showDetail}
                data-testid="agent-thread-notice-details-toggle"
              >
                {showDetail ? t`Hide details` : t`Show details`}
              </Button>
              {showDetail ? (
                <pre
                  className="mt-1 overflow-x-auto whitespace-pre-wrap font-mono text-[10px] opacity-70"
                  data-testid="agent-thread-notice-details"
                >
                  {highlightStderr(failure.machineDetail)}
                </pre>
              ) : null}
            </>
          ) : null}
          {(failure.reason === 'auth-required' && !showRetry) ||
          (failure.reason === 'exited' && authOffer.kind === 'new-chat') ? (
            <div className="mt-1.5">
              <ThreadAuthOfferButton
                offer={authOffer}
                runningAuthAction={runningAuthAction}
                onAction={onAuthAction}
              />
            </div>
          ) : null}
          {showRetry ? (
            <div className="mt-1.5">
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-6 text-xs"
                disabled={retryPending}
                onClick={onRetry}
                data-testid="agent-thread-retry"
              >
                {retryPending ? (
                  <>
                    <Spinner className="size-3" aria-hidden="true" />
                    {t`Retrying…`}
                  </>
                ) : (
                  t`Try again`
                )}
              </Button>
            </div>
          ) : null}
          {showRestore ? (
            <div className="mt-1.5">
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-6 text-xs"
                onClick={onRestore}
                data-testid="agent-thread-restore"
              >
                {t`Edit and resend`}
              </Button>
            </div>
          ) : null}
        </>
      )}
    </div>
  );
}

function MessageBubble({
  item,
  streaming,
  agent,
  onResend,
  canSendHere,
  isLatestUserTurn,
}: {
  item: Extract<RenderedItem, { kind: 'message' }>;
  streaming?: boolean;
  agent: ThreadInfo['agent'];
  onResend: (
    text: string,
    target: ResendTarget,
    attachments: readonly AttachmentPart[],
  ) => Promise<boolean>;
  canSendHere: boolean;
  isLatestUserTurn: boolean;
}): ReactNode {
  const [editing, setEditing] = useState(false);
  const [restoreFocus, setRestoreFocus] = useState(false);
  const editSession = useRef(0);
  const openEditor = (): void => {
    editSession.current += 1;
    setEditing(true);
  };
  const closeEditor = (restore: boolean): void => {
    editSession.current += 1;
    setEditing(false);
    setRestoreFocus(restore);
  };
  if (item.role === 'thought') {
    return <ThoughtBlock item={item} streaming={streaming === true} />;
  }
  if (item.role !== 'user') {
    return (
      <div
        className="w-full wrap-break-word text-sm text-foreground"
        data-testid="agent-thread-agent-message"
      >
        <AgentMarkdown text={item.text} />
      </div>
    );
  }
  const attachments = item.attachments;
  return (
    <div
      className={cn(
        'group/user-message my-3 ml-auto flex flex-col',
        editing ? 'w-full' : 'max-w-[85%]',
      )}
    >
      <div
        className={cn(
          'wrap-break-word rounded-2xl rounded-br-xs bg-muted text-sm text-foreground',
          editing ? 'p-2' : 'px-3 py-1.5',
        )}
        data-testid="agent-thread-user-message"
      >
        {editing ? (
          <UserMessageEditor
            initialText={item.text}
            currentAgent={agent}
            canSendHere={canSendHere}
            onCancel={() => closeEditor(true)}
            onSend={async (text, target, chips) => {
              const session = editSession.current;
              if (!(await onResend(text, target, [...(attachments ?? []), ...chips]))) return;
              if (editSession.current !== session) return;
              closeEditor(target.kind === 'this-thread');
            }}
          />
        ) : (
          <>
            <AgentMarkdown text={item.text} />
            {attachments !== undefined && attachments.length > 0 ? (
              <UserMessageAttachments attachments={attachments} />
            ) : null}
          </>
        )}
      </div>
      {editing ? null : (
        <UserMessageActions
          text={item.text}
          sentAt={item.sentAt}
          alwaysVisible={isLatestUserTurn}
          restoreFocus={restoreFocus}
          onEdit={openEditor}
        />
      )}
    </div>
  );
}

function ImagePreviewDialog({
  preview,
  onOpenChange,
}: {
  preview: ImagePreview | null;
  onOpenChange: (open: boolean) => void;
}): ReactNode {
  const { t } = useLingui();
  return (
    <Dialog open={preview !== null} onOpenChange={onOpenChange}>
      <DialogContent
        className="flex max-h-[min(90dvh,900px)] items-center justify-center bg-background p-2 sm:max-w-[min(90vw,1000px)]"
        data-testid="agent-thread-image-preview"
      >
        <DialogTitle className="sr-only">{preview?.name ?? t`Image preview`}</DialogTitle>
        {preview !== null ? (
          <img
            src={preview.src}
            alt={preview.name}
            className="max-h-[min(85dvh,850px)] max-w-full rounded object-contain"
            draggable={false}
          />
        ) : null}
      </DialogContent>
    </Dialog>
  );
}

const attachmentKeys = new WeakMap<object, string>();
let attachmentKeyCounter = 0;
function keyForAttachment(attachment: AttachmentPart): string {
  const existing = attachmentKeys.get(attachment);
  if (existing !== undefined) return existing;
  attachmentKeyCounter += 1;
  const key = `att-${attachmentKeyCounter}`;
  attachmentKeys.set(attachment, key);
  return key;
}

function UserMessageAttachments({
  attachments,
}: {
  attachments: readonly AttachmentPart[];
}): ReactNode {
  const { t } = useLingui();
  const openPreview = use(ImagePreviewContext);
  const pages = useOptionalPageList()?.pages ?? null;
  return (
    <div
      className="mt-1.5 flex flex-wrap justify-end gap-1.5"
      data-testid="agent-thread-user-message-attachments"
    >
      {attachments.map((attachment) => {
        const key = keyForAttachment(attachment);
        if (attachment.kind === 'image') {
          const src = `data:${attachment.mimeType};base64,${attachment.data}`;
          return (
            <Button
              key={key}
              type="button"
              variant="ghost"
              onClick={() => openPreview?.({ src, name: attachment.name })}
              disabled={openPreview === null}
              className="inline-flex size-10 items-center justify-center overflow-hidden rounded-md border border-input bg-background p-0 hover:bg-background focus-visible:ring-2"
              title={attachment.name}
              aria-label={attachment.name}
              data-attachment-kind="image"
            >
              <img
                src={src}
                alt={attachment.name}
                className="h-full w-full object-cover"
                draggable={false}
              />
            </Button>
          );
        }
        if (attachment.kind === 'blob') {
          return (
            <span
              key={key}
              className="composer-mention-chip"
              title={attachment.name}
              data-attachment-kind="blob"
            >
              <span className="composer-mention-label">{attachment.name}</span>
            </span>
          );
        }
        const label = `@${attachment.name || attachment.path}`;
        const docName = attachment.kind === 'file' ? filePathToDocName(attachment.path) : null;
        if (docName !== null && docName !== attachment.path && pages?.has(docName) === true) {
          return (
            <a
              key={key}
              href={hashFromDocName(docName)}
              className="composer-mention-chip text-primary! underline decoration-primary/40 underline-offset-2 hover:decoration-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              title={t`Open ${docName}`}
              data-attachment-kind={attachment.kind}
            >
              <span className="composer-mention-label">{label}</span>
            </a>
          );
        }
        return (
          <span
            key={key}
            className="composer-mention-chip"
            title={attachment.path}
            data-attachment-kind={attachment.kind}
          >
            <span className="composer-mention-label">{label}</span>
          </span>
        );
      })}
    </div>
  );
}

const TOOL_MARKDOWN_CLASS =
  '[&_pre]:text-[11px]! [&_code]:text-[11px]! [&_[data-streamdown=code-block-body]]:p-2! [&_[data-streamdown=code-block-body]]:max-h-none!';

interface ToolTooltipText {
  purpose: string | null;
  id: string;
}

function toolTooltipText(
  call: { title: string; toolKind: string; rawInput: unknown },
  labelText: string,
): ToolTooltipText | null {
  const purpose = describeToolPurpose(call);
  if (purpose === null && call.title === labelText) return null;
  return { purpose, id: call.title };
}

function toolTitleText(text: ToolTooltipText | null): string | undefined {
  if (text === null) return undefined;
  return text.purpose === null ? text.id : `${text.purpose}\n${text.id}`;
}

function ToolTooltipContent({ text }: { text: ToolTooltipText }): ReactNode {
  return (
    <TooltipContent
      side="top"
      align="start"
      sideOffset={6}
      arrow={false}
      className="max-w-72 border border-border bg-popover text-popover-foreground shadow-md"
      data-testid="agent-thread-tool-tooltip"
    >
      {text.purpose !== null ? <span className="block">{text.purpose}</span> : null}
      <span className="block font-mono text-[10px] text-muted-foreground" dir="ltr">
        {text.id}
      </span>
    </TooltipContent>
  );
}

function ToolOutputBlock({ text, mode }: { text: string; mode: ToolOutputMode }): ReactNode {
  const body = stripWrappingFence(text);
  const json = prettyJson(body);
  if (json !== null) {
    return (
      <div data-testid="agent-thread-tool-json">
        <AgentMarkdown text={jsonMarkdown(json)} className={TOOL_MARKDOWN_CLASS} untrusted />
      </div>
    );
  }
  if (mode === 'markdown' || (mode === 'auto' && looksLikeMarkdown(body))) {
    return (
      <div className="rounded bg-muted/50 px-2 py-1" data-testid="agent-thread-tool-markdown">
        <AgentMarkdown text={body} className={TOOL_MARKDOWN_CLASS} untrusted />
      </div>
    );
  }
  return (
    <pre className="overflow-x-auto whitespace-pre-wrap break-words rounded bg-muted/50 px-2 py-1 font-mono text-[11px]">
      {body}
    </pre>
  );
}

function CappedToolBody({ children }: { children: ReactNode }): ReactNode {
  const { t } = useLingui();
  const bodyRef = useRef<HTMLDivElement | null>(null);
  const [overflowing, setOverflowing] = useState(false);
  const [showAll, setShowAll] = useState(false);
  useEffect(() => {
    if (showAll) return;
    const el = bodyRef.current;
    if (el === null) return;
    const measure = (): void => setOverflowing(el.scrollHeight > el.clientHeight + 1);
    measure();
    if (typeof ResizeObserver === 'undefined') return;
    const observer = new ResizeObserver(measure);
    observer.observe(el);
    return () => observer.disconnect();
  }, [showAll]);
  const capped = !showAll && overflowing;
  return (
    <>
      <div
        ref={bodyRef}
        className={cn(
          'flex flex-col gap-1.5',
          !showAll && 'max-h-80 overflow-y-auto subtle-scrollbar',
          capped && 'scroll-fade-mask-bottom',
        )}
        data-testid="agent-thread-tool-body"
        data-capped={capped ? 'true' : undefined}
      >
        {children}
      </div>
      {overflowing ? (
        <Button
          type="button"
          variant="ghost"
          size="sm"
          className="h-auto self-start px-1 py-0.5 text-[10px] text-muted-foreground uppercase tracking-wide hover:bg-transparent"
          onClick={() => setShowAll((value) => !value)}
          aria-expanded={showAll}
          data-testid="agent-thread-tool-show-all"
        >
          {showAll ? t`Show less` : t`Show all`}
        </Button>
      ) : null}
    </>
  );
}

function formatRawInput(rawInput: unknown): string | null {
  if (rawInput === undefined || rawInput === null) return null;
  if (
    typeof rawInput === 'object' &&
    !Array.isArray(rawInput) &&
    Object.keys(rawInput).length === 0
  ) {
    return null;
  }
  let text: string | undefined;
  try {
    text = JSON.stringify(rawInput, null, 2);
  } catch {
    return null;
  }
  if (text === undefined) return null;
  return text.length > 8_000 ? `${text.slice(0, 8_000)}…` : text;
}

function stripWrappingFence(text: string): string {
  const trimmed = text.trim();
  if (!trimmed.startsWith('```')) return text;
  const lines = trimmed.split('\n');
  if (lines.length < 2 || lines[lines.length - 1]?.trim() !== '```') return text;
  return lines.slice(1, -1).join('\n');
}

function ToolCallGroupRow({
  calls,
  onExpand,
}: {
  calls: readonly RenderedToolCall[];
  onExpand: () => void;
}): ReactNode {
  const { t } = useLingui();
  const head = calls[0];
  if (head === undefined) return null;
  const Icon = TOOL_ICONS[describeToolCall(head).glyph];
  const label = toolRunLabel(head);
  const details = calls
    .map((call) => {
      const path = call.locations[0]?.path ?? call.diffs[0]?.path;
      return path !== undefined ? (path.split('/').pop() ?? path) : describeToolCall(call).preview;
    })
    .filter((detail): detail is string => detail !== undefined && detail !== '');
  const shown = [...new Set(details)].slice(0, 2);
  const rest = details.length - shown.length;
  const summary =
    shown.length === 0 ? '' : rest > 0 ? t`${shown.join(', ')} +${rest} more` : shown.join(', ');
  const tooltip = toolTooltipText(head, label);
  const button = (
    <Button
      type="button"
      variant="ghost"
      size="sm"
      className="h-auto w-full justify-start gap-1.5 rounded-md px-2 py-1.5 font-normal"
      onClick={onExpand}
      aria-expanded={false}
      data-testid="agent-thread-tool-group-expand"
    >
      <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
      <span className="shrink-0 truncate">{t`${calls.length} × ${label}`}</span>
      {summary === '' ? null : (
        <span className="min-w-0 flex-1 truncate text-left text-muted-foreground/70">
          {summary}
        </span>
      )}
      <ChevronRight className="ml-auto size-3 shrink-0 text-muted-foreground" aria-hidden />
    </Button>
  );
  return (
    <div className="text-xs" data-testid="agent-thread-tool-group">
      {tooltip === null ? (
        button
      ) : (
        <Tooltip>
          <TooltipTrigger asChild>{button}</TooltipTrigger>
          <ToolTooltipContent text={tooltip} />
        </Tooltip>
      )}
    </div>
  );
}

function ToolCallCard({
  call,
  terminals,
  permission,
}: {
  call: RenderedToolCall;
  terminals: Record<string, RenderedTerminal>;
  permission?: RenderedPermission;
}): ReactNode {
  const { t } = useLingui();
  const [open, setOpen] = useState(call.status === 'failed');
  const userToggledRef = useRef(false);
  const prevStatusRef = useRef(call.status);
  const [completedLive, setCompletedLive] = useState(false);
  const [checkVisible, setCheckVisible] = useState(false);
  useEffect(() => {
    const prev = prevStatusRef.current;
    prevStatusRef.current = call.status;
    if (prev === call.status) return;
    if (call.status === 'failed' && !userToggledRef.current) setOpen(true);
    if (prev !== 'completed' && call.status === 'completed') {
      setCompletedLive(true);
      setCheckVisible(true);
      const timer = setTimeout(() => setCheckVisible(false), COMPLETION_CHECK_MS);
      return () => clearTimeout(timer);
    }
  }, [call.status]);
  const toggleOpen = (): void => {
    userToggledRef.current = true;
    setOpen((value) => !value);
  };
  const display = describeToolCall(call);
  const Icon = TOOL_ICONS[display.glyph];
  const callTerminals = call.terminalIds
    .map((id) => terminals[id])
    .filter((terminal): terminal is RenderedTerminal => terminal !== undefined);
  const rawInput = formatRawInput(call.rawInput);
  const failureText = call.status === 'failed' ? call.content.join('\n').trim() : '';
  const failureHint = toolFailureHint(call, permission);
  const hasBody =
    call.diffs.length > 0 ||
    call.content.length > 0 ||
    call.locations.length > 0 ||
    callTerminals.length > 0 ||
    rawInput !== null ||
    failureHint !== null;
  const expanded = open && hasBody;
  const outputMode = toolOutputMode(call);
  const tooltip = toolTooltipText(call, display.text);
  const row = (
    <>
      <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
      <span className="min-w-0 truncate">{display.text}</span>
      {display.preview === undefined ? null : (
        <span
          className="min-w-0 flex-1 truncate text-muted-foreground/70"
          data-testid="agent-thread-tool-preview"
        >
          {display.preview}
        </span>
      )}
      <span className="ml-auto flex shrink-0 items-center gap-1.5">
        <PermissionRefusalMark permission={permission} status={call.status} />
        <ToolStatusIndicator
          status={call.status}
          completedLive={completedLive}
          checkVisible={checkVisible}
        />
      </span>
    </>
  );
  const rowButton = (
    <Button
      type="button"
      variant="ghost"
      size="sm"
      className="h-auto w-full justify-start gap-1.5 rounded-md px-2 py-1.5 font-normal"
      onClick={toggleOpen}
      aria-expanded={open}
    >
      {row}
    </Button>
  );
  return (
    <div
      className={cn('text-xs', expanded && 'rounded-md border border-border/60')}
      data-tool-call=""
      data-testid="agent-thread-tool-call"
    >
      {hasBody ? (
        tooltip === null ? (
          rowButton
        ) : (
          <Tooltip>
            <TooltipTrigger asChild>{rowButton}</TooltipTrigger>
            <ToolTooltipContent text={tooltip} />
          </Tooltip>
        )
      ) : (
        <div
          className="flex w-full items-center gap-1.5 px-2 py-1.5"
          title={toolTitleText(tooltip)}
        >
          {row}
        </div>
      )}
      {expanded ? (
        <div className="flex flex-col gap-1.5 border-border/60 border-t px-2 py-1.5">
          <CappedToolBody>
            {call.diffs.map((diff, index) => (
              // biome-ignore lint/suspicious/noArrayIndexKey: diffs are positional within a card
              <InlineDiff key={index} diff={diff} />
            ))}
            {callTerminals.map((terminal) => (
              <TerminalBlock key={terminal.terminalId} terminal={terminal} />
            ))}
            {call.content.map((text, index) => (
              // biome-ignore lint/suspicious/noArrayIndexKey: content blocks are positional
              <ToolOutputBlock key={index} text={text} mode={outputMode} />
            ))}
            {failureHint !== null || failureText !== '' ? (
              <div className="flex items-center gap-2" data-testid="agent-thread-tool-failure-help">
                <span className="flex-1 text-muted-foreground">{failureHint}</span>
                {failureText !== '' ? (
                  <CopyButton
                    copyContent={failureText}
                    clipboardWrite={scheduleClipboardWrite}
                    size="icon-xs"
                    ariaLabel={t`Copy error`}
                    testId="agent-thread-tool-failure-copy"
                  />
                ) : null}
              </div>
            ) : null}
            {rawInput !== null ? <RawInputBlock text={rawInput} /> : null}
            {call.locations.length > 0 ? (
              <div className="flex flex-wrap gap-1 text-muted-foreground">
                {call.locations.map((loc, index) => (
                  <span
                    // biome-ignore lint/suspicious/noArrayIndexKey: locations are positional
                    key={index}
                    className="rounded bg-muted/50 px-1 py-0.5 font-mono text-[11px]"
                  >
                    {loc.path}
                    {loc.line !== undefined ? `:${loc.line}` : ''}
                  </span>
                ))}
              </div>
            ) : null}
          </CappedToolBody>
        </div>
      ) : null}
    </div>
  );
}

const OUTCOME_SYNONYM_NAMES = new Set([
  'accept',
  'allow',
  'approve',
  'decline',
  'deny',
  'no',
  'ok',
  'reject',
  'yes',
]);

function informativeOptionName(name: string | null): string | null {
  if (name === null) return null;
  const normalized = name.trim().toLocaleLowerCase();
  return normalized === '' || OUTCOME_SYNONYM_NAMES.has(normalized) ? null : name;
}

function usePermissionOutcomeLabel(): (outcome: PermissionOutcome) => string | null {
  const { t } = useLingui();
  return (outcome) => {
    if (outcome === null) return null;
    if (outcome.kind === 'dismissed') return t`Not answered`;
    const optionName = informativeOptionName(outcome.optionName);
    if (outcome.kind === 'approved') {
      if (outcome.auto) return t`Auto-approved`;
      return optionName !== null ? t`Approved — ${optionName}` : t`Approved`;
    }
    if (outcome.auto) return t`Auto-denied`;
    return optionName !== null ? t`Denied — ${optionName}` : t`Denied`;
  };
}

function PermissionRefusalMark({
  permission,
  status,
}: {
  permission?: RenderedPermission;
  status: RenderedToolCall['status'];
}): ReactNode {
  const outcomeLabel = usePermissionOutcomeLabel();
  if (permission === undefined || !permission.mergedIntoToolCall) return null;
  const outcome = resolvePermissionOutcome(permission);
  if (outcome === null || outcome.kind === 'approved') return null;
  if (status === 'failed') return null;
  return (
    <span className="shrink-0 text-muted-foreground" data-testid="agent-thread-tool-permission">
      {outcomeLabel(outcome)}
    </span>
  );
}

function ToolStatusIndicator({
  status,
  completedLive,
  checkVisible,
}: {
  status: RenderedToolCall['status'];
  completedLive: boolean;
  checkVisible: boolean;
}): ReactNode {
  const { t } = useLingui();
  const label =
    status === 'completed'
      ? t`done`
      : status === 'failed'
        ? t`failed`
        : status === 'in_progress'
          ? t`running`
          : t`pending`;
  return (
    <span className="flex shrink-0 items-center">
      <span className="sr-only">{label}</span>
      {status === 'failed' ? (
        <Badge
          variant="destructive"
          className="rounded-sm px-1.5 py-0 text-[10px]"
          data-testid="agent-thread-tool-failed"
        >
          {label}
        </Badge>
      ) : status === 'in_progress' || status === 'pending' ? (
        <Spinner
          className="size-3.5 text-muted-foreground"
          aria-hidden="true"
          data-testid="agent-thread-tool-spinner"
        />
      ) : completedLive ? (
        <Check
          className={cn(
            'size-3.5 text-muted-foreground/70 transition-opacity duration-500 motion-reduce:transition-none',
            checkVisible ? 'opacity-100' : 'opacity-0',
          )}
          aria-hidden="true"
          data-testid="agent-thread-tool-check"
        />
      ) : null}
    </span>
  );
}

function InlineDiff({
  diff,
}: {
  diff: { path: string; oldText: string | null; newText: string };
}): ReactNode {
  const { t } = useLingui();
  const rows = computeDiffRows(diff.oldText, diff.newText);
  return (
    <div className="overflow-hidden rounded border border-border/60">
      <div className="bg-muted/50 px-2 py-0.5 font-mono text-[11px] text-muted-foreground">
        {diff.path}
      </div>
      <pre className="overflow-x-auto font-mono text-[11px] leading-snug">
        {rows.map((row, index) =>
          row.type === 'gap' ? (
            <div
              // biome-ignore lint/suspicious/noArrayIndexKey: diff rows are positional
              key={index}
              className="select-none px-2 text-muted-foreground/70"
            >
              {t`⋯ ${row.count} unchanged lines`}
            </div>
          ) : (
            <div
              // biome-ignore lint/suspicious/noArrayIndexKey: diff rows are positional
              key={index}
              className={cn(
                'px-2',
                row.type === 'add' && 'bg-success/10 text-success',
                row.type === 'del' && 'bg-destructive/10 text-destructive',
                row.type === 'ctx' && 'text-muted-foreground',
              )}
            >
              <span aria-hidden="true">
                {row.type === 'add' ? '+ ' : row.type === 'del' ? '- ' : '  '}
              </span>
              {row.text}
            </div>
          ),
        )}
      </pre>
    </div>
  );
}

function TerminalBlock({ terminal }: { terminal: RenderedTerminal }): ReactNode {
  const { t } = useLingui();
  const commandLine = [terminal.command, ...terminal.args].join(' ');
  const text = renderTerminalText(terminal.output);
  const exit = terminal.exit;
  const failed = exit !== null && (exit.signal !== null || exit.exitCode !== 0);
  return (
    <div
      className="overflow-hidden rounded border border-border/60"
      data-testid="agent-thread-terminal"
    >
      <div className="flex items-center gap-1.5 bg-muted/50 px-2 py-0.5">
        <TerminalIcon className="size-3 shrink-0 text-muted-foreground" aria-hidden="true" />
        <span className="truncate font-mono text-[11px] text-muted-foreground" title={commandLine}>
          {commandLine}
        </span>
        <span className="ml-auto shrink-0">
          {exit === null ? (
            <span className="flex items-center gap-1 text-[10px] text-muted-foreground shimmer">
              <Spinner className="size-3" aria-hidden="true" />
              {t`running`}
            </span>
          ) : (
            <Badge
              variant={failed ? 'destructive' : 'secondary'}
              className="px-1.5 py-0 font-mono text-[10px] rounded-sm"
              data-testid="agent-thread-terminal-exit"
            >
              {exit.signal !== null ? exit.signal : t`exit ${exit.exitCode ?? 0}`}
            </Badge>
          )}
        </span>
      </div>
      {text.trim() !== '' || terminal.truncated ? (
        <pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words px-2 py-1 font-mono text-[11px] leading-snug">
          {terminal.truncated ? `${t`… earlier output trimmed`}\n` : null}
          {text}
        </pre>
      ) : null}
    </div>
  );
}

function RawInputBlock({ text }: { text: string }): ReactNode {
  const { t } = useLingui();
  const [open, setOpen] = useState(false);
  return (
    <div data-testid="agent-thread-tool-raw-input">
      <Button
        type="button"
        variant="ghost"
        size="sm"
        className="h-auto w-full justify-start gap-1 px-0 py-0.5 text-[10px] text-muted-foreground uppercase tracking-wide hover:bg-transparent"
        onClick={() => setOpen((value) => !value)}
        aria-expanded={open}
      >
        {open ? (
          <ChevronDown className="size-3" aria-hidden="true" />
        ) : (
          <ChevronRight className="size-3" aria-hidden="true" />
        )}
        {t`Input`}
      </Button>
      {open ? (
        <AgentMarkdown text={jsonMarkdown(text)} className={TOOL_MARKDOWN_CLASS} untrusted />
      ) : null}
    </div>
  );
}

function ShellCommandBlock({ id, command }: { id: string; command: string }): ReactNode {
  const { t } = useLingui();
  const lines = formatShellCommand(command).map((line) => ({
    ...line,
    shown: revealHiddenCharacters(line.text),
  }));
  const concealed = lines.some((line) => line.shown !== line.text);
  return (
    <div className="mb-1.5" data-testid="agent-thread-permission-command">
      <pre
        id={id}
        dir="ltr"
        translate="no"
        // oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- keyboard-focusable scroll container — a long command scrolls inside this bounded box, and Safari leaves overflow:auto elements out of the tab order.
        tabIndex={0}
        className="max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/50 px-2 py-1 text-start font-mono text-[11px] leading-relaxed"
      >
        <code>
          {lines.map((line, index) => (
            // biome-ignore lint/suspicious/noArrayIndexKey: shell lines are positional
            <Fragment key={index}>
              {index > 0 ? '\n' : null}
              <span className={line.continuation ? 'ps-4' : undefined}>{line.shown}</span>
            </Fragment>
          ))}
        </code>
      </pre>
      {concealed ? (
        <p className="mt-1 text-warning text-xs">
          {t`This command contains hidden characters that can make it look different from what runs. They are shown here as ⟨U+…⟩.`}
        </p>
      ) : null}
    </div>
  );
}

function PermissionPrompt({
  item,
  threadId,
  actionable,
}: {
  item: Extract<RenderedItem, { kind: 'permission' }>;
  threadId: string;
  actionable: boolean;
}): ReactNode {
  const { t } = useLingui();
  const outcomeLabel = usePermissionOutcomeLabel();
  const client = getAgentThreadClient();
  const outcome = resolvePermissionOutcome(item);
  const pending = outcome === null;
  const cardRef = useRef<HTMLDivElement>(null);
  const primaryRef = useRef<HTMLButtonElement>(null);

  const selectOption = (optionId: string): void => {
    client.respondPermission(threadId, item.requestId, { kind: 'selected', optionId });
  };
  const allowReadOnlyShell = (optionId: string): void => {
    client.setChatGrant(threadId, 'read_only_shell', true);
    selectOption(optionId);
  };

  const allowOptions = item.options.filter((option) => option.kind.startsWith('allow'));
  const rejectOptions = item.options.filter((option) => option.kind.startsWith('reject'));
  const primaryAllow = allowOptions.find((o) => o.kind === 'allow_once') ?? allowOptions[0];
  const readOnlyOffer = item.readOnlyShell && primaryAllow !== undefined;
  const secondaryAllows = allowOptions.filter((option) => option !== primaryAllow);
  const primaryReject = rejectOptions.find((o) => o.kind === 'reject_once') ?? rejectOptions[0];
  const denyOptions =
    primaryReject === undefined
      ? []
      : [primaryReject, ...rejectOptions.filter((option) => option !== primaryReject)];
  const focusRefForDeny = primaryAllow === undefined ? primaryRef : undefined;
  const titleId = useId();
  const commandId = useId();
  const describedBy = item.command !== null ? commandId : undefined;
  const denyDescribedBy = primaryAllow === undefined ? describedBy : undefined;

  useEffect(() => {
    if (!pending || !actionable) return;
    const root = cardRef.current?.closest('[data-agent-thread-root]');
    if (root == null || !root.contains(document.activeElement)) return;
    primaryRef.current?.focus();
  }, [pending, actionable]);

  const resolvedLabel = outcomeLabel(outcome);

  return (
    // biome-ignore lint/a11y/useSemanticElements: a permission card is a title, a command and decision buttons, not a form-control set, so <fieldset> would impose form-field semantics and chrome.
    <div
      ref={cardRef}
      className={cn(
        'rounded-md border px-2.5 py-2 text-sm',
        pending && actionable ? 'border-border bg-muted/30' : 'border-border/60 bg-muted/20',
      )}
      role="group"
      aria-labelledby={titleId}
      data-testid="agent-thread-permission"
    >
      <div id={titleId} className="mb-1.5 font-medium">
        {item.title}
      </div>
      {item.command !== null ? <ShellCommandBlock id={commandId} command={item.command} /> : null}
      {!pending ? (
        <div
          className="text-muted-foreground text-xs"
          data-testid="agent-thread-permission-outcome"
        >
          {resolvedLabel}
        </div>
      ) : !actionable ? (
        <div className="text-muted-foreground text-xs">{t`This request is no longer active.`}</div>
      ) : allowOptions.length > 1 || denyOptions.length > 1 || readOnlyOffer ? (
        <div className="flex flex-col gap-1" data-testid="agent-thread-permission-stack">
          {(primaryAllow !== undefined ? [primaryAllow, ...secondaryAllows] : allowOptions).map(
            (option) => {
              const isPrimary = option === primaryAllow;
              return (
                <Fragment key={option.optionId}>
                  <Button
                    ref={isPrimary ? primaryRef : undefined}
                    aria-describedby={isPrimary ? describedBy : undefined}
                    type="button"
                    size="sm"
                    variant={isPrimary ? 'default' : 'outline'}
                    className="h-auto w-full justify-start whitespace-normal py-1.5 text-left text-xs normal-case font-sans"
                    onClick={() => selectOption(option.optionId)}
                    data-testid={isPrimary ? 'agent-thread-permission-allow' : undefined}
                    data-permission-kind={option.kind}
                  >
                    {option.name}
                  </Button>
                  {isPrimary && readOnlyOffer ? (
                    <Button
                      aria-describedby={describedBy}
                      type="button"
                      size="sm"
                      variant="outline"
                      className="h-auto w-full justify-start whitespace-normal py-1.5 text-left text-xs normal-case font-sans"
                      onClick={() => allowReadOnlyShell(option.optionId)}
                      data-testid="agent-thread-permission-allow-read-only"
                      data-permission-kind="chat_read_only_shell"
                    >
                      {t`Allow read-only commands while this chat is open`}
                    </Button>
                  ) : null}
                </Fragment>
              );
            },
          )}
          <div
            className={cn(
              'flex flex-col gap-1',
              allowOptions.length > 0 && 'mt-1.5 border-border/40 border-t pt-1.5',
            )}
          >
            {denyOptions.length > 0 ? (
              denyOptions.map((option, index) => (
                <Button
                  key={option.optionId}
                  ref={index === 0 ? focusRefForDeny : undefined}
                  aria-describedby={index === 0 ? denyDescribedBy : undefined}
                  type="button"
                  size="sm"
                  variant={index === 0 ? 'outline' : 'ghost'}
                  className="h-auto w-full justify-start whitespace-normal py-1.5 text-left text-xs normal-case font-sans text-muted-foreground hover:text-foreground"
                  onClick={() => selectOption(option.optionId)}
                  data-testid={index === 0 ? 'agent-thread-permission-deny' : undefined}
                  data-permission-kind={option.kind}
                >
                  {option.name}
                </Button>
              ))
            ) : (
              <Button
                ref={focusRefForDeny}
                aria-describedby={denyDescribedBy}
                type="button"
                size="sm"
                variant="outline"
                className="h-auto w-full justify-start whitespace-normal py-1.5 text-left text-xs normal-case font-sans text-muted-foreground hover:text-foreground"
                onClick={() =>
                  client.respondPermission(threadId, item.requestId, { kind: 'cancelled' })
                }
                data-testid="agent-thread-permission-deny"
              >
                {t`Deny`}
              </Button>
            )}
          </div>
        </div>
      ) : (
        <div className="flex flex-wrap items-center justify-between gap-2">
          {denyOptions.length > 0 ? (
            (() => {
              const only = denyOptions[0];
              return (
                <Button
                  ref={focusRefForDeny}
                  aria-describedby={denyDescribedBy}
                  type="button"
                  size="sm"
                  variant="outline"
                  className="text-xs normal-case font-sans"
                  title={only.name}
                  onClick={() => selectOption(only.optionId)}
                  data-testid="agent-thread-permission-deny"
                  data-permission-kind={only.kind}
                >
                  <span className="truncate max-w-64">{only.name}</span>
                </Button>
              );
            })()
          ) : (
            <Button
              ref={focusRefForDeny}
              aria-describedby={denyDescribedBy}
              type="button"
              size="sm"
              variant="outline"
              className="text-xs"
              onClick={() =>
                client.respondPermission(threadId, item.requestId, { kind: 'cancelled' })
              }
              data-testid="agent-thread-permission-deny"
            >
              {t`Deny`}
            </Button>
          )}
          {primaryAllow !== undefined ? (
            <Button
              ref={primaryRef}
              aria-describedby={describedBy}
              type="button"
              size="sm"
              className="text-xs normal-case font-sans"
              title={primaryAllow.name}
              onClick={() => selectOption(primaryAllow.optionId)}
              data-testid="agent-thread-permission-allow"
              data-permission-kind={primaryAllow.kind}
            >
              <span className="truncate max-w-64">{primaryAllow.name}</span>
            </Button>
          ) : null}
        </div>
      )}
    </div>
  );
}

function RuntimeConsentPrompt({
  item,
  threadId,
}: {
  item: Extract<RenderedItem, { kind: 'runtime_consent' }>;
  threadId: string;
}): ReactNode {
  const { t } = useLingui();
  const client = getAgentThreadClient();
  const downloadLabelId = useId();

  if (item.resolved === 'declined' || item.resolved === 'timeout') {
    return (
      <div
        className="rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-muted-foreground text-xs"
        data-testid="agent-thread-runtime-consent"
      >
        {item.resolved === 'declined'
          ? t`Skipped downloading ${item.displayName}.`
          : t`The ${item.displayName} download request timed out.`}
      </div>
    );
  }

  if (item.resolved === 'granted') {
    if (item.install === 'done') {
      return (
        <div
          className="flex items-center gap-1.5 rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-muted-foreground text-xs"
          data-testid="agent-thread-runtime-consent"
        >
          <Check className="size-3.5 shrink-0 text-success" aria-hidden="true" />
          <span>{t`Installed ${item.displayName} ${item.version}`}</span>
        </div>
      );
    }
    if (item.install === 'failed') {
      return (
        <div
          className="rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-muted-foreground text-xs"
          data-testid="agent-thread-runtime-consent"
        >
          {t`Couldn't finish installing ${item.displayName} — see below.`}
        </div>
      );
    }
    const pct = consentPercent(item.progress);
    return (
      <div
        className="rounded-md border border-border/60 bg-muted/30 px-2.5 py-2 text-xs"
        data-testid="agent-thread-runtime-consent"
      >
        <div className="mb-1.5 flex items-center gap-1.5 text-muted-foreground">
          <Spinner className="size-3.5 shrink-0" aria-hidden="true" />
          <span id={downloadLabelId}>{t`Downloading ${item.displayName} ${item.version}…`}</span>
        </div>
        <Progress
          value={pct}
          indeterminateFillPercent={40}
          aria-labelledby={downloadLabelId}
          className="h-1.5"
        />
        {pct !== null ? (
          <div
            aria-hidden="true"
            className="mt-1 text-[11px] text-muted-foreground"
          >{`${pct}%`}</div>
        ) : null}
      </div>
    );
  }

  return (
    <div
      className="rounded-md border border-info/40 px-2.5 py-2 text-sm"
      data-testid="agent-thread-runtime-consent"
    >
      <div className="mb-1 flex items-center gap-1.5 font-medium">
        <Download className="size-4 shrink-0" aria-hidden="true" />
        <span>
          {item.reason === 'damaged'
            ? t`${item.displayName} needs replacing`
            : t`${item.agentName} needs ${item.displayName}`}
        </span>
      </div>
      <p className="mb-2 text-muted-foreground text-xs">
        {item.reason === 'damaged'
          ? t`Open Knowledge's own copy of ${item.displayName} is damaged and won't run. It can download a fresh copy of ${item.displayName} ${item.version} (about ${item.approxSizeMB} MB from ${item.sourceHost}) to replace it.`
          : item.reason === 'broken'
            ? t`This agent runs through ${item.provides}, which is installed but won't run — its ${item.displayName} looks broken. Open Knowledge can download a private copy of ${item.displayName} ${item.version} (about ${item.approxSizeMB} MB from ${item.sourceHost}) that won't touch the rest of your system.`
            : t`This agent runs through ${item.provides}, which isn't installed. Open Knowledge can download a private copy of ${item.displayName} ${item.version} (about ${item.approxSizeMB} MB from ${item.sourceHost}) that won't touch the rest of your system.`}
      </p>
      <div className="flex flex-wrap gap-1.5">
        <Button
          type="button"
          size="sm"
          className="h-7 text-xs"
          onClick={() =>
            client.respondRuntimeConsent(threadId, item.requestId, { kind: 'granted' })
          }
          data-testid="agent-thread-runtime-consent-allow"
        >
          {t`Download ${item.displayName}`}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="outline"
          className="h-7 text-xs"
          onClick={() =>
            client.respondRuntimeConsent(threadId, item.requestId, { kind: 'declined' })
          }
          data-testid="agent-thread-runtime-consent-decline"
        >
          {t`Not now`}
        </Button>
      </div>
    </div>
  );
}

function PiBridgeOutcomeRow({
  outcome,
  bridgePath,
}: {
  outcome: NonNullable<Extract<RenderedItem, { kind: 'pi_bridge' }>['outcome']>;
  bridgePath: string;
}): ReactNode {
  const { t } = useLingui();
  const ready = outcome.state === 'ready';
  return (
    <div
      className="rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-muted-foreground text-xs"
      data-testid="agent-thread-pi-bridge"
    >
      <div className="flex items-start gap-1.5">
        {ready ? (
          <Check className="mt-px size-3.5 shrink-0 text-success" aria-hidden="true" />
        ) : null}
        <span>
          {outcome.state === 'ready'
            ? t`Open Knowledge tools are available in this thread.`
            : outcome.state === 'foreign-file'
              ? t`Open Knowledge tools are unavailable: a file Open Knowledge didn't write is already at ${bridgePath}.`
              : outcome.state === 'unreadable-file'
                ? t`Open Knowledge tools are unavailable: something is already at ${bridgePath} but couldn't be read, so Open Knowledge left it alone.`
                : outcome.state === 'project-path-unavailable'
                  ? t`Open Knowledge tools are unavailable because the project folder is missing, inaccessible, or has changed. Check its location and permissions, then retry.`
                  : outcome.state === 'trust-failed'
                    ? t`Wrote the Open Knowledge extension, but couldn't mark the folder trusted, so it won't load. This thread has no Open Knowledge tools.`
                    : t`Couldn't write the Open Knowledge extension. This thread has no Open Knowledge tools.`}
        </span>
      </div>
      {outcome.detail !== null ? (
        <div className="mt-1 break-all font-mono text-[11px] opacity-80">{outcome.detail}</div>
      ) : null}
    </div>
  );
}

function PiBridgeConsentPrompt({
  item,
  threadId,
}: {
  item: Extract<RenderedItem, { kind: 'pi_bridge' }>;
  threadId: string;
}): ReactNode {
  const { t } = useLingui();
  const client = getAgentThreadClient();

  if (item.row === 'notice') {
    return <PiBridgeOutcomeRow outcome={item.outcome} bridgePath={item.bridgePath} />;
  }
  if (item.outcome !== null) {
    return <PiBridgeOutcomeRow outcome={item.outcome} bridgePath={item.bridgePath} />;
  }

  if (item.decision === 'declined' || item.decision === 'timeout') {
    return (
      <div
        className="rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-muted-foreground text-xs"
        data-testid="agent-thread-pi-bridge"
      >
        {item.decision === 'declined'
          ? t`Skipped enabling Open Knowledge tools. This thread runs without them.`
          : t`The request to enable Open Knowledge tools timed out. This thread runs without them.`}
      </div>
    );
  }

  if (item.decision === 'granted') {
    return (
      <div
        className="flex items-center gap-1.5 rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-muted-foreground text-xs"
        data-testid="agent-thread-pi-bridge"
      >
        <Spinner className="size-3.5 shrink-0" aria-hidden="true" />
        <span>{t`Enabling Open Knowledge tools`}</span>
      </div>
    );
  }

  const prompt = item.prompt;
  const otherExtensions = prompt.otherExtensions.join(', ');
  return (
    <div
      className="rounded-md border border-info/40 px-2.5 py-2 text-sm"
      data-testid="agent-thread-pi-bridge"
    >
      <div className="mb-1 flex items-center gap-1.5 font-medium">
        <Wrench className="size-4 shrink-0" aria-hidden="true" />
        <span>{t`Enable Open Knowledge tools for ${prompt.agentName}?`}</span>
      </div>
      <p className="mb-1.5 text-muted-foreground text-xs">
        {t`${prompt.agentName} has no way to read or edit your documents on its own. Approving writes the Open Knowledge extension to ${item.bridgePath} and leaves it there, so this session and later ones in this project have the Open Knowledge tools.`}
      </p>
      <p className="mb-2 text-muted-foreground text-xs">
        {t`It also marks ${prompt.cwd} as trusted, which is what makes the extension load. That trust covers the whole folder — ${prompt.agentName} will load every extension in it, not only Open Knowledge's — and both stay until you remove Open Knowledge from this project.`}
      </p>
      {otherExtensions !== '' ? (
        <p className="mb-2 text-muted-foreground text-xs">
          {t`That folder already holds code Open Knowledge didn't write, which the same trust would let ${prompt.agentName} run: ${otherExtensions}.`}
        </p>
      ) : null}
      <div className="flex flex-wrap gap-1.5">
        <Button
          type="button"
          size="sm"
          className="h-7 text-xs"
          onClick={() =>
            client.respondPiBridgeConsent(threadId, prompt.requestId, { kind: 'granted' })
          }
          data-testid="agent-thread-pi-bridge-allow"
        >
          {t`Approve`}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="outline"
          className="h-7 text-xs"
          onClick={() =>
            client.respondPiBridgeConsent(threadId, prompt.requestId, { kind: 'declined' })
          }
          data-testid="agent-thread-pi-bridge-decline"
        >
          {t`Not now`}
        </Button>
      </div>
    </div>
  );
}

function consentPercent(
  progress: { receivedBytes: number; totalBytes: number | null } | null,
): number | null {
  if (progress === null || progress.totalBytes === null || progress.totalBytes <= 0) return null;
  return Math.min(100, Math.round((progress.receivedBytes / progress.totalBytes) * 100));
}

function formatCompactTokens(value: number): string {
  const thousands = Math.round(value / 1_000);
  if (thousands >= 1_000) {
    const millions = value / 1_000_000;
    return `${millions % 1 === 0 ? millions.toFixed(0) : millions.toFixed(1)}M`;
  }
  if (value >= 1_000) return `${thousands}k`;
  return String(value);
}

function ContextUsageRing({
  used,
  size,
  percent,
}: {
  used: number;
  size: number;
  percent: number;
}): ReactNode {
  const { t } = useLingui();
  const radius = 6;
  const circumference = 2 * Math.PI * radius;
  const tone =
    percent >= 90
      ? 'text-destructive'
      : percent >= 75
        ? 'text-warning'
        : 'text-muted-foreground/60';
  const left = 100 - percent;
  const usedLabel = formatCompactTokens(used);
  const sizeLabel = formatCompactTokens(size);
  return (
    <Tooltip>
      <TooltipTrigger
        aria-label={t`Context window: ${percent}% used, ${usedLabel} of ${sizeLabel} tokens`}
        className="flex size-5 items-center justify-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
        data-testid="agent-thread-usage"
      >
        <svg viewBox="0 0 16 16" className="size-4 -rotate-90" aria-hidden="true">
          <circle
            cx="8"
            cy="8"
            r={radius}
            fill="none"
            strokeWidth="2"
            className="stroke-current text-muted-foreground/10"
          />
          <circle
            cx="8"
            cy="8"
            r={radius}
            fill="none"
            strokeWidth="2"
            strokeLinecap="round"
            strokeDasharray={circumference}
            strokeDashoffset={circumference * (1 - percent / 100)}
            className={cn('stroke-current transition-[stroke-dashoffset]', tone)}
          />
        </svg>
      </TooltipTrigger>
      <TooltipContent side="top">
        <div className="flex flex-col items-center gap-0.5 text-center">
          <span className="text-background/60">{t`Context window:`}</span>
          <span>{t`${percent}% used (${left}% left)`}</span>
          <span className="tabular-nums">{t`${usedLabel} / ${sizeLabel} tokens used`}</span>
        </div>
      </TooltipContent>
    </Tooltip>
  );
}

function ThreadComposer({
  info,
  hasStartedWork,
  onNewChat,
  composerRef,
  onComposerReady,
  mentionRecency,
  onSubmit,
  canPrompt,
  canQueue,
  turnActive,
  cancelPending,
  onCancel,
  onSteer,
  status,
  archived,
  resumePending,
  usage,
  selectedCommentCount,
  selectedCommentDocs,
  hasQueuedComments,
  onAttachComments,
  onDismissComments,
  pendingAttachments,
  pendingUploads,
  imagesAccepted,
  onIngestImageFiles,
  onIngestAllFiles,
  onRemovePendingAttachment,
}: {
  info: ThreadInfo;
  hasStartedWork: boolean;
  onNewChat: () => void;
  composerRef: RefObject<ComposerMentionInputHandle | null>;
  onComposerReady: () => void;
  mentionRecency: MentionRecency;
  onSubmit: () => void;
  canPrompt: boolean;
  canQueue: boolean;
  turnActive: boolean;
  cancelPending: boolean;
  onCancel: () => void;
  onSteer: () => void;
  status: ThreadInfo['status'];
  archived: boolean;
  resumePending: boolean;
  usage: { used?: number; size?: number } | null;
  selectedCommentCount: number;
  selectedCommentDocs: readonly CommentDocTally[];
  hasQueuedComments: boolean;
  onAttachComments: () => void;
  onDismissComments: () => void;
  pendingAttachments: readonly AttachmentPart[];
  pendingUploads: readonly {
    readonly id: string;
    readonly name: string;
    readonly mimeType: string;
  }[];
  imagesAccepted: boolean;
  onIngestImageFiles: (files: readonly File[]) => Promise<void>;
  onIngestAllFiles: (files: readonly File[]) => Promise<void>;
  onRemovePendingAttachment: (index: number) => void;
}): ReactNode {
  const bugReport = useBugReport();
  const canReportProblem = typeof window !== 'undefined' && window.okDesktop != null;
  const { t, i18n } = useLingui();
  const agentName = agentDisplayName(info.agent.name);

  const [isEmpty, setIsEmpty] = useState(true);
  const settingsTriggerRef = useRef<HTMLButtonElement>(null);

  const composerDisabled = archived ? resumePending : status === 'exited';

  const usagePercent =
    usage !== null && usage.used !== undefined && usage.size !== undefined && usage.size > 0
      ? Math.min(100, Math.round((usage.used / usage.size) * 100))
      : null;

  const queue = info.queue ?? [];

  const hasSendableContent = !isEmpty || hasQueuedComments || pendingAttachments.length > 0;

  const agentHasCommands = (info.availableCommands ?? []).length > 0;
  const composerHintId = useId();
  const mentionHint = t`Type '@' to mention a page`;
  const commandHint = t`Type '/' for commands`;
  const composerHint = agentHasCommands
    ? formatToolList([mentionHint, commandHint], i18n.locale)
    : mentionHint;
  const placeholderRotating = !archived && status === 'ready';
  const placeholderPhrases = placeholderRotating
    ? [t`Message ${agentName}`, mentionHint, ...(agentHasCommands ? [commandHint] : [])]
    : [
        archived
          ? resumePending
            ? t`Resuming the chat`
            : t`Pick up where you left off`
          : status === 'auth_required'
            ? t`Sign in to ${agentName} first`
            : status === 'authenticating'
              ? t`Signing in to ${agentName}`
              : t`Message ${agentName}`,
      ];

  const sendButton = (
    <Button
      type="button"
      size="icon-sm"
      className="rounded-lg"
      disabled={!(canPrompt || canQueue) || !hasSendableContent || pendingUploads.length > 0}
      onClick={onSubmit}
      aria-label={canQueue ? t`Queue message` : t`Send`}
      data-testid="agent-thread-send"
    >
      {canQueue ? (
        <ListPlus className="size-4" aria-hidden="true" />
      ) : (
        <ArrowUp className="size-4" aria-hidden="true" />
      )}
    </Button>
  );

  return (
    <ComposerTooltipProvider>
      <div className="p-2">
        {queue.length > 0 && !archived ? (
          <QueuedMessageList threadId={info.threadId} queue={queue} turnActive={turnActive} />
        ) : null}
        <div // oxlint-disable-line jsx-a11y/no-static-element-interactions -- pointer-only affordance — pressing the card's whitespace focuses the composer input; keyboard/AT users reach it via Tab. See focus-composer-on-card-pointer.ts.
          onMouseDown={(event) => focusComposerInputOnCardPointer(event, composerRef)}
          onPaste={(event) => {
            const files = collectImageFiles(event.clipboardData);
            if (files.length === 0) return;
            event.preventDefault();
            if (!imagesAccepted) {
              toast.error(t`${agentName} doesn't accept image attachments.`);
              return;
            }
            void onIngestImageFiles(files);
          }}
          className="relative cursor-text rounded-lg border border-input bg-transparent transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30"
        >
          {hasQueuedComments ? (
            <ComposerContextChips className="px-3 pt-2 pb-1">
              <QueuedCommentsChip
                count={selectedCommentCount}
                docs={selectedCommentDocs}
                onDismiss={onDismissComments}
              />
            </ComposerContextChips>
          ) : null}
          {pendingAttachments.length > 0 || pendingUploads.length > 0 ? (
            <PendingImageStrip
              testIdPrefix="agent-thread"
              images={pendingAttachments}
              uploads={pendingUploads}
              onRemove={onRemovePendingAttachment}
            />
          ) : null}
          <div className="relative">
            <ComposerMentionInput
              ref={composerRef}
              onReady={onComposerReady}
              ariaLabel={t`Message ${agentName}`}
              ariaDescribedBy={placeholderRotating ? composerHintId : undefined}
              onEmptyChange={setIsEmpty}
              onSubmit={onSubmit}
              attachmentDrop={{ kind: 'host' }}
              onEscape={() => {
                if (turnActive && !cancelPending) onCancel();
              }}
              disabled={composerDisabled}
              slashCommands={info.availableCommands ?? null}
              mentionRecency={mentionRecency}
              className={cn(
                'max-h-40 overflow-y-auto px-2.5 pt-1 text-base md:text-sm',
                composerDisabled && 'opacity-50',
              )}
              testId="agent-thread-composer"
            />
            {placeholderRotating ? (
              <span id={composerHintId} className="sr-only">
                {composerHint}
              </span>
            ) : null}
            {isEmpty ? (
              <RotatingComposerPlaceholder
                phrases={placeholderPhrases}
                rotating={placeholderRotating}
                className={cn('px-2.5 pt-2', composerDisabled && 'opacity-50')}
                testId="agent-thread-composer-placeholder"
              />
            ) : null}
          </div>
          <div className="flex items-center gap-0.5 px-1.5 pt-1 pb-1.5">
            <ComposerAddMenu
              composerRef={composerRef}
              disabled={composerDisabled}
              disabledFocusTargetRef={settingsTriggerRef}
              testId="agent-thread-add-to-prompt"
            >
              <ComposerFilesMenuItem
                onFiles={onIngestAllFiles}
                attachmentMode={
                  info.promptCapabilities !== null &&
                  info.promptCapabilities !== undefined &&
                  info.promptCapabilities.embeddedContext !== true
                    ? 'reference'
                    : 'embedded'
                }
              />
              {selectedCommentCount > 0 && !hasQueuedComments ? (
                <ComposerCommentsMenuItem
                  count={selectedCommentCount}
                  onSelect={onAttachComments}
                />
              ) : null}
              <ComposerMentionMenuItem onSelect={() => composerRef.current?.openMentionPicker()} />
              {agentHasCommands && isEmpty ? (
                <ComposerCommandsMenuItem
                  onSelect={() => composerRef.current?.openSlashCommandPicker()}
                />
              ) : null}
            </ComposerAddMenu>
            <AgentSettingsPopover
              info={info}
              hasStartedWork={hasStartedWork}
              onNewChat={onNewChat}
              {...(canReportProblem
                ? { onReportProblem: () => bugReport.start({ launcherBorne: true }) }
                : {})}
              triggerRef={settingsTriggerRef}
            />
            {canReportProblem ? (
              <ReportBugDialog
                capture={bugReport.capture}
                onClose={bugReport.close}
                agentChat={{ threadId: info.threadId }}
              />
            ) : null}
            <div className="ml-auto flex items-center gap-1.5">
              {usagePercent !== null && usage?.used !== undefined && usage?.size !== undefined ? (
                <ContextUsageRing used={usage.used} size={usage.size} percent={usagePercent} />
              ) : null}
              {turnActive && (cancelPending || !hasSendableContent) ? (
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      type="button"
                      size="icon-sm"
                      className="rounded-lg"
                      disabled={cancelPending}
                      onClick={onCancel}
                      aria-label={cancelPending ? t`Stopping` : t`Stop`}
                      data-testid="agent-thread-cancel"
                    >
                      {cancelPending ? (
                        <Spinner className="size-3.5" aria-hidden="true" />
                      ) : (
                        <Square className="size-3 fill-current" aria-hidden="true" />
                      )}
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent side="top">{t`Stop (Esc)`}</TooltipContent>
                </Tooltip>
              ) : canQueue ? (
                <>
                  {!isEmpty ? (
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          type="button"
                          size="icon-sm"
                          variant="outline"
                          className="rounded-lg"
                          disabled={pendingUploads.length > 0}
                          onClick={onSteer}
                          aria-label={t`Steer now`}
                          data-testid="agent-thread-steer"
                        >
                          <Zap className="size-4" aria-hidden="true" />
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent side="top">{t`Stops the current run and sends this instead`}</TooltipContent>
                    </Tooltip>
                  ) : null}
                  <Tooltip>
                    <TooltipTrigger asChild>{sendButton}</TooltipTrigger>
                    <TooltipContent side="top">{t`Queues behind the running turn`}</TooltipContent>
                  </Tooltip>
                </>
              ) : (
                sendButton
              )}
            </div>
          </div>
        </div>
      </div>
    </ComposerTooltipProvider>
  );
}

function QueuedMessageList({
  threadId,
  queue,
  turnActive,
}: {
  threadId: string;
  queue: readonly QueuedMessage[];
  turnActive: boolean;
}): ReactNode {
  const { t } = useLingui();
  return (
    <div className="mb-1.5 flex flex-col gap-1" data-testid="agent-thread-queue">
      <span className="px-1 font-medium text-[10px] text-muted-foreground/70 uppercase tracking-wide">
        {t`Queued — sends when this run finishes`}
      </span>
      {queue.map((message) => (
        <QueuedMessageRow
          key={message.id}
          threadId={threadId}
          message={message}
          turnActive={turnActive}
        />
      ))}
    </div>
  );
}

function QueuedMessageRow({
  threadId,
  message,
  turnActive,
}: {
  threadId: string;
  message: QueuedMessage;
  turnActive: boolean;
}): ReactNode {
  const { t } = useLingui();
  const client = getAgentThreadClient();
  const [editing, setEditing] = useState(false);
  const [value, setValue] = useState('');

  const held = message.held === true;

  const release = (): void => client.holdQueued(threadId, message.id, false);

  const startEdit = (): void => {
    client.holdQueued(threadId, message.id, true);
    setValue(message.content);
    setEditing(true);
  };
  const cancelEdit = (): void => {
    setEditing(false);
    release();
  };
  const save = (): void => {
    const trimmed = value.trim();
    if (trimmed === '') {
      cancelEdit();
      return;
    }
    setEditing(false);
    if (trimmed === message.content) {
      release();
      return;
    }
    void client.editQueued(threadId, message.id, trimmed).catch(() => {
      toast.error(t`That message already went out — your edit wasn't applied.`);
    });
  };

  if (editing) {
    return (
      <div
        className="rounded-md border border-input bg-muted/30 p-1"
        data-testid="agent-thread-queued-editing"
      >
        <Textarea
          value={value}
          onChange={(event) => setValue(event.target.value)}
          onKeyDown={(event) => {
            if (event.key === 'Enter' && !event.shiftKey) {
              event.preventDefault();
              save();
            } else if (event.key === 'Escape') {
              event.preventDefault();
              cancelEdit();
            }
          }}
          autoFocus
          rows={1}
          aria-label={t`Edit queued message`}
          className="min-h-8 resize-none border-0 bg-transparent px-1.5 py-1 shadow-none focus-visible:border-0 focus-visible:ring-0 dark:bg-transparent"
          data-testid="agent-thread-queued-input"
        />
        <div className="flex items-center justify-end gap-1">
          <Button
            type="button"
            size="icon-sm"
            variant="ghost"
            className="size-6"
            onClick={cancelEdit}
            aria-label={t`Cancel editing`}
            data-testid="agent-thread-queued-cancel-edit"
          >
            <X className="size-3.5" aria-hidden="true" />
          </Button>
          <Button
            type="button"
            size="icon-sm"
            variant="ghost"
            className="size-6"
            disabled={value.trim() === ''}
            onClick={save}
            aria-label={t`Save queued message`}
            data-testid="agent-thread-queued-save"
          >
            <Check className="size-3.5" aria-hidden="true" />
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div
      className={cn(
        'flex items-center gap-1 rounded-md border py-0.5 pl-2 pr-1',
        held ? 'border-input/40 border-dashed bg-muted/20' : 'border-input/60 bg-muted/30',
      )}
      data-testid="agent-thread-queued"
      data-held={held ? 'true' : undefined}
    >
      <span
        className={cn(
          'min-w-0 flex-1 truncate text-sm',
          held ? 'text-muted-foreground/60' : 'text-muted-foreground',
        )}
      >
        {message.content}
      </span>
      {held ? (
        <>
          <span className="shrink-0 font-medium text-[10px] text-muted-foreground/70 uppercase tracking-wide">
            {t`Held`}
          </span>
          <Button
            type="button"
            size="icon-sm"
            variant="ghost"
            className="size-6 shrink-0 text-muted-foreground"
            onClick={release}
            aria-label={t`Send when the agent is free`}
            data-testid="agent-thread-queued-release"
          >
            <Check className="size-3.5" aria-hidden="true" />
          </Button>
        </>
      ) : null}
      {turnActive ? (
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              type="button"
              size="icon-sm"
              variant="ghost"
              className="size-6 shrink-0 text-muted-foreground"
              onClick={() => client.sendQueuedNow(threadId, message.id)}
              aria-label={t`Send now`}
              data-testid="agent-thread-queued-send-now"
            >
              <Zap className="size-3.5" aria-hidden="true" />
            </Button>
          </TooltipTrigger>
          <TooltipContent side="top">{t`Stops the current run and sends this instead`}</TooltipContent>
        </Tooltip>
      ) : null}
      <Button
        type="button"
        size="icon-sm"
        variant="ghost"
        className="size-6 shrink-0 text-muted-foreground"
        onClick={startEdit}
        aria-label={t`Edit queued message`}
        data-testid="agent-thread-queued-edit"
      >
        <SquarePen className="size-3.5" aria-hidden="true" />
      </Button>
      <Button
        type="button"
        size="icon-sm"
        variant="ghost"
        className="size-6 shrink-0 text-muted-foreground"
        onClick={() => client.removeQueued(threadId, message.id)}
        aria-label={t`Remove queued message`}
        data-testid="agent-thread-queued-remove"
      >
        <X className="size-3.5" aria-hidden="true" />
      </Button>
    </div>
  );
}

function ChatPanelDropOverlay({ onDismiss }: { onDismiss: () => void }): ReactNode {
  const { t } = useLingui();
  return (
    // oxlint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events -- transient drop overlay — keyboard/AT users never see it (drag-only surface), and click-to-dismiss is a safety escape for a stuck overlay.
    <div
      className="pointer-events-auto absolute inset-0 z-20 flex items-center justify-center bg-background/85 backdrop-blur-sm"
      onClick={onDismiss}
      data-testid="agent-thread-drop-overlay"
    >
      <div className="flex flex-col items-center gap-3 rounded-xl border-2 border-primary/70 border-dashed bg-background/90 px-8 py-6 text-center text-primary shadow-lg">
        <Plus className="size-8" aria-hidden="true" />
        <div className="flex flex-col gap-1">
          <span className="font-medium text-base">{t`Drop a file to attach`}</span>
          <span className="text-muted-foreground text-xs">
            {t`Images from anywhere · non-image files must be in the workspace`}
          </span>
        </div>
      </div>
    </div>
  );
}