okami.mom/strata

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

Niko1221Merge f-0243-guifix into f-0243-rel9caf39495

main
39.4 KiB496 linesraw
1import { tr } from '../lib/i18n';
2import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
3import { ActionError, Btn, Dialog, ErrorNotice, Icon, Select } from '../components/ui';
4import { Screen } from '../components/layout';
5import { DemoTest } from '../components/EngineExperience';
6import { RunExpertEditor } from '../components/RunExpertEditor';
7import { RunPreview } from '../components/RunPreview';
8import { api } from '../lib/client';
9import { RunningModels } from '../components/RunningModels';
10import { LocalModelImport } from '../components/LocalModelImport';
11import { gpuId } from '../lib/monitor-hardware';
12import { GpuRoles } from '../components/GpuRoles';
13import { normalize as normalizeRoles, order as roleOrder, recommend as recommendRoles, sameRoles, type RoleCard, type Roles } from '../lib/gpu-roles';
14import { RunImageModel } from '../components/RunImageModel';
15import { IMAGE_GENERATION_VISIBLE } from '../lib/features';
16import { FloatingMenu } from '../components/FloatingMenu';
17import { ModelsScreen } from './Models';
18import { configDocument, configPatch, readConfig, type ConfigDocument } from '../lib/config';
19import { contextTokens, estimate, execution } from '../lib/experience';
20import { demoRunExperience, planMemory } from '../lib/run-memory';
21import { computerIdentity, configIdentity, defaultProfileKey, emptyProfiles, readProfiles, recommendedConfig, resourceConfig, RUN_PROFILES_KEY, saveProfile, type ComputerUse, type RunProfiles } from '../lib/run-profiles';
22import { modelFamilyIcon } from '../lib/model-icons';
23import { familyVersion, modelFamilies } from '../lib/model-versions';
24import { sizeGb } from '../lib/format';
25import { applyImageModel, getState, useLifecycle, loadRuntimeModel, loadVariant, pushToast, restartEngine, saveEngine, selectImageModel, setConfigDraft, useStore, validateEngine } from '../lib/store';
26import type { ImageModelChoice, RuntimeModels, RuntimeModel } from '../lib/types';
27import { useNative, nativeSettled, subscribeNative } from '../lib/native';
28import { NativeModels } from '../components/NativeModels';
29import { NativeLocalModel } from '../components/NativeLocalModel';
30import { parseLocation } from '../lib/router';
31type Issue = {
32    level: 'error' | 'warn';
33    message: string;
34};
35type RunStage = 'idle' | 'checking' | 'loading' | 'ready';
36export function ModelRunScreen() {
37    const native = useNative();
38    const settled = useSyncExternalStore(subscribeNative, nativeSettled);
39    const location = parseLocation(window.location.hash), entry = location.param;
40    const [other, setOther] = useState(entry === 'local' || entry === 'local-import'), [importFirst, setImportFirst] = useState(entry === 'local-import');
41    // Before the engine's answer arrives the page would show the bundled Starter and then jump to the installed model (#3740): show a neutral placeholder instead.
42    if (!native && !settled)
43        return <div className="main__body"><div className="wrap stack" role="status" aria-label={tr("Loading…")}><div className="skel" style={{ height: 20, width: '60%' }}/><div className="skel" style={{ height: 20, width: '80%' }}/><div className="skel" style={{ height: 20, width: '70%' }}/></div></div>;
44    if (native && other)
45        return <NativeLocalModel onBack={() => { setOther(false); setImportFirst(false); }}/>;
46    if (native && !other)
47        return <NativeModels onOtherModels={() => setOther(true)} onImport={() => { setImportFirst(true); setOther(true); }}/>;
48    return <><LegacyModelRunScreen importFirst={importFirst} initialVariant={location.query.get('variant') ?? undefined}/>{tr(other ? <button className="st-btn native-return" onClick={() => setOther(false)}>{tr("Back")}</button> : null)}</>;
49}
50function LegacyModelRunScreen({ importFirst = false, initialVariant }: {
51    importFirst?: boolean;
52    initialVariant?: string;
53}) {
54    const engine = useStore(s => s.engine), hardware = useStore(s => s.hardware), library = useStore(s => s.library);
55    const runtime = useStore(s => s.runtime);
56    const [deviceChoice, setDeviceChoice] = useState('auto');
57    const [customGpus, setCustomGpus] = useState<string[]>([]);
58    // Two or more cards (Expert settings): a role for each card instead of the "Run on" list. null = the recommended roles.
59    const [runRoles, setRunRoles] = useState<Roles | null>(null);
60    const placementInitialized = useRef('');
61    const imageModels = useStore(s => s.imageModels), imagePending = useStore(s => !!s.busy['image:select']);
62    const imageChoice = imageModels?.selected ?? 'off';
63    const imageVersion = imageModels?.variants.find(v => v.id === imageChoice);
64    const imageNeedsDownload = imageChoice !== 'off' && imageVersion?.state !== 'installed';
65    const imageUnavailable = imageChoice !== 'off' && !imageModels?.generationAvailable;
66    const rawDraft = useStore(s => s.configDraft), connected = useStore(s => s.connection === 'live');
67    const lifecycle = useLifecycle();
68    const [selected, setSelected] = useState(() => {
69        if (initialVariant)
70            return initialVariant;
71        try {
72            return sessionStorage.getItem('strata.run-variant.v1') ?? '';
73        }
74        catch {
75            return '';
76        }
77    });
78    const [expert, setExpert] = useState(false);
79    const [allowMultiple, setAllowMultiple] = useState(false);
80    const executionMode = expert && allowMultiple ? 'multiple' : 'single';
81    const [basicsOpen, setBasicsOpen] = useState(false);
82    const [libraryOpen, setLibraryOpen] = useState(false);
83    const [localModelOpen, setLocalModelOpen] = useState(importFirst);
84    const [testOpen, setTestOpen] = useState(false);
85    const [profileOpen, setProfileOpen] = useState(false);
86    const [profileMenu, setProfileMenu] = useState(false);
87    const profileTrigger = useRef<HTMLButtonElement>(null);
88    const familySelections = useRef(new Map<string, string>());
89    const familyDrafts = useRef(new Map<string, {
90        variantId: string;
91        draft: string | null;
92        profile: string;
93        image: ImageModelChoice;
94    }>());
95    const [profileName, setProfileName] = useState('Everyday');
96    const [makeDefault, setMakeDefault] = useState(false);
97    const [updateExisting, setUpdateExisting] = useState(false);
98    const [activeProfile, setActiveProfile] = useState('current');
99    const [profiles, setProfiles] = useState<RunProfiles>(emptyProfiles);
100    const [profileError, setProfileError] = useState('');
101    const [issues, setIssues] = useState<Issue[]>([]);
102    const [pending, setPending] = useState(false);
103    const [placementError, setPlacementError] = useState('');
104    const [placementPlan, setPlacementPlan] = useState<{
105        memory: RuntimeModel['memory'];
106        budget: RuntimeModels['memory'];
107        allowed: boolean;
108        alreadyLoaded: boolean;
109        reloads: boolean;
110    } | null>(null);
111    const [stage, setStage] = useState<RunStage>('idle');
112    const [discardOpen, setDiscardOpen] = useState(false);
113    const initialized = useRef(false);
114    const saved = useMemo(() => engine ? configDocument(engine) : null, [engine]);
115    const text = rawDraft ?? (saved ? JSON.stringify(saved, null, 2) : '');
116    const parsed = useMemo(() => {
117        try {
118            return { config: readConfig(text), error: '' };
119        }
120        catch (error) {
121            return { config: null, error: error instanceof Error ? error.message : String(error) };
122        }
123    }, [text]);
124    const config = parsed.config;
125    const running = library?.variants.find(v => v.id === library.loaded);
126    const model = library?.variants.find(v => v.id === selected) ?? running ?? library?.variants.find(v => v.state === 'installed') ?? library?.variants[0];
127    const computer = hardware ? computerIdentity(hardware) : '';
128    const localProfiles = profiles.profiles.filter(p => p.variantId === model?.id && p.hardware === computer);
129    const selectedProfile = localProfiles.find(p => p.id === activeProfile);
130    const personalDefault = model ? profiles.defaults[defaultProfileKey(computer, model.id)] : undefined;
131    const profileChanged = !!selectedProfile && !!config && (configIdentity(config) !== configIdentity(selectedProfile.config) || imageChoice !== (selectedProfile.imageModel ?? 'off'));
132    const use = config?.headroom === 'full' ? 'full' : 'shared';
133    const ctx = contextTokens(config?.beginner.contextLength ?? 'recommended');
134    const roleCards: RoleCard[] = (hardware?.gpus ?? []).map((g, i) => ({ index: i, name: g.name, vram_gb: g.vramGb ?? 0, integrated: !!g.unified, vendor: g.vendor }));
135    const rolesMode = expert && roleCards.length > 1;
136    const recommendedRoles = recommendRoles(roleCards).roles, effectiveRoles: Roles = runRoles ? normalizeRoles(runRoles, roleCards) : recommendedRoles;
137    const effectiveDevice = expert ? deviceChoice : 'auto';
138    const gpuIds = hardware ? (rolesMode ? roleOrder(effectiveRoles, roleCards).map(i => gpuId(hardware.gpus[i])) : effectiveDevice === 'auto' ? hardware.gpus.map(gpuId) : effectiveDevice === 'cpu' ? [] : effectiveDevice === 'custom' ? customGpus : [effectiveDevice]) : [];
139    const executionHardware = hardware ? { ...hardware, gpus: hardware.gpus.filter(g => gpuIds.includes(gpuId(g))), accelerator: { ...hardware.accelerator, backend: gpuIds.length ? hardware.accelerator.backend : 'cpu', unified: gpuIds.length ? hardware.accelerator.unified : false, usableVramGb: hardware.gpus.filter(g => gpuIds.includes(gpuId(g))).reduce((n, g) => n + g.vramGb, 0) } } : null;
140    const cfg = execution({ ...config?.expert, ...(!expert ? { 'gpu.layers': gpuIds.length ? 'Automatic' : 'CPU only' } : !gpuIds.length ? { 'gpu.layers': 'CPU only' } : {}) }, ctx);
141    const baseExperience = estimate(model, executionHardware, cfg, 'document', library?.mode === 'simulated' && !model?.local);
142    const baseMemory = planMemory(baseExperience, executionHardware, use, Number(config?.expert['server.parallel'] ?? 1), config?.expert['mem.mmap'] !== false && config?.expert['mem.lock'] !== true);
143    const memory = baseMemory && placementPlan ? { ...baseMemory, total: placementPlan.memory.totalGb, ram: placementPlan.memory.ramGb, gpu: placementPlan.memory.gpuGb, ssd: placementPlan.memory.spillGb } : baseMemory;
144    const experience = demoRunExperience(baseExperience, memory, use);
145    const contextMax = Math.floor((model?.contextMax ?? 1048576) / 1024);
146    const unsupportedContext = !!model && ctx > model.contextMax;
147    const invalid = expert && deviceChoice === 'custom' && !gpuIds.length || !!parsed.error || issues.some(i => i.level === 'error') || unsupportedContext;
148    useEffect(() => {
149        if (!hardware || !model || !engine || initialized.current)
150            return;
151        initialized.current = true;
152        try {
153            const stored = readProfiles(localStorage.getItem(RUN_PROFILES_KEY));
154            setProfiles(stored);
155            const id = stored.defaults[defaultProfileKey(computer, model.id)];
156            const profile = stored.profiles.find(p => p.id === id);
157            if (profile && (rawDraft === null || parsed.config && configIdentity(parsed.config) === configIdentity(profile.config))) {
158                setActiveProfile(profile.id);
159                if (rawDraft === null)
160                    setConfigDraft(JSON.stringify(profile.config, null, 2));
161                // Retain an image selection that has not yet been applied.
162                if (imageModels?.selected === imageModels?.applied && (profile.imageModel ?? 'off') !== imageChoice)
163                    void chooseImage(profile.imageModel ?? 'off');
164            }
165        }
166        catch (error) {
167            setProfileError(error instanceof Error ? error.message : 'Run profiles could not be loaded.');
168        }
169    }, [hardware, model?.id, engine, computer, rawDraft]);
170    useEffect(() => {
171        if (model && (!selected || !library?.variants.some(v => v.id === selected)))
172            setSelected(model.id);
173    }, [model?.id, selected, library]);
174    useEffect(() => {
175        if (selected)
176            try {
177                sessionStorage.setItem('strata.run-variant.v1', selected);
178            }
179            catch { /* Selection remains available for this session. */ }
180    }, [selected]);
181    useEffect(() => {
182        if (!model || !runtime || placementInitialized.current === model.id)
183            return;
184        placementInitialized.current = model.id;
185        const existing = runtime.instances.find(i => i.variantId === model.id);
186        const ids = existing?.gpuIds;
187        setDeviceChoice(runtime.mode === 'real' || !ids ? 'auto' : !ids.length ? 'cpu' : ids.length === 1 ? ids[0] : 'custom');
188        setCustomGpus(ids ?? []);
189    }, [model?.id, runtime?.mode]);
190    useEffect(() => {
191        if (model)
192            familySelections.current.set(model.family, model.id);
193    }, [model?.id]);
194    useEffect(() => {
195        if (!config || !model || !connected)
196            return;
197        let active = true;
198        const timer = setTimeout(() => void validateEngine({ ...configPatch(config), variantId: model.id }).then(result => {
199            if (active)
200                setIssues(result.issues.filter(i => !i.message.startsWith('Estimated working memory (') && !i.message.includes('is fast memory. Actual fit')));
201        }).catch(error => {
202            if (active)
203                setIssues([{ level: 'error', message: error.message }]);
204        }), 180);
205        return () => { active = false; clearTimeout(timer); };
206    }, [text, model?.id, connected]);
207    useEffect(() => {
208        setPlacementPlan(null);
209        setPlacementError('');
210        if (!config || !model || !hardware || !connected)
211            return;
212        let active = true;
213        const timer = setTimeout(() => {
214            const patch = loadPatch(config);
215            void api.post<NonNullable<typeof placementPlan>>('/api/runtime/plan', { variantId: model.id, gpuIds, config: patch, executionMode }).then(plan => {
216                if (active)
217                    setPlacementPlan(plan);
218            }).catch(error => {
219                if (active) {
220                    setPlacementPlan(null);
221                    if (library?.mode === 'simulated')
222                        setPlacementError(error instanceof Error ? error.message : String(error));
223                }
224            });
225        }, 180);
226        return () => { active = false; clearTimeout(timer); };
227    }, [text, model?.id, deviceChoice, customGpus.join(','), JSON.stringify(runRoles), runtime?.revision, connected, expert, executionMode]);
228    function loadPatch(doc: ConfigDocument) {
229        const patch = configPatch(doc);
230        if (!expert || !gpuIds.length)
231            patch.expert = patch.expert.map(p => p.id === 'gpu.layers' ? { ...p, value: gpuIds.length ? 'Automatic' : 'CPU only' } : p);
232        return patch;
233    }
234    function update(next: ConfigDocument) { setIssues([]); setStage('idle'); setConfigDraft(JSON.stringify(next, null, 2)); }
235    async function chooseImage(choice: ImageModelChoice) {
236        setStage('idle');
237        try {
238            await selectImageModel(choice);
239        }
240        catch (error) {
241            setProfileError(error instanceof Error ? error.message : String(error));
242        }
243    }
244    function setContext(k: number) {
245        if (config)
246            update({ ...config, beginner: { ...config.beginner, contextLength: `${k}k` }, expert: { ...config.expert, 'ctx.length': `${k}K` } });
247    }
248    function chooseProfile(id: string) {
249        if (!engine || !hardware)
250            return;
251        setActiveProfile(id);
252        setStage('idle');
253        const profile = profiles.profiles.find(p => p.id === id);
254        if (profile) {
255            update(structuredClone(profile.config));
256            void chooseImage(profile.imageModel ?? 'off');
257        }
258        else if (id === 'current') {
259            setConfigDraft(null);
260            void chooseImage(imageModels?.applied ?? 'off');
261        }
262        else {
263            update(recommendedConfig(engine, hardware, 'recommended', id === 'maximum' ? 'full' : 'shared'));
264            void chooseImage('off');
265        }
266    }
267    function chooseModel(id: string) {
268        if (id === model?.id)
269            return;
270        const next = getState().library?.variants.find(v => v.id === id);
271        if (model && next && next.family !== model.family) {
272            familyDrafts.current.set(model.family, { variantId: model.id, draft: rawDraft, profile: activeProfile, image: imageChoice });
273            const previous = familyDrafts.current.get(next.family);
274            if (previous?.variantId === id) {
275                setSelected(id);
276                setStage('idle');
277                setIssues([]);
278                setActiveProfile(previous.profile);
279                setConfigDraft(previous.draft);
280                void chooseImage(previous.image);
281                return;
282            }
283        }
284        setSelected(id);
285        setStage('idle');
286        setIssues([]);
287        const profileId = profiles.defaults[defaultProfileKey(computer, id)];
288        if (profileId)
289            chooseProfile(profileId);
290        else {
291            setActiveProfile('current');
292            if (engine && hardware) {
293                const nextConfig = recommendedConfig(engine, hardware);
294                if (next?.local) {
295                    const k = [4, 8, 16, 32, 64, 128, 256, 512, 1024].filter(k => k * 1024 <= next.contextMax).at(-1) ?? 4;
296                    const context = Math.min(32, k);
297                    nextConfig.beginner.contextLength = `${context}k`;
298                    nextConfig.expert['ctx.length'] = `${context}K`;
299                }
300                update(nextConfig);
301            }
302        }
303    }
304    function chooseFamily(family: string) {
305        if (!library || family === model?.family)
306            return;
307        const version = familyVersion(library, family, model?.quant, familySelections.current.get(family));
308        if (version)
309            chooseModel(version.id);
310    }
311    function chooseComputerUse(value: ComputerUse) {
312        if (config && hardware)
313            update(resourceConfig(config, value, hardware));
314    }
315    function persist(next: RunProfiles) {
316        localStorage.setItem(RUN_PROFILES_KEY, JSON.stringify(next));
317        setProfiles(next);
318        setProfileError('');
319    }
320    function openSave(asNew = false) {
321        setUpdateExisting(!asNew && !!selectedProfile);
322        setProfileName(!asNew && selectedProfile ? selectedProfile.name : use === 'full' ? 'Maximum performance' : 'Everyday');
323        setMakeDefault(!asNew && !!selectedProfile && selectedProfile.id === personalDefault);
324        setProfileOpen(true);
325    }
326    async function storeProfile() {
327        if (!model || !config || !hardware || !engine)
328            return;
329        setPending(true);
330        try {
331            const checked = await validateEngine({ ...configPatch(config), variantId: model.id });
332            if (!checked.ok) {
333                setIssues(checked.issues);
334                throw new Error('Correct the configuration before saving a profile.');
335            }
336            const profile = { id: updateExisting && selectedProfile ? selectedProfile.id : crypto.randomUUID(), name: profileName.trim(), variantId: model.id, hardware: computer, engineVersion: engine.engine.version, config: structuredClone(config), imageModel: imageChoice, updatedAt: new Date().toISOString() };
337            persist(saveProfile(profiles, profile, makeDefault));
338            setActiveProfile(profile.id);
339            setProfileOpen(false);
340            pushToast('success', 'Settings saved', makeDefault ? 'Selected automatically for this model on this computer.' : 'Ready to restore from Saved settings.');
341        }
342        catch (error) {
343            setProfileError(error instanceof Error ? error.message : String(error));
344        }
345        finally {
346            setPending(false);
347        }
348    }
349    async function tune() {
350        if (!engine || !hardware || !config || !model || pending)
351            return;
352        setPending(true);
353        setStage('checking');
354        setIssues([]);
355        try {
356            const tuned = recommendedConfig(engine, executionHardware ?? hardware, config.beginner.contextLength, use);
357            const checked = await validateEngine({ ...configPatch(tuned), variantId: model.id });
358            if (!checked.ok) {
359                setIssues(checked.issues);
360                throw new Error('Review the highlighted settings before loading.');
361            }
362            update(tuned);
363            setStage('ready');
364            pushToast('success', 'Model tuned', 'Settings are ready. Load model when you’re ready.');
365        }
366        catch (error) {
367            setStage('idle');
368            setIssues([{ level: 'error', message: error instanceof Error ? error.message : String(error) }]);
369        }
370        finally {
371            setPending(false);
372        }
373    }
374    async function run() {
375        if (!config || !model || pending || imagePending || imageNeedsDownload || imageUnavailable)
376            return;
377        setPending(true);
378        setStage('loading');
379        setIssues([]);
380        try {
381            const patch = loadPatch(config);
382            const checked = await validateEngine({ ...patch, variantId: model.id });
383            if (!checked.ok) {
384                setIssues(checked.issues);
385                throw new Error('Review the highlighted settings before loading.');
386            }
387            if (library?.mode === 'simulated')
388                await loadRuntimeModel({ variantId: model.id, gpuIds, config: patch, executionMode });
389            else {
390                if (!lifecycle.allowed)
391                    throw new Error(lifecycle.reason);
392                if (expert && (rolesMode ? !!runRoles : deviceChoice !== 'auto'))
393                    throw new Error('GPU assignment requires a native engine adapter. Use Automatic with this host.');
394                await saveEngine(patch, true, true);
395                const ok = getState().library?.loaded === model.id ? await restartEngine() : await loadVariant(model.id);
396                if (!ok)
397                    throw new Error(getState().actionError?.message ?? 'The model could not be loaded.');
398            }
399            await applyImageModel();
400            setStage('ready');
401            pushToast('success', 'Model loaded', executionMode === 'multiple' ? 'Other loaded models stay available.' : 'Ready for requests.');
402        }
403        catch (error) {
404            setStage('idle');
405            setIssues([{ level: 'error', message: error instanceof Error ? error.message : String(error) }]);
406        }
407        finally {
408            setPending(false);
409        }
410    }
411    if (!engine || !library || !model || !saved)
412        return <Screen title={tr("Model")}><p className="small muted">{tr(connected ? 'Loading your models and settings…' : 'Connect the engine to configure a model.')}</p></Screen>;
413    const versions = library.variants.filter(v => v.family === model.family || !!v.local);
414    const installed = ['loaded', 'installed', 'loading', 'unloading'].includes(model.state) || !!model.installedAt;
415    const working = ['downloading', 'loading', 'unloading'].includes(model.state);
416    const modelSummary = <><Icon name={model.local ? 'model-file' : modelFamilyIcon(model.family)} size={21}/><span><strong>{tr(model.local ? model.name : model.family)}</strong><small>{tr(model.local ? model.quant : model.name)} · {tr(ctx / 1024)}{tr("K \u00B7 ")}{tr(use === 'full' ? 'Maximum performance' : 'Room for other apps')}{tr(imageChoice !== 'off' ? ` · Image ${imageChoice.toUpperCase()}` : '')}</small></span></>;
417    return <Screen plainHeader title={tr("Model")} titleDetail={<span className="run-family-switcher"><Select ariaLabel={tr("Model family")} value={model.family} disabled={pending || imagePending} menuWidth={340} menuClassName="model-family-menu" optionIcon={modelFamilyIcon} options={modelFamilies(library).map(family => ({ value: family, label: family }))} onChange={chooseFamily}/></span>} actions={<>{tr(expert ? <><Btn size="sm" disabled={!config || invalid || pending} onClick={() => setTestOpen(true)}><span className="run-header-full">{tr("Benchmark")}</span><span className="run-header-short">{tr("Benchmark")}</span></Btn><Btn size="sm" disabled={!hardware || pending} onClick={() => {
418                    if (hardware) {
419                        setActiveProfile('recommended');
420                        update(recommendedConfig(engine, hardware));
421                        void chooseImage('off');
422                    }
423                }}><span className="run-header-full">{tr("Reset to recommended")}</span><span className="run-header-short">{tr("Reset defaults")}</span></Btn></> : null)}<button className="st-btn st-btn--secondary" aria-pressed={expert} disabled={pending} onClick={() => setExpert(!expert)}><Icon name="sliders" size={16}/>{tr(expert ? <><span className="run-header-full">{tr("Close expert mode")}</span><span className="run-header-short">{tr("Easy mode")}</span></> : 'Expert mode')}</button></>}>
424    <div className="model-run">
425      <ActionError />
426      <div className="run-toolbar">
427        {tr(expert ? <button className="run-basics-summary run-toolbar-summary" aria-expanded={basicsOpen} aria-controls="run-basic-settings" onClick={() => setBasicsOpen(!basicsOpen)}>{tr(modelSummary)}<Icon name="chevron" size={15}/></button> : <div className="run-basics-summary run-toolbar-summary run-model-summary">{tr(modelSummary)}</div>)}
428        <button ref={profileTrigger} className="st-btn st-btn--secondary run-saved-settings" aria-label={tr("Saved settings{0}{1}", [selectedProfile ? `: ${selectedProfile.name}` : tr(''), profileChanged ? tr(' — unsaved changes') : tr('')])} aria-haspopup="menu" aria-expanded={profileMenu} disabled={pending} onClick={() => setProfileMenu(!profileMenu)}><Icon name="layers" size={17}/><span>{tr(selectedProfile?.name ?? 'Saved settings')}</span>{tr(profileChanged ? <i title={tr("Unsaved changes")}/> : null)}<Icon name="chevron" size={14}/></button>
429        <Btn icon="models" size="sm" onClick={() => setLibraryOpen(true)}>{tr("Manage models")}</Btn>
430      </div>
431      {tr(expert ? <RunningModels controls/> : null)}
432      {tr(profileError && !profileOpen ? <ErrorNotice message={profileError}/> : null)}
433      <div className="run-layout">
434        <div className="run-setup" data-expert={expert || undefined}>
435          <div className="run-basics" id="run-basic-settings" hidden={expert && !basicsOpen}>
436          <section className="run-card run-model-choice">
437            <div className="run-version-choice"><span>{tr("Version")}</span><Select ariaLabel={tr("Model version")} value={model.id} disabled={pending} menuClassName="run-version-menu" options={[...versions.map(v => ({ value: v.id, label: `${v.name} · ${v.quant} · ${sizeGb(v.diskGb)}${v.local ? ' · Local' : ''}` })), { value: 'use-local-model', label: 'Use a local model…' }]} onChange={id => id === 'use-local-model' ? setLocalModelOpen(true) : chooseModel(id)}/></div>
438            {tr(model.local ? <div className="run-local-model-note"><Icon name="model-file" size={15}/><span>{tr("Local model \u00B7 ")}{tr(model.local.architecture)}{tr(" \u00B7 Compatibility checked on load.")}</span><button className="text-btn" onClick={() => setLocalModelOpen(true)}>{tr("Change file")}</button></div> : null)}
439            {IMAGE_GENERATION_VISIBLE ? <RunImageModel library={imageModels} disabled={pending || imagePending || !connected} onChange={() => setStage('idle')}/> : null}
440          </section>
441          <section className="run-card run-context"><div className="run-card__head"><span><Icon name="chat" size={19}/><h2>{tr("Conversation context")}</h2></span><strong>{tr(ctx / 1024)}{tr("K ")}<small>{tr("tokens")}</small></strong></div><p>{tr("How much your model can keep in mind.")}</p>
442            <div className="run-context-presets" role="group" aria-label={tr("Context presets")}>{tr([32, 64, 128, 256].map(k => <button key={k} disabled={k > contextMax} aria-pressed={ctx === k * 1024} onClick={() => setContext(k)}><span>{tr(k)}{tr("K")}</span></button>))}</div>
443            <div className="run-context-bottom"><label className="run-context-exact">{tr("Custom ")}<input className="st-input" aria-label={tr("Custom context in K tokens")} type="number" min="4" max={contextMax} step="1" value={Number.isFinite(ctx) ? ctx / 1024 : ''} onChange={e => {
444            if (e.target.value)
445                setContext(Number(e.target.value));
446        }}/><span>{tr("K")}</span></label></div>
447            {tr(unsupportedContext ? <p className="inline-error xs">{tr("This model supports up to ")}{tr(contextMax)}{tr("K. Choose a supported context to run it.")}</p> : null)}
448          </section>
449          <section className="run-card run-resources"><div className="run-card__head"><span><Icon name="computer" size={19}/><h2>{tr("Computer use")}</h2></span></div>
450            <div className="run-resource-options">{tr([{ id: 'shared' as const, icon: 'computer' as const, title: 'Leave room for other apps', hint: 'Work alongside your model' }, { id: 'full' as const, icon: 'bolt' as const, title: 'Maximum performance', hint: 'Give your model more resources' }].map(option => <button key={option.id} aria-pressed={use === option.id} disabled={!hardware} onClick={() => chooseComputerUse(option.id)}><span><Icon name={option.icon} size={20}/><i>{tr(use === option.id ? <Icon name="check" size={12}/> : null)}</i></span><strong>{tr(option.title)}</strong><small>{tr(option.hint)}</small></button>))}</div>
451            <p className="run-resources__hint"><Icon name="cpu" size={14}/>{tr(cfg.threads)}{tr(" CPU threads")}{tr(memory ? ` · ${memory.reserve.toFixed(0)} GB RAM headroom in the estimate` : '')}</p>
452          </section>
453          </div>
454          {tr(expert ? <section className="run-card run-placement">
455            <div className="run-card__head"><span><Icon name="gpu" size={19}/><h2>{tr("Model execution")}</h2></span></div>
456            <label className="run-multiple-choice"><span><strong>{tr("Run multiple models")}</strong><small>{tr("Keep models loaded when you add another.")}</small></span><input type="checkbox" role="switch" aria-label={tr("Run multiple models")} checked={allowMultiple} disabled={pending || runtime?.capabilities.multipleModels === false} onChange={e => { setAllowMultiple(e.target.checked); setIssues([]); setStage('idle'); }}/></label>
457            {rolesMode ? <GpuRoles cards={roleCards} roles={effectiveRoles} custom={!!runRoles && !sameRoles(effectiveRoles, recommendedRoles)} disabled={pending || runtime?.capabilities.deviceAssignment === false} onChange={next => { setRunRoles(sameRoles(next, recommendedRoles) ? null : next); setStage('idle'); setIssues([]); }} onBack={() => { setRunRoles(null); setStage('idle'); setIssues([]); }}/> : <>
458            <span className="run-device-label">{tr("Run on")}</span>
459            <Select ariaLabel={tr("Execution device")} value={deviceChoice} disabled={pending || runtime?.capabilities.deviceAssignment === false} options={[{ value: 'auto', label: hardware?.gpus.length ? hardware.gpus.length > 1 ? 'Automatic · all GPUs' : 'Automatic · GPU 1' : 'CPU only' }, { value: 'cpu', label: 'CPU only' }, ...(hardware?.gpus ?? []).map((g, i) => ({ value: gpuId(g), label: `GPU ${i + 1} · ${g.name}` })), ...((hardware?.gpus.length ?? 0) > 1 ? [{ value: 'custom', label: 'Choose GPUs…' }] : [])]} onChange={id => { setDeviceChoice(id); setStage('idle'); setIssues([]); }}/>
460            {tr(deviceChoice === 'custom' ? <div className="run-gpu-options">{tr(hardware?.gpus.map((g, i) => <label key={gpuId(g)}><input type="checkbox" checked={customGpus.includes(gpuId(g))} onChange={e => { setCustomGpus(ids => e.target.checked ? [...ids, gpuId(g)] : ids.filter(id => id !== gpuId(g))); setStage('idle'); }}/><span>{tr("GPU ")}{tr(i + 1)} · {tr(g.name)}<small>{tr(g.unified ? 'Shared system memory' : `${sizeGb(g.vramGb)} VRAM`)}</small></span></label>))}</div> : null)}
461            </>}
462            <p className="xs muted">{tr(runtime?.capabilities.multipleModels === false ? 'This native host currently supports one model with automatic GPU placement.' : !allowMultiple ? 'One model at a time. Loading switches to the selected model.' : placementPlan?.reloads ? 'Loading applies these settings to this instance. Other models stay loaded.' : 'Loading adds a model. Existing models keep their settings and GPU assignments.')}</p>
463            {tr(runtime?.instances.length ? <div className="run-memory-reservations"><span>{tr(placementPlan && !placementPlan.alreadyLoaded ? 'Shared RAM after load' : 'Shared RAM reserved')} <strong>{tr((placementPlan?.budget.ramGb ?? runtime.memory.ramGb).toFixed(1))} / {tr((placementPlan?.budget.budgetGb ?? runtime.memory.budgetGb).toFixed(1))}{tr(" GB")}</strong></span><small>{tr(runtime.memory.reserveGb.toFixed(0))}{tr(" GB RAM headroom \u00B7 estimates include all loaded models")}</small>{tr((placementPlan?.budget.devices ?? runtime.memory.devices).map(d => <span key={d.id}>{tr(d.name)}<strong>{tr(d.usedGb.toFixed(1))} / {tr(d.budgetGb.toFixed(1))}{tr(" GB")}</strong></span>))}</div> : null)}
464          </section> : null)}
465          {tr(expert ? <RunExpertEditor engine={engine} config={config} text={text} onChange={update} onText={value => { setStage('idle'); setConfigDraft(value); }} onRestore={() => setDiscardOpen(true)} onError={message => setIssues([{ level: 'error', message }])}/> : null)}
466          {tr(parsed.error ? <ErrorNotice message={parsed.error}/> : null)}
467          {tr(issues.length ? <div className="run-issues" role="status">{tr(issues.map((issue, i) => <p key={i} data-tone={issue.level}><Icon name={issue.level === 'error' ? 'error' : 'info'} size={16}/>{tr(issue.message)}</p>))}</div> : null)}
468          {tr((executionMode === 'single' || library.mode === 'real') && !lifecycle.allowed ? <p className="small muted">{tr(lifecycle.reason)}</p> : null)}
469          {tr(placementError ? <p className="small inline-error" role="status">{tr(placementError)}</p> : null)}
470          {tr(placementPlan && !placementPlan.allowed ? <p className="small inline-error" role="status">{tr(executionMode === 'multiple' ? 'Other loaded models have reserved this memory. Choose another GPU, reduce context, or unload a model.' : 'Reduce context or choose a smaller version to fit this model.')}</p> : null)}
471          <section className="run-actions" aria-label={tr("Run model")}>
472            <Btn icon="sliders" disabled={invalid || pending || !connected} onClick={() => void tune()}>{tr(pending && stage === 'checking' ? 'Tuning…' : 'Tune model')}</Btn>
473            <Btn variant="primary" icon="models" disabled={!installed || invalid || !!placementError || placementPlan?.allowed === false || pending || imagePending || imageNeedsDownload || imageUnavailable || !connected || ((executionMode === 'single' || library.mode === 'real') && !lifecycle.allowed) || working} onClick={() => void run()}>{tr(pending && stage === 'loading' ? 'Loading…' : 'Load model')}</Btn>
474          </section>
475          {tr(imageUnavailable ? <p className="small muted">{tr("This engine cannot run image models yet. Choose Off to run the chat model.")}</p> : null)}
476          {tr(!installed ? <Btn icon={model.local ? 'folder' : 'download'} onClick={() => model.local ? setLocalModelOpen(true) : setLibraryOpen(true)}>{tr(model.local ? 'Reconnect local file' : 'Download model version')}</Btn> : null)}
477        </div>
478        <RunPreview experience={experience} memory={memory} hardware={hardware} imageEnabled={imageChoice !== 'off'}/>
479      </div>
480    </div>
481    {tr(profileMenu ? <FloatingMenu anchor={profileTrigger.current} title={tr("Saved settings")} width={320} onClose={() => setProfileMenu(false)}>
482      <div className="run-settings-menu-label">{tr("Saved settings")}</div>
483      <button role="menuitemradio" aria-checked={!selectedProfile} className="menu__item run-settings-option" onClick={() => { chooseProfile('current'); setProfileMenu(false); }}><span className="run-settings-icon"><Icon name="sliders" size={18}/></span><span>{tr("Current settings")}</span>{tr(!selectedProfile ? <Icon name="check" size={15} className="run-settings-selected"/> : null)}</button>
484      {tr(localProfiles.map(profile => <button key={profile.id} role="menuitemradio" aria-checked={profile.id === activeProfile} className="menu__item run-settings-option" onClick={() => { chooseProfile(profile.id); setProfileMenu(false); }}><span className="run-settings-icon"><Icon name="layers" size={18}/></span><span>{profile.name}{tr(profile.id === personalDefault ? <small>{tr("Default for this model")}</small> : null)}{tr(profile.engineVersion !== engine.engine.version ? <small>{tr("Engine changed \u00B7 tune again before running")}</small> : null)}</span>{tr(profile.id === activeProfile ? <Icon name="check" size={15} className="run-settings-selected"/> : null)}</button>))}
485      <div className="run-settings-menu-divider" role="separator"/>
486      {tr(selectedProfile ? <button role="menuitem" className="menu__item run-settings-action" disabled={!config} onClick={() => { setProfileMenu(false); openSave(); }}><span className="run-settings-icon"><Icon name="pencil" size={18}/></span>{tr("Edit saved settings\u2026")}</button> : null)}
487      <button role="menuitem" className="menu__item run-settings-action" disabled={!config} onClick={() => { setProfileMenu(false); openSave(true); }}><span className="run-settings-icon"><Icon name={selectedProfile ? 'copy' : 'plus'} size={18}/></span>{tr(selectedProfile ? 'Save as new…' : 'Save current settings…')}</button>
488      {tr(selectedProfile && profileChanged ? <button role="menuitem" className="menu__item run-settings-action" onClick={() => { setProfileMenu(false); chooseProfile(selectedProfile.id); }}><span className="run-settings-icon"><Icon name="refresh" size={18}/></span>{tr("Restore saved settings")}</button> : null)}
489    </FloatingMenu> : null)}
490    <Dialog open={libraryOpen} className="run-library-dialog" title={tr("Manage models")} onClose={() => setLibraryOpen(false)}><ModelsScreen embedded familyOverride={model.family} selectedVariant={model.id} contextOverride={ctx} onChoose={id => { chooseModel(id); setLibraryOpen(false); }}/></Dialog>
491    <LocalModelImport open={localModelOpen} directory={library.disk.modelsDir} onClose={() => setLocalModelOpen(false)} onChoose={id => chooseModel(id)}/>
492    <Dialog open={profileOpen} compact title={tr(updateExisting ? 'Update saved settings' : 'Save settings')} onClose={() => !pending && setProfileOpen(false)} actions={<><Btn disabled={pending} onClick={() => setProfileOpen(false)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!profileName.trim() || pending || imagePending || invalid} onClick={() => void storeProfile()}>{tr(pending ? 'Saving…' : updateExisting ? 'Update settings' : 'Save settings')}</Btn></>}><div className="run-save-profile"><label className="input-field"><span>{tr("Name")}</span><input className="st-input" aria-label={tr("Settings name")} maxLength={64} value={profileName} onChange={e => setProfileName(e.target.value)}/></label><p className="small muted">{tr(model.name)} · {tr(ctx / 1024)}{tr("K \u00B7 ")}{tr(use === 'full' ? 'Maximum performance' : 'Room for other apps')}</p><label className="run-default-choice"><input type="checkbox" checked={makeDefault} onChange={e => setMakeDefault(e.target.checked)}/><span>{tr("Use by default for this model")}<small>{tr("On this computer. Restore it whenever you open Models.")}</small></span></label>{tr(profileError ? <ErrorNotice message={profileError}/> : null)}</div></Dialog>
493    <DemoTest open={testOpen} onClose={() => setTestOpen(false)} experience={experience}/>
494    <Dialog open={discardOpen} compact title={tr("Restore saved settings?")} onClose={() => setDiscardOpen(false)} actions={<><Btn onClick={() => setDiscardOpen(false)}>{tr("Keep editing")}</Btn><Btn onClick={() => { setConfigDraft(null); void chooseImage(imageModels?.applied ?? 'off'); setActiveProfile('current'); setIssues([]); setDiscardOpen(false); }}>{tr("Restore settings")}</Btn></>}><p>{tr("Replace this draft with the settings last saved to the engine.")}</p></Dialog>
495  </Screen>;
496}