okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
14.5 KiB150 linesraw
1import { DecimalInput } from './DecimalInput';
2import { tr } from '../lib/i18n';
3import {nativeSettingsResponse,nativeSettingsValues} from '../lib/native-settings-response';
4import { describeChange, type TunedChange } from '../lib/tune-values';
5import { useEffect, useState } from 'react';
6import { api } from '../lib/client';
7import { refreshNative, useNative, type NativeField } from '../lib/native';
8import { Btn, ErrorNotice, Select } from './ui';
9import { draftingChoices } from '../lib/drafting';
10import { NativeMcpEditor } from './NativeMcpEditor';
11/** One of the speed features: what it is called, what it does, whether it is on by default, and the engine environment it writes outside its default (server/native-settings.mjs). */
12interface SpeedSwitch {
13    id: string;
14    label: string;
15    hint: string;
16    default: 'on' | 'off';
17    env: Record<string, string>;
18    /** What an earlier test build wrote for the same state: it reads as set, and goes with it. */
19    legacy?: Record<string, string>;
20    /** The Expert settings group the row is in (Speed when not given). */
21    group?: string;
22    /** The two option names instead of On / Off (the picture reader: Strata's own / llama.cpp's). */
23    words?: { on: string; off: string };
24}
25const switchGroup = (sw: SpeedSwitch) => sw.group ?? 'Speed';
26const switchHas = (entries: Record<string, string> | undefined, env: Record<string, string> | undefined) => !!entries && Object.keys(entries).length > 0 && Object.entries(entries).every(([name, value]) => env?.[name] === value);
27const switchIsSet = (sw: SpeedSwitch, env: Record<string, string> | undefined) => switchHas(sw.env, env) || switchHas(sw.legacy, env);
28const switchIsOn = (sw: SpeedSwitch, env: Record<string, string> | undefined) => switchIsSet(sw, env) !== (sw.default === 'on');
29export function NativeSettings({ model }: {
30    model: string;
31}) {
32    const native = useNative();
33    const [revision,setRevision]=useState(0);
34    const [hints, setHints] = useState<Record<string, string>>({});   // a field's hint worded for this model (the Drafting size)
35    const [switches, setSwitches] = useState<SpeedSwitch[]>([]);   // the speed switches that apply to this model on this PC
36    const [tuned, setTuned] = useState<{ preset: { name: string } | null; changed: TunedChange[] } | null>(null);
37    const [values, setValues] = useState<Record<string, any>>({}), [mcp, setMcp] = useState('{}'), [original, setOriginal] = useState(''), [text, setText] = useState(''), [tab, setTab] = useState('fields'), [pending, setPending] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState(''), [query, setQuery] = useState('');
38    useEffect(() => {
39        let active = true;
40        setOriginal('');
41        setValues({});
42        setText('');
43        setMcp('{}');
44        setError('');
45        setNotice('');
46        void api.get<{
47            values: Record<string, any>;
48            mcp: Record<string, any>;
49            tuned?: { preset: { name: string } | null; changed: TunedChange[] } | null;
50            hints?: Record<string, string>;
51            speedSwitches?: SpeedSwitch[];
52        }>(`/api/native/models/${model}/settings`).then(input => {
53            if (!active)
54                return;
55            setSwitches(input.speedSwitches ?? []);
56            setTuned(input.tuned ?? null);
57            setHints(input.hints ?? {});
58            const value = nativeSettingsResponse(input);
59            setValues(value.values);
60            setText(JSON.stringify(value.values, null, 2));
61            setMcp(JSON.stringify(value.mcp ?? {}, null, 2));
62            setOriginal(JSON.stringify({ values: value.values, mcp: value.mcp ?? {} }));
63        }).catch(e => {
64            if (active)
65                setError(e.message);
66        });
67        return () => { active = false; };
68    }, [model,revision]);
69    const change = (id: string, value: any) => { const next = { ...values, [id]: value }; setValues(next); setText(JSON.stringify(next, null, 2)); setNotice(''); };
70    /** The default removes the switch's environment entries, the other state writes them: the model's file then carries nothing for a default launch. */
71    const changeSwitch = (sw: SpeedSwitch, on: boolean) => { const env = { ...(values.env ?? {}) }; const write = on !== (sw.default === 'on'); for (const [name, value] of Object.entries(sw.env)) { if (write) env[name] = value; else delete env[name]; } if (!write) for (const name of Object.keys(sw.legacy ?? {})) delete env[name]; change('env', env); };
72    async function save() {
73        setPending(true);
74        setError('');
75        try {
76            const parsed = nativeSettingsValues(tab === 'json' ? JSON.parse(text) : values);
77            const tools = JSON.parse(mcp);
78            const input = await api.patch<{
79                values: Record<string, any>;
80                mcp: Record<string, any>;
81            }>(`/api/native/models/${model}/settings`, { values: parsed, mcp: tools });
82            const result = nativeSettingsResponse(input);
83            setValues(result.values);
84            setMcp(JSON.stringify(result.mcp, null, 2));
85            setText(JSON.stringify(result.values, null, 2));
86            setOriginal(JSON.stringify({ values: result.values, mcp: result.mcp }));
87            setNotice('Saved. Load the model again to apply these settings. A backup of the previous configuration was kept.');
88            await refreshNative(true);
89        }
90        catch (e) {
91            setError(e instanceof Error ? e.message : String(e));
92        }
93        finally {
94            setPending(false);
95        }
96    }
97    function chooseTab(next: string) {
98        if (tab === 'json') {
99            try {
100                setValues(nativeSettingsValues(JSON.parse(text)));
101            }
102            catch {
103                setError('Fix the JSON before changing tabs.');
104                return;
105            }
106        }
107        setTab(next);
108    }
109    const dirty = (() => {
110        try {
111            return original !== JSON.stringify({ values: tab === 'json' ? JSON.parse(text) : values, mcp: JSON.parse(mcp) });
112        }
113        catch {
114            return true;
115        }
116    })();
117    if (!original) return <details className="native-settings" open={!!error}>
118      <summary>{tr('Native engine settings')}</summary>
119      {error ? <><ErrorNotice message={tr('Couldn’t load model settings.')} next={tr('Check that the engine is connected and this model is installed, then try again.')} onRetry={() => setRevision(value => value + 1)}/><details className="native-settings-diagnostic"><summary className="small">{tr('Details')}</summary><p className="small muted">{error}</p></details></> : <p className="small muted" role="status">{tr('Reading saved settings…')}</p>}
120    </details>;
121    const family = (native?.catalog?.families ?? []).find(f => f.sizes.some(s => s.id === model))?.family ?? null;
122    const draftingOffered = !!draftingChoices(family, native?.capabilities?.dflash2);
123    const rows = (native?.fields ?? []).filter(f => (f.id !== 'drafting' || draftingOffered) && `${tr(f.label)} ${f.id} ${tr(f.group)}`.toLowerCase().includes(query.toLowerCase()));
124    const switchRows = switches.filter(sw => `${tr(sw.label)} ${sw.id} ${tr(switchGroup(sw))}`.toLowerCase().includes(query.toLowerCase()));
125    const switchRow = (sw: SpeedSwitch) => <label className="native-setting-row" key={sw.id}><span><strong>{tr(sw.label)}</strong><small>{tr(sw.hint)}</small></span><Select ariaLabel={tr(sw.label)} value={switchIsOn(sw, values.env) ? 'on' : 'off'} options={sw.words ? [{ value: sw.default, label: sw.words[sw.default] }, { value: sw.default === 'on' ? 'off' : 'on', label: sw.words[sw.default === 'on' ? 'off' : 'on'] }] : sw.default === 'on' ? [{ value: 'on', label: 'On (recommended)' }, { value: 'off', label: 'Off' }] : [{ value: 'off', label: 'Off (recommended)' }, { value: 'on', label: 'On' }]} onChange={v => changeSwitch(sw, v === 'on')}/></label>;
126    return <details className="native-settings"><summary>{tr("Native engine settings")}</summary>{tr(tuned?.changed?.length ? <div className="native-tuned"><p className="small"><strong>{tr("Your tuning '{0}' sets", [tuned.preset?.name ?? ''])}</strong></p><ul>{tuned.changed.map(c => { const d = describeChange(c); return <li key={c.flag}><span>{d.name}</span><b>{d.now || tr('off')}</b>{d.was !== null ? <small className="muted">{tr("was {0}", [d.was])}</small> : null}</li>; })}</ul></div> : null)}<p className="small muted">{tr(!original ? 'Reading saved settings… ' : '')}{tr("Settings for this model. Blank values use Strata\u2019s defaults.")}</p><div className="editor-tabs" role="tablist" aria-label={tr("Native settings editor")}>{tr(['fields', 'json', 'tools'].map(t => <button key={t} role="tab" aria-selected={tab === t} onClick={() => chooseTab(t)}>{tr(t === 'fields' ? 'Parameters' : t === 'json' ? 'JSON' : 'MCP tools')}</button>))}</div>
127  {tr(tab === 'fields' ? <><input className="st-input" type="search" aria-label={tr("Search native parameters")} placeholder={tr("Search parameters…")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(['Responses', 'GPU & memory', 'Serving', 'Image reading', 'Tools', 'Recovery'].map(group => rows.some(f => f.group === group) || switchRows.some(sw => switchGroup(sw) === group) ? <section className="native-settings-group" key={group}><h3 className="h4">{tr(group)}</h3>{tr(rows.filter(f => f.group === group).map(f => <label className="native-setting-row" key={f.id}><span><strong>{tr(f.label)}</strong>{tr(f.supported === false ? <small>{tr("Requires a newer Strata installation.")}</small> : f.hint ? <small>{tr(hints[f.id] ?? f.hint)}</small> : null)}</span><NativeFieldInput field={f} value={values[f.id]} onChange={v => change(f.id, v)}/></label>))}{tr(switchRows.filter(sw => switchGroup(sw) === group).map(switchRow))}</section> : null))}{tr(switchRows.some(sw => switchGroup(sw) === 'Speed') ? <section className="native-settings-group"><h3 className="h4">{tr("Speed")}</h3>{tr(switchRows.filter(sw => switchGroup(sw) === 'Speed').map(switchRow))}</section> : null)}<section className="native-settings-group"><h3 className="h4">{tr("Sampling")}</h3>{tr([['temperature', 'Temperature'], ['top_p', 'Top-p'], ['top_k', 'Top-k'], ['min_p', 'Min-p'], ['repetition_penalty', 'Repetition penalty'], ['presence_penalty', 'Presence penalty'], ['frequency_penalty', 'Frequency penalty'], ['penalty_last_n', 'Penalty window'], ['seed', 'Seed']].map(([id, label]) => <label className="native-setting-row" key={id}><span><strong>{tr(label)}</strong></span><DecimalInput ariaLabel={tr("Native {0}", [label])} value={values.sampling?.[id] ?? null} onChange={n => { const sampling = { ...values.sampling }; if (n === null) delete sampling[id]; else sampling[id] = n; change('sampling', sampling); }}/></label>))}</section></> : tab === 'json' ? <><p className="small muted">{tr("Engine arguments and STRATA environment flags are editable here. Program paths and network access remain managed by the host.")}</p><textarea className="st-input native-json" aria-label={tr("Native configuration JSON")} spellCheck={false} value={text} onChange={e => { setText(e.target.value); setNotice(''); }}/></> : <><p className="small muted">{tr("Add local programs or HTTP MCP servers. Connected tools can read or change the resources you give them access to. Enable tools in chat when you want the model to use them.")}</p><NativeMcpEditor text={mcp} onChange={value => { setMcp(value); setNotice(''); }}/><details><summary className="small">{tr("Configuration example")}</summary><pre className="native-example">{'{\n  "files": {\n    "command": "npx",\n    "args": ["-y", "@modelcontextprotocol/server-filesystem", "/your/folder"],\n    "disabled": false\n  }\n}'}</pre><p className="xs muted">{tr("Saved credentials are masked. Keep the mask to preserve an existing value; type a new value to replace it.")}</p></details></>)}
128  <div className="native-settings-actions"><Btn disabled={pending || !original || !dirty} variant="primary" onClick={() => void save()}>{tr(pending ? 'Saving…' : 'Save settings')}</Btn><Btn disabled={pending} onClick={() => { const saved = JSON.parse(original || '{"values":{},"mcp":{}}'); setValues(saved.values); setText(JSON.stringify(saved.values, null, 2)); setMcp(JSON.stringify(saved.mcp, null, 2)); setError(''); }}>{tr("Restore saved")}</Btn></div>{tr(notice ? <p role="status" className="small">{tr(notice)}</p> : null)}{tr(error ? <ErrorNotice message={error} onRetry={() => setRevision(value => value + 1)}/> : null)}
129 </details>;
130}
131function NativeFieldInput({ field, value, onChange }: {
132    field: NativeField;
133    value: any;
134    onChange: (v: any) => void;
135}) {
136    if (field.type === 'array')
137        return <NativeAliases field={field} value={value} onChange={onChange}/>;
138    if (field.type === 'boolean')
139        return <Select disabled={field.supported === false} ariaLabel={tr(field.label)} value={value === null || value === undefined ? '' : String(value)} options={[{ value: '', label: 'Default' }, { value: 'true', label: 'On' }, { value: 'false', label: 'Off' }]} onChange={v => onChange(v === '' ? null : v === 'true')}/>;
140    if (field.type === 'enum')
141        return <Select disabled={field.supported === false} ariaLabel={tr(field.label)} value={value ?? ''} options={[{ value: '', label: 'Default' }, ...(field.choices ?? []).map(v => ({ value: v, label: v }))]} onChange={v => onChange(v || null)}/>;
142    if (field.type === 'number')
143        return <DecimalInput disabled={field.supported === false} ariaLabel={tr(field.label)} placeholder={tr("Default")} value={value === null || value === undefined || value === '' || !Number.isFinite(Number(value)) ? null : Number(value)} onChange={onChange}/>;
144    return <input disabled={field.supported === false} className="st-input" aria-label={tr(field.label)} placeholder={tr("Default")} value={Array.isArray(value) ? value.join(', ') : value ?? ''} onChange={e => onChange(e.target.value === '' ? null : field.type === 'array' ? e.target.value.split(',').map(s => s.trim()).filter(Boolean) : field.type === 'number' ? Number(e.target.value) : e.target.value)}/>;
145}
146function NativeAliases({ field, value, onChange }: {
147    field: NativeField;
148    value: any;
149    onChange: (value: any) => void;
150}) { const [draft, setDraft] = useState(Array.isArray(value) ? value.join(', ') : ''); useEffect(() => setDraft(Array.isArray(value) ? value.join(', ') : ''), [JSON.stringify(value)]); return <input className="st-input" aria-label={tr(field.label)} disabled={field.supported === false} placeholder={tr("chat, coding")} value={draft} onChange={e => setDraft(e.target.value)} onBlur={() => onChange(draft.trim() ? draft.split(',').map(v => v.trim()).filter(Boolean) : null)}/>; }