Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

161 KB
Raw Blame
import React, { Fragment, useState, useRef, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from 'react';
import { parseWatchMeta, type WatchMeta } from '../missionWatch';
import { flushSync } from 'react-dom';
import { createStreamText, useStreamPart, useStreamThinking, useStreamWriting, type StreamText, type StreamView } from '../streamText';
import { queuedText } from '../claudeVm';
import { QueuedBeside } from './QueuedBeside';
import { WaitingBanner } from './WaitingBanner';
import { answerPlaceholder, isTeamTurn, onlyAskOpen, turnRail, waitingStopLabel } from '../waitingState';
import type { SwitchEntry } from '../watchLive';
import { emptyTrialReplyLine, trialCardsAfter, trialOf } from '../showOnce';
import { parsePick } from '../engines';
import { onContinuity } from '../continuity';
import { TrialWaitsCard } from './SkillsPanel';
import { agentSenderLabel, messageAbout, otherSenderLabel, senderLetter } from '../agentConnections';
import { ArrowDown, ArrowUp, AtSign, Paperclip, Sparkles, ChevronDown, ChevronRight, Check, ChevronLeft, User, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor, CircleSlash } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { WorkingAvatar } from './WorkingAvatar';
import { BotHome } from './BotHome';
import { accountCardShows } from '../firstScreen';
import { ChatHome, answerTarget, goodAt, recipientsOf, teamAnswerLine, teamChipLabel, teamChipTitle } from '../botHome';
import { moodNoticed } from '../kwantMood';
import { NewTag } from './NewTag';
import { PHONE_QUERY, TOUCH_QUERY } from '../layout';
import { useMedia } from '../useMedia';
import { composerStacked, fitPlaceholder, keyboardMode, measureText16, phonePlaceholder } from '../composer';
import { isNewThing, markNewSeen, subscribeNew } from '../whatsNew';
import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';
import { MentionPopover, MentionItem } from './MentionPopover';
import { MarkdownRenderer } from './MarkdownRenderer';
import { StreamMarkdown } from './StreamMarkdown';
import { ToolCallsList } from './ToolCallsList';
import { VirtualMachinePane, TerminalLogEntry } from './VirtualMachinePane';
import { playSfx } from '../audio/chiptune';
import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThreads';
import { PinnedInstructions, PinnedItem } from './Instructions';
import { DelegationMeta, parseDelegationMeta } from '../threads';
import { QuestionMeta, foldedAnswerIds, parseMetaObject, parseQuestionMeta } from '../questions';
import { fromTelegram, sentToTelegram } from '../telegram';
import { AllowedFromTelegram, ViaTelegram } from './TelegramMarks';
import { RefusedCustomerCall } from './RefusedCustomerCall';
import { HumanStep, HumanStepMeta, parseHumanStepMeta } from '../humanSteps';
import { LiveActivity, foldLiveSteps, hasThinkingText, parseActivityMeta } from '../activity';
import { LiveActivityList, SavedActivityList } from './ActivityList';
import { BrowsedChip } from './BrowsedChip';
import { pagesOfReply, type ReplyPage } from '../browserPages';
import { ReplyCheckLine } from './ReplyCheckLine';
import { replyOutcome } from '../replyOutcome';
import { effortWords, isCliRunLine } from '../reasoningEcho';
import { FailoverNote, REPLY_NAME, REPLY_NAME_LINE_LIVE_HEIGHT, ReplyMeta, replyNameLine } from './ReplyMeta';
import { assignSwitchNotes, liveSwitchNote, type SwitchNote } from '../failoverNotes';
import { savedFailoverHandoff, savedFailoverNotice } from '../failover';
import { SuggestionMeta, parseSuggestionMeta } from '../mcpSuggestions';
import { BotActionMeta, HireMeta, parseBotActionMeta, parseHireMeta } from '../botActions';
import {
  AttachmentRef,
  MAX_ATTACHMENTS,
  PendingUpload,
  UploadError,
  composerReady,
  filesFrom,
  isSharedFileMessage,
  parseAttachments,
  preflightFile,
  readyAttachments,
  uploadWithRetry,
  uploadRetryable,
  uploadSlotsLeft,
  pointPicks,
  ATTACH_TITLE,
} from '../attachments';
import type { Attachment } from '../attachments';
import type { PointSink } from './PointLayer';
import { DropRecipient, FOLDER_NOTE, dragHasFiles, dropAnnouncement, dropCard, leaveMs, modalOpen, previewDrag, splitDrop, windowDragWatch } from '../dragPreview';
import { DropBot, DropLayer, DropPhase } from './DropLayer';
import { EarlierCopies, FileTiles, PointChip, UploadChip } from './Attachments';
import { arrangeSharedFiles, botDisplayName, botOf, madeWithCaption, shareInfo } from '../sharedFiles';
import { parseToolNoteMeta } from '../toolNotes';
import { ToolFailureLine } from './ToolFailureLine';
import { parseToolFailureMeta } from '../toolFailures';
import { ToolNoteLine } from './ToolNoteLine';
import { ranOnLabel } from '../engines';
import { replyCostWords, replyTokens } from '../modelUsage';
import { parseRoutingMeta, ranOnAccount } from '../spaces';
import { SetupNeededCard, parseSetupMeta } from './SetupNeededCard';
import { ConnectionSuggestionMeta, parseConnectionMeta } from '../connectionSuggestions';
import { routeReasonText, routeWhyText } from '../routeReason';
import { useInbox } from '../inboxStore';
import { doneItemsOf, doneOf } from '../replyDone';
import { APPROVE_TEXT, approveRowId, changePlaceholder, refocusAfterApprove } from '../approvalAsk';
import { DoneCheckLine } from './DoneMarker';
import { ApproveRow } from './ApproveRow';
import { CopyGhost } from './CopyGhost';
import { copyText } from '../copyText';
import { ContinuedLine, MessageMore, MessageMoreError } from './MessageMore';
import { CONTINUE_LABEL, canContinueFrom } from '../continueChat';
import { RoutineRow } from './RoutineRow';
import { routineOf } from '../routineRow';
import { BudgetPausedNotice, ExpiredApprovalNotice, HandoffCappedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';
import { chainBudgetApi, parseBudgetPaused, parseHandoffCapped } from '../chainBudget';
import { parseSpendStopped } from '../spendStop';
import { SpendStoppedNotice } from './SpendStop';
import { awayApi } from '../away';
import { parseBudgetNotice } from '../botBudget';
import { BudgetNotice, BudgetPausedBanner, useBudgets } from './BotBudget';
import { isSystemNotice, parseExpiredApproval, parseInterruption, retryTargets } from '../interruptions';
import { parseIsolationFailed, parseRequestLimit } from '../isolationNotice';
import { IsolationNotice, RequestLimitNotice } from './IsolationNotice';
import { IDEA_MAX, isIdeaCommand } from '../ideas';
import { ideaBlockedLine, ideaLength } from '../ideaShell';
import { JarIcon } from './JarIcon';
import { consultedNames, hideStreamingDecisions, messageDecisions, parseWorkAhead } from '../decideFirst';
import { approvalScrollAction, fullyVisible, isNearBottom, nextFollowing } from '../approvalVisibility';
import { approvalPillShows, stripStepsAside } from '../askHere';
import { DecidingLine, DecisionChips, WorkAheadBody } from './Proactive';
import { RouteChoiceMeta, parseRouteChoiceMeta, questionsOfReplies } from '../routeChoice';
import { SmartActionsSlot } from './results/SmartActions';
import { WorkingStrip } from './WorkingStrip';
import { ScrollRow } from './ScrollRow';
import { liveBubble, waitingOn } from '../workingStrip';
import { COMPOSE_PREFILL_EVENT, withPrefill } from './results/SmartResult';
import { FilesPreviewOnly } from './results/Files';
import { ReactionButtons, ReplyButton, ReplyChip, ReplyQuote } from './MessageReactions';
import { DictationAnnouncer, DictationLine, DictationSetupPopover, MicButton, useDictation } from './DictationMic';
import { ReactResult, Reaction, ReplyRef, botNameOf, excerptOf, questionMessageId, reactionOf, replyRefOf } from '../reactReply';
import type { FloorResolveOpts } from '../dev/types';
import { useAfterRender } from '../focusAfterRender';

/** 31q: px the desktop mention tag keeps clear below the composer's top hairline. */
const NEW_TAG_CLEAR = 4;

export interface ChatMessage {
  id: string;
  sender_role: 'user' | 'kwant' | 'system';
  sender_id: string;
  text: string;
  reasoning_content?: string | null;
  tool_calls?: string | null;
  tokens_used?: number;
  channel_id?: string | null;
  direct_kwant_id?: string | null;
  thread_id?: string | null;
  /** JSON string kwnt sets on messages it writes itself, e.g. delegation notes. */
  meta?: string | null;
  created_at?: string | null;
  /** Smart Results blocks for a bot reply; null or absent while the setting is off. */
  results?: unknown;
  /** The person's thumbs on a bot reply; absent on servers before reactions (read as none). */
  reaction?: Reaction | null;
  /** The message the person replied to; absent or null when it isn't a reply. */
  reply_to?: ReplyRef | null;
}

/** Extra details of a message being sent. */
export interface SendOptions {
  /** The bot message this one replies to. */
  replyTo?: ChatMessage;
}

/** The open chat's turn is waiting for a free slot. */
export interface QueuedState {
  position: number | null;
  reason: 'agent_busy' | 'server_busy' | 'vm_busy';
  /** vm_busy only: how many replies run inside the VM at once. */
  slots?: number;
  speaker: string;
  /** The waiting turn, when known (keys the chips under a running reply). */
  turnId?: string;
  /** Under a running reply: the waiting turn is for a different bot than the one replying (a room), so the line leads with `speaker`. */
  named?: boolean;
}

/** "Drafter: Write" for a resolved approval row; the card's own words, nothing computed. */
function approvalLead(a: PendingApproval): string {
  const d = (a.details ?? {}) as Record<string, unknown>;
  const who = typeof d.kwant_name === 'string' && d.kwant_name ? d.kwant_name : null;
  const what = typeof d.summary === 'string' && d.summary ? d.summary : a.tool_name;
  return who ? `${who}: ${what}` : what;
}

export interface DiscussionState {
  inProgress: boolean;
  teamId?: string;
  contextId?: string;
  teamName?: string;
  currentSpeaker?: string;
  currentTurn?: number;
  totalTurns?: number;
  /** 'handoff' when kwants pulled each other in with @mentions. */
  kind?: string;
  /** Who handed the current speaker the turn. */
  askedBy?: string;
  /** Team discussion phase of the current turn: 'open', 'reply' or 'summary'. */
  phase?: string;
}

export interface RoutingCandidate {
  id: string;
  name: string;
  title: string;
}

export interface RoutingState {
  phase: 'deciding' | 'decided';
  contextId?: string;
  candidates: RoutingCandidate[];
  kwantId?: string;
  kwantName?: string;
  kwantTitle?: string;
  reason?: string;
  mode?: 'direct' | 'discuss' | string;
  /** How many bots Laya chose from, and whether keyword matching stood in for her. */
  candidateCount?: number | null;
  fallback?: boolean;
  matchedTerms?: string[];
  /** How the bot was picked: by role, the team lead as fallback, keywords, or the only choice. */
  basis?: string;
}

// One reply row geometry, shared by the live row and the finished one (16a), so a reply lands without a shift:
// a 36 px avatar column from sm up, a 20 px avatar in the name line on phones, and the same bubble padding.
const REPLY_AVATAR = 36;

/** 23c: someone else's "user" message (a customer, a bot's chat-API post) gets their letter, never the person's avatar. */
function SenderLetter({ name }: { name: string }) {
  const letter = senderLetter(name);
  return (
    <span
      aria-hidden="true"
      data-sender-letter={letter}
      className="w-9 h-9 shrink-0 rounded-full bg-zinc-800 border border-zinc-700/60 text-zinc-200 text-sm font-semibold inline-flex items-center justify-center select-none"
    >
      {letter || <User size={16} className="text-zinc-400" />}
    </span>
  );
}
const REPLY_AVATAR_PHONE = 20;
const REPLY_BUBBLE = 'px-3.5 py-3 sm:p-5 rounded-2xl text-sm leading-relaxed shadow-sm w-full';
const REPLY_BUBBLE_BOT = 'bg-zinc-900/60 text-zinc-200 rounded-tl-sm border border-zinc-800/80';
// 25b: a customer's or a bot's chat-API message, on the left. Outline only: not yours (filled, lighter), not a bot reply (filled); never violet.
const OTHER_BUBBLE = 'bg-transparent text-zinc-200 rounded-tl-sm border border-zinc-700';

export interface ChatViewProps {
  /** H3: a line under the person's held message ("Waiting for Juno: …", Try again), by message id. */
  heldNotes?: Record<string, React.ReactNode>;
  /**
   * The chat is mounted but covered by a page (Settings): it isn't a drop target, so a file drag
   * shows the "Open a chat" pill instead of a layer nobody can see (#478 L4).
   */
  dropOff?: boolean;
  title: string;
  subtitle: string;
  /** The open space, for "Message #general in Work" and Laya's lines. */
  spaceName?: string;
  /** Phones: back to the list. */
  onBack?: () => void;
  messages: ChatMessage[];
  /**
   * The open chat's streaming reply (14b): only the live reply's body subscribes to it, so a token never
   * re-renders this view or its finished messages. App passes this.
   */
  stream?: StreamText;
  /** Without `stream`: the streaming reply as plain props (tests, previews). */
  streamingText?: string;
  streamingThinking?: string;
  /** Tool approvals waiting in this chat, oldest first. */
  pendingApprovals: PendingApproval[];
  /** 0.8.0 B3: this bot's pre-push cards (Dev mode), shown above its approvals. */
  prepush?: React.ReactNode;
  /** Approvals answered in Telegram (G4), kept as a resolved row; `refused` marks a customer's call nobody allowed (22d). */
  settledApprovals?: (PendingApproval & { refused?: true })[];
  isStreaming: boolean;
  streamingSpeakerName?: string;
  /** `attachments` are files already uploaded from the composer. */
  /** Resolves to false when the message couldn't be sent. */
  /** A string back is a `/idea` that didn't go in: the composer gets the text back with that line. */
  onSendMessage: (text: string, attachments: AttachmentRef[], opts?: SendOptions) => void | Promise<boolean | string | void>;
  /** Saves the person's thumbs on a bot reply; absent hides the thumbs. */
  onReact?: (msg: ChatMessage, reaction: Reaction | null) => Promise<ReactResult> | void;
  onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny', opts?: FloorResolveOpts) => void;
  kwants?: Array<{ id: string; name: string; title: string; avatar_sprite: string; preferred_model?: string }>;
  teams?: Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>;
  /** Prompts offered above an empty chat, made from who is in it; none hides the bar. */
  suggestions?: string[];
  /** What kind of chat this is, for the empty-chat home and the composer's "who answers" pill. */
  home?: ChatHome;
  discussionState?: DiscussionState;
  routingState?: RoutingState | null;
  onCancelDiscussion?: () => void;
  teamMembers?: Array<{ id: string; name: string; title: string; avatar_sprite: string }>;
  teamId?: string;
  teamName?: string;
  workspacePath?: string;
  repoUrl?: string;
  onManageTeam?: () => void;
  onEditKwant?: () => void;
  /** Open a bot's Skills tab (the trial card's Open in Skills, A29). */
  onOpenSkills?: (kwantId: string) => void;
  // Grok-style Sandbox VM Pane props
  isVmPaneOpen?: boolean;
  onToggleVmPane?: () => void;
  activeUrl?: string;
  pageTitle?: string;
  screenshotBase64?: string | null;
  isRunning?: boolean;
  browserError?: string | null;
  terminalLogs?: TerminalLogEntry[];
  onRefreshVm?: () => void;
  onRestartVm?: () => void;
  onNavigateVm?: (url: string, page?: string | null) => void;
  /** Some bot in the space runs without asking (the saved-passwords note). */
  vmApprovalsOff?: boolean;
  /** The CAPTCHA the open bot's browser waits on, and a counter that opens it to solve. */
  vmCaptchaStep?: HumanStep | null;
  /** The newest open step (any kind) holding this browser. */
  vmHumanStep?: HumanStep | null;
  /** W1: set while this chat's browser is active; the working strip offers Watch when the panel is closed. */
  onWatchBrowser?: () => void;
  /** W3: the panel's switcher between browsing chats. */
  vmSwitcher?: { entries: SwitchEntry[]; current: string; onPick: (owner: string) => void } | null;
  /** Answers that step as done from the browser; resolves to an error message on failure. */
  onVmStepDone?: (id: string) => Promise<string | void> | void;
  vmSolveRequest?: number;
  /** 0.9.3: show this page of the team's browser (a card's Sign in / Solve); `n` goes up per ask. */
  vmPagePick?: { page: string; n: number } | null;
  /** Bot names by id, for the pane's page strip. */
  vmBotNames?: Record<string, string>;
  /** Show it once: the single bot this chat's browser belongs to (absent in teams and channels). */
  vmShowOnceBot?: { id: string; name: string };
  /** 0.9.8 browser panel: this chat's browser owner has a turn running (Live / Browsing now). */
  vmRunning?: boolean;
  /** 0.9.8: the person opened the panel (a chip): opens it, or marks a panel the bot opened as theirs. */
  onVmOpenByPerson?: () => void;
  /** 0.9.8: the person used the panel, so it won't close itself. */
  onVmTouch?: () => void;
  /** 0.9.8: control and pending Point picks, which also keep it open. */
  onVmUsage?: (u: { control: boolean; pointPending: boolean }) => void;
  /** 0.9.8: the panel is playing its close animation. */
  vmClosing?: boolean;
  /** Pinned team/channel instructions, shown collapsed above the messages. */
  pinned?: PinnedItem[];
  /** Opens the channel's instructions editor; only for channels. */
  onEditInstructions?: () => void;
  /**
   * Continue in a new chat from here (continueChat.ts): set only in a chat with one bot on a person's session.
   * Resolves to an error line when it failed; on success the app opens the new chat.
   */
  onContinueFrom?: (msg: ChatMessage) => Promise<string | void>;
  /** The open thread's kind ('chat' or 'delegation'); absent in the bot's main chat. */
  threadKind?: string | null;
  /** A continued chat's quiet first line, linking back to the message it came from. */
  continuedFrom?: { text: string; onOpen: () => void } | null;
  /** Goes up when the composer should take focus (a new continued chat just opened). */
  focusComposerKey?: number;
  /** A message to scroll to and flash (from search). */
  highlightMessageId?: string | null;
  /** 22i: also ring what `highlightMessageId` lands on (a Needs-attention row's ask), like a pre-push card. */
  highlightRing?: boolean;
  /** 22i: the "Needs you" strip, right above the composer. */
  needsYouStrip?: React.ReactNode;
  /** 22i: the strip shows an ask here, so the working line drops its own "Answer ↑". */
  needsYouOpen?: boolean;
  /** 29w: the strip's only ask is this chat's live approval, so it steps aside while that card's buttons are on screen. */
  stripOnlyApproval?: boolean;
  /** 30a: the strip offers "Go to the approval" for a live approval here, so the "Approval waiting" pill steps aside. */
  stripHasApproval?: boolean;
  onHighlightDone?: () => void;
  /** Set while `messages` is an older window (a search hit beyond the latest page). */
  viewingHistory?: boolean;
  /** Leaves that window for the latest messages. */
  onJumpToLatest?: () => void;
  /** Under the header: the bot's conversations and the open thread's controls. */
  subHeader?: React.ReactNode;
  /** Phone only: the header's second line in place of the subtitle (the thread picker in a bot's chat). */
  threadLine?: React.ReactNode;
  /** A note under the sub-header (the setup banner); hidden while `welcome` fills an empty chat. */
  notice?: React.ReactNode;
  /** Drawn in place of an empty chat (the first-run welcome). */
  welcome?: React.ReactNode;
  /** 0.7.7 T5: first in the message stream (a template team's Needs card); not a message. */
  topCard?: React.ReactNode;
  /** Next to the title, e.g. "Working on …" while the bot has background turns. */
  titleExtra?: React.ReactNode;
  /** Set while the open chat's turn waits in the queue. */
  queued?: QueuedState | null;
  /** P6: turns waiting behind the reply that runs in this chat, oldest first. Drawn under that reply. */
  queuedBeside?: QueuedState[];
  /** Draws a delegation note or result (messages with delegation `meta`). */
  renderDelegation?: (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => React.ReactNode;
  /** Draws a bot's question card (messages with `ask_user` meta). */
  renderQuestion?: (msg: ChatMessage, meta: QuestionMeta, flash: boolean) => React.ReactNode;
  /** Draws a bot's tool suggestion card (messages with `mcp_suggestion` meta). */
  renderMcpSuggestion?: (msg: ChatMessage, meta: SuggestionMeta, flash: boolean) => React.ReactNode;
  /** Draws a bot's offer to connect an app (message meta kind "connection_suggestion"). */
  renderConnectionSuggestion?: (msg: ChatMessage, meta: ConnectionSuggestionMeta, flash: boolean) => React.ReactNode;
  /** A change a bot made in the app (message meta kind "bot_action"). */
  renderBotAction?: (msg: ChatMessage, meta: BotActionMeta, flash: boolean) => React.ReactNode;
  /** 0.9.0 P5: a bot's tool-note line (meta kind "tool_note"); "See the note" opens it on Connections. */
  onOpenToolNote?: (noteId: string) => void;
  /** 0.9.5: a connection-failure line's fix button (meta kind "tool_failure") opens Connections. */
  onOpenConnections?: () => void;
  /** A mission watcher's check report (message meta kind "watch"). */
  renderWatchReport?: (msg: ChatMessage, meta: WatchMeta, flash: boolean) => React.ReactNode;
  /** A bot's proposal to hire a new bot (message meta kind "hire_proposal"). */
  renderHire?: (msg: ChatMessage, meta: HireMeta, flash: boolean) => React.ReactNode;
  /** Laya's "Who should answer this?" card (message meta kind "route_choice"); `question` is the
   *  person's message it is about, when it's loaded. */
  renderRouteChoice?: (msg: ChatMessage, meta: RouteChoiceMeta, flash: boolean, question?: string) => React.ReactNode;
  /** Bots a routed reply can be sent to instead ("Wrong bot? Send to…"); empty hides it. */
  rerouteTargets?: Array<{ id: string; name: string; title: string }>;
  /** Teaches routing that `question` should have gone to `kwantId` and asks that bot now.
   *  Resolves to an error message on failure. */
  onSendToOtherBot?: (question: ChatMessage, kwantId: string) => Promise<string | void>;
  /** Opens Space settings → Accounts; turns a "nothing can run" reply into a card with a button. */
  onOpenAccounts?: () => void;
  /** The space's real id (spc_…): the dictation mic asks it whether it can turn speech into text. */
  spaceId?: string;
  /** A short notice at the corner of the window (dictation stopped because you left the chat). */
  onToast?: (title: string, detail?: string) => void;
  /** Opens Settings › All spaces › Usage at the daily spending stop. */
  onOpenUsage?: () => void;
  /** Opens App settings at the Computer card, "Run Claude inside the VM" focused (isolation notices). */
  onOpenComputerSettings?: () => void;
  /** 0.9.5: the bot this 1:1 chat is with; its monthly-budget pause shows above the box. */
  budgetBotId?: string | null;
  /** 0.9.5: opens a bot's settings at its monthly budget, the first field focused. */
  onRaiseBudget?: (kwantId: string) => void;
  /** Opens Manage Team with its folder input focused (isolation notices 6 and 7). */
  onChangeTeamFolder?: (teamId: string) => void;
  /** Opens the named bot's Edit modal on Profile, where its AI is picked (notice 7). */
  onEditBot?: (botName: string) => void;
  /** Whether anything can run a bot in this space now (null while unknown). */
  canRun?: boolean | null;
  /** Whether Ollama answers now (null while unknown), for a bot's "Ollama isn't answering" card. */
  ollamaReady?: boolean | null;
  /** Checks the engines again, from that card's Re-check button. */
  onRecheckEngines?: () => void;
  recheckingEngines?: boolean;
  /** The open chat's turn is paused on a question: it is waiting for the person, not working. */
  awaitingAnswer?: boolean;
  /** …and the pause is a browser step (sign-in, CAPTCHA) rather than a question. */
  awaitingBrowser?: boolean;
  /** The bot whose question the open chat's turn waits on (its id and name), for the waiting banner. */
  awaitingBot?: { id: string; name: string } | null;
  /** The running reply's steps so far (thinking, tools, waits). */
  liveActivity?: LiveActivity | null;
  /** 16b: the running turn double-checks another bot's work: its line and a way to the audited task. */
  liveAudit?: { line: string; short?: string; onOpenTask?: () => void } | null;
  /** Draws a bot's browser-step card (message meta kind "human_step"). */
  renderHumanStep?: (msg: ChatMessage, meta: HumanStepMeta, flash: boolean) => React.ReactNode;
  /** Changes when another chat opens, so the view jumps to its bottom. */
  contextKey?: string;
  /** Set while a held reply in this chat is being decided ("Team is deciding…"). */
  deciding?: { botName: string; consulted: string[] } | null;
  /** Change on a decision chip; resolves to an error message on failure. */
  onChangeDecision?: (msg: ChatMessage, index: number, picked: string) => Promise<string | void>;
  /** Quiet "answered on another account" lines, one per outage; each shows under that bot's name. */
  switchNotes?: SwitchNote[];
}

export const renderFormattedText = (text: string): React.ReactNode => {
  if (!text) return null;
  const parts = text.split(/(@[a-zA-Z0-9_-]+)/g);
  return parts.map((part, index) => {
    if (part.startsWith('@') && /^@[a-zA-Z0-9_-]+$/.test(part)) {
      return (
        <span
          key={index}
          className="inline-flex items-center px-1.5 py-0.5 rounded text-sky-400 bg-sky-500/10 font-medium text-[11px] border border-sky-500/20"
        >
          {part}
        </span>
      );
    }
    return part;
  });
};

const LayaRoutingCard: React.FC<{ routing: RoutingState; spaceName?: string }> = ({ routing, spaceName }) => {
  const deciding = routing.phase === 'deciding';
  const isDiscuss = routing.mode === 'discuss';
  const why = routeReasonText(routing);
  const pool = routing.candidateCount ?? (routing.candidates.length || null);
  const where = spaceName ? ` in ${spaceName}` : '';

  return (
    <div className="flex items-start gap-3.5 w-full max-w-5xl" aria-live="polite">
      <div className="w-[34px] h-[34px] flex-shrink-0 rounded-full bg-sky-500/15 border border-sky-500/40 flex items-center justify-center shadow-sm shadow-sky-500/10">
        <Sparkles size={16} className={`text-info ${deciding ? 'animate-pulse' : ''}`} />
      </div>
      <div className="flex flex-col items-start min-w-0 flex-1 max-w-4xl">
        <div className="flex items-center gap-2 mb-1.5 text-[11px] text-zinc-400 font-medium">
          <span className="text-zinc-200">Laya</span>
          <span className="text-zinc-500">· router</span>
        </div>
        <div className="px-4 py-3 rounded-2xl rounded-tl-sm bg-sky-950/20 border border-sky-500/20 text-sm text-zinc-200 shadow-sm w-full">
          {deciding ? (
            <div className="flex items-center gap-2">
              <span>
                {pool ? `Choosing from ${pool} ${pool === 1 ? 'bot' : 'bots'}${where}` : `Choosing who's best to answer${where}`}
              </span>
              <span className="inline-flex gap-0.5" aria-hidden="true">
                {[0, 1, 2].map((i) => (
                  <span
                    key={i}
                    className="w-1 h-1 rounded-full bg-sky-300 animate-bounce"
                    style={{ animationDelay: `${i * 150}ms` }}
                  />
                ))}
              </span>
            </div>
          ) : (
            <div className="flex flex-col gap-0.5">
              <div className="flex items-center gap-1.5 flex-wrap">
                <span>{isDiscuss ? 'Starting a team discussion led by' : 'Sending your question to'}</span>
                <span className="font-semibold text-sky-200">{routing.kwantName}</span>
                {routing.kwantTitle && <span className="text-zinc-400 text-xs">({routing.kwantTitle})</span>}
              </div>
              {why && <span className="text-xs text-zinc-400">{why}</span>}
              {routing.fallback && <span className="text-xs text-amber-300/90">Picked by keywords (Laya is offline)</span>}
            </div>
          )}

          {routing.candidates.length > 0 && (
            <div className="mt-2.5 flex items-center gap-1.5 flex-wrap">
              {routing.candidates.map((c, i) => {
                const chosen = !deciding && c.id === routing.kwantId;
                return (
                  <div
                    key={c.id}
                    title={`${c.name} — ${c.title}`}
                    className={`flex items-center gap-1.5 pl-0.5 pr-2.5 py-0.5 rounded-full border text-[11px] transition-all duration-300 ${
                      chosen
                        ? 'border-sky-400/60 bg-sky-500/20 text-sky-100 scale-105'
                        : deciding
                          ? 'border-zinc-700/60 bg-zinc-900/60 text-zinc-300 animate-pulse'
                          : 'border-zinc-800 bg-zinc-900/40 text-zinc-500 opacity-50'
                    }`}
                    style={deciding ? { animationDelay: `${i * 200}ms` } : undefined}
                  >
                    <ModernAvatar role={c.name} name={c.name} size={18} />
                    <span>{c.name}</span>
                    {chosen && <Check size={11} className="text-info" />}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

/** True below Tailwind's sm breakpoint, kept in sync with resizes. */
const useNarrow = () => {
  const query = '(max-width: 639px)';
  const [narrow, setNarrow] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(query).matches);
  useEffect(() => {
    const mq = window.matchMedia?.(query);
    if (!mq) return;
    const on = () => setNarrow(mq.matches);
    mq.addEventListener('change', on);
    return () => mq.removeEventListener('change', on);
  }, []);
  return narrow;
};

/**
 * The live reply's words or thinking line (14b): the one place that re-renders with the stream, at most
 * once a frame. The finished messages around it never do. `onGrow` keeps the bottom pinned. Its markdown
 * renders a block at a time (15a, StreamMarkdown): only the open block at the end is parsed each frame.
 */
const StreamPart = React.memo(function StreamPart({ stream, part, onGrow }: { stream: StreamText; part: keyof StreamView; onGrow: () => void }) {
  const streamingText = useStreamPart(stream, part);
  useEffect(onGrow, [streamingText, onGrow]);
  if (part === 'thinking') return <>{streamingText}</>;
  return (
    <div className="kw-wa-in kw-wa-hold">
      <StreamMarkdown content={hideStreamingDecisions(stripDiscussionMarkers(streamingText))} />
    </div>
  );
});

export const ChatView: React.FC<ChatViewProps> = ({
  heldNotes,
  dropOff = false,
  title,
  subtitle,
  spaceName,
  onBack,
  messages,
  stream: streamProp,
  streamingText: streamingTextProp = '',
  streamingThinking: streamingThinkingProp = '',
  pendingApprovals,
  prepush,
  settledApprovals = [],
  isStreaming,
  streamingSpeakerName,
  onSendMessage,
  onReact,
  onResolveApproval,
  kwants: kwantsProp,
  teams: teamsProp,
  suggestions = [],
  home,
  discussionState,
  routingState,
  onCancelDiscussion,
  teamMembers,
  teamId,
  teamName,
  workspacePath,
  repoUrl,
  onManageTeam,
  onEditKwant,
  onOpenSkills,
  isVmPaneOpen,
  onToggleVmPane,
  activeUrl,
  pageTitle,
  screenshotBase64,
  isRunning = true,
  browserError,
  terminalLogs = [],
  onRefreshVm,
  onRestartVm,
  onNavigateVm,
  vmApprovalsOff,
  vmCaptchaStep,
  vmHumanStep,
  onWatchBrowser,
  vmSwitcher,
  onVmStepDone,
  vmSolveRequest,
  vmPagePick,
  vmBotNames,
  vmShowOnceBot,
  vmRunning = false,
  onVmOpenByPerson,
  onVmTouch,
  onVmUsage,
  vmClosing = false,
  pinned = [],
  onEditInstructions,
  highlightMessageId,
  highlightRing,
  needsYouStrip,
  needsYouOpen,
  stripOnlyApproval = false,
  stripHasApproval = false,
  onContinueFrom,
  threadKind,
  continuedFrom,
  focusComposerKey,
  onHighlightDone,
  viewingHistory,
  onJumpToLatest,
  subHeader,
  threadLine,
  notice,
  welcome,
  topCard,
  titleExtra,
  queued,
  queuedBeside,
  renderDelegation,
  renderQuestion,
  switchNotes,
  renderMcpSuggestion,
  renderConnectionSuggestion,
  renderBotAction,
  onOpenToolNote,
  onOpenConnections,
  renderWatchReport,
  renderHire,
  renderRouteChoice,
  rerouteTargets = [],
  onSendToOtherBot,
  onOpenAccounts,
  spaceId,
  onToast,
  onOpenUsage,
  onOpenComputerSettings,
  budgetBotId = null,
  onRaiseBudget,
  onChangeTeamFolder,
  onEditBot,
  canRun = null,
  ollamaReady = null,
  onRecheckEngines,
  recheckingEngines,
  awaitingAnswer,
  awaitingBrowser,
  awaitingBot,
  liveActivity,
  liveAudit,
  renderHumanStep,
  contextKey,
  deciding,
  onChangeDecision,
}) => {
  const narrow = useNarrow();
  const [internalIsVmPaneOpen, setInternalIsVmPaneOpen] = useState(false);
  const vmOpen = isVmPaneOpen !== undefined ? isVmPaneOpen : internalIsVmPaneOpen;
  const toggleVm = onToggleVmPane || (() => setInternalIsVmPaneOpen((prev) => !prev));

  const [inputVal, setInputVal] = useState('');
  // Phone (spec A1): keyboard mode while the composer has focus on a touch screen; the composer is two
  // rows while in use. Desktop never changes.
  const phone = useMedia(PHONE_QUERY);
  const touch = useMedia(TOUCH_QUERY);

  const [composerFocused, setComposerFocused] = useState(false);
  const kbd = keyboardMode({ phone, touch, focused: composerFocused });
  const [fieldWidth, setFieldWidth] = useState(0);
  const [uploads, setUploads] = useState<PendingUpload[]>([]);
  const stacked = composerStacked({ phone, focused: composerFocused, hasContent: inputVal.length > 0 || uploads.length > 0 });
  const [uploadNote, setUploadNote] = useState<string | null>(null);
  const uploadFiles = useRef(new Map<string, { file: File; abort: AbortController }>());
  const fileInputRef = useRef<HTMLInputElement>(null);
  // 0.8.0 drag and drop (Mira's design): the window knows a file drag is in it; this chat knows the
  // pointer is over its column (header, list and composer, not a side pane).
  const dragWatch = windowDragWatch();
  const winDrag = useSyncExternalStore(dragWatch.subscribe, dragWatch.get, dragWatch.get);
  useEffect(() => (dropOff ? undefined : dragWatch.registerChat()), [dragWatch, dropOff]);
  const overDepth = useRef(0);
  const [overChat, setOverChat] = useState(false);
  // The window watch renders the armed card at sync priority; the pane's own over/refused change has to
  // land in that same task, or the browser can paint one frame of "Drop here…" before the real card
  // (drag events are continuous priority, so a plain setState renders a scheduler task later).
  const overNow = useRef(false);
  const markOver = (v: boolean) => {
    if (overNow.current === v) return;
    overNow.current = v;
    flushSync(() => setOverChat(v));
  };
  const headerRef = useRef<HTMLDivElement>(null);
  const columnRef = useRef<HTMLDivElement>(null);
  const composerWrapRef = useRef<HTMLDivElement>(null);
  const { byBot: budgetsByBot } = useBudgets();
  const chatBudget = budgetBotId ? budgetsByBot[budgetBotId] : undefined;
  // 31x: a paused budget is a lasting state (its banner replaces the tag until it clears), not a passing overlay,
  // so like streaming it makes no room; the room comes back when the budget clears and "mention" is still new.
  const budgetPaused = chatBudget?.state === 'paused';
  // 31q: desktop's "New" on "@" sits 6 px above the field (#478). With nothing else above the field it poked
  // past the composer's top edge into the chat and covered whatever scrolled under it. While it shows, the
  // composer grows by exactly that overhang (+4 px clear of the hairline), so the tag never sits on a message;
  // when it goes, so does the room. The chat's own follow-the-bottom pin handles the list getting shorter.
  const mentionNew = useSyncExternalStore(subscribeNew, () => isNewThing('mention'), () => false);
  const [newTagRoom, setNewTagRoom] = useState(0);
  const newTagRoomRef = useRef(0);
  useLayoutEffect(() => {
    const wrap = composerWrapRef.current;
    const set = (v: number) => {
      newTagRoomRef.current = v;
      setNewTagRoom(v);
    };
    if (!wrap || phone || isStreaming || budgetPaused || !mentionNew) return set(0);
    const measure = () => {
      const tag = wrap.querySelector<HTMLElement>('[data-new-tag="mention"]');
      if (!tag) return set(0);
      const r = tag.getBoundingClientRect();
      // Hidden for a moment (picker, dictation, drop layer): keep the room, so the chat doesn't jump.
      if (r.height === 0) return;
      const edge = wrap.getBoundingClientRect().top + wrap.clientTop + NEW_TAG_CLEAR;
      const over = edge - r.top;
      const next = Math.max(0, Math.ceil(newTagRoomRef.current + over));
      if (Math.abs(next - newTagRoomRef.current) >= 1) set(next);
    };
    measure();
    if (typeof ResizeObserver === 'undefined') return;
    const ro = new ResizeObserver(measure);
    ro.observe(wrap);
    return () => ro.disconnect();
  }, [phone, isStreaming, budgetPaused, mentionNew]);
  const rootRef = useRef<HTMLDivElement>(null);
  // Chips that came with the drop that just landed, by key, with their place in it (for the stagger).
  const [freshChips, setFreshChips] = useState<Record<string, number>>({});
  // The drop card's words for screen readers, and "3 files added for Frontend. Uploading." after a drop;
  // cleared shortly after so the same line can be read again.
  const [dropAnnounce, setDropAnnounce] = useState('');
  useEffect(() => {
    if (!dropAnnounce) return;
    const t = setTimeout(() => setDropAnnounce(''), 4000);
    return () => clearTimeout(t);
  }, [dropAnnounce]);
  const [openThoughts, setOpenThoughts] = useState<Record<string, boolean>>({});
  const [copiedId, setCopiedId] = useState<{ id: string; ok: boolean } | null>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  // Dictation (design.md): the mic between @ and Send; one line at the top of the box says what's happening.
  const reducedMotion = useMedia('(prefers-reduced-motion: reduce)');
  const dict = useDictation({
    spaceId,
    chatKey: contextKey,
    phone,
    touch,
    value: inputVal,
    textareaRef,
    setValue: setInputVal,
    onToast: onToast ? (t) => onToast(t) : undefined,
  });

  const handleInsertTag = (tag: string) => {
    playSfx('click');
    setInputVal((prev) => {
      const trimmed = prev.trim();
      return trimmed ? `${trimmed} ${tag} ` : `${tag} `;
    });
    if (textareaRef.current) {
      textareaRef.current.focus();
    }
  };

  // Fallback to fetch kwants and teams if not provided as props
  const [internalKwants, setInternalKwants] = useState<Array<{ id: string; name: string; title: string; avatar_sprite: string; preferred_model?: string }>>([]);
  const [internalTeams, setInternalTeams] = useState<Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>>([]);

  useEffect(() => {
    if (!kwantsProp) {
      fetch('/api/kwants')
        .then((r) => (r.ok ? r.json() : []))
        .then((data) => setInternalKwants(data))
        .catch(() => {});
    }
  }, [kwantsProp]);

  useEffect(() => {
    if (!teamsProp) {
      fetch('/api/teams')
        .then((r) => (r.ok ? r.json() : []))
        .then((data) => setInternalTeams(data))
        .catch(() => {});
    }
  }, [teamsProp]);

  const activeKwants = kwantsProp || internalKwants;
  // Every bot a message here can come from: names and ids resolve against these, never the chat title (P4).
  const knownBots = useMemo(() => {
    const all: Array<{ id: string; name: string }> = [...activeKwants, ...(teamMembers ?? [])];
    if (home?.kind === 'bot' && home.bot) all.push({ id: home.bot.id, name: home.bot.name });
    return all;
  }, [activeKwants, teamMembers, home]);

  // ---------- 0.9.8 browser panel (design browser-panel/design.md A, B) ----------
  // The trail the panel shows: the reply whose chip was tapped; else the running turn's; else the newest reply that browsed.
  const [trailFrom, setTrailFrom] = useState<string | null>(null);
  const liveTurnId = liveActivity?.turnId ?? null;
  useEffect(() => {
    // A new turn browses: the panel follows it, not an older chip's reply
    if (liveTurnId) setTrailFrom(null);
  }, [liveTurnId]);
  const liveSpeaker = streamingSpeakerName || title;
  // Who the live row shows: the current speaker in a discussion, else the replying bot.
  const liveName = discussionState?.inProgress && discussionState.currentSpeaker ? discussionState.currentSpeaker : liveSpeaker;
  const livePages = useMemo(() => pagesOfReply(liveActivity?.steps), [liveActivity?.steps]);
  const savedTrail = useMemo((): { id: string; bot: string; pages: ReplyPage[] } | null => {
    const from = (m: ChatMessage) => {
      if (m.sender_role !== 'kwant' || !m.meta) return null;
      const pages = pagesOfReply(parseActivityMeta(m.meta)?.steps);
      return pages.length ? { id: m.id, bot: botDisplayName(m.sender_id, knownBots), pages } : null;
    };
    if (trailFrom) {
      const m = messages.find((x) => x.id === trailFrom);
      const t = m && from(m);
      if (t) return t;
    }
    for (let i = messages.length - 1; i >= 0; i--) {
      const t = from(messages[i]);
      if (t) return t;
    }
    return null;
  }, [messages, trailFrom, knownBots]);
  const showLiveTrail = !trailFrom && livePages.length > 0;
  const paneTrail = showLiveTrail ? livePages : savedTrail?.pages ?? [];
  const paneBot = showLiveTrail ? liveSpeaker : savedTrail?.bot ?? (home?.kind === 'bot' ? home.bot?.name ?? null : null);
  // "Finished 10:46 PM": when this chat's turn ended here, else the newest page of the shown trail
  const [endedAt, setEndedAt] = useState<string | null>(null);
  const wasRunning = useRef(vmRunning);
  useEffect(() => {
    if (wasRunning.current && !vmRunning) setEndedAt(new Date().toISOString());
    wasRunning.current = vmRunning;
  }, [vmRunning]);
  useEffect(() => setEndedAt(null), [teamId]);
  const paneFinishedAt = trailFrom ? paneTrail[0]?.at ?? null : endedAt ?? paneTrail[0]?.at ?? null;
  const openBrowserFor = (msgId: string | null) => {
    playSfx('click');
    setTrailFrom(msgId);
    if (onVmOpenByPerson) onVmOpenByPerson();
    else if (!vmOpen) toggleVm();
  };
  // Each routed reply's question: the person's latest saved message before it ("Wrong bot?").
  const questionOf = useMemo(() => questionsOfReplies(messages), [messages]);
  const activeTeams = teamsProp || internalTeams;

  const mentionItems: MentionItem[] = [
    ...activeKwants.map((k) => ({
      type: 'kwant' as const,
      id: k.id,
      name: k.name,
      title: k.title,
      goodAt: goodAt(k),
      avatar_sprite: k.avatar_sprite,
    })),
    ...activeTeams.map((t) => ({
      type: 'team' as const,
      id: t.id,
      name: t.name,
      title: t.description || 'Team',
      memberCount: t.member_kwants?.length || 0,
    })),
  ];

  const [mentionQuery, setMentionQuery] = useState<string | null>(null);
  const [mentionStartIndex, setMentionStartIndex] = useState<number>(-1);
  const [selectedIndex, setSelectedIndex] = useState(0);

  const checkMention = (text: string, cursorPos: number | null) => {
    if (cursorPos === null || cursorPos === undefined) {
      setMentionQuery(null);
      setMentionStartIndex(-1);
      return;
    }
    const textBeforeCursor = text.slice(0, cursorPos);
    const match = textBeforeCursor.match(/(?:^|\s)@([a-zA-Z0-9_-]*)$/);
    if (match) {
      const query = match[1];
      const atIndex = textBeforeCursor.lastIndexOf('@');
      setMentionQuery(query);
      setMentionStartIndex(atIndex);
    } else {
      setMentionQuery(null);
      setMentionStartIndex(-1);
    }
  };

  const matchingItems = mentionQuery !== null
    ? mentionItems.filter((item) => {
        const q = mentionQuery.toLowerCase();
        return (
          item.name.toLowerCase().includes(q) ||
          (item.title && item.title.toLowerCase().includes(q)) ||
          (item.goodAt?.some((g) => g.toLowerCase().includes(q)) ?? false)
        );
      })
    : [];

  const isMentionOpen = mentionQuery !== null && matchingItems.length > 0;
  const safeSelectedIndex = Math.min(
    selectedIndex,
    Math.max(0, matchingItems.length - 1)
  );

  useEffect(() => {
    setSelectedIndex(0);
  }, [mentionQuery]);
  // The picker opening by any route (typing "@" or the button) counts as using the new mention: "New" goes.
  useEffect(() => {
    if (isMentionOpen) markNewSeen('mention');
  }, [isMentionOpen]);

  const afterRender = useAfterRender();
  const handleSelectMention = (item: MentionItem) => {
    if (mentionStartIndex < 0) return;
    const cursorPos = textareaRef.current?.selectionStart ?? inputVal.length;
    const textBefore = inputVal.slice(0, mentionStartIndex);
    const textAfter = inputVal.slice(cursorPos);
    markNewSeen('mention');
    const mentionText = `@${item.name} `;
    const newVal = `${textBefore}${mentionText}${textAfter}`;
    setInputVal(newVal);
    setMentionQuery(null);
    setMentionStartIndex(-1);

    const nextCursor = mentionStartIndex + mentionText.length;
    // After the render that shows the new text, so the caret and the height are set on it.
    afterRender(() => {
      if (textareaRef.current) {
        textareaRef.current.focus();
        textareaRef.current.setSelectionRange(nextCursor, nextCursor);
        textareaRef.current.style.height = 'auto';
        textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 160)}px`;
      }
    });
  };

  // Follow new tokens only while the reader is at the bottom; scrolling up to read stays put.
  const stickRef = useRef(true);
  // The streaming reply (14b). Given as props instead of a store, those props feed a store of this view's own.
  const [propStream] = useState(() => createStreamText({ text: streamingTextProp, thinking: streamingThinkingProp }));
  const stream = streamProp ?? propStream;
  useLayoutEffect(() => {
    if (!streamProp) propStream.show({ text: streamingTextProp, thinking: streamingThinkingProp });
  }, [streamProp, propStream, streamingTextProp, streamingThinkingProp]);
  // Whether the reply is writing (has words) or thinking (has a thinking line) yet; each flips once per reply.
  // The words themselves reach StreamPart alone.
  const writing = useStreamWriting(stream) || (!streamProp && !!streamingTextProp);
  const thinking = useStreamThinking(stream) || (!streamProp && !!streamingThinkingProp);
  const lastScrollTopRef = useRef(0);
  // The empty chat's home and Get started open at their top: on a phone both are taller than the screen, and their heads come first (13d, 29u).
  const homeShowingRef = useRef(false);
  const pinToBottom = (el: HTMLDivElement) => {
    el.scrollTop = homeShowingRef.current ? 0 : el.scrollHeight;
    lastScrollTopRef.current = el.scrollTop;
  };
  // A waiting card whose buttons are off screen while the person reads further up.
  const [approvalOffscreen, setApprovalOffscreen] = useState(false);
  // 29w: some card's Allow / Deny row is fully on screen (the same measurement), so the strip need not repeat it.
  const [approvalCardInView, setApprovalCardInView] = useState(false);
  // ...or the chat follows the bottom with a card in it (the follow pin would undo the strip coming back there).
  const [followingCard, setFollowingCard] = useState(false);
  const approvalKey = pendingApprovals.map((a) => a.id).join(',');
  const checkApprovalVisible = () => {
    const el = scrollRef.current;
    if (!el) return;
    const view = el.getBoundingClientRect();
    const rows = Array.from(el.querySelectorAll<HTMLElement>('[data-approval-actions]'));
    const buttonsVisible = rows.some((r) => fullyVisible(r.getBoundingClientRect(), view));
    const action = approvalScrollAction({ waiting: rows.length, following: stickRef.current, buttonsVisible });
    setApprovalOffscreen(action === 'notify');
    setApprovalCardInView(buttonsVisible);
    setFollowingCard(stickRef.current && rows.length > 0);
  };
  const onScroll = () => {
    const el = scrollRef.current;
    if (el) {
      stickRef.current = nextFollowing(stickRef.current, { nearBottom: isNearBottom(el), scrollTop: el.scrollTop, lastScrollTop: lastScrollTopRef.current });
      lastScrollTopRef.current = el.scrollTop;
    }
    checkApprovalVisible();
  };
  // Phone (0.6.13 spec A3/C2): the working strip is the one live line, so the stream drops what repeats it.
  // (`phone` is the A1 PHONE_QUERY flag above).
  const stripWaitsOn = isStreaming ? waitingOn({ live: liveActivity, queued: !!queued, awaitingAnswer: !!awaitingAnswer, awaitingBrowser: !!awaitingBrowser }) : null;
  // What the live bubble holds before its first words: a pending approval reads as "waiting for your OK", not loading.
  const bubble = liveBubble({ live: liveActivity, queued: !!queued, awaitingAnswer: !!awaitingAnswer, awaitingBrowser: !!awaitingBrowser, writing });
  // The strip's "Answer ↑": the open question card, else the approval card, fully in view.
  const showWaitingCard = (on: 'question' | 'approval') => {
    if (on === 'approval') return showApproval();
    const cards = scrollRef.current?.querySelectorAll<HTMLElement>('[data-question-card="open"]');
    const card = cards?.[cards.length - 1];
    if (!card) return;
    const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
    card.scrollIntoView({ block: 'nearest', behavior: reduce ? 'auto' : 'smooth' });
    // Keyboard users land on the card: its first choice, else its answer field (the amber ring shows where).
    const target = card.querySelector<HTMLElement>('button[aria-pressed]') ?? card.querySelector<HTMLElement>('textarea');
    target?.focus({ preventScroll: true });
  };
  // Waiting state (UX audit #2): the only open thing is a question, so the chat waits for the person.
  const askOnly = onlyAskOpen({
    streaming: isStreaming,
    awaitingAnswer: !!awaitingAnswer,
    awaitingBrowser: !!awaitingBrowser,
    approvalOpen: pendingApprovals.length > 0,
    queued: !!queued,
    writing,
  });
  // Team words ("Stop team", the rail) only for a team turn; a single bot asking in a channel gets "Stop".
  const teamChat = isTeamTurn(home?.kind, !!discussionState?.inProgress);
  const askRail = askOnly && teamChat ? turnRail(messages, awaitingBot?.id, (id) => botOf(id, knownBots)) : [];
  const showApproval = () => {
    const cards = scrollRef.current?.querySelectorAll<HTMLElement>('[data-approval-card]');
    const card = cards?.[cards.length - 1];
    if (!card) return;
    // 30a: started from the keyboard (the pill or "Answer ↑" had keyboard focus), focus lands on the card itself,
    // never on Allow / Deny, so a second Enter can't approve. A tap or click never moves focus.
    const from = document.activeElement;
    const keyboard = from instanceof HTMLButtonElement && from.matches(':focus-visible');
    const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
    card.scrollIntoView({ block: 'end', behavior: reduce ? 'auto' : 'smooth' });
    setApprovalOffscreen(false);
    if (keyboard) card.focus({ preventScroll: true });
  };
  // 29w: the Needs-you strip steps aside while its one ask is the live approval whose buttons are on screen.
  const stripAside = stripStepsAside({ strip: !!needsYouStrip, onlyApproval: stripOnlyApproval, cardInView: approvalCardInView, followingCard });
  const stripSlotRef = useRef<HTMLDivElement | null>(null);
  const stripHadFocusRef = useRef(false);
  // Its "Go to the approval" brings the card into view and the strip goes: focus that was in it goes to the
  // composer (as when the strip leaves), never to the page body.
  useLayoutEffect(() => {
    if (!stripAside || !stripHadFocusRef.current) return;
    stripHadFocusRef.current = false;
    const a = document.activeElement;
    if (!a || a === document.body || stripSlotRef.current?.contains(a)) textareaRef.current?.focus({ preventScroll: true });
  }, [stripAside]);
  // The running turn's summary line (WorkingStrip): inside the composer section, right above the box.
  const budgetBanner = chatBudget?.state === 'paused' ? <BudgetPausedBanner budget={chatBudget} onRaise={onRaiseBudget} /> : null;
  // Waiting state: the banner says whose move it is, so no strip and no running clock.
  const workingStrip = askOnly ? null : (
    <WorkingStrip
      active={isStreaming}
      name={discussionState?.inProgress && discussionState.currentSpeaker ? discussionState.currentSpeaker : streamingSpeakerName || title}
      title={title}
      live={liveActivity}
      queued={!!queued}
      awaitingAnswer={!!awaitingAnswer}
      awaitingBrowser={!!awaitingBrowser}
      writing={writing}
      // 22i: one ask gets one button. While the Needs-you strip shows it, the strip's Go to … is that button.
      onAnswer={needsYouOpen ? undefined : showWaitingCard}
      onWatch={onWatchBrowser && !vmOpen ? onWatchBrowser : undefined}
      phone={phone}
      audit={liveAudit}
    />
  );
  // Cards are last in the stream. While the person follows the chat, keep the bottom pinned when a
  // card grows after it appears (its details arrive from the server) or the composer grows and
  // shrinks the stream, so Deny / Allow never sit below the composer.
  useEffect(() => {
    const el = scrollRef.current;
    if (!el || typeof ResizeObserver === 'undefined') return;
    const ro = new ResizeObserver(() => {
      if (stickRef.current) pinToBottom(el);
      checkApprovalVisible();
    });
    ro.observe(el);
    el.querySelectorAll('[data-approval-card]').forEach((c) => ro.observe(c));
    return () => ro.disconnect();
  }, [approvalKey]);
  useEffect(() => {
    stickRef.current = true;
  }, [contextKey]);
  // Phone: the field's width picks the placeholder (A1), and its height follows when it moves between
  // one row and two. Keyboard mode keeps the last message in view while the chat follows the bottom.
  useEffect(() => {
    const el = textareaRef.current;
    if (!el || !phone) return;
    const measure = () => setFieldWidth(el.clientWidth);
    measure();
    if (typeof ResizeObserver === 'undefined') return;
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    return () => ro.disconnect();
  }, [phone]);
  useLayoutEffect(() => {
    const el = textareaRef.current;
    if (el && phone && el.value) {
      el.style.height = 'auto';
      el.style.height = `${Math.min(el.scrollHeight, 160)}px`;
    }
    if (scrollRef.current && stickRef.current) pinToBottom(scrollRef.current);
  }, [kbd, stacked]);
  // Back from an older window: land on the newest message
  useEffect(() => {
    if (!viewingHistory) stickRef.current = true;
  }, [viewingHistory]);
  useEffect(() => {
    if (scrollRef.current && stickRef.current) pinToBottom(scrollRef.current);
    checkApprovalVisible();
  }, [messages, writing, thinking, approvalKey, routingState, queued, contextKey]);
  // Each streamed update (at most one a frame) keeps the bottom pinned while the person follows the chat.
  const onStreamGrowRef = useRef(() => {});
  onStreamGrowRef.current = () => {
    if (scrollRef.current && stickRef.current) pinToBottom(scrollRef.current);
    checkApprovalVisible();
  };
  const [onStreamGrow] = useState(() => () => onStreamGrowRef.current());

  // Jump to a search hit: open its folded discussion if needed, then centre and flash it.
  // Runs after the auto-scroll above, so it wins.
  const [flashId, setFlashId] = useState<string | null>(null);
  // A search hit glows amber for 2.4 s; the original of a reply quote gets a violet ring for 1.6 s.
  // 22i: a Needs-attention landing ('ask') is the same amber flash as search, tagged so tests tell them apart.
  const [flashKind, setFlashKind] = useState<'search' | 'quote' | 'ask'>('search');
  // 30n: a second "Go to the approval" (or search hit) on what is already flashing restarts the ring and its 2.4 s;
  // 30q: so does a second quote jump (1.6 s). Clear the flash, then set it again. Setting the same id again would
  // change nothing. The second step waits for the cleared flash to commit, then two frames, so the browser draws a frame without
  // kw-flash and the CSS animation starts over (rAFs queued at once can both run before React commits the null).
  const [flashNext, setFlashNext] = useState<string | null>(null);
  const restartFlash = (id: string, kind: 'search' | 'quote' | 'ask') => {
    setFlashId(null);
    setFlashKind(kind);
    setFlashNext(id);
  };
  useEffect(() => {
    if (!flashNext) return;
    let f = requestAnimationFrame(() => {
      f = requestAnimationFrame(() => {
        setFlashId(flashNext);
        setFlashNext(null);
      });
    });
    return () => cancelAnimationFrame(f);
  }, [flashNext]);
  useEffect(() => {
    if (!highlightMessageId) return;
    // 0.8.1 F6: an approval's card (a notification names it), not a message
    if (pendingApprovals.some((a) => a.id === highlightMessageId)) {
      const card = scrollRef.current?.querySelector<HTMLElement>(`[data-approval-card="${CSS.escape(highlightMessageId)}"]`);
      if (!card) return;
      const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
      card.scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' });
      // 30a: the strip's "Go to the approval" pressed from the keyboard lands focus on the card (as the question
      // card's first choice does), never on Allow / Deny. A tap, an Inbox row or a notification leaves focus alone.
      const from = document.activeElement;
      if (from instanceof HTMLElement && stripSlotRef.current?.contains(from) && from.matches('[data-strip-action="decide"]:focus-visible')) card.focus({ preventScroll: true });
      restartFlash(highlightMessageId, highlightRing ? 'ask' : 'search');
      onHighlightDone?.();
      return;
    }
    if (!messages.some((m) => m.id === highlightMessageId)) return;
    const thread = groupDiscussionThreads(messages, { foldOpen: askOnly }).find(
      (item) => item.kind === 'thread' && item.turns.some((t) => t.id === highlightMessageId),
    );
    if (thread && thread.kind === 'thread' && !openThoughts[`thread:${thread.id}`]) {
      setOpenThoughts((prev) => ({ ...prev, [`thread:${thread.id}`]: true }));
      return;
    }
    const el = scrollRef.current?.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(highlightMessageId)}"]`);
    if (!el) return;
    const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
    el.scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' });
    restartFlash(highlightMessageId, highlightRing ? 'ask' : 'search');
    onHighlightDone?.();
  }, [highlightMessageId, highlightRing, messages, openThoughts, onHighlightDone, pendingApprovals]);
  useEffect(() => {
    if (!flashId) return;
    const t = setTimeout(() => setFlashId(null), flashKind === 'quote' ? 1600 : 2400);
    return () => clearTimeout(t);
  }, [flashId, flashKind]);

  // Reply: the bot message the next send answers. Cleared on send and when the chat changes.
  const [replyTo, setReplyTo] = useState<ChatMessage | null>(null);
  useEffect(() => {
    setReplyTo(null);
  }, [contextKey]);
  const focusComposer = () => {
    const ta = textareaRef.current;
    if (!ta) return;
    ta.focus();
    ta.setSelectionRange(ta.value.length, ta.value.length);
  };
  // Continue in a new chat: the message whose request runs, and the one plain line when it failed.
  const [continuing, setContinuing] = useState<string | null>(null);
  const [continueError, setContinueError] = useState<{ id: string; text: string } | null>(null);
  useEffect(() => {
    setContinuing(null);
    setContinueError(null);
  }, [contextKey]);
  useEffect(() => {
    if (!focusComposerKey) return;
    // After the new chat's first paint, so its composer is the one that takes focus
    // Focus on a frame, not after render (kept): an effect after the commit; the composer is already rendered and the frame is cancelled on cleanup
    const raf = requestAnimationFrame(() => focusComposer());
    return () => cancelAnimationFrame(raf);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [focusComposerKey]);
  const continueFrom = async (msg: ChatMessage) => {
    if (!onContinueFrom || continuing) return;
    setContinuing(msg.id);
    setContinueError(null);
    try {
      const err = await onContinueFrom(msg);
      if (err) setContinueError({ id: msg.id, text: err });
    } finally {
      setContinuing((cur) => (cur === msg.id ? null : cur));
    }
  };
  const newestId = messages.length ? messages[messages.length - 1].id : null;
  const continueMenu = (msg: ChatMessage, about: string, align: 'start' | 'end', reveal?: 'hover') =>
    onContinueFrom &&
    canContinueFrom({
      chatKind: home?.kind,
      threadKind,
      message: msg,
      newest: msg.id === newestId,
      streaming: isStreaming,
      botSession: false,
    }) ? (
      <MessageMore
        messageId={msg.id}
        about={about}
        align={align}
        reveal={reveal}
        busy={continuing === msg.id}
        busyLabel="Starting a new chat…"
        items={[{ label: CONTINUE_LABEL, run: () => void continueFrom(msg) }]}
      />
    ) : null;
  const startReply = (msg: ChatMessage) => {
    setReplyTo(msg);
    setChangeFor(null);
    focusComposer();
  };
  // reply-chrome part 2: Change… starts a reply whose placeholder asks what to change; any other reply drops it.
  const [changeFor, setChangeFor] = useState<string | null>(null);
  useEffect(() => {
    if (!replyTo) setChangeFor(null);
  }, [replyTo]);
  const [approving, setApproving] = useState<string | null>(null);
  /** The chip's name: the bot by id or name, else this chat's title. */
  const replyBotName = (msg: ChatMessage) => {
    return botDisplayName(msg.sender_id, knownBots);
  };
  const cancelReply = () => {
    setReplyTo(null);
    setChangeFor(null);
    focusComposer();
  };
  /**
   * Jumps to a quote's original: opens its folded discussion if needed, centres it, moves focus there
   * and rings it. False when it isn't loaded in this chat.
   */
  const [quoteJump, setQuoteJump] = useState<{ id: string; n: number } | null>(null);
  const showOriginal = (id: string): boolean => {
    if (!messages.some((m) => m.id === id)) return false;
    stickRef.current = false;
    setQuoteJump((p) => ({ id, n: (p?.n ?? 0) + 1 }));
    return true;
  };
  useEffect(() => {
    if (!quoteJump) return;
    const thread = groupDiscussionThreads(messages, { foldOpen: askOnly }).find((item) => item.kind === 'thread' && item.turns.some((t) => t.id === quoteJump.id));
    if (thread && thread.kind === 'thread' && !openThoughts[`thread:${thread.id}`]) {
      setOpenThoughts((prev) => ({ ...prev, [`thread:${thread.id}`]: true }));
      return;
    }
    const el = scrollRef.current?.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(quoteJump.id)}"]`);
    setQuoteJump(null);
    if (!el) return;
    const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
    el.scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' });
    if (el.tabIndex < 0 || el.hasAttribute('tabindex')) el.focus({ preventScroll: true });
    // 30q: same race-free restart as search and approvals, so a second click on a quote always rings again.
    restartFlash(quoteJump.id, 'quote');
  }, [quoteJump, messages, openThoughts]);

  // Thumbs on the bot's newest question are a yes or no; once one has answered it, they're feedback again.
  const [answered, setAnswered] = useState<ReadonlySet<string>>(() => new Set());
  const questionId = questionMessageId(messages, isStreaming);
  // reply-chrome part 1: Inbox done items (finished, to review) by the reply they point at, for the Done marker.
  const inboxData = useInbox().data;
  const doneItems = useMemo(() => doneItemsOf([...(inboxData?.items ?? []), ...(inboxData?.batch_items ?? [])]), [inboxData]);
  // reply-chrome part 2: the newest message, when it's a bot reply asking for an OK and nothing else is open.
  // 22r: a 👍 that answered it counts as answered for good, across the turn-end reload.
  const approveId = useMemo(() => {
    const last = messages[messages.length - 1];
    return approveRowId(last, last ? parseMetaObject(last.meta) : null, { busy: isStreaming || !!awaitingAnswer || pendingApprovals.length > 0, answered });
  }, [messages, isStreaming, awaitingAnswer, pendingApprovals.length, answered]);
  const approve = async (msg: ChatMessage) => {
    if (approving) return;
    setApproving(msg.id);
    playSfx('click');
    stickRef.current = true;
    // 18e: remember the row so focus can come back to the composer instead of the page top.
    const row = (document.activeElement as HTMLElement | null)?.closest?.('[data-approve-row]') ?? null;
    try {
      const sent = await onSendMessage(APPROVE_TEXT, [], { replyTo: msg });
      // A failed send keeps the row (it is still the newest message) and offers the words in the composer.
      if (sent === false) setInputVal((now) => now || APPROVE_TEXT);
    } finally {
      setApproving(null);
      // After React commits (the row may unmount, the button re-enables), check where focus ended up.
      setTimeout(() => {
        const active = document.activeElement;
        const focusLost = !active || active === document.body || !active.isConnected;
        const inRow = !!row && row.isConnected && !!active && row.contains(active);
        if (refocusAfterApprove({ phone, focusLost, inRow })) focusComposer();
      }, 0);
    }
  };
  const react = async (msg: ChatMessage, reaction: Reaction | null): Promise<boolean> => {
    const result = await onReact?.(msg, reaction);
    if (result?.answered) setAnswered((prev) => new Set(prev).add(msg.id));
    return result ? result.ok : true;
  };

  // 26d: the line under a reply opens its Details at the step that failed or didn't run (a nonce per message).
  const [detailsAsk, setDetailsAsk] = useState<Record<string, number>>({});
  const askDetails = (id: string) => setDetailsAsk((m) => ({ ...m, [id]: (m[id] ?? 0) + 1 }));
  const toggleThought = (id: string) => {
    setOpenThoughts((prev) => ({ ...prev, [id]: !prev[id] }));
  };

  const handleCopy = async (text: string, id: string) => {
    const ok = await copyText(text);
    setCopiedId({ id, ok });
    if (ok) playSfx('click');
    setTimeout(() => setCopiedId(null), 2000);
  };

  const patchUpload = (key: string, patch: Partial<PendingUpload>) =>
    setUploads((list) => list.map((u) => (u.key === key ? { ...u, ...patch } : u)));

  const startUpload = (key: string, file: File) => {
    const abort = new AbortController();
    uploadFiles.current.set(key, { file, abort });
    uploadWithRetry(file, (progress) => patchUpload(key, { progress, retrying: false }), abort.signal, {
      onRetrying: () => patchUpload(key, { retrying: true, progress: 0 }),
    }).then(
      (attachment) => patchUpload(key, { state: 'done', progress: 1, attachment, error: undefined, retrying: false }),
      (err: Error) => {
        if (err.name === 'AbortError') return;
        const retryable = !(err instanceof UploadError) || uploadRetryable(err.status, err.code);
        patchUpload(key, { state: 'error', error: err.message, retryable, retrying: false });
      },
    );
  };

  /** Files from the picker, a drop or a paste: checked here, then uploaded right away. */
  const addFiles = (files: File[], extraNotes: string[] = []): string[] => {
    if (!files.length) {
      if (extraNotes.length) setUploadNote(extraNotes.join(' '));
      return [];
    }
    const room = uploadSlotsLeft(uploads);
    const notes: string[] = [...extraNotes];
    if (files.length > room) notes.push(`Up to ${MAX_ATTACHMENTS} files per message; ${files.length - room === 1 ? 'one was' : `${files.length - room} were`} left out.`);
    const added: PendingUpload[] = [];
    for (const file of files.slice(0, room)) {
      const problem = preflightFile(file);
      if (problem) {
        notes.push(problem);
        continue;
      }
      const key = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
      added.push({ key, name: file.name || 'pasted file', size: file.size, mime: file.type || undefined, progress: 0, state: 'uploading' });
      startUpload(key, file);
    }
    setUploadNote(notes.length ? notes.join(' ') : null);
    if (added.length) setUploads((list) => [...list, ...added]);
    return added.map((u) => u.key);
  };

  const removeUpload = (key: string) => {
    uploadFiles.current.get(key)?.abort.abort();
    uploadFiles.current.delete(key);
    setUploads((list) => list.filter((u) => u.key !== key));
  };

  // G3 Point at it: a pick from the browser pane is a composer upload with a `point`
  // 30o: counts the sent messages that carried a pick; the pane turns Point off when it goes up.
  const [sentPicks, setSentPicks] = useState(0);
  const pointSink: PointSink = {
    sentPicks,
    picks: pointPicks(uploads),
    filesLeft: uploadSlotsLeft(uploads),
    start: (label, n, { fromMouse }) => {
      const key = `point-${Date.now()}-${Math.random().toString(36).slice(2)}`;
      setUploads((list) => [...list, { key, name: `pointed-${n}.png`, size: 0, mime: 'image/png', progress: 0, state: 'uploading', point: { label } }]);
      // A mouse pick hands over to the composer only when nothing was typed yet
      if (fromMouse && !inputVal.trim()) textareaRef.current?.focus({ preventScroll: true });
      return key;
    },
    done: (key, pick) =>
      setUploads((list) =>
        list.map((u) =>
          u.key === key
            ? {
                ...u,
                state: 'done',
                progress: 1,
                mime: pick.picture ? 'image/png' : 'text/plain',
                point: { label: u.point?.label ?? pick.label, pick },
                attachment: { id: pick.attachment_id, name: u.name, mime: pick.picture ? 'image/png' : 'text/plain', size: 0 } as Attachment,
              }
            : u,
        ),
      ),
    fail: (key) => setUploads((list) => list.filter((u) => u.key !== key)),
  };

  const retryUpload = (key: string) => {
    const f = uploadFiles.current.get(key)?.file;
    if (!f) return;
    patchUpload(key, { state: 'uploading', progress: 0, error: undefined });
    startUpload(key, f);
  };

  // `/idea …` goes in the idea jar, not to a bot (spec §2.3): the field dresses violet and blocks a send it can't take.
  const ideaMode = isIdeaCommand(inputVal);
  const ideaBlocked = ideaMode ? ideaBlockedLine(inputVal, IDEA_MAX, uploads.length > 0) : null;
  // A failed drop's reason, shown while the field still holds the words it gave back.
  const [ideaError, setIdeaError] = useState<{ text: string; line: string } | null>(null);
  const [ideaTried, setIdeaTried] = useState(false);
  useEffect(() => {
    if (!ideaMode) setIdeaTried(false);
  }, [ideaMode]);
  // The one-item "/" popover: shows while the field holds a start of "/idea" and nothing else.
  const slashOpen = !ideaMode && inputVal.length > 0 && inputVal.length < 5 && '/idea'.startsWith(inputVal.toLowerCase()) && !uploads.length;
  const completeIdea = () => {
    setInputVal('/idea ');
    // Focus on a frame, not after render (kept): only Tab, Enter or a click calls this, and React renders that update before the next frame
    requestAnimationFrame(() => {
      const el = textareaRef.current;
      if (el) {
        el.focus();
        el.setSelectionRange(6, 6);
      }
    });
  };

  // Send waits for dictation to finish, like it waits for uploads.
  const canSend = !dict.busy && (ideaMode ? !ideaBlocked : composerReady(inputVal, uploads));
  // The line under the field: too long or a file shows at once; an empty idea only once Enter was tried.
  const ideaLine = (ideaError && ideaError.text === inputVal ? ideaError.line : null) ?? (ideaBlocked && (ideaTried || ideaLength(inputVal) > 0 || uploads.length > 0) ? ideaBlocked : null);
  const stillUploading = uploads.some((u) => u.state === 'uploading');

  const handleSubmit = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (dict.busy) return;
    dict.noteSent();
    // A reply in progress doesn't block the next message (it waits its turn); a team discussion does.
    if (ideaMode) {
      // Ideas never wait on a reply or a discussion: the jar is not a bot.
      if (ideaBlocked) {
        setIdeaTried(true);
        return;
      }
      const draft = inputVal;
      playSfx('click');
      const sent = onSendMessage(draft.trim(), [], undefined);
      setInputVal('');
      if (textareaRef.current) textareaRef.current.style.height = 'auto';
      if (sent && typeof (sent as Promise<unknown>).then === 'function')
        void (sent as Promise<boolean | string | void>).then((r) => {
          if (typeof r === 'string') {
            // A failed drop gives the words back, with the reason under the field.
            setInputVal((now) => (now ? now : draft));
            setIdeaError({ text: draft, line: r });
          }
        });
      return;
    }
    // While the only open thing is a question, a typed message answers it (the server closes the question).
    if (!canSend || (isStreaming && discussionState?.inProgress && !askOnly)) return;
    playSfx('click');
    stickRef.current = true;
    const replying = replyTo;
    const refs = readyAttachments(uploads);
    const sent = onSendMessage(inputVal.trim(), refs, replying ? { replyTo: replying } : undefined);
    if (refs.some((r) => r.point)) setSentPicks((n) => n + 1);
    setReplyTo(null);
    // A send that fails keeps the reply, unless the person has moved on to another one.
    if (replying && sent && typeof (sent as Promise<unknown>).then === 'function')
      void (sent as Promise<boolean | void>).then((ok) => {
        if (ok === false) setReplyTo((now) => now ?? replying);
      });
    // The bots this goes to blink once, so you see who received it.
    recipientsOf(inputVal, activeKwants, home?.kind === 'bot' ? home.bot?.id : undefined).forEach(moodNoticed);
    setInputVal('');
    setUploads([]);
    setUploadNote(null);
    uploadFiles.current.clear();
    setMentionQuery(null);
    setMentionStartIndex(-1);
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    // Backspace in an empty composer takes back the last part of the page that was picked
    if (e.key === 'Backspace' && !inputVal && !e.repeat) {
      const lastPick = [...uploads].reverse().find((u) => u.point);
      if (lastPick) {
        e.preventDefault();
        removeUpload(lastPick.key);
        return;
      }
    }
    if (slashOpen && (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey))) {
      e.preventDefault();
      completeIdea();
      return;
    }
    if (isMentionOpen) {
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        setSelectedIndex((prev) => (prev + 1) % matchingItems.length);
        return;
      }
      if (e.key === 'ArrowUp') {
        e.preventDefault();
        setSelectedIndex((prev) => (prev - 1 + matchingItems.length) % matchingItems.length);
        return;
      }
      if (e.key === 'Enter' || e.key === 'Tab') {
        e.preventDefault();
        if (matchingItems[safeSelectedIndex]) {
          handleSelectMention(matchingItems[safeSelectedIndex]);
        }
        return;
      }
      if (e.key === 'Escape') {
        e.preventDefault();
        setMentionQuery(null);
        return;
      }
    }

    if (e.key === 'Escape' && replyTo) {
      e.preventDefault();
      setReplyTo(null);
      return;
    }

    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
  };

  // "Ask about this" on a Smart Results row, card or finding: fill in the composer, never send.
  useEffect(() => {
    const prefill = (e: Event) => {
      const text = (e as CustomEvent<{ text?: unknown }>).detail?.text;
      if (typeof text !== 'string' || !text) return;
      setInputVal((prev) => withPrefill(prev, text));
      // After the render that shows the new text: the caret and height need it (the event can come from any caller)
      afterRender(() => {
        const el = textareaRef.current;
        if (!el) return;
        el.focus();
        el.setSelectionRange(el.value.length, el.value.length);
        el.style.height = 'auto';
        el.style.height = `${Math.min(el.scrollHeight, 160)}px`;
      });
    };
    window.addEventListener(COMPOSE_PREFILL_EVENT, prefill);
    return () => window.removeEventListener(COMPOSE_PREFILL_EVENT, prefill);
  }, []);

  const handlePromptSuggestion = (prompt: string) => {
    setInputVal(prompt);
    playSfx('click');
    if (textareaRef.current) {
      textareaRef.current.focus();
    }
  };

  const retries = retryTargets(messages);
  const retrySend = async (target: { text: string; attachments: AttachmentRef[] }) => {
    stickRef.current = true;
    if ((await onSendMessage(target.text, target.attachments)) === false) throw new Error('not sent');
  };

  const switchNoteFor = useMemo(
    () => assignSwitchNotes(switchNotes ?? [], messages, (m) => botDisplayName(m.sender_id, knownBots)),
    [switchNotes, messages, knownBots],
  );
  // P4: each turn's shared files move under their bot's reply, and repeats of one file fold into the newest.
  // While a bot's live row is on screen, its shares this turn sit under that row from the start (Mira, P4).
  const liveRowShown = isStreaming && !deciding && routingState?.phase !== 'deciding' && !discussionState?.inProgress;
  const liveBot = liveRowShown && streamingSpeakerName ? streamingSpeakerName : null;
  const arranged = useMemo(() => arrangeSharedFiles(messages, knownBots, liveBot), [messages, knownBots, liveBot]);
  const liveShareIds = useMemo(() => new Set(arranged.live.map((m) => m.id)), [arranged.live]);
  // 14c: an answer given on a question card shows once, on the card; its saved "You" message is not
  // drawn while that card is loaded (nothing folds when this chat doesn't draw question cards).
  const askCards = !!renderQuestion;
  const listed = useMemo(() => {
    const folded = askCards ? foldedAnswerIds(arranged.messages) : null;
    return folded?.size ? arranged.messages.filter((m) => !folded.has(m.id)) : arranged.messages;
  }, [arranged.messages, askCards]);
  const liveNote = isStreaming ? liveSwitchNote(switchNotes ?? [], switchNoteFor, streamingSpeakerName || title) : null;

  // Replies that arrive while the chat is open slide in; the first load and a stream handing over to its saved copy do not
  const freshTrack = useRef<{ key: string | undefined; seen: Set<string> | null; fresh: Set<string>; streamEnded: number; wasStreaming: boolean }>({
    key: undefined,
    seen: null,
    fresh: new Set(),
    streamEnded: 0,
    wasStreaming: false,
  });
  {
    const t = freshTrack.current;
    if (isStreaming) t.wasStreaming = true;
    else if (t.wasStreaming) {
      t.wasStreaming = false;
      t.streamEnded = Date.now();
    }
    if (t.key !== contextKey || t.seen === null) {
      t.key = contextKey;
      t.seen = new Set(messages.map((m) => m.id));
      t.fresh = new Set();
    } else {
      for (const m of messages) {
        if (t.seen.has(m.id)) continue;
        t.seen.add(m.id);
        if (!isStreaming && Date.now() - t.streamEnded > 2500) t.fresh.add(m.id);
      }
    }
  }

  // Show it once trials (A29): which trials ended in this tab (SSE); history covers a reload
  const [endedTrials, setEndedTrials] = useState<ReadonlySet<string>>(() => new Set());
  useEffect(() => onContinuity('trial_ended', (t) => setEndedTrials((prev) => (prev.has(t.skill_id) ? prev : new Set(prev).add(t.skill_id)))), []);
  const trialCards = useMemo(() => trialCardsAfter(messages, endedTrials), [messages, endedTrials]);

  // `prev`: the message shown just above, so a kwant line under another sits close to it (0.9.5 F5)
  const renderMessage = (msg: ChatMessage, prev?: ChatMessage) => {
    const interruption = parseInterruption(msg);
    if (interruption)
      return (
        <InterruptedNotice
          key={msg.id}
          messageId={msg.id}
          interruption={interruption}
          retry={retries.get(msg.id)}
          onRetry={retrySend}
          flash={flashId === msg.id}
        />
      );
    const isolation = parseIsolationFailed(msg);
    if (isolation)
      return (
        <IsolationNotice
          key={msg.id}
          messageId={msg.id}
          meta={isolation}
          text={msg.text}
          retry={canRun === false ? null : retries.get(msg.id)}
          onRetry={retrySend}
          onOpenComputerSettings={onOpenComputerSettings}
          onOpenAccounts={onOpenAccounts}
          onChangeTeamFolder={onChangeTeamFolder}
          onEditBot={onEditBot}
          flash={flashId === msg.id}
        />
      );
    const requestLimit = parseRequestLimit(msg);
    if (requestLimit)
      return (
        <RequestLimitNotice
          key={msg.id}
          messageId={msg.id}
          meta={requestLimit}
          canContinue={canRun !== false && retries.has(msg.id)}
          onSend={async (text) => {
            stickRef.current = true;
            if ((await onSendMessage(text, [])) === false) throw new Error('not sent');
          }}
          flash={flashId === msg.id}
        />
      );
    const meta = msg.meta && renderDelegation ? parseDelegationMeta(msg.meta) : null;
    if (meta && renderDelegation) return <React.Fragment key={msg.id}>{renderDelegation(msg, meta, flashId === msg.id)}</React.Fragment>;
    const question = msg.meta && renderQuestion ? parseQuestionMeta(msg.meta) : null;
    if (question && renderQuestion) return <React.Fragment key={msg.id}>{renderQuestion(msg, question, flashId === msg.id)}</React.Fragment>;
    const humanStep = msg.meta && renderHumanStep ? parseHumanStepMeta(msg.meta) : null;
    if (humanStep && renderHumanStep) return <React.Fragment key={msg.id}>{renderHumanStep(msg, humanStep, flashId === msg.id)}</React.Fragment>;
    const suggestion = msg.meta && renderMcpSuggestion ? parseSuggestionMeta(msg.meta) : null;
    if (suggestion && renderMcpSuggestion) return <React.Fragment key={msg.id}>{renderMcpSuggestion(msg, suggestion, flashId === msg.id)}</React.Fragment>;
    const connection = msg.meta && renderConnectionSuggestion ? parseConnectionMeta(msg.meta) : null;
    if (connection && renderConnectionSuggestion)
      return <React.Fragment key={msg.id}>{renderConnectionSuggestion(msg, connection, flashId === msg.id)}</React.Fragment>;
    const watch = msg.meta && renderWatchReport ? parseWatchMeta(msg.meta) : null;
    if (watch && renderWatchReport) return <React.Fragment key={msg.id}>{renderWatchReport(msg, watch, flashId === msg.id)}</React.Fragment>;
    const botAction = msg.meta && renderBotAction ? parseBotActionMeta(msg.meta) : null;
    if (botAction && renderBotAction) return <React.Fragment key={msg.id}>{renderBotAction(msg, botAction, flashId === msg.id)}</React.Fragment>;
    const toolFailure = msg.meta ? parseToolFailureMeta(msg.meta) : null;
    if (toolFailure)
      return (
        <ToolFailureLine
          key={msg.id}
          meta={toolFailure}
          messageId={msg.id}
          flash={flashId === msg.id}
          tight={!!prev?.meta && !!(parseToolFailureMeta(prev.meta) || parseToolNoteMeta(prev.meta))}
          onFix={onOpenConnections}
        />
      );
    const toolNote = msg.meta ? parseToolNoteMeta(msg.meta) : null;
    if (toolNote)
      return (
        <ToolNoteLine
          key={msg.id}
          meta={toolNote}
          messageId={msg.id}
          botName={botDisplayName(toolNote.kwant_id ?? msg.sender_id, knownBots)}
          flash={flashId === msg.id}
          onOpen={onOpenToolNote}
        />
      );
    const hire = msg.meta && renderHire ? parseHireMeta(msg.meta) : null;
    if (hire && renderHire) return <React.Fragment key={msg.id}>{renderHire(msg, hire, flashId === msg.id)}</React.Fragment>;
    const routeChoice = msg.meta && renderRouteChoice ? parseRouteChoiceMeta(msg.meta) : null;
    if (routeChoice && renderRouteChoice) {
      const asked = messages.find((m) => m.id === routeChoice.user_message_id);
      return <React.Fragment key={msg.id}>{renderRouteChoice(msg, routeChoice, flashId === msg.id, asked?.text)}</React.Fragment>;
    }
    const setup = msg.meta && onOpenAccounts ? parseSetupMeta(msg.meta) : null;
    if (setup && onOpenAccounts)
      return (
        <div key={msg.id} data-message-id={msg.id} className="w-full max-w-5xl">
          <SetupNeededCard
            meta={setup}
            botName={botDisplayName(msg.sender_id, knownBots)}
            spaceName={spaceName ?? 'this space'}
            canRun={canRun}
            onOpenAccounts={onOpenAccounts}
            ollamaReady={ollamaReady}
            onRecheck={onRecheckEngines}
            rechecking={recheckingEngines}
            flash={flashId === msg.id}
          />
        </div>
      );
    const budgetNote = parseBudgetNotice(msg.meta);
    if (budgetNote && (budgetNote.kind === 'bot_budget_stopped' || budgetNote.kind === 'bot_budget_warn'))
      return (
        <BudgetNotice
          key={msg.id}
          messageId={msg.id}
          text={msg.text}
          meta={budgetNote}
          onRaise={onRaiseBudget}
          canAct={!(budgetBotId === budgetNote.kwant_id && chatBudget?.state === 'paused')}
          flash={flashId === msg.id}
        />
      );
    const spend = parseSpendStopped(msg.meta);
    if (spend)
      return (
        <SpendStoppedNotice
          key={msg.id}
          messageId={msg.id}
          text={msg.text}
          meta={spend}
          onOpenSettings={onOpenUsage}
          flash={flashId === msg.id}
        />
      );
    const paused = parseBudgetPaused(msg.meta);
    if (paused)
      return (
        <BudgetPausedNotice
          key={msg.id}
          messageId={msg.id}
          text={msg.text}
          meta={paused}
          onContinue={canRun === false ? undefined : chainBudgetApi.continue}
          flash={flashId === msg.id}
        />
      );
    const capped = parseHandoffCapped(msg.meta);
    if (capped)
      return (
        <HandoffCappedNotice
          key={msg.id}
          messageId={msg.id}
          meta={capped}
          onContinue={canRun === false ? undefined : chainBudgetApi.continue}
          flash={flashId === msg.id}
        />
      );
    const expired = parseExpiredApproval(msg);
    if (expired)
      return (
        <ExpiredApprovalNotice
          key={msg.id}
          messageId={msg.id}
          text={msg.text}
          expired={expired}
          onRetry={canRun === false ? undefined : awayApi.retryApproval}
          flash={flashId === msg.id}
        />
      );
    if (isSystemNotice(msg) && !parseAttachments(msg.meta).length)
      return <SystemNotice key={msg.id} messageId={msg.id} text={msg.text} flash={flashId === msg.id} />;
    // UX audit #5: a routine's run is not the person speaking; it gets its own row, not a "You" bubble
    const routine = routineOf(msg);
    if (routine !== null)
      return (
        <RoutineRow
          key={msg.id}
          messageId={msg.id}
          name={routine}
          text={msg.text}
          body={renderFormattedText(msg.text)}
          at={msg.created_at}
          flash={flashId === msg.id}
        />
      );
    const isUser = msg.sender_role === 'user';
    const files = msg.meta ? parseAttachments(msg.meta) : [];
    // A bot's share_file note: the file tiles say it all.
    const filesOnly = files.length > 0 && isSharedFileMessage(msg.meta);
    const isThoughtOpen = !!openThoughts[msg.id];
    const savedActivity = !isUser && msg.meta ? parseActivityMeta(msg.meta) : null;
    const outcome = replyOutcome(savedActivity?.steps);
    const ranOn = isUser ? null : ranOnLabel(msg.meta);
    const account = isUser ? null : ranOnAccount(msg.meta);
    const tokens = isUser ? null : replyTokens(msg.tokens_used, msg.meta);
    const cost = isUser ? null : replyCostWords(msg.meta);
    const asksOk = msg.id === approveId;
    // A reply that asks (the Approve row, or the thumbs as yes/no) is never marked done.
    const done = isUser ? null : doneOf(msg, doneItems, { asks: asksOk || (msg.id === questionId && !answered.has(msg.id)) });
    // Any auto-routed channel, not only #general: the server attaches `routing` wherever it picked the bot.
    const routed = isUser ? null : parseRoutingMeta(msg.meta);
    // Older channel replies still hold a raw [DECISIONS] block: hidden here, its lines shown as chips
    const shownDecisions = isUser ? null : messageDecisions(msg.text, msg.meta);
    const decisions = shownDecisions?.decisions ?? [];
    const text = shownDecisions ? shownDecisions.text : msg.text;
    // S-F7: a trial turn that came back empty says so, in muted text, instead of a blank bubble.
    const emptyTrial =
      !isUser && msg.sender_role === 'kwant' && !(text ?? '').trim() && !files.length && msg.results == null && trialOf(msg)
        ? emptyTrialReplyLine(parsePick(activeKwants.find((k) => k.id === msg.sender_id || k.name === msg.sender_id)?.preferred_model).family)
        : null;
    const workAhead = isUser ? null : parseWorkAhead(msg.meta);
    // 23c: a customer's or a bot's "user" message says who wrote it; the person (Telegram too) and a coding agent as before
    const otherSender = isUser ? otherSenderLabel(msg.meta, knownBots, msg.sender_id) : null;
    const displayName = isUser ? otherSender ?? agentSenderLabel(msg.meta) ?? 'You' : botDisplayName(msg.sender_id, knownBots);
    // 25b: only what you wrote sits on your side (you, you from Telegram, your coding agent). A customer or a bot's
    // chat-API message sits on the left in a neutral bubble. Side and look only; content still follows isUser.
    const onYourSide = isUser && !otherSender;
    // P4: a share that now sits under its bot's reply reads as part of it, without a second header.
    const underReply = !isUser && filesOnly && (arranged.attached.has(msg.id) || liveShareIds.has(msg.id));
    const olderCopies = filesOnly ? arranged.earlier.get(msg.id) : undefined;
    const replyQuote = isUser ? replyRefOf(msg.reply_to) : null;
    // Whose mood the reply header shows (Pixel's AvatarMood, drawn by ModernAvatar given a kwantId):
    // Laya's pick, else this bot chat's bot, else the team member with that name. Unknown: no mood.
    const replyKwantId = isUser
      ? undefined
      : routed?.kwant_id ?? (home?.kind === 'bot' ? home.bot?.id : undefined) ?? botOf(msg.sender_id, knownBots)?.id;

    return (
      <div
        key={msg.id}
        data-message-id={msg.id}
        data-flash-kind={flashId === msg.id ? flashKind : undefined}
        tabIndex={-1}
        data-shared-under={underReply ? '' : undefined}
        // The log's space-y gap would win over a margin class; inline style pulls the tiles up to the reply's actions
        style={underReply ? { marginTop: '0.5rem' } : undefined}
        className={`group/msg flex items-start gap-3.5 w-full max-w-5xl rounded-xl focus:outline-none ${onYourSide ? 'ml-auto flex-row-reverse justify-start' : ''} ${
          flashId === msg.id ? (flashKind === 'quote' ? 'kw-flash-quote' : 'kw-flash') : ''
        } ${freshTrack.current.fresh.has(msg.id) ? 'kws-in' : ''}`}
      >
        {/* Phones show the avatar inside the name line instead, so the bubble gets the full width */}
        {underReply ? (
          // Keeps the tiles lined up with the reply bubble above, where the avatar would be
          <span className="hidden sm:block w-9 shrink-0" aria-hidden="true" />
        ) : (
        <span className="hidden sm:contents">
          {/* Laya hand-off: a reply she just routed brings the chosen bot's avatar up into the header */}
          <span className={routed && freshTrack.current.fresh.has(msg.id) ? 'kws-handoff inline-flex' : 'contents'}>
            {otherSender ? (
              <SenderLetter name={otherSender} />
            ) : (
              <ModernAvatar
                role={isUser ? 'user' : title}
                name={displayName}
                size={REPLY_AVATAR}
                kwantId={replyKwantId}
                modelBadge={false}
              />
            )}
          </span>
        </span>
        )}

        <div className={`flex flex-col min-w-0 ${onYourSide ? 'max-w-[85%] sm:max-w-2xl items-end' : isUser ? 'max-w-[85%] sm:max-w-2xl items-start' : 'flex-1 max-w-4xl items-start'}`}>
          {underReply ? (
            <span className="sr-only">Shared by {displayName}</span>
          ) : isUser ? (
            <div className="flex items-center gap-2 mb-1.5 text-[11px] text-zinc-400 font-medium max-w-full min-w-0 whitespace-nowrap" data-sender={otherSender ? 'other' : undefined}>
              <span className={otherSender ? 'text-zinc-200 min-w-0 truncate' : 'text-zinc-200 shrink-0'}>{displayName}</span>
              {fromTelegram(parseMetaObject(msg.meta)) && <ViaTelegram />}
            </div>
          ) : (
            // One line, "Name · 3:42 PM"; the model, account, tokens, steps and reasoning wait behind Details
            <ReplyMeta
              name={displayName}
              at={msg.created_at}
              sentToTelegram={sentToTelegram(parseMetaObject(msg.meta))}
              avatar={<span className={routed && freshTrack.current.fresh.has(msg.id) ? 'kws-handoff inline-flex' : 'inline-flex'}><ModernAvatar role={title} name={displayName} size={REPLY_AVATAR_PHONE} kwantId={replyKwantId} modelBadge={false} /></span>}
              ranOn={ranOn}
              account={account}
              effort={effortWords(msg.reasoning_content)}
              tokens={tokens}
              cost={cost}
              done={done}
              outcome={outcome}
              openRequest={detailsAsk[msg.id]}
              note={savedFailoverNotice(msg.meta) ?? switchNoteFor.get(msg.id)}
              handoff={savedFailoverHandoff(msg.meta)}
              route={
                routed
                  ? {
                      text: routeWhyText({
                        kwantName: routed.kwant_name,
                        basis: routed.basis,
                        reason: routed.reason,
                        fallback: routed.fallback,
                        matchedTerms: routed.matched_terms,
                        handedBackBy: routed.handed_back_by ? activeKwants.find((k) => k.id === routed.handed_back_by)?.name : undefined,
                      }),
                      fallback: !!routed.fallback,
                      reroute:
                        onSendToOtherBot && questionOf.get(msg.id)
                          ? {
                              key: msg.id,
                              targets: rerouteTargets.filter((k) => k.id !== routed.kwant_id && k.name !== displayName),
                              onPick: (kwantId) => onSendToOtherBot(questionOf.get(msg.id)!, kwantId),
                            }
                          : undefined,
                    }
                  : undefined
              }
            >
              {/* What the reply did: "12 steps · 41s", opening to the steps (tool calls go inside) */}
              {savedActivity && (
                <SavedActivityList activity={savedActivity} idBase={`act-${msg.id}`} openRequest={detailsAsk[msg.id]} focusStep={outcome?.stepId ?? null}>
                  {msg.tool_calls && (
                    <div className="border-t border-zinc-800/60 p-2">
                      <ToolCallsList raw={msg.tool_calls} />
                    </div>
                  )}
                </SavedActivityList>
              )}

              {/* Collapsible Reasoning Disclosure (the steps above already hold the thinking when they have it) */}
              {/* 30e: a CLI reply's only "reasoning" is its run line, which Ran on already says; its effort moves there */}
              {msg.reasoning_content && !isCliRunLine(msg.reasoning_content) && !hasThinkingText(savedActivity) && (
                <div className="mb-2 max-w-full">
                  <button
                    type="button"
                    onClick={() => toggleThought(msg.id)}
                    className="max-w-full min-w-0 flex items-center gap-2 px-3 py-1.5 rounded-xl text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-900/80 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700/80 transition-all cursor-pointer shadow-sm group"
                  >
                    <Sparkles size={13} className="text-sky-400 group-hover:rotate-12 transition-transform flex-shrink-0" />
                    <span className="truncate min-w-0 sm:max-w-md">
                      {msg.reasoning_content.split('\n')[0].replace(/^🔮\s*/, '')}
                    </span>
                    {isThoughtOpen ? <ChevronDown size={13} className="text-zinc-500 flex-shrink-0" /> : <ChevronRight size={13} className="text-zinc-500 flex-shrink-0" />}
                  </button>

                  {isThoughtOpen && (
                    <div className="mt-1.5 p-3.5 rounded-xl bg-zinc-950/90 border border-zinc-800 text-xs text-zinc-300 whitespace-pre-wrap leading-relaxed shadow-inner max-h-80 overflow-y-auto">
                      {msg.reasoning_content}
                    </div>
                  )}
                </div>
              )}
            </ReplyMeta>
          )}

          {/* Message Body Bubble */}
          {!filesOnly && (text.trim() || !files.length) && (
          <div className={isUser ? 'relative w-full max-w-2xl' : 'contents'}>
          {isUser && (() => {
            // A "user" message: the overflow sits in the empty gutter beside the bubble, bottom-aligned, no row.
            // Yours: left of your bubble. A customer's or a bot's (25b, on the left): right of theirs.
            const more = continueMenu(msg, messageAbout(otherSender), onYourSide ? 'end' : 'start', 'hover');
            return more ? (
              <div className={onYourSide ? 'absolute right-full bottom-0 mr-1' : 'absolute left-full bottom-0 ml-1'} data-message-more-gutter="">
                {more}
              </div>
            ) : null;
          })()}
          <div
            className={`${REPLY_BUBBLE} ${
              onYourSide
                ? 'bg-zinc-800 text-zinc-100 rounded-tr-sm border border-zinc-700/60 max-w-2xl'
                : isUser
                  ? `${OTHER_BUBBLE} max-w-2xl`
                  : workAhead
                    ? 'bg-sky-950/15 text-zinc-200 rounded-tl-sm border border-dashed border-sky-400/25'
                    : REPLY_BUBBLE_BOT
            }`}
            data-other-bubble={isUser && !onYourSide ? '' : undefined}
            data-work-ahead={workAhead ? '' : undefined}
          >
            {isUser ? (
              <>
                {replyQuote && (
                  <ReplyQuote reply={replyQuote} botName={botNameOf(replyQuote.sender_id, activeKwants)} onOpen={() => showOriginal(replyQuote.id)} />
                )}
                <div className="whitespace-pre-wrap break-words">{renderFormattedText(msg.text)}</div>
              </>
            ) : workAhead ? (
              <WorkAheadBody messageId={msg.id} text={text} />
            ) : emptyTrial ? (
              <p className="flex items-start gap-2 text-sm leading-5 text-zinc-400" data-empty-trial-reply="">
                <CircleSlash size={14} aria-hidden="true" className="mt-[3px] shrink-0" />
                <span>{emptyTrial}</span>
              </p>
            ) : (
              <MarkdownRenderer content={text} results={msg.results} messageId={msg.id} />
            )}
          </div>
          </div>
          )}
          {!isUser && !underReply && <ReplyCheckLine outcome={outcome} onDetails={() => askDetails(msg.id)} />}
          {files.length > 0 && <FileTiles files={files} align={onYourSide ? 'end' : 'start'} sharedBy={filesOnly && !isUser ? displayName : undefined} at={msg.created_at ?? null} />}
          {isUser && heldNotes?.[msg.id]}
          {filesOnly && !isUser && files.length > 0 && shareInfo(msg.meta).auto && (
            // P4: kwnt posted the turn's last screenshot because the reply claimed a picture and none was shared.
            // 26h: a file an MCP tool made names the app (its preset label, else the server name as typed).
            <p data-shared-auto="" className="mt-1 text-[11px] text-zinc-500">
              {madeWithCaption(shareInfo(msg.meta).madeWith)}
            </p>
          )}
          {olderCopies && olderCopies.length > 0 && (
            <EarlierCopies
              idBase={`earlier-${msg.id}`}
              sharedBy={displayName}
              copies={olderCopies.map((m) => ({ id: m.id, at: m.created_at ?? null, files: parseAttachments(m.meta) }))}
            />
          )}
          {/* A shared-file card has no bubble, so the files block (the table or text preview) is mounted here, after the tiles. */}
          {filesOnly && !isUser && msg.results != null && (
            // The column is `items-start`, so without a width cap a long cell stretches the preview past the message.
            <div className="w-full min-w-0 max-w-full">
              <FilesPreviewOnly.Provider value={true}>
                <MarkdownRenderer content="" results={msg.results} messageId={msg.id} />
              </FilesPreviewOnly.Provider>
            </div>
          )}

          {decisions.length > 0 && (
            <DecisionChips
              messageId={msg.id}
              decisions={decisions}
              consulted={consultedNames(msg.meta)}
              onChange={onChangeDecision && !shownDecisions?.readOnly ? (index, picked) => onChangeDecision(msg, index, picked) : undefined}
            />
          )}

          {!isUser && msg.tool_calls && !savedActivity && <ToolCallsList raw={msg.tool_calls} />}

          {done && <DoneCheckLine done={done} />}

          {asksOk && (
            <ApproveRow
              name={displayName}
              busy={approving === msg.id}
              onApprove={() => void approve(msg)}
              onChange={() => {
                startReply(msg);
                setChangeFor(displayName);
              }}
            />
          )}

          {/* Action row (reply-chrome part 3): Reply, the thumbs, then Copy as a quiet icon; smart-result actions portal in after Copy */}
          {/* 0.9.8: on a phone the browsed chip gets its own 44 px row above the action row (it would wrap) */}
          {/* 19f: only when the reply opened pages; BrowsedChip draws nothing otherwise, and the 44 px row was an empty gap */}
          {!isUser && !filesOnly && phone && savedActivity && pagesOfReply(savedActivity.steps).length > 0 && (
            <div className="mt-1 flex items-center min-h-[44px] max-w-full min-w-0" data-phone-browsed-row="">
              <BrowsedChip botName={displayName} steps={savedActivity.steps} live={false} phone onOpen={() => openBrowserFor(msg.id)} />
            </div>
          )}
          {!isUser && !filesOnly && (
            <>
            {/* 19f: on a phone the ghost icons keep one row (no wrap) and the smart-result actions get their own row below */}
            <div
              className={`mt-2 flex ${phone ? 'flex-nowrap' : 'flex-wrap'} items-center gap-0 sm:gap-1 text-zinc-400 text-xs max-w-full min-w-0`}
              data-reply-actions={phone ? 'phone' : 'desktop'}
            >
              {!phone && savedActivity && (
                <BrowsedChip botName={displayName} steps={savedActivity.steps} live={false} onOpen={() => openBrowserFor(msg.id)} />
              )}
              {msg.sender_role === 'kwant' && !workAhead && !msg.id.startsWith('temp-') && (
                <>
                  <ReplyButton botName={displayName} active={replyTo?.id === msg.id} onReply={() => startReply(msg)} />
                  {onReact && (
                    <ReactionButtons
                      messageId={msg.id}
                      reaction={reactionOf(msg.reaction)}
                      asks={msg.id === questionId && !answered.has(msg.id)}
                      onReact={(r) => react(msg, r)}
                    />
                  )}
                </>
              )}
              <CopyGhost copied={copiedId?.id === msg.id ? (copiedId.ok ? 'ok' : 'failed') : null} tipId={`copy-tip-${msg.id}`} onCopy={() => handleCopy(text, msg.id)} />
              {continueMenu(msg, `${displayName}'s reply`, 'start')}
              {!phone && msg.results != null && <SmartActionsSlot messageId={msg.id} />}
            </div>
            {phone && msg.results != null && (
              <div className="mt-1 flex flex-wrap items-center gap-2 text-zinc-400 text-xs max-w-full min-w-0 empty:hidden" data-smart-row="">
                <SmartActionsSlot messageId={msg.id} />
              </div>
            )}
            </>
          )}
          {continueError?.id === msg.id && <MessageMoreError text={continueError.text} align={onYourSide ? 'end' : 'start'} />}
        </div>
      </div>
    );
  };

  // The empty chat shows a home (a bot's own chat, #general, or a team's chat) instead of a bare pane and a row of chips
  // Nothing in the chat yet and nothing on its way: no message, reply, queued turn, routing or waiting card.
  const chatIsEmpty = messages.length === 0 && !isStreaming && !queued && !deciding && pendingApprovals.length === 0;
  const showHome =
    !!home &&
    (home.kind === 'bot' || home.kind === 'general' || (home.kind === 'team' && !!home.team)) &&
    !welcome && chatIsEmpty;
  // The home and Get started (the welcome) both open at their top (13d, 29u); once anything is in, the chat pins to the bottom.
  homeShowingRef.current = showHome || (!!welcome && chatIsEmpty);
  // first-screen E: nothing can run and Get started (the welcome) isn't on screen. The home shows it in place of its asks.
  const accountCard = accountCardShows({ canRun, getStartedShowing: !!welcome });
  // Who answers what's typed: the chat decides, an @mention overrides
  const target = answerTarget({
    kind: home?.kind ?? 'channel',
    text: inputVal,
    botName: home?.bot?.name ?? title,
    teamName,
    names: activeKwants.map((k) => k.name).concat(activeTeams.map((t) => t.name)),
  });

  // ---------- 0.8.0 drop files into the chat (design.md §2–§6) ----------
  // Who gets the files: the same answer as the "Answers:" hint, so the two never disagree.
  const mentioned = target.kind === 'mention' ? target.label.replace(/^@/, '') : '';
  const mentionedBot = mentioned ? activeKwants.find((k) => k.name.toLowerCase() === mentioned.toLowerCase()) : undefined;
  const asDropBot = (k: { id: string; name: string; avatar_sprite?: string }): DropBot => ({ id: k.id, name: k.name, avatar: k.avatar_sprite });
  const roomBots: DropBot[] = (teamMembers?.length ? teamMembers : activeKwants).map(asDropBot);
  // A team @mention shows that team's bots, like a room (#478 M4); never a made-up face for the team.
  const mentionedTeamName = mentioned.replace(/ team$/i, '');
  const mentionedTeam =
    mentioned && !mentionedBot
      ? activeTeams.find((t) => t.name.toLowerCase() === mentioned.toLowerCase() || t.name.toLowerCase() === mentionedTeamName.toLowerCase())
      : undefined;
  const mentionedTeamBots: DropBot[] = (mentionedTeam?.member_kwants ?? [])
    .map((id) => activeKwants.find((k) => k.id === id))
    .filter((k): k is (typeof activeKwants)[number] => !!k)
    .map(asDropBot);
  const dropTo: { recipient: DropRecipient; single: boolean; bots: DropBot[]; botId?: string } =
    target.kind === 'mention'
      ? mentionedBot
        ? { recipient: { kind: 'bot', name: mentionedBot.name }, single: true, bots: [asDropBot(mentionedBot)], botId: mentionedBot.id }
        : { recipient: { kind: 'team', name: mentionedTeam?.name ?? mentionedTeamName }, single: false, bots: mentionedTeamBots }
      : home?.kind === 'bot'
        ? {
            recipient: { kind: 'bot', name: home.bot?.name ?? title },
            single: true,
            bots: [{ id: home.bot?.id, name: home.bot?.name ?? title, avatar: home.bot?.avatar_sprite }],
            botId: home.bot?.id,
          }
        : home?.kind === 'general'
          ? { recipient: { kind: 'general', name: 'General' }, single: false, bots: roomBots }
          : home?.kind === 'team' || (target.kind === 'team' && teamName)
            ? { recipient: { kind: 'team', name: teamName ?? title }, single: false, bots: roomBots }
            : { recipient: { kind: 'channel', name: title }, single: false, bots: roomBots };
  // A modal open when the drag came in keeps the layer away (the Import dialog has its own drop zone).
  const modalUp = useMemo(() => winDrag.active && typeof document !== 'undefined' && modalOpen(document), [winDrag.active]);
  const dragOn = winDrag.active && !modalUp && !dropOff;
  const dropPreview = previewDrag(winDrag.items, uploads.length);
  const card = dropCard({ preview: dropPreview, recipient: dropTo.recipient, ideaMode });
  const livePhase: DropPhase | null = !dragOn ? null : overChat ? (card.state === 'refused' ? 'refused' : 'over') : 'armed';
  useEffect(() => {
    if (!winDrag.active) {
      overDepth.current = 0;
      overNow.current = false;
      setOverChat(false);
    }
  }, [winDrag.active]);
  // The layer runs its exit after the drag ends: the landing (160 ms) after a drop, else a fade (100 ms;
  // 120 ms with reduced motion, which is how long that fade runs there, #478 L7).
  const lastCard = useRef(card);
  if (livePhase) lastCard.current = card;
  const landed = useRef(false);
  const [exiting, setExiting] = useState<'landing' | 'leaving' | null>(null);
  const wasLive = useRef(false);
  useEffect(() => {
    if (livePhase) {
      // A new drag: a drop that landed after the last one ended must not play this one's exit as a landing.
      if (!wasLive.current) landed.current = false;
      wasLive.current = true;
      setExiting(null);
      return;
    }
    if (!wasLive.current) return;
    wasLive.current = false;
    const how = landed.current ? 'landing' : 'leaving';
    landed.current = false;
    setExiting(how);
    const t = setTimeout(() => setExiting(null), how === 'landing' ? 160 : leaveMs());
    return () => clearTimeout(t);
  }, [livePhase]);
  // Spoken on state changes only, never on every dragover.
  const announceLine = livePhase === 'over' || livePhase === 'refused' ? card.announce : '';
  useEffect(() => {
    if (announceLine) setDropAnnounce(announceLine);
  }, [announceLine]);
  // Card height room: the composer's height + 24 px; a side pane's width stays out of the layer.
  const [layerBox, setLayerBox] = useState({ bottomPad: 120, rightGap: 0 });
  useLayoutEffect(() => {
    if (!dragOn) return;
    const root = rootRef.current?.getBoundingClientRect();
    const col = columnRef.current?.getBoundingClientRect();
    const bottomPad = (composerWrapRef.current?.offsetHeight ?? 96) + 24;
    const rightGap = root && col && col.width ? Math.max(0, Math.round(root.right - col.right)) : 0;
    setLayerBox((b) => (b.bottomPad === bottomPad && b.rightGap === rightGap ? b : { bottomPad, rightGap }));
  }, [dragOn, uploads.length, vmOpen]);
  const inColumn = (t: EventTarget | null) => {
    if (!(t instanceof Node)) return false;
    if (t instanceof Element && t.closest('[data-drop-layer]')) return true;
    return !!(headerRef.current?.contains(t) || columnRef.current?.contains(t));
  };
  const dropHandlers = {
    onDragEnter: (e: React.DragEvent) => {
      if (!dragHasFiles(e.dataTransfer)) return;
      overDepth.current += 1;
      markOver(inColumn(e.target));
    },
    onDragOver: (e: React.DragEvent) => {
      if (!dragHasFiles(e.dataTransfer)) return;
      e.preventDefault();
      const inside = inColumn(e.target);
      markOver(inside);
      e.dataTransfer.dropEffect = inside && dragOn && card.state === 'over' ? 'copy' : 'none';
    },
    onDragLeave: (e: React.DragEvent) => {
      if (!dragHasFiles(e.dataTransfer)) return;
      overDepth.current = Math.max(0, overDepth.current - 1);
      if (overDepth.current === 0) markOver(false);
    },
    onDrop: (e: React.DragEvent) => {
      if (!dragHasFiles(e.dataTransfer)) return;
      e.preventDefault();
      // The window watch ends a drag one task after the drop so this handler gets it (the layer it
      // landed on is still mounted). End it here instead, in this same render, so no "Drop here…"
      // frame shows between the drop and the landing; `landed` is set before React renders.
      try {
        takeDrop(e);
      } finally {
        dragWatch.end();
      }
    },
  };
  // What a drop on this chat does (from onDrop above).
  const takeDrop = (e: React.DragEvent) => {
    overDepth.current = 0;
    // Not flushed: the drop ends the drag anyway, and the exit must see `landed` first.
    overNow.current = false;
    setOverChat(false);
    if (!inColumn(e.target) || modalUp || dropOff) return;
    // What the drop itself holds decides, the same way the card did (an ignored drop does nothing).
    const items = e.dataTransfer.items as unknown as ArrayLike<DataTransferItem>;
    const now = dropCard({ preview: previewDrag(items?.length ? items : winDrag.items, uploads.length), recipient: dropTo.recipient, ideaMode });
    if (now.state === 'refused') return;
    const dropped = splitDrop(items, e.dataTransfer.files);
    const keys = addFiles(dropped.files, dropped.folders.length ? [FOLDER_NOTE] : []);
    landed.current = true;
    textareaRef.current?.focus();
    playSfx('blip');
    if (dropTo.single && dropTo.botId) moodNoticed(dropTo.botId);
    setDropAnnounce(dropAnnouncement(keys.length, dropTo.recipient));
    if (keys.length) {
      setFreshChips((m) => ({ ...m, ...Object.fromEntries(keys.map((k, i) => [k, i])) }));
      setTimeout(() => setFreshChips((m) => Object.fromEntries(Object.entries(m).filter(([k]) => !keys.includes(k)))), 800);
    }
  };
  const layerPhase: DropPhase | null = livePhase ?? exiting;
  const composerLit = livePhase === 'over';
  const toolPhone = 'w-11 h-11 text-[#a39dcc] hover:text-zinc-100 hover:bg-white/[0.06] active:bg-white/[0.06] focus-visible:outline-[#b8adff]';
  // Phone hint row (spec A2): no "@ mention · attach files" on touch, and "Answers:" only where it isn't
  // obvious (channels and team chats, or a direct chat with an @mention typed).
  const showAnswers = !ideaMode && (!phone || home?.kind !== 'bot' || target.kind === 'mention');
  const showHintText = !(phone && touch);
  const measure16 = (t: string) => measureText16(t, textareaRef.current ? getComputedStyle(textareaRef.current).fontFamily : '');
  const placeholder = dict.phase === 'recording' && !inputVal
    ? 'Speak now…'
    : changeFor && replyTo
    ? changePlaceholder(changeFor)
    : askOnly
    ? phone
      ? fitPlaceholder(answerPlaceholder(awaitingBot?.name || streamingSpeakerName || title), 'Your answer…', fieldWidth, measure16)
      : answerPlaceholder(awaitingBot?.name || streamingSpeakerName || title)
    : phone
    ? phonePlaceholder(title, fieldWidth, (t) => measureText16(t, textareaRef.current ? getComputedStyle(textareaRef.current).fontFamily : ''))
    : spaceName && !narrow
      ? `Message ${title} in ${spaceName}`
      : `Message ${title}`;
  const insertAt = () => {
    playSfx('click');
    const el = textareaRef.current;
    const next = inputVal && !/\s$/.test(inputVal) ? `${inputVal} @` : `${inputVal}@`;
    setInputVal(next);
    el?.focus();
    requestAnimationFrame(() => checkMention(next, next.length));
  };

  // 18f: once the reply has words the steps fold (desktop: the saved reply's row; phone: the compact row as is) and
  // move below the bubble, into the landed action row's place, so landing moves nothing above the words.
  const stepsBelow = !!liveActivity && foldLiveSteps({ writing, steps: liveActivity.steps });
  const liveStepsList = liveActivity ? (
    <LiveActivityList
      live={liveActivity}
      idBase={`live-${liveActivity.turnId}`}
      compact={phone}
      folded={stepsBelow}
      lead={
        livePages.length > 0 ? (
          <BrowsedChip botName={liveSpeaker} steps={liveActivity.steps} live phone={phone} onOpen={() => openBrowserFor(null)} />
        ) : undefined
      }
    />
  ) : null;

  // 14c: on a phone the header's icon buttons carry a small caption under the icon (no hover there,
  // so a title alone was never seen); from sm up they keep their inline word.
  const headLabel = (wide: string, short: string = wide) => (
    <>
      <span className="hidden sm:inline">{wide}</span>
      <span className="sm:hidden text-[10px] leading-3 font-medium" data-head-caption>{short}</span>
    </>
  );
  const headPhone = 'max-sm:flex-col max-sm:gap-0.5 max-sm:h-11 max-sm:min-w-11 max-sm:px-1';
  return (
    <div
      ref={rootRef}
      className="relative flex-1 flex flex-col h-full bg-surface-main overflow-hidden"
      data-keyboard-mode={kbd ? 'on' : undefined}
      data-drop-target="chat"
      data-drop-active={livePhase && livePhase !== 'armed' ? 'true' : undefined}
      data-drop-phase={layerPhase ?? undefined}
      {...dropHandlers}
    >
      {/* Channel / bot header: 56 px on a phone, 48 px in keyboard mode (instant, no animation) */}
      <div
        ref={headerRef}
        data-chat-header
        className={`${kbd ? 'h-12' : 'h-14'} shrink-0 border-b border-hairline px-2 sm:px-6 gap-2 flex items-center justify-between bg-surface-main/80 backdrop-blur-md select-none`}
      >
        {onBack && (
          <button
            type="button"
            onClick={onBack}
            aria-label="Back to chats"
            className="shrink-0 w-11 h-11 -ml-1 inline-flex items-center justify-center rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#b8adff]"
          >
            <ChevronLeft size={18} />
          </button>
        )}
        {home?.kind === 'bot' && home.bot && (
          <ModernAvatar role={home.bot.avatar_sprite} name={home.bot.name} size={phone ? (kbd ? 28 : 32) : 34} kwantId={home.bot.id} className="rounded-xl" />
        )}
        <div className="min-w-0 flex-1">
          <h2
            className={`${phone ? (kbd ? 'text-[15px] leading-5' : 'text-base leading-5') : 'text-body'} font-semibold text-zinc-50 flex items-center gap-2 min-w-0`}
          >
            <span className="truncate">{title}</span>
            {titleExtra}
          </h2>
          {kbd ? null : phone && threadLine ? (
            <div className="flex min-w-0 mt-0.5">{threadLine}</div>
          ) : (
            <p className={`${phone ? 'text-[13px] leading-4 mt-0.5' : 'text-meta'} text-zinc-400 truncate max-w-lg`}>{subtitle}</p>
          )}
        </div>

        <div className="flex items-center gap-0.5 sm:gap-3 shrink-0">
          {/* Active Team Workspace Badge */}
          {(workspacePath || repoUrl) && (
            <div
              className="hidden sm:flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-mono text-zinc-300 bg-zinc-900 border border-zinc-700/60 max-w-[200px] truncate"
              title={workspacePath ? `Workspace directory: ${workspacePath}` : `Git Repository: ${repoUrl}`}
            >
              {workspacePath ? (
                <Folder size={12} className="text-amber-400 flex-shrink-0" />
              ) : (
                <GitBranch size={12} className="text-ok flex-shrink-0" />
              )}
              <span className="truncate">
                {workspacePath
                  ? workspacePath.replace(/^\/Users\/[^/]+/, '~')
                  : repoUrl?.replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '')}
              </span>
            </div>
          )}

          {teamMembers && teamMembers.length > 0 && (
            <div className="flex items-center gap-0.5 sm:gap-2 sm:pl-3 sm:border-l border-zinc-800">
              <div className="hidden sm:flex -space-x-2 items-center px-1 py-1 -my-0.5">
                {teamMembers.map((member) => (
                  <div
                    key={member.id}
                    title={`${member.name} (${member.title})`}
                    className="inline-block ring-2 ring-zinc-950 rounded-full"
                  >
                    <ModernAvatar role={member.avatar_sprite} name={member.name} size={24} kwantId={member.id} />
                  </div>
                ))}
              </div>
              {onManageTeam && (
                <button
                  type="button"
                  onClick={onManageTeam}
                  className={`kw-head-btn ${headPhone} flex items-center justify-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-200 bg-white/[0.04] hover:bg-white/[0.09] hover:text-zinc-50 border border-hairline-strong transition-colors cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400`}
                  title="Team members and settings"
                  aria-label="Manage team"
                >
                  <Settings2 size={12} className="text-zinc-400" aria-hidden="true" />
                  {headLabel('Manage team', 'Team')}
                </button>
              )}
            </div>
          )}

          {onEditInstructions && pinned.length === 0 && (
            <button
              type="button"
              onClick={onEditInstructions}
              className={`kw-head-btn ${headPhone} flex items-center justify-center gap-1.5 max-md:min-w-11 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-200 bg-white/[0.04] hover:bg-white/[0.09] hover:text-zinc-50 border border-hairline-strong transition-colors cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400`}
              title="Pin instructions every bot reads in this channel"
              aria-label="Pin instructions"
            >
              <Pin size={12} className="text-amber-300" aria-hidden="true" />
              {headLabel('Pin')}
            </button>
          )}

          {onEditKwant && (
            <button
              type="button"
              onClick={onEditKwant}
              className={`kw-head-btn ${headPhone} flex items-center justify-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-200 bg-white/[0.04] hover:bg-white/[0.09] hover:text-zinc-50 border border-hairline-strong transition-colors cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400`}
              title={`Edit ${title}'s name, avatar, model and persona`}
              aria-label={`Edit ${title}`}
            >
              <Pencil size={12} className="text-zinc-400" aria-hidden="true" />
              {headLabel('Edit')}
            </button>
          )}

          {/* No header Stop while the working strip shows (always, when a reply runs): the composer's stop square is the one Stop. */}
          {/* Sandbox VM & Live Browser Toggle Button */}
          <button
            type="button"
            onClick={() => {
              playSfx('click');
              toggleVm();
            }}
            className={`kw-head-btn ${headPhone} max-sm:rounded-lg flex items-center justify-center gap-1.5 max-md:min-w-11 px-2.5 py-1 rounded-full text-xs font-medium transition-colors border cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 ${
              vmOpen
                ? 'text-sky-200 bg-sky-400/15 border-sky-300/40'
                : 'text-zinc-200 bg-white/[0.04] hover:bg-white/[0.09] border-hairline-strong hover:text-zinc-50'
            }`}
            title="Show or hide the bot's browser"
            aria-label="Bot browser"
            aria-pressed={vmOpen}
          >
            <Monitor size={12} aria-hidden="true" />
            {headLabel('Bot browser', 'Browser')}
          </button>
        </div>
      </div>

      {/* In keyboard mode the thread controls and pinned instructions step aside (display: none) */}
      <div data-thread-bar className={kbd ? 'hidden' : 'contents'}>
        {subHeader}
      </div>
      {!(welcome && messages.length === 0) && notice}

      <div className={kbd ? 'hidden' : 'contents'}>
        <PinnedInstructions items={pinned} onEdit={onEditInstructions} />
      </div>

      {/* Waiting for the person: replaces the discussion banner while the only open thing is a question */}
      {askOnly && (
        <WaitingBanner
          lines={[{ kind: 'answer', bot: awaitingBot?.name || streamingSpeakerName || title }]}
          rail={askRail}
          stopLabel={waitingStopLabel(teamChat)}
          onStop={onCancelDiscussion}
          onShow={() => showWaitingCard('question')}
        />
      )}
      {/* Discussion In-Flight Banner */}
      {discussionState?.inProgress && !askOnly && (
        <div className="px-3 sm:px-6 pt-3 select-none flex-shrink-0">
          <div className="flex items-center justify-between gap-2 px-3 sm:px-4 py-2 bg-sky-950/40 border border-sky-800/40 rounded-xl mb-3 text-xs">
            <div className="flex items-center gap-2 text-sky-200 min-w-0">
              <Users size={14} className="text-sky-400 animate-pulse shrink-0" />
              <span className="min-w-0">
                {discussionState.kind === 'handoff' ? (
                  <>
                    Handoff: <strong>{discussionState.currentSpeaker || 'Teammate'}</strong> is replying
                    {discussionState.askedBy ? <> (asked by {discussionState.askedBy})</> : null}
                    {' '}• {discussionState.currentTurn || 1} of {discussionState.totalTurns || 1}
                  </>
                ) : discussionState.phase === 'summary' ? (
                  <>
                    <strong>{discussionState.currentSpeaker || 'The lead'}</strong> is summarizing the team's answer
                  </>
                ) : (
                  <>
                    Team discussion: <strong>{discussionState.currentSpeaker || 'Team member'}</strong>
                    {discussionState.phase === 'open'
                      ? ' is opening'
                      : discussionState.askedBy
                        ? <> is answering {discussionState.askedBy}</>
                        : ' is responding'}
                    {' '}• turn {discussionState.currentTurn || 1} of {discussionState.totalTurns || 1}
                  </>
                )}
              </span>
            </div>
            {onCancelDiscussion && (
              <button
                type="button"
                onClick={onCancelDiscussion}
                className="shrink-0 flex items-center gap-1 px-2.5 py-1 bg-rose-500/20 hover:bg-rose-500/30 text-rose-300 rounded border border-rose-500/30 transition-colors cursor-pointer"
              >
                <Square size={11} fill="currentColor" />
                <span>Stop<span className="hidden sm:inline"> Discussion</span></span>
              </button>
            )}
          </div>
        </div>
      )}

      {/* Main Split Layout: Messages/Input on Left + Virtual Machine Side Drawer on Right */}
      <div className="flex-1 flex overflow-hidden min-h-0">
        <div ref={columnRef} className="flex-1 flex flex-col h-full overflow-hidden min-w-0">
          {/* Messages Stream */}
          <div
            ref={scrollRef}
            onScroll={onScroll}
            className="relative flex-1 overflow-y-auto px-3 py-4 sm:p-6 space-y-5 sm:space-y-6"
            role="log"
            aria-label={`Messages in ${title}`}
            aria-busy={isStreaming}
          >
        {topCard}
        {continuedFrom && <ContinuedLine text={continuedFrom.text} onOpen={continuedFrom.onOpen} />}
        {welcome && messages.length === 0 && welcome}
        {showHome && home && (
          <div className="flex min-h-full items-center justify-center">
            <BotHome
              home={home}
              spaceName={spaceName}
              team={home.kind === 'team' ? home.team?.members : activeKwants}
              prompts={suggestions}
              answerLine={home.kind === 'team' ? teamAnswerLine(teamName) : undefined}
              canRun={canRun}
              onPick={handlePromptSuggestion}
              accountCard={accountCard}
              onOpenAccounts={onOpenAccounts}
            />
          </div>
        )}
        {groupDiscussionThreads(listed, { foldOpen: askOnly }).map((item, n, items) => {
          if (item.kind === 'message') {
            const trial = trialCards.get(item.message.id);
            const above = items[n - 1];
            const prev = above?.kind === 'message' && !trialCards.has(above.message.id) ? above.message : undefined;
            if (!trial) return renderMessage(item.message, prev);
            return (
              <Fragment key={item.message.id}>
                {renderMessage(item.message, prev)}
                <TrialWaitsCard key={`trial:${trial.skill_id}`} skillId={trial.skill_id} kwantId={item.message.sender_role === 'kwant' ? item.message.sender_id : (item.message.direct_kwant_id ?? item.message.sender_id)} onOpenSkills={onOpenSkills} />
              </Fragment>
            );
          }
          const threadKey = `thread:${item.id}`;
          const isThreadOpen = !!openThoughts[threadKey];
          return (
            <div key={threadKey} className="w-full max-w-5xl">
              <button
                type="button"
                onClick={() => toggleThought(threadKey)}
                className="sm:ml-[48px] max-w-full flex items-center gap-2.5 px-3 py-1.5 rounded-xl text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-900/60 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700/80 transition-all cursor-pointer"
              >
                {isThreadOpen ? <ChevronDown size={13} className="text-zinc-500" /> : <ChevronRight size={13} className="text-zinc-500" />}
                <span className="flex -space-x-1.5">
                  {item.speakers.map((name) => (
                    <ModernAvatar key={name} role={name} name={name} size={18} />
                  ))}
                </span>
                <span className="min-w-0 truncate">
                  Team discussed • {item.turns.length} {item.turns.length === 1 ? 'turn' : 'turns'} • {item.speakers.join(', ')}
                </span>
              </button>
              {isThreadOpen && (
                <div className="mt-4 ml-2 pl-3 sm:ml-[30px] sm:pl-4 border-l border-zinc-800 space-y-6">
                  {item.turns.map((t, i, all) => renderMessage(t, all[i - 1]))}
                </div>
              )}
            </div>
          );
        })}

        {/* Laya routing: which agent will answer */}
        {isStreaming && routingState && !discussionState?.inProgress && (
          <LayaRoutingCard routing={routingState} spaceName={spaceName} />
        )}

        {/* A held reply is being decided: the line stands in for the streamed draft and the consults */}
        {deciding && <DecidingLine botName={deciding.botName} consulted={deciding.consulted} />}

        {/* P6: turns waiting behind the held reply stay visible while the team decides (under the line, aligned with its card).
            !mt-2 beats the list's space-y-5/6, so the line sits 8 px under the card as it does under a reply (#476 L7). */}
        {(deciding || (isStreaming && routingState?.phase === 'deciding')) && !queued && (queuedBeside?.length ?? 0) > 0 && (
          <div className="w-full max-w-5xl pl-12 !mt-2" data-queued-beside-deciding="">
            <div className="max-w-4xl">
              <QueuedBeside items={queuedBeside} />
            </div>
          </div>
        )}

        {/* Live Streaming Assistant Message (or its place in the queue, in the same frame) */}
        {isStreaming && !deciding && routingState?.phase !== 'deciding' && !askOnly && (
          <div className="flex items-start gap-3.5 w-full max-w-5xl" data-live-row="">
            {/* The finished reply's geometry (16a): avatar column from sm up, in the name line on phones */}
            <span className="hidden sm:contents">
              <ModernAvatar role={liveName} name={liveName} size={REPLY_AVATAR} />
            </span>
            <div className="flex flex-col items-start min-w-0 flex-1 max-w-4xl">
              {/* The finished name line's type and height (17c), so it doesn't grow when the reply lands */}
              <div className={replyNameLine(REPLY_NAME_LINE_LIVE_HEIGHT)} data-live-name-line="">
                <span className="sm:hidden shrink-0 inline-flex">
                  <ModernAvatar role={liveName} name={liveName} size={REPLY_AVATAR_PHONE} />
                </span>
                <span className={REPLY_NAME}>{liveName}</span>
                {queued ? (
                  <span className="inline-flex items-center gap-1 text-zinc-400 text-[10px]">
                    <span className="w-1.5 h-1.5 rounded-full bg-zinc-500" aria-hidden="true" />
                    In line
                  </span>
                ) : (awaitingAnswer || bubble === 'approval') && !phone ? (
                  <span className="inline-flex items-center gap-1 text-amber-300 text-[10px]">
                    <span className="w-1.5 h-1.5 rounded-full bg-amber-300" aria-hidden="true" />
                    {bubble === 'approval' ? 'Waiting for your OK' : awaitingBrowser ? 'Waiting for you in the browser' : 'Waiting for your answer'}
                  </span>
                ) : discussionState?.inProgress ? (
                  <span className="inline-flex items-center gap-1 text-sky-400 text-[10px]">
                    <span className="w-1.5 h-1.5 rounded-full bg-sky-400 animate-ping motion-reduce:animate-none" aria-hidden="true" />
                    Speaking...
                  </span>
                ) : null /* "Generating" would repeat the working strip */}
              </div>

              {liveNote && <FailoverNote text={liveNote} />}

              {liveActivity && !stepsBelow && liveStepsList}

              {thinking && (
                <div className="mb-2 p-2.5 rounded-xl bg-sky-950/20 border border-sky-500/20 text-xs text-sky-300/90 flex items-center gap-2 animate-pulse motion-reduce:animate-none max-w-full">
                  <Sparkles size={13} className="text-sky-400 flex-shrink-0" />
                  <span className="truncate"><StreamPart stream={stream} part="thinking" onGrow={onStreamGrow} /></span>
                </div>
              )}

              {/* On a phone the strip says "working" and "waiting": no skeleton, no "Paused on…" bubble. */}
              {(!phone || queued || writing) && (
              <div className={`${REPLY_BUBBLE} min-h-[3.5rem] ${REPLY_BUBBLE_BOT}`} data-live-bubble-body="">
                {queued ? (
                  <p className="text-zinc-300" role="status">
                    {queued.position ? <strong className="font-medium text-zinc-100">#{queued.position} in line.</strong> : <strong className="font-medium text-zinc-100">In line.</strong>}{' '}
                    {queuedText(queued.reason, queued.slots)}
                  </p>
                ) : writing ? (
                  /* The scene's 62 px holds under the first words (kw-wa-hold, in StreamPart), so the bubble does not jump; they fade in once. */
                  <StreamPart stream={stream} part="text" onGrow={onStreamGrow} />
                ) : awaitingAnswer ? (
                  <p className="text-zinc-400" role="status">
                    {awaitingBrowser
                      ? 'Paused on the browser step above. Do it in the browser panel and press Done; this reply carries on from it.'
                      : 'Paused on the question above. Answer it there; this reply carries on from it.'}
                  </p>
                ) : bubble === 'approval' ? (
                  <p className="text-zinc-400" role="status" data-live-bubble="approval">
                    Paused on the approval below. Allow or deny it there; this reply carries on from it.
                  </p>
                ) : (
                  <WorkingAvatar
                    name={
                      discussionState?.inProgress && discussionState.currentSpeaker
                        ? discussionState.currentSpeaker
                        : streamingSpeakerName || title
                    }
                    audit={liveAudit}
                  />
                )}
              </div>
              )}

              {/* 18f: once words stream, the steps row sits below the bubble, where the landed action row goes */}
              {liveActivity && stepsBelow && liveStepsList}

              {!queued && <QueuedBeside items={queuedBeside} />}
            </div>
          </div>
        )}

        {/* P4: the running bot's shares, already in the place its saved reply will give them */}
        {liveRowShown && arranged.live.map((m) => renderMessage(m))}

        {/* Approvals allowed in Telegram (G4): "✓ Allowed once from Telegram", live and after a reload;
            22d: a customer's call nobody allowed, in that customer's chat */}
        {settledApprovals.map((approval) =>
          approval.refused ? (
            <RefusedCustomerCall key={approval.id} approval={approval} />
          ) : (
            <AllowedFromTelegram key={approval.id} lead={approvalLead(approval)} />
          ),
        )}

        {/* 0.8.0 B3: checks before this bot pushes */}
        {prepush}

        {/* Pending Security Approval Ticket */}
        {pendingApprovals.map((approval) => (
          // 0.8.1 F6: a notification's tap lands on this card and flashes it. 30a: the wrapper is always there
          // (display: contents when not flashing), so the flash never remounts the card: focus that "Go to the
          // approval" put on it stays, and so does a half-typed Deny reason. 30h: while flashing, the wrapper is as wide
          // as the card (the card's own max-w-2xl), so the amber box hugs the card instead of running to the column's
          // edge. Top and bottom already match: the card's my-3 collapses through the wrapper. 30j: the wrapper has
          // the same box idle and flashing (only kw-flash toggles), and !mt-0 cancels the list's space-y gap, so the
          // card stays where it sat idle instead of hopping 8 / 12 px as the flash starts and ends. It is the one
          // amber ring (the card root no longer gets its own), tagged with the flash kind as message rows are.
          <div
            key={approval.id}
            className={`max-w-2xl rounded-xl !mt-0${flashId === approval.id ? ' kw-flash' : ''}`}
            data-flash-kind={flashId === approval.id ? flashKind : undefined}
          >
            <ModernApprovalCard approval={approval} onResolve={onResolveApproval} />
          </div>
        ))}
      </div>

      {/* Suggested prompts for who is in this chat: one swipeable row on phones */}
      {/* O2 §6: hidden while nothing can run, instead of shown disabled */}
      {messages.length <= 1 && suggestions.length > 0 && !showHome && canRun !== false && (
        <ScrollRow
          className="kw-scroll-row px-3 sm:px-6 py-2 flex flex-nowrap sm:flex-wrap items-center gap-2 overflow-x-auto sm:overflow-visible select-none"
          role="group"
          aria-label="Suggested prompts"
        >
          <span className="shrink-0 text-[11px] font-medium text-zinc-500">Suggested:</span>
          {suggestions.map((prompt) => (
            <button
              key={prompt}
              type="button"
              onClick={() => handlePromptSuggestion(prompt)}
              className="shrink-0 whitespace-nowrap px-2.5 py-1 rounded-full text-xs text-zinc-400 bg-zinc-900 border border-zinc-800 hover:border-zinc-700 hover:text-zinc-200 transition-all shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
            >
              {prompt}
            </button>
          ))}
        </ScrollRow>
      )}

      {/* Modern Composer Input Bar */}
      <div
        ref={composerWrapRef}
        className={`px-3 ${phone ? 'pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]' : 'pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]'} sm:p-4 border-t border-hairline bg-surface-side/60`}
      >
        {newTagRoom > 0 && <div aria-hidden="true" data-new-tag-room={newTagRoom} style={{ height: newTagRoom }} />}
        {teamMembers && teamMembers.length > 0 && (
          <ScrollRow
            className={
              phone
                ? // Phone: 28 px chips that tap like 44 px. The row scrolls sideways, which clips
                  // anything sticking out of it, so it carries 8 px above and below for the chips'
                  // kws-hit areas and gives the same space back in its margins (row stays 28 px).
                  'kw-scroll-row max-w-4xl mx-auto -mt-1.5 mb-0.5 py-2 flex items-center gap-1.5 overflow-x-auto text-xs select-none'
                : 'kw-scroll-row max-w-4xl mx-auto mb-2.5 flex items-center gap-1.5 overflow-x-auto text-xs select-none'
            }
            role="group"
            aria-label="Ask a member"
          >
            <span className="shrink-0 text-[11px] font-medium text-zinc-500 whitespace-nowrap">Ask:</span>
            {teamMembers.map((m) => (
              <button
                key={m.id}
                type="button"
                onClick={() => handleInsertTag(`@${m.name}`)}
                data-compact={phone ? '' : undefined}
                className={
                  phone
                    ? 'kws-hit h-7 shrink-0 whitespace-nowrap flex items-center gap-1.5 px-2.5 rounded-full bg-zinc-800/90 hover:bg-zinc-700 text-zinc-300 hover:text-zinc-100 border border-zinc-700/60 transition-all text-xs cursor-pointer shadow-sm active:scale-95'
                    : 'shrink-0 whitespace-nowrap flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-zinc-800/90 hover:bg-zinc-700 text-zinc-300 hover:text-zinc-100 border border-zinc-700/60 transition-all text-xs cursor-pointer shadow-sm active:scale-95'
                }
                title={`Ask ${m.name}`}
              >
                <ModernAvatar role={m.avatar_sprite} name={m.name} size={14} kwantId={m.id} />
                <span>@{m.name}</span>
              </button>
            ))}
            {teamName && (
              <button
                type="button"
                onClick={() => handleInsertTag(`@${teamName}`)}
                data-compact={phone ? '' : undefined}
                className={
                  phone
                    ? 'kws-hit h-7 shrink-0 max-w-[14rem] whitespace-nowrap flex items-center gap-1.5 px-2.5 rounded-full bg-sky-950/60 hover:bg-sky-900/60 text-sky-300 hover:text-sky-200 border border-sky-800/60 transition-all text-xs cursor-pointer shadow-sm active:scale-95'
                    : 'shrink-0 max-w-[14rem] whitespace-nowrap flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-sky-950/60 hover:bg-sky-900/60 text-sky-300 hover:text-sky-200 border border-sky-800/60 transition-all text-xs cursor-pointer shadow-sm active:scale-95'
                }
                title={teamChipTitle(teamName)}
                aria-label={teamChipTitle(teamName)}
                data-team-chip=""
              >
                <Users size={12} className="shrink-0 text-sky-400" aria-hidden="true" />
                <span className="min-w-0 truncate">{teamChipLabel(teamName)}</span>
              </button>
            )}
          </ScrollRow>
        )}

        {/* On a phone the strip's "Answer ↑" stands in for this pill while the bot waits on the card. */}
        {/* 30a: one pointer per card: it also steps aside while the Needs-you strip offers "Go to the approval". */}
        {approvalPillShows({ offscreen: approvalOffscreen, waiting: pendingApprovals.length, phoneAnswerUp: phone && stripWaitsOn === 'approval', stripHasApproval }) && (
          <div role="status" className="max-w-4xl mx-auto mb-2 flex justify-center">
            <button
              type="button"
              onClick={() => {
                playSfx('click');
                showApproval();
              }}
              className="flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] rounded-full border border-amber-500/40 bg-amber-950/70 text-xs font-medium text-amber-200 hover:bg-amber-900/70 shadow-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
            >
              <ArrowDown size={12} aria-hidden="true" />
              {pendingApprovals.length === 1 ? 'Approval waiting' : `${pendingApprovals.length} approvals waiting`}
            </button>
          </div>
        )}

        {viewingHistory && (
          <div role="status" className="max-w-4xl mx-auto mb-2 flex items-center justify-between gap-2 px-3 py-1.5 rounded-xl border border-sky-800/50 bg-sky-950/40 text-xs text-sky-200">
            <span className="min-w-0">Showing older messages around the search result.</span>
            <button
              type="button"
              onClick={() => {
                playSfx('click');
                onJumpToLatest?.();
              }}
              className="shrink-0 flex items-center gap-1 px-2 py-0.5 rounded-lg border border-sky-700/60 text-sky-100 hover:bg-sky-900/60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
            >
              <ArrowDown size={12} aria-hidden="true" /> Jump to latest
            </button>
          </div>
        )}

        {/* Phone and desktop (0.8.1 F4): the quiet line sits inside the composer section, right above the box. */}
        {budgetBanner}
        {workingStrip}
        {/* 22i: below the working line, right above the box (design.md §2 order). */}
        {/* 29w: it steps aside (instantly, kept mounted) while it only repeats the approval card on screen. */}
        <div ref={stripSlotRef} className={stripAside ? 'hidden' : 'contents'} data-needs-you-slot={stripAside ? 'aside' : 'shown'} onFocus={(e) => (stripHadFocusRef.current = (e.target as HTMLElement).matches(':focus-visible'))} onBlur={() => (stripHadFocusRef.current = false)}>
          {needsYouStrip}
        </div>

        <form
          onSubmit={handleSubmit}
          aria-label={`Message ${title}`}
          data-composer-form
          data-stacked={phone ? String(stacked) : undefined}
          className={`relative max-w-4xl mx-auto flex flex-wrap items-end ${stacked ? 'gap-x-1.5 gap-y-1' : 'gap-1.5'} border rounded-2xl p-2 transition-colors ${
            phone ? 'bg-[#1a1538]' : 'bg-surface-raised shadow-raised'
          } ${phone ? 'border-white/10 focus-within:border-[#6c58e0]/70' : 'border-hairline-strong focus-within:border-sky-400/50'}${
            layerPhase ? ' kw-dd-raised' : ''
          }${composerLit ? ' kw-dd-lit' : ''}`}
          data-drop-lit={composerLit ? 'true' : undefined}
        >
          {replyTo && (
            <ReplyChip
              key={replyTo.id}
              botName={replyBotName(replyTo)}
              excerpt={excerptOf(replyTo.text, 200)}
              onOpen={() => showOriginal(replyTo.id)}
              onCancel={cancelReply}
            />
          )}
          {(uploads.length > 0 || uploadNote) && (
            <div className="basis-full min-w-0 px-1 pt-0.5 space-y-1.5">
              {uploads.length > 0 && (
                <ul className="flex flex-wrap gap-1.5 min-w-0" aria-label="Files to send">
                  {uploads.map((u) =>
                    u.point ? (
                      <PointChip key={u.key} item={u} onRemove={() => removeUpload(u.key)} />
                    ) : (
                      <UploadChip key={u.key} item={u} onRemove={() => removeUpload(u.key)} onRetry={() => retryUpload(u.key)} fresh={freshChips[u.key]} />
                    ),
                  )}
                </ul>
              )}
              {uploadNote && (
                <p role="alert" className="flex items-start gap-2 text-[11px] text-amber-300">
                  <span className="min-w-0">{uploadNote}</span>
                  <button type="button" onClick={() => setUploadNote(null)} className="shrink-0 text-zinc-500 hover:text-zinc-300 underline-offset-2 hover:underline">
                    Dismiss
                  </button>
                </p>
              )}
            </div>
          )}
          {ideaMode && (
            <p data-idea-hint className="basis-full min-w-0 px-1 pt-0.5 flex items-center gap-1.5 text-[12px] leading-4 text-sky-200">
              <JarIcon size={13} className="shrink-0 text-info" />
              <span className="min-w-0 line-clamp-2">
                Goes in the idea jar, not to{' '}
                <span className="font-medium text-sky-100">
                  {home?.kind === 'bot' ? home.bot?.name ?? title : title.startsWith('#') || home?.kind === 'team' ? title : `#${title}`}
                </span>
                . No bot reads it now.
              </span>
            </p>
          )}
          {slashOpen && (
            <div
              role="listbox"
              id="kw-slash-list"
              aria-label="Commands"
              data-slash-popover
              className="kw-fade-in absolute bottom-full left-0 mb-2 bg-surface-overlay border border-hairline-strong rounded-xl shadow-raised p-1.5 min-w-[260px] z-50"
            >
              <button
                type="button"
                role="option"
                id="kw-slash-idea"
                aria-selected="true"
                onMouseDown={(e) => e.preventDefault()}
                onClick={completeIdea}
                className="w-full flex items-center gap-2.5 px-2.5 min-h-11 sm:min-h-9 rounded-lg bg-white/[0.06] text-left text-sm text-zinc-100 hover:bg-white/[0.08]"
              >
                <JarIcon size={15} className="text-info shrink-0" />
                <span className="font-semibold text-info">/idea</span>
                <span className="text-zinc-400">Drop an idea in the jar</span>
                <kbd className="ml-auto font-sans text-[11px] text-zinc-500">Tab</kbd>
              </button>
            </div>
          )}
          {isMentionOpen && (
            <MentionPopover
              items={matchingItems}
              selectedIndex={safeSelectedIndex}
              onSelect={handleSelectMention}
            />
          )}
          <DictationSetupPopover d={dict} phone={phone} onOpenAccounts={onOpenAccounts} />
          <DictationLine d={dict} phone={phone} botName={title} reduced={reducedMotion} />
          <DictationAnnouncer d={dict} />

          <textarea
            ref={textareaRef}
            data-composer
            role="combobox"
            aria-expanded={isMentionOpen || slashOpen}
            aria-controls={isMentionOpen ? 'kw-mention-list' : slashOpen ? 'kw-slash-list' : undefined}
            aria-activedescendant={isMentionOpen ? `kw-mention-${safeSelectedIndex}` : slashOpen ? 'kw-slash-idea' : undefined}
            aria-invalid={ideaLine ? true : undefined}
            aria-describedby={ideaLine ? 'kw-idea-line' : undefined}
            aria-autocomplete="list"
            rows={1}
            value={inputVal}
            onFocus={() => setComposerFocused(true)}
            onBlur={() => setComposerFocused(false)}
            onChange={(e) => {
              const val = e.target.value;
              setInputVal(val);
              dict.noteTyping();
              e.target.style.height = 'auto';
              e.target.style.height = `${Math.min(e.target.scrollHeight, 160)}px`;
              checkMention(val, e.target.selectionStart);
            }}
            onKeyDown={handleKeyDown}
            onPaste={(e) => {
              const pasted = filesFrom(e.clipboardData.items);
              if (pasted.length) {
                e.preventDefault();
                addFiles(pasted);
              }
            }}
            onClick={(e) => {
              checkMention(inputVal, (e.target as HTMLTextAreaElement).selectionStart);
            }}
            onKeyUp={(e) => {
              if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) {
                checkMention(inputVal, (e.target as HTMLTextAreaElement).selectionStart);
              }
            }}
            // Phones: "Message {name}" only when it fits on one line, else "Message" (the header names the chat)
            placeholder={placeholder}
            title="Enter to send, Shift+Enter for a new line, @ to mention"

            className={
              phone
                ? `${stacked ? 'basis-full w-full py-2' : 'flex-1 py-2.5'} min-w-0 bg-transparent px-3 text-base leading-6 text-zinc-50 placeholder:text-[#8f88bb] placeholder:whitespace-nowrap placeholder:overflow-hidden placeholder:text-ellipsis focus:outline-none resize-none max-h-40 font-sans`
                : 'flex-1 min-w-0 bg-transparent px-3 py-1.5 text-body text-zinc-50 placeholder-zinc-400 focus:outline-none resize-none max-h-40 font-sans'
            }
          />
          <input
            ref={fileInputRef}
            type="file"
            multiple
            hidden
            tabIndex={-1}
            onChange={(e) => {
              addFiles(filesFrom(e.target.files));
              e.target.value = '';
            }}
          />
          {/* Phone, in use: the tools get their own 44 px row under the text. Elsewhere this wrapper is
              display: contents, so the buttons sit beside the field as before. */}
          <div data-composer-tools className={stacked ? 'basis-full flex items-center h-11' : 'contents'}>
          <button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            disabled={uploadSlotsLeft(uploads) === 0}
            title={uploadSlotsLeft(uploads) === 0 ? `Up to ${MAX_ATTACHMENTS} files per message` : ATTACH_TITLE}
            aria-label="Attach files"
            className={`${phone ? toolPhone : 'w-11 h-11 sm:w-9 sm:h-9 text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.08] focus-visible:outline-sky-400'} rounded-xl flex items-center justify-center flex-shrink-0 disabled:opacity-40 disabled:cursor-not-allowed transition-colors focus-visible:outline focus-visible:outline-2`}
          >
            <Paperclip size={phone ? 18 : 17} aria-hidden="true" />
          </button>
          <button
            type="button"
            onClick={() => {
              markNewSeen('mention');
              insertAt();
            }}
            title="Mention a bot: it answers instead of the default"
            aria-label="Mention a bot"
            className={`relative ${phone ? toolPhone : 'w-11 h-11 sm:w-9 sm:h-9 text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.08] focus-visible:outline-sky-400'} rounded-xl flex items-center justify-center flex-shrink-0 transition-colors focus-visible:outline focus-visible:outline-2`}
          >
            <AtSign size={phone ? 18 : 17} aria-hidden="true" />
            {/* Phone (spec A5): "New" anchors to the @ button's own box, never on the field's border or an Ask chip.
                15e: it sits centred above the 18 px glyph with 2 px clear (its bottom edge 9 + 2 px above the
                button's middle), so it never covers the "@". Same hide rules as desktop's tag below. */}
            {phone && !isStreaming && (
              <NewTag id="mention" className={`absolute left-1/2 -translate-x-1/2 bottom-[calc(50%+11px)] ${isMentionOpen ? 'hidden' : ''} ${dict.popOpen ? 'hidden' : ''} ${layerPhase || budgetBanner ? 'hidden' : ''}`} />
            )}
          </button>
          {stacked && <span className="flex-1" aria-hidden="true" />}
          {/* "New" sits just above the field's top edge, over the "@" button: never on or inside the border.
              Only the send button follows "@" when it shows: 44px on phones / 36px from sm, plus a 6px gap;
              11px is the form's border + padding. Hidden (not marked as seen) while a reply streams, so it
              never sits on the working strip's edge and comes back after the turn; hidden while the mention
              picker is open, so it never peeks under it; hidden (not marked as seen) while the drop layer is up,
              so it never outshines the drop card (#478 Mira M3). */}
          {!phone && !isStreaming && (
            <NewTag
              id="mention"
              className={`absolute bottom-full mb-1.5 [--kw-cbtn-step:50px] sm:[--kw-cbtn-step:42px] ${isMentionOpen ? 'hidden' : ''} ${dict.popOpen ? 'hidden' : ''} ${layerPhase || budgetBanner ? 'hidden' : ''}`}
              style={{ right: dict.view === 'hidden' ? 'calc(11px + var(--kw-cbtn-step))' : 'calc(11px + 2 * var(--kw-cbtn-step))' }}
            />
          )}

          {isStreaming && !askOnly && (
            <button
              type="button"
              onClick={onCancelDiscussion}
              className="w-11 h-11 sm:w-9 sm:h-9 rounded-xl flex items-center justify-center transition-colors flex-shrink-0 bg-rose-500/20 hover:bg-rose-500/30 text-rose-300 border border-rose-400/30 cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-400"
              title={discussionState?.inProgress ? 'Stop Discussion' : 'Stop'}
              aria-label={discussionState?.inProgress ? 'Stop discussion' : 'Stop'}
            >
              <Square size={12} fill="currentColor" aria-hidden="true" />
            </button>
          )}
          {ideaMode && (
            <span
              data-idea-counter
              aria-hidden="true"
              className={`flex-shrink-0 px-1.5 text-[11px] tabular-nums ${ideaLength(inputVal) > IDEA_MAX ? 'text-rose-300' : 'text-zinc-500'}`}
            >
              {ideaLength(inputVal).toLocaleString('en-US')} / {IDEA_MAX.toLocaleString('en-US')}
            </span>
          )}
          <MicButton d={dict} phone={phone} />
          {ideaMode ? (
            <button
              type="submit"
              aria-label="Drop in the jar"
              title="Drop in the jar"
              disabled={!canSend}
              data-send-ready={canSend ? 'true' : 'false'}
              data-idea-send
              className={`w-11 h-11 ${phone ? '' : 'sm:w-9 sm:h-9'} rounded-xl flex items-center justify-center flex-shrink-0 transition-[transform,background-color] duration-150 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 ${
                canSend
                  ? 'bg-sky-600 text-white hover:bg-sky-700 active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100'
                  : 'bg-sky-500/20 text-sky-300/60 cursor-not-allowed'
              }`}
            >
              <JarIcon size={phone ? 18 : 17} />
            </button>
          ) : !(phone && !stacked && dict.view !== 'hidden') && (askOnly || !(isStreaming && (discussionState?.inProgress || (!canSend && !dict.busy)))) && (
            <button
              type="submit"
              aria-label={dict.busy ? 'Send (waiting for dictation)' : stillUploading ? 'Send (waiting for uploads)' : askOnly ? 'Send (answers the question)' : isStreaming ? 'Send (waits for the current reply)' : 'Send'}
              title={dict.busy ? 'Waiting for dictation to finish' : stillUploading ? 'Waiting for uploads to finish' : undefined}
              disabled={!canSend}
              data-send-ready={canSend ? 'true' : 'false'}
              className={`${phone ? 'w-11 h-11 ml-1.5 focus-visible:outline-[#b8adff]' : 'w-11 h-11 sm:w-9 sm:h-9 focus-visible:outline-sky-300'} rounded-xl flex items-center justify-center flex-shrink-0 transition-[transform,filter,box-shadow,background-color] duration-150 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 ${
                canSend
                  ? phone
                    ? 'bg-[#6c58e0] text-white hover:bg-[#5845bd] active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100'
                    : 'bg-accent-gradient kw-hover-deepen text-white shadow-glow active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100'
                  : phone
                    ? 'bg-[#2c2552] text-[#5a5383] cursor-not-allowed'
                    : 'bg-surface-overlay text-zinc-400 cursor-not-allowed'
              }`}
            >
              <ArrowUp size={phone ? 18 : 17} strokeWidth={2.4} aria-hidden="true" />
            </button>
          )}
          </div>
        </form>
        {ideaLine && (
          <p id="kw-idea-line" role="alert" data-idea-line className="max-w-4xl mx-auto mt-1.5 px-1 text-meta text-rose-300">
            {ideaLine}
          </p>
        )}
        {/* Under the field: who will answer, and what the field understands */}
        <div
          className={`max-w-4xl mx-auto mt-1.5 px-1 flex items-center justify-between gap-3 text-meta text-zinc-400${kbd || (!showAnswers && !showHintText) ? ' hidden' : ''}`}
          data-composer-hints
        >
          {showAnswers && (
            <span
              className={`kw-chip min-w-0 ${showHintText ? 'max-w-[min(22rem,60%)]' : 'max-w-full'} ${target.kind === 'laya' ? 'kw-chip-accent' : target.kind === 'mention' ? 'kw-chip-info' : ''}`}
              title={target.detail}
              data-answer-target={target.kind}
            >
              {target.kind === 'laya' ? <Sparkles size={12} className="shrink-0" aria-hidden="true" /> : <AtSign size={12} className="shrink-0" aria-hidden="true" />}
              <span className="shrink-0 whitespace-nowrap text-zinc-400 font-normal">Answers:</span>
              <span className="min-w-0 truncate" data-answer-name="">{target.kind === 'laya' ? target.label : target.label.replace(/^@/, '')}</span>
            </span>
          )}
          {showHintText && (
            <span className="min-w-0 truncate text-right">
              <span className="sm:hidden">@ mention · attach files</span>
              <span className="hidden sm:inline">
                <kbd className="font-sans text-zinc-300">@</kbd> mention a bot · <kbd className="font-sans text-zinc-300">Enter</kbd> send · <kbd className="font-sans text-zinc-300">Shift+Enter</kbd> new line · drop or paste files
              </span>
            </span>
          )}
        </div>
      </div>
    </div>

    {/* Live Grok-style Virtual Machine / Browser Side Pane */}
    <VirtualMachinePane
      key={teamId}
      isOpen={vmOpen}
      onClose={() => {
        if (onToggleVmPane) {
          onToggleVmPane();
        } else {
          setInternalIsVmPaneOpen(false);
        }
      }}
      teamId={teamId}
      teamName={teamName}
      activeUrl={activeUrl}
      pageTitle={pageTitle}
      screenshotBase64={screenshotBase64}
      isRunning={isRunning}
      browserError={browserError}
      terminalLogs={terminalLogs}
      onRefresh={onRefreshVm}
      onRestartVm={onRestartVm}
      onNavigate={onNavigateVm}
      approvalsOff={vmApprovalsOff}
      captchaStep={vmCaptchaStep}
      humanStep={vmHumanStep}
      switcher={vmSwitcher}
      onStepDone={onVmStepDone}
      solveRequest={vmSolveRequest}
      pagePick={vmPagePick}
      botNames={vmBotNames}
      showOnceBot={vmShowOnceBot}
      point={pointSink}
      running={vmRunning}
      finishedAt={paneFinishedAt}
      browsingBot={paneBot}
      trail={paneTrail}
      onTouch={onVmTouch}
      onUsage={onVmUsage}
      closing={vmClosing}
    />
  </div>
      {layerPhase && (
        <DropLayer
          phase={layerPhase}
          card={livePhase ? card : lastCard.current}
          single={dropTo.single}
          bots={dropTo.bots}
          bottomPad={layerBox.bottomPad}
          rightGap={layerBox.rightGap}
        />
      )}
      {/* The drop card's words, and "3 files added for Frontend. Uploading." after a drop. */}
      <div role="status" aria-live="polite" className="sr-only" data-drop-announce>
        {dropAnnounce}
      </div>
</div>
  );
};