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. 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/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= 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 /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/scripts/make-df2-locales.py b/apps/host/scripts/make-df2-locales.py new file mode 100644 index 0000000000..c63d60bd93 --- /dev/null +++ b/apps/host/scripts/make-df2-locales.py @@ -0,0 +1,124 @@ +"""Writes src/locales/df2-.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 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 + +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") + +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 = " " + + +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/scripts/make-pick-locales.py b/apps/host/scripts/make-pick-locales.py new file mode 100644 index 0000000000..3519d32995 --- /dev/null +++ b/apps/host/scripts/make-pick-locales.py @@ -0,0 +1,75 @@ +"""Writes src/locales/pick-.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).""" +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("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", + "隐藏详情", "詳細を隠す", "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") + +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 = " " + + +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/scripts/make-r3-locales.py b/apps/host/scripts/make-r3-locales.py new file mode 100644 index 0000000000..1be1715ae1 --- /dev/null +++ b/apps/host/scripts/make-r3-locales.py @@ -0,0 +1,67 @@ +"""Writes src/locales/r3-.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") + +# 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") + +# 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.") + +# 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") + +# 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" +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/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-.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/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-`, and their `~s` 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/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/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/server/index.mjs b/apps/host/server/index.mjs index 36a4c066d1..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. @@ -2233,7 +2234,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/server/native-control.mjs b/apps/host/server/native-control.mjs index 6514252b10..ce517f749c 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; - 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,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)}));} @@ -88,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 /models/): 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'};})};} + /* 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 /models/): 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');} @@ -161,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 (/models/) 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.'};}}} @@ -195,7 +201,9 @@ 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}}:{})});} + /* 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; } } @@ -268,15 +276,17 @@ 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; 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. */ @@ -289,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; @@ -309,7 +320,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}); @@ -391,7 +403,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} } const deadline=Date.now()+300000;while(Date.now()setTimeout(resolve,1200)); } if(job.state!=='running'){await unload(id);return;} @@ -418,7 +430,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);} @@ -433,7 +445,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)]; @@ -446,6 +464,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()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. */ @@ -468,7 +526,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}); @@ -491,7 +549,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'); @@ -591,7 +649,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/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/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/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/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; }) { @@ -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(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 }: {
{ setWsName(w.name); setNavOpen(false); setRenameWsId(w.id); }}/>{tr(w.id !== 'root' ? { setNavOpen(false); setRemoveWorkspaceId(w.id); }}/> : null)}
{tr(expanded ?
{tr(shown.map(s => ))} {tr(!shown.length ?

{tr(q ? 'No matching chats' : 'No chats yet')}

: null)} {tr(!q && rows.length > shown.length ? : null)} @@ -102,7 +109,7 @@ export function Sidebar({ containerRef }: {
: null}
- + diff --git a/apps/host/src/components/ArtifactPanel.tsx b/apps/host/src/components/ArtifactPanel.tsx index 4669d3f014..985ee03cb5 100644 --- a/apps/host/src/components/ArtifactPanel.tsx +++ b/apps/host/src/components/ArtifactPanel.tsx @@ -62,15 +62,28 @@ 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 || document.documentElement.dataset.motion === 'reduced') return; + setLeaving(true); + // 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) - return null; + return leaving ?