Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Expert settings: Open settings file (the model's run config in the system text editor), and a plain check of it before every start
Niko122193192196234c
diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex 9d50f448e..bbb1b3b79 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -983,6 +983,9 @@ async function api(req, res, path, method, url) {/* Expert mode shows what will actually run: the saved tuning's values come with the settings (null when none applies or unreadable). */if(nativeSettings&&method==='GET'){const settings=native.settings(nativeSettings[1]);let tuned=null;try{const t=await native.tuneEffective({model:nativeSettings[1],resourceProfile:url.searchParams.get('resourceProfile')||undefined,vision:url.searchParams.get('vision')||undefined});tuned=t.applied?t:null;}catch{tuned=null;}return json(res,200,{...settings,tuned});}if(nativeSettings&&method==='PATCH')return json(res,200,native.save(nativeSettings[1],await readBody(req)));+ const nativeSettingsFile=/^\/api\/native\/models\/([a-z0-9_-]+)\/settings-file$/.exec(path);+ if(nativeSettingsFile&&method==='GET')return json(res,200,native.settingsFile(nativeSettingsFile[1]));+ if(nativeSettingsFile&&method==='POST')return json(res,200,await native.openSettingsFile(nativeSettingsFile[1]));// Credentials are handled only on the host. Responses and events expose a key-set flag.return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message);}}diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjsindex 13c710d59..b89315cd6 100644--- a/apps/host/server/native-control.mjs+++ b/apps/host/server/native-control.mjs@@ -15,6 +15,8 @@ import { componentsDirectory, installerEnvironment, controlEnvironment } from '.import { createEngineStep } from './engine-step.mjs';import { createAutoTune, writeTuneConfig } from './native-autotune.mjs';import { plainError, PHASE_TEXT } from './update-messages.mjs';+import { checkRunConfig, describeIssues } from './run-config-check.mjs';+import { openTextFile } from './open-text-file.mjs';const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..');const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value);@@ -115,7 +117,13 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp}function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}- function record(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path,config:readJson(path)};}+ function recordFile(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path};}+ function record(model){const {entry,path}=recordFile(model);return {entry,path,config:readJson(path)};}+ /* The text file a power user edits by hand: where it is and what is wrong in it (run-config-check.mjs). */+ function settingsFile(model){const {path}=recordFile(model);return {model,path,name:basename(path),...checkRunConfig(readFileSync(path,'utf8')),note:'Changes you make in the file apply the next time the model starts.'};}+ async function openSettingsFile(model,options={}){const info=settingsFile(model);await openTextFile(info.path,options);return info;}+ /* A mistake in the file holds the start back with the line, instead of an engine that dies on it. Warnings (an unknown key) never do. */+ function assertSettingsFile(path){const check=checkRunConfig(readFileSync(path,'utf8'));if(!check.ok)throw new Error(`The settings file for this model has a mistake, so the model was not started. ${describeIssues(check.issues,'error').join(' ')}`);}function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};}function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);}function previousEngine(){if(packaged)return !!snapshot.engine?.previous;try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}}@@ -194,7 +202,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}return {cfg,resources,visionPreferences,parallelChoice,parallelNote};}async function loadEngine(job,args){- await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.');+ await refresh(true);if(job.state!=='running')return;const {config,entry,path:configFile}=record(args.model);assertSettingsFile(configFile);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.');if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.');if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.');const {cfg,resources,visionPreferences,parallelChoice,parallelNote:chosenNote}=buildConfig(args,config);@@ -347,5 +355,5 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}// Remove nonserializable process references from public jobs.const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,engineAbort,rawResult,...job})=>job);return value;};async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());}- return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close};+ return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close};}diff --git a/apps/host/server/open-text-file.mjs b/apps/host/server/open-text-file.mjsnew file mode 100644index 000000000..0214c9b66--- /dev/null+++ b/apps/host/server/open-text-file.mjs@@ -0,0 +1,38 @@+/** Open a file in the person's text editor (not the program a .json happens to belong to: that can be a browser). */+import { execFile } from 'node:child_process';+import { launch } from './chat-files.mjs';+import { externalEnvironment } from './external-env.mjs';++/** The command that opens `file` as text on this system, or null when only the file's own program is known. */+export async function textEditorCommand(file, { platform = process.platform, ask = askSystem } = {}) {+ if (platform === 'win32') return ['notepad.exe', [file]];+ if (platform === 'darwin') return ['open', ['-t', file]];+ // Linux: the program the system opens plain text with (gedit, kate, mousepad, ...), through its desktop entry.+ const entry = (await ask('xdg-mime', ['query', 'default', 'text/plain'])).trim();+ if (/^[\w.+-]+\.desktop$/.test(entry)) {+ const gtk = (await ask('sh', ['-c', 'command -v gtk-launch'])).trim();+ if (gtk) return [gtk, [entry, file]];+ const gio = (await ask('sh', ['-c', 'command -v gio'])).trim();+ if (gio) {+ for (const dir of ['/usr/share/applications', '/usr/local/share/applications', `${process.env.HOME ?? ''}/.local/share/applications`]) {+ const path = `${dir}/${entry}`;+ if ((await ask('test', ['-f', path], true)) === 'yes') return [gio, ['launch', path, file]];+ }+ }+ }+ return null;+}++function askSystem(command, args, yesNo = false) {+ return new Promise(resolve => {+ execFile(command, args, { timeout: 3000, env: externalEnvironment() }, (error, stdout) => resolve(yesNo ? (error ? 'no' : 'yes') : (error ? '' : String(stdout))));+ });+}++/** Start the editor and return at once. Falls back to the file's own program (xdg-open) when no text editor is known. */+export async function openTextFile(file, { platform = process.platform, ask, recorder = null } = {}) {+ const found = await textEditorCommand(file, { platform, ask });+ const [command, args] = found ?? ['xdg-open', [file]];+ launch(command, args, { recorder });+ return { command, args };+}diff --git a/apps/host/server/run-config-check.mjs b/apps/host/server/run-config-check.mjsnew file mode 100644index 000000000..12a02ed0d--- /dev/null+++ b/apps/host/server/run-config-check.mjs@@ -0,0 +1,140 @@+/**+ * The run config of a model (strata-<model>.json in the installation folder) is the text file a power user can edit by hand:+ * every engine option goes in "args", every STRATA_* environment flag in "env", the rest are named keys. Changes apply the next+ * time the model starts. This checks the file BEFORE the model starts and says what is wrong in plain words, with the line, so a+ * typo is never a start that just fails.+ *+ * Errors (the start is held back until they are fixed): the file is not valid JSON, or a key the app knows has a value it cannot use.+ * Warnings (the start goes on): a key nothing reads (probably a typo; the nearest real name is offered), an option the app manages itself.+ *+ * Each issue is { level, code, key, line, params, message }: `code` and `params` are what the screen translates (src/lib/run-config-issues.ts),+ * `message` is the same sentence in English for logs and the Details of a refused start.+ */+import { NATIVE_FIELDS } from './native-settings.mjs';++/** Every top-level key a run config may carry: what setup writes, what serve/server.py reads, the app's own fields. */+export const KNOWN_KEYS = new Set([+ ...NATIVE_FIELDS.map(f => f.id),+ 'exe', 'args', 'cwd', 'tokenizer', 'model_name', 'model', 'arch', 'log', 'lib_dirs', 'port', 'host', 'api_key', 'cuda', 'backend', 'gpu', 'gpus_asked',+ 'gpu_policy', 'hip_ordinal', 'env', 'env_to_user', 'sampling', 'mcp_servers', 'mcpServers', 'before_load', 'before_load_ignore_failure',+ 'before_load_strict', 'before_load_timeout_s', 'cors_origins', 'trusted_origins', 'allowed_hosts', 'open_browser', 'prevent_sleep',+ 'max_queue', 'queue_timeout', 'max_tokens', 'min_tokens', 'answer_room', 'threads', 'replicas', 'replica_cpus', 'replica_load_tokens',+ 'elastic', 'elastic_idle_s', 'elastic_mib', 'min_free_vram_mib', 'vram_segment_mib', 'slot_save_path', 'telemetry_read_key', 'batch_telemetry',+ 'reasoning_effort', 'reasoning_close_retry', 'reasoning_loop_recovery', 'repeat_stop_tokens', 'tool_call_recovery', 'codex_compaction_cache',+ 'codex_thread_titles', 'expert_profile_save', 'expert_profile_save_every', 'images', 'vision', 'mmproj', 'draft_vocab', 'ui_resource_profile',+ 'ui_vision_enabled', 'component', 'native', 'uma', 'remote_expert_opt', 'diffusion_model', 'llm', 'vae', 'quant', 'type', 'url', 'timeout_s',+]);++const BOOLS = new Set(['open_browser', 'prevent_sleep', 'elastic', 'env_to_user', 'gpus_asked', 'batch_telemetry', 'tool_call_recovery', 'reasoning_loop_recovery']);+const NUMBERS = { port: [1, 65535], max_queue: [0, 1e6], queue_timeout: [0, 1e6], threads: [1, 4096], elastic_idle_s: [0, 1e7], min_free_vram_mib: [0, 1e7] };+const REASONING = ['none', 'low', 'medium', 'high'];+const SAMPLING = { temperature: [0, 10], top_p: [0, 1], top_k: [1, 64], min_p: [0, 1], presence_penalty: [-10, 10], repetition_penalty: [0, 10], repeat_penalty: [0, 10], frequency_penalty: [-10, 10], penalty_last_n: [0, 1048576], repeat_last_n: [0, 1048576], seed: [0, 4294967295] };+const WHOLE = new Set(['top_k', 'penalty_last_n', 'repeat_last_n', 'seed']);++function distance(a, b) {+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);+ for (let i = 1; i <= a.length; i++) {+ let prev = row[0]; row[0] = i;+ for (let j = 1; j <= b.length; j++) { const keep = row[j]; row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); prev = keep; }+ }+ return row[b.length];+}+/** The real key a mistyped one most likely meant, or null. */+export function nearestKey(key, known = KNOWN_KEYS) {+ let best = null, score = Infinity;+ const lower = key.toLowerCase().replace(/[-\s]/g, '_');+ for (const candidate of known) {+ const d = lower === candidate ? 0 : distance(lower, candidate);+ if (d < score) { score = d; best = candidate; }+ }+ return score <= Math.max(2, Math.floor(key.length / 4)) ? best : null;+}++const escape = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+/** 1-based line of a top-level key in the text, or null. */+function lineOf(text, key) {+ const m = new RegExp(`^[ \\t]{0,8}"${escape(key)}"\\s*:`, 'm').exec(text);+ return m ? text.slice(0, m.index).split('\n').length : null;+}++const show = v => { const t = JSON.stringify(v); return t === undefined ? 'nothing' : t.length > 40 ? `${t.slice(0, 37)}…` : t; };++/**+ * `text` is the file as it is on disk. Returns { ok, issues } where ok means no errors (warnings may remain). Never throws.+ */+export function checkRunConfig(text, { known = KNOWN_KEYS } = {}) {+ text = String(text ?? '');+ const issues = [];+ const add = (level, code, key, params, message) => issues.push({ level, code, key, line: key ? lineOf(text, key) : null, params, message });+ let config;+ try { config = JSON.parse(text.replace(/^/, '')); }+ catch (e) {+ const position = /position (\d+)/.exec(e.message ?? '');+ const line = position ? text.slice(0, Number(position[1])).split('\n').length : null;+ issues.push({ level: 'error', code: 'json', key: null, line, params: { line: line ?? 0 },+ message: `The settings file is not valid JSON${line ? `; look near line ${line}` : ''}. Check for a missing comma between two entries, a comma after the last entry, or a missing quote.` });+ return { ok: false, issues };+ }+ if (!config || typeof config !== 'object' || Array.isArray(config)) {+ issues.push({ level: 'error', code: 'not-object', key: null, line: null, params: {}, message: 'The settings file must hold one object, { … }, with the settings inside.' });+ return { ok: false, issues };+ }+ const fields = new Map(NATIVE_FIELDS.map(f => [f.id, f]));+ for (const [key, value] of Object.entries(config)) {+ if (!known.has(key)) {+ const near = nearestKey(key, known);+ add('warning', near ? 'unknown-key-near' : 'unknown-key', key, { key, near: near ?? '' }, `"${key}" is not a setting Strata reads, so it is ignored.${near ? ` Did you mean "${near}"?` : ''}`);+ continue;+ }+ if (value === null) continue;+ if (key === 'args') {+ if (!Array.isArray(value) || value.some(v => typeof v !== 'string')) add('error', 'args-type', key, {}, '"args" must be a list of quoted text entries, for example ["--ple-io", "mmap"]. Numbers need quotes too.');+ else if (value.some(v => ['--host', '--port', '--api-key'].includes(v))) add('warning', 'args-managed', key, {}, 'Strata manages the network address, port and API key itself, so --host, --port and --api-key in "args" are not honoured.');+ } else if (key === 'env') {+ if (!value || typeof value !== 'object' || Array.isArray(value)) add('error', 'env-type', key, {}, '"env" must be an object of names with quoted text values, for example { "STRATA_X": "1" }.');+ else for (const [name, v] of Object.entries(value)) {+ if (typeof v !== 'string') add('error', 'env-value', key, { name }, `"env" entry ${name} must be quoted text, for example "1", not ${show(v)}.`);+ }+ } else if (key === 'sampling') {+ if (!value || typeof value !== 'object' || Array.isArray(value)) add('error', 'sampling-type', key, {}, '"sampling" must be an object such as { "temperature": 0.7 }.');+ else for (const [name, n] of Object.entries(value)) {+ if (n === null) continue;+ if (name === 'experimental_speed_projection') { if (typeof n !== 'boolean') add('error', 'bool', key, { key: `sampling.${name}` }, `"sampling.${name}" must be true or false.`); continue; }+ if (!SAMPLING[name]) { add('warning', 'unknown-key', key, { key: `sampling.${name}`, near: '' }, `"sampling.${name}" is not a setting Strata reads, so it is ignored.`); continue; }+ const [lo, hi] = SAMPLING[name];+ if (typeof n !== 'number' || !Number.isFinite(n) || n < lo || n > hi || (WHOLE.has(name) && !Number.isInteger(n))) add('error', WHOLE.has(name) ? 'whole-range' : 'number-range', key, { key: `sampling.${name}`, min: lo, max: hi, value: show(n) }, `"sampling.${name}" must be ${WHOLE.has(name) ? 'a whole ' : 'a '}number from ${lo} to ${hi}, not ${show(n)}.`);+ }+ } else if (fields.has(key)) {+ const f = fields.get(key);+ if (value === '') continue;+ if (f.type === 'number' && (typeof value !== 'number' || !Number.isInteger(value) || value < f.min || value > f.max)) add('error', 'whole-range', key, { key, min: f.min, max: f.max, value: show(value) }, `"${key}" must be a whole number from ${f.min} to ${f.max}, not ${show(value)}.`);+ else if (f.type === 'boolean' && typeof value !== 'boolean') add('error', 'bool', key, { key, value: show(value) }, `"${key}" must be true or false, not ${show(value)}.`);+ else if (f.type === 'enum' && !f.choices.includes(value)) add('error', 'choice', key, { key, choices: f.choices.join(', '), value: show(value) }, `"${key}" must be one of ${f.choices.join(', ')}, not ${show(value)}.`);+ else if (f.type === 'string' && (typeof value !== 'string' || value.length > 256)) add('error', 'text', key, { key }, `"${key}" must be text of at most 256 characters.`);+ else if (f.type === 'array') {+ const list = typeof value === 'string' ? value.split(',').map(v => v.trim()).filter(Boolean) : value;+ if (!Array.isArray(list) || list.length > 24 || list.some(v => typeof v !== 'string' || !v.trim() || v.length > 80)) add('error', 'text', key, { key }, `"${key}" must be a list of short names, for example ["chat", "coding"].`);+ }+ if (key === 'layer_split' && typeof value === 'string' && value !== 'auto') {+ const points = value.split(',').map(Number);+ if (!points.length || points.some((n, i) => !Number.isInteger(n) || n < 1 || n >= 48 || (i > 0 && n <= points[i - 1]))) add('error', 'layer-split', key, {}, '"layer_split" points must increase from 1 to 47, for example "16,32", or be "auto".');+ }+ } else if (BOOLS.has(key)) {+ if (typeof value !== 'boolean') add('error', 'bool', key, { key, value: show(value) }, `"${key}" must be true or false, not ${show(value)}.`);+ } else if (key in NUMBERS) {+ const [lo, hi] = NUMBERS[key];+ if (typeof value !== 'number' || !Number.isFinite(value) || value < lo || value > hi) add('error', 'number-range', key, { key, min: lo, max: hi, value: show(value) }, `"${key}" must be a number from ${lo} to ${hi}, not ${show(value)}.`);+ } else if (key === 'reasoning_effort') {+ if (!REASONING.includes(value)) add('error', 'choice', key, { key, choices: REASONING.join(', '), value: show(value) }, `"reasoning_effort" must be one of ${REASONING.join(', ')}, not ${show(value)}.`);+ } else if (key === 'gpu') {+ const ok = Number.isInteger(value) && value >= 0 || Array.isArray(value) && value.length > 0 && value.every(n => Number.isInteger(n) && n >= 0);+ if (!ok) add('error', 'gpu', key, {}, '"gpu" must be a graphics card number such as 0, or a list such as [0, 1].');+ }+ }+ return { ok: !issues.some(i => i.level === 'error'), issues };+}++/** The English lines of the issues, `Line 12: …`, for the Details of a refused start. */+export function describeIssues(issues, level) {+ return issues.filter(i => !level || i.level === level).map(i => `${i.line ? `Line ${i.line}: ` : ''}${i.message}`);+}diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsxindex 0b9d01d9f..345f7cdb7 100644--- a/apps/host/src/components/NativeModels.tsx+++ b/apps/host/src/components/NativeModels.tsx@@ -16,6 +16,7 @@ import { nativeAction, useNative, type NativeJob } from '../lib/native';import { tuneEffective } from '../lib/native-tune';import { tunedFields } from '../lib/tune-values';import { NativeSettings } from './NativeSettings';+import { NativeSettingsFile } from './NativeSettingsFile';import { RunImageModel } from './RunImageModel';import { IMAGE_GENERATION_VISIBLE } from '../lib/features';import { useStore } from '../lib/store';@@ -145,7 +146,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine<div className="native-model-actions">{tr(loadedSelected ? <><Btn disabled={pending || !!active} onClick={() => void perform(() => nativeAction(`instances/${loadedSelected.id}/unload`))}>{tr("Unload")}</Btn>{tr(onReady ? <Btn variant="primary" onClick={onReady}>{tr("Start chatting")}</Btn> : <span className="native-ready">{tr("Ready")}</span>)}</> : onReady && native?.instances.some(i => i.status === 'ready') ? <Btn variant="primary" onClick={onReady}>{tr("Start chatting")}</Btn> : <><Btn icon="gauge" disabled={!installed?.ready || !native?.available || !!active || !selectedSize} onClick={() => setTuneOpen(true)}>{tr("Tune model")}</Btn><Btn variant="primary" icon="models" disabled={pending || !native?.available || !!active || !selectedSize || expert && deviceChoice === 'split' && gpus.length < 2} onClick={() => void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')}</Btn></>)}</div></section>{tr(expert && IMAGE_GENERATION_VISIBLE ? <><details className="native-generation"><summary>{tr("Image generation ")}<span className="muted">{tr("Optional")}</span></summary><RunImageModel library={imageLibrary} disabled={pending || !!active} onChange={() => { }}/></details></> : null)}- {tr(expert ? <section id="native-expert-settings" ref={expertSection} className="st-card native-execution"><h2 className="h4">{tr("Expert settings")}</h2>{tr(tunedNow ? <p className="small muted native-tuned-note">{tr("Showing the values of your tuning '{0}'.", [tunedNow.name])}</p> : null)}<label className="native-toggle"><span><strong>{tr("Run multiple models")}</strong><small>{tr("Loading another model keeps the others loaded.")}</small></span><button className="st-toggle" role="switch" aria-label={tr("Run multiple models")} aria-checked={multiple} onClick={() => setMultiple(v => !v)}/></label><h3 className="small strong">{tr("Run on")}</h3><p className="small muted">{tr("Automatic uses the installation\u2019s GPU placement. Choose a GPU, or split this model across several GPUs.")}</p><Select ariaLabel={tr("Run on")} value={deviceChoice} options={[{ value: 'auto', label: 'Automatic' }, ...(native?.hardware?.gpus ?? []).map(g => ({ value: String(g.index), label: `GPU ${g.index + 1} · ${g.name}` })), ...((native?.hardware?.gpus.length ?? 0) > 1 ? [{ value: 'split', label: 'Split across GPUs…' }] : [])]} onChange={value => { setDeviceChoice(value); setGpus(value === 'auto' ? [] : value === 'split' ? (native?.hardware?.gpus ?? []).map(g => g.index) : [Number(value)]); }}/>{tr(deviceChoice === 'split' ? <div className="native-gpu-options">{tr(native?.hardware?.gpus.map(g => <label key={g.index}><input type="checkbox" checked={gpus.includes(g.index)} onChange={e => setGpus(old => e.target.checked ? [...old, g.index] : old.filter(i => i !== g.index))}/><span>{tr("GPU ")}{tr(g.index + 1)} · {tr(g.name)}<small>{tr(g.vram_gb)}{tr(" GB VRAM")}</small></span></label>))}</div> : null)}{tr(gpus.length > 1 ? <label className="input-field"><span>{tr("Layer split")}</span><input className="st-input" value={split} placeholder={tr("auto or 16,32")} onChange={e => setSplit(e.target.value)}/></label> : null)}<div className="native-field-grid"><label className="input-field"><span>{tr("Context memory")}</span><Select ariaLabel={tr("Native KV format")} value={kv} options={[{ value: 'int8', label: 'INT8' }, { value: 'q4_0', label: 'Q4' }, { value: 'k8v4', label: 'K8 / V4' }]} onChange={setKv}/></label><label className="input-field"><span>{tr("Low-RAM mode")}</span><Select ariaLabel={tr("Native low RAM mode")} value={lowRam} options={['auto', 'resident', 'mmap'].map(v => ({ value: v, label: v === 'auto' ? 'Automatic' : v === 'resident' ? 'Keep experts in RAM' : 'Read experts from disk' }))} onChange={setLowRam}/></label></div>{tr(installed ? <NativeSettings model={installed.model}/> : <p className="small muted">{tr("More engine parameters become available after preparing this version.")}</p>)}</section> : null)}+ {tr(expert ? <section id="native-expert-settings" ref={expertSection} className="st-card native-execution"><h2 className="h4">{tr("Expert settings")}</h2>{tr(tunedNow ? <p className="small muted native-tuned-note">{tr("Showing the values of your tuning '{0}'.", [tunedNow.name])}</p> : null)}<label className="native-toggle"><span><strong>{tr("Run multiple models")}</strong><small>{tr("Loading another model keeps the others loaded.")}</small></span><button className="st-toggle" role="switch" aria-label={tr("Run multiple models")} aria-checked={multiple} onClick={() => setMultiple(v => !v)}/></label><h3 className="small strong">{tr("Run on")}</h3><p className="small muted">{tr("Automatic uses the installation\u2019s GPU placement. Choose a GPU, or split this model across several GPUs.")}</p><Select ariaLabel={tr("Run on")} value={deviceChoice} options={[{ value: 'auto', label: 'Automatic' }, ...(native?.hardware?.gpus ?? []).map(g => ({ value: String(g.index), label: `GPU ${g.index + 1} · ${g.name}` })), ...((native?.hardware?.gpus.length ?? 0) > 1 ? [{ value: 'split', label: 'Split across GPUs…' }] : [])]} onChange={value => { setDeviceChoice(value); setGpus(value === 'auto' ? [] : value === 'split' ? (native?.hardware?.gpus ?? []).map(g => g.index) : [Number(value)]); }}/>{tr(deviceChoice === 'split' ? <div className="native-gpu-options">{tr(native?.hardware?.gpus.map(g => <label key={g.index}><input type="checkbox" checked={gpus.includes(g.index)} onChange={e => setGpus(old => e.target.checked ? [...old, g.index] : old.filter(i => i !== g.index))}/><span>{tr("GPU ")}{tr(g.index + 1)} · {tr(g.name)}<small>{tr(g.vram_gb)}{tr(" GB VRAM")}</small></span></label>))}</div> : null)}{tr(gpus.length > 1 ? <label className="input-field"><span>{tr("Layer split")}</span><input className="st-input" value={split} placeholder={tr("auto or 16,32")} onChange={e => setSplit(e.target.value)}/></label> : null)}<div className="native-field-grid"><label className="input-field"><span>{tr("Context memory")}</span><Select ariaLabel={tr("Native KV format")} value={kv} options={[{ value: 'int8', label: 'INT8' }, { value: 'q4_0', label: 'Q4' }, { value: 'k8v4', label: 'K8 / V4' }]} onChange={setKv}/></label><label className="input-field"><span>{tr("Low-RAM mode")}</span><Select ariaLabel={tr("Native low RAM mode")} value={lowRam} options={['auto', 'resident', 'mmap'].map(v => ({ value: v, label: v === 'auto' ? 'Automatic' : v === 'resident' ? 'Keep experts in RAM' : 'Read experts from disk' }))} onChange={setLowRam}/></label></div>{tr(installed ? <><NativeSettingsFile model={installed.model}/><NativeSettings model={installed.model}/></> : <p className="small muted">{tr("More engine parameters become available after preparing this version.")}</p>)}</section> : null)}</div><aside className="stack stack--lg"><PcFitCard gpuName={pcGpu?.name} ramGb={pcRam} vramGb={pcVram} fit={selectedSize ? fitOn(selectedSize, fitHardware) : null}/><section className="st-card"><h2 className="h4">{tr("Model files")}</h2><p className="small muted">{tr("Strata prepares all shards, the draft layer and shared files. Completed downloads are reused.")}</p><code className="native-path">{installed?.dataFolder ?? native?.downloadDirectory ?? native?.installed?.data_folder ?? 'Choose an installation'}</code><Btn size="sm" variant="ghost" onClick={() => { setSettingsSection('Storage'); go('settings'); }}>{tr("Storage settings")}</Btn></section><Btn size="sm" variant="ghost" onClick={onOtherModels}>{tr("Other local models\u2026")}</Btn></aside></div>diff --git a/apps/host/src/components/NativeSettingsFile.tsx b/apps/host/src/components/NativeSettingsFile.tsxnew file mode 100644index 000000000..4fcd58684--- /dev/null+++ b/apps/host/src/components/NativeSettingsFile.tsx@@ -0,0 +1,43 @@+import { tr } from '../lib/i18n';+import { useCallback, useEffect, useState } from 'react';+import { api } from '../lib/client';+import { Btn, ErrorNotice } from './ui';+import { issueText, type SettingsFileInfo } from '../lib/run-config-issues';++/**+ * Expert settings: the model's settings live in one text file (its run configuration). A power user opens it in the system+ * text editor and changes any engine option; the change applies the next time the model starts. The file is checked here and+ * again before the model starts, and a mistake is shown in plain words with its line.+ */+export function NativeSettingsFile({ model }: { model: string }) {+ const [info, setInfo] = useState<SettingsFileInfo | null>(null), [pending, setPending] = useState(false), [error, setError] = useState('');+ const check = useCallback(() => api.get<SettingsFileInfo>(`/api/native/models/${model}/settings-file`).then(value => { setInfo(value); setError(''); }).catch(() => setInfo(null)), [model]);+ useEffect(() => {+ void check();+ // Back from the editor: look at the file again.+ const again = () => void check();+ window.addEventListener('focus', again);+ return () => window.removeEventListener('focus', again);+ }, [check]);+ async function open() {+ setPending(true);+ setError('');+ try {+ setInfo(await api.post<SettingsFileInfo>(`/api/native/models/${model}/settings-file`, {}));+ }+ catch (e) {+ setError((e as Error).message);+ }+ finally {+ setPending(false);+ }+ }+ const errors = info?.issues.filter(i => i.level === 'error') ?? [], warnings = info?.issues.filter(i => i.level === 'warning') ?? [];+ return <div className="native-settings-file">+ <h3 className="small strong">{tr("Settings file")}</h3>+ <div className="row"><Btn size="sm" disabled={pending || !info} onClick={() => void open()}>{tr("Open settings file")}</Btn><span className="small muted">{tr("Changes you make in the file apply the next time the model starts.")}</span></div>+ {tr(error ? <ErrorNotice message={error} next={tr("Open the file from its folder instead, or try again.")}/> : null)}+ {tr(errors.length ? <><ErrorNotice message={tr("Your settings file has a mistake, so the model will not start until it is fixed.")} next={tr("Open the settings file, fix the lines below, and load the model again.")}/>{tr(errors.map((issue, i) => <p className="small" key={`e${i}`}>{tr(issueText(issue))}</p>))}</> : null)}+ {tr(warnings.map((issue, i) => <p className="small muted" key={`w${i}`}>{tr(issueText(issue))}</p>))}+ </div>;+}diff --git a/apps/host/src/lib/plain-errors.ts b/apps/host/src/lib/plain-errors.tsindex 0c191037a..8b2997046 100644--- a/apps/host/src/lib/plain-errors.ts+++ b/apps/host/src/lib/plain-errors.ts@@ -15,6 +15,7 @@ const MEMORY_NEXT = 'Close other programs and try again, or choose “Leave 20%/** Order matters: the first rule that matches wins. */const RULES: Rule[] = [+ { kind: 'settings-file', match: /settings file for this model has a mistake/i, message: 'Your settings file has a mistake, so the model was not started.', next: 'Open the settings file under Expert settings, fix the line shown under Details, then load the model again.' },{ kind: 'connector-missing', match: /connector \(cloudflared\) is not installed/i, message: 'Strata could not find Cloudflare’s connector (cloudflared) on this computer.', next: 'Install cloudflared (with your package manager, or from Cloudflare’s website), then press Retry setup. Strata finds it on your PATH and in the usual places.' },{ kind: 'connector-old', match: /cloudflared at .* is version .* too old/i, message: 'The Cloudflare connector on this computer is too old.', next: 'Update cloudflared to a newer version, then press Retry setup.' },{ kind: 'connector-broken', match: /did not run as cloudflared/i, message: 'The file found as cloudflared did not run.', next: 'Reinstall cloudflared, then press Retry setup.' },diff --git a/apps/host/src/lib/run-config-issues.ts b/apps/host/src/lib/run-config-issues.tsnew file mode 100644index 000000000..b64880f55--- /dev/null+++ b/apps/host/src/lib/run-config-issues.ts@@ -0,0 +1,32 @@+/** The checks of a hand-edited run config (server/run-config-check.mjs) as sentences in the person's language. */+import { tr } from './i18n';++export interface RunConfigIssue { level: 'error' | 'warning'; code: string; key: string | null; line: number | null; params: Record<string, string | number>; message: string }+export interface SettingsFileInfo { model: string; path: string; name: string; ok: boolean; issues: RunConfigIssue[]; note: string }++/** One issue as a sentence. Every sentence is a fixed string so every language has it; names and numbers are slots. */+export function issueText(issue: RunConfigIssue): string {+ const p = issue.params;+ const text = (() => {+ switch (issue.code) {+ case 'json': return p.line ? tr('The settings file is not valid JSON; look near line {0}. Check for a missing comma between two entries, a comma after the last entry, or a missing quote.', [p.line]) : tr('The settings file is not valid JSON. Check for a missing comma between two entries, a comma after the last entry, or a missing quote.');+ case 'not-object': return tr('The settings file must hold one object, { … }, with the settings inside.');+ case 'unknown-key-near': return tr('"{0}" is not a setting Strata reads, so it is ignored. Did you mean "{1}"?', [p.key, p.near]);+ case 'unknown-key': return tr('"{0}" is not a setting Strata reads, so it is ignored.', [p.key]);+ case 'args-type': return tr('"args" must be a list of quoted text entries, for example ["--ple-io", "mmap"]. Numbers need quotes too.');+ case 'args-managed': return tr('Strata manages the network address, port and API key itself, so --host, --port and --api-key in "args" are not honoured.');+ case 'env-type': return tr('"env" must be an object of STRATA_ names with quoted text values.');+ case 'env-value': return tr('"env" entry {0} must be quoted text, for example "1".', [p.name]);+ case 'sampling-type': return tr('"sampling" must be an object such as { "temperature": 0.7 }.');+ case 'bool': return tr('"{0}" must be true or false, not {1}.', [p.key, p.value ?? '']);+ case 'number-range': return tr('"{0}" must be a number from {1} to {2}, not {3}.', [p.key, p.min, p.max, p.value]);+ case 'whole-range': return tr('"{0}" must be a whole number from {1} to {2}, not {3}.', [p.key, p.min, p.max, p.value]);+ case 'choice': return tr('"{0}" must be one of {1}, not {2}.', [p.key, p.choices, p.value]);+ case 'text': return tr('"{0}" must be short text, or a list of short names.', [p.key]);+ case 'layer-split': return tr('"layer_split" points must increase from 1 to 47, for example "16,32", or be "auto".');+ case 'gpu': return tr('"gpu" must be a graphics card number such as 0, or a list such as [0, 1].');+ default: return issue.message;+ }+ })();+ return issue.line ? tr('Line {0}: {1}', [issue.line, text]) : text;+}diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.jsonindex 81f48bb29..0848bcd64 100644--- a/apps/host/src/locales/de.json+++ b/apps/host/src/locales/de.json@@ -3161,5 +3161,31 @@"s3165": "Der Cloudflare-Connector auf diesem Computer ist zu alt.","s3166": "Aktualisiere cloudflared auf eine neuere Version und drücke dann „Einrichtung erneut versuchen“.","s3167": "Die als cloudflared gefundene Datei ließ sich nicht ausführen.",- "s3168": "Installiere cloudflared neu und drücke dann „Einrichtung erneut versuchen“."+ "s3168": "Installiere cloudflared neu und drücke dann „Einrichtung erneut versuchen“.",+ "s3169": "Einstellungsdatei",+ "s3170": "Einstellungsdatei öffnen",+ "s3171": "Änderungen in der Datei gelten beim nächsten Start des Modells.",+ "s3172": "Öffne die Datei stattdessen aus ihrem Ordner oder versuche es erneut.",+ "s3173": "In deiner Einstellungsdatei steckt ein Fehler, deshalb startet das Modell erst, wenn er behoben ist.",+ "s3174": "Öffne die Einstellungsdatei, behebe die unten genannten Zeilen und lade das Modell erneut.",+ "s3175": "Die Einstellungsdatei ist kein gültiges JSON; sieh dir die Gegend um Zeile {0} an. Prüfe auf ein fehlendes Komma zwischen zwei Einträgen, ein Komma nach dem letzten Eintrag oder ein fehlendes Anführungszeichen.",+ "s3176": "Die Einstellungsdatei ist kein gültiges JSON. Prüfe auf ein fehlendes Komma zwischen zwei Einträgen, ein Komma nach dem letzten Eintrag oder ein fehlendes Anführungszeichen.",+ "s3177": "Die Einstellungsdatei muss ein einzelnes Objekt { … } mit den Einstellungen darin enthalten.",+ "s3178": "„{0}“ ist keine Einstellung, die Strata liest, und wird ignoriert. Meintest du „{1}“?",+ "s3179": "„{0}“ ist keine Einstellung, die Strata liest, und wird ignoriert.",+ "s3180": "„args“ muss eine Liste von Texteinträgen in Anführungszeichen sein, zum Beispiel [\"--ple-io\", \"mmap\"]. Auch Zahlen brauchen Anführungszeichen.",+ "s3181": "Strata verwaltet Netzwerkadresse, Port und API-Schlüssel selbst, daher werden --host, --port und --api-key in „args“ nicht beachtet.",+ "s3182": "„env“ muss ein Objekt aus STRATA_-Namen mit Textwerten in Anführungszeichen sein.",+ "s3183": "„env“-Eintrag {0} muss Text in Anführungszeichen sein, zum Beispiel \"1\".",+ "s3184": "„sampling“ muss ein Objekt sein, zum Beispiel { \"temperature\": 0.7 }.",+ "s3185": "„{0}“ muss true oder false sein, nicht {1}.",+ "s3186": "„{0}“ muss eine Zahl von {1} bis {2} sein, nicht {3}.",+ "s3187": "„{0}“ muss eine ganze Zahl von {1} bis {2} sein, nicht {3}.",+ "s3188": "„{0}“ muss einer dieser Werte sein: {1}, nicht {2}.",+ "s3189": "„{0}“ muss ein kurzer Text oder eine Liste kurzer Namen sein.",+ "s3190": "Die Werte von „layer_split“ müssen von 1 bis 47 aufsteigen, zum Beispiel \"16,32\", oder \"auto\" lauten.",+ "s3191": "„gpu“ muss eine Grafikkartennummer wie 0 oder eine Liste wie [0, 1] sein.",+ "s3192": "Zeile {0}: {1}",+ "s3193": "In deiner Einstellungsdatei steckt ein Fehler, deshalb wurde das Modell nicht gestartet.",+ "s3194": "Öffne die Einstellungsdatei unter „Experteneinstellungen“, behebe die unter „Details“ gezeigte Zeile und lade das Modell dann erneut."}diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.jsonindex 88bbab521..abad2321e 100644--- a/apps/host/src/locales/en.json+++ b/apps/host/src/locales/en.json@@ -3161,5 +3161,31 @@"s3165": "The Cloudflare connector on this computer is too old.","s3166": "Update cloudflared to a newer version, then press Retry setup.","s3167": "The file found as cloudflared did not run.",- "s3168": "Reinstall cloudflared, then press Retry setup."+ "s3168": "Reinstall cloudflared, then press Retry setup.",+ "s3169": "Settings file",+ "s3170": "Open settings file",+ "s3171": "Changes you make in the file apply the next time the model starts.",+ "s3172": "Open the file from its folder instead, or try again.",+ "s3173": "Your settings file has a mistake, so the model will not start until it is fixed.",+ "s3174": "Open the settings file, fix the lines below, and load the model again.",+ "s3175": "The settings file is not valid JSON; look near line {0}. Check for a missing comma between two entries, a comma after the last entry, or a missing quote.",+ "s3176": "The settings file is not valid JSON. Check for a missing comma between two entries, a comma after the last entry, or a missing quote.",+ "s3177": "The settings file must hold one object, { … }, with the settings inside.",+ "s3178": "\"{0}\" is not a setting Strata reads, so it is ignored. Did you mean \"{1}\"?",+ "s3179": "\"{0}\" is not a setting Strata reads, so it is ignored.",+ "s3180": "\"args\" must be a list of quoted text entries, for example [\"--ple-io\", \"mmap\"]. Numbers need quotes too.",+ "s3181": "Strata manages the network address, port and API key itself, so --host, --port and --api-key in \"args\" are not honoured.",+ "s3182": "\"env\" must be an object of STRATA_ names with quoted text values.",+ "s3183": "\"env\" entry {0} must be quoted text, for example \"1\".",+ "s3184": "\"sampling\" must be an object such as { \"temperature\": 0.7 }.",+ "s3185": "\"{0}\" must be true or false, not {1}.",+ "s3186": "\"{0}\" must be a number from {1} to {2}, not {3}.",+ "s3187": "\"{0}\" must be a whole number from {1} to {2}, not {3}.",+ "s3188": "\"{0}\" must be one of {1}, not {2}.",+ "s3189": "\"{0}\" must be short text, or a list of short names.",+ "s3190": "\"layer_split\" points must increase from 1 to 47, for example \"16,32\", or be \"auto\".",+ "s3191": "\"gpu\" must be a graphics card number such as 0, or a list such as [0, 1].",+ "s3192": "Line {0}: {1}",+ "s3193": "Your settings file has a mistake, so the model was not started.",+ "s3194": "Open the settings file under Expert settings, fix the line shown under Details, then load the model again."}diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.jsonindex c92e13889..44aa044ab 100644--- a/apps/host/src/locales/es.json+++ b/apps/host/src/locales/es.json@@ -3161,5 +3161,31 @@"s3165": "El conector de Cloudflare de este equipo es demasiado antiguo.","s3166": "Actualiza cloudflared a una versión más reciente y pulsa «Reintentar configuración».","s3167": "El archivo encontrado como cloudflared no se pudo ejecutar.",- "s3168": "Reinstala cloudflared y pulsa «Reintentar configuración»."+ "s3168": "Reinstala cloudflared y pulsa «Reintentar configuración».",+ "s3169": "Archivo de ajustes",+ "s3170": "Abrir archivo de ajustes",+ "s3171": "Los cambios que hagas en el archivo se aplican la próxima vez que se inicie el modelo.",+ "s3172": "Abre el archivo desde su carpeta o inténtalo de nuevo.",+ "s3173": "Tu archivo de ajustes tiene un error, así que el modelo no se iniciará hasta que lo corrijas.",+ "s3174": "Abre el archivo de ajustes, corrige las líneas de abajo y vuelve a cargar el modelo.",+ "s3175": "El archivo de ajustes no es un JSON válido; revisa cerca de la línea {0}. Comprueba si falta una coma entre dos entradas, si sobra una coma tras la última o si falta una comilla.",+ "s3176": "El archivo de ajustes no es un JSON válido. Comprueba si falta una coma entre dos entradas, si sobra una coma tras la última o si falta una comilla.",+ "s3177": "El archivo de ajustes debe contener un único objeto, { … }, con los ajustes dentro.",+ "s3178": "«{0}» no es un ajuste que Strata lea, así que se ignora. ¿Querías decir «{1}»?",+ "s3179": "«{0}» no es un ajuste que Strata lea, así que se ignora.",+ "s3180": "«args» debe ser una lista de entradas de texto entre comillas, por ejemplo [\"--ple-io\", \"mmap\"]. Los números también llevan comillas.",+ "s3181": "Strata gestiona por sí mismo la dirección de red, el puerto y la clave de API, así que --host, --port y --api-key en «args» no se tienen en cuenta.",+ "s3182": "«env» debe ser un objeto de nombres STRATA_ con valores de texto entre comillas.",+ "s3183": "La entrada «env» {0} debe ser texto entre comillas, por ejemplo \"1\".",+ "s3184": "«sampling» debe ser un objeto como { \"temperature\": 0.7 }.",+ "s3185": "«{0}» debe ser true o false, no {1}.",+ "s3186": "«{0}» debe ser un número de {1} a {2}, no {3}.",+ "s3187": "«{0}» debe ser un número entero de {1} a {2}, no {3}.",+ "s3188": "«{0}» debe ser uno de estos valores: {1}, no {2}.",+ "s3189": "«{0}» debe ser un texto corto o una lista de nombres cortos.",+ "s3190": "Los puntos de «layer_split» deben aumentar de 1 a 47, por ejemplo \"16,32\", o ser \"auto\".",+ "s3191": "«gpu» debe ser el número de una tarjeta gráfica, como 0, o una lista como [0, 1].",+ "s3192": "Línea {0}: {1}",+ "s3193": "Tu archivo de ajustes tiene un error, así que el modelo no se ha iniciado.",+ "s3194": "Abre el archivo de ajustes en «Ajustes expertos», corrige la línea que aparece en «Detalles» y vuelve a cargar el modelo."}diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.jsonindex dd644d271..19714a4d4 100644--- a/apps/host/src/locales/ja.json+++ b/apps/host/src/locales/ja.json@@ -3161,5 +3161,31 @@"s3165": "このコンピューターのCloudflareコネクターは古すぎます。","s3166": "cloudflaredを新しいバージョンに更新してから、「セットアップを再試行」を押してください。","s3167": "cloudflaredとして見つかったファイルは実行できませんでした。",- "s3168": "cloudflaredを再インストールしてから、「セットアップを再試行」を押してください。"+ "s3168": "cloudflaredを再インストールしてから、「セットアップを再試行」を押してください。",+ "s3169": "設定ファイル",+ "s3170": "設定ファイルを開く",+ "s3171": "ファイルに加えた変更は、次にモデルを起動するときに反映されます。",+ "s3172": "代わりにフォルダーからファイルを開くか、もう一度お試しください。",+ "s3173": "設定ファイルに誤りがあるため、修正するまでモデルは起動しません。",+ "s3174": "設定ファイルを開き、下に示した行を修正してから、もう一度モデルを読み込んでください。",+ "s3175": "設定ファイルは有効なJSONではありません。{0}行目付近を確認してください。2つの項目の間のカンマ不足、最後の項目の後ろの余分なカンマ、引用符の閉じ忘れがないか確認してください。",+ "s3176": "設定ファイルは有効なJSONではありません。2つの項目の間のカンマ不足、最後の項目の後ろの余分なカンマ、引用符の閉じ忘れがないか確認してください。",+ "s3177": "設定ファイルには、設定を中に含む1つのオブジェクト { … } が必要です。",+ "s3178": "「{0}」はStrataが読み取る設定ではないため、無視されます。「{1}」のことではありませんか?",+ "s3179": "「{0}」はStrataが読み取る設定ではないため、無視されます。",+ "s3180": "「args」は引用符で囲んだ文字列のリストにしてください(例: [\"--ple-io\", \"mmap\"])。数値も引用符で囲みます。",+ "s3181": "ネットワークアドレス、ポート、APIキーはStrataが自動で管理するため、「args」内の --host、--port、--api-key は無視されます。",+ "s3182": "「env」は、引用符で囲んだ文字列の値を持つ STRATA_ 名のオブジェクトにしてください。",+ "s3183": "「env」の項目 {0} は引用符で囲んだ文字列にしてください(例: \"1\")。",+ "s3184": "「sampling」は { \"temperature\": 0.7 } のようなオブジェクトにしてください。",+ "s3185": "「{0}」は true または false にしてください(現在の値: {1})。",+ "s3186": "「{0}」は {1} から {2} までの数値にしてください(現在の値: {3})。",+ "s3187": "「{0}」は {1} から {2} までの整数にしてください(現在の値: {3})。",+ "s3188": "「{0}」は次のいずれかにしてください: {1}(現在の値: {2})。",+ "s3189": "「{0}」は短い文字列、または短い名前のリストにしてください。",+ "s3190": "「layer_split」の分割点は 1 から 47 の間で増える順にしてください(例: \"16,32\")。または \"auto\" にします。",+ "s3191": "「gpu」はグラフィックスカードの番号(例: 0)、または [0, 1] のようなリストにしてください。",+ "s3192": "{0}行目: {1}",+ "s3193": "設定ファイルに誤りがあるため、モデルを起動しませんでした。",+ "s3194": "「上級設定」で設定ファイルを開き、「詳細」に表示された行を修正してから、もう一度モデルを読み込んでください。"}diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.jsonindex 5f3d74cb3..f35ff3529 100644--- a/apps/host/src/locales/ko.json+++ b/apps/host/src/locales/ko.json@@ -3161,5 +3161,31 @@"s3165": "이 컴퓨터의 Cloudflare 커넥터가 너무 오래되었습니다.","s3166": "cloudflared를 최신 버전으로 업데이트한 뒤 '설정 다시 시도'를 누르세요.","s3167": "cloudflared로 찾은 파일이 실행되지 않았습니다.",- "s3168": "cloudflared를 다시 설치한 뒤 '설정 다시 시도'를 누르세요."+ "s3168": "cloudflared를 다시 설치한 뒤 '설정 다시 시도'를 누르세요.",+ "s3169": "설정 파일",+ "s3170": "설정 파일 열기",+ "s3171": "파일에서 변경한 내용은 다음에 모델을 시작할 때 적용됩니다.",+ "s3172": "대신 해당 폴더에서 파일을 열거나 다시 시도하세요.",+ "s3173": "설정 파일에 오류가 있어, 수정하기 전에는 모델이 시작되지 않습니다.",+ "s3174": "설정 파일을 열어 아래에 표시된 줄을 수정한 뒤 모델을 다시 불러오세요.",+ "s3175": "설정 파일이 올바른 JSON이 아닙니다. {0}번째 줄 근처를 확인하세요. 두 항목 사이의 쉼표 누락, 마지막 항목 뒤의 쉼표, 빠진 따옴표가 없는지 보세요.",+ "s3176": "설정 파일이 올바른 JSON이 아닙니다. 두 항목 사이의 쉼표 누락, 마지막 항목 뒤의 쉼표, 빠진 따옴표가 없는지 확인하세요.",+ "s3177": "설정 파일에는 설정이 들어 있는 객체 하나, { … } 가 있어야 합니다.",+ "s3178": "'{0}'은(는) Strata가 읽는 설정이 아니어서 무시됩니다. '{1}'을(를) 말씀하신 건가요?",+ "s3179": "'{0}'은(는) Strata가 읽는 설정이 아니어서 무시됩니다.",+ "s3180": "'args'는 따옴표로 묶은 텍스트 항목의 목록이어야 합니다(예: [\"--ple-io\", \"mmap\"]). 숫자도 따옴표로 묶어야 합니다.",+ "s3181": "네트워크 주소, 포트, API 키는 Strata가 직접 관리하므로 'args'의 --host, --port, --api-key는 적용되지 않습니다.",+ "s3182": "'env'는 따옴표로 묶은 텍스트 값을 가진 STRATA_ 이름의 객체여야 합니다.",+ "s3183": "'env' 항목 {0}은(는) 따옴표로 묶은 텍스트여야 합니다(예: \"1\").",+ "s3184": "'sampling'은 { \"temperature\": 0.7 }와 같은 객체여야 합니다.",+ "s3185": "'{0}'은(는) true 또는 false여야 합니다. 현재 값: {1}.",+ "s3186": "'{0}'은(는) {1}에서 {2} 사이의 숫자여야 합니다. 현재 값: {3}.",+ "s3187": "'{0}'은(는) {1}에서 {2} 사이의 정수여야 합니다. 현재 값: {3}.",+ "s3188": "'{0}'은(는) 다음 중 하나여야 합니다: {1}. 현재 값: {2}.",+ "s3189": "'{0}'은(는) 짧은 텍스트이거나 짧은 이름의 목록이어야 합니다.",+ "s3190": "'layer_split'의 분할 지점은 1에서 47 사이에서 증가해야 합니다(예: \"16,32\"). 또는 \"auto\"로 두세요.",+ "s3191": "'gpu'는 0과 같은 그래픽 카드 번호이거나 [0, 1]과 같은 목록이어야 합니다.",+ "s3192": "{0}번째 줄: {1}",+ "s3193": "설정 파일에 오류가 있어 모델을 시작하지 않았습니다.",+ "s3194": "'전문가 설정'에서 설정 파일을 열고 '세부 정보'에 표시된 줄을 수정한 뒤 모델을 다시 불러오세요."}diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.jsonindex 29408073d..181656108 100644--- a/apps/host/src/locales/pt.json+++ b/apps/host/src/locales/pt.json@@ -3161,5 +3161,31 @@"s3165": "O conector da Cloudflare deste computador é muito antigo.","s3166": "Atualize o cloudflared para uma versão mais nova e depois toque em «Tentar configurar novamente».","s3167": "O arquivo encontrado como cloudflared não foi executado.",- "s3168": "Reinstale o cloudflared e depois toque em «Tentar configurar novamente»."+ "s3168": "Reinstale o cloudflared e depois toque em «Tentar configurar novamente».",+ "s3169": "Arquivo de configurações",+ "s3170": "Abrir arquivo de configurações",+ "s3171": "As alterações feitas no arquivo valem na próxima vez que o modelo iniciar.",+ "s3172": "Abra o arquivo pela pasta dele ou tente novamente.",+ "s3173": "Seu arquivo de configurações tem um erro, então o modelo não iniciará até que ele seja corrigido.",+ "s3174": "Abra o arquivo de configurações, corrija as linhas abaixo e carregue o modelo novamente.",+ "s3175": "O arquivo de configurações não é um JSON válido; veja perto da linha {0}. Verifique se falta uma vírgula entre duas entradas, se há vírgula depois da última ou se falta uma aspa.",+ "s3176": "O arquivo de configurações não é um JSON válido. Verifique se falta uma vírgula entre duas entradas, se há vírgula depois da última ou se falta uma aspa.",+ "s3177": "O arquivo de configurações deve conter um único objeto, { … }, com as configurações dentro.",+ "s3178": "«{0}» não é uma configuração que o Strata lê, por isso é ignorada. Você quis dizer «{1}»?",+ "s3179": "«{0}» não é uma configuração que o Strata lê, por isso é ignorada.",+ "s3180": "«args» deve ser uma lista de textos entre aspas, por exemplo [\"--ple-io\", \"mmap\"]. Números também levam aspas.",+ "s3181": "O Strata gerencia sozinho o endereço de rede, a porta e a chave de API, então --host, --port e --api-key em «args» não são respeitados.",+ "s3182": "«env» deve ser um objeto de nomes STRATA_ com valores de texto entre aspas.",+ "s3183": "A entrada «env» {0} deve ser texto entre aspas, por exemplo \"1\".",+ "s3184": "«sampling» deve ser um objeto como { \"temperature\": 0.7 }.",+ "s3185": "«{0}» deve ser true ou false, não {1}.",+ "s3186": "«{0}» deve ser um número de {1} a {2}, não {3}.",+ "s3187": "«{0}» deve ser um número inteiro de {1} a {2}, não {3}.",+ "s3188": "«{0}» deve ser um destes valores: {1}, não {2}.",+ "s3189": "«{0}» deve ser um texto curto ou uma lista de nomes curtos.",+ "s3190": "Os pontos de «layer_split» devem crescer de 1 a 47, por exemplo \"16,32\", ou ser \"auto\".",+ "s3191": "«gpu» deve ser o número de uma placa de vídeo, como 0, ou uma lista como [0, 1].",+ "s3192": "Linha {0}: {1}",+ "s3193": "Seu arquivo de configurações tem um erro, então o modelo não foi iniciado.",+ "s3194": "Abra o arquivo de configurações em «Configurações avançadas», corrija a linha mostrada em «Detalhes» e carregue o modelo novamente."}diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.jsonindex 6748a9ac6..6594fce0b 100644--- a/apps/host/src/locales/ru.json+++ b/apps/host/src/locales/ru.json@@ -3161,5 +3161,31 @@"s3165": "Коннектор Cloudflare на этом компьютере слишком старый.","s3166": "Обновите cloudflared до более новой версии, затем нажмите «Повторить настройку».","s3167": "Файл, найденный как cloudflared, не запустился.",- "s3168": "Переустановите cloudflared, затем нажмите «Повторить настройку»."+ "s3168": "Переустановите cloudflared, затем нажмите «Повторить настройку».",+ "s3169": "Файл настроек",+ "s3170": "Открыть файл настроек",+ "s3171": "Изменения в файле вступают в силу при следующем запуске модели.",+ "s3172": "Откройте файл из его папки или повторите попытку.",+ "s3173": "В файле настроек есть ошибка, поэтому модель не запустится, пока её не исправить.",+ "s3174": "Откройте файл настроек, исправьте указанные ниже строки и загрузите модель снова.",+ "s3175": "Файл настроек не является корректным JSON; посмотрите рядом со строкой {0}. Проверьте, нет ли пропущенной запятой между двумя записями, лишней запятой после последней записи или незакрытой кавычки.",+ "s3176": "Файл настроек не является корректным JSON. Проверьте, нет ли пропущенной запятой между двумя записями, лишней запятой после последней записи или незакрытой кавычки.",+ "s3177": "Файл настроек должен содержать один объект { … } с настройками внутри.",+ "s3178": "«{0}» не является настройкой, которую читает Strata, поэтому она игнорируется. Возможно, вы имели в виду «{1}»?",+ "s3179": "«{0}» не является настройкой, которую читает Strata, поэтому она игнорируется.",+ "s3180": "«args» должен быть списком текстовых записей в кавычках, например [\"--ple-io\", \"mmap\"]. Числа тоже нужно писать в кавычках.",+ "s3181": "Сетевой адрес, порт и ключ API Strata задаёт сама, поэтому --host, --port и --api-key в «args» не учитываются.",+ "s3182": "«env» должен быть объектом из имён STRATA_ с текстовыми значениями в кавычках.",+ "s3183": "Запись «env» {0} должна быть текстом в кавычках, например \"1\".",+ "s3184": "«sampling» должен быть объектом, например { \"temperature\": 0.7 }.",+ "s3185": "«{0}» должно быть true или false, а не {1}.",+ "s3186": "«{0}» должно быть числом от {1} до {2}, а не {3}.",+ "s3187": "«{0}» должно быть целым числом от {1} до {2}, а не {3}.",+ "s3188": "«{0}» должно быть одним из значений: {1}, а не {2}.",+ "s3189": "«{0}» должно быть коротким текстом или списком коротких имён.",+ "s3190": "Точки «layer_split» должны возрастать от 1 до 47, например \"16,32\", или быть \"auto\".",+ "s3191": "«gpu» должно быть номером видеокарты, например 0, или списком, например [0, 1].",+ "s3192": "Строка {0}: {1}",+ "s3193": "В файле настроек есть ошибка, поэтому модель не была запущена.",+ "s3194": "Откройте файл настроек в разделе «Экспертные настройки», исправьте строку, указанную в «Подробностях», и загрузите модель снова."}diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.jsonindex 84f971ac9..0ce81de6c 100644--- a/apps/host/src/locales/zh.json+++ b/apps/host/src/locales/zh.json@@ -3161,5 +3161,31 @@"s3165": "这台电脑上的 Cloudflare 连接器版本太旧。","s3166": "请将 cloudflared 更新到较新版本,然后点击“重试设置”。","s3167": "找到的 cloudflared 文件无法运行。",- "s3168": "请重新安装 cloudflared,然后点击“重试设置”。"+ "s3168": "请重新安装 cloudflared,然后点击“重试设置”。",+ "s3169": "设置文件",+ "s3170": "打开设置文件",+ "s3171": "你在文件中所做的更改将在下次启动模型时生效。",+ "s3172": "请改从其所在文件夹打开该文件,或重试。",+ "s3173": "你的设置文件有错误,修复之前模型不会启动。",+ "s3174": "请打开设置文件,修复下面列出的行,然后重新加载模型。",+ "s3175": "设置文件不是有效的 JSON,请检查第 {0} 行附近。看看两项之间是否缺少逗号、最后一项后是否多了逗号,或是否缺少引号。",+ "s3176": "设置文件不是有效的 JSON。请检查两项之间是否缺少逗号、最后一项后是否多了逗号,或是否缺少引号。",+ "s3177": "设置文件必须包含一个对象 { … },设置写在其中。",+ "s3178": "“{0}”不是 Strata 会读取的设置,因此会被忽略。你是不是想写“{1}”?",+ "s3179": "“{0}”不是 Strata 会读取的设置,因此会被忽略。",+ "s3180": "“args”必须是带引号的文本项列表,例如 [\"--ple-io\", \"mmap\"]。数字也需要加引号。",+ "s3181": "网络地址、端口和 API 密钥由 Strata 自行管理,因此“args”中的 --host、--port 和 --api-key 不会生效。",+ "s3182": "“env”必须是由 STRATA_ 名称和带引号的文本值组成的对象。",+ "s3183": "“env”条目 {0} 必须是带引号的文本,例如 \"1\"。",+ "s3184": "“sampling”必须是类似 { \"temperature\": 0.7 } 的对象。",+ "s3185": "“{0}”必须是 true 或 false,而不是 {1}。",+ "s3186": "“{0}”必须是 {1} 到 {2} 之间的数字,而不是 {3}。",+ "s3187": "“{0}”必须是 {1} 到 {2} 之间的整数,而不是 {3}。",+ "s3188": "“{0}”必须是以下之一:{1},而不是 {2}。",+ "s3189": "“{0}”必须是简短文本,或简短名称的列表。",+ "s3190": "“layer_split”的分割点必须在 1 到 47 之间递增,例如 \"16,32\",或设为 \"auto\"。",+ "s3191": "“gpu”必须是显卡编号(如 0),或类似 [0, 1] 的列表。",+ "s3192": "第 {0} 行:{1}",+ "s3193": "你的设置文件有错误,因此没有启动模型。",+ "s3194": "在“专家设置”中打开设置文件,修复“详情”中显示的那一行,然后重新加载模型。"}diff --git a/apps/host/tests/native-settings-file.test.mjs b/apps/host/tests/native-settings-file.test.mjsnew file mode 100644index 000000000..055110b22--- /dev/null+++ b/apps/host/tests/native-settings-file.test.mjs@@ -0,0 +1,56 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { nativeFixture, finishJob } from './helpers/native-fixture.mjs';++const configOf = f => join(f.repo, 'strata-iq2_xs.json');++test('the settings file is found, checked, and opened in the text editor', async () => {+ const f = nativeFixture();+ try {+ await f.control.refresh();+ const info = f.control.settingsFile('iq2_xs');+ assert.equal(info.path, configOf(f));+ assert.equal(info.name, 'strata-iq2_xs.json');+ assert.equal(info.ok, true);+ assert.match(info.note, /apply the next time the model starts/);+ assert.ok(info.issues.every(i => i.level === 'warning'), 'the fixture’s own extra key is a warning at most');+ const seen = [];+ const opened = await f.control.openSettingsFile('iq2_xs', { recorder: seen, platform: 'win32' });+ assert.deepEqual(seen, [['notepad.exe', info.path]]);+ assert.equal(opened.name, 'strata-iq2_xs.json');+ assert.throws(() => f.control.settingsFile('../etc/passwd'), /installed model/);+ } finally { await f.cleanup(); }+});++test('a mistake in the file holds the start back with its line; a typo’d key only warns', async () => {+ const f = nativeFixture();+ try {+ await f.control.refresh(true);+ const path = configOf(f), good = readFileSync(path, 'utf8');+ // 1. a syntax slip (missing comma): not valid JSON, said with the line, and nothing is started+ writeFileSync(path, JSON.stringify(JSON.parse(good), null, 2).replace('"gpu": 0,', '"gpu": 0\n "x": 1,'));+ assert.equal(f.control.settingsFile('iq2_xs').ok, false);+ let done = await finishJob(f.control, f.control.operation('load', { model: 'iq2_xs' }).id);+ assert.equal(done.state, 'error');+ assert.match(done.error, /^The settings file for this model has a mistake, so the model was not started\. Line \d+: The settings file is not valid JSON/);+ assert.equal(f.control.state().instances.length, 0, 'no engine was started');+ assert.equal(f.calls.filter(c => /strata\.py|serve/.test(JSON.stringify(c.args))).length, 0);+ // 2. a bad value+ const config = JSON.parse(good); config.parallel = 99; config.lazy_load = 'yes';+ writeFileSync(path, JSON.stringify(config, null, 2));+ done = await finishJob(f.control, f.control.operation('load', { model: 'iq2_xs' }).id);+ assert.equal(done.state, 'error');+ assert.match(done.error, /"parallel" must be a whole number from 1 to 8, not 99/);+ assert.match(done.error, /"lazy_load" must be true or false, not "yes"/);+ // 3. an unknown key only warns and the model loads+ const typo = JSON.parse(good); typo.paralel = 2;+ writeFileSync(path, JSON.stringify(typo, null, 2));+ const info = f.control.settingsFile('iq2_xs');+ assert.equal(info.ok, true);+ assert.ok(info.issues.some(i => i.code === 'unknown-key-near' && i.params.near === 'parallel'));+ done = await finishJob(f.control, f.control.operation('load', { model: 'iq2_xs' }).id);+ assert.equal(done.state, 'done', done.error);+ } finally { await f.cleanup(); }+});diff --git a/apps/host/tests/plain-errors.test.mjs b/apps/host/tests/plain-errors.test.mjsindex b09cf8c33..e8f654d45 100644--- a/apps/host/tests/plain-errors.test.mjs+++ b/apps/host/tests/plain-errors.test.mjs@@ -9,6 +9,7 @@ const built = await build({ stdin: { contents: "export * from './src/lib/plain-econst { plainFailure, plainFailureText, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`);const cases = [+ ['The settings file for this model has a mistake, so the model was not started. Line 4: The settings file is not valid JSON; look near line 4.', 'settings-file', /settings file has a mistake/],['The Cloudflare connector (cloudflared) is not installed here, and the app never downloads it while it runs. Install it from the optional connector component.', 'connector-missing', /could not find Cloudflare’s connector/],['The cloudflared at /usr/bin/cloudflared is version 2021.3.0, which is too old. Strata needs 2022.1.0 or newer. Update cloudflared, then retry.', 'connector-old', /connector on this computer is too old/],['The file at /x/cloudflared did not run as cloudflared. Reinstall cloudflared, then retry.', 'connector-broken', /did not run/],diff --git a/apps/host/tests/run-config-check.test.mjs b/apps/host/tests/run-config-check.test.mjsnew file mode 100644index 000000000..fe2a8e9ce--- /dev/null+++ b/apps/host/tests/run-config-check.test.mjs@@ -0,0 +1,120 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import { build } from 'esbuild';+import { KNOWN_KEYS, checkRunConfig, describeIssues, nearestKey } from '../server/run-config-check.mjs';+import { NATIVE_FIELDS } from '../server/native-settings.mjs';+import { openTextFile, textEditorCommand } from '../server/open-text-file.mjs';++const good = `{+ "exe": "/opt/strata/strata",+ "args": ["--native", "/m/a.gguf", "--max-context", "65536"],+ "env": {"STRATA_PCIE_FRAC_DEFAULT": "old"},+ "sampling": {"temperature": 0.7, "repeat_penalty": 1.1},+ "parallel": 2,+ "aliases": "chat, coding",+ "gpu": [0, 1],+ "layer_split": "16,32",+ "port": 8080+}`;++test('a normal run config has no issues', () => {+ assert.deepEqual(checkRunConfig(good), { ok: true, issues: [] });+ assert.deepEqual(checkRunConfig('\uFEFF{}'), { ok: true, issues: [] }, 'Notepad’s byte-order mark is fine');+});++test('every key the app edits is a known key', () => {+ for (const field of NATIVE_FIELDS) assert.ok(KNOWN_KEYS.has(field.id), field.id);+});++test('broken JSON is reported with its line, in plain words', () => {+ const text = '{\n "args": ["--ple-io" "mmap"],\n "port": 8080\n}';+ const result = checkRunConfig(text);+ assert.equal(result.ok, false);+ assert.equal(result.issues[0].code, 'json');+ assert.equal(result.issues[0].level, 'error');+ assert.equal(result.issues[0].line, 2);+ assert.match(describeIssues(result.issues)[0], /^Line 2: The settings file is not valid JSON; look near line 2\. Check for a missing comma/);+ assert.equal(checkRunConfig('[1,2]').issues[0].code, 'not-object');+ assert.equal(checkRunConfig('').ok, false);+});++test('an unknown key is a warning with the nearest real name, and does not hold the start back', () => {+ const result = checkRunConfig('{\n "paralel": 2,\n "idle_unload_secs": 5,\n "totally_made_up_thing": 1\n}');+ assert.equal(result.ok, true);+ assert.deepEqual(result.issues.map(i => [i.level, i.code, i.key, i.params.near, i.line]), [+ ['warning', 'unknown-key-near', 'paralel', 'parallel', 2],+ ['warning', 'unknown-key-near', 'idle_unload_secs', 'idle_unload_s', 3],+ ['warning', 'unknown-key', 'totally_made_up_thing', '', 4]]);+ assert.match(result.issues[0].message, /"paralel" is not a setting Strata reads, so it is ignored\. Did you mean "parallel"\?/);+ assert.equal(nearestKey('Lazy-Load'), 'lazy_load');+ assert.equal(nearestKey('zzzzzzzz'), null);+});++test('a bad value is an error that names the key, the line, what is allowed and what was found', () => {+ const text = '{\n "parallel": 12,\n "lazy_load": "yes",\n "anthropic_thinking": "sometimes",\n "idle_unload_s": 1.5,\n "port": 70000,\n "args": ["--ple-io", 4],\n "env": {"PATH": "/x", "STRATA_Y": 2},\n "sampling": {"temperature": -1, "top_k": 0.5, "banana": 3},\n "gpu": "first",\n "layer_split": "32,16",\n "reasoning_effort": "max"\n}';+ const result = checkRunConfig(text);+ assert.equal(result.ok, false);+ const by = key => result.issues.filter(i => i.key === key);+ assert.deepEqual(by('parallel').map(i => [i.code, i.line, i.params.min, i.params.max, i.params.value]), [['whole-range', 2, 1, 8, '12']]);+ assert.equal(by('lazy_load')[0].code, 'bool');+ assert.deepEqual([by('anthropic_thinking')[0].code, by('anthropic_thinking')[0].params.choices], ['choice', 'model, on_request']);+ assert.equal(by('idle_unload_s')[0].code, 'whole-range');+ assert.equal(by('port')[0].code, 'number-range');+ assert.equal(by('args')[0].code, 'args-type');+ assert.deepEqual(by('env').map(i => i.code), ['env-value'], 'names other than STRATA_ (PATH) are kept, only a non-text value is wrong');+ assert.deepEqual(by('sampling').map(i => [i.code, i.params.key]), [['number-range', 'sampling.temperature'], ['whole-range', 'sampling.top_k'], ['unknown-key', 'sampling.banana']]);+ assert.equal(by('gpu')[0].code, 'gpu');+ assert.equal(by('layer_split')[0].code, 'layer-split');+ assert.equal(by('reasoning_effort')[0].code, 'choice');+ assert.ok(result.issues.filter(i => i.level === 'error').every(i => i.message.length > 20));+});++test('null and empty values mean "use the default" and are never an error', () => {+ assert.deepEqual(checkRunConfig('{"parallel": null, "lazy_load": null, "reasoning_budget_tokens": ""}'), { ok: true, issues: [] });+});++test('--host, --port and --api-key in args are a warning, not a refusal', () => {+ const r = checkRunConfig('{"args": ["--port", "9"]}');+ assert.equal(r.ok, true);+ assert.equal(r.issues[0].code, 'args-managed');+});++test('the text editor: Notepad on Windows, text mode on a Mac, the system text-file program on Linux', async () => {+ assert.deepEqual(await textEditorCommand('C:\\s\\strata-q.json', { platform: 'win32' }), ['notepad.exe', ['C:\\s\\strata-q.json']]);+ assert.deepEqual(await textEditorCommand('/s/strata-q.json', { platform: 'darwin' }), ['open', ['-t', '/s/strata-q.json']]);+ const ask = async (command, args) => command === 'xdg-mime' ? 'org.gnome.gedit.desktop\n' : args[1] === 'command -v gtk-launch' ? '/usr/bin/gtk-launch\n' : '';+ assert.deepEqual(await textEditorCommand('/s/strata-q.json', { platform: 'linux', ask }), ['/usr/bin/gtk-launch', ['org.gnome.gedit.desktop', '/s/strata-q.json']]);+ const noEditor = async () => '';+ const seen = [];+ await openTextFile('/s/strata-q.json', { platform: 'linux', ask: noEditor, recorder: seen });+ assert.deepEqual(seen, [['xdg-open', '/s/strata-q.json']], 'with no text editor known the file’s own program opens it');+});++test('every issue sentence exists in all eight languages and keeps its slots', async () => {+ const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];+ const compiled = await build({ stdin: { contents: "export * from './src/lib/run-config-issues'; export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, platform: 'node', format: 'esm' });+ const { issueText, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`);+ const samples = [+ { code: 'json', line: 3, params: { line: 3 } }, { code: 'json', line: null, params: { line: 0 } }, { code: 'not-object', params: {} },+ { code: 'unknown-key-near', params: { key: 'paralel', near: 'parallel' } }, { code: 'unknown-key', params: { key: 'zzz' } },+ { code: 'args-type', params: {} }, { code: 'args-managed', params: {} }, { code: 'env-type', params: {} },+ { code: 'env-value', params: { name: 'STRATA_X' } }, { code: 'sampling-type', params: {} }, { code: 'bool', params: { key: 'lazy_load', value: '"yes"' } },+ { code: 'number-range', params: { key: 'port', min: 1, max: 65535, value: '0' } }, { code: 'whole-range', params: { key: 'parallel', min: 1, max: 8, value: '12' } },+ { code: 'choice', params: { key: 'gpu_order', choices: 'auto, as_given', value: '"x"' } }, { code: 'text', params: { key: 'aliases' } },+ { code: 'layer-split', params: {} }, { code: 'gpu', params: {} },+ ].map(s => ({ level: 'error', key: 'k', message: 'ENGLISH FALLBACK', line: s.line === undefined ? 5 : s.line, ...s }));+ const english = {};+ setTranslationLanguage('en');+ for (const s of samples) english[`${s.code}:${s.line}`] = issueText(s);+ for (const s of samples) assert.notEqual(english[`${s.code}:${s.line}`], 'ENGLISH FALLBACK', s.code);+ for (const language of languages.filter(l => l !== 'en')) {+ setTranslationLanguage(language);+ for (const s of samples) {+ const text = issueText(s);+ assert.notEqual(text, english[`${s.code}:${s.line}`], `${language}:${s.code} is not translated`);+ assert.ok(!/\{\d+\}/.test(text), `${language}:${s.code} left a slot`);+ }+ }+ setTranslationLanguage('en');+});