Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

tech(M7): Boot-Chunk 2016 kB -> 711 kB, und 11 Schein-Splits sind jetzt echte

David140574bbe49f
diff --git a/src/api/agents/__tests__/sub-agent.test.ts b/src/api/agents/__tests__/sub-agent.test.ts
index c52fd4b3..78e092b6 100644
--- a/src/api/agents/__tests__/sub-agent.test.ts
+++ b/src/api/agents/__tests__/sub-agent.test.ts
@@ -48,7 +48,13 @@ vi.mock('../../providers', () => ({
}),
}))
-vi.mock('../../mcp', () => ({
+// M7 / Audit W-T2: sub-agent.ts holt `toolRegistry` seit der Auflösung der
+// INEFFECTIVE_DYNAMIC_IMPORT-Warnung direkt aus `mcp/tool-registry` statt aus
+// der Tonne `mcp` (der alte `await import('../mcp')` konnte nie splitten und
+// war nur da, um einen Modulzyklus zu brechen). Der Stub zeigt deshalb jetzt
+// auf dieselbe Naht unter ihrem echten Namen — Inhalt und Erwartungen dieses
+// Tests sind unverändert.
+vi.mock('../../mcp/tool-registry', () => ({
toolRegistry: {
getAll: () => [SHELL_DEF],
resolveExecutable: (name: string) => (name === 'shell_execute' ? SHELL_DEF : undefined),
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.ts
index a7658ab7..12af5dea 100644
--- a/src/api/agents/sub-agent.ts
+++ b/src/api/agents/sub-agent.ts
@@ -12,6 +12,21 @@
*/
import { settleThinking } from '../../lib/thinking-stripper'
+// M7 / Audit W-T2: hier stand zweimal `await import('../mcp')`. Gesplittet hat
+// das nie — die Tonne mcp/index.ts hängt über useAgentChat, useCodex und
+// api/tool-registry.ts ohnehin statisch im Graph, also meldete Rolldown
+// INEFFECTIVE_DYNAMIC_IMPORT. Der import() war auch nie fürs Splitten da,
+// sondern um den Zyklus mcp/index → builtin-tools → sub-agent → mcp/index zu
+// brechen.
+//
+// Die ehrliche Auflösung ist ein statischer Import auf das Modul, das hier
+// wirklich gebraucht wird, statt auf die Tonne: `mcp/tool-registry` hält den
+// Singleton und importiert selbst nichts aus diesem Cluster (seit die
+// retired-Kante invertiert ist), der Zyklus entsteht also gar nicht erst.
+// Die Registrierung der Builtins ist dabei garantiert schon gelaufen: beide
+// Einstiegspunkte dieser Datei hängen am `delegate_task`-Executor, den erst
+// registerBuiltinTools() verdrahtet.
+import { toolRegistry } from '../mcp/tool-registry'
import type { MCPToolDefinition } from '../mcp/types'
import type { AgentToolCall } from '../../types/agent-mode'
import type { ApprovalEntry } from '../../lib/approval-queue'
@@ -180,8 +195,7 @@ export async function buildSubAgentGates(run?: AgentRunContext): Promise<SubAgen
const abortSignal = run?.abortSignal
const refusals = new Map<string, string>()
- const [{ toolRegistry }, { usePermissionStore }, approvals] = await Promise.all([
- import('../mcp'),
+ const [{ usePermissionStore }, approvals] = await Promise.all([
import('../../stores/permissionStore'),
import('../../lib/approval-queue'),
])
@@ -281,7 +295,6 @@ export async function defaultSubAgentRunner(
): Promise<string> {
const { useModelStore } = await import('../../stores/modelStore')
const { getProviderForModel } = await import('../providers')
- const { toolRegistry } = await import('../mcp')
const activeModel = useModelStore.getState().activeModel
if (!activeModel) return 'Error: No active model configured.'
const { provider, modelId } = getProviderForModel(activeModel)
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index d25a7105..877d02af 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -1388,6 +1388,13 @@ export function registerBuiltinTools(registry: ToolRegistry) {
registry.registerBuiltin(tool, executor)
}
}
+ // M7 / Audit W-T2: der Redirect für zurückgezogene Namen wird hier ANGEMELDET,
+ // statt dass execute() ihn sich per `await import('./builtin-tools')` zurück-
+ // holt. Der alte Rück-Import konnte nie in einen eigenen Chunk splitten
+ // (mcp/index.ts lädt dieses Modul ohnehin statisch) und war damit genau das
+ // Muster, das M7 anprangert. Die Richtung stimmt jetzt: die konkreten Tools
+ // kennen die Registry, nicht umgekehrt.
+ registry.setRetiredRunner(runRetiredTool)
}
// ── Retired tools (2.6.6 merge, plan E5) ────────────────────────
diff --git a/src/api/mcp/tool-registry.ts b/src/api/mcp/tool-registry.ts
index 4430c518..b27f4fa2 100644
--- a/src/api/mcp/tool-registry.ts
+++ b/src/api/mcp/tool-registry.ts
@@ -51,9 +51,37 @@ export class ToolRegistry {
private builtinNames = new Set<string>()
/** Collisions refused since startup, for the MCP settings panel / report. */
private rejectedExternal: { serverId: string; toolName: string }[] = []
+ /**
+ * Fallback für zurückgezogene Tool-Namen (2.6.6 tool merge), gesetzt von
+ * registerBuiltinTools.
+ *
+ * M7 / Audit W-T2: hier stand vorher `await import('./builtin-tools')`
+ * mitten in execute(). Der Kommentar daneben nannte den echten Grund —
+ * „keeps the module graph acyclic" —, aber gesplittet hat dieser import()
+ * nie: mcp/index.ts zieht builtin-tools ohnehin statisch herein, also lag das
+ * Modul immer schon im selben Chunk. Rolldown hat das als
+ * INEFFECTIVE_DYNAMIC_IMPORT gemeldet, und zu Recht.
+ *
+ * Ein statischer Import wäre die falsche Auflösung gewesen: die generische
+ * Registry darf die konkreten Builtins nicht kennen (dieselbe Regel, wegen
+ * der RETIRED_MUTATING_NAMES schon in lib/retired-tools.ts ausgelagert ist).
+ * Also wird die Abhängigkeit umgedreht — builtin-tools *meldet* seinen
+ * Redirect an, statt dass die Registry ihn sich holt. Kante weg, Zyklus weg,
+ * Warnung weg.
+ */
+ private retiredRunner:
+ | ((name: string, args: Record<string, any>, run?: AgentRunContext) => Promise<string | null>)
+ | null = null
// ── Registration ──────────────────────────────────────────────
+ /** Siehe `retiredRunner`. Wird von registerBuiltinTools() verdrahtet. */
+ setRetiredRunner(
+ run: (name: string, args: Record<string, any>, run?: AgentRunContext) => Promise<string | null>,
+ ) {
+ this.retiredRunner = run
+ }
+
registerBuiltin(tool: MCPToolDefinition, executor: ToolExecutor) {
this.builtinNames.add(tool.name)
this.tools.set(tool.name, { definition: tool, executor })
@@ -197,9 +225,9 @@ export class ToolRegistry {
if (!entry) {
// Retired names (2.6.6 tool merge) still run: a restored session or a
// model that knows git_status from its context must not burn the step
- // on "Unknown tool". Dynamic import keeps the module graph acyclic.
- const { runRetiredTool } = await import('./builtin-tools')
- const redirected = await runRetiredTool(name, args, run)
+ // on "Unknown tool". Der Redirect kommt über setRetiredRunner herein
+ // (siehe `retiredRunner`) statt über einen Rück-Import auf builtin-tools.
+ const redirected = this.retiredRunner ? await this.retiredRunner(name, args, run) : null
if (redirected !== null) return redirected
return `Error: Unknown tool "${name}"`
}
diff --git a/src/components/chat/MarkdownRenderer.tsx b/src/components/chat/MarkdownRenderer.tsx
index dd888aa7..8c4b926d 100644
--- a/src/components/chat/MarkdownRenderer.tsx
+++ b/src/components/chat/MarkdownRenderer.tsx
@@ -1,18 +1,70 @@
+import { useEffect, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
-import rehypeKatex from 'rehype-katex'
import 'katex/dist/katex.min.css'
-import { MATH_OPTIONS } from '../../lib/markdown-math'
+import { MATH_OPTIONS, contentNeedsKatex } from '../../lib/markdown-math'
import { CodeBlock } from './CodeBlock'
import { codeBlockText } from '../../lib/markdown-code'
import { openExternal } from '../../api/backend'
-import type { Components } from 'react-markdown'
+import { log } from '../../lib/logger'
+import type { Components, Options } from 'react-markdown'
interface Props {
content: string
}
+// M7 / Audit W-T2 — rehype-katex zieht KaTeX (455 kB) hinter sich her und war
+// damit fast die Hälfte des Boot-Chunks, obwohl die meisten Unterhaltungen nie
+// eine Formel enthalten. Deshalb wird das Plugin erst geholt, wenn der Text
+// wirklich Math-Syntax enthält (contentNeedsKatex, siehe lib/markdown-math.ts:
+// bewiesene Obermenge, kein Heuristik-Raten).
+//
+// Das Stylesheet bleibt absichtlich ein statischer Import: es sind ~23 kB CSS,
+// und nachgeladenes CSS hieße, dass eine fertig gesetzte Formel für einen
+// Moment unformatiert steht. Nur der JS-Brocken wandert.
+type RehypePlugins = NonNullable<Options['rehypePlugins']>
+type KatexPlugin = RehypePlugins[number]
+
+let katexPlugin: KatexPlugin | null = null
+let katexLoad: Promise<void> | null = null
+
+function loadKatex(): Promise<void> {
+ katexLoad ??= import('rehype-katex').then(
+ (m) => { katexPlugin = m.default },
+ (err: unknown) => {
+ // Nachladen gescheitert (offline, kaputter Cache): der Rest der Nachricht
+ // wird weiter gerendert, die Formel bleibt als Quelltext stehen. Ein
+ // erneuter Versuch ist erlaubt, darum das Promise wieder freigeben.
+ katexLoad = null
+ log.warn('KaTeX konnte nicht nachgeladen werden; Formeln bleiben roh', { error: err })
+ },
+ )
+ return katexLoad
+}
+
+/**
+ * Liefert die rehype-Plugin-Liste für diesen Text und stößt das Nachladen an,
+ * sobald der Text zum ersten Mal Math enthält. Solange der Brocken unterwegs
+ * ist, rendert der Text ganz normal — nur die Formel steht noch als Quelltext.
+ * Beim Streamen ist das der Bruchteil zwischen dem ersten `$$` und dem Rest der
+ * Formel; danach hält das Modul-Singleton das Plugin für alle weiteren
+ * Nachrichten bereit, ohne erneutes Laden.
+ */
+function useRehypePlugins(content: string): RehypePlugins {
+ const needsKatex = contentNeedsKatex(content)
+ const [katexReady, setKatexReady] = useState(() => katexPlugin !== null)
+
+ useEffect(() => {
+ if (!needsKatex || katexPlugin) return
+ let alive = true
+ void loadKatex().then(() => { if (alive && katexPlugin) setKatexReady(true) })
+ return () => { alive = false }
+ }, [needsKatex])
+
+ return needsKatex && katexReady && katexPlugin ? [katexPlugin] : []
+}
+
// Assistant output can embed images via markdown `![](url)`. Auto-loading an
// arbitrary remote URL turns the renderer into a data-exfil beacon — a model
// (or a poisoned doc/tool-result it summarizes) emits
@@ -125,9 +177,10 @@ const components: Components = {
}
export function MarkdownRenderer({ content }: Props) {
+ const rehypePlugins = useRehypePlugins(content)
return (
<div className="markdown-content text-gray-800 dark:text-gray-200">
- <ReactMarkdown remarkPlugins={[remarkGfm, [remarkMath, MATH_OPTIONS]]} rehypePlugins={[rehypeKatex]} components={components}>
+ <ReactMarkdown remarkPlugins={[remarkGfm, [remarkMath, MATH_OPTIONS]]} rehypePlugins={rehypePlugins} components={components}>
{content}
</ReactMarkdown>
</div>
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 26bc53ad..98de791c 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -4,13 +4,16 @@ import { StaleModelsBanner } from './StaleModelsBanner'
import { StorageQuotaToast } from './StorageQuotaToast'
import { Sidebar } from './Sidebar'
import { ChatView } from '../chat/ChatView'
-import { ModelManager } from '../models/ModelManager'
-import { SettingsPage } from '../settings/SettingsPage'
-import { CreateExperimental } from '../create/experimental/CreateExperimental'
-import { BenchmarkView } from '../models/BenchmarkView'
-import { Onboarding } from '../onboarding/Onboarding'
import { BackendSelector } from '../onboarding/BackendSelector'
import { ErrorBoundary } from '../ui/ErrorBoundary'
+import { LazyView } from './LazyView'
+import {
+ BenchmarkSkeleton,
+ CreateSkeleton,
+ ModelManagerSkeleton,
+ OnboardingSkeleton,
+ SettingsSkeleton,
+} from './ViewSkeletons'
import { useUIStore } from '../../stores/uiStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useCompareStore } from '../../stores/compareStore'
@@ -47,6 +50,29 @@ import { Titlebar } from './Titlebar'
let resolveRestoreDecided: () => void = () => {}
const restoreDecided = new Promise<void>((resolve) => { resolveRestoreDecided = resolve })
+// M7 / Audit W-T2 — Lazy-Grenzen der Top-Level-Views.
+//
+// ChatView bleibt bewusst ein *statischer* Import: `currentView` wird nicht
+// persistiert (uiStore.partialize), jeder Start landet also auf 'chat'. Ihn
+// lazy zu laden hieße, Bundle-Größe gegen einen weißen Blitz beim Kaltstart zu
+// tauschen — genau der Handel, den dieses Audit verbietet.
+//
+// Die übrigen fünf Views sieht niemand, bevor er sie anklickt. Onboarding ist
+// der Grenzfall: es ist beim allerersten Start sofort sichtbar. Es liegt
+// trotzdem hinter der Grenze, weil (a) es genau *einmal* im Leben einer
+// Installation gezeigt wird, (b) der Rahmen davor ohnehin `restoring` abwartet,
+// und (c) sein Fallback den Vollbild-Hintergrund von index.html trägt, der
+// Übergang vom HTML-Splash also farblich nahtlos ist statt weiß.
+//
+// Die Loader stehen auf Modulebene, damit LazyView eine stabile Identität
+// bekommt — eine Factory, die pro Render neu entsteht, würde den View bei jedem
+// Repaint neu mounten.
+const loadModelManager = () => import('../models/ModelManager').then((m) => ({ default: m.ModelManager }))
+const loadBenchmarkView = () => import('../models/BenchmarkView').then((m) => ({ default: m.BenchmarkView }))
+const loadSettingsPage = () => import('../settings/SettingsPage').then((m) => ({ default: m.SettingsPage }))
+const loadCreateExperimental = () => import('../create/experimental/CreateExperimental').then((m) => ({ default: m.CreateExperimental }))
+const loadOnboarding = () => import('../onboarding/Onboarding').then((m) => ({ default: m.Onboarding }))
+
export function AppShell() {
// Targeted, NOT `useUIStore()`. A whole-store subscription here put the
// entire app tree behind every uiStore write — and the explorer's resize
@@ -801,7 +827,7 @@ export function AppShell() {
if (restoring) return null
if (!onboardingDone) {
- return <Onboarding />
+ return <LazyView load={loadOnboarding} fallback={<OnboardingSkeleton />} />
}
return (
@@ -814,11 +840,15 @@ export function AppShell() {
<div className="flex-1 flex overflow-hidden gap-2 p-2">
{!isComparing && <Sidebar />}
<main className="flex-1 overflow-hidden rounded-xl bg-white dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05]">
+ {/* Boot-View: statisch, damit der Kaltstart sofort etwas zeigt. */}
{currentView === 'chat' && <ErrorBoundary><ChatView /></ErrorBoundary>}
- {currentView === 'models' && <ErrorBoundary><ModelManager /></ErrorBoundary>}
- {currentView === 'benchmark' && <ErrorBoundary><BenchmarkView /></ErrorBoundary>}
- {currentView === 'settings' && <ErrorBoundary><SettingsPage /></ErrorBoundary>}
- {currentView === 'create' && <ErrorBoundary><CreateExperimental /></ErrorBoundary>}
+ {/* LazyView bringt seine eigene ErrorBoundary *um* die Suspense-
+ Grenze mit — ein abgelehnter Chunk-Import wird dort gefangen,
+ statt bis zur Root-Boundary durchzuschlagen. */}
+ {currentView === 'models' && <LazyView load={loadModelManager} fallback={<ModelManagerSkeleton />} />}
+ {currentView === 'benchmark' && <LazyView load={loadBenchmarkView} fallback={<BenchmarkSkeleton />} />}
+ {currentView === 'settings' && <LazyView load={loadSettingsPage} fallback={<SettingsSkeleton />} />}
+ {currentView === 'create' && <LazyView load={loadCreateExperimental} fallback={<CreateSkeleton />} />}
</main>
</div>
</div>
diff --git a/src/components/layout/LazyView.tsx b/src/components/layout/LazyView.tsx
new file mode 100644
index 00000000..a61acdc2
--- /dev/null
+++ b/src/components/layout/LazyView.tsx
@@ -0,0 +1,73 @@
+import { Suspense, lazy, useCallback, useState, type ComponentType, type ReactNode } from 'react'
+import { ErrorBoundary } from '../ui/ErrorBoundary'
+import { log } from '../../lib/logger'
+
+/**
+ * M7 / Audit W-T2 — Lazy-Grenze für die Top-Level-Views.
+ *
+ * Warum nicht einfach `lazy()` + `<Suspense>` direkt in AppShell:
+ *
+ * 1. **Ladefehler.** `React.lazy` merkt sich das Ergebnis der Factory — auch
+ * eine Ablehnung. Ein Chunk, dessen `import()` einmal gescheitert ist
+ * (Offline beim Web-Build, halb geschriebener Cache, abgebrochenes
+ * Update), bliebe für den Rest der Sitzung kaputt. Ohne Fehlergrenze
+ * propagiert der Fehler bis nach oben und die App kippt in die
+ * Root-Recovery — also faktisch weißer Bildschirm für einen Klick auf
+ * „Settings". Deshalb liegt die `<Suspense>`-Grenze *innerhalb* einer
+ * `<ErrorBoundary>`: die fängt den Reject und zeigt die Inline-Karte.
+ *
+ * 2. **Retry, der wirklich etwas tut.** Der Retry-Knopf der ErrorBoundary
+ * setzt nur ihren eigenen State zurück; die abgelehnte lazy-Payload wäre
+ * immer noch da und würde sofort wieder werfen. `attempt` erzeugt darum
+ * eine frische lazy-Komponente, deren Factory neu geladen wird.
+ *
+ * 3. **Erster Versuch mit einem Nachschlag.** Ein einzelner verlorener
+ * Chunk-Request ist der häufigste Fall. Die Factory versucht es genau
+ * einmal automatisch nach 300 ms erneut, bevor sie den Fehler an React
+ * durchreicht. Mehr Automatik wäre Rauschen — dann ist der Chunk wirklich
+ * weg und der Nutzer soll es sehen.
+ *
+ * Bekannte Grenze, ehrlich benannt: Browser cachen einen gescheiterten
+ * Modul-Fetch in der Modul-Map. Ein *dauerhaft* kaputter Chunk lässt sich
+ * darum weder durch den automatischen Nachschlag noch durch Retry heilen —
+ * dafür ist der „Reload"-Weg der Root-Boundary bzw. ein Neustart zuständig.
+ * Der Gewinn hier ist, dass die App dabei bedienbar bleibt statt zu erblinden.
+ */
+
+type Loader = () => Promise<{ default: ComponentType }>
+
+function withOneRetry(load: Loader): Loader {
+ return () =>
+ load().catch((err: unknown) => {
+ log.warn('LazyView: Chunk-Import fehlgeschlagen, ein Nachschlag', { error: err })
+ return new Promise<{ default: ComponentType }>((resolve, reject) => {
+ setTimeout(() => { load().then(resolve, reject) }, 300)
+ })
+ })
+}
+
+interface Props {
+ /**
+ * Muss modul-stabil sein (ein `const` auf Modulebene), sonst wirft jeder
+ * Render eine neue lazy-Komponente weg und der View re-mountet endlos.
+ */
+ load: Loader
+ /** Skelett in der Geometrie des Views — nie `null`, nie „Loading…". */
+ fallback: ReactNode
+}
+
+export function LazyView({ load, fallback }: Props) {
+ // Die lazy-Komponente liegt im State, nicht in einem useMemo: der Retry muss
+ // eine *frische* Payload erzeugen, und „neu erzeugen" ist ein Zustands-
+ // wechsel, keine abgeleitete Rechnung.
+ const [View, setView] = useState<ComponentType>(() => lazy(withOneRetry(load)))
+ const retry = useCallback(() => { setView(() => lazy(withOneRetry(load))) }, [load])
+
+ return (
+ <ErrorBoundary onRetry={retry}>
+ <Suspense fallback={fallback}>
+ <View />
+ </Suspense>
+ </ErrorBoundary>
+ )
+}
diff --git a/src/components/layout/ViewSkeletons.tsx b/src/components/layout/ViewSkeletons.tsx
new file mode 100644
index 00000000..fbf9d170
--- /dev/null
+++ b/src/components/layout/ViewSkeletons.tsx
@@ -0,0 +1,171 @@
+/**
+ * M7 / Audit W-T2 — Suspense-Fallbacks für die lazy geladenen Top-Level-Views.
+ *
+ * Regel dieser Datei: jeder Fallback trägt die *Geometrie* seines Views. Ein
+ * `null`-Fallback lässt `<main>` auf 0 px zusammenfallen und der ganze Rahmen
+ * springt; ein nacktes „Loading…" mittig im Nichts erzeugt denselben Sprung,
+ * nur mit Text. Also: gleiche Container-Klassen wie der echte View, gleiche
+ * Kopfzeile, gleiche Spalten — nur die Inhalte sind graue Balken.
+ *
+ * Die Balken sind bewusst keine Attrappen von echten Daten: sie tragen keine
+ * Zahlen, keine Namen, keine Zustände. Sie behaupten nichts, sie halten Platz.
+ *
+ * `aria-busy` + `role="status"` mit einem sr-only-Text, damit die Ladepause
+ * für Screenreader nicht stumm bleibt.
+ */
+
+function Bar({ className = '' }: { className?: string }) {
+ return <div className={`rounded bg-gray-200/70 dark:bg-white/[0.06] ${className}`} />
+}
+
+function Shell({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div role="status" aria-busy="true" aria-live="polite" className="h-full animate-pulse">
+ <span className="sr-only">{label}</span>
+ {children}
+ </div>
+ )
+}
+
+/** Geometrie von SettingsPage: h-full scroll → max-w-lg, Kopf + Tab-Leiste. */
+export function SettingsSkeleton() {
+ return (
+ <Shell label="Loading settings">
+ <div className="h-full overflow-hidden">
+ <div className="max-w-lg mx-auto px-4 py-4">
+ <div className="flex items-center gap-2 mb-4">
+ <Bar className="w-6 h-6 rounded" />
+ <Bar className="w-16 h-3" />
+ </div>
+ <div className="flex items-center gap-1 pb-2 mb-2 border-b border-gray-100 dark:border-white/[0.06]">
+ {[64, 58, 72, 54, 66].map((w, i) => (
+ <div key={i} className="shrink-0" style={{ width: w }}>
+ <Bar className="h-6 rounded-md" />
+ </div>
+ ))}
+ </div>
+ <div className="space-y-3">
+ {[0, 1, 2, 3].map((i) => (
+ <div key={i} className="rounded-lg border border-gray-200 dark:border-white/[0.06] p-3 space-y-2.5">
+ <Bar className="w-24 h-2.5" />
+ <Bar className="w-full h-2" />
+ <Bar className="w-4/5 h-2" />
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </Shell>
+ )
+}
+
+/** Geometrie von ModelManager: h-full flex → schmale Kategorie-Schiene + Raster. */
+export function ModelManagerSkeleton() {
+ return (
+ <Shell label="Loading models">
+ <div className="h-full flex overflow-hidden">
+ <aside className="shrink-0 w-12 lg:w-36 border-r border-gray-200 dark:border-white/[0.06] bg-gray-50/60 dark:bg-white/[0.015] flex flex-col py-3 px-1.5 lg:px-2 gap-1">
+ {[0, 1, 2].map((i) => (
+ <div key={i} className="flex items-center gap-2 px-2 py-2">
+ <Bar className="w-[15px] h-[15px] shrink-0" />
+ <Bar className="hidden lg:block flex-1 h-2.5" />
+ </div>
+ ))}
+ </aside>
+ <div className="flex-1 overflow-hidden px-4 py-4 space-y-3">
+ <div className="flex items-center gap-2">
+ <Bar className="w-40 h-6 rounded-lg" />
+ <Bar className="ml-auto w-24 h-6 rounded-lg" />
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2.5">
+ {[0, 1, 2, 3, 4, 5].map((i) => (
+ <div key={i} className="rounded-xl border border-gray-200 dark:border-white/[0.06] p-3 space-y-2.5">
+ <Bar className="w-3/5 h-3" />
+ <Bar className="w-full h-2" />
+ <Bar className="w-1/3 h-2" />
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </Shell>
+ )
+}
+
+/** Geometrie von BenchmarkView: h-full scroll → max-w-2xl, Kopfzeile + Tabelle. */
+export function BenchmarkSkeleton() {
+ return (
+ <Shell label="Loading benchmark">
+ <div className="h-full overflow-hidden">
+ <div className="max-w-2xl mx-auto px-4 py-4">
+ <div className="flex items-center gap-2 mb-4">
+ <Bar className="w-6 h-6" />
+ <Bar className="w-4 h-4" />
+ <Bar className="w-20 h-3" />
+ <Bar className="ml-auto w-20 h-5 rounded-md" />
+ </div>
+ <div className="space-y-2">
+ {[0, 1, 2, 3, 4].map((i) => (
+ <div key={i} className="flex items-center gap-3 rounded-lg border border-gray-200 dark:border-white/[0.06] px-3 py-2.5">
+ <Bar className="w-1/3 h-2.5" />
+ <Bar className="w-16 h-2.5 ml-auto" />
+ <Bar className="w-16 h-2.5" />
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </Shell>
+ )
+}
+
+/**
+ * Geometrie von CreateExperimental: Spalte aus IntentBar (oben), Bühne
+ * (dehnt sich) und Composer (unten).
+ */
+export function CreateSkeleton() {
+ return (
+ <Shell label="Loading create">
+ <div className="relative h-full w-full flex flex-col bg-white dark:bg-[#141414] overflow-hidden">
+ <div className="shrink-0 flex items-center gap-2 px-4 py-2.5 border-b border-gray-200 dark:border-white/[0.06]">
+ {[56, 56, 56, 56].map((w, i) => (
+ <div key={i} style={{ width: w }}><Bar className="h-6 rounded-md" /></div>
+ ))}
+ </div>
+ <div className="flex-1 min-h-0 flex items-center justify-center p-6">
+ <Bar className="w-full max-w-xl h-full max-h-[60%] rounded-xl" />
+ </div>
+ <div className="shrink-0 px-4 pb-4">
+ <Bar className="w-full h-16 rounded-xl" />
+ </div>
+ </div>
+ </Shell>
+ )
+}
+
+/**
+ * Geometrie von Onboarding: Vollbild, zentrierte schmale Karte, Schritt-Punkte
+ * oben. Anders als die vier Views oben füllt dieser Fallback den ganzen
+ * Bildschirm, weil Onboarding das auch tut (es rendert *vor* dem App-Rahmen).
+ * Der Hintergrundton ist der von index.html (#161616) — so bleibt der Übergang
+ * vom HTML-Splash zum ersten React-Frame farblich nahtlos.
+ */
+export function OnboardingSkeleton() {
+ return (
+ <Shell label="Loading setup">
+ <div className="h-screen w-screen flex items-center justify-center p-4 bg-[#161616]">
+ <div className="fixed top-10 left-1/2 -translate-x-1/2 flex gap-1.5">
+ {[0, 1, 2, 3].map((i) => (
+ <div key={i} className="w-1.5 h-1.5 rounded-full bg-white/15" />
+ ))}
+ </div>
+ <div className="max-w-sm w-full space-y-4 flex flex-col items-center">
+ <Bar className="w-40 h-3.5" />
+ <Bar className="w-full h-2" />
+ <Bar className="w-5/6 h-2" />
+ <Bar className="w-28 h-7 rounded-lg mt-2" />
+ </div>
+ </div>
+ </Shell>
+ )
+}
diff --git a/src/components/layout/__tests__/lazy-view-boundaries.test.ts b/src/components/layout/__tests__/lazy-view-boundaries.test.ts
new file mode 100644
index 00000000..151bfcc0
--- /dev/null
+++ b/src/components/layout/__tests__/lazy-view-boundaries.test.ts
@@ -0,0 +1,156 @@
+/**
+ * M7 / Audit W-T2 — die Lazy-Grenzen der Top-Level-Views.
+ *
+ * Der Boot-Chunk lag bei 1968 kB, das Audit-Soll bei < 800 kB. Der größte
+ * Hebel war, alles hinter eine `React.lazy`-Grenze zu legen, was beim Start
+ * niemand sieht. Diese Datei pinnt die vier Eigenschaften, ohne die genau
+ * dieser Umbau zum Rückschritt wird:
+ *
+ * 1. Der beim Start sichtbare View bleibt statisch — sonst tauscht man
+ * Bundle-Größe gegen einen weißen Blitz beim Kaltstart.
+ * 2. Die übrigen Views sind wirklich draußen (kein statischer Import, der
+ * das `import()` still wieder wirkungslos macht — Muster M7).
+ * 3. Jede Suspense-Grenze hat einen Fallback mit Geometrie, kein `null` und
+ * kein nacktes „Loading…".
+ * 4. Ein gescheiterter Chunk-Import landet in einer ErrorBoundary, nicht im
+ * weißen Bildschirm.
+ *
+ * Plus die Anti-Selbstbetrugs-Klausel des Audits: die Chunk-Warnung darf nicht
+ * weggeschraubt werden.
+ *
+ * Run: npx vitest run src/components/layout/__tests__/lazy-view-boundaries.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, resolve } from 'node:path'
+
+const here = dirname(fileURLToPath(import.meta.url))
+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')
+
+const appShell = read('../AppShell.tsx')
+const lazyView = read('../LazyView.tsx')
+const skeletons = read('../ViewSkeletons.tsx')
+const markdown = read('../../chat/MarkdownRenderer.tsx')
+const viteConfig = read('../../../../vite.config.ts')
+
+/** Die fünf Views, die niemand sieht, bevor er sie anklickt. */
+const LAZY_VIEWS = [
+ ['ModelManager', '../models/ModelManager'],
+ ['BenchmarkView', '../models/BenchmarkView'],
+ ['SettingsPage', '../settings/SettingsPage'],
+ ['CreateExperimental', '../create/experimental/CreateExperimental'],
+ ['Onboarding', '../onboarding/Onboarding'],
+] as const
+
+describe('der Boot-View bleibt statisch', () => {
+ it('ChatView wird direkt importiert, nicht lazy', () => {
+ expect(appShell).toContain("import { ChatView } from '../chat/ChatView'")
+ expect(appShell).not.toMatch(/import\(\s*'\.\.\/chat\/ChatView'/)
+ })
+
+ it('und rendert ohne Suspense-Umweg', () => {
+ expect(appShell).toContain("{currentView === 'chat' && <ErrorBoundary><ChatView /></ErrorBoundary>}")
+ })
+
+ it('uiStore startet weiterhin auf chat — sonst stimmt die Annahme oben nicht', () => {
+ const uiStore = read('../../../stores/uiStore.ts')
+ expect(uiStore).toContain("currentView: 'chat',")
+ // currentView wird nicht persistiert, jeder Kaltstart landet also auf chat.
+ expect(uiStore).not.toMatch(/partialize:[\s\S]{0,200}currentView/)
+ })
+})
+
+describe('die übrigen fünf Views sind wirklich draußen', () => {
+ it.each(LAZY_VIEWS)('%s wird dynamisch geladen', (_name, path) => {
+ expect(appShell).toContain(`import('${path}')`)
+ })
+
+ it.each(LAZY_VIEWS)('%s hat KEINEN statischen Import mehr (M7)', (_name, path) => {
+ // Genau das Muster, das das Audit anprangert: ein import(), das durch einen
+ // statischen Import derselben Datei wirkungslos wird.
+ expect(appShell).not.toMatch(new RegExp(`import\\s*\\{[^}]*\\}\\s*from\\s*'${path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}'`))
+ })
+
+ it('jeder Loader steht auf Modulebene, damit LazyView nicht bei jedem Repaint neu mountet', () => {
+ for (const [, path] of LAZY_VIEWS) {
+ expect(appShell).toMatch(new RegExp(`^const load\\w+ = \\(\\) => import\\('${path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}'\\)`, 'm'))
+ }
+ })
+})
+
+describe('jede Grenze hat einen Fallback mit Geometrie', () => {
+ it('jede LazyView-Verwendung reicht ein Skelett durch', () => {
+ const uses = [...appShell.matchAll(/<LazyView\s+load=\{(\w+)\}\s+fallback=\{<(\w+)\s*\/>\}/g)]
+ expect(uses.length).toBe(LAZY_VIEWS.length)
+ for (const [, , fallback] of uses) {
+ expect(fallback).toMatch(/Skeleton$/)
+ }
+ })
+
+ it('kein Fallback ist null oder ein blanker Text', () => {
+ expect(appShell).not.toMatch(/fallback=\{null\}/)
+ expect(appShell).not.toMatch(/fallback=\{?["']/)
+ expect(skeletons).not.toMatch(/>\s*Loading[.…]*\s*</)
+ })
+
+ it('die Skelette tragen die Container-Klassen ihrer Views, nicht nur einen Spinner', () => {
+ // h-full: sonst kollabiert <main> auf 0 px und der ganze Rahmen springt.
+ expect(skeletons).toContain('h-full flex overflow-hidden') // ModelManager
+ expect(skeletons).toContain('max-w-lg mx-auto px-4 py-4') // SettingsPage
+ expect(skeletons).toContain('max-w-2xl mx-auto px-4 py-4') // BenchmarkView
+ expect(skeletons).toContain('relative h-full w-full flex flex-col') // Create
+ expect(skeletons).toContain('h-screen w-screen flex items-center justify-center') // Onboarding
+ })
+
+ it('und melden sich bei Screenreadern', () => {
+ expect(skeletons).toContain('role="status"')
+ expect(skeletons).toContain('aria-busy="true"')
+ })
+
+ it('für jeden lazy View existiert genau ein Skelett-Export', () => {
+ for (const name of ['ModelManager', 'Benchmark', 'Settings', 'Create', 'Onboarding']) {
+ expect(skeletons).toContain(`export function ${name}Skeleton()`)
+ }
+ })
+})
+
+describe('ein kaputter Chunk kippt die App nicht in Weiß', () => {
+ it('die Suspense-Grenze liegt INNERHALB der ErrorBoundary', () => {
+ // Andersherum gefangen wäre der Reject nicht: die Boundary muss über der
+ // Stelle stehen, an der lazy() wirft.
+ expect(lazyView).toMatch(/<ErrorBoundary[^>]*>\s*<Suspense/)
+ })
+
+ it('der Retry der Boundary erzeugt eine frische lazy-Payload', () => {
+ // React.lazy merkt sich auch die Ablehnung — ohne Neuerzeugung wäre der
+ // Retry-Knopf Dekoration.
+ expect(lazyView).toContain('onRetry={retry}')
+ expect(lazyView).toContain('setView(() => lazy(withOneRetry(load)))')
+ })
+
+ it('die ErrorBoundary ruft onRetry auch wirklich auf', () => {
+ expect(read('../../ui/ErrorBoundary.tsx')).toContain('this.props.onRetry?.()')
+ })
+})
+
+describe('KaTeX hängt nicht mehr am Boot', () => {
+ it('MarkdownRenderer importiert rehype-katex nur dynamisch', () => {
+ expect(markdown).not.toMatch(/^import rehypeKatex from 'rehype-katex'/m)
+ expect(markdown).toContain("import('rehype-katex')")
+ })
+
+ it('das Stylesheet bleibt statisch — nachgeladenes CSS hieße unformatierte Formeln', () => {
+ expect(markdown).toContain("import 'katex/dist/katex.min.css'")
+ })
+
+ it('das Gatter kommt aus dem getesteten Leaf-Modul, nicht aus einer Inline-Heuristik', () => {
+ expect(markdown).toContain('contentNeedsKatex')
+ })
+})
+
+describe('ANTI-SELBSTBETRUG: die Warnschwelle bleibt, wo sie ist', () => {
+ it('chunkSizeWarningLimit wird nicht hochgeschraubt', () => {
+ expect(viteConfig).not.toContain('chunkSizeWarningLimit')
+ })
+})
diff --git a/src/components/ui/ErrorBoundary.tsx b/src/components/ui/ErrorBoundary.tsx
index 561c1b81..b090fa06 100644
--- a/src/components/ui/ErrorBoundary.tsx
+++ b/src/components/ui/ErrorBoundary.tsx
@@ -13,6 +13,13 @@ interface Props {
* reset settings) instead of the small inline card.
*/
root?: boolean
+ /**
+ * Called by the inline "Retry" button *in addition to* clearing the error
+ * state. LazyView uses it to throw away the memoized React.lazy payload —
+ * without that, a chunk whose import() rejected once stays rejected for the
+ * rest of the session and the Retry button would be decoration.
+ */
+ onRetry?: () => void
}
interface State {
@@ -36,6 +43,7 @@ export class ErrorBoundary extends Component<Props, State> {
handleReset = () => {
this.setState({ hasError: false, error: null })
+ this.props.onRetry?.()
}
render() {
diff --git a/src/lib/__tests__/markdown-katex-gate.test.ts b/src/lib/__tests__/markdown-katex-gate.test.ts
new file mode 100644
index 00000000..81abb223
--- /dev/null
+++ b/src/lib/__tests__/markdown-katex-gate.test.ts
@@ -0,0 +1,98 @@
+/**
+ * M7 / Audit W-T2 — das Nachlade-Gatter für KaTeX.
+ *
+ * MarkdownRenderer holt rehype-katex (455 kB) erst, wenn der Text es braucht.
+ * Die Behauptung dahinter ist keine Heuristik, sondern eine Aussage über den
+ * Baum: `contentNeedsKatex(content) === false` ⟹ rehype-katex ändert an diesem
+ * Dokument nichts. Genau das prüfen diese Tests — mit der echten Pipeline, in
+ * derselben Reihenfolge, mit denselben Plugins und Optionen wie im Renderer.
+ *
+ * Fällt das um, ist es kein Stilproblem: dann verschluckt die App still eine
+ * Formel. Der Vergleich läuft deshalb strukturell über den hast-Baum, nicht
+ * über eine Stichprobe von Klassennamen.
+ *
+ * Run: npx vitest run src/lib/__tests__/markdown-katex-gate.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { unified } from 'unified'
+import remarkParse from 'remark-parse'
+import remarkGfm from 'remark-gfm'
+import remarkMath from 'remark-math'
+import remarkRehype from 'remark-rehype'
+import rehypeKatex from 'rehype-katex'
+import { MATH_OPTIONS, contentNeedsKatex } from '../markdown-math'
+
+/** Der hast-Baum, so wie react-markdown ihn rendern würde. */
+async function tree(md: string, withKatex: boolean): Promise<string> {
+ const pipeline = unified()
+ .use(remarkParse)
+ .use(remarkGfm)
+ .use(remarkMath, MATH_OPTIONS)
+ .use(remarkRehype)
+ if (withKatex) pipeline.use(rehypeKatex)
+ const out = await pipeline.run(pipeline.parse(md))
+ return JSON.stringify(out)
+}
+
+/** Ändert rehype-katex an diesem Dokument etwas? */
+async function katexChangesAnything(md: string): Promise<boolean> {
+ const [without, withIt] = await Promise.all([tree(md, false), tree(md, true)])
+ return without !== withIt
+}
+
+// Texte OHNE Math — hier muss das Gatter zu bleiben, sonst laden wir 455 kB
+// für nichts.
+const NO_MATH = [
+ 'Just a plain sentence.',
+ 'Split the $30 bill. Each of the 3 pays $10.',
+ 'inline `code` and a [link](https://example.com)',
+ 'a lone $x$ stays currency because singleDollarTextMath is off',
+ '```js\nconst a = 1\n```',
+ '```mathematica\n(* not our fence *)\n```',
+ '| a | b |\n| - | - |\n| 1 | 2 |',
+ 'a backslash formula \\(a^2\\) is not a delimiter here',
+]
+
+// Texte MIT Math — beide Wege, über die rehype-katex überhaupt anspringt.
+const WITH_MATH = [
+ '$$a^2 + b^2 = c^2$$',
+ '$$\na^2 + b^2 = c^2\n$$',
+ 'the identity $$e^{i\\pi}=-1$$ holds',
+ '```math\na^2\n```',
+ '- item\n ```math\n a^2\n ```',
+ '1. step\n ```math\n a^2\n ```',
+]
+
+describe('contentNeedsKatex ist eine Obermenge dessen, was rehype-katex anfasst', () => {
+ it.each(NO_MATH)('kein Math, also kein Nachladen: %j', async (md) => {
+ // Die eigentliche Zusicherung: das Plugin wegzulassen ändert nichts …
+ expect(await katexChangesAnything(md)).toBe(false)
+ // … und genau deshalb darf das Gatter zu bleiben.
+ expect(contentNeedsKatex(md)).toBe(false)
+ })
+
+ it.each(WITH_MATH)('Math vorhanden, also Nachladen: %j', async (md) => {
+ // Erst beweisen, dass rehype-katex hier wirklich etwas tut …
+ expect(await katexChangesAnything(md)).toBe(true)
+ // … dann, dass das Gatter aufmacht.
+ expect(contentNeedsKatex(md)).toBe(true)
+ })
+})
+
+describe('NEGATIV-KONTROLLE: das Gatter irrt nur in die harmlose Richtung', () => {
+ it('ein $$ im Codeblock lädt einmal zu viel, aber nie zu wenig', () => {
+ // Hier ändert rehype-katex nichts, das Gatter macht trotzdem auf. Das ist
+ // der beabsichtigte Preis für eine Regel ohne Sonderfälle: ein überflüssiger
+ // Ladevorgang ist unsichtbar, eine verschluckte Formel nicht.
+ expect(contentNeedsKatex('```\n$$a^2$$\n```')).toBe(true)
+ })
+
+ it('ein einzelnes Dollarzeichen macht nicht auf', () => {
+ expect(contentNeedsKatex('costs $5')).toBe(false)
+ })
+
+ it('das Wort math allein macht nicht auf — nur der Zaun', () => {
+ expect(contentNeedsKatex('I like math and mathematics.')).toBe(false)
+ expect(contentNeedsKatex('```mathml\n<x/>\n```')).toBe(false)
+ })
+})
diff --git a/src/lib/markdown-math.ts b/src/lib/markdown-math.ts
index ede51826..2abb6950 100644
--- a/src/lib/markdown-math.ts
+++ b/src/lib/markdown-math.ts
@@ -4,3 +4,30 @@
// (David 2026-08-08, seen in the thinking stream). Block math ($$…$$) still
// renders, which is what an actual formula uses in this app.
export const MATH_OPTIONS = { singleDollarTextMath: false } as const
+
+// M7 / Audit W-T2 — KaTeX ist 455 kB und damit der mit Abstand größte einzelne
+// Posten im Boot-Chunk gewesen. Gebraucht wird es nur, wenn eine Nachricht
+// wirklich Formeln enthält. Damit das Nachladen kein Ratespiel wird, ist dieses
+// Prädikat eine bewiesene *Obermenge* der Fälle, in denen rehype-katex am Baum
+// überhaupt etwas ändert. rehype-katex greift an genau drei Klassen an:
+//
+// • `math-display` / `math-inline` — setzt remark-math. Mit
+// MATH_OPTIONS (singleDollarTextMath: false) entstehen sie ausschließlich
+// aus `$$`; ein einzelnes `$` ist Währung und erzeugt keinen Math-Knoten.
+// • `language-math` — entsteht aus einem Code-Zaun mit der Info-Zeichenkette
+// `math` (```math). Der Zaun geht durch rehype-katex, *bevor* die
+// `code`-Komponente von MarkdownRenderer ihn je zu sehen bekommt.
+//
+// Roher HTML-Code kann die Klassen nicht einschleusen: react-markdown läuft
+// ohne rehype-raw, HTML wird escaped. Fehlen also `$$` und der math-Zaun, ist
+// rehype-katex beweisbar ein No-op und das Nachladen entfällt ersatzlos.
+//
+// Die Einrückung ist absichtlich unbeschränkt (`[ \t]*` statt der 0–3 Zeichen
+// der CommonMark-Regel): ein tief in einer Liste verschachtelter Zaun bleibt so
+// erfasst. Die Regel irrt damit nur in die harmlose Richtung — sie lädt einmal
+// zu viel, nie einmal zu wenig.
+const MATH_FENCE = /(?:^|\n)[ \t]*(?:`{3,}|~{3,})[ \t]*math(?![\w-])/
+
+export function contentNeedsKatex(content: string): boolean {
+ return content.includes('$$') || MATH_FENCE.test(content)
+}