okami.mom/strata

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

Niko1221Merge f-dl99-fixes: the Qwen3.6 first-run download (no engine-race stop, no cancelled engine download, progress to 100%, the picture reader's real figure, the engine-not-ready sentence)361c8d94a

main
30.1 KiB282 linesraw
1import { tr } from '../lib/i18n';
2import { useEffect, useRef, useState, type KeyboardEvent } from 'react';
3import { Brand } from './Brand';
4import { Btn, ErrorNotice, Icon, Select } from './ui';
5import { OnboardingArt, OnboardingTour } from './OnboardingArt';
6import { OnboardingMemory } from './OnboardingMemory';
7import { OnboardingResources } from './OnboardingResources';
8import { OnboardingCheckbox } from './OnboardingCheckbox';
9import { api } from '../lib/client';
10import { navigate } from '../lib/router';
11import { nativeAction, useNative, type NativeJob } from '../lib/native';
12import { completeSetup, completeSetupStep, go, newSession, openSetup, selectRemoteModel, setSettingsSection, useStore } from '../lib/store';
13import type { LocalModelFolder, SetupState } from '../lib/types';
14import { downloadCounter, engineNotReadyAfterInstall, modelFolderLabel, onboardingError } from '../lib/onboarding-download';
15import { guidedStatusText, installProgress, useDownloadEta } from '../lib/download-eta';
16import { VersionPicker } from './VersionPicker';
17import { contextIsTight, defaultContext } from '../lib/default-context';
18import { contextCacheGb } from '../lib/native-fit';
19import { FirstRunLanguage } from './FirstRunLanguage';
20import { DownloadParts } from './DownloadParts';
21import { EngineWarning } from './EngineWarning';
22import { OTHER_NOTE, PICK_NOTE, cardRoomGb, recommendedVersions } from '../lib/native-fit';
23import { nativeCatalogModels, catalogVersionLabel, startingChoice } from '../lib/native-catalog';
24type Choices = NonNullable<NonNullable<SetupState['choices']>['onboarding']>;
25function radioKeys(event: KeyboardEvent<HTMLDivElement>) { if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key))
26    return; event.preventDefault(); const items = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>('[role=radio]')); const current = items.indexOf(event.target as HTMLButtonElement); const next = event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1 : (current + (['ArrowLeft', 'ArrowUp'].includes(event.key) ? -1 : 1) + items.length) % items.length; items[next]?.focus(); items[next]?.click(); }
27const steps = ['Welcome', 'Your model', 'Prepare', 'Make it yours'];
28export function GuidedSetup() {
29    const native = useNative(), setup = useStore(s => s.setup), hardware = useStore(s => s.hardware);
30    const families = nativeCatalogModels(native?.catalog?.families ?? []);
31    const saved = !setup?.complete && !setup?.choices?.onboarding?.manual ? setup?.choices?.onboarding : undefined;
32    const [step, setStep] = useState(saved?.manual || setup?.complete ? 1 : saved?.step ?? 1);
33    /* Only what the person (or an earlier visit) chose is state. Until then the start is worked out from the catalog on every render: a model already
34       on this computer first, else the catalog's recommendation. The state used to be filled once at mount, before the catalog had arrived, and
35       so fell back to the first size in the list (Q2_0, a 66 GB download) while an installed model sat beside it. */
36    const [chosenFamily, setFamily] = useState(saved?.family ?? ''), [chosenSize, setSize] = useState(saved?.size ?? '');
37    const start = startingChoice(families, (native?.installed?.models ?? []).filter(m => m.ready).map(m => m.model), native?.catalog?.recommendation);
38    const family = chosenFamily || start?.family || native?.catalog?.recommendation?.family || families[0]?.family || '';
39    const size = chosenSize || start?.size || '';
40    /* 128K for every configuration unless the person picks another, on every card. The warning for a card
41       it leaves little room on is under the chooser; nothing is lowered. */
42    const topCardGb = Math.max(0, ...(native?.hardware?.gpus ?? []).filter(g => g.usable !== false).map(g => g.vram_gb));
43    const [pickedContext, setContext] = useState<number | undefined>(saved?.context), [contextTouched, setContextTouched] = useState(false);
44    const [vision, setVision] = useState(saved?.vision ?? true), [directory, setDirectory] = useState(saved?.directory ?? '');
45    const [profile, setProfile] = useState<'work' | 'performance'>(saved?.profile ?? 'work');
46    const [installJobId, setInstallJobId] = useState(saved?.installJobId ?? ''), [tuneJobId, setTuneJobId] = useState(saved?.tuneJobId ?? '');
47    const [plan, setPlan] = useState<Record<string, any> | null>(null), [tour, setTour] = useState(0), [folderOpen, setFolderOpen] = useState(false);
48    const [pending, setPending] = useState(false), [checkingPlan, setCheckingPlan] = useState(false), [error, setError] = useState(''), [calibrate, setCalibrate] = useState(saved?.calibrate ?? true);
49    const writes = useRef(Promise.resolve()), leaving = useRef(false), saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null), titleRef = useRef<HTMLHeadingElement>(null);
50    const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0];
51    const version = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0];
52    const installed = native?.installed?.models.find(m => m.model === version?.id);
53    const contextList = native?.catalog?.contexts ?? [131072];
54    const context = pickedContext ?? defaultContext(contextList);
55    const installJob = native?.jobs.find(j => j.id === installJobId) ?? (step === 3 ? native?.jobs.find(j => j.kind === 'install' && j.state === 'running' && j.guided && j.model === version?.model) : undefined), tuneJob = native?.jobs.find(j => j.id === tuneJobId) ?? (step === 4 ? native?.jobs.find(j => j.kind === 'tune' && j.state === 'running' && j.guided && j.model === version?.id) : undefined);
56    const active = native?.jobs.find(j => j.state === 'running');
57    const ready = native?.instances.some(i => i.model === version?.id && i.status === 'ready');
58    const folder = directory || native?.downloadDirectory || native?.installed?.data_folder || setup?.app.modelsDir || '';
59    const choices: Choices = { step, family: selectedFamily?.family, size: version?.id, context, vision, directory, profile, installJobId, tuneJobId, calibrate };
60    function persist(next: number, patch: Partial<Choices> = {}, dismissed = false) {
61        const value = { ...choices, step: next, ...patch };
62        const work = writes.current.catch(() => { }).then(() => completeSetupStep(Math.min(4, next), { onboarding: value }, dismissed));
63        writes.current = work;
64        return work;
65    }
66    async function perform(action: () => Promise<void>) { setPending(true); setError(''); try {
67        await action();
68    }
69    catch (e) {
70        setError(e instanceof Error ? e.message : String(e));
71    }
72    finally {
73        setPending(false);
74    } }
75    async function advance(next: number, patch: Partial<Choices> = {}) { await persist(next, patch); setStep(next); setError(''); }
76    async function skip(manual = false, section?: 'Engine' | 'Models') {
77        await perform(async () => { leaving.current = true; if (saveTimer.current)
78            clearTimeout(saveTimer.current); try {
79            await persist(step, { manual }, true);
80            openSetup(false);
81            if (section) {
82                setSettingsSection(section);
83                navigate('chat', undefined, { settings: '1' });
84            }
85            else
86                go(manual || preparing ? 'models' : 'chat');
87        }
88        catch (e) {
89            leaving.current = false;
90            throw e;
91        } });
92    }
93    /* Files the person already has are checked and adopted by the "Use a local GGUF" page, not made the data folder (that downloaded them again, #3507). */
94    async function ownModel(path?: string) {
95        await perform(async () => { leaving.current = true; if (saveTimer.current)
96            clearTimeout(saveTimer.current); try {
97            await persist(step, { manual: true }, true);
98            openSetup(false);
99            navigate('models', 'local', path ? { path } : undefined);
100        }
101        catch (e) {
102            leaving.current = false;
103            throw e;
104        } });
105    }
106    async function finish() {
107        if (leaving.current)
108            return;
109        leaving.current = true;
110        if (saveTimer.current)
111            clearTimeout(saveTimer.current);
112        try {
113            await writes.current;
114            await completeSetup();
115            selectRemoteModel(null);
116            openSetup(false);
117            const chat = newSession();
118            go('chat', chat.id);
119        }
120        catch (e) {
121            leaving.current = false;
122            setError(e instanceof Error ? e.message : String(e));
123        }
124    }
125    function chooseNative(family: string, size: string) { setFamily(family); setSize(size); setVision(true); setPlan(null); setError(''); }
126    useEffect(() => { titleRef.current?.focus({ preventScroll: true }); titleRef.current?.closest('.setupmodal__surface')?.scrollTo({ top: 0 }); }, [step]);
127    useEffect(() => {
128        if (step < 2 || leaving.current)
129            return;
130        saveTimer.current = setTimeout(() => { void persist(step).catch(e => setError(e.message)); }, 450);
131        return () => { if (saveTimer.current)
132            clearTimeout(saveTimer.current); };
133    }, [step, family, size, context, vision, directory, profile, calibrate, installJobId, tuneJobId]);
134    useEffect(() => {
135        if (step === 3 && installJob?.state === 'done' && installed?.ready)
136            void advance(4).catch(e => setError(e.message));
137    }, [installJob?.state, installed?.ready, step]);
138    useEffect(() => { if (step === 4 && tuneJob?.state === 'done' && ready)
139        void finish(); }, [tuneJob?.state, ready, step]);
140    useEffect(() => { if (step === 3 && installJob?.state === 'running' && !installJobId) {
141        setInstallJobId(installJob.id);
142        void persist(3, { installJobId: installJob.id }).catch(e => setError(e.message));
143    } if (step === 4 && tuneJob?.state === 'running' && !tuneJobId) {
144        setTuneJobId(tuneJob.id);
145        void persist(4, { tuneJobId: tuneJob.id }).catch(e => setError(e.message));
146    } }, [step, installJob?.id, tuneJob?.id]);
147    const values = { guided: true, family: version?.sourceFamily, model: version?.model, context, ...(contextTouched ? { contextChosen: true } : {}), vision: version?.images ? 'yes' : 'no', kv: 'int8', low_ram: 'auto', loadAfter: false, multiple: false, ...(directory ? { data_dir: directory } : {}) };
148    async function review() {
149        await perform(async () => {
150            setInstallJobId('');
151            setTuneJobId('');
152            if (installed?.ready && installed.context === context && (!version?.images || installed.images && installed.images !== 'off') && (!directory || directory === installed.dataFolder)) {
153                await advance(4, { installJobId: '', tuneJobId: '' });
154                return;
155            }
156            setPlan(await api.post('/api/native/plan', values));
157            await advance(3, { installJobId: '', tuneJobId: '' });
158        });
159    }
160    async function download() {
161        await perform(async () => {
162            const result = await nativeAction<NativeJob>('operations', { kind: 'install', args: values });
163            setInstallJobId(result.id);
164            await persist(3, { installJobId: result.id });
165        });
166    }
167    async function tune() {
168        await perform(async () => {
169            const result = await nativeAction<NativeJob>('operations', { kind: 'tune', args: { guided: true, model: version?.id, profile, calibrate, vision: version?.images && vision ? 'yes' : 'no', multiple: false } });
170            setTuneJobId(result.id);
171            await persist(4, { tuneJobId: result.id });
172        });
173    }
174    const progress = installProgress(installJob?.result?.install);
175    const preparing = installJob?.state === 'running';
176    const stopped = installJob && ['error', 'cancelled'].includes(installJob.state);
177    useEffect(() => {
178        if (step !== 3 || plan || preparing || !native?.available || !version) {
179            setCheckingPlan(false);
180            return;
181        }
182        let cancelled = false;
183        setCheckingPlan(true);
184        api.post<Record<string, any>>('/api/native/plan', values).then(value => { if (!cancelled) {
185            setPlan(value);
186            setCheckingPlan(false);
187        } }).catch(e => { if (!cancelled) {
188            setError(e.message);
189            setCheckingPlan(false);
190        } });
191        return () => { cancelled = true; };
192    }, [step, plan, preparing, native?.available, version?.id, context, directory]);
193    const recommendedRows = recommendedVersions(selectedFamily?.sizes ?? [], native?.catalog?.recommendation);
194    const recommendedCards = recommendedRows.map(x => x.v);
195    const pickNote = (v: { id: string }) => recommendedRows.find(x => x.v.id === v.id && [PICK_NOTE, OTHER_NOTE].includes(x.r.note))?.r.note ?? '';
196    // The recommended four first, then a list with every other version (the Models page's version list); a family without a recommended set shows them all.
197    const cards = recommendedCards.length ? recommendedCards : selectedFamily?.sizes ?? [];
198    const others = recommendedCards.length ? (selectedFamily?.sizes ?? []).filter(v => !recommendedCards.includes(v)) : [];
199    const readyIds = new Set((native?.installed?.models ?? []).filter(m => m.ready).map(m => m.model));
200    const versionCard = (v: NonNullable<typeof version>) => <button key={v.id} type="button" role="radio" tabIndex={version?.id === v.id ? 0 : -1} aria-checked={version?.id === v.id} data-selected={version?.id === v.id} onClick={() => { setSize(v.id); setPlan(null); }}><span className="onboard-version-top"><span className="onboard-version-copy"><strong>{tr(catalogVersionLabel(v))}</strong><small>{tr(v.model)}{tr(pickNote(v) ? <> · {tr(pickNote(v))}</> : null)}</small></span><span className="onboard-version-radio">{tr(version?.id === v.id ? <Icon name="check" size={12}/> : null)}</span></span><span className="onboard-version-bottom"><span className="onboard-version-size"><Icon name="download" size={15}/>{tr(v.download_gb.toFixed(1))} <small>{tr("GB")}</small></span><span className="onboard-version-fit">{tr(v.on_this_pc === 'does not fit' || v.on_this_pc === 'tight' || v.on_this_pc?.includes('slower') || v.on_this_pc?.startsWith('experimental:') ? <><Icon name="clock" size={13}/>{tr("May run slower")}</> : v.installed ? <><Icon name="check" size={13}/>{tr("On this computer")}</> : <>{tr("Download size")}</>)}</span></span></button>;
201    const counter = downloadCounter(plan?.plan?.download_gb ?? version?.download_gb, progress, preparing);
202    const eta = useDownloadEta(preparing ? progress : undefined, installJob?.id);
203    const title = step === 1 ? 'State of the art. At home.' : step === 2 ? 'Select the model you want to run.' : step === 3 ? 'Downloading the model...' : tuneJob?.state === 'running' ? 'A little tuning. A better fit.' : 'How you would like to work with Strata?';
204    function changeDownloadFolder() { void perform(async () => { await advance(2); setFolderOpen(true); }); }
205    return <div className="setup guided-onboarding" data-step={step}>
206  <header className="onboard-header"><Brand variant="lockup" height={22}/>{tr(step === 1 ? <FirstRunLanguage/> : null)}{tr(step !== 1 ? <button className="onboard-later" disabled={pending} onClick={() => void skip(false)}>{tr("Finish later")}<Icon name="chevron" size={13}/></button> : null)}</header>
207  <div className="onboard-stepper" aria-label={tr("Setup progress")}>{tr(steps.map((label, i) => <div key={label} data-current={step === i + 1} data-done={step > i + 1} aria-current={step === i + 1 ? 'step' : undefined}><span>{tr(step > i + 1 ? <Icon name="check" size={12}/> : i + 1)}</span><small>{tr(label)}</small></div>))}</div>
208  {tr(step === 1 ? <>
209   <OnboardingArt />
210   <div className="onboard-welcome-copy"><h1 ref={titleRef} tabIndex={-1} data-initial-focus>{tr(title)}</h1><p>{tr("Get stuff done on hardware you own.")}<br />{tr("Use intelligence the way you want.")}</p><div className="onboard-benefits"><span><Icon name="shield" size={17}/>{tr("Privacy first")}</span><span><Icon name="bolt" size={17}/>{tr("Fastest AI")}</span><span><Icon name="check" size={17}/>{tr("Easy to use")}</span></div></div>
211   <footer className="onboard-footer onboard-footer--welcome"><Btn variant="primary" disabled={pending || !native} onClick={() => void perform(() => advance(2))}>{tr("Let\u2019s get started")}<Icon name="chevron" size={16}/></Btn><small>{tr("Already know your way around? ")}<button disabled={pending} onClick={() => void skip(true)}>{tr("Go straight to the app")}</button></small></footer>
212  </> : <>
213   <div className="onboard-stage-heading"><h1 ref={titleRef} tabIndex={-1} data-initial-focus>{tr(title)}</h1>{tr(step === 2 ? <p>{tr("You can always change your models later.")}</p> : step === 4 && tuneJob?.state === 'running' ? <p>{tr("We\u2019re measuring, applying your preference, and getting ready to chat.")}</p> : null)}</div>
214   {tr(step === 2 ? <div className="onboard-model-stage">
215    {tr(selectedFamily ? <>
216     <div className="onboard-model-top"><div className="onboard-model-picker"><span className="onboard-control-label">{tr("Model")}</span><div><span className="onboard-model-symbol"><Icon name="models" size={23}/></span><Select ariaLabel={tr("Setup model")} value={selectedFamily.family} options={families.map(f => ({ value: f.family, label: f.title }))} onChange={value => chooseNative(value, '')}/></div></div><div className="onboard-context"><span className="onboard-control-label">{tr("Conversation context")}</span><Select ariaLabel={tr("Setup conversation context")} value={String(context)} options={contextList.map(n => ({ value: String(n), label: `${n / 1024}K` }))} onChange={value => { setContextTouched(true); setContext(Number(value)); }}/></div></div>
217     {tr(contextIsTight(topCardGb, context, 'int8', version?.context_fit) ? <p className="small muted native-spill-note"><Icon name="warning" size={16}/>{tr("This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context.", [contextCacheGb(context, 'int8', version?.context_fit).toFixed(1)])}</p> : null)}
218     <OnboardingMemory hardware={hardware} native={native?.hardware}/>{tr(!version || version.needsNewerEngine ? <p className="small muted">{tr("This model needs a newer engine. Update your engine or import a local GGUF for this model.")}</p> : null)}
219     <div className="onboard-version-heading"><strong>{tr("Choose a version")}</strong><span>{tr(version ? `${catalogVersionLabel(version)} selected` : '')}</span></div>
220     <div className="onboard-versions" role="radiogroup" aria-label={tr("Model version")} onKeyDown={radioKeys}>{tr(cards.map(v => versionCard(v)))}</div>
221     {tr(others.length ? <div className="onboard-more-versions"><VersionPicker versions={others} selectedId={version?.id ?? ''} hardware={hardware ? { ram_gb: native?.hardware?.ram_gb ?? hardware.memory.totalGb, vram_gb: cardRoomGb((native?.hardware?.gpus ?? []).filter(g => g.usable !== false)) } : null} downloaded={readyIds} showRecommended={false} moreLabel="More versions" onSelect={id => { setSize(id); setPlan(null); }} onOwnGguf={() => void ownModel()}/></div> : null)}
222     <div className="onboard-folder"><Icon name="folder" size={20}/><div><strong>{tr(directory ? 'Your model folder' : 'Already downloaded the model?')}</strong><small>{tr(directory || "Choose the folder and we'll start your models with Strata.")}</small></div><Btn size="sm" onClick={() => setFolderOpen(v => !v)}>{tr(folderOpen ? 'Close' : directory ? 'Change' : 'Choose folder')}</Btn></div>
223     {tr(folderOpen ? <OnboardingFolder directory={folder} onChoose={(path, ggufFiles) => ggufFiles > 0 && !/strata/i.test(path.split(/[\\/]/).filter(Boolean).pop() ?? '') ? void ownModel(path) : void perform(async () => { await nativeAction('directory', { directory: path }); setDirectory(path); setFolderOpen(false); setPlan(null); })}/> : null)}
224    </> : <div className="onboard-engine-connect"><Icon name="models" size={24}/><strong>{tr("Connect your Strata installation")}</strong><Btn onClick={() => void skip(false, 'Engine')}>{tr("Connect engine")}</Btn></div>)}
225   </div> : step === 3 ? <div className="onboard-prepare-stage">
226    <section className="onboard-download"><EngineWarning native={native}/><div className="onboard-download-identity"><Icon name="models" size={19}/><strong>{tr(selectedFamily?.title)}</strong><span>{tr(version ? catalogVersionLabel(version) : '')}</span><small>{tr(version?.model)}</small></div><OnboardingArt kind="download" progress={progress?.percent ?? 0} counter={counter}/><div className="onboard-download-info">
227     {tr(preparing ? <div><strong className="onboard-download-status">{tr(guidedStatusText(installJob?.result?.install, progress))}</strong><div className="onboard-progress" data-indeterminate={!progress}>{tr(progress ? <progress max={100} value={progress.percent ?? 0} aria-label={tr("Current file download progress")}/> : <span />)}</div><DownloadParts parts={installJob?.result?.install?.parts}/><div className="onboard-progress-meta"><span>{tr(progress ? `${progress.percent ?? 0}%${Number.isFinite(progress.done_gb) && Number.isFinite(progress.total_gb) ? ` · ${progress.done_gb!.toFixed(1)} / ${progress.total_gb!.toFixed(1)} GB` : ''}` : 'Getting files ready…')}</span><div className="onboard-progress-actions">{tr(eta ? <span aria-live="off">{eta}</span> : null)}<button disabled={pending} onClick={() => void perform(async () => { await nativeAction(`operations/${installJob!.id}/cancel`); })}>{tr("Stop")}</button></div></div></div> : <>{tr(stopped ? <OnboardingError message={installJob?.error ?? 'Download stopped. Ready when you are.'} onFolder={changeDownloadFolder}/> : null)}{tr(engineNotReadyAfterInstall(installJob?.state, installed?.ready, native?.engine?.usable) ? <div className="engine-warning" role="status"><Icon name="info" size={18}/><div><p>{tr("Your model is downloaded, but the engine for this PC isn't ready yet. Open Settings > About to install it.")}</p></div></div> : null)}{tr(plan?.plan?.disk_short ? <OnboardingError message={plan.plan.disk_short} onFolder={changeDownloadFolder}/> : null)}</>)}
228     <small className="onboard-download-location" title={tr(folder)}><Icon name="folder" size={16}/><span><span>{tr("Save to")}</span><strong>{tr(modelFolderLabel(folder))}</strong></span>{tr(!preparing ? <button type="button" onClick={changeDownloadFolder}>{tr("Change")}</button> : null)}</small>
229    </div></section><OnboardingTour page={tour} onChange={setTour}/>
230   </div> : <div className="onboard-tune-stage">
231    {tr(tuneJob?.state === 'running' ? <><OnboardingArt kind="tune"/><div className="onboard-tuning-status" aria-live="polite"><span className="onboard-pulse-dot"/><strong>{tr(tuneJob.summary)}</strong><small>{tr("Your choice: ")}{tr(profile === 'work' ? '20% headroom for other work' : 'Full performance')}</small><div className="onboard-progress" data-indeterminate><span /></div><button disabled={pending} onClick={() => void perform(async () => { await nativeAction(`operations/${tuneJob.id}/cancel`); })}>{tr("Stop tuning")}</button></div><OnboardingTour page={tour} onChange={setTour}/></> : <>
232     <OnboardingResources profile={profile}/>
233     <div className="onboard-resource-options" role="radiogroup" aria-label={tr("Computer resource preference")} onKeyDown={radioKeys}>{tr(([{ id: 'work', icon: 'computer', title: 'Leave room for my work', hint: 'Keeps 5-8 GB of memory free for other programs.', badge: 'Everyday choice' }, { id: 'performance', icon: 'bolt', title: 'Use full performance', hint: 'Focus this computer on your AI.', badge: '100% priority' }] as const).map(option => <button key={option.id} role="radio" tabIndex={profile === option.id ? 0 : -1} aria-checked={profile === option.id} data-selected={profile === option.id} onClick={() => setProfile(option.id)}><span className="onboard-resource-option-top"><span className="onboard-resource-option-icon"><Icon name={option.icon} size={22}/></span><span className="onboard-version-radio">{tr(profile === option.id ? <Icon name="check" size={12}/> : null)}</span></span><strong>{tr(option.title)}</strong><p>{tr(option.hint)}</p><small>{tr(option.badge)}</small></button>))}</div>
234     <details className="onboard-resource-honesty"><summary>{tr("How resource sharing works")}</summary><p>{tr("We reserve GPU memory and limit CPU expert workers to leave headroom for other apps. Actual usage varies with your model. Model RAM requirements and system safety reserves still apply.")}</p></details>
235     {tr(version?.images ? <label className="onboard-picture onboard-load-vision"><OnboardingCheckbox checked={vision} onChange={setVision}/><Icon name="image" size={20}/><span><strong>{tr("Read pictures when this model loads")}</strong><small>{tr("Understand photos and screenshots. Vision files are already downloaded.")}</small></span></label> : null)}
236     {tr(native?.capabilities.calibration ? <label className="onboard-calibration"><OnboardingCheckbox checked={calibrate} onChange={setCalibrate}/><Icon name="gauge" size={20}/><span><strong>{tr("Find the fastest settings for this PC")}</strong><small>{tr("One-time measurement \u00B7 about 5\u201310 minutes. Your computer will be busy.")}</small></span></label> : <p className="onboard-calibration-note">{tr("We\u2019ll apply your preference and run a short speed check.")}</p>)}
237     {tr(tuneJob && ['error', 'cancelled'].includes(tuneJob.state) ? <ErrorNotice message={tuneJob.error ?? 'Tuning stopped. Your model files are safe.'} next={tr("Try again, or turn off the longer measurement above.")}/> : null)}
238    </>)}
239   </div>)}
240   <footer className="onboard-footer"><Btn variant="ghost" disabled={pending || !!active} onClick={() => void perform(() => advance(step === 4 ? 2 : step - 1))}>{tr("Back")}</Btn>{tr(step === 3 ? <span>{tr(preparing ? 'Take a look around while we prepare.' : 'Downloads start only when you’re ready.')}</span> : step === 4 && tuneJob?.state === 'running' ? <span>{tr("We\u2019ll open chat when your model is ready.")}</span> : null)}{tr(step === 2 ? <Btn variant="primary" disabled={pending || !!active || !version || !!version.needsNewerEngine || !native?.available || folderOpen} onClick={() => void review()}>{tr(pending ? 'Checking…' : 'Continue')}<Icon name="chevron" size={15}/></Btn> : step === 3 ? <Btn variant="primary" disabled={pending || checkingPlan || !!active || !!plan?.plan?.disk_short || !version || !!version.needsNewerEngine} onClick={() => void download()}>{tr(preparing ? 'Preparing…' : checkingPlan ? 'Checking storage…' : pending ? 'Starting…' : stopped ? 'Resume download' : 'Download model')}{tr(!preparing ? <Icon name="download" size={16}/> : null)}</Btn> : <Btn variant="primary" disabled={pending || !!active || !installed?.ready} onClick={() => void tune()}>{tr(tuneJob?.state === 'running' ? 'Tuning…' : pending ? 'Starting…' : 'Tune & start chatting')}<Icon name="chevron" size={15}/></Btn>)}</footer>
241   {tr(step === 4 && ready && ['error', 'cancelled'].includes(tuneJob?.state ?? '') ? <button className="onboard-continue-anyway" onClick={() => void finish()}>{tr("Continue to chat without a speed result")}</button> : null)}
242  </>)}
243  {tr(error ? <div className="onboard-error"><OnboardingError message={error} onFolder={changeDownloadFolder}/></div> : null)}
244 </div>;
245}
246function OnboardingError({ message, onFolder }: {
247    message: string;
248    onFolder: () => void;
249}) {
250    const detail = onboardingError(message);
251    if (!detail.storage)
252        return <ErrorNotice message={detail.message}/>;
253    return <div className="onboard-storage-error" role="alert"><Icon name="disk" size={20}/><div><strong>{tr(detail.title)}</strong><p>{tr(detail.message)}</p><small>{tr(detail.next)}</small><button type="button" onClick={onFolder}>{tr("Choose another folder")}<Icon name="chevron" size={13}/></button></div></div>;
254}
255function OnboardingFolder({ directory, onChoose }: {
256    directory: string;
257    onChoose: (path: string, ggufFiles: number) => void;
258}) {
259    const [path, setPath] = useState(directory), [folder, setFolder] = useState<LocalModelFolder | null>(null), [pending, setPending] = useState(false), [error, setError] = useState('');
260    async function browse(input: string, initial = false) { setPending(true); setError(''); try {
261        let value: LocalModelFolder;
262        try {
263            value = await api.get<LocalModelFolder>(`/api/local-models/browse?directory=${encodeURIComponent(input)}`);
264        }
265        catch (e) {
266            if (!initial)
267                throw e;
268            value = await api.get<LocalModelFolder>('/api/local-models/browse');
269        }
270        setFolder(value);
271        setPath(value.directory);
272    }
273    catch (e) {
274        setFolder(null);
275        setError(e instanceof Error ? e.message : String(e));
276    }
277    finally {
278        setPending(false);
279    } }
280    useEffect(() => { void browse(directory, true); }, []);
281    return <section className="onboard-folder-browser" aria-label={tr("Choose your model folder")}><form onSubmit={e => { e.preventDefault(); void browse(path); }}><input className="st-input" aria-label={tr("Existing model folder")} value={path} onChange={e => { setPath(e.target.value); setFolder(null); }} placeholder={tr("Full folder path")} spellCheck={false}/><Btn type="submit" size="sm" disabled={pending || !path.trim()}>{tr(pending ? 'Checking…' : 'Open')}</Btn></form><p>{tr("Choose the Strata data folder that holds your model downloads. Matching files are reused; missing files are prepared automatically.")}</p><div className="onboard-folder-shortcuts">{folder?.shortcuts?.map(item => <Btn key={item.path} size="sm" disabled={pending} onClick={() => void browse(item.path)}>{tr(item.name)}</Btn>)}</div><div className="onboard-folder-files">{tr(folder?.parent ? <button onClick={() => void browse(folder.parent!)}><Icon name="folder" size={16}/>{tr(" Up a folder")}</button> : null)}{folder?.entries.filter(e => e.kind === 'folder').slice(0, 30).map(e => <button key={e.path} onClick={() => void browse(e.path)}><Icon name="folder" size={16}/>{tr(e.name)}<Icon name="chevron" size={12}/></button>)}{tr(folder ? <small>{tr(folder.entries.filter(e => e.kind === 'model').length)}{tr(" GGUF files in this folder. Nested downloads are checked by the installer.")}</small> : null)}</div>{tr(folder ? <Btn variant="primary" size="sm" disabled={pending} onClick={() => onChoose(folder.directory, folder.entries.filter(e => e.kind === 'model').length)}>{tr("Use this folder")}</Btn> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}</section>;
282}