Skip to content

AI, fully local on your computer.

43.3 KB
Raw Blame
import { Fragment, memo, useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react'
import { AssistantMarkdown } from './AssistantMarkdownLazy'
import type {
  Citation,
  ConversationSummaryMarker,
  EvidenceReviewSummary,
  Message,
  PackArticleSaveResult
} from '@shared/types'
import type { AnswerSpeed } from '@shared/ipc'
import type { UiLanguage } from '@shared/i18n'
import { isReviewEligible } from '@shared/evidence-review'
import { formatAnswerSpeed } from './answerSpeed'
import { MessageActions } from './MessageActions'
import { SourcesDisclosure } from './SourcesDisclosure'
import { CodeBlockActionsContext } from './CodeBlockActionsContext'
import { PackOutcomesNotice } from './PackOutcomesNotice'
import { CoverageMeter, Icon, Spinner } from '../components'
import { localizeServerCopy } from '../lib/displayMap'
import { useT, type I18n } from '../i18n'

// Transcript (guidelines §3): the conversation IS the canvas — centered,
// max-width 720px, --text-md body (CSS). Assistant answers carry an inline
// "▸ Sources (N)" disclosure and a hover/focus action row; the live streaming bubble
// shows the collapsed "Thinking…" line (never persisted) and announces streamed text to
// screen readers via a separate visually-hidden plain-text live region (StreamAnnouncer,
// audit L7) — the visible markdown is intentionally not a live region.

interface TranscriptProps {
  messages: Message[]
  /** True when the in-flight stream belongs to THIS conversation. */
  streamingHere: boolean
  streamText: string
  /** Live Deep-mode reasoning; '' hides the Thinking… line. */
  streamThinking: string
  /** Controlled expand state of the Thinking… line (auto-collapses on first token). */
  thinkingOpen: boolean
  onThinkingOpenChange: (open: boolean) => void
  /**
   * #39: show the calm one-time "the first answer takes a little longer — the model is
   * warming up" line under the pending answer. The parent sets it only when the turn has
   * streamed nothing for a few seconds AND the runtime reports this is its first generation
   * since the model started; it drops the flag on the first streamed chunk. Ephemeral —
   * rendered inside the live streaming bubble only, never persisted.
   */
  warmupHint?: boolean
  /** Rendered when there is nothing to show (the teaching empty state). */
  emptyState: ReactNode
  /** Provided only for the message that can regenerate (last assistant turn, chat mode). */
  onTryAgain?: () => void
  /**
   * #613 "Send again": ask the conversation's last question again when no answer follows it (an
   * error, a crash, a stop before the first word). Rendered only under that question, in either mode,
   * and never while it is being answered. Gets the question's id, which main re-checks. Absent ⇒ the
   * affordance never renders: the parent withholds it while a reply streams and until its check that
   * none is in flight for this conversation has come back (so it is never shown disabled).
   */
  onSendAgain?: (messageId: string) => void
  /**
   * Re-run the turn skill-free (S13c "answer without it" undo). Surfaced on the last assistant turn
   * that ANY skill shaped — auto-fired OR explicitly picked (U3, audit §4.3: a per-turn pick must be
   * as reversible as an auto-fire). Absent ⇒ the affordance never renders.
   */
  onAnswerWithoutSkill?: () => void
  /**
   * Re-run the turn WITH the offered skill (#80, wave R80) — the one-click accept on a per-answer
   * `skillOffer`. Rendered only on the LAST assistant turn (it re-answers via the regenerate path,
   * which acts on the conversation's last turn — the SKA-37 gate the undo shares). The click IS
   * the consent (S13b/D4): main re-runs the same question with the skill explicitly set; nothing
   * auto-fires. Absent ⇒ the affordance never renders (the answer's prose hint remains).
   */
  onRunWithSkill?: (installId: string) => void
  /**
   * #132: is the offered skill STILL runnable right now (enabled + installed + available)? The offer
   * persists in `messages.skill_offer_json` indefinitely, but its offer-time gate ran only at mint —
   * without a click-time re-check, a click on an offer for a since-disabled/removed skill silently
   * regenerated the answer with NO skill. When this returns false the row renders DISABLED with an
   * honest tooltip (the AUD-01 disabled-never-hidden posture the undo shares). Absent ⇒ treated as
   * available (older callers keep their behavior; main still refuses the stale id).
   */
  isSkillOfferAvailable?: (installId: string) => boolean
  /**
   * #290: per-answer speed figures for answers generated in THIS session, keyed by message id.
   * A message without an entry (older turns after a reload, the mock runtime, an aborted answer)
   * renders no line. Absent ⇒ no lines at all.
   */
  answerSpeeds?: ReadonlyMap<string, AnswerSpeed>
  onCopy: (content: string) => void
  onSave: () => void
  /**
   * #286: save ONE fenced code block out of a persisted assistant reply as a file. Absent => no
   * per-block toolbar renders anywhere (the affordance is opt-in, D3) and the markdown DOM is
   * unchanged. `language` is the fence language token (model output); main maps it through the
   * shared extension allowlist. Never wired on the live streaming bubble.
   */
  onSaveCodeBlock?: (messageId: string, content: string, language: string) => void
  /**
   * Save one answer's attached RESULT TABLE as CSV (result-tables §4, Phase 2). Rendered only on
   * messages with `hasResultTable`; the MAIN side re-serializes the persisted table and opens the
   * save dialog. Absent ⇒ the affordance never renders.
   */
  onExportTable?: (messageId: string) => void
  /**
   * Open (or continue) the evidence review for one answer (EP-1 plan §7.2, spec §9.1). Rendered
   * only on `isReviewEligible` assistant turns — assistant ∧ (citations ∨ coverage) — and on
   * any assistant turn that already has a review in `reviewSummaries` (#976). Absent ⇒ the affordance never renders. The
   * STREAMING gate is the row's shared `actionsDisabled` (a live bubble has no action row at
   * all — only persisted turns reach MessageActions).
   */
  onOpenReview?: (messageId: string) => void
  /** Knowledge packs (ZIM wave): open the offline article viewer for an archive citation.
   *  Absent => archive source cards render without the open affordance. */
  onOpenArticle?: (citation: Citation) => void
  /** #418: save an archive citation's article to the user's documents from the card itself.
   *  Absent => the save affordance never renders (optional-callback gating, like onOpenArticle). */
  onSaveArticle?: (packId: string, articlePath: string) => Promise<PackArticleSaveResult>
  /**
   * Known review state per message id (null = checked, none exists) — drives the
   * "Review evidence" vs "Continue review" label + the Draft/Ready chip (spec §9.4).
   */
  reviewSummaries?: ReadonlyMap<string, EvidenceReviewSummary | null>
  actionsDisabled: boolean
  /**
   * Resolve a skill's per-message glyph title in the UI language (installId → localized title),
   * falling back to the stamped canonical title. Optional — when absent the stamped title is shown.
   */
  resolveSkillTitle?: (installId: string | null | undefined, fallbackTitle: string) => string
  /**
   * The live "working on it" notice above the streaming bubble for THIS turn, or null/absent when
   * none (context-compaction §5.2). `'compaction'` = summarizing earlier messages; `'analysis'` (U5,
   * audit §3.6) = an exhaustive skill handler reading the whole document before its answer. Ephemeral:
   * cleared by the parent on the first answer token.
   */
  progressNotice?: 'compaction' | 'analysis' | null
  /**
   * The latest compaction summary + where its transcript marker sits (context-compaction §5.3,
   * D-b). The "⌄ Earlier messages summarized" divider renders before the message whose id matches
   * `beforeMessageId`; expandable to read the summary. Absent/null ⇒ no marker.
   */
  summaryMarker?: ConversationSummaryMarker | null
}

// Memoized (perf audit FE-3): ChatScreen re-renders on every keystroke (input state) and every
// ~40 ms streaming flush. With stable props from the parent (useCallback'd handlers + a memoized
// emptyState), the transcript — and its per-message Markdown parsing — is skipped on a keystroke
// and only re-renders for genuine transcript/stream changes.
export const Transcript = memo(function Transcript({
  messages,
  streamingHere,
  streamText,
  streamThinking,
  thinkingOpen,
  onThinkingOpenChange,
  warmupHint,
  emptyState,
  onTryAgain,
  onSendAgain,
  onAnswerWithoutSkill,
  onRunWithSkill,
  isSkillOfferAvailable,
  onCopy,
  onSave,
  onSaveCodeBlock,
  onExportTable,
  onOpenReview,
  onOpenArticle,
  onSaveArticle,
  reviewSummaries,
  actionsDisabled,
  resolveSkillTitle,
  progressNotice,
  summaryMarker,
  answerSpeeds
}: TranscriptProps): JSX.Element {
  const { t, lang } = useT()
  // Stable ids wiring the live "Thinking…" toggle to its region (FE-D aria-controls).
  const thinkingId = useId()
  const scrollRef = useRef<HTMLDivElement>(null)
  // Whether the viewport is pinned to the bottom. We only auto-scroll on new content while the
  // user is already near the bottom, so a ~40 ms streaming flush no longer forces a layout +
  // scroll when the user has scrolled up to read an earlier turn (perf audit FE-1/FE-5).
  const atBottomRef = useRef(true)
  function onScroll(): void {
    const el = scrollRef.current
    if (!el) return
    atBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80
  }

  // Keep the transcript scrolled to the newest content — but only while pinned to the bottom,
  // so a streaming flush never yanks a user who scrolled up to read.
  useEffect(() => {
    if (atBottomRef.current) scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight })
  }, [messages, streamText, streamThinking])

  // Id of the assistant turn that drives the regenerate / "answer without it" affordances. SKA-37
  // (skills audit 2026-07-03, U6): these affordances re-answer via the REGENERATE path, which acts on
  // the conversation's LAST turn — so they must render ONLY when the last message IS that assistant
  // turn. A trailing UNANSWERED user turn (e.g. a send that failed to produce an answer) otherwise let
  // "Answer without this skill" on A1 actually re-answer the later Q2 skill-free. So the id is the last
  // message's id only when it is an assistant turn — a trailing user turn suppresses both affordances
  // (that question gets "Send again" instead — `resendableId` below, #613). Memoized (perf audit FE-1).
  const lastAssistantId = useMemo(() => {
    const last = messages[messages.length - 1]
    return last && last.role === 'assistant' ? last.id : undefined
  }, [messages])

  // #613: the question "Send again" sits under — the last message, when it is a user turn, i.e. no
  // answer follows it. Not while it is being answered: the live bubble below IS its answer.
  const resendableId = useMemo(() => {
    const last = messages[messages.length - 1]
    return last && last.role === 'user' && !streamingHere ? last.id : undefined
  }, [messages, streamingHere])

  // #600/#612: questions a turn that ended early left with no answer (a model stop, the Stop button,
  // lock or quit) — marked in the database, and still not followed by an answer (a later re-ask from
  // that question would answer it). #613: a resent question is being answered while this conversation
  // streams, so its old note waits — the persisted list after the turn says whether it still applies.
  const unansweredIds = useMemo(() => {
    const ids = new Set<string>()
    messages.forEach((m, i) => {
      if (m.role !== 'user' || m.endedEarly == null || messages[i + 1]?.role === 'assistant') return
      if (streamingHere && i === messages.length - 1) return
      ids.add(m.id)
    })
    return ids
  }, [messages, streamingHere])

  // localizeServerCopy is an O(n) Map-lookup + two regex .exec over the WHOLE growing buffer; it
  // was run TWICE per ~40 ms flush (visible bubble + StreamAnnouncer). Compute it once and feed
  // both — behavior identical, half the work on the CPU-bound streaming path (perf audit F2).
  const localizedStream = useMemo(() => localizeServerCopy(t, streamText), [t, streamText])

  return (
    // CH-12 (#148): the scroller is keyboard-reachable — user bubbles carry no focusable
    // elements, so without tabIndex a keyboard-only user could not scroll a long history
    // freely (only jump between the assistant turns' action buttons).
    <div
      className="chat-transcript"
      ref={scrollRef}
      onScroll={onScroll}
      tabIndex={0}
      role="region"
      aria-label={t('chat.transcript.label')}
    >
      <div className="chat-transcript-inner">
        {messages.length === 0 && !streamingHere && emptyState}
        {/* Each persisted message is a memoized MessageBlock keyed by id (its content is stamped
            once and never mutates), so a streaming flush — which only changes `streamText` on the
            live bubble below — never re-parses a prior message's Markdown (perf audit FE-1). */}
        {messages.map((m) => (
          <Fragment key={m.id}>
            {/* The summary divider (§5.3, D-b) renders just before the first turn the checkpoint
                does NOT subsume — "everything above was condensed for the model; below is verbatim". */}
            {summaryMarker && summaryMarker.beforeMessageId === m.id && (
              <SummaryMarker summary={summaryMarker.summary} t={t} />
            )}
            <MessageBlock
              m={m}
              t={t}
              isLast={m.id === lastAssistantId}
              unanswered={unansweredIds.has(m.id)}
              onTryAgain={onTryAgain}
              // Only the resendable question gets the handler, so the other blocks' memo holds (FE-3).
              onSendAgain={m.id === resendableId ? onSendAgain : undefined}
              onAnswerWithoutSkill={onAnswerWithoutSkill}
              onRunWithSkill={onRunWithSkill}
              isSkillOfferAvailable={isSkillOfferAvailable}
              onCopy={onCopy}
              onSave={onSave}
              onSaveCodeBlock={onSaveCodeBlock}
              onExportTable={onExportTable}
              onOpenReview={onOpenReview}
              onOpenArticle={onOpenArticle}
              onSaveArticle={onSaveArticle}
              reviewSummary={reviewSummaries?.get(m.id) ?? null}
              actionsDisabled={actionsDisabled}
              resolveSkillTitle={resolveSkillTitle}
              answerSpeed={answerSpeeds?.get(m.id) ?? null}
              lang={lang}
            />
          </Fragment>
        ))}
        {/* §5.2/U5: quiet "working on it" status above the streaming bubble; the parent clears
            `progressNotice` on the first answer token. 'analysis' (U5, §3.6) shows honest "reading the
            document…" copy instead of the compaction "summarizing…" line. Same spinner vocabulary. */}
        {progressNotice && streamingHere && (
          <div className="chat-compaction-notice" role="status">
            <Spinner />{' '}
            {t(progressNotice === 'analysis' ? 'chat.analysis.inProgress' : 'chat.compaction.inProgress')}
          </div>
        )}
        {streamingHere && (
          <div className="msg-block assistant">
            <div className="msg assistant">
              <div className="msg-role">{t('chat.role.assistant')}</div>
              {/* Deep mode: live reasoning, collapsed by default, auto-collapsed
                  again when the first answer token lands. Display-only — never persisted,
                  so it disappears once the final reply is re-read from history. */}
              {streamThinking !== '' && (
                // A <button aria-expanded> (the SourcesDisclosure pattern), not a
                // <details>/<summary> driven by preventDefault (audit L15): the controlled
                // toggle (auto-collapse on the first answer token) used to fight the native
                // <details> state, which could desync the implicit aria-expanded a screen
                // reader announces. An explicit aria-expanded button stays in lockstep.
                <div className="msg-thinking">
                  <button
                    type="button"
                    className="msg-thinking-toggle"
                    id={`${thinkingId}-toggle`}
                    aria-expanded={thinkingOpen}
                    aria-controls={`${thinkingId}-region`}
                    onClick={() => onThinkingOpenChange(!thinkingOpen)}
                  >
                    {t('chat.thinking')}
                  </button>
                  {/* Kept mounted and hidden (not unmounted) when collapsed, matching the
                      old <details> semantics: the live reasoning buffer keeps accumulating
                      and is available to AT, while `hidden` removes it from view + the a11y
                      tree when collapsed. The toggle's aria-controls names this region (FE-D). */}
                  <div
                    className="msg-thinking-text"
                    id={`${thinkingId}-region`}
                    role="region"
                    aria-labelledby={`${thinkingId}-toggle`}
                    hidden={!thinkingOpen}
                  >
                    {streamThinking}
                  </div>
                </div>
              )}
              {/* The live answer renders Markdown via Streamdown (perf audit FE-1, revisited):
                  Streamdown splits the buffer into blocks and memoizes each, so a ~40 ms flush only
                  re-parses the final block instead of the whole growing reply (the O(n²) that made
                  this plain text before). `parseIncompleteMarkdown` closes dangling **bold**, `code`,
                  fences and links mid-stream so the bubble formats cleanly instead of flashing raw
                  markers. `.md` applies the same prose CSS as a persisted turn. Feeds on the ONE
                  memoized `localizedStream` (perf audit F2) — inlining localizeServerCopy here would
                  re-scan the whole buffer a second time per flush. The visible text is NOT a live
                  region (audit L7) — announcement is delegated to the separate sentence-throttled
                  StreamAnnouncer below. */}
              <div className="msg-content md">
                <AssistantMarkdown text={localizedStream} streaming />
                <span className="cursor" aria-hidden="true">
                  ▋
                </span>
              </div>
              {/* #39: the calm warm-up honesty line — the app IS doing the right thing (one-time
                  prefill that `cache_prompt` reuses), it just says so at the moment a new user
                  would otherwise read the silence as "stuck". role="status" announces it once,
                  politely; the parent drops it the instant anything streams. */}
              {warmupHint && (
                <div className="chat-warmup-hint" role="status">
                  {t('chat.warmup.hint')}
                </div>
              )}
              <StreamAnnouncer text={localizedStream} />
            </div>
          </div>
        )}
      </div>
    </div>
  )
})

/**
 * One persisted message (user or assistant). Memoized (React.memo) and keyed by message id so a
 * ~40 ms streaming flush — which only updates the live bubble's `streamText` — never re-renders
 * or re-parses the Markdown of prior, unchanged turns (perf audit FE-1). The memo is fully
 * effective once the parent passes stable callbacks (perf audit FE-3); even before that, the
 * memoized `AssistantMarkdown` below keeps identical text from being re-parsed.
 */
const MessageBlock = memo(function MessageBlock({
  m,
  t,
  isLast,
  unanswered,
  onTryAgain,
  onSendAgain,
  onAnswerWithoutSkill,
  onRunWithSkill,
  isSkillOfferAvailable,
  onCopy,
  onSave,
  onSaveCodeBlock,
  onExportTable,
  onOpenReview,
  onOpenArticle,
  onSaveArticle,
  reviewSummary,
  actionsDisabled,
  resolveSkillTitle,
  answerSpeed,
  lang
}: {
  m: Message
  t: I18n['t']
  /** #290: this session's speed figures for the answer, or null (no line). */
  answerSpeed: AnswerSpeed | null
  lang: UiLanguage
  /** True on the last assistant turn — gates the regenerate + "answer without it" affordances. */
  isLast: boolean
  /** #600/#612: a question a turn that ended early left with no answer — shows the "Not answered"
   *  note for its `endedEarly` cause. */
  unanswered: boolean
  onTryAgain?: () => void
  /** #613: set only on the last question when no answer follows it — renders "Send again". */
  onSendAgain?: (messageId: string) => void
  onAnswerWithoutSkill?: () => void
  onRunWithSkill?: (installId: string) => void
  isSkillOfferAvailable?: (installId: string) => boolean
  onCopy: (content: string) => void
  onSave: () => void
  onSaveCodeBlock?: (messageId: string, content: string, language: string) => void
  onExportTable?: (messageId: string) => void
  onOpenReview?: (messageId: string) => void
  onOpenArticle?: (citation: Citation) => void
  onSaveArticle?: (packId: string, articlePath: string) => Promise<PackArticleSaveResult>
  reviewSummary?: EvidenceReviewSummary | null
  actionsDisabled: boolean
  resolveSkillTitle?: (installId: string | null | undefined, fallbackTitle: string) => string
}): JSX.Element {
  // Review-entry eligibility (spec §9.1) via the ONE shared predicate — the action row and
  // the sources-disclosure footer can never disagree. A persisted turn only; the live
  // streaming bubble never reaches MessageBlock (the caller's streaming gate, P1 handoff).
  // #976 (G-7): an answer with sources or a coverage label, or one that already has a review (so a review made
  // under a no-context answer keeps its "Continue review" entry and chip).
  const reviewable = onOpenReview != null && (isReviewEligible(m) || reviewSummary != null)
  const openReview = reviewable ? () => onOpenReview(m.id) : undefined
  // #80: the per-answer skill offer renders only on the LAST assistant turn (SKA-37 — accepting it
  // re-answers via regenerate, which acts on the conversation's last turn). A const so the JSX
  // narrowing holds inside the handler closures below.
  const skillOffer =
    m.role === 'assistant' && isLast && onRunWithSkill != null ? m.skillOffer : undefined
  // #286: the per-code-block Copy/Save actions for THIS persisted turn. null (no handler wired)
  // means AssistantMarkdown renders exactly the DOM it rendered before the feature existed — the
  // provider is inert. Memoized on the message id + the two (stable, useEventCallback'd) handlers
  // so a re-render never hands Streamdown a fresh context value and re-renders every block (FE-3).
  const codeBlockActions = useMemo(
    () =>
      onSaveCodeBlock
        ? {
            onCopy,
            onSave: (content: string, language: string) => onSaveCodeBlock(m.id, content, language)
          }
        : null,
    [m.id, onCopy, onSaveCodeBlock]
  )
  return (
    <div className={`msg-block ${m.role}`}>
      <div className={`msg ${m.role}`}>
        <div className="msg-role">{roleLabel(m.role, t)}</div>
        {m.role === 'assistant' ? (
          <div className="msg-content md">
            {/* The fixed RAG answers (no-context / reindex-needed) are persisted
                canonical English; the D-L4 display map translates them at render
                — exact match only, real model output passes through untouched. */}
            {/* #286: PERSISTED assistant turns only — the live streaming bubble below renders
                AssistantMarkdown with no provider, so a half-streamed fence has no Save button. */}
            <CodeBlockActionsContext.Provider value={codeBlockActions}>
              <AssistantMarkdown text={localizeServerCopy(t, m.content)} />
            </CodeBlockActionsContext.Provider>
          </div>
        ) : (
          <div className="msg-content">{m.content}</div>
        )}
        {m.citations && m.citations.length > 0 && (
          <>
            {/* The coverage mode tells the disclosure whether these are 1:1 inline-grounded
                excerpts (relevance, or a #643 labelled whole read) or whole-document LEAF
                PROVENANCE (tree/capped/extract) — FE-B / F11 renderer half. A NULL-coverage
                relevance turn passes undefined and renders byte-identically to before. */}
            <SourcesDisclosure
              citations={m.citations}
              mode={m.coverage?.mode}
              labelled={m.coverage?.labelledExcerpts}
              onReview={openReview}
              reviewDisabled={actionsDisabled}
              onOpenArticle={onOpenArticle}
              onSaveArticle={onSaveArticle}
            />
            {/* Honesty (whole-document-analysis §4.5/§5.2; full-doc-skills §3.3/D48): render the
                answer's PERSISTED coverage when we have it, else fall back to the relevance label —
                "based on the most relevant passages, NOT the whole document". A pre-migration row
                (NULL coverage) and a plain retrieval turn both hit the fallback, so the badge reads
                byte-identically to before; only a turn that recorded richer coverage shows it. */}
            <CoverageMeter
              coverage={m.coverage ?? { mode: 'relevance', chunksCovered: 0, chunksTotal: 0 }}
            />
          </>
        )}
        {/* Knowledge packs (#301 P4, findings M6/M7): what happened to each pack this ask
            selected. OUTSIDE the citations block on purpose — the turns that need it most are
            the ones with zero citation cards (a no-context answer whose every pack failed), and
            `SourcesDisclosure` only renders when the answer cited something. Assistant turns
            only; a turn with neither outcomes nor an archive citation renders nothing. */}
        {m.role === 'assistant' && (
          <PackOutcomesNotice
            outcomes={m.packOutcomes}
            hasArchiveCitation={m.citations?.some((c) => c.sourceKind === 'archive')}
          />
        )}
        {/* Per-message skill glyph (skills plan §15/DS16/§22-A5): a quiet, labelled marker on
            the answer a skill shaped — icon + word, never colour-only (guidelines §9). SKA-38
            (skills audit 2026-07-03, U6): gated off the PERSISTED `m.skillId`, not the JOIN-resolved
            title, so DELETING the skill no longer erases the glyph + undo from an already-stamped turn
            (a disabled skill already kept both). A stamped turn whose skill is gone (null title) shows
            a localized "(removed skill)" label. Decorative-but-labelled; never alarming. */}
        {m.role === 'assistant' && m.skillId && (() => {
          // Show the glyph title in the UI language when the skill carries a `localized` override;
          // fall back to the stamped canonical title; and to "(removed skill)" when the skill is gone.
          const removedLabel = t('chat.skill.removed')
          const fallback = m.skillTitle ?? removedLabel
          const glyphTitle = resolveSkillTitle ? resolveSkillTitle(m.skillId, fallback) : fallback
          // The "answer without it" undo re-runs the same question skill-free. S13c placed it on
          // AUTO-FIRED turns only; U3 (audit §4.3) extends it to EVERY skill-stamped last turn — a
          // per-turn pick is now as reversible as an auto-fire, so no skill-shaped answer is a
          // dead end. The glyph copy still distinguishes the two: an auto-fired turn reads "Answered
          // with <skill>" (the app chose it), an explicit pick keeps "Skill: <title>".
          const canUndo = isLast && onAnswerWithoutSkill != null
          // AUD-01: the undo re-answers the turn (regenerate), which DELETES this reply — and the
          // message foreign key cascades that delete through the reply's whole evidence review
          // (decisions, notes, links, export history), which no restore path can bring back. Main
          // refuses such a turn; the affordance must not invite the click either. DISABLED, never
          // hidden: the review chip renders in this same action row, so a vanishing button would
          // read as a bug — a dead button with a title that says why is the honest state.
          const blockedByReview = reviewSummary != null
          const undoButton = canUndo && (
            <button
              type="button"
              className="msg-skill-undo"
              onClick={onAnswerWithoutSkill}
              disabled={actionsDisabled || blockedByReview}
              title={blockedByReview ? t('chat.skill.answerWithoutBlockedByReview') : undefined}
            >
              {t('chat.skill.answerWithout')}
            </button>
          )
          if (m.autoFired) {
            return (
              <div
                className="msg-skill msg-skill-auto"
                title={t('chat.skill.autoFiredTitle', { title: glyphTitle })}
              >
                <Icon name="brain" className="msg-skill-icon" />
                <span>{t('chat.skill.autoFired', { title: glyphTitle })}</span>
                {undoButton}
              </div>
            )
          }
          return (
            <div className="msg-skill" title={t('chat.skill.usedTitle', { title: glyphTitle })}>
              <Icon name="brain" className="msg-skill-icon" />
              <span>{t('chat.skill.used', { title: glyphTitle })}</span>
              {undoButton}
            </div>
          )
        })()}
        {/* #80 (wave R80): the per-answer actionable skill OFFER — the answer's engine could not
            serve the asked shape, and one click re-runs the question WITH the offered skill (the
            click is the consent, S13b/D4 — nothing auto-fires). Rendered ONLY on the last
            assistant turn (SKA-37: it re-answers via regenerate, which acts on the last turn) —
            on older turns the answer's prose hint remains the pointer. DISABLED (never hidden,
            the AUD-01 posture the undo shares) when the reply carries an evidence review, because
            re-answering deletes the reply + cascades the review away. The classifier-sourced
            variant carries the "suggested by the local model" provenance label; the deterministic
            variant needs none (the answer's own hint explains it). Quiet vocabulary: the
            .msg-skill row + link-style action, never a loud button. */}
        {skillOffer &&
          onRunWithSkill &&
          (() => {
            // #132: click-time re-validation — the offer persists indefinitely, but the skill's state
            // can change between mint and click (disabled, deleted, folder gone). A stale offer
            // renders DISABLED with an honest tooltip (never hidden — the AUD-01 posture; and never a
            // silent skill-free re-answer — main refuses the stale id too, defense in depth).
            const offerAvailable = isSkillOfferAvailable ? isSkillOfferAvailable(skillOffer.installId) : true
            return (
              <div className="msg-skill msg-skill-offer">
                <Icon name="brain" className="msg-skill-icon" />
                <span>{t('chat.skill.offer.lead')}</span>
                {skillOffer.source === 'classifier' && (
                  <span className="msg-skill-offer-provenance">{t('chat.skill.offer.model')}</span>
                )}
                <button
                  type="button"
                  className="msg-skill-undo msg-skill-offer-run"
                  onClick={() => onRunWithSkill(skillOffer.installId)}
                  disabled={actionsDisabled || reviewSummary != null || !offerAvailable}
                  title={
                    !offerAvailable
                      ? t('chat.skill.offer.unavailable')
                      : reviewSummary != null
                        ? t('chat.skill.answerWithoutBlockedByReview')
                        : undefined
                  }
                >
                  {t('chat.skill.offer.run', {
                    title: resolveSkillTitle
                      ? resolveSkillTitle(skillOffer.installId, skillOffer.title)
                      : skillOffer.title
                  })}
                </button>
              </div>
            )
          })()}
        {/* Honest-signal truncation notice (§L0): a quiet, labelled line on an assistant reply that
            was cut off at a token ceiling (finish_reason 'length'). Never colour-only — a labelled
            marker with an explanatory tooltip (guidelines §9); role="note" so AT reads it as
            supplementary to the answer, not an alert. #498: the label names no cause (two different
            ceilings produce the same signal) and the tooltip follows `truncatedCause` — a row that
            carries none (written before #498) keeps the old context-window advice. #994: 'repeat' = the
            app stopped a whole-document answer that kept repeating itself. */}
        {m.role === 'assistant' && m.truncated && (
          <div
            className="msg-truncated"
            role="note"
            title={
              m.truncatedCause === 'cap'
                ? t('chat.truncated.hint.cap')
                : m.truncatedCause === 'repeat'
                  ? t('chat.truncated.hint.repeat')
                  : t('chat.truncated.hint.context')
            }
          >
            <span className="msg-truncated-glyph" aria-hidden="true">
              ⚠
            </span>
            <span>{t('chat.truncated.label')}</span>
          </div>
        )}
        {/* #600/#612: this reply ended before it was finished — the user stopped or switched the
            model, pressed Stop, or locked the workspace / quit. Its own label, not "Reply cut off"
            (that one means the model ran out of room); the same quiet labelled note, the cause in the
            tooltip. Lasting, so it reads the same after a reload and in every window. */}
        {m.role === 'assistant' && m.endedEarly != null && (
          <div className="msg-truncated" role="note" title={t(`chat.endedEarly.hint.${m.endedEarly}`)}>
            <span className="msg-truncated-glyph" aria-hidden="true">
              ⚠
            </span>
            <span>{t('chat.endedEarly.label')}</span>
          </div>
        )}
        {/* #600/#612: …or before it wrote anything — the question stays, and says why it has no answer. */}
        {m.role === 'user' && unanswered && m.endedEarly != null && (
          <div className="msg-truncated" role="note">
            <span className="msg-truncated-glyph" aria-hidden="true">
              ⚠
            </span>
            <span>{t(`chat.unanswered.${m.endedEarly}`)}</span>
          </div>
        )}
        {/* #290: the per-answer speed line — decode tokens/sec, time to first token, token count —
            in the same quiet metadata style as the skill glyph and the truncation note. Session-only:
            rendered only for an answer whose `chat:speed` payload arrived in this session, so older
            turns after a reload, a mock-runtime answer and an aborted answer show nothing. */}
        {m.role === 'assistant' && answerSpeed && (
          <div className="msg-speed" role="note" title={t('chat.speed.hint')}>
            {formatAnswerSpeed(answerSpeed, t, lang)}
          </div>
        )}
      </div>
      {m.role === 'assistant' && (
        <MessageActions
          onTryAgain={isLast ? onTryAgain : undefined}
          onCopy={() => onCopy(m.content)}
          onSave={onSave}
          onExportTable={
            m.hasResultTable && onExportTable ? () => onExportTable(m.id) : undefined
          }
          onReview={openReview}
          reviewStatus={reviewSummary?.status ?? null}
          reviewOutdated={reviewSummary?.outdated === true}
          disabled={actionsDisabled}
        />
      )}
      {/* #613: the question's counterpart of "Try again" — the same row and button style, but always
          shown, not on hover: it only exists while the question has no answer, and it is the way on
          (the crash copy says "Send your message again"). Main re-checks the id. */}
      {m.role === 'user' && onSendAgain && (
        <div className="msg-actions msg-actions-resend">
          <button type="button" className="msg-action" onClick={() => onSendAgain(m.id)}>
            ↺ {t('chat.actions.sendAgain')}
          </button>
        </div>
      )}
    </div>
  )
})

/**
 * The transcript summary marker (context-compaction plan §5.3, D-b): a subtle, non-bubble divider
 * where a compaction checkpoint sits — "⌄ Earlier messages summarized" — expandable to read the
 * checkpoint summary text. Makes the compression visible + auditable (the user confirms context was
 * condensed, not lost), matching the honest/local/nothing-hidden posture. The summary is the same
 * conversation-language text the model received; it never leaves the device. An aria-expanded
 * button (the SourcesDisclosure pattern), not a native <details>.
 */
function SummaryMarker({ summary, t }: { summary: string; t: I18n['t'] }): JSX.Element {
  const [open, setOpen] = useState(false)
  const id = useId()
  return (
    <div className="chat-summary-marker">
      <button
        type="button"
        className="chat-summary-marker-toggle"
        id={`${id}-toggle`}
        aria-expanded={open}
        aria-controls={`${id}-region`}
        title={t('chat.compaction.viewSummary')}
        onClick={() => setOpen((v) => !v)}
      >
        <span className="chat-summary-marker-chevron" aria-hidden="true">
          {open ? '⌄' : '›'}
        </span>
        <span className="chat-summary-marker-label">{t('chat.compaction.markerLabel')}</span>
      </button>
      {open && (
        <div
          className="chat-summary-marker-text"
          id={`${id}-region`}
          role="region"
          aria-labelledby={`${id}-toggle`}
        >
          {summary}
        </div>
      )}
    </div>
  )
}

/** Localized role chip; unknown roles (defensive) render as-is. */
function roleLabel(role: string, t: I18n['t']): string {
  return role === 'user' ? t('chat.role.user') : role === 'assistant' ? t('chat.role.assistant') : role
}

/**
 * Visually-hidden polite live region for streaming answers (audit L7). Screen readers
 * announce a live region by reading what is ADDED to it, so we feed it only newly
 * COMPLETED sentences as plain text — never the churning markdown buffer. This avoids
 * both failure modes of announcing the rendered markdown directly: re-reading the whole
 * answer on every flush, or (because the subtree remounts) going silent entirely.
 *
 * Sentence boundary = the position after the last terminator (. ! ? … or newline). We
 * announce the stable prefix up to that boundary and remember how far we've gone, so the
 * trailing in-progress sentence is held back until it completes. Markdown markup is
 * stripped to a rough plain-text form so the reader doesn't voice "asterisk asterisk".
 *
 * F6 (a11y fallback): a table-only or very long run-on answer can go a long time with no sentence
 * terminator, leaving the announcer silent until completion. When the UNANNOUNCED tail grows past a
 * soft cap with no new terminator, we flush up to the last WORD boundary instead, so AT still hears
 * progress. (A pure code block is stripped to ~nothing by stripMarkdown — voicing code punctuation
 * is worse a11y than silence — so that case stays intentionally quiet; the surrounding prose still
 * announces. Recorded as an accepted residual in known-limitations.)
 */
const ANNOUNCE_SOFT_CAP = 160

export function StreamAnnouncer({ text }: { text: string }): JSX.Element {
  const announcedLenRef = useRef(0)
  const [announced, setAnnounced] = useState('')

  useEffect(() => {
    // A new stream (text got shorter / reset) → start over.
    if (text.length < announcedLenRef.current) {
      announcedLenRef.current = 0
      setAnnounced('')
      return
    }
    // Prefer the last completed-sentence boundary; if none is new, fall back to a word boundary once
    // the unannounced tail is long enough (F6) so a terminator-less answer isn't held silent.
    let boundary = lastSentenceBoundary(text, announcedLenRef.current)
    if (boundary <= announcedLenRef.current) {
      if (text.length - announcedLenRef.current < ANNOUNCE_SOFT_CAP) return
      boundary = lastWordBoundary(text, announcedLenRef.current)
      if (boundary <= announcedLenRef.current) return
    }
    const next = stripMarkdown(text.slice(announcedLenRef.current, boundary)).trim()
    announcedLenRef.current = boundary
    if (next !== '') setAnnounced(next)
  }, [text])

  return (
    // No aria-atomic (F23): this is an ADDITIVE log — we feed it only the newest completed
    // sentence, so the AT should read what was ADDED. aria-atomic="true" forces a re-read of the
    // ENTIRE region on every change (re-announcing prior sentences; double-speak on fast
    // boundaries), defeating the sentence-slicing above. role="log" defaults to atomic=false.
    <div className="sr-only" role="log" aria-live="polite">
      {announced}
    </div>
  )
}

/**
 * F6 fallback: index just past the last whitespace in the unannounced tail (so we announce only
 * complete words and hold back the trailing partial). A single unbroken token past the cap returns
 * `text.length` — flush it whole rather than stall the announcer forever.
 */
function lastWordBoundary(text: string, from: number): number {
  for (let i = text.length - 1; i > from; i--) {
    if (/\s/.test(text[i]!)) return i + 1
  }
  return text.length
}

/**
 * Index just past the last sentence terminator (. ! ? … or newline); 0 if none at/after `from`.
 *
 * Streaming hot path (full audit 2026-07-10 PF-1): this runs on every ~40 ms stream flush,
 * so it scans only from the previous announce point instead of the whole growing buffer (which
 * made a long answer O(n²)). That is safe by definition: a NEW sentence boundary can only appear
 * at/after the previous announce point — the effect above ignores any boundary at or before it
 * (`boundary <= announcedLenRef.current` falls through to the F6 fallback either way), so matches
 * entirely before `from` never change the outcome. To stay byte-identical with a whole-buffer
 * scan, the tail scan must NOT start exactly at `from`: a match can span the announce point
 * (`\n` is both whitespace — a valid F6 word boundary — and a terminator, and the closing-quote
 * run extends a match), and text appended later can retroactively grow a match whose
 * end-of-string lookahead used to hold. Every character of such a spanning match before `from`
 * is in the terminator/closing-quote class, so backing up over that contiguous class run lands
 * at (or before) the match start, where the scanners provably re-synchronize: no match crosses a
 * non-class character.
 */
function lastSentenceBoundary(text: string, from: number): number {
  let start = from
  while (start > 0 && /[.!?…\n"')\]]/.test(text[start - 1]!)) start--
  // Match a terminator optionally followed by closing quotes/brackets then whitespace
  // or end-of-string — the last such match is our boundary.
  const re = /[.!?…\n]+["')\]]*(?=\s|$)/g
  re.lastIndex = start
  let last = 0
  let m: RegExpExecArray | null
  while ((m = re.exec(text)) !== null) last = m.index + m[0].length
  return last
}

/** Rough markdown → plain text for the announcer (not the visible render). */
function stripMarkdown(s: string): string {
  return s
    .replace(/`{1,3}[^`]*`{1,3}/g, ' ') // inline/code spans
    .replace(/[*_~`#>]+/g, '') // emphasis / heading / quote / strike markers
    .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1') // links/images → their text
    .replace(/^\s*[-+*]\s+/gm, '') // list bullets
    .replace(/\s+/g, ' ')
}