From 4b49729a1ef259ae6ace7816b86503fc24fe9fb6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:32:09 +0200 Subject: [PATCH 01/16] monitor: read Windows disk counters from one long-lived PowerShell instead of a cold one every 3 s (#3939) --- apps/host/server/system-telemetry.mjs | 64 +++++++++++++++++--- apps/host/tests/windows-disk-reader.test.mjs | 43 +++++++++++++ 2 files changed, 100 insertions(+), 7 deletions(-) create mode 100644 apps/host/tests/windows-disk-reader.test.mjs diff --git a/apps/host/server/system-telemetry.mjs b/apps/host/server/system-telemetry.mjs index 4d7c9c6d..768a83ff 100644 --- a/apps/host/server/system-telemetry.mjs +++ b/apps/host/server/system-telemetry.mjs @@ -1,5 +1,6 @@ /** Host counters. CPU sockets are measured only when their logical CPU IDs are known. */ import os from 'node:os'; +import { spawn } from 'node:child_process'; import { readFile, readdir } from 'node:fs/promises'; import { availableMemoryGb } from './hardware.mjs'; import { probe } from './util.mjs'; @@ -18,7 +19,7 @@ export function cpuUtilization(previous, current, ids) { } export function diskRate(previous, current, time) { - const elapsed=previous?(time-previous.time)/1000:0; + const elapsed=previous?((current?.at??time)-(previous.counters?.at??previous.time))/1000:0; if(elapsed<=0||!current||!previous?.counters)return {readMbs:null,writeMbs:null}; const read=current.read-previous.counters.read,write=current.write-previous.counters.write; return {readMbs:read>=0?read/1024**2/elapsed:null,writeMbs:write>=0?write/1024**2/elapsed:null}; @@ -41,6 +42,53 @@ export function parseMacDiskCounters(raw) { return reads.length&&writes.length?{read:reads.reduce((n,m)=>n+Number(m[1]),0),write:writes.reduce((n,m)=>n+Number(m[1]),0)}:null; } +export function parseWindowsDiskLine(line) { + const m=/^\s*(\d+)\s+(\d+)\s*$/.exec(String(line)); + return m?{read:Number(m[1]),write:Number(m[2])}:null; +} + +/** + * One long-lived PowerShell reads the disk counters in a loop. A new PowerShell per sample + * paid the cold WMI start every time, missed its timeout and burned WmiPrvSE (#3939). + * Gives up after repeated early exits, so a broken counter stays quiet. + */ +export function createWindowsDiskReader({ spawnFn=spawn, intervalSec=4, maxStarts=3, now=Date.now }={}) { + let child=null,latest=null,starts=0,buffer=''; + const script=`while($true){$d=Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk -Filter "Name='_Total'";if($d){[Console]::Out.WriteLine(([string]$d.DiskReadBytesPersec)+' '+([string]$d.DiskWriteBytesPersec));[Console]::Out.Flush()};Start-Sleep -Seconds ${intervalSec}}`; + function start() { + if(child||starts>=maxStarts)return; + starts++; + let proc; + try { proc=spawnFn('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{windowsHide:true,stdio:['ignore','pipe','ignore']}); } + catch { return; } + child=proc; + proc.on?.('error',()=>{ if(child===proc)child=null; }); + proc.on?.('exit',()=>{ if(child===proc){child=null;latest=null;} }); + proc.stdout?.on('data',chunk=>{ + buffer+=chunk; + let i; + while((i=buffer.indexOf('\n'))>=0){ + const parsed=parseWindowsDiskLine(buffer.slice(0,i)); + buffer=buffer.slice(i+1); + if(parsed){latest={...parsed,at:now()};starts=0;} + } + }); + proc.unref?.(); + proc.stdout?.unref?.(); + } + return { + read() { start(); return latest; }, + stop() { try{child?.kill();}catch{} child=null; }, + get starts() { return starts; }, + }; +} + +let windowsReader=null; +function windowsDisks() { + if(!windowsReader){windowsReader=createWindowsDiskReader();process.once('exit',()=>windowsReader.stop());} + return windowsReader.read(); +} + async function disks() { try { if(process.platform==='linux') { @@ -49,24 +97,26 @@ async function disks() { } if(process.platform==='darwin')return parseMacDiskCounters(await probe('ioreg',['-r','-c','IOBlockStorageDriver','-l'],1500)); if(process.platform==='win32') { - const raw=await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',"Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk -Filter \"Name='_Total'\" | Select-Object DiskReadBytesPersec,DiskWriteBytesPersec | ConvertTo-Json -Compress"],2000); - const value=JSON.parse(raw); - if(value.DiskReadBytesPersec!=null&&value.DiskWriteBytesPersec!=null)return {read:Number(value.DiskReadBytesPersec),write:Number(value.DiskWriteBytesPersec)}; + return windowsDisks(); } } catch { /* An unsupported counter stays unavailable. */ } return null; } export function createSystemSampler() { - let previousCpu=null,previousDisk=null; + let previousCpu=null,previousDisk=null,lastRate={readMbs:null,writeMbs:null}; return async processors => { const current=os.cpus(),time=Date.now(); const cpuLoad=cpuUtilization(previousCpu,current,current.map((_,i)=>i)); const cpus=processors.map(p=>({id:p.id,utilizationPct:cpuUtilization(previousCpu,current,p.logicalIds??(processors.length===1?current.map((_,i)=>i):[]))})); previousCpu=current; const [available,counters]=await Promise.all([availableMemoryGb(process.platform),disks()]); - const rate=diskRate(previousDisk,counters,time); - previousDisk={time,counters}; + let rate=lastRate; + if(!(counters&&counters.at!==undefined&&previousDisk?.counters?.at===counters.at)) { + rate=diskRate(previousDisk,counters,time); + previousDisk={time,counters}; + lastRate=rate; + } const total=os.totalmem()/1024**3,free=available??os.freemem()/1024**3; return {cpuLoad,cpus,ramUsedGb:Math.max(0,Math.min(total,total-free)),ramTotalGb:total,diskReadGbs:rate.readMbs===null?null:rate.readMbs/1024,diskWriteMbs:rate.writeMbs}; }; diff --git a/apps/host/tests/windows-disk-reader.test.mjs b/apps/host/tests/windows-disk-reader.test.mjs new file mode 100644 index 00000000..d8960b6f --- /dev/null +++ b/apps/host/tests/windows-disk-reader.test.mjs @@ -0,0 +1,43 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { parseWindowsDiskLine, createWindowsDiskReader, diskRate } from '../server/system-telemetry.mjs'; + +function fakeSpawn(log) { + return (cmd, args) => { + const proc = new EventEmitter(); + proc.stdout = new EventEmitter(); + proc.stdout.unref = () => {}; + proc.unref = () => {}; + proc.kill = () => { proc.killed = true; }; + log.push({ cmd, args, proc }); + return proc; + }; +} + +test('one PowerShell is started and reused for every sample (#3939)', () => { + const log = []; + const reader = createWindowsDiskReader({ spawnFn: fakeSpawn(log), now: () => 1000 }); + assert.equal(reader.read(), null, 'nothing before the first line'); + reader.read(); reader.read(); + assert.equal(log.length, 1); + log[0].proc.stdout.emit('data', '1000 2'); + log[0].proc.stdout.emit('data', '000\n'); + assert.deepEqual(reader.read(), { read: 1000, write: 2000, at: 1000 }); + assert.equal(log.length, 1); +}); + +test('after repeated early exits it stops starting processes', () => { + const log = []; + const reader = createWindowsDiskReader({ spawnFn: fakeSpawn(log), maxStarts: 3 }); + for (let i = 0; i < 6; i++) { reader.read(); log.at(-1).proc.emit('exit'); } + assert.equal(log.length, 3); + assert.equal(reader.read(), null); +}); + +test('garbage lines are ignored and a repeated reading gives no new rate', () => { + assert.equal(parseWindowsDiskLine('Name : x'), null); + assert.deepEqual(parseWindowsDiskLine('12 34\r'), { read: 12, write: 34 }); + const prev = { time: 0, counters: { read: 0, write: 0, at: 1000 } }; + assert.deepEqual(diskRate(prev, { read: 1048576, write: 0, at: 2000 }, 5000), { readMbs: 1, writeMbs: 0 }); +}); From 97c31168aabf4c12f8b86bbc1cdcf3723909917f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:33:56 +0200 Subject: [PATCH 02/16] chat model picker lists downloaded optimized models that are not loaded yet (#3814) --- apps/host/src/components/ChatModelPicker.tsx | 6 ++++-- apps/host/src/lib/model-picker.ts | 6 ++++++ apps/host/tests/model-picker.test.mjs | 9 ++++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/host/src/components/ChatModelPicker.tsx b/apps/host/src/components/ChatModelPicker.tsx index 7389b90c..5c267b2f 100644 --- a/apps/host/src/components/ChatModelPicker.tsx +++ b/apps/host/src/components/ChatModelPicker.tsx @@ -4,7 +4,7 @@ import { useId, useRef, useState } from 'react'; import { FloatingMenu } from './FloatingMenu'; import { Bar, Btn, Dialog, ErrorNotice, Icon } from './ui'; import { go, useLifecycle, loadVariant, selectRemoteModel, setSettingsSection, useStore } from '../lib/store'; -import { pickerGroups, pickerVersionState } from '../lib/model-picker'; +import { pickerGroups, pickerNativeModels, pickerVersionState } from '../lib/model-picker'; import { versionFit } from '../lib/model-versions'; import type { ModelVariant } from '../lib/types'; import { sizeGb } from '../lib/format'; @@ -37,6 +37,7 @@ function LegacyChatModelPicker() { const running = library?.variants.find(v => v.id === library.loaded); const version = library?.variants.find(v => v.id === selected); const groups = library ? pickerGroups(library) : []; + const installedNative = pickerNativeModels(native?.installed?.models, native?.instances); const status = version ? pickerVersionState(version, library?.loaded ?? null) : null; const tooBig = !!version && library?.mode === 'real' && versionFit(version, hardware, contextTokens(engine?.beginner.contextLength ?? '32K')).zone === 'too-big'; async function apply() { @@ -78,7 +79,8 @@ function LegacyChatModelPicker() { {tr(open ? setOpen(false)}> {tr(native?.instances.filter(i => i.status !== 'error').map(i => ))}

{tr("Local models")}

- {tr(!groups.length ?

{tr("No local models downloaded yet.")}

: null)} + {tr(installedNative.map(m => ))} + {tr(!groups.length && !installedNative.length ?

{tr("No local models downloaded yet.")}

: null)} {tr(groups.map(({ family, versions }, index) => { const main = versions[0], state = pickerVersionState(main, library!.loaded); const others = versions.slice(1), isExpanded = expanded.includes(family), id = `${groupsId}-${index}`; diff --git a/apps/host/src/lib/model-picker.ts b/apps/host/src/lib/model-picker.ts index a97a818c..ff3aae38 100644 --- a/apps/host/src/lib/model-picker.ts +++ b/apps/host/src/lib/model-picker.ts @@ -22,3 +22,9 @@ export function pickerGroups(library: ModelLibrary) { } return Array.from(groups, ([family, versions]) => ({ family, versions })); } + +/** Optimized models that are on this PC but not loaded yet: the chat picker must list them, or it says "none downloaded" while Storage shows them (#3814). */ +export function pickerNativeModels(installed: M[] | undefined | null, instances: { label: string }[] | undefined | null): M[] { + const loaded = new Set((instances ?? []).map(i => i.label)); + return (installed ?? []).filter(m => m.ready !== false && !loaded.has(m.model_name ?? m.model)); +} diff --git a/apps/host/tests/model-picker.test.mjs b/apps/host/tests/model-picker.test.mjs index 15779e35..934c4882 100644 --- a/apps/host/tests/model-picker.test.mjs +++ b/apps/host/tests/model-picker.test.mjs @@ -4,7 +4,7 @@ import { readFile } from 'node:fs/promises'; import { transform } from 'esbuild'; const { code } = await transform(await readFile(new URL('../src/lib/model-picker.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); -const { pickerGroups } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +const { pickerGroups, pickerNativeModels } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); const version = (id, family, state, diskGb, extra = {}) => ({ id, family, state, diskGb, ...extra }); test('chat picker groups every downloaded family and puts its running version first', () => { @@ -35,3 +35,10 @@ test('downloaded files stay visible during load transitions and recoverable fail assert.deepEqual(pickerGroups(library)[0].versions.map(v => v.id), ['loading', 'unloading', 'failed-load']); assert.deepEqual(pickerGroups({ loaded: null, variants: [library.variants[0]] }), []); }); + +test('downloaded optimized models that are not loaded still appear in the chat picker (#3814)', () => { + const installed = [{ model: 'swift', model_name: 'Swift IQ3_XXS', ready: true }, { model: 'half', model_name: 'Half', ready: false }, { model: 'run', model_name: 'Running one', ready: true }]; + const out = pickerNativeModels(installed, [{ label: 'Running one' }]); + assert.deepEqual(out.map(m => m.model), ['swift']); + assert.deepEqual(pickerNativeModels(undefined, null), []); +}); From c22e5e76335d2117b499f1535421acf40947b1a8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:34:11 +0200 Subject: [PATCH 03/16] missing files: name the engine program in words once, not as component:strata-engine (#3900) --- apps/host/server/missing-files.mjs | 6 +++--- apps/host/tests/plain-errors.test.mjs | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/apps/host/server/missing-files.mjs b/apps/host/server/missing-files.mjs index f575571a..25133a7e 100644 --- a/apps/host/server/missing-files.mjs +++ b/apps/host/server/missing-files.mjs @@ -5,15 +5,15 @@ */ import { basename } from 'node:path'; -const PART_WORDS = { engine: 'the engine program', 'tokenizer/vocab.json': 'the tokenizer', 'tokenizer/merges.txt': 'the tokenizer', 'tokenizer/token_type.json': 'the tokenizer' }; +const PART_WORDS = { engine: 'the engine program', 'component:strata-engine': 'the engine program', 'tokenizer/vocab.json': 'the tokenizer', 'tokenizer/merges.txt': 'the tokenizer', 'tokenizer/token_type.json': 'the tokenizer' }; /** Short readable names, no duplicates, most useful first. */ export function missingNames(controlParts, installerFiles) { const names = []; const add = text => { const t = String(text ?? '').trim(); if (t && !names.includes(t)) names.push(t); }; - for (const file of Array.isArray(installerFiles) ? installerFiles : []) add(basename(String(file).split(String.fromCharCode(92)).join('/'))); + for (const file of Array.isArray(installerFiles) ? installerFiles : []) { const name = basename(String(file).split(String.fromCharCode(92)).join('/')); add(PART_WORDS[name] ?? name); } for (const item of Array.isArray(controlParts) ? controlParts : []) { - add(PART_WORDS[item?.part] ?? item?.file ?? item?.part); + add(PART_WORDS[item?.part] ?? PART_WORDS[item?.file] ?? item?.file ?? item?.part); } return names; } diff --git a/apps/host/tests/plain-errors.test.mjs b/apps/host/tests/plain-errors.test.mjs index a5492e41..bb27d0e8 100644 --- a/apps/host/tests/plain-errors.test.mjs +++ b/apps/host/tests/plain-errors.test.mjs @@ -102,3 +102,8 @@ test('missing model files are named, in every language, with a next step (#3478) setTranslationLanguage('en'); assert.equal(plainFailure(missingFilesError('m', []).message).kind, 'plain', 'with no names the old sentence is left as it was'); }); + +test('the engine component is named in words, once (#3900)', async () => { + const { missingNames } = await import('../server/missing-files.mjs'); + assert.deepEqual(missingNames([{ part: 'engine', file: 'component:strata-engine' }], ['component:strata-engine']), ['the engine program']); +}); From 47ccec7c6ab096b923d62a2ba1881874db71d5bb Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:35:04 +0200 Subject: [PATCH 04/16] Delete a model: files Strata downloaded and packs it made go with it even in another models folder; the person's own files stay (#3716) --- tests/desktop/test_control_install.py | 17 +++++++++++++++++ tools/strata_mcp.py | 13 ++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/tests/desktop/test_control_install.py b/tests/desktop/test_control_install.py index 765f3f84..a886cd32 100644 --- a/tests/desktop/test_control_install.py +++ b/tests/desktop/test_control_install.py @@ -451,6 +451,23 @@ class DeleteModelTests(unittest.TestCase): described = self.s.describe_config(self.root / "strata-iq3_s.json") self.assertGreater(described["disk_bytes"], 10000) + def test_files_strata_downloaded_into_another_models_folder_are_deleted_too(self): + # The app installs into its own Models folder while settings.json names another data folder (#3716). + other = Path(self.tmp.name) / "Documents" / "Strata" + shard = self.make(other / "Models" / "IQ3" / "m-00001.gguf", 5000) + self.make(shard.with_name(shard.name + ".done"), 1) + pack = other / "packs" / "iq3" + self.make(pack / "dense.bin", 300) + self.make(pack / "conversions.json", 2) + mine = self.make(Path(self.tmp.name) / "mine" / "own.gguf", 99) + (self.root / "strata-iq3x.json").write_text(json.dumps({"exe": "component:strata-engine", "args": [ + "--pack", str(pack), "--native", str(shard), "--ple-gguf", str(mine)]}), encoding="utf-8") + result = self.tools.strata_remove(model="iq3x", confirm=True) + self.assertEqual(result["failed"], []) + self.assertFalse(shard.exists()) + self.assertFalse(pack.exists()) + self.assertTrue(mine.is_file(), "a file the person brought stays") + class LocalGgufInstallTests(unittest.TestCase): def test_a_plan_from_a_local_folder_adopts_the_files_and_needs_no_download_space(self): diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index cc284ae1..33d26d97 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -766,6 +766,17 @@ class Strata: return {"models": models, "shared_bytes": shared_bytes, "shared_gb": round(shared_bytes / 1e9, 2), "total_bytes": total, "total_gb": round(total / 1e9, 2)} + @staticmethod + def made_by_strata(p: Path, is_dir: bool) -> bool: + """A download or pack Strata wrote itself, even in a models folder the person picked or the app chose: a finished GGUF has its + .done mark beside it, a prepared pack has its conversion record. The person's own GGUF files have neither (#3716).""" + try: + if is_dir: + return any((p / n).is_file() for n in ("conversions.json", "experts.bin.src.json")) + return p.with_name(p.name + ".done").is_file() + except OSError: + return False + def removal_plan(self, config: Path) -> dict: """What deleting this model removes and what it keeps. A file or folder another installed model's config still names (the shared MTP draft, a shared PLE shard) is kept; so is anything outside Strata's own folders.""" @@ -789,7 +800,7 @@ class Strata: for p, is_dir in [(x, False) for x in files] + [(x, True) for x in dirs]: if not p.exists(): continue - if not self.allowed(p): + if not self.allowed(p) and not self.made_by_strata(p, is_dir): keep.append({"path": str(p), "reason": "outside Strata's folders"}) elif shared(p, is_dir): keep.append({"path": str(p), "reason": "another installed model still uses it"}) From ea897551ee07d4d739227b147e79eecdbc506aca Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:35:54 +0200 Subject: [PATCH 05/16] folder picker: a PowerShell that ends before its window opens (security software) falls back to typing the path (#3831) --- apps/host/server/folder-dialog.mjs | 5 ++++- apps/host/tests/folder-dialog.test.mjs | 6 +++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/host/server/folder-dialog.mjs b/apps/host/server/folder-dialog.mjs index 1785d86b..ef90a663 100644 --- a/apps/host/server/folder-dialog.mjs +++ b/apps/host/server/folder-dialog.mjs @@ -62,7 +62,10 @@ export function watchedWindowsDialog(shell, args, { readyMs = 30_000, openMs = 2 const later = () => { clearTimeout(timer); ready = true; setTimeout(() => end(resolve, { stdout: '' }), openMs).unref?.(); }; child.stdout?.on('data', chunk => { stdout += chunk; if (!ready && /^READY\s*$/m.test(stdout)) { clearTimeout(timer); later(); } }); child.on('error', error => end(reject, error)); - child.on('close', code => { if (settled) return; settled = true; clearTimeout(timer); code === 0 ? resolve({ stdout }) : reject(Object.assign(new Error('exit ' + code), { code })); }); + child.on('close', code => { if (settled) return; settled = true; clearTimeout(timer); + // PowerShell ended before its window opened (security software ended it, #3831): the person types the path instead. + if (!ready) return resolve({ noDialog: true }); + code === 0 ? resolve({ stdout }) : reject(Object.assign(new Error('exit ' + code), { code })); }); }); } diff --git a/apps/host/tests/folder-dialog.test.mjs b/apps/host/tests/folder-dialog.test.mjs index f92d7a9d..300b3fae 100644 --- a/apps/host/tests/folder-dialog.test.mjs +++ b/apps/host/tests/folder-dialog.test.mjs @@ -170,5 +170,9 @@ test('Windows: a PowerShell that is missing or fails is reported as before', asy f.child.emit('error', Object.assign(new Error('x'), { code: 'ENOENT' })); await assert.rejects(missing, e => e.code === 'ENOENT'); const g = fakeShell(); const failed = watchedWindowsDialog('powershell.exe', [], { spawnProcess: g.spawnProcess }); - g.child.emit('close', 1); await assert.rejects(failed, e => e.code === 1); + g.child.emit('close', 1); + // Ended by security software before any window opened (#3831): the app asks for the path instead of an error. + assert.deepEqual(await failed, { noDialog: true }); + const h = fakeShell(); const late = watchedWindowsDialog('powershell.exe', [], { spawnProcess: h.spawnProcess }); + h.child.stdout.emit('data', 'READY\n'); h.child.emit('close', 1); await assert.rejects(late, e => e.code === 1); }); From 1d20d3e2b06312e09abb2052151112dca3207839 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:36:35 +0200 Subject: [PATCH 06/16] chat: reopening a chat restores its workspace and the turn runs in that folder (#3754) --- apps/host/src/lib/session-workspace.ts | 8 ++++++++ apps/host/src/lib/store.ts | 11 ++++++++--- apps/host/tests/session-workspace.test.mjs | 17 +++++++++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 apps/host/src/lib/session-workspace.ts create mode 100644 apps/host/tests/session-workspace.test.mjs diff --git a/apps/host/src/lib/session-workspace.ts b/apps/host/src/lib/session-workspace.ts new file mode 100644 index 00000000..9c7752cb --- /dev/null +++ b/apps/host/src/lib/session-workspace.ts @@ -0,0 +1,8 @@ +import type { Session, Workspace } from './types'; + +/** The workspace a chat was made in: the sidebar groups chats by this same rule (the saved path, or an earlier folder of the workspace). */ +export function workspaceIdForSession(workspaces: Workspace[], session: Pick | null | undefined): string | null { + const path = session?.workspace; + if (!path) return null; + return workspaces.find(w => w.path === path || !!w.aliases?.includes(path))?.id ?? null; +} diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 7475e4da..3449089a 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -1,3 +1,4 @@ +import { workspaceIdForSession } from './session-workspace'; import { plainFailure, plainFailureText } from './plain-errors'; import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase'; import { updateAgent } from './agents'; @@ -721,7 +722,7 @@ export async function bootstrap() { skills, workspacePath: workspaceState.workspaces[0]?.path ?? '', workspaces: workspaceState.workspaces, - activeWorkspace: workspaceState.workspaces.some(w => w.id === state.activeWorkspace) ? state.activeWorkspace : workspaceState.workspaces[0]?.id ?? null, + activeWorkspace: workspaceState.workspaces.some(w => w.id === state.activeWorkspace) ? state.activeWorkspace : workspaceIdForSession(workspaceState.workspaces, state.sessions.find(s => s.id === state.activeSession)) ?? workspaceState.workspaces[0]?.id ?? null, connection: 'live', }); applyProviders(providers); @@ -1104,7 +1105,11 @@ export function continueTaskInNewChat(task: Task) { } export function selectSession(id: string) { - set({ activeSession: id }); + // A chat comes back in the workspace it was made in, so its next turn runs in the same folder (#3754). + const workspace = workspaceIdForSession(state.workspaces, state.sessions.find(s => s.id === id)); + const change = workspace && workspace !== state.activeWorkspace; + set(change ? { activeSession: id, activeWorkspace: workspace } : { activeSession: id }); + if (change) void loadWorkspaceFiles(); markRead(id); } @@ -1728,7 +1733,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g // The Mode menu's choice for this chat, read when the turn starts; the host applies it to the agent. mode:state.sessions.find(s=>s.id===sessionId)?.preferences?.mode??'manual', // So a skill narrowed to another workspace does not fire here. - workspaceId: state.activeWorkspace, + workspaceId: workspaceIdForSession(state.workspaces, state.sessions.find(s => s.id === sessionId)) ?? state.activeWorkspace, }, (frame) => { // A line from the app itself carries `key` (the English sentence): shown in the person's language. diff --git a/apps/host/tests/session-workspace.test.mjs b/apps/host/tests/session-workspace.test.mjs new file mode 100644 index 00000000..39c33901 --- /dev/null +++ b/apps/host/tests/session-workspace.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { transform } from 'esbuild'; + +const { code } = await transform(await readFile(new URL('../src/lib/session-workspace.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); +const { workspaceIdForSession } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +const workspaces = [{ id: 'a', name: 'A', path: 'C:\A', aliases: ['C:\old'] }, { id: 'b', name: 'B', path: 'D:\Project' }]; + +test('a chat finds the workspace it was made in, by path or by an earlier folder (#3754)', () => { + assert.equal(workspaceIdForSession(workspaces, { workspace: 'D:\Project' }), 'b'); + assert.equal(workspaceIdForSession(workspaces, { workspace: 'C:\old' }), 'a'); +}); +test('a chat with an unknown or no workspace changes nothing', () => { + assert.equal(workspaceIdForSession(workspaces, { workspace: 'E:\gone' }), null); + assert.equal(workspaceIdForSession(workspaces, undefined), null); +}); From 90a7aeea51eec805b0332cf03e9f2543601f1a2f Mon Sep 17 00:00:00 2001 From: chicco83 Date: Fri, 23 Oct 2026 08:27:24 +0200 Subject: [PATCH 07/16] Setup wizard: show the VRAM of AMD cards on Windows from the engine's list when the host probe reports 0 (#3727, PR #3798 by chicco83) --- apps/host/src/components/OnboardingMemory.tsx | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/apps/host/src/components/OnboardingMemory.tsx b/apps/host/src/components/OnboardingMemory.tsx index 92c05909..fe466570 100644 --- a/apps/host/src/components/OnboardingMemory.tsx +++ b/apps/host/src/components/OnboardingMemory.tsx @@ -8,9 +8,20 @@ export function OnboardingMemory({ hardware, native }: { hardware: Hardware | null; native: NativeState['hardware'] | undefined; }) { - const gpus = hardware ? hardware.gpus.filter(gpu => gpu.backend !== 'cpu').map(gpu => ({ id: gpu.id ?? String(gpu.index), name: gpu.name, memory: gpu.vramGb, shared: gpu.unified })) : native?.gpus.map(gpu => ({ id: String(gpu.index), name: gpu.name, memory: gpu.vram_gb, shared: false })) ?? []; + // The Windows host probe (Win32_VideoController) cannot read the VRAM of AMD cards and reports 0 for them; the engine's own list has + // the real size. For a dedicated card the host reports as 0, take the engine's figure for the card of the same name, or for the + // card in the same position when both lists have the same length. A card the engine does not list stays at 0. + const nativeGpus = native?.gpus ?? []; + const hostGpus = hardware ? hardware.gpus.filter(gpu => gpu.backend !== 'cpu') : []; + const engineVram = (name: string, position: number) => { + const norm = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, ''); + const byName = nativeGpus.find(g => norm(g.name).includes(norm(name)) || norm(name).includes(norm(g.name))); + return (byName ?? (nativeGpus.length === hostGpus.length ? nativeGpus[position] : undefined))?.vram_gb || 0; + }; + const gpus = hardware ? hostGpus.map((gpu, position) => ({ id: gpu.id ?? String(gpu.index), name: gpu.name, memory: gpu.unified || gpu.vramGb > 0 ? gpu.vramGb : engineVram(gpu.name, position), shared: gpu.unified })) : nativeGpus.map(gpu => ({ id: String(gpu.index), name: gpu.name, memory: gpu.vram_gb, shared: false })); const dedicatedCount = gpus.filter(gpu => !gpu.shared).length; - const memory = hardware ? memoryInventory(hardware) : native ? { ram: native.ram_gb, vram: native.gpus.reduce((sum, gpu) => sum + Math.max(0, gpu.vram_gb || 0), 0), total: 0, shared: false } : null; + const base = hardware ? memoryInventory(hardware) : null; + const memory = base ? (base.shared ? base : { ...base, vram: gpus.reduce((sum, gpu) => sum + (gpu.shared ? 0 : Math.max(0, gpu.memory || 0)), 0) }) : native ? { ram: native.ram_gb, vram: native.gpus.reduce((sum, gpu) => sum + Math.max(0, gpu.vram_gb || 0), 0), total: 0, shared: false } : null; if (!memory) return
{tr("Reading memory\u2026")}
; const total = memory.ram + memory.vram; From 4ccfd7ca30c472204eddc4bea6e2bb6a5630f27e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:40:59 +0200 Subject: [PATCH 08/16] Windows AMD/Intel cards: real memory size from the DirectX adapter list, load and memory in use from the Windows GPU counters, virtual monitors no longer listed as cards (#3727, #3836) --- apps/host/server/device-probes.mjs | 5 ++ apps/host/server/hardware.mjs | 12 ++-- apps/host/server/system-telemetry.mjs | 43 ++++--------- apps/host/server/windows-gpu.mjs | 90 +++++++++++++++++++++++++++ apps/host/server/windows-poll.mjs | 45 ++++++++++++++ apps/host/tests/windows-gpu.test.mjs | 47 ++++++++++++++ 6 files changed, 206 insertions(+), 36 deletions(-) create mode 100644 apps/host/server/windows-gpu.mjs create mode 100644 apps/host/server/windows-poll.mjs create mode 100644 apps/host/tests/windows-gpu.test.mjs diff --git a/apps/host/server/device-probes.mjs b/apps/host/server/device-probes.mjs index 496c3aeb..f29bd666 100644 --- a/apps/host/server/device-probes.mjs +++ b/apps/host/server/device-probes.mjs @@ -1,6 +1,7 @@ /** Physical topology and GPU sensors; unavailable values stay null. */ import { readFile, readdir, realpath } from 'node:fs/promises'; import { probe, round } from './util.mjs'; +import { windowsGpuReading } from './windows-gpu.mjs'; /** Unified GPUs share one system memory pool; dedicated GPUs each have their own. */ export function gpuMemoryTotals(devices, readings) { @@ -83,6 +84,10 @@ export async function readGpuTelemetry(gpus) { return Promise.all(gpus.map(async gpu=>{ let reading=nvidia.get(gpu.id)??{id:gpu.id??`${gpu.vendor}:${gpu.index}`,temperatureC:null,utilizationPct:null,memoryUsedGb:null,powerW:null,powerLimitW:null,pcieGen:null,pcieGenMax:null,pcieWidth:null,pcieRxMbs:null}; if(gpu.vendor==='nvidia')reading={...reading,pcieRxMbs:transfer.get(gpu.sensorIndex??gpu.index)??null}; + if(gpu.luid&&!nvidia.has(gpu.id)) { + const counters=windowsGpuReading(gpu.luid); + if(counters)reading={...reading,utilizationPct:counters.utilizationPct,memoryUsedGb:round(counters.memoryUsedGb,2)}; + } if(gpu.sensorPath&&!nvidia.has(gpu.id)) { let temperature=null,power=null,powerLimit=null; for(const hwmon of await list(`${gpu.sensorPath}/hwmon`)) { diff --git a/apps/host/server/hardware.mjs b/apps/host/server/hardware.mjs index 0a42b729..d53889e9 100644 --- a/apps/host/server/hardware.mjs +++ b/apps/host/server/hardware.mjs @@ -12,6 +12,7 @@ import { CONTEXT_TOKENS, VARIANTS, footprint } from './catalog.mjs'; import { MODELS_DIR, diskFreeGb, diskTotalGb } from './store.mjs'; import { probe, round } from './util.mjs'; import { utf8Script } from './powershell-utf8.mjs'; +import { DX_ADAPTERS_SCRIPT, parseDxAdapters, windowsOtherGpus } from './windows-gpu.mjs'; let cached = null; let cachedAt = 0; @@ -187,11 +188,12 @@ async function detectGpus(platform, totalGb) { } if(platform==='win32') { const raw=await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',utf8Script('Get-CimInstance Win32_VideoController | Select-Object Name,PNPDeviceID | ConvertTo-Json -Compress')]); - try {const parsed=JSON.parse(raw);for(const row of Array.isArray(parsed)?parsed:[parsed]) { - if(!row?.Name||(/nvidia/i.test(row.Name)&&gpus.some(g=>g.vendor==='nvidia')))continue; - const vendor=/amd|radeon/i.test(row.Name)?'amd':/intel/i.test(row.Name)?'intel':'unknown'; - gpus.push({id:String(row.PNPDeviceID),index:gpus.length,vendor,name:row.Name,vramGb:0,unified:false,backend:'vulkan'}); - }}catch{} + try { + const parsed=JSON.parse(raw); + const rows=(Array.isArray(parsed)?parsed:[parsed]).filter(row=>row?.Name&&!(/nvidia/i.test(row.Name)&&gpus.some(g=>g.vendor==='nvidia'))); + const dx=rows.length?parseDxAdapters(await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',DX_ADAPTERS_SCRIPT],8000)):[]; + for(const card of windowsOtherGpus(rows,dx))gpus.push({...card,index:gpus.length,unified:false,backend:'vulkan'}); + }catch{} } gpus.forEach((g,i)=>{g.index=i;}); diff --git a/apps/host/server/system-telemetry.mjs b/apps/host/server/system-telemetry.mjs index 768a83ff..4085cd54 100644 --- a/apps/host/server/system-telemetry.mjs +++ b/apps/host/server/system-telemetry.mjs @@ -1,6 +1,7 @@ /** Host counters. CPU sockets are measured only when their logical CPU IDs are known. */ import os from 'node:os'; import { spawn } from 'node:child_process'; +import { createPowerShellLoop, endWithHost } from './windows-poll.mjs'; import { readFile, readdir } from 'node:fs/promises'; import { availableMemoryGb } from './hardware.mjs'; import { probe } from './util.mjs'; @@ -47,45 +48,25 @@ export function parseWindowsDiskLine(line) { return m?{read:Number(m[1]),write:Number(m[2])}:null; } -/** - * One long-lived PowerShell reads the disk counters in a loop. A new PowerShell per sample - * paid the cold WMI start every time, missed its timeout and burned WmiPrvSE (#3939). - * Gives up after repeated early exits, so a broken counter stays quiet. - */ +/** The disk counters, read by one long-lived PowerShell (windows-poll.mjs; #3939). */ export function createWindowsDiskReader({ spawnFn=spawn, intervalSec=4, maxStarts=3, now=Date.now }={}) { - let child=null,latest=null,starts=0,buffer=''; + let latest=null; const script=`while($true){$d=Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk -Filter "Name='_Total'";if($d){[Console]::Out.WriteLine(([string]$d.DiskReadBytesPersec)+' '+([string]$d.DiskWriteBytesPersec));[Console]::Out.Flush()};Start-Sleep -Seconds ${intervalSec}}`; - function start() { - if(child||starts>=maxStarts)return; - starts++; - let proc; - try { proc=spawnFn('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{windowsHide:true,stdio:['ignore','pipe','ignore']}); } - catch { return; } - child=proc; - proc.on?.('error',()=>{ if(child===proc)child=null; }); - proc.on?.('exit',()=>{ if(child===proc){child=null;latest=null;} }); - proc.stdout?.on('data',chunk=>{ - buffer+=chunk; - let i; - while((i=buffer.indexOf('\n'))>=0){ - const parsed=parseWindowsDiskLine(buffer.slice(0,i)); - buffer=buffer.slice(i+1); - if(parsed){latest={...parsed,at:now()};starts=0;} - } - }); - proc.unref?.(); - proc.stdout?.unref?.(); - } + const loop=createPowerShellLoop({script,spawnFn,maxStarts,onLine:line=>{ + const parsed=parseWindowsDiskLine(line); + if(parsed)latest={...parsed,at:now()}; + return !!parsed; + }}); return { - read() { start(); return latest; }, - stop() { try{child?.kill();}catch{} child=null; }, - get starts() { return starts; }, + read() { loop.start(); return latest&&now()-latest.at<5*intervalSec*1000?latest:null; }, + stop() { loop.stop(); }, + get starts() { return loop.starts; }, }; } let windowsReader=null; function windowsDisks() { - if(!windowsReader){windowsReader=createWindowsDiskReader();process.once('exit',()=>windowsReader.stop());} + windowsReader??=endWithHost(createWindowsDiskReader()); return windowsReader.read(); } diff --git a/apps/host/server/windows-gpu.mjs b/apps/host/server/windows-gpu.mjs new file mode 100644 index 00000000..8475f192 --- /dev/null +++ b/apps/host/server/windows-gpu.mjs @@ -0,0 +1,90 @@ +/** + * Windows graphics cards that nvidia-smi does not cover (AMD, Intel): their size and their load. + * - size: the DirectX adapter list in the registry (HKLM\SOFTWARE\Microsoft\DirectX) has a 64-bit DedicatedVideoMemory and the adapter + * LUID. Win32_VideoController.AdapterRAM is 32 bits and reads 0 or 4 GB for a 16 GB card (#3727, #3836). + * - load and memory in use: the Windows GPU performance counters (the ones Task Manager shows), read by one long-lived PowerShell and + * matched to the card by LUID. Temperature, power and the PCIe link need the vendor's own library, so they stay "not available". + */ +import { createPowerShellLoop, endWithHost } from './windows-poll.mjs'; +import { utf8Script } from './powershell-utf8.mjs'; + +export const DX_ADAPTERS_SCRIPT = utf8Script( + "Get-ChildItem HKLM:\\SOFTWARE\\Microsoft\\DirectX | ForEach-Object { $p = Get-ItemProperty $_.PSPath; " + + "if ($p.Description -and $null -ne $p.AdapterLuid) { [pscustomobject]@{ Description = [string]$p.Description; VendorId = [string]$p.VendorId; " + + "Luid = [string]$p.AdapterLuid; Dedicated = [string]$p.DedicatedVideoMemory; Software = [string]$p.SoftwareAdapter } } } | ConvertTo-Json -Compress"); + +/** luid_0x_0x in the spelling of the performance counters, from the registry's 64-bit number. */ +export function luidName(value) { + try { + const n = BigInt.asUintN(64, BigInt(String(value))); + const hex = v => '0x' + v.toString(16).padStart(8, '0'); + return `luid_${hex(n >> 32n)}_${hex(n & 0xffffffffn)}`; + } catch { return null; } +} + +/** The adapters the DirectX registry lists: [{ description, vendorId, luid, bytes, software }]. Never throws. */ +export function parseDxAdapters(raw) { + try { + const parsed = JSON.parse(raw), rows = Array.isArray(parsed) ? parsed : [parsed]; + return rows.filter(r => r?.Description).map(r => ({ + description: String(r.Description), vendorId: Number(r.VendorId) || 0, luid: luidName(r.Luid), + bytes: Number(r.Dedicated) || 0, software: String(r.Software) === '1' || String(r.Software).toLowerCase() === 'true', + })); + } catch { return []; } +} + +const norm = text => String(text ?? '').toLowerCase().replace(/[^a-z0-9]/g, ''); +const VIRTUAL = /virtual|remote|indirect|mirror|basic render|meta |parsec|displaylink|idd/i; + +/** + * Win32_VideoController rows + the DirectX adapter list -> the cards this app can show. A card keeps the size from the registry; + * a display driver for a virtual monitor (no size, no known maker) is not a graphics card and is dropped. + */ +export function windowsOtherGpus(videoRows, dx) { + const used = new Set(); + const out = []; + for (const row of videoRows) { + if (!row?.Name) continue; + const match = dx.find((a, i) => !used.has(i) && !a.software && norm(a.description) === norm(row.Name)); + if (match) used.add(dx.indexOf(match)); + const vendor = /amd|radeon/i.test(row.Name) ? 'amd' : /intel/i.test(row.Name) ? 'intel' : 'unknown'; + const vramGb = match?.bytes ? Math.round(match.bytes / 1024 ** 3 * 10) / 10 : 0; + if (vendor === 'unknown' && (!vramGb || VIRTUAL.test(row.Name))) continue; + out.push({ id: String(row.PNPDeviceID), vendor, name: row.Name, vramGb, luid: match?.luid ?? null }); + } + return out; +} + +/** One counter line: "G ". */ +export function parseGpuCounterLine(line) { + const m = /^G\s+(luid_0x[0-9a-f]+_0x[0-9a-f]+)\s+(\d+(?:\.\d+)?)\s+(\d+)\s*$/i.exec(String(line)); + return m ? { luid: m[1].toLowerCase(), utilizationPct: Math.max(0, Math.min(100, Number(m[2]))), memoryUsedGb: Number(m[3]) / 1024 ** 3 } : null; +} + +export function createWindowsGpuReader({ spawnFn, intervalSec = 4, maxStarts = 3, now = Date.now } = {}) { + const readings = new Map(); + const script = utf8Script( + `while($true){` + + `$e=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUEngine);$m=@(Get-CimInstance Win32_PerfFormattedData_GPUPerformanceCounters_GPUAdapterMemory);` + + `$u=@{};foreach($r in $e){if($r.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)_phys_\\d+_eng_\\d+_engtype_(\\w+)'){$k=$matches[1].ToLower()+'|'+$matches[2];$u[$k]=[double]$u[$k]+[double]$r.UtilizationPercentage}};` + + `$b=@{};foreach($k in $u.Keys){$l=$k.Split('|')[0];if(-not $b.ContainsKey($l) -or $u[$k] -gt $b[$l]){$b[$l]=$u[$k]}};` + + `foreach($r in $m){if($r.Name -match '(luid_0x[0-9A-Fa-f]+_0x[0-9A-Fa-f]+)'){$l=$matches[1].ToLower();[Console]::Out.WriteLine('G '+$l+' '+[math]::Round([double]$b[$l],0)+' '+$r.DedicatedUsage)}};` + + `[Console]::Out.Flush();Start-Sleep -Seconds ${intervalSec}}`); + const loop = createPowerShellLoop({ script, spawnFn, maxStarts, onLine: line => { + const parsed = parseGpuCounterLine(line); + if (parsed) readings.set(parsed.luid, { ...parsed, at: now() }); + return !!parsed; + } }); + return { + read(luid) { loop.start(); const r = readings.get(String(luid ?? '').toLowerCase()); return r && now() - r.at < 6 * intervalSec * 1000 ? r : null; }, + stop() { loop.stop(); }, + }; +} + +let shared = null; +/** The card's load and memory in use from the Windows counters; null when there is no reading. */ +export function windowsGpuReading(luid) { + if (process.platform !== 'win32' || !luid) return null; + shared ??= endWithHost(createWindowsGpuReader()); + return shared.read(luid); +} diff --git a/apps/host/server/windows-poll.mjs b/apps/host/server/windows-poll.mjs new file mode 100644 index 00000000..39e247b3 --- /dev/null +++ b/apps/host/server/windows-poll.mjs @@ -0,0 +1,45 @@ +/** + * One long-lived PowerShell that prints a line per reading, in a loop. The monitor used to start a cold PowerShell for every sample; + * its WMI start cost more than the probe timeout, so every query failed and WmiPrvSE burned a core (#3939). + * The loop gives up after `maxStarts` early exits in a row, so a counter that cannot be read stays quiet. + */ +import { spawn } from 'node:child_process'; + +export function createPowerShellLoop({ script, onLine, spawnFn = spawn, maxStarts = 3 }) { + let child = null, starts = 0, buffer = ''; + function start() { + if (child || starts >= maxStarts) return; + starts++; + let proc; + try { proc = spawnFn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); } + catch { return; } + child = proc; + buffer = ''; + proc.on?.('error', () => { if (child === proc) child = null; }); + proc.on?.('exit', () => { if (child === proc) child = null; }); + proc.stdout?.on('data', chunk => { + buffer += chunk; + let i; + while ((i = buffer.indexOf('\n')) >= 0) { + const line = buffer.slice(0, i); + buffer = buffer.slice(i + 1); + if (onLine(line)) starts = 0; + } + }); + proc.unref?.(); + proc.stdout?.unref?.(); + } + return { + start, + stop() { try { child?.kill(); } catch { /* gone */ } child = null; }, + get starts() { return starts; }, + }; +} + +let stoppers = null; +/** Every loop is ended with the host. */ +export function endWithHost(loop) { + if (!stoppers) { stoppers = new Set(); process.once('exit', () => stoppers.forEach(l => l.stop())); } + stoppers.add(loop); + return loop; +} diff --git a/apps/host/tests/windows-gpu.test.mjs b/apps/host/tests/windows-gpu.test.mjs new file mode 100644 index 00000000..3550e6ff --- /dev/null +++ b/apps/host/tests/windows-gpu.test.mjs @@ -0,0 +1,47 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { luidName, parseDxAdapters, windowsOtherGpus, parseGpuCounterLine, createWindowsGpuReader } from '../server/windows-gpu.mjs'; + +const dxRaw = JSON.stringify([ + { Description: 'AMD Radeon RX 9070 XT', VendorId: '4098', Luid: '90370', Dedicated: '17094934528', Software: '0' }, + { Description: 'Microsoft Basic Render Driver', VendorId: '5140', Luid: '1', Dedicated: '0', Software: '1' }, +]); + +test('the LUID is spelled as the performance counters spell it', () => { + assert.equal(luidName('90370'), 'luid_0x00000000_0x00016102'); + assert.equal(luidName(String(0x12n * 2n ** 32n + 5n)), 'luid_0x00000012_0x00000005'); + assert.equal(luidName('nope'), null); +}); + +test('an AMD card on Windows gets its real memory size and a LUID, virtual monitors are not cards (#3727, #3836)', () => { + const dx = parseDxAdapters(dxRaw); + const cards = windowsOtherGpus([ + { Name: 'AMD Radeon RX 9070 XT', PNPDeviceID: 'PCI-A' }, + { Name: 'Meta Virtual Monitor', PNPDeviceID: 'ROOT-1' }, + { Name: 'Virtual Desktop Monitor', PNPDeviceID: 'ROOT-2' }, + ], dx); + assert.equal(cards.length, 1); + assert.equal(cards[0].vendor, 'amd'); + assert.equal(cards[0].vramGb, 15.9); + assert.equal(cards[0].luid, 'luid_0x00000000_0x00016102'); +}); + +test('without the registry list an AMD card is still listed, with no size', () => { + const cards = windowsOtherGpus([{ Name: 'AMD Radeon RX 7900 XT', PNPDeviceID: 'PCI-B' }], parseDxAdapters('garbage')); + assert.deepEqual(cards.map(c => [c.vendor, c.vramGb, c.luid]), [['amd', 0, null]]); +}); + +test('counter lines are read, and the load and VRAM in use reach the card by its LUID', () => { + assert.equal(parseGpuCounterLine('nonsense'), null); + const line = parseGpuCounterLine('G luid_0x00000000_0x00016102 37 4294967296'); + assert.equal(line.utilizationPct, 37); + assert.equal(line.memoryUsedGb, 4); + const procs = []; + const reader = createWindowsGpuReader({ spawnFn: () => { const p = new EventEmitter(); p.stdout = new EventEmitter(); p.kill = () => {}; procs.push(p); return p; }, now: () => 5 }); + assert.equal(reader.read('luid_0x00000000_0x00016102'), null, 'nothing before the first line'); + procs[0].stdout.emit('data', 'G luid_0x00000000_0x00016102 37 4294967296\nG luid_0x00000000_0x00000001 0 0\n'); + assert.equal(reader.read('LUID_0x00000000_0x00016102').utilizationPct, 37); + assert.equal(reader.read('luid_0x00000000_0x00099999'), null); + assert.equal(procs.length, 1, 'one process for every read'); +}); From f750086183f3530fd1fbb3a22941e0dbf6688a39 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:43:02 +0200 Subject: [PATCH 09/16] Models page: the chosen conversation context and cache format count in the memory estimate (#3832) --- apps/host/src/components/NativeModels.tsx | 2 +- apps/host/src/lib/native-fit.ts | 17 ++++++++++++++--- apps/host/tests/native-fit.test.mjs | 14 +++++++++++++- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 9523827c..4bf16382 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -204,7 +204,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(expert && IMAGE_GENERATION_VISIBLE ? <>
{tr("Image generation ")}{tr("Optional")} { }}/>
: null)} {tr(expert ?

{tr("Expert settings")}

{tr(tunedNow ?

{tr("Showing the values of your tuning '{0}'.", [tunedNow.name])}

: null)}
: null)} - + !pending && setPlan(null)} actions={<> setPlan(null)}>{tr("Cancel")} void download()}>{tr(installed?.ready ? "Apply & load" : "Download & load")}}>

{tr(plan?.plan?.title ?? selectedFamily?.title)}{tr(installed?.ready ? null : <>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")})}

{tr(plan?.drafting?.needed ?

{tr("Choosing DFlash2 also downloads its drafter: about {0} GB, once. If it does not fit in graphics memory, the model uses the MTP instead.", [plan.drafting.gb])}

: null)}{tr(installed?.ready ?

{tr("The model files are already on this computer. Nothing will be downloaded; only the settings you chose are applied.")}

: null)}{tr(plan?.plan?.disk_short ? : null)}{tr(installed?.ready ?

{tr("Any currently loaded native models will be unloaded first.")}

: <>

{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}

{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}

)}{tr(selectedSize?.images ?

{tr("Vision encoder files are included. Picture reading loads only when enabled.")}

: null)}
diff --git a/apps/host/src/lib/native-fit.ts b/apps/host/src/lib/native-fit.ts index 23dad9e6..b34d2784 100644 --- a/apps/host/src/lib/native-fit.ts +++ b/apps/host/src/lib/native-fit.ts @@ -30,16 +30,27 @@ export function memoryNeeded(v: FitInput): number { return round1((v.experts_gb ?? v.ram_needed_gb ?? 0) + DENSE_EXTRA_GB); } -export function fitOn(v: FitInput, hw: FitHardware | null | undefined, mtp = true): Fit { +/** The conversation cache of Flash-Next: 13 attention layers, bytes per token per layer by cache format, 5.4% over the bare cache + * (strata_control/vram_fit.py KV_BYTES, KV_MEASURED_FACTOR; setup.py UD_FIT_KV_BYTES). */ +const KV_BYTES: Record = { fp16: 2112, int8: 1056, q4_0: 576, k8v4: 816 }; +const KV_LAYERS = 13, KV_FACTOR = 1.054, BASE_CONTEXT = 32768; +export function cacheGb(context: number, kv = 'int8'): number { + return context * KV_LAYERS * (KV_BYTES[String(kv).toLowerCase()] ?? KV_BYTES.int8) * KV_FACTOR / 2 ** 30; +} +export interface CacheChoice { context: number; kv?: string } + +export function fitOn(v: FitInput, hw: FitHardware | null | undefined, mtp = true, cache?: CacheChoice | null): Fit { const memoryGb = memoryNeeded(v); + // DENSE_GB already holds a 32K cache in the default format; the person's context and format replace it (#3832). + const denseGb = cache && cache.context > 0 ? Math.max(DENSE_GB - cacheGb(BASE_CONTEXT), 0) + cacheGb(cache.context, cache.kv) : DENSE_GB; const ram = Number(hw?.ram_gb), vram = Number(hw?.vram_gb) || 0; if (!Number.isFinite(ram) || ram <= 0) return { memoryGb, vramUseGb: 0, ramUseGb: 0, spillGb: 0, known: false }; const experts = Math.max(0, memoryNeeded(v) - DENSE_EXTRA_GB); - const onGpu = Math.max(0, Math.min(experts, vram - DENSE_GB - (mtp && vram > 0 ? MTP_VRAM_GB : 0))); + const onGpu = Math.max(0, Math.min(experts, vram - denseGb - (mtp && vram > 0 ? MTP_VRAM_GB : 0))); const ramRoom = Math.max(0, ram - SYSTEM_ROOM_GB); const spillGb = Math.max(0, experts - onGpu - ramRoom); const inRam = Math.max(0, experts - onGpu - spillGb); - const vramUseGb = vram > 0 ? Math.min(vram, DENSE_GB + (mtp ? MTP_VRAM_GB : 0) + onGpu) : 0; + const vramUseGb = vram > 0 ? Math.min(vram, denseGb + (mtp ? MTP_VRAM_GB : 0) + onGpu) : 0; return { memoryGb, vramUseGb: round1(vramUseGb), ramUseGb: round1(inRam + DENSE_EXTRA_GB * (vram > 0 ? 0 : 1)), spillGb: round1(spillGb), known: true }; } diff --git a/apps/host/tests/native-fit.test.mjs b/apps/host/tests/native-fit.test.mjs index b09e2b2d..b1fb57fd 100644 --- a/apps/host/tests/native-fit.test.mjs +++ b/apps/host/tests/native-fit.test.mjs @@ -5,7 +5,7 @@ import { readFile } from 'node:fs/promises'; import { transform } from 'esbuild'; const { code } = await transform(await readFile(new URL('../src/lib/native-fit.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); -const { fitOn, memoryNeeded, RECOMMENDED, VERSION_GROUPS, groupOpen, recommendedVersions, PICK_NOTE, OTHER_NOTE, MTP_VRAM_GB } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +const { fitOn, cacheGb, memoryNeeded, RECOMMENDED, VERSION_GROUPS, groupOpen, recommendedVersions, PICK_NOTE, OTHER_NOTE, MTP_VRAM_GB } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); const swift = { ram_needed_gb: 48, experts_gb: 35.5 }; const gyroS = { ram_needed_gb: 27.6, experts_gb: 25.8, mem_total: true }; @@ -83,3 +83,15 @@ test('the tiers of the engine are 40 GB Swift IQ2_XS, 48 GB IQ3_XXS, 64 GB IQ3_S assert.deepEqual([...m[1].matchAll(/\(([\d.]+),\s*"(\w+)",\s*"(\w+)"\)/g)].map(x => [Number(x[1]), x[2], x[3]]), [[62, 'qwen', 'IQ3_S'], [46, 'qwen', 'IQ3_XXS'], [38, 'swift', 'IQ2_XS']], file); } }); + +test('the conversation context and cache format move the estimate (#3832)', () => { + const pc = { ram_gb: 64, vram_gb: 16 }; + const base = fitOn(swift, pc); + assert.deepEqual(fitOn(swift, pc, true, { context: 32768, kv: 'int8' }), base, 'the default context is what the fixed figure already held'); + const big = fitOn(swift, pc, true, { context: 524288, kv: 'int8' }); + assert.ok(big.vramUseGb >= base.vramUseGb && big.ramUseGb > base.ramUseGb, 'a bigger cache takes graphics memory from the experts, which then sit in RAM'); + assert.ok(fitOn(swift, pc, true, { context: 524288, kv: 'q4_0' }).ramUseGb < big.ramUseGb, 'a smaller cache format leaves more room'); + assert.ok(Math.abs(cacheGb(524288, 'int8') * 1024 - 7361) < 25, 'the 512K Int8 cache is the 7361 MiB the engine reports'); + const tight = fitOn(q4, pc, true, { context: 524288, kv: 'int8' }); + assert.ok(tight.spillGb > fitOn(q4, pc).spillGb, 'what no longer fits is read from the SSD and the card says so'); +}); From 25abbdd90cffead60abd063ee3b702ce50d62548 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:43:25 +0200 Subject: [PATCH 10/16] Models page: the chosen conversation context and cache format count in the memory estimate (#3832) --- apps/host/src/lib/native-fit.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/host/src/lib/native-fit.ts b/apps/host/src/lib/native-fit.ts index b34d2784..fad8c036 100644 --- a/apps/host/src/lib/native-fit.ts +++ b/apps/host/src/lib/native-fit.ts @@ -35,7 +35,7 @@ export function memoryNeeded(v: FitInput): number { const KV_BYTES: Record = { fp16: 2112, int8: 1056, q4_0: 576, k8v4: 816 }; const KV_LAYERS = 13, KV_FACTOR = 1.054, BASE_CONTEXT = 32768; export function cacheGb(context: number, kv = 'int8'): number { - return context * KV_LAYERS * (KV_BYTES[String(kv).toLowerCase()] ?? KV_BYTES.int8) * KV_FACTOR / 2 ** 30; + return (121 + context * KV_LAYERS * (KV_BYTES[String(kv).toLowerCase()] ?? KV_BYTES.int8) * KV_FACTOR / 2 ** 20) / 1024; // 121 MiB fixed per session } export interface CacheChoice { context: number; kv?: string } From e61b7024cfadff37f8e981735aaead921dd05973 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:45:12 +0200 Subject: [PATCH 11/16] Models page: a neutral placeholder until the engine's first answer, not the bundled Starter (#3740) --- apps/host/src/lib/native.ts | 6 +++++- apps/host/src/screens/ModelRun.tsx | 8 ++++++-- apps/host/tests/native-settled.test.mjs | 21 +++++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 apps/host/tests/native-settled.test.mjs diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index 3dfbf068..9e8588a8 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -15,6 +15,10 @@ export interface NativeState { visionReader?: boolean;available:boolean;repo:string;downloadDirectory?:string;/** Free bytes on the drive that holds the models folder. */downloadFreeBytes?:number|null;downloadTotalBytes?:number|null;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;/** The picture-reading files are on this computer (notes-split-agent8.md, item 8). */visionPrepared?:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';/** The Drafting choice saved with the model: auto | mtp | dflash2 | off. */drafting?:string;dataFolder?:string;diskGb?:number;diskBytes?:number;/** Files this model shares with another (the picture reader, the draft layer): counted once, in `usage`. */sharedBytes?:number;/** What Delete frees: files in Strata's own folders that no other model uses. */removableGb?:number;missing_files?:string[]}[];/** What all models take on disk, from their real files, shared files counted once. */usage?:{total_bytes:number;total_gb:number;shared_bytes:number;shared_gb:number;models:Record}|null;data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;engine_vendor?:string;gpus:{index:number;name:string;vram_gb:number;usable:boolean;/** SMs x clock: only the order between cards matters (strata_control/gpu_roles.py). */speed?:number;vendor?:string;uma?:boolean;integrated?:boolean;unified_gb?:number;problem?:string|null}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{/** The engine serves DFlash2 (Control says): the Drafting choice then offers it. */dflash2?:boolean;responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}} let state:NativeState|null=null; const listeners=new Set<()=>void>(); +/** True once the first read of the native state has ended, whatever its answer: until then the Models page must not pick a model of its own (#3740). */ +let settled=false; +export const nativeSettled=()=>settled; +export function subscribeNative(fn:()=>void){listeners.add(fn);return()=>{listeners.delete(fn);};} function put(value:NativeState){if(state&&JSON.stringify(state)===JSON.stringify(value))return;state=value;listeners.forEach(fn=>fn());} /** The host pushes its whole native state (jobs included) at every progress step: the page shows it at once, without waiting for the next poll. */ export function applyNativeEvent(value:unknown){if(value&&typeof value==='object'&&'available' in value&&'jobs' in value)put(value as NativeState);} @@ -24,7 +28,7 @@ function read(force:boolean):Promise{ // A read that never answers must not freeze the page: after the limit the next poll starts a fresh one. let stop:ReturnType|undefined; const limit=new Promise((_,reject)=>{stop=setTimeout(()=>reject(new Error('The host did not answer in time.')),READ_LIMIT_MS);}); - return Promise.race([request,limit]).then(put).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>clearTimeout(stop)); + return Promise.race([request,limit]).then(put).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>{clearTimeout(stop);if(!settled){settled=true;listeners.forEach(fn=>fn());}}); } /* Two kinds of read that never wait for each other: the light poll (the host answers at once with the jobs it holds) and the forced read after an action (the host re-reads the installation, which can take many seconds while a download is writing). A slow forced read used to hold every later poll, so a running download looked stuck. */ diff --git a/apps/host/src/screens/ModelRun.tsx b/apps/host/src/screens/ModelRun.tsx index d3674544..56f92aff 100644 --- a/apps/host/src/screens/ModelRun.tsx +++ b/apps/host/src/screens/ModelRun.tsx @@ -1,5 +1,5 @@ import { tr } from '../lib/i18n'; -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { ActionError, Btn, Dialog, ErrorNotice, Icon, Select } from '../components/ui'; import { Screen } from '../components/layout'; import { DemoTest } from '../components/EngineExperience'; @@ -24,7 +24,7 @@ import { familyVersion, modelFamilies } from '../lib/model-versions'; import { sizeGb } from '../lib/format'; import { applyImageModel, getState, useLifecycle, loadRuntimeModel, loadVariant, pushToast, restartEngine, saveEngine, selectImageModel, setConfigDraft, useStore, validateEngine } from '../lib/store'; import type { ImageModelChoice, RuntimeModels, RuntimeModel } from '../lib/types'; -import { useNative } from '../lib/native'; +import { useNative, nativeSettled, subscribeNative } from '../lib/native'; import { NativeModels } from '../components/NativeModels'; import { NativeLocalModel } from '../components/NativeLocalModel'; import { parseLocation } from '../lib/router'; @@ -35,8 +35,12 @@ type Issue = { type RunStage = 'idle' | 'checking' | 'loading' | 'ready'; export function ModelRunScreen() { const native = useNative(); + const settled = useSyncExternalStore(subscribeNative, nativeSettled); const location = parseLocation(window.location.hash), entry = location.param; const [other, setOther] = useState(entry === 'local' || entry === 'local-import'), [importFirst, setImportFirst] = useState(entry === 'local-import'); + // 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. + if (!native && !settled) + return
; if (native && other) return { setOther(false); setImportFirst(false); }}/>; if (native && !other) diff --git a/apps/host/tests/native-settled.test.mjs b/apps/host/tests/native-settled.test.mjs new file mode 100644 index 00000000..6283fd41 --- /dev/null +++ b/apps/host/tests/native-settled.test.mjs @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { build } from 'esbuild'; + +const compiled = await build({ stdin: { contents: "export * from './src/lib/native';", resolveDir: process.cwd() }, bundle: true, write: false, platform: 'node', format: 'esm' }); +const lib = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); + +test('the Models page waits for the first native answer before it picks a model (#3740)', async () => { + let release; + globalThis.fetch = () => new Promise(resolve => { release = () => resolve({ ok: true, status: 200, statusText: 'OK', text: async () => JSON.stringify({ available: true, jobs: [], instances: [] }) }); }); + let heard = 0; + const off = lib.subscribeNative(() => { heard++; }); + assert.equal(lib.nativeSettled(), false, 'nothing read yet: show a placeholder, not the Starter'); + const reading = lib.refreshNative(); + assert.equal(lib.nativeSettled(), false); + release(); + await reading; + assert.equal(lib.nativeSettled(), true); + assert.ok(heard >= 1, 'the page is told'); + off(); +}); From c7899f9c890ab14b0dfad61dc07292360c2eec63 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:45:58 +0200 Subject: [PATCH 12/16] chat: Copy response and Copy message answer Copied or say they could not (with an older-copy fallback); a typed message keeps its line breaks (#3731, #3720) --- apps/host/src/lib/clipboard.ts | 35 +++++++++++++++++++++++++ apps/host/src/screens/Chat.tsx | 9 ++++--- apps/host/src/styles/app.css | 3 +++ apps/host/tests/clipboard-copy.test.mjs | 30 +++++++++++++++++++++ 4 files changed, 73 insertions(+), 4 deletions(-) create mode 100644 apps/host/src/lib/clipboard.ts create mode 100644 apps/host/tests/clipboard-copy.test.mjs diff --git a/apps/host/src/lib/clipboard.ts b/apps/host/src/lib/clipboard.ts new file mode 100644 index 00000000..7a51f061 --- /dev/null +++ b/apps/host/src/lib/clipboard.ts @@ -0,0 +1,35 @@ +/** + * Copy text for the person. The browser clipboard call can be refused (the desktop web view asks for permission, or has no clipboard + * object); the older copy command through a hidden field still works there. The answer is always a toast: "Copied", or one plain + * sentence and what to do next (#3731). + */ +export interface ClipboardDeps { + clipboard?: { writeText(text: string): Promise } | null; + legacyCopy?: (text: string) => boolean; + toast: (tone: 'success' | 'warn', title: string, body?: string) => void; +} + +function legacyCopy(text: string): boolean { + if (typeof document === 'undefined') return false; + const field = document.createElement('textarea'); + field.value = text; + field.setAttribute('readonly', ''); + field.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none'; + document.body.appendChild(field); + const active = document.activeElement as HTMLElement | null; + try { + field.select(); + return document.execCommand('copy'); + } catch { return false; } + finally { field.remove(); active?.focus?.(); } +} + +export async function copyText(text: string, label: string, deps: ClipboardDeps): Promise { + const clipboard = deps.clipboard === undefined ? (typeof navigator === 'undefined' ? null : navigator.clipboard) : deps.clipboard; + let done = false; + try { if (clipboard) { await clipboard.writeText(text); done = true; } } catch { /* the fallback is next */ } + if (!done) { try { done = (deps.legacyCopy ?? legacyCopy)(text); } catch { done = false; } } + if (done) deps.toast('success', 'Copied', label); + else deps.toast('warn', 'Couldn’t copy', 'Select the text and copy it with Ctrl+C.'); + return done; +} diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 286fb723..97dc34f2 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -39,6 +39,7 @@ import { Btn, Icon, IconBtn, ErrorNotice, type IconName } from '../components/ui import { composerCap, scrollBehavior } from '../lib/responsive'; import { relTime, cx, duration, tokens, tps } from '../lib/format'; import { createSubagentExample, pushToast, setPreviewTabClosed, branchFrom, continueLast, markRead, resolveTool, retryLast, selectSession, rewindTo, sendMessage, stopStreaming, useStore, } from '../lib/store'; +import { copyText } from '../lib/clipboard'; import { getSlashCommands } from '../lib/commands'; import { useLocation } from '../lib/router'; import { composerSends } from '../lib/shortcut-bindings'; @@ -616,11 +617,11 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp const [sentTime, setSentTime] = useState(() => relTime(m.at)); if (m.role === 'user') { return (
setSentTime(relTime(m.at))} onFocus={() => setSentTime(relTime(m.at))}> -
{tr(m.photos?.length ? : null)}{m.markdown ? : m.content}
+
{tr(m.photos?.length ? : null)}{m.markdown ? : {m.content}}
- void navigator.clipboard.writeText(m.content)}/> + void copyText(m.content, 'Message', { toast: pushToast })}/> { const prompt = rewindTo(m.id); if (prompt !== null) @@ -659,11 +660,11 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp {tr(!m.streaming && !m.timeSkipId && (m.content || m.error) ? (
{tr(isLast ? <> - void navigator.clipboard.writeText(m.content)}/> + void copyText(m.content, 'Response', { toast: pushToast })}/> void retryLast(m.id)}/> : null)} - {tr(!isLast ? <> : null)} + {tr(!isLast ? <> : null)} {tr(isLast ? : null)} {tr(m.tokens || m.tps || m.durationMs ?

{tr(m.tokens ? `${tokens(m.tokens)} tokens` : '')}{tr(m.tps ? ` · ${tps(m.tps)} tok/s` : '')}{tr(m.durationMs ? ` · ${duration(m.durationMs)}` : '')}{tr(m.demo ? ' · Example' : '')}

: null)} diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index bb27e246..977ecbd5 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7517,3 +7517,6 @@ textarea { .md-math-block .md-math--display { margin: 0; } .md-math .katex { font-size: 1.08em; } .md-math .katex-display { margin: 0; } + +/* A message the person typed keeps its line breaks (#3720). */ +.st-bubble__text { white-space: pre-wrap; overflow-wrap: anywhere; } diff --git a/apps/host/tests/clipboard-copy.test.mjs b/apps/host/tests/clipboard-copy.test.mjs new file mode 100644 index 00000000..0ed7787a --- /dev/null +++ b/apps/host/tests/clipboard-copy.test.mjs @@ -0,0 +1,30 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { transform } from 'esbuild'; + +const { code } = await transform(await readFile(new URL('../src/lib/clipboard.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); +const { copyText } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +const toasts = () => { const list = []; return { list, toast: (...a) => list.push(a) }; }; + +test('Copy says Copied when the clipboard takes the text (#3731)', async () => { + const t = toasts(); let got = ''; + assert.equal(await copyText('hello', 'Response', { clipboard: { writeText: async v => { got = v; } }, toast: t.toast }), true); + assert.equal(got, 'hello'); assert.equal(t.list[0][0], 'success'); +}); +test('a refused clipboard falls back to the older copy command', async () => { + const t = toasts(); let got = ''; + assert.equal(await copyText('x', 'Response', { clipboard: { writeText: async () => { throw new Error('denied'); } }, legacyCopy: v => { got = v; return true; }, toast: t.toast }), true); + assert.equal(got, 'x'); assert.equal(t.list[0][0], 'success'); +}); +test('when nothing works the person is told, never left with a silent click', async () => { + const t = toasts(); + assert.equal(await copyText('x', 'Response', { clipboard: null, legacyCopy: () => false, toast: t.toast }), false); + assert.equal(t.list.length, 1); assert.equal(t.list[0][0], 'warn'); assert.match(t.list[0][2], /Ctrl\+C/); +}); +test('the typed message keeps its line breaks (#3720) and the chat uses the shared copy', async () => { + const css = await readFile(new URL('../src/styles/app.css', import.meta.url), 'utf8'); + assert.match(css, /\.st-bubble__text\s*\{[^}]*white-space:\s*pre-wrap/); + const chat = await readFile(new URL('../src/screens/Chat.tsx', import.meta.url), 'utf8'); + assert.doesNotMatch(chat, /void navigator\.clipboard\.writeText/); +}); From 780a69b41b50d04421ebb2014486bef4b951a329 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:47:18 +0200 Subject: [PATCH 13/16] Expert settings: decimals can be typed in sampling and number fields; Ctrl+V of a screenshot reads clipboard items (#3736, #3748) --- apps/host/src/components/DecimalInput.tsx | 28 +++++++++++++++++++++ apps/host/src/components/DropZone.tsx | 11 +------- apps/host/src/components/NativeSettings.tsx | 14 ++++------- apps/host/src/lib/decimal.ts | 9 +++++++ apps/host/src/lib/pasted-files.ts | 19 ++++++++++++++ apps/host/tests/typed-and-pasted.test.mjs | 24 ++++++++++++++++++ 6 files changed, 86 insertions(+), 19 deletions(-) create mode 100644 apps/host/src/components/DecimalInput.tsx create mode 100644 apps/host/src/lib/decimal.ts create mode 100644 apps/host/src/lib/pasted-files.ts create mode 100644 apps/host/tests/typed-and-pasted.test.mjs diff --git a/apps/host/src/components/DecimalInput.tsx b/apps/host/src/components/DecimalInput.tsx new file mode 100644 index 00000000..e48f9689 --- /dev/null +++ b/apps/host/src/components/DecimalInput.tsx @@ -0,0 +1,28 @@ +import { useEffect, useState } from 'react'; +import { parseDecimal, partialDecimal } from '../lib/decimal'; + +/** A number field that lets the person type a decimal point: it keeps the text while it is typed and tells the page the number once it is one (#3736). */ +export function DecimalInput({ value, onChange, ariaLabel, className = 'st-input', placeholder, disabled }: { + value: number | null | undefined; + onChange: (value: number | null) => void; + ariaLabel: string; + className?: string; + placeholder?: string; + disabled?: boolean; +}) { + const [text, setText] = useState(value === null || value === undefined ? '' : String(value)); + // A change that came from elsewhere (Restore saved, another tab) replaces the text, but never while the typed text already means this number. + useEffect(() => { + const shown = text === '' ? null : parseDecimal(text); + if ((value ?? null) !== shown) setText(value === null || value === undefined ? '' : String(value)); + }, [value]); + return { + const next = e.target.value; + if (!partialDecimal(next)) return; + setText(next); + if (next.trim() === '') onChange(null); + else { const n = parseDecimal(next); if (n !== null) onChange(n); } + }} + onBlur={() => { const n = text.trim() === '' ? null : parseDecimal(text); setText(n === null ? '' : String(n)); }}/>; +} diff --git a/apps/host/src/components/DropZone.tsx b/apps/host/src/components/DropZone.tsx index c0b1f976..d9a3ed46 100644 --- a/apps/host/src/components/DropZone.tsx +++ b/apps/host/src/components/DropZone.tsx @@ -6,16 +6,7 @@ import { Icon } from './ui'; /** Files dropped on the chat go where the attach button would put them: the composer reads the 'strata:drop-files' event. */ export const DROP_EVENT = 'strata:drop-files'; -/** The pictures on the clipboard, named so each one is told apart in the composer (a pasted screenshot arrives as "image.png"). */ -export function pastedFiles(data: DataTransfer | null | undefined): File[] { - const out: File[] = []; - for (const file of Array.from(data?.files ?? [])) { - if (!file.type.startsWith('image/')) continue; - const extension = file.type.split('/')[1]?.replace('jpeg', 'jpg').replace(/[+].*/, '') || 'png'; - out.push(new File([file], `Pasted picture ${new Date().toLocaleTimeString().replace(/[^0-9]+/g, '-').replace(/-$/, '')}${out.length ? `-${out.length + 1}` : ''}.${extension}`, { type: file.type })); - } - return out; -} +export { pastedFiles } from '../lib/pasted-files'; const hasFiles = (e: React.DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes('Files'); /** A file dropped outside the chat must not take the window to that file: the page ignores it (called once at start). */ diff --git a/apps/host/src/components/NativeSettings.tsx b/apps/host/src/components/NativeSettings.tsx index 8b1e39bb..53eac3e6 100644 --- a/apps/host/src/components/NativeSettings.tsx +++ b/apps/host/src/components/NativeSettings.tsx @@ -1,3 +1,4 @@ +import { DecimalInput } from './DecimalInput'; import { tr } from '../lib/i18n'; import {nativeSettingsResponse,nativeSettingsValues} from '../lib/native-settings-response'; import { describeChange, type TunedChange } from '../lib/tune-values'; @@ -92,14 +93,7 @@ export function NativeSettings({ model }: { ; const rows = (native?.fields ?? []).filter(f => `${tr(f.label)} ${f.id} ${tr(f.group)}`.toLowerCase().includes(query.toLowerCase())); return
{tr("Native engine settings")}{tr(tuned?.changed?.length ?

{tr("Your tuning '{0}' sets", [tuned.preset?.name ?? ''])}

    {tuned.changed.map(c => { const d = describeChange(c); return
  • {d.name}{d.now || tr('off')}{d.was !== null ? {tr("was {0}", [d.was])} : null}
  • ; })}
: null)}

{tr(!original ? 'Reading saved settings… ' : '')}{tr("Settings for this model. Blank values use Strata\u2019s defaults.")}

{tr(['fields', 'json', 'tools'].map(t => ))}
- {tr(tab === 'fields' ? <> setQuery(e.target.value)}/>{tr(['Responses', 'GPU & memory', 'Serving', 'Image reading', 'Tools', 'Recovery'].map(group => rows.some(f => f.group === group) ?

{tr(group)}

{tr(rows.filter(f => f.group === group).map(f => ))}
: null))}

{tr("Sampling")}

{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]) => ))}
: tab === 'json' ? <>

{tr("Engine arguments and STRATA environment flags are editable here. Program paths and network access remain managed by the host.")}