okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-clean-7 (045843071): the app loads screens, languages, Prism and Time-skip on first use; main chunk 3,123,528 -> 755,418 B, start screen 248.5 -> 143.4 ms (p2006 Chrome, median of 10); nothing users see changes (cleanup step 7)1631a9fde

main
11.1 KiB215 linesraw
1import { tr } from '../lib/i18n';
2/** App shell: routes, setup takeover, palette, toasts. */
3import { useNative } from '../lib/native';
4import { Component, Suspense, useDeferredValue, useEffect, useRef, useState, type ReactNode } from 'react';
5import { useSurfaceFocus } from '../lib/focus';
6import { closeSettings, useLocation } from '../lib/router';
7import { bootOnce, bootstrap, setNavOpen, setFocus, useStore, } from '../lib/store';
8import { Sidebar } from './Sidebar';
9import { CommandPalette } from './CommandPalette';
10import { ShortcutsDialog } from './Shortcuts';
11import { FolderPathDialog } from '../components/FolderPathDialog';
12import { MOD, handleAppShortcut, runCommand } from '../lib/commands';
13import { useMedia } from '../lib/responsive';
14import { Btn, Dialog, IconBtn, Toasts } from '../components/ui';
15import { Brand } from '../components/Brand';
16import { ChatScreen } from '../screens/Chat';
17import { lazyScreen, useLoadedModule } from '../lib/lazy-screen';
18// The start screen is Chat. Every other screen loads the first time it is opened (7.1), so the first start reads and runs less code.
19const loadSetup = () => import('../screens/Setup');
20const loadSettings = () => import('../screens/Settings');
21const ModelRunScreen = lazyScreen(() => import('../screens/ModelRun'), (m) => m.ModelRunScreen);
22const ServingScreen = lazyScreen(() => import('../screens/Serving'), (m) => m.ServingScreen);
23const MonitorScreen = lazyScreen(() => import('../screens/Monitor'), (m) => m.MonitorScreen);
24const TasksScreen = lazyScreen(() => import('../screens/Tasks'), (m) => m.TasksScreen);
25const SkillsScreen = lazyScreen(() => import('../screens/Skills'), (m) => m.SkillsScreen);
26function AppShell() {
27    useStore(s => s.language);
28    const location = useLocation();
29    const rail = useStore((s) => s.rail);
30    const ready = useStore((s) => s.ready);
31    const setup = useStore((s) => s.setup);
32    const paletteOpen = useStore((s) => s.paletteOpen);
33    const focus = useStore((s) => s.focus);
34    const firstRunOpen = useStore((s) => s.setupOpen);
35    const setupRef = useRef<HTMLDivElement>(null);
36    useEffect(() => {
37        bootOnce();
38    }, []);
39    useEffect(() => {
40        window.addEventListener('keydown', handleAppShortcut);
41        return () => window.removeEventListener('keydown', handleAppShortcut);
42    }, []);
43    const compact = useMedia('(max-width: 1279px)');
44    const mobile = useMedia('(max-width: 767px)');
45    const navOpen = useStore(s => s.navOpen);
46    const navRef = useRef<HTMLElement>(null);
47    useSurfaceFocus(navOpen && compact, navRef);
48    useEffect(() => { setNavOpen(false); }, [location.route, location.param, compact]);
49    // First run is a modal over the working shell rather than a takeover: the app
50    // is visibly there behind it, which is far less daunting than a blank window
51    // demanding five steps before anything appears.
52    const setupOpen = location.route === 'setup' || (!!setup && !setup.complete && !setup.dismissed) || firstRunOpen;
53    // Hook runs here, after setupOpen exists — see src/lib/focus.ts.
54    // The dialogs open once their code has loaded, so they appear and take focus exactly as before.
55    const setupCode = useLoadedModule(loadSetup, setupOpen);
56    const setupShown = setupOpen && !!setupCode;
57    useSurfaceFocus(setupShown, setupRef);
58    const settingsWanted = location.query.get('settings') === '1';
59    const settingsCode = useLoadedModule(loadSettings, settingsWanted);
60    const routeShown = useDeferredValue(location.route);
61    return (<div className="app" data-rail={compact ? !navOpen : rail} data-layout={mobile ? 'mobile' : compact ? 'compact' : 'desktop'} data-nav-open={navOpen || undefined} data-focus={focus && location.route === 'chat' || undefined}>
62      <Sidebar containerRef={navRef}/>
63      {tr(navOpen && compact ? <button className="nav-scrim" tabIndex={-1} aria-hidden="true" aria-label={tr("Close navigation")} onClick={() => setNavOpen(false)}/> : null)}
64      <main className="main">
65        <div className="mobile-bar">
66          <IconBtn name="panel" title={tr("Open navigation")} onClick={() => setNavOpen(true)}/>
67          <Brand variant="lockup" height={24}/>
68          <span className="spacer"/>
69          <IconBtn name="new-chat" title={tr("New chat")} onClick={() => runCommand('new')}/>
70        </div>
71        <ConnectionBar />
72        {tr(focus && location.route === 'chat' ? <FocusBar /> : null)}
73        {tr(!ready ? <BootSkeleton /> : <Suspense fallback={<BootSkeleton />}><RouteView route={routeShown}/></Suspense>)}
74      </main>
75      <CommandPalette open={paletteOpen}/>
76      <Dialog open={settingsWanted && !!settingsCode} title={tr("Settings")} className="settings-dialog" onClose={closeSettings}>{settingsCode ? <settingsCode.SettingsScreen /> : null}</Dialog>
77      <ShortcutsDialog />
78      <FolderPathDialog />
79      {tr(setupShown ? (<div className="setupmodal" role="dialog" aria-modal="true" aria-label={tr("Set up Strata")}>
80          <div className="scrim" data-open="true" aria-hidden="true"/>
81          <div className="setupmodal__surface" ref={setupRef}>
82            {setupCode ? <setupCode.SetupScreen /> : null}
83          </div>
84        </div>) : null)}
85      <Toasts />
86    </div>);
87}
88/**
89 * Says when the host is not answering.
90 *
91 * `connection` has been tracked since the beginning and never rendered, so a
92 * dead host looked exactly like an idle one: every panel simply empty, with no
93 * statement that anything was wrong. For someone who does not know what a host
94 * process is, "nothing works and nothing says why" is the worst possible state.
95 */
96function ConnectionBar() {
97    const connection = useStore((s) => s.connection);
98    const [retrying, setRetrying] = useState(false);
99    if (connection === 'live')
100        return null;
101    const offline = connection === 'offline';
102    return (<div className="connbar" data-state={connection} role="status">
103      <span className="connbar__dot"/>
104      <span className="connbar__text">
105        {tr(offline ? (<>
106            <strong>{tr("Strata isn\u2019t connected to its engine.")}</strong>{tr(" Your conversation and drafts are kept while it reconnects.")}</>) : (<>{tr("Connecting to the local engine\u2026")}</>))}
107      </span>
108      {tr(offline ? (<Btn variant="secondary" size="sm" icon="refresh" disabled={retrying} onClick={() => {
109                setRetrying(true);
110                void bootstrap().finally(() => setRetrying(false));
111            }}>
112          {tr(retrying ? 'Retrying…' : 'Retry')}
113        </Btn>) : null)}
114      {tr(offline ? <details className="connection-details"><summary>{tr("Connection details")}</summary><p className="xs">{tr("App host: ")}{tr(window.location.origin)}{tr(". Retained readings may be stale. Start the configured engine host, then retry.")}</p></details> : null)}
115    </div>);
116}
117/**
118 * The only chrome focus mode keeps: what is loaded, what it is doing, and the
119 * way out. Everything else on this screen is the conversation.
120 */
121function FocusBar() {
122    // The hints are chords, not decorations: on Windows the modifier is Ctrl and
123    // Alt is spelled out, because ⌘ and ⌥ are not on that keyboard.
124    const mac = MOD === '⌘';
125    const native = useNative(), nativeCurrent = native?.instances.find(i => i.id === native.defaultId);
126    const library = useStore((s) => s.library);
127    const monitor = useStore((s) => s.monitor);
128    const model = library?.variants.find((v) => v.id === library.loaded) ?? null;
129    const phase = nativeCurrent ? (nativeCurrent.status === 'ready' ? nativeCurrent.phase : nativeCurrent.status) : monitor?.phase ?? 'idle';
130    const state = ['error', 'unavailable'].includes(phase) ? 'idle' : phase === 'generating' || phase === 'reading' || phase === 'thinking' ? 'busy' : model || nativeCurrent ? 'ready' : 'idle';
131    return (<div className="focusbar" data-state={state}>
132      <span className="focusbar__dot"/>
133      <span className="strong" style={{ color: 'var(--st-ink)' }}>
134        {tr(nativeCurrent?.label ?? model?.label ?? 'No model loaded')}
135      </span>
136      <span>
137        {tr(phase === 'reading'
138            ? 'reading prompt'
139            : phase === 'generating'
140                ? `generating · ${(nativeCurrent ? nativeCurrent.metrics?.live?.tok_s ?? 0 : monitor?.outputTps ?? 0).toFixed(1)} tok/s`
141                : phase === 'thinking'
142                    ? 'thinking'
143                    : phase === 'error' ? 'engine error' : phase === 'unavailable' ? 'status unavailable' : phase === 'loading' ? 'loading' : model || nativeCurrent ? 'ready' : 'no model loaded')}
144      </span>
145      <span className="spacer"/>
146      {/* Grouped, so each hint reads as one instruction rather than a row of
147            loose keycaps. */}
148      <span className="focusbar__keys">
149        <span>
150          {/* A chord reads as one key: the two caps sit tight together, with
151            the space before the label doing the separating. */}
152          <span className="focusbar__chord">
153            <kbd>{mac ? '⌥↑' : 'Alt+↑'}</kbd>
154            <kbd>{mac ? '⌥↓' : 'Alt+↓'}</kbd>
155          </span>{tr("turns")}</span>
156        <span>
157          <kbd>{mac ? '⌘↓' : 'Ctrl+↓'}</kbd>{tr(" latest")}</span>
158        <span>
159          <kbd>{tr("Esc")}</kbd>{tr(" leave")}</span>
160      </span>
161      {/* The quietest control in the bar. It was the loudest thing in a mode
162            whose whole purpose is to remove chrome. */}
163      <IconBtn name="x" title={tr("Leave focus mode")} onClick={() => setFocus(false)}/>
164    </div>);
165}
166function RouteView({ route }: {
167    route: string;
168}) {
169    switch (route) {
170        case 'chat':
171            return <ChatScreen />;
172        case 'models':
173        case 'tuning':
174            return <ModelRunScreen />;
175        case 'serving':
176            return <ServingScreen />;
177        case 'monitor':
178            return <MonitorScreen />;
179        case 'tasks':
180            return <TasksScreen />;
181        case 'skills':
182            return <SkillsScreen />;
183        default:
184            return <ChatScreen />;
185    }
186}
187function BootSkeleton() {
188    return (<>
189      <header className="main__head">
190        <div className="col" style={{ gap: 8 }}>
191          <div className="skel" style={{ width: 180, height: 24 }}/>
192          <div className="skel" style={{ width: 320, height: 14 }}/>
193        </div>
194      </header>
195      <div className="main__body">
196        <div className="wrap stack">
197          <div className="skel" style={{ height: 20, width: '60%' }}/><div className="skel" style={{ height: 20, width: '80%' }}/><div className="skel" style={{ height: 20, width: '70%' }}/>
198        </div>
199      </div>
200    </>);
201}
202class AppBoundary extends Component<{
203    children: ReactNode;
204}, {
205    failed: boolean;
206}> {
207    state = { failed: false };
208    static getDerivedStateFromError() { return { failed: true }; }
209    render() {
210        if (!this.state.failed)
211            return this.props.children;
212        return <div className="app-recovery"><h1 className="h2">{tr("Strata couldn\u2019t show this screen")}</h1><p>{tr("Your saved conversations and settings are still available.")}</p><Btn variant="primary" onClick={() => { void bootstrap().then(() => this.setState({ failed: false })); }}>{tr("Retry")}</Btn></div>;
213    }
214}
215export function App() { return <AppBoundary><AppShell /></AppBoundary>; }