okami.mom/strata

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

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
11.1 KiB180 linesraw
1import { tr } from '../lib/i18n';
2import { useCallback, useEffect, useRef, useState } from 'react';
3import { Brand } from './Brand';
4import { Bar, Btn, Icon } from './ui';
5import { api } from '../lib/client';
6import { useDownloadEta } from '../lib/download-eta';
7import type { NativeJob } from '../lib/native';
8import { megabytes } from '../lib/format';
9import { FirstRunLanguage } from './FirstRunLanguage';
10
11/** What the host says about this PC's engine (GET /api/engine/first-run). */
12export interface FirstRunInfo {
13    status: 'offer' | 'none' | 'offline' | 'error' | 'installed' | 'wrong-make' | 'unavailable';
14    gpus: { name: string; vramGb: number | null }[];
15    driver?: string | null;
16    offer?: { version: string; bytes: number; variant: string; backend: string | null };
17    /** A newer Strata Control in the same feed: the Download takes it too (the Arc fix of 0.2.13.1 came this way). */
18    control?: { version: string; bytes: number } | null;
19    message?: string | null;
20    reasons?: string[];
21    details?: string;
22    freeBytes?: number;
23}
24
25export const mb = megabytes;
26/** After the size when the download also brings the newer Strata Control (owner-approved wording, 11-09). */
27export const WITH_CONTROL = " (with the Strata setup update)";
28
29/**
30 * Whether this PC still needs its engine. Reads only Control's local answer (no network): the engine is missing and the engine that came
31 * with the app is not being unpacked. `null` while that is not known yet.
32 */
33export function useEngineNeeded(): boolean | null {
34    const [needed, setNeeded] = useState<boolean | null>(null);
35    useEffect(() => {
36        let live = true;
37        const ask = () => api.get<{ engine?: { usable?: boolean } | null; engineSetup?: boolean }>('/api/control/status').then(s => {
38            if (!live) return;
39            if (s.engineSetup) return setNeeded(null);
40            setNeeded(!!s.engine && s.engine.usable === false);
41        }, () => { if (live) setNeeded(false); });
42        void ask();
43        const timer = setInterval(() => void ask(), 3000);
44        return () => { live = false; clearInterval(timer); };
45    }, []);
46    return needed;
47}
48
49function gpuLine(info: FirstRunInfo) {
50    // a processor's own tiny graphics (no memory of its own) is not "a card"
51    const first = info.gpus.find(g => (g.vramGb ?? 0) >= 1) ?? info.gpus[0];
52    if (!first) return '';
53    const vram = first.vramGb ? `, ${Math.round(first.vramGb)} GB` : '';
54    const driver = info.driver ? `, driver ${info.driver}` : '';
55    return `${first.name}${vram}${driver}`;
56}
57
58/**
59 * The first-run card: the engine this PC needs, one button to download it, progress, and the offline way (choose a downloaded file).
60 * Nothing is downloaded before a button is pressed.
61 */
62export function EngineFirstRun({ onDone }: { onDone: () => void }) {
63    const [info, setInfo] = useState<FirstRunInfo | null>(null);
64    const [job, setJob] = useState<NativeJob | null>(null);
65    const [busy, setBusy] = useState(false), [problem, setProblem] = useState('');
66    const [finished, setFinished] = useState(false);
67    const file = useRef<HTMLInputElement>(null);
68    const started = useRef(false);
69
70    const look = useCallback(() => {
71        setInfo(null);
72        setProblem('');
73        api.get<FirstRunInfo>('/api/engine/first-run').then(setInfo, e => setInfo({ status: 'error', gpus: [], message: e instanceof Error ? e.message : String(e) }));
74    }, []);
75    useEffect(() => { look(); }, [look]);
76
77    // follow the download / install job
78    useEffect(() => {
79        const timer = setInterval(() => {
80            if (!started.current) return;
81            api.get<{ job: NativeJob | null }>('/api/engine/job').then(r => {
82                setJob(r.job);
83                if (r.job?.state === 'done') setFinished(true);
84                if (r.job && r.job.state !== 'running') started.current = false;
85            }, () => { });
86        }, 700);
87        return () => clearInterval(timer);
88    }, []);
89
90    async function start() {
91        setBusy(true);
92        setProblem('');
93        try {
94            started.current = true;
95            setJob(await api.post<NativeJob>('/api/native/operations', { kind: 'update-engine', args: { firstRun: true, ...(info?.control ? { withControl: true } : {}) } }));
96        }
97        catch (e) {
98            started.current = false;
99            setProblem(e instanceof Error ? e.message : String(e));
100        }
101        finally {
102            setBusy(false);
103        }
104    }
105    async function chosen(files: FileList | null) {
106        const picked = files?.[0];
107        if (!picked) return;
108        setBusy(true);
109        setProblem('');
110        try {
111            const response = await fetch('/api/engine/from-file', { method: 'POST', headers: { 'x-file-name': picked.name }, body: picked });
112            const body = await response.json().catch(() => ({}));
113            if (!response.ok) throw new Error(body?.error ?? `The file could not be used (${response.status}).`);
114            started.current = true;
115            setJob(body as NativeJob);
116        }
117        catch (e) {
118            setProblem(e instanceof Error ? e.message : String(e));
119        }
120        finally {
121            setBusy(false);
122            if (file.current) file.current.value = '';
123        }
124    }
125
126    const running = job?.state === 'running';
127    const failed = !!job && (job.state === 'error' || job.state === 'cancelled');
128    const percent = Number(job?.result?.install?.download?.percent ?? 0);
129    const bytes = info?.offer?.bytes ?? 0;
130    const doneMb = Math.round(mb(bytes) * percent / 100);
131    const eta = useDownloadEta(running && bytes ? { done_gb: bytes * percent / 100 / 1e9, remaining_gb: bytes * (100 - percent) / 100 / 1e9 } : undefined, job?.id);
132    const cards = (info?.gpus ?? []).filter(g => (g.vramGb ?? 0) >= 1).length;
133    const hidden = <input ref={file} type="file" accept=".gz,.tgz,.xz,.zip" hidden onChange={e => void chosen(e.target.files)}/>;
134    const pick = (label: string) => <button type="button" className="onboard-continue-anyway" disabled={busy || running} onClick={() => file.current?.click()}>{tr(label)}</button>;
135
136    let body;
137    if (finished) {
138        body = <><div className="onboard-welcome-copy"><h1 tabIndex={-1} data-initial-focus>{tr("The engine is ready.")}</h1><p>{tr("Next: pick a model.")}</p></div>
139            <footer className="onboard-footer onboard-footer--welcome"><Btn variant="primary" onClick={onDone}>{tr("Continue")}<Icon name="chevron" size={16}/></Btn></footer></>;
140    }
141    else if (running) {
142        body = <><div className="onboard-welcome-copy"><h1 tabIndex={-1} data-initial-focus>{tr("Downloading the engine")}</h1>
143            <p>{bytes && job?.result?.install?.download ? `${doneMb} of ${mb(bytes)} MB${eta ? ' · ' + eta : ''}` : tr(job?.summary ?? 'Starting…')}</p></div>
144            <div className="onboard-error" style={{ maxWidth: 520, margin: '0 auto', width: '100%' }}><Bar value={percent} label="Downloading the engine"/><p className="small muted" style={{ textAlign: 'center' }}>{tr("You can close Strata; it continues where it stopped.")}</p></div></>;
145    }
146    else if (!info) {
147        body = <div className="onboard-welcome-copy"><h1 tabIndex={-1} data-initial-focus>{tr("Welcome to Strata")}</h1><p role="status">{tr("Looking at your graphics card…")}</p></div>;
148    }
149    else {
150        const card = gpuLine(info);
151        const found = card ? <p>{tr("Strata found your graphics card:")}<br/><strong>{card}</strong>{cards > 1 ? <><br/><span className="small muted">{tr("{0} cards found. Strata uses the first one for the engine; change it later in Settings.", [cards])}</span></> : null}</p>
152            : <p>{tr("Strata did not recognise a supported graphics card.")}</p>;
153        let main, actions;
154        if (info.status === 'offer' && info.offer) {
155            main = <>{found}<p>{tr("To run models on it, Strata needs one download:")}<br/><strong>{tr("The engine for this card")}: {mb(info.offer.bytes + (info.control?.bytes ?? 0))} MB{info.control ? tr(WITH_CONTROL) : null}</strong></p>
156                {info.freeBytes !== undefined && info.freeBytes < info.offer.bytes * 2.5 ? <p className="small inline-error">{tr("The engine needs about {0} GB of free space on this drive and only {1} GB is free. Free some space, then continue.", [Math.ceil(info.offer.bytes * 2.5 / 1e9), (info.freeBytes / 1e9).toFixed(1)])}</p> : null}
157                <p className="small muted">{tr("It comes from Strata’s own update server and is checked before it is used. Your models and chats are never touched by it.")}</p></>;
158            actions = <><Btn variant="primary" disabled={busy} onClick={() => void start()}>{tr(failed ? 'Continue' : 'Download the engine')}</Btn>{pick("I already have the file…")}</>;
159        }
160        else if (info.status === 'offline') {
161            main = <>{found}<p>{tr("Strata could not reach github.com. Check your connection and try again, or download the engine file on another PC and choose it here.")}</p></>;
162            actions = <><Btn variant="primary" disabled={busy} onClick={look}>{tr("Try again")}</Btn>{pick("Choose a downloaded file…")}</>;
163        }
164        else if (info.status === 'wrong-make') {
165            main = <>{found}<p>{info.message ?? tr("The engine installed here is for another make of graphics card.")}</p></>;
166            actions = <><Btn variant="primary" disabled={busy} onClick={look}>{tr("Try again")}</Btn>{pick("Choose a downloaded file…")}</>;
167        }
168        else {
169            main = <>{found}<p>{tr("Strata can’t pick an engine for this PC from its update list.")}</p>{info.message ? <p className="small muted">{info.message}</p> : null}{(info.reasons ?? []).length ? <ul className="small muted" style={{ textAlign: 'left', display: 'inline-block' }}>{(info.reasons ?? []).map(r => <li key={r}>{r}</li>)}</ul> : null}</>;
170            actions = <><Btn variant="primary" disabled={busy} onClick={look}>{tr("Try again")}</Btn>{pick("Choose a downloaded file…")}<button type="button" className="onboard-continue-anyway" onClick={onDone}>{tr("Continue without an engine")}</button></>;
171        }
172        body = <><div className="onboard-welcome-copy"><h1 tabIndex={-1} data-initial-focus>{tr("Welcome to Strata")}</h1>{main}</div>
173            {failed ? <div className="onboard-error" style={{ maxWidth: 560, margin: '0 auto' }}><p role="alert" className="small inline-error">{job?.error ?? job?.summary}</p>
174                {job?.details ? <details className="error-detail"><summary className="small">{tr('Details')}</summary><pre className="small muted">{job.details}</pre></details> : null}
175                <p className="small muted">{percent >= 100 ? tr("The file was downloaded. Continue tries the install again.") : tr("The download stopped. Continue picks it up where it stopped.")}</p></div> : null}
176            {problem ? <div className="onboard-error" style={{ maxWidth: 560, margin: '0 auto' }}><p role="alert" className="small inline-error">{problem}</p></div> : null}
177            <footer className="onboard-footer onboard-footer--welcome">{actions}</footer></>;
178    }
179    return <div className="setup guided-onboarding" data-step="engine">{hidden}<header className="onboard-header"><Brand variant="lockup" height={22}/><FirstRunLanguage/></header>{body}</div>;
180}