import { tr } from '../lib/i18n'; import { useEffect, useRef, useState, type KeyboardEvent } from 'react'; import { Brand } from './Brand'; import { Btn, ErrorNotice, Icon, Select } from './ui'; import { OnboardingArt, OnboardingTour } from './OnboardingArt'; import { OnboardingMemory } from './OnboardingMemory'; import { OnboardingResources } from './OnboardingResources'; import { OnboardingCheckbox } from './OnboardingCheckbox'; import { api } from '../lib/client'; import { navigate } from '../lib/router'; import { nativeAction, useNative, type NativeJob } from '../lib/native'; import { completeSetup, completeSetupStep, go, newSession, openSetup, selectRemoteModel, setSettingsSection, useStore } from '../lib/store'; import type { LocalModelFolder, SetupState } from '../lib/types'; import { downloadCounter, engineNotReadyAfterInstall, modelFolderLabel, onboardingError } from '../lib/onboarding-download'; import { guidedStatusText, installProgress, useDownloadEta } from '../lib/download-eta'; import { VersionPicker } from './VersionPicker'; import { contextIsTight, defaultContext } from '../lib/default-context'; import { contextCacheGb } from '../lib/native-fit'; import { FirstRunLanguage } from './FirstRunLanguage'; import { DownloadParts } from './DownloadParts'; import { EngineWarning } from './EngineWarning'; import { OTHER_NOTE, PICK_NOTE, cardRoomGb, recommendedVersions } from '../lib/native-fit'; import { nativeCatalogModels, catalogVersionLabel, startingChoice } from '../lib/native-catalog'; type Choices = NonNullable['onboarding']>; function radioKeys(event: KeyboardEvent) { if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) return; event.preventDefault(); const items = Array.from(event.currentTarget.querySelectorAll('[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(); } const steps = ['Welcome', 'Your model', 'Prepare', 'Make it yours']; export function GuidedSetup() { const native = useNative(), setup = useStore(s => s.setup), hardware = useStore(s => s.hardware); const families = nativeCatalogModels(native?.catalog?.families ?? []); const saved = !setup?.complete && !setup?.choices?.onboarding?.manual ? setup?.choices?.onboarding : undefined; const [step, setStep] = useState(saved?.manual || setup?.complete ? 1 : saved?.step ?? 1); /* 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 on this computer first, else the catalog's recommendation. The state used to be filled once at mount, before the catalog had arrived, and so fell back to the first size in the list (Q2_0, a 66 GB download) while an installed model sat beside it. */ const [chosenFamily, setFamily] = useState(saved?.family ?? ''), [chosenSize, setSize] = useState(saved?.size ?? ''); const start = startingChoice(families, (native?.installed?.models ?? []).filter(m => m.ready).map(m => m.model), native?.catalog?.recommendation); const family = chosenFamily || start?.family || native?.catalog?.recommendation?.family || families[0]?.family || ''; const size = chosenSize || start?.size || ''; /* 128K for every configuration unless the person picks another, on every card. The warning for a card it leaves little room on is under the chooser; nothing is lowered. */ const topCardGb = Math.max(0, ...(native?.hardware?.gpus ?? []).filter(g => g.usable !== false).map(g => g.vram_gb)); const [pickedContext, setContext] = useState(saved?.context), [contextTouched, setContextTouched] = useState(false); const [vision, setVision] = useState(saved?.vision ?? true), [directory, setDirectory] = useState(saved?.directory ?? ''); const [profile, setProfile] = useState<'work' | 'performance'>(saved?.profile ?? 'work'); const [installJobId, setInstallJobId] = useState(saved?.installJobId ?? ''), [tuneJobId, setTuneJobId] = useState(saved?.tuneJobId ?? ''); const [plan, setPlan] = useState | null>(null), [tour, setTour] = useState(0), [folderOpen, setFolderOpen] = useState(false); const [pending, setPending] = useState(false), [checkingPlan, setCheckingPlan] = useState(false), [error, setError] = useState(''), [calibrate, setCalibrate] = useState(saved?.calibrate ?? true); const writes = useRef(Promise.resolve()), leaving = useRef(false), saveTimer = useRef | null>(null), titleRef = useRef(null); const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0]; const version = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0]; const installed = native?.installed?.models.find(m => m.model === version?.id); const contextList = native?.catalog?.contexts ?? [131072]; const context = pickedContext ?? defaultContext(contextList); 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); const active = native?.jobs.find(j => j.state === 'running'); const ready = native?.instances.some(i => i.model === version?.id && i.status === 'ready'); const folder = directory || native?.downloadDirectory || native?.installed?.data_folder || setup?.app.modelsDir || ''; const choices: Choices = { step, family: selectedFamily?.family, size: version?.id, context, vision, directory, profile, installJobId, tuneJobId, calibrate }; function persist(next: number, patch: Partial = {}, dismissed = false) { const value = { ...choices, step: next, ...patch }; const work = writes.current.catch(() => { }).then(() => completeSetupStep(Math.min(4, next), { onboarding: value }, dismissed)); writes.current = work; return work; } async function perform(action: () => Promise) { setPending(true); setError(''); try { await action(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setPending(false); } } async function advance(next: number, patch: Partial = {}) { await persist(next, patch); setStep(next); setError(''); } async function skip(manual = false, section?: 'Engine' | 'Models') { await perform(async () => { leaving.current = true; if (saveTimer.current) clearTimeout(saveTimer.current); try { await persist(step, { manual }, true); openSetup(false); if (section) { setSettingsSection(section); navigate('chat', undefined, { settings: '1' }); } else go(manual || preparing ? 'models' : 'chat'); } catch (e) { leaving.current = false; throw e; } }); } /* 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). */ async function ownModel(path?: string) { await perform(async () => { leaving.current = true; if (saveTimer.current) clearTimeout(saveTimer.current); try { await persist(step, { manual: true }, true); openSetup(false); navigate('models', 'local', path ? { path } : undefined); } catch (e) { leaving.current = false; throw e; } }); } async function finish() { if (leaving.current) return; leaving.current = true; if (saveTimer.current) clearTimeout(saveTimer.current); try { await writes.current; await completeSetup(); selectRemoteModel(null); openSetup(false); const chat = newSession(); go('chat', chat.id); } catch (e) { leaving.current = false; setError(e instanceof Error ? e.message : String(e)); } } function chooseNative(family: string, size: string) { setFamily(family); setSize(size); setVision(true); setPlan(null); setError(''); } useEffect(() => { titleRef.current?.focus({ preventScroll: true }); titleRef.current?.closest('.setupmodal__surface')?.scrollTo({ top: 0 }); }, [step]); useEffect(() => { if (step < 2 || leaving.current) return; saveTimer.current = setTimeout(() => { void persist(step).catch(e => setError(e.message)); }, 450); return () => { if (saveTimer.current) clearTimeout(saveTimer.current); }; }, [step, family, size, context, vision, directory, profile, calibrate, installJobId, tuneJobId]); useEffect(() => { if (step === 3 && installJob?.state === 'done' && installed?.ready) void advance(4).catch(e => setError(e.message)); }, [installJob?.state, installed?.ready, step]); useEffect(() => { if (step === 4 && tuneJob?.state === 'done' && ready) void finish(); }, [tuneJob?.state, ready, step]); useEffect(() => { if (step === 3 && installJob?.state === 'running' && !installJobId) { setInstallJobId(installJob.id); void persist(3, { installJobId: installJob.id }).catch(e => setError(e.message)); } if (step === 4 && tuneJob?.state === 'running' && !tuneJobId) { setTuneJobId(tuneJob.id); void persist(4, { tuneJobId: tuneJob.id }).catch(e => setError(e.message)); } }, [step, installJob?.id, tuneJob?.id]); 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 } : {}) }; async function review() { await perform(async () => { setInstallJobId(''); setTuneJobId(''); if (installed?.ready && installed.context === context && (!version?.images || installed.images && installed.images !== 'off') && (!directory || directory === installed.dataFolder)) { await advance(4, { installJobId: '', tuneJobId: '' }); return; } setPlan(await api.post('/api/native/plan', values)); await advance(3, { installJobId: '', tuneJobId: '' }); }); } async function download() { await perform(async () => { const result = await nativeAction('operations', { kind: 'install', args: values }); setInstallJobId(result.id); await persist(3, { installJobId: result.id }); }); } async function tune() { await perform(async () => { const result = await nativeAction('operations', { kind: 'tune', args: { guided: true, model: version?.id, profile, calibrate, vision: version?.images && vision ? 'yes' : 'no', multiple: false } }); setTuneJobId(result.id); await persist(4, { tuneJobId: result.id }); }); } const progress = installProgress(installJob?.result?.install); const preparing = installJob?.state === 'running'; const stopped = installJob && ['error', 'cancelled'].includes(installJob.state); useEffect(() => { if (step !== 3 || plan || preparing || !native?.available || !version) { setCheckingPlan(false); return; } let cancelled = false; setCheckingPlan(true); api.post>('/api/native/plan', values).then(value => { if (!cancelled) { setPlan(value); setCheckingPlan(false); } }).catch(e => { if (!cancelled) { setError(e.message); setCheckingPlan(false); } }); return () => { cancelled = true; }; }, [step, plan, preparing, native?.available, version?.id, context, directory]); const recommendedRows = recommendedVersions(selectedFamily?.sizes ?? [], native?.catalog?.recommendation); const recommendedCards = recommendedRows.map(x => x.v); const pickNote = (v: { id: string }) => recommendedRows.find(x => x.v.id === v.id && [PICK_NOTE, OTHER_NOTE].includes(x.r.note))?.r.note ?? ''; // 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. const cards = recommendedCards.length ? recommendedCards : selectedFamily?.sizes ?? []; const others = recommendedCards.length ? (selectedFamily?.sizes ?? []).filter(v => !recommendedCards.includes(v)) : []; const readyIds = new Set((native?.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const versionCard = (v: NonNullable) => ; const counter = downloadCounter(plan?.plan?.download_gb ?? version?.download_gb, progress, preparing); const eta = useDownloadEta(preparing ? progress : undefined, installJob?.id); 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?'; function changeDownloadFolder() { void perform(async () => { await advance(2); setFolderOpen(true); }); } return
{tr(step === 1 ? : null)}{tr(step !== 1 ? : null)}
{tr(steps.map((label, i) =>
i + 1} aria-current={step === i + 1 ? 'step' : undefined}>{tr(step > i + 1 ? : i + 1)}{tr(label)}
))}
{tr(step === 1 ? <>

{tr(title)}

{tr("Get stuff done on hardware you own.")}
{tr("Use intelligence the way you want.")}

{tr("Privacy first")}{tr("Fastest AI")}{tr("Easy to use")}
void perform(() => advance(2))}>{tr("Let\u2019s get started")}{tr("Already know your way around? ")}
: <>

{tr(title)}

{tr(step === 2 ?

{tr("You can always change your models later.")}

: step === 4 && tuneJob?.state === 'running' ?

{tr("We\u2019re measuring, applying your preference, and getting ready to chat.")}

: null)}
{tr(step === 2 ?
{tr(selectedFamily ? <>
{tr("Model")}
({ value: String(n), label: `${n / 1024}K` }))} onChange={value => { setContextTouched(true); setContext(Number(value)); }}/>
{tr(contextIsTight(topCardGb, context, 'int8', version?.context_fit) ?

{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)])}

: null)} {tr(!version || version.needsNewerEngine ?

{tr("This model needs a newer engine. Update your engine or import a local GGUF for this model.")}

: null)}
{tr("Choose a version")}{tr(version ? `${catalogVersionLabel(version)} selected` : '')}
{tr(cards.map(v => versionCard(v)))}
{tr(others.length ?
g.usable !== false)) } : null} downloaded={readyIds} showRecommended={false} moreLabel="More versions" onSelect={id => { setSize(id); setPlan(null); }} onOwnGguf={() => void ownModel()}/>
: null)}
{tr(directory ? 'Your model folder' : 'Already downloaded the model?')}{tr(directory || "Choose the folder and we'll start your models with Strata.")}
setFolderOpen(v => !v)}>{tr(folderOpen ? 'Close' : directory ? 'Change' : 'Choose folder')}
{tr(folderOpen ? 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)} :
{tr("Connect your Strata installation")} void skip(false, 'Engine')}>{tr("Connect engine")}
)}
: step === 3 ?
{tr(selectedFamily?.title)}{tr(version ? catalogVersionLabel(version) : '')}{tr(version?.model)}
{tr(preparing ?
{tr(guidedStatusText(installJob?.result?.install, progress))}
{tr(progress ? : )}
{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…')}
{tr(eta ? {eta} : null)}
: <>{tr(stopped ? : null)}{tr(engineNotReadyAfterInstall(installJob?.state, installed?.ready, native?.engine?.usable) ?

{tr("Your model is downloaded, but the engine for this PC isn't ready yet. Open Settings > About to install it.")}

: null)}{tr(plan?.plan?.disk_short ? : null)})} {tr("Save to")}{tr(modelFolderLabel(folder))}{tr(!preparing ? : null)}
:
{tr(tuneJob?.state === 'running' ? <>
{tr(tuneJob.summary)}{tr("Your choice: ")}{tr(profile === 'work' ? '20% headroom for other work' : 'Full performance')}
: <>
{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 => ))}
{tr("How resource sharing works")}

{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.")}

{tr(version?.images ? : null)} {tr(native?.capabilities.calibration ? :

{tr("We\u2019ll apply your preference and run a short speed check.")}

)} {tr(tuneJob && ['error', 'cancelled'].includes(tuneJob.state) ? : null)} )}
)}
void perform(() => advance(step === 4 ? 2 : step - 1))}>{tr("Back")}{tr(step === 3 ? {tr(preparing ? 'Take a look around while we prepare.' : 'Downloads start only when you’re ready.')} : step === 4 && tuneJob?.state === 'running' ? {tr("We\u2019ll open chat when your model is ready.")} : null)}{tr(step === 2 ? void review()}>{tr(pending ? 'Checking…' : 'Continue')} : step === 3 ? void download()}>{tr(preparing ? 'Preparing…' : checkingPlan ? 'Checking storage…' : pending ? 'Starting…' : stopped ? 'Resume download' : 'Download model')}{tr(!preparing ? : null)} : void tune()}>{tr(tuneJob?.state === 'running' ? 'Tuning…' : pending ? 'Starting…' : 'Tune & start chatting')})}
{tr(step === 4 && ready && ['error', 'cancelled'].includes(tuneJob?.state ?? '') ? : null)} )} {tr(error ?
: null)}
; } function OnboardingError({ message, onFolder }: { message: string; onFolder: () => void; }) { const detail = onboardingError(message); if (!detail.storage) return ; return
{tr(detail.title)}

{tr(detail.message)}

{tr(detail.next)}
; } function OnboardingFolder({ directory, onChoose }: { directory: string; onChoose: (path: string, ggufFiles: number) => void; }) { const [path, setPath] = useState(directory), [folder, setFolder] = useState(null), [pending, setPending] = useState(false), [error, setError] = useState(''); async function browse(input: string, initial = false) { setPending(true); setError(''); try { let value: LocalModelFolder; try { value = await api.get(`/api/local-models/browse?directory=${encodeURIComponent(input)}`); } catch (e) { if (!initial) throw e; value = await api.get('/api/local-models/browse'); } setFolder(value); setPath(value.directory); } catch (e) { setFolder(null); setError(e instanceof Error ? e.message : String(e)); } finally { setPending(false); } } useEffect(() => { void browse(directory, true); }, []); return
{ e.preventDefault(); void browse(path); }}> { setPath(e.target.value); setFolder(null); }} placeholder={tr("Full folder path")} spellCheck={false}/>{tr(pending ? 'Checking…' : 'Open')}

{tr("Choose the Strata data folder that holds your model downloads. Matching files are reused; missing files are prepared automatically.")}

{folder?.shortcuts?.map(item => void browse(item.path)}>{tr(item.name)})}
{tr(folder?.parent ? : null)}{folder?.entries.filter(e => e.kind === 'folder').slice(0, 30).map(e => )}{tr(folder ? {tr(folder.entries.filter(e => e.kind === 'model').length)}{tr(" GGUF files in this folder. Nested downloads are checked by the installer.")} : null)}
{tr(folder ? onChoose(folder.directory, folder.entries.filter(e => e.kind === 'model').length)}>{tr("Use this folder")} : null)}{tr(error ? : null)}
; }