Skip to content

AI, fully local on your computer.

30.4 KB
Raw Blame
import {
  Suspense,
  lazy,
  useEffect,
  useRef,
  useState,
  type ComponentType,
  type LazyExoticComponent
} from 'react'
import { HomeScreen } from './screens/HomeScreen'
import { ChatScreen } from './screens/ChatScreen'
import { WorkspaceGate } from './screens/WorkspaceGate'

// Route-level code split (full-audit 2026-07-10 PF-6). These seven screens load as separate
// async chunks on first navigation, keeping their code (and their exclusive deps — e.g.
// pdfjs on Documents) out of the init bundle the modest-CPU target must parse before first
// paint. Deliberately EAGER: the workspace gate + HomeScreen (the first frame) and
// ChatScreen (the primary surface — first-run lands there, and its shared chat components
// are used by several screens so splitting it would buy little). The i18n catalogs stay in
// the init bundle by design — splitting them is a separate decision.
// Each lazy screen suspends to the quiet fallback below, inside the existing per-screen
// ErrorBoundary. SH-5 (#149): React caches a lazy factory's REJECTION for the session, so
// the boundary's "Try again" (and navigate-away-and-back) can never recover a failed chunk
// load on its own — the factory itself retries the import once, clearing the transient
// media-hiccup class (a portable drive briefly stalling, an AV scan). A chunk that fails
// BOTH attempts stays failed until the window reloads — the boundary fallback says so.

/** Lazy screen factory with one in-factory retry (SH-5) — see the comment above. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- React.lazy's own constraint
function lazyScreen<T extends ComponentType<any>>(
  importer: () => Promise<{ default: T }>
): LazyExoticComponent<T> {
  return lazy(async () => {
    try {
      return await importer()
    } catch {
      return await importer() // one fresh disk attempt before the boundary sees it
    }
  })
}

const DocumentsScreen = lazyScreen(() =>
  import('./screens/DocumentsScreen').then((m) => ({ default: m.DocumentsScreen }))
)
const TranslateScreen = lazyScreen(() =>
  import('./screens/TranslateScreen').then((m) => ({ default: m.TranslateScreen }))
)
const ImagesScreen = lazyScreen(() =>
  import('./screens/ImagesScreen').then((m) => ({ default: m.ImagesScreen }))
)
const ModelsScreen = lazyScreen(() =>
  import('./screens/ModelsScreen').then((m) => ({ default: m.ModelsScreen }))
)
const SettingsScreen = lazyScreen(() =>
  import('./screens/SettingsScreen').then((m) => ({ default: m.SettingsScreen }))
)
const PerformanceScreen = lazyScreen(() =>
  import('./screens/PerformanceScreen').then((m) => ({ default: m.PerformanceScreen }))
)
// Evidence-review workspace (EP-1 plan §7.1): lazy like the other non-first-frame screens.
// No nav-rail entry — reachable ONLY via the openReview handoff below.
const ReviewScreen = lazyScreen(() =>
  import('./screens/ReviewScreen').then((m) => ({ default: m.ReviewScreen }))
)
import {
  Banner,
  BrandMark,
  Button,
  ErrorBanner,
  ErrorBoundary,
  Icon,
  LocalIndicator,
  ToastProvider,
  type IconName
} from './components'
import { setThemeSetting } from './theme'
import { runAndSurface } from './lib/errors'
import { useEngineProblems } from './lib/useEngineProblems'
import { purgeSessionStores } from './lib/lockPurge'
import { flushReviewSessionBeforeLock, type ReviewHandoffTarget } from './lib/reviewSession'
import { I18nProvider, useT, type I18n } from './i18n'
import { resolveNavTarget, type ModelsFocus, type ScreenId, type SettingsTab } from './navigation'
import type { MessageKey } from '@shared/i18n'
import type { WorkspaceStateInfo } from '@shared/types'

interface NavItem {
  id: ScreenId
  labelKey: MessageKey
  icon: IconName
}

// Information architecture (design-guidelines §2, rail rework 2026-09-05): three groups.
//   work    = Chat · Documents · Translate · Images   (the everyday task surfaces)
//   machine = AI Model · Performance                  (what runs, and how well it runs)
//   utility = Settings                                (Privacy, Skills, Diagnostics as tabs)
// Home has no rail item: the brand mark above the groups IS the Home button (it already
// navigated home since #47; a logo atop a nav column reads as "go home", and two controls
// for one destination crowded the rail). It carries the lit state when Home is open.
// Skills moved back into Settings as a tab: the composer's skill picker in Chat is the
// everyday entry, so a rail slot for the library was redundant.
const NAV_WORK: NavItem[] = [
  { id: 'chat', labelKey: 'nav.chat', icon: 'chat' },
  { id: 'documents', labelKey: 'nav.documents', icon: 'file' },
  { id: 'translate', labelKey: 'nav.translate', icon: 'translate' },
  { id: 'images', labelKey: 'nav.images', icon: 'image' }
]

const NAV_MACHINE: NavItem[] = [
  { id: 'models', labelKey: 'nav.models', icon: 'brain' },
  { id: 'performance', labelKey: 'nav.performance', icon: 'gauge' }
]

const NAV_BOTTOM: NavItem[] = [{ id: 'settings', labelKey: 'nav.settings', icon: 'settings' }]

/** How often the rail indicator re-reads whether the local API is listening. Deliberately
 *  slow: the state changes at most a few times a session, and the read is an in-memory
 *  status snapshot — this exists so the indicator self-corrects, not to be timely. */
const LOCAL_API_INDICATOR_POLL_MS = 10_000

export function App(): JSX.Element {
  // The language provider wraps EVERYTHING, including the pre-unlock gate (which
  // resolves from the localStorage mirror / OS locale — i18n record §3.2).
  return (
    <I18nProvider>
      <AppShell />
    </I18nProvider>
  )
}

function AppShell(): JSX.Element {
  const [screen, setScreen] = useState<ScreenId>('home')
  // Which Settings tab is open: driven by navigate() so virtual targets
  // like 'settings:privacy' (and the legacy 'privacy' alias) land on the right tab.
  const [settingsTab, setSettingsTab] = useState<SettingsTab>('general')
  // Which composer mode the Chat screen opens with. Home's "Ask my documents" jumps
  // straight into a document-Q&A chat; plain "Chat" navigation resets to chat mode.
  const [chatMode, setChatMode] = useState<'chat' | 'documents'>('chat')
  // "Ask selected documents" handoff: the Documents screen's selection,
  // applied to the next documents conversation the Chat screen creates.
  const [chatScope, setChatScope] = useState<string[] | null>(null)
  // "Ask this pack" handoff (§11.16): the knowledge pack the next documents conversation
  // answers from alone. Same one-shot discipline as `chatScope`; the two never coexist.
  const [chatPackScope, setChatPackScope] = useState<string[] | null>(null)
  // Which mode the Documents screen opens with (§11.16): plain 'documents' navigation opens the
  // user's files; the 'documents:packs' deep link (Home's "Add packs", the chat picker's
  // "Add packs…") opens the knowledge-pack panel. The screen's own header switch takes over
  // once mounted.
  const [documentsMode, setDocumentsMode] = useState<'documents' | 'packs'>('documents')
  // Which library the AI Model screen opens on (#527, #539): a 'models:voice' / 'models:images' /
  // 'models:translation' deep link opens Browse filtered to that missing model; plain 'models'
  // navigation opens the screen's own default. Read once at mount, like `documentsMode`.
  const [modelsFocus, setModelsFocus] = useState<ModelsFocus | null>(null)
  // EP-1 P5 (plan §10): the conversation the Chat screen should open with — set ONLY by the
  // review screen's "Back to chat" so it returns to the ORIGINATING conversation. One-shot
  // by construction: every normal chat navigation (navigate below) clears it.
  const [chatConversation, setChatConversation] = useState<string | null>(null)
  // #573: the conversation a chat's "Go to Documents" came from (a failed attachment to make
  // searchable there). One-shot like `chatConversation`: set only by `openDocumentsFromChat`,
  // cleared by every other navigation, so Documents offers "Back to chat" for that trip alone.
  const [documentsReturn, setDocumentsReturn] = useState<string | null>(null)
  // Evidence-review handoff (EP-1 plan §7.1 — the chatScope idiom): which review (or
  // message, for a first review) the review screen opens. The screen is meaningless
  // without it, which is why plain navigate('review') resolves to home (navigation.ts).
  const [reviewHandoff, setReviewHandoff] = useState<ReviewHandoffTarget | null>(null)
  // The workspace lifecycle gate. Null = still loading; not 'unlocked' = show
  // the create-password / unlock gate before the normal app shell.
  const [workspace, setWorkspace] = useState<WorkspaceStateInfo | null>(null)
  // Live EFFECTIVE offline state for the single rail-foot privacy indicator (§1.2/§12.1
  // #2). `getPolicy().offlineMode` already folds the drive policy AND the network toggle,
  // so a policy that forces downloads off reads "Offline" even with the toggle on.
  // Re-checked when the Settings screen is visited (the toggle may have changed). Policy
  // detail ("disabled by policy" vs. off by choice) lives on the Privacy & data tab the
  // indicator opens.
  const [offline, setOffline] = useState(true)
  // Whether the opt-in local API endpoint is LISTENING right now — read from the same
  // post-unlock/navigation refresh as the policy, so the rail indicator can state it
  // instead of implying the model is reachable by nothing but this app (D1).
  const [localApiOn, setLocalApiOn] = useState(false)
  // Set when the backend never came up (getWorkspaceState rejected). Faking 'unlocked'
  // here would render the full shell with every screen surfacing raw IPC errors. #1024: a start that threw answers
  // `start_failed` instead, which the gate shows; this stays for a failure state that could not be registered.
  const [fatalError, setFatalError] = useState<string | null>(null)
  // One-line, dismissible runtime notice: currently the GPU crash auto-fallback's
  // friendly "switched to compatibility mode" message (spec §11.4 tone).
  // #530: `target` says where its button leads — absent: Diagnostics ("Details"); 'models': the
  // AI Model screen, where the engine banner names what to install.
  const [notice, setNotice] = useState<{ message: string; target?: 'models' } | null>(null)
  // full-audit 2026-07-11 CODE-26: a FAILED "Lock now" (main restored the unlocked vault,
  // CODE-1a) used to be an unhandled rejection — the shell silently stayed unlocked on the
  // most security-sensitive control. Main's friendly copy is surfaced here as a dismissible
  // error banner; the session stores are deliberately NOT purged and the shell stays usable
  // (the workspace really is still unlocked), so the user can free space and retry.
  const [lockError, setLockError] = useState<string | null>(null)
  const { t, applyLanguageSetting } = useT()

  useEffect(() => {
    const unsubscribe = window.api?.onRuntimeNotice?.((message, target) => setNotice({ message, target }))
    return () => unsubscribe?.()
  }, [])

  // #530: the engine notice ("can't run … replies are simulated") is stale the moment the chat
  // engine's verdict goes away (Check again healed it) — drop it then. Only on that TRANSITION:
  // the notice can arrive before this hook's first re-read lands, and an absent verdict at that
  // point must not clear it.
  const chatEngineBlocked = useEngineProblems()?.some((p) => p.family === 'llama_cpp') ?? null
  const wasChatEngineBlocked = useRef(false)
  useEffect(() => {
    if (chatEngineBlocked === true) wasChatEngineBlocked.current = true
    else if (chatEngineBlocked === false && wasChatEngineBlocked.current) {
      wasChatEngineBlocked.current = false
      setNotice((current) => (current?.target === 'models' ? null : current))
    }
  }, [chatEngineBlocked])

  useEffect(() => {
    let active = true
    window.api
      ?.getWorkspaceState()
      .then((s) => active && setWorkspace(s))
      .catch((e) => active && setFatalError(String(e instanceof Error ? e.message : e)))
    return () => {
      active = false
    }
  }, [])

  const unlocked = workspace?.state === 'unlocked'

  // Timing mark for opt-in measurement runs (main enforces the allowlist and no-ops
  // unless HILBERTRAUM_PERF_LOG=1): the workspace gate — the password prompt — became
  // visible. This is the end of the user-felt "launch to password prompt" span.
  // #1024: a start that failed shows the gate's failure card, which has no password prompt.
  const gateVisible = workspace !== null && !unlocked && workspace.state !== 'start_failed'
  useEffect(() => {
    if (gateVisible) window.api?.perfMark('gate_visible')
  }, [gateVisible])

  // The rail indicator must never claim the opposite of reality (D1), and the two events
  // that change this state are both invisible to a navigation-scoped read: the post-unlock
  // start is fire-and-forget, and the Settings toggle happens while the user stays put on
  // the Settings screen. So this one re-reads on a slow interval (and on window focus) —
  // enough to be self-correcting, far too rare to be a poll worth optimizing.
  useEffect(() => {
    if (!unlocked) {
      setLocalApiOn(false)
      return
    }
    let active = true
    const read = (): void => {
      window.api
        ?.getAppStatus()
        .then((st) => active && setLocalApiOn(st.localApi?.running === true))
        .catch(() => active && setLocalApiOn(false))
    }
    read()
    const onFocus = (): void => read()
    window.addEventListener('focus', onFocus)
    const timer = setInterval(read, LOCAL_API_INDICATOR_POLL_MS)
    return () => {
      active = false
      window.removeEventListener('focus', onFocus)
      clearInterval(timer)
    }
  }, [unlocked])

  // #1002 (S-4): main locks on its own at an OS session end and tells no window (there is no lock event). A window
  // that outlived it (a macOS shutdown another app cancelled) kept the unlocked shell, decrypted content on screen and
  // every call failing. So while the shell shows an unlocked workspace it re-reads the state when the window gains
  // focus, when it becomes visible again, and on a pointer press (a window that never lost focus gets no `focus`
  // event), one read at a time (a burst of clicks makes one call), and on `locked` ends the session here as Lock now
  // does. Only `locked`: a `plaintext_dev` workspace whose database closed reads `uninitialized` and has no gate to
  // show; a failed read changes nothing.
  useEffect(() => {
    if (!unlocked) return
    let active = true
    let reading = false
    const recheck = (): void => {
      if (reading) return
      reading = true
      Promise.resolve()
        .then(() => window.api.getWorkspaceState())
        .then((s) => {
          if (active && s.state === 'locked') showLocked(s)
        })
        .catch(() => {})
        .finally(() => {
          reading = false
        })
    }
    const onVisible = (): void => {
      if (document.visibilityState === 'visible') recheck()
    }
    window.addEventListener('focus', recheck)
    window.addEventListener('pointerdown', recheck, true)
    document.addEventListener('visibilitychange', onVisible)
    return () => {
      active = false
      window.removeEventListener('focus', recheck)
      window.removeEventListener('pointerdown', recheck, true)
      document.removeEventListener('visibilitychange', onVisible)
    }
  }, [unlocked])

  useEffect(() => {
    if (!unlocked) return
    let active = true
    window.api
      ?.getPolicy()
      .then((p) => active && setOffline(p.offlineMode))
      .catch(() => active && setOffline(true))
    // Apply the persisted Appearance + Language settings. Settings are only readable
    // post-unlock; re-checked alongside the policy so a Settings-screen change made
    // this session is also picked up after navigation. applyLanguageSetting also
    // refreshes <html lang> and the pre-unlock localStorage mirror.
    window.api
      ?.getSettings()
      .then((s) => {
        if (!active) return
        setThemeSetting(s.theme)
        applyLanguageSetting(s.uiLanguage)
      })
      .catch(() => {})
    return () => {
      active = false
    }
  }, [screen, unlocked, applyLanguageSetting])

  // Central navigation: screens hand any target (real, virtual, or legacy alias) to
  // resolveNavTarget — see navigation.ts for the table.
  function navigate(target: string): void {
    const next = resolveNavTarget(target)
    setDocumentsReturn(null)
    if (next.chatMode) {
      setChatMode(next.chatMode)
      setChatScope(null)
      setChatPackScope(null)
      setChatConversation(null)
    }
    if (next.settingsTab) setSettingsTab(next.settingsTab)
    if (next.documentsMode) setDocumentsMode(next.documentsMode)
    if (next.screen === 'models') setModelsFocus(next.modelsFocus ?? null)
    setScreen(next.screen)
  }

  // Documents screen → "Ask these documents" (spec §10.4): open Chat in
  // documents mode with the selection as the next conversation's retrieval scope.
  // P5 review FIX-1: this path mounts chat WITHOUT going through navigate(), so it must
  // clear the review back-handoff itself — a surviving `chatConversation` would make the
  // mount re-attach an OLD conversation and stomp the just-set documents mode (pinned by
  // an App-level test). The only setScreen('chat') paths are navigate() and this one.
  function askSelectedDocuments(documentIds: string[]): void {
    setDocumentsReturn(null)
    setChatMode('documents')
    setChatScope(documentIds.length > 0 ? documentIds : null)
    setChatPackScope(null)
    setChatConversation(null)
    setScreen('chat')
  }

  // Documents screen (packs mode) → "Ask this pack" (§11.16): open Chat in documents mode with
  // that pack as the next conversation's ONLY source. Same discipline as askSelectedDocuments —
  // it bypasses navigate(), so it clears the review back-handoff and the document scope itself.
  function askPack(packId: string): void {
    setDocumentsReturn(null)
    setChatMode('documents')
    setChatScope(null)
    setChatPackScope([packId])
    setChatConversation(null)
    setScreen('chat')
  }

  // Chat → evidence-review workspace (EP-1 plan §7.1): the ONLY way onto the review
  // screen. Back navigation is the screen's own "Back to chat" → backToConversation below.
  function openReview(target: ReviewHandoffTarget): void {
    setReviewHandoff(target)
    setScreen('review')
  }

  // Review → chat (EP-1 P5, plan §10): back restores the review's ORIGINATING conversation
  // as the active chat instead of landing on chat home (the named P2 UX debt). navigate()
  // runs FIRST (it clears the slot for plain chat navigations), then the handoff is set —
  // both land in the same React batch, so the Chat screen mounts with the id in place.
  function backToConversation(conversationId: string): void {
    navigate('chat')
    setChatConversation(conversationId)
  }

  // Chat → Documents from a failed attachment's pointer (#573): navigate() runs FIRST (it clears
  // the slot), then the slot is set — one React batch, so Documents mounts with it in place.
  function openDocumentsFromChat(conversationId: string): void {
    navigate('documents')
    setDocumentsReturn(conversationId)
  }

  async function lockNow(): Promise<void> {
    setLockError(null)
    // EP-1 plan §7.5: flush pending review auto-save edits BEFORE the vault re-encrypts —
    // after lockWorkspace the write would be refused. Best-effort: a failed flush must
    // never block the lock (the user's explicit security action wins) — nor a hung one: the
    // flush waits for a running bulk sweep, so it gives up after a bound (#837 review round 5).
    await flushReviewSessionBeforeLock()
    const next = await window.api.lockWorkspace()
    showLocked(next)
  }

  // The real lock seam (TA-2 / H3): main has aborted the jobs + re-encrypted the vault, so drop the resident
  // source/translation/image content from the module-level session stores in lockstep. Screens can't do this
  // themselves — lock unmounts every screen (the shell swaps to WorkspaceGate below), so a screen-effect purge would
  // never observe the lock. Lock now's end, and (#1002) the focus re-read below when main locked on its own.
  function showLocked(next: WorkspaceStateInfo): void {
    purgeSessionStores()
    // A "could not lock" banner from an earlier Lock now must not come back after the next unlock (#1002: main may
    // have locked on its own since).
    setLockError(null)
    setWorkspace(next)
    setScreen('home')
    setDocumentsReturn(null)
    // The locked gate cannot read settings — back to following the OS theme.
    // (The LANGUAGE deliberately stays: the gate follows the localStorage mirror.)
    setThemeSetting('system')
  }

  if (fatalError) {
    // The last resort: main's state could not be read at all. Since #1024 a back-end start that throws answers with the
    // gate's failure card instead (`start_failed`), so this shows only when that failure state could not be registered
    // either. It no longer points at `logs/app.log`: an encrypted workspace writes no log to the drive before an unlock.
    return (
      <div className="gate-shell">
        <div className="card">
          <h2>{t('app.fatal.title')}</h2>
          <p className="hint">{t('gate.startFailed.other')}</p>
          <p className="hint">{t('gate.startFailed.help')}</p>
          <p className="hint">
            <code>{fatalError}</code>
          </p>
        </div>
      </div>
    )
  }
  if (workspace && !unlocked) {
    return (
      <WorkspaceGate
        state={workspace}
        onUnlocked={(next, landOn) => {
          setWorkspace(next)
          // First-run create ends on the teaching Chat empty state (or the screen the
          // optional starter step picked); a plain unlock keeps the current screen.
          if (landOn) navigate(landOn)
        }}
        // #955 item 3: a create refused because a workspace is on the drive after all: show the gate for main's new
        // state (its unlock form). Nothing opened, so no landing.
        onStateChange={setWorkspace}
      />
    )
  }
  if (!workspace) {
    return (
      <div className="gate-shell">
        <p className="hint">{t('app.loadingWorkspace')}</p>
      </div>
    )
  }

  function navButton(item: NavItem): JSX.Element {
    const label = t(item.labelKey)
    const active = screen === item.id
    return (
      <li key={item.id}>
        <button
          className={`nav-item ${active ? 'active' : ''}`}
          // Icon + short label make a quiet rail; the label can wrap/clip on narrow
          // widths, so the title carries the full destination name for a tooltip too.
          title={label}
          aria-current={active ? 'page' : undefined}
          onClick={() => navigate(item.id)}
        >
          <Icon name={item.icon} className="nav-icon" />
          <span className="nav-label">{label}</span>
        </button>
      </li>
    )
  }

  return (
    // The single toast host: screens fire "Saved"-style confirmations via
    // useToast(); the polite live region lives once, here.
    <ToastProvider>
    <div className="app-shell">
      <nav className="sidebar" aria-label={t('nav.aria')}>
        {/* Issue #47: the lockup heads a column of clickable rail items, and decades of
            convention read a logo in that position as "go Home", so it must not be the one
            dead click on the rail. Since the 2026-09-05 rail rework it is THE Home control
            (the labelled Home item is gone), so it carries both the semantic aria-current
            and the visual lit state the other rail items use. The accessible name and the
            tooltip fold the wordmark and the destination. */}
        <button
          type="button"
          className={`brand ${screen === 'home' ? 'active' : ''}`}
          title={`HilbertRaum — ${t('nav.home')}`}
          aria-label={`HilbertRaum — ${t('nav.home')}`}
          aria-current={screen === 'home' ? 'page' : undefined}
          onClick={() => navigate('home')}
        >
          <BrandMark size={24} />
        </button>
        <ul className="nav-list">{NAV_WORK.map(navButton)}</ul>
        <ul className="nav-list nav-group">{NAV_MACHINE.map(navButton)}</ul>
        <ul className="nav-list nav-bottom">{NAV_BOTTOM.map(navButton)}</ul>
        {workspace.mode === 'encrypted' && (
          <button
            type="button"
            className="lock-btn"
            title={t('app.lockNowTitle')}
            aria-label={t('app.lockNow')}
            // CODE-26: surfaced, never fire-and-forget — a rejected lock lands on the banner.
            onClick={() => void runAndSurface(lockNow, setLockError)}
          >
            <Icon name="lock" className="nav-icon" />
            <span className="nav-label">{t('app.lockNow')}</span>
          </button>
        )}
        {/* The single app-wide privacy signal (§1.2/§7/§12.1 #2): one quiet, honest
            indicator at the foot of the rail, on EVERY screen. `offline` is the effective
            policy state owned by App, so a drive policy that forces downloads off reads
            "Offline" even with the toggle on. */}
        <LocalIndicator
          variant="sidebar"
          offline={offline}
          localApiOn={localApiOn}
          onNavigate={navigate}
          t={t}
        />
      </nav>

      <main className="content">
        {/* CODE-26: the failed-lock notice — main's friendly persist-canonical copy
            (already localized main-side), next to the content the user keeps working in.
            SH-2 (#145): via the always-mounted ErrorBanner so AT announces the FIRST failure
            (a freshly inserted alert element is missed by many screen readers — M-U1). */}
        <ErrorBanner message={lockError} t={t} onDismiss={() => setLockError(null)} />
        {notice && (
          <Banner
            tone="info"
            t={t}
            onDismiss={() => setNotice(null)}
            action={
              notice.target === 'models' ? (
                <Button size="sm" onClick={() => navigate('models')}>
                  {t('app.noticeGoToModels')}
                </Button>
              ) : (
                <Button size="sm" onClick={() => navigate('settings:diagnostics')}>
                  {t('app.noticeDetails')}
                </Button>
              )
            }
          >
            {notice.message}
          </Banner>
        )}
        {/* Per-screen error boundary (audit FE-1). KEYED by `screen`, so navigating to any
            other destination re-mounts the subtree and clears a captured error — the nav rail
            above lives OUTSIDE the boundary, so a render throw never traps the user. The
            fallback also offers an in-place retry. Logging is local-only (ErrorBoundary). */}
        <ErrorBoundary
          key={screen}
          fallback={(reset) => (
            // onHome resets the boundary AND navigates: if HOME itself threw, navigate('home') is
            // a same-value setScreen no-op (no key change → no re-mount), so reset() is what
            // actually clears the error; on any other screen the navigate changes the key and
            // reset() is harmless. Without the reset, "Go to Home" would be a dead no-op when the
            // throwing screen is Home (the default screen).
            <ScreenErrorFallback
              t={t}
              onRetry={reset}
              onHome={() => {
                reset()
                navigate('home')
              }}
            />
          )}
        >
          {/* The suspense point for the lazy screens (PF-6): a quiet, theme-correct hint in
              the same `.screen` container while a chunk loads off the local disk (a few ms,
              once per screen per session — React caches the resolved module). No spinner:
              guidelines §6 bans unlabeled spinners, and the text idiom matches
              app.loadingWorkspace. */}
          <Suspense
            fallback={
              <div className="screen" aria-busy="true">
                <p className="hint">{t('app.loadingScreen')}</p>
              </div>
            }
          >
            {screen === 'home' && <HomeScreen onNavigate={navigate} />}
            {screen === 'chat' && (
              <ChatScreen
                onNavigate={navigate}
                initialMode={chatMode}
                initialScopeDocumentIds={chatScope}
                initialScopePackIds={chatPackScope}
                initialConversationId={chatConversation}
                onOpenReview={openReview}
                onOpenDocumentsFrom={openDocumentsFromChat}
              />
            )}
            {/* Review renders ONLY with a handoff target (guaranteed by openReview being
                the sole path here; the guard keeps a future misroute blank-safe). */}
            {screen === 'review' && reviewHandoff && (
              <ReviewScreen
                handoff={reviewHandoff}
                onNavigate={navigate}
                onBackToConversation={backToConversation}
              />
            )}
            {screen === 'documents' && (
              <DocumentsScreen
                onAskSelected={askSelectedDocuments}
                onAskPack={askPack}
                onNavigate={navigate}
                initialMode={documentsMode}
                onBackToConversation={
                  documentsReturn ? () => backToConversation(documentsReturn) : undefined
                }
              />
            )}
            {screen === 'translate' && <TranslateScreen onNavigate={navigate} />}
            {screen === 'images' && <ImagesScreen onNavigate={navigate} />}
            {screen === 'models' && <ModelsScreen focus={modelsFocus} onNavigate={navigate} />}
            {screen === 'performance' && <PerformanceScreen onNavigate={navigate} />}
            {screen === 'settings' && (
              <SettingsScreen tab={settingsTab} onTabChange={setSettingsTab} />
            )}
          </Suspense>
        </ErrorBoundary>
      </main>
    </div>
    </ToastProvider>
  )
}

// The localized per-screen fallback (audit FE-1). role="alert" so the contained failure is
// announced; the calm copy (spec §11.4) reassures that nothing was lost, with an in-place
// retry and an escape to Home.
function ScreenErrorFallback({
  t,
  onRetry,
  onHome
}: {
  t: I18n['t']
  onRetry: () => void
  onHome: () => void
}): JSX.Element {
  return (
    <div className="screen" role="alert">
      <div className="card">
        <h2>{t('errorBoundary.title')}</h2>
        <p className="hint">{t('errorBoundary.body')}</p>
        <div className="actions">
          <Button variant="primary" onClick={onRetry}>
            {t('errorBoundary.retry')}
          </Button>
          <Button onClick={onHome}>{t('errorBoundary.home')}</Button>
        </div>
      </div>
    </div>
  )
}