From ea6fcea1d805c7e90a5610da43972e1be69911b2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 1 Nov 2026 12:34:39 +0100 Subject: [PATCH 01/59] Window title is Strata on every page --- apps/host/index.html | 2 +- apps/host/server/index.mjs | 2 +- apps/host/tests/window-title.test.mjs | 26 ++++++++++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 apps/host/tests/window-title.test.mjs diff --git a/apps/host/index.html b/apps/host/index.html index 7f7aae759d..5db8e099a2 100644 --- a/apps/host/index.html +++ b/apps/host/index.html @@ -3,7 +3,7 @@ - Strata — local AI, tuned to one model + Strata diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 36a4c066d1..b948969066 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -2233,7 +2233,7 @@ async function staticFile(req, res, path) { if (!existsSync(DIST)) { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end( - `Strata host + `Strata

Strata host is running

No built web app found at ${DIST}.

diff --git a/apps/host/tests/window-title.test.mjs b/apps/host/tests/window-title.test.mjs new file mode 100644 index 0000000000..76153bb02c --- /dev/null +++ b/apps/host/tests/window-title.test.mjs @@ -0,0 +1,26 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync, readdirSync, statSync} from 'node:fs'; +import {resolve, join} from 'node:path'; + +const root = resolve(import.meta.dirname, '..'); +const read = (p) => readFileSync(resolve(root, p), 'utf8'); + +test('the window title is "Strata" on every page', () => { + assert.match(read('index.html'), /Strata<\/title>/); + assert.match(read('server/index.mjs'), /<title>Strata<\/title>/); + assert.match(read('../desktop/src-tauri/src/main.rs'), /WebviewWindowBuilder::new\(app, "main"[^\n]*\.title\("Strata"\)/); +}); + +test('no screen sets document.title to anything else', () => { + const hits = []; + const walk = (dir) => { + for (const name of readdirSync(dir)) { + const full = join(dir, name); + if (statSync(full).isDirectory()) walk(full); + else if (/\.(ts|tsx)$/.test(name) && /document\.title\s*=/.test(readFileSync(full, 'utf8'))) hits.push(full); + } + }; + walk(resolve(root, 'src')); + assert.deepEqual(hits, []); +}); From 7f36ac9b2eedf7f08e5bf5104748534cf5f37ae5 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:37:08 +0100 Subject: [PATCH 02/59] Tasks: header is just the title, at the chat's title size --- apps/host/src/screens/Tasks.tsx | 2 +- apps/host/src/styles/liquid.css | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/host/src/screens/Tasks.tsx b/apps/host/src/screens/Tasks.tsx index cbb9ef55cb..27a4f38f4f 100644 --- a/apps/host/src/screens/Tasks.tsx +++ b/apps/host/src/screens/Tasks.tsx @@ -80,7 +80,7 @@ export function TasksScreen() { {tr(currentTask.lastRunAt || currentTask.output || currentTask.error ? <Btn icon="chat" disabled={pending || currentTask.status === 'running'} onClick={() => continueTaskInNewChat(currentTask)}>{tr("Continue in a new chat")}</Btn> : null)} <Btn variant="primary" icon={currentTask.status === 'running' ? 'stop' : 'bolt'} disabled={pending || !loaded && currentTask.status !== 'running'} onClick={() => void action(() => api.post(`/api/tasks/${currentTask.id}/${currentTask.status === 'running' ? 'stop' : 'run'}`))}>{tr(currentTask.status === 'running' ? 'Stop' : 'Run now')}</Btn> </div> : null; - return <Screen width={view === 'board' && !currentTask ? 'full' : 'normal'} title={currentTask ? <span className="sr-only">{currentTask.title}</span> : "Tasks"} sub={currentTask ? undefined : view === 'board' ? "Everything that is running, waiting for you, or needs a look." : "Run a prompt on a schedule, or whenever you need it."} actions={currentTask ? taskHeader : <div className="tasks-actions"><Seg ariaLabel="View" value={view} onChange={setView} options={[{ value: 'schedule', label: 'Schedule', icon: 'clock' }, { value: 'board', label: 'Board', icon: 'panel' }]}/><input className="st-input tasks-search" type="search" aria-label={tr("Search tasks")} placeholder={tr("Search tasks…")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(view === 'board' ? null : <Select ariaLabel={tr("Sort tasks")} value={sort} options={[{ value: 'next', label: 'Next run' }, { value: 'name', label: 'Name' }]} onChange={setSort}/>)}<IconBtn name="plus" title={tr("New task")} onClick={() => open(blank())}/></div>}> + return <Screen width={view === 'board' && !currentTask ? 'full' : 'normal'} title={currentTask ? <span className="sr-only">{currentTask.title}</span> : "Tasks"} actions={currentTask ? taskHeader : <div className="tasks-actions"><Seg ariaLabel="View" value={view} onChange={setView} options={[{ value: 'schedule', label: 'Schedule', icon: 'clock' }, { value: 'board', label: 'Board', icon: 'panel' }]}/><input className="st-input tasks-search" type="search" aria-label={tr("Search tasks")} placeholder={tr("Search tasks…")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(view === 'board' ? null : <Select ariaLabel={tr("Sort tasks")} value={sort} options={[{ value: 'next', label: 'Next run' }, { value: 'name', label: 'Name' }]} onChange={setSort}/>)}<IconBtn name="plus" title={tr("New task")} onClick={() => open(blank())}/></div>}> <div className="tasks-page"> {tr(!currentTask && view !== 'board' && <p className="task-runtime small muted"><Icon name="clock" size={16}/>{tr(library?.mode === 'simulated' ? 'Example model · sample answers. ' : '')}{tr("Runs while Strata\u2019s host is open. Runs saved instructions using the loaded model.")}</p>)} diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index d9b2d7fd56..6037deca9d 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -549,10 +549,14 @@ body { and two shapes for one row. The title is the row's subject and takes the reading step; both dropdowns are quiet capsules of the same height, with the border left to the hover state so the chrome stays behind the conversation. */ -.chat-toolbar__conversation h1 { +.chat-toolbar__conversation h1, +.main__head .main__title { font-size: var(--st-fs-md); letter-spacing: -0.01em; } +/* One title step for the chat's "New conversation" and every screen header + (Tasks, Skills, Monitor, Serving, Model, Engine): --st-fs-md, 600. */ +.main__head .main__title { font-weight: 600; } .chat-model-badge.chat-model-picker, .chat-agents { height: 30px; From 87610346d6a33d7a256d8275ee7c038f5df29a2b Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:37:13 +0100 Subject: [PATCH 03/59] Skills, Monitor and the other screens share the chat title size (one rule, tested) --- apps/host/tests/screen-titles.test.mjs | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 apps/host/tests/screen-titles.test.mjs diff --git a/apps/host/tests/screen-titles.test.mjs b/apps/host/tests/screen-titles.test.mjs new file mode 100644 index 0000000000..4fb98e60f5 --- /dev/null +++ b/apps/host/tests/screen-titles.test.mjs @@ -0,0 +1,29 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {resolve} from 'node:path'; + +const root = resolve(import.meta.dirname, '..'); +const read = (p) => readFileSync(resolve(root, p), 'utf8'); +const liquid = read('src/styles/liquid.css'); + +test('every screen header title uses the chat title step, from one rule', () => { + const rule = liquid.match(/\.chat-toolbar__conversation h1,\s*\.main__head \.main__title \{([^}]*)\}/); + assert.ok(rule, 'the chat title and the screen titles share one rule'); + assert.match(rule[1], /font-size:\s*var\(--st-fs-md\)/); + assert.match(liquid, /\.main__head \.main__title \{ font-weight: 600; \}/); + const imports = [...read('src/main.tsx').matchAll(/import '\.\/styles\/([^']+)'/g)].map(m => m[1]); + assert.equal(imports.at(-1), 'liquid.css', 'liquid.css loads last, so no sheet after it can resize a title'); +}); + +test('the chat title and the screen titles are the same size', () => { + const app = read('src/styles/app.css'); + const chat = app.match(/\.chat-toolbar__conversation h1 \{[^}]*font-size:\s*var\(--st-fs-sm\)/); + assert.ok(chat, 'app.css still sets the chat title; liquid.css raises it to --st-fs-md for chat and screens together'); +}); + +test('the Tasks header has no subtitle under it', () => { + const tasks = read('src/screens/Tasks.tsx'); + assert.ok(!/Everything that is running, waiting for you/.test(tasks)); + assert.ok(!/<Screen[^\n]*\bsub=/.test(tasks)); +}); From 63ae1eb3cdd32efbee4f4ef2f7cefacf26fcfc0b Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:38:13 +0100 Subject: [PATCH 04/59] Settings: Privacy is one compact paragraph --- apps/host/src/components/PrivacyNotes.tsx | 13 +++-------- apps/host/src/styles/app.css | 4 ++-- apps/host/tests/privacy-paragraph.test.mjs | 25 ++++++++++++++++++++++ 3 files changed, 30 insertions(+), 12 deletions(-) create mode 100644 apps/host/tests/privacy-paragraph.test.mjs diff --git a/apps/host/src/components/PrivacyNotes.tsx b/apps/host/src/components/PrivacyNotes.tsx index 599cd35c42..936970dbcd 100644 --- a/apps/host/src/components/PrivacyNotes.tsx +++ b/apps/host/src/components/PrivacyNotes.tsx @@ -1,17 +1,10 @@ import { tr } from '../lib/i18n'; -const NOTES = [ - 'Strata sends no usage telemetry.', - 'Conversations stay in browser storage.', - 'When you choose an API model, that conversation and enabled skill instructions are sent to its provider.', - 'The UI request log keeps client, timing and token metadata in memory.', - 'Native API monitoring can retain request content in memory when enabled.', - 'Connected tools access the resources you configure.', -]; +/** What Strata collects and where things go: one compact paragraph (the six sentences read together, translated as one in every language). */ +const NOTES = 'Strata sends no usage telemetry. Conversations stay in browser storage. When you choose an API model, that conversation and enabled skill instructions are sent to its provider. The UI request log keeps client, timing and token metadata in memory. Native API monitoring can retain request content in memory when enabled. Connected tools access the resources you configure.'; -/** What Strata collects and where things go: plain lines of text, nothing else. */ export function PrivacyNotes() { return <div className="privacy-notes" aria-label={tr("Collection and logs")}> - {NOTES.map(text => <p key={text}>{tr(text)}</p>)} + <p>{tr(NOTES)}</p> </div>; } diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index 05eba544d3..e92cc29e41 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7253,8 +7253,8 @@ textarea { .storage-model__size { font-variant-numeric: tabular-nums; font-size: var(--st-fs-sm); } /* ---- About > Privacy: plain text ---- */ -.privacy-notes { display: flex; flex-direction: column; gap: 8px; padding: 2px 0; } -.privacy-notes p { margin: 0; font-size: var(--st-fs-sm); line-height: 1.5; color: var(--st-ink-soft); } +.privacy-notes { padding: 2px 0; } +.privacy-notes p { margin: 0; max-width: 68ch; font-size: var(--st-fs-sm); line-height: 1.6; color: var(--st-ink-soft); } /* ---- an opened task: the name, and a last answer that is easy to read ---- */ .task-name { margin: 0 0 2px; font-size: var(--st-fs-xl); letter-spacing: -.02em; } diff --git a/apps/host/tests/privacy-paragraph.test.mjs b/apps/host/tests/privacy-paragraph.test.mjs new file mode 100644 index 0000000000..0cc3153b7b --- /dev/null +++ b/apps/host/tests/privacy-paragraph.test.mjs @@ -0,0 +1,25 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {resolve} from 'node:path'; + +const root = resolve(import.meta.dirname, '..'); +const source = readFileSync(resolve(root, 'src/components/PrivacyNotes.tsx'), 'utf8'); +const SENTENCES = ['Strata sends no usage telemetry.', 'Conversations stay in browser storage.', 'When you choose an API model, that conversation and enabled skill instructions are sent to its provider.', 'The UI request log keeps client, timing and token metadata in memory.', 'Native API monitoring can retain request content in memory when enabled.', 'Connected tools access the resources you configure.']; + +test('Privacy is one compact paragraph with all six sentences, in order', () => { + const text = source.match(/const NOTES = '([^']*)';/)?.[1]; + assert.equal(text, SENTENCES.join(' ')); + assert.equal((source.match(/<p>/g) ?? []).length, 1, 'one paragraph, not a line per sentence'); +}); + +test('the paragraph is translated as a whole in all 9 languages', () => { + const joined = SENTENCES.join(' '); + const en = JSON.parse(readFileSync(resolve(root, 'src/locales/en.json'), 'utf8')); + const id = Object.keys(en).find(k => en[k] === joined); + assert.ok(id, 'the English catalog has the whole paragraph'); + for (const lang of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) { + const cat = JSON.parse(readFileSync(resolve(root, `src/locales/${lang}.json`), 'utf8')); + assert.ok(cat[id] && cat[id] !== joined && cat[id].length > 80, `${lang} has its own translation of the paragraph`); + } +}); From b3dbb2c67c314f1847c59cace8299434c7d2b85c Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:41:06 +0100 Subject: [PATCH 05/59] Light mode New chat: the shared primary look, green text on the tint (5.48:1) --- apps/host/src/styles/liquid.css | 31 ++++++++++++++---------- apps/host/tests/new-chat-button.test.mjs | 23 ++++++++++++++++++ 2 files changed, 41 insertions(+), 13 deletions(-) create mode 100644 apps/host/tests/new-chat-button.test.mjs diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index 6037deca9d..33100520b6 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -362,20 +362,26 @@ body { "New chat" is the one action on every screen, so it has to read as a control without becoming the brightest object in the window. - Light mode keeps the accent at full strength with the dark accent ink, which - is the pairing the accent-ink correction documented (6.37:1): over a #f9fafb - page a full #10b981 fill is only 2.5:1 from its background, so it reads as a - confident control rather than glare, and the near-black label carries the - legibility. Dark mode takes the tinted accent material instead, because a - large saturated fill on a near-black page is the one thing that actually - glares (9.86:1 against the page; see interaction-guidelines §12). + Light mode used to give it the full #10b981 fill with the near-black accent + ink. The owner asked for white or green text instead, and white on #10b981 is + 2.54:1 (it failed `npm run contrast`, passes 1 and 7 of the pass log). White + needs a deeper green behind it, but every other primary in light mode is the + tinted accent surface with deep-green text (New skill, Run now, Connect an + app...), so a deep solid button would be the one object in the app that + looked different. It takes the same tinted surface and green text as they do: + #086a4a on the 20% tint is 5.47:1, and the hover and edge come from the same + tokens, so there is one primary button, not two. + + Dark mode takes the tinted accent material below, because a large saturated + fill on a near-black page is the one thing that actually glares (9.86:1 + against the page; see interaction-guidelines §12). Both carry the specular top edge, so the control is lit the same way as every other surface in the shell. */ .nav-new.st-btn--primary { - background: var(--st-accent); - border: 1px solid color-mix(in srgb, var(--st-accent) 70%, var(--st-accent-ink)); - color: var(--st-accent-ink); + background: var(--st-accent-surface); + border: 1px solid var(--st-accent-surface-edge); + color: var(--st-accent-surface-ink); box-shadow: inset 0 1px 0 var(--st-specular), var(--st-sh-card); @@ -384,11 +390,10 @@ body { box-shadow var(--st-t-control) var(--st-ease-standard); } .nav-new.st-btn--primary:hover:not(:disabled) { - background: var(--st-accent-hover); - border-color: color-mix(in srgb, var(--st-accent-hover) 70%, var(--st-accent-ink)); + background: var(--st-accent-surface-hover); } .nav-new.st-btn--primary:active:not(:disabled) { - background: color-mix(in srgb, var(--st-accent) 88%, var(--st-accent-ink)); + background: color-mix(in srgb, var(--st-accent) 36%, var(--st-surface)); } [data-theme='dark'] .nav-new.st-btn--primary { background: color-mix(in srgb, var(--st-accent) 22%, var(--st-surface)); diff --git a/apps/host/tests/new-chat-button.test.mjs b/apps/host/tests/new-chat-button.test.mjs new file mode 100644 index 0000000000..cbea0ea49e --- /dev/null +++ b/apps/host/tests/new-chat-button.test.mjs @@ -0,0 +1,23 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {resolve} from 'node:path'; + +const liquid = readFileSync(resolve(import.meta.dirname, '..', 'src/styles/liquid.css'), 'utf8'); +const rule = (selector) => { + const start = liquid.indexOf(`${selector} {`); + assert.ok(start >= 0, `${selector} exists`); + return liquid.slice(start, liquid.indexOf('}', start)); +}; + +test('light New chat is the shared primary: tinted surface, green text, no near-black ink', () => { + const light = rule('.nav-new.st-btn--primary'); + assert.match(light, /background:\s*var\(--st-accent-surface\)/); + assert.match(light, /color:\s*var\(--st-accent-surface-ink\)/); + assert.ok(!/--st-accent-ink/.test(light), 'not the dark ink on a saturated fill'); + assert.ok(!/background:\s*var\(--st-accent\)\s*;/.test(light), 'no full-strength #10b981 fill'); +}); + +test('its hover also uses the shared primary token', () => { + assert.match(rule('.nav-new.st-btn--primary:hover:not(:disabled)'), /var\(--st-accent-surface-hover\)/); +}); From 6f686536e5a09b9a60745b766ec312a8bb8262ac Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:50:14 +0100 Subject: [PATCH 06/59] Model versions list: each version once, plain names, small tags, details behind a toggle --- apps/host/scripts/make-pick-locales.py | 51 ++++++++++ apps/host/src/components/NativeModels.tsx | 2 +- apps/host/src/components/VersionPicker.tsx | 110 +++++++++++++-------- apps/host/src/lib/i18n.ts | 14 ++- apps/host/src/lib/native-fit.ts | 12 +++ apps/host/src/locales/pick-de.json | 9 ++ apps/host/src/locales/pick-en.json | 9 ++ apps/host/src/locales/pick-es.json | 9 ++ apps/host/src/locales/pick-fr.json | 9 ++ apps/host/src/locales/pick-ja.json | 9 ++ apps/host/src/locales/pick-ko.json | 9 ++ apps/host/src/locales/pick-pt.json | 9 ++ apps/host/src/locales/pick-ru.json | 9 ++ apps/host/src/locales/pick-zh.json | 9 ++ apps/host/src/styles/app.css | 46 +++++---- apps/host/tests/deepseek-card.test.mjs | 5 +- apps/host/tests/locale-gaps.test.mjs | 2 +- apps/host/tests/version-picker.test.mjs | 50 ++++++++++ 18 files changed, 304 insertions(+), 69 deletions(-) create mode 100644 apps/host/scripts/make-pick-locales.py create mode 100644 apps/host/src/locales/pick-de.json create mode 100644 apps/host/src/locales/pick-en.json create mode 100644 apps/host/src/locales/pick-es.json create mode 100644 apps/host/src/locales/pick-fr.json create mode 100644 apps/host/src/locales/pick-ja.json create mode 100644 apps/host/src/locales/pick-ko.json create mode 100644 apps/host/src/locales/pick-pt.json create mode 100644 apps/host/src/locales/pick-ru.json create mode 100644 apps/host/src/locales/pick-zh.json create mode 100644 apps/host/tests/version-picker.test.mjs diff --git a/apps/host/scripts/make-pick-locales.py b/apps/host/scripts/make-pick-locales.py new file mode 100644 index 0000000000..334b17d06d --- /dev/null +++ b/apps/host/scripts/make-pick-locales.py @@ -0,0 +1,51 @@ +"""Writes src/locales/pick-<lang>.json: the strings of the model version list (VersionPicker, branch f-0291-ui-fixes2). +Run from apps/host: python scripts/make-pick-locales.py +Every entry names all nine languages; the keys are vp01.. in the order of S. pick-en.json is the English source. Placeholders ({0}, {1}) must be kept +in every language. A separate file keeps this work from colliding with the other catalogs (the same reason tune-, tools-, fix-, gh-, ui- and engine- exist).""" +import json +import re +from pathlib import Path + +LANGS = ["en", "zh", "ja", "de", "es", "ru", "pt", "ko", "fr"] +S = [] + + +def add(en, zh, ja, de, es, ru, pt, ko, fr): + S.append(dict(en=en, zh=zh, ja=ja, de=de, es=es, ru=ru, pt=pt, ko=ko, fr=fr)) + + +add("{0} download", + "下载 {0}", "ダウンロード {0}", "{0} Download", "Descarga de {0}", "Загрузка {0}", "Download de {0}", "다운로드 {0}", "Téléchargement de {0}") +add("Needs {0} of memory", + "需要 {0} 内存", "{0} のメモリーが必要", "Braucht {0} Speicher", "Necesita {0} de memoria", "Нужно {0} памяти", "Precisa de {0} de memória", "메모리 {0} 필요", "Nécessite {0} de mémoire") +add("Needs {0} of memory and about {1} GB of disk", + "需要 {0} 内存和约 {1} GB 磁盘空间", "{0} のメモリーと約 {1} GB のディスク容量が必要", "Braucht {0} Speicher und etwa {1} GB Festplattenplatz", "Necesita {0} de memoria y unos {1} GB de disco", + "Нужно {0} памяти и около {1} ГБ на диске", "Precisa de {0} de memória e cerca de {1} GB de disco", "메모리 {0}와 디스크 약 {1} GB 필요", "Nécessite {0} de mémoire et environ {1} Go de disque") +add("Slower on this computer", + "在这台电脑上较慢", "このコンピューターでは遅くなります", "Auf diesem Computer langsamer", "Más lento en este equipo", "На этом компьютере медленнее", "Mais lento neste computador", "이 컴퓨터에서는 더 느립니다", "Plus lent sur cet ordinateur") +add("Show details", + "显示详情", "詳細を表示", "Details anzeigen", "Mostrar detalles", "Показать подробности", "Mostrar detalhes", "자세히 보기", "Afficher les détails") +add("Hide details", + "隐藏详情", "詳細を隠す", "Details ausblenden", "Ocultar detalles", "Скрыть подробности", "Ocultar detalhes", "자세히 숨기기", "Masquer les détails") +add("{0} RAM + VRAM", + "{0} 内存 + 显存", "{0} の RAM + VRAM", "{0} RAM + VRAM", "{0} de RAM + VRAM", "{0} RAM + VRAM", "{0} de RAM + VRAM", "RAM + VRAM {0}", "{0} de RAM + VRAM") + +here = Path(__file__).resolve().parent.parent / "src" / "locales" +NBSP = " " + + +def french(text): + text = re.sub(r"(?<=[A-Za-zÀ-ſ])'(?=[A-Za-zÀ-ſ{])", "’", text) + text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text) + text = re.sub(r"(?<=[\d}]) %", NBSP + "%", text) + return text + + +for lang in LANGS: + data = {} + for i, entry in enumerate(S): + text = entry[lang] + assert sorted(re.findall(r"\{\d+\}", entry["en"])) == sorted(re.findall(r"\{\d+\}", text)), (lang, entry["en"], text) + data[f"vp{i + 1:02d}"] = french(text) if lang == "fr" else text + (here / f"pick-{lang}.json").write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") +print("written", len(S), "strings in", len(LANGS), "languages") diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 06eae3a190..b0037c4b93 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(selectedSize ? <> <div className="native-choice__head"><span className="native-choice__label">{tr("Version")}</span><span className="native-choice__tools"><NativePresets values={values} onApply={v => { const f = families.find(f => f.family === v.family || f.sizes.some(s => s.sourceFamily === v.family)); if (!f) return; presetPending.current = true; setFamily(f.family); setSize(f.sizes.find(s => s.model === v.model && (s.sourceFamily === v.family || f.family === v.family))?.id ?? ''); setContext(v.context ?? 32768); setVision(v.vision ?? 'no'); setKv(v.kv ?? 'int8'); setLowRam(v.low_ram ?? 'auto'); }}/><Btn icon="models" size="sm" variant="ghost" onClick={() => setManage(true)}>{tr("Manage models")}</Btn></span></div> - <div className="native-version"><VersionPicker pick={native?.catalog?.recommendation} versions={allSizes} selectedId={selectedSize.id} hardware={fitHardware} downloaded={readyIds} onSelect={id => { const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/></div> + <div className="native-version"><VersionPicker pick={native?.catalog?.recommendation} versions={allSizes} models={families} details={expert} selectedId={selectedSize.id} hardware={fitHardware} downloaded={readyIds} onSelect={id => { const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/></div> {tr(noFit ? <p className="small muted native-spill-note"><Icon name="disk" size={16}/>{tr("May run slower \u00B7 Model data can be read from SSD.")}</p> : null)} {tr(selectedSize?.multi_file && deepseekContextNote(context) ? <p className="small muted native-spill-note"><Icon name="info" size={16}/>{tr(deepseekContextNote(context))}</p> : null)} <div className="native-choice__row"> diff --git a/apps/host/src/components/VersionPicker.tsx b/apps/host/src/components/VersionPicker.tsx index 5a078316b7..b5f5a864bc 100644 --- a/apps/host/src/components/VersionPicker.tsx +++ b/apps/host/src/components/VersionPicker.tsx @@ -1,87 +1,111 @@ -import { useRef, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { tr } from '../lib/i18n'; import { Icon } from './ui'; import { FloatingMenu } from './FloatingMenu'; import { cx } from '../lib/format'; -import { versionNote, type CatalogVersion } from '../lib/native-catalog'; +import { nativeVersionLabel, versionNote, type CatalogVersion } from '../lib/native-catalog'; import { nvfp4Version } from '../lib/native-names'; -import { VERSION_GROUPS, fitOn, groupOpen, recommendedVersions, type FitHardware, type PcPick } from '../lib/native-fit'; +import { fitOn, recommendedVersions, versionSections, PICK_NOTE, type FitHardware, type PcPick } from '../lib/native-fit'; -/** The name a version goes by in the list: the quantization, with the maker where the quantization alone is ambiguous. */ -export function versionName(v: CatalogVersion, withMaker = false): string { +/** The name a version goes by in the list: the quantization, with the maker only where the quantization alone would be ambiguous. */ +export function versionName(v: CatalogVersion): string { switch (v.sourceFamily) { case 'swift': return `Swift ${v.model}`; case 'unsloth': return `Unsloth ${v.model}`; case 'nvfp4': return tr(nvfp4Version(v.model)?.name ?? v.model); case 'coder': return `Coder ${v.model}`; - case 'qwen': return withMaker ? `${v.model} (GSQ-RCO)` : v.model; default: return v.model; } } +/** Who made a version (Details only): the family name of the quantization, a proper name in every language. */ +const MAKERS: Record<string, string> = { qwen: 'GSQ-RCO', coder: 'GSQ-RCO', swift: 'Swift', unsloth: 'Unsloth', gyro: 'Gyro', nvfp4: 'NVFP4' }; + const gb = (n: number) => `${Number.isInteger(n) ? n : n.toFixed(1)} GB`; +const whole = (n: number) => `${Math.round(n)} GB`; + +/** A short plain word for the version ("High quality"), empty where the name is all there is. */ +function plainLabel(v: CatalogVersion): string { + const label = nativeVersionLabel(v.model); + return label && label !== v.model && label !== versionName(v) ? label : ''; +} /** - * The version list of the Models screen: one line per model. The bold figure is the RAM + VRAM it needs together (the n-gram table, - * which stays on the SSD, is not in it); the download size is secondary. "Uses SSD N GB" appears only where this computer would read - * part of the model from its SSD. The first group is a fixed list of four; the rest fold away. + * Where the versions are listed: one row per version, each exactly once. The name is the main thing, with a plain word beside it + * ("High quality") and small tags (Recommended, Downloaded); under it, what it costs: the download and the memory it needs. The maker, + * the RAM + VRAM split and the SSD figure are behind "Show details" (open from the start in Expert mode). Rows are in order of size + * inside each model (by download size), and the pick for this PC comes first. With more than one model the sections carry the model name, small and quiet. */ -export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnGguf, downloaded, showRecommended = true, moreLabel, pick }: { +export function VersionPicker({ versions, models, selectedId, hardware, onSelect, onOwnGguf, downloaded, showRecommended = true, moreLabel, pick, details: detailsOpen = false }: { versions: CatalogVersion[]; + /** The models the versions belong to, in the order shown (each version appears under exactly one); without it the versions are one list. */ + models?: { family: string; title: string; sizes: CatalogVersion[] }[]; selectedId: string; hardware: FitHardware | null | undefined; onSelect: (id: string) => void; onOwnGguf: () => void; /** The versions already on this computer (ready to load): each gets a small "Downloaded" tag. */ downloaded?: ReadonlySet<string>; - /** False where the recommended four are shown elsewhere (the first-run page): the menu then holds only the groups. */ + /** False where the recommended ones are shown elsewhere (the first-run page): the menu then holds only the others. */ showRecommended?: boolean; - /** What the button says while the selected version is one of the recommended four shown elsewhere. */ + /** What the button says while the selected version is one of the recommended ones shown elsewhere. */ moreLabel?: string; - /** The engine's own pick for this PC (catalog.recommendation); it comes first in the Recommended group. */ + /** The engine's own pick for this PC (catalog.recommendation); it comes first, tagged Recommended. */ pick?: PcPick | null; + /** Start with the technical detail shown (Expert mode). */ + details?: boolean; }) { const trigger = useRef<HTMLButtonElement>(null); const [open, setOpen] = useState(false); - // A group is open when the person opened it; until they touch it, only the group that holds the selected version is open. - const [opened, setOpened] = useState<Record<string, boolean>>({}); + const [details, setDetails] = useState(detailsOpen); + useEffect(() => setDetails(detailsOpen), [detailsOpen]); const selected = versions.find(v => v.id === selectedId); - const recommended = recommendedVersions(versions, pick); - // Where the recommended four are shown outside the menu, the menu holds only the others. - const apart = new Set(showRecommended ? [] : recommended.map(x => x.v.id)); - const rest = versions.filter(v => !apart.has(v.id)); - const groups = [ - ...VERSION_GROUPS.map(g => ({ id: g.id, title: g.title, items: rest.filter(v => g.families.includes(v.sourceFamily)) })), - { id: 'other', title: 'Qwen3.6 models', items: rest.filter(v => !VERSION_GROUPS.some(g => g.families.includes(v.sourceFamily))) }, - ].filter(g => g.items.length); - const row = (v: CatalogVersion, label: string, note?: string) => { + // Where the recommended ones are shown outside the menu, the menu holds only the others. + const rows = recommendedVersions(versions, pick); + const apart = new Set(showRecommended ? [] : rows.map(x => x.v.id)); + const pickId = rows.find(x => x.r.note === PICK_NOTE)?.v.id; + const sections = versionSections(versions, models, apart, pickId); + const shown = selected && !apart.has(selected.id) ? selected : undefined; + + const need = (v: CatalogVersion, technical: boolean) => { + const fit = fitOn(v, hardware); + if (technical) return v.multi_file && v.disk_gb ? tr("{0} RAM + VRAM, plus about {1} GB of disk", [gb(fit.memoryGb), Math.round(v.disk_gb)]) : tr("{0} RAM + VRAM", [gb(fit.memoryGb)]); + return v.multi_file && v.disk_gb ? tr("Needs {0} of memory and about {1} GB of disk", [whole(fit.memoryGb), Math.round(v.disk_gb)]) : tr("Needs {0} of memory", [whole(fit.memoryGb)]); + }; + const row = (v: CatalogVersion) => { const fit = fitOn(v, hardware); const on = v.id === selectedId; - const line = versionNote(v.model); - return <button key={`${label}-${v.id}`} role="menuitemradio" aria-checked={on} className={cx('version-row', on && 'is-on')} onClick={() => { onSelect(v.id); setOpen(false); }}> - <span className="version-row__name"><span className="version-row__title">{tr(on ? <Icon name="check" size={14}/> : null)}<strong>{label}</strong>{tr(note ? <span className="muted"> · {tr(note)}</span> : null)}{tr(downloaded?.has(v.id) ? <span className="version-row__have">{tr("Downloaded")}</span> : null)}{tr(fit.known && fit.spillGb >= 1 ? <span className="version-row__ssd">{tr("Uses SSD {0} GB", [Math.round(fit.spillGb)])}</span> : null)}</span>{tr(line ? <small className="version-row__note muted">{line}</small> : null)}</span> - <span className="version-row__ram">{gb(fit.memoryGb)}</span> - <span className="version-row__dl">{gb(v.download_gb)}</span> + const word = plainLabel(v), note = versionNote(v.model); + const slow = fit.known && fit.spillGb >= 1; + const technical = [MAKERS[v.sourceFamily], need(v, true), slow ? tr("Uses SSD {0} GB", [Math.round(fit.spillGb)]) : ''].filter(Boolean).join(' · '); + return <button key={v.id} role="menuitemradio" aria-checked={on} className={cx('version-row', on && 'is-on')} onClick={() => { onSelect(v.id); setOpen(false); }}> + <span className="version-row__check">{tr(on ? <Icon name="check" size={14}/> : null)}</span> + <span className="version-row__body"> + <span className="version-row__title"><strong>{versionName(v)}</strong>{tr(word ? <span className="version-row__word">{word}</span> : null)}{tr(v.id === pickId ? <span className="version-tag version-tag--pick">{tr("Recommended")}</span> : null)}{tr(downloaded?.has(v.id) ? <span className="version-tag version-tag--have">{tr("Downloaded")}</span> : null)}{tr(slow ? <span className="version-row__slow">{tr("Slower on this computer")}</span> : null)}</span> + {tr(details ? <span className="version-row__tech">{technical}{tr(note ? <><br/>{note}</> : null)}</span> : null)} + </span> + <span className="version-row__size">{tr("{0} download", [gb(v.download_gb)])}</span> </button>; }; - const fit = selected && !apart.has(selected.id) ? fitOn(selected, hardware) : null; + // The open menu opens on the chosen version, not at the top of a long list. + const menu = useRef<HTMLDivElement>(null); + useEffect(() => { if (open) menu.current?.querySelector('.is-on')?.scrollIntoView({ block: 'nearest' }); }, [open]); return <> <button ref={trigger} type="button" className="version-trigger" aria-haspopup="menu" aria-expanded={open} aria-label={tr("Model version")} onClick={() => setOpen(v => !v)}> - <strong>{selected && !apart.has(selected.id) ? versionName(selected, true) : tr(moreLabel ?? "Choose a version")}</strong>{tr(selected && !apart.has(selected.id) && downloaded?.has(selected.id) ? <span className="version-row__have">{tr("Downloaded")}</span> : null)} - <span className="version-trigger__need muted">{tr(fit && selected?.multi_file && selected.disk_gb ? tr("{0} RAM + VRAM, plus about {1} GB of disk", [gb(fit.memoryGb), Math.round(selected.disk_gb)]) : fit ? `${gb(fit.memoryGb)} RAM + VRAM` : '')}</span> + <strong>{shown ? versionName(shown) : tr(moreLabel ?? "Choose a version")}</strong>{tr(shown && downloaded?.has(shown.id) ? <span className="version-tag version-tag--have">{tr("Downloaded")}</span> : null)} + <span className="version-trigger__need muted">{tr(shown ? need(shown, details) : '')}</span> <Icon name="chevron" size={14} className="version-trigger__chev"/> </button> - {tr(open ? <FloatingMenu anchor={trigger.current} title={tr("Model version")} width={620} onClose={() => setOpen(false)}> - <div className="version-menu"> - {tr(showRecommended ? <><div className="version-head"><span>{tr("Recommended")}</span><span>{tr("RAM + VRAM")}</span><span>{tr("Download")}</span></div>{tr(recommended.map(({ r, v }) => row(v, versionName(v, true), r.note)))}</> : <div className="version-head"><span>{tr("All other versions")}</span><span>{tr("RAM + VRAM")}</span><span>{tr("Download")}</span></div>)} - {tr(groups.map(g => { - const closed = !groupOpen(opened, g.id, g.items.some(v => v.id === selectedId)); - return <div className="version-group" key={g.id} data-open={!closed || undefined}> - <button role="menuitem" className="version-group__head" aria-expanded={!closed} onClick={() => setOpened(o => ({ ...o, [g.id]: closed }))}><span>{tr(g.title)} <span className="muted">{tr(g.items.length)}</span></span><Icon name="chevron" size={14} className={cx(!closed && 'is-open')}/></button> - {tr(!closed ? g.items.map(v => row(v, versionName(v))) : null)} - </div>; - }))} - <button role="menuitem" className="version-group__head version-own" onClick={() => { setOpen(false); onOwnGguf(); }}><span>{tr("Use your own GGUF…")}</span><Icon name="folder" size={14}/></button> + {tr(open ? <FloatingMenu anchor={trigger.current} title={tr("Model version")} width={480} onClose={() => setOpen(false)}> + <div className="version-menu" ref={menu}> + {tr(sections.map(s => <div className="version-section" role="group" aria-label={s.title || tr("Model version")} key={s.id}> + {tr(s.title ? <div className="version-section__title" aria-hidden="true">{s.title}</div> : null)} + {tr(s.versions.map(row))} + </div>))} + <div className="version-foot"> + <button role="menuitem" className="version-foot__btn" onClick={() => { setOpen(false); onOwnGguf(); }}><Icon name="folder" size={14}/>{tr("Use your own GGUF…")}</button> + <button role="menuitem" className="version-foot__btn" aria-pressed={details} onClick={() => setDetails(d => !d)}>{tr(details ? "Hide details" : "Show details")}</button> + </div> </div> </FloatingMenu> : null)} </>; diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index 6d13c63919..814a6d7ba8 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -56,6 +56,16 @@ import engine_ru from '../locales/engine-ru.json'; import engine_pt from '../locales/engine-pt.json'; import engine_ko from '../locales/engine-ko.json'; import engine_fr from '../locales/engine-fr.json'; +/* The strings of the model version list (pick-<lang>.json, scripts/make-pick-locales.py). */ +import pick_en from '../locales/pick-en.json'; +import pick_zh from '../locales/pick-zh.json'; +import pick_ja from '../locales/pick-ja.json'; +import pick_de from '../locales/pick-de.json'; +import pick_es from '../locales/pick-es.json'; +import pick_ru from '../locales/pick-ru.json'; +import pick_pt from '../locales/pick-pt.json'; +import pick_ko from '../locales/pick-ko.json'; +import pick_fr from '../locales/pick-fr.json'; import base_zh from '../locales/zh.json'; import base_ja from '../locales/ja.json'; import base_de from '../locales/de.json'; @@ -70,8 +80,8 @@ export type Language=typeof LANGUAGES[number]['value']; /* The Tune model dialog's strings live in tune-<lang>.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ /* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-<lang>.json for the same reason. */ /* The strings that had no key in the files above (#3479, #3825) and the 0.2.4.3 fixes live in fix-<lang>.json (scripts/make-fix-locales.py). */ -const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en}; -const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh,...ui_zh,...engine_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja,...ui_ja,...engine_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de,...ui_de,...engine_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es,...ui_es,...engine_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru,...ui_ru,...engine_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt,...ui_pt,...engine_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko,...ui_ko,...engine_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr,...gh_fr,...ui_fr,...engine_fr}] as Record<string,string>[]; +const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en,...pick_en}; +const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh,...ui_zh,...engine_zh,...pick_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja,...ui_ja,...engine_ja,...pick_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de,...ui_de,...engine_de,...pick_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es,...ui_es,...engine_es,...pick_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru,...ui_ru,...engine_ru,...pick_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt,...ui_pt,...engine_pt,...pick_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko,...ui_ko,...engine_ko,...pick_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr,...gh_fr,...ui_fr,...engine_fr,...pick_fr}] as Record<string,string>[]; const catalogs:Record<Language,Record<string,string>>={en:english,zh,ja,de,fr,es,ru,pt,ko}; const entities:Record<string,string>={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'}; const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole); diff --git a/apps/host/src/lib/native-fit.ts b/apps/host/src/lib/native-fit.ts index fad8c036a1..fd98e365f5 100644 --- a/apps/host/src/lib/native-fit.ts +++ b/apps/host/src/lib/native-fit.ts @@ -101,6 +101,18 @@ export function recommendedVersions<V extends { sourceFamily: string; model: str return [...out, ...rest.filter(x => x.v !== gyroM)]; } +/** + * The version list as the menu shows it: one section per model (a single unnamed one without `models`), each version exactly once, in order of + * download size with the pick for this PC first; the versions in `hidden` (shown elsewhere) are left out. A model with nothing to show has no section. + */ +export function versionSections<V extends { id: string; download_gb: number }>(versions: V[], models: { family: string; title: string; sizes: V[] }[] | undefined, hidden: ReadonlySet<string>, pickId?: string): { id: string; title: string; versions: V[] }[] { + const rank = (v: V) => v.id === pickId ? -1 : v.download_gb; + const seen = new Set<string>(); + return (models ?? [{ family: 'all', title: '', sizes: versions }]) + .map(m => ({ id: m.family, title: models && models.length > 1 ? m.title : '', versions: m.sizes.filter(v => !hidden.has(v.id) && !seen.has(v.id) && !!seen.add(v.id)).map((v, at) => ({ v, at })).sort((a, b) => rank(a.v) - rank(b.v) || a.at - b.at).map(x => x.v) })) + .filter(s => s.versions.length); +} + /** A card as the installer's hardware report lists it. */ export interface RunCard { index: number; name: string; vram_gb: number; usable?: boolean; vendor?: string; uma?: boolean; integrated?: boolean; unified_gb?: number } diff --git a/apps/host/src/locales/pick-de.json b/apps/host/src/locales/pick-de.json new file mode 100644 index 0000000000..c427957a61 --- /dev/null +++ b/apps/host/src/locales/pick-de.json @@ -0,0 +1,9 @@ +{ + "vp01": "{0} Download", + "vp02": "Braucht {0} Speicher", + "vp03": "Braucht {0} Speicher und etwa {1} GB Festplattenplatz", + "vp04": "Auf diesem Computer langsamer", + "vp05": "Details anzeigen", + "vp06": "Details ausblenden", + "vp07": "{0} RAM + VRAM" +} diff --git a/apps/host/src/locales/pick-en.json b/apps/host/src/locales/pick-en.json new file mode 100644 index 0000000000..f12998faa3 --- /dev/null +++ b/apps/host/src/locales/pick-en.json @@ -0,0 +1,9 @@ +{ + "vp01": "{0} download", + "vp02": "Needs {0} of memory", + "vp03": "Needs {0} of memory and about {1} GB of disk", + "vp04": "Slower on this computer", + "vp05": "Show details", + "vp06": "Hide details", + "vp07": "{0} RAM + VRAM" +} diff --git a/apps/host/src/locales/pick-es.json b/apps/host/src/locales/pick-es.json new file mode 100644 index 0000000000..221c2090d6 --- /dev/null +++ b/apps/host/src/locales/pick-es.json @@ -0,0 +1,9 @@ +{ + "vp01": "Descarga de {0}", + "vp02": "Necesita {0} de memoria", + "vp03": "Necesita {0} de memoria y unos {1} GB de disco", + "vp04": "Más lento en este equipo", + "vp05": "Mostrar detalles", + "vp06": "Ocultar detalles", + "vp07": "{0} de RAM + VRAM" +} diff --git a/apps/host/src/locales/pick-fr.json b/apps/host/src/locales/pick-fr.json new file mode 100644 index 0000000000..17519c323c --- /dev/null +++ b/apps/host/src/locales/pick-fr.json @@ -0,0 +1,9 @@ +{ + "vp01": "Téléchargement de {0}", + "vp02": "Nécessite {0} de mémoire", + "vp03": "Nécessite {0} de mémoire et environ {1} Go de disque", + "vp04": "Plus lent sur cet ordinateur", + "vp05": "Afficher les détails", + "vp06": "Masquer les détails", + "vp07": "{0} de RAM + VRAM" +} diff --git a/apps/host/src/locales/pick-ja.json b/apps/host/src/locales/pick-ja.json new file mode 100644 index 0000000000..8bb77ecb5c --- /dev/null +++ b/apps/host/src/locales/pick-ja.json @@ -0,0 +1,9 @@ +{ + "vp01": "ダウンロード {0}", + "vp02": "{0} のメモリーが必要", + "vp03": "{0} のメモリーと約 {1} GB のディスク容量が必要", + "vp04": "このコンピューターでは遅くなります", + "vp05": "詳細を表示", + "vp06": "詳細を隠す", + "vp07": "{0} の RAM + VRAM" +} diff --git a/apps/host/src/locales/pick-ko.json b/apps/host/src/locales/pick-ko.json new file mode 100644 index 0000000000..2cc5344c64 --- /dev/null +++ b/apps/host/src/locales/pick-ko.json @@ -0,0 +1,9 @@ +{ + "vp01": "다운로드 {0}", + "vp02": "메모리 {0} 필요", + "vp03": "메모리 {0}와 디스크 약 {1} GB 필요", + "vp04": "이 컴퓨터에서는 더 느립니다", + "vp05": "자세히 보기", + "vp06": "자세히 숨기기", + "vp07": "RAM + VRAM {0}" +} diff --git a/apps/host/src/locales/pick-pt.json b/apps/host/src/locales/pick-pt.json new file mode 100644 index 0000000000..b09664ae8f --- /dev/null +++ b/apps/host/src/locales/pick-pt.json @@ -0,0 +1,9 @@ +{ + "vp01": "Download de {0}", + "vp02": "Precisa de {0} de memória", + "vp03": "Precisa de {0} de memória e cerca de {1} GB de disco", + "vp04": "Mais lento neste computador", + "vp05": "Mostrar detalhes", + "vp06": "Ocultar detalhes", + "vp07": "{0} de RAM + VRAM" +} diff --git a/apps/host/src/locales/pick-ru.json b/apps/host/src/locales/pick-ru.json new file mode 100644 index 0000000000..d0332ddfbb --- /dev/null +++ b/apps/host/src/locales/pick-ru.json @@ -0,0 +1,9 @@ +{ + "vp01": "Загрузка {0}", + "vp02": "Нужно {0} памяти", + "vp03": "Нужно {0} памяти и около {1} ГБ на диске", + "vp04": "На этом компьютере медленнее", + "vp05": "Показать подробности", + "vp06": "Скрыть подробности", + "vp07": "{0} RAM + VRAM" +} diff --git a/apps/host/src/locales/pick-zh.json b/apps/host/src/locales/pick-zh.json new file mode 100644 index 0000000000..aa8597a505 --- /dev/null +++ b/apps/host/src/locales/pick-zh.json @@ -0,0 +1,9 @@ +{ + "vp01": "下载 {0}", + "vp02": "需要 {0} 内存", + "vp03": "需要 {0} 内存和约 {1} GB 磁盘空间", + "vp04": "在这台电脑上较慢", + "vp05": "显示详情", + "vp06": "隐藏详情", + "vp07": "{0} 内存 + 显存" +} diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index e92cc29e41..3cf9c673cc 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7026,28 +7026,34 @@ textarea { /* ---- Models: the version list and "This computer" ---- */ .version-trigger { display: flex; align-items: center; gap: 10px; width: 100%; min-height: 44px; padding: 0 14px; border: 1.5px solid var(--st-line); border-radius: var(--st-r-md); background: var(--st-surface); color: var(--st-ink); font: inherit; cursor: pointer; text-align: left; } -.version-trigger__need { margin-left: auto; font-size: var(--st-fs-sm); white-space: nowrap; } +.version-trigger__need { margin-left: auto; font-size: var(--st-fs-sm); text-align: right; } +@media (max-width: 560px) { + .version-trigger { flex-wrap: wrap; padding-block: 10px; row-gap: 2px; } + .version-trigger__need { order: 3; flex-basis: 100%; margin-left: 0; text-align: left; } + .version-trigger .version-trigger__chev { order: 2; margin-left: auto; } +} .version-trigger svg:last-child { flex: none; } -.version-menu { display: flex; flex-direction: column; max-height: min(70vh, 640px); overflow: auto; padding: 4px 0; min-width: min(620px, calc(100vw - 24px)); } -.version-head { display: grid; grid-template-columns: 1fr 84px 84px; gap: 10px; padding: 8px 18px 4px; font-size: var(--st-fs-xs); font-weight: 700; letter-spacing: .06em; text-transform: uppercase; color: var(--st-ink-muted); } -.version-head span:nth-child(n+2) { text-align: right; } -.version-row { display: grid; grid-template-columns: 1fr 84px 84px; gap: 10px; align-items: baseline; width: calc(100% - 12px); margin: 0 6px; padding: 6px 12px; border: 0; border-radius: var(--st-r-sm); background: transparent; color: var(--st-ink); font: inherit; font-size: var(--st-fs-md); text-align: left; cursor: pointer; } +/* The version list: one row per version, 14px names, 13px detail, small tags; the technical line is behind "Show details". */ +.version-menu { display: flex; flex-direction: column; max-height: min(70vh, 560px); overflow: auto; padding: 6px; } +.version-section + .version-section { margin-top: 6px; padding-top: 4px; border-top: 1px solid var(--st-hairline); } +.version-section__title { padding: 8px 10px 4px; font-size: var(--st-fs-xs); font-weight: 600; color: var(--st-ink-muted); } +.version-row { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; column-gap: 8px; align-items: start; width: 100%; padding: 8px 10px; border: 0; border-radius: var(--st-r-sm); background: transparent; color: var(--st-ink); font: inherit; font-size: var(--st-fs-md); text-align: left; cursor: pointer; } .version-row:hover, .version-row:focus-visible { background: var(--st-surface-2); } -.version-row.is-on { background: var(--st-surface-2); } -.version-row__name { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.version-row__name svg { color: var(--st-accent-text); margin-right: 6px; vertical-align: -2px; } -.version-row__title { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; } -.version-row__note { display: block; margin-top: 1px; font-size: var(--st-fs-xs); white-space: normal; line-height: 1.35; } -.version-row__have, .version-trigger .version-row__have { margin-left: 8px; padding: 1px 8px; border-radius: var(--st-r-pill); background: var(--st-accent-tint); color: var(--st-accent-text); font-size: var(--st-fs-xs); font-weight: 700; white-space: nowrap; } -.version-row__ssd { margin-left: 10px; font-size: var(--st-fs-xs); color: var(--st-warn-text); } -.version-row__ram { text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; } -.version-row__dl { text-align: right; font-size: var(--st-fs-xs); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; } -.version-group { border-top: 1px solid var(--st-line-soft); margin-top: 4px; } -.version-group[data-open] { background: var(--st-surface-2); padding-bottom: 6px; } -.version-group[data-open] .version-row:hover { background: var(--st-surface); } -.version-group__head { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; border: 0; background: transparent; color: var(--st-ink); font: inherit; font-weight: 700; cursor: pointer; text-align: left; } -.version-group__head svg.is-open { transform: rotate(180deg); } -.version-own { border-top: 1px solid var(--st-line-soft); margin-top: 4px; } +.version-row.is-on { background: var(--st-accent-tint); } +.version-row__check { padding-top: 3px; color: var(--st-accent-text); } +.version-row__body { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.version-row__title { display: flex; flex-wrap: wrap; align-items: center; gap: 2px 8px; min-width: 0; } +.version-row__title strong { font-weight: 600; overflow-wrap: anywhere; } +.version-row__word { font-size: var(--st-fs-sm); color: var(--st-ink-muted); } +.version-row__tech { font-size: var(--st-fs-sm); line-height: 1.4; color: var(--st-ink-muted); } +.version-row__size { font-size: var(--st-fs-sm); line-height: 20px; color: var(--st-ink-muted); font-variant-numeric: tabular-nums; white-space: nowrap; } +.version-row__slow { font-size: var(--st-fs-xs); color: var(--st-warn-text); } +.version-tag { padding: 0 8px; border-radius: var(--st-r-pill); font-size: var(--st-fs-xs); font-weight: 600; line-height: 20px; white-space: nowrap; } +.version-tag--pick { background: var(--st-accent-tint); color: var(--st-accent-text); } +.version-tag--have { box-shadow: inset 0 0 0 1px var(--st-line); color: var(--st-ink-soft); } +.version-foot { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px; margin-top: 6px; padding-top: 6px; border-top: 1px solid var(--st-hairline); } +.version-foot__btn { display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border: 0; border-radius: var(--st-r-sm); background: transparent; color: var(--st-ink-soft); font: inherit; font-size: var(--st-fs-sm); cursor: pointer; } +.version-foot__btn:hover, .version-foot__btn:focus-visible { background: var(--st-surface-2); color: var(--st-ink); } .pc-card { display: flex; flex-direction: column; gap: 18px; } .pc-card p { margin: 2px 0 0; } .pc-meter { display: flex; flex-direction: column; gap: 7px; } diff --git a/apps/host/tests/deepseek-card.test.mjs b/apps/host/tests/deepseek-card.test.mjs index 58b51a7e4b..ef03891cfc 100644 --- a/apps/host/tests/deepseek-card.test.mjs +++ b/apps/host/tests/deepseek-card.test.mjs @@ -67,6 +67,7 @@ test('the Models screen passes the set\'s disk to the card, and the version line const screen = read('../src/components/NativeModels.tsx'); assert.match(screen, /<PcFitCard [^>]*diskGb=\{selectedSize\?\.multi_file \? selectedSize\.disk_gb \?\? selectedSize\.download_gb : null\}/); const picker = read('../src/components/VersionPicker.tsx'); - assert.match(picker, /tr\("\{0\} RAM \+ VRAM, plus about \{1\} GB of disk", \[gb\(fit\.memoryGb\), Math\.round\(selected\.disk_gb\)\]\)/); - assert.match(picker, /: fit \? `\$\{gb\(fit\.memoryGb\)\} RAM \+ VRAM` : ''/, 'every other model keeps its line'); + assert.match(picker, /v\.multi_file && v\.disk_gb \? tr\("\{0\} RAM \+ VRAM, plus about \{1\} GB of disk", \[gb\(fit\.memoryGb\), Math\.round\(v\.disk_gb\)\]\)/, 'Details: the disk of the set for DeepSeek'); + assert.match(picker, /v\.multi_file && v\.disk_gb \? tr\("Needs \{0\} of memory and about \{1\} GB of disk"/, 'plain: the disk for DeepSeek only'); + assert.match(picker, /: tr\("Needs \{0\} of memory", \[whole\(fit\.memoryGb\)\]\)/, 'every other model keeps its line'); }); diff --git a/apps/host/tests/locale-gaps.test.mjs b/apps/host/tests/locale-gaps.test.mjs index e19890a7f0..377a70d092 100644 --- a/apps/host/tests/locale-gaps.test.mjs +++ b/apps/host/tests/locale-gaps.test.mjs @@ -12,7 +12,7 @@ const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64 test('every tr("...") literal and every command hint has a key in the English catalog, so no language is stuck in English (#3479)', async () => { const known = new Set(); - for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en', 'ui-en', 'engine-en']) for (const v of Object.values(await read(name))) known.add(String(v)); + for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en', 'ui-en', 'engine-en', 'pick-en']) for (const v of Object.values(await read(name))) known.add(String(v)); const missing = []; const scan = async dir => { for (const entry of await readdir(dir, { withFileTypes: true })) { diff --git a/apps/host/tests/version-picker.test.mjs b/apps/host/tests/version-picker.test.mjs new file mode 100644 index 0000000000..85d6eb7d36 --- /dev/null +++ b/apps/host/tests/version-picker.test.mjs @@ -0,0 +1,50 @@ +/** The version list: every version once, the pick first, sizes in order, the maker and the memory behind Details. */ +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/native-fit.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); +const { versionSections, recommendedVersions, PICK_NOTE } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +const source = await readFile(new URL('../src/components/VersionPicker.tsx', import.meta.url), 'utf8'); + +const v = (sourceFamily, model, download_gb, extra = {}) => ({ id: sourceFamily === 'qwen' ? model.toLowerCase() : `${sourceFamily}-${model.toLowerCase()}`, sourceFamily, model, download_gb, ...extra }); +const qwen38 = { family: 'qwen3.8', title: 'Qwen3.8-Flash-Next', sizes: [v('qwen', 'Q2_0', 66.4), v('qwen', 'IQ2_XS', 68), v('qwen', 'IQ3_XXS', 75.8), v('qwen', 'IQ3_S', 83.6), v('swift', 'IQ2_XS', 68), v('swift', 'IQ3_S', 83.6), v('coder', 'IQ1_M', 58.4), v('unsloth', 'UD-Q4_K_XL', 111.3), v('gyro', 'Gyro-S', 58.5), v('gyro', 'Gyro-M', 92)] }; +const qwen36 = { family: 'qwen3.6', title: 'Qwen3.6-35B-A3B', sizes: [v('qwen36', 'UD-Q4_K_XL', 22.9), v('qwen36', 'Q8_0', 37.8)] }; +const deepseek = { family: 'deepseek41', title: 'DeepSeek-V4.1-Flash', sizes: [v('deepseek41', 'IST-DAS-2.00bpw', 256.8, { multi_file: true, disk_gb: 262.8 }), v('deepseek41', 'IST-DAS-1.75bpw', 239.3, { multi_file: true, disk_gb: 245.3 })] }; +const models = [qwen38, qwen36, deepseek]; +const all = models.flatMap(m => m.sizes); + +test('every version is in the list exactly once (nothing lost, nothing doubled), DeepSeek and Qwen3.6 included', () => { + const sections = versionSections(all, models, new Set(), 'iq3_s'); + const ids = sections.flatMap(s => s.versions.map(x => x.id)); + assert.equal(ids.length, all.length); + assert.deepEqual([...ids].sort(), all.map(x => x.id).sort()); + assert.deepEqual(sections.map(s => s.title), ['Qwen3.8-Flash-Next', 'Qwen3.6-35B-A3B', 'DeepSeek-V4.1-Flash'], 'a model name, small, only where there is more than one model'); +}); + +test('IQ3_S downloaded and recommended shows once, first, not again under a maker group', () => { + const pick = { family: 'qwen', model: 'IQ3_S', why: '64 GB tier' }; + const pickId = recommendedVersions(all.filter(x => x.sourceFamily !== 'qwen36' && x.sourceFamily !== 'deepseek41'), pick).find(r => r.r.note === PICK_NOTE)?.v.id; + assert.equal(pickId, 'iq3_s'); + const first = versionSections(all, models, new Set(), pickId)[0].versions; + assert.equal(first[0].id, 'iq3_s'); + assert.equal(first.filter(x => x.model === 'IQ3_S' && x.sourceFamily === 'qwen').length, 1); + assert.deepEqual(first.slice(1).map(x => x.download_gb), [...first.slice(1).map(x => x.download_gb)].sort((a, b) => a - b), 'the rest in order of download size'); +}); + +test('one model: no section title; the first-run list leaves out what it shows elsewhere', () => { + const sections = versionSections(qwen38.sizes, undefined, new Set(['iq3_s', 'gyro-gyro-s'])); + assert.equal(sections.length, 1); + assert.equal(sections[0].title, ''); + assert.ok(!sections[0].versions.some(x => x.id === 'iq3_s' || x.id === 'gyro-gyro-s')); + assert.equal(sections[0].versions.length, qwen38.sizes.length - 2); +}); + +test('the picker has no maker groups or collapsible headings, and the technical lines sit behind Show details', () => { + assert.ok(!/VERSION_GROUPS|groupOpen|version-group/.test(source), 'no Swift / GSQ-RCO / Unsloth group headings'); + assert.ok(!/\(GSQ-RCO\)/.test(source), 'the maker is not part of the main name'); + assert.match(source, /details \? <span className="version-row__tech">/, 'maker, RAM + VRAM and the SSD figure are shown only with details on'); + assert.match(source, /Recommended/); + assert.match(source, /Downloaded/); +}); From a8e07c1b521213e3c8462ffe2414022767daa782 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:51:20 +0100 Subject: [PATCH 07/59] Version list: tags stay together on one line, a downloaded version shows its size without the word download --- apps/host/src/components/VersionPicker.tsx | 6 +++--- apps/host/src/styles/app.css | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/host/src/components/VersionPicker.tsx b/apps/host/src/components/VersionPicker.tsx index b5f5a864bc..16bc9a903e 100644 --- a/apps/host/src/components/VersionPicker.tsx +++ b/apps/host/src/components/VersionPicker.tsx @@ -81,10 +81,10 @@ export function VersionPicker({ versions, models, selectedId, hardware, onSelect return <button key={v.id} role="menuitemradio" aria-checked={on} className={cx('version-row', on && 'is-on')} onClick={() => { onSelect(v.id); setOpen(false); }}> <span className="version-row__check">{tr(on ? <Icon name="check" size={14}/> : null)}</span> <span className="version-row__body"> - <span className="version-row__title"><strong>{versionName(v)}</strong>{tr(word ? <span className="version-row__word">{word}</span> : null)}{tr(v.id === pickId ? <span className="version-tag version-tag--pick">{tr("Recommended")}</span> : null)}{tr(downloaded?.has(v.id) ? <span className="version-tag version-tag--have">{tr("Downloaded")}</span> : null)}{tr(slow ? <span className="version-row__slow">{tr("Slower on this computer")}</span> : null)}</span> + <span className="version-row__title"><strong>{versionName(v)}</strong>{tr(word ? <span className="version-row__word">{word}</span> : null)}{tr(v.id === pickId || downloaded?.has(v.id) ? <span className="version-row__tags">{tr(v.id === pickId ? <span className="version-tag version-tag--pick">{tr("Recommended")}</span> : null)}{tr(downloaded?.has(v.id) ? <span className="version-tag version-tag--have">{tr("Downloaded")}</span> : null)}</span> : null)}{tr(slow ? <span className="version-row__slow">{tr("Slower on this computer")}</span> : null)}</span> {tr(details ? <span className="version-row__tech">{technical}{tr(note ? <><br/>{note}</> : null)}</span> : null)} </span> - <span className="version-row__size">{tr("{0} download", [gb(v.download_gb)])}</span> + <span className="version-row__size">{downloaded?.has(v.id) ? gb(v.download_gb) : tr("{0} download", [gb(v.download_gb)])}</span> </button>; }; // The open menu opens on the chosen version, not at the top of a long list. @@ -96,7 +96,7 @@ export function VersionPicker({ versions, models, selectedId, hardware, onSelect <span className="version-trigger__need muted">{tr(shown ? need(shown, details) : '')}</span> <Icon name="chevron" size={14} className="version-trigger__chev"/> </button> - {tr(open ? <FloatingMenu anchor={trigger.current} title={tr("Model version")} width={480} onClose={() => setOpen(false)}> + {tr(open ? <FloatingMenu anchor={trigger.current} title={tr("Model version")} width={520} onClose={() => setOpen(false)}> <div className="version-menu" ref={menu}> {tr(sections.map(s => <div className="version-section" role="group" aria-label={s.title || tr("Model version")} key={s.id}> {tr(s.title ? <div className="version-section__title" aria-hidden="true">{s.title}</div> : null)} diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index 3cf9c673cc..49d8f5e7f8 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7048,6 +7048,7 @@ textarea { .version-row__tech { font-size: var(--st-fs-sm); line-height: 1.4; color: var(--st-ink-muted); } .version-row__size { font-size: var(--st-fs-sm); line-height: 20px; color: var(--st-ink-muted); font-variant-numeric: tabular-nums; white-space: nowrap; } .version-row__slow { font-size: var(--st-fs-xs); color: var(--st-warn-text); } +.version-row__tags { display: inline-flex; flex-wrap: nowrap; gap: 6px; white-space: nowrap; } .version-tag { padding: 0 8px; border-radius: var(--st-r-pill); font-size: var(--st-fs-xs); font-weight: 600; line-height: 20px; white-space: nowrap; } .version-tag--pick { background: var(--st-accent-tint); color: var(--st-accent-text); } .version-tag--have { box-shadow: inset 0 0 0 1px var(--st-line); color: var(--st-ink-soft); } From a44bcd4eb5ee50c75f70823739940100f56184d3 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:51:36 +0100 Subject: [PATCH 08/59] Copy: no Copied popover at the corner, the icon's check is the feedback (failures still say so) --- apps/host/src/lib/use-copy.ts | 5 +++-- apps/host/tests/clipboard-copy.test.mjs | 7 +++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/host/src/lib/use-copy.ts b/apps/host/src/lib/use-copy.ts index 08834ea1f3..e2147597f2 100644 --- a/apps/host/src/lib/use-copy.ts +++ b/apps/host/src/lib/use-copy.ts @@ -7,7 +7,7 @@ export const COPIED_MS = 1800; export const COPIED_MENU_MS = 900; /** - * One behaviour for every Copy control: copy the text (with the toast and the older fallback of copyText), and when it worked, + * One behaviour for every Copy control: copy the text (with the older fallback of copyText; only a failure gets a toast), and when it worked, * `copied` is true for a moment so the control itself can show it. A failed copy leaves the control as it was and the toast says so. * The text may be a function, for a value that has to be fetched first. */ @@ -21,7 +21,8 @@ export function useCopy(hold = COPIED_MS) { let value: string; try { value = typeof text === 'function' ? await text() : text; } catch { pushToast('warn', 'Couldn’t copy'); return false; } - const ok = await copyText(value, label, { toast: pushToast }); + // A copy that worked is shown on the control itself (the icon turns into a check): no "Copied" popover at the corner. A copy that failed still says so. + const ok = await copyText(value, label, { toast: (tone, title, body) => { if (tone !== 'success') pushToast(tone, title, body); } }); if (ok) { setCopied(true); clearTimeout(timer.current); diff --git a/apps/host/tests/clipboard-copy.test.mjs b/apps/host/tests/clipboard-copy.test.mjs index 0ed7787a1e..da500f9bed 100644 --- a/apps/host/tests/clipboard-copy.test.mjs +++ b/apps/host/tests/clipboard-copy.test.mjs @@ -28,3 +28,10 @@ test('the typed message keeps its line breaks (#3720) and the chat uses the shar const chat = await readFile(new URL('../src/screens/Chat.tsx', import.meta.url), 'utf8'); assert.doesNotMatch(chat, /void navigator\.clipboard\.writeText/); }); + +test('a copy that worked shows no corner popover: the control shows it; a failed copy still has its toast', async () => { + const { readFile } = await import('node:fs/promises'); + const hook = await readFile(new URL('../src/lib/use-copy.ts', import.meta.url), 'utf8'); + assert.match(hook, /toast: \(tone, title, body\) => \{ if \(tone !== 'success'\) pushToast\(tone, title, body\); \}/); + assert.match(hook, /pushToast\('warn', 'Couldn’t copy'\)/); +}); From 0a8499b0a329b648d559d9cd4810ba4b929b8cd1 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:57:39 +0100 Subject: [PATCH 09/59] Motion system: one press feedback and the reduced-motion gate for it (tokens in liquid.css section 17) --- apps/host/src/styles/liquid.css | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index 33100520b6..7c8c1038a1 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -1059,3 +1059,36 @@ body { line-height: 1.2; padding-top: 2px; } +/* ------------------------------------------------ 17. the motion system ----- + One scale (app.css section 1: micro 100, control 160, local 240, surface 320, + choreo 460ms; standard / enter / exit curves) and three habits, so the app + answers a touch the same way everywhere: + + - a control that is pressed gives a little (a 3% scale, micro time); + - a surface that appears arrives from the side it belongs to, decelerating, + and leaves faster than it came (enter = local/surface, exit = control); + - a disclosure opens by growing and fading in, never by snapping. + + Everything animates transform, opacity, or one small block-size (a disclosure), + never a transcript's layout, so streaming text and scrolling cost nothing + extra on a weak GPU while a heavy model is running beside the app. The + reduced-motion gate zeroes the durations (tokens) and the distances below. */ +:root { + --st-press-scale: 0.97; + --st-panel-shift: 28px; +} +.st-btn { + transition: + background-color var(--st-t-control) var(--st-ease-standard), + border-color var(--st-t-control) var(--st-ease-standard), + color var(--st-t-control) var(--st-ease-standard), + box-shadow var(--st-t-control) var(--st-ease-standard), + transform var(--st-t-micro) var(--st-ease-standard); +} +.st-btn:not(:disabled):active { + transform: scale(var(--st-press-scale)); +} +@media (prefers-reduced-motion: reduce) { + :root { --st-press-scale: 1; --st-panel-shift: 0px; } +} + From e47848a319f958e4923f294715a556e6527fb36a Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:57:39 +0100 Subject: [PATCH 10/59] Reasoning opens and closes smoothly: grows and fades, hover and press on the line, the rule belongs to the body --- apps/host/src/styles/liquid.css | 52 +++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index 7c8c1038a1..2a8ecb2ffa 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -1092,3 +1092,55 @@ body { :root { --st-press-scale: 1; --st-panel-shift: 0px; } } +/* Reasoning ("Thought for 38s"): the summary is a control (hover wash, press), + the chevron turns, and the passage grows open and fades in — it used to jump. + The rule that marks the passage belongs to the body, so the line above it + never moves. Where ::details-content is not supported it simply opens. */ +.rz > summary { + width: fit-content; + max-width: 100%; + margin-left: -8px; + padding: 2px 8px; + border-radius: var(--st-r-pill); + transition: + background-color var(--st-t-control) var(--st-ease-standard), + transform var(--st-t-micro) var(--st-ease-standard); +} +.rz > summary:hover { + background: var(--st-fill-hover); +} +.rz > summary:active { + background: var(--st-fill-press); + transform: scale(var(--st-press-scale)); +} +.rz > summary:focus-visible { + box-shadow: inset 0 0 0 1px var(--st-ink-muted); +} +.rz__chev { + transition: transform var(--st-t-local) var(--st-ease-standard); +} +.rz[open] { + border-left: 0; + padding-left: 0; +} +.rz__body { + margin-left: 2px; + padding-left: 12px; + border-left: 2px solid var(--st-hairline); +} +@supports (interpolate-size: allow-keywords) { + .rz::details-content { + block-size: 0; + opacity: 0; + overflow: hidden; + transition: + content-visibility var(--st-t-surface) allow-discrete, + block-size var(--st-t-surface) var(--st-ease-standard), + opacity var(--st-t-local) var(--st-ease-standard); + } + .rz[open]::details-content { + block-size: auto; + opacity: 1; + } +} + From b63a82e011eb60722749ebebe089f7c5d45dc3cf Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:57:39 +0100 Subject: [PATCH 11/59] Code blocks: room before and after, a lighter 34px bar and tighter padding (12px floor kept) --- apps/host/src/styles/liquid.css | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index 2a8ecb2ffa..006255de42 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -1144,3 +1144,28 @@ body { } } +/* Code blocks: a block is a figure inside the answer, so it gets room before and + after, and it is lighter than the text around it — a 34px bar, 10px of padding, + code at the reading step below the body (12px minimum at the default size: pass 37's + floor stays; 13px against 16px body at the larger sizes). */ +.st-bubble .st-code { + margin: 16px 0 20px; +} +.st-bubble .st-code:first-child { + margin-top: 0; +} +.st-bubble .st-code:last-child { + margin-bottom: 0; +} +.st-code__head { + min-height: 34px; + padding-block: 2px; +} +.st-code pre { + padding: 10px 14px; + line-height: 1.5; +} +.st-code .st-btn--icon { + width: 28px; + height: 28px; +} From 211ca210fb0b031783c825475fb559588e7a26e9 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:57:56 +0100 Subject: [PATCH 12/59] Code block preview is an icon button left of Copy, with an open and a close state (HTML and Markdown blocks) --- apps/host/scripts/make-pick-locales.py | 5 ++- apps/host/src/components/CodePreviewBtn.tsx | 15 +++++++++ apps/host/src/components/Markdown.tsx | 15 ++++++--- apps/host/src/lib/code-preview.ts | 36 +++++++++++++++++++++ apps/host/src/locales/pick-de.json | 3 +- apps/host/src/locales/pick-en.json | 3 +- apps/host/src/locales/pick-es.json | 3 +- apps/host/src/locales/pick-fr.json | 3 +- apps/host/src/locales/pick-ja.json | 3 +- apps/host/src/locales/pick-ko.json | 3 +- apps/host/src/locales/pick-pt.json | 3 +- apps/host/src/locales/pick-ru.json | 3 +- apps/host/src/locales/pick-zh.json | 3 +- apps/host/src/screens/Chat.tsx | 16 +++++---- apps/host/src/styles/liquid.css | 11 +++++++ 15 files changed, 105 insertions(+), 20 deletions(-) create mode 100644 apps/host/src/components/CodePreviewBtn.tsx create mode 100644 apps/host/src/lib/code-preview.ts diff --git a/apps/host/scripts/make-pick-locales.py b/apps/host/scripts/make-pick-locales.py index 334b17d06d..1118098afa 100644 --- a/apps/host/scripts/make-pick-locales.py +++ b/apps/host/scripts/make-pick-locales.py @@ -1,4 +1,4 @@ -"""Writes src/locales/pick-<lang>.json: the strings of the model version list (VersionPicker, branch f-0291-ui-fixes2). +"""Writes src/locales/pick-<lang>.json: the strings of the model version list (VersionPicker), the code-block preview button and the This computer panel (branch f-0291-ui-fixes2). Run from apps/host: python scripts/make-pick-locales.py Every entry names all nine languages; the keys are vp01.. in the order of S. pick-en.json is the English source. Placeholders ({0}, {1}) must be kept in every language. A separate file keeps this work from colliding with the other catalogs (the same reason tune-, tools-, fix-, gh-, ui- and engine- exist).""" @@ -30,6 +30,9 @@ add("Hide details", add("{0} RAM + VRAM", "{0} 内存 + 显存", "{0} の RAM + VRAM", "{0} RAM + VRAM", "{0} de RAM + VRAM", "{0} RAM + VRAM", "{0} de RAM + VRAM", "RAM + VRAM {0}", "{0} de RAM + VRAM") +add("Close preview", + "关闭预览", "プレビューを閉じる", "Vorschau schließen", "Cerrar vista previa", "Закрыть предпросмотр", "Fechar pré-visualização", "미리보기 닫기", "Fermer l'aperçu") + here = Path(__file__).resolve().parent.parent / "src" / "locales" NBSP = " " diff --git a/apps/host/src/components/CodePreviewBtn.tsx b/apps/host/src/components/CodePreviewBtn.tsx new file mode 100644 index 0000000000..59d5873f23 --- /dev/null +++ b/apps/host/src/components/CodePreviewBtn.tsx @@ -0,0 +1,15 @@ +import { tr } from '../lib/i18n'; +import { cx } from '../lib/format'; +import { Icon } from './ui'; +import { useSelectedPreviewId } from '../lib/code-preview'; +import type { PreviewArtifact } from '../lib/artifacts'; + +/** The preview control of a code block: an icon button like Copy, on its left. It shows both states: closed, and open (filled, "Close preview"). */ +export function CodePreviewBtn({ artifact, onPreview, onClose }: { artifact: PreviewArtifact; onPreview: (a: PreviewArtifact) => void; onClose?: (id: string) => void }) { + const open = useSelectedPreviewId() === artifact.id; + const label = tr(open ? 'Close preview' : 'Open preview'); + return <button type="button" className={cx('st-btn st-btn--icon', open && 'is-open')} data-open={open || undefined} aria-pressed={open} aria-label={label} title={label} + onClick={() => (open && onClose ? onClose(artifact.id) : onPreview(artifact))}> + <Icon name="panel" size={19}/> + </button>; +} diff --git a/apps/host/src/components/Markdown.tsx b/apps/host/src/components/Markdown.tsx index ec17415a0f..f25f7ca4fe 100644 --- a/apps/host/src/components/Markdown.tsx +++ b/apps/host/src/components/Markdown.tsx @@ -2,7 +2,9 @@ import { tr } from '../lib/i18n'; import { CopyBtn } from './CopyBtn'; /** Safe, dependency-free rendering of the Markdown structures used in answers. */ import { Fragment, type ReactNode } from 'react'; -import { Btn } from './ui'; +import { CodePreviewBtn } from './CodePreviewBtn'; +import { codePreview } from '../lib/code-preview'; +import type { PreviewArtifact } from '../lib/artifacts'; import { SyntaxCode } from './SyntaxCode'; import { MathView } from './MathView'; import { displayBlock, hasMath, splitMath } from '../lib/math'; @@ -57,10 +59,13 @@ export function continuesParagraph(lines: string[], at: number): boolean { return false; return !displayBlock(lines, at); } -export function Markdown({ text, onOpenLink, onPreviewHtml, imageSession }: { +export function Markdown({ text, onOpenLink, previewId, onPreview, onClosePreview, imageSession }: { text: string; onOpenLink?: (url: string) => void; - onPreviewHtml?: (html: string) => void; + /** Where an HTML or Markdown code block can be shown in the sidebar: the message it belongs to, and the handlers that open and close a preview. */ + previewId?: string; + onPreview?: (a: PreviewArtifact) => void; + onClosePreview?: (id: string) => void; /** The chat whose folder a picture path in the answer is read from (the host serves only files inside it). */ imageSession?: string | null; }) { @@ -79,7 +84,9 @@ export function Markdown({ text, onOpenLink, onPreviewHtml, imageSession }: { while (i < lines.length && !/^\s*```/.test(lines[i])) body.push(lines[i++]); i++; - nodes.push(<div className="st-code" key={key}><div className="st-code__head"><span>{language || tr('code')}</span>{tr(/^html$/i.test(language) && onPreviewHtml ? <Btn size="sm" onClick={() => onPreviewHtml(body.join('\n'))}>{tr("Open preview")}</Btn> : null)}<CopyBtn text={body.join('\n')} label="Code" title="Copy code"/></div><SyntaxCode text={body.join('\n')} language={language}/></div>); + const code = body.join('\n'); + const preview = previewId && onPreview ? codePreview(previewId, language, code) : null; + nodes.push(<div className="st-code" key={key}><div className="st-code__head"><span>{language || tr('code')}</span><span className="st-code__actions">{tr(preview && onPreview ? <CodePreviewBtn artifact={preview} onPreview={onPreview} onClose={onClosePreview}/> : null)}<CopyBtn text={code} label="Code" title="Copy code"/></span></div><SyntaxCode text={code} language={language}/></div>); continue; } const block = displayBlock(lines, i); diff --git a/apps/host/src/lib/code-preview.ts b/apps/host/src/lib/code-preview.ts new file mode 100644 index 0000000000..ab624b1eae --- /dev/null +++ b/apps/host/src/lib/code-preview.ts @@ -0,0 +1,36 @@ +import { useSyncExternalStore } from 'react'; +import type { PreviewArtifact } from './artifacts'; + +/** + * Code blocks that can be shown in the sidebar preview: an HTML page, or Markdown. The block's id comes from the message and the code itself, + * so two blocks in one answer are two previews, and the block's button can tell whether its own preview is the one open. + */ +const hash = (text: string) => { let h = 5381; for (let i = 0; i < text.length; i++) h = ((h << 5) + h + text.charCodeAt(i)) | 0; return (h >>> 0).toString(36); }; + +export function codePreviewKind(language: string): 'website' | 'markdown' | null { + const name = language.trim().toLowerCase(); + return name === 'html' ? 'website' : name === 'markdown' || name === 'md' ? 'markdown' : null; +} + +export function codePreview(base: string, language: string, code: string): PreviewArtifact | null { + const kind = codePreviewKind(language); + if (!kind) return null; + return { id: `${base}-${hash(code)}`, kind, title: kind === 'website' ? 'HTML preview' : 'Markdown preview', content: code }; +} + +/** The one complete page in a finished answer, or null: exactly one fenced html block that is a whole document (a snippet stays a button). */ +export function mainCodePreview(base: string, content: string): PreviewArtifact | null { + const blocks = [...content.matchAll(/^[ \t]*```([^\n`]*)\n([\s\S]*?)\n[ \t]*```[ \t]*$/gm)].map(m => ({ language: m[1].trim(), code: m[2] })).filter(b => codePreviewKind(b.language)); + if (blocks.length !== 1 || codePreviewKind(blocks[0].language) !== 'website') return null; + return /<!doctype\s+html|<html[\s>]/i.test(blocks[0].code) ? codePreview(base, blocks[0].language, blocks[0].code) : null; +} + +let selected: string | null = null; +const listeners = new Set<() => void>(); +/** The chat tells which preview is showing in the sidebar; only the code blocks' buttons listen, so no message re-renders for it. */ +export function setSelectedPreviewId(id: string | null) { + if (id === selected) return; + selected = id; + listeners.forEach(fn => fn()); +} +export const useSelectedPreviewId = () => useSyncExternalStore(fn => { listeners.add(fn); return () => { listeners.delete(fn); }; }, () => selected, () => null); diff --git a/apps/host/src/locales/pick-de.json b/apps/host/src/locales/pick-de.json index c427957a61..a113a6baaf 100644 --- a/apps/host/src/locales/pick-de.json +++ b/apps/host/src/locales/pick-de.json @@ -5,5 +5,6 @@ "vp04": "Auf diesem Computer langsamer", "vp05": "Details anzeigen", "vp06": "Details ausblenden", - "vp07": "{0} RAM + VRAM" + "vp07": "{0} RAM + VRAM", + "vp08": "Vorschau schließen" } diff --git a/apps/host/src/locales/pick-en.json b/apps/host/src/locales/pick-en.json index f12998faa3..68bffc949e 100644 --- a/apps/host/src/locales/pick-en.json +++ b/apps/host/src/locales/pick-en.json @@ -5,5 +5,6 @@ "vp04": "Slower on this computer", "vp05": "Show details", "vp06": "Hide details", - "vp07": "{0} RAM + VRAM" + "vp07": "{0} RAM + VRAM", + "vp08": "Close preview" } diff --git a/apps/host/src/locales/pick-es.json b/apps/host/src/locales/pick-es.json index 221c2090d6..0fa83985c1 100644 --- a/apps/host/src/locales/pick-es.json +++ b/apps/host/src/locales/pick-es.json @@ -5,5 +5,6 @@ "vp04": "Más lento en este equipo", "vp05": "Mostrar detalles", "vp06": "Ocultar detalles", - "vp07": "{0} de RAM + VRAM" + "vp07": "{0} de RAM + VRAM", + "vp08": "Cerrar vista previa" } diff --git a/apps/host/src/locales/pick-fr.json b/apps/host/src/locales/pick-fr.json index 17519c323c..d1138c9eff 100644 --- a/apps/host/src/locales/pick-fr.json +++ b/apps/host/src/locales/pick-fr.json @@ -5,5 +5,6 @@ "vp04": "Plus lent sur cet ordinateur", "vp05": "Afficher les détails", "vp06": "Masquer les détails", - "vp07": "{0} de RAM + VRAM" + "vp07": "{0} de RAM + VRAM", + "vp08": "Fermer l’aperçu" } diff --git a/apps/host/src/locales/pick-ja.json b/apps/host/src/locales/pick-ja.json index 8bb77ecb5c..e99e3c2327 100644 --- a/apps/host/src/locales/pick-ja.json +++ b/apps/host/src/locales/pick-ja.json @@ -5,5 +5,6 @@ "vp04": "このコンピューターでは遅くなります", "vp05": "詳細を表示", "vp06": "詳細を隠す", - "vp07": "{0} の RAM + VRAM" + "vp07": "{0} の RAM + VRAM", + "vp08": "プレビューを閉じる" } diff --git a/apps/host/src/locales/pick-ko.json b/apps/host/src/locales/pick-ko.json index 2cc5344c64..8ebffe201f 100644 --- a/apps/host/src/locales/pick-ko.json +++ b/apps/host/src/locales/pick-ko.json @@ -5,5 +5,6 @@ "vp04": "이 컴퓨터에서는 더 느립니다", "vp05": "자세히 보기", "vp06": "자세히 숨기기", - "vp07": "RAM + VRAM {0}" + "vp07": "RAM + VRAM {0}", + "vp08": "미리보기 닫기" } diff --git a/apps/host/src/locales/pick-pt.json b/apps/host/src/locales/pick-pt.json index b09664ae8f..32ca5429b4 100644 --- a/apps/host/src/locales/pick-pt.json +++ b/apps/host/src/locales/pick-pt.json @@ -5,5 +5,6 @@ "vp04": "Mais lento neste computador", "vp05": "Mostrar detalhes", "vp06": "Ocultar detalhes", - "vp07": "{0} de RAM + VRAM" + "vp07": "{0} de RAM + VRAM", + "vp08": "Fechar pré-visualização" } diff --git a/apps/host/src/locales/pick-ru.json b/apps/host/src/locales/pick-ru.json index d0332ddfbb..b0e904391d 100644 --- a/apps/host/src/locales/pick-ru.json +++ b/apps/host/src/locales/pick-ru.json @@ -5,5 +5,6 @@ "vp04": "На этом компьютере медленнее", "vp05": "Показать подробности", "vp06": "Скрыть подробности", - "vp07": "{0} RAM + VRAM" + "vp07": "{0} RAM + VRAM", + "vp08": "Закрыть предпросмотр" } diff --git a/apps/host/src/locales/pick-zh.json b/apps/host/src/locales/pick-zh.json index aa8597a505..b0d5381d6a 100644 --- a/apps/host/src/locales/pick-zh.json +++ b/apps/host/src/locales/pick-zh.json @@ -5,5 +5,6 @@ "vp04": "在这台电脑上较慢", "vp05": "显示详情", "vp06": "隐藏详情", - "vp07": "{0} 内存 + 显存" + "vp07": "{0} 内存 + 显存", + "vp08": "关闭预览" } diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index ef36d04eb6..c7a8c599a3 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -10,6 +10,7 @@ import { ChatTelemetry } from '../components/TelemetryPopover'; import { ArtifactCard } from '../components/ArtifactCard'; import { ChatMedia } from '../components/ChatMedia'; import { closePreviewTab } from '../lib/preview-tabs'; +import { setSelectedPreviewId } from '../lib/code-preview'; import { ArtifactPanel } from '../components/ArtifactPanel'; import { PreviewResizeHandle } from '../components/PreviewResizeHandle'; import { DEFAULT_PREVIEW_FRACTION, PREVIEW_SPLIT_KEY, previewWidth } from '../lib/preview-layout'; @@ -200,6 +201,7 @@ export function ChatScreen() { const sessionId = session.id; void previewOf(sessionId, main).then(item => { if (session.id === sessionId) openPreview(item); }, () => { }); }, [lastReply?.id, lastReply?.streaming]); + useEffect(() => { setSelectedPreviewId(setupVisible ? null : selectedPreview); return () => setSelectedPreviewId(null); }, [selectedPreview, setupVisible]); function closeTab(id: string) { const next = closePreviewTab([...previews.map(p => ({ id: p.id })), ...extraTabs], selectedPreview, id); setPreviews(previews.filter(p => p.id !== id)); @@ -228,11 +230,12 @@ export function ChatScreen() { } /* The message list is memoised (#4640 family: Out of Memory in a long chat): a streamed token changes one message, so the others must not re-render. These handlers keep one identity for the life of the screen and always call the newest functions above. */ - const latestHandlers = useRef({ editPrompt, openPreview, openTimeSkip, openLink }); - latestHandlers.current = { editPrompt, openPreview, openTimeSkip, openLink }; + const latestHandlers = useRef({ editPrompt, openPreview, closeTab, openTimeSkip, openLink }); + latestHandlers.current = { editPrompt, openPreview, closeTab, openTimeSkip, openLink }; const messageHandlers = useMemo(() => ({ onEditPrompt: (text: string) => latestHandlers.current.editPrompt(text), onPreview: (a: PreviewArtifact) => latestHandlers.current.openPreview(a), + onClosePreview: (id: string) => latestHandlers.current.closeTab(id), onOpenTimeSkip: (id: string) => latestHandlers.current.openTimeSkip(id), onOpenLink: (url: string) => latestHandlers.current.openLink(url), }), []); @@ -516,7 +519,7 @@ export function ChatScreen() { <div className="chat__inner"> {tr(session.messages.length === 0 ? (session.statsAvailable === false ? <p className="small muted">{tr("Editing from an earlier message. Update the prompt below.")}</p> : - <UsageDashboard loaded={!!loaded}/>) : (session.messages.map((m, i) => (<Message key={m.id} message={m} isLast={i === session.messages.length - 1} onEditPrompt={messageHandlers.onEditPrompt} onPreview={messageHandlers.onPreview} onOpenTimeSkip={messageHandlers.onOpenTimeSkip} timeSkipDone={!!allTimeSkipRuns.find(r => r.id === m.timeSkipId)?.completedAt} timeSkipReal={!!allTimeSkipRuns.find(r => r.id === m.timeSkipId)?.job} timeSkipRun={allTimeSkipRuns.find(r => r.id === m.timeSkipId)} onOpenLink={messageHandlers.onOpenLink}/>))))} + <UsageDashboard loaded={!!loaded}/>) : (session.messages.map((m, i) => (<Message key={m.id} message={m} isLast={i === session.messages.length - 1} onEditPrompt={messageHandlers.onEditPrompt} onPreview={messageHandlers.onPreview} onClosePreview={messageHandlers.onClosePreview} onOpenTimeSkip={messageHandlers.onOpenTimeSkip} timeSkipDone={!!allTimeSkipRuns.find(r => r.id === m.timeSkipId)?.completedAt} timeSkipReal={!!allTimeSkipRuns.find(r => r.id === m.timeSkipId)?.job} timeSkipRun={allTimeSkipRuns.find(r => r.id === m.timeSkipId)} onOpenLink={messageHandlers.onOpenLink}/>))))} <QueuedMessages chatId={session.id}/> </div> </div> @@ -700,11 +703,12 @@ function Composer({ draft, setDraft, loaded, streaming, onSubmit, onKey, session </div>); } const Message = memo(MessageView); -function MessageView({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOpenTimeSkip, timeSkipDone, timeSkipReal, timeSkipRun, }: { +function MessageView({ message: m, isLast, onEditPrompt, onPreview, onClosePreview, onOpenLink, onOpenTimeSkip, timeSkipDone, timeSkipReal, timeSkipRun, }: { message: ChatMessage; isLast: boolean; onEditPrompt: (text: string) => void; onPreview: (a: PreviewArtifact) => void; + onClosePreview: (id: string) => void; onOpenLink: (url: string) => void; onOpenTimeSkip: (id: string) => void; timeSkipDone: boolean; @@ -748,8 +752,8 @@ function MessageView({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, {tr(!(m.timeSkipId && timeSkipReal && !timeSkipDone) && (m.content || m.error || !m.streaming || !liveStatus) ? <div className="st-bubble"> {tr(planCard ? <PlanCard chatId={activeSession} planId={m.planId!}/> : null)} {tr(m.error ? (<ErrorNotice message={m.error} detail={m.errorDetail} {...contextRecovery(m.errorCode)}/>) : null)} - {tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? <ActivityLine key={b.id} group={b} sessionId={activeSession ?? ''} onPreview={onPreview}/> : <Markdown key={i} text={b.text} onOpenLink={onOpenLink} imageSession={activeSession} onPreviewHtml={content => onPreview({ id: m.id + '-html-' + i, kind: 'website', title: 'HTML preview', content })}/>) : null)} - {tr(m.content && !planCard && !grouped ? (<Markdown text={m.timeSkipId && !timeSkipReal ? hostLive ? tr('This was a sample run made while the app could not reach its host.') : timeSkipDone ? tr('The result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.') : tr('Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.') : m.content} onOpenLink={onOpenLink} imageSession={activeSession} onPreviewHtml={content => onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? (<span className="typing" aria-label={tr("Generating")}> + {tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? <ActivityLine key={b.id} group={b} sessionId={activeSession ?? ''} onPreview={onPreview}/> : <Markdown key={i} text={b.text} onOpenLink={onOpenLink} imageSession={activeSession} previewId={`${m.id}-b${i}`} onPreview={onPreview} onClosePreview={onClosePreview}/>) : null)} + {tr(m.content && !planCard && !grouped ? (<Markdown text={m.timeSkipId && !timeSkipReal ? hostLive ? tr('This was a sample run made while the app could not reach its host.') : timeSkipDone ? tr('The result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.') : tr('Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.') : m.content} onOpenLink={onOpenLink} imageSession={activeSession} previewId={m.id} onPreview={onPreview} onClosePreview={onClosePreview}/>) : !m.error && m.streaming && !liveStatus ? (<span className="typing" aria-label={tr("Generating")}> <i /> <i /> <i /> diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index 006255de42..77ba981fde 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -1169,3 +1169,14 @@ body { width: 28px; height: 28px; } +.st-code .st-btn--icon[data-open] { + color: var(--st-accent); + background: color-mix(in srgb, var(--st-code-ink) 10%, transparent); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--st-accent) 45%, transparent); +} + +.st-code__actions { + display: inline-flex; + align-items: center; + gap: 2px; +} From c25a2de200135c8d96792e36eef53499aaa27822 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:57:56 +0100 Subject: [PATCH 13/59] Sidebar preview: previewable pages open there first, and it comes in and goes out with motion --- apps/host/src/components/ArtifactPanel.tsx | 16 +++++- apps/host/src/screens/Chat.tsx | 5 +- apps/host/src/styles/liquid.css | 40 +++++++++++++ apps/host/tests/chat-details.test.mjs | 65 ++++++++++++++++++++++ 4 files changed, 122 insertions(+), 4 deletions(-) create mode 100644 apps/host/tests/chat-details.test.mjs diff --git a/apps/host/src/components/ArtifactPanel.tsx b/apps/host/src/components/ArtifactPanel.tsx index 4669d3f014..92fce0a1be 100644 --- a/apps/host/src/components/ArtifactPanel.tsx +++ b/apps/host/src/components/ArtifactPanel.tsx @@ -62,15 +62,27 @@ export function ArtifactPanel({ items, selected, onSelect, onClose, onCloseTab, }); return () => abort.abort(); }, [current?.id, revision]); + // A closed panel leaves with a short slide instead of vanishing (a bare shell; the page itself is already gone). + const hadCurrent = useRef(false); + const [leaving, setLeaving] = useState(false); + useEffect(() => { + if (current) { hadCurrent.current = true; setLeaving(false); return; } + if (!hadCurrent.current || !inline) return; + hadCurrent.current = false; + if (matchMedia('(prefers-reduced-motion: reduce)').matches) return; + setLeaving(true); + const timer = setTimeout(() => setLeaving(false), 260); + return () => clearTimeout(timer); + }, [!!current, inline]); if (!current) - return null; + return leaving ? <aside className="artifact-panel" data-leaving="true" aria-hidden="true"/> : null; const url = current.url ? safePreviewUrl(current.url) : null; const viewControls = current.kind === 'markdown' ? <Seg ariaLabel={tr("Markdown view")} value={mode} options={[{ value: 'preview', label: 'Read' }, { value: 'source', label: 'Source' }]} onChange={setMode}/> : current.kind === 'image' ? <PreviewControls label={tr("Image")} zoom={imageSize} onZoom={setImageSize}/> : null; const actions = <><div className="preview-file-actions__inline">{tr(current.kind === 'code' ? <CopyBtn text={text} label="Code" title="Copy code" disabled={loading || !!error}/> : null)}{tr(url ? <a className="st-btn st-btn--icon" href={url} target="_blank" rel="noreferrer" aria-label={tr("Open outside preview")} title={tr("Open outside preview")}><Icon name="link" size={17}/></a> : null)}<IconBtn name="refresh" title={tr("Reload preview")} onClick={() => setRevision(v => v + 1)}/></div><button ref={fileMenuRef} className="st-btn st-btn--icon preview-file-actions__more" aria-label={tr("Preview file actions")} title={tr("Preview file actions")} aria-haspopup="menu" aria-expanded={fileMenu} onClick={() => setFileMenu(v => !v)}><Icon name="ellipsis"/></button></>; const actionMenu = fileMenu ? <FloatingMenu anchor={fileMenuRef.current} title={tr("Preview file actions")} onClose={() => setFileMenu(false)}>{tr(current.kind === 'code' ? <CopyMenuItem text={text} label="Code" disabled={loading || !!error} onClose={() => setFileMenu(false)}>Copy code</CopyMenuItem> : null)}{tr(url ? <a role="menuitem" className="menu__item" href={url} target="_blank" rel="noreferrer" onClick={() => setFileMenu(false)}><Icon name="link"/>{tr("Open outside preview")}</a> : null)}<button role="menuitem" className="menu__item" onClick={() => { setRevision(v => v + 1); setFileMenu(false); }}><Icon name="refresh"/>{tr("Reload preview")}</button></FloatingMenu> : null; const content = <aside className="artifact-panel" aria-label={tr("{0} preview", [current.kind])}> {tr(!inline ? <ArtifactTabs onCloseTab={onCloseTab} items={items} selected={selected} onSelect={onSelect}/> : null)} - <div id="artifact-content" role="tabpanel" aria-labelledby={`artifact-tab-${items.findIndex(a => a.id === selected)}`} className="artifact-content"> + <div key={current.id} id="artifact-content" role="tabpanel" aria-labelledby={`artifact-tab-${items.findIndex(a => a.id === selected)}`} className="artifact-content"> {tr(current.kind === 'website' ? <><iframe key={`${current.id}-${revision}`} title={current.title} src={current.content ? undefined : url ?? undefined} srcDoc={current.content} sandbox="allow-scripts" referrerPolicy="no-referrer"/></> : current.kind === 'pdf' ? url ? <Suspense fallback={<p className="muted preview-placeholder">{tr("Opening PDF viewer\u2026")}</p>}><PdfPreview key={`${current.id}-${revision}`} url={url}/></Suspense> : <p>{tr("No PDF to display.")}</p> : current.kind === 'image' ? <div className="image-preview" data-size={imageSize === '1' ? 'actual' : 'fit'}>{tr(url ? <img key={`${current.id}-${revision}`} src={url} alt={current.title} onError={() => setError('Couldn’t load this image.')}/> : null)}{tr(error ? <p role="alert">{tr(error)}</p> : null)}</div> : loading ? <p className="muted preview-placeholder">{tr("Loading document\u2026")}</p> : error ? <p role="alert" className="inline-error preview-placeholder">{tr(error)}</p> : current.kind === 'code' ? <SyntaxCode text={text} filename={artifactFilename(current)} lineNumbers/> : current.kind === 'table' ? <TablePreview key={current.id} text={text}/> : mode === 'source' ? <SyntaxCode text={text} language="markdown" lineNumbers/> : <article className="document-markdown"><Markdown text={text}/></article>)} </div> {tr(viewControls ? <div className="artifact-view-controls">{tr(viewControls)}</div> : null)} diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index c7a8c599a3..f0c4ff9c23 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -10,7 +10,7 @@ import { ChatTelemetry } from '../components/TelemetryPopover'; import { ArtifactCard } from '../components/ArtifactCard'; import { ChatMedia } from '../components/ChatMedia'; import { closePreviewTab } from '../lib/preview-tabs'; -import { setSelectedPreviewId } from '../lib/code-preview'; +import { mainCodePreview, setSelectedPreviewId } from '../lib/code-preview'; import { ArtifactPanel } from '../components/ArtifactPanel'; import { PreviewResizeHandle } from '../components/PreviewResizeHandle'; import { DEFAULT_PREVIEW_FRACTION, PREVIEW_SPLIT_KEY, previewWidth } from '../lib/preview-layout'; @@ -197,7 +197,8 @@ export function ChatScreen() { replyWasStreaming.current.set(lastReply.id, !!lastReply.streaming); if (before !== true || lastReply.streaming || lastReply.error) return; const main = mainResult(lastReply.deliverables, lastReply.content); - if (!main) return; + // No file to open: one whole HTML page in the answer goes to the sidebar too (a snippet keeps its preview button). + if (!main) { const page = lastReply.blocks?.some(b => b.kind === 'group') ? null : mainCodePreview(lastReply.id, lastReply.content); if (page) openPreview(page); return; } const sessionId = session.id; void previewOf(sessionId, main).then(item => { if (session.id === sessionId) openPreview(item); }, () => { }); }, [lastReply?.id, lastReply?.streaming]); diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index 77ba981fde..3bdd1f2a36 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -1059,6 +1059,7 @@ body { line-height: 1.2; padding-top: 2px; } + /* ------------------------------------------------ 17. the motion system ----- One scale (app.css section 1: micro 100, control 160, local 240, surface 320, choreo 460ms; standard / enter / exit curves) and three habits, so the app @@ -1175,6 +1176,45 @@ body { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--st-accent) 45%, transparent); } +/* The sidebar preview arrives from the right with a short rise and fade, the + chosen file's content crossfades when you switch tabs, and a closed panel + leaves the same way (a bare shell over the column it vacated; the page itself + is already gone, so nothing heavy is animated). */ +.chatsplit .artifact-panel { + animation: st-panel-in var(--st-t-surface) var(--st-ease-enter) both; +} +.chatsplit .artifact-panel[data-leaving] { + position: absolute; + inset: 0 0 0 auto; + width: min(48%, 640px); + z-index: 3; + pointer-events: none; + animation: st-panel-out var(--st-t-local) var(--st-ease-exit) both; +} +.artifact-content { + animation: st-enter var(--st-t-control) var(--st-ease-enter) both; + --st-from-y: 4px; +} +@keyframes st-panel-in { + from { + opacity: 0; + transform: translateX(var(--st-panel-shift)); + } + to { + opacity: 1; + transform: none; + } +} +@keyframes st-panel-out { + from { + opacity: 1; + transform: none; + } + to { + opacity: 0; + transform: translateX(var(--st-panel-shift)); + } +} .st-code__actions { display: inline-flex; align-items: center; diff --git a/apps/host/tests/chat-details.test.mjs b/apps/host/tests/chat-details.test.mjs new file mode 100644 index 0000000000..39cd1901c8 --- /dev/null +++ b/apps/host/tests/chat-details.test.mjs @@ -0,0 +1,65 @@ +/** Second batch of the owner's chat feedback: reasoning that opens smoothly, code blocks, the preview icon button, the sidebar preview's motion. */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { transform } from 'esbuild'; + +const read = p => readFile(new URL(`../${p}`, import.meta.url), 'utf8'); +const { code } = await transform((await read('src/lib/code-preview.ts')).replace("import { useSyncExternalStore } from 'react';", 'const useSyncExternalStore = () => null;').replace("import type { PreviewArtifact } from './artifacts';", ''), { loader: 'ts', format: 'esm' }); +const lib = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +const liquid = await read('src/styles/liquid.css'); + +test('only HTML and Markdown blocks have a preview; each block has its own stable id', () => { + assert.equal(lib.codePreviewKind('html'), 'website'); + assert.equal(lib.codePreviewKind('HTML'), 'website'); + assert.equal(lib.codePreviewKind('md'), 'markdown'); + assert.equal(lib.codePreviewKind('markdown'), 'markdown'); + assert.equal(lib.codePreviewKind('bash'), null); + const a = lib.codePreview('m1', 'html', '<p>a</p>'), b = lib.codePreview('m1', 'html', '<p>b</p>'); + assert.notEqual(a.id, b.id, 'two blocks in one answer are two previews'); + assert.equal(a.id, lib.codePreview('m1', 'html', '<p>a</p>').id, 'the same block keeps its id'); + assert.equal(lib.codePreview('m1', 'bash', 'ls'), null); +}); + +test('a finished answer with exactly one whole HTML page goes to the sidebar by itself; snippets and several blocks do not', () => { + const page = '<!doctype html>\n<html><body>hi</body></html>'; + assert.equal(lib.mainCodePreview('m', `Here:\n\n\`\`\`html\n${page}\n\`\`\`\n`)?.kind, 'website'); + assert.equal(lib.mainCodePreview('m', 'A snippet:\n\n```html\n<b>x</b>\n```\n'), null); + assert.equal(lib.mainCodePreview('m', `\`\`\`html\n${page}\n\`\`\`\n\n\`\`\`html\n${page}\n\`\`\`\n`), null); + assert.equal(lib.mainCodePreview('m', 'Notes:\n\n```markdown\n# a\n```\n'), null, 'Markdown blocks keep the button only'); +}); + +test('the code block has an icon preview button left of Copy, with an open state, and no text button', async () => { + const md = await read('src/components/Markdown.tsx'), btn = await read('src/components/CodePreviewBtn.tsx'); + assert.ok(!/<Btn[^>]*>\{tr\("Open preview"\)/.test(md), 'no text button'); + assert.ok(md.indexOf('<CodePreviewBtn') < md.indexOf('<CopyBtn'), 'preview first, copy after it'); + assert.match(btn, /aria-pressed=\{open\}/); + assert.match(btn, /tr\(open \? 'Close preview' : 'Open preview'\)/); + assert.match(liquid, /\.st-code \.st-btn--icon\[data-open\]/); +}); + +test('reasoning opens by growing and fading, the line above never moves, and it has hover and press feedback', () => { + assert.match(liquid, /\.rz::details-content \{[^}]*block-size: 0;[^}]*opacity: 0;/); + assert.match(liquid, /\.rz\[open\]::details-content \{[^}]*block-size: auto;[^}]*opacity: 1;/); + assert.match(liquid, /\.rz > summary:hover \{[^}]*--st-fill-hover/); + assert.match(liquid, /\.rz > summary:active \{[^}]*--st-fill-press/); + assert.match(liquid, /\.rz__body \{[^}]*border-left: 2px solid/); +}); + +test('code blocks have room after them and are lighter than the text; the 12px floor of pass 37 is untouched', async () => { + assert.match(liquid, /\.st-bubble \.st-code \{\s*margin: 16px 0 20px;/); + assert.match(liquid, /\.st-code__head \{\s*min-height: 34px;/); + const app = await read('src/styles/app.css'); + assert.match(app, /--st-fs-read-sm: max\(12px, calc\(var\(--st-content-fs, 14px\) \* \.8125\)\);/); +}); + +test('the sidebar preview comes in and goes out with motion, from the one motion scale, and the reduced-motion gate zeroes the distance', () => { + assert.match(liquid, /\.chatsplit \.artifact-panel \{\s*animation: st-panel-in var\(--st-t-surface\) var\(--st-ease-enter\) both;/); + assert.match(liquid, /\[data-leaving\] \{[^}]*animation: st-panel-out var\(--st-t-local\) var\(--st-ease-exit\) both;/); + assert.match(liquid, /@media \(prefers-reduced-motion: reduce\) \{\s*:root \{ --st-press-scale: 1; --st-panel-shift: 0px; \}/); +}); + +test('only the layer-safe properties move: no transition on width, height or margin in the motion section', () => { + const section = liquid.slice(liquid.indexOf('17. the motion system')); + assert.ok(!/transition:[^;]*\b(width|height|margin|top|left)\b/.test(section)); +}); From d2c11867c0bf38a9d58fcca7aef0524f4d88c48b Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:04:58 +0100 Subject: [PATCH 14/59] Version list: only the chosen base model, recommendation and downloaded versions on top, the rest folded below, a Fits / Fits with SSD streaming word per row --- apps/host/scripts/make-pick-locales.py | 25 +++++++- apps/host/src/components/NativeModels.tsx | 2 +- apps/host/src/components/VersionPicker.tsx | 53 ++++++++-------- apps/host/src/lib/native-fit.ts | 26 +++++--- apps/host/src/locales/pick-de.json | 19 ++++-- apps/host/src/locales/pick-en.json | 19 ++++-- apps/host/src/locales/pick-es.json | 19 ++++-- apps/host/src/locales/pick-fr.json | 19 ++++-- apps/host/src/locales/pick-ja.json | 19 ++++-- apps/host/src/locales/pick-ko.json | 19 ++++-- apps/host/src/locales/pick-pt.json | 19 ++++-- apps/host/src/locales/pick-ru.json | 19 ++++-- apps/host/src/locales/pick-zh.json | 19 ++++-- apps/host/src/styles/app.css | 8 ++- apps/host/tests/version-picker.test.mjs | 70 +++++++++++++--------- 15 files changed, 243 insertions(+), 112 deletions(-) diff --git a/apps/host/scripts/make-pick-locales.py b/apps/host/scripts/make-pick-locales.py index 1118098afa..3519d32995 100644 --- a/apps/host/scripts/make-pick-locales.py +++ b/apps/host/scripts/make-pick-locales.py @@ -21,8 +21,12 @@ add("Needs {0} of memory", add("Needs {0} of memory and about {1} GB of disk", "需要 {0} 内存和约 {1} GB 磁盘空间", "{0} のメモリーと約 {1} GB のディスク容量が必要", "Braucht {0} Speicher und etwa {1} GB Festplattenplatz", "Necesita {0} de memoria y unos {1} GB de disco", "Нужно {0} памяти и около {1} ГБ на диске", "Precisa de {0} de memória e cerca de {1} GB de disco", "메모리 {0}와 디스크 약 {1} GB 필요", "Nécessite {0} de mémoire et environ {1} Go de disque") -add("Slower on this computer", - "在这台电脑上较慢", "このコンピューターでは遅くなります", "Auf diesem Computer langsamer", "Más lento en este equipo", "На этом компьютере медленнее", "Mais lento neste computador", "이 컴퓨터에서는 더 느립니다", "Plus lent sur cet ordinateur") +add("Fits", + "可以运行", "問題なく動きます", "Passt", "Cabe", "Помещается", "Cabe", "문제없이 실행됩니다", "Tient") +add("Fits with SSD streaming", + "可以运行,部分内容从 SSD 读取", "SSD から読み込みながら動きます", "Passt mit SSD-Streaming", "Cabe con streaming desde el SSD", "Помещается с потоковой подгрузкой с SSD", "Cabe com streaming do SSD", "SSD 스트리밍으로 실행됩니다", "Tient avec streaming depuis le SSD") +add("Doesn't fit", + "放不下", "収まりません", "Passt nicht", "No cabe", "Не помещается", "Não cabe", "맞지 않습니다", "Ne tient pas") add("Show details", "显示详情", "詳細を表示", "Details anzeigen", "Mostrar detalles", "Показать подробности", "Mostrar detalhes", "자세히 보기", "Afficher les détails") add("Hide details", @@ -33,6 +37,23 @@ add("{0} RAM + VRAM", add("Close preview", "关闭预览", "プレビューを閉じる", "Vorschau schließen", "Cerrar vista previa", "Закрыть предпросмотр", "Fechar pré-visualização", "미리보기 닫기", "Fermer l'aperçu") +add("Free right now", + "当前可用", "現在の空き", "Gerade frei", "Libre ahora", "Свободно сейчас", "Livre agora", "지금 비어 있음", "Libre en ce moment") +add("{0} free", + "可用 {0}", "空き {0}", "{0} frei", "{0} libres", "свободно {0}", "{0} livres", "{0} 사용 가능", "{0} libres") +add("{0}: {1} free of {2}", + "{0}:{2} 中有 {1} 可用", "{0}:{2} のうち {1} が空き", "{0}: {1} frei von {2}", "{0}: {1} libres de {2}", "{0}: свободно {1} из {2}", "{0}: {1} livres de {2}", "{0}: {2} 중 {1} 사용 가능", "{0} : {1} libres sur {2}") +add("It takes about", + "它大约占用", "使用量の目安", "Es belegt etwa", "Ocupa aproximadamente", "Занимает примерно", "Ocupa cerca de", "대략 사용하는 양", "Il occupe environ") +add("Nothing. It fits in memory.", + "没有。它完全放得进内存。", "ありません。すべてメモリーに収まっています。", "Nichts. Es passt in den Speicher.", "Nada. Cabe en la memoria.", "Ничего. Всё помещается в память.", "Nada. Cabe na memória.", "없음. 메모리에 모두 들어갑니다.", "Rien. Tout tient en mémoire.") +add("Reading from your SSD now: {0}", + "此刻正从 SSD 读取:{0}", "現在 SSD から読み込み中:{0}", "Gerade vom SSD gelesen: {0}", "Leyendo del SSD ahora: {0}", "Сейчас читается с SSD: {0}", "Lendo do SSD agora: {0}", "지금 SSD에서 읽는 중: {0}", "Lecture depuis le SSD en cours : {0}") +add("This version would take about {0} of graphics memory and {1} of RAM.", + "这个版本大约会占用 {0} 显存和 {1} 内存。", "このバージョンはグラフィックスメモリーを約 {0}、RAM を約 {1} 使います。", "Diese Version würde etwa {0} Grafikspeicher und {1} RAM belegen.", + "Esta versión ocuparía aproximadamente {0} de memoria gráfica y {1} de RAM.", "Эта версия займёт примерно {0} видеопамяти и {1} оперативной памяти.", "Esta versão ocuparia cerca de {0} de memória gráfica e {1} de RAM.", + "이 버전은 그래픽 메모리 약 {0}와 RAM 약 {1}을 사용합니다.", "Cette version occuperait environ {0} de mémoire graphique et {1} de RAM.") + here = Path(__file__).resolve().parent.parent / "src" / "locales" NBSP = " " diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index b0037c4b93..82a67e55cb 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(selectedSize ? <> <div className="native-choice__head"><span className="native-choice__label">{tr("Version")}</span><span className="native-choice__tools"><NativePresets values={values} onApply={v => { const f = families.find(f => f.family === v.family || f.sizes.some(s => s.sourceFamily === v.family)); if (!f) return; presetPending.current = true; setFamily(f.family); setSize(f.sizes.find(s => s.model === v.model && (s.sourceFamily === v.family || f.family === v.family))?.id ?? ''); setContext(v.context ?? 32768); setVision(v.vision ?? 'no'); setKv(v.kv ?? 'int8'); setLowRam(v.low_ram ?? 'auto'); }}/><Btn icon="models" size="sm" variant="ghost" onClick={() => setManage(true)}>{tr("Manage models")}</Btn></span></div> - <div className="native-version"><VersionPicker pick={native?.catalog?.recommendation} versions={allSizes} models={families} details={expert} selectedId={selectedSize.id} hardware={fitHardware} downloaded={readyIds} onSelect={id => { const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/></div> + <div className="native-version"><VersionPicker pick={native?.catalog?.recommendation} versions={selectedFamily?.sizes ?? []} details={expert} selectedId={selectedSize.id} hardware={fitHardware} downloaded={readyIds} onSelect={id => { const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/></div> {tr(noFit ? <p className="small muted native-spill-note"><Icon name="disk" size={16}/>{tr("May run slower \u00B7 Model data can be read from SSD.")}</p> : null)} {tr(selectedSize?.multi_file && deepseekContextNote(context) ? <p className="small muted native-spill-note"><Icon name="info" size={16}/>{tr(deepseekContextNote(context))}</p> : null)} <div className="native-choice__row"> diff --git a/apps/host/src/components/VersionPicker.tsx b/apps/host/src/components/VersionPicker.tsx index 16bc9a903e..c2a0d221b8 100644 --- a/apps/host/src/components/VersionPicker.tsx +++ b/apps/host/src/components/VersionPicker.tsx @@ -3,9 +3,9 @@ import { tr } from '../lib/i18n'; import { Icon } from './ui'; import { FloatingMenu } from './FloatingMenu'; import { cx } from '../lib/format'; -import { nativeVersionLabel, versionNote, type CatalogVersion } from '../lib/native-catalog'; +import { versionNote, type CatalogVersion } from '../lib/native-catalog'; import { nvfp4Version } from '../lib/native-names'; -import { fitOn, recommendedVersions, versionSections, PICK_NOTE, type FitHardware, type PcPick } from '../lib/native-fit'; +import { fitOn, recommendedVersions, versionFit, versionGroups, PICK_NOTE, type FitHardware, type PcPick } from '../lib/native-fit'; /** The name a version goes by in the list: the quantization, with the maker only where the quantization alone would be ambiguous. */ export function versionName(v: CatalogVersion): string { @@ -24,22 +24,16 @@ const MAKERS: Record<string, string> = { qwen: 'GSQ-RCO', coder: 'GSQ-RCO', swif const gb = (n: number) => `${Number.isInteger(n) ? n : n.toFixed(1)} GB`; const whole = (n: number) => `${Math.round(n)} GB`; -/** A short plain word for the version ("High quality"), empty where the name is all there is. */ -function plainLabel(v: CatalogVersion): string { - const label = nativeVersionLabel(v.model); - return label && label !== v.model && label !== versionName(v) ? label : ''; -} - /** - * Where the versions are listed: one row per version, each exactly once. The name is the main thing, with a plain word beside it - * ("High quality") and small tags (Recommended, Downloaded); under it, what it costs: the download and the memory it needs. The maker, - * the RAM + VRAM split and the SSD figure are behind "Show details" (open from the start in Expert mode). Rows are in order of size - * inside each model (by download size), and the pick for this PC comes first. With more than one model the sections carry the model name, small and quiet. + * Where the versions of the chosen base model are listed, each exactly once. At the top: our recommendation for this PC and the versions already + * downloaded (a downloaded version carries "Downloaded", and "Recommended" only while it is not yet downloaded). Below, folded under "More + * versions": all the others. A row is the name, small tags, whether it fits this PC ("Fits", "Fits with SSD streaming", "Doesn't fit": from the + * same fit figures as the This computer card) and the size. The maker, the memory it needs and the SSD figure are behind "Show details" + * (open from the start in Expert mode). The other base models are not in this list: they appear when picked at the top of the page. */ -export function VersionPicker({ versions, models, selectedId, hardware, onSelect, onOwnGguf, downloaded, showRecommended = true, moreLabel, pick, details: detailsOpen = false }: { +export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnGguf, downloaded, showRecommended = true, moreLabel, pick, details: detailsOpen = false }: { + /** The versions of the chosen base model. */ versions: CatalogVersion[]; - /** The models the versions belong to, in the order shown (each version appears under exactly one); without it the versions are one list. */ - models?: { family: string; title: string; sizes: CatalogVersion[] }[]; selectedId: string; hardware: FitHardware | null | undefined; onSelect: (id: string) => void; @@ -50,7 +44,7 @@ export function VersionPicker({ versions, models, selectedId, hardware, onSelect showRecommended?: boolean; /** What the button says while the selected version is one of the recommended ones shown elsewhere. */ moreLabel?: string; - /** The engine's own pick for this PC (catalog.recommendation); it comes first, tagged Recommended. */ + /** The engine's own pick for this PC (catalog.recommendation). */ pick?: PcPick | null; /** Start with the technical detail shown (Expert mode). */ details?: boolean; @@ -64,8 +58,11 @@ export function VersionPicker({ versions, models, selectedId, hardware, onSelect const rows = recommendedVersions(versions, pick); const apart = new Set(showRecommended ? [] : rows.map(x => x.v.id)); const pickId = rows.find(x => x.r.note === PICK_NOTE)?.v.id; - const sections = versionSections(versions, models, apart, pickId); + const { top, more } = versionGroups(versions, apart, downloaded, pickId); const shown = selected && !apart.has(selected.id) ? selected : undefined; + // The folded part opens by itself when it holds the chosen version or when there is nothing above it. + const [moreOpen, setMoreOpen] = useState(false); + const foldedOpen = moreOpen || !top.length || more.some(v => v.id === selectedId); const need = (v: CatalogVersion, technical: boolean) => { const fit = fitOn(v, hardware); @@ -74,17 +71,18 @@ export function VersionPicker({ versions, models, selectedId, hardware, onSelect }; const row = (v: CatalogVersion) => { const fit = fitOn(v, hardware); - const on = v.id === selectedId; - const word = plainLabel(v), note = versionNote(v.model); - const slow = fit.known && fit.spillGb >= 1; - const technical = [MAKERS[v.sourceFamily], need(v, true), slow ? tr("Uses SSD {0} GB", [Math.round(fit.spillGb)]) : ''].filter(Boolean).join(' · '); + const on = v.id === selectedId, have = !!downloaded?.has(v.id), recommended = v.id === pickId && !have; + const state = versionFit(v, hardware); + const technical = [MAKERS[v.sourceFamily], need(v, true), state === 'ssd' ? tr("Uses SSD {0} GB", [Math.round(fit.spillGb)]) : ''].filter(Boolean).join(' · '); + const note = versionNote(v.model); return <button key={v.id} role="menuitemradio" aria-checked={on} className={cx('version-row', on && 'is-on')} onClick={() => { onSelect(v.id); setOpen(false); }}> <span className="version-row__check">{tr(on ? <Icon name="check" size={14}/> : null)}</span> <span className="version-row__body"> - <span className="version-row__title"><strong>{versionName(v)}</strong>{tr(word ? <span className="version-row__word">{word}</span> : null)}{tr(v.id === pickId || downloaded?.has(v.id) ? <span className="version-row__tags">{tr(v.id === pickId ? <span className="version-tag version-tag--pick">{tr("Recommended")}</span> : null)}{tr(downloaded?.has(v.id) ? <span className="version-tag version-tag--have">{tr("Downloaded")}</span> : null)}</span> : null)}{tr(slow ? <span className="version-row__slow">{tr("Slower on this computer")}</span> : null)}</span> + <span className="version-row__title"><strong>{versionName(v)}</strong>{tr(recommended || have ? <span className="version-row__tags">{tr(recommended ? <span className="version-tag version-tag--pick">{tr("Recommended")}</span> : null)}{tr(have ? <span className="version-tag version-tag--have">{tr("Downloaded")}</span> : null)}</span> : null)}</span> + {tr(state !== 'unknown' ? <span className="version-row__fit" data-fit={state}>{tr(state === 'fits' ? 'Fits' : state === 'ssd' ? 'Fits with SSD streaming' : "Doesn't fit")}</span> : null)} {tr(details ? <span className="version-row__tech">{technical}{tr(note ? <><br/>{note}</> : null)}</span> : null)} </span> - <span className="version-row__size">{downloaded?.has(v.id) ? gb(v.download_gb) : tr("{0} download", [gb(v.download_gb)])}</span> + <span className="version-row__size">{have ? gb(v.download_gb) : tr("{0} download", [gb(v.download_gb)])}</span> </button>; }; // The open menu opens on the chosen version, not at the top of a long list. @@ -98,10 +96,11 @@ export function VersionPicker({ versions, models, selectedId, hardware, onSelect </button> {tr(open ? <FloatingMenu anchor={trigger.current} title={tr("Model version")} width={520} onClose={() => setOpen(false)}> <div className="version-menu" ref={menu}> - {tr(sections.map(s => <div className="version-section" role="group" aria-label={s.title || tr("Model version")} key={s.id}> - {tr(s.title ? <div className="version-section__title" aria-hidden="true">{s.title}</div> : null)} - {tr(s.versions.map(row))} - </div>))} + {tr(top.length ? <div className="version-section" role="group" aria-label={tr("Model version")}>{tr(top.map(row))}</div> : null)} + {tr(more.length ? <div className="version-section" role="group" aria-label={tr("More versions")}> + {tr(top.length ? <button role="menuitem" className="version-more" aria-expanded={foldedOpen} onClick={() => setMoreOpen(!foldedOpen)}><span>{tr("More versions")} <span className="muted">{more.length}</span></span><Icon name="chevron" size={14} className={cx('version-more__chev', foldedOpen && 'is-open')}/></button> : null)} + {tr(foldedOpen ? <div className="version-more__rows">{tr(more.map(row))}</div> : null)} + </div> : null)} <div className="version-foot"> <button role="menuitem" className="version-foot__btn" onClick={() => { setOpen(false); onOwnGguf(); }}><Icon name="folder" size={14}/>{tr("Use your own GGUF…")}</button> <button role="menuitem" className="version-foot__btn" aria-pressed={details} onClick={() => setDetails(d => !d)}>{tr(details ? "Hide details" : "Show details")}</button> diff --git a/apps/host/src/lib/native-fit.ts b/apps/host/src/lib/native-fit.ts index fd98e365f5..0f08e96108 100644 --- a/apps/host/src/lib/native-fit.ts +++ b/apps/host/src/lib/native-fit.ts @@ -102,15 +102,27 @@ export function recommendedVersions<V extends { sourceFamily: string; model: str } /** - * The version list as the menu shows it: one section per model (a single unnamed one without `models`), each version exactly once, in order of - * download size with the pick for this PC first; the versions in `hidden` (shown elsewhere) are left out. A model with nothing to show has no section. + * The version list as the menu shows it, for one base model: first the versions to look at (the pick for this PC, then the ones already on this + * computer, each by download size), then every other version by download size. A version is in exactly one of the two, so none is shown twice + * and none is lost; the ones in `hidden` (shown elsewhere, as on the first-run page) are left out. */ -export function versionSections<V extends { id: string; download_gb: number }>(versions: V[], models: { family: string; title: string; sizes: V[] }[] | undefined, hidden: ReadonlySet<string>, pickId?: string): { id: string; title: string; versions: V[] }[] { - const rank = (v: V) => v.id === pickId ? -1 : v.download_gb; +export function versionGroups<V extends { id: string; download_gb: number }>(versions: V[], hidden: ReadonlySet<string>, downloaded: ReadonlySet<string> | undefined, pickId?: string): { top: V[]; more: V[] } { const seen = new Set<string>(); - return (models ?? [{ family: 'all', title: '', sizes: versions }]) - .map(m => ({ id: m.family, title: models && models.length > 1 ? m.title : '', versions: m.sizes.filter(v => !hidden.has(v.id) && !seen.has(v.id) && !!seen.add(v.id)).map((v, at) => ({ v, at })).sort((a, b) => rank(a.v) - rank(b.v) || a.at - b.at).map(x => x.v) })) - .filter(s => s.versions.length); + const list = versions.filter(v => !hidden.has(v.id) && !seen.has(v.id) && !!seen.add(v.id)); + const bySize = (a: V, b: V) => a.download_gb - b.download_gb; + const pick = list.find(v => v.id === pickId); + const have = list.filter(v => v.id !== pickId && downloaded?.has(v.id)).sort(bySize); + const top = [...(pick ? [pick] : []), ...have]; + const inTop = new Set(top.map(v => v.id)); + return { top, more: list.filter(v => !inTop.has(v.id)).sort(bySize) }; +} + +/** What a version is on this computer, in the words the list shows: from the same fit figures the card uses, and the engine's own "does not fit". */ +export type VersionFit = 'fits' | 'ssd' | 'no' | 'unknown'; +export function versionFit(v: FitInput & { on_this_pc?: string | null }, hw: FitHardware | null | undefined): VersionFit { + if (v.on_this_pc === 'does not fit') return 'no'; + const fit = fitOn(v, hw); + return !fit.known ? 'unknown' : fit.spillGb >= 1 ? 'ssd' : 'fits'; } /** A card as the installer's hardware report lists it. */ diff --git a/apps/host/src/locales/pick-de.json b/apps/host/src/locales/pick-de.json index a113a6baaf..cd816aca30 100644 --- a/apps/host/src/locales/pick-de.json +++ b/apps/host/src/locales/pick-de.json @@ -2,9 +2,18 @@ "vp01": "{0} Download", "vp02": "Braucht {0} Speicher", "vp03": "Braucht {0} Speicher und etwa {1} GB Festplattenplatz", - "vp04": "Auf diesem Computer langsamer", - "vp05": "Details anzeigen", - "vp06": "Details ausblenden", - "vp07": "{0} RAM + VRAM", - "vp08": "Vorschau schließen" + "vp04": "Passt", + "vp05": "Passt mit SSD-Streaming", + "vp06": "Passt nicht", + "vp07": "Details anzeigen", + "vp08": "Details ausblenden", + "vp09": "{0} RAM + VRAM", + "vp10": "Vorschau schließen", + "vp11": "Gerade frei", + "vp12": "{0} frei", + "vp13": "{0}: {1} frei von {2}", + "vp14": "Es belegt etwa", + "vp15": "Nichts. Es passt in den Speicher.", + "vp16": "Gerade vom SSD gelesen: {0}", + "vp17": "Diese Version würde etwa {0} Grafikspeicher und {1} RAM belegen." } diff --git a/apps/host/src/locales/pick-en.json b/apps/host/src/locales/pick-en.json index 68bffc949e..d5034c2ca9 100644 --- a/apps/host/src/locales/pick-en.json +++ b/apps/host/src/locales/pick-en.json @@ -2,9 +2,18 @@ "vp01": "{0} download", "vp02": "Needs {0} of memory", "vp03": "Needs {0} of memory and about {1} GB of disk", - "vp04": "Slower on this computer", - "vp05": "Show details", - "vp06": "Hide details", - "vp07": "{0} RAM + VRAM", - "vp08": "Close preview" + "vp04": "Fits", + "vp05": "Fits with SSD streaming", + "vp06": "Doesn't fit", + "vp07": "Show details", + "vp08": "Hide details", + "vp09": "{0} RAM + VRAM", + "vp10": "Close preview", + "vp11": "Free right now", + "vp12": "{0} free", + "vp13": "{0}: {1} free of {2}", + "vp14": "It takes about", + "vp15": "Nothing. It fits in memory.", + "vp16": "Reading from your SSD now: {0}", + "vp17": "This version would take about {0} of graphics memory and {1} of RAM." } diff --git a/apps/host/src/locales/pick-es.json b/apps/host/src/locales/pick-es.json index 0fa83985c1..b5cf8012eb 100644 --- a/apps/host/src/locales/pick-es.json +++ b/apps/host/src/locales/pick-es.json @@ -2,9 +2,18 @@ "vp01": "Descarga de {0}", "vp02": "Necesita {0} de memoria", "vp03": "Necesita {0} de memoria y unos {1} GB de disco", - "vp04": "Más lento en este equipo", - "vp05": "Mostrar detalles", - "vp06": "Ocultar detalles", - "vp07": "{0} de RAM + VRAM", - "vp08": "Cerrar vista previa" + "vp04": "Cabe", + "vp05": "Cabe con streaming desde el SSD", + "vp06": "No cabe", + "vp07": "Mostrar detalles", + "vp08": "Ocultar detalles", + "vp09": "{0} de RAM + VRAM", + "vp10": "Cerrar vista previa", + "vp11": "Libre ahora", + "vp12": "{0} libres", + "vp13": "{0}: {1} libres de {2}", + "vp14": "Ocupa aproximadamente", + "vp15": "Nada. Cabe en la memoria.", + "vp16": "Leyendo del SSD ahora: {0}", + "vp17": "Esta versión ocuparía aproximadamente {0} de memoria gráfica y {1} de RAM." } diff --git a/apps/host/src/locales/pick-fr.json b/apps/host/src/locales/pick-fr.json index d1138c9eff..4240e29cba 100644 --- a/apps/host/src/locales/pick-fr.json +++ b/apps/host/src/locales/pick-fr.json @@ -2,9 +2,18 @@ "vp01": "Téléchargement de {0}", "vp02": "Nécessite {0} de mémoire", "vp03": "Nécessite {0} de mémoire et environ {1} Go de disque", - "vp04": "Plus lent sur cet ordinateur", - "vp05": "Afficher les détails", - "vp06": "Masquer les détails", - "vp07": "{0} de RAM + VRAM", - "vp08": "Fermer l’aperçu" + "vp04": "Tient", + "vp05": "Tient avec streaming depuis le SSD", + "vp06": "Ne tient pas", + "vp07": "Afficher les détails", + "vp08": "Masquer les détails", + "vp09": "{0} de RAM + VRAM", + "vp10": "Fermer l’aperçu", + "vp11": "Libre en ce moment", + "vp12": "{0} libres", + "vp13": "{0} : {1} libres sur {2}", + "vp14": "Il occupe environ", + "vp15": "Rien. Tout tient en mémoire.", + "vp16": "Lecture depuis le SSD en cours : {0}", + "vp17": "Cette version occuperait environ {0} de mémoire graphique et {1} de RAM." } diff --git a/apps/host/src/locales/pick-ja.json b/apps/host/src/locales/pick-ja.json index e99e3c2327..780b75d5c9 100644 --- a/apps/host/src/locales/pick-ja.json +++ b/apps/host/src/locales/pick-ja.json @@ -2,9 +2,18 @@ "vp01": "ダウンロード {0}", "vp02": "{0} のメモリーが必要", "vp03": "{0} のメモリーと約 {1} GB のディスク容量が必要", - "vp04": "このコンピューターでは遅くなります", - "vp05": "詳細を表示", - "vp06": "詳細を隠す", - "vp07": "{0} の RAM + VRAM", - "vp08": "プレビューを閉じる" + "vp04": "問題なく動きます", + "vp05": "SSD から読み込みながら動きます", + "vp06": "収まりません", + "vp07": "詳細を表示", + "vp08": "詳細を隠す", + "vp09": "{0} の RAM + VRAM", + "vp10": "プレビューを閉じる", + "vp11": "現在の空き", + "vp12": "空き {0}", + "vp13": "{0}:{2} のうち {1} が空き", + "vp14": "使用量の目安", + "vp15": "ありません。すべてメモリーに収まっています。", + "vp16": "現在 SSD から読み込み中:{0}", + "vp17": "このバージョンはグラフィックスメモリーを約 {0}、RAM を約 {1} 使います。" } diff --git a/apps/host/src/locales/pick-ko.json b/apps/host/src/locales/pick-ko.json index 8ebffe201f..96181dfe4d 100644 --- a/apps/host/src/locales/pick-ko.json +++ b/apps/host/src/locales/pick-ko.json @@ -2,9 +2,18 @@ "vp01": "다운로드 {0}", "vp02": "메모리 {0} 필요", "vp03": "메모리 {0}와 디스크 약 {1} GB 필요", - "vp04": "이 컴퓨터에서는 더 느립니다", - "vp05": "자세히 보기", - "vp06": "자세히 숨기기", - "vp07": "RAM + VRAM {0}", - "vp08": "미리보기 닫기" + "vp04": "문제없이 실행됩니다", + "vp05": "SSD 스트리밍으로 실행됩니다", + "vp06": "맞지 않습니다", + "vp07": "자세히 보기", + "vp08": "자세히 숨기기", + "vp09": "RAM + VRAM {0}", + "vp10": "미리보기 닫기", + "vp11": "지금 비어 있음", + "vp12": "{0} 사용 가능", + "vp13": "{0}: {2} 중 {1} 사용 가능", + "vp14": "대략 사용하는 양", + "vp15": "없음. 메모리에 모두 들어갑니다.", + "vp16": "지금 SSD에서 읽는 중: {0}", + "vp17": "이 버전은 그래픽 메모리 약 {0}와 RAM 약 {1}을 사용합니다." } diff --git a/apps/host/src/locales/pick-pt.json b/apps/host/src/locales/pick-pt.json index 32ca5429b4..fde653c90e 100644 --- a/apps/host/src/locales/pick-pt.json +++ b/apps/host/src/locales/pick-pt.json @@ -2,9 +2,18 @@ "vp01": "Download de {0}", "vp02": "Precisa de {0} de memória", "vp03": "Precisa de {0} de memória e cerca de {1} GB de disco", - "vp04": "Mais lento neste computador", - "vp05": "Mostrar detalhes", - "vp06": "Ocultar detalhes", - "vp07": "{0} de RAM + VRAM", - "vp08": "Fechar pré-visualização" + "vp04": "Cabe", + "vp05": "Cabe com streaming do SSD", + "vp06": "Não cabe", + "vp07": "Mostrar detalhes", + "vp08": "Ocultar detalhes", + "vp09": "{0} de RAM + VRAM", + "vp10": "Fechar pré-visualização", + "vp11": "Livre agora", + "vp12": "{0} livres", + "vp13": "{0}: {1} livres de {2}", + "vp14": "Ocupa cerca de", + "vp15": "Nada. Cabe na memória.", + "vp16": "Lendo do SSD agora: {0}", + "vp17": "Esta versão ocuparia cerca de {0} de memória gráfica e {1} de RAM." } diff --git a/apps/host/src/locales/pick-ru.json b/apps/host/src/locales/pick-ru.json index b0e904391d..f2cf885fdf 100644 --- a/apps/host/src/locales/pick-ru.json +++ b/apps/host/src/locales/pick-ru.json @@ -2,9 +2,18 @@ "vp01": "Загрузка {0}", "vp02": "Нужно {0} памяти", "vp03": "Нужно {0} памяти и около {1} ГБ на диске", - "vp04": "На этом компьютере медленнее", - "vp05": "Показать подробности", - "vp06": "Скрыть подробности", - "vp07": "{0} RAM + VRAM", - "vp08": "Закрыть предпросмотр" + "vp04": "Помещается", + "vp05": "Помещается с потоковой подгрузкой с SSD", + "vp06": "Не помещается", + "vp07": "Показать подробности", + "vp08": "Скрыть подробности", + "vp09": "{0} RAM + VRAM", + "vp10": "Закрыть предпросмотр", + "vp11": "Свободно сейчас", + "vp12": "свободно {0}", + "vp13": "{0}: свободно {1} из {2}", + "vp14": "Занимает примерно", + "vp15": "Ничего. Всё помещается в память.", + "vp16": "Сейчас читается с SSD: {0}", + "vp17": "Эта версия займёт примерно {0} видеопамяти и {1} оперативной памяти." } diff --git a/apps/host/src/locales/pick-zh.json b/apps/host/src/locales/pick-zh.json index b0d5381d6a..32f8a4b098 100644 --- a/apps/host/src/locales/pick-zh.json +++ b/apps/host/src/locales/pick-zh.json @@ -2,9 +2,18 @@ "vp01": "下载 {0}", "vp02": "需要 {0} 内存", "vp03": "需要 {0} 内存和约 {1} GB 磁盘空间", - "vp04": "在这台电脑上较慢", - "vp05": "显示详情", - "vp06": "隐藏详情", - "vp07": "{0} 内存 + 显存", - "vp08": "关闭预览" + "vp04": "可以运行", + "vp05": "可以运行,部分内容从 SSD 读取", + "vp06": "放不下", + "vp07": "显示详情", + "vp08": "隐藏详情", + "vp09": "{0} 内存 + 显存", + "vp10": "关闭预览", + "vp11": "当前可用", + "vp12": "可用 {0}", + "vp13": "{0}:{2} 中有 {1} 可用", + "vp14": "它大约占用", + "vp15": "没有。它完全放得进内存。", + "vp16": "此刻正从 SSD 读取:{0}", + "vp17": "这个版本大约会占用 {0} 显存和 {1} 内存。" } diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index 49d8f5e7f8..473131e0c4 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7047,7 +7047,13 @@ textarea { .version-row__word { font-size: var(--st-fs-sm); color: var(--st-ink-muted); } .version-row__tech { font-size: var(--st-fs-sm); line-height: 1.4; color: var(--st-ink-muted); } .version-row__size { font-size: var(--st-fs-sm); line-height: 20px; color: var(--st-ink-muted); font-variant-numeric: tabular-nums; white-space: nowrap; } -.version-row__slow { font-size: var(--st-fs-xs); color: var(--st-warn-text); } +.version-row__fit { font-size: var(--st-fs-sm); line-height: 1.4; color: var(--st-ink-muted); } +.version-row__fit[data-fit='ssd'], .version-row__fit[data-fit='no'] { color: var(--st-warn-text); } +.version-more { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 8px 10px; border: 0; border-radius: var(--st-r-sm); background: transparent; color: var(--st-ink-soft); font: inherit; font-size: var(--st-fs-sm); font-weight: 600; cursor: pointer; text-align: left; } +.version-more:hover, .version-more:focus-visible { background: var(--st-surface-2); color: var(--st-ink); } +.version-more__chev { transition: transform var(--st-t-local) var(--st-ease-standard); } +.version-more__chev.is-open { transform: rotate(180deg); } +.version-more__rows { animation: st-enter var(--st-t-local) var(--st-ease-enter) both; --st-from-y: -4px; } .version-row__tags { display: inline-flex; flex-wrap: nowrap; gap: 6px; white-space: nowrap; } .version-tag { padding: 0 8px; border-radius: var(--st-r-pill); font-size: var(--st-fs-xs); font-weight: 600; line-height: 20px; white-space: nowrap; } .version-tag--pick { background: var(--st-accent-tint); color: var(--st-accent-text); } diff --git a/apps/host/tests/version-picker.test.mjs b/apps/host/tests/version-picker.test.mjs index 85d6eb7d36..8f49af985a 100644 --- a/apps/host/tests/version-picker.test.mjs +++ b/apps/host/tests/version-picker.test.mjs @@ -1,50 +1,62 @@ -/** The version list: every version once, the pick first, sizes in order, the maker and the memory behind Details. */ +/** The version list: for one base model, the recommendation and the downloaded versions on top, every other version once below, a fit word per row. */ 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/native-fit.ts', import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' }); -const { versionSections, recommendedVersions, PICK_NOTE } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +const { versionGroups, versionFit, recommendedVersions, PICK_NOTE } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); const source = await readFile(new URL('../src/components/VersionPicker.tsx', import.meta.url), 'utf8'); -const v = (sourceFamily, model, download_gb, extra = {}) => ({ id: sourceFamily === 'qwen' ? model.toLowerCase() : `${sourceFamily}-${model.toLowerCase()}`, sourceFamily, model, download_gb, ...extra }); -const qwen38 = { family: 'qwen3.8', title: 'Qwen3.8-Flash-Next', sizes: [v('qwen', 'Q2_0', 66.4), v('qwen', 'IQ2_XS', 68), v('qwen', 'IQ3_XXS', 75.8), v('qwen', 'IQ3_S', 83.6), v('swift', 'IQ2_XS', 68), v('swift', 'IQ3_S', 83.6), v('coder', 'IQ1_M', 58.4), v('unsloth', 'UD-Q4_K_XL', 111.3), v('gyro', 'Gyro-S', 58.5), v('gyro', 'Gyro-M', 92)] }; -const qwen36 = { family: 'qwen3.6', title: 'Qwen3.6-35B-A3B', sizes: [v('qwen36', 'UD-Q4_K_XL', 22.9), v('qwen36', 'Q8_0', 37.8)] }; -const deepseek = { family: 'deepseek41', title: 'DeepSeek-V4.1-Flash', sizes: [v('deepseek41', 'IST-DAS-2.00bpw', 256.8, { multi_file: true, disk_gb: 262.8 }), v('deepseek41', 'IST-DAS-1.75bpw', 239.3, { multi_file: true, disk_gb: 245.3 })] }; -const models = [qwen38, qwen36, deepseek]; -const all = models.flatMap(m => m.sizes); +const v = (sourceFamily, model, download_gb, extra = {}) => ({ id: sourceFamily === 'qwen' ? model.toLowerCase() : `${sourceFamily}-${model.toLowerCase()}`, sourceFamily, model, download_gb, memory_gb: download_gb * 0.62, ...extra }); +const qwen38 = [v('qwen', 'Q2_0', 66.4), v('qwen', 'IQ2_XS', 68), v('qwen', 'IQ3_XXS', 75.8), v('qwen', 'IQ3_S', 83.6), v('swift', 'IQ2_XS', 68), v('swift', 'IQ3_S', 83.6), v('coder', 'IQ1_M', 58.4), v('unsloth', 'UD-Q4_K_XL', 111.3), v('gyro', 'Gyro-S', 58.5), v('gyro', 'Gyro-M', 92)]; +const ids = list => list.map(x => x.id); -test('every version is in the list exactly once (nothing lost, nothing doubled), DeepSeek and Qwen3.6 included', () => { - const sections = versionSections(all, models, new Set(), 'iq3_s'); - const ids = sections.flatMap(s => s.versions.map(x => x.id)); - assert.equal(ids.length, all.length); - assert.deepEqual([...ids].sort(), all.map(x => x.id).sort()); - assert.deepEqual(sections.map(s => s.title), ['Qwen3.8-Flash-Next', 'Qwen3.6-35B-A3B', 'DeepSeek-V4.1-Flash'], 'a model name, small, only where there is more than one model'); +test('top: the recommendation and the downloaded versions; below: all the others; nothing doubled, nothing lost', () => { + const have = new Set(['gyro-gyro-s', 'swift-iq2_xs']); + const { top, more } = versionGroups(qwen38, new Set(), have, 'iq3_s'); + assert.deepEqual(ids(top), ['iq3_s', 'gyro-gyro-s', 'swift-iq2_xs'], 'the pick first, then the downloaded ones by size'); + assert.equal(top.length + more.length, qwen38.length); + assert.deepEqual([...ids(top), ...ids(more)].sort(), ids(qwen38).sort()); + assert.ok(!more.some(x => top.includes(x)), 'a version at the top never appears again below'); + assert.deepEqual(more.map(x => x.download_gb), [...more.map(x => x.download_gb)].sort((a, b) => a - b), 'the others by size'); }); -test('IQ3_S downloaded and recommended shows once, first, not again under a maker group', () => { +test('IQ3_S downloaded and recommended: it is at the top once, as downloaded, and nowhere else', () => { const pick = { family: 'qwen', model: 'IQ3_S', why: '64 GB tier' }; - const pickId = recommendedVersions(all.filter(x => x.sourceFamily !== 'qwen36' && x.sourceFamily !== 'deepseek41'), pick).find(r => r.r.note === PICK_NOTE)?.v.id; + const pickId = recommendedVersions(qwen38, pick).find(r => r.r.note === PICK_NOTE)?.v.id; assert.equal(pickId, 'iq3_s'); - const first = versionSections(all, models, new Set(), pickId)[0].versions; - assert.equal(first[0].id, 'iq3_s'); - assert.equal(first.filter(x => x.model === 'IQ3_S' && x.sourceFamily === 'qwen').length, 1); - assert.deepEqual(first.slice(1).map(x => x.download_gb), [...first.slice(1).map(x => x.download_gb)].sort((a, b) => a - b), 'the rest in order of download size'); + const { top, more } = versionGroups(qwen38, new Set(), new Set(['iq3_s']), pickId); + assert.equal(top[0].id, 'iq3_s'); + assert.equal([...top, ...more].filter(x => x.id === 'iq3_s').length, 1); + assert.match(source, /recommended = v\.id === pickId && !have/, 'the Recommended tag is not shown once it is downloaded'); }); -test('one model: no section title; the first-run list leaves out what it shows elsewhere', () => { - const sections = versionSections(qwen38.sizes, undefined, new Set(['iq3_s', 'gyro-gyro-s'])); - assert.equal(sections.length, 1); - assert.equal(sections[0].title, ''); - assert.ok(!sections[0].versions.some(x => x.id === 'iq3_s' || x.id === 'gyro-gyro-s')); - assert.equal(sections[0].versions.length, qwen38.sizes.length - 2); +test('no downloads and no pick: everything is in the one list below, and the first-run page leaves out what it shows elsewhere', () => { + const { top, more } = versionGroups(qwen38, new Set(['iq3_s', 'gyro-gyro-s']), undefined, undefined); + assert.equal(top.length, 0); + assert.equal(more.length, qwen38.length - 2); + assert.ok(!more.some(x => x.id === 'iq3_s' || x.id === 'gyro-gyro-s')); }); -test('the picker has no maker groups or collapsible headings, and the technical lines sit behind Show details', () => { +test('a row says whether the version fits this PC, from the same figures as the card', () => { + const big = { id: 'x', download_gb: 111, memory_gb: 78 }, small = { id: 'y', download_gb: 66, memory_gb: 35 }; + assert.equal(versionFit(small, { ram_gb: 128, vram_gb: 24 }), 'fits'); + assert.equal(versionFit(big, { ram_gb: 64, vram_gb: 12 }), 'ssd', 'part of the experts read from the SSD'); + assert.equal(versionFit({ ...small, on_this_pc: 'does not fit' }, { ram_gb: 128, vram_gb: 24 }), 'no', "the engine's own verdict wins"); + assert.equal(versionFit(small, null), 'unknown', 'no hardware figures: no claim'); + assert.match(source, /'Fits with SSD streaming'/); + assert.ok(!/nativeVersionLabel|plainLabel/.test(source), 'no Fastest, Compact, High quality words'); +}); + +test("the list is for one base model: the page passes only the chosen model's versions", async () => { + const screen = await readFile(new URL('../src/components/NativeModels.tsx', import.meta.url), 'utf8'); + assert.match(screen, /<VersionPicker [^>]*versions=\{selectedFamily\?\.sizes \?\? \[\]\}/); + assert.ok(!/models=\{families\}/.test(screen)); +}); + +test('the picker has no maker groups, and the technical lines sit behind Show details', () => { assert.ok(!/VERSION_GROUPS|groupOpen|version-group/.test(source), 'no Swift / GSQ-RCO / Unsloth group headings'); assert.ok(!/\(GSQ-RCO\)/.test(source), 'the maker is not part of the main name'); assert.match(source, /details \? <span className="version-row__tech">/, 'maker, RAM + VRAM and the SSD figure are shown only with details on'); - assert.match(source, /Recommended/); - assert.match(source, /Downloaded/); }); From 4faa0cf0ee2238215595cce3a93f8291c3381a67 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:05:58 +0100 Subject: [PATCH 15/59] Models > This computer: free graphics memory and RAM from real readings, a loaded model changes the card, SSD only when it does not fit --- apps/host/src/components/NativeModels.tsx | 6 +- apps/host/src/components/PcComputer.tsx | 31 ++++++++ apps/host/src/components/PcFitCard.tsx | 48 ++++++++---- apps/host/src/styles/liquid.css | 88 ++++++++++++++++++++++ apps/host/tests/deepseek-card.test.mjs | 2 +- apps/host/tests/native-two-models.test.mjs | 4 +- apps/host/tests/pc-card.test.mjs | 74 ++++++++++++++++++ 7 files changed, 235 insertions(+), 18 deletions(-) create mode 100644 apps/host/src/components/PcComputer.tsx create mode 100644 apps/host/tests/pc-card.test.mjs diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 82a67e55cb..47cebf62d0 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -3,7 +3,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { Screen } from './layout'; import { VersionPicker } from './VersionPicker'; import { FamilySwitch } from './FamilySwitch'; -import { PcFitCard } from './PcFitCard'; +import { PcComputer } from './PcComputer'; import { fitOn, memoryNeeded } from '../lib/native-fit'; import { GpuRoles } from './GpuRoles'; import { fromLegacy, normalize as normalizeRoles, order as roleOrder, recommend as recommendRoles, rows as roleRows, sameRoles, vramOn, type RoleCard, type Roles } from '../lib/gpu-roles'; @@ -80,6 +80,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const keptUse = keptModels.map(i => { const s = sizeOf(i.model); const card = pcGpus.find(g => g.index === i.gpus[0]); const f = s && pcRam ? fitOn(s, { ram_gb: pcRam, vram_gb: card?.vram_gb ?? pcVram }) : null; return { gpus: i.gpus, ram: f?.ramUseGb ?? 0, vram: f?.vramUseGb ?? 0 }; }); const keptRam = keptUse.reduce((n, u) => n + u.ram, 0); const keptVramOn = (cards: number[]) => keptUse.filter(u => u.gpus.some(g => cards.includes(g))).reduce((n, u) => n + u.vram, 0); + // The models that are loaded now, with what each takes of graphics memory, RAM and SSD (the app's estimate from the same rule the fit uses: the engine does not report this split). + const loadedModels = (native?.instances ?? []).filter(i => i.status === 'ready' || i.status === 'loading').flatMap(i => { const s = sizeOf(i.model); if (!s || !pcRam) return []; const card = pcGpus.find(g => g.index === i.gpus[0]); return [{ id: i.model, label: `${i.label} · ${s.model}`, fit: fitOn(s, { ram_gb: pcRam, vram_gb: card?.vram_gb ?? pcVram }, true, { context: i.context ?? context, kv }) }]; }); // The versions that are really on this computer: a config whose files are all there (every part of a model in parts). const readyIds = useMemo(() => new Set(downloaded.filter(m => m.ready).map(m => m.model)), [downloaded]); // What a running job works on, by its name in the list: "Qwen3.8-Flash-Next · Gyro · Smallest". @@ -230,7 +232,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {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>{tr(cardsGpus.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={KV_CHOICES.map(c => ({ value: c.value, label: c.label, title: c.hint }))} onChange={setKv}/>{tr(KV_CHOICES.find(c => c.value === kv)?.hint ? <small className="muted native-kv-hint">{tr(KV_CHOICES.find(c => c.value === kv)!.hint)}</small> : null)}</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} diskGb={selectedSize?.multi_file ? selectedSize.disk_gb ?? selectedSize.download_gb : null} inUse={keptModels.length ? { ramGb: Math.round(keptRam), vramGb: Math.round(keptVramOn(chosenCards)) } : null} fit={selectedSize ? fitOn(selectedSize, fitHardware, true, { context, kv }) : 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} className="other-models">{tr("Other local models\u2026")}</Btn></aside> + <aside className="stack stack--lg"><PcComputer gpuName={pcGpu?.name} ramGb={pcRam} vramGb={pcVram} vramAllGb={pcGpus.reduce((n, g) => n + g.vram_gb, 0) || undefined} loaded={loadedModels} selectedLoaded={!!selectedSize && loadedModels.some(m => m.id === selectedSize.id)} diskGb={selectedSize?.multi_file ? selectedSize.disk_gb ?? selectedSize.download_gb : null} inUse={keptModels.length ? { ramGb: Math.round(keptRam), vramGb: Math.round(keptVramOn(chosenCards)) } : null} fit={selectedSize ? fitOn(selectedSize, fitHardware, true, { context, kv }) : 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} className="other-models">{tr("Other local models\u2026")}</Btn></aside> </div> <Dialog open={!!plan} title={tr(installed?.ready ? "Apply settings and load" : "Download and prepare")} compact onClose={() => !pending && setPlan(null)} actions={<><Btn disabled={pending} onClick={() => setPlan(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={pending || !!plan?.plan?.disk_short} onClick={() => void download()}>{tr(installed?.ready ? "Apply & load" : "Download & load")}</Btn></>}><p><strong>{tr(plan?.plan?.title ?? selectedFamily?.title)}</strong>{tr(installed?.ready ? null : <>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}</>)}</p>{tr(plan?.drafting?.needed ? <p className="small muted">{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])}</p> : null)}{tr(installed?.ready ? <p className="small muted">{tr("The model files are already on this computer. Nothing will be downloaded; only the settings you chose are applied.")}</p> : null)}{tr(plan?.plan?.disk_short ? <ErrorNotice message={plan.plan.disk_short}/> : null)}{tr(installed?.ready ? <p className="small muted">{tr("Any currently loaded native models will be unloaded first.")}</p> : <><p className="small muted">{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}</p><p className="small muted">{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}</p></>)}{tr(selectedSize?.images ? <p className="small muted">{tr("Vision encoder files are included. Picture reading loads only when enabled.")}</p> : null)}</Dialog> diff --git a/apps/host/src/components/PcComputer.tsx b/apps/host/src/components/PcComputer.tsx new file mode 100644 index 0000000000..6847e54d5e --- /dev/null +++ b/apps/host/src/components/PcComputer.tsx @@ -0,0 +1,31 @@ +import { useEffect } from 'react'; +import { api } from '../lib/client'; +import { useStore } from '../lib/store'; +import { PcFitCard, type PcLive } from './PcFitCard'; + +const tenth = (n: number | null | undefined) => typeof n === 'number' && Number.isFinite(n) ? Math.round(n * 10) / 10 : null; + +/** + * "This computer" with the host's own readings: while the Models page is open the host reads the card every few seconds (the same ask the + * Monitor makes), and the free graphics memory and RAM come from those readings, not from a guess. It subscribes to the three numbers only, + * so the Models page itself does not redraw on every reading. + */ +export function PcComputer(props: Omit<React.ComponentProps<typeof PcFitCard>, 'live'> & { vramAllGb?: number }) { + const vramUsed = useStore(s => tenth(s.monitor?.hardware?.vramUsedGb)); + const ramUsed = useStore(s => tenth(s.monitor?.hardware?.ramUsedGb)); + const diskRead = useStore(s => tenth(s.monitor?.hardware?.diskReadGbs)); + useEffect(() => { + const ask = () => { if (typeof document === 'undefined' || document.visibilityState !== 'hidden') void api.get('/api/monitor').catch(() => undefined); }; + ask(); + const timer = setInterval(ask, 10000); + return () => clearInterval(timer); + }, []); + const vramTotal = props.vramAllGb ?? props.vramGb; + const live: PcLive = { + vramTotalGb: vramTotal, + freeVramGb: vramUsed !== null && vramTotal > 0 ? Math.max(0, Math.round((vramTotal - vramUsed) * 10) / 10) : null, + freeRamGb: ramUsed !== null && props.ramGb ? Math.max(0, Math.round((props.ramGb - ramUsed) * 10) / 10) : null, + diskReadGbs: diskRead, + }; + return <PcFitCard {...props} live={live}/>; +} diff --git a/apps/host/src/components/PcFitCard.tsx b/apps/host/src/components/PcFitCard.tsx index 62a5e2a1ed..5e1dfd6478 100644 --- a/apps/host/src/components/PcFitCard.tsx +++ b/apps/host/src/components/PcFitCard.tsx @@ -2,28 +2,50 @@ import { tr } from '../lib/i18n'; import type { Fit } from '../lib/native-fit'; const gb = (n: number) => `${Number.isInteger(n) ? n : n.toFixed(1)} GB`; +const about = (n: number) => `${Math.round(n)} GB`; -function Meter({ label, total, use }: { label: string; total: number; use: number }) { - const pct = total > 0 ? Math.max(2, Math.min(100, (use / total) * 100)) : 0; - return <div className="pc-meter"> - <div className="pc-meter__top"><span>{tr(label)}</span><b>{gb(use)}</b><span className="muted">{tr("of {0}", [gb(total)])}</span></div> - <div className="pc-meter__track" role="img" aria-label={tr("{0}: about {1} of {2} used by this model", [tr(label), gb(use), gb(total)])}><i style={{ width: `${pct}%` }}/></div> +/** What this computer has free right now (real readings of the host; null where one is not available). */ +export interface PcLive { vramTotalGb?: number; freeVramGb: number | null; freeRamGb: number | null; diskReadGbs: number | null } +/** A model that is loaded: what it takes of graphics memory and RAM, and how much of it is read from the SSD (the app's estimate: the engine does not report this split). */ +export interface PcLoaded { id: string; label: string; fit: Fit } + +function FreeMeter({ label, total, free }: { label: string; total: number; free: number }) { + const used = total > 0 ? Math.max(0, Math.min(100, ((total - free) / total) * 100)) : 0; + return <div className="pc-meter" data-low={free / (total || 1) < 0.1 || undefined}> + <div className="pc-meter__top"><span>{tr(label)}</span><b>{tr("{0} free", [gb(free)])}</b><span className="muted">{tr("of {0}", [gb(total)])}</span></div> + <div className="pc-meter__track" role="img" aria-label={tr("{0}: {1} free of {2}", [tr(label), gb(free), gb(total)])}><i style={{ transform: `scaleX(${used / 100})` }}/></div> </div>; } /** - * "This computer": the graphics memory and RAM, and what the chosen version would take of each. One plain line says whether it fits - * or how much would be read from the SSD (the n-gram table, which always sits on the SSD, is not counted). + * "This computer": how much graphics memory and RAM is free right now, and, for the loaded model, what it takes of each. The SSD only + * appears where the model does not fit in memory (how much is read from it). Before anything is loaded the card says what the chosen + * version would take. (The n-gram table, which always sits on the SSD, is not counted.) */ -export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null, diskGb = null }: { gpuName?: string | null; ramGb: number | null; vramGb: number; fit: Fit | null; inUse?: { ramGb: number; vramGb: number } | null; diskGb?: number | null }) { - const freeVram = Math.max(0, vramGb - (inUse?.vramGb ?? 0)), freeRam = ramGb ? Math.max(0, ramGb - (inUse?.ramGb ?? 0)) : 0; - return <section className="st-card pc-card"> +export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null, diskGb = null, live = null, loaded = [], selectedLoaded = false }: { gpuName?: string | null; ramGb: number | null; vramGb: number; fit: Fit | null; inUse?: { ramGb: number; vramGb: number } | null; diskGb?: number | null; live?: PcLive | null; loaded?: PcLoaded[]; selectedLoaded?: boolean }) { + const showFit = !!fit?.known && !selectedLoaded; + return <section className="st-card pc-card" data-loaded={loaded.length ? true : undefined}> <div><h2 className="h4">{tr("This computer")}</h2> <p className="small muted">{tr(gpuName ? tr("{0} · {1} graphics memory", [gpuName, gb(vramGb)]) : tr("No supported graphics card reported by this installation."))}{ramGb ? tr(" · {0} RAM", [gb(ramGb)]) : ''}</p></div> - {tr(fit?.known && vramGb > 0 ? <Meter label="Graphics memory" total={freeVram} use={fit.vramUseGb}/> : null)} - {tr(fit?.known && ramGb ? <Meter label="RAM" total={freeRam} use={fit.ramUseGb}/> : null)} + {tr(loaded.map(m => <div className="pc-loaded" key={m.id}> + <div className="pc-loaded__head"><i aria-hidden="true"/><strong>{tr(m.label)}</strong><span className="pc-tag">{tr("Loaded")}</span></div> + <p className="small muted">{tr("It takes about")}</p> + <dl className="pc-takes"> + {tr(m.fit.known && vramGb > 0 ? <div><dt>{tr("Graphics memory")}</dt><dd>{about(m.fit.vramUseGb)}</dd></div> : null)} + {tr(m.fit.known && ramGb ? <div><dt>{tr("RAM")}</dt><dd>{about(m.fit.ramUseGb)}</dd></div> : null)} + {tr(m.fit.known && m.fit.spillGb >= 1 ? <div><dt>{tr("SSD")}</dt><dd>{about(m.fit.spillGb)}</dd></div> : null)} + </dl> + {tr(m.fit.known && m.fit.spillGb < 1 ? <p className="pc-note">{tr("Nothing. It fits in memory.")}</p> : null)} + {tr(m.fit.known && m.fit.spillGb >= 1 ? <p className="pc-note">{tr("About {0} GB will be read from the SSD, so answers can be a little slower.", [Math.round(m.fit.spillGb)])}{tr(live?.diskReadGbs && live.diskReadGbs >= 0.05 ? tr(" Reading from your SSD now: {0}", [`${live.diskReadGbs.toFixed(1)} GB/s`]) : '')}</p> : null)} + </div>))} + {tr(live && (live.freeVramGb !== null || live.freeRamGb !== null) ? <div className="pc-free"> + <h3 className="pc-label">{tr("Free right now")}</h3> + {tr(live.freeVramGb !== null && vramGb > 0 ? <FreeMeter label="Graphics memory" total={live.vramTotalGb ?? vramGb} free={live.freeVramGb}/> : null)} + {tr(live.freeRamGb !== null && ramGb ? <FreeMeter label="RAM" total={ramGb} free={live.freeRamGb}/> : null)} + </div> : null)} {tr(inUse ? <p className="xs muted">{tr("Models that stay loaded use about {0} GB of RAM and {1} GB of this card’s memory.", [inUse.ramGb, inUse.vramGb])}</p> : null)} + {tr(showFit && !selectedLoaded && !loaded.length && fit!.vramUseGb + fit!.ramUseGb > 0 ? <p className="pc-note">{tr("This version would take about {0} of graphics memory and {1} of RAM.", [about(fit!.vramUseGb), about(fit!.ramUseGb)])}</p> : null)} {tr(diskGb ? <p className="pc-note">{tr("Needs about {0} GB of free disk space. What does not fit in memory is read from your SSD.", [Math.round(diskGb)])}</p> : null)} - {tr(fit?.known && (diskGb ? fit.spillGb >= 1 : true) ? <p className="pc-note">{tr(fit.spillGb >= 1 ? 'About {0} GB will be read from the SSD, so answers can be a little slower.' : 'Fits fully in memory.', [Math.round(fit.spillGb)])}</p> : null)} + {tr(showFit && (diskGb ? fit!.spillGb >= 1 : true) ? <p className="pc-note">{tr(fit!.spillGb >= 1 ? 'About {0} GB will be read from the SSD, so answers can be a little slower.' : 'Fits fully in memory.', [Math.round(fit!.spillGb)])}</p> : null)} </section>; } diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index 3bdd1f2a36..f62530eff5 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -1220,3 +1220,91 @@ body { align-items: center; gap: 2px; } + +/* ------------------------------------------- 18. "This computer" on Models ---- + Free graphics memory and free RAM come first (real readings, a bar that is + filled by what is in use), a loaded model gets its own tinted block with what + it takes, and the SSD appears only in that block or in the fit line when the + model does not fit in memory. */ +.pc-label { + margin: 0; + font-size: var(--st-fs-xs); + font-weight: 600; + color: var(--st-ink-muted); +} +.pc-free { + display: flex; + flex-direction: column; + gap: 12px; +} +.pc-free .pc-meter__track i { + width: 100%; + transform-origin: left center; + transition: transform var(--st-t-surface) var(--st-ease-standard); +} +.pc-meter[data-low] .pc-meter__track i { + background: var(--st-warn); +} +.pc-loaded { + display: flex; + flex-direction: column; + gap: 8px; + padding: 12px 14px; + border: 1px solid var(--st-accent-surface-edge); + border-radius: var(--st-r-md); + background: var(--st-accent-tint); + animation: st-enter var(--st-t-local) var(--st-ease-enter) both; + --st-from-y: 4px; +} +.pc-loaded p { + margin: 0; +} +.pc-loaded__head { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; +} +.pc-loaded__head strong { + min-width: 0; + overflow-wrap: anywhere; +} +.pc-loaded__head i { + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--st-accent); +} +.pc-tag { + margin-left: auto; + padding: 0 8px; + border-radius: var(--st-r-pill); + font-size: var(--st-fs-xs); + font-weight: 600; + line-height: 20px; + color: var(--st-accent-text); + box-shadow: inset 0 0 0 1px var(--st-accent-surface-edge); +} +.pc-takes { + display: flex; + flex-wrap: wrap; + gap: 8px 24px; + margin: 0; +} +.pc-takes div { + display: flex; + flex-direction: column; + gap: 2px; +} +.pc-takes dt { + font-size: var(--st-fs-xs); + color: var(--st-ink-muted); +} +.pc-takes dd { + margin: 0; + font-size: var(--st-fs-lg); + font-weight: 700; + letter-spacing: -0.01em; + font-variant-numeric: tabular-nums; +} diff --git a/apps/host/tests/deepseek-card.test.mjs b/apps/host/tests/deepseek-card.test.mjs index ef03891cfc..94d4a9f0b9 100644 --- a/apps/host/tests/deepseek-card.test.mjs +++ b/apps/host/tests/deepseek-card.test.mjs @@ -65,7 +65,7 @@ test('the words are in all eight languages with the same slots', () => { test('the Models screen passes the set\'s disk to the card, and the version line states it for DeepSeek only', () => { const screen = read('../src/components/NativeModels.tsx'); - assert.match(screen, /<PcFitCard [^>]*diskGb=\{selectedSize\?\.multi_file \? selectedSize\.disk_gb \?\? selectedSize\.download_gb : null\}/); + assert.match(screen, /<PcComputer [\s\S]*?diskGb=\{selectedSize\?\.multi_file \? selectedSize\.disk_gb \?\? selectedSize\.download_gb : null\}/); const picker = read('../src/components/VersionPicker.tsx'); assert.match(picker, /v\.multi_file && v\.disk_gb \? tr\("\{0\} RAM \+ VRAM, plus about \{1\} GB of disk", \[gb\(fit\.memoryGb\), Math\.round\(v\.disk_gb\)\]\)/, 'Details: the disk of the set for DeepSeek'); assert.match(picker, /v\.multi_file && v\.disk_gb \? tr\("Needs \{0\} of memory and about \{1\} GB of disk"/, 'plain: the disk for DeepSeek only'); diff --git a/apps/host/tests/native-two-models.test.mjs b/apps/host/tests/native-two-models.test.mjs index ab428585d2..83e1fdd5e9 100644 --- a/apps/host/tests/native-two-models.test.mjs +++ b/apps/host/tests/native-two-models.test.mjs @@ -62,8 +62,8 @@ test('card names use the GPU numbering of the other screens, and the fit figures assert.match(models, /const keptModels = expert && multiple/); assert.match(models, /inUse=\{keptModels\.length \?/); const card = await readFile(new URL('../src/components/PcFitCard.tsx', import.meta.url), 'utf8'); - assert.match(card, /total=\{freeVram\}/); - assert.match(card, /total=\{freeRam\}/); + assert.match(card, /vramGb > 0 \? <FreeMeter label="Graphics memory" total=\{live\.vramTotalGb \?\? vramGb\} free=\{live\.freeVramGb\}/); + assert.match(card, /<FreeMeter label="RAM" total=\{ramGb\} free=\{live\.freeRamGb\}/); // the arithmetic itself const text = 'fits: needs 44 GB of the 273 GB available.'; const gone = Math.round(14 + 27); diff --git a/apps/host/tests/pc-card.test.mjs b/apps/host/tests/pc-card.test.mjs new file mode 100644 index 0000000000..7557af4747 --- /dev/null +++ b/apps/host/tests/pc-card.test.mjs @@ -0,0 +1,74 @@ +/** Models > This computer: free graphics memory and RAM first, the SSD only when the model does not fit, and a loaded model changes the card. */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { build } from 'esbuild'; +import { mkdtempSync, writeFileSync, rmSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const stdin = { contents: "import { createElement } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { PcFitCard } from './src/components/PcFitCard'; export { setTranslationLanguage } from './src/lib/i18n'; export const render = props => renderToStaticMarkup(createElement(PcFitCard, props));", resolveDir: fileURLToPath(new URL('..', import.meta.url)), loader: 'ts' }; +const built = await build({ stdin, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json', '.tsx': 'tsx' }, jsx: 'automatic', logLevel: 'silent', banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" } }); +const dir = mkdtempSync(join(tmpdir(), 'strata-pc-test-')); +writeFileSync(join(dir, 'card.mjs'), built.outputFiles[0].text); +const { render, setTranslationLanguage } = await import(pathToFileURL(join(dir, 'card.mjs')).href); +rmSync(dir, { recursive: true, force: true }); +const fit = (spillGb, vramUseGb = 12, ramUseGb = 44) => ({ memoryGb: vramUseGb + ramUseGb + spillGb, vramUseGb, ramUseGb, spillGb, known: true }); +const card = props => render({ gpuName: 'RTX 5070', ramGb: 64, vramGb: 12, ...props }); +const live = { vramTotalGb: 12, freeVramGb: 10.3, freeRamGb: 49.8, diskReadGbs: null }; + +test('free graphics memory and free RAM come first, as real readings', () => { + setTranslationLanguage('en'); + const html = card({ fit: fit(0), live }); + assert.match(html, /Free right now/); + assert.match(html, /Graphics memory<\/span><b>10\.3 GB free<\/b>/); + assert.match(html, /RAM<\/span><b>49\.8 GB free<\/b>/); + assert.match(html, /of 12 GB/); + assert.doesNotMatch(card({ fit: fit(0), live: null }), /Free right now/, 'no readings: no invented numbers'); +}); + +test('the SSD appears only when the model does not fit in memory, with how much is read from it', () => { + setTranslationLanguage('en'); + assert.doesNotMatch(card({ fit: fit(0), live }), /SSD/); + assert.match(card({ fit: fit(0), live }), /Fits fully in memory\./); + assert.match(card({ fit: fit(30), live }), /About 30 GB will be read from the SSD/); +}); + +test('a loaded model changes the card: it says Loaded and what the model takes of graphics memory, RAM and SSD', () => { + setTranslationLanguage('en'); + const fits = card({ fit: fit(0), live, loaded: [{ id: 'iq3_s', label: 'Qwen3.8-Flash-Next · IQ3_S', fit: fit(0) }], selectedLoaded: true }); + assert.match(fits, /pc-loaded/); + assert.match(fits, /Qwen3\.8-Flash-Next · IQ3_S/); + assert.match(fits, /Loaded/); + assert.match(fits, /<dt>Graphics memory<\/dt><dd>12 GB<\/dd>/); + assert.match(fits, /<dt>RAM<\/dt><dd>44 GB<\/dd>/); + assert.doesNotMatch(fits, /<dt>SSD<\/dt>/, 'it fits: no SSD row'); + assert.match(fits, /Nothing\. It fits in memory\./); + const spills = card({ fit: fit(18), live: { ...live, diskReadGbs: 1.2 }, loaded: [{ id: 'q', label: 'Qwen3.8-Flash-Next · UD-Q4_K_XL', fit: fit(18, 12, 53) }], selectedLoaded: true }); + assert.match(spills, /<dt>SSD<\/dt><dd>18 GB<\/dd>/); + assert.match(spills, /Reading from your SSD now: 1\.2 GB\/s/); + assert.doesNotMatch(spills, /This version would take/, 'the loaded block already says it'); +}); + +test('before anything is loaded the card says what the chosen version would take', () => { + setTranslationLanguage('en'); + assert.match(card({ fit: fit(0), live }), /This version would take about 12 GB of graphics memory and 44 GB of RAM\./); +}); + +test('the numbers come from the host\'s readings, polled while the page is open and read without redrawing the Models page', () => { + const wrapper = readFileSync(fileURLToPath(new URL('../src/components/PcComputer.tsx', import.meta.url)), 'utf8'); + assert.match(wrapper, /api\.get\('\/api\/monitor'\)/); + assert.match(wrapper, /useStore\(s => tenth\(s\.monitor\?\.hardware\?\.vramUsedGb\)\)/); + assert.match(wrapper, /useStore\(s => tenth\(s\.monitor\?\.hardware\?\.ramUsedGb\)\)/); +}); + +test('the new words are in all nine languages', () => { + const en = JSON.parse(readFileSync(fileURLToPath(new URL('../src/locales/pick-en.json', import.meta.url)), 'utf8')); + for (const lang of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) { + const cat = JSON.parse(readFileSync(fileURLToPath(new URL(`../src/locales/pick-${lang}.json`, import.meta.url)), 'utf8')); + for (const id of Object.keys(en)) { + assert.ok(cat[id], `${lang} ${id}`); + assert.deepEqual((cat[id].match(/\{\d+\}/g) ?? []).sort(), (en[id].match(/\{\d+\}/g) ?? []).sort(), `${lang} ${id} slots`); + } + } +}); From d615a9d643ae3db3e59260f3c0f59dd3bbc24df4 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:34:24 +0100 Subject: [PATCH 16/59] DFlash2 as a real option: the dropdown only where there is a choice (not DeepSeek), --spec 6 --draft-conf 0.35 with it, only on CUDA and HIP engines, one plain line per card, no-internet message, verified files reused, SSD line label --- apps/host/scripts/make-df2-locales.py | 114 ++++++++++++++ apps/host/server/native-control.mjs | 9 +- apps/host/server/native-settings.mjs | 6 +- apps/host/src/components/NativeModels.tsx | 3 +- apps/host/src/components/NativeSettings.tsx | 5 +- apps/host/src/components/PcFitCard.tsx | 2 +- apps/host/src/lib/drafting.ts | 15 +- apps/host/src/lib/i18n.ts | 14 +- apps/host/src/lib/native.ts | 4 +- apps/host/src/locales/df2-de.json | 10 ++ apps/host/src/locales/df2-en.json | 10 ++ apps/host/src/locales/df2-es.json | 10 ++ apps/host/src/locales/df2-fr.json | 10 ++ apps/host/src/locales/df2-ja.json | 10 ++ apps/host/src/locales/df2-ko.json | 10 ++ apps/host/src/locales/df2-pt.json | 10 ++ apps/host/src/locales/df2-ru.json | 10 ++ apps/host/src/locales/df2-zh.json | 10 ++ apps/host/tests/drafting.test.mjs | 56 +++++-- apps/host/tests/pc-card.test.mjs | 2 +- serve/server.py | 3 +- strata_cli/drafting_cmd.py | 20 +-- strata_cli/launch/app.py | 4 +- strata_cli/launch/runner.py | 13 +- strata_cli/launch/screens.py | 55 ++++++- strata_control/drafting.py | 136 +++++++++++++++-- strata_control/drafting_fetch.py | 64 +++++++- tests/terminal/test_drafting.py | 15 +- tests/terminal/test_drafting_hardware.py | 156 ++++++++++++++++++++ 29 files changed, 707 insertions(+), 79 deletions(-) create mode 100644 apps/host/scripts/make-df2-locales.py create mode 100644 apps/host/src/locales/df2-de.json create mode 100644 apps/host/src/locales/df2-en.json create mode 100644 apps/host/src/locales/df2-es.json create mode 100644 apps/host/src/locales/df2-fr.json create mode 100644 apps/host/src/locales/df2-ja.json create mode 100644 apps/host/src/locales/df2-ko.json create mode 100644 apps/host/src/locales/df2-pt.json create mode 100644 apps/host/src/locales/df2-ru.json create mode 100644 apps/host/src/locales/df2-zh.json create mode 100644 tests/terminal/test_drafting_hardware.py diff --git a/apps/host/scripts/make-df2-locales.py b/apps/host/scripts/make-df2-locales.py new file mode 100644 index 0000000000..a38d58788f --- /dev/null +++ b/apps/host/scripts/make-df2-locales.py @@ -0,0 +1,114 @@ +"""Writes src/locales/df2-<lang>.json: the strings of the Drafting choice that came with the DFlash2 option (branch f-0291-df2-option): the plain-words +paragraph under the dropdown, the three lines about the person's graphics card, the "not on this card" and "no internet" lines, and the SSD line of the +This computer panel. +Run from apps/host: python scripts/make-df2-locales.py +Every entry names all nine languages; the keys are df01.. in the order of S. df2-en.json is the English source. Placeholders ({0}) must be kept in every +language. A separate file keeps this work from colliding with the other catalogs (the same reason pick-, tune-, tools-, fix-, gh-, ui- and engine- exist). +The English lines of df03-df07 are also written in strata_control/drafting.py and strata_control/drafting_fetch.py; tests/drafting.test.mjs keeps the two the same.""" +import json +import re +from pathlib import Path + +LANGS = ["en", "zh", "ja", "de", "es", "ru", "pt", "ko", "fr"] +S = [] + + +def add(en, zh, ja, de, es, ru, pt, ko, fr): + S.append(dict(en=en, zh=zh, ja=ja, de=de, es=es, ru=ru, pt=pt, ko=ko, fr=fr)) + + +add("MTP is the default. DFlash2 is another way to guess the next words ahead, for Qwen3.8-Flash-Next only. On an RTX PRO 5000 it was 7.8% faster than MTP " + "on 19 short prompts and 1.1% faster on long thinking, and faster on 21 of 23 prompts. On the short prompts the answers were identical.", + "默认使用 MTP。DFlash2 是另一种提前猜测后续词语的方式,仅适用于 Qwen3.8-Flash-Next。在 RTX PRO 5000 上,它在 19 个短提示上比 MTP 快 7.8%,在长篇思考上快 1.1%," + "并且在 23 个提示中有 21 个更快。在短提示上,回答完全相同。", + "既定では MTP を使います。DFlash2 は次の語を先読みするもう一つの方法で、Qwen3.8-Flash-Next 専用です。RTX PRO 5000 では、短いプロンプト 19 件で MTP より 7.8% 速く、" + "長い思考では 1.1% 速く、23 件中 21 件で速くなりました。短いプロンプトでは回答が同一でした。", + "MTP ist die Voreinstellung. DFlash2 ist eine andere Art, die nächsten Wörter vorauszuraten, nur für Qwen3.8-Flash-Next. Auf einer RTX PRO 5000 war es bei 19 kurzen " + "Prompts 7,8 % schneller als MTP, bei langem Nachdenken 1,1 % schneller und bei 21 von 23 Prompts schneller. Bei den kurzen Prompts waren die Antworten identisch.", + "MTP es la opción predeterminada. DFlash2 es otra forma de adivinar las siguientes palabras por adelantado, solo para Qwen3.8-Flash-Next. En una RTX PRO 5000 fue un 7,8 % " + "más rápido que MTP en 19 prompts cortos y un 1,1 % más rápido en razonamientos largos, y más rápido en 21 de 23 prompts. En los prompts cortos las respuestas fueron idénticas.", + "По умолчанию используется MTP. DFlash2 — другой способ угадывать следующие слова наперёд, только для Qwen3.8-Flash-Next. На RTX PRO 5000 он был на 7,8 % быстрее MTP " + "на 19 коротких запросах и на 1,1 % быстрее на длинных рассуждениях, а на 21 из 23 запросов — быстрее. На коротких запросах ответы были идентичны.", + "MTP é o padrão. DFlash2 é outra forma de adivinhar as próximas palavras antecipadamente, só para o Qwen3.8-Flash-Next. Numa RTX PRO 5000 foi 7,8 % mais rápido que o MTP " + "em 19 prompts curtos e 1,1 % mais rápido em raciocínios longos, e mais rápido em 21 de 23 prompts. Nos prompts curtos as respostas foram idênticas.", + "기본값은 MTP입니다. DFlash2는 다음 단어를 미리 추측하는 또 다른 방식이며 Qwen3.8-Flash-Next 전용입니다. RTX PRO 5000에서 짧은 프롬프트 19개에서는 MTP보다 7.8% 빨랐고, " + "긴 사고 과정에서는 1.1% 빨랐으며, 23개 중 21개 프롬프트에서 더 빨랐습니다. 짧은 프롬프트에서는 답변이 동일했습니다.", + "MTP est le réglage par défaut. DFlash2 est une autre façon de deviner à l'avance les mots suivants, uniquement pour Qwen3.8-Flash-Next. Sur une RTX PRO 5000, il a été 7,8 % " + "plus rapide que MTP sur 19 prompts courts et 1,1 % plus rapide en réflexion longue, et plus rapide sur 21 prompts sur 23. Sur les prompts courts, les réponses étaient identiques.") +add("It downloads about 1.2 GB once, works with one graphics card and one request at a time, and uses MTP otherwise.", + "它会一次性下载约 1.2 GB,仅在使用一张显卡且一次处理一个请求时有效,其他情况下使用 MTP。", + "約 1.2 GB を一度だけダウンロードします。グラフィックスカード 1 枚で一度に 1 件のリクエストを処理するときに動作し、それ以外では MTP を使います。", + "Es lädt einmalig etwa 1,2 GB herunter, funktioniert mit einer Grafikkarte und einer Anfrage zur Zeit und nutzt sonst MTP.", + "Descarga unos 1,2 GB una sola vez, funciona con una tarjeta gráfica y una solicitud a la vez, y en los demás casos usa MTP.", + "Один раз скачивает около 1,2 ГБ, работает с одной видеокартой и одним запросом за раз, в остальных случаях используется MTP.", + "Baixa cerca de 1,2 GB uma única vez, funciona com uma placa de vídeo e um pedido de cada vez, e nos outros casos usa o MTP.", + "약 1.2 GB를 한 번만 내려받으며, 그래픽 카드 한 장과 한 번에 하나의 요청에서 작동하고, 그 외에는 MTP를 사용합니다.", + "Il télécharge environ 1,2 Go une seule fois, fonctionne avec une carte graphique et une requête à la fois, et utilise MTP sinon.") +add("On graphics cards like yours, DFlash2 was faster than MTP on some kinds of text and slower on others in our tests.", + "在与您类似的显卡上,我们的测试中 DFlash2 在某些类型的文本上比 MTP 快,在另一些上更慢。", + "お使いのようなグラフィックスカードでは、私たちのテストで DFlash2 は MTP より速い種類の文章と遅い種類の文章がありました。", + "Auf Grafikkarten wie Ihrer war DFlash2 in unseren Tests bei manchen Textarten schneller als MTP und bei anderen langsamer.", + "En tarjetas gráficas como la suya, en nuestras pruebas DFlash2 fue más rápido que MTP con algunos tipos de texto y más lento con otros.", + "На видеокартах, подобных вашей, в наших тестах DFlash2 был быстрее MTP на одних видах текста и медленнее на других.", + "Em placas de vídeo como a sua, nos nossos testes o DFlash2 foi mais rápido que o MTP em alguns tipos de texto e mais lento em outros.", + "고객님과 비슷한 그래픽 카드에서 저희 테스트 결과 DFlash2는 일부 유형의 글에서는 MTP보다 빨랐고 다른 유형에서는 더 느렸습니다.", + "Sur des cartes graphiques comme la vôtre, DFlash2 a été plus rapide que MTP sur certains types de texte et plus lent sur d'autres lors de nos tests.") +add("On graphics cards like yours, DFlash2 was slower than MTP in our tests.", + "在与您类似的显卡上,我们的测试中 DFlash2 比 MTP 更慢。", + "お使いのようなグラフィックスカードでは、私たちのテストで DFlash2 は MTP より遅くなりました。", + "Auf Grafikkarten wie Ihrer war DFlash2 in unseren Tests langsamer als MTP.", + "En tarjetas gráficas como la suya, en nuestras pruebas DFlash2 fue más lento que MTP.", + "На видеокартах, подобных вашей, в наших тестах DFlash2 был медленнее MTP.", + "Em placas de vídeo como a sua, nos nossos testes o DFlash2 foi mais lento que o MTP.", + "고객님과 비슷한 그래픽 카드에서 저희 테스트 결과 DFlash2는 MTP보다 느렸습니다.", + "Sur des cartes graphiques comme la vôtre, DFlash2 a été plus lent que MTP lors de nos tests.") +add("DFlash2 has not been tested on your graphics card yet.", + "DFlash2 尚未在您的显卡上测试过。", + "DFlash2 はまだお使いのグラフィックスカードでテストされていません。", + "DFlash2 wurde auf Ihrer Grafikkarte noch nicht getestet.", + "DFlash2 todavía no se ha probado en su tarjeta gráfica.", + "DFlash2 ещё не проверялся на вашей видеокарте.", + "O DFlash2 ainda não foi testado na sua placa de vídeo.", + "DFlash2는 아직 고객님의 그래픽 카드에서 테스트되지 않았습니다.", + "DFlash2 n'a pas encore été testé sur votre carte graphique.") +add("Drafting: MTP (DFlash2 isn't available on this graphics card)", + "预测方式:MTP(DFlash2 不适用于这张显卡)", + "先読み:MTP(DFlash2 はこのグラフィックスカードでは使えません)", + "Vorausraten: MTP (DFlash2 ist auf dieser Grafikkarte nicht verfügbar)", + "Predicción: MTP (DFlash2 no está disponible en esta tarjeta gráfica)", + "Упреждающая генерация: MTP (DFlash2 недоступен на этой видеокарте)", + "Previsão: MTP (o DFlash2 não está disponível nesta placa de vídeo)", + "미리 추측: MTP (이 그래픽 카드에서는 DFlash2를 사용할 수 없습니다)", + "Anticipation : MTP (DFlash2 n'est pas disponible sur cette carte graphique)") +add("There is no internet connection, so the DFlash2 drafter can't be downloaded now.", + "没有网络连接,因此现在无法下载 DFlash2 草稿模型。", + "インターネットに接続されていないため、今は DFlash2 のドラフターをダウンロードできません。", + "Es besteht keine Internetverbindung, deshalb kann der DFlash2-Drafter jetzt nicht heruntergeladen werden.", + "No hay conexión a internet, así que ahora no se puede descargar el borrador de DFlash2.", + "Нет подключения к интернету, поэтому сейчас нельзя скачать черновую модель DFlash2.", + "Não há ligação à internet, por isso não é possível transferir agora o rascunhador do DFlash2.", + "인터넷에 연결되어 있지 않아 지금은 DFlash2 드래프터를 내려받을 수 없습니다.", + "Il n'y a pas de connexion internet, le drafter DFlash2 ne peut donc pas être téléchargé pour le moment.") +add("SSD: not needed", + "SSD:不需要", "SSD:不要", "SSD: nicht nötig", "SSD: no hace falta", "SSD: не нужен", "SSD: não é necessário", "SSD: 필요 없음", "SSD : pas nécessaire") + +here = Path(__file__).resolve().parent.parent / "src" / "locales" +NBSP = " " + + +def french(text): + text = re.sub(r"(?<=[A-Za-zÀ-ſ])'(?=[A-Za-zÀ-ſ{])", "’", text) + text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text) + text = re.sub(r"(?<=[\d}]) %", NBSP + "%", text) + return text + + +for lang in LANGS: + data = {} + for i, entry in enumerate(S): + text = entry[lang] + assert sorted(re.findall(r"\{\d+\}", entry["en"])) == sorted(re.findall(r"\{\d+\}", text)), (lang, entry["en"], text) + data[f"df{i + 1:02d}"] = french(text) if lang == "fr" else text + with (here / f"df2-{lang}.json").open("w", encoding="utf-8", newline="\n") as handle: + handle.write(json.dumps(data, ensure_ascii=False, indent=1) + "\n") +print("written", len(S), "strings in", len(LANGS), "languages") diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 9c1abeeba1..fe9f16a74d 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -67,9 +67,9 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; function diskSpace(path){try{const s=statfsSync(path);return {free:Number(s.bavail)*Number(s.bsize),total:Number(s.blocks)*Number(s.bsize)};}catch{return null;}} /* Does the engine in this release serve DFlash2? Control knows (strata_control/drafting.py); asked once, false until it answers. The Models screen offers the choice only when true. */ - let dflash2Served=null; - function probeDrafting(){if(!packaged||dflash2Served!==null||typeof control.draftingPlan!=='function')return;dflash2Served=false;control.draftingPlan({mode:'auto'}).then(p=>{dflash2Served=p.serves===true;emit();}).catch(()=>{});} - function state(){const folder=preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),space=folder?diskSpace(folder):null;return {...snapshot,downloadDirectory:folder,downloadFreeBytes:space?.free??null,downloadTotalBytes:space?.total??null,fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false,dflash2:dflash2Served===true}};} + let dflash2Served=null,dflash2Support=null; + function probeDrafting(){if(!packaged||dflash2Served!==null||typeof control.draftingPlan!=='function')return;dflash2Served=false;control.draftingPlan({mode:'auto'}).then(p=>{dflash2Served=p.serves===true;dflash2Support=p.serves===true&&p.support&&p.support_line?{level:p.support,line:p.support_line}:null;emit();}).catch(()=>{});} + function state(){const folder=preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),space=folder?diskSpace(folder):null;return {...snapshot,downloadDirectory:folder,downloadFreeBytes:space?.free??null,downloadTotalBytes:space?.total??null,fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false,dflash2:dflash2Served===true,dflash2Support}};} let sourceCache={path:'',time:0,text:''}; function sourceText(){try{const path=join(packaged?control.control.dir:preferences.repo,'serve/server.py'),time=statSync(path).mtimeMs;if(sourceCache.path===path&&sourceCache.time===time)return sourceCache.text;sourceCache={path,time,text:readFileSync(path,'utf8')};return sourceCache.text;}catch{return '';}} function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:APP_OWNED_FIELDS.includes(field.id)||field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} @@ -309,7 +309,8 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} async function prepareDrafter(job,args,cfg,configFile){ const asked=args.values?.drafting; if(asked!==undefined)rememberSetting(configFile,'drafting',asked===null||asked==='auto'?null:asked); - if(!packaged||typeof control.draftingFetch!=='function'||!cfg.drafting||cfg.drafting==='auto'||cfg.drafting==='mtp'||cfg.drafting==='off')return; + /* Only the Models screen's own Load passes the choice (its dialog has listed the download): a restart, a tuning run or any other load leaves `asked` undefined and never fetches; the model then starts with the MTP and says why. */ + if(!packaged||typeof control.draftingFetch!=='function'||asked===undefined||!cfg.drafting||cfg.drafting==='auto'||cfg.drafting==='mtp'||cfg.drafting==='off')return; const work=join(directory,'native-instances');mkdirSync(work,{recursive:true});const probe=join(work,'drafting-'+randomUUID()+'.json'); try{ writeFileSync(probe,JSON.stringify(cfg),{mode:0o600}); diff --git a/apps/host/server/native-settings.mjs b/apps/host/server/native-settings.mjs index 8196788506..932b591df3 100644 --- a/apps/host/server/native-settings.mjs +++ b/apps/host/server/native-settings.mjs @@ -8,9 +8,9 @@ export const NATIVE_FIELDS=[ {id:'aliases',label:'API model aliases',group:'Serving',type:'array',hint:'Comma-separated names clients may use for this model.'}, {id:'idle_unload_s',label:'Unload after idle seconds',group:'Serving',type:'number',min:0,max:86400,hint:'Zero keeps the model loaded.'}, {id:'lazy_load',label:'Load on first request',group:'Serving',type:'boolean'}, - {id:'mtp',label:'Draft layer (MTP)',group:'Serving',type:'boolean',hint:'The draft layer guesses several words ahead, which makes answers faster, and costs about 1 GB of graphics memory and some RAM. Turn it off if the model stops while it starts, or the card is small: the expert cache gets that memory back and answers are slower. Default is on.'}, - {id:'drafting',label:'Drafting',group:'Serving',type:'enum',choices:['auto','mtp','dflash2','off'],hint:'Which drafter guesses words ahead to make answers faster. Auto (recommended) lets Strata pick from what it measured on cards like yours; today that is the MTP. DFlash2 is for Qwen3.8-Flash-Next only and downloads a 1.2 GB drafter once. If DFlash2 cannot run, the MTP is used and Details says why. Off turns the draft layer off.'}, - {id:'batchMtp',label:'MTP per request',group:'Serving',type:'boolean',hint:'Each concurrent request uses the draft layer. Left alone, Strata turns it on for one graphics card with 24 GB or more and several requests at once, and off otherwise; choose on or off here to decide yourself.'}, + {id:'mtp',notForModel:'deepseek',label:'Draft layer (MTP)',group:'Serving',type:'boolean',hint:'The draft layer guesses several words ahead, which makes answers faster, and costs about 1 GB of graphics memory and some RAM. Turn it off if the model stops while it starts, or the card is small: the expert cache gets that memory back and answers are slower. Default is on.'}, + {id:'drafting',notForModel:'deepseek',label:'Drafting',group:'Serving',type:'enum',choices:['auto','mtp','dflash2','off'],hint:'Which drafter guesses words ahead to make answers faster. Auto (recommended) lets Strata pick from what it measured on cards like yours; today that is the MTP. DFlash2 is for Qwen3.8-Flash-Next only and downloads a 1.2 GB drafter once. If DFlash2 cannot run, the MTP is used and Details says why. Off turns the draft layer off.'}, + {id:'batchMtp',notForModel:'deepseek',label:'MTP per request',group:'Serving',type:'boolean',hint:'Each concurrent request uses the draft layer. Left alone, Strata turns it on for one graphics card with 24 GB or more and several requests at once, and off otherwise; choose on or off here to decide yourself.'}, {id:'ds_experts',label:'Speed (DeepSeek)',group:'Serving',type:'enum',choices:['5','6'],forModel:'deepseek',hint:'Faster uses 5 of 6 experts per word: a small quality change, usually not noticeable. Full quality uses all 6. Left alone, the engine picks Faster on a PC whose graphics cards total 16 GB or less.'}, {id:'parallel',label:'Concurrent requests',group:'Serving',type:'number',min:1,max:8,hint:'More slots need more memory and can slow each response.'}, {id:'engine_silence_s',label:'Engine stall timeout (seconds)',group:'Recovery',type:'number',min:10,max:3600}, diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 47cebf62d0..a7cd9892d9 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -123,7 +123,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const fitHardware = { ram_gb: pcRam ? Math.max(0, pcRam - keptRam) : pcRam, vram_gb: Math.max(0, (roleCards.length > 1 ? vramOn(effectiveRoles, roleCards) : pcVram) - keptVramOn(chosenCards)) }; // A layer split written for another number of cards no longer fits: back to automatic. useEffect(() => { if (cardsGpus.length <= 1 && split !== 'auto') setSplit('auto'); }, [cardsGpus.length]); - // Drafting (which drafter guesses ahead): DFlash2 is for Qwen3.8-Flash-Next only (the qwen and gyro families), so no other model is offered it. + // Drafting (which drafter guesses ahead): a choice exists only for Qwen3.8-Flash-Next (the qwen and gyro families) on a computer whose engine can run DFlash2; every other model has no dropdown. const draftingChoices = selectedSize ? draftingOptions(selectedSize.sourceFamily ?? selectedFamily?.family, native?.capabilities?.dflash2) : null; const draftingWords: Record<string, string> = { auto: 'Auto (recommended)', mtp: 'MTP', dflash2: 'DFlash2', off: 'Off' }; const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(cardsGpus.length > 1 ? { gpus: cardsGpus.join(',') } : cardsGpus.length === 1 ? { gpu: cardsGpus[0] } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, cardsGpus.join(','), expert, multiple]); @@ -214,6 +214,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(draftingChoices ? <div className="native-choice__col"><span className="native-choice__label">{tr("Drafting")}</span><Select ariaLabel={tr("Drafting")} value={drafting} disabled={!!active} options={draftingChoices.map(v => ({ value: v, label: tr(draftingWords[v]) }))} onChange={v => setDrafting(String(v))}/></div> : null)} <div className="native-choice__col"><span className="native-choice__label">{tr("Computer use")}</span><div className="native-resource-choice"><button aria-pressed={resourceProfile === 'work'} data-selected={resourceProfile === 'work'} onClick={() => setResourceProfile('work')}><Icon name="computer" size={20}/><span><strong>{tr("Leave 20% for my work")}</strong><small>{tr("Headroom for your other apps")}</small></span>{tr(resourceProfile === 'work' ? <Icon name="check" size={15}/> : null)}</button><button aria-pressed={resourceProfile === 'performance'} data-selected={resourceProfile === 'performance'} onClick={() => setResourceProfile('performance')}><Icon name="bolt" size={20}/><span><strong>{tr("Full performance")}</strong><small>{tr("Give Strata priority")}</small></span>{tr(resourceProfile === 'performance' ? <Icon name="check" size={15}/> : null)}</button></div></div> </div> + {tr(draftingChoices ? <p className="small muted native-spill-note"><Icon name="info" size={16}/>{tr("MTP is the default. DFlash2 is another way to guess the next words ahead, for Qwen3.8-Flash-Next only. On an RTX PRO 5000 it was 7.8% faster than MTP on 19 short prompts and 1.1% faster on long thinking, and faster on 21 of 23 prompts. On the short prompts the answers were identical.")} {tr("It downloads about 1.2 GB once, works with one graphics card and one request at a time, and uses MTP otherwise.")}{native?.capabilities?.dflash2Support?.line ? <> {tr(native.capabilities.dflash2Support.line)}</> : null}</p> : null)} {tr(loadedSelected?.metrics?.engine?.drafting_note ? <p className="small muted native-spill-note">{tr(String(loadedSelected.metrics.engine.drafting_note))}</p> : null)} {roleCards.length > 1 ? <GpuRoles cards={roleCards} roles={effectiveRoles} custom={customRoles} recommendedRoles={recommended.roles} vendor={engineVendor} disabled={!!active} onChange={changeRoles} onBack={() => setRoles(null)} memoryGb={selectedSize ? memoryNeeded(selectedSize) || null : null} ramGb={pcRam} spillGb={selectedSize ? fitOn(selectedSize, fitHardware).spillGb : 0} usedBy={i => usedBy([i])}/> : null} {tr(roleCards.length > 1 && (native?.hardware?.gpus ?? []).length > roleCards.length ? <p className="small muted native-cards__note">{tr('Not used: {0} (another make of graphics card than this engine drives).', [(native?.hardware?.gpus ?? []).filter(g => !roleCards.some(r => r.index === g.index && r.vendor === g.vendor)).map(g => g.name).join(', ')])}</p> : null)} diff --git a/apps/host/src/components/NativeSettings.tsx b/apps/host/src/components/NativeSettings.tsx index 356652fad9..10fd0dc694 100644 --- a/apps/host/src/components/NativeSettings.tsx +++ b/apps/host/src/components/NativeSettings.tsx @@ -7,6 +7,7 @@ import { api } from '../lib/client'; import { refreshNative, useNative, type NativeField } from '../lib/native'; import { Btn, ErrorNotice, Select } from './ui'; import { speedOptions } from '../lib/deepseek-speed'; +import { draftingChoices } from '../lib/drafting'; import type { RunCard } from '../lib/native-fit'; import { NativeMcpEditor } from './NativeMcpEditor'; /** One of the speed features: what it is called, what it does, whether it is on by default, and the engine environment it writes outside its default (server/native-settings.mjs). */ @@ -114,7 +115,9 @@ export function NativeSettings({ model }: { <summary>{tr('Native engine settings')}</summary> {error ? <><ErrorNotice message={tr('Couldn’t load model settings.')} next={tr('Check that the engine is connected and this model is installed, then try again.')} onRetry={() => setRevision(value => value + 1)}/><details className="native-settings-diagnostic"><summary className="small">{tr('Details')}</summary><p className="small muted">{error}</p></details></> : <p className="small muted" role="status">{tr('Reading saved settings…')}</p>} </details>; - const rows = (native?.fields ?? []).filter(f => (!f.forModel || (model.toLowerCase().includes(f.forModel) && (f.id !== 'ds_experts' || dsExperts))) && `${tr(f.label)} ${f.id} ${tr(f.group)}`.toLowerCase().includes(query.toLowerCase())); + const family = (native?.catalog?.families ?? []).find(f => f.sizes.some(s => s.id === model))?.family ?? null; + const draftingOffered = !!draftingChoices(family, native?.capabilities?.dflash2); + const rows = (native?.fields ?? []).filter(f => (!f.forModel || (model.toLowerCase().includes(f.forModel) && (f.id !== 'ds_experts' || dsExperts))) && (!f.notForModel || !model.toLowerCase().includes(f.notForModel)) && (f.id !== 'drafting' || draftingOffered) && `${tr(f.label)} ${f.id} ${tr(f.group)}`.toLowerCase().includes(query.toLowerCase())); const switchRows = switches.filter(sw => `${tr(sw.label)} ${sw.id} ${tr('Speed')}`.toLowerCase().includes(query.toLowerCase())); return <details className="native-settings"><summary>{tr("Native engine settings")}</summary>{tr(tuned?.changed?.length ? <div className="native-tuned"><p className="small"><strong>{tr("Your tuning '{0}' sets", [tuned.preset?.name ?? ''])}</strong></p><ul>{tuned.changed.map(c => { const d = describeChange(c); return <li key={c.flag}><span>{d.name}</span><b>{d.now || tr('off')}</b>{d.was !== null ? <small className="muted">{tr("was {0}", [d.was])}</small> : null}</li>; })}</ul></div> : null)}<p className="small muted">{tr(!original ? 'Reading saved settings… ' : '')}{tr("Settings for this model. Blank values use Strata\u2019s defaults.")}</p><div className="editor-tabs" role="tablist" aria-label={tr("Native settings editor")}>{tr(['fields', 'json', 'tools'].map(t => <button key={t} role="tab" aria-selected={tab === t} onClick={() => chooseTab(t)}>{tr(t === 'fields' ? 'Parameters' : t === 'json' ? 'JSON' : 'MCP tools')}</button>))}</div> {tr(tab === 'fields' ? <><input className="st-input" type="search" aria-label={tr("Search native parameters")} placeholder={tr("Search parameters…")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(['Responses', 'GPU & memory', 'Serving', 'Image reading', 'Tools', 'Recovery'].map(group => rows.some(f => f.group === group) ? <section className="native-settings-group" key={group}><h3 className="h4">{tr(group)}</h3>{tr(rows.filter(f => f.group === group).map(f => <label className="native-setting-row" key={f.id}><span><strong>{tr(f.label)}</strong>{tr(f.supported === false ? <small>{tr("Requires a newer Strata installation.")}</small> : f.hint ? <small>{tr(f.hint)}</small> : null)}</span><NativeFieldInput field={f} value={values[f.id]} onChange={v => change(f.id, v)}/></label>))}</section> : null))}{tr(switchRows.length ? <section className="native-settings-group"><h3 className="h4">{tr("Speed")}</h3>{tr(switchRows.map(sw => <label className="native-setting-row" key={sw.id}><span><strong>{tr(sw.label)}</strong><small>{tr(sw.hint)}</small></span><Select ariaLabel={tr(sw.label)} value={switchIsOn(sw, values.env) ? 'on' : 'off'} options={sw.default === 'on' ? [{ value: 'on', label: 'On (recommended)' }, { value: 'off', label: 'Off' }] : [{ value: 'off', label: 'Off (recommended)' }, { value: 'on', label: 'On' }]} onChange={v => changeSwitch(sw, v === 'on')}/></label>))}</section> : null)}<section className="native-settings-group"><h3 className="h4">{tr("Sampling")}</h3>{tr([['temperature', 'Temperature'], ['top_p', 'Top-p'], ['top_k', 'Top-k'], ['min_p', 'Min-p'], ['repetition_penalty', 'Repetition penalty'], ['presence_penalty', 'Presence penalty'], ['frequency_penalty', 'Frequency penalty'], ['penalty_last_n', 'Penalty window'], ['seed', 'Seed']].map(([id, label]) => <label className="native-setting-row" key={id}><span><strong>{tr(label)}</strong></span><DecimalInput ariaLabel={tr("Native {0}", [label])} value={values.sampling?.[id] ?? null} onChange={n => { const sampling = { ...values.sampling }; if (n === null) delete sampling[id]; else sampling[id] = n; change('sampling', sampling); }}/></label>))}</section></> : tab === 'json' ? <><p className="small muted">{tr("Engine arguments and STRATA environment flags are editable here. Program paths and network access remain managed by the host.")}</p><textarea className="st-input native-json" aria-label={tr("Native configuration JSON")} spellCheck={false} value={text} onChange={e => { setText(e.target.value); setNotice(''); }}/></> : <><p className="small muted">{tr("Add local programs or HTTP MCP servers. Connected tools can read or change the resources you give them access to. Enable tools in chat when you want the model to use them.")}</p><NativeMcpEditor text={mcp} onChange={value => { setMcp(value); setNotice(''); }}/><details><summary className="small">{tr("Configuration example")}</summary><pre className="native-example">{'{\n "files": {\n "command": "npx",\n "args": ["-y", "@modelcontextprotocol/server-filesystem", "/your/folder"],\n "disabled": false\n }\n}'}</pre><p className="xs muted">{tr("Saved credentials are masked. Keep the mask to preserve an existing value; type a new value to replace it.")}</p></details></>)} diff --git a/apps/host/src/components/PcFitCard.tsx b/apps/host/src/components/PcFitCard.tsx index 5e1dfd6478..312769366c 100644 --- a/apps/host/src/components/PcFitCard.tsx +++ b/apps/host/src/components/PcFitCard.tsx @@ -35,7 +35,7 @@ export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null, diskGb = {tr(m.fit.known && ramGb ? <div><dt>{tr("RAM")}</dt><dd>{about(m.fit.ramUseGb)}</dd></div> : null)} {tr(m.fit.known && m.fit.spillGb >= 1 ? <div><dt>{tr("SSD")}</dt><dd>{about(m.fit.spillGb)}</dd></div> : null)} </dl> - {tr(m.fit.known && m.fit.spillGb < 1 ? <p className="pc-note">{tr("Nothing. It fits in memory.")}</p> : null)} + {tr(m.fit.known && m.fit.spillGb < 1 ? <p className="pc-note">{tr("SSD: not needed")}</p> : null)} {tr(m.fit.known && m.fit.spillGb >= 1 ? <p className="pc-note">{tr("About {0} GB will be read from the SSD, so answers can be a little slower.", [Math.round(m.fit.spillGb)])}{tr(live?.diskReadGbs && live.diskReadGbs >= 0.05 ? tr(" Reading from your SSD now: {0}", [`${live.diskReadGbs.toFixed(1)} GB/s`]) : '')}</p> : null)} </div>))} {tr(live && (live.freeVramGb !== null || live.freeRamGb !== null) ? <div className="pc-free"> diff --git a/apps/host/src/lib/drafting.ts b/apps/host/src/lib/drafting.ts index 85c25b467f..ad2199bc8e 100644 --- a/apps/host/src/lib/drafting.ts +++ b/apps/host/src/lib/drafting.ts @@ -1,10 +1,15 @@ /** - * The Drafting choices the Models screen offers for a model. DFlash2 is for Qwen3.8-Flash-Next only (the qwen and gyro families) AND only while - * the engine serves it: strata_control/drafting.py ENGINE_SERVES_DFLASH2 (Control reports it as `capabilities.dflash2`). Until then the setting - * is Auto / MTP / Off; DFlash2 appears by itself when the engine can run it. The Terminal's --drafting flag has it either way, gated with a note. + * The Drafting choice the Models screen offers for a model. It exists only where there is something to choose: DFlash2 is for Qwen3.8-Flash-Next + * only (the qwen and gyro families), and only while this computer's engine can run it: strata_control/drafting.py hardware_support (Control reports it as + * `capabilities.dflash2`; Metal and Intel engines and PCs without a supported card have none). Every other model has no dropdown at all: DeepSeek has no + * MTP (its own DSpark drafter is chosen by the engine), and the other families have the MTP and nothing to pick against it (Settings > Draft layer turns it off). */ export const DRAFTING_FAMILIES = ['qwen', 'gyro']; -export function draftingChoices(family: string | null | undefined, dflash2Served: boolean | null | undefined): string[] { - return DRAFTING_FAMILIES.includes(String(family)) && dflash2Served === true ? ['auto', 'mtp', 'dflash2', 'off'] : ['auto', 'mtp', 'off']; +/** What was measured on this kind of card (Control's words): tested = faster on some text and slower on others, slower = slower on every prompt. */ +export interface Dflash2Support { level: 'tested' | 'slower' | 'untested'; line: string } + +/** The choices for a model, or null when there is nothing to choose (no dropdown). */ +export function draftingChoices(family: string | null | undefined, dflash2Served: boolean | null | undefined): string[] | null { + return DRAFTING_FAMILIES.includes(String(family)) && dflash2Served === true ? ['auto', 'mtp', 'dflash2', 'off'] : null; } diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index 814a6d7ba8..c888cb0372 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -66,6 +66,16 @@ import pick_ru from '../locales/pick-ru.json'; import pick_pt from '../locales/pick-pt.json'; import pick_ko from '../locales/pick-ko.json'; import pick_fr from '../locales/pick-fr.json'; +/* The strings of the Drafting choice and the SSD line (df2-<lang>.json, scripts/make-df2-locales.py). */ +import df2_en from '../locales/df2-en.json'; +import df2_zh from '../locales/df2-zh.json'; +import df2_ja from '../locales/df2-ja.json'; +import df2_de from '../locales/df2-de.json'; +import df2_es from '../locales/df2-es.json'; +import df2_ru from '../locales/df2-ru.json'; +import df2_pt from '../locales/df2-pt.json'; +import df2_ko from '../locales/df2-ko.json'; +import df2_fr from '../locales/df2-fr.json'; import base_zh from '../locales/zh.json'; import base_ja from '../locales/ja.json'; import base_de from '../locales/de.json'; @@ -80,8 +90,8 @@ export type Language=typeof LANGUAGES[number]['value']; /* The Tune model dialog's strings live in tune-<lang>.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ /* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-<lang>.json for the same reason. */ /* The strings that had no key in the files above (#3479, #3825) and the 0.2.4.3 fixes live in fix-<lang>.json (scripts/make-fix-locales.py). */ -const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en,...pick_en}; -const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh,...ui_zh,...engine_zh,...pick_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja,...ui_ja,...engine_ja,...pick_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de,...ui_de,...engine_de,...pick_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es,...ui_es,...engine_es,...pick_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru,...ui_ru,...engine_ru,...pick_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt,...ui_pt,...engine_pt,...pick_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko,...ui_ko,...engine_ko,...pick_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr,...gh_fr,...ui_fr,...engine_fr,...pick_fr}] as Record<string,string>[]; +const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en,...pick_en,...df2_en}; +const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh,...ui_zh,...engine_zh,...pick_zh,...df2_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja,...ui_ja,...engine_ja,...pick_ja,...df2_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de,...ui_de,...engine_de,...pick_de,...df2_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es,...ui_es,...engine_es,...pick_es,...df2_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru,...ui_ru,...engine_ru,...pick_ru,...df2_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt,...ui_pt,...engine_pt,...pick_pt,...df2_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko,...ui_ko,...engine_ko,...pick_ko,...df2_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr,...gh_fr,...ui_fr,...engine_fr,...pick_fr,...df2_fr}] as Record<string,string>[]; const catalogs:Record<Language,Record<string,string>>={en:english,zh,ja,de,fr,es,ru,pt,ko}; const entities:Record<string,string>={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'}; const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole); diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index 642a18f1ae..539c516512 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -5,14 +5,14 @@ export interface GpuChoiceOption {key:string;cards:number[];label:string;verdict export interface GpuChoice {options:GpuChoiceOption[];recommended:string|null;ignored:{name?:string;why_ignored:string}[];cards:number} export interface NativeSize {/** The first engine that reads this size's files (the catalog), and whether the installed engine is older: the screen then says "needs a newer engine" and offers the update. */engine_min?:string|null;needsNewerEngine?:boolean;id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean;gpu_options?:GpuChoice|null;images?:boolean;imagesCapable?:boolean;/** DeepSeek-V4.1-Flash and the like: several big files and an engine of their own. */multi_file?:boolean;/** DeepSeek: the free disk the set needs (its download plus the pack and room to work), from the set itself. */disk_gb?:number} export interface NativeFamily {family:string;title:string;about:string;experimental:boolean;images:boolean;sizes:NativeSize[]} -export interface NativeField {id:string;label:string;group:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean;forModel?:string} +export interface NativeField {id:string;label:string;group:string;/** Not shown for a model whose id contains this (DeepSeek has no MTP). */notForModel?:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean;forModel?:string} export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;family?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;result:Record<string,any>|null;progress?:Record<string,any>|null} export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;resourceProfile?:'work'|'performance'|null;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record<string,any>|null} export interface NativeState { /** The picture reader (strata-vision) is installed with the engine, so models marked for pictures can read them here. */ /** Strata Control's view of the engine for this computer (the app): usable false = none found or recognised; `notice` says why in plain words. */ engine?:{usable:boolean;notice?:string|null;wrongMake?:boolean;version?:string|null;/** What the last update check found newer (kept on this PC, read without the network): the Qwen engine, the DeepSeek engine, the app. */updateAvailable?:{engine?:string|null;dsv41?:string|null;app?:string|null}|null}; - 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;/** DeepSeek: the most context its pack reads (max_position_embeddings in the pack's ds4.txt); absent when the pack does not say. */contextMax?:number;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<string,{bytes:number;gb:number}>}|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}} + 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;/** DeepSeek: the most context its pack reads (max_position_embeddings in the pack's ds4.txt); absent when the pack does not say. */contextMax?:number;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<string,{bytes:number;gb:number}>}|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;/** What was measured on this kind of card, in Control's words (null until Control answers). */dflash2Support?:{level:'tested'|'slower'|'untested';line:string}|null;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). */ diff --git a/apps/host/src/locales/df2-de.json b/apps/host/src/locales/df2-de.json new file mode 100644 index 0000000000..0f39c67ee5 --- /dev/null +++ b/apps/host/src/locales/df2-de.json @@ -0,0 +1,10 @@ +{ + "df01": "MTP ist die Voreinstellung. DFlash2 ist eine andere Art, die nächsten Wörter vorauszuraten, nur für Qwen3.8-Flash-Next. Auf einer RTX PRO 5000 war es bei 19 kurzen Prompts 7,8 % schneller als MTP, bei langem Nachdenken 1,1 % schneller und bei 21 von 23 Prompts schneller. Bei den kurzen Prompts waren die Antworten identisch.", + "df02": "Es lädt einmalig etwa 1,2 GB herunter, funktioniert mit einer Grafikkarte und einer Anfrage zur Zeit und nutzt sonst MTP.", + "df03": "Auf Grafikkarten wie Ihrer war DFlash2 in unseren Tests bei manchen Textarten schneller als MTP und bei anderen langsamer.", + "df04": "Auf Grafikkarten wie Ihrer war DFlash2 in unseren Tests langsamer als MTP.", + "df05": "DFlash2 wurde auf Ihrer Grafikkarte noch nicht getestet.", + "df06": "Vorausraten: MTP (DFlash2 ist auf dieser Grafikkarte nicht verfügbar)", + "df07": "Es besteht keine Internetverbindung, deshalb kann der DFlash2-Drafter jetzt nicht heruntergeladen werden.", + "df08": "SSD: nicht nötig" +} diff --git a/apps/host/src/locales/df2-en.json b/apps/host/src/locales/df2-en.json new file mode 100644 index 0000000000..49683541f8 --- /dev/null +++ b/apps/host/src/locales/df2-en.json @@ -0,0 +1,10 @@ +{ + "df01": "MTP is the default. DFlash2 is another way to guess the next words ahead, for Qwen3.8-Flash-Next only. On an RTX PRO 5000 it was 7.8% faster than MTP on 19 short prompts and 1.1% faster on long thinking, and faster on 21 of 23 prompts. On the short prompts the answers were identical.", + "df02": "It downloads about 1.2 GB once, works with one graphics card and one request at a time, and uses MTP otherwise.", + "df03": "On graphics cards like yours, DFlash2 was faster than MTP on some kinds of text and slower on others in our tests.", + "df04": "On graphics cards like yours, DFlash2 was slower than MTP in our tests.", + "df05": "DFlash2 has not been tested on your graphics card yet.", + "df06": "Drafting: MTP (DFlash2 isn't available on this graphics card)", + "df07": "There is no internet connection, so the DFlash2 drafter can't be downloaded now.", + "df08": "SSD: not needed" +} diff --git a/apps/host/src/locales/df2-es.json b/apps/host/src/locales/df2-es.json new file mode 100644 index 0000000000..44970dbfa5 --- /dev/null +++ b/apps/host/src/locales/df2-es.json @@ -0,0 +1,10 @@ +{ + "df01": "MTP es la opción predeterminada. DFlash2 es otra forma de adivinar las siguientes palabras por adelantado, solo para Qwen3.8-Flash-Next. En una RTX PRO 5000 fue un 7,8 % más rápido que MTP en 19 prompts cortos y un 1,1 % más rápido en razonamientos largos, y más rápido en 21 de 23 prompts. En los prompts cortos las respuestas fueron idénticas.", + "df02": "Descarga unos 1,2 GB una sola vez, funciona con una tarjeta gráfica y una solicitud a la vez, y en los demás casos usa MTP.", + "df03": "En tarjetas gráficas como la suya, en nuestras pruebas DFlash2 fue más rápido que MTP con algunos tipos de texto y más lento con otros.", + "df04": "En tarjetas gráficas como la suya, en nuestras pruebas DFlash2 fue más lento que MTP.", + "df05": "DFlash2 todavía no se ha probado en su tarjeta gráfica.", + "df06": "Predicción: MTP (DFlash2 no está disponible en esta tarjeta gráfica)", + "df07": "No hay conexión a internet, así que ahora no se puede descargar el borrador de DFlash2.", + "df08": "SSD: no hace falta" +} diff --git a/apps/host/src/locales/df2-fr.json b/apps/host/src/locales/df2-fr.json new file mode 100644 index 0000000000..da81041adb --- /dev/null +++ b/apps/host/src/locales/df2-fr.json @@ -0,0 +1,10 @@ +{ + "df01": "MTP est le réglage par défaut. DFlash2 est une autre façon de deviner à l’avance les mots suivants, uniquement pour Qwen3.8-Flash-Next. Sur une RTX PRO 5000, il a été 7,8 % plus rapide que MTP sur 19 prompts courts et 1,1 % plus rapide en réflexion longue, et plus rapide sur 21 prompts sur 23. Sur les prompts courts, les réponses étaient identiques.", + "df02": "Il télécharge environ 1,2 Go une seule fois, fonctionne avec une carte graphique et une requête à la fois, et utilise MTP sinon.", + "df03": "Sur des cartes graphiques comme la vôtre, DFlash2 a été plus rapide que MTP sur certains types de texte et plus lent sur d’autres lors de nos tests.", + "df04": "Sur des cartes graphiques comme la vôtre, DFlash2 a été plus lent que MTP lors de nos tests.", + "df05": "DFlash2 n’a pas encore été testé sur votre carte graphique.", + "df06": "Anticipation : MTP (DFlash2 n’est pas disponible sur cette carte graphique)", + "df07": "Il n’y a pas de connexion internet, le drafter DFlash2 ne peut donc pas être téléchargé pour le moment.", + "df08": "SSD : pas nécessaire" +} diff --git a/apps/host/src/locales/df2-ja.json b/apps/host/src/locales/df2-ja.json new file mode 100644 index 0000000000..468f829cc2 --- /dev/null +++ b/apps/host/src/locales/df2-ja.json @@ -0,0 +1,10 @@ +{ + "df01": "既定では MTP を使います。DFlash2 は次の語を先読みするもう一つの方法で、Qwen3.8-Flash-Next 専用です。RTX PRO 5000 では、短いプロンプト 19 件で MTP より 7.8% 速く、長い思考では 1.1% 速く、23 件中 21 件で速くなりました。短いプロンプトでは回答が同一でした。", + "df02": "約 1.2 GB を一度だけダウンロードします。グラフィックスカード 1 枚で一度に 1 件のリクエストを処理するときに動作し、それ以外では MTP を使います。", + "df03": "お使いのようなグラフィックスカードでは、私たちのテストで DFlash2 は MTP より速い種類の文章と遅い種類の文章がありました。", + "df04": "お使いのようなグラフィックスカードでは、私たちのテストで DFlash2 は MTP より遅くなりました。", + "df05": "DFlash2 はまだお使いのグラフィックスカードでテストされていません。", + "df06": "先読み:MTP(DFlash2 はこのグラフィックスカードでは使えません)", + "df07": "インターネットに接続されていないため、今は DFlash2 のドラフターをダウンロードできません。", + "df08": "SSD:不要" +} diff --git a/apps/host/src/locales/df2-ko.json b/apps/host/src/locales/df2-ko.json new file mode 100644 index 0000000000..7cb254f647 --- /dev/null +++ b/apps/host/src/locales/df2-ko.json @@ -0,0 +1,10 @@ +{ + "df01": "기본값은 MTP입니다. DFlash2는 다음 단어를 미리 추측하는 또 다른 방식이며 Qwen3.8-Flash-Next 전용입니다. RTX PRO 5000에서 짧은 프롬프트 19개에서는 MTP보다 7.8% 빨랐고, 긴 사고 과정에서는 1.1% 빨랐으며, 23개 중 21개 프롬프트에서 더 빨랐습니다. 짧은 프롬프트에서는 답변이 동일했습니다.", + "df02": "약 1.2 GB를 한 번만 내려받으며, 그래픽 카드 한 장과 한 번에 하나의 요청에서 작동하고, 그 외에는 MTP를 사용합니다.", + "df03": "고객님과 비슷한 그래픽 카드에서 저희 테스트 결과 DFlash2는 일부 유형의 글에서는 MTP보다 빨랐고 다른 유형에서는 더 느렸습니다.", + "df04": "고객님과 비슷한 그래픽 카드에서 저희 테스트 결과 DFlash2는 MTP보다 느렸습니다.", + "df05": "DFlash2는 아직 고객님의 그래픽 카드에서 테스트되지 않았습니다.", + "df06": "미리 추측: MTP (이 그래픽 카드에서는 DFlash2를 사용할 수 없습니다)", + "df07": "인터넷에 연결되어 있지 않아 지금은 DFlash2 드래프터를 내려받을 수 없습니다.", + "df08": "SSD: 필요 없음" +} diff --git a/apps/host/src/locales/df2-pt.json b/apps/host/src/locales/df2-pt.json new file mode 100644 index 0000000000..cdd76aefe6 --- /dev/null +++ b/apps/host/src/locales/df2-pt.json @@ -0,0 +1,10 @@ +{ + "df01": "MTP é o padrão. DFlash2 é outra forma de adivinhar as próximas palavras antecipadamente, só para o Qwen3.8-Flash-Next. Numa RTX PRO 5000 foi 7,8 % mais rápido que o MTP em 19 prompts curtos e 1,1 % mais rápido em raciocínios longos, e mais rápido em 21 de 23 prompts. Nos prompts curtos as respostas foram idênticas.", + "df02": "Baixa cerca de 1,2 GB uma única vez, funciona com uma placa de vídeo e um pedido de cada vez, e nos outros casos usa o MTP.", + "df03": "Em placas de vídeo como a sua, nos nossos testes o DFlash2 foi mais rápido que o MTP em alguns tipos de texto e mais lento em outros.", + "df04": "Em placas de vídeo como a sua, nos nossos testes o DFlash2 foi mais lento que o MTP.", + "df05": "O DFlash2 ainda não foi testado na sua placa de vídeo.", + "df06": "Previsão: MTP (o DFlash2 não está disponível nesta placa de vídeo)", + "df07": "Não há ligação à internet, por isso não é possível transferir agora o rascunhador do DFlash2.", + "df08": "SSD: não é necessário" +} diff --git a/apps/host/src/locales/df2-ru.json b/apps/host/src/locales/df2-ru.json new file mode 100644 index 0000000000..e294233e19 --- /dev/null +++ b/apps/host/src/locales/df2-ru.json @@ -0,0 +1,10 @@ +{ + "df01": "По умолчанию используется MTP. DFlash2 — другой способ угадывать следующие слова наперёд, только для Qwen3.8-Flash-Next. На RTX PRO 5000 он был на 7,8 % быстрее MTP на 19 коротких запросах и на 1,1 % быстрее на длинных рассуждениях, а на 21 из 23 запросов — быстрее. На коротких запросах ответы были идентичны.", + "df02": "Один раз скачивает около 1,2 ГБ, работает с одной видеокартой и одним запросом за раз, в остальных случаях используется MTP.", + "df03": "На видеокартах, подобных вашей, в наших тестах DFlash2 был быстрее MTP на одних видах текста и медленнее на других.", + "df04": "На видеокартах, подобных вашей, в наших тестах DFlash2 был медленнее MTP.", + "df05": "DFlash2 ещё не проверялся на вашей видеокарте.", + "df06": "Упреждающая генерация: MTP (DFlash2 недоступен на этой видеокарте)", + "df07": "Нет подключения к интернету, поэтому сейчас нельзя скачать черновую модель DFlash2.", + "df08": "SSD: не нужен" +} diff --git a/apps/host/src/locales/df2-zh.json b/apps/host/src/locales/df2-zh.json new file mode 100644 index 0000000000..55628ac759 --- /dev/null +++ b/apps/host/src/locales/df2-zh.json @@ -0,0 +1,10 @@ +{ + "df01": "默认使用 MTP。DFlash2 是另一种提前猜测后续词语的方式,仅适用于 Qwen3.8-Flash-Next。在 RTX PRO 5000 上,它在 19 个短提示上比 MTP 快 7.8%,在长篇思考上快 1.1%,并且在 23 个提示中有 21 个更快。在短提示上,回答完全相同。", + "df02": "它会一次性下载约 1.2 GB,仅在使用一张显卡且一次处理一个请求时有效,其他情况下使用 MTP。", + "df03": "在与您类似的显卡上,我们的测试中 DFlash2 在某些类型的文本上比 MTP 快,在另一些上更慢。", + "df04": "在与您类似的显卡上,我们的测试中 DFlash2 比 MTP 更慢。", + "df05": "DFlash2 尚未在您的显卡上测试过。", + "df06": "预测方式:MTP(DFlash2 不适用于这张显卡)", + "df07": "没有网络连接,因此现在无法下载 DFlash2 草稿模型。", + "df08": "SSD:不需要" +} diff --git a/apps/host/tests/drafting.test.mjs b/apps/host/tests/drafting.test.mjs index fe7d398f22..6d09db21d4 100644 --- a/apps/host/tests/drafting.test.mjs +++ b/apps/host/tests/drafting.test.mjs @@ -79,14 +79,19 @@ test('a load fetches the drafter first, never stops for it, and says what ran', test('every sentence of the Drafting choice is in the catalog in all nine languages, with the same slots', () => { const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; - const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(read(`../src/locales/${l}.json`))])); + const catalogs = Object.fromEntries(langs.map(l => [l, { ...JSON.parse(read(`../src/locales/${l}.json`)), ...JSON.parse(read(`../src/locales/df2-${l}.json`)) }])); const idOf = text => Object.entries(catalogs.en).find(([, v]) => v === text)?.[0]; const sentences = ['Drafting', 'Auto (recommended)', 'MTP', 'DFlash2', "Drafting: MTP (DFlash2 didn't fit)", "Drafting: MTP (DFlash2 isn't available in this mode)", 'Drafting: MTP (DFlash2 is for Qwen3.8-Flash-Next only)', "Drafting: MTP (the DFlash2 drafter isn't downloaded yet)", 'Choosing DFlash2 also downloads its drafter: about {0} GB, once. If it does not fit in graphics memory, the model uses the MTP instead.', 'Downloading the DFlash2 drafter…', 'Packing the DFlash2 drafter for the engine…', 'The DFlash2 drafter is ready.', - 'The DFlash2 drafter could not be downloaded, so the model starts with the MTP. Loading the model…', 'Loading the model…']; + 'The DFlash2 drafter could not be downloaded, so the model starts with the MTP. Loading the model…', 'Loading the model…', + // the DFlash2 option (df2-<lang>.json): the paragraph under the dropdown, the lines about the card, the two new notes + "Drafting: MTP (DFlash2 isn't available on this graphics card)", "There is no internet connection, so the DFlash2 drafter can't be downloaded now.", + 'It downloads about 1.2 GB once, works with one graphics card and one request at a time, and uses MTP otherwise.', + 'On graphics cards like yours, DFlash2 was faster than MTP on some kinds of text and slower on others in our tests.', + 'On graphics cards like yours, DFlash2 was slower than MTP in our tests.', 'DFlash2 has not been tested on your graphics card yet.', 'SSD: not needed']; const slots = t => (t.match(/\{\d+\}/g) ?? []).sort().join(); for (const text of sentences) { const id = idOf(text); @@ -100,24 +105,51 @@ test('every sentence of the Drafting choice is in the catalog in all nine langua } }); -test('DFlash2 is offered only for Qwen3.8-Flash-Next AND only once the engine serves it; until then the setting is Auto / MTP / Off', async () => { +test('the Drafting dropdown exists only where there is something to choose: Qwen3.8-Flash-Next (qwen, gyro) on a computer whose engine can run DFlash2', async () => { const { transform } = await import('esbuild'); const code = (await transform(read('../src/lib/drafting.ts'), { loader: 'ts', format: 'esm' })).code; const { draftingChoices } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); - const off = ['auto', 'mtp', 'off'], all = ['auto', 'mtp', 'dflash2', 'off']; - // the engine does not serve it (this release): never offered - for (const family of ['qwen', 'gyro', 'coder', 'swift', undefined]) { - assert.deepEqual(draftingChoices(family, false), off, `${family}, not served`); - assert.deepEqual(draftingChoices(family, undefined), off, `${family}, Control has not answered`); - assert.deepEqual(draftingChoices(family, null), off); + const all = ['auto', 'mtp', 'dflash2', 'off']; + // the engine here cannot run it (Metal, Intel, no card), or Control has not answered yet: no dropdown for anyone + for (const family of ['qwen', 'gyro', 'coder', 'swift', 'deepseek41', undefined]) { + assert.equal(draftingChoices(family, false), null, `${family}, not served`); + assert.equal(draftingChoices(family, undefined), null, `${family}, Control has not answered`); + assert.equal(draftingChoices(family, null), null); } - // the engine serves it: only the models it is for + // it can: only the models it is for. DeepSeek has no MTP (its DSpark drafter is chosen by the engine); the other families have the MTP and nothing to pick against it. assert.deepEqual(draftingChoices('qwen', true), all); assert.deepEqual(draftingChoices('gyro', true), all); - for (const family of ['coder', 'swift', 'unsloth', 'nvfp4', undefined]) assert.deepEqual(draftingChoices(family, true), off, `${family}, served`); + for (const family of ['coder', 'swift', 'unsloth', 'nvfp4', 'qwen36', 'deepseek41', undefined]) assert.equal(draftingChoices(family, true), null, `${family}, served`); // the app learns it from Control, once, and false until Control answers const host = read('../server/native-control.mjs'); - assert.match(host, /dflash2:dflash2Served===true/); + assert.match(host, /dflash2:dflash2Served===true,dflash2Support\}/); assert.match(host, /dflash2Served=p\.serves===true/); assert.match(host, /function probeDrafting\(\)\{if\(!packaged\|\|dflash2Served!==null/); + const screen = read('../src/components/NativeModels.tsx'); + assert.match(screen, /\{tr\(draftingChoices \? <div className="native-choice__col">/, 'no choices: no column'); +}); + +test('Settings > Native engine settings hides the MTP and Drafting rows for DeepSeek and the Drafting row where it has no choice', () => { + const byId = Object.fromEntries(NATIVE_FIELDS.map(f => [f.id, f])); + for (const id of ['mtp', 'drafting', 'batchMtp']) assert.equal(byId[id].notForModel, 'deepseek', id); + assert.equal(byId.ds_experts.forModel, 'deepseek'); + const settings = read('../src/components/NativeSettings.tsx'); + assert.match(settings, /\(!f\.notForModel \|\| !model\.toLowerCase\(\)\.includes\(f\.notForModel\)\) && \(f\.id !== 'drafting' \|\| draftingOffered\)/); +}); + +test('the DFlash2 drafter is fetched only by the Models screen own Load: a restart, a tuning run or any other load never downloads', () => { + const source = read('../server/native-control.mjs'); + const prepare = source.slice(source.indexOf('async function prepareDrafter'), source.indexOf('function rememberSetting')); + assert.match(prepare, /asked===undefined\|\|!cfg\.drafting/, 'no explicit choice in this job: return before any fetch'); + const loadScreen = read('../src/components/NativeModels.tsx'); + assert.match(loadScreen, /\.\.\.\(draftingChoices \? \{ values: \{ drafting \} \} : \{\}\)/, 'the screen passes the choice only when it showed the dropdown'); + const tune = source.slice(source.indexOf("const loaded=await loadEngine(job,{model:args.model,multiple:false"), source.indexOf("const loaded=await loadEngine(job,{model:args.model,multiple:false") + 140); + assert.doesNotMatch(tune, /values:/, 'the tuning run loads without a choice'); +}); + +test('the paragraph under the dropdown quotes the measurements without a verdict', () => { + const screen = read('../src/components/NativeModels.tsx'); + for (const part of ['7.8% faster than MTP on 19 short prompts', '1.1% faster on long thinking', 'faster on 21 of 23 prompts', 'the answers were identical']) assert.ok(screen.includes(part), part); + const en = JSON.parse(read('../src/locales/df2-en.json')); + for (const text of Object.values(en)) for (const word of ['recommend', 'best ', 'better', 'should']) assert.ok(!text.toLowerCase().includes(word), `${word} in "${text.slice(0, 50)}"`); }); diff --git a/apps/host/tests/pc-card.test.mjs b/apps/host/tests/pc-card.test.mjs index 7557af4747..2e8629888a 100644 --- a/apps/host/tests/pc-card.test.mjs +++ b/apps/host/tests/pc-card.test.mjs @@ -43,7 +43,7 @@ test('a loaded model changes the card: it says Loaded and what the model takes o assert.match(fits, /<dt>Graphics memory<\/dt><dd>12 GB<\/dd>/); assert.match(fits, /<dt>RAM<\/dt><dd>44 GB<\/dd>/); assert.doesNotMatch(fits, /<dt>SSD<\/dt>/, 'it fits: no SSD row'); - assert.match(fits, /Nothing\. It fits in memory\./); + assert.match(fits, /SSD: not needed/, 'the SSD line has its label even when nothing is read from it'); const spills = card({ fit: fit(18), live: { ...live, diskReadGbs: 1.2 }, loaded: [{ id: 'q', label: 'Qwen3.8-Flash-Next · UD-Q4_K_XL', fit: fit(18, 12, 53) }], selectedLoaded: true }); assert.match(spills, /<dt>SSD<\/dt><dd>18 GB<\/dd>/); assert.match(spills, /Reading from your SSD now: 1\.2 GB\/s/); diff --git a/serve/server.py b/serve/server.py index 4823ddf4d2..b68484c256 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3401,7 +3401,8 @@ def engine_args(cfg: dict) -> list[str]: # guesses ahead. A choice that cannot be applied starts the MTP and says why in the engine's /metrics ("drafting_note"). if cfg.get("drafting") is not None or drafting.suggest(drafting_card_class()) != "mtp": shaped = {**cfg, "args": args} - decision = drafting.apply(shaped, klass=drafting_card_class(), data_dir=drafting.data_dir_of(args)) + backend, archs = drafting.detect_hardware() + decision = drafting.apply(shaped, klass=drafting_card_class(), data_dir=drafting.data_dir_of(args), backend=backend, archs=archs) args = shaped["args"] drafting.remember_note(decision.note) if decision.note: diff --git a/strata_cli/drafting_cmd.py b/strata_cli/drafting_cmd.py index 716893ae78..4ce995f648 100644 --- a/strata_cli/drafting_cmd.py +++ b/strata_cli/drafting_cmd.py @@ -29,12 +29,8 @@ def add_parser(sp) -> None: one.add_argument("--output", choices=("human", "json", "jsonl"), default="human") -def _card_class() -> str: - try: - from strata_control import engine_component - return drafting.card_class(list(engine_component.cuda_archs_present()) + list(engine_component.hip_archs_present())) - except Exception: # noqa: BLE001 - an unknown card is the "other" class - return "other" +def _hardware() -> tuple[str | None, list[str]]: + return drafting.detect_hardware() def _inputs(a) -> dict: @@ -51,7 +47,9 @@ def _inputs(a) -> dict: if data is None: from strata_cli.launch.catalog import Catalog data = Catalog().data_dir() - return {"mode": a.mode if a.mode else cfg.get("drafting"), "klass": _card_class(), "model_name": cfg.get("model_name"), "family": a.family, "data_dir": data} + backend, archs = _hardware() + return {"mode": a.mode if a.mode else cfg.get("drafting"), "klass": drafting.card_class(archs), "model_name": cfg.get("model_name"), "family": a.family, "data_dir": data, + "backend": backend, "archs": archs} def run(a) -> int: @@ -61,9 +59,11 @@ def run(a) -> int: folder = want["data_dir"] needed = drafting.needs_pack(**want) if a.drafting_command == "plan": - decision = drafting.decide(want["mode"], klass=want["klass"], model_name=want["model_name"], family=want["family"], data_dir=folder) - result = {**drafting_fetch.plan(folder), "needed": needed, "serves": drafting.ENGINE_SERVES_DFLASH2, "drafter": decision.drafter, "note": decision.note, - "line": drafting.summary_line(decision)} + decision = drafting.decide(**want) + support = drafting.hardware_support(want["backend"], want["archs"]) + # serves: this computer's engine can run DFlash2 (the build has the code and the card is one it is made for); the app offers the choice only then + result = {**drafting_fetch.plan(folder), "needed": needed, "serves": drafting.ENGINE_SERVES_DFLASH2 and support.can_run, "drafter": decision.drafter, + "note": decision.note, "line": drafting.summary_line(decision), "support": support.level, "support_line": support.line} if (a.config or a.mode) and not needed: # asked about a model: nothing to download unless the choice uses the drafter result["gb"] = 0.0 if machine: diff --git a/strata_cli/launch/app.py b/strata_cli/launch/app.py index 8d7d90f25b..bcf20c02c4 100644 --- a/strata_cli/launch/app.py +++ b/strata_cli/launch/app.py @@ -23,12 +23,12 @@ from strata_cli.launch import settings as S from strata_cli.launch import store from strata_cli.launch.catalog import Catalog from strata_cli.launch.runner import Cancelled, Event, LaunchError, Result, Runner, read_config -from strata_cli.launch.screens import (AccessScreen, AdvancedScreen, CardsScreen, ConfirmScreen, ContextScreen, FolderScreen, +from strata_cli.launch.screens import (AccessScreen, AdvancedScreen, CardsScreen, ConfirmScreen, ContextScreen, DraftingScreen, FolderScreen, ModelScreen, ParallelScreen, PicturesScreen, RunScreen, SaveScreen, SpeedScreen, StartScreen, TuningScreen, flow_for) from strata_cli.launch.widgets import CSS, Glyphs -SCREENS = {"model": ModelScreen, "cards": CardsScreen, "folder": FolderScreen, "context": ContextScreen, "pictures": PicturesScreen, "speed": SpeedScreen, +SCREENS = {"model": ModelScreen, "cards": CardsScreen, "folder": FolderScreen, "context": ContextScreen, "pictures": PicturesScreen, "speed": SpeedScreen, "drafting": DraftingScreen, "parallel": ParallelScreen, "tuning": TuningScreen, "advanced": AdvancedScreen, "access": AccessScreen, "save": SaveScreen} diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index bc849cf504..abce224638 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -1461,14 +1461,12 @@ class Runner: # ---- 3. config and profile def drafting_inputs(self, cfg: dict) -> dict: """What strata_control/drafting.py needs to decide for this launch: the choice, the card class, the model and the data folder.""" - from strata_control import drafting, engine_component - try: - archs = list(engine_component.cuda_archs_present()) + list(engine_component.hip_archs_present()) - except Exception: # noqa: BLE001 - an unknown card is the "other" class - archs = [] + from strata_control import drafting + backend, archs = drafting.detect_hardware() mode = self.s.drafting if self.s.drafting is not None else cfg.get("drafting") return {"mode": mode, "klass": drafting.card_class(archs), "model_name": cfg.get("model_name"), "family": self.s.family, - "data_dir": drafting.data_dir_of(cfg.get("args") or []) or (Path(self.s.data_dir) if self.s.data_dir else None)} + "data_dir": drafting.data_dir_of(cfg.get("args") or []) or (Path(self.s.data_dir) if self.s.data_dir else None), + "backend": backend, "archs": archs} def ensure_drafter(self, base_path: Path) -> None: """Fetch the DFlash2 drafter when this launch will use it and it is not here yet. Never stops the launch: if it cannot be had, the model @@ -2228,8 +2226,7 @@ class Runner: try: base, cfg = self.installed_state() want = self.drafting_inputs(cfg or {}) - return drafting.summary_line(drafting.decide(want["mode"], klass=want["klass"], model_name=want["model_name"], family=want["family"], - data_dir=want["data_dir"])) + return drafting.summary_line(drafting.decide(**want)) except Exception: # noqa: BLE001 return "" diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index b3d16440e9..e611567d5f 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -32,7 +32,7 @@ STEPS = (("model", "Model"), ("cards", "Cards"), ("folder", "Folder"), ("context ("parallel", "Parallel"), ("tuning", "Tuning"), ("advanced", "Advanced"), ("access", "Access"), ("save", "Save")) -STEP_LABELS = {**dict(STEPS), "speed": "Speed"} +STEP_LABELS = {**dict(STEPS), "speed": "Speed", "drafting": "Drafting"} def speed_choice_available(ctx) -> bool: @@ -52,13 +52,26 @@ def speed_choice_available(ctx) -> bool: return cached +def drafting_choice_available(ctx) -> bool: + """The Drafting step exists only where there is something to choose: Qwen3.8-Flash-Next (qwen, gyro) on a computer whose engine can run DFlash2 + (CUDA or HIP, strata_control/drafting.py). Every other model has no step: DeepSeek has no MTP, the rest have only the MTP.""" + from strata_control import drafting + if getattr(getattr(ctx, "settings", None), "family", None) not in drafting.SUPPORTED_FAMILIES or not drafting.ENGINE_SERVES_DFLASH2: + return False + backend, archs = drafting.detect_hardware() + return drafting.hardware_support(backend, archs).can_run + + def flow_for(ctx) -> list[str]: - """The steps of this computer: the Cards step exists only when two or more graphics cards can be used; the Speed step only for DeepSeek.""" + """The steps of this computer: the Cards step exists only when two or more graphics cards can be used; the Speed step only for DeepSeek; the Drafting + step only for Qwen3.8-Flash-Next on a computer that can run DFlash2.""" ids = [sid for sid, _ in STEPS] if len(ctx.computer.usable_gpus) < 2: ids.remove("cards") if getattr(getattr(ctx, "settings", None), "family", None) == "deepseek41" and speed_choice_available(ctx): ids.insert(ids.index("context") + 1, "speed") + if drafting_choice_available(ctx): + ids.insert(ids.index("pictures") + 1, "drafting") return ids @@ -1112,6 +1125,43 @@ class SpeedScreen(Base): self.ctx.settings.speed = None if key == default else key # the default stays "the default for this PC" in a saved preset +class DraftingScreen(Base): + step_id = "drafting" + help_text = ("Drafting is how the model guesses the next words ahead to make answers faster. MTP comes with the model. DFlash2 is another way, for " + "Qwen3.8-Flash-Next only. Auto uses MTP today.") + + CHOICES = (("auto", "Auto (recommended)"), ("mtp", "MTP"), ("dflash2", "DFlash2"), ("off", "Off")) + + def body(self) -> ComposeResult: + yield Static(Text("How should the model guess ahead?", style=f"bold {ACCENT}"), markup=False) + yield Menu(id="menu") + + def on_mount(self) -> None: + s = self.ctx.settings + items = [Item([label, Cell("MTP today", "") if key == "auto" else Cell("", "")], key=key) for key, label in self.CHOICES] + sel = [key for key, _ in self.CHOICES].index(s.drafting) if s.drafting in dict(self.CHOICES) else 0 + self.query_one(Menu).columns = [("", 24), ("", 0)] + self.query_one(Menu).set_items(items, sel) + self.paint() + + def explain(self) -> Text: + from strata_control import drafting + key = self.menu().current.key if self.menu() and self.menu().current else "auto" + if key == "dflash2": + backend, archs = drafting.detect_hardware() + line = drafting.hardware_support(backend, archs).line + return Text(" ".join(x for x in (drafting.EXPLAIN_NUMBERS, drafting.EXPLAIN_LIMITS, line) if x), style=MUTE) + if key == "off": + return Text("No draft layer: about 1 GB less graphics memory and less RAM, and answers come a little slower.", style=MUTE) + if key == "mtp": + return Text("MTP is the draft layer that comes with the model. It guesses several words ahead and costs about 1 GB of graphics memory.", style=MUTE) + return Text("Strata picks how the model guesses ahead. Today that is MTP.", style=MUTE) + + def commit(self) -> None: + key = self.menu().current.key + self.ctx.settings.drafting = None if key == "auto" else key # Auto stays "nobody chose": a saved preset writes nothing + + # ------------------------------------------------------------------------------------------------ 6 parallel class ParallelScreen(Base): @@ -1601,6 +1651,7 @@ class SaveScreen(Base): ("Pictures", "on" if s.vision != "off" else "off"), *([("Speed", S.speed_words(s.speed or ("faster" if faster_by_default(self.ctx.computer, s) else "full"), s.speed is None))] if s.family == "deepseek41" and speed_choice_available(self.ctx) else []), + *([("Drafting", dict(DraftingScreen.CHOICES).get(s.drafting or "auto", "Auto (recommended)"))] if drafting_choice_available(self.ctx) else []), ("Parallel", f"{s.parallel} at a time" if s.parallel else f"fit to your card ({S.fit_parallel(self.ctx.computer.main_vram_gb)})"), ("Tuning", ({"quick": "quick (about 5-10 min)", "thorough": "thorough (about 10-15 min)", "skip": "skipped"} if s.family == "deepseek41" else {"quick": "quick (about 20 min)", "thorough": "thorough (up to 2 h)", "skip": "skipped"})[s.tune]), diff --git a/strata_control/drafting.py b/strata_control/drafting.py index a48400aae6..710ba0a22a 100644 --- a/strata_control/drafting.py +++ b/strata_control/drafting.py @@ -5,7 +5,9 @@ The choice is the person's, and it is saved in the model's run config as ``"draf (like ``"mtp": false``, strata_control/draft_layer.py), so a setup run that rewrites the engine arguments cannot undo it. mtp the engine's default drafter, the model's own draft layer (no extra flags) - dflash2 ``--draft dflash2 --draft-model <pack>``: the DFlash2 block drafter (incoai/Qwen3.8-Flash-Next-DFlash2) for Qwen3.8-Flash-Next + dflash2 ``--draft dflash2 --draft-model <pack> --spec 6 --draft-conf 0.35``: the DFlash2 block drafter (incoai/Qwen3.8-Flash-Next-DFlash2) for + Qwen3.8-Flash-Next, with the window and confidence that measured best (RESULTS-DRAFT.md section 4); a ``--spec`` or ``--draft-conf`` the + person set by hand (``user_args``) stays off no draft layer (the same as ``"mtp": false``: the engine still looks ahead in the text with ``--spec``) auto the table below says which of mtp / dflash2 this card class gets @@ -79,6 +81,71 @@ def suggest(klass: str) -> str: return "dflash2" if row.drafter == "dflash2" and row.faster_everywhere else "mtp" +# --------------------------------------------------------------------------------------------------- where the engine can run it +# +# The DFlash2 code (src/core/dflash2.cpp, src/kernels/cuda/dflash2.cu) is compiled into the CUDA and HIP engines only (CMakeLists.txt, STRATA_HAVE_DFLASH2); +# the Metal and SYCL engines have none, and a PC with no supported graphics card has no engine to run it. Where the code exists, three words say what was +# measured (DFlash2 against MTP, same prompts, same flags; the numbers are in the comment above SUGGESTED and in phaseA-tests/blackwell/RESULTS-DRAFT.md): +# tested measured on this kind of card: faster on some kinds of text, slower on others +# slower measured on this kind of card: slower on every prompt +# untested the engine has the code for this card but it was never measured on it + +#: What the Terminal's Drafting step and the app's paragraph under the dropdown say (the same words; apps/host/src/locales/df2-en.json, tests keep them equal). +#: The numbers are measured: l620, RTX PRO 5000, Qwen3.8-Flash-Next IQ3_S, DFlash2 `--spec 6 --draft-conf 0.35` against MTP (phaseA-tests/blackwell/RESULTS-DRAFT.md section 4). +EXPLAIN_NUMBERS = ("MTP is the default. DFlash2 is another way to guess the next words ahead, for Qwen3.8-Flash-Next only. On an RTX PRO 5000 it was 7.8% faster than MTP " + "on 19 short prompts and 1.1% faster on long thinking, and faster on 21 of 23 prompts. On the short prompts the answers were identical.") +EXPLAIN_LIMITS = "It downloads about 1.2 GB once, works with one graphics card and one request at a time, and uses MTP otherwise." + +LINE_TESTED = "On graphics cards like yours, DFlash2 was faster than MTP on some kinds of text and slower on others in our tests." +LINE_SLOWER = "On graphics cards like yours, DFlash2 was slower than MTP in our tests." +LINE_UNTESTED = "DFlash2 has not been tested on your graphics card yet." + + +@dataclass(frozen=True) +class Support: + can_run: bool # this engine build has the DFlash2 code for the card + level: str # none | tested | slower | untested + line: str # plain words for the person ("" when there is nothing to say) + + +_TESTED = {("cuda", "sm_120"), ("cuda", "sm_121"), ("hip", "gfx1151")} +_SLOWER = {("cuda", "sm_86"), ("hip", "gfx1201")} + + +_HARDWARE: list = [] + + +def detect_hardware() -> tuple[str | None, list[str]]: + """(engine family, card architectures) of this computer, looked up once: ``("cuda", ["sm_120"])``, ``("hip", ["gfx1151"])``, ``("metal", [])``; + ``(None, [])`` when nothing answers. Read-only probes of tools that are already installed; never raises, never downloads.""" + if not _HARDWARE: + backend: str | None = None + archs: list[str] = [] + try: + from strata_control import engine_component + backend = engine_component.detect_backend()[0] + archs = list(engine_component.cuda_archs_present()) + list(engine_component.hip_archs_present()) + except Exception: # noqa: BLE001 - an unknown computer is "no DFlash2", never an error + pass + _HARDWARE.append((backend, archs)) + return _HARDWARE[0] + + +def hardware_support(backend: str | None, archs: Any = None) -> Support: + """Can the engine for this backend and card run DFlash2, and what was measured on it. ``backend`` is the engine family (cuda | hip | sycl | metal); + ``archs`` the cards' architectures (``sm_120``, ``gfx1151``...), the first one counts like card_class does.""" + make = str(backend or "").strip().lower() + if make not in ("cuda", "hip"): + return Support(False, "none", "") + first = ([archs] if isinstance(archs, str) else list(archs or [])) + arch = str(first[0]).strip().lower() if first else "" + if (make, arch) in _TESTED: + return Support(True, "tested", LINE_TESTED) + if (make, arch) in _SLOWER: + return Support(True, "slower", LINE_SLOWER) + return Support(True, "untested", LINE_UNTESTED) + + # --------------------------------------------------------------------------------------------------- the drafter file # # incoai/Qwen3.8-Flash-Next-DFlash2 (Apache-2.0), pinned to one revision. The safetensors file is 1.2 GB; tools/dflash2_pack.py turns it into the @@ -98,6 +165,8 @@ PACK_GB = 0.76 # what stays on disk (the source file is removed af PACK_NAME = "qwen3.8-flash-next-dflash2.q8.pack" VRAM_GB = 1.2 # what the drafter needs in graphics memory (the engine's own estimate) FOLDER = "dflash2" # under the model data folder, next to ``mtp`` +SPEC_WINDOW = 6 # --spec with DFlash2: the widest window of drafted words per round (measured best on Blackwell; the engine caps it per card) +DRAFT_CONF = 0.35 # --draft-conf with DFlash2: the window ends where the chance that every draft so far holds falls below this #: model families (strata launch --family) the drafter was trained for and measured on: Qwen3.8-Flash-Next and its Gyro build. SUPPORTED_FAMILIES = ("qwen", "gyro") @@ -149,16 +218,24 @@ DIDNT_FIT = "DFlash2 didn't fit" NOT_HERE = "DFlash2 isn't available in this mode" NOT_SUPPORTED = "DFlash2 is for Qwen3.8-Flash-Next only" NOT_DOWNLOADED = "the DFlash2 drafter isn't downloaded yet" +NOT_THIS_CARD = "DFlash2 isn't available on this graphics card" NOT_SERVED = NOT_HERE -REASONS = (DIDNT_FIT, NOT_HERE, NOT_SUPPORTED, NOT_DOWNLOADED) +REASONS = (DIDNT_FIT, NOT_HERE, NOT_SUPPORTED, NOT_DOWNLOADED, NOT_THIS_CARD) def mtp_line(reason: str) -> str: return f"Drafting: MTP ({reason})" -def decide(mode: Any, *, klass: str, model_name: str | None = None, family: str | None = None, data_dir: str | Path | None = None) -> Decision: - """The drafter a start uses. Never raises: a choice that cannot be applied becomes MTP with a note.""" +def engine_flags(pack: str | Path) -> tuple[str, ...]: + """The engine arguments of a DFlash2 start: the drafter, its file, the window and the confidence.""" + return ("--draft", "dflash2", "--draft-model", str(pack), "--spec", str(SPEC_WINDOW), "--draft-conf", f"{DRAFT_CONF:g}") + + +def decide(mode: Any, *, klass: str, model_name: str | None = None, family: str | None = None, data_dir: str | Path | None = None, + backend: str | None = None, archs: Any = None) -> Decision: + """The drafter a start uses. Never raises: a choice that cannot be applied becomes MTP with a note. ``backend`` (cuda | hip | sycl | metal) + is optional: given, a build without the DFlash2 code (Metal, SYCL) keeps the MTP.""" asked = normalize(mode) if asked == "off": return Decision(asked, "off") @@ -169,23 +246,28 @@ def decide(mode: Any, *, klass: str, model_name: str | None = None, family: str return Decision(asked, "mtp", NOT_SUPPORTED if asked == "dflash2" else "") if not ENGINE_SERVES_DFLASH2: return Decision(asked, "mtp", NOT_SERVED if asked == "dflash2" else "") + if backend is not None and not hardware_support(backend, archs).can_run: + return Decision(asked, "mtp", NOT_THIS_CARD if asked == "dflash2" else "") if not pack_ready(data_dir): return Decision(asked, "mtp", NOT_DOWNLOADED) - return Decision(asked, "dflash2", flags=("--draft", "dflash2", "--draft-model", str(pack_path(data_dir)))) + return Decision(asked, "dflash2", flags=engine_flags(pack_path(data_dir))) -def needs_pack(mode: Any, *, klass: str, model_name: str | None = None, family: str | None = None, data_dir: str | Path | None = None) -> bool: +def needs_pack(mode: Any, *, klass: str, model_name: str | None = None, family: str | None = None, data_dir: str | Path | None = None, + backend: str | None = None, archs: Any = None) -> bool: """Would this choice use the DFlash2 drafter if its file were here, and is it not here yet? (Then it is fetched before the start.)""" asked = normalize(mode) want = suggest(klass) if asked == "auto" else asked + if backend is not None and not hardware_support(backend, archs).can_run: + return False return want == "dflash2" and ENGINE_SERVES_DFLASH2 and supported_model(model_name, family) and not pack_ready(data_dir) -DRAFT_FLAGS = {"--draft": True, "--draft-model": True} +DRAFT_FLAGS = {"--draft": True, "--draft-model": True, "--draft-conf": True} def strip_draft_flags(args: list[Any]) -> list[str]: - """The arguments without ``--draft`` / ``--draft-model`` (and their values).""" + """The arguments without ``--draft`` / ``--draft-model`` / ``--draft-conf`` (and their values).""" out: list[str] = [] items = [str(a) for a in args] i = 0 @@ -210,12 +292,33 @@ def data_dir_of(args: list[Any]) -> Path | None: return None -def apply(cfg: dict[str, Any], *, klass: str, data_dir: str | Path | None = None, family: str | None = None) -> Decision: - """Put the config's ``"drafting"`` choice on its engine arguments (in place). ``off`` is the draft layer's own switch (``"mtp": false``).""" +def _flag_value(args: list[Any], flag: str) -> str | None: + items = [str(a) for a in args or []] + return items[items.index(flag) + 1] if flag in items and items.index(flag) + 1 < len(items) else None + + +def _without_flag(args: list[str], flag: str) -> list[str]: + out: list[str] = [] + i = 0 + while i < len(args): + if args[i] == flag: + i += 2 if i + 1 < len(args) and not args[i + 1].startswith("--") else 1 + continue + out.append(args[i]) + i += 1 + return out + + +def apply(cfg: dict[str, Any], *, klass: str, data_dir: str | Path | None = None, family: str | None = None, + backend: str | None = None, archs: Any = None) -> Decision: + """Put the config's ``"drafting"`` choice on its engine arguments (in place). ``off`` is the draft layer's own switch (``"mtp": false``). + DFlash2 sets the window (``--spec 6``) and the confidence (``--draft-conf 0.35``) unless the person set either one by hand in ``user_args``.""" from strata_control import draft_layer - decision = decide(cfg.get("drafting"), klass=klass, model_name=cfg.get("model_name"), family=family, data_dir=data_dir) + decision = decide(cfg.get("drafting"), klass=klass, model_name=cfg.get("model_name"), family=family, data_dir=data_dir, backend=backend, archs=archs) if cfg.get("drafting") is None and decision.drafter == "mtp": return decision # nobody chose and Auto is the MTP: the arguments stay exactly as they are + mine = cfg.get("user_args") or [] + kept_conf = _flag_value(mine, "--draft-conf") args = strip_draft_flags(cfg.get("args") or []) if decision.drafter == "off": cfg["mtp"] = False @@ -224,7 +327,16 @@ def apply(cfg: dict[str, Any], *, klass: str, data_dir: str | Path | None = None else: if cfg.get("drafting") is not None and normalize(cfg.get("drafting")) != "off" and cfg.get("mtp") is False: cfg["mtp"] = True # an explicit drafter choice overrides an older "mtp": false - cfg["args"] = args + list(decision.flags) + flags = list(decision.flags) + if decision.drafter == "dflash2": + if kept_conf is not None: + flags[flags.index("--draft-conf") + 1] = kept_conf + if _flag_value(mine, "--spec") is None: + args = _without_flag(args, "--spec") # the person's own --spec stays; otherwise the window is the DFlash2 one + else: + i = flags.index("--spec") + del flags[i:i + 2] + cfg["args"] = args + flags return decision diff --git a/strata_control/drafting_fetch.py b/strata_control/drafting_fetch.py index eee25f392b..bc700daafc 100644 --- a/strata_control/drafting_fetch.py +++ b/strata_control/drafting_fetch.py @@ -14,6 +14,8 @@ import importlib.util import os import sys import threading +import urllib.error +import urllib.request from pathlib import Path from typing import Callable @@ -51,6 +53,50 @@ def _packer(): return module +REACH_SECONDS = 6.0 + + +def online(url: str, timeout: float = REACH_SECONDS) -> bool: + """Does the download address answer at all? One short HEAD request, no retry: with no internet (or a connection that hangs) the person gets a plain + sentence in a few seconds instead of a stalled progress bar. Any answer from the server counts, even an error page.""" + try: + request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-drafting/1"}) + with urllib.request.urlopen(request, timeout=timeout): + return True + except urllib.error.HTTPError: + return True + except (urllib.error.URLError, OSError, TimeoutError, ValueError) as exc: + from strata_control import tls + return bool(tls.is_certificate_error(exc)) # a certificate problem is an answer: the download explains it in its own words + + +def _hub_snapshots() -> list[Path]: + """Where the Hugging Face tools keep this repository's pinned revision, if the person already has it from them (nothing is created or changed).""" + roots: list[Path] = [] + for name in ("HF_HUB_CACHE", "HUGGINGFACE_HUB_CACHE"): + if os.environ.get(name): + roots.append(Path(os.environ[name])) + if os.environ.get("HF_HOME"): + roots.append(Path(os.environ["HF_HOME"]) / "hub") + roots.append(Path.home() / ".cache" / "huggingface" / "hub") + return [r / ("models--" + drafting.REPO.replace("/", "--")) / "snapshots" / drafting.REVISION for r in roots] + + +def _present(folders: list[Path], spec) -> dict[str, Path]: + """The pinned files that are already on this computer, found in these folders and checked against the repository's size and SHA-256.""" + found: dict[str, Path] = {} + for name, size, sha in spec: + for folder in folders: + candidate = folder / name + try: + if candidate.is_file() and candidate.stat().st_size == size and transfer.sha256_file(candidate) == sha: + found[name] = candidate + break + except OSError: + continue + return found + + def ensure(data_dir: str | Path, *, progress: Progress | None = None, cancel: threading.Event | None = None, base_url: str | None = None, files=None) -> Path: """Make the packed drafter exist under ``data_dir`` and return its path. A pack that is there is kept. Resumable: an interrupted @@ -63,13 +109,15 @@ def ensure(data_dir: str | Path, *, progress: Progress | None = None, cancel: th acquisition.require("the DFlash2 drafter", "strata drafting fetch") folder = out.parent src = folder / "src" - src.mkdir(parents=True, exist_ok=True) spec = tuple(files if files is not None else drafting.FILES) + have = _present([src, *(_hub_snapshots() if files is None else [])], spec) # already here and checked: used where it is, never fetched again + if len(have) < len(spec) and not online(base_url or drafting.BASE_URL): + raise DraftingError("There is no internet connection, so the DFlash2 drafter can't be downloaded now.") + src.mkdir(parents=True, exist_ok=True) total = sum(size for _n, size, _h in spec) done_before = 0 for name, size, sha in spec: - target = src / name - if not (target.is_file() and target.stat().st_size == size and transfer.sha256_file(target) == sha): + if name not in have: base = done_before partial = src / (name + ".part") try: @@ -80,20 +128,22 @@ def ensure(data_dir: str | Path, *, progress: Progress | None = None, cancel: th "happening, use MTP for now.") from None except transfer.TransferError as exc: raise DraftingError(f"The DFlash2 download did not finish: {exc}. Try again; it continues where it stopped.") from None - os.replace(partial, target) + os.replace(partial, src / name) + have[name] = src / name done_before += size report("Packing the DFlash2 drafter for the engine…", total, total) tmp = out.with_suffix(".tmp") try: - _packer().pack(str(src / "model.safetensors"), str(src / "config.json"), str(tmp), say=lambda *_: None) + _packer().pack(str(have["model.safetensors"]), str(have["config.json"]), str(tmp), say=lambda *_: None) os.replace(tmp, out) except DraftingError: raise except Exception as exc: # noqa: BLE001 - a plain sentence for any packing failure; the cause stays in the chain tmp.unlink(missing_ok=True) raise DraftingError("The DFlash2 drafter could not be prepared on this computer. The model keeps using the MTP.") from exc - for name, _size, _sha in spec: # the source files are 1.2 GB of nothing the engine reads - (src / name).unlink(missing_ok=True) + for name, _size, _sha in spec: # the source files are 1.2 GB of nothing the engine reads (a copy kept by the Hugging Face tools is theirs: left alone) + if have[name].parent == src: + have[name].unlink(missing_ok=True) try: src.rmdir() except OSError: diff --git a/tests/terminal/test_drafting.py b/tests/terminal/test_drafting.py index 80e2cd5214..d5905eefe7 100644 --- a/tests/terminal/test_drafting.py +++ b/tests/terminal/test_drafting.py @@ -100,7 +100,8 @@ class Decisions(unittest.TestCase): self.ready() d = drafting.decide("dflash2", klass="blackwell", model_name=GYRO, data_dir=self.data) self.assertEqual(d.drafter, "dflash2") - self.assertEqual(d.flags, ("--draft", "dflash2", "--draft-model", str(drafting.pack_path(self.data)))) + self.assertEqual(d.flags, ("--draft", "dflash2", "--draft-model", str(drafting.pack_path(self.data)), "--spec", "6", "--draft-conf", "0.35"), + "the window and confidence that measured best (RESULTS-DRAFT.md section 4)") self.assertFalse(drafting.needs_pack("dflash2", klass="blackwell", model_name=GYRO, data_dir=self.data)) def test_dflash2_is_for_qwen38_flash_next_only(self): @@ -162,8 +163,11 @@ class EngineArguments(unittest.TestCase): c = self.cfg(drafting="dflash2", args=[*self.ARGS, "--draft", "mtp", "--draft-model", "/old.pack"]) d = drafting.apply(c, klass="blackwell", data_dir=self.data) self.assertEqual(d.drafter, "dflash2") - self.assertEqual(c["args"], [*self.ARGS, "--draft", "dflash2", "--draft-model", str(pack)]) + spec_at = self.ARGS.index("--spec") + self.assertEqual(c["args"], [*self.ARGS[:spec_at], *self.ARGS[spec_at + 2:], "--draft", "dflash2", "--draft-model", str(pack), "--spec", "6", "--draft-conf", "0.35"], + "the MTP window of 4 gives way to DFlash2's 6; the MTP's own arguments stay") self.assertEqual(c["args"].count("--draft"), 1) + self.assertEqual(c["args"].count("--spec"), 1) self.assertIn("--mtp", c["args"], "the MTP stays as the fallback the engine names") def test_mtp_removes_a_drafter_that_was_written_by_hand(self): @@ -193,7 +197,7 @@ class EngineArguments(unittest.TestCase): with mock.patch("serve.server.drafting_card_class", return_value="blackwell"), serving_dflash2(), \ mock.patch.object(drafting, "pack_ready", return_value=True), mock.patch.object(drafting, "data_dir_of", return_value=Path("/d")): args = engine_args(self.cfg(drafting="dflash2")) - self.assertEqual(args[-4:], ["--draft", "dflash2", "--draft-model", str(pack)]) + self.assertEqual(args[-8:], ["--draft", "dflash2", "--draft-model", str(pack), "--spec", "6", "--draft-conf", "0.35"]) with mock.patch("serve.server.drafting_card_class", return_value="blackwell"), mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False): self.assertEqual(engine_args(self.cfg()), self.ARGS, "no choice: nothing changes") off = engine_args(self.cfg(drafting="off")) @@ -244,9 +248,10 @@ class WhatTheEngineSaid(unittest.TestCase): class WordsMatchTheApp(unittest.TestCase): def test_every_line_the_engine_start_can_say_is_in_the_apps_catalog_in_all_eight_languages(self): folder = ROOT / "apps" / "host" / "src" / "locales" - catalogs = {l: json.loads((folder / f"{l}.json").read_text(encoding="utf-8")) for l in ("en", "de", "es", "fr", "ja", "ko", "pt", "ru", "zh")} + catalogs = {l: {**json.loads((folder / f"{l}.json").read_text(encoding="utf-8")), **json.loads((folder / f"df2-{l}.json").read_text(encoding="utf-8"))} + for l in ("en", "de", "es", "fr", "ja", "ko", "pt", "ru", "zh")} ids = {v: k for k, v in catalogs["en"].items()} - self.assertEqual(len(drafting.REASONS), 4) + self.assertEqual(len(drafting.REASONS), 5) for reason in drafting.REASONS: line = drafting.mtp_line(reason) self.assertIn(line, ids, line) diff --git a/tests/terminal/test_drafting_hardware.py b/tests/terminal/test_drafting_hardware.py new file mode 100644 index 0000000000..e25b8eb7d3 --- /dev/null +++ b/tests/terminal/test_drafting_hardware.py @@ -0,0 +1,156 @@ +"""The DFlash2 option: where the engine can run it, the window it is started with, and the download when there is no internet or the files are already here. +(tests/terminal/test_drafting.py has the table, the Terminal flag and the pinned download.)""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import socket +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest import mock + +from strata_control import drafting, drafting_fetch +from tests.terminal.launch_support import run_cli + +ROOT = Path(__file__).resolve().parents[2] +GYRO = "qwen3.8-flash-next-gyro-gyro-s" + + +def serving_dflash2(): + return mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", True) + + +class WhereTheEngineCanRunIt(unittest.TestCase): + """DFlash2 exists in the CUDA and HIP engines only (CMakeLists.txt STRATA_HAVE_DFLASH2): the choice is offered, and applied, only there.""" + + def test_the_matrix(self): + h = drafting.hardware_support + for backend in ("metal", "sycl", "", None, "cpu"): + self.assertEqual(h(backend, ["sm_120"]), drafting.Support(False, "none", ""), backend) + self.assertEqual((h("cuda", ["sm_120"]).level, h("cuda", ["sm_121"]).level, h("hip", ["gfx1151"]).level), ("tested",) * 3) + self.assertEqual((h("cuda", ["sm_86"]).level, h("hip", ["gfx1201"]).level), ("slower",) * 2) + for backend, arch in (("cuda", "sm_75"), ("cuda", "sm_89"), ("cuda", "sm_90"), ("cuda", "sm_61"), ("hip", "gfx1100"), ("hip", "gfx1030"), ("cuda", None)): + support = h(backend, [arch] if arch else []) + self.assertEqual((support.can_run, support.level, support.line), (True, "untested", drafting.LINE_UNTESTED), (backend, arch)) + for backend, arch in (("cuda", "sm_120"), ("cuda", "sm_86"), ("cuda", "sm_75")): + self.assertTrue(h(backend, [arch]).line, "every card that is offered it gets one plain line") + + def test_no_verdicts_in_the_lines(self): + for line in (drafting.LINE_TESTED, drafting.LINE_SLOWER, drafting.LINE_UNTESTED): + for word in ("recommend", "best", "better", "should", "avoid"): + self.assertNotIn(word, line.lower()) + + def test_a_build_without_the_code_keeps_the_mtp_and_downloads_nothing(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + with serving_dflash2(): + for backend in ("metal", "sycl"): + d = drafting.decide("dflash2", klass="other", model_name=GYRO, data_dir=tmp.name, backend=backend, archs=[]) + self.assertEqual((d.drafter, d.note), ("mtp", drafting.NOT_THIS_CARD), backend) + self.assertFalse(drafting.needs_pack("dflash2", klass="other", model_name=GYRO, data_dir=tmp.name, backend=backend, archs=[]), backend) + self.assertTrue(drafting.needs_pack("dflash2", klass="blackwell", model_name=GYRO, data_dir=tmp.name, backend="cuda", archs=["sm_120"])) + self.assertEqual(drafting.decide("auto", klass="other", model_name=GYRO, data_dir=tmp.name, backend="metal", archs=[]).note, "", "Auto never nags") + + def test_a_window_or_confidence_the_person_set_by_hand_stays(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + pack = drafting.pack_path(tmp.name) + pack.parent.mkdir(parents=True) + pack.write_bytes(b"x" * (2 << 20)) + base = ["--pack", "/d/packs/g", "--mtp", "/d/mtp/rt", "--spec", "5", "--draft-conf", "0.5"] + with serving_dflash2(): + c = {"model_name": GYRO, "drafting": "dflash2", "args": list(base), "user_args": ["--spec", "5", "--draft-conf", "0.5"]} + drafting.apply(c, klass="blackwell", data_dir=tmp.name) + self.assertEqual(c["args"][c["args"].index("--spec") + 1], "5") + self.assertEqual(c["args"][c["args"].index("--draft-conf") + 1], "0.5") + self.assertEqual((c["args"].count("--spec"), c["args"].count("--draft-conf")), (1, 1)) + c = {"model_name": GYRO, "drafting": "mtp", "args": [*base, "--draft", "dflash2", "--draft-model", "/p"]} + drafting.apply(c, klass="blackwell", data_dir=tmp.name) + self.assertNotIn("--draft-conf", c["args"], "back to MTP: DFlash2's confidence goes with it") + self.assertEqual(c["args"][c["args"].index("--spec") + 1], "5", "and the MTP window is untouched") + + def test_the_plan_reports_whether_this_computer_can_run_it(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + for hardware, serves, level in ((("cuda", ["sm_120"]), True, "tested"), (("metal", []), False, "none"), (("hip", ["gfx1201"]), True, "slower")): + with mock.patch.object(drafting, "detect_hardware", return_value=hardware): + code, out, err = run_cli(["drafting", "plan", "--data-dir", tmp.name, "--mode", "auto", "--output", "json"]) + self.assertEqual(code, 0, err) + payload = json.loads(out) + self.assertEqual((payload["serves"], payload["support"]), (serves, level), hardware) + + +class OfflineAndReuse(unittest.TestCase): + """No internet is a plain sentence in seconds, never a hang; files that are already here are used, not fetched.""" + + @classmethod + def setUpClass(cls): + sys.path.insert(0, str(ROOT / "tools")) + spec = importlib.util.spec_from_file_location("t_pack2", ROOT / "tools" / "test_dflash2_pack.py") + cls.synth = importlib.util.module_from_spec(spec) + spec.loader.exec_module(cls.synth) + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = Path(self.tmp.name) + self.synth.write_safetensors(self.dir / "m.safetensors", self.synth.tensors()) + (self.dir / "c.json").write_text(json.dumps(self.synth.CFG)) + self.blobs = {"config.json": (self.dir / "c.json").read_bytes(), "model.safetensors": (self.dir / "m.safetensors").read_bytes()} + self.files = tuple((n, len(b), hashlib.sha256(b).hexdigest()) for n, b in self.blobs.items()) + self.data = self.dir / "data" + patcher = mock.patch.object(drafting, "pack_ready", lambda d: bool(d) and drafting.pack_path(d).is_file()) + patcher.start() + self.addCleanup(patcher.stop) + + def test_no_internet_is_a_plain_sentence_and_nothing_is_left_behind(self): + with mock.patch.object(drafting_fetch, "online", return_value=False), mock.patch.object(drafting_fetch.transfer, "download") as download: + with self.assertRaises(drafting_fetch.DraftingError) as ctx: + drafting_fetch.ensure(self.data, files=self.files) + self.assertEqual(str(ctx.exception), "There is no internet connection, so the DFlash2 drafter can't be downloaded now.") + download.assert_not_called() + self.assertFalse(drafting.pack_path(self.data).exists()) + + def test_the_reachability_check_gives_up_fast_on_a_connection_that_hangs(self): + hung = socket.socket() + hung.bind(("127.0.0.1", 0)) + hung.listen(0) # the kernel accepts the connection; nobody ever answers + self.addCleanup(hung.close) + started = time.monotonic() + self.assertFalse(drafting_fetch.online(f"http://127.0.0.1:{hung.getsockname()[1]}/x", timeout=1.0)) + self.assertLess(time.monotonic() - started, 5) + self.assertFalse(drafting_fetch.online("http://127.0.0.1:9/x", timeout=1.0), "nothing listens: refused at once") + + def test_verified_source_files_that_are_already_here_are_used_without_the_network(self): + src = drafting.pack_path(self.data).parent / "src" + src.mkdir(parents=True) + for name, blob in self.blobs.items(): + (src / name).write_bytes(blob) + with mock.patch.object(drafting_fetch, "online", side_effect=AssertionError("no network needed")), \ + mock.patch.object(drafting_fetch.transfer, "download", side_effect=AssertionError("nothing to download")): + out = drafting_fetch.ensure(self.data, files=self.files) + self.assertEqual(out.read_bytes()[:4], b"DF2P") + self.assertFalse(src.exists()) + + def test_a_copy_kept_by_the_hugging_face_tools_is_found_checked_and_never_deleted(self): + hub = self.dir / "hub" + hub.mkdir() + for name, blob in self.blobs.items(): + (hub / name).write_bytes(blob) + self.assertEqual(set(drafting_fetch._present([hub], self.files)), {"config.json", "model.safetensors"}) + (hub / "model.safetensors").write_bytes(b"corrupt") + self.assertNotIn("model.safetensors", drafting_fetch._present([hub], self.files), "a copy whose hash differs is never used") + + def test_the_hub_folders_are_the_pinned_revision_only(self): + with mock.patch.dict("os.environ", {"HF_HOME": str(self.dir / "hf")}): + folders = drafting_fetch._hub_snapshots() + self.assertIn(self.dir / "hf" / "hub" / "models--incoai--Qwen3.8-Flash-Next-DFlash2" / "snapshots" / drafting.REVISION, folders) + + +if __name__ == "__main__": + unittest.main() From 1ebae961679b4c95a51c6fb223b9d2a16b3fb961 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:43:37 +0100 Subject: [PATCH 17/59] DFlash2 chosen on purpose starts with one request at a time (request slots keep the MTP), Terminal Drafting step, plan line --- apps/host/scripts/make-df2-locales.py | 12 ++++- apps/host/server/native-parallel.mjs | 4 ++ apps/host/src/locales/df2-de.json | 3 +- apps/host/src/locales/df2-en.json | 3 +- apps/host/src/locales/df2-es.json | 3 +- apps/host/src/locales/df2-fr.json | 3 +- apps/host/src/locales/df2-ja.json | 3 +- apps/host/src/locales/df2-ko.json | 3 +- apps/host/src/locales/df2-pt.json | 3 +- apps/host/src/locales/df2-ru.json | 3 +- apps/host/src/locales/df2-zh.json | 3 +- apps/host/tests/parallel-default.test.mjs | 14 ++++++ strata_cli/launch/runner.py | 18 +++++++ strata_control/drafting.py | 12 +++++ tests/terminal/test_drafting_hardware.py | 57 +++++++++++++++++++++++ 15 files changed, 134 insertions(+), 10 deletions(-) diff --git a/apps/host/scripts/make-df2-locales.py b/apps/host/scripts/make-df2-locales.py index a38d58788f..c63d60bd93 100644 --- a/apps/host/scripts/make-df2-locales.py +++ b/apps/host/scripts/make-df2-locales.py @@ -4,7 +4,7 @@ This computer panel. Run from apps/host: python scripts/make-df2-locales.py Every entry names all nine languages; the keys are df01.. in the order of S. df2-en.json is the English source. Placeholders ({0}) must be kept in every language. A separate file keeps this work from colliding with the other catalogs (the same reason pick-, tune-, tools-, fix-, gh-, ui- and engine- exist). -The English lines of df03-df07 are also written in strata_control/drafting.py and strata_control/drafting_fetch.py; tests/drafting.test.mjs keeps the two the same.""" +The English lines of df03-df07 and df09 are also written in strata_control/drafting.py and strata_control/drafting_fetch.py; tests/drafting.test.mjs keeps the two the same.""" import json import re from pathlib import Path @@ -92,6 +92,16 @@ add("There is no internet connection, so the DFlash2 drafter can't be downloaded add("SSD: not needed", "SSD:不需要", "SSD:不要", "SSD: nicht nötig", "SSD: no hace falta", "SSD: не нужен", "SSD: não é necessário", "SSD: 필요 없음", "SSD : pas nécessaire") +add("DFlash2 answers one request at a time, so Strata set this model to one request at a time.", + "DFlash2 一次只处理一个请求,因此 Strata 将此模型设置为一次一个请求。", + "DFlash2 は一度に 1 件のリクエストしか処理しないため、Strata はこのモデルを一度に 1 件に設定しました。", + "DFlash2 beantwortet eine Anfrage nach der anderen, deshalb hat Strata dieses Modell auf eine Anfrage zur Zeit gestellt.", + "DFlash2 responde una solicitud a la vez, así que Strata configuró este modelo para una solicitud a la vez.", + "DFlash2 отвечает на один запрос за раз, поэтому Strata настроила эту модель на один запрос за раз.", + "O DFlash2 responde a um pedido de cada vez, por isso o Strata configurou este modelo para um pedido de cada vez.", + "DFlash2는 한 번에 하나의 요청만 처리하므로 Strata가 이 모델을 한 번에 하나의 요청으로 설정했습니다.", + "DFlash2 répond à une requête à la fois, Strata a donc réglé ce modèle sur une requête à la fois.") + here = Path(__file__).resolve().parent.parent / "src" / "locales" NBSP = " " diff --git a/apps/host/server/native-parallel.mjs b/apps/host/server/native-parallel.mjs index dfee0f6ec8..83a4fc4c98 100644 --- a/apps/host/server/native-parallel.mjs +++ b/apps/host/server/native-parallel.mjs @@ -19,6 +19,8 @@ */ export const DEFAULT_SLOTS = 4; +/** What the person is told when DFlash2 is chosen and nobody picked a number of requests (strata_control/drafting.py ONE_REQUEST_NOTE). */ +export const DFLASH2_NOTE = 'DFlash2 answers one request at a time, so Strata set this model to one request at a time.'; /** The most the engine's batch window holds without grouped MTP. */ export const MAX_SLOTS = 8; /** @@ -108,6 +110,8 @@ export function chooseParallel({ config = {}, values = {}, hardware = null, requ const wantMtp = (values.batchMtp ?? config.batchMtp) === true && !facts.batchMtp && facts.mtp && facts.gpus.length === 1 && (slots ?? 0) > 1; return { slots: slots ?? 0, batchMtp: wantMtp, explicit: true, requested, note: null, slotGb: slot }; } + // DFlash2 chosen on purpose: it answers one request at a time, and request slots would keep the MTP (the engine says "not --batch"). Nobody chose a number here, so one. + if ((values.drafting ?? config.drafting) === 'dflash2') return { slots: 1, batchMtp: false, explicit: false, requested, note: DFLASH2_NOTE, slotGb: slot }; const cards = (hardware?.gpus ?? []).filter(g => facts.gpus.includes(g.index)).map(g => Number(g.vram_gb)).filter(n => Number.isFinite(n) && n > 0); // Without a hardware read nothing can be sized: one at a time is the safe default (a number can still be chosen). if (!cards.length) return { slots: PARALLEL_POLICY === 'fixed' ? requested : 1, batchMtp: false, explicit: false, requested, note: null, slotGb: slot }; diff --git a/apps/host/src/locales/df2-de.json b/apps/host/src/locales/df2-de.json index 0f39c67ee5..22a5b59591 100644 --- a/apps/host/src/locales/df2-de.json +++ b/apps/host/src/locales/df2-de.json @@ -6,5 +6,6 @@ "df05": "DFlash2 wurde auf Ihrer Grafikkarte noch nicht getestet.", "df06": "Vorausraten: MTP (DFlash2 ist auf dieser Grafikkarte nicht verfügbar)", "df07": "Es besteht keine Internetverbindung, deshalb kann der DFlash2-Drafter jetzt nicht heruntergeladen werden.", - "df08": "SSD: nicht nötig" + "df08": "SSD: nicht nötig", + "df09": "DFlash2 beantwortet eine Anfrage nach der anderen, deshalb hat Strata dieses Modell auf eine Anfrage zur Zeit gestellt." } diff --git a/apps/host/src/locales/df2-en.json b/apps/host/src/locales/df2-en.json index 49683541f8..de586374d7 100644 --- a/apps/host/src/locales/df2-en.json +++ b/apps/host/src/locales/df2-en.json @@ -6,5 +6,6 @@ "df05": "DFlash2 has not been tested on your graphics card yet.", "df06": "Drafting: MTP (DFlash2 isn't available on this graphics card)", "df07": "There is no internet connection, so the DFlash2 drafter can't be downloaded now.", - "df08": "SSD: not needed" + "df08": "SSD: not needed", + "df09": "DFlash2 answers one request at a time, so Strata set this model to one request at a time." } diff --git a/apps/host/src/locales/df2-es.json b/apps/host/src/locales/df2-es.json index 44970dbfa5..0acae093e6 100644 --- a/apps/host/src/locales/df2-es.json +++ b/apps/host/src/locales/df2-es.json @@ -6,5 +6,6 @@ "df05": "DFlash2 todavía no se ha probado en su tarjeta gráfica.", "df06": "Predicción: MTP (DFlash2 no está disponible en esta tarjeta gráfica)", "df07": "No hay conexión a internet, así que ahora no se puede descargar el borrador de DFlash2.", - "df08": "SSD: no hace falta" + "df08": "SSD: no hace falta", + "df09": "DFlash2 responde una solicitud a la vez, así que Strata configuró este modelo para una solicitud a la vez." } diff --git a/apps/host/src/locales/df2-fr.json b/apps/host/src/locales/df2-fr.json index da81041adb..1114f21e1f 100644 --- a/apps/host/src/locales/df2-fr.json +++ b/apps/host/src/locales/df2-fr.json @@ -6,5 +6,6 @@ "df05": "DFlash2 n’a pas encore été testé sur votre carte graphique.", "df06": "Anticipation : MTP (DFlash2 n’est pas disponible sur cette carte graphique)", "df07": "Il n’y a pas de connexion internet, le drafter DFlash2 ne peut donc pas être téléchargé pour le moment.", - "df08": "SSD : pas nécessaire" + "df08": "SSD : pas nécessaire", + "df09": "DFlash2 répond à une requête à la fois, Strata a donc réglé ce modèle sur une requête à la fois." } diff --git a/apps/host/src/locales/df2-ja.json b/apps/host/src/locales/df2-ja.json index 468f829cc2..920887d8d0 100644 --- a/apps/host/src/locales/df2-ja.json +++ b/apps/host/src/locales/df2-ja.json @@ -6,5 +6,6 @@ "df05": "DFlash2 はまだお使いのグラフィックスカードでテストされていません。", "df06": "先読み:MTP(DFlash2 はこのグラフィックスカードでは使えません)", "df07": "インターネットに接続されていないため、今は DFlash2 のドラフターをダウンロードできません。", - "df08": "SSD:不要" + "df08": "SSD:不要", + "df09": "DFlash2 は一度に 1 件のリクエストしか処理しないため、Strata はこのモデルを一度に 1 件に設定しました。" } diff --git a/apps/host/src/locales/df2-ko.json b/apps/host/src/locales/df2-ko.json index 7cb254f647..d9cc1062e8 100644 --- a/apps/host/src/locales/df2-ko.json +++ b/apps/host/src/locales/df2-ko.json @@ -6,5 +6,6 @@ "df05": "DFlash2는 아직 고객님의 그래픽 카드에서 테스트되지 않았습니다.", "df06": "미리 추측: MTP (이 그래픽 카드에서는 DFlash2를 사용할 수 없습니다)", "df07": "인터넷에 연결되어 있지 않아 지금은 DFlash2 드래프터를 내려받을 수 없습니다.", - "df08": "SSD: 필요 없음" + "df08": "SSD: 필요 없음", + "df09": "DFlash2는 한 번에 하나의 요청만 처리하므로 Strata가 이 모델을 한 번에 하나의 요청으로 설정했습니다." } diff --git a/apps/host/src/locales/df2-pt.json b/apps/host/src/locales/df2-pt.json index cdd76aefe6..4e8edafe3e 100644 --- a/apps/host/src/locales/df2-pt.json +++ b/apps/host/src/locales/df2-pt.json @@ -6,5 +6,6 @@ "df05": "O DFlash2 ainda não foi testado na sua placa de vídeo.", "df06": "Previsão: MTP (o DFlash2 não está disponível nesta placa de vídeo)", "df07": "Não há ligação à internet, por isso não é possível transferir agora o rascunhador do DFlash2.", - "df08": "SSD: não é necessário" + "df08": "SSD: não é necessário", + "df09": "O DFlash2 responde a um pedido de cada vez, por isso o Strata configurou este modelo para um pedido de cada vez." } diff --git a/apps/host/src/locales/df2-ru.json b/apps/host/src/locales/df2-ru.json index e294233e19..1ceb5d0827 100644 --- a/apps/host/src/locales/df2-ru.json +++ b/apps/host/src/locales/df2-ru.json @@ -6,5 +6,6 @@ "df05": "DFlash2 ещё не проверялся на вашей видеокарте.", "df06": "Упреждающая генерация: MTP (DFlash2 недоступен на этой видеокарте)", "df07": "Нет подключения к интернету, поэтому сейчас нельзя скачать черновую модель DFlash2.", - "df08": "SSD: не нужен" + "df08": "SSD: не нужен", + "df09": "DFlash2 отвечает на один запрос за раз, поэтому Strata настроила эту модель на один запрос за раз." } diff --git a/apps/host/src/locales/df2-zh.json b/apps/host/src/locales/df2-zh.json index 55628ac759..eed2b7b18f 100644 --- a/apps/host/src/locales/df2-zh.json +++ b/apps/host/src/locales/df2-zh.json @@ -6,5 +6,6 @@ "df05": "DFlash2 尚未在您的显卡上测试过。", "df06": "预测方式:MTP(DFlash2 不适用于这张显卡)", "df07": "没有网络连接,因此现在无法下载 DFlash2 草稿模型。", - "df08": "SSD:不需要" + "df08": "SSD:不需要", + "df09": "DFlash2 一次只处理一个请求,因此 Strata 将此模型设置为一次一个请求。" } diff --git a/apps/host/tests/parallel-default.test.mjs b/apps/host/tests/parallel-default.test.mjs index 1cb9844f32..eee1f9c0b3 100644 --- a/apps/host/tests/parallel-default.test.mjs +++ b/apps/host/tests/parallel-default.test.mjs @@ -178,3 +178,17 @@ test('the draft layer (MTP) is part of what the card is sized for; switched off, assert.equal(slots(26.5, {}, ['--max-context', '32768', '--spec', '4']), 4, 'no draft layer in the arguments'); assert.equal(slots(12, { mtp: false }), 1, 'a 12 GB card still gets one request at a time'); }); + +test('DFlash2 chosen on purpose means one request at a time unless the person picked a number (the engine keeps the MTP with request slots)', () => { + const big = hw(72); + const auto = chooseParallel({ config: cfg(32768), hardware: big }); + assert.ok(auto.slots > 1, 'a card with room gets slots by default'); + const chosen = chooseParallel({ config: cfg(32768), values: { drafting: 'dflash2' }, hardware: big }); + assert.equal(chosen.slots, 1); + assert.equal(chosen.explicit, false); + assert.match(chosen.note, /DFlash2 answers one request at a time/); + assert.equal(chooseParallel({ config: cfg(32768, { drafting: 'dflash2' }), hardware: big }).slots, 1, 'a saved choice counts'); + assert.equal(chooseParallel({ config: cfg(32768), values: { drafting: 'mtp' }, hardware: big }).slots, auto.slots, 'MTP and Auto keep the slots'); + assert.equal(chooseParallel({ config: cfg(32768), values: { drafting: 'dflash2', parallel: 3 }, hardware: big }).slots, 3, 'a number the person chose is theirs'); + assert.equal(applyParallel(cfg(32768, { parallel: 4 }), chosen).cfg.parallel, undefined, 'and the saved config carries no slots'); +}); diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index abce224638..b0bc78ea36 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -1468,6 +1468,20 @@ class Runner: "data_dir": drafting.data_dir_of(cfg.get("args") or []) or (Path(self.s.data_dir) if self.s.data_dir else None), "backend": backend, "archs": archs} + def one_request_for_dflash2(self, config: Path) -> bool: + """DFlash2 chosen on purpose and the person gave no number of requests: one at a time, said once (drafting.wants_one_request).""" + try: + from strata_control import drafting + if not drafting.wants_one_request(**self.drafting_inputs(read_config(config))): + return False + except Exception: # noqa: BLE001 - a note is never a reason to stop a launch + return False + if not getattr(self, "_one_request_said", False): + self._one_request_said = True + self.notices.append(drafting.ONE_REQUEST_NOTE) + self.emit("model", drafting.ONE_REQUEST_NOTE, None) + return True + def ensure_drafter(self, base_path: Path) -> None: """Fetch the DFlash2 drafter when this launch will use it and it is not here yet. Never stops the launch: if it cannot be had, the model starts with the MTP and the person is told (recommend, never force).""" @@ -1551,6 +1565,8 @@ class Runner: parallel = self.s.parallel if self.s.parallel else (getattr(self, "four_card_parallel", None) or self.catalog_parallel()) if getattr(self, "parallel_dropped", False): # DeepSeek: the engine in use is from before the flag (gate_parallel) parallel = None + if parallel and not self.s.parallel and self.one_request_for_dflash2(config): + parallel = None # the slots Strata fills in by itself would keep the MTP: DFlash2 answers one request at a time sets = [f"host={acc.host_for(self.s.access)}", f"port={int(self.s.port)}"] + ([f"parallel={parallel}"] if parallel else []) try: current, _rev = profiles.load(name) @@ -2226,6 +2242,8 @@ class Runner: try: base, cfg = self.installed_state() want = self.drafting_inputs(cfg or {}) + if drafting.needs_pack(**want): # the launch fetches the drafter first (ensure_drafter), so that is what will run + return "Drafting: DFlash2 (its drafter is downloaded first)" return drafting.summary_line(drafting.decide(**want)) except Exception: # noqa: BLE001 return "" diff --git a/strata_control/drafting.py b/strata_control/drafting.py index 710ba0a22a..b88a5fc35c 100644 --- a/strata_control/drafting.py +++ b/strata_control/drafting.py @@ -253,6 +253,18 @@ def decide(mode: Any, *, klass: str, model_name: str | None = None, family: str return Decision(asked, "dflash2", flags=engine_flags(pack_path(data_dir))) +ONE_REQUEST_NOTE = "DFlash2 answers one request at a time, so Strata set this model to one request at a time." + + +def wants_one_request(mode: Any, *, klass: str = "other", model_name: str | None = None, family: str | None = None, backend: str | None = None, + archs: Any = None, **_ignored: Any) -> bool: + """DFlash2 was asked for (by name, not by Auto) and this model and computer can run it: the model then starts with one request at a time, because + the engine's request slots (``--batch``, which Strata fills in by itself on a card with room) keep the MTP. A number of requests the person chose + stays as they chose it; the callers check that.""" + return (normalize(mode) == "dflash2" and ENGINE_SERVES_DFLASH2 and supported_model(model_name, family) + and (backend is None or hardware_support(backend, archs).can_run)) + + def needs_pack(mode: Any, *, klass: str, model_name: str | None = None, family: str | None = None, data_dir: str | Path | None = None, backend: str | None = None, archs: Any = None) -> bool: """Would this choice use the DFlash2 drafter if its file were here, and is it not here yet? (Then it is fetched before the start.)""" diff --git a/tests/terminal/test_drafting_hardware.py b/tests/terminal/test_drafting_hardware.py index e25b8eb7d3..b0692dbce4 100644 --- a/tests/terminal/test_drafting_hardware.py +++ b/tests/terminal/test_drafting_hardware.py @@ -152,5 +152,62 @@ class OfflineAndReuse(unittest.TestCase): self.assertIn(self.dir / "hf" / "hub" / "models--incoai--Qwen3.8-Flash-Next-DFlash2" / "snapshots" / drafting.REVISION, folders) +class OneRequestAtATime(unittest.TestCase): + """DFlash2 keeps the MTP when the engine runs request slots (--batch); Strata fills slots in by itself, so choosing DFlash2 means one request.""" + + def test_only_a_named_choice_on_a_computer_that_can_run_it(self): + want = drafting.wants_one_request + with serving_dflash2(): + self.assertTrue(want("dflash2", model_name=GYRO, backend="cuda", archs=["sm_121"])) + self.assertTrue(want("DFlash2", family="qwen")) + for mode in ("auto", "mtp", "off", None): + self.assertFalse(want(mode, model_name=GYRO, backend="cuda", archs=["sm_121"]), mode) + self.assertFalse(want("dflash2", model_name="qwen3.8-flash-next-coder-iq1_m", backend="cuda", archs=["sm_121"])) + self.assertFalse(want("dflash2", model_name=GYRO, backend="metal", archs=[])) + with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False): + self.assertFalse(want("dflash2", model_name=GYRO, backend="cuda", archs=["sm_121"]), "while the engine does not serve it") + + +class TheTerminalStep(unittest.TestCase): + """strata launch: the Drafting step exists only where there is something to choose, like the DeepSeek-only Speed step.""" + + def flow(self, family, hardware): + from types import SimpleNamespace + from strata_cli.launch.screens import flow_for + ctx = SimpleNamespace(computer=SimpleNamespace(usable_gpus=[0]), settings=SimpleNamespace(family=family)) + with mock.patch.object(drafting, "detect_hardware", return_value=hardware), serving_dflash2(), mock.patch("strata_cli.launch.screens.speed_choice_available", return_value=False): + return flow_for(ctx) + + def test_only_flash_next_on_a_cuda_or_hip_engine_gets_the_step(self): + flow = self.flow("qwen", ("cuda", ["sm_120"])) + self.assertIn("drafting", flow) + self.assertEqual(flow.index("drafting"), flow.index("pictures") + 1) + self.assertIn("drafting", self.flow("gyro", ("hip", ["gfx1151"]))) + for family in ("deepseek41", "swift", "coder", "unsloth", "nvfp4", "qwen36", None): + self.assertNotIn("drafting", self.flow(family, ("cuda", ["sm_120"])), family) + for hardware in (("metal", []), ("sycl", []), (None, [])): + self.assertNotIn("drafting", self.flow("qwen", hardware), hardware) + + def test_the_choice_is_saved_as_the_flag_would_and_auto_writes_nothing(self): + from types import SimpleNamespace + from strata_cli.launch import settings as S + from strata_cli.launch.screens import DraftingScreen + self.assertEqual([k for k, _ in DraftingScreen.CHOICES], list(S.DRAFTING_MODES)) + for key, saved in (("dflash2", "dflash2"), ("auto", None), ("off", "off")): + fake = SimpleNamespace(ctx=SimpleNamespace(settings=S.LaunchSettings()), menu=lambda key=key: SimpleNamespace(current=SimpleNamespace(key=key))) + DraftingScreen.commit(fake) + self.assertEqual(fake.ctx.settings.drafting, saved) + + def test_the_words_are_the_apps_words(self): + folder = ROOT / "apps" / "host" / "src" / "locales" + en = json.loads((folder / "df2-en.json").read_text(encoding="utf-8")) + self.assertEqual(en["df01"], drafting.EXPLAIN_NUMBERS) + self.assertEqual(en["df02"], drafting.EXPLAIN_LIMITS) + self.assertEqual((en["df03"], en["df04"], en["df05"]), (drafting.LINE_TESTED, drafting.LINE_SLOWER, drafting.LINE_UNTESTED)) + self.assertEqual(en["df06"], drafting.mtp_line(drafting.NOT_THIS_CARD)) + self.assertEqual(en["df07"], "There is no internet connection, so the DFlash2 drafter can't be downloaded now.") + self.assertEqual(en["df09"], drafting.ONE_REQUEST_NOTE) + + if __name__ == "__main__": unittest.main() From 611ff41d41252c150d70b5ae7de3f5621eb8ea5d Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:00:01 +0100 Subject: [PATCH 18/59] DFlash2 option: reachability check through the download's own opener, one-request rule only when the drafter file is there, tests independent of the box's card --- strata_cli/launch/runner.py | 6 +++--- strata_control/drafting_fetch.py | 5 +++-- tests/terminal/test_drafting.py | 11 +++++++++++ 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index b0bc78ea36..d7ab5518a8 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -1472,14 +1472,14 @@ class Runner: """DFlash2 chosen on purpose and the person gave no number of requests: one at a time, said once (drafting.wants_one_request).""" try: from strata_control import drafting - if not drafting.wants_one_request(**self.drafting_inputs(read_config(config))): - return False + want = self.drafting_inputs(read_config(config)) + if not drafting.wants_one_request(**want) or not drafting.pack_ready(want["data_dir"]): + return False # (no drafter file after all, e.g. no internet: the MTP runs and the slots stay) except Exception: # noqa: BLE001 - a note is never a reason to stop a launch return False if not getattr(self, "_one_request_said", False): self._one_request_said = True self.notices.append(drafting.ONE_REQUEST_NOTE) - self.emit("model", drafting.ONE_REQUEST_NOTE, None) return True def ensure_drafter(self, base_path: Path) -> None: diff --git a/strata_control/drafting_fetch.py b/strata_control/drafting_fetch.py index bc700daafc..6e291cd3a3 100644 --- a/strata_control/drafting_fetch.py +++ b/strata_control/drafting_fetch.py @@ -60,12 +60,13 @@ def online(url: str, timeout: float = REACH_SECONDS) -> bool: """Does the download address answer at all? One short HEAD request, no retry: with no internet (or a connection that hangs) the person gets a plain sentence in a few seconds instead of a stalled progress bar. Any answer from the server counts, even an error page.""" try: + transfer.check_url_policy(url) request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-drafting/1"}) - with urllib.request.urlopen(request, timeout=timeout): + with transfer._opener.open(request, timeout=timeout): # the download's own opener: same certificates, same redirect policy, same proxy settings return True except urllib.error.HTTPError: return True - except (urllib.error.URLError, OSError, TimeoutError, ValueError) as exc: + except (urllib.error.URLError, OSError, TimeoutError, ValueError, transfer.TransferError) as exc: from strata_control import tls return bool(tls.is_certificate_error(exc)) # a certificate problem is an answer: the download explains it in its own words diff --git a/tests/terminal/test_drafting.py b/tests/terminal/test_drafting.py index d5905eefe7..ff09bba381 100644 --- a/tests/terminal/test_drafting.py +++ b/tests/terminal/test_drafting.py @@ -20,6 +20,17 @@ from tests.terminal.launch_support import run_cli ROOT = Path(__file__).resolve().parents[2] GYRO = "qwen3.8-flash-next-gyro-gyro-s" +_HARDWARE = mock.patch.object(drafting, "detect_hardware", return_value=("cuda", ["sm_120"])) + + +def setUpModule(): + """These tests are about the table, the flags and the download, on a computer whose engine can run DFlash2 (the box that runs them may have an Intel or no card; + tests/terminal/test_drafting_hardware.py has the hardware matrix).""" + _HARDWARE.start() + + +def tearDownModule(): + _HARDWARE.stop() def serving_dflash2(): From f19d36463783fb332eaea9addc40f5674451bb6f Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:22:22 +0100 Subject: [PATCH 19/59] locale-gaps test reads the df2 catalog --- apps/host/tests/locale-gaps.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/host/tests/locale-gaps.test.mjs b/apps/host/tests/locale-gaps.test.mjs index 377a70d092..f9f660b915 100644 --- a/apps/host/tests/locale-gaps.test.mjs +++ b/apps/host/tests/locale-gaps.test.mjs @@ -12,7 +12,7 @@ const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64 test('every tr("...") literal and every command hint has a key in the English catalog, so no language is stuck in English (#3479)', async () => { const known = new Set(); - for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en', 'ui-en', 'engine-en', 'pick-en']) for (const v of Object.values(await read(name))) known.add(String(v)); + for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en', 'ui-en', 'engine-en', 'pick-en', 'df2-en']) for (const v of Object.values(await read(name))) known.add(String(v)); const missing = []; const scan = async dir => { for (const entry of await readdir(dir, { withFileTypes: true })) { From c70e0499549aea38a33544d617f149b749bbc20d Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:50:42 +0100 Subject: [PATCH 20/59] Default reading size 12 px and interface size 90%: a size the person chose is kept, a save that holds the old defaults moves once; Reset returns to the new ones --- apps/host/src/lib/default-sizes.ts | 20 ++++++++++ apps/host/src/lib/store.ts | 12 ++++-- apps/host/src/styles/app.css | 22 +++++------ apps/host/tests/chat-details.test.mjs | 2 +- apps/host/tests/default-sizes.test.mjs | 49 ++++++++++++++++++++++++ apps/host/tests/gh-app-features.test.mjs | 3 +- 6 files changed, 91 insertions(+), 17 deletions(-) create mode 100644 apps/host/src/lib/default-sizes.ts create mode 100644 apps/host/tests/default-sizes.test.mjs diff --git a/apps/host/src/lib/default-sizes.ts b/apps/host/src/lib/default-sizes.ts new file mode 100644 index 0000000000..7d88c05097 --- /dev/null +++ b/apps/host/src/lib/default-sizes.ts @@ -0,0 +1,20 @@ +/** The default reading size and interface size (owner, 11-01: 12 px and 90%; they were 14 px and 100%). */ +export const DEFAULT_CONTENT_FS = 12; +export const DEFAULT_UI_SCALE = 0.9; +export const UI_SCALE_CHOICES = [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2] as const; +/** Saves made while the old defaults were in force carry no `sizeDefaults` mark. */ +export const SIZE_DEFAULTS_VERSION = 2; +const OLD_CONTENT_FS = 14; +const OLD_UI_SCALE = 1; + +/** The two sizes to use for a saved preferences record. A save without the mark is not a choice when it holds the old default (14 px, 100%): that + * becomes the new default once. Any other value is a size the person picked and stays. A save with the mark is kept as it is. Nothing saved: the defaults. */ +export function savedSizes(saved: { contentFontSize?: unknown; uiScale?: unknown; sizeDefaults?: unknown } | null | undefined, min: number, max: number) { + const fs = Number(saved?.contentFontSize), scale = Number(saved?.uiScale); + const marked = saved?.sizeDefaults === SIZE_DEFAULTS_VERSION; + const fsOk = Number.isFinite(fs) && fs > 0, scaleOk = (UI_SCALE_CHOICES as readonly number[]).includes(scale); + return { + contentFontSize: !fsOk || (!marked && fs === OLD_CONTENT_FS) ? DEFAULT_CONTENT_FS : Math.min(max, Math.max(min, fs)), + uiScale: !scaleOk || (!marked && scale === OLD_UI_SCALE) ? DEFAULT_UI_SCALE : scale, + }; +} diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 576d93bb16..b8be4c3266 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -1,4 +1,5 @@ import { workspaceIdForSession } from './session-workspace'; +import { DEFAULT_CONTENT_FS, DEFAULT_UI_SCALE, SIZE_DEFAULTS_VERSION, savedSizes } from './default-sizes'; import { detectLanguage } from './language-detect'; import { validWhileBusy, type WhileBusy } from './while-busy'; import { addToQuotes, type Quote } from './quotes'; @@ -152,6 +153,8 @@ const CONTENT_FS_MIN = 10; const CONTENT_FS_MAX = 22; export interface Prefs { + /** Which default sizes this save was made with (see SIZE_DEFAULTS_VERSION). */ + sizeDefaults?: number; language: Language; fontFamily: string; theme: 'dark' | 'light' | 'system'; @@ -181,11 +184,11 @@ const PREFS_DEFAULTS: Prefs = { contrast: 'standard', rail: false, focus: false, - contentFontSize: 14, + contentFontSize: DEFAULT_CONTENT_FS, density: 'comfortable', motion: 'system', transparency: 'translucent', - uiScale: 1, + uiScale: DEFAULT_UI_SCALE, electricityPrice: 0, electricityCurrency: '', doneSound: false, @@ -234,8 +237,8 @@ function loadPrefs(): Prefs { ...parsed, language: validLanguage(parsed.language) ? parsed.language : 'en', fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '', - contentFontSize: Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Number(parsed.contentFontSize) || 14)), - uiScale: [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2].includes(Number(parsed.uiScale)) ? Number(parsed.uiScale) : 1, + ...savedSizes(parsed, CONTENT_FS_MIN, CONTENT_FS_MAX), + sizeDefaults: SIZE_DEFAULTS_VERSION, electricityPrice: Number.isFinite(Number(parsed.electricityPrice)) && Number(parsed.electricityPrice) > 0 && Number(parsed.electricityPrice) < 1000 ? Number(parsed.electricityPrice) : 0, electricityCurrency: typeof parsed.electricityCurrency === 'string' && /^[A-Za-z]{3}$/.test(parsed.electricityCurrency) ? parsed.electricityCurrency.toUpperCase() : '', doneSound: parsed.doneSound === true, @@ -494,6 +497,7 @@ function applyPrefs() { function savePrefs() { const snapshot: Prefs = { + sizeDefaults: SIZE_DEFAULTS_VERSION, language: state.language, fontFamily: state.fontFamily, theme: state.theme, diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index 473131e0c4..6aa767d646 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -56,13 +56,13 @@ /* Type inside a conversation follows the reader's text size. The ratios are declared once here, so a rule that scales with the prose uses a token instead of a bespoke calc that the type audit cannot check. */ - --st-fs-read-lg: calc(var(--st-content-fs, 14px) * 1.125); - /* The small ratio has a floor: at the default 14px reading size, 0.8125 - would put code and tables at 11.4px, which is below what a table of + --st-fs-read-lg: calc(var(--st-content-fs, 12px) * 1.125); + /* The small ratio has a floor: at any reading size up to 14px, 0.8125 + would put code and tables under 12px (9.75px at the default 12px), which is below what a table of numbers should ask of a reader. */ - --st-fs-read-sm: max(12px, calc(var(--st-content-fs, 14px) * .8125)); - --st-fs-math: calc(var(--st-content-fs, 14px) * 1.08); - --st-fs-math-source: calc(var(--st-content-fs, 14px) * .9); + --st-fs-read-sm: max(12px, calc(var(--st-content-fs, 12px) * .8125)); + --st-fs-math: calc(var(--st-content-fs, 12px) * 1.08); + --st-fs-math-source: calc(var(--st-content-fs, 12px) * .9); } /* Two shared recipes replace the nine bespoke entrance keyframes this file used @@ -465,11 +465,11 @@ target is 45–75, verified by `npm run measure`). */ .app[data-focus='true'] .slashmenu, .app[data-focus='true'] .chat__inner { - font-size: var(--st-content-fs, 14px); + font-size: var(--st-content-fs, 12px); max-width: calc(var(--st-measure) + 72px); } .app[data-focus='true'] .composer__inner { - font-size: var(--st-content-fs, 14px); + font-size: var(--st-content-fs, 12px); /* the same column, less the transcript's 28px padding on each side */ max-width: calc(var(--st-measure) + 2.5em - 56px); } @@ -488,8 +488,8 @@ — the same scoping DSH uses for its 10–22px content setting. */ .st-msg--assistant .st-bubble, .st-msg--user .st-bubble { - font-size: var(--st-content-fs, 14px); - line-height: calc(var(--st-content-fs, 14px) * 1.62); + font-size: var(--st-content-fs, 12px); + line-height: calc(var(--st-content-fs, 12px) * 1.62); } /* Density — the difference between scanning data and reading it. */ @@ -7017,7 +7017,7 @@ textarea { .error-notice .error-detail pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 6px 0 0; font-family: var(--st-font-mono); max-height: 3.3em; overflow-y: auto; } .error-detail-text { white-space: pre-wrap; overflow-wrap: anywhere; margin: 6px 0 0; font-family: var(--st-font-mono); } /* What you type and the small print under each message follow the reading size too, so the whole conversation changes together. */ -.st-composer textarea { font-size: var(--st-content-fs, 14px); } +.st-composer textarea { font-size: var(--st-content-fs, 12px); } .st-msg__meta, .st-msg__meta time { font-size: var(--st-fs-read-sm); } /* What an approval is about, shown without opening the card: the file or the command. */ diff --git a/apps/host/tests/chat-details.test.mjs b/apps/host/tests/chat-details.test.mjs index 39cd1901c8..153d76057a 100644 --- a/apps/host/tests/chat-details.test.mjs +++ b/apps/host/tests/chat-details.test.mjs @@ -50,7 +50,7 @@ test('code blocks have room after them and are lighter than the text; the 12px f assert.match(liquid, /\.st-bubble \.st-code \{\s*margin: 16px 0 20px;/); assert.match(liquid, /\.st-code__head \{\s*min-height: 34px;/); const app = await read('src/styles/app.css'); - assert.match(app, /--st-fs-read-sm: max\(12px, calc\(var\(--st-content-fs, 14px\) \* \.8125\)\);/); + assert.match(app, /--st-fs-read-sm: max\(12px, calc\(var\(--st-content-fs, 12px\) \* \.8125\)\);/); }); test('the sidebar preview comes in and goes out with motion, from the one motion scale, and the reduced-motion gate zeroes the distance', () => { diff --git a/apps/host/tests/default-sizes.test.mjs b/apps/host/tests/default-sizes.test.mjs new file mode 100644 index 0000000000..5e7fdb534b --- /dev/null +++ b/apps/host/tests/default-sizes.test.mjs @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync as read } from 'node:fs'; +import { DEFAULT_CONTENT_FS, DEFAULT_UI_SCALE, SIZE_DEFAULTS_VERSION, savedSizes } from '../src/lib/default-sizes.ts'; + +const src = name => read(new URL(`../${name}`, import.meta.url), 'utf8'); +const MIN = 10, MAX = 22; + +test('the defaults are a 12 px reading size and a 90 percent interface', () => { + assert.equal(DEFAULT_CONTENT_FS, 12); + assert.equal(DEFAULT_UI_SCALE, 0.9); + const store = src('src/lib/store.ts'); + assert.match(store, /contentFontSize: DEFAULT_CONTENT_FS,/); + assert.match(store, /uiScale: DEFAULT_UI_SCALE,/); + assert.match(store, /contentFontSize: PREFS_DEFAULTS\.contentFontSize,[\s\S]*uiScale: PREFS_DEFAULTS\.uiScale,/, 'Reset appearance returns to the defaults, whatever they are'); + assert.doesNotMatch(src('src/styles/app.css'), /--st-content-fs, 14px/, 'the stylesheet fallbacks follow the new default'); +}); + +test('nothing saved gives the defaults; a size the person chose stays', () => { + assert.deepEqual(savedSizes(null, MIN, MAX), { contentFontSize: 12, uiScale: 0.9 }); + assert.deepEqual(savedSizes({}, MIN, MAX), { contentFontSize: 12, uiScale: 0.9 }); + assert.deepEqual(savedSizes({ contentFontSize: 18, uiScale: 1.25 }, MIN, MAX), { contentFontSize: 18, uiScale: 1.25 }, 'an old save that chose a size keeps it'); + assert.deepEqual(savedSizes({ contentFontSize: 11, uiScale: 1.1 }, MIN, MAX), { contentFontSize: 11, uiScale: 1.1 }); +}); + +test('an old save that holds the old defaults moves to the new ones once, then everything is kept as saved', () => { + assert.deepEqual(savedSizes({ contentFontSize: 14, uiScale: 1 }, MIN, MAX), { contentFontSize: 12, uiScale: 0.9 }); + const marked = { sizeDefaults: SIZE_DEFAULTS_VERSION }; + assert.deepEqual(savedSizes({ ...marked, contentFontSize: 14, uiScale: 1 }, MIN, MAX), { contentFontSize: 14, uiScale: 1 }, 'picked after the change: 14 px and 100% are a choice'); + assert.deepEqual(savedSizes({ ...marked, contentFontSize: 12, uiScale: 0.9 }, MIN, MAX), { contentFontSize: 12, uiScale: 0.9 }); +}); + +test('a damaged save falls back to the defaults and the reading size stays inside its range', () => { + assert.deepEqual(savedSizes({ contentFontSize: 'big', uiScale: 7 }, MIN, MAX), { contentFontSize: 12, uiScale: 0.9 }); + assert.equal(savedSizes({ sizeDefaults: SIZE_DEFAULTS_VERSION, contentFontSize: 99, uiScale: 1 }, MIN, MAX).contentFontSize, MAX); + assert.equal(savedSizes({ sizeDefaults: SIZE_DEFAULTS_VERSION, contentFontSize: 3, uiScale: 1 }, MIN, MAX).contentFontSize, MIN); +}); + +test('code keeps its 12 px floor, so at the default it is the size of the prose and stays apart by its font, bar and background', () => { + const css = src('src/styles/app.css'); + assert.match(css, /--st-fs-read-sm: max\(12px, calc\(var\(--st-content-fs, 12px\) \* \.8125\)\);/); + assert.match(css, /\.st-bubble \.st-code pre, \.st-bubble \.st-code pre code, \.st-bubble \.st-code \.syntax-text \{ font-size: var\(--st-fs-read-sm\); \}/); +}); + +test('the Settings controls show the stored values as they are, with no second default of their own', () => { + const settings = src('src/screens/Settings.tsx'); + assert.match(settings, /value=\{prefs\.contentFontSize\}/); + assert.match(settings, /value=\{String\(prefs\.uiScale\)\}/); +}); diff --git a/apps/host/tests/gh-app-features.test.mjs b/apps/host/tests/gh-app-features.test.mjs index 701832c1a2..ca0cd20623 100644 --- a/apps/host/tests/gh-app-features.test.mjs +++ b/apps/host/tests/gh-app-features.test.mjs @@ -174,7 +174,8 @@ test('the interface size scales the whole page, up to 200 percent, and a saved v assert.match(store, /setProperty\('zoom', state\.uiScale === 1 \? '' : String\(state\.uiScale\)\)/); assert.match(store, /setProperty\('--st-ui-scale', '1'\)/, 'the token stays at 1 so nothing is scaled twice'); assert.match(store, /UI_SCALES = \[0\.9, 1, 1\.1, 1\.25, 1\.5, 1\.75, 2\]/); - assert.match(store, /\[0\.9, 1, 1\.1, 1\.25, 1\.5, 1\.75, 2\]\.includes\(Number\(parsed\.uiScale\)\)/); + assert.match(readFileSync(new URL('../src/lib/default-sizes.ts', import.meta.url), 'utf8'), /UI_SCALE_CHOICES = \[0\.9, 1, 1\.1, 1\.25, 1\.5, 1\.75, 2\]/); + assert.match(store, /savedSizes\(parsed, CONTENT_FS_MIN, CONTENT_FS_MAX\)/, 'a saved value is checked'); const settings = readFileSync(new URL('../src/screens/Settings.tsx', import.meta.url), 'utf8'); assert.match(settings, /Makes all text, buttons and menus in Strata larger or smaller\./); }); From 0ffb1d567c53fd3aef3b00a2c67342b65bcdbc61 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:50:42 +0100 Subject: [PATCH 21/59] DFlash2 falling back to the MTP: the MTP runs its own window (--draft-mtp-spec), not DFlash2's 6, unless the person typed --spec --- src/program/generate.cpp | 7 +++++- strata_control/drafting.py | 12 ++++++--- tests/terminal/test_drafting.py | 44 ++++++++++++++++++++++++++++++--- 3 files changed, 56 insertions(+), 7 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1091fa9f49..c724017e8b 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -933,6 +933,7 @@ struct Options { bool draft_auto = false; std::string draft_rule = "df2"; ///< --draft-rule df2|mtp|learn: what a request without a draft= key gets int draft_mtp_spec = 4; ///< --draft-mtp-spec N: the widest window of a request that drafts with the MTP layer under --draft auto + bool draft_mtp_spec_set = false; ///< --draft-mtp-spec was given: it is also the window the MTP runs when --draft dflash2 falls back to it (the wider --spec was for DFlash2) double draft_mtp_min_p = -1.0; ///< --draft-mtp-min-p P: the MTP requests' --spec-min-p under --draft auto (-1 = --spec-min-p) int draft_cap = 0; ///< --draft-cap N: the widest verify window with --draft dflash2 (0 = by card class, see where the drafter loads) /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the @@ -3504,7 +3505,7 @@ int main(int argc, char** argv) { } } else if (a == "--draft-rule") o.draft_rule = next("--draft-rule"); - else if (a == "--draft-mtp-spec") o.draft_mtp_spec = std::max(2, std::atoi(next("--draft-mtp-spec"))); + else if (a == "--draft-mtp-spec") { o.draft_mtp_spec = std::max(2, std::atoi(next("--draft-mtp-spec"))); o.draft_mtp_spec_set = true; } else if (a == "--draft-mtp-min-p") o.draft_mtp_min_p = std::clamp(std::atof(next("--draft-mtp-min-p")), 0.0, 1.0); else if (a == "--draft-model") o.draft_model = next("--draft-model"); else if (a == "--draft-conf") o.draft_conf = std::clamp(std::atof(next("--draft-conf")), 0.0, 1.0); @@ -6608,6 +6609,8 @@ int main(int argc, char** argv) { } else { std::fprintf(stderr, "strata generate: --draft dflash2 is off: %s; the MTP drafts instead\n", why); } + // DFlash2 did not start: the MTP drafts, with its own window (the wider --spec was DFlash2's), when --draft-mtp-spec names it + if (!use_df2 && o.draft_mtp_spec_set && o.spec > o.draft_mtp_spec) o.spec = o.draft_mtp_spec; } #endif if (batch_mtp) { @@ -10601,6 +10604,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata serve: --draft dflash2: %s. It needs about 1.2 GiB of VRAM in all (the pack 0.76 GiB, buffers and K/V ring 0.25 GiB, " "a draft head 0.2 GiB, 0.1 GiB of prompt staging); --vram-reserve-mib 1900 keeps it. The MTP drafts instead.\n", why_not.c_str()); use_df2 = false; + if (o.draft_mtp_spec_set && o.spec > o.draft_mtp_spec) o.spec = o.draft_mtp_spec; // the MTP drafts with its own window, not DFlash2's } else { sp.on_taps = [&](const float* taps, int64_t rows, int64_t pos0, std::string& e) -> bool { return df2.context(taps, rows, pos0, e); }; std::fprintf(stderr, "strata serve: DFlash2 drafter on (%s, graphs captured in %.0f ms); windows up to %d tokens; the MTP layer stays as the fallback\n", @@ -18831,6 +18835,7 @@ int main(int argc, char** argv) { use_df2 = false; } if (use_df2) std::fprintf(stderr, "strata generate: DFlash2 drafter on (%s, graphs captured in %.0f ms), the MTP layer stays as the fallback\n", o.draft_model.c_str(), df2.ms_capture); + else if (o.draft == "dflash2" && o.draft_mtp_spec_set && o.spec > o.draft_mtp_spec) o.spec = o.draft_mtp_spec; // fell back: the MTP's own window #endif mem_mark("the verifier and the drafter's binding"); ver.set_sampling(sp); // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here diff --git a/strata_control/drafting.py b/strata_control/drafting.py index b88a5fc35c..5d9a3182a2 100644 --- a/strata_control/drafting.py +++ b/strata_control/drafting.py @@ -166,6 +166,7 @@ PACK_NAME = "qwen3.8-flash-next-dflash2.q8.pack" VRAM_GB = 1.2 # what the drafter needs in graphics memory (the engine's own estimate) FOLDER = "dflash2" # under the model data folder, next to ``mtp`` SPEC_WINDOW = 6 # --spec with DFlash2: the widest window of drafted words per round (measured best on Blackwell; the engine caps it per card) +MTP_WINDOW = 4 # the MTP's usual --spec: the window it runs when DFlash2 falls back to it, unless the config names another DRAFT_CONF = 0.35 # --draft-conf with DFlash2: the window ends where the chance that every draft so far holds falls below this #: model families (strata launch --family) the drafter was trained for and measured on: Qwen3.8-Flash-Next and its Gyro build. @@ -275,11 +276,11 @@ def needs_pack(mode: Any, *, klass: str, model_name: str | None = None, family: return want == "dflash2" and ENGINE_SERVES_DFLASH2 and supported_model(model_name, family) and not pack_ready(data_dir) -DRAFT_FLAGS = {"--draft": True, "--draft-model": True, "--draft-conf": True} +DRAFT_FLAGS = {"--draft": True, "--draft-model": True, "--draft-conf": True, "--draft-mtp-spec": True} def strip_draft_flags(args: list[Any]) -> list[str]: - """The arguments without ``--draft`` / ``--draft-model`` / ``--draft-conf`` (and their values).""" + """The arguments without ``--draft`` / ``--draft-model`` / ``--draft-conf`` / ``--draft-mtp-spec`` (and their values).""" out: list[str] = [] items = [str(a) for a in args] i = 0 @@ -344,7 +345,12 @@ def apply(cfg: dict[str, Any], *, klass: str, data_dir: str | Path | None = None if kept_conf is not None: flags[flags.index("--draft-conf") + 1] = kept_conf if _flag_value(mine, "--spec") is None: - args = _without_flag(args, "--spec") # the person's own --spec stays; otherwise the window is the DFlash2 one + # The person's own --spec stays; otherwise the window is the DFlash2 one. If the engine then falls back to the MTP (the card is too + # full for the drafter), the MTP must run its usual window, not DFlash2's: --draft-mtp-spec names it (the engine uses it for that). + mtp_window = _flag_value(args, "--spec") + args = _without_flag(args, "--spec") + kept_window = _flag_value(mine, "--draft-mtp-spec") + flags += ["--draft-mtp-spec", kept_window if kept_window is not None else mtp_window if (mtp_window or "").isdigit() and int(mtp_window) >= 2 else str(MTP_WINDOW)] else: i = flags.index("--spec") del flags[i:i + 2] diff --git a/tests/terminal/test_drafting.py b/tests/terminal/test_drafting.py index ff09bba381..a74e651504 100644 --- a/tests/terminal/test_drafting.py +++ b/tests/terminal/test_drafting.py @@ -175,12 +175,50 @@ class EngineArguments(unittest.TestCase): d = drafting.apply(c, klass="blackwell", data_dir=self.data) self.assertEqual(d.drafter, "dflash2") spec_at = self.ARGS.index("--spec") - self.assertEqual(c["args"], [*self.ARGS[:spec_at], *self.ARGS[spec_at + 2:], "--draft", "dflash2", "--draft-model", str(pack), "--spec", "6", "--draft-conf", "0.35"], - "the MTP window of 4 gives way to DFlash2's 6; the MTP's own arguments stay") + self.assertEqual(c["args"], [*self.ARGS[:spec_at], *self.ARGS[spec_at + 2:], "--draft", "dflash2", "--draft-model", str(pack), "--spec", "6", "--draft-conf", "0.35", "--draft-mtp-spec", "4"], + "the MTP window of 4 gives way to DFlash2's 6 (and is named for the fallback); the MTP's own arguments stay") self.assertEqual(c["args"].count("--draft"), 1) self.assertEqual(c["args"].count("--spec"), 1) self.assertIn("--mtp", c["args"], "the MTP stays as the fallback the engine names") + def test_a_fallback_to_the_mtp_keeps_the_mtps_own_window(self): + """DFlash2 starts with --spec 6; when the engine falls back to the MTP the window must be the MTP's usual one, named with --draft-mtp-spec.""" + pack = drafting.pack_path(self.data) + pack.parent.mkdir(parents=True) + pack.write_bytes(b"x" * (2 << 20)) + with serving_dflash2(): + c = self.cfg(drafting="dflash2") + drafting.apply(c, klass="blackwell", data_dir=self.data) + args = c["args"] + self.assertEqual(args[args.index("--draft-mtp-spec") + 1], "4", "the window the config had for the MTP") + self.assertEqual(args[args.index("--spec") + 1], "6") + # a config whose MTP window is 3 (a Mac preset) falls back to 3, and one with no window to the usual 4 + c = self.cfg(drafting="dflash2", args=[a if a != "4" else "3" for a in self.ARGS]) + drafting.apply(c, klass="blackwell", data_dir=self.data) + self.assertEqual(c["args"][c["args"].index("--draft-mtp-spec") + 1], "3") + c = self.cfg(drafting="dflash2", args=[a for i, a in enumerate(self.ARGS) if i not in (self.ARGS.index("--spec"), self.ARGS.index("--spec") + 1)]) + drafting.apply(c, klass="blackwell", data_dir=self.data) + self.assertEqual(c["args"][c["args"].index("--draft-mtp-spec") + 1], str(drafting.MTP_WINDOW)) + # a window the person typed by hand is theirs: DFlash2 and the fallback both run it, nothing is added + c = self.cfg(drafting="dflash2", args=[*self.ARGS[:self.ARGS.index("--spec")], "--spec", "5"], user_args=["--spec", "5"]) + drafting.apply(c, klass="blackwell", data_dir=self.data) + self.assertNotIn("--draft-mtp-spec", c["args"]) + self.assertEqual(c["args"][c["args"].index("--spec") + 1], "5") + # a --draft-mtp-spec the person typed stays as typed + c = self.cfg(drafting="dflash2", args=[*self.ARGS, "--draft-mtp-spec", "2"], user_args=["--draft-mtp-spec", "2"]) + drafting.apply(c, klass="blackwell", data_dir=self.data) + self.assertEqual((c["args"].count("--draft-mtp-spec"), c["args"][c["args"].index("--draft-mtp-spec") + 1]), (1, "2")) + # choosing the MTP again leaves no trace of it + c = self.cfg(drafting="mtp", args=[*self.ARGS, "--draft", "dflash2", "--draft-model", "/p", "--draft-mtp-spec", "4"]) + drafting.apply(c, klass="blackwell", data_dir=self.data) + self.assertEqual(c["args"], self.ARGS) + + def test_the_engine_uses_the_named_window_when_dflash2_falls_back(self): + """The engine side (src/program/generate.cpp): the flag marks itself as given, and each place DFlash2 falls back to the MTP applies it.""" + src = (ROOT / "src" / "program" / "generate.cpp").read_text(encoding="utf-8") + self.assertIn("o.draft_mtp_spec_set = true", src) + self.assertEqual(src.count("o.spec = o.draft_mtp_spec;"), 3, "the CLI start, the CLI loop and serve") + def test_mtp_removes_a_drafter_that_was_written_by_hand(self): c = self.cfg(drafting="mtp", args=[*self.ARGS, "--draft", "dflash2", "--draft-model", "/p"]) drafting.apply(c, klass="blackwell", data_dir=self.data) @@ -208,7 +246,7 @@ class EngineArguments(unittest.TestCase): with mock.patch("serve.server.drafting_card_class", return_value="blackwell"), serving_dflash2(), \ mock.patch.object(drafting, "pack_ready", return_value=True), mock.patch.object(drafting, "data_dir_of", return_value=Path("/d")): args = engine_args(self.cfg(drafting="dflash2")) - self.assertEqual(args[-8:], ["--draft", "dflash2", "--draft-model", str(pack), "--spec", "6", "--draft-conf", "0.35"]) + self.assertEqual(args[-10:], ["--draft", "dflash2", "--draft-model", str(pack), "--spec", "6", "--draft-conf", "0.35", "--draft-mtp-spec", "4"]) with mock.patch("serve.server.drafting_card_class", return_value="blackwell"), mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False): self.assertEqual(engine_args(self.cfg()), self.ARGS, "no choice: nothing changes") off = engine_args(self.cfg(drafting="off")) From a000bec3ce847035539fb1681f5103557de67160 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:57:08 +0100 Subject: [PATCH 22/59] Update engine with a model loaded: warn naming it, stop it with the person's yes through strata update --stop-model, progress in words, offer to start it again with the same settings (also on the old engine after a failed update); nine languages --- apps/host/scripts/make-update-locales.py | 125 ++++++++++ apps/host/server/control-runtime.mjs | 4 +- apps/host/server/index.mjs | 1 + apps/host/server/native-control.mjs | 58 ++++- .../src/components/EngineUpdateDialog.tsx | 130 +++++++++++ apps/host/src/components/NativeModels.tsx | 2 + apps/host/src/components/SettingsUpdates.tsx | 6 +- apps/host/src/lib/i18n.ts | 14 +- apps/host/src/lib/native.ts | 4 +- apps/host/src/locales/upd-de.json | 19 ++ apps/host/src/locales/upd-en.json | 19 ++ apps/host/src/locales/upd-es.json | 19 ++ apps/host/src/locales/upd-fr.json | 19 ++ apps/host/src/locales/upd-ja.json | 19 ++ apps/host/src/locales/upd-ko.json | 19 ++ apps/host/src/locales/upd-pt.json | 19 ++ apps/host/src/locales/upd-ru.json | 19 ++ apps/host/src/locales/upd-zh.json | 19 ++ apps/host/tests/engine-update-model.test.mjs | 220 ++++++++++++++++++ apps/host/tests/locale-gaps.test.mjs | 2 +- 20 files changed, 724 insertions(+), 13 deletions(-) create mode 100644 apps/host/scripts/make-update-locales.py create mode 100644 apps/host/src/components/EngineUpdateDialog.tsx create mode 100644 apps/host/src/locales/upd-de.json create mode 100644 apps/host/src/locales/upd-en.json create mode 100644 apps/host/src/locales/upd-es.json create mode 100644 apps/host/src/locales/upd-fr.json create mode 100644 apps/host/src/locales/upd-ja.json create mode 100644 apps/host/src/locales/upd-ko.json create mode 100644 apps/host/src/locales/upd-pt.json create mode 100644 apps/host/src/locales/upd-ru.json create mode 100644 apps/host/src/locales/upd-zh.json create mode 100644 apps/host/tests/engine-update-model.test.mjs diff --git a/apps/host/scripts/make-update-locales.py b/apps/host/scripts/make-update-locales.py new file mode 100644 index 0000000000..019f4475b2 --- /dev/null +++ b/apps/host/scripts/make-update-locales.py @@ -0,0 +1,125 @@ +"""Writes src/locales/upd-<lang>.json: the strings of the engine update beside a loaded model (the dialog of Settings > About, branch f-0291-ui-final). +Run from apps/host: python scripts/make-update-locales.py +Every entry names all nine languages; the keys are upd01.. in the order of S. upd-en.json is the English source. Placeholders ({0}) must be kept in every +language. A separate file keeps this work from colliding with the other catalogs (the same reason pick-, tune-, tools-, fix-, gh-, ui-, engine- and df2- exist).""" +import json +import re +from pathlib import Path + +LANGS = ["en", "zh", "ja", "de", "es", "ru", "pt", "ko", "fr"] +S = [] + + +def add(en, zh, ja, de, es, ru, pt, ko, fr): + S.append(dict(en=en, zh=zh, ja=ja, de=de, es=es, ru=ru, pt=pt, ko=ko, fr=fr)) + + +add("To update the engine, Strata has to stop the model that is loaded: {0}.", + "要更新引擎,Strata 必须先停止当前已加载的模型:{0}。", + "エンジンを更新するには、読み込み中のモデルを Strata が停止する必要があります:{0}。", + "Um die Engine zu aktualisieren, muss Strata das geladene Modell anhalten: {0}.", + "Para actualizar el motor, Strata tiene que detener el modelo cargado: {0}.", + "Чтобы обновить движок, Strata должна остановить загруженную модель: {0}.", + "Para atualizar o motor, o Strata precisa parar o modelo carregado: {0}.", + "엔진을 업데이트하려면 Strata가 불러온 모델을 중지해야 합니다: {0}.", + "Pour mettre à jour le moteur, Strata doit arrêter le modèle chargé : {0}.") +add("The new engine downloads first while the model keeps answering. Then the model stops (answers in progress finish first), the engine is updated, and you can start the model again with the same settings. Your models and settings are kept.", + "新引擎会先下载,此时模型仍可继续回答。然后模型停止(正在进行的回答会先完成),引擎随即更新,之后你可以用相同的设置再次启动该模型。你的模型和设置都会保留。", + "まず新しいエンジンをダウンロードします。その間、モデルは応答を続けます。その後モデルが停止し(進行中の回答は先に完了します)、エンジンが更新され、同じ設定でモデルをもう一度起動できます。モデルと設定はそのまま残ります。", + "Zuerst wird die neue Engine heruntergeladen, während das Modell weiter antwortet. Danach hält das Modell an (laufende Antworten werden zuerst beendet), die Engine wird aktualisiert, und Sie können das Modell mit denselben Einstellungen wieder starten. Ihre Modelle und Einstellungen bleiben erhalten.", + "Primero se descarga el motor nuevo mientras el modelo sigue respondiendo. Después el modelo se detiene (las respuestas en curso terminan antes), se actualiza el motor y puedes volver a iniciar el modelo con los mismos ajustes. Tus modelos y ajustes se conservan.", + "Сначала новый движок скачивается, пока модель продолжает отвечать. Затем модель останавливается (ответы в процессе сначала завершаются), движок обновляется, и вы можете снова запустить модель с теми же настройками. Ваши модели и настройки сохраняются.", + "Primeiro o novo motor é baixado enquanto o modelo continua a responder. Depois o modelo para (as respostas em curso terminam antes), o motor é atualizado e pode iniciar o modelo de novo com as mesmas definições. Os seus modelos e definições são mantidos.", + "먼저 모델이 계속 응답하는 동안 새 엔진을 다운로드합니다. 그다음 모델이 중지되고(진행 중인 답변은 먼저 끝납니다) 엔진이 업데이트되며, 같은 설정으로 모델을 다시 시작할 수 있습니다. 모델과 설정은 그대로 유지됩니다.", + "Le nouveau moteur est d'abord téléchargé pendant que le modèle continue de répondre. Ensuite le modèle s'arrête (les réponses en cours se terminent d'abord), le moteur est mis à jour, et vous pouvez redémarrer le modèle avec les mêmes réglages. Vos modèles et réglages sont conservés.") +add("Stop and update", "停止并更新", "停止して更新", "Anhalten und aktualisieren", "Detener y actualizar", "Остановить и обновить", "Parar e atualizar", "중지하고 업데이트", "Arrêter et mettre à jour") +add("Getting the new engine ready. {0} keeps working until it is ready.", + "正在准备新引擎。在准备好之前,{0} 会继续工作。", + "新しいエンジンを準備しています。準備ができるまで {0} は動き続けます。", + "Die neue Engine wird vorbereitet. {0} arbeitet weiter, bis sie bereit ist.", + "Preparando el motor nuevo. {0} sigue funcionando hasta que esté listo.", + "Готовим новый движок. {0} продолжает работать, пока он не будет готов.", + "A preparar o novo motor. {0} continua a funcionar até estar pronto.", + "새 엔진을 준비하는 중입니다. 준비될 때까지 {0}은(는) 계속 작동합니다.", + "Préparation du nouveau moteur. {0} continue de fonctionner jusqu'à ce qu'il soit prêt.") +add("Stopping {0}. Answers in progress finish first.", + "正在停止 {0}。正在进行的回答会先完成。", + "{0} を停止しています。進行中の回答は先に完了します。", + "{0} wird angehalten. Laufende Antworten werden zuerst beendet.", + "Deteniendo {0}. Las respuestas en curso terminan antes.", + "Останавливаем {0}. Ответы в процессе сначала завершаются.", + "A parar {0}. As respostas em curso terminam antes.", + "{0}을(를) 중지하는 중입니다. 진행 중인 답변은 먼저 끝납니다.", + "Arrêt de {0}. Les réponses en cours se terminent d'abord.") +add("{0} is stopped. Updating the engine…", + "{0} 已停止。正在更新引擎…", + "{0} を停止しました。エンジンを更新しています…", + "{0} ist angehalten. Die Engine wird aktualisiert…", + "{0} está detenido. Actualizando el motor…", + "{0} остановлена. Обновляем движок…", + "{0} está parado. A atualizar o motor…", + "{0}이(가) 중지되었습니다. 엔진을 업데이트하는 중입니다…", + "{0} est arrêté. Mise à jour du moteur…") +add("Updating the engine", "正在更新引擎", "エンジンを更新しています", "Engine wird aktualisiert", "Actualizando el motor", "Обновление движка", "A atualizar o motor", "엔진 업데이트 중", "Mise à jour du moteur") +add("The engine is updated", "引擎已更新", "エンジンを更新しました", "Die Engine ist aktualisiert", "El motor está actualizado", "Движок обновлён", "O motor está atualizado", "엔진이 업데이트되었습니다", "Le moteur est à jour") +add("The engine was not updated", "引擎未更新", "エンジンは更新されませんでした", "Die Engine wurde nicht aktualisiert", "El motor no se actualizó", "Движок не обновлён", "O motor não foi atualizado", "엔진이 업데이트되지 않았습니다", "Le moteur n'a pas été mis à jour") +add("The engine is updated. Start {0} again with the same settings?", + "引擎已更新。要用相同的设置再次启动 {0} 吗?", + "エンジンを更新しました。同じ設定で {0} をもう一度起動しますか?", + "Die Engine ist aktualisiert. {0} mit denselben Einstellungen wieder starten?", + "El motor está actualizado. ¿Iniciar {0} de nuevo con los mismos ajustes?", + "Движок обновлён. Запустить {0} снова с теми же настройками?", + "O motor está atualizado. Iniciar {0} de novo com as mesmas definições?", + "엔진이 업데이트되었습니다. 같은 설정으로 {0}을(를) 다시 시작할까요?", + "Le moteur est à jour. Redémarrer {0} avec les mêmes réglages ?") +add("The update didn't finish. Your old engine is unchanged and still works. Start {0} again on it?", + "更新没有完成。你原来的引擎没有改动,仍然可用。要在它上面再次启动 {0} 吗?", + "更新は完了しませんでした。以前のエンジンは変更されておらず、そのまま使えます。そのエンジンで {0} をもう一度起動しますか?", + "Die Aktualisierung wurde nicht abgeschlossen. Ihre alte Engine ist unverändert und funktioniert weiter. {0} damit wieder starten?", + "La actualización no terminó. Tu motor anterior no cambió y sigue funcionando. ¿Iniciar {0} de nuevo con él?", + "Обновление не завершилось. Прежний движок не изменён и работает. Запустить {0} снова на нём?", + "A atualização não terminou. O seu motor anterior não foi alterado e continua a funcionar. Iniciar {0} de novo com ele?", + "업데이트가 끝나지 않았습니다. 기존 엔진은 그대로이며 계속 작동합니다. 기존 엔진으로 {0}을(를) 다시 시작할까요?", + "La mise à jour ne s'est pas terminée. Votre ancien moteur est inchangé et fonctionne toujours. Redémarrer {0} avec lui ?") +add("Not now", "暂不", "今はしない", "Jetzt nicht", "Ahora no", "Не сейчас", "Agora não", "나중에", "Pas maintenant") +add("Starting {0}. Loading can take a few minutes.", + "正在启动 {0}。加载可能需要几分钟。", + "{0} を起動しています。読み込みには数分かかることがあります。", + "{0} wird gestartet. Das Laden kann einige Minuten dauern.", + "Iniciando {0}. La carga puede tardar unos minutos.", + "Запускаем {0}. Загрузка может занять несколько минут.", + "A iniciar {0}. O carregamento pode demorar alguns minutos.", + "{0}을(를) 시작하는 중입니다. 불러오는 데 몇 분이 걸릴 수 있습니다.", + "Démarrage de {0}. Le chargement peut prendre quelques minutes.") +add("Starting {0} again", "正在再次启动 {0}", "{0} をもう一度起動しています", "{0} wird wieder gestartet", "Iniciando {0} de nuevo", "Снова запускаем {0}", "A iniciar {0} de novo", "{0}을(를) 다시 시작하는 중", "Redémarrage de {0}") +add("The model did not start again", "模型没有重新启动", "モデルを再起動できませんでした", "Das Modell wurde nicht wieder gestartet", "El modelo no se inició de nuevo", "Модель не запустилась снова", "O modelo não voltou a iniciar", "모델이 다시 시작되지 않았습니다", "Le modèle n'a pas redémarré") +add("You can load it again from Models.", "你可以在“模型”中再次加载它。", "「モデル」からもう一度読み込めます。", "Sie können es unter „Modelle“ erneut laden.", "Puedes cargarlo de nuevo desde Modelos.", "Вы можете загрузить её снова в разделе «Модели».", "Pode carregá-lo de novo em Modelos.", "모델 화면에서 다시 불러올 수 있습니다.", "Vous pouvez le recharger depuis Modèles.") +add("A model that was not started from this app is running, so nothing was changed. Stop it, then update the engine again.", + "有一个不是从此应用启动的模型正在运行,因此没有做任何更改。请先停止它,然后再次更新引擎。", + "このアプリから起動していないモデルが動作しているため、何も変更していません。それを停止してから、もう一度エンジンを更新してください。", + "Ein Modell, das nicht aus dieser App gestartet wurde, läuft noch, daher wurde nichts geändert. Halten Sie es an und aktualisieren Sie die Engine dann erneut.", + "Hay un modelo en ejecución que no se inició desde esta aplicación, así que no se cambió nada. Deténlo y vuelve a actualizar el motor.", + "Работает модель, запущенная не из этого приложения, поэтому ничего не изменено. Остановите её и обновите движок снова.", + "Está em execução um modelo que não foi iniciado a partir desta aplicação, por isso nada foi alterado. Pare-o e atualize o motor de novo.", + "이 앱에서 시작하지 않은 모델이 실행 중이어서 아무것도 변경하지 않았습니다. 그 모델을 중지한 다음 엔진을 다시 업데이트하세요.", + "Un modèle qui n'a pas été démarré depuis cette application est en cours d'exécution, rien n'a donc été modifié. Arrêtez-le, puis mettez à nouveau le moteur à jour.") + +here = Path(__file__).resolve().parent.parent / "src" / "locales" +NBSP = " " + + +def french(text): + text = re.sub(r"(?<=[A-Za-zÀ-ſ])'(?=[A-Za-zÀ-ſ{])", "’", text) + text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text) + return text + + +for lang in LANGS: + data = {} + for i, entry in enumerate(S): + text = entry[lang] + assert sorted(re.findall(r"\{\d+\}", entry["en"])) == sorted(re.findall(r"\{\d+\}", text)), (lang, entry["en"], text) + data[f"upd{i + 1:02d}"] = french(text) if lang == "fr" else text + with (here / f"upd-{lang}.json").open("w", encoding="utf-8", newline="\n") as handle: + handle.write(json.dumps(data, ensure_ascii=False, indent=1) + "\n") +print("written", len(S), "strings in", len(LANGS), "languages") diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index 064fa8fd55..be69b70bb8 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -185,9 +185,9 @@ export function createControl({ control = findControl(), env = process.env, run if (result.json?.ok) return result.json; throw failure(result, 'The update check failed.'); }, - async update({ feed = env.STRATA_UPDATE_FEED ?? null, engine = true, control: withControl = true, appVersion = env.STRATA_APP_VERSION ?? null, force = false, onEvent = null, signal = null } = {}) { + async update({ feed = env.STRATA_UPDATE_FEED ?? null, engine = true, control: withControl = true, appVersion = env.STRATA_APP_VERSION ?? null, force = false, stopModel = false, onEvent = null, signal = null } = {}) { const args = ['update', '--output', 'jsonl', ...feedArgs(feed), ...(engine ? [] : ['--no-engine']), ...(withControl ? [] : ['--no-control']), - ...(appVersion ? ['--app-version', appVersion] : []), ...(force ? ['--force'] : [])]; + ...(appVersion ? ['--app-version', appVersion] : []), ...(force ? ['--force'] : []), ...(stopModel ? ['--stop-model'] : [])]; const result = await call(args, { timeoutMs: 3 * 3600_000, acquire: true, onLine: onEvent ?? (() => {}), signal }); if (result.json?.ok) return result.json; const failed = result.json?.results?.find?.(r => r.status === 'failed'); diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index b948969066..55259f03dc 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -1011,6 +1011,7 @@ async function api(req, res, path, method, url) { if(path==='/api/native/models-folder/leave'&&method==='POST')return json(res,200,await native.leaveInterruptedMove()); if(path==='/api/native/plan'&&method==='POST')return json(res,200,await native.plan(await readBody(req))); if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));} + if(path==='/api/native/engine-restart/dismiss'&&method==='POST')return json(res,200,native.dismissRestart()); if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()}); if(path==='/api/native/logs/save'&&method==='POST'){ /* Diagnostics to a file: the engine messages the app kept, failed operations, and the tail of each model's server log under Control. diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index fe9f16a74d..b1cb08636e 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -63,13 +63,15 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp const updateLog=line=>{try{console.log(`update · ${line}`);}catch{/* no console */}}; const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.'; let defaultId=null,timer=null,closing=false,polling=false; + /* Models the engine update stopped (with the person's yes): kept so the app can offer to start them again with the same settings. */ + let stoppedForUpdate=null; const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; function diskSpace(path){try{const s=statfsSync(path);return {free:Number(s.bavail)*Number(s.bsize),total:Number(s.blocks)*Number(s.bsize)};}catch{return null;}} /* Does the engine in this release serve DFlash2? Control knows (strata_control/drafting.py); asked once, false until it answers. The Models screen offers the choice only when true. */ let dflash2Served=null,dflash2Support=null; function probeDrafting(){if(!packaged||dflash2Served!==null||typeof control.draftingPlan!=='function')return;dflash2Served=false;control.draftingPlan({mode:'auto'}).then(p=>{dflash2Served=p.serves===true;dflash2Support=p.serves===true&&p.support&&p.support_line?{level:p.support,line:p.support_line}:null;emit();}).catch(()=>{});} - function state(){const folder=preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),space=folder?diskSpace(folder):null;return {...snapshot,downloadDirectory:folder,downloadFreeBytes:space?.free??null,downloadTotalBytes:space?.total??null,fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false,dflash2:dflash2Served===true,dflash2Support}};} + function state(){const folder=preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),space=folder?diskSpace(folder):null;return {...snapshot,downloadDirectory:folder,downloadFreeBytes:space?.free??null,downloadTotalBytes:space?.total??null,fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,stoppedForUpdate:stoppedForUpdate?{updated:stoppedForUpdate.updated,at:stoppedForUpdate.at,models:stoppedForUpdate.instances.map(i=>({id:i.id,label:i.label}))}:null,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false,dflash2:dflash2Served===true,dflash2Support}};} let sourceCache={path:'',time:0,text:''}; function sourceText(){try{const path=join(packaged?control.control.dir:preferences.repo,'serve/server.py'),time=statSync(path).mtimeMs;if(sourceCache.path===path&&sourceCache.time===time)return sourceCache.text;sourceCache={path,time,text:readFileSync(path,'utf8')};return sourceCache.text;}catch{return '';}} function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:APP_OWNED_FIELDS.includes(field.id)||field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} @@ -419,7 +421,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} shell's signed Tauri updater. Models are not part of any of it. */ async function componentProgram(job,args={}){ if(!COMPONENT_KINDS.includes(job.kind)||typeof control.update!=='function')throw new Error(NO_INSTALL); - if(instances.size)throw new Error('Unload native models before changing engine files.'); + if(instances.size&&!(job.kind==='update-engine'&&args.stopModel===true))throw new Error('Unload native models before changing engine files.'); job.abort=new AbortController(); const subject=job.kind==='update-strata'?'Strata':'engine'; try{return await componentSteps(job,subject,args);}catch(error){updateLog(`${job.kind} failed: ${String(error?.message??error).slice(0,400)}`);throw error?.details!==undefined&&error.message?error:plainError(error,subject,args?.firstRun===true?'Continue':undefined);} @@ -434,7 +436,13 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} updateLog(`${job.kind} started (app ${thisAppVersion()??'unknown'})`); if(job.kind==='install-engine-file'){if(typeof args.path!=='string'||!args.path)throw new Error('Choose the engine file first.');let done;try{done=await control.installEngineFile(args.path,{onEvent,signal:job.abort.signal});}finally{try{const own=resolve(directory,'incoming-engine')+sep;if(resolve(args.path).startsWith(own))rmSync(args.path,{force:true});}catch{/* the copy in the host's own folder; a leftover is harmless */}}return {summary:updateSummary(done)==='Everything is already up to date.'?(done.results?.[0]?.note??'Nothing was changed.'):updateSummary(done),result:done};} if(job.kind==='rollback'){const done=await control.rollbackEngine();return {summary:'The previous engine is back. Your models and settings are unchanged.',result:done};} - if(job.kind==='update-engine'){const done=await control.update({engine:true,control:false,onEvent,signal:job.abort.signal});return {summary:updateSummary(done),result:done};} + if(job.kind==='update-engine'){ + /* A model is loaded and the person said yes to stopping it (the dialog names it): Control downloads while it serves, stops it cleanly, updates, and leaves it stopped. + Whatever the result, the models it stopped are kept so the app offers to start them again, on the new engine or, after a failed update, on the old one. */ + const gate=args.stopModel===true&&instances.size?updateGate(job):null; + try{const done=await control.update({engine:true,control:false,stopModel:!!gate,onEvent:gate?e=>{onEvent(e);gate.event(e);}:onEvent,signal:job.abort.signal});gate?.finish(true);return {summary:updateSummary(done),result:done};} + catch(error){gate?.finish(false);if(gate?.refusal)throw Object.assign(new Error(gate.refusal),{details:`Running outside this app: ${gate.outside.join(', ')}`});throw error;} + } const done=await control.update({engine:false,control:true,onEvent,signal:job.abort.signal}); updateLog(`Control step finished: ${updateSummary(done)}`); const notes=[updateSummary(done)]; @@ -447,6 +455,46 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} } return {summary:notes.filter(Boolean).join(' '),result:done}; } + /* The engine update with a model loaded (strata update --stop-model --output jsonl). The `models` events say what Control is doing to the models; this turns them into the app's own + state: the model leaves the list when it is stopped, and a model the app did not start is never stopped (the update is ended before anything is downloaded). */ + function updateGate(job){ + const mine=new Map([...instances.values()].filter(i=>i.profile).map(i=>[i.profile,i])),stopped=[],gate={refusal:null,event(e){ + if(e.event!=='models')return; + const models=Array.isArray(e.models)?e.models:[],label=m=>mine.get(m.profile)?.label??m.name??'The model'; + if(e.phase==='consent'){ + const other=models.filter(m=>!mine.has(m.profile)); + if(other.length){gate.refusal='A model that was not started from this app is running, so nothing was changed. Stop it, then update the engine again.';gate.outside=other.map(label);job.abort.abort();return;} + job.step='getting-ready';job.models=models.map(label);job.summary=`Getting the new engine ready. ${job.models.join(' and ')} keeps running until it is ready.`; + } + else if(e.phase==='stopping'){for(const m of models){const i=mine.get(m.profile);if(i)i.status='unloading';}job.step='stopping';job.models=models.map(label);job.summary=`Stopping ${job.models.join(' and ')}. Answers in progress finish first.`;} + else if(e.phase==='stopped'){for(const m of models){const i=mine.get(m.profile);if(i&&instances.get(i.id)===i){instances.delete(i.id);stopped.push(i);if(defaultId===i.id)defaultId=instances.keys().next().value??null;}}job.step='stopped';job.models=models.map(label);job.summary=`${job.models.join(' and ')} stopped. Updating the engine…`;} + emit(); + },finish(updated){stoppedForUpdate=stopped.length?{updated,at:new Date().toISOString(),instances:stopped}:null;emit();}}; + return gate; + } + /* "Start again with the same settings": the stopped model's saved profile (the run file it was started with) is started again; the engine in use is whichever Control has primary now. */ + async function restartStopped(job){ + const offer=stoppedForUpdate;if(!offer?.instances?.length)throw new Error('There is no stopped model to start again.'); + stoppedForUpdate=null;emit(); + const labels=[]; + for(const old of offer.instances){ + const instance={...old,status:'loading',phase:'loading',error:null,metrics:null,loadedAt:new Date().toISOString()}; + instances.set(instance.id,instance);if(!defaultId||!instances.has(defaultId))defaultId=instance.id;job.summary=`Starting ${instance.label}. Loading can take a few minutes.`;emit(); + let wait=960;try{const {config,entry}=record(instance.model);wait=startWaitFor(config,entry,instance.model);}catch{/* the usual wait */} + try{ + await control.start(instance.profile,{waitSeconds:wait}); + const deadline=Date.now()+300000;let ready=false; + while(!ready&&Date.now()<deadline&&job.state==='running'){try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(2000)});ready=response.ok;}catch{/* not yet */}if(!ready)await new Promise(resolve=>setTimeout(resolve,1200));} + if(!ready)throw new Error('Loading took more than five minutes. Check the engine log and free memory.'); + instance.status='ready';instance.phase='idle';ensurePoll();emit();labels.push(instance.label); + }catch(error){ + await control.stop(instance.profile).catch(()=>{}); + instance.status='error';instance.error=humanStartError(error);emit();throw new Error(`${instance.label} did not start again. ${instance.error}`); + } + } + return {summary:`${labels.join(' and ')} ${labels.length>1?'are':'is'} running again with the same settings.`}; + } + function dismissRestart(){stoppedForUpdate=null;emit();return state();} function updateSummary(done){const r=(done.results??[]).filter(x=>x.status==='updated').map(x=>x.component==='engine'||x.component==='dsv41'?'The engine is updated and ready.':'Strata is updated. It takes effect the next time you open the app.');return r.length?r.join(' '):'Everything is already up to date.';} function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});} /* Every write of a model's run config keeps the person's options: those they wrote into "args" or "user_args" since the file was last written are read from the file itself, go over what the caller built, and "args_written" is refreshed. */ @@ -492,7 +540,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} const room=args.resourceProfile==='work'; return autotuner.start(job,job.kind==='recheck'?'recheck':'tune',{configPath:path,presetId:args.presetId,mode:args.mode,use:args.use,goal:room?'room':'speed',leaveRam:room?20:0,allowSmallDifferences:args.allowSmallDifferences===true,name:args.name},{onProgress:p=>{job.summary=p.text??job.summary;emit();}}); } - function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','install-engine-file','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available&&!(packaged&&COMPONENT_KINDS.includes(kind)))throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});} + function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','install-engine-file','remove','restart-models'].includes(kind))throw new Error('Choose a supported native operation.');if(kind==='restart-models'&&!packaged)throw new Error('Choose a supported native operation.');if(!snapshot.available&&!(packaged&&(COMPONENT_KINDS.includes(kind)||kind==='restart-models')))throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):kind==='restart-models'?restartStopped(job):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});} /* ---- The models folder card (0.2.2): what a picked folder means, and the three choices. The copying is Control's (strata models move). ---- */ const currentModelsFolder=()=>preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder)??null; const moveFile=()=>join(directory,'models-move.cancel'); @@ -592,7 +640,7 @@ 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,planModelsFolder,startModelsFolder,interruptedMove,finishInterruptedMove,leaveInterruptedMove,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'),defaultInstanceId:()=>defaultId,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,planModelsFolder,startModelsFolder,interruptedMove,finishInterruptedMove,leaveInterruptedMove,plan,settings,save,settingsFile,openSettingsFile,operation,dismissRestart,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'),defaultInstanceId:()=>defaultId,close}; } /* A DeepSeek config on AMD written by setup 0.2.8 or earlier names ONE card and marks it "asked", though setup picked it itself (strata_control/gpu_pick.py): it must not stop the app's recommended cards from applying. A card setup named for itself is the first of the usable cards, largest memory first; another card number was the person's. Roles and a "gpus_by" marker are always honoured. */ export function setupPickedOneCard(config,hardware){ diff --git a/apps/host/src/components/EngineUpdateDialog.tsx b/apps/host/src/components/EngineUpdateDialog.tsx new file mode 100644 index 0000000000..a84dfb928f --- /dev/null +++ b/apps/host/src/components/EngineUpdateDialog.tsx @@ -0,0 +1,130 @@ +import { useEffect, useState } from 'react'; +import { localeTag, tr } from '../lib/i18n'; +import { Bar, Btn, Dialog } from './ui'; +import { nativeAction, useNative, type NativeJob } from '../lib/native'; + +/** "A", "A and B", "A, B and C" in the language of the app. */ +const listOf = (names: string[]) => { + try { return new Intl.ListFormat(localeTag(), { style: 'long', type: 'conjunction' }).format(names); } catch { return names.join(', '); } +}; + +/** + * Update engine with a model loaded (Settings > About). Strata Control does the work (`strata update --stop-model --output jsonl`, through the host); this is the + * conversation around it, in four plain steps: + * 1. Warn, naming the model, and ask. Nothing happens before the yes. With no model loaded the older dialog of Settings is used instead. + * 2. Progress in words: the new engine downloads while the model keeps working; then the model stops; then the engine is updated. + * 3. Offer to start the model again with the same settings. Never automatic. + * 4. A failed update leaves the old engine as it was and offers to start the model again on it. + * The dialog follows the host's state, so it also shows the offer when the update finished while Settings was closed. + */ +export function EngineUpdateDialog({ open, onClose }: { open: boolean; onClose: () => void }) { + const native = useNative(); + const [jobId, setJobId] = useState(''); + const [restartId, setRestartId] = useState(''); + const [error, setError] = useState(''); + const [hidden, setHidden] = useState(false); + const loaded = native?.instances ?? []; + const offer = native?.stoppedForUpdate ?? null; + const job: NativeJob | undefined = native?.jobs.find(j => j.id === jobId); + const restart: NativeJob | undefined = native?.jobs.find(j => j.id === restartId); + const offerKey = offer?.at ?? ''; + useEffect(() => { setHidden(false); }, [offerKey]); + + const restarting = restart?.state === 'running'; + const updating = job?.state === 'running'; + const names = listOf(offer?.models.map(m => m.label) ?? loaded.map(i => i.label)); + const showOffer = !!offer && !hidden && !updating && !restarting; + const failedRestart = restart?.state === 'error' && !offer ? restart : undefined; + const ended = job?.state === 'done' || job?.state === 'error'; + const visible = open || updating || restarting || showOffer || !!failedRestart || ended; + if (!visible) return null; + + async function start() { + setError(''); + try { + const started = await nativeAction<NativeJob>('operations', { kind: 'update-engine', args: { stopModel: true } }); + setJobId(started.id); + onClose(); // the dialog now follows the job; the caller's "open" is spent + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } + } + async function startAgain() { + setError(''); + try { + const started = await nativeAction<NativeJob>('operations', { kind: 'restart-models' }); + setRestartId(started.id); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } + } + async function notNow() { + setHidden(true); + try { await nativeAction('engine-restart/dismiss'); } catch { /* the offer stays hidden here either way */ } + setJobId(''); + onClose(); + } + function close() { + if (showOffer) { void notNow(); return; } + if (failedRestart) setRestartId(''); + onClose(); + } + + const percent = Number(job?.result?.install?.download?.percent); + const details = (j: NativeJob) => j.details ? <details className="native-settings-diagnostic"><summary className="small">{tr("Details")}</summary><p className="small muted">{j.details}</p></details> : null; + + // 3 and 4: the model was stopped for the update. + if (showOffer && offer) { + const done = offer.updated; + return <Dialog open compact title={tr(done ? 'The engine is updated' : "The engine was not updated")} onClose={close} + actions={<><Btn onClick={() => void notNow()}>{tr("Not now")}</Btn><Btn variant="primary" onClick={() => void startAgain()}>{tr("Start again")}</Btn></>}> + <p>{done ? tr("The engine is updated. Start {0} again with the same settings?", [names]) : tr("The update didn't finish. Your old engine is unchanged and still works. Start {0} again on it?", [names])}</p> + {!done && job?.error ? <p className="small muted">{tr(job.error)}</p> : null} + {!done && job ? details(job) : null} + {error ? <p className="small inline-error" role="alert">{tr(error)}</p> : null} + </Dialog>; + } + // The model is starting again. + if (restarting) { + return <Dialog open compact title={tr("Starting {0} again", [names])} onClose={onClose}> + <p role="status">{tr("Starting {0}. Loading can take a few minutes.", [names])}</p> + <Bar value={0} indeterminate label={tr("Starting {0} again", [names])}/> + </Dialog>; + } + if (failedRestart) { + return <Dialog open compact title={tr("The model did not start again")} onClose={close} actions={<Btn variant="primary" onClick={close}>{tr("Close")}</Btn>}> + <p>{tr("You can load it again from Models.")}</p> + {failedRestart.error ? <p className="small muted">{failedRestart.error}</p> : null} + </Dialog>; + } + // 2: the update is running. + if (updating && job) { + const step = job.step, label = listOf(job.models ?? loaded.map(i => i.label)); + return <Dialog open compact title={tr("Updating the engine")} onClose={onClose}> + <p role="status" aria-live="polite">{step === 'stopping' ? tr("Stopping {0}. Answers in progress finish first.", [label]) + : step === 'stopped' ? tr("{0} is stopped. Updating the engine…", [label]) + : step === 'getting-ready' ? tr("Getting the new engine ready. {0} keeps working until it is ready.", [label]) + : tr(job.summary || 'Starting…')}</p> + {step === 'getting-ready' && Number.isFinite(percent) ? <Bar value={percent} label={tr("Downloading…")}/> : <Bar value={0} indeterminate label={tr("Updating the engine")}/>} + </Dialog>; + } + // The update ended without stopping anything (declined, refused, or failed before the model was touched). + if (job?.state === 'error') { + return <Dialog open compact title={tr("The engine was not updated")} onClose={() => { setJobId(''); onClose(); }} actions={<Btn variant="primary" onClick={() => { setJobId(''); onClose(); }}>{tr("Close")}</Btn>}> + <p>{tr(job.error ?? job.summary)}</p> + {details(job)} + </Dialog>; + } + if (job?.state === 'done') { + return <Dialog open compact title={tr("The engine is updated")} onClose={() => { setJobId(''); onClose(); }} actions={<Btn variant="primary" onClick={() => { setJobId(''); onClose(); }}>{tr("Close")}</Btn>}> + <p>{tr(job.summary)}</p> + </Dialog>; + } + // 1: warn and ask. + return <Dialog open compact title={tr("Update engine?")} onClose={close} + actions={<><Btn onClick={close}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!loaded.length} onClick={() => void start()}>{tr("Stop and update")}</Btn></>}> + <p>{tr("To update the engine, Strata has to stop the model that is loaded: {0}.", [names])}</p> + <p className="small muted">{tr("The new engine downloads first while the model keeps answering. Then the model stops (answers in progress finish first), the engine is updated, and you can start the model again with the same settings. Your models and settings are kept.")}</p> + {error ? <p className="small inline-error" role="alert">{tr(error)}</p> : null} + </Dialog>; +} diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index a7cd9892d9..9de8f06cdd 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -14,6 +14,7 @@ import { DownloadParts } from './DownloadParts'; import { useElapsed } from '../lib/use-elapsed'; import { EngineWarning } from './EngineWarning'; import { EngineUpdateCard } from './EngineUpdateCard'; +import { EngineUpdateDialog } from './EngineUpdateDialog'; import { duration, sizeGb } from '../lib/format'; import { NativeDeleteDialog } from './NativeDelete'; import { plainFailureText } from '../lib/plain-errors'; @@ -223,6 +224,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine </> : null)} <EngineWarning native={native}/> <EngineUpdateCard native={native} busy={!!active}/> + <EngineUpdateDialog open={false} onClose={() => {}}/> {tr(active ? <NativeProgress job={active} label={jobLabel(active)}/> : null)} {tr(active ? <p className="small muted native-wait-note">{tr("The buttons below wait until this finishes.")}</p> : null)} {tr(job?.state === 'error' ? <ErrorNotice message={job.error ?? job.summary} action={tr("Retry")} onRetry={() => void load()}/> : null)} diff --git a/apps/host/src/components/SettingsUpdates.tsx b/apps/host/src/components/SettingsUpdates.tsx index cfcfca2997..2d9843b051 100644 --- a/apps/host/src/components/SettingsUpdates.tsx +++ b/apps/host/src/components/SettingsUpdates.tsx @@ -6,6 +6,7 @@ import { useStore } from '../lib/store'; import type { SoftwareUpdate, UpdateCheckResult } from '../lib/types'; import { nativeAction, useNative } from '../lib/native'; import { NativeProgress } from './NativeModels'; +import { EngineUpdateDialog } from './EngineUpdateDialog'; import { jobErrorText } from '../lib/native-job-diagnostics'; import { appVersionLabel } from '../lib/app-version'; import { fetchUpdateCheck, publishUpdateCheck, useInstalledVersions, useLastUpdateCheck } from '../lib/update-check'; @@ -31,6 +32,8 @@ export function SettingsUpdates() { useEffect(() => () => request.current?.abort(), []); const active = native?.jobs.find(j => j.state === 'running'); const result = checking || error ? null : (fresh ?? last); + // Update engine with a model loaded: its own dialog (warns naming the model, stops it with the person's yes, offers to start it again). + const withModel = (native?.instances.length ?? 0) > 0 && !!native?.capabilities.componentUpdates; async function operate(kind: string) { setError(''); try { @@ -80,7 +83,8 @@ export function SettingsUpdates() { <div className="settings-update-inline" role="status" aria-live="polite">{tr(checking ? 'Checking for new versions…' : error ? <span className="inline-error">{tr(error)}</span> : result ? <><span className="sr-only">{tr(result.strata.message)} {tr(result.engine.message)} </span>{tr("Checked at ")}{tr(checkedLabel(result.checkedAt))}</> : null)}</div> </div> {tr(active ? <NativeProgress job={active}/> : null)}{tr(native?.jobs.filter(j => j.state === 'error' && ['update-strata', 'update-engine'].includes(j.kind)).slice(-1).map(j => <p role="alert" key={j.id} className="small inline-error">{tr(jobErrorText(j, native.jobs))}</p>))} - <Dialog open={!!confirm} compact title={tr(confirm === 'update-strata' ? 'Update Strata?' : 'Update engine?')} onClose={() => setConfirm('')} actions={<><Btn onClick={() => setConfirm('')}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!!active || (native?.instances.length ?? 0) > 0} onClick={() => void operate(confirm)}>{tr("Update")}</Btn></>}><p>{tr("The native installer updates the installation. Model files and settings are kept. Unload native models before updating.")}</p>{tr((native?.instances.length ?? 0) > 0 ? <p className="small muted">{tr("Open Models and unload the running native models first.")}</p> : null)}</Dialog> + <EngineUpdateDialog open={confirm === 'update-engine' && withModel} onClose={() => setConfirm('')}/> + <Dialog open={!!confirm && !(confirm === 'update-engine' && withModel)} compact title={tr(confirm === 'update-strata' ? 'Update Strata?' : 'Update engine?')} onClose={() => setConfirm('')} actions={<><Btn onClick={() => setConfirm('')}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!!active || (native?.instances.length ?? 0) > 0} onClick={() => void operate(confirm)}>{tr("Update")}</Btn></>}><p>{tr("The native installer updates the installation. Model files and settings are kept. Unload native models before updating.")}</p>{tr((native?.instances.length ?? 0) > 0 ? <p className="small muted">{tr("Open Models and unload the running native models first.")}</p> : null)}</Dialog> </>; } diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index c888cb0372..edc2c9c7c0 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -76,6 +76,16 @@ import df2_ru from '../locales/df2-ru.json'; import df2_pt from '../locales/df2-pt.json'; import df2_ko from '../locales/df2-ko.json'; import df2_fr from '../locales/df2-fr.json'; +/* The strings of the engine update beside a loaded model (upd-<lang>.json, scripts/make-update-locales.py). */ +import upd_en from '../locales/upd-en.json'; +import upd_zh from '../locales/upd-zh.json'; +import upd_ja from '../locales/upd-ja.json'; +import upd_de from '../locales/upd-de.json'; +import upd_es from '../locales/upd-es.json'; +import upd_ru from '../locales/upd-ru.json'; +import upd_pt from '../locales/upd-pt.json'; +import upd_ko from '../locales/upd-ko.json'; +import upd_fr from '../locales/upd-fr.json'; import base_zh from '../locales/zh.json'; import base_ja from '../locales/ja.json'; import base_de from '../locales/de.json'; @@ -90,8 +100,8 @@ export type Language=typeof LANGUAGES[number]['value']; /* The Tune model dialog's strings live in tune-<lang>.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ /* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-<lang>.json for the same reason. */ /* The strings that had no key in the files above (#3479, #3825) and the 0.2.4.3 fixes live in fix-<lang>.json (scripts/make-fix-locales.py). */ -const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en,...pick_en,...df2_en}; -const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh,...ui_zh,...engine_zh,...pick_zh,...df2_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja,...ui_ja,...engine_ja,...pick_ja,...df2_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de,...ui_de,...engine_de,...pick_de,...df2_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es,...ui_es,...engine_es,...pick_es,...df2_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru,...ui_ru,...engine_ru,...pick_ru,...df2_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt,...ui_pt,...engine_pt,...pick_pt,...df2_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko,...ui_ko,...engine_ko,...pick_ko,...df2_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr,...gh_fr,...ui_fr,...engine_fr,...pick_fr,...df2_fr}] as Record<string,string>[]; +const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en,...pick_en,...df2_en,...upd_en}; +const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh,...ui_zh,...engine_zh,...pick_zh,...df2_zh,...upd_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja,...ui_ja,...engine_ja,...pick_ja,...df2_ja,...upd_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de,...ui_de,...engine_de,...pick_de,...df2_de,...upd_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es,...ui_es,...engine_es,...pick_es,...df2_es,...upd_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru,...ui_ru,...engine_ru,...pick_ru,...df2_ru,...upd_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt,...ui_pt,...engine_pt,...pick_pt,...df2_pt,...upd_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko,...ui_ko,...engine_ko,...pick_ko,...df2_ko,...upd_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr,...gh_fr,...ui_fr,...engine_fr,...pick_fr,...df2_fr,...upd_fr}] as Record<string,string>[]; const catalogs:Record<Language,Record<string,string>>={en:english,zh,ja,de,fr,es,ru,pt,ko}; const entities:Record<string,string>={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'}; const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole); diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index 539c516512..038607a888 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -6,13 +6,13 @@ export interface GpuChoice {options:GpuChoiceOption[];recommended:string|null;ig export interface NativeSize {/** The first engine that reads this size's files (the catalog), and whether the installed engine is older: the screen then says "needs a newer engine" and offers the update. */engine_min?:string|null;needsNewerEngine?:boolean;id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean;gpu_options?:GpuChoice|null;images?:boolean;imagesCapable?:boolean;/** DeepSeek-V4.1-Flash and the like: several big files and an engine of their own. */multi_file?:boolean;/** DeepSeek: the free disk the set needs (its download plus the pack and room to work), from the set itself. */disk_gb?:number} export interface NativeFamily {family:string;title:string;about:string;experimental:boolean;images:boolean;sizes:NativeSize[]} export interface NativeField {id:string;label:string;group:string;/** Not shown for a model whose id contains this (DeepSeek has no MTP). */notForModel?:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean;forModel?:string} -export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;family?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;result:Record<string,any>|null;progress?:Record<string,any>|null} +export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;family?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;result:Record<string,any>|null;progress?:Record<string,any>|null;/** An engine update beside a loaded model: which step it is on and the models it concerns (the app words these itself). */step?:'getting-ready'|'stopping'|'stopped';models?:string[]} export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;resourceProfile?:'work'|'performance'|null;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record<string,any>|null} export interface NativeState { /** The picture reader (strata-vision) is installed with the engine, so models marked for pictures can read them here. */ /** Strata Control's view of the engine for this computer (the app): usable false = none found or recognised; `notice` says why in plain words. */ engine?:{usable:boolean;notice?:string|null;wrongMake?:boolean;version?:string|null;/** What the last update check found newer (kept on this PC, read without the network): the Qwen engine, the DeepSeek engine, the app. */updateAvailable?:{engine?:string|null;dsv41?:string|null;app?:string|null}|null}; - 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;/** DeepSeek: the most context its pack reads (max_position_embeddings in the pack's ds4.txt); absent when the pack does not say. */contextMax?:number;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<string,{bytes:number;gb:number}>}|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;/** What was measured on this kind of card, in Control's words (null until Control answers). */dflash2Support?:{level:'tested'|'slower'|'untested';line:string}|null;responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}} + 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;/** DeepSeek: the most context its pack reads (max_position_embeddings in the pack's ds4.txt); absent when the pack does not say. */contextMax?:number;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<string,{bytes:number;gb:number}>}|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;/** Models an engine update stopped, to offer starting them again with the same settings (updated: false = the update did not finish, the old engine is unchanged). */stoppedForUpdate?:{updated:boolean;at:string;models:{id:string;label:string}[]}|null;jobs:NativeJob[];capabilities:{/** The engine serves DFlash2 (Control says): the Drafting choice then offers it. */dflash2?:boolean;/** What was measured on this kind of card, in Control's words (null until Control answers). */dflash2Support?:{level:'tested'|'slower'|'untested';line:string}|null;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). */ diff --git a/apps/host/src/locales/upd-de.json b/apps/host/src/locales/upd-de.json new file mode 100644 index 0000000000..79ebb8af0e --- /dev/null +++ b/apps/host/src/locales/upd-de.json @@ -0,0 +1,19 @@ +{ + "upd01": "Um die Engine zu aktualisieren, muss Strata das geladene Modell anhalten: {0}.", + "upd02": "Zuerst wird die neue Engine heruntergeladen, während das Modell weiter antwortet. Danach hält das Modell an (laufende Antworten werden zuerst beendet), die Engine wird aktualisiert, und Sie können das Modell mit denselben Einstellungen wieder starten. Ihre Modelle und Einstellungen bleiben erhalten.", + "upd03": "Anhalten und aktualisieren", + "upd04": "Die neue Engine wird vorbereitet. {0} arbeitet weiter, bis sie bereit ist.", + "upd05": "{0} wird angehalten. Laufende Antworten werden zuerst beendet.", + "upd06": "{0} ist angehalten. Die Engine wird aktualisiert…", + "upd07": "Engine wird aktualisiert", + "upd08": "Die Engine ist aktualisiert", + "upd09": "Die Engine wurde nicht aktualisiert", + "upd10": "Die Engine ist aktualisiert. {0} mit denselben Einstellungen wieder starten?", + "upd11": "Die Aktualisierung wurde nicht abgeschlossen. Ihre alte Engine ist unverändert und funktioniert weiter. {0} damit wieder starten?", + "upd12": "Jetzt nicht", + "upd13": "{0} wird gestartet. Das Laden kann einige Minuten dauern.", + "upd14": "{0} wird wieder gestartet", + "upd15": "Das Modell wurde nicht wieder gestartet", + "upd16": "Sie können es unter „Modelle“ erneut laden.", + "upd17": "Ein Modell, das nicht aus dieser App gestartet wurde, läuft noch, daher wurde nichts geändert. Halten Sie es an und aktualisieren Sie die Engine dann erneut." +} diff --git a/apps/host/src/locales/upd-en.json b/apps/host/src/locales/upd-en.json new file mode 100644 index 0000000000..7145400e3c --- /dev/null +++ b/apps/host/src/locales/upd-en.json @@ -0,0 +1,19 @@ +{ + "upd01": "To update the engine, Strata has to stop the model that is loaded: {0}.", + "upd02": "The new engine downloads first while the model keeps answering. Then the model stops (answers in progress finish first), the engine is updated, and you can start the model again with the same settings. Your models and settings are kept.", + "upd03": "Stop and update", + "upd04": "Getting the new engine ready. {0} keeps working until it is ready.", + "upd05": "Stopping {0}. Answers in progress finish first.", + "upd06": "{0} is stopped. Updating the engine…", + "upd07": "Updating the engine", + "upd08": "The engine is updated", + "upd09": "The engine was not updated", + "upd10": "The engine is updated. Start {0} again with the same settings?", + "upd11": "The update didn't finish. Your old engine is unchanged and still works. Start {0} again on it?", + "upd12": "Not now", + "upd13": "Starting {0}. Loading can take a few minutes.", + "upd14": "Starting {0} again", + "upd15": "The model did not start again", + "upd16": "You can load it again from Models.", + "upd17": "A model that was not started from this app is running, so nothing was changed. Stop it, then update the engine again." +} diff --git a/apps/host/src/locales/upd-es.json b/apps/host/src/locales/upd-es.json new file mode 100644 index 0000000000..51890559be --- /dev/null +++ b/apps/host/src/locales/upd-es.json @@ -0,0 +1,19 @@ +{ + "upd01": "Para actualizar el motor, Strata tiene que detener el modelo cargado: {0}.", + "upd02": "Primero se descarga el motor nuevo mientras el modelo sigue respondiendo. Después el modelo se detiene (las respuestas en curso terminan antes), se actualiza el motor y puedes volver a iniciar el modelo con los mismos ajustes. Tus modelos y ajustes se conservan.", + "upd03": "Detener y actualizar", + "upd04": "Preparando el motor nuevo. {0} sigue funcionando hasta que esté listo.", + "upd05": "Deteniendo {0}. Las respuestas en curso terminan antes.", + "upd06": "{0} está detenido. Actualizando el motor…", + "upd07": "Actualizando el motor", + "upd08": "El motor está actualizado", + "upd09": "El motor no se actualizó", + "upd10": "El motor está actualizado. ¿Iniciar {0} de nuevo con los mismos ajustes?", + "upd11": "La actualización no terminó. Tu motor anterior no cambió y sigue funcionando. ¿Iniciar {0} de nuevo con él?", + "upd12": "Ahora no", + "upd13": "Iniciando {0}. La carga puede tardar unos minutos.", + "upd14": "Iniciando {0} de nuevo", + "upd15": "El modelo no se inició de nuevo", + "upd16": "Puedes cargarlo de nuevo desde Modelos.", + "upd17": "Hay un modelo en ejecución que no se inició desde esta aplicación, así que no se cambió nada. Deténlo y vuelve a actualizar el motor." +} diff --git a/apps/host/src/locales/upd-fr.json b/apps/host/src/locales/upd-fr.json new file mode 100644 index 0000000000..6cc6b785ca --- /dev/null +++ b/apps/host/src/locales/upd-fr.json @@ -0,0 +1,19 @@ +{ + "upd01": "Pour mettre à jour le moteur, Strata doit arrêter le modèle chargé : {0}.", + "upd02": "Le nouveau moteur est d’abord téléchargé pendant que le modèle continue de répondre. Ensuite le modèle s’arrête (les réponses en cours se terminent d’abord), le moteur est mis à jour, et vous pouvez redémarrer le modèle avec les mêmes réglages. Vos modèles et réglages sont conservés.", + "upd03": "Arrêter et mettre à jour", + "upd04": "Préparation du nouveau moteur. {0} continue de fonctionner jusqu’à ce qu’il soit prêt.", + "upd05": "Arrêt de {0}. Les réponses en cours se terminent d’abord.", + "upd06": "{0} est arrêté. Mise à jour du moteur…", + "upd07": "Mise à jour du moteur", + "upd08": "Le moteur est à jour", + "upd09": "Le moteur n’a pas été mis à jour", + "upd10": "Le moteur est à jour. Redémarrer {0} avec les mêmes réglages ?", + "upd11": "La mise à jour ne s’est pas terminée. Votre ancien moteur est inchangé et fonctionne toujours. Redémarrer {0} avec lui ?", + "upd12": "Pas maintenant", + "upd13": "Démarrage de {0}. Le chargement peut prendre quelques minutes.", + "upd14": "Redémarrage de {0}", + "upd15": "Le modèle n’a pas redémarré", + "upd16": "Vous pouvez le recharger depuis Modèles.", + "upd17": "Un modèle qui n’a pas été démarré depuis cette application est en cours d’exécution, rien n’a donc été modifié. Arrêtez-le, puis mettez à nouveau le moteur à jour." +} diff --git a/apps/host/src/locales/upd-ja.json b/apps/host/src/locales/upd-ja.json new file mode 100644 index 0000000000..add4f19331 --- /dev/null +++ b/apps/host/src/locales/upd-ja.json @@ -0,0 +1,19 @@ +{ + "upd01": "エンジンを更新するには、読み込み中のモデルを Strata が停止する必要があります:{0}。", + "upd02": "まず新しいエンジンをダウンロードします。その間、モデルは応答を続けます。その後モデルが停止し(進行中の回答は先に完了します)、エンジンが更新され、同じ設定でモデルをもう一度起動できます。モデルと設定はそのまま残ります。", + "upd03": "停止して更新", + "upd04": "新しいエンジンを準備しています。準備ができるまで {0} は動き続けます。", + "upd05": "{0} を停止しています。進行中の回答は先に完了します。", + "upd06": "{0} を停止しました。エンジンを更新しています…", + "upd07": "エンジンを更新しています", + "upd08": "エンジンを更新しました", + "upd09": "エンジンは更新されませんでした", + "upd10": "エンジンを更新しました。同じ設定で {0} をもう一度起動しますか?", + "upd11": "更新は完了しませんでした。以前のエンジンは変更されておらず、そのまま使えます。そのエンジンで {0} をもう一度起動しますか?", + "upd12": "今はしない", + "upd13": "{0} を起動しています。読み込みには数分かかることがあります。", + "upd14": "{0} をもう一度起動しています", + "upd15": "モデルを再起動できませんでした", + "upd16": "「モデル」からもう一度読み込めます。", + "upd17": "このアプリから起動していないモデルが動作しているため、何も変更していません。それを停止してから、もう一度エンジンを更新してください。" +} diff --git a/apps/host/src/locales/upd-ko.json b/apps/host/src/locales/upd-ko.json new file mode 100644 index 0000000000..fe53a23ebf --- /dev/null +++ b/apps/host/src/locales/upd-ko.json @@ -0,0 +1,19 @@ +{ + "upd01": "엔진을 업데이트하려면 Strata가 불러온 모델을 중지해야 합니다: {0}.", + "upd02": "먼저 모델이 계속 응답하는 동안 새 엔진을 다운로드합니다. 그다음 모델이 중지되고(진행 중인 답변은 먼저 끝납니다) 엔진이 업데이트되며, 같은 설정으로 모델을 다시 시작할 수 있습니다. 모델과 설정은 그대로 유지됩니다.", + "upd03": "중지하고 업데이트", + "upd04": "새 엔진을 준비하는 중입니다. 준비될 때까지 {0}은(는) 계속 작동합니다.", + "upd05": "{0}을(를) 중지하는 중입니다. 진행 중인 답변은 먼저 끝납니다.", + "upd06": "{0}이(가) 중지되었습니다. 엔진을 업데이트하는 중입니다…", + "upd07": "엔진 업데이트 중", + "upd08": "엔진이 업데이트되었습니다", + "upd09": "엔진이 업데이트되지 않았습니다", + "upd10": "엔진이 업데이트되었습니다. 같은 설정으로 {0}을(를) 다시 시작할까요?", + "upd11": "업데이트가 끝나지 않았습니다. 기존 엔진은 그대로이며 계속 작동합니다. 기존 엔진으로 {0}을(를) 다시 시작할까요?", + "upd12": "나중에", + "upd13": "{0}을(를) 시작하는 중입니다. 불러오는 데 몇 분이 걸릴 수 있습니다.", + "upd14": "{0}을(를) 다시 시작하는 중", + "upd15": "모델이 다시 시작되지 않았습니다", + "upd16": "모델 화면에서 다시 불러올 수 있습니다.", + "upd17": "이 앱에서 시작하지 않은 모델이 실행 중이어서 아무것도 변경하지 않았습니다. 그 모델을 중지한 다음 엔진을 다시 업데이트하세요." +} diff --git a/apps/host/src/locales/upd-pt.json b/apps/host/src/locales/upd-pt.json new file mode 100644 index 0000000000..0225443075 --- /dev/null +++ b/apps/host/src/locales/upd-pt.json @@ -0,0 +1,19 @@ +{ + "upd01": "Para atualizar o motor, o Strata precisa parar o modelo carregado: {0}.", + "upd02": "Primeiro o novo motor é baixado enquanto o modelo continua a responder. Depois o modelo para (as respostas em curso terminam antes), o motor é atualizado e pode iniciar o modelo de novo com as mesmas definições. Os seus modelos e definições são mantidos.", + "upd03": "Parar e atualizar", + "upd04": "A preparar o novo motor. {0} continua a funcionar até estar pronto.", + "upd05": "A parar {0}. As respostas em curso terminam antes.", + "upd06": "{0} está parado. A atualizar o motor…", + "upd07": "A atualizar o motor", + "upd08": "O motor está atualizado", + "upd09": "O motor não foi atualizado", + "upd10": "O motor está atualizado. Iniciar {0} de novo com as mesmas definições?", + "upd11": "A atualização não terminou. O seu motor anterior não foi alterado e continua a funcionar. Iniciar {0} de novo com ele?", + "upd12": "Agora não", + "upd13": "A iniciar {0}. O carregamento pode demorar alguns minutos.", + "upd14": "A iniciar {0} de novo", + "upd15": "O modelo não voltou a iniciar", + "upd16": "Pode carregá-lo de novo em Modelos.", + "upd17": "Está em execução um modelo que não foi iniciado a partir desta aplicação, por isso nada foi alterado. Pare-o e atualize o motor de novo." +} diff --git a/apps/host/src/locales/upd-ru.json b/apps/host/src/locales/upd-ru.json new file mode 100644 index 0000000000..495d208d2a --- /dev/null +++ b/apps/host/src/locales/upd-ru.json @@ -0,0 +1,19 @@ +{ + "upd01": "Чтобы обновить движок, Strata должна остановить загруженную модель: {0}.", + "upd02": "Сначала новый движок скачивается, пока модель продолжает отвечать. Затем модель останавливается (ответы в процессе сначала завершаются), движок обновляется, и вы можете снова запустить модель с теми же настройками. Ваши модели и настройки сохраняются.", + "upd03": "Остановить и обновить", + "upd04": "Готовим новый движок. {0} продолжает работать, пока он не будет готов.", + "upd05": "Останавливаем {0}. Ответы в процессе сначала завершаются.", + "upd06": "{0} остановлена. Обновляем движок…", + "upd07": "Обновление движка", + "upd08": "Движок обновлён", + "upd09": "Движок не обновлён", + "upd10": "Движок обновлён. Запустить {0} снова с теми же настройками?", + "upd11": "Обновление не завершилось. Прежний движок не изменён и работает. Запустить {0} снова на нём?", + "upd12": "Не сейчас", + "upd13": "Запускаем {0}. Загрузка может занять несколько минут.", + "upd14": "Снова запускаем {0}", + "upd15": "Модель не запустилась снова", + "upd16": "Вы можете загрузить её снова в разделе «Модели».", + "upd17": "Работает модель, запущенная не из этого приложения, поэтому ничего не изменено. Остановите её и обновите движок снова." +} diff --git a/apps/host/src/locales/upd-zh.json b/apps/host/src/locales/upd-zh.json new file mode 100644 index 0000000000..32138d7c56 --- /dev/null +++ b/apps/host/src/locales/upd-zh.json @@ -0,0 +1,19 @@ +{ + "upd01": "要更新引擎,Strata 必须先停止当前已加载的模型:{0}。", + "upd02": "新引擎会先下载,此时模型仍可继续回答。然后模型停止(正在进行的回答会先完成),引擎随即更新,之后你可以用相同的设置再次启动该模型。你的模型和设置都会保留。", + "upd03": "停止并更新", + "upd04": "正在准备新引擎。在准备好之前,{0} 会继续工作。", + "upd05": "正在停止 {0}。正在进行的回答会先完成。", + "upd06": "{0} 已停止。正在更新引擎…", + "upd07": "正在更新引擎", + "upd08": "引擎已更新", + "upd09": "引擎未更新", + "upd10": "引擎已更新。要用相同的设置再次启动 {0} 吗?", + "upd11": "更新没有完成。你原来的引擎没有改动,仍然可用。要在它上面再次启动 {0} 吗?", + "upd12": "暂不", + "upd13": "正在启动 {0}。加载可能需要几分钟。", + "upd14": "正在再次启动 {0}", + "upd15": "模型没有重新启动", + "upd16": "你可以在“模型”中再次加载它。", + "upd17": "有一个不是从此应用启动的模型正在运行,因此没有做任何更改。请先停止它,然后再次更新引擎。" +} diff --git a/apps/host/tests/engine-update-model.test.mjs b/apps/host/tests/engine-update-model.test.mjs new file mode 100644 index 0000000000..9a8de02fd8 --- /dev/null +++ b/apps/host/tests/engine-update-model.test.mjs @@ -0,0 +1,220 @@ +import './helpers/isolate-profile.mjs'; // a test run never writes the owner's real Strata profile +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync as read, mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createControl } from '../server/control-runtime.mjs'; +import { createNativeControl } from '../server/native-control.mjs'; + +const src = name => read(new URL(`../${name}`, import.meta.url), 'utf8'); + +/** A packaged host with one installed model and a fake Control whose `update` plays the events of `strata update --stop-model --output jsonl`. */ +function fixture({ updateScript } = {}) { + const root = mkdtempSync(join(tmpdir(), 'strata-update-model-')); + const install = join(root, 'install'), data = join(root, 'data'); + mkdirSync(install, { recursive: true }); + process.env.STRATA_INSTALL_DIR = install; + const config = join(install, 'strata-iq2_xs.json'); + writeFileSync(config, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(install, 'tok'), args: ['--max-context', '32768'], model_name: 'Qwen', port: 8080 })); + const calls = []; + const control = { + control: { dir: join(root, 'control') }, version: '0.1.45', + async installedModels() { return { install_dir: install, models: [{ id: 'iq2_xs', name: 'Qwen', source_config: config, component_status: 'present', context_tokens: 32768, backend: 'cuda' }] }; }, + async engine() { return { usable: true, backend: 'cuda', components_dir: 'E:\\c', previous: null, engine: { version: '0.1.45', platform: 'windows-x86_64', backend: 'cuda', exe: 'e', root: 'r' } }; }, + async saveProfile(profile) { calls.push(['saveProfile', profile]); return {}; }, + async start(profile) { calls.push(['start', profile]); return { ok: true, state: 'ready' }; }, + async stop(profile) { calls.push(['stop', profile]); return { ok: true }; }, + async update(options) { + calls.push(['update', options.engine, options.stopModel === true]); + const ids = native.state().instances.map(i => i.id); + const profile = 'app-1'; + options.onEvent?.({ event: 'models', phase: 'consent', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'ready' }], message: 'Qwen is running' }); + if (updateScript) return updateScript(options, { profile, ids, native }); + options.onEvent?.({ event: 'progress', phase: 'download', label: 'engine 0.1.46', percent: 40 }); + options.onEvent?.({ event: 'models', phase: 'stopping', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'ready' }] }); + options.onEvent?.({ event: 'models', phase: 'stopped', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'stopped' }] }); + options.onEvent?.({ event: 'models', phase: 'left-stopped', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'stopped' }], start: 'strata launch' }); + return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.46' } }] }; + }, + async rollbackEngine() { return { ok: true }; }, + }; + const native = createNativeControl({ control, directory: data, spawnProcess: () => { throw new Error('no process'); }, fetcher: async () => Response.json({}), requests: () => [] }); + return { native, calls, control, cleanup: () => rmSync(root, { recursive: true, force: true }) }; +} +const finish = async (native, id) => { for (let i = 0; i < 400; i++) { const job = native.state().jobs.find(j => j.id === id); if (job.state !== 'running') return job; await new Promise(r => setTimeout(r, 10)); } throw new Error('job did not finish'); }; +async function loaded(f) { + await f.native.refresh(true); + const load = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id); + assert.equal(load.state, 'done', load.error); + assert.equal(f.native.state().instances.length, 1); +} + +test('Control is called with --stop-model only when the app asks for it', async () => { + const seen = []; + const control = createControl({ control: { dir: '/c', python: '/c/python', cli: '/c/strata.py' }, env: {}, run: async args => { seen.push(args); return { code: 0, json: { ok: true, results: [] } }; } }); + await control.update({ engine: true, control: false }); + await control.update({ engine: true, control: false, stopModel: true }); + assert.ok(!seen[0].includes('--stop-model')); + assert.ok(seen[1].includes('--stop-model')); + assert.deepEqual(seen[1].slice(0, 3), ['update', '--output', 'jsonl'], 'the host reads the events (jsonl)'); + assert.ok(!seen[1].includes('--start-again'), 'starting again is the person\'s answer in the dialog, not an automatic flag'); +}); + +test('a loaded model is stopped for the update only with the person\'s yes, and is then offered a start with the same settings', async () => { + const f = fixture(); + try { + await loaded(f); + const refused = await finish(f.native, f.native.operation('update-engine', {}).id); + assert.equal(refused.state, 'error'); + assert.match(refused.error, /Unload native models/, 'no yes, no stop'); + assert.equal(f.calls.filter(c => c[0] === 'update').length, 0); + + const job = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id); + assert.equal(job.state, 'done', job.error); + assert.deepEqual(f.calls.find(c => c[0] === 'update'), ['update', true, true]); + const state = f.native.state(); + assert.equal(state.instances.length, 0, 'the stopped model has left the list'); + assert.equal(state.stoppedForUpdate.updated, true); + assert.deepEqual(state.stoppedForUpdate.models.map(m => m.label), [state.stoppedForUpdate.models[0].label]); + assert.equal(job.step, 'stopped'); + assert.equal(f.calls.filter(c => c[0] === 'start').length, 1, 'only the first load started it; nothing started it again by itself'); + + const again = await finish(f.native, f.native.operation('restart-models', {}).id); + assert.equal(again.state, 'done', again.error); + assert.match(again.summary, /running again with the same settings/); + const starts = f.calls.filter(c => c[0] === 'start'); + assert.equal(starts.length, 2); + assert.equal(starts[1][1], starts[0][1], 'the same profile (its saved run settings) is started again'); + const after = f.native.state(); + assert.equal(after.instances.length, 1); + assert.equal(after.instances[0].status, 'ready'); + assert.equal(after.stoppedForUpdate, null); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('a failed update leaves the old engine and still offers the model back, on the old engine', async () => { + const f = fixture({ + updateScript: async (options, { profile }) => { + options.onEvent?.({ event: 'models', phase: 'stopping', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'ready' }] }); + options.onEvent?.({ event: 'models', phase: 'stopped', models: [{ profile, name: 'Qwen', port: 8080, kind: 'profile', state: 'stopped' }] }); + throw Object.assign(new Error('The new engine did not pass its test start'), { exitCode: 6 }); + }, + }); + try { + await loaded(f); + const job = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id); + assert.equal(job.state, 'error'); + assert.match(job.error, /didn't start correctly, so nothing was changed\. Your current version still works/, 'plain words, not the exit code'); + const state = f.native.state(); + assert.equal(state.instances.length, 0); + assert.equal(state.stoppedForUpdate.updated, false, 'the dialog says the update did not finish and offers the old engine'); + const again = await finish(f.native, f.native.operation('restart-models', {}).id); + assert.equal(again.state, 'done', again.error); + assert.equal(f.native.state().instances[0].status, 'ready'); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('a failed update that never touched the model offers nothing', async () => { + const f = fixture({ updateScript: async () => { throw new Error('Could not reach the update server (timed out).'); } }); + try { + await loaded(f); + const job = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id); + assert.equal(job.state, 'error'); + assert.equal(f.native.state().instances.length, 1, 'the model is still running'); + assert.equal(f.native.state().stoppedForUpdate, null); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('a model the app did not start is never stopped: the update ends at the first event, before any download', async () => { + const f = fixture({ + updateScript: async (options, { profile }) => { + options.onEvent?.({ event: 'models', phase: 'consent', models: [{ profile: 'launch-qwen', name: 'Qwen (port 8081)', port: 8081, kind: 'launch', state: 'ready' }] }); + if (options.signal.aborted) throw new Error('killed'); // as runCli does: an aborted signal ends the Control process + await new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('killed')), { once: true })); + }, + }); + try { + await loaded(f); + const stopsBefore = f.calls.filter(c => c[0] === 'stop').length; + const job = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id); + assert.equal(job.state, 'error'); + assert.match(job.error, /not started from this app is running, so nothing was changed/); + assert.equal(f.native.state().instances.length, 1); + assert.equal(f.native.state().stoppedForUpdate, null); + assert.equal(f.calls.filter(c => c[0] === 'stop').length, stopsBefore, 'nothing was stopped by the update'); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('"Not now" forgets the offer; with nothing stopped there is nothing to start again', async () => { + const f = fixture(); + try { + await loaded(f); + await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id); + assert.ok(f.native.state().stoppedForUpdate); + f.native.dismissRestart(); + assert.equal(f.native.state().stoppedForUpdate, null); + const none = await finish(f.native, f.native.operation('restart-models', {}).id); + assert.equal(none.state, 'error'); + assert.match(none.error, /no stopped model/); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('with no model loaded the update behaves as before: no stop flag, no offer', async () => { + const f = fixture(); + try { + await f.native.refresh(true); + const job = await finish(f.native, f.native.operation('update-engine', {}).id); + assert.equal(job.state, 'done', job.error); + assert.deepEqual(f.calls.find(c => c[0] === 'update'), ['update', true, false]); + assert.equal(f.native.state().stoppedForUpdate, null); + const withFlag = await finish(f.native, f.native.operation('update-engine', { stopModel: true }).id); + assert.deepEqual(f.calls.filter(c => c[0] === 'update')[1], ['update', true, false], 'the flag is only sent when a model is loaded'); + assert.equal(withFlag.state, 'done'); + } finally { await f.native.close(); f.cleanup(); } +}); + +test('the dialog: warns naming the model, progress in plain words, the offer, the old-engine offer, and only Settings > About and the Models screen mount it', () => { + const dialog = src('src/components/EngineUpdateDialog.tsx'); + assert.match(dialog, /args: \{ stopModel: true \}/); + assert.match(dialog, /kind: 'restart-models'/); + assert.match(dialog, /To update the engine, Strata has to stop the model that is loaded: \{0\}\./, 'the warning names the model'); + for (const words of ['Getting the new engine ready. {0} keeps working until it is ready.', 'Stopping {0}. Answers in progress finish first.', '{0} is stopped. Updating the engine…', + 'The engine is updated. Start {0} again with the same settings?', "The update didn't finish. Your old engine is unchanged and still works. Start {0} again on it?"]) + assert.ok(dialog.includes(words), words); + assert.doesNotMatch(dialog, /fetch\(|api\.get|XMLHttpRequest/, 'no network from the dialog'); + const code = dialog.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, ''); + assert.doesNotMatch(code, /exit code|--stop-model|jsonl/i, 'no flags or codes in the words'); + assert.match(src('src/components/SettingsUpdates.tsx'), /<EngineUpdateDialog open=\{confirm === 'update-engine' && withModel\}/); + assert.match(src('src/components/SettingsUpdates.tsx'), /<Dialog open=\{!!confirm && !\(confirm === 'update-engine' && withModel\)\}/, 'with no model loaded the older dialog is the one shown'); + assert.equal((src('src/components/NativeModels.tsx').match(/<EngineUpdateDialog /g) ?? []).length, 1); + assert.match(src('server/index.mjs'), /\/api\/native\/engine-restart\/dismiss/); +}); + +test('the notice for a newer engine stays an ordinary quiet card: no toast, no banner, no timer, no network', () => { + const card = src('src/components/EngineUpdateCard.tsx'); + assert.doesNotMatch(card, /toast|setInterval|setTimeout|fetch\(|Notification/); + assert.doesNotMatch(src('src/components/EngineUpdateDialog.tsx'), /setInterval|setTimeout|Notification|toast/); +}); + +test('offline, the update says nothing by itself: the dialog opens only from a button and shows only what the host reports', () => { + const settings = src('src/components/SettingsUpdates.tsx'); + assert.match(settings, /onClick=\{\(\) => setConfirm\(name === 'Strata' \? 'update-strata' : 'update-engine'\)\}/, 'the button opens the confirmation; nothing opens it on a timer or on a failed check'); +}); + +test('all nine languages carry the dialog\'s words with the same slots', () => { + const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; + const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(src(`src/locales/upd-${l}.json`))])); + const keys = Object.keys(catalogs.en); + assert.equal(keys.length, 17); + for (const l of langs) { + assert.deepEqual(Object.keys(catalogs[l]), keys, l); + for (const k of keys) { + assert.ok(catalogs[l][k].trim(), `${l} ${k}`); + assert.deepEqual([...catalogs[l][k].matchAll(/\{\d+\}/g)].map(m => m[0]).sort(), [...catalogs.en[k].matchAll(/\{\d+\}/g)].map(m => m[0]).sort(), `${l} ${k} slots`); + if (l !== 'en') assert.notEqual(catalogs[l][k], catalogs.en[k], `${l} ${k} is translated`); + } + } + const i18n = src('src/lib/i18n.ts'); + for (const l of langs) assert.match(i18n, new RegExp(`\\.\\.\\.upd_${l}\\b`)); +}); diff --git a/apps/host/tests/locale-gaps.test.mjs b/apps/host/tests/locale-gaps.test.mjs index f9f660b915..7d2772d763 100644 --- a/apps/host/tests/locale-gaps.test.mjs +++ b/apps/host/tests/locale-gaps.test.mjs @@ -12,7 +12,7 @@ const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64 test('every tr("...") literal and every command hint has a key in the English catalog, so no language is stuck in English (#3479)', async () => { const known = new Set(); - for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en', 'ui-en', 'engine-en', 'pick-en', 'df2-en']) for (const v of Object.values(await read(name))) known.add(String(v)); + for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en', 'ui-en', 'engine-en', 'pick-en', 'df2-en', 'upd-en']) for (const v of Object.values(await read(name))) known.add(String(v)); const missing = []; const scan = async dir => { for (const entry of await readdir(dir, { withFileTypes: true })) { From e394c4857216af375ebf4c220dc1de5b5aebbea7 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:05:56 +0100 Subject: [PATCH 23/59] Engine update dialog: space above the progress bar; the failed-update offer shows the reason only under Details --- apps/host/src/components/EngineUpdateDialog.tsx | 5 ++--- apps/host/src/styles/onboarding.css | 3 +++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/host/src/components/EngineUpdateDialog.tsx b/apps/host/src/components/EngineUpdateDialog.tsx index a84dfb928f..4c93336357 100644 --- a/apps/host/src/components/EngineUpdateDialog.tsx +++ b/apps/host/src/components/EngineUpdateDialog.tsx @@ -79,7 +79,6 @@ export function EngineUpdateDialog({ open, onClose }: { open: boolean; onClose: return <Dialog open compact title={tr(done ? 'The engine is updated' : "The engine was not updated")} onClose={close} actions={<><Btn onClick={() => void notNow()}>{tr("Not now")}</Btn><Btn variant="primary" onClick={() => void startAgain()}>{tr("Start again")}</Btn></>}> <p>{done ? tr("The engine is updated. Start {0} again with the same settings?", [names]) : tr("The update didn't finish. Your old engine is unchanged and still works. Start {0} again on it?", [names])}</p> - {!done && job?.error ? <p className="small muted">{tr(job.error)}</p> : null} {!done && job ? details(job) : null} {error ? <p className="small inline-error" role="alert">{tr(error)}</p> : null} </Dialog>; @@ -88,7 +87,7 @@ export function EngineUpdateDialog({ open, onClose }: { open: boolean; onClose: if (restarting) { return <Dialog open compact title={tr("Starting {0} again", [names])} onClose={onClose}> <p role="status">{tr("Starting {0}. Loading can take a few minutes.", [names])}</p> - <Bar value={0} indeterminate label={tr("Starting {0} again", [names])}/> + <div className="engine-update-progress"><Bar value={0} indeterminate label={tr("Starting {0} again", [names])}/></div> </Dialog>; } if (failedRestart) { @@ -105,7 +104,7 @@ export function EngineUpdateDialog({ open, onClose }: { open: boolean; onClose: : step === 'stopped' ? tr("{0} is stopped. Updating the engine…", [label]) : step === 'getting-ready' ? tr("Getting the new engine ready. {0} keeps working until it is ready.", [label]) : tr(job.summary || 'Starting…')}</p> - {step === 'getting-ready' && Number.isFinite(percent) ? <Bar value={percent} label={tr("Downloading…")}/> : <Bar value={0} indeterminate label={tr("Updating the engine")}/>} + <div className="engine-update-progress">{step === 'getting-ready' && Number.isFinite(percent) ? <Bar value={percent} label={tr("Downloading…")}/> : <Bar value={0} indeterminate label={tr("Updating the engine")}/>}</div> </Dialog>; } // The update ended without stopping anything (declined, refused, or failed before the model was touched). diff --git a/apps/host/src/styles/onboarding.css b/apps/host/src/styles/onboarding.css index d966db2d06..f1a14dc308 100644 --- a/apps/host/src/styles/onboarding.css +++ b/apps/host/src/styles/onboarding.css @@ -257,3 +257,6 @@ @media(max-width:700px){.guided-onboarding[data-step="1"] .onboard-header{justify-content:space-between}.guided-onboarding[data-step="1"] .onboard-header>.brand{position:static;transform:none}.onboard-language{min-width:120px}} .engine-update { align-items: center; } .engine-update > div { flex: 1; } + +/* The progress bar under the words in the engine update dialog. */ +.engine-update-progress { margin-top: 12px; } From 811267e19f58f640cdfce505ab173ab66b834bcd Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:14:02 +0100 Subject: [PATCH 24/59] Terminal tests do not depend on the box's graphics card (the Drafting step changed the step count on Nvidia/AMD boxes); after a model is stopped for an engine update, wait briefly for its runtime host to release the engine lease (found on a real host) --- strata_control/engine_update.py | 13 +++++ tests/terminal/conftest.py | 18 +++++++ tests/terminal/test_engine_update_settle.py | 56 +++++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 tests/terminal/conftest.py create mode 100644 tests/terminal/test_engine_update_settle.py diff --git a/strata_control/engine_update.py b/strata_control/engine_update.py index e8efdd2c44..85e7045a9d 100644 --- a/strata_control/engine_update.py +++ b/strata_control/engine_update.py @@ -25,6 +25,7 @@ import datetime as dt import json import re import threading +import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable @@ -282,6 +283,9 @@ def start_hint(model: RunningModel) -> str: # ---------------------------------------------------------------------------------------------------- the gate +SETTLE_SECONDS = 20.0 # how long, after stopping a model, the update waits for its runtime host to let go of the engine lease + + class Declined(updater.UpdateError): """The person said no: nothing was changed. Exit 0.""" @@ -360,6 +364,15 @@ class ModelGate: if m.profile not in {s.profile for s in self.stopped}: self.stopped.append(m) self.emit({"event": "models", "phase": "stopped", "models": [m.to_dict()], "message": f"{m.label} is stopped"}) + self._settle(serving_now) + + def _settle(self, serving_now: Callable[[], list[dict]]) -> None: + """A stopped model's runtime host ends a moment after the stop returns, and until then it still holds the shared engine lease: the update's + "nothing may still be serving" check would call that "a running Strata server" and refuse (found on a real host: the model was stopped, the + update then failed). Wait, briefly, for the lease to be free; if something is still there after SETTLE_SECONDS the check says so as before.""" + deadline = time.monotonic() + SETTLE_SECONDS + while serving_now() and time.monotonic() < deadline: + time.sleep(0.25) # -- after the update, whatever happened def finish(self, update_ok: bool) -> bool: diff --git a/tests/terminal/conftest.py b/tests/terminal/conftest.py new file mode 100644 index 0000000000..aa9689d22e --- /dev/null +++ b/tests/terminal/conftest.py @@ -0,0 +1,18 @@ +"""Terminal tests do not depend on the graphics card of the box they run on. + +The Drafting step of `strata launch` (and the Drafting line of the summary) exists only where the engine can run DFlash2 (CUDA or HIP), so the number +of steps and the layout of the summary used to differ between an Nvidia box and an Intel one. Every test starts on a computer with no card the engine +knows; a test about drafting names the card it means (test_drafting.py and test_drafting_hardware.py patch `detect_hardware` themselves).""" +from unittest import mock + +import pytest + + +@pytest.fixture(autouse=True) +def _no_card_unless_a_test_names_one(request): + from strata_control import drafting + if request.module.__name__.rsplit(".", 1)[-1].startswith("test_drafting"): + yield # these name their card themselves (setUpModule / per test) + return + with mock.patch.object(drafting, "detect_hardware", return_value=("cpu", [])): + yield diff --git a/tests/terminal/test_engine_update_settle.py b/tests/terminal/test_engine_update_settle.py new file mode 100644 index 0000000000..2dbf3ffb14 --- /dev/null +++ b/tests/terminal/test_engine_update_settle.py @@ -0,0 +1,56 @@ +"""After a loaded model is stopped for an engine update, the runtime host that ran it ends a moment later and until then still holds the shared engine lease. +Found on a real host (Boston, the app's update with a real model): the model was stopped, the update then said "a running Strata server is serving" and failed. +The gate waits, briefly, for the lease to be free.""" +import unittest +from unittest import mock + +from strata_control import engine_update + +MODEL = {"profile": "launch-x", "state": "ready"} +LOOSE = {"profile": "a running Strata server", "state": "serving"} + + +class Settle(unittest.TestCase): + def gate(self): + events = [] + gate = engine_update.ModelGate(ask=None, say=lambda text: None, emit=events.append, allow_stop=True, stop=lambda m: None) + gate.consent([MODEL], "plan") + return gate, events + + def test_the_gate_waits_until_the_lease_is_free(self): + gate, events = self.gate() + answers = [[MODEL], [LOOSE], [LOOSE], []] # release's own look, then the lingering host twice, then free + calls = [] + + def serving(): + calls.append(1) + return answers.pop(0) if answers else [] + + with mock.patch.object(engine_update.time, "sleep") as sleep: + gate.release(serving) + self.assertEqual(len(calls), 4) + self.assertEqual(sleep.call_count, 2) + self.assertEqual([e["phase"] for e in events if e["event"] == "models"], ["consent", "stopping", "stopped"]) + self.assertEqual([m.profile for m in gate.stopped], ["launch-x"]) + + def test_something_that_never_lets_go_is_still_reported_by_the_normal_check_after_the_wait(self): + gate, _ = self.gate() + clock = iter([0.0, 0.1, 5.0, 25.0, 30.0, 40.0]) + + def serving(_state=[0]): + _state[0] += 1 + return [MODEL] if _state[0] == 1 else [LOOSE] + + with mock.patch.object(engine_update.time, "sleep"), mock.patch.object(engine_update.time, "monotonic", side_effect=lambda: next(clock)): + gate.release(serving) # returns; updater.wait_until_idle then refuses it, as before + self.assertTrue(gate.stopped) + + def test_nothing_stopped_means_no_waiting(self): + gate = engine_update.ModelGate(ask=None, say=lambda text: None, allow_stop=True, stop=lambda m: None) + with mock.patch.object(engine_update.time, "sleep") as sleep: + gate.release(lambda: []) + sleep.assert_not_called() + + +if __name__ == "__main__": + unittest.main() From b2365cecf20225fb74a164b33b26e865b840d88d Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:20:02 +0100 Subject: [PATCH 25/59] Models: no DFlash2 paragraph, no per-card line, no picture-reader sentence; the Drafting dropdown stays --- apps/host/src/components/NativeModels.tsx | 2 -- apps/host/tests/ui-r3.test.mjs | 14 ++++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 apps/host/tests/ui-r3.test.mjs diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 9de8f06cdd..bbba9741f5 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -215,11 +215,9 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(draftingChoices ? <div className="native-choice__col"><span className="native-choice__label">{tr("Drafting")}</span><Select ariaLabel={tr("Drafting")} value={drafting} disabled={!!active} options={draftingChoices.map(v => ({ value: v, label: tr(draftingWords[v]) }))} onChange={v => setDrafting(String(v))}/></div> : null)} <div className="native-choice__col"><span className="native-choice__label">{tr("Computer use")}</span><div className="native-resource-choice"><button aria-pressed={resourceProfile === 'work'} data-selected={resourceProfile === 'work'} onClick={() => setResourceProfile('work')}><Icon name="computer" size={20}/><span><strong>{tr("Leave 20% for my work")}</strong><small>{tr("Headroom for your other apps")}</small></span>{tr(resourceProfile === 'work' ? <Icon name="check" size={15}/> : null)}</button><button aria-pressed={resourceProfile === 'performance'} data-selected={resourceProfile === 'performance'} onClick={() => setResourceProfile('performance')}><Icon name="bolt" size={20}/><span><strong>{tr("Full performance")}</strong><small>{tr("Give Strata priority")}</small></span>{tr(resourceProfile === 'performance' ? <Icon name="check" size={15}/> : null)}</button></div></div> </div> - {tr(draftingChoices ? <p className="small muted native-spill-note"><Icon name="info" size={16}/>{tr("MTP is the default. DFlash2 is another way to guess the next words ahead, for Qwen3.8-Flash-Next only. On an RTX PRO 5000 it was 7.8% faster than MTP on 19 short prompts and 1.1% faster on long thinking, and faster on 21 of 23 prompts. On the short prompts the answers were identical.")} {tr("It downloads about 1.2 GB once, works with one graphics card and one request at a time, and uses MTP otherwise.")}{native?.capabilities?.dflash2Support?.line ? <> {tr(native.capabilities.dflash2Support.line)}</> : null}</p> : null)} {tr(loadedSelected?.metrics?.engine?.drafting_note ? <p className="small muted native-spill-note">{tr(String(loadedSelected.metrics.engine.drafting_note))}</p> : null)} {roleCards.length > 1 ? <GpuRoles cards={roleCards} roles={effectiveRoles} custom={customRoles} recommendedRoles={recommended.roles} vendor={engineVendor} disabled={!!active} onChange={changeRoles} onBack={() => setRoles(null)} memoryGb={selectedSize ? memoryNeeded(selectedSize) || null : null} ramGb={pcRam} spillGb={selectedSize ? fitOn(selectedSize, fitHardware).spillGb : 0} usedBy={i => usedBy([i])}/> : null} {tr(roleCards.length > 1 && (native?.hardware?.gpus ?? []).length > roleCards.length ? <p className="small muted native-cards__note">{tr('Not used: {0} (another make of graphics card than this engine drives).', [(native?.hardware?.gpus ?? []).filter(g => !roleCards.some(r => r.index === g.index && r.vendor === g.vendor)).map(g => g.name).join(', ')])}</p> : null)} - {tr(selectedSize?.imagesCapable && !selectedSize.images ? <p className="small muted native-spill-note">{tr("This model can read pictures, but the engine installed here does not include the picture reader yet, so Read pictures is off. Update the engine in Settings → About to turn it on.")}</p> : null)} {tr(selectedSize?.images ? <><div className="native-image-reading"><label><input type="checkbox" checked={vision !== 'no'} disabled={!selectedSize?.images || !!active} onChange={e => setVision(e.target.checked ? 'yes' : 'no')}/><span><strong>{tr("Read pictures ")}<small>{tr("On by default")}</small></strong><small>{tr("Understand photos, screenshots and charts. The picture files download automatically. Turn it off to save memory.")}</small></span></label>{tr(expert && vision !== 'no' ? <Select ariaLabel={tr("Image encoder device")} value={vision === 'yes' ? 'yes' : vision} options={[{ value: 'yes', label: 'Automatic' }, { value: 'gpu', label: 'GPU' }, { value: 'cpu', label: 'CPU' }]} onChange={setVision}/> : null)}</div>{tr(vision !== 'no' && installed?.ready && installed.visionPrepared === false ? <div className="native-vision-missing" role="status"><span>{tr("Picture reading needs a few more files that are not on this computer yet.")}</span><Btn size="sm" disabled={pending || !!active} onClick={() => void download()}>{tr("Download picture-reading files")}</Btn></div> : null)}</> : null)} </> : null)} <EngineWarning native={native}/> diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs new file mode 100644 index 0000000000..4deb94fbf8 --- /dev/null +++ b/apps/host/tests/ui-r3.test.mjs @@ -0,0 +1,14 @@ +/** Owner's GUI feedback round 3 (2026-11-01), items 1 to 14 that are UI: each pinned where the source can show it. */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const read = path => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8'); +const models = read('src/components/NativeModels.tsx'); + +test('1: the Models page carries no DFlash2 paragraph, no per-card line and no picture-reader sentence; the Drafting dropdown stays', () => { + assert.ok(!/MTP is the default\. DFlash2/.test(models), 'the DFlash2 paragraph is gone'); + assert.ok(!/dflash2Support/.test(models), 'the per-card line is gone'); + assert.ok(!/engine installed here does not include the picture reader/.test(models), 'the picture-reader sentence is gone'); + assert.match(models, /<Select ariaLabel=\{tr\("Drafting"\)\}/, 'the dropdown stays'); +}); From 2b9c2980e2c036da0ac02a329e7eebc47e49b2fe Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:22:06 +0100 Subject: [PATCH 26/59] DFlash2 drafter: the Q4_0 pack is made on the person's computer (522,458,112 bytes, pinned size and SHA-256), an existing Q8 pack keeps working --- strata_control/drafting.py | 37 +++++++++++--- strata_control/drafting_fetch.py | 14 ++++-- tests/terminal/test_drafting.py | 2 +- tests/terminal/test_drafting_hardware.py | 63 ++++++++++++++++++++++++ 4 files changed, 103 insertions(+), 13 deletions(-) diff --git a/strata_control/drafting.py b/strata_control/drafting.py index b88a5fc35c..fe915b369d 100644 --- a/strata_control/drafting.py +++ b/strata_control/drafting.py @@ -148,9 +148,11 @@ def hardware_support(backend: str | None, archs: Any = None) -> Support: # --------------------------------------------------------------------------------------------------- the drafter file # -# incoai/Qwen3.8-Flash-Next-DFlash2 (Apache-2.0), pinned to one revision. The safetensors file is 1.2 GB; tools/dflash2_pack.py turns it into the -# engine's runtime file (Q8 pack, about 0.76 GB). The sizes and hashes are the repository's own for that revision: a download is refused -# if either differs. +# incoai/Qwen3.8-Flash-Next-DFlash2 (Apache-2.0), pinned to one revision. The safetensors file is 1.2 GB; tools/dflash2_pack.py --q4_0 turns it, on the +# person's own computer, into the engine's runtime file (a Q4_0 pack, 522,458,112 bytes; the repository publishes only the bf16 file and we host nothing). +# The sizes and hashes are the repository's own for that revision: a download is refused if either differs. The pack itself is checked too: the same +# bytes come out on x86 Windows, x86 Linux and aarch64 Linux (numpy 2.3.3 and 2.5.3), so its size and SHA-256 are pinned and a pack that differs is deleted. +# A Q8 pack (760,353,792 bytes) made by an earlier Strata keeps working and is never fetched again; Q4_0 and Q8 ran the same speed (-0.3%, RESULTS-DRAFT.md). REPO = "incoai/Qwen3.8-Flash-Next-DFlash2" REVISION = "a22a1744e85c17364dcc54a6a420af7135d4c7f6" @@ -161,9 +163,12 @@ FILES = ( ("model.safetensors", 1206140008, "d6723f2a359eaf33ec0c95f22ae8edda896774020c552296a85e1913b4d3186f"), ) DOWNLOAD_GB = 1.2 # what is fetched (the safetensors file) -PACK_GB = 0.76 # what stays on disk (the source file is removed after packing) -PACK_NAME = "qwen3.8-flash-next-dflash2.q8.pack" -VRAM_GB = 1.2 # what the drafter needs in graphics memory (the engine's own estimate) +PACK_GB = 0.52 # what stays on disk (the source file is removed after packing) +PACK_NAME = "qwen3.8-flash-next-dflash2.q4_0.pack" +PACK_BYTES = 522458112 # the Q4_0 pack tools/dflash2_pack.py --q4_0 makes from the pinned safetensors file, and its SHA-256 +PACK_SHA256 = "cda40d62d0eb8f37ed6e272142641a1d2f0de4a32f9e14d0416e7a71534849f1" +LEGACY_PACK_NAME = "qwen3.8-flash-next-dflash2.q8.pack" # what Strata 0.2.9 test builds packed: still used when it is the one on disk +VRAM_GB = 1.0 # what the drafter needs in graphics memory (the engine's own estimate, measured with the Q4_0 pack) FOLDER = "dflash2" # under the model data folder, next to ``mtp`` SPEC_WINDOW = 6 # --spec with DFlash2: the widest window of drafted words per round (measured best on Blackwell; the engine caps it per card) DRAFT_CONF = 0.35 # --draft-conf with DFlash2: the window ends where the chance that every draft so far holds falls below this @@ -180,13 +185,29 @@ def supported_model(model_name: str | None = None, family: str | None = None) -> return bool(model_name and _SUPPORTED_NAME.match(str(model_name))) -def pack_path(data_dir: str | Path) -> Path: +def _here(path: Path) -> bool: + try: + return path.is_file() and path.stat().st_size > (1 << 20) + except OSError: + return False + + +def target_path(data_dir: str | Path) -> Path: + """Where a fetch writes the Q4_0 pack.""" return Path(data_dir) / FOLDER / PACK_NAME +def pack_path(data_dir: str | Path) -> Path: + """The pack the engine is started with: the Q4_0 pack, else a Q8 pack an earlier Strata made (no download for it), else where the Q4_0 pack will be.""" + for name in (PACK_NAME, LEGACY_PACK_NAME): + if _here(Path(data_dir) / FOLDER / name): + return Path(data_dir) / FOLDER / name + return target_path(data_dir) + + def pack_ready(data_dir: str | Path | None) -> bool: try: - return bool(data_dir) and pack_path(data_dir).is_file() and pack_path(data_dir).stat().st_size > (1 << 20) + return bool(data_dir) and _here(pack_path(data_dir)) except OSError: return False diff --git a/strata_control/drafting_fetch.py b/strata_control/drafting_fetch.py index 6e291cd3a3..65c342c080 100644 --- a/strata_control/drafting_fetch.py +++ b/strata_control/drafting_fetch.py @@ -5,7 +5,8 @@ Only an explicit command reaches the network (strata_control/acquisition.py): a start never downloads. The drafter is incoai/Qwen3.8-Flash-Next-DFlash2 at one revision (strata_control/drafting.py has the revision, the file sizes and hashes). The 1.2 GB -safetensors file is packed (tools/dflash2_pack.py, numpy only) into the engine's 0.76 GB runtime file and then removed. +safetensors file is packed (tools/dflash2_pack.py --q4_0, numpy only) into the engine's 0.52 GB runtime file, which is checked against its pinned size and +SHA-256, and the download is then removed. A Q8 pack from an earlier Strata is used as it is. """ from __future__ import annotations @@ -103,10 +104,10 @@ def ensure(data_dir: str | Path, *, progress: Progress | None = None, cancel: th """Make the packed drafter exist under ``data_dir`` and return its path. A pack that is there is kept. Resumable: an interrupted download is continued, a file whose hash differs is deleted and the person is told. ``base_url`` / ``files`` are for tests.""" report = progress or (lambda *_: None) - out = drafting.pack_path(data_dir) + out = drafting.target_path(data_dir) if drafting.pack_ready(data_dir): report("The DFlash2 drafter is ready.", 1, 1) - return out + return drafting.pack_path(data_dir) acquisition.require("the DFlash2 drafter", "strata drafting fetch") folder = out.parent src = folder / "src" @@ -135,7 +136,12 @@ def ensure(data_dir: str | Path, *, progress: Progress | None = None, cancel: th report("Packing the DFlash2 drafter for the engine…", total, total) tmp = out.with_suffix(".tmp") try: - _packer().pack(str(have["model.safetensors"]), str(have["config.json"]), str(tmp), say=lambda *_: None) + _packer().pack(str(have["model.safetensors"]), str(have["config.json"]), str(tmp), say=lambda *_: None, q4=True) + if files is None: # the real pinned files: the pack must be the exact bytes we measured (tests pack a small synthetic file) + if tmp.stat().st_size != drafting.PACK_BYTES or transfer.sha256_file(tmp) != drafting.PACK_SHA256: + tmp.unlink(missing_ok=True) + raise DraftingError("The DFlash2 drafter was prepared but did not pass the safety check, so it was deleted. The model keeps using the MTP. " + "Try again; if it keeps happening, update Strata.") os.replace(tmp, out) except DraftingError: raise diff --git a/tests/terminal/test_drafting.py b/tests/terminal/test_drafting.py index ff09bba381..743314a9f7 100644 --- a/tests/terminal/test_drafting.py +++ b/tests/terminal/test_drafting.py @@ -409,7 +409,7 @@ class FetchAndPack(unittest.TestCase): plan = drafting_fetch.plan(self.data) self.assertEqual(plan["gb"], 1.2) self.assertIn("1.2 GB to download", plan["text"]) - self.assertIn("0.76 GB", plan["text"]) + self.assertIn("0.52 GB", plan["text"]) self.assertIn("incoai/Qwen3.8-Flash-Next-DFlash2", plan["text"]) self.assertIn("Apache-2.0", plan["text"]) self.assertIn("starts with the MTP instead", plan["text"], "and what happens if it does not fit") diff --git a/tests/terminal/test_drafting_hardware.py b/tests/terminal/test_drafting_hardware.py index b0692dbce4..2f9a06c5c1 100644 --- a/tests/terminal/test_drafting_hardware.py +++ b/tests/terminal/test_drafting_hardware.py @@ -168,6 +168,69 @@ class OneRequestAtATime(unittest.TestCase): self.assertFalse(want("dflash2", model_name=GYRO, backend="cuda", archs=["sm_121"]), "while the engine does not serve it") +class TheQ4Pack(unittest.TestCase): + """The owner chose the Q4_0 pack (522 MB, same speed as Q8, less memory): made on the person's computer from the pinned download, checked, and an old Q8 pack keeps working.""" + + def test_the_pins(self): + self.assertEqual(drafting.PACK_NAME, "qwen3.8-flash-next-dflash2.q4_0.pack") + self.assertEqual(drafting.PACK_BYTES, 522458112) + self.assertEqual(len(drafting.PACK_SHA256), 64) + self.assertEqual(drafting.PACK_GB, 0.52) + self.assertEqual(drafting.LEGACY_PACK_NAME, "qwen3.8-flash-next-dflash2.q8.pack") + + def test_an_old_q8_pack_is_used_and_never_fetched_again(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + folder = Path(tmp.name) / drafting.FOLDER + folder.mkdir() + old = folder / drafting.LEGACY_PACK_NAME + old.write_bytes(b"x" * (2 << 20)) + self.assertEqual(drafting.pack_path(tmp.name), old) + self.assertTrue(drafting.pack_ready(tmp.name)) + with serving_dflash2(): + self.assertFalse(drafting.needs_pack("dflash2", klass="blackwell", model_name=GYRO, data_dir=tmp.name)) + self.assertEqual(drafting.decide("dflash2", klass="blackwell", model_name=GYRO, data_dir=tmp.name).flags[3], str(old)) + with mock.patch.object(drafting_fetch.transfer, "download", side_effect=AssertionError("no download for a pack that is here")): + self.assertEqual(drafting_fetch.ensure(tmp.name), old) + self.assertEqual(drafting.target_path(tmp.name), folder / drafting.PACK_NAME, "a new fetch would write the Q4_0 name") + (folder / drafting.PACK_NAME).write_bytes(b"y" * (2 << 20)) + self.assertEqual(drafting.pack_path(tmp.name), folder / drafting.PACK_NAME, "when both are there, the Q4_0 pack is the one used") + + def test_the_pack_is_made_q4_and_checked_against_its_pins(self): + sys.path.insert(0, str(ROOT / "tools")) + spec = importlib.util.spec_from_file_location("t_pack3", ROOT / "tools" / "test_dflash2_pack.py") + synth = importlib.util.module_from_spec(spec) + spec.loader.exec_module(synth) + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + d = Path(tmp.name) + synth.write_safetensors(d / "m.safetensors", synth.tensors()) + (d / "c.json").write_text(json.dumps(synth.CFG)) + files = tuple((n, (d / f).stat().st_size, hashlib.sha256((d / f).read_bytes()).hexdigest()) for n, f in (("config.json", "c.json"), ("model.safetensors", "m.safetensors"))) + src = d / "data" / drafting.FOLDER / "src" + src.mkdir(parents=True) + (src / "config.json").write_bytes((d / "c.json").read_bytes()) + (src / "model.safetensors").write_bytes((d / "m.safetensors").read_bytes()) + # not the real pinned files (files=...): the pack is made Q4_0 but the real pins do not apply + with mock.patch.object(drafting, "pack_ready", lambda x: False): + out = drafting_fetch.ensure(d / "data", files=files) + blob = out.read_bytes() + self.assertEqual(out.name, drafting.PACK_NAME) + self.assertIn(b"q4_0", blob[:4096]) + # with the real list (files=None) a pack whose bytes are not the pinned ones is deleted and the words are plain + (d / "data2").mkdir() + with mock.patch.object(drafting_fetch, "_present", lambda folders, spec: {"config.json": d / "c.json", "model.safetensors": d / "m.safetensors"}), mock.patch.object(drafting, "pack_ready", lambda x: False): + with self.assertRaises(drafting_fetch.DraftingError) as ctx: + drafting_fetch.ensure(d / "data2") + self.assertIn("did not pass the safety check", str(ctx.exception)) + self.assertFalse(drafting.target_path(d / "data2").exists()) + self.assertFalse(drafting.target_path(d / "data2").with_suffix(".tmp").exists()) + # and with the pins set to what this pack really is, it is kept + pins = {"PACK_BYTES": len(blob), "PACK_SHA256": hashlib.sha256(blob).hexdigest()} + with mock.patch.object(drafting_fetch, "_present", lambda folders, spec: {"config.json": d / "c.json", "model.safetensors": d / "m.safetensors"}), mock.patch.object(drafting, "pack_ready", lambda x: False), mock.patch.multiple(drafting, **pins): + self.assertEqual(drafting_fetch.ensure(d / "data2").read_bytes(), blob) + + class TheTerminalStep(unittest.TestCase): """strata launch: the Drafting step exists only where there is something to choose, like the DeepSeek-only Speed step.""" From eb87544a58b10547cd1142b7cc1e7dd65b7cce0c Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:24:20 +0100 Subject: [PATCH 27/59] Read pictures on by default for every model that can read them; a missing picture reader no longer saves an off, and the row has no sentence (tooltip only) --- apps/host/scripts/make-r3-locales.py | 41 +++++++++++++++++++++++ apps/host/server/native-control.mjs | 8 +++-- apps/host/src/components/NativeModels.tsx | 12 ++++--- apps/host/src/lib/i18n.ts | 13 +++++-- apps/host/src/locales/r3-de.json | 3 ++ apps/host/src/locales/r3-en.json | 3 ++ apps/host/src/locales/r3-es.json | 3 ++ apps/host/src/locales/r3-fr.json | 3 ++ apps/host/src/locales/r3-ja.json | 3 ++ apps/host/src/locales/r3-ko.json | 3 ++ apps/host/src/locales/r3-pt.json | 3 ++ apps/host/src/locales/r3-ru.json | 3 ++ apps/host/src/locales/r3-zh.json | 3 ++ apps/host/tests/drafting.test.mjs | 4 +-- apps/host/tests/locale-gaps.test.mjs | 2 +- apps/host/tests/ui-r3.test.mjs | 16 +++++++++ 16 files changed, 110 insertions(+), 13 deletions(-) create mode 100644 apps/host/scripts/make-r3-locales.py create mode 100644 apps/host/src/locales/r3-de.json create mode 100644 apps/host/src/locales/r3-en.json create mode 100644 apps/host/src/locales/r3-es.json create mode 100644 apps/host/src/locales/r3-fr.json create mode 100644 apps/host/src/locales/r3-ja.json create mode 100644 apps/host/src/locales/r3-ko.json create mode 100644 apps/host/src/locales/r3-pt.json create mode 100644 apps/host/src/locales/r3-ru.json create mode 100644 apps/host/src/locales/r3-zh.json diff --git a/apps/host/scripts/make-r3-locales.py b/apps/host/scripts/make-r3-locales.py new file mode 100644 index 0000000000..47ce498ecd --- /dev/null +++ b/apps/host/scripts/make-r3-locales.py @@ -0,0 +1,41 @@ +"""Writes src/locales/r3-<lang>.json: the strings added by the owner's GUI feedback round 3 (branch f-0291-ui-r3). +Run from apps/host: python scripts/make-r3-locales.py +Every entry names all nine languages; the keys are r3_01.. in the order of S. r3-en.json is the English source. Placeholders ({0}, {1}) must be kept in every +language. A separate file keeps this work from colliding with the other catalogs (the same reason pick-, upd-, df2- and the others exist).""" +import json +import re +from pathlib import Path + +LANGS = ["en", "zh", "ja", "de", "es", "ru", "pt", "ko", "fr"] +S = [] + + +def add(en, zh, ja, de, es, ru, pt, ko, fr): + S.append(dict(en=en, zh=zh, ja=ja, de=de, es=es, ru=ru, pt=pt, ko=ko, fr=fr)) + + +# 2: the Read pictures row while the installed engine has no picture reader (a tooltip, not a paragraph) +add("Needs an engine update", + "需要更新引擎", "エンジンの更新が必要です", "Braucht ein Engine-Update", "Necesita actualizar el motor", "Нужно обновить движок", "Precisa de uma atualização do motor", "엔진 업데이트가 필요합니다", "Nécessite une mise à jour du moteur") + +#@@MORE@@ + +here = Path(__file__).resolve().parent.parent / "src" / "locales" +NBSP = " " + + +def french(text): + text = re.sub(r"(?<=[A-Za-zÀ-ſ])'(?=[A-Za-zÀ-ſ{])", "’", text) + text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text) + text = re.sub(r"(?<=[\d}]) %", NBSP + "%", text) + return text + + +for lang in LANGS: + data = {} + for i, entry in enumerate(S): + text = entry[lang] + assert sorted(re.findall(r"\{\d+\}", entry["en"])) == sorted(re.findall(r"\{\d+\}", text)), (lang, entry["en"], text) + data[f"r3_{i + 1:02d}"] = french(text) if lang == "fr" else text + (here / f"r3-{lang}.json").write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") +print("written", len(S), "strings in", len(LANGS), "languages") diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index b1cb08636e..fce4661781 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -197,7 +197,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp const note=engineStep?.summaryNote(); const finalResult=engineStep?job.result:result; if(note)return {...finalResult,summary:note}; - if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision,...(typeof args.drafting==='string'?{values:{drafting:args.drafting}}:{})});} + if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision,...(args.visionUnavailable===true?{visionUnavailable:true}:{}),...(typeof args.drafting==='string'?{values:{drafting:args.drafting}}:{})});} return finalResult; } } @@ -270,8 +270,10 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} return Math.trunc(Math.max(300,Math.min(ceiling,Math.max(ready,sized)))); } function buildConfig(args,config){ - const vision=ownEngine(config)?undefined:runtimeVision(config,args.vision); /* DeepSeek has its own picture tower: its picture setting is the --vision flag setup wrote */ - const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{}; + /* `visionUnavailable`: this engine has no picture reader, so the run goes without pictures but nothing is saved: the model's own setting stays what the person had (it used to save "off", and the model stayed off after the engine got the reader). */ + const noReader=args.visionUnavailable===true; + const vision=ownEngine(config)?undefined:runtimeVision(config,noReader?'no':args.vision); /* DeepSeek has its own picture tower: its picture setting is the --vision flag setup wrote */ + const visionPreferences=args.vision!==undefined&&!noReader?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{}; /* The engine options the person set by hand (user_args, and what they wrote into "args" since the last write) go over everything the app generates, and an explicit GPU-memory reserve (the Expert setting, user_args, a value they wrote) is never replaced by the safety default (#3215 #3270 #3216). */ const values0=args.values??{},cleared='vram_reserve_mib' in values0&&(values0.vram_reserve_mib===null||values0.vram_reserve_mib===''),base0=cleared?{...config,vram_reserve_mib:undefined,[USER_KEY]:setUserFlag(config[USER_KEY],'--vram-reserve-mib',null)}:config; diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index bbba9741f5..eb879a7d2b 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -108,6 +108,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const job = native?.jobs.find(j => j.id === jobId && selectedJob(j)) ?? native?.jobs.filter(j => ['load', 'install'].includes(j.kind) && selectedJob(j)).at(-1); const noFit = selectedSize?.on_this_pc === 'does not fit'; + // This model can read pictures but the installed engine has no picture reader: pictures run off for now, nothing is saved, and the row says nothing wordy. + const noReader = !!selectedSize?.imagesCapable && !selectedSize.images; // Graphics cards (strata_control/gpu_fit.py: the one rule of the app, the Terminal and setup): the recommended option is pre-selected, the person may pick another // A card a loaded model already uses (a second model on it usually does not fit): said on its row, and not the pre-selected one while another is free. const usedBy = (cards: number[]) => (native?.instances ?? []).filter(i => i.status !== 'error' && i.model !== selectedSize?.id && i.gpus.some(g => cards.includes(g))).map(i => i.label); @@ -128,7 +130,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const draftingChoices = selectedSize ? draftingOptions(selectedSize.sourceFamily ?? selectedFamily?.family, native?.capabilities?.dflash2) : null; const draftingWords: Record<string, string> = { auto: 'Auto (recommended)', mtp: 'MTP', dflash2: 'DFlash2', off: 'Off' }; const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(cardsGpus.length > 1 ? { gpus: cardsGpus.join(',') } : cardsGpus.length === 1 ? { gpu: cardsGpus[0] } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, cardsGpus.join(','), expert, multiple]); - const downloadValues = { ...values, ...(draftingChoices ? { drafting } : {}), vision: selectedSize?.images && vision !== 'no' ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no' }; + const downloadValues = { ...values, ...(draftingChoices ? { drafting } : {}), vision: selectedSize?.images && vision !== 'no' ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}) }; useEffect(() => { if (!native?.catalog || family) return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const have = new Set((native.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const installedFamily = families.find(f => f.sizes.some(s => have.has(s.id))); const f = loadedFamily ?? installedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) { setFamily(f.family); @@ -152,8 +154,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine if (installed) { if (installed.context) setContext(installed.context); - // Off only when the person turned it off (a saved choice); a model prepared without the picture files (images 'off') still starts with it ON. - setVision(installed.visionEnabled === false ? 'no' : installed.visionDevice ?? (installed.images && installed.images !== 'off' ? installed.images : 'yes')); + // Off only when the person turned it off (a saved choice on a model that has the picture files); a model prepared without them (images 'off', or an old "off" saved while the engine had no reader) starts with it ON. + setVision(installed.visionEnabled === false && installed.visionPrepared !== false ? 'no' : installed.visionDevice ?? (installed.images && installed.images !== 'off' ? installed.images : 'yes')); setKv(installed.kv ?? 'int8'); setLowRam(installed.lowRamMode ?? 'auto'); setDrafting(installed.drafting ?? 'auto'); @@ -183,7 +185,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine } } async function load() { if (!selectedSize) return; await perform(async () => { if (installed?.ready && context === installed.context && (!selectedSize?.images || vision === 'no' || installed.images && installed.images !== 'off') && (!installed.kv || kv === installed.kv || kv === tunedNow?.fields.kv) && (lowRam === (installed.lowRamMode ?? 'auto') || lowRam === tunedNow?.fields.lowRam)) { - const result = await nativeAction<NativeJob>('operations', { kind: 'load', args: { model: selectedSize.id, resourceProfile, vision: selectedSize?.images ? vision : 'no', multiple: expert && multiple, ...(draftingChoices ? { values: { drafting } } : {}), ...(roleCards.length > 1 ? (roles && customRoles ? { gpuRoles: effectiveRoles, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : cardsGpus.length ? { gpus: cardsGpus, gpusFromRecommendation: true, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : {}) : {}) } }); + const result = await nativeAction<NativeJob>('operations', { kind: 'load', args: { model: selectedSize.id, resourceProfile, vision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), multiple: expert && multiple, ...(draftingChoices ? { values: { drafting } } : {}), ...(roleCards.length > 1 ? (roles && customRoles ? { gpuRoles: effectiveRoles, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : cardsGpus.length ? { gpus: cardsGpus, gpusFromRecommendation: true, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : {}) : {}) } }); setJobId(result.id); } else @@ -218,7 +220,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(loadedSelected?.metrics?.engine?.drafting_note ? <p className="small muted native-spill-note">{tr(String(loadedSelected.metrics.engine.drafting_note))}</p> : null)} {roleCards.length > 1 ? <GpuRoles cards={roleCards} roles={effectiveRoles} custom={customRoles} recommendedRoles={recommended.roles} vendor={engineVendor} disabled={!!active} onChange={changeRoles} onBack={() => setRoles(null)} memoryGb={selectedSize ? memoryNeeded(selectedSize) || null : null} ramGb={pcRam} spillGb={selectedSize ? fitOn(selectedSize, fitHardware).spillGb : 0} usedBy={i => usedBy([i])}/> : null} {tr(roleCards.length > 1 && (native?.hardware?.gpus ?? []).length > roleCards.length ? <p className="small muted native-cards__note">{tr('Not used: {0} (another make of graphics card than this engine drives).', [(native?.hardware?.gpus ?? []).filter(g => !roleCards.some(r => r.index === g.index && r.vendor === g.vendor)).map(g => g.name).join(', ')])}</p> : null)} - {tr(selectedSize?.images ? <><div className="native-image-reading"><label><input type="checkbox" checked={vision !== 'no'} disabled={!selectedSize?.images || !!active} onChange={e => setVision(e.target.checked ? 'yes' : 'no')}/><span><strong>{tr("Read pictures ")}<small>{tr("On by default")}</small></strong><small>{tr("Understand photos, screenshots and charts. The picture files download automatically. Turn it off to save memory.")}</small></span></label>{tr(expert && vision !== 'no' ? <Select ariaLabel={tr("Image encoder device")} value={vision === 'yes' ? 'yes' : vision} options={[{ value: 'yes', label: 'Automatic' }, { value: 'gpu', label: 'GPU' }, { value: 'cpu', label: 'CPU' }]} onChange={setVision}/> : null)}</div>{tr(vision !== 'no' && installed?.ready && installed.visionPrepared === false ? <div className="native-vision-missing" role="status"><span>{tr("Picture reading needs a few more files that are not on this computer yet.")}</span><Btn size="sm" disabled={pending || !!active} onClick={() => void download()}>{tr("Download picture-reading files")}</Btn></div> : null)}</> : null)} + {tr(selectedSize?.images || noReader ? <><div className="native-image-reading"><label title={noReader ? tr("Needs an engine update") : undefined}><input type="checkbox" checked={!noReader && vision !== 'no'} disabled={noReader || !!active} onChange={e => setVision(e.target.checked ? 'yes' : 'no')}/><span><strong>{tr("Read pictures ")}{tr(noReader ? null : <small>{tr("On by default")}</small>)}</strong>{tr(noReader ? null : <small>{tr("Understand photos, screenshots and charts. The picture files download automatically. Turn it off to save memory.")}</small>)}</span></label>{tr(expert && vision !== 'no' ? <Select ariaLabel={tr("Image encoder device")} value={vision === 'yes' ? 'yes' : vision} options={[{ value: 'yes', label: 'Automatic' }, { value: 'gpu', label: 'GPU' }, { value: 'cpu', label: 'CPU' }]} onChange={setVision}/> : null)}</div>{tr(vision !== 'no' && installed?.ready && installed.visionPrepared === false ? <div className="native-vision-missing" role="status"><span>{tr("Picture reading needs a few more files that are not on this computer yet.")}</span><Btn size="sm" disabled={pending || !!active} onClick={() => void download()}>{tr("Download picture-reading files")}</Btn></div> : null)}</> : null)} </> : null)} <EngineWarning native={native}/> <EngineUpdateCard native={native} busy={!!active}/> diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index edc2c9c7c0..d0cd3e06b7 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -86,6 +86,15 @@ import upd_ru from '../locales/upd-ru.json'; import upd_pt from '../locales/upd-pt.json'; import upd_ko from '../locales/upd-ko.json'; import upd_fr from '../locales/upd-fr.json'; +import r3_en from '../locales/r3-en.json'; +import r3_zh from '../locales/r3-zh.json'; +import r3_ja from '../locales/r3-ja.json'; +import r3_de from '../locales/r3-de.json'; +import r3_es from '../locales/r3-es.json'; +import r3_ru from '../locales/r3-ru.json'; +import r3_pt from '../locales/r3-pt.json'; +import r3_ko from '../locales/r3-ko.json'; +import r3_fr from '../locales/r3-fr.json'; import base_zh from '../locales/zh.json'; import base_ja from '../locales/ja.json'; import base_de from '../locales/de.json'; @@ -100,8 +109,8 @@ export type Language=typeof LANGUAGES[number]['value']; /* The Tune model dialog's strings live in tune-<lang>.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ /* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-<lang>.json for the same reason. */ /* The strings that had no key in the files above (#3479, #3825) and the 0.2.4.3 fixes live in fix-<lang>.json (scripts/make-fix-locales.py). */ -const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en,...pick_en,...df2_en,...upd_en}; -const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh,...ui_zh,...engine_zh,...pick_zh,...df2_zh,...upd_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja,...ui_ja,...engine_ja,...pick_ja,...df2_ja,...upd_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de,...ui_de,...engine_de,...pick_de,...df2_de,...upd_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es,...ui_es,...engine_es,...pick_es,...df2_es,...upd_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru,...ui_ru,...engine_ru,...pick_ru,...df2_ru,...upd_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt,...ui_pt,...engine_pt,...pick_pt,...df2_pt,...upd_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko,...ui_ko,...engine_ko,...pick_ko,...df2_ko,...upd_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr,...gh_fr,...ui_fr,...engine_fr,...pick_fr,...df2_fr,...upd_fr}] as Record<string,string>[]; +const english:Record<string,string>={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en,...pick_en,...df2_en,...upd_en,...r3_en}; +const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh,...ui_zh,...engine_zh,...pick_zh,...df2_zh,...upd_zh,...r3_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja,...ui_ja,...engine_ja,...pick_ja,...df2_ja,...upd_ja,...r3_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de,...ui_de,...engine_de,...pick_de,...df2_de,...upd_de,...r3_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es,...ui_es,...engine_es,...pick_es,...df2_es,...upd_es,...r3_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru,...ui_ru,...engine_ru,...pick_ru,...df2_ru,...upd_ru,...r3_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt,...ui_pt,...engine_pt,...pick_pt,...df2_pt,...upd_pt,...r3_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko,...ui_ko,...engine_ko,...pick_ko,...df2_ko,...upd_ko,...r3_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr,...gh_fr,...ui_fr,...engine_fr,...pick_fr,...df2_fr,...upd_fr,...r3_fr}] as Record<string,string>[]; const catalogs:Record<Language,Record<string,string>>={en:english,zh,ja,de,fr,es,ru,pt,ko}; const entities:Record<string,string>={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'}; const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole); diff --git a/apps/host/src/locales/r3-de.json b/apps/host/src/locales/r3-de.json new file mode 100644 index 0000000000..23878fc1bb --- /dev/null +++ b/apps/host/src/locales/r3-de.json @@ -0,0 +1,3 @@ +{ + "r3_01": "Braucht ein Engine-Update" +} diff --git a/apps/host/src/locales/r3-en.json b/apps/host/src/locales/r3-en.json new file mode 100644 index 0000000000..d859590676 --- /dev/null +++ b/apps/host/src/locales/r3-en.json @@ -0,0 +1,3 @@ +{ + "r3_01": "Needs an engine update" +} diff --git a/apps/host/src/locales/r3-es.json b/apps/host/src/locales/r3-es.json new file mode 100644 index 0000000000..0e6d7be9b9 --- /dev/null +++ b/apps/host/src/locales/r3-es.json @@ -0,0 +1,3 @@ +{ + "r3_01": "Necesita actualizar el motor" +} diff --git a/apps/host/src/locales/r3-fr.json b/apps/host/src/locales/r3-fr.json new file mode 100644 index 0000000000..53731a9270 --- /dev/null +++ b/apps/host/src/locales/r3-fr.json @@ -0,0 +1,3 @@ +{ + "r3_01": "Nécessite une mise à jour du moteur" +} diff --git a/apps/host/src/locales/r3-ja.json b/apps/host/src/locales/r3-ja.json new file mode 100644 index 0000000000..f86b5c9eb1 --- /dev/null +++ b/apps/host/src/locales/r3-ja.json @@ -0,0 +1,3 @@ +{ + "r3_01": "エンジンの更新が必要です" +} diff --git a/apps/host/src/locales/r3-ko.json b/apps/host/src/locales/r3-ko.json new file mode 100644 index 0000000000..18d188efd0 --- /dev/null +++ b/apps/host/src/locales/r3-ko.json @@ -0,0 +1,3 @@ +{ + "r3_01": "엔진 업데이트가 필요합니다" +} diff --git a/apps/host/src/locales/r3-pt.json b/apps/host/src/locales/r3-pt.json new file mode 100644 index 0000000000..98f2ebc5ec --- /dev/null +++ b/apps/host/src/locales/r3-pt.json @@ -0,0 +1,3 @@ +{ + "r3_01": "Precisa de uma atualização do motor" +} diff --git a/apps/host/src/locales/r3-ru.json b/apps/host/src/locales/r3-ru.json new file mode 100644 index 0000000000..b50627bcba --- /dev/null +++ b/apps/host/src/locales/r3-ru.json @@ -0,0 +1,3 @@ +{ + "r3_01": "Нужно обновить движок" +} diff --git a/apps/host/src/locales/r3-zh.json b/apps/host/src/locales/r3-zh.json new file mode 100644 index 0000000000..ce34e10eca --- /dev/null +++ b/apps/host/src/locales/r3-zh.json @@ -0,0 +1,3 @@ +{ + "r3_01": "需要更新引擎" +} diff --git a/apps/host/tests/drafting.test.mjs b/apps/host/tests/drafting.test.mjs index 6d09db21d4..6c23784c8a 100644 --- a/apps/host/tests/drafting.test.mjs +++ b/apps/host/tests/drafting.test.mjs @@ -147,9 +147,9 @@ test('the DFlash2 drafter is fetched only by the Models screen own Load: a resta assert.doesNotMatch(tune, /values:/, 'the tuning run loads without a choice'); }); -test('the paragraph under the dropdown quotes the measurements without a verdict', () => { +test('the paragraph under the dropdown is gone (owner, 11-01: people who care know what to do); the catalog words carry no verdict', () => { const screen = read('../src/components/NativeModels.tsx'); - for (const part of ['7.8% faster than MTP on 19 short prompts', '1.1% faster on long thinking', 'faster on 21 of 23 prompts', 'the answers were identical']) assert.ok(screen.includes(part), part); + for (const part of ['7.8% faster than MTP on 19 short prompts', '1.1% faster on long thinking', 'faster on 21 of 23 prompts', 'the answers were identical']) assert.ok(!screen.includes(part), part); const en = JSON.parse(read('../src/locales/df2-en.json')); for (const text of Object.values(en)) for (const word of ['recommend', 'best ', 'better', 'should']) assert.ok(!text.toLowerCase().includes(word), `${word} in "${text.slice(0, 50)}"`); }); diff --git a/apps/host/tests/locale-gaps.test.mjs b/apps/host/tests/locale-gaps.test.mjs index 7d2772d763..d19654f9e0 100644 --- a/apps/host/tests/locale-gaps.test.mjs +++ b/apps/host/tests/locale-gaps.test.mjs @@ -12,7 +12,7 @@ const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64 test('every tr("...") literal and every command hint has a key in the English catalog, so no language is stuck in English (#3479)', async () => { const known = new Set(); - for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en', 'ui-en', 'engine-en', 'pick-en', 'df2-en', 'upd-en']) for (const v of Object.values(await read(name))) known.add(String(v)); + for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en', 'ui-en', 'engine-en', 'pick-en', 'df2-en', 'upd-en', 'r3-en']) for (const v of Object.values(await read(name))) known.add(String(v)); const missing = []; const scan = async dir => { for (const entry of await readdir(dir, { withFileTypes: true })) { diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index 4deb94fbf8..d33427edbf 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -12,3 +12,19 @@ test('1: the Models page carries no DFlash2 paragraph, no per-card line and no p assert.ok(!/engine installed here does not include the picture reader/.test(models), 'the picture-reader sentence is gone'); assert.match(models, /<Select ariaLabel=\{tr\("Drafting"\)\}/, 'the dropdown stays'); }); + +test('2: pictures are on by default; a missing reader says nothing wordy and saves nothing', () => { + const host = read('server/native-control.mjs'); + // The row is shown for every model that can read pictures; without the reader it is off, disabled and carries a tooltip, no paragraph. + assert.match(models, /const noReader = !!selectedSize\?\.imagesCapable && !selectedSize\.images/); + assert.match(models, /selectedSize\?\.images \|\| noReader \? <><div className="native-image-reading"><label title=\{noReader \? tr\("Needs an engine update"\) : undefined\}>/); + assert.match(models, /checked=\{!noReader && vision !== 'no'\} disabled=\{noReader \|\| !!active\}/); + assert.match(models, /else \{\s*setVision\('yes'\);|setVision\('yes'\);/, 'a model that is not downloaded starts with pictures on'); + // A load without a reader used to save "off" (ui_vision_enabled false), and the model stayed off after the engine got the reader. + assert.match(models, /\.\.\.\(noReader \? \{ visionUnavailable: true \} : \{\}\)/); + assert.match(host, /const noReader=args\.visionUnavailable===true;/); + assert.match(host, /const visionPreferences=args\.vision!==undefined&&!noReader\?/, 'nothing is saved when the reader is missing'); + assert.match(host, /runtimeVision\(config,noReader\?'no':args\.vision\)/); + // An "off" that sits on a model without the picture files is not a choice of the person: it starts on. + assert.match(models, /installed\.visionEnabled === false && installed\.visionPrepared !== false \? 'no'/); +}); From 0627b1ec63f246e3442b55e4e13ac0f9af68a278 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:25:17 +0100 Subject: [PATCH 28/59] This computer with a model loaded: only the free memory is left (no hardware line, name, Loaded, It takes about, numbers or SSD line); a version that fits says nothing --- apps/host/src/components/PcFitCard.tsx | 31 +++++-------- apps/host/src/styles/liquid.css | 63 -------------------------- apps/host/tests/pc-card.test.mjs | 23 +++++----- 3 files changed, 23 insertions(+), 94 deletions(-) diff --git a/apps/host/src/components/PcFitCard.tsx b/apps/host/src/components/PcFitCard.tsx index 312769366c..0c9267187b 100644 --- a/apps/host/src/components/PcFitCard.tsx +++ b/apps/host/src/components/PcFitCard.tsx @@ -18,34 +18,27 @@ function FreeMeter({ label, total, free }: { label: string; total: number; free: } /** - * "This computer": how much graphics memory and RAM is free right now, and, for the loaded model, what it takes of each. The SSD only - * appears where the model does not fit in memory (how much is read from it). Before anything is loaded the card says what the chosen - * version would take. (The n-gram table, which always sits on the SSD, is not counted.) + * "This computer": how much graphics memory and RAM is free right now. While a model is loaded that is all the card shows: the hardware line, the model's + * name, "Loaded", what it takes and the SSD line are gone (owner, 11-01: the page already says what is loaded), except one calm sentence when the loaded + * model really reads part of itself from the SSD. Before anything is loaded the card says what the chosen version would take, and the SSD only where the + * version does not fit in memory (how much is read from it); a version that fits says nothing. (The n-gram table, which always sits on the SSD, is not counted.) */ export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null, diskGb = null, live = null, loaded = [], selectedLoaded = false }: { gpuName?: string | null; ramGb: number | null; vramGb: number; fit: Fit | null; inUse?: { ramGb: number; vramGb: number } | null; diskGb?: number | null; live?: PcLive | null; loaded?: PcLoaded[]; selectedLoaded?: boolean }) { const showFit = !!fit?.known && !selectedLoaded; - return <section className="st-card pc-card" data-loaded={loaded.length ? true : undefined}> - <div><h2 className="h4">{tr("This computer")}</h2> - <p className="small muted">{tr(gpuName ? tr("{0} · {1} graphics memory", [gpuName, gb(vramGb)]) : tr("No supported graphics card reported by this installation."))}{ramGb ? tr(" · {0} RAM", [gb(ramGb)]) : ''}</p></div> - {tr(loaded.map(m => <div className="pc-loaded" key={m.id}> - <div className="pc-loaded__head"><i aria-hidden="true"/><strong>{tr(m.label)}</strong><span className="pc-tag">{tr("Loaded")}</span></div> - <p className="small muted">{tr("It takes about")}</p> - <dl className="pc-takes"> - {tr(m.fit.known && vramGb > 0 ? <div><dt>{tr("Graphics memory")}</dt><dd>{about(m.fit.vramUseGb)}</dd></div> : null)} - {tr(m.fit.known && ramGb ? <div><dt>{tr("RAM")}</dt><dd>{about(m.fit.ramUseGb)}</dd></div> : null)} - {tr(m.fit.known && m.fit.spillGb >= 1 ? <div><dt>{tr("SSD")}</dt><dd>{about(m.fit.spillGb)}</dd></div> : null)} - </dl> - {tr(m.fit.known && m.fit.spillGb < 1 ? <p className="pc-note">{tr("SSD: not needed")}</p> : null)} - {tr(m.fit.known && m.fit.spillGb >= 1 ? <p className="pc-note">{tr("About {0} GB will be read from the SSD, so answers can be a little slower.", [Math.round(m.fit.spillGb)])}{tr(live?.diskReadGbs && live.diskReadGbs >= 0.05 ? tr(" Reading from your SSD now: {0}", [`${live.diskReadGbs.toFixed(1)} GB/s`]) : '')}</p> : null)} - </div>))} + const isLoaded = loaded.length > 0; + const streamed = Math.max(0, ...loaded.map(m => (m.fit.known ? m.fit.spillGb : 0))); + return <section className="st-card pc-card" data-loaded={isLoaded ? true : undefined}> + {isLoaded ? <h2 className="h4">{tr("This computer")}</h2> : <div><h2 className="h4">{tr("This computer")}</h2> + <p className="small muted">{tr(gpuName ? tr("{0} · {1} graphics memory", [gpuName, gb(vramGb)]) : tr("No supported graphics card reported by this installation."))}{ramGb ? tr(" · {0} RAM", [gb(ramGb)]) : ''}</p></div>} {tr(live && (live.freeVramGb !== null || live.freeRamGb !== null) ? <div className="pc-free"> <h3 className="pc-label">{tr("Free right now")}</h3> {tr(live.freeVramGb !== null && vramGb > 0 ? <FreeMeter label="Graphics memory" total={live.vramTotalGb ?? vramGb} free={live.freeVramGb}/> : null)} {tr(live.freeRamGb !== null && ramGb ? <FreeMeter label="RAM" total={ramGb} free={live.freeRamGb}/> : null)} </div> : null)} + {tr(isLoaded && streamed >= 1 ? <p className="pc-note">{tr("About {0} GB will be read from the SSD, so answers can be a little slower.", [Math.round(streamed)])}{tr(live?.diskReadGbs && live.diskReadGbs >= 0.05 ? tr(" Reading from your SSD now: {0}", [`${live.diskReadGbs.toFixed(1)} GB/s`]) : '')}</p> : null)} {tr(inUse ? <p className="xs muted">{tr("Models that stay loaded use about {0} GB of RAM and {1} GB of this card’s memory.", [inUse.ramGb, inUse.vramGb])}</p> : null)} - {tr(showFit && !selectedLoaded && !loaded.length && fit!.vramUseGb + fit!.ramUseGb > 0 ? <p className="pc-note">{tr("This version would take about {0} of graphics memory and {1} of RAM.", [about(fit!.vramUseGb), about(fit!.ramUseGb)])}</p> : null)} + {tr(showFit && !isLoaded && fit!.vramUseGb + fit!.ramUseGb > 0 ? <p className="pc-note">{tr("This version would take about {0} of graphics memory and {1} of RAM.", [about(fit!.vramUseGb), about(fit!.ramUseGb)])}</p> : null)} {tr(diskGb ? <p className="pc-note">{tr("Needs about {0} GB of free disk space. What does not fit in memory is read from your SSD.", [Math.round(diskGb)])}</p> : null)} - {tr(showFit && (diskGb ? fit!.spillGb >= 1 : true) ? <p className="pc-note">{tr(fit!.spillGb >= 1 ? 'About {0} GB will be read from the SSD, so answers can be a little slower.' : 'Fits fully in memory.', [Math.round(fit!.spillGb)])}</p> : null)} + {tr(showFit && fit!.spillGb >= 1 ? <p className="pc-note">{tr("About {0} GB will be read from the SSD, so answers can be a little slower.", [Math.round(fit!.spillGb)])}</p> : null)} </section>; } diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index f62530eff5..721bc7d038 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -1245,66 +1245,3 @@ body { .pc-meter[data-low] .pc-meter__track i { background: var(--st-warn); } -.pc-loaded { - display: flex; - flex-direction: column; - gap: 8px; - padding: 12px 14px; - border: 1px solid var(--st-accent-surface-edge); - border-radius: var(--st-r-md); - background: var(--st-accent-tint); - animation: st-enter var(--st-t-local) var(--st-ease-enter) both; - --st-from-y: 4px; -} -.pc-loaded p { - margin: 0; -} -.pc-loaded__head { - display: flex; - align-items: center; - gap: 8px; - min-width: 0; -} -.pc-loaded__head strong { - min-width: 0; - overflow-wrap: anywhere; -} -.pc-loaded__head i { - flex: none; - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--st-accent); -} -.pc-tag { - margin-left: auto; - padding: 0 8px; - border-radius: var(--st-r-pill); - font-size: var(--st-fs-xs); - font-weight: 600; - line-height: 20px; - color: var(--st-accent-text); - box-shadow: inset 0 0 0 1px var(--st-accent-surface-edge); -} -.pc-takes { - display: flex; - flex-wrap: wrap; - gap: 8px 24px; - margin: 0; -} -.pc-takes div { - display: flex; - flex-direction: column; - gap: 2px; -} -.pc-takes dt { - font-size: var(--st-fs-xs); - color: var(--st-ink-muted); -} -.pc-takes dd { - margin: 0; - font-size: var(--st-fs-lg); - font-weight: 700; - letter-spacing: -0.01em; - font-variant-numeric: tabular-nums; -} diff --git a/apps/host/tests/pc-card.test.mjs b/apps/host/tests/pc-card.test.mjs index 2e8629888a..1e9d906eeb 100644 --- a/apps/host/tests/pc-card.test.mjs +++ b/apps/host/tests/pc-card.test.mjs @@ -27,27 +27,26 @@ test('free graphics memory and free RAM come first, as real readings', () => { assert.doesNotMatch(card({ fit: fit(0), live: null }), /Free right now/, 'no readings: no invented numbers'); }); -test('the SSD appears only when the model does not fit in memory, with how much is read from it', () => { +test('the SSD appears only when the model does not fit in memory, with how much is read from it; a version that fits says nothing', () => { setTranslationLanguage('en'); assert.doesNotMatch(card({ fit: fit(0), live }), /SSD/); - assert.match(card({ fit: fit(0), live }), /Fits fully in memory\./); + assert.doesNotMatch(card({ fit: fit(0), live }), /Fits fully in memory/, 'no "Fits" words (owner, 11-01)'); assert.match(card({ fit: fit(30), live }), /About 30 GB will be read from the SSD/); }); -test('a loaded model changes the card: it says Loaded and what the model takes of graphics memory, RAM and SSD', () => { +test('a loaded model leaves the free memory and nothing else: no hardware line, no name, no Loaded, no "It takes about", no numbers, no SSD line', () => { setTranslationLanguage('en'); const fits = card({ fit: fit(0), live, loaded: [{ id: 'iq3_s', label: 'Qwen3.8-Flash-Next · IQ3_S', fit: fit(0) }], selectedLoaded: true }); - assert.match(fits, /pc-loaded/); - assert.match(fits, /Qwen3\.8-Flash-Next · IQ3_S/); - assert.match(fits, /Loaded/); - assert.match(fits, /<dt>Graphics memory<\/dt><dd>12 GB<\/dd>/); - assert.match(fits, /<dt>RAM<\/dt><dd>44 GB<\/dd>/); - assert.doesNotMatch(fits, /<dt>SSD<\/dt>/, 'it fits: no SSD row'); - assert.match(fits, /SSD: not needed/, 'the SSD line has its label even when nothing is read from it'); + assert.match(fits, /This computer/); + assert.match(fits, /Free right now/); + assert.match(fits, /Graphics memory<\/span><b>10\.3 GB free<\/b>/); + for (const gone of [/RTX 5070/, /graphics memory · /, /Qwen3\.8-Flash-Next/, /Loaded/, /It takes about/, /<dl/, /<dt>/, /SSD/, /pc-loaded/]) assert.doesNotMatch(fits, gone, String(gone)); + // A loaded model that really streams from the SSD keeps one calm sentence; nothing else comes back. const spills = card({ fit: fit(18), live: { ...live, diskReadGbs: 1.2 }, loaded: [{ id: 'q', label: 'Qwen3.8-Flash-Next · UD-Q4_K_XL', fit: fit(18, 12, 53) }], selectedLoaded: true }); - assert.match(spills, /<dt>SSD<\/dt><dd>18 GB<\/dd>/); + assert.match(spills, /About 18 GB will be read from the SSD/); assert.match(spills, /Reading from your SSD now: 1\.2 GB\/s/); - assert.doesNotMatch(spills, /This version would take/, 'the loaded block already says it'); + for (const gone of [/<dl/, /<dt>/, /Loaded/, /It takes about/, /RTX 5070/]) assert.doesNotMatch(spills, gone, String(gone)); + assert.doesNotMatch(spills, /This version would take/); }); test('before anything is loaded the card says what the chosen version would take', () => { From 943f29853a374042d6b7b65ec1616d7ace2f36d5 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:27:47 +0100 Subject: [PATCH 29/59] Version list: our recommended versions first and tagged Recommended, no Fits word anywhere, SSD streaming - will run slower for versions that do not fully fit; NVFP4 no longer says Doesn't fit (the fit follows graphics memory, RAM and SSD; Doesn't fit is left for no graphics card and under 16 GB) --- apps/host/scripts/make-r3-locales.py | 5 +++ apps/host/src/components/NativeModels.tsx | 7 +-- apps/host/src/components/VersionPicker.tsx | 21 ++++----- apps/host/src/lib/native-fit.ts | 38 +++++++++++----- apps/host/src/locales/r3-de.json | 3 +- apps/host/src/locales/r3-en.json | 3 +- apps/host/src/locales/r3-es.json | 3 +- apps/host/src/locales/r3-fr.json | 3 +- apps/host/src/locales/r3-ja.json | 3 +- apps/host/src/locales/r3-ko.json | 3 +- apps/host/src/locales/r3-pt.json | 3 +- apps/host/src/locales/r3-ru.json | 3 +- apps/host/src/locales/r3-zh.json | 3 +- apps/host/tests/version-picker.test.mjs | 52 ++++++++++++++++++---- 14 files changed, 109 insertions(+), 41 deletions(-) diff --git a/apps/host/scripts/make-r3-locales.py b/apps/host/scripts/make-r3-locales.py index 47ce498ecd..e2bc3ae741 100644 --- a/apps/host/scripts/make-r3-locales.py +++ b/apps/host/scripts/make-r3-locales.py @@ -18,6 +18,11 @@ def add(en, zh, ja, de, es, ru, pt, ko, fr): add("Needs an engine update", "需要更新引擎", "エンジンの更新が必要です", "Braucht ein Engine-Update", "Necesita actualizar el motor", "Нужно обновить движок", "Precisa de uma atualização do motor", "엔진 업데이트가 필요합니다", "Nécessite une mise à jour du moteur") +# 5: the one word the version list writes for a version that does not fully fit in memory +add("SSD streaming · will run slower", + "SSD 流式读取 · 运行会更慢", "SSD ストリーミング · 動作は遅くなります", "SSD-Streaming · läuft langsamer", "Streaming desde el SSD · irá más lento", "Потоковая подгрузка с SSD · будет работать медленнее", + "Streaming do SSD · vai rodar mais devagar", "SSD 스트리밍 · 더 느리게 실행됩니다", "Streaming depuis le SSD · plus lent") + #@@MORE@@ here = Path(__file__).resolve().parent.parent / "src" / "locales" diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index eb879a7d2b..7ec99d7871 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -4,7 +4,7 @@ import { Screen } from './layout'; import { VersionPicker } from './VersionPicker'; import { FamilySwitch } from './FamilySwitch'; import { PcComputer } from './PcComputer'; -import { fitOn, memoryNeeded } from '../lib/native-fit'; +import { fitOn, memoryNeeded, versionFit } from '../lib/native-fit'; import { GpuRoles } from './GpuRoles'; import { fromLegacy, normalize as normalizeRoles, order as roleOrder, recommend as recommendRoles, rows as roleRows, sameRoles, vramOn, type RoleCard, type Roles } from '../lib/gpu-roles'; import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; @@ -107,7 +107,6 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine (j.model === selectedSize.model && j.family === selectedSize.sourceFamily)); const job = native?.jobs.find(j => j.id === jobId && selectedJob(j)) ?? native?.jobs.filter(j => ['load', 'install'].includes(j.kind) && selectedJob(j)).at(-1); - const noFit = selectedSize?.on_this_pc === 'does not fit'; // This model can read pictures but the installed engine has no picture reader: pictures run off for now, nothing is saved, and the row says nothing wordy. const noReader = !!selectedSize?.imagesCapable && !selectedSize.images; // Graphics cards (strata_control/gpu_fit.py: the one rule of the app, the Terminal and setup): the recommended option is pre-selected, the person may pick another @@ -124,6 +123,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const cardsGpus: number[] = roleCards.length > 1 ? roleOrder(effectiveRoles, roleCards) : []; const chosenCards = cardsGpus; const fitHardware = { ram_gb: pcRam ? Math.max(0, pcRam - keptRam) : pcRam, vram_gb: Math.max(0, (roleCards.length > 1 ? vramOn(effectiveRoles, roleCards) : pcVram) - keptVramOn(chosenCards)) }; + // How the chosen version sits on this computer (the same rule as the version list): the page says a word only for "SSD streaming" and "Doesn't fit". + const fitState = selectedSize ? versionFit(selectedSize, fitHardware) : 'unknown'; // A layer split written for another number of cards no longer fits: back to automatic. useEffect(() => { if (cardsGpus.length <= 1 && split !== 'auto') setSplit('auto'); }, [cardsGpus.length]); // Drafting (which drafter guesses ahead): a choice exists only for Qwen3.8-Flash-Next (the qwen and gyro families) on a computer whose engine can run DFlash2; every other model has no dropdown. @@ -210,7 +211,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine <div className="native-choice__head"><span className="native-choice__label">{tr("Version")}</span><span className="native-choice__tools"><NativePresets values={values} onApply={v => { const f = families.find(f => f.family === v.family || f.sizes.some(s => s.sourceFamily === v.family)); if (!f) return; presetPending.current = true; setFamily(f.family); setSize(f.sizes.find(s => s.model === v.model && (s.sourceFamily === v.family || f.family === v.family))?.id ?? ''); setContext(v.context ?? 32768); setVision(v.vision ?? 'no'); setKv(v.kv ?? 'int8'); setLowRam(v.low_ram ?? 'auto'); }}/><Btn icon="models" size="sm" variant="ghost" onClick={() => setManage(true)}>{tr("Manage models")}</Btn></span></div> <div className="native-version"><VersionPicker pick={native?.catalog?.recommendation} versions={selectedFamily?.sizes ?? []} details={expert} selectedId={selectedSize.id} hardware={fitHardware} downloaded={readyIds} onSelect={id => { const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/></div> - {tr(noFit ? <p className="small muted native-spill-note"><Icon name="disk" size={16}/>{tr("May run slower \u00B7 Model data can be read from SSD.")}</p> : null)} + {tr(fitState === 'ssd' ? <p className="small muted native-spill-note"><Icon name="disk" size={16}/>{tr("SSD streaming · will run slower")}</p> : fitState === 'no' ? <p className="small muted native-spill-note"><Icon name="warning" size={16}/>{tr("Doesn't fit")}</p> : null)} {tr(selectedSize?.multi_file && deepseekContextNote(context) ? <p className="small muted native-spill-note"><Icon name="info" size={16}/>{tr(deepseekContextNote(context))}</p> : null)} <div className="native-choice__row"> <div className="native-choice__col"><span className="native-choice__label">{tr("Conversation context")}</span><Select ariaLabel={tr("Conversation context")} value={String(context)} options={contextChoices(selectedSize?.multi_file ? deepseekContexts(installed?.contextMax) : native?.catalog?.contexts ?? [8192, 32768, 65536, 131072, 262144], context).map(n => ({ value: String(n), label: n % 1024 === 0 ? `${n / 1024}K` : `${n.toLocaleString()} tokens` }))} onChange={n => setContext(Number(n))}/></div> diff --git a/apps/host/src/components/VersionPicker.tsx b/apps/host/src/components/VersionPicker.tsx index c2a0d221b8..611965822a 100644 --- a/apps/host/src/components/VersionPicker.tsx +++ b/apps/host/src/components/VersionPicker.tsx @@ -5,7 +5,7 @@ import { FloatingMenu } from './FloatingMenu'; import { cx } from '../lib/format'; import { versionNote, type CatalogVersion } from '../lib/native-catalog'; import { nvfp4Version } from '../lib/native-names'; -import { fitOn, recommendedVersions, versionFit, versionGroups, PICK_NOTE, type FitHardware, type PcPick } from '../lib/native-fit'; +import { fitOn, recommendedVersions, versionFit, versionGroups, type FitHardware, type PcPick } from '../lib/native-fit'; /** The name a version goes by in the list: the quantization, with the maker only where the quantization alone would be ambiguous. */ export function versionName(v: CatalogVersion): string { @@ -25,11 +25,12 @@ const gb = (n: number) => `${Number.isInteger(n) ? n : n.toFixed(1)} GB`; const whole = (n: number) => `${Math.round(n)} GB`; /** - * Where the versions of the chosen base model are listed, each exactly once. At the top: our recommendation for this PC and the versions already - * downloaded (a downloaded version carries "Downloaded", and "Recommended" only while it is not yet downloaded). Below, folded under "More - * versions": all the others. A row is the name, small tags, whether it fits this PC ("Fits", "Fits with SSD streaming", "Doesn't fit": from the - * same fit figures as the This computer card) and the size. The maker, the memory it needs and the SSD figure are behind "Show details" - * (open from the start in Expert mode). The other base models are not in this list: they appear when picked at the top of the page. + * Where the versions of the chosen base model are listed, each exactly once. At the top: the versions we recommend (the pick for this PC first, tagged + * "Recommended") and the versions already downloaded (tagged "Downloaded"; a downloaded recommended version carries both). Below, folded under "More + * versions": all the others. A row is the name, small tags, a word only where one is needed ("SSD streaming · will run slower" for a version that does + * not fully fit in memory, "Doesn't fit" where it cannot run at all; a version that fits says nothing: see `versionFit`) and the size. The maker, the + * memory it needs and the SSD figure are behind "Show details" (open from the start in Expert mode). The other base models are not in this list: they + * appear when picked at the top of the page. */ export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnGguf, downloaded, showRecommended = true, moreLabel, pick, details: detailsOpen = false }: { /** The versions of the chosen base model. */ @@ -57,8 +58,8 @@ export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnG // Where the recommended ones are shown outside the menu, the menu holds only the others. const rows = recommendedVersions(versions, pick); const apart = new Set(showRecommended ? [] : rows.map(x => x.v.id)); - const pickId = rows.find(x => x.r.note === PICK_NOTE)?.v.id; - const { top, more } = versionGroups(versions, apart, downloaded, pickId); + const recommendedIds = rows.map(x => x.v.id); + const { top, more } = versionGroups(versions, apart, downloaded, recommendedIds); const shown = selected && !apart.has(selected.id) ? selected : undefined; // The folded part opens by itself when it holds the chosen version or when there is nothing above it. const [moreOpen, setMoreOpen] = useState(false); @@ -71,7 +72,7 @@ export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnG }; const row = (v: CatalogVersion) => { const fit = fitOn(v, hardware); - const on = v.id === selectedId, have = !!downloaded?.has(v.id), recommended = v.id === pickId && !have; + const on = v.id === selectedId, have = !!downloaded?.has(v.id), recommended = recommendedIds.includes(v.id); const state = versionFit(v, hardware); const technical = [MAKERS[v.sourceFamily], need(v, true), state === 'ssd' ? tr("Uses SSD {0} GB", [Math.round(fit.spillGb)]) : ''].filter(Boolean).join(' · '); const note = versionNote(v.model); @@ -79,7 +80,7 @@ export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnG <span className="version-row__check">{tr(on ? <Icon name="check" size={14}/> : null)}</span> <span className="version-row__body"> <span className="version-row__title"><strong>{versionName(v)}</strong>{tr(recommended || have ? <span className="version-row__tags">{tr(recommended ? <span className="version-tag version-tag--pick">{tr("Recommended")}</span> : null)}{tr(have ? <span className="version-tag version-tag--have">{tr("Downloaded")}</span> : null)}</span> : null)}</span> - {tr(state !== 'unknown' ? <span className="version-row__fit" data-fit={state}>{tr(state === 'fits' ? 'Fits' : state === 'ssd' ? 'Fits with SSD streaming' : "Doesn't fit")}</span> : null)} + {tr(state === 'ssd' || state === 'no' ? <span className="version-row__fit" data-fit={state}>{tr(state === 'ssd' ? 'SSD streaming · will run slower' : "Doesn't fit")}</span> : null)} {tr(details ? <span className="version-row__tech">{technical}{tr(note ? <><br/>{note}</> : null)}</span> : null)} </span> <span className="version-row__size">{have ? gb(v.download_gb) : tr("{0} download", [gb(v.download_gb)])}</span> diff --git a/apps/host/src/lib/native-fit.ts b/apps/host/src/lib/native-fit.ts index 0f08e96108..bee9864f78 100644 --- a/apps/host/src/lib/native-fit.ts +++ b/apps/host/src/lib/native-fit.ts @@ -90,7 +90,7 @@ export function recommendedVersions<V extends { sourceFamily: string; model: str type Row = { r: typeof RECOMMENDED[number]; v: V }; const find = (family: string, model: string) => versions.find(v => v.sourceFamily === family && v.model === model); const rows: Row[] = RECOMMENDED.map(r => ({ r, v: find(r.family, r.model) })).filter((x): x is Row => !!x.v); - if (!rows.length || !pick?.family || !pick.model) return rows; + if (!pick?.family || !pick.model) return rows; const chosen = find(pick.family, pick.model); if (!chosen) return rows; const rest = rows.filter(x => x.v !== chosen); @@ -102,27 +102,43 @@ export function recommendedVersions<V extends { sourceFamily: string; model: str } /** - * The version list as the menu shows it, for one base model: first the versions to look at (the pick for this PC, then the ones already on this - * computer, each by download size), then every other version by download size. A version is in exactly one of the two, so none is shown twice - * and none is lost; the ones in `hidden` (shown elsewhere, as on the first-run page) are left out. + * The version list as the menu shows it, for one base model: first the versions to look at (the recommended ones, in the order given, then the ones already + * on this computer, each by download size), then every other version by download size. A version is in exactly one of the two, so none is shown twice + * and none is lost; the ones in `hidden` (shown elsewhere, as on the first-run page) are left out. `recommended` is one id or several. */ -export function versionGroups<V extends { id: string; download_gb: number }>(versions: V[], hidden: ReadonlySet<string>, downloaded: ReadonlySet<string> | undefined, pickId?: string): { top: V[]; more: V[] } { +export function versionGroups<V extends { id: string; download_gb: number }>(versions: V[], hidden: ReadonlySet<string>, downloaded: ReadonlySet<string> | undefined, recommended?: string | readonly string[]): { top: V[]; more: V[] } { const seen = new Set<string>(); const list = versions.filter(v => !hidden.has(v.id) && !seen.has(v.id) && !!seen.add(v.id)); const bySize = (a: V, b: V) => a.download_gb - b.download_gb; - const pick = list.find(v => v.id === pickId); - const have = list.filter(v => v.id !== pickId && downloaded?.has(v.id)).sort(bySize); - const top = [...(pick ? [pick] : []), ...have]; + const ids = typeof recommended === 'string' ? [recommended] : [...(recommended ?? [])]; + const picked = ids.map(id => list.find(v => v.id === id)).filter((v): v is V => !!v); + const have = list.filter(v => !ids.includes(v.id) && downloaded?.has(v.id)).sort(bySize); + const top = [...picked, ...have]; const inTop = new Set(top.map(v => v.id)); return { top, more: list.filter(v => !inTop.has(v.id)).sort(bySize) }; } -/** What a version is on this computer, in the words the list shows: from the same fit figures the card uses, and the engine's own "does not fit". */ +/** + * What a version is on this computer. The list writes a word only for the two cases that need one: "SSD streaming · will run slower" (part of the + * version is read from the SSD) and "Doesn't fit". A version that fits in memory says nothing. + * + * The figures are the app's own (`fitOn`: graphics memory, then RAM, then the SSD), the same ones the This computer card uses. The catalog's + * `on_this_pc` is only a RAM comparison for the plain families (it ignores the graphics card and the SSD): it said "does not fit" for NVFP4 on a + * 12 GB card with 63 GB of RAM, which runs with the rest read from the SSD. So the engine's "does not fit" is believed in exactly two cases: + * - the version needs a graphics card and this computer has none that counts (DeepSeek-V4.1-Flash: "does not fit: it needs one or more graphics cards"); + * - this computer has less memory than anything has ever been run with (MIN_RUN_GB) and the engine says it does not fit. + * Everything else that does not fit in memory is "ssd": it runs, slower. (Not enough free disk is a different question; the download says it.) + */ export type VersionFit = 'fits' | 'ssd' | 'no' | 'unknown'; +export const MIN_RUN_GB = 16; export function versionFit(v: FitInput & { on_this_pc?: string | null }, hw: FitHardware | null | undefined): VersionFit { - if (v.on_this_pc === 'does not fit') return 'no'; + const words = String(v.on_this_pc ?? '').trim().toLowerCase(); + const engineNo = words.startsWith('does not fit'); + if (/needs? (one or more|a) graphics cards?/.test(words)) return 'no'; const fit = fitOn(v, hw); - return !fit.known ? 'unknown' : fit.spillGb >= 1 ? 'ssd' : 'fits'; + if (!fit.known) return engineNo ? 'no' : 'unknown'; + if (engineNo && Number(hw?.ram_gb) < MIN_RUN_GB) return 'no'; + return fit.spillGb >= 1 ? 'ssd' : 'fits'; } /** A card as the installer's hardware report lists it. */ diff --git a/apps/host/src/locales/r3-de.json b/apps/host/src/locales/r3-de.json index 23878fc1bb..a1c2027d8a 100644 --- a/apps/host/src/locales/r3-de.json +++ b/apps/host/src/locales/r3-de.json @@ -1,3 +1,4 @@ { - "r3_01": "Braucht ein Engine-Update" + "r3_01": "Braucht ein Engine-Update", + "r3_02": "SSD-Streaming · läuft langsamer" } diff --git a/apps/host/src/locales/r3-en.json b/apps/host/src/locales/r3-en.json index d859590676..32e5880b65 100644 --- a/apps/host/src/locales/r3-en.json +++ b/apps/host/src/locales/r3-en.json @@ -1,3 +1,4 @@ { - "r3_01": "Needs an engine update" + "r3_01": "Needs an engine update", + "r3_02": "SSD streaming · will run slower" } diff --git a/apps/host/src/locales/r3-es.json b/apps/host/src/locales/r3-es.json index 0e6d7be9b9..323b5bde72 100644 --- a/apps/host/src/locales/r3-es.json +++ b/apps/host/src/locales/r3-es.json @@ -1,3 +1,4 @@ { - "r3_01": "Necesita actualizar el motor" + "r3_01": "Necesita actualizar el motor", + "r3_02": "Streaming desde el SSD · irá más lento" } diff --git a/apps/host/src/locales/r3-fr.json b/apps/host/src/locales/r3-fr.json index 53731a9270..3c3235f5f1 100644 --- a/apps/host/src/locales/r3-fr.json +++ b/apps/host/src/locales/r3-fr.json @@ -1,3 +1,4 @@ { - "r3_01": "Nécessite une mise à jour du moteur" + "r3_01": "Nécessite une mise à jour du moteur", + "r3_02": "Streaming depuis le SSD · plus lent" } diff --git a/apps/host/src/locales/r3-ja.json b/apps/host/src/locales/r3-ja.json index f86b5c9eb1..391ccd264f 100644 --- a/apps/host/src/locales/r3-ja.json +++ b/apps/host/src/locales/r3-ja.json @@ -1,3 +1,4 @@ { - "r3_01": "エンジンの更新が必要です" + "r3_01": "エンジンの更新が必要です", + "r3_02": "SSD ストリーミング · 動作は遅くなります" } diff --git a/apps/host/src/locales/r3-ko.json b/apps/host/src/locales/r3-ko.json index 18d188efd0..1501f01a4a 100644 --- a/apps/host/src/locales/r3-ko.json +++ b/apps/host/src/locales/r3-ko.json @@ -1,3 +1,4 @@ { - "r3_01": "엔진 업데이트가 필요합니다" + "r3_01": "엔진 업데이트가 필요합니다", + "r3_02": "SSD 스트리밍 · 더 느리게 실행됩니다" } diff --git a/apps/host/src/locales/r3-pt.json b/apps/host/src/locales/r3-pt.json index 98f2ebc5ec..1fa85b4b4e 100644 --- a/apps/host/src/locales/r3-pt.json +++ b/apps/host/src/locales/r3-pt.json @@ -1,3 +1,4 @@ { - "r3_01": "Precisa de uma atualização do motor" + "r3_01": "Precisa de uma atualização do motor", + "r3_02": "Streaming do SSD · vai rodar mais devagar" } diff --git a/apps/host/src/locales/r3-ru.json b/apps/host/src/locales/r3-ru.json index b50627bcba..a8ec6d3d29 100644 --- a/apps/host/src/locales/r3-ru.json +++ b/apps/host/src/locales/r3-ru.json @@ -1,3 +1,4 @@ { - "r3_01": "Нужно обновить движок" + "r3_01": "Нужно обновить движок", + "r3_02": "Потоковая подгрузка с SSD · будет работать медленнее" } diff --git a/apps/host/src/locales/r3-zh.json b/apps/host/src/locales/r3-zh.json index ce34e10eca..74510b380a 100644 --- a/apps/host/src/locales/r3-zh.json +++ b/apps/host/src/locales/r3-zh.json @@ -1,3 +1,4 @@ { - "r3_01": "需要更新引擎" + "r3_01": "需要更新引擎", + "r3_02": "SSD 流式读取 · 运行会更慢" } diff --git a/apps/host/tests/version-picker.test.mjs b/apps/host/tests/version-picker.test.mjs index 8f49af985a..4401840e90 100644 --- a/apps/host/tests/version-picker.test.mjs +++ b/apps/host/tests/version-picker.test.mjs @@ -22,14 +22,31 @@ test('top: the recommendation and the downloaded versions; below: all the others assert.deepEqual(more.map(x => x.download_gb), [...more.map(x => x.download_gb)].sort((a, b) => a - b), 'the others by size'); }); -test('IQ3_S downloaded and recommended: it is at the top once, as downloaded, and nowhere else', () => { +test('IQ3_S downloaded and recommended: it is at the top once, with both tags, and nowhere else', () => { const pick = { family: 'qwen', model: 'IQ3_S', why: '64 GB tier' }; - const pickId = recommendedVersions(qwen38, pick).find(r => r.r.note === PICK_NOTE)?.v.id; - assert.equal(pickId, 'iq3_s'); - const { top, more } = versionGroups(qwen38, new Set(), new Set(['iq3_s']), pickId); + const recommended = recommendedVersions(qwen38, pick); + assert.equal(recommended[0].v.id, 'iq3_s', 'the pick for this PC comes first'); + assert.equal(recommended[0].r.note, PICK_NOTE); + const { top, more } = versionGroups(qwen38, new Set(), new Set(['iq3_s']), recommended.map(r => r.v.id)); assert.equal(top[0].id, 'iq3_s'); assert.equal([...top, ...more].filter(x => x.id === 'iq3_s').length, 1); - assert.match(source, /recommended = v\.id === pickId && !have/, 'the Recommended tag is not shown once it is downloaded'); + assert.match(source, /recommended = recommendedIds\.includes\(v\.id\)/, 'Recommended is written on every recommended row, downloaded or not'); + assert.ok(!/recommended = [^;]*&& !have/.test(source), 'a downloaded recommended version keeps its Recommended tag'); +}); + +test('the recommended versions from us come first, in order, then the downloaded ones, then the rest', () => { + const pick = { family: 'qwen', model: 'IQ3_S', why: '64 GB tier' }; + const rec = recommendedVersions(qwen38, pick); + assert.deepEqual(rec.map(r => r.v.id), ['iq3_s', 'gyro-gyro-s', 'swift-iq2_xs', 'unsloth-ud-q4_k_xl'], 'the pick, then the fixed picks'); + const have = new Set(['coder-iq1_m', 'iq3_s']); + const { top, more } = versionGroups(qwen38, new Set(), have, rec.map(r => r.v.id)); + assert.deepEqual(ids(top), ['iq3_s', 'gyro-gyro-s', 'swift-iq2_xs', 'unsloth-ud-q4_k_xl', 'coder-iq1_m']); + assert.equal(top.length + more.length, qwen38.length, 'none lost'); + assert.ok(!more.some(x => ids(top).includes(x.id)), 'none twice'); + // A base model whose versions are not in the fixed list (DeepSeek) still shows the engine's own pick. + const ds = [{ id: 'ist-das-1.75bpw', sourceFamily: 'deepseek41', model: 'IST-DAS-1.75bpw', download_gb: 50 }, { id: 'ist-das-2.00bpw', sourceFamily: 'deepseek41', model: 'IST-DAS-2.00bpw', download_gb: 60 }]; + assert.deepEqual(recommendedVersions(ds, { family: 'deepseek41', model: 'IST-DAS-2.00bpw' }).map(r => r.v.id), ['ist-das-2.00bpw']); + assert.deepEqual(recommendedVersions(ds, null), [], 'no pick and no fixed picks: nothing is recommended'); }); test('no downloads and no pick: everything is in the one list below, and the first-run page leaves out what it shows elsewhere', () => { @@ -39,16 +56,35 @@ test('no downloads and no pick: everything is in the one list below, and the fir assert.ok(!more.some(x => x.id === 'iq3_s' || x.id === 'gyro-gyro-s')); }); -test('a row says whether the version fits this PC, from the same figures as the card', () => { +test("the list writes Fits nowhere; only 'SSD streaming · will run slower' and 'Doesn't fit' are words", () => { const big = { id: 'x', download_gb: 111, memory_gb: 78 }, small = { id: 'y', download_gb: 66, memory_gb: 35 }; assert.equal(versionFit(small, { ram_gb: 128, vram_gb: 24 }), 'fits'); assert.equal(versionFit(big, { ram_gb: 64, vram_gb: 12 }), 'ssd', 'part of the experts read from the SSD'); - assert.equal(versionFit({ ...small, on_this_pc: 'does not fit' }, { ram_gb: 128, vram_gb: 24 }), 'no', "the engine's own verdict wins"); assert.equal(versionFit(small, null), 'unknown', 'no hardware figures: no claim'); - assert.match(source, /'Fits with SSD streaming'/); + assert.ok(!/'Fits'|"Fits"|Fits with SSD streaming/.test(source), 'no Fits word in the picker'); + assert.match(source, /state === 'ssd' \|\| state === 'no' \? <span className="version-row__fit"/, 'a version that fits has no fit line at all'); + assert.match(source, /'SSD streaming · will run slower'|'SSD streaming · will run slower'/); assert.ok(!/nativeVersionLabel|plainLabel/.test(source), 'no Fastest, Compact, High quality words'); }); +test("NVFP4 on a 12 GB card with 63 GB of RAM is SSD streaming, not Doesn't fit (the engine's catalog compares RAM only)", () => { + // NVFP4: ram_gb 80, arena_gb 68, so the catalog says "does not fit" below 72 GB of RAM whatever the graphics card holds. + const nvfp4 = { id: 'nvfp4-nvfp4', download_gb: 128, ram_needed_gb: 80, experts_gb: 68, memory_gb: 69, on_this_pc: 'does not fit' }; + assert.equal(versionFit(nvfp4, { ram_gb: 63.1, vram_gb: 11.9 }), 'ssd'); + assert.equal(versionFit({ ...nvfp4, on_this_pc: 'does not fit' }, { ram_gb: 32, vram_gb: 24 }), 'ssd', 'a smaller PC still runs it, slower'); + assert.equal(versionFit({ ...nvfp4, on_this_pc: 'tight' }, { ram_gb: 128, vram_gb: 32 }), 'fits'); +}); + +test("Doesn't fit is left for the cases that cannot run at all", () => { + const v = { id: 'x', download_gb: 66, memory_gb: 35 }; + assert.equal(versionFit({ ...v, on_this_pc: 'does not fit: it needs one or more graphics cards' }, { ram_gb: 256, vram_gb: 0 }), 'no', 'DeepSeek without a graphics card'); + assert.equal(versionFit({ ...v, on_this_pc: 'does not fit' }, { ram_gb: 8, vram_gb: 0 }), 'no', 'less memory than anything was run with, and the engine agrees'); + assert.equal(versionFit({ ...v, on_this_pc: 'does not fit: this Mac has too little memory' }, { ram_gb: 8, vram_gb: 0 }), 'no'); + assert.equal(versionFit({ ...v, on_this_pc: 'does not fit' }, null), 'no', 'the engine says so and nothing contradicts it'); + assert.equal(versionFit({ ...v, on_this_pc: 'does not fit' }, { ram_gb: 16, vram_gb: 0 }), 'ssd', 'at the floor it runs from the SSD'); + assert.equal(versionFit({ ...v, memory_gb: 260, on_this_pc: 'does not fit: about 120 GB of its experts would be read from the SSD' }, { ram_gb: 128, vram_gb: 24 }), 'ssd', 'a big spill is slow, not a refusal'); +}); + test("the list is for one base model: the page passes only the chosen model's versions", async () => { const screen = await readFile(new URL('../src/components/NativeModels.tsx', import.meta.url), 'utf8'); assert.match(screen, /<VersionPicker [^>]*versions=\{selectedFamily\?\.sizes \?\? \[\]\}/); From 53f85fa81557cd44e54b8b0bdfd37a7420e43af0 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:31:16 +0100 Subject: [PATCH 30/59] Conversation context opens at 128K for every configuration (the model's largest size when under 128K); a tight card gets an inline warning, nothing is refused or lowered; DeepSeek keeps its checked 8K --- apps/host/scripts/make-r3-locales.py | 11 +++++++ apps/host/src/components/GuidedSetup.tsx | 7 ++++- apps/host/src/components/NativeModels.tsx | 27 ++++++++++------ apps/host/src/components/VersionPicker.tsx | 12 +++++--- apps/host/src/lib/default-context.ts | 36 ++++++++++++++++++++++ apps/host/src/lib/native-fit.ts | 10 +++--- apps/host/src/locales/r3-de.json | 3 +- apps/host/src/locales/r3-en.json | 3 +- apps/host/src/locales/r3-es.json | 3 +- apps/host/src/locales/r3-fr.json | 3 +- apps/host/src/locales/r3-ja.json | 3 +- apps/host/src/locales/r3-ko.json | 3 +- apps/host/src/locales/r3-pt.json | 3 +- apps/host/src/locales/r3-ru.json | 3 +- apps/host/src/locales/r3-zh.json | 3 +- apps/host/tests/ui-r3.test.mjs | 36 ++++++++++++++++++++++ 16 files changed, 137 insertions(+), 29 deletions(-) create mode 100644 apps/host/src/lib/default-context.ts diff --git a/apps/host/scripts/make-r3-locales.py b/apps/host/scripts/make-r3-locales.py index e2bc3ae741..e17f88bc9e 100644 --- a/apps/host/scripts/make-r3-locales.py +++ b/apps/host/scripts/make-r3-locales.py @@ -23,6 +23,17 @@ add("SSD streaming · will run slower", "SSD 流式读取 · 运行会更慢", "SSD ストリーミング · 動作は遅くなります", "SSD-Streaming · läuft langsamer", "Streaming desde el SSD · irá más lento", "Потоковая подгрузка с SSD · будет работать медленнее", "Streaming do SSD · vai rodar mais devagar", "SSD 스트리밍 · 더 느리게 실행됩니다", "Streaming depuis le SSD · plus lent") +# 6: the warning under the conversation context when a long context leaves little graphics memory for the model (nothing is refused or lowered) +add("This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context.", + "这么长的上下文大约占用 {0} GB 显存,留给模型的空间很少。Strata 会尝试运行;如果无法启动,请选择更短的上下文。", + "このコンテキストはグラフィックスメモリーを約 {0} GB 使い、このカードではモデルに残る余裕がわずかです。Strata は試しますが、起動しない場合はより短いコンテキストを選んでください。", + "So viel Kontext belegt etwa {0} GB Grafikspeicher und lässt auf dieser Karte wenig Platz für das Modell. Strata versucht es; startet es nicht, wähle einen kürzeren Kontext.", + "Este contexto ocupa unos {0} GB de memoria gráfica y deja poco espacio para el modelo en esta tarjeta. Strata lo intentará; si no arranca, elige un contexto más corto.", + "Такой контекст занимает около {0} ГБ видеопамяти и оставляет модели мало места на этой карте. Strata попробует запустить; если не получится, выберите контекст короче.", + "Esse contexto ocupa cerca de {0} GB de memória gráfica e deixa pouco espaço para o modelo nesta placa. O Strata vai tentar; se não iniciar, escolha um contexto menor.", + "이 정도의 컨텍스트는 그래픽 메모리를 약 {0} GB 사용하며 이 카드에서는 모델이 쓸 공간이 거의 남지 않습니다. Strata가 시도하지만 시작되지 않으면 더 짧은 컨텍스트를 선택하세요.", + "Ce contexte occupe environ {0} Go de mémoire graphique et laisse peu de place au modèle sur cette carte. Strata va essayer ; s'il ne démarre pas, choisissez un contexte plus court.") + #@@MORE@@ here = Path(__file__).resolve().parent.parent / "src" / "locales" diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsx index 4bb7be234a..d9fac9af94 100644 --- a/apps/host/src/components/GuidedSetup.tsx +++ b/apps/host/src/components/GuidedSetup.tsx @@ -14,6 +14,7 @@ import type { LocalModelFolder, SetupState } from '../lib/types'; import { downloadCounter, modelFolderLabel, onboardingError } from '../lib/onboarding-download'; import { installProgress, installStage, stageText, useDownloadEta } from '../lib/download-eta'; import { VersionPicker } from './VersionPicker'; +import { contextIsTight, defaultContext, DEFAULT_CONTEXT, OLD_DEFAULT_CONTEXT } from '../lib/default-context'; import { FirstRunLanguage } from './FirstRunLanguage'; import { DownloadParts } from './DownloadParts'; import { EngineWarning } from './EngineWarning'; @@ -44,7 +45,11 @@ export function GuidedSetup() { const start = startingChoice(families, (native?.installed?.models ?? []).filter(m => m.ready).map(m => m.model), native?.catalog?.recommendation); const family = chosenFamily || start?.family || native?.catalog?.recommendation?.family || families[0]?.family || ''; const size = chosenSize || start?.size || ''; - const [context, setContext] = useState(saved?.context ?? native?.catalog?.recommendation?.context ?? 32768); + /* 128K for every configuration unless the person picks another. This first step has no room for the memory warning the Models page gives, so a card + that a 128K cache would leave under 1 GB for the model starts at the 32K the engine was set up for. */ + const topCardGb = Math.max(0, ...(native?.hardware?.gpus ?? []).filter(g => g.usable !== false).map(g => g.vram_gb)); + const [pickedContext, setContext] = useState<number | undefined>(saved?.context); + const context = pickedContext ?? (contextIsTight(topCardGb, DEFAULT_CONTEXT) ? OLD_DEFAULT_CONTEXT : defaultContext(native?.catalog?.contexts)); const [vision, setVision] = useState(saved?.vision ?? true), [directory, setDirectory] = useState(saved?.directory ?? ''); const [profile, setProfile] = useState<'work' | 'performance'>(saved?.profile ?? 'work'); const [installJobId, setInstallJobId] = useState(saved?.installJobId ?? ''), [tuneJobId, setTuneJobId] = useState(saved?.tuneJobId ?? ''); diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 7ec99d7871..de7c8efda3 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -4,7 +4,8 @@ import { Screen } from './layout'; import { VersionPicker } from './VersionPicker'; import { FamilySwitch } from './FamilySwitch'; import { PcComputer } from './PcComputer'; -import { fitOn, memoryNeeded, versionFit } from '../lib/native-fit'; +import { cacheGb, fitOn, memoryNeeded, versionFit } from '../lib/native-fit'; +import { contextIsTight, defaultContext, DEFAULT_CONTEXT, openingContext } from '../lib/default-context'; import { GpuRoles } from './GpuRoles'; import { fromLegacy, normalize as normalizeRoles, order as roleOrder, recommend as recommendRoles, rows as roleRows, sameRoles, vramOn, type RoleCard, type Roles } from '../lib/gpu-roles'; import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; @@ -42,7 +43,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }) { const native = useNative(), imageLibrary = useStore(s => s.imageModels), hardware = useStore(s => s.hardware); // The choices are kept while the page is closed (Models -> Monitor -> Models used to start them over and a person lost track of what was downloading). - const [family, setFamily] = useKept('models.family', ''), [size, setSize] = useKept('models.size', ''), [context, setContext] = useKept('models.context', 32768), [vision, setVision] = useKept('models.vision', 'yes'); + const [family, setFamily] = useKept('models.family', ''), [size, setSize] = useKept('models.size', ''), [context, setContext] = useKept('models.context', DEFAULT_CONTEXT), [contextPicked, setContextPicked] = useKept('models.contextPicked', false), [vision, setVision] = useKept('models.vision', 'yes'); const manual = useStore(s => s.setup?.choices?.onboarding?.manual ?? false); const [expert, setExpert] = useKept('models.expert', manual), [multiple, setMultiple] = useKept('models.multiple', false), [roles, setRoles] = useKept<Roles | null>('models.roles', null), [kv, setKv] = useKept('models.kv', 'int8'), [lowRam, setLowRam] = useKept('models.lowRam', 'auto'), [split, setSplit] = useKept('models.split', 'auto'); const [resourceProfile, setResourceProfile] = useKept<'work' | 'performance'>('models.profile', 'work'); @@ -69,6 +70,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }, [expert]); const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0], selectedSize = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0]; const installed = native?.installed?.models.find(m => m.model === selectedSize?.id); + // The sizes this model offers for the conversation context; it opens at 128K (or its largest size when that is smaller). + const contextList = selectedSize?.multi_file ? deepseekContexts(installed?.contextMax) : native?.catalog?.contexts ?? [8192, 32768, 65536, 131072, 262144]; // The model that is running is shown as running, with Unload: not offered for loading again. const downloaded = native?.installed?.models ?? [], allSizes = families.flatMap(f => f.sizes); // This computer for the fit figures: the biggest usable graphics card, or the ones chosen under Expert settings. @@ -124,7 +127,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const chosenCards = cardsGpus; const fitHardware = { ram_gb: pcRam ? Math.max(0, pcRam - keptRam) : pcRam, vram_gb: Math.max(0, (roleCards.length > 1 ? vramOn(effectiveRoles, roleCards) : pcVram) - keptVramOn(chosenCards)) }; // How the chosen version sits on this computer (the same rule as the version list): the page says a word only for "SSD streaming" and "Doesn't fit". - const fitState = selectedSize ? versionFit(selectedSize, fitHardware) : 'unknown'; + const fitState = selectedSize ? versionFit(selectedSize, fitHardware, { context, kv }) : 'unknown'; // A layer split written for another number of cards no longer fits: back to automatic. useEffect(() => { if (cardsGpus.length <= 1 && split !== 'auto') setSplit('auto'); }, [cardsGpus.length]); // Drafting (which drafter guesses ahead): a choice exists only for Qwen3.8-Flash-Next (the qwen and gyro families) on a computer whose engine can run DFlash2; every other model has no dropdown. @@ -135,8 +138,10 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine useEffect(() => { if (!native?.catalog || family) return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const have = new Set((native.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const installedFamily = families.find(f => f.sizes.some(s => have.has(s.id))); const f = loadedFamily ?? installedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) { setFamily(f.family); - setSize(f.sizes.find(s => s.id === current?.model)?.id ?? f.sizes.find(s => have.has(s.id))?.id ?? f.sizes.find(s => s.model === rec.model)?.id ?? f.sizes[0]?.id ?? ''); - setContext(('context' in rec ? rec.context : undefined) ?? 32768); + const first = f.sizes.find(s => s.id === current?.model) ?? f.sizes.find(s => have.has(s.id)) ?? f.sizes.find(s => s.model === rec.model) ?? f.sizes[0]; + setSize(first?.id ?? ''); + // 128K for every configuration (the engine's own recommendation is not what the app opens with); DeepSeek keeps the 8K its engine was checked at. + setContext(first?.multi_file ? 8192 : defaultContext(native.catalog.contexts)); } }, [native?.catalog]); // The version that is selected: a model already on this PC shows the settings it was prepared with (so loading it never asks to download); // a model that is not yet downloaded starts with Read pictures ON (owner rule: pictures on by default). This runs when the SELECTION or the @@ -153,8 +158,9 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine return; setAppliedSig(sig); if (installed) { + // The context it was prepared with when someone chose it; a model that holds the old 32K default opens at the new default. if (installed.context) - setContext(installed.context); + setContext(selectedSize.multi_file ? installed.context : openingContext(installed.context, contextList)); // Off only when the person turned it off (a saved choice on a model that has the picture files); a model prepared without them (images 'off', or an old "off" saved while the engine had no reader) starts with it ON. setVision(installed.visionEnabled === false && installed.visionPrepared !== false ? 'no' : installed.visionDevice ?? (installed.images && installed.images !== 'off' ? installed.images : 'yes')); setKv(installed.kv ?? 'int8'); @@ -166,8 +172,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine } else { setVision('yes'); - if (selectedSize.multi_file) - setContext(8192); // DeepSeek runs at the one context its engine was checked at (as in the guided setup) + if (!contextPicked) // a context the person picked stays; otherwise 128K, and DeepSeek runs at the one context its engine was checked at (as in the guided setup) + setContext(selectedSize.multi_file ? 8192 : defaultContext(contextList)); } }, [selectedSize?.id, installed?.model, installed?.ready, installed?.context, installed?.kv, installed?.images, installed?.visionEnabled, installed?.visionDevice, installed?.lowRamMode, installed?.resourceProfile]); useEffect(() => { if (jobId && job?.state === 'done' && job.id !== toastedJob && (job.kind === 'load' || job.kind === 'install')) { @@ -210,14 +216,15 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(selectedSize ? <> <div className="native-choice__head"><span className="native-choice__label">{tr("Version")}</span><span className="native-choice__tools"><NativePresets values={values} onApply={v => { const f = families.find(f => f.family === v.family || f.sizes.some(s => s.sourceFamily === v.family)); if (!f) return; presetPending.current = true; setFamily(f.family); setSize(f.sizes.find(s => s.model === v.model && (s.sourceFamily === v.family || f.family === v.family))?.id ?? ''); setContext(v.context ?? 32768); setVision(v.vision ?? 'no'); setKv(v.kv ?? 'int8'); setLowRam(v.low_ram ?? 'auto'); }}/><Btn icon="models" size="sm" variant="ghost" onClick={() => setManage(true)}>{tr("Manage models")}</Btn></span></div> - <div className="native-version"><VersionPicker pick={native?.catalog?.recommendation} versions={selectedFamily?.sizes ?? []} details={expert} selectedId={selectedSize.id} hardware={fitHardware} downloaded={readyIds} onSelect={id => { const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/></div> + <div className="native-version"><VersionPicker pick={native?.catalog?.recommendation} versions={selectedFamily?.sizes ?? []} details={expert} selectedId={selectedSize.id} hardware={fitHardware} cache={{ context, kv }} downloaded={readyIds} onSelect={id => { const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/></div> {tr(fitState === 'ssd' ? <p className="small muted native-spill-note"><Icon name="disk" size={16}/>{tr("SSD streaming · will run slower")}</p> : fitState === 'no' ? <p className="small muted native-spill-note"><Icon name="warning" size={16}/>{tr("Doesn't fit")}</p> : null)} {tr(selectedSize?.multi_file && deepseekContextNote(context) ? <p className="small muted native-spill-note"><Icon name="info" size={16}/>{tr(deepseekContextNote(context))}</p> : null)} <div className="native-choice__row"> - <div className="native-choice__col"><span className="native-choice__label">{tr("Conversation context")}</span><Select ariaLabel={tr("Conversation context")} value={String(context)} options={contextChoices(selectedSize?.multi_file ? deepseekContexts(installed?.contextMax) : native?.catalog?.contexts ?? [8192, 32768, 65536, 131072, 262144], context).map(n => ({ value: String(n), label: n % 1024 === 0 ? `${n / 1024}K` : `${n.toLocaleString()} tokens` }))} onChange={n => setContext(Number(n))}/></div> + <div className="native-choice__col"><span className="native-choice__label">{tr("Conversation context")}</span><Select ariaLabel={tr("Conversation context")} value={String(context)} options={contextChoices(contextList, context).map(n => ({ value: String(n), label: n % 1024 === 0 ? `${n / 1024}K` : `${n.toLocaleString()} tokens` }))} onChange={n => { setContextPicked(true); setContext(Number(n)); }}/></div> {tr(draftingChoices ? <div className="native-choice__col"><span className="native-choice__label">{tr("Drafting")}</span><Select ariaLabel={tr("Drafting")} value={drafting} disabled={!!active} options={draftingChoices.map(v => ({ value: v, label: tr(draftingWords[v]) }))} onChange={v => setDrafting(String(v))}/></div> : null)} <div className="native-choice__col"><span className="native-choice__label">{tr("Computer use")}</span><div className="native-resource-choice"><button aria-pressed={resourceProfile === 'work'} data-selected={resourceProfile === 'work'} onClick={() => setResourceProfile('work')}><Icon name="computer" size={20}/><span><strong>{tr("Leave 20% for my work")}</strong><small>{tr("Headroom for your other apps")}</small></span>{tr(resourceProfile === 'work' ? <Icon name="check" size={15}/> : null)}</button><button aria-pressed={resourceProfile === 'performance'} data-selected={resourceProfile === 'performance'} onClick={() => setResourceProfile('performance')}><Icon name="bolt" size={20}/><span><strong>{tr("Full performance")}</strong><small>{tr("Give Strata priority")}</small></span>{tr(resourceProfile === 'performance' ? <Icon name="check" size={15}/> : null)}</button></div></div> </div> + {tr(!selectedSize?.multi_file && contextIsTight(fitHardware.vram_gb, context, kv) ? <p className="small muted native-spill-note"><Icon name="warning" size={16}/>{tr("This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context.", [cacheGb(context, kv).toFixed(1)])}</p> : null)} {tr(loadedSelected?.metrics?.engine?.drafting_note ? <p className="small muted native-spill-note">{tr(String(loadedSelected.metrics.engine.drafting_note))}</p> : null)} {roleCards.length > 1 ? <GpuRoles cards={roleCards} roles={effectiveRoles} custom={customRoles} recommendedRoles={recommended.roles} vendor={engineVendor} disabled={!!active} onChange={changeRoles} onBack={() => setRoles(null)} memoryGb={selectedSize ? memoryNeeded(selectedSize) || null : null} ramGb={pcRam} spillGb={selectedSize ? fitOn(selectedSize, fitHardware).spillGb : 0} usedBy={i => usedBy([i])}/> : null} {tr(roleCards.length > 1 && (native?.hardware?.gpus ?? []).length > roleCards.length ? <p className="small muted native-cards__note">{tr('Not used: {0} (another make of graphics card than this engine drives).', [(native?.hardware?.gpus ?? []).filter(g => !roleCards.some(r => r.index === g.index && r.vendor === g.vendor)).map(g => g.name).join(', ')])}</p> : null)} diff --git a/apps/host/src/components/VersionPicker.tsx b/apps/host/src/components/VersionPicker.tsx index 611965822a..2933a9ad54 100644 --- a/apps/host/src/components/VersionPicker.tsx +++ b/apps/host/src/components/VersionPicker.tsx @@ -5,7 +5,7 @@ import { FloatingMenu } from './FloatingMenu'; import { cx } from '../lib/format'; import { versionNote, type CatalogVersion } from '../lib/native-catalog'; import { nvfp4Version } from '../lib/native-names'; -import { fitOn, recommendedVersions, versionFit, versionGroups, type FitHardware, type PcPick } from '../lib/native-fit'; +import { fitOn, recommendedVersions, versionFit, versionGroups, type CacheChoice, type FitHardware, type PcPick } from '../lib/native-fit'; /** The name a version goes by in the list: the quantization, with the maker only where the quantization alone would be ambiguous. */ export function versionName(v: CatalogVersion): string { @@ -32,7 +32,7 @@ const whole = (n: number) => `${Math.round(n)} GB`; * memory it needs and the SSD figure are behind "Show details" (open from the start in Expert mode). The other base models are not in this list: they * appear when picked at the top of the page. */ -export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnGguf, downloaded, showRecommended = true, moreLabel, pick, details: detailsOpen = false }: { +export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnGguf, downloaded, showRecommended = true, moreLabel, pick, cache, details: detailsOpen = false }: { /** The versions of the chosen base model. */ versions: CatalogVersion[]; selectedId: string; @@ -47,6 +47,8 @@ export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnG moreLabel?: string; /** The engine's own pick for this PC (catalog.recommendation). */ pick?: PcPick | null; + /** The conversation context and cache format the person chose: the fit words follow them, as the This computer card does. */ + cache?: CacheChoice | null; /** Start with the technical detail shown (Expert mode). */ details?: boolean; }) { @@ -66,14 +68,14 @@ export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnG const foldedOpen = moreOpen || !top.length || more.some(v => v.id === selectedId); const need = (v: CatalogVersion, technical: boolean) => { - const fit = fitOn(v, hardware); + const fit = fitOn(v, hardware, true, cache); if (technical) return v.multi_file && v.disk_gb ? tr("{0} RAM + VRAM, plus about {1} GB of disk", [gb(fit.memoryGb), Math.round(v.disk_gb)]) : tr("{0} RAM + VRAM", [gb(fit.memoryGb)]); return v.multi_file && v.disk_gb ? tr("Needs {0} of memory and about {1} GB of disk", [whole(fit.memoryGb), Math.round(v.disk_gb)]) : tr("Needs {0} of memory", [whole(fit.memoryGb)]); }; const row = (v: CatalogVersion) => { - const fit = fitOn(v, hardware); + const fit = fitOn(v, hardware, true, cache); const on = v.id === selectedId, have = !!downloaded?.has(v.id), recommended = recommendedIds.includes(v.id); - const state = versionFit(v, hardware); + const state = versionFit(v, hardware, cache); const technical = [MAKERS[v.sourceFamily], need(v, true), state === 'ssd' ? tr("Uses SSD {0} GB", [Math.round(fit.spillGb)]) : ''].filter(Boolean).join(' · '); const note = versionNote(v.model); return <button key={v.id} role="menuitemradio" aria-checked={on} className={cx('version-row', on && 'is-on')} onClick={() => { onSelect(v.id); setOpen(false); }}> diff --git a/apps/host/src/lib/default-context.ts b/apps/host/src/lib/default-context.ts new file mode 100644 index 0000000000..ef3de8123b --- /dev/null +++ b/apps/host/src/lib/default-context.ts @@ -0,0 +1,36 @@ +import { BASE_CONTEXT, cacheGb, DENSE_GB, MTP_VRAM_GB } from './native-fit'; + +/** + * The conversation context a model opens with: 128K for every configuration, unless the person picks another (owner, 11-01). Where the + * model's own largest choice is under 128K, that largest choice. The engine's own recommendation (catalog.recommendation.context, which the + * Terminal still uses) is not what the app opens with. + */ +export const DEFAULT_CONTEXT = 131072; +/** What the Models page used to open with: a saved model that holds exactly this has never had a context chosen for it. */ +export const OLD_DEFAULT_CONTEXT = 32768; + +/** The default among the sizes a model offers: 128K, or the largest size under it. */ +export function defaultContext(choices: readonly number[] | null | undefined): number { + const sizes = (choices ?? []).filter(n => Number.isFinite(n) && n > 0); + const under = sizes.filter(n => n <= DEFAULT_CONTEXT); + return under.length ? Math.max(...under) : sizes.length ? Math.min(...sizes) : DEFAULT_CONTEXT; +} + +/** What a model that is already on this computer opens with: the context it was prepared with when someone chose it, else the default. */ +export function openingContext(saved: number | null | undefined, choices: readonly number[] | null | undefined): number { + return saved && saved > 0 && saved !== OLD_DEFAULT_CONTEXT ? saved : defaultContext(choices); +} + +/** + * Graphics memory left for the model's own data after the conversation memory of this context (the app's estimate, the same figures as the This + * computer card: dense weights and buffers, the conversation cache, the draft layer). Under ONE_GB the card is tight at this context. + */ +export function roomAfterContext(vramGb: number, context: number, kv = 'int8'): number { + const dense = Math.max(DENSE_GB - cacheGb(BASE_CONTEXT), 0) + cacheGb(context, kv); + return vramGb - dense - MTP_VRAM_GB; +} +/** A context past 32K that leaves a card under 1 GB for the model (the 32K default would leave more). Said as a warning; nothing is refused or lowered. */ +export function contextIsTight(vramGb: number | null | undefined, context: number, kv = 'int8'): boolean { + const vram = Number(vramGb); + return Number.isFinite(vram) && vram > 0 && context > BASE_CONTEXT && roomAfterContext(vram, context, kv) < 1; +} diff --git a/apps/host/src/lib/native-fit.ts b/apps/host/src/lib/native-fit.ts index bee9864f78..3ca0080e45 100644 --- a/apps/host/src/lib/native-fit.ts +++ b/apps/host/src/lib/native-fit.ts @@ -19,7 +19,8 @@ export interface Fit { known: boolean; } -const DENSE_GB = 5, SYSTEM_ROOM_GB = 10, DENSE_EXTRA_GB = 1; +export const DENSE_GB = 5; +const SYSTEM_ROOM_GB = 10, DENSE_EXTRA_GB = 1; /** The draft layer (MTP) takes about 1 GB of graphics memory (786 MiB of files + the draft head's ~218 MiB); it comes out of the expert cache while MTP is on (setup.py MTP_VRAM_GB). */ export const MTP_VRAM_GB = 1; const round1 = (n: number) => Math.round(n * 10) / 10; @@ -33,7 +34,8 @@ export function memoryNeeded(v: FitInput): number { /** 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<string, number> = { fp16: 2112, int8: 1056, q4_0: 576, k8v4: 816 }; -const KV_LAYERS = 13, KV_FACTOR = 1.054, BASE_CONTEXT = 32768; +const KV_LAYERS = 13, KV_FACTOR = 1.054; +export const BASE_CONTEXT = 32768; export function cacheGb(context: number, kv = 'int8'): number { return (121 + context * KV_LAYERS * (KV_BYTES[String(kv).toLowerCase()] ?? KV_BYTES.int8) * KV_FACTOR / 2 ** 20) / 1024; // 121 MiB fixed per session } @@ -131,11 +133,11 @@ export function versionGroups<V extends { id: string; download_gb: number }>(ver */ export type VersionFit = 'fits' | 'ssd' | 'no' | 'unknown'; export const MIN_RUN_GB = 16; -export function versionFit(v: FitInput & { on_this_pc?: string | null }, hw: FitHardware | null | undefined): VersionFit { +export function versionFit(v: FitInput & { on_this_pc?: string | null }, hw: FitHardware | null | undefined, cache?: CacheChoice | null): VersionFit { const words = String(v.on_this_pc ?? '').trim().toLowerCase(); const engineNo = words.startsWith('does not fit'); if (/needs? (one or more|a) graphics cards?/.test(words)) return 'no'; - const fit = fitOn(v, hw); + const fit = fitOn(v, hw, true, cache); if (!fit.known) return engineNo ? 'no' : 'unknown'; if (engineNo && Number(hw?.ram_gb) < MIN_RUN_GB) return 'no'; return fit.spillGb >= 1 ? 'ssd' : 'fits'; diff --git a/apps/host/src/locales/r3-de.json b/apps/host/src/locales/r3-de.json index a1c2027d8a..86cc195ebe 100644 --- a/apps/host/src/locales/r3-de.json +++ b/apps/host/src/locales/r3-de.json @@ -1,4 +1,5 @@ { "r3_01": "Braucht ein Engine-Update", - "r3_02": "SSD-Streaming · läuft langsamer" + "r3_02": "SSD-Streaming · läuft langsamer", + "r3_03": "So viel Kontext belegt etwa {0} GB Grafikspeicher und lässt auf dieser Karte wenig Platz für das Modell. Strata versucht es; startet es nicht, wähle einen kürzeren Kontext." } diff --git a/apps/host/src/locales/r3-en.json b/apps/host/src/locales/r3-en.json index 32e5880b65..07dd1d8c58 100644 --- a/apps/host/src/locales/r3-en.json +++ b/apps/host/src/locales/r3-en.json @@ -1,4 +1,5 @@ { "r3_01": "Needs an engine update", - "r3_02": "SSD streaming · will run slower" + "r3_02": "SSD streaming · will run slower", + "r3_03": "This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context." } diff --git a/apps/host/src/locales/r3-es.json b/apps/host/src/locales/r3-es.json index 323b5bde72..424604f7df 100644 --- a/apps/host/src/locales/r3-es.json +++ b/apps/host/src/locales/r3-es.json @@ -1,4 +1,5 @@ { "r3_01": "Necesita actualizar el motor", - "r3_02": "Streaming desde el SSD · irá más lento" + "r3_02": "Streaming desde el SSD · irá más lento", + "r3_03": "Este contexto ocupa unos {0} GB de memoria gráfica y deja poco espacio para el modelo en esta tarjeta. Strata lo intentará; si no arranca, elige un contexto más corto." } diff --git a/apps/host/src/locales/r3-fr.json b/apps/host/src/locales/r3-fr.json index 3c3235f5f1..13602afb14 100644 --- a/apps/host/src/locales/r3-fr.json +++ b/apps/host/src/locales/r3-fr.json @@ -1,4 +1,5 @@ { "r3_01": "Nécessite une mise à jour du moteur", - "r3_02": "Streaming depuis le SSD · plus lent" + "r3_02": "Streaming depuis le SSD · plus lent", + "r3_03": "Ce contexte occupe environ {0} Go de mémoire graphique et laisse peu de place au modèle sur cette carte. Strata va essayer ; s’il ne démarre pas, choisissez un contexte plus court." } diff --git a/apps/host/src/locales/r3-ja.json b/apps/host/src/locales/r3-ja.json index 391ccd264f..17de9387fa 100644 --- a/apps/host/src/locales/r3-ja.json +++ b/apps/host/src/locales/r3-ja.json @@ -1,4 +1,5 @@ { "r3_01": "エンジンの更新が必要です", - "r3_02": "SSD ストリーミング · 動作は遅くなります" + "r3_02": "SSD ストリーミング · 動作は遅くなります", + "r3_03": "このコンテキストはグラフィックスメモリーを約 {0} GB 使い、このカードではモデルに残る余裕がわずかです。Strata は試しますが、起動しない場合はより短いコンテキストを選んでください。" } diff --git a/apps/host/src/locales/r3-ko.json b/apps/host/src/locales/r3-ko.json index 1501f01a4a..b6f5deeb5f 100644 --- a/apps/host/src/locales/r3-ko.json +++ b/apps/host/src/locales/r3-ko.json @@ -1,4 +1,5 @@ { "r3_01": "엔진 업데이트가 필요합니다", - "r3_02": "SSD 스트리밍 · 더 느리게 실행됩니다" + "r3_02": "SSD 스트리밍 · 더 느리게 실행됩니다", + "r3_03": "이 정도의 컨텍스트는 그래픽 메모리를 약 {0} GB 사용하며 이 카드에서는 모델이 쓸 공간이 거의 남지 않습니다. Strata가 시도하지만 시작되지 않으면 더 짧은 컨텍스트를 선택하세요." } diff --git a/apps/host/src/locales/r3-pt.json b/apps/host/src/locales/r3-pt.json index 1fa85b4b4e..0394c2d4bf 100644 --- a/apps/host/src/locales/r3-pt.json +++ b/apps/host/src/locales/r3-pt.json @@ -1,4 +1,5 @@ { "r3_01": "Precisa de uma atualização do motor", - "r3_02": "Streaming do SSD · vai rodar mais devagar" + "r3_02": "Streaming do SSD · vai rodar mais devagar", + "r3_03": "Esse contexto ocupa cerca de {0} GB de memória gráfica e deixa pouco espaço para o modelo nesta placa. O Strata vai tentar; se não iniciar, escolha um contexto menor." } diff --git a/apps/host/src/locales/r3-ru.json b/apps/host/src/locales/r3-ru.json index a8ec6d3d29..412a730a85 100644 --- a/apps/host/src/locales/r3-ru.json +++ b/apps/host/src/locales/r3-ru.json @@ -1,4 +1,5 @@ { "r3_01": "Нужно обновить движок", - "r3_02": "Потоковая подгрузка с SSD · будет работать медленнее" + "r3_02": "Потоковая подгрузка с SSD · будет работать медленнее", + "r3_03": "Такой контекст занимает около {0} ГБ видеопамяти и оставляет модели мало места на этой карте. Strata попробует запустить; если не получится, выберите контекст короче." } diff --git a/apps/host/src/locales/r3-zh.json b/apps/host/src/locales/r3-zh.json index 74510b380a..b477ae8639 100644 --- a/apps/host/src/locales/r3-zh.json +++ b/apps/host/src/locales/r3-zh.json @@ -1,4 +1,5 @@ { "r3_01": "需要更新引擎", - "r3_02": "SSD 流式读取 · 运行会更慢" + "r3_02": "SSD 流式读取 · 运行会更慢", + "r3_03": "这么长的上下文大约占用 {0} GB 显存,留给模型的空间很少。Strata 会尝试运行;如果无法启动,请选择更短的上下文。" } diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index d33427edbf..7484d5b46b 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -2,9 +2,16 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; +import { build } from 'esbuild'; +import { fileURLToPath } from 'node:url'; const read = path => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8'); const models = read('src/components/NativeModels.tsx'); +/** Load a src/lib module (with its imports) the way the other tests do. */ +async function lib(file) { + const built = await build({ entryPoints: [fileURLToPath(new URL(`../${file}`, import.meta.url))], bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' }, logLevel: 'silent' }); + return import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`); +} test('1: the Models page carries no DFlash2 paragraph, no per-card line and no picture-reader sentence; the Drafting dropdown stays', () => { assert.ok(!/MTP is the default\. DFlash2/.test(models), 'the DFlash2 paragraph is gone'); @@ -28,3 +35,32 @@ test('2: pictures are on by default; a missing reader says nothing wordy and sav // An "off" that sits on a model without the picture files is not a choice of the person: it starts on. assert.match(models, /installed\.visionEnabled === false && installed\.visionPrepared !== false \? 'no'/); }); + +test('6: the conversation context opens at 128K for every configuration, or the model largest size when that is smaller; a warning, never a refusal', async () => { + const { defaultContext, openingContext, contextIsTight, DEFAULT_CONTEXT } = await lib('src/lib/default-context.ts'); + assert.equal(DEFAULT_CONTEXT, 131072); + assert.equal(defaultContext([8192, 32768, 65536, 131072, 262144]), 131072); + assert.equal(defaultContext([8192, 32768, 65536]), 65536, 'a model whose largest size is under 128K opens at its largest'); + assert.equal(defaultContext([8192, 32768, 65536, 131072, 262144, 524288, 1048576]), 131072); + assert.equal(defaultContext(undefined), 131072); + assert.equal(openingContext(32768, [8192, 32768, 131072]), 131072, 'a saved 32K is the old default, not a choice'); + assert.equal(openingContext(65536, [8192, 32768, 65536, 131072]), 65536, 'a size that was chosen is kept'); + assert.equal(openingContext(undefined, [8192, 131072]), 131072); + // What it costs: the conversation memory of 128K is 1.9 GB (int8) against 0.5 GB at 32K, so it is tight on cards of about 8 GB and below. + assert.equal(contextIsTight(6, 131072), true); + assert.equal(contextIsTight(8, 131072), true); + assert.equal(contextIsTight(12, 131072), false, 'the 12 GB card of the owner is fine'); + assert.equal(contextIsTight(24, 131072), false); + assert.equal(contextIsTight(8, 32768), false, '32K is the baseline: never a warning'); + assert.equal(contextIsTight(0, 131072), false, 'no card figure: no claim'); + assert.equal(contextIsTight(null, 131072), false); + // The page opens with the default, ignores the engine recommended context, warns inline and never lowers by itself. + assert.match(models, /useKept\('models\.context', DEFAULT_CONTEXT\)/); + assert.ok(!/rec\.context/.test(models), 'the engine recommendation is not what the page opens with'); + assert.match(models, /setContext\(first\?\.multi_file \? 8192 : defaultContext\(native\.catalog\.contexts\)\)/); + assert.match(models, /contextIsTight\(fitHardware\.vram_gb, context, kv\) \? <p className="small muted native-spill-note"><Icon name="warning"/); + assert.ok(!/setContext\([^)]*contextIsTight/.test(models), 'the warning never changes the context'); + assert.match(models, /cache=\{\{ context, kv \}\}/, 'the version list follows the chosen context, as the card does'); + const guided = read('src/components/GuidedSetup.tsx'); + assert.match(guided, /pickedContext \?\? \(contextIsTight\(topCardGb, DEFAULT_CONTEXT\) \? OLD_DEFAULT_CONTEXT : defaultContext\(native\?\.catalog\?\.contexts\)\)/); +}); From e60e03762e3f784a185c90ec13adaf1e0dcf2ee2 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:31:53 +0100 Subject: [PATCH 31/59] Model files: the sentence is gone and Other local models... sits inside the component beside Storage settings --- apps/host/src/components/NativeModels.tsx | 2 +- apps/host/src/styles/liquid.css | 14 ++++++++------ apps/host/tests/ui-r3.test.mjs | 8 ++++++++ 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index de7c8efda3..9d16c8ae68 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -243,7 +243,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {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>{tr(cardsGpus.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={KV_CHOICES.map(c => ({ value: c.value, label: c.label, title: c.hint }))} onChange={setKv}/>{tr(KV_CHOICES.find(c => c.value === kv)?.hint ? <small className="muted native-kv-hint">{tr(KV_CHOICES.find(c => c.value === kv)!.hint)}</small> : null)}</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"><PcComputer gpuName={pcGpu?.name} ramGb={pcRam} vramGb={pcVram} vramAllGb={pcGpus.reduce((n, g) => n + g.vram_gb, 0) || undefined} loaded={loadedModels} selectedLoaded={!!selectedSize && loadedModels.some(m => m.id === selectedSize.id)} diskGb={selectedSize?.multi_file ? selectedSize.disk_gb ?? selectedSize.download_gb : null} inUse={keptModels.length ? { ramGb: Math.round(keptRam), vramGb: Math.round(keptVramOn(chosenCards)) } : null} fit={selectedSize ? fitOn(selectedSize, fitHardware, true, { context, kv }) : 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} className="other-models">{tr("Other local models\u2026")}</Btn></aside> + <aside className="stack stack--lg"><PcComputer gpuName={pcGpu?.name} ramGb={pcRam} vramGb={pcVram} vramAllGb={pcGpus.reduce((n, g) => n + g.vram_gb, 0) || undefined} loaded={loadedModels} selectedLoaded={!!selectedSize && loadedModels.some(m => m.id === selectedSize.id)} diskGb={selectedSize?.multi_file ? selectedSize.disk_gb ?? selectedSize.download_gb : null} inUse={keptModels.length ? { ramGb: Math.round(keptRam), vramGb: Math.round(keptVramOn(chosenCards)) } : null} fit={selectedSize ? fitOn(selectedSize, fitHardware, true, { context, kv }) : null}/><section className="st-card"><h2 className="h4">{tr("Model files")}</h2><code className="native-path">{installed?.dataFolder ?? native?.downloadDirectory ?? native?.installed?.data_folder ?? 'Choose an installation'}</code><div className="model-files__actions"><Btn size="sm" variant="ghost" onClick={() => { setSettingsSection('Storage'); go('settings'); }}>{tr("Storage settings")}</Btn><Btn size="sm" variant="ghost" onClick={onOtherModels} className="other-models">{tr("Other local models\u2026")}</Btn></div></section></aside> </div> <Dialog open={!!plan} title={tr(installed?.ready ? "Apply settings and load" : "Download and prepare")} compact onClose={() => !pending && setPlan(null)} actions={<><Btn disabled={pending} onClick={() => setPlan(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={pending || !!plan?.plan?.disk_short} onClick={() => void download()}>{tr(installed?.ready ? "Apply & load" : "Download & load")}</Btn></>}><p><strong>{tr(plan?.plan?.title ?? selectedFamily?.title)}</strong>{tr(installed?.ready ? null : <>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}</>)}</p>{tr(plan?.drafting?.needed ? <p className="small muted">{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])}</p> : null)}{tr(installed?.ready ? <p className="small muted">{tr("The model files are already on this computer. Nothing will be downloaded; only the settings you chose are applied.")}</p> : null)}{tr(plan?.plan?.disk_short ? <ErrorNotice message={plan.plan.disk_short}/> : null)}{tr(installed?.ready ? <p className="small muted">{tr("Any currently loaded native models will be unloaded first.")}</p> : <><p className="small muted">{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}</p><p className="small muted">{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}</p></>)}{tr(selectedSize?.images ? <p className="small muted">{tr("Vision encoder files are included. Picture reading loads only when enabled.")}</p> : null)}</Dialog> diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index 721bc7d038..b9071580b4 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -349,12 +349,14 @@ body { } } -/* The one action under the model-files card read as a centred footer because a - stretched control centres its label. It sits at the card's left edge now, as - a quiet text action under the thing it belongs to. */ -.other-models { - align-self: flex-start; - padding-left: 12px; +/* "Other local models..." is part of the Model files card, beside "Storage settings" + (owner, 11-01), as a quiet text action. */ +.model-files__actions { + display: flex; + flex-wrap: wrap; + gap: 4px 8px; +} +.model-files__actions .other-models { font-weight: 500; } diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index 7484d5b46b..783b5c9138 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -64,3 +64,11 @@ test('6: the conversation context opens at 128K for every configuration, or the const guided = read('src/components/GuidedSetup.tsx'); assert.match(guided, /pickedContext \?\? \(contextIsTight\(topCardGb, DEFAULT_CONTEXT\) \? OLD_DEFAULT_CONTEXT : defaultContext\(native\?\.catalog\?\.contexts\)\)/); }); + +test('7 and 8: Model files has no explanatory sentence and holds "Other local models..." beside Storage settings', () => { + const card = models.slice(models.indexOf('<h2 className="h4">{tr("Model files")}</h2>'), models.indexOf('</aside>')); + assert.ok(!/Strata prepares all shards/.test(models), 'the sentence is gone'); + assert.ok(!/<p className="small muted">/.test(card), 'the card holds no paragraph'); + assert.match(card, /<div className="model-files__actions"><Btn[\s\S]*?>\{tr\("Storage settings"\)\}<\/Btn><Btn[^>]*onClick=\{onOtherModels\}[^>]*>\{tr\("Other local models\\u2026"\)\}<\/Btn><\/div><\/section>/, 'inside the card, after Storage settings'); + assert.ok(!/<\/section><Btn[^>]*other-models/.test(models), 'not a separate control under the card'); +}); From e22a48d866b3ea20401dc78684163892c7e3c068 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:32:28 +0100 Subject: [PATCH 32/59] Subagents dropdown: with none, the title says No subagents recorded on the row with the X; no icon, no explanation, no empty body --- apps/host/src/components/ChatToolbar.tsx | 2 +- apps/host/src/styles/annotation-fixes.css | 3 --- apps/host/src/styles/app.css | 2 ++ apps/host/tests/ui-r3.test.mjs | 8 ++++++++ 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/apps/host/src/components/ChatToolbar.tsx b/apps/host/src/components/ChatToolbar.tsx index a4708e48c5..bb04d0fedc 100644 --- a/apps/host/src/components/ChatToolbar.tsx +++ b/apps/host/src/components/ChatToolbar.tsx @@ -39,7 +39,7 @@ export function ChatToolbar({ session, items, selected, onSelect, onClose, onClo return <header className="chat-toolbar" style={previews && !expanded && previewWidth ? { gridTemplateColumns: `minmax(0,1fr) ${previewWidth}px` } : undefined} data-timeskip={selected?.startsWith('time-skip:') || undefined} data-preview={previews || undefined} data-expanded={expanded && previews || undefined}> <div className="chat-toolbar__conversation"><h1 title={title}>{title}</h1><ChatModelPicker /><button ref={agentsRef} className="chat-agents" title={tr(count ? `${count} subagents running · View overview` : 'View subagent overview')} aria-label={tr(count ? `${count} subagents running — show overview` : 'Subagents — show overview')} aria-haspopup="dialog" aria-expanded={agents} data-working={count > 0 || undefined} onClick={() => setAgents(v => !v)}><Icon name="experts" size={17}/>{tr(count > 0 ? <span className="agent-live-dot"/> : null)}<span className="chat-agents__label">{tr("Subagents")}</span>{tr(session?.agents?.length ? <span className="chat-agents__count">{tr(count || session.agents.length)}</span> : null)}<Icon name="chevron" className={agents ? 'is-open' : ''} size={13}/></button><span className="spacer"/><button ref={menuRef} className="st-btn st-btn--icon" title={tr("Chat options")} aria-label={tr("Chat options")} aria-haspopup="menu" aria-expanded={menu} onClick={() => setMenu(v => !v)}><Icon name="ellipsis"/></button>{tr(!selected && (items.length || extraTabs.length) ? <IconBtn name="panel" title={tr("Open previews")} onClick={() => onSelect(extraTabs.at(-1)?.id ?? items[0].id)}/> : null)}</div> {tr(previews ? <div className="chat-toolbar__previews"><ArtifactTabs extraTabs={extraTabs} onCloseTab={onCloseTab} items={items} selected={selected} onSelect={onSelect}/><div className="preview-window-actions"><div id="preview-file-actions" className="preview-file-actions"/><IconBtn name={expanded ? 'contract' : 'expand'} title={tr(expanded ? 'Exit full screen preview' : 'Full screen preview')} onClick={onExpand}/><IconBtn name="panel" title={tr("Collapse preview sidebar")} onClick={onClose}/></div></div> : null)} - {tr(agents ? <Popover anchor={agentsRef.current} title={tr("Subagents")} detail={session?.agents?.length ? <>{tr(count)}{tr(" running \u00B7 ")}{tr(session.agents.filter(a => a.status === 'completed').length)}{tr(" completed \u00B7 ")}{tr(session.agents.length)}{tr(" total")}</> : undefined} width={460} onClose={() => setAgents(false)}>{tr(session?.agents?.length ? <>{tr(session.agents.map(a => <SubagentRow key={a.id} agent={a} now={now} sessionId={session && !session.showcase ? session.id : undefined}/>))}</> : <div className="subagents-empty"><Icon name="experts" size={24}/><strong>{tr("No subagents recorded")}</strong><p className="small muted">{tr("Subagents that run in this conversation appear here, with their progress, token usage and elapsed time. Completed runs stay visible.")}</p></div>)}</Popover> : null)} + {tr(agents ? <Popover anchor={agentsRef.current} title={tr(session?.agents?.length ? "Subagents" : "No subagents recorded")} detail={session?.agents?.length ? <>{tr(count)}{tr(" running \u00B7 ")}{tr(session.agents.filter(a => a.status === 'completed').length)}{tr(" completed \u00B7 ")}{tr(session.agents.length)}{tr(" total")}</> : undefined} width={460} onClose={() => setAgents(false)}>{tr(session?.agents?.length ? <>{tr(session.agents.map(a => <SubagentRow key={a.id} agent={a} now={now} sessionId={session && !session.showcase ? session.id : undefined}/>))}</> : null)}</Popover> : null)} {tr(menu ? <FloatingMenu anchor={menuRef.current} title={tr("Chat options")} onClose={() => setMenu(false)}><button role="menuitem" className="menu__item" disabled={!!remote} title={tr(remote ? "API models use their provider’s response settings." : undefined)} onClick={() => { setMenu(false); setSettings(true); }}><Icon name="sliders"/>{tr("Response settings")}</button><button role="menuitem" className="menu__item" disabled={!session} onClick={() => { if (session) downloadSessionLog(session); setMenu(false); }}><Icon name="download"/>{tr("Download session log")}</button></FloatingMenu> : null)} <SamplingDrawer open={settings} onClose={() => setSettings(false)}/> diff --git a/apps/host/src/styles/annotation-fixes.css b/apps/host/src/styles/annotation-fixes.css index 05e7cc2067..2d9e0f8af3 100644 --- a/apps/host/src/styles/annotation-fixes.css +++ b/apps/host/src/styles/annotation-fixes.css @@ -597,9 +597,6 @@ html[data-motion='reduced'] .task-tree-row[data-leaving] { opacity: 0; } [data-preview-resizing='true'] .artifact-panel iframe { pointer-events:none; } .chat-toolbar__conversation { container-type:inline-size; container-name:chat-controls; } .chat-agents__count { font-size:11px; font-variant-numeric:tabular-nums; } -.subagents-empty { display:grid; justify-items:start; gap:10px; padding:18px 0 8px; } -.subagents-empty > svg { color:var(--st-ink-muted); } -.subagents-empty p { line-height:1.7; } .subagents-overview-summary { padding:8px 0 12px; } @container chat-controls (max-width:560px) { .chat-agents__label { display:none; } } @container chat-controls (max-width:460px) { .chat-toolbar__conversation .chat-model-badge { max-width:112px; } } diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index 6aa767d646..d04f0601bf 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7333,6 +7333,8 @@ textarea { .telepop__detail { margin-right: auto; font-size: var(--st-fs-sm); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; white-space: nowrap; } .telepop__head > .st-btn { align-self: center; margin-left: auto; } .telepop__detail + .st-btn { margin-left: 0; } +/* a popover with nothing under its title (Subagents, none recorded) is one row: no rule and no space below it */ +.telepop__head:last-child { padding-bottom: 0; margin-bottom: 0; border-bottom: 0; } /* the way back to the newest message: a small round arrow, shown only while scrolled up */ .jumplatest-row { position: relative; height: 0; flex: none; z-index: 3; } diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index 783b5c9138..0f5a281621 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -72,3 +72,11 @@ test('7 and 8: Model files has no explanatory sentence and holds "Other local mo assert.match(card, /<div className="model-files__actions"><Btn[\s\S]*?>\{tr\("Storage settings"\)\}<\/Btn><Btn[^>]*onClick=\{onOtherModels\}[^>]*>\{tr\("Other local models\\u2026"\)\}<\/Btn><\/div><\/section>/, 'inside the card, after Storage settings'); assert.ok(!/<\/section><Btn[^>]*other-models/.test(models), 'not a separate control under the card'); }); + +test('12: with no subagents the dropdown is one row, "No subagents recorded" and the X, with no icon and no explanation', () => { + const bar = read('src/components/ChatToolbar.tsx'); + assert.match(bar, /title=\{tr\(session\?\.agents\?\.length \? "Subagents" : "No subagents recorded"\)\}/, 'the empty state is the title'); + assert.ok(!/subagents-empty|Subagents that run in this conversation/.test(bar), 'no icon, no explanatory text'); + assert.ok(!/subagents-empty/.test(read('src/styles/annotation-fixes.css')), 'no dead rule'); + assert.match(read('src/styles/app.css'), /\.telepop__head:last-child \{ padding-bottom: 0; margin-bottom: 0; border-bottom: 0; \}/, 'no empty body under the title'); +}); From 04a007771cde92cfd9c685710a8b713ae25810ef Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:34:18 +0100 Subject: [PATCH 33/59] Tasks: the Board and Schedule help lines move into the header after the Tasks title, smaller, wrapping at narrow widths --- apps/host/src/components/TaskBoard.tsx | 1 - apps/host/src/screens/Tasks.tsx | 3 +-- apps/host/src/styles/annotation-fixes.css | 6 ++++++ apps/host/src/styles/app.css | 2 -- apps/host/src/styles/board.css | 2 -- apps/host/tests/ui-r3.test.mjs | 9 +++++++++ 6 files changed, 16 insertions(+), 7 deletions(-) diff --git a/apps/host/src/components/TaskBoard.tsx b/apps/host/src/components/TaskBoard.tsx index 43e3e67e5a..920eec0c60 100644 --- a/apps/host/src/components/TaskBoard.tsx +++ b/apps/host/src/components/TaskBoard.tsx @@ -179,7 +179,6 @@ export function TaskBoard({ query, canRun, onViewResult }: { query: string; canR const total = Object.values(board.columns).reduce((n, c) => n + c.length, 0); return <div className="board-wrap"> - <p className="board-note"><Icon name="info" size={16}/>{tr('Cards move on their own as things happen. A card in Needs attention stays there until you deal with it or dismiss it.')}</p> <p className="sr-only" role="status" aria-live="polite">{board.need ? tr('{0} need your attention', [board.need]) : tr('Nothing needs you right now.')}</p> <div className="board"> {COLUMNS.map(col => { diff --git a/apps/host/src/screens/Tasks.tsx b/apps/host/src/screens/Tasks.tsx index 27a4f38f4f..a8abb2bc5f 100644 --- a/apps/host/src/screens/Tasks.tsx +++ b/apps/host/src/screens/Tasks.tsx @@ -80,10 +80,9 @@ export function TasksScreen() { {tr(currentTask.lastRunAt || currentTask.output || currentTask.error ? <Btn icon="chat" disabled={pending || currentTask.status === 'running'} onClick={() => continueTaskInNewChat(currentTask)}>{tr("Continue in a new chat")}</Btn> : null)} <Btn variant="primary" icon={currentTask.status === 'running' ? 'stop' : 'bolt'} disabled={pending || !loaded && currentTask.status !== 'running'} onClick={() => void action(() => api.post(`/api/tasks/${currentTask.id}/${currentTask.status === 'running' ? 'stop' : 'run'}`))}>{tr(currentTask.status === 'running' ? 'Stop' : 'Run now')}</Btn> </div> : null; - return <Screen width={view === 'board' && !currentTask ? 'full' : 'normal'} title={currentTask ? <span className="sr-only">{currentTask.title}</span> : "Tasks"} actions={currentTask ? taskHeader : <div className="tasks-actions"><Seg ariaLabel="View" value={view} onChange={setView} options={[{ value: 'schedule', label: 'Schedule', icon: 'clock' }, { value: 'board', label: 'Board', icon: 'panel' }]}/><input className="st-input tasks-search" type="search" aria-label={tr("Search tasks")} placeholder={tr("Search tasks…")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(view === 'board' ? null : <Select ariaLabel={tr("Sort tasks")} value={sort} options={[{ value: 'next', label: 'Next run' }, { value: 'name', label: 'Name' }]} onChange={setSort}/>)}<IconBtn name="plus" title={tr("New task")} onClick={() => open(blank())}/></div>}> + return <Screen width={view === 'board' && !currentTask ? 'full' : 'normal'} title={currentTask ? <span className="sr-only">{currentTask.title}</span> : "Tasks"} titleDetail={currentTask ? undefined : view === 'board' ? <span className="tasks-note"><Icon name="info" size={14}/>{tr('Cards move on their own as things happen. A card in Needs attention stays there until you deal with it or dismiss it.')}</span> : <span className="tasks-note"><Icon name="clock" size={14}/>{tr(library?.mode === 'simulated' ? 'Example model · sample answers. ' : '')}{tr("Runs while Strata’s host is open. Runs saved instructions using the loaded model.")}</span>} actions={currentTask ? taskHeader : <div className="tasks-actions"><Seg ariaLabel="View" value={view} onChange={setView} options={[{ value: 'schedule', label: 'Schedule', icon: 'clock' }, { value: 'board', label: 'Board', icon: 'panel' }]}/><input className="st-input tasks-search" type="search" aria-label={tr("Search tasks")} placeholder={tr("Search tasks…")} value={query} onChange={e => setQuery(e.target.value)}/>{tr(view === 'board' ? null : <Select ariaLabel={tr("Sort tasks")} value={sort} options={[{ value: 'next', label: 'Next run' }, { value: 'name', label: 'Name' }]} onChange={setSort}/>)}<IconBtn name="plus" title={tr("New task")} onClick={() => open(blank())}/></div>}> <div className="tasks-page"> - {tr(!currentTask && view !== 'board' && <p className="task-runtime small muted"><Icon name="clock" size={16}/>{tr(library?.mode === 'simulated' ? 'Example model · sample answers. ' : '')}{tr("Runs while Strata\u2019s host is open. Runs saved instructions using the loaded model.")}</p>)} {tr(error && !editor ? <ErrorNotice message={error} onRetry={() => void refresh()}/> : null)} {tr(currentTask || view === 'board' ? null : !ready ? <p className="muted">{tr("Loading tasks\u2026")}</p> : !visible.length ? <div className="tasks-empty"><span className="tasks-empty__art"><Icon name="clock" size={30}/></span><h2 className="h3">{tr(query ? 'No matching tasks' : 'No scheduled tasks yet')}</h2>{tr(query ? <p className="muted">{tr('Try another search.')}</p> : <Btn variant="primary" icon="plus" onClick={() => open(blank())}>{tr("New task")}</Btn>)}</div> : <div className="task-list">{tr(visible.map(t => <article key={t.id} className="task-row"><span className="task-icon"><Icon name="clock" size={24}/></span><div className="task-copy"><h2 className="h4">{t.title}</h2><p className="small muted">{tr(t.status === 'running' ? 'Running…' : t.enabled ? (t.nextRunAt ? `Next: ${new Date(t.nextRunAt).toLocaleString(localeTag(), { dateStyle: 'medium', timeStyle: 'short' })}` : 'Scheduled · calculating next run') : 'Paused')} · {tr(t.timeZone)}</p>{tr(t.error ? <button className="task-failed text-action" onClick={() => setResult(t.id!)}>{tr("Last run failed \u00B7 View")}</button> : null)}{tr(t.output ? <button className="text-action" onClick={() => setResult(t.id!)}>{tr("View last result")}{tr(t.demo ? ' · Example' : '')}</button> : null)}</div><div className="row"><><IconBtn name="pencil" title={tr("Edit {0}", [t.title])} disabled={pending || t.status === 'running'} onClick={() => open(t)}/><Btn size="sm" icon={t.status === 'running' ? 'stop' : 'bolt'} title={tr(t.status === 'running' ? `Stop ${t.title}` : `Run ${t.title} now`)} disabled={pending || !loaded} onClick={() => void action(() => api.post(`/api/tasks/${t.id}/${t.status === 'running' ? 'stop' : 'run'}`))}>{tr(t.status === 'running' ? 'Stop' : 'Run now')}</Btn><label className="row small"><span>{tr("On schedule")}</span><button className="st-toggle" role="switch" aria-label={tr("Schedule {0}", [t.title])} aria-checked={t.enabled} disabled={pending || t.status === 'running'} onClick={() => void action(() => api.patch(`/api/tasks/${t.id}`, { enabled: !t.enabled }))}/></label></></div></article>))}</div>)} {tr(!currentTask && view === 'board' ? <TaskBoard query={query} canRun={!!loaded || !!native?.instances.some(i => i.status === 'ready')} onViewResult={setResult}/> : null)} diff --git a/apps/host/src/styles/annotation-fixes.css b/apps/host/src/styles/annotation-fixes.css index 2d9e0f8af3..ff5c2cb25a 100644 --- a/apps/host/src/styles/annotation-fixes.css +++ b/apps/host/src/styles/annotation-fixes.css @@ -157,6 +157,12 @@ html[data-motion='reduced'] .voice-wave span, html[data-motion='reduced'] .agent .main__title-line .main__title { margin: 0; flex: none; } .main__title-detail { font-size: var(--st-fs-xs); color: var(--st-ink-muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .main__titles { min-width: 0; } +/* Tasks: the help line (Board, Schedule) sits in the header after the title, smaller than body text. It wraps rather than being cut, and the header grows + to hold it, so it stays readable at narrow widths. */ +.main__title-detail:has(.tasks-note) { white-space: normal; overflow: visible; text-overflow: clip; line-height: 1.35; } +.tasks-note { display: inline-flex; align-items: flex-start; gap: 6px; max-width: 68ch; } +.tasks-note > svg { flex: none; margin-top: 1px; } +.main__head:has(.tasks-note) { height: auto; } .skills-header-search.st-input { width: 200px; min-width: 0; } .skills-library-title { margin: 0 0 20px; } .dialog-head__actions { display: flex; align-items: center; gap: 12px; flex: none; } diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index d04f0601bf..8d71a4e11d 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -5688,8 +5688,6 @@ textarea.config-editor.st-input { .hardware-cards article > svg { color: var(--st-ink-muted); flex: none; margin-top: 4px; } .hardware-cards h3 { margin: 6px 0; overflow-wrap: anywhere; } .tasks-page { display: flex; flex-direction: column; gap: 20px; } -.task-runtime { display: flex; align-items: flex-start; gap: 8px; } -.task-runtime > svg { flex: none; margin-top: 2px; } .tasks-empty { min-height: 270px; display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 16px; text-align: center; } .tasks-empty > svg { color: var(--st-ink-muted); margin-bottom: 12px; } .task-templates { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 24px 40px; border-top: 1px solid var(--st-line); padding-top: 36px; } diff --git a/apps/host/src/styles/board.css b/apps/host/src/styles/board.css index f3562dd893..ef81ac2184 100644 --- a/apps/host/src/styles/board.css +++ b/apps/host/src/styles/board.css @@ -5,8 +5,6 @@ .navsession__dot--warn { background: var(--st-warn); } .board-wrap { container-type: inline-size; min-width: 0; } -.board-note { display: flex; align-items: center; gap: 8px; margin: 0 0 14px; font-size: var(--st-fs-sm); color: var(--st-ink-muted); } -.board-note svg { flex: none; } .board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; align-items: start; } @container (max-width: 1080px) { .board { grid-template-columns: repeat(2, minmax(0, 1fr)); } } @container (max-width: 560px) { .board { grid-template-columns: minmax(0, 1fr); } } diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index 0f5a281621..253bfd96ad 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -80,3 +80,12 @@ test('12: with no subagents the dropdown is one row, "No subagents recorded" and assert.ok(!/subagents-empty/.test(read('src/styles/annotation-fixes.css')), 'no dead rule'); assert.match(read('src/styles/app.css'), /\.telepop__head:last-child \{ padding-bottom: 0; margin-bottom: 0; border-bottom: 0; \}/, 'no empty body under the title'); }); + +test('14: the Board and Schedule help lines sit in the Tasks header after the title, smaller, and wrap rather than being cut', () => { + const tasks = read('src/screens/Tasks.tsx'), board = read('src/components/TaskBoard.tsx'), css = read('src/styles/annotation-fixes.css'); + assert.match(tasks, /titleDetail=\{currentTask \? undefined : view === 'board' \? <span className="tasks-note"><Icon name="info" size=\{14\}\/>\{tr\('Cards move on their own as things happen\./); + assert.match(tasks, /<span className="tasks-note"><Icon name="clock" size=\{14\}\/>[\s\S]*Runs while Strata\u2019s host is open\. Runs saved instructions using the loaded model\./); + assert.ok(!/board-note|task-runtime/.test(tasks + board + read('src/styles/board.css') + read('src/styles/app.css')), 'not repeated in the body'); + assert.match(css, /\.main__title-detail:has\(\.tasks-note\) \{ white-space: normal; overflow: visible;/, 'wraps instead of being cut at narrow widths'); + assert.match(css, /\.main__head:has\(\.tasks-note\) \{ height: auto; \}/, 'the header grows to hold it'); +}); From 8d6351f55fac91fbd7ce32d5b0f954dae31201a5 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:36:17 +0100 Subject: [PATCH 34/59] Load model: no pop-up. The press starts it; the plan is read first and a disk that is too small is said in the page and stops it; the download size sits beside the button and the DFlash2 drafter download is said in the page while it runs --- apps/host/src/components/NativeModels.tsx | 26 +++++++++++++++++------ apps/host/src/styles/annotation-fixes.css | 3 +++ apps/host/tests/ui-r3.test.mjs | 16 ++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 9d16c8ae68..05bc1df136 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -48,7 +48,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const [expert, setExpert] = useKept('models.expert', manual), [multiple, setMultiple] = useKept('models.multiple', false), [roles, setRoles] = useKept<Roles | null>('models.roles', null), [kv, setKv] = useKept('models.kv', 'int8'), [lowRam, setLowRam] = useKept('models.lowRam', 'auto'), [split, setSplit] = useKept('models.split', 'auto'); const [resourceProfile, setResourceProfile] = useKept<'work' | 'performance'>('models.profile', 'work'); const [drafting, setDrafting] = useState('auto'); - const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState<Record<string, any> | null>(null), [loadedError, setLoadedError] = useState(''), [tuneOpen, setTuneOpen] = useState(false), [jobId, setJobId] = useKept('models.job', ''), [manage, setManage] = useState(false); + const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState<Record<string, any> | null>(null), [drafterGb, setDrafterGb] = useState<number | null>(null), [loadedError, setLoadedError] = useState(''), [tuneOpen, setTuneOpen] = useState(false), [jobId, setJobId] = useKept('models.job', ''), [manage, setManage] = useState(false); const [toastedJob, setToastedJob] = useKept('models.toasted', ''), [appliedSig, setAppliedSig] = useKept('models.applied', ''); const presetPending = useRef(false); const [deleting, setDeleting] = useState<string | null>(null); @@ -190,13 +190,23 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine finally { setPending(false); } } + /* Load model: no pop-up. The press itself is the yes. The plan is read first (Control checks the free disk space); a disk that is too small is said + here, in the page, and nothing starts. Otherwise the download or the apply-and-load starts at once, with its size and notes in the page. */ async function load() { if (!selectedSize) - return; await perform(async () => { if (installed?.ready && context === installed.context && (!selectedSize?.images || vision === 'no' || installed.images && installed.images !== 'off') && (!installed.kv || kv === installed.kv || kv === tunedNow?.fields.kv) && (lowRam === (installed.lowRamMode ?? 'auto') || lowRam === tunedNow?.fields.lowRam)) { + return; setPlan(null); setDrafterGb(null); await perform(async () => { if (installed?.ready && context === installed.context && (!selectedSize?.images || vision === 'no' || installed.images && installed.images !== 'off') && (!installed.kv || kv === installed.kv || kv === tunedNow?.fields.kv) && (lowRam === (installed.lowRamMode ?? 'auto') || lowRam === tunedNow?.fields.lowRam)) { const result = await nativeAction<NativeJob>('operations', { kind: 'load', args: { model: selectedSize.id, resourceProfile, vision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), multiple: expert && multiple, ...(draftingChoices ? { values: { drafting } } : {}), ...(roleCards.length > 1 ? (roles && customRoles ? { gpuRoles: effectiveRoles, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : cardsGpus.length ? { gpus: cardsGpus, gpusFromRecommendation: true, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : {}) : {}) } }); setJobId(result.id); } - else - setPlan(await api.post('/api/native/plan', downloadValues)); }); } + else { + const planned = await api.post<Record<string, any>>('/api/native/plan', downloadValues); + if (planned?.plan?.disk_short) { + setPlan(planned); + return; + } + setDrafterGb(planned?.drafting?.needed ? Number(planned.drafting.gb) || null : null); + const result = await nativeAction<NativeJob>('operations', { kind: 'install', args: downloadValues }); + setJobId(result.id); + } }); } /* Unload / Use in chat: a refusal (a chat is still using the model) is said here, beside the button, not far below the page. */ async function loadedAction(path: string) { setLoadedError(''); setPending(true); try { await nativeAction(path); @@ -208,6 +218,9 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine setPending(false); } } async function download() { await perform(async () => { const result = await nativeAction<NativeJob>('operations', { kind: 'install', args: downloadValues }); setJobId(result.id); setPlan(null); }); } + // The drafter note belongs to the download that is running; the not-enough-disk message belongs to the version it was said for. + useEffect(() => { if (!active) setDrafterGb(null); }, [!!active]); + useEffect(() => { setPlan(null); }, [selectedSize?.id]); return <Screen plainHeader title={<span className="sr-only">{tr("Models")}</span>} titleDetail={<FamilySwitch families={families} selected={selectedFamily?.family} onPick={f => { setFamily(f.family); setSize((f.sizes.find(s => native?.installed?.models.some(m => m.model === s.id && m.ready)) ?? f.sizes[0])?.id ?? ''); setVision('yes'); setError(''); }}/>} actions={<Btn icon="sliders" aria-pressed={expert} aria-expanded={expert} aria-controls="native-expert-settings" onClick={() => { setExpert(v => !v); setMultiple(false); }}>{tr(expert ? 'Close expert mode' : 'Expert mode')}</Btn>}> <div className="native-model-layout native-model-layout--fit"> <div className="stack"> @@ -234,11 +247,13 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine <EngineUpdateCard native={native} busy={!!active}/> <EngineUpdateDialog open={false} onClose={() => {}}/> {tr(active ? <NativeProgress job={active} label={jobLabel(active)}/> : null)} + {tr(active && drafterGb ? <p className="small muted native-spill-note"><Icon name="info" size={16}/>{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.", [drafterGb])}</p> : null)} {tr(active ? <p className="small muted native-wait-note">{tr("The buttons below wait until this finishes.")}</p> : null)} {tr(job?.state === 'error' ? <ErrorNotice message={job.error ?? job.summary} action={tr("Retry")} onRetry={() => void load()}/> : null)} + {tr(plan?.plan?.disk_short ? <ErrorNotice message={plan.plan.disk_short}/> : null)} {tr(error ? <ErrorNotice message={error}/> : null)} {selectedSize && installed?.ready ? <NativeTuneBadge model={selectedSize.id} resourceProfile={resourceProfile} vision={selectedSize.images ? vision : 'no'}/> : null} - <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 || selectedSize.needsNewerEngine} onClick={() => setTuneOpen(true)}>{tr("Tune model")}</Btn><Btn variant="primary" icon="models" disabled={pending || !native?.available || !!active || !selectedSize || !!selectedSize.needsNewerEngine} onClick={() => void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')}</Btn></>)}</div> + <div className="native-model-actions">{tr(!loadedSelected && !installed?.ready && selectedSize?.download_gb && !active ? <span className="native-download-size small muted">{tr("{0} download", [sizeGb(selectedSize.download_gb)])}</span> : null)}{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 || selectedSize.needsNewerEngine} onClick={() => setTuneOpen(true)}>{tr("Tune model")}</Btn><Btn variant="primary" icon="models" disabled={pending || !native?.available || !!active || !selectedSize || !!selectedSize.needsNewerEngine} 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>{tr(cardsGpus.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={KV_CHOICES.map(c => ({ value: c.value, label: c.label, title: c.hint }))} onChange={setKv}/>{tr(KV_CHOICES.find(c => c.value === kv)?.hint ? <small className="muted native-kv-hint">{tr(KV_CHOICES.find(c => c.value === kv)!.hint)}</small> : null)}</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)} @@ -246,7 +261,6 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine <aside className="stack stack--lg"><PcComputer gpuName={pcGpu?.name} ramGb={pcRam} vramGb={pcVram} vramAllGb={pcGpus.reduce((n, g) => n + g.vram_gb, 0) || undefined} loaded={loadedModels} selectedLoaded={!!selectedSize && loadedModels.some(m => m.id === selectedSize.id)} diskGb={selectedSize?.multi_file ? selectedSize.disk_gb ?? selectedSize.download_gb : null} inUse={keptModels.length ? { ramGb: Math.round(keptRam), vramGb: Math.round(keptVramOn(chosenCards)) } : null} fit={selectedSize ? fitOn(selectedSize, fitHardware, true, { context, kv }) : null}/><section className="st-card"><h2 className="h4">{tr("Model files")}</h2><code className="native-path">{installed?.dataFolder ?? native?.downloadDirectory ?? native?.installed?.data_folder ?? 'Choose an installation'}</code><div className="model-files__actions"><Btn size="sm" variant="ghost" onClick={() => { setSettingsSection('Storage'); go('settings'); }}>{tr("Storage settings")}</Btn><Btn size="sm" variant="ghost" onClick={onOtherModels} className="other-models">{tr("Other local models\u2026")}</Btn></div></section></aside> </div> -<Dialog open={!!plan} title={tr(installed?.ready ? "Apply settings and load" : "Download and prepare")} compact onClose={() => !pending && setPlan(null)} actions={<><Btn disabled={pending} onClick={() => setPlan(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={pending || !!plan?.plan?.disk_short} onClick={() => void download()}>{tr(installed?.ready ? "Apply & load" : "Download & load")}</Btn></>}><p><strong>{tr(plan?.plan?.title ?? selectedFamily?.title)}</strong>{tr(installed?.ready ? null : <>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}</>)}</p>{tr(plan?.drafting?.needed ? <p className="small muted">{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])}</p> : null)}{tr(installed?.ready ? <p className="small muted">{tr("The model files are already on this computer. Nothing will be downloaded; only the settings you chose are applied.")}</p> : null)}{tr(plan?.plan?.disk_short ? <ErrorNotice message={plan.plan.disk_short}/> : null)}{tr(installed?.ready ? <p className="small muted">{tr("Any currently loaded native models will be unloaded first.")}</p> : <><p className="small muted">{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}</p><p className="small muted">{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}</p></>)}{tr(selectedSize?.images ? <p className="small muted">{tr("Vision encoder files are included. Picture reading loads only when enabled.")}</p> : null)}</Dialog> <NativeDeleteDialog id={deleting} onClose={() => setDeleting(null)}/> <Dialog open={manage} compact title={tr("Manage models")} onClose={() => setManage(false)} actions={<Btn onClick={() => setManage(false)}>{tr("Done")}</Btn>}><div className="native-manage"> {tr(downloaded.some(m => m.ready || m.diskGb) ? <div className="native-manage-list" role="list">{tr(downloaded.filter(m => m.ready || m.diskGb).map(m => { const v = allSizes.find(x => x.id === m.model), loaded = native?.instances.some(i => i.model === m.model && i.status === 'ready'); return <div className="native-manage-row" role="listitem" key={m.model} data-selected={selectedSize?.id === m.model || undefined}> diff --git a/apps/host/src/styles/annotation-fixes.css b/apps/host/src/styles/annotation-fixes.css index ff5c2cb25a..68527bd611 100644 --- a/apps/host/src/styles/annotation-fixes.css +++ b/apps/host/src/styles/annotation-fixes.css @@ -648,6 +648,9 @@ html[data-motion='reduced'] .task-tree-row[data-leaving] { opacity: 0; } .native-gpu-options input { accent-color:var(--st-accent); } .native-gpu-options small { display:block; margin-top:5px; color:var(--st-ink-muted); } .native-model-actions { display:flex; gap:16px; justify-content:flex-end; border-top:1px solid var(--st-line); padding-top:20px; } +/* Load model has no pop-up: what the download is sits beside the button that starts it */ +.native-model-actions { align-items:center; } +.native-download-size { margin-right:auto; font-variant-numeric:tabular-nums; } .native-path { display:block; font-size:11px; line-height:1.8; overflow-wrap:anywhere; margin:16px 0; } .native-settings { margin-top:24px; border-top:1px solid var(--st-line-soft); padding-top:20px; } .native-settings>summary, .native-progress summary,.native-generation>summary { font-size:13px; font-weight:600; cursor:pointer; } diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index 253bfd96ad..ffd3868990 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -89,3 +89,19 @@ test('14: the Board and Schedule help lines sit in the Tasks header after the ti assert.match(css, /\.main__title-detail:has\(\.tasks-note\) \{ white-space: normal; overflow: visible;/, 'wraps instead of being cut at narrow widths'); assert.match(css, /\.main__head:has\(\.tasks-note\) \{ height: auto; \}/, 'the header grows to hold it'); }); + +test('13: Load model has no pop-up: the size and the warnings are in the page, a disk that is too small stops it there', () => { + assert.ok(!/<Dialog open=\{!!plan\}/.test(models), 'the download and prepare dialog is gone'); + assert.ok(!/Download and prepare|Apply settings and load|Apply & load/.test(models), 'none of its words are left'); + // The press is the yes: the plan is read (Control checks the free disk), a short disk is said inline and nothing starts, otherwise the install starts at once. + const load = models.slice(models.indexOf('async function load()'), models.indexOf('/* Unload / Use in chat')); + assert.match(load, /api\.post<Record<string, any>>\('\/api\/native\/plan', downloadValues\)/); + assert.match(load, /if \(planned\?\.plan\?\.disk_short\) \{\s*setPlan\(planned\);\s*return;\s*\}/, 'safety: not enough disk, nothing starts'); + assert.match(load, /kind: 'install', args: downloadValues/, 'otherwise it starts at once'); + assert.match(models, /\{tr\(plan\?\.plan\?\.disk_short \? <ErrorNotice message=\{plan\.plan\.disk_short\}\/> : null\)\}/, 'the disk message is in the page'); + assert.match(models, /active && drafterGb \? <p className="small muted native-spill-note"><Icon name="info" size=\{16\}\/>\{tr\("Choosing DFlash2 also downloads its drafter/, 'the extra download is said in the page while it runs'); + assert.match(models, /className="native-download-size small muted">\{tr\("\{0\} download", \[sizeGb\(selectedSize\.download_gb\)\]\)\}/, 'the download size sits beside the button'); + // The warnings for a version that does not fit stay inline (item 5): SSD streaming and Doesn't fit under the version list. + assert.match(models, /fitState === 'ssd' \? <p className="small muted native-spill-note"><Icon name="disk" size=\{16\}\/>/); + assert.match(models, /fitState === 'no' \? <p className="small muted native-spill-note"><Icon name="warning" size=\{16\}\/>/); +}); From fbaff162bc02a53ccb34dc6e5aa8a4b0711c030a Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:38:02 +0100 Subject: [PATCH 35/59] DFlash2: graphics memory of the Q4_0 drafter is 0.8 GB (engine: 799 MiB) --- strata_control/drafting.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strata_control/drafting.py b/strata_control/drafting.py index fe915b369d..9916d3b72a 100644 --- a/strata_control/drafting.py +++ b/strata_control/drafting.py @@ -168,7 +168,7 @@ PACK_NAME = "qwen3.8-flash-next-dflash2.q4_0.pack" PACK_BYTES = 522458112 # the Q4_0 pack tools/dflash2_pack.py --q4_0 makes from the pinned safetensors file, and its SHA-256 PACK_SHA256 = "cda40d62d0eb8f37ed6e272142641a1d2f0de4a32f9e14d0416e7a71534849f1" LEGACY_PACK_NAME = "qwen3.8-flash-next-dflash2.q8.pack" # what Strata 0.2.9 test builds packed: still used when it is the one on disk -VRAM_GB = 1.0 # what the drafter needs in graphics memory (the engine's own estimate, measured with the Q4_0 pack) +VRAM_GB = 0.8 # what the drafter needs in graphics memory: the engine reports "drafter 799 MiB of VRAM" with the Q4_0 pack (1026 MiB with the Q8 pack), p620 gfx1201 FOLDER = "dflash2" # under the model data folder, next to ``mtp`` SPEC_WINDOW = 6 # --spec with DFlash2: the widest window of drafted words per round (measured best on Blackwell; the engine caps it per card) DRAFT_CONF = 0.35 # --draft-conf with DFlash2: the window ends where the chance that every draft so far holds falls below this From c738d5bf34219298f0845a942fd8119c41f954d7 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:48:53 +0100 Subject: [PATCH 36/59] A chat that is working shows it on its sidebar row (a slow ring where the unread dot sits), and the model chip names the working chat while you are elsewhere --- apps/host/scripts/make-r3-locales.py | 6 ++++++ apps/host/src/app/Sidebar.tsx | 13 ++++++++++--- apps/host/src/locales/r3-de.json | 4 +++- apps/host/src/locales/r3-en.json | 4 +++- apps/host/src/locales/r3-es.json | 4 +++- apps/host/src/locales/r3-fr.json | 4 +++- apps/host/src/locales/r3-ja.json | 4 +++- apps/host/src/locales/r3-ko.json | 4 +++- apps/host/src/locales/r3-pt.json | 4 +++- apps/host/src/locales/r3-ru.json | 4 +++- apps/host/src/locales/r3-zh.json | 4 +++- apps/host/src/styles/liquid.css | 27 +++++++++++++++++++++++++++ apps/host/tests/ui-r3.test.mjs | 13 +++++++++++++ 13 files changed, 83 insertions(+), 12 deletions(-) diff --git a/apps/host/scripts/make-r3-locales.py b/apps/host/scripts/make-r3-locales.py index e17f88bc9e..560b9c5838 100644 --- a/apps/host/scripts/make-r3-locales.py +++ b/apps/host/scripts/make-r3-locales.py @@ -34,6 +34,12 @@ add("This much context takes about {0} GB of graphics memory and leaves little r "이 정도의 컨텍스트는 그래픽 메모리를 약 {0} GB 사용하며 이 카드에서는 모델이 쓸 공간이 거의 남지 않습니다. Strata가 시도하지만 시작되지 않으면 더 짧은 컨텍스트를 선택하세요.", "Ce contexte occupe environ {0} Go de mémoire graphique et laisse peu de place au modèle sur cette carte. Strata va essayer ; s'il ne démarre pas, choisissez un contexte plus court.") +# 9: a chat that is working while the person is elsewhere (the ring on its row, and the model chip's line) +add("Working · {0}", + "进行中 · {0}", "作業中 · {0}", "In Arbeit · {0}", "Trabajando · {0}", "В работе · {0}", "Trabalhando · {0}", "작업 중 · {0}", "En cours de travail · {0}") +add("{0} chats working", + "{0} 个对话进行中", "{0} 件のチャットが作業中", "{0} Chats in Arbeit", "{0} chats trabajando", "В работе чатов: {0}", "{0} chats trabalhando", "대화 {0}개 작업 중", "{0} conversations en cours") + #@@MORE@@ here = Path(__file__).resolve().parent.parent / "src" / "locales" diff --git a/apps/host/src/app/Sidebar.tsx b/apps/host/src/app/Sidebar.tsx index 1194e31eee..1cdaf48586 100644 --- a/apps/host/src/app/Sidebar.tsx +++ b/apps/host/src/app/Sidebar.tsx @@ -18,7 +18,7 @@ import { MOD, runCommand } from '../lib/commands'; import { bindingFor, bindingKeys, useBindings } from '../lib/shortcut-bindings'; import { Btn, Dialog, Icon, IconBtn, type IconName } from '../components/ui'; import { Brand } from '../components/Brand'; -import { addWorkspace, deleteSession, go, isUnread, pickWorkspace, renameSession, removeWorkspace, renameWorkspace, selectSession, setActiveWorkspace, setNavOpen, togglePin, toggleRail, setTheme, useStore } from '../lib/store'; +import { addWorkspace, deleteSession, go, isUnread, liveChatIds, pickWorkspace, renameSession, removeWorkspace, renameWorkspace, selectSession, setActiveWorkspace, setNavOpen, togglePin, toggleRail, setTheme, useStore } from '../lib/store'; export function Sidebar({ containerRef }: { containerRef: RefObject<HTMLElement | null>; }) { @@ -37,6 +37,9 @@ export function Sidebar({ containerRef }: { const workspaces = useStore(s => s.workspaces); const activeWorkspace = useStore(s => s.activeWorkspace); const activeSession = useStore(s => s.activeSession); + // The chats that have a turn running now (the board reads the same list). The count is what makes this redraw when one starts or ends. + const liveCount = useStore(s => s.liveChats); + const working = new Set(liveCount ? liveChatIds() : []); const [query, setQuery] = useState(''); const [searchOpen, setSearchOpen] = useState(false); const searchInput = useRef<HTMLInputElement>(null); @@ -65,6 +68,10 @@ export function Sidebar({ containerRef }: { const modelQuant = nativeSecond ?? current?.quant ?? tr('View model versions'); const phase = nativeCurrent ? (nativeCurrent.status === 'ready' ? nativeCurrent.phase : nativeCurrent.status) : monitor?.phase ?? 'idle'; const status = phase === 'unavailable' ? 'Status unavailable' : phase === 'error' ? 'Error' : phase === 'loading' ? 'Loading' : !current && !nativeCurrent ? 'No model loaded' : phase === 'reading' ? 'Reading prompt' : phase === 'thinking' ? 'Thinking' : phase === 'generating' ? 'Generating' : 'Ready'; + // The model is busy with a chat that is not the one in front of the person: the chip says which one (a title, or how many). + const awayChats = [...working].filter(id => !(location.route === 'chat' && id === activeSession)); + const awayTitle = awayChats.length === 1 ? sessions.find(s => s.id === awayChats[0]) : undefined; + const workingLine = awayChats.length === 1 && awayTitle ? tr("Working · {0}", [sessionTitle(awayTitle)]) : awayChats.length > 1 ? tr("{0} chats working", [awayChats.length]) : null; const menuSession = sessions.find(s => s.id === menuId); const q = query.trim().toLowerCase(); const matching = sessions.filter(s => (!s.archived || q || includeArchived) && (!q || `${sessionTitle(s)} ${s.messages.map(m => m.content).join(' ')}`.toLowerCase().includes(q))).sort((a, b) => Number(!!b.pinned) - Number(!!a.pinned) || b.updatedAt.localeCompare(a.updatedAt)); @@ -92,7 +99,7 @@ export function Sidebar({ containerRef }: { <div className={cx('ws__row', activeWorkspace === w.id && 'is-active')}><button className="ws__name" aria-expanded={expanded} onClick={() => { setActiveWorkspace(w.id); setFolders(f => ({ ...f, [w.id]: !expanded })); }}><Icon name="chevron" size={14} className={cx('ws__chev', expanded && 'is-open')}/><Icon name="folder" size={17}/><span>{w.name}</span></button><IconBtn name="pencil" title={tr("Rename {0}", [w.name])} onClick={() => { setWsName(w.name); setNavOpen(false); setRenameWsId(w.id); }}/>{tr(w.id !== 'root' ? <IconBtn name="x" title={tr("Remove {0} from sidebar", [w.name])} onClick={() => { setNavOpen(false); setRemoveWorkspaceId(w.id); }}/> : null)}</div> {tr(expanded ? <div className="navsessions"> {tr(shown.map(s => <div key={s.id}> - <div className="ws__session row"><a className="navsession" href={href('chat', s.id)} aria-current={activeSession === s.id && location.route === 'chat' ? 'page' : undefined} onClick={() => selectSession(s.id)} onContextMenu={e => { e.preventDefault(); openMenu(s.id, e.currentTarget); }} title={sessionTitle(s)}><span className="navsession__title">{sessionTitle(s)}</span>{tr(s.pinned ? <span aria-label={tr("Pinned")}><Icon name="pin" size={12}/></span> : <span className="navsession__time">{relTimeShort(s.updatedAt)}</span>)}{tr(isUnread(s, activeSession) ? <span className="navsession__unread" aria-label={tr("Unread")}/> : null)}{tr(s.archived ? <span className="xs muted">{tr("Archived")}</span> : null)}</a><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Actions for {0}", [sessionTitle(s)])} onClick={e => openMenu(s.id, e.currentTarget)}><Icon name="ellipsis" size={16}/></button></div> + <div className="ws__session row"><a className="navsession" href={href('chat', s.id)} data-working={working.has(s.id) || undefined} aria-current={activeSession === s.id && location.route === 'chat' ? 'page' : undefined} onClick={() => selectSession(s.id)} onContextMenu={e => { e.preventDefault(); openMenu(s.id, e.currentTarget); }} title={sessionTitle(s)}><span className="navsession__title">{sessionTitle(s)}</span>{tr(s.pinned ? <span aria-label={tr("Pinned")}><Icon name="pin" size={12}/></span> : <span className="navsession__time">{relTimeShort(s.updatedAt)}</span>)}{tr(working.has(s.id) ? <span className="navsession__working" role="img" aria-label={tr("Working")} title={tr("Working")}/> : isUnread(s, activeSession) ? <span className="navsession__unread" aria-label={tr("Unread")}/> : null)}{tr(s.archived ? <span className="xs muted">{tr("Archived")}</span> : null)}</a><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Actions for {0}", [sessionTitle(s)])} onClick={e => openMenu(s.id, e.currentTarget)}><Icon name="ellipsis" size={16}/></button></div> </div>))} {tr(!shown.length ? <p className="small muted ws__empty">{tr(q ? 'No matching chats' : 'No chats yet')}</p> : null)} {tr(!q && rows.length > shown.length ? <button className="ws-view small" onClick={() => { setNavOpen(false); setRecentOpen(true); }}>{tr("View all chats")}</button> : null)} @@ -102,7 +109,7 @@ export function Sidebar({ containerRef }: { </div> : null} </div> <div className="nav__foot"> - <button className="enginechip" data-state={status === 'Ready' ? 'ready' : ['Reading prompt', 'Thinking', 'Generating', 'Loading'].includes(status) ? 'busy' : 'off'} onClick={() => go('models')} title={tr("{0} \u00B7 {1} \u00B7 {2}", [modelName, modelQuant, tr(status)])} aria-label={tr("{0} \u00B7 {1}", [modelName, modelQuant])}><span className="enginechip__family"><Icon name={modelFamilyIcon(current?.family)} size={20}/><span className="enginechip__dot"/></span><span className="enginechip__text nav__rail-hide"><span className="enginechip__title">{modelName}</span><span className="enginechip__sub">{modelQuant}</span></span></button> + <button className="enginechip" data-state={status === 'Ready' ? 'ready' : ['Reading prompt', 'Thinking', 'Generating', 'Loading'].includes(status) ? 'busy' : 'off'} onClick={() => go('models')} title={tr("{0} \u00B7 {1} \u00B7 {2}", [modelName, workingLine ?? modelQuant, tr(status)])} aria-label={tr("{0} \u00B7 {1}", [modelName, modelQuant])}><span className="enginechip__family"><Icon name={modelFamilyIcon(current?.family)} size={20}/><span className="enginechip__dot"/></span><span className="enginechip__text nav__rail-hide"><span className="enginechip__title">{modelName}</span><span className="enginechip__sub">{workingLine ?? modelQuant}</span></span></button> <NavLink route="skills" label={tr("Skills")} icon="skills" current={location.route}/> <NavLink route="monitor" label={tr("Monitor")} icon="activity" current={location.route}/> <NavLink route="models" label={tr("Models")} icon="models" current={location.route === 'tuning' ? 'models' : location.route}/> diff --git a/apps/host/src/locales/r3-de.json b/apps/host/src/locales/r3-de.json index 86cc195ebe..6408ed125f 100644 --- a/apps/host/src/locales/r3-de.json +++ b/apps/host/src/locales/r3-de.json @@ -1,5 +1,7 @@ { "r3_01": "Braucht ein Engine-Update", "r3_02": "SSD-Streaming · läuft langsamer", - "r3_03": "So viel Kontext belegt etwa {0} GB Grafikspeicher und lässt auf dieser Karte wenig Platz für das Modell. Strata versucht es; startet es nicht, wähle einen kürzeren Kontext." + "r3_03": "So viel Kontext belegt etwa {0} GB Grafikspeicher und lässt auf dieser Karte wenig Platz für das Modell. Strata versucht es; startet es nicht, wähle einen kürzeren Kontext.", + "r3_04": "In Arbeit · {0}", + "r3_05": "{0} Chats in Arbeit" } diff --git a/apps/host/src/locales/r3-en.json b/apps/host/src/locales/r3-en.json index 07dd1d8c58..a5f9cdd9f9 100644 --- a/apps/host/src/locales/r3-en.json +++ b/apps/host/src/locales/r3-en.json @@ -1,5 +1,7 @@ { "r3_01": "Needs an engine update", "r3_02": "SSD streaming · will run slower", - "r3_03": "This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context." + "r3_03": "This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context.", + "r3_04": "Working · {0}", + "r3_05": "{0} chats working" } diff --git a/apps/host/src/locales/r3-es.json b/apps/host/src/locales/r3-es.json index 424604f7df..9b14199500 100644 --- a/apps/host/src/locales/r3-es.json +++ b/apps/host/src/locales/r3-es.json @@ -1,5 +1,7 @@ { "r3_01": "Necesita actualizar el motor", "r3_02": "Streaming desde el SSD · irá más lento", - "r3_03": "Este contexto ocupa unos {0} GB de memoria gráfica y deja poco espacio para el modelo en esta tarjeta. Strata lo intentará; si no arranca, elige un contexto más corto." + "r3_03": "Este contexto ocupa unos {0} GB de memoria gráfica y deja poco espacio para el modelo en esta tarjeta. Strata lo intentará; si no arranca, elige un contexto más corto.", + "r3_04": "Trabajando · {0}", + "r3_05": "{0} chats trabajando" } diff --git a/apps/host/src/locales/r3-fr.json b/apps/host/src/locales/r3-fr.json index 13602afb14..d1bbcf1387 100644 --- a/apps/host/src/locales/r3-fr.json +++ b/apps/host/src/locales/r3-fr.json @@ -1,5 +1,7 @@ { "r3_01": "Nécessite une mise à jour du moteur", "r3_02": "Streaming depuis le SSD · plus lent", - "r3_03": "Ce contexte occupe environ {0} Go de mémoire graphique et laisse peu de place au modèle sur cette carte. Strata va essayer ; s’il ne démarre pas, choisissez un contexte plus court." + "r3_03": "Ce contexte occupe environ {0} Go de mémoire graphique et laisse peu de place au modèle sur cette carte. Strata va essayer ; s’il ne démarre pas, choisissez un contexte plus court.", + "r3_04": "En cours de travail · {0}", + "r3_05": "{0} conversations en cours" } diff --git a/apps/host/src/locales/r3-ja.json b/apps/host/src/locales/r3-ja.json index 17de9387fa..6075400211 100644 --- a/apps/host/src/locales/r3-ja.json +++ b/apps/host/src/locales/r3-ja.json @@ -1,5 +1,7 @@ { "r3_01": "エンジンの更新が必要です", "r3_02": "SSD ストリーミング · 動作は遅くなります", - "r3_03": "このコンテキストはグラフィックスメモリーを約 {0} GB 使い、このカードではモデルに残る余裕がわずかです。Strata は試しますが、起動しない場合はより短いコンテキストを選んでください。" + "r3_03": "このコンテキストはグラフィックスメモリーを約 {0} GB 使い、このカードではモデルに残る余裕がわずかです。Strata は試しますが、起動しない場合はより短いコンテキストを選んでください。", + "r3_04": "作業中 · {0}", + "r3_05": "{0} 件のチャットが作業中" } diff --git a/apps/host/src/locales/r3-ko.json b/apps/host/src/locales/r3-ko.json index b6f5deeb5f..6a03a09a19 100644 --- a/apps/host/src/locales/r3-ko.json +++ b/apps/host/src/locales/r3-ko.json @@ -1,5 +1,7 @@ { "r3_01": "엔진 업데이트가 필요합니다", "r3_02": "SSD 스트리밍 · 더 느리게 실행됩니다", - "r3_03": "이 정도의 컨텍스트는 그래픽 메모리를 약 {0} GB 사용하며 이 카드에서는 모델이 쓸 공간이 거의 남지 않습니다. Strata가 시도하지만 시작되지 않으면 더 짧은 컨텍스트를 선택하세요." + "r3_03": "이 정도의 컨텍스트는 그래픽 메모리를 약 {0} GB 사용하며 이 카드에서는 모델이 쓸 공간이 거의 남지 않습니다. Strata가 시도하지만 시작되지 않으면 더 짧은 컨텍스트를 선택하세요.", + "r3_04": "작업 중 · {0}", + "r3_05": "대화 {0}개 작업 중" } diff --git a/apps/host/src/locales/r3-pt.json b/apps/host/src/locales/r3-pt.json index 0394c2d4bf..b5a20a554d 100644 --- a/apps/host/src/locales/r3-pt.json +++ b/apps/host/src/locales/r3-pt.json @@ -1,5 +1,7 @@ { "r3_01": "Precisa de uma atualização do motor", "r3_02": "Streaming do SSD · vai rodar mais devagar", - "r3_03": "Esse contexto ocupa cerca de {0} GB de memória gráfica e deixa pouco espaço para o modelo nesta placa. O Strata vai tentar; se não iniciar, escolha um contexto menor." + "r3_03": "Esse contexto ocupa cerca de {0} GB de memória gráfica e deixa pouco espaço para o modelo nesta placa. O Strata vai tentar; se não iniciar, escolha um contexto menor.", + "r3_04": "Trabalhando · {0}", + "r3_05": "{0} chats trabalhando" } diff --git a/apps/host/src/locales/r3-ru.json b/apps/host/src/locales/r3-ru.json index 412a730a85..75f021fe20 100644 --- a/apps/host/src/locales/r3-ru.json +++ b/apps/host/src/locales/r3-ru.json @@ -1,5 +1,7 @@ { "r3_01": "Нужно обновить движок", "r3_02": "Потоковая подгрузка с SSD · будет работать медленнее", - "r3_03": "Такой контекст занимает около {0} ГБ видеопамяти и оставляет модели мало места на этой карте. Strata попробует запустить; если не получится, выберите контекст короче." + "r3_03": "Такой контекст занимает около {0} ГБ видеопамяти и оставляет модели мало места на этой карте. Strata попробует запустить; если не получится, выберите контекст короче.", + "r3_04": "В работе · {0}", + "r3_05": "В работе чатов: {0}" } diff --git a/apps/host/src/locales/r3-zh.json b/apps/host/src/locales/r3-zh.json index b477ae8639..429318d98a 100644 --- a/apps/host/src/locales/r3-zh.json +++ b/apps/host/src/locales/r3-zh.json @@ -1,5 +1,7 @@ { "r3_01": "需要更新引擎", "r3_02": "SSD 流式读取 · 运行会更慢", - "r3_03": "这么长的上下文大约占用 {0} GB 显存,留给模型的空间很少。Strata 会尝试运行;如果无法启动,请选择更短的上下文。" + "r3_03": "这么长的上下文大约占用 {0} GB 显存,留给模型的空间很少。Strata 会尝试运行;如果无法启动,请选择更短的上下文。", + "r3_04": "进行中 · {0}", + "r3_05": "{0} 个对话进行中" } diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index b9071580b4..c6b9e0e7de 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -708,6 +708,32 @@ body { translate: 0 -50%; transition: opacity var(--st-t-micro) var(--st-ease-standard); } +/* A chat that has a turn running while the person is elsewhere: a small ring turns in the same gutter as the unread dot (it takes the dot's place: a + working chat is not "unread" yet). Info colour and a slow turn keep it calm; reduced motion holds it still. */ +.ws__session .navsession__working { + position: absolute; + top: 50%; + right: 7px; + width: 12px; + height: 12px; + border: 2px solid var(--st-info-tint); + border-top-color: var(--st-info); + border-radius: 50%; + translate: 0 -50%; + animation: st-spin 1400ms linear infinite; + transition: opacity var(--st-t-micro) var(--st-ease-standard); +} +.navsession[data-working] .navsession__title { + color: var(--st-ink); +} +@media (prefers-reduced-motion: reduce) { + .ws__session .navsession__working { + animation: none; + } +} +html[data-motion='reduced'] .ws__session .navsession__working { + animation: none; +} .ws__session .session-overflow { position: absolute; top: 50%; @@ -725,6 +751,7 @@ body { pointer-events: auto; } .ws__session:hover .navsession__time, +.ws__session:hover .navsession__working, .ws__session:hover .navsession__unread { opacity: 0; } diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index ffd3868990..ff11b0564e 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -105,3 +105,16 @@ test('13: Load model has no pop-up: the size and the warnings are in the page, a assert.match(models, /fitState === 'ssd' \? <p className="small muted native-spill-note"><Icon name="disk" size=\{16\}\/>/); assert.match(models, /fitState === 'no' \? <p className="small muted native-spill-note"><Icon name="warning" size=\{16\}\/>/); }); + +test('9: a chat that is working shows it on its sidebar row, and the model chip says which chat when it is elsewhere', () => { + const bar = read('src/app/Sidebar.tsx'), css = read('src/styles/liquid.css'); + assert.match(bar, /const working = new Set\(liveCount \? liveChatIds\(\) : \[\]\)/, 'the same list of running turns the board reads'); + assert.match(bar, /data-working=\{working\.has\(s\.id\) \|\| undefined\}/); + assert.match(bar, /working\.has\(s\.id\) \? <span className="navsession__working" role="img" aria-label=\{tr\("Working"\)\}/, 'a labelled cue, not only colour'); + assert.match(bar, /: isUnread\(s, activeSession\) \? <span className="navsession__unread"/, 'a working chat is not also shown as unread'); + assert.match(bar, /\{workingLine \?\? modelQuant\}/, 'the model chip names the working chat'); + assert.match(bar, /!\(location\.route === 'chat' && id === activeSession\)/, 'no line for the chat that is in front of the person'); + assert.match(css, /\.ws__session \.navsession__working \{[^}]*border-top-color: var\(--st-info\);[^}]*animation: st-spin 1400ms linear infinite;/, 'existing tokens, one slow turn'); + assert.match(css, /prefers-reduced-motion: reduce\) \{\s*\.ws__session \.navsession__working \{\s*animation: none;/, 'reduced motion holds it still'); + assert.match(css, /html\[data-motion='reduced'\] \.ws__session \.navsession__working \{\s*animation: none;/); +}); From 20c617a8cac36833fefb6e3d01d7ecf950c02234 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:48:58 +0100 Subject: [PATCH 37/59] Chat while it works: Stop and Send are one height so the box stops moving, one live cue per tool step, the caret follows text only, a slot for the host's live step and output on an open activity line, and the sidebar preview opens and closes in 460 ms --- apps/host/src/components/ArtifactPanel.tsx | 5 +++-- apps/host/src/components/Deliverables.tsx | 10 ++++++--- apps/host/src/lib/deliverables.ts | 10 +++++++-- apps/host/src/screens/Chat.tsx | 7 ++++-- apps/host/src/styles/annotation-fixes.css | 2 ++ apps/host/src/styles/app.css | 5 ++++- apps/host/src/styles/liquid.css | 11 +++++---- apps/host/tests/chat-details.test.mjs | 4 ++-- apps/host/tests/ui-r3.test.mjs | 26 ++++++++++++++++++++++ 9 files changed, 64 insertions(+), 16 deletions(-) diff --git a/apps/host/src/components/ArtifactPanel.tsx b/apps/host/src/components/ArtifactPanel.tsx index 92fce0a1be..985ee03cb5 100644 --- a/apps/host/src/components/ArtifactPanel.tsx +++ b/apps/host/src/components/ArtifactPanel.tsx @@ -69,9 +69,10 @@ export function ArtifactPanel({ items, selected, onSelect, onClose, onCloseTab, if (current) { hadCurrent.current = true; setLeaving(false); return; } if (!hadCurrent.current || !inline) return; hadCurrent.current = false; - if (matchMedia('(prefers-reduced-motion: reduce)').matches) return; + if (matchMedia('(prefers-reduced-motion: reduce)').matches || document.documentElement.dataset.motion === 'reduced') return; setLeaving(true); - const timer = setTimeout(() => setLeaving(false), 260); + // The leaving shell takes the 460 ms step of the motion scale (liquid.css); it is removed just after. + const timer = setTimeout(() => setLeaving(false), 520); return () => clearTimeout(timer); }, [!!current, inline]); if (!current) diff --git a/apps/host/src/components/Deliverables.tsx b/apps/host/src/components/Deliverables.tsx index 3d9f4e8aa6..0b49aae159 100644 --- a/apps/host/src/components/Deliverables.tsx +++ b/apps/host/src/components/Deliverables.tsx @@ -80,13 +80,17 @@ export function ActivityLine({ group, sessionId, onPreview }: { group: ActivityG const picture = group.files.find(f => f.kind === 'image'); // The host's sentence may end with the numbers ("… +225 −0"): they are drawn as figures instead. const sentence = group.line.replace(/\s*\+\d+\s*[−-]\s*\d+\s*$/, ''); - return <div className="act" data-open={open || undefined}> + // While the run is open this is the live step: the host's own words for it when it sends them, else the line it already had. + const live = !group.closed; + return <><div className="act" data-open={open || undefined} data-live={live || undefined}> <button type="button" className="act__line" aria-expanded={open} disabled={!group.files.length} onClick={() => setOpen(v => !v)}> - <span>{sentence}</span>{group.added || group.removed ? <Plusminus added={group.added} removed={group.removed}/> : null} + <span>{live && group.live?.label ? group.live.label : sentence}</span>{group.added || group.removed ? <Plusminus added={group.added} removed={group.removed}/> : null} {group.files.length ? <Icon name="chevron" size={14} className="act__chev"/> : null} {!group.closed ? <span className="act__live" aria-hidden="true"/> : null} </button> {picture ? <img className="act__thumb" src={rawUrlOf(sessionId, picture.path)} alt="" loading="lazy" onClick={() => void showOf(picture, sessionId, onPreview)}/> : null} {open ? <ul className="act__files">{group.files.map(f => <li key={f.path}><button type="button" onClick={() => void showOf(f, sessionId, onPreview, f.kind)}><Icon name="file" size={14}/>{f.name}{f.added || f.removed ? <Plusminus added={f.added} removed={f.removed}/> : null}</button></li>)}</ul> : null} - </div>; + </div> + {live && group.live?.output ? <p className="act__output" title={group.live.output}>{group.live.output}</p> : null} + </>; } diff --git a/apps/host/src/lib/deliverables.ts b/apps/host/src/lib/deliverables.ts index e839b016c4..66ae675c14 100644 --- a/apps/host/src/lib/deliverables.ts +++ b/apps/host/src/lib/deliverables.ts @@ -11,7 +11,10 @@ export type DeliverableKind = 'html' | 'markdown' | 'pdf' | 'csv' | 'image' | 'c export interface Deliverable { path: string; abs: string; name: string; kind: DeliverableKind; status: 'created' | 'changed'; size: number; lines: number | null; added: number; removed: number; /** Which write came last in this reply (set when the host's frames are merged): the newest is the run's main result. */ order?: number } export interface GroupFile { path: string; name: string; kind: DeliverableKind; status: string; added: number; removed: number } -export interface ActivityGroup { id: string; closed: boolean; line: string; added: number; removed: number; files: GroupFile[] } +/** What is happening in a run right now (the host sends it while the group is open and drops it when the group closes): `label` is the step in plain words + * ("Writing pagoda.html"), `output` the last line the step printed or the progress it can name ("412 lines written"). Optional: a group without it draws as before. */ +export interface GroupLive { label?: string; output?: string } +export interface ActivityGroup { id: string; closed: boolean; line: string; added: number; removed: number; files: GroupFile[]; live?: GroupLive } export type MessageBlock = { kind: 'text'; text: string } | ({ kind: 'group' } & ActivityGroup); const KINDS = ['html', 'markdown', 'pdf', 'csv', 'image', 'code', 'text', 'other']; @@ -36,7 +39,10 @@ export function readGroup(raw: unknown): ActivityGroup | null { const d = readDeliverable(x); return d ? [{ path: d.path, name: d.name, kind: d.kind, status: d.status, added: d.added, removed: d.removed }] : []; }) : []; - return { id: g.id, closed: g.closed === true, line: typeof g.line === 'string' ? g.line : '', added: num(g.added), removed: num(g.removed), files }; + const liveRaw = g.live && typeof g.live === 'object' ? g.live as Record<string, unknown> : null; + const last = (text: string) => text.trim().split(/\r?\n/).at(-1)!.slice(0, 200); + const live: GroupLive | undefined = liveRaw && g.closed !== true ? { ...(typeof liveRaw.label === 'string' && liveRaw.label ? { label: liveRaw.label.slice(0, 160) } : {}), ...(typeof liveRaw.output === 'string' && liveRaw.output.trim() ? { output: last(liveRaw.output) } : {}) } : undefined; + return { id: g.id, closed: g.closed === true, line: typeof g.line === 'string' ? g.line : '', added: num(g.added), removed: num(g.removed), files, ...(live && (live.label || live.output) ? { live } : {}) }; } /** The `skills-used` frame: the skills this reply used, each with the name the person gave it and a one-line description. */ diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index f0c4ff9c23..23e9b1fb4d 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -748,7 +748,9 @@ function MessageView({ message: m, isLast, onEditPrompt, onPreview, onClosePrevi {tr(m.reasoning ? <ReasoningBlock message={m}/> : null)} - {tr((m.tools ?? []).filter(t => !grouped || t.state !== 'done').map((t) => (<ToolCard key={t.id} tool={t}/>)))} + {/* In a reply with activity lines the line is the one live cue for a running or finished tool (and the status line below says what it is doing now); the + card stays only for what needs the person: a question waiting, a denied or failed call. A card that came and went above the text moved the whole reply. */} + {tr((m.tools ?? []).filter(t => !grouped || t.state === 'proposed' || t.state === 'denied' || t.state === 'error').map((t) => (<ToolCard key={t.id} tool={t}/>)))} {tr(!(m.timeSkipId && timeSkipReal && !timeSkipDone) && (m.content || m.error || !m.streaming || !liveStatus) ? <div className="st-bubble"> {tr(planCard ? <PlanCard chatId={activeSession} planId={m.planId!}/> : null)} @@ -759,7 +761,8 @@ function MessageView({ message: m, isLast, onEditPrompt, onPreview, onClosePrevi <i /> <i /> </span>) : null)} - {tr(m.streaming && m.content ? <span className="caret" aria-hidden="true"/> : null)} + {/* the caret follows the text being written; after an activity line it hung on a row of its own and the reply jumped when the text went on */} + {tr(m.streaming && m.content && (!grouped || m.blocks!.at(-1)?.kind === 'text') ? <span className="caret" aria-hidden="true"/> : null)} </div> : null)} {tr(m.skills?.length && !m.streaming ? <SkillsUsed skills={m.skills}/> : null)} {tr(m.deliverables?.length && !m.streaming ? <div className="deliverables">{m.deliverables.map(f => <FileCard key={f.path} file={f} sessionId={activeSession ?? ''} onPreview={onPreview}/>)}<EditedFiles files={m.deliverables} sessionId={activeSession ?? ''} onPreview={onPreview}/></div> : null)} diff --git a/apps/host/src/styles/annotation-fixes.css b/apps/host/src/styles/annotation-fixes.css index 68527bd611..e227119378 100644 --- a/apps/host/src/styles/annotation-fixes.css +++ b/apps/host/src/styles/annotation-fixes.css @@ -129,6 +129,8 @@ html[data-motion='reduced'] .tunnel-automatic .tunnel-stage__symbol .st-icon, ht .composer::before, .composer::after { display: none; } .st-composer__bar, .chatsplit[data-preview='true'] .st-composer__bar { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; } .st-composer__bar > .spacer, .chatsplit[data-preview='true'] .st-composer__bar > .spacer { display: block; flex: 1; min-width: 0; } +/* Stop and Send are the same height: Stop (secondary) was 38px and Send (primary) 32px, so the whole message box moved 5px every time a reply started or ended. */ +.st-composer__bar > .st-btn:not(.st-btn--icon) { height: 32px; min-height: 32px; box-sizing: border-box; } .composer-mic { display: grid; place-items: center; flex: none; width: 32px; height: 34px; border: 0; border-radius: 9px; background: transparent; color: var(--st-ink-muted); cursor: pointer; } .composer-mic:hover, .composer-mic[aria-pressed='true'] { color: var(--st-accent-text); background: var(--st-surface-2); } .composer-mode { max-width: 170px; } diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index 8d71a4e11d..3c069d4ee6 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7157,7 +7157,7 @@ textarea { .tool-summary > div { margin-top: 6px; padding-left: 20px; } /* ---- the live status line ---- */ -.live-status { display: grid; grid-template-columns: 14px minmax(0, 24ch) 6ch minmax(0, auto); align-items: center; column-gap: 10px; min-height: 28px; margin-top: 6px; color: var(--st-ink-soft); font-size: var(--st-fs-sm); } +.live-status { display: grid; grid-template-columns: 14px minmax(0, 32ch) 6ch minmax(0, auto); align-items: center; column-gap: 10px; min-height: 28px; margin-top: 6px; color: var(--st-ink-soft); font-size: var(--st-fs-sm); } /* the word has its own area: the timer and the token count stay where they are while the word changes length */ .live-status__verb { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .live-status__time, .live-status__tokens { font-variant-numeric: tabular-nums; color: var(--st-ink-muted); white-space: nowrap; } @@ -7444,6 +7444,9 @@ textarea { .act__chev { color: var(--st-icon); transition: transform var(--st-t-local) var(--st-ease-standard); } .act[data-open] .act__chev { transform: rotate(180deg); } .act__live { width: 6px; height: 6px; border-radius: 50%; background: var(--st-accent); animation: st-pulse 1.6s var(--st-ease-in-out) infinite; } +/* The step that is running reads as the current one (ink, not the muted past-tense of the lines above it) and its last output sits under it on one fixed line. */ +.act[data-live] .act__line { color: var(--st-ink); } +.act__output { margin: -4px 0 8px; padding-left: 1px; min-height: 1.4em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--st-font-mono); font-size: var(--st-fs-xs); line-height: 1.4; color: var(--st-ink-muted); } .act__thumb { width: 44px; height: 30px; object-fit: cover; border-radius: 6px; border: 1px solid var(--st-line); cursor: pointer; } .act__files { flex-basis: 100%; list-style: none; margin: 0; padding: 0 0 0 4px; display: flex; flex-direction: column; } .act__skill { display: inline-flex; align-items: center; gap: 8px; padding: 4px 0; color: var(--st-ink-soft); } diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index c6b9e0e7de..03422de47b 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -1205,12 +1205,15 @@ html[data-motion='reduced'] .ws__session .navsession__working { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--st-accent) 45%, transparent); } -/* The sidebar preview arrives from the right with a short rise and fade, the +/* The sidebar preview arrives from the right with a rise and fade, the chosen file's content crossfades when you switch tabs, and a closed panel leaves the same way (a bare shell over the column it vacated; the page itself - is already gone, so nothing heavy is animated). */ + is already gone, so nothing heavy is animated). Both take the 460 ms step of + the motion scale (`--st-t-choreo`), slower than a menu or a drawer so the + panel arrives and leaves calmly, with the same easings as before; reduced + motion makes the step 1 ms. */ .chatsplit .artifact-panel { - animation: st-panel-in var(--st-t-surface) var(--st-ease-enter) both; + animation: st-panel-in var(--st-t-choreo) var(--st-ease-enter) both; } .chatsplit .artifact-panel[data-leaving] { position: absolute; @@ -1218,7 +1221,7 @@ html[data-motion='reduced'] .ws__session .navsession__working { width: min(48%, 640px); z-index: 3; pointer-events: none; - animation: st-panel-out var(--st-t-local) var(--st-ease-exit) both; + animation: st-panel-out var(--st-t-choreo) var(--st-ease-exit) both; } .artifact-content { animation: st-enter var(--st-t-control) var(--st-ease-enter) both; diff --git a/apps/host/tests/chat-details.test.mjs b/apps/host/tests/chat-details.test.mjs index 153d76057a..d1cb511fdf 100644 --- a/apps/host/tests/chat-details.test.mjs +++ b/apps/host/tests/chat-details.test.mjs @@ -54,8 +54,8 @@ test('code blocks have room after them and are lighter than the text; the 12px f }); test('the sidebar preview comes in and goes out with motion, from the one motion scale, and the reduced-motion gate zeroes the distance', () => { - assert.match(liquid, /\.chatsplit \.artifact-panel \{\s*animation: st-panel-in var\(--st-t-surface\) var\(--st-ease-enter\) both;/); - assert.match(liquid, /\[data-leaving\] \{[^}]*animation: st-panel-out var\(--st-t-local\) var\(--st-ease-exit\) both;/); + assert.match(liquid, /\.chatsplit \.artifact-panel \{\s*animation: st-panel-in var\(--st-t-choreo\) var\(--st-ease-enter\) both;/); + assert.match(liquid, /\[data-leaving\] \{[^}]*animation: st-panel-out var\(--st-t-choreo\) var\(--st-ease-exit\) both;/); assert.match(liquid, /@media \(prefers-reduced-motion: reduce\) \{\s*:root \{ --st-press-scale: 1; --st-panel-shift: 0px; \}/); }); diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index ff11b0564e..6013c68563 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -118,3 +118,29 @@ test('9: a chat that is working shows it on its sidebar row, and the model chip assert.match(css, /prefers-reduced-motion: reduce\) \{\s*\.ws__session \.navsession__working \{\s*animation: none;/, 'reduced motion holds it still'); assert.match(css, /html\[data-motion='reduced'\] \.ws__session \.navsession__working \{\s*animation: none;/); }); + +test('10 (visual): the reply stays still while it streams, one live cue per step, a slot for the host to feed live output, a slower preview panel', async () => { + const chat = read('src/screens/Chat.tsx'), css = read('src/styles/annotation-fixes.css'), app = read('src/styles/app.css'), liquid = read('src/styles/liquid.css'); + // Stop and Send are one height, so the message box no longer moves 5px when a reply starts and ends. + assert.match(css, /\.st-composer__bar > \.st-btn:not\(\.st-btn--icon\) \{ height: 32px; min-height: 32px; box-sizing: border-box; \}/); + // In a reply with activity lines the line is the one live cue for a tool; the running card above the text is gone. + assert.match(chat, /filter\(t => !grouped \|\| t\.state === 'proposed' \|\| t\.state === 'denied' \|\| t\.state === 'error'\)/); + // The caret follows text, never an activity line. + assert.match(chat, /m\.streaming && m\.content && \(!grouped \|\| m\.blocks!\.at\(-1\)\?\.kind === 'text'\) \? <span className="caret"/); + // A slot for what the host knows while a run is open (AGENT-LOST feeds it): read, shown, dropped at close. + const { readGroup } = await lib('src/lib/deliverables.ts'); + const open = readGroup({ id: 'g', closed: false, line: 'Writing pagoda.html', live: { label: 'Writing pagoda.html', output: 'a\nb\n412 lines written\n' } }); + assert.deepEqual(open.live, { label: 'Writing pagoda.html', output: '412 lines written' }, 'the last line only, one fixed row'); + assert.equal(readGroup({ id: 'g', closed: true, line: 'Wrote a file', live: { label: 'x', output: 'y' } }).live, undefined, 'a closed group has no live part'); + assert.equal(readGroup({ id: 'g', closed: false, line: 'Ran a command' }).live, undefined, 'without data it draws as before'); + const deliver = read('src/components/Deliverables.tsx'); + assert.match(deliver, /live && group\.live\?\.output \? <p className="act__output"/); + assert.match(app, /\.act\[data-live\] \.act__line \{ color: var\(--st-ink\); \}/); + // The sidebar preview opens and closes in 460 ms (the motion scale's own step, existing easings); reduced motion makes it 1 ms. + assert.match(liquid, /animation: st-panel-in var\(--st-t-choreo\) var\(--st-ease-enter\) both;/); + assert.match(liquid, /animation: st-panel-out var\(--st-t-choreo\) var\(--st-ease-exit\) both;/); + assert.match(app, /--st-t-choreo: 460ms;/); + assert.match(app, /@media \(prefers-reduced-motion: reduce\) \{\s*:root \{[^}]*--st-t-choreo: 1ms;/); + assert.match(app, /\[data-motion='reduced'\] \{[^}]*--st-t-choreo: 1ms;/); + assert.match(read('src/components/ArtifactPanel.tsx'), /setTimeout\(\(\) => setLeaving\(false\), 520\)/, 'the leaving shell stays for the whole 460 ms'); +}); From 01dd40aa8fed72049434eee77bba5aeedf52624d Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:51:14 +0100 Subject: [PATCH 38/59] Working ring: its turn is a loop in seconds, as the other loops (the audit wants tokens for transitions) --- apps/host/src/styles/liquid.css | 2 +- apps/host/tests/ui-r3.test.mjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/host/src/styles/liquid.css b/apps/host/src/styles/liquid.css index 03422de47b..a0ed1461e1 100644 --- a/apps/host/src/styles/liquid.css +++ b/apps/host/src/styles/liquid.css @@ -720,7 +720,7 @@ body { border-top-color: var(--st-info); border-radius: 50%; translate: 0 -50%; - animation: st-spin 1400ms linear infinite; + animation: st-spin 1.4s linear infinite; transition: opacity var(--st-t-micro) var(--st-ease-standard); } .navsession[data-working] .navsession__title { diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index 6013c68563..62b8edf18e 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -114,7 +114,7 @@ test('9: a chat that is working shows it on its sidebar row, and the model chip assert.match(bar, /: isUnread\(s, activeSession\) \? <span className="navsession__unread"/, 'a working chat is not also shown as unread'); assert.match(bar, /\{workingLine \?\? modelQuant\}/, 'the model chip names the working chat'); assert.match(bar, /!\(location\.route === 'chat' && id === activeSession\)/, 'no line for the chat that is in front of the person'); - assert.match(css, /\.ws__session \.navsession__working \{[^}]*border-top-color: var\(--st-info\);[^}]*animation: st-spin 1400ms linear infinite;/, 'existing tokens, one slow turn'); + assert.match(css, /\.ws__session \.navsession__working \{[^}]*border-top-color: var\(--st-info\);[^}]*animation: st-spin 1.4s linear infinite;/, 'existing tokens, one slow turn'); assert.match(css, /prefers-reduced-motion: reduce\) \{\s*\.ws__session \.navsession__working \{\s*animation: none;/, 'reduced motion holds it still'); assert.match(css, /html\[data-motion='reduced'\] \.ws__session \.navsession__working \{\s*animation: none;/); }); From 5d4183edfab09569825a9ee39eae6dfa1a0269c9 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:53:06 +0100 Subject: [PATCH 39/59] Polish found in the preview: the SSD warning is said once (under the version picker), notes under controls keep their icon beside the words, the empty Subagents row is centred --- apps/host/src/components/PcFitCard.tsx | 9 ++++----- apps/host/src/styles/annotation-fixes.css | 3 +++ apps/host/src/styles/app.css | 2 +- apps/host/tests/pc-card.test.mjs | 9 +++++---- apps/host/tests/ui-r3.test.mjs | 15 ++++++++++++++- 5 files changed, 27 insertions(+), 11 deletions(-) diff --git a/apps/host/src/components/PcFitCard.tsx b/apps/host/src/components/PcFitCard.tsx index 0c9267187b..fbcadd675b 100644 --- a/apps/host/src/components/PcFitCard.tsx +++ b/apps/host/src/components/PcFitCard.tsx @@ -19,9 +19,9 @@ function FreeMeter({ label, total, free }: { label: string; total: number; free: /** * "This computer": how much graphics memory and RAM is free right now. While a model is loaded that is all the card shows: the hardware line, the model's - * name, "Loaded", what it takes and the SSD line are gone (owner, 11-01: the page already says what is loaded), except one calm sentence when the loaded - * model really reads part of itself from the SSD. Before anything is loaded the card says what the chosen version would take, and the SSD only where the - * version does not fit in memory (how much is read from it); a version that fits says nothing. (The n-gram table, which always sits on the SSD, is not counted.) + * name, "Loaded", what it takes and the SSD line are gone (owner, 11-01: the page already says what is loaded); only while the loaded model really reads + * from the SSD, how fast it reads right now. Before anything is loaded the card says what the chosen version would take. That a version does not fit in + * memory is said once, under the version picker ("SSD streaming · will run slower"), not again here. (The n-gram table, which always sits on the SSD, is not counted.) */ export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null, diskGb = null, live = null, loaded = [], selectedLoaded = false }: { gpuName?: string | null; ramGb: number | null; vramGb: number; fit: Fit | null; inUse?: { ramGb: number; vramGb: number } | null; diskGb?: number | null; live?: PcLive | null; loaded?: PcLoaded[]; selectedLoaded?: boolean }) { const showFit = !!fit?.known && !selectedLoaded; @@ -35,10 +35,9 @@ export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null, diskGb = {tr(live.freeVramGb !== null && vramGb > 0 ? <FreeMeter label="Graphics memory" total={live.vramTotalGb ?? vramGb} free={live.freeVramGb}/> : null)} {tr(live.freeRamGb !== null && ramGb ? <FreeMeter label="RAM" total={ramGb} free={live.freeRamGb}/> : null)} </div> : null)} - {tr(isLoaded && streamed >= 1 ? <p className="pc-note">{tr("About {0} GB will be read from the SSD, so answers can be a little slower.", [Math.round(streamed)])}{tr(live?.diskReadGbs && live.diskReadGbs >= 0.05 ? tr(" Reading from your SSD now: {0}", [`${live.diskReadGbs.toFixed(1)} GB/s`]) : '')}</p> : null)} + {tr(isLoaded && streamed >= 1 && live?.diskReadGbs && live.diskReadGbs >= 0.05 ? <p className="pc-note">{tr("Reading from your SSD now: {0}", [`${live.diskReadGbs.toFixed(1)} GB/s`])}</p> : null)} {tr(inUse ? <p className="xs muted">{tr("Models that stay loaded use about {0} GB of RAM and {1} GB of this card’s memory.", [inUse.ramGb, inUse.vramGb])}</p> : null)} {tr(showFit && !isLoaded && fit!.vramUseGb + fit!.ramUseGb > 0 ? <p className="pc-note">{tr("This version would take about {0} of graphics memory and {1} of RAM.", [about(fit!.vramUseGb), about(fit!.ramUseGb)])}</p> : null)} {tr(diskGb ? <p className="pc-note">{tr("Needs about {0} GB of free disk space. What does not fit in memory is read from your SSD.", [Math.round(diskGb)])}</p> : null)} - {tr(showFit && fit!.spillGb >= 1 ? <p className="pc-note">{tr("About {0} GB will be read from the SSD, so answers can be a little slower.", [Math.round(fit!.spillGb)])}</p> : null)} </section>; } diff --git a/apps/host/src/styles/annotation-fixes.css b/apps/host/src/styles/annotation-fixes.css index e227119378..d0f810afb4 100644 --- a/apps/host/src/styles/annotation-fixes.css +++ b/apps/host/src/styles/annotation-fixes.css @@ -653,6 +653,9 @@ html[data-motion='reduced'] .task-tree-row[data-leaving] { opacity: 0; } /* Load model has no pop-up: what the download is sits beside the button that starts it */ .native-model-actions { align-items:center; } .native-download-size { margin-right:auto; font-variant-numeric:tabular-nums; } +/* a short note under a control (SSD streaming, Doesn't fit, a long context, the drafter download): the icon sits beside the words */ +.native-spill-note { display:flex; align-items:center; gap:8px; margin:0; } +.native-spill-note > svg { flex:none; } .native-path { display:block; font-size:11px; line-height:1.8; overflow-wrap:anywhere; margin:16px 0; } .native-settings { margin-top:24px; border-top:1px solid var(--st-line-soft); padding-top:20px; } .native-settings>summary, .native-progress summary,.native-generation>summary { font-size:13px; font-weight:600; cursor:pointer; } diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index 3c069d4ee6..f02cdb8dd0 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7332,7 +7332,7 @@ textarea { .telepop__head > .st-btn { align-self: center; margin-left: auto; } .telepop__detail + .st-btn { margin-left: 0; } /* a popover with nothing under its title (Subagents, none recorded) is one row: no rule and no space below it */ -.telepop__head:last-child { padding-bottom: 0; margin-bottom: 0; border-bottom: 0; } +.telepop__head:last-child { align-items: center; padding-bottom: 0; margin-bottom: 0; border-bottom: 0; } /* the way back to the newest message: a small round arrow, shown only while scrolled up */ .jumplatest-row { position: relative; height: 0; flex: none; z-index: 3; } diff --git a/apps/host/tests/pc-card.test.mjs b/apps/host/tests/pc-card.test.mjs index 1e9d906eeb..c68798707d 100644 --- a/apps/host/tests/pc-card.test.mjs +++ b/apps/host/tests/pc-card.test.mjs @@ -27,11 +27,12 @@ test('free graphics memory and free RAM come first, as real readings', () => { assert.doesNotMatch(card({ fit: fit(0), live: null }), /Free right now/, 'no readings: no invented numbers'); }); -test('the SSD appears only when the model does not fit in memory, with how much is read from it; a version that fits says nothing', () => { +test('the card does not repeat the SSD warning the version picker already gives; a version that fits says nothing either', () => { setTranslationLanguage('en'); assert.doesNotMatch(card({ fit: fit(0), live }), /SSD/); assert.doesNotMatch(card({ fit: fit(0), live }), /Fits fully in memory/, 'no "Fits" words (owner, 11-01)'); - assert.match(card({ fit: fit(30), live }), /About 30 GB will be read from the SSD/); + assert.doesNotMatch(card({ fit: fit(30), live }), /read from the SSD/, 'said once, under the picker'); + assert.match(card({ fit: fit(30), live }), /This version would take about 12 GB of graphics memory and 44 GB of RAM\./); }); test('a loaded model leaves the free memory and nothing else: no hardware line, no name, no Loaded, no "It takes about", no numbers, no SSD line', () => { @@ -41,9 +42,9 @@ test('a loaded model leaves the free memory and nothing else: no hardware line, assert.match(fits, /Free right now/); assert.match(fits, /Graphics memory<\/span><b>10\.3 GB free<\/b>/); for (const gone of [/RTX 5070/, /graphics memory · /, /Qwen3\.8-Flash-Next/, /Loaded/, /It takes about/, /<dl/, /<dt>/, /SSD/, /pc-loaded/]) assert.doesNotMatch(fits, gone, String(gone)); - // A loaded model that really streams from the SSD keeps one calm sentence; nothing else comes back. + // A loaded model that really streams from the SSD keeps how fast it reads right now; nothing else comes back. const spills = card({ fit: fit(18), live: { ...live, diskReadGbs: 1.2 }, loaded: [{ id: 'q', label: 'Qwen3.8-Flash-Next · UD-Q4_K_XL', fit: fit(18, 12, 53) }], selectedLoaded: true }); - assert.match(spills, /About 18 GB will be read from the SSD/); + assert.doesNotMatch(spills, /About 18 GB will be read/); assert.match(spills, /Reading from your SSD now: 1\.2 GB\/s/); for (const gone of [/<dl/, /<dt>/, /Loaded/, /It takes about/, /RTX 5070/]) assert.doesNotMatch(spills, gone, String(gone)); assert.doesNotMatch(spills, /This version would take/); diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index 62b8edf18e..897f071eeb 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -78,7 +78,7 @@ test('12: with no subagents the dropdown is one row, "No subagents recorded" and assert.match(bar, /title=\{tr\(session\?\.agents\?\.length \? "Subagents" : "No subagents recorded"\)\}/, 'the empty state is the title'); assert.ok(!/subagents-empty|Subagents that run in this conversation/.test(bar), 'no icon, no explanatory text'); assert.ok(!/subagents-empty/.test(read('src/styles/annotation-fixes.css')), 'no dead rule'); - assert.match(read('src/styles/app.css'), /\.telepop__head:last-child \{ padding-bottom: 0; margin-bottom: 0; border-bottom: 0; \}/, 'no empty body under the title'); + assert.match(read('src/styles/app.css'), /\.telepop__head:last-child \{ align-items: center; padding-bottom: 0; margin-bottom: 0; border-bottom: 0; \}/, 'no empty body under the title'); }); test('14: the Board and Schedule help lines sit in the Tasks header after the title, smaller, and wrap rather than being cut', () => { @@ -144,3 +144,16 @@ test('10 (visual): the reply stays still while it streams, one live cue per step assert.match(app, /\[data-motion='reduced'\] \{[^}]*--st-t-choreo: 1ms;/); assert.match(read('src/components/ArtifactPanel.tsx'), /setTimeout\(\(\) => setLeaving\(false\), 520\)/, 'the leaving shell stays for the whole 460 ms'); }); + +test('the new words are in all nine languages with the same slots', () => { + const en = JSON.parse(read('src/locales/r3-en.json')); + assert.ok(Object.keys(en).length >= 5); + for (const lang of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) { + const cat = JSON.parse(read(`src/locales/r3-${lang}.json`)); + assert.deepEqual(Object.keys(cat), Object.keys(en), lang); + for (const [id, text] of Object.entries(en)) { + assert.ok(cat[id] && cat[id] !== text, `${lang} ${id} is translated`); + assert.deepEqual((cat[id].match(/\{\d+\}/g) ?? []).sort(), (text.match(/\{\d+\}/g) ?? []).sort(), `${lang} ${id} slots`); + } + } +}); From 18aacf5dd0442e7bfc98170ca5c11227a828dd52 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:55:06 +0100 Subject: [PATCH 40/59] Test: a load without a picture reader runs without pictures and saves no off --- apps/host/tests/native-onboarding.test.mjs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/apps/host/tests/native-onboarding.test.mjs b/apps/host/tests/native-onboarding.test.mjs index 69a41bf963..2ce09a321a 100644 --- a/apps/host/tests/native-onboarding.test.mjs +++ b/apps/host/tests/native-onboarding.test.mjs @@ -138,6 +138,19 @@ test('vision can be disabled at load without losing the prepared encoder config }finally{await f.cleanup();} }); +test('a load while the engine has no picture reader runs without pictures and saves nothing (it used to save "off" for good)',async()=>{ + const f=nativeFixture();try{ + await f.control.refresh(); + const first=await finishJob(f.control,f.control.operation('load',{model:'iq2_xs',vision:'no',visionUnavailable:true}).id); + assert.equal(first.state,'done',first.error); + assert.equal(f.control.state().instances[0].vision,false,'no picture reading for this run'); + const source=JSON.parse(readFileSync(join(f.repo,'strata-iq2_xs.json'))); + assert.equal(source.ui_vision_enabled,undefined,'no off was saved'); + assert.deepEqual(source.vision,{gpu:0},'the prepared picture files stay'); + assert.equal(f.control.state().installed.models[0].visionEnabled,false,'while it runs without pictures the state says so'); + }finally{await f.cleanup();} +}); + test('runtime vision checks prepared files, validates mode, and leaves the source config intact',()=>{ const config={vision:{mmproj:'/models/mmproj.gguf',gpu:true,max_tokens:8192},ui_vision_enabled:false}; const before=structuredClone(config); From 0038dbfd44ecaedf12f7773378af22982b91068f Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:56:39 +0100 Subject: [PATCH 41/59] The folder window no longer fails with an error when the Desktop folder is missing (it starts at This PC), and any failure of it now asks for the path instead of leaving no way to choose a folder (found in the review copy, whose profile has no Desktop folder) --- apps/host/server/folder-dialog.mjs | 407 +++++++++++++------------ apps/host/tests/folder-dialog.test.mjs | 360 +++++++++++----------- 2 files changed, 389 insertions(+), 378 deletions(-) diff --git a/apps/host/server/folder-dialog.mjs b/apps/host/server/folder-dialog.mjs index ef90a6639b..d37afd2bbc 100644 --- a/apps/host/server/folder-dialog.mjs +++ b/apps/host/server/folder-dialog.mjs @@ -1,200 +1,207 @@ -/** - * The host's native "choose a folder" dialog, one per platform: - * macOS osascript (choose folder) -- unchanged - * Windows PowerShell FolderBrowserDialog (STA, topmost owner so it never opens behind the app) - * Linux zenity, then kdialog, then the desktop portal (gdbus), all with the environment the AppImage was started from - * Where no dialog works the caller gets { unavailable: true } and the app shows a plain message and a field for the path. - */ -import { spawn } from 'node:child_process'; -import { stat } from 'node:fs/promises'; -import { exec } from './util.mjs'; -import { externalEnvironment } from './external-env.mjs'; - -const MAC_SCRIPT = prompt => `POSIX path of (choose folder with prompt "${prompt.replace(/["\\]/g, '')}")`; - -export function windowsFolderScript(prompt) { - const text = prompt.replace(/'/g, "''"); - return [ - 'Add-Type -AssemblyName System.Windows.Forms', - '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8', - '$owner = New-Object System.Windows.Forms.Form', - '$owner.TopMost = $true; $owner.ShowInTaskbar = $false; $owner.StartPosition = "CenterScreen"; $owner.Size = New-Object System.Drawing.Size(0, 0)', - '$owner.Show(); $owner.Activate()', - '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog', - `$dialog.Description = '${text}'`, - '$dialog.ShowNewFolderButton = $true', - // READY tells the host the window is about to open; a host that never sees it gives up and asks for the path in words (QA F06). - '[Console]::Out.WriteLine("READY"); [Console]::Out.Flush()', - 'if ($dialog.ShowDialog($owner) -eq "OK") { [Console]::Out.Write($dialog.SelectedPath) }', - '$owner.Close()', - ].join('; '); -} - -/** powershell.exe takes the script as UTF-16LE base64, so no quoting survives to be mangled. */ -export function windowsFolderArgs(prompt) { - return ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(windowsFolderScript(prompt), 'utf16le').toString('base64')]; -} - -/** Strip trailing separators, but leave a drive or filesystem root intact. */ -export function cleanChosenPath(value) { - const text = String(value ?? '').trim(); - if (/^[A-Za-z]:[\\/]*$/.test(text)) return text.slice(0, 2) + '\\'; - return text.length > 1 ? text.replace(/[\\/]+$/, '') || text.slice(0, 1) : text; -} - -const missing = error => error?.code === 'ENOENT'; - -/** What the script printed, without its READY line. */ -const answerOf = stdout => String(stdout ?? '').split(/\r?\n/).filter(line => line.trim() && line.trim() !== 'READY').join('\n'); - -/** - * Runs the Windows dialog and watches it. Resolves { stdout } when it ends, { noDialog: true } when its window never got as far as - * opening (no READY within `readyMs`: PowerShell blocked, stuck or without a desktop), and rejects with { code } as exec does. - * The person's own time with the open dialog is not limited (a day at most). - */ -export function watchedWindowsDialog(shell, args, { readyMs = 30_000, openMs = 24 * 3600_000, spawnProcess = spawn } = {}) { - return new Promise((resolve, reject) => { - const child = spawnProcess(shell, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); - let stdout = '', ready = false, settled = false; - child.stdout?.setEncoding?.('utf8'); // a multi-byte letter of a Cyrillic folder must not be cut between two chunks - const end = (fn, value) => { if (settled) return; settled = true; clearTimeout(timer); try { child.kill(); } catch { /* gone */ } fn(value); }; - const timer = setTimeout(() => end(resolve, ready ? { stdout: '' } : { noDialog: true }), readyMs); - 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); - // 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 })); }); - }); -} - -/** - * Ask for a folder. Resolves { path } | { cancelled: true } | { unavailable: true, reason }. - * `run` is injectable for tests: (command, args) => Promise<{ stdout }>. - */ -export async function chooseFolder(prompt, options = {}) { - const { platform = process.platform, run = exec, portal = portalFolder, windowsDialog = options.run ? null : watchedWindowsDialog } = options; - if (platform === 'darwin') { - try { - const { stdout } = await run('osascript', ['-e', MAC_SCRIPT(prompt)]); - return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true }; - } catch { - return { cancelled: true }; // dismissing the dialog is an exit code, not a failure - } - } - if (platform === 'win32') { - const shell = `${process.env.SystemRoot || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`; - try { - const done = windowsDialog ? await windowsDialog(shell, windowsFolderArgs(prompt)) : await run(shell, windowsFolderArgs(prompt)); - if (done.noDialog) return { unavailable: true, failed: true, reason: 'The folder window did not open. Type the folder path instead.' }; - const answer = answerOf(done.stdout).trim(); - return answer ? { path: cleanChosenPath(answer) } : { cancelled: true }; - } catch (error) { - if (missing(error)) return { unavailable: true, reason: 'Windows PowerShell was not found.' }; - throw new Error('The folder chooser could not open.'); - } - } - return chooseLinuxFolder(prompt, { run, portal }); -} - -/** A chooser that is there but broke (the display is missing, a library does not load) must say so; a bare exit 1 is a cancel. */ -const BROKEN = /unable to init server|cannot open display|can't open display|no protocol specified|error while loading shared libraries|symbol lookup error|version `[^']*' not found|cannot connect to|failed to connect|could not connect/i; -const firstLine = text => String(text ?? '').split(/\r?\n/).map(l => l.trim()).find(Boolean)?.slice(0, 160) ?? ''; - -/** - * Linux: zenity, then kdialog, then the desktop portal's file chooser through gdbus. Every one of them runs with the environment the - * AppImage was started from (external-env.mjs), not Strata's own libraries. A chooser that is missing is skipped; one that fails is - * remembered and the next is tried; when none works the answer says why and the person types the path. - */ -async function chooseLinuxFolder(prompt, { run, portal }) { - const env = externalEnvironment(); - const candidates = [ - ['zenity', ['--file-selection', '--directory', `--title=${prompt}`]], - ['kdialog', ['--getexistingdirectory', '.', '--title', prompt]], - ]; - const failures = []; - for (const [command, args] of candidates) { - try { - const { stdout } = await run(command, args, { env }); - return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true }; - } catch (error) { - if (missing(error)) continue; - const detail = `${error?.stderr ?? ''}`; - if (error?.code === 1 && !BROKEN.test(detail)) return { cancelled: true }; // both tools exit 1 when the dialog is dismissed - failures.push(`${command}: ${firstLine(detail) || firstLine(error?.message) || `exit ${error?.code}`}`); - } - } - try { - const picked = await portal(prompt, { run, env }); - if (picked) return picked; - } catch (error) { - failures.push(`portal: ${firstLine(error?.message)}`); - } - return { - unavailable: true, failed: failures.length > 0, ...(failures.length ? { detail: failures.join('; ') } : {}), - reason: failures.length - ? 'The folder chooser could not open. Install zenity or kdialog to pick a folder, or type the path.' - : 'No folder chooser was found. Install zenity or kdialog to pick a folder, or type the path.', - }; -} - -/** - * xdg-desktop-portal FileChooser through gdbus. Resolves { path } | { cancelled: true } | null when there is no portal or no gdbus. - * The answer arrives as a Response signal on the request the call returns, so a monitor is started first. - */ -export async function portalFolder(prompt, { run = exec, env = externalEnvironment(), spawnProcess = spawn, timeoutMs = 10 * 60_000 } = {}) { - const monitor = spawnProcess('gdbus', ['monitor', '--session', '--dest', 'org.freedesktop.portal.Desktop'], { env, stdio: ['ignore', 'pipe', 'ignore'] }); - let seen = ''; - let ended = false; - monitor.on('error', () => { ended = true; }); - monitor.on('close', () => { ended = true; }); - monitor.stdout?.on('data', chunk => { seen += chunk; }); - try { - let call; - try { - call = await run('gdbus', ['call', '--session', '--dest', 'org.freedesktop.portal.Desktop', '--object-path', '/org/freedesktop/portal/desktop', - '--method', 'org.freedesktop.portal.FileChooser.OpenFile', '', prompt, "{'directory': <true>, 'modal': <true>}"], { env }); - } catch { - return null; // no gdbus, or no portal on the session bus - } - const handle = /'(\/org\/freedesktop\/portal\/desktop\/request\/[^']+)'/.exec(call.stdout)?.[1]; - if (!handle) return null; - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - const line = seen.split('\n').find(l => l.startsWith(`${handle}: org.freedesktop.portal.Request.Response`)); - if (line) { - const m = /\(uint32 (\d+), (.*)\)\s*$/.exec(line); - if (!m || m[1] !== '0') return { cancelled: true }; - const uri = /'(file:\/\/[^']*)'/.exec(m[2])?.[1]; - return uri ? { path: cleanChosenPath(decodeURIComponent(uri.replace(/^file:\/\//, ''))) } : { cancelled: true }; - } - if (ended) return null; - await new Promise(r => setTimeout(r, 100)); - } - return { cancelled: true }; - } finally { - try { monitor.kill(); } catch { /* already gone */ } - } -} - -export const TYPE_A_PATH = 'No folder chooser is available on this system, so type the folder path instead.'; - -/** The host's answer when no chooser works: a plain sentence and a code the app turns into a field for typing the path. */ -export function chooserUnavailable(picked) { - return { message: picked.reason, code: 'folder-chooser-unavailable', details: picked.detail }; -} - -/** A typed path stands in for the dialog: it must be an absolute directory that exists. `fileType` (a RegExp on the name) also lets a - * file of that kind through (the model page takes a folder or one .gguf file). Quotes around the path (Windows "Copy as path") go. */ -export async function typedFolder(value, { isAbsolute, fileType = null }) { - let text = typeof value === 'string' ? value.trim() : ''; - if (text.length > 1 && /^(["'])[\s\S]*\1$/.test(text)) text = text.slice(1, -1).trim(); - if (!text || text.includes('\0')) return null; - if (!isAbsolute(text)) throw new Error(fileType ? 'Enter the full path of the folder or the file.' : 'Enter the full path of the folder.'); - let info; - try { info = await stat(text); } catch { throw new Error(fileType ? 'That folder or file does not exist.' : 'That folder does not exist.'); } - if (info.isFile() && fileType?.test(text)) return text; - if (!info.isDirectory()) throw new Error(fileType ? 'Choose a folder, or a .gguf file.' : 'Choose a folder, not a file.'); - return cleanChosenPath(text); -} +/** + * The host's native "choose a folder" dialog, one per platform: + * macOS osascript (choose folder) -- unchanged + * Windows PowerShell FolderBrowserDialog (STA, topmost owner so it never opens behind the app) + * Linux zenity, then kdialog, then the desktop portal (gdbus), all with the environment the AppImage was started from + * Where no dialog works the caller gets { unavailable: true } and the app shows a plain message and a field for the path. + */ +import { spawn } from 'node:child_process'; +import { stat } from 'node:fs/promises'; +import { exec } from './util.mjs'; +import { externalEnvironment } from './external-env.mjs'; + +const MAC_SCRIPT = prompt => `POSIX path of (choose folder with prompt "${prompt.replace(/["\\]/g, '')}")`; + +export function windowsFolderScript(prompt) { + const text = prompt.replace(/'/g, "''"); + return [ + 'Add-Type -AssemblyName System.Windows.Forms', + '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8', + '$owner = New-Object System.Windows.Forms.Form', + '$owner.TopMost = $true; $owner.ShowInTaskbar = $false; $owner.StartPosition = "CenterScreen"; $owner.Size = New-Object System.Drawing.Size(0, 0)', + '$owner.Show(); $owner.Activate()', + '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog', + `$dialog.Description = '${text}'`, + '$dialog.ShowNewFolderButton = $true', + // READY tells the host the window is about to open; a host that never sees it gives up and asks for the path in words (QA F06). + '[Console]::Out.WriteLine("READY"); [Console]::Out.Flush()', + // The dialog starts at the Desktop folder. Where that folder does not exist (it was deleted, a OneDrive move left a dead path, the profile was + // redirected) ShowDialog throws "Unable to retrieve the root folder" and no folder could be chosen at all: start at This PC instead, and when even + // that fails say NODIALOG so the app asks for the path. + '$answer = $null', + 'try { $answer = $dialog.ShowDialog($owner) } catch { try { $dialog.RootFolder = [System.Environment+SpecialFolder]::MyComputer; $answer = $dialog.ShowDialog($owner) } catch { [Console]::Out.WriteLine("NODIALOG"); [Console]::Out.Flush() } }', + 'if ($answer -eq "OK") { [Console]::Out.Write($dialog.SelectedPath) }', + '$owner.Close()', + ].join('; '); +} + +/** powershell.exe takes the script as UTF-16LE base64, so no quoting survives to be mangled. */ +export function windowsFolderArgs(prompt) { + return ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(windowsFolderScript(prompt), 'utf16le').toString('base64')]; +} + +/** Strip trailing separators, but leave a drive or filesystem root intact. */ +export function cleanChosenPath(value) { + const text = String(value ?? '').trim(); + if (/^[A-Za-z]:[\\/]*$/.test(text)) return text.slice(0, 2) + '\\'; + return text.length > 1 ? text.replace(/[\\/]+$/, '') || text.slice(0, 1) : text; +} + +const missing = error => error?.code === 'ENOENT'; + +/** What the script printed, without its READY line. */ +const answerOf = stdout => String(stdout ?? '').split(/\r?\n/).filter(line => line.trim() && line.trim() !== 'READY').join('\n'); + +/** + * Runs the Windows dialog and watches it. Resolves { stdout } when it ends, { noDialog: true } when its window never got as far as + * opening (no READY within `readyMs`: PowerShell blocked, stuck or without a desktop), and rejects with { code } as exec does. + * The person's own time with the open dialog is not limited (a day at most). + */ +export function watchedWindowsDialog(shell, args, { readyMs = 30_000, openMs = 24 * 3600_000, spawnProcess = spawn } = {}) { + return new Promise((resolve, reject) => { + const child = spawnProcess(shell, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); + let stdout = '', ready = false, settled = false; + child.stdout?.setEncoding?.('utf8'); // a multi-byte letter of a Cyrillic folder must not be cut between two chunks + const end = (fn, value) => { if (settled) return; settled = true; clearTimeout(timer); try { child.kill(); } catch { /* gone */ } fn(value); }; + const timer = setTimeout(() => end(resolve, ready ? { stdout: '' } : { noDialog: true }), readyMs); + 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); + // 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 })); }); + }); +} + +/** + * Ask for a folder. Resolves { path } | { cancelled: true } | { unavailable: true, reason }. + * `run` is injectable for tests: (command, args) => Promise<{ stdout }>. + */ +export async function chooseFolder(prompt, options = {}) { + const { platform = process.platform, run = exec, portal = portalFolder, windowsDialog = options.run ? null : watchedWindowsDialog } = options; + if (platform === 'darwin') { + try { + const { stdout } = await run('osascript', ['-e', MAC_SCRIPT(prompt)]); + return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true }; + } catch { + return { cancelled: true }; // dismissing the dialog is an exit code, not a failure + } + } + if (platform === 'win32') { + const shell = `${process.env.SystemRoot || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`; + try { + const done = windowsDialog ? await windowsDialog(shell, windowsFolderArgs(prompt)) : await run(shell, windowsFolderArgs(prompt)); + if (done.noDialog) return { unavailable: true, failed: true, reason: 'The folder window did not open. Type the folder path instead.' }; + if (/^NODIALOG\s*$/m.test(String(done.stdout ?? ''))) return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.' }; + const answer = answerOf(done.stdout).trim(); + return answer ? { path: cleanChosenPath(answer) } : { cancelled: true }; + } catch (error) { + if (missing(error)) return { unavailable: true, reason: 'Windows PowerShell was not found.' }; + // The window opened or tried to and ended with an error: the person is asked for the path instead of being left with an error and no way on. + return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.', detail: `exit ${error?.code ?? '?'}` }; + } + } + return chooseLinuxFolder(prompt, { run, portal }); +} + +/** A chooser that is there but broke (the display is missing, a library does not load) must say so; a bare exit 1 is a cancel. */ +const BROKEN = /unable to init server|cannot open display|can't open display|no protocol specified|error while loading shared libraries|symbol lookup error|version `[^']*' not found|cannot connect to|failed to connect|could not connect/i; +const firstLine = text => String(text ?? '').split(/\r?\n/).map(l => l.trim()).find(Boolean)?.slice(0, 160) ?? ''; + +/** + * Linux: zenity, then kdialog, then the desktop portal's file chooser through gdbus. Every one of them runs with the environment the + * AppImage was started from (external-env.mjs), not Strata's own libraries. A chooser that is missing is skipped; one that fails is + * remembered and the next is tried; when none works the answer says why and the person types the path. + */ +async function chooseLinuxFolder(prompt, { run, portal }) { + const env = externalEnvironment(); + const candidates = [ + ['zenity', ['--file-selection', '--directory', `--title=${prompt}`]], + ['kdialog', ['--getexistingdirectory', '.', '--title', prompt]], + ]; + const failures = []; + for (const [command, args] of candidates) { + try { + const { stdout } = await run(command, args, { env }); + return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true }; + } catch (error) { + if (missing(error)) continue; + const detail = `${error?.stderr ?? ''}`; + if (error?.code === 1 && !BROKEN.test(detail)) return { cancelled: true }; // both tools exit 1 when the dialog is dismissed + failures.push(`${command}: ${firstLine(detail) || firstLine(error?.message) || `exit ${error?.code}`}`); + } + } + try { + const picked = await portal(prompt, { run, env }); + if (picked) return picked; + } catch (error) { + failures.push(`portal: ${firstLine(error?.message)}`); + } + return { + unavailable: true, failed: failures.length > 0, ...(failures.length ? { detail: failures.join('; ') } : {}), + reason: failures.length + ? 'The folder chooser could not open. Install zenity or kdialog to pick a folder, or type the path.' + : 'No folder chooser was found. Install zenity or kdialog to pick a folder, or type the path.', + }; +} + +/** + * xdg-desktop-portal FileChooser through gdbus. Resolves { path } | { cancelled: true } | null when there is no portal or no gdbus. + * The answer arrives as a Response signal on the request the call returns, so a monitor is started first. + */ +export async function portalFolder(prompt, { run = exec, env = externalEnvironment(), spawnProcess = spawn, timeoutMs = 10 * 60_000 } = {}) { + const monitor = spawnProcess('gdbus', ['monitor', '--session', '--dest', 'org.freedesktop.portal.Desktop'], { env, stdio: ['ignore', 'pipe', 'ignore'] }); + let seen = ''; + let ended = false; + monitor.on('error', () => { ended = true; }); + monitor.on('close', () => { ended = true; }); + monitor.stdout?.on('data', chunk => { seen += chunk; }); + try { + let call; + try { + call = await run('gdbus', ['call', '--session', '--dest', 'org.freedesktop.portal.Desktop', '--object-path', '/org/freedesktop/portal/desktop', + '--method', 'org.freedesktop.portal.FileChooser.OpenFile', '', prompt, "{'directory': <true>, 'modal': <true>}"], { env }); + } catch { + return null; // no gdbus, or no portal on the session bus + } + const handle = /'(\/org\/freedesktop\/portal\/desktop\/request\/[^']+)'/.exec(call.stdout)?.[1]; + if (!handle) return null; + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const line = seen.split('\n').find(l => l.startsWith(`${handle}: org.freedesktop.portal.Request.Response`)); + if (line) { + const m = /\(uint32 (\d+), (.*)\)\s*$/.exec(line); + if (!m || m[1] !== '0') return { cancelled: true }; + const uri = /'(file:\/\/[^']*)'/.exec(m[2])?.[1]; + return uri ? { path: cleanChosenPath(decodeURIComponent(uri.replace(/^file:\/\//, ''))) } : { cancelled: true }; + } + if (ended) return null; + await new Promise(r => setTimeout(r, 100)); + } + return { cancelled: true }; + } finally { + try { monitor.kill(); } catch { /* already gone */ } + } +} + +export const TYPE_A_PATH = 'No folder chooser is available on this system, so type the folder path instead.'; + +/** The host's answer when no chooser works: a plain sentence and a code the app turns into a field for typing the path. */ +export function chooserUnavailable(picked) { + return { message: picked.reason, code: 'folder-chooser-unavailable', details: picked.detail }; +} + +/** A typed path stands in for the dialog: it must be an absolute directory that exists. `fileType` (a RegExp on the name) also lets a + * file of that kind through (the model page takes a folder or one .gguf file). Quotes around the path (Windows "Copy as path") go. */ +export async function typedFolder(value, { isAbsolute, fileType = null }) { + let text = typeof value === 'string' ? value.trim() : ''; + if (text.length > 1 && /^(["'])[\s\S]*\1$/.test(text)) text = text.slice(1, -1).trim(); + if (!text || text.includes('\0')) return null; + if (!isAbsolute(text)) throw new Error(fileType ? 'Enter the full path of the folder or the file.' : 'Enter the full path of the folder.'); + let info; + try { info = await stat(text); } catch { throw new Error(fileType ? 'That folder or file does not exist.' : 'That folder does not exist.'); } + if (info.isFile() && fileType?.test(text)) return text; + if (!info.isDirectory()) throw new Error(fileType ? 'Choose a folder, or a .gguf file.' : 'Choose a folder, not a file.'); + return cleanChosenPath(text); +} diff --git a/apps/host/tests/folder-dialog.test.mjs b/apps/host/tests/folder-dialog.test.mjs index 300b3fae43..9d1c9e499e 100644 --- a/apps/host/tests/folder-dialog.test.mjs +++ b/apps/host/tests/folder-dialog.test.mjs @@ -1,178 +1,182 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { spawn, execFileSync } from 'node:child_process'; -import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join, resolve, isAbsolute } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { chooseFolder, cleanChosenPath, typedFolder, windowsFolderScript } from '../server/folder-dialog.mjs'; - -const HOST_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); -const failure = (code) => Object.assign(new Error(`exit ${code}`), { code }); -const recorder = () => { - const seen = []; - return { seen, run: (outcome) => async (command, args) => { seen.push({ command, args }); if (outcome instanceof Error) throw outcome; return { stdout: outcome }; } }; -}; - -test('macOS keeps the osascript chooser and treats any dismissal as a cancel', async () => { - const c = recorder(); - assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run('/Users/me/skills/\n') }), { path: '/Users/me/skills' }); - assert.equal(c.seen[0].command, 'osascript'); - assert.equal(c.seen[0].args[1], 'POSIX path of (choose folder with prompt "Pick")'); - assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run(failure(1)) }), { cancelled: true }); -}); - -test('Windows uses a PowerShell FolderBrowserDialog passed as an encoded command', async () => { - const c = recorder(); - const result = await chooseFolder("Don't panic", { platform: 'win32', run: c.run('C:\\Users\\me\\Skills\r\n') }); - assert.deepEqual(result, { path: 'C:\\Users\\me\\Skills' }); - assert.match(c.seen[0].command, /powershell\.exe$/i); - assert.ok(c.seen[0].args.includes('-STA')); - const script = Buffer.from(c.seen[0].args.at(-1), 'base64').toString('utf16le'); - assert.equal(script, windowsFolderScript("Don't panic")); - assert.match(script, /FolderBrowserDialog/); - assert.match(script, /Description = 'Don''t panic'/); - assert.deepEqual(await chooseFolder('Pick', { platform: 'win32', run: c.run('') }), { cancelled: true }); - const missing = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure('ENOENT')) }); - assert.equal(missing.unavailable, true); - await assert.rejects(chooseFolder('Pick', { platform: 'win32', run: c.run(failure(2)) }), /could not open/); -}); - -test('the generated PowerShell parses without errors', { skip: process.platform !== 'win32' }, () => { - const shell = join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'); - const out = execFileSync(shell, - ['-NoProfile', '-NonInteractive', '-Command', '$e=$null; [void][System.Management.Automation.Language.Parser]::ParseInput($env:SCRIPT,[ref]$null,[ref]$e); $e.Count'], - { encoding: 'utf8', env: { ...process.env, SCRIPT: windowsFolderScript('Choose a folder for Strata') }, windowsHide: true }).trim(); - assert.equal(out, '0'); -}); - -test('Linux tries zenity, falls back to kdialog, then reports that none exists', async () => { - const order = []; - const run = async (command) => { order.push(command); if (command === 'zenity') throw failure('ENOENT'); return { stdout: '/home/me/skills/\n' }; }; - assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run }), { path: '/home/me/skills' }); - assert.deepEqual(order, ['zenity', 'kdialog']); - const none = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure('ENOENT'); } }); - assert.equal(none.unavailable, true); - assert.match(none.reason, /zenity or kdialog/); - assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure(1); } }), { cancelled: true }); - assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => ({ stdout: '' }) }), { cancelled: true }); -}); - -test('chosen paths lose trailing separators but roots survive', () => { - assert.equal(cleanChosenPath('/a/b/\n'), '/a/b'); - assert.equal(cleanChosenPath('/'), '/'); - assert.equal(cleanChosenPath('C:\\Users\\me\\'), 'C:\\Users\\me'); - assert.equal(cleanChosenPath('C:\\'), 'C:\\'); -}); - -test('a typed path must be an absolute existing directory', async () => { - const dir = await mkdtemp(join(tmpdir(), 'strata-typed-')); - try { - await writeFile(join(dir, 'file.txt'), 'x'); - assert.equal(await typedFolder(dir, { isAbsolute }), dir); - assert.equal(await typedFolder(undefined, { isAbsolute }), null); - await assert.rejects(typedFolder('relative/dir', { isAbsolute }), /full path/); - await assert.rejects(typedFolder(join(dir, 'missing'), { isAbsolute }), /does not exist/); - await assert.rejects(typedFolder(join(dir, 'file.txt'), { isAbsolute }), /not a file/); - } finally { await rm(dir, { recursive: true, force: true }); } -}); - -test('the model page takes a folder or one .gguf file, with or without quotes around the path', async () => { - const dir = await mkdtemp(join(tmpdir(), 'strata-gguf-typed-')); - try { - await writeFile(join(dir, 'model-00001-of-00002.gguf'), 'x'); - await writeFile(join(dir, 'notes.txt'), 'x'); - const only = { isAbsolute, fileType: /\.gguf$/i }; - assert.equal(await typedFolder(dir, only), dir); - assert.equal(await typedFolder(join(dir, 'model-00001-of-00002.gguf'), only), join(dir, 'model-00001-of-00002.gguf')); - assert.equal(await typedFolder(`"${join(dir, 'model-00001-of-00002.gguf')}"`, only), join(dir, 'model-00001-of-00002.gguf')); - assert.equal(await typedFolder(` "${dir}" `, only), dir); - await assert.rejects(typedFolder(join(dir, 'notes.txt'), only), /folder, or a \.gguf file/); - await assert.rejects(typedFolder(join(dir, 'missing.gguf'), only), /does not exist/); - // the other pickers still refuse a file - await assert.rejects(typedFolder(join(dir, 'model-00001-of-00002.gguf'), { isAbsolute }), /not a file/); - } finally { await rm(dir, { recursive: true, force: true }); } -}); - -async function startHost() { - const home = await mkdtemp(join(tmpdir(), 'strata-folder-home-')); - const net = await import('node:net'); - const probe = net.createServer(); - await new Promise(r => probe.listen(0, '127.0.0.1', r)); - const { port } = probe.address(); - await new Promise(r => probe.close(r)); - const child = spawn(process.execPath, [join(HOST_ROOT, 'server', 'index.mjs'), '--dist', join(HOST_ROOT, 'dist')], { - cwd: HOST_ROOT, env: { ...process.env, STRATA_HOME: home, STRATA_WORKSPACE: home, STRATA_PORT: String(port), STRATA_REAL_ENGINE: '0' }, stdio: 'ignore', - }); - const base = `http://127.0.0.1:${port}`; - for (let i = 0; i < 150; i++) { - try { if ((await fetch(`${base}/api/health`)).ok) return { child, base, home }; } catch { /* not up yet */ } - await new Promise(r => setTimeout(r, 100)); - } - child.kill(); - throw new Error('the host did not become healthy'); -} - -test('the host accepts a typed folder path for the picker and for adding a skill, on every OS', { timeout: 60000 }, async () => { - const { child, base, home } = await startHost(); - const skill = await mkdtemp(join(tmpdir(), 'strata-skill-')); - try { - const post = (path, body) => fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); - let r = await post('/api/workspaces/pick', { path: skill }); - assert.deepEqual(await r.json(), { path: skill }); - r = await post('/api/workspaces/pick', { path: join(skill, 'nope') }); - assert.equal(r.status, 400); - assert.match((await r.json()).error, /does not exist/); - r = await post('/api/skills/add', { path: skill }); - assert.equal(r.status, 400); - assert.match((await r.json()).error, /no SKILL\.md/); - await writeFile(join(skill, 'SKILL.md'), '---\nname: Typed\n---\nbody\n'); - r = await post('/api/skills/add', { path: skill }); - assert.equal(r.status, 200); - assert.ok((await r.json()).added); - } finally { - child.kill(); - await rm(skill, { recursive: true, force: true }); - await rm(home, { recursive: true, force: true }).catch(() => {}); - } -}); - -// QA report F06: a Windows folder window that never opens must not leave the button disabled forever. -import { EventEmitter } from 'node:events'; -import { watchedWindowsDialog } from '../server/folder-dialog.mjs'; -function fakeShell() { - const child = new EventEmitter(); child.stdout = new EventEmitter(); child.killed = false; child.kill = () => { child.killed = true; }; - return { child, spawnProcess: () => child }; -} -test('Windows: no READY from the dialog script means the host gives up and the app asks for the path', async () => { - const f = fakeShell(); - const result = await watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess }); - assert.deepEqual(result, { noDialog: true }); assert.equal(f.child.killed, true, 'the stuck PowerShell is ended'); - const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ noDialog: true }) }); - assert.equal(answer.unavailable, true); assert.match(answer.reason, /Type the folder path/); -}); -test('Windows: once READY has come the person may take their time, and the answer is read without the READY line', async () => { - const f = fakeShell(); - const pending = watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess }); - f.child.stdout.emit('data', 'READY\r\n'); - await new Promise(r => setTimeout(r, 80)); // longer than readyMs: still waiting, not given up - assert.equal(f.child.killed, false); - f.child.stdout.emit('data', 'C:\Users\me\Skills'); f.child.emit('close', 0); - const done = await pending; - const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => done }); - assert.deepEqual(answer, { path: 'C:\Users\me\Skills' }); - const cancelled = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ stdout: 'READY\r\n' }) }); - assert.deepEqual(cancelled, { cancelled: true }); -}); -test('Windows: a PowerShell that is missing or fails is reported as before', async () => { - const f = fakeShell(); - const missing = watchedWindowsDialog('powershell.exe', [], { spawnProcess: f.spawnProcess }); - 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); - // 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); -}); +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn, execFileSync } from 'node:child_process'; +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve, isAbsolute } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { chooseFolder, cleanChosenPath, typedFolder, windowsFolderScript } from '../server/folder-dialog.mjs'; + +const HOST_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); +const failure = (code) => Object.assign(new Error(`exit ${code}`), { code }); +const recorder = () => { + const seen = []; + return { seen, run: (outcome) => async (command, args) => { seen.push({ command, args }); if (outcome instanceof Error) throw outcome; return { stdout: outcome }; } }; +}; + +test('macOS keeps the osascript chooser and treats any dismissal as a cancel', async () => { + const c = recorder(); + assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run('/Users/me/skills/\n') }), { path: '/Users/me/skills' }); + assert.equal(c.seen[0].command, 'osascript'); + assert.equal(c.seen[0].args[1], 'POSIX path of (choose folder with prompt "Pick")'); + assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run(failure(1)) }), { cancelled: true }); +}); + +test('Windows uses a PowerShell FolderBrowserDialog passed as an encoded command', async () => { + const c = recorder(); + const result = await chooseFolder("Don't panic", { platform: 'win32', run: c.run('C:\\Users\\me\\Skills\r\n') }); + assert.deepEqual(result, { path: 'C:\\Users\\me\\Skills' }); + assert.match(c.seen[0].command, /powershell\.exe$/i); + assert.ok(c.seen[0].args.includes('-STA')); + const script = Buffer.from(c.seen[0].args.at(-1), 'base64').toString('utf16le'); + assert.equal(script, windowsFolderScript("Don't panic")); + assert.match(script, /FolderBrowserDialog/); + assert.match(script, /Description = 'Don''t panic'/); + assert.deepEqual(await chooseFolder('Pick', { platform: 'win32', run: c.run('') }), { cancelled: true }); + const missing = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure('ENOENT')) }); + assert.equal(missing.unavailable, true); + // A window that fails after it was started no longer ends in an error with no way on (AGENT-LOST, item 11): the app asks for the path. + const failed = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure(2)) }); + assert.equal(failed.unavailable, true); assert.match(failed.reason, /Type the folder path/); + const nodialog = await chooseFolder('Pick', { platform: 'win32', run: c.run('NODIALOG' + String.fromCharCode(13, 10)) }); + assert.equal(nodialog.unavailable, true); assert.match(nodialog.reason, /Type the folder path/); +}); + +test('the generated PowerShell parses without errors', { skip: process.platform !== 'win32' }, () => { + const shell = join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'); + const out = execFileSync(shell, + ['-NoProfile', '-NonInteractive', '-Command', '$e=$null; [void][System.Management.Automation.Language.Parser]::ParseInput($env:SCRIPT,[ref]$null,[ref]$e); $e.Count'], + { encoding: 'utf8', env: { ...process.env, SCRIPT: windowsFolderScript('Choose a folder for Strata') }, windowsHide: true }).trim(); + assert.equal(out, '0'); +}); + +test('Linux tries zenity, falls back to kdialog, then reports that none exists', async () => { + const order = []; + const run = async (command) => { order.push(command); if (command === 'zenity') throw failure('ENOENT'); return { stdout: '/home/me/skills/\n' }; }; + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run }), { path: '/home/me/skills' }); + assert.deepEqual(order, ['zenity', 'kdialog']); + const none = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure('ENOENT'); } }); + assert.equal(none.unavailable, true); + assert.match(none.reason, /zenity or kdialog/); + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure(1); } }), { cancelled: true }); + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => ({ stdout: '' }) }), { cancelled: true }); +}); + +test('chosen paths lose trailing separators but roots survive', () => { + assert.equal(cleanChosenPath('/a/b/\n'), '/a/b'); + assert.equal(cleanChosenPath('/'), '/'); + assert.equal(cleanChosenPath('C:\\Users\\me\\'), 'C:\\Users\\me'); + assert.equal(cleanChosenPath('C:\\'), 'C:\\'); +}); + +test('a typed path must be an absolute existing directory', async () => { + const dir = await mkdtemp(join(tmpdir(), 'strata-typed-')); + try { + await writeFile(join(dir, 'file.txt'), 'x'); + assert.equal(await typedFolder(dir, { isAbsolute }), dir); + assert.equal(await typedFolder(undefined, { isAbsolute }), null); + await assert.rejects(typedFolder('relative/dir', { isAbsolute }), /full path/); + await assert.rejects(typedFolder(join(dir, 'missing'), { isAbsolute }), /does not exist/); + await assert.rejects(typedFolder(join(dir, 'file.txt'), { isAbsolute }), /not a file/); + } finally { await rm(dir, { recursive: true, force: true }); } +}); + +test('the model page takes a folder or one .gguf file, with or without quotes around the path', async () => { + const dir = await mkdtemp(join(tmpdir(), 'strata-gguf-typed-')); + try { + await writeFile(join(dir, 'model-00001-of-00002.gguf'), 'x'); + await writeFile(join(dir, 'notes.txt'), 'x'); + const only = { isAbsolute, fileType: /\.gguf$/i }; + assert.equal(await typedFolder(dir, only), dir); + assert.equal(await typedFolder(join(dir, 'model-00001-of-00002.gguf'), only), join(dir, 'model-00001-of-00002.gguf')); + assert.equal(await typedFolder(`"${join(dir, 'model-00001-of-00002.gguf')}"`, only), join(dir, 'model-00001-of-00002.gguf')); + assert.equal(await typedFolder(` "${dir}" `, only), dir); + await assert.rejects(typedFolder(join(dir, 'notes.txt'), only), /folder, or a \.gguf file/); + await assert.rejects(typedFolder(join(dir, 'missing.gguf'), only), /does not exist/); + // the other pickers still refuse a file + await assert.rejects(typedFolder(join(dir, 'model-00001-of-00002.gguf'), { isAbsolute }), /not a file/); + } finally { await rm(dir, { recursive: true, force: true }); } +}); + +async function startHost() { + const home = await mkdtemp(join(tmpdir(), 'strata-folder-home-')); + const net = await import('node:net'); + const probe = net.createServer(); + await new Promise(r => probe.listen(0, '127.0.0.1', r)); + const { port } = probe.address(); + await new Promise(r => probe.close(r)); + const child = spawn(process.execPath, [join(HOST_ROOT, 'server', 'index.mjs'), '--dist', join(HOST_ROOT, 'dist')], { + cwd: HOST_ROOT, env: { ...process.env, STRATA_HOME: home, STRATA_WORKSPACE: home, STRATA_PORT: String(port), STRATA_REAL_ENGINE: '0' }, stdio: 'ignore', + }); + const base = `http://127.0.0.1:${port}`; + for (let i = 0; i < 150; i++) { + try { if ((await fetch(`${base}/api/health`)).ok) return { child, base, home }; } catch { /* not up yet */ } + await new Promise(r => setTimeout(r, 100)); + } + child.kill(); + throw new Error('the host did not become healthy'); +} + +test('the host accepts a typed folder path for the picker and for adding a skill, on every OS', { timeout: 60000 }, async () => { + const { child, base, home } = await startHost(); + const skill = await mkdtemp(join(tmpdir(), 'strata-skill-')); + try { + const post = (path, body) => fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + let r = await post('/api/workspaces/pick', { path: skill }); + assert.deepEqual(await r.json(), { path: skill }); + r = await post('/api/workspaces/pick', { path: join(skill, 'nope') }); + assert.equal(r.status, 400); + assert.match((await r.json()).error, /does not exist/); + r = await post('/api/skills/add', { path: skill }); + assert.equal(r.status, 400); + assert.match((await r.json()).error, /no SKILL\.md/); + await writeFile(join(skill, 'SKILL.md'), '---\nname: Typed\n---\nbody\n'); + r = await post('/api/skills/add', { path: skill }); + assert.equal(r.status, 200); + assert.ok((await r.json()).added); + } finally { + child.kill(); + await rm(skill, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }).catch(() => {}); + } +}); + +// QA report F06: a Windows folder window that never opens must not leave the button disabled forever. +import { EventEmitter } from 'node:events'; +import { watchedWindowsDialog } from '../server/folder-dialog.mjs'; +function fakeShell() { + const child = new EventEmitter(); child.stdout = new EventEmitter(); child.killed = false; child.kill = () => { child.killed = true; }; + return { child, spawnProcess: () => child }; +} +test('Windows: no READY from the dialog script means the host gives up and the app asks for the path', async () => { + const f = fakeShell(); + const result = await watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess }); + assert.deepEqual(result, { noDialog: true }); assert.equal(f.child.killed, true, 'the stuck PowerShell is ended'); + const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ noDialog: true }) }); + assert.equal(answer.unavailable, true); assert.match(answer.reason, /Type the folder path/); +}); +test('Windows: once READY has come the person may take their time, and the answer is read without the READY line', async () => { + const f = fakeShell(); + const pending = watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess }); + f.child.stdout.emit('data', 'READY\r\n'); + await new Promise(r => setTimeout(r, 80)); // longer than readyMs: still waiting, not given up + assert.equal(f.child.killed, false); + f.child.stdout.emit('data', 'C:\Users\me\Skills'); f.child.emit('close', 0); + const done = await pending; + const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => done }); + assert.deepEqual(answer, { path: 'C:\Users\me\Skills' }); + const cancelled = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ stdout: 'READY\r\n' }) }); + assert.deepEqual(cancelled, { cancelled: true }); +}); +test('Windows: a PowerShell that is missing or fails is reported as before', async () => { + const f = fakeShell(); + const missing = watchedWindowsDialog('powershell.exe', [], { spawnProcess: f.spawnProcess }); + 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); + // 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 b541d7ad660a6d5d1b355bf80c0e6d755f5de5fe Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:56:39 +0100 Subject: [PATCH 42/59] A reply the length limit cuts inside a file write is no longer lost without a word: requests may produce half the window (compaction's reserve is unchanged), a cut reply is announced and the agent is asked to go on in smaller parts, and the file being written streams to the page (name, size, lines, tail) --- apps/host/scripts/agent-lost-e2e.mjs | 181 + apps/host/server/agent/README.md | 334 +- apps/host/server/agent/agent-bridge.mjs | 2887 +++++------ apps/host/server/agent/events.mjs | 965 ++-- .../server/agent/plugins/strata-context.mjs | 365 +- apps/host/server/agent/reply-cut.mjs | 122 + apps/host/src/lib/store.ts | 4378 +++++++++-------- apps/host/src/lib/types.ts | 1058 ++-- apps/host/tests/agent-lost.test.mjs | 185 + apps/host/tests/agent-tools.test.mjs | 573 +-- apps/host/tests/helpers/scripted-worker.mjs | 17 + 11 files changed, 5855 insertions(+), 5210 deletions(-) create mode 100644 apps/host/scripts/agent-lost-e2e.mjs create mode 100644 apps/host/server/agent/reply-cut.mjs create mode 100644 apps/host/tests/agent-lost.test.mjs diff --git a/apps/host/scripts/agent-lost-e2e.mjs b/apps/host/scripts/agent-lost-e2e.mjs new file mode 100644 index 0000000000..787ba89fad --- /dev/null +++ b/apps/host/scripts/agent-lost-e2e.mjs @@ -0,0 +1,181 @@ +#!/usr/bin/env node +/** + * AGENT-LOST end to end: a long single-file write through the real agent bridge, the real Harness and a real engine. + * + * STRATA_HARNESS_DIR=<harness folder> node scripts/agent-lost-e2e.mjs [pagoda|long|cut ...] + * + * Scenarios (default: all) + * pagoda the owner's own prompt ("Write me a 100 voxel pagoda in one html file with garden."), thinking Medium, bypass mode + * long a deterministic long write: one file of N numbered lines (E2E_LINES, default 1800, about 22K tokens), thinking Off + * raw the model server alone: a reply cut inside a tool call, as the client receives it + * cut the same long write with the Harness told a small window (E2E_CUT_WINDOW, default 24000), so the reply budget is + * about 7K tokens and the reply is cut inside the tool call: the turn must say so in words and the agent must carry on + * + * A model server that is already running is used when E2E_BASE_URL is set (nothing is started or stopped). Otherwise this + * starts serve/server.py as its own child with the engine named below and stops it by PID. + * + * Environment: E2E_ENGINE (strata executable), E2E_PACK, E2E_GGUF1, E2E_GGUF2, E2E_MTP, E2E_PROFILE, E2E_LIB (library folder), + * E2E_PORT (18590), E2E_WINDOW (65536), E2E_OUT (result folder), E2E_PYTHON. + * + * It prints one table and writes <E2E_OUT>/result.json with the frames summary of each scenario. + */ +import { spawn } from 'node:child_process'; +import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; + +const REPO = join(import.meta.dirname, '..', '..', '..'); +const env = (name, fallback) => process.env[name] ?? fallback; +const HOME = process.env.HOME ?? ''; +const PORT = Number(env('E2E_PORT', '18590')); +const WINDOW = Number(env('E2E_WINDOW', '65536')); +const EXISTING = process.env.E2E_BASE_URL ?? ''; +const PYTHON = env('E2E_PYTHON', 'python3'); +const OUT = env('E2E_OUT', mkdtempSync(join(tmpdir(), 'strata-agent-lost-'))); +const LINES = Number(env('E2E_LINES', '1400')); +const wanted = process.argv.slice(2); +const want = id => wanted.length === 0 || wanted.includes(id); +mkdirSync(OUT, { recursive: true }); + +if (!process.env.STRATA_HARNESS_DIR) { console.error('STRATA_HARNESS_DIR is not set'); process.exit(2); } +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +let server = null, bridge = null; +const finish = async (code) => { + try { await bridge?.close(); } catch { /* going away */ } + if (server?.pid) { try { process.kill(-server.pid, 'SIGTERM'); } catch { try { process.kill(server.pid, 'SIGTERM'); } catch { /* gone */ } } } + await sleep(1500); + console.log(`\nresult folder: ${OUT}`); + process.exit(code); +}; +process.on('SIGINT', () => finish(130)); + +if (!EXISTING) { + const pack = env('E2E_PACK', join(HOME, '026q/pack-iq3s')); + const g1 = env('E2E_GGUF1', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf')); + const g2 = env('E2E_GGUF2', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf')); + const mtp = env('E2E_MTP', join(HOME, 'pr1426/mtp-rt')); + const profile = env('E2E_PROFILE', join(HOME, 'bwm/cnt3/data/expert-profile.bin')); + const exe = env('E2E_ENGINE', join(HOME, 'agentlost/eng/strata')); + const lib = env('E2E_LIB', join(HOME, 'agentlost/eng')); + for (const f of [pack, g1, g2, mtp, exe]) if (!existsSync(f)) { console.error(`missing: ${f}`); process.exit(2); } + const config = join(OUT, 'server.json'); + writeFileSync(config, JSON.stringify({ + exe, args: ['--pack', pack, '--native', g1, '--ple-gguf', g2, ...(existsSync(profile) ? ['--expert-profile', profile] : []), + '--prefill', 'auto', '--spec-min-p', '0.5', '--mtp', mtp, '--max-context', String(WINDOW), '--kv', 'int8', '--expert-cache', 'auto', '--spec', '4', + ...(process.env.E2E_ENGINE_ARGS ? process.env.E2E_ENGINE_ARGS.split(' ').filter(Boolean) : [])], + cwd: REPO, tokenizer: join(pack, 'tokenizer'), model_name: 'qwen3.8-flash-next-iq3_s', log: join(OUT, 'engine.log'), lib_dirs: [lib], port: PORT, gpu: 0, + fit_max_tokens: true, + }, null, 2)); + server = spawn(PYTHON, ['serve/server.py', '--engine', 'strata', '--config', config, '--port', String(PORT), '--no-api-key', '--ready-file', join(OUT, 'ready.json')], { + cwd: REPO, env: { ...process.env, LD_LIBRARY_PATH: `${lib}:${process.env.LD_LIBRARY_PATH ?? ''}`, STRATA_DATA_DIR: join(OUT, 'data'), PYTHONPATH: `${join(REPO, 'tools')}:${REPO}` }, stdio: ['ignore', 'pipe', 'pipe'], detached: true, + }); + const sink = []; + server.stdout.on('data', d => sink.push(String(d))); + server.stderr.on('data', d => sink.push(String(d))); + server.on('exit', code => { sink.push(`[server exited ${code}]`); server = null; writeFileSync(join(OUT, 'server.log'), sink.join('')); }); +} + +const base = EXISTING || `http://127.0.0.1:${PORT}`; +let ready = false; +for (let i = 0; i < 360 && !ready; i++) { + if (!EXISTING && !server) break; + try { ready = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(2000) })).ok; } catch { /* still loading */ } + if (!ready) await sleep(2000); +} +if (!ready) { console.error('the engine did not become ready'); await finish(4); } +const model = (await (await fetch(`${base}/v1/models`)).json()).data[0].id; +console.log(`engine ready: ${model}`); + +const rows = []; +const note = (id, ok, detail) => { rows.push({ id, ok, detail }); console.log(`${ok ? 'PASS' : 'FAIL'} ${id} ${detail}`); }; + +/** The bridge for a window as the host would tell it (the engine's own window stays WINDOW). */ +function makeBridge(window, dir) { + mkdirSync(join(OUT, dir), { recursive: true }); + return createAgentBridge({ + dataDir: join(OUT, dir), env: process.env, startTimeoutMs: 180_000, log: l => console.log(' bridge:', l), + localInstances: () => [{ id: 'e2e', label: 'iq3_s', baseUrl: `${base}/v1`, modelId: model, context: window, slots: 1, key: '' }], connections: () => [], + }); +} +bridge = makeBridge(WINDOW, 'agent'); + +/** One agent turn; every frame is kept in a compact timeline so the live data path can be read afterwards. */ +async function turn(name, message, { thinking = 'Medium', mode = 'bypass', chatId = name } = {}) { + const workspace = join(OUT, 'ws-' + name); + mkdirSync(workspace, { recursive: true }); + const frames = []; + const t0 = Date.now(); + await bridge.runTurn({ chatId, message, workspacePath: workspace, mode, thinking, onFrame: f => frames.push({ at: Date.now() - t0, f }) }); + const seconds = (Date.now() - t0) / 1000; + const byType = {}; + for (const { f } of frames) byType[f.type] = (byType[f.type] ?? 0) + 1; + const done = frames.map(x => x.f).filter(f => f.type === 'done').at(-1) ?? null; + const error = frames.map(x => x.f).filter(f => f.type === 'error').at(-1) ?? null; + const prepare = frames.map(x => x.f).filter(f => f.type === 'status' && (f.phase === 'preparing' || f.code === 'preparing-tool')); + const cards = frames.map(x => x.f).filter(f => f.type === 'agent-tool').map(f => f.tool); + const text = frames.map(x => x.f).filter(f => f.type === 'delta').map(f => f.text).join(''); + const files = readdirSync(workspace).map(n => ({ name: n, bytes: statSync(join(workspace, n)).size })); + const cutNotes = frames.map(x => x.f).filter(f => f.type === 'delta' && f.noteReason === 'cut').map(f => f.text.trim()); + const drafts = frames.map(x => x.f).filter(f => f.type === 'agent-tool-draft').map(f => f.draft); + const writes = drafts.filter(d => d.name === 'write' && d.bytes > 0); + const draftStats = { frames: drafts.length, writeFrames: writes.length, lastWrite: writes.filter(d => !d.done).at(-1) ? { target: writes.filter(d => !d.done).at(-1).target, bytes: writes.filter(d => !d.done).at(-1).bytes, lines: writes.filter(d => !d.done).at(-1).lines } : null, previewSample: writes.filter(d => !d.done).at(-1)?.preview.slice(-80) ?? null }; + const summary = { name, seconds, cutNotes, draftStats, byType, done, error, files, cards: cards.map(c => ({ name: c.name, state: c.state, target: c.target })), prepareStatuses: prepare.length, firstPrepare: prepare[0] ?? null, lastPrepare: prepare.at(-1) ?? null, text: text.slice(-1200) }; + writeFileSync(join(OUT, `turn-${name}.json`), JSON.stringify({ summary, frames: frames.slice(0, 4000) }, null, 1)); + return { ...summary, frames, workspace }; +} + +const longPrompt = `Create the file big.txt in the current folder with the write tool, in ONE call. It must hold exactly ${LINES} lines. Line N is "N: " followed by one short true sentence about a different city of the world (a new city on every line, no repeats, no pattern). Write every line out yourself, do not use a script or a loop, and do not shorten it.`; + +if (want('raw')) { + // What the model server itself sends when a reply is cut inside a tool call (no Harness): the stream of tool_calls pieces, then finish_reason "length". + const body = { model, stream: true, max_tokens: Number(env('E2E_RAW_CAP', '700')), temperature: 0.6, + chat_template_kwargs: { enable_thinking: false }, + tools: [{ type: 'function', function: { name: 'write', description: 'Write a file.', parameters: { type: 'object', properties: { file_path: { type: 'string' }, content: { type: 'string' } }, required: ['file_path', 'content'] } } }], + messages: [{ role: 'user', content: longPrompt }] }; + const res = await fetch(`${base}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + const text = await res.text(); + const events = text.split(String.fromCharCode(10)).filter(l => l.startsWith('data: {')).map(l => JSON.parse(l.slice(6))); + let args = '', name = '', content = '', finish = null, pieces = 0, ids = new Set(); + for (const e of events) for (const c of e.choices ?? []) { + for (const tc of c.delta?.tool_calls ?? []) { pieces += 1; if (tc.id) ids.add(tc.id); if (tc.function?.name) name = tc.function.name; args += tc.function?.arguments ?? ''; } + content += c.delta?.content ?? ''; + if (c.finish_reason) finish = c.finish_reason; + } + const usage = events.map(e => e.usage).filter(Boolean).at(-1); + writeFileSync(join(OUT, 'raw-sse.txt'), text); + note('raw: a reply cut inside a tool call reaches the client as pieces of the call and finish_reason length', finish === 'length' && name === 'write' && pieces > 5, `finish ${finish}; tool ${name}; ${pieces} call pieces, ${args.length} argument characters, closed JSON ${(() => { try { JSON.parse(args); return true; } catch { return false; } })()}; plain content ${JSON.stringify(content.slice(0, 80))}; ids ${ids.size}; usage ${JSON.stringify(usage)}`); +} + +if (want('pagoda')) { + const t = await turn('pagoda', 'Write me a 100 voxel pagoda in one html file with garden.'); + const html = t.files.find(f => /\.html?$/i.test(f.name)); + console.log(` pagoda: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, files ${JSON.stringify(t.files)}`); + note('pagoda: a file was written or the turn says why not', !!html || /cut|too long|ran out|limit/i.test(t.text), `file ${html ? html.name + ' ' + html.bytes + ' B' : 'none'}; finish ${t.done?.finishReason}; text tail: ${JSON.stringify(t.text.slice(-240))}`); +} +if (want('long')) { + const t = await turn('long', longPrompt, { thinking: 'Off' }); + const f = t.files.find(x => x.name === 'big.txt'); + const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0; + console.log(` long: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, draft ${JSON.stringify(t.draftStats)}, cut notes ${JSON.stringify(t.cutNotes)}`); + note(`long: big.txt written (${LINES} lines asked)`, lines >= LINES * 0.95 || t.cutNotes.length > 0 && !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}; tokens out ${t.done?.tokensOut}; cards ${JSON.stringify(t.cards.filter(c => c.state !== 'running').map(c => c.name))}; cut notes ${t.cutNotes.length}; draft frames ${t.draftStats.frames}`); + note('long: the turn did not end silently', !!f || t.cutNotes.length > 0 || t.text.trim().length > 0, `text tail ${JSON.stringify(t.text.slice(-160))}`); +} + +if (want('cut')) { + // A small window told to the Harness (E2E_CUT_WINDOW, default 24000; the engine's own stays WINDOW) makes the reply budget about 7K tokens (raised to + // 12K by the fix), so the first reply is cut inside the tool call, as the pagoda's was at 19,660. + await bridge.close(); + bridge = makeBridge(Number(env('E2E_CUT_WINDOW', '24000')), 'agent-cut'); + const t = await turn('cut', longPrompt, { thinking: 'Off' }); + const f = t.files.find(x => x.name === 'big.txt'); + const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0; + console.log(` cut: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason })}, files ${JSON.stringify(t.files)}, cut notes ${JSON.stringify(t.cutNotes)}, draft ${JSON.stringify(t.draftStats)}`); + note('cut: the chat said the reply was cut, in words', t.cutNotes.length > 0 && t.cutNotes.every(n => /length limit/.test(n)), JSON.stringify(t.cutNotes)); + note('cut: the agent went on and the file exists', !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}`); +} + +writeFileSync(join(OUT, 'result.json'), JSON.stringify(rows, null, 2)); +console.log('\n' + rows.map(r => `${r.ok ? 'PASS' : 'FAIL'} ${r.id}`).join('\n')); +await finish(rows.some(r => !r.ok) ? 1 : 0); diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index 11c3279bc0..4b8838c3e6 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -1,167 +1,167 @@ -# Agent bridge (Strata chats as DeepSeek Harness sessions) - -This page is for developers who work on the app host's agent code. It lists the files, the frames and routes, and the rules the -bridge enforces. Tests are listed at the end. - -The Harness is a separate, pinned component (`DSH 0.2.1-alpha.3`, commit `57190202`, MIT). The host finds it through -`STRATA_HARNESS_DIR` (or `<STRATA_COMPONENTS_DIR>/harness`), starts one `dsh --profile web` process on a loopback port, -and talks to its Gateway. Nothing here downloads or builds anything. - -| File | Job | -| --- | --- | -| `harness-runtime.mjs` | locate the component, start/stop the process, scrub its environment, clean up a leftover process from a dead host | -| `gateway-client.mjs` | HTTP RPC plus the `remote.mux` WebSocket (`$events`, `session/follow`) | -| `profile.mjs` | generate the Harness profile: one route per ready local instance and per saved API connection; credential names only | -| `task-run.mjs` | a scheduled task as the agent | -| `events.mjs` | pure projection of Harness session events into the chat's NDJSON frames | -| `children.mjs` | pure projection of one helper agent's events into its row and its approval card | -| `preset.mjs` | the agent preset (which tools the chat has) | -| `plugins/strata-gate.mjs` | the Manual-mode approval gate (a Harness plugin, loaded by path) | -| `plugins/strata-search.mjs`, `plugins/strata-models.mjs` | the app's web search registered with the Harness; helper agents on a named model | -| `plugins/strata-context.mjs`, `context-budget.mjs`, `context-fit.mjs` | measured context pressure, summaries that fit the window, the check before a message goes out | -| `agent-bridge.mjs` | the chat-to-session map, turns, approvals, Stop, status | - -## Frames sent on `/api/chat/stream` for an agent turn - -`queued`, `start` (`agent:true`), `reasoning`, `delta`, `agent-tool` (upserts a tool card by call id with -`running | proposed | done | denied | error`), `done` (usage, `finishReason`, `cancelled`), `error`, and `notice` -(why a chat is not using the agent). The chat UI renders them with its existing components. - -## Routes - -- `GET /api/agent/status`: component, routes, active turns, pending approvals (no tokens, no keys) -- `POST /api/chat/approval {sessionId, toolId, decision: approve|deny}` -- `POST /api/chat/stop {sessionId}`: cancels that chat's Harness session and answers once the turn has ended -- `GET /api/agent/pending?chatId=` - -## Behaviour worth knowing - -- **Stop is per chat.** `session/cancel` is only an admission; the bridge waits for the durable `turn/end`. Stop before the - prompt reached the Harness cancels the start. The process is never killed to implement Stop. -- **A closed tab is not Stop.** The turn keeps running; an approval it needs stays pending until someone answers. -- **Resume.** The chat id maps to a Harness session id (`<data>/agent/sessions.json`). Reopening prompts that session; the - Harness resumes it from its own record, so nothing is replayed. (`session/create` with a started id returns a new - session, so it is never used for resume.) -- **Models.** Each chat sends its choice; the bridge calls `session/selectModel` for that route before the prompt. A route - that is gone is a typed `model-unavailable` error, never another model. Keys travel as environment variables named by - `apiKeyEnv`; the agent's shell does not inherit them, and logs are redacted. -- **No answerer, no hang.** The agent's own questions (`ask_user_question`) are declared unanswerable until the app has a - surface for them. -- **Fallback.** Without the component the host says so (`/api/agent/status`, a `notice` frame) and the chat runs on the - direct path with the model the user picked. - -## Modes (the Mode menu) - -The chat's Mode menu is real Harness behaviour. Each turn the page sends the chat's mode (`mode` in the `/api/chat/stream` body); before the prompt reaches the Harness the bridge puts that chat's session into the matching permission preset with the Harness's own `/permission` command (`commands/execute`), reads the `permissions` projection back, and refuses to start the turn (typed error `mode-unavailable`) if it does not match. The preset table is ours (profile entry `permission`). - -| Menu | Preset | Sandbox | Approval | What it means | -| --- | --- | --- | --- | --- | -| Manual (default) | `strata-manual` | open (`danger-full-access`) | `ask` | The Strata gate (`plugins/strata-gate.mjs`) asks BEFORE any change runs: one Approve/Deny card, nothing has happened when it appears, no blocked attempt, no sandbox or PowerShell error. Reads and read-only commands run without a question; anything the gate cannot prove read-only asks. | -| Plan | `strata-plan` | `read-only` | `never` | Nothing can change. A request is rejected without asking anyone, so no Approve card is shown; the card ends "Not allowed in this mode". | -| Bypass | `strata-bypass` | `danger-full-access` | `never` | Full access without prompts, as before. | - -- Manual relies on the gate, so a Manual turn does not start unless the bridge has confirmed the gate is loaded (`/strata-gate` command): without it Manual would be an open sandbox that nobody asks about. -- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked, each only with the options listed for it in `strata-gate.mjs` (an unknown option, or one that writes, runs a program, sets something or never ends, asks); MCP and unknown tools ask. -- Web search and web pages (`web_search`, `web_fetch`) ask once per chat in Manual, not once per call. The gate asks through the approval service itself (`webDecision`: "The assistant wants to search the web for: ... Search words go to <service>." / "... open the web page ..."), remembers a yes for the chat (a helper agent shares its chat's answer, and two searches started together share one card), and on a no gives the model `WEB_REFUSAL` ("The person did not allow web access ... Go on without it and say so."). Plan and Bypass are unchanged. Settings -> Tools has a switch, "Let the assistant search the web without asking" (off by default, `webWithoutAsking` in `tools-settings.mjs`, passed to the gate as `config.web.skipAsk`), that skips the question in Manual. A scheduled task has nobody at the card, so its web call is answered no unless that switch is on. Tests: `tests/web-ask.test.mjs`. -- The mode is read once per turn; an unknown or missing value is Manual. - -## Tools - -`preset.mjs` is the agent preset: the Harness `standard` preset minus the scheduler (Tasks is the only one), the agent's own question tool (no place to answer) and the Harness's plan mode. `tests/agent-tools.test.mjs` compares the list with the pinned Harness's own file, so a Harness update that adds or renames a plugin fails a test instead of silently dropping a tool. - -### Settings -> Tools - -What the person chose is saved by `tools-settings.mjs` (inside the host's settings file) and shown by `src/components/SettingsTools.tsx` (`GET/PUT /api/agent/tools`, `POST/PATCH/DELETE /api/agent/tools/custom[/id]`). A change reaches the agent from the next message: the profile carries a `toolsSignature`, and the bridge restarts the Harness (after the running turns end) when it differs. - -- Tool groups (`tools-catalog.mjs`): each is one switch in plain words and is one or more preset plugins (`withoutDisabled`); `fetch` and `search` are the two halves of the Harness's `tool-web` (both off drops it). Goals off: `/goal` answers that goals are turned off. -- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`), with Bing's plain result page (`../web-search-bing.mjs`) as the second source. Manners, because DuckDuckGo refuses a program that asks fast: a browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*), one request at a time per source, 2.5 to 4 s apart (random), at most 8 a minute, a 30 minute session cache per question, a cooldown after a refusal that doubles (1, 2, 4 ... 10 minutes, `Retry-After` honoured) during which that source gets no request, no lite-page follow-up after a refusal, one retry for a timeout or a 5xx, a 15 s limit. When every source refuses, the tool answers one plain sentence (`LIMITED_SENTENCE`: "Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings -> Tools -> Web search.") plus an instruction to the model not to retry; the turn guard in `agent-bridge.mjs` (see Turn guard) stops a model that retries anyway. **The results come from DuckDuckGo or Bing**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous. -- The browser: Playwright's MCP server (`@playwright/mcp`, staged next to the Harness by `apps/desktop/scripts/stage-harness.mjs`) on the person's own Chrome, Edge or Chromium (`browser-probe.mjs`), `--isolated` so it never sees their profile. Tools appear as `mcp__browser__browser_*`. In Manual, opening a page, clicking, typing, uploading, running a script in the page and closing tabs ask (plain reasons: "Open the web page ...", "Click on the page: ..."); looking (snapshot, screenshot, console, network, waiting, listing tabs) does not. Plan refuses every connected tool. The screen says plainly when no browser, or no tool server, is found. -- The person's own tools: `instructions` (the tool returns their text; look-only, never asks), `command` (runs their command with the assistant's text in the `STRATA_INPUT` environment variable, never spliced into the command line; asks in Manual, refused in Plan) and `server` (a web address or a program, added as `mcp__custom-<name>__*`; asks in Manual). Instruction and command tools are served by `custom-tools-mcp.mjs` (stdio MCP) from a JSON file the settings module rewrites on every change, so a switch in Settings is seen without a restart. -- `strata-gate.mjs` implements the Manual/Plan rules above (`planDecision`, `browserDecision`, the look-only instruction server). - -## Helper agents (subagents) - -- A Harness `subagent/catalog` event on the chat's session creates a row; `children.mjs` folds the helper's `session/follow` (address `{kind:'subagent', parentSessionId, childSessionId}`) into `{type:'agent', agent:{id,name,description,status,durationMs,tokens,updatedAt}}`, the shape the Subagents popover already reads. The delegation tools have no card. -- A helper's request for approval is the same card (state `proposed`, id `<helper session>:<call>`), answered with the same `/api/chat/approval`; a chat can only answer its own helpers. -- The run (the chat's one NDJSON response) stays open until the parent is idle, every helper has finished and reported back, and no armed goal is waiting; `done` is sent then. -- Stop: pauses an active goal, interrupts every helper (`subagents/interruptByParent`; `session/cancel` on a helper session is refused by the Harness), cancels the parent, waits; a report that would wake the parent afterwards is cancelled too. -- The number of helpers at once is the engine's request slots, with a floor of 4 for a local model and 8 for an API model (`maxActiveSubagents` in the profile). The Harness refuses more with a message the model reads. - -## /goal - -`/goal` typed in a chat goes to `bridge.goalCommand`: nothing = show the goal, `clear`, `pause`, `resume`, `edit <text>`, `complete`, anything else = a new goal (one unfinished goal at a time). Create/resume use the Harness goal Remotes (`goals/create|get|resume|pause|edit|clear|complete`); the Harness's goal driver runs the rounds and they stream into the chat ("Working on the goal…", with no step counter); the run ends when the goal stops (complete, paused, blocked, round limit - the default cap is the Harness's 256, a run with `maxRounds` is capped) and says how in plain words. After a restart an active goal stays disarmed until `/goal resume`. - -## Thinking and the output budget - -The Harness staging script (`apps/desktop/scripts/stage-harness.mjs`) applies Strata's guarded pi-ai 1.1.0 patch to its staged copy -(`harness-budget.mjs`, #3684): below 64K the context safety room is at most `min(4096, floor(contextWindow / 16))` and never more -than half the estimated remaining room, so an 8K window keeps output room after a tool result instead of ending with a one-token -cap. The caller's output cap and the one-token floor remain; windows of 64K or more keep the previous calculation. `BUNDLE.json.patches` -records the patch identity, the dependency version and the before/after SHA-256. Unknown dependency bytes stop staging for review. -Source and already-installed Harness copies are not changed. - -- A local route is reasoning-capable (`reasoning: true`) with `compat.thinkingFormat: 'chat-template'`: the request carries `chat_template_kwargs {enable_thinking, reasoning_effort}`, which the Strata server reads (a top-level `enable_thinking` is ignored by it, which is why pi-ai's `qwen` format left the model thinking). The chat's Reasoning menu travels as `thinking` in the stream body; the bridge sends it with `session/selectModel` (`reasoningEffort`) whenever the model or the level changed; a level a route does not have is dropped (never an error). API routes keep the provider default (the menu is disabled for them in the UI). -- `localOutputBudget(context)` is 30 percent of the window, at least 4096 and at most 32768 (9,830 tokens at 32K, 19,660 at 64K). The Harness's automatic compaction reads it as the room a reply reserves. pi-ai sends the window minus the prompt. App-loaded models get `fit_max_tokens: true` so the engine clamps instead of answering 400. Sampling is not set here: the Harness sends none, so the server's own defaults apply. - -## Tasks - -`task-run.mjs` runs a scheduled task as the agent: a Harness session of its own (`task:<id>`, dropped after every run), the task's mode (`plan` default, `manual`, `bypass`), and a result built by `../task-report.mjs`. Nobody is at the screen: an approval request is answered "no" at once and reported ("Nothing was changed"). `server/tasks.mjs` stays the only scheduler; it sends a `task` event when a run ends (the page shows a toast). - -## Plain words - -Failures the person sees are plain sentences with a next step (`AgentUnavailable.message`); the technical text is in `.details` / the `details` field of error and notice frames, and in `/api/agent/status` `detail`. A failed tool's card result is a plain sentence followed by "Details: <original text>". - -## Tests - -`tests/agent-events.test.mjs` (pure), `tests/agent-tools-settings.test.mjs` (Settings -> Tools, web search, the browser and the person's own tools; the Harness-backed ones need STRATA_HARNESS_DIR and the browser one also Chrome or Edge), `tests/agent-bridge.test.mjs`, `tests/agent-modes.test.mjs` and `tests/agent-host.test.mjs` (need a built Harness: -`STRATA_HARNESS_DIR=<checkout>`, otherwise they skip and say so). The model in those tests is `tests/helpers/scripted-worker.mjs`. -`scripts/agent-flow.mjs` drives the real app in Chrome and takes screenshots. - -## Helper agents on a named model (`plugins/strata-models.mjs`, `model-routes.mjs`) - -The Harness's `subagent` tool takes an exact `provider` route key and model id. The profile enables the Harness's `subagent-model-selection-settings` with every route the app can reach (local instances and saved API models), and the `strata-models` plugin wraps the two tool definitions the Harness registers for each chat (`subagent`, `list_subagent_models`) in place: - -- the model is found from its id, `provider/id`, the name in the model picker, `connection name`, or "local" (any letters). A close guess is not started: the tool answers "Did you mean ...?" and nothing runs until the call is made again with that model. Several fits are listed; nothing fitting lists the models that can be used and says they can be added in Models. -- the tool's own text says when to use it ("ask a subagent", "ask model X"), not to look for the model with shell commands, and not to wait with sleep. The system prompt (`preset.mjs`) says the same, so it reaches every model, local or hosted. -- `list_subagent_models` lists the models by the names the person knows. - -If a Harness update renames those tools the wrapping does nothing and `tests/agent-subagent-models.test.mjs` (real Harness) fails. - -## Reasoning for API models - -A model on OpenRouter whose model list names `reasoning` in `supported_parameters` gets `reasoning: true` and the efforts `{off: none, low, medium, high, max: xhigh}` and the `openrouter` thinking format, so the Reasoning menu works and the choice reaches OpenRouter as `reasoning: { effort }`. Other API models keep the provider's own default (the menu stays greyed). - -## Pictures - -Pictures are on by default for every model that can read them: an API model reads them unless the person switched it off (Settings > Models > "Read pictures with this model") or its server says it cannot; a local model reads them when it was loaded with Read pictures (on by default). `src/lib/pictures.ts` is the one answer used by the composer and by Send; the agent route declares image input from the same flag. - -## Turn guard (`turn-guard.mjs`) - -A turn that keeps failing the same way is stopped by the app, never left to the model. - -- **Counted, from what the turn shows:** web searches that failed in a row (3), searches in one turn (10 in a plan turn, 25 otherwise), a plan turn that starts its numbered list from `1.` again (4 times), and a context of 93% or more (the Harness's own compaction did not keep up). -- **Stopped the way Stop stops** (`session/cancel`, helpers first) but ended as a normal turn (`done`, not cancelled, no error card), so the plan the model had written is still proposed. The plan card carries the reason (`plan.caution`); any other turn ends with one `delta` frame that has `own: true` and `key` (the English sentence, translated by the page; `GUARD_NOTES` are in the interface catalog in all eight languages). Each sentence says what happened and gives one next step. -- **Compaction:** after a guard stop (and after a turn the model server refused because the context was full) the bridge asks the Harness for `/compact` on that session, so the next message has room. Best effort and logged. -- **Never silent:** a turn that ends (`completed` or `max-tokens`) with no answer text gets "I ran out of room in this chat..." when the last request used 85% of the window or more, otherwise "I stopped without writing an answer..." (not when tool cards were shown, not after Stop, not after an error, which says why by itself). Goal runs have their own ending lines and are not guarded. -- Tests: `tests/agent-turn-guard.test.mjs` (counting, always; end to end with the real Harness, the scripted model's `searchloop` and `bloat` scripts and `searchMock: 'limited'` on the bridge, which runs the real search code on a pretend web that refuses, no network). - -## Context: measured pressure, summaries that fit, the check before a message goes out - -- **`plugins/strata-context.mjs`** (inserted by the profile, like the gate) wraps `tokenMeter.measure` and `llm.stream` in place, once each. Pressure = the last prompt size the model server reported for an answer, plus what changed since priced at the density that measurement showed (`context-budget.mjs`: `pressureNow`, `densityOf`); never lower than the Harness's own price. Node prices are scaled the same way, so the retained tail is in real tokens. A summary request (`purpose: 'compaction'`) that would not fit the window is asked for in pieces: a message bigger than a piece is cut for the request only, each piece builds on the summary before it, a piece the server refuses is halved and tried again. `/strata-context` (a Harness command, like `/strata-gate`) answers `{tokens, window}` for a session so the host can tell the person true figures. -- **`context-fit.mjs`**: before a message is sent the model server counts it (`POST /v1/messages/count_tokens`, its own tokenizer). `decideFit`: send; summarise first and then send (the message fits an otherwise empty chat); or never fits. The last one is not sent: the error frame has `code: 'CONTEXT_MESSAGE_TOO_LARGE'` and the page offers "Attach as a file" (`oversize.mjs`, `/api/chat/oversize`: the text is saved in the chat's folder, the assistant reads it in parts) or "Send a shortened preview". An engine that cannot count lets the message through; the Harness's own compact-and-retry is the net. -- **`/compact`** is handled by the host (`compactCommand`): the Harness's `/compact`, then a plain line with the measured figures ("The chat was 90% full and is now 38% full"), or "nothing older to summarize" when the newest message is what fills the chat. -- **Visible:** `compaction/start` shows "Summarizing earlier messages..." in the status line; `compaction/end` adds one plain line to the reply. The projector also sends a `context` frame after every model request, so the meter follows the running turn. -- **A refusal that is left** (`CONTEXT_WINDOW_EXCEEDED`) is a plain sentence with the engine's text under Details and the buttons "Summarize and continue" and "Start a new chat". "Try sending the message again" is for other errors only. -- Tests: `tests/agent-context.test.mjs` (arithmetic; the real Harness against the scripted worker with `window`, `charsPerToken` and `noCount`), `tests/oversize.test.mjs`, `tests/context-ui.test.mjs`. The run against a real engine is `scripts/context-e2e.mjs`. - -## History / older measurements - -- **Search refusals (2026-10):** on a real box two DuckDuckGo searches in 1.2 s answered, the third got HTTP 202, and every DuckDuckGo page refused for many minutes. - The pacing, cooldown and cache rules above come from that test. -- **Search-heavy `/plan` (2026-10):** every web search was refused, the model searched again and rewrote its plan after each one until the context reached 100%. - The turn ended with no answer and no message. The turn guard comes from that run. -- **Large log paste (2026-10-22, installed 0.2.1, Gyro-S, 64K):** a 118 KB log was 66,500 tokens to the engine and about 29,500 to the Harness - (4 characters a token; logs and code are about 2). The engine refused it with a 400. The refusal stayed in the history, so neither the next message nor `/compact` could - go through, because the summary request carried the same history. `/compact` was also not a command of the app yet: it went to the model as a question. This - produced `strata-context.mjs`, `context-fit.mjs` and the host's own `/compact`. -- **Output budget:** an earlier local budget of a quarter of the window, capped at 8192, cut big answers off at exactly 8192 tokens. +# Agent bridge (Strata chats as DeepSeek Harness sessions) + +This page is for developers who work on the app host's agent code. It lists the files, the frames and routes, and the rules the +bridge enforces. Tests are listed at the end. + +The Harness is a separate, pinned component (`DSH 0.2.1-alpha.3`, commit `57190202`, MIT). The host finds it through +`STRATA_HARNESS_DIR` (or `<STRATA_COMPONENTS_DIR>/harness`), starts one `dsh --profile web` process on a loopback port, +and talks to its Gateway. Nothing here downloads or builds anything. + +| File | Job | +| --- | --- | +| `harness-runtime.mjs` | locate the component, start/stop the process, scrub its environment, clean up a leftover process from a dead host | +| `gateway-client.mjs` | HTTP RPC plus the `remote.mux` WebSocket (`$events`, `session/follow`) | +| `profile.mjs` | generate the Harness profile: one route per ready local instance and per saved API connection; credential names only | +| `task-run.mjs` | a scheduled task as the agent | +| `events.mjs` | pure projection of Harness session events into the chat's NDJSON frames | +| `children.mjs` | pure projection of one helper agent's events into its row and its approval card | +| `preset.mjs` | the agent preset (which tools the chat has) | +| `plugins/strata-gate.mjs` | the Manual-mode approval gate (a Harness plugin, loaded by path) | +| `plugins/strata-search.mjs`, `plugins/strata-models.mjs` | the app's web search registered with the Harness; helper agents on a named model | +| `plugins/strata-context.mjs`, `context-budget.mjs`, `context-fit.mjs` | measured context pressure, summaries that fit the window, the check before a message goes out | +| `agent-bridge.mjs` | the chat-to-session map, turns, approvals, Stop, status | + +## Frames sent on `/api/chat/stream` for an agent turn + +`queued`, `start` (`agent:true`), `reasoning`, `delta`, `agent-tool` (upserts a tool card by call id with +`running | proposed | done | denied | error`), `done` (usage, `finishReason`, `cancelled`), `error`, and `notice` +(why a chat is not using the agent). The chat UI renders them with its existing components. + +## Routes + +- `GET /api/agent/status`: component, routes, active turns, pending approvals (no tokens, no keys) +- `POST /api/chat/approval {sessionId, toolId, decision: approve|deny}` +- `POST /api/chat/stop {sessionId}`: cancels that chat's Harness session and answers once the turn has ended +- `GET /api/agent/pending?chatId=` + +## Behaviour worth knowing + +- **Stop is per chat.** `session/cancel` is only an admission; the bridge waits for the durable `turn/end`. Stop before the + prompt reached the Harness cancels the start. The process is never killed to implement Stop. +- **A closed tab is not Stop.** The turn keeps running; an approval it needs stays pending until someone answers. +- **Resume.** The chat id maps to a Harness session id (`<data>/agent/sessions.json`). Reopening prompts that session; the + Harness resumes it from its own record, so nothing is replayed. (`session/create` with a started id returns a new + session, so it is never used for resume.) +- **Models.** Each chat sends its choice; the bridge calls `session/selectModel` for that route before the prompt. A route + that is gone is a typed `model-unavailable` error, never another model. Keys travel as environment variables named by + `apiKeyEnv`; the agent's shell does not inherit them, and logs are redacted. +- **No answerer, no hang.** The agent's own questions (`ask_user_question`) are declared unanswerable until the app has a + surface for them. +- **Fallback.** Without the component the host says so (`/api/agent/status`, a `notice` frame) and the chat runs on the + direct path with the model the user picked. + +## Modes (the Mode menu) + +The chat's Mode menu is real Harness behaviour. Each turn the page sends the chat's mode (`mode` in the `/api/chat/stream` body); before the prompt reaches the Harness the bridge puts that chat's session into the matching permission preset with the Harness's own `/permission` command (`commands/execute`), reads the `permissions` projection back, and refuses to start the turn (typed error `mode-unavailable`) if it does not match. The preset table is ours (profile entry `permission`). + +| Menu | Preset | Sandbox | Approval | What it means | +| --- | --- | --- | --- | --- | +| Manual (default) | `strata-manual` | open (`danger-full-access`) | `ask` | The Strata gate (`plugins/strata-gate.mjs`) asks BEFORE any change runs: one Approve/Deny card, nothing has happened when it appears, no blocked attempt, no sandbox or PowerShell error. Reads and read-only commands run without a question; anything the gate cannot prove read-only asks. | +| Plan | `strata-plan` | `read-only` | `never` | Nothing can change. A request is rejected without asking anyone, so no Approve card is shown; the card ends "Not allowed in this mode". | +| Bypass | `strata-bypass` | `danger-full-access` | `never` | Full access without prompts, as before. | + +- Manual relies on the gate, so a Manual turn does not start unless the bridge has confirmed the gate is loaded (`/strata-gate` command): without it Manual would be an open sandbox that nobody asks about. +- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked, each only with the options listed for it in `strata-gate.mjs` (an unknown option, or one that writes, runs a program, sets something or never ends, asks); MCP and unknown tools ask. +- Web search and web pages (`web_search`, `web_fetch`) ask once per chat in Manual, not once per call. The gate asks through the approval service itself (`webDecision`: "The assistant wants to search the web for: ... Search words go to <service>." / "... open the web page ..."), remembers a yes for the chat (a helper agent shares its chat's answer, and two searches started together share one card), and on a no gives the model `WEB_REFUSAL` ("The person did not allow web access ... Go on without it and say so."). Plan and Bypass are unchanged. Settings -> Tools has a switch, "Let the assistant search the web without asking" (off by default, `webWithoutAsking` in `tools-settings.mjs`, passed to the gate as `config.web.skipAsk`), that skips the question in Manual. A scheduled task has nobody at the card, so its web call is answered no unless that switch is on. Tests: `tests/web-ask.test.mjs`. +- The mode is read once per turn; an unknown or missing value is Manual. + +## Tools + +`preset.mjs` is the agent preset: the Harness `standard` preset minus the scheduler (Tasks is the only one), the agent's own question tool (no place to answer) and the Harness's plan mode. `tests/agent-tools.test.mjs` compares the list with the pinned Harness's own file, so a Harness update that adds or renames a plugin fails a test instead of silently dropping a tool. + +### Settings -> Tools + +What the person chose is saved by `tools-settings.mjs` (inside the host's settings file) and shown by `src/components/SettingsTools.tsx` (`GET/PUT /api/agent/tools`, `POST/PATCH/DELETE /api/agent/tools/custom[/id]`). A change reaches the agent from the next message: the profile carries a `toolsSignature`, and the bridge restarts the Harness (after the running turns end) when it differs. + +- Tool groups (`tools-catalog.mjs`): each is one switch in plain words and is one or more preset plugins (`withoutDisabled`); `fetch` and `search` are the two halves of the Harness's `tool-web` (both off drops it). Goals off: `/goal` answers that goals are turned off. +- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`), with Bing's plain result page (`../web-search-bing.mjs`) as the second source. Manners, because DuckDuckGo refuses a program that asks fast: a browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*), one request at a time per source, 2.5 to 4 s apart (random), at most 8 a minute, a 30 minute session cache per question, a cooldown after a refusal that doubles (1, 2, 4 ... 10 minutes, `Retry-After` honoured) during which that source gets no request, no lite-page follow-up after a refusal, one retry for a timeout or a 5xx, a 15 s limit. When every source refuses, the tool answers one plain sentence (`LIMITED_SENTENCE`: "Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings -> Tools -> Web search.") plus an instruction to the model not to retry; the turn guard in `agent-bridge.mjs` (see Turn guard) stops a model that retries anyway. **The results come from DuckDuckGo or Bing**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous. +- The browser: Playwright's MCP server (`@playwright/mcp`, staged next to the Harness by `apps/desktop/scripts/stage-harness.mjs`) on the person's own Chrome, Edge or Chromium (`browser-probe.mjs`), `--isolated` so it never sees their profile. Tools appear as `mcp__browser__browser_*`. In Manual, opening a page, clicking, typing, uploading, running a script in the page and closing tabs ask (plain reasons: "Open the web page ...", "Click on the page: ..."); looking (snapshot, screenshot, console, network, waiting, listing tabs) does not. Plan refuses every connected tool. The screen says plainly when no browser, or no tool server, is found. +- The person's own tools: `instructions` (the tool returns their text; look-only, never asks), `command` (runs their command with the assistant's text in the `STRATA_INPUT` environment variable, never spliced into the command line; asks in Manual, refused in Plan) and `server` (a web address or a program, added as `mcp__custom-<name>__*`; asks in Manual). Instruction and command tools are served by `custom-tools-mcp.mjs` (stdio MCP) from a JSON file the settings module rewrites on every change, so a switch in Settings is seen without a restart. +- `strata-gate.mjs` implements the Manual/Plan rules above (`planDecision`, `browserDecision`, the look-only instruction server). + +## Helper agents (subagents) + +- A Harness `subagent/catalog` event on the chat's session creates a row; `children.mjs` folds the helper's `session/follow` (address `{kind:'subagent', parentSessionId, childSessionId}`) into `{type:'agent', agent:{id,name,description,status,durationMs,tokens,updatedAt}}`, the shape the Subagents popover already reads. The delegation tools have no card. +- A helper's request for approval is the same card (state `proposed`, id `<helper session>:<call>`), answered with the same `/api/chat/approval`; a chat can only answer its own helpers. +- The run (the chat's one NDJSON response) stays open until the parent is idle, every helper has finished and reported back, and no armed goal is waiting; `done` is sent then. +- Stop: pauses an active goal, interrupts every helper (`subagents/interruptByParent`; `session/cancel` on a helper session is refused by the Harness), cancels the parent, waits; a report that would wake the parent afterwards is cancelled too. +- The number of helpers at once is the engine's request slots, with a floor of 4 for a local model and 8 for an API model (`maxActiveSubagents` in the profile). The Harness refuses more with a message the model reads. + +## /goal + +`/goal` typed in a chat goes to `bridge.goalCommand`: nothing = show the goal, `clear`, `pause`, `resume`, `edit <text>`, `complete`, anything else = a new goal (one unfinished goal at a time). Create/resume use the Harness goal Remotes (`goals/create|get|resume|pause|edit|clear|complete`); the Harness's goal driver runs the rounds and they stream into the chat ("Working on the goal…", with no step counter); the run ends when the goal stops (complete, paused, blocked, round limit - the default cap is the Harness's 256, a run with `maxRounds` is capped) and says how in plain words. After a restart an active goal stays disarmed until `/goal resume`. + +## Thinking and the output budget + +The Harness staging script (`apps/desktop/scripts/stage-harness.mjs`) applies Strata's guarded pi-ai 1.1.0 patch to its staged copy +(`harness-budget.mjs`, #3684): below 64K the context safety room is at most `min(4096, floor(contextWindow / 16))` and never more +than half the estimated remaining room, so an 8K window keeps output room after a tool result instead of ending with a one-token +cap. The caller's output cap and the one-token floor remain; windows of 64K or more keep the previous calculation. `BUNDLE.json.patches` +records the patch identity, the dependency version and the before/after SHA-256. Unknown dependency bytes stop staging for review. +Source and already-installed Harness copies are not changed. + +- A local route is reasoning-capable (`reasoning: true`) with `compat.thinkingFormat: 'chat-template'`: the request carries `chat_template_kwargs {enable_thinking, reasoning_effort}`, which the Strata server reads (a top-level `enable_thinking` is ignored by it, which is why pi-ai's `qwen` format left the model thinking). The chat's Reasoning menu travels as `thinking` in the stream body; the bridge sends it with `session/selectModel` (`reasoningEffort`) whenever the model or the level changed; a level a route does not have is dropped (never an error). API routes keep the provider default (the menu is disabled for them in the UI). +- `localOutputBudget(context)` is 30 percent of the window, at least 4096 and at most 32768 (9,830 tokens at 32K, 19,660 at 64K). The Harness's automatic compaction reads it as the room a reply reserves (the request header), and it is NOT the ceiling of a request: `plugins/strata-context.mjs` raises what the adapter sends to half the window, at most 64K tokens (`reply-cut.mjs` `replyCap`; pi-ai clamps it to the window minus the prompt), because a thinking model that writes a whole file in one call was cut inside the call at 19,660 and lost it (AGENT-LOST). A reply that is cut anyway is announced in the chat, the agent is asked to go on in smaller pieces (twice at most), and the file being written is streamed to the page as `agent-tool-draft` frames (name, size, lines, tail of the text). App-loaded models get `fit_max_tokens: true` so the engine clamps instead of answering 400. Sampling is not set here: the Harness sends none, so the server's own defaults apply. + +## Tasks + +`task-run.mjs` runs a scheduled task as the agent: a Harness session of its own (`task:<id>`, dropped after every run), the task's mode (`plan` default, `manual`, `bypass`), and a result built by `../task-report.mjs`. Nobody is at the screen: an approval request is answered "no" at once and reported ("Nothing was changed"). `server/tasks.mjs` stays the only scheduler; it sends a `task` event when a run ends (the page shows a toast). + +## Plain words + +Failures the person sees are plain sentences with a next step (`AgentUnavailable.message`); the technical text is in `.details` / the `details` field of error and notice frames, and in `/api/agent/status` `detail`. A failed tool's card result is a plain sentence followed by "Details: <original text>". + +## Tests + +`tests/agent-events.test.mjs` (pure), `tests/agent-tools-settings.test.mjs` (Settings -> Tools, web search, the browser and the person's own tools; the Harness-backed ones need STRATA_HARNESS_DIR and the browser one also Chrome or Edge), `tests/agent-bridge.test.mjs`, `tests/agent-modes.test.mjs` and `tests/agent-host.test.mjs` (need a built Harness: +`STRATA_HARNESS_DIR=<checkout>`, otherwise they skip and say so). The model in those tests is `tests/helpers/scripted-worker.mjs`. +`scripts/agent-flow.mjs` drives the real app in Chrome and takes screenshots. + +## Helper agents on a named model (`plugins/strata-models.mjs`, `model-routes.mjs`) + +The Harness's `subagent` tool takes an exact `provider` route key and model id. The profile enables the Harness's `subagent-model-selection-settings` with every route the app can reach (local instances and saved API models), and the `strata-models` plugin wraps the two tool definitions the Harness registers for each chat (`subagent`, `list_subagent_models`) in place: + +- the model is found from its id, `provider/id`, the name in the model picker, `connection name`, or "local" (any letters). A close guess is not started: the tool answers "Did you mean ...?" and nothing runs until the call is made again with that model. Several fits are listed; nothing fitting lists the models that can be used and says they can be added in Models. +- the tool's own text says when to use it ("ask a subagent", "ask model X"), not to look for the model with shell commands, and not to wait with sleep. The system prompt (`preset.mjs`) says the same, so it reaches every model, local or hosted. +- `list_subagent_models` lists the models by the names the person knows. + +If a Harness update renames those tools the wrapping does nothing and `tests/agent-subagent-models.test.mjs` (real Harness) fails. + +## Reasoning for API models + +A model on OpenRouter whose model list names `reasoning` in `supported_parameters` gets `reasoning: true` and the efforts `{off: none, low, medium, high, max: xhigh}` and the `openrouter` thinking format, so the Reasoning menu works and the choice reaches OpenRouter as `reasoning: { effort }`. Other API models keep the provider's own default (the menu stays greyed). + +## Pictures + +Pictures are on by default for every model that can read them: an API model reads them unless the person switched it off (Settings > Models > "Read pictures with this model") or its server says it cannot; a local model reads them when it was loaded with Read pictures (on by default). `src/lib/pictures.ts` is the one answer used by the composer and by Send; the agent route declares image input from the same flag. + +## Turn guard (`turn-guard.mjs`) + +A turn that keeps failing the same way is stopped by the app, never left to the model. + +- **Counted, from what the turn shows:** web searches that failed in a row (3), searches in one turn (10 in a plan turn, 25 otherwise), a plan turn that starts its numbered list from `1.` again (4 times), and a context of 93% or more (the Harness's own compaction did not keep up). +- **Stopped the way Stop stops** (`session/cancel`, helpers first) but ended as a normal turn (`done`, not cancelled, no error card), so the plan the model had written is still proposed. The plan card carries the reason (`plan.caution`); any other turn ends with one `delta` frame that has `own: true` and `key` (the English sentence, translated by the page; `GUARD_NOTES` are in the interface catalog in all eight languages). Each sentence says what happened and gives one next step. +- **Compaction:** after a guard stop (and after a turn the model server refused because the context was full) the bridge asks the Harness for `/compact` on that session, so the next message has room. Best effort and logged. +- **Never silent:** a turn that ends (`completed` or `max-tokens`) with no answer text gets "I ran out of room in this chat..." when the last request used 85% of the window or more, otherwise "I stopped without writing an answer..." (not when tool cards were shown, not after Stop, not after an error, which says why by itself). Goal runs have their own ending lines and are not guarded. +- Tests: `tests/agent-turn-guard.test.mjs` (counting, always; end to end with the real Harness, the scripted model's `searchloop` and `bloat` scripts and `searchMock: 'limited'` on the bridge, which runs the real search code on a pretend web that refuses, no network). + +## Context: measured pressure, summaries that fit, the check before a message goes out + +- **`plugins/strata-context.mjs`** (inserted by the profile, like the gate) wraps `tokenMeter.measure` and `llm.stream` in place, once each. Pressure = the last prompt size the model server reported for an answer, plus what changed since priced at the density that measurement showed (`context-budget.mjs`: `pressureNow`, `densityOf`); never lower than the Harness's own price. Node prices are scaled the same way, so the retained tail is in real tokens. A summary request (`purpose: 'compaction'`) that would not fit the window is asked for in pieces: a message bigger than a piece is cut for the request only, each piece builds on the summary before it, a piece the server refuses is halved and tried again. `/strata-context` (a Harness command, like `/strata-gate`) answers `{tokens, window}` for a session so the host can tell the person true figures. +- **`context-fit.mjs`**: before a message is sent the model server counts it (`POST /v1/messages/count_tokens`, its own tokenizer). `decideFit`: send; summarise first and then send (the message fits an otherwise empty chat); or never fits. The last one is not sent: the error frame has `code: 'CONTEXT_MESSAGE_TOO_LARGE'` and the page offers "Attach as a file" (`oversize.mjs`, `/api/chat/oversize`: the text is saved in the chat's folder, the assistant reads it in parts) or "Send a shortened preview". An engine that cannot count lets the message through; the Harness's own compact-and-retry is the net. +- **`/compact`** is handled by the host (`compactCommand`): the Harness's `/compact`, then a plain line with the measured figures ("The chat was 90% full and is now 38% full"), or "nothing older to summarize" when the newest message is what fills the chat. +- **Visible:** `compaction/start` shows "Summarizing earlier messages..." in the status line; `compaction/end` adds one plain line to the reply. The projector also sends a `context` frame after every model request, so the meter follows the running turn. +- **A refusal that is left** (`CONTEXT_WINDOW_EXCEEDED`) is a plain sentence with the engine's text under Details and the buttons "Summarize and continue" and "Start a new chat". "Try sending the message again" is for other errors only. +- Tests: `tests/agent-context.test.mjs` (arithmetic; the real Harness against the scripted worker with `window`, `charsPerToken` and `noCount`), `tests/oversize.test.mjs`, `tests/context-ui.test.mjs`. The run against a real engine is `scripts/context-e2e.mjs`. + +## History / older measurements + +- **Search refusals (2026-10):** on a real box two DuckDuckGo searches in 1.2 s answered, the third got HTTP 202, and every DuckDuckGo page refused for many minutes. + The pacing, cooldown and cache rules above come from that test. +- **Search-heavy `/plan` (2026-10):** every web search was refused, the model searched again and rewrote its plan after each one until the context reached 100%. + The turn ended with no answer and no message. The turn guard comes from that run. +- **Large log paste (2026-10-22, installed 0.2.1, Gyro-S, 64K):** a 118 KB log was 66,500 tokens to the engine and about 29,500 to the Harness + (4 characters a token; logs and code are about 2). The engine refused it with a 400. The refusal stayed in the history, so neither the next message nor `/compact` could + go through, because the summary request carried the same history. `/compact` was also not a command of the app yet: it went to the model as a question. This + produced `strata-context.mjs`, `context-fit.mjs` and the host's own `/compact`. +- **Output budget:** an earlier local budget of a quarter of the window, capped at 8192, cut big answers off at exactly 8192 tokens. diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index a9853b450c..42e0399ee3 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -1,1428 +1,1459 @@ -/** - * The agent bridge: Strata chats as Harness sessions. - * - * What it owns - * - the pinned Harness process (one, lazily started, restarted only when a route it needs changed); - * - the stable Strata-chat -> Harness-session map, persisted next to the host's other state; - * - one `session/follow` stream per live turn, projected into the NDJSON frames the chat UI renders; - * - approvals: the Harness `approval/request` waterfall in, the user's Approve/Deny back out; - * - Stop: `session/cancel` for exactly one session, resolved only once the turn has really ended. - * - * What it deliberately does not do - * - it never falls back to another model: a chat picks a route (local instance or saved API - * connection) and a missing route is a typed error; - * - it never implements Stop by killing the Harness (that would cancel every other chat); - * - it never holds a secret outside the environment of the agent process it starts. - */ -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; -import { join, resolve } from 'node:path'; -import { homedir, tmpdir } from 'node:os'; -import { fileURLToPath } from 'node:url'; -import { randomUUID } from 'node:crypto'; -import { GatewayClient } from './gateway-client.mjs'; -import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs'; -import { StatusReporter } from './status.mjs'; -import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf, localOutputBudget, compactionHeadroom } from './profile.mjs'; -import { TurnProjector, parseArguments as parseArgs } from './events.mjs'; -import { ChildProjector } from './children.mjs'; -import { nearestBudget } from './llm-shape.mjs'; -import { DeliverableTracker, ActivityGroups } from './deliverables.mjs'; -import { SkillsUsed, skillInfoFrom } from './skills-used.mjs'; -import { turnEngineSpeed } from './engine-speed.mjs'; -import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs'; -import { buildAnswer, parseQuestions } from './user-questions.mjs'; -import { BASE_TOKENS, COUNT_ABOVE_CHARS, FIT_TEXT, countTokens, decideFit, fill, grouped } from './context-fit.mjs'; -import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; - -/** - * A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical - * text for the Details disclosure (experts), already free of secrets. - */ -export class AgentUnavailable extends Error { - constructor(message, code = 'agent-unavailable', details = null) { super(message); this.name = 'AgentUnavailable'; this.code = code; this.details = details; } -} - -/** The plain sentence for a raw agent failure text, whatever produced it. */ -export function plainAgentFailure(raw) { - const text = String(raw ?? ''); - if (/did not print its address|exited during start|could not start|ECONNREFUSED.*127\.0\.0\.1|refused the launch token|socket/i.test(text)) return 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.'; - if (/process stopped|lost the session stream|stream did not open|session stream/i.test(text)) return 'The coding assistant stopped unexpectedly, so this answer is incomplete. Send your message again.'; - if (/did not accept the message/i.test(text)) return 'The coding assistant did not take this message. Send it again in a moment.'; - return text; -} - -/** - * A failure thrown while a turn starts, as `{ message, details, code }` for the chat's error card. The agent's own errors read like - * `session/create: tool-bash (...): waiting for shell ...` (a plugin chain that never started): never shown raw. The plain sentence - * goes in `message`; the technical text goes in `details`, which the app shows only behind Details. - */ -export function plainTurnFailure(err) { - const raw = String(err?.message ?? err ?? ''); - const details = typeof err?.details === 'string' && err.details ? err.details : raw; - if (err instanceof AgentUnavailable) return { message: err.message, details, code: err.code ?? 'AGENT_ERROR' }; - if (err?.code === 'agent-preset/invalid' || /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)|failed to import|did not activate/i.test(raw)) { - return { message: 'The coding assistant is missing a part it needs, so it cannot work on files yet. Close and reopen Strata. If it keeps happening, reinstall Strata. Chatting without tools still works.', details, code: 'AGENT_INCOMPLETE' }; - } - if (/^[a-z][a-z-]*\/[a-z][a-z-]*: /i.test(raw) || /^(gateway|rpc)/i.test(raw)) { - return { message: 'The coding assistant could not start this message. Try again. If it keeps happening, close and reopen Strata.', details, code: err?.code ?? 'AGENT_ERROR' }; - } - return { message: plainAgentFailure(raw), details, code: err?.code ?? 'AGENT_ERROR' }; -} - -/** The Harness's plugins start one after another: until they are all up, session/create answers "<plugin>: waiting for <service>". */ -const STARTING_UP = /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)/i; - -/** - * Create a Harness session, waiting for its plugins to finish starting. Right after the app opens (or the Harness restarts) the first - * message can arrive before they are up: that is retried every `retryMs` for up to `readyMs` (`onWait` tells the page "Starting the assistant…") - * instead of failing the first chat. Any other error is thrown at once; a start that never finishes is a plain AGENT_NOT_READY error - * with the Harness's text kept for Details. Returns null when `cancelled()` turns true while waiting. - */ -export async function createSessionWhenReady(create, { readyMs = 60_000, retryMs = 1_500, onWait = () => {}, cancelled = () => false, now = Date.now } = {}) { - const until = now() + readyMs; - for (;;) { - try { return await create(); } catch (e) { - const text = String(e?.message ?? e ?? ''); - if (!STARTING_UP.test(text)) throw e; - if (now() >= until) throw new AgentUnavailable('The assistant could not start. Try again in a moment.', 'AGENT_NOT_READY', text); - onWait(); - await new Promise(r => setTimeout(r, retryMs)); - if (cancelled()) return null; - } - } -} - -/** Attached pictures (data addresses) as the Harness's image prompt parts. */ -export function imageParts(images) { - return (Array.isArray(images) ? images : []).map(i => { - const m = /^data:(image\/(?:png|jpeg|webp));base64,(.+)$/.exec(String(i?.url ?? '')); - return m ? { type: 'image', mediaType: m[1], data: m[2], name: String(i.name ?? 'Picture').slice(0, 120) } : null; - }).filter(Boolean); -} - -/** A timer that never keeps the process alive by itself. */ -const after = (ms, fn) => { const t = setTimeout(fn, ms); t.unref?.(); return t; }; -/** The app's own host folder: never a place an answer's files can be (this file lives in <host>/server/agent). */ -const HOST_DIR = fileURLToPath(new URL('../..', import.meta.url)); - -const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; }; - -/** - * @param {object} options - * @param {string} options.dataDir the host's data directory (agent state lives in `<dataDir>/agent`) - * @param {string|null} [options.componentsDir] where installed components live - * @param {() => Array} options.localInstances ready local instances (see profile.mjs) - * @param {() => Array} options.connections saved API connections WITH their keys (host-internal) - * @param {() => (string|null)} [options.defaultLocalId] the local instance the chat runs on: its tool servers are the agent's (T5) - * @param {NodeJS.ProcessEnv} [options.env] - * @param {string} [options.nodePath] the Node runtime that runs the Harness - * @param {(line:string)=>void} [options.log] - */ -export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, defaultLocalId = () => null, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, engineProgress = () => null, engineGraceMs = 30 * 60_000, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000, sessionReadyMs = 60_000, sessionRetryMs = 1_500 }) { - const root = join(dataDir, 'agent'); - const home = join(root, 'home'); - const sessionsFile = join(root, 'sessions.json'); - mkdirSync(root, { recursive: true }); - - /** - * Where the turn's file tracker must never look (deliverables.mjs): the app, the engine and its components, Strata's own data, AppData - * and temp. `forbid` ones also switch tracking off when the chat's folder is one of them or inside one. - */ - function trackerFolders() { - const user = env.USERPROFILE ?? env.HOME ?? homedir(); - const forbid = [HOST_DIR, componentsDir, bundledDir].filter(Boolean); - const exclude = [dataDir, tmpdir(), env.LOCALAPPDATA, env.APPDATA, env.ProgramData, env.ProgramFiles, env['ProgramFiles(x86)'], env.TEMP, env.TMP, - join(user, 'AppData'), join(user, '.cache'), join(user, '.config'), join(user, '.local'), join(user, 'Library')].filter(Boolean); - return { forbid, exclude }; - } - - /** chatId -> { sessionId, cwd, createdAt } */ - let sessionMap = {}; - if (existsSync(sessionsFile)) { - try { sessionMap = JSON.parse(readFileSync(sessionsFile, 'utf8')) ?? {}; } catch { sessionMap = {}; } - } - const persist = () => { - const temp = `${sessionsFile}.${randomUUID()}.tmp`; - writeFileSync(temp, JSON.stringify(sessionMap, null, 2)); - renameSync(temp, sessionsFile); - }; - - /** @type {{hp:HarnessProcess, gw:GatewayClient, profile:object, clientId:string|null, generation:number, events:object}|null} */ - let rt = null; - let generation = 0; - let lastError = null; - let starting = null; - const chats = new Map(); // chatId -> { turn, route, routeGeneration } - const plans = new PlanStore(join(root, 'plans.json')); - /** chatId -> messages the person typed while a goal ran: [{ id, text, at, deliverAt }]; delivered between steps or when the goal ends */ - const queues = new Map(); - const queueView = chatId => (queues.get(chatId) ?? []).map(({ id, text, at, deliverAt }) => ({ id, text, at, deliverAt })); - const pending = new Map(); // `${sessionId}:${callId}` -> { eventId, sessionId, callId, at } - const questions = new Map(); // `${sessionId}:${callId}` -> the agent's own question waiting for the person: { eventId, sessionId, callId, items, at, clientId } (#4244) - const chatOfSession = sessionId => Object.keys(sessionMap).find(id => sessionMap[id]?.sessionId === sessionId) ?? null; - const idleWaiters = new Set(); - - const chat = id => { let c = chats.get(id); if (!c) { c = { id, turn: null, route: null, routeGeneration: -1 }; chats.set(id, c); } return c; }; - const activeTurns = () => [...chats.values()].filter(c => c.turn).length; - const notifyIdle = () => { if (activeTurns() === 0) { for (const w of idleWaiters) w(); idleWaiters.clear(); } }; - const waitIdle = (signal, ms) => new Promise((resolve, reject) => { - if (activeTurns() === 0) return resolve(); - const timer = setTimeout(() => { idleWaiters.delete(done); reject(new AgentUnavailable('Another chat is still working and the list of models changed. Try again when it finishes.', 'agent-busy')); }, ms); - const done = () => { clearTimeout(timer); resolve(); }; - idleWaiters.add(done); - signal?.addEventListener('abort', () => { clearTimeout(timer); idleWaiters.delete(done); reject(signal.reason ?? new Error('aborted')); }, { once: true }); - }); - - /** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */ - let shapeTargets = {}; - function buildProfileNow() { - const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock, defaultLocalId: defaultLocalId() }); - shapeTargets = profile.shapeTargets ?? {}; - return profile; - } - const llmTarget = key => shapeTargets[key] ?? null; - - function harnessInfo() { return resolveHarness({ env, componentsDir, bundledDir }); } - /** Where the agent component is (the browser tool server lives inside it), or null. */ - const harnessDir = () => { const h = harnessInfo(); return h.ok ? h.dir : null; }; - - /** The capability state the app shows. Never carries a token or a key. */ - function status() { - const h = harnessInfo(); - if (!h.ok) return { state: 'unavailable', reason: 'The coding assistant isn’t installed on this computer yet. Chat works without it.', detail: h.reason, code: 'component-missing' }; - const profile = buildProfileNow(); - return { - state: rt?.hp.running ? 'ready' : starting ? 'starting' : lastError ? 'error' : 'idle', - reason: lastError ? plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again.' : plainAgentFailure(lastError) : null, - detail: lastError ?? null, - harness: { version: h.version }, - runtime: rt?.hp.running ? { pid: rt.hp.pid, generation: rt.generation } : null, - routes: profile.routes.map(({ route, kind, modelId, name, contextWindow }) => ({ route, kind, modelId, name, contextWindow })), - // tool servers that could not be wired (a name the rule does not allow, no program or address): the chat says so - skippedServers: profile.mcpSkipped ?? [], - activeTurns: activeTurns(), - pendingApprovals: pending.size, - }; - } - - async function startRuntime(profile) { - const h = harnessInfo(); - if (!h.ok) throw new AgentUnavailable('The coding assistant isn’t installed on this computer yet. Chat works without it.', 'component-missing', h.reason); - mkdirSync(home, { recursive: true }); - const stale = stopStaleAgent(join(root, 'harness.pid')); - if (stale) log(`agent · stopped a leftover Harness process (pid ${stale}) from an earlier run`); - const patchFile = join(root, `profile-${profile.signature}.patch.yml`); - writeFileSync(patchFile, profile.patch); - const workdir = join(root, 'run'); - const hp = new HarnessProcess({ - harness: h, home, patchFile, cwd: workdir, env: profile.env, nodePath, logFile: join(root, 'harness.log'), pidFile: join(root, 'harness.pid'), - onExit: exit => { - log(`agent · the Harness process exited (code ${exit.code})`); - if (rt?.hp === hp) { lastError = 'The agent process stopped.'; rt = null; } - for (const c of chats.values()) c.turn?.abortFromRuntime('The agent process stopped before this turn finished.'); - }, - }); - const info = await hp.start({ timeoutMs: startTimeoutMs }); - const gw = new GatewayClient({ baseUrl: info.baseUrl, token: info.token }); - await gw.connect(); - const next = { hp, gw, profile, clientId: null, generation: ++generation, events: null }; - next.events = gw.openStream('$events', {}, { - onItem: value => onHostEvent(next, value), - onError: e => log(`agent · event stream: ${redact(e.message, Object.values(profile.env))}`), - }); - rt = next; - lastError = null; - log(`agent · Harness ${h.version ?? ''} ready (pid ${hp.pid}, ${profile.routes.length} route(s))`); - return next; - } - - /** The local engine's own speed for this turn's requests (null when it cannot be read: the stream's estimate stays). */ - async function engineSpeedOf(route, projector) { - const inst = localInstances().find(i => i.id === route.instanceId); - if (!inst) return null; - return turnEngineSpeed({ baseUrl: inst.baseUrl, key: inst.key, since: projector.startedAt, attempts: projector.streams.size, timeoutMs: 800 }); - } - - /** Make sure a runtime exists that knows the route this turn needs. */ - async function ensureRuntime(choice, signal) { - for (;;) { - if (starting) { await starting.catch(() => {}); continue; } - const profile = buildProfileNow(); - const route = routeFor(profile, choice); - if (!route) { - throw new AgentUnavailable(choice?.connectionId - ? 'This API model is no longer available. Choose another model in the chat picker.' - : 'No local model is ready for the agent. Load a model in Models, or choose an API model.', 'model-unavailable'); - } - const known = rt?.hp.running && rt.profile.toolsSignature === profile.toolsSignature && rt.profile.routes.some(r => r.route === route.route && r.modelId === route.modelId && r.fp === route.fp); - if (known) return { rt, route }; - starting = (async () => { - if (rt?.hp.running) { - await waitIdle(signal, 120_000); - const old = rt; rt = null; - old.events?.close(); old.gw.close(); await old.hp.stop(); - } - try { return await startRuntime(profile); } catch (e) { - lastError = redact(String(e.message ?? e), Object.values(profile.env)); - throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.' : plainAgentFailure(lastError), 'agent-start-failed', lastError); - } - })(); - try { await starting; } finally { starting = null; } - } - } - - function onHostEvent(runtime, value) { - if (value.type === 'ready') { runtime.clientId = value.clientId; return; } - if (value.type === 'waterfall' && value.event === 'approval/request') { - const r = value.request ?? {}; - if (!r.callId) return; - pending.set(`${value.agentId}:${r.callId}`, { eventId: value.eventId, sessionId: value.agentId, callId: r.callId, tool: r.toolName, reason: r.reason ?? null, at: Date.now(), clientId: runtime.clientId }); - } else if (value.type === 'waterfall' && value.event === 'user-questions/request') { - // The agent of a chat that is running in front of the person asks the person: the question goes to the page (the question card above the message box) and the - // Harness waits for the answer. Anything else (a helper's question, a chat that is stopping, a request with nothing to show) is declared - // unanswerable, which makes the tool return an error the model reads and carries on from, instead of a turn that waits forever. - const r = value.request ?? {}; - const chatId = chatOfSession(value.agentId); - const turn = chatId ? chats.get(chatId)?.turn : null; - const items = parseQuestions(r.questions); - // A goal or a plan step runs without anyone there: a question would stall it, so it is declined at once (the model reads "could not be answered" and goes on). - if (!turn || turn.finished || turn.stopping || turn.goalRun || turn.plan || !turn.announceQuestion || !items.length) { - void runtime.gw.answerEvent({ clientId: runtime.clientId, eventId: value.eventId, outcome: 'next' }).catch(() => {}); - } else { - const callId = String(r.wait?.callId ?? value.eventId); - questions.set(`${value.agentId}:${callId}`, { eventId: value.eventId, sessionId: value.agentId, callId, items, at: Date.now(), clientId: runtime.clientId }); - turn.announceQuestion({ type: 'agent-question', callId, questions: items }); - } - } else if (value.type === 'cancel') { - for (const [k, v] of questions) if (v.eventId === value.eventId) { questions.delete(k); chats.get(chatOfSession(v.sessionId))?.turn?.announceQuestion?.({ type: 'agent-question-end', callId: v.callId }); } - for (const [k, v] of pending) if (v.eventId === value.eventId) pending.delete(k); - } - } - - async function sessionFor(c, cwd, runtime, { onWait = () => {} } = {}) { - let known = sessionMap[c.id]; - // The chat's folder changed: the agent's working folder and sandbox are fixed when its session starts, so the chat gets a new session - // in the new folder (the earlier conversation is carried into its first message, as for any fresh session). - if (known && cwd && known.cwd && resolve(known.cwd) !== resolve(cwd)) { delete sessionMap[c.id]; persist(); known = null; } - if (known) return { sessionId: known.sessionId, fresh: false }; - const created = await createSessionWhenReady(() => runtime.gw.rpc('session/create', { request: { cwd } }), { readyMs: sessionReadyMs, retryMs: sessionRetryMs, onWait, cancelled: () => c.cancelStart }); - if (!created) return null; - sessionMap[c.id] = { sessionId: created.sessionId, cwd, createdAt: new Date().toISOString() }; - persist(); - return { sessionId: created.sessionId, fresh: true }; - } - - /** - * Put the session into the preset of the chat's mode, through the Harness's own `/permission` command, and - * check that it took. A turn never starts in a mode other than the one asked for: if the switch cannot be - * confirmed the turn fails closed with a typed error instead of running with unknown permissions. - */ - async function applyMode(runtime, sessionId, mode) { - const want = MODE_PRESETS[mode].key; - const read = async () => { - const r = await runtime.gw.rpc('session/projections', { request: { sessionId, keys: ['permissions'] } }); - return r?.values?.permissions?.currentValue ?? null; - }; - try { - if (await read() !== want) { - const done = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: `/permission ${want}`, submittedAttachments: [] }); - if (done?.result?.kind !== 'success') throw new Error(done?.result?.text ?? 'the agent did not recognise the command'); - const now = await read(); - if (now !== want) throw new Error(`the session reports "${now}" instead of "${want}"`); - } - } catch (e) { - throw new AgentUnavailable(`Strata could not set this chat to ${MODE_PRESETS[mode].name} mode, so nothing ran. Try again.`, 'mode-unavailable', e.message); - } - // Manual leaves the sandbox open and relies on the Strata gate to ask first. Without the gate it must not start. - if (mode === 'manual' && !runtime.gateChecked) { - try { - const probe = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-gate', submittedAttachments: [] }); - if (probe?.result?.kind !== 'success' || !String(probe.result.text ?? '').includes('strata-gate active')) throw new Error('the approval gate is not loaded'); - runtime.gateChecked = true; - } catch (e) { - throw new AgentUnavailable('Strata could not make sure the coding assistant asks before changing anything, so nothing ran. Close and reopen Strata, then try again.', 'mode-unavailable', e.message); - } - } - } - - /** - * Run one agent turn for a Strata chat and stream it as frames. - * `signal` means the client went away: the turn keeps running (that is not Stop). - */ - async function runTurn(options) { - const c = chat(options.chatId); - if (c.turn || c.starting) throw new AgentUnavailable('This chat is still working. Stop it or wait for it to finish.', 'turn-active'); - // From here until the Harness has the prompt, Stop has no session to cancel; it cancels the start. - c.starting = true; c.cancelStart = false; - try { return await runTurnInner(c, options); } finally { c.starting = false; } - } - - async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, thinkingBudget = 0, images = [], planTask = null, planRun = null, researchTopic = null }) { - let send = onFrame; let attached = true; - // A research run gathers first; what the assistant writes while gathering is notes, not the answer, so it is not shown. - let hideDeltas = !!researchTopic; - signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true }); - // What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary. - const written = { all: '', step: '' }; - // The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known. - let guard = null; - const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } }; - // What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends. - const tracker = new DeliverableTracker(workspacePath, trackerFolders()); - let toolsRan = false; // a turn that ran no tool wrote nothing, so there is nothing to look for at its end - try { tracker.snapshot(); } catch { /* a folder that cannot be read has no deliverables */ } - const groups = new ActivityGroups({ emit: raw }); - const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) }); - const emit = frame => { - if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (guard) trip(guard.text(frame.text)); if (hideDeltas) return; } - if (frame.own) { const { own, ...rest } = frame; frame = rest; } - if (frame.type === 'delta' && frame.text) groups.text(); - if (frame.type === 'agent-tool' && frame.tool) { - if (['done', 'error'].includes(frame.tool.state) && !['read', 'read_image', 'glob', 'grep', 'web_fetch', 'web_search'].includes(frame.tool.name)) toolsRan = true; - let made = null; - if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } } - raw(frame); - if (made) raw(made); - if (guard) trip(guard.card(frame.tool)); - groups.card(frame.tool, made); - skills.card(frame.tool); - return; - } - raw(frame); - }; - // What the assistant is doing right now, one small frame (status.mjs). Cleared before the final frame of the turn. - const reporter = new StatusReporter({ emit }); - - emit({ type: 'queued', requestId }); - reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' }); - const { rt: runtime, route } = await ensureRuntime(choice, signal); - const made = await sessionFor(c, workspacePath, runtime, { onWait: () => reporter.set({ phase: 'starting', code: 'assistant-starting', text: 'Starting the assistant…' }) }); - const { sessionId, fresh } = made ?? {}; - const cancelled = () => { reporter.clear(); emit({ type: 'done', finishReason: 'aborted', cancelled: true, tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0, model: route.name, contextMax: route.contextWindow }); return { cancelled: true }; }; - if (c.cancelStart || !made) return cancelled(); - - // The model and the chat's thinking level (the Reasoning menu) are sent to the Harness when either changed. A level the route does - // not have (an API model with its own vocabulary) is dropped and the model's own default stands: never an error for the person. - const level = effortOf(thinking ?? 'Medium'); // the menu's default is Medium - // Response settings the Harness cannot send itself (the thinking budget, the Expert sampling) go through this host's forwarding - // endpoint, on a copy of the route; with every setting at its default the route is used directly, as before. - const budget = level === 'off' ? 0 : nearestBudget(thinkingBudget); - const sampling = proxyBase && route.shaped ? expertSampling() : null; - const provider = route.shaped && (budget || sampling) ? route.shaped[budget] : route.route; - const wanted = `${provider}/${route.modelId}/${level ?? ''}`; - if (c.route !== wanted || c.routeGeneration !== runtime.generation) { - const select = effort => runtime.gw.rpc('session/selectModel', { request: { sessionId, provider, model: route.modelId, ...(effort ? { reasoningEffort: effort } : {}) } }); - try { - try { await select(level); } catch (e) { if (!level || e.code === 'session/not-found') throw e; await select(null); } - } catch (e) { - if (e.code === 'session/not-found') { delete sessionMap[c.id]; persist(); } - throw new AgentUnavailable(`The coding assistant could not use ${route.name}. Pick the model again and retry.`, 'model-unavailable', e.message); - } - c.route = wanted; c.routeGeneration = runtime.generation; - } - - // The chat's permission mode is read once, here, for this whole turn. A change the user makes while the - // turn runs applies to the next one, so a running turn never sees its permissions move under it. - const appliedMode = planTask ? 'plan' : modeOf(mode); - await applyMode(runtime, sessionId, appliedMode); - - // Does the message fit the model's window? Asked before anything is sent, with the model server's own count (context-fit.mjs). A message - // that fits once the older messages are a summary is sent after a summary; one that can never fit is not sent, and the person is told - // plainly and offered the two ways out. Whatever cannot be counted goes through: the Harness recovers from a refusal by itself. - if (!goal && route.kind === 'local') { - const fit = await fitCheck({ runtime, route, sessionId, fresh, history, message }).catch(() => null); - if (fit?.action === 'too-large') { - reporter.clear(); - const values = [grouped(fit.tokens), grouped(fit.window)]; - const text = fill(FIT_TEXT.tooLarge, values); - emit({ type: 'error', message: text, key: FIT_TEXT.tooLarge, values, code: 'CONTEXT_MESSAGE_TOO_LARGE', tokens: fit.tokens, window: fit.window }); - return { error: text }; - } - if (fit?.action === 'summarize') { - reporter.set({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] }); - const done = await compactChat(runtime, sessionId); - reporter.clear(); - if (done.ok) emit(summarizedNote(done.before, done.after, fit.window)); - } - } - - const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval, window: route.contextWindow }); - if (!goal) guard = new TurnGuard({ plan: !!planTask, contextMax: route.kind === 'local' ? route.contextWindow : 0 }); // a saved connection's window is often only assumed: never judged by a guess - projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); }; - const turn = { - sessionId, projector, route, requestId, live: false, lastSeq: -1, - ended: deferred(), follow: null, snapshot: deferred(), finished: false, prompted: false, stopBeforePrompt: false, - abortFromRuntime: reason => finishTurn(reason), finish: failure => finishTurn(failure), - // Helper agents (subagents) the Harness started for this chat, and the state of the run around them. - children: new Map(), subagentCalls: new Map(), parentOpen: false, stopping: false, settleTimer: null, mode: appliedMode, - plan: null, advancing: false, goalRun: false, lastActivity: Date.now(), heard: Date.now(), engineMark: null, watchdog: null, - research: researchTopic ? { phase: 'gather', nudged: false, waitingStart: false } : null, - }; - c.turn = turn; - /** - * A turn must always end. If the Harness sends nothing at all for a while (a tool that never returns, a model server that went - * quiet, a lost event) the turn is stopped and ended with a plain message instead of showing "thinking" forever. A running tool gets - * a longer allowance than a quiet model (a build can be silent for minutes). Whatever the assistant finished is kept. - */ - turn.watchdog = setInterval(() => { - if (turn.finished || turn.stopping) return; - const toolRunning = [...projector.tools.values()].some(x => x.card?.state === 'running' || x.card?.state === 'proposed') || pending.size > 0 && pendingFor(chatId).length > 0; - const limit = toolRunning ? stallToolMs : stallMs; - // A local engine reading a long prompt sends the Harness nothing for minutes (#3623). Its /metrics progress counts as activity, - // for at most engineGraceMs after the Harness last spoke: progress for another chat cannot keep a lost turn alive forever. - if (turn.route?.kind === 'local' && Date.now() - turn.heard < engineGraceMs) { - let mark = null; - try { mark = engineProgress(turn.route.instanceId); } catch { /* no progress known: the Harness alone decides */ } - if (mark != null && mark !== turn.engineMark) { turn.engineMark = mark; turn.lastActivity = Date.now(); return; } - } - if (Date.now() - turn.lastActivity < limit) return; - turn.stalledFor = Math.round((Date.now() - turn.lastActivity) / 1000); - turn.stopping = true; - void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); - for (const h of turn.children.values()) if (!h.done) void runtime.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: sessionId, mode: 'continuable' }).catch(() => {}); - const mins = Math.max(1, Math.round(turn.stalledFor / 60)); - turn.finish(`The assistant stopped answering for ${mins > 1 ? mins + ' minutes' : 'a minute'}, so I ended this turn. Anything it already finished is kept. Send your message again to go on.`); - }, Math.min(15_000, Math.max(200, Math.floor(stallMs / 4)))); - turn.watchdog.unref?.(); - async function finishTurn(failure) { - if (turn.finished) return; - turn.finished = true; - for (const [k, v] of questions) if (v.sessionId === turn.sessionId) questions.delete(k); - clearTimeout(turn.settleTimer); - clearInterval(turn.watchdog); - turn.follow?.close(); - for (const child of turn.children.values()) child.follow?.close(); - if (turn.stopping && !failure) projector.ended = turn.guard ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'user' } }; - reporter.clear(); - const extra = []; - try { if (toolsRan) for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ } - groups.end(); - if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); } - try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ } - // The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself). - let noteReason = turn.guard ?? null; - if (!noteReason && guard && !failure && !turn.stopping && !turn.goalRun) { - noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens }); - } - if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); } - for (const f of extra) emit(f); - // The answer speed of a turn on this computer is the engine's own (tokens it produced over its decode time, as the Monitor shows it). - const engine = !failure && route.kind === 'local' ? await engineSpeedOf(route, projector) : null; - const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow, engine }); - for (const f of frames.slice(0, -1)) emit(f); - // Messages typed while the goal ran and not delivered between steps go back to the page now, to be sent as ordinary messages. - if (turn.goalRun && attached) { - const left = queueView(chatId); - if (left.length) { queues.delete(chatId); onQueue(chatId, []); emit({ type: 'queued-release', messages: left.map(({ id, text }) => ({ id, text })) }); } - } - for (const f of frames.slice(-1)) emit(f); - c.turn = null; - turn.ended.resolve({ reason: projector.ended, failure: failure ?? null }); - notifyIdle(); - // A turn that filled the context, or that the guard stopped, leaves a long history behind: summarise the older part now so the next message has room. - if (noteReason === 'context' || noteReason === 'searches' || noteReason === 'searches-failed' || noteReason === 'rewrites' || /context window|too long|exceeds/i.test(String(projector.ended?.error?.message ?? ''))) void compactSession(runtime, sessionId); - } - - emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [], ...(planTask ? { planning: true } : {}) }); - - turn.follow = runtime.gw.openStream('session/follow', { request: { address: { kind: 'session', sessionId }, assistantStream: true } }, { - onItem: item => { - if (item.type === 'snapshot') { - if (turn.lastSeq < 0) turn.lastSeq = item.cursor; - else for (const r of item.records ?? []) if (r.type === 'event' && r.event.seq > turn.lastSeq) handle({ type: 'event', event: r.event }); - turn.snapshot.resolve(); - return; - } - handle(item); - }, - onError: e => finishTurn(`The agent lost the session stream: ${e.message}`), - }); - - /** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */ - function trip(reason) { - if (!reason || turn.guard || turn.finished || turn.stopping) return; - turn.guard = reason; - log(`agent · turn guard: ${reason} (searches ${guard?.searches ?? 0}, failed in a row ${guard?.failedInARow ?? 0}, plan rewrites ${guard?.rewrites ?? 0})`); - void stop(chatId).catch(() => {}); - } - - function handle(item) { - if (turn.finished) return; - turn.lastActivity = Date.now(); - turn.heard = turn.lastActivity; - if (item.type === 'event') { - const e = item.event; - if (e.seq <= turn.lastSeq) return; - turn.lastSeq = e.seq; - // The turn is ours from the user message that carries our request id. Until then an older, - // detached turn on the same session may still be finishing; its events are not ours. - if (!turn.live) { - if (e.type === 'user/message' && e.data?.source?.rpcId === requestId) turn.live = true; - return; - } - } else if (!turn.live) return; - for (const f of projector.consume(item)) emit(f); - if (guard && projector.contextTokens != null) trip(guard.context(projector.contextTokens)); - if (item.type === 'event') watchParent(item.event); - } - - // -- helper agents --------------------------------------------------------------------------------------- - - const rowFrame = child => ({ type: 'agent', agent: child.cp.agent() }); - const emitRow = (child, force = false) => { - const now = Date.now(); - if (!force && now - child.lastRow < 400) { child.rowPending = true; return; } - child.lastRow = now; child.rowPending = false; - emit(rowFrame(child)); - const working = [...turn.children.values()].filter(h => !h.done).length; - if (working && !turn.parentOpen) reporter.set({ phase: 'helpers', code: 'helpers', text: `Helpers are working (${working})…`, key: 'Helpers are working ({0})…', values: [working], args: { n: working } }); - }; - - function openChild(d) { - const id = d.childId; - if (!id || turn.children.has(id)) return; - const cp = new ChildProjector({ id, name: d.label || 'Helper' }); - const child = { id, cp, follow: null, noticed: false, done: false, lastRow: 0, rowPending: false, endedAt: 0 }; - turn.children.set(id, child); - emitRow(child, true); - const fold = item => { - if (turn.finished) return; - turn.lastActivity = turn.heard = Date.now(); - // A helper that finishes before its throttled "working" row went out would show queued -> completed and never "working": send the held row first. - if (item.type === 'event' && item.event.type === 'turn/end' && child.rowPending) emitRow(child, true); - const { frames, row } = cp.consume(item); - for (const f of frames) emit(f); - if (item.type === 'event' && item.event.type === 'turn/end') { child.done = true; child.endedAt = Date.now(); emitRow(child, true); armSettle(); return; } - if (item.type === 'event' && child.done && cp.status === 'working') { child.done = false; } - if (row) emitRow(child); - }; - child.follow = runtime.gw.openStream('session/follow', { - request: { address: { kind: 'subagent', parentSessionId: sessionId, childSessionId: id, mode: d.mode ?? 'unknown' }, assistantStream: true }, - }, { - onItem: item => { - if (item.type === 'snapshot') { for (const r of item.records ?? []) if (r.type === 'event') fold({ type: 'event', event: r.event }); return; } - fold(item); - }, - onError: e => { - log(`agent · helper stream ended: ${e.message}`); - if (!child.done) { child.done = true; child.endedAt = Date.now(); cp.status = 'failed'; cp.failure = 'Lost contact with this helper.'; cp.endedAt = Date.now(); emitRow(child, true); armSettle(); } - }, - }); - // A late reader still gets the final row: flush any row held back by the throttle. - child.flush = after(500, function tick() { if (!turn.finished && child.rowPending) emitRow(child, true); if (!turn.finished && !child.done) child.flush = after(500, tick); }); - } - - function watchParent(e) { - const d = e.data ?? {}; - switch (e.type) { - case 'turn/start': - turn.parentOpen = true; - if (turn.research) turn.research.waitingStart = false; - clearTimeout(turn.settleTimer); - // After Stop, a helper's report would start a new turn that nobody asked for. - if (turn.stopping) void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); - break; - case 'turn/end': - turn.parentOpen = false; - armSettle(); - break; - // The first turn of a prompt may have started before this follow stream attached (no turn/start seen): any step of the parent is proof that it is - // still working. Without this a helper that finished while the parent was still answering ended the run early ("The agent turn was interrupted"). - case 'step/start': - if (!turn.parentOpen) { turn.parentOpen = true; clearTimeout(turn.settleTimer); } - break; - case 'tool/call': - if (d.name === 'subagent' || d.name === 'subagent_fork') turn.subagentCalls.set(d.callId, parseArgs(d.arguments)); - break; - case 'subagent/catalog': - openChild(d); - break; - case 'tool/result': { - const call = turn.subagentCalls.get(d.message?.toolCallId); - const text = (d.message?.content ?? []).map(p => p.text ?? '').join(' '); - const started = /started subagent ([0-9a-f-]{36})/i.exec(text); - const child = started ? turn.children.get(started[1]) : null; - if (call && child) { child.cp.task = String(call.prompt ?? call.description ?? '').replace(/\s+/g, ' ').trim().slice(0, 140); emitRow(child, true); } - break; - } - case 'user/message': - if (d.source?.kind === 'goal' && Number.isInteger(d.source.round)) { turn.goalRound = d.source.round; void announceGoal(); } - // falls through - case 'agent/inbox/spliced': { - const hit = JSON.stringify(d); - if (!/Background subagent/.test(hit)) break; - for (const child of turn.children.values()) if (hit.includes(child.id)) child.noticed = true; - break; - } - default: - break; - } - } - - // -- plans and goal steps ---------------------------------------------------------------------------------- - - const planFrame = (event, plan, extra = {}) => ({ type: 'plan', event, plan: planView(plan), ...extra }); - const publishPlan = (event, plan) => { onPlan(chatId, event, planView(plan)); return planFrame(event, plan); }; - const stepFrame = (plan, index) => { - const st = plan.steps[index]; - return { type: 'plan-step', planId: plan.id, stepId: st.id, index: index + 1, total: plan.steps.length, state: st.state, text: st.text, summary: st.summary ?? null, line: stepLine(index, plan.steps.length, st.text, st.state === 'running' ? 'started' : st.state) }; - }; - const currentStep = plan => plan.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped'); - - /** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */ - function settlePlan(failure) { - if (planTask) { - if (failure || (turn.stopping && !turn.guard)) return []; - const parsed = parsePlan(written.all, planTask); - if (!parsed) return []; - const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask, ...(turn.guard ? { caution: GUARD_NOTES[turn.guard] } : {}) }); - return [publishPlan('proposed', plan)]; - } - const run = turn.plan; - if (!run) return []; - const plan = plans.get(chatId); - if (!plan || plan.id !== run.id) return []; - if (plan.state !== 'running') return []; - const out = []; - const at = currentStep(plan); - plans.update(chatId, p => { - if (at < 0) { p.state = 'done'; return; } - // The step that was running goes back to waiting, so Resume runs it again. - p.steps[at].state = 'pending'; - p.state = 'paused'; - }); - const updated = plans.get(chatId); - if (at >= 0) out.push(stepFrame(updated, at)); - out.push(publishPlan(updated.state === 'done' ? 'done' : 'paused', updated)); - return out; - } - - /** The goal the Harness runs for the plan's next waiting step, and the frames that say so. */ - async function startStep(plan, index) { - plans.update(chatId, p => { p.state = 'running'; p.goalStarted = true; p.steps[index].state = 'running'; }); - const now = plans.get(chatId); - await runtime.gw.rpc('goals/create', { agentId: sessionId, request: { objective: stepObjective(now, index) } }); - written.step = ''; written.stepAt = Date.now(); - emit(stepFrame(now, index)); - emit(publishPlan('step', now)); - const st = now.steps[index]; - reporter.set({ phase: 'goal', code: 'goal-step', text: stepLine(index, now.steps.length, st.text, 'started'), key: '{0}', values: [st.text], args: { step: index + 1, steps: now.steps.length } }); - } - - /** One goal step finished: say so, hand over queued messages, and begin the next step (or end the plan). */ - async function advancePlan() { - const run = turn.plan; - const plan = plans.get(chatId); - if (!run || !plan || plan.id !== run.id) return false; - const at = currentStep(plan); - if (at < 0) return false; - const cards = [...projector.tools.values()].filter(x => x.calledAt >= (written.stepAt ?? 0) - 50 && x.card?.state === 'done').map(x => x.card); - const summary = stepSummary(cards, written.step.split(/\n\s*\n/).filter(Boolean).at(-1) ?? written.step); - plans.update(chatId, p => { p.steps[at].state = 'done'; p.steps[at].summary = summary; }); - let now = plans.get(chatId); - emit(stepFrame(now, at)); - emit({ type: 'delta', own: true, text: `\n\n${stepLine(at, now.steps.length, now.steps[at].text, 'done')}\n` }); - const next = currentStep(now); - emit(publishPlan(next < 0 ? 'done' : 'step', next < 0 ? (plans.update(chatId, p => { p.state = 'done'; }), plans.get(chatId)) : now)); - await deliverQueued(at + 1); - if (turn.stopping || turn.finished) return true; - if (next < 0) return false; - // One step per turn (Time-skip): the plan stays open for the next step, which starts in a session of its own so the conversation never grows across steps. - if (run.once) { plans.update(chatId, p => { p.state = 'approved'; }); emit(publishPlan('step', plans.get(chatId))); return false; } - await startStep(plans.get(chatId), next); - void announceGoal(); - return true; - } - - /** Hand the person's queued messages to the assistant, one at a time, each answered before the next. */ - async function deliverQueued(afterStep) { - const list = queues.get(chatId) ?? []; - while (list.length && !turn.stopping && !turn.finished) { - const item = list.shift(); - if (!list.length) queues.delete(chatId); - onQueue(chatId, queueView(chatId)); - emit({ type: 'queued-message', state: 'delivered', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, afterStep, queue: queueView(chatId) }); - try { await runtime.gw.rpc('session/prompt', { request: { requestId: `queued-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: item.text }] } }); } - catch { emit({ type: 'queued-release', messages: [{ id: item.id, text: item.text }] }); continue; } - // Wait for the answer: the parent opens a turn for it and closes it again. - const t0 = Date.now(); - while (!turn.parentOpen && Date.now() - t0 < 4000 && !turn.finished) await new Promise(r => setTimeout(r, 50)); - while (turn.parentOpen && !turn.finished && !turn.stopping) await new Promise(r => setTimeout(r, 100)); - } - } - - /** - * The run is over when the parent is idle and every helper has finished and reported back. A helper's report - * wakes the parent a moment after the helper ends, so a helper that ended but has not reported yet keeps the run - * open (for a few seconds at most); after Stop nobody waits for reports. - */ - function armSettle() { - clearTimeout(turn.settleTimer); - if (turn.finished) return; - turn.settleTimer = after(turn.stopping ? 1200 : turn.children.size ? 600 : 0, async () => { - if (turn.finished || turn.parentOpen || turn.advancing) return; - const open = [...turn.children.values()]; - if (open.some(c => !c.done)) return; - if (!turn.stopping) { - if (open.some(c => !c.noticed && Date.now() - c.endedAt < 8000)) { armSettle(); return; } - // An armed goal starts its next round as soon as the agent is idle: the run is not over until the goal stops. - const current = await goalGet(); - if (turn.finished || turn.parentOpen) return; - if (current && current.phase === 'active' && current.activation === 'armed') { turn.settleTimer = after(700, armSettle); return; } - // Research: gather (search and read pages), then write the answer in the fixed shape. A step that did not open pages is sent back once. - if (turn.research && !turn.stopping) { - const r = turn.research; - if (r.waitingStart) { turn.settleTimer = after(300, armSettle); return; } - const opened = [...projector.tools.values()].filter(x => x.card?.name === 'web_fetch' && x.card.state === 'done').length; - const prompt = r.phase === 'write' ? null : (opened < 2 && !r.nudged) ? RESEARCH_NUDGE : researchWritePrompt(researchTopic); - if (prompt) { - if (prompt !== RESEARCH_NUDGE) { r.phase = 'write'; hideDeltas = false; written.all = ''; reporter.set({ phase: 'waiting', code: 'research-writing', text: 'Writing the answer…', key: 'Writing the answer…', values: [], args: {} }); } else r.nudged = true; - r.waitingStart = true; - try { await runtime.gw.rpc('session/prompt', { request: { requestId: `research-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }] } }); } - catch { r.waitingStart = false; hideDeltas = false; finishTurn(null); return; } - turn.settleTimer = after(500, armSettle); - return; - } - } - // A plan step's goal is complete: record it, deliver queued messages, start the next step. - if (turn.plan && current && current.phase === 'complete' && !turn.advancing) { - turn.advancing = true; - let more = false; - try { more = await advancePlan(); } catch (e) { emit({ type: 'delta', own: true, text: `\n\nThe plan stopped: ${plainGoalError(e)}\n` }); } - turn.advancing = false; - if (more && !turn.finished && !turn.stopping) { turn.settleTimer = after(700, armSettle); return; } - } - - if (turn.goalRun && current) { const line = goalEnding(current); if (line) emit({ type: 'delta', text: line }); } - if (turn.goalRun) await announceGoal(true); - } - finishTurn(null); - }); - } - const goalGet = () => runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined); - /** The goal's state to the page: a `goal` frame, the SSE event for the bar, and (while a round runs) the status line. */ - async function announceGoal(final = false) { - const view = await goalGet(); - if (turn.finished && !final) return; - const goal = goalObject(view, chatId); - emit({ type: 'goal', goal }); - onGoal(chatId, goal); - if (!final && goal && goal.phase === 'active' && turn.goalRound) reporter.set({ phase: 'goal', code: 'goal-step', text: 'Working on the goal…', args: { round: turn.goalRound, max: goal.maxRounds } }); - } - turn.announceGoal = announceGoal; - turn.announceQueue = frame => emit(frame); - turn.announceQuestion = frame => emit(frame); - - const snapshotTimer = {}; - await Promise.race([turn.snapshot.promise, new Promise((_, rej) => { snapshotTimer.t = after(20_000, () => rej(new Error('the session stream did not open'))); })]) - .catch(e => { finishTurn(e.message); }) - .finally(() => clearTimeout(snapshotTimer.t)); - if (turn.finished) return { error: true }; - if (turn.stopBeforePrompt || c.cancelStart) { projector.ended = { kind: 'aborted', reason: { kind: 'user' } }; finishTurn(null); return { cancelled: true }; } - - if (goal) { - // A goal run has no prompt of its own: the Harness's goal driver starts the rounds. Everything from now on is ours. - turn.live = true; turn.goalRun = true; - try { - if (planRun) { - const plan = plans.get(chatId); - if (!plan || plan.id !== planRun.planId) throw new AgentUnavailable('That plan is no longer there. Ask for a new one with /plan.', 'plan-gone'); - turn.plan = { id: plan.id, once: !!planRun.once }; - const at = currentStep(plan); - if (at < 0) throw new AgentUnavailable('Every step of this plan is already done.', 'plan-done'); - if (goal.action === 'resume' && plan.goalStarted) { - plans.update(chatId, p => { p.state = 'running'; p.steps[at].state = 'running'; }); - await startGoal(runtime, sessionId, goal); - emit(publishPlan('step', plans.get(chatId))); - } else await startStep(plan, at); - } else { - await startGoal(runtime, sessionId, goal); - } - } catch (e) { finishTurn(e instanceof AgentUnavailable ? e.message : plainGoalError(e)); return { error: true }; } - reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); - void announceGoal(); - } else { - let prompt = message; - if (fresh && history.length) prompt = withEarlierConversation(history, message); - try { - await runtime.gw.rpc('session/prompt', { request: { requestId, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }, ...imageParts(images)] } }); - } catch (e) { - finishTurn(`The agent did not accept the message: ${e.message}`); - return { error: true }; - } - } - if (!goal) reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); - turn.prompted = true; - if (turn.stopBeforePrompt) { - // Stop landed in the instant between 'prompt sent' and 'prompt accepted'. A cancel before the turn - // starts arms nothing, so wait for the turn to be ours, then cancel it. - for (let i = 0; i < 100 && !turn.live && !turn.finished; i++) await new Promise(r => setTimeout(r, 50)); - if (!turn.finished) await runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); - } - - // Wait for the turn, or for the client to leave. Leaving does not stop the turn. - const gone = new Promise(r => signal?.addEventListener('abort', () => r('detached'), { once: true })); - const outcome = await Promise.race([turn.ended.promise, gone]); - if (outcome === 'detached') return { detached: true, sessionId, ended: turn.ended.promise.then(r => ({ ...r, tokensOut: projector.tokensOut })) }; - return { sessionId, reason: outcome.reason, tokensIn: projector.tokensIn, tokensOut: projector.tokensOut }; - } - - // -- /goal ----------------------------------------------------------------------------------------------- - - /** Create or resume the chat's goal; the Harness's goal driver then runs the rounds by itself. */ - async function startGoal(runtime, sessionId, goal) { - if (goal.action === 'create') { - const request = { objective: goal.objective, ...(goal.maxRounds ? { maxGoalRounds: goal.maxRounds } : {}) }; - await runtime.gw.rpc('goals/create', { agentId: sessionId, request }); - return; - } - const current = await runtime.gw.rpc('goals/get', { agentId: sessionId }); - if (!current) throw new AgentUnavailable('There is no goal to continue. Start one with /goal followed by what you want done.', 'goal-none'); - await runtime.gw.rpc('goals/resume', { agentId: sessionId, ref: { id: current.id, revision: current.revision } }); - } - - async function pauseGoal(runtime, sessionId, chatId = null) { - try { - const current = await runtime.gw.rpc('goals/get', { agentId: sessionId }); - if (current && current.phase === 'active') { - await runtime.gw.rpc('goals/pause', { agentId: sessionId, ref: { id: current.id, revision: current.revision } }); - if (chatId) onGoal(chatId, goalObject(await runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined))); - } - } catch { /* no goal service, or nothing to pause */ } - } - - /** The goal as the page and the goal bar see it (notes-split-agent3.md), or null. */ - function goalObject(view, chatId = null) { - if (!view) return null; - const phase = ['active', 'paused', 'complete', 'blocked'].includes(view.phase) ? view.phase : 'blocked'; - // A goal that is running a plan (or the points of a goal) shows the plan's title and which step it is on. - const plan = chatId ? plans.get(chatId) : null; - const running = plan && plan.goalStarted && ['running', 'paused'].includes(plan.state) ? plan : null; - const at = running ? running.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped') : -1; - const step = running && at >= 0 ? { index: at + 1, total: running.steps.length, text: running.steps[at].text } : null; - return { objective: step ? running.title : String(view.objective ?? ''), ...(step ? { step } : {}), phase, round: view.roundsStarted ?? 0, maxRounds: view.maxGoalRounds ?? null, ...(phase === 'blocked' ? { blocked: plainBlocker(view.blockedReason) } : {}) }; - } - - /** The goal of a chat now, from the Harness (null: none, or the agent is not running). */ - async function goalState(chatId) { - const known = sessionMap[chatId]?.sessionId; - if (!known || !rt?.hp.running) return null; - return goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId); - } - - /** Pause, edit or remove the goal from the goal bar. Instant; resume runs rounds and goes through the chat stream. */ - async function goalControl({ chatId, action, text }) { - const known = sessionMap[chatId]?.sessionId; - if (!known || !rt?.hp.running) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none'); - const current = await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined); - if (!current) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none'); - const ref = { id: current.id, revision: current.revision }; - try { - if (action === 'pause') { if (current.phase === 'active') await rt.gw.rpc('goals/pause', { agentId: known, ref }); } - else if (action === 'clear') await rt.gw.rpc('goals/clear', { agentId: known, ref }); - else if (action === 'edit') { - const objective = String(text ?? '').trim().slice(0, 4000); - if (!objective) throw new AgentUnavailable('A goal needs a few words about what you want done.', 'goal-text'); - await rt.gw.rpc('goals/edit', { agentId: known, ref, request: { objective } }); - } else throw new AgentUnavailable('That goal action is not known.', 'goal-action'); - } catch (e) { throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainGoalError(e), 'goal-failed', e.message); } - if (action === 'clear') { const plan = plans.get(chatId); if (plan && ['running', 'paused'].includes(plan.state)) { plans.update(chatId, p => { p.state = 'stopped'; for (const st of p.steps) if (st.state === 'running') st.state = 'pending'; }); onPlan(chatId, 'stopped', planView(plans.get(chatId))); } } - const goal = action === 'clear' ? null : goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId); - onGoal(chatId, goal); - return { goal }; - } - - /** The goal's state in plain words. */ - function describeGoal(view) { - if (!view) return 'No goal is set. Start one with /goal followed by what you want done.'; - const what = `"${view.objective}"`; - if (view.phase === 'active') return `Working on the goal ${what}.`; - if (view.phase === 'paused') return `The goal ${what} is paused. Type /goal resume to go on.`; - if (view.phase === 'complete') return `The goal ${what} is complete.`; - return `The goal ${what} stopped: ${plainBlocker(view.blockedReason)}`; - } - - /** - * Handle a "/goal ..." line for a chat, as the Harness's own /goal command reads it: nothing = show the goal, - * clear, pause, resume, edit <text>, or any other text = a new goal. Starting or resuming runs the rounds and - * streams them like a chat turn (Stop pauses the goal); every other verb answers at once. - */ - async function goalCommand(options) { - const { chatId, line, onFrame } = options; - const text = String(line ?? '').trim(); - const verb = text.split(/\s+/)[0]?.toLowerCase() ?? ''; - const rest = text.slice(verb.length).trim(); - const say = reply => { - onFrame({ type: 'queued', requestId: `goal-${randomUUID()}` }); - onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); - onFrame({ type: 'delta', text: reply }); - onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); - return { goal: true }; - }; - if (tools()?.off?.has('goals')) return say('Goals are turned off. You can turn them back on in Settings, Tools.'); - const known = sessionMap[chatId]?.sessionId; - const quick = ['', 'clear', 'pause', 'edit', 'complete'].includes(verb) || (verb === 'status'); - let runtime = rt; - if (quick) { - if (!known || !runtime?.hp.running) return say(verb === '' || verb === 'status' ? describeGoal(null) : 'There is no goal in this chat yet.'); - const current = await runtime.gw.rpc('goals/get', { agentId: known }).catch(() => undefined); - const ref = current ? { id: current.id, revision: current.revision } : null; - try { - if (verb === '' || verb === 'status') return say(describeGoal(current)); - if (!ref) return say('There is no goal in this chat yet.'); - if (verb === 'clear') { await runtime.gw.rpc('goals/clear', { agentId: known, ref }); return say('The goal is cleared.'); } - if (verb === 'pause') { - if (current.phase === 'active') await runtime.gw.rpc('goals/pause', { agentId: known, ref }); - return say(describeGoal(await runtime.gw.rpc('goals/get', { agentId: known }))); - } - if (verb === 'complete') { await runtime.gw.rpc('goals/complete', { agentId: known, ref }); return say('The goal is marked complete.'); } - if (verb === 'edit') { - if (!rest) return say('Type /goal edit followed by the new wording of the goal.'); - await runtime.gw.rpc('goals/edit', { agentId: known, ref, request: { objective: rest } }); - return say(`The goal now reads: "${rest}".`); - } - } catch (e) { return say(plainGoalError(e)); } - } - if (verb === 'resume') { - const plan = plans.get(chatId); - const goalPlan = plan && plan.goalStarted && plan.state === 'paused' ? { planId: plan.id } : null; - return runTurn({ ...options, goal: { action: 'resume' }, ...(goalPlan ? { planRun: goalPlan } : {}) }); - } - // A goal whose own words hold numbered points ("1. ... 2. ... 3. ...") runs point by point, each one reported. - const points = parsePoints(text); - if (points) { - const plan = plans.create(chatId, { title: points.title, steps: points.steps, request: text, source: 'goal', state: 'approved' }); - onPlan(chatId, 'approved', planView(plan)); - return runTurn({ ...options, goal: { action: 'create', objective: text }, planRun: { planId: plan.id } }); - } - // Any other text is a new goal. One unfinished goal at a time (the Harness's rule): say so in plain words. - return runTurn({ ...options, goal: { action: 'create', objective: text } }); - } - - // -- /plan ----------------------------------------------------------------------------------------------- - - /** A short answer in the chat that the page translates (the sentence is in the interface catalog, "values" fill its slots). */ - function sayKey(options, template, values = []) { - const { onFrame } = options; - onFrame({ type: 'queued', requestId: 'compact-' + randomUUID() }); - onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); - onFrame({ type: 'delta', text: fill(template, values), key: template, values }); - onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); - return { compact: true }; - } - - /** A short answer in the chat (no model): the same frames a turn sends. */ - function sayOnce(options, reply) { - const { onFrame } = options; - onFrame({ type: 'queued', requestId: `plan-${randomUUID()}` }); - onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); - onFrame({ type: 'delta', text: reply }); - onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); - return { plan: true }; - } - - /** - * "/plan <what you want>": the assistant looks around (the chat is put in Plan mode for this turn, so nothing can change), writes the - * plan, and the host sends it as a `plan` frame. Nothing runs until the person approves it. - */ - async function planCommand(options) { - const task = String(options.line ?? '').trim(); - if (!task) { - const open = plans.get(options.chatId); - return sayOnce(options, open && ['proposed', 'approved'].includes(open.state) - ? 'A plan is waiting for you above. Approve it, edit it or reject it, or type /plan followed by something else to make a new one.' - : 'Type /plan followed by what you want done, for example: /plan build a small pagoda page. I will look around and write a plan; nothing changes until you approve it.'); - } - return runTurn({ ...options, message: planPrompt(task), planTask: task, mode: 'plan' }); - } - - /** - * "/research <topic>": the assistant searches the web, opens and reads pages, and writes a short structured answer (Summary, Key findings, - * Sources). The host also sends the sources as a `research` frame before the end of the turn. Needs web search turned on. - */ - async function researchCommand(options) { - const topic = String(options.line ?? '').trim(); - if (!topic) return sayOnce(options, 'Type /research followed by what you want to know, for example: /research how do heat pumps compare with gas boilers. I will search the web, read the pages and answer with sources.'); - if (tools()?.off?.has('search')) return sayOnce(options, 'Research needs web search, which is turned off. Turn it on in Settings, Tools (DuckDuckGo needs no key), then try again.'); - return runTurn({ ...options, message: researchPrompt(topic), researchTopic: topic }); - } - - const planGone = () => new AgentUnavailable('There is no plan waiting in this chat. Ask for one with /plan followed by what you want done.', 'plan-gone'); - function planOf(chatId, planId) { - const plan = plans.get(chatId); - if (!plan || (planId && plan.id !== planId)) throw planGone(); - return plan; - } - const mustBeOpen = plan => { if (plan.state !== 'proposed' && plan.state !== 'approved') throw new AgentUnavailable('This plan has already been used. Ask for a new one with /plan.', 'plan-used'); }; - - /** A short note added to every step of the chat's plan (the Time-skip B path: where its work comes from). */ - function setPlanBriefing(chatId, text) { plans.update(chatId, p => { p.briefing = String(text ?? '').slice(0, 600); }); } - - /** The plan of a chat, or null. */ - const planState = chatId => planView(plans.get(chatId)); - - /** Approve, edit or reject the plan; instant. Approve also returns the message that carries the plan out as an ordinary turn. */ - function planControl({ chatId, planId, action, steps, title }) { - const plan = planOf(chatId, planId); - if (action === 'edit') { - mustBeOpen(plan); - const next = editedSteps(steps, plan.steps); - const t = String(title ?? '').replace(/\s+/g, ' ').trim().slice(0, 80); - plans.update(chatId, p => { p.steps = next; if (t) p.title = t; p.state = 'proposed'; }); - onPlan(chatId, 'edited', planView(plans.get(chatId))); - return { plan: planView(plans.get(chatId)) }; - } - if (action === 'approve') { - mustBeOpen(plan); - plans.update(chatId, p => { p.state = 'approved'; }); - const approved = plans.get(chatId); - onPlan(chatId, 'approved', planView(approved)); - return { plan: planView(approved), prompt: planAsPrompt(approved) }; - } - if (action === 'reject') { - mustBeOpen(plan); - plans.update(chatId, p => { p.state = 'rejected'; }); - onPlan(chatId, 'rejected', planView(plans.get(chatId))); - return { plan: planView(plans.get(chatId)) }; - } - throw new AgentUnavailable('That plan action is not known.', 'plan-action'); - } - - /** "Start as goal": each step of the plan becomes a goal step, run one after another and reported. Streams like a chat turn. */ - async function planGoal(options) { - const { chatId, planId } = options; - let plan; - try { plan = planOf(chatId, planId); } catch (e) { return sayOnce(options, e.message); } - if (modeOf(options.mode) === 'plan') return sayOnce(options, 'Plan mode only looks, so it cannot carry out a plan. Switch this chat to Manual or Bypass, then start it again.'); - if (plan.state === 'paused' && plan.goalStarted) return goalCommand({ ...options, line: 'resume' }); - try { mustBeOpen(plan); } catch (e) { return sayOnce(options, e.message); } - if (tools()?.off?.has('goals')) return sayOnce(options, 'Goals are turned off. You can turn them back on in Settings, Tools.'); - plans.update(chatId, p => { p.state = 'approved'; }); - onPlan(chatId, 'approved', planView(plans.get(chatId))); - return runTurn({ ...options, goal: { action: 'create', objective: plan.title }, planRun: { planId: plan.id, once: options.once === true } }); - } - - /** A paused plan becomes open again (a step that did not finish is tried again in a fresh session). */ - function reopenPlan(chatId) { const p = plans.get(chatId); if (p && p.state === 'paused') { plans.update(chatId, x => { x.state = 'approved'; }); onPlan(chatId, 'approved', planView(plans.get(chatId))); } } - - /** Give up on one step with a plain note (a check that cannot be done here) so the rest of the plan can go on. */ - function skipStep(chatId, index, note) { plans.update(chatId, p => { const st = p.steps[index]; if (st) { st.state = 'skipped'; st.summary = String(note ?? 'Skipped.').slice(0, 140); } if (p.state === 'paused') p.state = 'approved'; }); onPlan(chatId, 'step', planView(plans.get(chatId))); } - - /** Forget the chat's agent session (not its plan): the next turn starts a fresh one in the same folder. */ - function resetSession(chatId) { - if (chats.get(chatId)?.turn || chats.get(chatId)?.starting) throw new AgentUnavailable('This chat is still working.', 'turn-active'); - delete sessionMap[chatId]; persist(); - } - - // -- the agent's own questions ------------------------------------------------------------------------------ - - /** - * The person's answer to a question the agent asked (#4244), or a skip. The answer is checked against the questions that were asked, then sent - * to the Harness as the result of the waiting `user-questions/request`; a skip declares the question unanswerable, as before, and the model - * carries on. - */ - async function answerQuestion({ chatId, callId, answers, skip = false }) { - const sessionId = sessionMap[chatId]?.sessionId; - const key = `${sessionId}:${callId}`; - const entry = questions.get(key); - if (!entry || !rt?.hp.running) throw new AgentUnavailable('That question was already answered, or the assistant has gone on.', 'question-gone'); - const outcome = skip ? 'next' : buildAnswer(entry.items, answers); - await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome }); - questions.delete(key); - return { ok: true, skipped: !!skip }; - } - - // -- a message for a helper --------------------------------------------------------------------------------- - - /** - * The person's own words for one helper (#4749), through the Harness's `subagents/prompt`: it delivers one browser-authored message to a - * continuable child through its live parent. "steer" reaches a working helper at its next step; "queue" gives a helper that has finished - * (or is between steps) a new turn. The Harness refuses a helper that cannot take messages (a one-shot one) and a parent that is not live; - * either comes back as a plain sentence. - */ - async function messageHelper({ chatId, helperId, text, delivery = 'queue' }) { - const clean = String(text ?? '').trim().slice(0, 8000); - if (!clean) throw new AgentUnavailable('Type a few words for the helper.', 'helper-empty'); - if (!/^[\w.:@-]{1,160}$/.test(String(helperId ?? ''))) throw new AgentUnavailable('That helper is not known.', 'helper-unknown'); - const parent = sessionMap[chatId]?.sessionId; - if (!parent || !rt?.hp.running) throw new AgentUnavailable('The assistant is not running in this chat, so it cannot pass a message on. Send a message in the chat first.', 'helper-idle'); - try { - const receipt = await rt.gw.rpc('subagents/prompt', { request: { requestId: `helper-${randomUUID()}`, parentSessionId: parent, childSessionId: String(helperId), mode: 'continuable', delivery: delivery === 'steer' ? 'steer' : 'queue', content: [{ type: 'text', text: clean }] } }); - return { ok: true, messageId: receipt?.messageId ?? null, delivery: delivery === 'steer' ? 'steer' : 'queue' }; - } catch (e) { - log(`agent · message for a helper refused: ${String(e?.message ?? e).slice(0, 200)}`); - throw new AgentUnavailable(/continuable|one-shot|not.*(found|live|open)|unavailable|closed|ended/i.test(String(e?.message ?? '')) ? 'This helper cannot take a message any more. Ask the assistant in the chat to start a new one.' : 'The message could not be delivered right now. Try again in a moment.', 'helper-refused'); - } - } - - // -- messages typed while a goal runs ---------------------------------------------------------------------- - - /** Queue a message for the running goal. It is delivered between steps, or handed back to the page when the goal ends or pauses. */ - function queueMessage({ chatId, text }) { - const turn = chats.get(chatId)?.turn; - if (!turn || !turn.goalRun || turn.stopping || turn.finished) throw new AgentUnavailable('No goal is running in this chat, so there is nothing to queue behind. Send the message as usual.', 'queue-idle'); - const clean = String(text ?? '').trim().slice(0, 8000); - if (!clean) throw new AgentUnavailable('Type a few words to queue.', 'queue-empty'); - const list = queues.get(chatId) ?? []; - if (list.length >= 20) throw new AgentUnavailable('Twenty messages are already waiting. Wait for some to be delivered.', 'queue-full'); - const item = { id: randomUUID(), text: clean, at: new Date().toISOString(), deliverAt: turn.plan ? 'step' : 'end' }; - list.push(item); queues.set(chatId, list); - const message = { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }; - onQueue(chatId, queueView(chatId)); - turn.announceQueue?.({ type: 'queued-message', state: 'queued', message, queue: queueView(chatId) }); - return { message, queue: queueView(chatId) }; - } - - /** Take a queued message back (the x on it). A message already being delivered cannot be taken back. */ - function cancelQueued({ chatId, id }) { - const list = queues.get(chatId) ?? []; - const at = list.findIndex(m => m.id === id); - if (at < 0) throw new AgentUnavailable('That message was already sent or removed.', 'queue-gone'); - const [item] = list.splice(at, 1); - if (!list.length) queues.delete(chatId); - onQueue(chatId, queueView(chatId)); - chats.get(chatId)?.turn?.announceQueue?.({ type: 'queued-message', state: 'cancelled', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, queue: queueView(chatId) }); - return { queue: queueView(chatId) }; - } - - /** Messages waiting for a chat, and (after a goal ended while the page was away) the ones it should now send. */ - function takeQueue(chatId, { release = false } = {}) { - const turn = chats.get(chatId)?.turn; - const list = queueView(chatId); - if (release && !turn && list.length) { queues.delete(chatId); onQueue(chatId, []); return { queue: [], released: list.map(({ id, text }) => ({ id, text })) }; } - return { queue: list, released: [] }; - } - - /** - * The person changed the chat's mode while a turn (a goal and its helpers included) is running. The new preset - * is put on the session at once, the running turn's own bookkeeping follows, and questions already waiting are - * settled the way the new mode would have settled them: Bypass allows them, Plan rejects them. - */ - async function setMode(chatId, mode) { - const want = modeOf(mode); - const c = chats.get(chatId); - const sessionId = sessionMap[chatId]?.sessionId; - if (!rt || !sessionId) return { applied: false, mode: want, reason: 'no session yet' }; - if (c?.turn && c.turn.mode === want) return { applied: true, mode: want, settled: 0 }; - await applyMode(rt, sessionId, want); - let settled = 0; - if (c?.turn) { - c.turn.mode = want; - c.turn.projector.policy = MODE_PRESETS[want].approval; - if (want !== 'manual') { - const helpers = c.turn.children; - for (const [key, entry] of [...pending.entries()]) { - if (entry.sessionId !== sessionId && !helpers?.has(entry.sessionId)) continue; - pending.delete(key); - try { await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: want === 'bypass' ? 'allowed-once' : 'rejected' }); settled++; } catch { /* already answered */ } - } - } - } - return { applied: true, mode: want, settled }; - } - - /** Answer one pending approval. `decision` is `approve` or `deny`. */ - async function approve({ chatId, callId, decision }) { - const sessionId = sessionMap[chatId]?.sessionId; - // A helper agent's question carries the helper's session id in front of its call id. Only a helper that belongs to - // THIS chat's run can be answered from this chat. - const [maybeChild] = String(callId).split(':'); - const ownHelper = callId.includes(':') && chats.get(chatId)?.turn?.children.has(maybeChild); - const key = ownHelper ? callId : `${sessionId}:${callId}`; - // The durable `approval/asked` (which makes the card say "needs approval") and the waterfall frame - // (which makes it answerable) travel on different streams; a fast click can beat the second one. - let entry = sessionId ? pending.get(key) : null; - for (let i = 0; !entry && sessionId && i < 40; i++) { - await new Promise(r => setTimeout(r, 50)); - entry = pending.get(key); - } - if (!entry) throw new AgentUnavailable('That question is no longer waiting for an answer.', 'approval-gone'); - if (!rt?.hp.running) throw new AgentUnavailable('That question expired because the coding assistant restarted. Ask again.', 'approval-gone'); - pending.delete(key); - try { - await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: decision === 'approve' ? 'allowed-once' : 'rejected' }); - } catch (e) { - throw new AgentUnavailable('Your answer could not be delivered. Ask again.', 'approval-gone', e.message); - } - return { ok: true }; - } - - /** - * Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the - * Harness acknowledges a cancel as admitted, not as done. - */ - /** What the chat holds now and the model's window, as the context plugin measures them (null when it cannot be read). */ - async function contextOf(runtime, sessionId) { - try { - const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-context', submittedAttachments: [] }); - if (r?.result?.kind !== 'success') return null; - const v = JSON.parse(String(r.result.text)); - return Number.isFinite(v.tokens) ? { tokens: Math.round(v.tokens), window: Number(v.window) > 0 ? Math.round(v.window) : 0 } : null; - } catch { return null; } - } - - /** The decision of context-fit.mjs for the message about to be sent, or null when the model server cannot count it. */ - async function fitCheck({ runtime, route, sessionId, fresh, history, message }) { - const inst = localInstances().find(i => i.id === route.instanceId); - if (!inst || !(route.contextWindow > 0)) return null; - const carried = fresh && history.length ? withEarlierConversation(history, message) : message; - if (carried.length < COUNT_ABOVE_CHARS) return null; - const count = text => countTokens({ baseUrl: inst.baseUrl, key: inst.key, model: inst.modelId, text }); - let tokens = await count(carried); - if (tokens == null) return null; - const now = fresh ? null : await contextOf(runtime, sessionId); - const window = now?.window || route.contextWindow; - const pressure = now?.tokens ?? 0; - // Where the Harness starts summarising by itself on this window (profile.mjs: the reply keeps its room, then the headroom). - const reply = localOutputBudget(window); - const threshold = Math.floor(Math.min(window * 0.8, window - reply - compactionHeadroom(window, reply))); - let verdict = decideFit({ window, pressure, messageTokens: tokens, threshold }); - // The earlier conversation carried into a fresh session is what pushed it over: send the message alone instead. - if (verdict.action === 'too-large' && carried !== message) { - const alone = await count(message); - if (alone != null) { tokens = alone; verdict = decideFit({ window, pressure, messageTokens: alone, threshold }); } - } - return { ...verdict, tokens, window, pressure }; - } - - /** - * Summarise the older part of a chat with the Harness's /compact and say what happened. Never throws. - * ok:true carries the figures before and after; ok:false says why (nothing to summarise, busy, failed). - */ - async function compactChat(runtime, sessionId) { - const before = await contextOf(runtime, sessionId); - let result; - try { result = (await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }))?.result; } - catch (e) { return { ok: false, reason: /not.found|no such/i.test(String(e.message)) ? 'nothing' : 'failed', before, text: String(e.message ?? e) }; } - const text = String(result?.text ?? ''); - log('agent · compact: ' + (result?.kind ?? 'none') + ' ' + text.slice(0, 140)); - if (result?.kind === 'success' && /^Compacted/i.test(text)) return { ok: true, before, after: await contextOf(runtime, sessionId) }; - if (result?.kind === 'success') return { ok: false, reason: 'nothing', before, text }; - if (/active compaction|not idle/i.test(text)) return { ok: false, reason: 'busy', before, text }; - // The Harness cannot make a summary smaller than what is left when the chat holds little beyond its first prompt: that is nothing to summarise, not a failure. - const little = before && before.window > 0 && before.tokens - BASE_TOKENS < before.window * 0.25; - return { ok: false, reason: little && /useful summary|not smaller/i.test(text) ? 'nothing' : 'failed', before, text }; - } - - /** The line in the chat that explains why the context meter fell: how full it was and how full it is. */ - function summarizedNote(before, after, window) { - const w = after?.window || before?.window || window || 0; - const pct = v => Math.max(0, Math.min(100, Math.round(100 * v.tokens / w))); - const known = w > 0 && before && after; - const template = known ? FIT_TEXT.summarized : FIT_TEXT.summarizedShort; - const values = known ? [pct(before), pct(after)] : []; - return { type: 'delta', own: true, text: '\n\n' + fill(template, values), key: template, values, noteReason: 'compacted' }; - } - - /** "/compact": summarise the older messages of this chat now, and say in plain words what happened. */ - async function compactCommand(options) { - const { chatId, choice, signal } = options; - const c = chat(chatId); - const say = (template, values = []) => sayKey(options, template, values); - if (c.turn || c.starting) return say(FIT_TEXT.compactBusy); - const known = sessionMap[chatId]?.sessionId; - if (!known) return say(FIT_TEXT.noChatYet); - let runtime; - try { ({ rt: runtime } = await ensureRuntime(choice, signal)); } catch { return say(FIT_TEXT.compactFailed); } - const done = await compactChat(runtime, known); - if (done.ok) { - const note = summarizedNote(done.before, done.after, 0); - return say(note.key, note.values); - } - if (done.reason === 'busy') return say(FIT_TEXT.compactBusy); - if (done.reason === 'nothing') { - const w = done.before?.window || 0; - const pct = w > 0 && done.before ? Math.round(100 * done.before.tokens / w) : 0; - return say(pct >= 60 ? FIT_TEXT.nothingFull : FIT_TEXT.nothingToSummarize, pct >= 60 ? [pct] : []); - } - return say(FIT_TEXT.compactFailed); - } - - /** Summarise the older part of a session with the Harness's own /compact. Best effort: the next message compacts again by itself when it must. */ - async function compactSession(runtime, sessionId) { - try { - const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }); - log(`agent · compact after a stopped turn: ${r?.result?.kind ?? 'done'} ${String(r?.result?.text ?? '').slice(0, 120)}`); - } catch (e) { log(`agent · compact after a stopped turn failed: ${e.message}`); } - } - - async function stop(chatId, { waitMs = 20_000 } = {}) { - const c = chats.get(chatId); - const turn = c?.turn; - if (!turn && c?.starting) { c.cancelStart = true; return { stopped: true, ended: 'cancelled-before-start', ms: 0 }; } - if (!turn || !rt) return { stopped: false, reason: 'no active turn' }; - const t0 = Date.now(); - if (!turn.prompted) { - // The Harness has not been given the prompt yet, so there is nothing to cancel there. - turn.stopBeforePrompt = true; - const early = await Promise.race([turn.ended.promise, new Promise(r => setTimeout(() => r(null), 100))]); - if (early) return { stopped: true, ended: early.reason?.kind ?? 'aborted', ms: Date.now() - t0 }; - } - turn.stopping = true; - await pauseGoal(rt, turn.sessionId, chatId); - // Helpers first: a helper still working would otherwise report back and wake the parent again. - await Promise.allSettled([...turn.children.values()].filter(h => !h.done).map(h => rt.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: turn.sessionId, mode: 'continuable' }))); - await rt.gw.rpc('session/cancel', { request: { sessionId: turn.sessionId } }).catch(e => { if (turn.parentOpen) throw e; }); - // Nothing is running in the parent (it was waiting for its helpers): the run ends once they are all down. - if (!turn.parentOpen) { clearTimeout(turn.settleTimer); turn.settleTimer = after(300, () => { if (!turn.finished && !turn.parentOpen && [...turn.children.values()].every(h => h.done)) turn.finish(null); }); } - let timer; const result = await Promise.race([turn.ended.promise, new Promise(r => { timer = after(waitMs, () => r(null)); })]); - clearTimeout(timer); - if (!result) return { stopped: false, pending: true, reason: 'the turn is still stopping' }; - return { stopped: true, ended: result.reason?.kind ?? 'unknown', ms: Date.now() - t0 }; - } - - function pendingFor(chatId) { - const sessionId = sessionMap[chatId]?.sessionId; - const helpers = chats.get(chatId)?.turn?.children; - return [...pending.values()].filter(p => p.sessionId === sessionId || helpers?.has(p.sessionId)) - .map(p => (p.sessionId === sessionId ? p : { ...p, callId: `${p.sessionId}:${p.callId}` })).map(({ callId, tool, reason, at }) => ({ callId, tool, reason, at })); - } - - /** Every chat that has an approval waiting, for the task board: the chat, its working folder and what is waiting (same items as pendingFor). */ - function pendingAll() { - if (!pending.size) return []; - return Object.keys(sessionMap).map(chatId => ({ chatId, folder: sessionMap[chatId]?.cwd ?? null, pending: pendingFor(chatId) })).filter(c => c.pending.length); - } - - async function close() { - const r = rt; rt = null; - if (r) { r.events?.close(); r.gw.close(); await r.hp.stop(); } - } - - /** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */ - function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); } - - return { compactCommand, messageHelper, answerQuestion, goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, llmTarget, setPlanBriefing, resetSession, reopenPlan, skipStep, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, pendingAll, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, workingFolder: chatId => sessionMap[chatId]?.cwd ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) }; -} - -/** A goal that stopped by itself, in words. */ -export function plainBlocker(reason) { - if (!reason) return 'it could not go on.'; - if (reason.code === 'round-limit') return 'it worked for the most steps it was allowed. Type /goal clear, then start a new goal to go on.'; - return String(reason.message ?? 'it could not go on.'); -} - -/** What a goal run says when it ends. */ -export function goalEnding(view) { - if (view.phase === 'complete') return '\n\n*The goal is complete.*'; - if (view.phase === 'blocked') return `\n\n*The goal stopped: ${plainBlocker(view.blockedReason)}*`; - if (view.phase === 'paused') return '\n\n*The goal is paused. Type /goal resume to go on.*'; - return ''; -} - -/** A goal request the Harness refused, as a sentence. */ -export function plainGoalError(e) { - const message = String(e?.message ?? e); - if (/already|unfinished|current goal/i.test(message)) return 'This chat already has a goal that is not finished. Type /goal edit to change it, /goal clear to remove it, or /goal to see it.'; - if (/GOAL_NONE|no goal/i.test(message) || e?.code === 'goal-none') return 'There is no goal to continue. Start one with /goal followed by what you want done.'; - if (/objective/i.test(message)) return 'A goal needs a few words about what you want done, for example: /goal make every test pass.'; - return 'The goal could not be changed right now. Try again in a moment.'; -} - -/** The Harness session of a chat that existed before the agent did knows nothing; carry a bounded summary. */ -export function withEarlierConversation(history, message) { - const rows = history.filter(m => (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim()).slice(-12); - if (!rows.length) return message; - const text = rows.map(m => `${m.role}: ${m.content.length > 1500 ? `${m.content.slice(0, 1499)}…` : m.content}`).join('\n'); - return `Earlier in this conversation, before you were given tools:\n${text}\n\nCurrent message:\n${message}`; -} +/** + * The agent bridge: Strata chats as Harness sessions. + * + * What it owns + * - the pinned Harness process (one, lazily started, restarted only when a route it needs changed); + * - the stable Strata-chat -> Harness-session map, persisted next to the host's other state; + * - one `session/follow` stream per live turn, projected into the NDJSON frames the chat UI renders; + * - approvals: the Harness `approval/request` waterfall in, the user's Approve/Deny back out; + * - Stop: `session/cancel` for exactly one session, resolved only once the turn has really ended. + * + * What it deliberately does not do + * - it never falls back to another model: a chat picks a route (local instance or saved API + * connection) and a missing route is a typed error; + * - it never implements Stop by killing the Harness (that would cancel every other chat); + * - it never holds a secret outside the environment of the agent process it starts. + */ +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { homedir, tmpdir } from 'node:os'; +import { fileURLToPath } from 'node:url'; +import { randomUUID } from 'node:crypto'; +import { GatewayClient } from './gateway-client.mjs'; +import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs'; +import { StatusReporter } from './status.mjs'; +import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf, localOutputBudget, compactionHeadroom } from './profile.mjs'; +import { TurnProjector, parseArguments as parseArgs } from './events.mjs'; +import { ChildProjector } from './children.mjs'; +import { nearestBudget } from './llm-shape.mjs'; +import { DeliverableTracker, ActivityGroups } from './deliverables.mjs'; +import { SkillsUsed, skillInfoFrom } from './skills-used.mjs'; +import { turnEngineSpeed } from './engine-speed.mjs'; +import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs'; +import { cutNotice, cutNudge } from './reply-cut.mjs'; + +/** How often one turn asks the agent to carry on after a reply the length limit cut (each time in smaller pieces). */ +export const MAX_CUT_RETRIES = 2; +import { buildAnswer, parseQuestions } from './user-questions.mjs'; +import { BASE_TOKENS, COUNT_ABOVE_CHARS, FIT_TEXT, countTokens, decideFit, fill, grouped } from './context-fit.mjs'; +import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; + +/** + * A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical + * text for the Details disclosure (experts), already free of secrets. + */ +export class AgentUnavailable extends Error { + constructor(message, code = 'agent-unavailable', details = null) { super(message); this.name = 'AgentUnavailable'; this.code = code; this.details = details; } +} + +/** The plain sentence for a raw agent failure text, whatever produced it. */ +export function plainAgentFailure(raw) { + const text = String(raw ?? ''); + if (/did not print its address|exited during start|could not start|ECONNREFUSED.*127\.0\.0\.1|refused the launch token|socket/i.test(text)) return 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.'; + if (/process stopped|lost the session stream|stream did not open|session stream/i.test(text)) return 'The coding assistant stopped unexpectedly, so this answer is incomplete. Send your message again.'; + if (/did not accept the message/i.test(text)) return 'The coding assistant did not take this message. Send it again in a moment.'; + return text; +} + +/** + * A failure thrown while a turn starts, as `{ message, details, code }` for the chat's error card. The agent's own errors read like + * `session/create: tool-bash (...): waiting for shell ...` (a plugin chain that never started): never shown raw. The plain sentence + * goes in `message`; the technical text goes in `details`, which the app shows only behind Details. + */ +export function plainTurnFailure(err) { + const raw = String(err?.message ?? err ?? ''); + const details = typeof err?.details === 'string' && err.details ? err.details : raw; + if (err instanceof AgentUnavailable) return { message: err.message, details, code: err.code ?? 'AGENT_ERROR' }; + if (err?.code === 'agent-preset/invalid' || /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)|failed to import|did not activate/i.test(raw)) { + return { message: 'The coding assistant is missing a part it needs, so it cannot work on files yet. Close and reopen Strata. If it keeps happening, reinstall Strata. Chatting without tools still works.', details, code: 'AGENT_INCOMPLETE' }; + } + if (/^[a-z][a-z-]*\/[a-z][a-z-]*: /i.test(raw) || /^(gateway|rpc)/i.test(raw)) { + return { message: 'The coding assistant could not start this message. Try again. If it keeps happening, close and reopen Strata.', details, code: err?.code ?? 'AGENT_ERROR' }; + } + return { message: plainAgentFailure(raw), details, code: err?.code ?? 'AGENT_ERROR' }; +} + +/** The Harness's plugins start one after another: until they are all up, session/create answers "<plugin>: waiting for <service>". */ +const STARTING_UP = /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)/i; + +/** + * Create a Harness session, waiting for its plugins to finish starting. Right after the app opens (or the Harness restarts) the first + * message can arrive before they are up: that is retried every `retryMs` for up to `readyMs` (`onWait` tells the page "Starting the assistant…") + * instead of failing the first chat. Any other error is thrown at once; a start that never finishes is a plain AGENT_NOT_READY error + * with the Harness's text kept for Details. Returns null when `cancelled()` turns true while waiting. + */ +export async function createSessionWhenReady(create, { readyMs = 60_000, retryMs = 1_500, onWait = () => {}, cancelled = () => false, now = Date.now } = {}) { + const until = now() + readyMs; + for (;;) { + try { return await create(); } catch (e) { + const text = String(e?.message ?? e ?? ''); + if (!STARTING_UP.test(text)) throw e; + if (now() >= until) throw new AgentUnavailable('The assistant could not start. Try again in a moment.', 'AGENT_NOT_READY', text); + onWait(); + await new Promise(r => setTimeout(r, retryMs)); + if (cancelled()) return null; + } + } +} + +/** Attached pictures (data addresses) as the Harness's image prompt parts. */ +export function imageParts(images) { + return (Array.isArray(images) ? images : []).map(i => { + const m = /^data:(image\/(?:png|jpeg|webp));base64,(.+)$/.exec(String(i?.url ?? '')); + return m ? { type: 'image', mediaType: m[1], data: m[2], name: String(i.name ?? 'Picture').slice(0, 120) } : null; + }).filter(Boolean); +} + +/** A timer that never keeps the process alive by itself. */ +const after = (ms, fn) => { const t = setTimeout(fn, ms); t.unref?.(); return t; }; +/** The app's own host folder: never a place an answer's files can be (this file lives in <host>/server/agent). */ +const HOST_DIR = fileURLToPath(new URL('../..', import.meta.url)); + +const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; }; + +/** + * @param {object} options + * @param {string} options.dataDir the host's data directory (agent state lives in `<dataDir>/agent`) + * @param {string|null} [options.componentsDir] where installed components live + * @param {() => Array} options.localInstances ready local instances (see profile.mjs) + * @param {() => Array} options.connections saved API connections WITH their keys (host-internal) + * @param {() => (string|null)} [options.defaultLocalId] the local instance the chat runs on: its tool servers are the agent's (T5) + * @param {NodeJS.ProcessEnv} [options.env] + * @param {string} [options.nodePath] the Node runtime that runs the Harness + * @param {(line:string)=>void} [options.log] + */ +export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, defaultLocalId = () => null, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, engineProgress = () => null, engineGraceMs = 30 * 60_000, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000, sessionReadyMs = 60_000, sessionRetryMs = 1_500 }) { + const root = join(dataDir, 'agent'); + const home = join(root, 'home'); + const sessionsFile = join(root, 'sessions.json'); + mkdirSync(root, { recursive: true }); + + /** + * Where the turn's file tracker must never look (deliverables.mjs): the app, the engine and its components, Strata's own data, AppData + * and temp. `forbid` ones also switch tracking off when the chat's folder is one of them or inside one. + */ + function trackerFolders() { + const user = env.USERPROFILE ?? env.HOME ?? homedir(); + const forbid = [HOST_DIR, componentsDir, bundledDir].filter(Boolean); + const exclude = [dataDir, tmpdir(), env.LOCALAPPDATA, env.APPDATA, env.ProgramData, env.ProgramFiles, env['ProgramFiles(x86)'], env.TEMP, env.TMP, + join(user, 'AppData'), join(user, '.cache'), join(user, '.config'), join(user, '.local'), join(user, 'Library')].filter(Boolean); + return { forbid, exclude }; + } + + /** chatId -> { sessionId, cwd, createdAt } */ + let sessionMap = {}; + if (existsSync(sessionsFile)) { + try { sessionMap = JSON.parse(readFileSync(sessionsFile, 'utf8')) ?? {}; } catch { sessionMap = {}; } + } + const persist = () => { + const temp = `${sessionsFile}.${randomUUID()}.tmp`; + writeFileSync(temp, JSON.stringify(sessionMap, null, 2)); + renameSync(temp, sessionsFile); + }; + + /** @type {{hp:HarnessProcess, gw:GatewayClient, profile:object, clientId:string|null, generation:number, events:object}|null} */ + let rt = null; + let generation = 0; + let lastError = null; + let starting = null; + const chats = new Map(); // chatId -> { turn, route, routeGeneration } + const plans = new PlanStore(join(root, 'plans.json')); + /** chatId -> messages the person typed while a goal ran: [{ id, text, at, deliverAt }]; delivered between steps or when the goal ends */ + const queues = new Map(); + const queueView = chatId => (queues.get(chatId) ?? []).map(({ id, text, at, deliverAt }) => ({ id, text, at, deliverAt })); + const pending = new Map(); // `${sessionId}:${callId}` -> { eventId, sessionId, callId, at } + const questions = new Map(); // `${sessionId}:${callId}` -> the agent's own question waiting for the person: { eventId, sessionId, callId, items, at, clientId } (#4244) + const chatOfSession = sessionId => Object.keys(sessionMap).find(id => sessionMap[id]?.sessionId === sessionId) ?? null; + const idleWaiters = new Set(); + + const chat = id => { let c = chats.get(id); if (!c) { c = { id, turn: null, route: null, routeGeneration: -1 }; chats.set(id, c); } return c; }; + const activeTurns = () => [...chats.values()].filter(c => c.turn).length; + const notifyIdle = () => { if (activeTurns() === 0) { for (const w of idleWaiters) w(); idleWaiters.clear(); } }; + const waitIdle = (signal, ms) => new Promise((resolve, reject) => { + if (activeTurns() === 0) return resolve(); + const timer = setTimeout(() => { idleWaiters.delete(done); reject(new AgentUnavailable('Another chat is still working and the list of models changed. Try again when it finishes.', 'agent-busy')); }, ms); + const done = () => { clearTimeout(timer); resolve(); }; + idleWaiters.add(done); + signal?.addEventListener('abort', () => { clearTimeout(timer); idleWaiters.delete(done); reject(signal.reason ?? new Error('aborted')); }, { once: true }); + }); + + /** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */ + let shapeTargets = {}; + function buildProfileNow() { + const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock, defaultLocalId: defaultLocalId() }); + shapeTargets = profile.shapeTargets ?? {}; + return profile; + } + const llmTarget = key => shapeTargets[key] ?? null; + + function harnessInfo() { return resolveHarness({ env, componentsDir, bundledDir }); } + /** Where the agent component is (the browser tool server lives inside it), or null. */ + const harnessDir = () => { const h = harnessInfo(); return h.ok ? h.dir : null; }; + + /** The capability state the app shows. Never carries a token or a key. */ + function status() { + const h = harnessInfo(); + if (!h.ok) return { state: 'unavailable', reason: 'The coding assistant isn’t installed on this computer yet. Chat works without it.', detail: h.reason, code: 'component-missing' }; + const profile = buildProfileNow(); + return { + state: rt?.hp.running ? 'ready' : starting ? 'starting' : lastError ? 'error' : 'idle', + reason: lastError ? plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again.' : plainAgentFailure(lastError) : null, + detail: lastError ?? null, + harness: { version: h.version }, + runtime: rt?.hp.running ? { pid: rt.hp.pid, generation: rt.generation } : null, + routes: profile.routes.map(({ route, kind, modelId, name, contextWindow }) => ({ route, kind, modelId, name, contextWindow })), + // tool servers that could not be wired (a name the rule does not allow, no program or address): the chat says so + skippedServers: profile.mcpSkipped ?? [], + activeTurns: activeTurns(), + pendingApprovals: pending.size, + }; + } + + async function startRuntime(profile) { + const h = harnessInfo(); + if (!h.ok) throw new AgentUnavailable('The coding assistant isn’t installed on this computer yet. Chat works without it.', 'component-missing', h.reason); + mkdirSync(home, { recursive: true }); + const stale = stopStaleAgent(join(root, 'harness.pid')); + if (stale) log(`agent · stopped a leftover Harness process (pid ${stale}) from an earlier run`); + const patchFile = join(root, `profile-${profile.signature}.patch.yml`); + writeFileSync(patchFile, profile.patch); + const workdir = join(root, 'run'); + const hp = new HarnessProcess({ + harness: h, home, patchFile, cwd: workdir, env: profile.env, nodePath, logFile: join(root, 'harness.log'), pidFile: join(root, 'harness.pid'), + onExit: exit => { + log(`agent · the Harness process exited (code ${exit.code})`); + if (rt?.hp === hp) { lastError = 'The agent process stopped.'; rt = null; } + for (const c of chats.values()) c.turn?.abortFromRuntime('The agent process stopped before this turn finished.'); + }, + }); + const info = await hp.start({ timeoutMs: startTimeoutMs }); + const gw = new GatewayClient({ baseUrl: info.baseUrl, token: info.token }); + await gw.connect(); + const next = { hp, gw, profile, clientId: null, generation: ++generation, events: null }; + next.events = gw.openStream('$events', {}, { + onItem: value => onHostEvent(next, value), + onError: e => log(`agent · event stream: ${redact(e.message, Object.values(profile.env))}`), + }); + rt = next; + lastError = null; + log(`agent · Harness ${h.version ?? ''} ready (pid ${hp.pid}, ${profile.routes.length} route(s))`); + return next; + } + + /** The local engine's own speed for this turn's requests (null when it cannot be read: the stream's estimate stays). */ + async function engineSpeedOf(route, projector) { + const inst = localInstances().find(i => i.id === route.instanceId); + if (!inst) return null; + return turnEngineSpeed({ baseUrl: inst.baseUrl, key: inst.key, since: projector.startedAt, attempts: projector.streams.size, timeoutMs: 800 }); + } + + /** Make sure a runtime exists that knows the route this turn needs. */ + async function ensureRuntime(choice, signal) { + for (;;) { + if (starting) { await starting.catch(() => {}); continue; } + const profile = buildProfileNow(); + const route = routeFor(profile, choice); + if (!route) { + throw new AgentUnavailable(choice?.connectionId + ? 'This API model is no longer available. Choose another model in the chat picker.' + : 'No local model is ready for the agent. Load a model in Models, or choose an API model.', 'model-unavailable'); + } + const known = rt?.hp.running && rt.profile.toolsSignature === profile.toolsSignature && rt.profile.routes.some(r => r.route === route.route && r.modelId === route.modelId && r.fp === route.fp); + if (known) return { rt, route }; + starting = (async () => { + if (rt?.hp.running) { + await waitIdle(signal, 120_000); + const old = rt; rt = null; + old.events?.close(); old.gw.close(); await old.hp.stop(); + } + try { return await startRuntime(profile); } catch (e) { + lastError = redact(String(e.message ?? e), Object.values(profile.env)); + throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.' : plainAgentFailure(lastError), 'agent-start-failed', lastError); + } + })(); + try { await starting; } finally { starting = null; } + } + } + + function onHostEvent(runtime, value) { + if (value.type === 'ready') { runtime.clientId = value.clientId; return; } + if (value.type === 'waterfall' && value.event === 'approval/request') { + const r = value.request ?? {}; + if (!r.callId) return; + pending.set(`${value.agentId}:${r.callId}`, { eventId: value.eventId, sessionId: value.agentId, callId: r.callId, tool: r.toolName, reason: r.reason ?? null, at: Date.now(), clientId: runtime.clientId }); + } else if (value.type === 'waterfall' && value.event === 'user-questions/request') { + // The agent of a chat that is running in front of the person asks the person: the question goes to the page (the question card above the message box) and the + // Harness waits for the answer. Anything else (a helper's question, a chat that is stopping, a request with nothing to show) is declared + // unanswerable, which makes the tool return an error the model reads and carries on from, instead of a turn that waits forever. + const r = value.request ?? {}; + const chatId = chatOfSession(value.agentId); + const turn = chatId ? chats.get(chatId)?.turn : null; + const items = parseQuestions(r.questions); + // A goal or a plan step runs without anyone there: a question would stall it, so it is declined at once (the model reads "could not be answered" and goes on). + if (!turn || turn.finished || turn.stopping || turn.goalRun || turn.plan || !turn.announceQuestion || !items.length) { + void runtime.gw.answerEvent({ clientId: runtime.clientId, eventId: value.eventId, outcome: 'next' }).catch(() => {}); + } else { + const callId = String(r.wait?.callId ?? value.eventId); + questions.set(`${value.agentId}:${callId}`, { eventId: value.eventId, sessionId: value.agentId, callId, items, at: Date.now(), clientId: runtime.clientId }); + turn.announceQuestion({ type: 'agent-question', callId, questions: items }); + } + } else if (value.type === 'cancel') { + for (const [k, v] of questions) if (v.eventId === value.eventId) { questions.delete(k); chats.get(chatOfSession(v.sessionId))?.turn?.announceQuestion?.({ type: 'agent-question-end', callId: v.callId }); } + for (const [k, v] of pending) if (v.eventId === value.eventId) pending.delete(k); + } + } + + async function sessionFor(c, cwd, runtime, { onWait = () => {} } = {}) { + let known = sessionMap[c.id]; + // The chat's folder changed: the agent's working folder and sandbox are fixed when its session starts, so the chat gets a new session + // in the new folder (the earlier conversation is carried into its first message, as for any fresh session). + if (known && cwd && known.cwd && resolve(known.cwd) !== resolve(cwd)) { delete sessionMap[c.id]; persist(); known = null; } + if (known) return { sessionId: known.sessionId, fresh: false }; + const created = await createSessionWhenReady(() => runtime.gw.rpc('session/create', { request: { cwd } }), { readyMs: sessionReadyMs, retryMs: sessionRetryMs, onWait, cancelled: () => c.cancelStart }); + if (!created) return null; + sessionMap[c.id] = { sessionId: created.sessionId, cwd, createdAt: new Date().toISOString() }; + persist(); + return { sessionId: created.sessionId, fresh: true }; + } + + /** + * Put the session into the preset of the chat's mode, through the Harness's own `/permission` command, and + * check that it took. A turn never starts in a mode other than the one asked for: if the switch cannot be + * confirmed the turn fails closed with a typed error instead of running with unknown permissions. + */ + async function applyMode(runtime, sessionId, mode) { + const want = MODE_PRESETS[mode].key; + const read = async () => { + const r = await runtime.gw.rpc('session/projections', { request: { sessionId, keys: ['permissions'] } }); + return r?.values?.permissions?.currentValue ?? null; + }; + try { + if (await read() !== want) { + const done = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: `/permission ${want}`, submittedAttachments: [] }); + if (done?.result?.kind !== 'success') throw new Error(done?.result?.text ?? 'the agent did not recognise the command'); + const now = await read(); + if (now !== want) throw new Error(`the session reports "${now}" instead of "${want}"`); + } + } catch (e) { + throw new AgentUnavailable(`Strata could not set this chat to ${MODE_PRESETS[mode].name} mode, so nothing ran. Try again.`, 'mode-unavailable', e.message); + } + // Manual leaves the sandbox open and relies on the Strata gate to ask first. Without the gate it must not start. + if (mode === 'manual' && !runtime.gateChecked) { + try { + const probe = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-gate', submittedAttachments: [] }); + if (probe?.result?.kind !== 'success' || !String(probe.result.text ?? '').includes('strata-gate active')) throw new Error('the approval gate is not loaded'); + runtime.gateChecked = true; + } catch (e) { + throw new AgentUnavailable('Strata could not make sure the coding assistant asks before changing anything, so nothing ran. Close and reopen Strata, then try again.', 'mode-unavailable', e.message); + } + } + } + + /** + * Run one agent turn for a Strata chat and stream it as frames. + * `signal` means the client went away: the turn keeps running (that is not Stop). + */ + async function runTurn(options) { + const c = chat(options.chatId); + if (c.turn || c.starting) throw new AgentUnavailable('This chat is still working. Stop it or wait for it to finish.', 'turn-active'); + // From here until the Harness has the prompt, Stop has no session to cancel; it cancels the start. + c.starting = true; c.cancelStart = false; + try { return await runTurnInner(c, options); } finally { c.starting = false; } + } + + async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, thinkingBudget = 0, images = [], planTask = null, planRun = null, researchTopic = null }) { + let send = onFrame; let attached = true; + // A research run gathers first; what the assistant writes while gathering is notes, not the answer, so it is not shown. + let hideDeltas = !!researchTopic; + signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true }); + // What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary. + const written = { all: '', step: '' }; + // The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known. + let guard = null; + const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } }; + // What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends. + const tracker = new DeliverableTracker(workspacePath, trackerFolders()); + let toolsRan = false; // a turn that ran no tool wrote nothing, so there is nothing to look for at its end + try { tracker.snapshot(); } catch { /* a folder that cannot be read has no deliverables */ } + const groups = new ActivityGroups({ emit: raw }); + const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) }); + const emit = frame => { + if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (guard) trip(guard.text(frame.text)); if (hideDeltas) return; } + if (frame.own) { const { own, ...rest } = frame; frame = rest; } + if (frame.type === 'delta' && frame.text) groups.text(); + if (frame.type === 'agent-tool' && frame.tool) { + if (['done', 'error'].includes(frame.tool.state) && !['read', 'read_image', 'glob', 'grep', 'web_fetch', 'web_search'].includes(frame.tool.name)) toolsRan = true; + let made = null; + if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } } + raw(frame); + if (made) raw(made); + if (guard) trip(guard.card(frame.tool)); + groups.card(frame.tool, made); + skills.card(frame.tool); + return; + } + raw(frame); + }; + // What the assistant is doing right now, one small frame (status.mjs). Cleared before the final frame of the turn. + const reporter = new StatusReporter({ emit }); + + emit({ type: 'queued', requestId }); + reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' }); + const { rt: runtime, route } = await ensureRuntime(choice, signal); + const made = await sessionFor(c, workspacePath, runtime, { onWait: () => reporter.set({ phase: 'starting', code: 'assistant-starting', text: 'Starting the assistant…' }) }); + const { sessionId, fresh } = made ?? {}; + const cancelled = () => { reporter.clear(); emit({ type: 'done', finishReason: 'aborted', cancelled: true, tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0, model: route.name, contextMax: route.contextWindow }); return { cancelled: true }; }; + if (c.cancelStart || !made) return cancelled(); + + // The model and the chat's thinking level (the Reasoning menu) are sent to the Harness when either changed. A level the route does + // not have (an API model with its own vocabulary) is dropped and the model's own default stands: never an error for the person. + const level = effortOf(thinking ?? 'Medium'); // the menu's default is Medium + // Response settings the Harness cannot send itself (the thinking budget, the Expert sampling) go through this host's forwarding + // endpoint, on a copy of the route; with every setting at its default the route is used directly, as before. + const budget = level === 'off' ? 0 : nearestBudget(thinkingBudget); + const sampling = proxyBase && route.shaped ? expertSampling() : null; + const provider = route.shaped && (budget || sampling) ? route.shaped[budget] : route.route; + const wanted = `${provider}/${route.modelId}/${level ?? ''}`; + if (c.route !== wanted || c.routeGeneration !== runtime.generation) { + const select = effort => runtime.gw.rpc('session/selectModel', { request: { sessionId, provider, model: route.modelId, ...(effort ? { reasoningEffort: effort } : {}) } }); + try { + try { await select(level); } catch (e) { if (!level || e.code === 'session/not-found') throw e; await select(null); } + } catch (e) { + if (e.code === 'session/not-found') { delete sessionMap[c.id]; persist(); } + throw new AgentUnavailable(`The coding assistant could not use ${route.name}. Pick the model again and retry.`, 'model-unavailable', e.message); + } + c.route = wanted; c.routeGeneration = runtime.generation; + } + + // The chat's permission mode is read once, here, for this whole turn. A change the user makes while the + // turn runs applies to the next one, so a running turn never sees its permissions move under it. + const appliedMode = planTask ? 'plan' : modeOf(mode); + await applyMode(runtime, sessionId, appliedMode); + + // Does the message fit the model's window? Asked before anything is sent, with the model server's own count (context-fit.mjs). A message + // that fits once the older messages are a summary is sent after a summary; one that can never fit is not sent, and the person is told + // plainly and offered the two ways out. Whatever cannot be counted goes through: the Harness recovers from a refusal by itself. + if (!goal && route.kind === 'local') { + const fit = await fitCheck({ runtime, route, sessionId, fresh, history, message }).catch(() => null); + if (fit?.action === 'too-large') { + reporter.clear(); + const values = [grouped(fit.tokens), grouped(fit.window)]; + const text = fill(FIT_TEXT.tooLarge, values); + emit({ type: 'error', message: text, key: FIT_TEXT.tooLarge, values, code: 'CONTEXT_MESSAGE_TOO_LARGE', tokens: fit.tokens, window: fit.window }); + return { error: text }; + } + if (fit?.action === 'summarize') { + reporter.set({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] }); + const done = await compactChat(runtime, sessionId); + reporter.clear(); + if (done.ok) emit(summarizedNote(done.before, done.after, fit.window)); + } + } + + const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval, window: route.contextWindow }); + if (!goal) guard = new TurnGuard({ plan: !!planTask, contextMax: route.kind === 'local' ? route.contextWindow : 0 }); // a saved connection's window is often only assumed: never judged by a guess + projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); }; + const turn = { + sessionId, projector, route, requestId, live: false, lastSeq: -1, + ended: deferred(), follow: null, snapshot: deferred(), finished: false, prompted: false, stopBeforePrompt: false, + abortFromRuntime: reason => finishTurn(reason), finish: failure => finishTurn(failure), + // Helper agents (subagents) the Harness started for this chat, and the state of the run around them. + children: new Map(), subagentCalls: new Map(), parentOpen: false, stopping: false, settleTimer: null, mode: appliedMode, + plan: null, advancing: false, goalRun: false, lastActivity: Date.now(), heard: Date.now(), engineMark: null, watchdog: null, + research: researchTopic ? { phase: 'gather', nudged: false, waitingStart: false } : null, + }; + c.turn = turn; + /** + * A turn must always end. If the Harness sends nothing at all for a while (a tool that never returns, a model server that went + * quiet, a lost event) the turn is stopped and ended with a plain message instead of showing "thinking" forever. A running tool gets + * a longer allowance than a quiet model (a build can be silent for minutes). Whatever the assistant finished is kept. + */ + turn.watchdog = setInterval(() => { + if (turn.finished || turn.stopping) return; + const toolRunning = [...projector.tools.values()].some(x => x.card?.state === 'running' || x.card?.state === 'proposed') || pending.size > 0 && pendingFor(chatId).length > 0; + const limit = toolRunning ? stallToolMs : stallMs; + // A local engine reading a long prompt sends the Harness nothing for minutes (#3623). Its /metrics progress counts as activity, + // for at most engineGraceMs after the Harness last spoke: progress for another chat cannot keep a lost turn alive forever. + if (turn.route?.kind === 'local' && Date.now() - turn.heard < engineGraceMs) { + let mark = null; + try { mark = engineProgress(turn.route.instanceId); } catch { /* no progress known: the Harness alone decides */ } + if (mark != null && mark !== turn.engineMark) { turn.engineMark = mark; turn.lastActivity = Date.now(); return; } + } + if (Date.now() - turn.lastActivity < limit) return; + turn.stalledFor = Math.round((Date.now() - turn.lastActivity) / 1000); + turn.stopping = true; + void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); + for (const h of turn.children.values()) if (!h.done) void runtime.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: sessionId, mode: 'continuable' }).catch(() => {}); + const mins = Math.max(1, Math.round(turn.stalledFor / 60)); + turn.finish(`The assistant stopped answering for ${mins > 1 ? mins + ' minutes' : 'a minute'}, so I ended this turn. Anything it already finished is kept. Send your message again to go on.`); + }, Math.min(15_000, Math.max(200, Math.floor(stallMs / 4)))); + turn.watchdog.unref?.(); + async function finishTurn(failure) { + if (turn.finished) return; + turn.finished = true; + for (const [k, v] of questions) if (v.sessionId === turn.sessionId) questions.delete(k); + clearTimeout(turn.settleTimer); + clearInterval(turn.watchdog); + turn.follow?.close(); + for (const child of turn.children.values()) child.follow?.close(); + if (turn.stopping && !failure) projector.ended = turn.guard ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'user' } }; + reporter.clear(); + const extra = []; + try { if (toolsRan) for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ } + groups.end(); + if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); } + try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ } + // The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself). + let noteReason = turn.guard ?? null; + // A reply the length limit cut ends with a sentence that says so (and what was lost), never with silence (AGENT-LOST). + const cutEnd = !failure && !turn.stopping && projector.ended?.kind === 'max-tokens'; + if (cutEnd && !noteReason) { + const note = cutNotice({ ...projector.cut(), retrying: false }); + extra.push({ type: 'delta', own: true, text: ` + +${note.text}`, key: note.key, values: note.values, noteReason: 'cut' }); + } + if (!noteReason && !cutEnd && guard && !failure && !turn.stopping && !turn.goalRun) { + noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens }); + } + if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); } + for (const f of extra) emit(f); + // The answer speed of a turn on this computer is the engine's own (tokens it produced over its decode time, as the Monitor shows it). + const engine = !failure && route.kind === 'local' ? await engineSpeedOf(route, projector) : null; + const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow, engine }); + for (const f of frames.slice(0, -1)) emit(f); + // Messages typed while the goal ran and not delivered between steps go back to the page now, to be sent as ordinary messages. + if (turn.goalRun && attached) { + const left = queueView(chatId); + if (left.length) { queues.delete(chatId); onQueue(chatId, []); emit({ type: 'queued-release', messages: left.map(({ id, text }) => ({ id, text })) }); } + } + for (const f of frames.slice(-1)) emit(f); + c.turn = null; + turn.ended.resolve({ reason: projector.ended, failure: failure ?? null }); + notifyIdle(); + // A turn that filled the context, or that the guard stopped, leaves a long history behind: summarise the older part now so the next message has room. + if (noteReason === 'context' || noteReason === 'searches' || noteReason === 'searches-failed' || noteReason === 'rewrites' || /context window|too long|exceeds/i.test(String(projector.ended?.error?.message ?? ''))) void compactSession(runtime, sessionId); + } + + emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [], ...(planTask ? { planning: true } : {}) }); + + turn.follow = runtime.gw.openStream('session/follow', { request: { address: { kind: 'session', sessionId }, assistantStream: true } }, { + onItem: item => { + if (item.type === 'snapshot') { + if (turn.lastSeq < 0) turn.lastSeq = item.cursor; + else for (const r of item.records ?? []) if (r.type === 'event' && r.event.seq > turn.lastSeq) handle({ type: 'event', event: r.event }); + turn.snapshot.resolve(); + return; + } + handle(item); + }, + onError: e => finishTurn(`The agent lost the session stream: ${e.message}`), + }); + + /** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */ + function trip(reason) { + if (!reason || turn.guard || turn.finished || turn.stopping) return; + turn.guard = reason; + log(`agent · turn guard: ${reason} (searches ${guard?.searches ?? 0}, failed in a row ${guard?.failedInARow ?? 0}, plan rewrites ${guard?.rewrites ?? 0})`); + void stop(chatId).catch(() => {}); + } + + function handle(item) { + if (turn.finished) return; + turn.lastActivity = Date.now(); + turn.heard = turn.lastActivity; + if (item.type === 'event') { + const e = item.event; + if (e.seq <= turn.lastSeq) return; + turn.lastSeq = e.seq; + // The turn is ours from the user message that carries our request id. Until then an older, + // detached turn on the same session may still be finishing; its events are not ours. + if (!turn.live) { + if (e.type === 'user/message' && e.data?.source?.rpcId === requestId) turn.live = true; + return; + } + } else if (!turn.live) return; + for (const f of projector.consume(item)) emit(f); + if (guard && projector.contextTokens != null) trip(guard.context(projector.contextTokens)); + if (item.type === 'event') watchParent(item.event); + } + + // -- helper agents --------------------------------------------------------------------------------------- + + const rowFrame = child => ({ type: 'agent', agent: child.cp.agent() }); + const emitRow = (child, force = false) => { + const now = Date.now(); + if (!force && now - child.lastRow < 400) { child.rowPending = true; return; } + child.lastRow = now; child.rowPending = false; + emit(rowFrame(child)); + const working = [...turn.children.values()].filter(h => !h.done).length; + if (working && !turn.parentOpen) reporter.set({ phase: 'helpers', code: 'helpers', text: `Helpers are working (${working})…`, key: 'Helpers are working ({0})…', values: [working], args: { n: working } }); + }; + + function openChild(d) { + const id = d.childId; + if (!id || turn.children.has(id)) return; + const cp = new ChildProjector({ id, name: d.label || 'Helper' }); + const child = { id, cp, follow: null, noticed: false, done: false, lastRow: 0, rowPending: false, endedAt: 0 }; + turn.children.set(id, child); + emitRow(child, true); + const fold = item => { + if (turn.finished) return; + turn.lastActivity = turn.heard = Date.now(); + // A helper that finishes before its throttled "working" row went out would show queued -> completed and never "working": send the held row first. + if (item.type === 'event' && item.event.type === 'turn/end' && child.rowPending) emitRow(child, true); + const { frames, row } = cp.consume(item); + for (const f of frames) emit(f); + if (item.type === 'event' && item.event.type === 'turn/end') { child.done = true; child.endedAt = Date.now(); emitRow(child, true); armSettle(); return; } + if (item.type === 'event' && child.done && cp.status === 'working') { child.done = false; } + if (row) emitRow(child); + }; + child.follow = runtime.gw.openStream('session/follow', { + request: { address: { kind: 'subagent', parentSessionId: sessionId, childSessionId: id, mode: d.mode ?? 'unknown' }, assistantStream: true }, + }, { + onItem: item => { + if (item.type === 'snapshot') { for (const r of item.records ?? []) if (r.type === 'event') fold({ type: 'event', event: r.event }); return; } + fold(item); + }, + onError: e => { + log(`agent · helper stream ended: ${e.message}`); + if (!child.done) { child.done = true; child.endedAt = Date.now(); cp.status = 'failed'; cp.failure = 'Lost contact with this helper.'; cp.endedAt = Date.now(); emitRow(child, true); armSettle(); } + }, + }); + // A late reader still gets the final row: flush any row held back by the throttle. + child.flush = after(500, function tick() { if (!turn.finished && child.rowPending) emitRow(child, true); if (!turn.finished && !child.done) child.flush = after(500, tick); }); + } + + function watchParent(e) { + const d = e.data ?? {}; + switch (e.type) { + case 'turn/start': + turn.parentOpen = true; + if (turn.research) turn.research.waitingStart = false; + turn.cutWaiting = false; + clearTimeout(turn.settleTimer); + // After Stop, a helper's report would start a new turn that nobody asked for. + if (turn.stopping) void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); + break; + case 'turn/end': + turn.parentOpen = false; + armSettle(); + break; + // The first turn of a prompt may have started before this follow stream attached (no turn/start seen): any step of the parent is proof that it is + // still working. Without this a helper that finished while the parent was still answering ended the run early ("The agent turn was interrupted"). + case 'step/start': + if (!turn.parentOpen) { turn.parentOpen = true; clearTimeout(turn.settleTimer); } + break; + case 'tool/call': + if (d.name === 'subagent' || d.name === 'subagent_fork') turn.subagentCalls.set(d.callId, parseArgs(d.arguments)); + break; + case 'subagent/catalog': + openChild(d); + break; + case 'tool/result': { + const call = turn.subagentCalls.get(d.message?.toolCallId); + const text = (d.message?.content ?? []).map(p => p.text ?? '').join(' '); + const started = /started subagent ([0-9a-f-]{36})/i.exec(text); + const child = started ? turn.children.get(started[1]) : null; + if (call && child) { child.cp.task = String(call.prompt ?? call.description ?? '').replace(/\s+/g, ' ').trim().slice(0, 140); emitRow(child, true); } + break; + } + case 'user/message': + if (d.source?.kind === 'goal' && Number.isInteger(d.source.round)) { turn.goalRound = d.source.round; void announceGoal(); } + // falls through + case 'agent/inbox/spliced': { + const hit = JSON.stringify(d); + if (!/Background subagent/.test(hit)) break; + for (const child of turn.children.values()) if (hit.includes(child.id)) child.noticed = true; + break; + } + default: + break; + } + } + + // -- plans and goal steps ---------------------------------------------------------------------------------- + + const planFrame = (event, plan, extra = {}) => ({ type: 'plan', event, plan: planView(plan), ...extra }); + const publishPlan = (event, plan) => { onPlan(chatId, event, planView(plan)); return planFrame(event, plan); }; + const stepFrame = (plan, index) => { + const st = plan.steps[index]; + return { type: 'plan-step', planId: plan.id, stepId: st.id, index: index + 1, total: plan.steps.length, state: st.state, text: st.text, summary: st.summary ?? null, line: stepLine(index, plan.steps.length, st.text, st.state === 'running' ? 'started' : st.state) }; + }; + const currentStep = plan => plan.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped'); + + /** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */ + function settlePlan(failure) { + if (planTask) { + if (failure || (turn.stopping && !turn.guard)) return []; + const parsed = parsePlan(written.all, planTask); + if (!parsed) return []; + const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask, ...(turn.guard ? { caution: GUARD_NOTES[turn.guard] } : {}) }); + return [publishPlan('proposed', plan)]; + } + const run = turn.plan; + if (!run) return []; + const plan = plans.get(chatId); + if (!plan || plan.id !== run.id) return []; + if (plan.state !== 'running') return []; + const out = []; + const at = currentStep(plan); + plans.update(chatId, p => { + if (at < 0) { p.state = 'done'; return; } + // The step that was running goes back to waiting, so Resume runs it again. + p.steps[at].state = 'pending'; + p.state = 'paused'; + }); + const updated = plans.get(chatId); + if (at >= 0) out.push(stepFrame(updated, at)); + out.push(publishPlan(updated.state === 'done' ? 'done' : 'paused', updated)); + return out; + } + + /** The goal the Harness runs for the plan's next waiting step, and the frames that say so. */ + async function startStep(plan, index) { + plans.update(chatId, p => { p.state = 'running'; p.goalStarted = true; p.steps[index].state = 'running'; }); + const now = plans.get(chatId); + await runtime.gw.rpc('goals/create', { agentId: sessionId, request: { objective: stepObjective(now, index) } }); + written.step = ''; written.stepAt = Date.now(); + emit(stepFrame(now, index)); + emit(publishPlan('step', now)); + const st = now.steps[index]; + reporter.set({ phase: 'goal', code: 'goal-step', text: stepLine(index, now.steps.length, st.text, 'started'), key: '{0}', values: [st.text], args: { step: index + 1, steps: now.steps.length } }); + } + + /** One goal step finished: say so, hand over queued messages, and begin the next step (or end the plan). */ + async function advancePlan() { + const run = turn.plan; + const plan = plans.get(chatId); + if (!run || !plan || plan.id !== run.id) return false; + const at = currentStep(plan); + if (at < 0) return false; + const cards = [...projector.tools.values()].filter(x => x.calledAt >= (written.stepAt ?? 0) - 50 && x.card?.state === 'done').map(x => x.card); + const summary = stepSummary(cards, written.step.split(/\n\s*\n/).filter(Boolean).at(-1) ?? written.step); + plans.update(chatId, p => { p.steps[at].state = 'done'; p.steps[at].summary = summary; }); + let now = plans.get(chatId); + emit(stepFrame(now, at)); + emit({ type: 'delta', own: true, text: `\n\n${stepLine(at, now.steps.length, now.steps[at].text, 'done')}\n` }); + const next = currentStep(now); + emit(publishPlan(next < 0 ? 'done' : 'step', next < 0 ? (plans.update(chatId, p => { p.state = 'done'; }), plans.get(chatId)) : now)); + await deliverQueued(at + 1); + if (turn.stopping || turn.finished) return true; + if (next < 0) return false; + // One step per turn (Time-skip): the plan stays open for the next step, which starts in a session of its own so the conversation never grows across steps. + if (run.once) { plans.update(chatId, p => { p.state = 'approved'; }); emit(publishPlan('step', plans.get(chatId))); return false; } + await startStep(plans.get(chatId), next); + void announceGoal(); + return true; + } + + /** Hand the person's queued messages to the assistant, one at a time, each answered before the next. */ + async function deliverQueued(afterStep) { + const list = queues.get(chatId) ?? []; + while (list.length && !turn.stopping && !turn.finished) { + const item = list.shift(); + if (!list.length) queues.delete(chatId); + onQueue(chatId, queueView(chatId)); + emit({ type: 'queued-message', state: 'delivered', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, afterStep, queue: queueView(chatId) }); + try { await runtime.gw.rpc('session/prompt', { request: { requestId: `queued-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: item.text }] } }); } + catch { emit({ type: 'queued-release', messages: [{ id: item.id, text: item.text }] }); continue; } + // Wait for the answer: the parent opens a turn for it and closes it again. + const t0 = Date.now(); + while (!turn.parentOpen && Date.now() - t0 < 4000 && !turn.finished) await new Promise(r => setTimeout(r, 50)); + while (turn.parentOpen && !turn.finished && !turn.stopping) await new Promise(r => setTimeout(r, 100)); + } + } + + /** + * The run is over when the parent is idle and every helper has finished and reported back. A helper's report + * wakes the parent a moment after the helper ends, so a helper that ended but has not reported yet keeps the run + * open (for a few seconds at most); after Stop nobody waits for reports. + */ + function armSettle() { + clearTimeout(turn.settleTimer); + if (turn.finished) return; + turn.settleTimer = after(turn.stopping ? 1200 : turn.children.size ? 600 : 0, async () => { + if (turn.finished || turn.parentOpen || turn.advancing) return; + const open = [...turn.children.values()]; + if (open.some(c => !c.done)) return; + if (!turn.stopping) { + if (open.some(c => !c.noticed && Date.now() - c.endedAt < 8000)) { armSettle(); return; } + // An armed goal starts its next round as soon as the agent is idle: the run is not over until the goal stops. + const current = await goalGet(); + if (turn.finished || turn.parentOpen) return; + if (current && current.phase === 'active' && current.activation === 'armed') { turn.settleTimer = after(700, armSettle); return; } + // A reply the length limit cut (AGENT-LOST): the agent lost what it was writing. Say so in the chat and ask it to carry on in smaller pieces, twice at most. + if (turn.cutWaiting) { turn.settleTimer = after(300, armSettle); return; } + if (projector.ended?.kind === 'max-tokens' && !turn.goalRun && !turn.stopping && (turn.cuts ?? 0) < MAX_CUT_RETRIES) { + const cut = projector.cut(); + turn.cuts = (turn.cuts ?? 0) + 1; + const note = cutNotice({ ...cut, retrying: true }); + emit({ type: 'delta', own: true, text: ` + +${note.text} + +`, key: note.key, values: note.values, noteReason: 'cut' }); + for (const f of projector.clearCut()) emit(f); + turn.cutWaiting = true; + try { await runtime.gw.rpc('session/prompt', { request: { requestId: `cut-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: cutNudge(cut) }] } }); } + catch { turn.cutWaiting = false; finishTurn(null); return; } + turn.settleTimer = after(500, armSettle); + return; + } + // Research: gather (search and read pages), then write the answer in the fixed shape. A step that did not open pages is sent back once. + if (turn.research && !turn.stopping) { + const r = turn.research; + if (r.waitingStart) { turn.settleTimer = after(300, armSettle); return; } + const opened = [...projector.tools.values()].filter(x => x.card?.name === 'web_fetch' && x.card.state === 'done').length; + const prompt = r.phase === 'write' ? null : (opened < 2 && !r.nudged) ? RESEARCH_NUDGE : researchWritePrompt(researchTopic); + if (prompt) { + if (prompt !== RESEARCH_NUDGE) { r.phase = 'write'; hideDeltas = false; written.all = ''; reporter.set({ phase: 'waiting', code: 'research-writing', text: 'Writing the answer…', key: 'Writing the answer…', values: [], args: {} }); } else r.nudged = true; + r.waitingStart = true; + try { await runtime.gw.rpc('session/prompt', { request: { requestId: `research-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }] } }); } + catch { r.waitingStart = false; hideDeltas = false; finishTurn(null); return; } + turn.settleTimer = after(500, armSettle); + return; + } + } + // A plan step's goal is complete: record it, deliver queued messages, start the next step. + if (turn.plan && current && current.phase === 'complete' && !turn.advancing) { + turn.advancing = true; + let more = false; + try { more = await advancePlan(); } catch (e) { emit({ type: 'delta', own: true, text: `\n\nThe plan stopped: ${plainGoalError(e)}\n` }); } + turn.advancing = false; + if (more && !turn.finished && !turn.stopping) { turn.settleTimer = after(700, armSettle); return; } + } + + if (turn.goalRun && current) { const line = goalEnding(current); if (line) emit({ type: 'delta', text: line }); } + if (turn.goalRun) await announceGoal(true); + } + finishTurn(null); + }); + } + const goalGet = () => runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined); + /** The goal's state to the page: a `goal` frame, the SSE event for the bar, and (while a round runs) the status line. */ + async function announceGoal(final = false) { + const view = await goalGet(); + if (turn.finished && !final) return; + const goal = goalObject(view, chatId); + emit({ type: 'goal', goal }); + onGoal(chatId, goal); + if (!final && goal && goal.phase === 'active' && turn.goalRound) reporter.set({ phase: 'goal', code: 'goal-step', text: 'Working on the goal…', args: { round: turn.goalRound, max: goal.maxRounds } }); + } + turn.announceGoal = announceGoal; + turn.announceQueue = frame => emit(frame); + turn.announceQuestion = frame => emit(frame); + + const snapshotTimer = {}; + await Promise.race([turn.snapshot.promise, new Promise((_, rej) => { snapshotTimer.t = after(20_000, () => rej(new Error('the session stream did not open'))); })]) + .catch(e => { finishTurn(e.message); }) + .finally(() => clearTimeout(snapshotTimer.t)); + if (turn.finished) return { error: true }; + if (turn.stopBeforePrompt || c.cancelStart) { projector.ended = { kind: 'aborted', reason: { kind: 'user' } }; finishTurn(null); return { cancelled: true }; } + + if (goal) { + // A goal run has no prompt of its own: the Harness's goal driver starts the rounds. Everything from now on is ours. + turn.live = true; turn.goalRun = true; + try { + if (planRun) { + const plan = plans.get(chatId); + if (!plan || plan.id !== planRun.planId) throw new AgentUnavailable('That plan is no longer there. Ask for a new one with /plan.', 'plan-gone'); + turn.plan = { id: plan.id, once: !!planRun.once }; + const at = currentStep(plan); + if (at < 0) throw new AgentUnavailable('Every step of this plan is already done.', 'plan-done'); + if (goal.action === 'resume' && plan.goalStarted) { + plans.update(chatId, p => { p.state = 'running'; p.steps[at].state = 'running'; }); + await startGoal(runtime, sessionId, goal); + emit(publishPlan('step', plans.get(chatId))); + } else await startStep(plan, at); + } else { + await startGoal(runtime, sessionId, goal); + } + } catch (e) { finishTurn(e instanceof AgentUnavailable ? e.message : plainGoalError(e)); return { error: true }; } + reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); + void announceGoal(); + } else { + let prompt = message; + if (fresh && history.length) prompt = withEarlierConversation(history, message); + try { + await runtime.gw.rpc('session/prompt', { request: { requestId, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }, ...imageParts(images)] } }); + } catch (e) { + finishTurn(`The agent did not accept the message: ${e.message}`); + return { error: true }; + } + } + if (!goal) reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); + turn.prompted = true; + if (turn.stopBeforePrompt) { + // Stop landed in the instant between 'prompt sent' and 'prompt accepted'. A cancel before the turn + // starts arms nothing, so wait for the turn to be ours, then cancel it. + for (let i = 0; i < 100 && !turn.live && !turn.finished; i++) await new Promise(r => setTimeout(r, 50)); + if (!turn.finished) await runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); + } + + // Wait for the turn, or for the client to leave. Leaving does not stop the turn. + const gone = new Promise(r => signal?.addEventListener('abort', () => r('detached'), { once: true })); + const outcome = await Promise.race([turn.ended.promise, gone]); + if (outcome === 'detached') return { detached: true, sessionId, ended: turn.ended.promise.then(r => ({ ...r, tokensOut: projector.tokensOut })) }; + return { sessionId, reason: outcome.reason, tokensIn: projector.tokensIn, tokensOut: projector.tokensOut }; + } + + // -- /goal ----------------------------------------------------------------------------------------------- + + /** Create or resume the chat's goal; the Harness's goal driver then runs the rounds by itself. */ + async function startGoal(runtime, sessionId, goal) { + if (goal.action === 'create') { + const request = { objective: goal.objective, ...(goal.maxRounds ? { maxGoalRounds: goal.maxRounds } : {}) }; + await runtime.gw.rpc('goals/create', { agentId: sessionId, request }); + return; + } + const current = await runtime.gw.rpc('goals/get', { agentId: sessionId }); + if (!current) throw new AgentUnavailable('There is no goal to continue. Start one with /goal followed by what you want done.', 'goal-none'); + await runtime.gw.rpc('goals/resume', { agentId: sessionId, ref: { id: current.id, revision: current.revision } }); + } + + async function pauseGoal(runtime, sessionId, chatId = null) { + try { + const current = await runtime.gw.rpc('goals/get', { agentId: sessionId }); + if (current && current.phase === 'active') { + await runtime.gw.rpc('goals/pause', { agentId: sessionId, ref: { id: current.id, revision: current.revision } }); + if (chatId) onGoal(chatId, goalObject(await runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined))); + } + } catch { /* no goal service, or nothing to pause */ } + } + + /** The goal as the page and the goal bar see it (notes-split-agent3.md), or null. */ + function goalObject(view, chatId = null) { + if (!view) return null; + const phase = ['active', 'paused', 'complete', 'blocked'].includes(view.phase) ? view.phase : 'blocked'; + // A goal that is running a plan (or the points of a goal) shows the plan's title and which step it is on. + const plan = chatId ? plans.get(chatId) : null; + const running = plan && plan.goalStarted && ['running', 'paused'].includes(plan.state) ? plan : null; + const at = running ? running.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped') : -1; + const step = running && at >= 0 ? { index: at + 1, total: running.steps.length, text: running.steps[at].text } : null; + return { objective: step ? running.title : String(view.objective ?? ''), ...(step ? { step } : {}), phase, round: view.roundsStarted ?? 0, maxRounds: view.maxGoalRounds ?? null, ...(phase === 'blocked' ? { blocked: plainBlocker(view.blockedReason) } : {}) }; + } + + /** The goal of a chat now, from the Harness (null: none, or the agent is not running). */ + async function goalState(chatId) { + const known = sessionMap[chatId]?.sessionId; + if (!known || !rt?.hp.running) return null; + return goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId); + } + + /** Pause, edit or remove the goal from the goal bar. Instant; resume runs rounds and goes through the chat stream. */ + async function goalControl({ chatId, action, text }) { + const known = sessionMap[chatId]?.sessionId; + if (!known || !rt?.hp.running) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none'); + const current = await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined); + if (!current) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none'); + const ref = { id: current.id, revision: current.revision }; + try { + if (action === 'pause') { if (current.phase === 'active') await rt.gw.rpc('goals/pause', { agentId: known, ref }); } + else if (action === 'clear') await rt.gw.rpc('goals/clear', { agentId: known, ref }); + else if (action === 'edit') { + const objective = String(text ?? '').trim().slice(0, 4000); + if (!objective) throw new AgentUnavailable('A goal needs a few words about what you want done.', 'goal-text'); + await rt.gw.rpc('goals/edit', { agentId: known, ref, request: { objective } }); + } else throw new AgentUnavailable('That goal action is not known.', 'goal-action'); + } catch (e) { throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainGoalError(e), 'goal-failed', e.message); } + if (action === 'clear') { const plan = plans.get(chatId); if (plan && ['running', 'paused'].includes(plan.state)) { plans.update(chatId, p => { p.state = 'stopped'; for (const st of p.steps) if (st.state === 'running') st.state = 'pending'; }); onPlan(chatId, 'stopped', planView(plans.get(chatId))); } } + const goal = action === 'clear' ? null : goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId); + onGoal(chatId, goal); + return { goal }; + } + + /** The goal's state in plain words. */ + function describeGoal(view) { + if (!view) return 'No goal is set. Start one with /goal followed by what you want done.'; + const what = `"${view.objective}"`; + if (view.phase === 'active') return `Working on the goal ${what}.`; + if (view.phase === 'paused') return `The goal ${what} is paused. Type /goal resume to go on.`; + if (view.phase === 'complete') return `The goal ${what} is complete.`; + return `The goal ${what} stopped: ${plainBlocker(view.blockedReason)}`; + } + + /** + * Handle a "/goal ..." line for a chat, as the Harness's own /goal command reads it: nothing = show the goal, + * clear, pause, resume, edit <text>, or any other text = a new goal. Starting or resuming runs the rounds and + * streams them like a chat turn (Stop pauses the goal); every other verb answers at once. + */ + async function goalCommand(options) { + const { chatId, line, onFrame } = options; + const text = String(line ?? '').trim(); + const verb = text.split(/\s+/)[0]?.toLowerCase() ?? ''; + const rest = text.slice(verb.length).trim(); + const say = reply => { + onFrame({ type: 'queued', requestId: `goal-${randomUUID()}` }); + onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); + onFrame({ type: 'delta', text: reply }); + onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); + return { goal: true }; + }; + if (tools()?.off?.has('goals')) return say('Goals are turned off. You can turn them back on in Settings, Tools.'); + const known = sessionMap[chatId]?.sessionId; + const quick = ['', 'clear', 'pause', 'edit', 'complete'].includes(verb) || (verb === 'status'); + let runtime = rt; + if (quick) { + if (!known || !runtime?.hp.running) return say(verb === '' || verb === 'status' ? describeGoal(null) : 'There is no goal in this chat yet.'); + const current = await runtime.gw.rpc('goals/get', { agentId: known }).catch(() => undefined); + const ref = current ? { id: current.id, revision: current.revision } : null; + try { + if (verb === '' || verb === 'status') return say(describeGoal(current)); + if (!ref) return say('There is no goal in this chat yet.'); + if (verb === 'clear') { await runtime.gw.rpc('goals/clear', { agentId: known, ref }); return say('The goal is cleared.'); } + if (verb === 'pause') { + if (current.phase === 'active') await runtime.gw.rpc('goals/pause', { agentId: known, ref }); + return say(describeGoal(await runtime.gw.rpc('goals/get', { agentId: known }))); + } + if (verb === 'complete') { await runtime.gw.rpc('goals/complete', { agentId: known, ref }); return say('The goal is marked complete.'); } + if (verb === 'edit') { + if (!rest) return say('Type /goal edit followed by the new wording of the goal.'); + await runtime.gw.rpc('goals/edit', { agentId: known, ref, request: { objective: rest } }); + return say(`The goal now reads: "${rest}".`); + } + } catch (e) { return say(plainGoalError(e)); } + } + if (verb === 'resume') { + const plan = plans.get(chatId); + const goalPlan = plan && plan.goalStarted && plan.state === 'paused' ? { planId: plan.id } : null; + return runTurn({ ...options, goal: { action: 'resume' }, ...(goalPlan ? { planRun: goalPlan } : {}) }); + } + // A goal whose own words hold numbered points ("1. ... 2. ... 3. ...") runs point by point, each one reported. + const points = parsePoints(text); + if (points) { + const plan = plans.create(chatId, { title: points.title, steps: points.steps, request: text, source: 'goal', state: 'approved' }); + onPlan(chatId, 'approved', planView(plan)); + return runTurn({ ...options, goal: { action: 'create', objective: text }, planRun: { planId: plan.id } }); + } + // Any other text is a new goal. One unfinished goal at a time (the Harness's rule): say so in plain words. + return runTurn({ ...options, goal: { action: 'create', objective: text } }); + } + + // -- /plan ----------------------------------------------------------------------------------------------- + + /** A short answer in the chat that the page translates (the sentence is in the interface catalog, "values" fill its slots). */ + function sayKey(options, template, values = []) { + const { onFrame } = options; + onFrame({ type: 'queued', requestId: 'compact-' + randomUUID() }); + onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); + onFrame({ type: 'delta', text: fill(template, values), key: template, values }); + onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); + return { compact: true }; + } + + /** A short answer in the chat (no model): the same frames a turn sends. */ + function sayOnce(options, reply) { + const { onFrame } = options; + onFrame({ type: 'queued', requestId: `plan-${randomUUID()}` }); + onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); + onFrame({ type: 'delta', text: reply }); + onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); + return { plan: true }; + } + + /** + * "/plan <what you want>": the assistant looks around (the chat is put in Plan mode for this turn, so nothing can change), writes the + * plan, and the host sends it as a `plan` frame. Nothing runs until the person approves it. + */ + async function planCommand(options) { + const task = String(options.line ?? '').trim(); + if (!task) { + const open = plans.get(options.chatId); + return sayOnce(options, open && ['proposed', 'approved'].includes(open.state) + ? 'A plan is waiting for you above. Approve it, edit it or reject it, or type /plan followed by something else to make a new one.' + : 'Type /plan followed by what you want done, for example: /plan build a small pagoda page. I will look around and write a plan; nothing changes until you approve it.'); + } + return runTurn({ ...options, message: planPrompt(task), planTask: task, mode: 'plan' }); + } + + /** + * "/research <topic>": the assistant searches the web, opens and reads pages, and writes a short structured answer (Summary, Key findings, + * Sources). The host also sends the sources as a `research` frame before the end of the turn. Needs web search turned on. + */ + async function researchCommand(options) { + const topic = String(options.line ?? '').trim(); + if (!topic) return sayOnce(options, 'Type /research followed by what you want to know, for example: /research how do heat pumps compare with gas boilers. I will search the web, read the pages and answer with sources.'); + if (tools()?.off?.has('search')) return sayOnce(options, 'Research needs web search, which is turned off. Turn it on in Settings, Tools (DuckDuckGo needs no key), then try again.'); + return runTurn({ ...options, message: researchPrompt(topic), researchTopic: topic }); + } + + const planGone = () => new AgentUnavailable('There is no plan waiting in this chat. Ask for one with /plan followed by what you want done.', 'plan-gone'); + function planOf(chatId, planId) { + const plan = plans.get(chatId); + if (!plan || (planId && plan.id !== planId)) throw planGone(); + return plan; + } + const mustBeOpen = plan => { if (plan.state !== 'proposed' && plan.state !== 'approved') throw new AgentUnavailable('This plan has already been used. Ask for a new one with /plan.', 'plan-used'); }; + + /** A short note added to every step of the chat's plan (the Time-skip B path: where its work comes from). */ + function setPlanBriefing(chatId, text) { plans.update(chatId, p => { p.briefing = String(text ?? '').slice(0, 600); }); } + + /** The plan of a chat, or null. */ + const planState = chatId => planView(plans.get(chatId)); + + /** Approve, edit or reject the plan; instant. Approve also returns the message that carries the plan out as an ordinary turn. */ + function planControl({ chatId, planId, action, steps, title }) { + const plan = planOf(chatId, planId); + if (action === 'edit') { + mustBeOpen(plan); + const next = editedSteps(steps, plan.steps); + const t = String(title ?? '').replace(/\s+/g, ' ').trim().slice(0, 80); + plans.update(chatId, p => { p.steps = next; if (t) p.title = t; p.state = 'proposed'; }); + onPlan(chatId, 'edited', planView(plans.get(chatId))); + return { plan: planView(plans.get(chatId)) }; + } + if (action === 'approve') { + mustBeOpen(plan); + plans.update(chatId, p => { p.state = 'approved'; }); + const approved = plans.get(chatId); + onPlan(chatId, 'approved', planView(approved)); + return { plan: planView(approved), prompt: planAsPrompt(approved) }; + } + if (action === 'reject') { + mustBeOpen(plan); + plans.update(chatId, p => { p.state = 'rejected'; }); + onPlan(chatId, 'rejected', planView(plans.get(chatId))); + return { plan: planView(plans.get(chatId)) }; + } + throw new AgentUnavailable('That plan action is not known.', 'plan-action'); + } + + /** "Start as goal": each step of the plan becomes a goal step, run one after another and reported. Streams like a chat turn. */ + async function planGoal(options) { + const { chatId, planId } = options; + let plan; + try { plan = planOf(chatId, planId); } catch (e) { return sayOnce(options, e.message); } + if (modeOf(options.mode) === 'plan') return sayOnce(options, 'Plan mode only looks, so it cannot carry out a plan. Switch this chat to Manual or Bypass, then start it again.'); + if (plan.state === 'paused' && plan.goalStarted) return goalCommand({ ...options, line: 'resume' }); + try { mustBeOpen(plan); } catch (e) { return sayOnce(options, e.message); } + if (tools()?.off?.has('goals')) return sayOnce(options, 'Goals are turned off. You can turn them back on in Settings, Tools.'); + plans.update(chatId, p => { p.state = 'approved'; }); + onPlan(chatId, 'approved', planView(plans.get(chatId))); + return runTurn({ ...options, goal: { action: 'create', objective: plan.title }, planRun: { planId: plan.id, once: options.once === true } }); + } + + /** A paused plan becomes open again (a step that did not finish is tried again in a fresh session). */ + function reopenPlan(chatId) { const p = plans.get(chatId); if (p && p.state === 'paused') { plans.update(chatId, x => { x.state = 'approved'; }); onPlan(chatId, 'approved', planView(plans.get(chatId))); } } + + /** Give up on one step with a plain note (a check that cannot be done here) so the rest of the plan can go on. */ + function skipStep(chatId, index, note) { plans.update(chatId, p => { const st = p.steps[index]; if (st) { st.state = 'skipped'; st.summary = String(note ?? 'Skipped.').slice(0, 140); } if (p.state === 'paused') p.state = 'approved'; }); onPlan(chatId, 'step', planView(plans.get(chatId))); } + + /** Forget the chat's agent session (not its plan): the next turn starts a fresh one in the same folder. */ + function resetSession(chatId) { + if (chats.get(chatId)?.turn || chats.get(chatId)?.starting) throw new AgentUnavailable('This chat is still working.', 'turn-active'); + delete sessionMap[chatId]; persist(); + } + + // -- the agent's own questions ------------------------------------------------------------------------------ + + /** + * The person's answer to a question the agent asked (#4244), or a skip. The answer is checked against the questions that were asked, then sent + * to the Harness as the result of the waiting `user-questions/request`; a skip declares the question unanswerable, as before, and the model + * carries on. + */ + async function answerQuestion({ chatId, callId, answers, skip = false }) { + const sessionId = sessionMap[chatId]?.sessionId; + const key = `${sessionId}:${callId}`; + const entry = questions.get(key); + if (!entry || !rt?.hp.running) throw new AgentUnavailable('That question was already answered, or the assistant has gone on.', 'question-gone'); + const outcome = skip ? 'next' : buildAnswer(entry.items, answers); + await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome }); + questions.delete(key); + return { ok: true, skipped: !!skip }; + } + + // -- a message for a helper --------------------------------------------------------------------------------- + + /** + * The person's own words for one helper (#4749), through the Harness's `subagents/prompt`: it delivers one browser-authored message to a + * continuable child through its live parent. "steer" reaches a working helper at its next step; "queue" gives a helper that has finished + * (or is between steps) a new turn. The Harness refuses a helper that cannot take messages (a one-shot one) and a parent that is not live; + * either comes back as a plain sentence. + */ + async function messageHelper({ chatId, helperId, text, delivery = 'queue' }) { + const clean = String(text ?? '').trim().slice(0, 8000); + if (!clean) throw new AgentUnavailable('Type a few words for the helper.', 'helper-empty'); + if (!/^[\w.:@-]{1,160}$/.test(String(helperId ?? ''))) throw new AgentUnavailable('That helper is not known.', 'helper-unknown'); + const parent = sessionMap[chatId]?.sessionId; + if (!parent || !rt?.hp.running) throw new AgentUnavailable('The assistant is not running in this chat, so it cannot pass a message on. Send a message in the chat first.', 'helper-idle'); + try { + const receipt = await rt.gw.rpc('subagents/prompt', { request: { requestId: `helper-${randomUUID()}`, parentSessionId: parent, childSessionId: String(helperId), mode: 'continuable', delivery: delivery === 'steer' ? 'steer' : 'queue', content: [{ type: 'text', text: clean }] } }); + return { ok: true, messageId: receipt?.messageId ?? null, delivery: delivery === 'steer' ? 'steer' : 'queue' }; + } catch (e) { + log(`agent · message for a helper refused: ${String(e?.message ?? e).slice(0, 200)}`); + throw new AgentUnavailable(/continuable|one-shot|not.*(found|live|open)|unavailable|closed|ended/i.test(String(e?.message ?? '')) ? 'This helper cannot take a message any more. Ask the assistant in the chat to start a new one.' : 'The message could not be delivered right now. Try again in a moment.', 'helper-refused'); + } + } + + // -- messages typed while a goal runs ---------------------------------------------------------------------- + + /** Queue a message for the running goal. It is delivered between steps, or handed back to the page when the goal ends or pauses. */ + function queueMessage({ chatId, text }) { + const turn = chats.get(chatId)?.turn; + if (!turn || !turn.goalRun || turn.stopping || turn.finished) throw new AgentUnavailable('No goal is running in this chat, so there is nothing to queue behind. Send the message as usual.', 'queue-idle'); + const clean = String(text ?? '').trim().slice(0, 8000); + if (!clean) throw new AgentUnavailable('Type a few words to queue.', 'queue-empty'); + const list = queues.get(chatId) ?? []; + if (list.length >= 20) throw new AgentUnavailable('Twenty messages are already waiting. Wait for some to be delivered.', 'queue-full'); + const item = { id: randomUUID(), text: clean, at: new Date().toISOString(), deliverAt: turn.plan ? 'step' : 'end' }; + list.push(item); queues.set(chatId, list); + const message = { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }; + onQueue(chatId, queueView(chatId)); + turn.announceQueue?.({ type: 'queued-message', state: 'queued', message, queue: queueView(chatId) }); + return { message, queue: queueView(chatId) }; + } + + /** Take a queued message back (the x on it). A message already being delivered cannot be taken back. */ + function cancelQueued({ chatId, id }) { + const list = queues.get(chatId) ?? []; + const at = list.findIndex(m => m.id === id); + if (at < 0) throw new AgentUnavailable('That message was already sent or removed.', 'queue-gone'); + const [item] = list.splice(at, 1); + if (!list.length) queues.delete(chatId); + onQueue(chatId, queueView(chatId)); + chats.get(chatId)?.turn?.announceQueue?.({ type: 'queued-message', state: 'cancelled', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, queue: queueView(chatId) }); + return { queue: queueView(chatId) }; + } + + /** Messages waiting for a chat, and (after a goal ended while the page was away) the ones it should now send. */ + function takeQueue(chatId, { release = false } = {}) { + const turn = chats.get(chatId)?.turn; + const list = queueView(chatId); + if (release && !turn && list.length) { queues.delete(chatId); onQueue(chatId, []); return { queue: [], released: list.map(({ id, text }) => ({ id, text })) }; } + return { queue: list, released: [] }; + } + + /** + * The person changed the chat's mode while a turn (a goal and its helpers included) is running. The new preset + * is put on the session at once, the running turn's own bookkeeping follows, and questions already waiting are + * settled the way the new mode would have settled them: Bypass allows them, Plan rejects them. + */ + async function setMode(chatId, mode) { + const want = modeOf(mode); + const c = chats.get(chatId); + const sessionId = sessionMap[chatId]?.sessionId; + if (!rt || !sessionId) return { applied: false, mode: want, reason: 'no session yet' }; + if (c?.turn && c.turn.mode === want) return { applied: true, mode: want, settled: 0 }; + await applyMode(rt, sessionId, want); + let settled = 0; + if (c?.turn) { + c.turn.mode = want; + c.turn.projector.policy = MODE_PRESETS[want].approval; + if (want !== 'manual') { + const helpers = c.turn.children; + for (const [key, entry] of [...pending.entries()]) { + if (entry.sessionId !== sessionId && !helpers?.has(entry.sessionId)) continue; + pending.delete(key); + try { await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: want === 'bypass' ? 'allowed-once' : 'rejected' }); settled++; } catch { /* already answered */ } + } + } + } + return { applied: true, mode: want, settled }; + } + + /** Answer one pending approval. `decision` is `approve` or `deny`. */ + async function approve({ chatId, callId, decision }) { + const sessionId = sessionMap[chatId]?.sessionId; + // A helper agent's question carries the helper's session id in front of its call id. Only a helper that belongs to + // THIS chat's run can be answered from this chat. + const [maybeChild] = String(callId).split(':'); + const ownHelper = callId.includes(':') && chats.get(chatId)?.turn?.children.has(maybeChild); + const key = ownHelper ? callId : `${sessionId}:${callId}`; + // The durable `approval/asked` (which makes the card say "needs approval") and the waterfall frame + // (which makes it answerable) travel on different streams; a fast click can beat the second one. + let entry = sessionId ? pending.get(key) : null; + for (let i = 0; !entry && sessionId && i < 40; i++) { + await new Promise(r => setTimeout(r, 50)); + entry = pending.get(key); + } + if (!entry) throw new AgentUnavailable('That question is no longer waiting for an answer.', 'approval-gone'); + if (!rt?.hp.running) throw new AgentUnavailable('That question expired because the coding assistant restarted. Ask again.', 'approval-gone'); + pending.delete(key); + try { + await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: decision === 'approve' ? 'allowed-once' : 'rejected' }); + } catch (e) { + throw new AgentUnavailable('Your answer could not be delivered. Ask again.', 'approval-gone', e.message); + } + return { ok: true }; + } + + /** + * Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the + * Harness acknowledges a cancel as admitted, not as done. + */ + /** What the chat holds now and the model's window, as the context plugin measures them (null when it cannot be read). */ + async function contextOf(runtime, sessionId) { + try { + const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-context', submittedAttachments: [] }); + if (r?.result?.kind !== 'success') return null; + const v = JSON.parse(String(r.result.text)); + return Number.isFinite(v.tokens) ? { tokens: Math.round(v.tokens), window: Number(v.window) > 0 ? Math.round(v.window) : 0 } : null; + } catch { return null; } + } + + /** The decision of context-fit.mjs for the message about to be sent, or null when the model server cannot count it. */ + async function fitCheck({ runtime, route, sessionId, fresh, history, message }) { + const inst = localInstances().find(i => i.id === route.instanceId); + if (!inst || !(route.contextWindow > 0)) return null; + const carried = fresh && history.length ? withEarlierConversation(history, message) : message; + if (carried.length < COUNT_ABOVE_CHARS) return null; + const count = text => countTokens({ baseUrl: inst.baseUrl, key: inst.key, model: inst.modelId, text }); + let tokens = await count(carried); + if (tokens == null) return null; + const now = fresh ? null : await contextOf(runtime, sessionId); + const window = now?.window || route.contextWindow; + const pressure = now?.tokens ?? 0; + // Where the Harness starts summarising by itself on this window (profile.mjs: the reply keeps its room, then the headroom). + const reply = localOutputBudget(window); + const threshold = Math.floor(Math.min(window * 0.8, window - reply - compactionHeadroom(window, reply))); + let verdict = decideFit({ window, pressure, messageTokens: tokens, threshold }); + // The earlier conversation carried into a fresh session is what pushed it over: send the message alone instead. + if (verdict.action === 'too-large' && carried !== message) { + const alone = await count(message); + if (alone != null) { tokens = alone; verdict = decideFit({ window, pressure, messageTokens: alone, threshold }); } + } + return { ...verdict, tokens, window, pressure }; + } + + /** + * Summarise the older part of a chat with the Harness's /compact and say what happened. Never throws. + * ok:true carries the figures before and after; ok:false says why (nothing to summarise, busy, failed). + */ + async function compactChat(runtime, sessionId) { + const before = await contextOf(runtime, sessionId); + let result; + try { result = (await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }))?.result; } + catch (e) { return { ok: false, reason: /not.found|no such/i.test(String(e.message)) ? 'nothing' : 'failed', before, text: String(e.message ?? e) }; } + const text = String(result?.text ?? ''); + log('agent · compact: ' + (result?.kind ?? 'none') + ' ' + text.slice(0, 140)); + if (result?.kind === 'success' && /^Compacted/i.test(text)) return { ok: true, before, after: await contextOf(runtime, sessionId) }; + if (result?.kind === 'success') return { ok: false, reason: 'nothing', before, text }; + if (/active compaction|not idle/i.test(text)) return { ok: false, reason: 'busy', before, text }; + // The Harness cannot make a summary smaller than what is left when the chat holds little beyond its first prompt: that is nothing to summarise, not a failure. + const little = before && before.window > 0 && before.tokens - BASE_TOKENS < before.window * 0.25; + return { ok: false, reason: little && /useful summary|not smaller/i.test(text) ? 'nothing' : 'failed', before, text }; + } + + /** The line in the chat that explains why the context meter fell: how full it was and how full it is. */ + function summarizedNote(before, after, window) { + const w = after?.window || before?.window || window || 0; + const pct = v => Math.max(0, Math.min(100, Math.round(100 * v.tokens / w))); + const known = w > 0 && before && after; + const template = known ? FIT_TEXT.summarized : FIT_TEXT.summarizedShort; + const values = known ? [pct(before), pct(after)] : []; + return { type: 'delta', own: true, text: '\n\n' + fill(template, values), key: template, values, noteReason: 'compacted' }; + } + + /** "/compact": summarise the older messages of this chat now, and say in plain words what happened. */ + async function compactCommand(options) { + const { chatId, choice, signal } = options; + const c = chat(chatId); + const say = (template, values = []) => sayKey(options, template, values); + if (c.turn || c.starting) return say(FIT_TEXT.compactBusy); + const known = sessionMap[chatId]?.sessionId; + if (!known) return say(FIT_TEXT.noChatYet); + let runtime; + try { ({ rt: runtime } = await ensureRuntime(choice, signal)); } catch { return say(FIT_TEXT.compactFailed); } + const done = await compactChat(runtime, known); + if (done.ok) { + const note = summarizedNote(done.before, done.after, 0); + return say(note.key, note.values); + } + if (done.reason === 'busy') return say(FIT_TEXT.compactBusy); + if (done.reason === 'nothing') { + const w = done.before?.window || 0; + const pct = w > 0 && done.before ? Math.round(100 * done.before.tokens / w) : 0; + return say(pct >= 60 ? FIT_TEXT.nothingFull : FIT_TEXT.nothingToSummarize, pct >= 60 ? [pct] : []); + } + return say(FIT_TEXT.compactFailed); + } + + /** Summarise the older part of a session with the Harness's own /compact. Best effort: the next message compacts again by itself when it must. */ + async function compactSession(runtime, sessionId) { + try { + const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }); + log(`agent · compact after a stopped turn: ${r?.result?.kind ?? 'done'} ${String(r?.result?.text ?? '').slice(0, 120)}`); + } catch (e) { log(`agent · compact after a stopped turn failed: ${e.message}`); } + } + + async function stop(chatId, { waitMs = 20_000 } = {}) { + const c = chats.get(chatId); + const turn = c?.turn; + if (!turn && c?.starting) { c.cancelStart = true; return { stopped: true, ended: 'cancelled-before-start', ms: 0 }; } + if (!turn || !rt) return { stopped: false, reason: 'no active turn' }; + const t0 = Date.now(); + if (!turn.prompted) { + // The Harness has not been given the prompt yet, so there is nothing to cancel there. + turn.stopBeforePrompt = true; + const early = await Promise.race([turn.ended.promise, new Promise(r => setTimeout(() => r(null), 100))]); + if (early) return { stopped: true, ended: early.reason?.kind ?? 'aborted', ms: Date.now() - t0 }; + } + turn.stopping = true; + await pauseGoal(rt, turn.sessionId, chatId); + // Helpers first: a helper still working would otherwise report back and wake the parent again. + await Promise.allSettled([...turn.children.values()].filter(h => !h.done).map(h => rt.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: turn.sessionId, mode: 'continuable' }))); + await rt.gw.rpc('session/cancel', { request: { sessionId: turn.sessionId } }).catch(e => { if (turn.parentOpen) throw e; }); + // Nothing is running in the parent (it was waiting for its helpers): the run ends once they are all down. + if (!turn.parentOpen) { clearTimeout(turn.settleTimer); turn.settleTimer = after(300, () => { if (!turn.finished && !turn.parentOpen && [...turn.children.values()].every(h => h.done)) turn.finish(null); }); } + let timer; const result = await Promise.race([turn.ended.promise, new Promise(r => { timer = after(waitMs, () => r(null)); })]); + clearTimeout(timer); + if (!result) return { stopped: false, pending: true, reason: 'the turn is still stopping' }; + return { stopped: true, ended: result.reason?.kind ?? 'unknown', ms: Date.now() - t0 }; + } + + function pendingFor(chatId) { + const sessionId = sessionMap[chatId]?.sessionId; + const helpers = chats.get(chatId)?.turn?.children; + return [...pending.values()].filter(p => p.sessionId === sessionId || helpers?.has(p.sessionId)) + .map(p => (p.sessionId === sessionId ? p : { ...p, callId: `${p.sessionId}:${p.callId}` })).map(({ callId, tool, reason, at }) => ({ callId, tool, reason, at })); + } + + /** Every chat that has an approval waiting, for the task board: the chat, its working folder and what is waiting (same items as pendingFor). */ + function pendingAll() { + if (!pending.size) return []; + return Object.keys(sessionMap).map(chatId => ({ chatId, folder: sessionMap[chatId]?.cwd ?? null, pending: pendingFor(chatId) })).filter(c => c.pending.length); + } + + async function close() { + const r = rt; rt = null; + if (r) { r.events?.close(); r.gw.close(); await r.hp.stop(); } + } + + /** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */ + function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); } + + return { compactCommand, messageHelper, answerQuestion, goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, llmTarget, setPlanBriefing, resetSession, reopenPlan, skipStep, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, pendingAll, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, workingFolder: chatId => sessionMap[chatId]?.cwd ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) }; +} + +/** A goal that stopped by itself, in words. */ +export function plainBlocker(reason) { + if (!reason) return 'it could not go on.'; + if (reason.code === 'round-limit') return 'it worked for the most steps it was allowed. Type /goal clear, then start a new goal to go on.'; + return String(reason.message ?? 'it could not go on.'); +} + +/** What a goal run says when it ends. */ +export function goalEnding(view) { + if (view.phase === 'complete') return '\n\n*The goal is complete.*'; + if (view.phase === 'blocked') return `\n\n*The goal stopped: ${plainBlocker(view.blockedReason)}*`; + if (view.phase === 'paused') return '\n\n*The goal is paused. Type /goal resume to go on.*'; + return ''; +} + +/** A goal request the Harness refused, as a sentence. */ +export function plainGoalError(e) { + const message = String(e?.message ?? e); + if (/already|unfinished|current goal/i.test(message)) return 'This chat already has a goal that is not finished. Type /goal edit to change it, /goal clear to remove it, or /goal to see it.'; + if (/GOAL_NONE|no goal/i.test(message) || e?.code === 'goal-none') return 'There is no goal to continue. Start one with /goal followed by what you want done.'; + if (/objective/i.test(message)) return 'A goal needs a few words about what you want done, for example: /goal make every test pass.'; + return 'The goal could not be changed right now. Try again in a moment.'; +} + +/** The Harness session of a chat that existed before the agent did knows nothing; carry a bounded summary. */ +export function withEarlierConversation(history, message) { + const rows = history.filter(m => (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim()).slice(-12); + if (!rows.length) return message; + const text = rows.map(m => `${m.role}: ${m.content.length > 1500 ? `${m.content.slice(0, 1499)}…` : m.content}`).join('\n'); + return `Earlier in this conversation, before you were given tools:\n${text}\n\nCurrent message:\n${message}`; +} diff --git a/apps/host/server/agent/events.mjs b/apps/host/server/agent/events.mjs index 176eba4b36..ec7705d250 100644 --- a/apps/host/server/agent/events.mjs +++ b/apps/host/server/agent/events.mjs @@ -1,469 +1,496 @@ -/** - * Pure projections from Harness facts to the frames the chat UI already renders. - * - * No I/O here, so the mapping can be tested without an agent. The inputs are the two things a - * `session/follow` stream carries: durable session events (`tool/call`, `approval/asked`, - * `tool/result`, `turn/end`, ...) and the process-local `assistant-stream` frames (text and - * reasoning deltas, usage). - */ - -import { toolUpdate, TokenCount, fmtTokens } from './status.mjs'; -import { askFor } from './ask.mjs'; -import { FIT_TEXT, fill } from './context-fit.mjs'; -import { isContextOverflow } from './context-budget.mjs'; - -const SHELL = new Set(['pwsh', 'bash', 'job_kill', 'job_output', 'job_list']); -const WRITE = new Set(['write', 'edit']); -const READ = new Set(['read', 'glob', 'grep', 'read_image', 'working_directory', 'todo_write', 'get_goal', 'list_agents', 'skill', 'present']); - -/** Delegation tools have no card: the helper agents show as rows, and the tool's raw reply ("started subagent <id>") is not for the person. */ -export const NO_CARD = new Set(['subagent', 'subagent_fork', 'send_message', 'interrupt_agent', 'list_agents']); - -export function toolScope(name) { - if (SHELL.has(name)) return 'shell'; - if (WRITE.has(name)) return 'write'; - if (READ.has(name)) return 'read'; - return 'connected'; -} - -/** Shown on a card the mode refused (Plan, Bypass): the model's own error text would say "the user rejected". */ -export const NOT_IN_MODE = 'Not allowed in this mode. Nothing ran.'; - -const clip = (value, max) => { - const text = String(value ?? ''); - return text.length > max ? `${text.slice(0, max - 1)}…` : text; -}; - -export function parseArguments(raw) { - if (raw && typeof raw === 'object') return raw; - try { const v = JSON.parse(String(raw ?? '{}')); return v && typeof v === 'object' ? v : {}; } catch { return {}; } -} - -/** - * One plain sentence and one short detail per tool, so a card never shows raw JSON or an internal tool name as its - * explanation. Unknown tools (a connected MCP server's) fall back to a generic sentence with their arguments. - */ -const WORDS = { - read: a => ['Reads a file.', a.file_path ?? a.path], - glob: a => ['Looks for files by name.', a.pattern], - grep: a => ['Searches inside files.', a.pattern ?? a.query], - read_image: a => ['Looks at a picture.', a.file_path ?? a.path], - working_directory: () => ['Checks which folder it is working in.', ''], - todo_write: a => ['Updates its to-do list.', Array.isArray(a.todos) ? a.todos.map(t => t?.content ?? t?.title ?? '').filter(Boolean).join('; ') : ''], - skill: a => ['Uses a saved skill.', a.name ?? a.skill], - present: a => ['Shows you a result.', a.file_path ?? a.path ?? a.title], - create_goal: a => ['Sets a goal to work towards.', a.objective], - update_goal: a => ['Updates the goal.', a.objective ?? a.status ?? ''], - get_goal: () => ['Checks the current goal.', ''], - web_fetch: a => ['Opens a web page.', a.url], - web_search: a => ['Searches the web.', Array.isArray(a.queries) ? a.queries.join('; ') : a.query], - workflow: a => ['Runs a multi-step plan.', a.description ?? a.name ?? ''], - job_list: () => ['Checks the background tasks.', ''], - job_output: a => ['Reads what a background task printed.', a.job_id ?? a.id], - job_kill: a => ['Stops a background task.', a.job_id ?? a.id], - lsp: a => ['Looks up how the code fits together.', a.file_path], -}; - -/** - * What a card says it is doing, in the person's words: [while it runs, when it worked, when it failed]. The UI translates - * these fixed sentences and writes the target (a file path, the command) beside them, so a row never shows `pwsh · Ran`. - */ -const VERBS = { - write: ['Writing a file', 'Wrote a file', "Couldn't write the file"], - edit: ['Changing a file', 'Changed a file', "Couldn't change the file"], - read: ['Reading a file', 'Read a file', "Couldn't read the file"], - read_image: ['Looking at a picture', 'Looked at a picture', "Couldn't look at the picture"], - glob: ['Searching for files', 'Searched for files', "Couldn't search for files"], - grep: ['Searching inside files', 'Searched inside files', "Couldn't search inside files"], - pwsh: ['Running a command', 'Ran a command', 'The command failed'], - bash: ['Running a command', 'Ran a command', 'The command failed'], - web_fetch: ['Opening a web page', 'Opened a web page', "Couldn't open the web page"], - web_search: ['Searching the web', 'Searched the web', "Couldn't search the web"], - create_goal: ['Setting the goal', 'Set the goal', "Couldn't set the goal"], - update_goal: ['Updating the goal', 'Updated the goal', "Couldn't update the goal"], - get_goal: ['Checking the goal', 'Checked the goal', "Couldn't check the goal"], - skill: ['Loading your skill', 'Loaded your skill', "Couldn't load the skill"], - todo_write: ['Updating its to-do list', 'Updated its to-do list', "Couldn't update its to-do list"], - present: ['Showing you a result', 'Showed you a result', "Couldn't show the result"], - working_directory: ['Checking the folder', 'Checked the folder', "Couldn't check the folder"], - job_list: ['Checking background tasks', 'Checked background tasks', "Couldn't check background tasks"], - job_output: ['Reading a background task', 'Read a background task', "Couldn't read the background task"], - job_kill: ['Stopping a background task', 'Stopped a background task', "Couldn't stop the background task"], -}; -const GENERIC_VERBS = ['Using a tool', 'Used a tool', 'The tool failed']; -/** The browser tool server's tools (Settings -> Tools): the card says what happened to the page, not the tool's internal name. */ -const BROWSER_VERBS = { - browser_navigate: ['Opening a page in the browser', 'Opened a page in the browser', "Couldn't open the page"], - browser_click: ['Clicking on the page', 'Clicked on the page', "Couldn't click on the page"], - browser_hover: ['Pointing at the page', 'Pointed at the page', "Couldn't point at the page"], - browser_type: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], - browser_fill_form: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], - browser_press_key: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], - browser_snapshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"], - browser_take_screenshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"], - browser_evaluate: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"], - browser_run_code: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"], - browser_wait_for: ['Waiting for the page', 'Waited for the page', "Couldn't wait for the page"], - browser_navigate_back: ['Going back a page', 'Went back a page', "Couldn't go back"], - browser_tabs: ['Managing browser tabs', 'Managed browser tabs', "Couldn't manage the browser tabs"], - browser_close: ['Closing the browser page', 'Closed the browser page', "Couldn't close the browser page"], -}; -const BROWSER_GENERIC = ['Using the browser', 'Used the browser', 'The browser step failed']; -const BROWSER_PREFIX = 'mcp__browser__', INSTRUCTIONS_PREFIX = 'mcp__strata-instructions__', COMMANDS_PREFIX = 'mcp__strata-commands__'; -/** The person's own tool's name as they wrote it (spaces for underscores). */ -const ownToolName = name => name.replace(/^mcp__strata-(?:instructions|commands)__/, '').replace(/_/g, ' '); -/** The three sentences (running, worked, failed) for a tool, and whether this is one the app knows by name. */ -function verbsFor(name) { - if (VERBS[name]) return { verbs: VERBS[name], known: true }; - if (name.startsWith(BROWSER_PREFIX)) return { verbs: BROWSER_VERBS[name.slice(BROWSER_PREFIX.length)] ?? BROWSER_GENERIC, known: true }; - if (name.startsWith(INSTRUCTIONS_PREFIX)) return { verbs: ['Reading your instructions', 'Read your instructions', "Couldn't read your instructions"], known: true }; - if (name.startsWith(COMMANDS_PREFIX)) return { verbs: ['Running your tool', 'Ran your tool', 'Your tool failed'], known: true }; - return { verbs: GENERIC_VERBS, known: false }; -} - -/** The sentence for a card in this state (the first for a running or waiting card). */ -export function toolVerb(name, state) { - const v = verbsFor(name).verbs; - return state === 'error' ? v[2] : state === 'done' ? v[1] : v[0]; -} -/** The ToolCall fields the card needs, from one Harness tool call. */ -export function presentTool({ callId, name, args, reason = null }) { - const scope = toolScope(name); - const words = WORDS[name]?.(args); - const preview = scope === 'shell' && !words ? args.command ?? '' - : scope === 'write' ? args.file_path ?? args.path ?? args.filePath ?? '' - : words ? words[1] ?? '' : name.startsWith(INSTRUCTIONS_PREFIX) || name.startsWith(COMMANDS_PREFIX) ? ownToolName(name) : /^mcp__browser__browser_(evaluate|run_code)$/.test(name) ? '' : args.file_path ?? args.path ?? args.pattern ?? args.url ?? args.element ?? args.query ?? args.text ?? args.action ?? (Object.keys(args).length ? JSON.stringify(args) : ''); - const effect = reason ?? (words ? words[0] : scope === 'shell' ? (args.description ?? 'Runs a command in the workspace.') - : scope === 'write' ? 'Changes a file in the workspace.' - : scope === 'read' ? 'Reads from the workspace.' : 'Uses a connected tool.'); - return { id: callId, name, args, preview: clip(preview, 600), effect: clip(effect, 400), scope, verb: toolVerb(name, 'running'), target: clip(verbsFor(name).known ? preview : name, 300), ask: askFor(name, args, typeof args.description === 'string' ? args.description : null) }; -} - -/** A tool's failure in plain words, or null when there is nothing better than the original text. */ -export function plainToolError(text) { - const t = String(text ?? ''); - if (/non-public ip|enotfound|getaddrinfo|web fetch failed|econnrefused|econnreset|etimedout|fetch failed/i.test(t)) return 'That web page could not be opened. Check the address and your internet connection.'; - if (/invalid arguments|missing required property|not a declared property/i.test(t)) return 'The assistant asked this tool in the wrong way. It will usually try again.'; - if (/unknown or no longer available/i.test(t)) return 'That skill is not available.'; - if (/cannot modify|must (?:first )?be read|has not been read|changed since/i.test(t)) return 'The file could not be changed. It may need to be read again first, or it changed in the meantime.'; - if (/sandbox|access denied|permission denied|eacces|eperm/i.test(t)) return 'The computer did not allow this.'; - if (/timed out|timeout/i.test(t)) return 'This took too long and was stopped.'; - if (/does not declare image input|image input/i.test(t)) return 'Picture reading is off for this model. Open Models and turn on Read pictures for it (load it again if it is a local model), or choose a model that reads pictures.'; - if (/extension|not a supported image|cannot read/i.test(t)) return 'This file could not be read.'; - return null; -} - -/** A failed tool's result: the plain sentence first, the original text after it (the card's disclosure is the Details). */ -export function withPlain(raw) { - const plain = plainToolError(raw); - return plain ? `${plain}\n\nDetails: ${raw.replace(/^Error:\s*/, '')}` : raw; -} - -/** What a launch that printed nothing proves, and no more. */ -export const LAUNCHED_TEXT = 'The command finished without an error, so the program was started. Strata cannot confirm that a window or page actually opened.'; - -/** A command whose whole point is to open something: it has no output to show when it worked. */ -const LAUNCH = /(^|[\s;|&(])(start-process|start|invoke-item|ii|explorer(?:\.exe)?|xdg-open|open|notepad(?:\.exe)?|code)(?=[\s;|&)]|$)/i; - -/** - * A command that succeeded and printed nothing says so in words (the card used to show "(no output)" under a "Ran" that could not - * tell the person whether anything happened). Opening a folder or a window is not something a command can prove it did, so the - * sentence says only what is known. - */ -export function outcomeText(tool, text, args = {}) { - if (tool === 'pwsh' || tool === 'bash') { - // In the read-only modes PowerShell runs in Constrained Language Mode and complains about the Harness's own output-encoding line: - // noise appended after a command that worked. It says nothing about the command, so it is not shown. - text = text.replace(/\r?\n?\[stderr\]\r?\n(?:Cannot create type\. Only core types are supported in this language mode\.[\s\S]*?CannotCreateTypeConstrainedLanguage\s*)+$/, ''); - if (!text.trim()) text = '(no output)'; - } - // Starting a program or opening a folder prints nothing when it worked, and also when it did not (a browser given a file:// address, a - // program that closed at once). T9 / #3576: the card used to say "was opened", and the model repeated it ("I previewed it in a browser to - // confirm it renders"). It says what is known: the command returned without an error. - if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim()) && LAUNCH.test(String(args?.command ?? ''))) return LAUNCHED_TEXT; - if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim())) return 'The command finished without any error. It printed nothing, so there is nothing more to show.'; - return text; -} - -/** Text of a tool-result message, bounded. */ -export function resultText(message) { - const parts = Array.isArray(message?.content) ? message.content : []; - const text = parts.map(p => (p?.type === 'text' ? p.text : p?.type ? `[${p.type}]` : '')).join('\n').trim(); - return clip(text || '(no output)', 4000); -} - -/** - * Accumulates one turn's frames. Feed it follow items; it returns the frames to send. - * It owns the per-turn state (tool cards, usage, text emitted) so the I/O layer stays thin. - */ -export class TurnProjector { - /** - * `policy` is the session's approval policy for this turn. Under `never` the Harness rejects an ask by itself, so - * no question ever reaches the person: the card goes straight from running to denied, without a moment where it - * offers Approve and Deny buttons that would do nothing. - */ - constructor({ startedAt = Date.now(), policy = 'ask', window = 0 } = {}) { - this.startedAt = startedAt; - this.window = Number(window) || 0; // the model's window, for the figures in the line that says the chat was summarised - this.summarizing = false; - this.policy = policy; - this.byPolicy = new Set(); // callIds the approval policy rejected without asking - this.tools = new Map(); // callId -> { card, calledAt } - this.tokensIn = 0; - this.tokensOut = 0; - this.contextTokens = null; // the LAST model request's prompt + reply: what the context holds now (the sums above count every request again) - this.usageSeen = false; - this.firstTokenAt = null; - this.streams = new Map(); // attemptId -> { first, last, chunks, chars }: the time a model request actually spent producing - this.lastStats = 0; - this.emittedText = new Map(); // attemptId -> chars sent live - this.ended = null; // the turn/end reason, once seen - this.denied = new Set(); // callIds a human or the policy rejected - this.asked = new Map(); // approval id -> callId - this.onStatus = null; // (update) => void: what the assistant is doing now (status.mjs); set by the bridge - this.reasoning = new TokenCount(); - this.composing = new Map(); // callId -> { name, head, bytes }: a tool call the model is still writing - this.running = []; // callIds of tools that are running, oldest first - } - - #status(update) { if (this.onStatus) this.onStatus(update); } - - /** After a tool ends: another tool still running is what is happening, otherwise the model is working out what to do next. */ - #afterTool() { - const id = this.running.at(-1); - const card = id ? this.tools.get(id)?.card : null; - if (card) this.#status(toolUpdate('tool', 'tool', card.name, card.args, {}, { args: { tool: card.name, verb: card.verb, target: card.target } })); - else this.#status({ phase: 'waiting', code: 'model-working', text: 'Working out the next step…' }); - } - - #card(callId, patch) { - const entry = this.tools.get(callId); - if (!entry) return null; - entry.card = { ...entry.card, ...patch }; - entry.card.verb = toolVerb(entry.card.name, entry.card.state); - return { type: 'agent-tool', tool: entry.card }; - } - - /* The speed shown while a reply streams, and after it: everything the model generated (reasoning and tool calls included) over the time its - requests spent producing it, not over the whole turn (tool runs and the wait for the prompt are not decoding). One stream per model - request; tokens are one per streamed chunk, or characters / 4 when a server batches. */ - #produced(attemptId, text, out) { - const now = Date.now(); - const s = this.streams.get(attemptId) ?? { first: now, last: now, chunks: 0, chars: 0 }; - s.last = now; s.chunks += 1; s.chars += text.length; - this.streams.set(attemptId, s); - if (now - this.lastStats < 400) return; - const { tokens, seconds } = this.decode(); - if (seconds < 0.5) return; - this.lastStats = now; - out.push({ type: 'stats', tokensOut: tokens, tps: Number((tokens / seconds).toFixed(1)), source: 'stream' }); - } - - decode() { - let tokens = 0, ms = 0; - for (const s of this.streams.values()) { tokens += s.chars / Math.max(1, s.chunks) < 8 ? s.chunks : Math.ceil(s.chars / 4); ms += s.last - s.first; } - return { tokens, seconds: ms / 1000 }; - } - - /** Process one `session/follow` item (event or assistant-stream). Returns frames. */ - consume(item) { - const out = []; - if (item.type === 'assistant-stream') { - const f = item.frame; - if (f.type === 'chunk') { - const c = f.chunk; - if (c.type === 'text-delta' && c.text) { - this.firstTokenAt ??= Date.now(); - this.#produced(f.attemptId, c.text, out); - this.emittedAny = true; - this.#status({ phase: 'answering', code: 'answering', text: 'Writing the answer…' }); - this.emittedText.set(f.attemptId, (this.emittedText.get(f.attemptId) ?? 0) + c.text.length); - out.push({ type: 'delta', text: c.text }); - } else if (c.type === 'reasoning-delta' && c.text) { - this.firstTokenAt ??= Date.now(); - this.#produced(f.attemptId, c.text, out); - // The count is for the model's current thinking (each model request starts again from zero), not the whole turn. - if (this.reasoningAttempt !== f.attemptId) { this.reasoning = new TokenCount(); this.reasoningAttempt = f.attemptId; } - this.reasoning.add(c.text); - this.#status({ phase: 'thinking', code: 'thinking', text: `Thinking… ${fmtTokens(this.reasoning.tokens)} tokens`, key: 'Thinking… {0} tokens', values: [fmtTokens(this.reasoning.tokens)], tokens: this.reasoning.tokens, args: { tokens: this.reasoning.tokens } }); - out.push({ type: 'reasoning', text: c.text }); - } else if (c.type === 'tool-call-delta' && c.id) { - // The model is writing a tool call. For a big file this is the long silent part: nothing else arrives until it is finished. - const call = this.composing.get(c.id) ?? { name: c.name ?? '', head: '', bytes: 0 }; - if (c.name) call.name = c.name; - const piece = String(c.argumentsDelta ?? ''); - // Writing a tool call (a whole file, say) is decoding too: its tokens are in the engine's output count, so its time belongs in the speed. - this.#produced(f.attemptId, piece, out); - call.bytes += piece.length; - if (call.head.length < 4000) call.head += piece; - this.composing.set(c.id, call); - if (call.name && !NO_CARD.has(call.name)) { - const raw = (/"(?:file_path|path|filePath)"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(call.head) ?? /"url"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(call.head))?.[1]; - let target = raw; try { if (raw !== undefined) target = JSON.parse('"' + raw + '"'); } catch { /* a half-written escape: show it as it is */ } - const args = target ? { file_path: target, url: target } : {}; - this.#status(toolUpdate('preparing', 'preparing-tool', call.name, args, { bytes: call.bytes }, { args: { tool: call.name, verb: toolVerb(call.name, 'running'), target: target ?? '', bytes: call.bytes } })); - } - } else if (c.type === 'usage' && c.usage) { - this.usageSeen = true; - // The Harness counts input, cache reads and cache writes apart (a prompt the server's conversation cache already held is `cacheReadTokens`, - // not `inputTokens`): the prompt of a request is all three. Counting only `inputTokens` made a long agent chat look nearly empty (0%). - const prompt = (Number(c.usage.inputTokens) || 0) + (Number(c.usage.cacheReadTokens) || 0) + (Number(c.usage.cacheWriteTokens) || 0); - this.tokensIn += prompt; - this.tokensOut += Number(c.usage.outputTokens) || 0; - this.contextTokens = prompt + (Number(c.usage.outputTokens) || 0); - out.push({ type: 'context', contextTokens: this.contextTokens, contextMax: this.window || undefined }); - } - } - return out; - } - if (item.type !== 'event') return out; - const e = item.event; - const d = e.data ?? {}; - switch (e.type) { - case 'assistant/message': { - // Reconcile a text the live frames did not fully carry (a socket gap), never duplicating it. - const live = [...this.emittedText.values()].pop() ?? 0; - const text = (d.message?.content ?? []).filter(p => p.type === 'text').map(p => p.text).join(''); - if (text.length > live && live > 0) out.push({ type: 'delta', text: text.slice(live) }); - this.emittedText.clear(); - break; - } - case 'tool/call': { - if (NO_CARD.has(d.name)) break; - const args = parseArguments(d.arguments); - const card = { ...presentTool({ callId: d.callId, name: d.name, args }), state: 'running' }; - this.tools.set(d.callId, { card, calledAt: e.time }); - this.composing.delete(d.callId); - this.running.push(d.callId); - this.#status(toolUpdate('tool', 'tool', d.name, args, {}, { args: { tool: d.name, verb: card.verb, target: card.target } })); - out.push({ type: 'agent-tool', tool: card }); - break; - } - case 'approval/asked': { - if (!d.callId) break; - this.asked.set(d.id, d.callId); - if (this.policy === 'never') break; - const entry = this.tools.get(d.callId); - this.#status({ phase: 'approval', code: 'waiting-approval', text: 'Waiting for your answer…', args: { tool: entry?.card.name ?? '' } }); - const patch = { state: 'proposed', effect: clip(d.reason ?? entry?.card.effect ?? 'Needs your approval.', 400) }; - const frame = this.#card(d.callId, patch); - if (frame) out.push(frame); - break; - } - case 'approval/decided': { - const callId = this.asked.get(d.id); - if (callId && this.policy === 'never' && d.outcome !== 'allowed-once') { - this.byPolicy.add(callId); this.denied.add(callId); - const frame = this.#card(callId, { state: 'denied', result: NOT_IN_MODE }); - if (frame) out.push(frame); - break; - } - this.#afterTool(); - const frame = callId ? this.decide(callId, d.outcome) : null; - if (frame) out.push(frame); - break; - } - case 'tool/result': { - const callId = d.message?.toolCallId; - const entry = this.tools.get(callId); - if (!entry) break; - this.running = this.running.filter(id => id !== callId); - this.#afterTool(); - const isError = d.message?.isError === true; - const denied = this.denied.has(callId); - const frame = this.#card(callId, { - state: denied ? 'denied' : isError ? 'error' : 'done', - // A card the person (or the mode) refused keeps its plain sentence; the model's own error text ("the user rejected ...") is not for them. - result: this.byPolicy.has(callId) ? NOT_IN_MODE : denied ? (entry.card.result ?? 'Denied. Nothing ran.') : isError ? withPlain(resultText(d.message)) : outcomeText(entry.card.name, resultText(d.message), entry.card.args), - durationMs: Math.max(0, (e.time ?? 0) - entry.calledAt), - }); - if (frame) out.push(frame); - break; - } - case 'compaction/start': - // The Harness is summarising the older messages to make room: say so while it does, and again (once) when it is done. - this.summarizing = true; - this.#status({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] }); - break; - case 'compaction/end': - if (!this.summarizing) break; - this.summarizing = false; - this.#afterTool(); - if (!d.error) { - const before = this.window > 0 && this.contextTokens ? Math.min(100, Math.round(100 * this.contextTokens / this.window)) : null; - const text = before === null ? FIT_TEXT.summarizedShort : FIT_TEXT.summarizedWas; - const values = before === null ? [] : [before]; - out.push({ type: 'delta', own: true, text: '\n\n' + fill(text, values), key: text, values, noteReason: 'compacted' }); - } - break; - case 'turn/start': - // The parent woke up again (a helper finished and reported back): the message goes on, as a new paragraph. - this.ended = null; - if (this.emittedAny) out.push({ type: 'delta', text: '\n\n' }); - break; - case 'turn/end': - this.ended = d.reason ?? { kind: 'completed' }; - break; - default: - break; - } - return out; - } - - /** An approval was decided. `outcome` is the Harness vocabulary. */ - decide(callId, outcome) { - if (!this.tools.has(callId)) return null; - // `approved` is what lets the card say "Approved" (the user answered) rather than "Ran" (it never asked). - if (outcome === 'allowed-once') return this.#card(callId, { state: 'running', approved: true }); - this.denied.add(callId); - return this.#card(callId, { state: 'denied', result: outcome === 'rejected' ? 'Denied. Nothing ran.' : outcome === 'cancelled' ? 'Cancelled. Nothing ran.' : 'No one could answer this request, so nothing ran.' }); - } - - /** The terminal frames for a finished turn. */ - finish({ model, contextMax, engine = null } = {}) { - const reason = this.ended ?? { kind: 'interrupted' }; - const durationMs = Date.now() - this.startedAt; - const usage = this.usageSeen - ? { tokensIn: this.tokensIn, tokensOut: this.tokensOut, usageSource: 'reported' } - : { tokensIn: null, tokensOut: null, usageSource: 'unavailable' }; - const decoded = this.decode(); - const generated = this.usageSeen && this.tokensOut > 0 ? this.tokensOut : decoded.tokens; - // Answer speed, one definition everywhere: all the tokens the model produced over its decode time. The engine's own figures (the ones the - // Monitor shows) when the bridge could read them; otherwise the stream's own span. A very short reply has almost no span, so its decode time - // is then the time from its first chunk to the end of the turn (only when no tool ran, so no tool time is in it): the number is still shown. - let tps = null; - if (engine?.tps > 0) tps = engine.tps; - else if (generated > 0 && decoded.seconds >= 0.3) tps = Number((generated / decoded.seconds).toFixed(1)); - else if (generated > 0 && this.tools.size === 0 && this.firstTokenAt && Date.now() - this.firstTokenAt >= 50) tps = Number((generated / ((Date.now() - this.firstTokenAt) / 1000)).toFixed(1)); - const promptTps = engine?.promptTps > 0 ? engine.promptTps : null; - const base = { durationMs, ttftMs: this.firstTokenAt ? this.firstTokenAt - this.startedAt : null, model, contextMax, tps, ...(promptTps ? { promptTps } : {}), contextTokens: this.contextTokens }; - switch (reason.kind) { - case 'completed': - return [{ type: 'done', ...base, ...usage, finishReason: 'stop' }]; - case 'max-tokens': - return [{ type: 'done', ...base, ...usage, finishReason: 'length' }]; - case 'aborted': - return [{ type: 'done', ...base, ...usage, finishReason: 'aborted', cancelled: true }]; - case 'error': - return [{ type: 'error', message: friendlyFailure(reason.error), code: isContextFailure(reason.error) ? 'CONTEXT_WINDOW_EXCEEDED' : reason.error?.code ?? 'UNKNOWN', ...(isContextFailure(reason.error) ? { key: FIT_TEXT.full, details: String(reason.error?.message ?? '') } : {}) }]; - case 'blocked': - return [{ type: 'error', message: 'The agent stopped because this turn was blocked by policy.', code: 'BLOCKED' }]; - default: - return [{ type: 'error', message: 'The agent turn was interrupted before it finished.', code: 'INTERRUPTED' }]; - } - } -} - -/** Whether a failure is the model server saying the conversation does not fit its window (its code, or the engine's own words). */ -export function isContextFailure(failure) { - return isContextOverflow(failure) || /context window|too long for|exceeds the context/i.test(String(failure?.message ?? '')); -} - -/** A model-route failure in words a user can act on. */ -export function friendlyFailure(failure) { - const message = String(failure?.message ?? 'The model request failed.'); - if (isContextFailure(failure)) return FIT_TEXT.full; - if (/ECONNREFUSED|fetch failed|connect/i.test(message)) return `The model is not reachable. ${clip(message, 200)}`; - if (/401|403|credential|api key/i.test(message)) return 'The model rejected the credentials. Check the connection in Settings.'; - return clip(message, 400); -} +/** + * Pure projections from Harness facts to the frames the chat UI already renders. + * + * No I/O here, so the mapping can be tested without an agent. The inputs are the two things a + * `session/follow` stream carries: durable session events (`tool/call`, `approval/asked`, + * `tool/result`, `turn/end`, ...) and the process-local `assistant-stream` frames (text and + * reasoning deltas, usage). + */ + +import { toolUpdate, TokenCount, fmtTokens } from './status.mjs'; +import { askFor } from './ask.mjs'; +import { FIT_TEXT, fill } from './context-fit.mjs'; +import { isContextOverflow } from './context-budget.mjs'; +import { ToolDraft, cutCalls } from './reply-cut.mjs'; + +const SHELL = new Set(['pwsh', 'bash', 'job_kill', 'job_output', 'job_list']); +const WRITE = new Set(['write', 'edit']); +const READ = new Set(['read', 'glob', 'grep', 'read_image', 'working_directory', 'todo_write', 'get_goal', 'list_agents', 'skill', 'present']); + +/** Delegation tools have no card: the helper agents show as rows, and the tool's raw reply ("started subagent <id>") is not for the person. */ +export const NO_CARD = new Set(['subagent', 'subagent_fork', 'send_message', 'interrupt_agent', 'list_agents']); + +export function toolScope(name) { + if (SHELL.has(name)) return 'shell'; + if (WRITE.has(name)) return 'write'; + if (READ.has(name)) return 'read'; + return 'connected'; +} + +/** Shown on a card the mode refused (Plan, Bypass): the model's own error text would say "the user rejected". */ +export const NOT_IN_MODE = 'Not allowed in this mode. Nothing ran.'; + +const clip = (value, max) => { + const text = String(value ?? ''); + return text.length > max ? `${text.slice(0, max - 1)}…` : text; +}; + +export function parseArguments(raw) { + if (raw && typeof raw === 'object') return raw; + try { const v = JSON.parse(String(raw ?? '{}')); return v && typeof v === 'object' ? v : {}; } catch { return {}; } +} + +/** + * One plain sentence and one short detail per tool, so a card never shows raw JSON or an internal tool name as its + * explanation. Unknown tools (a connected MCP server's) fall back to a generic sentence with their arguments. + */ +const WORDS = { + read: a => ['Reads a file.', a.file_path ?? a.path], + glob: a => ['Looks for files by name.', a.pattern], + grep: a => ['Searches inside files.', a.pattern ?? a.query], + read_image: a => ['Looks at a picture.', a.file_path ?? a.path], + working_directory: () => ['Checks which folder it is working in.', ''], + todo_write: a => ['Updates its to-do list.', Array.isArray(a.todos) ? a.todos.map(t => t?.content ?? t?.title ?? '').filter(Boolean).join('; ') : ''], + skill: a => ['Uses a saved skill.', a.name ?? a.skill], + present: a => ['Shows you a result.', a.file_path ?? a.path ?? a.title], + create_goal: a => ['Sets a goal to work towards.', a.objective], + update_goal: a => ['Updates the goal.', a.objective ?? a.status ?? ''], + get_goal: () => ['Checks the current goal.', ''], + web_fetch: a => ['Opens a web page.', a.url], + web_search: a => ['Searches the web.', Array.isArray(a.queries) ? a.queries.join('; ') : a.query], + workflow: a => ['Runs a multi-step plan.', a.description ?? a.name ?? ''], + job_list: () => ['Checks the background tasks.', ''], + job_output: a => ['Reads what a background task printed.', a.job_id ?? a.id], + job_kill: a => ['Stops a background task.', a.job_id ?? a.id], + lsp: a => ['Looks up how the code fits together.', a.file_path], +}; + +/** + * What a card says it is doing, in the person's words: [while it runs, when it worked, when it failed]. The UI translates + * these fixed sentences and writes the target (a file path, the command) beside them, so a row never shows `pwsh · Ran`. + */ +const VERBS = { + write: ['Writing a file', 'Wrote a file', "Couldn't write the file"], + edit: ['Changing a file', 'Changed a file', "Couldn't change the file"], + read: ['Reading a file', 'Read a file', "Couldn't read the file"], + read_image: ['Looking at a picture', 'Looked at a picture', "Couldn't look at the picture"], + glob: ['Searching for files', 'Searched for files', "Couldn't search for files"], + grep: ['Searching inside files', 'Searched inside files', "Couldn't search inside files"], + pwsh: ['Running a command', 'Ran a command', 'The command failed'], + bash: ['Running a command', 'Ran a command', 'The command failed'], + web_fetch: ['Opening a web page', 'Opened a web page', "Couldn't open the web page"], + web_search: ['Searching the web', 'Searched the web', "Couldn't search the web"], + create_goal: ['Setting the goal', 'Set the goal', "Couldn't set the goal"], + update_goal: ['Updating the goal', 'Updated the goal', "Couldn't update the goal"], + get_goal: ['Checking the goal', 'Checked the goal', "Couldn't check the goal"], + skill: ['Loading your skill', 'Loaded your skill', "Couldn't load the skill"], + todo_write: ['Updating its to-do list', 'Updated its to-do list', "Couldn't update its to-do list"], + present: ['Showing you a result', 'Showed you a result', "Couldn't show the result"], + working_directory: ['Checking the folder', 'Checked the folder', "Couldn't check the folder"], + job_list: ['Checking background tasks', 'Checked background tasks', "Couldn't check background tasks"], + job_output: ['Reading a background task', 'Read a background task', "Couldn't read the background task"], + job_kill: ['Stopping a background task', 'Stopped a background task', "Couldn't stop the background task"], +}; +const GENERIC_VERBS = ['Using a tool', 'Used a tool', 'The tool failed']; +/** The browser tool server's tools (Settings -> Tools): the card says what happened to the page, not the tool's internal name. */ +const BROWSER_VERBS = { + browser_navigate: ['Opening a page in the browser', 'Opened a page in the browser', "Couldn't open the page"], + browser_click: ['Clicking on the page', 'Clicked on the page', "Couldn't click on the page"], + browser_hover: ['Pointing at the page', 'Pointed at the page', "Couldn't point at the page"], + browser_type: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], + browser_fill_form: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], + browser_press_key: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], + browser_snapshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"], + browser_take_screenshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"], + browser_evaluate: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"], + browser_run_code: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"], + browser_wait_for: ['Waiting for the page', 'Waited for the page', "Couldn't wait for the page"], + browser_navigate_back: ['Going back a page', 'Went back a page', "Couldn't go back"], + browser_tabs: ['Managing browser tabs', 'Managed browser tabs', "Couldn't manage the browser tabs"], + browser_close: ['Closing the browser page', 'Closed the browser page', "Couldn't close the browser page"], +}; +const BROWSER_GENERIC = ['Using the browser', 'Used the browser', 'The browser step failed']; +const BROWSER_PREFIX = 'mcp__browser__', INSTRUCTIONS_PREFIX = 'mcp__strata-instructions__', COMMANDS_PREFIX = 'mcp__strata-commands__'; +/** The person's own tool's name as they wrote it (spaces for underscores). */ +const ownToolName = name => name.replace(/^mcp__strata-(?:instructions|commands)__/, '').replace(/_/g, ' '); +/** The three sentences (running, worked, failed) for a tool, and whether this is one the app knows by name. */ +function verbsFor(name) { + if (VERBS[name]) return { verbs: VERBS[name], known: true }; + if (name.startsWith(BROWSER_PREFIX)) return { verbs: BROWSER_VERBS[name.slice(BROWSER_PREFIX.length)] ?? BROWSER_GENERIC, known: true }; + if (name.startsWith(INSTRUCTIONS_PREFIX)) return { verbs: ['Reading your instructions', 'Read your instructions', "Couldn't read your instructions"], known: true }; + if (name.startsWith(COMMANDS_PREFIX)) return { verbs: ['Running your tool', 'Ran your tool', 'Your tool failed'], known: true }; + return { verbs: GENERIC_VERBS, known: false }; +} + +/** The sentence for a card in this state (the first for a running or waiting card). */ +export function toolVerb(name, state) { + const v = verbsFor(name).verbs; + return state === 'error' ? v[2] : state === 'done' ? v[1] : v[0]; +} +/** The ToolCall fields the card needs, from one Harness tool call. */ +export function presentTool({ callId, name, args, reason = null }) { + const scope = toolScope(name); + const words = WORDS[name]?.(args); + const preview = scope === 'shell' && !words ? args.command ?? '' + : scope === 'write' ? args.file_path ?? args.path ?? args.filePath ?? '' + : words ? words[1] ?? '' : name.startsWith(INSTRUCTIONS_PREFIX) || name.startsWith(COMMANDS_PREFIX) ? ownToolName(name) : /^mcp__browser__browser_(evaluate|run_code)$/.test(name) ? '' : args.file_path ?? args.path ?? args.pattern ?? args.url ?? args.element ?? args.query ?? args.text ?? args.action ?? (Object.keys(args).length ? JSON.stringify(args) : ''); + const effect = reason ?? (words ? words[0] : scope === 'shell' ? (args.description ?? 'Runs a command in the workspace.') + : scope === 'write' ? 'Changes a file in the workspace.' + : scope === 'read' ? 'Reads from the workspace.' : 'Uses a connected tool.'); + return { id: callId, name, args, preview: clip(preview, 600), effect: clip(effect, 400), scope, verb: toolVerb(name, 'running'), target: clip(verbsFor(name).known ? preview : name, 300), ask: askFor(name, args, typeof args.description === 'string' ? args.description : null) }; +} + +/** A tool's failure in plain words, or null when there is nothing better than the original text. */ +export function plainToolError(text) { + const t = String(text ?? ''); + if (/non-public ip|enotfound|getaddrinfo|web fetch failed|econnrefused|econnreset|etimedout|fetch failed/i.test(t)) return 'That web page could not be opened. Check the address and your internet connection.'; + if (/invalid arguments|missing required property|not a declared property/i.test(t)) return 'The assistant asked this tool in the wrong way. It will usually try again.'; + if (/unknown or no longer available/i.test(t)) return 'That skill is not available.'; + if (/cannot modify|must (?:first )?be read|has not been read|changed since/i.test(t)) return 'The file could not be changed. It may need to be read again first, or it changed in the meantime.'; + if (/sandbox|access denied|permission denied|eacces|eperm/i.test(t)) return 'The computer did not allow this.'; + if (/timed out|timeout/i.test(t)) return 'This took too long and was stopped.'; + if (/does not declare image input|image input/i.test(t)) return 'Picture reading is off for this model. Open Models and turn on Read pictures for it (load it again if it is a local model), or choose a model that reads pictures.'; + if (/extension|not a supported image|cannot read/i.test(t)) return 'This file could not be read.'; + return null; +} + +/** A failed tool's result: the plain sentence first, the original text after it (the card's disclosure is the Details). */ +export function withPlain(raw) { + const plain = plainToolError(raw); + return plain ? `${plain}\n\nDetails: ${raw.replace(/^Error:\s*/, '')}` : raw; +} + +/** What a launch that printed nothing proves, and no more. */ +export const LAUNCHED_TEXT = 'The command finished without an error, so the program was started. Strata cannot confirm that a window or page actually opened.'; + +/** A command whose whole point is to open something: it has no output to show when it worked. */ +const LAUNCH = /(^|[\s;|&(])(start-process|start|invoke-item|ii|explorer(?:\.exe)?|xdg-open|open|notepad(?:\.exe)?|code)(?=[\s;|&)]|$)/i; + +/** + * A command that succeeded and printed nothing says so in words (the card used to show "(no output)" under a "Ran" that could not + * tell the person whether anything happened). Opening a folder or a window is not something a command can prove it did, so the + * sentence says only what is known. + */ +export function outcomeText(tool, text, args = {}) { + if (tool === 'pwsh' || tool === 'bash') { + // In the read-only modes PowerShell runs in Constrained Language Mode and complains about the Harness's own output-encoding line: + // noise appended after a command that worked. It says nothing about the command, so it is not shown. + text = text.replace(/\r?\n?\[stderr\]\r?\n(?:Cannot create type\. Only core types are supported in this language mode\.[\s\S]*?CannotCreateTypeConstrainedLanguage\s*)+$/, ''); + if (!text.trim()) text = '(no output)'; + } + // Starting a program or opening a folder prints nothing when it worked, and also when it did not (a browser given a file:// address, a + // program that closed at once). T9 / #3576: the card used to say "was opened", and the model repeated it ("I previewed it in a browser to + // confirm it renders"). It says what is known: the command returned without an error. + if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim()) && LAUNCH.test(String(args?.command ?? ''))) return LAUNCHED_TEXT; + if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim())) return 'The command finished without any error. It printed nothing, so there is nothing more to show.'; + return text; +} + +/** Text of a tool-result message, bounded. */ +export function resultText(message) { + const parts = Array.isArray(message?.content) ? message.content : []; + const text = parts.map(p => (p?.type === 'text' ? p.text : p?.type ? `[${p.type}]` : '')).join('\n').trim(); + return clip(text || '(no output)', 4000); +} + +/** + * Accumulates one turn's frames. Feed it follow items; it returns the frames to send. + * It owns the per-turn state (tool cards, usage, text emitted) so the I/O layer stays thin. + */ +export class TurnProjector { + /** + * `policy` is the session's approval policy for this turn. Under `never` the Harness rejects an ask by itself, so + * no question ever reaches the person: the card goes straight from running to denied, without a moment where it + * offers Approve and Deny buttons that would do nothing. + */ + constructor({ startedAt = Date.now(), policy = 'ask', window = 0 } = {}) { + this.startedAt = startedAt; + this.window = Number(window) || 0; // the model's window, for the figures in the line that says the chat was summarised + this.summarizing = false; + this.policy = policy; + this.byPolicy = new Set(); // callIds the approval policy rejected without asking + this.tools = new Map(); // callId -> { card, calledAt } + this.tokensIn = 0; + this.tokensOut = 0; + this.contextTokens = null; // the LAST model request's prompt + reply: what the context holds now (the sums above count every request again) + this.usageSeen = false; + this.firstTokenAt = null; + this.streams = new Map(); // attemptId -> { first, last, chunks, chars }: the time a model request actually spent producing + this.lastStats = 0; + this.emittedText = new Map(); // attemptId -> chars sent live + this.ended = null; // the turn/end reason, once seen + this.denied = new Set(); // callIds a human or the policy rejected + this.asked = new Map(); // approval id -> callId + this.onStatus = null; // (update) => void: what the assistant is doing now (status.mjs); set by the bridge + this.reasoning = new TokenCount(); + this.composing = new Map(); // callId -> ToolDraft: a tool call the model is still writing (still here at a cut reply = it was lost) + this.lastOutput = 0; // tokens the LAST model request produced + this.running = []; // callIds of tools that are running, oldest first + } + + #status(update) { if (this.onStatus) this.onStatus(update); } + + /** After a tool ends: another tool still running is what is happening, otherwise the model is working out what to do next. */ + #afterTool() { + const id = this.running.at(-1); + const card = id ? this.tools.get(id)?.card : null; + if (card) this.#status(toolUpdate('tool', 'tool', card.name, card.args, {}, { args: { tool: card.name, verb: card.verb, target: card.target } })); + else this.#status({ phase: 'waiting', code: 'model-working', text: 'Working out the next step…' }); + } + + #card(callId, patch) { + const entry = this.tools.get(callId); + if (!entry) return null; + entry.card = { ...entry.card, ...patch }; + entry.card.verb = toolVerb(entry.card.name, entry.card.state); + return { type: 'agent-tool', tool: entry.card }; + } + + /* The speed shown while a reply streams, and after it: everything the model generated (reasoning and tool calls included) over the time its + requests spent producing it, not over the whole turn (tool runs and the wait for the prompt are not decoding). One stream per model + request; tokens are one per streamed chunk, or characters / 4 when a server batches. */ + #produced(attemptId, text, out) { + const now = Date.now(); + const s = this.streams.get(attemptId) ?? { first: now, last: now, chunks: 0, chars: 0 }; + s.last = now; s.chunks += 1; s.chars += text.length; + this.streams.set(attemptId, s); + if (now - this.lastStats < 400) return; + const { tokens, seconds } = this.decode(); + if (seconds < 0.5) return; + this.lastStats = now; + out.push({ type: 'stats', tokensOut: tokens, tps: Number((tokens / seconds).toFixed(1)), source: 'stream' }); + } + + decode() { + let tokens = 0, ms = 0; + for (const s of this.streams.values()) { tokens += s.chars / Math.max(1, s.chunks) < 8 ? s.chunks : Math.ceil(s.chars / 4); ms += s.last - s.first; } + return { tokens, seconds: ms / 1000 }; + } + + /** Process one `session/follow` item (event or assistant-stream). Returns frames. */ + consume(item) { + const out = []; + if (item.type === 'assistant-stream') { + const f = item.frame; + if (f.type === 'chunk') { + const c = f.chunk; + if (c.type === 'text-delta' && c.text) { + this.firstTokenAt ??= Date.now(); + this.#produced(f.attemptId, c.text, out); + this.emittedAny = true; + this.#status({ phase: 'answering', code: 'answering', text: 'Writing the answer…' }); + this.emittedText.set(f.attemptId, (this.emittedText.get(f.attemptId) ?? 0) + c.text.length); + out.push({ type: 'delta', text: c.text }); + } else if (c.type === 'reasoning-delta' && c.text) { + this.firstTokenAt ??= Date.now(); + this.#produced(f.attemptId, c.text, out); + // The count is for the model's current thinking (each model request starts again from zero), not the whole turn. + if (this.reasoningAttempt !== f.attemptId) { this.reasoning = new TokenCount(); this.reasoningAttempt = f.attemptId; } + this.reasoning.add(c.text); + this.#status({ phase: 'thinking', code: 'thinking', text: `Thinking… ${fmtTokens(this.reasoning.tokens)} tokens`, key: 'Thinking… {0} tokens', values: [fmtTokens(this.reasoning.tokens)], tokens: this.reasoning.tokens, args: { tokens: this.reasoning.tokens } }); + out.push({ type: 'reasoning', text: c.text }); + } else if (c.type === 'tool-call-delta' && c.id) { + // The model is writing a tool call. For a big file this is the long silent part: nothing else arrives until it is finished. + const call = this.composing.get(c.id) ?? new ToolDraft(c.id, c.name ?? ''); + if (c.name) call.name = c.name; + const piece = String(c.argumentsDelta ?? ''); + // Writing a tool call (a whole file, say) is decoding too: its tokens are in the engine's output count, so its time belongs in the speed. + this.#produced(f.attemptId, piece, out); + call.add(piece); + this.composing.set(c.id, call); + if (call.name && !NO_CARD.has(call.name)) { + const target = call.target; + const args = target ? { file_path: target, url: target } : {}; + this.#status(toolUpdate('preparing', 'preparing-tool', call.name, args, { bytes: call.bytes }, { args: { tool: call.name, verb: toolVerb(call.name, 'running'), target: target ?? '', bytes: call.bytes } })); + // The live data path of a file being written (AGENT-LOST): the name, a growing size and the tail of the text, at most five times a second. + const now = Date.now(); + if (now - call.at >= 200) { call.at = now; out.push(call.frame({ scope: toolScope(call.name), verb: toolVerb(call.name, 'running') })); } + } + } else if (c.type === 'usage' && c.usage) { + this.usageSeen = true; + // The Harness counts input, cache reads and cache writes apart (a prompt the server's conversation cache already held is `cacheReadTokens`, + // not `inputTokens`): the prompt of a request is all three. Counting only `inputTokens` made a long agent chat look nearly empty (0%). + const prompt = (Number(c.usage.inputTokens) || 0) + (Number(c.usage.cacheReadTokens) || 0) + (Number(c.usage.cacheWriteTokens) || 0); + this.tokensIn += prompt; + this.tokensOut += Number(c.usage.outputTokens) || 0; + this.lastOutput = Number(c.usage.outputTokens) || 0; + this.contextTokens = prompt + (Number(c.usage.outputTokens) || 0); + out.push({ type: 'context', contextTokens: this.contextTokens, contextMax: this.window || undefined }); + } + } + return out; + } + if (item.type !== 'event') return out; + const e = item.event; + const d = e.data ?? {}; + switch (e.type) { + case 'assistant/message': { + // Reconcile a text the live frames did not fully carry (a socket gap), never duplicating it. + const live = [...this.emittedText.values()].pop() ?? 0; + const text = (d.message?.content ?? []).filter(p => p.type === 'text').map(p => p.text).join(''); + if (text.length > live && live > 0) out.push({ type: 'delta', text: text.slice(live) }); + this.emittedText.clear(); + break; + } + case 'tool/call': { + if (NO_CARD.has(d.name)) break; + const args = parseArguments(d.arguments); + const card = { ...presentTool({ callId: d.callId, name: d.name, args }), state: 'running' }; + this.tools.set(d.callId, { card, calledAt: e.time }); + const draft = this.composing.get(d.callId); + this.composing.delete(d.callId); + if (draft && draft.bytes > 0 && !NO_CARD.has(d.name)) out.push(draft.frame({ done: true })); + this.running.push(d.callId); + this.#status(toolUpdate('tool', 'tool', d.name, args, {}, { args: { tool: d.name, verb: card.verb, target: card.target } })); + out.push({ type: 'agent-tool', tool: card }); + break; + } + case 'approval/asked': { + if (!d.callId) break; + this.asked.set(d.id, d.callId); + if (this.policy === 'never') break; + const entry = this.tools.get(d.callId); + this.#status({ phase: 'approval', code: 'waiting-approval', text: 'Waiting for your answer…', args: { tool: entry?.card.name ?? '' } }); + const patch = { state: 'proposed', effect: clip(d.reason ?? entry?.card.effect ?? 'Needs your approval.', 400) }; + const frame = this.#card(d.callId, patch); + if (frame) out.push(frame); + break; + } + case 'approval/decided': { + const callId = this.asked.get(d.id); + if (callId && this.policy === 'never' && d.outcome !== 'allowed-once') { + this.byPolicy.add(callId); this.denied.add(callId); + const frame = this.#card(callId, { state: 'denied', result: NOT_IN_MODE }); + if (frame) out.push(frame); + break; + } + this.#afterTool(); + const frame = callId ? this.decide(callId, d.outcome) : null; + if (frame) out.push(frame); + break; + } + case 'tool/result': { + const callId = d.message?.toolCallId; + const entry = this.tools.get(callId); + if (!entry) break; + this.running = this.running.filter(id => id !== callId); + this.#afterTool(); + const isError = d.message?.isError === true; + const denied = this.denied.has(callId); + const frame = this.#card(callId, { + state: denied ? 'denied' : isError ? 'error' : 'done', + // A card the person (or the mode) refused keeps its plain sentence; the model's own error text ("the user rejected ...") is not for them. + result: this.byPolicy.has(callId) ? NOT_IN_MODE : denied ? (entry.card.result ?? 'Denied. Nothing ran.') : isError ? withPlain(resultText(d.message)) : outcomeText(entry.card.name, resultText(d.message), entry.card.args), + durationMs: Math.max(0, (e.time ?? 0) - entry.calledAt), + }); + if (frame) out.push(frame); + break; + } + case 'compaction/start': + // The Harness is summarising the older messages to make room: say so while it does, and again (once) when it is done. + this.summarizing = true; + this.#status({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] }); + break; + case 'compaction/end': + if (!this.summarizing) break; + this.summarizing = false; + this.#afterTool(); + if (!d.error) { + const before = this.window > 0 && this.contextTokens ? Math.min(100, Math.round(100 * this.contextTokens / this.window)) : null; + const text = before === null ? FIT_TEXT.summarizedShort : FIT_TEXT.summarizedWas; + const values = before === null ? [] : [before]; + out.push({ type: 'delta', own: true, text: '\n\n' + fill(text, values), key: text, values, noteReason: 'compacted' }); + } + break; + case 'turn/start': + // The parent woke up again (a helper finished and reported back): the message goes on, as a new paragraph. + this.ended = null; + if (this.emittedAny) out.push({ type: 'delta', text: '\n\n' }); + break; + case 'turn/end': + this.ended = d.reason ?? { kind: 'completed' }; + break; + default: + break; + } + return out; + } + + /** An approval was decided. `outcome` is the Harness vocabulary. */ + decide(callId, outcome) { + if (!this.tools.has(callId)) return null; + // `approved` is what lets the card say "Approved" (the user answered) rather than "Ran" (it never asked). + if (outcome === 'allowed-once') return this.#card(callId, { state: 'running', approved: true }); + this.denied.add(callId); + return this.#card(callId, { state: 'denied', result: outcome === 'rejected' ? 'Denied. Nothing ran.' : outcome === 'cancelled' ? 'Cancelled. Nothing ran.' : 'No one could answer this request, so nothing ran.' }); + } + + /** A reply the model could not finish (the turn ended on the length limit): what it was writing, so nothing is lost without a word. */ + cut() { + return { tokens: this.lastOutput, calls: cutCalls(this.composing.values()) }; + } + + /** The agent was asked to carry on: the calls it lost are not pending any more. */ + clearCut() { const frames = this.#dropDrafts(); this.ended = null; return frames; } + + /** Frames that take the writing cards of calls that will never be whole off the page (the reply was cut, or the turn ended). */ + #dropDrafts() { + const frames = [...this.composing.values()].filter(d => d.bytes > 0 && !NO_CARD.has(d.name)).map(d => d.frame({ done: true, lost: true })); + this.composing.clear(); + return frames; + } + + /** The terminal frames for a finished turn. */ + finish(options = {}) { + const cutInfo = this.ended?.kind === 'max-tokens' ? this.cut() : null; + const dropped = this.#dropDrafts(); + return [...dropped, ...this.#finished(options, cutInfo)]; + } + + #finished({ model, contextMax, engine = null } = {}, cutInfo = null) { + const reason = this.ended ?? { kind: 'interrupted' }; + const durationMs = Date.now() - this.startedAt; + const usage = this.usageSeen + ? { tokensIn: this.tokensIn, tokensOut: this.tokensOut, usageSource: 'reported' } + : { tokensIn: null, tokensOut: null, usageSource: 'unavailable' }; + const decoded = this.decode(); + const generated = this.usageSeen && this.tokensOut > 0 ? this.tokensOut : decoded.tokens; + // Answer speed, one definition everywhere: all the tokens the model produced over its decode time. The engine's own figures (the ones the + // Monitor shows) when the bridge could read them; otherwise the stream's own span. A very short reply has almost no span, so its decode time + // is then the time from its first chunk to the end of the turn (only when no tool ran, so no tool time is in it): the number is still shown. + let tps = null; + if (engine?.tps > 0) tps = engine.tps; + else if (generated > 0 && decoded.seconds >= 0.3) tps = Number((generated / decoded.seconds).toFixed(1)); + else if (generated > 0 && this.tools.size === 0 && this.firstTokenAt && Date.now() - this.firstTokenAt >= 50) tps = Number((generated / ((Date.now() - this.firstTokenAt) / 1000)).toFixed(1)); + const promptTps = engine?.promptTps > 0 ? engine.promptTps : null; + const base = { durationMs, ttftMs: this.firstTokenAt ? this.firstTokenAt - this.startedAt : null, model, contextMax, tps, ...(promptTps ? { promptTps } : {}), contextTokens: this.contextTokens }; + switch (reason.kind) { + case 'completed': + return [{ type: 'done', ...base, ...usage, finishReason: 'stop' }]; + case 'max-tokens': + return [{ type: 'done', ...base, ...usage, finishReason: 'length', cut: cutInfo }]; + case 'aborted': + return [{ type: 'done', ...base, ...usage, finishReason: 'aborted', cancelled: true }]; + case 'error': + return [{ type: 'error', message: friendlyFailure(reason.error), code: isContextFailure(reason.error) ? 'CONTEXT_WINDOW_EXCEEDED' : reason.error?.code ?? 'UNKNOWN', ...(isContextFailure(reason.error) ? { key: FIT_TEXT.full, details: String(reason.error?.message ?? '') } : {}) }]; + case 'blocked': + return [{ type: 'error', message: 'The agent stopped because this turn was blocked by policy.', code: 'BLOCKED' }]; + default: + return [{ type: 'error', message: 'The agent turn was interrupted before it finished.', code: 'INTERRUPTED' }]; + } + } +} + +/** Whether a failure is the model server saying the conversation does not fit its window (its code, or the engine's own words). */ +export function isContextFailure(failure) { + return isContextOverflow(failure) || /context window|too long for|exceeds the context/i.test(String(failure?.message ?? '')); +} + +/** A model-route failure in words a user can act on. */ +export function friendlyFailure(failure) { + const message = String(failure?.message ?? 'The model request failed.'); + if (isContextFailure(failure)) return FIT_TEXT.full; + if (/ECONNREFUSED|fetch failed|connect/i.test(message)) return `The model is not reachable. ${clip(message, 200)}`; + if (/401|403|credential|api key/i.test(message)) return 'The model rejected the credentials. Check the connection in Settings.'; + return clip(message, 400); +} diff --git a/apps/host/server/agent/plugins/strata-context.mjs b/apps/host/server/agent/plugins/strata-context.mjs index 589e0fd065..a33f8d6b2d 100644 --- a/apps/host/server/agent/plugins/strata-context.mjs +++ b/apps/host/server/agent/plugins/strata-context.mjs @@ -1,160 +1,205 @@ -/** - * Strata's context plugin for the Harness (plain ESM, loaded by absolute path from the profile, like strata-gate and strata-models). - * - * What it fixes (2026-10-22 hands-on test, Gyro-S at 64K): - * 1. Compaction decided from the Harness's own price of the conversation, 4 characters a token. Code, logs and JSON are about twice as - * dense, so a chat the engine had read as 59,048 tokens was priced at 31,794 and compaction started far too late. Here the token meter - * is calibrated by what the model server reports for each answer (its real prompt size): the measured size is exact, and what was - * added since is priced with the density that measurement showed. Automatic compaction and the manual /compact both measure through - * the token meter, so both read the same number as the context meter in the app. - * 2. The summarising request itself could be bigger than the window ("/compact" sent a 66,507-token prompt to a 65,536 window). The - * summary is now asked for in pieces that fit: a message bigger than a piece is cut for the request (the conversation keeps it until - * the summary replaces it), the pieces are summarised one after the other, each building on the summary before it, and a piece the - * server still refuses is halved and tried again. - * - * How. It wraps `tokenMeter.measure` and `llm.stream` in place, once each (the same way strata-models wraps the subagent tools). Only a - * request the Harness marks `purpose: 'compaction'` is touched in `llm.stream`. Nothing in the Harness is rewritten: a Harness update - * that renames either leaves compaction as it was, and the test that runs the real Harness fails. - */ -import { densityOf, estimateMessage, estimateTools, isContextOverflow, MAX_DENSITY, pressureNow, promptTokensOf, splitMessages, summaryBudget, usageOfEvent, WINDOW_SLACK, withSummaryLanguage } from '../context-budget.mjs'; - -export const name = 'strata-context'; -export const inject = ['tokenMeter', 'llm']; - -/** Real prompt measurements per session: { real, estimated } for the last answer the model server reported. */ -const samples = new WeakMap(); -const bySessionId = new Map(); -const wrapped = new WeakSet(); -/** Densities that made a summary request fail on this server, per session id (the next request starts from a more careful one). */ -const careful = new Map(); - -export function apply(ctx) { - const meter = ctx.tokenMeter; - const llm = ctx.llm; - const log = (level, text) => { try { ctx.logger?.[level]?.(`strata-context: ${text}`); } catch { /* logging never blocks */ } }; - - // 1. The measured size of the prompt, from the model server's own report for each answer. - if (meter && typeof meter.measure === 'function' && !wrapped.has(meter)) { - wrapped.add(meter); - const original = meter.measure; - meter.measure = function measure(session, requestHeader) { - const m = original.call(this, session, requestHeader); - const sample = samples.get(session); - if (!sample) return m; - const now = m.surfaceTokens + estimateTools(requestHeader ?? session.requestHeader?.()); - const total = Math.max(m.totalTokens, pressureNow({ sample, now })); - if (total <= m.totalTokens) return m; - const density = densityOf(sample.real, sample.estimated); - return { ...m, totalTokens: total, nodes: m.nodes.map(n => ({ ...n, tokens: Math.ceil(n.tokens * density) })) }; - }; - ctx.on('session/event', (session, event) => { - if (event.type !== 'assistant/message') return; - const real = promptTokensOf(usageOfEvent(event)); - if (!(real > 0)) return; - try { - // The request that was just answered saw the conversation without this answer: its price is the surface before the answer's node. - const m = original.call(meter, session); - const heuristic = m.nodes.reduce((n, x) => n + (x.seq === event.seq ? 0 : x.heuristicTokens), 0); - const estimated = heuristic + estimateTools(session.requestHeader?.()); - if (!(estimated > 0)) return; - const sample = { real, estimated }; - samples.set(session, sample); - if (session.id) bySessionId.set(String(session.id), sample); - } catch (e) { log('warn', `could not record a measurement: ${e.message}`); } - }); - } - - // 2. A summary request that fits the window. - if (llm && typeof llm.stream === 'function' && !wrapped.has(llm)) { - wrapped.add(llm); - const original = llm.stream; - llm.stream = function stream(options) { - if (options?.purpose !== 'compaction') return original.call(this, options); - return summaryStream.call(this, options, original); - }; - } - - // The host asks, with /strata-context, how much of the window the chat holds right now: the same measured number compaction decides on - // (JSON in the command's text: { tokens, window }). Before a message goes out, and after /compact, so the person is told true figures. - ctx.inject(['commands'], (commandCtx) => { - commandCtx.commands.register({ - definitionId: 'strata-context', - name: 'strata-context', - description: 'Reports how many tokens the conversation holds now and the size of the model window', - handler: async (invocation) => { - try { - const session = invocation.agent.session; - const tokens = meter.measure(session).totalTokens; - const config = session.requestHeader?.()?.config; - let window = 0; - if (config) window = (await llm.resolveModelInfo(config.provider, config.model))?.context?.contextWindow ?? 0; - return { kind: 'success', text: JSON.stringify({ tokens, window }) }; - } catch (e) { return { kind: 'error', text: `strata-context: ${e.message}` }; } - }, - }); - }); - - /** A finished stream: its chunks, the text it wrote and why it ended. */ - async function drain(iterable) { - let text = '', finish = null; - const chunks = []; - for await (const chunk of iterable) { - chunks.push(chunk); - if (chunk.type === 'text-delta') text += chunk.text ?? ''; - else if (chunk.type === 'finish') finish = chunk.reason; - } - return { text, finish, chunks }; - } - const refusedForSize = finish => finish?.kind === 'error' && isContextOverflow(finish.failure ?? finish); - - async function* summaryStream(options, original) { - options = { ...options, messages: withSummaryLanguage(options.messages) }; // #4750: the summary follows the conversation's language - let window = 0; - try { window = (await llm.resolveModelInfo(options.provider, options.model, options.signal))?.context?.contextWindow ?? 0; } catch { window = 0; } - const messages = options.messages ?? []; - const key = String(options.sessionId ?? ''); - const summaryTokens = options.maxTokens ?? 4096; - if (!(window > 0) || messages.length < 2) { yield* original.call(this, options); return; } - const own = bySessionId.get(key); - let density = Math.max(careful.get(key) ?? 1, own ? densityOf(own.real, own.estimated) : 1); - const price = list => list.reduce((n, m) => n + estimateMessage(m), 0) * density; - const limit = window - summaryTokens - WINDOW_SLACK; - // The whole request fits by this price: ask as the Harness would (the model server's cache of the conversation is reused). - if (price(messages) + estimateTools({ tools: options.tools }) * density <= limit) { - const first = await drain(original.call(this, options)); - if (!refusedForSize(first.finish)) { for (const chunk of first.chunks) yield chunk; return; } - density = Math.min(MAX_DENSITY, density * 1.6); - careful.set(key, density); - log('warn', 'the summary request did not fit the window; asking in pieces'); - } - // In pieces. The instruction is the last message; the system prompt, when there is one, the first. - const instruction = messages[messages.length - 1]; - const system = messages[0]?.role === 'system' ? messages[0] : null; - const body = messages.slice(system ? 1 : 0, -1); - let tools = options.tools; - if (tools && estimateTools({ tools }) * density > window / 3) tools = undefined; // a long tool list only describes tools: the summary does not need it - const fixed = (system ? estimateMessage(system) : 0) * density + estimateTools({ tools }) * density + estimateMessage(instruction) * density; - let budget = summaryBudget({ window, summaryTokens: summaryTokens * 2, systemTokens: fixed, instructionTokens: 0 }); - for (let attempt = 0; ; attempt++) { - const runs = splitMessages(body, Math.max(1024, budget), density); - log('info', `summarising ${body.length} messages in ${runs.length} piece(s) for a ${window}-token window (density ${density.toFixed(2)}, about ${Math.round(budget)} tokens a piece)`); - let failed = null, summary = ''; - for (let i = 0; i < runs.length && !failed; i++) { - options.signal?.throwIfAborted?.(); - const carried = summary ? [{ role: 'user', content: [{ type: 'text', text: `<compacted-summary>\n${summary}\n</compacted-summary>` }] }] : []; - const { tools: _drop, ...rest } = options; - const piece = { ...rest, ...(tools ? { tools } : {}), messages: [...(system ? [system] : []), ...carried, ...runs[i], instruction] }; - const { text, finish, chunks } = await drain(original.call(this, piece)); - if (refusedForSize(finish)) { failed = finish; break; } - // The last piece's answer is the summary the Harness reads; a piece that ended in another error ends the request the same way. - if (i === runs.length - 1 || finish?.kind === 'error' || finish?.kind === 'aborted') { for (const chunk of chunks) yield chunk; return; } - summary = text; - } - if (!failed || attempt >= 3) throw Object.assign(new Error(failed?.failure?.message ?? 'the summary request does not fit the window'), { code: 'CONTEXT_WINDOW_EXCEEDED' }); - density = Math.min(MAX_DENSITY, density * 1.6); - careful.set(key, density); - budget = Math.max(1024, budget / 2); - log('warn', `a piece did not fit; asking again with pieces of about ${Math.round(budget)} tokens`); - } - } -} +/** + * Strata's context plugin for the Harness (plain ESM, loaded by absolute path from the profile, like strata-gate and strata-models). + * + * What it fixes (2026-10-22 hands-on test, Gyro-S at 64K): + * 1. Compaction decided from the Harness's own price of the conversation, 4 characters a token. Code, logs and JSON are about twice as + * dense, so a chat the engine had read as 59,048 tokens was priced at 31,794 and compaction started far too late. Here the token meter + * is calibrated by what the model server reports for each answer (its real prompt size): the measured size is exact, and what was + * added since is priced with the density that measurement showed. Automatic compaction and the manual /compact both measure through + * the token meter, so both read the same number as the context meter in the app. + * 2. The summarising request itself could be bigger than the window ("/compact" sent a 66,507-token prompt to a 65,536 window). The + * summary is now asked for in pieces that fit: a message bigger than a piece is cut for the request (the conversation keeps it until + * the summary replaces it), the pieces are summarised one after the other, each building on the summary before it, and a piece the + * server still refuses is halved and tried again. + * + * How. It wraps `tokenMeter.measure` and `llm.stream` in place, once each (the same way strata-models wraps the subagent tools). Only a + * request the Harness marks `purpose: 'compaction'` is touched in `llm.stream`. Nothing in the Harness is rewritten: a Harness update + * that renames either leaves compaction as it was, and the test that runs the real Harness fails. + */ +import { replyCap } from '../reply-cut.mjs'; +import { densityOf, estimateMessage, estimateTools, isContextOverflow, MAX_DENSITY, pressureNow, promptTokensOf, splitMessages, summaryBudget, usageOfEvent, WINDOW_SLACK, withSummaryLanguage } from '../context-budget.mjs'; + +export const name = 'strata-context'; + +/** The routes the host writes for models on this computer (profile.mjs): `strata-local`, `strata-local-<id>`, and their `~s<budget>` copies. */ +const isLocalRoute = provider => typeof provider === 'string' && provider.startsWith('strata-local'); +export const inject = ['tokenMeter', 'llm']; + +/** Real prompt measurements per session: { real, estimated } for the last answer the model server reported. */ +const samples = new WeakMap(); +const bySessionId = new Map(); +const wrapped = new WeakSet(); +/** Densities that made a summary request fail on this server, per session id (the next request starts from a more careful one). */ +const careful = new Map(); + +export function apply(ctx) { + const meter = ctx.tokenMeter; + const llm = ctx.llm; + const log = (level, text) => { try { ctx.logger?.[level]?.(`strata-context: ${text}`); } catch { /* logging never blocks */ } }; + + // 1. The measured size of the prompt, from the model server's own report for each answer. + if (meter && typeof meter.measure === 'function' && !wrapped.has(meter)) { + wrapped.add(meter); + const original = meter.measure; + meter.measure = function measure(session, requestHeader) { + const m = original.call(this, session, requestHeader); + const sample = samples.get(session); + if (!sample) return m; + const now = m.surfaceTokens + estimateTools(requestHeader ?? session.requestHeader?.()); + const total = Math.max(m.totalTokens, pressureNow({ sample, now })); + if (total <= m.totalTokens) return m; + const density = densityOf(sample.real, sample.estimated); + return { ...m, totalTokens: total, nodes: m.nodes.map(n => ({ ...n, tokens: Math.ceil(n.tokens * density) })) }; + }; + ctx.on('session/event', (session, event) => { + if (event.type !== 'assistant/message') return; + const real = promptTokensOf(usageOfEvent(event)); + if (!(real > 0)) return; + try { + // The request that was just answered saw the conversation without this answer: its price is the surface before the answer's node. + const m = original.call(meter, session); + const heuristic = m.nodes.reduce((n, x) => n + (x.seq === event.seq ? 0 : x.heuristicTokens), 0); + const estimated = heuristic + estimateTools(session.requestHeader?.()); + if (!(estimated > 0)) return; + const sample = { real, estimated }; + samples.set(session, sample); + if (session.id) bySessionId.set(String(session.id), sample); + } catch (e) { log('warn', `could not record a measurement: ${e.message}`); } + }); + } + + // 2. A summary request that fits the window. + if (llm && typeof llm.stream === 'function' && !wrapped.has(llm)) { + wrapped.add(llm); + const original = llm.stream; + llm.stream = function stream(options) { + if (options?.purpose !== 'compaction') return original.call(this, options); + return summaryStream.call(this, options, original); + }; + } + + // 3. A reply that has room to finish (AGENT-LOST, 11-01). The output budget in the profile is what the Harness's compaction sets aside for a + // reply (30 percent of the window; it reads it from the request header), and the same number was also the ceiling of every request: a thinking + // model that wrote a 15K-token file after 9K tokens of thinking was cut inside the tool call at 19,660, the unfinished call was dropped and the + // turn ended with no file and no word. The header (and so compaction) stays as it is; the request that goes to the model server may produce up + // to half the window, at most 64K tokens (replyCap), and pi-ai still clamps it to what the window has left after the prompt. The agent loop + // dispatches through the adapter's `streamWithSnapshot`, after the loop has checked the request against its header, so that is where the ceiling + // is raised, once per adapter, the first time a local route is prepared. A Harness that renames it leaves the ceiling as it was (the test that + // runs the real Harness fails). + if (llm && typeof llm.prepareCall === 'function' && !wrapped.has(llm.prepareCall)) { + const original = llm.prepareCall; + const raised = new WeakSet(); + const prepare = async function prepareCall(config, signal, configure) { + try { raiseReplyCeiling(config?.provider, raised); } catch (e) { log('warn', `could not raise the reply ceiling: ${e.message}`); } + return original.call(this, config, signal, configure); + }; + wrapped.add(prepare); + llm.prepareCall = prepare; + } + function raiseReplyCeiling(provider, raised) { + if (!isLocalRoute(provider)) return; + const adapter = llm.adapters?.get?.(provider)?.adapter; + if (!adapter || raised.has(adapter) || typeof adapter.streamWithSnapshot !== 'function' || typeof adapter.modelOf !== 'function') return; + raised.add(adapter); + const stream = adapter.streamWithSnapshot; + adapter.streamWithSnapshot = function streamWithSnapshot(options, snapshot) { + let next = options; + try { + if (isLocalRoute(options?.provider)) { + const model = this.modelOf(snapshot, options.provider, options.model); + const asked = options.maxTokens ?? model.maxTokens ?? 0; + // Only the agent's own reply budget is raised: a summary or a title asks for far less and keeps what it asked. + if (model.contextWindow > 0 && asked >= Math.floor(model.contextWindow * 0.25)) { + const cap = replyCap(model.contextWindow, asked); + if (cap > asked) next = { ...options, maxTokens: cap }; + } + } + } catch { next = options; } + return stream.call(this, next, snapshot); + }; + } + + // The host asks, with /strata-context, how much of the window the chat holds right now: the same measured number compaction decides on + // (JSON in the command's text: { tokens, window }). Before a message goes out, and after /compact, so the person is told true figures. + ctx.inject(['commands'], (commandCtx) => { + commandCtx.commands.register({ + definitionId: 'strata-context', + name: 'strata-context', + description: 'Reports how many tokens the conversation holds now and the size of the model window', + handler: async (invocation) => { + try { + const session = invocation.agent.session; + const tokens = meter.measure(session).totalTokens; + const config = session.requestHeader?.()?.config; + let window = 0; + if (config) window = (await llm.resolveModelInfo(config.provider, config.model))?.context?.contextWindow ?? 0; + return { kind: 'success', text: JSON.stringify({ tokens, window }) }; + } catch (e) { return { kind: 'error', text: `strata-context: ${e.message}` }; } + }, + }); + }); + + /** A finished stream: its chunks, the text it wrote and why it ended. */ + async function drain(iterable) { + let text = '', finish = null; + const chunks = []; + for await (const chunk of iterable) { + chunks.push(chunk); + if (chunk.type === 'text-delta') text += chunk.text ?? ''; + else if (chunk.type === 'finish') finish = chunk.reason; + } + return { text, finish, chunks }; + } + const refusedForSize = finish => finish?.kind === 'error' && isContextOverflow(finish.failure ?? finish); + + async function* summaryStream(options, original) { + options = { ...options, messages: withSummaryLanguage(options.messages) }; // #4750: the summary follows the conversation's language + let window = 0; + try { window = (await llm.resolveModelInfo(options.provider, options.model, options.signal))?.context?.contextWindow ?? 0; } catch { window = 0; } + const messages = options.messages ?? []; + const key = String(options.sessionId ?? ''); + const summaryTokens = options.maxTokens ?? 4096; + if (!(window > 0) || messages.length < 2) { yield* original.call(this, options); return; } + const own = bySessionId.get(key); + let density = Math.max(careful.get(key) ?? 1, own ? densityOf(own.real, own.estimated) : 1); + const price = list => list.reduce((n, m) => n + estimateMessage(m), 0) * density; + const limit = window - summaryTokens - WINDOW_SLACK; + // The whole request fits by this price: ask as the Harness would (the model server's cache of the conversation is reused). + if (price(messages) + estimateTools({ tools: options.tools }) * density <= limit) { + const first = await drain(original.call(this, options)); + if (!refusedForSize(first.finish)) { for (const chunk of first.chunks) yield chunk; return; } + density = Math.min(MAX_DENSITY, density * 1.6); + careful.set(key, density); + log('warn', 'the summary request did not fit the window; asking in pieces'); + } + // In pieces. The instruction is the last message; the system prompt, when there is one, the first. + const instruction = messages[messages.length - 1]; + const system = messages[0]?.role === 'system' ? messages[0] : null; + const body = messages.slice(system ? 1 : 0, -1); + let tools = options.tools; + if (tools && estimateTools({ tools }) * density > window / 3) tools = undefined; // a long tool list only describes tools: the summary does not need it + const fixed = (system ? estimateMessage(system) : 0) * density + estimateTools({ tools }) * density + estimateMessage(instruction) * density; + let budget = summaryBudget({ window, summaryTokens: summaryTokens * 2, systemTokens: fixed, instructionTokens: 0 }); + for (let attempt = 0; ; attempt++) { + const runs = splitMessages(body, Math.max(1024, budget), density); + log('info', `summarising ${body.length} messages in ${runs.length} piece(s) for a ${window}-token window (density ${density.toFixed(2)}, about ${Math.round(budget)} tokens a piece)`); + let failed = null, summary = ''; + for (let i = 0; i < runs.length && !failed; i++) { + options.signal?.throwIfAborted?.(); + const carried = summary ? [{ role: 'user', content: [{ type: 'text', text: `<compacted-summary>\n${summary}\n</compacted-summary>` }] }] : []; + const { tools: _drop, ...rest } = options; + const piece = { ...rest, ...(tools ? { tools } : {}), messages: [...(system ? [system] : []), ...carried, ...runs[i], instruction] }; + const { text, finish, chunks } = await drain(original.call(this, piece)); + if (refusedForSize(finish)) { failed = finish; break; } + // The last piece's answer is the summary the Harness reads; a piece that ended in another error ends the request the same way. + if (i === runs.length - 1 || finish?.kind === 'error' || finish?.kind === 'aborted') { for (const chunk of chunks) yield chunk; return; } + summary = text; + } + if (!failed || attempt >= 3) throw Object.assign(new Error(failed?.failure?.message ?? 'the summary request does not fit the window'), { code: 'CONTEXT_WINDOW_EXCEEDED' }); + density = Math.min(MAX_DENSITY, density * 1.6); + careful.set(key, density); + budget = Math.max(1024, budget / 2); + log('warn', `a piece did not fit; asking again with pieces of about ${Math.round(budget)} tokens`); + } + } +} diff --git a/apps/host/server/agent/reply-cut.mjs b/apps/host/server/agent/reply-cut.mjs new file mode 100644 index 0000000000..1d63dfa523 --- /dev/null +++ b/apps/host/server/agent/reply-cut.mjs @@ -0,0 +1,122 @@ +/** + * A reply the model could not finish (AGENT-LOST, 11-01): pure helpers, no I/O. + * + * A model reply has a ceiling (the "output budget"). A thinking model that then writes a whole file in one tool call can spend all of it + * before the call is closed. The Harness drops a tool call that was not closed (its arguments are half a JSON text), the turn ends with + * the reason `max-tokens`, and until now the person saw nothing: no file, no card, no sentence. Here: + * + * - `replyCap(window)` how much one reply may produce (the request's ceiling), much larger than the budget the Harness reserves + * for compaction (profile.mjs `localOutputBudget`): the Harness still clamps it to what the window has left. + * - `ToolDraft` what a tool call that is being written looks like so far: its name, the file it is for, a size, a tail of the text. + * - `cutNotice(...)` the plain sentence for the chat, and `cutNudge(...)` the message that lets the agent carry on in smaller pieces. + */ + +/** Half the window, at most 64K tokens, and never less than the budget compaction reserves. The Harness clamps it to the room left (window minus prompt). */ +export function replyCap(window, reserved = 0) { + const w = Number.isFinite(window) && window > 0 ? Math.floor(window) : 32768; + return Math.max(Math.floor(reserved) || 0, Math.min(Math.floor(w / 2), 65536)); +} + +const ESCAPES = { n: '\n', t: '\t', r: '', '"': '"', '\\': '\\', '/': '/', b: '', f: '' }; + +/** A tail of a JSON string body, read back to text: `\n` becomes a newline, `\"` a quote. A half-written escape at the end is dropped. */ +export function unescapeJsonTail(raw) { + let text = String(raw ?? ''); + const cut = /\\(u[0-9a-fA-F]{0,3})?$/.exec(text); + if (cut) text = text.slice(0, cut.index); + return text.replace(/\\(u[0-9a-fA-F]{4}|[nrtbf"\\/])/g, (_, e) => (e[0] === 'u' ? String.fromCharCode(parseInt(e.slice(1), 16)) : ESCAPES[e] ?? e)); +} + +const TARGET = /"(?:file_path|path|filePath)"\s*:\s*"((?:[^"\\]|\\.)*)"/; +const URL_ARG = /"url"\s*:\s*"((?:[^"\\]|\\.)*)"/; +/** The long text argument of the common writing tools; the tail of the arguments is previewed after the first one of these. */ +const BODY = /"(?:content|new_string|new_str|text|code|body|command|file_text)"\s*:\s*"/; + +/** One tool call being written: the model's streamed arguments, kept small. */ +export class ToolDraft { + constructor(id, name = '') { + this.id = id; this.name = name; + this.bytes = 0; this.lines = 0; + this.head = ''; // the first 4,000 characters: the body argument usually starts here + this.where = ''; // the file (or address) the call is for, once seen: a model may write it before or after the text + this.carry = ''; // the last 300 characters, so a name split between two pieces is still seen + this.tail = ''; // the last 2,400 characters: what is being written now + this.at = 0; // when a frame was last sent for it + } + + add(piece) { + const text = String(piece ?? ''); + if (!text) return; + this.bytes += text.length; + for (let i = text.indexOf('\\n'); i >= 0; i = text.indexOf('\\n', i + 2)) this.lines += 1; + if (this.head.length < 4000) this.head += text.slice(0, 4000 - this.head.length); + this.tail = (this.tail + text).slice(-2400); + if (!this.where) { + const seen = this.carry + text; + const raw = (TARGET.exec(seen) ?? URL_ARG.exec(seen))?.[1]; + if (raw !== undefined) { try { this.where = JSON.parse(`"${raw}"`); } catch { this.where = unescapeJsonTail(raw); } } + this.carry = seen.slice(-300); + } + } + + get target() { return this.where; } + + /** The text of the body so far, only its last `max` characters; empty until the body argument has started. */ + preview(max = 1600) { + const start = BODY.exec(this.head); + if (!start) return ''; + const bodyAt = start.index + start[0].length; // where the body begins, counted in streamed characters + if (bodyAt >= this.bytes) return ''; + const tailAt = this.bytes - this.tail.length; // where the kept tail begins + const body = unescapeJsonTail(this.tail.slice(Math.max(0, bodyAt - tailAt))); + return body.length > max ? body.slice(-max) : body; + } + + /** The frame for the page. */ + frame({ done = false, ...extra } = {}) { + return { type: 'agent-tool-draft', draft: { id: this.id, name: this.name, target: this.target, bytes: this.bytes, lines: this.lines, preview: done ? '' : this.preview(), ...extra, done } }; + } +} + +const kb = n => (n >= 10_000 ? `${Math.round(n / 1000)} KB` : `${(n / 1000).toFixed(1)} KB`); + +/** Calls the model was still writing when its reply was cut: [{ name, target, bytes }]. */ +export function cutCalls(drafts) { + return [...drafts].filter(d => d.bytes > 0).map(d => ({ name: d.name, target: d.target, bytes: d.bytes })); +} + +const withTokens = tokens => (tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''); + +/** The sentence for the person, with the catalog slots it needs: { text, key, values }. `again` is true when the agent was already asked to carry on. */ +export function cutNotice({ calls = [], tokens = 0, again = false, retrying = false } = {}) { + const call = calls.find(c => c.target) ?? calls[0] ?? null; + const file = call?.target ? String(call.target).split(/[\\/]/).filter(Boolean).at(-1) : ''; + if (call && retrying) { + const key = 'That reply reached its length limit{0} while writing {1} ({2}), so nothing was saved. I asked the assistant to write it again in smaller parts.'; + const values = [withTokens(tokens), file || call.name, kb(call.bytes)]; + return { key, values, text: fill(key, values) }; + } + if (call) { + const key = 'The reply reached its length limit{0} while writing {1} ({2}), so nothing was saved. Say “continue” and it will write it again in smaller parts.'; + const values = [withTokens(tokens), file || call.name, kb(call.bytes)]; + return { key, values, text: fill(key, values) }; + } + if (retrying) { + const key = 'That reply reached its length limit{0} and was cut off. I asked the assistant to carry on.'; + return { key, values: [withTokens(tokens)], text: fill(key, [withTokens(tokens)]) }; + } + const key = 'The reply reached its length limit{0} and was cut off. Say “continue” to go on.'; + return { key, values: [withTokens(tokens)], text: fill(key, [withTokens(tokens)]) }; +} + +export function fill(template, values) { return String(template).replace(/\{(\d+)\}/g, (_, i) => String(values[Number(i)] ?? '')); } + +/** The message sent to the assistant so it carries on. It is not shown as the person's message. */ +export function cutNudge({ calls = [], tokens = 0 } = {}) { + const call = calls.find(c => c.target) ?? calls[0] ?? null; + if (!call) { + return 'Your last reply was cut off by the output limit before it was finished. Carry on from where it stopped without repeating what you already wrote, and keep your thinking short.'; + } + const file = call.target || 'the file'; + return `Your last reply was cut off by the output limit${tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''} while you were writing ${file} in one tool call, so nothing was saved. Do not make the same big call again. Write ${file} in several smaller parts: create it with the first part (about 150 lines or fewer), then add each next part with its own edit or append, and read the end of the file back at the end. Keep your thinking short.`; +} diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index b8be4c3266..33cb353c98 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -1,2183 +1,2195 @@ -import { workspaceIdForSession } from './session-workspace'; -import { DEFAULT_CONTENT_FS, DEFAULT_UI_SCALE, SIZE_DEFAULTS_VERSION, savedSizes } from './default-sizes'; -import { detectLanguage } from './language-detect'; -import { validWhileBusy, type WhileBusy } from './while-busy'; -import { addToQuotes, type Quote } from './quotes'; -import { readAsk, type AgentAnswer, type AgentAsk } from './agent-ask'; -import { plainFailure, plainFailureText } from './plain-errors'; -import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase'; -import { settleAgents, updateAgent } from './agents'; -import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop'; -import { LoopScheduler } from './loop-runner'; -import { applyStatusFrame, clearStatus } from './live-status'; -import { approvalNeeded, workFinished } from './attention'; -import { applyGoalFrame } from './goal'; -import { tidyAnswer } from './answer-text'; -import { appendText, mergeDeliverable, readDeliverable, readGroup, readSkills, upsertGroup } from './deliverables'; -import { applyPlanFrame, applyQueueFrame, planApprove, queueMessage } from './plan'; -import { forkFields, isForkJob, TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipFile, type TimeSkipJob, type TimeSkipRun, type TimeSkipVersion } from './time-skip'; -import { PREVIEW_EXAMPLES, type PreviewArtifact } from './artifacts'; -import { lifecyclePolicy } from './lifecycle'; -import { newestServingState } from './serving-state'; -import { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos'; -import { applyNativeEvent, nativeState } from './native'; -import { pictureStatus } from './pictures'; -import { noModelNotice } from './no-model'; -import { taskHandoverMessage, taskHandoverTitle, chatHandoverMessage, chatHandoverTitle } from './task-handover'; -import type { Task } from './tasks'; -import { postWithFolderFallback } from './folder-pick'; -import { createSessionWriter } from './session-persist'; -import { setTranslationLanguage, tr, validLanguage, type Language } from './i18n'; -/** - * Strata app store. - * - * A single immutable state object + a tiny subscribe/emit pair, consumed through - * useSyncExternalStore. Data comes from the engine host over /api; live updates - * arrive on the event stream. No state library, no dependencies. - */ -import { useSyncExternalStore } from 'react'; -import { api, onEvent, streamPost, type StreamEvent } from './client'; -import type { - Workspace, - ChatMessage, - ToolCall, - EngineConfig, - Hardware, - ModelLibrary, - RuntimeModels, - ImageModelLibrary, - ImageModelChoice, - ModelProviders, - ModelConnectionDraft, - RemoteModelSelection, - MonitorState, - ServingState, - Session, - SetupState, - Skill, - WorkspaceFile, -} from './types'; -import { navigate, type Route } from './router'; -import { estimate, execution, contextTokens } from './experience'; - -export interface Toast { - id: string; - tone: 'info' | 'success' | 'warn' | 'error'; - title: string; - body?: string; - leaving?: boolean; -} - -export interface AppState { - language: Language; - fontFamily: string; - configDraft: string | null; - navOpen: boolean; - ready: boolean; - connection: 'connecting' | 'live' | 'offline'; - theme: 'dark' | 'light' | 'system'; - contrast: 'standard' | 'increased'; - rail: boolean; - /** Distraction-free reading: chrome recedes, the transcript narrows. */ - focus: boolean; - /** Conversation prose size in px, 10–22. Does not touch the UI chrome. */ - contentFontSize: number; - density: 'comfortable' | 'compact'; - motion: 'system' | 'full' | 'reduced'; - /** Translucent materials, or flat surfaces for anyone who prefers them. */ - transparency: 'translucent' | 'opaque'; - /** Chrome scale, independent of the conversation's reading size. */ - uiScale: number; - /** Price of one kWh for the Monitor's cost line (0 = not set) and the currency the person picked instead of the detected one ('' = automatic) (#3628). */ - electricityPrice: number; - electricityCurrency: string; - /** Opt-in: a short sound when a task finishes (#3586). */ - doneSound: boolean; - /** Opt-in: a desktop notification when Manual mode waits for an approval (#3477). */ - approvalNotify: boolean; - /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ - whileBusy: WhileBusy; - /** Governs anonymous usage reporting. Nothing is sent in this build; the - * choice is recorded so a version that does offer it starts from it. */ - shareTelemetry: boolean; - paletteOpen: boolean; - shortcutsOpen: boolean; - settingsSection: 'Appearance' | 'Models' | 'Tools' | 'Storage' | 'Engine' | 'About'; - hardware: Hardware | null; - library: ModelLibrary | null; - imageModels: ImageModelLibrary | null; - runtime: RuntimeModels | null; - providers: ModelProviders | null; - remoteModel: RemoteModelSelection | null; - engine: EngineConfig | null; - serving: ServingState | null; - monitor: MonitorState | null; - setup: SetupState | null; - skills: Skill[]; - files: WorkspaceFile[]; - workspacePath: string; - workspaces: Workspace[]; - /** Id of the workspace the file tree is scoped to. */ - activeWorkspace: string | null; - /** First run, and "run setup again", both present the wizard as a modal. */ - setupOpen: boolean; - sessions: Session[]; - activeSession: string | null; - streaming: boolean; - /** Messages the person sent while an answer was being written, waiting to go when it ends (Send after, Interrupt), by chat (#4783). */ - parked: Record<string, string[]>; - /** The passages quoted into the message being written, by chat, in the order they were quoted (#4785). */ - quotes: Record<string, Quote[]>; - /** The questions the agent asked the person and is waiting for, by chat (#4244). */ - agentAsks: Record<string, AgentAsk[]>; - /** Chats with a turn in flight. `streaming` is about the open chat; this is about all of them. */ - liveChats: number; - toasts: Toast[]; - /** Files the model has been granted read access to, and when. */ - touchedPaths: Record<string, string>; - /** The last action that failed, kept until it is retried or dismissed. - * A toast disappears after five seconds; a failure the reader has not dealt - * with should not. */ - actionError: { message: string; label: string; retry: () => void } | null; - busy: Record<string, boolean>; -} - -const SESSION_KEY = 'strata.sessions.v1'; -const PREFS_KEY = 'strata.prefs.v2'; -/** What the model has been allowed to read, kept across restarts. */ -const TOUCHED_KEY = 'strata.touched.v1'; -/** Kept one release so downgrading does not lose the theme and sidebar state. */ -const PREFS_KEY_V1 = 'strata.prefs.v1'; - -const CONTENT_FS_MIN = 10; -const CONTENT_FS_MAX = 22; - -export interface Prefs { - /** Which default sizes this save was made with (see SIZE_DEFAULTS_VERSION). */ - sizeDefaults?: number; - language: Language; - fontFamily: string; - theme: 'dark' | 'light' | 'system'; - contrast: 'standard' | 'increased'; - rail: boolean; - focus: boolean; - contentFontSize: number; - density: 'comfortable' | 'compact'; - motion: 'system' | 'full' | 'reduced'; - transparency: 'translucent' | 'opaque'; - uiScale: number; - electricityPrice: number; - electricityCurrency: string; - doneSound: boolean; - approvalNotify: boolean; - /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ - whileBusy: WhileBusy; - /** Governs anonymous usage reporting. Nothing is sent in this build; the - * choice is recorded so a version that does offer it starts from it. */ - shareTelemetry: boolean; -} - -const PREFS_DEFAULTS: Prefs = { - language: 'en', - fontFamily: '', - theme: 'system', - contrast: 'standard', - rail: false, - focus: false, - contentFontSize: DEFAULT_CONTENT_FS, - density: 'comfortable', - motion: 'system', - transparency: 'translucent', - uiScale: DEFAULT_UI_SCALE, - electricityPrice: 0, - electricityCurrency: '', - doneSound: false, - approvalNotify: false, - whileBusy: 'wait', - shareTelemetry: false, -}; - -function uid(prefix = 'id'): string { - return `${prefix}_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36).slice(-4)}`; -} - -function loadSessions(): Session[] { - try { - const raw = localStorage.getItem(SESSION_KEY); - if (!raw) return []; - const parsed = JSON.parse(raw) as Session[]; - return Array.isArray(parsed) ? parsed.map(session => ({ - ...session, - ...(session.showcase && !session.showcaseAgentStates ? {agents:SHOWCASE_AGENTS,showcaseAgentStates:true}:{}), - ...(!session.showcase && session.agents ? { agents: settleAgents(session.agents) } : {}), - messages: session.messages.map(message => message.streaming ? { - ...message, - streaming: false, - error: message.error ?? 'Response interrupted. Ask again to retry; the partial answer is kept.', - } : message), - })) : []; - } catch { - return []; - } -} - -/** - * v2 adds focus, reading size, density and the motion override. A v1 blob (only - * theme and rail) is read as-is and upgraded on the next write, so the first run - * after this change keeps the user's theme instead of resetting it. - */ -function loadPrefs(): Prefs { - for (const key of [PREFS_KEY, PREFS_KEY_V1]) { - try { - const raw = localStorage.getItem(key); - if (!raw) continue; - const parsed = JSON.parse(raw) as Partial<Prefs>; - return { - ...PREFS_DEFAULTS, - ...parsed, - language: validLanguage(parsed.language) ? parsed.language : 'en', - fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '', - ...savedSizes(parsed, CONTENT_FS_MIN, CONTENT_FS_MAX), - sizeDefaults: SIZE_DEFAULTS_VERSION, - electricityPrice: Number.isFinite(Number(parsed.electricityPrice)) && Number(parsed.electricityPrice) > 0 && Number(parsed.electricityPrice) < 1000 ? Number(parsed.electricityPrice) : 0, - electricityCurrency: typeof parsed.electricityCurrency === 'string' && /^[A-Za-z]{3}$/.test(parsed.electricityCurrency) ? parsed.electricityCurrency.toUpperCase() : '', - doneSound: parsed.doneSound === true, - approvalNotify: parsed.approvalNotify === true, - whileBusy: validWhileBusy(parsed.whileBusy) ? parsed.whileBusy : 'wait', - }; - } catch { - /* fall through to the next key */ - } - } - // Nothing saved: a first start. It opens in the language of the computer; a choice made on the first screen is saved like any other. - const tags = typeof navigator === 'undefined' ? [] : navigator.languages?.length ? navigator.languages : [navigator.language]; - return { ...PREFS_DEFAULTS, language: detectLanguage(tags) ?? 'en' }; -} - -const prefs = loadPrefs(); -// Use the saved language for the very first render, before host bootstrap. -setTranslationLanguage(prefs.language); - -/** The last approval question a notification was shown for, so one question is announced once. */ -let lastApprovalNotice = ''; - -let state: AppState = { - language: prefs.language, - fontFamily: prefs.fontFamily, - configDraft: (() => { try { return sessionStorage.getItem('strata.config-draft.v1'); } catch { return null; } })(), - navOpen: false, - ready: false, - connection: 'connecting', - shareTelemetry: prefs.shareTelemetry, - theme: prefs.theme, - contrast: prefs.contrast, - rail: prefs.rail, - focus: prefs.focus, - contentFontSize: prefs.contentFontSize, - density: prefs.density, - motion: prefs.motion, - transparency: prefs.transparency, - uiScale: prefs.uiScale, - electricityPrice: prefs.electricityPrice, - electricityCurrency: prefs.electricityCurrency, - doneSound: prefs.doneSound, - approvalNotify: prefs.approvalNotify, - whileBusy: prefs.whileBusy, - parked: {}, - quotes: {}, - agentAsks: {}, - paletteOpen: false, - shortcutsOpen: false, - settingsSection: 'Appearance', - hardware: null, - library: null, - imageModels: null, - runtime: null, - providers: null, - /** The open chat's API model, or null for the local model (the default for every chat). */ - remoteModel: null, - engine: null, - serving: null, - monitor: null, - setup: null, - skills: [], - files: [], - workspacePath: '', - workspaces: [], - activeWorkspace: null, - setupOpen: false, - sessions: loadSessions(), - activeSession: null, - streaming: false, - liveChats: 0, - toasts: [], - touchedPaths: (() => { - try { - return JSON.parse(localStorage.getItem(TOUCHED_KEY) ?? '{}') as Record<string, string>; - } catch { - return {}; - } - })(), - actionError: null, - busy: {}, -}; - -const listeners = new Set<() => void>(); - -/** Chats with a turn in flight: the abort handle, and whether the host is running it as an agent turn. */ -const liveTurns = new Map<string, { abort: AbortController; agent: boolean }>(); - -function set(patch: Partial<AppState> | ((s: AppState) => Partial<AppState>)) { - const before = state.activeSession; - const next = typeof patch === 'function' ? patch(state) : patch; - state = { ...state, ...next }; - // Opening another chat shows that chat's model choice and whether that chat is mid-turn. - if (state.activeSession !== before) { - const chosen = state.sessions.find(s => s.id === state.activeSession)?.preferences?.remoteModel ?? null; - state = { ...state, remoteModel: 'remoteModel' in next ? state.remoteModel : chosen, streaming: !!state.activeSession && liveTurns.has(state.activeSession) }; - } - for (const l of listeners) l(); -} - -function subscribe(l: () => void) { - listeners.add(l); - return () => listeners.delete(l); -} - -export function getState(): AppState { - return state; -} - -export function setConfigDraft(configDraft: string | null) { - set({ configDraft }); - try { - if (configDraft === null) sessionStorage.removeItem('strata.config-draft.v1'); - else sessionStorage.setItem('strata.config-draft.v1', configDraft); - } catch { /* Keep the session draft even when browser storage is unavailable. */ } -} - -export function setNavOpen(navOpen: boolean) { set({ navOpen }); } -export function setSettingsSection(settingsSection: AppState['settingsSection']) { set({ settingsSection }); } - -/** Choose the open chat's model: an API model, or null for the local one. Other chats keep theirs. */ -export function selectRemoteModel(remoteModel: RemoteModelSelection | null) { - if (state.streaming) return; - if (remoteModel && !state.providers?.connections.some(c => c.id === remoteModel.connectionId && c.models.some(m => m.id === remoteModel.modelId))) return; - set({ remoteModel }); - const id = state.activeSession; - if (id) patchSession(id, s => ({ ...s, preferences: { ...s.preferences, remoteModel } })); - try { localStorage.removeItem('strata.remote-model.v1'); } catch { /* The old global choice is retired. */ } -} -function applyProviders(providers: ModelProviders) { - // A chat whose API model was removed keeps its choice: the next send says the model is gone, rather - // than quietly answering from the local model. - set({ providers }); -} -export async function saveModelConnection(draft: ModelConnectionDraft) { - applyProviders(await api.post<ModelProviders>('/api/model-providers', draft)); -} -export async function removeModelConnection(id: string) { - applyProviders(await api.del<ModelProviders>(`/api/model-providers/${encodeURIComponent(id)}`)); -} - -function libraryResponse(data: ModelLibrary): ModelLibrary { - if (!data || !Array.isArray(data.variants)) throw new Error('The engine returned an incomplete model list. Retry the operation.'); - return data; -} - -export function lifecycleStatus(s = state) { - return lifecyclePolicy({ connected: s.connection === 'live', streaming: !!s.streaming || s.liveChats > 0, stats: s.serving?.stats, busy: s.busy }); -} -/** The lifecycle status without subscribing to the whole store: a screen that only needs this must not redraw on every monitor tick (round 8, item 13). */ -export function useLifecycle() { - const connected = useStore(s => s.connection === 'live'); - const streaming = useStore(s => !!s.streaming || s.liveChats > 0); - const stats = useStore(s => s.serving?.stats); - const busy = useStore(s => s.busy); - return lifecyclePolicy({ connected, streaming, stats, busy }); -} -export function lifecycleAvailable(): boolean { - const result = lifecycleStatus(); - if (!result.allowed) pushToast('warn', 'Model change unavailable', result.reason); - return result.allowed; -} - -export function useStore<T>(selector: (s: AppState) => T): T { - return useSyncExternalStore( - subscribe, - () => selector(state), - () => selector(state), - ); -} - -/* ------------------------------------------------------------------ toasts */ - -/** Dismissal timers, held so a hovered toast can be paused rather than lost. */ -const toastTimers = new Map<string, ReturnType<typeof setTimeout>>(); -const TOAST_MS = 5200; - -export function pushToast(tone: Toast['tone'], title: string, body?: string) { - const id = uid('toast'); - // Cap the stack: past three, the oldest collapses rather than pushing the - // rest off-screen. A toast nobody can read is not a notification. - const next = [...state.toasts, { id, tone, title, body }]; - const overflow = next.length > 3 ? next.slice(0, next.length - 3) : []; - for (const gone of overflow) { - const t = toastTimers.get(gone.id); - if (t) clearTimeout(t); - toastTimers.delete(gone.id); - } - const kept = overflow.length ? next.slice(-3) : next; - set({ toasts: kept }); - toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS)); -} - -/** - * Stops a toast's clock while the pointer is over it, so reading one does not - * race its own dismissal. Restarting gives a full window rather than the - * remainder — the intent is "I am reading this", and a resumed half-second is - * not enough to act on. - */ -export function holdToast(id: string) { - const t = toastTimers.get(id); - if (t) clearTimeout(t); - toastTimers.delete(id); -} - -export function releaseToast(id: string) { - if (toastTimers.has(id)) return; - if (!state.toasts.some((t) => t.id === id && !t.leaving)) return; - toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS)); -} - -export function dismissToast(id: string) { - const t = toastTimers.get(id); - if (t) clearTimeout(t); - toastTimers.delete(id); - set((s) => ({ toasts: s.toasts.map((x) => (x.id === id ? { ...x, leaving: true } : x)) })); - setTimeout(() => set((s) => ({ toasts: s.toasts.filter((x) => x.id !== id) })), 340); -} - -/* ------------------------------------------------------------------- prefs */ - -/** - * Preferences live on <html> as data attributes plus one custom property, so CSS - * owns presentation and React owns state — the same split the theme already - * used. Nothing here re-renders a screen: the attributes do the work. - */ -function applyPrefs() { - const root = document.documentElement; - setTranslationLanguage(state.language); - root.lang = state.language === 'zh' ? 'zh-CN' : state.language; - if(state.fontFamily)root.style.setProperty('--st-font',`${JSON.stringify(state.fontFamily)},system-ui,-apple-system,"Segoe UI",sans-serif`); - else root.style.removeProperty('--st-font'); - root.dataset.theme = state.theme === 'system' ? matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : state.theme; - document.querySelector<HTMLMetaElement>('meta[name="theme-color"]')?.setAttribute('content', root.dataset.theme === 'dark' ? '#0e1113' : '#f9fafb'); - root.dataset.contrast = state.contrast; - root.dataset.density = state.density; - root.style.setProperty('--st-content-fs', `${state.contentFontSize}px`); - // The interface size (#3970): the whole page is scaled, so every text, button, menu and dialog follows, not only the parts that were - // written with the scale token. The token stays at 1 so nothing is scaled twice. The reading size stays separate: someone who needs - // larger prose does not necessarily want larger buttons. - root.style.setProperty('--st-ui-scale', '1'); - root.style.setProperty('zoom', state.uiScale === 1 ? '' : String(state.uiScale)); - - // "system" means the OS decides, so the attribute is absent rather than set - // to a third value the stylesheet would have to special-case. - if (state.motion === 'system') delete root.dataset.motion; - else root.dataset.motion = state.motion; - - if (state.focus) root.dataset.focus = 'true'; - else delete root.dataset.focus; - - // "translucent" is the default, so the attribute only appears when it is off. - if (state.transparency === 'opaque') root.dataset.transparency = 'opaque'; - else delete root.dataset.transparency; -} - -function savePrefs() { - const snapshot: Prefs = { - sizeDefaults: SIZE_DEFAULTS_VERSION, - language: state.language, - fontFamily: state.fontFamily, - theme: state.theme, - contrast: state.contrast, - rail: state.rail, - focus: state.focus, - contentFontSize: state.contentFontSize, - density: state.density, - motion: state.motion, - transparency: state.transparency, - uiScale: state.uiScale, - electricityPrice: state.electricityPrice, - electricityCurrency: state.electricityCurrency, - doneSound: state.doneSound, - approvalNotify: state.approvalNotify, - whileBusy: state.whileBusy, - shareTelemetry: state.shareTelemetry, - }; - try { - localStorage.setItem(PREFS_KEY, JSON.stringify(snapshot)); - } catch { - /* a full quota must not break the UI */ - } - applyPrefs(); -} - -export function setTheme(theme: 'dark' | 'light' | 'system') { - set({ theme }); - savePrefs(); -} - -export function toggleRail() { - set({ rail: !state.rail }); - savePrefs(); -} -export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();rememberShellLanguage(language);} -let shellAnnounced = false; -/** The desktop shell's tray menu follows the app's language; it reads it from a small file the host keeps (no effect in a browser). */ -function rememberShellLanguage(language:Language){api.post('/api/shell/prefs',{language}).catch(()=>undefined);} -/** The shell started on another port than it wanted: the chats and settings saved on that port are not here, so say so once (#3402). */ -async function announcePortNotice(){ - try{ - const shell=await api.get<{portNotice:{wanted:number;used:number}|null}>('/api/shell'); - if(shell.portNotice)pushToast('warn',tr('Strata could not use its port'),tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.',[shell.portNotice.wanted,shell.portNotice.used])); - }catch{/* a browser or an older host has no shell */} -} -export function setFontFamily(fontFamily:string){set({fontFamily:fontFamily.trim().slice(0,128).replace(/[\x00-\x1f]/g,'')});savePrefs();} - -export function setFocus(focus: boolean) { - set({ focus }); - savePrefs(); -} - -export function toggleFocus() { - setFocus(!state.focus); -} - -/** - * Puts every appearance and reading preference back to its shipped value. - * - * Deliberately excludes `shareTelemetry`: a privacy choice is not an appearance - * setting, and re-enabling reporting as a side effect of resetting one's font - * size would be exactly the kind of thing this control exists to prevent. - * - * Deliberately does **not** touch `rail` or `focus`: those are where you happen - * to be working, not settings you chose, and collapsing the sidebar on someone - * who asked to reset their font size would be a surprise. The engine has its own - * reset, since an expert override and a font size have nothing to do with each - * other. - */ -export function resetAppearance() { - set({ - fontFamily: PREFS_DEFAULTS.fontFamily, - theme: PREFS_DEFAULTS.theme, - contrast: PREFS_DEFAULTS.contrast, - contentFontSize: PREFS_DEFAULTS.contentFontSize, - density: PREFS_DEFAULTS.density, - motion: PREFS_DEFAULTS.motion, - transparency: PREFS_DEFAULTS.transparency, - uiScale: PREFS_DEFAULTS.uiScale, - }); - savePrefs(); -} - -/** - * Records the standing privacy choice. - * - * The control was local component state that nothing persisted and nothing - * read — it snapped back on every reload, so a reader who turned reporting off - * had no way to know their choice had not been recorded. A privacy control that - * silently forgets is worse than no control at all. - */ -export function setShareTelemetry(on: boolean) { - set({ shareTelemetry: on }); - savePrefs(); -} - -export function setContentFontSize(px: number) { - const clamped = Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Math.round(px))); - set({ contentFontSize: clamped }); - savePrefs(); -} - -export function setDensity(density: 'comfortable' | 'compact') { - set({ density }); - savePrefs(); -} - -export function setMotion(motion: 'system' | 'full' | 'reduced') { - set({ motion }); - savePrefs(); -} - -export function setTransparency(transparency: 'translucent' | 'opaque') { - set({ transparency }); - savePrefs(); -} - -/** The electricity price for the Monitor's cost line: a positive price per kWh; 0 turns the line off. The currency is the detected one unless a three-letter code is given (#3628). */ -export function setElectricity(price: number, currency: string) { - const ok = Number.isFinite(price) && price > 0 && price < 1000; - set({ electricityPrice: ok ? Math.round(price * 10000) / 10000 : 0, electricityCurrency: /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : '' }); - savePrefs(); -} - -export function setWhileBusy(whileBusy: WhileBusy) { - if (!validWhileBusy(whileBusy)) return; - set({ whileBusy }); - savePrefs(); -} - -/** A message sent while an answer is being written waits here; the chat sends it when the answer is done (it is also where Interrupt leaves it). */ -export function parkMessage(sessionId: string, text: string) { - const clean = text.trim(); - if (!clean) return; - set({ parked: { ...state.parked, [sessionId]: [...(state.parked[sessionId] ?? []), clean] } }); -} -function setAsks(sessionId: string, list: AgentAsk[]) { - const next = { ...state.agentAsks }; - if (list.length) next[sessionId] = list; else delete next[sessionId]; - set({ agentAsks: next }); -} -/** The agent asked the person something (a frame of the host), or the question ended without an answer. */ -export function addAgentAsk(sessionId: string, frame: { callId?: unknown; questions?: unknown }) { - const ask = readAsk(frame); - // A /loop runs without anyone there: the question is skipped at once, so the loop never waits for an answer. - if (ask && loopScheduler.isRunning(sessionId)) { void answerAgentAsk(sessionId, ask.callId, null).catch(() => {}); return; } - if (ask) setAsks(sessionId, [...(state.agentAsks[sessionId] ?? []).filter(a => a.callId !== ask.callId), ask]); -} -export function removeAgentAsk(sessionId: string, callId?: string) { - const rest = callId === undefined ? [] : (state.agentAsks[sessionId] ?? []).filter(a => a.callId !== callId); - if ((state.agentAsks[sessionId]?.length ?? 0) !== rest.length) setAsks(sessionId, rest); -} -/** Sends the person's answer to the agent, or a skip (answers null). A refusal comes back as an error for the card to say in words. */ -export async function answerAgentAsk(sessionId: string, callId: string, answers: AgentAnswer[] | null) { - await api.post('/api/chat/answer', { sessionId, callId, ...(answers ? { answers } : { skip: true }) }); - removeAgentAsk(sessionId, callId); -} - -/** Puts a turn or a selected passage above the message box. */ -export function addQuote(sessionId: string, text: string, messageId: string, role: 'user' | 'assistant') { - const list = state.quotes[sessionId] ?? []; - const next = addToQuotes(list, { text, messageId, role }); - if (next.length !== list.length) set({ quotes: { ...state.quotes, [sessionId]: next } }); -} -export function removeQuote(sessionId: string, id: string) { - const rest = (state.quotes[sessionId] ?? []).filter(q => q.id !== id); - const next = { ...state.quotes }; - if (rest.length) next[sessionId] = rest; else delete next[sessionId]; - set({ quotes: next }); -} -export function clearQuotes(sessionId: string) { - if (!state.quotes[sessionId]) return; - const next = { ...state.quotes }; - delete next[sessionId]; - set({ quotes: next }); -} - -/** The first parked message of a chat, taken out of the list (to send it, or to give it back to the box). */ -export function takeParked(sessionId: string, index = 0): string | undefined { - const list = state.parked[sessionId] ?? []; - if (index < 0 || index >= list.length) return undefined; - const rest = list.filter((_, i) => i !== index); - const next = { ...state.parked }; - if (rest.length) next[sessionId] = rest; else delete next[sessionId]; - set({ parked: next }); - return list[index]; -} - -export function setDoneSound(doneSound: boolean) { - set({ doneSound }); - savePrefs(); -} - -export function setApprovalNotify(approvalNotify: boolean) { - set({ approvalNotify }); - savePrefs(); -} - -export const UI_SCALES = [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2] as const; - -export function setUiScale(uiScale: number) { - set({ uiScale }); - savePrefs(); -} - -export const CONTENT_FONT_RANGE = { min: CONTENT_FS_MIN, max: CONTENT_FS_MAX }; - -/* -------------------------------------------------------------- workspaces */ - -/** Opens the system folder chooser. Returns null when it is dismissed. */ -export async function pickWorkspace(): Promise<string | null> { - const res = await postWithFolderFallback<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick') as { path?: string }; - return res.path ?? null; -} - -export async function addWorkspace(path: string) { - try { - const ws = await api.post<Workspace>('/api/workspaces', { path }); - set({ workspaces: [...state.workspaces, ws] }); - pushToast('success', 'Workspace added', `Strata can now read files in ${ws.name}.`); - } catch (err) { - pushToast('error', "Couldn't add that folder", err instanceof Error ? err.message : String(err)); - } -} - -/** The name the sidebar shows for a workspace; its folder is unchanged. */ -export async function renameWorkspace(id: string, name: string) { - try { - const ws = await api.patch<Workspace>(`/api/workspaces/${id}`, { name }); - set({ workspaces: state.workspaces.map(w => (w.id === id ? { ...w, name: ws.name } : w)) }); - } catch (err) { - pushToast('error', "Couldn't rename that workspace", err instanceof Error ? err.message : String(err)); - } -} - -export async function removeWorkspace(id: string) { - const ws = state.workspaces.find((w) => w.id === id); - try { - await api.del(`/api/workspaces/${id}`); - set({ workspaces: state.workspaces.filter((w) => w.id !== id) }); - if (state.activeWorkspace === id) set({ activeWorkspace: state.workspaces[0]?.id ?? null }); - } catch (err) { - pushToast('error', "Couldn't remove that workspace", err instanceof Error ? err.message : String(err)); - } - void ws; -} - -/** - * Pins a conversation to the top of its workspace. - * - * Sessions are currently ordered by recency, which is right until you have - * thirty of them and two matter. `Session.pinned` has existed in the type since - * the beginning and was never written to. - */ -export function toggleArchive(id: string) { - const sessions = state.sessions.map((s) => (s.id === id ? { ...s, archived: !s.archived } : s)); - persistSessions(sessions); - set({ sessions }); -} - -export function togglePin(id: string) { - const sessions = state.sessions.map((s) => (s.id === id ? { ...s, pinned: !s.pinned } : s)); - persistSessions(sessions); - set({ sessions }); -} - -export function setActiveWorkspace(id: string) { - set({ activeWorkspace: id }); - void loadWorkspaceFiles(); -} - -export function openSetup(open: boolean) { - set({ setupOpen: open }); -} - -export function setPalette(open: boolean) { - set({ paletteOpen: open }); -} - -export function setShortcuts(open: boolean) { - set({ shortcutsOpen: open }); -} - -/* --------------------------------------------------------------- transport */ - -function applyEvent(e: StreamEvent) { - const data = e.data as Record<string, unknown>; - switch (e.event) { - case 'monitor': - set({ monitor: data as unknown as MonitorState }); - break; - case 'skills': - set({ skills: data as unknown as Skill[] }); - break; - case 'models': - if (Array.isArray(data.variants)) set({ library: data as unknown as ModelLibrary }); - break; - case 'runtime': - set({runtime:data as unknown as RuntimeModels}); - break; - case 'native': - applyNativeEvent(data); - break; - case 'image-models': - if (Array.isArray(data.variants)) set({ imageModels: data as unknown as ImageModelLibrary }); - break; - case 'providers': - applyProviders(data as unknown as ModelProviders); - break; - case 'goal': - if (typeof data.chatId === 'string') applyGoalFrame(data.chatId, data.goal); - break; - case 'plan': - if (typeof data.chatId === 'string') applyPlanFrame(data.chatId, data.plan); - break; - case 'queue': - if (typeof data.chatId === 'string') applyQueueFrame(data.chatId, data.queue); - break; - case 'timeskip': - applyTimeSkipEvent(data); - break; - case 'engine': - set({ engine: data as unknown as EngineConfig }); - break; - case 'serving': - set({ serving: newestServingState(state.serving, data as unknown as ServingState) }); - break; - case 'setup': - set({ setup: data as unknown as SetupState }); - break; - case 'task': { - // A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed. - const t = data as unknown as { title?: string; status?: string; attention?: string | null; error?: string | null }; - if (t.status === 'error') pushToast('error', 'Task failed', String(t.title ?? '')); - else if (t.attention) { pushToast('warn', 'Task needs your yes', String(t.title ?? '')); void approvalNeeded(state.approvalNotify, String(t.title ?? '')); } - else if (t.status === 'done') { pushToast('success', 'Task finished', String(t.title ?? '')); workFinished(state.doneSound, Infinity); } - break; - } - case 'agent': - if (typeof data.sessionId === 'string') patchSession(data.sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], data.agent) })); - break; - default: - break; - } -} - -let closeEvents: (() => void) | null = null; -export async function bootstrap() { - applyPrefs(); - try { - const [setup, hardware, library, engine, serving, monitor, skills, providers, imageModels, runtime] = await Promise.all([ - api.get<SetupState>('/api/setup'), - api.get<Hardware>('/api/hardware'), - api.get<ModelLibrary>('/api/models'), - api.get<EngineConfig>('/api/engine'), - api.get<ServingState>('/api/serving'), - api.get<MonitorState>('/api/monitor'), - api.get<Skill[]>('/api/skills'), - api.get<ModelProviders>('/api/model-providers'), - api.get<ImageModelLibrary>('/api/image-models'), - api.get<RuntimeModels>('/api/runtime'), - ]); - const workspaceState = await api.get<{ workspaces: Workspace[] }>('/api/workspaces'); - set({ - ready: true, - setup, - hardware, - library: libraryResponse(library), - imageModels, - runtime, - engine, - serving: newestServingState(state.serving, serving), - monitor, - skills, - workspacePath: workspaceState.workspaces[0]?.path ?? '', - workspaces: workspaceState.workspaces, - 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); - if (!shellAnnounced) { shellAnnounced = true; void announcePortNotice(); rememberShellLanguage(state.language); } - closeEvents?.(); - let reconnect = false; - closeEvents = onEvent(applyEvent, (status) => { - if (status === 'offline') reconnect = true; - if (status === 'live' && reconnect) { - reconnect = false; - // The restarted host may have new logs, config or readiness. Refresh - // those facts in place while retaining conversations and unsent drafts. - void bootstrap(); - return; - } - set({ connection: status }); - }); - if (!setup.complete && !setup.dismissed && !window.location.hash.includes('setup')) navigate('setup'); - } catch (err) { - set({ ready: true, connection: 'offline' }); - pushToast( - 'error', - 'Engine host unreachable', - err instanceof Error ? err.message : 'Start it with `npm run host` and reload.', - ); - } -} - -/* ------------------------------------------------------------- reads/writes */ - -export async function refreshHardware() { - set((s) => ({ busy: { ...s.busy, hardware: true } })); - try { - set({ hardware: await api.get<Hardware>('/api/hardware?reprobe=1') }); - } finally { - set((s) => ({ busy: { ...s.busy, hardware: false } })); - } -} - -function modelFits(id: string) { - const model = state.library?.variants.find(v => v.id === id); - if (state.library?.mode === 'real' && model && state.hardware && state.engine && ['too-large', 'unsupported'].includes(estimate(model, state.hardware, execution(Object.fromEntries(state.engine.expert.map(p => [p.id, p.value])), contextTokens(state.engine.beginner.contextLength))).fit)) { - pushToast('warn', 'Choose a smaller model', 'The estimated memory requirement exceeds this computer.'); - return false; - } - return true; -} - -export async function selectImageModel(selected: ImageModelChoice) { - set(s => ({ busy: { ...s.busy, 'image:select': true } })); - try { set({ imageModels: await api.patch<ImageModelLibrary>('/api/image-models', { selected }) }); } - finally { set(s => ({ busy: { ...s.busy, 'image:select': false } })); } -} -export async function installImageModel(id: Exclude<ImageModelChoice, 'off'>) { - set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/install`) }); -} -export async function cancelImageModel(id: Exclude<ImageModelChoice, 'off'>) { - set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/cancel`) }); -} -export async function applyImageModel() { - set({ imageModels: await api.post<ImageModelLibrary>('/api/image-models/apply') }); -} - -export async function installVariant(id: string) { - // Download eligibility is checked against disk space by the host. Runtime fit - // is reviewed separately when the model is loaded. - if (state.busy[`install:${id}`]) return false; - set((s) => ({ busy: { ...s.busy, [`install:${id}`]: true } })); - try { - const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/install`)); - set({ library }); - const complete = library.variants.find(v => v.id === id)?.state === 'installed'; - pushToast(complete ? 'success' : 'info', complete ? 'Files installed' : library.mode === 'simulated' ? 'Example installation started' : 'Download started', complete ? 'Load the model to start a request.' : 'Progress is shown in Models.'); - return true; - } catch (err) { - pushToast('error', 'Download failed', err instanceof Error ? err.message : undefined); - return false; - } finally { - set((s) => ({ busy: { ...s.busy, [`install:${id}`]: false } })); - } -} - -export async function cancelInstall(id: string) { - try { set({ library: libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/cancel`)) }); } catch (e) { pushToast('error', 'Cancel failed', e instanceof Error ? e.message : String(e)); } -} - -export async function loadVariant(id: string) { - if (!modelFits(id)) return false; - if (!lifecycleAvailable()) return false; - set((s) => ({ busy: { ...s.busy, [`load:${id}`]: true }, actionError: null })); - try { - const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/load`)); - set({ library }); - const model = library.variants.find(v => v.id === id); - if (library.loaded !== id || model?.state !== 'loaded') throw new Error(model?.error ?? 'The model did not finish loading.'); - pushToast('success', library.mode === 'simulated' ? 'Example model ready' : 'Model loaded', library.mode === 'simulated' ? 'Answers are simulated samples, not from a real model.' : 'Ready for a request.'); - return true; - } catch (err) { - const message = err instanceof Error ? err.message : 'The model did not load.'; - set({ - actionError: { - label: 'Could not load model', - message, - retry: () => void loadVariant(id), - }, - }); - pushToast('error', 'Could not load model', message); - return false; - } finally { - set((s) => ({ busy: { ...s.busy, [`load:${id}`]: false } })); - } -} - -export async function unloadModel() { - if (!lifecycleAvailable()) return false; - set(s => ({ busy: { ...s.busy, unload: true } })); - try { - const previousInstance=state.runtime?.defaultId; - const library = libraryResponse(await api.post<ModelLibrary>('/api/models/unload')); - const runtime=await api.get<RuntimeModels>('/api/runtime'); - set({runtime}); - set({ library }); - if (previousInstance?runtime.instances.some(i=>i.id===previousInstance):library.loaded!==null) throw new Error('The engine still reports this model instance as loaded.'); - pushToast('info', 'Model unloaded', library.mode === 'simulated' ? 'Example load state cleared.' : 'Model memory released.'); - return true; - } catch (err) { pushToast('error', 'Unload failed', err instanceof Error ? err.message : String(err)); return false; } - finally { set(s => ({ busy: { ...s.busy, unload: false } })); } -} - -export async function removeVariant(id: string) { - if (state.library?.loaded === id && !lifecycleAvailable()) return false; - const local = !!state.library?.variants.find(v => v.id === id)?.local; - try { const library = libraryResponse(await api.del<ModelLibrary>(`/api/models/${id}`)); set({ library }); - const remaining = library.variants.find(v => v.id === id); - if (remaining && remaining.state !== 'available') throw new Error('The model files were not removed.'); - pushToast('success', local ? 'Local model removed' : 'Files removed', local ? 'The original GGUF files are kept.' : library.mode === 'simulated' ? 'Example install state cleared.' : 'Model files removed from disk.'); return true; - } catch (e) { pushToast('error', 'Remove failed', e instanceof Error ? e.message : String(e)); return false; } -} - -export async function waitForInstalled(id: string) { - const deadline = Date.now() + 60 * 60 * 1000; - while (Date.now() < deadline) { - const v = state.library?.variants.find(v => v.id === id); - if (v && ['installed', 'loaded'].includes(v.state)) return; - if (!v || ['available', 'error'].includes(v.state)) throw new Error(v?.error ?? 'Download cancelled.'); - await new Promise(resolve => setTimeout(resolve, 500)); - } - throw new Error('Download timed out. Try again from Models.'); -} - -export async function saveEngine(patch: Partial<EngineConfig> | Record<string, unknown>, silent = false, requireIdle = false) { - if (requireIdle) { - const status = lifecycleStatus(); - if (!status.allowed) throw new Error(status.reason); - } - const engine = await api.patch<EngineConfig>('/api/engine', patch); - set({ engine, actionError: null }); - if (!silent) pushToast('success', 'Settings saved', 'Load settings take effect on the next load. Sampling defaults affect the next request.'); - return engine; -} - -export async function restartEngine() { - if (state.library?.mode === 'simulated') { pushToast('info', 'Restart unavailable with the example engine', 'Save settings for the next load.'); return false; } - if (!lifecycleAvailable()) return false; - set((s) => ({ busy: { ...s.busy, restart: true }, actionError: null })); - try { - const engine = await api.post<EngineConfig>('/api/engine/restart'); - set({ engine }); - if (!engine.engine.running) throw new Error(engine.engine.error ?? 'The engine is not running. Load a model before applying settings.'); - pushToast('success', 'Engine restarted', 'Warm-up takes a few seconds.'); - return true; - } catch (err) { - // Reported in place as well as in a toast: the toast is a summary, the - // surface that failed is where the retry belongs. - set({ - actionError: { - label: 'Restart failed', - message: err instanceof Error ? err.message : 'The engine did not come back up.', - retry: () => void restartEngine(), - }, - }); - pushToast('error', 'Restart failed', err instanceof Error ? err.message : undefined); - return false; - } finally { - set((s) => ({ busy: { ...s.busy, restart: false } })); - } -} - -export function dismissActionError() { - set({ actionError: null }); -} - -export async function resetEngine() { - set({ engine: await api.post<EngineConfig>('/api/engine/reset') }); - pushToast('info', 'Back to recommended', 'Every value returned to the safe default.'); -} - -/** - * Checks an engine config — the saved one by default, or a draft to preview what - * a change would do before committing to it. - */ -export async function validateEngine(draft?: unknown) { - return api.post<{ - ok: boolean; - issues: { level: 'warn' | 'error'; message: string }[]; - predicted?: EngineConfig['predicted']; - }>('/api/engine/validate', draft ?? {}); -} - -export async function exportEngine() { - return api.get<Record<string, unknown>>('/api/engine/export'); -} - -export async function setCloudflare(body: {action: 'start' | 'stop' | 'prepare'; mode?: 'quick' | 'domain'; hostname?: string; token?: string}) { - const result = await api.post<ServingState>('/api/serving/tunnel', body); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function setLocalSharing(enabled: boolean) { - const result = await api.post<ServingState>('/api/serving/share', { enabled }); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function setServingAccess(patch: { otherDevices?: boolean; apiKey?: string | null }) { - const result = await api.patch<ServingState>('/api/serving', patch); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function pauseServing(paused: boolean) { - const result = await api.patch<ServingState>('/api/serving', { pauseServing: paused }); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function cancelRequest(id: string) { - const result = await api.post<ServingState>(`/api/serving/requests/${id}/cancel`); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function completeSetupStep(step: number, choices?: SetupState['choices'], dismissed = false) { - set({ setup: await api.post<SetupState>('/api/setup/step', { step, choices, dismissed, flowVersion: 2 }) }); -} - -export async function completeSetup() { - const setup = await api.post<SetupState>('/api/setup/complete'); - set({ setup }); -} - -export async function setSkills(skills: Skill[]) { - set({ skills }); -} - -/** - * Re-reads the skill list from the host. - * - * For the case where a skill was added to the workspace folder while the app was - * open — otherwise the only way to see it is to restart. - */ -export async function loadSkills() { - set({ skills: await api.get<Skill[]>('/api/skills') }); -} - -/** Re-reads the workspace tree from disk, for the same reason. */ -export async function loadWorkspaceFiles() { - const data = await api.get<{ path: string; entries: WorkspaceFile[] }>(`/api/workspace${state.activeWorkspace ? '?root=' + encodeURIComponent(state.activeWorkspace) : ''}`); - set({ files: data.entries, workspacePath: data.path }); -} - -export async function toggleSkill(id: string, enabled: boolean) { - set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { enabled }) }); -} - -export async function editSkill(id: string, patch: Pick<Skill, 'name' | 'description' | 'body' | 'triggers' | 'enabled' | 'onlyIn'>) { - set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, patch) }); -} - -/** - * Narrows a skill to the workspace you are in, or widens it again. - * - * Passing null clears the narrowing. The host resolves `onlyIn` against the - * workspace the request came from, so the answer depends on where the reader - * is rather than on a single global switch. - */ -export async function scopeSkill(id: string, workspaceId: string | null) { - set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { onlyIn: workspaceId }) }); -} - -/* ---------------------------------------------------------------- sessions */ - -const sessionWriter = createSessionWriter({ - write: (json) => { - try { - localStorage.setItem(SESSION_KEY, json); - } catch { - /* quota — sessions are a cache, not the source of truth */ - } - }, -}); - -/** - * Save the chat list. A one-off change (new, rename, delete, pin) is written now; `soon` is for the streaming - * path, where a write per token grew the renderer to gigabytes (#3604, #3603): those are coalesced to one a second. - */ -function persistSessions(sessions: Session[], soon = false) { - sessionWriter.schedule(sessions); - if (!soon) sessionWriter.flush(); -} - -/** Write the newest chat list now: a turn ended, or the page is going away. */ -export function flushSessions() { - sessionWriter.flush(); -} - -if (typeof window !== 'undefined' && typeof document !== 'undefined' && window.addEventListener) { - window.addEventListener('pagehide', flushSessions); - document.addEventListener?.('visibilitychange', () => { if (document.visibilityState === 'hidden') flushSessions(); }); -} - -export function newSession(): Session { - const session: Session = { - id: uid('s'), - title: 'New conversation', - defaultTitle: true, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - messages: [], - workspace: state.workspaces.find(w => w.id === state.activeWorkspace)?.path ?? state.workspacePath, - tokensIn: 0, - tokensOut: 0, - ...(state.activeSession === null && state.remoteModel ? { preferences: { remoteModel: state.remoteModel } } : {}), - }; - const sessions = [session, ...state.sessions]; - persistSessions(sessions); - set({ sessions, activeSession: session.id }); - return session; -} - -export function setChatPreferences(id: string | undefined, preferences: NonNullable<Session['preferences']>) { - const sessionId = id ?? newSession().id; - patchSession(sessionId, s => ({ ...s, preferences: { ...s.preferences, ...preferences } })); - // A mode change applies to the very next tool call of a turn that is already running (a goal and its helpers included). - if (preferences.mode && liveTurns.get(sessionId)?.agent) void api.post('/api/chat/mode', { sessionId, mode: preferences.mode }).catch(() => undefined); -} -export function setPreviewTabClosed(sessionId:string|undefined, artifactId:string, closed:boolean, selected:string|null) { - if(!sessionId)return; - patchSession(sessionId,s=>({...s,closedPreviews:closed?[...new Set([...(s.closedPreviews??[]),artifactId])]:(s.closedPreviews??[]).filter(id=>id!==artifactId),previewOpen:selected??undefined})); -} -export function createChatShowcase() { - const session=newSession();const at=new Date().toISOString(); - patchSession(session.id,s=>({...s,title:'Chat showcase · code, tools & media',showcase:true,statsAvailable:true,tokensIn:28000000,tokensOut:4000000,messages:showcaseMessages(at),agents:SHOWCASE_AGENTS,showcaseAgentStates:true})); - go('chat',session.id); -} - -/** A visible example for checking the subagent interface in the design build. */ -export function createSubagentExample() { - const session = newSession(); const now = Date.now(); - patchSession(session.id, s => ({ ...s, title: 'Subagent preview', showcase: true, showcaseAgentStates: true, - agents: [ - {id:'example-layout',name:'Layout review',description:'Checking spacing and component alignment.',status:'working',durationMs:39000,tokens:12600,updatedAt:now}, - {id:'example-interactions',name:'Interaction review',description:'Checking menus, controls and keyboard navigation.',status:'working',durationMs:21000,tokens:8400,updatedAt:now}, - {id:'example-copy',name:'Copy review',description:'Labels and descriptions reviewed.',status:'completed',durationMs:18000,tokens:4200,updatedAt:now}, - ], messages: [{id:uid('m'),role:'assistant',at:new Date(now).toISOString(),example:true,content:'Open the subagent count above to inspect this example run. Each row shows status, token usage and elapsed time.'}] - })); - go('chat', session.id); -} - -export function createPreviewExamples() { - const session = newSession(); - const at = new Date().toISOString(); - patchSession(session.id, s => ({ ...s, title: 'Design review · six previews', previewOpen:'sample-website', messages: [ - { id:uid('m'), role:'user', at, content:'Open six different output types so I can iterate on the preview design.' }, - { id:uid('m'), role:'assistant', at, demo:true, content:'Here is a design-review workspace for Fieldnotes: a website, PDF, Markdown brief, cover image, TypeScript file and release table.\n\nAll six are loaded in the panel on the right. Switch tabs to explore each view while keeping this conversation in place.', artifacts:PREVIEW_EXAMPLES }, - ] })); - go('chat', session.id); -} - -/** "Continue in a new chat" on a task: a new chat whose first message is the task's findings, what it did and its files (src/lib/task-handover.ts). */ -export function continueTaskInNewChat(task: Task) { - const session = newSession(); - go('chat', session.id); - void sendMessage(taskHandoverMessage(task), { title: taskHandoverTitle(task), markdown: true }); -} - -export function selectSession(id: string) { - // 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); -} - -/** Records that a conversation has been looked at. */ -export function markRead(id: string) { - const at = new Date().toISOString(); - const sessions = state.sessions.map((s) => (s.id === id ? { ...s, lastReadAt: at } : s)); - persistSessions(sessions); - set({ sessions }); -} - -/** - * Whether a conversation has moved on since it was last looked at. - * - * The active conversation is never unread: you are looking at it, or its reply - * is arriving in front of you. - */ -export function isUnread(s: Session, activeSession: string | null): boolean { - if (s.id === activeSession) return false; - if (!s.lastReadAt) return s.messages.length > 0; - return s.updatedAt > s.lastReadAt; -} - -export function deleteSession(id: string) { - const sessions = state.sessions.filter((s) => s.id !== id); - persistSessions(sessions); - set({ sessions, activeSession: state.activeSession === id ? (sessions[0]?.id ?? null) : state.activeSession }); -} - -export function renameSession(id: string, title: string) { - const sessions = state.sessions.map((s) => (s.id === id ? { ...s, title, defaultTitle: false } : s)); - persistSessions(sessions); - set({ sessions }); -} - -function patchSession(id: string, fn: (s: Session) => Session) { - const sessions = state.sessions.map((s) => (s.id === id ? fn(s) : s)); - persistSessions(sessions, true); - set({ sessions }); -} - -// The demo clock belongs to the session, so hiding the sidebar or navigating -// away never pauses it. Only start and completion are written to storage. -const timeSkipTimers = new Map<string, ReturnType<typeof setTimeout>>(); -function scheduleTimeSkip(sessionId: string, run: TimeSkipRun) { - const timerId = `${sessionId}:${run.id}`; - clearTimeout(timeSkipTimers.get(timerId)); - if (run.completedAt || run.job) return; - timeSkipTimers.set(timerId, setTimeout(() => { - timeSkipTimers.delete(timerId); - const session = state.sessions.find(s => s.id === sessionId); - const current = session?.timeSkips?.find(r => r.id === run.id); - if (!current || current.startedAt !== run.startedAt || !session?.messages.some(m => m.timeSkipId === run.id && m.role === 'assistant')) return; - patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(), - timeSkips: s.timeSkips?.map(r => r.id === run.id ? { ...r, completedAt: run.startedAt + TIME_SKIP_DURATION } : r), - messages: s.messages.map(m => m.timeSkipId === run.id && m.role === 'assistant' ? { ...m, content: 'The updated result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.' } : m), - })); - }, Math.max(0, run.startedAt + TIME_SKIP_DURATION - Date.now()))); -} - -export function replayTimeSkip(sessionId: string, runId: string) { - const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); - if (!run) return; - const next = { ...run, startedAt: Date.now(), completedAt: undefined, retainedVersion: undefined }; - patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r), - messages: s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.' } : m), - })); - scheduleTimeSkip(sessionId, next); -} - -export function setTimeSkipResult(sessionId: string, runId: string, version: TimeSkipVersion) { - const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); - if (!run) return; - if (run.job) { void keepTimeSkip(sessionId, runId, version); return; } - const next = withTimeSkipResult(run, version, Date.now()); - if (next === run) return; - patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r) })); -} - -/* ------------------------------------------------------- Time-skip, for real - The host copies the chat's folder, lets the assistant change the copy, checks it and keeps the original untouched until the - person chooses. The sidebar follows the job's own record; nothing here invents progress. */ -const TS_TERMINAL = ['completed', 'cancelled', 'failed', 'interrupted']; -const TS_WORKING = () => tr('Working on a copy of your files. Follow the progress in the sidebar.'); -const TS_READY = () => tr('The result is ready. Switch between Original and Updated, or compare them side by side.'); - -function patchRun(sessionId: string, runId: string, fn: (run: TimeSkipRun) => TimeSkipRun, content?: string) { - patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(), - timeSkips: s.timeSkips?.map(r => r.id === runId ? fn(r) : r), - messages: content === undefined ? s.messages : s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content } : m), - })); -} - -/** The job's error in a sentence a person can use. */ -export function plainTimeSkipError(raw: string | null | undefined): string { - const text = String(raw ?? '').trim(); - if (!text) return tr('Something went wrong.'); - const afterExit = /\(exit \d+\):\s*([\s\S]*)$/.exec(text); - const body = (afterExit?.[1] ?? text).replace(/^\w*Error:\s*/, '').trim(); - if (/destination changed|refusing to overwrite/i.test(body)) return tr('Your files changed after this trial started, so nothing was overwritten. Run Time-skip again.'); - if (/too big/i.test(body)) return tr('This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.'); - if (/folder of your own/i.test(body)) return tr('Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.'); - if (/Load a model|model first/i.test(body)) return tr('Load a model first, then try Time-skip again.'); - if (/needs the Strata app|could not be reached/i.test(body)) return tr('The assistant could not be reached. Try again.'); - return body.length > 300 ? body.slice(0, 299) + '…' : body; -} - -/** The host says a Time-skip run moved on (phase, and what it is doing now): the working view shows the newest words. */ -function applyTimeSkipEvent(data: Record<string, unknown>) { - const id = typeof data.id === 'string' ? data.id : ''; - if (!id) return; - for (const session of state.sessions) { - const run = session.timeSkips?.find(r => r.job?.id === id); - if (!run || run.completedAt) continue; - patchRun(session.id, run.id, r => ({ ...r, job: { ...r.job!, ...(typeof data.phase === 'string' ? { phase: data.phase as TimeSkipJob['phase'] } : {}), activity: data.activity as TimeSkipJob['activity'], ...forkFields(data) } })); - } -} - -function timeSkipEnding(job: TimeSkipJob, files: TimeSkipFile[]): string { - if (job.phase === 'failed') return tr('Time-skip stopped. {0} Your files were not changed.', [plainTimeSkipError(job.error)]); - if (job.phase === 'cancelled' || job.phase === 'interrupted') return tr('Time-skip was stopped before it finished. Your files were not changed.'); - if (!files.length) return tr('The assistant did not change anything, so there is nothing to compare. Your files were not changed.'); - return isForkJob(job) ? tr('Both versions are ready. Compare A and B, then keep one.') : TS_READY(); -} - -async function startTimeSkipReal(prompt: string) { - const sessionId = state.activeSession ?? newSession().id; - const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now(), - job: { id: '', phase: 'queued', attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: false, error: null } }; - const at = new Date().toISOString(); - patchSession(sessionId, s => ({ ...s, - defaultTitle: false, - title: s.messages.length ? s.title : prompt.length > 48 ? prompt.slice(0, 47).trimEnd() + '…' : prompt, updatedAt: at, - // The comparison sidebar opens only when there is an update to compare (when the job ends with changed files), never while it works. - timeSkips: [...(s.timeSkips ?? []), run], - messages: [...s.messages, - { id: uid('m'), role: 'user', at, content: '/time-skip ' + prompt, timeSkipId: run.id }, - { id: uid('m'), role: 'assistant', at, timeSkipId: run.id, content: TS_WORKING() }, - ], - })); - go('chat', sessionId); - markTurn(sessionId, { abort: new AbortController(), agent: false }); - try { - const started = await api.post<{ run: TimeSkipJob }>('/api/timeskip/start', { prompt, sessionId, workspaceId: state.activeWorkspace, attempts: 1, ...(state.remoteModel ? { remoteModel: state.remoteModel } : {}) }); - patchRun(sessionId, run.id, r => ({ ...r, job: started.run })); - void followTimeSkip(sessionId, run.id); - } catch (e) { - const message = plainTimeSkipError(e instanceof Error ? e.message : String(e)); - patchRun(sessionId, run.id, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'failed', error: message } }), tr('Time-skip could not start. {0}', [message])); - markTurn(sessionId, null); - } -} - -const followingTimeSkips = new Set<string>(); -/** Read the job's record until it ends. Safe to call again for a run already being followed. */ -export async function followTimeSkip(sessionId: string, runId: string) { - const key = sessionId + ':' + runId; - if (followingTimeSkips.has(key)) return; - followingTimeSkips.add(key); - let misses = 0; - try { - for (;;) { - const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); - if (!run?.job?.id || run.completedAt) return; - let job: TimeSkipJob | null = null; - try { job = (await api.get<{ run: TimeSkipJob }>('/api/timeskip/status?id=' + encodeURIComponent(run.job.id))).run; misses = 0; } - catch { misses += 1; } - if (job && TS_TERMINAL.includes(job.phase)) { - let files: TimeSkipFile[] = [], extra: Partial<TimeSkipJob> = {}; - // The changed files are what the person came for: ask again a few times before settling for "nothing to compare". - for (let tryNo = 0; tryNo < 4; tryNo++) { - try { - const found = await api.get<{ files: TimeSkipFile[]; applyAttempt: number | null; more: number }>('/api/timeskip/files?id=' + encodeURIComponent(job.id)); - files = found.files; extra = { files: found.files, applyAttempt: found.applyAttempt, moreFiles: found.more }; - break; - } catch { await new Promise(r => setTimeout(r, 700 * (tryNo + 1))); } - } - const finished = { ...job, ...forkFields(job as unknown as Record<string, unknown>) }; - patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, ...finished, ...extra } }), timeSkipEnding(finished, files)); - // A run that changed files opens the comparison; one that changed nothing, failed or was stopped has no sidebar tab. - if (files.length > 0 && !['failed', 'cancelled', 'interrupted'].includes(finished.phase)) patchSession(sessionId, s => ({ ...s, previewOpen: timeSkipTabId(runId) })); - markTurn(sessionId, null); - return; - } - if (job) { const live = { ...job, ...forkFields(job as unknown as Record<string, unknown>) }; patchRun(sessionId, runId, r => ({ ...r, job: { ...r.job!, ...live } })); } - if (misses >= 6) { - patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'interrupted' } }), tr('Time-skip lost contact with the app and stopped. Your files were not changed.')); - markTurn(sessionId, null); - return; - } - await new Promise(r => setTimeout(r, 2000)); - } - } finally { followingTimeSkips.delete(key); } -} - -/** Ask the host to stop a running trial. The saved version stays. */ -export async function stopTimeSkip(sessionId: string, runId: string) { - const id = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId)?.job?.id; - if (id) await api.post('/api/timeskip/stop', { id }).catch(() => undefined); -} - -/** Put the update into the person's files, or put the original back. Both are checked and undoable. */ -export async function keepTimeSkip(sessionId: string, runId: string, version: TimeSkipVersion) { - const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); - const job = run?.job; - if (!run || !job?.id || !job.phase || !TS_TERMINAL.includes(job.phase)) return; - if ((run.retainedVersion ?? 'original') === version && !(isForkJob(job) && run.retainedVersion === undefined)) { patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); return; } - try { - if (isForkJob(job)) await api.post('/api/timeskip/apply', { id: job.id, which: version === 'original' ? 'a' : 'b' }); - else if (version === 'updated') await api.post('/api/timeskip/apply', { id: job.id, attempt: job.applyAttempt ?? null }); - else await api.post('/api/timeskip/apply', { id: job.id, restore: true }); - patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); - pushToast('success', version === 'updated' ? tr('The update is now in your files') : tr('Your original files are back')); - } catch (e) { - pushToast('error', tr('Your files were not changed'), plainTimeSkipError(e instanceof Error ? e.message : String(e))); - } -} - -function startTimeSkipDemo(prompt: string) { - if (!prompt) { pushToast('info', 'Add a prompt after /time-skip', 'For example: /time-skip Make a launch plan for my app'); return; } - const sessionId = state.activeSession ?? newSession().id; - const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now() }; - const at = new Date().toISOString(); - patchSession(sessionId, s => ({ ...s, - defaultTitle: false, - title: s.messages.length ? s.title : prompt.length>48?prompt.slice(0,47).trimEnd()+'…':prompt, updatedAt: at, - timeSkips: [...(s.timeSkips ?? []), run], previewOpen: timeSkipTabId(run.id), - messages: [...s.messages, - { id: uid('m'), role: 'user', at, content: `/time-skip ${prompt}`, timeSkipId: run.id }, - { id: uid('m'), role: 'assistant', at, example: true, timeSkipId: run.id, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks; it doesn’t run your model.' }, - ], - })); - scheduleTimeSkip(sessionId, run); - go('chat', sessionId); -} - -function markTurn(sessionId: string, turn: { abort: AbortController; agent: boolean } | null) { - if (turn) liveTurns.set(sessionId, turn); else liveTurns.delete(sessionId); - set({ streaming: !!state.activeSession && liveTurns.has(state.activeSession), liveChats: liveTurns.size }); - document.documentElement.dataset.streaming = liveTurns.size ? 'true' : 'false'; -} - -/** - * Stop the open chat's turn. The host is asked first: for an agent turn it cancels exactly this chat's - * Harness session and answers only once the turn has ended, and the stream then closes by itself with - * what was produced. For any other turn the host reports nothing to stop and the request is aborted. - */ -export function stopStreaming() { - const id = state.activeSession; - const turn = id ? liveTurns.get(id) : undefined; - if (!id || !turn) return; - const abort = () => { turn.abort.abort(); }; - void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then( - result => { - if (!result.stopped) abort(); - // An agent turn that was told to stop but is slow to end must not leave the chat stuck. - else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); - }, - abort, - ); -} - -/** - * Re-runs the last exchange: drops the assistant reply and asks again. - * - * Kept in the store rather than the screen because it has to touch the message - * list, and every attempt to do this from a component ends up duplicating the - * stream handling that already lives here. - */ -export async function retryLast(messageId?: string) { - const source = state.sessions.find(s => s.id === state.activeSession); - if (!source || state.streaming) return; - const end = messageId ? source.messages.findIndex(m => m.id === messageId) : source.messages.length - 1; - const user = source.messages.slice(0, end + 1).reverse().find(m => m.role === 'user'); - if (!user) return; - const prompt = rewindTo(user.id); - if (prompt !== null) { - // Retry sends immediately; only Edit should leave the prompt in the composer. - sessionStorage.setItem(`strata.chat-draft.${state.activeSession}`, ''); - await sendMessage(prompt); - } -} - -/** The open chat's last question and the answer that failed under it (null when the chat does not end that way). */ -function failedExchange(): { prompt: string; sessionId: string } | null { - const sessionId = state.activeSession; - const chat = state.sessions.find(s => s.id === sessionId); - if (!sessionId || !chat || state.streaming) return null; - const reply = chat.messages[chat.messages.length - 1], ask = chat.messages[chat.messages.length - 2]; - return reply?.role === 'assistant' && reply.error && ask?.role === 'user' ? { prompt: ask.content, sessionId } : null; -} -/** Takes the failed question and its error out of the transcript, so asking again does not show the question twice. */ -function dropFailedExchange(sessionId: string) { - patchSession(sessionId, s => ({ ...s, messages: s.messages.slice(0, -2) })); -} - -/** - * The error card of a conversation that no longer fits the model's window: summarise the older messages (the same as typing /compact), then - * ask the assistant to answer. The refused question is already in the assistant's conversation (it is the newest message, and a summary keeps - * the newest message as it is), so it is not sent a second time: a large one twice would not fit either. - */ -export async function summarizeAndContinue() { - if (!failedExchange()) return; - await sendMessage('/compact'); - await sendMessage('Please answer my last message now.'); -} - -/** - * The error card of a message that is too large to send: the host makes it small enough (its text as a file in the chat's folder that the - * assistant reads in parts, or a shortened preview), and that is sent in its place. - */ -export async function sendOversized(mode: 'file' | 'preview') { - const failed = failedExchange(); - if (!failed) return; - let reply: { message?: string }; - try { - reply = await api.post<{ message?: string }>('/api/chat/oversize', { sessionId: failed.sessionId, mode, text: failed.prompt, nativeModelId: nativeState()?.instances.length ? nativeState()?.defaultId : undefined }); - } catch { - pushToast('error', 'The message could not be prepared. Try a shorter message.'); - return; - } - if (!reply.message) return; - dropFailedExchange(failed.sessionId); - await sendMessage(reply.message); -} - -/** A new, empty chat, opened. */ -export function startNewChat() { - const session = newSession(); - go('chat', session.id); -} - -/** - * Forks a conversation at a message, leaving the original untouched. - * - * The alternative people reach for is duplicating the whole session and - * deleting messages by hand, which loses the original. Branching keeps both: - * the new session carries the history up to the chosen turn and diverges there. - */ -export function branchFrom(messageId: string): string | null { - const sessionId = state.activeSession; - if (!sessionId) return null; - const source = state.sessions.find((s) => s.id === sessionId); - if (!source) return null; - const at = source.messages.findIndex((m) => m.id === messageId); - if (at < 0) return null; - - const now = new Date().toISOString(); - const branch: Session = { - ...source, - id: uid('s'), - title: `${source.title} (branch)`, - defaultTitle: false, - createdAt: now, - updatedAt: now, - messages: source.messages.slice(0, at + 1).map((m) => ({ ...m, id: uid('m') })), - tokensIn: 0, - tokensOut: source.messages.slice(0, at + 1).reduce((n, m) => n + (m.tokens ?? 0), 0), - statsAvailable: false, - }; - const sessions = [branch, ...state.sessions]; - persistSessions(sessions); - set({ sessions, activeSession: branch.id }); - for (const run of branch.timeSkips ?? []) scheduleTimeSkip(branch.id, run); - // The URL wins over `activeSession` when it names a session, so a programmatic - // switch has to move the route too — otherwise the sidebar shows the branch - // while the transcript still shows the original, which reads as a broken - // button rather than a created branch. - navigate('chat', branch.id); - return branch.id; -} - -/** - * Asks the model to keep going from where it stopped. - * - * Sent as an ordinary user turn rather than a special mode, because that is - * what it is: a continuation is a request, and the transcript should show it. - */ -export async function continueLast() { - const sessionId = state.activeSession; - if (!sessionId || state.streaming) return; - const session = state.sessions.find((s) => s.id === sessionId); - const last = session?.messages[session.messages.length - 1]; - if (!last || last.role !== 'assistant' || !last.content.trim()) return; - await sendMessage('Continue from where you left off. Do not repeat what you have already written.'); -} - -/** - * Rewinds the transcript to just before a turn so it can be re-asked with a - * different prompt. Returns the text so the composer can be filled with it. - */ -export function rewindTo(messageId: string): string | null { - if (state.streaming) return null; - const source = state.sessions.find(s => s.id === state.activeSession); - const at = source?.messages.findIndex(m => m.id === messageId) ?? -1; - if (!source || at < 0) return null; - const prompt = source.messages[at].content; - const branchId = branchFrom(messageId); - if (!branchId) return null; - patchSession(branchId, s => ({ ...s, messages: s.messages.slice(0, -1), tokensIn: 0, tokensOut: s.messages.slice(0, -1).reduce((n, m) => n + (m.tokens ?? 0), 0) })); - sessionStorage.setItem(`strata.chat-draft.${branchId}`, prompt); - return prompt; -} - -export function exportConversation() { - const session = state.sessions.find(s => s.id === state.activeSession); - if (!session) return; - const text = '# ' + session.title + '\n\n' + session.messages.map(m => '## ' + m.role + '\n\n' + (m.role === 'assistant' ? tidyAnswer(m.content) : m.content)).join('\n\n'); - const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown' })); - const a = document.createElement('a'); a.href = url; a.download = session.title.replace(/[^a-z0-9 -]/gi, '').slice(0, 60) + '.md'; - document.body.append(a); a.click(); a.remove(); - // Keep the Blob alive until browsers have started consuming the download. - setTimeout(() => URL.revokeObjectURL(url), 1000); -} - -/* ---------------------------------------------------------------- /loop - The same message, again and again, while the chat is open. The scheduler (count, time, "the answer says it is done") is - lib/loop-runner.ts; this is the part that talks to the chat. See lib/loop.ts. */ - -/** A line from the app itself (not the model) in the transcript. It is never sent to the model. */ -function addNote(sessionId: string, content: string) { - const at = new Date().toISOString(); - patchSession(sessionId, s => ({ ...s, updatedAt: at, messages: [...s.messages, { id: uid('m'), role: 'assistant', at, content, local: true }] })); -} - -const lastAnswer = (sessionId: string) => [...(state.sessions.find(s => s.id === sessionId)?.messages ?? [])].reverse().find(m => m.role === 'assistant' && !m.local); - -const loopScheduler = new LoopScheduler({ - async send(sessionId, { text, shown }) { - const before = lastAnswer(sessionId)?.id; - await sendMessage(text, { fromLoop: true, shown, title: shown.length > 48 ? shown.slice(0, 47).trimEnd() + '…' : shown }); - const answer = lastAnswer(sessionId); - if (!answer || answer.id === before || answer.streaming) return { answered: false, text: '', failed: false }; - return { answered: true, text: answer.content ?? '', failed: !!answer.error }; - }, - note: addNote, - exists: sessionId => state.sessions.some(s => s.id === sessionId), - ready: sessionId => state.activeSession === sessionId && !state.streaming, - now: () => Date.now(), - setTimer: (fn, ms) => setTimeout(fn, ms), - clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>), - track: (sessionId, loop) => patchSession(sessionId, s => ({ ...s, loop })), -}); - -export function loopIsRunning(sessionId: string | null): boolean { return loopScheduler.isRunning(sessionId); } - -/* ------------------------------------------------------------- task board */ - -/** The chats with a turn going, and the chats with a loop going: what the board needs besides the sessions themselves. */ -export function liveChatIds(): string[] { return [...liveTurns.keys()]; } -export function loopChatIds(): string[] { return loopScheduler.ids(); } - -/** Stop any chat's turn, not only the open one (the board's Stop). Same two-step as stopStreaming. */ -export function stopChat(id: string) { - const turn = liveTurns.get(id); - if (!turn) return; - const abort = () => { turn.abort.abort(); }; - void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then( - result => { if (!result.stopped) abort(); else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); }, - abort, - ); -} - -/** Stop a chat's loop from the board. The chat gets the same line /loop stop writes. */ -export function stopLoop(id: string) { - if (loopScheduler.stop(id)) addNote(id, tr('The loop is stopped.')); -} - -/** Dismiss a chat's (or its loop's) card: it leaves the board until something newer goes wrong. The chat itself is untouched. */ -export function dismissChat(id: string) { - const sessions = state.sessions.map(s => (s.id === id ? { ...s, ackedAt: new Date().toISOString() } : s)); - persistSessions(sessions); - set({ sessions }); -} - -/** Answer a waiting tool card in any chat (the board's Approve and Deny). Only a live card has an approval behind it. */ -export function answerChatTool(sessionId: string, messageId: string, toolId: string, approved: boolean) { - const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId); - if (tool?.live && tool.state === 'proposed') answerAgentTool(sessionId, messageId, tool, approved); -} - -/** "Continue in a new chat" on a chat or a loop that went wrong: a new chat that starts from what happened (src/lib/task-handover.ts). */ -export function continueChatInNewChat(sessionId: string) { - const old = state.sessions.find(s => s.id === sessionId); - if (!old) return; - const session = newSession(); - go('chat', session.id); - void sendMessage(chatHandoverMessage(old), { title: chatHandoverTitle(old), markdown: true }); -} - -async function runLoopCommand(command: LoopCommand) { - const sessionId = state.activeSession ?? newSession().id; - const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); }; - if (command.kind === 'help') { say(tr(command.problem) + '\n\n' + tr(LOOP_USAGE)); return; } - if (command.kind === 'status') { say(loopScheduler.describe(sessionId) ?? tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE)); return; } - if (command.kind === 'stop') { say(loopScheduler.stop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; } - go('chat', sessionId); - await loopScheduler.start(sessionId, command); -} - -/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */ -export async function resumeGoal() { await sendMessage('', { goalAction: 'resume' }); } - -/** Approve a proposed plan and carry it out: the host answers with the message that does the work, which goes out as an ordinary turn. */ -export async function approvePlan(sessionId: string, planId: string) { - const { prompt } = await planApprove(sessionId, planId); - // A chat in Plan mode only reads; carrying the plan out needs a mode that may act. - if (state.sessions.find(s => s.id === sessionId)?.preferences?.mode === 'plan') setChatPreferences(sessionId, { mode: 'manual' }); - if (prompt) await sendMessage(prompt, { shown: tr('Approved the plan.') }); -} - -/** "Start as goal" (and Resume on a paused plan): the host streams the run like any chat turn. */ -export async function startPlanGoal(planId: string) { await sendMessage('', { planId }); } - -export async function sendMessage(text: string, options: { fromLoop?: boolean; goalAction?: 'resume'; planId?: string; shown?: string; title?: string; markdown?: boolean } = {}) { - if (state.streaming) { - // Typed while the assistant works: behind a running goal it waits in the queue; otherwise there is nothing to do but wait. - const waiting = state.activeSession, line = text.trim(); - if (waiting && line && !options.planId && !options.goalAction) { - try { if (!(await queueMessage(waiting, line))) pushToast('info', 'The assistant is still answering', 'Send your message when it has finished.'); } - catch (e) { pushToast('error', 'The message was not queued', plainFailureText(e instanceof Error ? e.message : String(e)).message); } - } - return; - } - const resume = options.goalAction === 'resume'; - const planStart = options.planId; - const loopCommand = options.fromLoop || resume || planStart ? null : parseLoop(text.trim()); - if (loopCommand) { await runLoopCommand(loopCommand); return; } - const demoPrompt = resume || planStart ? null : timeSkipPrompt(text.trim()); - if (demoPrompt !== null) { - if (demoPrompt && (state.remoteModel || nativeState()?.instances.some(i => i.status === 'ready'))) void startTimeSkipReal(demoPrompt); else if (state.connection === 'live' && demoPrompt) pushToast('info', 'Load a model first', 'Time-skip works on a loaded model. Choose one on the Models tab, then try again.'); - else if (state.connection === 'connecting' && demoPrompt) pushToast('info', 'Still starting up', 'Time-skip needs the app to finish starting. Try again in a moment.'); - else startTimeSkipDemo(demoPrompt); - return; - } - // Whatever sent this (the box, a loop, a plan): with no model to answer, say so in plain words and start nothing. - if (state.connection === 'live') { - // The first read of the engine's state has not come back yet: do not say "no model" about something not known yet, and do not send. - if (!nativeState() && !state.remoteModel && !state.library?.loaded) { pushToast('info', 'Still starting up', 'Strata is still checking your models. Try again in a moment.'); return; } - const why = noModelNotice(nativeState(), { remote: !!state.remoteModel, libraryLoaded: !!state.library?.loaded }); - if (why) { pushToast('info', why.title, why.message); return; } - } - const pictureCheck=pictureStatus(nativeState(),state.remoteModel,state.providers); - if(pendingChatPhotos(state.activeSession).length&&!pictureCheck.ok){pushToast('error','This model cannot read pictures',tr(pictureCheck.message));return;} - const pictures=takeChatPhotos(state.activeSession); - const body=text.trim()||(pictures.length?'Describe this picture.':''); - if(!body&&!resume&&!planStart)return; - - let sessionId = state.activeSession; - if (!sessionId) sessionId = newSession().id; - - const userMsg: ChatMessage = { id: uid('m'), role: 'user', content: options.shown ?? body, at: new Date().toISOString(),...(pictures.length?{photos:pictures}:{}),...(options.markdown?{markdown:true}:{}) }; - let assistantId = uid('m'); - const assistantMsg: ChatMessage = { - id: assistantId, - role: 'assistant', - content: '', - at: new Date().toISOString(), - streaming: true, - }; - - /* Everything said before this turn, which the model needs in order to have a - conversation at all. - - It was never sent. The real-engine path builds its prompt as - `[...history, message]`, and `history` was always empty, so each message - arrived as the first thing the model had ever heard — no memory of the - turns above it in the transcript. The demo path hides this, because its - replies are canned. - - The context meter was reading the same empty array, which is why it sat at - ~350 tokens however long the conversation grew. */ - const prior = (state.sessions.find((s) => s.id === sessionId)?.messages ?? []) - .filter(m => !m.timeSkipId && !m.local) - .filter((m) => m.role === 'user' || m.role === 'assistant') - .filter((m) => m.content.trim()) - .map((m) => ({ role: m.role, content: m.content,photos:m.photos })) - // Bounded so a long conversation cannot send an unbounded body. - .slice(-40); - - patchSession(sessionId, (s) => ({ - ...s, - defaultTitle: false, - title: s.messages.length === 0 && !resume && !planStart ? (options.title ?? (body.length>48?body.slice(0,47).trimEnd()+'…':body)) : s.title, - updatedAt: new Date().toISOString(), - messages: [...s.messages, ...(resume || planStart ? [] : [userMsg]), assistantMsg], - })); - - const turnAbort = new AbortController(); - markTurn(sessionId, { abort: turnAbort, agent: false }); - // Read by the router to skip view transitions mid-stream, and by CSS to keep - // the transcript still while tokens arrive. - - const patchAssistant = (fn: (m: ChatMessage) => ChatMessage) => - patchSession(sessionId, (s) => ({ - ...s, - updatedAt: new Date().toISOString(), - messages: s.messages.map((m) => (m.id === assistantId ? fn(m) : m)), - })); - - const started = performance.now(); - - const imageSlots=photoHistorySlots(prior,pictures.length); - /* Text and reasoning arrive token by token (90 a second or more). Drawing the whole answer again for each one made the page do more work for every - word the longer the answer grew (measured: 15.7 s of main-thread time for 24 s of a 40,000-token answer), until the page stopped answering - and ran out of memory. The pieces are gathered and applied together about ten times a second; any other frame, the end and a failure - apply what is waiting first, so the order the person sees is the order it was written. */ - const waiting: ['reasoning' | 'delta', string][] = []; - let waitingTimer: ReturnType<typeof setTimeout> | null = null; - const applyReasoning = (text: string) => patchAssistant((m) => ({ ...m, reasoning: (m.reasoning ?? '') + text, reasoningStartedAt: m.reasoningStartedAt ?? Date.now() })); - const applyDelta = (text: string) => patchAssistant((m) => { const content=tidyAnswer(m.content+text); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,...(m.blocks?{blocks:appendText(m.blocks,text)}:{}),tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; }); - const flushWaiting = () => { - if (waitingTimer !== null) { clearTimeout(waitingTimer); waitingTimer = null; } - for (const [kind, text] of waiting.splice(0)) if (kind === 'delta') applyDelta(text); else applyReasoning(text); - }; - const queueText = (kind: 'reasoning' | 'delta', text: string) => { - const last = waiting[waiting.length - 1]; - if (last && last[0] === kind) last[1] += text; else waiting.push([kind, text]); - waitingTimer ??= setTimeout(flushWaiting, 90); - }; - try { - await streamPost( - planStart ? '/api/plan/start-goal' : '/api/chat/stream', - { - sessionId, - ...(planStart ? { planId: planStart } : {}), - ...(resume ? { goalAction: 'resume' } : planStart ? {} : { message: options.shown ? body : body }), - history:await Promise.all(prior.map(async(m,index)=>{const included=pictureCheck.ok?(m.photos??[]).filter((_,p)=>imageSlots.has(`${index}:${p}`)):[];const omitted=(m.photos??[]).filter(p=>!included.includes(p));const text=m.content+(omitted.length?`\n[Earlier pictures: ${omitted.map(p=>p.name).join(', ')}. Their pixels are outside this model's image context; ask to reattach them if needed.]`:'');return {role:m.role,content:included.length?[{type:'text',text},...await Promise.all(included.map(async photo=>({type:'image_url',image_url:{url:(await photoData(photo)).url}})))]:text};})), - model: state.library?.loaded ?? state.library?.current ?? null, - remoteModel: state.remoteModel, - nativeModelId:nativeState()?.instances.length?nativeState()?.defaultId:undefined, - ...(pictures.length ? { imageIds: await uploadChatPhotos(pictures, sessionId) } : {}), - useTools:state.sessions.find(s=>s.id===sessionId)?.preferences?.useTools===true, - // A chat set to plain talk (preferences.agent === false) never runs a tool: the host answers it directly. - ...(state.sessions.find(s=>s.id===sessionId)?.preferences?.agent===false?{agent:false}:{}), - thinking:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinking??'Medium', - thinkingBudget:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinkingBudget??0, - // 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: 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. - if (frame.type === 'delta' && typeof frame.key === 'string') frame = { ...frame, text: tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) }; - const type = frame.type as string; - if (type === 'delta' || type === 'reasoning') { queueText(type, String(frame.text ?? '')); return; } - flushWaiting(); - if (type === 'start' && frame.agent === true) { const turn = liveTurns.get(sessionId); if (turn) turn.agent = true; } - if (type === 'queued') { - patchAssistant(m => ({ ...m, requestId: String(frame.requestId) })); - } else if (type === 'start') { - patchAssistant((m) => ({ ...m, demo: frame.demo === true, remoteModel: frame.remoteModel === true, requestId: typeof frame.requestId === 'string' ? frame.requestId : m.requestId, model: String(frame.model), contextMax: Number(frame.contextMax), skillsUsed: Array.isArray(frame.skills) ? frame.skills.map(String) : [] })); - } else if (type === 'status') { - applyStatusFrame(sessionId, frame as Record<string, unknown>); - // Manual mode waits for the person: a notification when they have opted in and Strata is in the background (#3477), once per question. - if (frame.code === 'waiting-approval' && lastApprovalNotice !== `${sessionId}:${String(frame.seq)}`) { - lastApprovalNotice = `${sessionId}:${String(frame.seq)}`; - const tool = (frame.args as { tool?: unknown } | undefined)?.tool; - void approvalNeeded(state.approvalNotify, typeof tool === 'string' ? tool : ''); - } - } else if (type === 'goal') { - applyGoalFrame(sessionId, frame.goal); - } else if (type === 'plan') { - applyPlanFrame(sessionId, frame.plan); - // A proposed plan is shown as the plan card in place of this turn's closing text (that text is the plan in prose). - const planned = frame.plan as { id?: unknown } | null; - if (frame.event === 'proposed' && planned && typeof planned.id === 'string') { const pid = planned.id; patchAssistant(m => ({ ...m, planId: pid })); } - } else if (type === 'queued-message') { - applyQueueFrame(sessionId, frame.queue); - const sent = frame.message as { text?: unknown } | undefined; - if (frame.state === 'delivered' && sent && typeof sent.text === 'string') { - // The host has just sent it into the run: it becomes an ordinary message here, and the answer to it starts a new reply. - const before = assistantId; assistantId = uid('m'); - const next: ChatMessage = { id: assistantId, role: 'assistant', content: '', at: new Date().toISOString(), streaming: true }; - patchSession(sessionId, sess => ({ ...sess, messages: [...sess.messages.map(m => m.id === before ? { ...m, streaming: false } : m), { id: uid('m'), role: 'user', content: sent.text as string, at: new Date().toISOString() }, next] })); - } - } else if (type === 'queued-release') { - // The goal ended with messages left: they go out now, in order, as ordinary messages once this turn has finished. - const left = Array.isArray(frame.messages) ? frame.messages.flatMap(q => (q && typeof (q as { text?: unknown }).text === 'string' ? [String((q as { text: string }).text)] : [])) : []; - if (left.length) releasedMessages.set(sessionId, [...(releasedMessages.get(sessionId) ?? []), ...left]); - } else if (type === 'plan-step') { - /* the whole plan follows in a plan frame; the live status already says which step is running */ - } else if (type === 'reasoning') { - /* applied through queueText above */ - } else if (type === 'notice') { - // The host says why this chat is not using the agent. One toast per reason per page load. - const code = String(frame.code ?? 'notice'); - if (!noticed.has(code)) { noticed.add(code); pushToast('info', 'Agent', plainFailureText(String(frame.message ?? '')).message); } - } else if (type === 'agent-question') { - addAgentAsk(sessionId, frame as { callId?: unknown; questions?: unknown }); - } else if (type === 'agent-question-end') { - removeAgentAsk(sessionId, String(frame.callId ?? '')); - } else if (type === 'agent-tool') { - const tool = frame.tool as ToolCall; - patchAssistant(m => { - const existing = m.tools?.find(t => t.id === tool.id); - const next: ToolCall = { ...existing, ...tool, live: true }; - return { ...m, tools: existing ? m.tools!.map(t => t.id === tool.id ? next : t) : [...(m.tools ?? []), next] }; - }); - } else if (type === 'agent') { - patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) })); - } else if (type === 'delta') { - /* applied through queueText above */ - } else if (type === 'deliverable') { - const file = readDeliverable(frame); - if (file) patchAssistant(m => ({ ...m, deliverables: mergeDeliverable(m.deliverables, file) })); - } else if (type === 'skills-used') { - const skills = readSkills(frame); - if (skills.length) patchAssistant(m => ({ ...m, skills })); - } else if (type === 'activity-group') { - const group = readGroup(frame); - if (group) patchAssistant(m => ({ ...m, blocks: upsertGroup(m.blocks ?? (m.content ? appendText(undefined, m.content) : undefined), group) })); - } else if (type === 'artifacts' && Array.isArray(frame.artifacts)) { - patchAssistant(m => ({ ...m, artifacts: frame.artifacts as PreviewArtifact[] })); - } else if(type==='native-tool'){ - const event=frame.event as {event:string;id:string;name?:string;arguments?:Record<string,unknown>;text?:string;ok?:boolean;ms?:number}; - if(event.id)patchAssistant(m=>{const existing=m.tools?.find(t=>t.id===event.id);const tool={id:event.id,name:event.name??existing?.name??'Connected tool',args:event.arguments??existing?.args??{},preview:'Authorized connected tool',effect:'Access configured in the MCP server',scope:'connected' as const,state:event.event==='result'?event.ok?'done' as const:'error' as const:'running' as const,result:event.text,durationMs:event.ms};return {...m,tools:[...(m.tools??[]).filter(t=>t.id!==tool.id),{...existing,...tool}]};}); - } else if (type === 'tool') { - const tool = frame.tool as ChatMessage['tools'] extends (infer T)[] | undefined ? T : never; - patchAssistant((m) => ({ ...m, tools: [...(m.tools ?? []), { ...tool, state: 'proposed' }] })); - } else if (type === 'stats') { - patchAssistant((m) => ({ - ...m, - tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : m.tokens, - tps: typeof frame.tps === 'number' ? frame.tps : m.tps, - promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps, - })); - } else if (type === 'context') { - // What the context holds after each model request of an agent turn: the meter follows the turn instead of waiting for its end. - const used = Number(frame.contextTokens), max = Number(frame.contextMax); - if (Number.isFinite(used) && used > 0) patchAssistant((m) => ({ ...m, contextUsed: used, ...(Number.isFinite(max) && max > 0 ? { contextMax: max } : {}) })); - } else if (type === 'error') { - clearStatus(sessionId); - // A sentence the host wrote for the person (it carries its catalog key) is shown in their language as it is; anything else is made plain here. - const said = typeof frame.key === 'string' ? tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) : plainFailure(String(frame.message ?? 'Engine error')).message; - patchAssistant((m) => ({ ...m, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) })); - } else if (type === 'done') { - clearStatus(sessionId); - workFinished(state.doneSound, Number(frame.durationMs ?? performance.now() - started)); - patchSession(sessionId, (sess) => ({ - ...sess, - tokensIn: sess.tokensIn + Number(frame.tokensIn ?? 0), - tokensOut: sess.tokensOut + Number(frame.tokensOut ?? 0), - statsAvailable: typeof frame.tokensIn === 'number' && typeof frame.tokensOut === 'number' && sess.messages.filter(m=>m.role==='assistant'&&!m.streaming).every(m=>typeof m.inputTokens==='number'), - })); - patchAssistant((m) => ({ - ...m, - streaming: false, - durationMs: Number(frame.durationMs ?? performance.now() - started), - tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : undefined, - ttftMs: typeof frame.ttftMs === 'number' ? frame.ttftMs : undefined, - inputTokens: typeof frame.tokensIn === 'number' ? frame.tokensIn : undefined, - contextUsed: typeof frame.contextTokens === 'number' ? frame.contextTokens : undefined, - usageSource: frame.usageSource === 'reported' || frame.usageSource === 'demo' ? frame.usageSource : 'unavailable', - tps: typeof frame.tps === 'number' ? frame.tps : m.tps, - promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps, - })); - // The final text is in `state`: write it once now instead of waiting for the coalescing timer. - flushSessions(); - } - }, - turnAbort.signal, - ); - } catch (err) { - flushWaiting(); - if ((err as Error).name !== 'AbortError') { - patchAssistant((m) => ({ - ...m, - streaming: false, - error: err instanceof Error ? err.message : 'Engine error', - })); - pushToast('error', 'Generation failed', err instanceof Error ? err.message : undefined); - } else { - patchAssistant((m) => ({ ...m, streaming: false })); - } - } finally { - flushWaiting(); - // A cancelled or failed turn is still worth keeping. - flushSessions(); - clearStatus(sessionId); - markTurn(sessionId, null); - removeAgentAsk(sessionId); - const next = releasedMessages.get(sessionId)?.shift(); - if (next !== undefined) { if (!releasedMessages.get(sessionId)?.length) releasedMessages.delete(sessionId); setTimeout(() => void sendMessage(next), 0); } - } -} - -/** Messages the host handed back when a goal ended with some still waiting; sent one after another. */ -const releasedMessages = new Map<string, string[]>(); - -/* -------------------------------------------------------------- tool grants */ - -const noticed = new Set<string>(); - -/** - * Approve or deny a tool the agent asked about. The answer goes to the host, which hands it to the - * Harness approval for exactly this chat and call; the card then follows what the Harness reports - * (running, done, denied). The card shows the choice straight away and goes back if the host refuses. - */ -function answerAgentTool(sessionId: string, messageId: string, tool: ToolCall, approved: boolean) { - const setState = (state_: ToolCall['state'], result?: string) => patchSession(sessionId, s => ({ - ...s, messages: s.messages.map(m => m.id === messageId ? { ...m, tools: (m.tools ?? []).map(t => t.id === tool.id ? { ...t, state: state_, ...(result !== undefined ? { result } : {}) } : t) } : m), - })); - setState(approved ? 'running' : 'denied'); - api.post('/api/chat/approval', { sessionId, toolId: tool.id, decision: approved ? 'approve' : 'deny' }).catch(error => { - setState('proposed'); - pushToast('error', 'That answer was not delivered', error instanceof Error ? error.message : undefined); - }); -} - -/** - * Approving a tool in the design build resolves locally: there is no tool - * runtime behind it yet, so the result is a labelled stand-in. The interaction — - * what is asked, what is shown, what needs a grant — is the real deliverable. - */ -export function resolveTool(messageId: string, toolId: string, approved: boolean) { - const sessionId = state.activeSession; - if (!sessionId) return; - const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId); - if (tool?.live) { answerAgentTool(sessionId, messageId, tool, approved); return; } - - patchSession(sessionId, (s) => ({ - ...s, - messages: s.messages.map((m) => - m.id === messageId - ? { - ...m, - tools: (m.tools ?? []).map((t) => - t.id === toolId - ? { - ...t, - state: approved ? 'done' : 'denied', - durationMs: undefined, - result: approved ? 'Approval recorded. Nothing was executed.' : 'Denied. Nothing ran.', - } - : t, - ), - } - : m, - ), - })); - -} - -/* ------------------------------------------------------------------- routes */ - -export function go(route: Route, param?: string) { - navigate(route, param); - // Focus mode is a reading mode for the conversation. Leaving it to work on - // something else leaves the mode, rather than stranding a bare shell. - if (state.focus && route !== 'chat' && route !== 'settings') setFocus(false); - set({ paletteOpen: false, navOpen: false }); -} - -/* ---------------------------------------------------------------- bootstrap */ - -export function bootOnce() { - if ((globalThis as { __strataBooted?: boolean }).__strataBooted) return; - (globalThis as { __strataBooted?: boolean }).__strataBooted = true; - for (const session of state.sessions) for (const run of session.timeSkips ?? []) { scheduleTimeSkip(session.id, run); if (run.job && !run.completedAt) { markTurn(session.id, { abort: new AbortController(), agent: false }); void followTimeSkip(session.id, run.id); } } - // A loop lives in the window: one the last window left "running" has ended, and the board says so. - if (state.sessions.some(s => s.loop?.state === 'running')) { - const sessions = state.sessions.map(s => s.loop?.state === 'running' ? { ...s, loop: { ...s.loop, state: 'ended' as const, endedWhy: 'closed' as const, endedAt: Date.parse(s.updatedAt) || Date.now() } } : s); - persistSessions(sessions); - set({ sessions }); - } - void bootstrap(); - void reconcileAgentTools(); -} - -/** - * After a reload, a tool card the browser remembers as waiting or running may belong to a turn that no - * longer exists. Cards whose approval the host still holds stay answerable; the rest are marked as - * interrupted so nothing looks like it is still working. - */ -async function reconcileAgentTools() { - const open = (t: ToolCall) => t.live && (t.state === 'proposed' || t.state === 'running'); - for (const session of state.sessions) { - if (!session.messages.some(m => m.tools?.some(open))) continue; - let waiting = new Set<string>(); - try { - const r = await api.get<{ pending: { callId: string }[] }>(`/api/agent/pending?chatId=${encodeURIComponent(session.id)}`); - waiting = new Set(r.pending.map(p => p.callId)); - } catch { /* The host is unreachable; leave the cards for the next load. */ continue; } - patchSession(session.id, sess => ({ ...sess, messages: sess.messages.map(m => m.tools?.some(open) ? { ...m, tools: m.tools.map(t => open(t) && !waiting.has(t.id) ? { ...t, state: 'error' as const, result: 'The page closed before this finished. Check the workspace to see what it did.' } : t) } : m) })); - } -} - - -export function setContrast(contrast: 'standard' | 'increased') { set({ contrast }); savePrefs(); } -matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (state.theme === 'system') applyPrefs(); }); - -export async function loadRuntimeModel(body:unknown){ - const result=await api.post<{state:RuntimeModels;instance:{id:string}}>('/api/runtime/load',body); - set({runtime:result.state});return result.instance.id; -} -export async function runtimeModelAction(id:string,action:'unload'|'default'){ - set({runtime:await api.post<RuntimeModels>(`/api/runtime/${id}/${action}`)}); -} - -export async function changeModelDirectory(directory: string, unload: boolean) { - set(s => ({ busy: { ...s.busy, modelDirectory: true } })); - try { - const result = await api.post<{ library: ModelLibrary; imageModels: ImageModelLibrary; runtime: RuntimeModels; hardware: Hardware; setup: SetupState }>('/api/storage/models-directory', { directory, unload }); - set(result); - return result; - } finally { - set(s => ({ busy: { ...s.busy, modelDirectory: false } })); - } -} - -export async function addLocalModel(path: string, name?: string) { - const result = await api.post<{ library: ModelLibrary; variantId: string }>('/api/local-models', { path, name }); - set({ library: result.library }); - return result.variantId; -} +import { workspaceIdForSession } from './session-workspace'; +import { DEFAULT_CONTENT_FS, DEFAULT_UI_SCALE, SIZE_DEFAULTS_VERSION, savedSizes } from './default-sizes'; +import { detectLanguage } from './language-detect'; +import { validWhileBusy, type WhileBusy } from './while-busy'; +import { addToQuotes, type Quote } from './quotes'; +import { readAsk, type AgentAnswer, type AgentAsk } from './agent-ask'; +import { plainFailure, plainFailureText } from './plain-errors'; +import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase'; +import { settleAgents, updateAgent } from './agents'; +import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop'; +import { LoopScheduler } from './loop-runner'; +import { applyStatusFrame, clearStatus } from './live-status'; +import { approvalNeeded, workFinished } from './attention'; +import { applyGoalFrame } from './goal'; +import { tidyAnswer } from './answer-text'; +import { appendText, mergeDeliverable, readDeliverable, readGroup, readSkills, upsertGroup } from './deliverables'; +import { applyPlanFrame, applyQueueFrame, planApprove, queueMessage } from './plan'; +import { forkFields, isForkJob, TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipFile, type TimeSkipJob, type TimeSkipRun, type TimeSkipVersion } from './time-skip'; +import { PREVIEW_EXAMPLES, type PreviewArtifact } from './artifacts'; +import { lifecyclePolicy } from './lifecycle'; +import { newestServingState } from './serving-state'; +import { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos'; +import { applyNativeEvent, nativeState } from './native'; +import { pictureStatus } from './pictures'; +import { noModelNotice } from './no-model'; +import { taskHandoverMessage, taskHandoverTitle, chatHandoverMessage, chatHandoverTitle } from './task-handover'; +import type { Task } from './tasks'; +import { postWithFolderFallback } from './folder-pick'; +import { createSessionWriter } from './session-persist'; +import { setTranslationLanguage, tr, validLanguage, type Language } from './i18n'; +/** + * Strata app store. + * + * A single immutable state object + a tiny subscribe/emit pair, consumed through + * useSyncExternalStore. Data comes from the engine host over /api; live updates + * arrive on the event stream. No state library, no dependencies. + */ +import { useSyncExternalStore } from 'react'; +import { api, onEvent, streamPost, type StreamEvent } from './client'; +import type { + Workspace, + ChatMessage, + ToolCall, + EngineConfig, + Hardware, + ModelLibrary, + RuntimeModels, + ImageModelLibrary, + ImageModelChoice, + ModelProviders, + ModelConnectionDraft, + RemoteModelSelection, + MonitorState, + ServingState, + Session, + SetupState, + Skill, + WorkspaceFile, + ToolDraft, +} from './types'; +import { navigate, type Route } from './router'; +import { estimate, execution, contextTokens } from './experience'; + +export interface Toast { + id: string; + tone: 'info' | 'success' | 'warn' | 'error'; + title: string; + body?: string; + leaving?: boolean; +} + +export interface AppState { + language: Language; + fontFamily: string; + configDraft: string | null; + navOpen: boolean; + ready: boolean; + connection: 'connecting' | 'live' | 'offline'; + theme: 'dark' | 'light' | 'system'; + contrast: 'standard' | 'increased'; + rail: boolean; + /** Distraction-free reading: chrome recedes, the transcript narrows. */ + focus: boolean; + /** Conversation prose size in px, 10–22. Does not touch the UI chrome. */ + contentFontSize: number; + density: 'comfortable' | 'compact'; + motion: 'system' | 'full' | 'reduced'; + /** Translucent materials, or flat surfaces for anyone who prefers them. */ + transparency: 'translucent' | 'opaque'; + /** Chrome scale, independent of the conversation's reading size. */ + uiScale: number; + /** Price of one kWh for the Monitor's cost line (0 = not set) and the currency the person picked instead of the detected one ('' = automatic) (#3628). */ + electricityPrice: number; + electricityCurrency: string; + /** Opt-in: a short sound when a task finishes (#3586). */ + doneSound: boolean; + /** Opt-in: a desktop notification when Manual mode waits for an approval (#3477). */ + approvalNotify: boolean; + /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ + whileBusy: WhileBusy; + /** Governs anonymous usage reporting. Nothing is sent in this build; the + * choice is recorded so a version that does offer it starts from it. */ + shareTelemetry: boolean; + paletteOpen: boolean; + shortcutsOpen: boolean; + settingsSection: 'Appearance' | 'Models' | 'Tools' | 'Storage' | 'Engine' | 'About'; + hardware: Hardware | null; + library: ModelLibrary | null; + imageModels: ImageModelLibrary | null; + runtime: RuntimeModels | null; + providers: ModelProviders | null; + remoteModel: RemoteModelSelection | null; + engine: EngineConfig | null; + serving: ServingState | null; + monitor: MonitorState | null; + setup: SetupState | null; + skills: Skill[]; + files: WorkspaceFile[]; + workspacePath: string; + workspaces: Workspace[]; + /** Id of the workspace the file tree is scoped to. */ + activeWorkspace: string | null; + /** First run, and "run setup again", both present the wizard as a modal. */ + setupOpen: boolean; + sessions: Session[]; + activeSession: string | null; + streaming: boolean; + /** Messages the person sent while an answer was being written, waiting to go when it ends (Send after, Interrupt), by chat (#4783). */ + parked: Record<string, string[]>; + /** The passages quoted into the message being written, by chat, in the order they were quoted (#4785). */ + quotes: Record<string, Quote[]>; + /** The questions the agent asked the person and is waiting for, by chat (#4244). */ + agentAsks: Record<string, AgentAsk[]>; + /** Chats with a turn in flight. `streaming` is about the open chat; this is about all of them. */ + liveChats: number; + toasts: Toast[]; + /** Files the model has been granted read access to, and when. */ + touchedPaths: Record<string, string>; + /** The last action that failed, kept until it is retried or dismissed. + * A toast disappears after five seconds; a failure the reader has not dealt + * with should not. */ + actionError: { message: string; label: string; retry: () => void } | null; + busy: Record<string, boolean>; +} + +const SESSION_KEY = 'strata.sessions.v1'; +const PREFS_KEY = 'strata.prefs.v2'; +/** What the model has been allowed to read, kept across restarts. */ +const TOUCHED_KEY = 'strata.touched.v1'; +/** Kept one release so downgrading does not lose the theme and sidebar state. */ +const PREFS_KEY_V1 = 'strata.prefs.v1'; + +const CONTENT_FS_MIN = 10; +const CONTENT_FS_MAX = 22; + +export interface Prefs { + /** Which default sizes this save was made with (see SIZE_DEFAULTS_VERSION). */ + sizeDefaults?: number; + language: Language; + fontFamily: string; + theme: 'dark' | 'light' | 'system'; + contrast: 'standard' | 'increased'; + rail: boolean; + focus: boolean; + contentFontSize: number; + density: 'comfortable' | 'compact'; + motion: 'system' | 'full' | 'reduced'; + transparency: 'translucent' | 'opaque'; + uiScale: number; + electricityPrice: number; + electricityCurrency: string; + doneSound: boolean; + approvalNotify: boolean; + /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ + whileBusy: WhileBusy; + /** Governs anonymous usage reporting. Nothing is sent in this build; the + * choice is recorded so a version that does offer it starts from it. */ + shareTelemetry: boolean; +} + +const PREFS_DEFAULTS: Prefs = { + language: 'en', + fontFamily: '', + theme: 'system', + contrast: 'standard', + rail: false, + focus: false, + contentFontSize: DEFAULT_CONTENT_FS, + density: 'comfortable', + motion: 'system', + transparency: 'translucent', + uiScale: DEFAULT_UI_SCALE, + electricityPrice: 0, + electricityCurrency: '', + doneSound: false, + approvalNotify: false, + whileBusy: 'wait', + shareTelemetry: false, +}; + +function uid(prefix = 'id'): string { + return `${prefix}_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36).slice(-4)}`; +} + +function loadSessions(): Session[] { + try { + const raw = localStorage.getItem(SESSION_KEY); + if (!raw) return []; + const parsed = JSON.parse(raw) as Session[]; + return Array.isArray(parsed) ? parsed.map(session => ({ + ...session, + ...(session.showcase && !session.showcaseAgentStates ? {agents:SHOWCASE_AGENTS,showcaseAgentStates:true}:{}), + ...(!session.showcase && session.agents ? { agents: settleAgents(session.agents) } : {}), + messages: session.messages.map(message => message.streaming ? { + ...message, + streaming: false, + error: message.error ?? 'Response interrupted. Ask again to retry; the partial answer is kept.', + } : message), + })) : []; + } catch { + return []; + } +} + +/** + * v2 adds focus, reading size, density and the motion override. A v1 blob (only + * theme and rail) is read as-is and upgraded on the next write, so the first run + * after this change keeps the user's theme instead of resetting it. + */ +function loadPrefs(): Prefs { + for (const key of [PREFS_KEY, PREFS_KEY_V1]) { + try { + const raw = localStorage.getItem(key); + if (!raw) continue; + const parsed = JSON.parse(raw) as Partial<Prefs>; + return { + ...PREFS_DEFAULTS, + ...parsed, + language: validLanguage(parsed.language) ? parsed.language : 'en', + fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '', + ...savedSizes(parsed, CONTENT_FS_MIN, CONTENT_FS_MAX), + sizeDefaults: SIZE_DEFAULTS_VERSION, + electricityPrice: Number.isFinite(Number(parsed.electricityPrice)) && Number(parsed.electricityPrice) > 0 && Number(parsed.electricityPrice) < 1000 ? Number(parsed.electricityPrice) : 0, + electricityCurrency: typeof parsed.electricityCurrency === 'string' && /^[A-Za-z]{3}$/.test(parsed.electricityCurrency) ? parsed.electricityCurrency.toUpperCase() : '', + doneSound: parsed.doneSound === true, + approvalNotify: parsed.approvalNotify === true, + whileBusy: validWhileBusy(parsed.whileBusy) ? parsed.whileBusy : 'wait', + }; + } catch { + /* fall through to the next key */ + } + } + // Nothing saved: a first start. It opens in the language of the computer; a choice made on the first screen is saved like any other. + const tags = typeof navigator === 'undefined' ? [] : navigator.languages?.length ? navigator.languages : [navigator.language]; + return { ...PREFS_DEFAULTS, language: detectLanguage(tags) ?? 'en' }; +} + +const prefs = loadPrefs(); +// Use the saved language for the very first render, before host bootstrap. +setTranslationLanguage(prefs.language); + +/** The last approval question a notification was shown for, so one question is announced once. */ +let lastApprovalNotice = ''; + +let state: AppState = { + language: prefs.language, + fontFamily: prefs.fontFamily, + configDraft: (() => { try { return sessionStorage.getItem('strata.config-draft.v1'); } catch { return null; } })(), + navOpen: false, + ready: false, + connection: 'connecting', + shareTelemetry: prefs.shareTelemetry, + theme: prefs.theme, + contrast: prefs.contrast, + rail: prefs.rail, + focus: prefs.focus, + contentFontSize: prefs.contentFontSize, + density: prefs.density, + motion: prefs.motion, + transparency: prefs.transparency, + uiScale: prefs.uiScale, + electricityPrice: prefs.electricityPrice, + electricityCurrency: prefs.electricityCurrency, + doneSound: prefs.doneSound, + approvalNotify: prefs.approvalNotify, + whileBusy: prefs.whileBusy, + parked: {}, + quotes: {}, + agentAsks: {}, + paletteOpen: false, + shortcutsOpen: false, + settingsSection: 'Appearance', + hardware: null, + library: null, + imageModels: null, + runtime: null, + providers: null, + /** The open chat's API model, or null for the local model (the default for every chat). */ + remoteModel: null, + engine: null, + serving: null, + monitor: null, + setup: null, + skills: [], + files: [], + workspacePath: '', + workspaces: [], + activeWorkspace: null, + setupOpen: false, + sessions: loadSessions(), + activeSession: null, + streaming: false, + liveChats: 0, + toasts: [], + touchedPaths: (() => { + try { + return JSON.parse(localStorage.getItem(TOUCHED_KEY) ?? '{}') as Record<string, string>; + } catch { + return {}; + } + })(), + actionError: null, + busy: {}, +}; + +const listeners = new Set<() => void>(); + +/** Chats with a turn in flight: the abort handle, and whether the host is running it as an agent turn. */ +const liveTurns = new Map<string, { abort: AbortController; agent: boolean }>(); + +function set(patch: Partial<AppState> | ((s: AppState) => Partial<AppState>)) { + const before = state.activeSession; + const next = typeof patch === 'function' ? patch(state) : patch; + state = { ...state, ...next }; + // Opening another chat shows that chat's model choice and whether that chat is mid-turn. + if (state.activeSession !== before) { + const chosen = state.sessions.find(s => s.id === state.activeSession)?.preferences?.remoteModel ?? null; + state = { ...state, remoteModel: 'remoteModel' in next ? state.remoteModel : chosen, streaming: !!state.activeSession && liveTurns.has(state.activeSession) }; + } + for (const l of listeners) l(); +} + +function subscribe(l: () => void) { + listeners.add(l); + return () => listeners.delete(l); +} + +export function getState(): AppState { + return state; +} + +export function setConfigDraft(configDraft: string | null) { + set({ configDraft }); + try { + if (configDraft === null) sessionStorage.removeItem('strata.config-draft.v1'); + else sessionStorage.setItem('strata.config-draft.v1', configDraft); + } catch { /* Keep the session draft even when browser storage is unavailable. */ } +} + +export function setNavOpen(navOpen: boolean) { set({ navOpen }); } +export function setSettingsSection(settingsSection: AppState['settingsSection']) { set({ settingsSection }); } + +/** Choose the open chat's model: an API model, or null for the local one. Other chats keep theirs. */ +export function selectRemoteModel(remoteModel: RemoteModelSelection | null) { + if (state.streaming) return; + if (remoteModel && !state.providers?.connections.some(c => c.id === remoteModel.connectionId && c.models.some(m => m.id === remoteModel.modelId))) return; + set({ remoteModel }); + const id = state.activeSession; + if (id) patchSession(id, s => ({ ...s, preferences: { ...s.preferences, remoteModel } })); + try { localStorage.removeItem('strata.remote-model.v1'); } catch { /* The old global choice is retired. */ } +} +function applyProviders(providers: ModelProviders) { + // A chat whose API model was removed keeps its choice: the next send says the model is gone, rather + // than quietly answering from the local model. + set({ providers }); +} +export async function saveModelConnection(draft: ModelConnectionDraft) { + applyProviders(await api.post<ModelProviders>('/api/model-providers', draft)); +} +export async function removeModelConnection(id: string) { + applyProviders(await api.del<ModelProviders>(`/api/model-providers/${encodeURIComponent(id)}`)); +} + +function libraryResponse(data: ModelLibrary): ModelLibrary { + if (!data || !Array.isArray(data.variants)) throw new Error('The engine returned an incomplete model list. Retry the operation.'); + return data; +} + +export function lifecycleStatus(s = state) { + return lifecyclePolicy({ connected: s.connection === 'live', streaming: !!s.streaming || s.liveChats > 0, stats: s.serving?.stats, busy: s.busy }); +} +/** The lifecycle status without subscribing to the whole store: a screen that only needs this must not redraw on every monitor tick (round 8, item 13). */ +export function useLifecycle() { + const connected = useStore(s => s.connection === 'live'); + const streaming = useStore(s => !!s.streaming || s.liveChats > 0); + const stats = useStore(s => s.serving?.stats); + const busy = useStore(s => s.busy); + return lifecyclePolicy({ connected, streaming, stats, busy }); +} +export function lifecycleAvailable(): boolean { + const result = lifecycleStatus(); + if (!result.allowed) pushToast('warn', 'Model change unavailable', result.reason); + return result.allowed; +} + +export function useStore<T>(selector: (s: AppState) => T): T { + return useSyncExternalStore( + subscribe, + () => selector(state), + () => selector(state), + ); +} + +/* ------------------------------------------------------------------ toasts */ + +/** Dismissal timers, held so a hovered toast can be paused rather than lost. */ +const toastTimers = new Map<string, ReturnType<typeof setTimeout>>(); +const TOAST_MS = 5200; + +export function pushToast(tone: Toast['tone'], title: string, body?: string) { + const id = uid('toast'); + // Cap the stack: past three, the oldest collapses rather than pushing the + // rest off-screen. A toast nobody can read is not a notification. + const next = [...state.toasts, { id, tone, title, body }]; + const overflow = next.length > 3 ? next.slice(0, next.length - 3) : []; + for (const gone of overflow) { + const t = toastTimers.get(gone.id); + if (t) clearTimeout(t); + toastTimers.delete(gone.id); + } + const kept = overflow.length ? next.slice(-3) : next; + set({ toasts: kept }); + toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS)); +} + +/** + * Stops a toast's clock while the pointer is over it, so reading one does not + * race its own dismissal. Restarting gives a full window rather than the + * remainder — the intent is "I am reading this", and a resumed half-second is + * not enough to act on. + */ +export function holdToast(id: string) { + const t = toastTimers.get(id); + if (t) clearTimeout(t); + toastTimers.delete(id); +} + +export function releaseToast(id: string) { + if (toastTimers.has(id)) return; + if (!state.toasts.some((t) => t.id === id && !t.leaving)) return; + toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS)); +} + +export function dismissToast(id: string) { + const t = toastTimers.get(id); + if (t) clearTimeout(t); + toastTimers.delete(id); + set((s) => ({ toasts: s.toasts.map((x) => (x.id === id ? { ...x, leaving: true } : x)) })); + setTimeout(() => set((s) => ({ toasts: s.toasts.filter((x) => x.id !== id) })), 340); +} + +/* ------------------------------------------------------------------- prefs */ + +/** + * Preferences live on <html> as data attributes plus one custom property, so CSS + * owns presentation and React owns state — the same split the theme already + * used. Nothing here re-renders a screen: the attributes do the work. + */ +function applyPrefs() { + const root = document.documentElement; + setTranslationLanguage(state.language); + root.lang = state.language === 'zh' ? 'zh-CN' : state.language; + if(state.fontFamily)root.style.setProperty('--st-font',`${JSON.stringify(state.fontFamily)},system-ui,-apple-system,"Segoe UI",sans-serif`); + else root.style.removeProperty('--st-font'); + root.dataset.theme = state.theme === 'system' ? matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : state.theme; + document.querySelector<HTMLMetaElement>('meta[name="theme-color"]')?.setAttribute('content', root.dataset.theme === 'dark' ? '#0e1113' : '#f9fafb'); + root.dataset.contrast = state.contrast; + root.dataset.density = state.density; + root.style.setProperty('--st-content-fs', `${state.contentFontSize}px`); + // The interface size (#3970): the whole page is scaled, so every text, button, menu and dialog follows, not only the parts that were + // written with the scale token. The token stays at 1 so nothing is scaled twice. The reading size stays separate: someone who needs + // larger prose does not necessarily want larger buttons. + root.style.setProperty('--st-ui-scale', '1'); + root.style.setProperty('zoom', state.uiScale === 1 ? '' : String(state.uiScale)); + + // "system" means the OS decides, so the attribute is absent rather than set + // to a third value the stylesheet would have to special-case. + if (state.motion === 'system') delete root.dataset.motion; + else root.dataset.motion = state.motion; + + if (state.focus) root.dataset.focus = 'true'; + else delete root.dataset.focus; + + // "translucent" is the default, so the attribute only appears when it is off. + if (state.transparency === 'opaque') root.dataset.transparency = 'opaque'; + else delete root.dataset.transparency; +} + +function savePrefs() { + const snapshot: Prefs = { + sizeDefaults: SIZE_DEFAULTS_VERSION, + language: state.language, + fontFamily: state.fontFamily, + theme: state.theme, + contrast: state.contrast, + rail: state.rail, + focus: state.focus, + contentFontSize: state.contentFontSize, + density: state.density, + motion: state.motion, + transparency: state.transparency, + uiScale: state.uiScale, + electricityPrice: state.electricityPrice, + electricityCurrency: state.electricityCurrency, + doneSound: state.doneSound, + approvalNotify: state.approvalNotify, + whileBusy: state.whileBusy, + shareTelemetry: state.shareTelemetry, + }; + try { + localStorage.setItem(PREFS_KEY, JSON.stringify(snapshot)); + } catch { + /* a full quota must not break the UI */ + } + applyPrefs(); +} + +export function setTheme(theme: 'dark' | 'light' | 'system') { + set({ theme }); + savePrefs(); +} + +export function toggleRail() { + set({ rail: !state.rail }); + savePrefs(); +} +export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();rememberShellLanguage(language);} +let shellAnnounced = false; +/** The desktop shell's tray menu follows the app's language; it reads it from a small file the host keeps (no effect in a browser). */ +function rememberShellLanguage(language:Language){api.post('/api/shell/prefs',{language}).catch(()=>undefined);} +/** The shell started on another port than it wanted: the chats and settings saved on that port are not here, so say so once (#3402). */ +async function announcePortNotice(){ + try{ + const shell=await api.get<{portNotice:{wanted:number;used:number}|null}>('/api/shell'); + if(shell.portNotice)pushToast('warn',tr('Strata could not use its port'),tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.',[shell.portNotice.wanted,shell.portNotice.used])); + }catch{/* a browser or an older host has no shell */} +} +export function setFontFamily(fontFamily:string){set({fontFamily:fontFamily.trim().slice(0,128).replace(/[\x00-\x1f]/g,'')});savePrefs();} + +export function setFocus(focus: boolean) { + set({ focus }); + savePrefs(); +} + +export function toggleFocus() { + setFocus(!state.focus); +} + +/** + * Puts every appearance and reading preference back to its shipped value. + * + * Deliberately excludes `shareTelemetry`: a privacy choice is not an appearance + * setting, and re-enabling reporting as a side effect of resetting one's font + * size would be exactly the kind of thing this control exists to prevent. + * + * Deliberately does **not** touch `rail` or `focus`: those are where you happen + * to be working, not settings you chose, and collapsing the sidebar on someone + * who asked to reset their font size would be a surprise. The engine has its own + * reset, since an expert override and a font size have nothing to do with each + * other. + */ +export function resetAppearance() { + set({ + fontFamily: PREFS_DEFAULTS.fontFamily, + theme: PREFS_DEFAULTS.theme, + contrast: PREFS_DEFAULTS.contrast, + contentFontSize: PREFS_DEFAULTS.contentFontSize, + density: PREFS_DEFAULTS.density, + motion: PREFS_DEFAULTS.motion, + transparency: PREFS_DEFAULTS.transparency, + uiScale: PREFS_DEFAULTS.uiScale, + }); + savePrefs(); +} + +/** + * Records the standing privacy choice. + * + * The control was local component state that nothing persisted and nothing + * read — it snapped back on every reload, so a reader who turned reporting off + * had no way to know their choice had not been recorded. A privacy control that + * silently forgets is worse than no control at all. + */ +export function setShareTelemetry(on: boolean) { + set({ shareTelemetry: on }); + savePrefs(); +} + +export function setContentFontSize(px: number) { + const clamped = Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Math.round(px))); + set({ contentFontSize: clamped }); + savePrefs(); +} + +export function setDensity(density: 'comfortable' | 'compact') { + set({ density }); + savePrefs(); +} + +export function setMotion(motion: 'system' | 'full' | 'reduced') { + set({ motion }); + savePrefs(); +} + +export function setTransparency(transparency: 'translucent' | 'opaque') { + set({ transparency }); + savePrefs(); +} + +/** The electricity price for the Monitor's cost line: a positive price per kWh; 0 turns the line off. The currency is the detected one unless a three-letter code is given (#3628). */ +export function setElectricity(price: number, currency: string) { + const ok = Number.isFinite(price) && price > 0 && price < 1000; + set({ electricityPrice: ok ? Math.round(price * 10000) / 10000 : 0, electricityCurrency: /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : '' }); + savePrefs(); +} + +export function setWhileBusy(whileBusy: WhileBusy) { + if (!validWhileBusy(whileBusy)) return; + set({ whileBusy }); + savePrefs(); +} + +/** A message sent while an answer is being written waits here; the chat sends it when the answer is done (it is also where Interrupt leaves it). */ +export function parkMessage(sessionId: string, text: string) { + const clean = text.trim(); + if (!clean) return; + set({ parked: { ...state.parked, [sessionId]: [...(state.parked[sessionId] ?? []), clean] } }); +} +function setAsks(sessionId: string, list: AgentAsk[]) { + const next = { ...state.agentAsks }; + if (list.length) next[sessionId] = list; else delete next[sessionId]; + set({ agentAsks: next }); +} +/** The agent asked the person something (a frame of the host), or the question ended without an answer. */ +export function addAgentAsk(sessionId: string, frame: { callId?: unknown; questions?: unknown }) { + const ask = readAsk(frame); + // A /loop runs without anyone there: the question is skipped at once, so the loop never waits for an answer. + if (ask && loopScheduler.isRunning(sessionId)) { void answerAgentAsk(sessionId, ask.callId, null).catch(() => {}); return; } + if (ask) setAsks(sessionId, [...(state.agentAsks[sessionId] ?? []).filter(a => a.callId !== ask.callId), ask]); +} +export function removeAgentAsk(sessionId: string, callId?: string) { + const rest = callId === undefined ? [] : (state.agentAsks[sessionId] ?? []).filter(a => a.callId !== callId); + if ((state.agentAsks[sessionId]?.length ?? 0) !== rest.length) setAsks(sessionId, rest); +} +/** Sends the person's answer to the agent, or a skip (answers null). A refusal comes back as an error for the card to say in words. */ +export async function answerAgentAsk(sessionId: string, callId: string, answers: AgentAnswer[] | null) { + await api.post('/api/chat/answer', { sessionId, callId, ...(answers ? { answers } : { skip: true }) }); + removeAgentAsk(sessionId, callId); +} + +/** Puts a turn or a selected passage above the message box. */ +export function addQuote(sessionId: string, text: string, messageId: string, role: 'user' | 'assistant') { + const list = state.quotes[sessionId] ?? []; + const next = addToQuotes(list, { text, messageId, role }); + if (next.length !== list.length) set({ quotes: { ...state.quotes, [sessionId]: next } }); +} +export function removeQuote(sessionId: string, id: string) { + const rest = (state.quotes[sessionId] ?? []).filter(q => q.id !== id); + const next = { ...state.quotes }; + if (rest.length) next[sessionId] = rest; else delete next[sessionId]; + set({ quotes: next }); +} +export function clearQuotes(sessionId: string) { + if (!state.quotes[sessionId]) return; + const next = { ...state.quotes }; + delete next[sessionId]; + set({ quotes: next }); +} + +/** The first parked message of a chat, taken out of the list (to send it, or to give it back to the box). */ +export function takeParked(sessionId: string, index = 0): string | undefined { + const list = state.parked[sessionId] ?? []; + if (index < 0 || index >= list.length) return undefined; + const rest = list.filter((_, i) => i !== index); + const next = { ...state.parked }; + if (rest.length) next[sessionId] = rest; else delete next[sessionId]; + set({ parked: next }); + return list[index]; +} + +export function setDoneSound(doneSound: boolean) { + set({ doneSound }); + savePrefs(); +} + +export function setApprovalNotify(approvalNotify: boolean) { + set({ approvalNotify }); + savePrefs(); +} + +export const UI_SCALES = [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2] as const; + +export function setUiScale(uiScale: number) { + set({ uiScale }); + savePrefs(); +} + +export const CONTENT_FONT_RANGE = { min: CONTENT_FS_MIN, max: CONTENT_FS_MAX }; + +/* -------------------------------------------------------------- workspaces */ + +/** Opens the system folder chooser. Returns null when it is dismissed. */ +export async function pickWorkspace(): Promise<string | null> { + const res = await postWithFolderFallback<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick') as { path?: string }; + return res.path ?? null; +} + +export async function addWorkspace(path: string) { + try { + const ws = await api.post<Workspace>('/api/workspaces', { path }); + set({ workspaces: [...state.workspaces, ws] }); + pushToast('success', 'Workspace added', `Strata can now read files in ${ws.name}.`); + } catch (err) { + pushToast('error', "Couldn't add that folder", err instanceof Error ? err.message : String(err)); + } +} + +/** The name the sidebar shows for a workspace; its folder is unchanged. */ +export async function renameWorkspace(id: string, name: string) { + try { + const ws = await api.patch<Workspace>(`/api/workspaces/${id}`, { name }); + set({ workspaces: state.workspaces.map(w => (w.id === id ? { ...w, name: ws.name } : w)) }); + } catch (err) { + pushToast('error', "Couldn't rename that workspace", err instanceof Error ? err.message : String(err)); + } +} + +export async function removeWorkspace(id: string) { + const ws = state.workspaces.find((w) => w.id === id); + try { + await api.del(`/api/workspaces/${id}`); + set({ workspaces: state.workspaces.filter((w) => w.id !== id) }); + if (state.activeWorkspace === id) set({ activeWorkspace: state.workspaces[0]?.id ?? null }); + } catch (err) { + pushToast('error', "Couldn't remove that workspace", err instanceof Error ? err.message : String(err)); + } + void ws; +} + +/** + * Pins a conversation to the top of its workspace. + * + * Sessions are currently ordered by recency, which is right until you have + * thirty of them and two matter. `Session.pinned` has existed in the type since + * the beginning and was never written to. + */ +export function toggleArchive(id: string) { + const sessions = state.sessions.map((s) => (s.id === id ? { ...s, archived: !s.archived } : s)); + persistSessions(sessions); + set({ sessions }); +} + +export function togglePin(id: string) { + const sessions = state.sessions.map((s) => (s.id === id ? { ...s, pinned: !s.pinned } : s)); + persistSessions(sessions); + set({ sessions }); +} + +export function setActiveWorkspace(id: string) { + set({ activeWorkspace: id }); + void loadWorkspaceFiles(); +} + +export function openSetup(open: boolean) { + set({ setupOpen: open }); +} + +export function setPalette(open: boolean) { + set({ paletteOpen: open }); +} + +export function setShortcuts(open: boolean) { + set({ shortcutsOpen: open }); +} + +/* --------------------------------------------------------------- transport */ + +function applyEvent(e: StreamEvent) { + const data = e.data as Record<string, unknown>; + switch (e.event) { + case 'monitor': + set({ monitor: data as unknown as MonitorState }); + break; + case 'skills': + set({ skills: data as unknown as Skill[] }); + break; + case 'models': + if (Array.isArray(data.variants)) set({ library: data as unknown as ModelLibrary }); + break; + case 'runtime': + set({runtime:data as unknown as RuntimeModels}); + break; + case 'native': + applyNativeEvent(data); + break; + case 'image-models': + if (Array.isArray(data.variants)) set({ imageModels: data as unknown as ImageModelLibrary }); + break; + case 'providers': + applyProviders(data as unknown as ModelProviders); + break; + case 'goal': + if (typeof data.chatId === 'string') applyGoalFrame(data.chatId, data.goal); + break; + case 'plan': + if (typeof data.chatId === 'string') applyPlanFrame(data.chatId, data.plan); + break; + case 'queue': + if (typeof data.chatId === 'string') applyQueueFrame(data.chatId, data.queue); + break; + case 'timeskip': + applyTimeSkipEvent(data); + break; + case 'engine': + set({ engine: data as unknown as EngineConfig }); + break; + case 'serving': + set({ serving: newestServingState(state.serving, data as unknown as ServingState) }); + break; + case 'setup': + set({ setup: data as unknown as SetupState }); + break; + case 'task': { + // A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed. + const t = data as unknown as { title?: string; status?: string; attention?: string | null; error?: string | null }; + if (t.status === 'error') pushToast('error', 'Task failed', String(t.title ?? '')); + else if (t.attention) { pushToast('warn', 'Task needs your yes', String(t.title ?? '')); void approvalNeeded(state.approvalNotify, String(t.title ?? '')); } + else if (t.status === 'done') { pushToast('success', 'Task finished', String(t.title ?? '')); workFinished(state.doneSound, Infinity); } + break; + } + case 'agent': + if (typeof data.sessionId === 'string') patchSession(data.sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], data.agent) })); + break; + default: + break; + } +} + +let closeEvents: (() => void) | null = null; +export async function bootstrap() { + applyPrefs(); + try { + const [setup, hardware, library, engine, serving, monitor, skills, providers, imageModels, runtime] = await Promise.all([ + api.get<SetupState>('/api/setup'), + api.get<Hardware>('/api/hardware'), + api.get<ModelLibrary>('/api/models'), + api.get<EngineConfig>('/api/engine'), + api.get<ServingState>('/api/serving'), + api.get<MonitorState>('/api/monitor'), + api.get<Skill[]>('/api/skills'), + api.get<ModelProviders>('/api/model-providers'), + api.get<ImageModelLibrary>('/api/image-models'), + api.get<RuntimeModels>('/api/runtime'), + ]); + const workspaceState = await api.get<{ workspaces: Workspace[] }>('/api/workspaces'); + set({ + ready: true, + setup, + hardware, + library: libraryResponse(library), + imageModels, + runtime, + engine, + serving: newestServingState(state.serving, serving), + monitor, + skills, + workspacePath: workspaceState.workspaces[0]?.path ?? '', + workspaces: workspaceState.workspaces, + 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); + if (!shellAnnounced) { shellAnnounced = true; void announcePortNotice(); rememberShellLanguage(state.language); } + closeEvents?.(); + let reconnect = false; + closeEvents = onEvent(applyEvent, (status) => { + if (status === 'offline') reconnect = true; + if (status === 'live' && reconnect) { + reconnect = false; + // The restarted host may have new logs, config or readiness. Refresh + // those facts in place while retaining conversations and unsent drafts. + void bootstrap(); + return; + } + set({ connection: status }); + }); + if (!setup.complete && !setup.dismissed && !window.location.hash.includes('setup')) navigate('setup'); + } catch (err) { + set({ ready: true, connection: 'offline' }); + pushToast( + 'error', + 'Engine host unreachable', + err instanceof Error ? err.message : 'Start it with `npm run host` and reload.', + ); + } +} + +/* ------------------------------------------------------------- reads/writes */ + +export async function refreshHardware() { + set((s) => ({ busy: { ...s.busy, hardware: true } })); + try { + set({ hardware: await api.get<Hardware>('/api/hardware?reprobe=1') }); + } finally { + set((s) => ({ busy: { ...s.busy, hardware: false } })); + } +} + +function modelFits(id: string) { + const model = state.library?.variants.find(v => v.id === id); + if (state.library?.mode === 'real' && model && state.hardware && state.engine && ['too-large', 'unsupported'].includes(estimate(model, state.hardware, execution(Object.fromEntries(state.engine.expert.map(p => [p.id, p.value])), contextTokens(state.engine.beginner.contextLength))).fit)) { + pushToast('warn', 'Choose a smaller model', 'The estimated memory requirement exceeds this computer.'); + return false; + } + return true; +} + +export async function selectImageModel(selected: ImageModelChoice) { + set(s => ({ busy: { ...s.busy, 'image:select': true } })); + try { set({ imageModels: await api.patch<ImageModelLibrary>('/api/image-models', { selected }) }); } + finally { set(s => ({ busy: { ...s.busy, 'image:select': false } })); } +} +export async function installImageModel(id: Exclude<ImageModelChoice, 'off'>) { + set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/install`) }); +} +export async function cancelImageModel(id: Exclude<ImageModelChoice, 'off'>) { + set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/cancel`) }); +} +export async function applyImageModel() { + set({ imageModels: await api.post<ImageModelLibrary>('/api/image-models/apply') }); +} + +export async function installVariant(id: string) { + // Download eligibility is checked against disk space by the host. Runtime fit + // is reviewed separately when the model is loaded. + if (state.busy[`install:${id}`]) return false; + set((s) => ({ busy: { ...s.busy, [`install:${id}`]: true } })); + try { + const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/install`)); + set({ library }); + const complete = library.variants.find(v => v.id === id)?.state === 'installed'; + pushToast(complete ? 'success' : 'info', complete ? 'Files installed' : library.mode === 'simulated' ? 'Example installation started' : 'Download started', complete ? 'Load the model to start a request.' : 'Progress is shown in Models.'); + return true; + } catch (err) { + pushToast('error', 'Download failed', err instanceof Error ? err.message : undefined); + return false; + } finally { + set((s) => ({ busy: { ...s.busy, [`install:${id}`]: false } })); + } +} + +export async function cancelInstall(id: string) { + try { set({ library: libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/cancel`)) }); } catch (e) { pushToast('error', 'Cancel failed', e instanceof Error ? e.message : String(e)); } +} + +export async function loadVariant(id: string) { + if (!modelFits(id)) return false; + if (!lifecycleAvailable()) return false; + set((s) => ({ busy: { ...s.busy, [`load:${id}`]: true }, actionError: null })); + try { + const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/load`)); + set({ library }); + const model = library.variants.find(v => v.id === id); + if (library.loaded !== id || model?.state !== 'loaded') throw new Error(model?.error ?? 'The model did not finish loading.'); + pushToast('success', library.mode === 'simulated' ? 'Example model ready' : 'Model loaded', library.mode === 'simulated' ? 'Answers are simulated samples, not from a real model.' : 'Ready for a request.'); + return true; + } catch (err) { + const message = err instanceof Error ? err.message : 'The model did not load.'; + set({ + actionError: { + label: 'Could not load model', + message, + retry: () => void loadVariant(id), + }, + }); + pushToast('error', 'Could not load model', message); + return false; + } finally { + set((s) => ({ busy: { ...s.busy, [`load:${id}`]: false } })); + } +} + +export async function unloadModel() { + if (!lifecycleAvailable()) return false; + set(s => ({ busy: { ...s.busy, unload: true } })); + try { + const previousInstance=state.runtime?.defaultId; + const library = libraryResponse(await api.post<ModelLibrary>('/api/models/unload')); + const runtime=await api.get<RuntimeModels>('/api/runtime'); + set({runtime}); + set({ library }); + if (previousInstance?runtime.instances.some(i=>i.id===previousInstance):library.loaded!==null) throw new Error('The engine still reports this model instance as loaded.'); + pushToast('info', 'Model unloaded', library.mode === 'simulated' ? 'Example load state cleared.' : 'Model memory released.'); + return true; + } catch (err) { pushToast('error', 'Unload failed', err instanceof Error ? err.message : String(err)); return false; } + finally { set(s => ({ busy: { ...s.busy, unload: false } })); } +} + +export async function removeVariant(id: string) { + if (state.library?.loaded === id && !lifecycleAvailable()) return false; + const local = !!state.library?.variants.find(v => v.id === id)?.local; + try { const library = libraryResponse(await api.del<ModelLibrary>(`/api/models/${id}`)); set({ library }); + const remaining = library.variants.find(v => v.id === id); + if (remaining && remaining.state !== 'available') throw new Error('The model files were not removed.'); + pushToast('success', local ? 'Local model removed' : 'Files removed', local ? 'The original GGUF files are kept.' : library.mode === 'simulated' ? 'Example install state cleared.' : 'Model files removed from disk.'); return true; + } catch (e) { pushToast('error', 'Remove failed', e instanceof Error ? e.message : String(e)); return false; } +} + +export async function waitForInstalled(id: string) { + const deadline = Date.now() + 60 * 60 * 1000; + while (Date.now() < deadline) { + const v = state.library?.variants.find(v => v.id === id); + if (v && ['installed', 'loaded'].includes(v.state)) return; + if (!v || ['available', 'error'].includes(v.state)) throw new Error(v?.error ?? 'Download cancelled.'); + await new Promise(resolve => setTimeout(resolve, 500)); + } + throw new Error('Download timed out. Try again from Models.'); +} + +export async function saveEngine(patch: Partial<EngineConfig> | Record<string, unknown>, silent = false, requireIdle = false) { + if (requireIdle) { + const status = lifecycleStatus(); + if (!status.allowed) throw new Error(status.reason); + } + const engine = await api.patch<EngineConfig>('/api/engine', patch); + set({ engine, actionError: null }); + if (!silent) pushToast('success', 'Settings saved', 'Load settings take effect on the next load. Sampling defaults affect the next request.'); + return engine; +} + +export async function restartEngine() { + if (state.library?.mode === 'simulated') { pushToast('info', 'Restart unavailable with the example engine', 'Save settings for the next load.'); return false; } + if (!lifecycleAvailable()) return false; + set((s) => ({ busy: { ...s.busy, restart: true }, actionError: null })); + try { + const engine = await api.post<EngineConfig>('/api/engine/restart'); + set({ engine }); + if (!engine.engine.running) throw new Error(engine.engine.error ?? 'The engine is not running. Load a model before applying settings.'); + pushToast('success', 'Engine restarted', 'Warm-up takes a few seconds.'); + return true; + } catch (err) { + // Reported in place as well as in a toast: the toast is a summary, the + // surface that failed is where the retry belongs. + set({ + actionError: { + label: 'Restart failed', + message: err instanceof Error ? err.message : 'The engine did not come back up.', + retry: () => void restartEngine(), + }, + }); + pushToast('error', 'Restart failed', err instanceof Error ? err.message : undefined); + return false; + } finally { + set((s) => ({ busy: { ...s.busy, restart: false } })); + } +} + +export function dismissActionError() { + set({ actionError: null }); +} + +export async function resetEngine() { + set({ engine: await api.post<EngineConfig>('/api/engine/reset') }); + pushToast('info', 'Back to recommended', 'Every value returned to the safe default.'); +} + +/** + * Checks an engine config — the saved one by default, or a draft to preview what + * a change would do before committing to it. + */ +export async function validateEngine(draft?: unknown) { + return api.post<{ + ok: boolean; + issues: { level: 'warn' | 'error'; message: string }[]; + predicted?: EngineConfig['predicted']; + }>('/api/engine/validate', draft ?? {}); +} + +export async function exportEngine() { + return api.get<Record<string, unknown>>('/api/engine/export'); +} + +export async function setCloudflare(body: {action: 'start' | 'stop' | 'prepare'; mode?: 'quick' | 'domain'; hostname?: string; token?: string}) { + const result = await api.post<ServingState>('/api/serving/tunnel', body); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function setLocalSharing(enabled: boolean) { + const result = await api.post<ServingState>('/api/serving/share', { enabled }); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function setServingAccess(patch: { otherDevices?: boolean; apiKey?: string | null }) { + const result = await api.patch<ServingState>('/api/serving', patch); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function pauseServing(paused: boolean) { + const result = await api.patch<ServingState>('/api/serving', { pauseServing: paused }); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function cancelRequest(id: string) { + const result = await api.post<ServingState>(`/api/serving/requests/${id}/cancel`); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function completeSetupStep(step: number, choices?: SetupState['choices'], dismissed = false) { + set({ setup: await api.post<SetupState>('/api/setup/step', { step, choices, dismissed, flowVersion: 2 }) }); +} + +export async function completeSetup() { + const setup = await api.post<SetupState>('/api/setup/complete'); + set({ setup }); +} + +export async function setSkills(skills: Skill[]) { + set({ skills }); +} + +/** + * Re-reads the skill list from the host. + * + * For the case where a skill was added to the workspace folder while the app was + * open — otherwise the only way to see it is to restart. + */ +export async function loadSkills() { + set({ skills: await api.get<Skill[]>('/api/skills') }); +} + +/** Re-reads the workspace tree from disk, for the same reason. */ +export async function loadWorkspaceFiles() { + const data = await api.get<{ path: string; entries: WorkspaceFile[] }>(`/api/workspace${state.activeWorkspace ? '?root=' + encodeURIComponent(state.activeWorkspace) : ''}`); + set({ files: data.entries, workspacePath: data.path }); +} + +export async function toggleSkill(id: string, enabled: boolean) { + set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { enabled }) }); +} + +export async function editSkill(id: string, patch: Pick<Skill, 'name' | 'description' | 'body' | 'triggers' | 'enabled' | 'onlyIn'>) { + set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, patch) }); +} + +/** + * Narrows a skill to the workspace you are in, or widens it again. + * + * Passing null clears the narrowing. The host resolves `onlyIn` against the + * workspace the request came from, so the answer depends on where the reader + * is rather than on a single global switch. + */ +export async function scopeSkill(id: string, workspaceId: string | null) { + set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { onlyIn: workspaceId }) }); +} + +/* ---------------------------------------------------------------- sessions */ + +const sessionWriter = createSessionWriter({ + write: (json) => { + try { + localStorage.setItem(SESSION_KEY, json); + } catch { + /* quota — sessions are a cache, not the source of truth */ + } + }, +}); + +/** + * Save the chat list. A one-off change (new, rename, delete, pin) is written now; `soon` is for the streaming + * path, where a write per token grew the renderer to gigabytes (#3604, #3603): those are coalesced to one a second. + */ +function persistSessions(sessions: Session[], soon = false) { + sessionWriter.schedule(sessions); + if (!soon) sessionWriter.flush(); +} + +/** Write the newest chat list now: a turn ended, or the page is going away. */ +export function flushSessions() { + sessionWriter.flush(); +} + +if (typeof window !== 'undefined' && typeof document !== 'undefined' && window.addEventListener) { + window.addEventListener('pagehide', flushSessions); + document.addEventListener?.('visibilitychange', () => { if (document.visibilityState === 'hidden') flushSessions(); }); +} + +export function newSession(): Session { + const session: Session = { + id: uid('s'), + title: 'New conversation', + defaultTitle: true, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + messages: [], + workspace: state.workspaces.find(w => w.id === state.activeWorkspace)?.path ?? state.workspacePath, + tokensIn: 0, + tokensOut: 0, + ...(state.activeSession === null && state.remoteModel ? { preferences: { remoteModel: state.remoteModel } } : {}), + }; + const sessions = [session, ...state.sessions]; + persistSessions(sessions); + set({ sessions, activeSession: session.id }); + return session; +} + +export function setChatPreferences(id: string | undefined, preferences: NonNullable<Session['preferences']>) { + const sessionId = id ?? newSession().id; + patchSession(sessionId, s => ({ ...s, preferences: { ...s.preferences, ...preferences } })); + // A mode change applies to the very next tool call of a turn that is already running (a goal and its helpers included). + if (preferences.mode && liveTurns.get(sessionId)?.agent) void api.post('/api/chat/mode', { sessionId, mode: preferences.mode }).catch(() => undefined); +} +export function setPreviewTabClosed(sessionId:string|undefined, artifactId:string, closed:boolean, selected:string|null) { + if(!sessionId)return; + patchSession(sessionId,s=>({...s,closedPreviews:closed?[...new Set([...(s.closedPreviews??[]),artifactId])]:(s.closedPreviews??[]).filter(id=>id!==artifactId),previewOpen:selected??undefined})); +} +export function createChatShowcase() { + const session=newSession();const at=new Date().toISOString(); + patchSession(session.id,s=>({...s,title:'Chat showcase · code, tools & media',showcase:true,statsAvailable:true,tokensIn:28000000,tokensOut:4000000,messages:showcaseMessages(at),agents:SHOWCASE_AGENTS,showcaseAgentStates:true})); + go('chat',session.id); +} + +/** A visible example for checking the subagent interface in the design build. */ +export function createSubagentExample() { + const session = newSession(); const now = Date.now(); + patchSession(session.id, s => ({ ...s, title: 'Subagent preview', showcase: true, showcaseAgentStates: true, + agents: [ + {id:'example-layout',name:'Layout review',description:'Checking spacing and component alignment.',status:'working',durationMs:39000,tokens:12600,updatedAt:now}, + {id:'example-interactions',name:'Interaction review',description:'Checking menus, controls and keyboard navigation.',status:'working',durationMs:21000,tokens:8400,updatedAt:now}, + {id:'example-copy',name:'Copy review',description:'Labels and descriptions reviewed.',status:'completed',durationMs:18000,tokens:4200,updatedAt:now}, + ], messages: [{id:uid('m'),role:'assistant',at:new Date(now).toISOString(),example:true,content:'Open the subagent count above to inspect this example run. Each row shows status, token usage and elapsed time.'}] + })); + go('chat', session.id); +} + +export function createPreviewExamples() { + const session = newSession(); + const at = new Date().toISOString(); + patchSession(session.id, s => ({ ...s, title: 'Design review · six previews', previewOpen:'sample-website', messages: [ + { id:uid('m'), role:'user', at, content:'Open six different output types so I can iterate on the preview design.' }, + { id:uid('m'), role:'assistant', at, demo:true, content:'Here is a design-review workspace for Fieldnotes: a website, PDF, Markdown brief, cover image, TypeScript file and release table.\n\nAll six are loaded in the panel on the right. Switch tabs to explore each view while keeping this conversation in place.', artifacts:PREVIEW_EXAMPLES }, + ] })); + go('chat', session.id); +} + +/** "Continue in a new chat" on a task: a new chat whose first message is the task's findings, what it did and its files (src/lib/task-handover.ts). */ +export function continueTaskInNewChat(task: Task) { + const session = newSession(); + go('chat', session.id); + void sendMessage(taskHandoverMessage(task), { title: taskHandoverTitle(task), markdown: true }); +} + +export function selectSession(id: string) { + // 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); +} + +/** Records that a conversation has been looked at. */ +export function markRead(id: string) { + const at = new Date().toISOString(); + const sessions = state.sessions.map((s) => (s.id === id ? { ...s, lastReadAt: at } : s)); + persistSessions(sessions); + set({ sessions }); +} + +/** + * Whether a conversation has moved on since it was last looked at. + * + * The active conversation is never unread: you are looking at it, or its reply + * is arriving in front of you. + */ +export function isUnread(s: Session, activeSession: string | null): boolean { + if (s.id === activeSession) return false; + if (!s.lastReadAt) return s.messages.length > 0; + return s.updatedAt > s.lastReadAt; +} + +export function deleteSession(id: string) { + const sessions = state.sessions.filter((s) => s.id !== id); + persistSessions(sessions); + set({ sessions, activeSession: state.activeSession === id ? (sessions[0]?.id ?? null) : state.activeSession }); +} + +export function renameSession(id: string, title: string) { + const sessions = state.sessions.map((s) => (s.id === id ? { ...s, title, defaultTitle: false } : s)); + persistSessions(sessions); + set({ sessions }); +} + +function patchSession(id: string, fn: (s: Session) => Session) { + const sessions = state.sessions.map((s) => (s.id === id ? fn(s) : s)); + persistSessions(sessions, true); + set({ sessions }); +} + +// The demo clock belongs to the session, so hiding the sidebar or navigating +// away never pauses it. Only start and completion are written to storage. +const timeSkipTimers = new Map<string, ReturnType<typeof setTimeout>>(); +function scheduleTimeSkip(sessionId: string, run: TimeSkipRun) { + const timerId = `${sessionId}:${run.id}`; + clearTimeout(timeSkipTimers.get(timerId)); + if (run.completedAt || run.job) return; + timeSkipTimers.set(timerId, setTimeout(() => { + timeSkipTimers.delete(timerId); + const session = state.sessions.find(s => s.id === sessionId); + const current = session?.timeSkips?.find(r => r.id === run.id); + if (!current || current.startedAt !== run.startedAt || !session?.messages.some(m => m.timeSkipId === run.id && m.role === 'assistant')) return; + patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(), + timeSkips: s.timeSkips?.map(r => r.id === run.id ? { ...r, completedAt: run.startedAt + TIME_SKIP_DURATION } : r), + messages: s.messages.map(m => m.timeSkipId === run.id && m.role === 'assistant' ? { ...m, content: 'The updated result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.' } : m), + })); + }, Math.max(0, run.startedAt + TIME_SKIP_DURATION - Date.now()))); +} + +export function replayTimeSkip(sessionId: string, runId: string) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + if (!run) return; + const next = { ...run, startedAt: Date.now(), completedAt: undefined, retainedVersion: undefined }; + patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r), + messages: s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.' } : m), + })); + scheduleTimeSkip(sessionId, next); +} + +export function setTimeSkipResult(sessionId: string, runId: string, version: TimeSkipVersion) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + if (!run) return; + if (run.job) { void keepTimeSkip(sessionId, runId, version); return; } + const next = withTimeSkipResult(run, version, Date.now()); + if (next === run) return; + patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r) })); +} + +/* ------------------------------------------------------- Time-skip, for real + The host copies the chat's folder, lets the assistant change the copy, checks it and keeps the original untouched until the + person chooses. The sidebar follows the job's own record; nothing here invents progress. */ +const TS_TERMINAL = ['completed', 'cancelled', 'failed', 'interrupted']; +const TS_WORKING = () => tr('Working on a copy of your files. Follow the progress in the sidebar.'); +const TS_READY = () => tr('The result is ready. Switch between Original and Updated, or compare them side by side.'); + +function patchRun(sessionId: string, runId: string, fn: (run: TimeSkipRun) => TimeSkipRun, content?: string) { + patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(), + timeSkips: s.timeSkips?.map(r => r.id === runId ? fn(r) : r), + messages: content === undefined ? s.messages : s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content } : m), + })); +} + +/** The job's error in a sentence a person can use. */ +export function plainTimeSkipError(raw: string | null | undefined): string { + const text = String(raw ?? '').trim(); + if (!text) return tr('Something went wrong.'); + const afterExit = /\(exit \d+\):\s*([\s\S]*)$/.exec(text); + const body = (afterExit?.[1] ?? text).replace(/^\w*Error:\s*/, '').trim(); + if (/destination changed|refusing to overwrite/i.test(body)) return tr('Your files changed after this trial started, so nothing was overwritten. Run Time-skip again.'); + if (/too big/i.test(body)) return tr('This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.'); + if (/folder of your own/i.test(body)) return tr('Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.'); + if (/Load a model|model first/i.test(body)) return tr('Load a model first, then try Time-skip again.'); + if (/needs the Strata app|could not be reached/i.test(body)) return tr('The assistant could not be reached. Try again.'); + return body.length > 300 ? body.slice(0, 299) + '…' : body; +} + +/** The host says a Time-skip run moved on (phase, and what it is doing now): the working view shows the newest words. */ +function applyTimeSkipEvent(data: Record<string, unknown>) { + const id = typeof data.id === 'string' ? data.id : ''; + if (!id) return; + for (const session of state.sessions) { + const run = session.timeSkips?.find(r => r.job?.id === id); + if (!run || run.completedAt) continue; + patchRun(session.id, run.id, r => ({ ...r, job: { ...r.job!, ...(typeof data.phase === 'string' ? { phase: data.phase as TimeSkipJob['phase'] } : {}), activity: data.activity as TimeSkipJob['activity'], ...forkFields(data) } })); + } +} + +function timeSkipEnding(job: TimeSkipJob, files: TimeSkipFile[]): string { + if (job.phase === 'failed') return tr('Time-skip stopped. {0} Your files were not changed.', [plainTimeSkipError(job.error)]); + if (job.phase === 'cancelled' || job.phase === 'interrupted') return tr('Time-skip was stopped before it finished. Your files were not changed.'); + if (!files.length) return tr('The assistant did not change anything, so there is nothing to compare. Your files were not changed.'); + return isForkJob(job) ? tr('Both versions are ready. Compare A and B, then keep one.') : TS_READY(); +} + +async function startTimeSkipReal(prompt: string) { + const sessionId = state.activeSession ?? newSession().id; + const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now(), + job: { id: '', phase: 'queued', attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: false, error: null } }; + const at = new Date().toISOString(); + patchSession(sessionId, s => ({ ...s, + defaultTitle: false, + title: s.messages.length ? s.title : prompt.length > 48 ? prompt.slice(0, 47).trimEnd() + '…' : prompt, updatedAt: at, + // The comparison sidebar opens only when there is an update to compare (when the job ends with changed files), never while it works. + timeSkips: [...(s.timeSkips ?? []), run], + messages: [...s.messages, + { id: uid('m'), role: 'user', at, content: '/time-skip ' + prompt, timeSkipId: run.id }, + { id: uid('m'), role: 'assistant', at, timeSkipId: run.id, content: TS_WORKING() }, + ], + })); + go('chat', sessionId); + markTurn(sessionId, { abort: new AbortController(), agent: false }); + try { + const started = await api.post<{ run: TimeSkipJob }>('/api/timeskip/start', { prompt, sessionId, workspaceId: state.activeWorkspace, attempts: 1, ...(state.remoteModel ? { remoteModel: state.remoteModel } : {}) }); + patchRun(sessionId, run.id, r => ({ ...r, job: started.run })); + void followTimeSkip(sessionId, run.id); + } catch (e) { + const message = plainTimeSkipError(e instanceof Error ? e.message : String(e)); + patchRun(sessionId, run.id, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'failed', error: message } }), tr('Time-skip could not start. {0}', [message])); + markTurn(sessionId, null); + } +} + +const followingTimeSkips = new Set<string>(); +/** Read the job's record until it ends. Safe to call again for a run already being followed. */ +export async function followTimeSkip(sessionId: string, runId: string) { + const key = sessionId + ':' + runId; + if (followingTimeSkips.has(key)) return; + followingTimeSkips.add(key); + let misses = 0; + try { + for (;;) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + if (!run?.job?.id || run.completedAt) return; + let job: TimeSkipJob | null = null; + try { job = (await api.get<{ run: TimeSkipJob }>('/api/timeskip/status?id=' + encodeURIComponent(run.job.id))).run; misses = 0; } + catch { misses += 1; } + if (job && TS_TERMINAL.includes(job.phase)) { + let files: TimeSkipFile[] = [], extra: Partial<TimeSkipJob> = {}; + // The changed files are what the person came for: ask again a few times before settling for "nothing to compare". + for (let tryNo = 0; tryNo < 4; tryNo++) { + try { + const found = await api.get<{ files: TimeSkipFile[]; applyAttempt: number | null; more: number }>('/api/timeskip/files?id=' + encodeURIComponent(job.id)); + files = found.files; extra = { files: found.files, applyAttempt: found.applyAttempt, moreFiles: found.more }; + break; + } catch { await new Promise(r => setTimeout(r, 700 * (tryNo + 1))); } + } + const finished = { ...job, ...forkFields(job as unknown as Record<string, unknown>) }; + patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, ...finished, ...extra } }), timeSkipEnding(finished, files)); + // A run that changed files opens the comparison; one that changed nothing, failed or was stopped has no sidebar tab. + if (files.length > 0 && !['failed', 'cancelled', 'interrupted'].includes(finished.phase)) patchSession(sessionId, s => ({ ...s, previewOpen: timeSkipTabId(runId) })); + markTurn(sessionId, null); + return; + } + if (job) { const live = { ...job, ...forkFields(job as unknown as Record<string, unknown>) }; patchRun(sessionId, runId, r => ({ ...r, job: { ...r.job!, ...live } })); } + if (misses >= 6) { + patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'interrupted' } }), tr('Time-skip lost contact with the app and stopped. Your files were not changed.')); + markTurn(sessionId, null); + return; + } + await new Promise(r => setTimeout(r, 2000)); + } + } finally { followingTimeSkips.delete(key); } +} + +/** Ask the host to stop a running trial. The saved version stays. */ +export async function stopTimeSkip(sessionId: string, runId: string) { + const id = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId)?.job?.id; + if (id) await api.post('/api/timeskip/stop', { id }).catch(() => undefined); +} + +/** Put the update into the person's files, or put the original back. Both are checked and undoable. */ +export async function keepTimeSkip(sessionId: string, runId: string, version: TimeSkipVersion) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + const job = run?.job; + if (!run || !job?.id || !job.phase || !TS_TERMINAL.includes(job.phase)) return; + if ((run.retainedVersion ?? 'original') === version && !(isForkJob(job) && run.retainedVersion === undefined)) { patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); return; } + try { + if (isForkJob(job)) await api.post('/api/timeskip/apply', { id: job.id, which: version === 'original' ? 'a' : 'b' }); + else if (version === 'updated') await api.post('/api/timeskip/apply', { id: job.id, attempt: job.applyAttempt ?? null }); + else await api.post('/api/timeskip/apply', { id: job.id, restore: true }); + patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); + pushToast('success', version === 'updated' ? tr('The update is now in your files') : tr('Your original files are back')); + } catch (e) { + pushToast('error', tr('Your files were not changed'), plainTimeSkipError(e instanceof Error ? e.message : String(e))); + } +} + +function startTimeSkipDemo(prompt: string) { + if (!prompt) { pushToast('info', 'Add a prompt after /time-skip', 'For example: /time-skip Make a launch plan for my app'); return; } + const sessionId = state.activeSession ?? newSession().id; + const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now() }; + const at = new Date().toISOString(); + patchSession(sessionId, s => ({ ...s, + defaultTitle: false, + title: s.messages.length ? s.title : prompt.length>48?prompt.slice(0,47).trimEnd()+'…':prompt, updatedAt: at, + timeSkips: [...(s.timeSkips ?? []), run], previewOpen: timeSkipTabId(run.id), + messages: [...s.messages, + { id: uid('m'), role: 'user', at, content: `/time-skip ${prompt}`, timeSkipId: run.id }, + { id: uid('m'), role: 'assistant', at, example: true, timeSkipId: run.id, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks; it doesn’t run your model.' }, + ], + })); + scheduleTimeSkip(sessionId, run); + go('chat', sessionId); +} + +function markTurn(sessionId: string, turn: { abort: AbortController; agent: boolean } | null) { + if (turn) liveTurns.set(sessionId, turn); else liveTurns.delete(sessionId); + set({ streaming: !!state.activeSession && liveTurns.has(state.activeSession), liveChats: liveTurns.size }); + document.documentElement.dataset.streaming = liveTurns.size ? 'true' : 'false'; +} + +/** + * Stop the open chat's turn. The host is asked first: for an agent turn it cancels exactly this chat's + * Harness session and answers only once the turn has ended, and the stream then closes by itself with + * what was produced. For any other turn the host reports nothing to stop and the request is aborted. + */ +export function stopStreaming() { + const id = state.activeSession; + const turn = id ? liveTurns.get(id) : undefined; + if (!id || !turn) return; + const abort = () => { turn.abort.abort(); }; + void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then( + result => { + if (!result.stopped) abort(); + // An agent turn that was told to stop but is slow to end must not leave the chat stuck. + else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); + }, + abort, + ); +} + +/** + * Re-runs the last exchange: drops the assistant reply and asks again. + * + * Kept in the store rather than the screen because it has to touch the message + * list, and every attempt to do this from a component ends up duplicating the + * stream handling that already lives here. + */ +export async function retryLast(messageId?: string) { + const source = state.sessions.find(s => s.id === state.activeSession); + if (!source || state.streaming) return; + const end = messageId ? source.messages.findIndex(m => m.id === messageId) : source.messages.length - 1; + const user = source.messages.slice(0, end + 1).reverse().find(m => m.role === 'user'); + if (!user) return; + const prompt = rewindTo(user.id); + if (prompt !== null) { + // Retry sends immediately; only Edit should leave the prompt in the composer. + sessionStorage.setItem(`strata.chat-draft.${state.activeSession}`, ''); + await sendMessage(prompt); + } +} + +/** The open chat's last question and the answer that failed under it (null when the chat does not end that way). */ +function failedExchange(): { prompt: string; sessionId: string } | null { + const sessionId = state.activeSession; + const chat = state.sessions.find(s => s.id === sessionId); + if (!sessionId || !chat || state.streaming) return null; + const reply = chat.messages[chat.messages.length - 1], ask = chat.messages[chat.messages.length - 2]; + return reply?.role === 'assistant' && reply.error && ask?.role === 'user' ? { prompt: ask.content, sessionId } : null; +} +/** Takes the failed question and its error out of the transcript, so asking again does not show the question twice. */ +function dropFailedExchange(sessionId: string) { + patchSession(sessionId, s => ({ ...s, messages: s.messages.slice(0, -2) })); +} + +/** + * The error card of a conversation that no longer fits the model's window: summarise the older messages (the same as typing /compact), then + * ask the assistant to answer. The refused question is already in the assistant's conversation (it is the newest message, and a summary keeps + * the newest message as it is), so it is not sent a second time: a large one twice would not fit either. + */ +export async function summarizeAndContinue() { + if (!failedExchange()) return; + await sendMessage('/compact'); + await sendMessage('Please answer my last message now.'); +} + +/** + * The error card of a message that is too large to send: the host makes it small enough (its text as a file in the chat's folder that the + * assistant reads in parts, or a shortened preview), and that is sent in its place. + */ +export async function sendOversized(mode: 'file' | 'preview') { + const failed = failedExchange(); + if (!failed) return; + let reply: { message?: string }; + try { + reply = await api.post<{ message?: string }>('/api/chat/oversize', { sessionId: failed.sessionId, mode, text: failed.prompt, nativeModelId: nativeState()?.instances.length ? nativeState()?.defaultId : undefined }); + } catch { + pushToast('error', 'The message could not be prepared. Try a shorter message.'); + return; + } + if (!reply.message) return; + dropFailedExchange(failed.sessionId); + await sendMessage(reply.message); +} + +/** A new, empty chat, opened. */ +export function startNewChat() { + const session = newSession(); + go('chat', session.id); +} + +/** + * Forks a conversation at a message, leaving the original untouched. + * + * The alternative people reach for is duplicating the whole session and + * deleting messages by hand, which loses the original. Branching keeps both: + * the new session carries the history up to the chosen turn and diverges there. + */ +export function branchFrom(messageId: string): string | null { + const sessionId = state.activeSession; + if (!sessionId) return null; + const source = state.sessions.find((s) => s.id === sessionId); + if (!source) return null; + const at = source.messages.findIndex((m) => m.id === messageId); + if (at < 0) return null; + + const now = new Date().toISOString(); + const branch: Session = { + ...source, + id: uid('s'), + title: `${source.title} (branch)`, + defaultTitle: false, + createdAt: now, + updatedAt: now, + messages: source.messages.slice(0, at + 1).map((m) => ({ ...m, id: uid('m') })), + tokensIn: 0, + tokensOut: source.messages.slice(0, at + 1).reduce((n, m) => n + (m.tokens ?? 0), 0), + statsAvailable: false, + }; + const sessions = [branch, ...state.sessions]; + persistSessions(sessions); + set({ sessions, activeSession: branch.id }); + for (const run of branch.timeSkips ?? []) scheduleTimeSkip(branch.id, run); + // The URL wins over `activeSession` when it names a session, so a programmatic + // switch has to move the route too — otherwise the sidebar shows the branch + // while the transcript still shows the original, which reads as a broken + // button rather than a created branch. + navigate('chat', branch.id); + return branch.id; +} + +/** + * Asks the model to keep going from where it stopped. + * + * Sent as an ordinary user turn rather than a special mode, because that is + * what it is: a continuation is a request, and the transcript should show it. + */ +export async function continueLast() { + const sessionId = state.activeSession; + if (!sessionId || state.streaming) return; + const session = state.sessions.find((s) => s.id === sessionId); + const last = session?.messages[session.messages.length - 1]; + if (!last || last.role !== 'assistant' || !last.content.trim()) return; + await sendMessage('Continue from where you left off. Do not repeat what you have already written.'); +} + +/** + * Rewinds the transcript to just before a turn so it can be re-asked with a + * different prompt. Returns the text so the composer can be filled with it. + */ +export function rewindTo(messageId: string): string | null { + if (state.streaming) return null; + const source = state.sessions.find(s => s.id === state.activeSession); + const at = source?.messages.findIndex(m => m.id === messageId) ?? -1; + if (!source || at < 0) return null; + const prompt = source.messages[at].content; + const branchId = branchFrom(messageId); + if (!branchId) return null; + patchSession(branchId, s => ({ ...s, messages: s.messages.slice(0, -1), tokensIn: 0, tokensOut: s.messages.slice(0, -1).reduce((n, m) => n + (m.tokens ?? 0), 0) })); + sessionStorage.setItem(`strata.chat-draft.${branchId}`, prompt); + return prompt; +} + +export function exportConversation() { + const session = state.sessions.find(s => s.id === state.activeSession); + if (!session) return; + const text = '# ' + session.title + '\n\n' + session.messages.map(m => '## ' + m.role + '\n\n' + (m.role === 'assistant' ? tidyAnswer(m.content) : m.content)).join('\n\n'); + const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown' })); + const a = document.createElement('a'); a.href = url; a.download = session.title.replace(/[^a-z0-9 -]/gi, '').slice(0, 60) + '.md'; + document.body.append(a); a.click(); a.remove(); + // Keep the Blob alive until browsers have started consuming the download. + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +/* ---------------------------------------------------------------- /loop + The same message, again and again, while the chat is open. The scheduler (count, time, "the answer says it is done") is + lib/loop-runner.ts; this is the part that talks to the chat. See lib/loop.ts. */ + +/** A line from the app itself (not the model) in the transcript. It is never sent to the model. */ +function addNote(sessionId: string, content: string) { + const at = new Date().toISOString(); + patchSession(sessionId, s => ({ ...s, updatedAt: at, messages: [...s.messages, { id: uid('m'), role: 'assistant', at, content, local: true }] })); +} + +const lastAnswer = (sessionId: string) => [...(state.sessions.find(s => s.id === sessionId)?.messages ?? [])].reverse().find(m => m.role === 'assistant' && !m.local); + +const loopScheduler = new LoopScheduler({ + async send(sessionId, { text, shown }) { + const before = lastAnswer(sessionId)?.id; + await sendMessage(text, { fromLoop: true, shown, title: shown.length > 48 ? shown.slice(0, 47).trimEnd() + '…' : shown }); + const answer = lastAnswer(sessionId); + if (!answer || answer.id === before || answer.streaming) return { answered: false, text: '', failed: false }; + return { answered: true, text: answer.content ?? '', failed: !!answer.error }; + }, + note: addNote, + exists: sessionId => state.sessions.some(s => s.id === sessionId), + ready: sessionId => state.activeSession === sessionId && !state.streaming, + now: () => Date.now(), + setTimer: (fn, ms) => setTimeout(fn, ms), + clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>), + track: (sessionId, loop) => patchSession(sessionId, s => ({ ...s, loop })), +}); + +export function loopIsRunning(sessionId: string | null): boolean { return loopScheduler.isRunning(sessionId); } + +/* ------------------------------------------------------------- task board */ + +/** The chats with a turn going, and the chats with a loop going: what the board needs besides the sessions themselves. */ +export function liveChatIds(): string[] { return [...liveTurns.keys()]; } +export function loopChatIds(): string[] { return loopScheduler.ids(); } + +/** Stop any chat's turn, not only the open one (the board's Stop). Same two-step as stopStreaming. */ +export function stopChat(id: string) { + const turn = liveTurns.get(id); + if (!turn) return; + const abort = () => { turn.abort.abort(); }; + void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then( + result => { if (!result.stopped) abort(); else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); }, + abort, + ); +} + +/** Stop a chat's loop from the board. The chat gets the same line /loop stop writes. */ +export function stopLoop(id: string) { + if (loopScheduler.stop(id)) addNote(id, tr('The loop is stopped.')); +} + +/** Dismiss a chat's (or its loop's) card: it leaves the board until something newer goes wrong. The chat itself is untouched. */ +export function dismissChat(id: string) { + const sessions = state.sessions.map(s => (s.id === id ? { ...s, ackedAt: new Date().toISOString() } : s)); + persistSessions(sessions); + set({ sessions }); +} + +/** Answer a waiting tool card in any chat (the board's Approve and Deny). Only a live card has an approval behind it. */ +export function answerChatTool(sessionId: string, messageId: string, toolId: string, approved: boolean) { + const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId); + if (tool?.live && tool.state === 'proposed') answerAgentTool(sessionId, messageId, tool, approved); +} + +/** "Continue in a new chat" on a chat or a loop that went wrong: a new chat that starts from what happened (src/lib/task-handover.ts). */ +export function continueChatInNewChat(sessionId: string) { + const old = state.sessions.find(s => s.id === sessionId); + if (!old) return; + const session = newSession(); + go('chat', session.id); + void sendMessage(chatHandoverMessage(old), { title: chatHandoverTitle(old), markdown: true }); +} + +async function runLoopCommand(command: LoopCommand) { + const sessionId = state.activeSession ?? newSession().id; + const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); }; + if (command.kind === 'help') { say(tr(command.problem) + '\n\n' + tr(LOOP_USAGE)); return; } + if (command.kind === 'status') { say(loopScheduler.describe(sessionId) ?? tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE)); return; } + if (command.kind === 'stop') { say(loopScheduler.stop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; } + go('chat', sessionId); + await loopScheduler.start(sessionId, command); +} + +/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */ +export async function resumeGoal() { await sendMessage('', { goalAction: 'resume' }); } + +/** Approve a proposed plan and carry it out: the host answers with the message that does the work, which goes out as an ordinary turn. */ +export async function approvePlan(sessionId: string, planId: string) { + const { prompt } = await planApprove(sessionId, planId); + // A chat in Plan mode only reads; carrying the plan out needs a mode that may act. + if (state.sessions.find(s => s.id === sessionId)?.preferences?.mode === 'plan') setChatPreferences(sessionId, { mode: 'manual' }); + if (prompt) await sendMessage(prompt, { shown: tr('Approved the plan.') }); +} + +/** "Start as goal" (and Resume on a paused plan): the host streams the run like any chat turn. */ +export async function startPlanGoal(planId: string) { await sendMessage('', { planId }); } + +export async function sendMessage(text: string, options: { fromLoop?: boolean; goalAction?: 'resume'; planId?: string; shown?: string; title?: string; markdown?: boolean } = {}) { + if (state.streaming) { + // Typed while the assistant works: behind a running goal it waits in the queue; otherwise there is nothing to do but wait. + const waiting = state.activeSession, line = text.trim(); + if (waiting && line && !options.planId && !options.goalAction) { + try { if (!(await queueMessage(waiting, line))) pushToast('info', 'The assistant is still answering', 'Send your message when it has finished.'); } + catch (e) { pushToast('error', 'The message was not queued', plainFailureText(e instanceof Error ? e.message : String(e)).message); } + } + return; + } + const resume = options.goalAction === 'resume'; + const planStart = options.planId; + const loopCommand = options.fromLoop || resume || planStart ? null : parseLoop(text.trim()); + if (loopCommand) { await runLoopCommand(loopCommand); return; } + const demoPrompt = resume || planStart ? null : timeSkipPrompt(text.trim()); + if (demoPrompt !== null) { + if (demoPrompt && (state.remoteModel || nativeState()?.instances.some(i => i.status === 'ready'))) void startTimeSkipReal(demoPrompt); else if (state.connection === 'live' && demoPrompt) pushToast('info', 'Load a model first', 'Time-skip works on a loaded model. Choose one on the Models tab, then try again.'); + else if (state.connection === 'connecting' && demoPrompt) pushToast('info', 'Still starting up', 'Time-skip needs the app to finish starting. Try again in a moment.'); + else startTimeSkipDemo(demoPrompt); + return; + } + // Whatever sent this (the box, a loop, a plan): with no model to answer, say so in plain words and start nothing. + if (state.connection === 'live') { + // The first read of the engine's state has not come back yet: do not say "no model" about something not known yet, and do not send. + if (!nativeState() && !state.remoteModel && !state.library?.loaded) { pushToast('info', 'Still starting up', 'Strata is still checking your models. Try again in a moment.'); return; } + const why = noModelNotice(nativeState(), { remote: !!state.remoteModel, libraryLoaded: !!state.library?.loaded }); + if (why) { pushToast('info', why.title, why.message); return; } + } + const pictureCheck=pictureStatus(nativeState(),state.remoteModel,state.providers); + if(pendingChatPhotos(state.activeSession).length&&!pictureCheck.ok){pushToast('error','This model cannot read pictures',tr(pictureCheck.message));return;} + const pictures=takeChatPhotos(state.activeSession); + const body=text.trim()||(pictures.length?'Describe this picture.':''); + if(!body&&!resume&&!planStart)return; + + let sessionId = state.activeSession; + if (!sessionId) sessionId = newSession().id; + + const userMsg: ChatMessage = { id: uid('m'), role: 'user', content: options.shown ?? body, at: new Date().toISOString(),...(pictures.length?{photos:pictures}:{}),...(options.markdown?{markdown:true}:{}) }; + let assistantId = uid('m'); + const assistantMsg: ChatMessage = { + id: assistantId, + role: 'assistant', + content: '', + at: new Date().toISOString(), + streaming: true, + }; + + /* Everything said before this turn, which the model needs in order to have a + conversation at all. + + It was never sent. The real-engine path builds its prompt as + `[...history, message]`, and `history` was always empty, so each message + arrived as the first thing the model had ever heard — no memory of the + turns above it in the transcript. The demo path hides this, because its + replies are canned. + + The context meter was reading the same empty array, which is why it sat at + ~350 tokens however long the conversation grew. */ + const prior = (state.sessions.find((s) => s.id === sessionId)?.messages ?? []) + .filter(m => !m.timeSkipId && !m.local) + .filter((m) => m.role === 'user' || m.role === 'assistant') + .filter((m) => m.content.trim()) + .map((m) => ({ role: m.role, content: m.content,photos:m.photos })) + // Bounded so a long conversation cannot send an unbounded body. + .slice(-40); + + patchSession(sessionId, (s) => ({ + ...s, + defaultTitle: false, + title: s.messages.length === 0 && !resume && !planStart ? (options.title ?? (body.length>48?body.slice(0,47).trimEnd()+'…':body)) : s.title, + updatedAt: new Date().toISOString(), + messages: [...s.messages, ...(resume || planStart ? [] : [userMsg]), assistantMsg], + })); + + const turnAbort = new AbortController(); + markTurn(sessionId, { abort: turnAbort, agent: false }); + // Read by the router to skip view transitions mid-stream, and by CSS to keep + // the transcript still while tokens arrive. + + const patchAssistant = (fn: (m: ChatMessage) => ChatMessage) => + patchSession(sessionId, (s) => ({ + ...s, + updatedAt: new Date().toISOString(), + messages: s.messages.map((m) => (m.id === assistantId ? fn(m) : m)), + })); + + const started = performance.now(); + + const imageSlots=photoHistorySlots(prior,pictures.length); + /* Text and reasoning arrive token by token (90 a second or more). Drawing the whole answer again for each one made the page do more work for every + word the longer the answer grew (measured: 15.7 s of main-thread time for 24 s of a 40,000-token answer), until the page stopped answering + and ran out of memory. The pieces are gathered and applied together about ten times a second; any other frame, the end and a failure + apply what is waiting first, so the order the person sees is the order it was written. */ + const waiting: ['reasoning' | 'delta', string][] = []; + let waitingTimer: ReturnType<typeof setTimeout> | null = null; + const applyReasoning = (text: string) => patchAssistant((m) => ({ ...m, reasoning: (m.reasoning ?? '') + text, reasoningStartedAt: m.reasoningStartedAt ?? Date.now() })); + const applyDelta = (text: string) => patchAssistant((m) => { const content=tidyAnswer(m.content+text); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,...(m.blocks?{blocks:appendText(m.blocks,text)}:{}),tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; }); + const flushWaiting = () => { + if (waitingTimer !== null) { clearTimeout(waitingTimer); waitingTimer = null; } + for (const [kind, text] of waiting.splice(0)) if (kind === 'delta') applyDelta(text); else applyReasoning(text); + }; + const queueText = (kind: 'reasoning' | 'delta', text: string) => { + const last = waiting[waiting.length - 1]; + if (last && last[0] === kind) last[1] += text; else waiting.push([kind, text]); + waitingTimer ??= setTimeout(flushWaiting, 90); + }; + try { + await streamPost( + planStart ? '/api/plan/start-goal' : '/api/chat/stream', + { + sessionId, + ...(planStart ? { planId: planStart } : {}), + ...(resume ? { goalAction: 'resume' } : planStart ? {} : { message: options.shown ? body : body }), + history:await Promise.all(prior.map(async(m,index)=>{const included=pictureCheck.ok?(m.photos??[]).filter((_,p)=>imageSlots.has(`${index}:${p}`)):[];const omitted=(m.photos??[]).filter(p=>!included.includes(p));const text=m.content+(omitted.length?`\n[Earlier pictures: ${omitted.map(p=>p.name).join(', ')}. Their pixels are outside this model's image context; ask to reattach them if needed.]`:'');return {role:m.role,content:included.length?[{type:'text',text},...await Promise.all(included.map(async photo=>({type:'image_url',image_url:{url:(await photoData(photo)).url}})))]:text};})), + model: state.library?.loaded ?? state.library?.current ?? null, + remoteModel: state.remoteModel, + nativeModelId:nativeState()?.instances.length?nativeState()?.defaultId:undefined, + ...(pictures.length ? { imageIds: await uploadChatPhotos(pictures, sessionId) } : {}), + useTools:state.sessions.find(s=>s.id===sessionId)?.preferences?.useTools===true, + // A chat set to plain talk (preferences.agent === false) never runs a tool: the host answers it directly. + ...(state.sessions.find(s=>s.id===sessionId)?.preferences?.agent===false?{agent:false}:{}), + thinking:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinking??'Medium', + thinkingBudget:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinkingBudget??0, + // 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: 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. + if (frame.type === 'delta' && typeof frame.key === 'string') frame = { ...frame, text: tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) }; + const type = frame.type as string; + if (type === 'delta' || type === 'reasoning') { queueText(type, String(frame.text ?? '')); return; } + flushWaiting(); + if (type === 'start' && frame.agent === true) { const turn = liveTurns.get(sessionId); if (turn) turn.agent = true; } + if (type === 'queued') { + patchAssistant(m => ({ ...m, requestId: String(frame.requestId) })); + } else if (type === 'start') { + patchAssistant((m) => ({ ...m, demo: frame.demo === true, remoteModel: frame.remoteModel === true, requestId: typeof frame.requestId === 'string' ? frame.requestId : m.requestId, model: String(frame.model), contextMax: Number(frame.contextMax), skillsUsed: Array.isArray(frame.skills) ? frame.skills.map(String) : [] })); + } else if (type === 'status') { + applyStatusFrame(sessionId, frame as Record<string, unknown>); + // Manual mode waits for the person: a notification when they have opted in and Strata is in the background (#3477), once per question. + if (frame.code === 'waiting-approval' && lastApprovalNotice !== `${sessionId}:${String(frame.seq)}`) { + lastApprovalNotice = `${sessionId}:${String(frame.seq)}`; + const tool = (frame.args as { tool?: unknown } | undefined)?.tool; + void approvalNeeded(state.approvalNotify, typeof tool === 'string' ? tool : ''); + } + } else if (type === 'goal') { + applyGoalFrame(sessionId, frame.goal); + } else if (type === 'plan') { + applyPlanFrame(sessionId, frame.plan); + // A proposed plan is shown as the plan card in place of this turn's closing text (that text is the plan in prose). + const planned = frame.plan as { id?: unknown } | null; + if (frame.event === 'proposed' && planned && typeof planned.id === 'string') { const pid = planned.id; patchAssistant(m => ({ ...m, planId: pid })); } + } else if (type === 'queued-message') { + applyQueueFrame(sessionId, frame.queue); + const sent = frame.message as { text?: unknown } | undefined; + if (frame.state === 'delivered' && sent && typeof sent.text === 'string') { + // The host has just sent it into the run: it becomes an ordinary message here, and the answer to it starts a new reply. + const before = assistantId; assistantId = uid('m'); + const next: ChatMessage = { id: assistantId, role: 'assistant', content: '', at: new Date().toISOString(), streaming: true }; + patchSession(sessionId, sess => ({ ...sess, messages: [...sess.messages.map(m => m.id === before ? { ...m, streaming: false } : m), { id: uid('m'), role: 'user', content: sent.text as string, at: new Date().toISOString() }, next] })); + } + } else if (type === 'queued-release') { + // The goal ended with messages left: they go out now, in order, as ordinary messages once this turn has finished. + const left = Array.isArray(frame.messages) ? frame.messages.flatMap(q => (q && typeof (q as { text?: unknown }).text === 'string' ? [String((q as { text: string }).text)] : [])) : []; + if (left.length) releasedMessages.set(sessionId, [...(releasedMessages.get(sessionId) ?? []), ...left]); + } else if (type === 'plan-step') { + /* the whole plan follows in a plan frame; the live status already says which step is running */ + } else if (type === 'reasoning') { + /* applied through queueText above */ + } else if (type === 'notice') { + // The host says why this chat is not using the agent. One toast per reason per page load. + const code = String(frame.code ?? 'notice'); + if (!noticed.has(code)) { noticed.add(code); pushToast('info', 'Agent', plainFailureText(String(frame.message ?? '')).message); } + } else if (type === 'agent-question') { + addAgentAsk(sessionId, frame as { callId?: unknown; questions?: unknown }); + } else if (type === 'agent-question-end') { + removeAgentAsk(sessionId, String(frame.callId ?? '')); + } else if (type === 'agent-tool-draft') { + // A tool call (a whole file, say) is being written: keep its name, size and the tail of its text on the reply until the call is whole or lost. + const d = frame.draft as (ToolDraft & { done?: boolean }) | undefined; + if (d && typeof d.id === 'string') { + const { done, ...view } = d; + patchAssistant(m => { + const rest = (m.drafts ?? []).filter(x => x.id !== d.id); + return { ...m, drafts: done ? (rest.length ? rest : undefined) : [...rest, view] }; + }); + } + } else if (type === 'agent-tool') { + const tool = frame.tool as ToolCall; + patchAssistant(m => { + const existing = m.tools?.find(t => t.id === tool.id); + const next: ToolCall = { ...existing, ...tool, live: true }; + return { ...m, tools: existing ? m.tools!.map(t => t.id === tool.id ? next : t) : [...(m.tools ?? []), next] }; + }); + } else if (type === 'agent') { + patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) })); + } else if (type === 'delta') { + /* applied through queueText above */ + } else if (type === 'deliverable') { + const file = readDeliverable(frame); + if (file) patchAssistant(m => ({ ...m, deliverables: mergeDeliverable(m.deliverables, file) })); + } else if (type === 'skills-used') { + const skills = readSkills(frame); + if (skills.length) patchAssistant(m => ({ ...m, skills })); + } else if (type === 'activity-group') { + const group = readGroup(frame); + if (group) patchAssistant(m => ({ ...m, blocks: upsertGroup(m.blocks ?? (m.content ? appendText(undefined, m.content) : undefined), group) })); + } else if (type === 'artifacts' && Array.isArray(frame.artifacts)) { + patchAssistant(m => ({ ...m, artifacts: frame.artifacts as PreviewArtifact[] })); + } else if(type==='native-tool'){ + const event=frame.event as {event:string;id:string;name?:string;arguments?:Record<string,unknown>;text?:string;ok?:boolean;ms?:number}; + if(event.id)patchAssistant(m=>{const existing=m.tools?.find(t=>t.id===event.id);const tool={id:event.id,name:event.name??existing?.name??'Connected tool',args:event.arguments??existing?.args??{},preview:'Authorized connected tool',effect:'Access configured in the MCP server',scope:'connected' as const,state:event.event==='result'?event.ok?'done' as const:'error' as const:'running' as const,result:event.text,durationMs:event.ms};return {...m,tools:[...(m.tools??[]).filter(t=>t.id!==tool.id),{...existing,...tool}]};}); + } else if (type === 'tool') { + const tool = frame.tool as ChatMessage['tools'] extends (infer T)[] | undefined ? T : never; + patchAssistant((m) => ({ ...m, tools: [...(m.tools ?? []), { ...tool, state: 'proposed' }] })); + } else if (type === 'stats') { + patchAssistant((m) => ({ + ...m, + tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : m.tokens, + tps: typeof frame.tps === 'number' ? frame.tps : m.tps, + promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps, + })); + } else if (type === 'context') { + // What the context holds after each model request of an agent turn: the meter follows the turn instead of waiting for its end. + const used = Number(frame.contextTokens), max = Number(frame.contextMax); + if (Number.isFinite(used) && used > 0) patchAssistant((m) => ({ ...m, contextUsed: used, ...(Number.isFinite(max) && max > 0 ? { contextMax: max } : {}) })); + } else if (type === 'error') { + clearStatus(sessionId); + // A sentence the host wrote for the person (it carries its catalog key) is shown in their language as it is; anything else is made plain here. + const said = typeof frame.key === 'string' ? tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) : plainFailure(String(frame.message ?? 'Engine error')).message; + patchAssistant((m) => ({ ...m, drafts: undefined, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) })); + } else if (type === 'done') { + clearStatus(sessionId); + workFinished(state.doneSound, Number(frame.durationMs ?? performance.now() - started)); + patchSession(sessionId, (sess) => ({ + ...sess, + tokensIn: sess.tokensIn + Number(frame.tokensIn ?? 0), + tokensOut: sess.tokensOut + Number(frame.tokensOut ?? 0), + statsAvailable: typeof frame.tokensIn === 'number' && typeof frame.tokensOut === 'number' && sess.messages.filter(m=>m.role==='assistant'&&!m.streaming).every(m=>typeof m.inputTokens==='number'), + })); + patchAssistant((m) => ({ + ...m, + streaming: false, + drafts: undefined, + durationMs: Number(frame.durationMs ?? performance.now() - started), + tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : undefined, + ttftMs: typeof frame.ttftMs === 'number' ? frame.ttftMs : undefined, + inputTokens: typeof frame.tokensIn === 'number' ? frame.tokensIn : undefined, + contextUsed: typeof frame.contextTokens === 'number' ? frame.contextTokens : undefined, + usageSource: frame.usageSource === 'reported' || frame.usageSource === 'demo' ? frame.usageSource : 'unavailable', + tps: typeof frame.tps === 'number' ? frame.tps : m.tps, + promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps, + })); + // The final text is in `state`: write it once now instead of waiting for the coalescing timer. + flushSessions(); + } + }, + turnAbort.signal, + ); + } catch (err) { + flushWaiting(); + if ((err as Error).name !== 'AbortError') { + patchAssistant((m) => ({ + ...m, + streaming: false, + error: err instanceof Error ? err.message : 'Engine error', + })); + pushToast('error', 'Generation failed', err instanceof Error ? err.message : undefined); + } else { + patchAssistant((m) => ({ ...m, streaming: false })); + } + } finally { + flushWaiting(); + // A cancelled or failed turn is still worth keeping. + flushSessions(); + clearStatus(sessionId); + markTurn(sessionId, null); + removeAgentAsk(sessionId); + const next = releasedMessages.get(sessionId)?.shift(); + if (next !== undefined) { if (!releasedMessages.get(sessionId)?.length) releasedMessages.delete(sessionId); setTimeout(() => void sendMessage(next), 0); } + } +} + +/** Messages the host handed back when a goal ended with some still waiting; sent one after another. */ +const releasedMessages = new Map<string, string[]>(); + +/* -------------------------------------------------------------- tool grants */ + +const noticed = new Set<string>(); + +/** + * Approve or deny a tool the agent asked about. The answer goes to the host, which hands it to the + * Harness approval for exactly this chat and call; the card then follows what the Harness reports + * (running, done, denied). The card shows the choice straight away and goes back if the host refuses. + */ +function answerAgentTool(sessionId: string, messageId: string, tool: ToolCall, approved: boolean) { + const setState = (state_: ToolCall['state'], result?: string) => patchSession(sessionId, s => ({ + ...s, messages: s.messages.map(m => m.id === messageId ? { ...m, tools: (m.tools ?? []).map(t => t.id === tool.id ? { ...t, state: state_, ...(result !== undefined ? { result } : {}) } : t) } : m), + })); + setState(approved ? 'running' : 'denied'); + api.post('/api/chat/approval', { sessionId, toolId: tool.id, decision: approved ? 'approve' : 'deny' }).catch(error => { + setState('proposed'); + pushToast('error', 'That answer was not delivered', error instanceof Error ? error.message : undefined); + }); +} + +/** + * Approving a tool in the design build resolves locally: there is no tool + * runtime behind it yet, so the result is a labelled stand-in. The interaction — + * what is asked, what is shown, what needs a grant — is the real deliverable. + */ +export function resolveTool(messageId: string, toolId: string, approved: boolean) { + const sessionId = state.activeSession; + if (!sessionId) return; + const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId); + if (tool?.live) { answerAgentTool(sessionId, messageId, tool, approved); return; } + + patchSession(sessionId, (s) => ({ + ...s, + messages: s.messages.map((m) => + m.id === messageId + ? { + ...m, + tools: (m.tools ?? []).map((t) => + t.id === toolId + ? { + ...t, + state: approved ? 'done' : 'denied', + durationMs: undefined, + result: approved ? 'Approval recorded. Nothing was executed.' : 'Denied. Nothing ran.', + } + : t, + ), + } + : m, + ), + })); + +} + +/* ------------------------------------------------------------------- routes */ + +export function go(route: Route, param?: string) { + navigate(route, param); + // Focus mode is a reading mode for the conversation. Leaving it to work on + // something else leaves the mode, rather than stranding a bare shell. + if (state.focus && route !== 'chat' && route !== 'settings') setFocus(false); + set({ paletteOpen: false, navOpen: false }); +} + +/* ---------------------------------------------------------------- bootstrap */ + +export function bootOnce() { + if ((globalThis as { __strataBooted?: boolean }).__strataBooted) return; + (globalThis as { __strataBooted?: boolean }).__strataBooted = true; + for (const session of state.sessions) for (const run of session.timeSkips ?? []) { scheduleTimeSkip(session.id, run); if (run.job && !run.completedAt) { markTurn(session.id, { abort: new AbortController(), agent: false }); void followTimeSkip(session.id, run.id); } } + // A loop lives in the window: one the last window left "running" has ended, and the board says so. + if (state.sessions.some(s => s.loop?.state === 'running')) { + const sessions = state.sessions.map(s => s.loop?.state === 'running' ? { ...s, loop: { ...s.loop, state: 'ended' as const, endedWhy: 'closed' as const, endedAt: Date.parse(s.updatedAt) || Date.now() } } : s); + persistSessions(sessions); + set({ sessions }); + } + void bootstrap(); + void reconcileAgentTools(); +} + +/** + * After a reload, a tool card the browser remembers as waiting or running may belong to a turn that no + * longer exists. Cards whose approval the host still holds stay answerable; the rest are marked as + * interrupted so nothing looks like it is still working. + */ +async function reconcileAgentTools() { + const open = (t: ToolCall) => t.live && (t.state === 'proposed' || t.state === 'running'); + for (const session of state.sessions) { + if (!session.messages.some(m => m.tools?.some(open))) continue; + let waiting = new Set<string>(); + try { + const r = await api.get<{ pending: { callId: string }[] }>(`/api/agent/pending?chatId=${encodeURIComponent(session.id)}`); + waiting = new Set(r.pending.map(p => p.callId)); + } catch { /* The host is unreachable; leave the cards for the next load. */ continue; } + patchSession(session.id, sess => ({ ...sess, messages: sess.messages.map(m => m.tools?.some(open) ? { ...m, tools: m.tools.map(t => open(t) && !waiting.has(t.id) ? { ...t, state: 'error' as const, result: 'The page closed before this finished. Check the workspace to see what it did.' } : t) } : m) })); + } +} + + +export function setContrast(contrast: 'standard' | 'increased') { set({ contrast }); savePrefs(); } +matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (state.theme === 'system') applyPrefs(); }); + +export async function loadRuntimeModel(body:unknown){ + const result=await api.post<{state:RuntimeModels;instance:{id:string}}>('/api/runtime/load',body); + set({runtime:result.state});return result.instance.id; +} +export async function runtimeModelAction(id:string,action:'unload'|'default'){ + set({runtime:await api.post<RuntimeModels>(`/api/runtime/${id}/${action}`)}); +} + +export async function changeModelDirectory(directory: string, unload: boolean) { + set(s => ({ busy: { ...s.busy, modelDirectory: true } })); + try { + const result = await api.post<{ library: ModelLibrary; imageModels: ImageModelLibrary; runtime: RuntimeModels; hardware: Hardware; setup: SetupState }>('/api/storage/models-directory', { directory, unload }); + set(result); + return result; + } finally { + set(s => ({ busy: { ...s.busy, modelDirectory: false } })); + } +} + +export async function addLocalModel(path: string, name?: string) { + const result = await api.post<{ library: ModelLibrary; variantId: string }>('/api/local-models', { path, name }); + set({ library: result.library }); + return result.variantId; +} diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts index 5b9b8c1828..be8d9f3a1c 100644 --- a/apps/host/src/lib/types.ts +++ b/apps/host/src/lib/types.ts @@ -1,517 +1,541 @@ -/** Shared shapes for the Strata host API. Mirrors server/types.d.ts. */ - -export type CheckState = 'pass' | 'warn' | 'fail'; -export interface SoftwareUpdate { - installedVersion?: string; - status: 'available' | 'current' | 'unavailable' | 'error' | 'no-releases'; - latestVersion?: string; - releaseUrl?: string; - canInstall: boolean; - message: string; - /** The technical reason behind `message`, shown only behind the Details disclosure. */ - details?: string; -} -export interface UpdateCheckResult { checkedAt: string; strata: SoftwareUpdate; engine: SoftwareUpdate } - -export interface HardwareCheck { - id: 'gpu' | 'memory' | 'cpu' | 'storage'; - label: string; - state: CheckState; - detail: string; - value?: string; -} - -export interface ProcessorInfo { id:string; socket:string; model:string; cores:number; threads:number; arch:string; ghz:number; logicalIds?:number[] } -export interface CpuReading { id:string; utilizationPct:number|null } -export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null; fanPct?:number|null; clockMhz?:number|null } - -export interface GpuInfo { - id?: string; - index: number; - vendor: 'apple' | 'nvidia' | 'amd' | 'intel' | 'unknown'; - name: string; - vramGb: number; - freeVramGb?: number; - unified: boolean; - backend: 'metal' | 'cuda' | 'rocm' | 'vulkan' | 'cpu'; - driver?: string; -} - -export interface Hardware { - probedAt: string; - host: { name: string; platform: string; release: string; arch: string; app: string }; - processors?: ProcessorInfo[]; - cpu: { topologyKnown?:boolean; model: string; cores: number; threads: number; arch: string; ghz: number }; - memory: { totalGb: number; freeGb: number; usedGb: number; pressure: 'low' | 'medium' | 'high' }; - disk: { path: string; totalGb: number; freeGb: number; modelsDir: string }; - gpus: GpuInfo[]; - accelerator: { backend: string; label: string; usableVramGb: number; unified: boolean }; - checks: HardwareCheck[]; - verdict: { ok: boolean; headline: string; detail: string }; - recommendedVariantId: string; -} - -export type VariantState = - | 'available' - | 'downloading' - | 'installed' - | 'loading' - | 'loaded' - | 'unloading' - | 'error'; - -export interface ModelVariant { - local?: { path: string; files: { path: string; bytes: number; mtimeMs: number; ctimeMs: number }[]; architecture: string; contextLength: number; hasChatTemplate: boolean; shards: number; metadataSignature: string }; - source?: { repo: string; file: string; bytes?: number }; - downloadUrl?: string; - kvKbPerToken?: number; - catalog?: { family: string; version: string; purpose: string; capabilities: string[]; agentApproved: boolean; balancedRank: number; review: string }; - performance?: import('./experience').SpeedEvidence[]; - id: string; - name: string; - family: string; - quant: string; - label: string; - params: string; - blurb: string; - role: 'best-fit' | 'option'; - ramClass: { minGb: number; maxGb: number; label: string }; - diskGb: number; - downloadGb: number; - contextMax: number; - layerCount: number; - experts: number; - hasDraft: boolean; - kvModes: string[]; - tags: string[]; - state: VariantState; - progress?: { pct: number; mbps: number; etaSec: number; stage: string }; - error?: string; - installedAt?: string; -} - -export interface LocalModelPreview { variant: ModelVariant; files: string[]; warnings: string[] } -export interface LocalModelFolder { directory: string; parent: string | null; entries: { name: string; path: string; kind: 'folder' | 'model'; bytes?: number }[]; truncated: boolean; shortcuts: { name: string; path: string }[] } - -export interface ModelLibrary { - mode?: 'real' | 'simulated'; - current: string | null; - loaded: string | null; - variants: ModelVariant[]; - downloads: { active: number; queued: number; totalGbToday: number }; - disk: { modelsDir: string; usedGb: number; freeGb: number }; -} - -export type ImageModelChoice = 'off' | 'q4' | 'q5' | 'q6' | 'q8'; -export interface ImageModelVariant { - id: Exclude<ImageModelChoice, 'off'>; - label: string; - quant: string; - file: string; - bytes: number; - downloadGb: number; - downloadUrl: string; - state: 'available' | 'downloading' | 'installed' | 'error'; - progress?: { pct: number; stage: string }; - error?: string; -} -export interface ImageModelLibrary { - mode: 'real' | 'simulated'; - family: string; - sourceUrl: string; - revision: string; - selected: ImageModelChoice; - applied: ImageModelChoice; - generationAvailable: boolean; - variants: ImageModelVariant[]; -} - -export type ModelProtocol = 'openai-chat' | 'openai-responses' | 'anthropic'; -export interface ApiModel { id: string; name: string; contextMax?: number | null; /** What the person ticked ("This model reads pictures"): true, false, or null for not set. */ vision?: boolean | null; /** The answer in use: the tick, else what the server said; null when nobody knows. */ reads?: boolean | null; /** The provider says the model can think (OpenRouter's supported_parameters): the Reasoning menu then works. */ reasoning?: boolean | null; thinks?: boolean | null } -export interface ModelProviderPreset { id: string; name: string; baseUrl: string; protocol: ModelProtocol; baseUrlHint?: string } -export interface ModelConnection { - id: string; kind: 'provider' | 'custom'; provider: string | null; name: string; - baseUrl: string; protocol: ModelProtocol; apiKeySet: boolean; models: ApiModel[]; -} -export interface ModelProviders { catalog: ModelProviderPreset[]; connections: ModelConnection[] } -export interface RemoteModelSelection { connectionId: string; modelId: string } -export interface ModelConnectionDraft { - id?: string; kind: 'provider' | 'custom'; provider: string | null; name: string; - baseUrl: string; protocol: ModelProtocol; apiKey: string; clearKey?: boolean; models: ApiModel[]; -} - -export type Effort = 'fastest' | 'balanced' | 'quality' | 'max'; - -export interface BeginnerConfig { - priority: 'speed' | 'balanced' | 'quality' | 'coding'; - contextLength: 'recommended' | `${number}k`; - readImages: boolean; - gpuIdle: 'never' | '5m' | '15m' | '1h'; -} - -export interface ExpertParam { - applies?: string; - id: string; - group: string; - label: string; - effect: string; - type: 'select' | 'number' | 'text' | 'toggle'; - options?: string[]; - value: string | number | boolean; - recommended: string | number | boolean; - advanced?: boolean; -} - -export interface EngineConfig { - extra?: Record<string, unknown>; - variantId: string; - beginner: BeginnerConfig; - expert: ExpertParam[]; - predicted: { - responseSpeed: string; - memory: string; - restartNeeded: boolean; - notes: string[]; - }; - dirty: boolean; - appliedAt?: string; - engine: { - status?: string; - error?: string | null; - port?: number; - running: boolean; - pid?: number; - uptimeSec: number; - version: string; - backend: string; - startedAt?: string; - }; -} - -export interface RuntimeModel { - id:string; apiModelId:string; variantId:string; family:string; name:string; quant:string; - gpuIds:string[]; loadedAt:string; status:'ready'; phase:MonitorState['phase']; - active:number; queued:number; prompt:MonitorState['prompt']; outputTps:number; promptTps:number; - context:MonitorState['context']; - memory:{context:number;ramGb:number;gpuGb:number;spillGb:number;reserveGb:number;totalGb:number;devices:{id:string;gb:number}[]}; -} -export interface RuntimeModels { - revision:number; mode:'real'|'simulated'; capabilities:{multipleModels:boolean;deviceAssignment:boolean}; defaultId:string|null; - instances:RuntimeModel[]; - memory:{ramGb:number;budgetGb:number;reserveGb:number;totalGb:number;fits:boolean;devices:{id:string;name:string;usedGb:number;budgetGb:number}[]}; -} - -export interface ServeRequest { - instanceId?:string; - gpuIds?:string[]; - id: string; - at: string; - client: string; - endpoint: string; - state: 'generating' | 'queued' | 'done' | 'error'; - tokensIn: number | null; - tokensOut: number | null; - cancellable?: boolean; - cancelRequested?: boolean; - usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated'; - durationMs: number; - error?: string; - model: string; - cachedTokens?: number | null; - tps?: number | null; - promptTps?: number | null; - hitRate?: number | null; - pcieShare?: number | null; - finishReason?: string | null; -} - -export interface TunnelState { status: 'idle' | 'starting' | 'connected' | 'stopping' | 'error'; mode: 'quick' | 'domain' | null; url: string | null; error: string | null; warning?: string | null; installed: boolean; originUrl: string; connector?: { path: string; version: string | null; source: string; label: string; summary: string } | null; external?: { kind: 'service' | 'process'; others: number[]; own: number[]; message: string } | null; } - -export interface ServingState { - tunnel?: TunnelState; - sharing?: { active: boolean; url: string | null; warning?: string | null }; - revision?: number; - running: boolean; - baseUrl: string; - /** The address on this computer (the app's own port); baseUrl is the network address while sharing is on. */ - localUrl?: string; - port: number; - endpoints: { openai: string; anthropic: string; models: string }; - access: { otherDevices: boolean; apiKeySet: boolean; apiKeyHint: string | null; allowOrigin: string }; - stats: { running: number; waiting: number; completed: number; failed: number; tokensOut: number }; - requests: ServeRequest[]; - pauseServing: boolean; -} - -export interface MonitorSample { - /** Device IDs covered by aggregate GPU history; omitted for legacy host-wide samples. */ - gpuIds?: string[]; - t: number; - outputTps: number | null; - promptTps: number | null; - gpuLoad: number | null; - vramUsedGb: number | null; - ramUsedGb: number | null; - gpuTempC: number | null; - diskReadGbs: number | null; - cpuLoad?: number | null; - powerW?: number | null; - pcieRxMbs?: number | null; - gpus?: GpuReading[]; - cpus?: CpuReading[]; -} - -export interface MonitorState { - telemetry?: { throughput: string; thermals: string; memory: string; system?:string; context?: string; ttftMs?: number | null }; - phase: 'idle' | 'reading' | 'thinking' | 'generating' | 'loading' | 'error'; - phaseLabel: string; - variantId: string | null; - prompt: { done: number; total: number; pct: number }; - generation?: { done:number|null; total:number|null }; - outputTps: number; - promptTps: number; - queue: { running: number; waiting: number }; - context: { - requestId?: string; - sessionId?: string; - usedTokens: number; - maxTokens: number; - pct: number; - parts?: { system: number; tools: number; messages: number }; - }; - expertCache: { used: number; total: number; memoryGb?:number|null; source?:string }; - hardware: { - gpus?: GpuReading[]; - cpus?: CpuReading[]; - cpuLoad?: number | null; - powerW?: number | null; - powerLimitW?: number | null; - pcieRxMbs?: number | null; - /** CPU and SSD temperatures (only where this PC can give one) and the GPU energy used since the host started, in Wh (#3628). */ - cpuTempC?: number | null; - ssdTempC?: number | null; - energyWh?: number | null; - diskReadGbs?: number | null; - diskWriteMbs?: number | null; - gpuLoad: number | null; - vramUsedGb: number | null; - vramTotalGb: number; - ramUsedGb: number | null; - ramTotalGb: number; - gpuTempC: number | null; - tempLimitC: number; - }; - history: MonitorSample[]; - requests?: ServeRequest[]; - conversationCache?: { enabled?:boolean; parked?:number; slots?:number; memoryGb?:number; budgetGb?:number; parks?:number; restores?:number; evictions?:number; lastEvent?:string; lastAt?:number; lastTokens?:number; requests?:number;requestsReused?:number;lastPrompt?:number;lastReused?:number; source:string }; - mcp?: { servers:{ name:string; state:string; transport?:string; info?:{name?:string;version?:string}; error?:string; tools:{name:string;description?:string}[] }[]; tools:number }; - totals: { - promptMs?: number; - decodeMs?: number; - usageRequests?: number; - latencyRequests?: number; - tokensIn: number; - tokensOut: number; - requests: number; - avgTps: number; - since: string; - ttftMs: number; - cachedTokens: number; - uncachedTokens: number; - }; -} - -export interface ChatMessage { - /** The person's message is written with Markdown (a task handover: bold headings and lists), so the bubble draws it as such. */ - markdown?: boolean; - photos?:import('./chat-photos').ChatPhoto[]; - /** Reply came from a saved API connection, rather than the local engine. */ - remoteModel?: boolean; - timeSkipId?: string; - /** The plan this reply proposed: shown as the plan card in place of the reply text. */ - planId?: string; - /** The reply in the order it came: text and grouped activity lines (round 8, item 12). Absent on older replies. */ - blocks?: import('./deliverables').MessageBlock[]; - /** The saved skills this reply used (the line under the answer), in the order they were loaded. */ - skills?: { name: string; description: string }[]; - /** Files the assistant made or changed in this reply, one card each. */ - deliverables?: import('./deliverables').Deliverable[]; - /** A line from the app itself (for example from /loop), never sent to the model. */ - local?: boolean; - ttftMs?: number; - example?: boolean; - media?: {kind: 'image' | 'video' | 'gif'; src:string; title:string; caption?:string; poster?:string}[]; - artifacts?: import('./artifacts').PreviewArtifact[]; - requestId?: string; - model?: string; - inputTokens?: number; - /** What the context held after this reply (the last model request's prompt + reply); an agent turn's inputTokens add every request up. */ - contextUsed?: number; - /** When the first reasoning arrived, and how long the model reasoned before it began the answer (for "Thought for 38s"). */ - reasoningStartedAt?: number; - reasoningMs?: number; - contextMax?: number; - usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated'; - skillsUsed?: string[]; - id: string; - role: 'user' | 'assistant' | 'system'; - content: string; - at: string; - streaming?: boolean; - demo?: boolean; - reasoning?: string; - reasoningOpen?: boolean; - tokens?: number; - tps?: number; - promptTps?: number; - durationMs?: number; - error?: string; - /** What went wrong, as a code the page acts on (a context error offers its own recovery buttons). */ - errorCode?: string; - /** The engine's own text of the error, kept behind Details. */ - errorDetail?: string; - tools?: ToolCall[]; -} - -export type ToolState = 'proposed' | 'approved' | 'running' | 'done' | 'denied' | 'error'; - -export interface ToolCall { - id: string; - name: string; - args: Record<string, unknown>; - preview: string; - effect: string; - scope: 'read' | 'write' | 'shell' | 'connected'; - /** The card's headline in plain words for its current state ("Wrote a file"); the host sends it, the UI translates it. */ - verb?: string; - /** What the action is on: a file path, the command, a web address. */ - target?: string; - /** The question an approval card asks in plain words (server/agent/ask.mjs); the page translates it. */ - ask?: { id: string; params?: (string | number)[]; why?: string; detail?: string }; - state: ToolState; - result?: string; - durationMs?: number; - /** Reported by the agent runtime: an approval answers a real request. Absent for design-build examples. */ - live?: boolean; - /** The person approved this call. A finished card without it was never asked about. */ - approved?: boolean; -} - -/** A folder the model may read, and that sessions are grouped under. */ -export interface Workspace { - id: string; - name: string; - path: string; - /** Earlier folders whose chats belong here (the first workspace moved off the app's own folder). */ - aliases?: string[]; -} - -export interface SessionAgent { - id: string; - name: string; - description: string; - status: 'working' | 'completed' | 'failed' | 'queued' | 'cancelled'; - durationMs: number; - tokens: number; - /** Time the latest duration measurement was received. */ - updatedAt?: number; -} - -export type ChatMode = 'auto' | 'manual' | 'accept-edits' | 'plan' | 'bypass'; - -/** - * What the board needs to know about a /loop after the window closes: loops live in memory, so the chat keeps a small record of the - * last one (running, or how it ended). A record that says `running` with no loop behind it is a loop the window closed on. - */ -export interface LoopRecord { - prompt: string; - everyMs: number; - startedAt: number; - state: 'running' | 'ended'; - answers: number; - maxRuns?: number; - /** When the next answer is due (ms), while running. */ - nextAt?: number; - endedAt?: number; - /** count, said-done, time, failures, cap; `stopped` when the person typed /loop stop; `closed` when the window closed on it. */ - endedWhy?: 'count' | 'said-done' | 'time' | 'failures' | 'cap' | 'stopped' | 'closed'; - /** The last answer's first words, for the card. */ - lastText?: string; -} - -export interface Session { - /** The person dismissed this chat's (or its loop's) card on the board at this time. A later problem brings it back. */ - ackedAt?: string; - loop?: LoopRecord; - timeSkips?: import('./time-skip').TimeSkipRun[]; - showcase?: boolean; - agents?: SessionAgent[]; - previewOpen?: string; - closedPreviews?: string[]; - showcaseAgentStates?: boolean; - preferences?: { access?: 'read' | 'write' | 'full'; thinking?: string; thinkingBudget?: number; mode?: ChatMode; useTools?:boolean; /** false: plain conversation, no tools of any kind. */ agent?: boolean; /** This chat's API model; absent or null means the local model. */ remoteModel?: RemoteModelSelection | null }; - /** A branch does not have retained per-turn input usage. */ - statsAvailable?: boolean; - id: string; - title: string; - defaultTitle?: boolean; - updatedAt: string; - createdAt: string; - messages: ChatMessage[]; - workspace: string; - tokensIn: number; - tokensOut: number; - pinned?: boolean; - /** Put away without deleting. Archiving is for "done with this for now" — - * deleting is for "never want to see it again", and conflating the two makes - * people keep things they are finished with. */ - archived?: boolean; - /** When this conversation was last on screen. A session is unread when it has - * been updated since — which is the only way to tell, with more than a - * handful of conversations, which ones have something new in them. */ - lastReadAt?: string; -} - -export interface Skill { - id: string; - name: string; - description: string; - source: 'bundled' | 'workspace' | 'user'; - enabled: boolean; - triggers: string[]; - /** The instruction text itself — what the model is actually told. Deciding - * whether to trust a skill means reading this, not its name. */ - body?: string; - /** When set, the skill applies only in this workspace. A skill written for - * one project is noise in another, and on/off cannot express "here, not - * there". */ - onlyIn?: string | null; - /** How many times a prompt has actually triggered this skill, and when last. */ - useCount?: number; - lastUsedAt?: string | null; - sizeKb: number; -} - -export interface WorkspaceFile { - path: string; - kind: 'file' | 'dir'; - sizeKb?: number; - updatedAt?: string; -} - -export interface SetupState { - flowVersion?: number; - dismissed?: boolean; - choices?: { onboarding?: { step:number; family?:string; size?:string; context?:number; vision?:boolean; directory?:string; profile?:'work'|'performance'; installJobId?:string; tuneJobId?:string; calibrate?:boolean; manual?:boolean }; variantId?: string; contextLength?: BeginnerConfig["contextLength"]; profile?: import("./experience").Profile; batch?: number; batchAuto?: boolean }; - complete: boolean; - step: number; - completedAt?: string; - history: { step: number; at: string }[]; - app: { version: string; modelsDir: string; dataDir: string; modelsDirNotice?: string }; -} - -export interface EngineEvent { - type: 'engine' | 'monitor' | 'models' | 'serving' | 'download' | 'log'; - at: string; - payload: unknown; -} +/** Shared shapes for the Strata host API. Mirrors server/types.d.ts. */ + +export type CheckState = 'pass' | 'warn' | 'fail'; +export interface SoftwareUpdate { + installedVersion?: string; + status: 'available' | 'current' | 'unavailable' | 'error' | 'no-releases'; + latestVersion?: string; + releaseUrl?: string; + canInstall: boolean; + message: string; + /** The technical reason behind `message`, shown only behind the Details disclosure. */ + details?: string; +} +export interface UpdateCheckResult { checkedAt: string; strata: SoftwareUpdate; engine: SoftwareUpdate } + +export interface HardwareCheck { + id: 'gpu' | 'memory' | 'cpu' | 'storage'; + label: string; + state: CheckState; + detail: string; + value?: string; +} + +export interface ProcessorInfo { id:string; socket:string; model:string; cores:number; threads:number; arch:string; ghz:number; logicalIds?:number[] } +export interface CpuReading { id:string; utilizationPct:number|null } +export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null; fanPct?:number|null; clockMhz?:number|null } + +export interface GpuInfo { + id?: string; + index: number; + vendor: 'apple' | 'nvidia' | 'amd' | 'intel' | 'unknown'; + name: string; + vramGb: number; + freeVramGb?: number; + unified: boolean; + backend: 'metal' | 'cuda' | 'rocm' | 'vulkan' | 'cpu'; + driver?: string; +} + +export interface Hardware { + probedAt: string; + host: { name: string; platform: string; release: string; arch: string; app: string }; + processors?: ProcessorInfo[]; + cpu: { topologyKnown?:boolean; model: string; cores: number; threads: number; arch: string; ghz: number }; + memory: { totalGb: number; freeGb: number; usedGb: number; pressure: 'low' | 'medium' | 'high' }; + disk: { path: string; totalGb: number; freeGb: number; modelsDir: string }; + gpus: GpuInfo[]; + accelerator: { backend: string; label: string; usableVramGb: number; unified: boolean }; + checks: HardwareCheck[]; + verdict: { ok: boolean; headline: string; detail: string }; + recommendedVariantId: string; +} + +export type VariantState = + | 'available' + | 'downloading' + | 'installed' + | 'loading' + | 'loaded' + | 'unloading' + | 'error'; + +export interface ModelVariant { + local?: { path: string; files: { path: string; bytes: number; mtimeMs: number; ctimeMs: number }[]; architecture: string; contextLength: number; hasChatTemplate: boolean; shards: number; metadataSignature: string }; + source?: { repo: string; file: string; bytes?: number }; + downloadUrl?: string; + kvKbPerToken?: number; + catalog?: { family: string; version: string; purpose: string; capabilities: string[]; agentApproved: boolean; balancedRank: number; review: string }; + performance?: import('./experience').SpeedEvidence[]; + id: string; + name: string; + family: string; + quant: string; + label: string; + params: string; + blurb: string; + role: 'best-fit' | 'option'; + ramClass: { minGb: number; maxGb: number; label: string }; + diskGb: number; + downloadGb: number; + contextMax: number; + layerCount: number; + experts: number; + hasDraft: boolean; + kvModes: string[]; + tags: string[]; + state: VariantState; + progress?: { pct: number; mbps: number; etaSec: number; stage: string }; + error?: string; + installedAt?: string; +} + +export interface LocalModelPreview { variant: ModelVariant; files: string[]; warnings: string[] } +export interface LocalModelFolder { directory: string; parent: string | null; entries: { name: string; path: string; kind: 'folder' | 'model'; bytes?: number }[]; truncated: boolean; shortcuts: { name: string; path: string }[] } + +export interface ModelLibrary { + mode?: 'real' | 'simulated'; + current: string | null; + loaded: string | null; + variants: ModelVariant[]; + downloads: { active: number; queued: number; totalGbToday: number }; + disk: { modelsDir: string; usedGb: number; freeGb: number }; +} + +export type ImageModelChoice = 'off' | 'q4' | 'q5' | 'q6' | 'q8'; +export interface ImageModelVariant { + id: Exclude<ImageModelChoice, 'off'>; + label: string; + quant: string; + file: string; + bytes: number; + downloadGb: number; + downloadUrl: string; + state: 'available' | 'downloading' | 'installed' | 'error'; + progress?: { pct: number; stage: string }; + error?: string; +} +export interface ImageModelLibrary { + mode: 'real' | 'simulated'; + family: string; + sourceUrl: string; + revision: string; + selected: ImageModelChoice; + applied: ImageModelChoice; + generationAvailable: boolean; + variants: ImageModelVariant[]; +} + +export type ModelProtocol = 'openai-chat' | 'openai-responses' | 'anthropic'; +export interface ApiModel { id: string; name: string; contextMax?: number | null; /** What the person ticked ("This model reads pictures"): true, false, or null for not set. */ vision?: boolean | null; /** The answer in use: the tick, else what the server said; null when nobody knows. */ reads?: boolean | null; /** The provider says the model can think (OpenRouter's supported_parameters): the Reasoning menu then works. */ reasoning?: boolean | null; thinks?: boolean | null } +export interface ModelProviderPreset { id: string; name: string; baseUrl: string; protocol: ModelProtocol; baseUrlHint?: string } +export interface ModelConnection { + id: string; kind: 'provider' | 'custom'; provider: string | null; name: string; + baseUrl: string; protocol: ModelProtocol; apiKeySet: boolean; models: ApiModel[]; +} +export interface ModelProviders { catalog: ModelProviderPreset[]; connections: ModelConnection[] } +export interface RemoteModelSelection { connectionId: string; modelId: string } +export interface ModelConnectionDraft { + id?: string; kind: 'provider' | 'custom'; provider: string | null; name: string; + baseUrl: string; protocol: ModelProtocol; apiKey: string; clearKey?: boolean; models: ApiModel[]; +} + +export type Effort = 'fastest' | 'balanced' | 'quality' | 'max'; + +export interface BeginnerConfig { + priority: 'speed' | 'balanced' | 'quality' | 'coding'; + contextLength: 'recommended' | `${number}k`; + readImages: boolean; + gpuIdle: 'never' | '5m' | '15m' | '1h'; +} + +export interface ExpertParam { + applies?: string; + id: string; + group: string; + label: string; + effect: string; + type: 'select' | 'number' | 'text' | 'toggle'; + options?: string[]; + value: string | number | boolean; + recommended: string | number | boolean; + advanced?: boolean; +} + +export interface EngineConfig { + extra?: Record<string, unknown>; + variantId: string; + beginner: BeginnerConfig; + expert: ExpertParam[]; + predicted: { + responseSpeed: string; + memory: string; + restartNeeded: boolean; + notes: string[]; + }; + dirty: boolean; + appliedAt?: string; + engine: { + status?: string; + error?: string | null; + port?: number; + running: boolean; + pid?: number; + uptimeSec: number; + version: string; + backend: string; + startedAt?: string; + }; +} + +export interface RuntimeModel { + id:string; apiModelId:string; variantId:string; family:string; name:string; quant:string; + gpuIds:string[]; loadedAt:string; status:'ready'; phase:MonitorState['phase']; + active:number; queued:number; prompt:MonitorState['prompt']; outputTps:number; promptTps:number; + context:MonitorState['context']; + memory:{context:number;ramGb:number;gpuGb:number;spillGb:number;reserveGb:number;totalGb:number;devices:{id:string;gb:number}[]}; +} +export interface RuntimeModels { + revision:number; mode:'real'|'simulated'; capabilities:{multipleModels:boolean;deviceAssignment:boolean}; defaultId:string|null; + instances:RuntimeModel[]; + memory:{ramGb:number;budgetGb:number;reserveGb:number;totalGb:number;fits:boolean;devices:{id:string;name:string;usedGb:number;budgetGb:number}[]}; +} + +export interface ServeRequest { + instanceId?:string; + gpuIds?:string[]; + id: string; + at: string; + client: string; + endpoint: string; + state: 'generating' | 'queued' | 'done' | 'error'; + tokensIn: number | null; + tokensOut: number | null; + cancellable?: boolean; + cancelRequested?: boolean; + usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated'; + durationMs: number; + error?: string; + model: string; + cachedTokens?: number | null; + tps?: number | null; + promptTps?: number | null; + hitRate?: number | null; + pcieShare?: number | null; + finishReason?: string | null; +} + +export interface TunnelState { status: 'idle' | 'starting' | 'connected' | 'stopping' | 'error'; mode: 'quick' | 'domain' | null; url: string | null; error: string | null; warning?: string | null; installed: boolean; originUrl: string; connector?: { path: string; version: string | null; source: string; label: string; summary: string } | null; external?: { kind: 'service' | 'process'; others: number[]; own: number[]; message: string } | null; } + +export interface ServingState { + tunnel?: TunnelState; + sharing?: { active: boolean; url: string | null; warning?: string | null }; + revision?: number; + running: boolean; + baseUrl: string; + /** The address on this computer (the app's own port); baseUrl is the network address while sharing is on. */ + localUrl?: string; + port: number; + endpoints: { openai: string; anthropic: string; models: string }; + access: { otherDevices: boolean; apiKeySet: boolean; apiKeyHint: string | null; allowOrigin: string }; + stats: { running: number; waiting: number; completed: number; failed: number; tokensOut: number }; + requests: ServeRequest[]; + pauseServing: boolean; +} + +export interface MonitorSample { + /** Device IDs covered by aggregate GPU history; omitted for legacy host-wide samples. */ + gpuIds?: string[]; + t: number; + outputTps: number | null; + promptTps: number | null; + gpuLoad: number | null; + vramUsedGb: number | null; + ramUsedGb: number | null; + gpuTempC: number | null; + diskReadGbs: number | null; + cpuLoad?: number | null; + powerW?: number | null; + pcieRxMbs?: number | null; + gpus?: GpuReading[]; + cpus?: CpuReading[]; +} + +export interface MonitorState { + telemetry?: { throughput: string; thermals: string; memory: string; system?:string; context?: string; ttftMs?: number | null }; + phase: 'idle' | 'reading' | 'thinking' | 'generating' | 'loading' | 'error'; + phaseLabel: string; + variantId: string | null; + prompt: { done: number; total: number; pct: number }; + generation?: { done:number|null; total:number|null }; + outputTps: number; + promptTps: number; + queue: { running: number; waiting: number }; + context: { + requestId?: string; + sessionId?: string; + usedTokens: number; + maxTokens: number; + pct: number; + parts?: { system: number; tools: number; messages: number }; + }; + expertCache: { used: number; total: number; memoryGb?:number|null; source?:string }; + hardware: { + gpus?: GpuReading[]; + cpus?: CpuReading[]; + cpuLoad?: number | null; + powerW?: number | null; + powerLimitW?: number | null; + pcieRxMbs?: number | null; + /** CPU and SSD temperatures (only where this PC can give one) and the GPU energy used since the host started, in Wh (#3628). */ + cpuTempC?: number | null; + ssdTempC?: number | null; + energyWh?: number | null; + diskReadGbs?: number | null; + diskWriteMbs?: number | null; + gpuLoad: number | null; + vramUsedGb: number | null; + vramTotalGb: number; + ramUsedGb: number | null; + ramTotalGb: number; + gpuTempC: number | null; + tempLimitC: number; + }; + history: MonitorSample[]; + requests?: ServeRequest[]; + conversationCache?: { enabled?:boolean; parked?:number; slots?:number; memoryGb?:number; budgetGb?:number; parks?:number; restores?:number; evictions?:number; lastEvent?:string; lastAt?:number; lastTokens?:number; requests?:number;requestsReused?:number;lastPrompt?:number;lastReused?:number; source:string }; + mcp?: { servers:{ name:string; state:string; transport?:string; info?:{name?:string;version?:string}; error?:string; tools:{name:string;description?:string}[] }[]; tools:number }; + totals: { + promptMs?: number; + decodeMs?: number; + usageRequests?: number; + latencyRequests?: number; + tokensIn: number; + tokensOut: number; + requests: number; + avgTps: number; + since: string; + ttftMs: number; + cachedTokens: number; + uncachedTokens: number; + }; +} + +export interface ChatMessage { + /** Tool calls the model is writing right now (a file, a command): live data for the writing card; see ToolDraft. */ + drafts?: ToolDraft[]; + /** The person's message is written with Markdown (a task handover: bold headings and lists), so the bubble draws it as such. */ + markdown?: boolean; + photos?:import('./chat-photos').ChatPhoto[]; + /** Reply came from a saved API connection, rather than the local engine. */ + remoteModel?: boolean; + timeSkipId?: string; + /** The plan this reply proposed: shown as the plan card in place of the reply text. */ + planId?: string; + /** The reply in the order it came: text and grouped activity lines (round 8, item 12). Absent on older replies. */ + blocks?: import('./deliverables').MessageBlock[]; + /** The saved skills this reply used (the line under the answer), in the order they were loaded. */ + skills?: { name: string; description: string }[]; + /** Files the assistant made or changed in this reply, one card each. */ + deliverables?: import('./deliverables').Deliverable[]; + /** A line from the app itself (for example from /loop), never sent to the model. */ + local?: boolean; + ttftMs?: number; + example?: boolean; + media?: {kind: 'image' | 'video' | 'gif'; src:string; title:string; caption?:string; poster?:string}[]; + artifacts?: import('./artifacts').PreviewArtifact[]; + requestId?: string; + model?: string; + inputTokens?: number; + /** What the context held after this reply (the last model request's prompt + reply); an agent turn's inputTokens add every request up. */ + contextUsed?: number; + /** When the first reasoning arrived, and how long the model reasoned before it began the answer (for "Thought for 38s"). */ + reasoningStartedAt?: number; + reasoningMs?: number; + contextMax?: number; + usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated'; + skillsUsed?: string[]; + id: string; + role: 'user' | 'assistant' | 'system'; + content: string; + at: string; + streaming?: boolean; + demo?: boolean; + reasoning?: string; + reasoningOpen?: boolean; + tokens?: number; + tps?: number; + promptTps?: number; + durationMs?: number; + error?: string; + /** What went wrong, as a code the page acts on (a context error offers its own recovery buttons). */ + errorCode?: string; + /** The engine's own text of the error, kept behind Details. */ + errorDetail?: string; + tools?: ToolCall[]; +} + +export type ToolState = 'proposed' | 'approved' | 'running' | 'done' | 'denied' | 'error'; + +/** + * A tool call the model is still writing (a whole file in one call, say), as the host streams it: the name, the file it is for, a growing size + * and the tail of the text. It lives on the assistant message while the call is written and is removed when the call is complete (the + * ordinary tool card takes over) or the reply was cut and the call was lost (`lost`). + */ +export interface ToolDraft { + id: string; + name: string; + /** The file (or address) the call is for; empty until the model has written it. */ + target: string; + /** Characters of the call's arguments so far (a file's size, a little more because of escapes). */ + bytes: number; + /** Lines of text written so far. */ + lines: number; + /** The last part of the text being written, read back from its JSON form (at most 1,600 characters). */ + preview: string; + /** What the call is: 'write', 'edit', 'shell', ... (same as ToolCall.scope). */ + scope?: 'read' | 'write' | 'shell' | 'connected'; + /** The plain verb for the card while it is written ("Writing"). */ + verb?: string; +} + +export interface ToolCall { + id: string; + name: string; + args: Record<string, unknown>; + preview: string; + effect: string; + scope: 'read' | 'write' | 'shell' | 'connected'; + /** The card's headline in plain words for its current state ("Wrote a file"); the host sends it, the UI translates it. */ + verb?: string; + /** What the action is on: a file path, the command, a web address. */ + target?: string; + /** The question an approval card asks in plain words (server/agent/ask.mjs); the page translates it. */ + ask?: { id: string; params?: (string | number)[]; why?: string; detail?: string }; + state: ToolState; + result?: string; + durationMs?: number; + /** Reported by the agent runtime: an approval answers a real request. Absent for design-build examples. */ + live?: boolean; + /** The person approved this call. A finished card without it was never asked about. */ + approved?: boolean; +} + +/** A folder the model may read, and that sessions are grouped under. */ +export interface Workspace { + id: string; + name: string; + path: string; + /** Earlier folders whose chats belong here (the first workspace moved off the app's own folder). */ + aliases?: string[]; +} + +export interface SessionAgent { + id: string; + name: string; + description: string; + status: 'working' | 'completed' | 'failed' | 'queued' | 'cancelled'; + durationMs: number; + tokens: number; + /** Time the latest duration measurement was received. */ + updatedAt?: number; +} + +export type ChatMode = 'auto' | 'manual' | 'accept-edits' | 'plan' | 'bypass'; + +/** + * What the board needs to know about a /loop after the window closes: loops live in memory, so the chat keeps a small record of the + * last one (running, or how it ended). A record that says `running` with no loop behind it is a loop the window closed on. + */ +export interface LoopRecord { + prompt: string; + everyMs: number; + startedAt: number; + state: 'running' | 'ended'; + answers: number; + maxRuns?: number; + /** When the next answer is due (ms), while running. */ + nextAt?: number; + endedAt?: number; + /** count, said-done, time, failures, cap; `stopped` when the person typed /loop stop; `closed` when the window closed on it. */ + endedWhy?: 'count' | 'said-done' | 'time' | 'failures' | 'cap' | 'stopped' | 'closed'; + /** The last answer's first words, for the card. */ + lastText?: string; +} + +export interface Session { + /** The person dismissed this chat's (or its loop's) card on the board at this time. A later problem brings it back. */ + ackedAt?: string; + loop?: LoopRecord; + timeSkips?: import('./time-skip').TimeSkipRun[]; + showcase?: boolean; + agents?: SessionAgent[]; + previewOpen?: string; + closedPreviews?: string[]; + showcaseAgentStates?: boolean; + preferences?: { access?: 'read' | 'write' | 'full'; thinking?: string; thinkingBudget?: number; mode?: ChatMode; useTools?:boolean; /** false: plain conversation, no tools of any kind. */ agent?: boolean; /** This chat's API model; absent or null means the local model. */ remoteModel?: RemoteModelSelection | null }; + /** A branch does not have retained per-turn input usage. */ + statsAvailable?: boolean; + id: string; + title: string; + defaultTitle?: boolean; + updatedAt: string; + createdAt: string; + messages: ChatMessage[]; + workspace: string; + tokensIn: number; + tokensOut: number; + pinned?: boolean; + /** Put away without deleting. Archiving is for "done with this for now" — + * deleting is for "never want to see it again", and conflating the two makes + * people keep things they are finished with. */ + archived?: boolean; + /** When this conversation was last on screen. A session is unread when it has + * been updated since — which is the only way to tell, with more than a + * handful of conversations, which ones have something new in them. */ + lastReadAt?: string; +} + +export interface Skill { + id: string; + name: string; + description: string; + source: 'bundled' | 'workspace' | 'user'; + enabled: boolean; + triggers: string[]; + /** The instruction text itself — what the model is actually told. Deciding + * whether to trust a skill means reading this, not its name. */ + body?: string; + /** When set, the skill applies only in this workspace. A skill written for + * one project is noise in another, and on/off cannot express "here, not + * there". */ + onlyIn?: string | null; + /** How many times a prompt has actually triggered this skill, and when last. */ + useCount?: number; + lastUsedAt?: string | null; + sizeKb: number; +} + +export interface WorkspaceFile { + path: string; + kind: 'file' | 'dir'; + sizeKb?: number; + updatedAt?: string; +} + +export interface SetupState { + flowVersion?: number; + dismissed?: boolean; + choices?: { onboarding?: { step:number; family?:string; size?:string; context?:number; vision?:boolean; directory?:string; profile?:'work'|'performance'; installJobId?:string; tuneJobId?:string; calibrate?:boolean; manual?:boolean }; variantId?: string; contextLength?: BeginnerConfig["contextLength"]; profile?: import("./experience").Profile; batch?: number; batchAuto?: boolean }; + complete: boolean; + step: number; + completedAt?: string; + history: { step: number; at: string }[]; + app: { version: string; modelsDir: string; dataDir: string; modelsDirNotice?: string }; +} + +export interface EngineEvent { + type: 'engine' | 'monitor' | 'models' | 'serving' | 'download' | 'log'; + at: string; + payload: unknown; +} diff --git a/apps/host/tests/agent-lost.test.mjs b/apps/host/tests/agent-lost.test.mjs new file mode 100644 index 0000000000..628923fc36 --- /dev/null +++ b/apps/host/tests/agent-lost.test.mjs @@ -0,0 +1,185 @@ +// AGENT-LOST (11-01): a reply the length limit cut inside a tool call used to vanish: no file, no card, no sentence. +// Pure parts always run; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and use the scripted model server. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { replyCap, unescapeJsonTail, ToolDraft, cutCalls, cutNotice, cutNudge } from '../server/agent/reply-cut.mjs'; +import { TurnProjector } from '../server/agent/events.mjs'; +import { startScriptedWorker } from './helpers/scripted-worker.mjs'; +import { createAgentBridge, MAX_CUT_RETRIES } from '../server/agent/agent-bridge.mjs'; +import { resolveHarness } from '../server/agent/harness-runtime.mjs'; +import { localOutputBudget } from '../server/agent/profile.mjs'; + +const HARNESS = process.env.STRATA_HARNESS_DIR; +const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; + +test('the reply ceiling is half the window up to 64K tokens and never below what compaction reserves', () => { + assert.equal(replyCap(65536, localOutputBudget(65536)), 32768); + assert.ok(replyCap(65536, localOutputBudget(65536)) > localOutputBudget(65536), '19,660 was the cut that lost the pagoda'); + assert.equal(replyCap(131072, localOutputBudget(131072)), 65536); + assert.equal(replyCap(262144, localOutputBudget(262144)), 65536, 'at most 64K tokens, so a loop cannot run for an hour'); + assert.equal(replyCap(8192, localOutputBudget(8192)), 4096); + assert.equal(replyCap(0, 5000), 16384, 'no window known: 32K is assumed'); + assert.equal(replyCap(4096, 4096), 4096, 'never below the reserve'); +}); + +test('JSON text is read back for the preview, and a half-written escape is dropped', () => { + assert.equal(unescapeJsonTail('a\\nb\\t\\"c\\"\\\\d'), 'a\nb\t"c"\\d'); + assert.equal(unescapeJsonTail('line\\'), 'line'); + assert.equal(unescapeJsonTail('x\\u00e9y'), 'xéy'); + assert.equal(unescapeJsonTail('x\\u00'), 'x'); +}); + +test('a call being written knows its file, its size, its lines and the tail of its text', () => { + const d = new ToolDraft('c1', 'write'); + for (const piece of ['{"file_pa', 'th":"C:\\\\work\\\\pagoda.html","con', 'tent":"<!doctype html>\\n<html>\\n']) d.add(piece); + assert.equal(d.target, 'C:\\work\\pagoda.html'); + assert.equal(d.lines, 2); + assert.equal(d.preview(), '<!doctype html>\n<html>\n'); + for (let i = 0; i < 400; i++) d.add(`<div class=\\"row${i}\\">text ${i}</div>\\n`); + assert.ok(d.bytes > 10_000); + assert.equal(d.lines, 402); + const p = d.preview(1000); + assert.ok(p.length <= 1000 && p.endsWith('</div>\n') && !p.includes('\\n') && p.includes('class="row'), 'the tail, read back, ends where the model is'); + const f = d.frame({ scope: 'write', verb: 'Writing' }); + assert.deepEqual(Object.keys(f.draft).sort(), ['bytes', 'done', 'id', 'lines', 'name', 'preview', 'scope', 'target', 'verb']); + assert.equal(d.frame({ done: true }).draft.preview, '', 'a finished draft carries no text'); +}); + +test('the file is found when the model writes its name after the text, or split between two pieces', () => { + const d = new ToolDraft('c2', 'write'); + d.add('{"content":"line one\nline two\n'); + assert.equal(d.target, ''); + d.add('more","file_pa'); d.add('th":"/w/big.txt"}'); + assert.equal(d.target, '/w/big.txt'); +}); + +test('the sentences name the file and the size, say what to do, and the nudge asks for smaller parts', () => { + const draft = new ToolDraft('a', 'write'); draft.add('{"file_path":"/w/pagoda.html","content":"'); draft.bytes = 52_300; + const calls = cutCalls([draft]); + assert.deepEqual(calls, [{ name: 'write', target: '/w/pagoda.html', bytes: 52_300 }]); + const again = cutNotice({ calls, tokens: 19660, retrying: true }); + assert.match(again.text, /reached its length limit \(19,660 tokens\) while writing pagoda\.html \(52 KB\), so nothing was saved\. I asked the assistant to write it again in smaller parts\./); + const last = cutNotice({ calls, tokens: 19660 }); + assert.match(last.text, /Say “continue”/); + assert.match(cutNotice({ tokens: 500 }).text, /^The reply reached its length limit \(500 tokens\) and was cut off\. Say “continue”/); + assert.match(cutNudge({ calls, tokens: 19660 }), /writing \/w\/pagoda\.html in one tool call, so nothing was saved[\s\S]*smaller parts/); + assert.match(cutNudge({}), /cut off by the output limit/); + for (const n of [again, last]) assert.equal(n.text, n.key.replace(/\{(\d)\}/g, (_, i) => n.values[i]), 'the key and its values make the sentence'); +}); + +// ------------------------------------------------------------------------------------------------ the projector + +const chunk = (c, attemptId = 'a1') => ({ type: 'assistant-stream', frame: { type: 'chunk', attemptId, chunk: c } }); +const event = (type, data = {}) => ({ type: 'event', event: { type, time: Date.now(), data } }); + +test('the projector streams a growing draft frame for a call being written, and the whole call ends it', () => { + const p = new TurnProjector(); + const frames = []; + const head = '{"file_path":"big.txt","content":"'; + frames.push(...p.consume(chunk({ type: 'tool-call-delta', id: 'c1', name: 'write', argumentsDelta: head }))); + assert.equal(frames.filter(f => f.type === 'agent-tool-draft').length, 1, 'the first piece shows at once'); + const first = frames.find(f => f.type === 'agent-tool-draft').draft; + assert.equal(first.name, 'write'); assert.equal(first.target, 'big.txt'); assert.equal(first.scope, 'write'); assert.equal(first.verb, 'Writing a file'); + // A burst inside 200 ms sends no more frames, but the next one after the pause carries everything so far. + for (let i = 0; i < 20; i++) p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: `entry ${i}\\n` })); + assert.equal(p.composing.get('c1').lines, 20); + p.composing.get('c1').at = 0; + const later = p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: 'entry 20\\n' })).find(f => f.type === 'agent-tool-draft').draft; + assert.equal(later.lines, 21); assert.match(later.preview, /entry 20\n$/); + const out = p.consume(event('tool/call', { callId: 'c1', name: 'write', arguments: '{"file_path":"big.txt","content":"x"}' })); + assert.ok(out.some(f => f.type === 'agent-tool'), 'the ordinary card takes over'); + assert.equal(out.find(f => f.type === 'agent-tool-draft')?.draft.done, true, 'and the draft is closed'); + assert.equal(p.composing.size, 0); +}); + +test('a reply cut in a call: the done frame says length and what was lost, and the draft is taken down', () => { + const p = new TurnProjector(); + p.consume(chunk({ type: 'tool-call-delta', id: 'c9', name: 'write', argumentsDelta: '{"file_path":"/w/pagoda.html","content":"abc' })); + p.consume(chunk({ type: 'usage', usage: { inputTokens: 6000, outputTokens: 19660 } })); + p.consume(event('turn/end', { reason: { kind: 'max-tokens' } })); + assert.deepEqual(p.cut(), { tokens: 19660, calls: [{ name: 'write', target: '/w/pagoda.html', bytes: p.composing.get('c9').bytes }] }); + const frames = p.finish({ model: 'm', contextMax: 65536 }); + const drop = frames.find(f => f.type === 'agent-tool-draft'); + assert.ok(drop && drop.draft.done && drop.draft.lost, 'the writing card goes away'); + const done = frames.at(-1); + assert.equal(done.type, 'done'); assert.equal(done.finishReason, 'length'); + assert.equal(done.cut.tokens, 19660); assert.equal(done.cut.calls[0].target, '/w/pagoda.html'); +}); + +test('a call nobody writes a card for (a helper agent) makes no draft', () => { + const p = new TurnProjector(); + const out = p.consume(chunk({ type: 'tool-call-delta', id: 's1', name: 'subagent', argumentsDelta: '{"prompt":"x' })); + assert.equal(out.filter(f => f.type === 'agent-tool-draft').length, 0); +}); + +// ------------------------------------------------------------------------------------------------ with the real Harness + +async function rig(t, { window = 65536 } = {}) { + const worker = await startScriptedWorker({ chunkDelayMs: 5 }); + const dir = mkdtempSync(join(tmpdir(), 'strata-lost-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const logs = []; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: window, slots: 2 }], connections: () => [], + env: process.env, startTimeoutMs: 90_000, log: l => logs.push(l) }); + t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } }); + return { worker, bridge, ws, logs, base: (chatId, onFrame) => ({ chatId, workspacePath: ws, mode: 'bypass', thinking: 'Off', onFrame }) }; +} +const words = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join(''); +const capOf = q => q.params.max_tokens ?? q.params.max_completion_tokens; +const writes = r => r.worker.requests.filter(q => q.directive === 'cutwrite' || q.directive === 'cutalways'); + +test('every model request may produce half the window, not the 30 percent the Harness reserves for compaction', { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.runTurn({ ...r.base('c0', f => out.push(f)), message: 'SCRIPT:echo hello' }); + const asked = r.worker.requests.find(q => q.directive === 'echo'); + assert.ok(asked, 'the model was asked'); + assert.equal(capOf(asked), 32768, `the request carried ${capOf(asked)}; the pagoda's carried 19660`); +}); + +test('a small window still gets a request that fits it (the Harness clamps to the room left)', { skip }, async (t) => { + const r = await rig(t, { window: 8192 }); + await r.bridge.runTurn({ ...r.base('c0s', () => {}), message: 'SCRIPT:echo hello' }); + const asked = r.worker.requests.find(q => q.directive === 'echo'); + assert.ok(capOf(asked) > 0 && capOf(asked) <= 4096, `max_tokens ${capOf(asked)} for an 8K window`); +}); + +test('a reply cut inside a file write: the chat says so, the agent is asked to go on in smaller parts, and the file gets written', { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:cutwrite big.txt' }); + const said = out.find(f => f.type === 'delta' && f.noteReason === 'cut'); + assert.ok(said, 'a sentence about the cut'); + assert.match(said.text, /while writing big\.txt/); assert.match(said.text, /I asked the assistant to write it again in smaller parts/); + assert.equal(out.filter(f => f.type === 'error').length, 0); + const done = out.filter(f => f.type === 'done').at(-1); + assert.equal(done.finishReason, 'stop', 'the turn ends on the agent\'s own finish, not on the cut'); + assert.ok(existsSync(join(r.ws, 'big.txt')), 'the file is on disk'); + assert.match(readFileSync(join(r.ws, 'big.txt'), 'utf8'), /entry 0001/); + assert.match(words(out), /Written in parts/); + assert.equal(writes(r).length, 3, 'the cut reply, the nudged write, the closing words'); + assert.ok(writes(r)[1].raw.includes('cut off by the output limit'), 'the second request carries the nudge'); + const drafts = out.filter(f => f.type === 'agent-tool-draft'); + assert.ok(drafts.length >= 2, 'the writing was shown live'); + assert.ok(drafts.some(f => !f.draft.done && f.draft.name === 'write'), 'a writing card opened as soon as the model named the call'); + // The Harness hands the streamed pieces over in batches (a few a second at most), so a short script may show only the first and the last. + assert.ok(drafts.some(f => f.draft.done && f.draft.lost && f.draft.target === 'big.txt' && f.draft.bytes > 1000), 'and taken down, with its file and size, when it was lost'); +}); + +test(`a model that is cut every time is asked ${MAX_CUT_RETRIES} times, then the turn ends with a plain sentence, never silently`, { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.runTurn({ ...r.base('c2', f => out.push(f)), message: 'SCRIPT:cutalways big.txt' }); + assert.equal(writes(r).length, MAX_CUT_RETRIES + 1); + const notes = out.filter(f => f.type === 'delta' && f.noteReason === 'cut'); + assert.equal(notes.length, MAX_CUT_RETRIES + 1, 'one sentence per cut'); + assert.match(notes.at(-1).text, /nothing was saved\. Say “continue”/); + const done = out.filter(f => f.type === 'done').at(-1); + assert.ok(done, 'the turn ended'); + assert.equal(done.finishReason, 'length'); + assert.equal(done.cut.calls[0].target, 'big.txt'); + assert.equal(existsSync(join(r.ws, 'big.txt')), false, 'nothing half-written is left behind'); +}); diff --git a/apps/host/tests/agent-tools.test.mjs b/apps/host/tests/agent-tools.test.mjs index 63aef01b4d..67c4ab8139 100644 --- a/apps/host/tests/agent-tools.test.mjs +++ b/apps/host/tests/agent-tools.test.mjs @@ -1,286 +1,287 @@ -/** - * The agent's tools in the app: the inventory, a tool from each family, and Manual mode's one approval card. - * - * Pure tests (the gate's rules, the preset list, the profile) always run. The rest need a built Harness - * (STRATA_HARNESS_DIR) and skip loudly without it. The model is scripted (tests/helpers/scripted-worker.mjs): what is real is - * the Harness, its tool executor, its sandbox, its approval service, the Strata gate plugin and the bridge. - */ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { startScriptedWorker } from './helpers/scripted-worker.mjs'; -import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; -import { resolveHarness } from '../server/agent/harness-runtime.mjs'; -import { buildProfile, GATE_PLUGIN } from '../server/agent/profile.mjs'; -import { STANDARD_PLUGIN_IDS, REMOVED_PLUGIN_IDS, standardPreset } from '../server/agent/preset.mjs'; -import { isReadOnlyShell, manualDecision, maskQuotes, READ_ONLY_TOOLS } from '../server/agent/plugins/strata-gate.mjs'; -import { plainToolError, withPlain } from '../server/agent/events.mjs'; - -const HARNESS = process.env.STRATA_HARNESS_DIR; -const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; -const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } }; -const fwd = p => p.replaceAll('\\', '/'); - -// ---------------------------------------------------------------------------------------------------------- pure - -test('the gate: only commands that provably just look are allowed without a question', () => { - for (const ok of ['Get-ChildItem', 'Get-ChildItem -Recurse src | Select-Object -First 5', 'git status', 'git log --oneline -5', 'git diff', 'cat notes.txt', 'ls -la', 'node --version', 'Get-Content a.txt | Select-String needle', 'git branch', 'git remote -v']) { - assert.equal(isReadOnlyShell(ok), true, ok); - } - for (const bad of ['', 'Set-Content a.txt x', 'echo hi > a.txt', 'Get-ChildItem; Remove-Item a.txt', 'rm -rf x', 'git commit -m x', 'git push', 'git branch -D x', 'git config user.name x', 'git remote add o u', 'curl http://x', 'Get-ChildItem | ForEach-Object { $_ }', 'Start-Process explorer.exe', 'explorer.exe C:/Users/x/Downloads', 'ii ~/Downloads', 'Invoke-Item $env:USERPROFILE/Downloads', 'start .', 'open .', 'xdg-open .', 'notepad a.txt', 'powershell -Command x', 'node script.js', 'python x.py', 'ls && rm a', 'find . -delete', 'echo $(whoami)', 'Invoke-WebRequest u', 'Start-Process x', 'New-Item a', 'cat a | tee b']) { - assert.equal(isReadOnlyShell(bad), false, bad); - } - assert.equal(isReadOnlyShell('x'.repeat(700)), false, 'a long command is never trusted'); -}); - -test('the gate: quoted text is data, so an & ( ) ; { } in a quoted path does not make a look-only command ask (2026-10-22)', () => { - for (const ok of [ - 'Get-ChildItem "C:\\Users\\AI-Server\\Downloads\\GUI Q&A" | Select-Object -First 5 Name', - 'Get-Content "C:\\Users\\AI-Server\\Downloads\\GUI Q&A\\a.txt"', - "Get-ChildItem 'C:\\Users\\x\\Notes (old) {draft}; v2'", - 'Select-String -Path a.txt "a|b"', - 'Select-String needle "C:\\x\\a & b.txt" | Measure-Object', - 'git log --oneline "docs/Q&A.md"', - 'cat "my file (1).txt"', - "Get-ChildItem 'it''s here'", - ]) assert.equal(isReadOnlyShell(ok), true, ok); - // Quoting does not hide anything that acts: outside the quotes the same characters still ask, and inside double quotes an expansion does. - for (const bad of [ - 'Get-ChildItem C:\\Q&A', - 'Get-ChildItem "C:\\a" ; Remove-Item x', - 'Get-ChildItem "C:\\a" & calc', - 'Get-ChildItem "C:\\a" > out.txt', - 'Get-ChildItem "$env:USERPROFILE"', - 'Get-ChildItem "$(whoami)"', - 'Get-ChildItem "a`b"', - "Get-ChildItem 'unterminated", - 'Get-ChildItem "unterminated', - 'git diff "--output=out.txt"', - 'git diff --out"put"=out.txt', - 'git diff --"output"=out.txt', - 'Get-Content "a"b', - '"Remove-Item" x', - 'Set-Content "a.txt" "x"', - 'Get-ChildItem "a" | Remove-Item', - 'curl "http://x"', - ]) assert.equal(isReadOnlyShell(bad), false, bad); - assert.equal(maskQuotes('Get-ChildItem "C:\\Q&A" | Select-Object Name'), 'Get-ChildItem "_" | Select-Object Name'); - assert.equal(maskQuotes("echo 'a' \"b\""), 'echo "_" "_"'); - assert.equal(maskQuotes('echo "$HOME"'), null); -}); - -test('the gate: every tool outside the read-only list asks, including unknown and connected ones', () => { - for (const name of READ_ONLY_TOOLS) assert.equal(manualDecision({ name, arguments: {} }), null, name); - for (const name of ['write', 'edit', 'job_kill', 'mcp__github__create_issue', 'something_new']) assert.equal(manualDecision({ name, arguments: {} })?.kind, 'ask', name); - assert.equal(manualDecision({ name: 'pwsh', arguments: { command: 'Get-ChildItem' } }), null); - assert.match(manualDecision({ name: 'pwsh', arguments: { command: 'Remove-Item x', description: 'Delete x' } }).reason, /Delete x/); - assert.match(manualDecision({ name: 'write', arguments: { file_path: 'C:/a/b.txt' } }).reason, /b\.txt/); - assert.equal(manualDecision({ name: 'pwsh', arguments: {} }).kind, 'ask', 'no command is not a read-only command'); -}); - -test('the preset: our list is the Harness standard list minus exactly what the app replaces', () => { - const ids = standardPreset({ platform: 'win32' }).plugins.map(p => p.id); - assert.deepEqual(ids, STANDARD_PLUGIN_IDS.filter(id => !REMOVED_PLUGIN_IDS.includes(id) && id !== 'tool-bash')); - assert.ok(standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-bash') && !standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-pwsh')); - const web = standardPreset().plugins.find(p => p.id === 'tool-web').config; - assert.equal(web.fetch, true); assert.equal(web.search, false, 'the preset alone leaves search to the profile, which switches it on (DuckDuckGo needs no key)'); - assert.equal(standardPreset({ search: true }).plugins.find(p => p.id === 'tool-web').config.search, true); - assert.ok(!ids.includes('tool-schedule'), 'Tasks is the only scheduler'); -}); - -test('the profile loads the gate by path, sizes helper agents to the engine slots and keeps no secret', () => { - const p = buildProfile({ local: [{ id: 'a', baseUrl: 'http://127.0.0.1:1/v1', modelId: 'm', context: 32768, slots: 2, key: 'sekret-key-123' }] }); - const entries = JSON.parse(p.patch.split('\n').slice(1).join('\n')); - assert.deepEqual(entries.find(e => e.insert)?.insert, [{ id: 'strata-gate', name: GATE_PLUGIN, config: { web: { provider: 'DuckDuckGo, or Bing when DuckDuckGo is busy', skipAsk: false } } }]); - assert.ok(existsSync(GATE_PLUGIN)); - assert.equal(entries.find(e => e.id === 'subagent').config.maxActiveSubagents, 4, 'at least the 4 helpers; more only with more slots'); - assert.equal(entries.find(e => e.id === 'preset-standard').config.plugins.some(x => x.id === 'tool-schedule'), false); - assert.ok(!p.patch.includes('sekret-key-123')); - const api = buildProfile({ local: [], connections: [{ id: 'c1', name: 'C', baseUrl: 'https://x/v1', protocol: 'openai-chat', models: [{ id: 'm' }] }] }); - assert.equal(JSON.parse(api.patch.split('\n').slice(1).join('\n')).find(e => e.id === 'subagent').config.maxActiveSubagents, 8, 'API models take the Harness limit'); -}); - -test('tool failures are said in plain words with the original text kept after them', () => { - assert.match(plainToolError('Error: URL hostname "127.0.0.1" resolves to a non-public IP address'), /web page could not be opened/); - assert.match(plainToolError('Error: invalid arguments: missing required property "files"'), /wrong way/); - assert.equal(plainToolError('something unusual'), null); - const text = withPlain('Error: web fetch failed: Error: getaddrinfo ENOTFOUND example.invalid'); - assert.match(text, /^That web page could not be opened/); - assert.match(text, /Details: web fetch failed/); -}); - -// ------------------------------------------------------------------------------------------------- real Harness - -async function rig(t) { - const worker = await startScriptedWorker({}); - const dir = mkdtempSync(join(tmpdir(), 'strata-tools-')); - const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); - const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 4 }]; - const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); - t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); - const run = async (chatId, message, { mode = 'bypass', answer } = {}) => { - const frames = []; - await bridge.runTurn({ - chatId, message, workspacePath: ws, mode, - onFrame: f => { - frames.push(f); - if (answer && f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId, callId: f.tool.id, decision: answer }).catch(e => frames.push({ type: 'test-error', message: e.message })); - }, - }); - return frames; - }; - const call = (chatId, tool, args, options) => run(chatId, `SCRIPT:call ${tool} ${JSON.stringify(args)}`, options); - return { worker, bridge, dir, ws, run, call }; -} -const cards = frames => frames.filter(f => f.type === 'agent-tool').map(f => f.tool); -const last = frames => cards(frames).at(-1); - -test('the agent is offered exactly these tools: everything useful including web search (no key needed), no scheduler, and the question tool the app can answer', { skip }, async (t) => { - const r = await rig(t); - await r.run('inv', 'SCRIPT:echo hi'); - const offered = [...r.worker.requests].reverse().find(q => q.toolNames.length)?.toolNames.sort(); - assert.deepEqual(offered, ['ask_user_question', 'create_goal', 'edit', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'present', 'pwsh', 'read', 'read_image', 'send_message', 'skill', 'subagent', 'subagent_fork', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'working_directory', 'write'].sort()); - assert.ok(!offered.some(n => n.startsWith('schedule_')) && offered.includes('web_search') && offered.includes('ask_user_question') && !offered.includes('exit_plan_mode')); -}); - -test('a tool from each family runs and shows a card the page can render', { skip }, async (t) => { - const r = await rig(t); - const file = join(r.ws, 'notes.txt'); - writeFileSync(file, 'alpha\nneedle here\nomega\n'); - const f = fwd(file); - // read-only family - assert.match(last(await r.call('fam-r', 'read', { file_path: f })).result, /needle here/); - assert.match(last(await r.call('fam-g', 'glob', { pattern: '*.txt' })).result, /notes\.txt/); - assert.match(last(await r.call('fam-s', 'grep', { pattern: 'needle' })).result, /Line 2/); - assert.equal(last(await r.call('fam-w', 'working_directory', {})).state, 'done'); - assert.equal(last(await r.call('fam-j', 'job_list', {})).state, 'done'); - // plan / list family - assert.equal(last(await r.call('fam-t', 'todo_write', { todos: [{ content: 'check the build', status: 'pending' }] })).state, 'done'); - const goal = last(await r.call('fam-goal', 'create_goal', { objective: 'finish the notes' })); - assert.equal(goal.state, 'done'); assert.equal(goal.effect, 'Sets a goal to work towards.'); - // write family (Bypass: no card asks) - const wrote = await r.call('fam-fs', 'write', { file_path: fwd(join(r.ws, 'new.txt')), content: 'made\n' }); - assert.equal(last(wrote).state, 'done'); assert.equal(readFileSync(join(r.ws, 'new.txt'), 'utf8').trim(), 'made'); - await r.call('fam-fs', 'read', { file_path: f }); - const edited = await r.call('fam-fs', 'edit', { file_path: f, old_string: 'alpha', new_string: 'ALPHA' }); - assert.equal(last(edited).state, 'done'); assert.match(readFileSync(file, 'utf8'), /^ALPHA/); - // shell family - assert.match(last(await r.call('fam-sh', 'pwsh', { command: 'Get-ChildItem', description: 'list files' })).result, /notes\.txt/); - // web family: offline, loopback is refused by the Harness itself; the failure is plain with Details after it - const web = last(await r.call('fam-web', 'web_fetch', { url: 'http://127.0.0.1:9/' })); - assert.equal(web.state, 'error'); assert.match(web.result, /^That web page could not be opened/); assert.match(web.result, /Details: /); - assert.equal(web.effect, 'Opens a web page.'); assert.equal(web.preview, 'http://127.0.0.1:9/'); - // no card shows raw JSON as its explanation - for (const c of [last(await r.call('fam-t2', 'todo_write', { todos: [{ content: 'x', status: 'pending' }] }))]) assert.ok(!c.preview.startsWith('{')); -}); - -test('Manual: one change is one card. Nothing ran when it appeared, and no sandbox or PowerShell error was ever shown', { skip }, async (t) => { - const r = await rig(t); - const a = join(r.ws, 'a.txt'), b = join(r.ws, 'b.txt'), c = join(r.ws, 'c.txt'); - // approve a file write - let frames = await r.call('man1', 'write', { file_path: fwd(a), content: 'hello\n' }, { mode: 'manual', answer: 'approve' }); - assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']); - assert.equal(new Set(cards(frames).map(x => x.id)).size, 1, 'one card, updated in place'); - assert.equal(readFileSync(a, 'utf8').trim(), 'hello'); - // deny a file write - frames = await r.call('man2', 'write', { file_path: fwd(b), content: 'no\n' }, { mode: 'manual', answer: 'deny' }); - assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'denied', 'denied']); - assert.equal(last(frames).result, 'Denied. Nothing ran.', 'the card says it in plain words, not the model-facing error'); - assert.equal(existsSync(b), false); - // a shell command that changes things - frames = await r.call('man3', 'pwsh', { command: `Set-Content -Path '${c}' -Value x`, description: 'Make c.txt' }, { mode: 'manual', answer: 'approve' }); - assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']); - assert.ok(existsSync(c)); - // a shell command that only looks needs no question - frames = await r.call('man4', 'pwsh', { command: 'Get-ChildItem', description: 'List files' }, { mode: 'manual' }); - assert.deepEqual(cards(frames).map(x => x.state), ['running', 'done']); - // nowhere in any of it does the person see the sandbox talking - const all = JSON.stringify([...cards(frames), ...cards(await r.call('man5', 'write', { file_path: fwd(join(r.ws, 'd.txt')), content: 'd' }, { mode: 'manual', answer: 'approve' }))]); - assert.ok(!/sandbox|Constrained|language mode|access denied/i.test(all), all.slice(0, 300)); -}); - -test('Plan stays read-only and Bypass asks nothing', { skip }, async (t) => { - const r = await rig(t); - const p = join(r.ws, 'p.txt'), q = join(r.ws, 'q.txt'); - const planned = await r.call('pl', 'write', { file_path: fwd(p), content: 'x' }, { mode: 'plan' }); - assert.equal(existsSync(p), false); - assert.ok(!cards(planned).some(x => x.state === 'proposed')); - const free = await r.call('bp', 'write', { file_path: fwd(q), content: 'x' }, { mode: 'bypass' }); - assert.equal(existsSync(q), true); - assert.ok(!cards(free).some(x => x.state === 'proposed')); -}); - -test('Manual refuses to start when the gate is not loaded (it would be an open sandbox that nobody asks about)', { skip }, async (t) => { - // A Harness started without the gate plugin (the bridge's `gate: false`). - const worker = await startScriptedWorker({}); - const dir = mkdtempSync(join(tmpdir(), 'strata-nogate-')); - mkdirSync(join(dir, 'ws'), { recursive: true }); - const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }]; - const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, gate: false, startTimeoutMs: 90_000 }); - t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); - await assert.rejects(bridge.runTurn({ chatId: 'x', message: 'SCRIPT:echo hi', workspacePath: join(dir, 'ws'), mode: 'manual', onFrame: () => {} }), error => error.code === 'mode-unavailable' && /asks before changing/.test(error.message) && !/sandbox/i.test(error.message)); -}); - -test('a tool server set up for the model is connected to the agent: its tools are offered, Manual asks before using them, and its secret never reaches a file', { skip }, async (t) => { - const worker = await startScriptedWorker({}); - const dir = mkdtempSync(join(tmpdir(), 'strata-mcp-')); - const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); - const mcpServers = { demo: { command: process.execPath, args: [fwd(join(import.meta.dirname, 'helpers', 'mini-mcp.mjs'))], env: { DEMO_TOKEN: 'tok-123456-secret' } }, off: { command: 'x', disabled: true } }; - const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2, mcpServers }]; - const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); - t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); - const frames = []; - await bridge.runTurn({ chatId: 'mcp-bypass', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'hello' })}`, workspacePath: ws, mode: 'bypass', onFrame: f => frames.push(f) }); - assert.ok([...worker.requests].reverse().find(q => q.toolNames.length).toolNames.includes('mcp__demo__shout')); - assert.ok(![...worker.requests].some(q => q.toolNames.some(n => n.startsWith('mcp__off'))), 'a disabled server is not connected'); - const card = cards(frames).at(-1); - assert.equal(card.state, 'done'); assert.match(card.result, /HELLO\|token:set/, 'the secret reached the server through the environment'); - assert.equal(card.scope, 'connected'); - // Manual: a connected tool has unknown effects, so it asks first - const manual = []; - await bridge.runTurn({ - chatId: 'mcp-manual', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'ask me' })}`, workspacePath: ws, mode: 'manual', - onFrame: f => { manual.push(f); if (f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId: 'mcp-manual', callId: f.tool.id, decision: 'approve' }); }, - }); - assert.deepEqual(cards(manual).map(c => c.state), ['running', 'proposed', 'running', 'done']); - assert.match(cards(manual)[1].effect, /Use the connected tool demo \/ shout/); - // the secret is in the environment of the agent only: never in the profile file - const files = JSON.stringify(readdirDeep(join(dir, 'agent')).filter(f => f.endsWith('.yml')).map(f => readFileSync(f, 'utf8'))); - assert.ok(files.includes('process.env.STRATA_MCP_0_E_DEMO_TOKEN') && !files.includes('tok-123456-secret')); -}); - -function readdirDeep(dir) { - const out = []; - for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) out.push(...readdirDeep(p)); else out.push(p); } - return out; -} - -test('the output budget is not the old 8192, and the Reasoning menu reaches the request (off sends enable_thinking false)', { skip }, async (t) => { - const worker = await startScriptedWorker({}); - const dir = mkdtempSync(join(tmpdir(), 'strata-think-')); - const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); - const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 65536 }]; - const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); - t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); - const ask = async (chatId, thinking) => { - worker.requests.length = 0; - await bridge.runTurn({ chatId, message: 'SCRIPT:echo hi', workspacePath: ws, mode: 'bypass', thinking, onFrame: () => {} }); - return worker.requests.find(r => r.toolNames.length).params; - }; - const ctk = p => p.chat_template_kwargs ?? {}; - const off = await ask('think-off', 'Off'); - assert.equal(ctk(off).enable_thinking, false); assert.equal(ctk(off).reasoning_effort, undefined); - assert.equal(off.enable_thinking, undefined, 'a top-level enable_thinking is the field the Strata server ignores'); - assert.ok(off.max_completion_tokens === 19660, `budget ${off.max_completion_tokens} (half the window, at most 32K: never the old 8192, and room is left for the conversation to be compacted)`); - const high = await ask('think-high', 'High'); - assert.equal(ctk(high).enable_thinking, true); assert.equal(ctk(high).reasoning_effort, 'high'); - const low = await ask('think-low', 'Low'); - assert.equal(ctk(low).enable_thinking, true); assert.equal(ctk(low).reasoning_effort, 'low'); - const max = await ask('think-max', 'Max'); - assert.equal(ctk(max).enable_thinking, true); assert.equal(ctk(max).reasoning_effort, 'high'); - // the same chat switching its level between turns - assert.equal(ctk(await ask('think-off', 'High')).enable_thinking, true); - assert.equal(ctk(await ask('think-off', 'Off')).enable_thinking, false); -}); +/** + * The agent's tools in the app: the inventory, a tool from each family, and Manual mode's one approval card. + * + * Pure tests (the gate's rules, the preset list, the profile) always run. The rest need a built Harness + * (STRATA_HARNESS_DIR) and skip loudly without it. The model is scripted (tests/helpers/scripted-worker.mjs): what is real is + * the Harness, its tool executor, its sandbox, its approval service, the Strata gate plugin and the bridge. + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { startScriptedWorker } from './helpers/scripted-worker.mjs'; +import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; +import { resolveHarness } from '../server/agent/harness-runtime.mjs'; +import { buildProfile, GATE_PLUGIN } from '../server/agent/profile.mjs'; +import { STANDARD_PLUGIN_IDS, REMOVED_PLUGIN_IDS, standardPreset } from '../server/agent/preset.mjs'; +import { isReadOnlyShell, manualDecision, maskQuotes, READ_ONLY_TOOLS } from '../server/agent/plugins/strata-gate.mjs'; +import { plainToolError, withPlain } from '../server/agent/events.mjs'; + +const HARNESS = process.env.STRATA_HARNESS_DIR; +const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; +const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } }; +const fwd = p => p.replaceAll('\\', '/'); + +// ---------------------------------------------------------------------------------------------------------- pure + +test('the gate: only commands that provably just look are allowed without a question', () => { + for (const ok of ['Get-ChildItem', 'Get-ChildItem -Recurse src | Select-Object -First 5', 'git status', 'git log --oneline -5', 'git diff', 'cat notes.txt', 'ls -la', 'node --version', 'Get-Content a.txt | Select-String needle', 'git branch', 'git remote -v']) { + assert.equal(isReadOnlyShell(ok), true, ok); + } + for (const bad of ['', 'Set-Content a.txt x', 'echo hi > a.txt', 'Get-ChildItem; Remove-Item a.txt', 'rm -rf x', 'git commit -m x', 'git push', 'git branch -D x', 'git config user.name x', 'git remote add o u', 'curl http://x', 'Get-ChildItem | ForEach-Object { $_ }', 'Start-Process explorer.exe', 'explorer.exe C:/Users/x/Downloads', 'ii ~/Downloads', 'Invoke-Item $env:USERPROFILE/Downloads', 'start .', 'open .', 'xdg-open .', 'notepad a.txt', 'powershell -Command x', 'node script.js', 'python x.py', 'ls && rm a', 'find . -delete', 'echo $(whoami)', 'Invoke-WebRequest u', 'Start-Process x', 'New-Item a', 'cat a | tee b']) { + assert.equal(isReadOnlyShell(bad), false, bad); + } + assert.equal(isReadOnlyShell('x'.repeat(700)), false, 'a long command is never trusted'); +}); + +test('the gate: quoted text is data, so an & ( ) ; { } in a quoted path does not make a look-only command ask (2026-10-22)', () => { + for (const ok of [ + 'Get-ChildItem "C:\\Users\\AI-Server\\Downloads\\GUI Q&A" | Select-Object -First 5 Name', + 'Get-Content "C:\\Users\\AI-Server\\Downloads\\GUI Q&A\\a.txt"', + "Get-ChildItem 'C:\\Users\\x\\Notes (old) {draft}; v2'", + 'Select-String -Path a.txt "a|b"', + 'Select-String needle "C:\\x\\a & b.txt" | Measure-Object', + 'git log --oneline "docs/Q&A.md"', + 'cat "my file (1).txt"', + "Get-ChildItem 'it''s here'", + ]) assert.equal(isReadOnlyShell(ok), true, ok); + // Quoting does not hide anything that acts: outside the quotes the same characters still ask, and inside double quotes an expansion does. + for (const bad of [ + 'Get-ChildItem C:\\Q&A', + 'Get-ChildItem "C:\\a" ; Remove-Item x', + 'Get-ChildItem "C:\\a" & calc', + 'Get-ChildItem "C:\\a" > out.txt', + 'Get-ChildItem "$env:USERPROFILE"', + 'Get-ChildItem "$(whoami)"', + 'Get-ChildItem "a`b"', + "Get-ChildItem 'unterminated", + 'Get-ChildItem "unterminated', + 'git diff "--output=out.txt"', + 'git diff --out"put"=out.txt', + 'git diff --"output"=out.txt', + 'Get-Content "a"b', + '"Remove-Item" x', + 'Set-Content "a.txt" "x"', + 'Get-ChildItem "a" | Remove-Item', + 'curl "http://x"', + ]) assert.equal(isReadOnlyShell(bad), false, bad); + assert.equal(maskQuotes('Get-ChildItem "C:\\Q&A" | Select-Object Name'), 'Get-ChildItem "_" | Select-Object Name'); + assert.equal(maskQuotes("echo 'a' \"b\""), 'echo "_" "_"'); + assert.equal(maskQuotes('echo "$HOME"'), null); +}); + +test('the gate: every tool outside the read-only list asks, including unknown and connected ones', () => { + for (const name of READ_ONLY_TOOLS) assert.equal(manualDecision({ name, arguments: {} }), null, name); + for (const name of ['write', 'edit', 'job_kill', 'mcp__github__create_issue', 'something_new']) assert.equal(manualDecision({ name, arguments: {} })?.kind, 'ask', name); + assert.equal(manualDecision({ name: 'pwsh', arguments: { command: 'Get-ChildItem' } }), null); + assert.match(manualDecision({ name: 'pwsh', arguments: { command: 'Remove-Item x', description: 'Delete x' } }).reason, /Delete x/); + assert.match(manualDecision({ name: 'write', arguments: { file_path: 'C:/a/b.txt' } }).reason, /b\.txt/); + assert.equal(manualDecision({ name: 'pwsh', arguments: {} }).kind, 'ask', 'no command is not a read-only command'); +}); + +test('the preset: our list is the Harness standard list minus exactly what the app replaces', () => { + const ids = standardPreset({ platform: 'win32' }).plugins.map(p => p.id); + assert.deepEqual(ids, STANDARD_PLUGIN_IDS.filter(id => !REMOVED_PLUGIN_IDS.includes(id) && id !== 'tool-bash')); + assert.ok(standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-bash') && !standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-pwsh')); + const web = standardPreset().plugins.find(p => p.id === 'tool-web').config; + assert.equal(web.fetch, true); assert.equal(web.search, false, 'the preset alone leaves search to the profile, which switches it on (DuckDuckGo needs no key)'); + assert.equal(standardPreset({ search: true }).plugins.find(p => p.id === 'tool-web').config.search, true); + assert.ok(!ids.includes('tool-schedule'), 'Tasks is the only scheduler'); +}); + +test('the profile loads the gate by path, sizes helper agents to the engine slots and keeps no secret', () => { + const p = buildProfile({ local: [{ id: 'a', baseUrl: 'http://127.0.0.1:1/v1', modelId: 'm', context: 32768, slots: 2, key: 'sekret-key-123' }] }); + const entries = JSON.parse(p.patch.split('\n').slice(1).join('\n')); + assert.deepEqual(entries.find(e => e.insert)?.insert, [{ id: 'strata-gate', name: GATE_PLUGIN, config: { web: { provider: 'DuckDuckGo, or Bing when DuckDuckGo is busy', skipAsk: false } } }]); + assert.ok(existsSync(GATE_PLUGIN)); + assert.equal(entries.find(e => e.id === 'subagent').config.maxActiveSubagents, 4, 'at least the 4 helpers; more only with more slots'); + assert.equal(entries.find(e => e.id === 'preset-standard').config.plugins.some(x => x.id === 'tool-schedule'), false); + assert.ok(!p.patch.includes('sekret-key-123')); + const api = buildProfile({ local: [], connections: [{ id: 'c1', name: 'C', baseUrl: 'https://x/v1', protocol: 'openai-chat', models: [{ id: 'm' }] }] }); + assert.equal(JSON.parse(api.patch.split('\n').slice(1).join('\n')).find(e => e.id === 'subagent').config.maxActiveSubagents, 8, 'API models take the Harness limit'); +}); + +test('tool failures are said in plain words with the original text kept after them', () => { + assert.match(plainToolError('Error: URL hostname "127.0.0.1" resolves to a non-public IP address'), /web page could not be opened/); + assert.match(plainToolError('Error: invalid arguments: missing required property "files"'), /wrong way/); + assert.equal(plainToolError('something unusual'), null); + const text = withPlain('Error: web fetch failed: Error: getaddrinfo ENOTFOUND example.invalid'); + assert.match(text, /^That web page could not be opened/); + assert.match(text, /Details: web fetch failed/); +}); + +// ------------------------------------------------------------------------------------------------- real Harness + +async function rig(t) { + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-tools-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 4 }]; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); + const run = async (chatId, message, { mode = 'bypass', answer } = {}) => { + const frames = []; + await bridge.runTurn({ + chatId, message, workspacePath: ws, mode, + onFrame: f => { + frames.push(f); + if (answer && f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId, callId: f.tool.id, decision: answer }).catch(e => frames.push({ type: 'test-error', message: e.message })); + }, + }); + return frames; + }; + const call = (chatId, tool, args, options) => run(chatId, `SCRIPT:call ${tool} ${JSON.stringify(args)}`, options); + return { worker, bridge, dir, ws, run, call }; +} +const cards = frames => frames.filter(f => f.type === 'agent-tool').map(f => f.tool); +const last = frames => cards(frames).at(-1); + +test('the agent is offered exactly these tools: everything useful including web search (no key needed), no scheduler, and the question tool the app can answer', { skip }, async (t) => { + const r = await rig(t); + await r.run('inv', 'SCRIPT:echo hi'); + const offered = [...r.worker.requests].reverse().find(q => q.toolNames.length)?.toolNames.sort(); + assert.deepEqual(offered, ['ask_user_question', 'create_goal', 'edit', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'present', 'pwsh', 'read', 'read_image', 'send_message', 'skill', 'subagent', 'subagent_fork', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'working_directory', 'write'].sort()); + assert.ok(!offered.some(n => n.startsWith('schedule_')) && offered.includes('web_search') && offered.includes('ask_user_question') && !offered.includes('exit_plan_mode')); +}); + +test('a tool from each family runs and shows a card the page can render', { skip }, async (t) => { + const r = await rig(t); + const file = join(r.ws, 'notes.txt'); + writeFileSync(file, 'alpha\nneedle here\nomega\n'); + const f = fwd(file); + // read-only family + assert.match(last(await r.call('fam-r', 'read', { file_path: f })).result, /needle here/); + assert.match(last(await r.call('fam-g', 'glob', { pattern: '*.txt' })).result, /notes\.txt/); + assert.match(last(await r.call('fam-s', 'grep', { pattern: 'needle' })).result, /Line 2/); + assert.equal(last(await r.call('fam-w', 'working_directory', {})).state, 'done'); + assert.equal(last(await r.call('fam-j', 'job_list', {})).state, 'done'); + // plan / list family + assert.equal(last(await r.call('fam-t', 'todo_write', { todos: [{ content: 'check the build', status: 'pending' }] })).state, 'done'); + const goal = last(await r.call('fam-goal', 'create_goal', { objective: 'finish the notes' })); + assert.equal(goal.state, 'done'); assert.equal(goal.effect, 'Sets a goal to work towards.'); + // write family (Bypass: no card asks) + const wrote = await r.call('fam-fs', 'write', { file_path: fwd(join(r.ws, 'new.txt')), content: 'made\n' }); + assert.equal(last(wrote).state, 'done'); assert.equal(readFileSync(join(r.ws, 'new.txt'), 'utf8').trim(), 'made'); + await r.call('fam-fs', 'read', { file_path: f }); + const edited = await r.call('fam-fs', 'edit', { file_path: f, old_string: 'alpha', new_string: 'ALPHA' }); + assert.equal(last(edited).state, 'done'); assert.match(readFileSync(file, 'utf8'), /^ALPHA/); + // shell family + assert.match(last(await r.call('fam-sh', 'pwsh', { command: 'Get-ChildItem', description: 'list files' })).result, /notes\.txt/); + // web family: offline, loopback is refused by the Harness itself; the failure is plain with Details after it + const web = last(await r.call('fam-web', 'web_fetch', { url: 'http://127.0.0.1:9/' })); + assert.equal(web.state, 'error'); assert.match(web.result, /^That web page could not be opened/); assert.match(web.result, /Details: /); + assert.equal(web.effect, 'Opens a web page.'); assert.equal(web.preview, 'http://127.0.0.1:9/'); + // no card shows raw JSON as its explanation + for (const c of [last(await r.call('fam-t2', 'todo_write', { todos: [{ content: 'x', status: 'pending' }] }))]) assert.ok(!c.preview.startsWith('{')); +}); + +test('Manual: one change is one card. Nothing ran when it appeared, and no sandbox or PowerShell error was ever shown', { skip }, async (t) => { + const r = await rig(t); + const a = join(r.ws, 'a.txt'), b = join(r.ws, 'b.txt'), c = join(r.ws, 'c.txt'); + // approve a file write + let frames = await r.call('man1', 'write', { file_path: fwd(a), content: 'hello\n' }, { mode: 'manual', answer: 'approve' }); + assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']); + assert.equal(new Set(cards(frames).map(x => x.id)).size, 1, 'one card, updated in place'); + assert.equal(readFileSync(a, 'utf8').trim(), 'hello'); + // deny a file write + frames = await r.call('man2', 'write', { file_path: fwd(b), content: 'no\n' }, { mode: 'manual', answer: 'deny' }); + assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'denied', 'denied']); + assert.equal(last(frames).result, 'Denied. Nothing ran.', 'the card says it in plain words, not the model-facing error'); + assert.equal(existsSync(b), false); + // a shell command that changes things + frames = await r.call('man3', 'pwsh', { command: `Set-Content -Path '${c}' -Value x`, description: 'Make c.txt' }, { mode: 'manual', answer: 'approve' }); + assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']); + assert.ok(existsSync(c)); + // a shell command that only looks needs no question + frames = await r.call('man4', 'pwsh', { command: 'Get-ChildItem', description: 'List files' }, { mode: 'manual' }); + assert.deepEqual(cards(frames).map(x => x.state), ['running', 'done']); + // nowhere in any of it does the person see the sandbox talking + const all = JSON.stringify([...cards(frames), ...cards(await r.call('man5', 'write', { file_path: fwd(join(r.ws, 'd.txt')), content: 'd' }, { mode: 'manual', answer: 'approve' }))]); + assert.ok(!/sandbox|Constrained|language mode|access denied/i.test(all), all.slice(0, 300)); +}); + +test('Plan stays read-only and Bypass asks nothing', { skip }, async (t) => { + const r = await rig(t); + const p = join(r.ws, 'p.txt'), q = join(r.ws, 'q.txt'); + const planned = await r.call('pl', 'write', { file_path: fwd(p), content: 'x' }, { mode: 'plan' }); + assert.equal(existsSync(p), false); + assert.ok(!cards(planned).some(x => x.state === 'proposed')); + const free = await r.call('bp', 'write', { file_path: fwd(q), content: 'x' }, { mode: 'bypass' }); + assert.equal(existsSync(q), true); + assert.ok(!cards(free).some(x => x.state === 'proposed')); +}); + +test('Manual refuses to start when the gate is not loaded (it would be an open sandbox that nobody asks about)', { skip }, async (t) => { + // A Harness started without the gate plugin (the bridge's `gate: false`). + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-nogate-')); + mkdirSync(join(dir, 'ws'), { recursive: true }); + const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }]; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, gate: false, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); + await assert.rejects(bridge.runTurn({ chatId: 'x', message: 'SCRIPT:echo hi', workspacePath: join(dir, 'ws'), mode: 'manual', onFrame: () => {} }), error => error.code === 'mode-unavailable' && /asks before changing/.test(error.message) && !/sandbox/i.test(error.message)); +}); + +test('a tool server set up for the model is connected to the agent: its tools are offered, Manual asks before using them, and its secret never reaches a file', { skip }, async (t) => { + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-mcp-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const mcpServers = { demo: { command: process.execPath, args: [fwd(join(import.meta.dirname, 'helpers', 'mini-mcp.mjs'))], env: { DEMO_TOKEN: 'tok-123456-secret' } }, off: { command: 'x', disabled: true } }; + const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2, mcpServers }]; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); + const frames = []; + await bridge.runTurn({ chatId: 'mcp-bypass', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'hello' })}`, workspacePath: ws, mode: 'bypass', onFrame: f => frames.push(f) }); + assert.ok([...worker.requests].reverse().find(q => q.toolNames.length).toolNames.includes('mcp__demo__shout')); + assert.ok(![...worker.requests].some(q => q.toolNames.some(n => n.startsWith('mcp__off'))), 'a disabled server is not connected'); + const card = cards(frames).at(-1); + assert.equal(card.state, 'done'); assert.match(card.result, /HELLO\|token:set/, 'the secret reached the server through the environment'); + assert.equal(card.scope, 'connected'); + // Manual: a connected tool has unknown effects, so it asks first + const manual = []; + await bridge.runTurn({ + chatId: 'mcp-manual', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'ask me' })}`, workspacePath: ws, mode: 'manual', + onFrame: f => { manual.push(f); if (f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId: 'mcp-manual', callId: f.tool.id, decision: 'approve' }); }, + }); + assert.deepEqual(cards(manual).map(c => c.state), ['running', 'proposed', 'running', 'done']); + assert.match(cards(manual)[1].effect, /Use the connected tool demo \/ shout/); + // the secret is in the environment of the agent only: never in the profile file + const files = JSON.stringify(readdirDeep(join(dir, 'agent')).filter(f => f.endsWith('.yml')).map(f => readFileSync(f, 'utf8'))); + assert.ok(files.includes('process.env.STRATA_MCP_0_E_DEMO_TOKEN') && !files.includes('tok-123456-secret')); +}); + +function readdirDeep(dir) { + const out = []; + for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) out.push(...readdirDeep(p)); else out.push(p); } + return out; +} + +test('the output budget is not the old 8192, and the Reasoning menu reaches the request (off sends enable_thinking false)', { skip }, async (t) => { + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-think-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 65536 }]; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); + const ask = async (chatId, thinking) => { + worker.requests.length = 0; + await bridge.runTurn({ chatId, message: 'SCRIPT:echo hi', workspacePath: ws, mode: 'bypass', thinking, onFrame: () => {} }); + return worker.requests.find(r => r.toolNames.length).params; + }; + const ctk = p => p.chat_template_kwargs ?? {}; + const off = await ask('think-off', 'Off'); + assert.equal(ctk(off).enable_thinking, false); assert.equal(ctk(off).reasoning_effort, undefined); + assert.equal(off.enable_thinking, undefined, 'a top-level enable_thinking is the field the Strata server ignores'); + // The profile's budget (19,660 at 64K: what compaction sets aside for a reply) is the header the Harness reads; the request itself may produce half the window (AGENT-LOST). + assert.ok(off.max_completion_tokens === 32768, `ceiling ${off.max_completion_tokens} (half the window, at most 64K: never the old 8192, and a file written in one call is not cut at the 30 percent compaction reserves)`); + const high = await ask('think-high', 'High'); + assert.equal(ctk(high).enable_thinking, true); assert.equal(ctk(high).reasoning_effort, 'high'); + const low = await ask('think-low', 'Low'); + assert.equal(ctk(low).enable_thinking, true); assert.equal(ctk(low).reasoning_effort, 'low'); + const max = await ask('think-max', 'Max'); + assert.equal(ctk(max).enable_thinking, true); assert.equal(ctk(max).reasoning_effort, 'high'); + // the same chat switching its level between turns + assert.equal(ctk(await ask('think-off', 'High')).enable_thinking, true); + assert.equal(ctk(await ask('think-off', 'Off')).enable_thinking, false); +}); diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjs index 8840b0b133..cf66f3baf2 100644 --- a/apps/host/tests/helpers/scripted-worker.mjs +++ b/apps/host/tests/helpers/scripted-worker.mjs @@ -152,6 +152,23 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model = send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'web_search', arguments: argsJson } }] }); return finish('tool_calls', 60); } + if (directive?.[1] === 'cutwrite' || directive?.[1] === 'cutalways') { + // A reply the length limit cuts inside a tool call (AGENT-LOST): some words, then `write` arguments that never close, finish "length". + // `cutwrite` is cut once and then, asked to carry on, writes the file in a small call; `cutalways` is cut every time. + const nudged = messages.some(m => m.role === 'user' && /cut off by the output limit/.test(text(m))); + if (directive[1] === 'cutwrite' && nudged) { + if (last.role === 'tool') return say(['Written in parts. The file is complete.']); + return toolCall('write', { file_path: (directive[2] ?? '').trim() || 'big.txt', content: 'entry 0001\nentry 0002\n' }); + } + send({ role: 'assistant', content: 'Writing the whole file in one call now. ' }); + await delay(chunkDelayMs); + const file = (directive[2] ?? '').trim() || 'big.txt'; + send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'write', arguments: '' } }] }); + const head = `{"file_path":"${file}","content":"`; + for (let i = 0; i < head.length; i += 11) { send({ tool_calls: [{ index: 0, function: { arguments: head.slice(i, i + 11) } }] }); await delay(2); } + for (let n = 1; n <= 60; n++) { send({ tool_calls: [{ index: 0, function: { arguments: `entry ${String(n).padStart(4, '0')}: alpha beta gamma delta\\n` } }] }); await delay(2); } + return finish('length', 19660); + } if (directive?.[1] === 'bloat') { promptTokens = parseInt((directive[2] ?? '').trim(), 10) || 100; send({ role: 'assistant', content: '', reasoning_content: 'Thinking about it for a long time and never getting to the answer.' }); From 5ab569aa472ffaad15c1ff602a418aa739af5a2b Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:02:14 +0100 Subject: [PATCH 43/59] Tests that pinned the old words and places follow the new ones; a DeepSeek card keeps its own SSD line; the status line keeps its 24ch column --- apps/host/src/components/PcFitCard.tsx | 1 + apps/host/src/styles/app.css | 2 +- apps/host/tests/deepseek-card.test.mjs | 6 +++--- apps/host/tests/deepseek-context.test.mjs | 8 ++++---- apps/host/tests/qa1-downloads.test.mjs | 2 +- apps/host/tests/ui4-fixes.test.mjs | 2 +- apps/host/tests/ui5-live.test.mjs | 2 +- 7 files changed, 12 insertions(+), 11 deletions(-) diff --git a/apps/host/src/components/PcFitCard.tsx b/apps/host/src/components/PcFitCard.tsx index fbcadd675b..76a270bc53 100644 --- a/apps/host/src/components/PcFitCard.tsx +++ b/apps/host/src/components/PcFitCard.tsx @@ -38,6 +38,7 @@ export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null, diskGb = {tr(isLoaded && streamed >= 1 && live?.diskReadGbs && live.diskReadGbs >= 0.05 ? <p className="pc-note">{tr("Reading from your SSD now: {0}", [`${live.diskReadGbs.toFixed(1)} GB/s`])}</p> : null)} {tr(inUse ? <p className="xs muted">{tr("Models that stay loaded use about {0} GB of RAM and {1} GB of this card’s memory.", [inUse.ramGb, inUse.vramGb])}</p> : null)} {tr(showFit && !isLoaded && fit!.vramUseGb + fit!.ramUseGb > 0 ? <p className="pc-note">{tr("This version would take about {0} of graphics memory and {1} of RAM.", [about(fit!.vramUseGb), about(fit!.ramUseGb)])}</p> : null)} + {tr(showFit && diskGb && fit!.spillGb >= 1 ? <p className="pc-note">{tr("About {0} GB will be read from the SSD, so answers can be a little slower.", [Math.round(fit!.spillGb)])}</p> : null)} {tr(diskGb ? <p className="pc-note">{tr("Needs about {0} GB of free disk space. What does not fit in memory is read from your SSD.", [Math.round(diskGb)])}</p> : null)} </section>; } diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index f02cdb8dd0..16a0dabfcd 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7157,7 +7157,7 @@ textarea { .tool-summary > div { margin-top: 6px; padding-left: 20px; } /* ---- the live status line ---- */ -.live-status { display: grid; grid-template-columns: 14px minmax(0, 32ch) 6ch minmax(0, auto); align-items: center; column-gap: 10px; min-height: 28px; margin-top: 6px; color: var(--st-ink-soft); font-size: var(--st-fs-sm); } +.live-status { display: grid; grid-template-columns: 14px minmax(0, 24ch) 6ch minmax(0, auto); align-items: center; column-gap: 10px; min-height: 28px; margin-top: 6px; color: var(--st-ink-soft); font-size: var(--st-fs-sm); } /* the word has its own area: the timer and the token count stay where they are while the word changes length */ .live-status__verb { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .live-status__time, .live-status__tokens { font-variant-numeric: tabular-nums; color: var(--st-ink-muted); white-space: nowrap; } diff --git a/apps/host/tests/deepseek-card.test.mjs b/apps/host/tests/deepseek-card.test.mjs index 94d4a9f0b9..2c53c038bf 100644 --- a/apps/host/tests/deepseek-card.test.mjs +++ b/apps/host/tests/deepseek-card.test.mjs @@ -41,10 +41,10 @@ test('a DeepSeek card that does spill keeps its spill line beside the disk line' test('every other model keeps its card as it was', () => { setTranslationLanguage('en'); - assert.match(card({ fit: fit(0) }), /Fits fully in memory\./); - assert.match(card({ fit: fit(0), diskGb: null }), /Fits fully in memory\./); + // Owner, 11-01: no "Fits" words, and the SSD warning is said once, under the version picker (a DeepSeek card keeps its own line above). + assert.doesNotMatch(card({ fit: fit(0) }), /Fits fully in memory\./); assert.doesNotMatch(card({ fit: fit(0) }), /free disk space/); - assert.match(card({ fit: fit(30) }), /About 30 GB will be read from the SSD/); + assert.doesNotMatch(card({ fit: fit(30) }), /read from the SSD/); }); test('the words are in all eight languages with the same slots', () => { diff --git a/apps/host/tests/deepseek-context.test.mjs b/apps/host/tests/deepseek-context.test.mjs index 40bdd7cb72..694829af47 100644 --- a/apps/host/tests/deepseek-context.test.mjs +++ b/apps/host/tests/deepseek-context.test.mjs @@ -79,11 +79,11 @@ test('through the host: an installed DeepSeek model reports its pack\'s limit, a test('the Models screen honours the choice (it no longer forces 8K), offers the DeepSeek list, and shows the note on the existing note markup', () => { const screen = read('../src/components/NativeModels.tsx'); - assert.doesNotMatch(screen, /multi_file \? 8192 : context/, 'the chosen context is what is installed and loaded'); - assert.match(screen, /contextChoices\(selectedSize\?\.multi_file \? deepseekContexts\(installed\?\.contextMax\) : native\?\.catalog\?\.contexts \?\? \[8192, 32768, 65536, 131072, 262144\], context\)/); + assert.doesNotMatch(screen, /multi_file ? 8192 : context/, 'the chosen context is what is installed and loaded'); + assert.match(screen, /selectedSize\?\.multi_file \? deepseekContexts\(installed\?\.contextMax\) : native\?\.catalog\?\.contexts \?\? \[8192, 32768, 65536, 131072, 262144\][\s\S]*contextChoices\(contextList, context\)/); assert.match(screen, /selectedSize\?\.multi_file && deepseekContextNote\(context\) \? <p className="small muted native-spill-note"><Icon name="info" size=\{16\}\/>\{tr\(deepseekContextNote\(context\)\)\}<\/p> : null/); - assert.match(screen, /if \(selectedSize\.multi_file\)\s+setContext\(8192\)/, 'the default for a DeepSeek version that is not installed stays 8K'); - assert.match(screen, /if \(installed\.context\)\s+setContext\(installed\.context\)/, 'an installed DeepSeek model shows and loads the context it was prepared with, whatever was kept from another model'); + assert.match(screen, /setContext\(selectedSize\.multi_file \? 8192 : defaultContext\(contextList\)\)/, 'the default for a DeepSeek version that is not installed stays 8K'); + assert.match(screen, /setContext\(selectedSize\.multi_file \? installed\.context : openingContext/, 'an installed DeepSeek model shows and loads the context it was prepared with, whatever was kept from another model'); assert.match(screen, /installed\?\.ready && context === installed\.context/, 'a load at the prepared context starts from the saved file; only a changed choice runs setup again'); }); diff --git a/apps/host/tests/qa1-downloads.test.mjs b/apps/host/tests/qa1-downloads.test.mjs index 1aaf053c31..05f2b5e42c 100644 --- a/apps/host/tests/qa1-downloads.test.mjs +++ b/apps/host/tests/qa1-downloads.test.mjs @@ -144,7 +144,7 @@ test('4d: picture reading is on unless the person turned it off (no saved choice assert.equal(first().visionEnabled, true); } finally { await f.cleanup(); } const screen = readSource(new URL('../src/components/NativeModels.tsx', import.meta.url), 'utf8'); - assert.match(screen, /setVision\(installed\.visionEnabled === false \? 'no'/); + assert.match(screen, /setVision\(installed\.visionEnabled === false && installed\.visionPrepared !== false \? 'no'/); assert.match(screen, /else\s*\{?\s*setVision\('yes'\)/, 'a version that is not downloaded starts with Read pictures on'); }); diff --git a/apps/host/tests/ui4-fixes.test.mjs b/apps/host/tests/ui4-fixes.test.mjs index 04ec8304a8..55df1acd70 100644 --- a/apps/host/tests/ui4-fixes.test.mjs +++ b/apps/host/tests/ui4-fixes.test.mjs @@ -56,7 +56,7 @@ test('items 6, 7, 8: Bypass permissions everywhere, no deleted-tasks list or sug assert.match(lib, /mode:'bypass'/, 'a new task starts as Bypass permissions'); assert.ok(!/Deleted tasks|task-templates|Restore/.test(tasks), 'no deleted list, suggestions or restore on the Tasks screen'); assert.match(tasks, /IconBtn name="plus"/); - assert.ok(!/back=\{|titleDetail=/.test(tasks), 'nothing on the left of the navbar of an opened task'); + assert.ok(!/back=\{/.test(tasks) && /titleDetail=\{currentTask \? undefined/.test(tasks), 'nothing on the left of the navbar of an opened task (the help lines show only on the list views)'); assert.ok(!/modelName|"Model"/.test(detail), 'no Model section'); assert.match(tree, /pushToast\('success', 'Task removed'\)/); assert.match(tasks, /pushToast\('success', 'Task removed'\)/); }); diff --git a/apps/host/tests/ui5-live.test.mjs b/apps/host/tests/ui5-live.test.mjs index bae721baf2..02feafe5cb 100644 --- a/apps/host/tests/ui5-live.test.mjs +++ b/apps/host/tests/ui5-live.test.mjs @@ -50,7 +50,7 @@ test('item 10: the status line has fixed columns, so the word changing length mo test('items 15, 16, 17: counts on the Subagents title row, Privacy as plain text, a round arrow', async () => { const bar = await read('components/ChatToolbar.tsx'), pop = await read('components/Popover.tsx'), privacy = await read('components/PrivacyNotes.tsx'), chat = await read('screens/Chat.tsx'); - assert.match(bar, /title=\{tr\("Subagents"\)\} detail=\{/); assert.ok(!/subagents-overview-summary/.test(bar), 'no second line of counts'); + assert.match(bar, /title=\{tr\(session\?\.agents\?\.length \? "Subagents" : "No subagents recorded"\)\} detail=\{/); assert.ok(!/subagents-overview-summary/.test(bar), 'no second line of counts'); assert.match(pop, /telepop__detail/); assert.ok(!/Icon/.test(privacy), 'no icons in Privacy'); assert.ok(!/>\{tr\("Latest"\)\}</.test(chat) && (chat.match(/aria-label=\{tr\("Scroll to the latest message"\)\}/g) ?? []).length === 2, 'the Latest button is a round arrow'); From 8550019663c8b15fa0ca195d778f058971e01355 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:13:27 +0100 Subject: [PATCH 44/59] A context picked after this update sticks, 32K included: saved with a marker (ui_context_chosen) by a load, an install or the first-run step; only an old unmarked 32K moves to 128K. The Tune dialog also saves no picture off when the engine has no reader --- apps/host/server/native-control.mjs | 10 +++++---- apps/host/server/run-config-check.mjs | 2 +- apps/host/src/components/GuidedSetup.tsx | 6 +++--- apps/host/src/components/NativeModels.tsx | 12 +++++------ apps/host/src/components/NativeTune.tsx | 6 ++++-- apps/host/src/lib/default-context.ts | 10 ++++++--- apps/host/src/lib/native.ts | 2 +- apps/host/tests/native-onboarding.test.mjs | 17 +++++++++++++++ apps/host/tests/ui-r3.test.mjs | 24 ++++++++++++++++++++++ 9 files changed, 69 insertions(+), 20 deletions(-) diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index fce4661781..40593ac42a 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -90,7 +90,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp for(const name of names){const path=join(dir,name),config=readJson(path,null);if(!config||typeof config!=='object')continue; const next={...config,...(config.cwd!==undefined?{cwd:fix(config.cwd)}:{}),...(Array.isArray(config.args)?{args:config.args.map(fix)}:{})}; if(JSON.stringify(next)!==JSON.stringify(config)){try{writeModelConfig(path,next);}catch{/* read-only folder: the load reports it */}}}} - function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_.-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;/* A model the person pointed at their own GGUF folder (not <data>/models/<tag>): remembered, so a later load runs setup with that folder again instead of downloading the files (#3199). */const ownGgufDir=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))!=='models'&&existsSync(nativeFile)?dirname(nativeFile):undefined;return {...entry,ownGgufDir,contextMax:configContextLimit(cfg)??undefined,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,visionPrepared:!!cfg.vision,/* The picture files are prepared when the run config has a vision section: the Models screen then loads straight away instead of running setup again (it used to read 'off' for every model, which sent every load of a picture-capable model through "Apply settings and load", and setup writes the arguments, the draft layer and the reader back each time). */images:cfg.vision?'yes':'off',draftLayer:cfg.mtp!==false,drafting:cfg.drafting??'auto',/* Picture reading is ON unless the person turned it off: no saved choice and not loaded is undefined, not false (owner rule: pictures on by default). */visionEnabled:cfg.ui_vision_enabled??(()=>{const running=[...instances.values()].find(i=>i.model===entry.model&&i.status==='ready');return running?!!running.vision:undefined;})(),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} + function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_.-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;/* A model the person pointed at their own GGUF folder (not <data>/models/<tag>): remembered, so a later load runs setup with that folder again instead of downloading the files (#3199). */const ownGgufDir=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))!=='models'&&existsSync(nativeFile)?dirname(nativeFile):undefined;return {...entry,ownGgufDir,contextMax:configContextLimit(cfg)??undefined,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,contextChosen:cfg.ui_context_chosen===true,visionPrepared:!!cfg.vision,/* The picture files are prepared when the run config has a vision section: the Models screen then loads straight away instead of running setup again (it used to read 'off' for every model, which sent every load of a picture-capable model through "Apply settings and load", and setup writes the arguments, the draft layer and the reader back each time). */images:cfg.vision?'yes':'off',draftLayer:cfg.mtp!==false,drafting:cfg.drafting??'auto',/* Picture reading is ON unless the person turned it off: no saved choice and not loaded is undefined, not false (owner rule: pictures on by default). */visionEnabled:cfg.ui_vision_enabled??(()=>{const running=[...instances.values()].find(i=>i.model===entry.model&&i.status==='ready');return running?!!running.vision:undefined;})(),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} function installRoot(){const found=[preferences.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} /* The settings file Strata Control and the installer read (control-runtime.mjs sets STRATA_SETTINGS_FILE to it): the app's data folder is written there. */ function controlSettingsFile(){return process.env.STRATA_SETTINGS_FILE||join(dirname(componentsDirectory()),'app-settings.json');} @@ -197,6 +197,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp const note=engineStep?.summaryNote(); const finalResult=engineStep?job.result:result; if(note)return {...finalResult,summary:note}; + /* A context the person picked is kept with a marker (ui_context_chosen), so only an old saved 32K, which has no marker, is read as the old default. */ + if(args.contextChosen===true){try{const id=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;rememberSetting(record(id).path,'ui_context_chosen',true);}catch{/* the install itself is done */}} if(args.loadAfter){const model=(result.install.family??args.family??'qwen')==='qwen'?String(args.model).toLowerCase():`${args.family}-${String(args.model).toLowerCase()}`;return loadEngine(job,{model,multiple:!!args.multiple,resourceProfile:args.resourceProfile,vision:args.loadVision,...(args.visionUnavailable===true?{visionUnavailable:true}:{}),...(typeof args.drafting==='string'?{values:{drafting:args.drafting}}:{})});} return finalResult; } @@ -280,7 +282,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} let mine=captureUserArgs(base0);const asked=cleared?null:reserveChoice({...base0,[USER_KEY]:mine},snapshot.hardware,values0).asked; if(asked!==null)mine=setUserFlag(mine,'--vram-reserve-mib',asked); const resources=args.resourceProfile&&!ownEngine(config)?resourceSettings({...base0,[USER_KEY]:mine,vision},snapshot.hardware,args.resourceProfile,modelArena(args.model),values0):null; - const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision}; + const cfg={...config,...visionPreferences,...(args.contextChosen===true?{ui_context_chosen:true}:{}),...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision}; /* The app's suggested cards only fill a gap: a model whose settings file already names its GPUs ("gpu": [1, 0], with "gpu_order": "as_given") keeps them (#3256). A card the person picked in the screen always wins. */ const namedInFile=((Array.isArray(config.gpu)?config.gpu.length>0:config.gpu!==undefined&&config.gpu!==null&&config.gpu!=='')||!!config.gpu_roles)&&!setupPickedOneCard(config,snapshot.hardware); /* Roles chosen in the screen (Main / Helper / Off per card, gpu-roles.mjs): the card list is the roles' mirror - Helpers first, the Main card LAST, Off cards left out - with "gpu_roles" beside it. Every card Off is allowed: the server says plainly what the engine can do. */ @@ -396,7 +398,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} } const deadline=Date.now()+300000;while(Date.now()<deadline&&job.state==='running'){ if(instance.status==='error')throw new Error(instance.error); - try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(job.state!=='running'){await unload(id);return;}if(response.ok){instance.status='ready';instance.phase='idle';await noteDrafting(job,instance,key);if(resources||args.vision!==undefined||JSON.stringify(cfg[USER_KEY]??null)!==JSON.stringify(config[USER_KEY]??null))writeModelConfig(record(args.model).path,{...config,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),...visionPreferences,...(cfg[USER_KEY]?{[USER_KEY]:cfg[USER_KEY]}:{})});emit();ensurePoll();instance.parallelNote=parallelNote;return {summary:retried?`${instance.label} is ready, after a second try: ${retried.words}`:`${instance.label} is ready.${parallelNote?' '+parallelNote:''}`,instanceId:id};}}catch{} + try{const response=await fetcher(`http://127.0.0.1:${instance.port}/health`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(job.state!=='running'){await unload(id);return;}if(response.ok){instance.status='ready';instance.phase='idle';await noteDrafting(job,instance,key);if(resources||args.vision!==undefined||args.contextChosen===true||JSON.stringify(cfg[USER_KEY]??null)!==JSON.stringify(config[USER_KEY]??null))writeModelConfig(record(args.model).path,{...config,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),...visionPreferences,...(args.contextChosen===true?{ui_context_chosen:true}:{}),...(cfg[USER_KEY]?{[USER_KEY]:cfg[USER_KEY]}:{})});emit();ensurePoll();instance.parallelNote=parallelNote;return {summary:retried?`${instance.label} is ready, after a second try: ${retried.words}`:`${instance.label} is ready.${parallelNote?' '+parallelNote:''}`,instanceId:id};}}catch{} await new Promise(resolve=>setTimeout(resolve,1200)); } if(job.state!=='running'){await unload(id);return;} @@ -519,7 +521,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} const next={...current.config,...values,ui_resource_profile:args.profile}; writeModelConfig(current.path,next); job.summary='Applying your resource preference and loading the model…';emit(); - const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:current.config.vision?args.vision:'no'}); + const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:current.config.vision?args.vision:'no',...(args.visionUnavailable===true?{visionUnavailable:true}:{})}); if(job.state!=='running'||!loaded?.instanceId)return; job.summary='Checking your model’s speed…';emit(); const measured=await benchmark(job,{instanceId:loaded.instanceId}); diff --git a/apps/host/server/run-config-check.mjs b/apps/host/server/run-config-check.mjs index 12ca8b84ce..91e3ed2fda 100644 --- a/apps/host/server/run-config-check.mjs +++ b/apps/host/server/run-config-check.mjs @@ -22,7 +22,7 @@ export const KNOWN_KEYS = new Set([ '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', + 'ui_vision_enabled', 'ui_context_chosen', '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']); diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsx index d9fac9af94..5879fdd170 100644 --- a/apps/host/src/components/GuidedSetup.tsx +++ b/apps/host/src/components/GuidedSetup.tsx @@ -48,7 +48,7 @@ export function GuidedSetup() { /* 128K for every configuration unless the person picks another. This first step has no room for the memory warning the Models page gives, so a card that a 128K cache would leave under 1 GB for the model starts at the 32K the engine was set up for. */ const topCardGb = Math.max(0, ...(native?.hardware?.gpus ?? []).filter(g => g.usable !== false).map(g => g.vram_gb)); - const [pickedContext, setContext] = useState<number | undefined>(saved?.context); + const [pickedContext, setContext] = useState<number | undefined>(saved?.context), [contextTouched, setContextTouched] = useState(false); const context = pickedContext ?? (contextIsTight(topCardGb, DEFAULT_CONTEXT) ? OLD_DEFAULT_CONTEXT : defaultContext(native?.catalog?.contexts)); const [vision, setVision] = useState(saved?.vision ?? true), [directory, setDirectory] = useState(saved?.directory ?? ''); const [profile, setProfile] = useState<'work' | 'performance'>(saved?.profile ?? 'work'); @@ -152,7 +152,7 @@ export function GuidedSetup() { void persist(4, { tuneJobId: tuneJob.id }).catch(e => setError(e.message)); } }, [step, installJob?.id, tuneJob?.id]); const fixedContext = version?.multi_file ? 8192 : null; // the one context DeepSeek's engine was checked at - const values = { guided: true, family: version?.sourceFamily, model: version?.model, context: fixedContext ?? context, vision: version?.images ? 'yes' : 'no', kv: 'int8', low_ram: 'auto', loadAfter: false, multiple: false, ...(directory ? { data_dir: directory } : {}) }; + const values = { guided: true, family: version?.sourceFamily, model: version?.model, context: fixedContext ?? context, ...(contextTouched && !fixedContext ? { contextChosen: true } : {}), vision: version?.images ? 'yes' : 'no', kv: 'int8', low_ram: 'auto', loadAfter: false, multiple: false, ...(directory ? { data_dir: directory } : {}) }; async function review() { await perform(async () => { setInstallJobId(''); @@ -221,7 +221,7 @@ export function GuidedSetup() { <div className="onboard-stage-heading"><h1 ref={titleRef} tabIndex={-1} data-initial-focus>{tr(title)}</h1>{tr(step === 2 ? <p>{tr("You can always change your models later.")}</p> : step === 4 && tuneJob?.state === 'running' ? <p>{tr("We\u2019re measuring, applying your preference, and getting ready to chat.")}</p> : null)}</div> {tr(step === 2 ? <div className="onboard-model-stage"> {tr(selectedFamily ? <> - <div className="onboard-model-top"><div className="onboard-model-picker"><span className="onboard-control-label">{tr("Model")}</span><div><span className="onboard-model-symbol"><Icon name="models" size={23}/></span><Select ariaLabel={tr("Setup model")} value={selectedFamily.family} options={families.map(f => ({ value: f.family, label: f.title }))} onChange={value => chooseNative(value, '')}/></div></div><div className="onboard-context"><span className="onboard-control-label">{tr("Conversation context")}</span><Select ariaLabel={tr("Setup conversation context")} value={String(version?.multi_file ? 8192 : context)} options={(version?.multi_file ? [8192] : native?.catalog?.contexts ?? [32768]).map(n => ({ value: String(n), label: `${n / 1024}K` }))} onChange={value => setContext(Number(value))}/></div></div> + <div className="onboard-model-top"><div className="onboard-model-picker"><span className="onboard-control-label">{tr("Model")}</span><div><span className="onboard-model-symbol"><Icon name="models" size={23}/></span><Select ariaLabel={tr("Setup model")} value={selectedFamily.family} options={families.map(f => ({ value: f.family, label: f.title }))} onChange={value => chooseNative(value, '')}/></div></div><div className="onboard-context"><span className="onboard-control-label">{tr("Conversation context")}</span><Select ariaLabel={tr("Setup conversation context")} value={String(version?.multi_file ? 8192 : context)} options={(version?.multi_file ? [8192] : native?.catalog?.contexts ?? [32768]).map(n => ({ value: String(n), label: `${n / 1024}K` }))} onChange={value => { setContextTouched(true); setContext(Number(value)); }}/></div></div> <OnboardingMemory hardware={hardware} native={native?.hardware}/>{tr(!version || version.needsNewerEngine ? <p className="small muted">{tr("This model needs a newer engine. Update your engine or import a local GGUF for this model.")}</p> : null)} <div className="onboard-version-heading"><strong>{tr("Choose a version")}</strong><span>{tr(version ? `${catalogVersionLabel(version)} selected` : '')}</span></div> {tr(version?.multi_file ? <DeepSeekNote version={version} plan={plan}/> : null)} diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 05bc1df136..dcd1e74547 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -134,7 +134,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const draftingChoices = selectedSize ? draftingOptions(selectedSize.sourceFamily ?? selectedFamily?.family, native?.capabilities?.dflash2) : null; const draftingWords: Record<string, string> = { auto: 'Auto (recommended)', mtp: 'MTP', dflash2: 'DFlash2', off: 'Off' }; const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(cardsGpus.length > 1 ? { gpus: cardsGpus.join(',') } : cardsGpus.length === 1 ? { gpu: cardsGpus[0] } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, cardsGpus.join(','), expert, multiple]); - const downloadValues = { ...values, ...(draftingChoices ? { drafting } : {}), vision: selectedSize?.images && vision !== 'no' ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}) }; + const downloadValues = { ...values, ...(draftingChoices ? { drafting } : {}), vision: selectedSize?.images && vision !== 'no' ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), ...(contextPicked ? { contextChosen: true } : {}) }; useEffect(() => { if (!native?.catalog || family) return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const have = new Set((native.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const installedFamily = families.find(f => f.sizes.some(s => have.has(s.id))); const f = loadedFamily ?? installedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) { setFamily(f.family); @@ -153,14 +153,14 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine } if (!selectedSize) return; - const sig = installed ? ['have', installed.model, installed.ready, installed.context, installed.kv, installed.images, installed.visionEnabled, installed.visionDevice, installed.lowRamMode, installed.drafting, installed.resourceProfile].join('|') : `new|${selectedSize.id}`; + const sig = installed ? ['have', installed.model, installed.ready, installed.context, installed.contextChosen, installed.kv, installed.images, installed.visionEnabled, installed.visionDevice, installed.lowRamMode, installed.drafting, installed.resourceProfile].join('|') : `new|${selectedSize.id}`; if (sig === appliedSig) return; setAppliedSig(sig); if (installed) { // The context it was prepared with when someone chose it; a model that holds the old 32K default opens at the new default. if (installed.context) - setContext(selectedSize.multi_file ? installed.context : openingContext(installed.context, contextList)); + setContext(selectedSize.multi_file ? installed.context : openingContext(installed.context, contextList, installed.contextChosen === true)); // Off only when the person turned it off (a saved choice on a model that has the picture files); a model prepared without them (images 'off', or an old "off" saved while the engine had no reader) starts with it ON. setVision(installed.visionEnabled === false && installed.visionPrepared !== false ? 'no' : installed.visionDevice ?? (installed.images && installed.images !== 'off' ? installed.images : 'yes')); setKv(installed.kv ?? 'int8'); @@ -175,7 +175,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine if (!contextPicked) // a context the person picked stays; otherwise 128K, and DeepSeek runs at the one context its engine was checked at (as in the guided setup) setContext(selectedSize.multi_file ? 8192 : defaultContext(contextList)); } - }, [selectedSize?.id, installed?.model, installed?.ready, installed?.context, installed?.kv, installed?.images, installed?.visionEnabled, installed?.visionDevice, installed?.lowRamMode, installed?.resourceProfile]); + }, [selectedSize?.id, installed?.model, installed?.ready, installed?.context, installed?.contextChosen, installed?.kv, installed?.images, installed?.visionEnabled, installed?.visionDevice, installed?.lowRamMode, installed?.resourceProfile]); useEffect(() => { if (jobId && job?.state === 'done' && job.id !== toastedJob && (job.kind === 'load' || job.kind === 'install')) { setToastedJob(job.id); selectRemoteModel(null); @@ -194,7 +194,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine here, in the page, and nothing starts. Otherwise the download or the apply-and-load starts at once, with its size and notes in the page. */ async function load() { if (!selectedSize) return; setPlan(null); setDrafterGb(null); await perform(async () => { if (installed?.ready && context === installed.context && (!selectedSize?.images || vision === 'no' || installed.images && installed.images !== 'off') && (!installed.kv || kv === installed.kv || kv === tunedNow?.fields.kv) && (lowRam === (installed.lowRamMode ?? 'auto') || lowRam === tunedNow?.fields.lowRam)) { - const result = await nativeAction<NativeJob>('operations', { kind: 'load', args: { model: selectedSize.id, resourceProfile, vision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), multiple: expert && multiple, ...(draftingChoices ? { values: { drafting } } : {}), ...(roleCards.length > 1 ? (roles && customRoles ? { gpuRoles: effectiveRoles, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : cardsGpus.length ? { gpus: cardsGpus, gpusFromRecommendation: true, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : {}) : {}) } }); + const result = await nativeAction<NativeJob>('operations', { kind: 'load', args: { model: selectedSize.id, resourceProfile, vision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), ...(contextPicked && !installed.contextChosen ? { contextChosen: true } : {}), multiple: expert && multiple, ...(draftingChoices ? { values: { drafting } } : {}), ...(roleCards.length > 1 ? (roles && customRoles ? { gpuRoles: effectiveRoles, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : cardsGpus.length ? { gpus: cardsGpus, gpusFromRecommendation: true, layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : {}) : {}) } }); setJobId(result.id); } else { @@ -270,7 +270,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine </div>; }))}</div> : <p className="small muted native-manage-empty">{tr("No downloaded models")}</p>)} <div className="native-manage-foot"><Btn variant="ghost" icon="folder" onClick={() => { setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF…")}</Btn></div> </div></Dialog> - {selectedSize ? <NativeTune open={tuneOpen} onClose={() => setTuneOpen(false)} model={selectedSize.id} resourceProfile={resourceProfile} vision={selectedSize.images ? vision : 'no'}/> : null} + {selectedSize ? <NativeTune open={tuneOpen} onClose={() => setTuneOpen(false)} model={selectedSize.id} resourceProfile={resourceProfile} vision={selectedSize.images ? vision : 'no'} visionUnavailable={noReader}/> : null} </Screen>; } /** setup's "5/7: downloading …" as a sentence a person can read. */ diff --git a/apps/host/src/components/NativeTune.tsx b/apps/host/src/components/NativeTune.tsx index 9fe497a3a6..736aaf8ba6 100644 --- a/apps/host/src/components/NativeTune.tsx +++ b/apps/host/src/components/NativeTune.tsx @@ -14,12 +14,14 @@ type Phase = 'idle' | 'running' | 'result'; * with the same saved tunings); this dialog only starts it, shows its progress and result in plain words, and lists, switches, * renames, deletes and undoes the saved tunings. It reuses the Auto-tune dialog's look. */ -export function NativeTune({ open, onClose, model, resourceProfile, vision }: { +export function NativeTune({ open, onClose, model, resourceProfile, vision, visionUnavailable = false }: { open: boolean; onClose: () => void; model: string; resourceProfile: 'work' | 'performance'; vision: string; + /** The engine has no picture reader: the run goes without pictures and the model's own setting is left as it is. */ + visionUnavailable?: boolean; }) { const native = useNative(); const [status, setStatus] = useState<TuneStatus | null>(null), [error, setError] = useState(''), [busy, setBusy] = useState(false); @@ -40,7 +42,7 @@ export function NativeTune({ open, onClose, model, resourceProfile, vision }: { async function start(kind: 'autotune' | 'recheck') { setBusy(true); setError(''); try { - const started = await nativeAction<NativeJob>('operations', { kind, args: { model, resourceProfile, vision, mode, use, allowSmallDifferences: allowSmall, presetId: status?.active?.id } }); + const started = await nativeAction<NativeJob>('operations', { kind, args: { model, resourceProfile, vision, ...(visionUnavailable ? { visionUnavailable: true } : {}), mode, use, allowSmallDifferences: allowSmall, presetId: status?.active?.id } }); setJobId(started.id); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); } diff --git a/apps/host/src/lib/default-context.ts b/apps/host/src/lib/default-context.ts index ef3de8123b..38543bb108 100644 --- a/apps/host/src/lib/default-context.ts +++ b/apps/host/src/lib/default-context.ts @@ -16,9 +16,13 @@ export function defaultContext(choices: readonly number[] | null | undefined): n return under.length ? Math.max(...under) : sizes.length ? Math.min(...sizes) : DEFAULT_CONTEXT; } -/** What a model that is already on this computer opens with: the context it was prepared with when someone chose it, else the default. */ -export function openingContext(saved: number | null | undefined, choices: readonly number[] | null | undefined): number { - return saved && saved > 0 && saved !== OLD_DEFAULT_CONTEXT ? saved : defaultContext(choices); +/** + * What a model that is already on this computer opens with: the context it was prepared with when someone chose it, else the default. A choice made + * from this update on is saved with a marker (`chosen`), whatever its size, 32K included; only an old saved 32K without a marker (the old default) moves + * to the new default. + */ +export function openingContext(saved: number | null | undefined, choices: readonly number[] | null | undefined, chosen = false): number { + return saved && saved > 0 && (chosen || saved !== OLD_DEFAULT_CONTEXT) ? saved : defaultContext(choices); } /** diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index 038607a888..f502b4f42b 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -12,7 +12,7 @@ export interface NativeState { /** The picture reader (strata-vision) is installed with the engine, so models marked for pictures can read them here. */ /** Strata Control's view of the engine for this computer (the app): usable false = none found or recognised; `notice` says why in plain words. */ engine?:{usable:boolean;notice?:string|null;wrongMake?:boolean;version?:string|null;/** What the last update check found newer (kept on this PC, read without the network): the Qwen engine, the DeepSeek engine, the app. */updateAvailable?:{engine?:string|null;dsv41?:string|null;app?:string|null}|null}; - 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;/** DeepSeek: the most context its pack reads (max_position_embeddings in the pack's ds4.txt); absent when the pack does not say. */contextMax?:number;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<string,{bytes:number;gb:number}>}|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;/** Models an engine update stopped, to offer starting them again with the same settings (updated: false = the update did not finish, the old engine is unchanged). */stoppedForUpdate?:{updated:boolean;at:string;models:{id:string;label:string}[]}|null;jobs:NativeJob[];capabilities:{/** The engine serves DFlash2 (Control says): the Drafting choice then offers it. */dflash2?:boolean;/** What was measured on this kind of card, in Control's words (null until Control answers). */dflash2Support?:{level:'tested'|'slower'|'untested';line:string}|null;responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}} + 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;/** DeepSeek: the most context its pack reads (max_position_embeddings in the pack's ds4.txt); absent when the pack does not say. */contextMax?:number;/** The context was picked by a person (a marker saved with the model); a saved 32K without it is the old default. */contextChosen?:boolean;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<string,{bytes:number;gb:number}>}|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;/** Models an engine update stopped, to offer starting them again with the same settings (updated: false = the update did not finish, the old engine is unchanged). */stoppedForUpdate?:{updated:boolean;at:string;models:{id:string;label:string}[]}|null;jobs:NativeJob[];capabilities:{/** The engine serves DFlash2 (Control says): the Drafting choice then offers it. */dflash2?:boolean;/** What was measured on this kind of card, in Control's words (null until Control answers). */dflash2Support?:{level:'tested'|'slower'|'untested';line:string}|null;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). */ diff --git a/apps/host/tests/native-onboarding.test.mjs b/apps/host/tests/native-onboarding.test.mjs index 2ce09a321a..d24b8d977c 100644 --- a/apps/host/tests/native-onboarding.test.mjs +++ b/apps/host/tests/native-onboarding.test.mjs @@ -151,6 +151,23 @@ test('a load while the engine has no picture reader runs without pictures and sa }finally{await f.cleanup();} }); +test('a context the person picked is saved with a marker and read back (32K included); nothing is marked when none was picked',async()=>{ + const plainFixture=nativeFixture();try{ + await plainFixture.control.refresh(); + const plain=await finishJob(plainFixture.control,plainFixture.control.operation('load',{model:'iq2_xs'}).id); + assert.equal(plain.state,'done',plain.error); + assert.equal(JSON.parse(readFileSync(join(plainFixture.repo,'strata-iq2_xs.json'))).ui_context_chosen,undefined); + assert.equal(plainFixture.control.state().installed.models[0].contextChosen,false); + }finally{await plainFixture.cleanup();} + const f=nativeFixture();try{ + await f.control.refresh(); + const picked=await finishJob(f.control,f.control.operation('load',{model:'iq2_xs',contextChosen:true}).id); + assert.equal(picked.state,'done',picked.error); + assert.equal(JSON.parse(readFileSync(join(f.repo,'strata-iq2_xs.json'))).ui_context_chosen,true); + assert.equal(f.control.state().installed.models[0].contextChosen,true); + }finally{await f.cleanup();} +}); + test('runtime vision checks prepared files, validates mode, and leaves the source config intact',()=>{ const config={vision:{mmproj:'/models/mmproj.gguf',gpu:true,max_tokens:8192},ui_vision_enabled:false}; const before=structuredClone(config); diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index 897f071eeb..5ab47218bb 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -157,3 +157,27 @@ test('the new words are in all nine languages with the same slots', () => { } } }); + +test('a context picked after this update sticks, 32K included; only an old saved 32K without the marker moves once', async () => { + const { openingContext } = await lib('src/lib/default-context.ts'); + const list = [8192, 32768, 65536, 131072]; + assert.equal(openingContext(32768, list), 131072, 'an old saved 32K has no marker: it moves to the new default'); + assert.equal(openingContext(32768, list, true), 32768, 'a 32K that was picked has the marker: it stays'); + assert.equal(openingContext(65536, list), 65536); + const host = read('server/native-control.mjs'); + assert.match(host, /\.\.\.\(args\.contextChosen===true\?\{ui_context_chosen:true\}:\{\}\)/, 'a load saves the marker'); + assert.match(host, /rememberSetting\(record\(id\)\.path,'ui_context_chosen',true\)/, 'an install saves it too'); + assert.match(host, /contextChosen:cfg\.ui_context_chosen===true/, 'and it is read back'); + assert.match(models, /openingContext\(installed\.context, contextList, installed\.contextChosen === true\)/); + assert.match(models, /\.\.\.\(contextPicked \? \{ contextChosen: true \} : \{\}\)/, 'a pick is sent with the install'); + assert.match(models, /\.\.\.\(contextPicked && !installed\.contextChosen \? \{ contextChosen: true \} : \{\}\)/, 'and with a direct load, so a picked 32K that equals the saved one is marked too'); + assert.match(read('src/components/GuidedSetup.tsx'), /contextTouched && !fixedContext \? \{ contextChosen: true \}/); +}); + +test('the tune dialog also runs without pictures and saves nothing when the engine has no reader', () => { + assert.match(models, /vision=\{selectedSize\.images \? vision : 'no'\} visionUnavailable=\{noReader\}/); + assert.match(read('src/components/NativeTune.tsx'), /\.\.\.\(visionUnavailable \? \{ visionUnavailable: true \} : \{\}\)/); + const host = read('server/native-control.mjs'); + assert.match(host, /vision:current\.config\.vision\?args\.vision:'no',\.\.\.\(args\.visionUnavailable===true\?\{visionUnavailable:true\}:\{\}\)/); + assert.match(host, /args\.contextChosen===true\|\|JSON\.stringify\(cfg\[USER_KEY\]/, 'a load that carries the context marker writes it to the saved settings'); +}); From bd7e44c90d27f2cf77aa57aae154d5a9870dfca3 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:35:17 +0100 Subject: [PATCH 45/59] 128K on every card, first-run setup and DeepSeek included: one rule (strata_control/default_context.py) for the app, the Terminal launch default, setup and the MCP install default; the tight-card fallback and DeepSeek's fixed 8K are gone, the inline warning stays --- apps/host/src/components/GuidedSetup.tsx | 17 ++++++----- apps/host/src/components/NativeModels.tsx | 16 +++++------ apps/host/src/lib/default-context.ts | 6 ++-- apps/host/tests/deepseek-context.test.mjs | 4 +-- apps/host/tests/ui-r3.test.mjs | 24 +++++++++++++--- setup.py | 8 ++---- strata_cli/launch/catalog.py | 35 ++++------------------- strata_control/default_context.py | 19 ++++++++++++ tools/strata_mcp.py | 7 ++--- 9 files changed, 74 insertions(+), 62 deletions(-) create mode 100644 strata_control/default_context.py diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsx index 5879fdd170..39248d5107 100644 --- a/apps/host/src/components/GuidedSetup.tsx +++ b/apps/host/src/components/GuidedSetup.tsx @@ -14,7 +14,9 @@ import type { LocalModelFolder, SetupState } from '../lib/types'; import { downloadCounter, modelFolderLabel, onboardingError } from '../lib/onboarding-download'; import { installProgress, installStage, stageText, useDownloadEta } from '../lib/download-eta'; import { VersionPicker } from './VersionPicker'; -import { contextIsTight, defaultContext, DEFAULT_CONTEXT, OLD_DEFAULT_CONTEXT } from '../lib/default-context'; +import { contextIsTight, defaultContext } from '../lib/default-context'; +import { deepseekContexts } from '../lib/deepseek-context'; +import { cacheGb } from '../lib/native-fit'; import { FirstRunLanguage } from './FirstRunLanguage'; import { DownloadParts } from './DownloadParts'; import { EngineWarning } from './EngineWarning'; @@ -45,11 +47,10 @@ export function GuidedSetup() { const start = startingChoice(families, (native?.installed?.models ?? []).filter(m => m.ready).map(m => m.model), native?.catalog?.recommendation); const family = chosenFamily || start?.family || native?.catalog?.recommendation?.family || families[0]?.family || ''; const size = chosenSize || start?.size || ''; - /* 128K for every configuration unless the person picks another. This first step has no room for the memory warning the Models page gives, so a card - that a 128K cache would leave under 1 GB for the model starts at the 32K the engine was set up for. */ + /* 128K for every configuration unless the person picks another, on every card and for DeepSeek too (its pack's own limit allows it). The warning for a card + it leaves little room on is under the chooser; nothing is lowered. */ const topCardGb = Math.max(0, ...(native?.hardware?.gpus ?? []).filter(g => g.usable !== false).map(g => g.vram_gb)); const [pickedContext, setContext] = useState<number | undefined>(saved?.context), [contextTouched, setContextTouched] = useState(false); - const context = pickedContext ?? (contextIsTight(topCardGb, DEFAULT_CONTEXT) ? OLD_DEFAULT_CONTEXT : defaultContext(native?.catalog?.contexts)); const [vision, setVision] = useState(saved?.vision ?? true), [directory, setDirectory] = useState(saved?.directory ?? ''); const [profile, setProfile] = useState<'work' | 'performance'>(saved?.profile ?? 'work'); const [installJobId, setInstallJobId] = useState(saved?.installJobId ?? ''), [tuneJobId, setTuneJobId] = useState(saved?.tuneJobId ?? ''); @@ -59,6 +60,8 @@ export function GuidedSetup() { const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0]; const version = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0]; const installed = native?.installed?.models.find(m => m.model === version?.id); + const contextList = version?.multi_file ? deepseekContexts(installed?.contextMax) : native?.catalog?.contexts ?? [131072]; + const context = pickedContext ?? defaultContext(contextList); const installJob = native?.jobs.find(j => j.id === installJobId) ?? (step === 3 ? native?.jobs.find(j => j.kind === 'install' && j.state === 'running' && j.guided && j.model === version?.model) : undefined), tuneJob = native?.jobs.find(j => j.id === tuneJobId) ?? (step === 4 ? native?.jobs.find(j => j.kind === 'tune' && j.state === 'running' && j.guided && j.model === version?.id) : undefined); const active = native?.jobs.find(j => j.state === 'running'); const ready = native?.instances.some(i => i.model === version?.id && i.status === 'ready'); @@ -151,8 +154,7 @@ export function GuidedSetup() { setTuneJobId(tuneJob.id); void persist(4, { tuneJobId: tuneJob.id }).catch(e => setError(e.message)); } }, [step, installJob?.id, tuneJob?.id]); - const fixedContext = version?.multi_file ? 8192 : null; // the one context DeepSeek's engine was checked at - const values = { guided: true, family: version?.sourceFamily, model: version?.model, context: fixedContext ?? context, ...(contextTouched && !fixedContext ? { contextChosen: true } : {}), vision: version?.images ? 'yes' : 'no', kv: 'int8', low_ram: 'auto', loadAfter: false, multiple: false, ...(directory ? { data_dir: directory } : {}) }; + const values = { guided: true, family: version?.sourceFamily, model: version?.model, context, ...(contextTouched ? { contextChosen: true } : {}), vision: version?.images ? 'yes' : 'no', kv: 'int8', low_ram: 'auto', loadAfter: false, multiple: false, ...(directory ? { data_dir: directory } : {}) }; async function review() { await perform(async () => { setInstallJobId(''); @@ -221,7 +223,8 @@ export function GuidedSetup() { <div className="onboard-stage-heading"><h1 ref={titleRef} tabIndex={-1} data-initial-focus>{tr(title)}</h1>{tr(step === 2 ? <p>{tr("You can always change your models later.")}</p> : step === 4 && tuneJob?.state === 'running' ? <p>{tr("We\u2019re measuring, applying your preference, and getting ready to chat.")}</p> : null)}</div> {tr(step === 2 ? <div className="onboard-model-stage"> {tr(selectedFamily ? <> - <div className="onboard-model-top"><div className="onboard-model-picker"><span className="onboard-control-label">{tr("Model")}</span><div><span className="onboard-model-symbol"><Icon name="models" size={23}/></span><Select ariaLabel={tr("Setup model")} value={selectedFamily.family} options={families.map(f => ({ value: f.family, label: f.title }))} onChange={value => chooseNative(value, '')}/></div></div><div className="onboard-context"><span className="onboard-control-label">{tr("Conversation context")}</span><Select ariaLabel={tr("Setup conversation context")} value={String(version?.multi_file ? 8192 : context)} options={(version?.multi_file ? [8192] : native?.catalog?.contexts ?? [32768]).map(n => ({ value: String(n), label: `${n / 1024}K` }))} onChange={value => { setContextTouched(true); setContext(Number(value)); }}/></div></div> + <div className="onboard-model-top"><div className="onboard-model-picker"><span className="onboard-control-label">{tr("Model")}</span><div><span className="onboard-model-symbol"><Icon name="models" size={23}/></span><Select ariaLabel={tr("Setup model")} value={selectedFamily.family} options={families.map(f => ({ value: f.family, label: f.title }))} onChange={value => chooseNative(value, '')}/></div></div><div className="onboard-context"><span className="onboard-control-label">{tr("Conversation context")}</span><Select ariaLabel={tr("Setup conversation context")} value={String(context)} options={contextList.map(n => ({ value: String(n), label: `${n / 1024}K` }))} onChange={value => { setContextTouched(true); setContext(Number(value)); }}/></div></div> + {tr(contextIsTight(topCardGb, context) ? <p className="small muted native-spill-note"><Icon name="warning" size={16}/>{tr("This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context.", [cacheGb(context).toFixed(1)])}</p> : null)} <OnboardingMemory hardware={hardware} native={native?.hardware}/>{tr(!version || version.needsNewerEngine ? <p className="small muted">{tr("This model needs a newer engine. Update your engine or import a local GGUF for this model.")}</p> : null)} <div className="onboard-version-heading"><strong>{tr("Choose a version")}</strong><span>{tr(version ? `${catalogVersionLabel(version)} selected` : '')}</span></div> {tr(version?.multi_file ? <DeepSeekNote version={version} plan={plan}/> : null)} diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index dcd1e74547..18a5ff7ef8 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -5,7 +5,7 @@ import { VersionPicker } from './VersionPicker'; import { FamilySwitch } from './FamilySwitch'; import { PcComputer } from './PcComputer'; import { cacheGb, fitOn, memoryNeeded, versionFit } from '../lib/native-fit'; -import { contextIsTight, defaultContext, DEFAULT_CONTEXT, openingContext } from '../lib/default-context'; +import { contextIsTight, defaultContext, DEFAULT_CONTEXT, OLD_DEEPSEEK_CONTEXT, openingContext } from '../lib/default-context'; import { GpuRoles } from './GpuRoles'; import { fromLegacy, normalize as normalizeRoles, order as roleOrder, recommend as recommendRoles, rows as roleRows, sameRoles, vramOn, type RoleCard, type Roles } from '../lib/gpu-roles'; import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; @@ -140,8 +140,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine setFamily(f.family); const first = f.sizes.find(s => s.id === current?.model) ?? f.sizes.find(s => have.has(s.id)) ?? f.sizes.find(s => s.model === rec.model) ?? f.sizes[0]; setSize(first?.id ?? ''); - // 128K for every configuration (the engine's own recommendation is not what the app opens with); DeepSeek keeps the 8K its engine was checked at. - setContext(first?.multi_file ? 8192 : defaultContext(native.catalog.contexts)); + // 128K for every configuration, DeepSeek included where its pack allows (the engine's own recommendation is not what the app opens with). + setContext(defaultContext(first?.multi_file ? deepseekContexts() : native.catalog.contexts)); } }, [native?.catalog]); // The version that is selected: a model already on this PC shows the settings it was prepared with (so loading it never asks to download); // a model that is not yet downloaded starts with Read pictures ON (owner rule: pictures on by default). This runs when the SELECTION or the @@ -158,9 +158,9 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine return; setAppliedSig(sig); if (installed) { - // The context it was prepared with when someone chose it; a model that holds the old 32K default opens at the new default. + // The context it was prepared with when someone chose it; a model that holds the old default (32K, DeepSeek's 8K) without the marker opens at the new default. if (installed.context) - setContext(selectedSize.multi_file ? installed.context : openingContext(installed.context, contextList, installed.contextChosen === true)); + setContext(openingContext(installed.context, contextList, installed.contextChosen === true, selectedSize.multi_file ? [OLD_DEEPSEEK_CONTEXT] : undefined)); // Off only when the person turned it off (a saved choice on a model that has the picture files); a model prepared without them (images 'off', or an old "off" saved while the engine had no reader) starts with it ON. setVision(installed.visionEnabled === false && installed.visionPrepared !== false ? 'no' : installed.visionDevice ?? (installed.images && installed.images !== 'off' ? installed.images : 'yes')); setKv(installed.kv ?? 'int8'); @@ -172,8 +172,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine } else { setVision('yes'); - if (!contextPicked) // a context the person picked stays; otherwise 128K, and DeepSeek runs at the one context its engine was checked at (as in the guided setup) - setContext(selectedSize.multi_file ? 8192 : defaultContext(contextList)); + if (!contextPicked) // a context the person picked stays; otherwise 128K (DeepSeek too, where its pack allows) + setContext(defaultContext(contextList)); } }, [selectedSize?.id, installed?.model, installed?.ready, installed?.context, installed?.contextChosen, installed?.kv, installed?.images, installed?.visionEnabled, installed?.visionDevice, installed?.lowRamMode, installed?.resourceProfile]); useEffect(() => { if (jobId && job?.state === 'done' && job.id !== toastedJob && (job.kind === 'load' || job.kind === 'install')) { @@ -237,7 +237,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(draftingChoices ? <div className="native-choice__col"><span className="native-choice__label">{tr("Drafting")}</span><Select ariaLabel={tr("Drafting")} value={drafting} disabled={!!active} options={draftingChoices.map(v => ({ value: v, label: tr(draftingWords[v]) }))} onChange={v => setDrafting(String(v))}/></div> : null)} <div className="native-choice__col"><span className="native-choice__label">{tr("Computer use")}</span><div className="native-resource-choice"><button aria-pressed={resourceProfile === 'work'} data-selected={resourceProfile === 'work'} onClick={() => setResourceProfile('work')}><Icon name="computer" size={20}/><span><strong>{tr("Leave 20% for my work")}</strong><small>{tr("Headroom for your other apps")}</small></span>{tr(resourceProfile === 'work' ? <Icon name="check" size={15}/> : null)}</button><button aria-pressed={resourceProfile === 'performance'} data-selected={resourceProfile === 'performance'} onClick={() => setResourceProfile('performance')}><Icon name="bolt" size={20}/><span><strong>{tr("Full performance")}</strong><small>{tr("Give Strata priority")}</small></span>{tr(resourceProfile === 'performance' ? <Icon name="check" size={15}/> : null)}</button></div></div> </div> - {tr(!selectedSize?.multi_file && contextIsTight(fitHardware.vram_gb, context, kv) ? <p className="small muted native-spill-note"><Icon name="warning" size={16}/>{tr("This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context.", [cacheGb(context, kv).toFixed(1)])}</p> : null)} + {tr(contextIsTight(fitHardware.vram_gb, context, kv) ? <p className="small muted native-spill-note"><Icon name="warning" size={16}/>{tr("This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context.", [cacheGb(context, kv).toFixed(1)])}</p> : null)} {tr(loadedSelected?.metrics?.engine?.drafting_note ? <p className="small muted native-spill-note">{tr(String(loadedSelected.metrics.engine.drafting_note))}</p> : null)} {roleCards.length > 1 ? <GpuRoles cards={roleCards} roles={effectiveRoles} custom={customRoles} recommendedRoles={recommended.roles} vendor={engineVendor} disabled={!!active} onChange={changeRoles} onBack={() => setRoles(null)} memoryGb={selectedSize ? memoryNeeded(selectedSize) || null : null} ramGb={pcRam} spillGb={selectedSize ? fitOn(selectedSize, fitHardware).spillGb : 0} usedBy={i => usedBy([i])}/> : null} {tr(roleCards.length > 1 && (native?.hardware?.gpus ?? []).length > roleCards.length ? <p className="small muted native-cards__note">{tr('Not used: {0} (another make of graphics card than this engine drives).', [(native?.hardware?.gpus ?? []).filter(g => !roleCards.some(r => r.index === g.index && r.vendor === g.vendor)).map(g => g.name).join(', ')])}</p> : null)} diff --git a/apps/host/src/lib/default-context.ts b/apps/host/src/lib/default-context.ts index 38543bb108..37c6aceb7e 100644 --- a/apps/host/src/lib/default-context.ts +++ b/apps/host/src/lib/default-context.ts @@ -21,9 +21,11 @@ export function defaultContext(choices: readonly number[] | null | undefined): n * from this update on is saved with a marker (`chosen`), whatever its size, 32K included; only an old saved 32K without a marker (the old default) moves * to the new default. */ -export function openingContext(saved: number | null | undefined, choices: readonly number[] | null | undefined, chosen = false): number { - return saved && saved > 0 && (chosen || saved !== OLD_DEFAULT_CONTEXT) ? saved : defaultContext(choices); +export function openingContext(saved: number | null | undefined, choices: readonly number[] | null | undefined, chosen = false, oldDefaults: readonly number[] = [OLD_DEFAULT_CONTEXT]): number { + return saved && saved > 0 && (chosen || !oldDefaults.includes(saved)) ? saved : defaultContext(choices); } +/** What DeepSeek-V4.1-Flash used to open with (the one context its engine was checked at): an unmarked saved 8K is that default, not a choice. */ +export const OLD_DEEPSEEK_CONTEXT = 8192; /** * Graphics memory left for the model's own data after the conversation memory of this context (the app's estimate, the same figures as the This diff --git a/apps/host/tests/deepseek-context.test.mjs b/apps/host/tests/deepseek-context.test.mjs index 694829af47..3a79a83864 100644 --- a/apps/host/tests/deepseek-context.test.mjs +++ b/apps/host/tests/deepseek-context.test.mjs @@ -82,8 +82,8 @@ test('the Models screen honours the choice (it no longer forces 8K), offers the assert.doesNotMatch(screen, /multi_file ? 8192 : context/, 'the chosen context is what is installed and loaded'); assert.match(screen, /selectedSize\?\.multi_file \? deepseekContexts\(installed\?\.contextMax\) : native\?\.catalog\?\.contexts \?\? \[8192, 32768, 65536, 131072, 262144\][\s\S]*contextChoices\(contextList, context\)/); assert.match(screen, /selectedSize\?\.multi_file && deepseekContextNote\(context\) \? <p className="small muted native-spill-note"><Icon name="info" size=\{16\}\/>\{tr\(deepseekContextNote\(context\)\)\}<\/p> : null/); - assert.match(screen, /setContext\(selectedSize\.multi_file \? 8192 : defaultContext\(contextList\)\)/, 'the default for a DeepSeek version that is not installed stays 8K'); - assert.match(screen, /setContext\(selectedSize\.multi_file \? installed\.context : openingContext/, 'an installed DeepSeek model shows and loads the context it was prepared with, whatever was kept from another model'); + assert.match(screen, /setContext\(defaultContext\(contextList\)\)/, 'a DeepSeek version that is not installed opens at 128K like every model (owner, 11-01), from its own list'); + assert.match(screen, /setContext\(openingContext\(installed\.context, contextList, installed\.contextChosen === true, selectedSize\.multi_file \? \[OLD_DEEPSEEK_CONTEXT\] : undefined\)\)/, 'an installed DeepSeek model shows and loads the context it was prepared with, whatever was kept from another model'); assert.match(screen, /installed\?\.ready && context === installed\.context/, 'a load at the prepared context starts from the saved file; only a changed choice runs setup again'); }); diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index 5ab47218bb..ba986c1721 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -57,12 +57,14 @@ test('6: the conversation context opens at 128K for every configuration, or the // The page opens with the default, ignores the engine recommended context, warns inline and never lowers by itself. assert.match(models, /useKept\('models\.context', DEFAULT_CONTEXT\)/); assert.ok(!/rec\.context/.test(models), 'the engine recommendation is not what the page opens with'); - assert.match(models, /setContext\(first\?\.multi_file \? 8192 : defaultContext\(native\.catalog\.contexts\)\)/); + assert.match(models, /setContext\(defaultContext\(first\?\.multi_file \? deepseekContexts\(\) : native\.catalog\.contexts\)\)/, 'DeepSeek too, from its own list'); assert.match(models, /contextIsTight\(fitHardware\.vram_gb, context, kv\) \? <p className="small muted native-spill-note"><Icon name="warning"/); assert.ok(!/setContext\([^)]*contextIsTight/.test(models), 'the warning never changes the context'); assert.match(models, /cache=\{\{ context, kv \}\}/, 'the version list follows the chosen context, as the card does'); const guided = read('src/components/GuidedSetup.tsx'); - assert.match(guided, /pickedContext \?\? \(contextIsTight\(topCardGb, DEFAULT_CONTEXT\) \? OLD_DEFAULT_CONTEXT : defaultContext\(native\?\.catalog\?\.contexts\)\)/); + assert.match(guided, /const context = pickedContext \?\? defaultContext\(contextList\)/, 'first-run opens at 128K on every card too'); + assert.ok(!/OLD_DEFAULT_CONTEXT|contextIsTight\(topCardGb, DEFAULT_CONTEXT/.test(guided), 'no fallback to 32K on a tight card'); + assert.match(guided, /contextIsTight\(topCardGb, context\) \? <p className="small muted native-spill-note">/, 'the same inline warning, nothing lowered'); }); test('7 and 8: Model files has no explanatory sentence and holds "Other local models..." beside Storage settings', () => { @@ -168,10 +170,10 @@ test('a context picked after this update sticks, 32K included; only an old saved assert.match(host, /\.\.\.\(args\.contextChosen===true\?\{ui_context_chosen:true\}:\{\}\)/, 'a load saves the marker'); assert.match(host, /rememberSetting\(record\(id\)\.path,'ui_context_chosen',true\)/, 'an install saves it too'); assert.match(host, /contextChosen:cfg\.ui_context_chosen===true/, 'and it is read back'); - assert.match(models, /openingContext\(installed\.context, contextList, installed\.contextChosen === true\)/); + assert.match(models, /openingContext\(installed\.context, contextList, installed\.contextChosen === true, selectedSize\.multi_file \? \[OLD_DEEPSEEK_CONTEXT\] : undefined\)/); assert.match(models, /\.\.\.\(contextPicked \? \{ contextChosen: true \} : \{\}\)/, 'a pick is sent with the install'); assert.match(models, /\.\.\.\(contextPicked && !installed\.contextChosen \? \{ contextChosen: true \} : \{\}\)/, 'and with a direct load, so a picked 32K that equals the saved one is marked too'); - assert.match(read('src/components/GuidedSetup.tsx'), /contextTouched && !fixedContext \? \{ contextChosen: true \}/); + assert.match(read('src/components/GuidedSetup.tsx'), /contextTouched \? \{ contextChosen: true \}/); }); test('the tune dialog also runs without pictures and saves nothing when the engine has no reader', () => { @@ -181,3 +183,17 @@ test('the tune dialog also runs without pictures and saves nothing when the engi assert.match(host, /vision:current\.config\.vision\?args\.vision:'no',\.\.\.\(args\.visionUnavailable===true\?\{visionUnavailable:true\}:\{\}\)/); assert.match(host, /args\.contextChosen===true\|\|JSON\.stringify\(cfg\[USER_KEY\]/, 'a load that carries the context marker writes it to the saved settings'); }); + +test('owner 11-01 (second decision): 128K on every card, in first-run setup, and for DeepSeek where its pack allows it', async () => { + const { defaultContext, openingContext, OLD_DEEPSEEK_CONTEXT } = await lib('src/lib/default-context.ts'); + const { deepseekContexts } = await lib('src/lib/deepseek-context.ts'); + assert.equal(defaultContext(deepseekContexts()), 131072, 'DeepSeek without a pack limit: 128K'); + assert.equal(defaultContext(deepseekContexts(65536)), 65536, 'a pack that stops at 64K opens at its largest'); + assert.equal(defaultContext(deepseekContexts(1048576)), 131072, 'a pack that reads 1M still opens at 128K'); + assert.equal(openingContext(8192, deepseekContexts(), false, [OLD_DEEPSEEK_CONTEXT]), 131072, 'an unmarked saved 8K is the old DeepSeek default'); + assert.equal(openingContext(8192, deepseekContexts(), true, [OLD_DEEPSEEK_CONTEXT]), 8192, 'an 8K that was picked stays'); + assert.equal(openingContext(8192, [8192, 32768, 131072]), 8192, 'for any other model an 8K is a choice (Terminal setups for small cards write it)'); + const guided = read('src/components/GuidedSetup.tsx'); + assert.ok(!/fixedContext/.test(guided) && !/\[8192\]/.test(guided), 'DeepSeek is no longer fixed at 8K in first-run setup'); + assert.match(guided, /options=\{contextList\.map\(n =>/); +}); diff --git a/setup.py b/setup.py index 7938d49a0f..a12964a0b0 100644 --- a/setup.py +++ b/setup.py @@ -805,7 +805,7 @@ DSV41_UD_FILES = { DSV41_FILES.update(DSV41_UD_FILES) # (the repository's pins: REPO_PINS) DSV41_ALL_FILES = {**DSV41_FILES, **DSV41_ISTA_FILES, **DSV41_ISTA6_FILES, **DSV41_LEGACY_FILES, **DSV41_UD_FILES} DSV41_PROFILES = ROOT / "data" / "dsv41" # the shipped hot-expert profiles (profile-2.00.bin, profile-2.25.bin, + .sha256) -DSV41_CONTEXT = 8192 # the context the engine was checked at (4096 and 8192; 64K is not tried yet) +DSV41_CONTEXT = 131072 # 128K like every model (owner, 2026-11-01; strata_control/default_context.py); the engine was checked at 4096 and 8192 before, INT3 checks 128K on real cards DSV41_MAC_VISION = False # an Apple Silicon Mac: the Metal engine has not run DeepSeek's picture tower (0.2.7.1), so pictures stay off there MULTI_FILE_FAMILIES = { "deepseek41": {"title": "DeepSeek-V4.1-Flash", "by": "DeepSeek; the 2-bit GGUFs by ISTA-DAS, UD-Q8_K_XL by Unsloth", "arch": "deepseek41", @@ -7887,7 +7887,7 @@ def engine_families(eng: Path) -> set: def own_path_context(fam: dict, vram_gb: float) -> int: """The recommended context for an own-path family: its KV cache (VRAM) beside the dense weights and the most-used experts - 32K up to 16 GB, 64K up to 24 GB, 128K above.""" - return 32768 if vram_gb <= 16.5 else 65536 if vram_gb <= 24.5 else 131072 + return 131072 # 128K on every card (owner, 2026-11-01) def own_path_size(fam: dict, ram: float) -> str: @@ -9836,9 +9836,7 @@ def main() -> int: say(f" Its license: {MODELS[model]['license']}") tag = fam["tag"] + model # names of the pack, config and start script small = min(x["vram_gb"] for x in chosen) # each card keeps its layers' KV of the whole context - rec_ctx = 32768 if small < 14 else 65536 if small < 20 else 131072 - if budget is not None: # UD-Q4_K_XL: every GB of KV is a GB fewer of cached experts - rec_ctx = 8192 if small < 14 else 32768 + rec_ctx = 131072 # 128K on every card (owner, 2026-11-01); a card it leaves little room on is warned about below, never lowered # #406: the RAM rule is part of the recommendation (the smaller of the two), no longer a cap over the user's choice rec_ctx = min(rec_ctx, ram_ctx(model, ram, low_ram)) if a.context: diff --git a/strata_cli/launch/catalog.py b/strata_cli/launch/catalog.py index 6d7d2a40c0..e298cc29a9 100644 --- a/strata_cli/launch/catalog.py +++ b/strata_cli/launch/catalog.py @@ -442,38 +442,15 @@ class Catalog: return tokens * 13 * table.get(kv, 1056) / 1e9 def max_context(self, family: str, model: str, hw: dict | None = None) -> int | None: - """The recommended context for this computer and model (setup.py: VRAM rule, then the RAM rule).""" + """The context a model starts with: 128K on every card, or the largest size the model offers under it (strata_control/default_context.py, + the one rule of the app, the Terminal and setup). A Mac keeps its unified-memory rule.""" + from strata_control import default_context hw = hw or self.hardware() - if self.strata.multi_family(family): # DeepSeek-V4.1-Flash: the context the engine was checked at - return int(getattr(self.strata.setup_module(), "DSV41_CONTEXT", 8192)) - if hw.get("mac") and hw.get("ram_gb"): # a Mac: the context by unified memory (strata_control/mac_fit.py) - mac = self.strata.mac() + if hw.get("mac") and hw.get("ram_gb") and not self.strata.multi_family(family): + mac = self.strata.mac() # a Mac: the context by unified memory (strata_control/mac_fit.py) if mac is not None: return int(mac.recommend_context(float(hw["ram_gb"]))) - usable = [g for g in hw.get("gpus") or [] if g.get("usable", True)] - vram = max((float(g.get("vram_gb") or 0) for g in usable), default=12.0) - rec = 32768 if vram < 14 else 65536 if vram < 20 else 131072 - if usable and all(g.get("vendor") == "intel" for g in usable): - rec = 8192 if vram < 10 else 16384 if vram < 20 else 32768 # an Arc keeps the session and the experts in the same memory - mod = self.strata.setup_module() - models = self.tables()[0] - if mod is not None and models[model].get("budget"): - try: - if mod.unsloth_budget(model, hw.get("ram_gb") or 0.0): - rec = 8192 if vram < 14 else 32768 - except Exception: # noqa: BLE001 - pass - if mod is not None and hasattr(mod, "ram_ctx") and hw.get("ram_gb"): - try: - rec = min(rec, int(mod.ram_ctx(model, hw["ram_gb"], False))) - except Exception: # noqa: BLE001 - pass - if usable: # 0.2.2: a model a few hundred MiB short on this card gets the next context down - from strata_control import vram_fit - best = max(usable, key=lambda g: float(g.get("vram_gb") or 0)) - rec = vram_fit.fit_context(f"{family} {model}", float(best.get("vram_gb") or 0), rec, "int8", 300, - str(best.get("vendor") or "")) - return rec + return default_context.pick(self.contexts_for(family, model)) # ---- pictures def engine_backend(self) -> str | None: diff --git a/strata_control/default_context.py b/strata_control/default_context.py new file mode 100644 index 0000000000..b2bbe0d681 --- /dev/null +++ b/strata_control/default_context.py @@ -0,0 +1,19 @@ +"""The conversation context a model starts with: 128K on every card, unless the person picks another (owner, 2026-11-01). + +One rule for the app (apps/host/src/lib/default-context.ts says the same), the Terminal (`strata launch`, `setup`) and the MCP tools: 128K, or the +largest size the model offers when that is under 128K (DeepSeek-V4.1-Flash: up to its pack's own limit). The VRAM tiers that used to lower it on small +cards are gone; a card that 128K leaves little room on gets a warning, never a lower number (the engine says plainly if it cannot start). +A Mac keeps its unified-memory rule (strata_control/mac_fit.py), which the owner has not changed. +""" +from __future__ import annotations + +from typing import Iterable + +DEFAULT_CONTEXT = 131072 + + +def pick(sizes: Iterable[int] | None = None) -> int: + """128K, or the largest of `sizes` under it, or (when every size is longer) the smallest.""" + have = sorted(int(s) for s in (sizes or ()) if int(s) > 0) + under = [s for s in have if s <= DEFAULT_CONTEXT] + return under[-1] if under else (have[0] if have else DEFAULT_CONTEXT) diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index ff89d11abb..acbe73b95f 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -1252,7 +1252,7 @@ class Strata: return {"family": None, "model": None, "why": f"{ram:.0f} GB of RAM: Strata needs 32 GB or more " "(the smallest model, the Coder, keeps ~23 GB of experts in " "RAM)"} - ctx = 32768 if vram < 14 else 65536 if vram < 20 else 131072 + ctx = 131072 # 128K on every card (owner, 2026-11-01) # #3425: the tiers count RAM + VRAM together, but the desktop keeps about 10 GB of the RAM and the card keeps ~6 GB for # its dense weights, so a PC at the floor of its tier reads part of the experts from the SSD at every answer. Said # plainly beside the pick (the same arithmetic as the app's "This computer" card); the pick itself stays the owner's tier. @@ -2350,10 +2350,7 @@ class Tools: if context is None: usable = s.engine_gpus(hw) vram = max((g["vram_gb"] for g in usable), default=12) - context = 32768 if vram < 14 else 65536 if vram < 20 else 131072 - if md.get("budget") and (not hasattr(s.setup_module(), "unsloth_budget") or - s.setup_module().unsloth_budget(model, hw.get("ram_gb") or 0.0)): - context = 8192 if vram < 14 else 32768 + context = 131072 # 128K on every card (owner, 2026-11-01; strata_control/default_context.py) if vision in ("yes", "gpu", "cpu") and md.get("vision", families[family].get("vision")) is False: raise ToolError(f"images are not available with {families[family]['title']} {model} yet: use vision=no") if vision is None: From d29a6640e43e4c165eb5f4a6c544e33dc9e7392d Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:44:39 +0100 Subject: [PATCH 46/59] Chat: a file or command the model is writing right now is drawn from message.drafts through the open activity line: the file and its growing size, the last three lines when they read well, in a box that never changes height; drawn about three times a second, nothing animates --- apps/host/scripts/make-r3-locales.py | 4 +++ apps/host/src/components/Deliverables.tsx | 34 +++++++++++++++++++++-- apps/host/src/lib/deliverables.ts | 5 +++- apps/host/src/lib/draft-view.ts | 33 ++++++++++++++++++++++ apps/host/src/locales/r3-de.json | 3 +- apps/host/src/locales/r3-en.json | 3 +- apps/host/src/locales/r3-es.json | 3 +- apps/host/src/locales/r3-fr.json | 3 +- apps/host/src/locales/r3-ja.json | 3 +- apps/host/src/locales/r3-ko.json | 3 +- apps/host/src/locales/r3-pt.json | 3 +- apps/host/src/locales/r3-ru.json | 3 +- apps/host/src/locales/r3-zh.json | 3 +- apps/host/src/screens/Chat.tsx | 8 ++++-- apps/host/src/styles/app.css | 5 ++++ apps/host/tests/ui-r3.test.mjs | 25 ++++++++++++++++- 16 files changed, 125 insertions(+), 16 deletions(-) create mode 100644 apps/host/src/lib/draft-view.ts diff --git a/apps/host/scripts/make-r3-locales.py b/apps/host/scripts/make-r3-locales.py index 560b9c5838..1be1715ae1 100644 --- a/apps/host/scripts/make-r3-locales.py +++ b/apps/host/scripts/make-r3-locales.py @@ -40,6 +40,10 @@ add("Working · {0}", add("{0} chats working", "{0} 个对话进行中", "{0} 件のチャットが作業中", "{0} Chats in Arbeit", "{0} chats trabajando", "В работе чатов: {0}", "{0} chats trabalhando", "대화 {0}개 작업 중", "{0} conversations en cours") +# 10: the size line of a file being written +add("{0} lines", + "{0} 行", "{0} 行", "{0} Zeilen", "{0} líneas", "{0} строк", "{0} linhas", "{0}줄", "{0} lignes") + #@@MORE@@ here = Path(__file__).resolve().parent.parent / "src" / "locales" diff --git a/apps/host/src/components/Deliverables.tsx b/apps/host/src/components/Deliverables.tsx index 0b49aae159..21271f331b 100644 --- a/apps/host/src/components/Deliverables.tsx +++ b/apps/host/src/components/Deliverables.tsx @@ -1,7 +1,9 @@ -import { useRef, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { tr } from '../lib/i18n'; import { fileAction, fileSize, fileTypeLabel, previewOf, rawUrlOf, type ActivityGroup, type Deliverable } from '../lib/deliverables'; import type { PreviewArtifact } from '../lib/artifacts'; +import { draftSize, groupFromDraft } from '../lib/draft-view'; +import type { ToolDraft } from '../lib/types'; import { pushToast } from '../lib/store'; import { plainFailureText } from '../lib/plain-errors'; import { FloatingMenu } from './FloatingMenu'; @@ -84,7 +86,7 @@ export function ActivityLine({ group, sessionId, onPreview }: { group: ActivityG const live = !group.closed; return <><div className="act" data-open={open || undefined} data-live={live || undefined}> <button type="button" className="act__line" aria-expanded={open} disabled={!group.files.length} onClick={() => setOpen(v => !v)}> - <span>{live && group.live?.label ? group.live.label : sentence}</span>{group.added || group.removed ? <Plusminus added={group.added} removed={group.removed}/> : null} + <span>{live && group.live?.label ? group.live.label : sentence}</span>{live && group.live?.bytes ? <span className="act__meta">{draftSize(group.live.bytes)}{group.live.lines && group.live.lines > 1 ? <> {"\u00B7"} {tr("{0} lines", [group.live.lines])}</> : null}</span> : null}{group.added || group.removed ? <Plusminus added={group.added} removed={group.removed}/> : null} {group.files.length ? <Icon name="chevron" size={14} className="act__chev"/> : null} {!group.closed ? <span className="act__live" aria-hidden="true"/> : null} </button> @@ -92,5 +94,33 @@ export function ActivityLine({ group, sessionId, onPreview }: { group: ActivityG {open ? <ul className="act__files">{group.files.map(f => <li key={f.path}><button type="button" onClick={() => void showOf(f, sessionId, onPreview, f.kind)}><Icon name="file" size={14}/>{f.name}{f.added || f.removed ? <Plusminus added={f.added} removed={f.removed}/> : null}</button></li>)}</ul> : null} </div> {live && group.live?.output ? <p className="act__output" title={group.live.output}>{group.live.output}</p> : null} + {live && group.live?.tail !== undefined ? <div className="act__tail" aria-hidden="true">{group.live.tail.split('\n').filter(Boolean).map((line, i) => <span key={i}>{line}</span>)}</div> : null} </>; } + +/** The value, at most every `ms` (a file arrives about five times a second; the eye needs two). A cleared value is shown at once. */ +function useThrottled<T>(value: T, ms: number, cleared: (v: T) => boolean): T { + const [shown, setShown] = useState(value), last = useRef(0), timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); + useEffect(() => { + clearTimeout(timer.current); + if (cleared(value)) { setShown(value); return; } + const wait = Math.max(0, last.current + ms - Date.now()); + timer.current = setTimeout(() => { last.current = Date.now(); setShown(value); }, wait); + return () => clearTimeout(timer.current); + }, [value, ms]); + return shown; +} + +/** + * The files (or commands) the model is writing right now, from `message.drafts`: each is one open activity line with the file's name, its growing size + * and the last lines of its text. It draws nothing while there is nothing being written, and takes the place of the ordinary card when the call is whole. + */ +export function DraftLines({ drafts, sessionId, onPreview }: { drafts: ToolDraft[] | undefined; sessionId: string; onPreview: (a: PreviewArtifact) => void }) { + const shown = useThrottled(drafts, 350, v => !v?.length); + if (!drafts?.length || !shown?.length) return null; + return <>{shown.map(d => { + const file = d.target ? d.target.split(/[\\/]/).filter(Boolean).at(-1) : ''; + const verb = tr(d.verb ?? (d.scope === 'shell' ? 'Running a command' : 'Writing a file')); + return <ActivityLine key={d.id} group={groupFromDraft(d, file ? `${verb} · ${file}` : verb)} sessionId={sessionId} onPreview={onPreview}/>; + })}</>; +} diff --git a/apps/host/src/lib/deliverables.ts b/apps/host/src/lib/deliverables.ts index 66ae675c14..d2d2bc4ddb 100644 --- a/apps/host/src/lib/deliverables.ts +++ b/apps/host/src/lib/deliverables.ts @@ -13,7 +13,9 @@ export interface Deliverable { path: string; abs: string; name: string; kind: De export interface GroupFile { path: string; name: string; kind: DeliverableKind; status: string; added: number; removed: number } /** What is happening in a run right now (the host sends it while the group is open and drops it when the group closes): `label` is the step in plain words * ("Writing pagoda.html"), `output` the last line the step printed or the progress it can name ("412 lines written"). Optional: a group without it draws as before. */ -export interface GroupLive { label?: string; output?: string } +export interface GroupLive { label?: string; output?: string; + /** A file being written right now (from `message.drafts`): characters so far, lines so far and the last lines of the text. */ + bytes?: number; lines?: number; tail?: string } export interface ActivityGroup { id: string; closed: boolean; line: string; added: number; removed: number; files: GroupFile[]; live?: GroupLive } export type MessageBlock = { kind: 'text'; text: string } | ({ kind: 'group' } & ActivityGroup); @@ -133,3 +135,4 @@ export const fileAction = { }; export const rawUrlOf = (sessionId: string, path: string) => `/api/files/raw?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(path)}`; + diff --git a/apps/host/src/lib/draft-view.ts b/apps/host/src/lib/draft-view.ts new file mode 100644 index 0000000000..ff322c8092 --- /dev/null +++ b/apps/host/src/lib/draft-view.ts @@ -0,0 +1,33 @@ +import type { ActivityGroup } from './deliverables'; +import type { ToolDraft } from './types'; + +/** + * A tool call the model is still writing (`message.drafts`, the host's `agent-tool-draft` frames: a whole file in one call, say) drawn through the + * open activity line: the verb and the file, its growing size and line count, and the tail of its text when that reads well. + */ + +/** "18 KB", the way the "cut" sentence says it (thousands, not 1,024s), one decimal under 10 KB. */ +export function draftSize(bytes: number): string { + if (!(bytes > 0)) return '0 KB'; + if (bytes < 100) return `${Math.round(bytes)} B`; + return bytes >= 10_000 ? `${Math.round(bytes / 1000)} KB` : `${(bytes / 1000).toFixed(1)} KB`; +} + +/** The last lines of a draft's text, if they read well (words and code, not a wall of escapes); at most `count` lines of 160 characters, else none. */ +export function draftTail(preview: string | undefined, count = 3): string[] { + const lines = String(preview ?? '').replace(/\t/g, ' ').split(/\r?\n/).map(l => l.replace(/\s+$/, '')).filter(l => l.trim()).slice(-count).map(l => l.slice(0, 160)); + const text = lines.join(''); + if (text.length < 12) return []; + const printable = [...text].filter(c => c >= ' ' && c !== '\u007f').length / text.length; + const wordy = (text.match(/[A-Za-z]{2,}/g) ?? []).length; + return printable > 0.95 && wordy >= 2 ? lines : []; +} + +/** Whether a draft has a place for its text (a file or a command): the box is kept from the start so the line does not grow when the text arrives. */ +export const draftHasTail = (d: Pick<ToolDraft, 'scope'>) => d.scope === 'write' || d.scope === 'shell'; + +/** The activity line for one draft: `label` is the plain sentence ("Writing pagoda.html"), already in the person's language. */ +export function groupFromDraft(draft: ToolDraft, label: string): ActivityGroup { + const tail = draftHasTail(draft) ? draftTail(draft.preview) : []; + return { id: `draft-${draft.id}`, closed: false, line: label, added: 0, removed: 0, files: [], live: { label, bytes: draft.bytes, lines: draft.lines, ...(draftHasTail(draft) ? { tail: tail.join('\n') } : {}) } }; +} diff --git a/apps/host/src/locales/r3-de.json b/apps/host/src/locales/r3-de.json index 6408ed125f..c81ce407dc 100644 --- a/apps/host/src/locales/r3-de.json +++ b/apps/host/src/locales/r3-de.json @@ -3,5 +3,6 @@ "r3_02": "SSD-Streaming · läuft langsamer", "r3_03": "So viel Kontext belegt etwa {0} GB Grafikspeicher und lässt auf dieser Karte wenig Platz für das Modell. Strata versucht es; startet es nicht, wähle einen kürzeren Kontext.", "r3_04": "In Arbeit · {0}", - "r3_05": "{0} Chats in Arbeit" + "r3_05": "{0} Chats in Arbeit", + "r3_06": "{0} Zeilen" } diff --git a/apps/host/src/locales/r3-en.json b/apps/host/src/locales/r3-en.json index a5f9cdd9f9..7fd0f0c567 100644 --- a/apps/host/src/locales/r3-en.json +++ b/apps/host/src/locales/r3-en.json @@ -3,5 +3,6 @@ "r3_02": "SSD streaming · will run slower", "r3_03": "This much context takes about {0} GB of graphics memory and leaves little room for the model on this card. Strata will try it; if it does not start, choose a shorter context.", "r3_04": "Working · {0}", - "r3_05": "{0} chats working" + "r3_05": "{0} chats working", + "r3_06": "{0} lines" } diff --git a/apps/host/src/locales/r3-es.json b/apps/host/src/locales/r3-es.json index 9b14199500..8e5adc3ccd 100644 --- a/apps/host/src/locales/r3-es.json +++ b/apps/host/src/locales/r3-es.json @@ -3,5 +3,6 @@ "r3_02": "Streaming desde el SSD · irá más lento", "r3_03": "Este contexto ocupa unos {0} GB de memoria gráfica y deja poco espacio para el modelo en esta tarjeta. Strata lo intentará; si no arranca, elige un contexto más corto.", "r3_04": "Trabajando · {0}", - "r3_05": "{0} chats trabajando" + "r3_05": "{0} chats trabajando", + "r3_06": "{0} líneas" } diff --git a/apps/host/src/locales/r3-fr.json b/apps/host/src/locales/r3-fr.json index d1bbcf1387..924db440b9 100644 --- a/apps/host/src/locales/r3-fr.json +++ b/apps/host/src/locales/r3-fr.json @@ -3,5 +3,6 @@ "r3_02": "Streaming depuis le SSD · plus lent", "r3_03": "Ce contexte occupe environ {0} Go de mémoire graphique et laisse peu de place au modèle sur cette carte. Strata va essayer ; s’il ne démarre pas, choisissez un contexte plus court.", "r3_04": "En cours de travail · {0}", - "r3_05": "{0} conversations en cours" + "r3_05": "{0} conversations en cours", + "r3_06": "{0} lignes" } diff --git a/apps/host/src/locales/r3-ja.json b/apps/host/src/locales/r3-ja.json index 6075400211..b4f1d5a6bd 100644 --- a/apps/host/src/locales/r3-ja.json +++ b/apps/host/src/locales/r3-ja.json @@ -3,5 +3,6 @@ "r3_02": "SSD ストリーミング · 動作は遅くなります", "r3_03": "このコンテキストはグラフィックスメモリーを約 {0} GB 使い、このカードではモデルに残る余裕がわずかです。Strata は試しますが、起動しない場合はより短いコンテキストを選んでください。", "r3_04": "作業中 · {0}", - "r3_05": "{0} 件のチャットが作業中" + "r3_05": "{0} 件のチャットが作業中", + "r3_06": "{0} 行" } diff --git a/apps/host/src/locales/r3-ko.json b/apps/host/src/locales/r3-ko.json index 6a03a09a19..4b63095534 100644 --- a/apps/host/src/locales/r3-ko.json +++ b/apps/host/src/locales/r3-ko.json @@ -3,5 +3,6 @@ "r3_02": "SSD 스트리밍 · 더 느리게 실행됩니다", "r3_03": "이 정도의 컨텍스트는 그래픽 메모리를 약 {0} GB 사용하며 이 카드에서는 모델이 쓸 공간이 거의 남지 않습니다. Strata가 시도하지만 시작되지 않으면 더 짧은 컨텍스트를 선택하세요.", "r3_04": "작업 중 · {0}", - "r3_05": "대화 {0}개 작업 중" + "r3_05": "대화 {0}개 작업 중", + "r3_06": "{0}줄" } diff --git a/apps/host/src/locales/r3-pt.json b/apps/host/src/locales/r3-pt.json index b5a20a554d..bbff35ac2f 100644 --- a/apps/host/src/locales/r3-pt.json +++ b/apps/host/src/locales/r3-pt.json @@ -3,5 +3,6 @@ "r3_02": "Streaming do SSD · vai rodar mais devagar", "r3_03": "Esse contexto ocupa cerca de {0} GB de memória gráfica e deixa pouco espaço para o modelo nesta placa. O Strata vai tentar; se não iniciar, escolha um contexto menor.", "r3_04": "Trabalhando · {0}", - "r3_05": "{0} chats trabalhando" + "r3_05": "{0} chats trabalhando", + "r3_06": "{0} linhas" } diff --git a/apps/host/src/locales/r3-ru.json b/apps/host/src/locales/r3-ru.json index 75f021fe20..6fc034412d 100644 --- a/apps/host/src/locales/r3-ru.json +++ b/apps/host/src/locales/r3-ru.json @@ -3,5 +3,6 @@ "r3_02": "Потоковая подгрузка с SSD · будет работать медленнее", "r3_03": "Такой контекст занимает около {0} ГБ видеопамяти и оставляет модели мало места на этой карте. Strata попробует запустить; если не получится, выберите контекст короче.", "r3_04": "В работе · {0}", - "r3_05": "В работе чатов: {0}" + "r3_05": "В работе чатов: {0}", + "r3_06": "{0} строк" } diff --git a/apps/host/src/locales/r3-zh.json b/apps/host/src/locales/r3-zh.json index 429318d98a..7270735e9f 100644 --- a/apps/host/src/locales/r3-zh.json +++ b/apps/host/src/locales/r3-zh.json @@ -3,5 +3,6 @@ "r3_02": "SSD 流式读取 · 运行会更慢", "r3_03": "这么长的上下文大约占用 {0} GB 显存,留给模型的空间很少。Strata 会尝试运行;如果无法启动,请选择更短的上下文。", "r3_04": "进行中 · {0}", - "r3_05": "{0} 个对话进行中" + "r3_05": "{0} 个对话进行中", + "r3_06": "{0} 行" } diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 23e9b1fb4d..e459404cc6 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -26,7 +26,7 @@ import { GoalBar } from '../components/GoalBar'; import { PlanCard, PlanPanel, QueuedMessages } from '../components/PlanCard'; import { FolderChip } from '../components/FolderChip'; import { DropZone, DROP_EVENT, pastedFiles } from '../components/DropZone'; -import { ActivityLine, EditedFiles, FileCard, SkillsUsed } from '../components/Deliverables'; +import { ActivityLine, DraftLines, EditedFiles, FileCard, SkillsUsed } from '../components/Deliverables'; import { queueMessage, usePlan, usePlanQuiet } from '../lib/plan'; import { plainFailureText } from '../lib/plain-errors'; import { contextRecovery } from '../lib/context-recovery'; @@ -752,7 +752,7 @@ function MessageView({ message: m, isLast, onEditPrompt, onPreview, onClosePrevi card stays only for what needs the person: a question waiting, a denied or failed call. A card that came and went above the text moved the whole reply. */} {tr((m.tools ?? []).filter(t => !grouped || t.state === 'proposed' || t.state === 'denied' || t.state === 'error').map((t) => (<ToolCard key={t.id} tool={t}/>)))} - {tr(!(m.timeSkipId && timeSkipReal && !timeSkipDone) && (m.content || m.error || !m.streaming || !liveStatus) ? <div className="st-bubble"> + {tr(!(m.timeSkipId && timeSkipReal && !timeSkipDone) && (m.content || m.error || !m.streaming || !liveStatus || !!m.drafts?.length) ? <div className="st-bubble"> {tr(planCard ? <PlanCard chatId={activeSession} planId={m.planId!}/> : null)} {tr(m.error ? (<ErrorNotice message={m.error} detail={m.errorDetail} {...contextRecovery(m.errorCode)}/>) : null)} {tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? <ActivityLine key={b.id} group={b} sessionId={activeSession ?? ''} onPreview={onPreview}/> : <Markdown key={i} text={b.text} onOpenLink={onOpenLink} imageSession={activeSession} previewId={`${m.id}-b${i}`} onPreview={onPreview} onClosePreview={onClosePreview}/>) : null)} @@ -761,8 +761,10 @@ function MessageView({ message: m, isLast, onEditPrompt, onPreview, onClosePrevi <i /> <i /> </span>) : null)} + {/* a file or command the model is writing right now: its name, growing size and the last lines of it (live data from the host, see ToolDraft) */} + {tr(m.streaming && m.drafts?.length && !planCard ? <DraftLines drafts={m.drafts} sessionId={activeSession ?? ''} onPreview={onPreview}/> : null)} {/* the caret follows the text being written; after an activity line it hung on a row of its own and the reply jumped when the text went on */} - {tr(m.streaming && m.content && (!grouped || m.blocks!.at(-1)?.kind === 'text') ? <span className="caret" aria-hidden="true"/> : null)} + {tr(m.streaming && m.content && !m.drafts?.length && (!grouped || m.blocks!.at(-1)?.kind === 'text') ? <span className="caret" aria-hidden="true"/> : null)} </div> : null)} {tr(m.skills?.length && !m.streaming ? <SkillsUsed skills={m.skills}/> : null)} {tr(m.deliverables?.length && !m.streaming ? <div className="deliverables">{m.deliverables.map(f => <FileCard key={f.path} file={f} sessionId={activeSession ?? ''} onPreview={onPreview}/>)}<EditedFiles files={m.deliverables} sessionId={activeSession ?? ''} onPreview={onPreview}/></div> : null)} diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index 16a0dabfcd..f7014cb8b4 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7446,6 +7446,11 @@ textarea { .act__live { width: 6px; height: 6px; border-radius: 50%; background: var(--st-accent); animation: st-pulse 1.6s var(--st-ease-in-out) infinite; } /* The step that is running reads as the current one (ink, not the muted past-tense of the lines above it) and its last output sits under it on one fixed line. */ .act[data-live] .act__line { color: var(--st-ink); } +/* A file the model is writing right now: its size beside the name (figures do not jitter), and the last three lines in a box that is always three lines + high, the newest line at the bottom, so nothing under it moves while the text grows. Nothing here animates (the one dot pulse is gated already). */ +.act__meta { color: var(--st-ink-muted); font-size: var(--st-fs-xs); font-variant-numeric: tabular-nums; white-space: nowrap; } +.act__tail { display: flex; flex-direction: column; justify-content: flex-end; gap: 0; box-sizing: border-box; max-width: 72ch; height: calc(3 * 1.45 * var(--st-fs-xs) + 16px); margin: -2px 0 8px; padding: 8px 12px; overflow: hidden; border-radius: var(--st-r-md); background: var(--st-surface-2); font-family: var(--st-font-mono); font-size: var(--st-fs-xs); line-height: 1.45; color: var(--st-ink-muted); } +.act__tail > span { display: block; flex: none; overflow: hidden; white-space: pre; text-overflow: ellipsis; } .act__output { margin: -4px 0 8px; padding-left: 1px; min-height: 1.4em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--st-font-mono); font-size: var(--st-fs-xs); line-height: 1.4; color: var(--st-ink-muted); } .act__thumb { width: 44px; height: 30px; object-fit: cover; border-radius: 6px; border: 1px solid var(--st-line); cursor: pointer; } .act__files { flex-basis: 100%; list-style: none; margin: 0; padding: 0 0 0 4px; display: flex; flex-direction: column; } diff --git a/apps/host/tests/ui-r3.test.mjs b/apps/host/tests/ui-r3.test.mjs index ba986c1721..58955b81d5 100644 --- a/apps/host/tests/ui-r3.test.mjs +++ b/apps/host/tests/ui-r3.test.mjs @@ -128,7 +128,7 @@ test('10 (visual): the reply stays still while it streams, one live cue per step // In a reply with activity lines the line is the one live cue for a tool; the running card above the text is gone. assert.match(chat, /filter\(t => !grouped \|\| t\.state === 'proposed' \|\| t\.state === 'denied' \|\| t\.state === 'error'\)/); // The caret follows text, never an activity line. - assert.match(chat, /m\.streaming && m\.content && \(!grouped \|\| m\.blocks!\.at\(-1\)\?\.kind === 'text'\) \? <span className="caret"/); + assert.match(chat, /m\.streaming && m\.content && !m\.drafts\?\.length && \(!grouped \|\| m\.blocks!\.at\(-1\)\?\.kind === 'text'\) \? <span className="caret"/); // A slot for what the host knows while a run is open (AGENT-LOST feeds it): read, shown, dropped at close. const { readGroup } = await lib('src/lib/deliverables.ts'); const open = readGroup({ id: 'g', closed: false, line: 'Writing pagoda.html', live: { label: 'Writing pagoda.html', output: 'a\nb\n412 lines written\n' } }); @@ -197,3 +197,26 @@ test('owner 11-01 (second decision): 128K on every card, in first-run setup, and assert.ok(!/fixedContext/.test(guided) && !/\[8192\]/.test(guided), 'DeepSeek is no longer fixed at 8K in first-run setup'); assert.match(guided, /options=\{contextList\.map\(n =>/); }); + +test('10 (live file write): message.drafts is drawn through the open activity line: file, growing size, the tail only if it reads well, no jumps', async () => { + const { draftSize, draftTail, groupFromDraft } = await lib('src/lib/draft-view.ts'); + assert.equal(draftSize(0), '0 KB'); assert.equal(draftSize(80), '80 B'); assert.equal(draftSize(7800), '7.8 KB'); assert.equal(draftSize(18720), '19 KB', 'the same thousands as the cut sentence'); + const code = ['<!doctype html>', '<html lang="en">', '<head><meta charset="utf-8"></head>', '<script type="module">', 'const scene = new THREE.Scene();'].join('\n'); + assert.deepEqual(draftTail(code), ['<head><meta charset="utf-8"></head>', '<script type="module">', 'const scene = new THREE.Scene();'], 'the last three lines'); + assert.deepEqual(draftTail(''), [], 'nothing yet'); + assert.deepEqual(draftTail('\u00e9\u0001\u0002 \u0003\u0004\u0005\u0006\u0007\u0008\u000b\u000c\u000e\u000f'), [], 'a wall of control characters is not shown'); + assert.deepEqual(draftTail('{"a":1,"b":2,"c":3,"d":4,"e":5}'), [], 'a line without words is not shown'); + const draft = { id: 't1', name: 'write_file', target: 'pagoda.html', bytes: 7800, lines: 165, preview: code, scope: 'write', verb: 'Writing' }; + const g = groupFromDraft(draft, 'Writing · pagoda.html'); + assert.equal(g.closed, false); assert.equal(g.live.bytes, 7800); assert.equal(g.live.lines, 165); assert.match(g.live.tail, /THREE\.Scene/); + assert.equal(groupFromDraft({ ...draft, scope: 'edit' }, 'x').live.tail, undefined, 'a tool that is not a write or a command has no text box'); + assert.equal(groupFromDraft({ ...draft, preview: '' }, 'x').live.tail, '', 'the box is kept from the start (empty) so it does not appear later and push the text down'); + const deliver = read('src/components/Deliverables.tsx'), chat = read('src/screens/Chat.tsx'), app = read('src/styles/app.css'); + assert.match(deliver, /useThrottled\(drafts, 350,/, 'about five frames a second are drawn about three times a second'); + assert.match(deliver, /<div className="act__tail" aria-hidden="true">/); + assert.match(chat, /m\.streaming && m\.drafts\?\.length && !planCard \? <DraftLines drafts=\{m\.drafts\}/); + assert.match(chat, /\|\| !!m\.drafts\?\.length\) \? <div className="st-bubble">/, 'the reply shows before any text, as soon as a file starts'); + assert.match(chat, /!m\.drafts\?\.length && \(!grouped/, 'no caret while a file is being written'); + assert.match(app, /\.act__tail \{[^}]*height: calc\(3 \* 1\.45 \* var\(--st-fs-xs\) \+ 16px\);[^}]*overflow: hidden;/, 'a box that is always three lines high'); + assert.ok(!/animation|transition/.test(app.slice(app.indexOf('.act__meta {'), app.indexOf('.act__output {'))), 'nothing in the write line animates, so reduced motion has nothing to hold still'); +}); From 6dbf88c78489225bae5d4debdbe9ed078bddc9a0 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:59:32 +0100 Subject: [PATCH 47/59] Line endings of the files the agent-lost branch changed go back to LF (it saved whole files as CRLF; ui-do and anything that reads them by line broke); only its real changes remain --- apps/host/scripts/agent-lost-e2e.mjs | 362 +- apps/host/server/agent/README.md | 334 +- apps/host/server/agent/agent-bridge.mjs | 2918 +++++------ apps/host/server/agent/events.mjs | 992 ++-- .../server/agent/plugins/strata-context.mjs | 410 +- apps/host/server/agent/reply-cut.mjs | 244 +- apps/host/server/folder-dialog.mjs | 414 +- apps/host/src/lib/store.ts | 4390 ++++++++--------- apps/host/src/lib/types.ts | 1082 ++-- apps/host/tests/agent-lost.test.mjs | 370 +- apps/host/tests/agent-tools.test.mjs | 574 +-- apps/host/tests/folder-dialog.test.mjs | 364 +- 12 files changed, 6227 insertions(+), 6227 deletions(-) diff --git a/apps/host/scripts/agent-lost-e2e.mjs b/apps/host/scripts/agent-lost-e2e.mjs index 787ba89fad..642b2f25c8 100644 --- a/apps/host/scripts/agent-lost-e2e.mjs +++ b/apps/host/scripts/agent-lost-e2e.mjs @@ -1,181 +1,181 @@ -#!/usr/bin/env node -/** - * AGENT-LOST end to end: a long single-file write through the real agent bridge, the real Harness and a real engine. - * - * STRATA_HARNESS_DIR=<harness folder> node scripts/agent-lost-e2e.mjs [pagoda|long|cut ...] - * - * Scenarios (default: all) - * pagoda the owner's own prompt ("Write me a 100 voxel pagoda in one html file with garden."), thinking Medium, bypass mode - * long a deterministic long write: one file of N numbered lines (E2E_LINES, default 1800, about 22K tokens), thinking Off - * raw the model server alone: a reply cut inside a tool call, as the client receives it - * cut the same long write with the Harness told a small window (E2E_CUT_WINDOW, default 24000), so the reply budget is - * about 7K tokens and the reply is cut inside the tool call: the turn must say so in words and the agent must carry on - * - * A model server that is already running is used when E2E_BASE_URL is set (nothing is started or stopped). Otherwise this - * starts serve/server.py as its own child with the engine named below and stops it by PID. - * - * Environment: E2E_ENGINE (strata executable), E2E_PACK, E2E_GGUF1, E2E_GGUF2, E2E_MTP, E2E_PROFILE, E2E_LIB (library folder), - * E2E_PORT (18590), E2E_WINDOW (65536), E2E_OUT (result folder), E2E_PYTHON. - * - * It prints one table and writes <E2E_OUT>/result.json with the frames summary of each scenario. - */ -import { spawn } from 'node:child_process'; -import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; - -const REPO = join(import.meta.dirname, '..', '..', '..'); -const env = (name, fallback) => process.env[name] ?? fallback; -const HOME = process.env.HOME ?? ''; -const PORT = Number(env('E2E_PORT', '18590')); -const WINDOW = Number(env('E2E_WINDOW', '65536')); -const EXISTING = process.env.E2E_BASE_URL ?? ''; -const PYTHON = env('E2E_PYTHON', 'python3'); -const OUT = env('E2E_OUT', mkdtempSync(join(tmpdir(), 'strata-agent-lost-'))); -const LINES = Number(env('E2E_LINES', '1400')); -const wanted = process.argv.slice(2); -const want = id => wanted.length === 0 || wanted.includes(id); -mkdirSync(OUT, { recursive: true }); - -if (!process.env.STRATA_HARNESS_DIR) { console.error('STRATA_HARNESS_DIR is not set'); process.exit(2); } -const sleep = ms => new Promise(r => setTimeout(r, ms)); - -let server = null, bridge = null; -const finish = async (code) => { - try { await bridge?.close(); } catch { /* going away */ } - if (server?.pid) { try { process.kill(-server.pid, 'SIGTERM'); } catch { try { process.kill(server.pid, 'SIGTERM'); } catch { /* gone */ } } } - await sleep(1500); - console.log(`\nresult folder: ${OUT}`); - process.exit(code); -}; -process.on('SIGINT', () => finish(130)); - -if (!EXISTING) { - const pack = env('E2E_PACK', join(HOME, '026q/pack-iq3s')); - const g1 = env('E2E_GGUF1', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf')); - const g2 = env('E2E_GGUF2', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf')); - const mtp = env('E2E_MTP', join(HOME, 'pr1426/mtp-rt')); - const profile = env('E2E_PROFILE', join(HOME, 'bwm/cnt3/data/expert-profile.bin')); - const exe = env('E2E_ENGINE', join(HOME, 'agentlost/eng/strata')); - const lib = env('E2E_LIB', join(HOME, 'agentlost/eng')); - for (const f of [pack, g1, g2, mtp, exe]) if (!existsSync(f)) { console.error(`missing: ${f}`); process.exit(2); } - const config = join(OUT, 'server.json'); - writeFileSync(config, JSON.stringify({ - exe, args: ['--pack', pack, '--native', g1, '--ple-gguf', g2, ...(existsSync(profile) ? ['--expert-profile', profile] : []), - '--prefill', 'auto', '--spec-min-p', '0.5', '--mtp', mtp, '--max-context', String(WINDOW), '--kv', 'int8', '--expert-cache', 'auto', '--spec', '4', - ...(process.env.E2E_ENGINE_ARGS ? process.env.E2E_ENGINE_ARGS.split(' ').filter(Boolean) : [])], - cwd: REPO, tokenizer: join(pack, 'tokenizer'), model_name: 'qwen3.8-flash-next-iq3_s', log: join(OUT, 'engine.log'), lib_dirs: [lib], port: PORT, gpu: 0, - fit_max_tokens: true, - }, null, 2)); - server = spawn(PYTHON, ['serve/server.py', '--engine', 'strata', '--config', config, '--port', String(PORT), '--no-api-key', '--ready-file', join(OUT, 'ready.json')], { - cwd: REPO, env: { ...process.env, LD_LIBRARY_PATH: `${lib}:${process.env.LD_LIBRARY_PATH ?? ''}`, STRATA_DATA_DIR: join(OUT, 'data'), PYTHONPATH: `${join(REPO, 'tools')}:${REPO}` }, stdio: ['ignore', 'pipe', 'pipe'], detached: true, - }); - const sink = []; - server.stdout.on('data', d => sink.push(String(d))); - server.stderr.on('data', d => sink.push(String(d))); - server.on('exit', code => { sink.push(`[server exited ${code}]`); server = null; writeFileSync(join(OUT, 'server.log'), sink.join('')); }); -} - -const base = EXISTING || `http://127.0.0.1:${PORT}`; -let ready = false; -for (let i = 0; i < 360 && !ready; i++) { - if (!EXISTING && !server) break; - try { ready = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(2000) })).ok; } catch { /* still loading */ } - if (!ready) await sleep(2000); -} -if (!ready) { console.error('the engine did not become ready'); await finish(4); } -const model = (await (await fetch(`${base}/v1/models`)).json()).data[0].id; -console.log(`engine ready: ${model}`); - -const rows = []; -const note = (id, ok, detail) => { rows.push({ id, ok, detail }); console.log(`${ok ? 'PASS' : 'FAIL'} ${id} ${detail}`); }; - -/** The bridge for a window as the host would tell it (the engine's own window stays WINDOW). */ -function makeBridge(window, dir) { - mkdirSync(join(OUT, dir), { recursive: true }); - return createAgentBridge({ - dataDir: join(OUT, dir), env: process.env, startTimeoutMs: 180_000, log: l => console.log(' bridge:', l), - localInstances: () => [{ id: 'e2e', label: 'iq3_s', baseUrl: `${base}/v1`, modelId: model, context: window, slots: 1, key: '' }], connections: () => [], - }); -} -bridge = makeBridge(WINDOW, 'agent'); - -/** One agent turn; every frame is kept in a compact timeline so the live data path can be read afterwards. */ -async function turn(name, message, { thinking = 'Medium', mode = 'bypass', chatId = name } = {}) { - const workspace = join(OUT, 'ws-' + name); - mkdirSync(workspace, { recursive: true }); - const frames = []; - const t0 = Date.now(); - await bridge.runTurn({ chatId, message, workspacePath: workspace, mode, thinking, onFrame: f => frames.push({ at: Date.now() - t0, f }) }); - const seconds = (Date.now() - t0) / 1000; - const byType = {}; - for (const { f } of frames) byType[f.type] = (byType[f.type] ?? 0) + 1; - const done = frames.map(x => x.f).filter(f => f.type === 'done').at(-1) ?? null; - const error = frames.map(x => x.f).filter(f => f.type === 'error').at(-1) ?? null; - const prepare = frames.map(x => x.f).filter(f => f.type === 'status' && (f.phase === 'preparing' || f.code === 'preparing-tool')); - const cards = frames.map(x => x.f).filter(f => f.type === 'agent-tool').map(f => f.tool); - const text = frames.map(x => x.f).filter(f => f.type === 'delta').map(f => f.text).join(''); - const files = readdirSync(workspace).map(n => ({ name: n, bytes: statSync(join(workspace, n)).size })); - const cutNotes = frames.map(x => x.f).filter(f => f.type === 'delta' && f.noteReason === 'cut').map(f => f.text.trim()); - const drafts = frames.map(x => x.f).filter(f => f.type === 'agent-tool-draft').map(f => f.draft); - const writes = drafts.filter(d => d.name === 'write' && d.bytes > 0); - const draftStats = { frames: drafts.length, writeFrames: writes.length, lastWrite: writes.filter(d => !d.done).at(-1) ? { target: writes.filter(d => !d.done).at(-1).target, bytes: writes.filter(d => !d.done).at(-1).bytes, lines: writes.filter(d => !d.done).at(-1).lines } : null, previewSample: writes.filter(d => !d.done).at(-1)?.preview.slice(-80) ?? null }; - const summary = { name, seconds, cutNotes, draftStats, byType, done, error, files, cards: cards.map(c => ({ name: c.name, state: c.state, target: c.target })), prepareStatuses: prepare.length, firstPrepare: prepare[0] ?? null, lastPrepare: prepare.at(-1) ?? null, text: text.slice(-1200) }; - writeFileSync(join(OUT, `turn-${name}.json`), JSON.stringify({ summary, frames: frames.slice(0, 4000) }, null, 1)); - return { ...summary, frames, workspace }; -} - -const longPrompt = `Create the file big.txt in the current folder with the write tool, in ONE call. It must hold exactly ${LINES} lines. Line N is "N: " followed by one short true sentence about a different city of the world (a new city on every line, no repeats, no pattern). Write every line out yourself, do not use a script or a loop, and do not shorten it.`; - -if (want('raw')) { - // What the model server itself sends when a reply is cut inside a tool call (no Harness): the stream of tool_calls pieces, then finish_reason "length". - const body = { model, stream: true, max_tokens: Number(env('E2E_RAW_CAP', '700')), temperature: 0.6, - chat_template_kwargs: { enable_thinking: false }, - tools: [{ type: 'function', function: { name: 'write', description: 'Write a file.', parameters: { type: 'object', properties: { file_path: { type: 'string' }, content: { type: 'string' } }, required: ['file_path', 'content'] } } }], - messages: [{ role: 'user', content: longPrompt }] }; - const res = await fetch(`${base}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); - const text = await res.text(); - const events = text.split(String.fromCharCode(10)).filter(l => l.startsWith('data: {')).map(l => JSON.parse(l.slice(6))); - let args = '', name = '', content = '', finish = null, pieces = 0, ids = new Set(); - for (const e of events) for (const c of e.choices ?? []) { - for (const tc of c.delta?.tool_calls ?? []) { pieces += 1; if (tc.id) ids.add(tc.id); if (tc.function?.name) name = tc.function.name; args += tc.function?.arguments ?? ''; } - content += c.delta?.content ?? ''; - if (c.finish_reason) finish = c.finish_reason; - } - const usage = events.map(e => e.usage).filter(Boolean).at(-1); - writeFileSync(join(OUT, 'raw-sse.txt'), text); - note('raw: a reply cut inside a tool call reaches the client as pieces of the call and finish_reason length', finish === 'length' && name === 'write' && pieces > 5, `finish ${finish}; tool ${name}; ${pieces} call pieces, ${args.length} argument characters, closed JSON ${(() => { try { JSON.parse(args); return true; } catch { return false; } })()}; plain content ${JSON.stringify(content.slice(0, 80))}; ids ${ids.size}; usage ${JSON.stringify(usage)}`); -} - -if (want('pagoda')) { - const t = await turn('pagoda', 'Write me a 100 voxel pagoda in one html file with garden.'); - const html = t.files.find(f => /\.html?$/i.test(f.name)); - console.log(` pagoda: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, files ${JSON.stringify(t.files)}`); - note('pagoda: a file was written or the turn says why not', !!html || /cut|too long|ran out|limit/i.test(t.text), `file ${html ? html.name + ' ' + html.bytes + ' B' : 'none'}; finish ${t.done?.finishReason}; text tail: ${JSON.stringify(t.text.slice(-240))}`); -} -if (want('long')) { - const t = await turn('long', longPrompt, { thinking: 'Off' }); - const f = t.files.find(x => x.name === 'big.txt'); - const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0; - console.log(` long: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, draft ${JSON.stringify(t.draftStats)}, cut notes ${JSON.stringify(t.cutNotes)}`); - note(`long: big.txt written (${LINES} lines asked)`, lines >= LINES * 0.95 || t.cutNotes.length > 0 && !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}; tokens out ${t.done?.tokensOut}; cards ${JSON.stringify(t.cards.filter(c => c.state !== 'running').map(c => c.name))}; cut notes ${t.cutNotes.length}; draft frames ${t.draftStats.frames}`); - note('long: the turn did not end silently', !!f || t.cutNotes.length > 0 || t.text.trim().length > 0, `text tail ${JSON.stringify(t.text.slice(-160))}`); -} - -if (want('cut')) { - // A small window told to the Harness (E2E_CUT_WINDOW, default 24000; the engine's own stays WINDOW) makes the reply budget about 7K tokens (raised to - // 12K by the fix), so the first reply is cut inside the tool call, as the pagoda's was at 19,660. - await bridge.close(); - bridge = makeBridge(Number(env('E2E_CUT_WINDOW', '24000')), 'agent-cut'); - const t = await turn('cut', longPrompt, { thinking: 'Off' }); - const f = t.files.find(x => x.name === 'big.txt'); - const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0; - console.log(` cut: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason })}, files ${JSON.stringify(t.files)}, cut notes ${JSON.stringify(t.cutNotes)}, draft ${JSON.stringify(t.draftStats)}`); - note('cut: the chat said the reply was cut, in words', t.cutNotes.length > 0 && t.cutNotes.every(n => /length limit/.test(n)), JSON.stringify(t.cutNotes)); - note('cut: the agent went on and the file exists', !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}`); -} - -writeFileSync(join(OUT, 'result.json'), JSON.stringify(rows, null, 2)); -console.log('\n' + rows.map(r => `${r.ok ? 'PASS' : 'FAIL'} ${r.id}`).join('\n')); -await finish(rows.some(r => !r.ok) ? 1 : 0); +#!/usr/bin/env node +/** + * AGENT-LOST end to end: a long single-file write through the real agent bridge, the real Harness and a real engine. + * + * STRATA_HARNESS_DIR=<harness folder> node scripts/agent-lost-e2e.mjs [pagoda|long|cut ...] + * + * Scenarios (default: all) + * pagoda the owner's own prompt ("Write me a 100 voxel pagoda in one html file with garden."), thinking Medium, bypass mode + * long a deterministic long write: one file of N numbered lines (E2E_LINES, default 1800, about 22K tokens), thinking Off + * raw the model server alone: a reply cut inside a tool call, as the client receives it + * cut the same long write with the Harness told a small window (E2E_CUT_WINDOW, default 24000), so the reply budget is + * about 7K tokens and the reply is cut inside the tool call: the turn must say so in words and the agent must carry on + * + * A model server that is already running is used when E2E_BASE_URL is set (nothing is started or stopped). Otherwise this + * starts serve/server.py as its own child with the engine named below and stops it by PID. + * + * Environment: E2E_ENGINE (strata executable), E2E_PACK, E2E_GGUF1, E2E_GGUF2, E2E_MTP, E2E_PROFILE, E2E_LIB (library folder), + * E2E_PORT (18590), E2E_WINDOW (65536), E2E_OUT (result folder), E2E_PYTHON. + * + * It prints one table and writes <E2E_OUT>/result.json with the frames summary of each scenario. + */ +import { spawn } from 'node:child_process'; +import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; + +const REPO = join(import.meta.dirname, '..', '..', '..'); +const env = (name, fallback) => process.env[name] ?? fallback; +const HOME = process.env.HOME ?? ''; +const PORT = Number(env('E2E_PORT', '18590')); +const WINDOW = Number(env('E2E_WINDOW', '65536')); +const EXISTING = process.env.E2E_BASE_URL ?? ''; +const PYTHON = env('E2E_PYTHON', 'python3'); +const OUT = env('E2E_OUT', mkdtempSync(join(tmpdir(), 'strata-agent-lost-'))); +const LINES = Number(env('E2E_LINES', '1400')); +const wanted = process.argv.slice(2); +const want = id => wanted.length === 0 || wanted.includes(id); +mkdirSync(OUT, { recursive: true }); + +if (!process.env.STRATA_HARNESS_DIR) { console.error('STRATA_HARNESS_DIR is not set'); process.exit(2); } +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +let server = null, bridge = null; +const finish = async (code) => { + try { await bridge?.close(); } catch { /* going away */ } + if (server?.pid) { try { process.kill(-server.pid, 'SIGTERM'); } catch { try { process.kill(server.pid, 'SIGTERM'); } catch { /* gone */ } } } + await sleep(1500); + console.log(`\nresult folder: ${OUT}`); + process.exit(code); +}; +process.on('SIGINT', () => finish(130)); + +if (!EXISTING) { + const pack = env('E2E_PACK', join(HOME, '026q/pack-iq3s')); + const g1 = env('E2E_GGUF1', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf')); + const g2 = env('E2E_GGUF2', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf')); + const mtp = env('E2E_MTP', join(HOME, 'pr1426/mtp-rt')); + const profile = env('E2E_PROFILE', join(HOME, 'bwm/cnt3/data/expert-profile.bin')); + const exe = env('E2E_ENGINE', join(HOME, 'agentlost/eng/strata')); + const lib = env('E2E_LIB', join(HOME, 'agentlost/eng')); + for (const f of [pack, g1, g2, mtp, exe]) if (!existsSync(f)) { console.error(`missing: ${f}`); process.exit(2); } + const config = join(OUT, 'server.json'); + writeFileSync(config, JSON.stringify({ + exe, args: ['--pack', pack, '--native', g1, '--ple-gguf', g2, ...(existsSync(profile) ? ['--expert-profile', profile] : []), + '--prefill', 'auto', '--spec-min-p', '0.5', '--mtp', mtp, '--max-context', String(WINDOW), '--kv', 'int8', '--expert-cache', 'auto', '--spec', '4', + ...(process.env.E2E_ENGINE_ARGS ? process.env.E2E_ENGINE_ARGS.split(' ').filter(Boolean) : [])], + cwd: REPO, tokenizer: join(pack, 'tokenizer'), model_name: 'qwen3.8-flash-next-iq3_s', log: join(OUT, 'engine.log'), lib_dirs: [lib], port: PORT, gpu: 0, + fit_max_tokens: true, + }, null, 2)); + server = spawn(PYTHON, ['serve/server.py', '--engine', 'strata', '--config', config, '--port', String(PORT), '--no-api-key', '--ready-file', join(OUT, 'ready.json')], { + cwd: REPO, env: { ...process.env, LD_LIBRARY_PATH: `${lib}:${process.env.LD_LIBRARY_PATH ?? ''}`, STRATA_DATA_DIR: join(OUT, 'data'), PYTHONPATH: `${join(REPO, 'tools')}:${REPO}` }, stdio: ['ignore', 'pipe', 'pipe'], detached: true, + }); + const sink = []; + server.stdout.on('data', d => sink.push(String(d))); + server.stderr.on('data', d => sink.push(String(d))); + server.on('exit', code => { sink.push(`[server exited ${code}]`); server = null; writeFileSync(join(OUT, 'server.log'), sink.join('')); }); +} + +const base = EXISTING || `http://127.0.0.1:${PORT}`; +let ready = false; +for (let i = 0; i < 360 && !ready; i++) { + if (!EXISTING && !server) break; + try { ready = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(2000) })).ok; } catch { /* still loading */ } + if (!ready) await sleep(2000); +} +if (!ready) { console.error('the engine did not become ready'); await finish(4); } +const model = (await (await fetch(`${base}/v1/models`)).json()).data[0].id; +console.log(`engine ready: ${model}`); + +const rows = []; +const note = (id, ok, detail) => { rows.push({ id, ok, detail }); console.log(`${ok ? 'PASS' : 'FAIL'} ${id} ${detail}`); }; + +/** The bridge for a window as the host would tell it (the engine's own window stays WINDOW). */ +function makeBridge(window, dir) { + mkdirSync(join(OUT, dir), { recursive: true }); + return createAgentBridge({ + dataDir: join(OUT, dir), env: process.env, startTimeoutMs: 180_000, log: l => console.log(' bridge:', l), + localInstances: () => [{ id: 'e2e', label: 'iq3_s', baseUrl: `${base}/v1`, modelId: model, context: window, slots: 1, key: '' }], connections: () => [], + }); +} +bridge = makeBridge(WINDOW, 'agent'); + +/** One agent turn; every frame is kept in a compact timeline so the live data path can be read afterwards. */ +async function turn(name, message, { thinking = 'Medium', mode = 'bypass', chatId = name } = {}) { + const workspace = join(OUT, 'ws-' + name); + mkdirSync(workspace, { recursive: true }); + const frames = []; + const t0 = Date.now(); + await bridge.runTurn({ chatId, message, workspacePath: workspace, mode, thinking, onFrame: f => frames.push({ at: Date.now() - t0, f }) }); + const seconds = (Date.now() - t0) / 1000; + const byType = {}; + for (const { f } of frames) byType[f.type] = (byType[f.type] ?? 0) + 1; + const done = frames.map(x => x.f).filter(f => f.type === 'done').at(-1) ?? null; + const error = frames.map(x => x.f).filter(f => f.type === 'error').at(-1) ?? null; + const prepare = frames.map(x => x.f).filter(f => f.type === 'status' && (f.phase === 'preparing' || f.code === 'preparing-tool')); + const cards = frames.map(x => x.f).filter(f => f.type === 'agent-tool').map(f => f.tool); + const text = frames.map(x => x.f).filter(f => f.type === 'delta').map(f => f.text).join(''); + const files = readdirSync(workspace).map(n => ({ name: n, bytes: statSync(join(workspace, n)).size })); + const cutNotes = frames.map(x => x.f).filter(f => f.type === 'delta' && f.noteReason === 'cut').map(f => f.text.trim()); + const drafts = frames.map(x => x.f).filter(f => f.type === 'agent-tool-draft').map(f => f.draft); + const writes = drafts.filter(d => d.name === 'write' && d.bytes > 0); + const draftStats = { frames: drafts.length, writeFrames: writes.length, lastWrite: writes.filter(d => !d.done).at(-1) ? { target: writes.filter(d => !d.done).at(-1).target, bytes: writes.filter(d => !d.done).at(-1).bytes, lines: writes.filter(d => !d.done).at(-1).lines } : null, previewSample: writes.filter(d => !d.done).at(-1)?.preview.slice(-80) ?? null }; + const summary = { name, seconds, cutNotes, draftStats, byType, done, error, files, cards: cards.map(c => ({ name: c.name, state: c.state, target: c.target })), prepareStatuses: prepare.length, firstPrepare: prepare[0] ?? null, lastPrepare: prepare.at(-1) ?? null, text: text.slice(-1200) }; + writeFileSync(join(OUT, `turn-${name}.json`), JSON.stringify({ summary, frames: frames.slice(0, 4000) }, null, 1)); + return { ...summary, frames, workspace }; +} + +const longPrompt = `Create the file big.txt in the current folder with the write tool, in ONE call. It must hold exactly ${LINES} lines. Line N is "N: " followed by one short true sentence about a different city of the world (a new city on every line, no repeats, no pattern). Write every line out yourself, do not use a script or a loop, and do not shorten it.`; + +if (want('raw')) { + // What the model server itself sends when a reply is cut inside a tool call (no Harness): the stream of tool_calls pieces, then finish_reason "length". + const body = { model, stream: true, max_tokens: Number(env('E2E_RAW_CAP', '700')), temperature: 0.6, + chat_template_kwargs: { enable_thinking: false }, + tools: [{ type: 'function', function: { name: 'write', description: 'Write a file.', parameters: { type: 'object', properties: { file_path: { type: 'string' }, content: { type: 'string' } }, required: ['file_path', 'content'] } } }], + messages: [{ role: 'user', content: longPrompt }] }; + const res = await fetch(`${base}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + const text = await res.text(); + const events = text.split(String.fromCharCode(10)).filter(l => l.startsWith('data: {')).map(l => JSON.parse(l.slice(6))); + let args = '', name = '', content = '', finish = null, pieces = 0, ids = new Set(); + for (const e of events) for (const c of e.choices ?? []) { + for (const tc of c.delta?.tool_calls ?? []) { pieces += 1; if (tc.id) ids.add(tc.id); if (tc.function?.name) name = tc.function.name; args += tc.function?.arguments ?? ''; } + content += c.delta?.content ?? ''; + if (c.finish_reason) finish = c.finish_reason; + } + const usage = events.map(e => e.usage).filter(Boolean).at(-1); + writeFileSync(join(OUT, 'raw-sse.txt'), text); + note('raw: a reply cut inside a tool call reaches the client as pieces of the call and finish_reason length', finish === 'length' && name === 'write' && pieces > 5, `finish ${finish}; tool ${name}; ${pieces} call pieces, ${args.length} argument characters, closed JSON ${(() => { try { JSON.parse(args); return true; } catch { return false; } })()}; plain content ${JSON.stringify(content.slice(0, 80))}; ids ${ids.size}; usage ${JSON.stringify(usage)}`); +} + +if (want('pagoda')) { + const t = await turn('pagoda', 'Write me a 100 voxel pagoda in one html file with garden.'); + const html = t.files.find(f => /\.html?$/i.test(f.name)); + console.log(` pagoda: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, files ${JSON.stringify(t.files)}`); + note('pagoda: a file was written or the turn says why not', !!html || /cut|too long|ran out|limit/i.test(t.text), `file ${html ? html.name + ' ' + html.bytes + ' B' : 'none'}; finish ${t.done?.finishReason}; text tail: ${JSON.stringify(t.text.slice(-240))}`); +} +if (want('long')) { + const t = await turn('long', longPrompt, { thinking: 'Off' }); + const f = t.files.find(x => x.name === 'big.txt'); + const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0; + console.log(` long: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, draft ${JSON.stringify(t.draftStats)}, cut notes ${JSON.stringify(t.cutNotes)}`); + note(`long: big.txt written (${LINES} lines asked)`, lines >= LINES * 0.95 || t.cutNotes.length > 0 && !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}; tokens out ${t.done?.tokensOut}; cards ${JSON.stringify(t.cards.filter(c => c.state !== 'running').map(c => c.name))}; cut notes ${t.cutNotes.length}; draft frames ${t.draftStats.frames}`); + note('long: the turn did not end silently', !!f || t.cutNotes.length > 0 || t.text.trim().length > 0, `text tail ${JSON.stringify(t.text.slice(-160))}`); +} + +if (want('cut')) { + // A small window told to the Harness (E2E_CUT_WINDOW, default 24000; the engine's own stays WINDOW) makes the reply budget about 7K tokens (raised to + // 12K by the fix), so the first reply is cut inside the tool call, as the pagoda's was at 19,660. + await bridge.close(); + bridge = makeBridge(Number(env('E2E_CUT_WINDOW', '24000')), 'agent-cut'); + const t = await turn('cut', longPrompt, { thinking: 'Off' }); + const f = t.files.find(x => x.name === 'big.txt'); + const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0; + console.log(` cut: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason })}, files ${JSON.stringify(t.files)}, cut notes ${JSON.stringify(t.cutNotes)}, draft ${JSON.stringify(t.draftStats)}`); + note('cut: the chat said the reply was cut, in words', t.cutNotes.length > 0 && t.cutNotes.every(n => /length limit/.test(n)), JSON.stringify(t.cutNotes)); + note('cut: the agent went on and the file exists', !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}`); +} + +writeFileSync(join(OUT, 'result.json'), JSON.stringify(rows, null, 2)); +console.log('\n' + rows.map(r => `${r.ok ? 'PASS' : 'FAIL'} ${r.id}`).join('\n')); +await finish(rows.some(r => !r.ok) ? 1 : 0); diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index 4b8838c3e6..d92d679855 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -1,167 +1,167 @@ -# Agent bridge (Strata chats as DeepSeek Harness sessions) - -This page is for developers who work on the app host's agent code. It lists the files, the frames and routes, and the rules the -bridge enforces. Tests are listed at the end. - -The Harness is a separate, pinned component (`DSH 0.2.1-alpha.3`, commit `57190202`, MIT). The host finds it through -`STRATA_HARNESS_DIR` (or `<STRATA_COMPONENTS_DIR>/harness`), starts one `dsh --profile web` process on a loopback port, -and talks to its Gateway. Nothing here downloads or builds anything. - -| File | Job | -| --- | --- | -| `harness-runtime.mjs` | locate the component, start/stop the process, scrub its environment, clean up a leftover process from a dead host | -| `gateway-client.mjs` | HTTP RPC plus the `remote.mux` WebSocket (`$events`, `session/follow`) | -| `profile.mjs` | generate the Harness profile: one route per ready local instance and per saved API connection; credential names only | -| `task-run.mjs` | a scheduled task as the agent | -| `events.mjs` | pure projection of Harness session events into the chat's NDJSON frames | -| `children.mjs` | pure projection of one helper agent's events into its row and its approval card | -| `preset.mjs` | the agent preset (which tools the chat has) | -| `plugins/strata-gate.mjs` | the Manual-mode approval gate (a Harness plugin, loaded by path) | -| `plugins/strata-search.mjs`, `plugins/strata-models.mjs` | the app's web search registered with the Harness; helper agents on a named model | -| `plugins/strata-context.mjs`, `context-budget.mjs`, `context-fit.mjs` | measured context pressure, summaries that fit the window, the check before a message goes out | -| `agent-bridge.mjs` | the chat-to-session map, turns, approvals, Stop, status | - -## Frames sent on `/api/chat/stream` for an agent turn - -`queued`, `start` (`agent:true`), `reasoning`, `delta`, `agent-tool` (upserts a tool card by call id with -`running | proposed | done | denied | error`), `done` (usage, `finishReason`, `cancelled`), `error`, and `notice` -(why a chat is not using the agent). The chat UI renders them with its existing components. - -## Routes - -- `GET /api/agent/status`: component, routes, active turns, pending approvals (no tokens, no keys) -- `POST /api/chat/approval {sessionId, toolId, decision: approve|deny}` -- `POST /api/chat/stop {sessionId}`: cancels that chat's Harness session and answers once the turn has ended -- `GET /api/agent/pending?chatId=` - -## Behaviour worth knowing - -- **Stop is per chat.** `session/cancel` is only an admission; the bridge waits for the durable `turn/end`. Stop before the - prompt reached the Harness cancels the start. The process is never killed to implement Stop. -- **A closed tab is not Stop.** The turn keeps running; an approval it needs stays pending until someone answers. -- **Resume.** The chat id maps to a Harness session id (`<data>/agent/sessions.json`). Reopening prompts that session; the - Harness resumes it from its own record, so nothing is replayed. (`session/create` with a started id returns a new - session, so it is never used for resume.) -- **Models.** Each chat sends its choice; the bridge calls `session/selectModel` for that route before the prompt. A route - that is gone is a typed `model-unavailable` error, never another model. Keys travel as environment variables named by - `apiKeyEnv`; the agent's shell does not inherit them, and logs are redacted. -- **No answerer, no hang.** The agent's own questions (`ask_user_question`) are declared unanswerable until the app has a - surface for them. -- **Fallback.** Without the component the host says so (`/api/agent/status`, a `notice` frame) and the chat runs on the - direct path with the model the user picked. - -## Modes (the Mode menu) - -The chat's Mode menu is real Harness behaviour. Each turn the page sends the chat's mode (`mode` in the `/api/chat/stream` body); before the prompt reaches the Harness the bridge puts that chat's session into the matching permission preset with the Harness's own `/permission` command (`commands/execute`), reads the `permissions` projection back, and refuses to start the turn (typed error `mode-unavailable`) if it does not match. The preset table is ours (profile entry `permission`). - -| Menu | Preset | Sandbox | Approval | What it means | -| --- | --- | --- | --- | --- | -| Manual (default) | `strata-manual` | open (`danger-full-access`) | `ask` | The Strata gate (`plugins/strata-gate.mjs`) asks BEFORE any change runs: one Approve/Deny card, nothing has happened when it appears, no blocked attempt, no sandbox or PowerShell error. Reads and read-only commands run without a question; anything the gate cannot prove read-only asks. | -| Plan | `strata-plan` | `read-only` | `never` | Nothing can change. A request is rejected without asking anyone, so no Approve card is shown; the card ends "Not allowed in this mode". | -| Bypass | `strata-bypass` | `danger-full-access` | `never` | Full access without prompts, as before. | - -- Manual relies on the gate, so a Manual turn does not start unless the bridge has confirmed the gate is loaded (`/strata-gate` command): without it Manual would be an open sandbox that nobody asks about. -- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked, each only with the options listed for it in `strata-gate.mjs` (an unknown option, or one that writes, runs a program, sets something or never ends, asks); MCP and unknown tools ask. -- Web search and web pages (`web_search`, `web_fetch`) ask once per chat in Manual, not once per call. The gate asks through the approval service itself (`webDecision`: "The assistant wants to search the web for: ... Search words go to <service>." / "... open the web page ..."), remembers a yes for the chat (a helper agent shares its chat's answer, and two searches started together share one card), and on a no gives the model `WEB_REFUSAL` ("The person did not allow web access ... Go on without it and say so."). Plan and Bypass are unchanged. Settings -> Tools has a switch, "Let the assistant search the web without asking" (off by default, `webWithoutAsking` in `tools-settings.mjs`, passed to the gate as `config.web.skipAsk`), that skips the question in Manual. A scheduled task has nobody at the card, so its web call is answered no unless that switch is on. Tests: `tests/web-ask.test.mjs`. -- The mode is read once per turn; an unknown or missing value is Manual. - -## Tools - -`preset.mjs` is the agent preset: the Harness `standard` preset minus the scheduler (Tasks is the only one), the agent's own question tool (no place to answer) and the Harness's plan mode. `tests/agent-tools.test.mjs` compares the list with the pinned Harness's own file, so a Harness update that adds or renames a plugin fails a test instead of silently dropping a tool. - -### Settings -> Tools - -What the person chose is saved by `tools-settings.mjs` (inside the host's settings file) and shown by `src/components/SettingsTools.tsx` (`GET/PUT /api/agent/tools`, `POST/PATCH/DELETE /api/agent/tools/custom[/id]`). A change reaches the agent from the next message: the profile carries a `toolsSignature`, and the bridge restarts the Harness (after the running turns end) when it differs. - -- Tool groups (`tools-catalog.mjs`): each is one switch in plain words and is one or more preset plugins (`withoutDisabled`); `fetch` and `search` are the two halves of the Harness's `tool-web` (both off drops it). Goals off: `/goal` answers that goals are turned off. -- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`), with Bing's plain result page (`../web-search-bing.mjs`) as the second source. Manners, because DuckDuckGo refuses a program that asks fast: a browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*), one request at a time per source, 2.5 to 4 s apart (random), at most 8 a minute, a 30 minute session cache per question, a cooldown after a refusal that doubles (1, 2, 4 ... 10 minutes, `Retry-After` honoured) during which that source gets no request, no lite-page follow-up after a refusal, one retry for a timeout or a 5xx, a 15 s limit. When every source refuses, the tool answers one plain sentence (`LIMITED_SENTENCE`: "Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings -> Tools -> Web search.") plus an instruction to the model not to retry; the turn guard in `agent-bridge.mjs` (see Turn guard) stops a model that retries anyway. **The results come from DuckDuckGo or Bing**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous. -- The browser: Playwright's MCP server (`@playwright/mcp`, staged next to the Harness by `apps/desktop/scripts/stage-harness.mjs`) on the person's own Chrome, Edge or Chromium (`browser-probe.mjs`), `--isolated` so it never sees their profile. Tools appear as `mcp__browser__browser_*`. In Manual, opening a page, clicking, typing, uploading, running a script in the page and closing tabs ask (plain reasons: "Open the web page ...", "Click on the page: ..."); looking (snapshot, screenshot, console, network, waiting, listing tabs) does not. Plan refuses every connected tool. The screen says plainly when no browser, or no tool server, is found. -- The person's own tools: `instructions` (the tool returns their text; look-only, never asks), `command` (runs their command with the assistant's text in the `STRATA_INPUT` environment variable, never spliced into the command line; asks in Manual, refused in Plan) and `server` (a web address or a program, added as `mcp__custom-<name>__*`; asks in Manual). Instruction and command tools are served by `custom-tools-mcp.mjs` (stdio MCP) from a JSON file the settings module rewrites on every change, so a switch in Settings is seen without a restart. -- `strata-gate.mjs` implements the Manual/Plan rules above (`planDecision`, `browserDecision`, the look-only instruction server). - -## Helper agents (subagents) - -- A Harness `subagent/catalog` event on the chat's session creates a row; `children.mjs` folds the helper's `session/follow` (address `{kind:'subagent', parentSessionId, childSessionId}`) into `{type:'agent', agent:{id,name,description,status,durationMs,tokens,updatedAt}}`, the shape the Subagents popover already reads. The delegation tools have no card. -- A helper's request for approval is the same card (state `proposed`, id `<helper session>:<call>`), answered with the same `/api/chat/approval`; a chat can only answer its own helpers. -- The run (the chat's one NDJSON response) stays open until the parent is idle, every helper has finished and reported back, and no armed goal is waiting; `done` is sent then. -- Stop: pauses an active goal, interrupts every helper (`subagents/interruptByParent`; `session/cancel` on a helper session is refused by the Harness), cancels the parent, waits; a report that would wake the parent afterwards is cancelled too. -- The number of helpers at once is the engine's request slots, with a floor of 4 for a local model and 8 for an API model (`maxActiveSubagents` in the profile). The Harness refuses more with a message the model reads. - -## /goal - -`/goal` typed in a chat goes to `bridge.goalCommand`: nothing = show the goal, `clear`, `pause`, `resume`, `edit <text>`, `complete`, anything else = a new goal (one unfinished goal at a time). Create/resume use the Harness goal Remotes (`goals/create|get|resume|pause|edit|clear|complete`); the Harness's goal driver runs the rounds and they stream into the chat ("Working on the goal…", with no step counter); the run ends when the goal stops (complete, paused, blocked, round limit - the default cap is the Harness's 256, a run with `maxRounds` is capped) and says how in plain words. After a restart an active goal stays disarmed until `/goal resume`. - -## Thinking and the output budget - -The Harness staging script (`apps/desktop/scripts/stage-harness.mjs`) applies Strata's guarded pi-ai 1.1.0 patch to its staged copy -(`harness-budget.mjs`, #3684): below 64K the context safety room is at most `min(4096, floor(contextWindow / 16))` and never more -than half the estimated remaining room, so an 8K window keeps output room after a tool result instead of ending with a one-token -cap. The caller's output cap and the one-token floor remain; windows of 64K or more keep the previous calculation. `BUNDLE.json.patches` -records the patch identity, the dependency version and the before/after SHA-256. Unknown dependency bytes stop staging for review. -Source and already-installed Harness copies are not changed. - -- A local route is reasoning-capable (`reasoning: true`) with `compat.thinkingFormat: 'chat-template'`: the request carries `chat_template_kwargs {enable_thinking, reasoning_effort}`, which the Strata server reads (a top-level `enable_thinking` is ignored by it, which is why pi-ai's `qwen` format left the model thinking). The chat's Reasoning menu travels as `thinking` in the stream body; the bridge sends it with `session/selectModel` (`reasoningEffort`) whenever the model or the level changed; a level a route does not have is dropped (never an error). API routes keep the provider default (the menu is disabled for them in the UI). -- `localOutputBudget(context)` is 30 percent of the window, at least 4096 and at most 32768 (9,830 tokens at 32K, 19,660 at 64K). The Harness's automatic compaction reads it as the room a reply reserves (the request header), and it is NOT the ceiling of a request: `plugins/strata-context.mjs` raises what the adapter sends to half the window, at most 64K tokens (`reply-cut.mjs` `replyCap`; pi-ai clamps it to the window minus the prompt), because a thinking model that writes a whole file in one call was cut inside the call at 19,660 and lost it (AGENT-LOST). A reply that is cut anyway is announced in the chat, the agent is asked to go on in smaller pieces (twice at most), and the file being written is streamed to the page as `agent-tool-draft` frames (name, size, lines, tail of the text). App-loaded models get `fit_max_tokens: true` so the engine clamps instead of answering 400. Sampling is not set here: the Harness sends none, so the server's own defaults apply. - -## Tasks - -`task-run.mjs` runs a scheduled task as the agent: a Harness session of its own (`task:<id>`, dropped after every run), the task's mode (`plan` default, `manual`, `bypass`), and a result built by `../task-report.mjs`. Nobody is at the screen: an approval request is answered "no" at once and reported ("Nothing was changed"). `server/tasks.mjs` stays the only scheduler; it sends a `task` event when a run ends (the page shows a toast). - -## Plain words - -Failures the person sees are plain sentences with a next step (`AgentUnavailable.message`); the technical text is in `.details` / the `details` field of error and notice frames, and in `/api/agent/status` `detail`. A failed tool's card result is a plain sentence followed by "Details: <original text>". - -## Tests - -`tests/agent-events.test.mjs` (pure), `tests/agent-tools-settings.test.mjs` (Settings -> Tools, web search, the browser and the person's own tools; the Harness-backed ones need STRATA_HARNESS_DIR and the browser one also Chrome or Edge), `tests/agent-bridge.test.mjs`, `tests/agent-modes.test.mjs` and `tests/agent-host.test.mjs` (need a built Harness: -`STRATA_HARNESS_DIR=<checkout>`, otherwise they skip and say so). The model in those tests is `tests/helpers/scripted-worker.mjs`. -`scripts/agent-flow.mjs` drives the real app in Chrome and takes screenshots. - -## Helper agents on a named model (`plugins/strata-models.mjs`, `model-routes.mjs`) - -The Harness's `subagent` tool takes an exact `provider` route key and model id. The profile enables the Harness's `subagent-model-selection-settings` with every route the app can reach (local instances and saved API models), and the `strata-models` plugin wraps the two tool definitions the Harness registers for each chat (`subagent`, `list_subagent_models`) in place: - -- the model is found from its id, `provider/id`, the name in the model picker, `connection name`, or "local" (any letters). A close guess is not started: the tool answers "Did you mean ...?" and nothing runs until the call is made again with that model. Several fits are listed; nothing fitting lists the models that can be used and says they can be added in Models. -- the tool's own text says when to use it ("ask a subagent", "ask model X"), not to look for the model with shell commands, and not to wait with sleep. The system prompt (`preset.mjs`) says the same, so it reaches every model, local or hosted. -- `list_subagent_models` lists the models by the names the person knows. - -If a Harness update renames those tools the wrapping does nothing and `tests/agent-subagent-models.test.mjs` (real Harness) fails. - -## Reasoning for API models - -A model on OpenRouter whose model list names `reasoning` in `supported_parameters` gets `reasoning: true` and the efforts `{off: none, low, medium, high, max: xhigh}` and the `openrouter` thinking format, so the Reasoning menu works and the choice reaches OpenRouter as `reasoning: { effort }`. Other API models keep the provider's own default (the menu stays greyed). - -## Pictures - -Pictures are on by default for every model that can read them: an API model reads them unless the person switched it off (Settings > Models > "Read pictures with this model") or its server says it cannot; a local model reads them when it was loaded with Read pictures (on by default). `src/lib/pictures.ts` is the one answer used by the composer and by Send; the agent route declares image input from the same flag. - -## Turn guard (`turn-guard.mjs`) - -A turn that keeps failing the same way is stopped by the app, never left to the model. - -- **Counted, from what the turn shows:** web searches that failed in a row (3), searches in one turn (10 in a plan turn, 25 otherwise), a plan turn that starts its numbered list from `1.` again (4 times), and a context of 93% or more (the Harness's own compaction did not keep up). -- **Stopped the way Stop stops** (`session/cancel`, helpers first) but ended as a normal turn (`done`, not cancelled, no error card), so the plan the model had written is still proposed. The plan card carries the reason (`plan.caution`); any other turn ends with one `delta` frame that has `own: true` and `key` (the English sentence, translated by the page; `GUARD_NOTES` are in the interface catalog in all eight languages). Each sentence says what happened and gives one next step. -- **Compaction:** after a guard stop (and after a turn the model server refused because the context was full) the bridge asks the Harness for `/compact` on that session, so the next message has room. Best effort and logged. -- **Never silent:** a turn that ends (`completed` or `max-tokens`) with no answer text gets "I ran out of room in this chat..." when the last request used 85% of the window or more, otherwise "I stopped without writing an answer..." (not when tool cards were shown, not after Stop, not after an error, which says why by itself). Goal runs have their own ending lines and are not guarded. -- Tests: `tests/agent-turn-guard.test.mjs` (counting, always; end to end with the real Harness, the scripted model's `searchloop` and `bloat` scripts and `searchMock: 'limited'` on the bridge, which runs the real search code on a pretend web that refuses, no network). - -## Context: measured pressure, summaries that fit, the check before a message goes out - -- **`plugins/strata-context.mjs`** (inserted by the profile, like the gate) wraps `tokenMeter.measure` and `llm.stream` in place, once each. Pressure = the last prompt size the model server reported for an answer, plus what changed since priced at the density that measurement showed (`context-budget.mjs`: `pressureNow`, `densityOf`); never lower than the Harness's own price. Node prices are scaled the same way, so the retained tail is in real tokens. A summary request (`purpose: 'compaction'`) that would not fit the window is asked for in pieces: a message bigger than a piece is cut for the request only, each piece builds on the summary before it, a piece the server refuses is halved and tried again. `/strata-context` (a Harness command, like `/strata-gate`) answers `{tokens, window}` for a session so the host can tell the person true figures. -- **`context-fit.mjs`**: before a message is sent the model server counts it (`POST /v1/messages/count_tokens`, its own tokenizer). `decideFit`: send; summarise first and then send (the message fits an otherwise empty chat); or never fits. The last one is not sent: the error frame has `code: 'CONTEXT_MESSAGE_TOO_LARGE'` and the page offers "Attach as a file" (`oversize.mjs`, `/api/chat/oversize`: the text is saved in the chat's folder, the assistant reads it in parts) or "Send a shortened preview". An engine that cannot count lets the message through; the Harness's own compact-and-retry is the net. -- **`/compact`** is handled by the host (`compactCommand`): the Harness's `/compact`, then a plain line with the measured figures ("The chat was 90% full and is now 38% full"), or "nothing older to summarize" when the newest message is what fills the chat. -- **Visible:** `compaction/start` shows "Summarizing earlier messages..." in the status line; `compaction/end` adds one plain line to the reply. The projector also sends a `context` frame after every model request, so the meter follows the running turn. -- **A refusal that is left** (`CONTEXT_WINDOW_EXCEEDED`) is a plain sentence with the engine's text under Details and the buttons "Summarize and continue" and "Start a new chat". "Try sending the message again" is for other errors only. -- Tests: `tests/agent-context.test.mjs` (arithmetic; the real Harness against the scripted worker with `window`, `charsPerToken` and `noCount`), `tests/oversize.test.mjs`, `tests/context-ui.test.mjs`. The run against a real engine is `scripts/context-e2e.mjs`. - -## History / older measurements - -- **Search refusals (2026-10):** on a real box two DuckDuckGo searches in 1.2 s answered, the third got HTTP 202, and every DuckDuckGo page refused for many minutes. - The pacing, cooldown and cache rules above come from that test. -- **Search-heavy `/plan` (2026-10):** every web search was refused, the model searched again and rewrote its plan after each one until the context reached 100%. - The turn ended with no answer and no message. The turn guard comes from that run. -- **Large log paste (2026-10-22, installed 0.2.1, Gyro-S, 64K):** a 118 KB log was 66,500 tokens to the engine and about 29,500 to the Harness - (4 characters a token; logs and code are about 2). The engine refused it with a 400. The refusal stayed in the history, so neither the next message nor `/compact` could - go through, because the summary request carried the same history. `/compact` was also not a command of the app yet: it went to the model as a question. This - produced `strata-context.mjs`, `context-fit.mjs` and the host's own `/compact`. -- **Output budget:** an earlier local budget of a quarter of the window, capped at 8192, cut big answers off at exactly 8192 tokens. +# Agent bridge (Strata chats as DeepSeek Harness sessions) + +This page is for developers who work on the app host's agent code. It lists the files, the frames and routes, and the rules the +bridge enforces. Tests are listed at the end. + +The Harness is a separate, pinned component (`DSH 0.2.1-alpha.3`, commit `57190202`, MIT). The host finds it through +`STRATA_HARNESS_DIR` (or `<STRATA_COMPONENTS_DIR>/harness`), starts one `dsh --profile web` process on a loopback port, +and talks to its Gateway. Nothing here downloads or builds anything. + +| File | Job | +| --- | --- | +| `harness-runtime.mjs` | locate the component, start/stop the process, scrub its environment, clean up a leftover process from a dead host | +| `gateway-client.mjs` | HTTP RPC plus the `remote.mux` WebSocket (`$events`, `session/follow`) | +| `profile.mjs` | generate the Harness profile: one route per ready local instance and per saved API connection; credential names only | +| `task-run.mjs` | a scheduled task as the agent | +| `events.mjs` | pure projection of Harness session events into the chat's NDJSON frames | +| `children.mjs` | pure projection of one helper agent's events into its row and its approval card | +| `preset.mjs` | the agent preset (which tools the chat has) | +| `plugins/strata-gate.mjs` | the Manual-mode approval gate (a Harness plugin, loaded by path) | +| `plugins/strata-search.mjs`, `plugins/strata-models.mjs` | the app's web search registered with the Harness; helper agents on a named model | +| `plugins/strata-context.mjs`, `context-budget.mjs`, `context-fit.mjs` | measured context pressure, summaries that fit the window, the check before a message goes out | +| `agent-bridge.mjs` | the chat-to-session map, turns, approvals, Stop, status | + +## Frames sent on `/api/chat/stream` for an agent turn + +`queued`, `start` (`agent:true`), `reasoning`, `delta`, `agent-tool` (upserts a tool card by call id with +`running | proposed | done | denied | error`), `done` (usage, `finishReason`, `cancelled`), `error`, and `notice` +(why a chat is not using the agent). The chat UI renders them with its existing components. + +## Routes + +- `GET /api/agent/status`: component, routes, active turns, pending approvals (no tokens, no keys) +- `POST /api/chat/approval {sessionId, toolId, decision: approve|deny}` +- `POST /api/chat/stop {sessionId}`: cancels that chat's Harness session and answers once the turn has ended +- `GET /api/agent/pending?chatId=` + +## Behaviour worth knowing + +- **Stop is per chat.** `session/cancel` is only an admission; the bridge waits for the durable `turn/end`. Stop before the + prompt reached the Harness cancels the start. The process is never killed to implement Stop. +- **A closed tab is not Stop.** The turn keeps running; an approval it needs stays pending until someone answers. +- **Resume.** The chat id maps to a Harness session id (`<data>/agent/sessions.json`). Reopening prompts that session; the + Harness resumes it from its own record, so nothing is replayed. (`session/create` with a started id returns a new + session, so it is never used for resume.) +- **Models.** Each chat sends its choice; the bridge calls `session/selectModel` for that route before the prompt. A route + that is gone is a typed `model-unavailable` error, never another model. Keys travel as environment variables named by + `apiKeyEnv`; the agent's shell does not inherit them, and logs are redacted. +- **No answerer, no hang.** The agent's own questions (`ask_user_question`) are declared unanswerable until the app has a + surface for them. +- **Fallback.** Without the component the host says so (`/api/agent/status`, a `notice` frame) and the chat runs on the + direct path with the model the user picked. + +## Modes (the Mode menu) + +The chat's Mode menu is real Harness behaviour. Each turn the page sends the chat's mode (`mode` in the `/api/chat/stream` body); before the prompt reaches the Harness the bridge puts that chat's session into the matching permission preset with the Harness's own `/permission` command (`commands/execute`), reads the `permissions` projection back, and refuses to start the turn (typed error `mode-unavailable`) if it does not match. The preset table is ours (profile entry `permission`). + +| Menu | Preset | Sandbox | Approval | What it means | +| --- | --- | --- | --- | --- | +| Manual (default) | `strata-manual` | open (`danger-full-access`) | `ask` | The Strata gate (`plugins/strata-gate.mjs`) asks BEFORE any change runs: one Approve/Deny card, nothing has happened when it appears, no blocked attempt, no sandbox or PowerShell error. Reads and read-only commands run without a question; anything the gate cannot prove read-only asks. | +| Plan | `strata-plan` | `read-only` | `never` | Nothing can change. A request is rejected without asking anyone, so no Approve card is shown; the card ends "Not allowed in this mode". | +| Bypass | `strata-bypass` | `danger-full-access` | `never` | Full access without prompts, as before. | + +- Manual relies on the gate, so a Manual turn does not start unless the bridge has confirmed the gate is loaded (`/strata-gate` command): without it Manual would be an open sandbox that nobody asks about. +- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked, each only with the options listed for it in `strata-gate.mjs` (an unknown option, or one that writes, runs a program, sets something or never ends, asks); MCP and unknown tools ask. +- Web search and web pages (`web_search`, `web_fetch`) ask once per chat in Manual, not once per call. The gate asks through the approval service itself (`webDecision`: "The assistant wants to search the web for: ... Search words go to <service>." / "... open the web page ..."), remembers a yes for the chat (a helper agent shares its chat's answer, and two searches started together share one card), and on a no gives the model `WEB_REFUSAL` ("The person did not allow web access ... Go on without it and say so."). Plan and Bypass are unchanged. Settings -> Tools has a switch, "Let the assistant search the web without asking" (off by default, `webWithoutAsking` in `tools-settings.mjs`, passed to the gate as `config.web.skipAsk`), that skips the question in Manual. A scheduled task has nobody at the card, so its web call is answered no unless that switch is on. Tests: `tests/web-ask.test.mjs`. +- The mode is read once per turn; an unknown or missing value is Manual. + +## Tools + +`preset.mjs` is the agent preset: the Harness `standard` preset minus the scheduler (Tasks is the only one), the agent's own question tool (no place to answer) and the Harness's plan mode. `tests/agent-tools.test.mjs` compares the list with the pinned Harness's own file, so a Harness update that adds or renames a plugin fails a test instead of silently dropping a tool. + +### Settings -> Tools + +What the person chose is saved by `tools-settings.mjs` (inside the host's settings file) and shown by `src/components/SettingsTools.tsx` (`GET/PUT /api/agent/tools`, `POST/PATCH/DELETE /api/agent/tools/custom[/id]`). A change reaches the agent from the next message: the profile carries a `toolsSignature`, and the bridge restarts the Harness (after the running turns end) when it differs. + +- Tool groups (`tools-catalog.mjs`): each is one switch in plain words and is one or more preset plugins (`withoutDisabled`); `fetch` and `search` are the two halves of the Harness's `tool-web` (both off drops it). Goals off: `/goal` answers that goals are turned off. +- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`), with Bing's plain result page (`../web-search-bing.mjs`) as the second source. Manners, because DuckDuckGo refuses a program that asks fast: a browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*), one request at a time per source, 2.5 to 4 s apart (random), at most 8 a minute, a 30 minute session cache per question, a cooldown after a refusal that doubles (1, 2, 4 ... 10 minutes, `Retry-After` honoured) during which that source gets no request, no lite-page follow-up after a refusal, one retry for a timeout or a 5xx, a 15 s limit. When every source refuses, the tool answers one plain sentence (`LIMITED_SENTENCE`: "Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings -> Tools -> Web search.") plus an instruction to the model not to retry; the turn guard in `agent-bridge.mjs` (see Turn guard) stops a model that retries anyway. **The results come from DuckDuckGo or Bing**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous. +- The browser: Playwright's MCP server (`@playwright/mcp`, staged next to the Harness by `apps/desktop/scripts/stage-harness.mjs`) on the person's own Chrome, Edge or Chromium (`browser-probe.mjs`), `--isolated` so it never sees their profile. Tools appear as `mcp__browser__browser_*`. In Manual, opening a page, clicking, typing, uploading, running a script in the page and closing tabs ask (plain reasons: "Open the web page ...", "Click on the page: ..."); looking (snapshot, screenshot, console, network, waiting, listing tabs) does not. Plan refuses every connected tool. The screen says plainly when no browser, or no tool server, is found. +- The person's own tools: `instructions` (the tool returns their text; look-only, never asks), `command` (runs their command with the assistant's text in the `STRATA_INPUT` environment variable, never spliced into the command line; asks in Manual, refused in Plan) and `server` (a web address or a program, added as `mcp__custom-<name>__*`; asks in Manual). Instruction and command tools are served by `custom-tools-mcp.mjs` (stdio MCP) from a JSON file the settings module rewrites on every change, so a switch in Settings is seen without a restart. +- `strata-gate.mjs` implements the Manual/Plan rules above (`planDecision`, `browserDecision`, the look-only instruction server). + +## Helper agents (subagents) + +- A Harness `subagent/catalog` event on the chat's session creates a row; `children.mjs` folds the helper's `session/follow` (address `{kind:'subagent', parentSessionId, childSessionId}`) into `{type:'agent', agent:{id,name,description,status,durationMs,tokens,updatedAt}}`, the shape the Subagents popover already reads. The delegation tools have no card. +- A helper's request for approval is the same card (state `proposed`, id `<helper session>:<call>`), answered with the same `/api/chat/approval`; a chat can only answer its own helpers. +- The run (the chat's one NDJSON response) stays open until the parent is idle, every helper has finished and reported back, and no armed goal is waiting; `done` is sent then. +- Stop: pauses an active goal, interrupts every helper (`subagents/interruptByParent`; `session/cancel` on a helper session is refused by the Harness), cancels the parent, waits; a report that would wake the parent afterwards is cancelled too. +- The number of helpers at once is the engine's request slots, with a floor of 4 for a local model and 8 for an API model (`maxActiveSubagents` in the profile). The Harness refuses more with a message the model reads. + +## /goal + +`/goal` typed in a chat goes to `bridge.goalCommand`: nothing = show the goal, `clear`, `pause`, `resume`, `edit <text>`, `complete`, anything else = a new goal (one unfinished goal at a time). Create/resume use the Harness goal Remotes (`goals/create|get|resume|pause|edit|clear|complete`); the Harness's goal driver runs the rounds and they stream into the chat ("Working on the goal…", with no step counter); the run ends when the goal stops (complete, paused, blocked, round limit - the default cap is the Harness's 256, a run with `maxRounds` is capped) and says how in plain words. After a restart an active goal stays disarmed until `/goal resume`. + +## Thinking and the output budget + +The Harness staging script (`apps/desktop/scripts/stage-harness.mjs`) applies Strata's guarded pi-ai 1.1.0 patch to its staged copy +(`harness-budget.mjs`, #3684): below 64K the context safety room is at most `min(4096, floor(contextWindow / 16))` and never more +than half the estimated remaining room, so an 8K window keeps output room after a tool result instead of ending with a one-token +cap. The caller's output cap and the one-token floor remain; windows of 64K or more keep the previous calculation. `BUNDLE.json.patches` +records the patch identity, the dependency version and the before/after SHA-256. Unknown dependency bytes stop staging for review. +Source and already-installed Harness copies are not changed. + +- A local route is reasoning-capable (`reasoning: true`) with `compat.thinkingFormat: 'chat-template'`: the request carries `chat_template_kwargs {enable_thinking, reasoning_effort}`, which the Strata server reads (a top-level `enable_thinking` is ignored by it, which is why pi-ai's `qwen` format left the model thinking). The chat's Reasoning menu travels as `thinking` in the stream body; the bridge sends it with `session/selectModel` (`reasoningEffort`) whenever the model or the level changed; a level a route does not have is dropped (never an error). API routes keep the provider default (the menu is disabled for them in the UI). +- `localOutputBudget(context)` is 30 percent of the window, at least 4096 and at most 32768 (9,830 tokens at 32K, 19,660 at 64K). The Harness's automatic compaction reads it as the room a reply reserves (the request header), and it is NOT the ceiling of a request: `plugins/strata-context.mjs` raises what the adapter sends to half the window, at most 64K tokens (`reply-cut.mjs` `replyCap`; pi-ai clamps it to the window minus the prompt), because a thinking model that writes a whole file in one call was cut inside the call at 19,660 and lost it (AGENT-LOST). A reply that is cut anyway is announced in the chat, the agent is asked to go on in smaller pieces (twice at most), and the file being written is streamed to the page as `agent-tool-draft` frames (name, size, lines, tail of the text). App-loaded models get `fit_max_tokens: true` so the engine clamps instead of answering 400. Sampling is not set here: the Harness sends none, so the server's own defaults apply. + +## Tasks + +`task-run.mjs` runs a scheduled task as the agent: a Harness session of its own (`task:<id>`, dropped after every run), the task's mode (`plan` default, `manual`, `bypass`), and a result built by `../task-report.mjs`. Nobody is at the screen: an approval request is answered "no" at once and reported ("Nothing was changed"). `server/tasks.mjs` stays the only scheduler; it sends a `task` event when a run ends (the page shows a toast). + +## Plain words + +Failures the person sees are plain sentences with a next step (`AgentUnavailable.message`); the technical text is in `.details` / the `details` field of error and notice frames, and in `/api/agent/status` `detail`. A failed tool's card result is a plain sentence followed by "Details: <original text>". + +## Tests + +`tests/agent-events.test.mjs` (pure), `tests/agent-tools-settings.test.mjs` (Settings -> Tools, web search, the browser and the person's own tools; the Harness-backed ones need STRATA_HARNESS_DIR and the browser one also Chrome or Edge), `tests/agent-bridge.test.mjs`, `tests/agent-modes.test.mjs` and `tests/agent-host.test.mjs` (need a built Harness: +`STRATA_HARNESS_DIR=<checkout>`, otherwise they skip and say so). The model in those tests is `tests/helpers/scripted-worker.mjs`. +`scripts/agent-flow.mjs` drives the real app in Chrome and takes screenshots. + +## Helper agents on a named model (`plugins/strata-models.mjs`, `model-routes.mjs`) + +The Harness's `subagent` tool takes an exact `provider` route key and model id. The profile enables the Harness's `subagent-model-selection-settings` with every route the app can reach (local instances and saved API models), and the `strata-models` plugin wraps the two tool definitions the Harness registers for each chat (`subagent`, `list_subagent_models`) in place: + +- the model is found from its id, `provider/id`, the name in the model picker, `connection name`, or "local" (any letters). A close guess is not started: the tool answers "Did you mean ...?" and nothing runs until the call is made again with that model. Several fits are listed; nothing fitting lists the models that can be used and says they can be added in Models. +- the tool's own text says when to use it ("ask a subagent", "ask model X"), not to look for the model with shell commands, and not to wait with sleep. The system prompt (`preset.mjs`) says the same, so it reaches every model, local or hosted. +- `list_subagent_models` lists the models by the names the person knows. + +If a Harness update renames those tools the wrapping does nothing and `tests/agent-subagent-models.test.mjs` (real Harness) fails. + +## Reasoning for API models + +A model on OpenRouter whose model list names `reasoning` in `supported_parameters` gets `reasoning: true` and the efforts `{off: none, low, medium, high, max: xhigh}` and the `openrouter` thinking format, so the Reasoning menu works and the choice reaches OpenRouter as `reasoning: { effort }`. Other API models keep the provider's own default (the menu stays greyed). + +## Pictures + +Pictures are on by default for every model that can read them: an API model reads them unless the person switched it off (Settings > Models > "Read pictures with this model") or its server says it cannot; a local model reads them when it was loaded with Read pictures (on by default). `src/lib/pictures.ts` is the one answer used by the composer and by Send; the agent route declares image input from the same flag. + +## Turn guard (`turn-guard.mjs`) + +A turn that keeps failing the same way is stopped by the app, never left to the model. + +- **Counted, from what the turn shows:** web searches that failed in a row (3), searches in one turn (10 in a plan turn, 25 otherwise), a plan turn that starts its numbered list from `1.` again (4 times), and a context of 93% or more (the Harness's own compaction did not keep up). +- **Stopped the way Stop stops** (`session/cancel`, helpers first) but ended as a normal turn (`done`, not cancelled, no error card), so the plan the model had written is still proposed. The plan card carries the reason (`plan.caution`); any other turn ends with one `delta` frame that has `own: true` and `key` (the English sentence, translated by the page; `GUARD_NOTES` are in the interface catalog in all eight languages). Each sentence says what happened and gives one next step. +- **Compaction:** after a guard stop (and after a turn the model server refused because the context was full) the bridge asks the Harness for `/compact` on that session, so the next message has room. Best effort and logged. +- **Never silent:** a turn that ends (`completed` or `max-tokens`) with no answer text gets "I ran out of room in this chat..." when the last request used 85% of the window or more, otherwise "I stopped without writing an answer..." (not when tool cards were shown, not after Stop, not after an error, which says why by itself). Goal runs have their own ending lines and are not guarded. +- Tests: `tests/agent-turn-guard.test.mjs` (counting, always; end to end with the real Harness, the scripted model's `searchloop` and `bloat` scripts and `searchMock: 'limited'` on the bridge, which runs the real search code on a pretend web that refuses, no network). + +## Context: measured pressure, summaries that fit, the check before a message goes out + +- **`plugins/strata-context.mjs`** (inserted by the profile, like the gate) wraps `tokenMeter.measure` and `llm.stream` in place, once each. Pressure = the last prompt size the model server reported for an answer, plus what changed since priced at the density that measurement showed (`context-budget.mjs`: `pressureNow`, `densityOf`); never lower than the Harness's own price. Node prices are scaled the same way, so the retained tail is in real tokens. A summary request (`purpose: 'compaction'`) that would not fit the window is asked for in pieces: a message bigger than a piece is cut for the request only, each piece builds on the summary before it, a piece the server refuses is halved and tried again. `/strata-context` (a Harness command, like `/strata-gate`) answers `{tokens, window}` for a session so the host can tell the person true figures. +- **`context-fit.mjs`**: before a message is sent the model server counts it (`POST /v1/messages/count_tokens`, its own tokenizer). `decideFit`: send; summarise first and then send (the message fits an otherwise empty chat); or never fits. The last one is not sent: the error frame has `code: 'CONTEXT_MESSAGE_TOO_LARGE'` and the page offers "Attach as a file" (`oversize.mjs`, `/api/chat/oversize`: the text is saved in the chat's folder, the assistant reads it in parts) or "Send a shortened preview". An engine that cannot count lets the message through; the Harness's own compact-and-retry is the net. +- **`/compact`** is handled by the host (`compactCommand`): the Harness's `/compact`, then a plain line with the measured figures ("The chat was 90% full and is now 38% full"), or "nothing older to summarize" when the newest message is what fills the chat. +- **Visible:** `compaction/start` shows "Summarizing earlier messages..." in the status line; `compaction/end` adds one plain line to the reply. The projector also sends a `context` frame after every model request, so the meter follows the running turn. +- **A refusal that is left** (`CONTEXT_WINDOW_EXCEEDED`) is a plain sentence with the engine's text under Details and the buttons "Summarize and continue" and "Start a new chat". "Try sending the message again" is for other errors only. +- Tests: `tests/agent-context.test.mjs` (arithmetic; the real Harness against the scripted worker with `window`, `charsPerToken` and `noCount`), `tests/oversize.test.mjs`, `tests/context-ui.test.mjs`. The run against a real engine is `scripts/context-e2e.mjs`. + +## History / older measurements + +- **Search refusals (2026-10):** on a real box two DuckDuckGo searches in 1.2 s answered, the third got HTTP 202, and every DuckDuckGo page refused for many minutes. + The pacing, cooldown and cache rules above come from that test. +- **Search-heavy `/plan` (2026-10):** every web search was refused, the model searched again and rewrote its plan after each one until the context reached 100%. + The turn ended with no answer and no message. The turn guard comes from that run. +- **Large log paste (2026-10-22, installed 0.2.1, Gyro-S, 64K):** a 118 KB log was 66,500 tokens to the engine and about 29,500 to the Harness + (4 characters a token; logs and code are about 2). The engine refused it with a 400. The refusal stayed in the history, so neither the next message nor `/compact` could + go through, because the summary request carried the same history. `/compact` was also not a command of the app yet: it went to the model as a question. This + produced `strata-context.mjs`, `context-fit.mjs` and the host's own `/compact`. +- **Output budget:** an earlier local budget of a quarter of the window, capped at 8192, cut big answers off at exactly 8192 tokens. diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index 42e0399ee3..c3f2fe7eac 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -1,1459 +1,1459 @@ -/** - * The agent bridge: Strata chats as Harness sessions. - * - * What it owns - * - the pinned Harness process (one, lazily started, restarted only when a route it needs changed); - * - the stable Strata-chat -> Harness-session map, persisted next to the host's other state; - * - one `session/follow` stream per live turn, projected into the NDJSON frames the chat UI renders; - * - approvals: the Harness `approval/request` waterfall in, the user's Approve/Deny back out; - * - Stop: `session/cancel` for exactly one session, resolved only once the turn has really ended. - * - * What it deliberately does not do - * - it never falls back to another model: a chat picks a route (local instance or saved API - * connection) and a missing route is a typed error; - * - it never implements Stop by killing the Harness (that would cancel every other chat); - * - it never holds a secret outside the environment of the agent process it starts. - */ -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; -import { join, resolve } from 'node:path'; -import { homedir, tmpdir } from 'node:os'; -import { fileURLToPath } from 'node:url'; -import { randomUUID } from 'node:crypto'; -import { GatewayClient } from './gateway-client.mjs'; -import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs'; -import { StatusReporter } from './status.mjs'; -import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf, localOutputBudget, compactionHeadroom } from './profile.mjs'; -import { TurnProjector, parseArguments as parseArgs } from './events.mjs'; -import { ChildProjector } from './children.mjs'; -import { nearestBudget } from './llm-shape.mjs'; -import { DeliverableTracker, ActivityGroups } from './deliverables.mjs'; -import { SkillsUsed, skillInfoFrom } from './skills-used.mjs'; -import { turnEngineSpeed } from './engine-speed.mjs'; -import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs'; -import { cutNotice, cutNudge } from './reply-cut.mjs'; - -/** How often one turn asks the agent to carry on after a reply the length limit cut (each time in smaller pieces). */ -export const MAX_CUT_RETRIES = 2; -import { buildAnswer, parseQuestions } from './user-questions.mjs'; -import { BASE_TOKENS, COUNT_ABOVE_CHARS, FIT_TEXT, countTokens, decideFit, fill, grouped } from './context-fit.mjs'; -import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; - -/** - * A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical - * text for the Details disclosure (experts), already free of secrets. - */ -export class AgentUnavailable extends Error { - constructor(message, code = 'agent-unavailable', details = null) { super(message); this.name = 'AgentUnavailable'; this.code = code; this.details = details; } -} - -/** The plain sentence for a raw agent failure text, whatever produced it. */ -export function plainAgentFailure(raw) { - const text = String(raw ?? ''); - if (/did not print its address|exited during start|could not start|ECONNREFUSED.*127\.0\.0\.1|refused the launch token|socket/i.test(text)) return 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.'; - if (/process stopped|lost the session stream|stream did not open|session stream/i.test(text)) return 'The coding assistant stopped unexpectedly, so this answer is incomplete. Send your message again.'; - if (/did not accept the message/i.test(text)) return 'The coding assistant did not take this message. Send it again in a moment.'; - return text; -} - -/** - * A failure thrown while a turn starts, as `{ message, details, code }` for the chat's error card. The agent's own errors read like - * `session/create: tool-bash (...): waiting for shell ...` (a plugin chain that never started): never shown raw. The plain sentence - * goes in `message`; the technical text goes in `details`, which the app shows only behind Details. - */ -export function plainTurnFailure(err) { - const raw = String(err?.message ?? err ?? ''); - const details = typeof err?.details === 'string' && err.details ? err.details : raw; - if (err instanceof AgentUnavailable) return { message: err.message, details, code: err.code ?? 'AGENT_ERROR' }; - if (err?.code === 'agent-preset/invalid' || /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)|failed to import|did not activate/i.test(raw)) { - return { message: 'The coding assistant is missing a part it needs, so it cannot work on files yet. Close and reopen Strata. If it keeps happening, reinstall Strata. Chatting without tools still works.', details, code: 'AGENT_INCOMPLETE' }; - } - if (/^[a-z][a-z-]*\/[a-z][a-z-]*: /i.test(raw) || /^(gateway|rpc)/i.test(raw)) { - return { message: 'The coding assistant could not start this message. Try again. If it keeps happening, close and reopen Strata.', details, code: err?.code ?? 'AGENT_ERROR' }; - } - return { message: plainAgentFailure(raw), details, code: err?.code ?? 'AGENT_ERROR' }; -} - -/** The Harness's plugins start one after another: until they are all up, session/create answers "<plugin>: waiting for <service>". */ -const STARTING_UP = /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)/i; - -/** - * Create a Harness session, waiting for its plugins to finish starting. Right after the app opens (or the Harness restarts) the first - * message can arrive before they are up: that is retried every `retryMs` for up to `readyMs` (`onWait` tells the page "Starting the assistant…") - * instead of failing the first chat. Any other error is thrown at once; a start that never finishes is a plain AGENT_NOT_READY error - * with the Harness's text kept for Details. Returns null when `cancelled()` turns true while waiting. - */ -export async function createSessionWhenReady(create, { readyMs = 60_000, retryMs = 1_500, onWait = () => {}, cancelled = () => false, now = Date.now } = {}) { - const until = now() + readyMs; - for (;;) { - try { return await create(); } catch (e) { - const text = String(e?.message ?? e ?? ''); - if (!STARTING_UP.test(text)) throw e; - if (now() >= until) throw new AgentUnavailable('The assistant could not start. Try again in a moment.', 'AGENT_NOT_READY', text); - onWait(); - await new Promise(r => setTimeout(r, retryMs)); - if (cancelled()) return null; - } - } -} - -/** Attached pictures (data addresses) as the Harness's image prompt parts. */ -export function imageParts(images) { - return (Array.isArray(images) ? images : []).map(i => { - const m = /^data:(image\/(?:png|jpeg|webp));base64,(.+)$/.exec(String(i?.url ?? '')); - return m ? { type: 'image', mediaType: m[1], data: m[2], name: String(i.name ?? 'Picture').slice(0, 120) } : null; - }).filter(Boolean); -} - -/** A timer that never keeps the process alive by itself. */ -const after = (ms, fn) => { const t = setTimeout(fn, ms); t.unref?.(); return t; }; -/** The app's own host folder: never a place an answer's files can be (this file lives in <host>/server/agent). */ -const HOST_DIR = fileURLToPath(new URL('../..', import.meta.url)); - -const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; }; - -/** - * @param {object} options - * @param {string} options.dataDir the host's data directory (agent state lives in `<dataDir>/agent`) - * @param {string|null} [options.componentsDir] where installed components live - * @param {() => Array} options.localInstances ready local instances (see profile.mjs) - * @param {() => Array} options.connections saved API connections WITH their keys (host-internal) - * @param {() => (string|null)} [options.defaultLocalId] the local instance the chat runs on: its tool servers are the agent's (T5) - * @param {NodeJS.ProcessEnv} [options.env] - * @param {string} [options.nodePath] the Node runtime that runs the Harness - * @param {(line:string)=>void} [options.log] - */ -export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, defaultLocalId = () => null, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, engineProgress = () => null, engineGraceMs = 30 * 60_000, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000, sessionReadyMs = 60_000, sessionRetryMs = 1_500 }) { - const root = join(dataDir, 'agent'); - const home = join(root, 'home'); - const sessionsFile = join(root, 'sessions.json'); - mkdirSync(root, { recursive: true }); - - /** - * Where the turn's file tracker must never look (deliverables.mjs): the app, the engine and its components, Strata's own data, AppData - * and temp. `forbid` ones also switch tracking off when the chat's folder is one of them or inside one. - */ - function trackerFolders() { - const user = env.USERPROFILE ?? env.HOME ?? homedir(); - const forbid = [HOST_DIR, componentsDir, bundledDir].filter(Boolean); - const exclude = [dataDir, tmpdir(), env.LOCALAPPDATA, env.APPDATA, env.ProgramData, env.ProgramFiles, env['ProgramFiles(x86)'], env.TEMP, env.TMP, - join(user, 'AppData'), join(user, '.cache'), join(user, '.config'), join(user, '.local'), join(user, 'Library')].filter(Boolean); - return { forbid, exclude }; - } - - /** chatId -> { sessionId, cwd, createdAt } */ - let sessionMap = {}; - if (existsSync(sessionsFile)) { - try { sessionMap = JSON.parse(readFileSync(sessionsFile, 'utf8')) ?? {}; } catch { sessionMap = {}; } - } - const persist = () => { - const temp = `${sessionsFile}.${randomUUID()}.tmp`; - writeFileSync(temp, JSON.stringify(sessionMap, null, 2)); - renameSync(temp, sessionsFile); - }; - - /** @type {{hp:HarnessProcess, gw:GatewayClient, profile:object, clientId:string|null, generation:number, events:object}|null} */ - let rt = null; - let generation = 0; - let lastError = null; - let starting = null; - const chats = new Map(); // chatId -> { turn, route, routeGeneration } - const plans = new PlanStore(join(root, 'plans.json')); - /** chatId -> messages the person typed while a goal ran: [{ id, text, at, deliverAt }]; delivered between steps or when the goal ends */ - const queues = new Map(); - const queueView = chatId => (queues.get(chatId) ?? []).map(({ id, text, at, deliverAt }) => ({ id, text, at, deliverAt })); - const pending = new Map(); // `${sessionId}:${callId}` -> { eventId, sessionId, callId, at } - const questions = new Map(); // `${sessionId}:${callId}` -> the agent's own question waiting for the person: { eventId, sessionId, callId, items, at, clientId } (#4244) - const chatOfSession = sessionId => Object.keys(sessionMap).find(id => sessionMap[id]?.sessionId === sessionId) ?? null; - const idleWaiters = new Set(); - - const chat = id => { let c = chats.get(id); if (!c) { c = { id, turn: null, route: null, routeGeneration: -1 }; chats.set(id, c); } return c; }; - const activeTurns = () => [...chats.values()].filter(c => c.turn).length; - const notifyIdle = () => { if (activeTurns() === 0) { for (const w of idleWaiters) w(); idleWaiters.clear(); } }; - const waitIdle = (signal, ms) => new Promise((resolve, reject) => { - if (activeTurns() === 0) return resolve(); - const timer = setTimeout(() => { idleWaiters.delete(done); reject(new AgentUnavailable('Another chat is still working and the list of models changed. Try again when it finishes.', 'agent-busy')); }, ms); - const done = () => { clearTimeout(timer); resolve(); }; - idleWaiters.add(done); - signal?.addEventListener('abort', () => { clearTimeout(timer); idleWaiters.delete(done); reject(signal.reason ?? new Error('aborted')); }, { once: true }); - }); - - /** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */ - let shapeTargets = {}; - function buildProfileNow() { - const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock, defaultLocalId: defaultLocalId() }); - shapeTargets = profile.shapeTargets ?? {}; - return profile; - } - const llmTarget = key => shapeTargets[key] ?? null; - - function harnessInfo() { return resolveHarness({ env, componentsDir, bundledDir }); } - /** Where the agent component is (the browser tool server lives inside it), or null. */ - const harnessDir = () => { const h = harnessInfo(); return h.ok ? h.dir : null; }; - - /** The capability state the app shows. Never carries a token or a key. */ - function status() { - const h = harnessInfo(); - if (!h.ok) return { state: 'unavailable', reason: 'The coding assistant isn’t installed on this computer yet. Chat works without it.', detail: h.reason, code: 'component-missing' }; - const profile = buildProfileNow(); - return { - state: rt?.hp.running ? 'ready' : starting ? 'starting' : lastError ? 'error' : 'idle', - reason: lastError ? plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again.' : plainAgentFailure(lastError) : null, - detail: lastError ?? null, - harness: { version: h.version }, - runtime: rt?.hp.running ? { pid: rt.hp.pid, generation: rt.generation } : null, - routes: profile.routes.map(({ route, kind, modelId, name, contextWindow }) => ({ route, kind, modelId, name, contextWindow })), - // tool servers that could not be wired (a name the rule does not allow, no program or address): the chat says so - skippedServers: profile.mcpSkipped ?? [], - activeTurns: activeTurns(), - pendingApprovals: pending.size, - }; - } - - async function startRuntime(profile) { - const h = harnessInfo(); - if (!h.ok) throw new AgentUnavailable('The coding assistant isn’t installed on this computer yet. Chat works without it.', 'component-missing', h.reason); - mkdirSync(home, { recursive: true }); - const stale = stopStaleAgent(join(root, 'harness.pid')); - if (stale) log(`agent · stopped a leftover Harness process (pid ${stale}) from an earlier run`); - const patchFile = join(root, `profile-${profile.signature}.patch.yml`); - writeFileSync(patchFile, profile.patch); - const workdir = join(root, 'run'); - const hp = new HarnessProcess({ - harness: h, home, patchFile, cwd: workdir, env: profile.env, nodePath, logFile: join(root, 'harness.log'), pidFile: join(root, 'harness.pid'), - onExit: exit => { - log(`agent · the Harness process exited (code ${exit.code})`); - if (rt?.hp === hp) { lastError = 'The agent process stopped.'; rt = null; } - for (const c of chats.values()) c.turn?.abortFromRuntime('The agent process stopped before this turn finished.'); - }, - }); - const info = await hp.start({ timeoutMs: startTimeoutMs }); - const gw = new GatewayClient({ baseUrl: info.baseUrl, token: info.token }); - await gw.connect(); - const next = { hp, gw, profile, clientId: null, generation: ++generation, events: null }; - next.events = gw.openStream('$events', {}, { - onItem: value => onHostEvent(next, value), - onError: e => log(`agent · event stream: ${redact(e.message, Object.values(profile.env))}`), - }); - rt = next; - lastError = null; - log(`agent · Harness ${h.version ?? ''} ready (pid ${hp.pid}, ${profile.routes.length} route(s))`); - return next; - } - - /** The local engine's own speed for this turn's requests (null when it cannot be read: the stream's estimate stays). */ - async function engineSpeedOf(route, projector) { - const inst = localInstances().find(i => i.id === route.instanceId); - if (!inst) return null; - return turnEngineSpeed({ baseUrl: inst.baseUrl, key: inst.key, since: projector.startedAt, attempts: projector.streams.size, timeoutMs: 800 }); - } - - /** Make sure a runtime exists that knows the route this turn needs. */ - async function ensureRuntime(choice, signal) { - for (;;) { - if (starting) { await starting.catch(() => {}); continue; } - const profile = buildProfileNow(); - const route = routeFor(profile, choice); - if (!route) { - throw new AgentUnavailable(choice?.connectionId - ? 'This API model is no longer available. Choose another model in the chat picker.' - : 'No local model is ready for the agent. Load a model in Models, or choose an API model.', 'model-unavailable'); - } - const known = rt?.hp.running && rt.profile.toolsSignature === profile.toolsSignature && rt.profile.routes.some(r => r.route === route.route && r.modelId === route.modelId && r.fp === route.fp); - if (known) return { rt, route }; - starting = (async () => { - if (rt?.hp.running) { - await waitIdle(signal, 120_000); - const old = rt; rt = null; - old.events?.close(); old.gw.close(); await old.hp.stop(); - } - try { return await startRuntime(profile); } catch (e) { - lastError = redact(String(e.message ?? e), Object.values(profile.env)); - throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.' : plainAgentFailure(lastError), 'agent-start-failed', lastError); - } - })(); - try { await starting; } finally { starting = null; } - } - } - - function onHostEvent(runtime, value) { - if (value.type === 'ready') { runtime.clientId = value.clientId; return; } - if (value.type === 'waterfall' && value.event === 'approval/request') { - const r = value.request ?? {}; - if (!r.callId) return; - pending.set(`${value.agentId}:${r.callId}`, { eventId: value.eventId, sessionId: value.agentId, callId: r.callId, tool: r.toolName, reason: r.reason ?? null, at: Date.now(), clientId: runtime.clientId }); - } else if (value.type === 'waterfall' && value.event === 'user-questions/request') { - // The agent of a chat that is running in front of the person asks the person: the question goes to the page (the question card above the message box) and the - // Harness waits for the answer. Anything else (a helper's question, a chat that is stopping, a request with nothing to show) is declared - // unanswerable, which makes the tool return an error the model reads and carries on from, instead of a turn that waits forever. - const r = value.request ?? {}; - const chatId = chatOfSession(value.agentId); - const turn = chatId ? chats.get(chatId)?.turn : null; - const items = parseQuestions(r.questions); - // A goal or a plan step runs without anyone there: a question would stall it, so it is declined at once (the model reads "could not be answered" and goes on). - if (!turn || turn.finished || turn.stopping || turn.goalRun || turn.plan || !turn.announceQuestion || !items.length) { - void runtime.gw.answerEvent({ clientId: runtime.clientId, eventId: value.eventId, outcome: 'next' }).catch(() => {}); - } else { - const callId = String(r.wait?.callId ?? value.eventId); - questions.set(`${value.agentId}:${callId}`, { eventId: value.eventId, sessionId: value.agentId, callId, items, at: Date.now(), clientId: runtime.clientId }); - turn.announceQuestion({ type: 'agent-question', callId, questions: items }); - } - } else if (value.type === 'cancel') { - for (const [k, v] of questions) if (v.eventId === value.eventId) { questions.delete(k); chats.get(chatOfSession(v.sessionId))?.turn?.announceQuestion?.({ type: 'agent-question-end', callId: v.callId }); } - for (const [k, v] of pending) if (v.eventId === value.eventId) pending.delete(k); - } - } - - async function sessionFor(c, cwd, runtime, { onWait = () => {} } = {}) { - let known = sessionMap[c.id]; - // The chat's folder changed: the agent's working folder and sandbox are fixed when its session starts, so the chat gets a new session - // in the new folder (the earlier conversation is carried into its first message, as for any fresh session). - if (known && cwd && known.cwd && resolve(known.cwd) !== resolve(cwd)) { delete sessionMap[c.id]; persist(); known = null; } - if (known) return { sessionId: known.sessionId, fresh: false }; - const created = await createSessionWhenReady(() => runtime.gw.rpc('session/create', { request: { cwd } }), { readyMs: sessionReadyMs, retryMs: sessionRetryMs, onWait, cancelled: () => c.cancelStart }); - if (!created) return null; - sessionMap[c.id] = { sessionId: created.sessionId, cwd, createdAt: new Date().toISOString() }; - persist(); - return { sessionId: created.sessionId, fresh: true }; - } - - /** - * Put the session into the preset of the chat's mode, through the Harness's own `/permission` command, and - * check that it took. A turn never starts in a mode other than the one asked for: if the switch cannot be - * confirmed the turn fails closed with a typed error instead of running with unknown permissions. - */ - async function applyMode(runtime, sessionId, mode) { - const want = MODE_PRESETS[mode].key; - const read = async () => { - const r = await runtime.gw.rpc('session/projections', { request: { sessionId, keys: ['permissions'] } }); - return r?.values?.permissions?.currentValue ?? null; - }; - try { - if (await read() !== want) { - const done = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: `/permission ${want}`, submittedAttachments: [] }); - if (done?.result?.kind !== 'success') throw new Error(done?.result?.text ?? 'the agent did not recognise the command'); - const now = await read(); - if (now !== want) throw new Error(`the session reports "${now}" instead of "${want}"`); - } - } catch (e) { - throw new AgentUnavailable(`Strata could not set this chat to ${MODE_PRESETS[mode].name} mode, so nothing ran. Try again.`, 'mode-unavailable', e.message); - } - // Manual leaves the sandbox open and relies on the Strata gate to ask first. Without the gate it must not start. - if (mode === 'manual' && !runtime.gateChecked) { - try { - const probe = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-gate', submittedAttachments: [] }); - if (probe?.result?.kind !== 'success' || !String(probe.result.text ?? '').includes('strata-gate active')) throw new Error('the approval gate is not loaded'); - runtime.gateChecked = true; - } catch (e) { - throw new AgentUnavailable('Strata could not make sure the coding assistant asks before changing anything, so nothing ran. Close and reopen Strata, then try again.', 'mode-unavailable', e.message); - } - } - } - - /** - * Run one agent turn for a Strata chat and stream it as frames. - * `signal` means the client went away: the turn keeps running (that is not Stop). - */ - async function runTurn(options) { - const c = chat(options.chatId); - if (c.turn || c.starting) throw new AgentUnavailable('This chat is still working. Stop it or wait for it to finish.', 'turn-active'); - // From here until the Harness has the prompt, Stop has no session to cancel; it cancels the start. - c.starting = true; c.cancelStart = false; - try { return await runTurnInner(c, options); } finally { c.starting = false; } - } - - async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, thinkingBudget = 0, images = [], planTask = null, planRun = null, researchTopic = null }) { - let send = onFrame; let attached = true; - // A research run gathers first; what the assistant writes while gathering is notes, not the answer, so it is not shown. - let hideDeltas = !!researchTopic; - signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true }); - // What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary. - const written = { all: '', step: '' }; - // The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known. - let guard = null; - const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } }; - // What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends. - const tracker = new DeliverableTracker(workspacePath, trackerFolders()); - let toolsRan = false; // a turn that ran no tool wrote nothing, so there is nothing to look for at its end - try { tracker.snapshot(); } catch { /* a folder that cannot be read has no deliverables */ } - const groups = new ActivityGroups({ emit: raw }); - const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) }); - const emit = frame => { - if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (guard) trip(guard.text(frame.text)); if (hideDeltas) return; } - if (frame.own) { const { own, ...rest } = frame; frame = rest; } - if (frame.type === 'delta' && frame.text) groups.text(); - if (frame.type === 'agent-tool' && frame.tool) { - if (['done', 'error'].includes(frame.tool.state) && !['read', 'read_image', 'glob', 'grep', 'web_fetch', 'web_search'].includes(frame.tool.name)) toolsRan = true; - let made = null; - if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } } - raw(frame); - if (made) raw(made); - if (guard) trip(guard.card(frame.tool)); - groups.card(frame.tool, made); - skills.card(frame.tool); - return; - } - raw(frame); - }; - // What the assistant is doing right now, one small frame (status.mjs). Cleared before the final frame of the turn. - const reporter = new StatusReporter({ emit }); - - emit({ type: 'queued', requestId }); - reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' }); - const { rt: runtime, route } = await ensureRuntime(choice, signal); - const made = await sessionFor(c, workspacePath, runtime, { onWait: () => reporter.set({ phase: 'starting', code: 'assistant-starting', text: 'Starting the assistant…' }) }); - const { sessionId, fresh } = made ?? {}; - const cancelled = () => { reporter.clear(); emit({ type: 'done', finishReason: 'aborted', cancelled: true, tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0, model: route.name, contextMax: route.contextWindow }); return { cancelled: true }; }; - if (c.cancelStart || !made) return cancelled(); - - // The model and the chat's thinking level (the Reasoning menu) are sent to the Harness when either changed. A level the route does - // not have (an API model with its own vocabulary) is dropped and the model's own default stands: never an error for the person. - const level = effortOf(thinking ?? 'Medium'); // the menu's default is Medium - // Response settings the Harness cannot send itself (the thinking budget, the Expert sampling) go through this host's forwarding - // endpoint, on a copy of the route; with every setting at its default the route is used directly, as before. - const budget = level === 'off' ? 0 : nearestBudget(thinkingBudget); - const sampling = proxyBase && route.shaped ? expertSampling() : null; - const provider = route.shaped && (budget || sampling) ? route.shaped[budget] : route.route; - const wanted = `${provider}/${route.modelId}/${level ?? ''}`; - if (c.route !== wanted || c.routeGeneration !== runtime.generation) { - const select = effort => runtime.gw.rpc('session/selectModel', { request: { sessionId, provider, model: route.modelId, ...(effort ? { reasoningEffort: effort } : {}) } }); - try { - try { await select(level); } catch (e) { if (!level || e.code === 'session/not-found') throw e; await select(null); } - } catch (e) { - if (e.code === 'session/not-found') { delete sessionMap[c.id]; persist(); } - throw new AgentUnavailable(`The coding assistant could not use ${route.name}. Pick the model again and retry.`, 'model-unavailable', e.message); - } - c.route = wanted; c.routeGeneration = runtime.generation; - } - - // The chat's permission mode is read once, here, for this whole turn. A change the user makes while the - // turn runs applies to the next one, so a running turn never sees its permissions move under it. - const appliedMode = planTask ? 'plan' : modeOf(mode); - await applyMode(runtime, sessionId, appliedMode); - - // Does the message fit the model's window? Asked before anything is sent, with the model server's own count (context-fit.mjs). A message - // that fits once the older messages are a summary is sent after a summary; one that can never fit is not sent, and the person is told - // plainly and offered the two ways out. Whatever cannot be counted goes through: the Harness recovers from a refusal by itself. - if (!goal && route.kind === 'local') { - const fit = await fitCheck({ runtime, route, sessionId, fresh, history, message }).catch(() => null); - if (fit?.action === 'too-large') { - reporter.clear(); - const values = [grouped(fit.tokens), grouped(fit.window)]; - const text = fill(FIT_TEXT.tooLarge, values); - emit({ type: 'error', message: text, key: FIT_TEXT.tooLarge, values, code: 'CONTEXT_MESSAGE_TOO_LARGE', tokens: fit.tokens, window: fit.window }); - return { error: text }; - } - if (fit?.action === 'summarize') { - reporter.set({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] }); - const done = await compactChat(runtime, sessionId); - reporter.clear(); - if (done.ok) emit(summarizedNote(done.before, done.after, fit.window)); - } - } - - const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval, window: route.contextWindow }); - if (!goal) guard = new TurnGuard({ plan: !!planTask, contextMax: route.kind === 'local' ? route.contextWindow : 0 }); // a saved connection's window is often only assumed: never judged by a guess - projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); }; - const turn = { - sessionId, projector, route, requestId, live: false, lastSeq: -1, - ended: deferred(), follow: null, snapshot: deferred(), finished: false, prompted: false, stopBeforePrompt: false, - abortFromRuntime: reason => finishTurn(reason), finish: failure => finishTurn(failure), - // Helper agents (subagents) the Harness started for this chat, and the state of the run around them. - children: new Map(), subagentCalls: new Map(), parentOpen: false, stopping: false, settleTimer: null, mode: appliedMode, - plan: null, advancing: false, goalRun: false, lastActivity: Date.now(), heard: Date.now(), engineMark: null, watchdog: null, - research: researchTopic ? { phase: 'gather', nudged: false, waitingStart: false } : null, - }; - c.turn = turn; - /** - * A turn must always end. If the Harness sends nothing at all for a while (a tool that never returns, a model server that went - * quiet, a lost event) the turn is stopped and ended with a plain message instead of showing "thinking" forever. A running tool gets - * a longer allowance than a quiet model (a build can be silent for minutes). Whatever the assistant finished is kept. - */ - turn.watchdog = setInterval(() => { - if (turn.finished || turn.stopping) return; - const toolRunning = [...projector.tools.values()].some(x => x.card?.state === 'running' || x.card?.state === 'proposed') || pending.size > 0 && pendingFor(chatId).length > 0; - const limit = toolRunning ? stallToolMs : stallMs; - // A local engine reading a long prompt sends the Harness nothing for minutes (#3623). Its /metrics progress counts as activity, - // for at most engineGraceMs after the Harness last spoke: progress for another chat cannot keep a lost turn alive forever. - if (turn.route?.kind === 'local' && Date.now() - turn.heard < engineGraceMs) { - let mark = null; - try { mark = engineProgress(turn.route.instanceId); } catch { /* no progress known: the Harness alone decides */ } - if (mark != null && mark !== turn.engineMark) { turn.engineMark = mark; turn.lastActivity = Date.now(); return; } - } - if (Date.now() - turn.lastActivity < limit) return; - turn.stalledFor = Math.round((Date.now() - turn.lastActivity) / 1000); - turn.stopping = true; - void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); - for (const h of turn.children.values()) if (!h.done) void runtime.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: sessionId, mode: 'continuable' }).catch(() => {}); - const mins = Math.max(1, Math.round(turn.stalledFor / 60)); - turn.finish(`The assistant stopped answering for ${mins > 1 ? mins + ' minutes' : 'a minute'}, so I ended this turn. Anything it already finished is kept. Send your message again to go on.`); - }, Math.min(15_000, Math.max(200, Math.floor(stallMs / 4)))); - turn.watchdog.unref?.(); - async function finishTurn(failure) { - if (turn.finished) return; - turn.finished = true; - for (const [k, v] of questions) if (v.sessionId === turn.sessionId) questions.delete(k); - clearTimeout(turn.settleTimer); - clearInterval(turn.watchdog); - turn.follow?.close(); - for (const child of turn.children.values()) child.follow?.close(); - if (turn.stopping && !failure) projector.ended = turn.guard ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'user' } }; - reporter.clear(); - const extra = []; - try { if (toolsRan) for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ } - groups.end(); - if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); } - try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ } - // The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself). - let noteReason = turn.guard ?? null; - // A reply the length limit cut ends with a sentence that says so (and what was lost), never with silence (AGENT-LOST). - const cutEnd = !failure && !turn.stopping && projector.ended?.kind === 'max-tokens'; - if (cutEnd && !noteReason) { - const note = cutNotice({ ...projector.cut(), retrying: false }); - extra.push({ type: 'delta', own: true, text: ` - -${note.text}`, key: note.key, values: note.values, noteReason: 'cut' }); - } - if (!noteReason && !cutEnd && guard && !failure && !turn.stopping && !turn.goalRun) { - noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens }); - } - if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); } - for (const f of extra) emit(f); - // The answer speed of a turn on this computer is the engine's own (tokens it produced over its decode time, as the Monitor shows it). - const engine = !failure && route.kind === 'local' ? await engineSpeedOf(route, projector) : null; - const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow, engine }); - for (const f of frames.slice(0, -1)) emit(f); - // Messages typed while the goal ran and not delivered between steps go back to the page now, to be sent as ordinary messages. - if (turn.goalRun && attached) { - const left = queueView(chatId); - if (left.length) { queues.delete(chatId); onQueue(chatId, []); emit({ type: 'queued-release', messages: left.map(({ id, text }) => ({ id, text })) }); } - } - for (const f of frames.slice(-1)) emit(f); - c.turn = null; - turn.ended.resolve({ reason: projector.ended, failure: failure ?? null }); - notifyIdle(); - // A turn that filled the context, or that the guard stopped, leaves a long history behind: summarise the older part now so the next message has room. - if (noteReason === 'context' || noteReason === 'searches' || noteReason === 'searches-failed' || noteReason === 'rewrites' || /context window|too long|exceeds/i.test(String(projector.ended?.error?.message ?? ''))) void compactSession(runtime, sessionId); - } - - emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [], ...(planTask ? { planning: true } : {}) }); - - turn.follow = runtime.gw.openStream('session/follow', { request: { address: { kind: 'session', sessionId }, assistantStream: true } }, { - onItem: item => { - if (item.type === 'snapshot') { - if (turn.lastSeq < 0) turn.lastSeq = item.cursor; - else for (const r of item.records ?? []) if (r.type === 'event' && r.event.seq > turn.lastSeq) handle({ type: 'event', event: r.event }); - turn.snapshot.resolve(); - return; - } - handle(item); - }, - onError: e => finishTurn(`The agent lost the session stream: ${e.message}`), - }); - - /** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */ - function trip(reason) { - if (!reason || turn.guard || turn.finished || turn.stopping) return; - turn.guard = reason; - log(`agent · turn guard: ${reason} (searches ${guard?.searches ?? 0}, failed in a row ${guard?.failedInARow ?? 0}, plan rewrites ${guard?.rewrites ?? 0})`); - void stop(chatId).catch(() => {}); - } - - function handle(item) { - if (turn.finished) return; - turn.lastActivity = Date.now(); - turn.heard = turn.lastActivity; - if (item.type === 'event') { - const e = item.event; - if (e.seq <= turn.lastSeq) return; - turn.lastSeq = e.seq; - // The turn is ours from the user message that carries our request id. Until then an older, - // detached turn on the same session may still be finishing; its events are not ours. - if (!turn.live) { - if (e.type === 'user/message' && e.data?.source?.rpcId === requestId) turn.live = true; - return; - } - } else if (!turn.live) return; - for (const f of projector.consume(item)) emit(f); - if (guard && projector.contextTokens != null) trip(guard.context(projector.contextTokens)); - if (item.type === 'event') watchParent(item.event); - } - - // -- helper agents --------------------------------------------------------------------------------------- - - const rowFrame = child => ({ type: 'agent', agent: child.cp.agent() }); - const emitRow = (child, force = false) => { - const now = Date.now(); - if (!force && now - child.lastRow < 400) { child.rowPending = true; return; } - child.lastRow = now; child.rowPending = false; - emit(rowFrame(child)); - const working = [...turn.children.values()].filter(h => !h.done).length; - if (working && !turn.parentOpen) reporter.set({ phase: 'helpers', code: 'helpers', text: `Helpers are working (${working})…`, key: 'Helpers are working ({0})…', values: [working], args: { n: working } }); - }; - - function openChild(d) { - const id = d.childId; - if (!id || turn.children.has(id)) return; - const cp = new ChildProjector({ id, name: d.label || 'Helper' }); - const child = { id, cp, follow: null, noticed: false, done: false, lastRow: 0, rowPending: false, endedAt: 0 }; - turn.children.set(id, child); - emitRow(child, true); - const fold = item => { - if (turn.finished) return; - turn.lastActivity = turn.heard = Date.now(); - // A helper that finishes before its throttled "working" row went out would show queued -> completed and never "working": send the held row first. - if (item.type === 'event' && item.event.type === 'turn/end' && child.rowPending) emitRow(child, true); - const { frames, row } = cp.consume(item); - for (const f of frames) emit(f); - if (item.type === 'event' && item.event.type === 'turn/end') { child.done = true; child.endedAt = Date.now(); emitRow(child, true); armSettle(); return; } - if (item.type === 'event' && child.done && cp.status === 'working') { child.done = false; } - if (row) emitRow(child); - }; - child.follow = runtime.gw.openStream('session/follow', { - request: { address: { kind: 'subagent', parentSessionId: sessionId, childSessionId: id, mode: d.mode ?? 'unknown' }, assistantStream: true }, - }, { - onItem: item => { - if (item.type === 'snapshot') { for (const r of item.records ?? []) if (r.type === 'event') fold({ type: 'event', event: r.event }); return; } - fold(item); - }, - onError: e => { - log(`agent · helper stream ended: ${e.message}`); - if (!child.done) { child.done = true; child.endedAt = Date.now(); cp.status = 'failed'; cp.failure = 'Lost contact with this helper.'; cp.endedAt = Date.now(); emitRow(child, true); armSettle(); } - }, - }); - // A late reader still gets the final row: flush any row held back by the throttle. - child.flush = after(500, function tick() { if (!turn.finished && child.rowPending) emitRow(child, true); if (!turn.finished && !child.done) child.flush = after(500, tick); }); - } - - function watchParent(e) { - const d = e.data ?? {}; - switch (e.type) { - case 'turn/start': - turn.parentOpen = true; - if (turn.research) turn.research.waitingStart = false; - turn.cutWaiting = false; - clearTimeout(turn.settleTimer); - // After Stop, a helper's report would start a new turn that nobody asked for. - if (turn.stopping) void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); - break; - case 'turn/end': - turn.parentOpen = false; - armSettle(); - break; - // The first turn of a prompt may have started before this follow stream attached (no turn/start seen): any step of the parent is proof that it is - // still working. Without this a helper that finished while the parent was still answering ended the run early ("The agent turn was interrupted"). - case 'step/start': - if (!turn.parentOpen) { turn.parentOpen = true; clearTimeout(turn.settleTimer); } - break; - case 'tool/call': - if (d.name === 'subagent' || d.name === 'subagent_fork') turn.subagentCalls.set(d.callId, parseArgs(d.arguments)); - break; - case 'subagent/catalog': - openChild(d); - break; - case 'tool/result': { - const call = turn.subagentCalls.get(d.message?.toolCallId); - const text = (d.message?.content ?? []).map(p => p.text ?? '').join(' '); - const started = /started subagent ([0-9a-f-]{36})/i.exec(text); - const child = started ? turn.children.get(started[1]) : null; - if (call && child) { child.cp.task = String(call.prompt ?? call.description ?? '').replace(/\s+/g, ' ').trim().slice(0, 140); emitRow(child, true); } - break; - } - case 'user/message': - if (d.source?.kind === 'goal' && Number.isInteger(d.source.round)) { turn.goalRound = d.source.round; void announceGoal(); } - // falls through - case 'agent/inbox/spliced': { - const hit = JSON.stringify(d); - if (!/Background subagent/.test(hit)) break; - for (const child of turn.children.values()) if (hit.includes(child.id)) child.noticed = true; - break; - } - default: - break; - } - } - - // -- plans and goal steps ---------------------------------------------------------------------------------- - - const planFrame = (event, plan, extra = {}) => ({ type: 'plan', event, plan: planView(plan), ...extra }); - const publishPlan = (event, plan) => { onPlan(chatId, event, planView(plan)); return planFrame(event, plan); }; - const stepFrame = (plan, index) => { - const st = plan.steps[index]; - return { type: 'plan-step', planId: plan.id, stepId: st.id, index: index + 1, total: plan.steps.length, state: st.state, text: st.text, summary: st.summary ?? null, line: stepLine(index, plan.steps.length, st.text, st.state === 'running' ? 'started' : st.state) }; - }; - const currentStep = plan => plan.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped'); - - /** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */ - function settlePlan(failure) { - if (planTask) { - if (failure || (turn.stopping && !turn.guard)) return []; - const parsed = parsePlan(written.all, planTask); - if (!parsed) return []; - const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask, ...(turn.guard ? { caution: GUARD_NOTES[turn.guard] } : {}) }); - return [publishPlan('proposed', plan)]; - } - const run = turn.plan; - if (!run) return []; - const plan = plans.get(chatId); - if (!plan || plan.id !== run.id) return []; - if (plan.state !== 'running') return []; - const out = []; - const at = currentStep(plan); - plans.update(chatId, p => { - if (at < 0) { p.state = 'done'; return; } - // The step that was running goes back to waiting, so Resume runs it again. - p.steps[at].state = 'pending'; - p.state = 'paused'; - }); - const updated = plans.get(chatId); - if (at >= 0) out.push(stepFrame(updated, at)); - out.push(publishPlan(updated.state === 'done' ? 'done' : 'paused', updated)); - return out; - } - - /** The goal the Harness runs for the plan's next waiting step, and the frames that say so. */ - async function startStep(plan, index) { - plans.update(chatId, p => { p.state = 'running'; p.goalStarted = true; p.steps[index].state = 'running'; }); - const now = plans.get(chatId); - await runtime.gw.rpc('goals/create', { agentId: sessionId, request: { objective: stepObjective(now, index) } }); - written.step = ''; written.stepAt = Date.now(); - emit(stepFrame(now, index)); - emit(publishPlan('step', now)); - const st = now.steps[index]; - reporter.set({ phase: 'goal', code: 'goal-step', text: stepLine(index, now.steps.length, st.text, 'started'), key: '{0}', values: [st.text], args: { step: index + 1, steps: now.steps.length } }); - } - - /** One goal step finished: say so, hand over queued messages, and begin the next step (or end the plan). */ - async function advancePlan() { - const run = turn.plan; - const plan = plans.get(chatId); - if (!run || !plan || plan.id !== run.id) return false; - const at = currentStep(plan); - if (at < 0) return false; - const cards = [...projector.tools.values()].filter(x => x.calledAt >= (written.stepAt ?? 0) - 50 && x.card?.state === 'done').map(x => x.card); - const summary = stepSummary(cards, written.step.split(/\n\s*\n/).filter(Boolean).at(-1) ?? written.step); - plans.update(chatId, p => { p.steps[at].state = 'done'; p.steps[at].summary = summary; }); - let now = plans.get(chatId); - emit(stepFrame(now, at)); - emit({ type: 'delta', own: true, text: `\n\n${stepLine(at, now.steps.length, now.steps[at].text, 'done')}\n` }); - const next = currentStep(now); - emit(publishPlan(next < 0 ? 'done' : 'step', next < 0 ? (plans.update(chatId, p => { p.state = 'done'; }), plans.get(chatId)) : now)); - await deliverQueued(at + 1); - if (turn.stopping || turn.finished) return true; - if (next < 0) return false; - // One step per turn (Time-skip): the plan stays open for the next step, which starts in a session of its own so the conversation never grows across steps. - if (run.once) { plans.update(chatId, p => { p.state = 'approved'; }); emit(publishPlan('step', plans.get(chatId))); return false; } - await startStep(plans.get(chatId), next); - void announceGoal(); - return true; - } - - /** Hand the person's queued messages to the assistant, one at a time, each answered before the next. */ - async function deliverQueued(afterStep) { - const list = queues.get(chatId) ?? []; - while (list.length && !turn.stopping && !turn.finished) { - const item = list.shift(); - if (!list.length) queues.delete(chatId); - onQueue(chatId, queueView(chatId)); - emit({ type: 'queued-message', state: 'delivered', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, afterStep, queue: queueView(chatId) }); - try { await runtime.gw.rpc('session/prompt', { request: { requestId: `queued-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: item.text }] } }); } - catch { emit({ type: 'queued-release', messages: [{ id: item.id, text: item.text }] }); continue; } - // Wait for the answer: the parent opens a turn for it and closes it again. - const t0 = Date.now(); - while (!turn.parentOpen && Date.now() - t0 < 4000 && !turn.finished) await new Promise(r => setTimeout(r, 50)); - while (turn.parentOpen && !turn.finished && !turn.stopping) await new Promise(r => setTimeout(r, 100)); - } - } - - /** - * The run is over when the parent is idle and every helper has finished and reported back. A helper's report - * wakes the parent a moment after the helper ends, so a helper that ended but has not reported yet keeps the run - * open (for a few seconds at most); after Stop nobody waits for reports. - */ - function armSettle() { - clearTimeout(turn.settleTimer); - if (turn.finished) return; - turn.settleTimer = after(turn.stopping ? 1200 : turn.children.size ? 600 : 0, async () => { - if (turn.finished || turn.parentOpen || turn.advancing) return; - const open = [...turn.children.values()]; - if (open.some(c => !c.done)) return; - if (!turn.stopping) { - if (open.some(c => !c.noticed && Date.now() - c.endedAt < 8000)) { armSettle(); return; } - // An armed goal starts its next round as soon as the agent is idle: the run is not over until the goal stops. - const current = await goalGet(); - if (turn.finished || turn.parentOpen) return; - if (current && current.phase === 'active' && current.activation === 'armed') { turn.settleTimer = after(700, armSettle); return; } - // A reply the length limit cut (AGENT-LOST): the agent lost what it was writing. Say so in the chat and ask it to carry on in smaller pieces, twice at most. - if (turn.cutWaiting) { turn.settleTimer = after(300, armSettle); return; } - if (projector.ended?.kind === 'max-tokens' && !turn.goalRun && !turn.stopping && (turn.cuts ?? 0) < MAX_CUT_RETRIES) { - const cut = projector.cut(); - turn.cuts = (turn.cuts ?? 0) + 1; - const note = cutNotice({ ...cut, retrying: true }); - emit({ type: 'delta', own: true, text: ` - -${note.text} - -`, key: note.key, values: note.values, noteReason: 'cut' }); - for (const f of projector.clearCut()) emit(f); - turn.cutWaiting = true; - try { await runtime.gw.rpc('session/prompt', { request: { requestId: `cut-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: cutNudge(cut) }] } }); } - catch { turn.cutWaiting = false; finishTurn(null); return; } - turn.settleTimer = after(500, armSettle); - return; - } - // Research: gather (search and read pages), then write the answer in the fixed shape. A step that did not open pages is sent back once. - if (turn.research && !turn.stopping) { - const r = turn.research; - if (r.waitingStart) { turn.settleTimer = after(300, armSettle); return; } - const opened = [...projector.tools.values()].filter(x => x.card?.name === 'web_fetch' && x.card.state === 'done').length; - const prompt = r.phase === 'write' ? null : (opened < 2 && !r.nudged) ? RESEARCH_NUDGE : researchWritePrompt(researchTopic); - if (prompt) { - if (prompt !== RESEARCH_NUDGE) { r.phase = 'write'; hideDeltas = false; written.all = ''; reporter.set({ phase: 'waiting', code: 'research-writing', text: 'Writing the answer…', key: 'Writing the answer…', values: [], args: {} }); } else r.nudged = true; - r.waitingStart = true; - try { await runtime.gw.rpc('session/prompt', { request: { requestId: `research-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }] } }); } - catch { r.waitingStart = false; hideDeltas = false; finishTurn(null); return; } - turn.settleTimer = after(500, armSettle); - return; - } - } - // A plan step's goal is complete: record it, deliver queued messages, start the next step. - if (turn.plan && current && current.phase === 'complete' && !turn.advancing) { - turn.advancing = true; - let more = false; - try { more = await advancePlan(); } catch (e) { emit({ type: 'delta', own: true, text: `\n\nThe plan stopped: ${plainGoalError(e)}\n` }); } - turn.advancing = false; - if (more && !turn.finished && !turn.stopping) { turn.settleTimer = after(700, armSettle); return; } - } - - if (turn.goalRun && current) { const line = goalEnding(current); if (line) emit({ type: 'delta', text: line }); } - if (turn.goalRun) await announceGoal(true); - } - finishTurn(null); - }); - } - const goalGet = () => runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined); - /** The goal's state to the page: a `goal` frame, the SSE event for the bar, and (while a round runs) the status line. */ - async function announceGoal(final = false) { - const view = await goalGet(); - if (turn.finished && !final) return; - const goal = goalObject(view, chatId); - emit({ type: 'goal', goal }); - onGoal(chatId, goal); - if (!final && goal && goal.phase === 'active' && turn.goalRound) reporter.set({ phase: 'goal', code: 'goal-step', text: 'Working on the goal…', args: { round: turn.goalRound, max: goal.maxRounds } }); - } - turn.announceGoal = announceGoal; - turn.announceQueue = frame => emit(frame); - turn.announceQuestion = frame => emit(frame); - - const snapshotTimer = {}; - await Promise.race([turn.snapshot.promise, new Promise((_, rej) => { snapshotTimer.t = after(20_000, () => rej(new Error('the session stream did not open'))); })]) - .catch(e => { finishTurn(e.message); }) - .finally(() => clearTimeout(snapshotTimer.t)); - if (turn.finished) return { error: true }; - if (turn.stopBeforePrompt || c.cancelStart) { projector.ended = { kind: 'aborted', reason: { kind: 'user' } }; finishTurn(null); return { cancelled: true }; } - - if (goal) { - // A goal run has no prompt of its own: the Harness's goal driver starts the rounds. Everything from now on is ours. - turn.live = true; turn.goalRun = true; - try { - if (planRun) { - const plan = plans.get(chatId); - if (!plan || plan.id !== planRun.planId) throw new AgentUnavailable('That plan is no longer there. Ask for a new one with /plan.', 'plan-gone'); - turn.plan = { id: plan.id, once: !!planRun.once }; - const at = currentStep(plan); - if (at < 0) throw new AgentUnavailable('Every step of this plan is already done.', 'plan-done'); - if (goal.action === 'resume' && plan.goalStarted) { - plans.update(chatId, p => { p.state = 'running'; p.steps[at].state = 'running'; }); - await startGoal(runtime, sessionId, goal); - emit(publishPlan('step', plans.get(chatId))); - } else await startStep(plan, at); - } else { - await startGoal(runtime, sessionId, goal); - } - } catch (e) { finishTurn(e instanceof AgentUnavailable ? e.message : plainGoalError(e)); return { error: true }; } - reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); - void announceGoal(); - } else { - let prompt = message; - if (fresh && history.length) prompt = withEarlierConversation(history, message); - try { - await runtime.gw.rpc('session/prompt', { request: { requestId, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }, ...imageParts(images)] } }); - } catch (e) { - finishTurn(`The agent did not accept the message: ${e.message}`); - return { error: true }; - } - } - if (!goal) reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); - turn.prompted = true; - if (turn.stopBeforePrompt) { - // Stop landed in the instant between 'prompt sent' and 'prompt accepted'. A cancel before the turn - // starts arms nothing, so wait for the turn to be ours, then cancel it. - for (let i = 0; i < 100 && !turn.live && !turn.finished; i++) await new Promise(r => setTimeout(r, 50)); - if (!turn.finished) await runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); - } - - // Wait for the turn, or for the client to leave. Leaving does not stop the turn. - const gone = new Promise(r => signal?.addEventListener('abort', () => r('detached'), { once: true })); - const outcome = await Promise.race([turn.ended.promise, gone]); - if (outcome === 'detached') return { detached: true, sessionId, ended: turn.ended.promise.then(r => ({ ...r, tokensOut: projector.tokensOut })) }; - return { sessionId, reason: outcome.reason, tokensIn: projector.tokensIn, tokensOut: projector.tokensOut }; - } - - // -- /goal ----------------------------------------------------------------------------------------------- - - /** Create or resume the chat's goal; the Harness's goal driver then runs the rounds by itself. */ - async function startGoal(runtime, sessionId, goal) { - if (goal.action === 'create') { - const request = { objective: goal.objective, ...(goal.maxRounds ? { maxGoalRounds: goal.maxRounds } : {}) }; - await runtime.gw.rpc('goals/create', { agentId: sessionId, request }); - return; - } - const current = await runtime.gw.rpc('goals/get', { agentId: sessionId }); - if (!current) throw new AgentUnavailable('There is no goal to continue. Start one with /goal followed by what you want done.', 'goal-none'); - await runtime.gw.rpc('goals/resume', { agentId: sessionId, ref: { id: current.id, revision: current.revision } }); - } - - async function pauseGoal(runtime, sessionId, chatId = null) { - try { - const current = await runtime.gw.rpc('goals/get', { agentId: sessionId }); - if (current && current.phase === 'active') { - await runtime.gw.rpc('goals/pause', { agentId: sessionId, ref: { id: current.id, revision: current.revision } }); - if (chatId) onGoal(chatId, goalObject(await runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined))); - } - } catch { /* no goal service, or nothing to pause */ } - } - - /** The goal as the page and the goal bar see it (notes-split-agent3.md), or null. */ - function goalObject(view, chatId = null) { - if (!view) return null; - const phase = ['active', 'paused', 'complete', 'blocked'].includes(view.phase) ? view.phase : 'blocked'; - // A goal that is running a plan (or the points of a goal) shows the plan's title and which step it is on. - const plan = chatId ? plans.get(chatId) : null; - const running = plan && plan.goalStarted && ['running', 'paused'].includes(plan.state) ? plan : null; - const at = running ? running.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped') : -1; - const step = running && at >= 0 ? { index: at + 1, total: running.steps.length, text: running.steps[at].text } : null; - return { objective: step ? running.title : String(view.objective ?? ''), ...(step ? { step } : {}), phase, round: view.roundsStarted ?? 0, maxRounds: view.maxGoalRounds ?? null, ...(phase === 'blocked' ? { blocked: plainBlocker(view.blockedReason) } : {}) }; - } - - /** The goal of a chat now, from the Harness (null: none, or the agent is not running). */ - async function goalState(chatId) { - const known = sessionMap[chatId]?.sessionId; - if (!known || !rt?.hp.running) return null; - return goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId); - } - - /** Pause, edit or remove the goal from the goal bar. Instant; resume runs rounds and goes through the chat stream. */ - async function goalControl({ chatId, action, text }) { - const known = sessionMap[chatId]?.sessionId; - if (!known || !rt?.hp.running) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none'); - const current = await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined); - if (!current) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none'); - const ref = { id: current.id, revision: current.revision }; - try { - if (action === 'pause') { if (current.phase === 'active') await rt.gw.rpc('goals/pause', { agentId: known, ref }); } - else if (action === 'clear') await rt.gw.rpc('goals/clear', { agentId: known, ref }); - else if (action === 'edit') { - const objective = String(text ?? '').trim().slice(0, 4000); - if (!objective) throw new AgentUnavailable('A goal needs a few words about what you want done.', 'goal-text'); - await rt.gw.rpc('goals/edit', { agentId: known, ref, request: { objective } }); - } else throw new AgentUnavailable('That goal action is not known.', 'goal-action'); - } catch (e) { throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainGoalError(e), 'goal-failed', e.message); } - if (action === 'clear') { const plan = plans.get(chatId); if (plan && ['running', 'paused'].includes(plan.state)) { plans.update(chatId, p => { p.state = 'stopped'; for (const st of p.steps) if (st.state === 'running') st.state = 'pending'; }); onPlan(chatId, 'stopped', planView(plans.get(chatId))); } } - const goal = action === 'clear' ? null : goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId); - onGoal(chatId, goal); - return { goal }; - } - - /** The goal's state in plain words. */ - function describeGoal(view) { - if (!view) return 'No goal is set. Start one with /goal followed by what you want done.'; - const what = `"${view.objective}"`; - if (view.phase === 'active') return `Working on the goal ${what}.`; - if (view.phase === 'paused') return `The goal ${what} is paused. Type /goal resume to go on.`; - if (view.phase === 'complete') return `The goal ${what} is complete.`; - return `The goal ${what} stopped: ${plainBlocker(view.blockedReason)}`; - } - - /** - * Handle a "/goal ..." line for a chat, as the Harness's own /goal command reads it: nothing = show the goal, - * clear, pause, resume, edit <text>, or any other text = a new goal. Starting or resuming runs the rounds and - * streams them like a chat turn (Stop pauses the goal); every other verb answers at once. - */ - async function goalCommand(options) { - const { chatId, line, onFrame } = options; - const text = String(line ?? '').trim(); - const verb = text.split(/\s+/)[0]?.toLowerCase() ?? ''; - const rest = text.slice(verb.length).trim(); - const say = reply => { - onFrame({ type: 'queued', requestId: `goal-${randomUUID()}` }); - onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); - onFrame({ type: 'delta', text: reply }); - onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); - return { goal: true }; - }; - if (tools()?.off?.has('goals')) return say('Goals are turned off. You can turn them back on in Settings, Tools.'); - const known = sessionMap[chatId]?.sessionId; - const quick = ['', 'clear', 'pause', 'edit', 'complete'].includes(verb) || (verb === 'status'); - let runtime = rt; - if (quick) { - if (!known || !runtime?.hp.running) return say(verb === '' || verb === 'status' ? describeGoal(null) : 'There is no goal in this chat yet.'); - const current = await runtime.gw.rpc('goals/get', { agentId: known }).catch(() => undefined); - const ref = current ? { id: current.id, revision: current.revision } : null; - try { - if (verb === '' || verb === 'status') return say(describeGoal(current)); - if (!ref) return say('There is no goal in this chat yet.'); - if (verb === 'clear') { await runtime.gw.rpc('goals/clear', { agentId: known, ref }); return say('The goal is cleared.'); } - if (verb === 'pause') { - if (current.phase === 'active') await runtime.gw.rpc('goals/pause', { agentId: known, ref }); - return say(describeGoal(await runtime.gw.rpc('goals/get', { agentId: known }))); - } - if (verb === 'complete') { await runtime.gw.rpc('goals/complete', { agentId: known, ref }); return say('The goal is marked complete.'); } - if (verb === 'edit') { - if (!rest) return say('Type /goal edit followed by the new wording of the goal.'); - await runtime.gw.rpc('goals/edit', { agentId: known, ref, request: { objective: rest } }); - return say(`The goal now reads: "${rest}".`); - } - } catch (e) { return say(plainGoalError(e)); } - } - if (verb === 'resume') { - const plan = plans.get(chatId); - const goalPlan = plan && plan.goalStarted && plan.state === 'paused' ? { planId: plan.id } : null; - return runTurn({ ...options, goal: { action: 'resume' }, ...(goalPlan ? { planRun: goalPlan } : {}) }); - } - // A goal whose own words hold numbered points ("1. ... 2. ... 3. ...") runs point by point, each one reported. - const points = parsePoints(text); - if (points) { - const plan = plans.create(chatId, { title: points.title, steps: points.steps, request: text, source: 'goal', state: 'approved' }); - onPlan(chatId, 'approved', planView(plan)); - return runTurn({ ...options, goal: { action: 'create', objective: text }, planRun: { planId: plan.id } }); - } - // Any other text is a new goal. One unfinished goal at a time (the Harness's rule): say so in plain words. - return runTurn({ ...options, goal: { action: 'create', objective: text } }); - } - - // -- /plan ----------------------------------------------------------------------------------------------- - - /** A short answer in the chat that the page translates (the sentence is in the interface catalog, "values" fill its slots). */ - function sayKey(options, template, values = []) { - const { onFrame } = options; - onFrame({ type: 'queued', requestId: 'compact-' + randomUUID() }); - onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); - onFrame({ type: 'delta', text: fill(template, values), key: template, values }); - onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); - return { compact: true }; - } - - /** A short answer in the chat (no model): the same frames a turn sends. */ - function sayOnce(options, reply) { - const { onFrame } = options; - onFrame({ type: 'queued', requestId: `plan-${randomUUID()}` }); - onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); - onFrame({ type: 'delta', text: reply }); - onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); - return { plan: true }; - } - - /** - * "/plan <what you want>": the assistant looks around (the chat is put in Plan mode for this turn, so nothing can change), writes the - * plan, and the host sends it as a `plan` frame. Nothing runs until the person approves it. - */ - async function planCommand(options) { - const task = String(options.line ?? '').trim(); - if (!task) { - const open = plans.get(options.chatId); - return sayOnce(options, open && ['proposed', 'approved'].includes(open.state) - ? 'A plan is waiting for you above. Approve it, edit it or reject it, or type /plan followed by something else to make a new one.' - : 'Type /plan followed by what you want done, for example: /plan build a small pagoda page. I will look around and write a plan; nothing changes until you approve it.'); - } - return runTurn({ ...options, message: planPrompt(task), planTask: task, mode: 'plan' }); - } - - /** - * "/research <topic>": the assistant searches the web, opens and reads pages, and writes a short structured answer (Summary, Key findings, - * Sources). The host also sends the sources as a `research` frame before the end of the turn. Needs web search turned on. - */ - async function researchCommand(options) { - const topic = String(options.line ?? '').trim(); - if (!topic) return sayOnce(options, 'Type /research followed by what you want to know, for example: /research how do heat pumps compare with gas boilers. I will search the web, read the pages and answer with sources.'); - if (tools()?.off?.has('search')) return sayOnce(options, 'Research needs web search, which is turned off. Turn it on in Settings, Tools (DuckDuckGo needs no key), then try again.'); - return runTurn({ ...options, message: researchPrompt(topic), researchTopic: topic }); - } - - const planGone = () => new AgentUnavailable('There is no plan waiting in this chat. Ask for one with /plan followed by what you want done.', 'plan-gone'); - function planOf(chatId, planId) { - const plan = plans.get(chatId); - if (!plan || (planId && plan.id !== planId)) throw planGone(); - return plan; - } - const mustBeOpen = plan => { if (plan.state !== 'proposed' && plan.state !== 'approved') throw new AgentUnavailable('This plan has already been used. Ask for a new one with /plan.', 'plan-used'); }; - - /** A short note added to every step of the chat's plan (the Time-skip B path: where its work comes from). */ - function setPlanBriefing(chatId, text) { plans.update(chatId, p => { p.briefing = String(text ?? '').slice(0, 600); }); } - - /** The plan of a chat, or null. */ - const planState = chatId => planView(plans.get(chatId)); - - /** Approve, edit or reject the plan; instant. Approve also returns the message that carries the plan out as an ordinary turn. */ - function planControl({ chatId, planId, action, steps, title }) { - const plan = planOf(chatId, planId); - if (action === 'edit') { - mustBeOpen(plan); - const next = editedSteps(steps, plan.steps); - const t = String(title ?? '').replace(/\s+/g, ' ').trim().slice(0, 80); - plans.update(chatId, p => { p.steps = next; if (t) p.title = t; p.state = 'proposed'; }); - onPlan(chatId, 'edited', planView(plans.get(chatId))); - return { plan: planView(plans.get(chatId)) }; - } - if (action === 'approve') { - mustBeOpen(plan); - plans.update(chatId, p => { p.state = 'approved'; }); - const approved = plans.get(chatId); - onPlan(chatId, 'approved', planView(approved)); - return { plan: planView(approved), prompt: planAsPrompt(approved) }; - } - if (action === 'reject') { - mustBeOpen(plan); - plans.update(chatId, p => { p.state = 'rejected'; }); - onPlan(chatId, 'rejected', planView(plans.get(chatId))); - return { plan: planView(plans.get(chatId)) }; - } - throw new AgentUnavailable('That plan action is not known.', 'plan-action'); - } - - /** "Start as goal": each step of the plan becomes a goal step, run one after another and reported. Streams like a chat turn. */ - async function planGoal(options) { - const { chatId, planId } = options; - let plan; - try { plan = planOf(chatId, planId); } catch (e) { return sayOnce(options, e.message); } - if (modeOf(options.mode) === 'plan') return sayOnce(options, 'Plan mode only looks, so it cannot carry out a plan. Switch this chat to Manual or Bypass, then start it again.'); - if (plan.state === 'paused' && plan.goalStarted) return goalCommand({ ...options, line: 'resume' }); - try { mustBeOpen(plan); } catch (e) { return sayOnce(options, e.message); } - if (tools()?.off?.has('goals')) return sayOnce(options, 'Goals are turned off. You can turn them back on in Settings, Tools.'); - plans.update(chatId, p => { p.state = 'approved'; }); - onPlan(chatId, 'approved', planView(plans.get(chatId))); - return runTurn({ ...options, goal: { action: 'create', objective: plan.title }, planRun: { planId: plan.id, once: options.once === true } }); - } - - /** A paused plan becomes open again (a step that did not finish is tried again in a fresh session). */ - function reopenPlan(chatId) { const p = plans.get(chatId); if (p && p.state === 'paused') { plans.update(chatId, x => { x.state = 'approved'; }); onPlan(chatId, 'approved', planView(plans.get(chatId))); } } - - /** Give up on one step with a plain note (a check that cannot be done here) so the rest of the plan can go on. */ - function skipStep(chatId, index, note) { plans.update(chatId, p => { const st = p.steps[index]; if (st) { st.state = 'skipped'; st.summary = String(note ?? 'Skipped.').slice(0, 140); } if (p.state === 'paused') p.state = 'approved'; }); onPlan(chatId, 'step', planView(plans.get(chatId))); } - - /** Forget the chat's agent session (not its plan): the next turn starts a fresh one in the same folder. */ - function resetSession(chatId) { - if (chats.get(chatId)?.turn || chats.get(chatId)?.starting) throw new AgentUnavailable('This chat is still working.', 'turn-active'); - delete sessionMap[chatId]; persist(); - } - - // -- the agent's own questions ------------------------------------------------------------------------------ - - /** - * The person's answer to a question the agent asked (#4244), or a skip. The answer is checked against the questions that were asked, then sent - * to the Harness as the result of the waiting `user-questions/request`; a skip declares the question unanswerable, as before, and the model - * carries on. - */ - async function answerQuestion({ chatId, callId, answers, skip = false }) { - const sessionId = sessionMap[chatId]?.sessionId; - const key = `${sessionId}:${callId}`; - const entry = questions.get(key); - if (!entry || !rt?.hp.running) throw new AgentUnavailable('That question was already answered, or the assistant has gone on.', 'question-gone'); - const outcome = skip ? 'next' : buildAnswer(entry.items, answers); - await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome }); - questions.delete(key); - return { ok: true, skipped: !!skip }; - } - - // -- a message for a helper --------------------------------------------------------------------------------- - - /** - * The person's own words for one helper (#4749), through the Harness's `subagents/prompt`: it delivers one browser-authored message to a - * continuable child through its live parent. "steer" reaches a working helper at its next step; "queue" gives a helper that has finished - * (or is between steps) a new turn. The Harness refuses a helper that cannot take messages (a one-shot one) and a parent that is not live; - * either comes back as a plain sentence. - */ - async function messageHelper({ chatId, helperId, text, delivery = 'queue' }) { - const clean = String(text ?? '').trim().slice(0, 8000); - if (!clean) throw new AgentUnavailable('Type a few words for the helper.', 'helper-empty'); - if (!/^[\w.:@-]{1,160}$/.test(String(helperId ?? ''))) throw new AgentUnavailable('That helper is not known.', 'helper-unknown'); - const parent = sessionMap[chatId]?.sessionId; - if (!parent || !rt?.hp.running) throw new AgentUnavailable('The assistant is not running in this chat, so it cannot pass a message on. Send a message in the chat first.', 'helper-idle'); - try { - const receipt = await rt.gw.rpc('subagents/prompt', { request: { requestId: `helper-${randomUUID()}`, parentSessionId: parent, childSessionId: String(helperId), mode: 'continuable', delivery: delivery === 'steer' ? 'steer' : 'queue', content: [{ type: 'text', text: clean }] } }); - return { ok: true, messageId: receipt?.messageId ?? null, delivery: delivery === 'steer' ? 'steer' : 'queue' }; - } catch (e) { - log(`agent · message for a helper refused: ${String(e?.message ?? e).slice(0, 200)}`); - throw new AgentUnavailable(/continuable|one-shot|not.*(found|live|open)|unavailable|closed|ended/i.test(String(e?.message ?? '')) ? 'This helper cannot take a message any more. Ask the assistant in the chat to start a new one.' : 'The message could not be delivered right now. Try again in a moment.', 'helper-refused'); - } - } - - // -- messages typed while a goal runs ---------------------------------------------------------------------- - - /** Queue a message for the running goal. It is delivered between steps, or handed back to the page when the goal ends or pauses. */ - function queueMessage({ chatId, text }) { - const turn = chats.get(chatId)?.turn; - if (!turn || !turn.goalRun || turn.stopping || turn.finished) throw new AgentUnavailable('No goal is running in this chat, so there is nothing to queue behind. Send the message as usual.', 'queue-idle'); - const clean = String(text ?? '').trim().slice(0, 8000); - if (!clean) throw new AgentUnavailable('Type a few words to queue.', 'queue-empty'); - const list = queues.get(chatId) ?? []; - if (list.length >= 20) throw new AgentUnavailable('Twenty messages are already waiting. Wait for some to be delivered.', 'queue-full'); - const item = { id: randomUUID(), text: clean, at: new Date().toISOString(), deliverAt: turn.plan ? 'step' : 'end' }; - list.push(item); queues.set(chatId, list); - const message = { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }; - onQueue(chatId, queueView(chatId)); - turn.announceQueue?.({ type: 'queued-message', state: 'queued', message, queue: queueView(chatId) }); - return { message, queue: queueView(chatId) }; - } - - /** Take a queued message back (the x on it). A message already being delivered cannot be taken back. */ - function cancelQueued({ chatId, id }) { - const list = queues.get(chatId) ?? []; - const at = list.findIndex(m => m.id === id); - if (at < 0) throw new AgentUnavailable('That message was already sent or removed.', 'queue-gone'); - const [item] = list.splice(at, 1); - if (!list.length) queues.delete(chatId); - onQueue(chatId, queueView(chatId)); - chats.get(chatId)?.turn?.announceQueue?.({ type: 'queued-message', state: 'cancelled', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, queue: queueView(chatId) }); - return { queue: queueView(chatId) }; - } - - /** Messages waiting for a chat, and (after a goal ended while the page was away) the ones it should now send. */ - function takeQueue(chatId, { release = false } = {}) { - const turn = chats.get(chatId)?.turn; - const list = queueView(chatId); - if (release && !turn && list.length) { queues.delete(chatId); onQueue(chatId, []); return { queue: [], released: list.map(({ id, text }) => ({ id, text })) }; } - return { queue: list, released: [] }; - } - - /** - * The person changed the chat's mode while a turn (a goal and its helpers included) is running. The new preset - * is put on the session at once, the running turn's own bookkeeping follows, and questions already waiting are - * settled the way the new mode would have settled them: Bypass allows them, Plan rejects them. - */ - async function setMode(chatId, mode) { - const want = modeOf(mode); - const c = chats.get(chatId); - const sessionId = sessionMap[chatId]?.sessionId; - if (!rt || !sessionId) return { applied: false, mode: want, reason: 'no session yet' }; - if (c?.turn && c.turn.mode === want) return { applied: true, mode: want, settled: 0 }; - await applyMode(rt, sessionId, want); - let settled = 0; - if (c?.turn) { - c.turn.mode = want; - c.turn.projector.policy = MODE_PRESETS[want].approval; - if (want !== 'manual') { - const helpers = c.turn.children; - for (const [key, entry] of [...pending.entries()]) { - if (entry.sessionId !== sessionId && !helpers?.has(entry.sessionId)) continue; - pending.delete(key); - try { await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: want === 'bypass' ? 'allowed-once' : 'rejected' }); settled++; } catch { /* already answered */ } - } - } - } - return { applied: true, mode: want, settled }; - } - - /** Answer one pending approval. `decision` is `approve` or `deny`. */ - async function approve({ chatId, callId, decision }) { - const sessionId = sessionMap[chatId]?.sessionId; - // A helper agent's question carries the helper's session id in front of its call id. Only a helper that belongs to - // THIS chat's run can be answered from this chat. - const [maybeChild] = String(callId).split(':'); - const ownHelper = callId.includes(':') && chats.get(chatId)?.turn?.children.has(maybeChild); - const key = ownHelper ? callId : `${sessionId}:${callId}`; - // The durable `approval/asked` (which makes the card say "needs approval") and the waterfall frame - // (which makes it answerable) travel on different streams; a fast click can beat the second one. - let entry = sessionId ? pending.get(key) : null; - for (let i = 0; !entry && sessionId && i < 40; i++) { - await new Promise(r => setTimeout(r, 50)); - entry = pending.get(key); - } - if (!entry) throw new AgentUnavailable('That question is no longer waiting for an answer.', 'approval-gone'); - if (!rt?.hp.running) throw new AgentUnavailable('That question expired because the coding assistant restarted. Ask again.', 'approval-gone'); - pending.delete(key); - try { - await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: decision === 'approve' ? 'allowed-once' : 'rejected' }); - } catch (e) { - throw new AgentUnavailable('Your answer could not be delivered. Ask again.', 'approval-gone', e.message); - } - return { ok: true }; - } - - /** - * Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the - * Harness acknowledges a cancel as admitted, not as done. - */ - /** What the chat holds now and the model's window, as the context plugin measures them (null when it cannot be read). */ - async function contextOf(runtime, sessionId) { - try { - const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-context', submittedAttachments: [] }); - if (r?.result?.kind !== 'success') return null; - const v = JSON.parse(String(r.result.text)); - return Number.isFinite(v.tokens) ? { tokens: Math.round(v.tokens), window: Number(v.window) > 0 ? Math.round(v.window) : 0 } : null; - } catch { return null; } - } - - /** The decision of context-fit.mjs for the message about to be sent, or null when the model server cannot count it. */ - async function fitCheck({ runtime, route, sessionId, fresh, history, message }) { - const inst = localInstances().find(i => i.id === route.instanceId); - if (!inst || !(route.contextWindow > 0)) return null; - const carried = fresh && history.length ? withEarlierConversation(history, message) : message; - if (carried.length < COUNT_ABOVE_CHARS) return null; - const count = text => countTokens({ baseUrl: inst.baseUrl, key: inst.key, model: inst.modelId, text }); - let tokens = await count(carried); - if (tokens == null) return null; - const now = fresh ? null : await contextOf(runtime, sessionId); - const window = now?.window || route.contextWindow; - const pressure = now?.tokens ?? 0; - // Where the Harness starts summarising by itself on this window (profile.mjs: the reply keeps its room, then the headroom). - const reply = localOutputBudget(window); - const threshold = Math.floor(Math.min(window * 0.8, window - reply - compactionHeadroom(window, reply))); - let verdict = decideFit({ window, pressure, messageTokens: tokens, threshold }); - // The earlier conversation carried into a fresh session is what pushed it over: send the message alone instead. - if (verdict.action === 'too-large' && carried !== message) { - const alone = await count(message); - if (alone != null) { tokens = alone; verdict = decideFit({ window, pressure, messageTokens: alone, threshold }); } - } - return { ...verdict, tokens, window, pressure }; - } - - /** - * Summarise the older part of a chat with the Harness's /compact and say what happened. Never throws. - * ok:true carries the figures before and after; ok:false says why (nothing to summarise, busy, failed). - */ - async function compactChat(runtime, sessionId) { - const before = await contextOf(runtime, sessionId); - let result; - try { result = (await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }))?.result; } - catch (e) { return { ok: false, reason: /not.found|no such/i.test(String(e.message)) ? 'nothing' : 'failed', before, text: String(e.message ?? e) }; } - const text = String(result?.text ?? ''); - log('agent · compact: ' + (result?.kind ?? 'none') + ' ' + text.slice(0, 140)); - if (result?.kind === 'success' && /^Compacted/i.test(text)) return { ok: true, before, after: await contextOf(runtime, sessionId) }; - if (result?.kind === 'success') return { ok: false, reason: 'nothing', before, text }; - if (/active compaction|not idle/i.test(text)) return { ok: false, reason: 'busy', before, text }; - // The Harness cannot make a summary smaller than what is left when the chat holds little beyond its first prompt: that is nothing to summarise, not a failure. - const little = before && before.window > 0 && before.tokens - BASE_TOKENS < before.window * 0.25; - return { ok: false, reason: little && /useful summary|not smaller/i.test(text) ? 'nothing' : 'failed', before, text }; - } - - /** The line in the chat that explains why the context meter fell: how full it was and how full it is. */ - function summarizedNote(before, after, window) { - const w = after?.window || before?.window || window || 0; - const pct = v => Math.max(0, Math.min(100, Math.round(100 * v.tokens / w))); - const known = w > 0 && before && after; - const template = known ? FIT_TEXT.summarized : FIT_TEXT.summarizedShort; - const values = known ? [pct(before), pct(after)] : []; - return { type: 'delta', own: true, text: '\n\n' + fill(template, values), key: template, values, noteReason: 'compacted' }; - } - - /** "/compact": summarise the older messages of this chat now, and say in plain words what happened. */ - async function compactCommand(options) { - const { chatId, choice, signal } = options; - const c = chat(chatId); - const say = (template, values = []) => sayKey(options, template, values); - if (c.turn || c.starting) return say(FIT_TEXT.compactBusy); - const known = sessionMap[chatId]?.sessionId; - if (!known) return say(FIT_TEXT.noChatYet); - let runtime; - try { ({ rt: runtime } = await ensureRuntime(choice, signal)); } catch { return say(FIT_TEXT.compactFailed); } - const done = await compactChat(runtime, known); - if (done.ok) { - const note = summarizedNote(done.before, done.after, 0); - return say(note.key, note.values); - } - if (done.reason === 'busy') return say(FIT_TEXT.compactBusy); - if (done.reason === 'nothing') { - const w = done.before?.window || 0; - const pct = w > 0 && done.before ? Math.round(100 * done.before.tokens / w) : 0; - return say(pct >= 60 ? FIT_TEXT.nothingFull : FIT_TEXT.nothingToSummarize, pct >= 60 ? [pct] : []); - } - return say(FIT_TEXT.compactFailed); - } - - /** Summarise the older part of a session with the Harness's own /compact. Best effort: the next message compacts again by itself when it must. */ - async function compactSession(runtime, sessionId) { - try { - const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }); - log(`agent · compact after a stopped turn: ${r?.result?.kind ?? 'done'} ${String(r?.result?.text ?? '').slice(0, 120)}`); - } catch (e) { log(`agent · compact after a stopped turn failed: ${e.message}`); } - } - - async function stop(chatId, { waitMs = 20_000 } = {}) { - const c = chats.get(chatId); - const turn = c?.turn; - if (!turn && c?.starting) { c.cancelStart = true; return { stopped: true, ended: 'cancelled-before-start', ms: 0 }; } - if (!turn || !rt) return { stopped: false, reason: 'no active turn' }; - const t0 = Date.now(); - if (!turn.prompted) { - // The Harness has not been given the prompt yet, so there is nothing to cancel there. - turn.stopBeforePrompt = true; - const early = await Promise.race([turn.ended.promise, new Promise(r => setTimeout(() => r(null), 100))]); - if (early) return { stopped: true, ended: early.reason?.kind ?? 'aborted', ms: Date.now() - t0 }; - } - turn.stopping = true; - await pauseGoal(rt, turn.sessionId, chatId); - // Helpers first: a helper still working would otherwise report back and wake the parent again. - await Promise.allSettled([...turn.children.values()].filter(h => !h.done).map(h => rt.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: turn.sessionId, mode: 'continuable' }))); - await rt.gw.rpc('session/cancel', { request: { sessionId: turn.sessionId } }).catch(e => { if (turn.parentOpen) throw e; }); - // Nothing is running in the parent (it was waiting for its helpers): the run ends once they are all down. - if (!turn.parentOpen) { clearTimeout(turn.settleTimer); turn.settleTimer = after(300, () => { if (!turn.finished && !turn.parentOpen && [...turn.children.values()].every(h => h.done)) turn.finish(null); }); } - let timer; const result = await Promise.race([turn.ended.promise, new Promise(r => { timer = after(waitMs, () => r(null)); })]); - clearTimeout(timer); - if (!result) return { stopped: false, pending: true, reason: 'the turn is still stopping' }; - return { stopped: true, ended: result.reason?.kind ?? 'unknown', ms: Date.now() - t0 }; - } - - function pendingFor(chatId) { - const sessionId = sessionMap[chatId]?.sessionId; - const helpers = chats.get(chatId)?.turn?.children; - return [...pending.values()].filter(p => p.sessionId === sessionId || helpers?.has(p.sessionId)) - .map(p => (p.sessionId === sessionId ? p : { ...p, callId: `${p.sessionId}:${p.callId}` })).map(({ callId, tool, reason, at }) => ({ callId, tool, reason, at })); - } - - /** Every chat that has an approval waiting, for the task board: the chat, its working folder and what is waiting (same items as pendingFor). */ - function pendingAll() { - if (!pending.size) return []; - return Object.keys(sessionMap).map(chatId => ({ chatId, folder: sessionMap[chatId]?.cwd ?? null, pending: pendingFor(chatId) })).filter(c => c.pending.length); - } - - async function close() { - const r = rt; rt = null; - if (r) { r.events?.close(); r.gw.close(); await r.hp.stop(); } - } - - /** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */ - function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); } - - return { compactCommand, messageHelper, answerQuestion, goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, llmTarget, setPlanBriefing, resetSession, reopenPlan, skipStep, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, pendingAll, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, workingFolder: chatId => sessionMap[chatId]?.cwd ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) }; -} - -/** A goal that stopped by itself, in words. */ -export function plainBlocker(reason) { - if (!reason) return 'it could not go on.'; - if (reason.code === 'round-limit') return 'it worked for the most steps it was allowed. Type /goal clear, then start a new goal to go on.'; - return String(reason.message ?? 'it could not go on.'); -} - -/** What a goal run says when it ends. */ -export function goalEnding(view) { - if (view.phase === 'complete') return '\n\n*The goal is complete.*'; - if (view.phase === 'blocked') return `\n\n*The goal stopped: ${plainBlocker(view.blockedReason)}*`; - if (view.phase === 'paused') return '\n\n*The goal is paused. Type /goal resume to go on.*'; - return ''; -} - -/** A goal request the Harness refused, as a sentence. */ -export function plainGoalError(e) { - const message = String(e?.message ?? e); - if (/already|unfinished|current goal/i.test(message)) return 'This chat already has a goal that is not finished. Type /goal edit to change it, /goal clear to remove it, or /goal to see it.'; - if (/GOAL_NONE|no goal/i.test(message) || e?.code === 'goal-none') return 'There is no goal to continue. Start one with /goal followed by what you want done.'; - if (/objective/i.test(message)) return 'A goal needs a few words about what you want done, for example: /goal make every test pass.'; - return 'The goal could not be changed right now. Try again in a moment.'; -} - -/** The Harness session of a chat that existed before the agent did knows nothing; carry a bounded summary. */ -export function withEarlierConversation(history, message) { - const rows = history.filter(m => (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim()).slice(-12); - if (!rows.length) return message; - const text = rows.map(m => `${m.role}: ${m.content.length > 1500 ? `${m.content.slice(0, 1499)}…` : m.content}`).join('\n'); - return `Earlier in this conversation, before you were given tools:\n${text}\n\nCurrent message:\n${message}`; -} +/** + * The agent bridge: Strata chats as Harness sessions. + * + * What it owns + * - the pinned Harness process (one, lazily started, restarted only when a route it needs changed); + * - the stable Strata-chat -> Harness-session map, persisted next to the host's other state; + * - one `session/follow` stream per live turn, projected into the NDJSON frames the chat UI renders; + * - approvals: the Harness `approval/request` waterfall in, the user's Approve/Deny back out; + * - Stop: `session/cancel` for exactly one session, resolved only once the turn has really ended. + * + * What it deliberately does not do + * - it never falls back to another model: a chat picks a route (local instance or saved API + * connection) and a missing route is a typed error; + * - it never implements Stop by killing the Harness (that would cancel every other chat); + * - it never holds a secret outside the environment of the agent process it starts. + */ +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { homedir, tmpdir } from 'node:os'; +import { fileURLToPath } from 'node:url'; +import { randomUUID } from 'node:crypto'; +import { GatewayClient } from './gateway-client.mjs'; +import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs'; +import { StatusReporter } from './status.mjs'; +import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf, localOutputBudget, compactionHeadroom } from './profile.mjs'; +import { TurnProjector, parseArguments as parseArgs } from './events.mjs'; +import { ChildProjector } from './children.mjs'; +import { nearestBudget } from './llm-shape.mjs'; +import { DeliverableTracker, ActivityGroups } from './deliverables.mjs'; +import { SkillsUsed, skillInfoFrom } from './skills-used.mjs'; +import { turnEngineSpeed } from './engine-speed.mjs'; +import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs'; +import { cutNotice, cutNudge } from './reply-cut.mjs'; + +/** How often one turn asks the agent to carry on after a reply the length limit cut (each time in smaller pieces). */ +export const MAX_CUT_RETRIES = 2; +import { buildAnswer, parseQuestions } from './user-questions.mjs'; +import { BASE_TOKENS, COUNT_ABOVE_CHARS, FIT_TEXT, countTokens, decideFit, fill, grouped } from './context-fit.mjs'; +import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; + +/** + * A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical + * text for the Details disclosure (experts), already free of secrets. + */ +export class AgentUnavailable extends Error { + constructor(message, code = 'agent-unavailable', details = null) { super(message); this.name = 'AgentUnavailable'; this.code = code; this.details = details; } +} + +/** The plain sentence for a raw agent failure text, whatever produced it. */ +export function plainAgentFailure(raw) { + const text = String(raw ?? ''); + if (/did not print its address|exited during start|could not start|ECONNREFUSED.*127\.0\.0\.1|refused the launch token|socket/i.test(text)) return 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.'; + if (/process stopped|lost the session stream|stream did not open|session stream/i.test(text)) return 'The coding assistant stopped unexpectedly, so this answer is incomplete. Send your message again.'; + if (/did not accept the message/i.test(text)) return 'The coding assistant did not take this message. Send it again in a moment.'; + return text; +} + +/** + * A failure thrown while a turn starts, as `{ message, details, code }` for the chat's error card. The agent's own errors read like + * `session/create: tool-bash (...): waiting for shell ...` (a plugin chain that never started): never shown raw. The plain sentence + * goes in `message`; the technical text goes in `details`, which the app shows only behind Details. + */ +export function plainTurnFailure(err) { + const raw = String(err?.message ?? err ?? ''); + const details = typeof err?.details === 'string' && err.details ? err.details : raw; + if (err instanceof AgentUnavailable) return { message: err.message, details, code: err.code ?? 'AGENT_ERROR' }; + if (err?.code === 'agent-preset/invalid' || /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)|failed to import|did not activate/i.test(raw)) { + return { message: 'The coding assistant is missing a part it needs, so it cannot work on files yet. Close and reopen Strata. If it keeps happening, reinstall Strata. Chatting without tools still works.', details, code: 'AGENT_INCOMPLETE' }; + } + if (/^[a-z][a-z-]*\/[a-z][a-z-]*: /i.test(raw) || /^(gateway|rpc)/i.test(raw)) { + return { message: 'The coding assistant could not start this message. Try again. If it keeps happening, close and reopen Strata.', details, code: err?.code ?? 'AGENT_ERROR' }; + } + return { message: plainAgentFailure(raw), details, code: err?.code ?? 'AGENT_ERROR' }; +} + +/** The Harness's plugins start one after another: until they are all up, session/create answers "<plugin>: waiting for <service>". */ +const STARTING_UP = /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)/i; + +/** + * Create a Harness session, waiting for its plugins to finish starting. Right after the app opens (or the Harness restarts) the first + * message can arrive before they are up: that is retried every `retryMs` for up to `readyMs` (`onWait` tells the page "Starting the assistant…") + * instead of failing the first chat. Any other error is thrown at once; a start that never finishes is a plain AGENT_NOT_READY error + * with the Harness's text kept for Details. Returns null when `cancelled()` turns true while waiting. + */ +export async function createSessionWhenReady(create, { readyMs = 60_000, retryMs = 1_500, onWait = () => {}, cancelled = () => false, now = Date.now } = {}) { + const until = now() + readyMs; + for (;;) { + try { return await create(); } catch (e) { + const text = String(e?.message ?? e ?? ''); + if (!STARTING_UP.test(text)) throw e; + if (now() >= until) throw new AgentUnavailable('The assistant could not start. Try again in a moment.', 'AGENT_NOT_READY', text); + onWait(); + await new Promise(r => setTimeout(r, retryMs)); + if (cancelled()) return null; + } + } +} + +/** Attached pictures (data addresses) as the Harness's image prompt parts. */ +export function imageParts(images) { + return (Array.isArray(images) ? images : []).map(i => { + const m = /^data:(image\/(?:png|jpeg|webp));base64,(.+)$/.exec(String(i?.url ?? '')); + return m ? { type: 'image', mediaType: m[1], data: m[2], name: String(i.name ?? 'Picture').slice(0, 120) } : null; + }).filter(Boolean); +} + +/** A timer that never keeps the process alive by itself. */ +const after = (ms, fn) => { const t = setTimeout(fn, ms); t.unref?.(); return t; }; +/** The app's own host folder: never a place an answer's files can be (this file lives in <host>/server/agent). */ +const HOST_DIR = fileURLToPath(new URL('../..', import.meta.url)); + +const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; }; + +/** + * @param {object} options + * @param {string} options.dataDir the host's data directory (agent state lives in `<dataDir>/agent`) + * @param {string|null} [options.componentsDir] where installed components live + * @param {() => Array} options.localInstances ready local instances (see profile.mjs) + * @param {() => Array} options.connections saved API connections WITH their keys (host-internal) + * @param {() => (string|null)} [options.defaultLocalId] the local instance the chat runs on: its tool servers are the agent's (T5) + * @param {NodeJS.ProcessEnv} [options.env] + * @param {string} [options.nodePath] the Node runtime that runs the Harness + * @param {(line:string)=>void} [options.log] + */ +export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, defaultLocalId = () => null, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, engineProgress = () => null, engineGraceMs = 30 * 60_000, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000, sessionReadyMs = 60_000, sessionRetryMs = 1_500 }) { + const root = join(dataDir, 'agent'); + const home = join(root, 'home'); + const sessionsFile = join(root, 'sessions.json'); + mkdirSync(root, { recursive: true }); + + /** + * Where the turn's file tracker must never look (deliverables.mjs): the app, the engine and its components, Strata's own data, AppData + * and temp. `forbid` ones also switch tracking off when the chat's folder is one of them or inside one. + */ + function trackerFolders() { + const user = env.USERPROFILE ?? env.HOME ?? homedir(); + const forbid = [HOST_DIR, componentsDir, bundledDir].filter(Boolean); + const exclude = [dataDir, tmpdir(), env.LOCALAPPDATA, env.APPDATA, env.ProgramData, env.ProgramFiles, env['ProgramFiles(x86)'], env.TEMP, env.TMP, + join(user, 'AppData'), join(user, '.cache'), join(user, '.config'), join(user, '.local'), join(user, 'Library')].filter(Boolean); + return { forbid, exclude }; + } + + /** chatId -> { sessionId, cwd, createdAt } */ + let sessionMap = {}; + if (existsSync(sessionsFile)) { + try { sessionMap = JSON.parse(readFileSync(sessionsFile, 'utf8')) ?? {}; } catch { sessionMap = {}; } + } + const persist = () => { + const temp = `${sessionsFile}.${randomUUID()}.tmp`; + writeFileSync(temp, JSON.stringify(sessionMap, null, 2)); + renameSync(temp, sessionsFile); + }; + + /** @type {{hp:HarnessProcess, gw:GatewayClient, profile:object, clientId:string|null, generation:number, events:object}|null} */ + let rt = null; + let generation = 0; + let lastError = null; + let starting = null; + const chats = new Map(); // chatId -> { turn, route, routeGeneration } + const plans = new PlanStore(join(root, 'plans.json')); + /** chatId -> messages the person typed while a goal ran: [{ id, text, at, deliverAt }]; delivered between steps or when the goal ends */ + const queues = new Map(); + const queueView = chatId => (queues.get(chatId) ?? []).map(({ id, text, at, deliverAt }) => ({ id, text, at, deliverAt })); + const pending = new Map(); // `${sessionId}:${callId}` -> { eventId, sessionId, callId, at } + const questions = new Map(); // `${sessionId}:${callId}` -> the agent's own question waiting for the person: { eventId, sessionId, callId, items, at, clientId } (#4244) + const chatOfSession = sessionId => Object.keys(sessionMap).find(id => sessionMap[id]?.sessionId === sessionId) ?? null; + const idleWaiters = new Set(); + + const chat = id => { let c = chats.get(id); if (!c) { c = { id, turn: null, route: null, routeGeneration: -1 }; chats.set(id, c); } return c; }; + const activeTurns = () => [...chats.values()].filter(c => c.turn).length; + const notifyIdle = () => { if (activeTurns() === 0) { for (const w of idleWaiters) w(); idleWaiters.clear(); } }; + const waitIdle = (signal, ms) => new Promise((resolve, reject) => { + if (activeTurns() === 0) return resolve(); + const timer = setTimeout(() => { idleWaiters.delete(done); reject(new AgentUnavailable('Another chat is still working and the list of models changed. Try again when it finishes.', 'agent-busy')); }, ms); + const done = () => { clearTimeout(timer); resolve(); }; + idleWaiters.add(done); + signal?.addEventListener('abort', () => { clearTimeout(timer); idleWaiters.delete(done); reject(signal.reason ?? new Error('aborted')); }, { once: true }); + }); + + /** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */ + let shapeTargets = {}; + function buildProfileNow() { + const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock, defaultLocalId: defaultLocalId() }); + shapeTargets = profile.shapeTargets ?? {}; + return profile; + } + const llmTarget = key => shapeTargets[key] ?? null; + + function harnessInfo() { return resolveHarness({ env, componentsDir, bundledDir }); } + /** Where the agent component is (the browser tool server lives inside it), or null. */ + const harnessDir = () => { const h = harnessInfo(); return h.ok ? h.dir : null; }; + + /** The capability state the app shows. Never carries a token or a key. */ + function status() { + const h = harnessInfo(); + if (!h.ok) return { state: 'unavailable', reason: 'The coding assistant isn’t installed on this computer yet. Chat works without it.', detail: h.reason, code: 'component-missing' }; + const profile = buildProfileNow(); + return { + state: rt?.hp.running ? 'ready' : starting ? 'starting' : lastError ? 'error' : 'idle', + reason: lastError ? plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again.' : plainAgentFailure(lastError) : null, + detail: lastError ?? null, + harness: { version: h.version }, + runtime: rt?.hp.running ? { pid: rt.hp.pid, generation: rt.generation } : null, + routes: profile.routes.map(({ route, kind, modelId, name, contextWindow }) => ({ route, kind, modelId, name, contextWindow })), + // tool servers that could not be wired (a name the rule does not allow, no program or address): the chat says so + skippedServers: profile.mcpSkipped ?? [], + activeTurns: activeTurns(), + pendingApprovals: pending.size, + }; + } + + async function startRuntime(profile) { + const h = harnessInfo(); + if (!h.ok) throw new AgentUnavailable('The coding assistant isn’t installed on this computer yet. Chat works without it.', 'component-missing', h.reason); + mkdirSync(home, { recursive: true }); + const stale = stopStaleAgent(join(root, 'harness.pid')); + if (stale) log(`agent · stopped a leftover Harness process (pid ${stale}) from an earlier run`); + const patchFile = join(root, `profile-${profile.signature}.patch.yml`); + writeFileSync(patchFile, profile.patch); + const workdir = join(root, 'run'); + const hp = new HarnessProcess({ + harness: h, home, patchFile, cwd: workdir, env: profile.env, nodePath, logFile: join(root, 'harness.log'), pidFile: join(root, 'harness.pid'), + onExit: exit => { + log(`agent · the Harness process exited (code ${exit.code})`); + if (rt?.hp === hp) { lastError = 'The agent process stopped.'; rt = null; } + for (const c of chats.values()) c.turn?.abortFromRuntime('The agent process stopped before this turn finished.'); + }, + }); + const info = await hp.start({ timeoutMs: startTimeoutMs }); + const gw = new GatewayClient({ baseUrl: info.baseUrl, token: info.token }); + await gw.connect(); + const next = { hp, gw, profile, clientId: null, generation: ++generation, events: null }; + next.events = gw.openStream('$events', {}, { + onItem: value => onHostEvent(next, value), + onError: e => log(`agent · event stream: ${redact(e.message, Object.values(profile.env))}`), + }); + rt = next; + lastError = null; + log(`agent · Harness ${h.version ?? ''} ready (pid ${hp.pid}, ${profile.routes.length} route(s))`); + return next; + } + + /** The local engine's own speed for this turn's requests (null when it cannot be read: the stream's estimate stays). */ + async function engineSpeedOf(route, projector) { + const inst = localInstances().find(i => i.id === route.instanceId); + if (!inst) return null; + return turnEngineSpeed({ baseUrl: inst.baseUrl, key: inst.key, since: projector.startedAt, attempts: projector.streams.size, timeoutMs: 800 }); + } + + /** Make sure a runtime exists that knows the route this turn needs. */ + async function ensureRuntime(choice, signal) { + for (;;) { + if (starting) { await starting.catch(() => {}); continue; } + const profile = buildProfileNow(); + const route = routeFor(profile, choice); + if (!route) { + throw new AgentUnavailable(choice?.connectionId + ? 'This API model is no longer available. Choose another model in the chat picker.' + : 'No local model is ready for the agent. Load a model in Models, or choose an API model.', 'model-unavailable'); + } + const known = rt?.hp.running && rt.profile.toolsSignature === profile.toolsSignature && rt.profile.routes.some(r => r.route === route.route && r.modelId === route.modelId && r.fp === route.fp); + if (known) return { rt, route }; + starting = (async () => { + if (rt?.hp.running) { + await waitIdle(signal, 120_000); + const old = rt; rt = null; + old.events?.close(); old.gw.close(); await old.hp.stop(); + } + try { return await startRuntime(profile); } catch (e) { + lastError = redact(String(e.message ?? e), Object.values(profile.env)); + throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.' : plainAgentFailure(lastError), 'agent-start-failed', lastError); + } + })(); + try { await starting; } finally { starting = null; } + } + } + + function onHostEvent(runtime, value) { + if (value.type === 'ready') { runtime.clientId = value.clientId; return; } + if (value.type === 'waterfall' && value.event === 'approval/request') { + const r = value.request ?? {}; + if (!r.callId) return; + pending.set(`${value.agentId}:${r.callId}`, { eventId: value.eventId, sessionId: value.agentId, callId: r.callId, tool: r.toolName, reason: r.reason ?? null, at: Date.now(), clientId: runtime.clientId }); + } else if (value.type === 'waterfall' && value.event === 'user-questions/request') { + // The agent of a chat that is running in front of the person asks the person: the question goes to the page (the question card above the message box) and the + // Harness waits for the answer. Anything else (a helper's question, a chat that is stopping, a request with nothing to show) is declared + // unanswerable, which makes the tool return an error the model reads and carries on from, instead of a turn that waits forever. + const r = value.request ?? {}; + const chatId = chatOfSession(value.agentId); + const turn = chatId ? chats.get(chatId)?.turn : null; + const items = parseQuestions(r.questions); + // A goal or a plan step runs without anyone there: a question would stall it, so it is declined at once (the model reads "could not be answered" and goes on). + if (!turn || turn.finished || turn.stopping || turn.goalRun || turn.plan || !turn.announceQuestion || !items.length) { + void runtime.gw.answerEvent({ clientId: runtime.clientId, eventId: value.eventId, outcome: 'next' }).catch(() => {}); + } else { + const callId = String(r.wait?.callId ?? value.eventId); + questions.set(`${value.agentId}:${callId}`, { eventId: value.eventId, sessionId: value.agentId, callId, items, at: Date.now(), clientId: runtime.clientId }); + turn.announceQuestion({ type: 'agent-question', callId, questions: items }); + } + } else if (value.type === 'cancel') { + for (const [k, v] of questions) if (v.eventId === value.eventId) { questions.delete(k); chats.get(chatOfSession(v.sessionId))?.turn?.announceQuestion?.({ type: 'agent-question-end', callId: v.callId }); } + for (const [k, v] of pending) if (v.eventId === value.eventId) pending.delete(k); + } + } + + async function sessionFor(c, cwd, runtime, { onWait = () => {} } = {}) { + let known = sessionMap[c.id]; + // The chat's folder changed: the agent's working folder and sandbox are fixed when its session starts, so the chat gets a new session + // in the new folder (the earlier conversation is carried into its first message, as for any fresh session). + if (known && cwd && known.cwd && resolve(known.cwd) !== resolve(cwd)) { delete sessionMap[c.id]; persist(); known = null; } + if (known) return { sessionId: known.sessionId, fresh: false }; + const created = await createSessionWhenReady(() => runtime.gw.rpc('session/create', { request: { cwd } }), { readyMs: sessionReadyMs, retryMs: sessionRetryMs, onWait, cancelled: () => c.cancelStart }); + if (!created) return null; + sessionMap[c.id] = { sessionId: created.sessionId, cwd, createdAt: new Date().toISOString() }; + persist(); + return { sessionId: created.sessionId, fresh: true }; + } + + /** + * Put the session into the preset of the chat's mode, through the Harness's own `/permission` command, and + * check that it took. A turn never starts in a mode other than the one asked for: if the switch cannot be + * confirmed the turn fails closed with a typed error instead of running with unknown permissions. + */ + async function applyMode(runtime, sessionId, mode) { + const want = MODE_PRESETS[mode].key; + const read = async () => { + const r = await runtime.gw.rpc('session/projections', { request: { sessionId, keys: ['permissions'] } }); + return r?.values?.permissions?.currentValue ?? null; + }; + try { + if (await read() !== want) { + const done = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: `/permission ${want}`, submittedAttachments: [] }); + if (done?.result?.kind !== 'success') throw new Error(done?.result?.text ?? 'the agent did not recognise the command'); + const now = await read(); + if (now !== want) throw new Error(`the session reports "${now}" instead of "${want}"`); + } + } catch (e) { + throw new AgentUnavailable(`Strata could not set this chat to ${MODE_PRESETS[mode].name} mode, so nothing ran. Try again.`, 'mode-unavailable', e.message); + } + // Manual leaves the sandbox open and relies on the Strata gate to ask first. Without the gate it must not start. + if (mode === 'manual' && !runtime.gateChecked) { + try { + const probe = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-gate', submittedAttachments: [] }); + if (probe?.result?.kind !== 'success' || !String(probe.result.text ?? '').includes('strata-gate active')) throw new Error('the approval gate is not loaded'); + runtime.gateChecked = true; + } catch (e) { + throw new AgentUnavailable('Strata could not make sure the coding assistant asks before changing anything, so nothing ran. Close and reopen Strata, then try again.', 'mode-unavailable', e.message); + } + } + } + + /** + * Run one agent turn for a Strata chat and stream it as frames. + * `signal` means the client went away: the turn keeps running (that is not Stop). + */ + async function runTurn(options) { + const c = chat(options.chatId); + if (c.turn || c.starting) throw new AgentUnavailable('This chat is still working. Stop it or wait for it to finish.', 'turn-active'); + // From here until the Harness has the prompt, Stop has no session to cancel; it cancels the start. + c.starting = true; c.cancelStart = false; + try { return await runTurnInner(c, options); } finally { c.starting = false; } + } + + async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, thinkingBudget = 0, images = [], planTask = null, planRun = null, researchTopic = null }) { + let send = onFrame; let attached = true; + // A research run gathers first; what the assistant writes while gathering is notes, not the answer, so it is not shown. + let hideDeltas = !!researchTopic; + signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true }); + // What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary. + const written = { all: '', step: '' }; + // The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known. + let guard = null; + const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } }; + // What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends. + const tracker = new DeliverableTracker(workspacePath, trackerFolders()); + let toolsRan = false; // a turn that ran no tool wrote nothing, so there is nothing to look for at its end + try { tracker.snapshot(); } catch { /* a folder that cannot be read has no deliverables */ } + const groups = new ActivityGroups({ emit: raw }); + const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) }); + const emit = frame => { + if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (guard) trip(guard.text(frame.text)); if (hideDeltas) return; } + if (frame.own) { const { own, ...rest } = frame; frame = rest; } + if (frame.type === 'delta' && frame.text) groups.text(); + if (frame.type === 'agent-tool' && frame.tool) { + if (['done', 'error'].includes(frame.tool.state) && !['read', 'read_image', 'glob', 'grep', 'web_fetch', 'web_search'].includes(frame.tool.name)) toolsRan = true; + let made = null; + if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } } + raw(frame); + if (made) raw(made); + if (guard) trip(guard.card(frame.tool)); + groups.card(frame.tool, made); + skills.card(frame.tool); + return; + } + raw(frame); + }; + // What the assistant is doing right now, one small frame (status.mjs). Cleared before the final frame of the turn. + const reporter = new StatusReporter({ emit }); + + emit({ type: 'queued', requestId }); + reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' }); + const { rt: runtime, route } = await ensureRuntime(choice, signal); + const made = await sessionFor(c, workspacePath, runtime, { onWait: () => reporter.set({ phase: 'starting', code: 'assistant-starting', text: 'Starting the assistant…' }) }); + const { sessionId, fresh } = made ?? {}; + const cancelled = () => { reporter.clear(); emit({ type: 'done', finishReason: 'aborted', cancelled: true, tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0, model: route.name, contextMax: route.contextWindow }); return { cancelled: true }; }; + if (c.cancelStart || !made) return cancelled(); + + // The model and the chat's thinking level (the Reasoning menu) are sent to the Harness when either changed. A level the route does + // not have (an API model with its own vocabulary) is dropped and the model's own default stands: never an error for the person. + const level = effortOf(thinking ?? 'Medium'); // the menu's default is Medium + // Response settings the Harness cannot send itself (the thinking budget, the Expert sampling) go through this host's forwarding + // endpoint, on a copy of the route; with every setting at its default the route is used directly, as before. + const budget = level === 'off' ? 0 : nearestBudget(thinkingBudget); + const sampling = proxyBase && route.shaped ? expertSampling() : null; + const provider = route.shaped && (budget || sampling) ? route.shaped[budget] : route.route; + const wanted = `${provider}/${route.modelId}/${level ?? ''}`; + if (c.route !== wanted || c.routeGeneration !== runtime.generation) { + const select = effort => runtime.gw.rpc('session/selectModel', { request: { sessionId, provider, model: route.modelId, ...(effort ? { reasoningEffort: effort } : {}) } }); + try { + try { await select(level); } catch (e) { if (!level || e.code === 'session/not-found') throw e; await select(null); } + } catch (e) { + if (e.code === 'session/not-found') { delete sessionMap[c.id]; persist(); } + throw new AgentUnavailable(`The coding assistant could not use ${route.name}. Pick the model again and retry.`, 'model-unavailable', e.message); + } + c.route = wanted; c.routeGeneration = runtime.generation; + } + + // The chat's permission mode is read once, here, for this whole turn. A change the user makes while the + // turn runs applies to the next one, so a running turn never sees its permissions move under it. + const appliedMode = planTask ? 'plan' : modeOf(mode); + await applyMode(runtime, sessionId, appliedMode); + + // Does the message fit the model's window? Asked before anything is sent, with the model server's own count (context-fit.mjs). A message + // that fits once the older messages are a summary is sent after a summary; one that can never fit is not sent, and the person is told + // plainly and offered the two ways out. Whatever cannot be counted goes through: the Harness recovers from a refusal by itself. + if (!goal && route.kind === 'local') { + const fit = await fitCheck({ runtime, route, sessionId, fresh, history, message }).catch(() => null); + if (fit?.action === 'too-large') { + reporter.clear(); + const values = [grouped(fit.tokens), grouped(fit.window)]; + const text = fill(FIT_TEXT.tooLarge, values); + emit({ type: 'error', message: text, key: FIT_TEXT.tooLarge, values, code: 'CONTEXT_MESSAGE_TOO_LARGE', tokens: fit.tokens, window: fit.window }); + return { error: text }; + } + if (fit?.action === 'summarize') { + reporter.set({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] }); + const done = await compactChat(runtime, sessionId); + reporter.clear(); + if (done.ok) emit(summarizedNote(done.before, done.after, fit.window)); + } + } + + const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval, window: route.contextWindow }); + if (!goal) guard = new TurnGuard({ plan: !!planTask, contextMax: route.kind === 'local' ? route.contextWindow : 0 }); // a saved connection's window is often only assumed: never judged by a guess + projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); }; + const turn = { + sessionId, projector, route, requestId, live: false, lastSeq: -1, + ended: deferred(), follow: null, snapshot: deferred(), finished: false, prompted: false, stopBeforePrompt: false, + abortFromRuntime: reason => finishTurn(reason), finish: failure => finishTurn(failure), + // Helper agents (subagents) the Harness started for this chat, and the state of the run around them. + children: new Map(), subagentCalls: new Map(), parentOpen: false, stopping: false, settleTimer: null, mode: appliedMode, + plan: null, advancing: false, goalRun: false, lastActivity: Date.now(), heard: Date.now(), engineMark: null, watchdog: null, + research: researchTopic ? { phase: 'gather', nudged: false, waitingStart: false } : null, + }; + c.turn = turn; + /** + * A turn must always end. If the Harness sends nothing at all for a while (a tool that never returns, a model server that went + * quiet, a lost event) the turn is stopped and ended with a plain message instead of showing "thinking" forever. A running tool gets + * a longer allowance than a quiet model (a build can be silent for minutes). Whatever the assistant finished is kept. + */ + turn.watchdog = setInterval(() => { + if (turn.finished || turn.stopping) return; + const toolRunning = [...projector.tools.values()].some(x => x.card?.state === 'running' || x.card?.state === 'proposed') || pending.size > 0 && pendingFor(chatId).length > 0; + const limit = toolRunning ? stallToolMs : stallMs; + // A local engine reading a long prompt sends the Harness nothing for minutes (#3623). Its /metrics progress counts as activity, + // for at most engineGraceMs after the Harness last spoke: progress for another chat cannot keep a lost turn alive forever. + if (turn.route?.kind === 'local' && Date.now() - turn.heard < engineGraceMs) { + let mark = null; + try { mark = engineProgress(turn.route.instanceId); } catch { /* no progress known: the Harness alone decides */ } + if (mark != null && mark !== turn.engineMark) { turn.engineMark = mark; turn.lastActivity = Date.now(); return; } + } + if (Date.now() - turn.lastActivity < limit) return; + turn.stalledFor = Math.round((Date.now() - turn.lastActivity) / 1000); + turn.stopping = true; + void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); + for (const h of turn.children.values()) if (!h.done) void runtime.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: sessionId, mode: 'continuable' }).catch(() => {}); + const mins = Math.max(1, Math.round(turn.stalledFor / 60)); + turn.finish(`The assistant stopped answering for ${mins > 1 ? mins + ' minutes' : 'a minute'}, so I ended this turn. Anything it already finished is kept. Send your message again to go on.`); + }, Math.min(15_000, Math.max(200, Math.floor(stallMs / 4)))); + turn.watchdog.unref?.(); + async function finishTurn(failure) { + if (turn.finished) return; + turn.finished = true; + for (const [k, v] of questions) if (v.sessionId === turn.sessionId) questions.delete(k); + clearTimeout(turn.settleTimer); + clearInterval(turn.watchdog); + turn.follow?.close(); + for (const child of turn.children.values()) child.follow?.close(); + if (turn.stopping && !failure) projector.ended = turn.guard ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'user' } }; + reporter.clear(); + const extra = []; + try { if (toolsRan) for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ } + groups.end(); + if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); } + try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ } + // The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself). + let noteReason = turn.guard ?? null; + // A reply the length limit cut ends with a sentence that says so (and what was lost), never with silence (AGENT-LOST). + const cutEnd = !failure && !turn.stopping && projector.ended?.kind === 'max-tokens'; + if (cutEnd && !noteReason) { + const note = cutNotice({ ...projector.cut(), retrying: false }); + extra.push({ type: 'delta', own: true, text: ` + +${note.text}`, key: note.key, values: note.values, noteReason: 'cut' }); + } + if (!noteReason && !cutEnd && guard && !failure && !turn.stopping && !turn.goalRun) { + noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens }); + } + if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); } + for (const f of extra) emit(f); + // The answer speed of a turn on this computer is the engine's own (tokens it produced over its decode time, as the Monitor shows it). + const engine = !failure && route.kind === 'local' ? await engineSpeedOf(route, projector) : null; + const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow, engine }); + for (const f of frames.slice(0, -1)) emit(f); + // Messages typed while the goal ran and not delivered between steps go back to the page now, to be sent as ordinary messages. + if (turn.goalRun && attached) { + const left = queueView(chatId); + if (left.length) { queues.delete(chatId); onQueue(chatId, []); emit({ type: 'queued-release', messages: left.map(({ id, text }) => ({ id, text })) }); } + } + for (const f of frames.slice(-1)) emit(f); + c.turn = null; + turn.ended.resolve({ reason: projector.ended, failure: failure ?? null }); + notifyIdle(); + // A turn that filled the context, or that the guard stopped, leaves a long history behind: summarise the older part now so the next message has room. + if (noteReason === 'context' || noteReason === 'searches' || noteReason === 'searches-failed' || noteReason === 'rewrites' || /context window|too long|exceeds/i.test(String(projector.ended?.error?.message ?? ''))) void compactSession(runtime, sessionId); + } + + emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [], ...(planTask ? { planning: true } : {}) }); + + turn.follow = runtime.gw.openStream('session/follow', { request: { address: { kind: 'session', sessionId }, assistantStream: true } }, { + onItem: item => { + if (item.type === 'snapshot') { + if (turn.lastSeq < 0) turn.lastSeq = item.cursor; + else for (const r of item.records ?? []) if (r.type === 'event' && r.event.seq > turn.lastSeq) handle({ type: 'event', event: r.event }); + turn.snapshot.resolve(); + return; + } + handle(item); + }, + onError: e => finishTurn(`The agent lost the session stream: ${e.message}`), + }); + + /** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */ + function trip(reason) { + if (!reason || turn.guard || turn.finished || turn.stopping) return; + turn.guard = reason; + log(`agent · turn guard: ${reason} (searches ${guard?.searches ?? 0}, failed in a row ${guard?.failedInARow ?? 0}, plan rewrites ${guard?.rewrites ?? 0})`); + void stop(chatId).catch(() => {}); + } + + function handle(item) { + if (turn.finished) return; + turn.lastActivity = Date.now(); + turn.heard = turn.lastActivity; + if (item.type === 'event') { + const e = item.event; + if (e.seq <= turn.lastSeq) return; + turn.lastSeq = e.seq; + // The turn is ours from the user message that carries our request id. Until then an older, + // detached turn on the same session may still be finishing; its events are not ours. + if (!turn.live) { + if (e.type === 'user/message' && e.data?.source?.rpcId === requestId) turn.live = true; + return; + } + } else if (!turn.live) return; + for (const f of projector.consume(item)) emit(f); + if (guard && projector.contextTokens != null) trip(guard.context(projector.contextTokens)); + if (item.type === 'event') watchParent(item.event); + } + + // -- helper agents --------------------------------------------------------------------------------------- + + const rowFrame = child => ({ type: 'agent', agent: child.cp.agent() }); + const emitRow = (child, force = false) => { + const now = Date.now(); + if (!force && now - child.lastRow < 400) { child.rowPending = true; return; } + child.lastRow = now; child.rowPending = false; + emit(rowFrame(child)); + const working = [...turn.children.values()].filter(h => !h.done).length; + if (working && !turn.parentOpen) reporter.set({ phase: 'helpers', code: 'helpers', text: `Helpers are working (${working})…`, key: 'Helpers are working ({0})…', values: [working], args: { n: working } }); + }; + + function openChild(d) { + const id = d.childId; + if (!id || turn.children.has(id)) return; + const cp = new ChildProjector({ id, name: d.label || 'Helper' }); + const child = { id, cp, follow: null, noticed: false, done: false, lastRow: 0, rowPending: false, endedAt: 0 }; + turn.children.set(id, child); + emitRow(child, true); + const fold = item => { + if (turn.finished) return; + turn.lastActivity = turn.heard = Date.now(); + // A helper that finishes before its throttled "working" row went out would show queued -> completed and never "working": send the held row first. + if (item.type === 'event' && item.event.type === 'turn/end' && child.rowPending) emitRow(child, true); + const { frames, row } = cp.consume(item); + for (const f of frames) emit(f); + if (item.type === 'event' && item.event.type === 'turn/end') { child.done = true; child.endedAt = Date.now(); emitRow(child, true); armSettle(); return; } + if (item.type === 'event' && child.done && cp.status === 'working') { child.done = false; } + if (row) emitRow(child); + }; + child.follow = runtime.gw.openStream('session/follow', { + request: { address: { kind: 'subagent', parentSessionId: sessionId, childSessionId: id, mode: d.mode ?? 'unknown' }, assistantStream: true }, + }, { + onItem: item => { + if (item.type === 'snapshot') { for (const r of item.records ?? []) if (r.type === 'event') fold({ type: 'event', event: r.event }); return; } + fold(item); + }, + onError: e => { + log(`agent · helper stream ended: ${e.message}`); + if (!child.done) { child.done = true; child.endedAt = Date.now(); cp.status = 'failed'; cp.failure = 'Lost contact with this helper.'; cp.endedAt = Date.now(); emitRow(child, true); armSettle(); } + }, + }); + // A late reader still gets the final row: flush any row held back by the throttle. + child.flush = after(500, function tick() { if (!turn.finished && child.rowPending) emitRow(child, true); if (!turn.finished && !child.done) child.flush = after(500, tick); }); + } + + function watchParent(e) { + const d = e.data ?? {}; + switch (e.type) { + case 'turn/start': + turn.parentOpen = true; + if (turn.research) turn.research.waitingStart = false; + turn.cutWaiting = false; + clearTimeout(turn.settleTimer); + // After Stop, a helper's report would start a new turn that nobody asked for. + if (turn.stopping) void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); + break; + case 'turn/end': + turn.parentOpen = false; + armSettle(); + break; + // The first turn of a prompt may have started before this follow stream attached (no turn/start seen): any step of the parent is proof that it is + // still working. Without this a helper that finished while the parent was still answering ended the run early ("The agent turn was interrupted"). + case 'step/start': + if (!turn.parentOpen) { turn.parentOpen = true; clearTimeout(turn.settleTimer); } + break; + case 'tool/call': + if (d.name === 'subagent' || d.name === 'subagent_fork') turn.subagentCalls.set(d.callId, parseArgs(d.arguments)); + break; + case 'subagent/catalog': + openChild(d); + break; + case 'tool/result': { + const call = turn.subagentCalls.get(d.message?.toolCallId); + const text = (d.message?.content ?? []).map(p => p.text ?? '').join(' '); + const started = /started subagent ([0-9a-f-]{36})/i.exec(text); + const child = started ? turn.children.get(started[1]) : null; + if (call && child) { child.cp.task = String(call.prompt ?? call.description ?? '').replace(/\s+/g, ' ').trim().slice(0, 140); emitRow(child, true); } + break; + } + case 'user/message': + if (d.source?.kind === 'goal' && Number.isInteger(d.source.round)) { turn.goalRound = d.source.round; void announceGoal(); } + // falls through + case 'agent/inbox/spliced': { + const hit = JSON.stringify(d); + if (!/Background subagent/.test(hit)) break; + for (const child of turn.children.values()) if (hit.includes(child.id)) child.noticed = true; + break; + } + default: + break; + } + } + + // -- plans and goal steps ---------------------------------------------------------------------------------- + + const planFrame = (event, plan, extra = {}) => ({ type: 'plan', event, plan: planView(plan), ...extra }); + const publishPlan = (event, plan) => { onPlan(chatId, event, planView(plan)); return planFrame(event, plan); }; + const stepFrame = (plan, index) => { + const st = plan.steps[index]; + return { type: 'plan-step', planId: plan.id, stepId: st.id, index: index + 1, total: plan.steps.length, state: st.state, text: st.text, summary: st.summary ?? null, line: stepLine(index, plan.steps.length, st.text, st.state === 'running' ? 'started' : st.state) }; + }; + const currentStep = plan => plan.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped'); + + /** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */ + function settlePlan(failure) { + if (planTask) { + if (failure || (turn.stopping && !turn.guard)) return []; + const parsed = parsePlan(written.all, planTask); + if (!parsed) return []; + const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask, ...(turn.guard ? { caution: GUARD_NOTES[turn.guard] } : {}) }); + return [publishPlan('proposed', plan)]; + } + const run = turn.plan; + if (!run) return []; + const plan = plans.get(chatId); + if (!plan || plan.id !== run.id) return []; + if (plan.state !== 'running') return []; + const out = []; + const at = currentStep(plan); + plans.update(chatId, p => { + if (at < 0) { p.state = 'done'; return; } + // The step that was running goes back to waiting, so Resume runs it again. + p.steps[at].state = 'pending'; + p.state = 'paused'; + }); + const updated = plans.get(chatId); + if (at >= 0) out.push(stepFrame(updated, at)); + out.push(publishPlan(updated.state === 'done' ? 'done' : 'paused', updated)); + return out; + } + + /** The goal the Harness runs for the plan's next waiting step, and the frames that say so. */ + async function startStep(plan, index) { + plans.update(chatId, p => { p.state = 'running'; p.goalStarted = true; p.steps[index].state = 'running'; }); + const now = plans.get(chatId); + await runtime.gw.rpc('goals/create', { agentId: sessionId, request: { objective: stepObjective(now, index) } }); + written.step = ''; written.stepAt = Date.now(); + emit(stepFrame(now, index)); + emit(publishPlan('step', now)); + const st = now.steps[index]; + reporter.set({ phase: 'goal', code: 'goal-step', text: stepLine(index, now.steps.length, st.text, 'started'), key: '{0}', values: [st.text], args: { step: index + 1, steps: now.steps.length } }); + } + + /** One goal step finished: say so, hand over queued messages, and begin the next step (or end the plan). */ + async function advancePlan() { + const run = turn.plan; + const plan = plans.get(chatId); + if (!run || !plan || plan.id !== run.id) return false; + const at = currentStep(plan); + if (at < 0) return false; + const cards = [...projector.tools.values()].filter(x => x.calledAt >= (written.stepAt ?? 0) - 50 && x.card?.state === 'done').map(x => x.card); + const summary = stepSummary(cards, written.step.split(/\n\s*\n/).filter(Boolean).at(-1) ?? written.step); + plans.update(chatId, p => { p.steps[at].state = 'done'; p.steps[at].summary = summary; }); + let now = plans.get(chatId); + emit(stepFrame(now, at)); + emit({ type: 'delta', own: true, text: `\n\n${stepLine(at, now.steps.length, now.steps[at].text, 'done')}\n` }); + const next = currentStep(now); + emit(publishPlan(next < 0 ? 'done' : 'step', next < 0 ? (plans.update(chatId, p => { p.state = 'done'; }), plans.get(chatId)) : now)); + await deliverQueued(at + 1); + if (turn.stopping || turn.finished) return true; + if (next < 0) return false; + // One step per turn (Time-skip): the plan stays open for the next step, which starts in a session of its own so the conversation never grows across steps. + if (run.once) { plans.update(chatId, p => { p.state = 'approved'; }); emit(publishPlan('step', plans.get(chatId))); return false; } + await startStep(plans.get(chatId), next); + void announceGoal(); + return true; + } + + /** Hand the person's queued messages to the assistant, one at a time, each answered before the next. */ + async function deliverQueued(afterStep) { + const list = queues.get(chatId) ?? []; + while (list.length && !turn.stopping && !turn.finished) { + const item = list.shift(); + if (!list.length) queues.delete(chatId); + onQueue(chatId, queueView(chatId)); + emit({ type: 'queued-message', state: 'delivered', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, afterStep, queue: queueView(chatId) }); + try { await runtime.gw.rpc('session/prompt', { request: { requestId: `queued-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: item.text }] } }); } + catch { emit({ type: 'queued-release', messages: [{ id: item.id, text: item.text }] }); continue; } + // Wait for the answer: the parent opens a turn for it and closes it again. + const t0 = Date.now(); + while (!turn.parentOpen && Date.now() - t0 < 4000 && !turn.finished) await new Promise(r => setTimeout(r, 50)); + while (turn.parentOpen && !turn.finished && !turn.stopping) await new Promise(r => setTimeout(r, 100)); + } + } + + /** + * The run is over when the parent is idle and every helper has finished and reported back. A helper's report + * wakes the parent a moment after the helper ends, so a helper that ended but has not reported yet keeps the run + * open (for a few seconds at most); after Stop nobody waits for reports. + */ + function armSettle() { + clearTimeout(turn.settleTimer); + if (turn.finished) return; + turn.settleTimer = after(turn.stopping ? 1200 : turn.children.size ? 600 : 0, async () => { + if (turn.finished || turn.parentOpen || turn.advancing) return; + const open = [...turn.children.values()]; + if (open.some(c => !c.done)) return; + if (!turn.stopping) { + if (open.some(c => !c.noticed && Date.now() - c.endedAt < 8000)) { armSettle(); return; } + // An armed goal starts its next round as soon as the agent is idle: the run is not over until the goal stops. + const current = await goalGet(); + if (turn.finished || turn.parentOpen) return; + if (current && current.phase === 'active' && current.activation === 'armed') { turn.settleTimer = after(700, armSettle); return; } + // A reply the length limit cut (AGENT-LOST): the agent lost what it was writing. Say so in the chat and ask it to carry on in smaller pieces, twice at most. + if (turn.cutWaiting) { turn.settleTimer = after(300, armSettle); return; } + if (projector.ended?.kind === 'max-tokens' && !turn.goalRun && !turn.stopping && (turn.cuts ?? 0) < MAX_CUT_RETRIES) { + const cut = projector.cut(); + turn.cuts = (turn.cuts ?? 0) + 1; + const note = cutNotice({ ...cut, retrying: true }); + emit({ type: 'delta', own: true, text: ` + +${note.text} + +`, key: note.key, values: note.values, noteReason: 'cut' }); + for (const f of projector.clearCut()) emit(f); + turn.cutWaiting = true; + try { await runtime.gw.rpc('session/prompt', { request: { requestId: `cut-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: cutNudge(cut) }] } }); } + catch { turn.cutWaiting = false; finishTurn(null); return; } + turn.settleTimer = after(500, armSettle); + return; + } + // Research: gather (search and read pages), then write the answer in the fixed shape. A step that did not open pages is sent back once. + if (turn.research && !turn.stopping) { + const r = turn.research; + if (r.waitingStart) { turn.settleTimer = after(300, armSettle); return; } + const opened = [...projector.tools.values()].filter(x => x.card?.name === 'web_fetch' && x.card.state === 'done').length; + const prompt = r.phase === 'write' ? null : (opened < 2 && !r.nudged) ? RESEARCH_NUDGE : researchWritePrompt(researchTopic); + if (prompt) { + if (prompt !== RESEARCH_NUDGE) { r.phase = 'write'; hideDeltas = false; written.all = ''; reporter.set({ phase: 'waiting', code: 'research-writing', text: 'Writing the answer…', key: 'Writing the answer…', values: [], args: {} }); } else r.nudged = true; + r.waitingStart = true; + try { await runtime.gw.rpc('session/prompt', { request: { requestId: `research-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }] } }); } + catch { r.waitingStart = false; hideDeltas = false; finishTurn(null); return; } + turn.settleTimer = after(500, armSettle); + return; + } + } + // A plan step's goal is complete: record it, deliver queued messages, start the next step. + if (turn.plan && current && current.phase === 'complete' && !turn.advancing) { + turn.advancing = true; + let more = false; + try { more = await advancePlan(); } catch (e) { emit({ type: 'delta', own: true, text: `\n\nThe plan stopped: ${plainGoalError(e)}\n` }); } + turn.advancing = false; + if (more && !turn.finished && !turn.stopping) { turn.settleTimer = after(700, armSettle); return; } + } + + if (turn.goalRun && current) { const line = goalEnding(current); if (line) emit({ type: 'delta', text: line }); } + if (turn.goalRun) await announceGoal(true); + } + finishTurn(null); + }); + } + const goalGet = () => runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined); + /** The goal's state to the page: a `goal` frame, the SSE event for the bar, and (while a round runs) the status line. */ + async function announceGoal(final = false) { + const view = await goalGet(); + if (turn.finished && !final) return; + const goal = goalObject(view, chatId); + emit({ type: 'goal', goal }); + onGoal(chatId, goal); + if (!final && goal && goal.phase === 'active' && turn.goalRound) reporter.set({ phase: 'goal', code: 'goal-step', text: 'Working on the goal…', args: { round: turn.goalRound, max: goal.maxRounds } }); + } + turn.announceGoal = announceGoal; + turn.announceQueue = frame => emit(frame); + turn.announceQuestion = frame => emit(frame); + + const snapshotTimer = {}; + await Promise.race([turn.snapshot.promise, new Promise((_, rej) => { snapshotTimer.t = after(20_000, () => rej(new Error('the session stream did not open'))); })]) + .catch(e => { finishTurn(e.message); }) + .finally(() => clearTimeout(snapshotTimer.t)); + if (turn.finished) return { error: true }; + if (turn.stopBeforePrompt || c.cancelStart) { projector.ended = { kind: 'aborted', reason: { kind: 'user' } }; finishTurn(null); return { cancelled: true }; } + + if (goal) { + // A goal run has no prompt of its own: the Harness's goal driver starts the rounds. Everything from now on is ours. + turn.live = true; turn.goalRun = true; + try { + if (planRun) { + const plan = plans.get(chatId); + if (!plan || plan.id !== planRun.planId) throw new AgentUnavailable('That plan is no longer there. Ask for a new one with /plan.', 'plan-gone'); + turn.plan = { id: plan.id, once: !!planRun.once }; + const at = currentStep(plan); + if (at < 0) throw new AgentUnavailable('Every step of this plan is already done.', 'plan-done'); + if (goal.action === 'resume' && plan.goalStarted) { + plans.update(chatId, p => { p.state = 'running'; p.steps[at].state = 'running'; }); + await startGoal(runtime, sessionId, goal); + emit(publishPlan('step', plans.get(chatId))); + } else await startStep(plan, at); + } else { + await startGoal(runtime, sessionId, goal); + } + } catch (e) { finishTurn(e instanceof AgentUnavailable ? e.message : plainGoalError(e)); return { error: true }; } + reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); + void announceGoal(); + } else { + let prompt = message; + if (fresh && history.length) prompt = withEarlierConversation(history, message); + try { + await runtime.gw.rpc('session/prompt', { request: { requestId, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }, ...imageParts(images)] } }); + } catch (e) { + finishTurn(`The agent did not accept the message: ${e.message}`); + return { error: true }; + } + } + if (!goal) reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' }); + turn.prompted = true; + if (turn.stopBeforePrompt) { + // Stop landed in the instant between 'prompt sent' and 'prompt accepted'. A cancel before the turn + // starts arms nothing, so wait for the turn to be ours, then cancel it. + for (let i = 0; i < 100 && !turn.live && !turn.finished; i++) await new Promise(r => setTimeout(r, 50)); + if (!turn.finished) await runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); + } + + // Wait for the turn, or for the client to leave. Leaving does not stop the turn. + const gone = new Promise(r => signal?.addEventListener('abort', () => r('detached'), { once: true })); + const outcome = await Promise.race([turn.ended.promise, gone]); + if (outcome === 'detached') return { detached: true, sessionId, ended: turn.ended.promise.then(r => ({ ...r, tokensOut: projector.tokensOut })) }; + return { sessionId, reason: outcome.reason, tokensIn: projector.tokensIn, tokensOut: projector.tokensOut }; + } + + // -- /goal ----------------------------------------------------------------------------------------------- + + /** Create or resume the chat's goal; the Harness's goal driver then runs the rounds by itself. */ + async function startGoal(runtime, sessionId, goal) { + if (goal.action === 'create') { + const request = { objective: goal.objective, ...(goal.maxRounds ? { maxGoalRounds: goal.maxRounds } : {}) }; + await runtime.gw.rpc('goals/create', { agentId: sessionId, request }); + return; + } + const current = await runtime.gw.rpc('goals/get', { agentId: sessionId }); + if (!current) throw new AgentUnavailable('There is no goal to continue. Start one with /goal followed by what you want done.', 'goal-none'); + await runtime.gw.rpc('goals/resume', { agentId: sessionId, ref: { id: current.id, revision: current.revision } }); + } + + async function pauseGoal(runtime, sessionId, chatId = null) { + try { + const current = await runtime.gw.rpc('goals/get', { agentId: sessionId }); + if (current && current.phase === 'active') { + await runtime.gw.rpc('goals/pause', { agentId: sessionId, ref: { id: current.id, revision: current.revision } }); + if (chatId) onGoal(chatId, goalObject(await runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined))); + } + } catch { /* no goal service, or nothing to pause */ } + } + + /** The goal as the page and the goal bar see it (notes-split-agent3.md), or null. */ + function goalObject(view, chatId = null) { + if (!view) return null; + const phase = ['active', 'paused', 'complete', 'blocked'].includes(view.phase) ? view.phase : 'blocked'; + // A goal that is running a plan (or the points of a goal) shows the plan's title and which step it is on. + const plan = chatId ? plans.get(chatId) : null; + const running = plan && plan.goalStarted && ['running', 'paused'].includes(plan.state) ? plan : null; + const at = running ? running.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped') : -1; + const step = running && at >= 0 ? { index: at + 1, total: running.steps.length, text: running.steps[at].text } : null; + return { objective: step ? running.title : String(view.objective ?? ''), ...(step ? { step } : {}), phase, round: view.roundsStarted ?? 0, maxRounds: view.maxGoalRounds ?? null, ...(phase === 'blocked' ? { blocked: plainBlocker(view.blockedReason) } : {}) }; + } + + /** The goal of a chat now, from the Harness (null: none, or the agent is not running). */ + async function goalState(chatId) { + const known = sessionMap[chatId]?.sessionId; + if (!known || !rt?.hp.running) return null; + return goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId); + } + + /** Pause, edit or remove the goal from the goal bar. Instant; resume runs rounds and goes through the chat stream. */ + async function goalControl({ chatId, action, text }) { + const known = sessionMap[chatId]?.sessionId; + if (!known || !rt?.hp.running) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none'); + const current = await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined); + if (!current) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none'); + const ref = { id: current.id, revision: current.revision }; + try { + if (action === 'pause') { if (current.phase === 'active') await rt.gw.rpc('goals/pause', { agentId: known, ref }); } + else if (action === 'clear') await rt.gw.rpc('goals/clear', { agentId: known, ref }); + else if (action === 'edit') { + const objective = String(text ?? '').trim().slice(0, 4000); + if (!objective) throw new AgentUnavailable('A goal needs a few words about what you want done.', 'goal-text'); + await rt.gw.rpc('goals/edit', { agentId: known, ref, request: { objective } }); + } else throw new AgentUnavailable('That goal action is not known.', 'goal-action'); + } catch (e) { throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainGoalError(e), 'goal-failed', e.message); } + if (action === 'clear') { const plan = plans.get(chatId); if (plan && ['running', 'paused'].includes(plan.state)) { plans.update(chatId, p => { p.state = 'stopped'; for (const st of p.steps) if (st.state === 'running') st.state = 'pending'; }); onPlan(chatId, 'stopped', planView(plans.get(chatId))); } } + const goal = action === 'clear' ? null : goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId); + onGoal(chatId, goal); + return { goal }; + } + + /** The goal's state in plain words. */ + function describeGoal(view) { + if (!view) return 'No goal is set. Start one with /goal followed by what you want done.'; + const what = `"${view.objective}"`; + if (view.phase === 'active') return `Working on the goal ${what}.`; + if (view.phase === 'paused') return `The goal ${what} is paused. Type /goal resume to go on.`; + if (view.phase === 'complete') return `The goal ${what} is complete.`; + return `The goal ${what} stopped: ${plainBlocker(view.blockedReason)}`; + } + + /** + * Handle a "/goal ..." line for a chat, as the Harness's own /goal command reads it: nothing = show the goal, + * clear, pause, resume, edit <text>, or any other text = a new goal. Starting or resuming runs the rounds and + * streams them like a chat turn (Stop pauses the goal); every other verb answers at once. + */ + async function goalCommand(options) { + const { chatId, line, onFrame } = options; + const text = String(line ?? '').trim(); + const verb = text.split(/\s+/)[0]?.toLowerCase() ?? ''; + const rest = text.slice(verb.length).trim(); + const say = reply => { + onFrame({ type: 'queued', requestId: `goal-${randomUUID()}` }); + onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); + onFrame({ type: 'delta', text: reply }); + onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); + return { goal: true }; + }; + if (tools()?.off?.has('goals')) return say('Goals are turned off. You can turn them back on in Settings, Tools.'); + const known = sessionMap[chatId]?.sessionId; + const quick = ['', 'clear', 'pause', 'edit', 'complete'].includes(verb) || (verb === 'status'); + let runtime = rt; + if (quick) { + if (!known || !runtime?.hp.running) return say(verb === '' || verb === 'status' ? describeGoal(null) : 'There is no goal in this chat yet.'); + const current = await runtime.gw.rpc('goals/get', { agentId: known }).catch(() => undefined); + const ref = current ? { id: current.id, revision: current.revision } : null; + try { + if (verb === '' || verb === 'status') return say(describeGoal(current)); + if (!ref) return say('There is no goal in this chat yet.'); + if (verb === 'clear') { await runtime.gw.rpc('goals/clear', { agentId: known, ref }); return say('The goal is cleared.'); } + if (verb === 'pause') { + if (current.phase === 'active') await runtime.gw.rpc('goals/pause', { agentId: known, ref }); + return say(describeGoal(await runtime.gw.rpc('goals/get', { agentId: known }))); + } + if (verb === 'complete') { await runtime.gw.rpc('goals/complete', { agentId: known, ref }); return say('The goal is marked complete.'); } + if (verb === 'edit') { + if (!rest) return say('Type /goal edit followed by the new wording of the goal.'); + await runtime.gw.rpc('goals/edit', { agentId: known, ref, request: { objective: rest } }); + return say(`The goal now reads: "${rest}".`); + } + } catch (e) { return say(plainGoalError(e)); } + } + if (verb === 'resume') { + const plan = plans.get(chatId); + const goalPlan = plan && plan.goalStarted && plan.state === 'paused' ? { planId: plan.id } : null; + return runTurn({ ...options, goal: { action: 'resume' }, ...(goalPlan ? { planRun: goalPlan } : {}) }); + } + // A goal whose own words hold numbered points ("1. ... 2. ... 3. ...") runs point by point, each one reported. + const points = parsePoints(text); + if (points) { + const plan = plans.create(chatId, { title: points.title, steps: points.steps, request: text, source: 'goal', state: 'approved' }); + onPlan(chatId, 'approved', planView(plan)); + return runTurn({ ...options, goal: { action: 'create', objective: text }, planRun: { planId: plan.id } }); + } + // Any other text is a new goal. One unfinished goal at a time (the Harness's rule): say so in plain words. + return runTurn({ ...options, goal: { action: 'create', objective: text } }); + } + + // -- /plan ----------------------------------------------------------------------------------------------- + + /** A short answer in the chat that the page translates (the sentence is in the interface catalog, "values" fill its slots). */ + function sayKey(options, template, values = []) { + const { onFrame } = options; + onFrame({ type: 'queued', requestId: 'compact-' + randomUUID() }); + onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); + onFrame({ type: 'delta', text: fill(template, values), key: template, values }); + onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); + return { compact: true }; + } + + /** A short answer in the chat (no model): the same frames a turn sends. */ + function sayOnce(options, reply) { + const { onFrame } = options; + onFrame({ type: 'queued', requestId: `plan-${randomUUID()}` }); + onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] }); + onFrame({ type: 'delta', text: reply }); + onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 }); + return { plan: true }; + } + + /** + * "/plan <what you want>": the assistant looks around (the chat is put in Plan mode for this turn, so nothing can change), writes the + * plan, and the host sends it as a `plan` frame. Nothing runs until the person approves it. + */ + async function planCommand(options) { + const task = String(options.line ?? '').trim(); + if (!task) { + const open = plans.get(options.chatId); + return sayOnce(options, open && ['proposed', 'approved'].includes(open.state) + ? 'A plan is waiting for you above. Approve it, edit it or reject it, or type /plan followed by something else to make a new one.' + : 'Type /plan followed by what you want done, for example: /plan build a small pagoda page. I will look around and write a plan; nothing changes until you approve it.'); + } + return runTurn({ ...options, message: planPrompt(task), planTask: task, mode: 'plan' }); + } + + /** + * "/research <topic>": the assistant searches the web, opens and reads pages, and writes a short structured answer (Summary, Key findings, + * Sources). The host also sends the sources as a `research` frame before the end of the turn. Needs web search turned on. + */ + async function researchCommand(options) { + const topic = String(options.line ?? '').trim(); + if (!topic) return sayOnce(options, 'Type /research followed by what you want to know, for example: /research how do heat pumps compare with gas boilers. I will search the web, read the pages and answer with sources.'); + if (tools()?.off?.has('search')) return sayOnce(options, 'Research needs web search, which is turned off. Turn it on in Settings, Tools (DuckDuckGo needs no key), then try again.'); + return runTurn({ ...options, message: researchPrompt(topic), researchTopic: topic }); + } + + const planGone = () => new AgentUnavailable('There is no plan waiting in this chat. Ask for one with /plan followed by what you want done.', 'plan-gone'); + function planOf(chatId, planId) { + const plan = plans.get(chatId); + if (!plan || (planId && plan.id !== planId)) throw planGone(); + return plan; + } + const mustBeOpen = plan => { if (plan.state !== 'proposed' && plan.state !== 'approved') throw new AgentUnavailable('This plan has already been used. Ask for a new one with /plan.', 'plan-used'); }; + + /** A short note added to every step of the chat's plan (the Time-skip B path: where its work comes from). */ + function setPlanBriefing(chatId, text) { plans.update(chatId, p => { p.briefing = String(text ?? '').slice(0, 600); }); } + + /** The plan of a chat, or null. */ + const planState = chatId => planView(plans.get(chatId)); + + /** Approve, edit or reject the plan; instant. Approve also returns the message that carries the plan out as an ordinary turn. */ + function planControl({ chatId, planId, action, steps, title }) { + const plan = planOf(chatId, planId); + if (action === 'edit') { + mustBeOpen(plan); + const next = editedSteps(steps, plan.steps); + const t = String(title ?? '').replace(/\s+/g, ' ').trim().slice(0, 80); + plans.update(chatId, p => { p.steps = next; if (t) p.title = t; p.state = 'proposed'; }); + onPlan(chatId, 'edited', planView(plans.get(chatId))); + return { plan: planView(plans.get(chatId)) }; + } + if (action === 'approve') { + mustBeOpen(plan); + plans.update(chatId, p => { p.state = 'approved'; }); + const approved = plans.get(chatId); + onPlan(chatId, 'approved', planView(approved)); + return { plan: planView(approved), prompt: planAsPrompt(approved) }; + } + if (action === 'reject') { + mustBeOpen(plan); + plans.update(chatId, p => { p.state = 'rejected'; }); + onPlan(chatId, 'rejected', planView(plans.get(chatId))); + return { plan: planView(plans.get(chatId)) }; + } + throw new AgentUnavailable('That plan action is not known.', 'plan-action'); + } + + /** "Start as goal": each step of the plan becomes a goal step, run one after another and reported. Streams like a chat turn. */ + async function planGoal(options) { + const { chatId, planId } = options; + let plan; + try { plan = planOf(chatId, planId); } catch (e) { return sayOnce(options, e.message); } + if (modeOf(options.mode) === 'plan') return sayOnce(options, 'Plan mode only looks, so it cannot carry out a plan. Switch this chat to Manual or Bypass, then start it again.'); + if (plan.state === 'paused' && plan.goalStarted) return goalCommand({ ...options, line: 'resume' }); + try { mustBeOpen(plan); } catch (e) { return sayOnce(options, e.message); } + if (tools()?.off?.has('goals')) return sayOnce(options, 'Goals are turned off. You can turn them back on in Settings, Tools.'); + plans.update(chatId, p => { p.state = 'approved'; }); + onPlan(chatId, 'approved', planView(plans.get(chatId))); + return runTurn({ ...options, goal: { action: 'create', objective: plan.title }, planRun: { planId: plan.id, once: options.once === true } }); + } + + /** A paused plan becomes open again (a step that did not finish is tried again in a fresh session). */ + function reopenPlan(chatId) { const p = plans.get(chatId); if (p && p.state === 'paused') { plans.update(chatId, x => { x.state = 'approved'; }); onPlan(chatId, 'approved', planView(plans.get(chatId))); } } + + /** Give up on one step with a plain note (a check that cannot be done here) so the rest of the plan can go on. */ + function skipStep(chatId, index, note) { plans.update(chatId, p => { const st = p.steps[index]; if (st) { st.state = 'skipped'; st.summary = String(note ?? 'Skipped.').slice(0, 140); } if (p.state === 'paused') p.state = 'approved'; }); onPlan(chatId, 'step', planView(plans.get(chatId))); } + + /** Forget the chat's agent session (not its plan): the next turn starts a fresh one in the same folder. */ + function resetSession(chatId) { + if (chats.get(chatId)?.turn || chats.get(chatId)?.starting) throw new AgentUnavailable('This chat is still working.', 'turn-active'); + delete sessionMap[chatId]; persist(); + } + + // -- the agent's own questions ------------------------------------------------------------------------------ + + /** + * The person's answer to a question the agent asked (#4244), or a skip. The answer is checked against the questions that were asked, then sent + * to the Harness as the result of the waiting `user-questions/request`; a skip declares the question unanswerable, as before, and the model + * carries on. + */ + async function answerQuestion({ chatId, callId, answers, skip = false }) { + const sessionId = sessionMap[chatId]?.sessionId; + const key = `${sessionId}:${callId}`; + const entry = questions.get(key); + if (!entry || !rt?.hp.running) throw new AgentUnavailable('That question was already answered, or the assistant has gone on.', 'question-gone'); + const outcome = skip ? 'next' : buildAnswer(entry.items, answers); + await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome }); + questions.delete(key); + return { ok: true, skipped: !!skip }; + } + + // -- a message for a helper --------------------------------------------------------------------------------- + + /** + * The person's own words for one helper (#4749), through the Harness's `subagents/prompt`: it delivers one browser-authored message to a + * continuable child through its live parent. "steer" reaches a working helper at its next step; "queue" gives a helper that has finished + * (or is between steps) a new turn. The Harness refuses a helper that cannot take messages (a one-shot one) and a parent that is not live; + * either comes back as a plain sentence. + */ + async function messageHelper({ chatId, helperId, text, delivery = 'queue' }) { + const clean = String(text ?? '').trim().slice(0, 8000); + if (!clean) throw new AgentUnavailable('Type a few words for the helper.', 'helper-empty'); + if (!/^[\w.:@-]{1,160}$/.test(String(helperId ?? ''))) throw new AgentUnavailable('That helper is not known.', 'helper-unknown'); + const parent = sessionMap[chatId]?.sessionId; + if (!parent || !rt?.hp.running) throw new AgentUnavailable('The assistant is not running in this chat, so it cannot pass a message on. Send a message in the chat first.', 'helper-idle'); + try { + const receipt = await rt.gw.rpc('subagents/prompt', { request: { requestId: `helper-${randomUUID()}`, parentSessionId: parent, childSessionId: String(helperId), mode: 'continuable', delivery: delivery === 'steer' ? 'steer' : 'queue', content: [{ type: 'text', text: clean }] } }); + return { ok: true, messageId: receipt?.messageId ?? null, delivery: delivery === 'steer' ? 'steer' : 'queue' }; + } catch (e) { + log(`agent · message for a helper refused: ${String(e?.message ?? e).slice(0, 200)}`); + throw new AgentUnavailable(/continuable|one-shot|not.*(found|live|open)|unavailable|closed|ended/i.test(String(e?.message ?? '')) ? 'This helper cannot take a message any more. Ask the assistant in the chat to start a new one.' : 'The message could not be delivered right now. Try again in a moment.', 'helper-refused'); + } + } + + // -- messages typed while a goal runs ---------------------------------------------------------------------- + + /** Queue a message for the running goal. It is delivered between steps, or handed back to the page when the goal ends or pauses. */ + function queueMessage({ chatId, text }) { + const turn = chats.get(chatId)?.turn; + if (!turn || !turn.goalRun || turn.stopping || turn.finished) throw new AgentUnavailable('No goal is running in this chat, so there is nothing to queue behind. Send the message as usual.', 'queue-idle'); + const clean = String(text ?? '').trim().slice(0, 8000); + if (!clean) throw new AgentUnavailable('Type a few words to queue.', 'queue-empty'); + const list = queues.get(chatId) ?? []; + if (list.length >= 20) throw new AgentUnavailable('Twenty messages are already waiting. Wait for some to be delivered.', 'queue-full'); + const item = { id: randomUUID(), text: clean, at: new Date().toISOString(), deliverAt: turn.plan ? 'step' : 'end' }; + list.push(item); queues.set(chatId, list); + const message = { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }; + onQueue(chatId, queueView(chatId)); + turn.announceQueue?.({ type: 'queued-message', state: 'queued', message, queue: queueView(chatId) }); + return { message, queue: queueView(chatId) }; + } + + /** Take a queued message back (the x on it). A message already being delivered cannot be taken back. */ + function cancelQueued({ chatId, id }) { + const list = queues.get(chatId) ?? []; + const at = list.findIndex(m => m.id === id); + if (at < 0) throw new AgentUnavailable('That message was already sent or removed.', 'queue-gone'); + const [item] = list.splice(at, 1); + if (!list.length) queues.delete(chatId); + onQueue(chatId, queueView(chatId)); + chats.get(chatId)?.turn?.announceQueue?.({ type: 'queued-message', state: 'cancelled', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, queue: queueView(chatId) }); + return { queue: queueView(chatId) }; + } + + /** Messages waiting for a chat, and (after a goal ended while the page was away) the ones it should now send. */ + function takeQueue(chatId, { release = false } = {}) { + const turn = chats.get(chatId)?.turn; + const list = queueView(chatId); + if (release && !turn && list.length) { queues.delete(chatId); onQueue(chatId, []); return { queue: [], released: list.map(({ id, text }) => ({ id, text })) }; } + return { queue: list, released: [] }; + } + + /** + * The person changed the chat's mode while a turn (a goal and its helpers included) is running. The new preset + * is put on the session at once, the running turn's own bookkeeping follows, and questions already waiting are + * settled the way the new mode would have settled them: Bypass allows them, Plan rejects them. + */ + async function setMode(chatId, mode) { + const want = modeOf(mode); + const c = chats.get(chatId); + const sessionId = sessionMap[chatId]?.sessionId; + if (!rt || !sessionId) return { applied: false, mode: want, reason: 'no session yet' }; + if (c?.turn && c.turn.mode === want) return { applied: true, mode: want, settled: 0 }; + await applyMode(rt, sessionId, want); + let settled = 0; + if (c?.turn) { + c.turn.mode = want; + c.turn.projector.policy = MODE_PRESETS[want].approval; + if (want !== 'manual') { + const helpers = c.turn.children; + for (const [key, entry] of [...pending.entries()]) { + if (entry.sessionId !== sessionId && !helpers?.has(entry.sessionId)) continue; + pending.delete(key); + try { await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: want === 'bypass' ? 'allowed-once' : 'rejected' }); settled++; } catch { /* already answered */ } + } + } + } + return { applied: true, mode: want, settled }; + } + + /** Answer one pending approval. `decision` is `approve` or `deny`. */ + async function approve({ chatId, callId, decision }) { + const sessionId = sessionMap[chatId]?.sessionId; + // A helper agent's question carries the helper's session id in front of its call id. Only a helper that belongs to + // THIS chat's run can be answered from this chat. + const [maybeChild] = String(callId).split(':'); + const ownHelper = callId.includes(':') && chats.get(chatId)?.turn?.children.has(maybeChild); + const key = ownHelper ? callId : `${sessionId}:${callId}`; + // The durable `approval/asked` (which makes the card say "needs approval") and the waterfall frame + // (which makes it answerable) travel on different streams; a fast click can beat the second one. + let entry = sessionId ? pending.get(key) : null; + for (let i = 0; !entry && sessionId && i < 40; i++) { + await new Promise(r => setTimeout(r, 50)); + entry = pending.get(key); + } + if (!entry) throw new AgentUnavailable('That question is no longer waiting for an answer.', 'approval-gone'); + if (!rt?.hp.running) throw new AgentUnavailable('That question expired because the coding assistant restarted. Ask again.', 'approval-gone'); + pending.delete(key); + try { + await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: decision === 'approve' ? 'allowed-once' : 'rejected' }); + } catch (e) { + throw new AgentUnavailable('Your answer could not be delivered. Ask again.', 'approval-gone', e.message); + } + return { ok: true }; + } + + /** + * Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the + * Harness acknowledges a cancel as admitted, not as done. + */ + /** What the chat holds now and the model's window, as the context plugin measures them (null when it cannot be read). */ + async function contextOf(runtime, sessionId) { + try { + const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-context', submittedAttachments: [] }); + if (r?.result?.kind !== 'success') return null; + const v = JSON.parse(String(r.result.text)); + return Number.isFinite(v.tokens) ? { tokens: Math.round(v.tokens), window: Number(v.window) > 0 ? Math.round(v.window) : 0 } : null; + } catch { return null; } + } + + /** The decision of context-fit.mjs for the message about to be sent, or null when the model server cannot count it. */ + async function fitCheck({ runtime, route, sessionId, fresh, history, message }) { + const inst = localInstances().find(i => i.id === route.instanceId); + if (!inst || !(route.contextWindow > 0)) return null; + const carried = fresh && history.length ? withEarlierConversation(history, message) : message; + if (carried.length < COUNT_ABOVE_CHARS) return null; + const count = text => countTokens({ baseUrl: inst.baseUrl, key: inst.key, model: inst.modelId, text }); + let tokens = await count(carried); + if (tokens == null) return null; + const now = fresh ? null : await contextOf(runtime, sessionId); + const window = now?.window || route.contextWindow; + const pressure = now?.tokens ?? 0; + // Where the Harness starts summarising by itself on this window (profile.mjs: the reply keeps its room, then the headroom). + const reply = localOutputBudget(window); + const threshold = Math.floor(Math.min(window * 0.8, window - reply - compactionHeadroom(window, reply))); + let verdict = decideFit({ window, pressure, messageTokens: tokens, threshold }); + // The earlier conversation carried into a fresh session is what pushed it over: send the message alone instead. + if (verdict.action === 'too-large' && carried !== message) { + const alone = await count(message); + if (alone != null) { tokens = alone; verdict = decideFit({ window, pressure, messageTokens: alone, threshold }); } + } + return { ...verdict, tokens, window, pressure }; + } + + /** + * Summarise the older part of a chat with the Harness's /compact and say what happened. Never throws. + * ok:true carries the figures before and after; ok:false says why (nothing to summarise, busy, failed). + */ + async function compactChat(runtime, sessionId) { + const before = await contextOf(runtime, sessionId); + let result; + try { result = (await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }))?.result; } + catch (e) { return { ok: false, reason: /not.found|no such/i.test(String(e.message)) ? 'nothing' : 'failed', before, text: String(e.message ?? e) }; } + const text = String(result?.text ?? ''); + log('agent · compact: ' + (result?.kind ?? 'none') + ' ' + text.slice(0, 140)); + if (result?.kind === 'success' && /^Compacted/i.test(text)) return { ok: true, before, after: await contextOf(runtime, sessionId) }; + if (result?.kind === 'success') return { ok: false, reason: 'nothing', before, text }; + if (/active compaction|not idle/i.test(text)) return { ok: false, reason: 'busy', before, text }; + // The Harness cannot make a summary smaller than what is left when the chat holds little beyond its first prompt: that is nothing to summarise, not a failure. + const little = before && before.window > 0 && before.tokens - BASE_TOKENS < before.window * 0.25; + return { ok: false, reason: little && /useful summary|not smaller/i.test(text) ? 'nothing' : 'failed', before, text }; + } + + /** The line in the chat that explains why the context meter fell: how full it was and how full it is. */ + function summarizedNote(before, after, window) { + const w = after?.window || before?.window || window || 0; + const pct = v => Math.max(0, Math.min(100, Math.round(100 * v.tokens / w))); + const known = w > 0 && before && after; + const template = known ? FIT_TEXT.summarized : FIT_TEXT.summarizedShort; + const values = known ? [pct(before), pct(after)] : []; + return { type: 'delta', own: true, text: '\n\n' + fill(template, values), key: template, values, noteReason: 'compacted' }; + } + + /** "/compact": summarise the older messages of this chat now, and say in plain words what happened. */ + async function compactCommand(options) { + const { chatId, choice, signal } = options; + const c = chat(chatId); + const say = (template, values = []) => sayKey(options, template, values); + if (c.turn || c.starting) return say(FIT_TEXT.compactBusy); + const known = sessionMap[chatId]?.sessionId; + if (!known) return say(FIT_TEXT.noChatYet); + let runtime; + try { ({ rt: runtime } = await ensureRuntime(choice, signal)); } catch { return say(FIT_TEXT.compactFailed); } + const done = await compactChat(runtime, known); + if (done.ok) { + const note = summarizedNote(done.before, done.after, 0); + return say(note.key, note.values); + } + if (done.reason === 'busy') return say(FIT_TEXT.compactBusy); + if (done.reason === 'nothing') { + const w = done.before?.window || 0; + const pct = w > 0 && done.before ? Math.round(100 * done.before.tokens / w) : 0; + return say(pct >= 60 ? FIT_TEXT.nothingFull : FIT_TEXT.nothingToSummarize, pct >= 60 ? [pct] : []); + } + return say(FIT_TEXT.compactFailed); + } + + /** Summarise the older part of a session with the Harness's own /compact. Best effort: the next message compacts again by itself when it must. */ + async function compactSession(runtime, sessionId) { + try { + const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }); + log(`agent · compact after a stopped turn: ${r?.result?.kind ?? 'done'} ${String(r?.result?.text ?? '').slice(0, 120)}`); + } catch (e) { log(`agent · compact after a stopped turn failed: ${e.message}`); } + } + + async function stop(chatId, { waitMs = 20_000 } = {}) { + const c = chats.get(chatId); + const turn = c?.turn; + if (!turn && c?.starting) { c.cancelStart = true; return { stopped: true, ended: 'cancelled-before-start', ms: 0 }; } + if (!turn || !rt) return { stopped: false, reason: 'no active turn' }; + const t0 = Date.now(); + if (!turn.prompted) { + // The Harness has not been given the prompt yet, so there is nothing to cancel there. + turn.stopBeforePrompt = true; + const early = await Promise.race([turn.ended.promise, new Promise(r => setTimeout(() => r(null), 100))]); + if (early) return { stopped: true, ended: early.reason?.kind ?? 'aborted', ms: Date.now() - t0 }; + } + turn.stopping = true; + await pauseGoal(rt, turn.sessionId, chatId); + // Helpers first: a helper still working would otherwise report back and wake the parent again. + await Promise.allSettled([...turn.children.values()].filter(h => !h.done).map(h => rt.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: turn.sessionId, mode: 'continuable' }))); + await rt.gw.rpc('session/cancel', { request: { sessionId: turn.sessionId } }).catch(e => { if (turn.parentOpen) throw e; }); + // Nothing is running in the parent (it was waiting for its helpers): the run ends once they are all down. + if (!turn.parentOpen) { clearTimeout(turn.settleTimer); turn.settleTimer = after(300, () => { if (!turn.finished && !turn.parentOpen && [...turn.children.values()].every(h => h.done)) turn.finish(null); }); } + let timer; const result = await Promise.race([turn.ended.promise, new Promise(r => { timer = after(waitMs, () => r(null)); })]); + clearTimeout(timer); + if (!result) return { stopped: false, pending: true, reason: 'the turn is still stopping' }; + return { stopped: true, ended: result.reason?.kind ?? 'unknown', ms: Date.now() - t0 }; + } + + function pendingFor(chatId) { + const sessionId = sessionMap[chatId]?.sessionId; + const helpers = chats.get(chatId)?.turn?.children; + return [...pending.values()].filter(p => p.sessionId === sessionId || helpers?.has(p.sessionId)) + .map(p => (p.sessionId === sessionId ? p : { ...p, callId: `${p.sessionId}:${p.callId}` })).map(({ callId, tool, reason, at }) => ({ callId, tool, reason, at })); + } + + /** Every chat that has an approval waiting, for the task board: the chat, its working folder and what is waiting (same items as pendingFor). */ + function pendingAll() { + if (!pending.size) return []; + return Object.keys(sessionMap).map(chatId => ({ chatId, folder: sessionMap[chatId]?.cwd ?? null, pending: pendingFor(chatId) })).filter(c => c.pending.length); + } + + async function close() { + const r = rt; rt = null; + if (r) { r.events?.close(); r.gw.close(); await r.hp.stop(); } + } + + /** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */ + function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); } + + return { compactCommand, messageHelper, answerQuestion, goalState, goalControl, harnessDir, status, runTurn, goalCommand, planCommand, researchCommand, llmTarget, setPlanBriefing, resetSession, reopenPlan, skipStep, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, pendingAll, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, workingFolder: chatId => sessionMap[chatId]?.cwd ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) }; +} + +/** A goal that stopped by itself, in words. */ +export function plainBlocker(reason) { + if (!reason) return 'it could not go on.'; + if (reason.code === 'round-limit') return 'it worked for the most steps it was allowed. Type /goal clear, then start a new goal to go on.'; + return String(reason.message ?? 'it could not go on.'); +} + +/** What a goal run says when it ends. */ +export function goalEnding(view) { + if (view.phase === 'complete') return '\n\n*The goal is complete.*'; + if (view.phase === 'blocked') return `\n\n*The goal stopped: ${plainBlocker(view.blockedReason)}*`; + if (view.phase === 'paused') return '\n\n*The goal is paused. Type /goal resume to go on.*'; + return ''; +} + +/** A goal request the Harness refused, as a sentence. */ +export function plainGoalError(e) { + const message = String(e?.message ?? e); + if (/already|unfinished|current goal/i.test(message)) return 'This chat already has a goal that is not finished. Type /goal edit to change it, /goal clear to remove it, or /goal to see it.'; + if (/GOAL_NONE|no goal/i.test(message) || e?.code === 'goal-none') return 'There is no goal to continue. Start one with /goal followed by what you want done.'; + if (/objective/i.test(message)) return 'A goal needs a few words about what you want done, for example: /goal make every test pass.'; + return 'The goal could not be changed right now. Try again in a moment.'; +} + +/** The Harness session of a chat that existed before the agent did knows nothing; carry a bounded summary. */ +export function withEarlierConversation(history, message) { + const rows = history.filter(m => (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim()).slice(-12); + if (!rows.length) return message; + const text = rows.map(m => `${m.role}: ${m.content.length > 1500 ? `${m.content.slice(0, 1499)}…` : m.content}`).join('\n'); + return `Earlier in this conversation, before you were given tools:\n${text}\n\nCurrent message:\n${message}`; +} diff --git a/apps/host/server/agent/events.mjs b/apps/host/server/agent/events.mjs index ec7705d250..509b43118e 100644 --- a/apps/host/server/agent/events.mjs +++ b/apps/host/server/agent/events.mjs @@ -1,496 +1,496 @@ -/** - * Pure projections from Harness facts to the frames the chat UI already renders. - * - * No I/O here, so the mapping can be tested without an agent. The inputs are the two things a - * `session/follow` stream carries: durable session events (`tool/call`, `approval/asked`, - * `tool/result`, `turn/end`, ...) and the process-local `assistant-stream` frames (text and - * reasoning deltas, usage). - */ - -import { toolUpdate, TokenCount, fmtTokens } from './status.mjs'; -import { askFor } from './ask.mjs'; -import { FIT_TEXT, fill } from './context-fit.mjs'; -import { isContextOverflow } from './context-budget.mjs'; -import { ToolDraft, cutCalls } from './reply-cut.mjs'; - -const SHELL = new Set(['pwsh', 'bash', 'job_kill', 'job_output', 'job_list']); -const WRITE = new Set(['write', 'edit']); -const READ = new Set(['read', 'glob', 'grep', 'read_image', 'working_directory', 'todo_write', 'get_goal', 'list_agents', 'skill', 'present']); - -/** Delegation tools have no card: the helper agents show as rows, and the tool's raw reply ("started subagent <id>") is not for the person. */ -export const NO_CARD = new Set(['subagent', 'subagent_fork', 'send_message', 'interrupt_agent', 'list_agents']); - -export function toolScope(name) { - if (SHELL.has(name)) return 'shell'; - if (WRITE.has(name)) return 'write'; - if (READ.has(name)) return 'read'; - return 'connected'; -} - -/** Shown on a card the mode refused (Plan, Bypass): the model's own error text would say "the user rejected". */ -export const NOT_IN_MODE = 'Not allowed in this mode. Nothing ran.'; - -const clip = (value, max) => { - const text = String(value ?? ''); - return text.length > max ? `${text.slice(0, max - 1)}…` : text; -}; - -export function parseArguments(raw) { - if (raw && typeof raw === 'object') return raw; - try { const v = JSON.parse(String(raw ?? '{}')); return v && typeof v === 'object' ? v : {}; } catch { return {}; } -} - -/** - * One plain sentence and one short detail per tool, so a card never shows raw JSON or an internal tool name as its - * explanation. Unknown tools (a connected MCP server's) fall back to a generic sentence with their arguments. - */ -const WORDS = { - read: a => ['Reads a file.', a.file_path ?? a.path], - glob: a => ['Looks for files by name.', a.pattern], - grep: a => ['Searches inside files.', a.pattern ?? a.query], - read_image: a => ['Looks at a picture.', a.file_path ?? a.path], - working_directory: () => ['Checks which folder it is working in.', ''], - todo_write: a => ['Updates its to-do list.', Array.isArray(a.todos) ? a.todos.map(t => t?.content ?? t?.title ?? '').filter(Boolean).join('; ') : ''], - skill: a => ['Uses a saved skill.', a.name ?? a.skill], - present: a => ['Shows you a result.', a.file_path ?? a.path ?? a.title], - create_goal: a => ['Sets a goal to work towards.', a.objective], - update_goal: a => ['Updates the goal.', a.objective ?? a.status ?? ''], - get_goal: () => ['Checks the current goal.', ''], - web_fetch: a => ['Opens a web page.', a.url], - web_search: a => ['Searches the web.', Array.isArray(a.queries) ? a.queries.join('; ') : a.query], - workflow: a => ['Runs a multi-step plan.', a.description ?? a.name ?? ''], - job_list: () => ['Checks the background tasks.', ''], - job_output: a => ['Reads what a background task printed.', a.job_id ?? a.id], - job_kill: a => ['Stops a background task.', a.job_id ?? a.id], - lsp: a => ['Looks up how the code fits together.', a.file_path], -}; - -/** - * What a card says it is doing, in the person's words: [while it runs, when it worked, when it failed]. The UI translates - * these fixed sentences and writes the target (a file path, the command) beside them, so a row never shows `pwsh · Ran`. - */ -const VERBS = { - write: ['Writing a file', 'Wrote a file', "Couldn't write the file"], - edit: ['Changing a file', 'Changed a file', "Couldn't change the file"], - read: ['Reading a file', 'Read a file', "Couldn't read the file"], - read_image: ['Looking at a picture', 'Looked at a picture', "Couldn't look at the picture"], - glob: ['Searching for files', 'Searched for files', "Couldn't search for files"], - grep: ['Searching inside files', 'Searched inside files', "Couldn't search inside files"], - pwsh: ['Running a command', 'Ran a command', 'The command failed'], - bash: ['Running a command', 'Ran a command', 'The command failed'], - web_fetch: ['Opening a web page', 'Opened a web page', "Couldn't open the web page"], - web_search: ['Searching the web', 'Searched the web', "Couldn't search the web"], - create_goal: ['Setting the goal', 'Set the goal', "Couldn't set the goal"], - update_goal: ['Updating the goal', 'Updated the goal', "Couldn't update the goal"], - get_goal: ['Checking the goal', 'Checked the goal', "Couldn't check the goal"], - skill: ['Loading your skill', 'Loaded your skill', "Couldn't load the skill"], - todo_write: ['Updating its to-do list', 'Updated its to-do list', "Couldn't update its to-do list"], - present: ['Showing you a result', 'Showed you a result', "Couldn't show the result"], - working_directory: ['Checking the folder', 'Checked the folder', "Couldn't check the folder"], - job_list: ['Checking background tasks', 'Checked background tasks', "Couldn't check background tasks"], - job_output: ['Reading a background task', 'Read a background task', "Couldn't read the background task"], - job_kill: ['Stopping a background task', 'Stopped a background task', "Couldn't stop the background task"], -}; -const GENERIC_VERBS = ['Using a tool', 'Used a tool', 'The tool failed']; -/** The browser tool server's tools (Settings -> Tools): the card says what happened to the page, not the tool's internal name. */ -const BROWSER_VERBS = { - browser_navigate: ['Opening a page in the browser', 'Opened a page in the browser', "Couldn't open the page"], - browser_click: ['Clicking on the page', 'Clicked on the page', "Couldn't click on the page"], - browser_hover: ['Pointing at the page', 'Pointed at the page', "Couldn't point at the page"], - browser_type: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], - browser_fill_form: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], - browser_press_key: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], - browser_snapshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"], - browser_take_screenshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"], - browser_evaluate: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"], - browser_run_code: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"], - browser_wait_for: ['Waiting for the page', 'Waited for the page', "Couldn't wait for the page"], - browser_navigate_back: ['Going back a page', 'Went back a page', "Couldn't go back"], - browser_tabs: ['Managing browser tabs', 'Managed browser tabs', "Couldn't manage the browser tabs"], - browser_close: ['Closing the browser page', 'Closed the browser page', "Couldn't close the browser page"], -}; -const BROWSER_GENERIC = ['Using the browser', 'Used the browser', 'The browser step failed']; -const BROWSER_PREFIX = 'mcp__browser__', INSTRUCTIONS_PREFIX = 'mcp__strata-instructions__', COMMANDS_PREFIX = 'mcp__strata-commands__'; -/** The person's own tool's name as they wrote it (spaces for underscores). */ -const ownToolName = name => name.replace(/^mcp__strata-(?:instructions|commands)__/, '').replace(/_/g, ' '); -/** The three sentences (running, worked, failed) for a tool, and whether this is one the app knows by name. */ -function verbsFor(name) { - if (VERBS[name]) return { verbs: VERBS[name], known: true }; - if (name.startsWith(BROWSER_PREFIX)) return { verbs: BROWSER_VERBS[name.slice(BROWSER_PREFIX.length)] ?? BROWSER_GENERIC, known: true }; - if (name.startsWith(INSTRUCTIONS_PREFIX)) return { verbs: ['Reading your instructions', 'Read your instructions', "Couldn't read your instructions"], known: true }; - if (name.startsWith(COMMANDS_PREFIX)) return { verbs: ['Running your tool', 'Ran your tool', 'Your tool failed'], known: true }; - return { verbs: GENERIC_VERBS, known: false }; -} - -/** The sentence for a card in this state (the first for a running or waiting card). */ -export function toolVerb(name, state) { - const v = verbsFor(name).verbs; - return state === 'error' ? v[2] : state === 'done' ? v[1] : v[0]; -} -/** The ToolCall fields the card needs, from one Harness tool call. */ -export function presentTool({ callId, name, args, reason = null }) { - const scope = toolScope(name); - const words = WORDS[name]?.(args); - const preview = scope === 'shell' && !words ? args.command ?? '' - : scope === 'write' ? args.file_path ?? args.path ?? args.filePath ?? '' - : words ? words[1] ?? '' : name.startsWith(INSTRUCTIONS_PREFIX) || name.startsWith(COMMANDS_PREFIX) ? ownToolName(name) : /^mcp__browser__browser_(evaluate|run_code)$/.test(name) ? '' : args.file_path ?? args.path ?? args.pattern ?? args.url ?? args.element ?? args.query ?? args.text ?? args.action ?? (Object.keys(args).length ? JSON.stringify(args) : ''); - const effect = reason ?? (words ? words[0] : scope === 'shell' ? (args.description ?? 'Runs a command in the workspace.') - : scope === 'write' ? 'Changes a file in the workspace.' - : scope === 'read' ? 'Reads from the workspace.' : 'Uses a connected tool.'); - return { id: callId, name, args, preview: clip(preview, 600), effect: clip(effect, 400), scope, verb: toolVerb(name, 'running'), target: clip(verbsFor(name).known ? preview : name, 300), ask: askFor(name, args, typeof args.description === 'string' ? args.description : null) }; -} - -/** A tool's failure in plain words, or null when there is nothing better than the original text. */ -export function plainToolError(text) { - const t = String(text ?? ''); - if (/non-public ip|enotfound|getaddrinfo|web fetch failed|econnrefused|econnreset|etimedout|fetch failed/i.test(t)) return 'That web page could not be opened. Check the address and your internet connection.'; - if (/invalid arguments|missing required property|not a declared property/i.test(t)) return 'The assistant asked this tool in the wrong way. It will usually try again.'; - if (/unknown or no longer available/i.test(t)) return 'That skill is not available.'; - if (/cannot modify|must (?:first )?be read|has not been read|changed since/i.test(t)) return 'The file could not be changed. It may need to be read again first, or it changed in the meantime.'; - if (/sandbox|access denied|permission denied|eacces|eperm/i.test(t)) return 'The computer did not allow this.'; - if (/timed out|timeout/i.test(t)) return 'This took too long and was stopped.'; - if (/does not declare image input|image input/i.test(t)) return 'Picture reading is off for this model. Open Models and turn on Read pictures for it (load it again if it is a local model), or choose a model that reads pictures.'; - if (/extension|not a supported image|cannot read/i.test(t)) return 'This file could not be read.'; - return null; -} - -/** A failed tool's result: the plain sentence first, the original text after it (the card's disclosure is the Details). */ -export function withPlain(raw) { - const plain = plainToolError(raw); - return plain ? `${plain}\n\nDetails: ${raw.replace(/^Error:\s*/, '')}` : raw; -} - -/** What a launch that printed nothing proves, and no more. */ -export const LAUNCHED_TEXT = 'The command finished without an error, so the program was started. Strata cannot confirm that a window or page actually opened.'; - -/** A command whose whole point is to open something: it has no output to show when it worked. */ -const LAUNCH = /(^|[\s;|&(])(start-process|start|invoke-item|ii|explorer(?:\.exe)?|xdg-open|open|notepad(?:\.exe)?|code)(?=[\s;|&)]|$)/i; - -/** - * A command that succeeded and printed nothing says so in words (the card used to show "(no output)" under a "Ran" that could not - * tell the person whether anything happened). Opening a folder or a window is not something a command can prove it did, so the - * sentence says only what is known. - */ -export function outcomeText(tool, text, args = {}) { - if (tool === 'pwsh' || tool === 'bash') { - // In the read-only modes PowerShell runs in Constrained Language Mode and complains about the Harness's own output-encoding line: - // noise appended after a command that worked. It says nothing about the command, so it is not shown. - text = text.replace(/\r?\n?\[stderr\]\r?\n(?:Cannot create type\. Only core types are supported in this language mode\.[\s\S]*?CannotCreateTypeConstrainedLanguage\s*)+$/, ''); - if (!text.trim()) text = '(no output)'; - } - // Starting a program or opening a folder prints nothing when it worked, and also when it did not (a browser given a file:// address, a - // program that closed at once). T9 / #3576: the card used to say "was opened", and the model repeated it ("I previewed it in a browser to - // confirm it renders"). It says what is known: the command returned without an error. - if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim()) && LAUNCH.test(String(args?.command ?? ''))) return LAUNCHED_TEXT; - if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim())) return 'The command finished without any error. It printed nothing, so there is nothing more to show.'; - return text; -} - -/** Text of a tool-result message, bounded. */ -export function resultText(message) { - const parts = Array.isArray(message?.content) ? message.content : []; - const text = parts.map(p => (p?.type === 'text' ? p.text : p?.type ? `[${p.type}]` : '')).join('\n').trim(); - return clip(text || '(no output)', 4000); -} - -/** - * Accumulates one turn's frames. Feed it follow items; it returns the frames to send. - * It owns the per-turn state (tool cards, usage, text emitted) so the I/O layer stays thin. - */ -export class TurnProjector { - /** - * `policy` is the session's approval policy for this turn. Under `never` the Harness rejects an ask by itself, so - * no question ever reaches the person: the card goes straight from running to denied, without a moment where it - * offers Approve and Deny buttons that would do nothing. - */ - constructor({ startedAt = Date.now(), policy = 'ask', window = 0 } = {}) { - this.startedAt = startedAt; - this.window = Number(window) || 0; // the model's window, for the figures in the line that says the chat was summarised - this.summarizing = false; - this.policy = policy; - this.byPolicy = new Set(); // callIds the approval policy rejected without asking - this.tools = new Map(); // callId -> { card, calledAt } - this.tokensIn = 0; - this.tokensOut = 0; - this.contextTokens = null; // the LAST model request's prompt + reply: what the context holds now (the sums above count every request again) - this.usageSeen = false; - this.firstTokenAt = null; - this.streams = new Map(); // attemptId -> { first, last, chunks, chars }: the time a model request actually spent producing - this.lastStats = 0; - this.emittedText = new Map(); // attemptId -> chars sent live - this.ended = null; // the turn/end reason, once seen - this.denied = new Set(); // callIds a human or the policy rejected - this.asked = new Map(); // approval id -> callId - this.onStatus = null; // (update) => void: what the assistant is doing now (status.mjs); set by the bridge - this.reasoning = new TokenCount(); - this.composing = new Map(); // callId -> ToolDraft: a tool call the model is still writing (still here at a cut reply = it was lost) - this.lastOutput = 0; // tokens the LAST model request produced - this.running = []; // callIds of tools that are running, oldest first - } - - #status(update) { if (this.onStatus) this.onStatus(update); } - - /** After a tool ends: another tool still running is what is happening, otherwise the model is working out what to do next. */ - #afterTool() { - const id = this.running.at(-1); - const card = id ? this.tools.get(id)?.card : null; - if (card) this.#status(toolUpdate('tool', 'tool', card.name, card.args, {}, { args: { tool: card.name, verb: card.verb, target: card.target } })); - else this.#status({ phase: 'waiting', code: 'model-working', text: 'Working out the next step…' }); - } - - #card(callId, patch) { - const entry = this.tools.get(callId); - if (!entry) return null; - entry.card = { ...entry.card, ...patch }; - entry.card.verb = toolVerb(entry.card.name, entry.card.state); - return { type: 'agent-tool', tool: entry.card }; - } - - /* The speed shown while a reply streams, and after it: everything the model generated (reasoning and tool calls included) over the time its - requests spent producing it, not over the whole turn (tool runs and the wait for the prompt are not decoding). One stream per model - request; tokens are one per streamed chunk, or characters / 4 when a server batches. */ - #produced(attemptId, text, out) { - const now = Date.now(); - const s = this.streams.get(attemptId) ?? { first: now, last: now, chunks: 0, chars: 0 }; - s.last = now; s.chunks += 1; s.chars += text.length; - this.streams.set(attemptId, s); - if (now - this.lastStats < 400) return; - const { tokens, seconds } = this.decode(); - if (seconds < 0.5) return; - this.lastStats = now; - out.push({ type: 'stats', tokensOut: tokens, tps: Number((tokens / seconds).toFixed(1)), source: 'stream' }); - } - - decode() { - let tokens = 0, ms = 0; - for (const s of this.streams.values()) { tokens += s.chars / Math.max(1, s.chunks) < 8 ? s.chunks : Math.ceil(s.chars / 4); ms += s.last - s.first; } - return { tokens, seconds: ms / 1000 }; - } - - /** Process one `session/follow` item (event or assistant-stream). Returns frames. */ - consume(item) { - const out = []; - if (item.type === 'assistant-stream') { - const f = item.frame; - if (f.type === 'chunk') { - const c = f.chunk; - if (c.type === 'text-delta' && c.text) { - this.firstTokenAt ??= Date.now(); - this.#produced(f.attemptId, c.text, out); - this.emittedAny = true; - this.#status({ phase: 'answering', code: 'answering', text: 'Writing the answer…' }); - this.emittedText.set(f.attemptId, (this.emittedText.get(f.attemptId) ?? 0) + c.text.length); - out.push({ type: 'delta', text: c.text }); - } else if (c.type === 'reasoning-delta' && c.text) { - this.firstTokenAt ??= Date.now(); - this.#produced(f.attemptId, c.text, out); - // The count is for the model's current thinking (each model request starts again from zero), not the whole turn. - if (this.reasoningAttempt !== f.attemptId) { this.reasoning = new TokenCount(); this.reasoningAttempt = f.attemptId; } - this.reasoning.add(c.text); - this.#status({ phase: 'thinking', code: 'thinking', text: `Thinking… ${fmtTokens(this.reasoning.tokens)} tokens`, key: 'Thinking… {0} tokens', values: [fmtTokens(this.reasoning.tokens)], tokens: this.reasoning.tokens, args: { tokens: this.reasoning.tokens } }); - out.push({ type: 'reasoning', text: c.text }); - } else if (c.type === 'tool-call-delta' && c.id) { - // The model is writing a tool call. For a big file this is the long silent part: nothing else arrives until it is finished. - const call = this.composing.get(c.id) ?? new ToolDraft(c.id, c.name ?? ''); - if (c.name) call.name = c.name; - const piece = String(c.argumentsDelta ?? ''); - // Writing a tool call (a whole file, say) is decoding too: its tokens are in the engine's output count, so its time belongs in the speed. - this.#produced(f.attemptId, piece, out); - call.add(piece); - this.composing.set(c.id, call); - if (call.name && !NO_CARD.has(call.name)) { - const target = call.target; - const args = target ? { file_path: target, url: target } : {}; - this.#status(toolUpdate('preparing', 'preparing-tool', call.name, args, { bytes: call.bytes }, { args: { tool: call.name, verb: toolVerb(call.name, 'running'), target: target ?? '', bytes: call.bytes } })); - // The live data path of a file being written (AGENT-LOST): the name, a growing size and the tail of the text, at most five times a second. - const now = Date.now(); - if (now - call.at >= 200) { call.at = now; out.push(call.frame({ scope: toolScope(call.name), verb: toolVerb(call.name, 'running') })); } - } - } else if (c.type === 'usage' && c.usage) { - this.usageSeen = true; - // The Harness counts input, cache reads and cache writes apart (a prompt the server's conversation cache already held is `cacheReadTokens`, - // not `inputTokens`): the prompt of a request is all three. Counting only `inputTokens` made a long agent chat look nearly empty (0%). - const prompt = (Number(c.usage.inputTokens) || 0) + (Number(c.usage.cacheReadTokens) || 0) + (Number(c.usage.cacheWriteTokens) || 0); - this.tokensIn += prompt; - this.tokensOut += Number(c.usage.outputTokens) || 0; - this.lastOutput = Number(c.usage.outputTokens) || 0; - this.contextTokens = prompt + (Number(c.usage.outputTokens) || 0); - out.push({ type: 'context', contextTokens: this.contextTokens, contextMax: this.window || undefined }); - } - } - return out; - } - if (item.type !== 'event') return out; - const e = item.event; - const d = e.data ?? {}; - switch (e.type) { - case 'assistant/message': { - // Reconcile a text the live frames did not fully carry (a socket gap), never duplicating it. - const live = [...this.emittedText.values()].pop() ?? 0; - const text = (d.message?.content ?? []).filter(p => p.type === 'text').map(p => p.text).join(''); - if (text.length > live && live > 0) out.push({ type: 'delta', text: text.slice(live) }); - this.emittedText.clear(); - break; - } - case 'tool/call': { - if (NO_CARD.has(d.name)) break; - const args = parseArguments(d.arguments); - const card = { ...presentTool({ callId: d.callId, name: d.name, args }), state: 'running' }; - this.tools.set(d.callId, { card, calledAt: e.time }); - const draft = this.composing.get(d.callId); - this.composing.delete(d.callId); - if (draft && draft.bytes > 0 && !NO_CARD.has(d.name)) out.push(draft.frame({ done: true })); - this.running.push(d.callId); - this.#status(toolUpdate('tool', 'tool', d.name, args, {}, { args: { tool: d.name, verb: card.verb, target: card.target } })); - out.push({ type: 'agent-tool', tool: card }); - break; - } - case 'approval/asked': { - if (!d.callId) break; - this.asked.set(d.id, d.callId); - if (this.policy === 'never') break; - const entry = this.tools.get(d.callId); - this.#status({ phase: 'approval', code: 'waiting-approval', text: 'Waiting for your answer…', args: { tool: entry?.card.name ?? '' } }); - const patch = { state: 'proposed', effect: clip(d.reason ?? entry?.card.effect ?? 'Needs your approval.', 400) }; - const frame = this.#card(d.callId, patch); - if (frame) out.push(frame); - break; - } - case 'approval/decided': { - const callId = this.asked.get(d.id); - if (callId && this.policy === 'never' && d.outcome !== 'allowed-once') { - this.byPolicy.add(callId); this.denied.add(callId); - const frame = this.#card(callId, { state: 'denied', result: NOT_IN_MODE }); - if (frame) out.push(frame); - break; - } - this.#afterTool(); - const frame = callId ? this.decide(callId, d.outcome) : null; - if (frame) out.push(frame); - break; - } - case 'tool/result': { - const callId = d.message?.toolCallId; - const entry = this.tools.get(callId); - if (!entry) break; - this.running = this.running.filter(id => id !== callId); - this.#afterTool(); - const isError = d.message?.isError === true; - const denied = this.denied.has(callId); - const frame = this.#card(callId, { - state: denied ? 'denied' : isError ? 'error' : 'done', - // A card the person (or the mode) refused keeps its plain sentence; the model's own error text ("the user rejected ...") is not for them. - result: this.byPolicy.has(callId) ? NOT_IN_MODE : denied ? (entry.card.result ?? 'Denied. Nothing ran.') : isError ? withPlain(resultText(d.message)) : outcomeText(entry.card.name, resultText(d.message), entry.card.args), - durationMs: Math.max(0, (e.time ?? 0) - entry.calledAt), - }); - if (frame) out.push(frame); - break; - } - case 'compaction/start': - // The Harness is summarising the older messages to make room: say so while it does, and again (once) when it is done. - this.summarizing = true; - this.#status({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] }); - break; - case 'compaction/end': - if (!this.summarizing) break; - this.summarizing = false; - this.#afterTool(); - if (!d.error) { - const before = this.window > 0 && this.contextTokens ? Math.min(100, Math.round(100 * this.contextTokens / this.window)) : null; - const text = before === null ? FIT_TEXT.summarizedShort : FIT_TEXT.summarizedWas; - const values = before === null ? [] : [before]; - out.push({ type: 'delta', own: true, text: '\n\n' + fill(text, values), key: text, values, noteReason: 'compacted' }); - } - break; - case 'turn/start': - // The parent woke up again (a helper finished and reported back): the message goes on, as a new paragraph. - this.ended = null; - if (this.emittedAny) out.push({ type: 'delta', text: '\n\n' }); - break; - case 'turn/end': - this.ended = d.reason ?? { kind: 'completed' }; - break; - default: - break; - } - return out; - } - - /** An approval was decided. `outcome` is the Harness vocabulary. */ - decide(callId, outcome) { - if (!this.tools.has(callId)) return null; - // `approved` is what lets the card say "Approved" (the user answered) rather than "Ran" (it never asked). - if (outcome === 'allowed-once') return this.#card(callId, { state: 'running', approved: true }); - this.denied.add(callId); - return this.#card(callId, { state: 'denied', result: outcome === 'rejected' ? 'Denied. Nothing ran.' : outcome === 'cancelled' ? 'Cancelled. Nothing ran.' : 'No one could answer this request, so nothing ran.' }); - } - - /** A reply the model could not finish (the turn ended on the length limit): what it was writing, so nothing is lost without a word. */ - cut() { - return { tokens: this.lastOutput, calls: cutCalls(this.composing.values()) }; - } - - /** The agent was asked to carry on: the calls it lost are not pending any more. */ - clearCut() { const frames = this.#dropDrafts(); this.ended = null; return frames; } - - /** Frames that take the writing cards of calls that will never be whole off the page (the reply was cut, or the turn ended). */ - #dropDrafts() { - const frames = [...this.composing.values()].filter(d => d.bytes > 0 && !NO_CARD.has(d.name)).map(d => d.frame({ done: true, lost: true })); - this.composing.clear(); - return frames; - } - - /** The terminal frames for a finished turn. */ - finish(options = {}) { - const cutInfo = this.ended?.kind === 'max-tokens' ? this.cut() : null; - const dropped = this.#dropDrafts(); - return [...dropped, ...this.#finished(options, cutInfo)]; - } - - #finished({ model, contextMax, engine = null } = {}, cutInfo = null) { - const reason = this.ended ?? { kind: 'interrupted' }; - const durationMs = Date.now() - this.startedAt; - const usage = this.usageSeen - ? { tokensIn: this.tokensIn, tokensOut: this.tokensOut, usageSource: 'reported' } - : { tokensIn: null, tokensOut: null, usageSource: 'unavailable' }; - const decoded = this.decode(); - const generated = this.usageSeen && this.tokensOut > 0 ? this.tokensOut : decoded.tokens; - // Answer speed, one definition everywhere: all the tokens the model produced over its decode time. The engine's own figures (the ones the - // Monitor shows) when the bridge could read them; otherwise the stream's own span. A very short reply has almost no span, so its decode time - // is then the time from its first chunk to the end of the turn (only when no tool ran, so no tool time is in it): the number is still shown. - let tps = null; - if (engine?.tps > 0) tps = engine.tps; - else if (generated > 0 && decoded.seconds >= 0.3) tps = Number((generated / decoded.seconds).toFixed(1)); - else if (generated > 0 && this.tools.size === 0 && this.firstTokenAt && Date.now() - this.firstTokenAt >= 50) tps = Number((generated / ((Date.now() - this.firstTokenAt) / 1000)).toFixed(1)); - const promptTps = engine?.promptTps > 0 ? engine.promptTps : null; - const base = { durationMs, ttftMs: this.firstTokenAt ? this.firstTokenAt - this.startedAt : null, model, contextMax, tps, ...(promptTps ? { promptTps } : {}), contextTokens: this.contextTokens }; - switch (reason.kind) { - case 'completed': - return [{ type: 'done', ...base, ...usage, finishReason: 'stop' }]; - case 'max-tokens': - return [{ type: 'done', ...base, ...usage, finishReason: 'length', cut: cutInfo }]; - case 'aborted': - return [{ type: 'done', ...base, ...usage, finishReason: 'aborted', cancelled: true }]; - case 'error': - return [{ type: 'error', message: friendlyFailure(reason.error), code: isContextFailure(reason.error) ? 'CONTEXT_WINDOW_EXCEEDED' : reason.error?.code ?? 'UNKNOWN', ...(isContextFailure(reason.error) ? { key: FIT_TEXT.full, details: String(reason.error?.message ?? '') } : {}) }]; - case 'blocked': - return [{ type: 'error', message: 'The agent stopped because this turn was blocked by policy.', code: 'BLOCKED' }]; - default: - return [{ type: 'error', message: 'The agent turn was interrupted before it finished.', code: 'INTERRUPTED' }]; - } - } -} - -/** Whether a failure is the model server saying the conversation does not fit its window (its code, or the engine's own words). */ -export function isContextFailure(failure) { - return isContextOverflow(failure) || /context window|too long for|exceeds the context/i.test(String(failure?.message ?? '')); -} - -/** A model-route failure in words a user can act on. */ -export function friendlyFailure(failure) { - const message = String(failure?.message ?? 'The model request failed.'); - if (isContextFailure(failure)) return FIT_TEXT.full; - if (/ECONNREFUSED|fetch failed|connect/i.test(message)) return `The model is not reachable. ${clip(message, 200)}`; - if (/401|403|credential|api key/i.test(message)) return 'The model rejected the credentials. Check the connection in Settings.'; - return clip(message, 400); -} +/** + * Pure projections from Harness facts to the frames the chat UI already renders. + * + * No I/O here, so the mapping can be tested without an agent. The inputs are the two things a + * `session/follow` stream carries: durable session events (`tool/call`, `approval/asked`, + * `tool/result`, `turn/end`, ...) and the process-local `assistant-stream` frames (text and + * reasoning deltas, usage). + */ + +import { toolUpdate, TokenCount, fmtTokens } from './status.mjs'; +import { askFor } from './ask.mjs'; +import { FIT_TEXT, fill } from './context-fit.mjs'; +import { isContextOverflow } from './context-budget.mjs'; +import { ToolDraft, cutCalls } from './reply-cut.mjs'; + +const SHELL = new Set(['pwsh', 'bash', 'job_kill', 'job_output', 'job_list']); +const WRITE = new Set(['write', 'edit']); +const READ = new Set(['read', 'glob', 'grep', 'read_image', 'working_directory', 'todo_write', 'get_goal', 'list_agents', 'skill', 'present']); + +/** Delegation tools have no card: the helper agents show as rows, and the tool's raw reply ("started subagent <id>") is not for the person. */ +export const NO_CARD = new Set(['subagent', 'subagent_fork', 'send_message', 'interrupt_agent', 'list_agents']); + +export function toolScope(name) { + if (SHELL.has(name)) return 'shell'; + if (WRITE.has(name)) return 'write'; + if (READ.has(name)) return 'read'; + return 'connected'; +} + +/** Shown on a card the mode refused (Plan, Bypass): the model's own error text would say "the user rejected". */ +export const NOT_IN_MODE = 'Not allowed in this mode. Nothing ran.'; + +const clip = (value, max) => { + const text = String(value ?? ''); + return text.length > max ? `${text.slice(0, max - 1)}…` : text; +}; + +export function parseArguments(raw) { + if (raw && typeof raw === 'object') return raw; + try { const v = JSON.parse(String(raw ?? '{}')); return v && typeof v === 'object' ? v : {}; } catch { return {}; } +} + +/** + * One plain sentence and one short detail per tool, so a card never shows raw JSON or an internal tool name as its + * explanation. Unknown tools (a connected MCP server's) fall back to a generic sentence with their arguments. + */ +const WORDS = { + read: a => ['Reads a file.', a.file_path ?? a.path], + glob: a => ['Looks for files by name.', a.pattern], + grep: a => ['Searches inside files.', a.pattern ?? a.query], + read_image: a => ['Looks at a picture.', a.file_path ?? a.path], + working_directory: () => ['Checks which folder it is working in.', ''], + todo_write: a => ['Updates its to-do list.', Array.isArray(a.todos) ? a.todos.map(t => t?.content ?? t?.title ?? '').filter(Boolean).join('; ') : ''], + skill: a => ['Uses a saved skill.', a.name ?? a.skill], + present: a => ['Shows you a result.', a.file_path ?? a.path ?? a.title], + create_goal: a => ['Sets a goal to work towards.', a.objective], + update_goal: a => ['Updates the goal.', a.objective ?? a.status ?? ''], + get_goal: () => ['Checks the current goal.', ''], + web_fetch: a => ['Opens a web page.', a.url], + web_search: a => ['Searches the web.', Array.isArray(a.queries) ? a.queries.join('; ') : a.query], + workflow: a => ['Runs a multi-step plan.', a.description ?? a.name ?? ''], + job_list: () => ['Checks the background tasks.', ''], + job_output: a => ['Reads what a background task printed.', a.job_id ?? a.id], + job_kill: a => ['Stops a background task.', a.job_id ?? a.id], + lsp: a => ['Looks up how the code fits together.', a.file_path], +}; + +/** + * What a card says it is doing, in the person's words: [while it runs, when it worked, when it failed]. The UI translates + * these fixed sentences and writes the target (a file path, the command) beside them, so a row never shows `pwsh · Ran`. + */ +const VERBS = { + write: ['Writing a file', 'Wrote a file', "Couldn't write the file"], + edit: ['Changing a file', 'Changed a file', "Couldn't change the file"], + read: ['Reading a file', 'Read a file', "Couldn't read the file"], + read_image: ['Looking at a picture', 'Looked at a picture', "Couldn't look at the picture"], + glob: ['Searching for files', 'Searched for files', "Couldn't search for files"], + grep: ['Searching inside files', 'Searched inside files', "Couldn't search inside files"], + pwsh: ['Running a command', 'Ran a command', 'The command failed'], + bash: ['Running a command', 'Ran a command', 'The command failed'], + web_fetch: ['Opening a web page', 'Opened a web page', "Couldn't open the web page"], + web_search: ['Searching the web', 'Searched the web', "Couldn't search the web"], + create_goal: ['Setting the goal', 'Set the goal', "Couldn't set the goal"], + update_goal: ['Updating the goal', 'Updated the goal', "Couldn't update the goal"], + get_goal: ['Checking the goal', 'Checked the goal', "Couldn't check the goal"], + skill: ['Loading your skill', 'Loaded your skill', "Couldn't load the skill"], + todo_write: ['Updating its to-do list', 'Updated its to-do list', "Couldn't update its to-do list"], + present: ['Showing you a result', 'Showed you a result', "Couldn't show the result"], + working_directory: ['Checking the folder', 'Checked the folder', "Couldn't check the folder"], + job_list: ['Checking background tasks', 'Checked background tasks', "Couldn't check background tasks"], + job_output: ['Reading a background task', 'Read a background task', "Couldn't read the background task"], + job_kill: ['Stopping a background task', 'Stopped a background task', "Couldn't stop the background task"], +}; +const GENERIC_VERBS = ['Using a tool', 'Used a tool', 'The tool failed']; +/** The browser tool server's tools (Settings -> Tools): the card says what happened to the page, not the tool's internal name. */ +const BROWSER_VERBS = { + browser_navigate: ['Opening a page in the browser', 'Opened a page in the browser', "Couldn't open the page"], + browser_click: ['Clicking on the page', 'Clicked on the page', "Couldn't click on the page"], + browser_hover: ['Pointing at the page', 'Pointed at the page', "Couldn't point at the page"], + browser_type: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], + browser_fill_form: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], + browser_press_key: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"], + browser_snapshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"], + browser_take_screenshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"], + browser_evaluate: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"], + browser_run_code: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"], + browser_wait_for: ['Waiting for the page', 'Waited for the page', "Couldn't wait for the page"], + browser_navigate_back: ['Going back a page', 'Went back a page', "Couldn't go back"], + browser_tabs: ['Managing browser tabs', 'Managed browser tabs', "Couldn't manage the browser tabs"], + browser_close: ['Closing the browser page', 'Closed the browser page', "Couldn't close the browser page"], +}; +const BROWSER_GENERIC = ['Using the browser', 'Used the browser', 'The browser step failed']; +const BROWSER_PREFIX = 'mcp__browser__', INSTRUCTIONS_PREFIX = 'mcp__strata-instructions__', COMMANDS_PREFIX = 'mcp__strata-commands__'; +/** The person's own tool's name as they wrote it (spaces for underscores). */ +const ownToolName = name => name.replace(/^mcp__strata-(?:instructions|commands)__/, '').replace(/_/g, ' '); +/** The three sentences (running, worked, failed) for a tool, and whether this is one the app knows by name. */ +function verbsFor(name) { + if (VERBS[name]) return { verbs: VERBS[name], known: true }; + if (name.startsWith(BROWSER_PREFIX)) return { verbs: BROWSER_VERBS[name.slice(BROWSER_PREFIX.length)] ?? BROWSER_GENERIC, known: true }; + if (name.startsWith(INSTRUCTIONS_PREFIX)) return { verbs: ['Reading your instructions', 'Read your instructions', "Couldn't read your instructions"], known: true }; + if (name.startsWith(COMMANDS_PREFIX)) return { verbs: ['Running your tool', 'Ran your tool', 'Your tool failed'], known: true }; + return { verbs: GENERIC_VERBS, known: false }; +} + +/** The sentence for a card in this state (the first for a running or waiting card). */ +export function toolVerb(name, state) { + const v = verbsFor(name).verbs; + return state === 'error' ? v[2] : state === 'done' ? v[1] : v[0]; +} +/** The ToolCall fields the card needs, from one Harness tool call. */ +export function presentTool({ callId, name, args, reason = null }) { + const scope = toolScope(name); + const words = WORDS[name]?.(args); + const preview = scope === 'shell' && !words ? args.command ?? '' + : scope === 'write' ? args.file_path ?? args.path ?? args.filePath ?? '' + : words ? words[1] ?? '' : name.startsWith(INSTRUCTIONS_PREFIX) || name.startsWith(COMMANDS_PREFIX) ? ownToolName(name) : /^mcp__browser__browser_(evaluate|run_code)$/.test(name) ? '' : args.file_path ?? args.path ?? args.pattern ?? args.url ?? args.element ?? args.query ?? args.text ?? args.action ?? (Object.keys(args).length ? JSON.stringify(args) : ''); + const effect = reason ?? (words ? words[0] : scope === 'shell' ? (args.description ?? 'Runs a command in the workspace.') + : scope === 'write' ? 'Changes a file in the workspace.' + : scope === 'read' ? 'Reads from the workspace.' : 'Uses a connected tool.'); + return { id: callId, name, args, preview: clip(preview, 600), effect: clip(effect, 400), scope, verb: toolVerb(name, 'running'), target: clip(verbsFor(name).known ? preview : name, 300), ask: askFor(name, args, typeof args.description === 'string' ? args.description : null) }; +} + +/** A tool's failure in plain words, or null when there is nothing better than the original text. */ +export function plainToolError(text) { + const t = String(text ?? ''); + if (/non-public ip|enotfound|getaddrinfo|web fetch failed|econnrefused|econnreset|etimedout|fetch failed/i.test(t)) return 'That web page could not be opened. Check the address and your internet connection.'; + if (/invalid arguments|missing required property|not a declared property/i.test(t)) return 'The assistant asked this tool in the wrong way. It will usually try again.'; + if (/unknown or no longer available/i.test(t)) return 'That skill is not available.'; + if (/cannot modify|must (?:first )?be read|has not been read|changed since/i.test(t)) return 'The file could not be changed. It may need to be read again first, or it changed in the meantime.'; + if (/sandbox|access denied|permission denied|eacces|eperm/i.test(t)) return 'The computer did not allow this.'; + if (/timed out|timeout/i.test(t)) return 'This took too long and was stopped.'; + if (/does not declare image input|image input/i.test(t)) return 'Picture reading is off for this model. Open Models and turn on Read pictures for it (load it again if it is a local model), or choose a model that reads pictures.'; + if (/extension|not a supported image|cannot read/i.test(t)) return 'This file could not be read.'; + return null; +} + +/** A failed tool's result: the plain sentence first, the original text after it (the card's disclosure is the Details). */ +export function withPlain(raw) { + const plain = plainToolError(raw); + return plain ? `${plain}\n\nDetails: ${raw.replace(/^Error:\s*/, '')}` : raw; +} + +/** What a launch that printed nothing proves, and no more. */ +export const LAUNCHED_TEXT = 'The command finished without an error, so the program was started. Strata cannot confirm that a window or page actually opened.'; + +/** A command whose whole point is to open something: it has no output to show when it worked. */ +const LAUNCH = /(^|[\s;|&(])(start-process|start|invoke-item|ii|explorer(?:\.exe)?|xdg-open|open|notepad(?:\.exe)?|code)(?=[\s;|&)]|$)/i; + +/** + * A command that succeeded and printed nothing says so in words (the card used to show "(no output)" under a "Ran" that could not + * tell the person whether anything happened). Opening a folder or a window is not something a command can prove it did, so the + * sentence says only what is known. + */ +export function outcomeText(tool, text, args = {}) { + if (tool === 'pwsh' || tool === 'bash') { + // In the read-only modes PowerShell runs in Constrained Language Mode and complains about the Harness's own output-encoding line: + // noise appended after a command that worked. It says nothing about the command, so it is not shown. + text = text.replace(/\r?\n?\[stderr\]\r?\n(?:Cannot create type\. Only core types are supported in this language mode\.[\s\S]*?CannotCreateTypeConstrainedLanguage\s*)+$/, ''); + if (!text.trim()) text = '(no output)'; + } + // Starting a program or opening a folder prints nothing when it worked, and also when it did not (a browser given a file:// address, a + // program that closed at once). T9 / #3576: the card used to say "was opened", and the model repeated it ("I previewed it in a browser to + // confirm it renders"). It says what is known: the command returned without an error. + if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim()) && LAUNCH.test(String(args?.command ?? ''))) return LAUNCHED_TEXT; + if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim())) return 'The command finished without any error. It printed nothing, so there is nothing more to show.'; + return text; +} + +/** Text of a tool-result message, bounded. */ +export function resultText(message) { + const parts = Array.isArray(message?.content) ? message.content : []; + const text = parts.map(p => (p?.type === 'text' ? p.text : p?.type ? `[${p.type}]` : '')).join('\n').trim(); + return clip(text || '(no output)', 4000); +} + +/** + * Accumulates one turn's frames. Feed it follow items; it returns the frames to send. + * It owns the per-turn state (tool cards, usage, text emitted) so the I/O layer stays thin. + */ +export class TurnProjector { + /** + * `policy` is the session's approval policy for this turn. Under `never` the Harness rejects an ask by itself, so + * no question ever reaches the person: the card goes straight from running to denied, without a moment where it + * offers Approve and Deny buttons that would do nothing. + */ + constructor({ startedAt = Date.now(), policy = 'ask', window = 0 } = {}) { + this.startedAt = startedAt; + this.window = Number(window) || 0; // the model's window, for the figures in the line that says the chat was summarised + this.summarizing = false; + this.policy = policy; + this.byPolicy = new Set(); // callIds the approval policy rejected without asking + this.tools = new Map(); // callId -> { card, calledAt } + this.tokensIn = 0; + this.tokensOut = 0; + this.contextTokens = null; // the LAST model request's prompt + reply: what the context holds now (the sums above count every request again) + this.usageSeen = false; + this.firstTokenAt = null; + this.streams = new Map(); // attemptId -> { first, last, chunks, chars }: the time a model request actually spent producing + this.lastStats = 0; + this.emittedText = new Map(); // attemptId -> chars sent live + this.ended = null; // the turn/end reason, once seen + this.denied = new Set(); // callIds a human or the policy rejected + this.asked = new Map(); // approval id -> callId + this.onStatus = null; // (update) => void: what the assistant is doing now (status.mjs); set by the bridge + this.reasoning = new TokenCount(); + this.composing = new Map(); // callId -> ToolDraft: a tool call the model is still writing (still here at a cut reply = it was lost) + this.lastOutput = 0; // tokens the LAST model request produced + this.running = []; // callIds of tools that are running, oldest first + } + + #status(update) { if (this.onStatus) this.onStatus(update); } + + /** After a tool ends: another tool still running is what is happening, otherwise the model is working out what to do next. */ + #afterTool() { + const id = this.running.at(-1); + const card = id ? this.tools.get(id)?.card : null; + if (card) this.#status(toolUpdate('tool', 'tool', card.name, card.args, {}, { args: { tool: card.name, verb: card.verb, target: card.target } })); + else this.#status({ phase: 'waiting', code: 'model-working', text: 'Working out the next step…' }); + } + + #card(callId, patch) { + const entry = this.tools.get(callId); + if (!entry) return null; + entry.card = { ...entry.card, ...patch }; + entry.card.verb = toolVerb(entry.card.name, entry.card.state); + return { type: 'agent-tool', tool: entry.card }; + } + + /* The speed shown while a reply streams, and after it: everything the model generated (reasoning and tool calls included) over the time its + requests spent producing it, not over the whole turn (tool runs and the wait for the prompt are not decoding). One stream per model + request; tokens are one per streamed chunk, or characters / 4 when a server batches. */ + #produced(attemptId, text, out) { + const now = Date.now(); + const s = this.streams.get(attemptId) ?? { first: now, last: now, chunks: 0, chars: 0 }; + s.last = now; s.chunks += 1; s.chars += text.length; + this.streams.set(attemptId, s); + if (now - this.lastStats < 400) return; + const { tokens, seconds } = this.decode(); + if (seconds < 0.5) return; + this.lastStats = now; + out.push({ type: 'stats', tokensOut: tokens, tps: Number((tokens / seconds).toFixed(1)), source: 'stream' }); + } + + decode() { + let tokens = 0, ms = 0; + for (const s of this.streams.values()) { tokens += s.chars / Math.max(1, s.chunks) < 8 ? s.chunks : Math.ceil(s.chars / 4); ms += s.last - s.first; } + return { tokens, seconds: ms / 1000 }; + } + + /** Process one `session/follow` item (event or assistant-stream). Returns frames. */ + consume(item) { + const out = []; + if (item.type === 'assistant-stream') { + const f = item.frame; + if (f.type === 'chunk') { + const c = f.chunk; + if (c.type === 'text-delta' && c.text) { + this.firstTokenAt ??= Date.now(); + this.#produced(f.attemptId, c.text, out); + this.emittedAny = true; + this.#status({ phase: 'answering', code: 'answering', text: 'Writing the answer…' }); + this.emittedText.set(f.attemptId, (this.emittedText.get(f.attemptId) ?? 0) + c.text.length); + out.push({ type: 'delta', text: c.text }); + } else if (c.type === 'reasoning-delta' && c.text) { + this.firstTokenAt ??= Date.now(); + this.#produced(f.attemptId, c.text, out); + // The count is for the model's current thinking (each model request starts again from zero), not the whole turn. + if (this.reasoningAttempt !== f.attemptId) { this.reasoning = new TokenCount(); this.reasoningAttempt = f.attemptId; } + this.reasoning.add(c.text); + this.#status({ phase: 'thinking', code: 'thinking', text: `Thinking… ${fmtTokens(this.reasoning.tokens)} tokens`, key: 'Thinking… {0} tokens', values: [fmtTokens(this.reasoning.tokens)], tokens: this.reasoning.tokens, args: { tokens: this.reasoning.tokens } }); + out.push({ type: 'reasoning', text: c.text }); + } else if (c.type === 'tool-call-delta' && c.id) { + // The model is writing a tool call. For a big file this is the long silent part: nothing else arrives until it is finished. + const call = this.composing.get(c.id) ?? new ToolDraft(c.id, c.name ?? ''); + if (c.name) call.name = c.name; + const piece = String(c.argumentsDelta ?? ''); + // Writing a tool call (a whole file, say) is decoding too: its tokens are in the engine's output count, so its time belongs in the speed. + this.#produced(f.attemptId, piece, out); + call.add(piece); + this.composing.set(c.id, call); + if (call.name && !NO_CARD.has(call.name)) { + const target = call.target; + const args = target ? { file_path: target, url: target } : {}; + this.#status(toolUpdate('preparing', 'preparing-tool', call.name, args, { bytes: call.bytes }, { args: { tool: call.name, verb: toolVerb(call.name, 'running'), target: target ?? '', bytes: call.bytes } })); + // The live data path of a file being written (AGENT-LOST): the name, a growing size and the tail of the text, at most five times a second. + const now = Date.now(); + if (now - call.at >= 200) { call.at = now; out.push(call.frame({ scope: toolScope(call.name), verb: toolVerb(call.name, 'running') })); } + } + } else if (c.type === 'usage' && c.usage) { + this.usageSeen = true; + // The Harness counts input, cache reads and cache writes apart (a prompt the server's conversation cache already held is `cacheReadTokens`, + // not `inputTokens`): the prompt of a request is all three. Counting only `inputTokens` made a long agent chat look nearly empty (0%). + const prompt = (Number(c.usage.inputTokens) || 0) + (Number(c.usage.cacheReadTokens) || 0) + (Number(c.usage.cacheWriteTokens) || 0); + this.tokensIn += prompt; + this.tokensOut += Number(c.usage.outputTokens) || 0; + this.lastOutput = Number(c.usage.outputTokens) || 0; + this.contextTokens = prompt + (Number(c.usage.outputTokens) || 0); + out.push({ type: 'context', contextTokens: this.contextTokens, contextMax: this.window || undefined }); + } + } + return out; + } + if (item.type !== 'event') return out; + const e = item.event; + const d = e.data ?? {}; + switch (e.type) { + case 'assistant/message': { + // Reconcile a text the live frames did not fully carry (a socket gap), never duplicating it. + const live = [...this.emittedText.values()].pop() ?? 0; + const text = (d.message?.content ?? []).filter(p => p.type === 'text').map(p => p.text).join(''); + if (text.length > live && live > 0) out.push({ type: 'delta', text: text.slice(live) }); + this.emittedText.clear(); + break; + } + case 'tool/call': { + if (NO_CARD.has(d.name)) break; + const args = parseArguments(d.arguments); + const card = { ...presentTool({ callId: d.callId, name: d.name, args }), state: 'running' }; + this.tools.set(d.callId, { card, calledAt: e.time }); + const draft = this.composing.get(d.callId); + this.composing.delete(d.callId); + if (draft && draft.bytes > 0 && !NO_CARD.has(d.name)) out.push(draft.frame({ done: true })); + this.running.push(d.callId); + this.#status(toolUpdate('tool', 'tool', d.name, args, {}, { args: { tool: d.name, verb: card.verb, target: card.target } })); + out.push({ type: 'agent-tool', tool: card }); + break; + } + case 'approval/asked': { + if (!d.callId) break; + this.asked.set(d.id, d.callId); + if (this.policy === 'never') break; + const entry = this.tools.get(d.callId); + this.#status({ phase: 'approval', code: 'waiting-approval', text: 'Waiting for your answer…', args: { tool: entry?.card.name ?? '' } }); + const patch = { state: 'proposed', effect: clip(d.reason ?? entry?.card.effect ?? 'Needs your approval.', 400) }; + const frame = this.#card(d.callId, patch); + if (frame) out.push(frame); + break; + } + case 'approval/decided': { + const callId = this.asked.get(d.id); + if (callId && this.policy === 'never' && d.outcome !== 'allowed-once') { + this.byPolicy.add(callId); this.denied.add(callId); + const frame = this.#card(callId, { state: 'denied', result: NOT_IN_MODE }); + if (frame) out.push(frame); + break; + } + this.#afterTool(); + const frame = callId ? this.decide(callId, d.outcome) : null; + if (frame) out.push(frame); + break; + } + case 'tool/result': { + const callId = d.message?.toolCallId; + const entry = this.tools.get(callId); + if (!entry) break; + this.running = this.running.filter(id => id !== callId); + this.#afterTool(); + const isError = d.message?.isError === true; + const denied = this.denied.has(callId); + const frame = this.#card(callId, { + state: denied ? 'denied' : isError ? 'error' : 'done', + // A card the person (or the mode) refused keeps its plain sentence; the model's own error text ("the user rejected ...") is not for them. + result: this.byPolicy.has(callId) ? NOT_IN_MODE : denied ? (entry.card.result ?? 'Denied. Nothing ran.') : isError ? withPlain(resultText(d.message)) : outcomeText(entry.card.name, resultText(d.message), entry.card.args), + durationMs: Math.max(0, (e.time ?? 0) - entry.calledAt), + }); + if (frame) out.push(frame); + break; + } + case 'compaction/start': + // The Harness is summarising the older messages to make room: say so while it does, and again (once) when it is done. + this.summarizing = true; + this.#status({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] }); + break; + case 'compaction/end': + if (!this.summarizing) break; + this.summarizing = false; + this.#afterTool(); + if (!d.error) { + const before = this.window > 0 && this.contextTokens ? Math.min(100, Math.round(100 * this.contextTokens / this.window)) : null; + const text = before === null ? FIT_TEXT.summarizedShort : FIT_TEXT.summarizedWas; + const values = before === null ? [] : [before]; + out.push({ type: 'delta', own: true, text: '\n\n' + fill(text, values), key: text, values, noteReason: 'compacted' }); + } + break; + case 'turn/start': + // The parent woke up again (a helper finished and reported back): the message goes on, as a new paragraph. + this.ended = null; + if (this.emittedAny) out.push({ type: 'delta', text: '\n\n' }); + break; + case 'turn/end': + this.ended = d.reason ?? { kind: 'completed' }; + break; + default: + break; + } + return out; + } + + /** An approval was decided. `outcome` is the Harness vocabulary. */ + decide(callId, outcome) { + if (!this.tools.has(callId)) return null; + // `approved` is what lets the card say "Approved" (the user answered) rather than "Ran" (it never asked). + if (outcome === 'allowed-once') return this.#card(callId, { state: 'running', approved: true }); + this.denied.add(callId); + return this.#card(callId, { state: 'denied', result: outcome === 'rejected' ? 'Denied. Nothing ran.' : outcome === 'cancelled' ? 'Cancelled. Nothing ran.' : 'No one could answer this request, so nothing ran.' }); + } + + /** A reply the model could not finish (the turn ended on the length limit): what it was writing, so nothing is lost without a word. */ + cut() { + return { tokens: this.lastOutput, calls: cutCalls(this.composing.values()) }; + } + + /** The agent was asked to carry on: the calls it lost are not pending any more. */ + clearCut() { const frames = this.#dropDrafts(); this.ended = null; return frames; } + + /** Frames that take the writing cards of calls that will never be whole off the page (the reply was cut, or the turn ended). */ + #dropDrafts() { + const frames = [...this.composing.values()].filter(d => d.bytes > 0 && !NO_CARD.has(d.name)).map(d => d.frame({ done: true, lost: true })); + this.composing.clear(); + return frames; + } + + /** The terminal frames for a finished turn. */ + finish(options = {}) { + const cutInfo = this.ended?.kind === 'max-tokens' ? this.cut() : null; + const dropped = this.#dropDrafts(); + return [...dropped, ...this.#finished(options, cutInfo)]; + } + + #finished({ model, contextMax, engine = null } = {}, cutInfo = null) { + const reason = this.ended ?? { kind: 'interrupted' }; + const durationMs = Date.now() - this.startedAt; + const usage = this.usageSeen + ? { tokensIn: this.tokensIn, tokensOut: this.tokensOut, usageSource: 'reported' } + : { tokensIn: null, tokensOut: null, usageSource: 'unavailable' }; + const decoded = this.decode(); + const generated = this.usageSeen && this.tokensOut > 0 ? this.tokensOut : decoded.tokens; + // Answer speed, one definition everywhere: all the tokens the model produced over its decode time. The engine's own figures (the ones the + // Monitor shows) when the bridge could read them; otherwise the stream's own span. A very short reply has almost no span, so its decode time + // is then the time from its first chunk to the end of the turn (only when no tool ran, so no tool time is in it): the number is still shown. + let tps = null; + if (engine?.tps > 0) tps = engine.tps; + else if (generated > 0 && decoded.seconds >= 0.3) tps = Number((generated / decoded.seconds).toFixed(1)); + else if (generated > 0 && this.tools.size === 0 && this.firstTokenAt && Date.now() - this.firstTokenAt >= 50) tps = Number((generated / ((Date.now() - this.firstTokenAt) / 1000)).toFixed(1)); + const promptTps = engine?.promptTps > 0 ? engine.promptTps : null; + const base = { durationMs, ttftMs: this.firstTokenAt ? this.firstTokenAt - this.startedAt : null, model, contextMax, tps, ...(promptTps ? { promptTps } : {}), contextTokens: this.contextTokens }; + switch (reason.kind) { + case 'completed': + return [{ type: 'done', ...base, ...usage, finishReason: 'stop' }]; + case 'max-tokens': + return [{ type: 'done', ...base, ...usage, finishReason: 'length', cut: cutInfo }]; + case 'aborted': + return [{ type: 'done', ...base, ...usage, finishReason: 'aborted', cancelled: true }]; + case 'error': + return [{ type: 'error', message: friendlyFailure(reason.error), code: isContextFailure(reason.error) ? 'CONTEXT_WINDOW_EXCEEDED' : reason.error?.code ?? 'UNKNOWN', ...(isContextFailure(reason.error) ? { key: FIT_TEXT.full, details: String(reason.error?.message ?? '') } : {}) }]; + case 'blocked': + return [{ type: 'error', message: 'The agent stopped because this turn was blocked by policy.', code: 'BLOCKED' }]; + default: + return [{ type: 'error', message: 'The agent turn was interrupted before it finished.', code: 'INTERRUPTED' }]; + } + } +} + +/** Whether a failure is the model server saying the conversation does not fit its window (its code, or the engine's own words). */ +export function isContextFailure(failure) { + return isContextOverflow(failure) || /context window|too long for|exceeds the context/i.test(String(failure?.message ?? '')); +} + +/** A model-route failure in words a user can act on. */ +export function friendlyFailure(failure) { + const message = String(failure?.message ?? 'The model request failed.'); + if (isContextFailure(failure)) return FIT_TEXT.full; + if (/ECONNREFUSED|fetch failed|connect/i.test(message)) return `The model is not reachable. ${clip(message, 200)}`; + if (/401|403|credential|api key/i.test(message)) return 'The model rejected the credentials. Check the connection in Settings.'; + return clip(message, 400); +} diff --git a/apps/host/server/agent/plugins/strata-context.mjs b/apps/host/server/agent/plugins/strata-context.mjs index a33f8d6b2d..c728e4adde 100644 --- a/apps/host/server/agent/plugins/strata-context.mjs +++ b/apps/host/server/agent/plugins/strata-context.mjs @@ -1,205 +1,205 @@ -/** - * Strata's context plugin for the Harness (plain ESM, loaded by absolute path from the profile, like strata-gate and strata-models). - * - * What it fixes (2026-10-22 hands-on test, Gyro-S at 64K): - * 1. Compaction decided from the Harness's own price of the conversation, 4 characters a token. Code, logs and JSON are about twice as - * dense, so a chat the engine had read as 59,048 tokens was priced at 31,794 and compaction started far too late. Here the token meter - * is calibrated by what the model server reports for each answer (its real prompt size): the measured size is exact, and what was - * added since is priced with the density that measurement showed. Automatic compaction and the manual /compact both measure through - * the token meter, so both read the same number as the context meter in the app. - * 2. The summarising request itself could be bigger than the window ("/compact" sent a 66,507-token prompt to a 65,536 window). The - * summary is now asked for in pieces that fit: a message bigger than a piece is cut for the request (the conversation keeps it until - * the summary replaces it), the pieces are summarised one after the other, each building on the summary before it, and a piece the - * server still refuses is halved and tried again. - * - * How. It wraps `tokenMeter.measure` and `llm.stream` in place, once each (the same way strata-models wraps the subagent tools). Only a - * request the Harness marks `purpose: 'compaction'` is touched in `llm.stream`. Nothing in the Harness is rewritten: a Harness update - * that renames either leaves compaction as it was, and the test that runs the real Harness fails. - */ -import { replyCap } from '../reply-cut.mjs'; -import { densityOf, estimateMessage, estimateTools, isContextOverflow, MAX_DENSITY, pressureNow, promptTokensOf, splitMessages, summaryBudget, usageOfEvent, WINDOW_SLACK, withSummaryLanguage } from '../context-budget.mjs'; - -export const name = 'strata-context'; - -/** The routes the host writes for models on this computer (profile.mjs): `strata-local`, `strata-local-<id>`, and their `~s<budget>` copies. */ -const isLocalRoute = provider => typeof provider === 'string' && provider.startsWith('strata-local'); -export const inject = ['tokenMeter', 'llm']; - -/** Real prompt measurements per session: { real, estimated } for the last answer the model server reported. */ -const samples = new WeakMap(); -const bySessionId = new Map(); -const wrapped = new WeakSet(); -/** Densities that made a summary request fail on this server, per session id (the next request starts from a more careful one). */ -const careful = new Map(); - -export function apply(ctx) { - const meter = ctx.tokenMeter; - const llm = ctx.llm; - const log = (level, text) => { try { ctx.logger?.[level]?.(`strata-context: ${text}`); } catch { /* logging never blocks */ } }; - - // 1. The measured size of the prompt, from the model server's own report for each answer. - if (meter && typeof meter.measure === 'function' && !wrapped.has(meter)) { - wrapped.add(meter); - const original = meter.measure; - meter.measure = function measure(session, requestHeader) { - const m = original.call(this, session, requestHeader); - const sample = samples.get(session); - if (!sample) return m; - const now = m.surfaceTokens + estimateTools(requestHeader ?? session.requestHeader?.()); - const total = Math.max(m.totalTokens, pressureNow({ sample, now })); - if (total <= m.totalTokens) return m; - const density = densityOf(sample.real, sample.estimated); - return { ...m, totalTokens: total, nodes: m.nodes.map(n => ({ ...n, tokens: Math.ceil(n.tokens * density) })) }; - }; - ctx.on('session/event', (session, event) => { - if (event.type !== 'assistant/message') return; - const real = promptTokensOf(usageOfEvent(event)); - if (!(real > 0)) return; - try { - // The request that was just answered saw the conversation without this answer: its price is the surface before the answer's node. - const m = original.call(meter, session); - const heuristic = m.nodes.reduce((n, x) => n + (x.seq === event.seq ? 0 : x.heuristicTokens), 0); - const estimated = heuristic + estimateTools(session.requestHeader?.()); - if (!(estimated > 0)) return; - const sample = { real, estimated }; - samples.set(session, sample); - if (session.id) bySessionId.set(String(session.id), sample); - } catch (e) { log('warn', `could not record a measurement: ${e.message}`); } - }); - } - - // 2. A summary request that fits the window. - if (llm && typeof llm.stream === 'function' && !wrapped.has(llm)) { - wrapped.add(llm); - const original = llm.stream; - llm.stream = function stream(options) { - if (options?.purpose !== 'compaction') return original.call(this, options); - return summaryStream.call(this, options, original); - }; - } - - // 3. A reply that has room to finish (AGENT-LOST, 11-01). The output budget in the profile is what the Harness's compaction sets aside for a - // reply (30 percent of the window; it reads it from the request header), and the same number was also the ceiling of every request: a thinking - // model that wrote a 15K-token file after 9K tokens of thinking was cut inside the tool call at 19,660, the unfinished call was dropped and the - // turn ended with no file and no word. The header (and so compaction) stays as it is; the request that goes to the model server may produce up - // to half the window, at most 64K tokens (replyCap), and pi-ai still clamps it to what the window has left after the prompt. The agent loop - // dispatches through the adapter's `streamWithSnapshot`, after the loop has checked the request against its header, so that is where the ceiling - // is raised, once per adapter, the first time a local route is prepared. A Harness that renames it leaves the ceiling as it was (the test that - // runs the real Harness fails). - if (llm && typeof llm.prepareCall === 'function' && !wrapped.has(llm.prepareCall)) { - const original = llm.prepareCall; - const raised = new WeakSet(); - const prepare = async function prepareCall(config, signal, configure) { - try { raiseReplyCeiling(config?.provider, raised); } catch (e) { log('warn', `could not raise the reply ceiling: ${e.message}`); } - return original.call(this, config, signal, configure); - }; - wrapped.add(prepare); - llm.prepareCall = prepare; - } - function raiseReplyCeiling(provider, raised) { - if (!isLocalRoute(provider)) return; - const adapter = llm.adapters?.get?.(provider)?.adapter; - if (!adapter || raised.has(adapter) || typeof adapter.streamWithSnapshot !== 'function' || typeof adapter.modelOf !== 'function') return; - raised.add(adapter); - const stream = adapter.streamWithSnapshot; - adapter.streamWithSnapshot = function streamWithSnapshot(options, snapshot) { - let next = options; - try { - if (isLocalRoute(options?.provider)) { - const model = this.modelOf(snapshot, options.provider, options.model); - const asked = options.maxTokens ?? model.maxTokens ?? 0; - // Only the agent's own reply budget is raised: a summary or a title asks for far less and keeps what it asked. - if (model.contextWindow > 0 && asked >= Math.floor(model.contextWindow * 0.25)) { - const cap = replyCap(model.contextWindow, asked); - if (cap > asked) next = { ...options, maxTokens: cap }; - } - } - } catch { next = options; } - return stream.call(this, next, snapshot); - }; - } - - // The host asks, with /strata-context, how much of the window the chat holds right now: the same measured number compaction decides on - // (JSON in the command's text: { tokens, window }). Before a message goes out, and after /compact, so the person is told true figures. - ctx.inject(['commands'], (commandCtx) => { - commandCtx.commands.register({ - definitionId: 'strata-context', - name: 'strata-context', - description: 'Reports how many tokens the conversation holds now and the size of the model window', - handler: async (invocation) => { - try { - const session = invocation.agent.session; - const tokens = meter.measure(session).totalTokens; - const config = session.requestHeader?.()?.config; - let window = 0; - if (config) window = (await llm.resolveModelInfo(config.provider, config.model))?.context?.contextWindow ?? 0; - return { kind: 'success', text: JSON.stringify({ tokens, window }) }; - } catch (e) { return { kind: 'error', text: `strata-context: ${e.message}` }; } - }, - }); - }); - - /** A finished stream: its chunks, the text it wrote and why it ended. */ - async function drain(iterable) { - let text = '', finish = null; - const chunks = []; - for await (const chunk of iterable) { - chunks.push(chunk); - if (chunk.type === 'text-delta') text += chunk.text ?? ''; - else if (chunk.type === 'finish') finish = chunk.reason; - } - return { text, finish, chunks }; - } - const refusedForSize = finish => finish?.kind === 'error' && isContextOverflow(finish.failure ?? finish); - - async function* summaryStream(options, original) { - options = { ...options, messages: withSummaryLanguage(options.messages) }; // #4750: the summary follows the conversation's language - let window = 0; - try { window = (await llm.resolveModelInfo(options.provider, options.model, options.signal))?.context?.contextWindow ?? 0; } catch { window = 0; } - const messages = options.messages ?? []; - const key = String(options.sessionId ?? ''); - const summaryTokens = options.maxTokens ?? 4096; - if (!(window > 0) || messages.length < 2) { yield* original.call(this, options); return; } - const own = bySessionId.get(key); - let density = Math.max(careful.get(key) ?? 1, own ? densityOf(own.real, own.estimated) : 1); - const price = list => list.reduce((n, m) => n + estimateMessage(m), 0) * density; - const limit = window - summaryTokens - WINDOW_SLACK; - // The whole request fits by this price: ask as the Harness would (the model server's cache of the conversation is reused). - if (price(messages) + estimateTools({ tools: options.tools }) * density <= limit) { - const first = await drain(original.call(this, options)); - if (!refusedForSize(first.finish)) { for (const chunk of first.chunks) yield chunk; return; } - density = Math.min(MAX_DENSITY, density * 1.6); - careful.set(key, density); - log('warn', 'the summary request did not fit the window; asking in pieces'); - } - // In pieces. The instruction is the last message; the system prompt, when there is one, the first. - const instruction = messages[messages.length - 1]; - const system = messages[0]?.role === 'system' ? messages[0] : null; - const body = messages.slice(system ? 1 : 0, -1); - let tools = options.tools; - if (tools && estimateTools({ tools }) * density > window / 3) tools = undefined; // a long tool list only describes tools: the summary does not need it - const fixed = (system ? estimateMessage(system) : 0) * density + estimateTools({ tools }) * density + estimateMessage(instruction) * density; - let budget = summaryBudget({ window, summaryTokens: summaryTokens * 2, systemTokens: fixed, instructionTokens: 0 }); - for (let attempt = 0; ; attempt++) { - const runs = splitMessages(body, Math.max(1024, budget), density); - log('info', `summarising ${body.length} messages in ${runs.length} piece(s) for a ${window}-token window (density ${density.toFixed(2)}, about ${Math.round(budget)} tokens a piece)`); - let failed = null, summary = ''; - for (let i = 0; i < runs.length && !failed; i++) { - options.signal?.throwIfAborted?.(); - const carried = summary ? [{ role: 'user', content: [{ type: 'text', text: `<compacted-summary>\n${summary}\n</compacted-summary>` }] }] : []; - const { tools: _drop, ...rest } = options; - const piece = { ...rest, ...(tools ? { tools } : {}), messages: [...(system ? [system] : []), ...carried, ...runs[i], instruction] }; - const { text, finish, chunks } = await drain(original.call(this, piece)); - if (refusedForSize(finish)) { failed = finish; break; } - // The last piece's answer is the summary the Harness reads; a piece that ended in another error ends the request the same way. - if (i === runs.length - 1 || finish?.kind === 'error' || finish?.kind === 'aborted') { for (const chunk of chunks) yield chunk; return; } - summary = text; - } - if (!failed || attempt >= 3) throw Object.assign(new Error(failed?.failure?.message ?? 'the summary request does not fit the window'), { code: 'CONTEXT_WINDOW_EXCEEDED' }); - density = Math.min(MAX_DENSITY, density * 1.6); - careful.set(key, density); - budget = Math.max(1024, budget / 2); - log('warn', `a piece did not fit; asking again with pieces of about ${Math.round(budget)} tokens`); - } - } -} +/** + * Strata's context plugin for the Harness (plain ESM, loaded by absolute path from the profile, like strata-gate and strata-models). + * + * What it fixes (2026-10-22 hands-on test, Gyro-S at 64K): + * 1. Compaction decided from the Harness's own price of the conversation, 4 characters a token. Code, logs and JSON are about twice as + * dense, so a chat the engine had read as 59,048 tokens was priced at 31,794 and compaction started far too late. Here the token meter + * is calibrated by what the model server reports for each answer (its real prompt size): the measured size is exact, and what was + * added since is priced with the density that measurement showed. Automatic compaction and the manual /compact both measure through + * the token meter, so both read the same number as the context meter in the app. + * 2. The summarising request itself could be bigger than the window ("/compact" sent a 66,507-token prompt to a 65,536 window). The + * summary is now asked for in pieces that fit: a message bigger than a piece is cut for the request (the conversation keeps it until + * the summary replaces it), the pieces are summarised one after the other, each building on the summary before it, and a piece the + * server still refuses is halved and tried again. + * + * How. It wraps `tokenMeter.measure` and `llm.stream` in place, once each (the same way strata-models wraps the subagent tools). Only a + * request the Harness marks `purpose: 'compaction'` is touched in `llm.stream`. Nothing in the Harness is rewritten: a Harness update + * that renames either leaves compaction as it was, and the test that runs the real Harness fails. + */ +import { replyCap } from '../reply-cut.mjs'; +import { densityOf, estimateMessage, estimateTools, isContextOverflow, MAX_DENSITY, pressureNow, promptTokensOf, splitMessages, summaryBudget, usageOfEvent, WINDOW_SLACK, withSummaryLanguage } from '../context-budget.mjs'; + +export const name = 'strata-context'; + +/** The routes the host writes for models on this computer (profile.mjs): `strata-local`, `strata-local-<id>`, and their `~s<budget>` copies. */ +const isLocalRoute = provider => typeof provider === 'string' && provider.startsWith('strata-local'); +export const inject = ['tokenMeter', 'llm']; + +/** Real prompt measurements per session: { real, estimated } for the last answer the model server reported. */ +const samples = new WeakMap(); +const bySessionId = new Map(); +const wrapped = new WeakSet(); +/** Densities that made a summary request fail on this server, per session id (the next request starts from a more careful one). */ +const careful = new Map(); + +export function apply(ctx) { + const meter = ctx.tokenMeter; + const llm = ctx.llm; + const log = (level, text) => { try { ctx.logger?.[level]?.(`strata-context: ${text}`); } catch { /* logging never blocks */ } }; + + // 1. The measured size of the prompt, from the model server's own report for each answer. + if (meter && typeof meter.measure === 'function' && !wrapped.has(meter)) { + wrapped.add(meter); + const original = meter.measure; + meter.measure = function measure(session, requestHeader) { + const m = original.call(this, session, requestHeader); + const sample = samples.get(session); + if (!sample) return m; + const now = m.surfaceTokens + estimateTools(requestHeader ?? session.requestHeader?.()); + const total = Math.max(m.totalTokens, pressureNow({ sample, now })); + if (total <= m.totalTokens) return m; + const density = densityOf(sample.real, sample.estimated); + return { ...m, totalTokens: total, nodes: m.nodes.map(n => ({ ...n, tokens: Math.ceil(n.tokens * density) })) }; + }; + ctx.on('session/event', (session, event) => { + if (event.type !== 'assistant/message') return; + const real = promptTokensOf(usageOfEvent(event)); + if (!(real > 0)) return; + try { + // The request that was just answered saw the conversation without this answer: its price is the surface before the answer's node. + const m = original.call(meter, session); + const heuristic = m.nodes.reduce((n, x) => n + (x.seq === event.seq ? 0 : x.heuristicTokens), 0); + const estimated = heuristic + estimateTools(session.requestHeader?.()); + if (!(estimated > 0)) return; + const sample = { real, estimated }; + samples.set(session, sample); + if (session.id) bySessionId.set(String(session.id), sample); + } catch (e) { log('warn', `could not record a measurement: ${e.message}`); } + }); + } + + // 2. A summary request that fits the window. + if (llm && typeof llm.stream === 'function' && !wrapped.has(llm)) { + wrapped.add(llm); + const original = llm.stream; + llm.stream = function stream(options) { + if (options?.purpose !== 'compaction') return original.call(this, options); + return summaryStream.call(this, options, original); + }; + } + + // 3. A reply that has room to finish (AGENT-LOST, 11-01). The output budget in the profile is what the Harness's compaction sets aside for a + // reply (30 percent of the window; it reads it from the request header), and the same number was also the ceiling of every request: a thinking + // model that wrote a 15K-token file after 9K tokens of thinking was cut inside the tool call at 19,660, the unfinished call was dropped and the + // turn ended with no file and no word. The header (and so compaction) stays as it is; the request that goes to the model server may produce up + // to half the window, at most 64K tokens (replyCap), and pi-ai still clamps it to what the window has left after the prompt. The agent loop + // dispatches through the adapter's `streamWithSnapshot`, after the loop has checked the request against its header, so that is where the ceiling + // is raised, once per adapter, the first time a local route is prepared. A Harness that renames it leaves the ceiling as it was (the test that + // runs the real Harness fails). + if (llm && typeof llm.prepareCall === 'function' && !wrapped.has(llm.prepareCall)) { + const original = llm.prepareCall; + const raised = new WeakSet(); + const prepare = async function prepareCall(config, signal, configure) { + try { raiseReplyCeiling(config?.provider, raised); } catch (e) { log('warn', `could not raise the reply ceiling: ${e.message}`); } + return original.call(this, config, signal, configure); + }; + wrapped.add(prepare); + llm.prepareCall = prepare; + } + function raiseReplyCeiling(provider, raised) { + if (!isLocalRoute(provider)) return; + const adapter = llm.adapters?.get?.(provider)?.adapter; + if (!adapter || raised.has(adapter) || typeof adapter.streamWithSnapshot !== 'function' || typeof adapter.modelOf !== 'function') return; + raised.add(adapter); + const stream = adapter.streamWithSnapshot; + adapter.streamWithSnapshot = function streamWithSnapshot(options, snapshot) { + let next = options; + try { + if (isLocalRoute(options?.provider)) { + const model = this.modelOf(snapshot, options.provider, options.model); + const asked = options.maxTokens ?? model.maxTokens ?? 0; + // Only the agent's own reply budget is raised: a summary or a title asks for far less and keeps what it asked. + if (model.contextWindow > 0 && asked >= Math.floor(model.contextWindow * 0.25)) { + const cap = replyCap(model.contextWindow, asked); + if (cap > asked) next = { ...options, maxTokens: cap }; + } + } + } catch { next = options; } + return stream.call(this, next, snapshot); + }; + } + + // The host asks, with /strata-context, how much of the window the chat holds right now: the same measured number compaction decides on + // (JSON in the command's text: { tokens, window }). Before a message goes out, and after /compact, so the person is told true figures. + ctx.inject(['commands'], (commandCtx) => { + commandCtx.commands.register({ + definitionId: 'strata-context', + name: 'strata-context', + description: 'Reports how many tokens the conversation holds now and the size of the model window', + handler: async (invocation) => { + try { + const session = invocation.agent.session; + const tokens = meter.measure(session).totalTokens; + const config = session.requestHeader?.()?.config; + let window = 0; + if (config) window = (await llm.resolveModelInfo(config.provider, config.model))?.context?.contextWindow ?? 0; + return { kind: 'success', text: JSON.stringify({ tokens, window }) }; + } catch (e) { return { kind: 'error', text: `strata-context: ${e.message}` }; } + }, + }); + }); + + /** A finished stream: its chunks, the text it wrote and why it ended. */ + async function drain(iterable) { + let text = '', finish = null; + const chunks = []; + for await (const chunk of iterable) { + chunks.push(chunk); + if (chunk.type === 'text-delta') text += chunk.text ?? ''; + else if (chunk.type === 'finish') finish = chunk.reason; + } + return { text, finish, chunks }; + } + const refusedForSize = finish => finish?.kind === 'error' && isContextOverflow(finish.failure ?? finish); + + async function* summaryStream(options, original) { + options = { ...options, messages: withSummaryLanguage(options.messages) }; // #4750: the summary follows the conversation's language + let window = 0; + try { window = (await llm.resolveModelInfo(options.provider, options.model, options.signal))?.context?.contextWindow ?? 0; } catch { window = 0; } + const messages = options.messages ?? []; + const key = String(options.sessionId ?? ''); + const summaryTokens = options.maxTokens ?? 4096; + if (!(window > 0) || messages.length < 2) { yield* original.call(this, options); return; } + const own = bySessionId.get(key); + let density = Math.max(careful.get(key) ?? 1, own ? densityOf(own.real, own.estimated) : 1); + const price = list => list.reduce((n, m) => n + estimateMessage(m), 0) * density; + const limit = window - summaryTokens - WINDOW_SLACK; + // The whole request fits by this price: ask as the Harness would (the model server's cache of the conversation is reused). + if (price(messages) + estimateTools({ tools: options.tools }) * density <= limit) { + const first = await drain(original.call(this, options)); + if (!refusedForSize(first.finish)) { for (const chunk of first.chunks) yield chunk; return; } + density = Math.min(MAX_DENSITY, density * 1.6); + careful.set(key, density); + log('warn', 'the summary request did not fit the window; asking in pieces'); + } + // In pieces. The instruction is the last message; the system prompt, when there is one, the first. + const instruction = messages[messages.length - 1]; + const system = messages[0]?.role === 'system' ? messages[0] : null; + const body = messages.slice(system ? 1 : 0, -1); + let tools = options.tools; + if (tools && estimateTools({ tools }) * density > window / 3) tools = undefined; // a long tool list only describes tools: the summary does not need it + const fixed = (system ? estimateMessage(system) : 0) * density + estimateTools({ tools }) * density + estimateMessage(instruction) * density; + let budget = summaryBudget({ window, summaryTokens: summaryTokens * 2, systemTokens: fixed, instructionTokens: 0 }); + for (let attempt = 0; ; attempt++) { + const runs = splitMessages(body, Math.max(1024, budget), density); + log('info', `summarising ${body.length} messages in ${runs.length} piece(s) for a ${window}-token window (density ${density.toFixed(2)}, about ${Math.round(budget)} tokens a piece)`); + let failed = null, summary = ''; + for (let i = 0; i < runs.length && !failed; i++) { + options.signal?.throwIfAborted?.(); + const carried = summary ? [{ role: 'user', content: [{ type: 'text', text: `<compacted-summary>\n${summary}\n</compacted-summary>` }] }] : []; + const { tools: _drop, ...rest } = options; + const piece = { ...rest, ...(tools ? { tools } : {}), messages: [...(system ? [system] : []), ...carried, ...runs[i], instruction] }; + const { text, finish, chunks } = await drain(original.call(this, piece)); + if (refusedForSize(finish)) { failed = finish; break; } + // The last piece's answer is the summary the Harness reads; a piece that ended in another error ends the request the same way. + if (i === runs.length - 1 || finish?.kind === 'error' || finish?.kind === 'aborted') { for (const chunk of chunks) yield chunk; return; } + summary = text; + } + if (!failed || attempt >= 3) throw Object.assign(new Error(failed?.failure?.message ?? 'the summary request does not fit the window'), { code: 'CONTEXT_WINDOW_EXCEEDED' }); + density = Math.min(MAX_DENSITY, density * 1.6); + careful.set(key, density); + budget = Math.max(1024, budget / 2); + log('warn', `a piece did not fit; asking again with pieces of about ${Math.round(budget)} tokens`); + } + } +} diff --git a/apps/host/server/agent/reply-cut.mjs b/apps/host/server/agent/reply-cut.mjs index 1d63dfa523..afcc52adb4 100644 --- a/apps/host/server/agent/reply-cut.mjs +++ b/apps/host/server/agent/reply-cut.mjs @@ -1,122 +1,122 @@ -/** - * A reply the model could not finish (AGENT-LOST, 11-01): pure helpers, no I/O. - * - * A model reply has a ceiling (the "output budget"). A thinking model that then writes a whole file in one tool call can spend all of it - * before the call is closed. The Harness drops a tool call that was not closed (its arguments are half a JSON text), the turn ends with - * the reason `max-tokens`, and until now the person saw nothing: no file, no card, no sentence. Here: - * - * - `replyCap(window)` how much one reply may produce (the request's ceiling), much larger than the budget the Harness reserves - * for compaction (profile.mjs `localOutputBudget`): the Harness still clamps it to what the window has left. - * - `ToolDraft` what a tool call that is being written looks like so far: its name, the file it is for, a size, a tail of the text. - * - `cutNotice(...)` the plain sentence for the chat, and `cutNudge(...)` the message that lets the agent carry on in smaller pieces. - */ - -/** Half the window, at most 64K tokens, and never less than the budget compaction reserves. The Harness clamps it to the room left (window minus prompt). */ -export function replyCap(window, reserved = 0) { - const w = Number.isFinite(window) && window > 0 ? Math.floor(window) : 32768; - return Math.max(Math.floor(reserved) || 0, Math.min(Math.floor(w / 2), 65536)); -} - -const ESCAPES = { n: '\n', t: '\t', r: '', '"': '"', '\\': '\\', '/': '/', b: '', f: '' }; - -/** A tail of a JSON string body, read back to text: `\n` becomes a newline, `\"` a quote. A half-written escape at the end is dropped. */ -export function unescapeJsonTail(raw) { - let text = String(raw ?? ''); - const cut = /\\(u[0-9a-fA-F]{0,3})?$/.exec(text); - if (cut) text = text.slice(0, cut.index); - return text.replace(/\\(u[0-9a-fA-F]{4}|[nrtbf"\\/])/g, (_, e) => (e[0] === 'u' ? String.fromCharCode(parseInt(e.slice(1), 16)) : ESCAPES[e] ?? e)); -} - -const TARGET = /"(?:file_path|path|filePath)"\s*:\s*"((?:[^"\\]|\\.)*)"/; -const URL_ARG = /"url"\s*:\s*"((?:[^"\\]|\\.)*)"/; -/** The long text argument of the common writing tools; the tail of the arguments is previewed after the first one of these. */ -const BODY = /"(?:content|new_string|new_str|text|code|body|command|file_text)"\s*:\s*"/; - -/** One tool call being written: the model's streamed arguments, kept small. */ -export class ToolDraft { - constructor(id, name = '') { - this.id = id; this.name = name; - this.bytes = 0; this.lines = 0; - this.head = ''; // the first 4,000 characters: the body argument usually starts here - this.where = ''; // the file (or address) the call is for, once seen: a model may write it before or after the text - this.carry = ''; // the last 300 characters, so a name split between two pieces is still seen - this.tail = ''; // the last 2,400 characters: what is being written now - this.at = 0; // when a frame was last sent for it - } - - add(piece) { - const text = String(piece ?? ''); - if (!text) return; - this.bytes += text.length; - for (let i = text.indexOf('\\n'); i >= 0; i = text.indexOf('\\n', i + 2)) this.lines += 1; - if (this.head.length < 4000) this.head += text.slice(0, 4000 - this.head.length); - this.tail = (this.tail + text).slice(-2400); - if (!this.where) { - const seen = this.carry + text; - const raw = (TARGET.exec(seen) ?? URL_ARG.exec(seen))?.[1]; - if (raw !== undefined) { try { this.where = JSON.parse(`"${raw}"`); } catch { this.where = unescapeJsonTail(raw); } } - this.carry = seen.slice(-300); - } - } - - get target() { return this.where; } - - /** The text of the body so far, only its last `max` characters; empty until the body argument has started. */ - preview(max = 1600) { - const start = BODY.exec(this.head); - if (!start) return ''; - const bodyAt = start.index + start[0].length; // where the body begins, counted in streamed characters - if (bodyAt >= this.bytes) return ''; - const tailAt = this.bytes - this.tail.length; // where the kept tail begins - const body = unescapeJsonTail(this.tail.slice(Math.max(0, bodyAt - tailAt))); - return body.length > max ? body.slice(-max) : body; - } - - /** The frame for the page. */ - frame({ done = false, ...extra } = {}) { - return { type: 'agent-tool-draft', draft: { id: this.id, name: this.name, target: this.target, bytes: this.bytes, lines: this.lines, preview: done ? '' : this.preview(), ...extra, done } }; - } -} - -const kb = n => (n >= 10_000 ? `${Math.round(n / 1000)} KB` : `${(n / 1000).toFixed(1)} KB`); - -/** Calls the model was still writing when its reply was cut: [{ name, target, bytes }]. */ -export function cutCalls(drafts) { - return [...drafts].filter(d => d.bytes > 0).map(d => ({ name: d.name, target: d.target, bytes: d.bytes })); -} - -const withTokens = tokens => (tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''); - -/** The sentence for the person, with the catalog slots it needs: { text, key, values }. `again` is true when the agent was already asked to carry on. */ -export function cutNotice({ calls = [], tokens = 0, again = false, retrying = false } = {}) { - const call = calls.find(c => c.target) ?? calls[0] ?? null; - const file = call?.target ? String(call.target).split(/[\\/]/).filter(Boolean).at(-1) : ''; - if (call && retrying) { - const key = 'That reply reached its length limit{0} while writing {1} ({2}), so nothing was saved. I asked the assistant to write it again in smaller parts.'; - const values = [withTokens(tokens), file || call.name, kb(call.bytes)]; - return { key, values, text: fill(key, values) }; - } - if (call) { - const key = 'The reply reached its length limit{0} while writing {1} ({2}), so nothing was saved. Say “continue” and it will write it again in smaller parts.'; - const values = [withTokens(tokens), file || call.name, kb(call.bytes)]; - return { key, values, text: fill(key, values) }; - } - if (retrying) { - const key = 'That reply reached its length limit{0} and was cut off. I asked the assistant to carry on.'; - return { key, values: [withTokens(tokens)], text: fill(key, [withTokens(tokens)]) }; - } - const key = 'The reply reached its length limit{0} and was cut off. Say “continue” to go on.'; - return { key, values: [withTokens(tokens)], text: fill(key, [withTokens(tokens)]) }; -} - -export function fill(template, values) { return String(template).replace(/\{(\d+)\}/g, (_, i) => String(values[Number(i)] ?? '')); } - -/** The message sent to the assistant so it carries on. It is not shown as the person's message. */ -export function cutNudge({ calls = [], tokens = 0 } = {}) { - const call = calls.find(c => c.target) ?? calls[0] ?? null; - if (!call) { - return 'Your last reply was cut off by the output limit before it was finished. Carry on from where it stopped without repeating what you already wrote, and keep your thinking short.'; - } - const file = call.target || 'the file'; - return `Your last reply was cut off by the output limit${tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''} while you were writing ${file} in one tool call, so nothing was saved. Do not make the same big call again. Write ${file} in several smaller parts: create it with the first part (about 150 lines or fewer), then add each next part with its own edit or append, and read the end of the file back at the end. Keep your thinking short.`; -} +/** + * A reply the model could not finish (AGENT-LOST, 11-01): pure helpers, no I/O. + * + * A model reply has a ceiling (the "output budget"). A thinking model that then writes a whole file in one tool call can spend all of it + * before the call is closed. The Harness drops a tool call that was not closed (its arguments are half a JSON text), the turn ends with + * the reason `max-tokens`, and until now the person saw nothing: no file, no card, no sentence. Here: + * + * - `replyCap(window)` how much one reply may produce (the request's ceiling), much larger than the budget the Harness reserves + * for compaction (profile.mjs `localOutputBudget`): the Harness still clamps it to what the window has left. + * - `ToolDraft` what a tool call that is being written looks like so far: its name, the file it is for, a size, a tail of the text. + * - `cutNotice(...)` the plain sentence for the chat, and `cutNudge(...)` the message that lets the agent carry on in smaller pieces. + */ + +/** Half the window, at most 64K tokens, and never less than the budget compaction reserves. The Harness clamps it to the room left (window minus prompt). */ +export function replyCap(window, reserved = 0) { + const w = Number.isFinite(window) && window > 0 ? Math.floor(window) : 32768; + return Math.max(Math.floor(reserved) || 0, Math.min(Math.floor(w / 2), 65536)); +} + +const ESCAPES = { n: '\n', t: '\t', r: '', '"': '"', '\\': '\\', '/': '/', b: '', f: '' }; + +/** A tail of a JSON string body, read back to text: `\n` becomes a newline, `\"` a quote. A half-written escape at the end is dropped. */ +export function unescapeJsonTail(raw) { + let text = String(raw ?? ''); + const cut = /\\(u[0-9a-fA-F]{0,3})?$/.exec(text); + if (cut) text = text.slice(0, cut.index); + return text.replace(/\\(u[0-9a-fA-F]{4}|[nrtbf"\\/])/g, (_, e) => (e[0] === 'u' ? String.fromCharCode(parseInt(e.slice(1), 16)) : ESCAPES[e] ?? e)); +} + +const TARGET = /"(?:file_path|path|filePath)"\s*:\s*"((?:[^"\\]|\\.)*)"/; +const URL_ARG = /"url"\s*:\s*"((?:[^"\\]|\\.)*)"/; +/** The long text argument of the common writing tools; the tail of the arguments is previewed after the first one of these. */ +const BODY = /"(?:content|new_string|new_str|text|code|body|command|file_text)"\s*:\s*"/; + +/** One tool call being written: the model's streamed arguments, kept small. */ +export class ToolDraft { + constructor(id, name = '') { + this.id = id; this.name = name; + this.bytes = 0; this.lines = 0; + this.head = ''; // the first 4,000 characters: the body argument usually starts here + this.where = ''; // the file (or address) the call is for, once seen: a model may write it before or after the text + this.carry = ''; // the last 300 characters, so a name split between two pieces is still seen + this.tail = ''; // the last 2,400 characters: what is being written now + this.at = 0; // when a frame was last sent for it + } + + add(piece) { + const text = String(piece ?? ''); + if (!text) return; + this.bytes += text.length; + for (let i = text.indexOf('\\n'); i >= 0; i = text.indexOf('\\n', i + 2)) this.lines += 1; + if (this.head.length < 4000) this.head += text.slice(0, 4000 - this.head.length); + this.tail = (this.tail + text).slice(-2400); + if (!this.where) { + const seen = this.carry + text; + const raw = (TARGET.exec(seen) ?? URL_ARG.exec(seen))?.[1]; + if (raw !== undefined) { try { this.where = JSON.parse(`"${raw}"`); } catch { this.where = unescapeJsonTail(raw); } } + this.carry = seen.slice(-300); + } + } + + get target() { return this.where; } + + /** The text of the body so far, only its last `max` characters; empty until the body argument has started. */ + preview(max = 1600) { + const start = BODY.exec(this.head); + if (!start) return ''; + const bodyAt = start.index + start[0].length; // where the body begins, counted in streamed characters + if (bodyAt >= this.bytes) return ''; + const tailAt = this.bytes - this.tail.length; // where the kept tail begins + const body = unescapeJsonTail(this.tail.slice(Math.max(0, bodyAt - tailAt))); + return body.length > max ? body.slice(-max) : body; + } + + /** The frame for the page. */ + frame({ done = false, ...extra } = {}) { + return { type: 'agent-tool-draft', draft: { id: this.id, name: this.name, target: this.target, bytes: this.bytes, lines: this.lines, preview: done ? '' : this.preview(), ...extra, done } }; + } +} + +const kb = n => (n >= 10_000 ? `${Math.round(n / 1000)} KB` : `${(n / 1000).toFixed(1)} KB`); + +/** Calls the model was still writing when its reply was cut: [{ name, target, bytes }]. */ +export function cutCalls(drafts) { + return [...drafts].filter(d => d.bytes > 0).map(d => ({ name: d.name, target: d.target, bytes: d.bytes })); +} + +const withTokens = tokens => (tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''); + +/** The sentence for the person, with the catalog slots it needs: { text, key, values }. `again` is true when the agent was already asked to carry on. */ +export function cutNotice({ calls = [], tokens = 0, again = false, retrying = false } = {}) { + const call = calls.find(c => c.target) ?? calls[0] ?? null; + const file = call?.target ? String(call.target).split(/[\\/]/).filter(Boolean).at(-1) : ''; + if (call && retrying) { + const key = 'That reply reached its length limit{0} while writing {1} ({2}), so nothing was saved. I asked the assistant to write it again in smaller parts.'; + const values = [withTokens(tokens), file || call.name, kb(call.bytes)]; + return { key, values, text: fill(key, values) }; + } + if (call) { + const key = 'The reply reached its length limit{0} while writing {1} ({2}), so nothing was saved. Say “continue” and it will write it again in smaller parts.'; + const values = [withTokens(tokens), file || call.name, kb(call.bytes)]; + return { key, values, text: fill(key, values) }; + } + if (retrying) { + const key = 'That reply reached its length limit{0} and was cut off. I asked the assistant to carry on.'; + return { key, values: [withTokens(tokens)], text: fill(key, [withTokens(tokens)]) }; + } + const key = 'The reply reached its length limit{0} and was cut off. Say “continue” to go on.'; + return { key, values: [withTokens(tokens)], text: fill(key, [withTokens(tokens)]) }; +} + +export function fill(template, values) { return String(template).replace(/\{(\d+)\}/g, (_, i) => String(values[Number(i)] ?? '')); } + +/** The message sent to the assistant so it carries on. It is not shown as the person's message. */ +export function cutNudge({ calls = [], tokens = 0 } = {}) { + const call = calls.find(c => c.target) ?? calls[0] ?? null; + if (!call) { + return 'Your last reply was cut off by the output limit before it was finished. Carry on from where it stopped without repeating what you already wrote, and keep your thinking short.'; + } + const file = call.target || 'the file'; + return `Your last reply was cut off by the output limit${tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''} while you were writing ${file} in one tool call, so nothing was saved. Do not make the same big call again. Write ${file} in several smaller parts: create it with the first part (about 150 lines or fewer), then add each next part with its own edit or append, and read the end of the file back at the end. Keep your thinking short.`; +} diff --git a/apps/host/server/folder-dialog.mjs b/apps/host/server/folder-dialog.mjs index d37afd2bbc..cc293416c4 100644 --- a/apps/host/server/folder-dialog.mjs +++ b/apps/host/server/folder-dialog.mjs @@ -1,207 +1,207 @@ -/** - * The host's native "choose a folder" dialog, one per platform: - * macOS osascript (choose folder) -- unchanged - * Windows PowerShell FolderBrowserDialog (STA, topmost owner so it never opens behind the app) - * Linux zenity, then kdialog, then the desktop portal (gdbus), all with the environment the AppImage was started from - * Where no dialog works the caller gets { unavailable: true } and the app shows a plain message and a field for the path. - */ -import { spawn } from 'node:child_process'; -import { stat } from 'node:fs/promises'; -import { exec } from './util.mjs'; -import { externalEnvironment } from './external-env.mjs'; - -const MAC_SCRIPT = prompt => `POSIX path of (choose folder with prompt "${prompt.replace(/["\\]/g, '')}")`; - -export function windowsFolderScript(prompt) { - const text = prompt.replace(/'/g, "''"); - return [ - 'Add-Type -AssemblyName System.Windows.Forms', - '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8', - '$owner = New-Object System.Windows.Forms.Form', - '$owner.TopMost = $true; $owner.ShowInTaskbar = $false; $owner.StartPosition = "CenterScreen"; $owner.Size = New-Object System.Drawing.Size(0, 0)', - '$owner.Show(); $owner.Activate()', - '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog', - `$dialog.Description = '${text}'`, - '$dialog.ShowNewFolderButton = $true', - // READY tells the host the window is about to open; a host that never sees it gives up and asks for the path in words (QA F06). - '[Console]::Out.WriteLine("READY"); [Console]::Out.Flush()', - // The dialog starts at the Desktop folder. Where that folder does not exist (it was deleted, a OneDrive move left a dead path, the profile was - // redirected) ShowDialog throws "Unable to retrieve the root folder" and no folder could be chosen at all: start at This PC instead, and when even - // that fails say NODIALOG so the app asks for the path. - '$answer = $null', - 'try { $answer = $dialog.ShowDialog($owner) } catch { try { $dialog.RootFolder = [System.Environment+SpecialFolder]::MyComputer; $answer = $dialog.ShowDialog($owner) } catch { [Console]::Out.WriteLine("NODIALOG"); [Console]::Out.Flush() } }', - 'if ($answer -eq "OK") { [Console]::Out.Write($dialog.SelectedPath) }', - '$owner.Close()', - ].join('; '); -} - -/** powershell.exe takes the script as UTF-16LE base64, so no quoting survives to be mangled. */ -export function windowsFolderArgs(prompt) { - return ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(windowsFolderScript(prompt), 'utf16le').toString('base64')]; -} - -/** Strip trailing separators, but leave a drive or filesystem root intact. */ -export function cleanChosenPath(value) { - const text = String(value ?? '').trim(); - if (/^[A-Za-z]:[\\/]*$/.test(text)) return text.slice(0, 2) + '\\'; - return text.length > 1 ? text.replace(/[\\/]+$/, '') || text.slice(0, 1) : text; -} - -const missing = error => error?.code === 'ENOENT'; - -/** What the script printed, without its READY line. */ -const answerOf = stdout => String(stdout ?? '').split(/\r?\n/).filter(line => line.trim() && line.trim() !== 'READY').join('\n'); - -/** - * Runs the Windows dialog and watches it. Resolves { stdout } when it ends, { noDialog: true } when its window never got as far as - * opening (no READY within `readyMs`: PowerShell blocked, stuck or without a desktop), and rejects with { code } as exec does. - * The person's own time with the open dialog is not limited (a day at most). - */ -export function watchedWindowsDialog(shell, args, { readyMs = 30_000, openMs = 24 * 3600_000, spawnProcess = spawn } = {}) { - return new Promise((resolve, reject) => { - const child = spawnProcess(shell, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); - let stdout = '', ready = false, settled = false; - child.stdout?.setEncoding?.('utf8'); // a multi-byte letter of a Cyrillic folder must not be cut between two chunks - const end = (fn, value) => { if (settled) return; settled = true; clearTimeout(timer); try { child.kill(); } catch { /* gone */ } fn(value); }; - const timer = setTimeout(() => end(resolve, ready ? { stdout: '' } : { noDialog: true }), readyMs); - 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); - // 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 })); }); - }); -} - -/** - * Ask for a folder. Resolves { path } | { cancelled: true } | { unavailable: true, reason }. - * `run` is injectable for tests: (command, args) => Promise<{ stdout }>. - */ -export async function chooseFolder(prompt, options = {}) { - const { platform = process.platform, run = exec, portal = portalFolder, windowsDialog = options.run ? null : watchedWindowsDialog } = options; - if (platform === 'darwin') { - try { - const { stdout } = await run('osascript', ['-e', MAC_SCRIPT(prompt)]); - return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true }; - } catch { - return { cancelled: true }; // dismissing the dialog is an exit code, not a failure - } - } - if (platform === 'win32') { - const shell = `${process.env.SystemRoot || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`; - try { - const done = windowsDialog ? await windowsDialog(shell, windowsFolderArgs(prompt)) : await run(shell, windowsFolderArgs(prompt)); - if (done.noDialog) return { unavailable: true, failed: true, reason: 'The folder window did not open. Type the folder path instead.' }; - if (/^NODIALOG\s*$/m.test(String(done.stdout ?? ''))) return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.' }; - const answer = answerOf(done.stdout).trim(); - return answer ? { path: cleanChosenPath(answer) } : { cancelled: true }; - } catch (error) { - if (missing(error)) return { unavailable: true, reason: 'Windows PowerShell was not found.' }; - // The window opened or tried to and ended with an error: the person is asked for the path instead of being left with an error and no way on. - return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.', detail: `exit ${error?.code ?? '?'}` }; - } - } - return chooseLinuxFolder(prompt, { run, portal }); -} - -/** A chooser that is there but broke (the display is missing, a library does not load) must say so; a bare exit 1 is a cancel. */ -const BROKEN = /unable to init server|cannot open display|can't open display|no protocol specified|error while loading shared libraries|symbol lookup error|version `[^']*' not found|cannot connect to|failed to connect|could not connect/i; -const firstLine = text => String(text ?? '').split(/\r?\n/).map(l => l.trim()).find(Boolean)?.slice(0, 160) ?? ''; - -/** - * Linux: zenity, then kdialog, then the desktop portal's file chooser through gdbus. Every one of them runs with the environment the - * AppImage was started from (external-env.mjs), not Strata's own libraries. A chooser that is missing is skipped; one that fails is - * remembered and the next is tried; when none works the answer says why and the person types the path. - */ -async function chooseLinuxFolder(prompt, { run, portal }) { - const env = externalEnvironment(); - const candidates = [ - ['zenity', ['--file-selection', '--directory', `--title=${prompt}`]], - ['kdialog', ['--getexistingdirectory', '.', '--title', prompt]], - ]; - const failures = []; - for (const [command, args] of candidates) { - try { - const { stdout } = await run(command, args, { env }); - return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true }; - } catch (error) { - if (missing(error)) continue; - const detail = `${error?.stderr ?? ''}`; - if (error?.code === 1 && !BROKEN.test(detail)) return { cancelled: true }; // both tools exit 1 when the dialog is dismissed - failures.push(`${command}: ${firstLine(detail) || firstLine(error?.message) || `exit ${error?.code}`}`); - } - } - try { - const picked = await portal(prompt, { run, env }); - if (picked) return picked; - } catch (error) { - failures.push(`portal: ${firstLine(error?.message)}`); - } - return { - unavailable: true, failed: failures.length > 0, ...(failures.length ? { detail: failures.join('; ') } : {}), - reason: failures.length - ? 'The folder chooser could not open. Install zenity or kdialog to pick a folder, or type the path.' - : 'No folder chooser was found. Install zenity or kdialog to pick a folder, or type the path.', - }; -} - -/** - * xdg-desktop-portal FileChooser through gdbus. Resolves { path } | { cancelled: true } | null when there is no portal or no gdbus. - * The answer arrives as a Response signal on the request the call returns, so a monitor is started first. - */ -export async function portalFolder(prompt, { run = exec, env = externalEnvironment(), spawnProcess = spawn, timeoutMs = 10 * 60_000 } = {}) { - const monitor = spawnProcess('gdbus', ['monitor', '--session', '--dest', 'org.freedesktop.portal.Desktop'], { env, stdio: ['ignore', 'pipe', 'ignore'] }); - let seen = ''; - let ended = false; - monitor.on('error', () => { ended = true; }); - monitor.on('close', () => { ended = true; }); - monitor.stdout?.on('data', chunk => { seen += chunk; }); - try { - let call; - try { - call = await run('gdbus', ['call', '--session', '--dest', 'org.freedesktop.portal.Desktop', '--object-path', '/org/freedesktop/portal/desktop', - '--method', 'org.freedesktop.portal.FileChooser.OpenFile', '', prompt, "{'directory': <true>, 'modal': <true>}"], { env }); - } catch { - return null; // no gdbus, or no portal on the session bus - } - const handle = /'(\/org\/freedesktop\/portal\/desktop\/request\/[^']+)'/.exec(call.stdout)?.[1]; - if (!handle) return null; - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - const line = seen.split('\n').find(l => l.startsWith(`${handle}: org.freedesktop.portal.Request.Response`)); - if (line) { - const m = /\(uint32 (\d+), (.*)\)\s*$/.exec(line); - if (!m || m[1] !== '0') return { cancelled: true }; - const uri = /'(file:\/\/[^']*)'/.exec(m[2])?.[1]; - return uri ? { path: cleanChosenPath(decodeURIComponent(uri.replace(/^file:\/\//, ''))) } : { cancelled: true }; - } - if (ended) return null; - await new Promise(r => setTimeout(r, 100)); - } - return { cancelled: true }; - } finally { - try { monitor.kill(); } catch { /* already gone */ } - } -} - -export const TYPE_A_PATH = 'No folder chooser is available on this system, so type the folder path instead.'; - -/** The host's answer when no chooser works: a plain sentence and a code the app turns into a field for typing the path. */ -export function chooserUnavailable(picked) { - return { message: picked.reason, code: 'folder-chooser-unavailable', details: picked.detail }; -} - -/** A typed path stands in for the dialog: it must be an absolute directory that exists. `fileType` (a RegExp on the name) also lets a - * file of that kind through (the model page takes a folder or one .gguf file). Quotes around the path (Windows "Copy as path") go. */ -export async function typedFolder(value, { isAbsolute, fileType = null }) { - let text = typeof value === 'string' ? value.trim() : ''; - if (text.length > 1 && /^(["'])[\s\S]*\1$/.test(text)) text = text.slice(1, -1).trim(); - if (!text || text.includes('\0')) return null; - if (!isAbsolute(text)) throw new Error(fileType ? 'Enter the full path of the folder or the file.' : 'Enter the full path of the folder.'); - let info; - try { info = await stat(text); } catch { throw new Error(fileType ? 'That folder or file does not exist.' : 'That folder does not exist.'); } - if (info.isFile() && fileType?.test(text)) return text; - if (!info.isDirectory()) throw new Error(fileType ? 'Choose a folder, or a .gguf file.' : 'Choose a folder, not a file.'); - return cleanChosenPath(text); -} +/** + * The host's native "choose a folder" dialog, one per platform: + * macOS osascript (choose folder) -- unchanged + * Windows PowerShell FolderBrowserDialog (STA, topmost owner so it never opens behind the app) + * Linux zenity, then kdialog, then the desktop portal (gdbus), all with the environment the AppImage was started from + * Where no dialog works the caller gets { unavailable: true } and the app shows a plain message and a field for the path. + */ +import { spawn } from 'node:child_process'; +import { stat } from 'node:fs/promises'; +import { exec } from './util.mjs'; +import { externalEnvironment } from './external-env.mjs'; + +const MAC_SCRIPT = prompt => `POSIX path of (choose folder with prompt "${prompt.replace(/["\\]/g, '')}")`; + +export function windowsFolderScript(prompt) { + const text = prompt.replace(/'/g, "''"); + return [ + 'Add-Type -AssemblyName System.Windows.Forms', + '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8', + '$owner = New-Object System.Windows.Forms.Form', + '$owner.TopMost = $true; $owner.ShowInTaskbar = $false; $owner.StartPosition = "CenterScreen"; $owner.Size = New-Object System.Drawing.Size(0, 0)', + '$owner.Show(); $owner.Activate()', + '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog', + `$dialog.Description = '${text}'`, + '$dialog.ShowNewFolderButton = $true', + // READY tells the host the window is about to open; a host that never sees it gives up and asks for the path in words (QA F06). + '[Console]::Out.WriteLine("READY"); [Console]::Out.Flush()', + // The dialog starts at the Desktop folder. Where that folder does not exist (it was deleted, a OneDrive move left a dead path, the profile was + // redirected) ShowDialog throws "Unable to retrieve the root folder" and no folder could be chosen at all: start at This PC instead, and when even + // that fails say NODIALOG so the app asks for the path. + '$answer = $null', + 'try { $answer = $dialog.ShowDialog($owner) } catch { try { $dialog.RootFolder = [System.Environment+SpecialFolder]::MyComputer; $answer = $dialog.ShowDialog($owner) } catch { [Console]::Out.WriteLine("NODIALOG"); [Console]::Out.Flush() } }', + 'if ($answer -eq "OK") { [Console]::Out.Write($dialog.SelectedPath) }', + '$owner.Close()', + ].join('; '); +} + +/** powershell.exe takes the script as UTF-16LE base64, so no quoting survives to be mangled. */ +export function windowsFolderArgs(prompt) { + return ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(windowsFolderScript(prompt), 'utf16le').toString('base64')]; +} + +/** Strip trailing separators, but leave a drive or filesystem root intact. */ +export function cleanChosenPath(value) { + const text = String(value ?? '').trim(); + if (/^[A-Za-z]:[\\/]*$/.test(text)) return text.slice(0, 2) + '\\'; + return text.length > 1 ? text.replace(/[\\/]+$/, '') || text.slice(0, 1) : text; +} + +const missing = error => error?.code === 'ENOENT'; + +/** What the script printed, without its READY line. */ +const answerOf = stdout => String(stdout ?? '').split(/\r?\n/).filter(line => line.trim() && line.trim() !== 'READY').join('\n'); + +/** + * Runs the Windows dialog and watches it. Resolves { stdout } when it ends, { noDialog: true } when its window never got as far as + * opening (no READY within `readyMs`: PowerShell blocked, stuck or without a desktop), and rejects with { code } as exec does. + * The person's own time with the open dialog is not limited (a day at most). + */ +export function watchedWindowsDialog(shell, args, { readyMs = 30_000, openMs = 24 * 3600_000, spawnProcess = spawn } = {}) { + return new Promise((resolve, reject) => { + const child = spawnProcess(shell, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); + let stdout = '', ready = false, settled = false; + child.stdout?.setEncoding?.('utf8'); // a multi-byte letter of a Cyrillic folder must not be cut between two chunks + const end = (fn, value) => { if (settled) return; settled = true; clearTimeout(timer); try { child.kill(); } catch { /* gone */ } fn(value); }; + const timer = setTimeout(() => end(resolve, ready ? { stdout: '' } : { noDialog: true }), readyMs); + 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); + // 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 })); }); + }); +} + +/** + * Ask for a folder. Resolves { path } | { cancelled: true } | { unavailable: true, reason }. + * `run` is injectable for tests: (command, args) => Promise<{ stdout }>. + */ +export async function chooseFolder(prompt, options = {}) { + const { platform = process.platform, run = exec, portal = portalFolder, windowsDialog = options.run ? null : watchedWindowsDialog } = options; + if (platform === 'darwin') { + try { + const { stdout } = await run('osascript', ['-e', MAC_SCRIPT(prompt)]); + return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true }; + } catch { + return { cancelled: true }; // dismissing the dialog is an exit code, not a failure + } + } + if (platform === 'win32') { + const shell = `${process.env.SystemRoot || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`; + try { + const done = windowsDialog ? await windowsDialog(shell, windowsFolderArgs(prompt)) : await run(shell, windowsFolderArgs(prompt)); + if (done.noDialog) return { unavailable: true, failed: true, reason: 'The folder window did not open. Type the folder path instead.' }; + if (/^NODIALOG\s*$/m.test(String(done.stdout ?? ''))) return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.' }; + const answer = answerOf(done.stdout).trim(); + return answer ? { path: cleanChosenPath(answer) } : { cancelled: true }; + } catch (error) { + if (missing(error)) return { unavailable: true, reason: 'Windows PowerShell was not found.' }; + // The window opened or tried to and ended with an error: the person is asked for the path instead of being left with an error and no way on. + return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.', detail: `exit ${error?.code ?? '?'}` }; + } + } + return chooseLinuxFolder(prompt, { run, portal }); +} + +/** A chooser that is there but broke (the display is missing, a library does not load) must say so; a bare exit 1 is a cancel. */ +const BROKEN = /unable to init server|cannot open display|can't open display|no protocol specified|error while loading shared libraries|symbol lookup error|version `[^']*' not found|cannot connect to|failed to connect|could not connect/i; +const firstLine = text => String(text ?? '').split(/\r?\n/).map(l => l.trim()).find(Boolean)?.slice(0, 160) ?? ''; + +/** + * Linux: zenity, then kdialog, then the desktop portal's file chooser through gdbus. Every one of them runs with the environment the + * AppImage was started from (external-env.mjs), not Strata's own libraries. A chooser that is missing is skipped; one that fails is + * remembered and the next is tried; when none works the answer says why and the person types the path. + */ +async function chooseLinuxFolder(prompt, { run, portal }) { + const env = externalEnvironment(); + const candidates = [ + ['zenity', ['--file-selection', '--directory', `--title=${prompt}`]], + ['kdialog', ['--getexistingdirectory', '.', '--title', prompt]], + ]; + const failures = []; + for (const [command, args] of candidates) { + try { + const { stdout } = await run(command, args, { env }); + return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true }; + } catch (error) { + if (missing(error)) continue; + const detail = `${error?.stderr ?? ''}`; + if (error?.code === 1 && !BROKEN.test(detail)) return { cancelled: true }; // both tools exit 1 when the dialog is dismissed + failures.push(`${command}: ${firstLine(detail) || firstLine(error?.message) || `exit ${error?.code}`}`); + } + } + try { + const picked = await portal(prompt, { run, env }); + if (picked) return picked; + } catch (error) { + failures.push(`portal: ${firstLine(error?.message)}`); + } + return { + unavailable: true, failed: failures.length > 0, ...(failures.length ? { detail: failures.join('; ') } : {}), + reason: failures.length + ? 'The folder chooser could not open. Install zenity or kdialog to pick a folder, or type the path.' + : 'No folder chooser was found. Install zenity or kdialog to pick a folder, or type the path.', + }; +} + +/** + * xdg-desktop-portal FileChooser through gdbus. Resolves { path } | { cancelled: true } | null when there is no portal or no gdbus. + * The answer arrives as a Response signal on the request the call returns, so a monitor is started first. + */ +export async function portalFolder(prompt, { run = exec, env = externalEnvironment(), spawnProcess = spawn, timeoutMs = 10 * 60_000 } = {}) { + const monitor = spawnProcess('gdbus', ['monitor', '--session', '--dest', 'org.freedesktop.portal.Desktop'], { env, stdio: ['ignore', 'pipe', 'ignore'] }); + let seen = ''; + let ended = false; + monitor.on('error', () => { ended = true; }); + monitor.on('close', () => { ended = true; }); + monitor.stdout?.on('data', chunk => { seen += chunk; }); + try { + let call; + try { + call = await run('gdbus', ['call', '--session', '--dest', 'org.freedesktop.portal.Desktop', '--object-path', '/org/freedesktop/portal/desktop', + '--method', 'org.freedesktop.portal.FileChooser.OpenFile', '', prompt, "{'directory': <true>, 'modal': <true>}"], { env }); + } catch { + return null; // no gdbus, or no portal on the session bus + } + const handle = /'(\/org\/freedesktop\/portal\/desktop\/request\/[^']+)'/.exec(call.stdout)?.[1]; + if (!handle) return null; + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const line = seen.split('\n').find(l => l.startsWith(`${handle}: org.freedesktop.portal.Request.Response`)); + if (line) { + const m = /\(uint32 (\d+), (.*)\)\s*$/.exec(line); + if (!m || m[1] !== '0') return { cancelled: true }; + const uri = /'(file:\/\/[^']*)'/.exec(m[2])?.[1]; + return uri ? { path: cleanChosenPath(decodeURIComponent(uri.replace(/^file:\/\//, ''))) } : { cancelled: true }; + } + if (ended) return null; + await new Promise(r => setTimeout(r, 100)); + } + return { cancelled: true }; + } finally { + try { monitor.kill(); } catch { /* already gone */ } + } +} + +export const TYPE_A_PATH = 'No folder chooser is available on this system, so type the folder path instead.'; + +/** The host's answer when no chooser works: a plain sentence and a code the app turns into a field for typing the path. */ +export function chooserUnavailable(picked) { + return { message: picked.reason, code: 'folder-chooser-unavailable', details: picked.detail }; +} + +/** A typed path stands in for the dialog: it must be an absolute directory that exists. `fileType` (a RegExp on the name) also lets a + * file of that kind through (the model page takes a folder or one .gguf file). Quotes around the path (Windows "Copy as path") go. */ +export async function typedFolder(value, { isAbsolute, fileType = null }) { + let text = typeof value === 'string' ? value.trim() : ''; + if (text.length > 1 && /^(["'])[\s\S]*\1$/.test(text)) text = text.slice(1, -1).trim(); + if (!text || text.includes('\0')) return null; + if (!isAbsolute(text)) throw new Error(fileType ? 'Enter the full path of the folder or the file.' : 'Enter the full path of the folder.'); + let info; + try { info = await stat(text); } catch { throw new Error(fileType ? 'That folder or file does not exist.' : 'That folder does not exist.'); } + if (info.isFile() && fileType?.test(text)) return text; + if (!info.isDirectory()) throw new Error(fileType ? 'Choose a folder, or a .gguf file.' : 'Choose a folder, not a file.'); + return cleanChosenPath(text); +} diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 33cb353c98..24885c6dbb 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -1,2195 +1,2195 @@ -import { workspaceIdForSession } from './session-workspace'; -import { DEFAULT_CONTENT_FS, DEFAULT_UI_SCALE, SIZE_DEFAULTS_VERSION, savedSizes } from './default-sizes'; -import { detectLanguage } from './language-detect'; -import { validWhileBusy, type WhileBusy } from './while-busy'; -import { addToQuotes, type Quote } from './quotes'; -import { readAsk, type AgentAnswer, type AgentAsk } from './agent-ask'; -import { plainFailure, plainFailureText } from './plain-errors'; -import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase'; -import { settleAgents, updateAgent } from './agents'; -import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop'; -import { LoopScheduler } from './loop-runner'; -import { applyStatusFrame, clearStatus } from './live-status'; -import { approvalNeeded, workFinished } from './attention'; -import { applyGoalFrame } from './goal'; -import { tidyAnswer } from './answer-text'; -import { appendText, mergeDeliverable, readDeliverable, readGroup, readSkills, upsertGroup } from './deliverables'; -import { applyPlanFrame, applyQueueFrame, planApprove, queueMessage } from './plan'; -import { forkFields, isForkJob, TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipFile, type TimeSkipJob, type TimeSkipRun, type TimeSkipVersion } from './time-skip'; -import { PREVIEW_EXAMPLES, type PreviewArtifact } from './artifacts'; -import { lifecyclePolicy } from './lifecycle'; -import { newestServingState } from './serving-state'; -import { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos'; -import { applyNativeEvent, nativeState } from './native'; -import { pictureStatus } from './pictures'; -import { noModelNotice } from './no-model'; -import { taskHandoverMessage, taskHandoverTitle, chatHandoverMessage, chatHandoverTitle } from './task-handover'; -import type { Task } from './tasks'; -import { postWithFolderFallback } from './folder-pick'; -import { createSessionWriter } from './session-persist'; -import { setTranslationLanguage, tr, validLanguage, type Language } from './i18n'; -/** - * Strata app store. - * - * A single immutable state object + a tiny subscribe/emit pair, consumed through - * useSyncExternalStore. Data comes from the engine host over /api; live updates - * arrive on the event stream. No state library, no dependencies. - */ -import { useSyncExternalStore } from 'react'; -import { api, onEvent, streamPost, type StreamEvent } from './client'; -import type { - Workspace, - ChatMessage, - ToolCall, - EngineConfig, - Hardware, - ModelLibrary, - RuntimeModels, - ImageModelLibrary, - ImageModelChoice, - ModelProviders, - ModelConnectionDraft, - RemoteModelSelection, - MonitorState, - ServingState, - Session, - SetupState, - Skill, - WorkspaceFile, - ToolDraft, -} from './types'; -import { navigate, type Route } from './router'; -import { estimate, execution, contextTokens } from './experience'; - -export interface Toast { - id: string; - tone: 'info' | 'success' | 'warn' | 'error'; - title: string; - body?: string; - leaving?: boolean; -} - -export interface AppState { - language: Language; - fontFamily: string; - configDraft: string | null; - navOpen: boolean; - ready: boolean; - connection: 'connecting' | 'live' | 'offline'; - theme: 'dark' | 'light' | 'system'; - contrast: 'standard' | 'increased'; - rail: boolean; - /** Distraction-free reading: chrome recedes, the transcript narrows. */ - focus: boolean; - /** Conversation prose size in px, 10–22. Does not touch the UI chrome. */ - contentFontSize: number; - density: 'comfortable' | 'compact'; - motion: 'system' | 'full' | 'reduced'; - /** Translucent materials, or flat surfaces for anyone who prefers them. */ - transparency: 'translucent' | 'opaque'; - /** Chrome scale, independent of the conversation's reading size. */ - uiScale: number; - /** Price of one kWh for the Monitor's cost line (0 = not set) and the currency the person picked instead of the detected one ('' = automatic) (#3628). */ - electricityPrice: number; - electricityCurrency: string; - /** Opt-in: a short sound when a task finishes (#3586). */ - doneSound: boolean; - /** Opt-in: a desktop notification when Manual mode waits for an approval (#3477). */ - approvalNotify: boolean; - /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ - whileBusy: WhileBusy; - /** Governs anonymous usage reporting. Nothing is sent in this build; the - * choice is recorded so a version that does offer it starts from it. */ - shareTelemetry: boolean; - paletteOpen: boolean; - shortcutsOpen: boolean; - settingsSection: 'Appearance' | 'Models' | 'Tools' | 'Storage' | 'Engine' | 'About'; - hardware: Hardware | null; - library: ModelLibrary | null; - imageModels: ImageModelLibrary | null; - runtime: RuntimeModels | null; - providers: ModelProviders | null; - remoteModel: RemoteModelSelection | null; - engine: EngineConfig | null; - serving: ServingState | null; - monitor: MonitorState | null; - setup: SetupState | null; - skills: Skill[]; - files: WorkspaceFile[]; - workspacePath: string; - workspaces: Workspace[]; - /** Id of the workspace the file tree is scoped to. */ - activeWorkspace: string | null; - /** First run, and "run setup again", both present the wizard as a modal. */ - setupOpen: boolean; - sessions: Session[]; - activeSession: string | null; - streaming: boolean; - /** Messages the person sent while an answer was being written, waiting to go when it ends (Send after, Interrupt), by chat (#4783). */ - parked: Record<string, string[]>; - /** The passages quoted into the message being written, by chat, in the order they were quoted (#4785). */ - quotes: Record<string, Quote[]>; - /** The questions the agent asked the person and is waiting for, by chat (#4244). */ - agentAsks: Record<string, AgentAsk[]>; - /** Chats with a turn in flight. `streaming` is about the open chat; this is about all of them. */ - liveChats: number; - toasts: Toast[]; - /** Files the model has been granted read access to, and when. */ - touchedPaths: Record<string, string>; - /** The last action that failed, kept until it is retried or dismissed. - * A toast disappears after five seconds; a failure the reader has not dealt - * with should not. */ - actionError: { message: string; label: string; retry: () => void } | null; - busy: Record<string, boolean>; -} - -const SESSION_KEY = 'strata.sessions.v1'; -const PREFS_KEY = 'strata.prefs.v2'; -/** What the model has been allowed to read, kept across restarts. */ -const TOUCHED_KEY = 'strata.touched.v1'; -/** Kept one release so downgrading does not lose the theme and sidebar state. */ -const PREFS_KEY_V1 = 'strata.prefs.v1'; - -const CONTENT_FS_MIN = 10; -const CONTENT_FS_MAX = 22; - -export interface Prefs { - /** Which default sizes this save was made with (see SIZE_DEFAULTS_VERSION). */ - sizeDefaults?: number; - language: Language; - fontFamily: string; - theme: 'dark' | 'light' | 'system'; - contrast: 'standard' | 'increased'; - rail: boolean; - focus: boolean; - contentFontSize: number; - density: 'comfortable' | 'compact'; - motion: 'system' | 'full' | 'reduced'; - transparency: 'translucent' | 'opaque'; - uiScale: number; - electricityPrice: number; - electricityCurrency: string; - doneSound: boolean; - approvalNotify: boolean; - /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ - whileBusy: WhileBusy; - /** Governs anonymous usage reporting. Nothing is sent in this build; the - * choice is recorded so a version that does offer it starts from it. */ - shareTelemetry: boolean; -} - -const PREFS_DEFAULTS: Prefs = { - language: 'en', - fontFamily: '', - theme: 'system', - contrast: 'standard', - rail: false, - focus: false, - contentFontSize: DEFAULT_CONTENT_FS, - density: 'comfortable', - motion: 'system', - transparency: 'translucent', - uiScale: DEFAULT_UI_SCALE, - electricityPrice: 0, - electricityCurrency: '', - doneSound: false, - approvalNotify: false, - whileBusy: 'wait', - shareTelemetry: false, -}; - -function uid(prefix = 'id'): string { - return `${prefix}_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36).slice(-4)}`; -} - -function loadSessions(): Session[] { - try { - const raw = localStorage.getItem(SESSION_KEY); - if (!raw) return []; - const parsed = JSON.parse(raw) as Session[]; - return Array.isArray(parsed) ? parsed.map(session => ({ - ...session, - ...(session.showcase && !session.showcaseAgentStates ? {agents:SHOWCASE_AGENTS,showcaseAgentStates:true}:{}), - ...(!session.showcase && session.agents ? { agents: settleAgents(session.agents) } : {}), - messages: session.messages.map(message => message.streaming ? { - ...message, - streaming: false, - error: message.error ?? 'Response interrupted. Ask again to retry; the partial answer is kept.', - } : message), - })) : []; - } catch { - return []; - } -} - -/** - * v2 adds focus, reading size, density and the motion override. A v1 blob (only - * theme and rail) is read as-is and upgraded on the next write, so the first run - * after this change keeps the user's theme instead of resetting it. - */ -function loadPrefs(): Prefs { - for (const key of [PREFS_KEY, PREFS_KEY_V1]) { - try { - const raw = localStorage.getItem(key); - if (!raw) continue; - const parsed = JSON.parse(raw) as Partial<Prefs>; - return { - ...PREFS_DEFAULTS, - ...parsed, - language: validLanguage(parsed.language) ? parsed.language : 'en', - fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '', - ...savedSizes(parsed, CONTENT_FS_MIN, CONTENT_FS_MAX), - sizeDefaults: SIZE_DEFAULTS_VERSION, - electricityPrice: Number.isFinite(Number(parsed.electricityPrice)) && Number(parsed.electricityPrice) > 0 && Number(parsed.electricityPrice) < 1000 ? Number(parsed.electricityPrice) : 0, - electricityCurrency: typeof parsed.electricityCurrency === 'string' && /^[A-Za-z]{3}$/.test(parsed.electricityCurrency) ? parsed.electricityCurrency.toUpperCase() : '', - doneSound: parsed.doneSound === true, - approvalNotify: parsed.approvalNotify === true, - whileBusy: validWhileBusy(parsed.whileBusy) ? parsed.whileBusy : 'wait', - }; - } catch { - /* fall through to the next key */ - } - } - // Nothing saved: a first start. It opens in the language of the computer; a choice made on the first screen is saved like any other. - const tags = typeof navigator === 'undefined' ? [] : navigator.languages?.length ? navigator.languages : [navigator.language]; - return { ...PREFS_DEFAULTS, language: detectLanguage(tags) ?? 'en' }; -} - -const prefs = loadPrefs(); -// Use the saved language for the very first render, before host bootstrap. -setTranslationLanguage(prefs.language); - -/** The last approval question a notification was shown for, so one question is announced once. */ -let lastApprovalNotice = ''; - -let state: AppState = { - language: prefs.language, - fontFamily: prefs.fontFamily, - configDraft: (() => { try { return sessionStorage.getItem('strata.config-draft.v1'); } catch { return null; } })(), - navOpen: false, - ready: false, - connection: 'connecting', - shareTelemetry: prefs.shareTelemetry, - theme: prefs.theme, - contrast: prefs.contrast, - rail: prefs.rail, - focus: prefs.focus, - contentFontSize: prefs.contentFontSize, - density: prefs.density, - motion: prefs.motion, - transparency: prefs.transparency, - uiScale: prefs.uiScale, - electricityPrice: prefs.electricityPrice, - electricityCurrency: prefs.electricityCurrency, - doneSound: prefs.doneSound, - approvalNotify: prefs.approvalNotify, - whileBusy: prefs.whileBusy, - parked: {}, - quotes: {}, - agentAsks: {}, - paletteOpen: false, - shortcutsOpen: false, - settingsSection: 'Appearance', - hardware: null, - library: null, - imageModels: null, - runtime: null, - providers: null, - /** The open chat's API model, or null for the local model (the default for every chat). */ - remoteModel: null, - engine: null, - serving: null, - monitor: null, - setup: null, - skills: [], - files: [], - workspacePath: '', - workspaces: [], - activeWorkspace: null, - setupOpen: false, - sessions: loadSessions(), - activeSession: null, - streaming: false, - liveChats: 0, - toasts: [], - touchedPaths: (() => { - try { - return JSON.parse(localStorage.getItem(TOUCHED_KEY) ?? '{}') as Record<string, string>; - } catch { - return {}; - } - })(), - actionError: null, - busy: {}, -}; - -const listeners = new Set<() => void>(); - -/** Chats with a turn in flight: the abort handle, and whether the host is running it as an agent turn. */ -const liveTurns = new Map<string, { abort: AbortController; agent: boolean }>(); - -function set(patch: Partial<AppState> | ((s: AppState) => Partial<AppState>)) { - const before = state.activeSession; - const next = typeof patch === 'function' ? patch(state) : patch; - state = { ...state, ...next }; - // Opening another chat shows that chat's model choice and whether that chat is mid-turn. - if (state.activeSession !== before) { - const chosen = state.sessions.find(s => s.id === state.activeSession)?.preferences?.remoteModel ?? null; - state = { ...state, remoteModel: 'remoteModel' in next ? state.remoteModel : chosen, streaming: !!state.activeSession && liveTurns.has(state.activeSession) }; - } - for (const l of listeners) l(); -} - -function subscribe(l: () => void) { - listeners.add(l); - return () => listeners.delete(l); -} - -export function getState(): AppState { - return state; -} - -export function setConfigDraft(configDraft: string | null) { - set({ configDraft }); - try { - if (configDraft === null) sessionStorage.removeItem('strata.config-draft.v1'); - else sessionStorage.setItem('strata.config-draft.v1', configDraft); - } catch { /* Keep the session draft even when browser storage is unavailable. */ } -} - -export function setNavOpen(navOpen: boolean) { set({ navOpen }); } -export function setSettingsSection(settingsSection: AppState['settingsSection']) { set({ settingsSection }); } - -/** Choose the open chat's model: an API model, or null for the local one. Other chats keep theirs. */ -export function selectRemoteModel(remoteModel: RemoteModelSelection | null) { - if (state.streaming) return; - if (remoteModel && !state.providers?.connections.some(c => c.id === remoteModel.connectionId && c.models.some(m => m.id === remoteModel.modelId))) return; - set({ remoteModel }); - const id = state.activeSession; - if (id) patchSession(id, s => ({ ...s, preferences: { ...s.preferences, remoteModel } })); - try { localStorage.removeItem('strata.remote-model.v1'); } catch { /* The old global choice is retired. */ } -} -function applyProviders(providers: ModelProviders) { - // A chat whose API model was removed keeps its choice: the next send says the model is gone, rather - // than quietly answering from the local model. - set({ providers }); -} -export async function saveModelConnection(draft: ModelConnectionDraft) { - applyProviders(await api.post<ModelProviders>('/api/model-providers', draft)); -} -export async function removeModelConnection(id: string) { - applyProviders(await api.del<ModelProviders>(`/api/model-providers/${encodeURIComponent(id)}`)); -} - -function libraryResponse(data: ModelLibrary): ModelLibrary { - if (!data || !Array.isArray(data.variants)) throw new Error('The engine returned an incomplete model list. Retry the operation.'); - return data; -} - -export function lifecycleStatus(s = state) { - return lifecyclePolicy({ connected: s.connection === 'live', streaming: !!s.streaming || s.liveChats > 0, stats: s.serving?.stats, busy: s.busy }); -} -/** The lifecycle status without subscribing to the whole store: a screen that only needs this must not redraw on every monitor tick (round 8, item 13). */ -export function useLifecycle() { - const connected = useStore(s => s.connection === 'live'); - const streaming = useStore(s => !!s.streaming || s.liveChats > 0); - const stats = useStore(s => s.serving?.stats); - const busy = useStore(s => s.busy); - return lifecyclePolicy({ connected, streaming, stats, busy }); -} -export function lifecycleAvailable(): boolean { - const result = lifecycleStatus(); - if (!result.allowed) pushToast('warn', 'Model change unavailable', result.reason); - return result.allowed; -} - -export function useStore<T>(selector: (s: AppState) => T): T { - return useSyncExternalStore( - subscribe, - () => selector(state), - () => selector(state), - ); -} - -/* ------------------------------------------------------------------ toasts */ - -/** Dismissal timers, held so a hovered toast can be paused rather than lost. */ -const toastTimers = new Map<string, ReturnType<typeof setTimeout>>(); -const TOAST_MS = 5200; - -export function pushToast(tone: Toast['tone'], title: string, body?: string) { - const id = uid('toast'); - // Cap the stack: past three, the oldest collapses rather than pushing the - // rest off-screen. A toast nobody can read is not a notification. - const next = [...state.toasts, { id, tone, title, body }]; - const overflow = next.length > 3 ? next.slice(0, next.length - 3) : []; - for (const gone of overflow) { - const t = toastTimers.get(gone.id); - if (t) clearTimeout(t); - toastTimers.delete(gone.id); - } - const kept = overflow.length ? next.slice(-3) : next; - set({ toasts: kept }); - toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS)); -} - -/** - * Stops a toast's clock while the pointer is over it, so reading one does not - * race its own dismissal. Restarting gives a full window rather than the - * remainder — the intent is "I am reading this", and a resumed half-second is - * not enough to act on. - */ -export function holdToast(id: string) { - const t = toastTimers.get(id); - if (t) clearTimeout(t); - toastTimers.delete(id); -} - -export function releaseToast(id: string) { - if (toastTimers.has(id)) return; - if (!state.toasts.some((t) => t.id === id && !t.leaving)) return; - toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS)); -} - -export function dismissToast(id: string) { - const t = toastTimers.get(id); - if (t) clearTimeout(t); - toastTimers.delete(id); - set((s) => ({ toasts: s.toasts.map((x) => (x.id === id ? { ...x, leaving: true } : x)) })); - setTimeout(() => set((s) => ({ toasts: s.toasts.filter((x) => x.id !== id) })), 340); -} - -/* ------------------------------------------------------------------- prefs */ - -/** - * Preferences live on <html> as data attributes plus one custom property, so CSS - * owns presentation and React owns state — the same split the theme already - * used. Nothing here re-renders a screen: the attributes do the work. - */ -function applyPrefs() { - const root = document.documentElement; - setTranslationLanguage(state.language); - root.lang = state.language === 'zh' ? 'zh-CN' : state.language; - if(state.fontFamily)root.style.setProperty('--st-font',`${JSON.stringify(state.fontFamily)},system-ui,-apple-system,"Segoe UI",sans-serif`); - else root.style.removeProperty('--st-font'); - root.dataset.theme = state.theme === 'system' ? matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : state.theme; - document.querySelector<HTMLMetaElement>('meta[name="theme-color"]')?.setAttribute('content', root.dataset.theme === 'dark' ? '#0e1113' : '#f9fafb'); - root.dataset.contrast = state.contrast; - root.dataset.density = state.density; - root.style.setProperty('--st-content-fs', `${state.contentFontSize}px`); - // The interface size (#3970): the whole page is scaled, so every text, button, menu and dialog follows, not only the parts that were - // written with the scale token. The token stays at 1 so nothing is scaled twice. The reading size stays separate: someone who needs - // larger prose does not necessarily want larger buttons. - root.style.setProperty('--st-ui-scale', '1'); - root.style.setProperty('zoom', state.uiScale === 1 ? '' : String(state.uiScale)); - - // "system" means the OS decides, so the attribute is absent rather than set - // to a third value the stylesheet would have to special-case. - if (state.motion === 'system') delete root.dataset.motion; - else root.dataset.motion = state.motion; - - if (state.focus) root.dataset.focus = 'true'; - else delete root.dataset.focus; - - // "translucent" is the default, so the attribute only appears when it is off. - if (state.transparency === 'opaque') root.dataset.transparency = 'opaque'; - else delete root.dataset.transparency; -} - -function savePrefs() { - const snapshot: Prefs = { - sizeDefaults: SIZE_DEFAULTS_VERSION, - language: state.language, - fontFamily: state.fontFamily, - theme: state.theme, - contrast: state.contrast, - rail: state.rail, - focus: state.focus, - contentFontSize: state.contentFontSize, - density: state.density, - motion: state.motion, - transparency: state.transparency, - uiScale: state.uiScale, - electricityPrice: state.electricityPrice, - electricityCurrency: state.electricityCurrency, - doneSound: state.doneSound, - approvalNotify: state.approvalNotify, - whileBusy: state.whileBusy, - shareTelemetry: state.shareTelemetry, - }; - try { - localStorage.setItem(PREFS_KEY, JSON.stringify(snapshot)); - } catch { - /* a full quota must not break the UI */ - } - applyPrefs(); -} - -export function setTheme(theme: 'dark' | 'light' | 'system') { - set({ theme }); - savePrefs(); -} - -export function toggleRail() { - set({ rail: !state.rail }); - savePrefs(); -} -export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();rememberShellLanguage(language);} -let shellAnnounced = false; -/** The desktop shell's tray menu follows the app's language; it reads it from a small file the host keeps (no effect in a browser). */ -function rememberShellLanguage(language:Language){api.post('/api/shell/prefs',{language}).catch(()=>undefined);} -/** The shell started on another port than it wanted: the chats and settings saved on that port are not here, so say so once (#3402). */ -async function announcePortNotice(){ - try{ - const shell=await api.get<{portNotice:{wanted:number;used:number}|null}>('/api/shell'); - if(shell.portNotice)pushToast('warn',tr('Strata could not use its port'),tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.',[shell.portNotice.wanted,shell.portNotice.used])); - }catch{/* a browser or an older host has no shell */} -} -export function setFontFamily(fontFamily:string){set({fontFamily:fontFamily.trim().slice(0,128).replace(/[\x00-\x1f]/g,'')});savePrefs();} - -export function setFocus(focus: boolean) { - set({ focus }); - savePrefs(); -} - -export function toggleFocus() { - setFocus(!state.focus); -} - -/** - * Puts every appearance and reading preference back to its shipped value. - * - * Deliberately excludes `shareTelemetry`: a privacy choice is not an appearance - * setting, and re-enabling reporting as a side effect of resetting one's font - * size would be exactly the kind of thing this control exists to prevent. - * - * Deliberately does **not** touch `rail` or `focus`: those are where you happen - * to be working, not settings you chose, and collapsing the sidebar on someone - * who asked to reset their font size would be a surprise. The engine has its own - * reset, since an expert override and a font size have nothing to do with each - * other. - */ -export function resetAppearance() { - set({ - fontFamily: PREFS_DEFAULTS.fontFamily, - theme: PREFS_DEFAULTS.theme, - contrast: PREFS_DEFAULTS.contrast, - contentFontSize: PREFS_DEFAULTS.contentFontSize, - density: PREFS_DEFAULTS.density, - motion: PREFS_DEFAULTS.motion, - transparency: PREFS_DEFAULTS.transparency, - uiScale: PREFS_DEFAULTS.uiScale, - }); - savePrefs(); -} - -/** - * Records the standing privacy choice. - * - * The control was local component state that nothing persisted and nothing - * read — it snapped back on every reload, so a reader who turned reporting off - * had no way to know their choice had not been recorded. A privacy control that - * silently forgets is worse than no control at all. - */ -export function setShareTelemetry(on: boolean) { - set({ shareTelemetry: on }); - savePrefs(); -} - -export function setContentFontSize(px: number) { - const clamped = Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Math.round(px))); - set({ contentFontSize: clamped }); - savePrefs(); -} - -export function setDensity(density: 'comfortable' | 'compact') { - set({ density }); - savePrefs(); -} - -export function setMotion(motion: 'system' | 'full' | 'reduced') { - set({ motion }); - savePrefs(); -} - -export function setTransparency(transparency: 'translucent' | 'opaque') { - set({ transparency }); - savePrefs(); -} - -/** The electricity price for the Monitor's cost line: a positive price per kWh; 0 turns the line off. The currency is the detected one unless a three-letter code is given (#3628). */ -export function setElectricity(price: number, currency: string) { - const ok = Number.isFinite(price) && price > 0 && price < 1000; - set({ electricityPrice: ok ? Math.round(price * 10000) / 10000 : 0, electricityCurrency: /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : '' }); - savePrefs(); -} - -export function setWhileBusy(whileBusy: WhileBusy) { - if (!validWhileBusy(whileBusy)) return; - set({ whileBusy }); - savePrefs(); -} - -/** A message sent while an answer is being written waits here; the chat sends it when the answer is done (it is also where Interrupt leaves it). */ -export function parkMessage(sessionId: string, text: string) { - const clean = text.trim(); - if (!clean) return; - set({ parked: { ...state.parked, [sessionId]: [...(state.parked[sessionId] ?? []), clean] } }); -} -function setAsks(sessionId: string, list: AgentAsk[]) { - const next = { ...state.agentAsks }; - if (list.length) next[sessionId] = list; else delete next[sessionId]; - set({ agentAsks: next }); -} -/** The agent asked the person something (a frame of the host), or the question ended without an answer. */ -export function addAgentAsk(sessionId: string, frame: { callId?: unknown; questions?: unknown }) { - const ask = readAsk(frame); - // A /loop runs without anyone there: the question is skipped at once, so the loop never waits for an answer. - if (ask && loopScheduler.isRunning(sessionId)) { void answerAgentAsk(sessionId, ask.callId, null).catch(() => {}); return; } - if (ask) setAsks(sessionId, [...(state.agentAsks[sessionId] ?? []).filter(a => a.callId !== ask.callId), ask]); -} -export function removeAgentAsk(sessionId: string, callId?: string) { - const rest = callId === undefined ? [] : (state.agentAsks[sessionId] ?? []).filter(a => a.callId !== callId); - if ((state.agentAsks[sessionId]?.length ?? 0) !== rest.length) setAsks(sessionId, rest); -} -/** Sends the person's answer to the agent, or a skip (answers null). A refusal comes back as an error for the card to say in words. */ -export async function answerAgentAsk(sessionId: string, callId: string, answers: AgentAnswer[] | null) { - await api.post('/api/chat/answer', { sessionId, callId, ...(answers ? { answers } : { skip: true }) }); - removeAgentAsk(sessionId, callId); -} - -/** Puts a turn or a selected passage above the message box. */ -export function addQuote(sessionId: string, text: string, messageId: string, role: 'user' | 'assistant') { - const list = state.quotes[sessionId] ?? []; - const next = addToQuotes(list, { text, messageId, role }); - if (next.length !== list.length) set({ quotes: { ...state.quotes, [sessionId]: next } }); -} -export function removeQuote(sessionId: string, id: string) { - const rest = (state.quotes[sessionId] ?? []).filter(q => q.id !== id); - const next = { ...state.quotes }; - if (rest.length) next[sessionId] = rest; else delete next[sessionId]; - set({ quotes: next }); -} -export function clearQuotes(sessionId: string) { - if (!state.quotes[sessionId]) return; - const next = { ...state.quotes }; - delete next[sessionId]; - set({ quotes: next }); -} - -/** The first parked message of a chat, taken out of the list (to send it, or to give it back to the box). */ -export function takeParked(sessionId: string, index = 0): string | undefined { - const list = state.parked[sessionId] ?? []; - if (index < 0 || index >= list.length) return undefined; - const rest = list.filter((_, i) => i !== index); - const next = { ...state.parked }; - if (rest.length) next[sessionId] = rest; else delete next[sessionId]; - set({ parked: next }); - return list[index]; -} - -export function setDoneSound(doneSound: boolean) { - set({ doneSound }); - savePrefs(); -} - -export function setApprovalNotify(approvalNotify: boolean) { - set({ approvalNotify }); - savePrefs(); -} - -export const UI_SCALES = [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2] as const; - -export function setUiScale(uiScale: number) { - set({ uiScale }); - savePrefs(); -} - -export const CONTENT_FONT_RANGE = { min: CONTENT_FS_MIN, max: CONTENT_FS_MAX }; - -/* -------------------------------------------------------------- workspaces */ - -/** Opens the system folder chooser. Returns null when it is dismissed. */ -export async function pickWorkspace(): Promise<string | null> { - const res = await postWithFolderFallback<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick') as { path?: string }; - return res.path ?? null; -} - -export async function addWorkspace(path: string) { - try { - const ws = await api.post<Workspace>('/api/workspaces', { path }); - set({ workspaces: [...state.workspaces, ws] }); - pushToast('success', 'Workspace added', `Strata can now read files in ${ws.name}.`); - } catch (err) { - pushToast('error', "Couldn't add that folder", err instanceof Error ? err.message : String(err)); - } -} - -/** The name the sidebar shows for a workspace; its folder is unchanged. */ -export async function renameWorkspace(id: string, name: string) { - try { - const ws = await api.patch<Workspace>(`/api/workspaces/${id}`, { name }); - set({ workspaces: state.workspaces.map(w => (w.id === id ? { ...w, name: ws.name } : w)) }); - } catch (err) { - pushToast('error', "Couldn't rename that workspace", err instanceof Error ? err.message : String(err)); - } -} - -export async function removeWorkspace(id: string) { - const ws = state.workspaces.find((w) => w.id === id); - try { - await api.del(`/api/workspaces/${id}`); - set({ workspaces: state.workspaces.filter((w) => w.id !== id) }); - if (state.activeWorkspace === id) set({ activeWorkspace: state.workspaces[0]?.id ?? null }); - } catch (err) { - pushToast('error', "Couldn't remove that workspace", err instanceof Error ? err.message : String(err)); - } - void ws; -} - -/** - * Pins a conversation to the top of its workspace. - * - * Sessions are currently ordered by recency, which is right until you have - * thirty of them and two matter. `Session.pinned` has existed in the type since - * the beginning and was never written to. - */ -export function toggleArchive(id: string) { - const sessions = state.sessions.map((s) => (s.id === id ? { ...s, archived: !s.archived } : s)); - persistSessions(sessions); - set({ sessions }); -} - -export function togglePin(id: string) { - const sessions = state.sessions.map((s) => (s.id === id ? { ...s, pinned: !s.pinned } : s)); - persistSessions(sessions); - set({ sessions }); -} - -export function setActiveWorkspace(id: string) { - set({ activeWorkspace: id }); - void loadWorkspaceFiles(); -} - -export function openSetup(open: boolean) { - set({ setupOpen: open }); -} - -export function setPalette(open: boolean) { - set({ paletteOpen: open }); -} - -export function setShortcuts(open: boolean) { - set({ shortcutsOpen: open }); -} - -/* --------------------------------------------------------------- transport */ - -function applyEvent(e: StreamEvent) { - const data = e.data as Record<string, unknown>; - switch (e.event) { - case 'monitor': - set({ monitor: data as unknown as MonitorState }); - break; - case 'skills': - set({ skills: data as unknown as Skill[] }); - break; - case 'models': - if (Array.isArray(data.variants)) set({ library: data as unknown as ModelLibrary }); - break; - case 'runtime': - set({runtime:data as unknown as RuntimeModels}); - break; - case 'native': - applyNativeEvent(data); - break; - case 'image-models': - if (Array.isArray(data.variants)) set({ imageModels: data as unknown as ImageModelLibrary }); - break; - case 'providers': - applyProviders(data as unknown as ModelProviders); - break; - case 'goal': - if (typeof data.chatId === 'string') applyGoalFrame(data.chatId, data.goal); - break; - case 'plan': - if (typeof data.chatId === 'string') applyPlanFrame(data.chatId, data.plan); - break; - case 'queue': - if (typeof data.chatId === 'string') applyQueueFrame(data.chatId, data.queue); - break; - case 'timeskip': - applyTimeSkipEvent(data); - break; - case 'engine': - set({ engine: data as unknown as EngineConfig }); - break; - case 'serving': - set({ serving: newestServingState(state.serving, data as unknown as ServingState) }); - break; - case 'setup': - set({ setup: data as unknown as SetupState }); - break; - case 'task': { - // A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed. - const t = data as unknown as { title?: string; status?: string; attention?: string | null; error?: string | null }; - if (t.status === 'error') pushToast('error', 'Task failed', String(t.title ?? '')); - else if (t.attention) { pushToast('warn', 'Task needs your yes', String(t.title ?? '')); void approvalNeeded(state.approvalNotify, String(t.title ?? '')); } - else if (t.status === 'done') { pushToast('success', 'Task finished', String(t.title ?? '')); workFinished(state.doneSound, Infinity); } - break; - } - case 'agent': - if (typeof data.sessionId === 'string') patchSession(data.sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], data.agent) })); - break; - default: - break; - } -} - -let closeEvents: (() => void) | null = null; -export async function bootstrap() { - applyPrefs(); - try { - const [setup, hardware, library, engine, serving, monitor, skills, providers, imageModels, runtime] = await Promise.all([ - api.get<SetupState>('/api/setup'), - api.get<Hardware>('/api/hardware'), - api.get<ModelLibrary>('/api/models'), - api.get<EngineConfig>('/api/engine'), - api.get<ServingState>('/api/serving'), - api.get<MonitorState>('/api/monitor'), - api.get<Skill[]>('/api/skills'), - api.get<ModelProviders>('/api/model-providers'), - api.get<ImageModelLibrary>('/api/image-models'), - api.get<RuntimeModels>('/api/runtime'), - ]); - const workspaceState = await api.get<{ workspaces: Workspace[] }>('/api/workspaces'); - set({ - ready: true, - setup, - hardware, - library: libraryResponse(library), - imageModels, - runtime, - engine, - serving: newestServingState(state.serving, serving), - monitor, - skills, - workspacePath: workspaceState.workspaces[0]?.path ?? '', - workspaces: workspaceState.workspaces, - 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); - if (!shellAnnounced) { shellAnnounced = true; void announcePortNotice(); rememberShellLanguage(state.language); } - closeEvents?.(); - let reconnect = false; - closeEvents = onEvent(applyEvent, (status) => { - if (status === 'offline') reconnect = true; - if (status === 'live' && reconnect) { - reconnect = false; - // The restarted host may have new logs, config or readiness. Refresh - // those facts in place while retaining conversations and unsent drafts. - void bootstrap(); - return; - } - set({ connection: status }); - }); - if (!setup.complete && !setup.dismissed && !window.location.hash.includes('setup')) navigate('setup'); - } catch (err) { - set({ ready: true, connection: 'offline' }); - pushToast( - 'error', - 'Engine host unreachable', - err instanceof Error ? err.message : 'Start it with `npm run host` and reload.', - ); - } -} - -/* ------------------------------------------------------------- reads/writes */ - -export async function refreshHardware() { - set((s) => ({ busy: { ...s.busy, hardware: true } })); - try { - set({ hardware: await api.get<Hardware>('/api/hardware?reprobe=1') }); - } finally { - set((s) => ({ busy: { ...s.busy, hardware: false } })); - } -} - -function modelFits(id: string) { - const model = state.library?.variants.find(v => v.id === id); - if (state.library?.mode === 'real' && model && state.hardware && state.engine && ['too-large', 'unsupported'].includes(estimate(model, state.hardware, execution(Object.fromEntries(state.engine.expert.map(p => [p.id, p.value])), contextTokens(state.engine.beginner.contextLength))).fit)) { - pushToast('warn', 'Choose a smaller model', 'The estimated memory requirement exceeds this computer.'); - return false; - } - return true; -} - -export async function selectImageModel(selected: ImageModelChoice) { - set(s => ({ busy: { ...s.busy, 'image:select': true } })); - try { set({ imageModels: await api.patch<ImageModelLibrary>('/api/image-models', { selected }) }); } - finally { set(s => ({ busy: { ...s.busy, 'image:select': false } })); } -} -export async function installImageModel(id: Exclude<ImageModelChoice, 'off'>) { - set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/install`) }); -} -export async function cancelImageModel(id: Exclude<ImageModelChoice, 'off'>) { - set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/cancel`) }); -} -export async function applyImageModel() { - set({ imageModels: await api.post<ImageModelLibrary>('/api/image-models/apply') }); -} - -export async function installVariant(id: string) { - // Download eligibility is checked against disk space by the host. Runtime fit - // is reviewed separately when the model is loaded. - if (state.busy[`install:${id}`]) return false; - set((s) => ({ busy: { ...s.busy, [`install:${id}`]: true } })); - try { - const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/install`)); - set({ library }); - const complete = library.variants.find(v => v.id === id)?.state === 'installed'; - pushToast(complete ? 'success' : 'info', complete ? 'Files installed' : library.mode === 'simulated' ? 'Example installation started' : 'Download started', complete ? 'Load the model to start a request.' : 'Progress is shown in Models.'); - return true; - } catch (err) { - pushToast('error', 'Download failed', err instanceof Error ? err.message : undefined); - return false; - } finally { - set((s) => ({ busy: { ...s.busy, [`install:${id}`]: false } })); - } -} - -export async function cancelInstall(id: string) { - try { set({ library: libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/cancel`)) }); } catch (e) { pushToast('error', 'Cancel failed', e instanceof Error ? e.message : String(e)); } -} - -export async function loadVariant(id: string) { - if (!modelFits(id)) return false; - if (!lifecycleAvailable()) return false; - set((s) => ({ busy: { ...s.busy, [`load:${id}`]: true }, actionError: null })); - try { - const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/load`)); - set({ library }); - const model = library.variants.find(v => v.id === id); - if (library.loaded !== id || model?.state !== 'loaded') throw new Error(model?.error ?? 'The model did not finish loading.'); - pushToast('success', library.mode === 'simulated' ? 'Example model ready' : 'Model loaded', library.mode === 'simulated' ? 'Answers are simulated samples, not from a real model.' : 'Ready for a request.'); - return true; - } catch (err) { - const message = err instanceof Error ? err.message : 'The model did not load.'; - set({ - actionError: { - label: 'Could not load model', - message, - retry: () => void loadVariant(id), - }, - }); - pushToast('error', 'Could not load model', message); - return false; - } finally { - set((s) => ({ busy: { ...s.busy, [`load:${id}`]: false } })); - } -} - -export async function unloadModel() { - if (!lifecycleAvailable()) return false; - set(s => ({ busy: { ...s.busy, unload: true } })); - try { - const previousInstance=state.runtime?.defaultId; - const library = libraryResponse(await api.post<ModelLibrary>('/api/models/unload')); - const runtime=await api.get<RuntimeModels>('/api/runtime'); - set({runtime}); - set({ library }); - if (previousInstance?runtime.instances.some(i=>i.id===previousInstance):library.loaded!==null) throw new Error('The engine still reports this model instance as loaded.'); - pushToast('info', 'Model unloaded', library.mode === 'simulated' ? 'Example load state cleared.' : 'Model memory released.'); - return true; - } catch (err) { pushToast('error', 'Unload failed', err instanceof Error ? err.message : String(err)); return false; } - finally { set(s => ({ busy: { ...s.busy, unload: false } })); } -} - -export async function removeVariant(id: string) { - if (state.library?.loaded === id && !lifecycleAvailable()) return false; - const local = !!state.library?.variants.find(v => v.id === id)?.local; - try { const library = libraryResponse(await api.del<ModelLibrary>(`/api/models/${id}`)); set({ library }); - const remaining = library.variants.find(v => v.id === id); - if (remaining && remaining.state !== 'available') throw new Error('The model files were not removed.'); - pushToast('success', local ? 'Local model removed' : 'Files removed', local ? 'The original GGUF files are kept.' : library.mode === 'simulated' ? 'Example install state cleared.' : 'Model files removed from disk.'); return true; - } catch (e) { pushToast('error', 'Remove failed', e instanceof Error ? e.message : String(e)); return false; } -} - -export async function waitForInstalled(id: string) { - const deadline = Date.now() + 60 * 60 * 1000; - while (Date.now() < deadline) { - const v = state.library?.variants.find(v => v.id === id); - if (v && ['installed', 'loaded'].includes(v.state)) return; - if (!v || ['available', 'error'].includes(v.state)) throw new Error(v?.error ?? 'Download cancelled.'); - await new Promise(resolve => setTimeout(resolve, 500)); - } - throw new Error('Download timed out. Try again from Models.'); -} - -export async function saveEngine(patch: Partial<EngineConfig> | Record<string, unknown>, silent = false, requireIdle = false) { - if (requireIdle) { - const status = lifecycleStatus(); - if (!status.allowed) throw new Error(status.reason); - } - const engine = await api.patch<EngineConfig>('/api/engine', patch); - set({ engine, actionError: null }); - if (!silent) pushToast('success', 'Settings saved', 'Load settings take effect on the next load. Sampling defaults affect the next request.'); - return engine; -} - -export async function restartEngine() { - if (state.library?.mode === 'simulated') { pushToast('info', 'Restart unavailable with the example engine', 'Save settings for the next load.'); return false; } - if (!lifecycleAvailable()) return false; - set((s) => ({ busy: { ...s.busy, restart: true }, actionError: null })); - try { - const engine = await api.post<EngineConfig>('/api/engine/restart'); - set({ engine }); - if (!engine.engine.running) throw new Error(engine.engine.error ?? 'The engine is not running. Load a model before applying settings.'); - pushToast('success', 'Engine restarted', 'Warm-up takes a few seconds.'); - return true; - } catch (err) { - // Reported in place as well as in a toast: the toast is a summary, the - // surface that failed is where the retry belongs. - set({ - actionError: { - label: 'Restart failed', - message: err instanceof Error ? err.message : 'The engine did not come back up.', - retry: () => void restartEngine(), - }, - }); - pushToast('error', 'Restart failed', err instanceof Error ? err.message : undefined); - return false; - } finally { - set((s) => ({ busy: { ...s.busy, restart: false } })); - } -} - -export function dismissActionError() { - set({ actionError: null }); -} - -export async function resetEngine() { - set({ engine: await api.post<EngineConfig>('/api/engine/reset') }); - pushToast('info', 'Back to recommended', 'Every value returned to the safe default.'); -} - -/** - * Checks an engine config — the saved one by default, or a draft to preview what - * a change would do before committing to it. - */ -export async function validateEngine(draft?: unknown) { - return api.post<{ - ok: boolean; - issues: { level: 'warn' | 'error'; message: string }[]; - predicted?: EngineConfig['predicted']; - }>('/api/engine/validate', draft ?? {}); -} - -export async function exportEngine() { - return api.get<Record<string, unknown>>('/api/engine/export'); -} - -export async function setCloudflare(body: {action: 'start' | 'stop' | 'prepare'; mode?: 'quick' | 'domain'; hostname?: string; token?: string}) { - const result = await api.post<ServingState>('/api/serving/tunnel', body); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function setLocalSharing(enabled: boolean) { - const result = await api.post<ServingState>('/api/serving/share', { enabled }); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function setServingAccess(patch: { otherDevices?: boolean; apiKey?: string | null }) { - const result = await api.patch<ServingState>('/api/serving', patch); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function pauseServing(paused: boolean) { - const result = await api.patch<ServingState>('/api/serving', { pauseServing: paused }); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function cancelRequest(id: string) { - const result = await api.post<ServingState>(`/api/serving/requests/${id}/cancel`); - set({ serving: newestServingState(state.serving, result) }); -} - -export async function completeSetupStep(step: number, choices?: SetupState['choices'], dismissed = false) { - set({ setup: await api.post<SetupState>('/api/setup/step', { step, choices, dismissed, flowVersion: 2 }) }); -} - -export async function completeSetup() { - const setup = await api.post<SetupState>('/api/setup/complete'); - set({ setup }); -} - -export async function setSkills(skills: Skill[]) { - set({ skills }); -} - -/** - * Re-reads the skill list from the host. - * - * For the case where a skill was added to the workspace folder while the app was - * open — otherwise the only way to see it is to restart. - */ -export async function loadSkills() { - set({ skills: await api.get<Skill[]>('/api/skills') }); -} - -/** Re-reads the workspace tree from disk, for the same reason. */ -export async function loadWorkspaceFiles() { - const data = await api.get<{ path: string; entries: WorkspaceFile[] }>(`/api/workspace${state.activeWorkspace ? '?root=' + encodeURIComponent(state.activeWorkspace) : ''}`); - set({ files: data.entries, workspacePath: data.path }); -} - -export async function toggleSkill(id: string, enabled: boolean) { - set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { enabled }) }); -} - -export async function editSkill(id: string, patch: Pick<Skill, 'name' | 'description' | 'body' | 'triggers' | 'enabled' | 'onlyIn'>) { - set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, patch) }); -} - -/** - * Narrows a skill to the workspace you are in, or widens it again. - * - * Passing null clears the narrowing. The host resolves `onlyIn` against the - * workspace the request came from, so the answer depends on where the reader - * is rather than on a single global switch. - */ -export async function scopeSkill(id: string, workspaceId: string | null) { - set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { onlyIn: workspaceId }) }); -} - -/* ---------------------------------------------------------------- sessions */ - -const sessionWriter = createSessionWriter({ - write: (json) => { - try { - localStorage.setItem(SESSION_KEY, json); - } catch { - /* quota — sessions are a cache, not the source of truth */ - } - }, -}); - -/** - * Save the chat list. A one-off change (new, rename, delete, pin) is written now; `soon` is for the streaming - * path, where a write per token grew the renderer to gigabytes (#3604, #3603): those are coalesced to one a second. - */ -function persistSessions(sessions: Session[], soon = false) { - sessionWriter.schedule(sessions); - if (!soon) sessionWriter.flush(); -} - -/** Write the newest chat list now: a turn ended, or the page is going away. */ -export function flushSessions() { - sessionWriter.flush(); -} - -if (typeof window !== 'undefined' && typeof document !== 'undefined' && window.addEventListener) { - window.addEventListener('pagehide', flushSessions); - document.addEventListener?.('visibilitychange', () => { if (document.visibilityState === 'hidden') flushSessions(); }); -} - -export function newSession(): Session { - const session: Session = { - id: uid('s'), - title: 'New conversation', - defaultTitle: true, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - messages: [], - workspace: state.workspaces.find(w => w.id === state.activeWorkspace)?.path ?? state.workspacePath, - tokensIn: 0, - tokensOut: 0, - ...(state.activeSession === null && state.remoteModel ? { preferences: { remoteModel: state.remoteModel } } : {}), - }; - const sessions = [session, ...state.sessions]; - persistSessions(sessions); - set({ sessions, activeSession: session.id }); - return session; -} - -export function setChatPreferences(id: string | undefined, preferences: NonNullable<Session['preferences']>) { - const sessionId = id ?? newSession().id; - patchSession(sessionId, s => ({ ...s, preferences: { ...s.preferences, ...preferences } })); - // A mode change applies to the very next tool call of a turn that is already running (a goal and its helpers included). - if (preferences.mode && liveTurns.get(sessionId)?.agent) void api.post('/api/chat/mode', { sessionId, mode: preferences.mode }).catch(() => undefined); -} -export function setPreviewTabClosed(sessionId:string|undefined, artifactId:string, closed:boolean, selected:string|null) { - if(!sessionId)return; - patchSession(sessionId,s=>({...s,closedPreviews:closed?[...new Set([...(s.closedPreviews??[]),artifactId])]:(s.closedPreviews??[]).filter(id=>id!==artifactId),previewOpen:selected??undefined})); -} -export function createChatShowcase() { - const session=newSession();const at=new Date().toISOString(); - patchSession(session.id,s=>({...s,title:'Chat showcase · code, tools & media',showcase:true,statsAvailable:true,tokensIn:28000000,tokensOut:4000000,messages:showcaseMessages(at),agents:SHOWCASE_AGENTS,showcaseAgentStates:true})); - go('chat',session.id); -} - -/** A visible example for checking the subagent interface in the design build. */ -export function createSubagentExample() { - const session = newSession(); const now = Date.now(); - patchSession(session.id, s => ({ ...s, title: 'Subagent preview', showcase: true, showcaseAgentStates: true, - agents: [ - {id:'example-layout',name:'Layout review',description:'Checking spacing and component alignment.',status:'working',durationMs:39000,tokens:12600,updatedAt:now}, - {id:'example-interactions',name:'Interaction review',description:'Checking menus, controls and keyboard navigation.',status:'working',durationMs:21000,tokens:8400,updatedAt:now}, - {id:'example-copy',name:'Copy review',description:'Labels and descriptions reviewed.',status:'completed',durationMs:18000,tokens:4200,updatedAt:now}, - ], messages: [{id:uid('m'),role:'assistant',at:new Date(now).toISOString(),example:true,content:'Open the subagent count above to inspect this example run. Each row shows status, token usage and elapsed time.'}] - })); - go('chat', session.id); -} - -export function createPreviewExamples() { - const session = newSession(); - const at = new Date().toISOString(); - patchSession(session.id, s => ({ ...s, title: 'Design review · six previews', previewOpen:'sample-website', messages: [ - { id:uid('m'), role:'user', at, content:'Open six different output types so I can iterate on the preview design.' }, - { id:uid('m'), role:'assistant', at, demo:true, content:'Here is a design-review workspace for Fieldnotes: a website, PDF, Markdown brief, cover image, TypeScript file and release table.\n\nAll six are loaded in the panel on the right. Switch tabs to explore each view while keeping this conversation in place.', artifacts:PREVIEW_EXAMPLES }, - ] })); - go('chat', session.id); -} - -/** "Continue in a new chat" on a task: a new chat whose first message is the task's findings, what it did and its files (src/lib/task-handover.ts). */ -export function continueTaskInNewChat(task: Task) { - const session = newSession(); - go('chat', session.id); - void sendMessage(taskHandoverMessage(task), { title: taskHandoverTitle(task), markdown: true }); -} - -export function selectSession(id: string) { - // 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); -} - -/** Records that a conversation has been looked at. */ -export function markRead(id: string) { - const at = new Date().toISOString(); - const sessions = state.sessions.map((s) => (s.id === id ? { ...s, lastReadAt: at } : s)); - persistSessions(sessions); - set({ sessions }); -} - -/** - * Whether a conversation has moved on since it was last looked at. - * - * The active conversation is never unread: you are looking at it, or its reply - * is arriving in front of you. - */ -export function isUnread(s: Session, activeSession: string | null): boolean { - if (s.id === activeSession) return false; - if (!s.lastReadAt) return s.messages.length > 0; - return s.updatedAt > s.lastReadAt; -} - -export function deleteSession(id: string) { - const sessions = state.sessions.filter((s) => s.id !== id); - persistSessions(sessions); - set({ sessions, activeSession: state.activeSession === id ? (sessions[0]?.id ?? null) : state.activeSession }); -} - -export function renameSession(id: string, title: string) { - const sessions = state.sessions.map((s) => (s.id === id ? { ...s, title, defaultTitle: false } : s)); - persistSessions(sessions); - set({ sessions }); -} - -function patchSession(id: string, fn: (s: Session) => Session) { - const sessions = state.sessions.map((s) => (s.id === id ? fn(s) : s)); - persistSessions(sessions, true); - set({ sessions }); -} - -// The demo clock belongs to the session, so hiding the sidebar or navigating -// away never pauses it. Only start and completion are written to storage. -const timeSkipTimers = new Map<string, ReturnType<typeof setTimeout>>(); -function scheduleTimeSkip(sessionId: string, run: TimeSkipRun) { - const timerId = `${sessionId}:${run.id}`; - clearTimeout(timeSkipTimers.get(timerId)); - if (run.completedAt || run.job) return; - timeSkipTimers.set(timerId, setTimeout(() => { - timeSkipTimers.delete(timerId); - const session = state.sessions.find(s => s.id === sessionId); - const current = session?.timeSkips?.find(r => r.id === run.id); - if (!current || current.startedAt !== run.startedAt || !session?.messages.some(m => m.timeSkipId === run.id && m.role === 'assistant')) return; - patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(), - timeSkips: s.timeSkips?.map(r => r.id === run.id ? { ...r, completedAt: run.startedAt + TIME_SKIP_DURATION } : r), - messages: s.messages.map(m => m.timeSkipId === run.id && m.role === 'assistant' ? { ...m, content: 'The updated result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.' } : m), - })); - }, Math.max(0, run.startedAt + TIME_SKIP_DURATION - Date.now()))); -} - -export function replayTimeSkip(sessionId: string, runId: string) { - const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); - if (!run) return; - const next = { ...run, startedAt: Date.now(), completedAt: undefined, retainedVersion: undefined }; - patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r), - messages: s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.' } : m), - })); - scheduleTimeSkip(sessionId, next); -} - -export function setTimeSkipResult(sessionId: string, runId: string, version: TimeSkipVersion) { - const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); - if (!run) return; - if (run.job) { void keepTimeSkip(sessionId, runId, version); return; } - const next = withTimeSkipResult(run, version, Date.now()); - if (next === run) return; - patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r) })); -} - -/* ------------------------------------------------------- Time-skip, for real - The host copies the chat's folder, lets the assistant change the copy, checks it and keeps the original untouched until the - person chooses. The sidebar follows the job's own record; nothing here invents progress. */ -const TS_TERMINAL = ['completed', 'cancelled', 'failed', 'interrupted']; -const TS_WORKING = () => tr('Working on a copy of your files. Follow the progress in the sidebar.'); -const TS_READY = () => tr('The result is ready. Switch between Original and Updated, or compare them side by side.'); - -function patchRun(sessionId: string, runId: string, fn: (run: TimeSkipRun) => TimeSkipRun, content?: string) { - patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(), - timeSkips: s.timeSkips?.map(r => r.id === runId ? fn(r) : r), - messages: content === undefined ? s.messages : s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content } : m), - })); -} - -/** The job's error in a sentence a person can use. */ -export function plainTimeSkipError(raw: string | null | undefined): string { - const text = String(raw ?? '').trim(); - if (!text) return tr('Something went wrong.'); - const afterExit = /\(exit \d+\):\s*([\s\S]*)$/.exec(text); - const body = (afterExit?.[1] ?? text).replace(/^\w*Error:\s*/, '').trim(); - if (/destination changed|refusing to overwrite/i.test(body)) return tr('Your files changed after this trial started, so nothing was overwritten. Run Time-skip again.'); - if (/too big/i.test(body)) return tr('This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.'); - if (/folder of your own/i.test(body)) return tr('Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.'); - if (/Load a model|model first/i.test(body)) return tr('Load a model first, then try Time-skip again.'); - if (/needs the Strata app|could not be reached/i.test(body)) return tr('The assistant could not be reached. Try again.'); - return body.length > 300 ? body.slice(0, 299) + '…' : body; -} - -/** The host says a Time-skip run moved on (phase, and what it is doing now): the working view shows the newest words. */ -function applyTimeSkipEvent(data: Record<string, unknown>) { - const id = typeof data.id === 'string' ? data.id : ''; - if (!id) return; - for (const session of state.sessions) { - const run = session.timeSkips?.find(r => r.job?.id === id); - if (!run || run.completedAt) continue; - patchRun(session.id, run.id, r => ({ ...r, job: { ...r.job!, ...(typeof data.phase === 'string' ? { phase: data.phase as TimeSkipJob['phase'] } : {}), activity: data.activity as TimeSkipJob['activity'], ...forkFields(data) } })); - } -} - -function timeSkipEnding(job: TimeSkipJob, files: TimeSkipFile[]): string { - if (job.phase === 'failed') return tr('Time-skip stopped. {0} Your files were not changed.', [plainTimeSkipError(job.error)]); - if (job.phase === 'cancelled' || job.phase === 'interrupted') return tr('Time-skip was stopped before it finished. Your files were not changed.'); - if (!files.length) return tr('The assistant did not change anything, so there is nothing to compare. Your files were not changed.'); - return isForkJob(job) ? tr('Both versions are ready. Compare A and B, then keep one.') : TS_READY(); -} - -async function startTimeSkipReal(prompt: string) { - const sessionId = state.activeSession ?? newSession().id; - const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now(), - job: { id: '', phase: 'queued', attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: false, error: null } }; - const at = new Date().toISOString(); - patchSession(sessionId, s => ({ ...s, - defaultTitle: false, - title: s.messages.length ? s.title : prompt.length > 48 ? prompt.slice(0, 47).trimEnd() + '…' : prompt, updatedAt: at, - // The comparison sidebar opens only when there is an update to compare (when the job ends with changed files), never while it works. - timeSkips: [...(s.timeSkips ?? []), run], - messages: [...s.messages, - { id: uid('m'), role: 'user', at, content: '/time-skip ' + prompt, timeSkipId: run.id }, - { id: uid('m'), role: 'assistant', at, timeSkipId: run.id, content: TS_WORKING() }, - ], - })); - go('chat', sessionId); - markTurn(sessionId, { abort: new AbortController(), agent: false }); - try { - const started = await api.post<{ run: TimeSkipJob }>('/api/timeskip/start', { prompt, sessionId, workspaceId: state.activeWorkspace, attempts: 1, ...(state.remoteModel ? { remoteModel: state.remoteModel } : {}) }); - patchRun(sessionId, run.id, r => ({ ...r, job: started.run })); - void followTimeSkip(sessionId, run.id); - } catch (e) { - const message = plainTimeSkipError(e instanceof Error ? e.message : String(e)); - patchRun(sessionId, run.id, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'failed', error: message } }), tr('Time-skip could not start. {0}', [message])); - markTurn(sessionId, null); - } -} - -const followingTimeSkips = new Set<string>(); -/** Read the job's record until it ends. Safe to call again for a run already being followed. */ -export async function followTimeSkip(sessionId: string, runId: string) { - const key = sessionId + ':' + runId; - if (followingTimeSkips.has(key)) return; - followingTimeSkips.add(key); - let misses = 0; - try { - for (;;) { - const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); - if (!run?.job?.id || run.completedAt) return; - let job: TimeSkipJob | null = null; - try { job = (await api.get<{ run: TimeSkipJob }>('/api/timeskip/status?id=' + encodeURIComponent(run.job.id))).run; misses = 0; } - catch { misses += 1; } - if (job && TS_TERMINAL.includes(job.phase)) { - let files: TimeSkipFile[] = [], extra: Partial<TimeSkipJob> = {}; - // The changed files are what the person came for: ask again a few times before settling for "nothing to compare". - for (let tryNo = 0; tryNo < 4; tryNo++) { - try { - const found = await api.get<{ files: TimeSkipFile[]; applyAttempt: number | null; more: number }>('/api/timeskip/files?id=' + encodeURIComponent(job.id)); - files = found.files; extra = { files: found.files, applyAttempt: found.applyAttempt, moreFiles: found.more }; - break; - } catch { await new Promise(r => setTimeout(r, 700 * (tryNo + 1))); } - } - const finished = { ...job, ...forkFields(job as unknown as Record<string, unknown>) }; - patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, ...finished, ...extra } }), timeSkipEnding(finished, files)); - // A run that changed files opens the comparison; one that changed nothing, failed or was stopped has no sidebar tab. - if (files.length > 0 && !['failed', 'cancelled', 'interrupted'].includes(finished.phase)) patchSession(sessionId, s => ({ ...s, previewOpen: timeSkipTabId(runId) })); - markTurn(sessionId, null); - return; - } - if (job) { const live = { ...job, ...forkFields(job as unknown as Record<string, unknown>) }; patchRun(sessionId, runId, r => ({ ...r, job: { ...r.job!, ...live } })); } - if (misses >= 6) { - patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'interrupted' } }), tr('Time-skip lost contact with the app and stopped. Your files were not changed.')); - markTurn(sessionId, null); - return; - } - await new Promise(r => setTimeout(r, 2000)); - } - } finally { followingTimeSkips.delete(key); } -} - -/** Ask the host to stop a running trial. The saved version stays. */ -export async function stopTimeSkip(sessionId: string, runId: string) { - const id = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId)?.job?.id; - if (id) await api.post('/api/timeskip/stop', { id }).catch(() => undefined); -} - -/** Put the update into the person's files, or put the original back. Both are checked and undoable. */ -export async function keepTimeSkip(sessionId: string, runId: string, version: TimeSkipVersion) { - const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); - const job = run?.job; - if (!run || !job?.id || !job.phase || !TS_TERMINAL.includes(job.phase)) return; - if ((run.retainedVersion ?? 'original') === version && !(isForkJob(job) && run.retainedVersion === undefined)) { patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); return; } - try { - if (isForkJob(job)) await api.post('/api/timeskip/apply', { id: job.id, which: version === 'original' ? 'a' : 'b' }); - else if (version === 'updated') await api.post('/api/timeskip/apply', { id: job.id, attempt: job.applyAttempt ?? null }); - else await api.post('/api/timeskip/apply', { id: job.id, restore: true }); - patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); - pushToast('success', version === 'updated' ? tr('The update is now in your files') : tr('Your original files are back')); - } catch (e) { - pushToast('error', tr('Your files were not changed'), plainTimeSkipError(e instanceof Error ? e.message : String(e))); - } -} - -function startTimeSkipDemo(prompt: string) { - if (!prompt) { pushToast('info', 'Add a prompt after /time-skip', 'For example: /time-skip Make a launch plan for my app'); return; } - const sessionId = state.activeSession ?? newSession().id; - const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now() }; - const at = new Date().toISOString(); - patchSession(sessionId, s => ({ ...s, - defaultTitle: false, - title: s.messages.length ? s.title : prompt.length>48?prompt.slice(0,47).trimEnd()+'…':prompt, updatedAt: at, - timeSkips: [...(s.timeSkips ?? []), run], previewOpen: timeSkipTabId(run.id), - messages: [...s.messages, - { id: uid('m'), role: 'user', at, content: `/time-skip ${prompt}`, timeSkipId: run.id }, - { id: uid('m'), role: 'assistant', at, example: true, timeSkipId: run.id, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks; it doesn’t run your model.' }, - ], - })); - scheduleTimeSkip(sessionId, run); - go('chat', sessionId); -} - -function markTurn(sessionId: string, turn: { abort: AbortController; agent: boolean } | null) { - if (turn) liveTurns.set(sessionId, turn); else liveTurns.delete(sessionId); - set({ streaming: !!state.activeSession && liveTurns.has(state.activeSession), liveChats: liveTurns.size }); - document.documentElement.dataset.streaming = liveTurns.size ? 'true' : 'false'; -} - -/** - * Stop the open chat's turn. The host is asked first: for an agent turn it cancels exactly this chat's - * Harness session and answers only once the turn has ended, and the stream then closes by itself with - * what was produced. For any other turn the host reports nothing to stop and the request is aborted. - */ -export function stopStreaming() { - const id = state.activeSession; - const turn = id ? liveTurns.get(id) : undefined; - if (!id || !turn) return; - const abort = () => { turn.abort.abort(); }; - void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then( - result => { - if (!result.stopped) abort(); - // An agent turn that was told to stop but is slow to end must not leave the chat stuck. - else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); - }, - abort, - ); -} - -/** - * Re-runs the last exchange: drops the assistant reply and asks again. - * - * Kept in the store rather than the screen because it has to touch the message - * list, and every attempt to do this from a component ends up duplicating the - * stream handling that already lives here. - */ -export async function retryLast(messageId?: string) { - const source = state.sessions.find(s => s.id === state.activeSession); - if (!source || state.streaming) return; - const end = messageId ? source.messages.findIndex(m => m.id === messageId) : source.messages.length - 1; - const user = source.messages.slice(0, end + 1).reverse().find(m => m.role === 'user'); - if (!user) return; - const prompt = rewindTo(user.id); - if (prompt !== null) { - // Retry sends immediately; only Edit should leave the prompt in the composer. - sessionStorage.setItem(`strata.chat-draft.${state.activeSession}`, ''); - await sendMessage(prompt); - } -} - -/** The open chat's last question and the answer that failed under it (null when the chat does not end that way). */ -function failedExchange(): { prompt: string; sessionId: string } | null { - const sessionId = state.activeSession; - const chat = state.sessions.find(s => s.id === sessionId); - if (!sessionId || !chat || state.streaming) return null; - const reply = chat.messages[chat.messages.length - 1], ask = chat.messages[chat.messages.length - 2]; - return reply?.role === 'assistant' && reply.error && ask?.role === 'user' ? { prompt: ask.content, sessionId } : null; -} -/** Takes the failed question and its error out of the transcript, so asking again does not show the question twice. */ -function dropFailedExchange(sessionId: string) { - patchSession(sessionId, s => ({ ...s, messages: s.messages.slice(0, -2) })); -} - -/** - * The error card of a conversation that no longer fits the model's window: summarise the older messages (the same as typing /compact), then - * ask the assistant to answer. The refused question is already in the assistant's conversation (it is the newest message, and a summary keeps - * the newest message as it is), so it is not sent a second time: a large one twice would not fit either. - */ -export async function summarizeAndContinue() { - if (!failedExchange()) return; - await sendMessage('/compact'); - await sendMessage('Please answer my last message now.'); -} - -/** - * The error card of a message that is too large to send: the host makes it small enough (its text as a file in the chat's folder that the - * assistant reads in parts, or a shortened preview), and that is sent in its place. - */ -export async function sendOversized(mode: 'file' | 'preview') { - const failed = failedExchange(); - if (!failed) return; - let reply: { message?: string }; - try { - reply = await api.post<{ message?: string }>('/api/chat/oversize', { sessionId: failed.sessionId, mode, text: failed.prompt, nativeModelId: nativeState()?.instances.length ? nativeState()?.defaultId : undefined }); - } catch { - pushToast('error', 'The message could not be prepared. Try a shorter message.'); - return; - } - if (!reply.message) return; - dropFailedExchange(failed.sessionId); - await sendMessage(reply.message); -} - -/** A new, empty chat, opened. */ -export function startNewChat() { - const session = newSession(); - go('chat', session.id); -} - -/** - * Forks a conversation at a message, leaving the original untouched. - * - * The alternative people reach for is duplicating the whole session and - * deleting messages by hand, which loses the original. Branching keeps both: - * the new session carries the history up to the chosen turn and diverges there. - */ -export function branchFrom(messageId: string): string | null { - const sessionId = state.activeSession; - if (!sessionId) return null; - const source = state.sessions.find((s) => s.id === sessionId); - if (!source) return null; - const at = source.messages.findIndex((m) => m.id === messageId); - if (at < 0) return null; - - const now = new Date().toISOString(); - const branch: Session = { - ...source, - id: uid('s'), - title: `${source.title} (branch)`, - defaultTitle: false, - createdAt: now, - updatedAt: now, - messages: source.messages.slice(0, at + 1).map((m) => ({ ...m, id: uid('m') })), - tokensIn: 0, - tokensOut: source.messages.slice(0, at + 1).reduce((n, m) => n + (m.tokens ?? 0), 0), - statsAvailable: false, - }; - const sessions = [branch, ...state.sessions]; - persistSessions(sessions); - set({ sessions, activeSession: branch.id }); - for (const run of branch.timeSkips ?? []) scheduleTimeSkip(branch.id, run); - // The URL wins over `activeSession` when it names a session, so a programmatic - // switch has to move the route too — otherwise the sidebar shows the branch - // while the transcript still shows the original, which reads as a broken - // button rather than a created branch. - navigate('chat', branch.id); - return branch.id; -} - -/** - * Asks the model to keep going from where it stopped. - * - * Sent as an ordinary user turn rather than a special mode, because that is - * what it is: a continuation is a request, and the transcript should show it. - */ -export async function continueLast() { - const sessionId = state.activeSession; - if (!sessionId || state.streaming) return; - const session = state.sessions.find((s) => s.id === sessionId); - const last = session?.messages[session.messages.length - 1]; - if (!last || last.role !== 'assistant' || !last.content.trim()) return; - await sendMessage('Continue from where you left off. Do not repeat what you have already written.'); -} - -/** - * Rewinds the transcript to just before a turn so it can be re-asked with a - * different prompt. Returns the text so the composer can be filled with it. - */ -export function rewindTo(messageId: string): string | null { - if (state.streaming) return null; - const source = state.sessions.find(s => s.id === state.activeSession); - const at = source?.messages.findIndex(m => m.id === messageId) ?? -1; - if (!source || at < 0) return null; - const prompt = source.messages[at].content; - const branchId = branchFrom(messageId); - if (!branchId) return null; - patchSession(branchId, s => ({ ...s, messages: s.messages.slice(0, -1), tokensIn: 0, tokensOut: s.messages.slice(0, -1).reduce((n, m) => n + (m.tokens ?? 0), 0) })); - sessionStorage.setItem(`strata.chat-draft.${branchId}`, prompt); - return prompt; -} - -export function exportConversation() { - const session = state.sessions.find(s => s.id === state.activeSession); - if (!session) return; - const text = '# ' + session.title + '\n\n' + session.messages.map(m => '## ' + m.role + '\n\n' + (m.role === 'assistant' ? tidyAnswer(m.content) : m.content)).join('\n\n'); - const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown' })); - const a = document.createElement('a'); a.href = url; a.download = session.title.replace(/[^a-z0-9 -]/gi, '').slice(0, 60) + '.md'; - document.body.append(a); a.click(); a.remove(); - // Keep the Blob alive until browsers have started consuming the download. - setTimeout(() => URL.revokeObjectURL(url), 1000); -} - -/* ---------------------------------------------------------------- /loop - The same message, again and again, while the chat is open. The scheduler (count, time, "the answer says it is done") is - lib/loop-runner.ts; this is the part that talks to the chat. See lib/loop.ts. */ - -/** A line from the app itself (not the model) in the transcript. It is never sent to the model. */ -function addNote(sessionId: string, content: string) { - const at = new Date().toISOString(); - patchSession(sessionId, s => ({ ...s, updatedAt: at, messages: [...s.messages, { id: uid('m'), role: 'assistant', at, content, local: true }] })); -} - -const lastAnswer = (sessionId: string) => [...(state.sessions.find(s => s.id === sessionId)?.messages ?? [])].reverse().find(m => m.role === 'assistant' && !m.local); - -const loopScheduler = new LoopScheduler({ - async send(sessionId, { text, shown }) { - const before = lastAnswer(sessionId)?.id; - await sendMessage(text, { fromLoop: true, shown, title: shown.length > 48 ? shown.slice(0, 47).trimEnd() + '…' : shown }); - const answer = lastAnswer(sessionId); - if (!answer || answer.id === before || answer.streaming) return { answered: false, text: '', failed: false }; - return { answered: true, text: answer.content ?? '', failed: !!answer.error }; - }, - note: addNote, - exists: sessionId => state.sessions.some(s => s.id === sessionId), - ready: sessionId => state.activeSession === sessionId && !state.streaming, - now: () => Date.now(), - setTimer: (fn, ms) => setTimeout(fn, ms), - clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>), - track: (sessionId, loop) => patchSession(sessionId, s => ({ ...s, loop })), -}); - -export function loopIsRunning(sessionId: string | null): boolean { return loopScheduler.isRunning(sessionId); } - -/* ------------------------------------------------------------- task board */ - -/** The chats with a turn going, and the chats with a loop going: what the board needs besides the sessions themselves. */ -export function liveChatIds(): string[] { return [...liveTurns.keys()]; } -export function loopChatIds(): string[] { return loopScheduler.ids(); } - -/** Stop any chat's turn, not only the open one (the board's Stop). Same two-step as stopStreaming. */ -export function stopChat(id: string) { - const turn = liveTurns.get(id); - if (!turn) return; - const abort = () => { turn.abort.abort(); }; - void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then( - result => { if (!result.stopped) abort(); else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); }, - abort, - ); -} - -/** Stop a chat's loop from the board. The chat gets the same line /loop stop writes. */ -export function stopLoop(id: string) { - if (loopScheduler.stop(id)) addNote(id, tr('The loop is stopped.')); -} - -/** Dismiss a chat's (or its loop's) card: it leaves the board until something newer goes wrong. The chat itself is untouched. */ -export function dismissChat(id: string) { - const sessions = state.sessions.map(s => (s.id === id ? { ...s, ackedAt: new Date().toISOString() } : s)); - persistSessions(sessions); - set({ sessions }); -} - -/** Answer a waiting tool card in any chat (the board's Approve and Deny). Only a live card has an approval behind it. */ -export function answerChatTool(sessionId: string, messageId: string, toolId: string, approved: boolean) { - const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId); - if (tool?.live && tool.state === 'proposed') answerAgentTool(sessionId, messageId, tool, approved); -} - -/** "Continue in a new chat" on a chat or a loop that went wrong: a new chat that starts from what happened (src/lib/task-handover.ts). */ -export function continueChatInNewChat(sessionId: string) { - const old = state.sessions.find(s => s.id === sessionId); - if (!old) return; - const session = newSession(); - go('chat', session.id); - void sendMessage(chatHandoverMessage(old), { title: chatHandoverTitle(old), markdown: true }); -} - -async function runLoopCommand(command: LoopCommand) { - const sessionId = state.activeSession ?? newSession().id; - const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); }; - if (command.kind === 'help') { say(tr(command.problem) + '\n\n' + tr(LOOP_USAGE)); return; } - if (command.kind === 'status') { say(loopScheduler.describe(sessionId) ?? tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE)); return; } - if (command.kind === 'stop') { say(loopScheduler.stop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; } - go('chat', sessionId); - await loopScheduler.start(sessionId, command); -} - -/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */ -export async function resumeGoal() { await sendMessage('', { goalAction: 'resume' }); } - -/** Approve a proposed plan and carry it out: the host answers with the message that does the work, which goes out as an ordinary turn. */ -export async function approvePlan(sessionId: string, planId: string) { - const { prompt } = await planApprove(sessionId, planId); - // A chat in Plan mode only reads; carrying the plan out needs a mode that may act. - if (state.sessions.find(s => s.id === sessionId)?.preferences?.mode === 'plan') setChatPreferences(sessionId, { mode: 'manual' }); - if (prompt) await sendMessage(prompt, { shown: tr('Approved the plan.') }); -} - -/** "Start as goal" (and Resume on a paused plan): the host streams the run like any chat turn. */ -export async function startPlanGoal(planId: string) { await sendMessage('', { planId }); } - -export async function sendMessage(text: string, options: { fromLoop?: boolean; goalAction?: 'resume'; planId?: string; shown?: string; title?: string; markdown?: boolean } = {}) { - if (state.streaming) { - // Typed while the assistant works: behind a running goal it waits in the queue; otherwise there is nothing to do but wait. - const waiting = state.activeSession, line = text.trim(); - if (waiting && line && !options.planId && !options.goalAction) { - try { if (!(await queueMessage(waiting, line))) pushToast('info', 'The assistant is still answering', 'Send your message when it has finished.'); } - catch (e) { pushToast('error', 'The message was not queued', plainFailureText(e instanceof Error ? e.message : String(e)).message); } - } - return; - } - const resume = options.goalAction === 'resume'; - const planStart = options.planId; - const loopCommand = options.fromLoop || resume || planStart ? null : parseLoop(text.trim()); - if (loopCommand) { await runLoopCommand(loopCommand); return; } - const demoPrompt = resume || planStart ? null : timeSkipPrompt(text.trim()); - if (demoPrompt !== null) { - if (demoPrompt && (state.remoteModel || nativeState()?.instances.some(i => i.status === 'ready'))) void startTimeSkipReal(demoPrompt); else if (state.connection === 'live' && demoPrompt) pushToast('info', 'Load a model first', 'Time-skip works on a loaded model. Choose one on the Models tab, then try again.'); - else if (state.connection === 'connecting' && demoPrompt) pushToast('info', 'Still starting up', 'Time-skip needs the app to finish starting. Try again in a moment.'); - else startTimeSkipDemo(demoPrompt); - return; - } - // Whatever sent this (the box, a loop, a plan): with no model to answer, say so in plain words and start nothing. - if (state.connection === 'live') { - // The first read of the engine's state has not come back yet: do not say "no model" about something not known yet, and do not send. - if (!nativeState() && !state.remoteModel && !state.library?.loaded) { pushToast('info', 'Still starting up', 'Strata is still checking your models. Try again in a moment.'); return; } - const why = noModelNotice(nativeState(), { remote: !!state.remoteModel, libraryLoaded: !!state.library?.loaded }); - if (why) { pushToast('info', why.title, why.message); return; } - } - const pictureCheck=pictureStatus(nativeState(),state.remoteModel,state.providers); - if(pendingChatPhotos(state.activeSession).length&&!pictureCheck.ok){pushToast('error','This model cannot read pictures',tr(pictureCheck.message));return;} - const pictures=takeChatPhotos(state.activeSession); - const body=text.trim()||(pictures.length?'Describe this picture.':''); - if(!body&&!resume&&!planStart)return; - - let sessionId = state.activeSession; - if (!sessionId) sessionId = newSession().id; - - const userMsg: ChatMessage = { id: uid('m'), role: 'user', content: options.shown ?? body, at: new Date().toISOString(),...(pictures.length?{photos:pictures}:{}),...(options.markdown?{markdown:true}:{}) }; - let assistantId = uid('m'); - const assistantMsg: ChatMessage = { - id: assistantId, - role: 'assistant', - content: '', - at: new Date().toISOString(), - streaming: true, - }; - - /* Everything said before this turn, which the model needs in order to have a - conversation at all. - - It was never sent. The real-engine path builds its prompt as - `[...history, message]`, and `history` was always empty, so each message - arrived as the first thing the model had ever heard — no memory of the - turns above it in the transcript. The demo path hides this, because its - replies are canned. - - The context meter was reading the same empty array, which is why it sat at - ~350 tokens however long the conversation grew. */ - const prior = (state.sessions.find((s) => s.id === sessionId)?.messages ?? []) - .filter(m => !m.timeSkipId && !m.local) - .filter((m) => m.role === 'user' || m.role === 'assistant') - .filter((m) => m.content.trim()) - .map((m) => ({ role: m.role, content: m.content,photos:m.photos })) - // Bounded so a long conversation cannot send an unbounded body. - .slice(-40); - - patchSession(sessionId, (s) => ({ - ...s, - defaultTitle: false, - title: s.messages.length === 0 && !resume && !planStart ? (options.title ?? (body.length>48?body.slice(0,47).trimEnd()+'…':body)) : s.title, - updatedAt: new Date().toISOString(), - messages: [...s.messages, ...(resume || planStart ? [] : [userMsg]), assistantMsg], - })); - - const turnAbort = new AbortController(); - markTurn(sessionId, { abort: turnAbort, agent: false }); - // Read by the router to skip view transitions mid-stream, and by CSS to keep - // the transcript still while tokens arrive. - - const patchAssistant = (fn: (m: ChatMessage) => ChatMessage) => - patchSession(sessionId, (s) => ({ - ...s, - updatedAt: new Date().toISOString(), - messages: s.messages.map((m) => (m.id === assistantId ? fn(m) : m)), - })); - - const started = performance.now(); - - const imageSlots=photoHistorySlots(prior,pictures.length); - /* Text and reasoning arrive token by token (90 a second or more). Drawing the whole answer again for each one made the page do more work for every - word the longer the answer grew (measured: 15.7 s of main-thread time for 24 s of a 40,000-token answer), until the page stopped answering - and ran out of memory. The pieces are gathered and applied together about ten times a second; any other frame, the end and a failure - apply what is waiting first, so the order the person sees is the order it was written. */ - const waiting: ['reasoning' | 'delta', string][] = []; - let waitingTimer: ReturnType<typeof setTimeout> | null = null; - const applyReasoning = (text: string) => patchAssistant((m) => ({ ...m, reasoning: (m.reasoning ?? '') + text, reasoningStartedAt: m.reasoningStartedAt ?? Date.now() })); - const applyDelta = (text: string) => patchAssistant((m) => { const content=tidyAnswer(m.content+text); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,...(m.blocks?{blocks:appendText(m.blocks,text)}:{}),tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; }); - const flushWaiting = () => { - if (waitingTimer !== null) { clearTimeout(waitingTimer); waitingTimer = null; } - for (const [kind, text] of waiting.splice(0)) if (kind === 'delta') applyDelta(text); else applyReasoning(text); - }; - const queueText = (kind: 'reasoning' | 'delta', text: string) => { - const last = waiting[waiting.length - 1]; - if (last && last[0] === kind) last[1] += text; else waiting.push([kind, text]); - waitingTimer ??= setTimeout(flushWaiting, 90); - }; - try { - await streamPost( - planStart ? '/api/plan/start-goal' : '/api/chat/stream', - { - sessionId, - ...(planStart ? { planId: planStart } : {}), - ...(resume ? { goalAction: 'resume' } : planStart ? {} : { message: options.shown ? body : body }), - history:await Promise.all(prior.map(async(m,index)=>{const included=pictureCheck.ok?(m.photos??[]).filter((_,p)=>imageSlots.has(`${index}:${p}`)):[];const omitted=(m.photos??[]).filter(p=>!included.includes(p));const text=m.content+(omitted.length?`\n[Earlier pictures: ${omitted.map(p=>p.name).join(', ')}. Their pixels are outside this model's image context; ask to reattach them if needed.]`:'');return {role:m.role,content:included.length?[{type:'text',text},...await Promise.all(included.map(async photo=>({type:'image_url',image_url:{url:(await photoData(photo)).url}})))]:text};})), - model: state.library?.loaded ?? state.library?.current ?? null, - remoteModel: state.remoteModel, - nativeModelId:nativeState()?.instances.length?nativeState()?.defaultId:undefined, - ...(pictures.length ? { imageIds: await uploadChatPhotos(pictures, sessionId) } : {}), - useTools:state.sessions.find(s=>s.id===sessionId)?.preferences?.useTools===true, - // A chat set to plain talk (preferences.agent === false) never runs a tool: the host answers it directly. - ...(state.sessions.find(s=>s.id===sessionId)?.preferences?.agent===false?{agent:false}:{}), - thinking:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinking??'Medium', - thinkingBudget:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinkingBudget??0, - // 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: 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. - if (frame.type === 'delta' && typeof frame.key === 'string') frame = { ...frame, text: tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) }; - const type = frame.type as string; - if (type === 'delta' || type === 'reasoning') { queueText(type, String(frame.text ?? '')); return; } - flushWaiting(); - if (type === 'start' && frame.agent === true) { const turn = liveTurns.get(sessionId); if (turn) turn.agent = true; } - if (type === 'queued') { - patchAssistant(m => ({ ...m, requestId: String(frame.requestId) })); - } else if (type === 'start') { - patchAssistant((m) => ({ ...m, demo: frame.demo === true, remoteModel: frame.remoteModel === true, requestId: typeof frame.requestId === 'string' ? frame.requestId : m.requestId, model: String(frame.model), contextMax: Number(frame.contextMax), skillsUsed: Array.isArray(frame.skills) ? frame.skills.map(String) : [] })); - } else if (type === 'status') { - applyStatusFrame(sessionId, frame as Record<string, unknown>); - // Manual mode waits for the person: a notification when they have opted in and Strata is in the background (#3477), once per question. - if (frame.code === 'waiting-approval' && lastApprovalNotice !== `${sessionId}:${String(frame.seq)}`) { - lastApprovalNotice = `${sessionId}:${String(frame.seq)}`; - const tool = (frame.args as { tool?: unknown } | undefined)?.tool; - void approvalNeeded(state.approvalNotify, typeof tool === 'string' ? tool : ''); - } - } else if (type === 'goal') { - applyGoalFrame(sessionId, frame.goal); - } else if (type === 'plan') { - applyPlanFrame(sessionId, frame.plan); - // A proposed plan is shown as the plan card in place of this turn's closing text (that text is the plan in prose). - const planned = frame.plan as { id?: unknown } | null; - if (frame.event === 'proposed' && planned && typeof planned.id === 'string') { const pid = planned.id; patchAssistant(m => ({ ...m, planId: pid })); } - } else if (type === 'queued-message') { - applyQueueFrame(sessionId, frame.queue); - const sent = frame.message as { text?: unknown } | undefined; - if (frame.state === 'delivered' && sent && typeof sent.text === 'string') { - // The host has just sent it into the run: it becomes an ordinary message here, and the answer to it starts a new reply. - const before = assistantId; assistantId = uid('m'); - const next: ChatMessage = { id: assistantId, role: 'assistant', content: '', at: new Date().toISOString(), streaming: true }; - patchSession(sessionId, sess => ({ ...sess, messages: [...sess.messages.map(m => m.id === before ? { ...m, streaming: false } : m), { id: uid('m'), role: 'user', content: sent.text as string, at: new Date().toISOString() }, next] })); - } - } else if (type === 'queued-release') { - // The goal ended with messages left: they go out now, in order, as ordinary messages once this turn has finished. - const left = Array.isArray(frame.messages) ? frame.messages.flatMap(q => (q && typeof (q as { text?: unknown }).text === 'string' ? [String((q as { text: string }).text)] : [])) : []; - if (left.length) releasedMessages.set(sessionId, [...(releasedMessages.get(sessionId) ?? []), ...left]); - } else if (type === 'plan-step') { - /* the whole plan follows in a plan frame; the live status already says which step is running */ - } else if (type === 'reasoning') { - /* applied through queueText above */ - } else if (type === 'notice') { - // The host says why this chat is not using the agent. One toast per reason per page load. - const code = String(frame.code ?? 'notice'); - if (!noticed.has(code)) { noticed.add(code); pushToast('info', 'Agent', plainFailureText(String(frame.message ?? '')).message); } - } else if (type === 'agent-question') { - addAgentAsk(sessionId, frame as { callId?: unknown; questions?: unknown }); - } else if (type === 'agent-question-end') { - removeAgentAsk(sessionId, String(frame.callId ?? '')); - } else if (type === 'agent-tool-draft') { - // A tool call (a whole file, say) is being written: keep its name, size and the tail of its text on the reply until the call is whole or lost. - const d = frame.draft as (ToolDraft & { done?: boolean }) | undefined; - if (d && typeof d.id === 'string') { - const { done, ...view } = d; - patchAssistant(m => { - const rest = (m.drafts ?? []).filter(x => x.id !== d.id); - return { ...m, drafts: done ? (rest.length ? rest : undefined) : [...rest, view] }; - }); - } - } else if (type === 'agent-tool') { - const tool = frame.tool as ToolCall; - patchAssistant(m => { - const existing = m.tools?.find(t => t.id === tool.id); - const next: ToolCall = { ...existing, ...tool, live: true }; - return { ...m, tools: existing ? m.tools!.map(t => t.id === tool.id ? next : t) : [...(m.tools ?? []), next] }; - }); - } else if (type === 'agent') { - patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) })); - } else if (type === 'delta') { - /* applied through queueText above */ - } else if (type === 'deliverable') { - const file = readDeliverable(frame); - if (file) patchAssistant(m => ({ ...m, deliverables: mergeDeliverable(m.deliverables, file) })); - } else if (type === 'skills-used') { - const skills = readSkills(frame); - if (skills.length) patchAssistant(m => ({ ...m, skills })); - } else if (type === 'activity-group') { - const group = readGroup(frame); - if (group) patchAssistant(m => ({ ...m, blocks: upsertGroup(m.blocks ?? (m.content ? appendText(undefined, m.content) : undefined), group) })); - } else if (type === 'artifacts' && Array.isArray(frame.artifacts)) { - patchAssistant(m => ({ ...m, artifacts: frame.artifacts as PreviewArtifact[] })); - } else if(type==='native-tool'){ - const event=frame.event as {event:string;id:string;name?:string;arguments?:Record<string,unknown>;text?:string;ok?:boolean;ms?:number}; - if(event.id)patchAssistant(m=>{const existing=m.tools?.find(t=>t.id===event.id);const tool={id:event.id,name:event.name??existing?.name??'Connected tool',args:event.arguments??existing?.args??{},preview:'Authorized connected tool',effect:'Access configured in the MCP server',scope:'connected' as const,state:event.event==='result'?event.ok?'done' as const:'error' as const:'running' as const,result:event.text,durationMs:event.ms};return {...m,tools:[...(m.tools??[]).filter(t=>t.id!==tool.id),{...existing,...tool}]};}); - } else if (type === 'tool') { - const tool = frame.tool as ChatMessage['tools'] extends (infer T)[] | undefined ? T : never; - patchAssistant((m) => ({ ...m, tools: [...(m.tools ?? []), { ...tool, state: 'proposed' }] })); - } else if (type === 'stats') { - patchAssistant((m) => ({ - ...m, - tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : m.tokens, - tps: typeof frame.tps === 'number' ? frame.tps : m.tps, - promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps, - })); - } else if (type === 'context') { - // What the context holds after each model request of an agent turn: the meter follows the turn instead of waiting for its end. - const used = Number(frame.contextTokens), max = Number(frame.contextMax); - if (Number.isFinite(used) && used > 0) patchAssistant((m) => ({ ...m, contextUsed: used, ...(Number.isFinite(max) && max > 0 ? { contextMax: max } : {}) })); - } else if (type === 'error') { - clearStatus(sessionId); - // A sentence the host wrote for the person (it carries its catalog key) is shown in their language as it is; anything else is made plain here. - const said = typeof frame.key === 'string' ? tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) : plainFailure(String(frame.message ?? 'Engine error')).message; - patchAssistant((m) => ({ ...m, drafts: undefined, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) })); - } else if (type === 'done') { - clearStatus(sessionId); - workFinished(state.doneSound, Number(frame.durationMs ?? performance.now() - started)); - patchSession(sessionId, (sess) => ({ - ...sess, - tokensIn: sess.tokensIn + Number(frame.tokensIn ?? 0), - tokensOut: sess.tokensOut + Number(frame.tokensOut ?? 0), - statsAvailable: typeof frame.tokensIn === 'number' && typeof frame.tokensOut === 'number' && sess.messages.filter(m=>m.role==='assistant'&&!m.streaming).every(m=>typeof m.inputTokens==='number'), - })); - patchAssistant((m) => ({ - ...m, - streaming: false, - drafts: undefined, - durationMs: Number(frame.durationMs ?? performance.now() - started), - tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : undefined, - ttftMs: typeof frame.ttftMs === 'number' ? frame.ttftMs : undefined, - inputTokens: typeof frame.tokensIn === 'number' ? frame.tokensIn : undefined, - contextUsed: typeof frame.contextTokens === 'number' ? frame.contextTokens : undefined, - usageSource: frame.usageSource === 'reported' || frame.usageSource === 'demo' ? frame.usageSource : 'unavailable', - tps: typeof frame.tps === 'number' ? frame.tps : m.tps, - promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps, - })); - // The final text is in `state`: write it once now instead of waiting for the coalescing timer. - flushSessions(); - } - }, - turnAbort.signal, - ); - } catch (err) { - flushWaiting(); - if ((err as Error).name !== 'AbortError') { - patchAssistant((m) => ({ - ...m, - streaming: false, - error: err instanceof Error ? err.message : 'Engine error', - })); - pushToast('error', 'Generation failed', err instanceof Error ? err.message : undefined); - } else { - patchAssistant((m) => ({ ...m, streaming: false })); - } - } finally { - flushWaiting(); - // A cancelled or failed turn is still worth keeping. - flushSessions(); - clearStatus(sessionId); - markTurn(sessionId, null); - removeAgentAsk(sessionId); - const next = releasedMessages.get(sessionId)?.shift(); - if (next !== undefined) { if (!releasedMessages.get(sessionId)?.length) releasedMessages.delete(sessionId); setTimeout(() => void sendMessage(next), 0); } - } -} - -/** Messages the host handed back when a goal ended with some still waiting; sent one after another. */ -const releasedMessages = new Map<string, string[]>(); - -/* -------------------------------------------------------------- tool grants */ - -const noticed = new Set<string>(); - -/** - * Approve or deny a tool the agent asked about. The answer goes to the host, which hands it to the - * Harness approval for exactly this chat and call; the card then follows what the Harness reports - * (running, done, denied). The card shows the choice straight away and goes back if the host refuses. - */ -function answerAgentTool(sessionId: string, messageId: string, tool: ToolCall, approved: boolean) { - const setState = (state_: ToolCall['state'], result?: string) => patchSession(sessionId, s => ({ - ...s, messages: s.messages.map(m => m.id === messageId ? { ...m, tools: (m.tools ?? []).map(t => t.id === tool.id ? { ...t, state: state_, ...(result !== undefined ? { result } : {}) } : t) } : m), - })); - setState(approved ? 'running' : 'denied'); - api.post('/api/chat/approval', { sessionId, toolId: tool.id, decision: approved ? 'approve' : 'deny' }).catch(error => { - setState('proposed'); - pushToast('error', 'That answer was not delivered', error instanceof Error ? error.message : undefined); - }); -} - -/** - * Approving a tool in the design build resolves locally: there is no tool - * runtime behind it yet, so the result is a labelled stand-in. The interaction — - * what is asked, what is shown, what needs a grant — is the real deliverable. - */ -export function resolveTool(messageId: string, toolId: string, approved: boolean) { - const sessionId = state.activeSession; - if (!sessionId) return; - const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId); - if (tool?.live) { answerAgentTool(sessionId, messageId, tool, approved); return; } - - patchSession(sessionId, (s) => ({ - ...s, - messages: s.messages.map((m) => - m.id === messageId - ? { - ...m, - tools: (m.tools ?? []).map((t) => - t.id === toolId - ? { - ...t, - state: approved ? 'done' : 'denied', - durationMs: undefined, - result: approved ? 'Approval recorded. Nothing was executed.' : 'Denied. Nothing ran.', - } - : t, - ), - } - : m, - ), - })); - -} - -/* ------------------------------------------------------------------- routes */ - -export function go(route: Route, param?: string) { - navigate(route, param); - // Focus mode is a reading mode for the conversation. Leaving it to work on - // something else leaves the mode, rather than stranding a bare shell. - if (state.focus && route !== 'chat' && route !== 'settings') setFocus(false); - set({ paletteOpen: false, navOpen: false }); -} - -/* ---------------------------------------------------------------- bootstrap */ - -export function bootOnce() { - if ((globalThis as { __strataBooted?: boolean }).__strataBooted) return; - (globalThis as { __strataBooted?: boolean }).__strataBooted = true; - for (const session of state.sessions) for (const run of session.timeSkips ?? []) { scheduleTimeSkip(session.id, run); if (run.job && !run.completedAt) { markTurn(session.id, { abort: new AbortController(), agent: false }); void followTimeSkip(session.id, run.id); } } - // A loop lives in the window: one the last window left "running" has ended, and the board says so. - if (state.sessions.some(s => s.loop?.state === 'running')) { - const sessions = state.sessions.map(s => s.loop?.state === 'running' ? { ...s, loop: { ...s.loop, state: 'ended' as const, endedWhy: 'closed' as const, endedAt: Date.parse(s.updatedAt) || Date.now() } } : s); - persistSessions(sessions); - set({ sessions }); - } - void bootstrap(); - void reconcileAgentTools(); -} - -/** - * After a reload, a tool card the browser remembers as waiting or running may belong to a turn that no - * longer exists. Cards whose approval the host still holds stay answerable; the rest are marked as - * interrupted so nothing looks like it is still working. - */ -async function reconcileAgentTools() { - const open = (t: ToolCall) => t.live && (t.state === 'proposed' || t.state === 'running'); - for (const session of state.sessions) { - if (!session.messages.some(m => m.tools?.some(open))) continue; - let waiting = new Set<string>(); - try { - const r = await api.get<{ pending: { callId: string }[] }>(`/api/agent/pending?chatId=${encodeURIComponent(session.id)}`); - waiting = new Set(r.pending.map(p => p.callId)); - } catch { /* The host is unreachable; leave the cards for the next load. */ continue; } - patchSession(session.id, sess => ({ ...sess, messages: sess.messages.map(m => m.tools?.some(open) ? { ...m, tools: m.tools.map(t => open(t) && !waiting.has(t.id) ? { ...t, state: 'error' as const, result: 'The page closed before this finished. Check the workspace to see what it did.' } : t) } : m) })); - } -} - - -export function setContrast(contrast: 'standard' | 'increased') { set({ contrast }); savePrefs(); } -matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (state.theme === 'system') applyPrefs(); }); - -export async function loadRuntimeModel(body:unknown){ - const result=await api.post<{state:RuntimeModels;instance:{id:string}}>('/api/runtime/load',body); - set({runtime:result.state});return result.instance.id; -} -export async function runtimeModelAction(id:string,action:'unload'|'default'){ - set({runtime:await api.post<RuntimeModels>(`/api/runtime/${id}/${action}`)}); -} - -export async function changeModelDirectory(directory: string, unload: boolean) { - set(s => ({ busy: { ...s.busy, modelDirectory: true } })); - try { - const result = await api.post<{ library: ModelLibrary; imageModels: ImageModelLibrary; runtime: RuntimeModels; hardware: Hardware; setup: SetupState }>('/api/storage/models-directory', { directory, unload }); - set(result); - return result; - } finally { - set(s => ({ busy: { ...s.busy, modelDirectory: false } })); - } -} - -export async function addLocalModel(path: string, name?: string) { - const result = await api.post<{ library: ModelLibrary; variantId: string }>('/api/local-models', { path, name }); - set({ library: result.library }); - return result.variantId; -} +import { workspaceIdForSession } from './session-workspace'; +import { DEFAULT_CONTENT_FS, DEFAULT_UI_SCALE, SIZE_DEFAULTS_VERSION, savedSizes } from './default-sizes'; +import { detectLanguage } from './language-detect'; +import { validWhileBusy, type WhileBusy } from './while-busy'; +import { addToQuotes, type Quote } from './quotes'; +import { readAsk, type AgentAnswer, type AgentAsk } from './agent-ask'; +import { plainFailure, plainFailureText } from './plain-errors'; +import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase'; +import { settleAgents, updateAgent } from './agents'; +import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop'; +import { LoopScheduler } from './loop-runner'; +import { applyStatusFrame, clearStatus } from './live-status'; +import { approvalNeeded, workFinished } from './attention'; +import { applyGoalFrame } from './goal'; +import { tidyAnswer } from './answer-text'; +import { appendText, mergeDeliverable, readDeliverable, readGroup, readSkills, upsertGroup } from './deliverables'; +import { applyPlanFrame, applyQueueFrame, planApprove, queueMessage } from './plan'; +import { forkFields, isForkJob, TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipFile, type TimeSkipJob, type TimeSkipRun, type TimeSkipVersion } from './time-skip'; +import { PREVIEW_EXAMPLES, type PreviewArtifact } from './artifacts'; +import { lifecyclePolicy } from './lifecycle'; +import { newestServingState } from './serving-state'; +import { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos'; +import { applyNativeEvent, nativeState } from './native'; +import { pictureStatus } from './pictures'; +import { noModelNotice } from './no-model'; +import { taskHandoverMessage, taskHandoverTitle, chatHandoverMessage, chatHandoverTitle } from './task-handover'; +import type { Task } from './tasks'; +import { postWithFolderFallback } from './folder-pick'; +import { createSessionWriter } from './session-persist'; +import { setTranslationLanguage, tr, validLanguage, type Language } from './i18n'; +/** + * Strata app store. + * + * A single immutable state object + a tiny subscribe/emit pair, consumed through + * useSyncExternalStore. Data comes from the engine host over /api; live updates + * arrive on the event stream. No state library, no dependencies. + */ +import { useSyncExternalStore } from 'react'; +import { api, onEvent, streamPost, type StreamEvent } from './client'; +import type { + Workspace, + ChatMessage, + ToolCall, + EngineConfig, + Hardware, + ModelLibrary, + RuntimeModels, + ImageModelLibrary, + ImageModelChoice, + ModelProviders, + ModelConnectionDraft, + RemoteModelSelection, + MonitorState, + ServingState, + Session, + SetupState, + Skill, + WorkspaceFile, + ToolDraft, +} from './types'; +import { navigate, type Route } from './router'; +import { estimate, execution, contextTokens } from './experience'; + +export interface Toast { + id: string; + tone: 'info' | 'success' | 'warn' | 'error'; + title: string; + body?: string; + leaving?: boolean; +} + +export interface AppState { + language: Language; + fontFamily: string; + configDraft: string | null; + navOpen: boolean; + ready: boolean; + connection: 'connecting' | 'live' | 'offline'; + theme: 'dark' | 'light' | 'system'; + contrast: 'standard' | 'increased'; + rail: boolean; + /** Distraction-free reading: chrome recedes, the transcript narrows. */ + focus: boolean; + /** Conversation prose size in px, 10–22. Does not touch the UI chrome. */ + contentFontSize: number; + density: 'comfortable' | 'compact'; + motion: 'system' | 'full' | 'reduced'; + /** Translucent materials, or flat surfaces for anyone who prefers them. */ + transparency: 'translucent' | 'opaque'; + /** Chrome scale, independent of the conversation's reading size. */ + uiScale: number; + /** Price of one kWh for the Monitor's cost line (0 = not set) and the currency the person picked instead of the detected one ('' = automatic) (#3628). */ + electricityPrice: number; + electricityCurrency: string; + /** Opt-in: a short sound when a task finishes (#3586). */ + doneSound: boolean; + /** Opt-in: a desktop notification when Manual mode waits for an approval (#3477). */ + approvalNotify: boolean; + /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ + whileBusy: WhileBusy; + /** Governs anonymous usage reporting. Nothing is sent in this build; the + * choice is recorded so a version that does offer it starts from it. */ + shareTelemetry: boolean; + paletteOpen: boolean; + shortcutsOpen: boolean; + settingsSection: 'Appearance' | 'Models' | 'Tools' | 'Storage' | 'Engine' | 'About'; + hardware: Hardware | null; + library: ModelLibrary | null; + imageModels: ImageModelLibrary | null; + runtime: RuntimeModels | null; + providers: ModelProviders | null; + remoteModel: RemoteModelSelection | null; + engine: EngineConfig | null; + serving: ServingState | null; + monitor: MonitorState | null; + setup: SetupState | null; + skills: Skill[]; + files: WorkspaceFile[]; + workspacePath: string; + workspaces: Workspace[]; + /** Id of the workspace the file tree is scoped to. */ + activeWorkspace: string | null; + /** First run, and "run setup again", both present the wizard as a modal. */ + setupOpen: boolean; + sessions: Session[]; + activeSession: string | null; + streaming: boolean; + /** Messages the person sent while an answer was being written, waiting to go when it ends (Send after, Interrupt), by chat (#4783). */ + parked: Record<string, string[]>; + /** The passages quoted into the message being written, by chat, in the order they were quoted (#4785). */ + quotes: Record<string, Quote[]>; + /** The questions the agent asked the person and is waiting for, by chat (#4244). */ + agentAsks: Record<string, AgentAsk[]>; + /** Chats with a turn in flight. `streaming` is about the open chat; this is about all of them. */ + liveChats: number; + toasts: Toast[]; + /** Files the model has been granted read access to, and when. */ + touchedPaths: Record<string, string>; + /** The last action that failed, kept until it is retried or dismissed. + * A toast disappears after five seconds; a failure the reader has not dealt + * with should not. */ + actionError: { message: string; label: string; retry: () => void } | null; + busy: Record<string, boolean>; +} + +const SESSION_KEY = 'strata.sessions.v1'; +const PREFS_KEY = 'strata.prefs.v2'; +/** What the model has been allowed to read, kept across restarts. */ +const TOUCHED_KEY = 'strata.touched.v1'; +/** Kept one release so downgrading does not lose the theme and sidebar state. */ +const PREFS_KEY_V1 = 'strata.prefs.v1'; + +const CONTENT_FS_MIN = 10; +const CONTENT_FS_MAX = 22; + +export interface Prefs { + /** Which default sizes this save was made with (see SIZE_DEFAULTS_VERSION). */ + sizeDefaults?: number; + language: Language; + fontFamily: string; + theme: 'dark' | 'light' | 'system'; + contrast: 'standard' | 'increased'; + rail: boolean; + focus: boolean; + contentFontSize: number; + density: 'comfortable' | 'compact'; + motion: 'system' | 'full' | 'reduced'; + transparency: 'translucent' | 'opaque'; + uiScale: number; + electricityPrice: number; + electricityCurrency: string; + doneSound: boolean; + approvalNotify: boolean; + /** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ + whileBusy: WhileBusy; + /** Governs anonymous usage reporting. Nothing is sent in this build; the + * choice is recorded so a version that does offer it starts from it. */ + shareTelemetry: boolean; +} + +const PREFS_DEFAULTS: Prefs = { + language: 'en', + fontFamily: '', + theme: 'system', + contrast: 'standard', + rail: false, + focus: false, + contentFontSize: DEFAULT_CONTENT_FS, + density: 'comfortable', + motion: 'system', + transparency: 'translucent', + uiScale: DEFAULT_UI_SCALE, + electricityPrice: 0, + electricityCurrency: '', + doneSound: false, + approvalNotify: false, + whileBusy: 'wait', + shareTelemetry: false, +}; + +function uid(prefix = 'id'): string { + return `${prefix}_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36).slice(-4)}`; +} + +function loadSessions(): Session[] { + try { + const raw = localStorage.getItem(SESSION_KEY); + if (!raw) return []; + const parsed = JSON.parse(raw) as Session[]; + return Array.isArray(parsed) ? parsed.map(session => ({ + ...session, + ...(session.showcase && !session.showcaseAgentStates ? {agents:SHOWCASE_AGENTS,showcaseAgentStates:true}:{}), + ...(!session.showcase && session.agents ? { agents: settleAgents(session.agents) } : {}), + messages: session.messages.map(message => message.streaming ? { + ...message, + streaming: false, + error: message.error ?? 'Response interrupted. Ask again to retry; the partial answer is kept.', + } : message), + })) : []; + } catch { + return []; + } +} + +/** + * v2 adds focus, reading size, density and the motion override. A v1 blob (only + * theme and rail) is read as-is and upgraded on the next write, so the first run + * after this change keeps the user's theme instead of resetting it. + */ +function loadPrefs(): Prefs { + for (const key of [PREFS_KEY, PREFS_KEY_V1]) { + try { + const raw = localStorage.getItem(key); + if (!raw) continue; + const parsed = JSON.parse(raw) as Partial<Prefs>; + return { + ...PREFS_DEFAULTS, + ...parsed, + language: validLanguage(parsed.language) ? parsed.language : 'en', + fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '', + ...savedSizes(parsed, CONTENT_FS_MIN, CONTENT_FS_MAX), + sizeDefaults: SIZE_DEFAULTS_VERSION, + electricityPrice: Number.isFinite(Number(parsed.electricityPrice)) && Number(parsed.electricityPrice) > 0 && Number(parsed.electricityPrice) < 1000 ? Number(parsed.electricityPrice) : 0, + electricityCurrency: typeof parsed.electricityCurrency === 'string' && /^[A-Za-z]{3}$/.test(parsed.electricityCurrency) ? parsed.electricityCurrency.toUpperCase() : '', + doneSound: parsed.doneSound === true, + approvalNotify: parsed.approvalNotify === true, + whileBusy: validWhileBusy(parsed.whileBusy) ? parsed.whileBusy : 'wait', + }; + } catch { + /* fall through to the next key */ + } + } + // Nothing saved: a first start. It opens in the language of the computer; a choice made on the first screen is saved like any other. + const tags = typeof navigator === 'undefined' ? [] : navigator.languages?.length ? navigator.languages : [navigator.language]; + return { ...PREFS_DEFAULTS, language: detectLanguage(tags) ?? 'en' }; +} + +const prefs = loadPrefs(); +// Use the saved language for the very first render, before host bootstrap. +setTranslationLanguage(prefs.language); + +/** The last approval question a notification was shown for, so one question is announced once. */ +let lastApprovalNotice = ''; + +let state: AppState = { + language: prefs.language, + fontFamily: prefs.fontFamily, + configDraft: (() => { try { return sessionStorage.getItem('strata.config-draft.v1'); } catch { return null; } })(), + navOpen: false, + ready: false, + connection: 'connecting', + shareTelemetry: prefs.shareTelemetry, + theme: prefs.theme, + contrast: prefs.contrast, + rail: prefs.rail, + focus: prefs.focus, + contentFontSize: prefs.contentFontSize, + density: prefs.density, + motion: prefs.motion, + transparency: prefs.transparency, + uiScale: prefs.uiScale, + electricityPrice: prefs.electricityPrice, + electricityCurrency: prefs.electricityCurrency, + doneSound: prefs.doneSound, + approvalNotify: prefs.approvalNotify, + whileBusy: prefs.whileBusy, + parked: {}, + quotes: {}, + agentAsks: {}, + paletteOpen: false, + shortcutsOpen: false, + settingsSection: 'Appearance', + hardware: null, + library: null, + imageModels: null, + runtime: null, + providers: null, + /** The open chat's API model, or null for the local model (the default for every chat). */ + remoteModel: null, + engine: null, + serving: null, + monitor: null, + setup: null, + skills: [], + files: [], + workspacePath: '', + workspaces: [], + activeWorkspace: null, + setupOpen: false, + sessions: loadSessions(), + activeSession: null, + streaming: false, + liveChats: 0, + toasts: [], + touchedPaths: (() => { + try { + return JSON.parse(localStorage.getItem(TOUCHED_KEY) ?? '{}') as Record<string, string>; + } catch { + return {}; + } + })(), + actionError: null, + busy: {}, +}; + +const listeners = new Set<() => void>(); + +/** Chats with a turn in flight: the abort handle, and whether the host is running it as an agent turn. */ +const liveTurns = new Map<string, { abort: AbortController; agent: boolean }>(); + +function set(patch: Partial<AppState> | ((s: AppState) => Partial<AppState>)) { + const before = state.activeSession; + const next = typeof patch === 'function' ? patch(state) : patch; + state = { ...state, ...next }; + // Opening another chat shows that chat's model choice and whether that chat is mid-turn. + if (state.activeSession !== before) { + const chosen = state.sessions.find(s => s.id === state.activeSession)?.preferences?.remoteModel ?? null; + state = { ...state, remoteModel: 'remoteModel' in next ? state.remoteModel : chosen, streaming: !!state.activeSession && liveTurns.has(state.activeSession) }; + } + for (const l of listeners) l(); +} + +function subscribe(l: () => void) { + listeners.add(l); + return () => listeners.delete(l); +} + +export function getState(): AppState { + return state; +} + +export function setConfigDraft(configDraft: string | null) { + set({ configDraft }); + try { + if (configDraft === null) sessionStorage.removeItem('strata.config-draft.v1'); + else sessionStorage.setItem('strata.config-draft.v1', configDraft); + } catch { /* Keep the session draft even when browser storage is unavailable. */ } +} + +export function setNavOpen(navOpen: boolean) { set({ navOpen }); } +export function setSettingsSection(settingsSection: AppState['settingsSection']) { set({ settingsSection }); } + +/** Choose the open chat's model: an API model, or null for the local one. Other chats keep theirs. */ +export function selectRemoteModel(remoteModel: RemoteModelSelection | null) { + if (state.streaming) return; + if (remoteModel && !state.providers?.connections.some(c => c.id === remoteModel.connectionId && c.models.some(m => m.id === remoteModel.modelId))) return; + set({ remoteModel }); + const id = state.activeSession; + if (id) patchSession(id, s => ({ ...s, preferences: { ...s.preferences, remoteModel } })); + try { localStorage.removeItem('strata.remote-model.v1'); } catch { /* The old global choice is retired. */ } +} +function applyProviders(providers: ModelProviders) { + // A chat whose API model was removed keeps its choice: the next send says the model is gone, rather + // than quietly answering from the local model. + set({ providers }); +} +export async function saveModelConnection(draft: ModelConnectionDraft) { + applyProviders(await api.post<ModelProviders>('/api/model-providers', draft)); +} +export async function removeModelConnection(id: string) { + applyProviders(await api.del<ModelProviders>(`/api/model-providers/${encodeURIComponent(id)}`)); +} + +function libraryResponse(data: ModelLibrary): ModelLibrary { + if (!data || !Array.isArray(data.variants)) throw new Error('The engine returned an incomplete model list. Retry the operation.'); + return data; +} + +export function lifecycleStatus(s = state) { + return lifecyclePolicy({ connected: s.connection === 'live', streaming: !!s.streaming || s.liveChats > 0, stats: s.serving?.stats, busy: s.busy }); +} +/** The lifecycle status without subscribing to the whole store: a screen that only needs this must not redraw on every monitor tick (round 8, item 13). */ +export function useLifecycle() { + const connected = useStore(s => s.connection === 'live'); + const streaming = useStore(s => !!s.streaming || s.liveChats > 0); + const stats = useStore(s => s.serving?.stats); + const busy = useStore(s => s.busy); + return lifecyclePolicy({ connected, streaming, stats, busy }); +} +export function lifecycleAvailable(): boolean { + const result = lifecycleStatus(); + if (!result.allowed) pushToast('warn', 'Model change unavailable', result.reason); + return result.allowed; +} + +export function useStore<T>(selector: (s: AppState) => T): T { + return useSyncExternalStore( + subscribe, + () => selector(state), + () => selector(state), + ); +} + +/* ------------------------------------------------------------------ toasts */ + +/** Dismissal timers, held so a hovered toast can be paused rather than lost. */ +const toastTimers = new Map<string, ReturnType<typeof setTimeout>>(); +const TOAST_MS = 5200; + +export function pushToast(tone: Toast['tone'], title: string, body?: string) { + const id = uid('toast'); + // Cap the stack: past three, the oldest collapses rather than pushing the + // rest off-screen. A toast nobody can read is not a notification. + const next = [...state.toasts, { id, tone, title, body }]; + const overflow = next.length > 3 ? next.slice(0, next.length - 3) : []; + for (const gone of overflow) { + const t = toastTimers.get(gone.id); + if (t) clearTimeout(t); + toastTimers.delete(gone.id); + } + const kept = overflow.length ? next.slice(-3) : next; + set({ toasts: kept }); + toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS)); +} + +/** + * Stops a toast's clock while the pointer is over it, so reading one does not + * race its own dismissal. Restarting gives a full window rather than the + * remainder — the intent is "I am reading this", and a resumed half-second is + * not enough to act on. + */ +export function holdToast(id: string) { + const t = toastTimers.get(id); + if (t) clearTimeout(t); + toastTimers.delete(id); +} + +export function releaseToast(id: string) { + if (toastTimers.has(id)) return; + if (!state.toasts.some((t) => t.id === id && !t.leaving)) return; + toastTimers.set(id, setTimeout(() => dismissToast(id), TOAST_MS)); +} + +export function dismissToast(id: string) { + const t = toastTimers.get(id); + if (t) clearTimeout(t); + toastTimers.delete(id); + set((s) => ({ toasts: s.toasts.map((x) => (x.id === id ? { ...x, leaving: true } : x)) })); + setTimeout(() => set((s) => ({ toasts: s.toasts.filter((x) => x.id !== id) })), 340); +} + +/* ------------------------------------------------------------------- prefs */ + +/** + * Preferences live on <html> as data attributes plus one custom property, so CSS + * owns presentation and React owns state — the same split the theme already + * used. Nothing here re-renders a screen: the attributes do the work. + */ +function applyPrefs() { + const root = document.documentElement; + setTranslationLanguage(state.language); + root.lang = state.language === 'zh' ? 'zh-CN' : state.language; + if(state.fontFamily)root.style.setProperty('--st-font',`${JSON.stringify(state.fontFamily)},system-ui,-apple-system,"Segoe UI",sans-serif`); + else root.style.removeProperty('--st-font'); + root.dataset.theme = state.theme === 'system' ? matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : state.theme; + document.querySelector<HTMLMetaElement>('meta[name="theme-color"]')?.setAttribute('content', root.dataset.theme === 'dark' ? '#0e1113' : '#f9fafb'); + root.dataset.contrast = state.contrast; + root.dataset.density = state.density; + root.style.setProperty('--st-content-fs', `${state.contentFontSize}px`); + // The interface size (#3970): the whole page is scaled, so every text, button, menu and dialog follows, not only the parts that were + // written with the scale token. The token stays at 1 so nothing is scaled twice. The reading size stays separate: someone who needs + // larger prose does not necessarily want larger buttons. + root.style.setProperty('--st-ui-scale', '1'); + root.style.setProperty('zoom', state.uiScale === 1 ? '' : String(state.uiScale)); + + // "system" means the OS decides, so the attribute is absent rather than set + // to a third value the stylesheet would have to special-case. + if (state.motion === 'system') delete root.dataset.motion; + else root.dataset.motion = state.motion; + + if (state.focus) root.dataset.focus = 'true'; + else delete root.dataset.focus; + + // "translucent" is the default, so the attribute only appears when it is off. + if (state.transparency === 'opaque') root.dataset.transparency = 'opaque'; + else delete root.dataset.transparency; +} + +function savePrefs() { + const snapshot: Prefs = { + sizeDefaults: SIZE_DEFAULTS_VERSION, + language: state.language, + fontFamily: state.fontFamily, + theme: state.theme, + contrast: state.contrast, + rail: state.rail, + focus: state.focus, + contentFontSize: state.contentFontSize, + density: state.density, + motion: state.motion, + transparency: state.transparency, + uiScale: state.uiScale, + electricityPrice: state.electricityPrice, + electricityCurrency: state.electricityCurrency, + doneSound: state.doneSound, + approvalNotify: state.approvalNotify, + whileBusy: state.whileBusy, + shareTelemetry: state.shareTelemetry, + }; + try { + localStorage.setItem(PREFS_KEY, JSON.stringify(snapshot)); + } catch { + /* a full quota must not break the UI */ + } + applyPrefs(); +} + +export function setTheme(theme: 'dark' | 'light' | 'system') { + set({ theme }); + savePrefs(); +} + +export function toggleRail() { + set({ rail: !state.rail }); + savePrefs(); +} +export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();rememberShellLanguage(language);} +let shellAnnounced = false; +/** The desktop shell's tray menu follows the app's language; it reads it from a small file the host keeps (no effect in a browser). */ +function rememberShellLanguage(language:Language){api.post('/api/shell/prefs',{language}).catch(()=>undefined);} +/** The shell started on another port than it wanted: the chats and settings saved on that port are not here, so say so once (#3402). */ +async function announcePortNotice(){ + try{ + const shell=await api.get<{portNotice:{wanted:number;used:number}|null}>('/api/shell'); + if(shell.portNotice)pushToast('warn',tr('Strata could not use its port'),tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.',[shell.portNotice.wanted,shell.portNotice.used])); + }catch{/* a browser or an older host has no shell */} +} +export function setFontFamily(fontFamily:string){set({fontFamily:fontFamily.trim().slice(0,128).replace(/[\x00-\x1f]/g,'')});savePrefs();} + +export function setFocus(focus: boolean) { + set({ focus }); + savePrefs(); +} + +export function toggleFocus() { + setFocus(!state.focus); +} + +/** + * Puts every appearance and reading preference back to its shipped value. + * + * Deliberately excludes `shareTelemetry`: a privacy choice is not an appearance + * setting, and re-enabling reporting as a side effect of resetting one's font + * size would be exactly the kind of thing this control exists to prevent. + * + * Deliberately does **not** touch `rail` or `focus`: those are where you happen + * to be working, not settings you chose, and collapsing the sidebar on someone + * who asked to reset their font size would be a surprise. The engine has its own + * reset, since an expert override and a font size have nothing to do with each + * other. + */ +export function resetAppearance() { + set({ + fontFamily: PREFS_DEFAULTS.fontFamily, + theme: PREFS_DEFAULTS.theme, + contrast: PREFS_DEFAULTS.contrast, + contentFontSize: PREFS_DEFAULTS.contentFontSize, + density: PREFS_DEFAULTS.density, + motion: PREFS_DEFAULTS.motion, + transparency: PREFS_DEFAULTS.transparency, + uiScale: PREFS_DEFAULTS.uiScale, + }); + savePrefs(); +} + +/** + * Records the standing privacy choice. + * + * The control was local component state that nothing persisted and nothing + * read — it snapped back on every reload, so a reader who turned reporting off + * had no way to know their choice had not been recorded. A privacy control that + * silently forgets is worse than no control at all. + */ +export function setShareTelemetry(on: boolean) { + set({ shareTelemetry: on }); + savePrefs(); +} + +export function setContentFontSize(px: number) { + const clamped = Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Math.round(px))); + set({ contentFontSize: clamped }); + savePrefs(); +} + +export function setDensity(density: 'comfortable' | 'compact') { + set({ density }); + savePrefs(); +} + +export function setMotion(motion: 'system' | 'full' | 'reduced') { + set({ motion }); + savePrefs(); +} + +export function setTransparency(transparency: 'translucent' | 'opaque') { + set({ transparency }); + savePrefs(); +} + +/** The electricity price for the Monitor's cost line: a positive price per kWh; 0 turns the line off. The currency is the detected one unless a three-letter code is given (#3628). */ +export function setElectricity(price: number, currency: string) { + const ok = Number.isFinite(price) && price > 0 && price < 1000; + set({ electricityPrice: ok ? Math.round(price * 10000) / 10000 : 0, electricityCurrency: /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : '' }); + savePrefs(); +} + +export function setWhileBusy(whileBusy: WhileBusy) { + if (!validWhileBusy(whileBusy)) return; + set({ whileBusy }); + savePrefs(); +} + +/** A message sent while an answer is being written waits here; the chat sends it when the answer is done (it is also where Interrupt leaves it). */ +export function parkMessage(sessionId: string, text: string) { + const clean = text.trim(); + if (!clean) return; + set({ parked: { ...state.parked, [sessionId]: [...(state.parked[sessionId] ?? []), clean] } }); +} +function setAsks(sessionId: string, list: AgentAsk[]) { + const next = { ...state.agentAsks }; + if (list.length) next[sessionId] = list; else delete next[sessionId]; + set({ agentAsks: next }); +} +/** The agent asked the person something (a frame of the host), or the question ended without an answer. */ +export function addAgentAsk(sessionId: string, frame: { callId?: unknown; questions?: unknown }) { + const ask = readAsk(frame); + // A /loop runs without anyone there: the question is skipped at once, so the loop never waits for an answer. + if (ask && loopScheduler.isRunning(sessionId)) { void answerAgentAsk(sessionId, ask.callId, null).catch(() => {}); return; } + if (ask) setAsks(sessionId, [...(state.agentAsks[sessionId] ?? []).filter(a => a.callId !== ask.callId), ask]); +} +export function removeAgentAsk(sessionId: string, callId?: string) { + const rest = callId === undefined ? [] : (state.agentAsks[sessionId] ?? []).filter(a => a.callId !== callId); + if ((state.agentAsks[sessionId]?.length ?? 0) !== rest.length) setAsks(sessionId, rest); +} +/** Sends the person's answer to the agent, or a skip (answers null). A refusal comes back as an error for the card to say in words. */ +export async function answerAgentAsk(sessionId: string, callId: string, answers: AgentAnswer[] | null) { + await api.post('/api/chat/answer', { sessionId, callId, ...(answers ? { answers } : { skip: true }) }); + removeAgentAsk(sessionId, callId); +} + +/** Puts a turn or a selected passage above the message box. */ +export function addQuote(sessionId: string, text: string, messageId: string, role: 'user' | 'assistant') { + const list = state.quotes[sessionId] ?? []; + const next = addToQuotes(list, { text, messageId, role }); + if (next.length !== list.length) set({ quotes: { ...state.quotes, [sessionId]: next } }); +} +export function removeQuote(sessionId: string, id: string) { + const rest = (state.quotes[sessionId] ?? []).filter(q => q.id !== id); + const next = { ...state.quotes }; + if (rest.length) next[sessionId] = rest; else delete next[sessionId]; + set({ quotes: next }); +} +export function clearQuotes(sessionId: string) { + if (!state.quotes[sessionId]) return; + const next = { ...state.quotes }; + delete next[sessionId]; + set({ quotes: next }); +} + +/** The first parked message of a chat, taken out of the list (to send it, or to give it back to the box). */ +export function takeParked(sessionId: string, index = 0): string | undefined { + const list = state.parked[sessionId] ?? []; + if (index < 0 || index >= list.length) return undefined; + const rest = list.filter((_, i) => i !== index); + const next = { ...state.parked }; + if (rest.length) next[sessionId] = rest; else delete next[sessionId]; + set({ parked: next }); + return list[index]; +} + +export function setDoneSound(doneSound: boolean) { + set({ doneSound }); + savePrefs(); +} + +export function setApprovalNotify(approvalNotify: boolean) { + set({ approvalNotify }); + savePrefs(); +} + +export const UI_SCALES = [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2] as const; + +export function setUiScale(uiScale: number) { + set({ uiScale }); + savePrefs(); +} + +export const CONTENT_FONT_RANGE = { min: CONTENT_FS_MIN, max: CONTENT_FS_MAX }; + +/* -------------------------------------------------------------- workspaces */ + +/** Opens the system folder chooser. Returns null when it is dismissed. */ +export async function pickWorkspace(): Promise<string | null> { + const res = await postWithFolderFallback<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick') as { path?: string }; + return res.path ?? null; +} + +export async function addWorkspace(path: string) { + try { + const ws = await api.post<Workspace>('/api/workspaces', { path }); + set({ workspaces: [...state.workspaces, ws] }); + pushToast('success', 'Workspace added', `Strata can now read files in ${ws.name}.`); + } catch (err) { + pushToast('error', "Couldn't add that folder", err instanceof Error ? err.message : String(err)); + } +} + +/** The name the sidebar shows for a workspace; its folder is unchanged. */ +export async function renameWorkspace(id: string, name: string) { + try { + const ws = await api.patch<Workspace>(`/api/workspaces/${id}`, { name }); + set({ workspaces: state.workspaces.map(w => (w.id === id ? { ...w, name: ws.name } : w)) }); + } catch (err) { + pushToast('error', "Couldn't rename that workspace", err instanceof Error ? err.message : String(err)); + } +} + +export async function removeWorkspace(id: string) { + const ws = state.workspaces.find((w) => w.id === id); + try { + await api.del(`/api/workspaces/${id}`); + set({ workspaces: state.workspaces.filter((w) => w.id !== id) }); + if (state.activeWorkspace === id) set({ activeWorkspace: state.workspaces[0]?.id ?? null }); + } catch (err) { + pushToast('error', "Couldn't remove that workspace", err instanceof Error ? err.message : String(err)); + } + void ws; +} + +/** + * Pins a conversation to the top of its workspace. + * + * Sessions are currently ordered by recency, which is right until you have + * thirty of them and two matter. `Session.pinned` has existed in the type since + * the beginning and was never written to. + */ +export function toggleArchive(id: string) { + const sessions = state.sessions.map((s) => (s.id === id ? { ...s, archived: !s.archived } : s)); + persistSessions(sessions); + set({ sessions }); +} + +export function togglePin(id: string) { + const sessions = state.sessions.map((s) => (s.id === id ? { ...s, pinned: !s.pinned } : s)); + persistSessions(sessions); + set({ sessions }); +} + +export function setActiveWorkspace(id: string) { + set({ activeWorkspace: id }); + void loadWorkspaceFiles(); +} + +export function openSetup(open: boolean) { + set({ setupOpen: open }); +} + +export function setPalette(open: boolean) { + set({ paletteOpen: open }); +} + +export function setShortcuts(open: boolean) { + set({ shortcutsOpen: open }); +} + +/* --------------------------------------------------------------- transport */ + +function applyEvent(e: StreamEvent) { + const data = e.data as Record<string, unknown>; + switch (e.event) { + case 'monitor': + set({ monitor: data as unknown as MonitorState }); + break; + case 'skills': + set({ skills: data as unknown as Skill[] }); + break; + case 'models': + if (Array.isArray(data.variants)) set({ library: data as unknown as ModelLibrary }); + break; + case 'runtime': + set({runtime:data as unknown as RuntimeModels}); + break; + case 'native': + applyNativeEvent(data); + break; + case 'image-models': + if (Array.isArray(data.variants)) set({ imageModels: data as unknown as ImageModelLibrary }); + break; + case 'providers': + applyProviders(data as unknown as ModelProviders); + break; + case 'goal': + if (typeof data.chatId === 'string') applyGoalFrame(data.chatId, data.goal); + break; + case 'plan': + if (typeof data.chatId === 'string') applyPlanFrame(data.chatId, data.plan); + break; + case 'queue': + if (typeof data.chatId === 'string') applyQueueFrame(data.chatId, data.queue); + break; + case 'timeskip': + applyTimeSkipEvent(data); + break; + case 'engine': + set({ engine: data as unknown as EngineConfig }); + break; + case 'serving': + set({ serving: newestServingState(state.serving, data as unknown as ServingState) }); + break; + case 'setup': + set({ setup: data as unknown as SetupState }); + break; + case 'task': { + // A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed. + const t = data as unknown as { title?: string; status?: string; attention?: string | null; error?: string | null }; + if (t.status === 'error') pushToast('error', 'Task failed', String(t.title ?? '')); + else if (t.attention) { pushToast('warn', 'Task needs your yes', String(t.title ?? '')); void approvalNeeded(state.approvalNotify, String(t.title ?? '')); } + else if (t.status === 'done') { pushToast('success', 'Task finished', String(t.title ?? '')); workFinished(state.doneSound, Infinity); } + break; + } + case 'agent': + if (typeof data.sessionId === 'string') patchSession(data.sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], data.agent) })); + break; + default: + break; + } +} + +let closeEvents: (() => void) | null = null; +export async function bootstrap() { + applyPrefs(); + try { + const [setup, hardware, library, engine, serving, monitor, skills, providers, imageModels, runtime] = await Promise.all([ + api.get<SetupState>('/api/setup'), + api.get<Hardware>('/api/hardware'), + api.get<ModelLibrary>('/api/models'), + api.get<EngineConfig>('/api/engine'), + api.get<ServingState>('/api/serving'), + api.get<MonitorState>('/api/monitor'), + api.get<Skill[]>('/api/skills'), + api.get<ModelProviders>('/api/model-providers'), + api.get<ImageModelLibrary>('/api/image-models'), + api.get<RuntimeModels>('/api/runtime'), + ]); + const workspaceState = await api.get<{ workspaces: Workspace[] }>('/api/workspaces'); + set({ + ready: true, + setup, + hardware, + library: libraryResponse(library), + imageModels, + runtime, + engine, + serving: newestServingState(state.serving, serving), + monitor, + skills, + workspacePath: workspaceState.workspaces[0]?.path ?? '', + workspaces: workspaceState.workspaces, + 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); + if (!shellAnnounced) { shellAnnounced = true; void announcePortNotice(); rememberShellLanguage(state.language); } + closeEvents?.(); + let reconnect = false; + closeEvents = onEvent(applyEvent, (status) => { + if (status === 'offline') reconnect = true; + if (status === 'live' && reconnect) { + reconnect = false; + // The restarted host may have new logs, config or readiness. Refresh + // those facts in place while retaining conversations and unsent drafts. + void bootstrap(); + return; + } + set({ connection: status }); + }); + if (!setup.complete && !setup.dismissed && !window.location.hash.includes('setup')) navigate('setup'); + } catch (err) { + set({ ready: true, connection: 'offline' }); + pushToast( + 'error', + 'Engine host unreachable', + err instanceof Error ? err.message : 'Start it with `npm run host` and reload.', + ); + } +} + +/* ------------------------------------------------------------- reads/writes */ + +export async function refreshHardware() { + set((s) => ({ busy: { ...s.busy, hardware: true } })); + try { + set({ hardware: await api.get<Hardware>('/api/hardware?reprobe=1') }); + } finally { + set((s) => ({ busy: { ...s.busy, hardware: false } })); + } +} + +function modelFits(id: string) { + const model = state.library?.variants.find(v => v.id === id); + if (state.library?.mode === 'real' && model && state.hardware && state.engine && ['too-large', 'unsupported'].includes(estimate(model, state.hardware, execution(Object.fromEntries(state.engine.expert.map(p => [p.id, p.value])), contextTokens(state.engine.beginner.contextLength))).fit)) { + pushToast('warn', 'Choose a smaller model', 'The estimated memory requirement exceeds this computer.'); + return false; + } + return true; +} + +export async function selectImageModel(selected: ImageModelChoice) { + set(s => ({ busy: { ...s.busy, 'image:select': true } })); + try { set({ imageModels: await api.patch<ImageModelLibrary>('/api/image-models', { selected }) }); } + finally { set(s => ({ busy: { ...s.busy, 'image:select': false } })); } +} +export async function installImageModel(id: Exclude<ImageModelChoice, 'off'>) { + set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/install`) }); +} +export async function cancelImageModel(id: Exclude<ImageModelChoice, 'off'>) { + set({ imageModels: await api.post<ImageModelLibrary>(`/api/image-models/${id}/cancel`) }); +} +export async function applyImageModel() { + set({ imageModels: await api.post<ImageModelLibrary>('/api/image-models/apply') }); +} + +export async function installVariant(id: string) { + // Download eligibility is checked against disk space by the host. Runtime fit + // is reviewed separately when the model is loaded. + if (state.busy[`install:${id}`]) return false; + set((s) => ({ busy: { ...s.busy, [`install:${id}`]: true } })); + try { + const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/install`)); + set({ library }); + const complete = library.variants.find(v => v.id === id)?.state === 'installed'; + pushToast(complete ? 'success' : 'info', complete ? 'Files installed' : library.mode === 'simulated' ? 'Example installation started' : 'Download started', complete ? 'Load the model to start a request.' : 'Progress is shown in Models.'); + return true; + } catch (err) { + pushToast('error', 'Download failed', err instanceof Error ? err.message : undefined); + return false; + } finally { + set((s) => ({ busy: { ...s.busy, [`install:${id}`]: false } })); + } +} + +export async function cancelInstall(id: string) { + try { set({ library: libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/cancel`)) }); } catch (e) { pushToast('error', 'Cancel failed', e instanceof Error ? e.message : String(e)); } +} + +export async function loadVariant(id: string) { + if (!modelFits(id)) return false; + if (!lifecycleAvailable()) return false; + set((s) => ({ busy: { ...s.busy, [`load:${id}`]: true }, actionError: null })); + try { + const library = libraryResponse(await api.post<ModelLibrary>(`/api/models/${id}/load`)); + set({ library }); + const model = library.variants.find(v => v.id === id); + if (library.loaded !== id || model?.state !== 'loaded') throw new Error(model?.error ?? 'The model did not finish loading.'); + pushToast('success', library.mode === 'simulated' ? 'Example model ready' : 'Model loaded', library.mode === 'simulated' ? 'Answers are simulated samples, not from a real model.' : 'Ready for a request.'); + return true; + } catch (err) { + const message = err instanceof Error ? err.message : 'The model did not load.'; + set({ + actionError: { + label: 'Could not load model', + message, + retry: () => void loadVariant(id), + }, + }); + pushToast('error', 'Could not load model', message); + return false; + } finally { + set((s) => ({ busy: { ...s.busy, [`load:${id}`]: false } })); + } +} + +export async function unloadModel() { + if (!lifecycleAvailable()) return false; + set(s => ({ busy: { ...s.busy, unload: true } })); + try { + const previousInstance=state.runtime?.defaultId; + const library = libraryResponse(await api.post<ModelLibrary>('/api/models/unload')); + const runtime=await api.get<RuntimeModels>('/api/runtime'); + set({runtime}); + set({ library }); + if (previousInstance?runtime.instances.some(i=>i.id===previousInstance):library.loaded!==null) throw new Error('The engine still reports this model instance as loaded.'); + pushToast('info', 'Model unloaded', library.mode === 'simulated' ? 'Example load state cleared.' : 'Model memory released.'); + return true; + } catch (err) { pushToast('error', 'Unload failed', err instanceof Error ? err.message : String(err)); return false; } + finally { set(s => ({ busy: { ...s.busy, unload: false } })); } +} + +export async function removeVariant(id: string) { + if (state.library?.loaded === id && !lifecycleAvailable()) return false; + const local = !!state.library?.variants.find(v => v.id === id)?.local; + try { const library = libraryResponse(await api.del<ModelLibrary>(`/api/models/${id}`)); set({ library }); + const remaining = library.variants.find(v => v.id === id); + if (remaining && remaining.state !== 'available') throw new Error('The model files were not removed.'); + pushToast('success', local ? 'Local model removed' : 'Files removed', local ? 'The original GGUF files are kept.' : library.mode === 'simulated' ? 'Example install state cleared.' : 'Model files removed from disk.'); return true; + } catch (e) { pushToast('error', 'Remove failed', e instanceof Error ? e.message : String(e)); return false; } +} + +export async function waitForInstalled(id: string) { + const deadline = Date.now() + 60 * 60 * 1000; + while (Date.now() < deadline) { + const v = state.library?.variants.find(v => v.id === id); + if (v && ['installed', 'loaded'].includes(v.state)) return; + if (!v || ['available', 'error'].includes(v.state)) throw new Error(v?.error ?? 'Download cancelled.'); + await new Promise(resolve => setTimeout(resolve, 500)); + } + throw new Error('Download timed out. Try again from Models.'); +} + +export async function saveEngine(patch: Partial<EngineConfig> | Record<string, unknown>, silent = false, requireIdle = false) { + if (requireIdle) { + const status = lifecycleStatus(); + if (!status.allowed) throw new Error(status.reason); + } + const engine = await api.patch<EngineConfig>('/api/engine', patch); + set({ engine, actionError: null }); + if (!silent) pushToast('success', 'Settings saved', 'Load settings take effect on the next load. Sampling defaults affect the next request.'); + return engine; +} + +export async function restartEngine() { + if (state.library?.mode === 'simulated') { pushToast('info', 'Restart unavailable with the example engine', 'Save settings for the next load.'); return false; } + if (!lifecycleAvailable()) return false; + set((s) => ({ busy: { ...s.busy, restart: true }, actionError: null })); + try { + const engine = await api.post<EngineConfig>('/api/engine/restart'); + set({ engine }); + if (!engine.engine.running) throw new Error(engine.engine.error ?? 'The engine is not running. Load a model before applying settings.'); + pushToast('success', 'Engine restarted', 'Warm-up takes a few seconds.'); + return true; + } catch (err) { + // Reported in place as well as in a toast: the toast is a summary, the + // surface that failed is where the retry belongs. + set({ + actionError: { + label: 'Restart failed', + message: err instanceof Error ? err.message : 'The engine did not come back up.', + retry: () => void restartEngine(), + }, + }); + pushToast('error', 'Restart failed', err instanceof Error ? err.message : undefined); + return false; + } finally { + set((s) => ({ busy: { ...s.busy, restart: false } })); + } +} + +export function dismissActionError() { + set({ actionError: null }); +} + +export async function resetEngine() { + set({ engine: await api.post<EngineConfig>('/api/engine/reset') }); + pushToast('info', 'Back to recommended', 'Every value returned to the safe default.'); +} + +/** + * Checks an engine config — the saved one by default, or a draft to preview what + * a change would do before committing to it. + */ +export async function validateEngine(draft?: unknown) { + return api.post<{ + ok: boolean; + issues: { level: 'warn' | 'error'; message: string }[]; + predicted?: EngineConfig['predicted']; + }>('/api/engine/validate', draft ?? {}); +} + +export async function exportEngine() { + return api.get<Record<string, unknown>>('/api/engine/export'); +} + +export async function setCloudflare(body: {action: 'start' | 'stop' | 'prepare'; mode?: 'quick' | 'domain'; hostname?: string; token?: string}) { + const result = await api.post<ServingState>('/api/serving/tunnel', body); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function setLocalSharing(enabled: boolean) { + const result = await api.post<ServingState>('/api/serving/share', { enabled }); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function setServingAccess(patch: { otherDevices?: boolean; apiKey?: string | null }) { + const result = await api.patch<ServingState>('/api/serving', patch); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function pauseServing(paused: boolean) { + const result = await api.patch<ServingState>('/api/serving', { pauseServing: paused }); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function cancelRequest(id: string) { + const result = await api.post<ServingState>(`/api/serving/requests/${id}/cancel`); + set({ serving: newestServingState(state.serving, result) }); +} + +export async function completeSetupStep(step: number, choices?: SetupState['choices'], dismissed = false) { + set({ setup: await api.post<SetupState>('/api/setup/step', { step, choices, dismissed, flowVersion: 2 }) }); +} + +export async function completeSetup() { + const setup = await api.post<SetupState>('/api/setup/complete'); + set({ setup }); +} + +export async function setSkills(skills: Skill[]) { + set({ skills }); +} + +/** + * Re-reads the skill list from the host. + * + * For the case where a skill was added to the workspace folder while the app was + * open — otherwise the only way to see it is to restart. + */ +export async function loadSkills() { + set({ skills: await api.get<Skill[]>('/api/skills') }); +} + +/** Re-reads the workspace tree from disk, for the same reason. */ +export async function loadWorkspaceFiles() { + const data = await api.get<{ path: string; entries: WorkspaceFile[] }>(`/api/workspace${state.activeWorkspace ? '?root=' + encodeURIComponent(state.activeWorkspace) : ''}`); + set({ files: data.entries, workspacePath: data.path }); +} + +export async function toggleSkill(id: string, enabled: boolean) { + set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { enabled }) }); +} + +export async function editSkill(id: string, patch: Pick<Skill, 'name' | 'description' | 'body' | 'triggers' | 'enabled' | 'onlyIn'>) { + set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, patch) }); +} + +/** + * Narrows a skill to the workspace you are in, or widens it again. + * + * Passing null clears the narrowing. The host resolves `onlyIn` against the + * workspace the request came from, so the answer depends on where the reader + * is rather than on a single global switch. + */ +export async function scopeSkill(id: string, workspaceId: string | null) { + set({ skills: await api.patch<Skill[]>(`/api/skills/${encodeURIComponent(id)}`, { onlyIn: workspaceId }) }); +} + +/* ---------------------------------------------------------------- sessions */ + +const sessionWriter = createSessionWriter({ + write: (json) => { + try { + localStorage.setItem(SESSION_KEY, json); + } catch { + /* quota — sessions are a cache, not the source of truth */ + } + }, +}); + +/** + * Save the chat list. A one-off change (new, rename, delete, pin) is written now; `soon` is for the streaming + * path, where a write per token grew the renderer to gigabytes (#3604, #3603): those are coalesced to one a second. + */ +function persistSessions(sessions: Session[], soon = false) { + sessionWriter.schedule(sessions); + if (!soon) sessionWriter.flush(); +} + +/** Write the newest chat list now: a turn ended, or the page is going away. */ +export function flushSessions() { + sessionWriter.flush(); +} + +if (typeof window !== 'undefined' && typeof document !== 'undefined' && window.addEventListener) { + window.addEventListener('pagehide', flushSessions); + document.addEventListener?.('visibilitychange', () => { if (document.visibilityState === 'hidden') flushSessions(); }); +} + +export function newSession(): Session { + const session: Session = { + id: uid('s'), + title: 'New conversation', + defaultTitle: true, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + messages: [], + workspace: state.workspaces.find(w => w.id === state.activeWorkspace)?.path ?? state.workspacePath, + tokensIn: 0, + tokensOut: 0, + ...(state.activeSession === null && state.remoteModel ? { preferences: { remoteModel: state.remoteModel } } : {}), + }; + const sessions = [session, ...state.sessions]; + persistSessions(sessions); + set({ sessions, activeSession: session.id }); + return session; +} + +export function setChatPreferences(id: string | undefined, preferences: NonNullable<Session['preferences']>) { + const sessionId = id ?? newSession().id; + patchSession(sessionId, s => ({ ...s, preferences: { ...s.preferences, ...preferences } })); + // A mode change applies to the very next tool call of a turn that is already running (a goal and its helpers included). + if (preferences.mode && liveTurns.get(sessionId)?.agent) void api.post('/api/chat/mode', { sessionId, mode: preferences.mode }).catch(() => undefined); +} +export function setPreviewTabClosed(sessionId:string|undefined, artifactId:string, closed:boolean, selected:string|null) { + if(!sessionId)return; + patchSession(sessionId,s=>({...s,closedPreviews:closed?[...new Set([...(s.closedPreviews??[]),artifactId])]:(s.closedPreviews??[]).filter(id=>id!==artifactId),previewOpen:selected??undefined})); +} +export function createChatShowcase() { + const session=newSession();const at=new Date().toISOString(); + patchSession(session.id,s=>({...s,title:'Chat showcase · code, tools & media',showcase:true,statsAvailable:true,tokensIn:28000000,tokensOut:4000000,messages:showcaseMessages(at),agents:SHOWCASE_AGENTS,showcaseAgentStates:true})); + go('chat',session.id); +} + +/** A visible example for checking the subagent interface in the design build. */ +export function createSubagentExample() { + const session = newSession(); const now = Date.now(); + patchSession(session.id, s => ({ ...s, title: 'Subagent preview', showcase: true, showcaseAgentStates: true, + agents: [ + {id:'example-layout',name:'Layout review',description:'Checking spacing and component alignment.',status:'working',durationMs:39000,tokens:12600,updatedAt:now}, + {id:'example-interactions',name:'Interaction review',description:'Checking menus, controls and keyboard navigation.',status:'working',durationMs:21000,tokens:8400,updatedAt:now}, + {id:'example-copy',name:'Copy review',description:'Labels and descriptions reviewed.',status:'completed',durationMs:18000,tokens:4200,updatedAt:now}, + ], messages: [{id:uid('m'),role:'assistant',at:new Date(now).toISOString(),example:true,content:'Open the subagent count above to inspect this example run. Each row shows status, token usage and elapsed time.'}] + })); + go('chat', session.id); +} + +export function createPreviewExamples() { + const session = newSession(); + const at = new Date().toISOString(); + patchSession(session.id, s => ({ ...s, title: 'Design review · six previews', previewOpen:'sample-website', messages: [ + { id:uid('m'), role:'user', at, content:'Open six different output types so I can iterate on the preview design.' }, + { id:uid('m'), role:'assistant', at, demo:true, content:'Here is a design-review workspace for Fieldnotes: a website, PDF, Markdown brief, cover image, TypeScript file and release table.\n\nAll six are loaded in the panel on the right. Switch tabs to explore each view while keeping this conversation in place.', artifacts:PREVIEW_EXAMPLES }, + ] })); + go('chat', session.id); +} + +/** "Continue in a new chat" on a task: a new chat whose first message is the task's findings, what it did and its files (src/lib/task-handover.ts). */ +export function continueTaskInNewChat(task: Task) { + const session = newSession(); + go('chat', session.id); + void sendMessage(taskHandoverMessage(task), { title: taskHandoverTitle(task), markdown: true }); +} + +export function selectSession(id: string) { + // 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); +} + +/** Records that a conversation has been looked at. */ +export function markRead(id: string) { + const at = new Date().toISOString(); + const sessions = state.sessions.map((s) => (s.id === id ? { ...s, lastReadAt: at } : s)); + persistSessions(sessions); + set({ sessions }); +} + +/** + * Whether a conversation has moved on since it was last looked at. + * + * The active conversation is never unread: you are looking at it, or its reply + * is arriving in front of you. + */ +export function isUnread(s: Session, activeSession: string | null): boolean { + if (s.id === activeSession) return false; + if (!s.lastReadAt) return s.messages.length > 0; + return s.updatedAt > s.lastReadAt; +} + +export function deleteSession(id: string) { + const sessions = state.sessions.filter((s) => s.id !== id); + persistSessions(sessions); + set({ sessions, activeSession: state.activeSession === id ? (sessions[0]?.id ?? null) : state.activeSession }); +} + +export function renameSession(id: string, title: string) { + const sessions = state.sessions.map((s) => (s.id === id ? { ...s, title, defaultTitle: false } : s)); + persistSessions(sessions); + set({ sessions }); +} + +function patchSession(id: string, fn: (s: Session) => Session) { + const sessions = state.sessions.map((s) => (s.id === id ? fn(s) : s)); + persistSessions(sessions, true); + set({ sessions }); +} + +// The demo clock belongs to the session, so hiding the sidebar or navigating +// away never pauses it. Only start and completion are written to storage. +const timeSkipTimers = new Map<string, ReturnType<typeof setTimeout>>(); +function scheduleTimeSkip(sessionId: string, run: TimeSkipRun) { + const timerId = `${sessionId}:${run.id}`; + clearTimeout(timeSkipTimers.get(timerId)); + if (run.completedAt || run.job) return; + timeSkipTimers.set(timerId, setTimeout(() => { + timeSkipTimers.delete(timerId); + const session = state.sessions.find(s => s.id === sessionId); + const current = session?.timeSkips?.find(r => r.id === run.id); + if (!current || current.startedAt !== run.startedAt || !session?.messages.some(m => m.timeSkipId === run.id && m.role === 'assistant')) return; + patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(), + timeSkips: s.timeSkips?.map(r => r.id === run.id ? { ...r, completedAt: run.startedAt + TIME_SKIP_DURATION } : r), + messages: s.messages.map(m => m.timeSkipId === run.id && m.role === 'assistant' ? { ...m, content: 'The updated result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.' } : m), + })); + }, Math.max(0, run.startedAt + TIME_SKIP_DURATION - Date.now()))); +} + +export function replayTimeSkip(sessionId: string, runId: string) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + if (!run) return; + const next = { ...run, startedAt: Date.now(), completedAt: undefined, retainedVersion: undefined }; + patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r), + messages: s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.' } : m), + })); + scheduleTimeSkip(sessionId, next); +} + +export function setTimeSkipResult(sessionId: string, runId: string, version: TimeSkipVersion) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + if (!run) return; + if (run.job) { void keepTimeSkip(sessionId, runId, version); return; } + const next = withTimeSkipResult(run, version, Date.now()); + if (next === run) return; + patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r) })); +} + +/* ------------------------------------------------------- Time-skip, for real + The host copies the chat's folder, lets the assistant change the copy, checks it and keeps the original untouched until the + person chooses. The sidebar follows the job's own record; nothing here invents progress. */ +const TS_TERMINAL = ['completed', 'cancelled', 'failed', 'interrupted']; +const TS_WORKING = () => tr('Working on a copy of your files. Follow the progress in the sidebar.'); +const TS_READY = () => tr('The result is ready. Switch between Original and Updated, or compare them side by side.'); + +function patchRun(sessionId: string, runId: string, fn: (run: TimeSkipRun) => TimeSkipRun, content?: string) { + patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(), + timeSkips: s.timeSkips?.map(r => r.id === runId ? fn(r) : r), + messages: content === undefined ? s.messages : s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content } : m), + })); +} + +/** The job's error in a sentence a person can use. */ +export function plainTimeSkipError(raw: string | null | undefined): string { + const text = String(raw ?? '').trim(); + if (!text) return tr('Something went wrong.'); + const afterExit = /\(exit \d+\):\s*([\s\S]*)$/.exec(text); + const body = (afterExit?.[1] ?? text).replace(/^\w*Error:\s*/, '').trim(); + if (/destination changed|refusing to overwrite/i.test(body)) return tr('Your files changed after this trial started, so nothing was overwritten. Run Time-skip again.'); + if (/too big/i.test(body)) return tr('This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.'); + if (/folder of your own/i.test(body)) return tr('Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.'); + if (/Load a model|model first/i.test(body)) return tr('Load a model first, then try Time-skip again.'); + if (/needs the Strata app|could not be reached/i.test(body)) return tr('The assistant could not be reached. Try again.'); + return body.length > 300 ? body.slice(0, 299) + '…' : body; +} + +/** The host says a Time-skip run moved on (phase, and what it is doing now): the working view shows the newest words. */ +function applyTimeSkipEvent(data: Record<string, unknown>) { + const id = typeof data.id === 'string' ? data.id : ''; + if (!id) return; + for (const session of state.sessions) { + const run = session.timeSkips?.find(r => r.job?.id === id); + if (!run || run.completedAt) continue; + patchRun(session.id, run.id, r => ({ ...r, job: { ...r.job!, ...(typeof data.phase === 'string' ? { phase: data.phase as TimeSkipJob['phase'] } : {}), activity: data.activity as TimeSkipJob['activity'], ...forkFields(data) } })); + } +} + +function timeSkipEnding(job: TimeSkipJob, files: TimeSkipFile[]): string { + if (job.phase === 'failed') return tr('Time-skip stopped. {0} Your files were not changed.', [plainTimeSkipError(job.error)]); + if (job.phase === 'cancelled' || job.phase === 'interrupted') return tr('Time-skip was stopped before it finished. Your files were not changed.'); + if (!files.length) return tr('The assistant did not change anything, so there is nothing to compare. Your files were not changed.'); + return isForkJob(job) ? tr('Both versions are ready. Compare A and B, then keep one.') : TS_READY(); +} + +async function startTimeSkipReal(prompt: string) { + const sessionId = state.activeSession ?? newSession().id; + const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now(), + job: { id: '', phase: 'queued', attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: false, error: null } }; + const at = new Date().toISOString(); + patchSession(sessionId, s => ({ ...s, + defaultTitle: false, + title: s.messages.length ? s.title : prompt.length > 48 ? prompt.slice(0, 47).trimEnd() + '…' : prompt, updatedAt: at, + // The comparison sidebar opens only when there is an update to compare (when the job ends with changed files), never while it works. + timeSkips: [...(s.timeSkips ?? []), run], + messages: [...s.messages, + { id: uid('m'), role: 'user', at, content: '/time-skip ' + prompt, timeSkipId: run.id }, + { id: uid('m'), role: 'assistant', at, timeSkipId: run.id, content: TS_WORKING() }, + ], + })); + go('chat', sessionId); + markTurn(sessionId, { abort: new AbortController(), agent: false }); + try { + const started = await api.post<{ run: TimeSkipJob }>('/api/timeskip/start', { prompt, sessionId, workspaceId: state.activeWorkspace, attempts: 1, ...(state.remoteModel ? { remoteModel: state.remoteModel } : {}) }); + patchRun(sessionId, run.id, r => ({ ...r, job: started.run })); + void followTimeSkip(sessionId, run.id); + } catch (e) { + const message = plainTimeSkipError(e instanceof Error ? e.message : String(e)); + patchRun(sessionId, run.id, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'failed', error: message } }), tr('Time-skip could not start. {0}', [message])); + markTurn(sessionId, null); + } +} + +const followingTimeSkips = new Set<string>(); +/** Read the job's record until it ends. Safe to call again for a run already being followed. */ +export async function followTimeSkip(sessionId: string, runId: string) { + const key = sessionId + ':' + runId; + if (followingTimeSkips.has(key)) return; + followingTimeSkips.add(key); + let misses = 0; + try { + for (;;) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + if (!run?.job?.id || run.completedAt) return; + let job: TimeSkipJob | null = null; + try { job = (await api.get<{ run: TimeSkipJob }>('/api/timeskip/status?id=' + encodeURIComponent(run.job.id))).run; misses = 0; } + catch { misses += 1; } + if (job && TS_TERMINAL.includes(job.phase)) { + let files: TimeSkipFile[] = [], extra: Partial<TimeSkipJob> = {}; + // The changed files are what the person came for: ask again a few times before settling for "nothing to compare". + for (let tryNo = 0; tryNo < 4; tryNo++) { + try { + const found = await api.get<{ files: TimeSkipFile[]; applyAttempt: number | null; more: number }>('/api/timeskip/files?id=' + encodeURIComponent(job.id)); + files = found.files; extra = { files: found.files, applyAttempt: found.applyAttempt, moreFiles: found.more }; + break; + } catch { await new Promise(r => setTimeout(r, 700 * (tryNo + 1))); } + } + const finished = { ...job, ...forkFields(job as unknown as Record<string, unknown>) }; + patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, ...finished, ...extra } }), timeSkipEnding(finished, files)); + // A run that changed files opens the comparison; one that changed nothing, failed or was stopped has no sidebar tab. + if (files.length > 0 && !['failed', 'cancelled', 'interrupted'].includes(finished.phase)) patchSession(sessionId, s => ({ ...s, previewOpen: timeSkipTabId(runId) })); + markTurn(sessionId, null); + return; + } + if (job) { const live = { ...job, ...forkFields(job as unknown as Record<string, unknown>) }; patchRun(sessionId, runId, r => ({ ...r, job: { ...r.job!, ...live } })); } + if (misses >= 6) { + patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'interrupted' } }), tr('Time-skip lost contact with the app and stopped. Your files were not changed.')); + markTurn(sessionId, null); + return; + } + await new Promise(r => setTimeout(r, 2000)); + } + } finally { followingTimeSkips.delete(key); } +} + +/** Ask the host to stop a running trial. The saved version stays. */ +export async function stopTimeSkip(sessionId: string, runId: string) { + const id = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId)?.job?.id; + if (id) await api.post('/api/timeskip/stop', { id }).catch(() => undefined); +} + +/** Put the update into the person's files, or put the original back. Both are checked and undoable. */ +export async function keepTimeSkip(sessionId: string, runId: string, version: TimeSkipVersion) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + const job = run?.job; + if (!run || !job?.id || !job.phase || !TS_TERMINAL.includes(job.phase)) return; + if ((run.retainedVersion ?? 'original') === version && !(isForkJob(job) && run.retainedVersion === undefined)) { patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); return; } + try { + if (isForkJob(job)) await api.post('/api/timeskip/apply', { id: job.id, which: version === 'original' ? 'a' : 'b' }); + else if (version === 'updated') await api.post('/api/timeskip/apply', { id: job.id, attempt: job.applyAttempt ?? null }); + else await api.post('/api/timeskip/apply', { id: job.id, restore: true }); + patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); + pushToast('success', version === 'updated' ? tr('The update is now in your files') : tr('Your original files are back')); + } catch (e) { + pushToast('error', tr('Your files were not changed'), plainTimeSkipError(e instanceof Error ? e.message : String(e))); + } +} + +function startTimeSkipDemo(prompt: string) { + if (!prompt) { pushToast('info', 'Add a prompt after /time-skip', 'For example: /time-skip Make a launch plan for my app'); return; } + const sessionId = state.activeSession ?? newSession().id; + const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now() }; + const at = new Date().toISOString(); + patchSession(sessionId, s => ({ ...s, + defaultTitle: false, + title: s.messages.length ? s.title : prompt.length>48?prompt.slice(0,47).trimEnd()+'…':prompt, updatedAt: at, + timeSkips: [...(s.timeSkips ?? []), run], previewOpen: timeSkipTabId(run.id), + messages: [...s.messages, + { id: uid('m'), role: 'user', at, content: `/time-skip ${prompt}`, timeSkipId: run.id }, + { id: uid('m'), role: 'assistant', at, example: true, timeSkipId: run.id, content: 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks; it doesn’t run your model.' }, + ], + })); + scheduleTimeSkip(sessionId, run); + go('chat', sessionId); +} + +function markTurn(sessionId: string, turn: { abort: AbortController; agent: boolean } | null) { + if (turn) liveTurns.set(sessionId, turn); else liveTurns.delete(sessionId); + set({ streaming: !!state.activeSession && liveTurns.has(state.activeSession), liveChats: liveTurns.size }); + document.documentElement.dataset.streaming = liveTurns.size ? 'true' : 'false'; +} + +/** + * Stop the open chat's turn. The host is asked first: for an agent turn it cancels exactly this chat's + * Harness session and answers only once the turn has ended, and the stream then closes by itself with + * what was produced. For any other turn the host reports nothing to stop and the request is aborted. + */ +export function stopStreaming() { + const id = state.activeSession; + const turn = id ? liveTurns.get(id) : undefined; + if (!id || !turn) return; + const abort = () => { turn.abort.abort(); }; + void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then( + result => { + if (!result.stopped) abort(); + // An agent turn that was told to stop but is slow to end must not leave the chat stuck. + else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); + }, + abort, + ); +} + +/** + * Re-runs the last exchange: drops the assistant reply and asks again. + * + * Kept in the store rather than the screen because it has to touch the message + * list, and every attempt to do this from a component ends up duplicating the + * stream handling that already lives here. + */ +export async function retryLast(messageId?: string) { + const source = state.sessions.find(s => s.id === state.activeSession); + if (!source || state.streaming) return; + const end = messageId ? source.messages.findIndex(m => m.id === messageId) : source.messages.length - 1; + const user = source.messages.slice(0, end + 1).reverse().find(m => m.role === 'user'); + if (!user) return; + const prompt = rewindTo(user.id); + if (prompt !== null) { + // Retry sends immediately; only Edit should leave the prompt in the composer. + sessionStorage.setItem(`strata.chat-draft.${state.activeSession}`, ''); + await sendMessage(prompt); + } +} + +/** The open chat's last question and the answer that failed under it (null when the chat does not end that way). */ +function failedExchange(): { prompt: string; sessionId: string } | null { + const sessionId = state.activeSession; + const chat = state.sessions.find(s => s.id === sessionId); + if (!sessionId || !chat || state.streaming) return null; + const reply = chat.messages[chat.messages.length - 1], ask = chat.messages[chat.messages.length - 2]; + return reply?.role === 'assistant' && reply.error && ask?.role === 'user' ? { prompt: ask.content, sessionId } : null; +} +/** Takes the failed question and its error out of the transcript, so asking again does not show the question twice. */ +function dropFailedExchange(sessionId: string) { + patchSession(sessionId, s => ({ ...s, messages: s.messages.slice(0, -2) })); +} + +/** + * The error card of a conversation that no longer fits the model's window: summarise the older messages (the same as typing /compact), then + * ask the assistant to answer. The refused question is already in the assistant's conversation (it is the newest message, and a summary keeps + * the newest message as it is), so it is not sent a second time: a large one twice would not fit either. + */ +export async function summarizeAndContinue() { + if (!failedExchange()) return; + await sendMessage('/compact'); + await sendMessage('Please answer my last message now.'); +} + +/** + * The error card of a message that is too large to send: the host makes it small enough (its text as a file in the chat's folder that the + * assistant reads in parts, or a shortened preview), and that is sent in its place. + */ +export async function sendOversized(mode: 'file' | 'preview') { + const failed = failedExchange(); + if (!failed) return; + let reply: { message?: string }; + try { + reply = await api.post<{ message?: string }>('/api/chat/oversize', { sessionId: failed.sessionId, mode, text: failed.prompt, nativeModelId: nativeState()?.instances.length ? nativeState()?.defaultId : undefined }); + } catch { + pushToast('error', 'The message could not be prepared. Try a shorter message.'); + return; + } + if (!reply.message) return; + dropFailedExchange(failed.sessionId); + await sendMessage(reply.message); +} + +/** A new, empty chat, opened. */ +export function startNewChat() { + const session = newSession(); + go('chat', session.id); +} + +/** + * Forks a conversation at a message, leaving the original untouched. + * + * The alternative people reach for is duplicating the whole session and + * deleting messages by hand, which loses the original. Branching keeps both: + * the new session carries the history up to the chosen turn and diverges there. + */ +export function branchFrom(messageId: string): string | null { + const sessionId = state.activeSession; + if (!sessionId) return null; + const source = state.sessions.find((s) => s.id === sessionId); + if (!source) return null; + const at = source.messages.findIndex((m) => m.id === messageId); + if (at < 0) return null; + + const now = new Date().toISOString(); + const branch: Session = { + ...source, + id: uid('s'), + title: `${source.title} (branch)`, + defaultTitle: false, + createdAt: now, + updatedAt: now, + messages: source.messages.slice(0, at + 1).map((m) => ({ ...m, id: uid('m') })), + tokensIn: 0, + tokensOut: source.messages.slice(0, at + 1).reduce((n, m) => n + (m.tokens ?? 0), 0), + statsAvailable: false, + }; + const sessions = [branch, ...state.sessions]; + persistSessions(sessions); + set({ sessions, activeSession: branch.id }); + for (const run of branch.timeSkips ?? []) scheduleTimeSkip(branch.id, run); + // The URL wins over `activeSession` when it names a session, so a programmatic + // switch has to move the route too — otherwise the sidebar shows the branch + // while the transcript still shows the original, which reads as a broken + // button rather than a created branch. + navigate('chat', branch.id); + return branch.id; +} + +/** + * Asks the model to keep going from where it stopped. + * + * Sent as an ordinary user turn rather than a special mode, because that is + * what it is: a continuation is a request, and the transcript should show it. + */ +export async function continueLast() { + const sessionId = state.activeSession; + if (!sessionId || state.streaming) return; + const session = state.sessions.find((s) => s.id === sessionId); + const last = session?.messages[session.messages.length - 1]; + if (!last || last.role !== 'assistant' || !last.content.trim()) return; + await sendMessage('Continue from where you left off. Do not repeat what you have already written.'); +} + +/** + * Rewinds the transcript to just before a turn so it can be re-asked with a + * different prompt. Returns the text so the composer can be filled with it. + */ +export function rewindTo(messageId: string): string | null { + if (state.streaming) return null; + const source = state.sessions.find(s => s.id === state.activeSession); + const at = source?.messages.findIndex(m => m.id === messageId) ?? -1; + if (!source || at < 0) return null; + const prompt = source.messages[at].content; + const branchId = branchFrom(messageId); + if (!branchId) return null; + patchSession(branchId, s => ({ ...s, messages: s.messages.slice(0, -1), tokensIn: 0, tokensOut: s.messages.slice(0, -1).reduce((n, m) => n + (m.tokens ?? 0), 0) })); + sessionStorage.setItem(`strata.chat-draft.${branchId}`, prompt); + return prompt; +} + +export function exportConversation() { + const session = state.sessions.find(s => s.id === state.activeSession); + if (!session) return; + const text = '# ' + session.title + '\n\n' + session.messages.map(m => '## ' + m.role + '\n\n' + (m.role === 'assistant' ? tidyAnswer(m.content) : m.content)).join('\n\n'); + const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown' })); + const a = document.createElement('a'); a.href = url; a.download = session.title.replace(/[^a-z0-9 -]/gi, '').slice(0, 60) + '.md'; + document.body.append(a); a.click(); a.remove(); + // Keep the Blob alive until browsers have started consuming the download. + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +/* ---------------------------------------------------------------- /loop + The same message, again and again, while the chat is open. The scheduler (count, time, "the answer says it is done") is + lib/loop-runner.ts; this is the part that talks to the chat. See lib/loop.ts. */ + +/** A line from the app itself (not the model) in the transcript. It is never sent to the model. */ +function addNote(sessionId: string, content: string) { + const at = new Date().toISOString(); + patchSession(sessionId, s => ({ ...s, updatedAt: at, messages: [...s.messages, { id: uid('m'), role: 'assistant', at, content, local: true }] })); +} + +const lastAnswer = (sessionId: string) => [...(state.sessions.find(s => s.id === sessionId)?.messages ?? [])].reverse().find(m => m.role === 'assistant' && !m.local); + +const loopScheduler = new LoopScheduler({ + async send(sessionId, { text, shown }) { + const before = lastAnswer(sessionId)?.id; + await sendMessage(text, { fromLoop: true, shown, title: shown.length > 48 ? shown.slice(0, 47).trimEnd() + '…' : shown }); + const answer = lastAnswer(sessionId); + if (!answer || answer.id === before || answer.streaming) return { answered: false, text: '', failed: false }; + return { answered: true, text: answer.content ?? '', failed: !!answer.error }; + }, + note: addNote, + exists: sessionId => state.sessions.some(s => s.id === sessionId), + ready: sessionId => state.activeSession === sessionId && !state.streaming, + now: () => Date.now(), + setTimer: (fn, ms) => setTimeout(fn, ms), + clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>), + track: (sessionId, loop) => patchSession(sessionId, s => ({ ...s, loop })), +}); + +export function loopIsRunning(sessionId: string | null): boolean { return loopScheduler.isRunning(sessionId); } + +/* ------------------------------------------------------------- task board */ + +/** The chats with a turn going, and the chats with a loop going: what the board needs besides the sessions themselves. */ +export function liveChatIds(): string[] { return [...liveTurns.keys()]; } +export function loopChatIds(): string[] { return loopScheduler.ids(); } + +/** Stop any chat's turn, not only the open one (the board's Stop). Same two-step as stopStreaming. */ +export function stopChat(id: string) { + const turn = liveTurns.get(id); + if (!turn) return; + const abort = () => { turn.abort.abort(); }; + void api.post<{ stopped: boolean }>('/api/chat/stop', { sessionId: id }).then( + result => { if (!result.stopped) abort(); else setTimeout(() => { if (liveTurns.get(id) === turn) abort(); }, 30000); }, + abort, + ); +} + +/** Stop a chat's loop from the board. The chat gets the same line /loop stop writes. */ +export function stopLoop(id: string) { + if (loopScheduler.stop(id)) addNote(id, tr('The loop is stopped.')); +} + +/** Dismiss a chat's (or its loop's) card: it leaves the board until something newer goes wrong. The chat itself is untouched. */ +export function dismissChat(id: string) { + const sessions = state.sessions.map(s => (s.id === id ? { ...s, ackedAt: new Date().toISOString() } : s)); + persistSessions(sessions); + set({ sessions }); +} + +/** Answer a waiting tool card in any chat (the board's Approve and Deny). Only a live card has an approval behind it. */ +export function answerChatTool(sessionId: string, messageId: string, toolId: string, approved: boolean) { + const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId); + if (tool?.live && tool.state === 'proposed') answerAgentTool(sessionId, messageId, tool, approved); +} + +/** "Continue in a new chat" on a chat or a loop that went wrong: a new chat that starts from what happened (src/lib/task-handover.ts). */ +export function continueChatInNewChat(sessionId: string) { + const old = state.sessions.find(s => s.id === sessionId); + if (!old) return; + const session = newSession(); + go('chat', session.id); + void sendMessage(chatHandoverMessage(old), { title: chatHandoverTitle(old), markdown: true }); +} + +async function runLoopCommand(command: LoopCommand) { + const sessionId = state.activeSession ?? newSession().id; + const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); }; + if (command.kind === 'help') { say(tr(command.problem) + '\n\n' + tr(LOOP_USAGE)); return; } + if (command.kind === 'status') { say(loopScheduler.describe(sessionId) ?? tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE)); return; } + if (command.kind === 'stop') { say(loopScheduler.stop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; } + go('chat', sessionId); + await loopScheduler.start(sessionId, command); +} + +/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */ +export async function resumeGoal() { await sendMessage('', { goalAction: 'resume' }); } + +/** Approve a proposed plan and carry it out: the host answers with the message that does the work, which goes out as an ordinary turn. */ +export async function approvePlan(sessionId: string, planId: string) { + const { prompt } = await planApprove(sessionId, planId); + // A chat in Plan mode only reads; carrying the plan out needs a mode that may act. + if (state.sessions.find(s => s.id === sessionId)?.preferences?.mode === 'plan') setChatPreferences(sessionId, { mode: 'manual' }); + if (prompt) await sendMessage(prompt, { shown: tr('Approved the plan.') }); +} + +/** "Start as goal" (and Resume on a paused plan): the host streams the run like any chat turn. */ +export async function startPlanGoal(planId: string) { await sendMessage('', { planId }); } + +export async function sendMessage(text: string, options: { fromLoop?: boolean; goalAction?: 'resume'; planId?: string; shown?: string; title?: string; markdown?: boolean } = {}) { + if (state.streaming) { + // Typed while the assistant works: behind a running goal it waits in the queue; otherwise there is nothing to do but wait. + const waiting = state.activeSession, line = text.trim(); + if (waiting && line && !options.planId && !options.goalAction) { + try { if (!(await queueMessage(waiting, line))) pushToast('info', 'The assistant is still answering', 'Send your message when it has finished.'); } + catch (e) { pushToast('error', 'The message was not queued', plainFailureText(e instanceof Error ? e.message : String(e)).message); } + } + return; + } + const resume = options.goalAction === 'resume'; + const planStart = options.planId; + const loopCommand = options.fromLoop || resume || planStart ? null : parseLoop(text.trim()); + if (loopCommand) { await runLoopCommand(loopCommand); return; } + const demoPrompt = resume || planStart ? null : timeSkipPrompt(text.trim()); + if (demoPrompt !== null) { + if (demoPrompt && (state.remoteModel || nativeState()?.instances.some(i => i.status === 'ready'))) void startTimeSkipReal(demoPrompt); else if (state.connection === 'live' && demoPrompt) pushToast('info', 'Load a model first', 'Time-skip works on a loaded model. Choose one on the Models tab, then try again.'); + else if (state.connection === 'connecting' && demoPrompt) pushToast('info', 'Still starting up', 'Time-skip needs the app to finish starting. Try again in a moment.'); + else startTimeSkipDemo(demoPrompt); + return; + } + // Whatever sent this (the box, a loop, a plan): with no model to answer, say so in plain words and start nothing. + if (state.connection === 'live') { + // The first read of the engine's state has not come back yet: do not say "no model" about something not known yet, and do not send. + if (!nativeState() && !state.remoteModel && !state.library?.loaded) { pushToast('info', 'Still starting up', 'Strata is still checking your models. Try again in a moment.'); return; } + const why = noModelNotice(nativeState(), { remote: !!state.remoteModel, libraryLoaded: !!state.library?.loaded }); + if (why) { pushToast('info', why.title, why.message); return; } + } + const pictureCheck=pictureStatus(nativeState(),state.remoteModel,state.providers); + if(pendingChatPhotos(state.activeSession).length&&!pictureCheck.ok){pushToast('error','This model cannot read pictures',tr(pictureCheck.message));return;} + const pictures=takeChatPhotos(state.activeSession); + const body=text.trim()||(pictures.length?'Describe this picture.':''); + if(!body&&!resume&&!planStart)return; + + let sessionId = state.activeSession; + if (!sessionId) sessionId = newSession().id; + + const userMsg: ChatMessage = { id: uid('m'), role: 'user', content: options.shown ?? body, at: new Date().toISOString(),...(pictures.length?{photos:pictures}:{}),...(options.markdown?{markdown:true}:{}) }; + let assistantId = uid('m'); + const assistantMsg: ChatMessage = { + id: assistantId, + role: 'assistant', + content: '', + at: new Date().toISOString(), + streaming: true, + }; + + /* Everything said before this turn, which the model needs in order to have a + conversation at all. + + It was never sent. The real-engine path builds its prompt as + `[...history, message]`, and `history` was always empty, so each message + arrived as the first thing the model had ever heard — no memory of the + turns above it in the transcript. The demo path hides this, because its + replies are canned. + + The context meter was reading the same empty array, which is why it sat at + ~350 tokens however long the conversation grew. */ + const prior = (state.sessions.find((s) => s.id === sessionId)?.messages ?? []) + .filter(m => !m.timeSkipId && !m.local) + .filter((m) => m.role === 'user' || m.role === 'assistant') + .filter((m) => m.content.trim()) + .map((m) => ({ role: m.role, content: m.content,photos:m.photos })) + // Bounded so a long conversation cannot send an unbounded body. + .slice(-40); + + patchSession(sessionId, (s) => ({ + ...s, + defaultTitle: false, + title: s.messages.length === 0 && !resume && !planStart ? (options.title ?? (body.length>48?body.slice(0,47).trimEnd()+'…':body)) : s.title, + updatedAt: new Date().toISOString(), + messages: [...s.messages, ...(resume || planStart ? [] : [userMsg]), assistantMsg], + })); + + const turnAbort = new AbortController(); + markTurn(sessionId, { abort: turnAbort, agent: false }); + // Read by the router to skip view transitions mid-stream, and by CSS to keep + // the transcript still while tokens arrive. + + const patchAssistant = (fn: (m: ChatMessage) => ChatMessage) => + patchSession(sessionId, (s) => ({ + ...s, + updatedAt: new Date().toISOString(), + messages: s.messages.map((m) => (m.id === assistantId ? fn(m) : m)), + })); + + const started = performance.now(); + + const imageSlots=photoHistorySlots(prior,pictures.length); + /* Text and reasoning arrive token by token (90 a second or more). Drawing the whole answer again for each one made the page do more work for every + word the longer the answer grew (measured: 15.7 s of main-thread time for 24 s of a 40,000-token answer), until the page stopped answering + and ran out of memory. The pieces are gathered and applied together about ten times a second; any other frame, the end and a failure + apply what is waiting first, so the order the person sees is the order it was written. */ + const waiting: ['reasoning' | 'delta', string][] = []; + let waitingTimer: ReturnType<typeof setTimeout> | null = null; + const applyReasoning = (text: string) => patchAssistant((m) => ({ ...m, reasoning: (m.reasoning ?? '') + text, reasoningStartedAt: m.reasoningStartedAt ?? Date.now() })); + const applyDelta = (text: string) => patchAssistant((m) => { const content=tidyAnswer(m.content+text); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,...(m.blocks?{blocks:appendText(m.blocks,text)}:{}),tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; }); + const flushWaiting = () => { + if (waitingTimer !== null) { clearTimeout(waitingTimer); waitingTimer = null; } + for (const [kind, text] of waiting.splice(0)) if (kind === 'delta') applyDelta(text); else applyReasoning(text); + }; + const queueText = (kind: 'reasoning' | 'delta', text: string) => { + const last = waiting[waiting.length - 1]; + if (last && last[0] === kind) last[1] += text; else waiting.push([kind, text]); + waitingTimer ??= setTimeout(flushWaiting, 90); + }; + try { + await streamPost( + planStart ? '/api/plan/start-goal' : '/api/chat/stream', + { + sessionId, + ...(planStart ? { planId: planStart } : {}), + ...(resume ? { goalAction: 'resume' } : planStart ? {} : { message: options.shown ? body : body }), + history:await Promise.all(prior.map(async(m,index)=>{const included=pictureCheck.ok?(m.photos??[]).filter((_,p)=>imageSlots.has(`${index}:${p}`)):[];const omitted=(m.photos??[]).filter(p=>!included.includes(p));const text=m.content+(omitted.length?`\n[Earlier pictures: ${omitted.map(p=>p.name).join(', ')}. Their pixels are outside this model's image context; ask to reattach them if needed.]`:'');return {role:m.role,content:included.length?[{type:'text',text},...await Promise.all(included.map(async photo=>({type:'image_url',image_url:{url:(await photoData(photo)).url}})))]:text};})), + model: state.library?.loaded ?? state.library?.current ?? null, + remoteModel: state.remoteModel, + nativeModelId:nativeState()?.instances.length?nativeState()?.defaultId:undefined, + ...(pictures.length ? { imageIds: await uploadChatPhotos(pictures, sessionId) } : {}), + useTools:state.sessions.find(s=>s.id===sessionId)?.preferences?.useTools===true, + // A chat set to plain talk (preferences.agent === false) never runs a tool: the host answers it directly. + ...(state.sessions.find(s=>s.id===sessionId)?.preferences?.agent===false?{agent:false}:{}), + thinking:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinking??'Medium', + thinkingBudget:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinkingBudget??0, + // 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: 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. + if (frame.type === 'delta' && typeof frame.key === 'string') frame = { ...frame, text: tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) }; + const type = frame.type as string; + if (type === 'delta' || type === 'reasoning') { queueText(type, String(frame.text ?? '')); return; } + flushWaiting(); + if (type === 'start' && frame.agent === true) { const turn = liveTurns.get(sessionId); if (turn) turn.agent = true; } + if (type === 'queued') { + patchAssistant(m => ({ ...m, requestId: String(frame.requestId) })); + } else if (type === 'start') { + patchAssistant((m) => ({ ...m, demo: frame.demo === true, remoteModel: frame.remoteModel === true, requestId: typeof frame.requestId === 'string' ? frame.requestId : m.requestId, model: String(frame.model), contextMax: Number(frame.contextMax), skillsUsed: Array.isArray(frame.skills) ? frame.skills.map(String) : [] })); + } else if (type === 'status') { + applyStatusFrame(sessionId, frame as Record<string, unknown>); + // Manual mode waits for the person: a notification when they have opted in and Strata is in the background (#3477), once per question. + if (frame.code === 'waiting-approval' && lastApprovalNotice !== `${sessionId}:${String(frame.seq)}`) { + lastApprovalNotice = `${sessionId}:${String(frame.seq)}`; + const tool = (frame.args as { tool?: unknown } | undefined)?.tool; + void approvalNeeded(state.approvalNotify, typeof tool === 'string' ? tool : ''); + } + } else if (type === 'goal') { + applyGoalFrame(sessionId, frame.goal); + } else if (type === 'plan') { + applyPlanFrame(sessionId, frame.plan); + // A proposed plan is shown as the plan card in place of this turn's closing text (that text is the plan in prose). + const planned = frame.plan as { id?: unknown } | null; + if (frame.event === 'proposed' && planned && typeof planned.id === 'string') { const pid = planned.id; patchAssistant(m => ({ ...m, planId: pid })); } + } else if (type === 'queued-message') { + applyQueueFrame(sessionId, frame.queue); + const sent = frame.message as { text?: unknown } | undefined; + if (frame.state === 'delivered' && sent && typeof sent.text === 'string') { + // The host has just sent it into the run: it becomes an ordinary message here, and the answer to it starts a new reply. + const before = assistantId; assistantId = uid('m'); + const next: ChatMessage = { id: assistantId, role: 'assistant', content: '', at: new Date().toISOString(), streaming: true }; + patchSession(sessionId, sess => ({ ...sess, messages: [...sess.messages.map(m => m.id === before ? { ...m, streaming: false } : m), { id: uid('m'), role: 'user', content: sent.text as string, at: new Date().toISOString() }, next] })); + } + } else if (type === 'queued-release') { + // The goal ended with messages left: they go out now, in order, as ordinary messages once this turn has finished. + const left = Array.isArray(frame.messages) ? frame.messages.flatMap(q => (q && typeof (q as { text?: unknown }).text === 'string' ? [String((q as { text: string }).text)] : [])) : []; + if (left.length) releasedMessages.set(sessionId, [...(releasedMessages.get(sessionId) ?? []), ...left]); + } else if (type === 'plan-step') { + /* the whole plan follows in a plan frame; the live status already says which step is running */ + } else if (type === 'reasoning') { + /* applied through queueText above */ + } else if (type === 'notice') { + // The host says why this chat is not using the agent. One toast per reason per page load. + const code = String(frame.code ?? 'notice'); + if (!noticed.has(code)) { noticed.add(code); pushToast('info', 'Agent', plainFailureText(String(frame.message ?? '')).message); } + } else if (type === 'agent-question') { + addAgentAsk(sessionId, frame as { callId?: unknown; questions?: unknown }); + } else if (type === 'agent-question-end') { + removeAgentAsk(sessionId, String(frame.callId ?? '')); + } else if (type === 'agent-tool-draft') { + // A tool call (a whole file, say) is being written: keep its name, size and the tail of its text on the reply until the call is whole or lost. + const d = frame.draft as (ToolDraft & { done?: boolean }) | undefined; + if (d && typeof d.id === 'string') { + const { done, ...view } = d; + patchAssistant(m => { + const rest = (m.drafts ?? []).filter(x => x.id !== d.id); + return { ...m, drafts: done ? (rest.length ? rest : undefined) : [...rest, view] }; + }); + } + } else if (type === 'agent-tool') { + const tool = frame.tool as ToolCall; + patchAssistant(m => { + const existing = m.tools?.find(t => t.id === tool.id); + const next: ToolCall = { ...existing, ...tool, live: true }; + return { ...m, tools: existing ? m.tools!.map(t => t.id === tool.id ? next : t) : [...(m.tools ?? []), next] }; + }); + } else if (type === 'agent') { + patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) })); + } else if (type === 'delta') { + /* applied through queueText above */ + } else if (type === 'deliverable') { + const file = readDeliverable(frame); + if (file) patchAssistant(m => ({ ...m, deliverables: mergeDeliverable(m.deliverables, file) })); + } else if (type === 'skills-used') { + const skills = readSkills(frame); + if (skills.length) patchAssistant(m => ({ ...m, skills })); + } else if (type === 'activity-group') { + const group = readGroup(frame); + if (group) patchAssistant(m => ({ ...m, blocks: upsertGroup(m.blocks ?? (m.content ? appendText(undefined, m.content) : undefined), group) })); + } else if (type === 'artifacts' && Array.isArray(frame.artifacts)) { + patchAssistant(m => ({ ...m, artifacts: frame.artifacts as PreviewArtifact[] })); + } else if(type==='native-tool'){ + const event=frame.event as {event:string;id:string;name?:string;arguments?:Record<string,unknown>;text?:string;ok?:boolean;ms?:number}; + if(event.id)patchAssistant(m=>{const existing=m.tools?.find(t=>t.id===event.id);const tool={id:event.id,name:event.name??existing?.name??'Connected tool',args:event.arguments??existing?.args??{},preview:'Authorized connected tool',effect:'Access configured in the MCP server',scope:'connected' as const,state:event.event==='result'?event.ok?'done' as const:'error' as const:'running' as const,result:event.text,durationMs:event.ms};return {...m,tools:[...(m.tools??[]).filter(t=>t.id!==tool.id),{...existing,...tool}]};}); + } else if (type === 'tool') { + const tool = frame.tool as ChatMessage['tools'] extends (infer T)[] | undefined ? T : never; + patchAssistant((m) => ({ ...m, tools: [...(m.tools ?? []), { ...tool, state: 'proposed' }] })); + } else if (type === 'stats') { + patchAssistant((m) => ({ + ...m, + tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : m.tokens, + tps: typeof frame.tps === 'number' ? frame.tps : m.tps, + promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps, + })); + } else if (type === 'context') { + // What the context holds after each model request of an agent turn: the meter follows the turn instead of waiting for its end. + const used = Number(frame.contextTokens), max = Number(frame.contextMax); + if (Number.isFinite(used) && used > 0) patchAssistant((m) => ({ ...m, contextUsed: used, ...(Number.isFinite(max) && max > 0 ? { contextMax: max } : {}) })); + } else if (type === 'error') { + clearStatus(sessionId); + // A sentence the host wrote for the person (it carries its catalog key) is shown in their language as it is; anything else is made plain here. + const said = typeof frame.key === 'string' ? tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) : plainFailure(String(frame.message ?? 'Engine error')).message; + patchAssistant((m) => ({ ...m, drafts: undefined, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) })); + } else if (type === 'done') { + clearStatus(sessionId); + workFinished(state.doneSound, Number(frame.durationMs ?? performance.now() - started)); + patchSession(sessionId, (sess) => ({ + ...sess, + tokensIn: sess.tokensIn + Number(frame.tokensIn ?? 0), + tokensOut: sess.tokensOut + Number(frame.tokensOut ?? 0), + statsAvailable: typeof frame.tokensIn === 'number' && typeof frame.tokensOut === 'number' && sess.messages.filter(m=>m.role==='assistant'&&!m.streaming).every(m=>typeof m.inputTokens==='number'), + })); + patchAssistant((m) => ({ + ...m, + streaming: false, + drafts: undefined, + durationMs: Number(frame.durationMs ?? performance.now() - started), + tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : undefined, + ttftMs: typeof frame.ttftMs === 'number' ? frame.ttftMs : undefined, + inputTokens: typeof frame.tokensIn === 'number' ? frame.tokensIn : undefined, + contextUsed: typeof frame.contextTokens === 'number' ? frame.contextTokens : undefined, + usageSource: frame.usageSource === 'reported' || frame.usageSource === 'demo' ? frame.usageSource : 'unavailable', + tps: typeof frame.tps === 'number' ? frame.tps : m.tps, + promptTps: typeof frame.promptTps === 'number' ? frame.promptTps : m.promptTps, + })); + // The final text is in `state`: write it once now instead of waiting for the coalescing timer. + flushSessions(); + } + }, + turnAbort.signal, + ); + } catch (err) { + flushWaiting(); + if ((err as Error).name !== 'AbortError') { + patchAssistant((m) => ({ + ...m, + streaming: false, + error: err instanceof Error ? err.message : 'Engine error', + })); + pushToast('error', 'Generation failed', err instanceof Error ? err.message : undefined); + } else { + patchAssistant((m) => ({ ...m, streaming: false })); + } + } finally { + flushWaiting(); + // A cancelled or failed turn is still worth keeping. + flushSessions(); + clearStatus(sessionId); + markTurn(sessionId, null); + removeAgentAsk(sessionId); + const next = releasedMessages.get(sessionId)?.shift(); + if (next !== undefined) { if (!releasedMessages.get(sessionId)?.length) releasedMessages.delete(sessionId); setTimeout(() => void sendMessage(next), 0); } + } +} + +/** Messages the host handed back when a goal ended with some still waiting; sent one after another. */ +const releasedMessages = new Map<string, string[]>(); + +/* -------------------------------------------------------------- tool grants */ + +const noticed = new Set<string>(); + +/** + * Approve or deny a tool the agent asked about. The answer goes to the host, which hands it to the + * Harness approval for exactly this chat and call; the card then follows what the Harness reports + * (running, done, denied). The card shows the choice straight away and goes back if the host refuses. + */ +function answerAgentTool(sessionId: string, messageId: string, tool: ToolCall, approved: boolean) { + const setState = (state_: ToolCall['state'], result?: string) => patchSession(sessionId, s => ({ + ...s, messages: s.messages.map(m => m.id === messageId ? { ...m, tools: (m.tools ?? []).map(t => t.id === tool.id ? { ...t, state: state_, ...(result !== undefined ? { result } : {}) } : t) } : m), + })); + setState(approved ? 'running' : 'denied'); + api.post('/api/chat/approval', { sessionId, toolId: tool.id, decision: approved ? 'approve' : 'deny' }).catch(error => { + setState('proposed'); + pushToast('error', 'That answer was not delivered', error instanceof Error ? error.message : undefined); + }); +} + +/** + * Approving a tool in the design build resolves locally: there is no tool + * runtime behind it yet, so the result is a labelled stand-in. The interaction — + * what is asked, what is shown, what needs a grant — is the real deliverable. + */ +export function resolveTool(messageId: string, toolId: string, approved: boolean) { + const sessionId = state.activeSession; + if (!sessionId) return; + const tool = state.sessions.find(s => s.id === sessionId)?.messages.find(m => m.id === messageId)?.tools?.find(t => t.id === toolId); + if (tool?.live) { answerAgentTool(sessionId, messageId, tool, approved); return; } + + patchSession(sessionId, (s) => ({ + ...s, + messages: s.messages.map((m) => + m.id === messageId + ? { + ...m, + tools: (m.tools ?? []).map((t) => + t.id === toolId + ? { + ...t, + state: approved ? 'done' : 'denied', + durationMs: undefined, + result: approved ? 'Approval recorded. Nothing was executed.' : 'Denied. Nothing ran.', + } + : t, + ), + } + : m, + ), + })); + +} + +/* ------------------------------------------------------------------- routes */ + +export function go(route: Route, param?: string) { + navigate(route, param); + // Focus mode is a reading mode for the conversation. Leaving it to work on + // something else leaves the mode, rather than stranding a bare shell. + if (state.focus && route !== 'chat' && route !== 'settings') setFocus(false); + set({ paletteOpen: false, navOpen: false }); +} + +/* ---------------------------------------------------------------- bootstrap */ + +export function bootOnce() { + if ((globalThis as { __strataBooted?: boolean }).__strataBooted) return; + (globalThis as { __strataBooted?: boolean }).__strataBooted = true; + for (const session of state.sessions) for (const run of session.timeSkips ?? []) { scheduleTimeSkip(session.id, run); if (run.job && !run.completedAt) { markTurn(session.id, { abort: new AbortController(), agent: false }); void followTimeSkip(session.id, run.id); } } + // A loop lives in the window: one the last window left "running" has ended, and the board says so. + if (state.sessions.some(s => s.loop?.state === 'running')) { + const sessions = state.sessions.map(s => s.loop?.state === 'running' ? { ...s, loop: { ...s.loop, state: 'ended' as const, endedWhy: 'closed' as const, endedAt: Date.parse(s.updatedAt) || Date.now() } } : s); + persistSessions(sessions); + set({ sessions }); + } + void bootstrap(); + void reconcileAgentTools(); +} + +/** + * After a reload, a tool card the browser remembers as waiting or running may belong to a turn that no + * longer exists. Cards whose approval the host still holds stay answerable; the rest are marked as + * interrupted so nothing looks like it is still working. + */ +async function reconcileAgentTools() { + const open = (t: ToolCall) => t.live && (t.state === 'proposed' || t.state === 'running'); + for (const session of state.sessions) { + if (!session.messages.some(m => m.tools?.some(open))) continue; + let waiting = new Set<string>(); + try { + const r = await api.get<{ pending: { callId: string }[] }>(`/api/agent/pending?chatId=${encodeURIComponent(session.id)}`); + waiting = new Set(r.pending.map(p => p.callId)); + } catch { /* The host is unreachable; leave the cards for the next load. */ continue; } + patchSession(session.id, sess => ({ ...sess, messages: sess.messages.map(m => m.tools?.some(open) ? { ...m, tools: m.tools.map(t => open(t) && !waiting.has(t.id) ? { ...t, state: 'error' as const, result: 'The page closed before this finished. Check the workspace to see what it did.' } : t) } : m) })); + } +} + + +export function setContrast(contrast: 'standard' | 'increased') { set({ contrast }); savePrefs(); } +matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (state.theme === 'system') applyPrefs(); }); + +export async function loadRuntimeModel(body:unknown){ + const result=await api.post<{state:RuntimeModels;instance:{id:string}}>('/api/runtime/load',body); + set({runtime:result.state});return result.instance.id; +} +export async function runtimeModelAction(id:string,action:'unload'|'default'){ + set({runtime:await api.post<RuntimeModels>(`/api/runtime/${id}/${action}`)}); +} + +export async function changeModelDirectory(directory: string, unload: boolean) { + set(s => ({ busy: { ...s.busy, modelDirectory: true } })); + try { + const result = await api.post<{ library: ModelLibrary; imageModels: ImageModelLibrary; runtime: RuntimeModels; hardware: Hardware; setup: SetupState }>('/api/storage/models-directory', { directory, unload }); + set(result); + return result; + } finally { + set(s => ({ busy: { ...s.busy, modelDirectory: false } })); + } +} + +export async function addLocalModel(path: string, name?: string) { + const result = await api.post<{ library: ModelLibrary; variantId: string }>('/api/local-models', { path, name }); + set({ library: result.library }); + return result.variantId; +} diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts index be8d9f3a1c..a7b5d9deed 100644 --- a/apps/host/src/lib/types.ts +++ b/apps/host/src/lib/types.ts @@ -1,541 +1,541 @@ -/** Shared shapes for the Strata host API. Mirrors server/types.d.ts. */ - -export type CheckState = 'pass' | 'warn' | 'fail'; -export interface SoftwareUpdate { - installedVersion?: string; - status: 'available' | 'current' | 'unavailable' | 'error' | 'no-releases'; - latestVersion?: string; - releaseUrl?: string; - canInstall: boolean; - message: string; - /** The technical reason behind `message`, shown only behind the Details disclosure. */ - details?: string; -} -export interface UpdateCheckResult { checkedAt: string; strata: SoftwareUpdate; engine: SoftwareUpdate } - -export interface HardwareCheck { - id: 'gpu' | 'memory' | 'cpu' | 'storage'; - label: string; - state: CheckState; - detail: string; - value?: string; -} - -export interface ProcessorInfo { id:string; socket:string; model:string; cores:number; threads:number; arch:string; ghz:number; logicalIds?:number[] } -export interface CpuReading { id:string; utilizationPct:number|null } -export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null; fanPct?:number|null; clockMhz?:number|null } - -export interface GpuInfo { - id?: string; - index: number; - vendor: 'apple' | 'nvidia' | 'amd' | 'intel' | 'unknown'; - name: string; - vramGb: number; - freeVramGb?: number; - unified: boolean; - backend: 'metal' | 'cuda' | 'rocm' | 'vulkan' | 'cpu'; - driver?: string; -} - -export interface Hardware { - probedAt: string; - host: { name: string; platform: string; release: string; arch: string; app: string }; - processors?: ProcessorInfo[]; - cpu: { topologyKnown?:boolean; model: string; cores: number; threads: number; arch: string; ghz: number }; - memory: { totalGb: number; freeGb: number; usedGb: number; pressure: 'low' | 'medium' | 'high' }; - disk: { path: string; totalGb: number; freeGb: number; modelsDir: string }; - gpus: GpuInfo[]; - accelerator: { backend: string; label: string; usableVramGb: number; unified: boolean }; - checks: HardwareCheck[]; - verdict: { ok: boolean; headline: string; detail: string }; - recommendedVariantId: string; -} - -export type VariantState = - | 'available' - | 'downloading' - | 'installed' - | 'loading' - | 'loaded' - | 'unloading' - | 'error'; - -export interface ModelVariant { - local?: { path: string; files: { path: string; bytes: number; mtimeMs: number; ctimeMs: number }[]; architecture: string; contextLength: number; hasChatTemplate: boolean; shards: number; metadataSignature: string }; - source?: { repo: string; file: string; bytes?: number }; - downloadUrl?: string; - kvKbPerToken?: number; - catalog?: { family: string; version: string; purpose: string; capabilities: string[]; agentApproved: boolean; balancedRank: number; review: string }; - performance?: import('./experience').SpeedEvidence[]; - id: string; - name: string; - family: string; - quant: string; - label: string; - params: string; - blurb: string; - role: 'best-fit' | 'option'; - ramClass: { minGb: number; maxGb: number; label: string }; - diskGb: number; - downloadGb: number; - contextMax: number; - layerCount: number; - experts: number; - hasDraft: boolean; - kvModes: string[]; - tags: string[]; - state: VariantState; - progress?: { pct: number; mbps: number; etaSec: number; stage: string }; - error?: string; - installedAt?: string; -} - -export interface LocalModelPreview { variant: ModelVariant; files: string[]; warnings: string[] } -export interface LocalModelFolder { directory: string; parent: string | null; entries: { name: string; path: string; kind: 'folder' | 'model'; bytes?: number }[]; truncated: boolean; shortcuts: { name: string; path: string }[] } - -export interface ModelLibrary { - mode?: 'real' | 'simulated'; - current: string | null; - loaded: string | null; - variants: ModelVariant[]; - downloads: { active: number; queued: number; totalGbToday: number }; - disk: { modelsDir: string; usedGb: number; freeGb: number }; -} - -export type ImageModelChoice = 'off' | 'q4' | 'q5' | 'q6' | 'q8'; -export interface ImageModelVariant { - id: Exclude<ImageModelChoice, 'off'>; - label: string; - quant: string; - file: string; - bytes: number; - downloadGb: number; - downloadUrl: string; - state: 'available' | 'downloading' | 'installed' | 'error'; - progress?: { pct: number; stage: string }; - error?: string; -} -export interface ImageModelLibrary { - mode: 'real' | 'simulated'; - family: string; - sourceUrl: string; - revision: string; - selected: ImageModelChoice; - applied: ImageModelChoice; - generationAvailable: boolean; - variants: ImageModelVariant[]; -} - -export type ModelProtocol = 'openai-chat' | 'openai-responses' | 'anthropic'; -export interface ApiModel { id: string; name: string; contextMax?: number | null; /** What the person ticked ("This model reads pictures"): true, false, or null for not set. */ vision?: boolean | null; /** The answer in use: the tick, else what the server said; null when nobody knows. */ reads?: boolean | null; /** The provider says the model can think (OpenRouter's supported_parameters): the Reasoning menu then works. */ reasoning?: boolean | null; thinks?: boolean | null } -export interface ModelProviderPreset { id: string; name: string; baseUrl: string; protocol: ModelProtocol; baseUrlHint?: string } -export interface ModelConnection { - id: string; kind: 'provider' | 'custom'; provider: string | null; name: string; - baseUrl: string; protocol: ModelProtocol; apiKeySet: boolean; models: ApiModel[]; -} -export interface ModelProviders { catalog: ModelProviderPreset[]; connections: ModelConnection[] } -export interface RemoteModelSelection { connectionId: string; modelId: string } -export interface ModelConnectionDraft { - id?: string; kind: 'provider' | 'custom'; provider: string | null; name: string; - baseUrl: string; protocol: ModelProtocol; apiKey: string; clearKey?: boolean; models: ApiModel[]; -} - -export type Effort = 'fastest' | 'balanced' | 'quality' | 'max'; - -export interface BeginnerConfig { - priority: 'speed' | 'balanced' | 'quality' | 'coding'; - contextLength: 'recommended' | `${number}k`; - readImages: boolean; - gpuIdle: 'never' | '5m' | '15m' | '1h'; -} - -export interface ExpertParam { - applies?: string; - id: string; - group: string; - label: string; - effect: string; - type: 'select' | 'number' | 'text' | 'toggle'; - options?: string[]; - value: string | number | boolean; - recommended: string | number | boolean; - advanced?: boolean; -} - -export interface EngineConfig { - extra?: Record<string, unknown>; - variantId: string; - beginner: BeginnerConfig; - expert: ExpertParam[]; - predicted: { - responseSpeed: string; - memory: string; - restartNeeded: boolean; - notes: string[]; - }; - dirty: boolean; - appliedAt?: string; - engine: { - status?: string; - error?: string | null; - port?: number; - running: boolean; - pid?: number; - uptimeSec: number; - version: string; - backend: string; - startedAt?: string; - }; -} - -export interface RuntimeModel { - id:string; apiModelId:string; variantId:string; family:string; name:string; quant:string; - gpuIds:string[]; loadedAt:string; status:'ready'; phase:MonitorState['phase']; - active:number; queued:number; prompt:MonitorState['prompt']; outputTps:number; promptTps:number; - context:MonitorState['context']; - memory:{context:number;ramGb:number;gpuGb:number;spillGb:number;reserveGb:number;totalGb:number;devices:{id:string;gb:number}[]}; -} -export interface RuntimeModels { - revision:number; mode:'real'|'simulated'; capabilities:{multipleModels:boolean;deviceAssignment:boolean}; defaultId:string|null; - instances:RuntimeModel[]; - memory:{ramGb:number;budgetGb:number;reserveGb:number;totalGb:number;fits:boolean;devices:{id:string;name:string;usedGb:number;budgetGb:number}[]}; -} - -export interface ServeRequest { - instanceId?:string; - gpuIds?:string[]; - id: string; - at: string; - client: string; - endpoint: string; - state: 'generating' | 'queued' | 'done' | 'error'; - tokensIn: number | null; - tokensOut: number | null; - cancellable?: boolean; - cancelRequested?: boolean; - usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated'; - durationMs: number; - error?: string; - model: string; - cachedTokens?: number | null; - tps?: number | null; - promptTps?: number | null; - hitRate?: number | null; - pcieShare?: number | null; - finishReason?: string | null; -} - -export interface TunnelState { status: 'idle' | 'starting' | 'connected' | 'stopping' | 'error'; mode: 'quick' | 'domain' | null; url: string | null; error: string | null; warning?: string | null; installed: boolean; originUrl: string; connector?: { path: string; version: string | null; source: string; label: string; summary: string } | null; external?: { kind: 'service' | 'process'; others: number[]; own: number[]; message: string } | null; } - -export interface ServingState { - tunnel?: TunnelState; - sharing?: { active: boolean; url: string | null; warning?: string | null }; - revision?: number; - running: boolean; - baseUrl: string; - /** The address on this computer (the app's own port); baseUrl is the network address while sharing is on. */ - localUrl?: string; - port: number; - endpoints: { openai: string; anthropic: string; models: string }; - access: { otherDevices: boolean; apiKeySet: boolean; apiKeyHint: string | null; allowOrigin: string }; - stats: { running: number; waiting: number; completed: number; failed: number; tokensOut: number }; - requests: ServeRequest[]; - pauseServing: boolean; -} - -export interface MonitorSample { - /** Device IDs covered by aggregate GPU history; omitted for legacy host-wide samples. */ - gpuIds?: string[]; - t: number; - outputTps: number | null; - promptTps: number | null; - gpuLoad: number | null; - vramUsedGb: number | null; - ramUsedGb: number | null; - gpuTempC: number | null; - diskReadGbs: number | null; - cpuLoad?: number | null; - powerW?: number | null; - pcieRxMbs?: number | null; - gpus?: GpuReading[]; - cpus?: CpuReading[]; -} - -export interface MonitorState { - telemetry?: { throughput: string; thermals: string; memory: string; system?:string; context?: string; ttftMs?: number | null }; - phase: 'idle' | 'reading' | 'thinking' | 'generating' | 'loading' | 'error'; - phaseLabel: string; - variantId: string | null; - prompt: { done: number; total: number; pct: number }; - generation?: { done:number|null; total:number|null }; - outputTps: number; - promptTps: number; - queue: { running: number; waiting: number }; - context: { - requestId?: string; - sessionId?: string; - usedTokens: number; - maxTokens: number; - pct: number; - parts?: { system: number; tools: number; messages: number }; - }; - expertCache: { used: number; total: number; memoryGb?:number|null; source?:string }; - hardware: { - gpus?: GpuReading[]; - cpus?: CpuReading[]; - cpuLoad?: number | null; - powerW?: number | null; - powerLimitW?: number | null; - pcieRxMbs?: number | null; - /** CPU and SSD temperatures (only where this PC can give one) and the GPU energy used since the host started, in Wh (#3628). */ - cpuTempC?: number | null; - ssdTempC?: number | null; - energyWh?: number | null; - diskReadGbs?: number | null; - diskWriteMbs?: number | null; - gpuLoad: number | null; - vramUsedGb: number | null; - vramTotalGb: number; - ramUsedGb: number | null; - ramTotalGb: number; - gpuTempC: number | null; - tempLimitC: number; - }; - history: MonitorSample[]; - requests?: ServeRequest[]; - conversationCache?: { enabled?:boolean; parked?:number; slots?:number; memoryGb?:number; budgetGb?:number; parks?:number; restores?:number; evictions?:number; lastEvent?:string; lastAt?:number; lastTokens?:number; requests?:number;requestsReused?:number;lastPrompt?:number;lastReused?:number; source:string }; - mcp?: { servers:{ name:string; state:string; transport?:string; info?:{name?:string;version?:string}; error?:string; tools:{name:string;description?:string}[] }[]; tools:number }; - totals: { - promptMs?: number; - decodeMs?: number; - usageRequests?: number; - latencyRequests?: number; - tokensIn: number; - tokensOut: number; - requests: number; - avgTps: number; - since: string; - ttftMs: number; - cachedTokens: number; - uncachedTokens: number; - }; -} - -export interface ChatMessage { - /** Tool calls the model is writing right now (a file, a command): live data for the writing card; see ToolDraft. */ - drafts?: ToolDraft[]; - /** The person's message is written with Markdown (a task handover: bold headings and lists), so the bubble draws it as such. */ - markdown?: boolean; - photos?:import('./chat-photos').ChatPhoto[]; - /** Reply came from a saved API connection, rather than the local engine. */ - remoteModel?: boolean; - timeSkipId?: string; - /** The plan this reply proposed: shown as the plan card in place of the reply text. */ - planId?: string; - /** The reply in the order it came: text and grouped activity lines (round 8, item 12). Absent on older replies. */ - blocks?: import('./deliverables').MessageBlock[]; - /** The saved skills this reply used (the line under the answer), in the order they were loaded. */ - skills?: { name: string; description: string }[]; - /** Files the assistant made or changed in this reply, one card each. */ - deliverables?: import('./deliverables').Deliverable[]; - /** A line from the app itself (for example from /loop), never sent to the model. */ - local?: boolean; - ttftMs?: number; - example?: boolean; - media?: {kind: 'image' | 'video' | 'gif'; src:string; title:string; caption?:string; poster?:string}[]; - artifacts?: import('./artifacts').PreviewArtifact[]; - requestId?: string; - model?: string; - inputTokens?: number; - /** What the context held after this reply (the last model request's prompt + reply); an agent turn's inputTokens add every request up. */ - contextUsed?: number; - /** When the first reasoning arrived, and how long the model reasoned before it began the answer (for "Thought for 38s"). */ - reasoningStartedAt?: number; - reasoningMs?: number; - contextMax?: number; - usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated'; - skillsUsed?: string[]; - id: string; - role: 'user' | 'assistant' | 'system'; - content: string; - at: string; - streaming?: boolean; - demo?: boolean; - reasoning?: string; - reasoningOpen?: boolean; - tokens?: number; - tps?: number; - promptTps?: number; - durationMs?: number; - error?: string; - /** What went wrong, as a code the page acts on (a context error offers its own recovery buttons). */ - errorCode?: string; - /** The engine's own text of the error, kept behind Details. */ - errorDetail?: string; - tools?: ToolCall[]; -} - -export type ToolState = 'proposed' | 'approved' | 'running' | 'done' | 'denied' | 'error'; - -/** - * A tool call the model is still writing (a whole file in one call, say), as the host streams it: the name, the file it is for, a growing size - * and the tail of the text. It lives on the assistant message while the call is written and is removed when the call is complete (the - * ordinary tool card takes over) or the reply was cut and the call was lost (`lost`). - */ -export interface ToolDraft { - id: string; - name: string; - /** The file (or address) the call is for; empty until the model has written it. */ - target: string; - /** Characters of the call's arguments so far (a file's size, a little more because of escapes). */ - bytes: number; - /** Lines of text written so far. */ - lines: number; - /** The last part of the text being written, read back from its JSON form (at most 1,600 characters). */ - preview: string; - /** What the call is: 'write', 'edit', 'shell', ... (same as ToolCall.scope). */ - scope?: 'read' | 'write' | 'shell' | 'connected'; - /** The plain verb for the card while it is written ("Writing"). */ - verb?: string; -} - -export interface ToolCall { - id: string; - name: string; - args: Record<string, unknown>; - preview: string; - effect: string; - scope: 'read' | 'write' | 'shell' | 'connected'; - /** The card's headline in plain words for its current state ("Wrote a file"); the host sends it, the UI translates it. */ - verb?: string; - /** What the action is on: a file path, the command, a web address. */ - target?: string; - /** The question an approval card asks in plain words (server/agent/ask.mjs); the page translates it. */ - ask?: { id: string; params?: (string | number)[]; why?: string; detail?: string }; - state: ToolState; - result?: string; - durationMs?: number; - /** Reported by the agent runtime: an approval answers a real request. Absent for design-build examples. */ - live?: boolean; - /** The person approved this call. A finished card without it was never asked about. */ - approved?: boolean; -} - -/** A folder the model may read, and that sessions are grouped under. */ -export interface Workspace { - id: string; - name: string; - path: string; - /** Earlier folders whose chats belong here (the first workspace moved off the app's own folder). */ - aliases?: string[]; -} - -export interface SessionAgent { - id: string; - name: string; - description: string; - status: 'working' | 'completed' | 'failed' | 'queued' | 'cancelled'; - durationMs: number; - tokens: number; - /** Time the latest duration measurement was received. */ - updatedAt?: number; -} - -export type ChatMode = 'auto' | 'manual' | 'accept-edits' | 'plan' | 'bypass'; - -/** - * What the board needs to know about a /loop after the window closes: loops live in memory, so the chat keeps a small record of the - * last one (running, or how it ended). A record that says `running` with no loop behind it is a loop the window closed on. - */ -export interface LoopRecord { - prompt: string; - everyMs: number; - startedAt: number; - state: 'running' | 'ended'; - answers: number; - maxRuns?: number; - /** When the next answer is due (ms), while running. */ - nextAt?: number; - endedAt?: number; - /** count, said-done, time, failures, cap; `stopped` when the person typed /loop stop; `closed` when the window closed on it. */ - endedWhy?: 'count' | 'said-done' | 'time' | 'failures' | 'cap' | 'stopped' | 'closed'; - /** The last answer's first words, for the card. */ - lastText?: string; -} - -export interface Session { - /** The person dismissed this chat's (or its loop's) card on the board at this time. A later problem brings it back. */ - ackedAt?: string; - loop?: LoopRecord; - timeSkips?: import('./time-skip').TimeSkipRun[]; - showcase?: boolean; - agents?: SessionAgent[]; - previewOpen?: string; - closedPreviews?: string[]; - showcaseAgentStates?: boolean; - preferences?: { access?: 'read' | 'write' | 'full'; thinking?: string; thinkingBudget?: number; mode?: ChatMode; useTools?:boolean; /** false: plain conversation, no tools of any kind. */ agent?: boolean; /** This chat's API model; absent or null means the local model. */ remoteModel?: RemoteModelSelection | null }; - /** A branch does not have retained per-turn input usage. */ - statsAvailable?: boolean; - id: string; - title: string; - defaultTitle?: boolean; - updatedAt: string; - createdAt: string; - messages: ChatMessage[]; - workspace: string; - tokensIn: number; - tokensOut: number; - pinned?: boolean; - /** Put away without deleting. Archiving is for "done with this for now" — - * deleting is for "never want to see it again", and conflating the two makes - * people keep things they are finished with. */ - archived?: boolean; - /** When this conversation was last on screen. A session is unread when it has - * been updated since — which is the only way to tell, with more than a - * handful of conversations, which ones have something new in them. */ - lastReadAt?: string; -} - -export interface Skill { - id: string; - name: string; - description: string; - source: 'bundled' | 'workspace' | 'user'; - enabled: boolean; - triggers: string[]; - /** The instruction text itself — what the model is actually told. Deciding - * whether to trust a skill means reading this, not its name. */ - body?: string; - /** When set, the skill applies only in this workspace. A skill written for - * one project is noise in another, and on/off cannot express "here, not - * there". */ - onlyIn?: string | null; - /** How many times a prompt has actually triggered this skill, and when last. */ - useCount?: number; - lastUsedAt?: string | null; - sizeKb: number; -} - -export interface WorkspaceFile { - path: string; - kind: 'file' | 'dir'; - sizeKb?: number; - updatedAt?: string; -} - -export interface SetupState { - flowVersion?: number; - dismissed?: boolean; - choices?: { onboarding?: { step:number; family?:string; size?:string; context?:number; vision?:boolean; directory?:string; profile?:'work'|'performance'; installJobId?:string; tuneJobId?:string; calibrate?:boolean; manual?:boolean }; variantId?: string; contextLength?: BeginnerConfig["contextLength"]; profile?: import("./experience").Profile; batch?: number; batchAuto?: boolean }; - complete: boolean; - step: number; - completedAt?: string; - history: { step: number; at: string }[]; - app: { version: string; modelsDir: string; dataDir: string; modelsDirNotice?: string }; -} - -export interface EngineEvent { - type: 'engine' | 'monitor' | 'models' | 'serving' | 'download' | 'log'; - at: string; - payload: unknown; -} +/** Shared shapes for the Strata host API. Mirrors server/types.d.ts. */ + +export type CheckState = 'pass' | 'warn' | 'fail'; +export interface SoftwareUpdate { + installedVersion?: string; + status: 'available' | 'current' | 'unavailable' | 'error' | 'no-releases'; + latestVersion?: string; + releaseUrl?: string; + canInstall: boolean; + message: string; + /** The technical reason behind `message`, shown only behind the Details disclosure. */ + details?: string; +} +export interface UpdateCheckResult { checkedAt: string; strata: SoftwareUpdate; engine: SoftwareUpdate } + +export interface HardwareCheck { + id: 'gpu' | 'memory' | 'cpu' | 'storage'; + label: string; + state: CheckState; + detail: string; + value?: string; +} + +export interface ProcessorInfo { id:string; socket:string; model:string; cores:number; threads:number; arch:string; ghz:number; logicalIds?:number[] } +export interface CpuReading { id:string; utilizationPct:number|null } +export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null; fanPct?:number|null; clockMhz?:number|null } + +export interface GpuInfo { + id?: string; + index: number; + vendor: 'apple' | 'nvidia' | 'amd' | 'intel' | 'unknown'; + name: string; + vramGb: number; + freeVramGb?: number; + unified: boolean; + backend: 'metal' | 'cuda' | 'rocm' | 'vulkan' | 'cpu'; + driver?: string; +} + +export interface Hardware { + probedAt: string; + host: { name: string; platform: string; release: string; arch: string; app: string }; + processors?: ProcessorInfo[]; + cpu: { topologyKnown?:boolean; model: string; cores: number; threads: number; arch: string; ghz: number }; + memory: { totalGb: number; freeGb: number; usedGb: number; pressure: 'low' | 'medium' | 'high' }; + disk: { path: string; totalGb: number; freeGb: number; modelsDir: string }; + gpus: GpuInfo[]; + accelerator: { backend: string; label: string; usableVramGb: number; unified: boolean }; + checks: HardwareCheck[]; + verdict: { ok: boolean; headline: string; detail: string }; + recommendedVariantId: string; +} + +export type VariantState = + | 'available' + | 'downloading' + | 'installed' + | 'loading' + | 'loaded' + | 'unloading' + | 'error'; + +export interface ModelVariant { + local?: { path: string; files: { path: string; bytes: number; mtimeMs: number; ctimeMs: number }[]; architecture: string; contextLength: number; hasChatTemplate: boolean; shards: number; metadataSignature: string }; + source?: { repo: string; file: string; bytes?: number }; + downloadUrl?: string; + kvKbPerToken?: number; + catalog?: { family: string; version: string; purpose: string; capabilities: string[]; agentApproved: boolean; balancedRank: number; review: string }; + performance?: import('./experience').SpeedEvidence[]; + id: string; + name: string; + family: string; + quant: string; + label: string; + params: string; + blurb: string; + role: 'best-fit' | 'option'; + ramClass: { minGb: number; maxGb: number; label: string }; + diskGb: number; + downloadGb: number; + contextMax: number; + layerCount: number; + experts: number; + hasDraft: boolean; + kvModes: string[]; + tags: string[]; + state: VariantState; + progress?: { pct: number; mbps: number; etaSec: number; stage: string }; + error?: string; + installedAt?: string; +} + +export interface LocalModelPreview { variant: ModelVariant; files: string[]; warnings: string[] } +export interface LocalModelFolder { directory: string; parent: string | null; entries: { name: string; path: string; kind: 'folder' | 'model'; bytes?: number }[]; truncated: boolean; shortcuts: { name: string; path: string }[] } + +export interface ModelLibrary { + mode?: 'real' | 'simulated'; + current: string | null; + loaded: string | null; + variants: ModelVariant[]; + downloads: { active: number; queued: number; totalGbToday: number }; + disk: { modelsDir: string; usedGb: number; freeGb: number }; +} + +export type ImageModelChoice = 'off' | 'q4' | 'q5' | 'q6' | 'q8'; +export interface ImageModelVariant { + id: Exclude<ImageModelChoice, 'off'>; + label: string; + quant: string; + file: string; + bytes: number; + downloadGb: number; + downloadUrl: string; + state: 'available' | 'downloading' | 'installed' | 'error'; + progress?: { pct: number; stage: string }; + error?: string; +} +export interface ImageModelLibrary { + mode: 'real' | 'simulated'; + family: string; + sourceUrl: string; + revision: string; + selected: ImageModelChoice; + applied: ImageModelChoice; + generationAvailable: boolean; + variants: ImageModelVariant[]; +} + +export type ModelProtocol = 'openai-chat' | 'openai-responses' | 'anthropic'; +export interface ApiModel { id: string; name: string; contextMax?: number | null; /** What the person ticked ("This model reads pictures"): true, false, or null for not set. */ vision?: boolean | null; /** The answer in use: the tick, else what the server said; null when nobody knows. */ reads?: boolean | null; /** The provider says the model can think (OpenRouter's supported_parameters): the Reasoning menu then works. */ reasoning?: boolean | null; thinks?: boolean | null } +export interface ModelProviderPreset { id: string; name: string; baseUrl: string; protocol: ModelProtocol; baseUrlHint?: string } +export interface ModelConnection { + id: string; kind: 'provider' | 'custom'; provider: string | null; name: string; + baseUrl: string; protocol: ModelProtocol; apiKeySet: boolean; models: ApiModel[]; +} +export interface ModelProviders { catalog: ModelProviderPreset[]; connections: ModelConnection[] } +export interface RemoteModelSelection { connectionId: string; modelId: string } +export interface ModelConnectionDraft { + id?: string; kind: 'provider' | 'custom'; provider: string | null; name: string; + baseUrl: string; protocol: ModelProtocol; apiKey: string; clearKey?: boolean; models: ApiModel[]; +} + +export type Effort = 'fastest' | 'balanced' | 'quality' | 'max'; + +export interface BeginnerConfig { + priority: 'speed' | 'balanced' | 'quality' | 'coding'; + contextLength: 'recommended' | `${number}k`; + readImages: boolean; + gpuIdle: 'never' | '5m' | '15m' | '1h'; +} + +export interface ExpertParam { + applies?: string; + id: string; + group: string; + label: string; + effect: string; + type: 'select' | 'number' | 'text' | 'toggle'; + options?: string[]; + value: string | number | boolean; + recommended: string | number | boolean; + advanced?: boolean; +} + +export interface EngineConfig { + extra?: Record<string, unknown>; + variantId: string; + beginner: BeginnerConfig; + expert: ExpertParam[]; + predicted: { + responseSpeed: string; + memory: string; + restartNeeded: boolean; + notes: string[]; + }; + dirty: boolean; + appliedAt?: string; + engine: { + status?: string; + error?: string | null; + port?: number; + running: boolean; + pid?: number; + uptimeSec: number; + version: string; + backend: string; + startedAt?: string; + }; +} + +export interface RuntimeModel { + id:string; apiModelId:string; variantId:string; family:string; name:string; quant:string; + gpuIds:string[]; loadedAt:string; status:'ready'; phase:MonitorState['phase']; + active:number; queued:number; prompt:MonitorState['prompt']; outputTps:number; promptTps:number; + context:MonitorState['context']; + memory:{context:number;ramGb:number;gpuGb:number;spillGb:number;reserveGb:number;totalGb:number;devices:{id:string;gb:number}[]}; +} +export interface RuntimeModels { + revision:number; mode:'real'|'simulated'; capabilities:{multipleModels:boolean;deviceAssignment:boolean}; defaultId:string|null; + instances:RuntimeModel[]; + memory:{ramGb:number;budgetGb:number;reserveGb:number;totalGb:number;fits:boolean;devices:{id:string;name:string;usedGb:number;budgetGb:number}[]}; +} + +export interface ServeRequest { + instanceId?:string; + gpuIds?:string[]; + id: string; + at: string; + client: string; + endpoint: string; + state: 'generating' | 'queued' | 'done' | 'error'; + tokensIn: number | null; + tokensOut: number | null; + cancellable?: boolean; + cancelRequested?: boolean; + usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated'; + durationMs: number; + error?: string; + model: string; + cachedTokens?: number | null; + tps?: number | null; + promptTps?: number | null; + hitRate?: number | null; + pcieShare?: number | null; + finishReason?: string | null; +} + +export interface TunnelState { status: 'idle' | 'starting' | 'connected' | 'stopping' | 'error'; mode: 'quick' | 'domain' | null; url: string | null; error: string | null; warning?: string | null; installed: boolean; originUrl: string; connector?: { path: string; version: string | null; source: string; label: string; summary: string } | null; external?: { kind: 'service' | 'process'; others: number[]; own: number[]; message: string } | null; } + +export interface ServingState { + tunnel?: TunnelState; + sharing?: { active: boolean; url: string | null; warning?: string | null }; + revision?: number; + running: boolean; + baseUrl: string; + /** The address on this computer (the app's own port); baseUrl is the network address while sharing is on. */ + localUrl?: string; + port: number; + endpoints: { openai: string; anthropic: string; models: string }; + access: { otherDevices: boolean; apiKeySet: boolean; apiKeyHint: string | null; allowOrigin: string }; + stats: { running: number; waiting: number; completed: number; failed: number; tokensOut: number }; + requests: ServeRequest[]; + pauseServing: boolean; +} + +export interface MonitorSample { + /** Device IDs covered by aggregate GPU history; omitted for legacy host-wide samples. */ + gpuIds?: string[]; + t: number; + outputTps: number | null; + promptTps: number | null; + gpuLoad: number | null; + vramUsedGb: number | null; + ramUsedGb: number | null; + gpuTempC: number | null; + diskReadGbs: number | null; + cpuLoad?: number | null; + powerW?: number | null; + pcieRxMbs?: number | null; + gpus?: GpuReading[]; + cpus?: CpuReading[]; +} + +export interface MonitorState { + telemetry?: { throughput: string; thermals: string; memory: string; system?:string; context?: string; ttftMs?: number | null }; + phase: 'idle' | 'reading' | 'thinking' | 'generating' | 'loading' | 'error'; + phaseLabel: string; + variantId: string | null; + prompt: { done: number; total: number; pct: number }; + generation?: { done:number|null; total:number|null }; + outputTps: number; + promptTps: number; + queue: { running: number; waiting: number }; + context: { + requestId?: string; + sessionId?: string; + usedTokens: number; + maxTokens: number; + pct: number; + parts?: { system: number; tools: number; messages: number }; + }; + expertCache: { used: number; total: number; memoryGb?:number|null; source?:string }; + hardware: { + gpus?: GpuReading[]; + cpus?: CpuReading[]; + cpuLoad?: number | null; + powerW?: number | null; + powerLimitW?: number | null; + pcieRxMbs?: number | null; + /** CPU and SSD temperatures (only where this PC can give one) and the GPU energy used since the host started, in Wh (#3628). */ + cpuTempC?: number | null; + ssdTempC?: number | null; + energyWh?: number | null; + diskReadGbs?: number | null; + diskWriteMbs?: number | null; + gpuLoad: number | null; + vramUsedGb: number | null; + vramTotalGb: number; + ramUsedGb: number | null; + ramTotalGb: number; + gpuTempC: number | null; + tempLimitC: number; + }; + history: MonitorSample[]; + requests?: ServeRequest[]; + conversationCache?: { enabled?:boolean; parked?:number; slots?:number; memoryGb?:number; budgetGb?:number; parks?:number; restores?:number; evictions?:number; lastEvent?:string; lastAt?:number; lastTokens?:number; requests?:number;requestsReused?:number;lastPrompt?:number;lastReused?:number; source:string }; + mcp?: { servers:{ name:string; state:string; transport?:string; info?:{name?:string;version?:string}; error?:string; tools:{name:string;description?:string}[] }[]; tools:number }; + totals: { + promptMs?: number; + decodeMs?: number; + usageRequests?: number; + latencyRequests?: number; + tokensIn: number; + tokensOut: number; + requests: number; + avgTps: number; + since: string; + ttftMs: number; + cachedTokens: number; + uncachedTokens: number; + }; +} + +export interface ChatMessage { + /** Tool calls the model is writing right now (a file, a command): live data for the writing card; see ToolDraft. */ + drafts?: ToolDraft[]; + /** The person's message is written with Markdown (a task handover: bold headings and lists), so the bubble draws it as such. */ + markdown?: boolean; + photos?:import('./chat-photos').ChatPhoto[]; + /** Reply came from a saved API connection, rather than the local engine. */ + remoteModel?: boolean; + timeSkipId?: string; + /** The plan this reply proposed: shown as the plan card in place of the reply text. */ + planId?: string; + /** The reply in the order it came: text and grouped activity lines (round 8, item 12). Absent on older replies. */ + blocks?: import('./deliverables').MessageBlock[]; + /** The saved skills this reply used (the line under the answer), in the order they were loaded. */ + skills?: { name: string; description: string }[]; + /** Files the assistant made or changed in this reply, one card each. */ + deliverables?: import('./deliverables').Deliverable[]; + /** A line from the app itself (for example from /loop), never sent to the model. */ + local?: boolean; + ttftMs?: number; + example?: boolean; + media?: {kind: 'image' | 'video' | 'gif'; src:string; title:string; caption?:string; poster?:string}[]; + artifacts?: import('./artifacts').PreviewArtifact[]; + requestId?: string; + model?: string; + inputTokens?: number; + /** What the context held after this reply (the last model request's prompt + reply); an agent turn's inputTokens add every request up. */ + contextUsed?: number; + /** When the first reasoning arrived, and how long the model reasoned before it began the answer (for "Thought for 38s"). */ + reasoningStartedAt?: number; + reasoningMs?: number; + contextMax?: number; + usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated'; + skillsUsed?: string[]; + id: string; + role: 'user' | 'assistant' | 'system'; + content: string; + at: string; + streaming?: boolean; + demo?: boolean; + reasoning?: string; + reasoningOpen?: boolean; + tokens?: number; + tps?: number; + promptTps?: number; + durationMs?: number; + error?: string; + /** What went wrong, as a code the page acts on (a context error offers its own recovery buttons). */ + errorCode?: string; + /** The engine's own text of the error, kept behind Details. */ + errorDetail?: string; + tools?: ToolCall[]; +} + +export type ToolState = 'proposed' | 'approved' | 'running' | 'done' | 'denied' | 'error'; + +/** + * A tool call the model is still writing (a whole file in one call, say), as the host streams it: the name, the file it is for, a growing size + * and the tail of the text. It lives on the assistant message while the call is written and is removed when the call is complete (the + * ordinary tool card takes over) or the reply was cut and the call was lost (`lost`). + */ +export interface ToolDraft { + id: string; + name: string; + /** The file (or address) the call is for; empty until the model has written it. */ + target: string; + /** Characters of the call's arguments so far (a file's size, a little more because of escapes). */ + bytes: number; + /** Lines of text written so far. */ + lines: number; + /** The last part of the text being written, read back from its JSON form (at most 1,600 characters). */ + preview: string; + /** What the call is: 'write', 'edit', 'shell', ... (same as ToolCall.scope). */ + scope?: 'read' | 'write' | 'shell' | 'connected'; + /** The plain verb for the card while it is written ("Writing"). */ + verb?: string; +} + +export interface ToolCall { + id: string; + name: string; + args: Record<string, unknown>; + preview: string; + effect: string; + scope: 'read' | 'write' | 'shell' | 'connected'; + /** The card's headline in plain words for its current state ("Wrote a file"); the host sends it, the UI translates it. */ + verb?: string; + /** What the action is on: a file path, the command, a web address. */ + target?: string; + /** The question an approval card asks in plain words (server/agent/ask.mjs); the page translates it. */ + ask?: { id: string; params?: (string | number)[]; why?: string; detail?: string }; + state: ToolState; + result?: string; + durationMs?: number; + /** Reported by the agent runtime: an approval answers a real request. Absent for design-build examples. */ + live?: boolean; + /** The person approved this call. A finished card without it was never asked about. */ + approved?: boolean; +} + +/** A folder the model may read, and that sessions are grouped under. */ +export interface Workspace { + id: string; + name: string; + path: string; + /** Earlier folders whose chats belong here (the first workspace moved off the app's own folder). */ + aliases?: string[]; +} + +export interface SessionAgent { + id: string; + name: string; + description: string; + status: 'working' | 'completed' | 'failed' | 'queued' | 'cancelled'; + durationMs: number; + tokens: number; + /** Time the latest duration measurement was received. */ + updatedAt?: number; +} + +export type ChatMode = 'auto' | 'manual' | 'accept-edits' | 'plan' | 'bypass'; + +/** + * What the board needs to know about a /loop after the window closes: loops live in memory, so the chat keeps a small record of the + * last one (running, or how it ended). A record that says `running` with no loop behind it is a loop the window closed on. + */ +export interface LoopRecord { + prompt: string; + everyMs: number; + startedAt: number; + state: 'running' | 'ended'; + answers: number; + maxRuns?: number; + /** When the next answer is due (ms), while running. */ + nextAt?: number; + endedAt?: number; + /** count, said-done, time, failures, cap; `stopped` when the person typed /loop stop; `closed` when the window closed on it. */ + endedWhy?: 'count' | 'said-done' | 'time' | 'failures' | 'cap' | 'stopped' | 'closed'; + /** The last answer's first words, for the card. */ + lastText?: string; +} + +export interface Session { + /** The person dismissed this chat's (or its loop's) card on the board at this time. A later problem brings it back. */ + ackedAt?: string; + loop?: LoopRecord; + timeSkips?: import('./time-skip').TimeSkipRun[]; + showcase?: boolean; + agents?: SessionAgent[]; + previewOpen?: string; + closedPreviews?: string[]; + showcaseAgentStates?: boolean; + preferences?: { access?: 'read' | 'write' | 'full'; thinking?: string; thinkingBudget?: number; mode?: ChatMode; useTools?:boolean; /** false: plain conversation, no tools of any kind. */ agent?: boolean; /** This chat's API model; absent or null means the local model. */ remoteModel?: RemoteModelSelection | null }; + /** A branch does not have retained per-turn input usage. */ + statsAvailable?: boolean; + id: string; + title: string; + defaultTitle?: boolean; + updatedAt: string; + createdAt: string; + messages: ChatMessage[]; + workspace: string; + tokensIn: number; + tokensOut: number; + pinned?: boolean; + /** Put away without deleting. Archiving is for "done with this for now" — + * deleting is for "never want to see it again", and conflating the two makes + * people keep things they are finished with. */ + archived?: boolean; + /** When this conversation was last on screen. A session is unread when it has + * been updated since — which is the only way to tell, with more than a + * handful of conversations, which ones have something new in them. */ + lastReadAt?: string; +} + +export interface Skill { + id: string; + name: string; + description: string; + source: 'bundled' | 'workspace' | 'user'; + enabled: boolean; + triggers: string[]; + /** The instruction text itself — what the model is actually told. Deciding + * whether to trust a skill means reading this, not its name. */ + body?: string; + /** When set, the skill applies only in this workspace. A skill written for + * one project is noise in another, and on/off cannot express "here, not + * there". */ + onlyIn?: string | null; + /** How many times a prompt has actually triggered this skill, and when last. */ + useCount?: number; + lastUsedAt?: string | null; + sizeKb: number; +} + +export interface WorkspaceFile { + path: string; + kind: 'file' | 'dir'; + sizeKb?: number; + updatedAt?: string; +} + +export interface SetupState { + flowVersion?: number; + dismissed?: boolean; + choices?: { onboarding?: { step:number; family?:string; size?:string; context?:number; vision?:boolean; directory?:string; profile?:'work'|'performance'; installJobId?:string; tuneJobId?:string; calibrate?:boolean; manual?:boolean }; variantId?: string; contextLength?: BeginnerConfig["contextLength"]; profile?: import("./experience").Profile; batch?: number; batchAuto?: boolean }; + complete: boolean; + step: number; + completedAt?: string; + history: { step: number; at: string }[]; + app: { version: string; modelsDir: string; dataDir: string; modelsDirNotice?: string }; +} + +export interface EngineEvent { + type: 'engine' | 'monitor' | 'models' | 'serving' | 'download' | 'log'; + at: string; + payload: unknown; +} diff --git a/apps/host/tests/agent-lost.test.mjs b/apps/host/tests/agent-lost.test.mjs index 628923fc36..c5c6fbbe7e 100644 --- a/apps/host/tests/agent-lost.test.mjs +++ b/apps/host/tests/agent-lost.test.mjs @@ -1,185 +1,185 @@ -// AGENT-LOST (11-01): a reply the length limit cut inside a tool call used to vanish: no file, no card, no sentence. -// Pure parts always run; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and use the scripted model server. -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { replyCap, unescapeJsonTail, ToolDraft, cutCalls, cutNotice, cutNudge } from '../server/agent/reply-cut.mjs'; -import { TurnProjector } from '../server/agent/events.mjs'; -import { startScriptedWorker } from './helpers/scripted-worker.mjs'; -import { createAgentBridge, MAX_CUT_RETRIES } from '../server/agent/agent-bridge.mjs'; -import { resolveHarness } from '../server/agent/harness-runtime.mjs'; -import { localOutputBudget } from '../server/agent/profile.mjs'; - -const HARNESS = process.env.STRATA_HARNESS_DIR; -const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; - -test('the reply ceiling is half the window up to 64K tokens and never below what compaction reserves', () => { - assert.equal(replyCap(65536, localOutputBudget(65536)), 32768); - assert.ok(replyCap(65536, localOutputBudget(65536)) > localOutputBudget(65536), '19,660 was the cut that lost the pagoda'); - assert.equal(replyCap(131072, localOutputBudget(131072)), 65536); - assert.equal(replyCap(262144, localOutputBudget(262144)), 65536, 'at most 64K tokens, so a loop cannot run for an hour'); - assert.equal(replyCap(8192, localOutputBudget(8192)), 4096); - assert.equal(replyCap(0, 5000), 16384, 'no window known: 32K is assumed'); - assert.equal(replyCap(4096, 4096), 4096, 'never below the reserve'); -}); - -test('JSON text is read back for the preview, and a half-written escape is dropped', () => { - assert.equal(unescapeJsonTail('a\\nb\\t\\"c\\"\\\\d'), 'a\nb\t"c"\\d'); - assert.equal(unescapeJsonTail('line\\'), 'line'); - assert.equal(unescapeJsonTail('x\\u00e9y'), 'xéy'); - assert.equal(unescapeJsonTail('x\\u00'), 'x'); -}); - -test('a call being written knows its file, its size, its lines and the tail of its text', () => { - const d = new ToolDraft('c1', 'write'); - for (const piece of ['{"file_pa', 'th":"C:\\\\work\\\\pagoda.html","con', 'tent":"<!doctype html>\\n<html>\\n']) d.add(piece); - assert.equal(d.target, 'C:\\work\\pagoda.html'); - assert.equal(d.lines, 2); - assert.equal(d.preview(), '<!doctype html>\n<html>\n'); - for (let i = 0; i < 400; i++) d.add(`<div class=\\"row${i}\\">text ${i}</div>\\n`); - assert.ok(d.bytes > 10_000); - assert.equal(d.lines, 402); - const p = d.preview(1000); - assert.ok(p.length <= 1000 && p.endsWith('</div>\n') && !p.includes('\\n') && p.includes('class="row'), 'the tail, read back, ends where the model is'); - const f = d.frame({ scope: 'write', verb: 'Writing' }); - assert.deepEqual(Object.keys(f.draft).sort(), ['bytes', 'done', 'id', 'lines', 'name', 'preview', 'scope', 'target', 'verb']); - assert.equal(d.frame({ done: true }).draft.preview, '', 'a finished draft carries no text'); -}); - -test('the file is found when the model writes its name after the text, or split between two pieces', () => { - const d = new ToolDraft('c2', 'write'); - d.add('{"content":"line one\nline two\n'); - assert.equal(d.target, ''); - d.add('more","file_pa'); d.add('th":"/w/big.txt"}'); - assert.equal(d.target, '/w/big.txt'); -}); - -test('the sentences name the file and the size, say what to do, and the nudge asks for smaller parts', () => { - const draft = new ToolDraft('a', 'write'); draft.add('{"file_path":"/w/pagoda.html","content":"'); draft.bytes = 52_300; - const calls = cutCalls([draft]); - assert.deepEqual(calls, [{ name: 'write', target: '/w/pagoda.html', bytes: 52_300 }]); - const again = cutNotice({ calls, tokens: 19660, retrying: true }); - assert.match(again.text, /reached its length limit \(19,660 tokens\) while writing pagoda\.html \(52 KB\), so nothing was saved\. I asked the assistant to write it again in smaller parts\./); - const last = cutNotice({ calls, tokens: 19660 }); - assert.match(last.text, /Say “continue”/); - assert.match(cutNotice({ tokens: 500 }).text, /^The reply reached its length limit \(500 tokens\) and was cut off\. Say “continue”/); - assert.match(cutNudge({ calls, tokens: 19660 }), /writing \/w\/pagoda\.html in one tool call, so nothing was saved[\s\S]*smaller parts/); - assert.match(cutNudge({}), /cut off by the output limit/); - for (const n of [again, last]) assert.equal(n.text, n.key.replace(/\{(\d)\}/g, (_, i) => n.values[i]), 'the key and its values make the sentence'); -}); - -// ------------------------------------------------------------------------------------------------ the projector - -const chunk = (c, attemptId = 'a1') => ({ type: 'assistant-stream', frame: { type: 'chunk', attemptId, chunk: c } }); -const event = (type, data = {}) => ({ type: 'event', event: { type, time: Date.now(), data } }); - -test('the projector streams a growing draft frame for a call being written, and the whole call ends it', () => { - const p = new TurnProjector(); - const frames = []; - const head = '{"file_path":"big.txt","content":"'; - frames.push(...p.consume(chunk({ type: 'tool-call-delta', id: 'c1', name: 'write', argumentsDelta: head }))); - assert.equal(frames.filter(f => f.type === 'agent-tool-draft').length, 1, 'the first piece shows at once'); - const first = frames.find(f => f.type === 'agent-tool-draft').draft; - assert.equal(first.name, 'write'); assert.equal(first.target, 'big.txt'); assert.equal(first.scope, 'write'); assert.equal(first.verb, 'Writing a file'); - // A burst inside 200 ms sends no more frames, but the next one after the pause carries everything so far. - for (let i = 0; i < 20; i++) p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: `entry ${i}\\n` })); - assert.equal(p.composing.get('c1').lines, 20); - p.composing.get('c1').at = 0; - const later = p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: 'entry 20\\n' })).find(f => f.type === 'agent-tool-draft').draft; - assert.equal(later.lines, 21); assert.match(later.preview, /entry 20\n$/); - const out = p.consume(event('tool/call', { callId: 'c1', name: 'write', arguments: '{"file_path":"big.txt","content":"x"}' })); - assert.ok(out.some(f => f.type === 'agent-tool'), 'the ordinary card takes over'); - assert.equal(out.find(f => f.type === 'agent-tool-draft')?.draft.done, true, 'and the draft is closed'); - assert.equal(p.composing.size, 0); -}); - -test('a reply cut in a call: the done frame says length and what was lost, and the draft is taken down', () => { - const p = new TurnProjector(); - p.consume(chunk({ type: 'tool-call-delta', id: 'c9', name: 'write', argumentsDelta: '{"file_path":"/w/pagoda.html","content":"abc' })); - p.consume(chunk({ type: 'usage', usage: { inputTokens: 6000, outputTokens: 19660 } })); - p.consume(event('turn/end', { reason: { kind: 'max-tokens' } })); - assert.deepEqual(p.cut(), { tokens: 19660, calls: [{ name: 'write', target: '/w/pagoda.html', bytes: p.composing.get('c9').bytes }] }); - const frames = p.finish({ model: 'm', contextMax: 65536 }); - const drop = frames.find(f => f.type === 'agent-tool-draft'); - assert.ok(drop && drop.draft.done && drop.draft.lost, 'the writing card goes away'); - const done = frames.at(-1); - assert.equal(done.type, 'done'); assert.equal(done.finishReason, 'length'); - assert.equal(done.cut.tokens, 19660); assert.equal(done.cut.calls[0].target, '/w/pagoda.html'); -}); - -test('a call nobody writes a card for (a helper agent) makes no draft', () => { - const p = new TurnProjector(); - const out = p.consume(chunk({ type: 'tool-call-delta', id: 's1', name: 'subagent', argumentsDelta: '{"prompt":"x' })); - assert.equal(out.filter(f => f.type === 'agent-tool-draft').length, 0); -}); - -// ------------------------------------------------------------------------------------------------ with the real Harness - -async function rig(t, { window = 65536 } = {}) { - const worker = await startScriptedWorker({ chunkDelayMs: 5 }); - const dir = mkdtempSync(join(tmpdir(), 'strata-lost-')); - const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); - const logs = []; - const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: window, slots: 2 }], connections: () => [], - env: process.env, startTimeoutMs: 90_000, log: l => logs.push(l) }); - t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } }); - return { worker, bridge, ws, logs, base: (chatId, onFrame) => ({ chatId, workspacePath: ws, mode: 'bypass', thinking: 'Off', onFrame }) }; -} -const words = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join(''); -const capOf = q => q.params.max_tokens ?? q.params.max_completion_tokens; -const writes = r => r.worker.requests.filter(q => q.directive === 'cutwrite' || q.directive === 'cutalways'); - -test('every model request may produce half the window, not the 30 percent the Harness reserves for compaction', { skip }, async (t) => { - const r = await rig(t); - const out = []; - await r.bridge.runTurn({ ...r.base('c0', f => out.push(f)), message: 'SCRIPT:echo hello' }); - const asked = r.worker.requests.find(q => q.directive === 'echo'); - assert.ok(asked, 'the model was asked'); - assert.equal(capOf(asked), 32768, `the request carried ${capOf(asked)}; the pagoda's carried 19660`); -}); - -test('a small window still gets a request that fits it (the Harness clamps to the room left)', { skip }, async (t) => { - const r = await rig(t, { window: 8192 }); - await r.bridge.runTurn({ ...r.base('c0s', () => {}), message: 'SCRIPT:echo hello' }); - const asked = r.worker.requests.find(q => q.directive === 'echo'); - assert.ok(capOf(asked) > 0 && capOf(asked) <= 4096, `max_tokens ${capOf(asked)} for an 8K window`); -}); - -test('a reply cut inside a file write: the chat says so, the agent is asked to go on in smaller parts, and the file gets written', { skip }, async (t) => { - const r = await rig(t); - const out = []; - await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:cutwrite big.txt' }); - const said = out.find(f => f.type === 'delta' && f.noteReason === 'cut'); - assert.ok(said, 'a sentence about the cut'); - assert.match(said.text, /while writing big\.txt/); assert.match(said.text, /I asked the assistant to write it again in smaller parts/); - assert.equal(out.filter(f => f.type === 'error').length, 0); - const done = out.filter(f => f.type === 'done').at(-1); - assert.equal(done.finishReason, 'stop', 'the turn ends on the agent\'s own finish, not on the cut'); - assert.ok(existsSync(join(r.ws, 'big.txt')), 'the file is on disk'); - assert.match(readFileSync(join(r.ws, 'big.txt'), 'utf8'), /entry 0001/); - assert.match(words(out), /Written in parts/); - assert.equal(writes(r).length, 3, 'the cut reply, the nudged write, the closing words'); - assert.ok(writes(r)[1].raw.includes('cut off by the output limit'), 'the second request carries the nudge'); - const drafts = out.filter(f => f.type === 'agent-tool-draft'); - assert.ok(drafts.length >= 2, 'the writing was shown live'); - assert.ok(drafts.some(f => !f.draft.done && f.draft.name === 'write'), 'a writing card opened as soon as the model named the call'); - // The Harness hands the streamed pieces over in batches (a few a second at most), so a short script may show only the first and the last. - assert.ok(drafts.some(f => f.draft.done && f.draft.lost && f.draft.target === 'big.txt' && f.draft.bytes > 1000), 'and taken down, with its file and size, when it was lost'); -}); - -test(`a model that is cut every time is asked ${MAX_CUT_RETRIES} times, then the turn ends with a plain sentence, never silently`, { skip }, async (t) => { - const r = await rig(t); - const out = []; - await r.bridge.runTurn({ ...r.base('c2', f => out.push(f)), message: 'SCRIPT:cutalways big.txt' }); - assert.equal(writes(r).length, MAX_CUT_RETRIES + 1); - const notes = out.filter(f => f.type === 'delta' && f.noteReason === 'cut'); - assert.equal(notes.length, MAX_CUT_RETRIES + 1, 'one sentence per cut'); - assert.match(notes.at(-1).text, /nothing was saved\. Say “continue”/); - const done = out.filter(f => f.type === 'done').at(-1); - assert.ok(done, 'the turn ended'); - assert.equal(done.finishReason, 'length'); - assert.equal(done.cut.calls[0].target, 'big.txt'); - assert.equal(existsSync(join(r.ws, 'big.txt')), false, 'nothing half-written is left behind'); -}); +// AGENT-LOST (11-01): a reply the length limit cut inside a tool call used to vanish: no file, no card, no sentence. +// Pure parts always run; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and use the scripted model server. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { replyCap, unescapeJsonTail, ToolDraft, cutCalls, cutNotice, cutNudge } from '../server/agent/reply-cut.mjs'; +import { TurnProjector } from '../server/agent/events.mjs'; +import { startScriptedWorker } from './helpers/scripted-worker.mjs'; +import { createAgentBridge, MAX_CUT_RETRIES } from '../server/agent/agent-bridge.mjs'; +import { resolveHarness } from '../server/agent/harness-runtime.mjs'; +import { localOutputBudget } from '../server/agent/profile.mjs'; + +const HARNESS = process.env.STRATA_HARNESS_DIR; +const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; + +test('the reply ceiling is half the window up to 64K tokens and never below what compaction reserves', () => { + assert.equal(replyCap(65536, localOutputBudget(65536)), 32768); + assert.ok(replyCap(65536, localOutputBudget(65536)) > localOutputBudget(65536), '19,660 was the cut that lost the pagoda'); + assert.equal(replyCap(131072, localOutputBudget(131072)), 65536); + assert.equal(replyCap(262144, localOutputBudget(262144)), 65536, 'at most 64K tokens, so a loop cannot run for an hour'); + assert.equal(replyCap(8192, localOutputBudget(8192)), 4096); + assert.equal(replyCap(0, 5000), 16384, 'no window known: 32K is assumed'); + assert.equal(replyCap(4096, 4096), 4096, 'never below the reserve'); +}); + +test('JSON text is read back for the preview, and a half-written escape is dropped', () => { + assert.equal(unescapeJsonTail('a\\nb\\t\\"c\\"\\\\d'), 'a\nb\t"c"\\d'); + assert.equal(unescapeJsonTail('line\\'), 'line'); + assert.equal(unescapeJsonTail('x\\u00e9y'), 'xéy'); + assert.equal(unescapeJsonTail('x\\u00'), 'x'); +}); + +test('a call being written knows its file, its size, its lines and the tail of its text', () => { + const d = new ToolDraft('c1', 'write'); + for (const piece of ['{"file_pa', 'th":"C:\\\\work\\\\pagoda.html","con', 'tent":"<!doctype html>\\n<html>\\n']) d.add(piece); + assert.equal(d.target, 'C:\\work\\pagoda.html'); + assert.equal(d.lines, 2); + assert.equal(d.preview(), '<!doctype html>\n<html>\n'); + for (let i = 0; i < 400; i++) d.add(`<div class=\\"row${i}\\">text ${i}</div>\\n`); + assert.ok(d.bytes > 10_000); + assert.equal(d.lines, 402); + const p = d.preview(1000); + assert.ok(p.length <= 1000 && p.endsWith('</div>\n') && !p.includes('\\n') && p.includes('class="row'), 'the tail, read back, ends where the model is'); + const f = d.frame({ scope: 'write', verb: 'Writing' }); + assert.deepEqual(Object.keys(f.draft).sort(), ['bytes', 'done', 'id', 'lines', 'name', 'preview', 'scope', 'target', 'verb']); + assert.equal(d.frame({ done: true }).draft.preview, '', 'a finished draft carries no text'); +}); + +test('the file is found when the model writes its name after the text, or split between two pieces', () => { + const d = new ToolDraft('c2', 'write'); + d.add('{"content":"line one\nline two\n'); + assert.equal(d.target, ''); + d.add('more","file_pa'); d.add('th":"/w/big.txt"}'); + assert.equal(d.target, '/w/big.txt'); +}); + +test('the sentences name the file and the size, say what to do, and the nudge asks for smaller parts', () => { + const draft = new ToolDraft('a', 'write'); draft.add('{"file_path":"/w/pagoda.html","content":"'); draft.bytes = 52_300; + const calls = cutCalls([draft]); + assert.deepEqual(calls, [{ name: 'write', target: '/w/pagoda.html', bytes: 52_300 }]); + const again = cutNotice({ calls, tokens: 19660, retrying: true }); + assert.match(again.text, /reached its length limit \(19,660 tokens\) while writing pagoda\.html \(52 KB\), so nothing was saved\. I asked the assistant to write it again in smaller parts\./); + const last = cutNotice({ calls, tokens: 19660 }); + assert.match(last.text, /Say “continue”/); + assert.match(cutNotice({ tokens: 500 }).text, /^The reply reached its length limit \(500 tokens\) and was cut off\. Say “continue”/); + assert.match(cutNudge({ calls, tokens: 19660 }), /writing \/w\/pagoda\.html in one tool call, so nothing was saved[\s\S]*smaller parts/); + assert.match(cutNudge({}), /cut off by the output limit/); + for (const n of [again, last]) assert.equal(n.text, n.key.replace(/\{(\d)\}/g, (_, i) => n.values[i]), 'the key and its values make the sentence'); +}); + +// ------------------------------------------------------------------------------------------------ the projector + +const chunk = (c, attemptId = 'a1') => ({ type: 'assistant-stream', frame: { type: 'chunk', attemptId, chunk: c } }); +const event = (type, data = {}) => ({ type: 'event', event: { type, time: Date.now(), data } }); + +test('the projector streams a growing draft frame for a call being written, and the whole call ends it', () => { + const p = new TurnProjector(); + const frames = []; + const head = '{"file_path":"big.txt","content":"'; + frames.push(...p.consume(chunk({ type: 'tool-call-delta', id: 'c1', name: 'write', argumentsDelta: head }))); + assert.equal(frames.filter(f => f.type === 'agent-tool-draft').length, 1, 'the first piece shows at once'); + const first = frames.find(f => f.type === 'agent-tool-draft').draft; + assert.equal(first.name, 'write'); assert.equal(first.target, 'big.txt'); assert.equal(first.scope, 'write'); assert.equal(first.verb, 'Writing a file'); + // A burst inside 200 ms sends no more frames, but the next one after the pause carries everything so far. + for (let i = 0; i < 20; i++) p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: `entry ${i}\\n` })); + assert.equal(p.composing.get('c1').lines, 20); + p.composing.get('c1').at = 0; + const later = p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: 'entry 20\\n' })).find(f => f.type === 'agent-tool-draft').draft; + assert.equal(later.lines, 21); assert.match(later.preview, /entry 20\n$/); + const out = p.consume(event('tool/call', { callId: 'c1', name: 'write', arguments: '{"file_path":"big.txt","content":"x"}' })); + assert.ok(out.some(f => f.type === 'agent-tool'), 'the ordinary card takes over'); + assert.equal(out.find(f => f.type === 'agent-tool-draft')?.draft.done, true, 'and the draft is closed'); + assert.equal(p.composing.size, 0); +}); + +test('a reply cut in a call: the done frame says length and what was lost, and the draft is taken down', () => { + const p = new TurnProjector(); + p.consume(chunk({ type: 'tool-call-delta', id: 'c9', name: 'write', argumentsDelta: '{"file_path":"/w/pagoda.html","content":"abc' })); + p.consume(chunk({ type: 'usage', usage: { inputTokens: 6000, outputTokens: 19660 } })); + p.consume(event('turn/end', { reason: { kind: 'max-tokens' } })); + assert.deepEqual(p.cut(), { tokens: 19660, calls: [{ name: 'write', target: '/w/pagoda.html', bytes: p.composing.get('c9').bytes }] }); + const frames = p.finish({ model: 'm', contextMax: 65536 }); + const drop = frames.find(f => f.type === 'agent-tool-draft'); + assert.ok(drop && drop.draft.done && drop.draft.lost, 'the writing card goes away'); + const done = frames.at(-1); + assert.equal(done.type, 'done'); assert.equal(done.finishReason, 'length'); + assert.equal(done.cut.tokens, 19660); assert.equal(done.cut.calls[0].target, '/w/pagoda.html'); +}); + +test('a call nobody writes a card for (a helper agent) makes no draft', () => { + const p = new TurnProjector(); + const out = p.consume(chunk({ type: 'tool-call-delta', id: 's1', name: 'subagent', argumentsDelta: '{"prompt":"x' })); + assert.equal(out.filter(f => f.type === 'agent-tool-draft').length, 0); +}); + +// ------------------------------------------------------------------------------------------------ with the real Harness + +async function rig(t, { window = 65536 } = {}) { + const worker = await startScriptedWorker({ chunkDelayMs: 5 }); + const dir = mkdtempSync(join(tmpdir(), 'strata-lost-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const logs = []; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: window, slots: 2 }], connections: () => [], + env: process.env, startTimeoutMs: 90_000, log: l => logs.push(l) }); + t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } }); + return { worker, bridge, ws, logs, base: (chatId, onFrame) => ({ chatId, workspacePath: ws, mode: 'bypass', thinking: 'Off', onFrame }) }; +} +const words = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join(''); +const capOf = q => q.params.max_tokens ?? q.params.max_completion_tokens; +const writes = r => r.worker.requests.filter(q => q.directive === 'cutwrite' || q.directive === 'cutalways'); + +test('every model request may produce half the window, not the 30 percent the Harness reserves for compaction', { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.runTurn({ ...r.base('c0', f => out.push(f)), message: 'SCRIPT:echo hello' }); + const asked = r.worker.requests.find(q => q.directive === 'echo'); + assert.ok(asked, 'the model was asked'); + assert.equal(capOf(asked), 32768, `the request carried ${capOf(asked)}; the pagoda's carried 19660`); +}); + +test('a small window still gets a request that fits it (the Harness clamps to the room left)', { skip }, async (t) => { + const r = await rig(t, { window: 8192 }); + await r.bridge.runTurn({ ...r.base('c0s', () => {}), message: 'SCRIPT:echo hello' }); + const asked = r.worker.requests.find(q => q.directive === 'echo'); + assert.ok(capOf(asked) > 0 && capOf(asked) <= 4096, `max_tokens ${capOf(asked)} for an 8K window`); +}); + +test('a reply cut inside a file write: the chat says so, the agent is asked to go on in smaller parts, and the file gets written', { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:cutwrite big.txt' }); + const said = out.find(f => f.type === 'delta' && f.noteReason === 'cut'); + assert.ok(said, 'a sentence about the cut'); + assert.match(said.text, /while writing big\.txt/); assert.match(said.text, /I asked the assistant to write it again in smaller parts/); + assert.equal(out.filter(f => f.type === 'error').length, 0); + const done = out.filter(f => f.type === 'done').at(-1); + assert.equal(done.finishReason, 'stop', 'the turn ends on the agent\'s own finish, not on the cut'); + assert.ok(existsSync(join(r.ws, 'big.txt')), 'the file is on disk'); + assert.match(readFileSync(join(r.ws, 'big.txt'), 'utf8'), /entry 0001/); + assert.match(words(out), /Written in parts/); + assert.equal(writes(r).length, 3, 'the cut reply, the nudged write, the closing words'); + assert.ok(writes(r)[1].raw.includes('cut off by the output limit'), 'the second request carries the nudge'); + const drafts = out.filter(f => f.type === 'agent-tool-draft'); + assert.ok(drafts.length >= 2, 'the writing was shown live'); + assert.ok(drafts.some(f => !f.draft.done && f.draft.name === 'write'), 'a writing card opened as soon as the model named the call'); + // The Harness hands the streamed pieces over in batches (a few a second at most), so a short script may show only the first and the last. + assert.ok(drafts.some(f => f.draft.done && f.draft.lost && f.draft.target === 'big.txt' && f.draft.bytes > 1000), 'and taken down, with its file and size, when it was lost'); +}); + +test(`a model that is cut every time is asked ${MAX_CUT_RETRIES} times, then the turn ends with a plain sentence, never silently`, { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.runTurn({ ...r.base('c2', f => out.push(f)), message: 'SCRIPT:cutalways big.txt' }); + assert.equal(writes(r).length, MAX_CUT_RETRIES + 1); + const notes = out.filter(f => f.type === 'delta' && f.noteReason === 'cut'); + assert.equal(notes.length, MAX_CUT_RETRIES + 1, 'one sentence per cut'); + assert.match(notes.at(-1).text, /nothing was saved\. Say “continue”/); + const done = out.filter(f => f.type === 'done').at(-1); + assert.ok(done, 'the turn ended'); + assert.equal(done.finishReason, 'length'); + assert.equal(done.cut.calls[0].target, 'big.txt'); + assert.equal(existsSync(join(r.ws, 'big.txt')), false, 'nothing half-written is left behind'); +}); diff --git a/apps/host/tests/agent-tools.test.mjs b/apps/host/tests/agent-tools.test.mjs index 67c4ab8139..faaeeb33d8 100644 --- a/apps/host/tests/agent-tools.test.mjs +++ b/apps/host/tests/agent-tools.test.mjs @@ -1,287 +1,287 @@ -/** - * The agent's tools in the app: the inventory, a tool from each family, and Manual mode's one approval card. - * - * Pure tests (the gate's rules, the preset list, the profile) always run. The rest need a built Harness - * (STRATA_HARNESS_DIR) and skip loudly without it. The model is scripted (tests/helpers/scripted-worker.mjs): what is real is - * the Harness, its tool executor, its sandbox, its approval service, the Strata gate plugin and the bridge. - */ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { startScriptedWorker } from './helpers/scripted-worker.mjs'; -import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; -import { resolveHarness } from '../server/agent/harness-runtime.mjs'; -import { buildProfile, GATE_PLUGIN } from '../server/agent/profile.mjs'; -import { STANDARD_PLUGIN_IDS, REMOVED_PLUGIN_IDS, standardPreset } from '../server/agent/preset.mjs'; -import { isReadOnlyShell, manualDecision, maskQuotes, READ_ONLY_TOOLS } from '../server/agent/plugins/strata-gate.mjs'; -import { plainToolError, withPlain } from '../server/agent/events.mjs'; - -const HARNESS = process.env.STRATA_HARNESS_DIR; -const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; -const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } }; -const fwd = p => p.replaceAll('\\', '/'); - -// ---------------------------------------------------------------------------------------------------------- pure - -test('the gate: only commands that provably just look are allowed without a question', () => { - for (const ok of ['Get-ChildItem', 'Get-ChildItem -Recurse src | Select-Object -First 5', 'git status', 'git log --oneline -5', 'git diff', 'cat notes.txt', 'ls -la', 'node --version', 'Get-Content a.txt | Select-String needle', 'git branch', 'git remote -v']) { - assert.equal(isReadOnlyShell(ok), true, ok); - } - for (const bad of ['', 'Set-Content a.txt x', 'echo hi > a.txt', 'Get-ChildItem; Remove-Item a.txt', 'rm -rf x', 'git commit -m x', 'git push', 'git branch -D x', 'git config user.name x', 'git remote add o u', 'curl http://x', 'Get-ChildItem | ForEach-Object { $_ }', 'Start-Process explorer.exe', 'explorer.exe C:/Users/x/Downloads', 'ii ~/Downloads', 'Invoke-Item $env:USERPROFILE/Downloads', 'start .', 'open .', 'xdg-open .', 'notepad a.txt', 'powershell -Command x', 'node script.js', 'python x.py', 'ls && rm a', 'find . -delete', 'echo $(whoami)', 'Invoke-WebRequest u', 'Start-Process x', 'New-Item a', 'cat a | tee b']) { - assert.equal(isReadOnlyShell(bad), false, bad); - } - assert.equal(isReadOnlyShell('x'.repeat(700)), false, 'a long command is never trusted'); -}); - -test('the gate: quoted text is data, so an & ( ) ; { } in a quoted path does not make a look-only command ask (2026-10-22)', () => { - for (const ok of [ - 'Get-ChildItem "C:\\Users\\AI-Server\\Downloads\\GUI Q&A" | Select-Object -First 5 Name', - 'Get-Content "C:\\Users\\AI-Server\\Downloads\\GUI Q&A\\a.txt"', - "Get-ChildItem 'C:\\Users\\x\\Notes (old) {draft}; v2'", - 'Select-String -Path a.txt "a|b"', - 'Select-String needle "C:\\x\\a & b.txt" | Measure-Object', - 'git log --oneline "docs/Q&A.md"', - 'cat "my file (1).txt"', - "Get-ChildItem 'it''s here'", - ]) assert.equal(isReadOnlyShell(ok), true, ok); - // Quoting does not hide anything that acts: outside the quotes the same characters still ask, and inside double quotes an expansion does. - for (const bad of [ - 'Get-ChildItem C:\\Q&A', - 'Get-ChildItem "C:\\a" ; Remove-Item x', - 'Get-ChildItem "C:\\a" & calc', - 'Get-ChildItem "C:\\a" > out.txt', - 'Get-ChildItem "$env:USERPROFILE"', - 'Get-ChildItem "$(whoami)"', - 'Get-ChildItem "a`b"', - "Get-ChildItem 'unterminated", - 'Get-ChildItem "unterminated', - 'git diff "--output=out.txt"', - 'git diff --out"put"=out.txt', - 'git diff --"output"=out.txt', - 'Get-Content "a"b', - '"Remove-Item" x', - 'Set-Content "a.txt" "x"', - 'Get-ChildItem "a" | Remove-Item', - 'curl "http://x"', - ]) assert.equal(isReadOnlyShell(bad), false, bad); - assert.equal(maskQuotes('Get-ChildItem "C:\\Q&A" | Select-Object Name'), 'Get-ChildItem "_" | Select-Object Name'); - assert.equal(maskQuotes("echo 'a' \"b\""), 'echo "_" "_"'); - assert.equal(maskQuotes('echo "$HOME"'), null); -}); - -test('the gate: every tool outside the read-only list asks, including unknown and connected ones', () => { - for (const name of READ_ONLY_TOOLS) assert.equal(manualDecision({ name, arguments: {} }), null, name); - for (const name of ['write', 'edit', 'job_kill', 'mcp__github__create_issue', 'something_new']) assert.equal(manualDecision({ name, arguments: {} })?.kind, 'ask', name); - assert.equal(manualDecision({ name: 'pwsh', arguments: { command: 'Get-ChildItem' } }), null); - assert.match(manualDecision({ name: 'pwsh', arguments: { command: 'Remove-Item x', description: 'Delete x' } }).reason, /Delete x/); - assert.match(manualDecision({ name: 'write', arguments: { file_path: 'C:/a/b.txt' } }).reason, /b\.txt/); - assert.equal(manualDecision({ name: 'pwsh', arguments: {} }).kind, 'ask', 'no command is not a read-only command'); -}); - -test('the preset: our list is the Harness standard list minus exactly what the app replaces', () => { - const ids = standardPreset({ platform: 'win32' }).plugins.map(p => p.id); - assert.deepEqual(ids, STANDARD_PLUGIN_IDS.filter(id => !REMOVED_PLUGIN_IDS.includes(id) && id !== 'tool-bash')); - assert.ok(standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-bash') && !standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-pwsh')); - const web = standardPreset().plugins.find(p => p.id === 'tool-web').config; - assert.equal(web.fetch, true); assert.equal(web.search, false, 'the preset alone leaves search to the profile, which switches it on (DuckDuckGo needs no key)'); - assert.equal(standardPreset({ search: true }).plugins.find(p => p.id === 'tool-web').config.search, true); - assert.ok(!ids.includes('tool-schedule'), 'Tasks is the only scheduler'); -}); - -test('the profile loads the gate by path, sizes helper agents to the engine slots and keeps no secret', () => { - const p = buildProfile({ local: [{ id: 'a', baseUrl: 'http://127.0.0.1:1/v1', modelId: 'm', context: 32768, slots: 2, key: 'sekret-key-123' }] }); - const entries = JSON.parse(p.patch.split('\n').slice(1).join('\n')); - assert.deepEqual(entries.find(e => e.insert)?.insert, [{ id: 'strata-gate', name: GATE_PLUGIN, config: { web: { provider: 'DuckDuckGo, or Bing when DuckDuckGo is busy', skipAsk: false } } }]); - assert.ok(existsSync(GATE_PLUGIN)); - assert.equal(entries.find(e => e.id === 'subagent').config.maxActiveSubagents, 4, 'at least the 4 helpers; more only with more slots'); - assert.equal(entries.find(e => e.id === 'preset-standard').config.plugins.some(x => x.id === 'tool-schedule'), false); - assert.ok(!p.patch.includes('sekret-key-123')); - const api = buildProfile({ local: [], connections: [{ id: 'c1', name: 'C', baseUrl: 'https://x/v1', protocol: 'openai-chat', models: [{ id: 'm' }] }] }); - assert.equal(JSON.parse(api.patch.split('\n').slice(1).join('\n')).find(e => e.id === 'subagent').config.maxActiveSubagents, 8, 'API models take the Harness limit'); -}); - -test('tool failures are said in plain words with the original text kept after them', () => { - assert.match(plainToolError('Error: URL hostname "127.0.0.1" resolves to a non-public IP address'), /web page could not be opened/); - assert.match(plainToolError('Error: invalid arguments: missing required property "files"'), /wrong way/); - assert.equal(plainToolError('something unusual'), null); - const text = withPlain('Error: web fetch failed: Error: getaddrinfo ENOTFOUND example.invalid'); - assert.match(text, /^That web page could not be opened/); - assert.match(text, /Details: web fetch failed/); -}); - -// ------------------------------------------------------------------------------------------------- real Harness - -async function rig(t) { - const worker = await startScriptedWorker({}); - const dir = mkdtempSync(join(tmpdir(), 'strata-tools-')); - const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); - const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 4 }]; - const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); - t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); - const run = async (chatId, message, { mode = 'bypass', answer } = {}) => { - const frames = []; - await bridge.runTurn({ - chatId, message, workspacePath: ws, mode, - onFrame: f => { - frames.push(f); - if (answer && f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId, callId: f.tool.id, decision: answer }).catch(e => frames.push({ type: 'test-error', message: e.message })); - }, - }); - return frames; - }; - const call = (chatId, tool, args, options) => run(chatId, `SCRIPT:call ${tool} ${JSON.stringify(args)}`, options); - return { worker, bridge, dir, ws, run, call }; -} -const cards = frames => frames.filter(f => f.type === 'agent-tool').map(f => f.tool); -const last = frames => cards(frames).at(-1); - -test('the agent is offered exactly these tools: everything useful including web search (no key needed), no scheduler, and the question tool the app can answer', { skip }, async (t) => { - const r = await rig(t); - await r.run('inv', 'SCRIPT:echo hi'); - const offered = [...r.worker.requests].reverse().find(q => q.toolNames.length)?.toolNames.sort(); - assert.deepEqual(offered, ['ask_user_question', 'create_goal', 'edit', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'present', 'pwsh', 'read', 'read_image', 'send_message', 'skill', 'subagent', 'subagent_fork', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'working_directory', 'write'].sort()); - assert.ok(!offered.some(n => n.startsWith('schedule_')) && offered.includes('web_search') && offered.includes('ask_user_question') && !offered.includes('exit_plan_mode')); -}); - -test('a tool from each family runs and shows a card the page can render', { skip }, async (t) => { - const r = await rig(t); - const file = join(r.ws, 'notes.txt'); - writeFileSync(file, 'alpha\nneedle here\nomega\n'); - const f = fwd(file); - // read-only family - assert.match(last(await r.call('fam-r', 'read', { file_path: f })).result, /needle here/); - assert.match(last(await r.call('fam-g', 'glob', { pattern: '*.txt' })).result, /notes\.txt/); - assert.match(last(await r.call('fam-s', 'grep', { pattern: 'needle' })).result, /Line 2/); - assert.equal(last(await r.call('fam-w', 'working_directory', {})).state, 'done'); - assert.equal(last(await r.call('fam-j', 'job_list', {})).state, 'done'); - // plan / list family - assert.equal(last(await r.call('fam-t', 'todo_write', { todos: [{ content: 'check the build', status: 'pending' }] })).state, 'done'); - const goal = last(await r.call('fam-goal', 'create_goal', { objective: 'finish the notes' })); - assert.equal(goal.state, 'done'); assert.equal(goal.effect, 'Sets a goal to work towards.'); - // write family (Bypass: no card asks) - const wrote = await r.call('fam-fs', 'write', { file_path: fwd(join(r.ws, 'new.txt')), content: 'made\n' }); - assert.equal(last(wrote).state, 'done'); assert.equal(readFileSync(join(r.ws, 'new.txt'), 'utf8').trim(), 'made'); - await r.call('fam-fs', 'read', { file_path: f }); - const edited = await r.call('fam-fs', 'edit', { file_path: f, old_string: 'alpha', new_string: 'ALPHA' }); - assert.equal(last(edited).state, 'done'); assert.match(readFileSync(file, 'utf8'), /^ALPHA/); - // shell family - assert.match(last(await r.call('fam-sh', 'pwsh', { command: 'Get-ChildItem', description: 'list files' })).result, /notes\.txt/); - // web family: offline, loopback is refused by the Harness itself; the failure is plain with Details after it - const web = last(await r.call('fam-web', 'web_fetch', { url: 'http://127.0.0.1:9/' })); - assert.equal(web.state, 'error'); assert.match(web.result, /^That web page could not be opened/); assert.match(web.result, /Details: /); - assert.equal(web.effect, 'Opens a web page.'); assert.equal(web.preview, 'http://127.0.0.1:9/'); - // no card shows raw JSON as its explanation - for (const c of [last(await r.call('fam-t2', 'todo_write', { todos: [{ content: 'x', status: 'pending' }] }))]) assert.ok(!c.preview.startsWith('{')); -}); - -test('Manual: one change is one card. Nothing ran when it appeared, and no sandbox or PowerShell error was ever shown', { skip }, async (t) => { - const r = await rig(t); - const a = join(r.ws, 'a.txt'), b = join(r.ws, 'b.txt'), c = join(r.ws, 'c.txt'); - // approve a file write - let frames = await r.call('man1', 'write', { file_path: fwd(a), content: 'hello\n' }, { mode: 'manual', answer: 'approve' }); - assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']); - assert.equal(new Set(cards(frames).map(x => x.id)).size, 1, 'one card, updated in place'); - assert.equal(readFileSync(a, 'utf8').trim(), 'hello'); - // deny a file write - frames = await r.call('man2', 'write', { file_path: fwd(b), content: 'no\n' }, { mode: 'manual', answer: 'deny' }); - assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'denied', 'denied']); - assert.equal(last(frames).result, 'Denied. Nothing ran.', 'the card says it in plain words, not the model-facing error'); - assert.equal(existsSync(b), false); - // a shell command that changes things - frames = await r.call('man3', 'pwsh', { command: `Set-Content -Path '${c}' -Value x`, description: 'Make c.txt' }, { mode: 'manual', answer: 'approve' }); - assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']); - assert.ok(existsSync(c)); - // a shell command that only looks needs no question - frames = await r.call('man4', 'pwsh', { command: 'Get-ChildItem', description: 'List files' }, { mode: 'manual' }); - assert.deepEqual(cards(frames).map(x => x.state), ['running', 'done']); - // nowhere in any of it does the person see the sandbox talking - const all = JSON.stringify([...cards(frames), ...cards(await r.call('man5', 'write', { file_path: fwd(join(r.ws, 'd.txt')), content: 'd' }, { mode: 'manual', answer: 'approve' }))]); - assert.ok(!/sandbox|Constrained|language mode|access denied/i.test(all), all.slice(0, 300)); -}); - -test('Plan stays read-only and Bypass asks nothing', { skip }, async (t) => { - const r = await rig(t); - const p = join(r.ws, 'p.txt'), q = join(r.ws, 'q.txt'); - const planned = await r.call('pl', 'write', { file_path: fwd(p), content: 'x' }, { mode: 'plan' }); - assert.equal(existsSync(p), false); - assert.ok(!cards(planned).some(x => x.state === 'proposed')); - const free = await r.call('bp', 'write', { file_path: fwd(q), content: 'x' }, { mode: 'bypass' }); - assert.equal(existsSync(q), true); - assert.ok(!cards(free).some(x => x.state === 'proposed')); -}); - -test('Manual refuses to start when the gate is not loaded (it would be an open sandbox that nobody asks about)', { skip }, async (t) => { - // A Harness started without the gate plugin (the bridge's `gate: false`). - const worker = await startScriptedWorker({}); - const dir = mkdtempSync(join(tmpdir(), 'strata-nogate-')); - mkdirSync(join(dir, 'ws'), { recursive: true }); - const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }]; - const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, gate: false, startTimeoutMs: 90_000 }); - t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); - await assert.rejects(bridge.runTurn({ chatId: 'x', message: 'SCRIPT:echo hi', workspacePath: join(dir, 'ws'), mode: 'manual', onFrame: () => {} }), error => error.code === 'mode-unavailable' && /asks before changing/.test(error.message) && !/sandbox/i.test(error.message)); -}); - -test('a tool server set up for the model is connected to the agent: its tools are offered, Manual asks before using them, and its secret never reaches a file', { skip }, async (t) => { - const worker = await startScriptedWorker({}); - const dir = mkdtempSync(join(tmpdir(), 'strata-mcp-')); - const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); - const mcpServers = { demo: { command: process.execPath, args: [fwd(join(import.meta.dirname, 'helpers', 'mini-mcp.mjs'))], env: { DEMO_TOKEN: 'tok-123456-secret' } }, off: { command: 'x', disabled: true } }; - const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2, mcpServers }]; - const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); - t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); - const frames = []; - await bridge.runTurn({ chatId: 'mcp-bypass', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'hello' })}`, workspacePath: ws, mode: 'bypass', onFrame: f => frames.push(f) }); - assert.ok([...worker.requests].reverse().find(q => q.toolNames.length).toolNames.includes('mcp__demo__shout')); - assert.ok(![...worker.requests].some(q => q.toolNames.some(n => n.startsWith('mcp__off'))), 'a disabled server is not connected'); - const card = cards(frames).at(-1); - assert.equal(card.state, 'done'); assert.match(card.result, /HELLO\|token:set/, 'the secret reached the server through the environment'); - assert.equal(card.scope, 'connected'); - // Manual: a connected tool has unknown effects, so it asks first - const manual = []; - await bridge.runTurn({ - chatId: 'mcp-manual', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'ask me' })}`, workspacePath: ws, mode: 'manual', - onFrame: f => { manual.push(f); if (f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId: 'mcp-manual', callId: f.tool.id, decision: 'approve' }); }, - }); - assert.deepEqual(cards(manual).map(c => c.state), ['running', 'proposed', 'running', 'done']); - assert.match(cards(manual)[1].effect, /Use the connected tool demo \/ shout/); - // the secret is in the environment of the agent only: never in the profile file - const files = JSON.stringify(readdirDeep(join(dir, 'agent')).filter(f => f.endsWith('.yml')).map(f => readFileSync(f, 'utf8'))); - assert.ok(files.includes('process.env.STRATA_MCP_0_E_DEMO_TOKEN') && !files.includes('tok-123456-secret')); -}); - -function readdirDeep(dir) { - const out = []; - for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) out.push(...readdirDeep(p)); else out.push(p); } - return out; -} - -test('the output budget is not the old 8192, and the Reasoning menu reaches the request (off sends enable_thinking false)', { skip }, async (t) => { - const worker = await startScriptedWorker({}); - const dir = mkdtempSync(join(tmpdir(), 'strata-think-')); - const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); - const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 65536 }]; - const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); - t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); - const ask = async (chatId, thinking) => { - worker.requests.length = 0; - await bridge.runTurn({ chatId, message: 'SCRIPT:echo hi', workspacePath: ws, mode: 'bypass', thinking, onFrame: () => {} }); - return worker.requests.find(r => r.toolNames.length).params; - }; - const ctk = p => p.chat_template_kwargs ?? {}; - const off = await ask('think-off', 'Off'); - assert.equal(ctk(off).enable_thinking, false); assert.equal(ctk(off).reasoning_effort, undefined); - assert.equal(off.enable_thinking, undefined, 'a top-level enable_thinking is the field the Strata server ignores'); - // The profile's budget (19,660 at 64K: what compaction sets aside for a reply) is the header the Harness reads; the request itself may produce half the window (AGENT-LOST). - assert.ok(off.max_completion_tokens === 32768, `ceiling ${off.max_completion_tokens} (half the window, at most 64K: never the old 8192, and a file written in one call is not cut at the 30 percent compaction reserves)`); - const high = await ask('think-high', 'High'); - assert.equal(ctk(high).enable_thinking, true); assert.equal(ctk(high).reasoning_effort, 'high'); - const low = await ask('think-low', 'Low'); - assert.equal(ctk(low).enable_thinking, true); assert.equal(ctk(low).reasoning_effort, 'low'); - const max = await ask('think-max', 'Max'); - assert.equal(ctk(max).enable_thinking, true); assert.equal(ctk(max).reasoning_effort, 'high'); - // the same chat switching its level between turns - assert.equal(ctk(await ask('think-off', 'High')).enable_thinking, true); - assert.equal(ctk(await ask('think-off', 'Off')).enable_thinking, false); -}); +/** + * The agent's tools in the app: the inventory, a tool from each family, and Manual mode's one approval card. + * + * Pure tests (the gate's rules, the preset list, the profile) always run. The rest need a built Harness + * (STRATA_HARNESS_DIR) and skip loudly without it. The model is scripted (tests/helpers/scripted-worker.mjs): what is real is + * the Harness, its tool executor, its sandbox, its approval service, the Strata gate plugin and the bridge. + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { startScriptedWorker } from './helpers/scripted-worker.mjs'; +import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; +import { resolveHarness } from '../server/agent/harness-runtime.mjs'; +import { buildProfile, GATE_PLUGIN } from '../server/agent/profile.mjs'; +import { STANDARD_PLUGIN_IDS, REMOVED_PLUGIN_IDS, standardPreset } from '../server/agent/preset.mjs'; +import { isReadOnlyShell, manualDecision, maskQuotes, READ_ONLY_TOOLS } from '../server/agent/plugins/strata-gate.mjs'; +import { plainToolError, withPlain } from '../server/agent/events.mjs'; + +const HARNESS = process.env.STRATA_HARNESS_DIR; +const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; +const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } }; +const fwd = p => p.replaceAll('\\', '/'); + +// ---------------------------------------------------------------------------------------------------------- pure + +test('the gate: only commands that provably just look are allowed without a question', () => { + for (const ok of ['Get-ChildItem', 'Get-ChildItem -Recurse src | Select-Object -First 5', 'git status', 'git log --oneline -5', 'git diff', 'cat notes.txt', 'ls -la', 'node --version', 'Get-Content a.txt | Select-String needle', 'git branch', 'git remote -v']) { + assert.equal(isReadOnlyShell(ok), true, ok); + } + for (const bad of ['', 'Set-Content a.txt x', 'echo hi > a.txt', 'Get-ChildItem; Remove-Item a.txt', 'rm -rf x', 'git commit -m x', 'git push', 'git branch -D x', 'git config user.name x', 'git remote add o u', 'curl http://x', 'Get-ChildItem | ForEach-Object { $_ }', 'Start-Process explorer.exe', 'explorer.exe C:/Users/x/Downloads', 'ii ~/Downloads', 'Invoke-Item $env:USERPROFILE/Downloads', 'start .', 'open .', 'xdg-open .', 'notepad a.txt', 'powershell -Command x', 'node script.js', 'python x.py', 'ls && rm a', 'find . -delete', 'echo $(whoami)', 'Invoke-WebRequest u', 'Start-Process x', 'New-Item a', 'cat a | tee b']) { + assert.equal(isReadOnlyShell(bad), false, bad); + } + assert.equal(isReadOnlyShell('x'.repeat(700)), false, 'a long command is never trusted'); +}); + +test('the gate: quoted text is data, so an & ( ) ; { } in a quoted path does not make a look-only command ask (2026-10-22)', () => { + for (const ok of [ + 'Get-ChildItem "C:\\Users\\AI-Server\\Downloads\\GUI Q&A" | Select-Object -First 5 Name', + 'Get-Content "C:\\Users\\AI-Server\\Downloads\\GUI Q&A\\a.txt"', + "Get-ChildItem 'C:\\Users\\x\\Notes (old) {draft}; v2'", + 'Select-String -Path a.txt "a|b"', + 'Select-String needle "C:\\x\\a & b.txt" | Measure-Object', + 'git log --oneline "docs/Q&A.md"', + 'cat "my file (1).txt"', + "Get-ChildItem 'it''s here'", + ]) assert.equal(isReadOnlyShell(ok), true, ok); + // Quoting does not hide anything that acts: outside the quotes the same characters still ask, and inside double quotes an expansion does. + for (const bad of [ + 'Get-ChildItem C:\\Q&A', + 'Get-ChildItem "C:\\a" ; Remove-Item x', + 'Get-ChildItem "C:\\a" & calc', + 'Get-ChildItem "C:\\a" > out.txt', + 'Get-ChildItem "$env:USERPROFILE"', + 'Get-ChildItem "$(whoami)"', + 'Get-ChildItem "a`b"', + "Get-ChildItem 'unterminated", + 'Get-ChildItem "unterminated', + 'git diff "--output=out.txt"', + 'git diff --out"put"=out.txt', + 'git diff --"output"=out.txt', + 'Get-Content "a"b', + '"Remove-Item" x', + 'Set-Content "a.txt" "x"', + 'Get-ChildItem "a" | Remove-Item', + 'curl "http://x"', + ]) assert.equal(isReadOnlyShell(bad), false, bad); + assert.equal(maskQuotes('Get-ChildItem "C:\\Q&A" | Select-Object Name'), 'Get-ChildItem "_" | Select-Object Name'); + assert.equal(maskQuotes("echo 'a' \"b\""), 'echo "_" "_"'); + assert.equal(maskQuotes('echo "$HOME"'), null); +}); + +test('the gate: every tool outside the read-only list asks, including unknown and connected ones', () => { + for (const name of READ_ONLY_TOOLS) assert.equal(manualDecision({ name, arguments: {} }), null, name); + for (const name of ['write', 'edit', 'job_kill', 'mcp__github__create_issue', 'something_new']) assert.equal(manualDecision({ name, arguments: {} })?.kind, 'ask', name); + assert.equal(manualDecision({ name: 'pwsh', arguments: { command: 'Get-ChildItem' } }), null); + assert.match(manualDecision({ name: 'pwsh', arguments: { command: 'Remove-Item x', description: 'Delete x' } }).reason, /Delete x/); + assert.match(manualDecision({ name: 'write', arguments: { file_path: 'C:/a/b.txt' } }).reason, /b\.txt/); + assert.equal(manualDecision({ name: 'pwsh', arguments: {} }).kind, 'ask', 'no command is not a read-only command'); +}); + +test('the preset: our list is the Harness standard list minus exactly what the app replaces', () => { + const ids = standardPreset({ platform: 'win32' }).plugins.map(p => p.id); + assert.deepEqual(ids, STANDARD_PLUGIN_IDS.filter(id => !REMOVED_PLUGIN_IDS.includes(id) && id !== 'tool-bash')); + assert.ok(standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-bash') && !standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-pwsh')); + const web = standardPreset().plugins.find(p => p.id === 'tool-web').config; + assert.equal(web.fetch, true); assert.equal(web.search, false, 'the preset alone leaves search to the profile, which switches it on (DuckDuckGo needs no key)'); + assert.equal(standardPreset({ search: true }).plugins.find(p => p.id === 'tool-web').config.search, true); + assert.ok(!ids.includes('tool-schedule'), 'Tasks is the only scheduler'); +}); + +test('the profile loads the gate by path, sizes helper agents to the engine slots and keeps no secret', () => { + const p = buildProfile({ local: [{ id: 'a', baseUrl: 'http://127.0.0.1:1/v1', modelId: 'm', context: 32768, slots: 2, key: 'sekret-key-123' }] }); + const entries = JSON.parse(p.patch.split('\n').slice(1).join('\n')); + assert.deepEqual(entries.find(e => e.insert)?.insert, [{ id: 'strata-gate', name: GATE_PLUGIN, config: { web: { provider: 'DuckDuckGo, or Bing when DuckDuckGo is busy', skipAsk: false } } }]); + assert.ok(existsSync(GATE_PLUGIN)); + assert.equal(entries.find(e => e.id === 'subagent').config.maxActiveSubagents, 4, 'at least the 4 helpers; more only with more slots'); + assert.equal(entries.find(e => e.id === 'preset-standard').config.plugins.some(x => x.id === 'tool-schedule'), false); + assert.ok(!p.patch.includes('sekret-key-123')); + const api = buildProfile({ local: [], connections: [{ id: 'c1', name: 'C', baseUrl: 'https://x/v1', protocol: 'openai-chat', models: [{ id: 'm' }] }] }); + assert.equal(JSON.parse(api.patch.split('\n').slice(1).join('\n')).find(e => e.id === 'subagent').config.maxActiveSubagents, 8, 'API models take the Harness limit'); +}); + +test('tool failures are said in plain words with the original text kept after them', () => { + assert.match(plainToolError('Error: URL hostname "127.0.0.1" resolves to a non-public IP address'), /web page could not be opened/); + assert.match(plainToolError('Error: invalid arguments: missing required property "files"'), /wrong way/); + assert.equal(plainToolError('something unusual'), null); + const text = withPlain('Error: web fetch failed: Error: getaddrinfo ENOTFOUND example.invalid'); + assert.match(text, /^That web page could not be opened/); + assert.match(text, /Details: web fetch failed/); +}); + +// ------------------------------------------------------------------------------------------------- real Harness + +async function rig(t) { + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-tools-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 4 }]; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); + const run = async (chatId, message, { mode = 'bypass', answer } = {}) => { + const frames = []; + await bridge.runTurn({ + chatId, message, workspacePath: ws, mode, + onFrame: f => { + frames.push(f); + if (answer && f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId, callId: f.tool.id, decision: answer }).catch(e => frames.push({ type: 'test-error', message: e.message })); + }, + }); + return frames; + }; + const call = (chatId, tool, args, options) => run(chatId, `SCRIPT:call ${tool} ${JSON.stringify(args)}`, options); + return { worker, bridge, dir, ws, run, call }; +} +const cards = frames => frames.filter(f => f.type === 'agent-tool').map(f => f.tool); +const last = frames => cards(frames).at(-1); + +test('the agent is offered exactly these tools: everything useful including web search (no key needed), no scheduler, and the question tool the app can answer', { skip }, async (t) => { + const r = await rig(t); + await r.run('inv', 'SCRIPT:echo hi'); + const offered = [...r.worker.requests].reverse().find(q => q.toolNames.length)?.toolNames.sort(); + assert.deepEqual(offered, ['ask_user_question', 'create_goal', 'edit', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'present', 'pwsh', 'read', 'read_image', 'send_message', 'skill', 'subagent', 'subagent_fork', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'working_directory', 'write'].sort()); + assert.ok(!offered.some(n => n.startsWith('schedule_')) && offered.includes('web_search') && offered.includes('ask_user_question') && !offered.includes('exit_plan_mode')); +}); + +test('a tool from each family runs and shows a card the page can render', { skip }, async (t) => { + const r = await rig(t); + const file = join(r.ws, 'notes.txt'); + writeFileSync(file, 'alpha\nneedle here\nomega\n'); + const f = fwd(file); + // read-only family + assert.match(last(await r.call('fam-r', 'read', { file_path: f })).result, /needle here/); + assert.match(last(await r.call('fam-g', 'glob', { pattern: '*.txt' })).result, /notes\.txt/); + assert.match(last(await r.call('fam-s', 'grep', { pattern: 'needle' })).result, /Line 2/); + assert.equal(last(await r.call('fam-w', 'working_directory', {})).state, 'done'); + assert.equal(last(await r.call('fam-j', 'job_list', {})).state, 'done'); + // plan / list family + assert.equal(last(await r.call('fam-t', 'todo_write', { todos: [{ content: 'check the build', status: 'pending' }] })).state, 'done'); + const goal = last(await r.call('fam-goal', 'create_goal', { objective: 'finish the notes' })); + assert.equal(goal.state, 'done'); assert.equal(goal.effect, 'Sets a goal to work towards.'); + // write family (Bypass: no card asks) + const wrote = await r.call('fam-fs', 'write', { file_path: fwd(join(r.ws, 'new.txt')), content: 'made\n' }); + assert.equal(last(wrote).state, 'done'); assert.equal(readFileSync(join(r.ws, 'new.txt'), 'utf8').trim(), 'made'); + await r.call('fam-fs', 'read', { file_path: f }); + const edited = await r.call('fam-fs', 'edit', { file_path: f, old_string: 'alpha', new_string: 'ALPHA' }); + assert.equal(last(edited).state, 'done'); assert.match(readFileSync(file, 'utf8'), /^ALPHA/); + // shell family + assert.match(last(await r.call('fam-sh', 'pwsh', { command: 'Get-ChildItem', description: 'list files' })).result, /notes\.txt/); + // web family: offline, loopback is refused by the Harness itself; the failure is plain with Details after it + const web = last(await r.call('fam-web', 'web_fetch', { url: 'http://127.0.0.1:9/' })); + assert.equal(web.state, 'error'); assert.match(web.result, /^That web page could not be opened/); assert.match(web.result, /Details: /); + assert.equal(web.effect, 'Opens a web page.'); assert.equal(web.preview, 'http://127.0.0.1:9/'); + // no card shows raw JSON as its explanation + for (const c of [last(await r.call('fam-t2', 'todo_write', { todos: [{ content: 'x', status: 'pending' }] }))]) assert.ok(!c.preview.startsWith('{')); +}); + +test('Manual: one change is one card. Nothing ran when it appeared, and no sandbox or PowerShell error was ever shown', { skip }, async (t) => { + const r = await rig(t); + const a = join(r.ws, 'a.txt'), b = join(r.ws, 'b.txt'), c = join(r.ws, 'c.txt'); + // approve a file write + let frames = await r.call('man1', 'write', { file_path: fwd(a), content: 'hello\n' }, { mode: 'manual', answer: 'approve' }); + assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']); + assert.equal(new Set(cards(frames).map(x => x.id)).size, 1, 'one card, updated in place'); + assert.equal(readFileSync(a, 'utf8').trim(), 'hello'); + // deny a file write + frames = await r.call('man2', 'write', { file_path: fwd(b), content: 'no\n' }, { mode: 'manual', answer: 'deny' }); + assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'denied', 'denied']); + assert.equal(last(frames).result, 'Denied. Nothing ran.', 'the card says it in plain words, not the model-facing error'); + assert.equal(existsSync(b), false); + // a shell command that changes things + frames = await r.call('man3', 'pwsh', { command: `Set-Content -Path '${c}' -Value x`, description: 'Make c.txt' }, { mode: 'manual', answer: 'approve' }); + assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']); + assert.ok(existsSync(c)); + // a shell command that only looks needs no question + frames = await r.call('man4', 'pwsh', { command: 'Get-ChildItem', description: 'List files' }, { mode: 'manual' }); + assert.deepEqual(cards(frames).map(x => x.state), ['running', 'done']); + // nowhere in any of it does the person see the sandbox talking + const all = JSON.stringify([...cards(frames), ...cards(await r.call('man5', 'write', { file_path: fwd(join(r.ws, 'd.txt')), content: 'd' }, { mode: 'manual', answer: 'approve' }))]); + assert.ok(!/sandbox|Constrained|language mode|access denied/i.test(all), all.slice(0, 300)); +}); + +test('Plan stays read-only and Bypass asks nothing', { skip }, async (t) => { + const r = await rig(t); + const p = join(r.ws, 'p.txt'), q = join(r.ws, 'q.txt'); + const planned = await r.call('pl', 'write', { file_path: fwd(p), content: 'x' }, { mode: 'plan' }); + assert.equal(existsSync(p), false); + assert.ok(!cards(planned).some(x => x.state === 'proposed')); + const free = await r.call('bp', 'write', { file_path: fwd(q), content: 'x' }, { mode: 'bypass' }); + assert.equal(existsSync(q), true); + assert.ok(!cards(free).some(x => x.state === 'proposed')); +}); + +test('Manual refuses to start when the gate is not loaded (it would be an open sandbox that nobody asks about)', { skip }, async (t) => { + // A Harness started without the gate plugin (the bridge's `gate: false`). + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-nogate-')); + mkdirSync(join(dir, 'ws'), { recursive: true }); + const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }]; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, gate: false, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); + await assert.rejects(bridge.runTurn({ chatId: 'x', message: 'SCRIPT:echo hi', workspacePath: join(dir, 'ws'), mode: 'manual', onFrame: () => {} }), error => error.code === 'mode-unavailable' && /asks before changing/.test(error.message) && !/sandbox/i.test(error.message)); +}); + +test('a tool server set up for the model is connected to the agent: its tools are offered, Manual asks before using them, and its secret never reaches a file', { skip }, async (t) => { + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-mcp-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const mcpServers = { demo: { command: process.execPath, args: [fwd(join(import.meta.dirname, 'helpers', 'mini-mcp.mjs'))], env: { DEMO_TOKEN: 'tok-123456-secret' } }, off: { command: 'x', disabled: true } }; + const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2, mcpServers }]; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); + const frames = []; + await bridge.runTurn({ chatId: 'mcp-bypass', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'hello' })}`, workspacePath: ws, mode: 'bypass', onFrame: f => frames.push(f) }); + assert.ok([...worker.requests].reverse().find(q => q.toolNames.length).toolNames.includes('mcp__demo__shout')); + assert.ok(![...worker.requests].some(q => q.toolNames.some(n => n.startsWith('mcp__off'))), 'a disabled server is not connected'); + const card = cards(frames).at(-1); + assert.equal(card.state, 'done'); assert.match(card.result, /HELLO\|token:set/, 'the secret reached the server through the environment'); + assert.equal(card.scope, 'connected'); + // Manual: a connected tool has unknown effects, so it asks first + const manual = []; + await bridge.runTurn({ + chatId: 'mcp-manual', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'ask me' })}`, workspacePath: ws, mode: 'manual', + onFrame: f => { manual.push(f); if (f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId: 'mcp-manual', callId: f.tool.id, decision: 'approve' }); }, + }); + assert.deepEqual(cards(manual).map(c => c.state), ['running', 'proposed', 'running', 'done']); + assert.match(cards(manual)[1].effect, /Use the connected tool demo \/ shout/); + // the secret is in the environment of the agent only: never in the profile file + const files = JSON.stringify(readdirDeep(join(dir, 'agent')).filter(f => f.endsWith('.yml')).map(f => readFileSync(f, 'utf8'))); + assert.ok(files.includes('process.env.STRATA_MCP_0_E_DEMO_TOKEN') && !files.includes('tok-123456-secret')); +}); + +function readdirDeep(dir) { + const out = []; + for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) out.push(...readdirDeep(p)); else out.push(p); } + return out; +} + +test('the output budget is not the old 8192, and the Reasoning menu reaches the request (off sends enable_thinking false)', { skip }, async (t) => { + const worker = await startScriptedWorker({}); + const dir = mkdtempSync(join(tmpdir(), 'strata-think-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 65536 }]; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 }); + t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); }); + const ask = async (chatId, thinking) => { + worker.requests.length = 0; + await bridge.runTurn({ chatId, message: 'SCRIPT:echo hi', workspacePath: ws, mode: 'bypass', thinking, onFrame: () => {} }); + return worker.requests.find(r => r.toolNames.length).params; + }; + const ctk = p => p.chat_template_kwargs ?? {}; + const off = await ask('think-off', 'Off'); + assert.equal(ctk(off).enable_thinking, false); assert.equal(ctk(off).reasoning_effort, undefined); + assert.equal(off.enable_thinking, undefined, 'a top-level enable_thinking is the field the Strata server ignores'); + // The profile's budget (19,660 at 64K: what compaction sets aside for a reply) is the header the Harness reads; the request itself may produce half the window (AGENT-LOST). + assert.ok(off.max_completion_tokens === 32768, `ceiling ${off.max_completion_tokens} (half the window, at most 64K: never the old 8192, and a file written in one call is not cut at the 30 percent compaction reserves)`); + const high = await ask('think-high', 'High'); + assert.equal(ctk(high).enable_thinking, true); assert.equal(ctk(high).reasoning_effort, 'high'); + const low = await ask('think-low', 'Low'); + assert.equal(ctk(low).enable_thinking, true); assert.equal(ctk(low).reasoning_effort, 'low'); + const max = await ask('think-max', 'Max'); + assert.equal(ctk(max).enable_thinking, true); assert.equal(ctk(max).reasoning_effort, 'high'); + // the same chat switching its level between turns + assert.equal(ctk(await ask('think-off', 'High')).enable_thinking, true); + assert.equal(ctk(await ask('think-off', 'Off')).enable_thinking, false); +}); diff --git a/apps/host/tests/folder-dialog.test.mjs b/apps/host/tests/folder-dialog.test.mjs index 9d1c9e499e..3ea0268b83 100644 --- a/apps/host/tests/folder-dialog.test.mjs +++ b/apps/host/tests/folder-dialog.test.mjs @@ -1,182 +1,182 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { spawn, execFileSync } from 'node:child_process'; -import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join, resolve, isAbsolute } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { chooseFolder, cleanChosenPath, typedFolder, windowsFolderScript } from '../server/folder-dialog.mjs'; - -const HOST_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); -const failure = (code) => Object.assign(new Error(`exit ${code}`), { code }); -const recorder = () => { - const seen = []; - return { seen, run: (outcome) => async (command, args) => { seen.push({ command, args }); if (outcome instanceof Error) throw outcome; return { stdout: outcome }; } }; -}; - -test('macOS keeps the osascript chooser and treats any dismissal as a cancel', async () => { - const c = recorder(); - assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run('/Users/me/skills/\n') }), { path: '/Users/me/skills' }); - assert.equal(c.seen[0].command, 'osascript'); - assert.equal(c.seen[0].args[1], 'POSIX path of (choose folder with prompt "Pick")'); - assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run(failure(1)) }), { cancelled: true }); -}); - -test('Windows uses a PowerShell FolderBrowserDialog passed as an encoded command', async () => { - const c = recorder(); - const result = await chooseFolder("Don't panic", { platform: 'win32', run: c.run('C:\\Users\\me\\Skills\r\n') }); - assert.deepEqual(result, { path: 'C:\\Users\\me\\Skills' }); - assert.match(c.seen[0].command, /powershell\.exe$/i); - assert.ok(c.seen[0].args.includes('-STA')); - const script = Buffer.from(c.seen[0].args.at(-1), 'base64').toString('utf16le'); - assert.equal(script, windowsFolderScript("Don't panic")); - assert.match(script, /FolderBrowserDialog/); - assert.match(script, /Description = 'Don''t panic'/); - assert.deepEqual(await chooseFolder('Pick', { platform: 'win32', run: c.run('') }), { cancelled: true }); - const missing = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure('ENOENT')) }); - assert.equal(missing.unavailable, true); - // A window that fails after it was started no longer ends in an error with no way on (AGENT-LOST, item 11): the app asks for the path. - const failed = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure(2)) }); - assert.equal(failed.unavailable, true); assert.match(failed.reason, /Type the folder path/); - const nodialog = await chooseFolder('Pick', { platform: 'win32', run: c.run('NODIALOG' + String.fromCharCode(13, 10)) }); - assert.equal(nodialog.unavailable, true); assert.match(nodialog.reason, /Type the folder path/); -}); - -test('the generated PowerShell parses without errors', { skip: process.platform !== 'win32' }, () => { - const shell = join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'); - const out = execFileSync(shell, - ['-NoProfile', '-NonInteractive', '-Command', '$e=$null; [void][System.Management.Automation.Language.Parser]::ParseInput($env:SCRIPT,[ref]$null,[ref]$e); $e.Count'], - { encoding: 'utf8', env: { ...process.env, SCRIPT: windowsFolderScript('Choose a folder for Strata') }, windowsHide: true }).trim(); - assert.equal(out, '0'); -}); - -test('Linux tries zenity, falls back to kdialog, then reports that none exists', async () => { - const order = []; - const run = async (command) => { order.push(command); if (command === 'zenity') throw failure('ENOENT'); return { stdout: '/home/me/skills/\n' }; }; - assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run }), { path: '/home/me/skills' }); - assert.deepEqual(order, ['zenity', 'kdialog']); - const none = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure('ENOENT'); } }); - assert.equal(none.unavailable, true); - assert.match(none.reason, /zenity or kdialog/); - assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure(1); } }), { cancelled: true }); - assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => ({ stdout: '' }) }), { cancelled: true }); -}); - -test('chosen paths lose trailing separators but roots survive', () => { - assert.equal(cleanChosenPath('/a/b/\n'), '/a/b'); - assert.equal(cleanChosenPath('/'), '/'); - assert.equal(cleanChosenPath('C:\\Users\\me\\'), 'C:\\Users\\me'); - assert.equal(cleanChosenPath('C:\\'), 'C:\\'); -}); - -test('a typed path must be an absolute existing directory', async () => { - const dir = await mkdtemp(join(tmpdir(), 'strata-typed-')); - try { - await writeFile(join(dir, 'file.txt'), 'x'); - assert.equal(await typedFolder(dir, { isAbsolute }), dir); - assert.equal(await typedFolder(undefined, { isAbsolute }), null); - await assert.rejects(typedFolder('relative/dir', { isAbsolute }), /full path/); - await assert.rejects(typedFolder(join(dir, 'missing'), { isAbsolute }), /does not exist/); - await assert.rejects(typedFolder(join(dir, 'file.txt'), { isAbsolute }), /not a file/); - } finally { await rm(dir, { recursive: true, force: true }); } -}); - -test('the model page takes a folder or one .gguf file, with or without quotes around the path', async () => { - const dir = await mkdtemp(join(tmpdir(), 'strata-gguf-typed-')); - try { - await writeFile(join(dir, 'model-00001-of-00002.gguf'), 'x'); - await writeFile(join(dir, 'notes.txt'), 'x'); - const only = { isAbsolute, fileType: /\.gguf$/i }; - assert.equal(await typedFolder(dir, only), dir); - assert.equal(await typedFolder(join(dir, 'model-00001-of-00002.gguf'), only), join(dir, 'model-00001-of-00002.gguf')); - assert.equal(await typedFolder(`"${join(dir, 'model-00001-of-00002.gguf')}"`, only), join(dir, 'model-00001-of-00002.gguf')); - assert.equal(await typedFolder(` "${dir}" `, only), dir); - await assert.rejects(typedFolder(join(dir, 'notes.txt'), only), /folder, or a \.gguf file/); - await assert.rejects(typedFolder(join(dir, 'missing.gguf'), only), /does not exist/); - // the other pickers still refuse a file - await assert.rejects(typedFolder(join(dir, 'model-00001-of-00002.gguf'), { isAbsolute }), /not a file/); - } finally { await rm(dir, { recursive: true, force: true }); } -}); - -async function startHost() { - const home = await mkdtemp(join(tmpdir(), 'strata-folder-home-')); - const net = await import('node:net'); - const probe = net.createServer(); - await new Promise(r => probe.listen(0, '127.0.0.1', r)); - const { port } = probe.address(); - await new Promise(r => probe.close(r)); - const child = spawn(process.execPath, [join(HOST_ROOT, 'server', 'index.mjs'), '--dist', join(HOST_ROOT, 'dist')], { - cwd: HOST_ROOT, env: { ...process.env, STRATA_HOME: home, STRATA_WORKSPACE: home, STRATA_PORT: String(port), STRATA_REAL_ENGINE: '0' }, stdio: 'ignore', - }); - const base = `http://127.0.0.1:${port}`; - for (let i = 0; i < 150; i++) { - try { if ((await fetch(`${base}/api/health`)).ok) return { child, base, home }; } catch { /* not up yet */ } - await new Promise(r => setTimeout(r, 100)); - } - child.kill(); - throw new Error('the host did not become healthy'); -} - -test('the host accepts a typed folder path for the picker and for adding a skill, on every OS', { timeout: 60000 }, async () => { - const { child, base, home } = await startHost(); - const skill = await mkdtemp(join(tmpdir(), 'strata-skill-')); - try { - const post = (path, body) => fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); - let r = await post('/api/workspaces/pick', { path: skill }); - assert.deepEqual(await r.json(), { path: skill }); - r = await post('/api/workspaces/pick', { path: join(skill, 'nope') }); - assert.equal(r.status, 400); - assert.match((await r.json()).error, /does not exist/); - r = await post('/api/skills/add', { path: skill }); - assert.equal(r.status, 400); - assert.match((await r.json()).error, /no SKILL\.md/); - await writeFile(join(skill, 'SKILL.md'), '---\nname: Typed\n---\nbody\n'); - r = await post('/api/skills/add', { path: skill }); - assert.equal(r.status, 200); - assert.ok((await r.json()).added); - } finally { - child.kill(); - await rm(skill, { recursive: true, force: true }); - await rm(home, { recursive: true, force: true }).catch(() => {}); - } -}); - -// QA report F06: a Windows folder window that never opens must not leave the button disabled forever. -import { EventEmitter } from 'node:events'; -import { watchedWindowsDialog } from '../server/folder-dialog.mjs'; -function fakeShell() { - const child = new EventEmitter(); child.stdout = new EventEmitter(); child.killed = false; child.kill = () => { child.killed = true; }; - return { child, spawnProcess: () => child }; -} -test('Windows: no READY from the dialog script means the host gives up and the app asks for the path', async () => { - const f = fakeShell(); - const result = await watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess }); - assert.deepEqual(result, { noDialog: true }); assert.equal(f.child.killed, true, 'the stuck PowerShell is ended'); - const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ noDialog: true }) }); - assert.equal(answer.unavailable, true); assert.match(answer.reason, /Type the folder path/); -}); -test('Windows: once READY has come the person may take their time, and the answer is read without the READY line', async () => { - const f = fakeShell(); - const pending = watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess }); - f.child.stdout.emit('data', 'READY\r\n'); - await new Promise(r => setTimeout(r, 80)); // longer than readyMs: still waiting, not given up - assert.equal(f.child.killed, false); - f.child.stdout.emit('data', 'C:\Users\me\Skills'); f.child.emit('close', 0); - const done = await pending; - const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => done }); - assert.deepEqual(answer, { path: 'C:\Users\me\Skills' }); - const cancelled = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ stdout: 'READY\r\n' }) }); - assert.deepEqual(cancelled, { cancelled: true }); -}); -test('Windows: a PowerShell that is missing or fails is reported as before', async () => { - const f = fakeShell(); - const missing = watchedWindowsDialog('powershell.exe', [], { spawnProcess: f.spawnProcess }); - 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); - // 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); -}); +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn, execFileSync } from 'node:child_process'; +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve, isAbsolute } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { chooseFolder, cleanChosenPath, typedFolder, windowsFolderScript } from '../server/folder-dialog.mjs'; + +const HOST_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); +const failure = (code) => Object.assign(new Error(`exit ${code}`), { code }); +const recorder = () => { + const seen = []; + return { seen, run: (outcome) => async (command, args) => { seen.push({ command, args }); if (outcome instanceof Error) throw outcome; return { stdout: outcome }; } }; +}; + +test('macOS keeps the osascript chooser and treats any dismissal as a cancel', async () => { + const c = recorder(); + assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run('/Users/me/skills/\n') }), { path: '/Users/me/skills' }); + assert.equal(c.seen[0].command, 'osascript'); + assert.equal(c.seen[0].args[1], 'POSIX path of (choose folder with prompt "Pick")'); + assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run(failure(1)) }), { cancelled: true }); +}); + +test('Windows uses a PowerShell FolderBrowserDialog passed as an encoded command', async () => { + const c = recorder(); + const result = await chooseFolder("Don't panic", { platform: 'win32', run: c.run('C:\\Users\\me\\Skills\r\n') }); + assert.deepEqual(result, { path: 'C:\\Users\\me\\Skills' }); + assert.match(c.seen[0].command, /powershell\.exe$/i); + assert.ok(c.seen[0].args.includes('-STA')); + const script = Buffer.from(c.seen[0].args.at(-1), 'base64').toString('utf16le'); + assert.equal(script, windowsFolderScript("Don't panic")); + assert.match(script, /FolderBrowserDialog/); + assert.match(script, /Description = 'Don''t panic'/); + assert.deepEqual(await chooseFolder('Pick', { platform: 'win32', run: c.run('') }), { cancelled: true }); + const missing = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure('ENOENT')) }); + assert.equal(missing.unavailable, true); + // A window that fails after it was started no longer ends in an error with no way on (AGENT-LOST, item 11): the app asks for the path. + const failed = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure(2)) }); + assert.equal(failed.unavailable, true); assert.match(failed.reason, /Type the folder path/); + const nodialog = await chooseFolder('Pick', { platform: 'win32', run: c.run('NODIALOG' + String.fromCharCode(13, 10)) }); + assert.equal(nodialog.unavailable, true); assert.match(nodialog.reason, /Type the folder path/); +}); + +test('the generated PowerShell parses without errors', { skip: process.platform !== 'win32' }, () => { + const shell = join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'); + const out = execFileSync(shell, + ['-NoProfile', '-NonInteractive', '-Command', '$e=$null; [void][System.Management.Automation.Language.Parser]::ParseInput($env:SCRIPT,[ref]$null,[ref]$e); $e.Count'], + { encoding: 'utf8', env: { ...process.env, SCRIPT: windowsFolderScript('Choose a folder for Strata') }, windowsHide: true }).trim(); + assert.equal(out, '0'); +}); + +test('Linux tries zenity, falls back to kdialog, then reports that none exists', async () => { + const order = []; + const run = async (command) => { order.push(command); if (command === 'zenity') throw failure('ENOENT'); return { stdout: '/home/me/skills/\n' }; }; + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run }), { path: '/home/me/skills' }); + assert.deepEqual(order, ['zenity', 'kdialog']); + const none = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure('ENOENT'); } }); + assert.equal(none.unavailable, true); + assert.match(none.reason, /zenity or kdialog/); + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure(1); } }), { cancelled: true }); + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => ({ stdout: '' }) }), { cancelled: true }); +}); + +test('chosen paths lose trailing separators but roots survive', () => { + assert.equal(cleanChosenPath('/a/b/\n'), '/a/b'); + assert.equal(cleanChosenPath('/'), '/'); + assert.equal(cleanChosenPath('C:\\Users\\me\\'), 'C:\\Users\\me'); + assert.equal(cleanChosenPath('C:\\'), 'C:\\'); +}); + +test('a typed path must be an absolute existing directory', async () => { + const dir = await mkdtemp(join(tmpdir(), 'strata-typed-')); + try { + await writeFile(join(dir, 'file.txt'), 'x'); + assert.equal(await typedFolder(dir, { isAbsolute }), dir); + assert.equal(await typedFolder(undefined, { isAbsolute }), null); + await assert.rejects(typedFolder('relative/dir', { isAbsolute }), /full path/); + await assert.rejects(typedFolder(join(dir, 'missing'), { isAbsolute }), /does not exist/); + await assert.rejects(typedFolder(join(dir, 'file.txt'), { isAbsolute }), /not a file/); + } finally { await rm(dir, { recursive: true, force: true }); } +}); + +test('the model page takes a folder or one .gguf file, with or without quotes around the path', async () => { + const dir = await mkdtemp(join(tmpdir(), 'strata-gguf-typed-')); + try { + await writeFile(join(dir, 'model-00001-of-00002.gguf'), 'x'); + await writeFile(join(dir, 'notes.txt'), 'x'); + const only = { isAbsolute, fileType: /\.gguf$/i }; + assert.equal(await typedFolder(dir, only), dir); + assert.equal(await typedFolder(join(dir, 'model-00001-of-00002.gguf'), only), join(dir, 'model-00001-of-00002.gguf')); + assert.equal(await typedFolder(`"${join(dir, 'model-00001-of-00002.gguf')}"`, only), join(dir, 'model-00001-of-00002.gguf')); + assert.equal(await typedFolder(` "${dir}" `, only), dir); + await assert.rejects(typedFolder(join(dir, 'notes.txt'), only), /folder, or a \.gguf file/); + await assert.rejects(typedFolder(join(dir, 'missing.gguf'), only), /does not exist/); + // the other pickers still refuse a file + await assert.rejects(typedFolder(join(dir, 'model-00001-of-00002.gguf'), { isAbsolute }), /not a file/); + } finally { await rm(dir, { recursive: true, force: true }); } +}); + +async function startHost() { + const home = await mkdtemp(join(tmpdir(), 'strata-folder-home-')); + const net = await import('node:net'); + const probe = net.createServer(); + await new Promise(r => probe.listen(0, '127.0.0.1', r)); + const { port } = probe.address(); + await new Promise(r => probe.close(r)); + const child = spawn(process.execPath, [join(HOST_ROOT, 'server', 'index.mjs'), '--dist', join(HOST_ROOT, 'dist')], { + cwd: HOST_ROOT, env: { ...process.env, STRATA_HOME: home, STRATA_WORKSPACE: home, STRATA_PORT: String(port), STRATA_REAL_ENGINE: '0' }, stdio: 'ignore', + }); + const base = `http://127.0.0.1:${port}`; + for (let i = 0; i < 150; i++) { + try { if ((await fetch(`${base}/api/health`)).ok) return { child, base, home }; } catch { /* not up yet */ } + await new Promise(r => setTimeout(r, 100)); + } + child.kill(); + throw new Error('the host did not become healthy'); +} + +test('the host accepts a typed folder path for the picker and for adding a skill, on every OS', { timeout: 60000 }, async () => { + const { child, base, home } = await startHost(); + const skill = await mkdtemp(join(tmpdir(), 'strata-skill-')); + try { + const post = (path, body) => fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + let r = await post('/api/workspaces/pick', { path: skill }); + assert.deepEqual(await r.json(), { path: skill }); + r = await post('/api/workspaces/pick', { path: join(skill, 'nope') }); + assert.equal(r.status, 400); + assert.match((await r.json()).error, /does not exist/); + r = await post('/api/skills/add', { path: skill }); + assert.equal(r.status, 400); + assert.match((await r.json()).error, /no SKILL\.md/); + await writeFile(join(skill, 'SKILL.md'), '---\nname: Typed\n---\nbody\n'); + r = await post('/api/skills/add', { path: skill }); + assert.equal(r.status, 200); + assert.ok((await r.json()).added); + } finally { + child.kill(); + await rm(skill, { recursive: true, force: true }); + await rm(home, { recursive: true, force: true }).catch(() => {}); + } +}); + +// QA report F06: a Windows folder window that never opens must not leave the button disabled forever. +import { EventEmitter } from 'node:events'; +import { watchedWindowsDialog } from '../server/folder-dialog.mjs'; +function fakeShell() { + const child = new EventEmitter(); child.stdout = new EventEmitter(); child.killed = false; child.kill = () => { child.killed = true; }; + return { child, spawnProcess: () => child }; +} +test('Windows: no READY from the dialog script means the host gives up and the app asks for the path', async () => { + const f = fakeShell(); + const result = await watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess }); + assert.deepEqual(result, { noDialog: true }); assert.equal(f.child.killed, true, 'the stuck PowerShell is ended'); + const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ noDialog: true }) }); + assert.equal(answer.unavailable, true); assert.match(answer.reason, /Type the folder path/); +}); +test('Windows: once READY has come the person may take their time, and the answer is read without the READY line', async () => { + const f = fakeShell(); + const pending = watchedWindowsDialog('powershell.exe', [], { readyMs: 30, spawnProcess: f.spawnProcess }); + f.child.stdout.emit('data', 'READY\r\n'); + await new Promise(r => setTimeout(r, 80)); // longer than readyMs: still waiting, not given up + assert.equal(f.child.killed, false); + f.child.stdout.emit('data', 'C:\Users\me\Skills'); f.child.emit('close', 0); + const done = await pending; + const answer = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => done }); + assert.deepEqual(answer, { path: 'C:\Users\me\Skills' }); + const cancelled = await chooseFolder('Pick', { platform: 'win32', windowsDialog: async () => ({ stdout: 'READY\r\n' }) }); + assert.deepEqual(cancelled, { cancelled: true }); +}); +test('Windows: a PowerShell that is missing or fails is reported as before', async () => { + const f = fakeShell(); + const missing = watchedWindowsDialog('powershell.exe', [], { spawnProcess: f.spawnProcess }); + 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); + // 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 de19caff7664c66aa8467b07e7bf45897ab68433 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:04:34 +0100 Subject: [PATCH 48/59] The folder window no longer fails with an error when the Desktop folder is missing (it starts at This PC), and any failure of it now asks for the path instead of leaving no way to choose a folder (found in the review copy, whose profile has no Desktop folder) --- apps/host/server/folder-dialog.mjs | 11 +++++++++-- apps/host/tests/folder-dialog.test.mjs | 6 +++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/apps/host/server/folder-dialog.mjs b/apps/host/server/folder-dialog.mjs index ef90a6639b..cc293416c4 100644 --- a/apps/host/server/folder-dialog.mjs +++ b/apps/host/server/folder-dialog.mjs @@ -25,7 +25,12 @@ export function windowsFolderScript(prompt) { '$dialog.ShowNewFolderButton = $true', // READY tells the host the window is about to open; a host that never sees it gives up and asks for the path in words (QA F06). '[Console]::Out.WriteLine("READY"); [Console]::Out.Flush()', - 'if ($dialog.ShowDialog($owner) -eq "OK") { [Console]::Out.Write($dialog.SelectedPath) }', + // The dialog starts at the Desktop folder. Where that folder does not exist (it was deleted, a OneDrive move left a dead path, the profile was + // redirected) ShowDialog throws "Unable to retrieve the root folder" and no folder could be chosen at all: start at This PC instead, and when even + // that fails say NODIALOG so the app asks for the path. + '$answer = $null', + 'try { $answer = $dialog.ShowDialog($owner) } catch { try { $dialog.RootFolder = [System.Environment+SpecialFolder]::MyComputer; $answer = $dialog.ShowDialog($owner) } catch { [Console]::Out.WriteLine("NODIALOG"); [Console]::Out.Flush() } }', + 'if ($answer -eq "OK") { [Console]::Out.Write($dialog.SelectedPath) }', '$owner.Close()', ].join('; '); } @@ -88,11 +93,13 @@ export async function chooseFolder(prompt, options = {}) { try { const done = windowsDialog ? await windowsDialog(shell, windowsFolderArgs(prompt)) : await run(shell, windowsFolderArgs(prompt)); if (done.noDialog) return { unavailable: true, failed: true, reason: 'The folder window did not open. Type the folder path instead.' }; + if (/^NODIALOG\s*$/m.test(String(done.stdout ?? ''))) return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.' }; const answer = answerOf(done.stdout).trim(); return answer ? { path: cleanChosenPath(answer) } : { cancelled: true }; } catch (error) { if (missing(error)) return { unavailable: true, reason: 'Windows PowerShell was not found.' }; - throw new Error('The folder chooser could not open.'); + // The window opened or tried to and ended with an error: the person is asked for the path instead of being left with an error and no way on. + return { unavailable: true, failed: true, reason: 'The folder window could not open. Type the folder path instead.', detail: `exit ${error?.code ?? '?'}` }; } } return chooseLinuxFolder(prompt, { run, portal }); diff --git a/apps/host/tests/folder-dialog.test.mjs b/apps/host/tests/folder-dialog.test.mjs index 300b3fae43..3ea0268b83 100644 --- a/apps/host/tests/folder-dialog.test.mjs +++ b/apps/host/tests/folder-dialog.test.mjs @@ -35,7 +35,11 @@ test('Windows uses a PowerShell FolderBrowserDialog passed as an encoded command assert.deepEqual(await chooseFolder('Pick', { platform: 'win32', run: c.run('') }), { cancelled: true }); const missing = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure('ENOENT')) }); assert.equal(missing.unavailable, true); - await assert.rejects(chooseFolder('Pick', { platform: 'win32', run: c.run(failure(2)) }), /could not open/); + // A window that fails after it was started no longer ends in an error with no way on (AGENT-LOST, item 11): the app asks for the path. + const failed = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure(2)) }); + assert.equal(failed.unavailable, true); assert.match(failed.reason, /Type the folder path/); + const nodialog = await chooseFolder('Pick', { platform: 'win32', run: c.run('NODIALOG' + String.fromCharCode(13, 10)) }); + assert.equal(nodialog.unavailable, true); assert.match(nodialog.reason, /Type the folder path/); }); test('the generated PowerShell parses without errors', { skip: process.platform !== 'win32' }, () => { From d42341d7971a9d66fc6ee6b05e8f77c76772e449 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:04:34 +0100 Subject: [PATCH 49/59] A reply the length limit cuts inside a file write is no longer lost without a word: requests may produce half the window (compaction's reserve is unchanged), a cut reply is announced and the agent is asked to look at what is on disk and go on in smaller parts, and the file being written streams to the page (name, size, lines, tail) --- apps/host/scripts/agent-lost-e2e.mjs | 209 ++++++++++++++++++ apps/host/server/agent/README.md | 2 +- apps/host/server/agent/agent-bridge.mjs | 33 ++- apps/host/server/agent/events.mjs | 43 +++- .../server/agent/plugins/strata-context.mjs | 45 ++++ apps/host/server/agent/reply-cut.mjs | 123 +++++++++++ apps/host/src/lib/store.ts | 14 +- apps/host/src/lib/types.ts | 24 ++ apps/host/tests/agent-lost.test.mjs | 185 ++++++++++++++++ apps/host/tests/agent-tools.test.mjs | 3 +- apps/host/tests/helpers/scripted-worker.mjs | 17 ++ 11 files changed, 686 insertions(+), 12 deletions(-) create mode 100644 apps/host/scripts/agent-lost-e2e.mjs create mode 100644 apps/host/server/agent/reply-cut.mjs create mode 100644 apps/host/tests/agent-lost.test.mjs diff --git a/apps/host/scripts/agent-lost-e2e.mjs b/apps/host/scripts/agent-lost-e2e.mjs new file mode 100644 index 0000000000..f45e67e8b8 --- /dev/null +++ b/apps/host/scripts/agent-lost-e2e.mjs @@ -0,0 +1,209 @@ +#!/usr/bin/env node +/** + * AGENT-LOST end to end: a long single-file write through the real agent bridge, the real Harness and a real engine. + * + * STRATA_HARNESS_DIR=<harness folder> node scripts/agent-lost-e2e.mjs [pagoda|long|cut ...] + * + * Scenarios (default: all) + * pagoda the owner's own prompt ("Write me a 100 voxel pagoda in one html file with garden."), thinking Medium, bypass mode + * long a deterministic long write: one file of N numbered lines (E2E_LINES, default 1800, about 22K tokens), thinking Off + * mcp Strata's own tool loop (serve runs an MCP tool itself): a call that finishes, and a call the reply is cut inside + * raw the model server alone: a reply cut inside a tool call, as the client receives it + * cut the same long write with the Harness told a small window (E2E_CUT_WINDOW, default 24000), so the reply budget is + * about 7K tokens and the reply is cut inside the tool call: the turn must say so in words and the agent must carry on + * + * A model server that is already running is used when E2E_BASE_URL is set (nothing is started or stopped). Otherwise this + * starts serve/server.py as its own child with the engine named below and stops it by PID. + * + * Environment: E2E_ENGINE (strata executable), E2E_PACK, E2E_GGUF1, E2E_GGUF2, E2E_MTP, E2E_PROFILE, E2E_LIB (library folder), + * E2E_PORT (18590), E2E_WINDOW (65536), E2E_OUT (result folder), E2E_PYTHON. + * + * It prints one table and writes <E2E_OUT>/result.json with the frames summary of each scenario. + */ +import { spawn } from 'node:child_process'; +import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createAgentBridge } from '../server/agent/agent-bridge.mjs'; + +const REPO = join(import.meta.dirname, '..', '..', '..'); +const env = (name, fallback) => process.env[name] ?? fallback; +const HOME = process.env.HOME ?? ''; +const PORT = Number(env('E2E_PORT', '18590')); +const WINDOW = Number(env('E2E_WINDOW', '65536')); +const EXISTING = process.env.E2E_BASE_URL ?? ''; +const PYTHON = env('E2E_PYTHON', 'python3'); +const OUT = env('E2E_OUT', mkdtempSync(join(tmpdir(), 'strata-agent-lost-'))); +const LINES = Number(env('E2E_LINES', '1100')); +const REPEAT = Number(env('E2E_REPEAT', '1')); +const TURN_S = Number(env('E2E_TURN_S', '900')); +const wanted = process.argv.slice(2); +const want = id => wanted.length === 0 || wanted.includes(id); +mkdirSync(OUT, { recursive: true }); + +if (!process.env.STRATA_HARNESS_DIR) { console.error('STRATA_HARNESS_DIR is not set'); process.exit(2); } +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +let server = null, bridge = null; +const finish = async (code) => { + try { await bridge?.close(); } catch { /* going away */ } + if (server?.pid) { try { process.kill(-server.pid, 'SIGTERM'); } catch { try { process.kill(server.pid, 'SIGTERM'); } catch { /* gone */ } } } + await sleep(1500); + console.log(`\nresult folder: ${OUT}`); + process.exit(code); +}; +process.on('SIGINT', () => finish(130)); +process.on('SIGTERM', () => finish(143)); + +if (!EXISTING) { + const pack = env('E2E_PACK', join(HOME, '026q/pack-iq3s')); + const g1 = env('E2E_GGUF1', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf')); + const g2 = env('E2E_GGUF2', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf')); + const mtp = env('E2E_MTP', join(HOME, 'pr1426/mtp-rt')); + const profile = env('E2E_PROFILE', join(HOME, 'bwm/cnt3/data/expert-profile.bin')); + const exe = env('E2E_ENGINE', join(HOME, 'agentlost/eng/strata')); + const lib = env('E2E_LIB', join(HOME, 'agentlost/eng')); + for (const f of [pack, g1, g2, mtp, exe]) if (!existsSync(f)) { console.error(`missing: ${f}`); process.exit(2); } + const config = join(OUT, 'server.json'); + writeFileSync(config, JSON.stringify({ + exe, args: ['--pack', pack, '--native', g1, '--ple-gguf', g2, ...(existsSync(profile) ? ['--expert-profile', profile] : []), + '--prefill', 'auto', '--spec-min-p', '0.5', '--mtp', mtp, '--max-context', String(WINDOW), '--kv', 'int8', '--expert-cache', 'auto', '--spec', '4', + ...(process.env.E2E_ENGINE_ARGS ? process.env.E2E_ENGINE_ARGS.split(' ').filter(Boolean) : [])], + cwd: REPO, tokenizer: join(pack, 'tokenizer'), model_name: 'qwen3.8-flash-next-iq3_s', log: join(OUT, 'engine.log'), lib_dirs: [lib], port: PORT, gpu: 0, + fit_max_tokens: true, + // Strata's own tool loop (serve/server.py run_with_mcp): one small MCP server, offered only to requests that ask for it (strata_mcp). + mcp_servers: { fake: { command: PYTHON, args: [join(REPO, 'serve', 'mcp_fake_server.py')] } }, + }, null, 2)); + server = spawn(PYTHON, ['serve/server.py', '--engine', 'strata', '--config', config, '--port', String(PORT), '--no-api-key', '--ready-file', join(OUT, 'ready.json')], { + cwd: REPO, env: { ...process.env, LD_LIBRARY_PATH: `${lib}:${process.env.LD_LIBRARY_PATH ?? ''}`, STRATA_DATA_DIR: join(OUT, 'data'), PYTHONPATH: `${join(REPO, 'tools')}:${REPO}` }, stdio: ['ignore', 'pipe', 'pipe'], detached: true, + }); + const sink = []; + server.stdout.on('data', d => sink.push(String(d))); + server.stderr.on('data', d => sink.push(String(d))); + server.on('exit', code => { sink.push(`[server exited ${code}]`); server = null; writeFileSync(join(OUT, 'server.log'), sink.join('')); }); +} + +const base = EXISTING || `http://127.0.0.1:${PORT}`; +let ready = false; +for (let i = 0; i < 360 && !ready; i++) { + if (!EXISTING && !server) break; + try { ready = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(2000) })).ok; } catch { /* still loading */ } + if (!ready) await sleep(2000); +} +if (!ready) { console.error('the engine did not become ready'); await finish(4); } +const model = (await (await fetch(`${base}/v1/models`)).json()).data[0].id; +console.log(`engine ready: ${model}`); + +const rows = []; +const note = (id, ok, detail) => { rows.push({ id, ok, detail }); console.log(`${ok ? 'PASS' : 'FAIL'} ${id} ${detail}`); }; + +/** The bridge for a window as the host would tell it (the engine's own window stays WINDOW). */ +function makeBridge(window, dir) { + mkdirSync(join(OUT, dir), { recursive: true }); + return createAgentBridge({ + dataDir: join(OUT, dir), env: process.env, startTimeoutMs: 180_000, log: l => console.log(' bridge:', l), + localInstances: () => [{ id: 'e2e', label: 'iq3_s', baseUrl: `${base}/v1`, modelId: model, context: window, slots: 1, key: '' }], connections: () => [], + }); +} +bridge = makeBridge(WINDOW, 'agent'); + +/** One agent turn; every frame is kept in a compact timeline so the live data path can be read afterwards. */ +async function turn(name, message, { thinking = 'Medium', mode = 'bypass', chatId = name } = {}) { + const workspace = join(OUT, 'ws-' + name); + mkdirSync(workspace, { recursive: true }); + const frames = []; + const t0 = Date.now(); + let timedOut = false; + const stopTimer = setTimeout(() => { timedOut = true; void bridge.stop(chatId).catch(() => {}); }, TURN_S * 1000); + await bridge.runTurn({ chatId, message, workspacePath: workspace, mode, thinking, onFrame: f => frames.push({ at: Date.now() - t0, f }) }); + clearTimeout(stopTimer); + const seconds = (Date.now() - t0) / 1000; + const byType = {}; + for (const { f } of frames) byType[f.type] = (byType[f.type] ?? 0) + 1; + const done = frames.map(x => x.f).filter(f => f.type === 'done').at(-1) ?? null; + const error = frames.map(x => x.f).filter(f => f.type === 'error').at(-1) ?? null; + const prepare = frames.map(x => x.f).filter(f => f.type === 'status' && (f.phase === 'preparing' || f.code === 'preparing-tool')); + const cards = frames.map(x => x.f).filter(f => f.type === 'agent-tool').map(f => f.tool); + const text = frames.map(x => x.f).filter(f => f.type === 'delta').map(f => f.text).join(''); + const files = readdirSync(workspace).map(n => ({ name: n, bytes: statSync(join(workspace, n)).size })); + const cutNotes = frames.map(x => x.f).filter(f => f.type === 'delta' && f.noteReason === 'cut').map(f => f.text.trim()); + const drafts = frames.map(x => x.f).filter(f => f.type === 'agent-tool-draft').map(f => f.draft); + const writes = drafts.filter(d => d.name === 'write' && d.bytes > 0); + const draftStats = { frames: drafts.length, writeFrames: writes.length, lastWrite: writes.filter(d => !d.done).at(-1) ? { target: writes.filter(d => !d.done).at(-1).target, bytes: writes.filter(d => !d.done).at(-1).bytes, lines: writes.filter(d => !d.done).at(-1).lines } : null, previewSample: writes.filter(d => !d.done).at(-1)?.preview.slice(-80) ?? null }; + const writesDone = cards.filter(c => c.name === 'write' && c.state === 'done').length; + const summary = { name, seconds, timedOut, writesDone, cutNotes, draftStats, byType, done, error, files, cards: cards.map(c => ({ name: c.name, state: c.state, target: c.target })), prepareStatuses: prepare.length, firstPrepare: prepare[0] ?? null, lastPrepare: prepare.at(-1) ?? null, text: text.slice(-1200) }; + writeFileSync(join(OUT, `turn-${name}.json`), JSON.stringify({ summary, frames: frames.slice(0, 4000) }, null, 1)); + return { ...summary, frames, workspace }; +} + +const longPrompt = `Create the file big.txt in the current folder with the write tool, in ONE call. It must hold exactly ${LINES} lines. Line N is "N: " followed by one short true sentence about a different city of the world (a new city on every line, no repeats, no pattern). Write every line out yourself, do not use a script or a loop, and do not shorten it.`; + +if (want('raw')) { + // What the model server itself sends when a reply is cut inside a tool call (no Harness): the stream of tool_calls pieces, then finish_reason "length". + const body = { model, stream: true, max_tokens: Number(env('E2E_RAW_CAP', '700')), temperature: 0.6, + chat_template_kwargs: { enable_thinking: false }, + tools: [{ type: 'function', function: { name: 'write', description: 'Write a file.', parameters: { type: 'object', properties: { file_path: { type: 'string' }, content: { type: 'string' } }, required: ['file_path', 'content'] } } }], + messages: [{ role: 'user', content: longPrompt }] }; + const res = await fetch(`${base}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + const text = await res.text(); + const events = text.split(String.fromCharCode(10)).filter(l => l.startsWith('data: {')).map(l => JSON.parse(l.slice(6))); + let args = '', name = '', content = '', finish = null, pieces = 0, ids = new Set(); + for (const e of events) for (const c of e.choices ?? []) { + for (const tc of c.delta?.tool_calls ?? []) { pieces += 1; if (tc.id) ids.add(tc.id); if (tc.function?.name) name = tc.function.name; args += tc.function?.arguments ?? ''; } + content += c.delta?.content ?? ''; + if (c.finish_reason) finish = c.finish_reason; + } + const usage = events.map(e => e.usage).filter(Boolean).at(-1); + writeFileSync(join(OUT, 'raw-sse.txt'), text); + note('raw: a reply cut inside a tool call reaches the client as pieces of the call and finish_reason length', finish === 'length' && name === 'write' && pieces > 5, `finish ${finish}; tool ${name}; ${pieces} call pieces, ${args.length} argument characters, closed JSON ${(() => { try { JSON.parse(args); return true; } catch { return false; } })()}; plain content ${JSON.stringify(content.slice(0, 80))}; ids ${ids.size}; usage ${JSON.stringify(usage)}`); +} + +if (want('mcp')) { + // Strata's own tool loop: the server runs the MCP tool itself. A call that finishes is run; a call the reply is cut inside is announced and never run. + const ask = async (content, max_tokens) => { + const res = await fetch(`${base}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model, stream: true, strata_mcp: true, max_tokens, temperature: 0.6, chat_template_kwargs: { enable_thinking: false }, messages: [{ role: 'user', content }] }) }); + const text = await res.text(); + const events = text.split(String.fromCharCode(10)).filter(l => l.startsWith('data: {')).map(l => JSON.parse(l.slice(6))); + const mcp = events.map(e => e.strata_mcp).filter(Boolean); + const finish = events.flatMap(e => e.choices ?? []).map(c => c.finish_reason).filter(Boolean).at(-1); + const said = events.flatMap(e => e.choices ?? []).map(c => c.delta?.content ?? '').join(''); + return { mcp, finish, said }; + }; + const ok = await ask('Use the fake__echo tool to echo the text "hello from the tool", then tell me what it returned.', 600); + note('mcp: a short call is run by the server and answered', ok.mcp.some(m => m.event === 'result' && m.ok) && ok.finish === 'stop', `events ${JSON.stringify(ok.mcp.map(m => m.event))}; finish ${ok.finish}; said ${JSON.stringify(ok.said.slice(-120))}`); + const cut = await ask('Use the fake__echo tool once. Its text must be the sentence "the quick brown fox jumps over the lazy dog" written out 300 times in a row, separated by spaces.', 300); + note('mcp: a call the reply is cut inside is announced and never run (#211), and the stream says length', cut.mcp.some(m => m.event === 'start') && !cut.mcp.some(m => m.event === 'call') && cut.finish === 'length', `events ${JSON.stringify(cut.mcp.map(m => m.event))}; finish ${cut.finish}; said ${JSON.stringify(cut.said.slice(0, 100))}`); +} + +if (want('pagoda')) { + const t = await turn('pagoda', 'Write me a 100 voxel pagoda in one html file with garden.'); + const html = t.files.find(f => /\.html?$/i.test(f.name)); + console.log(` pagoda: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, files ${JSON.stringify(t.files)}`); + note('pagoda: a file was written or the turn says why not', !!html || /cut|too long|ran out|limit/i.test(t.text), `file ${html ? html.name + ' ' + html.bytes + ' B' : 'none'}; finish ${t.done?.finishReason}; text tail: ${JSON.stringify(t.text.slice(-240))}`); +} +if (want('long')) for (let rep = 1; rep <= REPEAT; rep++) { + const t = await turn(`long${rep}`, longPrompt, { thinking: 'Off' }); + const f = t.files.find(x => x.name === 'big.txt'); + const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0; + console.log(` long${rep}: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, draft ${JSON.stringify(t.draftStats)}, cut notes ${JSON.stringify(t.cutNotes)}`); + note(`long${rep}: big.txt written (${LINES} lines asked)`, lines >= LINES * 0.95 || t.writesDone > 0 || t.cutNotes.length > 0 && !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}; tokens out ${t.done?.tokensOut}; cards ${JSON.stringify(t.cards.filter(c => c.state !== 'running').map(c => c.name))}; writes done ${t.writesDone}; cut notes ${t.cutNotes.length}; draft frames ${t.draftStats.frames}`); + note(`long${rep}: the turn did not end silently`, !!f || t.cutNotes.length > 0 || t.text.trim().length > 0, `text tail ${JSON.stringify(t.text.slice(-160))}`); +} + +if (want('cut')) { + // A small window told to the Harness (E2E_CUT_WINDOW, default 24000; the engine's own stays WINDOW) makes the reply budget about 7K tokens (raised to + // 12K by the fix), so the first reply is cut inside the tool call, as the pagoda's was at 19,660. + await bridge.close(); + bridge = makeBridge(Number(env('E2E_CUT_WINDOW', '24000')), 'agent-cut'); + const t = await turn('cut', longPrompt, { thinking: 'Off' }); + const f = t.files.find(x => x.name === 'big.txt'); + const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0; + console.log(` cut: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason })}, files ${JSON.stringify(t.files)}, cut notes ${JSON.stringify(t.cutNotes)}, draft ${JSON.stringify(t.draftStats)}`); + note('cut: the chat said the reply was cut, in words', t.cutNotes.length > 0 && t.cutNotes.every(n => /length limit/.test(n)), JSON.stringify(t.cutNotes)); + note('cut: the agent went on and the file exists', !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}`); +} + +writeFileSync(join(OUT, 'result.json'), JSON.stringify(rows, null, 2)); +console.log('\n' + rows.map(r => `${r.ok ? 'PASS' : 'FAIL'} ${r.id}`).join('\n')); +await finish(rows.some(r => !r.ok) ? 1 : 0); diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index 11c3279bc0..d92d679855 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -101,7 +101,7 @@ records the patch identity, the dependency version and the before/after SHA-256. Source and already-installed Harness copies are not changed. - A local route is reasoning-capable (`reasoning: true`) with `compat.thinkingFormat: 'chat-template'`: the request carries `chat_template_kwargs {enable_thinking, reasoning_effort}`, which the Strata server reads (a top-level `enable_thinking` is ignored by it, which is why pi-ai's `qwen` format left the model thinking). The chat's Reasoning menu travels as `thinking` in the stream body; the bridge sends it with `session/selectModel` (`reasoningEffort`) whenever the model or the level changed; a level a route does not have is dropped (never an error). API routes keep the provider default (the menu is disabled for them in the UI). -- `localOutputBudget(context)` is 30 percent of the window, at least 4096 and at most 32768 (9,830 tokens at 32K, 19,660 at 64K). The Harness's automatic compaction reads it as the room a reply reserves. pi-ai sends the window minus the prompt. App-loaded models get `fit_max_tokens: true` so the engine clamps instead of answering 400. Sampling is not set here: the Harness sends none, so the server's own defaults apply. +- `localOutputBudget(context)` is 30 percent of the window, at least 4096 and at most 32768 (9,830 tokens at 32K, 19,660 at 64K). The Harness's automatic compaction reads it as the room a reply reserves (the request header), and it is NOT the ceiling of a request: `plugins/strata-context.mjs` raises what the adapter sends to half the window, at most 64K tokens (`reply-cut.mjs` `replyCap`; pi-ai clamps it to the window minus the prompt), because a thinking model that writes a whole file in one call was cut inside the call at 19,660 and lost it (AGENT-LOST). A reply that is cut anyway is announced in the chat, the agent is asked to go on in smaller pieces (twice at most), and the file being written is streamed to the page as `agent-tool-draft` frames (name, size, lines, tail of the text). App-loaded models get `fit_max_tokens: true` so the engine clamps instead of answering 400. Sampling is not set here: the Harness sends none, so the server's own defaults apply. ## Tasks diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index a9853b450c..c3f2fe7eac 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -30,6 +30,10 @@ import { DeliverableTracker, ActivityGroups } from './deliverables.mjs'; import { SkillsUsed, skillInfoFrom } from './skills-used.mjs'; import { turnEngineSpeed } from './engine-speed.mjs'; import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs'; +import { cutNotice, cutNudge } from './reply-cut.mjs'; + +/** How often one turn asks the agent to carry on after a reply the length limit cut (each time in smaller pieces). */ +export const MAX_CUT_RETRIES = 2; import { buildAnswer, parseQuestions } from './user-questions.mjs'; import { BASE_TOKENS, COUNT_ABOVE_CHARS, FIT_TEXT, countTokens, decideFit, fill, grouped } from './context-fit.mjs'; import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; @@ -501,7 +505,15 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ } // The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself). let noteReason = turn.guard ?? null; - if (!noteReason && guard && !failure && !turn.stopping && !turn.goalRun) { + // A reply the length limit cut ends with a sentence that says so (and what was lost), never with silence (AGENT-LOST). + const cutEnd = !failure && !turn.stopping && projector.ended?.kind === 'max-tokens'; + if (cutEnd && !noteReason) { + const note = cutNotice({ ...projector.cut(), retrying: false }); + extra.push({ type: 'delta', own: true, text: ` + +${note.text}`, key: note.key, values: note.values, noteReason: 'cut' }); + } + if (!noteReason && !cutEnd && guard && !failure && !turn.stopping && !turn.goalRun) { noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens }); } if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); } @@ -618,6 +630,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = case 'turn/start': turn.parentOpen = true; if (turn.research) turn.research.waitingStart = false; + turn.cutWaiting = false; clearTimeout(turn.settleTimer); // After Stop, a helper's report would start a new turn that nobody asked for. if (turn.stopping) void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {}); @@ -769,6 +782,24 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = const current = await goalGet(); if (turn.finished || turn.parentOpen) return; if (current && current.phase === 'active' && current.activation === 'armed') { turn.settleTimer = after(700, armSettle); return; } + // A reply the length limit cut (AGENT-LOST): the agent lost what it was writing. Say so in the chat and ask it to carry on in smaller pieces, twice at most. + if (turn.cutWaiting) { turn.settleTimer = after(300, armSettle); return; } + if (projector.ended?.kind === 'max-tokens' && !turn.goalRun && !turn.stopping && (turn.cuts ?? 0) < MAX_CUT_RETRIES) { + const cut = projector.cut(); + turn.cuts = (turn.cuts ?? 0) + 1; + const note = cutNotice({ ...cut, retrying: true }); + emit({ type: 'delta', own: true, text: ` + +${note.text} + +`, key: note.key, values: note.values, noteReason: 'cut' }); + for (const f of projector.clearCut()) emit(f); + turn.cutWaiting = true; + try { await runtime.gw.rpc('session/prompt', { request: { requestId: `cut-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: cutNudge(cut) }] } }); } + catch { turn.cutWaiting = false; finishTurn(null); return; } + turn.settleTimer = after(500, armSettle); + return; + } // Research: gather (search and read pages), then write the answer in the fixed shape. A step that did not open pages is sent back once. if (turn.research && !turn.stopping) { const r = turn.research; diff --git a/apps/host/server/agent/events.mjs b/apps/host/server/agent/events.mjs index 176eba4b36..509b43118e 100644 --- a/apps/host/server/agent/events.mjs +++ b/apps/host/server/agent/events.mjs @@ -11,6 +11,7 @@ import { toolUpdate, TokenCount, fmtTokens } from './status.mjs'; import { askFor } from './ask.mjs'; import { FIT_TEXT, fill } from './context-fit.mjs'; import { isContextOverflow } from './context-budget.mjs'; +import { ToolDraft, cutCalls } from './reply-cut.mjs'; const SHELL = new Set(['pwsh', 'bash', 'job_kill', 'job_output', 'job_list']); const WRITE = new Set(['write', 'edit']); @@ -222,7 +223,8 @@ export class TurnProjector { this.asked = new Map(); // approval id -> callId this.onStatus = null; // (update) => void: what the assistant is doing now (status.mjs); set by the bridge this.reasoning = new TokenCount(); - this.composing = new Map(); // callId -> { name, head, bytes }: a tool call the model is still writing + this.composing = new Map(); // callId -> ToolDraft: a tool call the model is still writing (still here at a cut reply = it was lost) + this.lastOutput = 0; // tokens the LAST model request produced this.running = []; // callIds of tools that are running, oldest first } @@ -289,19 +291,20 @@ export class TurnProjector { out.push({ type: 'reasoning', text: c.text }); } else if (c.type === 'tool-call-delta' && c.id) { // The model is writing a tool call. For a big file this is the long silent part: nothing else arrives until it is finished. - const call = this.composing.get(c.id) ?? { name: c.name ?? '', head: '', bytes: 0 }; + const call = this.composing.get(c.id) ?? new ToolDraft(c.id, c.name ?? ''); if (c.name) call.name = c.name; const piece = String(c.argumentsDelta ?? ''); // Writing a tool call (a whole file, say) is decoding too: its tokens are in the engine's output count, so its time belongs in the speed. this.#produced(f.attemptId, piece, out); - call.bytes += piece.length; - if (call.head.length < 4000) call.head += piece; + call.add(piece); this.composing.set(c.id, call); if (call.name && !NO_CARD.has(call.name)) { - const raw = (/"(?:file_path|path|filePath)"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(call.head) ?? /"url"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(call.head))?.[1]; - let target = raw; try { if (raw !== undefined) target = JSON.parse('"' + raw + '"'); } catch { /* a half-written escape: show it as it is */ } + const target = call.target; const args = target ? { file_path: target, url: target } : {}; this.#status(toolUpdate('preparing', 'preparing-tool', call.name, args, { bytes: call.bytes }, { args: { tool: call.name, verb: toolVerb(call.name, 'running'), target: target ?? '', bytes: call.bytes } })); + // The live data path of a file being written (AGENT-LOST): the name, a growing size and the tail of the text, at most five times a second. + const now = Date.now(); + if (now - call.at >= 200) { call.at = now; out.push(call.frame({ scope: toolScope(call.name), verb: toolVerb(call.name, 'running') })); } } } else if (c.type === 'usage' && c.usage) { this.usageSeen = true; @@ -310,6 +313,7 @@ export class TurnProjector { const prompt = (Number(c.usage.inputTokens) || 0) + (Number(c.usage.cacheReadTokens) || 0) + (Number(c.usage.cacheWriteTokens) || 0); this.tokensIn += prompt; this.tokensOut += Number(c.usage.outputTokens) || 0; + this.lastOutput = Number(c.usage.outputTokens) || 0; this.contextTokens = prompt + (Number(c.usage.outputTokens) || 0); out.push({ type: 'context', contextTokens: this.contextTokens, contextMax: this.window || undefined }); } @@ -333,7 +337,9 @@ export class TurnProjector { const args = parseArguments(d.arguments); const card = { ...presentTool({ callId: d.callId, name: d.name, args }), state: 'running' }; this.tools.set(d.callId, { card, calledAt: e.time }); + const draft = this.composing.get(d.callId); this.composing.delete(d.callId); + if (draft && draft.bytes > 0 && !NO_CARD.has(d.name)) out.push(draft.frame({ done: true })); this.running.push(d.callId); this.#status(toolUpdate('tool', 'tool', d.name, args, {}, { args: { tool: d.name, verb: card.verb, target: card.target } })); out.push({ type: 'agent-tool', tool: card }); @@ -419,8 +425,29 @@ export class TurnProjector { return this.#card(callId, { state: 'denied', result: outcome === 'rejected' ? 'Denied. Nothing ran.' : outcome === 'cancelled' ? 'Cancelled. Nothing ran.' : 'No one could answer this request, so nothing ran.' }); } + /** A reply the model could not finish (the turn ended on the length limit): what it was writing, so nothing is lost without a word. */ + cut() { + return { tokens: this.lastOutput, calls: cutCalls(this.composing.values()) }; + } + + /** The agent was asked to carry on: the calls it lost are not pending any more. */ + clearCut() { const frames = this.#dropDrafts(); this.ended = null; return frames; } + + /** Frames that take the writing cards of calls that will never be whole off the page (the reply was cut, or the turn ended). */ + #dropDrafts() { + const frames = [...this.composing.values()].filter(d => d.bytes > 0 && !NO_CARD.has(d.name)).map(d => d.frame({ done: true, lost: true })); + this.composing.clear(); + return frames; + } + /** The terminal frames for a finished turn. */ - finish({ model, contextMax, engine = null } = {}) { + finish(options = {}) { + const cutInfo = this.ended?.kind === 'max-tokens' ? this.cut() : null; + const dropped = this.#dropDrafts(); + return [...dropped, ...this.#finished(options, cutInfo)]; + } + + #finished({ model, contextMax, engine = null } = {}, cutInfo = null) { const reason = this.ended ?? { kind: 'interrupted' }; const durationMs = Date.now() - this.startedAt; const usage = this.usageSeen @@ -441,7 +468,7 @@ export class TurnProjector { case 'completed': return [{ type: 'done', ...base, ...usage, finishReason: 'stop' }]; case 'max-tokens': - return [{ type: 'done', ...base, ...usage, finishReason: 'length' }]; + return [{ type: 'done', ...base, ...usage, finishReason: 'length', cut: cutInfo }]; case 'aborted': return [{ type: 'done', ...base, ...usage, finishReason: 'aborted', cancelled: true }]; case 'error': diff --git a/apps/host/server/agent/plugins/strata-context.mjs b/apps/host/server/agent/plugins/strata-context.mjs index 589e0fd065..c728e4adde 100644 --- a/apps/host/server/agent/plugins/strata-context.mjs +++ b/apps/host/server/agent/plugins/strata-context.mjs @@ -16,9 +16,13 @@ * request the Harness marks `purpose: 'compaction'` is touched in `llm.stream`. Nothing in the Harness is rewritten: a Harness update * that renames either leaves compaction as it was, and the test that runs the real Harness fails. */ +import { replyCap } from '../reply-cut.mjs'; import { densityOf, estimateMessage, estimateTools, isContextOverflow, MAX_DENSITY, pressureNow, promptTokensOf, splitMessages, summaryBudget, usageOfEvent, WINDOW_SLACK, withSummaryLanguage } from '../context-budget.mjs'; export const name = 'strata-context'; + +/** The routes the host writes for models on this computer (profile.mjs): `strata-local`, `strata-local-<id>`, and their `~s<budget>` copies. */ +const isLocalRoute = provider => typeof provider === 'string' && provider.startsWith('strata-local'); export const inject = ['tokenMeter', 'llm']; /** Real prompt measurements per session: { real, estimated } for the last answer the model server reported. */ @@ -74,6 +78,47 @@ export function apply(ctx) { }; } + // 3. A reply that has room to finish (AGENT-LOST, 11-01). The output budget in the profile is what the Harness's compaction sets aside for a + // reply (30 percent of the window; it reads it from the request header), and the same number was also the ceiling of every request: a thinking + // model that wrote a 15K-token file after 9K tokens of thinking was cut inside the tool call at 19,660, the unfinished call was dropped and the + // turn ended with no file and no word. The header (and so compaction) stays as it is; the request that goes to the model server may produce up + // to half the window, at most 64K tokens (replyCap), and pi-ai still clamps it to what the window has left after the prompt. The agent loop + // dispatches through the adapter's `streamWithSnapshot`, after the loop has checked the request against its header, so that is where the ceiling + // is raised, once per adapter, the first time a local route is prepared. A Harness that renames it leaves the ceiling as it was (the test that + // runs the real Harness fails). + if (llm && typeof llm.prepareCall === 'function' && !wrapped.has(llm.prepareCall)) { + const original = llm.prepareCall; + const raised = new WeakSet(); + const prepare = async function prepareCall(config, signal, configure) { + try { raiseReplyCeiling(config?.provider, raised); } catch (e) { log('warn', `could not raise the reply ceiling: ${e.message}`); } + return original.call(this, config, signal, configure); + }; + wrapped.add(prepare); + llm.prepareCall = prepare; + } + function raiseReplyCeiling(provider, raised) { + if (!isLocalRoute(provider)) return; + const adapter = llm.adapters?.get?.(provider)?.adapter; + if (!adapter || raised.has(adapter) || typeof adapter.streamWithSnapshot !== 'function' || typeof adapter.modelOf !== 'function') return; + raised.add(adapter); + const stream = adapter.streamWithSnapshot; + adapter.streamWithSnapshot = function streamWithSnapshot(options, snapshot) { + let next = options; + try { + if (isLocalRoute(options?.provider)) { + const model = this.modelOf(snapshot, options.provider, options.model); + const asked = options.maxTokens ?? model.maxTokens ?? 0; + // Only the agent's own reply budget is raised: a summary or a title asks for far less and keeps what it asked. + if (model.contextWindow > 0 && asked >= Math.floor(model.contextWindow * 0.25)) { + const cap = replyCap(model.contextWindow, asked); + if (cap > asked) next = { ...options, maxTokens: cap }; + } + } + } catch { next = options; } + return stream.call(this, next, snapshot); + }; + } + // The host asks, with /strata-context, how much of the window the chat holds right now: the same measured number compaction decides on // (JSON in the command's text: { tokens, window }). Before a message goes out, and after /compact, so the person is told true figures. ctx.inject(['commands'], (commandCtx) => { diff --git a/apps/host/server/agent/reply-cut.mjs b/apps/host/server/agent/reply-cut.mjs new file mode 100644 index 0000000000..5cdd8c0e57 --- /dev/null +++ b/apps/host/server/agent/reply-cut.mjs @@ -0,0 +1,123 @@ +/** + * A reply the model could not finish (AGENT-LOST, 11-01): pure helpers, no I/O. + * + * A model reply has a ceiling (the "output budget"). A thinking model that then writes a whole file in one tool call can spend all of it + * before the call is closed. The Harness drops a tool call that was not closed (its arguments are half a JSON text), the turn ends with + * the reason `max-tokens`, and until now the person saw nothing: no file, no card, no sentence. Here: + * + * - `replyCap(window)` how much one reply may produce (the request's ceiling), much larger than the budget the Harness reserves + * for compaction (profile.mjs `localOutputBudget`): the Harness still clamps it to what the window has left. + * - `ToolDraft` what a tool call that is being written looks like so far: its name, the file it is for, a size, a tail of the text. + * - `cutNotice(...)` the plain sentence for the chat, and `cutNudge(...)` the message that lets the agent carry on in smaller pieces. + */ + +/** Half the window, at most 64K tokens, and never less than the budget compaction reserves. The Harness clamps it to the room left (window minus prompt). */ +export function replyCap(window, reserved = 0) { + const w = Number.isFinite(window) && window > 0 ? Math.floor(window) : 32768; + return Math.max(Math.floor(reserved) || 0, Math.min(Math.floor(w / 2), 65536)); +} + +const ESCAPES = { n: '\n', t: '\t', r: '', '"': '"', '\\': '\\', '/': '/', b: '', f: '' }; + +/** A tail of a JSON string body, read back to text: `\n` becomes a newline, `\"` a quote. A half-written escape at the end is dropped. */ +export function unescapeJsonTail(raw) { + let text = String(raw ?? ''); + const cut = /\\(u[0-9a-fA-F]{0,3})?$/.exec(text); + if (cut) text = text.slice(0, cut.index); + return text.replace(/\\(u[0-9a-fA-F]{4}|[nrtbf"\\/])/g, (_, e) => (e[0] === 'u' ? String.fromCharCode(parseInt(e.slice(1), 16)) : ESCAPES[e] ?? e)); +} + +const TARGET = /"(?:file_path|path|filePath)"\s*:\s*"((?:[^"\\]|\\.)*)"/; +const URL_ARG = /"url"\s*:\s*"((?:[^"\\]|\\.)*)"/; +/** The long text argument of the common writing tools; the tail of the arguments is previewed after the first one of these. */ +const BODY = /"(?:content|new_string|new_str|text|code|body|command|file_text)"\s*:\s*"/; + +/** One tool call being written: the model's streamed arguments, kept small. */ +export class ToolDraft { + constructor(id, name = '') { + this.id = id; this.name = name; + this.bytes = 0; this.lines = 0; + this.head = ''; // the first 4,000 characters: the body argument usually starts here + this.where = ''; // the file (or address) the call is for, once seen: a model may write it before or after the text + this.carry = ''; // the last 300 characters, so a name split between two pieces is still seen + this.tail = ''; // the last 2,400 characters: what is being written now + this.at = 0; // when a frame was last sent for it + } + + add(piece) { + const text = String(piece ?? ''); + if (!text) return; + this.bytes += text.length; + for (let i = text.indexOf('\\n'); i >= 0; i = text.indexOf('\\n', i + 2)) this.lines += 1; + if (this.head.length < 4000) this.head += text.slice(0, 4000 - this.head.length); + this.tail = (this.tail + text).slice(-2400); + if (!this.where) { + const seen = this.carry + text; + const raw = (TARGET.exec(seen) ?? URL_ARG.exec(seen))?.[1]; + if (raw !== undefined) { try { this.where = JSON.parse(`"${raw}"`); } catch { this.where = unescapeJsonTail(raw); } } + this.carry = seen.slice(-300); + } + } + + get target() { return this.where; } + + /** The text of the body so far, only its last `max` characters; empty until the body argument has started. */ + preview(max = 1600) { + const start = BODY.exec(this.head); + if (!start) return ''; + const bodyAt = start.index + start[0].length; // where the body begins, counted in streamed characters + if (bodyAt >= this.bytes) return ''; + const tailAt = this.bytes - this.tail.length; // where the kept tail begins + const body = unescapeJsonTail(this.tail.slice(Math.max(0, bodyAt - tailAt))); + return body.length > max ? body.slice(-max) : body; + } + + /** The frame for the page. */ + frame({ done = false, ...extra } = {}) { + return { type: 'agent-tool-draft', draft: { id: this.id, name: this.name, target: this.target, bytes: this.bytes, lines: this.lines, preview: done ? '' : this.preview(), ...extra, done } }; + } +} + +const kb = n => (n >= 10_000 ? `${Math.round(n / 1000)} KB` : `${(n / 1000).toFixed(1)} KB`); + +/** Calls the model was still writing when its reply was cut: [{ name, target, bytes }]. */ +export function cutCalls(drafts) { + return [...drafts].filter(d => d.bytes > 0).map(d => ({ name: d.name, target: d.target, bytes: d.bytes })); +} + +const withTokens = tokens => (tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''); + +/** The sentence for the person, with the catalog slots it needs: { text, key, values }. `again` is true when the agent was already asked to carry on. */ +export function cutNotice({ calls = [], tokens = 0, again = false, retrying = false } = {}) { + const call = calls.find(c => c.target) ?? calls[0] ?? null; + const file = call?.target ? String(call.target).split(/[\\/]/).filter(Boolean).at(-1) : ''; + const what = file || (/^(write|edit)$/.test(call?.name ?? '') ? 'a file' : call?.name); + if (call && retrying) { + const key = 'That reply reached its length limit{0} while writing {1} ({2}), so that write did not happen. I asked the assistant to look at what is on disk and write the rest in smaller parts.'; + const values = [withTokens(tokens), what, kb(call.bytes)]; + return { key, values, text: fill(key, values) }; + } + if (call) { + const key = 'The reply reached its length limit{0} while writing {1} ({2}), so that write did not happen. Say “continue” and it will look at what is on disk and go on in smaller parts.'; + const values = [withTokens(tokens), what, kb(call.bytes)]; + return { key, values, text: fill(key, values) }; + } + if (retrying) { + const key = 'That reply reached its length limit{0} and was cut off. I asked the assistant to carry on.'; + return { key, values: [withTokens(tokens)], text: fill(key, [withTokens(tokens)]) }; + } + const key = 'The reply reached its length limit{0} and was cut off. Say “continue” to go on.'; + return { key, values: [withTokens(tokens)], text: fill(key, [withTokens(tokens)]) }; +} + +export function fill(template, values) { return String(template).replace(/\{(\d+)\}/g, (_, i) => String(values[Number(i)] ?? '')); } + +/** The message sent to the assistant so it carries on. It is not shown as the person's message. */ +export function cutNudge({ calls = [], tokens = 0 } = {}) { + const call = calls.find(c => c.target) ?? calls[0] ?? null; + if (!call) { + return 'Your last reply was cut off by the output limit before it was finished. Carry on from where it stopped without repeating what you already wrote, and keep your thinking short.'; + } + const file = call.target || 'the file'; + return `Your last reply was cut off by the output limit${tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''} while you were writing ${file} in one tool call, so that call did not run and nothing was changed by it. First look at what is on disk now (list the folder, read the end of the file). Do not delete or start over a file that is already complete. If it is not complete, write what is missing in several smaller parts (about 150 lines or fewer each) with edits or appends, and read the end of the file back when you are done. Keep your thinking short.`; +} diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index b8be4c3266..24885c6dbb 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -56,6 +56,7 @@ import type { SetupState, Skill, WorkspaceFile, + ToolDraft, } from './types'; import { navigate, type Route } from './router'; import { estimate, execution, contextTokens } from './experience'; @@ -1957,6 +1958,16 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g addAgentAsk(sessionId, frame as { callId?: unknown; questions?: unknown }); } else if (type === 'agent-question-end') { removeAgentAsk(sessionId, String(frame.callId ?? '')); + } else if (type === 'agent-tool-draft') { + // A tool call (a whole file, say) is being written: keep its name, size and the tail of its text on the reply until the call is whole or lost. + const d = frame.draft as (ToolDraft & { done?: boolean }) | undefined; + if (d && typeof d.id === 'string') { + const { done, ...view } = d; + patchAssistant(m => { + const rest = (m.drafts ?? []).filter(x => x.id !== d.id); + return { ...m, drafts: done ? (rest.length ? rest : undefined) : [...rest, view] }; + }); + } } else if (type === 'agent-tool') { const tool = frame.tool as ToolCall; patchAssistant(m => { @@ -2000,7 +2011,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g clearStatus(sessionId); // A sentence the host wrote for the person (it carries its catalog key) is shown in their language as it is; anything else is made plain here. const said = typeof frame.key === 'string' ? tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) : plainFailure(String(frame.message ?? 'Engine error')).message; - patchAssistant((m) => ({ ...m, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) })); + patchAssistant((m) => ({ ...m, drafts: undefined, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) })); } else if (type === 'done') { clearStatus(sessionId); workFinished(state.doneSound, Number(frame.durationMs ?? performance.now() - started)); @@ -2013,6 +2024,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g patchAssistant((m) => ({ ...m, streaming: false, + drafts: undefined, durationMs: Number(frame.durationMs ?? performance.now() - started), tokens: typeof frame.tokensOut === 'number' ? frame.tokensOut : undefined, ttftMs: typeof frame.ttftMs === 'number' ? frame.ttftMs : undefined, diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts index 5b9b8c1828..a7b5d9deed 100644 --- a/apps/host/src/lib/types.ts +++ b/apps/host/src/lib/types.ts @@ -322,6 +322,8 @@ export interface MonitorState { } export interface ChatMessage { + /** Tool calls the model is writing right now (a file, a command): live data for the writing card; see ToolDraft. */ + drafts?: ToolDraft[]; /** The person's message is written with Markdown (a task handover: bold headings and lists), so the bubble draws it as such. */ markdown?: boolean; photos?:import('./chat-photos').ChatPhoto[]; @@ -375,6 +377,28 @@ export interface ChatMessage { export type ToolState = 'proposed' | 'approved' | 'running' | 'done' | 'denied' | 'error'; +/** + * A tool call the model is still writing (a whole file in one call, say), as the host streams it: the name, the file it is for, a growing size + * and the tail of the text. It lives on the assistant message while the call is written and is removed when the call is complete (the + * ordinary tool card takes over) or the reply was cut and the call was lost (`lost`). + */ +export interface ToolDraft { + id: string; + name: string; + /** The file (or address) the call is for; empty until the model has written it. */ + target: string; + /** Characters of the call's arguments so far (a file's size, a little more because of escapes). */ + bytes: number; + /** Lines of text written so far. */ + lines: number; + /** The last part of the text being written, read back from its JSON form (at most 1,600 characters). */ + preview: string; + /** What the call is: 'write', 'edit', 'shell', ... (same as ToolCall.scope). */ + scope?: 'read' | 'write' | 'shell' | 'connected'; + /** The plain verb for the card while it is written ("Writing"). */ + verb?: string; +} + export interface ToolCall { id: string; name: string; diff --git a/apps/host/tests/agent-lost.test.mjs b/apps/host/tests/agent-lost.test.mjs new file mode 100644 index 0000000000..68b14f7534 --- /dev/null +++ b/apps/host/tests/agent-lost.test.mjs @@ -0,0 +1,185 @@ +// AGENT-LOST (11-01): a reply the length limit cut inside a tool call used to vanish: no file, no card, no sentence. +// Pure parts always run; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and use the scripted model server. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { replyCap, unescapeJsonTail, ToolDraft, cutCalls, cutNotice, cutNudge } from '../server/agent/reply-cut.mjs'; +import { TurnProjector } from '../server/agent/events.mjs'; +import { startScriptedWorker } from './helpers/scripted-worker.mjs'; +import { createAgentBridge, MAX_CUT_RETRIES } from '../server/agent/agent-bridge.mjs'; +import { resolveHarness } from '../server/agent/harness-runtime.mjs'; +import { localOutputBudget } from '../server/agent/profile.mjs'; + +const HARNESS = process.env.STRATA_HARNESS_DIR; +const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false; + +test('the reply ceiling is half the window up to 64K tokens and never below what compaction reserves', () => { + assert.equal(replyCap(65536, localOutputBudget(65536)), 32768); + assert.ok(replyCap(65536, localOutputBudget(65536)) > localOutputBudget(65536), '19,660 was the cut that lost the pagoda'); + assert.equal(replyCap(131072, localOutputBudget(131072)), 65536); + assert.equal(replyCap(262144, localOutputBudget(262144)), 65536, 'at most 64K tokens, so a loop cannot run for an hour'); + assert.equal(replyCap(8192, localOutputBudget(8192)), 4096); + assert.equal(replyCap(0, 5000), 16384, 'no window known: 32K is assumed'); + assert.equal(replyCap(4096, 4096), 4096, 'never below the reserve'); +}); + +test('JSON text is read back for the preview, and a half-written escape is dropped', () => { + assert.equal(unescapeJsonTail('a\\nb\\t\\"c\\"\\\\d'), 'a\nb\t"c"\\d'); + assert.equal(unescapeJsonTail('line\\'), 'line'); + assert.equal(unescapeJsonTail('x\\u00e9y'), 'xéy'); + assert.equal(unescapeJsonTail('x\\u00'), 'x'); +}); + +test('a call being written knows its file, its size, its lines and the tail of its text', () => { + const d = new ToolDraft('c1', 'write'); + for (const piece of ['{"file_pa', 'th":"C:\\\\work\\\\pagoda.html","con', 'tent":"<!doctype html>\\n<html>\\n']) d.add(piece); + assert.equal(d.target, 'C:\\work\\pagoda.html'); + assert.equal(d.lines, 2); + assert.equal(d.preview(), '<!doctype html>\n<html>\n'); + for (let i = 0; i < 400; i++) d.add(`<div class=\\"row${i}\\">text ${i}</div>\\n`); + assert.ok(d.bytes > 10_000); + assert.equal(d.lines, 402); + const p = d.preview(1000); + assert.ok(p.length <= 1000 && p.endsWith('</div>\n') && !p.includes('\\n') && p.includes('class="row'), 'the tail, read back, ends where the model is'); + const f = d.frame({ scope: 'write', verb: 'Writing' }); + assert.deepEqual(Object.keys(f.draft).sort(), ['bytes', 'done', 'id', 'lines', 'name', 'preview', 'scope', 'target', 'verb']); + assert.equal(d.frame({ done: true }).draft.preview, '', 'a finished draft carries no text'); +}); + +test('the file is found when the model writes its name after the text, or split between two pieces', () => { + const d = new ToolDraft('c2', 'write'); + d.add('{"content":"line one\nline two\n'); + assert.equal(d.target, ''); + d.add('more","file_pa'); d.add('th":"/w/big.txt"}'); + assert.equal(d.target, '/w/big.txt'); +}); + +test('the sentences name the file and the size, say what to do, and the nudge asks for smaller parts', () => { + const draft = new ToolDraft('a', 'write'); draft.add('{"file_path":"/w/pagoda.html","content":"'); draft.bytes = 52_300; + const calls = cutCalls([draft]); + assert.deepEqual(calls, [{ name: 'write', target: '/w/pagoda.html', bytes: 52_300 }]); + const again = cutNotice({ calls, tokens: 19660, retrying: true }); + assert.match(again.text, /reached its length limit \(19,660 tokens\) while writing pagoda\.html \(52 KB\), so that write did not happen\. I asked the assistant to look at what is on disk and write the rest in smaller parts\./); + const last = cutNotice({ calls, tokens: 19660 }); + assert.match(last.text, /Say “continue”/); + assert.match(cutNotice({ tokens: 500 }).text, /^The reply reached its length limit \(500 tokens\) and was cut off\. Say “continue”/); + assert.match(cutNudge({ calls, tokens: 19660 }), /writing \/w\/pagoda\.html in one tool call, so that call did not run[\s\S]*Do not delete or start over a file that is already complete[\s\S]*smaller parts/); + assert.match(cutNudge({}), /cut off by the output limit/); + for (const n of [again, last]) assert.equal(n.text, n.key.replace(/\{(\d)\}/g, (_, i) => n.values[i]), 'the key and its values make the sentence'); +}); + +// ------------------------------------------------------------------------------------------------ the projector + +const chunk = (c, attemptId = 'a1') => ({ type: 'assistant-stream', frame: { type: 'chunk', attemptId, chunk: c } }); +const event = (type, data = {}) => ({ type: 'event', event: { type, time: Date.now(), data } }); + +test('the projector streams a growing draft frame for a call being written, and the whole call ends it', () => { + const p = new TurnProjector(); + const frames = []; + const head = '{"file_path":"big.txt","content":"'; + frames.push(...p.consume(chunk({ type: 'tool-call-delta', id: 'c1', name: 'write', argumentsDelta: head }))); + assert.equal(frames.filter(f => f.type === 'agent-tool-draft').length, 1, 'the first piece shows at once'); + const first = frames.find(f => f.type === 'agent-tool-draft').draft; + assert.equal(first.name, 'write'); assert.equal(first.target, 'big.txt'); assert.equal(first.scope, 'write'); assert.equal(first.verb, 'Writing a file'); + // A burst inside 200 ms sends no more frames, but the next one after the pause carries everything so far. + for (let i = 0; i < 20; i++) p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: `entry ${i}\\n` })); + assert.equal(p.composing.get('c1').lines, 20); + p.composing.get('c1').at = 0; + const later = p.consume(chunk({ type: 'tool-call-delta', id: 'c1', argumentsDelta: 'entry 20\\n' })).find(f => f.type === 'agent-tool-draft').draft; + assert.equal(later.lines, 21); assert.match(later.preview, /entry 20\n$/); + const out = p.consume(event('tool/call', { callId: 'c1', name: 'write', arguments: '{"file_path":"big.txt","content":"x"}' })); + assert.ok(out.some(f => f.type === 'agent-tool'), 'the ordinary card takes over'); + assert.equal(out.find(f => f.type === 'agent-tool-draft')?.draft.done, true, 'and the draft is closed'); + assert.equal(p.composing.size, 0); +}); + +test('a reply cut in a call: the done frame says length and what was lost, and the draft is taken down', () => { + const p = new TurnProjector(); + p.consume(chunk({ type: 'tool-call-delta', id: 'c9', name: 'write', argumentsDelta: '{"file_path":"/w/pagoda.html","content":"abc' })); + p.consume(chunk({ type: 'usage', usage: { inputTokens: 6000, outputTokens: 19660 } })); + p.consume(event('turn/end', { reason: { kind: 'max-tokens' } })); + assert.deepEqual(p.cut(), { tokens: 19660, calls: [{ name: 'write', target: '/w/pagoda.html', bytes: p.composing.get('c9').bytes }] }); + const frames = p.finish({ model: 'm', contextMax: 65536 }); + const drop = frames.find(f => f.type === 'agent-tool-draft'); + assert.ok(drop && drop.draft.done && drop.draft.lost, 'the writing card goes away'); + const done = frames.at(-1); + assert.equal(done.type, 'done'); assert.equal(done.finishReason, 'length'); + assert.equal(done.cut.tokens, 19660); assert.equal(done.cut.calls[0].target, '/w/pagoda.html'); +}); + +test('a call nobody writes a card for (a helper agent) makes no draft', () => { + const p = new TurnProjector(); + const out = p.consume(chunk({ type: 'tool-call-delta', id: 's1', name: 'subagent', argumentsDelta: '{"prompt":"x' })); + assert.equal(out.filter(f => f.type === 'agent-tool-draft').length, 0); +}); + +// ------------------------------------------------------------------------------------------------ with the real Harness + +async function rig(t, { window = 65536 } = {}) { + const worker = await startScriptedWorker({ chunkDelayMs: 5 }); + const dir = mkdtempSync(join(tmpdir(), 'strata-lost-')); + const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true }); + const logs = []; + const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: window, slots: 2 }], connections: () => [], + env: process.env, startTimeoutMs: 90_000, log: l => logs.push(l) }); + t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } }); + return { worker, bridge, ws, logs, base: (chatId, onFrame) => ({ chatId, workspacePath: ws, mode: 'bypass', thinking: 'Off', onFrame }) }; +} +const words = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join(''); +const capOf = q => q.params.max_tokens ?? q.params.max_completion_tokens; +const writes = r => r.worker.requests.filter(q => q.directive === 'cutwrite' || q.directive === 'cutalways'); + +test('every model request may produce half the window, not the 30 percent the Harness reserves for compaction', { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.runTurn({ ...r.base('c0', f => out.push(f)), message: 'SCRIPT:echo hello' }); + const asked = r.worker.requests.find(q => q.directive === 'echo'); + assert.ok(asked, 'the model was asked'); + assert.equal(capOf(asked), 32768, `the request carried ${capOf(asked)}; the pagoda's carried 19660`); +}); + +test('a small window still gets a request that fits it (the Harness clamps to the room left)', { skip }, async (t) => { + const r = await rig(t, { window: 8192 }); + await r.bridge.runTurn({ ...r.base('c0s', () => {}), message: 'SCRIPT:echo hello' }); + const asked = r.worker.requests.find(q => q.directive === 'echo'); + assert.ok(capOf(asked) > 0 && capOf(asked) <= 4096, `max_tokens ${capOf(asked)} for an 8K window`); +}); + +test('a reply cut inside a file write: the chat says so, the agent is asked to go on in smaller parts, and the file gets written', { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:cutwrite big.txt' }); + const said = out.find(f => f.type === 'delta' && f.noteReason === 'cut'); + assert.ok(said, 'a sentence about the cut'); + assert.match(said.text, /while writing big\.txt/); assert.match(said.text, /that write did not happen. I asked the assistant to look at what is on disk and write the rest in smaller parts/); + assert.equal(out.filter(f => f.type === 'error').length, 0); + const done = out.filter(f => f.type === 'done').at(-1); + assert.equal(done.finishReason, 'stop', 'the turn ends on the agent\'s own finish, not on the cut'); + assert.ok(existsSync(join(r.ws, 'big.txt')), 'the file is on disk'); + assert.match(readFileSync(join(r.ws, 'big.txt'), 'utf8'), /entry 0001/); + assert.match(words(out), /Written in parts/); + assert.equal(writes(r).length, 3, 'the cut reply, the nudged write, the closing words'); + assert.ok(writes(r)[1].raw.includes('cut off by the output limit'), 'the second request carries the nudge'); + const drafts = out.filter(f => f.type === 'agent-tool-draft'); + assert.ok(drafts.length >= 2, 'the writing was shown live'); + assert.ok(drafts.some(f => !f.draft.done && f.draft.name === 'write'), 'a writing card opened as soon as the model named the call'); + // The Harness hands the streamed pieces over in batches (a few a second at most), so a short script may show only the first and the last. + assert.ok(drafts.some(f => f.draft.done && f.draft.lost && f.draft.target === 'big.txt' && f.draft.bytes > 1000), 'and taken down, with its file and size, when it was lost'); +}); + +test(`a model that is cut every time is asked ${MAX_CUT_RETRIES} times, then the turn ends with a plain sentence, never silently`, { skip }, async (t) => { + const r = await rig(t); + const out = []; + await r.bridge.runTurn({ ...r.base('c2', f => out.push(f)), message: 'SCRIPT:cutalways big.txt' }); + assert.equal(writes(r).length, MAX_CUT_RETRIES + 1); + const notes = out.filter(f => f.type === 'delta' && f.noteReason === 'cut'); + assert.equal(notes.length, MAX_CUT_RETRIES + 1, 'one sentence per cut'); + assert.match(notes.at(-1).text, /that write did not happen\. Say “continue”/); + const done = out.filter(f => f.type === 'done').at(-1); + assert.ok(done, 'the turn ended'); + assert.equal(done.finishReason, 'length'); + assert.equal(done.cut.calls[0].target, 'big.txt'); + assert.equal(existsSync(join(r.ws, 'big.txt')), false, 'nothing half-written is left behind'); +}); diff --git a/apps/host/tests/agent-tools.test.mjs b/apps/host/tests/agent-tools.test.mjs index 63aef01b4d..faaeeb33d8 100644 --- a/apps/host/tests/agent-tools.test.mjs +++ b/apps/host/tests/agent-tools.test.mjs @@ -273,7 +273,8 @@ test('the output budget is not the old 8192, and the Reasoning menu reaches the const off = await ask('think-off', 'Off'); assert.equal(ctk(off).enable_thinking, false); assert.equal(ctk(off).reasoning_effort, undefined); assert.equal(off.enable_thinking, undefined, 'a top-level enable_thinking is the field the Strata server ignores'); - assert.ok(off.max_completion_tokens === 19660, `budget ${off.max_completion_tokens} (half the window, at most 32K: never the old 8192, and room is left for the conversation to be compacted)`); + // The profile's budget (19,660 at 64K: what compaction sets aside for a reply) is the header the Harness reads; the request itself may produce half the window (AGENT-LOST). + assert.ok(off.max_completion_tokens === 32768, `ceiling ${off.max_completion_tokens} (half the window, at most 64K: never the old 8192, and a file written in one call is not cut at the 30 percent compaction reserves)`); const high = await ask('think-high', 'High'); assert.equal(ctk(high).enable_thinking, true); assert.equal(ctk(high).reasoning_effort, 'high'); const low = await ask('think-low', 'Low'); diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjs index 8840b0b133..cf66f3baf2 100644 --- a/apps/host/tests/helpers/scripted-worker.mjs +++ b/apps/host/tests/helpers/scripted-worker.mjs @@ -152,6 +152,23 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model = send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'web_search', arguments: argsJson } }] }); return finish('tool_calls', 60); } + if (directive?.[1] === 'cutwrite' || directive?.[1] === 'cutalways') { + // A reply the length limit cuts inside a tool call (AGENT-LOST): some words, then `write` arguments that never close, finish "length". + // `cutwrite` is cut once and then, asked to carry on, writes the file in a small call; `cutalways` is cut every time. + const nudged = messages.some(m => m.role === 'user' && /cut off by the output limit/.test(text(m))); + if (directive[1] === 'cutwrite' && nudged) { + if (last.role === 'tool') return say(['Written in parts. The file is complete.']); + return toolCall('write', { file_path: (directive[2] ?? '').trim() || 'big.txt', content: 'entry 0001\nentry 0002\n' }); + } + send({ role: 'assistant', content: 'Writing the whole file in one call now. ' }); + await delay(chunkDelayMs); + const file = (directive[2] ?? '').trim() || 'big.txt'; + send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'write', arguments: '' } }] }); + const head = `{"file_path":"${file}","content":"`; + for (let i = 0; i < head.length; i += 11) { send({ tool_calls: [{ index: 0, function: { arguments: head.slice(i, i + 11) } }] }); await delay(2); } + for (let n = 1; n <= 60; n++) { send({ tool_calls: [{ index: 0, function: { arguments: `entry ${String(n).padStart(4, '0')}: alpha beta gamma delta\\n` } }] }); await delay(2); } + return finish('length', 19660); + } if (directive?.[1] === 'bloat') { promptTokens = parseInt((directive[2] ?? '').trim(), 10) || 100; send({ role: 'assistant', content: '', reasoning_content: 'Thinking about it for a long time and never getting to the answer.' }); From 68baeabc54da4c2736db7892322d862de6d51aa7 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:20:54 +0100 Subject: [PATCH 50/59] Terminal and MCP agree with 128K: DeepSeek's setup default is 128K (a Mac keeps 8K), setup no longer calls the default untested, the pinned tests follow --- apps/host/src/lib/native-fit.ts | 4 ++-- setup.py | 7 ++++--- tests/terminal/test_dsv41_context.py | 15 ++++++++------- tests/terminal/test_launch.py | 8 ++++---- tests/terminal/test_launch_dsv41.py | 4 ++-- tests/terminal/test_launch_tui.py | 8 ++++---- tests/terminal/test_tui3.py | 2 +- tools/strata_mcp.py | 2 +- tools/test_setup_dsv41.py | 10 +++++----- tools/test_strata_mcp.py | 4 ++-- 10 files changed, 33 insertions(+), 31 deletions(-) diff --git a/apps/host/src/lib/native-fit.ts b/apps/host/src/lib/native-fit.ts index 3ca0080e45..7e8a5fcabf 100644 --- a/apps/host/src/lib/native-fit.ts +++ b/apps/host/src/lib/native-fit.ts @@ -19,8 +19,8 @@ export interface Fit { known: boolean; } -export const DENSE_GB = 5; -const SYSTEM_ROOM_GB = 10, DENSE_EXTRA_GB = 1; +const DENSE_GB = 5, SYSTEM_ROOM_GB = 10, DENSE_EXTRA_GB = 1; +export { DENSE_GB }; /** The draft layer (MTP) takes about 1 GB of graphics memory (786 MiB of files + the draft head's ~218 MiB); it comes out of the expert cache while MTP is on (setup.py MTP_VRAM_GB). */ export const MTP_VRAM_GB = 1; const round1 = (n: number) => Math.round(n * 10) / 10; diff --git a/setup.py b/setup.py index a12964a0b0..a7fb85afc8 100644 --- a/setup.py +++ b/setup.py @@ -805,6 +805,7 @@ DSV41_UD_FILES = { DSV41_FILES.update(DSV41_UD_FILES) # (the repository's pins: REPO_PINS) DSV41_ALL_FILES = {**DSV41_FILES, **DSV41_ISTA_FILES, **DSV41_ISTA6_FILES, **DSV41_LEGACY_FILES, **DSV41_UD_FILES} DSV41_PROFILES = ROOT / "data" / "dsv41" # the shipped hot-expert profiles (profile-2.00.bin, profile-2.25.bin, + .sha256) +DSV41_MAC_CONTEXT = 8192 # DeepSeek on a Mac keeps the 8K it was run at (the owner's 128K decision is for cards; nothing was run on a Mac at 128K) DSV41_CONTEXT = 131072 # 128K like every model (owner, 2026-11-01; strata_control/default_context.py); the engine was checked at 4096 and 8192 before, INT3 checks 128K on real cards DSV41_MAC_VISION = False # an Apple Silicon Mac: the Metal engine has not run DeepSeek's picture tower (0.2.7.1), so pictures stay off there MULTI_FILE_FAMILIES = { @@ -8601,7 +8602,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, cards = dsv41_cards(gpu, all_cards, named) ctx = a.context or DSV41_CONTEXT if dsv41_context.problem(ctx): # 8K to 1M: the model reads 1,048,576 positions (Project Maya #442); a size it cannot address stops here, before any download - fail(dsv41_context.problem(ctx), "--context takes 8192 up to 1048576 (8K, 32K, 64K, 128K, 256K, 512K, 1M); the default is 8192") + fail(dsv41_context.problem(ctx), "--context takes 8192 up to 1048576 (8K, 32K, 64K, 128K, 256K, 512K, 1M); the default is 131072 (128K)") if dsv41_context.note(ctx): warn(f"context {dsv41_context.label(ctx)}: {dsv41_context.note(ctx)}") folder = dsv41_folder(a, fam, tag, model) @@ -8668,8 +8669,8 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, "answers), or --gguf-dir for files you already have") if left and free < left + dsv41_fit.DISK_HEADROOM_GB: warn(f"little free disk space in {folder}: {free:.1f} GB free for about {left:.1f} GB. Setup goes on and should fit") - if ctx > 65536: - warn(f"{ctx // 1024}K tokens of context: the engine was checked at 4K and 8K; longer is kept as you chose, but untested") + if ctx > DSV41_CONTEXT: # 128K is the default now (owner, 2026-11-01); only a longer one the person asked for is said to be untested + warn(f"{ctx // 1024}K tokens of context: longer than the {DSV41_CONTEXT // 1024}K the engine is checked at; kept as you chose, but untested") # Pictures are on by default (owner rule): the engine reads them with its own vision tower (319 MiB, loaded with the model, no separate # reader process). --vision no turns them off (--vision off for the engine); gpu / cpu name a Flash-Next reader and mean "on" here. if a.vision in ("gpu", "cpu"): diff --git a/tests/terminal/test_dsv41_context.py b/tests/terminal/test_dsv41_context.py index 95bc5c8658..bcf8929920 100644 --- a/tests/terminal/test_dsv41_context.py +++ b/tests/terminal/test_dsv41_context.py @@ -117,16 +117,17 @@ class Terminal(unittest.TestCase): class SetupAndApp(unittest.TestCase): - def test_nobody_gets_a_bigger_context_than_before_unless_they_choose_it(self): - """The default stays 8K everywhere: setup writes it, the Terminal recommends it, the app starts a new DeepSeek version at it and shows an installed one at - the context it was prepared with (so a 0.2.5 / 0.2.6 user's load is the saved file's, as it was).""" + def test_the_default_is_128k_everywhere_unless_the_person_chooses(self): + """Owner, 2026-11-01: 128K on every card and for DeepSeek too. setup writes it, the Terminal recommends it, the app starts a new DeepSeek version at it + and shows an installed one at the context it was prepared with when someone chose it (a saved 8K without the app's marker is the old default).""" import setup - self.assertEqual(setup.DSV41_CONTEXT, 8192) + self.assertEqual(setup.DSV41_CONTEXT, 131072) + self.assertEqual(setup.DSV41_MAC_CONTEXT, 8192) # nothing was run on a Mac at 128K: a Mac keeps its 8K with Home(), mock.patch.object(Catalog, "hardware", lambda self, fresh=False: dict(HW_4X32)): - self.assertEqual(catalog(HW_4X32).max_context("deepseek41", "UD-Q8_K_XL"), 8192) + self.assertEqual(catalog(HW_4X32).max_context("deepseek41", "UD-Q8_K_XL"), 131072) screen = (ROOT / "apps" / "host" / "src" / "components" / "NativeModels.tsx").read_text(encoding="utf-8") - self.assertRegex(screen, r"if \(selectedSize\.multi_file\)\s+setContext\(8192\)") - self.assertRegex(screen, r"if \(installed\.context\)\s+setContext\(installed\.context\)") + self.assertRegex(screen, r"setContext\(defaultContext\(contextList\)\)") + self.assertRegex(screen, r"openingContext\(installed\.context, contextList, installed\.contextChosen === true, selectedSize\.multi_file \? \[OLD_DEEPSEEK_CONTEXT\] : undefined\)") def test_setup_stops_before_any_download_and_checks_the_pack_again(self): source = (ROOT / "setup.py").read_text(encoding="utf-8") diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index 8f933fcd26..a98bf33458 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -193,7 +193,7 @@ class CatalogRules(unittest.TestCase): cat = catalog() self.assertAlmostEqual(cat.kv_gb(131072, "int8"), 1.799, places=2) self.assertLess(cat.kv_gb(131072, "q4_0"), cat.kv_gb(131072, "int8")) - self.assertEqual(cat.max_context("qwen", "IQ3_XXS", HW_12), 32768) + self.assertEqual(cat.max_context("qwen", "IQ3_XXS", HW_12), 131072) # 128K on every card (owner, 2026-11-01) self.assertEqual(cat.max_context("qwen", "IQ3_XXS", HW_24), 131072) def test_missing_installer_files_are_said_in_words(self): @@ -568,9 +568,9 @@ class AdoptRules(unittest.TestCase): hw["gpus"] = cards cat = catalog(hw) self.assertEqual(cat.computer().line().split(" 8 GB")[0], "Arc A750".replace("Arc", "Intel Arc")) - self.assertEqual(cat.max_context("qwen", "IQ3_XXS", hw), 8192) + self.assertEqual(cat.max_context("qwen", "IQ3_XXS", hw), 131072) # an 8 GB Arc too: warned about, never lowered hw["gpus"] = [{"vendor": "intel", "name": "Intel Arc Pro B70", "vram_gb": 32.0, "usable": True}] - self.assertEqual(cat.max_context("qwen", "IQ3_XXS", hw), 32768) + self.assertEqual(cat.max_context("qwen", "IQ3_XXS", hw), 131072) def test_plan_names_what_is_missing(self): from strata_cli.launch import adopt @@ -859,7 +859,7 @@ class FlagsCommand(unittest.TestCase): def test_defaults_come_from_the_recommendation(self): p = self.plan() s = p["settings"] - self.assertEqual((s["family"], s["model"], s["context"], s["access"], s["tune"]), ("qwen", "IQ3_S", 32768, "local", "skip")) + self.assertEqual((s["family"], s["model"], s["context"], s["access"], s["tune"]), ("qwen", "IQ3_S", 131072, "local", "skip")) self.assertTrue(any("picked" in w for w in p["warnings"])) def test_family_and_kv_and_gpu_and_data_dir_and_set(self): diff --git a/tests/terminal/test_launch_dsv41.py b/tests/terminal/test_launch_dsv41.py index 4e8fbec02f..2be9bb4fb4 100644 --- a/tests/terminal/test_launch_dsv41.py +++ b/tests/terminal/test_launch_dsv41.py @@ -43,13 +43,13 @@ class LaunchDeepSeek(unittest.TestCase): r = rows[5] self.assertEqual((r.id, r.download_gb, r.verdict, r.images), ("deepseek-v4.1-flash-ud-q8_k_xl", 508.4, "fits", True)) # 0.2.7: pictures through the engine's own tower self.assertEqual(catalog(self.hw).resolve("ud-q8_k_xl"), ("deepseek41", "UD-Q8_K_XL")) - self.assertEqual(catalog(self.hw).max_context("deepseek41", "UD-Q8_K_XL"), 8192) + self.assertEqual(catalog(self.hw).max_context("deepseek41", "UD-Q8_K_XL"), 131072) def test_the_plan_places_the_model_on_the_four_cards(self): p = self.plan("--model", "ud-q8_k_xl", "--no-tui") pl = p["placement"] self.assertEqual(p["settings"]["family"], "deepseek41") - self.assertEqual(p["settings"]["context"], 8192) + self.assertEqual(p["settings"]["context"], 131072) self.assertEqual(p["settings"]["tune"], "skip") self.assertEqual(p["settings"]["vision"], "on") # pictures are on by default (the engine's own tower) self.assertEqual(pl["verdict"], "fits") diff --git a/tests/terminal/test_launch_tui.py b/tests/terminal/test_launch_tui.py index 4d859cebdc..8753ce19b1 100644 --- a/tests/terminal/test_launch_tui.py +++ b/tests/terminal/test_launch_tui.py @@ -399,7 +399,7 @@ class ContextStep(Base): def test_choose_128k(self): async def case(app, pilot, ctx): - await press(pilot, "enter", "enter", "enter", "down", "down", "enter") + await press(pilot, "enter", "enter", "enter", "enter") # the cursor starts on 128K now (the default on every card) self.assertEqual(ctx.settings.context, 131072) self.assertIn("Should the model read pictures?", text_of(app)) self.run_app(case) @@ -799,13 +799,13 @@ class SaveAndRun(Base): t = text_of(app) self.assertIn("Save as preset, then launch", t) self.assertIn("Qwen3.8-Flash-Next IQ3_S", t) - self.assertIn("32K, memory int8", t) + self.assertIn("128K, memory int8", t) self.assertIn("quick (about 20 min)", t) self.assertIn("This computer only, port 8080", t) await press(pilot, "enter") # Save as a preset and launch await pilot.pause(0.8) - self.assertEqual([p.name for p in store.list_presets()], ["IQ3_S 32K"]) - self.assertEqual(FakeRunner.instances[0].s.name, "IQ3_S 32K") + self.assertEqual([p.name for p in store.list_presets()], ["IQ3_S 128K"]) + self.assertEqual(FakeRunner.instances[0].s.name, "IQ3_S 128K") self.assertIsNotNone(app.result) self.run_app(case) diff --git a/tests/terminal/test_tui3.py b/tests/terminal/test_tui3.py index 7858e34040..344b75db46 100644 --- a/tests/terminal/test_tui3.py +++ b/tests/terminal/test_tui3.py @@ -218,7 +218,7 @@ class SaveWaitsForRestartAnswer(unittest.TestCase): return [p.name for p in store.list_presets()] after = asyncio.run(go()) self.assertEqual(seen["presets_during_run"], []) # not saved before the runner's check - self.assertEqual(after, ["IQ3_S 32K"]) # saved once the run went on + self.assertEqual(after, ["IQ3_S 128K"]) # saved once the run went on class DraftingOffConfig(unittest.TestCase): diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index acbe73b95f..63c113953b 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -2339,7 +2339,7 @@ class Tools: if vision in ("yes", "gpu", "cpu"): raise ToolError("images are not available with DeepSeek on a Mac yet: use vision=no") vision = "no" - context = context or getattr(s.setup_module(), "DSV41_CONTEXT", 8192) + context = context or getattr(s.setup_module(), "DSV41_MAC_CONTEXT", 8192) context = context or (s.mac().recommend_context(hw.get("ram_gb") or 0) if s.mac() else 32768) if context is None and md.get("multi_file"): context = getattr(s.setup_module(), "DSV41_CONTEXT", 8192) # the context the engine was checked at diff --git a/tools/test_setup_dsv41.py b/tools/test_setup_dsv41.py index baecd94835..45f2417721 100644 --- a/tools/test_setup_dsv41.py +++ b/tools/test_setup_dsv41.py @@ -218,7 +218,7 @@ class Install(unittest.TestCase): self.assertEqual(self.cfg["exe"], str(self.exe)) self.assertEqual(self.cfg["model_name"], "deepseek-v4.1-flash") a = self.cfg["args"] - self.assertEqual(a[a.index("--max-context") + 1], "8192") + self.assertEqual(a[a.index("--max-context") + 1], "131072") self.assertEqual(a[a.index("--eos") + 1], "1") self.assertEqual(a[a.index("--tp") + 1], "2") self.assertTrue(Path(a[a.index("--pack") + 1]).match("*packs/deepseek-v4.1-flash-ud-q8_k_xl")) @@ -277,7 +277,7 @@ class Install(unittest.TestCase): self.assertEqual(rc, 0, out) self.assertIn("read from the SSD", out) self.assertIn("installing UD-Q8_K_XL with 64 GB of RAM, as you chose", out) - self.assertEqual(self.cfg["args"][self.cfg["args"].index("--max-context") + 1], "8192") + self.assertEqual(self.cfg["args"][self.cfg["args"].index("--max-context") + 1], "131072") self.assertNotIn("--tp", self.cfg["args"]) def test_little_ram_with_yes_alone_stops_where_the_rule_says(self): @@ -302,7 +302,7 @@ class Install(unittest.TestCase): self.assertEqual(a[a.index("--vision") + 1], "on") self.assertIn("Flash-Next settings", out) self.assertEqual(self.cfg["args"][self.cfg["args"].index("--max-context") + 1], "131072") - self.assertIn("checked at 4K and 8K", out) + self.assertNotIn("untested", out) # 128K is the default: nothing to warn about class Catalog(unittest.TestCase): @@ -351,7 +351,7 @@ class Catalog(unittest.TestCase): "cpu": {"avx2": True}} s.disk_free = lambda p: 2000.0 plan, a = M.Tools(s).install_plan("deepseek41", "UD-Q8_K_XL", None, None, None, None, None, None, None, None, None) - self.assertEqual((plan["title"], plan["download_gb"], plan["context"], plan["images"]), ("DeepSeek-V4.1-Flash UD-Q8_K_XL", 508.4, 8192, "yes")) # 0.2.7: pictures on by default + self.assertEqual((plan["title"], plan["download_gb"], plan["context"], plan["images"]), ("DeepSeek-V4.1-Flash UD-Q8_K_XL", 508.4, 131072, "yes")) # 0.2.7: pictures on by default self.assertEqual(a[:6], ["--yes", "--no-start", "--family", "deepseek41", "--model", "UD-Q8_K_XL"]) self.assertTrue(plan["ram"].startswith("fits")) for flag in ("--kv", "--low-ram", "--experimental-speed-projection"): @@ -882,7 +882,7 @@ class InstallOfficial(Install): self.assertNotIn("--prefill-chunk", a) # the engine's own default is the layer-major prompt path self.assertEqual(a[a.index("--dspark-conf") + 1], "0.65") # never a floor below 0.3 # the layer-major prompt path self.assertNotIn("--ssd-cache", a) # the store sizes itself - self.assertEqual(a[a.index("--max-context") + 1], "8192") + self.assertEqual(a[a.index("--max-context") + 1], "131072") self.assertIn("checked: every file the engine needs is there", out) self.assertIn("test question answered sensibly", out) self.assertTrue(Path(a[a.index("--pack") + 1]).match("*packs/deepseek-v4.1-flash-ist-das-2.00bpw")) diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index 87aa30e1a7..a5fa4db86c 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -392,7 +392,7 @@ class Install(FakeRoot): res, err = self.call("strata_install", {}) self.assertFalse(err) self.assertIn("Nothing was done yet", res["summary"]) - self.assertEqual((res["plan"]["family"], res["plan"]["model"], res["plan"]["context"]), ("qwen", "IQ3_S", 32768)) + self.assertEqual((res["plan"]["family"], res["plan"]["model"], res["plan"]["context"]), ("qwen", "IQ3_S", 131072)) self.assertFalse((self.root / "setup-args.json").exists()) self.assertIsNone(self.strata.install_job()) @@ -665,7 +665,7 @@ class Helpers(unittest.TestCase): r = s.recommend({"ram_gb": 64, "gpus": [], "cpu": {"avx2": True}}) self.assertIsNone(r["model"]) r = s.recommend({"ram_gb": 64, "gpus": [{**gpu[0], "vram_gb": 12.0}], "cpu": {"avx2": True}}) - self.assertEqual(r["context"], 32768) + self.assertEqual(r["context"], 131072) # 128K on every card, a 12 GB one too (owner, 2026-11-01) def test_a_pick_that_reads_from_the_ssd_says_so(self): # #3425: 36 GB RAM + 16 GB VRAM - 5 GB is the 48 GB tier; about 8 GB of IQ3_XXS would come from the SSD From d7d2ffab974fcdc5a421ca8633adc59fc68335e2 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:34:50 +0100 Subject: [PATCH 51/59] Take the rewritten agent-lost files (the cut sentence says the write did not happen and what the assistant is asked; the e2e script) --- apps/host/scripts/agent-lost-e2e.mjs | 42 +++++++++++++++++++++++----- apps/host/server/agent/reply-cut.mjs | 11 ++++---- apps/host/tests/agent-lost.test.mjs | 8 +++--- 3 files changed, 45 insertions(+), 16 deletions(-) diff --git a/apps/host/scripts/agent-lost-e2e.mjs b/apps/host/scripts/agent-lost-e2e.mjs index 642b2f25c8..f45e67e8b8 100644 --- a/apps/host/scripts/agent-lost-e2e.mjs +++ b/apps/host/scripts/agent-lost-e2e.mjs @@ -7,6 +7,7 @@ * Scenarios (default: all) * pagoda the owner's own prompt ("Write me a 100 voxel pagoda in one html file with garden."), thinking Medium, bypass mode * long a deterministic long write: one file of N numbered lines (E2E_LINES, default 1800, about 22K tokens), thinking Off + * mcp Strata's own tool loop (serve runs an MCP tool itself): a call that finishes, and a call the reply is cut inside * raw the model server alone: a reply cut inside a tool call, as the client receives it * cut the same long write with the Harness told a small window (E2E_CUT_WINDOW, default 24000), so the reply budget is * about 7K tokens and the reply is cut inside the tool call: the turn must say so in words and the agent must carry on @@ -33,7 +34,9 @@ const WINDOW = Number(env('E2E_WINDOW', '65536')); const EXISTING = process.env.E2E_BASE_URL ?? ''; const PYTHON = env('E2E_PYTHON', 'python3'); const OUT = env('E2E_OUT', mkdtempSync(join(tmpdir(), 'strata-agent-lost-'))); -const LINES = Number(env('E2E_LINES', '1400')); +const LINES = Number(env('E2E_LINES', '1100')); +const REPEAT = Number(env('E2E_REPEAT', '1')); +const TURN_S = Number(env('E2E_TURN_S', '900')); const wanted = process.argv.slice(2); const want = id => wanted.length === 0 || wanted.includes(id); mkdirSync(OUT, { recursive: true }); @@ -50,6 +53,7 @@ const finish = async (code) => { process.exit(code); }; process.on('SIGINT', () => finish(130)); +process.on('SIGTERM', () => finish(143)); if (!EXISTING) { const pack = env('E2E_PACK', join(HOME, '026q/pack-iq3s')); @@ -67,6 +71,8 @@ if (!EXISTING) { ...(process.env.E2E_ENGINE_ARGS ? process.env.E2E_ENGINE_ARGS.split(' ').filter(Boolean) : [])], cwd: REPO, tokenizer: join(pack, 'tokenizer'), model_name: 'qwen3.8-flash-next-iq3_s', log: join(OUT, 'engine.log'), lib_dirs: [lib], port: PORT, gpu: 0, fit_max_tokens: true, + // Strata's own tool loop (serve/server.py run_with_mcp): one small MCP server, offered only to requests that ask for it (strata_mcp). + mcp_servers: { fake: { command: PYTHON, args: [join(REPO, 'serve', 'mcp_fake_server.py')] } }, }, null, 2)); server = spawn(PYTHON, ['serve/server.py', '--engine', 'strata', '--config', config, '--port', String(PORT), '--no-api-key', '--ready-file', join(OUT, 'ready.json')], { cwd: REPO, env: { ...process.env, LD_LIBRARY_PATH: `${lib}:${process.env.LD_LIBRARY_PATH ?? ''}`, STRATA_DATA_DIR: join(OUT, 'data'), PYTHONPATH: `${join(REPO, 'tools')}:${REPO}` }, stdio: ['ignore', 'pipe', 'pipe'], detached: true, @@ -107,7 +113,10 @@ async function turn(name, message, { thinking = 'Medium', mode = 'bypass', chatI mkdirSync(workspace, { recursive: true }); const frames = []; const t0 = Date.now(); + let timedOut = false; + const stopTimer = setTimeout(() => { timedOut = true; void bridge.stop(chatId).catch(() => {}); }, TURN_S * 1000); await bridge.runTurn({ chatId, message, workspacePath: workspace, mode, thinking, onFrame: f => frames.push({ at: Date.now() - t0, f }) }); + clearTimeout(stopTimer); const seconds = (Date.now() - t0) / 1000; const byType = {}; for (const { f } of frames) byType[f.type] = (byType[f.type] ?? 0) + 1; @@ -121,7 +130,8 @@ async function turn(name, message, { thinking = 'Medium', mode = 'bypass', chatI const drafts = frames.map(x => x.f).filter(f => f.type === 'agent-tool-draft').map(f => f.draft); const writes = drafts.filter(d => d.name === 'write' && d.bytes > 0); const draftStats = { frames: drafts.length, writeFrames: writes.length, lastWrite: writes.filter(d => !d.done).at(-1) ? { target: writes.filter(d => !d.done).at(-1).target, bytes: writes.filter(d => !d.done).at(-1).bytes, lines: writes.filter(d => !d.done).at(-1).lines } : null, previewSample: writes.filter(d => !d.done).at(-1)?.preview.slice(-80) ?? null }; - const summary = { name, seconds, cutNotes, draftStats, byType, done, error, files, cards: cards.map(c => ({ name: c.name, state: c.state, target: c.target })), prepareStatuses: prepare.length, firstPrepare: prepare[0] ?? null, lastPrepare: prepare.at(-1) ?? null, text: text.slice(-1200) }; + const writesDone = cards.filter(c => c.name === 'write' && c.state === 'done').length; + const summary = { name, seconds, timedOut, writesDone, cutNotes, draftStats, byType, done, error, files, cards: cards.map(c => ({ name: c.name, state: c.state, target: c.target })), prepareStatuses: prepare.length, firstPrepare: prepare[0] ?? null, lastPrepare: prepare.at(-1) ?? null, text: text.slice(-1200) }; writeFileSync(join(OUT, `turn-${name}.json`), JSON.stringify({ summary, frames: frames.slice(0, 4000) }, null, 1)); return { ...summary, frames, workspace }; } @@ -148,19 +158,37 @@ if (want('raw')) { note('raw: a reply cut inside a tool call reaches the client as pieces of the call and finish_reason length', finish === 'length' && name === 'write' && pieces > 5, `finish ${finish}; tool ${name}; ${pieces} call pieces, ${args.length} argument characters, closed JSON ${(() => { try { JSON.parse(args); return true; } catch { return false; } })()}; plain content ${JSON.stringify(content.slice(0, 80))}; ids ${ids.size}; usage ${JSON.stringify(usage)}`); } +if (want('mcp')) { + // Strata's own tool loop: the server runs the MCP tool itself. A call that finishes is run; a call the reply is cut inside is announced and never run. + const ask = async (content, max_tokens) => { + const res = await fetch(`${base}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model, stream: true, strata_mcp: true, max_tokens, temperature: 0.6, chat_template_kwargs: { enable_thinking: false }, messages: [{ role: 'user', content }] }) }); + const text = await res.text(); + const events = text.split(String.fromCharCode(10)).filter(l => l.startsWith('data: {')).map(l => JSON.parse(l.slice(6))); + const mcp = events.map(e => e.strata_mcp).filter(Boolean); + const finish = events.flatMap(e => e.choices ?? []).map(c => c.finish_reason).filter(Boolean).at(-1); + const said = events.flatMap(e => e.choices ?? []).map(c => c.delta?.content ?? '').join(''); + return { mcp, finish, said }; + }; + const ok = await ask('Use the fake__echo tool to echo the text "hello from the tool", then tell me what it returned.', 600); + note('mcp: a short call is run by the server and answered', ok.mcp.some(m => m.event === 'result' && m.ok) && ok.finish === 'stop', `events ${JSON.stringify(ok.mcp.map(m => m.event))}; finish ${ok.finish}; said ${JSON.stringify(ok.said.slice(-120))}`); + const cut = await ask('Use the fake__echo tool once. Its text must be the sentence "the quick brown fox jumps over the lazy dog" written out 300 times in a row, separated by spaces.', 300); + note('mcp: a call the reply is cut inside is announced and never run (#211), and the stream says length', cut.mcp.some(m => m.event === 'start') && !cut.mcp.some(m => m.event === 'call') && cut.finish === 'length', `events ${JSON.stringify(cut.mcp.map(m => m.event))}; finish ${cut.finish}; said ${JSON.stringify(cut.said.slice(0, 100))}`); +} + if (want('pagoda')) { const t = await turn('pagoda', 'Write me a 100 voxel pagoda in one html file with garden.'); const html = t.files.find(f => /\.html?$/i.test(f.name)); console.log(` pagoda: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, files ${JSON.stringify(t.files)}`); note('pagoda: a file was written or the turn says why not', !!html || /cut|too long|ran out|limit/i.test(t.text), `file ${html ? html.name + ' ' + html.bytes + ' B' : 'none'}; finish ${t.done?.finishReason}; text tail: ${JSON.stringify(t.text.slice(-240))}`); } -if (want('long')) { - const t = await turn('long', longPrompt, { thinking: 'Off' }); +if (want('long')) for (let rep = 1; rep <= REPEAT; rep++) { + const t = await turn(`long${rep}`, longPrompt, { thinking: 'Off' }); const f = t.files.find(x => x.name === 'big.txt'); const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0; - console.log(` long: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, draft ${JSON.stringify(t.draftStats)}, cut notes ${JSON.stringify(t.cutNotes)}`); - note(`long: big.txt written (${LINES} lines asked)`, lines >= LINES * 0.95 || t.cutNotes.length > 0 && !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}; tokens out ${t.done?.tokensOut}; cards ${JSON.stringify(t.cards.filter(c => c.state !== 'running').map(c => c.name))}; cut notes ${t.cutNotes.length}; draft frames ${t.draftStats.frames}`); - note('long: the turn did not end silently', !!f || t.cutNotes.length > 0 || t.text.trim().length > 0, `text tail ${JSON.stringify(t.text.slice(-160))}`); + console.log(` long${rep}: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, draft ${JSON.stringify(t.draftStats)}, cut notes ${JSON.stringify(t.cutNotes)}`); + note(`long${rep}: big.txt written (${LINES} lines asked)`, lines >= LINES * 0.95 || t.writesDone > 0 || t.cutNotes.length > 0 && !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}; tokens out ${t.done?.tokensOut}; cards ${JSON.stringify(t.cards.filter(c => c.state !== 'running').map(c => c.name))}; writes done ${t.writesDone}; cut notes ${t.cutNotes.length}; draft frames ${t.draftStats.frames}`); + note(`long${rep}: the turn did not end silently`, !!f || t.cutNotes.length > 0 || t.text.trim().length > 0, `text tail ${JSON.stringify(t.text.slice(-160))}`); } if (want('cut')) { diff --git a/apps/host/server/agent/reply-cut.mjs b/apps/host/server/agent/reply-cut.mjs index afcc52adb4..5cdd8c0e57 100644 --- a/apps/host/server/agent/reply-cut.mjs +++ b/apps/host/server/agent/reply-cut.mjs @@ -91,14 +91,15 @@ const withTokens = tokens => (tokens > 0 ? ` (${Number(tokens).toLocaleString('e export function cutNotice({ calls = [], tokens = 0, again = false, retrying = false } = {}) { const call = calls.find(c => c.target) ?? calls[0] ?? null; const file = call?.target ? String(call.target).split(/[\\/]/).filter(Boolean).at(-1) : ''; + const what = file || (/^(write|edit)$/.test(call?.name ?? '') ? 'a file' : call?.name); if (call && retrying) { - const key = 'That reply reached its length limit{0} while writing {1} ({2}), so nothing was saved. I asked the assistant to write it again in smaller parts.'; - const values = [withTokens(tokens), file || call.name, kb(call.bytes)]; + const key = 'That reply reached its length limit{0} while writing {1} ({2}), so that write did not happen. I asked the assistant to look at what is on disk and write the rest in smaller parts.'; + const values = [withTokens(tokens), what, kb(call.bytes)]; return { key, values, text: fill(key, values) }; } if (call) { - const key = 'The reply reached its length limit{0} while writing {1} ({2}), so nothing was saved. Say “continue” and it will write it again in smaller parts.'; - const values = [withTokens(tokens), file || call.name, kb(call.bytes)]; + const key = 'The reply reached its length limit{0} while writing {1} ({2}), so that write did not happen. Say “continue” and it will look at what is on disk and go on in smaller parts.'; + const values = [withTokens(tokens), what, kb(call.bytes)]; return { key, values, text: fill(key, values) }; } if (retrying) { @@ -118,5 +119,5 @@ export function cutNudge({ calls = [], tokens = 0 } = {}) { return 'Your last reply was cut off by the output limit before it was finished. Carry on from where it stopped without repeating what you already wrote, and keep your thinking short.'; } const file = call.target || 'the file'; - return `Your last reply was cut off by the output limit${tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''} while you were writing ${file} in one tool call, so nothing was saved. Do not make the same big call again. Write ${file} in several smaller parts: create it with the first part (about 150 lines or fewer), then add each next part with its own edit or append, and read the end of the file back at the end. Keep your thinking short.`; + return `Your last reply was cut off by the output limit${tokens > 0 ? ` (${Number(tokens).toLocaleString('en-US')} tokens)` : ''} while you were writing ${file} in one tool call, so that call did not run and nothing was changed by it. First look at what is on disk now (list the folder, read the end of the file). Do not delete or start over a file that is already complete. If it is not complete, write what is missing in several smaller parts (about 150 lines or fewer each) with edits or appends, and read the end of the file back when you are done. Keep your thinking short.`; } diff --git a/apps/host/tests/agent-lost.test.mjs b/apps/host/tests/agent-lost.test.mjs index c5c6fbbe7e..68b14f7534 100644 --- a/apps/host/tests/agent-lost.test.mjs +++ b/apps/host/tests/agent-lost.test.mjs @@ -61,11 +61,11 @@ test('the sentences name the file and the size, say what to do, and the nudge as const calls = cutCalls([draft]); assert.deepEqual(calls, [{ name: 'write', target: '/w/pagoda.html', bytes: 52_300 }]); const again = cutNotice({ calls, tokens: 19660, retrying: true }); - assert.match(again.text, /reached its length limit \(19,660 tokens\) while writing pagoda\.html \(52 KB\), so nothing was saved\. I asked the assistant to write it again in smaller parts\./); + assert.match(again.text, /reached its length limit \(19,660 tokens\) while writing pagoda\.html \(52 KB\), so that write did not happen\. I asked the assistant to look at what is on disk and write the rest in smaller parts\./); const last = cutNotice({ calls, tokens: 19660 }); assert.match(last.text, /Say “continue”/); assert.match(cutNotice({ tokens: 500 }).text, /^The reply reached its length limit \(500 tokens\) and was cut off\. Say “continue”/); - assert.match(cutNudge({ calls, tokens: 19660 }), /writing \/w\/pagoda\.html in one tool call, so nothing was saved[\s\S]*smaller parts/); + assert.match(cutNudge({ calls, tokens: 19660 }), /writing \/w\/pagoda\.html in one tool call, so that call did not run[\s\S]*Do not delete or start over a file that is already complete[\s\S]*smaller parts/); assert.match(cutNudge({}), /cut off by the output limit/); for (const n of [again, last]) assert.equal(n.text, n.key.replace(/\{(\d)\}/g, (_, i) => n.values[i]), 'the key and its values make the sentence'); }); @@ -153,7 +153,7 @@ test('a reply cut inside a file write: the chat says so, the agent is asked to g await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:cutwrite big.txt' }); const said = out.find(f => f.type === 'delta' && f.noteReason === 'cut'); assert.ok(said, 'a sentence about the cut'); - assert.match(said.text, /while writing big\.txt/); assert.match(said.text, /I asked the assistant to write it again in smaller parts/); + assert.match(said.text, /while writing big\.txt/); assert.match(said.text, /that write did not happen. I asked the assistant to look at what is on disk and write the rest in smaller parts/); assert.equal(out.filter(f => f.type === 'error').length, 0); const done = out.filter(f => f.type === 'done').at(-1); assert.equal(done.finishReason, 'stop', 'the turn ends on the agent\'s own finish, not on the cut'); @@ -176,7 +176,7 @@ test(`a model that is cut every time is asked ${MAX_CUT_RETRIES} times, then the assert.equal(writes(r).length, MAX_CUT_RETRIES + 1); const notes = out.filter(f => f.type === 'delta' && f.noteReason === 'cut'); assert.equal(notes.length, MAX_CUT_RETRIES + 1, 'one sentence per cut'); - assert.match(notes.at(-1).text, /nothing was saved\. Say “continue”/); + assert.match(notes.at(-1).text, /that write did not happen\. Say “continue”/); const done = out.filter(f => f.type === 'done').at(-1); assert.ok(done, 'the turn ended'); assert.equal(done.finishReason, 'length'); From 85dd085241c496a619bf8ed4c79eab88ebc91596 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:18:48 +0100 Subject: [PATCH 52/59] Add the ISTA-DAS Coder set (192 experts a layer): one JSON for the repository, setup recipe, fit numbers, menu rows, Mac note, tests --- apps/host/src/lib/native-catalog.ts | 2 +- data/dsv41/coder-set.json | 41 ++++ setup.py | 65 +++++- strata_cli/launch/catalog.py | 1 + strata_cli/launch/runner.py | 8 +- strata_control/dsv41_fit.py | 93 ++++++--- strata_control/dsv41_sets.py | 11 +- tests/terminal/test_dsv41_import_preview.py | 4 +- tests/terminal/test_launch.py | 4 +- tests/terminal/test_launch_dsv41.py | 6 +- tools/dsv41/pin_coder.py | 210 +++++++++++++++++++ tools/test_setup_coder.py | 220 ++++++++++++++++++++ tools/test_setup_dsv41.py | 6 +- tools/test_strata_mcp.py | 9 +- 14 files changed, 630 insertions(+), 50 deletions(-) create mode 100644 data/dsv41/coder-set.json create mode 100644 tools/dsv41/pin_coder.py create mode 100644 tools/test_setup_coder.py diff --git a/apps/host/src/lib/native-catalog.ts b/apps/host/src/lib/native-catalog.ts index 30ae29b559..5b7fc8ecba 100644 --- a/apps/host/src/lib/native-catalog.ts +++ b/apps/host/src/lib/native-catalog.ts @@ -3,7 +3,7 @@ import {tr} from './i18n'; import {nvfp4Version} from './native-names'; export interface CatalogVersion extends NativeSize{sourceFamily:string;edition:string;images:boolean} export interface CatalogModel extends Omit<NativeFamily,'sizes'>{sizes:CatalogVersion[]} -export function nativeVersionLabel(model:string){const nv=nvfp4Version(model);if(nv)return tr(nv.name);return tr(({Q2_0:'Fastest',IQ2_XS:'Compact',IQ3_XXS:'Balanced',IQ3_S:'High quality',IQ1_M:'Coding','Gyro-S':'Smallest','Gyro-M':'Small memory','IST-DAS-1.75bpw':'Smallest','IST-DAS-2.00bpw':'Balanced','IST-DAS-2.25bpw':'Best quality'} as Record<string,string>)[model]??model);} +export function nativeVersionLabel(model:string){const nv=nvfp4Version(model);if(nv)return tr(nv.name);return tr(({Q2_0:'Fastest',IQ2_XS:'Compact',IQ3_XXS:'Balanced',IQ3_S:'High quality',IQ1_M:'Coding','Gyro-S':'Smallest','Gyro-M':'Small memory','IST-DAS-1.75bpw':'Smallest','IST-DAS-2.00bpw':'Balanced','IST-DAS-2.25bpw':'Best quality','ISTA-DAS-Coder':'ISTA-DAS Coder'} as Record<string,string>)[model]??model);} export const catalogVersionLabel=(version:CatalogVersion)=>{const label=nativeVersionLabel(version.model);return [tr(version.edition),label===version.model&&version.edition?'':label].filter(Boolean).join(' · ');}; /** The one line that says how a version differs from its neighbours (the three NVFP4 versions); empty for the rest. */ export const versionNote=(model:string)=>{const nv=nvfp4Version(model);return nv?tr(nv.note):'';}; diff --git a/data/dsv41/coder-set.json b/data/dsv41/coder-set.json new file mode 100644 index 0000000000..3b9d0df331 --- /dev/null +++ b/data/dsv41/coder-set.json @@ -0,0 +1,41 @@ +{ + "name": "ISTA-DAS-Coder", + "label": "ISTA-DAS Coder", + "repo": "helcig/tmp-oct26-4", + "revision": "31b7f2dcd5aa5824423a75da9807f617d15c3017", + "pinned_from": "2026-11-01T15:51:03.000Z", + "license_in_metadata": "mit", + "experts_per_layer": 192, + "layers": 40, + "experts_used": 6, + "shards": [ + "model-00001-of-00004.gguf", + "model-00002-of-00004.gguf", + "model-00003-of-00004.gguf" + ], + "engram_shard": "model-00004-of-00004.gguf", + "mmproj": "mmproj-BF16.gguf", + "profile": "profile-coder.bin", + "files": { + "model-00001-of-00004.gguf": [ + 5779840, + "ebfd9c38fbd7c3221b4817138eb2ff2f1ad75e48af9a576a8aa0bcba7ecbd21c" + ], + "model-00002-of-00004.gguf": [ + 39716054528, + "c8dc2ce2ac96970ba6cde7aa6f4f1c6380f39ccc0b33e7ef3c3baeaee5a820cb" + ], + "model-00003-of-00004.gguf": [ + 32401731968, + "4b04342749ac37b3388c3c803af151838c5c07b188b23a579ed95a65522e6f30" + ], + "model-00004-of-00004.gguf": [ + 110595290592, + "94ceeb431d894366b8ab207b2aaa3291c2b7d570163984862333a4264faefb1a" + ], + "mmproj-BF16.gguf": [ + 972207968, + "a7cdd95589d0b58fdab59263b700657364520667e06f40b1f3828f0f206ba609" + ] + } +} diff --git a/setup.py b/setup.py index 7bbf755261..131f263719 100644 --- a/setup.py +++ b/setup.py @@ -194,6 +194,8 @@ def source_hint(url: str) -> str: def model_alias(name: str) -> str: """The set is named ISTA-DAS on screen; its ids keep the first spelling (--model IST-DAS-2.25bpw), and the new one is accepted too.""" + if isinstance(name, str) and re.fullmatch(r"(?i)ista?-das-coder", name): + return DSV41_CODER_MODEL # (the Coder has only ever had the longer spelling; the shorter one is accepted) return re.sub(r"(?i)^ista-das(?=-\d)", "IST-DAS", name) if isinstance(name, str) else name @@ -803,7 +805,33 @@ DSV41_UD_FILES = { "DeepSeek-V4.1-Flash-1017-UD-IQ1_S-00005-of-00005.gguf": (110595290592, "771805301e695d72d268151dfc43043581ba904298574aa879d4349cbe67b020"), } DSV41_FILES.update(DSV41_UD_FILES) # (the repository's pins: REPO_PINS) -DSV41_ALL_FILES = {**DSV41_FILES, **DSV41_ISTA_FILES, **DSV41_ISTA6_FILES, **DSV41_LEGACY_FILES, **DSV41_UD_FILES} +# The ISTA-DAS Coder (2026-11-01): ISTA-DAS's coding variant of this model, "the layout of the IQ2_XXS set with half of the experts removed": 192 routed experts a layer +# instead of 384 (the router, the experts and the routing biases are narrower; every other tensor has the 2.00 set's name, shape and type). Four files: shard 1 = the metadata, +# shards 2-3 = the model, shard 4 = the Engram table (the same single tensor as ISTA-DAS's Engram file), and a picture file (mmproj-BF16.gguf). Its repository id, commit, file +# names, sizes and SHA-256 are in ONE place, data/dsv41/coder-set.json, written by tools/dsv41/pin_coder.py from the Hub: a new repository is `pin_coder.py NEW/REPO` and +# nothing else (strata_control/dsv41_fit.py and the app read the same file). The repository's name was a temporary one when this was pinned. +DSV41_CODER_JSON = ROOT / "data" / "dsv41" / "coder-set.json" +try: + DSV41_CODER = json.loads(DSV41_CODER_JSON.read_text(encoding="utf-8")) +except (OSError, ValueError): + DSV41_CODER = {} # a checkout or a package without the file: the set is simply not offered +DSV41_CODER_REPO = DSV41_CODER.get("repo", "") +DSV41_CODER_FILES = {n: (int(v[0]), str(v[1])) for n, v in (DSV41_CODER.get("files") or {}).items()} +DSV41_CODER_MODEL = DSV41_CODER.get("name", "ISTA-DAS-Coder") +if DSV41_CODER_REPO: + HF_REVISIONS[DSV41_CODER_REPO] = DSV41_CODER["revision"] +# the Coder repository's own picture file has Unsloth's tensors under another header (and so another size and SHA-256): a copy of it already here is accepted as the shared +# picture file (find_shared / verify_sha256), and nothing is fetched under its name +DSV41_ALT_FILES = {DSV41_MMPROJ: [DSV41_CODER_FILES[DSV41_CODER["mmproj"]]]} if DSV41_CODER_REPO else {} +DSV41_ALL_FILES = {**DSV41_FILES, **DSV41_ISTA_FILES, **DSV41_ISTA6_FILES, **DSV41_LEGACY_FILES, **DSV41_UD_FILES, + **{n: v for n, v in DSV41_CODER_FILES.items() if n != DSV41_CODER.get("mmproj")}} + + +def dsv41_also(name: str) -> tuple: + """The other SHA-256 values that are the same file as `name` (DSV41_SHA_ALSO) and the other published copies of it (DSV41_ALT_FILES).""" + return (*DSV41_SHA_ALSO.get(name, ()), *(v[1] for v in DSV41_ALT_FILES.get(name, ()))) + + DSV41_PROFILES = ROOT / "data" / "dsv41" # the shipped hot-expert profiles (profile-2.00.bin, profile-2.25.bin, + .sha256) DSV41_MAC_CONTEXT = 8192 # DeepSeek on a Mac keeps the 8K it was run at (the owner's 128K decision is for cards; nothing was run on a Mac at 128K) DSV41_CONTEXT = 131072 # 128K like every model (owner, 2026-11-01; strata_control/default_context.py); the engine was checked at 4096 and 8192 before, INT3 checks 128K on real cards @@ -847,6 +875,15 @@ MULTI_FILE_FAMILIES["deepseek41"]["models"] = { "shards": [DSV41_ISTA_SHARD.format(quant="IQ1_M", i=i) for i in range(1, 5)], "shards6": [DSV41_ISTA6_SHARD.format(quant="IQ1_M", i=i) for i in range(1, DSV41_ISTA6_SHARDS + 1)], "shared": [DSV41_ISTA_ENGRAM, DSV41_SHARD.format(i=1), DSV41_DSPARK]}, + **({DSV41_CODER_MODEL: { + "label": DSV41_CODER.get("label", "ISTA-DAS Coder"), + "about": "ISTA-DAS's coding version of DeepSeek-V4.1-Flash: %d of the model's 384 experts in every layer are kept, the rest removed, with the 2.00 version's file layout and " + "tensor types: %.0f GB of model + 111 GB n-gram table + 8 GB drafter (about %.0f GB of disk). Not run on a Mac or a Ryzen AI Max yet. Its quality is not measured " + "against the original model yet" % (DSV41_CODER["experts_per_layer"], sum(DSV41_CODER_FILES[n][0] for n in DSV41_CODER["shards"]) / 1e9, + (sum(DSV41_CODER_FILES[n][0] for n in DSV41_CODER["shards"]) + 110_595_290_816 + 7_976_914_240) / 1e9 + 6), + "ram_gb": 24, "recipe": "coder", "subdir": None, "legacy_subdir": None, "profile": DSV41_CODER.get("profile", "profile-coder.bin"), "hf": hf(DSV41_CODER_REPO), + "shards": list(DSV41_CODER["shards"]), "engram_shard": DSV41_CODER["engram_shard"], "experts": DSV41_CODER["experts_per_layer"], "generic_names": True, + "shared": [DSV41_ISTA_ENGRAM, DSV41_DSPARK]}} if DSV41_CODER_REPO else {}), "UD-IQ1_S": { "label": "Unsloth UD-IQ1_S", "about": "Unsloth's smallest dynamic version: 122 GB of model (experts in IQ1_S / IQ2_XXS, attention in Q6_K) + the 111 GB n-gram table + 8 GB drafter. Same size class as ISTA-DAS 1.75 bpw. A 1-bit version: expect weaker answers than the 2.00 and 2.25 versions on long, detailed or careful work (short answers, code and tool calls looked fine in our check; its quality is not measured against the original yet). Pick 2.00 or 2.25 if they fit", @@ -8430,13 +8467,23 @@ def dsv41_find_shared(a, name: str, folder: Path, shared: Path, alt: tuple = ()) for n in names: f = k / n try: - if f.is_file() and f.stat().st_size == DSV41_ALL_FILES[n][0]: + if f.is_file() and f.stat().st_size in (DSV41_ALL_FILES[n][0], *(v[0] for v in DSV41_ALT_FILES.get(n, ()))): return f except OSError: pass return shared / name +def dsv41_pin_of(f: Path, pin: tuple) -> tuple: + """The (bytes, sha256) a shared file is checked against: the pinned one, or the other published copy of the same file (DSV41_ALT_FILES: the Coder repository's + picture file) when that is the size it has.""" + try: + size = f.stat().st_size + except OSError: + return pin + return next((p for p in (pin, *DSV41_ALT_FILES.get(f.name, ())) if p[0] == size), pin) + + def dsv41_pack_has_tower(pack: Path) -> bool: """Does the pack carry the vision tower (pack_gguf.py writes vision.* and image_token_id into ds4.txt when it found the mmproj)?""" try: @@ -8629,9 +8676,11 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, say(" Its GGUF files: " + ("ISTA-DAS / ISTA-DASLab (huggingface.co/ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF), with the DSpark drafter and a small metadata file from Unsloth" if md.get("recipe") == "ista" else "Unsloth (huggingface.co/unsloth/DeepSeek-V4.1-Flash-1017-GGUF); the Engram table is the same data as ISTA-DAS's, so a copy of it already here is used" - if md.get("recipe") == "udlow" else "Unsloth (huggingface.co/unsloth/DeepSeek-V4.1-Flash-1017-GGUF)")) - udlow = md.get("recipe") == "udlow" # Unsloth's UD-IQ1_S / UD-IQ1_M: packed and checked like the ISTA-DAS sets; shard 5 is the Engram - ista = md.get("recipe") in ("ista", "udlow") + if md.get("recipe") == "udlow" else + f"{DSV41_CODER_REPO} (huggingface.co); its last file is the Engram table, the same data as ISTA-DAS's, so a copy of it already here is used" + if md.get("recipe") == "coder" else "Unsloth (huggingface.co/unsloth/DeepSeek-V4.1-Flash-1017-GGUF)")) + udlow = md.get("recipe") in ("udlow", "coder") # Unsloth's UD-IQ1_S / UD-IQ1_M and the ISTA-DAS Coder: packed and checked like the ISTA-DAS sets; the set's last file is the Engram + ista = md.get("recipe") in ("ista", "udlow", "coder") tag = fam["tag"] + model named = cards_named(a, hip) cards = dsv41_cards(gpu, all_cards, named) @@ -8676,7 +8725,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, say(" Nothing to download: the files are already here.") unchecked = [f for f in [*shards, *shared] if f.exists() and not any( f"sha256 {x}" in (mark_text(f) or "") - for x in (fam['sha256'][f.name][1], *DSV41_SHA_ALSO.get(f.name, ())))] + for x in (fam['sha256'][f.name][1], *dsv41_also(f.name)))] if unchecked: gb = sum(fam["sha256"][f.name][0] for f in unchecked) / 1e9 say(f" The files already here ({gb:.0f} GB) are checked against their SHA-256 once, now: about {max(1, round(gb / 55))} minutes on a fast " @@ -8777,7 +8826,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, ok(f"{f.name} already here ({f.parent})") else: download(DSV41_SHARED[f.name] + f.name, f) - verify_sha256(f, *fam["sha256"][f.name], own=own_files[f], also=DSV41_SHA_ALSO.get(f.name, ())) + verify_sha256(f, *dsv41_pin_of(f, fam["sha256"][f.name]), own=own_files[f], also=dsv41_also(f.name)) ok(f"model files: {folder} ({len(shards)} shards" + (f"; shared files: {shared_dir if any(not own_files[f] for f in shared) else shared[0].parent}" if shared else "") + ")") step(6, "preparing the model for Strata") @@ -8845,7 +8894,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, # A Mac (0.2.7.1): the drafter is not loaded at all (--dspark none). It was exact there but not faster (15.1 and 11.0 tokens/s against 15.3 # without it on the M5 Max), and the engine's "auto" would load it on a 128 GB Mac: its 7 GB of experts take memory the trunk's experts need. args = ["--pack", str(pack), "--max-context", str(ctx), "--eos", "1", "--vision", ds_vision, "--dspark", "none" if mac else "auto", - *(["--dspark-conf", "0.65"] if md.get("recipe") == "ista" and not mac else []), *dsv41_prefill_chunk_args(cards, ram), + *(["--dspark-conf", "0.65"] if md.get("recipe") in ("ista", "coder") and not mac else []), *dsv41_prefill_chunk_args(cards, ram), *plan["args"]] env = dsv41_config_env(cards) cfg = {"exe": str(exe), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), diff --git a/strata_cli/launch/catalog.py b/strata_cli/launch/catalog.py index 1430516b90..fac8c9422e 100644 --- a/strata_cli/launch/catalog.py +++ b/strata_cli/launch/catalog.py @@ -394,6 +394,7 @@ class Catalog: names += [m for m in self.strata.sizes_of(models, fam_name) if m not in names] import re wanted = re.sub(r"(?i)^ista-das(?=-\d)", "IST-DAS", model) # the set's name on screen is ISTA-DAS; its ids keep the first spelling + wanted = re.sub(r"(?i)^ist-das(?=-coder$)", "ISTA-DAS", wanted) # (the Coder has only the longer spelling; the shorter one is accepted) match = next((n for n in names if n.lower() == wanted.lower()), None) if match is None: near = S.closest(model, names) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 42f525a6c0..a133e1b0da 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -1403,7 +1403,13 @@ class Runner: subs = [d.get("subdir"), d.get("legacy_subdir"), m] folders = [p, *[p / x for x in subs if x]] if p.is_dir() else [p.parent] names = [n for s in d["shards"] for n in (s, legacy.get(s)) if n] + list(d.get("shards6") or []) # (+ the six-shard layout of 2026-10-27) - folder = next((f for f in folders if any((f / n).exists() for n in names)), None) + sizes = getattr(mod, "DSV41_ALL_FILES", {}) + + def there(f, n): # a set whose files have generic names (model-00002-of-00004.gguf: the ISTA-DAS Coder's) is only claimed by files of the pinned size + if not (f / n).exists(): + return False + return not d.get("generic_names") or ((f / n).is_file() and n in sizes and (f / n).stat().st_size == sizes[n][0]) + folder = next((f for f in folders if any(there(f, n) for n in names)), None) if folder is not None: return m, d, folder return None diff --git a/strata_control/dsv41_fit.py b/strata_control/dsv41_fit.py index 853f9df3f8..a244acc101 100644 --- a/strata_control/dsv41_fit.py +++ b/strata_control/dsv41_fit.py @@ -85,6 +85,30 @@ ISTA_SETS["UD-IQ1_S"] = {"title": "Unsloth UD-IQ1_S", "set_bytes": 122_384_317_8 ISTA_SETS["UD-IQ1_M"] = {"title": "Unsloth UD-IQ1_M", "set_bytes": 139_809_056_132, "experts_gb": 132.21, "profile": "profile-2.00.bin", "meta_bytes": 0, "ppl": "?", "ram_ok_gb": 40.0, "disk_total": 258.0, "quality": "Unsloth's next dynamic version, the size of ISTA-DAS 2.00 bpw; not measured here yet"} +# The ISTA-DAS Coder (2026-11-01): ISTA-DAS's coding variant, "the layout of the IQ2_XXS set with experts removed": 192 routed experts a layer instead of 384 (read from the header of its +# shards: the experts, the router and the routing biases are half as wide; every other tensor is the 2.00 set's). Where the repository, the commit and the files are is ONE +# file, data/dsv41/coder-set.json (tools/dsv41/pin_coder.py writes it); the sizes here come from it. Shard 1 = the metadata, shards 2-3 = the model, shard 4 = the Engram +# (the same single IQ4_NL tensor as ISTA-DAS's Engram file, so it is shared with them). The tensors' bytes (from their offsets): experts 66.04 GB (7,680 of 8.60 MB, exactly half +# of 2.00's 132.07 GB), the other weights 6.08 GB. +def coder_set() -> dict | None: + """data/dsv41/coder-set.json as a dict, None when this checkout or package does not have it (the set is then not offered).""" + import json + from pathlib import Path + try: + return json.loads((Path(__file__).resolve().parents[1] / "data" / "dsv41" / "coder-set.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + + +CODER = coder_set() +CODER_MODEL = (CODER or {}).get("name", "ISTA-DAS-Coder") +if CODER: + _coder_bytes = sum(int(CODER["files"][n][0]) for n in CODER["shards"]) + ISTA_SETS[CODER_MODEL] = { + "title": CODER.get("label", "ISTA-DAS Coder"), "set_bytes": _coder_bytes, "experts_gb": 66.04, "dense_gb": 6.08, "profile": CODER.get("profile", "profile-coder.bin"), + "meta_bytes": 0, "experts_per_layer": int(CODER["experts_per_layer"]), "ppl": "?", "ram_ok_gb": 24.0, "measured": "", + "disk_total": round((_coder_bytes + ISTA_ENGRAM_BYTES + ISTA_DSPARK_BYTES) / GB), + "quality": "ISTA-DAS's coding version, half of the model's experts removed (192 of 384 in every layer); not measured against the original model here yet"} ISTA_DENSE_GB = 6.16 # the dense weights in the shards (attention, router, shared experts, the head; the embedding stays on the CPU) ISTA_DENSE_ON_GPU_GB = 4.5 # (the old plan's figure, kept for the Unsloth Q8 plan above; the official sets use the measured ones below) # What the engine really puts on a card, from its own startup line ("CUDA0 layers [0, 39] + head: weights 5.86 GB, experts 25.29 GB (2566 of 15360 in @@ -99,7 +123,7 @@ ISTA_DENSE_ON_GPU_GB = 4.5 # (the old plan's figure, kept for the Uns # card cannot hold are read in place and the prompt chunk is 32768 with the borrowed slots; the 8192 chunk of the older engine took 4.5 GB and # the card held 2,366); NVIDIA and others 3.6 GB (2 x A6000 3.7, an A4000 3.5; not tied to the chunk) # and the experts that stay on a card are a little bigger than the set's average (the hot ones: 9.86-10.0 MB against 9.70 for 2.25 bpw): x1.025 -ISTA_DENSE_GPU_BASE_GB = {"IST-DAS-2.00bpw": 5.62, "IST-DAS-2.25bpw": 5.62, "IST-DAS-1.75bpw": 5.62, "UD-IQ1_S": 6.34, "UD-IQ1_M": 7.37} +ISTA_DENSE_GPU_BASE_GB = {CODER_MODEL: 5.54, "IST-DAS-2.00bpw": 5.62, "IST-DAS-2.25bpw": 5.62, "IST-DAS-1.75bpw": 5.62, "UD-IQ1_S": 6.34, "UD-IQ1_M": 7.37} CARD_DENSE_REPEAT_GB = 0.24 ENGINE_FREE_GB = 0.62 CARD_OTHER_GB = {"amd": 1.60, "amd_low_share": 2.58, "other": 3.6} @@ -298,15 +322,19 @@ def _plan_ista(model: str, cards: list[dict] | None, ram_gb: float | None, disk_ expert the CPU lane keeps ("fits"), with 40 GB or more the engine's RAM store keeps the hot experts and reads the rest from the SSD ("tight": measured 4.7 tokens a second on 64 GB, 7.2 on 46 GB), under 40 GB it is untested and slower ("spills"). Never a refusal.""" v = variant(model) + epl = int(v.get("experts_per_layer", EXPERTS_PER_LAYER)) # a layer's routed experts (192 in the ISTA-DAS Coder) + n_experts = LAYERS * epl + dense_gb_v = float(v.get("dense_gb", ISTA_DENSE_GB)) + measured_v = v.get("measured", ISTA_MEASURED) keep, ignored = run_cards(cards, vendor, named=named) n = len(keep) - expert_gb = v["experts_gb"] / EXPERTS + expert_gb = v["experts_gb"] / n_experts set_gb = v["set_bytes"] / GB download = ista_download_bytes(model) / GB - out: dict[str, Any] = {"variant": model, "cards": [], "experts_total": EXPERTS, "experts_in_vram": 0, "vram_experts_gb": 0.0, + out: dict[str, Any] = {"variant": model, "cards": [], "experts_total": n_experts, "experts_in_vram": 0, "vram_experts_gb": 0.0, "cpu_experts_gb": v["experts_gb"], "weights_gb": _round1(set_gb), "experts_gb": _round1(v["experts_gb"]), - "dense_gb": _round1(ISTA_DENSE_GB), "engram_gb": _round1(ISTA_ENGRAM_BYTES / GB), "download_gb": _round1(download), - "tp": tp_for(n, keep), "args": [], "measured": ISTA_MEASURED, "lines": [], "warnings": [], "ram_gb": ram_gb, + "dense_gb": _round1(dense_gb_v), "engram_gb": _round1(ISTA_ENGRAM_BYTES / GB), "download_gb": _round1(download), + "tp": tp_for(n, keep), "args": [], "measured": measured_v, "lines": [], "warnings": [], "ram_gb": ram_gb, "context": context, "disk_total_gb": v["disk_total"]} need_disk = download + DISK_HEADROOM_GB out["disk_need_gb"] = _round1(need_disk) @@ -332,11 +360,11 @@ def _plan_ista(model: str, cards: list[dict] | None, ram_gb: float | None, disk_ counts = [] for room, (a, b) in zip(cap, ranges): gb = min(room, vram_exp * (room / sum(cap))) if sum(cap) else 0.0 - counts.append(min(int(gb / res_gb), (b - a + 1) * EXPERTS_PER_LAYER)) + counts.append(min(int(gb / res_gb), (b - a + 1) * epl)) return cap, counts cap, counts = place(CARD_OTHER_GB["amd"] if amd else CARD_OTHER_GB["other"]) - if amd and sum(counts) < EXPERTS / 2: # cards that hold under half of the experts: the engine's larger prompt buffers + if amd and sum(counts) < n_experts / 2: # cards that hold under half of the experts: the engine's larger prompt buffers cap, counts = place(CARD_OTHER_GB["amd_low_share"]) in_vram = 0 for c, ne, (a, b) in zip(keep, counts, ranges): @@ -349,8 +377,8 @@ def _plan_ista(model: str, cards: list[dict] | None, ram_gb: float | None, disk_ out["tp"] = tp_for(n, keep) out["args"] = _tp_args(n, out["tp"]) names = " + ".join(f"{c['name'] or 'card ' + str(c['index'])} ({c['vram_gb']:.0f} GB)" for c in out["cards"]) - lines.append(f"Graphics memory: {names}. About {in_vram:,} of the {EXPERTS:,} experts ({out['vram_experts_gb']:.0f} GB) stay on " - f"the card{'s' if n > 1 else ''}; the other {EXPERTS - in_vram:,} ({out['cpu_experts_gb']:.0f} GB) are computed on the " + lines.append(f"Graphics memory: {names}. About {in_vram:,} of the {n_experts:,} experts ({out['vram_experts_gb']:.0f} GB) stay on " + f"the card{'s' if n > 1 else ''}; the other {n_experts - in_vram:,} ({out['cpu_experts_gb']:.0f} GB) are computed on the " "CPU from RAM, and the ones RAM cannot hold are read from the SSD when a word needs them.") if n >= 2 and out["tp"] == 2: lines.append("Two cards share each layer's matrices (--tp 2): measured about twice as fast at reading prompts.") @@ -380,7 +408,10 @@ def _plan_ista(model: str, cards: list[dict] | None, ram_gb: float | None, disk_ f"({float(short[0].get('vram_gb') or 0):.0f} GB) has hardly that: the engine may stop at the start. It is still allowed.") if ignored: lines.append("Not used: " + "; ".join(f"{c.get('name') or 'a card'} ({c.get('why_ignored')})" for c in ignored) + ".") - lines.append("Measured on " + ISTA_MEASURED + ". Other computers are slower or faster by what their cards, RAM and drive can do.") + if measured_v: + lines.append("Measured on " + measured_v + ". Other computers are slower or faster by what their cards, RAM and drive can do.") + else: + lines.append("This version has not been timed on a computer like this one yet; the sizes above are exact.") if disk_free_gb is not None and disk_free_gb < need_disk: warns.append(f"The download needs about {need_disk:.0f} GB of free disk space and {disk_free_gb:.0f} GB are free where the files go. " "Use --models-dir on a bigger drive, or --gguf-dir for files you already have.") @@ -393,27 +424,31 @@ def _plan_uma(key: str, model: str, card: dict, ram_gb: float | None, disk_free_ counted once. The engine holds what fits beside the dense weights and the reserve and reads the rest from the SSD; the numbers in UMA_MEASURED are the measured 64 GB box. Never a refusal.""" v = ISTA_SETS[key] + epl = int(v.get("experts_per_layer", EXPERTS_PER_LAYER)) # a layer's routed experts (192 in the ISTA-DAS Coder) + n_experts = LAYERS * epl + dense_gb_v = float(v.get("dense_gb", ISTA_DENSE_GB)) + measured_v = v.get("measured", ISTA_MEASURED) total = uma_total_gb(card, ram_gb) - expert_gb = v["experts_gb"] / EXPERTS + expert_gb = v["experts_gb"] / n_experts set_gb = v["set_bytes"] / GB download = ista_download_bytes(model) / GB - room = max(0.0, total - ISTA_DENSE_GB - UMA_RESERVE_GB) + room = max(0.0, total - dense_gb_v - UMA_RESERVE_GB) resident = min(float(v["experts_gb"]), room) streamed = max(0.0, float(v["experts_gb"]) - room) in_mem = int(resident / expert_gb) need_disk = download + DISK_HEADROOM_GB out: dict[str, Any] = { "variant": model, "cards": [{"index": card.get("index"), "name": card.get("name"), "vram_gb": _round1(total), - "layers": [0, LAYERS - 1], "dense_gb": _round1(ISTA_DENSE_GB), + "layers": [0, LAYERS - 1], "dense_gb": _round1(dense_gb_v), "experts_gb": _round1(resident), "experts": in_mem}], - "experts_total": EXPERTS, "experts_in_vram": in_mem, "vram_experts_gb": _round1(resident), "cpu_experts_gb": 0.0, - "weights_gb": _round1(set_gb), "experts_gb": _round1(v["experts_gb"]), "dense_gb": _round1(ISTA_DENSE_GB), + "experts_total": n_experts, "experts_in_vram": in_mem, "vram_experts_gb": _round1(resident), "cpu_experts_gb": 0.0, + "weights_gb": _round1(set_gb), "experts_gb": _round1(v["experts_gb"]), "dense_gb": _round1(dense_gb_v), "engram_gb": _round1(ISTA_ENGRAM_BYTES / GB), "download_gb": _round1(download), "tp": 1, "args": [], "measured": UMA_MEASURED, "lines": [], "warnings": [], "ram_gb": ram_gb, "context": context, "disk_total_gb": v["disk_total"], "disk_need_gb": _round1(need_disk), "disk_ok": None if disk_free_gb is None else disk_free_gb >= need_disk, "uma": True, "streamed_gb": _round1(streamed), "ram_needed_gb": _round1(total), "spill_gb": _round1(streamed), - "spare_ram_gb": _round1(max(0.0, total - ISTA_DENSE_GB - v["experts_gb"] - UMA_RESERVE_GB)), + "spare_ram_gb": _round1(max(0.0, total - dense_gb_v - v["experts_gb"] - UMA_RESERVE_GB)), } lines, warns = out["lines"], out["warnings"] lines.append(f"DeepSeek-V4.1-Flash, {v['title']}: a {download:.0f} GB download ({set_gb:.0f} GB of model, " @@ -423,12 +458,12 @@ def _plan_uma(key: str, model: str, card: dict, ram_gb: float | None, disk_free_ name = card.get("name") or "the built-in Radeon" if float(card.get("dedicated_gb") or 0.0) > 0 or "GB10" not in str(card.get("name") or ""): lines.append(f"{name} shares this PC's memory: the RAM and the GPU's BIOS carve-out are one pool of {total:.0f} GB. About " - f"{resident:.0f} GB of the {float(v['experts_gb']):.0f} GB of experts stay in it beside {ISTA_DENSE_GB:.1f} GB of " + f"{resident:.0f} GB of the {float(v['experts_gb']):.0f} GB of experts stay in it beside {dense_gb_v:.1f} GB of " f"dense weights and {UMA_RESERVE_GB:.0f} GB kept for Windows; the other {streamed:.0f} GB are read from the SSD while it answers.") lines.append(f"Measured on this kind of PC: {UMA_MEASURED}.") else: # a DGX Spark's GB10: one memory for the CPU and the GPU, nothing set aside in a BIOS, Linux lines.append(f"{name} shares this computer's memory: the CPU and the GPU are one pool of {total:.0f} GB. About " - f"{resident:.0f} GB of the {float(v['experts_gb']):.0f} GB of experts stay in it beside {ISTA_DENSE_GB:.1f} GB of " + f"{resident:.0f} GB of the {float(v['experts_gb']):.0f} GB of experts stay in it beside {dense_gb_v:.1f} GB of " f"dense weights and {UMA_RESERVE_GB:.0f} GB kept for the system; the other {streamed:.0f} GB are read from the SSD while it answers.") lines.append(f"Measured on this kind of computer: {UMA_MEASURED_GB10}.") out["measured"] = UMA_MEASURED_GB10 @@ -614,6 +649,8 @@ MAC_PACKS: dict[str, dict[str, Any]] = { "IQ2_XS": {"name": "2.25 bpw (IQ2_XS), the quality one", "routed_gb": 149.06, "backbone_gb": 155.23, "bpw": 2.25}, "UD-IQ1_S": {"name": "Unsloth UD-IQ1_S (1-bit experts)", "routed_gb": 115.23, "backbone_gb": 122.38, "bpw": 1.75}, "UD-IQ1_M": {"name": "Unsloth UD-IQ1_M (1-bit experts)", "routed_gb": 132.21, "backbone_gb": 139.81, "bpw": 2.00}, + **({CODER_MODEL: {"name": f"{CODER.get('label', 'ISTA-DAS Coder')} (half of the experts removed)", "routed_gb": 66.04, + "backbone_gb": round(ISTA_SETS[CODER_MODEL]["set_bytes"] / GB, 2), "bpw": 2.00}} if CODER else {}), } MAC_ENGRAM_GB = 110.60 # the same Engram table for all three, read row by row off the SSD MAC_ENGINE_FOOTPRINT_GB = 12.0 # the process' anonymous memory after the load (Metal buffers, host buffers, the KV cache) @@ -633,6 +670,7 @@ MAC_MEASURED_PACK = { "UD-IQ1_S": ("M5 Max, 128 GB, Unsloth UD-IQ1_S: 15-18 tokens/s for a short answer (16-18 after a 3,000-token prompt), a 3,000-token prompt at " "about 230-310 tokens/s, 14,000 at about 520; the engine kept about 68 GB of the experts resident and the process used about 79 GB"), "UD-IQ1_M": "Not run on a Mac yet; UD-IQ1_S was. It keeps fewer experts in memory, so expect it to be slower.", + CODER_MODEL: "Not run on a Mac yet. It has 192 experts in a layer where the sets run there have 384, and the Metal engine was not tried with that.", } @@ -712,7 +750,8 @@ def mac_plan(ram_gb: float, quant: str = "IQ2_XS", disk_free_gb: float | None = # the 1.75 bpw set shares the 2.00 set's IQ1_M kernel but was never run there, so it is not offered on a Mac. -MAC_SET_PACK = {"IST-DAS-2.00bpw": "IQ2_XXS", "IST-DAS-2.25bpw": "IQ2_XS", "UD-IQ1_S": "UD-IQ1_S", "UD-IQ1_M": "UD-IQ1_M"} +MAC_SET_PACK = {"IST-DAS-2.00bpw": "IQ2_XXS", "IST-DAS-2.25bpw": "IQ2_XS", "UD-IQ1_S": "UD-IQ1_S", "UD-IQ1_M": "UD-IQ1_M", + **({CODER_MODEL: CODER_MODEL} if CODER else {})} # Unsloth's UD-IQ1_S was run on an M5 Max (f-039-mac-dsu). UD-IQ1_M has the same kernels and was not run there; the owner chose to offer it anyway ("they # will tell if it works"), with a plain "not run yet" line in its plan. The gate stays as a mechanism, empty: put a name here to keep a set off a Mac # (the model lists, setup, the launch and the "I already have the model" check all read it through not_here()). @@ -745,9 +784,13 @@ def _plan_mac(key: str, model: str, card: dict, ram_gb: float | None, disk_free_ beside the dense weights resident (mac_expert_cap_gb) and reads the rest from the SSD in place. Never a refusal: a smaller Mac gets a plain warning, not a block.""" v = ISTA_SETS[key] + epl = int(v.get("experts_per_layer", EXPERTS_PER_LAYER)) # a layer's routed experts (192 in the ISTA-DAS Coder) + n_experts = LAYERS * epl + dense_gb_v = float(v.get("dense_gb", ISTA_DENSE_GB)) + measured_v = v.get("measured", ISTA_MEASURED) ram = float(ram_gb or card.get("unified_gb") or 0.0) mp = mac_plan(ram, MAC_SET_PACK[key], disk_free_gb) - expert_gb = v["experts_gb"] / EXPERTS + expert_gb = v["experts_gb"] / n_experts resident = float(mp["resident_gb"]) streamed = float(mp["streaming_gb"]) in_mem = int(resident / expert_gb) @@ -757,15 +800,15 @@ def _plan_mac(key: str, model: str, card: dict, ram_gb: float | None, disk_free_ out: dict[str, Any] = { "variant": model, "mac": True, "mac_verdict": mp["verdict"], "cards": [{"index": card.get("index", 0), "name": card.get("name") or "Apple Silicon", "vram_gb": _round1(ram), - "layers": [0, LAYERS - 1], "dense_gb": _round1(ISTA_DENSE_GB), "experts_gb": _round1(resident), "experts": in_mem}], - "experts_total": EXPERTS, "experts_in_vram": in_mem, "vram_experts_gb": _round1(resident), "cpu_experts_gb": 0.0, - "weights_gb": _round1(v["set_bytes"] / GB), "experts_gb": _round1(v["experts_gb"]), "dense_gb": _round1(ISTA_DENSE_GB), + "layers": [0, LAYERS - 1], "dense_gb": _round1(dense_gb_v), "experts_gb": _round1(resident), "experts": in_mem}], + "experts_total": n_experts, "experts_in_vram": in_mem, "vram_experts_gb": _round1(resident), "cpu_experts_gb": 0.0, + "weights_gb": _round1(v["set_bytes"] / GB), "experts_gb": _round1(v["experts_gb"]), "dense_gb": _round1(dense_gb_v), "engram_gb": _round1(ISTA_ENGRAM_BYTES / GB), "download_gb": _round1(download), "tp": 1, "args": [], "measured": MAC_MEASURED, "lines": [], "warnings": [], "ram_gb": ram_gb, "context": context, "disk_total_gb": v["disk_total"], "disk_need_gb": _round1(need_disk), "disk_ok": None if disk_free_gb is None else disk_free_gb >= need_disk, - "streamed_gb": _round1(streamed), "ram_needed_gb": _round1(resident + ISTA_DENSE_GB + MAC_ENGINE_FOOTPRINT_GB), - "spill_gb": _round1(streamed), "spare_ram_gb": _round1(max(0.0, ram - resident - ISTA_DENSE_GB - MAC_ENGINE_FOOTPRINT_GB)), + "streamed_gb": _round1(streamed), "ram_needed_gb": _round1(resident + dense_gb_v + MAC_ENGINE_FOOTPRINT_GB), + "spill_gb": _round1(streamed), "spare_ram_gb": _round1(max(0.0, ram - resident - dense_gb_v - MAC_ENGINE_FOOTPRINT_GB)), "verdict": verdict, } lines, warns = out["lines"], out["warnings"] diff --git a/strata_control/dsv41_sets.py b/strata_control/dsv41_sets.py index e75a7ccb76..10650f9684 100644 --- a/strata_control/dsv41_sets.py +++ b/strata_control/dsv41_sets.py @@ -8,6 +8,9 @@ sizes alone: no tensor is read and no 40 GB file is hashed in a preview (setup c The tables are setup.py's own (read from it, never copied), so a new size added there is recognised here. +The ISTA-DAS Coder (setup.py DSV41_CODER, data/dsv41/coder-set.json) is one more set of the same kind: its metadata shard and two model shards under the repository's own generic names +(model-0000N-of-00004.gguf, matched by name AND size), its last file the Engram table. + Three kinds of files are the same set: the pinned four-shard files (and the first release's names), the four-shard files as ISTA-DASLab re-published their shard 1 on 2026-10-26 (a larger chat template: DSV41_NEW_SHARD1, what the Hub's last four-shard commit 653a9874 serves), and, since 0.2.8.1, ISTA-DASLab's six-shard layout of 2026-10-27 (DSV41_ISTA6_FILES). setup downloads only the first; it takes the other two from files already here. @@ -37,13 +40,13 @@ def tables() -> dict | None: new1, six = getattr(module, "DSV41_NEW_SHARD1", {}), getattr(module, "DSV41_ISTA6_FILES", {}) result: dict = {"sets": {}, "engram": {}} for model, entry in family["models"].items(): - if entry.get("recipe") not in ("ista", "udlow"): + if entry.get("recipe") not in ("ista", "udlow", "coder"): continue # Unsloth's 508 GB set is not an "already have it" case of the app - ista = {**ista, **getattr(module, "DSV41_UD_FILES", {})} + ista = {**ista, **getattr(module, "DSV41_UD_FILES", {}), **getattr(module, "DSV41_CODER_FILES", {})} shards = {name: ista[name][0] for name in entry["shards"]} old = {renamed[name]: legacy[renamed[name]][0] for name in entry["shards"] if name in renamed and renamed[name] in legacy} alt = entry.get("engram_shard") # Unsloth's UD-IQ1 sets: shard 5 is the Engram (the same data as ISTA-DAS's file) - result["sets"][model] = {"label": entry.get("label", model), "shards": shards, "legacy": old, + result["sets"][model] = {"label": entry.get("label", model), "shards": shards, "legacy": old, "generic": bool(entry.get("generic_names")), "engram_alt": {alt: ista[alt][0]} if alt else {}, "new1": {name: new1[name][0] for name in entry["shards"] if name in new1}, "six": {name: six[name][0] for name in entry.get("shards6") or [] if name in six}} @@ -77,6 +80,8 @@ def match(files: dict[str, int]) -> list[dict]: present = [n for n in pinned if n in files] if not present: continue + if entry.get("generic") and not any(files[n] in {pinned[n], *([entry["new1"][n]] if n in entry.get("new1", {}) else [])} for n in present): + continue # generic names (model-00002-of-00004.gguf): a file of another size is another model's, not a cut copy of this one ok_sizes = {n: {pinned[n], *([entry["new1"][n]] if layout == "four" and n in entry.get("new1", {}) else [])} for n in pinned} wrong = [n for n in present if files[n] not in ok_sizes[n]] missing = [n for n in pinned if n not in files] diff --git a/tests/terminal/test_dsv41_import_preview.py b/tests/terminal/test_dsv41_import_preview.py index f5dea641e3..ad729a6fd3 100644 --- a/tests/terminal/test_dsv41_import_preview.py +++ b/tests/terminal/test_dsv41_import_preview.py @@ -11,7 +11,7 @@ from strata_control import dsv41_sets, models T = dsv41_sets.tables() -ISTA = [m for m in T["sets"] if m.startswith("ISTA-DAS")] # the Unsloth UD-IQ1 sets have no legacy, six-shard or re-published layouts (tools/test_setup_udlow.py) +ISTA = [m for m in T["sets"] if m.startswith("IST-DAS-")] # the Unsloth UD-IQ1 sets have no legacy, six-shard or re-published layouts (tools/test_setup_udlow.py) def files_of(model, legacy=False, engram="official", drop=(), wrong=(), layout=None): entry = T["sets"][model] @@ -37,7 +37,7 @@ class DeepSeekPreview(unittest.TestCase): return models.plan_import(str(target)), folder def test_the_tables_come_from_setup_and_cover_the_three_official_sizes(self): - self.assertEqual(sorted(T["sets"]), ["IST-DAS-1.75bpw", "IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "UD-IQ1_M", "UD-IQ1_S"]) + self.assertEqual(sorted(T["sets"]), ["IST-DAS-1.75bpw", "IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "ISTA-DAS-Coder", "UD-IQ1_M", "UD-IQ1_S"]) self.assertEqual(len(T["engram"]), 2) def test_each_official_set_is_recognised_with_its_size_name(self): diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index a98bf33458..be10b15d37 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -110,7 +110,7 @@ class CatalogRules(unittest.TestCase): self.assertEqual(source, "setup.py") # the same tables setup.py and the app read for r in rows: if r.family == "deepseek41": # its sizes are in MULTI_FILE_FAMILIES (shards + shared files), not in MODELS - self.assertAlmostEqual(r.download_gb, {"UD-Q8_K_XL": 508.4, "IST-DAS-2.00bpw": 256.8, "IST-DAS-2.25bpw": 273.8, "IST-DAS-1.75bpw": 239.3, "UD-IQ1_S": 241.0, "UD-IQ1_M": 258.4}[r.model], delta=0.1) + self.assertAlmostEqual(r.download_gb, {"UD-Q8_K_XL": 508.4, "IST-DAS-2.00bpw": 256.8, "IST-DAS-2.25bpw": 273.8, "IST-DAS-1.75bpw": 239.3, "ISTA-DAS-Coder": 190.7, "UD-IQ1_S": 241.0, "UD-IQ1_M": 258.4}[r.model], delta=0.1) continue self.assertAlmostEqual(r.download_gb, models[r.model]["download_gb"]) rec = [r for r in rows if r.recommended] @@ -144,7 +144,7 @@ class CatalogRules(unittest.TestCase): with Home(): cat = catalog(hw) rows = {r.model: r for r in cat.rows()} - self.assertEqual(set(rows), {"Q2_0", "IQ3_XXS", "IQ3_S", "Gyro-S", "Gyro-M", "IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "UD-IQ1_S", "UD-IQ1_M"}) # DeepSeek (0.2.7.1): the two ISTA-DAS sets run on a Mac, UD-IQ1_S since f-039 + self.assertEqual(set(rows), {"Q2_0", "IQ3_XXS", "IQ3_S", "Gyro-S", "Gyro-M", "IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "ISTA-DAS-Coder", "UD-IQ1_S", "UD-IQ1_M"}) # DeepSeek (0.2.7.1): the two ISTA-DAS sets run on a Mac, UD-IQ1_S since f-039; the Coder and UD-IQ1_M are offered with a "not run yet" line self.assertEqual([r.model for r in rows.values() if r.recommended], ["Q2_0"]) for name in ("IST-DAS-2.00bpw", "IST-DAS-2.25bpw"): # a 32 GB Mac: said plainly (mostly read from the SSD), never refused self.assertEqual(rows[name].family, "deepseek41") diff --git a/tests/terminal/test_launch_dsv41.py b/tests/terminal/test_launch_dsv41.py index 2be9bb4fb4..8e9d6dffe8 100644 --- a/tests/terminal/test_launch_dsv41.py +++ b/tests/terminal/test_launch_dsv41.py @@ -36,11 +36,13 @@ class LaunchDeepSeek(unittest.TestCase): def test_the_model_is_in_the_list(self): rows = [r for r in catalog(self.hw).rows() if r.family == "deepseek41"] - self.assertEqual([r.model for r in rows], ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "IST-DAS-1.75bpw", "UD-IQ1_S", "UD-IQ1_M", "UD-Q8_K_XL"]) + self.assertEqual([r.model for r in rows], ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "IST-DAS-1.75bpw", "ISTA-DAS-Coder", "UD-IQ1_S", "UD-IQ1_M", "UD-Q8_K_XL"]) self.assertEqual([r.download_gb for r in rows[:3]], [256.8, 273.8, 239.3]) self.assertEqual(catalog(self.hw).resolve("ist-das-2.25bpw"), ("deepseek41", "IST-DAS-2.25bpw")) self.assertEqual(catalog(self.hw).resolve("ISTA-DAS-2.25bpw"), ("deepseek41", "IST-DAS-2.25bpw")) # the name on screen is accepted too - r = rows[5] + self.assertEqual(catalog(self.hw).resolve("ista-das-coder"), ("deepseek41", "ISTA-DAS-Coder")) + self.assertEqual(catalog(self.hw).resolve("IST-DAS-Coder"), ("deepseek41", "ISTA-DAS-Coder")) # (the shorter spelling the other ids have is accepted) + r = rows[-1] self.assertEqual((r.id, r.download_gb, r.verdict, r.images), ("deepseek-v4.1-flash-ud-q8_k_xl", 508.4, "fits", True)) # 0.2.7: pictures through the engine's own tower self.assertEqual(catalog(self.hw).resolve("ud-q8_k_xl"), ("deepseek41", "UD-Q8_K_XL")) self.assertEqual(catalog(self.hw).max_context("deepseek41", "UD-Q8_K_XL"), 131072) diff --git a/tools/dsv41/pin_coder.py b/tools/dsv41/pin_coder.py new file mode 100644 index 0000000000..1c6836b642 --- /dev/null +++ b/tools/dsv41/pin_coder.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Pin the ISTA-DAS Coder set to a Hugging Face repository: the ONE place the repo id lives is data/dsv41/coder-set.json. + + python tools/dsv41/pin_coder.py helcig/tmp-oct26-4 # read the repo now, write data/dsv41/coder-set.json + python tools/dsv41/pin_coder.py NEW/REPO --revision <40 hex> # a commit other than the repository's current one + python tools/dsv41/pin_coder.py --check # read the JSON, compare it with the Hub, change nothing + +What it does (only range requests for the GGUF headers, never a model download): + 1. asks the Hub for the repository's current commit and for every file's size and LFS sha256 (public repositories only); + 2. reads the header of each .gguf: the shard without tensors is the metadata shard, the shard with the single per_layer_token_embd tensor is the + Engram table, the others are the model; the mmproj is the file whose clip.projector_type is deepseek41v; + 3. takes the routed expert count from the metadata and checks that every layer's expert tensors and router agree with it + (a set whose layers have different counts, or whose router and experts disagree, is refused: the engine reads one number a model); + 4. writes data/dsv41/coder-set.json. setup.py, strata_control/dsv41_fit.py and the app read only that file, so a new URL is this one command. + +Everything the repository serves is data: names are checked against a plain pattern, sizes are capped, nothing is executed or written outside +the JSON. The repository's own license text is not read here; the metadata's general.license is copied into the JSON so a person can see it. +""" +from __future__ import annotations + +import argparse +import json +import re +import struct +import sys +import urllib.parse +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +OUT = ROOT / "data" / "dsv41" / "coder-set.json" +HUB = "https://huggingface.co" +NAME_OK = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.gguf$") +REPO_OK = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,95}/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$") +MAX_HEADER = 64 << 20 # a GGUF header (metadata + tensor table) larger than this is not read + + +class Remote: + """A growing prefix of a remote file read with Range requests.""" + + def __init__(self, url: str, chunk: int = 1 << 21): + self.url, self.chunk, self.buf, self.pos = url, chunk, b"", 0 + self.total = None + self._more(chunk) + + def _more(self, need: int) -> None: + start = len(self.buf) + end = start + max(self.chunk, need) - 1 + req = urllib.request.Request(self.url, headers={"Range": f"bytes={start}-{end}", "User-Agent": "strata-pin"}) + with urllib.request.urlopen(req, timeout=120) as r: + self.buf += r.read() + cr = r.headers.get("Content-Range") + if cr and "/" in cr: + self.total = int(cr.rsplit("/", 1)[1]) + + def read(self, n: int) -> bytes: + if self.pos + n > MAX_HEADER: + raise ValueError("header too large") + while self.pos + n > len(self.buf): + self._more(self.pos + n - len(self.buf)) + b = self.buf[self.pos:self.pos + n] + self.pos += n + return b + + +_SCALARS = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"} + + +def _u(f, fmt): + return struct.unpack("<" + fmt, f.read(struct.calcsize(fmt)))[0] + + +def _s(f) -> str: + n = _u(f, "Q") + if n > 1 << 24: + raise ValueError("string too long") + return f.read(n).decode("utf-8", "replace") + + +def _val(f, t): + if t == 8: + return _s(f) + if t == 9: + et, n = _u(f, "I"), _u(f, "Q") + if n > 1 << 22: + raise ValueError("array too long") + if et == 8: + return [_s(f) for _ in range(n)][:4] + if et == 9: + raise ValueError("nested arrays") + sz = struct.calcsize(_SCALARS[et]) + raw = f.read(sz * n) + return list(struct.unpack("<%d%s" % (min(n, 8), _SCALARS[et]), raw[:sz * min(n, 8)])) + return _u(f, _SCALARS[t]) + + +def read_header(url: str) -> dict: + f = Remote(url) + if f.read(4) != b"GGUF": + raise ValueError("not a GGUF file") + version, n_tensors, n_kv = _u(f, "I"), _u(f, "Q"), _u(f, "Q") + if version not in (2, 3) or n_tensors > 100000 or n_kv > 100000: + raise ValueError("unexpected GGUF header") + kv = {} + for _ in range(n_kv): + k = _s(f) + kv[k] = _val(f, _u(f, "I")) + tensors = {} + for _ in range(n_tensors): + name = _s(f) + dims = [_u(f, "Q") for _ in range(_u(f, "I"))] + tensors[name] = dims + _u(f, "I"), _u(f, "Q") # type, offset + return {"kv": kv, "tensors": tensors, "total": f.total} + + +def get_json(url: str): + with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "strata-pin"}), timeout=60) as r: + return json.loads(r.read().decode("utf-8", "replace")) + + +def build(repo: str, revision: str | None) -> dict: + if not REPO_OK.match(repo): + raise SystemExit(f"not a repository id: {repo!r}") + info = get_json(f"{HUB}/api/models/{repo}" + (f"/revision/{revision}" if revision else "") + "?blobs=true") + if info.get("private") or info.get("gated"): + raise SystemExit("the repository is private or gated: setup downloads without a login, so it cannot serve it") + rev = info["sha"] + if not re.fullmatch(r"[0-9a-f]{40}", rev): + raise SystemExit("the Hub gave no commit id") + files = {} + for s in info["siblings"]: + name = s["rfilename"] + if name.endswith(".gguf") and "/" not in name: + if not NAME_OK.match(name) or not s.get("size") or not (s.get("lfs") or {}).get("sha256"): + raise SystemExit(f"{name}: no size or LFS hash from the Hub") + files[name] = [int(s["size"]), s["lfs"]["sha256"].lower()] + if not files: + raise SystemExit("no .gguf files in the repository") + base = f"{HUB}/{repo}/resolve/{rev}/" + heads = {n: read_header(base + urllib.parse.quote(n)) for n in sorted(files)} + mmproj = [n for n, h in heads.items() if h["kv"].get("clip.projector_type") == "deepseek41v"] + models = {n: h for n, h in heads.items() if n not in mmproj} # (the later shards of a split carry only split.* keys, no architecture) + meta = [n for n, h in models.items() if not h["tensors"]] + engram = [n for n, h in models.items() if list(h["tensors"]) == ["per_layer_token_embd.weight"]] + body = sorted(n for n, h in models.items() if n not in engram and h["tensors"]) + if len(mmproj) != 1 or len(meta) != 1 or len(engram) != 1 or not body: + raise SystemExit(f"expected 1 metadata shard, 1 Engram shard, 1 picture file and model shards; got meta={meta} engram={engram} " + f"mmproj={mmproj} model={body}") + kv = models[meta[0]]["kv"] + if kv.get("general.architecture") != "deepseek41": + raise SystemExit(f"{meta[0]}: architecture {kv.get('general.architecture')!r}, not deepseek41") + n_exp = int(kv["deepseek41.expert_count"]) + layers = {} + for n in body: + for t, dims in models[n]["tensors"].items(): + m = re.match(r"blk\.(\d+)\.(ffn_(?:gate|up|down)_exps\.weight|ffn_gate_inp\.weight|exp_probs_b\.bias)$", t) + if m: + got = dims[2] if m.group(2).endswith("exps.weight") else dims[-1] + layers.setdefault(int(m.group(1)), set()).add(got) + bad = {i: v for i, v in layers.items() if v != {n_exp}} + if not layers or bad: + raise SystemExit(f"expert counts disagree with the metadata's {n_exp}: {dict(list(bad.items())[:4])}") + order = [meta[0]] + body + return { + "name": "ISTA-DAS-Coder", + "label": "ISTA-DAS Coder", + "repo": repo, + "revision": rev, + "pinned_from": info.get("lastModified", ""), + "license_in_metadata": str(kv.get("general.license", "")), + "experts_per_layer": n_exp, + "layers": len(layers), + "experts_used": int(kv["deepseek41.expert_used_count"]), + "shards": order, + "engram_shard": engram[0], + "mmproj": mmproj[0], + "profile": "profile-coder.bin", + "files": {n: files[n] for n in order + engram + mmproj}, + } + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("repo", nargs="?", help="the Hugging Face repository id, owner/name") + ap.add_argument("--revision", help="a commit (40 hex) instead of the current one") + ap.add_argument("--check", action="store_true", help="compare data/dsv41/coder-set.json with the Hub and change nothing") + ap.add_argument("--out", default=str(OUT)) + a = ap.parse_args() + cur = json.loads(Path(a.out).read_text(encoding="utf-8")) if Path(a.out).is_file() else {} + if a.check or not a.repo: + repo = cur.get("repo") + if not repo: + raise SystemExit("no repository pinned yet") + new = build(repo, cur.get("revision")) + keep = {k: v for k, v in cur.items() if k in new} + same = {k: (new[k] == keep.get(k)) for k in ("revision", "experts_per_layer", "shards", "engram_shard", "mmproj", "files")} + print(json.dumps(same)) + return 0 if all(same.values()) else 1 + new = build(a.repo, a.revision) + Path(a.out).write_text(json.dumps(new, indent=2, sort_keys=False) + "\n", encoding="utf-8") + print(f"{a.repo} @ {new['revision'][:8]}: {new['experts_per_layer']} experts a layer, {len(new['shards'])} model files + Engram " + f"{new['engram_shard']} + {new['mmproj']}; wrote {a.out}") + for n, (size, sha) in new["files"].items(): + print(f" {n} {size} {sha}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/test_setup_coder.py b/tools/test_setup_coder.py new file mode 100644 index 0000000000..1f5905ddb0 --- /dev/null +++ b/tools/test_setup_coder.py @@ -0,0 +1,220 @@ +"""The ISTA-DAS Coder (DeepSeek-V4.1-Flash with half of each layer's experts removed, 2026-11-01): the one file that names its repository, the pins, +the app's file recognition, the fit numbers, the pack call and the engine's profile size gate. +Run: python -m pytest tools/test_setup_coder.py""" +import importlib.util +import json +import re +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +spec = importlib.util.spec_from_file_location("setup_coder", ROOT / "setup.py") +setup = importlib.util.module_from_spec(spec) +spec.loader.exec_module(setup) + +from strata_control import dsv41_fit, dsv41_sets # noqa: E402 + +JSON = ROOT / "data" / "dsv41" / "coder-set.json" +PIN = json.loads(JSON.read_text(encoding="utf-8")) +NAME = "ISTA-DAS-Coder" +R9700 = {"index": 0, "name": "Radeon AI PRO R9700", "vram_gb": 32, "vendor": "amd", "arch": "gfx1201"} +FOUR = [{**R9700, "index": i} for i in range(4)] + + +class OnePlace(unittest.TestCase): + """The repository id, the commit and the files are in data/dsv41/coder-set.json and nowhere else: a new URL is tools/dsv41/pin_coder.py.""" + + def test_the_json_is_complete(self): + self.assertRegex(PIN["revision"], r"^[0-9a-f]{40}$") + self.assertRegex(PIN["repo"], r"^[\w.-]+/[\w.-]+$") + self.assertEqual(PIN["experts_per_layer"], 192) + for n in (*PIN["shards"], PIN["engram_shard"], PIN["mmproj"]): + size, sha = PIN["files"][n] + self.assertRegex(sha, r"^[0-9a-f]{64}$", n) + self.assertGreater(size, 0) + self.assertEqual(len(PIN["shards"]), 3) # the metadata shard and two model shards; the fourth file is the Engram + + def test_setup_reads_it(self): + self.assertEqual(setup.DSV41_CODER_REPO, PIN["repo"]) + self.assertEqual(setup.HF_REVISIONS[PIN["repo"]], PIN["revision"]) + self.assertEqual(setup.REPO_PINS.get(PIN["repo"]) or setup.DSV41_CODER_FILES, setup.DSV41_CODER_FILES) + self.assertEqual({n: list(v) for n, v in setup.DSV41_CODER_FILES.items()}, PIN["files"]) + md = setup.MULTI_FILE_FAMILIES["deepseek41"]["models"][NAME] + self.assertEqual(md["hf"], f"https://huggingface.co/{PIN['repo']}/resolve/{PIN['revision']}/") + self.assertEqual((md["shards"], md["engram_shard"]), (PIN["shards"], PIN["engram_shard"])) + + def test_nothing_else_names_the_repository(self): + """A grep over the sources the packaged Terminal and the app ship: the id appears in the JSON only (tests and notes may quote it).""" + hits = [] + for p in list(ROOT.glob("*.py")) + list((ROOT / "strata_control").glob("*.py")) + list((ROOT / "strata_cli").rglob("*.py")) \ + + list((ROOT / "tools").glob("*.py")) + list((ROOT / "serve").glob("*.py")) + list((ROOT / "apps" / "host" / "src").rglob("*.ts*")): + if p.name.startswith("test_") or p.name == "pin_coder.py": + continue + if PIN["repo"] in p.read_text(encoding="utf-8", errors="replace"): + hits.append(str(p.relative_to(ROOT))) + self.assertEqual(hits, []) + + def test_the_fit_numbers_come_from_the_same_file(self): + v = dsv41_fit.ISTA_SETS[NAME] + self.assertEqual(v["set_bytes"], sum(PIN["files"][n][0] for n in PIN["shards"])) + self.assertEqual(v["experts_per_layer"], PIN["experts_per_layer"]) + + def test_the_short_spelling_is_accepted(self): + self.assertEqual(setup.model_alias("IST-DAS-Coder"), NAME) + self.assertEqual(setup.model_alias("ista-das-coder"), NAME) + self.assertEqual(setup.model_alias("ISTA-DAS-2.25bpw"), "IST-DAS-2.25bpw") # the others as before + + +class Pins(unittest.TestCase): + def test_every_file_is_pinned_and_the_model_is_half_the_experts(self): + md = setup.MULTI_FILE_FAMILIES["deepseek41"]["models"][NAME] + self.assertEqual(md["recipe"], "coder") + for n in (*md["shards"], md["engram_shard"]): + self.assertIn(n, setup.DSV41_ALL_FILES) + self.assertEqual(setup.DSV41_ALL_FILES[md["engram_shard"]][0], 110_595_290_592) # the same size as Unsloth's shard 5 + self.assertEqual(md["shared"], [setup.DSV41_ISTA_ENGRAM, setup.DSV41_DSPARK]) # the Engram and the drafter are the shared files; no second metadata file + + def test_the_picture_file_is_the_shared_one_and_the_coders_copy_is_accepted(self): + """The repository's mmproj has Unsloth's tensors byte for byte (checked on the tensor data) under another header: one shared file serves every set.""" + pin = setup.DSV41_CODER_FILES[setup.DSV41_CODER["mmproj"]] + self.assertNotEqual(pin, setup.DSV41_ALL_FILES[setup.DSV41_MMPROJ]) + self.assertEqual(setup.DSV41_ALL_FILES[setup.DSV41_MMPROJ][0], 972_208_288) # Unsloth's, not overwritten by the name clash + self.assertEqual(setup.DSV41_ALT_FILES[setup.DSV41_MMPROJ], [pin]) + self.assertIn(pin[1], setup.dsv41_also(setup.DSV41_MMPROJ)) + self.assertEqual(setup.DSV41_SHA_ALSO, {setup.DSV41_ISTA_ENGRAM: (setup.DSV41_ENGRAM_CONVERTED[1],)}) # unchanged + with tempfile.TemporaryDirectory() as tmp: + f = Path(tmp) / setup.DSV41_MMPROJ + f.write_bytes(b"\0" * 16) + self.assertEqual(setup.dsv41_pin_of(f, setup.DSV41_ALL_FILES[setup.DSV41_MMPROJ]), setup.DSV41_ALL_FILES[setup.DSV41_MMPROJ]) + + def test_the_other_sets_are_unchanged(self): + fam = setup.MULTI_FILE_FAMILIES["deepseek41"]["models"] + self.assertEqual(fam["IST-DAS-2.00bpw"]["recipe"], "ista") + self.assertEqual(len(fam["IST-DAS-2.00bpw"]["shards"]), 4) + self.assertEqual(list(fam)[:4], ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "IST-DAS-1.75bpw", NAME]) + + +class Recognised(unittest.TestCase): + def files(self): + t = dsv41_sets.tables()["sets"][NAME] + return {**t["shards"], **t["engram_alt"]} + + def test_a_whole_set_is_recognised_by_names_and_sizes(self): + rows = [r for r in dsv41_sets.match(self.files()) if r["model"] == NAME] + self.assertTrue(rows and rows[0]["complete"]) + self.assertEqual(rows[0]["engram"], PIN["engram_shard"]) + + def test_another_models_split_files_with_the_same_names_are_not_the_set(self): + """model-00002-of-00004.gguf is a name any split model has: only the pinned sizes make it this set.""" + other = {n: s + 1000 for n, s in self.files().items()} + self.assertEqual([r for r in dsv41_sets.match(other) if r["model"] == NAME and r["complete"]], []) + self.assertEqual([r for r in dsv41_sets.match(other) if r["model"] == NAME and r["present"]], []) + + def test_a_cut_shard_is_refused(self): + files = self.files() + files[PIN["shards"][1]] -= 1 << 20 + row = next(r for r in dsv41_sets.match(files) if r["model"] == NAME) + self.assertFalse(row["complete"]) + self.assertEqual(row["wrong_size"], [PIN["shards"][1]]) + + def test_the_launch_claims_a_folder_only_when_the_sizes_are_the_pinned_ones(self): + from strata_cli.launch.runner import Runner # noqa: F401 (the staticmethod lives on the runner class) + with tempfile.TemporaryDirectory() as tmp: + for n in PIN["shards"]: + (Path(tmp) / n).write_bytes(b"GGUF") # right names, wrong sizes: some other model's split + self.assertIsNone(self.set_in(tmp)) + sizes = {n: v[0] for n, v in setup.DSV41_ALL_FILES.items()} + for n in PIN["shards"]: + with (Path(tmp) / n).open("wb") as f: + f.truncate(sizes[n]) # sparse files of the pinned sizes + found = self.set_in(tmp) + self.assertEqual(found[0], NAME) + + @staticmethod + def set_in(folder): + from strata_cli.launch import runner + cls = next(c for c in vars(runner).values() if isinstance(c, type) and hasattr(c, "deepseek_set_in")) + return cls.deepseek_set_in(setup, folder) + + +class Plan(unittest.TestCase): + def test_the_model_has_half_the_experts(self): + for cards in ([R9700], FOUR): + p = dsv41_fit.plan(cards, 125.0, None, 131072, model=NAME) + self.assertEqual(p["experts_total"], 7680) + self.assertLessEqual(p["experts_in_vram"], 7680) + self.assertEqual(p["variant"], NAME) + self.assertAlmostEqual(p["experts_gb"], 66.0, delta=0.1) + p = dsv41_fit.plan(FOUR, 251.0, None, 131072, model=NAME) + self.assertEqual(p["experts_in_vram"], 7680) # four 32 GB cards hold every one of them + self.assertEqual(p["verdict"], "fits") + + def test_the_download_is_the_model_plus_the_shared_files(self): + gb = dsv41_fit.ista_download_bytes(NAME) / 1e9 + self.assertAlmostEqual(gb, (72_123_566_336 + 110_595_290_816 + 7_976_914_240) / 1e9, delta=0.01) + self.assertEqual(dsv41_fit.ista_download_bytes(NAME, have_engram=True), 72_123_566_336 + 7_976_914_240) + + def test_the_other_sets_still_have_384_experts_a_layer(self): + for m in ("IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "IST-DAS-1.75bpw", "UD-IQ1_S", "UD-IQ1_M"): + self.assertEqual(dsv41_fit.plan([R9700], 125.0, None, 131072, model=m)["experts_total"], 15360, m) + + def test_a_mac_gets_the_plain_not_run_line(self): + mac = {"index": 0, "name": "Apple M5 Max", "vendor": "apple", "unified_gb": 128.0, "vram_gb": 128.0} + p = dsv41_fit.plan([mac], 128.0, None, 131072, model=NAME) + self.assertTrue(p["mac"]) + self.assertIn("Not run on a Mac yet", p["words"]) + self.assertEqual(p["experts_total"], 7680) + + def test_the_menu_row_is_there(self): + import strata_mcp as M + s = M.Strata(ROOT) + fam = next(f for f in s.model_table({"ram_gb": 251.0, "gpus": [{**c, "usable": True} for c in FOUR], "engine_vendor": "amd"}) + if f["family"] == "deepseek41") + row = next(x for x in fam["sizes"] if x["model"] == NAME) + self.assertEqual(row["id"], "deepseek-v4.1-flash-" + NAME.lower()) + self.assertTrue(row["images"] and row["multi_file"]) + self.assertEqual(row["disk_gb"], round(row["download_gb"] + dsv41_fit.DISK_HEADROOM_GB, 1)) + self.assertIn("192", row["about"]) + self.assertTrue(row["on_this_pc"].startswith("fits")) + + +class Pack(unittest.TestCase): + def test_the_pack_call_is_the_ista_one_with_the_sets_own_metadata_shard(self): + md = setup.MULTI_FILE_FAMILIES["deepseek41"]["models"][NAME] + cmd = setup.dsv41_pack_cmd(Path("/m"), md["shards"], Path("/s/e.gguf"), Path("/m") / md["shards"][0], Path("/s/d.gguf"), Path("/p"), Path("/s/mm.gguf")) + self.assertEqual(cmd[cmd.index("--shards") + 1:cmd.index("--engram")], md["shards"]) + self.assertEqual(cmd[cmd.index("--engram-meta") + 1], str(Path("/m") / md["shards"][0])) + self.assertIn("--mmproj", cmd) + self.assertIn("--dspark-noise-token", cmd) + + +class PinTool(unittest.TestCase): + def test_build_reads_the_hub_and_the_headers(self): + sys.path.insert(0, str(ROOT / "tools" / "dsv41")) + import pin_coder as P + names = ["mmproj-BF16.gguf", "model-00001-of-00003.gguf", "model-00002-of-00003.gguf", "model-00003-of-00003.gguf"] + info = {"sha": "a" * 40, "private": False, "gated": False, "lastModified": "x", + "siblings": [{"rfilename": n, "size": 100 + i, "lfs": {"sha256": f"{i:064x}"}} for i, n in enumerate(names)] + [{"rfilename": ".gitattributes", "size": 1}]} + kv_meta = {"general.architecture": "deepseek41", "deepseek41.expert_count": 128, "deepseek41.expert_used_count": 6, "general.license": "mit"} + heads = {"mmproj-BF16.gguf": {"kv": {"clip.projector_type": "deepseek41v"}, "tensors": {}}, + "model-00001-of-00003.gguf": {"kv": kv_meta, "tensors": {}}, + "model-00002-of-00003.gguf": {"kv": {}, "tensors": {"blk.0.ffn_gate_exps.weight": [5120, 2304, 128], "blk.0.ffn_gate_inp.weight": [5120, 128], + "blk.0.exp_probs_b.bias": [128]}}, + "model-00003-of-00003.gguf": {"kv": {}, "tensors": {"per_layer_token_embd.weight": [256, 5]}}} + with mock.patch.object(P, "get_json", return_value=info), mock.patch.object(P, "read_header", side_effect=lambda url: heads[url.rsplit("/", 1)[1]]): + out = P.build("owner/new-name", None) + self.assertEqual((out["repo"], out["revision"], out["experts_per_layer"]), ("owner/new-name", "a" * 40, 128)) + self.assertEqual(out["shards"], ["model-00001-of-00003.gguf", "model-00002-of-00003.gguf"]) + self.assertEqual((out["engram_shard"], out["mmproj"]), ("model-00003-of-00003.gguf", "mmproj-BF16.gguf")) + heads["model-00002-of-00003.gguf"]["tensors"]["blk.1.ffn_gate_inp.weight"] = [5120, 64] # a layer that disagrees: refused + with self.assertRaises(SystemExit): + P.build("owner/new-name", None) + self.assertRaises(SystemExit, P.build, "not a repo", None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_dsv41.py b/tools/test_setup_dsv41.py index 45f2417721..da1314e1cd 100644 --- a/tools/test_setup_dsv41.py +++ b/tools/test_setup_dsv41.py @@ -316,7 +316,7 @@ class Catalog(unittest.TestCase): s = M.Strata(ROOT) fam = next(f for f in s.model_table({"ram_gb": 251.0, "gpus": [{**c, "usable": True} for c in FOUR], "engine_vendor": "amd"}) if f["family"] == "deepseek41") - self.assertEqual([x["model"] for x in fam["sizes"]], ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "IST-DAS-1.75bpw", "UD-IQ1_S", "UD-IQ1_M", "UD-Q8_K_XL"]) + self.assertEqual([x["model"] for x in fam["sizes"]], ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "IST-DAS-1.75bpw", "ISTA-DAS-Coder", "UD-IQ1_S", "UD-IQ1_M", "UD-Q8_K_XL"]) small_sets = {x["model"]: x for x in fam["sizes"]} self.assertEqual((small_sets["IST-DAS-2.00bpw"]["download_gb"], small_sets["IST-DAS-2.25bpw"]["download_gb"]), (256.8, 273.8)) self.assertTrue(small_sets["IST-DAS-2.00bpw"]["on_this_pc"].startswith("fits")) @@ -428,7 +428,7 @@ class OfficialSets(unittest.TestCase): def test_the_pinned_files(self): fam = setup.MULTI_FILE_FAMILIES["deepseek41"] - self.assertEqual(list(fam["models"]), ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "IST-DAS-1.75bpw", "UD-IQ1_S", "UD-IQ1_M", "UD-Q8_K_XL"]) # the official sets first + self.assertEqual(list(fam["models"]), ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "IST-DAS-1.75bpw", "ISTA-DAS-Coder", "UD-IQ1_S", "UD-IQ1_M", "UD-Q8_K_XL"]) # the official sets first repo = "ISTA-DASLab/DeepSeek-V4.1-Flash-1017-GSQ-RCO-GGUF" self.assertEqual(setup.HF_REVISIONS[repo], "cb02422c900df489cea5833e8a92171224059b3c") self.assertIs(setup.REPO_PINS[repo], setup.DSV41_ISTA_FILES) @@ -696,7 +696,7 @@ class Smallest(unittest.TestCase): self.assertNotIn("--skip-tensors", cmd) def test_it_is_the_smallest_and_warns_never_refuses(self): - sizes = {m: dsv41_fit.ista_download_bytes(m) / 1e9 for m in dsv41_fit.ISTA_SETS} + sizes = {m: dsv41_fit.ista_download_bytes(m) / 1e9 for m in dsv41_fit.ISTA_SETS if m.startswith("IST-DAS-")} # (the ISTA-DAS Coder has half the experts: tools/test_setup_coder.py) self.assertEqual(min(sizes, key=sizes.get), "IST-DAS-1.75bpw") self.assertAlmostEqual(sizes["IST-DAS-1.75bpw"], 239.3, delta=0.1) for ram in (24.0, 36.0, 64.0): diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index a5fa4db86c..3f96813d2c 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -778,16 +778,19 @@ class MacCatalog(unittest.TestCase): self.assertEqual({x["on_this_pc"] for f in s.model_table(hw) if f["family"] != "deepseek41" for x in f["sizes"]}, {"does not fit"}) self.assertTrue(all(x["on_this_pc"].startswith("does not fit") for f in s.model_table(hw) if f["family"] == "deepseek41" for x in f["sizes"])) - def test_deepseek_on_a_mac_offers_the_two_sets_that_were_run_with_the_mac_words(self): + def test_deepseek_on_a_mac_offers_the_sets_with_the_mac_words(self): s, hw = self.hw(128) ds = next(f for f in s.model_table(hw) if f["family"] == "deepseek41") by = {x["model"]: x for x in ds["sizes"]} - self.assertEqual(list(by), ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw"], "the 1.75 bpw set was never run on a Mac") + self.assertEqual(list(by), ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "ISTA-DAS-Coder", "UD-IQ1_S", "UD-IQ1_M"], "the 1.75 bpw set was never run on a Mac; the Coder, UD-IQ1_S and UD-IQ1_M are offered with a plain note") for x in by.values(): self.assertTrue(x["multi_file"] and not x["images"]) + self.assertGreater(x["disk_gb"], x["download_gb"]) + if x["model"] == "ISTA-DAS-Coder": # 66 GB of experts: all of them stay in a 128 GB Mac's memory + self.assertTrue(x["on_this_pc"].startswith("fits: every expert stays"), x["on_this_pc"]) + continue self.assertTrue(x["on_this_pc"].startswith("runs on this Mac's memory"), x["on_this_pc"]) self.assertIn("read from the SSD", x["on_this_pc"]) - self.assertGreater(x["disk_gb"], x["download_gb"]) s, hw = self.hw(32) ds = next(f for f in s.model_table(hw) if f["family"] == "deepseek41") for x in ds["sizes"]: # a small Mac: said plainly, never refused From 8dbdcf1b205d81b0e12faf4a9603fa0b2447fb3d Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:18:48 +0100 Subject: [PATCH 53/59] DeepSeek engine: an expert profile of another model's size is not read; the router tests run with 192 experts and poisoned padding (CUDA, Metal) --- metal/tests/ds4_route_guard_parity.cpp | 18 ++++++++++++------ src/dsv41/ds4_experts_rule.hpp | 12 ++++++++++++ src/dsv41/ds4_model.cu | 18 +++++++++++++++--- tests/dsv41/ds4_route_guard_test.cu | 17 +++++++++++++---- tests/dsv41/experts_rule_test.cpp | 14 ++++++++++++++ 5 files changed, 66 insertions(+), 13 deletions(-) diff --git a/metal/tests/ds4_route_guard_parity.cpp b/metal/tests/ds4_route_guard_parity.cpp index 6657c3f31f..a3980c9447 100644 --- a/metal/tests/ds4_route_guard_parity.cpp +++ b/metal/tests/ds4_route_guard_parity.cpp @@ -20,17 +20,17 @@ static void check(bool ok, const char* what) { if (!ok) ++fails; } -int main() { - mtl::Context cx; - const int lib = cx.compile({"../src/engine/msl/ds4_init.metal"}, "", false); +// n routed experts: 384 (every set so far) and 192 (the ISTA-DAS Coder). The entries past n hold a poison score (30, bias 5): a kernel that read one would pick it. +static void run(mtl::Context& cx, const int lib, const int n) { + std::printf("-- %d experts\n", n); mtl::Pipeline p_route = cx.pipeline(lib, "ds4_route"), p_pub = cx.pipeline(lib, "ds4_route_publish"); - const int n = 384, k = 6, T = 16, kPicks = 8; + const int k = 6, T = 16, kPicks = 8; const float scale = 1.5f; mtl::Buffer b_logits = cx.alloc((size_t) T * 1024 * 4), b_bias = cx.alloc(1024 * 4), b_idx = cx.alloc((size_t) T * kPicks * 4), b_w = cx.alloc((size_t) T * kPicks * 4), b_vram = cx.alloc(1024 * 8), b_plan = cx.alloc((size_t) T * kPicks * 8), b_vlw = cx.alloc(1024), b_bad = cx.alloc(64); - std::vector<float> bias(1024, 0.0f), logits((size_t) T * 1024, 0.0f); + std::vector<float> bias(1024, 5.0f), logits((size_t) T * 1024, 30.0f); for (int i = 0; i < n; ++i) bias[(size_t) i] = 0.01f * (float) ((i * 37) % 17); std::vector<unsigned long long> vram(1024, 0ull); for (int i = 0; i < n; i += 2) vram[(size_t) i] = 0x1000ull + (unsigned long long) i; @@ -45,7 +45,7 @@ int main() { for (int i = 0; i < 1024; ++i) { s = s * 1664525u + 1013904223u; float v = ((float) (s >> 8) / (float) (1 << 24) - 0.5f) * 8.0f; - if (i >= n) v = 0.0f; + if (i >= n) v = 30.0f; // (the poison; the NaN / inf modes overwrite every entry) if (mode == 1) v = nan; if (mode == 2) v = inf; if (mode == 3) v = -inf; @@ -134,6 +134,12 @@ int main() { } } } +} + +int main() { + mtl::Context cx; + const int lib = cx.compile({"../src/engine/msl/ds4_init.metal"}, "", false); + for (int n : {384, 192}) run(cx, lib, n); std::printf("%s\n", fails ? "ds4_route_guard_parity: FAILED" : "ds4_route_guard_parity: all ok"); return fails ? 1 : 0; } diff --git a/src/dsv41/ds4_experts_rule.hpp b/src/dsv41/ds4_experts_rule.hpp index 01f01650ad..69c0ee1384 100644 --- a/src/dsv41/ds4_experts_rule.hpp +++ b/src/dsv41/ds4_experts_rule.hpp @@ -50,6 +50,18 @@ inline int experts_per_word(int requested, uint64_t vram_bytes, int model_k, boo return n < 1 ? 1 : n; } +// The expert profile (`expert-profile.bin`, --expert-profile) is a bare array of u32 counts: one row of n_exp per layer, the drafter's blocks after the 40 layers, no header. +// Its size is the only thing that says which model it was counted on, and the engine used to read the first rows of any file that was long enough: a profile counted on +// 384 experts a layer (43 rows of 384 = 66,048 bytes) read as rows of 192 gives every layer the wrong experts, silently (the ISTA-DAS Coder has 192). A file +// holds the layers and at most kProfileExtraRows more (the drafter's 3 blocks, with room); anything longer is another model's. Every profile written by the engine +// or shipped with Strata (40 + 3 rows, or 40) passes, so a set with 384 experts reads exactly the files it read before. +constexpr int kProfileExtraRows = 8; +inline bool profile_size_fits(uint64_t bytes, int layers, int n_exp) { + if (layers <= 0 || n_exp <= 0) return false; + const uint64_t row = 4ull * (uint64_t) n_exp; + return bytes >= row * (uint64_t) layers && bytes <= row * (uint64_t) (layers + kProfileExtraRows); +} + // Prompt chunk (--prefill-chunk) default, one rule decided once at load from bytes (no timing). The chunk's buffers come out of the VRAM the // expert tier would have, and every chunk streams the experts the cards do not hold once, so a bigger chunk is fewer passes. Measured (8K prompt): // - the GPUs hold most of the experts (4 x R9700, share 0.86): 1024 370 tok/s, 8192 214 -> small chunk; diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index d8e752071e..e5940d6e17 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -2840,6 +2840,10 @@ struct Model::Impl { l.mtp = il >= g.nl; l.name = l.mtp ? "mtp." + std::to_string(il - g.nl) + "." : "layers." + std::to_string(il) + "."; l.n_exp = l.mtp ? g.d_n_exp : g.n_exp; + if (l.mtp && l.n_exp > g.n_exp) { // the profile keeps one row width (g.n_exp) for every block: a drafter with more experts than the model would write past it + err = l.name + ": the drafter has " + std::to_string(l.n_exp) + " experts and the model " + std::to_string(g.n_exp) + ": not covered"; + return false; + } l.k_exp = l.mtp ? g.d_k : g.k_exp; if (!l.mtp) { // experts a word takes: --experts N / the faster-mode rule (ds4_experts_rule.hpp), DS4_TOPK=N over both (a test) if (il == 0) { @@ -3470,9 +3474,17 @@ struct Model::Impl { if (!o.profile.empty()) { std::FILE* f = std::fopen(o.profile.c_str(), "rb"); if (f != nullptr) { - std::vector<uint32_t> p(prof.size()); - const size_t n = std::fread(p.data(), 4, p.size(), f); - if (n == p.size() || n == (size_t) g.nl * g.n_exp) std::copy(p.begin(), p.begin() + (long) n, prof.begin()); + std::fseek(f, 0, SEEK_END); + const long long bytes = (long long) std::ftell(f); + std::rewind(f); + if (bytes >= 0 && !profile_size_fits((uint64_t) bytes, g.nl, g.n_exp)) { // another model's counts (see ds4_experts_rule.hpp) + std::fprintf(stderr, "ds4: %s is %lld bytes and this model's profile is %d layers of %d experts (%d bytes and a few drafter rows): " + "not read, the experts start unranked\n", o.profile.c_str(), bytes, g.nl, g.n_exp, g.nl * g.n_exp * 4); + } else { + std::vector<uint32_t> p(prof.size()); + const size_t n = std::fread(p.data(), 4, p.size(), f); + if (n == p.size() || n == (size_t) g.nl * g.n_exp) std::copy(p.begin(), p.begin() + (long) n, prof.begin()); + } std::fclose(f); } } diff --git a/tests/dsv41/ds4_route_guard_test.cu b/tests/dsv41/ds4_route_guard_test.cu index 681044908f..1d121ec1aa 100644 --- a/tests/dsv41/ds4_route_guard_test.cu +++ b/tests/dsv41/ds4_route_guard_test.cu @@ -29,9 +29,12 @@ static void check(bool ok, const char* what) { if (!ok) ++fails; } -int main() { - const int n = 384, k = 6, T = 16; - std::vector<float> bias(1024, 0.0f), logits((size_t) T * 1024, 0.0f); +// n routed experts: 384 (every set so far) and 192 (the ISTA-DAS Coder: half of each layer's experts removed). The entries past n hold a score no real +// expert has (30, and a bias of 5), so a router that read one would pick it and the checks below would fail. +static int run(int n) { + std::printf("-- %d experts\n", n); + const int k = 6, T = 16; + std::vector<float> bias(1024, 5.0f), logits((size_t) T * 1024, 30.0f); for (int i = 0; i < n; ++i) bias[(size_t) i] = 0.01f * (float) ((i * 37) % 17); std::vector<unsigned long long> vram(1024, 0ull); float *d_logits, *d_bias, *d_w; @@ -57,7 +60,7 @@ int main() { for (int i = 0; i < 1024; ++i) { s = s * 1664525u + 1013904223u; float v = ((float) (s >> 8) / (float) (1 << 24) - 0.5f) * 8.0f; - if (i >= n) v = 0.0f; + if (i >= n) v = 30.0f; // (the poison; the NaN / inf modes below overwrite every entry, as before) if (mode == 1) v = nan; if (mode == 2) v = inf; if (mode == 3) v = -inf; @@ -170,6 +173,12 @@ int main() { std::printf("TIMING %s T=%d best of 7 rounds: %.3f us a launch\n", which ? "route_publish" : "route", tt, best); } } + return 0; +} + +int main() { + for (int n : {384, 192}) + if (run(n) != 0) return 1; // (a device error: the context is gone) std::printf("%s\n", fails ? "ds4_route_guard_test: FAILED" : "ds4_route_guard_test: all ok"); return fails ? 1 : 0; } diff --git a/tests/dsv41/experts_rule_test.cpp b/tests/dsv41/experts_rule_test.cpp index 48e696be26..160802c4fc 100644 --- a/tests/dsv41/experts_rule_test.cpp +++ b/tests/dsv41/experts_rule_test.cpp @@ -11,6 +11,7 @@ using strata::ds4::copy_all_fits; using strata::ds4::attn_slab_rows; using strata::ds4::staging_ring_mb; using strata::ds4::store_gpu_shares_ram; +using strata::ds4::profile_size_fits; static int fails = 0; #define CHECK_EQ(a, b) \ @@ -121,6 +122,19 @@ int main() { CHECK_EQ(attn_slab_rows(512, 1024, 256, 1e18, bpr, 0.77), 512); // DS4_ATTN_SLAB=N: that many rows whatever the share CHECK_EQ(attn_slab_rows(-1, 1024, 1024, -5.0e9, bpr, 0.77), 1024); // a unified-memory base (32 MB of q = 1024 rows) is kept } + // the expert profile's size gate: a bare array of rows of n_exp counts, 40 layers (+ the drafter's 3 blocks); another model's file is not read + { + CHECK_EQ(profile_size_fits(66048, 40, 384), 1); // the shipped 2.00 / 2.25 profiles (43 rows of 384) on a 384-expert set: as before + CHECK_EQ(profile_size_fits(40 * 384 * 4, 40, 384), 1); // 40 rows (a run without the drafter) + CHECK_EQ(profile_size_fits(43 * 192 * 4, 40, 192), 1); // the Coder's own file (43 rows of 192) + CHECK_EQ(profile_size_fits(40 * 192 * 4, 40, 192), 1); + CHECK_EQ(profile_size_fits(66048, 40, 192), 0); // a 384-expert profile on the 192-expert set: 86 rows of 192, not its file + CHECK_EQ(profile_size_fits(40 * 384 * 4, 40, 192), 0); + CHECK_EQ(profile_size_fits(43 * 192 * 4, 40, 384), 0); // and the other way round (too short for 40 rows of 384) + CHECK_EQ(profile_size_fits(0, 40, 384), 0); + CHECK_EQ(profile_size_fits(66048, 0, 384), 0); + CHECK_EQ(profile_size_fits(66048, 40, 0), 0); + } // the staging ring (MB): staging_ring_mb(share, room_bytes, n_dev, integrated, hip) { const double GB = 1e9; From adf7e54127c6e4ed32c1a628396b7e511384fa6d Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:33:47 +0100 Subject: [PATCH 54/59] ISTA-DAS Coder: Strix and Spark note (sizes exact, speed not measured), app label test --- apps/host/tests/qa1-downloads.test.mjs | 5 +++++ strata_control/dsv41_fit.py | 13 +++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/apps/host/tests/qa1-downloads.test.mjs b/apps/host/tests/qa1-downloads.test.mjs index 05f2b5e42c..c70a5cd487 100644 --- a/apps/host/tests/qa1-downloads.test.mjs +++ b/apps/host/tests/qa1-downloads.test.mjs @@ -103,6 +103,11 @@ test('the recommended four come first; the others are what the "More versions" l assert.deepEqual(lib.recommendedVersions([v('qwen36', 'UD-Q4_K_XL')]), [], 'Qwen3.6 has no recommended set: its versions are all shown'); }); +test("the DeepSeek versions have their names, the ISTA-DAS Coder under the owner's spelling", () => { + lib.setTranslationLanguage('en'); + assert.deepEqual(['IST-DAS-1.75bpw', 'IST-DAS-2.00bpw', 'IST-DAS-2.25bpw', 'ISTA-DAS-Coder'].map(m => lib.nativeVersionLabel(m)), ['Smallest', 'Balanced', 'Best quality', 'ISTA-DAS Coder']); +}); + test('the three NVFP4 versions have clear names and one line that tells them apart', () => { lib.setTranslationLanguage('en'); const names = ['NVFP4', 'NVFP4-NVIDIA', 'NVFP4-QAD'].map(m => lib.nativeVersionLabel(m)); diff --git a/strata_control/dsv41_fit.py b/strata_control/dsv41_fit.py index a244acc101..7f2b70f1dd 100644 --- a/strata_control/dsv41_fit.py +++ b/strata_control/dsv41_fit.py @@ -107,6 +107,7 @@ if CODER: ISTA_SETS[CODER_MODEL] = { "title": CODER.get("label", "ISTA-DAS Coder"), "set_bytes": _coder_bytes, "experts_gb": 66.04, "dense_gb": 6.08, "profile": CODER.get("profile", "profile-coder.bin"), "meta_bytes": 0, "experts_per_layer": int(CODER["experts_per_layer"]), "ppl": "?", "ram_ok_gb": 24.0, "measured": "", + "unproven_uma": "Not run on a Ryzen AI Max (Strix Halo) or a DGX Spark yet: the sizes above are exact, the speed is not measured on a shared-memory computer.", "disk_total": round((_coder_bytes + ISTA_ENGRAM_BYTES + ISTA_DSPARK_BYTES) / GB), "quality": "ISTA-DAS's coding version, half of the model's experts removed (192 of 384 in every layer); not measured against the original model here yet"} ISTA_DENSE_GB = 6.16 # the dense weights in the shards (attention, router, shared experts, the head; the embedding stays on the CPU) @@ -444,7 +445,7 @@ def _plan_uma(key: str, model: str, card: dict, ram_gb: float | None, disk_free_ "experts_total": n_experts, "experts_in_vram": in_mem, "vram_experts_gb": _round1(resident), "cpu_experts_gb": 0.0, "weights_gb": _round1(set_gb), "experts_gb": _round1(v["experts_gb"]), "dense_gb": _round1(dense_gb_v), "engram_gb": _round1(ISTA_ENGRAM_BYTES / GB), "download_gb": _round1(download), "tp": 1, "args": [], - "measured": UMA_MEASURED, "lines": [], "warnings": [], "ram_gb": ram_gb, "context": context, + "measured": "" if v.get("unproven_uma") else UMA_MEASURED, "lines": [], "warnings": [], "ram_gb": ram_gb, "context": context, "disk_total_gb": v["disk_total"], "disk_need_gb": _round1(need_disk), "disk_ok": None if disk_free_gb is None else disk_free_gb >= need_disk, "uma": True, "streamed_gb": _round1(streamed), "ram_needed_gb": _round1(total), "spill_gb": _round1(streamed), @@ -460,13 +461,17 @@ def _plan_uma(key: str, model: str, card: dict, ram_gb: float | None, disk_free_ lines.append(f"{name} shares this PC's memory: the RAM and the GPU's BIOS carve-out are one pool of {total:.0f} GB. About " f"{resident:.0f} GB of the {float(v['experts_gb']):.0f} GB of experts stay in it beside {dense_gb_v:.1f} GB of " f"dense weights and {UMA_RESERVE_GB:.0f} GB kept for Windows; the other {streamed:.0f} GB are read from the SSD while it answers.") - lines.append(f"Measured on this kind of PC: {UMA_MEASURED}.") + if not v.get("unproven_uma"): # (these speeds are the 2.00 set's: a set not run there says so below instead) + lines.append(f"Measured on this kind of PC: {UMA_MEASURED}.") else: # a DGX Spark's GB10: one memory for the CPU and the GPU, nothing set aside in a BIOS, Linux lines.append(f"{name} shares this computer's memory: the CPU and the GPU are one pool of {total:.0f} GB. About " f"{resident:.0f} GB of the {float(v['experts_gb']):.0f} GB of experts stay in it beside {dense_gb_v:.1f} GB of " f"dense weights and {UMA_RESERVE_GB:.0f} GB kept for the system; the other {streamed:.0f} GB are read from the SSD while it answers.") - lines.append(f"Measured on this kind of computer: {UMA_MEASURED_GB10}.") - out["measured"] = UMA_MEASURED_GB10 + if not v.get("unproven_uma"): + lines.append(f"Measured on this kind of computer: {UMA_MEASURED_GB10}.") + out["measured"] = "" if v.get("unproven_uma") else UMA_MEASURED_GB10 + if v.get("unproven_uma"): + lines.append(v["unproven_uma"]) if streamed > 0.5: lines.append("Keep the model files on the NVMe drive and the machine otherwise idle while it answers: every word reads experts from it.") if streamed <= 0.5: From 93e43af9e10a48d27250663f7a02635869b8d376 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:42:20 +0100 Subject: [PATCH 55/59] App: DeepSeek reads pictures by default (catalog images true, install keeps vision on, no reader device choice, a pack without the tower offers the missing shared file); load applies the --vision pair --- apps/host/server/native-control.mjs | 9 ++++- apps/host/src/components/NativeModels.tsx | 2 +- apps/host/src/lib/native-catalog.ts | 2 +- apps/host/tests/native-ds-args.test.mjs | 46 ++++++++++++++++++++++- 4 files changed, 53 insertions(+), 6 deletions(-) diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 40593ac42a..b38221016e 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -90,7 +90,11 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp for(const name of names){const path=join(dir,name),config=readJson(path,null);if(!config||typeof config!=='object')continue; const next={...config,...(config.cwd!==undefined?{cwd:fix(config.cwd)}:{}),...(Array.isArray(config.args)?{args:config.args.map(fix)}:{})}; if(JSON.stringify(next)!==JSON.stringify(config)){try{writeModelConfig(path,next);}catch{/* read-only folder: the load reports it */}}}} - function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_.-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;/* A model the person pointed at their own GGUF folder (not <data>/models/<tag>): remembered, so a later load runs setup with that folder again instead of downloading the files (#3199). */const ownGgufDir=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))!=='models'&&existsSync(nativeFile)?dirname(nativeFile):undefined;return {...entry,ownGgufDir,contextMax:configContextLimit(cfg)??undefined,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,contextChosen:cfg.ui_context_chosen===true,visionPrepared:!!cfg.vision,/* The picture files are prepared when the run config has a vision section: the Models screen then loads straight away instead of running setup again (it used to read 'off' for every model, which sent every load of a picture-capable model through "Apply settings and load", and setup writes the arguments, the draft layer and the reader back each time). */images:cfg.vision?'yes':'off',draftLayer:cfg.mtp!==false,drafting:cfg.drafting??'auto',/* Picture reading is ON unless the person turned it off: no saved choice and not loaded is undefined, not false (owner rule: pictures on by default). */visionEnabled:cfg.ui_vision_enabled??(()=>{const running=[...instances.values()].find(i=>i.model===entry.model&&i.status==='ready');return running?!!running.vision:undefined;})(),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} + /* DeepSeek reads pictures with the engine's own tower, which is part of the pack (pack_gguf writes the tower's geometry into ds4.txt when the picture file was there): a pack with it is "prepared", a text-only pack (made with --vision off, as the app did before 0.2.9) is not, and the Models screen then offers the one missing shared file. null for every other model. */ + const dsPictures=cfg=>{if(cfg?.arch!=='deepseek41')return null;const a=Array.isArray(cfg.args)?cfg.args:[];const at=a.indexOf('--pack');if(at<0||typeof a[at+1]!=='string')return false;try{const t=readFileSync(join(a[at+1],'ds4.txt'),'utf8');return /image_token_id/.test(t)&&/vision[.]num_hidden_layers/.test(t);}catch{return false;}}; + /* DeepSeek's picture switch is a pair, --vision on|off, in the saved arguments: set it to the person's choice at every load (on only where the pack carries the tower). */ + const dsVisionPair=(a,value)=>{if(!value)return a;const at=a.indexOf('--vision');return at<0?[...a,'--vision',value]:a.map((x,i)=>i===at+1?value:x);}; + function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_.-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;/* A model the person pointed at their own GGUF folder (not <data>/models/<tag>): remembered, so a later load runs setup with that folder again instead of downloading the files (#3199). */const ownGgufDir=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))!=='models'&&existsSync(nativeFile)?dirname(nativeFile):undefined;return {...entry,ownGgufDir,contextMax:configContextLimit(cfg)??undefined,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,contextChosen:cfg.ui_context_chosen===true,visionPrepared:dsPictures(cfg)??!!cfg.vision,/* The picture files are prepared when the run config has a vision section: the Models screen then loads straight away instead of running setup again (it used to read 'off' for every model, which sent every load of a picture-capable model through "Apply settings and load", and setup writes the arguments, the draft layer and the reader back each time). */images:(dsPictures(cfg)??!!cfg.vision)?'yes':'off',draftLayer:cfg.mtp!==false,drafting:cfg.drafting??'auto',/* Picture reading is ON unless the person turned it off: no saved choice and not loaded is undefined, not false (owner rule: pictures on by default). */visionEnabled:cfg.ui_vision_enabled??(()=>{const running=[...instances.values()].find(i=>i.model===entry.model&&i.status==='ready');return running?!!running.vision:undefined;})(),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} function installRoot(){const found=[preferences.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} /* The settings file Strata Control and the installer read (control-runtime.mjs sets STRATA_SETTINGS_FILE to it): the app's data folder is written there. */ function controlSettingsFile(){return process.env.STRATA_SETTINGS_FILE||join(dirname(componentsDirectory()),'app-settings.json');} @@ -163,7 +167,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp return result;} /* The folder the person picked in the first-run chooser can be the one that holds their GGUF files (or a folder inside it). It is theirs, not a Strata data folder: packs are never made in it, and a Strata folder around it (<Strata>/models/<tag>) is used instead (#3507, #3424). */ function ownFilesDataFolder(candidate,args){if(!candidate||args.data_dir!==undefined||!args.gguf_dir)return candidate;const same=(a,b)=>{const x=resolve(a),y=resolve(b);return process.platform==='win32'?x.toLowerCase()===y.toLowerCase():x===y;};const inside=(a,b)=>{const rel=relative(resolve(b),resolve(a));return rel===''||(!!rel&&!rel.startsWith('..')&&!isAbsolute(rel));};if(!same(candidate,args.gguf_dir)&&!inside(candidate,args.gguf_dir))return candidate;const models=dirname(resolve(args.gguf_dir)),top=dirname(models);return basename(models).toLowerCase()==='models'&&/strata/i.test(basename(top))?top:undefined;} - function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port','gguf_dir'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);/* A model adopted from the person's own GGUF folder reports that folder's parent as its data folder: it is theirs, not Strata's, so a second preparation never uses it for the packs. */if(args.gguf_dir===undefined&&existing?.ownGgufDir)args={...args,gguf_dir:existing.ownGgufDir};const data=nativeDataDirectory(ownFilesDataFolder(args.data_dir??(args.gguf_dir?undefined:existing?.dataFolder)??preferences.downloadDirectory??modelsDirectory?.(),args));if(data&&packaged&&!args.data_dir)rememberDataFolder(controlSettingsFile(),data);return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),/* One card is "gpu", never "gpus" (the installer wants two or more there: "Gpus='0' is not valid", #3203). */...(/^\d{1,2}$/.test(String(args.gpus??''))?{gpu:Number(args.gpus),gpus:undefined}:{}),/* Picture reading is only downloaded when it was asked for (Read pictures); the default stays the smaller download. */...(packaged&&args.vision===undefined?{vision:'no'}:{}),confirm};} + function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port','gguf_dir'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);/* A model adopted from the person's own GGUF folder reports that folder's parent as its data folder: it is theirs, not Strata's, so a second preparation never uses it for the packs. */if(args.gguf_dir===undefined&&existing?.ownGgufDir)args={...args,gguf_dir:existing.ownGgufDir};const data=nativeDataDirectory(ownFilesDataFolder(args.data_dir??(args.gguf_dir?undefined:existing?.dataFolder)??preferences.downloadDirectory??modelsDirectory?.(),args));if(data&&packaged&&!args.data_dir)rememberDataFolder(controlSettingsFile(),data);return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),/* One card is "gpu", never "gpus" (the installer wants two or more there: "Gpus='0' is not valid", #3203). */...(/^\d{1,2}$/.test(String(args.gpus??''))?{gpu:Number(args.gpus),gpus:undefined}:{}),/* Picture reading is only downloaded when it was asked for (Read pictures); the default stays the smaller download. */...(packaged&&args.vision===undefined&&args.family!=='deepseek41'?{vision:'no'}:{}),confirm};} function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,...(error.details?{details:error.details}:{}),finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);} async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}} @@ -295,6 +299,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} if((cfg.mtp===false||cfg.drafting==='off')&&Array.isArray(cfg.args))cfg.args=withoutDraftLayer(cfg.args); /* The Qwen engine's --vision stands alone, so it goes (with a picture word after it, if an older file has one). The DeepSeek engine's is a pair, `--vision on|off`, that setup wrote and the engine reads: it stays whole (taking out only the name left `off` behind: `--eos 1 off`, "unknown option off", #4358 #4359 #4505 #4507). */ if(!cfg.vision&&!ownEngine(config)&&Array.isArray(cfg.args))cfg.args=withoutVisionFlag(cfg.args); + if(ownEngine(config)&&Array.isArray(cfg.args)&&args.vision!==undefined)cfg.args=dsVisionPair(cfg.args,args.vision==='no'?'off':dsPictures(cfg)?'on':null); for(const arg of cfg.args??[])if(arg.endsWith('.gguf')&&!existsSync(resolve(repo(),arg)))throw new Error('An engine argument names a missing GGUF. Restore the saved arguments or repair the files.'); /* The app's own choice of request slots (4, fewer where the card has no room) is part of the configuration, so a tune measures the engine a load will start: slots take VRAM from the expert cache. */ const parallelChoice=packaged&&!ownEngine(config)?chooseParallel({config:cfg,values:args.values??{},hardware:snapshot.hardware?.gpus?.length?snapshot.hardware:{gpus:hardwareProbe()??[]}}):null; diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 18a5ff7ef8..d5300c6193 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -241,7 +241,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(loadedSelected?.metrics?.engine?.drafting_note ? <p className="small muted native-spill-note">{tr(String(loadedSelected.metrics.engine.drafting_note))}</p> : null)} {roleCards.length > 1 ? <GpuRoles cards={roleCards} roles={effectiveRoles} custom={customRoles} recommendedRoles={recommended.roles} vendor={engineVendor} disabled={!!active} onChange={changeRoles} onBack={() => setRoles(null)} memoryGb={selectedSize ? memoryNeeded(selectedSize) || null : null} ramGb={pcRam} spillGb={selectedSize ? fitOn(selectedSize, fitHardware).spillGb : 0} usedBy={i => usedBy([i])}/> : null} {tr(roleCards.length > 1 && (native?.hardware?.gpus ?? []).length > roleCards.length ? <p className="small muted native-cards__note">{tr('Not used: {0} (another make of graphics card than this engine drives).', [(native?.hardware?.gpus ?? []).filter(g => !roleCards.some(r => r.index === g.index && r.vendor === g.vendor)).map(g => g.name).join(', ')])}</p> : null)} - {tr(selectedSize?.images || noReader ? <><div className="native-image-reading"><label title={noReader ? tr("Needs an engine update") : undefined}><input type="checkbox" checked={!noReader && vision !== 'no'} disabled={noReader || !!active} onChange={e => setVision(e.target.checked ? 'yes' : 'no')}/><span><strong>{tr("Read pictures ")}{tr(noReader ? null : <small>{tr("On by default")}</small>)}</strong>{tr(noReader ? null : <small>{tr("Understand photos, screenshots and charts. The picture files download automatically. Turn it off to save memory.")}</small>)}</span></label>{tr(expert && vision !== 'no' ? <Select ariaLabel={tr("Image encoder device")} value={vision === 'yes' ? 'yes' : vision} options={[{ value: 'yes', label: 'Automatic' }, { value: 'gpu', label: 'GPU' }, { value: 'cpu', label: 'CPU' }]} onChange={setVision}/> : null)}</div>{tr(vision !== 'no' && installed?.ready && installed.visionPrepared === false ? <div className="native-vision-missing" role="status"><span>{tr("Picture reading needs a few more files that are not on this computer yet.")}</span><Btn size="sm" disabled={pending || !!active} onClick={() => void download()}>{tr("Download picture-reading files")}</Btn></div> : null)}</> : null)} + {tr(selectedSize?.images || noReader ? <><div className="native-image-reading"><label title={noReader ? tr("Needs an engine update") : undefined}><input type="checkbox" checked={!noReader && vision !== 'no'} disabled={noReader || !!active} onChange={e => setVision(e.target.checked ? 'yes' : 'no')}/><span><strong>{tr("Read pictures ")}{tr(noReader ? null : <small>{tr("On by default")}</small>)}</strong>{tr(noReader ? null : <small>{tr("Understand photos, screenshots and charts. The picture files download automatically. Turn it off to save memory.")}</small>)}</span></label>{tr(expert && vision !== 'no' && selectedSize?.sourceFamily !== 'deepseek41' ? <Select ariaLabel={tr("Image encoder device")} value={vision === 'yes' ? 'yes' : vision} options={[{ value: 'yes', label: 'Automatic' }, { value: 'gpu', label: 'GPU' }, { value: 'cpu', label: 'CPU' }]} onChange={setVision}/> : null)}</div>{tr(vision !== 'no' && installed?.ready && installed.visionPrepared === false ? <div className="native-vision-missing" role="status"><span>{tr("Picture reading needs a few more files that are not on this computer yet.")}</span><Btn size="sm" disabled={pending || !!active} onClick={() => void download()}>{tr("Download picture-reading files")}</Btn></div> : null)}</> : null)} </> : null)} <EngineWarning native={native}/> <EngineUpdateCard native={native} busy={!!active}/> diff --git a/apps/host/src/lib/native-catalog.ts b/apps/host/src/lib/native-catalog.ts index 5b7fc8ecba..c0332093e2 100644 --- a/apps/host/src/lib/native-catalog.ts +++ b/apps/host/src/lib/native-catalog.ts @@ -12,7 +12,7 @@ export function nativeCatalogModels(families:NativeFamily[]):CatalogModel[]{ if(!families.length)return[]; const groups:CatalogModel[]=[{family:'qwen3.8',title:'Qwen3.8-Flash-Next',about:'',experimental:false,images:false,sizes:[]},{family:'qwen3.6',title:'Qwen3.6-35B-A3B',about:'',experimental:false,images:false,sizes:[]}]; for(const family of families){ - if(family.family==='deepseek41'){const sizes=family.sizes.filter(size=>!/^UD-Q8/i.test(size.model));if(sizes.length)groups.push({family:'deepseek41',title:family.title||'DeepSeek-V4.1-Flash',about:family.about??'',experimental:false,images:false,sizes:sizes.map(size=>({...size,sourceFamily:family.family,edition:'',images:false}))});continue;} + if(family.family==='deepseek41'){const sizes=family.sizes.filter(size=>!/^UD-Q8/i.test(size.model));if(sizes.length)groups.push({family:'deepseek41',title:family.title||'DeepSeek-V4.1-Flash',about:family.about??'',experimental:false,images:sizes.some(size=>size.images!==false),sizes:sizes.map(size=>({...size,sourceFamily:family.family,edition:'',images:size.images!==false}))});continue;} const target=/qwen3[._-]?6|35b[-_]?a3b/i.test(family.title+' '+family.family)?groups[1]:['qwen','swift','coder','unsloth','gyro'].includes(family.family)||/qwen3[._-]?8|flash.next/i.test(family.title)?groups[0]:undefined; if(!target)continue; const edition=target===groups[0]?({swift:'Swift 1.5',coder:'Coder',unsloth:'Unsloth',gyro:'Gyro'} as Record<string,string>)[family.family]??'':''; diff --git a/apps/host/tests/native-ds-args.test.mjs b/apps/host/tests/native-ds-args.test.mjs index 5decca51df..23a5f63f50 100644 --- a/apps/host/tests/native-ds-args.test.mjs +++ b/apps/host/tests/native-ds-args.test.mjs @@ -105,18 +105,60 @@ test('#4358 #4359 #4505 #4507: a DeepSeek load with pictures off leaves the --vi } finally { await f.native.close(); f.cleanup(); } }); -test('a DeepSeek model with pictures on keeps `--vision on` too', async () => { +test('a DeepSeek model with pictures on: Read pictures off in the app turns the pair to `--vision off` (the app lists the switch since 0.2.9)', async () => { const f = fixture({ args: DS_ARGS.map(a => (a === 'off' ? 'on' : a)) }); try { await f.native.refresh(true); const job = await finish(f.native, f.native.operation('load', { model: f.id, vision: 'no' }).id); assert.equal(job.state, 'done', job.error); const args = f.saved[0].args; - assert.equal(args[args.indexOf('--vision') + 1], 'on'); + assert.equal(args[args.indexOf('--vision') + 1], 'off'); assert.equal(args[args.indexOf('--eos') + 1], '1'); + assert.deepEqual(strayWords(args, new Set(['--pack', '--max-context', '--eos', '--vision', '--dspark', '--dspark-conf', '--prefill-chunk'])), []); } finally { await f.native.close(); f.cleanup(); } }); +/** A pack folder as pack_gguf.py leaves it: ds4.txt names the tower's geometry and the picture token when the picture file was there. */ +function packWith(root, tower) { + const pack = join(root, tower ? 'pack-pictures' : 'pack-text'); + mkdirSync(pack, { recursive: true }); + writeFileSync(join(pack, 'ds4.txt'), ['n_layers 43', ...(tower ? ['image_token_id 128815', 'vision.num_hidden_layers 32'] : []), ''].join('\n')); + return pack; +} + +test('a DeepSeek model whose pack carries the picture tower is prepared for pictures; a text-only pack is not, and says so', async () => { + const root = mkdtempSync(join(tmpdir(), 'strata-ds-pics-')); + const seen = []; + try { + for (const [tower, vision] of [[true, 'on'], [false, 'off']]) { + const f = fixture({ args: ['--pack', packWith(root, tower), '--vision', vision, '--eos', '1'] }); // (one at a time: the fixture sets STRATA_INSTALL_DIR) + try { + await f.native.refresh(true); + const m = f.native.state().installed.models.find(x => x.model === f.id); + seen.push([m.visionPrepared, m.images]); + } finally { await f.native.close(); f.cleanup(); } + } + assert.deepEqual(seen, [[true, 'yes'], [false, 'off']], 'a text-only pack: the Models screen offers the missing shared file, nothing is fetched on its own'); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + +test('a DeepSeek pack with the tower and `--vision off` in its arguments: Read pictures on turns it on, and only where the tower is', async () => { + const root = mkdtempSync(join(tmpdir(), 'strata-ds-pics-')); + const got = []; + try { + for (const tower of [true, false]) { + const f = fixture({ args: ['--pack', packWith(root, tower), '--vision', 'off', '--eos', '1'] }); + try { + await f.native.refresh(true); + const job = await finish(f.native, f.native.operation('load', { model: f.id, vision: 'yes' }).id); + assert.equal(job.state, 'done', job.error); + got.push(f.saved[0].args[f.saved[0].args.indexOf('--vision') + 1]); + } finally { await f.native.close(); f.cleanup(); } + } + assert.deepEqual(got, ['on', 'off'], 'no tower in the pack: the engine is not told to read pictures'); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + test('#4504: the reserve field and the resource preference reach strata-dsv41 as --reserve-mib, with no --pool-workers', async () => { const f = fixture({ vram_reserve_mib: 512, ui_resource_profile: 'work', args: [...DS_ARGS, '--pool-workers', '20', '--vram-reserve-mib', '512'], args_written: [...DS_ARGS, '--pool-workers', '20', '--vram-reserve-mib', '512'], user_args: ['--pool-workers', '20'] }); try { From c021f48d76ace4e324aae2c087aaef563ba50b2a Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:36:28 +0100 Subject: [PATCH 56/59] ISTA-DAS Coder: its own expert profile (519,422 prompt tokens of the calibration texts) and tests --- data/dsv41/profile-coder.bin | Bin 0 -> 33024 bytes data/dsv41/profile-coder.bin.sha256 | 1 + tools/test_setup_coder.py | 24 ++++++++++++++++++++++++ 3 files changed, 25 insertions(+) create mode 100644 data/dsv41/profile-coder.bin create mode 100644 data/dsv41/profile-coder.bin.sha256 diff --git a/data/dsv41/profile-coder.bin b/data/dsv41/profile-coder.bin new file mode 100644 index 0000000000000000000000000000000000000000..743376500de93024f228a15afa3f1fec32e14c85 GIT binary patch literal 33024 zcmeI*ca#-X*Dm_n-Axn$NrD8)IW^tnoO8}ONS2(lWF#n(6hsgS3L-&4%pfR;V!(uC z5d%T+H4Dc3TlRRz@Q(9+=R4=zbI)IgF=|xps<q~P<};r)*Q(mJo9SnwXiTaoDpoLx z3Kx%}ZiS+#evT+A-yw?H<c^}R?~I}j4Wp=Gy(pUOTGbj+bSh^QWojBlzcq@Y9aW+z zd#NbuI4+7lZxcm7b&jG>*%>!Eiq@BnqSx|9QFrazH?Y^gptc`ojiNuCyVvI?d{izR zMG5(%=-rA@G_`yb<t`UR3rj~)mSRzKXZ9$%7>lA>t)i&2J~InM(KpFa^jXa)nwJ<w zrAtQ98~l8fIf{C-aZAT2N}d=+)k7@oooXf?cJ}M@Zc-H0tHnM{`JC%L9M-{6bVS>B zeBRJEtJn|ZiK4FB-UIU^aFl8hMM=4$XkANNbzJp`qRjSnadg48I$}P=)<f(rg)cLE z3&qyOwK@4<=kqCBoiS1LF}pw4#{uq6RgR*$V!u%#itei_PM@E>-Eo>I>Liwvu=ivq z$ABn$peQcISvyk{t>ODaSf;`}vyAib4!=8!ejF4<8SwXIUHo>6qLutFg5_U6*SsT& z9>>SoB2iRUzgTU3e6GRnsq}0*ZY}=F`j3P0E%@?QilSEVy`3Ew+7;>-MNh-fcwiLu za{l=?xQG3=68f~oBMrSSA4i>A$;V#(HtLhl=NH8Mi*|?D%!HHlVz>-b2K#ZXqo|Qw zro-{x=5)h;2{A2_^KI<i(B>T6)7ft%-hLUPXjIlH>R&C2US{)E8ZD3sC-hORbQCp( z^$2`-)7nP7KFmg<bHC#3s{9<~e<(a>^c&qRie7Q;?XgjG0#D!Ly%M|gaIrYV;N0u@ z*_s8<4@S{nbkvddI*MZtZu7ws;bbM=_TjV=O?;u>a=5zK7CUz@|6jv$L2eg`A-P5r z&4%~7b2D;8(Q(J+#zoOFe0(LYi<ylr_+EE@2)|ziJ4@gUpT(HZxukON<K#vanr#|I zhf~qXtzxE~7c0^b9_|<!Ma>eT=oz}I5BCT3`LJu9={J$Ceqi?^Y*X#u=DVG^i>HmE zVR1NyZ8Bb#!+f5fJLKo8?I*aRmyACcKW;20u`Cqx(>Ps3<0rK*!d4yp51dGc@|B7G z<&In6X-fYndS70<&_-H0j%oV?ee6$)qMbd}1AI53gY)p`%^gLT^gj)AZ|C>mye<qo zaF`L_w~6O&eBCN%<+YhApK&o`LL8N~{f3Q1V`8K8`|*@(w6WQUruARfM0{I~SGaq$ z)yMfqotp{kP5u+Q(Gt9e*zYQ)Dq_3XU7aZ&MO(x$2;NoBf3{go<EI~g9mLU4pAC3< zxS{yuz8?<r;U|)}ann-j&;%SFbv}!jp6e1tX<*1A*2DJM_}Tk}>+GznLnr&AXrefG zIDaVvp0&HbfI1<D*=wVyD4rj6yh*-xrlCC=Kgm~C{5)iv5f??fVfoPY@_gQcn~$5* z1sl8JFV!@qCO<C^=kZtxzvmr4W&5reZ1OaaMwfS$w|Mm^L+tOd-<H<qzD4sjqi7o3 zso@wfT&_Ar(R=tV&3738ufkFYFUdHXMRWPI%~d28Wu(XUd^Oa+R9ZG#n};?Ue=XE! zadr~tEEwMECr7u)i9D<w6h+%%s$LzxY^A*iu4++qg@)^~)6BTIPh9=vuR6^h#_c4! zD1QZC+0^3jIioz_vy~iXs1%FV$wdKJim^LHzZjeqD;saP$t$Kdu4lyI^YL`t)0muz zTljLNmrHH7x>iPxF3bN$<8wQnvx<8uEY+Ml*(i!ein#!uW3+QhE{2L_r2e(Ue+cd_ z1C2Z5`F(9)hb>_I);<&8E8}BPxdz6L+|0w%CC8O$^u=_v!&gi3e*@=Q{rAK5coqHR zYXd$X)oywd*Z3c#&1(B^#MzgfgYuK>F7twZN2|&izW&nhB{n)_ilP<GT$jh6Z!?x- zG>5-jFx>`k1^GBz#~dL3bKRq;x$}P-4}IBRA+~qAnWtRaPQ%?Q%P}7Z<*`R9F~V^k zH|@mOL5?TGaw<Xod#O8o75y<qmw8+db55Ja#$87_ggdlvpl0L=$1~K$7UmVaE@gKz zO;lQ9JUVW~<~O!8ZRG}U-_hWC8jN7PDUV_Ph{Nq7ILFIXjFykU)WY}-^II=*zs%2B ze(x1)SMfa|UxE8t+D_$vrgL?co2zhk0T-`}aVNZqxSN85Q2$@b97TOzS9f99fSb<t z%Li!hcyB?P!|O#jPwMjk|7&1u&F*TP&GES>JKxFgFStyy<)+i9mboO2v4M+a-PHhn zs+Xaok|})6meXI^t}VZXTEhv$db%$JTc}qr<Np{R`|$Lc<IiyTC7T!dI`U;Ks?w8Q zYV&U_4DT0<y3ptu{ocdjr?fSI?fK$gCB8`y#6=@U7+W|iEMG5+;~ug7STl+q({>F^ zXZ6b<hN!guN$Rz&58LP1c^a2Li*s5L@!g?D;c_y(-xe}2KNm$$;^tAfZZEE#v2oXT zY8Q=cqs5>2KQ!9<OdMCm6V{obzO=F5K+gs3uk#<)Q|;hd&tF%zyRtb*4w}QeTKikr z`ceB#xY&i$sy?65{%O3t#cxZPcDHh_hT7u%%DURqL`Qb|!yM+8H^lbaow4ZBf|Qz- zDFa?{`n$G|>R(LW+u|rOH5!`9D?ed9Tv#kOHmYUy_!Y-_zCWSC#7?-?e~=hn7iamq zX$Fr4VSY`%&ra0`mO*&SMyGG+S3DhTFg?-N+{ecN_MdZpXm8_CF4Cl@Yd+qSyRmKL z0p_P*tNx-q(^HA3j0g5-$W0r#E{N@Se7(ZQskP>K@xR1pwjT1b)RL#O`YLxB*_tZn zE#&DV82jqiOnlwg7}Xw!a0DG6Xo~Ocv{^|#ps%H{KFMaSnsn07{9zp4r|)@~KBLux zIGhg89`O!kYpYy5(byQ0$531E5y#*Tv`iO;^tpzs5ySB)u6ObMvDoLpyPEHpaWilg zTd<r?G+)R|t)9lcoQz{P=r`6xUBmSh+i-opVq<Y-`cea`!yGTqyBeBj@RK%P9Ae$Z z??$l?aV-aacZjDRjM>|YzkvCJPJY3~AN)Ol%V!J5qOI`8aP}#E&-^4Vn#fNfTYNS4 z_rfpkM>_dDOsz{}E`lel@gsKn3~)cB?R?ip)9zW?UW(&ld=Fvwu$a%{;evQq!=2Um zTCRNs7%RbhSo^TnI8jO-?YH78oS%;0{5bf`=XP-Zi1#CW{Ls=kx4p}5-;(N0A2G0h zk)7URFD6fEo71XXOzKV(a30it0iSDN2sI+iA9vvFj$~_GxqP>#aao5p*z9aSKX6E6 zXS7)$mKLc~IE(b1j>FTN)h8HlYMUf~6ZOj<$1fZK%j4zoS(wIYC_PT@(kGYwZ`F;D zJl1ORd(?g?ADgmA(FA_-!aoYeP;bJ0#0;7WHGe`S{>1d0c9-A|>yw;vu!WyS{LaJA zTDF$q=wWe;c~l*emnyjWh5uMp>(lwL!F!JXx$OL<UH*3Z@HtKYb2!)u^8}yoORG-9 zeo^~VZ1$gEj?{1Mt$f4sTgR07F4T_R8O+u4+?c(jw(_lgOsp;S-P9pvE_s;!Bd)hB zr)JWA5Bl2(-(InG&q7=D6XyEOZPXRlW{Lg0>osullF$2{|6bdEwDB?fSK&{Kw>Rja z8~;aaD@vI&`I!J~lKz{!<7OBhwEvu)5br$un?C0^rXE=w7k!r?CT+hHR}=O^K6;3| z*Wi?O>Sj5g{1=_e)mP3vsQ;S{q9_&K*2`r9TT*Lzz()<a3iHuec<Y`~w^q^|ZB`Lq zu_`HR+>CvV8$4H#<8=JqUCVkahqZrm_c@>7oUJgQma+9nhM)aO^0p7AZ0v_Q{X_Ow z!BbM7y>zf-i26p;Rh@4oA6s$MuvCN~I$dHtBJNYJm)19TAHKWb&3M=c*D>*g_2jei z^@F@LN@9Pp9N@PAE`GrIATgBZ>vsA0xV^E!&e$<9)-#sa&ZJEYhO3qMy2pBqPUi;f z^8d~yYkfX`l%EgmE9AA_rj;^{&3EkfrsZq;?{4IpSX$PX2eCcw{6tt5P1FvqQhd#= zV@!zeqF9pke}n#C!sX$*w9%DKn8RA~jL(A>#-hK(x2qL?v^$TBnc`_tJ}yebcKRCD zXT_}L>23lX#r0bYZ_m_X7U$D2&c(|@`N+?1SYvgErvmMKimTso&<Tz#z06f?hnjL; ze0yO1HXGfGGrO3Zm3A#_%9{TYjor%5hI8tC6}f1FdpV2ZJr`(U9^fw*TsxmPX8CH4 z!;a!j%ug$P_U0$(@h5oJ!h1hGj4!8VURS@0y1%mhjKiXMx|8qlEa_hSWM%hT{Xc+f z8J@!PkAtwjj_aMcUjxIjjGo14zsDFzw#9HZmi?NzSS+TwVwl0_=d;Y=?Na8*eEJ+{ z20JY^3iD%a8o<w*nd+@LceQuT^=W*ah38l8D^)b-!1>@ob0AIa=KD6+hVWAbm(%&Z zf!k;2#G+&Dj9%v+#JS7*EaPLxNcR`;gmIc>h1!|QXB@qY+oL7jmzMH8p*sIQk8yko zXHT*Jy_kL%f0D5=BF>m<X)9-pvHJuZk2Ro&yHoQ1Antd-eHkC;U<vhbH+$jP#wxa_ z!qbV(IGm1Uw|akZvymCTaIZCh7GB3isHNkad#OMydJx_)<{ny2YqWf>tr{`fxUFWq zja5%zYk;%E@Q&dl-21OE_FsgxE#Gh6LKC=s)xHSa-C@WL`)B%oz|R)fLJhBI>rCI< zVQ!75wQRQ2F3%2}YS-AdjGk`tUqUVq)w1458;h>sK90?$wDmZDy<oipQyw-JmY_8` z{E}X}6=#?I3klYbjl_^uU7?e2^&2V=w}?H~S}cijI#eDmdxnI!X>j+&*LKIr;(Nzf z>rD@1i@6`-_XoJ!@G%r$ja+{fzw6kY4(oYs!+NlVm_}AHUk|~bzM+1k)2{$LuU7S0 z+uiVnXDo;8%i5CRm<3yDzVqwz$|Kfh_J!&GLH){fiA7)XdlL^u<g#%o^$ecR<o;|O z{_%QR-yz~G21Bt2ana1W&AEAljTb)e_$n@%ONVd4d8wxH;o6ao#vMOhQj5*!Z^T_8 z$=DFXb#0I1cs~ro%35dO`iwY6?J{1=nQwf)A@^ZDeF2W<IBD*DvCi(djln83vQXb0 zxZWs+@cif+z6SC)K+d*kb42X#(Oea=U7&&6#Bvtb53+kxoRggUlJBs_NRO`<;2hpr z-sL!<fpHDvS++mQN3ZzEPD9VvHLqxQitW!~IG7ucS>vOo+CB`=3K&YCO{t%oaP>;1 zl;;_l^?koWEQ$;KG*Yj`Iv*$da8Q(wL+sRyu_=y8uDv#1-Gp`VT)1hkPa9*aKYZ*g z_Bq_&HmR+S71tl1-^)=R{${vVXa)}1ZI6p_IPVE(F)=<}5hr+D)0lq69=5r*g02;u zg8!0o&rj2C?qT(rK(AlAHdUX!d<+p|D>~}ZT>Ub)+{XSV8~En;GENc`&0YGP(WfU3 zY!cIK+hN=d<!6}K>$BCnhCcXhDVA{G*HIkHaS+?6URJio5KEZjE88FLU`?<#7RB@b zG~1`+`KE)s>^xsyP0%K15{-_wF2v_yW1xa-pN?Z^l)3`PY<{o6T8b{-q?aDXda2`a zQEIr>(MOm=1{ap=7Vz=Y6t^?s*^2+6Q*c2);aS^8wtC8OQfK!IeBLdl>)M~Kt|s!a z6P5(N!*k6SDjP%n=&viSh$R>9CQg=TeipZ(6XzPhl!LEI7ia^9NUlccJDT3wPvjf6 z>+-lxoA9jS228VHPB11;>6`sE+9*Q5`c_>8S9x<`f}G-EV+J)-zYpQe{fJs&EPhwk zxL_}*{u#uyq7tpJ^R#y3pAfgWZqe^6IlJWgXU0o-&QeC3?lfCmzRtMzQY|%>PCpU* z80YR2+dh82!fm|xmfAlqSJ&Z4q^WKV@xyQD)Y`X@qxLkoo2F{GuVnkQ(0}GP+y_?H zZc(BW_<k17hWOkr-%mI<+4b-E{1z9}+ZtPEjT5nl@!yZ_U&1)m=E>18(CCqB)(P;8 z5&J{z=aHis#%)^~YUsGt4LF^@ZMk`|KEB~iulAkfvk+_pw8_R_TQUEd#ri@VW5v}< z-fyyh%=5{uS?PKpAKKhzY$P?c&Z{YZu;=1u60AQCO{vS%H}YSFjS1GcO+5GK`yl)G z+TMWsVo!58Kl9{eKi)DnLIZxrv0GIh2Fg><S#&l#F4~2sr@P3fT-1c&>#}T#_f`I$ zcP;;QT5&xUyBS??-<V(h@3w_|yzty0tSQ2nNrZD0pFyW>?O!NPH~1ff^DTJDNDHmR zeXSmzV183R!n49p*q&odO_a~3xOykqy3Y0GG<ZLocfk~%wWfzLiNC_Q&m`_zj*qqw zx7eP~PXqd%smKrBPq%`ljCmL*%eAiv??aBixJA8kErV;VO31sug~U2$LM%$cS-7`s ziRZgvs!RtNwBN$_mp#~Fqk`+h#MX^ohREN3vGkVfUvRLNpPF^?ejGOEH;8rm0Xg2P z*1-C#Hnqj|AUmy#sulcgqPP3?o6JY}Zm^JZxt&Y5&iI6()<ttK3@6x%^j#&+x8yVz zKYe1xJUrn!OkLU?gtx=h)pju@N3ketYxgzH#DR|w)y6P3cFRL$wvKCmrmt~;v+B;D zw}tQYuJd)Uim?hq1$NVlt!qPV>1I!N&$^9+y!FlRY#d-CKQ8;i+`9t~@v?0aOmtF# z?UJd~XF1Oz|0l)1x}SA19JwpQ5@+pH&Uh1d1%9j2%wtXYa_;0D+~K51aT*d&EAg}} z4VSi=D;UGhf1*$4#p<1S0`{xgj8{`fIDST+cfUh}+0+Jo&a%14`O{(v_YyrFH=kyn zaQsAD<4sH@XzPYJ^NOh?-JKFcH!&?`>ka*Tvft0~{zlfWbhB=uIwS5dr`FQGULCcd zxp+qzYk261yP7zN#M<vxddF8;w!bMahTfi|!xf&5t-=3sIemz~y3W09JKo7Syv2P- zMQgMI^j(uqwfh)`sdTiV2~Dw4NgQ>jq}*rhm6K%oKTkvP;*6VW-f3stv@m{Yy$U|_ z^6?4`9Y){}uILHRBJ?}V=c~_%O|E{#VYQX=_^>f~Sq|iI3cm%#F#0KLg<|H`aeSBM zS58OE=?O7?Ta+I0^I3XzU=V%Uw^=|>^0R^8*>d{VGUwQv&=^j!hkN1LVw*G6eee)= zeO|`@r}*1E5D%G+iEP@_M$ZGZ26MNL=5h9N()7+^wi(8>{N0nJPV4`)eKuS@+h5IW zMbqLfMY~_&<z2qNC}`f{d+K2M5?6R0a>hQJSku6lz+W-(Y{YvTZ8Mgpp?KHXD2&g- z{5@99T0@^JIDJ^VthO7*OL#Vv8n%7>KdA59V&6vx?Z)DUhMM)neaqP2>$DYJ@SSL! z^)R>Bg}ni;;a`Nupw*SGU4^+&Q}OG&$N61sU;okC{kfF&&LljB`Zl1ud*O8Ih;|3% z>2aED4R>a^w$e*@M<LAB8Ta6t?OEDPDGr~QF4`K>Zb`ZSv>Ba>YeQ|iu43Hax2m?s zySnek%SiDied#=VlO2B}<}V#@O%h)gT5KhMz4)NN=hCQE@P)PXn1opLS{cuXU`-9v zEpq%7pS64r&;GO2Q=jEwEUpsf7#sNbl<jsCtS!V*>m0o#!%P>Aar8NEe+lD6J_oW} zojw}r|FOKSr<v4pULBv|KDJk<lzDm-KX>ecD*=aWR>x)8-Nv83Z;K^7YnYwa`NHNF zxK349UpAPJ@UmAtm)SlmCzFl0;+54twx6>d7T>Knd=(GHVa#v4AXn-1YpbRti6cBS zTc_<`d~TfV{!JX+`5lwqxZ!iG_@8}BP2%^ZS7Xud`gEy^&p3LAV=L}Iq4$pXS;toK z{Nk)>>}ogO=dLaFXQzm`mOA&jbKyRx5dV$jVOtI3(Y{Vm>rrtwz+boz-R5&1*BZkT z){4i(er+KibntEuvA|iCmQVC!`&oOsc#8e~xG#h6`Rs&yvg~XeXcLS6#KoD>v8aST z-NpYju1n5iJC8hdwMGrG@IOr)&&%EGG}w_IN;{q=rm*&}q+cKVa9{p&5!dR&z<wUM z>abVI_<s{0^TqdIiP+!I)#DxiO5a1pJGQ$#(a3ok3(xcO<NTg2Dg3=8rqu)JFP0Mf z{JzG>FxTWE|J$Zl__OJ|7N0-KSDx`O!hVLn7sH&Uq8Q-JE%x2|h3|###a#t4EXVmu zvF+sZZQRCO^D#Pxt81>6f}<{tOvKqP<KzOY+vAOqH?8I9t0(?zi*qsUzFUSyjl(hc zDeHVK_NMX?p4Zot$Ar$-J-7+q%ZzPkeyn58!_9RXxF4P{wpYSmh!z)hQjgjHw5b~Y zlH9h&v%cY-fGOI9=gq6?rQD|#GhS!ly>@#w36A07{7@XH#QmXmVU03A&YB*74dozw zr}hYZ6SPf~-x8_lijDp7p2UAX{j%~kJ!34|$<7zfjTgfuxX1I|LM#LExx8h{Gq`N_ zInr5kl%>-~G*Ma}9<@$dBxbha2e^lxY&<rHQNQrL$U(7HP^-R>|B?7>#^xhFe^1My zE;q&bFMpapi&}fIeZl8`VjNT7Ggx?IY&`cF9`TkJzUQ_397mgQIJ%5l>ilcsdy%GF zRZ=6w{8T^Z;R|c+kG1a!&k6i&8YAXDYBCMyaDLn%HK(IFOwQBQGPjRZ=in{@>xCsW z49h`$9GIt0_2tL4K75r+ZT;CzZKRoE+GLl*nru|YOQ_K=!0<Hx+u^$>*?P36^#K3P z=y)id78_3o+TCO)o_-Uj=*LcYW|`|&y1t9QrpA|RFY`aBx-~8yPU%}mZjaU0SB{p! zbA*pW`qfxwJwnHeI>-xd|B%l|ZQ&iDS!`^<`A8hyQA~XJjcZIZuzj1^J$DInf_|@R zQ)w8k=(PB7cyTm9ys7yf+zJ=$&&N@C2PwSs6Yi73Jp3x&U+6`ncxwrB0-V)pvy+&A z9j!fH-h#1@c0=mWPtI7>@NSxNu1z&_GrUXhF;?a6eLUPlOUL;e;`(+ud_<gUI^z^4 zC2>9#NB8fear&sj-}LO}2U~(X^uWulVqPZBf7zd4Z>t!dpqaYxm5DRnVLOh4!0ofz zwX185+|Kxc;VoD$!XLidxthax!SC6c_}QS3^M^~ai;wGg`k9@!{LO-I7_NTD<9d9Y zaD6-9)ANb7w0a@WMd8aR)}H%mwYRy3eoHrZFQs32wt3z45d%}!7tQGN(aJQ4<85%> zs_oZ~L(P0I-kgh*@Eqebzk%aD_wl7oRT@kj!sbMp;PVe$m4dm7;}>uro};$L*L`fh zf`@GEm8AQ@aK~^|vyJ@G=m9<sw=kCJVW7Tmsy9>h%|8xSoX^8ecs4dwUYFn_pBSHs z<k^-FwnsAIU*BW=q-8J6qbv2#2JhJf`b(BeTH4z{ZI^@P>EohLXfxX|nq>1ddn41P ze8<$-^~d@8k=>WYb`lTa9<!cvLmR8-;tBI>L)V+Z{Xr>XN6dGMZM!xZ_$%PJc%ppa z|LGCdhq$|1pABu3*>6w?rge1O#9S+9pUV3qwD_I=+ZVx9n=S_6eU<s9qdlJ5!}&om z^Tljy$j4|{zKXCLYG_qBhS0{8qVA1pxCDFA5xL{<)7OldI%+eH!uQhkOPGi765q(0 z3oow)p78ZOT+?W&IbCk6DmEC~!qZQl!t=z_bopfUSky_|*KyU1k0h8zcgHJE!acw@ z`YaRANNq0D*Jb+H+ZmsHm$};*8euKR=Rh27!q1XH#sKb)iMbma`yKC;*gy2|CDvEO zJ#Yb?vwMO6YqZdx-G9+p5pCDe;CIfIHYQ5RZ_yU9Xh_T$!qMEzDQo0|Vm&2?Gime^ zY<=U+pO?f`()`z&?+WHTyiD6?tQZFo{#xO5xbuT5s<pSO5je=r=PKvgbr5Uo*xwwy zgo6@EILBqF+tnU@f5-U)^zpLK;kiV1y52@-4H~9kT_cvN><)uD%;5vIFIdi6f~^nX ztl3TdtDz=|XX^%9V*h*Br{c2XC>+!6WwCFN$3I3|TePP~V=Al#Gm0q#zvtwyJ%1n3 z@B0n#*ws8G{vY{xlD|IF%+Y)$Xmc;#d(&yC-`{pL-=pA4O&p!D4&O|}Y216k^DYd% z=i#~)?LSKwV$IYJ$6fGVln-&0w9UiQkhXlm_n;g<)YLtqeg3+}d1IP)Ju^OM%hUJ= z)DN6D^LZ|ug%6tN3d2%I4JmJqte<jUvp3my;<$PS#&KfUXS^n9^On4=ajsy3=k?+# z?p#lNKOskDX(Ro3nDe^_#oc>&>8|ZVc+ZnvF4zgR`W@FN!JonTt<A;n{GGO+X}^Y; zPvUEKXLS<Bqxfu4(a_>+GVNc5wFaE4@V+d)*!BB}&n0}9k&n6Fne0NhzqB^i#6230 zxwO?;eiCr;k>l6-y@At>mDPOx!g}Ky$Im-|lf66iJD$$`rq4xNjy^cRSzh+{!v0)4 zbsV-!&FD}rr)%E?z6~@uKk}R|Nnib6(f126EfG^jytSgE@IGzF?#|hNnNi(!t|lz? zGtlL&bOK9XpL4>I4-e}q8C$f_YPou~)|g@MH=M4Ax19EI##dMereX8l)z(9Dd>>vG zWTGkYq!sTroW0!Nd?D5&@P=oskH8mq5@voLa=qgKec;KofR1iA7R6H^&t2r}d&e)~ z^zE6(86L9IM)3q~a1quW%VF68Q+U7p5{^IUqF*t&s*tjFVlrBQqws7ry!SNo5n7S= zu*M9}WbQI19)dfejrD@~!fzNBO;Hx?m*8!k?N>2%g)uGr4e_vKupDPLhc%*0w&UaF zRlBf0Ix$oYZVMky2h;FL_*%GLfbV9V)Va~dS}JoiT*K|}zGlwQcRoJ%7oivX#@aXX z?(A@RIxWx7Jcp||+`@DYj$Sy)$=*45W_2~E;^k-dp7Z%d`QOQBcn120^W)Q~!M1nd z{QQu60$l!7GA=q+)w;PG|LlZ&%+2yx#un;S*Zb%m7w5#C7N&mshc)K`*Q(bSlk<Pt z&P??^6uaBRnhKZCguKdccrJS!j!9L_ZzViWlIN+}%{?$>sit31b9O_R<s>{u@3~y< zsH3)s`*WJf%yzhMohgSiw7nt5n~l{X=kt!DExebe>o2swlxV!yw*DNKvSz>0PhFd1 z?2L6y``d6hi2nlYJj`FXXKy2pDCA4*0e=>J&ZNUK>0?p)islG$oYr;_UHnXI{b74X zZd<od6Z8-7jWv+lRQi4B`cCaj;2^8mx^yw7aIwMp7nT|;;=2RBoO05d-|)PmCp>LG zHmB87+g_s`d97EB7F~ZeH%*KE=lhMlQtUatyFU!@X5_Cg-+A~emu%j^b9m3;n~BzY zxR|W}Xt;9m^(dcrh`*V(N9U@UxPM4)g68MtPpRFnyB;u%i!;7xCDhyP^88D0<3E+W zwN-PpKf?dCN%&$rt_fQu<N>eYJ;YD(x*x7n;=lBuHIvv9ad;%bI_PC<l#({rI@tFr zZZFO*_Tj$2zS{C)Vcff3R($!`JKdfZwXN;?r?`yRA9LM(g6j$JuGW4uzD~<sbsFmH zTzZ^@cZ?>9qpLi15px+D*ej+3+BT?wQ*-8whOy|r>F&Y!dA}@Ple~+gZ%*-z<Z~`A z7R2NUp1m#Qpqu-Z#?~`zR^lss5B8Is{OeA3@f3bjk<PX3e1sgnBA2Q4uPA5z*uQ5G zec+?y(=<o_tKk~cOD#MNi#Bg>HcsflSKd*6@m^_SU9rnvE`MPA_B&!xrb23&ytRMF zIFO&3#%+Hb{8`1g%R{enQM0%j$<L|OYLWAUXl~Jc#>X1ktWS&lekrEb;=V<0!gqfi z<u4b#41pmNyWxBL8n?ohkg}eeYyUzA<43=1d(?$Q`Pb$tdb_hUe&Nn2-)rgh8M(NB zzHwWV7RA2^ua|L@gP(ds@uyFCCwVLmTEiZ`gG`psnvLjDtQ+<DguQRf50A6gQM)mZ zo3mTGC&c;iC2%!0U&-V5+7{%0T2bSkMlawvyh9Y;-C1KyloHd6a<xHz-h=BkdA}yE zc%S#d^p3u_Z+9;(Uk|XoyS7}}*LE(^xoAf$I&i;y<LY6&)PnC4es?ybbC<Wm9)mA@ z|8f0<Jn=X80<LkMpPfeSo!2KVpI_&fbNN^U$EV^dB994`)CuRCvok;}S?qg%B%kol zXo0&7YIJLJjGUFyuC#m~p5-|M4Exy6Xl&0bW-Rj)o*RW{PJ8k2yS%=Q_iPJN=FEHb z%Z%gS+1bGV9=5`LUWPx6N4dy0!n$^}=S}uC^sVCht72L@+<XATy>;bOY_)K57w(_4 z4K9?jrnu0-xT%KU^fopx!V`W6xU@W6#&kQrYst@-2pd|*`b69C?)gL<OoMkZyhY@r zTxT}L6uyVQTfe8AyO++M#L+Qr!ac)nIcOubbq8&P?+WjKi?1?liD};u*YJ=-K5DbG zVuJP1pT;0uGp4Yo%>!9!M_i?FlV7{$jg84cbjfbb`D&wa@Q%1X#=}$HjAxvN`?AU~ zg?onYa;dE_Kd<lVJB&RzFR^=1Lz*gL{^$2WJT1%zqy9tn`)jE2E{4yv--qi(d~PdY zZGrES{qTi{<M_Q@|HH;ZcHHEuX^y0svGkddy+qf-{n0SjyBx%+oSYKh`*^+Axny=X z$=T2Po|+zuI_Uc)40B;S(_H=EPOC5`vA0KjOU2($%&*H$Q=EnS$*b(=m?BR5ElrF+ zn8SAi@5$qSInB?0p_VYwz%}vDsRoz$vx;XCUkhCi@6K0hB!6`L$Zhf?&UNq?(&uai zb=kR_Woc7<&*E~l?OnNCt4;Xs^_u;vihR++dOq)GGkZIH;3xc!C7&1u!E_*<T){c0 z4(*8J8V&YOwjP7I*WGkkhMx!EvEKy$0+_lsupToOlkgF~j~Uy8Mn+g8>XTy_4X_uU zZ+;?%pyQ|E4Qu=GyOsd~r*=K@eV=_h96rxa_&wN*a6f5WU(r6i^Y;-hi?crpo~7{a zVyk6G;~rOs9nTj>HaQEwFPZ1umtvjm{2H9*cCASPH58V0*VIPb)P(;^y_E4<IEOg- zT;=?HJ_~C<gN|y;#U8f8J>J6VV!GXYJ4!n|g?sgBaIF}Sg6om-ViM1NO|63h*Td-? z*B{H{_*C?Q^XWZpO^lCKDbIX9jkE4AWt_=hb2V~fqPXQT{NCWVme!U<#K_NA@|P%% z@H>!OVSaL^Is!|6pL5^pnG&qG>%T8E{j4`f!%-H0wbJ5OTra~hyjCpA!(MpTtp_fy z@OkGuY_NYCZ!f!c+?bB%H++xZC$*Zz&Mj$-H*M$RKa8d6a<tvK?d;wskGu5g$^HO+ zew?l^tYwU&TYJIp_%Yg8s^)yi#s@ek*~0jOHT@)OAUT-oe2o9G#(%i~osQEu+mT1q zap!_QUgKl>K%3m3xy8L6-VU;RKOg0Bl@s4_+I~Y*;r-W(Fz)hs7hEOVSvTgyE1oOi zYO8pkh5v?az(IC8rK~H<x1|qQe$eJk+Yo)a6qJ89f5!9usXSwVuZkF|=$lSHj<OZr zo!wjphwsFq?&4}Ge^tdD-XH8h*PCz=-tAb^%ACK<n9gcVyIDTq{z3o0v}ykY4Dh}z z&JWq@%g3KHV^IUxzoy~iOUy5K$O-+NtYeJOU$LFI<?p-uQs(!o{49Wb8oh2zFotT0 z6Hi%JSj(~**0GPvQFwNpo`zPrzLC9`@fd#3ms{H>;apeE+|-i(9yFhdxr<nK8yBbY z854XDrm^rFtK00WvemPM@q~};d=_VC_vP5%za#Dncdump!TKmI6~}K_`;^sw`%Jaa z{yR3GXJ=G>{%Q4Kd@OonsCj`da=12yhHI4MkKL=dN`NH|+%<6bR5SApPCqNBj^eO9 zA6EyeF*F<QdE@jQIS99RnX41Ub4l%y-!jA0HZkwTaesKiJD}?uS!>hVpOx5f?(@Pa zYnkWiFucQ5pt&4qf37r+@G}vPZH~it-8o=?X`MFm6P|6gC`70Huhl;Mrf4qvFVj+S zdAX_2a9HQRsMf~RG?;&&hsDO@L2c^8`;hp*q}9Bzyf0s29a`7*aQ~IuU0fAt5w2<C zJi^CzISap$xQ^?*#Zu<7kgL@*jRP9}TAT2_dU${1m!Jpn^kU})?O&0{op9VyMLlyp zvwcQ+D0!ULB3hu6%wh=ZxLwYNcOAn!6{qm{sQiYpSOJbFaJEPPfu3b{^*ICld+1;e zF51a&9eg}e*O(G(G5NY8_i5#|5>CQ*KsjMN?sGcWzDh3!x;)9(L0pCJ^uoG0+-HS% zQ_egNKYOd><TRhTo5}&6cEI_woM*=A@N{Y$j&9IO2YpkIR+sE|!1bs;cMVrVU>~EV zWoak}Y=>tt;knN;c)HudbAYfG>yy^{ZwIdS8!!5V_r)*36rLG&g#Utg_lYU+8ou|P zg8M_w&3k3=ARp755A}G6Yp3Y?1TBA||2!OgZ2YXfEyc%CxLd%Soxd#joG8|nIGZA8 zf7EdwR-K=Y<_YI3%jXr_a=Hlf+b&}-3)_9g(}%C{Y<JW)^R}47?-L(RBOh}9vTH|r zsaJDorHge6OebJ?jL#wX5ASY;cO#qloJO3t(0MIm?Juzmfn`-Awwrl2_Pn`%thzB< z{d29!qt+bSKSr~QCZ#+(yAPj>hs#@EIpROuSKUamE@J;=edChtNbbsrX$_6vlO--% zfQz+aKT(vP#a*ejxaoblc;>|89KLq?Ucpmh6LW7tIh5;6ZD<e9D{!|Ce54W|yBVvR zd-y)iemgl1-|ely<)3tNx3)L6z3Tc_Si-w^OUtQ!_}bHoO<cv(<%f9LH$&~g+sy&$ zp3fU$9D)DJ_z&-T?`J!FcTtVKLbO|~8-8fz2^{6E=RS>2!dw#GM@&P1-`Q$ij*E)m zG^}kB<nB?vL+u$~%)JWRx9e9E&TDXlciFem)t~r(D|amV29KZf71lIiO?Y=pwLvbQ zhAmkRhQbtnL!NA$9L3%0Rk3Id-{WZS0sh9yO%68mHn!HmX{h1*=__I@+-naIPq@$h znVqGB+(Yy*mp3sE;k#B`p7GG0t=2GC;G@i8+=xG6p1FqK2XG%RhuP(Pkv5O>cT(TO zVjC>Sg~a`p*cv%LhWlabVXX)!Y<t8skL^({tmW`nE|E6$?W|1|xYn|r1Fm@IZt@X+ zOLxNgNyE)Y$?9`k>l-|E&FWeowG6)SzED`>H)4OYwoTa&f6Jlc`>t0}8`vtOUD@e0 zKZHNIdZD4YguQ)mZZWP7>${_pdeoezX=F6K&2ZO^KL7rk9`d!|ZFOFoZ(7O^yG7_{ zHJ(3_gY<0ffn&bUCHlL+ah!jeF<#sHpc!7<#YN>x#iH>2{6==eI%KxC@%O7Oa+6>G z_#|UdE=KYnp20+T*dd-c{7!?t6udKylWlkpYtiugjtltB4SV>Gr0)pxvo@=7+X3zs z@cjZuC!e1b<3hf#&cab?>r%N1-&u{Pt2AOu6H|A~r>v>w#j%r0oy7lYyuE;<&)7@P zcfJP3L47rj-^(=dE9~L-=by8aFkbxfyP=G6EuNofX+Hcx!=>bEwY(f~zBer4cM&(} zCA>FtM4xl)?G)2D|5A(e$wsq5KgIOP;&WKz94}%{O`G!k=xul!scnb#4Qs6My+jFq zrgnf2w+Ea%>G^LqF(vjjPqwp0yv5kzcM2PA?}8^W<(bnt`3UcPkD$kQd&;MHw&=gN zuDIo7KrM3zoV)P(sNB?i4Ck=-#_f?ha+DgsL*<(Pk8yfJ|9Q5WI9w0+rY`13dU{|i zA8At7QC}tKLreG5`&==!5POz#o<FJs`Dp9Mw(e0U#zkY~YODO`kdq#GxSx$DUNDb| zcZ0l#`{(ek=z3aMiLVpA#K%WZHf!VVO}J(i<_jm``NteN>zctF8c!cS=dX{a*6JBv zI`R>|s~^%xePF+`bK&nHJc76I+ogtLnFM!!J`b}Kz6+S#3a1U_LM-jY+s@V=muJPZ z17~Y+c98$@o=j_ezR?>Vy57L<kNkf{KW~fsr;grl8)W{2?RWNbJD*)%T50#KKG)f5 zWviKtNBBlX{<a1?m*k_K{yS{z#T|Z26aH?=Yd-f8L+aMnZ!i?5r|fW@cl?qVPBypx zVY?lU2FP3Z{x_`e-nugu<s6<erw_;uv)J+$6(_D^#mpDtIyzV_!go0SRNu+Yx24A? z@w5o9sc|(RaLo1+_<qptr%X1v*sAaKSB&WfYH^a-Qd<k8g;{RT>%a3;bx91Q7-bhv z_Il>WV{}ie;Wr3p<SVp$wTAfurkQg8fc8DgT8G8O{{Brx2fpSz*X%pLB{J4dw$vWi zJ=j~&)B2^BdJF%Tus6ijMSLvB`6e9PxyzapmUG(v%0@NVdf;vVoZ)+!?(~=p`{Q(* z)tLGcH<{!ryn|C7#_*ng7Wnp-j72&08O`pInE6qkRh`V?aF?RfkL4k}cNhM)QMlK= z3}f-eDPtr2{x|#{BK%Hkss25>s#`GUdCHuS+r0sNsX{E`pWH#N<+T_eAJW*CIDK*6 z)%mhwIf09$?l`qSvzMObvz3@$n&@09_~k9ESBtwo75?y@OsK2%575256;EaUfcL0` z{O($<!tNtsevJO>cEKIa(!icy+!JvT-Y=UZXK%uOn!Z+Q*Akw6;%Ow_w~ERATJ@97 zPjDHY+wX_x=dW;=P2J<K5F0hvyu{{<#&KtDQsZ)$^ErJUB%Z$7&1JtmtmpXMARiB3 z7ne5S??7B}F8l_03k|2$_Ouuu6Yrnn<quCuqtv=){0%pEiX%-Qwo0mVju+%McKEs3 zTwEWk2V&S$R-GBFW+!`gjEAT3y=@Q<#o5I5+W3pZeKmbQaV?$v?1i}!ewT@Rdl?#r zW1F^x<ZDO~->1{&cd&k(V9kP~QSy1bHaj@(3}g8IYatt(8>m}#)ige`y<vkT)ct%k z)TtrPTUuwVH-?S9^DrFaZxIcCP)$5EcSl9J!&Co$1{EHL55bGigEz<j{hPP2)*r;) zQU22RG6%u=EB|TWsUuHg;p=JtJ3YLhU3e~&gZ*5%*d)$-#1MWDb@EN$Yq<6>-gmG$ ztrdTZ^{JC`5A}5^_mReMXZ(#2OMheWOZo}VR^Eqmp!4Nn?~J4Hd%(+m>AyOA#zR}@ z!r%FMna_`W{#x4?ZJk;>2k(0QZ|FP6^_qO|Yih0#cMQ*!aCDrV@vCFeWw`IFWv$3Y z6}&yk?%0xYsIDwhQ`6s-a_{#2LTglcdP_Vj#MrB<+JN7`9x~@>|FOI*ggyMdp=SI( z!f&aXw4_~iJT4Pw&LQdxyW#IT&GPx4;^@HTU-Fwxzaxdj)(x+GR_tRe(dHhpJmP$~ z#}40ph8jFk-<jGM>OyDoFq{2XD)BAXo!J~;S}gj_!&&%yMKj?I&+>l8ab0=IWt?n~ z&-C)Ji@nF$N@im+Tz}A3kw)rt2^y`<r*`dTdv5W7*l9cbR(>6h`f3~AM?SjM*ud{% zxjp3E$h!E0cZlPqhvK3SQ{yJ1xs#4==Q~w*>kQcL#nCdl-7hCK9gl-8+y{4qH9TMX zUOeMrp5S~Y9L*NzL*nUx&+wjbE`1(#Zpi}rmY0oVVQ-SMCTkT_bF<N9Z(4)p#}BNp zXs0P{{3iB4YKWEn&*Ax%?kBY~*H?pkxOGzCx3al~&nFKVzs>0`)SEH#gOg`n5BDZ> z<Y_Lf1LCzWo-&`6gCqQHoRMtivu&5x@Q%gL)2wIUnSa%|!E*^Z4ZlV23R8GzdkwBC z$=NY|64^K<zM^pVc_(E}+O2zBw4$wg&c<hQo_!+yHl__YCdki<btz--W4<@b&2hFK zpp~XgW6`U3i?0ZM1-<E4m{#l9GT0sz|E+vqtHw4QU+Z5$4zf8vd84)T@swxl4;3&T z+R&}|E0j_j;8+Ul5&OP!@|E}-$<sQ#J*nNSWb?x9#tkf2;^;z55AYN6w{x(0ubA(k zD$t(mgR+`m%F7#_Ze%a~HftL!$$W<I(!<|p+C>k!aG6uAWttho`ZaH;K4&p@ohvL? z;hAfA#_^{ducXKM_)Evf0{srx#W@?{c~JOX@j_zC{l-E*#>wGT=PSVWYi8q5erIdD zUY`>!)Fk+}H4zVA@3K9S7QU<JzF51=u9Xn;L-Oz;-{S|u(iE>Vj4yuj->a`&EGP#z z+t=lwe@pXw3~u@SME`HQ(LC(+VG8ee521_jesKG=w1LA?xG7i(f3W_A`|v$iL$>1B z4bS8=i*re5`cu!kz7mVZ>VKd;esQ!zpJl1VD#q`{P)7R~jGs^kUUa@MJ7L|qbhT#@ z>0O6o5+ASAMy4t7EK0dw>Q_r$g(0`|>+zjY{&vFFJU<-Hm4l^?9E9&ApTSSsLDnSp zx5)WIF^|UGEVy2PqcQz{X-w4afbV2AjQ`3D<X>F~?}HcGgU{kA{ik*`5Ac%{x6S)n ztMK);7<M*LAK#<D0oE>J`I`Um9Z*p*-N5bnisqjlDeIFHczBzQ&u%m4z*9hs|Kd0N zw(E?3!*KKi8&kwI2)E%qpEsM!2mWj88=m`yzc<sf2w!7qeVF?<*EZ60#fH|s_*yWC z#<lD3T&Vr;;wx^G<3_Q+-$`#&f__HHCtSD4acXu)(0lLn>LI=7qNnh8sDANzJWlK3 zVzWM<#aVCRJN&MB(?T_(EG+m8@4bHS+-oDugRMNLhV4x;<O;mvb7PWN%^$zW$<wp= z7>P4F3-^t)vZnN{uWkC*@r~QJchY)By5f5}yFuq&`N&9DkK!j8j{43Y!(UxnckMC+ zKGRrd>epMF`bVwdjG^cF7~)+10mdCZ!uyrk<Rx1>c4@BxoR^KS&r?~y>Oa0Z`xC7- z@qRCCE#xLVhi_b)HesLtTwJufFx+kASUjs7S7U!QO{L;@3A?N5rm<`9Riq`k4);JA zYoy$hh4*>FdqgAUrI9w79rvja7p+=l{Rd0iIkY9FHGC$*cTxK<X#HLBPJ7HekIw@A z)C@VR!|%&|>6`sxe1`j!?DQPI8*Z%q*Nv<Z#WqA-O~jGj{zdreluhY7n4gmJ`N2?H z;o~M<-9ooN1$#qqCAOV%zZC!R_$WDA&DH+nCg$CSYKt5$hGR=(wPP~<Hieb`!t=&{ z+pTrkOQNsmeSW^HIjAoCN8+O!xLPUJtM)z1^H<1m2lF|;?!$Rr_8V5<8|D>aDbCjn z?=5we=bQZ3qq$V#8pdww`sPY;hTo~YijU3rs1?rTrup!@r10L-iA8dXx3lyR-miNe zu5XIKFV3@rV$oEeSGazyfpNf2m_MIj<6f9Lw}+9fyXE#ze0-s8xL12j-{FIeaWPcH z^{^6Zx2;AJUCa4QTP-%iyGbv?IzfK!4`W3<U+uD%n}kQ7cXU?Y*ec9#LAIYr#5Wvg z(;8diTkBf5SIp}CYJKk&Loyz|fcLQ4b8NQygp>U1oS&=jz3kIgteDz|!|>gFcwTe6 ze&M~RT68#E|2c3!>)I9AH}Lb4efYieGdZnK*zN7yaQHT{pRSJkM;xE2=~%z8HryhA z9kdJY(U-?dUb!9A4Zq3O<+exp?*v!)9aET#Kd|4?N$z0#LEDS24Sy^$u+;~6*0OyI zj>G+2er+nlQh=7m@_o7mzT~R|4#RVXzK(CxHr(Tf=V)gtd2XT4EB=6GxOd7!*UgOe z&tWS|hg+Jdv21-^k}n)pnyBXB<B4+Sqa9+n&6-k9`&NXP|L_~`dH9~tUv8SD)TA!X zZL_Uy>iTYcu>CL`;djYn8><^)3hxzk!Oc{Byv}Cnj@G06gzvD5i!;e_w!`eg7T(tg ze|PQW4%R3%|5O>dkmoX;@j!23E}zNAPp_JX*jle|YO&8R!Ir!{>+?~uzo=bd@!p7+ z_oeh&SzlayZH$NCWo~{Nrb6PsM-6~$vlx%y;pJY&BmdRq`DNdoZkMnAa(h6ZLAEzx zPTd^0V(JIuZ2R@KX|0Pj8lN@qqJ_T3@qF_E9=D{nj+K)e_{$`|X5x5Je%8uaTs7-l zwhO_%%C$UreGB$KVBSg>6W}R}tA#jtTc7Z^3www?tigY$^R{@ujFT7n$;i(f*upy% zdE2Us_y~V1=tF+PGv*2U&5(n;U0>o{_+4JeT@#q!E#kfq#)aePTRh=68{s>#{<P6l zEQ{!9R(ZVmyn*lVF5A?4@M>F7jz7ljRalG0SznA)_hGv!hGOvi26Om(nFVHAKgn%) zt{eWQ&=A;uFKy4)9ojE%LmSSA?_O5u^SSGz?AOU{xL553?@!u&=z91bX`xv1$me6W z@8x-=n7?;CymefZSuR_`JcPZpaOI|-Z>IR%iH(L_upP&48eC+ghkMz3poKo!jd#aq zdzeS`&DzMk>|7bR&pkmy$vD)na20E#GR7^tzubi<I=stx2;UvwBY&~I=HI}lxHs!N zQ*499y->ffZVbOqo6$Vwncr}jJFzuT{>F$e9=^o%;_R(f^uz}a!n4=6U=Hh(N5#;e z-|EH8!E7F)y~kaj3Rf34E3x+#uDTC~xv`ooj(Vd#4|G0!k2ge4n%6bH`&kpq`?9~( zKrueYf9yxT@!BbyddP1R+Z&E&h%fvdl|#nrOSRN2e&4L4rs6hjC2dO?zwl+R>OOIv zJ-^%V(7l5(^^Wz9KD*f{0(U<A{)LC5`hE@L3$PZy$9f}K-I)e!dAeb*vFoX5KD?8& zT@3H1bN;OM<>&~Othmb0=U&%J!GC<9^AFG|UT(nm=MrPVm})16PuiJ(w5^Q4HS!YX zxN0+u1Du8T{=U@b2iLEp;lCU19oLn+3iWY=-=f-t_tDl@$Di%|IGEXbLQM5{8=GS4 zXe)it*k?N<AM3;z-e1VZe|Xk4Qr-(sq+=Y0_XsDAr@Q8~P(xn(;8IS)dp31^{sX6B z%>3nZ_}gm(_<GvddgB&x%%x#lC7AoAXFKFw+gbME?+dJL#RpFM;QuDxH{1T|Wd5SV zFdnAs)3}*6sXpP|w4WD<(fGX&?mBtQ75s12_FMS~bKiGjXl2d`&r3JKc>qU8Y~gRO zo=TEOv7Xm2vv%S8`tVM7S^XaOxjn7@DgI^+)g9ySj2xcU?=ifE@5jn(+e+JZa9>?) z&W1hw?YK6N_?`&&;qM}aXBO?-#G;KjJ7W8chBB{IbLchbt0+G=@zRQ~A<61k&{#dV z^b5}tmuNGz7yHiV<S(oP!*iawc$g&Cvt?jxsx~(;XW~6*B>X+>!LS~uqsj6T4{ylj zVZ8J$t<K{#)X7^n!6-lf!d(^|?8Z;uHs&vQYRU6vc-o0~l78WDH6DT~{BAM{X9L8) zg`E~`?}V*WG3(e=)-N=2&b7<zKEdWf*RBn~yZ)cEH>#yJ+J$@4cj;p$-CcD28{3m$ zepM_b@wCOY?9FISzZdb?y1Sg>BivWdo*Ih|PgPUcI)LZaFm$OD`}=prWhdiodVJJJ zoImn^FTDG3^_-eDmfy#Wjqv{Da9dcT-o|!ezE;xr2k>3#YyQ`#lJ*-*sWoa&_<ciV zyoBFmh4)hLAC6bYx!b{CN1Sl~bjC5BmWrcf5q$9(=9gFGBK+-@8PCvlyk~6r<-9D8 zoKMBpO?Y<<Ggig5xT<B7b7i$3kFy%=<&(FD%dBmCiQx-#V}f-lt=uKAi<;m|>?_^> zh40LER5Ui=?!fo2K0hx0?Anas>jPL5@jQTjHi~<oc&Fm_ZXAbaQ{g#zxG(?G{#iDk zbu9_D_uxIcBxTKcTXh`zTuhrU<SEPvU#l;J%gHUgm+%lj$Q+VIU280ET!h~doq%~E z{$8zO9)<l!oV{<`T0-rEv1Jai$z#>##>KIeIrg`P`oi;jDzU<vy|~!fKj_7pi9_U_ zoiP3)Si(JX+ZW8cQ_LN(%%#O$^1Khv%X-tTcI!*a3+%V2QA6PV&=?E9>+aA0AF-7E zZaMe?hVUN1A^vLOa0KpNolCbXjWcn*Ev8eQ+;eIBr`W<X!wvoM1Vd`qbJ>TQ8Qu-w zCjSME^C>|?x5y<N4~ZfCzXS7a>35mS;s33avCrSXx~a#m*JnG6^T*)*q@?`w6aGfi zOy{z(5uOqKDgIZ|(xJ9RM$567UKC4eZL7>M78{x4=pcM=n?S2)63s>O`iS=3E2xWb zh2P<P0%PeyYQsfyi`bs@g--o;w8HNPFwbK%0sn>hcoOEZI9pLd&i5NT+C0a`QSrXn zRV`vOJeOR@-fTF+T-{o1m2n@w<88;*v@+u2Glw{KyY^#q^Ekct6jO#_#>HXlz#Q6$ zH~c;0JIa|G=%8n1<EJ4l!T65PJ=p)mer6YQfPHH?7S^NRS}=<HfX|DX$^+YPIbP}9 zbsT?EjRrG&ra4d>`zu4?3_OapB@AtGbfpQNwYw*LsZl^5ItbsPd^FZax()Y);aO3{ z-%0!I{CC027JOWjzeUSZ)(S~54(?31rPK`9|0U)oV^YT5)M<{5!yRlb$InWdo2YL> zYc<6Fd@KCYUZ$IJi`R>|Jj2!l>P!c@UPZ^{aM6X08MtaKwhj7BcpMJ>2W`i<K6&Im zk&mk42;V6ltV)+S3Gcxbp5r+V{2Rrzz70O$TZGT)`X6y^I6trIS6=_{oT`z$?N9^i z@E4v{g}-;7Todm1j3vk4x0P$0j?zB7<Fd8_{s$O?KHtUmVEuBs{tYf><1;~g;djYD z9<uI`>pXCs(6;SdIDGzmusOp1Mf!WYs4<zJ-s}&`O?Elm0pkVvDp@!7_xoxuuvdJK z4WFM(SD&k>RfWu*ur@9yS1_CqPxu>Y$@I`t-?!wZoNM9xpDS_@o|VP5RtxJ}Pl~lW zUdDHq_hg*VR=D5aiLcpgRk8holg9EK-ivF&RwnwM#LiXcC(*$~$CI+sb2sY(*qdte z0{^Lug`k=6yTbKy@CD4_Iez%gaROV(u8q_$tM;$q^0m?C3Y?{BNaN0h??l4;ifQCH zyc_!kY|V=p!>-+B{EXYgx3;r#%U26yIh}gpH#rr=ISbFH*>5O!sq4g|55zhQra1im z<a+o!VFPgY6u;s3ns2b#J>D_S%gA#Re2#T~1>al5{tesv#oGslG2$p$Uf!Ce)SK7D zl%4JOo$tiw-T1Az8h7>7#zt!3FypqQx<OxI%!YMlLpon!KZCE`uKg~Ty_}l?#{j<S zXD}A{|F|kmZKvff<`LJz-(1<J-;?*!iWtxFyITM5ebna;YA8Og`CPh3${IYp`}jBx zUKlS%_%6Z_zK5P{pJ|Obk5+zPOh-O%!SP7jE;?v~pIl;DVta=+hRIVUzT<E)AWwYs z+%4*s&+R9{$zD1>zJNEpKh!DFJWr=R#1!uJpTlbm&LV2h;-%&XZD!C(8rwbc7@o@v zVPgeuzcrptz_1uk%a+rge2wfThdHeo(x@4@%qRZwP0gKnD*2jmkE`(|)oAuQ(OLoh z!yFNwPrtEJtn7|={s+DuXLk>O*Bt*s<C`2eggaax$L{m^2!Fq961<aOD#cbN8W=9# z!!Y#2>!Walziaj^9qpFCR4}d;?^|-vPybNkCJdJ&e7}XagY4FL$-Iq=;>J!9+=hF% zb8_`r6=Opl_qsMn9QO?{FYYwg7<Y~7?b+I5sAz6TNLi00&{P#Rv)840`>xvbw110_ zfiMs4=zg!O`vMr^;4jF2>z;h;_dRTVX*K+IHjNx)5<?f)@6zX><J00e)&*94<ZT6C z3A)8k9@_XKkJ{_}Np_CH7Jj4Ds*U?QK7PefFWX@G8qeN);(52NbrW3a*c(7UP2{E^ z4$Ja;xiZ@|ea@*4;wZf9KA63&P303et8oy1YZUIUD&wox1Fo@km*WxjX=k<ZJ;z)p z_QKVyZE%rWE`DeK2X+p@d?!4gH&FN43Gcp#_x-~A>ES)<@VBf+@V%s$e26p53Gt<j zYcb}KlM!O7jnCS2(|2wx`a|5|?>S_Fy(Espd@(Dd@1`7oAUC7gUBT|xbTO<%ELsTT z@q@-o3u6H0fMqw1%kcBEHaE)g&DSnAhc#nEyx-B$AecrpP8t6v;r=LtoN0TX*xHGA zf*6wc3eQ-s@&Ai9RYtoGNB1h~J6~<(syXdHIp2COZ!G%IweX(OxFWbI?;e={MdB!a ztG|Q%0xn_g<k~E;UMWe(j!zHOhp!AYIa2@do<OL}b>(rZ{D<E<%&1_j<Ls+8#ups9 z>8CARr|wdp*!dm4De>yPT)!iZT&c}FrQMJ9p@sDL(&tg}mVoD^_`-Y}*U<Q3a~6%3 zN~DSG>IN*0wGHn*RdD@Je*4YE3vE6{6D?Zc7nfn39iD^#sofmMJI5HuK0hgsh4He5 z7S@h1&+1#EDots(SZrDN8if1pQ;jomZMKzmEsgyiTIx2${Z)eRQE)n*W>3p~cpjZ# zAO4QhWAgJ69d3fL$T*tOE}qZZo6s>X%e&r0?k~wt$jv}JZO6^jEMh36o{N2VH?>Br z;rIF{<z}~jXW;qDaabFNca=ICQ?tq%+k73z!&H8L%|wrUHKdvFzQ6?WJvm+7bZxTw zwne_DE`TRDjX9pD?<kySsB2vEyXLxh<Yg@WE{f;VrsiN<=f&o*mTHJ|ui5_OW6TZw z%4bD(%N<X7X7M%u;di2e?>@iq+sWD+<_<Yx(QGk&$4B^1Dz7}1<^OTM!uR~;@tU2@ zDr|+{TRbTbfya|@B;zN^^$o61VJmeVJ{^a5N`~X;19|C%k0xzBYp&=XgYDm(n<KVT zwodG)X=ZHUu%PpM<#&@dHM^Q?@ZGAl@l(M$+lqQ}$L@N^8O8gPSbl}^XBz#9R>M7e z8#xYt6Ks4Xx|YM8^e|B@Kfv&FdSe>5uh7Hp?6IiiX5;j1ELuLB9p^q|YXzTQ!7?BA zMa5F?bsxh?eQ}rdxiH-{#?vXbH{<h)&-cR87xwTh<p95V<-Vb|`3KUjd`#YFT`&=5 zc*ot%C;k?eQr{}8dFiY-Z98c7IXKV7@SLcw;iZ;%#<TS=V=cFsme65%{-4|vH+Z-c zhOd&$0dzK|6`tRtb9p>Lms@evaj&|57am;CF0S<Q(uJ)F`rOyloE74QBePgL{tQ13 zrt|YoZ{xUz|D#}(S|Uev-_+0fJJ-dc@;-N#qeEi*nbt?jX~Vj>gJ(87j~g>18t}Og zKd`5AelVWK;6A+XuqA=d{`UBpo|7(Ij~%vdtcC}+3c_{>r?1wtR-vui#_4N&3dd#W zZAl~RZu{_FVtD5%5th6#4TL2f`=fncg3Cg<%;0laH@>n>{baW<8{xiwB@Kk{?dQwc zH+*e%yufkzePQu<^JOxBFn=p|)m%UH2wgjO1K(%aU&cnJ?&cWrHBIF?D<7|yvleM@ ztiTt(KN?WR7-1t73`+*c8%%lmuc^;U`E4Rc;cu|tD{puB`~f@ras1|bedM7YE>p>2 zc>g^opKsu}tM<8_KaHnO+Wa7n@Ev0ddJ4}ve_f`JIMVpsxrDU^|AqMvYx`rcFLExy zmc-7wvesMT3-4Bh-``I&ZhlN{e9eQ6&G0wAM#6M{EDZYJiJOD;d&U@l45lt{gy(Kq z+NC@vyiS*E;?z_zCedI$c^yB<Jjdn^+=SnA{M5nv+x|S;cgR;Ic3U^)uZXz`zu|q} z@Xo{S{68nQ*06rgMsNG!a`Y?Cdo`nF@m+mO?GkG$Hqx|JH|3-?{z}5uca{F^%<BP9 zQRAt;+T{9UFi&|=A6$j^>t+wbE!=zL>H?eD#Wy0GT;ingK;r_gg06*nHA4UJyz-vA z%nR`MQ%{bHE4*)CD^JQ;8UaT)zQS|RTSgmWcwVk1EUu2@Tcf}KcKJ(q{A|8j%f>lc zI0@tR1jk)c*12VIaKyFn9oQ9pi^1}o9L^F)ct^GmOv|)sSxxTlH)kcLtm})ret8Cs z)Dp`$xm&EpO%#K^;hoF$^!F}*i}cyH6<?LrRD8Ts6-Q#+ESLF`_|^VLTu-d1&eG4h zj_kA90XI9ftAT?!zQViM&0O!x?h^cjzxT05pXTs{XCb|{{g*tRmXA)&<#C5K>4VlK zJ&h-v7tv=N3_%|o;MzFEe8B%2nh*a6&@%SI-*gDyMRbP$jPsrGoj6vla_)dW58!=~ zw)J7|mkw^2em#Q+pU=UtM2_ZVP)mx({{B0>8MS|k-#PZ5usJMQf3YmZLF=|O)&bY@ zn>f&z*7wBov}z25xhecDz`^}+&`gf`{P(}uzYpyHdHj#l|4WDewq;2Dr~m%lCN%ix z@jpAD@PFywf8_T+I`?nm|GjJfZu4L5{~5zSk3+wIe*U+wf1dlVY=`Ur?)RUy{jaY7 zXZ`-~`TzeI_|J0upPm1&ko@=h8S4Mdzkjy>=kb5j@PFdO|1LYhrLy!t{O>=~_rK5m zd;d>k@&Ekre~<r%82FEP3?2WO^M4+PYyUGj4DJ6<{`=43`QL%z|Eq1wrvKMJw;uoZ J-~S;7{vQRIqOJe{ literal 0 HcmV?d00001 diff --git a/data/dsv41/profile-coder.bin.sha256 b/data/dsv41/profile-coder.bin.sha256 new file mode 100644 index 0000000000..54e8a1be1f --- /dev/null +++ b/data/dsv41/profile-coder.bin.sha256 @@ -0,0 +1 @@ +92860ca14abbb3319a773aa237a4007898a8eb35edaff50d65073843b33c8904 *profile-coder.bin diff --git a/tools/test_setup_coder.py b/tools/test_setup_coder.py index 1f5905ddb0..81b8ff77a6 100644 --- a/tools/test_setup_coder.py +++ b/tools/test_setup_coder.py @@ -98,6 +98,30 @@ class Pins(unittest.TestCase): self.assertEqual(list(fam)[:4], ["IST-DAS-2.00bpw", "IST-DAS-2.25bpw", "IST-DAS-1.75bpw", NAME]) +class Profile(unittest.TestCase): + """The set's own hot-expert profile (made from the engine's routing over the 264 calibration texts, 519,422 prompt tokens): rows of 192, not the 2.00 set's.""" + + def test_the_profile_is_the_sets_own_and_its_hash_is_pinned(self): + import hashlib + f = ROOT / "data" / "dsv41" / PIN["profile"] + data = f.read_bytes() + self.assertEqual(len(data), (40 + 3) * 192 * 4) # 40 layers and the drafter's 3 blocks, rows of 192 + self.assertEqual(hashlib.sha256(data).hexdigest(), f.with_name(f.name + ".sha256").read_text().split()[0]) + self.assertEqual(setup.MULTI_FILE_FAMILIES["deepseek41"]["models"][NAME]["profile"], PIN["profile"]) + self.assertEqual(dsv41_fit.ISTA_SETS[NAME]["profile"], PIN["profile"]) + + def test_the_engine_reads_it_and_not_the_2_00_one(self): + """The same size gate as src/dsv41/ds4_experts_rule.hpp profile_size_fits (tests/dsv41/experts_rule_test.cpp runs the C++ one).""" + def fits(n, layers, n_exp): + return 4 * n_exp * layers <= n <= 4 * n_exp * (layers + 8) + mine = (ROOT / "data" / "dsv41" / PIN["profile"]).stat().st_size + other = (ROOT / "data" / "dsv41" / "profile-2.00.bin").stat().st_size + self.assertTrue(fits(mine, 40, 192)) + self.assertFalse(fits(other, 40, 192), "a profile counted on 384 experts a layer is not read by the 192-expert pack") + self.assertTrue(fits(other, 40, 384)) + self.assertFalse(fits(mine, 40, 384)) + + class Recognised(unittest.TestCase): def files(self): t = dsv41_sets.tables()["sets"][NAME] From 05e276aa8cfcf3be273db1b3528cdf8dd28e11b5 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:58:06 +0100 Subject: [PATCH 57/59] ISTA-DAS Coder: dense weights and RAM classes from measured runs on r9700 (placement lines, memory-capped one-card decode), words and menu row of its own --- strata_control/dsv41_fit.py | 20 +++++++++++++++----- tools/strata_mcp.py | 5 +++++ tools/test_setup_coder.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/strata_control/dsv41_fit.py b/strata_control/dsv41_fit.py index 7f2b70f1dd..828eb58e13 100644 --- a/strata_control/dsv41_fit.py +++ b/strata_control/dsv41_fit.py @@ -106,7 +106,14 @@ if CODER: _coder_bytes = sum(int(CODER["files"][n][0]) for n in CODER["shards"]) ISTA_SETS[CODER_MODEL] = { "title": CODER.get("label", "ISTA-DAS Coder"), "set_bytes": _coder_bytes, "experts_gb": 66.04, "dense_gb": 6.08, "profile": CODER.get("profile", "profile-coder.bin"), - "meta_bytes": 0, "experts_per_layer": int(CODER["experts_per_layer"]), "ppl": "?", "ram_ok_gb": 24.0, "measured": "", + "meta_bytes": 0, "experts_per_layer": int(CODER["experts_per_layer"]), "ppl": "?", "ram_ok_gb": 24.0, + # measured 11-01 on r9700 (one Radeon AI PRO R9700, 251 GB RAM, this branch's engine, packaged Terminal, 128K context, 5 experts a word): the whole run in a user scope with MemoryMax + # and no swap; decode median of 3 prompts x 200 tokens, one run each: no cap 25.6 tok/s, 40 GB 20.9, 32 GB 18.5, 24 GB 15.0, 16 GB 8.0; four cards, no cap: 59.0 (all experts in graphics memory) + "measured": "one Radeon AI PRO R9700 (32 GB) with 251 GB of RAM: answers about 26 tokens a second, a 93,000-token prompt read in 78 s; four of them: about 59 tokens a second", + "tight_words": "reads the rest from the SSD. Measured on one R9700 with the RAM capped for the whole run: about 21 tokens a second with 40 GB, 18 with 32 GB, 15 with 24 GB (26 with all the RAM it wanted).", + "spill_words": "This computer has {ram:.0f} GB of RAM. This set was measured down to 16 GB (about 8 tokens a second on one R9700); with less, most experts come from the SSD while it answers: it works but is slower, and a word can take seconds. More RAM fixes it. It is still allowed.", + "tight_short": "tight: runs, with the experts RAM cannot hold read from the SSD (about 21 to 15 tokens a second measured with 40 to 24 GB of RAM on one R9700)", + "spill_short": "slow here: this computer has {ram:.0f} GB of RAM and the set was measured down to 16 GB (about 8 tokens a second on one R9700); it can still be installed", "unproven_uma": "Not run on a Ryzen AI Max (Strix Halo) or a DGX Spark yet: the sizes above are exact, the speed is not measured on a shared-memory computer.", "disk_total": round((_coder_bytes + ISTA_ENGRAM_BYTES + ISTA_DSPARK_BYTES) / GB), "quality": "ISTA-DAS's coding version, half of the model's experts removed (192 of 384 in every layer); not measured against the original model here yet"} @@ -124,7 +131,9 @@ ISTA_DENSE_ON_GPU_GB = 4.5 # (the old plan's figure, kept for the Uns # card cannot hold are read in place and the prompt chunk is 32768 with the borrowed slots; the 8192 chunk of the older engine took 4.5 GB and # the card held 2,366); NVIDIA and others 3.6 GB (2 x A6000 3.7, an A4000 3.5; not tied to the chunk) # and the experts that stay on a card are a little bigger than the set's average (the hot ones: 9.86-10.0 MB against 9.70 for 2.25 bpw): x1.025 -ISTA_DENSE_GPU_BASE_GB = {CODER_MODEL: 5.54, "IST-DAS-2.00bpw": 5.62, "IST-DAS-2.25bpw": 5.62, "IST-DAS-1.75bpw": 5.62, "UD-IQ1_S": 6.34, "UD-IQ1_M": 7.37} +# ISTA-DAS Coder: the engine's startup lines on r9700 with this branch at 128K context, 11-01: one R9700 weights 5.70 GB, experts 24.91 GB (2,859 of 7,680); four R9700 weights +# 0.74 + 0.87 + 2.25 + 2.56 = 6.42 GB and all 7,680 experts in graphics memory -> base 5.46 + 0.24 for each card (5.70 on one, 6.42 on four). +ISTA_DENSE_GPU_BASE_GB = {CODER_MODEL: 5.46, "IST-DAS-2.00bpw": 5.62, "IST-DAS-2.25bpw": 5.62, "IST-DAS-1.75bpw": 5.62, "UD-IQ1_S": 6.34, "UD-IQ1_M": 7.37} CARD_DENSE_REPEAT_GB = 0.24 ENGINE_FREE_GB = 0.62 CARD_OTHER_GB = {"amd": 1.60, "amd_low_share": 2.58, "other": 3.6} @@ -394,11 +403,12 @@ def _plan_ista(model: str, cards: list[dict] | None, ram_gb: float | None, disk_ elif float(ram_gb) >= v["ram_ok_gb"]: out["verdict"] = "tight" lines.append(f"This computer has {ram_gb:.0f} GB of RAM: Strata keeps the experts you use most in RAM (it sizes this itself) and " - "reads the rest from the SSD. Measured: about 4.7 tokens a second on 64 GB of RAM and a 12 GB card, about 7 on " - "46 GB with a faster drive. More RAM or a faster NVMe drive makes it quicker.") + + (v["tight_words"] if v.get("tight_words") else "reads the rest from the SSD. Measured: about 4.7 tokens a second on 64 GB of RAM and a 12 GB card, about 7 on " + "46 GB with a faster drive. More RAM or a faster NVMe drive makes it quicker.")) else: out["verdict"] = "spills" - warns.append(f"This computer has {ram_gb:.0f} GB of RAM and this model was measured with 46 GB and 64 GB. With less, most " + warns.append(v["spill_words"].format(ram=ram_gb) if v.get("spill_words") else + f"This computer has {ram_gb:.0f} GB of RAM and this model was measured with 46 GB and 64 GB. With less, most " "experts come from the SSD while it answers: it works but is slow (a word can take seconds). More RAM fixes " "it. It is still allowed.") else: diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 49911cf321..91dec2a80c 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -1434,6 +1434,11 @@ class Strata: f"in memory and the other {pl['streamed_gb']:.0f} GB are read from the SSD; measured 14-16 tokens a second on code and " "10-11 on chat") if pl.get("variant"): # an official ISTA-DAS set (strata_control/dsv41_fit.py): measured on 46-64 GB, never a refusal + own = ((__import__("strata_control.dsv41_fit", fromlist=["x"]).variant(pl["variant"]) or {})) + if v == "spills" and own.get("spill_short"): + return own["spill_short"].format(ram=pl["ram_gb"]) + if v == "tight" and own.get("tight_short"): + return own["tight_short"] if v == "spills": return (f"slow here: this computer has {pl['ram_gb']:.0f} GB of RAM and the set was measured with 46-64 GB, so most of its " "experts are read from the SSD; it can still be installed" diff --git a/tools/test_setup_coder.py b/tools/test_setup_coder.py index 81b8ff77a6..85703abf48 100644 --- a/tools/test_setup_coder.py +++ b/tools/test_setup_coder.py @@ -177,6 +177,34 @@ class Plan(unittest.TestCase): self.assertEqual(p["experts_in_vram"], 7680) # four 32 GB cards hold every one of them self.assertEqual(p["verdict"], "fits") + def test_the_plan_follows_the_engine_on_r9700_cards(self): + """The engine's own startup lines (r9700, 128K): one card holds 2,859 of 7,680 with 5.70 GB of other weights; four cards hold all of them with 6.42 GB.""" + p = dsv41_fit.plan([R9700], 251.0, None, 131072, model=NAME) + self.assertAlmostEqual(p["experts_in_vram"], 2859, delta=2859 * 0.03) + self.assertAlmostEqual(p["cards"][0]["dense_gb"], 5.70, delta=0.05) + if __import__("os").name != "nt": # (Windows runs one AMD card: the plan counts one there) + p4 = dsv41_fit.plan(FOUR, 251.0, None, 131072, model=NAME) + self.assertEqual(p4["experts_in_vram"], 7680) + self.assertAlmostEqual(sum(c["dense_gb"] for c in p4["cards"]), 6.42, delta=0.1) + + def test_the_ram_words_are_the_sets_own_measured_ones(self): + """One R9700 with the RAM capped for the whole run (decode median, 3 prompts): 25.6 tok/s uncapped, 20.9 at 40 GB, 18.5 at 32, 15.0 at 24, 8.0 at 16.""" + tight = dsv41_fit.plan([R9700], 45.0, None, 131072, model=NAME) + self.assertEqual(tight["verdict"], "tight") + self.assertIn("21 tokens a second with 40 GB", tight["words"]) + self.assertNotIn("4.7 tokens", tight["words"]) + slow = dsv41_fit.plan([R9700], 20.0, None, 131072, model=NAME) + self.assertEqual(slow["verdict"], "spills") + self.assertIn("down to 16 GB", " ".join(slow["warnings"])) + self.assertNotIn("46 GB and 64 GB", " ".join(slow["warnings"])) + import strata_mcp as M + s = M.Strata(ROOT) + s.dsv41_plan = lambda hw, disk_free=None, only=None, model=None: slow + self.assertTrue(s._dsv41_memory_words({}, NAME).startswith("slow here: this computer has 20 GB of RAM and the set was measured down to 16 GB")) + # the other sets keep their words + other = dsv41_fit.plan([R9700], 30.0, None, 131072, model="IST-DAS-2.00bpw") + self.assertIn("46 GB and 64 GB", " ".join(other["warnings"])) + def test_the_download_is_the_model_plus_the_shared_files(self): gb = dsv41_fit.ista_download_bytes(NAME) / 1e9 self.assertAlmostEqual(gb, (72_123_566_336 + 110_595_290_816 + 7_976_914_240) / 1e9, delta=0.01) From 11e02ea876b4d1f5b3da63ef04d6ad7c192e70b6 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:29:19 +0100 Subject: [PATCH 58/59] ISTA-DAS Coder: measured numbers in the menu text and the docs (KL, perplexity, speed on R9700 and RTX PRO 6000) --- docs/DEEPSEEK41.md | 15 +++++++++++++++ docs/MODELS.md | 1 + setup.py | 4 ++-- strata_control/dsv41_fit.py | 4 ++-- tools/test_setup_coder.py | 1 + 5 files changed, 21 insertions(+), 4 deletions(-) diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 3a5dc6e543..2e045f342e 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -77,6 +77,21 @@ into the pack as `expert-profile.bin`, checks `strata-dsv41 --pack-info` (every (`tools/dsv41/smoke.py`, the text must name Paris). The start script passes `--dspark auto` (never `off`: `off` still loads the drafter and its 7 GB of experts take the graphics memory); the RAM store sizes itself. Long prompts use the engine's fast chunked path on its own (no flag is written: the engine picks the chunk size for your cards). +## The ISTA-DAS Coder + +ISTA-DAS's coding version of this model: in every layer 192 of the 384 routed experts are kept and the other 192 removed (the router, the experts and the routing biases are half as wide; every +other tensor is the 2.00 set's, with the same types). `strata launch --model ista-das-coder` (or "ISTA-DAS Coder" in the app's version list). Download 191 GB: 72 GB of model, the 111 GB n-gram +table (the same file the other sets use, downloaded once) and the 8 GB drafter; the picture file is the one every DeepSeek set shares. Where it comes from, the commit, the file names and their +SHA-256 are in one file, `data/dsv41/coder-set.json` (`python tools/dsv41/pin_coder.py OWNER/REPO` writes it from the Hub). Its hot-expert profile is its own (`data/dsv41/profile-coder.bin`, made from the engine's routing over 519,422 +tokens of the calibration texts): a profile counted on 384 experts is not read by it (the engine checks the file's size). + +Measured on 4 x Radeon AI PRO R9700 (the packaged Terminal, 128K context, 5 experts per word by default there): all 7,680 experts sit in graphics memory, decode about 59 tokens a second, a 93,000-token prompt +read in 80 s; on one R9700: 2,859 experts on the card, decode about 26 tokens a second (with the RAM capped for the whole run: 21 with 40 GB, 18 with 32 GB, 15 with 24 GB, 8 with 16 GB); an RTX PRO 6000 Blackwell +(CUDA 12.8, sm_120, one of two cards on a shared box): about 100 tokens a second. Against the original model (4,995 positions, 6 experts a word, 4 cards, same harness): KL 0.397, top-1 76.4%, perplexity 4.645 +(reference 3.140); the same run gives 2.00 KL 0.171, top-1 83.7%, perplexity 3.630 and 2.25 KL 0.109, top-1 87.2%, perplexity 3.405. By part (KL): code 0.230, agent 0.199, documents 0.302, English 0.476, multilingual 0.777 +for the Coder; 0.104, 0.108, 0.202, 0.303, 0.138 for 2.00. One run per cell unless the numbers repeat; details and the task suite in `phaseA-tests/maya-port/DS-CODER.md`. Not run on a Mac or a Ryzen AI Max +(Strix Halo) yet; the plan says so there. + ## Install ``` diff --git a/docs/MODELS.md b/docs/MODELS.md index bcf28338e2..ec5ef6cc0a 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -60,6 +60,7 @@ It uses its own engine, a separate download that the app and `strata launch` fet | 1.75 bpw | 239 GB | perplexity +21%; code and agent text +8.9% and +10.2%; weaker on plain prose | | 2.00 bpw | 257 GB | perplexity +16%; code and agent text +8.5% and +5.9% | | 2.25 bpw | 274 GB | perplexity +7.7% to +8.3%; code and agent text +3.5% and +2.5% | +| ISTA-DAS Coder | 191 GB | ISTA-DAS's coding version: 192 of the 384 experts in every layer kept (72 GB of model instead of 138 GB); numbers against the original model are in [DEEPSEEK41.md](DEEPSEEK41.md#the-ista-das-coder) | The download includes the shared n-gram (Engram) table and the DSpark drafter. Pick 2.25 for coding and agent work if you have the disk. Perplexity is measured on a fixed set of 4,995 test texts; lower is closer to the original. diff --git a/setup.py b/setup.py index 131f263719..9f9bf5b063 100644 --- a/setup.py +++ b/setup.py @@ -878,8 +878,8 @@ MULTI_FILE_FAMILIES["deepseek41"]["models"] = { **({DSV41_CODER_MODEL: { "label": DSV41_CODER.get("label", "ISTA-DAS Coder"), "about": "ISTA-DAS's coding version of DeepSeek-V4.1-Flash: %d of the model's 384 experts in every layer are kept, the rest removed, with the 2.00 version's file layout and " - "tensor types: %.0f GB of model + 111 GB n-gram table + 8 GB drafter (about %.0f GB of disk). Not run on a Mac or a Ryzen AI Max yet. Its quality is not measured " - "against the original model yet" % (DSV41_CODER["experts_per_layer"], sum(DSV41_CODER_FILES[n][0] for n in DSV41_CODER["shards"]) / 1e9, + "tensor types: %.0f GB of model + 111 GB n-gram table + 8 GB drafter (about %.0f GB of disk). Not run on a Mac or a Ryzen AI Max yet. Against the original model (our test, 4,995 positions): " + "perplexity +48%%, KL 0.40 (2.00 bpw: +16%%, 0.17; 2.25 bpw: +8%%, 0.11)" % (DSV41_CODER["experts_per_layer"], sum(DSV41_CODER_FILES[n][0] for n in DSV41_CODER["shards"]) / 1e9, (sum(DSV41_CODER_FILES[n][0] for n in DSV41_CODER["shards"]) + 110_595_290_816 + 7_976_914_240) / 1e9 + 6), "ram_gb": 24, "recipe": "coder", "subdir": None, "legacy_subdir": None, "profile": DSV41_CODER.get("profile", "profile-coder.bin"), "hf": hf(DSV41_CODER_REPO), "shards": list(DSV41_CODER["shards"]), "engram_shard": DSV41_CODER["engram_shard"], "experts": DSV41_CODER["experts_per_layer"], "generic_names": True, diff --git a/strata_control/dsv41_fit.py b/strata_control/dsv41_fit.py index 828eb58e13..9bbe02d583 100644 --- a/strata_control/dsv41_fit.py +++ b/strata_control/dsv41_fit.py @@ -106,7 +106,7 @@ if CODER: _coder_bytes = sum(int(CODER["files"][n][0]) for n in CODER["shards"]) ISTA_SETS[CODER_MODEL] = { "title": CODER.get("label", "ISTA-DAS Coder"), "set_bytes": _coder_bytes, "experts_gb": 66.04, "dense_gb": 6.08, "profile": CODER.get("profile", "profile-coder.bin"), - "meta_bytes": 0, "experts_per_layer": int(CODER["experts_per_layer"]), "ppl": "?", "ram_ok_gb": 24.0, + "meta_bytes": 0, "experts_per_layer": int(CODER["experts_per_layer"]), "ppl": "48%", "ram_ok_gb": 24.0, # measured 11-01 on r9700 (one Radeon AI PRO R9700, 251 GB RAM, this branch's engine, packaged Terminal, 128K context, 5 experts a word): the whole run in a user scope with MemoryMax # and no swap; decode median of 3 prompts x 200 tokens, one run each: no cap 25.6 tok/s, 40 GB 20.9, 32 GB 18.5, 24 GB 15.0, 16 GB 8.0; four cards, no cap: 59.0 (all experts in graphics memory) "measured": "one Radeon AI PRO R9700 (32 GB) with 251 GB of RAM: answers about 26 tokens a second, a 93,000-token prompt read in 78 s; four of them: about 59 tokens a second", @@ -116,7 +116,7 @@ if CODER: "spill_short": "slow here: this computer has {ram:.0f} GB of RAM and the set was measured down to 16 GB (about 8 tokens a second on one R9700); it can still be installed", "unproven_uma": "Not run on a Ryzen AI Max (Strix Halo) or a DGX Spark yet: the sizes above are exact, the speed is not measured on a shared-memory computer.", "disk_total": round((_coder_bytes + ISTA_ENGRAM_BYTES + ISTA_DSPARK_BYTES) / GB), - "quality": "ISTA-DAS's coding version, half of the model's experts removed (192 of 384 in every layer); not measured against the original model here yet"} + "quality": "ISTA-DAS's coding version, half of the model's experts removed (192 of 384 in every layer); against the original model perplexity +48% and KL 0.40 (code and agent work: KL 0.23 and 0.20; 2.00 bpw 0.10 and 0.11)"} ISTA_DENSE_GB = 6.16 # the dense weights in the shards (attention, router, shared experts, the head; the embedding stays on the CPU) ISTA_DENSE_ON_GPU_GB = 4.5 # (the old plan's figure, kept for the Unsloth Q8 plan above; the official sets use the measured ones below) # What the engine really puts on a card, from its own startup line ("CUDA0 layers [0, 39] + head: weights 5.86 GB, experts 25.29 GB (2566 of 15360 in diff --git a/tools/test_setup_coder.py b/tools/test_setup_coder.py index 85703abf48..6b49ab124b 100644 --- a/tools/test_setup_coder.py +++ b/tools/test_setup_coder.py @@ -231,6 +231,7 @@ class Plan(unittest.TestCase): self.assertTrue(row["images"] and row["multi_file"]) self.assertEqual(row["disk_gb"], round(row["download_gb"] + dsv41_fit.DISK_HEADROOM_GB, 1)) self.assertIn("192", row["about"]) + self.assertNotIn("not measured", row["about"]) self.assertTrue(row["on_this_pc"].startswith("fits")) From d6a5a7837e9d88cd613dfc7fffe530c3a8db9374 Mon Sep 17 00:00:00 2001 From: Niko1221 <Niko1221@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:15:09 +0100 Subject: [PATCH 59/59] README: the ISTA-DAS Coder row --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 799de83b82..f46c4e8741 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ disk space. | 1.75 bpw | 239 GB | about 245 GB | | 2.00 bpw | 257 GB | about 265 GB | | 2.25 bpw | 274 GB | about 280 GB | +| ISTA-DAS Coder (half of the experts removed) | 191 GB | about 197 GB | Runs on NVIDIA RTX 30, 40 and 50 series (Windows and Linux), AMD Radeon AI PRO R9700 (Linux), AMD Ryzen AI Max — Strix Halo (Windows), and Apple Silicon Macs with 64 GB or more, text only ([Mac](docs/DEEPSEEK_MAC.md)). Setup downloads the files and the DeepSeek engine, then starts the model.