engine/strata: bring the Strata subtree to upstream 41cf05a0 (engine 0.1.50) with the local patches re-applied

Documented tree replacement (the history has no git-subtree metadata): 3-way merge of the old subtree
(570201a:engine/strata) against upstream 41cf05a06a25dd29103b7b27a2279a3f60c21876 (2026-10-25), merge base =
the old pin d9ab8435 (tree-identical to upstream 5b734e42; d9ab8435 is not an ancestor of upstream main).

Local patches re-applied by hand where they conflicted (15 files): STRATA_CUDA_STATIC profile, experimental KAR
experts and KAR PLE arms, keyless V-only arm (now beside upstream's K8V4 hybrid KV and fused norm+rope). Details,
conflict table and left-out files are in docs/upstream.md.

Left out (weights, captures, logs, media): new bench/results (2022 files), binary media and app assets (61),
docs/work/evidence (24), *.bin / *.gguf data files, and the 7 files the first import already left out.

scripts/build-cpu.sh: build the 11 CPU tests upstream registered since the old pin (they ran as "Not Run").
Checked: build-cpu.sh 16/16 ctest in WSL; sm_86 CUDA objects of the patched files compile, also with the KAR
macros on. No GPU run, no quality gate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-25 12:49:15 +01:00
co-authored by Claude Sonnet 5.5
parent 570201a0dc
commit 87e2633afe
2498 changed files with 641871 additions and 7323 deletions
+18
View File
@@ -4,6 +4,24 @@ bench/prompts/** -text
# launchers keep their platform line endings wherever the repository is cloned
*.sh text eol=lf
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
bin/strata text eol=lf
# copies of real packs' native_experts.txt, parsed byte for byte by tests/core/expert_layout_test.cpp
tests/data/native_experts/** -text
# the quant yardstick's text set: tokenized byte for byte (set.ids.json), never convert its line endings
data/quant_quality/** -text
# the license text is shipped and checked as LF text on every checkout
LICENSE text eol=lf
# container scripts run in Linux: always LF
docker/*.sh text eol=lf
Dockerfile text eol=lf
docker/Dockerfile text eol=lf
docker/compose/* text eol=lf
# Apple tools (codesign, plutil) read these: LF only, wherever the repository is cloned
*.plist text eol=lf
+26
View File
@@ -0,0 +1,26 @@
name: Benchmark
description: Share measurements from your machine, or report a problem with the benchmark tools
title: "[Benchmark] "
labels: ["benchmark"]
body:
- type: markdown
value: |
The title must start with **[Benchmark]**. Keep it, and add the GPU and model after it.
To share a full report, follow the [community benchmark guide](https://github.com/Niko1221/Strata/blob/main/docs/COMMUNITY_BENCHMARKS.md) and open a results-only pull request. The standard protocol is a [draft](https://github.com/Niko1221/Strata/blob/main/docs/BENCHMARK_PROTOCOL.md); existing tools do not implement it yet. Include poor results and failed requests.
- type: textarea
id: what
attributes:
label: What did you measure, or what went wrong
description: Hardware (GPU and VRAM, CPU, RAM, OS), Strata version, model and quantization, the exact command, and the numbers. Paste the report or link the pull request.
validations:
required: true
- type: dropdown
id: reproduction-status
attributes:
label: Reproduction status
options:
- Measured locally
- Unconfirmed (I did not run it)
validations:
required: true
+101
View File
@@ -0,0 +1,101 @@
name: Bug report
description: Something in Strata doesn't work as documented
title: "[Area] "
labels: ["bug"]
body:
- type: markdown
value: |
Thanks for the report. Please read [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md) first.
Search the [open and closed issues](https://github.com/Niko1221/Strata/issues?q=is%3Aissue) first: this may already be tracked, and new evidence belongs in that thread.
Write only what you saw. Do not guess at steps, errors, hardware or severity.
**The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below.
- type: dropdown
id: area
attributes:
label: Area
description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits.
options:
- "[Engine] (speed, kernels, models, the server and API)"
- "[GUI] (the desktop app)"
- "[TUI] (the Terminal: strata launch, connect, monitor)"
- "[Benchmark] (measurements and reports)"
- "[Docs] (documentation)"
- "[Other] (anything else, including setup and installation)"
validations:
required: true
- type: dropdown
id: how
attributes:
label: Desktop app, Terminal or source?
options:
- Desktop app (Windows, Linux or Mac)
- Terminal (the `strata` command)
- Source (START-HERE.bat, setup.sh or a build)
- Docker
- Other
validations:
required: true
- type: textarea
id: what
attributes:
label: What happened
description: What you did, what you got, and what you expected instead. Paste the exact error text if there is one.
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: Smallest steps or command that reproduce it
description: The shortest list of steps that shows the problem. If you cannot make it happen again, say so here.
validations:
required: false
- type: dropdown
id: reproduction-status
attributes:
label: Reproduction status
options:
- Reproduced locally
- Unconfirmed static analysis (I read code or ran a scanner; I did not see it fail)
validations:
required: true
- type: input
id: version
attributes:
label: Strata version
description: "In the app: Settings > About. In the Terminal: `strata --version`. From source: the About tab of the web page, or `engine` in `GET /v1/status`, or the git commit."
placeholder: "Strata 0.2.5 · engine 0.1.50"
validations:
required: true
- type: input
id: hardware
attributes:
label: Graphics card, memory and system
description: The card and its VRAM, the RAM of the PC, and the operating system.
placeholder: "RTX 5070 12 GB · 64 GB RAM · Windows 11"
validations:
required: true
- type: input
id: model
attributes:
label: Model, size and settings
description: The model and size you started, the context, and whether pictures were on. Write what is relevant.
placeholder: "Qwen3.8-Flash-Next IQ2_XS · 128K context · pictures on"
validations:
required: false
- type: textarea
id: log
attributes:
label: Logs
description: |
The app: Settings > Engine > Diagnostics > View logs > Save logs, then drag the file in. The Terminal: paste the output of `strata doctor`. From source: drag in `strata-<model>.log` from your Strata folder.
Remove API keys, passwords and private text first.
validations:
required: false
- type: markdown
value: |
A couple of extras that help a lot:
- Check the [troubleshooting page](https://github.com/Niko1221/Strata/blob/main/docs/TROUBLESHOOTING.md) first, many reports are already solved there.
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Troubleshooting and known issues
url: https://github.com/Niko1221/Strata/blob/main/docs/TROUBLESHOOTING.md
about: Symptom-to-fix table for crashes, out of memory, hangs, and port problems.
@@ -0,0 +1,41 @@
name: Feature request
description: Suggest something new or an improvement
title: "[Area] "
labels: ["enhancement"]
body:
- type: markdown
value: |
Explain what you want in plain language. For a large feature, a change to a default or a refactor, please agree the scope here first. Read [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md).
**The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below.
- type: dropdown
id: area
attributes:
label: Area
description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits.
options:
- "[Engine] (speed, kernels, models, the server and API)"
- "[GUI] (the desktop app)"
- "[TUI] (the Terminal: strata launch, connect, monitor)"
- "[Benchmark] (measurements and reports)"
- "[Docs] (documentation)"
- "[Other] (anything else, including setup and installation)"
validations:
required: true
- type: textarea
id: idea
attributes:
label: What do you want to do?
description: Describe the goal rather than the implementation. Say who needs it and why.
validations:
required: true
- type: textarea
id: workaround
attributes:
label: What do you do today instead?
description: The workaround you use now, if there is one.
validations:
required: false
- type: markdown
value: |
All of this counts: model and architecture support, the server and API, the app and the Terminal, multi-GPU and layer split, images and vision, MCP servers, setup and installation, and performance.
+45
View File
@@ -0,0 +1,45 @@
name: Question
description: Ask how to use Strata, or share a result
title: "[Area] "
labels: ["question"]
body:
- type: markdown
value: |
Not sure how to do something, or want to share numbers from your machine? Ask here. To share a full benchmark, see [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md#share-a-benchmark).
**The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below.
- type: dropdown
id: area
attributes:
label: Area
description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits.
options:
- "[Engine] (speed, kernels, models, the server and API)"
- "[GUI] (the desktop app)"
- "[TUI] (the Terminal: strata launch, connect, monitor)"
- "[Benchmark] (measurements and reports)"
- "[Docs] (documentation)"
- "[Other] (anything else, including setup and installation)"
validations:
required: true
- type: textarea
id: question
attributes:
label: Your question
description: What you're trying to do. Include your version, GPU, and OS if it affects the answer.
validations:
required: true
- type: textarea
id: tried
attributes:
label: What you tried
description: What you already did and where you got stuck.
validations:
required: false
- type: textarea
id: numbers
attributes:
label: Results (optional)
description: Only if you ran a benchmark or measured speed. Model, quant, context, and the tok/s you get.
validations:
required: false
+30
View File
@@ -0,0 +1,30 @@
**The title must start with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], for example "[Engine] fix decode stop on long prompts" or "[GUI] keep the model list after a tab switch".**
<!--
Read CONTRIBUTING.md first. Lead with the problem and the result, not a file-by-file list.
Placeholders below are not test results: replace them with what you observed, or write "none".
-->
## Problem and result
<!-- What triggered this change. How it behaves before and after. -->
## Related discussion
<!-- The issue URL and the maintainer's agreement on scope, when the change needs one (features, refactors, defaults). Write "none" if not applicable. -->
## Approach
<!-- Why this fix. Compatibility effects. Keep unrelated cleanup out of the PR. -->
## Validation
<!-- Exact commands, the revision and the environment tested, what you saw. Keep the three lists apart. -->
**Passed:**
<!-- command, revision/environment, observed result, log -->
**Failed:**
<!-- command and failure, or "none observed" -->
**Not run:**
<!-- check, why, and what stays unverified (for example CUDA, HIP, SYCL or Metal builds you could not do) -->
## Limits
<!-- Known limitations or remaining work. -->
+218
View File
@@ -0,0 +1,218 @@
'use strict';
// Format check for issues and pull requests (see CONTRIBUTING.md and .github/ISSUE_TEMPLATE/*.yml).
// Pure functions only: no network, no filesystem. Used by intake.yml and reopen.yml through reset-bot.js.
const AREAS = ['Engine', 'GUI', 'TUI', 'Benchmark', 'Docs', 'Other'];
const TITLE_RE = new RegExp('^\\[(' + AREAS.join('|') + ')\\] \\S');
const NO_ANSWER = /^(_no response_|none|n\/a|na|-|todo|tbd|\.|\?)$/i;
const NOT_RUN_LABELS = /^\*\*(passed|failed|not run)\s*:?\*\*\s*:?/gim;
// Version the reopened work must be tested on.
const CURRENT_VERSION_RE = /\b0\.2\.\d+|0\.2\.0-beta/i;
// Any version or commit.
const ANY_VERSION_RE = /\bv?\d+\.\d+(\.\d+)*(-[a-z0-9.]+)?\b|\b[0-9a-f]{7,40}\b|\bcommit\b/i;
const HARDWARE_RE = /\b(rtx|gtx|geforce|quadro|tesla|radeon|rx ?\d|instinct|arc|a\d{3,4}|b\d{2,3}|apple|m[1-5]( pro| max| ultra)?|nvidia|amd|intel|gpu|cpu|vram|\d+ ?gb|ram|windows|linux|ubuntu|debian|fedora|arch|macos|mac os|wsl)\b/i;
const REVISION_RE = /0\.2\.\d|beta|\bmain\b|\b[0-9a-f]{7,40}\b/i;
function stripComments(text) {
return String(text || '').replace(/<!--[\s\S]*?-->/g, '');
}
function hasAreaPrefix(title) {
return TITLE_RE.test(String(title || ''));
}
// Issue forms render as "### Label\n\nvalue". Returns { label: value } for those headings.
function parseSections(body) {
const out = {};
let cur = null;
for (const line of stripComments(body).split(/\r?\n/)) {
const m = /^#{1,6}\s+(.+?)\s*#*\s*$/.exec(line);
if (m) {
cur = m[1].trim();
out[cur] = '';
} else if (cur !== null) {
out[cur] += line + '\n';
}
}
for (const k of Object.keys(out)) out[k] = out[k].trim();
return out;
}
function realText(value) {
const t = String(value || '').replace(NOT_RUN_LABELS, '').replace(/\s+/g, ' ').trim();
return NO_ANSWER.test(t) ? '' : t;
}
function findSection(sections, re) {
for (const k of Object.keys(sections)) if (re.test(k)) return { key: k, value: sections[k] };
return null;
}
// Required parts of each issue form: [display name, heading regex, minimum characters of real text].
const FORMS = {
bug: {
detect: /what happened/i,
parts: [
['Area', /^area$/i, 2],
['Desktop app, Terminal or source?', /desktop app, terminal or source/i, 2],
['What happened', /what happened/i, 20],
['Reproduction status', /reproduction status/i, 2],
['Strata version', /strata version/i, 3],
['Graphics card, memory and system', /graphics card|memory and system/i, 3],
],
needsCurrentVersion: 'Strata version',
},
feature: {
detect: /what do you want to do/i,
parts: [
['Area', /^area$/i, 2],
['What do you want to do?', /what do you want to do/i, 20],
],
},
question: {
detect: /your question/i,
parts: [
['Area', /^area$/i, 2],
['Your question', /your question/i, 15],
],
},
benchmark: {
detect: /what did you measure/i,
parts: [
['What did you measure, or what went wrong', /what did you measure/i, 30],
['Reproduction status', /reproduction status/i, 2],
],
needsCurrentVersionInBody: true,
},
};
function checkIssue({ title, body, labels = [], mode = 'intake' }) {
const missing = [];
if (!hasAreaPrefix(title)) {
missing.push('Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] decode stops after 2 minutes".');
}
const text = stripComments(body);
const sections = parseSections(text);
const labelSet = new Set(labels.map((l) => String(l).toLowerCase()));
const needCurrent = mode === 'reopen';
let formKey = null;
for (const [key, f] of Object.entries(FORMS)) {
if (findSection(sections, f.detect)) { formKey = key; break; }
}
if (formKey) {
const form = FORMS[formKey];
for (const [name, re, min] of form.parts) {
const s = findSection(sections, re);
if (!s || realText(s.value).length < min) missing.push('Fill in "' + name + '".');
}
if (needCurrent && form.needsCurrentVersion) {
const s = findSection(sections, /strata version/i);
if (s && realText(s.value) && !CURRENT_VERSION_RE.test(s.value)) {
missing.push('Re-test on Strata 0.2.0-beta and put that version in "' + form.needsCurrentVersion + '". If it no longer happens, say so in a comment instead.');
}
}
if (needCurrent && form.needsCurrentVersionInBody && !CURRENT_VERSION_RE.test(text)) {
missing.push('Say which Strata version you measured on. Re-measure on 0.2.0-beta if you can.');
}
return { ok: missing.length === 0, missing, kind: formKey };
}
// Free-form text (older issues, blank issues).
const plain = realText(text);
const lenient = labelSet.has('enhancement') || labelSet.has('question');
if (plain.length < (lenient ? 40 : 80)) {
missing.push('Describe it in the issue body: what happened, what you expected, and the exact error if there is one. The issue forms (New issue > Bug report) list what to include.');
}
if (!lenient) {
if (!ANY_VERSION_RE.test(text)) missing.push('Add the Strata version (Settings > About, or `strata --version`).');
else if (needCurrent && !CURRENT_VERSION_RE.test(text)) missing.push('Re-test on Strata 0.2.0-beta and name that version in the issue. If it no longer happens, say so in a comment instead.');
if (!HARDWARE_RE.test(text)) missing.push('Add your graphics card with its VRAM, your RAM and your operating system.');
}
return { ok: missing.length === 0, missing, kind: 'free-form' };
}
function checkPull({ title, body, mode = 'intake' }) {
const missing = [];
if (!hasAreaPrefix(title)) {
missing.push('Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] fix decode stop on long prompts".');
}
const text = stripComments(body);
const sections = parseSections(text);
const problem = findSection(sections, /problem|result|summary|what.*change/i);
const validation = findSection(sections, /validation|testing|tests?\b|how.*tested/i);
let valText = '';
if (problem || validation) {
if (!problem || realText(problem.value).length < 20) missing.push('Fill in "Problem and result": what triggered the change, and how it behaves before and after.');
if (!validation || realText(validation.value).length < 20) {
missing.push('Fill in "Validation": the exact commands, the revision and environment tested, what you saw. Keep Passed, Failed and Not run apart.');
} else {
valText = validation.value;
}
} else {
const plain = realText(text);
if (plain.length < 150) {
missing.push('Describe the pull request: the problem and the result. The pull request template shows the parts (Problem and result, Related discussion, Approach, Validation, Limits).');
}
if (!/(problem|result|before|after|fix|because|bug)/i.test(plain)) missing.push('Add "Problem and result": what triggered the change, and how it behaves before and after.');
if (!/(validat|tested|passed|ran |built|build|not run)/i.test(plain)) missing.push('Add "Validation": the exact commands, the revision and environment tested, and what you saw.');
valText = plain;
}
if (mode === 'reopen' && valText && !REVISION_RE.test(valText)) {
missing.push('Say in Validation which revision you tested: rebase on main (or 0.2.0-beta) and re-run your checks.');
}
return { ok: missing.length === 0, missing, kind: 'pull' };
}
function checkItem({ isPull, ...rest }) {
return isPull ? checkPull(rest) : checkIssue(rest);
}
function checklist(missing) {
return missing.map((m) => '- [ ] ' + m).join('\n');
}
const CONTRIB = 'https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md';
function intakeComment(isPull, missing) {
return [
'Thanks for the ' + (isPull ? 'pull request' : 'issue') + '. To keep the tracker readable, every item needs an area prefix in the title and the parts of the ' + (isPull ? 'pull request template' : 'issue form') + ' filled in. This one is missing:',
'',
checklist(missing),
'',
'Edit the ' + (isPull ? 'pull request' : 'issue') + ' (title and description) and this note goes away on its own. If it is still missing parts in 5 days it will be closed, which is not a rejection: fix it and comment `/reopen`.',
'',
'Details: [CONTRIBUTING.md](' + CONTRIB + ')',
].join('\n');
}
function reopenMissingComment(isPull, missing) {
return [
'Not reopened yet. Still missing:',
'',
checklist(missing),
'',
'Edit the ' + (isPull ? 'pull request' : 'issue') + ' and comment `/reopen` again. Details: [CONTRIBUTING.md](' + CONTRIB + ')',
].join('\n');
}
function reopenOkComment(isPull) {
return 'Reopened, thank you. A maintainer will pick it up from here.' + (isPull ? ' If it conflicts with main, rebase it first; that speeds up review.' : '');
}
function staleComment(isPull) {
return [
'Closing this ' + (isPull ? 'pull request' : 'issue') + ' because it still did not follow the format after 5 days. That is housekeeping, not a rejection.',
'',
'To bring it back: fix the title (area prefix) and the missing parts, then comment `/reopen`. A check runs and reopens it, or tells you what is still missing. See [CONTRIBUTING.md](' + CONTRIB + ').',
].join('\n');
}
module.exports = {
AREAS, TITLE_RE, hasAreaPrefix, parseSections, stripComments, realText,
checkIssue, checkPull, checkItem, checklist,
intakeComment, reopenMissingComment, reopenOkComment, staleComment,
};
+192
View File
@@ -0,0 +1,192 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert');
const c = require('./item-check');
const bot = require('./reset-bot');
const bugForm = (over = {}) => {
const f = {
'Area': '[Engine] (speed, kernels, models, the server and API)',
'Desktop app, Terminal or source?': 'Terminal (the `strata` command)',
'What happened': 'Decode stops after two minutes with "CUDA error 700". I expected it to continue.',
'Smallest steps or command that reproduce it': '_No response_',
'Reproduction status': 'Reproduced locally',
'Strata version': 'Strata 0.2.0-beta · engine 0.1.45.3',
'Graphics card, memory and system': 'RTX 5070 12 GB · 64 GB RAM · Windows 11',
...over,
};
return Object.entries(f).map(([k, v]) => `### ${k}\n\n${v}`).join('\n\n');
};
test('title prefix', () => {
assert.ok(c.hasAreaPrefix('[Engine] fix decode'));
assert.ok(c.hasAreaPrefix('[Docs] x'));
assert.ok(!c.hasAreaPrefix('Engine fix'));
assert.ok(!c.hasAreaPrefix('[engine] fix'));
assert.ok(!c.hasAreaPrefix('[Engine]'));
assert.ok(!c.hasAreaPrefix('[Engine] '));
assert.ok(!c.hasAreaPrefix('[Area] foo'));
assert.ok(!c.hasAreaPrefix(''));
assert.ok(!c.hasAreaPrefix(undefined));
});
test('filled bug form passes in both modes', () => {
for (const mode of ['intake', 'reopen']) {
const r = c.checkIssue({ title: '[Engine] decode stops', body: bugForm(), labels: ['bug'], mode });
assert.deepStrictEqual(r.missing, []);
assert.strictEqual(r.kind, 'bug');
}
});
test('bug form: missing parts are named', () => {
const r = c.checkIssue({ title: 'decode stops', body: bugForm({ 'Strata version': '_No response_', 'What happened': 'bad' }) });
assert.ok(!r.ok);
assert.ok(r.missing.some((m) => /title/i.test(m)));
assert.ok(r.missing.some((m) => m.includes('What happened')));
assert.ok(r.missing.some((m) => m.includes('Strata version')));
});
test('reopen needs a 0.2 version, intake does not', () => {
const body = bugForm({ 'Strata version': 'Strata 0.1.44' });
assert.ok(c.checkIssue({ title: '[Engine] x y', body, mode: 'intake' }).ok);
const r = c.checkIssue({ title: '[Engine] x y', body, mode: 'reopen' });
assert.ok(!r.ok);
assert.ok(r.missing.some((m) => m.includes('0.2.0-beta')));
});
test('html comments and placeholders do not count', () => {
const r = c.checkIssue({ title: '[Engine] x y', body: bugForm({ 'What happened': '<!-- describe -->' }) });
assert.ok(r.missing.some((m) => m.includes('What happened')));
});
test('feature and question forms', () => {
const f = '### Area\n\n[GUI] (the desktop app)\n\n### What do you want to do?\n\nLet me pin a model to the top of the list in the app.';
assert.ok(c.checkIssue({ title: '[GUI] pin models', body: f, mode: 'reopen' }).ok);
assert.ok(!c.checkIssue({ title: '[GUI] pin models', body: '### Area\n\n[GUI]\n\n### What do you want to do?\n\n_No response_' }).ok);
const q = '### Area\n\n[Other]\n\n### Your question\n\nHow do I move the model folder to another drive?';
assert.ok(c.checkIssue({ title: '[Other] model folder', body: q }).ok);
});
test('free-form issue', () => {
const good = 'Strata 0.2.0-beta on an RTX 3060 12 GB with 32 GB RAM on Linux: the server hangs when I send two requests at once. Expected both to finish.';
assert.ok(c.checkIssue({ title: '[Engine] hang on two requests', body: good, mode: 'reopen' }).ok);
assert.ok(!c.checkIssue({ title: '[Engine] hang', body: 'it crashes', mode: 'intake' }).ok);
const old = good.replace('0.2.0-beta', '0.1.40');
assert.ok(c.checkIssue({ title: '[Engine] hang', body: old, mode: 'intake' }).ok);
assert.ok(!c.checkIssue({ title: '[Engine] hang', body: old, mode: 'reopen' }).ok);
assert.ok(c.checkIssue({ title: '[Other] idea', body: 'It would help if the app remembered my last model between runs, today I pick it again.', labels: ['enhancement'], mode: 'reopen' }).ok);
});
const prBody = (over = {}) => {
const p = {
problem: 'Decode stopped on prompts above 8k because the stop check read the wrong length. Now it continues.',
validation: '**Passed:** `ctest -R decode`, commit abcdef1, RTX 3060, 12 of 12.\n\n**Failed:** none observed\n\n**Not run:** HIP build',
...over,
};
return `## Problem and result\n<!-- hint -->\n${p.problem}\n\n## Related discussion\nnone\n\n## Approach\nFix the length.\n\n## Validation\n${p.validation}\n\n## Limits\nnone`;
};
test('filled PR passes', () => {
assert.deepStrictEqual(c.checkPull({ title: '[Engine] fix stop', body: prBody(), mode: 'reopen' }).missing, []);
});
test('untouched PR template fails', () => {
const tpl = '## Problem and result\n<!-- What triggered -->\n\n## Validation\n<!-- cmds -->\n\n**Passed:**\n<!-- x -->\n\n**Failed:**\n\n**Not run:**\n';
const r = c.checkPull({ title: '[Engine] fix stop', body: tpl });
assert.ok(!r.ok);
assert.ok(r.missing.some((m) => m.includes('Problem and result')));
assert.ok(r.missing.some((m) => m.includes('Validation')));
});
test('PR: empty body and bad title', () => {
const r = c.checkPull({ title: 'fix', body: null });
assert.ok(!r.ok);
assert.ok(r.missing.length >= 2);
});
test('PR reopen needs a revision', () => {
const body = prBody({ validation: '**Passed:** I tried it and it worked for me on my machine, looked fine.' });
assert.ok(c.checkPull({ title: '[Engine] x y', body, mode: 'intake' }).ok);
assert.ok(!c.checkPull({ title: '[Engine] x y', body, mode: 'reopen' }).ok);
});
test('free-form PR', () => {
const body = 'This fixes a crash when the context is above 8k, because the length was read from the wrong field. Before it aborted, after it continues. I built it on CUDA and ran the decode test, passed.';
assert.ok(c.checkPull({ title: '[Engine] fix crash', body }).ok);
assert.ok(!c.checkPull({ title: '[Engine] fix crash', body: 'fixes stuff' }).ok);
});
test('messages', () => {
const m = c.intakeComment(false, ['a', 'b']);
assert.ok(m.includes('- [ ] a') && m.includes('/reopen') && m.includes('CONTRIBUTING.md'));
assert.ok(c.staleComment(true).includes('/reopen'));
});
// handlers with a fake GitHub client
function fake(calls, extra = {}) {
const rest = {
issues: {
getLabel: async () => ({}),
createLabel: async (a) => calls.push(['createLabel', a.name]),
addLabels: async (a) => calls.push(['addLabels', a.labels]),
removeLabel: async (a) => calls.push(['removeLabel', a.name]),
createComment: async (a) => calls.push(['comment', a.body]),
update: async (a) => calls.push(['update', a.state]),
get: async () => ({ data: extra.live }),
listEvents: async () => {},
listForRepo: async () => {},
},
pulls: { get: async () => ({ data: { mergeable_state: 'clean' } }) },
};
return { rest, paginate: async (fn) => (fn === rest.issues.listEvents ? (extra.events || []) : (extra.items || [])) };
}
const core = { info() {} };
const repo = { owner: 'o', repo: 'r' };
test('intake labels and comments once', async () => {
const calls = [];
const item = { number: 1, title: 'bad', body: '', labels: [], user: { type: 'User' }, author_association: 'NONE' };
await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'opened', issue: item } }, core });
assert.deepStrictEqual(calls.map((c) => c[0]), ['addLabels', 'comment']);
calls.length = 0;
item.labels = [{ name: 'needs-format' }];
await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'edited', issue: item } }, core });
assert.deepStrictEqual(calls, []);
});
test('intake clears the label when edited into shape', async () => {
const calls = [];
const item = { number: 1, title: '[Engine] x y', body: bugForm(), labels: [{ name: 'needs-format' }], user: { type: 'User' } };
await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'edited', issue: item } }, core });
assert.deepStrictEqual(calls.map((c) => c[0]), ['removeLabel', 'comment']);
});
test('reopen: ignores strangers, reopens the author when it passes', async () => {
const issue = { number: 5, state: 'closed', user: { login: 'amy' }, labels: [] };
let calls = [];
const comment = { body: '/reopen', user: { login: 'bob', type: 'User' }, author_association: 'NONE' };
await bot.reopen({ github: fake(calls), context: { repo, payload: { issue, comment } }, core });
assert.deepStrictEqual(calls, []);
const live = { number: 5, title: '[Engine] x y', body: bugForm(), labels: [] };
comment.user.login = 'amy';
await bot.reopen({ github: fake(calls, { live }), context: { repo, payload: { issue, comment } }, core });
assert.deepStrictEqual(calls.map((c) => c[0]), ['update', 'removeLabel', 'comment']);
assert.strictEqual(calls[0][1], 'open');
calls = [];
live.title = 'no prefix';
await bot.reopen({ github: fake(calls, { live }), context: { repo, payload: { issue, comment } }, core });
assert.deepStrictEqual(calls.map((c) => c[0]), ['comment']);
assert.ok(calls[0][1].includes('Not reopened'));
});
test('sweep closes only old flagged items', async () => {
const calls = [];
const old = new Date(Date.now() - 6 * 86400000).toISOString();
const fresh = new Date(Date.now() - 1 * 86400000).toISOString();
const mk = (n, created) => ({ number: n, title: 'bad', body: '', labels: [{ name: 'needs-format' }], created_at: created });
const gh = fake(calls, { items: [mk(1, old), mk(2, fresh)] });
await bot.sweep({ github: gh, context: { repo }, core });
assert.deepStrictEqual(calls.map((c) => c[0]), ['comment', 'update']);
});
+164
View File
@@ -0,0 +1,164 @@
'use strict';
// GitHub-side handlers for intake.yml, reopen.yml and the 5-day sweep.
// They take the actions/github-script objects ({ github, context, core }) and never touch PR code:
// everything comes from the event payload and the REST API.
const check = require('./item-check');
const LABEL = 'needs-format';
const STALE_DAYS = 5;
const MAINTAINER = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
// Items a maintainer closed on purpose stay closed.
const BLOCK_LABELS = new Set(['wontfix', 'invalid', 'duplicate', 'declined']);
function labelNames(item) {
return (item.labels || []).map((l) => (typeof l === 'string' ? l : l.name));
}
async function ensureLabel(github, context) {
const { owner, repo } = context.repo;
try {
await github.rest.issues.getLabel({ owner, repo, name: LABEL });
} catch (e) {
if (e.status !== 404) throw e;
await github.rest.issues.createLabel({
owner, repo, name: LABEL, color: 'fbca04',
description: 'Title or description does not follow CONTRIBUTING.md yet',
});
}
}
async function removeLabel(github, context, number) {
const { owner, repo } = context.repo;
try {
await github.rest.issues.removeLabel({ owner, repo, issue_number: number, name: LABEL });
} catch (e) {
if (e.status !== 404) throw e;
}
}
function itemFromPayload(context) {
const p = context.payload;
return p.pull_request || p.issue;
}
function isPullItem(item, context) {
return Boolean(context.payload.pull_request || item.pull_request);
}
// issues: opened/edited/reopened, pull_request_target: opened/edited/reopened
async function intake({ github, context, core }) {
const { owner, repo } = context.repo;
const item = itemFromPayload(context);
if (!item || (item.user && item.user.type === 'Bot')) return;
if (MAINTAINER.has(item.author_association) && context.payload.action === 'opened') {
// Maintainer items are not nagged on creation.
return;
}
const isPull = isPullItem(item, context);
const labels = labelNames(item);
const hasLabel = labels.includes(LABEL);
const res = check.checkItem({ isPull, title: item.title, body: item.body, labels, mode: 'intake' });
core.info('check ' + (isPull ? 'PR' : 'issue') + ' #' + item.number + ': ' + (res.ok ? 'ok' : res.missing.join(' | ')));
if (res.ok) {
if (hasLabel) {
await removeLabel(github, context, item.number);
await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: 'Thanks, this follows the format now.' });
}
return;
}
if (context.payload.action === 'edited' && !hasLabel) return; // edits only matter for items already flagged
if (hasLabel) return; // one note only
await ensureLabel(github, context);
await github.rest.issues.addLabels({ owner, repo, issue_number: item.number, labels: [LABEL] });
await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: check.intakeComment(isPull, res.missing) });
}
// issue_comment created, body starts with /reopen
async function reopen({ github, context, core }) {
const { owner, repo } = context.repo;
const comment = context.payload.comment;
const issue = context.payload.issue;
if (!/^\s*\/reopen\b/.test(comment.body || '')) return;
if (comment.user.type === 'Bot') return;
const isAuthor = comment.user.login === issue.user.login;
const isMaint = MAINTAINER.has(comment.author_association);
if (!isAuthor && !isMaint) {
core.info('ignored /reopen from ' + comment.user.login + ' (not the author or a maintainer)');
return;
}
const isPull = Boolean(issue.pull_request);
const say = (body) => github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body });
const labels = labelNames(issue);
const wasOpen = issue.state === 'open';
if (labels.some((l) => BLOCK_LABELS.has(l.toLowerCase())) && !isMaint) {
await say('This one was closed on purpose (' + labels.filter((l) => BLOCK_LABELS.has(l.toLowerCase())).join(', ') + '). Please add your new evidence in a comment and a maintainer will decide.');
return;
}
if (wasOpen && !labels.includes(LABEL)) {
core.info('already open, nothing to do');
return;
}
// The bot reads the live item, not the possibly stale event copy.
const live = (await github.rest.issues.get({ owner, repo, issue_number: issue.number })).data;
const res = check.checkItem({ isPull, title: live.title, body: live.body, labels: labelNames(live), mode: 'reopen' });
core.info('reopen check #' + live.number + ': ' + (res.ok ? 'ok' : res.missing.join(' | ')));
if (!res.ok) {
await say(check.reopenMissingComment(isPull, res.missing));
return;
}
if (!wasOpen) {
try {
await github.rest.issues.update({ owner, repo, issue_number: live.number, state: 'open' });
} catch (e) {
await say('The check passed, but GitHub would not reopen it (' + (e.message || e.status) + '). ' + (isPull ? 'If the branch was deleted, restore it or open a new pull request and link this one.' : 'Please open a new issue and link this one.'));
return;
}
}
await removeLabel(github, context, live.number);
let extra = '';
if (isPull) {
try {
const pr = (await github.rest.pulls.get({ owner, repo, pull_number: live.number })).data;
if (pr.mergeable_state === 'dirty') extra = '\n\nIt has conflicts with main now: please rebase it.';
} catch (e) { /* best effort */ }
}
await say(check.reopenOkComment(isPull) + extra);
}
async function labelTime(github, owner, repo, number, fallback) {
const events = await github.paginate(github.rest.issues.listEvents, { owner, repo, issue_number: number, per_page: 100 });
let t = null;
for (const e of events) {
if (e.event === 'labeled' && e.label && e.label.name === LABEL) t = e.created_at;
}
return t || fallback;
}
// scheduled: close items that kept the needs-format label for more than 5 days
async function sweep({ github, context, core }) {
const { owner, repo } = context.repo;
const cutoff = Date.now() - STALE_DAYS * 86400 * 1000;
const items = await github.paginate(github.rest.issues.listForRepo, { owner, repo, state: 'open', labels: LABEL, per_page: 100 });
core.info(items.length + ' open items with ' + LABEL);
for (const item of items) {
const since = new Date(await labelTime(github, owner, repo, item.number, item.created_at)).getTime();
if (since > cutoff) continue;
const isPull = Boolean(item.pull_request);
// Re-check first: an edit that fixed it should have cleared the label already; do not close good items.
const res = check.checkItem({ isPull, title: item.title, body: item.body, labels: labelNames(item), mode: 'intake' });
if (res.ok) {
await removeLabel(github, context, item.number);
continue;
}
await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: check.staleComment(isPull) });
await github.rest.issues.update({ owner, repo, issue_number: item.number, state: 'closed', state_reason: 'not_planned' });
core.info('closed #' + item.number);
}
}
module.exports = { intake, reopen, sweep, LABEL, STALE_DAYS };
+114
View File
@@ -0,0 +1,114 @@
name: Docker images
# Builds the Strata container images of one release from its engine packages and pushes them to ghcr.io.
# Run by hand only (Actions tab -> Docker images -> Run workflow). Nothing starts it on its own.
#
# For each flavor the job downloads the engine package from the release and checks it against the signed update feed
# (docker/fetch-engines.py: the feed's Ed25519 signature, the archive's SHA-256, the manifest hash, the package signature,
# every file's hash), builds the image with docker/build.sh and, only when "push" is on, pushes
# ghcr.io/niko1221/strata:<version>-<flavor> and ghcr.io/niko1221/strata:latest-<flavor>
# The first run with "push" off builds everything without publishing it (a dry run).
on:
workflow_dispatch:
inputs:
release_tag:
description: 'Release tag whose engine packages go into the images (for example v0.2.3)'
required: true
type: string
flavors:
description: 'Flavors to build, comma separated (empty: every flavor the release has a package for)'
required: false
default: ''
type: string
push:
description: 'Push the images to ghcr.io (off: build only, nothing is published)'
required: true
default: false
type: boolean
latest:
description: 'Also move the latest-<flavor> tags (turn off for a pre-release or a test)'
required: true
default: true
type: boolean
source_ref:
description: 'Git ref of the Dockerfile and the Terminal sources (empty: the release tag)'
required: false
default: ''
type: string
permissions:
contents: read
env:
IMAGE: ghcr.io/niko1221/strata
jobs:
plan:
runs-on: ubuntu-24.04
outputs:
flavors: ${{ steps.list.outputs.flavors }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_ref || inputs.release_tag }}
- name: Which flavors does the release have a package for
id: list
env:
WANT: ${{ inputs.flavors }}
TAG: ${{ inputs.release_tag }}
run: |
set -eu
args="--release-tag $TAG --list --skip-missing"
[ -n "$WANT" ] && args="$args --flavors $WANT"
python3 docker/fetch-engines.py $args > list.tsv
cat list.tsv
flavors=$(awk -F'\t' '$3 != "SKIP" {printf "%s\"%s\"", (n++ ? "," : ""), $1}' list.tsv)
[ -n "$flavors" ] || { echo "the release has no engine package for any requested flavor"; exit 1; }
echo "flavors=[$flavors]" >> "$GITHUB_OUTPUT"
image:
needs: plan
runs-on: ubuntu-24.04
timeout-minutes: 120
permissions:
contents: read
packages: write
strategy:
fail-fast: false
max-parallel: 3
matrix:
flavor: ${{ fromJSON(needs.plan.outputs.flavors) }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_ref || inputs.release_tag }}
- name: Free disk space (the runner has about 14 GB; a package plus its image needs about 10 GB)
run: |
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL || true
docker system prune -af >/dev/null 2>&1 || true
df -h /
- name: Log in to ghcr.io
if: ${{ inputs.push }}
env:
REGISTRY_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REGISTRY_USER: ${{ github.actor }}
run: printf '%s' "$REGISTRY_TOKEN" | docker login ghcr.io -u "$REGISTRY_USER" --password-stdin
- name: Fetch, verify, build (and push when push is on)
env:
TAG: ${{ inputs.release_tag }}
FLAVOR: ${{ matrix.flavor }}
PUSH: ${{ inputs.push && '--push' || '' }}
LATEST: ${{ !inputs.latest && '--no-latest' || '' }}
run: |
docker/publish.sh --release-tag "$TAG" --flavors "$FLAVOR" --image "$IMAGE" $PUSH $LATEST
- name: Summary
if: ${{ always() }}
run: |
{
echo "### ${{ matrix.flavor }}"
echo "- release: ${{ inputs.release_tag }}, pushed: ${{ inputs.push }}"
echo "- image: \`$IMAGE:${INPUT_TAG#v}-${{ matrix.flavor }}\`"
} >> "$GITHUB_STEP_SUMMARY"
env:
INPUT_TAG: ${{ inputs.release_tag }}
+58
View File
@@ -0,0 +1,58 @@
name: Intake
# New issues and pull requests that do not follow CONTRIBUTING.md get the needs-format label and one friendly note.
# Items that keep the label for 5 days are closed by the daily sweep, with a note on how to /reopen.
#
# pull_request_target is used instead of pull_request on purpose: a pull request from a fork gets a read-only
# GITHUB_TOKEN under pull_request, so it could not be labelled or commented on. It is safe here because this
# workflow never checks out or runs the pull request's code. It checks out the default branch only (the bot
# scripts) and reads the title and description from the event payload and the REST API.
on:
issues:
types: [opened, edited]
pull_request_target:
types: [opened, edited]
schedule:
- cron: '17 4 * * *'
workflow_dispatch:
permissions:
contents: read
issues: write
pull-requests: write
concurrency:
group: intake-${{ github.event.issue.number || github.event.pull_request.number || 'sweep' }}
cancel-in-progress: false
jobs:
check:
if: github.event_name == 'issues' || github.event_name == 'pull_request_target'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.repository.default_branch }}
sparse-checkout: .github/scripts
persist-credentials: false
- uses: actions/github-script@v7
with:
script: |
const bot = require('./.github/scripts/reset-bot.js');
await bot.intake({ github, context, core });
sweep:
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.repository.default_branch }}
sparse-checkout: .github/scripts
persist-credentials: false
- uses: actions/github-script@v7
with:
script: |
const bot = require('./.github/scripts/reset-bot.js');
await bot.sweep({ github, context, core });
+51
View File
@@ -0,0 +1,51 @@
name: Metal build
# Compile and link the Metal engine on a macOS runner (no GPU needed: the kernels are compiled at run time). The shared host files
# (src/core/verify.cpp, src/prefill, src/program/generate.cpp) call kernel entry points that exist only for CUDA / HIP until Metal gets a
# stub or an implementation; a missing one is a link error here, not on a user's Mac (owner round 9, G6).
on:
pull_request:
paths:
- 'src/**'
- 'include/**'
- 'metal/**'
- 'third_party/**'
- 'CMakeLists.txt'
- '.github/workflows/metal-build.yml'
workflow_dispatch:
permissions:
contents: read
jobs:
metal-link:
runs-on: macos-14
timeout-minutes: 45
env:
# setup.py's LLAMA_CPP_COMMIT and metal/setup_mac.py's metal-cpp pin
LLAMA_CPP_COMMIT: 3cf03257f219afbe7334045ff7c6a06ac68c627d
METAL_CPP_URL: https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip
METAL_CPP_SHA256: 4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4
steps:
- uses: actions/checkout@v4
- name: Tools
run: brew install ninja
- name: metal-cpp
run: |
curl -fsSL "$METAL_CPP_URL" -o metal-cpp.zip
echo "$METAL_CPP_SHA256 metal-cpp.zip" | shasum -a 256 -c -
unzip -q metal-cpp.zip -d _mcpp
- name: llama.cpp (ggml) at the pinned commit
run: |
mkdir llama.cpp && cd llama.cpp
git init -q
git remote add origin https://github.com/ggml-org/llama.cpp.git
git fetch -q --depth 1 origin "$LLAMA_CPP_COMMIT"
git checkout -q FETCH_HEAD
- name: Configure
run: |
cmake -S metal -B build-metal -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DMETAL_CPP_DIR="$PWD/_mcpp/metal-cpp" -DSTRATA_GGML_DIR="$PWD/llama.cpp"
- name: Build and link the engine
run: cmake --build build-metal --target strata
+38
View File
@@ -0,0 +1,38 @@
name: Reopen
# An author comments /reopen on their closed issue or pull request. The check runs and the item is reopened,
# or the bot replies with what is still missing. GitHub does not let authors reopen items a maintainer closed,
# so this workflow does it for them.
#
# issue_comment always runs the workflow file from the default branch with a write-capable token, which is what
# we need for fork authors too. It never checks out or executes the pull request's code: it reads the live
# title and description through the REST API. Only the author of the item or a maintainer can trigger it.
on:
issue_comment:
types: [created]
permissions:
contents: read
issues: write
pull-requests: write
concurrency:
group: reopen-${{ github.event.issue.number }}
cancel-in-progress: false
jobs:
reopen:
if: startsWith(github.event.comment.body, '/reopen') && github.event.comment.user.type != 'Bot'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.repository.default_branch }}
sparse-checkout: .github/scripts
persist-credentials: false
- uses: actions/github-script@v7
with:
script: |
const bot = require('./.github/scripts/reset-bot.js');
await bot.reopen({ github, context, core });
+21
View File
@@ -0,0 +1,21 @@
name: Scripts test
on:
pull_request:
paths:
- '.github/scripts/**'
- '.github/workflows/intake.yml'
- '.github/workflows/reopen.yml'
permissions:
contents: read
jobs:
node-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: node --test .github/scripts/item-check.test.js
@@ -0,0 +1,65 @@
name: Minimal serving runtime
on:
push:
paths:
- .github/workflows/terminal-minimal-server.yml
- requirements.txt
- strata.py
- strata_cli/**
- strata_control/**
- serve/**
- tests/terminal/test_runtime.py
- tools/minimal_server_smoke.py
- tools/strata_tokenizer.py
pull_request:
paths:
- .github/workflows/terminal-minimal-server.yml
- requirements.txt
- strata.py
- strata_cli/**
- strata_control/**
- serve/**
- tests/terminal/test_runtime.py
- tools/minimal_server_smoke.py
- tools/strata_tokenizer.py
workflow_dispatch:
permissions:
contents: read
jobs:
fake-engine:
name: Linux / runtime requirements only
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-python@v7
with:
python-version: '3.11'
- name: Install only pinned runtime requirements
shell: bash
run: |
python -m venv "$RUNNER_TEMP/strata-runtime-venv"
"$RUNNER_TEMP/strata-runtime-venv/bin/python" -m pip install -r requirements.txt
- name: Check fake-engine serving without terminal packages
shell: bash
run: |
python - <<'PY'
import os
import subprocess
from pathlib import Path
report = Path(os.environ['RUNNER_TEMP']) / 'minimal-server-smoke.json'
python = str(Path(os.environ['RUNNER_TEMP']) / 'strata-runtime-venv' / 'bin' / 'python')
subprocess.run([python, 'tools/minimal_server_smoke.py',
'--report', str(report)], check=True)
print(report.read_text())
PY
- name: Run full server suite without terminal packages
shell: bash
run: |
"$RUNNER_TEMP/strata-runtime-venv/bin/python" -m unittest discover -s serve -p 'test_*.py'
@@ -0,0 +1,115 @@
name: Portable monitor client
on:
push:
paths:
- .github/workflows/terminal-portable-monitor.yml
- packaging/monitor_bundle.py
- strata.py
- strata_cli/**
- strata_control/**
- tools/minimal_cli_smoke.py
- tools/portable_monitor_smoke.py
- tools/portable_monitor_pty_smoke.py
- requirements-monitor.txt
- LICENSE
pull_request:
paths:
- .github/workflows/terminal-portable-monitor.yml
- packaging/monitor_bundle.py
- strata.py
- strata_cli/**
- strata_control/**
- tools/minimal_cli_smoke.py
- tools/portable_monitor_smoke.py
- tools/portable_monitor_pty_smoke.py
- requirements-monitor.txt
- LICENSE
workflow_dispatch:
permissions:
contents: read
jobs:
client:
name: ${{ matrix.os }} / Python ${{ matrix.python }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
python: ['3.10', '3.11']
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python }}
- name: Check source CLI without optional packages
shell: bash
run: |
python - <<'PY'
import os
import subprocess
import sys
from pathlib import Path
report = Path(os.environ['RUNNER_TEMP']) / 'minimal-cli-smoke.json'
subprocess.run([sys.executable, 'tools/minimal_cli_smoke.py',
'--report', str(report)], check=True)
print(report.read_text())
PY
- name: Build and smoke test without site packages
shell: bash
run: |
python - <<'PY'
import os
import subprocess
import sys
from pathlib import Path
bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz'
report = bundle.with_name('monitor-stdlib-smoke.json')
subprocess.run([sys.executable, 'packaging/monitor_bundle.py',
'build', str(bundle)], check=True)
subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py',
'--bundle', str(bundle), '--report', str(report)], check=True)
print(report.read_text())
PY
- name: Install optional Textual dependency
if: matrix.python == '3.11'
run: python -m pip install -r requirements-monitor.txt
- name: Smoke test packaged interactive Overview
if: matrix.python == '3.11'
shell: bash
run: |
python - <<'PY'
import os
import subprocess
import sys
from pathlib import Path
bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz'
report = bundle.with_name('monitor-interactive-smoke.json')
subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py',
'--bundle', str(bundle), '--interactive',
'--report', str(report)], check=True)
print(report.read_text())
PY
- name: Check POSIX terminal restoration
if: matrix.os == 'ubuntu-latest' && matrix.python == '3.11'
shell: bash
run: |
python - <<'PY'
import os
import subprocess
import sys
from pathlib import Path
bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz'
report = bundle.with_name('monitor-pty-smoke.json')
subprocess.run([sys.executable, 'tools/portable_monitor_pty_smoke.py',
'--bundle', str(bundle), '--report', str(report)], check=True)
print(report.read_text())
PY
+28
View File
@@ -0,0 +1,28 @@
name: Title area
# Checks that a pull request or issue title starts with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other].
# It reads the title only: no checkout, no labels, no comments, no write access.
on:
pull_request:
types: [opened, edited, reopened, synchronize]
issues:
types: [opened, edited, reopened]
permissions: {}
jobs:
title:
runs-on: ubuntu-latest
steps:
- name: Check the title
env:
TITLE: ${{ github.event.pull_request.title || github.event.issue.title }}
run: |
case "$TITLE" in
"[Engine] "?*|"[GUI] "?*|"[TUI] "?*|"[Benchmark] "?*|"[Docs] "?*|"[Other] "?*)
echo "Title OK: $TITLE" ;;
*)
echo "::error::The title must start with its area and then a short description. Allowed areas: [Engine], [GUI], [TUI], [Benchmark], [Docs], [Other]. Example: \"[Engine] fix decode stop on long prompts\". Your title: $TITLE"
exit 1 ;;
esac
+34
View File
@@ -37,17 +37,51 @@ td.log
/strata-*.json
/strata-*.log
/build-strata.bat
/build-strata-cuda12.bat
/build-cuda12/
/.strata-mcp/
# image encoder (setup.py --vision): build output and the generated build script
build-vision*/
build-vision.bat
build-vision-cuda12.bat
# setup.py outputs (engine, downloads) and release builds
/engine/
/engine-sycl/
/engine-cuda12/
/build-release*/
/dist/
*.done
/third_party/*.zip
# IDEs
.vscode/
.idea/
.cursor/
/.ccache/
/.rocm-win/
# local Windows HIP packaging output
dist-hip/
# Terminal / Desktop split: local venvs, build output and archives never enter git
.terminal-venv/
.terminal-test-venv/
node_modules/
*.dmg
/release/artifacts/
/apps/host/dist/
/apps/desktop/src-tauri/target/
/apps/desktop/src-tauri/resources/node/*
!/apps/desktop/src-tauri/resources/node/.gitignore
# the Control component (bundled CPython + wheels + strata_control) is built by apps/desktop/scripts/stage-control.py
/apps/desktop/src-tauri/resources/control/*
!/apps/desktop/src-tauri/resources/control/.gitignore
# the pruned DeepSeek Harness (MIT) is built by apps/desktop/scripts/stage-harness.mjs
/apps/desktop/src-tauri/resources/harness/*
!/apps/desktop/src-tauri/resources/harness/.gitignore
# screenshots and checkpoints from the Mac rebuild live outside git (StrataSplit\evidence-archive)
/apps/host/docs/evidence/
/apps/host/docs/checkpoints/
+91 -13
View File
@@ -1,23 +1,101 @@
# AGENTS.md
Strata runs the Qwen3.8-Flash-Next mixture-of-experts model (and its Coder, Swift 1.5 and Unsloth variants) on a
normal PC: one NVIDIA or AMD graphics card plus system RAM, on Windows or Linux. It has a C++/CUDA/HIP engine
(`src/`, `include/`), a Python server with an OpenAI- and Anthropic-compatible API and a web app (`serve/`), and a
one-click installer (`setup.py`, started by `START-HERE.bat` / `setup.sh`).
Version 0.2.5, engine 0.1.50. The public model families are DeepSeekV4.1-Flash-1017,
Qwen3.8-Flash-Next and Qwen3.6-35B-A3B. DeepSeek V4.1-Flash runs in the app and in the Terminal
(`strata launch --family deepseek41 --model ist-das-2.00bpw`; sets in
[docs/MODELS.md](docs/MODELS.md#deepseek-v41-flash)). Read **[docs/AI_REFERENCE.md](docs/AI_REFERENCE.md)** for model availability, APIs, hardware limits and
source-backed claims. Articles and videos should use **[docs/MEDIA_KIT.md](docs/MEDIA_KIT.md)**.
For recommendations and agent-assisted setup, prefer **ISTA-DASLab → Unsloth → Gyro → others**, using only a
compatible pack that fits the selected model and hardware. ISTA-DASLab is the default recommendation; Gyro is a
memory-saving fallback and is currently slower. Honor an explicit user choice. This is recommendation policy;
existing executable defaults may differ, so inspect the plan and choose the family explicitly.
Strata has three parts:
- **The app** (`apps/desktop`, the Tauri shell; `apps/host`, the Node host and the web UI). It is for people who do
not want a terminal. One installer per system ([latest release](https://github.com/Niko1221/Strata/releases/latest)):
`Strata-0.2.5-windows-x64-setup.exe`, `Strata-0.2.5-linux-x86_64.AppImage`, `Strata-0.2.5-macos-arm64.dmg`.
The Windows and Linux installers carry no engine: the app downloads the engine for the graphics card on first
start, or installs a file the user already has. The Mac dmg keeps its small Metal engine inside.
- **The Terminal** (`strata.py`, `strata_cli/`, `strata_control/`): the `strata` command. It sets up a model, serves
it and watches it. Agents use this part.
- **The engine and the server** (`src/`, `include/`, `metal/`, `sycl/` for the C++/CUDA/HIP/SYCL/Metal engine;
`serve/` for the Python server with an OpenAI- and Anthropic-compatible API and a web page). `setup.py`, started by
`START-HERE.bat` or `setup.sh`, is setup from a source checkout, for developers. The release paths are the
installer and `strata launch`.
## Installing Strata for a user
Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**: check the PC, pick the model by RAM, run setup non-interactively,
start and verify the server, and connect the user's apps. Never expose the server beyond `127.0.0.1` without
`--api-key`. As an alternative to shell commands, Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md))
offers the same steps as tools.
Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**. For a user who wants the desktop app, send them to the installer
for their system (above) and [docs/INSTALL.md](docs/INSTALL.md). For an agent that has a shell, use the Terminal; the
short version is:
1. Install the Terminal. It needs no administrator rights.
```sh
curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh # Linux, Mac
irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex # Windows PowerShell
```
On Windows, open a new terminal afterwards so that `strata` is on the PATH.
2. Check what would happen. Nothing is changed:
```sh
strata launch --plan --family qwen --model q2_0
```
3. Set up and serve without questions. It downloads the engine for the card and the model (tens of GB), starts the
server, prints the addresses and returns. The server keeps running.
```sh
strata launch --family qwen --model q2_0 --yes --no-tui
```
Useful flags (all of them: `strata launch --help`): `--family`, `--model-path` (files the user already has),
`--data-dir`, `--context 32k|64k|128k`, `--vision off|on|gpu|cpu`, `--parallel N`, `--gpu 0,1`,
`--access local|lan|cloudflare|tailscale`, `--port`, `--api-key-env NAME`, `--new-key`, `--save-preset NAME`,
`--speed faster|full` (DeepSeek), `--output json`. `strata launch --status` shows what is serving, `strata launch --stop` stops it, and
`strata launch --show-key` prints the API key.
4. Connect the user's apps: `strata connect` lists them, `strata connect <app> --check` sends one prompt and one tool
call the way that app does.
Keep the server on `127.0.0.1` unless the user asks for more. Beyond it an API key is recommended: `--access lan` makes one for you, and `--no-api-key` serves without one (a warning, never a refusal; on a public tunnel the warning is stronger). Source setup (`START-HERE.bat`, `setup.sh`) is the fallback for a developer or for a system with no release package; it is
documented in [docs/SOURCE_INSTALL.md](docs/SOURCE_INSTALL.md). Those wrappers exist in a source checkout, not in the
released app. Do not tell an app user to find a `.bat` file.
Source setup does not make an unsupported model or backend compatible. Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md)) offers the same steps as tools.
## Working on the code
- How the engine works, every measured number, the API and all settings: [docs/DETAILS.md](docs/DETAILS.md) and
the [paper](docs/paper/Strata-Paper.pdf).
- AMD (HIP) build and validation: [docs/AMD_HIP.md](docs/AMD_HIP.md); multi-GPU: [docs/MULTI_GPU.md](docs/MULTI_GPU.md).
- Setup's own tests run without a GPU or downloads: `python tools/test_setup_<name>.py` (for example
`tools/test_setup_amd.py`, `tools/test_setup_choices.py`).
- Keep the docs' style: plain words, measured numbers with what they were measured on, no claims without a
measurement.
- The Terminal: [docs/TERMINAL.md](docs/TERMINAL.md) and [docs/TERMINAL_LAUNCH.md](docs/TERMINAL_LAUNCH.md). The app,
the packages and the update feed: [packaging/README.md](packaging/README.md) and [packaging/UPDATES.md](packaging/UPDATES.md).
- AMD (HIP) build and validation: [docs/AMD_HIP.md](docs/AMD_HIP.md); multi-GPU: [docs/MULTI_GPU.md](docs/MULTI_GPU.md);
Mac (Metal): [docs/MAC.md](docs/MAC.md).
- Tests: the Terminal and Control tests are in `tests/terminal` (`python -m pytest tests/terminal`). The app's UI
tests run with `npm test` in `apps/host`. Setup's own tests run without a GPU or downloads:
`python tools/test_setup_<name>.py` (for example `tools/test_setup_amd.py`, `tools/test_setup_choices.py`).
- Keep the docs' style: plain words, short sentences, written for non-technical users first. Give measured numbers
with what they were measured on. Make no claim without a measurement.
## Contributing a change or report
The rules are in **[CONTRIBUTING.md](CONTRIBUTING.md)**. Read it before you open an issue or a pull request, and
follow it whether a person or an agent writes the text. The short version:
- Start every issue and pull request title with its area: `[Engine]`, `[GUI]`, `[TUI]`, `[Benchmark]`, `[Docs]` or
`[Other]`, for example `[Engine] fix …`. A check on GitHub fails a pull request whose title has no area.
- Search the open and closed issues and pull requests first, and add to a thread that already covers your point.
- Agree the scope in an issue before a large feature, a refactor or a change to a default.
- One problem per pull request. Lead with the problem and the result, then the approach, then the validation
(passed, failed and not run, kept apart) and the limits.
- A new feature is opt-in, and the default path stays byte-identical to the last release. Say how you checked.
- Build every backend a file touches (CUDA, HIP, SYCL) before asking for review.
- Change a default only where you measured it faster, and show the numbers with what they were measured on.
- Never submit measurements, logs or reproduction steps you did not produce. Mark a finding from reading code as
unconfirmed static analysis.
- A report from hardware the maintainers do not have is welcome. Follow
[docs/COMMUNITY_BENCHMARKS.md](docs/COMMUNITY_BENCHMARKS.md), compare against a same-day run of the build you are
testing, and say what you did not test.
- Open test requests and the hardware that is wanted are listed in [docs/TEST_REQUESTS.md](docs/TEST_REQUESTS.md).
+19
View File
@@ -0,0 +1,19 @@
@echo off
rem Benchmark this Strata install the way it is used and write a report you can share (docs/COMMUNITY_BENCHMARKS.md).
rem It starts the model with your settings (or uses the one already running), takes about 10 minutes and changes nothing.
rem Options: --clients 4 (several requests at once), --long (a 32K prompt), --compare <older results folder>.
rem This is the quick speed check. The standard benchmark (docs/BENCHMARK_PROTOCOL.md), whose results other people can compare with, is `strata bench run`.
setlocal
title Strata - benchmark
cd /d "%~dp0"
if not exist ".venv\Scripts\python.exe" (
echo Strata is not set up here yet: run START-HERE.bat first.
pause
exit /b 1
)
echo Quick speed check. For results other people can compare with (the standard benchmark, a few minutes), run: .venv\Scripts\python.exe strata.py bench run
echo.
".venv\Scripts\python.exe" tools\strata_bench.py %*
set "RC=%ERRORLEVEL%"
pause
exit /b %RC%
File diff suppressed because it is too large Load Diff
+122
View File
@@ -0,0 +1,122 @@
# Contributing to Strata
**AI assistance is welcome. The contributor is responsible for understanding the change and supplying real evidence.**
These rules apply to issues, pull requests, benchmark reports, and the agents helping prepare them.
You should be able to explain every changed line and answer review questions about it.
## Before starting
1. Search [issues](https://github.com/Niko1221/Strata/issues) and
[pull requests](https://github.com/Niko1221/Strata/pulls), including closed discussions. Add new evidence to an
existing thread when it covers your problem.
2. Read [AGENTS.md](AGENTS.md) and the documentation for the component you want to change.
3. Get maintainer agreement on scope before substantial features, refactors, architecture changes, or changes to
defaults. Describe the user problem, proposed behavior, and tradeoffs in an issue first. Agreement on scope
does not guarantee a merge. Focused fixes and benchmark reports can go straight to a PR.
4. Keep one problem per PR. Update that PR after feedback; do not open competing attempts for the same change.
Do not resubmit a declined proposal under a different title or through another agent. If new evidence changes
the situation, bring it to the original discussion and let a maintainer decide whether to reopen it.
## Report a problem people can investigate
Use the matching [issue form](https://github.com/Niko1221/Strata/issues/new/choose). A bug report should include:
- The smallest steps or command that reproduce the problem, and the expected and actual behavior.
- Strata version or commit, OS, GPU and VRAM, and relevant model, quantization, and configuration.
- The exact error and relevant logs, with credentials and private content removed.
- Whether you reproduced it yourself. Label a finding based only on reading code or a scanner as
**unconfirmed static analysis**, and explain the suspected path without presenting it as an observed failure.
Do not invent reproduction steps, errors, affected hardware, or severity. If you cannot reproduce something,
say what you inspected and what would verify the hypothesis. Feature requests should explain a concrete user
need and the current workaround. Questions should say what you tried and where you got stuck.
Example structure, with placeholders to replace with actual observations:
```text
Problem: <one observed behavior>
Environment: <commit, OS, GPU/VRAM, model/quant, relevant settings>
Reproduce: <exact command or short sequence>
Expected: <documented or intended behavior>
Actual: <observed behavior and exact error>
Evidence: <sanitized log attachment>
Reproduction status: <reproduced locally OR unconfirmed static analysis>
```
## Titles
Every issue and pull request title starts with its area in square brackets, then a short description: `[Engine]`, `[GUI]`, `[TUI]`,
`[Benchmark]`, `[Docs]` or `[Other]`. For example `[Engine] fix decode stop on long prompts` or `[GUI] keep the model list after a tab
switch`. The issue forms ask for the area and a check on the title fails when the prefix is missing.
## Prepare a focused pull request
Lead with the problem and resulting behavior. Explain why the approach is needed, the important limits, and
any compatibility effects. Link the issue and scope agreement when applicable. A file-by-file narration or
an AI-generated summary of the diff is not a substitute for this explanation.
- Keep unrelated formatting, cleanup, dependency changes, and speculative abstractions out of the PR.
- Add documentation where it changes what a user or developer needs to know. Avoid repeated summaries,
speculative roadmaps, and generated documentation with no actionable information.
- Preserve existing behavior outside the intended change. New features are opt-in; follow the default-path
and performance requirements in [AGENTS.md](AGENTS.md).
- Read the complete diff, including generated files, before submitting. Remove debugging output, secrets,
private paths, and accidental files.
- Prefer a small relevant regression check over tests that only restate the implementation. Documentation-only
changes need link, example, and consistency checks; they do not require GPU builds.
## Show the validation you actually performed
List exact commands, the revision and environment tested, and observed outcomes. Keep **passed**, **failed**,
and **not run** separate. Include relevant output or a log attachment. A command you suggest running is not
evidence that it passed; a CI run on a different revision is not validation of the submitted code.
Build every backend a code change touches, including CUDA, HIP, and SYCL where applicable, before requesting
review. For changes that need hardware execution, report that execution separately from compilation. A mock,
static check, or successful build does not establish hardware correctness. If you lack a required environment,
keep the PR as a draft, identify the missing checks, and ask for targeted help in the same thread. Do not claim
compatibility you have not tested.
Performance claims need before/after runs on the same hardware and workload, with every changed setting
identified. Preserve the individual runs, failures, and variability. Follow the
[community measurement guide](docs/COMMUNITY_BENCHMARKS.md); standard submissions will use the
[benchmark protocol](docs/BENCHMARK_PROTOCOL.md) once it is activated. One fast run does not justify changing a
default or claiming a speedup for other machines.
Example PR body; placeholders are not test results:
```text
Problem and result: <trigger; behavior before and after the change>
Related discussion: <issue URL and scope agreement, when required>
Approach: <why this fix; relevant compatibility effects>
Validation:
Passed: <exact command, revision/environment, observed result, log>
Failed: <exact command and failure, or none observed>
Not run: <check, reason, and what remains unverified>
Limits: <known limitations or remaining work>
```
## Rules for AI-assisted work
Use agents to help investigate, implement, and explain work that you can review. Before submitting, verify
their claims against the source, actual command output, or a cited primary reference.
Never submit fabricated measurements, invented test results, fake logs, or copied claims you have not checked.
Do not turn a repository scan into a batch of speculative issues or PRs. Consolidate related findings, establish
their effect, and submit the useful evidence. Do not present an agent's confidence or another model's approval
as validation. Keep review replies concise and address the requested change or evidence directly.
Maintainers may request a smaller change, return a PR to draft, or close a submission that lacks evidence,
duplicates existing work, or ignores agreed scope. A smaller, understandable contribution with honest limits
is easier to review and maintain.
## Share a benchmark
A results-only PR should contain the human report, raw measurements, sanitized configuration, and supporting
logs. Keep it separate from engine changes and include poor results and failed requests.
The [current community benchmark guide](docs/COMMUNITY_BENCHMARKS.md) remains available for measurements made
with today's tools. The [new protocol](docs/BENCHMARK_PROTOCOL.md) defines the draft standard and future approval
workflow. Its draft status must remain visible: existing reports are not automatically standard or approved.
+96 -101
View File
@@ -1,115 +1,110 @@
# syntax=docker/dockerfile:1
# Strata, built FROM SOURCE (NVIDIA CUDA 13). The engine is compiled here, packaged as an engine component package and then
# installed into the same runtime image as the ready-made ones (docker/Dockerfile): same Terminal, same entrypoint, same /data volume.
#
# Strata: Qwen3.8-Flash-Next on NVIDIA GPUs (RTX 30/40/50, 12+ GB VRAM; two or
# three cards can share one model, 8 GB each - docs/MULTI_GPU.md).
# Most people want the ready-made images instead (nothing compiled): docs/DOCKER.md.
#
# The engine is compiled during docker build, so the first container start only
# downloads the model (~70 GB) and starts the server. docker build has no GPU,
# so the CUDA architectures are fixed here instead of read from nvidia-smi: the
# engine is a fat binary with a cubin per listed arch, and the runtime picks the
# one matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster
# build; a card outside the set needs a rebuild with its own arch.
# docker build -t strata:src . # RTX 20/30/40/50 (compiles for each, ~25 min)
# docker build -t strata:src --build-arg CUDA_ARCHITECTURES=86 . # one card only (faster); 86 = RTX 30, 89 = RTX 40, 120 = RTX 50
# docker build -t strata:src-cuda12 --build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 \
# --build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 . # GTX 10 / P100 / V100 (driver 575+)
# docker run --rm --gpus all -p 127.0.0.1:8080:8080 --ulimit memlock=-1 --shm-size 2g --stop-timeout 120 \
# -v strata-data:/data -e MODEL=IQ3_XXS -e API_KEY=change-me-please-123 strata:src
#
# Build:
# docker build -t strata .
# docker build -t strata --build-arg CUDA_ARCHITECTURES=89 . # RTX 40 only
# docker build has no GPU, so the CUDA architectures are given here instead of read from nvidia-smi. The engine is a fat binary with
# a machine-code part per listed architecture (plus PTX for the newest, which later cards can JIT), and the runtime picks the one
# matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster build. Native code for the CPU that builds the image is NOT
# used (STRATA_PORTABLE=ON), so the image runs on any x86-64 CPU with AVX2.
#
# Run (host needs an NVIDIA driver >= 580 and nvidia-container-toolkit):
# docker run --rm --gpus all \
# -p 8080:8080 \
# --ulimit memlock=-1 \
# -v strata-data:/data \
# -e MODEL=IQ2_XS \
# strata
#
# Setup choices are env vars, read by docker-entrypoint.sh: FAMILY, MODEL, CONTEXT,
# VISION (no | yes | cpu), KV (int8 | q4_0 | k8v4), GPU (one card) or GPUS ("0,2"
# or "all", with LAYER_SPLIT), LOW_RAM (auto | on | off), HOST, PORT, API_KEY.
#
# Only the model files, the prepared pack, the MTP layer and the install config
# live in the /data volume; the engine is part of the image. Strata loads 32-62 GB
# into RAM, so a capped container needs -e LOW_RAM=on: setup.py reads the RAM from
# /proc/meminfo, which here is the host's total, not the container's limit. Add an
# API key before exposing the port to a network: -e API_KEY=<secret>. Pass
# -e REINSTALL=1 to change the model settings later.
#
# --gpus all on a host with two usable cards: setup takes both (the layer split is
# its recommended default). Pin one card with -e GPU=0, or name them with
# -e GPUS=0,2. A volume set up for one card switches to the pair on its first start
# on a two-card host unless GPU or GPUS pins it. LOW_RAM=on runs on one card.
# Plain legacy-builder features only (no heredocs, no --mount). AMD (HIP) and Intel (SYCL) source builds: docs/AMD_HIP.md, docs/INTEL.md.
FROM nvidia/cuda:13.0.0-devel-ubuntu24.04
# STRATA_EXECV=1: setup.py replaces itself with the server, so the server is PID 1
# and docker stop's SIGTERM reaches it (see setup.start). Normal Linux starts, which
# don't set it, keep spawning the server as a child.
ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 LANG=C.UTF-8 STRATA_EXECV=1
ARG CUDA_IMAGE=nvidia/cuda:13.0.0-devel-ubuntu24.04
ARG RUNTIME_BASE=ubuntu:24.04
# ---- 1. compile the engine and make its component package
FROM ${CUDA_IMAGE} AS engine-build
ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 PATH=/venv/bin:$PATH
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential ca-certificates curl git libatomic1 libgomp1 \
python3 python3-pip python3-venv unzip \
build-essential ca-certificates git libgomp1 libatomic1 python3 python3-pip python3-venv unzip \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /opt/strata
WORKDIR /src
COPY . .
# RTX 20 (75), RTX 30 (86), RTX 40 (89), RTX 50 (120), plus 80 for A-series. CMakeLists
# refuses anything below 75. BUILD_VISION=0 skips the image encoder build.
ARG CUDA_ARCHITECTURES=75;80;86;89;120
ARG CUDA_ARCHITECTURES="75;80;86;89;120"
ARG BUILD_VISION=1
ARG ENGINE_VERSION=
RUN python3 -m venv /venv && /venv/bin/pip install --no-cache-dir -r requirements.txt -r requirements-build.txt
# llama.cpp at the pinned commit (ggml for the engine, mtmd for pictures), exactly as setup.py fetches it
RUN /venv/bin/python -c "import setup; print(setup.get_llama_cpp())"
RUN set -e; \
real=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do real="$real;${a}-real"; done; real=${real#;}; \
last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \
sm60=OFF; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do if [ "$a" -lt 75 ]; then sm60=ON; fi; done; \
/venv/bin/cmake -G Ninja -S . -B build -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF \
-DSTRATA_EXPERIMENTAL_SM60=$sm60 \
-DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_Q6K_EXPERTS=ON -DSTRATA_MMQ_KQUANTS=ON \
"-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual" -DSTRATA_GGML_DIR=/src/third_party/llama.cpp; \
/venv/bin/cmake --build build --target strata strata_kq -j "$(nproc)"; \
if [ "$BUILD_VISION" = "1" ]; then \
/venv/bin/cmake -G Ninja -S tools/vision -B build-vision -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR=/src/third_party/llama.cpp \
-DSTRATA_VISION_CUDA=ON -DSTRATA_PORTABLE=ON -DGGML_CUDA_NCCL=OFF "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual"; \
/venv/bin/cmake --build build-vision --target strata-vision -j "$(nproc)"; \
fi
RUN set -e; \
mkdir -p /stage /engine; \
cp build/strata /stage/; \
[ -f build/libstrata_kq.so ] && cp build/libstrata_kq.so /stage/ || true; \
[ -f build-vision/bin/strata-vision ] && cp build-vision/bin/strata-vision /stage/ || true; \
ver="${ENGINE_VERSION:-$(sed -n 's/^[[:space:]]*project([^)]*VERSION[[:space:]]*\([0-9][0-9.]*\).*/\1/p' CMakeLists.txt | head -1)}"; \
cudafull=$(nvcc --version | sed -n 's/.*release \([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1); cudamajor=${cudafull%%.*}; \
if [ "$cudamajor" = 13 ]; then mindriver=580.65; else mindriver=575.51; fi; \
vision_archs=""; [ -f /stage/strata-vision ] && vision_archs=", \"vision_archs\": \"$CUDA_ARCHITECTURES\""; \
echo "{\"version\": \"$ver\", \"source\": \"docker build\", \"archs\": \"$CUDA_ARCHITECTURES\", \"cuda\": \"$cudafull\", \"portable\": true${vision_archs}}" > /stage/BUILD.json; \
python3 packaging/collect_libs.py --binary build/strata --search /usr/local/cuda/lib64 --out /stage --also 'libcublasLt.so*'; \
archs=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do archs="$archs --arch sm_$a"; done; \
last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \
python3 packaging/package_engine.py --src /stage --backend cuda --version "$ver" --out /engine $archs --arch "compute_$last" \
--min-driver nvidia=$mindriver --variant cuda$cudamajor --platform linux-x86_64 --build-id "docker-source-${ver}-cuda${cudafull}" --include SYSTEM-LIBS.txt --include 'libstrata_kq*' \
--include strata-vision; \
for d in /engine/*/; do python3 packaging/package_engine.py --verify "$d"; python3 packaging/binary_deps.py "$d"; done
RUN python3 -m venv .venv \
&& .venv/bin/pip install --no-cache-dir --upgrade pip \
&& .venv/bin/pip install --no-cache-dir -r requirements.txt \
&& chmod +x setup.sh docker-entrypoint.sh
# llama.cpp at the pinned commit, then the engine and the image encoder, built
# exactly the way setup.py builds them. BUILD.json is what setup.py reads to
# decide whether an engine is current: source=local with a matching src hash
# means the first start reuses it instead of recompiling.
RUN .venv/bin/python - <<'PYEOF'
import json, os, pathlib, shutil
import setup
llama = setup.get_llama_cpp()
nvcc, _ = setup.find_nvcc()
arch = os.environ.get("CUDA_ARCHITECTURES", "75;80;86;89;120").strip().strip('"').replace(",", ";")
vision = "gpu" if os.environ.get("BUILD_VISION", "1") == "1" else "none"
setup.cmake_build(setup.ROOT, setup.ROOT / "build", "strata",
["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF",
f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}",
f"-DSTRATA_GGML_DIR={llama}"], None, "build-strata.bat")
if vision != "none":
setup.cmake_build(setup.ROOT / "tools" / "vision", setup.ROOT / "build-vision", "strata-vision",
[f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=ON",
f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}"], None, "build-vision.bat")
eng = setup.ROOT / "engine"
eng.mkdir(exist_ok=True)
shutil.copy2(setup.ROOT / "build" / setup.EXE, eng / setup.EXE)
if vision != "none":
shutil.copy2(setup.ROOT / "build-vision" / "bin" / setup.VEXE, eng / setup.VEXE)
bindir = pathlib.Path(nvcc).parent
meta = {"source": "local", "version": setup.source_version(),
"archs": [int(a.split("-")[0]) for a in arch.split(";") if a.split("-")[0].isdigit()], "vision": vision,
"cuda_dirs": [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()],
"src": setup.source_hash(setup.ENGINE_SOURCES),
"vision_src": setup.source_hash(setup.VISION_SOURCES) if vision != "none" else None}
(eng / "BUILD.json").write_text(json.dumps(meta, indent=1))
PYEOF
# the cmake trees are build-time only; the engine itself is what the container needs
RUN rm -rf build build-vision
# ---- 2. the Terminal (the release archive, built here)
FROM ${RUNTIME_BASE} AS terminal
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends python3 ca-certificates git && rm -rf /var/lib/apt/lists/*
COPY . /src/
RUN python3 /src/packaging/package_terminal.py --out /out --cache /cache \
&& mkdir -p /opt/strata \
&& tar -xzf /out/strata-terminal-*-linux-x86_64.tar.gz -C /opt/strata \
&& mv /opt/strata/strata-terminal-* /opt/strata/terminal \
&& /opt/strata/terminal/bin/strata --version
# llama.cpp at the commit setup.py pins: fetched here, so the first start does not depend on GitHub. Only gguf-py (the model preparation
# tools) and the file setup.py looks for (ggml/CMakeLists.txt) are kept: 170 MB become a few
RUN cd /opt/strata/terminal && STRATA_CONTROL_INSTALL=1 STRATA_INSTALL_DIR=/opt/strata/seed PYTHONNOUSERSITE=1 \
/opt/strata/terminal/python/bin/python3 -c "import setup; print(setup.get_llama_cpp())" \
&& rm -rf /opt/strata/seed/third_party/*.zip* \
&& cd /opt/strata/seed/third_party/llama.cpp \
&& find . -mindepth 1 -maxdepth 1 ! -name gguf-py ! -name ggml ! -name 'LICENSE*' -exec rm -rf {} + \
&& find ggml -mindepth 1 -depth ! -type d ! -name CMakeLists.txt -delete && find ggml -mindepth 1 -type d -empty -delete \
&& du -sh /opt/strata/seed
# ---- 3. the runtime image (the same as docker/Dockerfile's, FLAVOR=cuda)
FROM ${RUNTIME_BASE}
ARG STRATA_VERSION=dev
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends tini ca-certificates libgomp1 libatomic1 libnuma1 zlib1g \
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/*
COPY --from=terminal /opt/strata/terminal /opt/strata/terminal
COPY --from=terminal /opt/strata/seed /opt/strata/seed
COPY --from=engine-build /engine/ /opt/strata/components/engine/
COPY docker/entrypoint.sh docker/healthcheck.sh /opt/strata/
COPY docker/strata-wrapper.sh /usr/local/bin/strata
RUN chmod 0755 /opt/strata/entrypoint.sh /opt/strata/healthcheck.sh /usr/local/bin/strata
ENV STRATA_COMPONENTS_DIR=/opt/strata/components STRATA_INSTALL_DIR=/data/install XDG_STATE_HOME=/data/state \
XDG_CONFIG_HOME=/data/config HOME=/data/home PORT=8080 LANG=C.UTF-8 PYTHONUNBUFFERED=1 PYTHONNOUSERSITE=1 STRATA_IN_DOCKER=1 \
NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility
VOLUME ["/data"]
EXPOSE 8080
# /health is answered before the API key gate, so it works with or without one.
# The port only opens after the model loads (1-3 minutes, longer on a first run),
# so the start period is generous: a too short one marks a still-loading container
# unhealthy and a restart policy would kill it mid-download.
HEALTHCHECK --interval=30s --timeout=5s --start-period=600s --retries=3 \
CMD curl -fs "http://127.0.0.1:${PORT:-8080}/health" || exit 1
ENTRYPOINT ["./docker-entrypoint.sh"]
LABEL org.opencontainers.image.title="Strata" com.strata.flavor="cuda" com.strata.build="from-source" org.opencontainers.image.version="${STRATA_VERSION}"
HEALTHCHECK --interval=30s --timeout=8s --start-period=2h --retries=3 CMD ["/opt/strata/healthcheck.sh"]
STOPSIGNAL SIGTERM
ENTRYPOINT ["/usr/bin/tini", "--", "/opt/strata/entrypoint.sh"]
CMD ["run"]
+188
View File
@@ -0,0 +1,188 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="apps/host/public/brand/strata-lockup-dark.svg">
<img src="apps/host/public/brand/strata-lockup-light.svg" alt="Strata" width="340">
</picture>
</p>
<h3 align="center">Leistungsstarke KI auf deinem eigenen Computer.</h3>
<p align="center">Chatten, programmieren und mit Bildern arbeiten, lokal.</p>
<p align="center">
<a href="#modelle">Modelle</a> · <a href="#installation"><b>Installation</b></a> ·
<a href="#hardware">Hardware</a> · <a href="#tools">Tools</a> ·
<a href="#hilfe">Hilfe</a> · <a href="#strata-unterstützen">Unterstützen</a>
</p>
<p align="center">
<a href="https://github.com/Niko1221/Strata/releases/latest"><img src="https://img.shields.io/github/v/release/Niko1221/Strata?label=download&color=0ab887" alt="Strata herunterladen"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Niko1221/Strata" alt="MIT-Lizenz"></a>
<a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Strata auf Buy Me a Coffee unterstützen"></a>
</p>
<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <b>Deutsch</b> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a></sub></p>
**Kostenlos, Open Source und ganz in deiner Hand.** Nutze Strata auf dem Desktop oder mit deinen liebsten Coding-Tools. Kein Konto nötig.
## Modelle
Wir empfehlen **zuerst ISTA-DASLab**, danach **Unsloth** und andere Anbieter, soweit ein passendes Modell in deinen Speicher passt.
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.8-Flash-Next</b></summary>
| Anbieter | Auswahl |
| --- | --- |
| **ISTA-DASLab · empfohlen** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) zum Programmieren. |
| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 |
| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Geringerer Speicherbedarf, aber langsamer. |
| **Weitere Optionen** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) |
[Größen, Speicherbedarf und Kompatibilität vergleichen](docs/MODELS.md).
</details>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.6-35B-A3B</b></summary>
**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Das sind die derzeit dokumentierten Pakete für dieses Modell.
[Modellanleitung und Kompatibilität](docs/QWEN36.md).
</details>
<details>
<summary><img src="docs/media/models/deepseek.svg" width="22" alt="" align="middle"> &nbsp;<b>DeepSeekV4.1-Flash-1017</b></summary>
In der **Desktop-App** und im **Terminal**. Was nicht in den Arbeitsspeicher passt, wird von deiner SSD gelesen. Darum brauchst du viel freien Speicherplatz.
| Set (IST-DAS) | Download | Freier Speicherplatz nötig |
| --- | ---: | ---: |
| 1.75 bpw | 239 GB | etwa 245 GB |
| 2.00 bpw | 257 GB | etwa 265 GB |
| 2.25 bpw | 274 GB | etwa 280 GB |
Läuft auf NVIDIA RTX 30, 40 und 50 (Windows und Linux) und auf AMD Radeon AI PRO R9700 (Linux). Das Setup lädt die Dateien und die DeepSeek-Engine herunter und startet dann das Modell.
```sh
strata launch --family deepseek41 --model ist-das-2.00bpw --plan
```
Gemessen mit dem 2.00-bpw-Set auf Strata 0.2.5. „Ausgabe“ ist das Tempo der Antwort, „Prompt“ zeigt, wie schnell Strata deine Eingabe liest.
| Hardware | Ausgabe | Prompt |
| --- | ---: | ---: |
| RTX 5070 12 GB, 64 GB RAM | 4 bis 6 Token/s | etwa 110 Token/s (4K) |
| RTX 3060 12 GB, 46 GB RAM | 9 bis 11 Token/s | etwa 155 Token/s (4K) |
| 1x Radeon AI PRO R9700, 251 GB RAM | 21 bis 25 Token/s | 320 bis 360 Token/s (8K) |
| 4x Radeon AI PRO R9700 | 74 bis 77 Token/s | 400 bis 450 Token/s (8K) |
[Speicher, Festplatte und Details](docs/DEEPSEEK41.md) · [Versionshinweise](https://github.com/Niko1221/Strata/releases)
</details>
<a id="the-other-sizes"></a>
Unsicher, was passt? [Wähle ein Modell für deinen Computer](docs/MODELS.md#pick-by-memory).
## Installation
<a id="option-a-the-strata-app"></a>
### Desktop-App
**[Strata für Windows, Linux oder Mac herunterladen →](https://github.com/Niko1221/Strata/releases/latest)**
Installiere die App, wähle ein Modell und leg mit dem Chat los. Es gibt einen Installer pro System. Beim ersten Start lädt die App die Engine für deine Grafikkarte herunter. [Hilfe zum Installer](docs/INSTALL.md#the-app).
<sub>Dateien: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg`</sub>
<p align="center">
<img src="docs/media/app-chat.png" width="900" alt="Strata-Desktop-App mit Chat und Live-Codevorschau nebeneinander">
<br><sub>Chat, Dateien und Live-Vorschau in einem Fenster.</sub>
</p>
<a id="option-b-the-terminal-one-line"></a>
### Terminal-App
Lieber im Terminal? Installiere Strata und starte dann **`strata launch`**.
<details open>
<summary><b>Installationsbefehle</b></summary>
**Linux / Mac**
```sh
curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh
```
**Windows PowerShell**
```powershell
irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
```
Öffne unter Windows danach ein neues Terminal. Dann:
```sh
strata launch
```
Folge den Anweisungen, um ein Modell herunterzuladen und zu starten. [Terminal-Anleitung](docs/TERMINAL_LAUNCH.md).
</details>
<p align="center">
<img src="docs/media/terminal-monitor.png" width="900" alt="Strata-Terminal-App mit Modellaktivität, Tempo, Speicher und letzten Anfragen">
<br><sub>Behalte Modell und Hardware im Blick, während es läuft.</sub>
</p>
<a id="build-from-source"></a>
[Aus dem Quellcode bauen](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Vollständige Installationsanleitung](docs/INSTALL.md)
<a id="what-you-need"></a>
## Hardware
| Unterstützte Hardware | Anleitung |
| --- | --- |
| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [NVIDIA-Setup](docs/INSTALL.md#what-you-need) |
| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [AMD-Setup](docs/AMD_HIP.md) |
| **AMD Radeon RX 6800 / 6900 · experimentell** | [RX-6000-Setup](docs/AMD_HIP.md#rdna2-gfx1030) |
| **Intel Arc · Linux** | [Intel-Setup](docs/INTEL_ARC.md) |
| **Apple Silicon · M1 oder neuer** | [Mac-Setup](docs/MAC.md) |
| **AMD Ryzen AI Max · Strix Halo** | [Strix-Halo-Setup](docs/STRIX_HALO.md) |
<a id="using-it"></a>
## Tools
**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, und weitere über die OpenAI- und Anthropic-kompatiblen APIs.
Führe **`strata connect`** aus, um die Einrichtung für dein Tool zu sehen. [Verbindungsanleitung](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect).
<a id="guides"></a>
<a id="how-fast-is-it"></a>
<a id="how-does-it-work"></a>
<a id="something-went-wrong"></a>
## Hilfe
[Alle Anleitungen](docs) · [Fehlerbehebung](docs/TROUBLESHOOTING.md) · [Fehler melden](https://github.com/Niko1221/Strata/issues/new/choose) ·
[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [So funktioniert es](docs/HOW_IT_WORKS.md) · [Mitmachen](CONTRIBUTING.md)
## Strata unterstützen
**Hilf mit, lokale KI für alle offen zu halten.** Ein Kaffee hilft, Entwicklung und Tests auf mehr Hardware zu finanzieren.
<a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee: Strata unterstützen" height="48"></a>
[MIT-Lizenz](LICENSE) · [Danksagung und Modelllizenzen](docs/HOW_IT_WORKS.md#credits) · [Datenschutz](docs/SAFETY.md)
<a id="option-c-let-your-ai-set-it-up"></a>
<sub>Für KI-Tools und automatische Leser: <a href="AGENTS.md">technische Referenz</a> · <a href="docs/AI_SETUP.md">Setup-Anleitung</a>.</sub>
**Sponsoring, Hardware-Partnerschaften oder Zusammenarbeit:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com).
+188
View File
@@ -0,0 +1,188 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="apps/host/public/brand/strata-lockup-dark.svg">
<img src="apps/host/public/brand/strata-lockup-light.svg" alt="Strata" width="340">
</picture>
</p>
<h3 align="center">IA potente en tu propio ordenador.</h3>
<p align="center">Chatea, programa y trabaja con imágenes, en local.</p>
<p align="center">
<a href="#modelos">Modelos</a> · <a href="#instalación"><b>Instalación</b></a> ·
<a href="#hardware">Hardware</a> · <a href="#herramientas">Herramientas</a> ·
<a href="#ayuda">Ayuda</a> · <a href="#apoya-strata">Apoyar</a>
</p>
<p align="center">
<a href="https://github.com/Niko1221/Strata/releases/latest"><img src="https://img.shields.io/github/v/release/Niko1221/Strata?label=download&color=0ab887" alt="Descargar Strata"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Niko1221/Strata" alt="Licencia MIT"></a>
<a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Apoya Strata en Buy Me a Coffee"></a>
</p>
<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <b>Español</b> · <a href="README.pt-BR.md">Português</a></sub></p>
**Gratis, de código abierto y tuyo para ejecutar.** Usa Strata en tu escritorio o con tus herramientas de programación favoritas. No necesitas cuenta.
## Modelos
Recomendamos **primero ISTA-DASLab**, después **Unsloth** y otros proveedores, siempre que haya un modelo compatible que quepa en tu memoria.
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.8-Flash-Next</b></summary>
| Proveedor | Opciones |
| --- | --- |
| **ISTA-DASLab · recomendado** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) para programar. |
| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 |
| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Usa menos memoria, pero es más lento. |
| **Otras opciones** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) |
[Compara tamaños, necesidades de memoria y compatibilidad](docs/MODELS.md).
</details>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.6-35B-A3B</b></summary>
**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Son los paquetes documentados actualmente para este modelo.
[Guía del modelo y compatibilidad](docs/QWEN36.md).
</details>
<details>
<summary><img src="docs/media/models/deepseek.svg" width="22" alt="" align="middle"> &nbsp;<b>DeepSeekV4.1-Flash-1017</b></summary>
En la **aplicación de escritorio** y en el **Terminal**. Lo que no cabe en la memoria se lee desde tu SSD, así que hace falta mucho espacio libre en disco.
| Conjunto (IST-DAS) | Descarga | Espacio libre necesario |
| --- | ---: | ---: |
| 1.75 bpw | 239 GB | unos 245 GB |
| 2.00 bpw | 257 GB | unos 265 GB |
| 2.25 bpw | 274 GB | unos 280 GB |
Funciona en NVIDIA RTX 30, 40 y 50 (Windows y Linux) y en AMD Radeon AI PRO R9700 (Linux). La instalación descarga los archivos y el motor de DeepSeek, y después inicia el modelo.
```sh
strata launch --family deepseek41 --model ist-das-2.00bpw --plan
```
Medido con el conjunto de 2.00 bpw en Strata 0.2.5. «Salida» es la velocidad de la respuesta; «Prompt» es la rapidez con la que Strata lee tu texto.
| Hardware | Salida | Prompt |
| --- | ---: | ---: |
| RTX 5070 12 GB, 64 GB de RAM | 4 a 6 tokens/s | unos 110 tokens/s (4K) |
| RTX 3060 12 GB, 46 GB de RAM | 9 a 11 tokens/s | unos 155 tokens/s (4K) |
| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 a 25 tokens/s | 320 a 360 tokens/s (8K) |
| 4x Radeon AI PRO R9700 | 74 a 77 tokens/s | 400 a 450 tokens/s (8K) |
[Memoria, disco y detalles](docs/DEEPSEEK41.md) · [Notas de la versión](https://github.com/Niko1221/Strata/releases)
</details>
<a id="the-other-sizes"></a>
¿No sabes qué cabe? [Elige un modelo para tu ordenador](docs/MODELS.md#pick-by-memory).
## Instalación
<a id="option-a-the-strata-app"></a>
### Aplicación de escritorio
**[Descargar Strata para Windows, Linux o Mac →](https://github.com/Niko1221/Strata/releases/latest)**
Instala la aplicación, elige un modelo y empieza a chatear. Hay un instalador por sistema. En el primer arranque, la aplicación descarga el motor para tu tarjeta gráfica. [Ayuda con el instalador](docs/INSTALL.md#the-app).
<sub>Archivos: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg`</sub>
<p align="center">
<img src="docs/media/app-chat.png" width="900" alt="Aplicación de escritorio de Strata con un chat y una vista previa del código en vivo, una junto a otra">
<br><sub>Chat, archivos y vista previa en vivo en una sola ventana.</sub>
</p>
<a id="option-b-the-terminal-one-line"></a>
### Aplicación de Terminal
¿Prefieres la terminal? Instala Strata y ejecuta **`strata launch`**.
<details open>
<summary><b>Comandos de instalación</b></summary>
**Linux / Mac**
```sh
curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh
```
**Windows PowerShell**
```powershell
irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
```
En Windows, abre una terminal nueva después. Luego:
```sh
strata launch
```
Sigue las indicaciones para descargar e iniciar un modelo. [Guía del Terminal](docs/TERMINAL_LAUNCH.md).
</details>
<p align="center">
<img src="docs/media/terminal-monitor.png" width="900" alt="Aplicación de Terminal de Strata con la actividad del modelo, la velocidad, la memoria y las peticiones recientes">
<br><sub>Observa tu modelo y tu hardware mientras se ejecuta.</sub>
</p>
<a id="build-from-source"></a>
[Compilar desde el código fuente](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guía de instalación completa](docs/INSTALL.md)
<a id="what-you-need"></a>
## Hardware
| Hardware compatible | Guía |
| --- | --- |
| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Instalación en NVIDIA](docs/INSTALL.md#what-you-need) |
| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Instalación en AMD](docs/AMD_HIP.md) |
| **AMD Radeon RX 6800 / 6900 · experimental** | [Instalación en RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) |
| **Intel Arc · Linux** | [Instalación en Intel](docs/INTEL_ARC.md) |
| **Apple Silicon · M1 o posterior** | [Instalación en Mac](docs/MAC.md) |
| **AMD Ryzen AI Max · Strix Halo** | [Instalación en Strix Halo](docs/STRIX_HALO.md) |
<a id="using-it"></a>
## Herramientas
**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, y más, mediante las API compatibles con OpenAI y Anthropic.
Ejecuta **`strata connect`** para ver las instrucciones de tu herramienta. [Guía de conexión](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect).
<a id="guides"></a>
<a id="how-fast-is-it"></a>
<a id="how-does-it-work"></a>
<a id="something-went-wrong"></a>
## Ayuda
[Todas las guías](docs) · [Solución de problemas](docs/TROUBLESHOOTING.md) · [Informar de un error](https://github.com/Niko1221/Strata/issues/new/choose) ·
[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Cómo funciona](docs/HOW_IT_WORKS.md) · [Contribuir](CONTRIBUTING.md)
## Apoya Strata
**Ayuda a mantener la IA local abierta a todos.** Un café ayuda a financiar el desarrollo y las pruebas en más hardware.
<a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee: apoya Strata" height="48"></a>
[Licencia MIT](LICENSE) · [Créditos y licencias de los modelos](docs/HOW_IT_WORKS.md#credits) · [Privacidad](docs/SAFETY.md)
<a id="option-c-let-your-ai-set-it-up"></a>
<sub>Para herramientas de IA y lectores automáticos: <a href="AGENTS.md">referencia técnica</a> · <a href="docs/AI_SETUP.md">instrucciones de instalación</a>.</sub>
**Patrocinios, alianzas de hardware o colaboraciones:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com).
+188
View File
@@ -0,0 +1,188 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="apps/host/public/brand/strata-lockup-dark.svg">
<img src="apps/host/public/brand/strata-lockup-light.svg" alt="Strata" width="340">
</picture>
</p>
<h3 align="center">Une IA puissante sur votre propre ordinateur.</h3>
<p align="center">Discutez, programmez et travaillez avec des images, en local.</p>
<p align="center">
<a href="#modèles">Modèles</a> · <a href="#installation"><b>Installation</b></a> ·
<a href="#matériel">Matériel</a> · <a href="#outils">Outils</a> ·
<a href="#aide">Aide</a> · <a href="#soutenir-strata">Soutenir</a>
</p>
<p align="center">
<a href="https://github.com/Niko1221/Strata/releases/latest"><img src="https://img.shields.io/github/v/release/Niko1221/Strata?label=download&color=0ab887" alt="Télécharger Strata"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Niko1221/Strata" alt="Licence MIT"></a>
<a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Soutenir Strata sur Buy Me a Coffee"></a>
</p>
<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <b>Français</b> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a></sub></p>
**Gratuit, open source, et à vous de l'exécuter.** Utilisez Strata sur votre bureau ou avec vos outils de programmation préférés. Aucun compte nécessaire.
## Modèles
Nous recommandons **d'abord ISTA-DASLab**, puis **Unsloth** et d'autres fournisseurs, lorsqu'un modèle compatible tient en mémoire.
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.8-Flash-Next</b></summary>
| Fournisseur | Choix |
| --- | --- |
| **ISTA-DASLab · recommandé** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder : IQ1\_M](docs/MODELS.md#coder) pour programmer. |
| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 |
| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Utilise moins de mémoire, mais plus lent. |
| **Autres options** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) |
[Comparer les tailles, la mémoire nécessaire et la compatibilité](docs/MODELS.md).
</details>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.6-35B-A3B</b></summary>
**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Ce sont les paquets actuellement documentés pour ce modèle.
[Guide du modèle et compatibilité](docs/QWEN36.md).
</details>
<details>
<summary><img src="docs/media/models/deepseek.svg" width="22" alt="" align="middle"> &nbsp;<b>DeepSeekV4.1-Flash-1017</b></summary>
Dans l'**application de bureau** et dans le **Terminal**. Ce qui ne tient pas en mémoire est lu depuis votre SSD : il faut donc beaucoup d'espace disque libre.
| Jeu (IST-DAS) | Téléchargement | Espace disque libre nécessaire |
| --- | ---: | ---: |
| 1.75 bpw | 239 GB | environ 245 GB |
| 2.00 bpw | 257 GB | environ 265 GB |
| 2.25 bpw | 274 GB | environ 280 GB |
Fonctionne sur les NVIDIA RTX 30, 40 et 50 (Windows et Linux) et sur l'AMD Radeon AI PRO R9700 (Linux). L'installation télécharge les fichiers et le moteur DeepSeek, puis démarre le modèle.
```sh
strata launch --family deepseek41 --model ist-das-2.00bpw --plan
```
Mesuré avec le jeu 2.00 bpw sur Strata 0.2.5. « Sortie » est la vitesse de la réponse, « Prompt » la vitesse à laquelle Strata lit votre texte.
| Matériel | Sortie | Prompt |
| --- | ---: | ---: |
| RTX 5070 12 GB, 64 GB de RAM | 4 à 6 tokens/s | environ 110 tokens/s (4K) |
| RTX 3060 12 GB, 46 GB de RAM | 9 à 11 tokens/s | environ 155 tokens/s (4K) |
| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 à 25 tokens/s | 320 à 360 tokens/s (8K) |
| 4x Radeon AI PRO R9700 | 74 à 77 tokens/s | 400 à 450 tokens/s (8K) |
[Mémoire, disque et détails](docs/DEEPSEEK41.md) · [Notes de version](https://github.com/Niko1221/Strata/releases)
</details>
<a id="the-other-sizes"></a>
Vous ne savez pas ce qui tient ? [Choisir un modèle pour votre ordinateur](docs/MODELS.md#pick-by-memory).
## Installation
<a id="option-a-the-strata-app"></a>
### Application de bureau
**[Télécharger Strata pour Windows, Linux ou Mac →](https://github.com/Niko1221/Strata/releases/latest)**
Installez l'application, choisissez un modèle et commencez à discuter. Il y a un seul installateur par système. Au premier lancement, l'application télécharge le moteur de votre carte graphique. [Aide pour l'installateur](docs/INSTALL.md#the-app).
<sub>Fichiers: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg`</sub>
<p align="center">
<img src="docs/media/app-chat.png" width="900" alt="Application de bureau Strata avec une discussion et un aperçu du code en direct côte à côte">
<br><sub>Discussion, fichiers et aperçu en direct dans une seule fenêtre.</sub>
</p>
<a id="option-b-the-terminal-one-line"></a>
### Application Terminal
Vous préférez le terminal ? Installez Strata, puis lancez **`strata launch`**.
<details open>
<summary><b>Commandes d'installation</b></summary>
**Linux / Mac**
```sh
curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh
```
**Windows PowerShell**
```powershell
irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
```
Sous Windows, ouvrez ensuite un nouveau terminal. Puis :
```sh
strata launch
```
Suivez les invites pour télécharger et démarrer un modèle. [Guide du Terminal](docs/TERMINAL_LAUNCH.md).
</details>
<p align="center">
<img src="docs/media/terminal-monitor.png" width="900" alt="Application Terminal de Strata affichant l'activité du modèle, la vitesse, la mémoire et les requêtes récentes">
<br><sub>Suivez votre modèle et votre matériel pendant qu'il tourne.</sub>
</p>
<a id="build-from-source"></a>
[Compiler depuis les sources](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guide d'installation complet](docs/INSTALL.md)
<a id="what-you-need"></a>
## Matériel
| Matériel pris en charge | Guide |
| --- | --- |
| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Installation NVIDIA](docs/INSTALL.md#what-you-need) |
| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Installation AMD](docs/AMD_HIP.md) |
| **AMD Radeon RX 6800 / 6900 · expérimental** | [Installation RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) |
| **Intel Arc · Linux** | [Installation Intel](docs/INTEL_ARC.md) |
| **Apple Silicon · M1 ou plus récent** | [Installation sur Mac](docs/MAC.md) |
| **AMD Ryzen AI Max · Strix Halo** | [Installation Strix Halo](docs/STRIX_HALO.md) |
<a id="using-it"></a>
## Outils
**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, et d'autres via les API compatibles OpenAI et Anthropic.
Lancez **`strata connect`** pour voir la configuration de votre outil. [Guide de connexion](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect).
<a id="guides"></a>
<a id="how-fast-is-it"></a>
<a id="how-does-it-work"></a>
<a id="something-went-wrong"></a>
## Aide
[Tous les guides](docs) · [Dépannage](docs/TROUBLESHOOTING.md) · [Signaler un bogue](https://github.com/Niko1221/Strata/issues/new/choose) ·
[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Comment ça marche](docs/HOW_IT_WORKS.md) · [Contribuer](CONTRIBUTING.md)
## Soutenir Strata
**Aidez à garder l'IA locale ouverte à tous.** Un café aide à financer le développement et les tests sur davantage de matériel.
<a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee : soutenir Strata" height="48"></a>
[Licence MIT](LICENSE) · [Crédits et licences des modèles](docs/HOW_IT_WORKS.md#credits) · [Confidentialité](docs/SAFETY.md)
<a id="option-c-let-your-ai-set-it-up"></a>
<sub>Pour les outils d'IA et les lecteurs automatiques : <a href="AGENTS.md">référence technique</a> · <a href="docs/AI_SETUP.md">instructions d'installation</a>.</sub>
**Parrainages, partenariats matériel ou collaborations :** [niko.veit@outlook.com](mailto:niko.veit@outlook.com).
+188
View File
@@ -0,0 +1,188 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="apps/host/public/brand/strata-lockup-dark.svg">
<img src="apps/host/public/brand/strata-lockup-light.svg" alt="Strata" width="340">
</picture>
</p>
<h3 align="center">あなた自身のパソコンで、高性能な AI を。</h3>
<p align="center">チャット、コーディング、画像の処理を、すべてローカルで。</p>
<p align="center">
<a href="#モデル">モデル</a> · <a href="#インストール"><b>インストール</b></a> ·
<a href="#ハードウェア">ハードウェア</a> · <a href="#ツール">ツール</a> ·
<a href="#ヘルプ">ヘルプ</a> · <a href="#strata-を支援する">支援</a>
</p>
<p align="center">
<a href="https://github.com/Niko1221/Strata/releases/latest"><img src="https://img.shields.io/github/v/release/Niko1221/Strata?label=download&color=0ab887" alt="Strata をダウンロード"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Niko1221/Strata" alt="MIT ライセンス"></a>
<a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Buy Me a Coffee で Strata を支援する"></a>
</p>
<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <b>日本語</b> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a></sub></p>
**無料でオープンソース。自分の環境で動かせます。** デスクトップで、またはお好みのコーディングツールと一緒に Strata を使えます。アカウントは不要です。
## モデル
まず **ISTA-DASLab** をおすすめします。次に **Unsloth** などの提供元です。メモリに収まる互換モデルがある場合に選べます。
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.8-Flash-Next</b></summary>
| 提供元 | 選択肢 |
| --- | --- |
| **ISTA-DASLab · おすすめ** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S。[Coder: IQ1\_M](docs/MODELS.md#coder)(コーディング向け)。 |
| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 |
| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF)。メモリ使用量は少ないですが、動作は遅くなります。 |
| **その他の選択肢** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) |
[サイズ、必要なメモリ、互換性を比べる](docs/MODELS.md)。
</details>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.6-35B-A3B</b></summary>
**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0。現在、このモデルで文書化されているパックです。
[モデルガイドと互換性](docs/QWEN36.md)。
</details>
<details>
<summary><img src="docs/media/models/deepseek.svg" width="22" alt="" align="middle"> &nbsp;<b>DeepSeekV4.1-Flash-1017</b></summary>
**デスクトップアプリ**と**ターミナル**で使えます。メモリに収まらない分は SSD から読み込むため、空きディスク容量がたくさん必要です。
| セット(IST-DAS) | ダウンロード | 必要な空き容量 |
| --- | ---: | ---: |
| 1.75 bpw | 239 GB | 約245 GB |
| 2.00 bpw | 257 GB | 約265 GB |
| 2.25 bpw | 274 GB | 約280 GB |
NVIDIA RTX 30・40・50 シリーズ(Windows と Linux)と、AMD Radeon AI PRO R9700(Linux)で動きます。セットアップがファイルと DeepSeek エンジンをダウンロードし、モデルを起動します。
```sh
strata launch --family deepseek41 --model ist-das-2.00bpw --plan
```
Strata 0.2.5 で 2.00 bpw のセットを使って測定しました。「出力」は回答の速さ、「プロンプト」は Strata が入力を読み込む速さです。
| ハードウェア | 出力 | プロンプト |
| --- | ---: | ---: |
| RTX 5070 12 GB, 64 GB RAM | 4〜6 トークン/秒 | 約 110 トークン/秒 (4K) |
| RTX 3060 12 GB, 46 GB RAM | 9〜11 トークン/秒 | 約 155 トークン/秒 (4K) |
| 1x Radeon AI PRO R9700, 251 GB RAM | 21〜25 トークン/秒 | 320〜360 トークン/秒 (8K) |
| 4x Radeon AI PRO R9700 | 74〜77 トークン/秒 | 400〜450 トークン/秒 (8K) |
[メモリ、ディスク、詳細](docs/DEEPSEEK41.md) · [リリースノート](https://github.com/Niko1221/Strata/releases)
</details>
<a id="the-other-sizes"></a>
どれが動くかわからない場合は、[お使いのパソコンに合うモデルを選ぶ](docs/MODELS.md#pick-by-memory)。
## インストール
<a id="option-a-the-strata-app"></a>
### デスクトップアプリ
**[Windows、Linux、Mac 用の Strata をダウンロード →](https://github.com/Niko1221/Strata/releases/latest)**
アプリをインストールし、モデルを選んで、チャットを始めましょう。インストーラーはシステムごとに1つです。初回起動時に、アプリがお使いのグラフィックスカード用のエンジンをダウンロードします。[インストーラーのヘルプ](docs/INSTALL.md#the-app)。
<sub>ファイル: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg`</sub>
<p align="center">
<img src="docs/media/app-chat.png" width="900" alt="チャットとライブのコードプレビューを並べて表示した Strata デスクトップアプリ">
<br><sub>チャット、ファイル、ライブプレビューを1つのウィンドウで。</sub>
</p>
<a id="option-b-the-terminal-one-line"></a>
### ターミナルアプリ
ターミナルのほうが好みですか? Strata をインストールして、**`strata launch`** を実行します。
<details open>
<summary><b>インストールコマンド</b></summary>
**Linux / Mac**
```sh
curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh
```
**Windows PowerShell**
```powershell
irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
```
Windows では、インストール後に新しいターミナルを開きます。そのあと:
```sh
strata launch
```
画面の案内に従って、モデルをダウンロードして起動します。[ターミナルガイド](docs/TERMINAL_LAUNCH.md)。
</details>
<p align="center">
<img src="docs/media/terminal-monitor.png" width="900" alt="モデルの動作、速度、メモリ、最近のリクエストを表示する Strata ターミナルアプリ">
<br><sub>動作中のモデルとハードウェアの状態を確認できます。</sub>
</p>
<a id="build-from-source"></a>
[ソースからビルド](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [インストールガイド(全文)](docs/INSTALL.md)
<a id="what-you-need"></a>
## ハードウェア
| 対応ハードウェア | ガイド |
| --- | --- |
| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 シリーズ** | [NVIDIA のセットアップ](docs/INSTALL.md#what-you-need) |
| **AMD Radeon RX 7700 / 7800 / 7900、RX 9060 / 9070、AI PRO R9700** | [AMD のセットアップ](docs/AMD_HIP.md) |
| **AMD Radeon RX 6800 / 6900 · 試験的** | [RX 6000 のセットアップ](docs/AMD_HIP.md#rdna2-gfx1030) |
| **Intel Arc · Linux** | [Intel のセットアップ](docs/INTEL_ARC.md) |
| **Apple Silicon · M1 以降** | [Mac のセットアップ](docs/MAC.md) |
| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo のセットアップ](docs/STRIX_HALO.md) |
<a id="using-it"></a>
## ツール
**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**。OpenAI 互換と Anthropic 互換の API を通じて、ほかのツールも使えます。
**`strata connect`** を実行すると、お使いのツールの設定方法が表示されます。[接続ガイド](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect)。
<a id="guides"></a>
<a id="how-fast-is-it"></a>
<a id="how-does-it-work"></a>
<a id="something-went-wrong"></a>
## ヘルプ
[すべてのガイド](docs) · [トラブルシューティング](docs/TROUBLESHOOTING.md) · [不具合を報告](https://github.com/Niko1221/Strata/issues/new/choose) ·
[ベンチマーク](docs/COMMUNITY_BENCHMARKS.md) · [仕組み](docs/HOW_IT_WORKS.md) · [貢献する](CONTRIBUTING.md)
## Strata を支援する
**ローカル AI をみんなに開かれたものに。** コーヒー1杯が、開発と、より多くのハードウェアでのテストの支えになります。
<a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee: Strata を支援する" height="48"></a>
[MIT ライセンス](LICENSE) · [クレジットとモデルのライセンス](docs/HOW_IT_WORKS.md#credits) · [プライバシー](docs/SAFETY.md)
<a id="option-c-let-your-ai-set-it-up"></a>
<sub>AI ツールと自動リーダー向け: <a href="AGENTS.md">技術リファレンス</a> · <a href="docs/AI_SETUP.md">セットアップ手順</a></sub>
**スポンサー、ハードウェア提携、共同開発のご相談:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com).
+151 -144
View File
@@ -1,184 +1,191 @@
<h1 align="center">Strata</h1>
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="apps/host/public/brand/strata-lockup-dark.svg">
<img src="apps/host/public/brand/strata-lockup-light.svg" alt="Strata" width="340">
</picture>
</p>
<p align="center"><b>Run a 125-billion-parameter AI model on your own gaming PC</b><br>
NVIDIA or AMD graphics card (12 GB or more) · Windows or Linux · free and open source</p>
<h3 align="center">Run powerful AI on your own computer.</h3>
<p align="center">Chat, code and work with images, locally.</p>
<p align="center"><a href="https://github.com/Niko1221/Strata/releases/download/v0.1.10/Pagoda.mp4"><img src="docs/media/pagoda-preview.webp" width="720" alt="A voxel pagoda garden that Strata's model wrote, running in the browser"></a><br>
<sub>A voxel pagoda garden, 1 shot prompt running on an RTX 5070 with Strata (IQ3_S, 128K context) ·
<a href="https://github.com/Niko1221/Strata/releases/download/v0.1.10/Pagoda.mp4">full video (49 s)</a></sub></p>
<p align="center">
<a href="#models">Models</a> · <a href="#install"><b>Install</b></a> ·
<a href="#hardware">Hardware</a> · <a href="#tools">Tools</a> ·
<a href="#help">Help</a> · <a href="#support-strata">Support</a>
</p>
Strata runs **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** - a large, smart AI model that
normally needs a server - on a normal PC. It chats, writes code, reads pictures and works with your apps and coding
agents, and nothing leaves your PC.
<p align="center">
<a href="https://github.com/Niko1221/Strata/releases/latest"><img src="https://img.shields.io/github/v/release/Niko1221/Strata?label=download&color=0ab887" alt="Download Strata"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Niko1221/Strata" alt="MIT license"></a>
<a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Support Strata on Buy Me a Coffee"></a>
</p>
## How fast is it?
<p align="center"><sub><b>English</b> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a></sub></p>
Measured on two ordinary gaming PCs. "Writes answers" is how fast the reply appears in a short chat; "reads your
prompt" is how fast it takes in what you send (a 32K-token document, code or chat history). A token is about ¾ of a
word, so 60 tokens per second is faster than you can read.
**Free, open source, and yours to run.** Use Strata on your desktop or with your favorite coding tools. No account needed.
<table>
<tr><th>NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAM</th><th>AMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM</th></tr>
<tr><td>
## Models
| Size | Writes answers | Reads your prompt |
| --- | ---: | ---: |
| **Q2_0** | 93 tokens/s | 2,170 tokens/s |
| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s |
| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s |
| **IQ3_S** | 53 tokens/s | 1,620 tokens/s |
| **Coder** | 55 tokens/s | 2,180 tokens/s |
We recommend **ISTA-DASLab first**, then **Unsloth** and other providers, where a compatible model fits.
</td><td>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.8-Flash-Next</b></summary>
| Size | Writes answers | Reads your prompt |
| --- | ---: | ---: |
| **Q2_0** | 60 tokens/s | 1,160 tokens/s |
| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s |
| **Coder** | 44 tokens/s | 1,420 tokens/s |
</td></tr>
</table>
A card with more VRAM is faster: an RTX 3090 (24 GB) should write roughly 100-140 tokens per second. Long chats,
other cards: [speed of each model](docs/MODELS.md#how-fast-is-each-size), [community results](docs/COMMUNITY_BENCHMARKS.md).
<p align="center"><a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" height="50"></a><br>
<sub>Strata is free. If it runs well on your PC, a coffee keeps the work on it going.</sub></p>
## What you need
| | |
| Provider | Choices |
| --- | --- |
| **Graphics card** | **NVIDIA** GeForce RTX 20, 30, 40 or 50 series, or **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 or RX 6800 / 6900 series - with **12 GB of VRAM or more** |
| **RAM** | 32 GB or more - how much decides [which model](#which-model-should-i-pick) fits; 64 GB runs every size |
| **Disk** | about 80 GB free, on an SSD if you can (the first start is much faster) |
| **System** | Windows 10 / 11 or Linux, and a current graphics driver from NVIDIA or AMD |
| **ISTA-DASLab · recommended** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) for coding. |
| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 |
| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Lower memory use but slower. |
| **Other options** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) |
Everything else is installed for you. Two or three cards can share the model ([multi-GPU](docs/MULTI_GPU.md)).
The full list: [docs/INSTALL.md](docs/INSTALL.md#what-you-need).
[Compare sizes, memory needs and compatibility](docs/MODELS.md).
</details>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.6-35B-A3B</b></summary>
**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. These are the currently documented packs for this model.
[Model guide and compatibility](docs/QWEN36.md).
</details>
<details>
<summary><img src="docs/media/models/deepseek.svg" width="22" alt="" align="middle"> &nbsp;<b>DeepSeekV4.1-Flash-1017</b></summary>
In the **desktop app** and the **Terminal**. What does not fit in memory is read from your SSD, so it needs a lot of free
disk space.
| Set (IST-DAS) | Download | Free disk needed |
| --- | ---: | ---: |
| 1.75 bpw | 239 GB | about 245 GB |
| 2.00 bpw | 257 GB | about 265 GB |
| 2.25 bpw | 274 GB | about 280 GB |
Runs on NVIDIA RTX 30, 40 and 50 series (Windows and Linux) and AMD Radeon AI PRO R9700 (Linux). Setup downloads the
files and the DeepSeek engine, then starts the model.
```sh
strata launch --family deepseek41 --model ist-das-2.00bpw --plan
```
Measured with the 2.00 bpw set on Strata 0.2.5. Output is the speed of the answer, prompt is how fast Strata reads your input.
| Hardware | Output | Prompt |
| --- | ---: | ---: |
| RTX 5070 12 GB, 64 GB RAM | 4 to 6 tokens/s | about 110 tokens/s (4K) |
| RTX 3060 12 GB, 46 GB RAM | 9 to 11 tokens/s | about 155 tokens/s (4K) |
| 1x Radeon AI PRO R9700, 251 GB RAM | 21 to 25 tokens/s | 320 to 360 tokens/s (8K) |
| 4x Radeon AI PRO R9700 | 74 to 77 tokens/s | 400 to 450 tokens/s (8K) |
[Memory, disk and details](docs/DEEPSEEK41.md) · [Release notes](https://github.com/Niko1221/Strata/releases)
</details>
<a id="the-other-sizes"></a>
Not sure what fits? [Choose a model for your computer](docs/MODELS.md#pick-by-memory).
## Install
### Let your AI set it up
<a id="option-a-the-strata-app"></a>
Use an AI coding assistant (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Paste this into it:
### Desktop app
```text
Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository.
**[Download Strata for Windows, Linux or Mac →](https://github.com/Niko1221/Strata/releases/latest)**
Install the app, choose a model, and start chatting. There is one installer for each system. On first start the app
downloads the engine for your graphics card. [Help with the installer](docs/INSTALL.md#the-app).
<sub>Files: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg`</sub>
<p align="center">
<img src="docs/media/app-chat.png" width="900" alt="Strata desktop app with a chat and live code preview side by side">
<br><sub>Chat, files and a live preview in one window.</sub>
</p>
<a id="option-b-the-terminal-one-line"></a>
### Terminal app
Prefer the terminal? Install Strata, then run **`strata launch`**.
<details open>
<summary><b>Install commands</b></summary>
**Linux / Mac**
```sh
curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh
```
It checks your graphics card, RAM and disk, picks the model that fits, installs it, starts it and tells you how to
connect your apps. AI tools can also install, start and stop Strata themselves through its
[MCP server](docs/MCP_SERVER.md).
**Windows PowerShell**
### Or do it yourself
```powershell
irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
```
[Download Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) and unzip it (or `git clone` it).
**Windows:** double-click **`START-HERE.bat`**. **Linux:** run **`./setup.sh`** in the Strata folder.
On Windows, open a new terminal afterwards. Then:
The same steps for NVIDIA and AMD: the installer finds your card and sets up the right engine for it. It asks which
model, which size, how much context (how much text it keeps in mind) and whether it should read pictures - press
Enter each time for the recommended answer. Then it downloads the model (~70 GB; you can stop and it continues where
it left off) and starts it. Your browser opens the Strata app at `http://127.0.0.1:8080`.
```sh
strata launch
```
> **While the model starts, your PC can be slow or stop responding for 1-3 minutes** (longest the first time): Strata
> loads 35-55 GB into your RAM and locks part of it for the graphics card. That's normal - wait, and don't close the
> window. The window tells you what it is doing.
Follow the prompts to download and start a model. [Terminal guide](docs/TERMINAL_LAUNCH.md).
**Next time**, run `START-HERE.bat` (or `./setup.sh`) again: it starts right away, nothing is downloaded twice. Close
its window to stop the model. Updating, Docker, several cards, where the files go and every option:
[docs/INSTALL.md](docs/INSTALL.md).
</details>
## Which model should I pick?
<p align="center">
<img src="docs/media/terminal-monitor.png" width="900" alt="Strata terminal app showing model activity, speed, memory and recent requests">
<br><sub>Watch your model and hardware while it runs.</sub>
</p>
The installer recommends one for your RAM. The same model comes in sizes that are compressed more or less: smaller
is faster, larger is a bit smarter.
<a id="build-from-source"></a>
| Your RAM | Take | Why |
| --- | --- | --- |
| **32 GB** | **Coder** | it fits 32 GB, and it is made for code (with a 24 GB card, Q2_0 and IQ2_XS run too) |
| **48 GB** | **IQ2_XS** (or Q2_0, the fastest) | the larger sizes do not fit |
| **64 GB** | **IQ2_XS** (recommended), or IQ3_XXS / IQ3_S | every size fits; IQ3_S is the best, and the slowest |
| **96 GB or more** | **IQ3_S**, or Unsloth's 4-bit (experimental) | room for the largest sizes with everything else open |
[Build from source](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Full install guide](docs/INSTALL.md)
- **[Coder](docs/MODELS.md#coder)** - a coding version with half of the experts removed: 91% of the full model's
SWE-bench Verified score (by its authors), fits 32 GB of RAM. Weaker outside code, including Chinese and other
CJK text (#438): for those, take Q2_0, IQ2_XS or IQ3_S, which keep every expert.
- **[Swift 1.5](docs/MODELS.md#swift-15)** - a fine-tune that thinks much shorter before it answers, so you get the
answer sooner, at about the same quality.
- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)** (experimental) - the closest to the full
model, but most of it is read from the SSD while it answers: 7-8.5 tokens/s on a 64 GB PC.
- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs)** - a manual setup, not in the
installer's menu.
<a id="what-you-need"></a>
Sizes, downloads and what fits where: [docs/MODELS.md](docs/MODELS.md). You can add another model later with
`SETUP.bat` (Linux: `./setup.sh --setup`).
## Hardware
## Using it
| Supported hardware | Guide |
| --- | --- |
| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 series** | [NVIDIA setup](docs/INSTALL.md#what-you-need) |
| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [AMD setup](docs/AMD_HIP.md) |
| **AMD Radeon RX 6800 / 6900 · experimental** | [RX 6000 setup](docs/AMD_HIP.md#rdna2-gfx1030) |
| **Intel Arc · Linux** | [Intel setup](docs/INTEL_ARC.md) |
| **Apple Silicon · M1 or newer** | [Mac setup](docs/MAC.md) |
| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo setup](docs/STRIX_HALO.md) |
<p align="center"><img src="docs/media/runpagoda.png" width="900" alt="The Strata app's Monitor tab next to a coding agent"><br>
<sub>The Strata app's <b>Monitor</b> (left) while a coding agent writes the pagoda garden from the video (right)</sub></p>
<a id="using-it"></a>
- **In the browser:** `http://127.0.0.1:8080` - **Chat**, a live **Monitor** of the model and your GPU/CPU/RAM, and
**About** with the settings and addresses.
- **Your apps and coding agents:** add an "OpenAI-compatible" provider with base URL **`http://127.0.0.1:8080/v1`**,
any API key and any model name. Apps that use Anthropic's API: `http://127.0.0.1:8080/v1/messages` (Claude Code:
`ANTHROPIC_BASE_URL=http://127.0.0.1:8080`).
- **Thinking:** choose **off, low, medium or high** in the chat menu or your app's "reasoning effort". Off is
fastest; high is best for hard questions.
- **Pictures:** say yes to "Images?" in setup, then click **Picture** in the chat, or attach them in your app
(AMD cards: on Linux through the processor, not on Windows yet).
- **From your phone or another PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key <secret>` - always with a key.
- **Good to know:** it answers one request at a time. The first message of a chat is read in full (about 1 minute
per 30,000 tokens); follow-ups start in seconds.
## Tools
More: [where your chats are stored](docs/INSTALL.md#where-things-are-stored), [the API](docs/DETAILS.md#using-it).
**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, and more through the OpenAI- and Anthropic-compatible APIs.
## Something went wrong?
Run **`strata connect`** to see setup instructions for your tool. [Connection guide](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect).
- **My PC froze the first time Strata started.** Normal while it loads the model: wait, don't close the window.
Still frozen after 10 minutes? Restart the PC, close other programs and try again, or pick a smaller size.
- **It stopped while downloading or installing.** Run `START-HERE.bat` (or `./setup.sh`) again: it continues where
it stopped.
- **It's very slow and the disk light keeps blinking, or "the engine stopped unexpectedly".** Not enough free RAM:
close other programs (browsers use a lot), or pick a smaller size (Q2_0 or IQ2_XS).
- **It says port 8080 is already in use.** Strata is already running - look for its window.
<a id="guides"></a>
<a id="how-fast-is-it"></a>
<a id="how-does-it-work"></a>
<a id="something-went-wrong"></a>
More problems and their fixes: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Still stuck? Open an
[issue](https://github.com/Niko1221/Strata/issues) and attach `strata-<model>.log` from the Strata folder.
## Help
## How does it work?
Models like this one normally run on servers with hundreds of gigabytes of graphics memory. Your graphics card has
12-24 GB. Strata makes it fit by **sharing the work across your whole PC** - like a kitchen, where the things you use
all the time stay on the counter and the rest waits in the pantry.
<p align="center"><img src="docs/media/how-it-works.svg" width="860" alt="The model's 24,576 experts: the busiest on the graphics card, all of them in RAM, a lookup table on the SSD"></p>
- **The model is a team of 24,576 small specialists ("experts"),** and each word needs only 10 of them.
- **Your graphics card** keeps the few thousand experts that are asked most often; **your RAM** holds all of them,
and **your processor** works on the rest at the same time. **Your SSD** holds a big lookup table.
<p align="center"><img src="docs/media/guess-and-check.svg" width="860" alt="A small helper guesses the next words; the big model checks them all at once and keeps the right ones"></p>
- **Guess, then check:** a small helper guesses the next few words and the big model checks them all at once, so
you get the same answer, 1.6-1.8x sooner.
- **Long texts are read in big pieces** (up to 8,192 tokens at a time): over 1,000 tokens per second.
The longer explanation: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Every part and its numbers: [the
details](docs/DETAILS.md#how-it-works) and the [paper](docs/paper/Strata-Paper.pdf).
## Credits and license
The model is [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team, compressed by
[ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) and Unsloth;
Strata is built with parts of [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). All credits:
[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata is open source under the [MIT License](LICENSE); a few
parts and every model carry their own licenses ([which ones](docs/HOW_IT_WORKS.md#license)).
[All guides](docs) · [Troubleshooting](docs/TROUBLESHOOTING.md) · [Report a bug](https://github.com/Niko1221/Strata/issues/new/choose) ·
[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [How it works](docs/HOW_IT_WORKS.md) · [Contribute](CONTRIBUTING.md)
## Support Strata
Strata is free and open source. If it is useful to you, you can support its development:
**Help keep local AI open to everyone.** A coffee helps fund development and testing on more hardware.
<p align="center"><a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" height="50"></a></p>
<a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee: support Strata" height="48"></a>
[MIT license](LICENSE) · [Credits and model licenses](docs/HOW_IT_WORKS.md#credits) · [Privacy](docs/SAFETY.md)
<a id="option-c-let-your-ai-set-it-up"></a>
<sub>For AI tools and automated readers: <a href="AGENTS.md">technical reference</a> · <a href="docs/AI_SETUP.md">setup instructions</a>.</sub>
**Sponsorships, hardware partnerships or collaborations:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com).
+188
View File
@@ -0,0 +1,188 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="apps/host/public/brand/strata-lockup-dark.svg">
<img src="apps/host/public/brand/strata-lockup-light.svg" alt="Strata" width="340">
</picture>
</p>
<h3 align="center">IA poderosa no seu próprio computador.</h3>
<p align="center">Converse, programe e trabalhe com imagens, localmente.</p>
<p align="center">
<a href="#modelos">Modelos</a> · <a href="#instalação"><b>Instalação</b></a> ·
<a href="#hardware">Hardware</a> · <a href="#ferramentas">Ferramentas</a> ·
<a href="#ajuda">Ajuda</a> · <a href="#apoie-o-strata">Apoiar</a>
</p>
<p align="center">
<a href="https://github.com/Niko1221/Strata/releases/latest"><img src="https://img.shields.io/github/v/release/Niko1221/Strata?label=download&color=0ab887" alt="Baixar o Strata"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Niko1221/Strata" alt="Licença MIT"></a>
<a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Apoie o Strata no Buy Me a Coffee"></a>
</p>
<p align="center"><sub><a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <b>Português</b></sub></p>
**Gratuito, de código aberto e seu para executar.** Use o Strata no desktop ou com suas ferramentas de programação favoritas. Não precisa de conta.
## Modelos
Recomendamos **primeiro a ISTA-DASLab**, depois a **Unsloth** e outros provedores, quando um modelo compatível cabe na memória.
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.8-Flash-Next</b></summary>
| Provedor | Opções |
| --- | --- |
| **ISTA-DASLab · recomendado** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) para programar. |
| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 |
| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Usa menos memória, mas é mais lento. |
| **Outras opções** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) |
[Compare tamanhos, necessidades de memória e compatibilidade](docs/MODELS.md).
</details>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.6-35B-A3B</b></summary>
**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Esses são os pacotes documentados atualmente para este modelo.
[Guia do modelo e compatibilidade](docs/QWEN36.md).
</details>
<details>
<summary><img src="docs/media/models/deepseek.svg" width="22" alt="" align="middle"> &nbsp;<b>DeepSeekV4.1-Flash-1017</b></summary>
No **aplicativo de desktop** e no **Terminal**. O que não cabe na memória é lido do seu SSD, por isso é preciso muito espaço livre em disco.
| Conjunto (IST-DAS) | Download | Espaço livre necessário |
| --- | ---: | ---: |
| 1.75 bpw | 239 GB | cerca de 245 GB |
| 2.00 bpw | 257 GB | cerca de 265 GB |
| 2.25 bpw | 274 GB | cerca de 280 GB |
Roda em NVIDIA RTX 30, 40 e 50 (Windows e Linux) e em AMD Radeon AI PRO R9700 (Linux). A instalação baixa os arquivos e o motor do DeepSeek e depois inicia o modelo.
```sh
strata launch --family deepseek41 --model ist-das-2.00bpw --plan
```
Medido com o conjunto de 2.00 bpw no Strata 0.2.5. “Saída” é a velocidade da resposta; “Prompt” é a rapidez com que o Strata lê o seu texto.
| Hardware | Saída | Prompt |
| --- | ---: | ---: |
| RTX 5070 12 GB, 64 GB de RAM | 4 a 6 tokens/s | cerca de 110 tokens/s (4K) |
| RTX 3060 12 GB, 46 GB de RAM | 9 a 11 tokens/s | cerca de 155 tokens/s (4K) |
| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 a 25 tokens/s | 320 a 360 tokens/s (8K) |
| 4x Radeon AI PRO R9700 | 74 a 77 tokens/s | 400 a 450 tokens/s (8K) |
[Memória, disco e detalhes](docs/DEEPSEEK41.md) · [Notas da versão](https://github.com/Niko1221/Strata/releases)
</details>
<a id="the-other-sizes"></a>
Não sabe o que cabe? [Escolha um modelo para o seu computador](docs/MODELS.md#pick-by-memory).
## Instalação
<a id="option-a-the-strata-app"></a>
### Aplicativo de desktop
**[Baixar o Strata para Windows, Linux ou Mac →](https://github.com/Niko1221/Strata/releases/latest)**
Instale o aplicativo, escolha um modelo e comece a conversar. Há um instalador por sistema. Na primeira vez que abre, o aplicativo baixa o motor da sua placa de vídeo. [Ajuda com o instalador](docs/INSTALL.md#the-app).
<sub>Arquivos: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg`</sub>
<p align="center">
<img src="docs/media/app-chat.png" width="900" alt="Aplicativo de desktop do Strata com um chat e uma prévia do código ao vivo lado a lado">
<br><sub>Chat, arquivos e prévia ao vivo em uma só janela.</sub>
</p>
<a id="option-b-the-terminal-one-line"></a>
### Aplicativo de Terminal
Prefere o terminal? Instale o Strata e execute **`strata launch`**.
<details open>
<summary><b>Comandos de instalação</b></summary>
**Linux / Mac**
```sh
curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh
```
**Windows PowerShell**
```powershell
irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
```
No Windows, abra um novo terminal depois. Em seguida:
```sh
strata launch
```
Siga as instruções para baixar e iniciar um modelo. [Guia do Terminal](docs/TERMINAL_LAUNCH.md).
</details>
<p align="center">
<img src="docs/media/terminal-monitor.png" width="900" alt="Aplicativo de Terminal do Strata mostrando a atividade do modelo, a velocidade, a memória e as solicitações recentes">
<br><sub>Acompanhe seu modelo e seu hardware enquanto ele roda.</sub>
</p>
<a id="build-from-source"></a>
[Compilar a partir do código-fonte](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guia de instalação completo](docs/INSTALL.md)
<a id="what-you-need"></a>
## Hardware
| Hardware compatível | Guia |
| --- | --- |
| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Instalação para NVIDIA](docs/INSTALL.md#what-you-need) |
| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Instalação para AMD](docs/AMD_HIP.md) |
| **AMD Radeon RX 6800 / 6900 · experimental** | [Instalação para RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) |
| **Intel Arc · Linux** | [Instalação para Intel](docs/INTEL_ARC.md) |
| **Apple Silicon · M1 ou mais novo** | [Instalação para Mac](docs/MAC.md) |
| **AMD Ryzen AI Max · Strix Halo** | [Instalação para Strix Halo](docs/STRIX_HALO.md) |
<a id="using-it"></a>
## Ferramentas
**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, e outras, pelas APIs compatíveis com OpenAI e Anthropic.
Execute **`strata connect`** para ver as instruções da sua ferramenta. [Guia de conexão](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect).
<a id="guides"></a>
<a id="how-fast-is-it"></a>
<a id="how-does-it-work"></a>
<a id="something-went-wrong"></a>
## Ajuda
[Todos os guias](docs) · [Solução de problemas](docs/TROUBLESHOOTING.md) · [Relatar um bug](https://github.com/Niko1221/Strata/issues/new/choose) ·
[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Como funciona](docs/HOW_IT_WORKS.md) · [Contribuir](CONTRIBUTING.md)
## Apoie o Strata
**Ajude a manter a IA local aberta para todos.** Um café ajuda a financiar o desenvolvimento e os testes em mais hardware.
<a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee: apoie o Strata" height="48"></a>
[Licença MIT](LICENSE) · [Créditos e licenças dos modelos](docs/HOW_IT_WORKS.md#credits) · [Privacidade](docs/SAFETY.md)
<a id="option-c-let-your-ai-set-it-up"></a>
<sub>Para ferramentas de IA e leitores automáticos: <a href="AGENTS.md">referência técnica</a> · <a href="docs/AI_SETUP.md">instruções de instalação</a>.</sub>
**Patrocínios, parcerias de hardware ou colaborações:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com).
+188
View File
@@ -0,0 +1,188 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="apps/host/public/brand/strata-lockup-dark.svg">
<img src="apps/host/public/brand/strata-lockup-light.svg" alt="Strata" width="340">
</picture>
</p>
<h3 align="center">在你自己的电脑上运行强大的 AI。</h3>
<p align="center">本地聊天、写代码、处理图片。</p>
<p align="center">
<a href="#模型">模型</a> · <a href="#安装"><b>安装</b></a> ·
<a href="#硬件">硬件</a> · <a href="#工具">工具</a> ·
<a href="#帮助">帮助</a> · <a href="#支持-strata">支持</a>
</p>
<p align="center">
<a href="https://github.com/Niko1221/Strata/releases/latest"><img src="https://img.shields.io/github/v/release/Niko1221/Strata?label=download&color=0ab887" alt="下载 Strata"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Niko1221/Strata" alt="MIT 许可证"></a>
<a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="在 Buy Me a Coffee 上支持 Strata"></a>
</p>
<p align="center"><sub><a href="README.md">English</a> · <b>简体中文</b> · <a href="README.ja.md">日本語</a> · <a href="README.de.md">Deutsch</a> · <a href="README.fr.md">Français</a> · <a href="README.es.md">Español</a> · <a href="README.pt-BR.md">Português</a></sub></p>
**免费、开源,由你自己运行。** 在桌面上使用 Strata,或搭配你喜欢的编程工具。无需账号。
## 模型
我们**首先推荐 ISTA-DASLab**,其次是 **Unsloth** 和其他提供方,前提是有内存放得下的兼容模型。
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.8-Flash-Next</b></summary>
| 提供方 | 可选项 |
| --- | --- |
| **ISTA-DASLab · 推荐** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S。[Coder:IQ1\_M](docs/MODELS.md#coder),适合写代码。 |
| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 |
| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF)。占用内存更少,但速度更慢。 |
| **其他选项** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) |
[比较大小、内存需求和兼容性](docs/MODELS.md)。
</details>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.6-35B-A3B</b></summary>
**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0。这些是目前文档中收录的该模型的版本。
[模型指南和兼容性](docs/QWEN36.md)。
</details>
<details>
<summary><img src="docs/media/models/deepseek.svg" width="22" alt="" align="middle"> &nbsp;<b>DeepSeekV4.1-Flash-1017</b></summary>
可在**桌面应用**和**终端**中使用。内存放不下的部分会从 SSD 读取,所以需要大量空闲磁盘空间。
| 版本(IST-DAS) | 下载大小 | 所需空闲磁盘 |
| --- | ---: | ---: |
| 1.75 bpw | 239 GB | 约245 GB |
| 2.00 bpw | 257 GB | 约265 GB |
| 2.25 bpw | 274 GB | 约280 GB |
支持 NVIDIA RTX 30、40 和 50 系列(Windows 和 Linux),以及 AMD Radeon AI PRO R9700(Linux)。安装程序会下载模型文件和 DeepSeek 引擎,然后启动模型。
```sh
strata launch --family deepseek41 --model ist-das-2.00bpw --plan
```
以下为 Strata 0.2.5 上 2.00 bpw 版本的实测结果。“输出”是回答的速度,“提示词”是 Strata 读取你输入内容的速度。
| 硬件 | 输出 | 提示词 |
| --- | ---: | ---: |
| RTX 5070 12 GB, 64 GB 内存 | 4 到 6 tokens/s | 约 110 tokens/s(4K) |
| RTX 3060 12 GB, 46 GB 内存 | 9 到 11 tokens/s | 约 155 tokens/s(4K) |
| 1x Radeon AI PRO R9700, 251 GB 内存 | 21 到 25 tokens/s | 320 到 360 tokens/s (8K) |
| 4x Radeon AI PRO R9700 | 74 到 77 tokens/s | 400 到 450 tokens/s (8K) |
[内存、磁盘和详细信息](docs/DEEPSEEK41.md) · [发行说明](https://github.com/Niko1221/Strata/releases)
</details>
<a id="the-other-sizes"></a>
不确定哪个放得下?[为你的电脑选择模型](docs/MODELS.md#pick-by-memory)。
## 安装
<a id="option-a-the-strata-app"></a>
### 桌面应用
**[下载适用于 Windows、Linux 或 Mac 的 Strata →](https://github.com/Niko1221/Strata/releases/latest)**
安装应用,选择模型,就可以开始聊天。每个系统只有一个安装程序。首次启动时,应用会下载适合你显卡的引擎。[安装程序帮助](docs/INSTALL.md#the-app)。
<sub>文件: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg`</sub>
<p align="center">
<img src="docs/media/app-chat.png" width="900" alt="Strata 桌面应用,聊天和实时代码预览并排显示">
<br><sub>聊天、文件和实时预览都在一个窗口里。</sub>
</p>
<a id="option-b-the-terminal-one-line"></a>
### 终端应用
更喜欢终端?安装 Strata,然后运行 **`strata launch`**。
<details open>
<summary><b>安装命令</b></summary>
**Linux / Mac**
```sh
curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh
```
**Windows PowerShell**
```powershell
irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
```
在 Windows 上,安装后请打开一个新的终端。然后运行:
```sh
strata launch
```
按提示下载并启动模型。[终端指南](docs/TERMINAL_LAUNCH.md)。
</details>
<p align="center">
<img src="docs/media/terminal-monitor.png" width="900" alt="Strata 终端应用,显示模型活动、速度、内存和最近的请求">
<br><sub>模型运行时,随时查看模型和硬件状态。</sub>
</p>
<a id="build-from-source"></a>
[从源码构建](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [完整安装指南](docs/INSTALL.md)
<a id="what-you-need"></a>
## 硬件
| 支持的硬件 | 指南 |
| --- | --- |
| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 系列** | [NVIDIA 安装](docs/INSTALL.md#what-you-need) |
| **AMD Radeon RX 7700 / 7800 / 7900、RX 9060 / 9070、AI PRO R9700** | [AMD 安装](docs/AMD_HIP.md) |
| **AMD Radeon RX 6800 / 6900 · 实验性** | [RX 6000 安装](docs/AMD_HIP.md#rdna2-gfx1030) |
| **Intel Arc · Linux** | [Intel 安装](docs/INTEL_ARC.md) |
| **Apple Silicon · M1 或更新** | [Mac 安装](docs/MAC.md) |
| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo 安装](docs/STRIX_HALO.md) |
<a id="using-it"></a>
## 工具
**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**,也可以通过兼容 OpenAI 和 Anthropic 的 API 使用更多工具。
运行 **`strata connect`**,查看你所用工具的设置方法。[连接指南](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect)。
<a id="guides"></a>
<a id="how-fast-is-it"></a>
<a id="how-does-it-work"></a>
<a id="something-went-wrong"></a>
## 帮助
[全部指南](docs) · [故障排查](docs/TROUBLESHOOTING.md) · [报告问题](https://github.com/Niko1221/Strata/issues/new/choose) ·
[基准测试](docs/COMMUNITY_BENCHMARKS.md) · [工作原理](docs/HOW_IT_WORKS.md) · [参与贡献](CONTRIBUTING.md)
## 支持 Strata
**帮助本地 AI 保持开放。** 一杯咖啡能帮助我们在更多硬件上开发和测试。
<a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee:支持 Strata" height="48"></a>
[MIT 许可证](LICENSE) · [致谢和模型许可证](docs/HOW_IT_WORKS.md#credits) · [隐私](docs/SAFETY.md)
<a id="option-c-let-your-ai-set-it-up"></a>
<sub>面向 AI 工具和自动阅读器: <a href="AGENTS.md">技术参考</a> · <a href="docs/AI_SETUP.md">安装说明</a></sub>
**赞助、硬件合作或其他合作:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com).
+95
View File
@@ -0,0 +1,95 @@
# Security
## Reporting a vulnerability
Please report anything that should not be public until it is fixed **privately**, through GitHub's private
vulnerability reporting: the repository's **Security** tab, **Report a vulnerability**
([direct link](https://github.com/Niko1221/Strata/security/advisories/new)). Say what you found, how to reproduce it
(the request, the config keys involved, the Strata version), and what an attacker gains. We answer there, fix it in
a release, and credit you in the advisory unless you ask us not to.
Ordinary hardening ideas and findings that are safe to discuss in public are welcome as an
[issue](https://github.com/Niko1221/Strata/issues) (#544 collects audit findings) or as a pull request, which we
review like our own code.
Supported: the latest release. Fixes go into the next release, not into older ones.
## What the server exposes
Strata runs a model on your PC and serves it over HTTP (`serve/server.py`). Out of the box it is reachable from
this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAILS.md) ("From other devices",
"Host names", "Web pages without an API key", "Tools from MCP servers").
- **Where it listens.** `127.0.0.1` by default. `--host 0.0.0.0` (or `"host"` in `strata-<model>.json`) opens it to
your network, and the server then warns when no API key is set.
- **API key.** `"api_key"` in the run config (or `STRATA_API_KEY`) is required on `/v1/*` and on every endpoint
that shows the model's state, requests or answers (`/status`, `/metrics`, `/settings`, `/mcp`, `/props`, `/slots`,
`/api/requests`, `/config`) and on every `POST`. It is compared in constant time. Set one before you open the
server to your network or put a tunnel in front of it.
- **Host check (DNS rebinding, 0.1.38).** Without an API key the server answers only requests whose `Host` is a name
it knows (`localhost`, an IP address, the address it listens on and, when it listens beyond this PC, this PC's
name). Others get 403. `"allowed_hosts"` adds names; with an API key the key decides.
- **Origin check (0.1.38).** Without an API key, a browser `POST` to `/v1/*` from another web site's page (it carries
an `Origin` header) gets 403 unless that origin is Strata's own page, `localhost`, an allowed host, or listed in
`"trusted_origins"` / `"cors_origins"`. Changing settings (`/settings`, and `/config`: the few run config keys the
page's Model settings may change - never the network, key, MCP or program keys), `/load` and `/unload` and the
MCP tools are accepted only as JSON from Strata's own page (or `"trusted_origins"`), so a page elsewhere cannot
change settings or run tools.
- **CORS** is off unless `"cors_origins"` lists origins, and then only for `/v1/*`.
- **MCP tools** are opt-in: only the servers you put in the run config, only for requests from Strata's own page
that ask for them. They run with your user's rights, and the model decides when to call them.
- **The request monitor** (`/api-monitor`, which keeps the last prompts and answers in memory) is off unless
`"api_monitor": true` is set. Apart from it, the server keeps in its process memory the text and tokens of its
last few prompts, whatever `"api_monitor"` says, to encode the next turn faster; no endpoint shows them, and they
are gone when the server stops.
## The desktop app and the Terminal
Strata comes in three parts that share one engine: the **desktop app**, the **Terminal** (`strata`) and the **engine** that runs
the model. The section above is about the engine's HTTP server. This is what the other two add.
- **The app's host listens on this PC only.** The app serves its page from a local host process on `127.0.0.1` (port 8791 unless
changed). A request to its `/api/` endpoints that carries a browser `Origin` from any other site gets 403. The app shell holds a
random secret (32 characters or more, compared in constant time) that is needed to quit the host or tell it which window is open,
and the host gives its own helper processes a second random secret. By default the models the app starts are served on this PC only.
- **Sharing is a separate, key-protected listener.** "Share with other devices" (and the Cloudflare tunnel) will not start until an
API key is set. It opens a different listener that answers only `/v1/models`, `/v1/chat/completions` and `/v1/messages`, never the
app's page or its host endpoints.
- **App and Terminal talk through an owner channel.** One owner process per installation starts and ends the engine, and a second
client (the Terminal) attaches to it. On macOS and Linux that is a private Unix socket in a folder only you can open. On Windows it
is a TCP listener on `127.0.0.1` that answers only requests carrying a 256-bit token kept in an owner-only folder. That is a weaker
guarantee than a socket other users cannot open: on Windows the token is what protects it, as with any loopback service that has a
token (`strata_control/owner_transport.py`). The bridge between the app shell and the host (used for the app update) is also loopback and protected by a token.
- **Starting a model and serving never download anything.** Downloads and updates are one explicit step: `strata update`, or "Update
engine" and "Update Strata" in the app's Settings. Models and saved tuning are never replaced by an update.
- **Updates come from a signed feed.** The release publishes `strata-feed.json` and `strata-feed.json.sig` (Ed25519). An installed
Strata checks the signature against the public key it carries (`strata_control/update_keys.json`), refuses a feed older than the last
one it accepted (a replayed old feed) or expired, and checks every engine package against its SHA-256, its signed manifest and the
card in your PC before it test-starts it and switches to it. Any failure keeps the engine you had. The app installer itself is signed
with a separate key (Tauri's minisign key) that the app and the Terminal both check. The private keys are kept offline by the owner.
See [packaging/UPDATES.md](packaging/UPDATES.md).
### How far to trust `curl | sh` and `irm | iex`
The Terminal installs with one line:
```sh
curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh
irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
```
Piping a script into a shell runs whatever the server sends, so it deserves the same care as running any downloaded program.
What the script does is short and written at its top: it fetches the Terminal archive named in the release's `install-manifest.txt`,
checks its SHA-256, unpacks it into your home folder (no administrator rights, nothing outside your home), checks the release's signed feed
with the Terminal it just unpacked and removes it again if that fails, and puts `strata` on your PATH.
Those checks have a limit. The checksum comes from the same release as the archive, and the public key that checks the feed arrives inside
that archive, so for the first install all trust rests on HTTPS and on the `Niko1221/Strata` GitHub release itself. The checks catch a
damaged or half-finished download and a feed that was not signed by the release key; they do not protect you if the release has been replaced
by someone who controls it. Later updates are checked against the key already on your PC, which is a stronger position.
If that is not enough: save the script (`curl -fsSLO https://github.com/Niko1221/Strata/releases/latest/download/install.sh`), read it, and
run it from the file; or install the desktop app or build from source instead and check the code you build.
Strata has not had an outside security audit yet.
What Strata downloads, when it uses the internet, what stays on your PC and how downloads are checked is written up in [docs/SAFETY.md](docs/SAFETY.md).
+13
View File
@@ -2,8 +2,13 @@
rem Strata for Windows: the first run installs everything and starts the model; later runs just start it.
rem Needs only an NVIDIA or AMD graphics driver. Python is installed for your user account if it is missing (no admin needed).
setlocal
rem Python reads and writes text as UTF-8, not in the Windows code page (cp1251, cp866, ...): a folder or user name with Cyrillic or other letters stays intact (#3202).
set "PYTHONUTF8=1"
title Strata
cd /d "%~dp0"
rem A bundled Python runtime (the python\ folder of the terminal archive) is used when it is there: nothing to find,
rem install or download. SETUP.bat and UPDATE.bat run this file, so they use it too.
if exist "python\python.exe" goto bundled
if exist ".venv\Scripts\python.exe" goto run
call :findpy
@@ -36,6 +41,14 @@ echo Could not create the Python environment in .venv
pause
exit /b 1
:bundled
set "PYTHONNOUSERSITE=1"
set "PYTHONHOME="
set "PYTHONPATH="
"python\python.exe" setup.py %*
if errorlevel 1 pause
exit /b
:run
".venv\Scripts\python.exe" setup.py %*
if errorlevel 1 pause
+82
View File
@@ -0,0 +1,82 @@
@echo off
rem Update Strata without starting the model (#475): the newest code (git pull, when this folder is a git clone), then
rem what START-HERE.bat does before a start - the engine (a new one when this version needs it), the Python packages,
rem each installed model's settings and draft subset. The model files are not touched. Start the model later with
rem START-HERE.bat. Options are passed on to setup.py. The bundled Python (python\ beside this file) is used when
rem there is one: START-HERE.bat, which this file runs, picks it.
setlocal
title Strata - update
cd /d "%~dp0"
rem All of it in one block: cmd reads a .bat file while it runs it, and the git pull can change this very file.
(
if exist ".git" (
where git >nul 2>nul || (
echo This folder is a git clone, but git is not on PATH: install Git for Windows ^(winget install Git.Git^)
echo or run "git pull" here yourself, then run UPDATE.bat again.
pause
exit /b 1
)
echo Getting the newest Strata ^(git pull^) ...
git pull --ff-only
if errorlevel 1 (
rem The history was rewritten on 2026-10-06, see #1276: a clone from before has no commit in common with origin/main.
set "REWR="
git merge-base HEAD origin/main >nul 2>nul
if errorlevel 1 set "REWR=1"
git rev-parse --is-shallow-repository 2>nul | findstr /x true >nul && set "REWR="
if defined REWR (
echo.
echo This clone is on the repository's old history ^(cleaned up on 2026-10-06^): it has no commit in common
echo with origin/main, so it cannot be updated by git pull.
set "DIRTY="
for /f "delims=" %%i in ('git status --porcelain --untracked-files^=no') do set "DIRTY=1"
if defined DIRTY (
echo You have local changes to tracked files here, so nothing was touched. To move to the new history
echo yourself ^(your untracked files, models and settings stay where they are^):
echo git branch pre-cleanup-backup
echo git stash push
echo git checkout -B main origin/main
echo then run UPDATE.bat again.
pause
exit /b 1
)
set "BK=pre-cleanup-backup"
git rev-parse --verify -q refs/heads/pre-cleanup-backup >nul 2>nul && set "BK=pre-cleanup-backup-%RANDOM%"
set "BR=main"
for /f "delims=" %%i in ('git symbolic-ref --short -q HEAD 2^>nul') do set "BR=%%i"
call git branch %%BK%% HEAD
if errorlevel 1 (
echo Could not make the backup branch: nothing was updated.
pause
exit /b 1
)
call git checkout -q -B %%BR%% origin/main
if errorlevel 1 (
call git branch -D %%BK%% >nul 2>nul
echo.
echo Could not move to the new history ^(the reason is above^): nothing was updated. By hand:
echo git checkout -B main origin/main
pause
exit /b 1
)
call echo Moved to the new history. Your old commits are kept in the branch %%BK%%.
echo Untracked files ^(models, settings, the engine^) were not touched.
) else (
echo.
echo git pull did not succeed ^(the reason is above^): nothing was updated. Files you changed here can stop it:
echo "git status" lists them.
pause
exit /b 1
)
)
) else (
echo This copy of Strata was not made with git, so it cannot fetch new files itself. Download the newest one:
echo https://github.com/Niko1221/Strata/archive/refs/heads/main.zip
echo unzip it anywhere and run START-HERE.bat ^(or UPDATE.bat^) in it: it finds the model files in Strata-data
echo and sets itself up the same way - nothing big is downloaded again.
echo Checking this copy's engine and settings meanwhile ...
)
call "%~dp0START-HERE.bat" --update %*
if not errorlevel 1 pause
exit /b
)
+232
View File
@@ -0,0 +1,232 @@
{
"name": "strata-desktop",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "strata-desktop",
"version": "0.1.0",
"devDependencies": {
"@tauri-apps/cli": "2.12.3"
}
},
"node_modules/@tauri-apps/cli": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.3.tgz",
"integrity": "sha512-f7/LsY74SVb1ChmOPw1ajOpxii0GSzDAgmWHRci8JUYuuai04rXsSbFobpmB0sP2DdlvMD/B5ZotEn8GOGMRUg==",
"dev": true,
"license": "Apache-2.0 OR MIT",
"bin": {
"tauri": "tauri.js"
},
"engines": {
"node": ">= 10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/tauri"
},
"optionalDependencies": {
"@tauri-apps/cli-darwin-arm64": "2.12.3",
"@tauri-apps/cli-darwin-x64": "2.12.3",
"@tauri-apps/cli-linux-arm-gnueabihf": "2.12.3",
"@tauri-apps/cli-linux-arm64-gnu": "2.12.3",
"@tauri-apps/cli-linux-arm64-musl": "2.12.3",
"@tauri-apps/cli-linux-riscv64-gnu": "2.12.3",
"@tauri-apps/cli-linux-x64-gnu": "2.12.3",
"@tauri-apps/cli-linux-x64-musl": "2.12.3",
"@tauri-apps/cli-win32-arm64-msvc": "2.12.3",
"@tauri-apps/cli-win32-ia32-msvc": "2.12.3",
"@tauri-apps/cli-win32-x64-msvc": "2.12.3"
}
},
"node_modules/@tauri-apps/cli-darwin-arm64": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.3.tgz",
"integrity": "sha512-xmVNoJOOKzKLj7GLHXmXLimRby9M42aBIJa0sB80N7o24eKV5JiVmToKTRLVH9yhL05GZ/B6rSSOmbzNFJwBAA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-darwin-x64": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.3.tgz",
"integrity": "sha512-URd+0usfmUQQyb5kNPiKt2OT8gp7oGU7QR+qOppB6e35mpVBFFVNhWc9oWb3p0u71fDJ09DpF4T6m9xYxoIB8g==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.3.tgz",
"integrity": "sha512-0kwUVx2LbmOoTRlwF1oDww7th4/NSluv4ZBQ6KRZsFKg4g0TlTcIiJ0VehqkQYUeC9xIT1Mk6XtF52mI155VSQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm64-gnu": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.3.tgz",
"integrity": "sha512-gKSGDx6fx+HBLQmG6guChFdisbrCSdx9Yli+j5teOa64gm1CeM+C6NLru5Pj3ZkkEep05BmCFjxvX+cjqAycZQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm64-musl": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.3.tgz",
"integrity": "sha512-Yr59qMy/gcvAfBuFdCGlAmGiLsYWMFDbsP4bAI6iNBzcJTGrYWZGeiQhGDo29MQwfF/NUBqyM2qljXu5tZ6wjQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-riscv64-gnu": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.3.tgz",
"integrity": "sha512-jKr0/REBMnLKC0OwPQZkyge0mKDaNZ0b/AbfGwVyCgFfwS730EVLfVDo3nt7MUu6jJaytRq08+xSj5qfy+U1+Q==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-x64-gnu": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.3.tgz",
"integrity": "sha512-gTkEqJAGCMROGanxHnzaJzQ+/rXl39HWVg0/hDODS1wDWBGqoceqGC6Qm1+mQbyT11xnsB8mKu/gyVID/YpFIw==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-x64-musl": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.3.tgz",
"integrity": "sha512-T2dTxL1svRym71fZtaW4pZYXbthbfFsEJr1NeOUg/p7laWXZbUt/8DMSZf8recu9f7+1F/Lv00HtzsEu6vDO9w==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-arm64-msvc": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.3.tgz",
"integrity": "sha512-eoiQwpEZWbpsVHcM9BAzqqe4TCHszvr3rsM7pUQ4ofLK0lF1i1d/jX0Qo5DYMqcrUtwQuDdDuOCbcT0Izf1VwQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-ia32-msvc": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.3.tgz",
"integrity": "sha512-kE+KUg6Dbbkgvcw0m99wJVIToFQzJqpMBAXah74WqxaLzssNwSTUccrHp6+QVzMhjQP330tvekFmnQF+0NbE6Q==",
"cpu": [
"ia32"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-x64-msvc": {
"version": "2.12.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.3.tgz",
"integrity": "sha512-L7wndWAgX2mLW7alswpL3d1R0P9FN2WYBgHaQkAYEBxHHGkY4vFX9CjcRQ1LAxDAMIJxrY7/aDziFJeChS84NQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
}
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"name": "strata-desktop",
"productName": "Strata",
"version": "0.2.5",
"private": true,
"description": "Strata Desktop - local AI, tuned to one model.",
"scripts": {
"build:ui": "npm --prefix ../host run build",
"typecheck:ui": "npm --prefix ../host run typecheck",
"test:ui": "npm --prefix ../host test",
"tauri": "tauri",
"dev": "npm run build:ui && tauri dev",
"build": "npm run build:ui && tauri build",
"build:app": "npm run build:ui && tauri build --bundles app",
"dmg": "npm run build:ui && tauri build --bundles dmg"
},
"devDependencies": {
"@tauri-apps/cli": "2.12.3"
}
}
@@ -0,0 +1,361 @@
#!/usr/bin/env python3
"""The installed Windows app, closed every way, with a stub engine: nothing may be left running.
python apps/desktop/scripts/app-close-matrix.py --install <folder the installer wrote> [--scenarios all] [--report out.json]
For each case it starts the REAL installed `strata-desktop.exe` (its window opens), loads a stub engine through the host's API
(profile + `runtime start` under Control's owner runtime, exactly the app's path), records every process of the tree (the app,
the host, Control, the owner host, the server, the engine), ends the app one way, and asserts:
* no process of the tree is left, the engine's port is free, the runtime lease can be taken again;
* the engine got the clean stop where the way of closing allows one (normal close, window X);
* the next load of the same slot works (a lost owner's state is cleaned, not a blocker).
It also proves a second launch focuses the open window and starts nothing, and that one app runs two engines and closes both.
Everything per-user lives under a scratch folder; the stub engine is a script. No real engine ever runs.
"""
from __future__ import annotations
import argparse
import ctypes
import json
import os
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
from ctypes import wintypes
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
import psutil # noqa: E402
from strata_control import procs, runtime # noqa: E402
from tests.terminal.lifecycle_matrix import install_fake_engine, port_open # noqa: E402
if os.name != "nt":
raise SystemExit("this matrix drives the Windows installer's app")
user32 = ctypes.WinDLL("user32", use_last_error=True)
WM_CLOSE = 0x0010
def main_window(pid: int) -> int | None:
found = []
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
def visit(hwnd, _):
owner = wintypes.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
if owner.value == pid and user32.IsWindowVisible(hwnd):
buf = ctypes.create_unicode_buffer(256)
user32.GetWindowTextW(hwnd, buf, 256)
if buf.value.strip() == "Strata":
found.append(hwnd)
return True
user32.EnumWindows(visit, 0)
return found[0] if found else None
class Scratch:
def __init__(self, root: Path, install: Path):
self.root, self.install = root, install
self.components = root / "components"
self.models = root / "models"
self.mark = root / "mark"
for d in (self.components, self.models, self.mark, root / "local", root / "home", root / "appdata", root / "webview"):
d.mkdir(parents=True, exist_ok=True)
install_fake_engine(self.components)
from tools.strata_tokenizer import BYTE_TO_UNICODE
tok = self.models / "tokenizer"
tok.mkdir()
tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ["ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"]
(tok / "vocab.json").write_text(json.dumps({t: i for i, t in enumerate(tokens)}))
(tok / "merges.txt").write_text("a b")
(tok / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3]))
for name in ("stub", "stub2"):
(self.models / f"strata-{name}.json").write_text(json.dumps({
"exe": "component:strata-engine", "backend": "cuda", "tokenizer": str(tok), "args": [], "cwd": str(root),
"model_name": name, "host": "127.0.0.1", "port": 0}))
self.env = {**os.environ, "STRATA_COMPONENTS_DIR": str(self.components), "STRATA_PROFILE_DIR": str(root / "profiles"),
"STRATA_RUNTIME_DIR": str(root / "runtime"), "STRATA_INSTALL_DIR": str(self.models),
"STRATA_MODELS_DIR": str(root / "models-unused"), "STRATA_ENGINE_BACKEND": "cuda",
"STRATA_HOME": str(root / "home"), "APPDATA": str(root / "appdata"), "LOCALAPPDATA": str(root / "local"),
"WEBVIEW2_USER_DATA_FOLDER": str(root / "webview"), "FAKE_ENGINE_MARK": str(self.mark),
"FAKE_ENGINE_SLOW_STEPS": "0", "PYTHONDONTWRITEBYTECODE": "1"}
self.env.pop("STRATA_API_KEY", None)
for key in ("STRATA_COMPONENTS_DIR", "STRATA_PROFILE_DIR", "STRATA_RUNTIME_DIR", "LOCALAPPDATA", "STRATA_ENGINE_BACKEND",
"STRATA_NO_ACQUIRE", "FAKE_ENGINE_MARK"):
os.environ[key] = self.env.get(key, "1") # this process reads the same runtime and records folders
class App:
def __init__(self, scratch: Scratch):
self.s = scratch
self.proc = subprocess.Popen([str(scratch.install / "strata-desktop.exe")], cwd=scratch.install, env=scratch.env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.base = None
def host(self):
for child in psutil.Process(self.proc.pid).children(recursive=True):
if child.name().lower() == "node.exe":
return child
return None
def wait_up(self, seconds=90):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if self.proc.poll() is not None:
raise RuntimeError(f"the app exited with {self.proc.returncode}")
try:
host = self.host()
if host:
for c in host.net_connections(kind="tcp"):
if c.status == "LISTEN" and c.laddr.ip == "127.0.0.1":
base = f"http://127.0.0.1:{c.laddr.port}"
try:
if urllib.request.urlopen(base + "/api/health", timeout=2).status == 200 and main_window(self.proc.pid):
self.base = base
return
except OSError:
pass
except psutil.Error:
pass
time.sleep(0.5)
raise RuntimeError("the app did not come up")
def call(self, path, method="GET", body=None):
req = urllib.request.Request(self.base + path, method=method, data=None if body is None else json.dumps(body).encode(),
headers={"content-type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=120) as r:
return json.loads(r.read() or b"null")
except urllib.error.HTTPError as exc:
raise RuntimeError(f"{method} {path} -> {exc.code} {exc.read()[:300]!r}") from None
def load(self, model, multiple=False):
self.call("/api/native?refresh=1")
started = self.call("/api/native/operations", "POST", {"kind": "load", "args": {"model": model, **({"multiple": True} if multiple else {})}})
deadline = time.monotonic() + 180
while time.monotonic() < deadline:
state = self.call("/api/native")
job = next((j for j in state["jobs"] if j["id"] == started["id"]), None)
if job and job["state"] != "running":
if job["state"] != "done":
raise RuntimeError(f"load {model}: {job['state']} {job.get('error')}")
return state
time.sleep(0.3)
raise RuntimeError("load did not finish")
def tree_of(app: App, slots=("app-1",)) -> tuple[list[procs.Ident], list[int]]:
idents, ports = [], []
members = [psutil.Process(app.proc.pid), *psutil.Process(app.proc.pid).children(recursive=True)]
pids = {p.pid for p in members}
for slot in slots:
state = runtime._read_state(slot)
if state:
pids.add(state["host_pid"])
for r in procs.records():
if r.get("profile") in slots: # the app's own slots; a Terminal service is not part of the app's tree
pids.add(r["pid"])
for pid in pids:
token = procs.start_token(pid)
if token:
idents.append(procs.Ident(pid, token, tuple(procs.command_line(pid) or [])))
return idents, ports
def survivors(idents):
return [f"{i.pid} {' '.join(i.cmd)[:80]}" for i in idents if procs.start_token(i.pid) == i.token]
def wait_gone(idents, seconds):
deadline = time.monotonic() + seconds
left = survivors(idents)
while left and time.monotonic() < deadline:
time.sleep(0.25)
left = survivors(idents)
return left
def lease_free() -> bool:
try:
fd = runtime.acquire_activity_lease(shared=False)
except Exception: # noqa: BLE001
return False
runtime._unlock_file(fd)
os.close(fd)
return True
def control(scratch: Scratch, *argv: str, timeout: int = 300) -> dict:
py = scratch.install / "control" / "python" / "python.exe"
out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), *argv, "--output", "json"],
env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"},
capture_output=True, text=True, timeout=timeout)
try:
return json.loads(out.stdout)
except ValueError:
return {"ok": False, "raw": out.stdout[-300:] + out.stderr[-300:]}
def stop_cli(scratch: Scratch, slot: str) -> dict:
py = scratch.install / "control" / "python" / "python.exe"
out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), "runtime", "stop", "--profile", slot, "--wait", "30",
"--output", "json"], env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"},
capture_output=True, text=True, timeout=120)
try:
return json.loads(out.stdout)
except ValueError:
return {"state": "?", "raw": out.stdout[-200:] + out.stderr[-200:]}
def case(name: str, install: Path, how: str) -> dict:
with tempfile.TemporaryDirectory(prefix="strata-app-matrix-", ignore_cleanup_errors=True) as tmp:
saved = dict(os.environ)
scratch = Scratch(Path(tmp), install)
app = App(scratch)
problems, note = [], ""
try:
app.wait_up()
slots = ("app-1", "app-2") if how == "two-engines" else ("app-1",)
terminal = None
if how == "window-x-terminal-engine":
# an engine the Terminal started (its own profile, no tie to the app) must survive the app's close
control(scratch, "profile", "create", "terminal-1", "--from-config", str(scratch.models / "strata-stub2.json"))
terminal = control(scratch, "runtime", "start", "--profile", "terminal-1", "--wait", "60")
if terminal.get("state") != "ready":
raise RuntimeError(f"the Terminal's service did not start: {terminal}")
terminal_pids = {r["pid"] for r in procs.records(profile="terminal-1")} | {runtime._read_state("terminal-1")["host_pid"]}
state = app.load("stub")
if how == "two-engines":
state = app.load("stub2", multiple=True)
engine_ports = [i["port"] for i in state["instances"]]
idents, _ = tree_of(app, slots)
kinds = sorted({("engine" if "engine" in " ".join(i.cmd) else "server" if "serve.server" in " ".join(i.cmd) else
"owner" if "strata_control.runtime" in " ".join(i.cmd) else "app" if "strata-desktop" in i.cmd[0].lower()
else "host" if "node" in i.cmd[0].lower() else "other") for i in idents})
note = f"tree {len(idents)} processes: {', '.join(kinds)}; engine ports {engine_ports}"
t0 = time.monotonic()
if how == "normal-close":
subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True)
elif how in ("window-x", "two-engines", "window-x-terminal-engine"):
hwnd = main_window(app.proc.pid)
if not hwnd:
raise RuntimeError("no main window")
user32.PostMessageW(hwnd, WM_CLOSE, 0, 0)
elif how == "kill-app":
subprocess.run(["taskkill", "/F", "/PID", str(app.proc.pid)], capture_output=True)
elif how == "host-crash":
host = app.host()
subprocess.run(["taskkill", "/F", "/PID", str(host.pid)], capture_output=True)
elif how == "second-launch":
second = subprocess.Popen([str(install / "strata-desktop.exe")], cwd=install, env=scratch.env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
code = second.wait(timeout=30)
except subprocess.TimeoutExpired:
second.kill()
problems.append("the second launch did not exit")
code = None
time.sleep(2)
hosts = [p for p in psutil.process_iter(["name", "pid"]) if p.info["name"].lower() == "node.exe"
and (p.parent() and p.parent().pid == app.proc.pid)]
apps = [p for p in psutil.process_iter(["name"]) if p.info["name"].lower() == "strata-desktop.exe"]
if app.proc.poll() is not None:
problems.append("the first app went away")
if len(apps) != 1:
problems.append(f"{len(apps)} app processes (want 1)")
if len(hosts) != 1:
problems.append(f"{len(hosts)} hosts under the first app (want 1)")
after, _ = tree_of(app, slots)
new = [i for i in after if i.pid not in {x.pid for x in idents}]
if new:
problems.append(f"the second launch started: {[' '.join(i.cmd)[:60] for i in new]}")
note += f"; second launch exit code {code}, app processes {len(apps)}, hosts {len(hosts)}"
subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True)
if how == "host-crash":
# the shell and its window stay (nothing here restarts a dead host); the host, Control's owner, the server and
# the engine must not
idents = [i for i in idents if any(k in " ".join(i.cmd) for k in ("strata_control.runtime", "serve.server", "engine", "node.exe"))]
left = wait_gone(idents, 90)
if left:
problems.append(f"processes left: {left}")
for port in engine_ports:
deadline = time.monotonic() + 10
while port_open(port) and time.monotonic() < deadline:
time.sleep(0.2)
if port_open(port):
problems.append(f"engine port {port} still open")
if terminal is None and not lease_free():
problems.append("lease still held")
marks = sorted(p.name for p in scratch.mark.iterdir())
if terminal is not None:
status = control(scratch, "runtime", "status", "--profile", "terminal-1")
alive_pids = [p for p in terminal_pids if procs.start_token(p)]
if status.get("state") != "ready" or len(alive_pids) != len(terminal_pids):
problems.append(f"closing the app disturbed the Terminal's service: {status.get('state')}, alive {alive_pids} of {sorted(terminal_pids)}")
note += f"; the Terminal's service is {status.get('state')} after the app closed"
stopped = control(scratch, "runtime", "stop", "--profile", "terminal-1", "--wait", "30")
if stopped.get("state") != "stopped" or [p for p in terminal_pids if procs.start_token(p)]:
problems.append(f"the Terminal's service did not stop on request: {stopped}")
time.sleep(1)
if not lease_free():
problems.append("lease still held after the Terminal's service stopped")
if how in ("normal-close", "window-x", "two-engines", "second-launch", "window-x-terminal-engine") and not ({"quit", "eof"} & set(marks)):
problems.append(f"the engine was not stopped the clean way (marks {marks})")
seconds = round(time.monotonic() - t0, 1)
if how == "host-crash":
subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True)
note += "; the app shell stays open after a host crash (by design today)"
# the slot must be usable again: stopping a lost owner's slot cleans its state; nothing blocks the next load
for slot in slots:
res = stop_cli(scratch, slot)
already = "not managed or is stopped" in json.dumps(res) # nothing was left to stop: the clean outcome
if res.get("state") not in ("stopped",) and not already:
problems.append(f"runtime stop {slot} after the close: {res}")
if runtime._read_state(slot) is not None:
problems.append(f"state of {slot} left behind")
return {"name": f"app-{how}", "ok": not problems, "problems": problems, "seconds": seconds, "marks": marks, "note": note}
except Exception as exc: # noqa: BLE001
return {"name": f"app-{how}", "ok": False, "problems": [f"{type(exc).__name__}: {exc}"] + problems, "note": note}
finally:
for p in psutil.process_iter(["name", "exe"]):
try:
if (p.info["exe"] or "").lower().startswith(str(install).lower()):
p.kill()
except psutil.Error:
pass
for r in procs.records():
try:
psutil.Process(r["pid"]).kill()
except psutil.Error:
pass
os.environ.clear(); os.environ.update(saved)
SCENARIOS = ["normal-close", "window-x", "window-x-terminal-engine", "kill-app", "host-crash", "second-launch", "two-engines"]
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--install", required=True)
ap.add_argument("--scenarios", default="all")
ap.add_argument("--report")
a = ap.parse_args()
names = SCENARIOS if a.scenarios == "all" else a.scenarios.split(",")
results = []
for how in names:
r = case(how, Path(a.install), how)
results.append(r)
print(("PASS " if r["ok"] else "FAIL ") + r["name"], r.get("seconds", ""), r.get("problems") or "", r.get("note", ""), flush=True)
if a.report:
Path(a.report).write_text(json.dumps({"platform": "windows", "engine": "fake", "results": results}, indent=1), encoding="utf-8")
return 0 if all(r["ok"] for r in results) else 1
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,110 @@
#!/usr/bin/env node
/**
* The Graphics cards choice of the app, end to end on a box with two cards, through the installed app layout (packaged host + bundled Control + a real
* engine component): the model list carries the options (one rule, strata_control/gpu_fit.py), a model that fits one card recommends that card, then
* load with ONE card -> answers, only that card holds the model; load with BOTH cards (the layer split) -> answers, both cards hold the model.
*
* node cards-e2e.mjs --install <folder with node/ host/ control/> --components <folder holding engine/<package>> --work <scratch> \
* --family qwen --model IQ3_XXS --data <data folder that has the model files> [--smi "nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits"]
*/
import { spawn, spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, readdirSync } from 'node:fs';
import { createServer } from 'node:net';
import { join, resolve } from 'node:path';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), []));
for (const need of ['install', 'components', 'work', 'model']) if (!args[need]) { console.error('missing --' + need); process.exit(2); }
const install = resolve(args.install), work = resolve(args.work), components = resolve(args.components), family = String(args.family ?? 'qwen'), modelId = String(args.model);
const node = join(install, 'node', 'node'), hostEntry = join(install, 'host', 'server', 'index.mjs');
const dirs = { models: join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home'), xdg: join(work, 'xdg'), appdata: join(work, 'appdata') };
for (const d of [dirs.models, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true });
const delay = ms => new Promise(r => setTimeout(r, ms));
let failed = false;
const record = (name, ok, detail = '') => { if (!ok) failed = true; console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 500) : ''}`); };
const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
const env = { ...process.env, STRATA_COMPONENTS_DIR: components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.models,
STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models-unused'), APPDATA: dirs.appdata, XDG_CONFIG_HOME: dirs.xdg, PYTHONDONTWRITEBYTECODE: '1' };
delete env.STRATA_API_KEY;
const port = await freePort();
const base = `http://127.0.0.1:${port}`;
const host = spawn(node, [hostEntry], { cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'],
env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1',
STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } });
let hostLog = '';
host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; });
const call = async (path, method = 'GET', body) => {
const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
return { status: response.status, body: await response.json().catch(() => null) };
};
async function waitJob(id, seconds) {
let last = '';
for (let i = 0; i < seconds * 2; i++) {
const state = (await call('/api/native')).body;
const job = state.jobs.find(j => j.id === id);
if (job && job.summary !== last) { last = job.summary; console.log(' ... ' + String(last).slice(0, 120)); }
if (job && job.state !== 'running') return { job, state };
await delay(500);
}
throw new Error('operation did not finish');
}
const smi = () => {
const cmd = String(args.smi ?? 'nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits').split(' ');
const r = spawnSync(cmd[0], cmd.slice(1), { encoding: 'utf8' });
return (r.stdout ?? '').split('\n').map(s => Number(s.trim())).filter(Number.isFinite);
};
async function chatPong(instance) {
const chat = await call('/v1/chat/completions', 'POST', { model: instance?.apiModelId ?? modelId.toLowerCase(), max_tokens: 400, stream: false, temperature: 0, messages: [{ role: 'user', content: 'Reply with exactly one word: pong' }] });
const m = chat.body?.choices?.[0]?.message ?? {};
return { ok: chat.status === 200 && /pong/i.test(`${m.content ?? ''}`), text: `${m.content ?? ''}`.slice(0, 60), status: chat.status };
}
async function main() {
let up = false;
for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { /* not yet */ } if (!up) await delay(150); }
record('host healthy', up, up ? base : hostLog.slice(-500));
if (!up) return;
const packages = existsSync(join(components, 'engine')) ? readdirSync(join(components, 'engine')) : [];
record('an engine component is installed', packages.length > 0, packages.join(', '));
// ---- the model list carries the choice
const native = (await call('/api/native?refresh=1')).body;
const gpus = native.hardware?.gpus ?? [];
record('the host sees two or more graphics cards', gpus.filter(g => g.usable !== false).length >= 2, JSON.stringify(gpus.map(g => ({ i: g.index, n: g.name, gb: g.vram_gb }))));
const size = native.catalog?.families?.find(f => f.family === family)?.sizes.find(s => s.model === modelId);
const opt = size?.gpu_options;
record('the model list offers the cards choice for this model', !!opt && opt.options.length >= 2, JSON.stringify(opt?.options?.map(o => ({ key: o.key, cards: o.cards, verdict: o.verdict, rec: o.recommended }))));
record('a model that fits one card recommends the single largest card (the split is offered, not forced)', opt?.recommended === 'single' && opt.options.find(o => o.key === 'split'), `recommended=${opt?.recommended}`);
const single = opt?.options.find(o => o.key === 'single')?.cards ?? [0];
const both = opt?.options.find(o => o.key === 'split')?.cards ?? [0, 1];
// ---- Download and prepare with the recommended card
const values = { family, model: modelId, context: 32768, vision: 'no', gpu: single[0], ...(args.data ? { data_dir: resolve(args.data) } : {}) };
const started = await call('/api/native/operations', 'POST', { kind: 'install', args: values });
record('the install operation starts', started.status === 200 || started.status === 202, JSON.stringify(started.body).slice(0, 160));
const done = await waitJob(started.body.id, 3600);
record('Download and prepare finishes', done.job.state === 'done', `${done.job.state} ${done.job.error ?? done.job.summary}`);
const installed = (await call('/api/native?refresh=1')).body.installed?.models?.find(m => String(m.model).toLowerCase() === modelId.toLowerCase());
const model = installed?.model ?? modelId.toLowerCase();
for (const [label, cards] of [['ONE card', single], ['BOTH cards (layer split)', both]]) {
const before = smi();
const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model, gpus: cards } });
const loaded = await waitJob(load.body.id, 900);
const instance = loaded.state.instances[0];
record(`load with ${label} starts the engine`, loaded.job.state === 'done' && instance?.status === 'ready', `${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}; gpus=${JSON.stringify(instance?.gpus)}`);
record(`the instance runs on exactly the chosen card(s)`, JSON.stringify([...(instance?.gpus ?? [])].sort()) === JSON.stringify([...cards].sort()), `want ${JSON.stringify(cards)} got ${JSON.stringify(instance?.gpus)}`);
await delay(3000);
const used = smi();
const holding = used.map((mb, i) => (mb - (before[i] ?? 0)) > 1000 ? i : -1).filter(i => i >= 0);
record(`only the chosen card(s) hold the model (graphics memory in use: ${used.join(', ')} MiB)`, JSON.stringify(holding) === JSON.stringify([...cards].sort()), `holding ${JSON.stringify(holding)}`);
const pong = await chatPong(instance);
record(`it answers (${label})`, pong.ok, `${pong.status} ${JSON.stringify(pong.text)}`);
const unloaded = await call(`/api/native/instances/${instance?.id}/unload`, 'POST', {});
record(`unload (${label})`, unloaded.status === 200, unloaded.status);
await delay(4000);
}
}
try { await main(); } catch (e) { record('run', false, e.stack ?? e); }
host.kill();
await delay(1500);
console.log(failed ? 'CARDS-E2E FAIL' : 'CARDS-E2E PASS');
process.exit(failed ? 1 : 0);
@@ -0,0 +1,72 @@
# Fetch and verify the private Node runtime the Windows desktop bundle ships (win-x64).
#
# The PowerShell twin of fetch-node.sh: same pinned version, same SHA-256 pin, same refusal to
# install anything whose digest does not match. Not committed output: node.exe is a ~90 MB binary.
#
# Usage:
# powershell -NoProfile -ExecutionPolicy Bypass -File apps\desktop\scripts\fetch-node.ps1
# ... -File fetch-node.ps1 -Check # verify what is already installed
# ... -File fetch-node.ps1 -FromFile node.zip # verify and install a zip you already have (offline)
#
# The Node version must satisfy the App Host's own engines.node (>= 24.12.0).
[CmdletBinding()]
param(
[switch]$Check,
[string]$FromFile = '',
[string]$Dest = ''
)
$ErrorActionPreference = 'Stop'
$NodeVersion = if ($env:STRATA_NODE_VERSION) { $env:STRATA_NODE_VERSION } else { '24.12.0' }
$Target = 'win-x64'
# SHA-256 of node-v24.12.0-win-x64.zip from nodejs.org's SHASUMS256.txt; keep equal to fetch-node.sh.
$Expected = '9c125f61ae947b52e779095830f9cac267846a043ef7192183c84016aaad2812'
if (-not $Dest) { $Dest = Join-Path $PSScriptRoot '..\src-tauri\resources\node' }
$Installed = Join-Path $Dest 'node.exe'
function Fail([string]$Message) { [Console]::Error.WriteLine("fetch-node: $Message"); exit 1 }
if ($Check) {
if (-not (Test-Path -LiteralPath $Installed)) { Fail "not installed at $Installed" }
$got = (& $Installed --version).Trim()
Write-Output "fetch-node: $Installed is $got"
if ($got -ne "v$NodeVersion") { Fail "expected v$NodeVersion" }
exit 0
}
$Archive = "node-v$NodeVersion-$Target.zip"
$Work = Join-Path ([IO.Path]::GetTempPath()) ("strata-node-" + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $Work | Out-Null
try {
$Zip = Join-Path $Work $Archive
if ($FromFile) {
Copy-Item -LiteralPath $FromFile -Destination $Zip
} else {
$Url = "https://nodejs.org/dist/v$NodeVersion/$Archive"
Write-Output "fetch-node: $Url"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Zip
}
$Actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $Zip).Hash.ToLowerInvariant()
if ($NodeVersion -ne '24.12.0') {
# another version has no recorded digest: say so rather than implying a verification
[Console]::Error.WriteLine("fetch-node: WARNING - no recorded digest for v$NodeVersion; this download is NOT authenticated.")
[Console]::Error.WriteLine("fetch-node: computed sha256 $Actual - record it in this script and fetch-node.sh.")
} elseif ($Actual -ne $Expected) {
Fail "REFUSING - $Archive hashes $Actual, expected $Expected"
} else {
Write-Output 'fetch-node: sha256 verified against the recorded digest'
}
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zipFile = [IO.Compression.ZipFile]::OpenRead($Zip)
try {
$entry = $zipFile.GetEntry("node-v$NodeVersion-$Target/node.exe")
if (-not $entry) { Fail "node.exe is not inside $Archive" }
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
[IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $Installed, $true)
} finally { $zipFile.Dispose() }
Write-Output "fetch-node: installed at $Installed"
} finally {
Remove-Item -LiteralPath $Work -Recurse -Force -ErrorAction SilentlyContinue
}
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env bash
# Fetch and verify the private Node runtime the desktop bundle ships.
#
# The App Host is an ordinary Node program, and the packaging requirement is that an end user
# supplies no runtime of their own. The desktop bundle therefore carries a pinned standalone Node
# beside the host.
#
# It is NOT committed. It is a ~117 MB platform binary: committing it would bloat every clone, it
# cannot be reviewed in a diff, and it is not source. This script is the reproducible substitute —
# it downloads the official build for the target and refuses to install anything whose SHA-256 does
# not match the recorded digest.
#
# Usage:
# apps/desktop/scripts/fetch-node.sh # host platform
# apps/desktop/scripts/fetch-node.sh --target linux-x64
# apps/desktop/scripts/fetch-node.sh --check # verify what is already installed
#
# The Node version must satisfy the App Host's own `engines.node` (>= 24.12.0).
set -euo pipefail
NODE_VERSION="${STRATA_NODE_VERSION:-24.12.0}"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEST="$HERE/../src-tauri/resources/node"
# Published SHA-256 of each official nodejs.org archive, recorded so a tampered or truncated
# download is refused rather than shipped. Add a row when bumping the version.
# Taken from nodejs.org's own SHASUMS256.txt for v24.12.0, which is published over HTTPS beside
# the archives. Recorded here so the fetch is verified against a value that does not come from the
# same response as the payload.
digest_for() {
case "$1" in
darwin-arm64) echo "319f221adc5e44ff0ed57e8a441b2284f02b8dc6fc87b8eb92a6a93643fd8080" ;;
linux-x64) echo "6159227e0af7d7c3c6bb2fa900452b04a6cb8841a702a79acc613209d70b04d0" ;;
linux-arm64) echo "9b2a2eeb98a8eb37361224e2a1d060300ad2dd143af58dfdb16de785df0f1228" ;;
win-x64) echo "9c125f61ae947b52e779095830f9cac267846a043ef7192183c84016aaad2812" ;;
*) echo "" ;;
esac
}
target() {
if [ "${1:-}" = "--target" ]; then echo "${2:?--target needs a value}"; return; fi
case "$(uname -s)-$(uname -m)" in
Darwin-arm64) echo darwin-arm64 ;;
Linux-x86_64) echo linux-x64 ;;
Linux-aarch64) echo linux-arm64 ;;
MINGW*|MSYS*|CYGWIN*) echo win-x64 ;;
*) echo "unsupported host: $(uname -s)-$(uname -m)" >&2; exit 2 ;;
esac
}
TARGET="$(target "$@")"
EXE="node"
case "$TARGET" in win-*) EXE="node.exe" ;; esac
INSTALLED="$DEST/$EXE"
if [ "${1:-}" = "--check" ]; then
if [ ! -x "$INSTALLED" ]; then echo "fetch-node: not installed at $INSTALLED" >&2; exit 1; fi
got="$("$INSTALLED" --version)"
echo "fetch-node: $INSTALLED is $got"
case "$got" in "v$NODE_VERSION") exit 0 ;; *) echo "fetch-node: expected v$NODE_VERSION" >&2; exit 1 ;; esac
fi
# The official archive for this target.
case "$TARGET" in
darwin-arm64) ARCHIVE="node-v$NODE_VERSION-darwin-arm64.tar.gz" ;;
darwin-x64) ARCHIVE="node-v$NODE_VERSION-darwin-x64.tar.gz" ;;
linux-x64) ARCHIVE="node-v$NODE_VERSION-linux-x64.tar.gz" ;;
linux-arm64) ARCHIVE="node-v$NODE_VERSION-linux-arm64.tar.gz" ;;
win-x64) ARCHIVE="node-v$NODE_VERSION-win-x64.zip" ;;
*) echo "fetch-node: no archive known for $TARGET" >&2; exit 2 ;;
esac
URL="https://nodejs.org/dist/v$NODE_VERSION/$ARCHIVE"
EXPECTED="$(digest_for "$TARGET")"
WORK="$(mktemp -d "${TMPDIR:-/tmp}/strata-node.XXXXXX")" # GNU mktemp needs the X template; BSD accepts it too
trap 'rm -rf "$WORK"' EXIT
echo "fetch-node: $URL"
curl -fsSL -o "$WORK/$ARCHIVE" "$URL"
ACTUAL="$(shasum -a 256 "$WORK/$ARCHIVE" 2>/dev/null | cut -d' ' -f1 || sha256sum "$WORK/$ARCHIVE" | cut -d' ' -f1)"
if [ -n "$EXPECTED" ]; then
if [ "$ACTUAL" != "$EXPECTED" ]; then
echo "fetch-node: REFUSING — $ARCHIVE hashes $ACTUAL, expected $EXPECTED" >&2
exit 1
fi
echo "fetch-node: sha256 verified against the recorded digest"
else
# Without a recorded digest the download cannot be authenticated. Say so loudly and keep the
# computed value so it can be recorded, rather than implying a verification that did not happen.
echo "fetch-node: WARNING — no recorded digest for $TARGET; this download is NOT authenticated." >&2
echo "fetch-node: computed sha256 $ACTUAL — record it in $(basename "${BASH_SOURCE[0]}") to enable verification." >&2
fi
mkdir -p "$DEST"
case "$ARCHIVE" in
*.zip) unzip -q -j "$WORK/$ARCHIVE" "node-v$NODE_VERSION-win-x64/node.exe" -d "$DEST" ;;
*) tar xzf "$WORK/$ARCHIVE" -C "$WORK"
cp "$WORK/node-v$NODE_VERSION-$TARGET/bin/node" "$DEST/node" ;;
esac
chmod +x "$DEST/$EXE"
echo "fetch-node: installed $("$DEST/$EXE" --version) at $DEST/$EXE"
@@ -0,0 +1,121 @@
#!/usr/bin/env node
/**
* The first run of the installed app, headless: the host as the Tauri shell starts it (STRATA_PACKAGED=1, STRATA_NO_ACQUIRE=1,
* the staged Control, nothing installed, nothing in the per-user folders) and Chrome on its onboarding.
*
* node apps/desktop/scripts/first-run-ui.mjs [--control <staged control>] [--node <node.exe>] [--work <scratch>] [--shots <dir>]
*
* Checks, one line each (exit 1 if any fails):
* the host answers; /api/native has a real catalog (families with sizes), a recommendation and the GPUs of this PC
* (from Control's bundled installer on Control's Python); the page shows "Let's get started", and after it the model
* list with sizes (no "couldn't show this screen"); no page error; the install plan for the recommended model is a
* plan (nothing is downloaded or started: a plan changes nothing); the spy sees no pip/git/compiler/engine fetch.
* Per-user folders (STRATA_HOME, APPDATA, LOCALAPPDATA, the components and install folders) are all under --work.
* No model is downloaded and no engine runs.
*/
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') ? true : all[i + 1]]] : acc), []));
const here = dirname(fileURLToPath(import.meta.url));
const repoHost = resolve(here, '../../host');
const staged = resolve(here, '../src-tauri/resources');
const control = resolve(args.control ?? join(staged, 'control'));
const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node'));
const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-first-run-')));
const shots = resolve(args.shots ?? join(work, 'shots'));
mkdirSync(work, { recursive: true }); mkdirSync(shots, { recursive: true });
const spy = pathToFileURL(join(repoHost, 'tests/helpers/acquire-spy.mjs')).href;
const spyLog = join(work, 'spy.log'); writeFileSync(spyLog, '');
const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(existsSync);
let failed = false;
const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); if (!ok) failed = true; };
const delay = ms => new Promise(r => setTimeout(r, ms));
const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
for (const need of [nodeExe, join(control, 'strata.py'), join(repoHost, 'dist', 'index.html')]) if (!existsSync(need)) { console.error(`missing ${need} (run stage-control.py, fetch-node and "npm run build" in apps/host first)`); process.exit(2); }
const dirs = { home: join(work, 'home'), appdata: join(work, 'appdata'), local: join(work, 'local'), components: join(work, 'local', 'Strata', 'components') };
for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true });
const port = await freePort();
const env = {
...process.env,
STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1',
STRATA_CONTROL_DIR: control, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models'), STRATA_COMPONENTS_DIR: dirs.components,
APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, XDG_CONFIG_HOME: join(work, 'xdg'), XDG_DATA_HOME: join(work, 'xdgdata'),
STRATA_PROFILE_DIR: join(work, 'profiles'), STRATA_RUNTIME_DIR: join(work, 'runtime'), ACQUIRE_SPY_LOG: spyLog,
};
delete env.STRATA_INSTALL_DIR;
mkdirSync(env.STRATA_MODELS_DIR, { recursive: true });
const host = spawn(nodeExe, [...(args['no-spy'] === undefined ? ['--import', spy] : []), join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, env, stdio: ['ignore', 'pipe', 'pipe'] });
let hostLog = '';
host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; });
const base = `http://127.0.0.1:${port}`;
const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; };
let browser;
try {
let up = false;
for (let i = 0; i < 150 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(200); } }
check(up, 'the packaged host starts', `port ${port}`);
if (!up) throw new Error(hostLog.slice(-2000));
const native = await api('/api/native?refresh=1');
const state = native.body;
check(native.status === 200 && state?.available === true, 'the host reads Control', state?.error ?? '');
const sizes = (state?.catalog?.families ?? []).reduce((n, f) => n + (f.sizes?.length ?? 0), 0);
check((state?.catalog?.families?.length ?? 0) > 0 && sizes >= 3, 'the catalog has real families and sizes', `${state?.catalog?.families?.length} families, ${sizes} sizes`);
check(!!state?.catalog?.recommendation, 'the catalog has a recommendation', JSON.stringify(state?.catalog?.recommendation ?? null).slice(0, 120));
check(Array.isArray(state?.hardware?.gpus), 'the hardware lists GPUs', (state?.hardware?.gpus ?? []).map(g => `${g.name} ${g.vram_gb} GB`).join('; ') || 'none on this PC');
check(state?.installDir && realpathSync.native(state.installDir).toLowerCase().startsWith(realpathSync.native(work).toLowerCase()), 'models go to a writable per-user folder, not the bundle', state?.installDir);
const hw = (await api('/api/hardware')).body;
console.log('info host hardware probe:', JSON.stringify((hw?.gpus ?? []).map(g => ({ name: g.name, backend: g.backend, vramGb: g.vramGb, unified: g.unified }))));
check(!state?.installerError, 'the bundled installer answers', state?.installerError ?? '');
browser = await chromium.launch({ executablePath: CHROME, headless: true });
const page = await browser.newPage({ viewport: { width: 1400, height: 950 } });
const problems = [];
page.on('pageerror', e => problems.push(`pageerror: ${e.message}`));
await page.goto(base, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('text=/Let.s get started|Choose a version|Connect your Strata/i', { timeout: 30000 }).catch(() => {});
await page.screenshot({ path: join(shots, '1-welcome.png') });
const broken = await page.locator('text=/couldn.t show this screen/i').count();
check(broken === 0, 'the first screen renders (not "Strata couldn\'t show this screen")');
const start = page.getByRole('button', { name: /get started/i });
check(await start.count() > 0, 'the welcome step offers "Let\'s get started"');
if (await start.count()) await start.first().click();
await page.waitForSelector('text=/Choose a version/i', { timeout: 30000 }).catch(() => {});
await delay(1200);
await page.screenshot({ path: join(shots, '2-models.png') });
check(await page.locator('text=/couldn.t show this screen/i').count() === 0, 'the model step renders');
check(await page.getByText(/Choose a version/i).count() > 0, 'the model step lists the versions');
const labels = await page.locator('[role=radio]').allInnerTexts();
check(labels.length >= 3, 'the versions are the real catalog\'s sizes', labels.map(l => l.replace(/\s+/g, ' ').slice(0, 40)).join(' | '));
check(labels.some(l => /\d+\.\d\s*GB/.test(l)), 'each version shows its download size');
check(problems.length === 0, 'no page error', problems.join('; '));
const recommended = state?.catalog?.recommendation;
if (recommended?.model) {
const plan = await api('/api/native/plan', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ family: recommended.family, model: recommended.model, context: recommended.context, data_dir: join(work, 'Strata-data') }) });
check(plan.status === 200 && !!plan.body?.plan, 'the install plan for the recommended model is a plan (nothing downloaded)', plan.body?.summary?.slice(0, 100) ?? JSON.stringify(plan.body).slice(0, 150));
check(!existsSync(join(work, 'Strata-data', 'models')), 'a plan wrote no model files');
}
} catch (error) {
check(false, 'the run', String(error?.message ?? error).slice(0, 600));
} finally {
await browser?.close().catch(() => {});
host.kill();
await new Promise(r => host.once('exit', r)); // only the PID this script started
const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean);
check(attempts.length === 0, 'the spy saw no pip, git, compiler, engine or internet access', attempts.slice(0, 3).join(' '));
console.log(`shots in ${shots}`);
if (!args.work) rmSync(work, { recursive: true, force: true, maxRetries: 3 });
}
process.exit(failed ? 1 : 0);
@@ -0,0 +1,133 @@
/**
* Turn a pnpm "isolated" node_modules (a virtual store in `.pnpm` full of links) into an ordinary hoisted tree of real folders.
*
* Why: the installer copies the Harness folder file by file. pnpm's layout is thousands of links (junctions on Windows); a copy
* that follows them duplicates every package once per dependent and one that does not breaks on the first dangling link. A hoisted
* tree has each package once (nested only where two versions of the same name are needed), no links, and Node resolves it
* exactly as it resolves any npm install.
*
* Algorithm (the one npm uses, in short): the packages the root names come first, at the top. Then, walking each placed package's
* own dependencies: look the name up from the package's own folder upwards; if the same instance is already visible, nothing to
* do; if a DIFFERENT instance of that name is visible, nest this one inside the dependent; if none is visible, hoist it to the top.
*
* @param {string} out folder holding `node_modules`
* @param {{skip?: RegExp}} [options] package names never copied (the caller removes them anyway)
* @returns {{packages:number, copied:number, nested:number}}
*/
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync } from 'node:fs';
import { dirname, join, relative, sep } from 'node:path';
export function flattenPnpm(out, { skip = null } = {}) {
const nm = join(out, 'node_modules');
const store = join(nm, '.pnpm');
const flatRoot = join(out, 'node_modules.flat');
rmSync(flatRoot, { recursive: true, force: true });
mkdirSync(join(flatRoot, 'node_modules'), { recursive: true });
const manifest = dir => { try { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')); } catch { return null; } };
const nameOf = dir => manifest(dir)?.name ?? null;
/**
* What makes two instances "the same package": name and version. pnpm keeps one copy per set of peer packages (the same workspace
* package under many hashed folders); in one hoisted tree they are one package.
*/
const identity = dir => { const m = manifest(dir); return m ? `${m.name}@${m.version}` : dir; };
/** The sibling links of a store instance: its dependencies, by name -> real instance folder. */
function storeDeps(instance, name) {
const container = name.startsWith('@') ? dirname(dirname(instance)) : dirname(instance);
const found = new Map();
for (const e of readdirSync(container, { withFileTypes: true })) {
if (e.name === '.bin') continue;
const entries = e.name.startsWith('@') ? readdirSync(join(container, e.name), { withFileTypes: true }).map(x => [`${e.name}/${x.name}`, join(container, e.name, x.name)]) : [[e.name, join(container, e.name)]];
for (const [dep, p] of entries) {
if (dep === name) continue;
try { if (lstatSync(p).isSymbolicLink() || existsSync(p)) found.set(dep, realpathSync(p)); } catch { /* a dangling link: the package was removed on purpose */ }
}
}
return found;
}
/** Every instance in the store by package name, for packages that arrived without a store entry (copied peers). */
const byName = new Map();
if (existsSync(store)) {
for (const id of readdirSync(store, { withFileTypes: true })) {
if (!id.isDirectory()) continue;
const container = join(store, id.name, 'node_modules');
if (!existsSync(container)) continue;
for (const e of readdirSync(container, { withFileTypes: true })) {
if (e.name === '.bin') continue;
const dirs = e.name.startsWith('@') ? readdirSync(join(container, e.name)).map(x => join(container, e.name, x)) : [join(container, e.name)];
for (const d of dirs) {
let real; try { real = realpathSync(d); } catch { continue; }
if (!real.startsWith(store)) continue; // a link to a workspace package outside the store is handled through the instance table
const n = nameOf(real);
if (n && !byName.has(n)) byName.set(n, real);
}
}
}
}
const placed = new Map(); // folder (in the flat tree) -> real instance folder it holds
let copied = 0, nested = 0;
const visibleFrom = (chain, name) => {
for (const dir of chain) {
const slot = join(dir, 'node_modules', ...name.split('/'));
if (placed.has(slot)) return { slot, instance: placed.get(slot) };
}
return null;
};
const copyInto = (slot, instance) => {
mkdirSync(dirname(slot), { recursive: true });
cpSync(instance, slot, { recursive: true, dereference: true, filter: f => !relative(instance, f).split(sep).includes('node_modules') });
placed.set(slot, identity(instance));
copied++;
};
const queue = []; // { slotDir (folder of the placed package), chain (folders searched upwards), instance, name }
const rootChain = [flatRoot];
const place = (name, instance, chain, forceHere) => {
if (skip?.test(name)) return;
const seen = visibleFrom(chain, name);
if (seen && seen.instance === identity(instance)) return;
const hoist = !seen && !forceHere;
const base = hoist ? flatRoot : chain[0];
const slot = join(base, 'node_modules', ...name.split('/'));
if (placed.has(slot)) return; // another instance already sits where this one would go (it nests below, handled by the caller's chain)
copyInto(slot, instance);
if (!hoist && base !== flatRoot) nested++;
queue.push({ slotDir: slot, chain: [slot, ...(hoist ? rootChain : chain)], instance, name });
};
// 1. the packages the root names
const rootEntries = [];
for (const e of readdirSync(nm, { withFileTypes: true })) {
if (e.name === '.pnpm' || e.name === '.bin' || e.name.startsWith('.')) continue;
const entries = e.name.startsWith('@') ? readdirSync(join(nm, e.name)).map(x => [`${e.name}/${x}`, join(nm, e.name, x)]) : [[e.name, join(nm, e.name)]];
for (const [name, p] of entries) rootEntries.push([name, p]);
}
for (const [name, p] of rootEntries) {
let real; try { real = realpathSync(p); } catch { continue; }
place(name, real, rootChain, true);
}
// 2. their dependencies, breadth first
while (queue.length) {
const { slotDir, chain, instance, name } = queue.shift();
let wants;
if (instance.startsWith(store)) wants = storeDeps(instance, name);
else {
// a package copied in without a store entry: its declared requirements, taken from the store by name when not visible yet
const m = manifest(instance) ?? {};
wants = new Map();
for (const dep of [...Object.keys(m.dependencies ?? {}), ...Object.keys(m.peerDependencies ?? {}), ...Object.keys(m.optionalDependencies ?? {})]) {
if (visibleFrom(chain, dep)) continue;
const real = byName.get(dep);
if (real) wants.set(dep, real);
}
}
for (const [dep, real] of wants) place(dep, real, chain, false);
}
rmSync(nm, { recursive: true, force: true });
renameSync(join(flatRoot, 'node_modules'), nm);
rmSync(flatRoot, { recursive: true, force: true });
return { packages: placed.size, copied, nested };
}
@@ -0,0 +1,79 @@
/**
* Which files and folders of the staged Harness are dropped, and the check that nothing the Harness imports is gone.
*
* The 2026-10-17 tester report: on Linux and Mac every agent chat failed ("session/create ... waiting for workflowEngine").
* Cause: the old rule "drop any folder named after another operating system" also removed the Harness's own JavaScript package
* `@deepseek-ai/dsh-win32-process`. It is plain JS (no binary), and `dsh-subprocess-local` and `dsh-sandbox-local` import it by
* name on every platform, so those two plugins failed to load, and everything waiting on them (shell, subprocess, ptcRuntime,
* workflowEngine) never started. Windows kept it (the rule differs there), so the Windows tests passed.
*/
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { join, sep } from 'node:path';
export const OTHER_OS = {
win32: /(^|[\\/._-])(darwin|linux|android|freebsd|musl)([\\/._-]|$)/i,
darwin: /(^|[\\/._-])(win32|linux|android|freebsd|musl)([\\/._-]|$)/i,
// Linux: the AppImage bundler (linuxdeploy) resolves the libraries of every ELF file under resources and stops on one it
// cannot satisfy (koffi's musl build wants libc.musl). The app is glibc x86_64, so musl and other-CPU builds are dropped.
linux: /(^|[\\/._-])(win32|darwin|android|freebsd|musl|arm64|aarch64|armv7|arm|ia32|riscv64|ppc64|s390x|loong64)([\\/._-]|$)/i,
};
const NATIVE_FOLDER = /prebuild|bin|native|platform|-(win32|darwin|linux)/i;
/** The Harness's own JavaScript packages (`@deepseek-ai/dsh-*`) are code every platform imports by name; never drop one. */
export function isHarnessCodePackage(path) {
const parts = path.split(sep);
const i = parts.lastIndexOf('@deepseek-ai');
return i >= 0 && i === parts.length - 2 && parts[i + 1].startsWith('dsh-');
}
/** True when the folder `path` (a directory named `name`) is another operating system's prebuilt binary and can go. */
export function isOtherOsBinaryFolder(platform, name, path) {
const rule = OTHER_OS[platform] ?? OTHER_OS.linux;
if (isHarnessCodePackage(path)) return false;
return rule.test(name) && NATIVE_FOLDER.test(path);
}
/** Imports the Windows copy (which works) is also without: browser-side or dev-only bundles, and the document converter the app drops on purpose. */
const KNOWN_ABSENT = new Set([
'@deepseek-ai/libreoffice-kit', '@deepseek-ai/dsh-client-ui-dockkit', '@deepseek-ai/dsh-client-web',
'@deepseek-ai/dsh-experimental-webworker-runtime', '@deepseek-ai/dsh-remote-mock', '@deepseek-ai/dsh-client-test-runtime',
]);
function jsFiles(dir, out = []) {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, e.name);
if (e.isSymbolicLink()) continue;
if (e.isDirectory()) jsFiles(p, out);
else if (/\.(m?js|cjs)$/.test(e.name)) out.push(p);
}
return out;
}
/**
* Every bare `@deepseek-ai/<package>` the staged Harness's own packages import (static `from "x"` and `import("x")`) must exist
* in the staged node_modules. Returns the list of `{from, missing}` problems (empty = good). Plugins that are only loaded on
* another platform still count: Node resolves a static import whether or not the code runs.
*/
export function missingHarnessImports(harnessDir) {
const scope = join(harnessDir, 'node_modules', '@deepseek-ai');
if (!existsSync(scope)) return [{ from: scope, missing: '@deepseek-ai (no installed packages)' }];
const problems = [];
const seen = new Set();
const re = /(?:from|import)\s*\(?\s*["'](@deepseek-ai\/[^"'/]+)(?:\/[^"']*)?["']/g;
for (const pkg of readdirSync(scope)) {
const lib = join(scope, pkg, 'lib');
if (!existsSync(lib)) continue;
for (const file of jsFiles(lib)) {
const text = readFileSync(file, 'utf8');
for (const m of text.matchAll(re)) {
const name = m[1];
const key = `${pkg}>${name}`;
if (seen.has(key) || KNOWN_ABSENT.has(name)) continue;
seen.add(key);
if (!existsSync(join(harnessDir, 'node_modules', ...name.split('/')))
&& !existsSync(join(scope, pkg, 'node_modules', ...name.split('/')))) problems.push({ from: `${pkg}`, missing: name });
}
}
}
return problems;
}
@@ -0,0 +1,310 @@
#!/usr/bin/env node
/**
* Prove the INSTALLED app layout can start and stop an engine with nothing acquired, using a stub engine.
*
* node apps/desktop/scripts/installed-flow.mjs --install <folder the installer wrote> [--work <scratch>] [--spy <acquire-spy.mjs>]
*
* It starts the installed host with the installed node.exe exactly as the Tauri shell does (STRATA_PACKAGED=1,
* STRATA_NO_ACQUIRE=1; Control found beside the host), against a scratch component folder holding a fake engine
* package and a scratch install folder holding one run config. Everything per-user (profiles, runtime state, host data,
* components) lives under --work, so the real profile of whoever runs this is never read or written.
*
* Steps (each one printed, the run exits 1 if any fails):
* host health, Control status (engine usable, acquiring forbidden), models from Control, load through the host
* (profile + `runtime start` under the owner runtime), a chat answer from the stub engine, a second client attaches to
* the same owner/instance, unload stops it, no engine for this PC is a notice with nothing started, the Tauri-style
* clean shutdown stops the engines the host started, a hard-killed host takes its engine with it.
* With --spy the host runs under tests/helpers/acquire-spy.mjs and the run fails on any attempt to reach the internet or
* run an installer.
*
* REAL mode (a test box with a GPU): --components <folder holding engine/<package>> --models <folder with strata-<id>.json
* whose engine is "component:strata-engine"> --model <id> [--backend cuda]. The same host and Control, a real engine and a
* real model: load, a real answer, ownership, unload, the missing-engine notice, load again, clean shutdown. The stub-only
* steps (the marker file, the hard-kill report) are left out.
*/
import { spawn, spawnSync } from 'node:child_process';
import { createHash, randomBytes } from 'node:crypto';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, chmodSync } from 'node:fs';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), []));
if (!args.install) { console.error('usage: installed-flow.mjs --install <folder> [--work <dir>] [--spy <acquire-spy.mjs>]'); process.exit(2); }
const install = resolve(args.install);
const isWin = process.platform === 'win32';
const node = join(install, 'node', isWin ? 'node.exe' : 'node');
const hostEntry = join(install, 'host', 'server', 'index.mjs');
const controlDir = join(install, 'control');
const python = isWin ? join(controlDir, 'python', 'python.exe') : join(controlDir, 'python', 'bin', 'python3');
const real = !!args.components;
const modelId = String(args.model ?? 'stub');
const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-installed-flow-')));
mkdirSync(work, { recursive: true });
const dirs = { components: real ? resolve(args.components) : join(work, 'components'), models: real ? resolve(args.models) : join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home') };
// the runtime and profile folders are created by Control itself, with the owner-only ACL it insists on
for (const [name, d] of Object.entries(dirs)) if (!['runtime', 'profiles'].includes(name) && !(real && ['components', 'models'].includes(name))) mkdirSync(d, { recursive: true });
const steps = [];
const record = (name, ok, detail = '') => { steps.push({ name, ok: !!ok, detail: String(detail) }); console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`); };
const delay = ms => new Promise(r => setTimeout(r, ms));
const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
const sha = buf => createHash('sha256').update(buf).digest('hex');
// ------------------------------------------------------------------------------ fixtures
const baseEnv = {
...process.env,
STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime,
STRATA_INSTALL_DIR: dirs.models, STRATA_ENGINE_BACKEND: String(args.backend ?? 'cuda'), STRATA_HOME: dirs.home, STRATA_MODELS_DIR: real ? join(work, 'models-unused') : dirs.models,
APPDATA: join(work, 'appdata'), XDG_CONFIG_HOME: join(work, 'xdg'), PYTHONDONTWRITEBYTECODE: '1',
};
delete baseEnv.STRATA_API_KEY;
mkdirSync(baseEnv.APPDATA, { recursive: true });
const mark = join(work, 'engine-ran.json');
const FAKE_ENGINE = `import os, sys, json
from pathlib import Path
Path(os.environ['FAKE_ENGINE_MARK']).write_text(json.dumps({'pid': os.getpid(), 'script': os.path.abspath(__file__), 'argv': sys.argv[1:]}))
print('READY 4096 stop', flush=True)
for line in sys.stdin:
if line.strip() == 'QUIT': break
if line.startswith(('GEN ', 'BGEN ')):
slot = int(line.split()[1]) if line.startswith('BGEN ') else None
print('T 97', flush=True)
print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True)
if slot is not None: print(f'BADM {slot} 0', flush=True)
`;
function installFakeEngine() {
const platform = isWin ? 'windows-x86_64' : 'linux-x86_64';
const folder = join(dirs.components, 'engine', `0.1.45-${platform}-cuda`);
mkdirSync(folder, { recursive: true });
writeFileSync(join(folder, 'engine_main.py'), FAKE_ENGINE);
const entry = isWin ? 'engine.cmd' : 'engine';
writeFileSync(join(folder, entry), isWin
? `@echo off\r\n"${python}" "%~dp0engine_main.py" %*\r\n`
: `#!/bin/sh\nexec "${python}" "$(dirname "$0")/engine_main.py" "$@"\n`);
if (!isWin) chmodSync(join(folder, entry), 0o755);
const files = [entry, 'engine_main.py'].map(p => { const b = readFileSync(join(folder, p)); return { path: p, sha256: sha(b), bytes: b.length }; });
writeFileSync(join(folder, 'engine-component.json'), JSON.stringify({ schema_version: 1, id: 'strata-engine', version: '0.1.45', platform, backend: 'cuda', entrypoint: entry, files }));
return folder;
}
function makeTokenizerAndConfig() {
const tok = join(dirs.models, 'tokenizer');
mkdirSync(tok, { recursive: true });
const script = `import json, sys\nfrom tools.strata_tokenizer import BYTE_TO_UNICODE\ntok = sys.argv[1]\ntokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ['ab', '<|im_start|>', '<|im_end|>', '<|endoftext|>']\njson.dump({t: i for i, t in enumerate(tokens)}, open(tok + '/vocab.json', 'w'))\nopen(tok + '/merges.txt', 'w').write('a b')\njson.dump([0] * 257 + [3, 3, 3], open(tok + '/token_type.json', 'w'))\n`;
const done = spawnSync(python, ['-c', script, tok], { cwd: controlDir, env: { ...baseEnv, PYTHONNOUSERSITE: '1' }, encoding: 'utf8' });
if (done.status !== 0) throw new Error('tokenizer fixture failed: ' + done.stderr);
writeFileSync(join(dirs.models, 'strata-stub.json'), JSON.stringify({ exe: 'component:strata-engine', backend: 'cuda', tokenizer: tok, args: [], cwd: work, model_name: 'stub', host: '127.0.0.1', port: 0 }));
}
const control = (...argv) => spawnSync(python, [join(controlDir, 'strata.py'), ...argv, '--output', 'json'], { cwd: controlDir, env: { ...baseEnv, PYTHONNOUSERSITE: '1', STRATA_NO_ACQUIRE: '1', FAKE_ENGINE_MARK: mark }, encoding: 'utf8', timeout: 120000 });
const controlJson = (...argv) => { const r = control(...argv); let json = null; try { json = JSON.parse(r.stdout.slice(r.stdout.indexOf('{'))); } catch { /* not json */ } return { code: r.status, json, text: r.stdout + r.stderr }; };
const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };
// ------------------------------------------------------------------------------ the host
let host = null, port = 0, base = '', spyLog = null, shutdownToken = randomBytes(32).toString('hex');
async function startHost() {
port = await freePort(); base = `http://127.0.0.1:${port}`;
const hostArgs = [...(args.spy ? ['--import', pathToFileURL(resolve(args.spy)).href] : []), hostEntry];
if (args.spy) { spyLog = join(work, 'acquire-spy.log'); writeFileSync(spyLog, ''); }
host = spawn(node, hostArgs, {
cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1',
STRATA_NO_ACQUIRE: '1', STRATA_SHUTDOWN_TOKEN: shutdownToken, FAKE_ENGINE_MARK: mark, STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()),
...(spyLog ? { ACQUIRE_SPY_LOG: spyLog } : {}) },
});
let log = '';
host.stdout.on('data', c => { log += c; }); host.stderr.on('data', c => { log += c; });
host.hostLog = () => log;
for (let i = 0; i < 200; i++) { try { if ((await fetch(base + '/api/health')).ok) return true; } catch { /* not yet */ } await delay(150); }
return false;
}
/** The host started the way the Tauri shell starts it, by a stand-in shell (a node process) that can then be killed hard. */
async function startHostViaShell() {
port = await freePort(); base = `http://127.0.0.1:${port}`;
const spec = { command: node, args: [hostEntry], options: {
cwd: join(install, 'host'), stdio: 'ignore', windowsHide: true,
env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1',
STRATA_NO_ACQUIRE: '1', STRATA_SHUTDOWN_TOKEN: shutdownToken, STRATA_EXIT_WITH_PARENT: '1', FAKE_ENGINE_MARK: mark,
STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } } };
const shell = spawn(node, ['-e', "const s=JSON.parse(process.env.HOST_SPEC);const c=require('node:child_process').spawn(s.command,s.args,s.options);console.log(c.pid);setInterval(()=>{},1000);"],
{ env: { ...process.env, HOST_SPEC: JSON.stringify(spec) }, stdio: ['ignore', 'pipe', 'inherit'], windowsHide: true });
const hostPid = await new Promise(r => shell.stdout.once('data', c => r(Number(String(c).trim()))));
for (let i = 0; i < 200; i++) { try { if ((await fetch(base + '/api/health')).ok) return { shell, hostPid }; } catch { /* not yet */ } await delay(150); }
return { shell, hostPid, failed: true };
}
const call = async (path, method = 'GET', body) => {
const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
return { status: response.status, body: await response.json().catch(() => null) };
};
async function waitJob(id, seconds = 120) {
for (let i = 0; i < seconds * 5; i++) {
const state = (await call('/api/native')).body;
const job = state.jobs.find(j => j.id === id);
if (job && job.state !== 'running') return { job, state };
await delay(200);
}
throw new Error('operation did not finish');
}
async function stopHost(hard = false) {
if (!host || host.exitCode !== null) return;
if (hard) { if (isWin) spawnSync('taskkill', ['/PID', String(host.pid), '/T', '/F'], { windowsHide: true }); else host.kill('SIGKILL'); }
else host.kill();
for (let i = 0; i < 100 && host.exitCode === null; i++) await delay(100);
}
async function main() {
for (const need of [node, hostEntry, python, join(controlDir, 'strata.py')]) if (!existsSync(need)) { record('installed layout', false, `missing ${need}`); return; }
record('installed layout', true, install);
if (real) {
const packages = existsSync(join(dirs.components, 'engine')) ? readdirSync(join(dirs.components, 'engine')) : [];
record('fixtures', packages.length > 0 && existsSync(join(dirs.models, `strata-${modelId}.json`)), `engine package(s) ${packages.join(', ')} in ${dirs.components}; run config strata-${modelId}.json in ${dirs.models}`);
} else {
installFakeEngine();
makeTokenizerAndConfig();
record('fixtures', true, `stub engine package in ${dirs.components}; run config strata-stub.json`);
}
if (!(await startHost())) { record('host healthy', false, host.hostLog().slice(-600)); return; }
record('host healthy', true, base);
const status = (await call('/api/control/status')).body;
record('Control status: bundled, engine usable, acquiring forbidden', status.control?.python?.startsWith(controlDir) && status.engine?.usable === true && status.acquisition?.forbidden === true,
`python=${status.control?.python}; engine=${status.engine?.engine?.version}; forbidden=${status.acquisition?.forbidden}`);
const native = (await call('/api/native?refresh=1')).body;
const model = native.installed?.models?.find(m => m.model === modelId);
record('models come from Control', native.available && model?.ready === true && native.packaged === true, `available=${native.available}; model ready=${model?.ready}; ${native.summary ?? native.error}`);
// ---- load
const started = (await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body;
const loaded = await waitJob(started.id, 400);
const instance = loaded.state.instances[0];
record('load through the host starts the engine under Control', loaded.job.state === 'done' && instance?.status === 'ready', `job=${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}`);
let ran = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null;
if (real) {
const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve'));
ran = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]), script: listed[0].trim().split(/\s+/)[1] } : null;
record('the engine process running is the binary from the component folder', !!ran, listed[0] ? listed[0].trim().slice(0, 160) : 'no engine process under the component folder');
} else {
record('the engine that ran is the one in the component folder', ran && ran.script.toLowerCase().startsWith(dirs.components.toLowerCase()), ran?.script ?? 'engine never ran');
}
const runtime = controlJson('runtime', 'status', '--profile', 'app-1');
record('a second client sees the same owner and instance (ownership)', runtime.json?.state === 'ready' && !!runtime.json.owner_id && !!runtime.json.instance_id && runtime.json.host_pid !== host.pid,
`state=${runtime.json?.state}; owner=${String(runtime.json?.owner_id).slice(0, 8)}; instance=${String(runtime.json?.instance_id).slice(0, 8)}; owner host pid ${runtime.json?.host_pid} is not the app host (${host.pid})`);
// ---- answer
const chat = await call('/v1/chat/completions', 'POST', real
? { model: instance?.apiModelId ?? modelId, messages: [{ role: 'user', content: 'Reply with exactly one word: pong' }], max_tokens: 200, temperature: 0, reasoning_effort: 'none', stream: false }
: { model: instance?.apiModelId ?? modelId, messages: [{ role: 'user', content: 'hi' }], max_tokens: 4, stream: false });
const message = chat.body?.choices?.[0]?.message ?? {};
const answer = `${message.content ?? ''}${message.reasoning_content ?? ''}`; // the stub emits token 97 ("a"); the server files it as reasoning
record(real ? 'the real model answers through the host (the answer text is checked)' : 'the engine answers through the host (the stub token, not an error)',
chat.status === 200 && (real ? /pong/i.test(answer) : answer === 'a'), `status=${chat.status}; answer=${JSON.stringify(answer.slice(0, 200))}${chat.status === 200 ? '' : ' ' + JSON.stringify(chat.body).slice(0, 160)}`);
// ---- unload
const unloaded = await call(`/api/native/instances/${instance.id}/unload`, 'POST', {});
await delay(500);
const after = controlJson('runtime', 'status', '--profile', 'app-1');
for (let i = 0; i < 100 && ran && alive(ran.pid); i++) await delay(100); // a real engine takes a moment to release the GPU
record('unload stops the engine', unloaded.status === 200 && after.json?.state === 'stopped' && (!ran || !alive(ran.pid)), `status=${unloaded.status}; runtime=${after.json?.state}; engine pid ${ran?.pid} alive=${ran ? alive(ran.pid) : 'n/a'}`);
// ---- no engine for this PC
const hidden = join(dirs.components, real ? 'engine.hidden-by-flow' : 'engine.gone');
renameSync(join(dirs.components, 'engine'), hidden);
rmSync(mark, { force: true });
const missing = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id);
record('no engine for this PC is a notice and nothing is started', missing.job.state === 'error' && /No engine for this PC/.test(missing.job.error) && /never downloads/.test(missing.job.error) && !existsSync(mark),
`${missing.job.state}: ${String(missing.job.error).slice(0, 160)}`);
const refused = await waitJob((await call('/api/native/operations', 'POST', { kind: 'install', args: { family: 'qwen', model: 'IQ2_XS' } })).body.id);
record('installing from the app is refused (Terminal only)', refused.job.state === 'error' && /Terminal/.test(refused.job.error), refused.job.error);
const binary = await call('/api/engine/binary', 'POST');
record('the llama.cpp download route is refused', binary.status === 409 && /never downloads/.test(binary.body?.error ?? ''), `${binary.status} ${binary.body?.error}`);
// ---- clean shutdown (what the Tauri shell does on exit)
renameSync(hidden, join(dirs.components, 'engine'));
rmSync(mark, { force: true });
const again = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400);
let ran2 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null;
if (real) {
const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve'));
ran2 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null;
}
record('load again after the engine package returns', again.job.state === 'done', again.job.error ?? '');
const wrong = await fetch(base + '/api/control/shutdown', { method: 'POST', headers: { 'x-strata-shutdown': 'nope' } });
record('shutdown without the shell\'s secret is refused', wrong.status === 403, String(wrong.status));
const exited = new Promise(r => host.once('exit', code => r(code)));
const stopping = await fetch(base + '/api/control/shutdown', { method: 'POST', headers: { 'x-strata-shutdown': shutdownToken } });
const code = await Promise.race([exited, delay(90000).then(() => 'timeout')]);
for (let i = 0; i < 100 && ran2 && alive(ran2.pid); i++) await delay(100);
const final = controlJson('runtime', 'status', '--profile', 'app-1');
record('clean shutdown stops the engine the app started and exits', stopping.status === 202 && code === 0 && final.json?.state === 'stopped' && (!ran2 || !alive(ran2.pid)), `status=${stopping.status}; host exit=${code}; runtime=${final.json?.state}; engine alive=${ran2 ? alive(ran2.pid) : 'n/a'}`);
// ---- hard kill: an engine whose app host dies ends with it (the owner follows the host: runtime start --die-with-pid)
if (!(await startHost())) { record('host restarts', false, host.hostLog().slice(-400)); return; }
await call('/api/native?refresh=1');
rmSync(mark, { force: true });
const third = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400);
let ran3 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null;
if (real) {
const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve'));
ran3 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null;
record('(real) the engine is up before the host is killed', !!ran3, listed[0] ? listed[0].trim().slice(0, 120) : 'no engine process');
}
await stopHost(true);
for (let i = 0; i < 600 && ran3 && alive(ran3.pid); i++) await delay(100); // the owner notices within a second, drains, stops
const orphan = controlJson('runtime', 'status', '--profile', 'app-1');
record('a hard-killed app host takes its engine with it', third.job.state === 'done' && (!ran3 || !alive(ran3.pid)), `engine alive=${ran3 ? alive(ran3.pid) : 'n/a'}; runtime=${orphan.json?.state ?? orphan.json?.error?.message}`);
const cleanup = controlJson('runtime', 'stop', '--profile', 'app-1');
record('nothing is left to stop afterwards', /stopped|not managed/.test(JSON.stringify(cleanup.json)) && controlJson('runtime', 'status', '--profile', 'app-1').json?.state === 'stopped', JSON.stringify(cleanup.json).slice(0, 160));
// ---- the shell itself is killed (what the desktop shell's crash or kill looks like to the host): the host leaves, and
// its engine with it, with nothing announced. Windows also has the job object; this is the path that works everywhere.
const started2 = await startHostViaShell();
if (started2.failed) { record('host starts under a stand-in shell', false, ''); try { started2.shell.kill('SIGKILL'); } catch { /* gone */ } }
else {
await call('/api/native?refresh=1');
rmSync(mark, { force: true });
const fourth = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400);
let ran4 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null;
if (real) {
const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve'));
ran4 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null;
}
if (isWin) spawnSync('taskkill', ['/PID', String(started2.shell.pid), '/F'], { windowsHide: true }); else started2.shell.kill('SIGKILL');
for (let i = 0; i < 100 && alive(started2.hostPid); i++) await delay(100);
const hostGone = !alive(started2.hostPid);
for (let i = 0; i < 900 && ran4 && alive(ran4.pid); i++) await delay(100);
const engineGone = !ran4 || !alive(ran4.pid);
record('a killed shell takes the host and its engine with it', fourth.job.state === 'done' && hostGone && engineGone,
`host pid ${started2.hostPid} gone=${hostGone}; engine pid ${ran4?.pid} gone=${engineGone}; runtime=${controlJson('runtime', 'status', '--profile', 'app-1').json?.state}`);
controlJson('runtime', 'stop', '--profile', 'app-1');
}
await finishSpy();
}
async function finishSpy() {
if (spyLog) {
const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean);
record('no acquisition attempt by the host during the whole run (spy)', attempts.length === 0, attempts.join(' | '));
}
}
try { await main(); }
catch (error) { record('flow', false, error.stack ?? error.message); }
finally {
try { const hid = join(dirs.components, 'engine.hidden-by-flow'); if (real && existsSync(hid) && !existsSync(join(dirs.components, 'engine'))) renameSync(hid, join(dirs.components, 'engine')); } catch { /* reported by the run */ }
await stopHost(true);
controlJson('runtime', 'stop', '--profile', 'app-1');
controlJson('runtime', 'stop', '--profile', 'app-2');
}
const failed = steps.filter(s => !s.ok);
writeFileSync(join(work, 'installed-flow.json'), JSON.stringify({ ok: failed.length === 0, install, work, steps }, null, 1));
console.log(`\n${steps.length - failed.length}/${steps.length} ok; report ${join(work, 'installed-flow.json')}`);
if (!args.keep && !args.work && failed.length === 0) { try { rmSync(work, { recursive: true, force: true }); } catch { /* leave it */ } }
process.exit(failed.length ? 1 : 0);
@@ -0,0 +1,73 @@
#!/usr/bin/env node
/**
* Mock-ups of the Windows installer in Strata's own look: four screens (welcome, where, installing, done), light and dark, drawn with
* the app's built CSS (apps/host/dist) and brand files, then photographed with Chrome. Nothing here is built or shipped: it is what
* the owner is shown before an installer is chosen.
*
* node apps/desktop/scripts/installer-mockups.mjs [--out <folder>]
*/
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []));
const here = dirname(fileURLToPath(import.meta.url));
const host = resolve(here, '../../host');
const out = resolve(args.out ?? join(here, '../installer-mockups'));
mkdirSync(out, { recursive: true });
const dist = join(host, 'dist');
const css = readdirSync(join(dist, 'assets')).filter(f => f.endsWith('.css')).map(f => readFileSync(join(dist, 'assets', f), 'utf8')).join('\n');
const logo = theme => readFileSync(join(dist, 'brand', `strata-lockup-${theme}.svg`), 'utf8');
const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
const check = '<svg class="st-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>';
const folder = '<svg class="st-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
const screens = {
welcome: theme => `<header class="onboard-header"><span class="mock-logo">${logo(theme)}</span></header>
<div class="onboard-welcome-copy"><h1>State of the art. At home.</h1><p>Strata runs AI on your own computer.<br>Setting it up takes a few minutes.</p>
<div class="onboard-benefits"><span>${check}Private</span><span>${check}Fast</span><span>${check}Easy to use</span></div></div>
<footer class="onboard-footer onboard-footer--welcome"><button class="st-btn st-btn--primary">Install Strata</button><small>Installs for you only. No administrator needed.</small></footer>`,
where: theme => `<header class="onboard-header"><span class="mock-logo">${logo(theme)}</span></header>
<div class="mock-body"><h2 class="mock-title">Where should Strata go?</h2><p class="mock-sub">This is the right place for most people.</p>
<div class="onboard-folder">${folder}<div><strong>Your Strata folder</strong><small>C:\\Users\\Alex\\AppData\\Local\\Strata</small></div><button class="st-btn st-btn--sm">Change</button></div>
<p class="mock-note">About 310 MB. Your models and chats are kept somewhere else and are never removed by an update.</p></div>
<footer class="onboard-footer"><button class="st-btn st-btn--ghost">Back</button><span></span><button class="st-btn st-btn--primary">Install</button></footer>`,
installing: theme => `<header class="onboard-header"><span class="mock-logo">${logo(theme)}</span></header>
<div class="mock-body"><h2 class="mock-title">Installing Strata…</h2><p class="mock-sub">Copying the app and its engine room. You can keep working meanwhile.</p>
<div class="onboard-progress" style="--p:62%"><progress max="100" value="62"></progress></div>
<div class="onboard-progress-meta"><span>62% · 190 / 310 MB</span><div class="onboard-progress-actions"><span>About 1 min left</span><button>Cancel</button></div></div></div>
<footer class="onboard-footer"><span></span><span class="mock-hint">Next: choose your first model inside Strata.</span><button class="st-btn st-btn--primary" disabled>Installing…</button></footer>`,
done: theme => `<header class="onboard-header"><span class="mock-logo">${logo(theme)}</span></header>
<div class="onboard-welcome-copy"><h1>Strata is ready.</h1><p>Open it to pick your first model. Strata downloads it for you and gets it ready.</p></div>
<footer class="onboard-footer onboard-footer--welcome"><button class="st-btn st-btn--primary">Open Strata</button><small>A shortcut was added to your Start menu and desktop.</small></footer>`,
};
const page = (name, theme) => `<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css}
body{background:${theme === 'dark' ? '#0b0d0e' : '#e9edef'};margin:0;display:grid;place-items:center;min-height:100vh}
.mock-window{width:720px;border-radius:14px;overflow:hidden;background:var(--st-surface,#fff);border:1px solid var(--st-line,#dde);box-shadow:0 30px 80px #0003}
.mock-titlebar{height:34px;display:flex;align-items:center;justify-content:space-between;padding:0 14px;font-size:12px;color:var(--st-ink-muted);background:var(--st-surface-2,#f3f5f6);border-bottom:1px solid var(--st-line-soft,#e6e9eb)}
.mock-logo svg{height:22px;width:auto;display:block}
.mock-body{padding:8px 36px 28px}.mock-title{font-size:28px;margin:16px 0 8px}.mock-sub{color:var(--st-ink-muted);margin:0 0 22px;line-height:1.6}
.mock-note{color:var(--st-ink-muted);font-size:12px;margin-top:16px;line-height:1.6}.mock-hint{font-size:12px;color:var(--st-ink-muted)}
.onboard-progress progress{width:100%}
.guided-onboarding{min-height:430px;display:flex;flex-direction:column}.onboard-footer{margin-top:auto}
</style></head><body><div class="mock-window"><div class="mock-titlebar"><span>Strata setup</span><span>– ☐ ✕</span></div>
<div class="setup guided-onboarding" data-step="${name === 'welcome' || name === 'done' ? 1 : 2}">${screens[name](theme)}</div></div></body></html>`;
const browser = await chromium.launch({ executablePath: CHROME, headless: true });
const written = [];
for (const theme of ['light', 'dark']) {
for (const name of Object.keys(screens)) {
const tab = await browser.newPage({ viewport: { width: 860, height: 620 }, deviceScaleFactor: 1 });
await tab.setContent(page(name, theme));
await tab.waitForTimeout(250);
const file = join(out, `${name}-${theme}.png`);
await tab.screenshot({ path: file });
written.push(file);
await tab.close();
}
}
await browser.close();
console.log(written.join('\n'));
@@ -0,0 +1,126 @@
#!/usr/bin/env node
/**
* "Use your own GGUF" end to end on a box, through the installed app layout (packaged host + bundled Control + a real engine component):
* preview a folder of a supported model, preview an unsupported GGUF (must be refused in plain terms), prepare the supported one
* (pack, from the folder, nothing copied), load it, get a chat answer, unload, shut down, and check nothing is left running.
*
* node local-gguf-e2e.mjs --root /data/ui4-e2e --good /data/141-gyro/models/IQ2_XS --bad /data/ui4-e2e/bad [--context 8192] [--backend cuda|metal]
* (the app folder is <root>/app: node/, host/, control/ ...; <root>/components gets the engine, from <root>/app/engine-bundle when the app carries one)
*/
import { spawn, spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:net';
import { join, resolve } from 'node:path';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []));
const root = resolve(args.root);
const good = args.good, bad = args.bad;
const context = Number(args.context ?? 8192);
const app = join(root, 'app');
const dirs = { components: join(root, 'components'), install: join(root, 'install'), profiles: join(root, 'profiles'), runtime: join(root, 'runtime'), home: join(root, 'home'), xdg: join(root, 'xdg'), appdata: join(root, 'appdata') };
for (const d of [dirs.install, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true });
const delay = ms => new Promise(r => setTimeout(r, ms));
const steps = [];
let failed = false;
const record = (name, ok, detail = '') => { steps.push({ name, ok: !!ok, detail: String(detail).slice(0, 400) }); console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 300) : ''}`); if (!ok) failed = true; };
const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
const env = { ...process.env, STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.install, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(root, 'Strata-data'), STRATA_ENGINE_BACKEND: args.backend ?? 'cuda', XDG_CONFIG_HOME: dirs.xdg, APPDATA: dirs.appdata, PYTHONDONTWRITEBYTECODE: '1' };
delete env.STRATA_API_KEY;
const port = await freePort();
const base = `http://127.0.0.1:${port}`;
const host = spawn(join(app, 'node', 'node'), [join(app, 'host', 'server', 'index.mjs')], { cwd: join(app, 'host'), stdio: ['ignore', 'pipe', 'pipe'], detached: false,
env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(app, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', STRATA_EXIT_WITH_PARENT: '1',
STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_WORKSPACE: join(root, 'workspace') } });
mkdirSync(join(root, 'workspace'), { recursive: true });
let hostLog = ''; host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; });
const call = async (path, method = 'GET', body) => { const r = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); return { status: r.status, body: await r.json().catch(() => null) }; };
async function waitJob(id, seconds) {
const until = Date.now() + seconds * 1000;
let last = '';
while (Date.now() < until) {
const state = (await call('/api/native')).body;
const job = state.jobs.find(j => j.id === id);
if (job && job.state !== 'running') return { job, state };
if (job && job.summary !== last) { last = job.summary; console.log(' ...', String(job.summary).slice(0, 140)); }
await delay(2000);
}
throw new Error('operation did not finish in time');
}
const engineProcs = () => spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(join(dirs.components, 'engine')) && /\/strata( |$)/.test(l));
async function main() {
let up = false;
for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { await delay(150); } }
record('host healthy', up, up ? base : hostLog.slice(-500));
if (!up) return;
let status = (await call('/api/control/status')).body;
for (let i = 0; i < 180 && status?.engineSetup; i++) { await delay(1000); status = (await call('/api/control/status')).body; } // the engine that came with the app is copied on the first start
record('Control status: bundled, engine usable', status?.engine?.usable === true, `engine=${status?.engine?.engine?.version} ${status?.engine?.notice ?? ''}`);
await call('/api/native?refresh=1');
// ---- the unsupported GGUF: a plain refusal
const badPreview = await call('/api/native/local/preview', 'POST', { path: bad });
const badIssues = badPreview.body?.preview?.issues ?? badPreview.body?.issues ?? [];
const badStatus = badPreview.body?.preview?.file_set_status;
console.log(' bad preview:', badPreview.status, JSON.stringify(badPreview.body).slice(0, 400));
record('an unsupported GGUF is refused, nothing adopted', badPreview.status === 200 ? (badStatus !== 'plausible' || !badPreview.body.preview.candidate_selection) : badPreview.status >= 400, `status=${badPreview.status}; file_set_status=${badStatus}; issues=${JSON.stringify(badIssues)}`);
// ---- the supported folder
const goodPreview = await call('/api/native/local/preview', 'POST', { path: good });
const selection = goodPreview.body?.preview?.candidate_selection;
console.log(' good preview:', JSON.stringify(goodPreview.body).slice(0, 500));
record('a folder of a supported model is recognised', goodPreview.status === 200 && goodPreview.body?.preview?.file_set_status === 'plausible' && !!selection, `family=${selection?.family}; model=${selection?.model}; files=${goodPreview.body?.preview?.file_count}`);
if (!selection || args.only === 'preview') return;
// ---- prepare (what the page's button does): install from the folder, nothing copied or downloaded
const native0 = (await call('/api/native?refresh=1')).body;
const catalogSize = native0.catalog?.families?.find(f => f.family === selection.family)?.sizes.find(s => s.model === selection.model);
record('the catalog lists the recognised version', !!catalogSize, catalogSize ? `id=${catalogSize.id}` : `no ${selection.family}/${selection.model} in the catalog`);
const started = await call('/api/native/operations', 'POST', { kind: 'install', args: { family: selection.family, model: selection.model, gguf_dir: good, context, vision: 'no' } });
record('prepare starts', started.status < 300 && !!started.body?.id, `status=${started.status} ${JSON.stringify(started.body).slice(0, 200)}`);
if (!started.body?.id) return;
const prepared = await waitJob(started.body.id, 3600);
record('prepare finishes', prepared.job.state === 'done', `${prepared.job.state}: ${prepared.job.error ?? prepared.job.summary}`);
if (prepared.job.state !== 'done') return;
const native1 = (await call('/api/native?refresh=1')).body;
const modelId = catalogSize?.id ?? `${selection.family === 'qwen' ? '' : selection.family + '-'}${String(selection.model).toLowerCase()}`;
const entry = native1.installed?.models?.find(m => m.model === modelId);
record('the model is ready and points at the folder, not a copy', entry?.ready === true, `model=${modelId}; ready=${entry?.ready}; dataFolder=${entry?.dataFolder}`);
if (!entry?.ready) return;
// ---- load
const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } });
const loaded = await waitJob(load.body.id, 1800);
const instance = loaded.state.instances[0];
record('load starts the engine from the component folder', loaded.job.state === 'done' && instance?.status === 'ready', `job=${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}`);
if (instance?.status !== 'ready') return;
record('one engine process is running', engineProcs().length === 1, engineProcs().map(l => l.trim().slice(0, 140)).join(' | '));
// ---- a chat answer, checked
const chat = await fetch(base + '/api/chat/stream', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: 'e2e-chat', message: 'Reply with exactly one word: pong', history: [], nativeModelId: instance.id, thinking: 'Off', agent: false, workspaceId: null }) });
let text = '', done = null;
for await (const chunk of chat.body) {
for (const line of Buffer.from(chunk).toString('utf8').split('\n')) {
if (!line.trim()) continue;
try { const f = JSON.parse(line); if (f.type === 'delta') text += f.text ?? ''; if (f.type === 'done') done = f; if (f.type === 'error') text += ` [error: ${f.message}]`; } catch { /* partial line */ }
}
}
record('the model answers through the app (the answer text is checked)', chat.status === 200 && /pong/i.test(text), `status=${chat.status}; answer=${JSON.stringify(text.slice(0, 120))}; tokensOut=${done?.tokensOut}; tps=${done?.tps}`);
// ---- unload, shutdown, nothing left
const unload = await call(`/api/native/instances/${instance.id}/unload`, 'POST');
await delay(3000);
record('unload stops the engine', unload.status < 300 && engineProcs().length === 0, `status=${unload.status}; engines left=${engineProcs().length}`);
}
try { await main(); } catch (e) { record('the flow', false, e?.stack ?? e); }
host.kill();
for (let i = 0; i < 100 && host.exitCode === null; i++) await delay(100);
if (host.exitCode === null) host.kill('SIGKILL');
await delay(2000);
const left = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => (l.includes(dirs.install) || l.includes(join(app, 'host'))) && !l.includes('ps -eo'));
record('nothing of this run is left running', left.length === 0, left.join(' | ').slice(0, 300));
writeFileSync(join(root, 'e2e-result.json'), JSON.stringify({ steps, hostLogTail: hostLog.slice(-2000) }, null, 1));
console.log(failed ? 'FAILED' : 'ALL OK');
process.exit(failed ? 1 : 0);
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env bash
# Build the Strata DMG without a Finder session.
#
# Tauri's default DMG step runs an AppleScript that asks Finder to arrange the window (icon
# positions, background). Finder AppleEvents time out in a non-GUI or sandboxed context — observed
# here as `Finder got an error: AppleEvent timed out. (-1712)` — so the default path cannot be
# relied on for an automated build. The upstream `create-dmg` script already supports exactly this
# case via `--skip-jenkins`, which produces a plain, correct DMG with the app and the Applications
# drop link and no cosmetic arrangement.
#
# Usage: scripts/make-dmg.sh [output.dmg]
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DESKTOP="$(cd "$HERE/.." && pwd)"
BUNDLE="$DESKTOP/src-tauri/target/release/bundle"
APP="$BUNDLE/macos/Strata.app"
VERSION="$(grep -m1 '^version = ' "$DESKTOP/src-tauri/Cargo.toml" | cut -d'"' -f2)" # the one place the app version is written
OUT="${1:-$BUNDLE/dmg/Strata_${VERSION}_aarch64.dmg}"
if [ ! -d "$APP" ]; then
echo "error: $APP does not exist; run 'cargo tauri build --bundles app' first" >&2
exit 1
fi
WORK="$(mktemp -d -t strata-dmg)"
trap 'rm -rf "$WORK"' EXIT
# A staging folder is what create-dmg copies into the image: the app, and nothing else.
#
# The Applications drop link is created by `--app-drop-link` below. Adding one here as well makes
# create-dmg fail with "File exists", because it links into the volume it is assembling.
mkdir -p "$WORK/stage"
cp -R "$APP" "$WORK/stage/"
# Reuse Tauri's vendored create-dmg if the bundler left it behind, otherwise take it from the
# bundle cache. Building it yourself is not necessary and not expected.
SCRIPT="$BUNDLE/dmg/bundle_dmg.sh"
if [ ! -x "$SCRIPT" ]; then
echo "error: $SCRIPT not found; run 'cargo tauri build --bundles dmg' once to vendor it" >&2
exit 1
fi
mkdir -p "$(dirname "$OUT")"
rm -f "$OUT"
# --skip-jenkins: no Finder AppleScript. Everything else is the same code path Tauri uses.
"$SCRIPT" \
--volname "Strata $VERSION" \
--volicon "$BUNDLE/macos/Strata.app/Contents/Resources/Strata.icns" \
--app-drop-link 400 200 \
--skip-jenkins \
--no-internet-enable \
"$OUT" "$WORK/stage"
echo
echo "built: $OUT"
ls -lh "$OUT" | awk '{print "size: " $5}'
shasum -a 256 "$OUT"
@@ -0,0 +1,78 @@
#!/usr/bin/env node
/**
* The app and installer icon, refined from the existing Strata mark (apps/host/public/brand/strata-mark-*.svg and the current
* icons/icon.png): the same three rounded bars on the same dark tile, in the same colours. Nothing is redrawn. What changes is
* how it is cut for small sizes: at 16-48 px the bars are snapped to whole pixels and made a little bolder and wider so they
* stay crisp instead of blurring; from 64 px up the geometry is the mark's own proportions.
*
* node apps/desktop/scripts/make-icons.mjs [--out <folder>] writes icon-<size>.png for every size and icon.ico
*/
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []));
const here = dirname(fileURLToPath(import.meta.url));
const host = resolve(here, '../../host');
const out = resolve(args.out ?? join(here, '../src-tauri/icons'));
mkdirSync(out, { recursive: true });
const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
const TILE = '#161a1d', LIGHT = '#eef1f3', GREEN = '#34d399'; // the colours of the current icon.png
/** Integer geometry for the small sizes: bars on whole pixels, centred. Returns [{x,y,w,h,fill}]. */
function hinted(size) {
const bar = Math.max(2, Math.round(size * 0.14)), gap = Math.max(2, Math.round(size * 0.1)), mid = bar + 1;
const total = 2 * bar + mid + 2 * gap, top = Math.floor((size - total) / 2);
const even = w => (w % 2 === size % 2 ? w : w + 1);
const wide = even(Math.round(size * 0.5)), long = even(Math.round(size * 0.76));
return [
{ x: (size - wide) / 2, y: top, w: wide, h: bar, fill: LIGHT },
{ x: (size - long) / 2, y: top + bar + gap, w: long, h: mid, fill: GREEN },
{ x: (size - wide) / 2, y: top + bar + gap + mid + gap, w: wide, h: bar, fill: LIGHT },
];
}
/** The mark's own proportions (from icon.png at 512): bars 34% / 50% / 34% wide, 9% high, on a tile with 21.5% corners. */
function proportional(size) {
const k = size / 512;
return [
{ x: 170 * k, y: 156 * k, w: 173 * k, h: 46 * k, fill: LIGHT },
{ x: 128 * k, y: 232 * k, w: 256 * k, h: 48 * k, fill: GREEN },
{ x: 170 * k, y: 309 * k, w: 173 * k, h: 46 * k, fill: LIGHT },
];
}
function svg(size) {
const small = size <= 48;
const bars = (small ? hinted(size) : proportional(size));
const radius = small ? Math.round(size * 0.22) : size * 0.215;
const rects = bars.map(b => `<rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="${small ? Math.min(b.h / 2, 1.5 + size / 32) : b.h / 2}" fill="${b.fill}"${small ? ' shape-rendering="crispEdges"' : ''}/>`).join('');
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><rect width="${size}" height="${size}" rx="${radius}" fill="${TILE}"/>${rects}</svg>`;
}
const SIZES = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256, 512, 1024];
const browser = await chromium.launch({ executablePath: CHROME, headless: true });
const png = {};
for (const size of SIZES) {
const page = await browser.newPage({ viewport: { width: size, height: size }, deviceScaleFactor: 1 });
await page.setContent(`<!doctype html><body style="margin:0;background:transparent">${svg(size)}</body>`);
png[size] = await page.screenshot({ omitBackground: true, clip: { x: 0, y: 0, width: size, height: size } });
await page.close();
writeFileSync(join(out, `icon-${size}.png`), png[size]);
}
await browser.close();
// The .ico: one PNG image per size (16-256), the sizes Windows asks for at 100-250% scaling.
const ICO = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256];
const head = Buffer.alloc(6); head.writeUInt16LE(0, 0); head.writeUInt16LE(1, 2); head.writeUInt16LE(ICO.length, 4);
let offset = 6 + 16 * ICO.length;
const entries = [], blobs = [];
for (const size of ICO) {
const data = png[size], e = Buffer.alloc(16);
e.writeUInt8(size === 256 ? 0 : size, 0); e.writeUInt8(size === 256 ? 0 : size, 1); e.writeUInt8(0, 2); e.writeUInt8(0, 3);
e.writeUInt16LE(1, 4); e.writeUInt16LE(32, 6); e.writeUInt32LE(data.length, 8); e.writeUInt32LE(offset, 12);
offset += data.length; entries.push(e); blobs.push(data);
}
writeFileSync(join(out, 'icon.ico'), Buffer.concat([head, ...entries, ...blobs]));
writeFileSync(join(out, 'icon.png'), png[512]);
console.log('icons in', out, ICO.join(','));
@@ -0,0 +1,66 @@
#!/usr/bin/env node
/**
* The installer's pictures, drawn from the app's own design: the light surface and ink colours of the app (src/styles tokens), the
* brand lockup and mark files, GT Walsheim Bold for the words (baked into the pictures, because NSIS cannot use a web font).
*
* node apps/desktop/scripts/make-installer-images.mjs [--out <folder>] [--preview <folder>]
*
* Writes sidebar.bmp (164x314, the welcome and finish pages) and header.bmp (150x57, the other pages) as 24-bit BMPs, and with
* --preview the same as PNGs at 3x.
*/
import { spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { tmpdir } from 'node:os';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []));
const here = dirname(fileURLToPath(import.meta.url));
const host = resolve(here, '../../host');
const out = resolve(args.out ?? join(here, '../src-tauri/nsis'));
mkdirSync(out, { recursive: true });
const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
const font = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Bold.woff2')).href;
const fontMedium = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Medium.woff2')).href;
const lockup = readFileSync(join(host, 'public/brand/strata-lockup-light.svg'), 'utf8');
const mark = readFileSync(join(host, 'public/brand/strata-mark-light.svg'), 'utf8');
// the app's light tokens
const SURFACE = '#f9fafb', INK = '#171b1e', MUTED = '#5b646b', ACCENT = '#10b981', LINE = '#e3e8ea';
const css = `@font-face{font-family:GT;font-weight:700;src:url(${font})}@font-face{font-family:GT;font-weight:500;src:url(${fontMedium})}
*{box-sizing:border-box}body{margin:0;font-family:GT,'Segoe UI',sans-serif;color:${INK};background:${SURFACE}}`;
const pages = {
sidebar: { w: 164, h: 314, html: `<div style="width:164px;height:314px;padding:22px 18px;display:flex;flex-direction:column;background:linear-gradient(180deg,#f9fafb 0%,#eef6f2 100%);border-right:1px solid ${LINE}">
<div style="height:26px">${lockup.replace('<svg', '<svg style="height:26px;width:auto;display:block"')}</div>
<div style="margin-top:auto">
<div style="font-weight:700;font-size:22px;line-height:1.12;letter-spacing:-.01em">State of<br>the art.<br>At home.</div>
<div style="margin-top:10px;font-weight:500;font-size:11px;line-height:1.5;color:${MUTED}">AI on your own computer.<br>Private. Fast. Easy.</div>
<div style="margin-top:16px;height:3px;width:34px;border-radius:2px;background:${ACCENT}"></div>
</div></div>` },
header: { w: 150, h: 57, html: `<div style="width:150px;height:57px;display:flex;align-items:center;justify-content:flex-end;padding-right:12px;background:${SURFACE}">${lockup.replace('<svg', '<svg style="height:22px;width:auto;display:block"')}</div>` },
};
const browser = await chromium.launch({ executablePath: CHROME, headless: true });
const work = join(tmpdir(), 'strata-installer-images'); mkdirSync(work, { recursive: true });
for (const [name, page] of Object.entries(pages)) {
for (const scale of [1, 3]) {
const file = join(work, `${name}.html`);
writeFileSync(file, `<!doctype html><meta charset="utf-8"><style>${css}</style><body>${page.html}</body>`);
const tab = await browser.newPage({ viewport: { width: page.w, height: page.h }, deviceScaleFactor: scale });
await tab.goto(pathToFileURL(file).href);
await tab.evaluate(() => document.fonts.ready);
await tab.waitForTimeout(200);
const png = join(work, `${name}@${scale}.png`);
await tab.screenshot({ path: png, clip: { x: 0, y: 0, width: page.w, height: page.h } });
await tab.close();
if (scale === 3 && args.preview) { mkdirSync(resolve(args.preview), { recursive: true }); writeFileSync(join(resolve(args.preview), `${name}.png`), readFileSync(png)); }
}
}
await browser.close();
// 24-bit BMP, the format NSIS wants: render at 3x, shrink with a good filter
const py = `import sys\nfrom PIL import Image\nfor name in ('sidebar','header'):\n im = Image.open(sys.argv[1] + '/' + name + '@3.png').convert('RGB')\n w, h = im.width // 3, im.height // 3\n im.resize((w, h), Image.LANCZOS).save(sys.argv[2] + '/' + name + '.bmp', 'BMP')\n`;
const done = spawnSync('python', ['-c', py, work, out], { encoding: 'utf8' });
if (done.status !== 0) { console.error(done.stderr); process.exit(1); }
console.log('wrote', join(out, 'sidebar.bmp'), join(out, 'header.bmp'));
@@ -0,0 +1,85 @@
#!/usr/bin/env bash
# Write a tester's README with the checksums and sizes of the files it names, computed from the files themselves.
#
# apps/desktop/scripts/make-tester-readme.sh <template> <out.txt> --appimage <file name> --files-dir <dir> [--files-dir <dir> ...]
#
# Why: a README that carries a hand-pasted sha256 goes stale the moment the file is rebuilt (the Ubuntu 26.04 tester compared the file
# with the old build's hash). The template holds placeholders instead, and this script fills them from the real files:
# @APPIMAGE@ the AppImage's file name
# @APP_VERSION@ the app version, read from apps/desktop/src-tauri/Cargo.toml
# @SHA256:<name>@ sha256 of the file <name> found in one of the --files-dir folders
# @SIZE_GB:<name>@ its size in GB with one decimal
# @INCLUDE:<file>@ (alone on a line) the contents of <file> from the template's folder, with the same placeholders
# It refuses to write the README when a named file is missing or a placeholder is left over, so a stale or empty hash cannot ship.
# The same check is done by `--verify <readme> --files-dir <dir>`: every "<64 hex> <name>" or "sha256 <64 hex>" pair that names a file
# present in the folders must match that file.
set -euo pipefail
usage() { echo "usage: $0 <template> <out.txt> --appimage <name> --files-dir <dir> [--files-dir <dir> ...]" >&2; echo " $0 --verify <readme> --files-dir <dir> [...]" >&2; exit 2; }
VERIFY=""; TEMPLATE=""; OUT=""; APPIMAGE=""; DIRS=()
if [ "${1:-}" = "--verify" ]; then VERIFY="${2:?readme}"; shift 2; else TEMPLATE="${1:?template}"; OUT="${2:?out}"; shift 2 || usage; fi
while [ $# -gt 0 ]; do
case "$1" in
--appimage) APPIMAGE="$2"; shift 2 ;;
--files-dir) DIRS+=("$2"); shift 2 ;;
*) usage ;;
esac
done
[ ${#DIRS[@]} -gt 0 ] || usage
find_file() { local d; for d in "${DIRS[@]}"; do [ -f "$d/$1" ] && { echo "$d/$1"; return 0; }; done; return 1; }
sha_of() { sha256sum "$1" | awk '{print $1}'; }
size_gb() { awk -v b="$(stat -c %s "$1" 2>/dev/null || stat -f %z "$1")" 'BEGIN{printf "%.1f", b/1000000000}'; }
if [ -n "$VERIFY" ]; then
# every checksum in the README must be the checksum of a file that is here, and a line that names a file and carries a checksum must carry that file's checksum
hashes=""; bad=0; seen=0
for d in "${DIRS[@]}"; do for f in "$d"/*; do [ -f "$f" ] && grep -qF "$(basename "$f")" "$VERIFY" && hashes="$hashes $(sha_of "$f")"; done; done # only files the README names are hashed (a folder may hold big unrelated files)
readme_hashes="$(grep -Eo '[0-9a-f]{64}' "$VERIFY" | sort -u || true)"
for h in $readme_hashes; do
seen=$((seen + 1))
case " $hashes " in *" $h "*) ;; *) echo "STALE: the README lists $h, which is the checksum of no file in: ${DIRS[*]}" >&2; bad=$((bad + 1)) ;; esac
done
for d in "${DIRS[@]}"; do for f in "$d"/*; do
[ -f "$f" ] || continue
grep -qF "$(basename "$f")" "$VERIFY" || continue
# a line that names this file AND carries a checksum must carry this file's checksum (a sentence that merely mentions the file is fine)
line_hash="$(grep -F "$(basename "$f")" "$VERIFY" | grep -Eo '[0-9a-f]{64}' | head -1 || true)"
if [ -n "$line_hash" ] && [ "$line_hash" != "$(sha_of "$f")" ]; then
echo "STALE: $(basename "$f") is $(sha_of "$f"), the README says $line_hash" >&2; bad=$((bad + 1))
fi
done; done
echo "$seen checksum(s) in the README checked, $bad stale"
[ "$bad" = 0 ] && [ "$seen" -gt 0 ]
exit
fi
[ -n "$APPIMAGE" ] || usage
TDIR="$(cd "$(dirname "$TEMPLATE")" && pwd)"
# the app version has one source (the same file Tauri and the shell use)
APP_VERSION="$(grep -m1 '^version = ' "$TDIR/../src-tauri/Cargo.toml" | cut -d'"' -f2)"
[ -n "$APP_VERSION" ] || { echo "make-tester-readme: no version in $TDIR/../src-tauri/Cargo.toml" >&2; exit 1; }
TMP="$(mktemp)"; trap 'rm -f "$TMP" "$TMP.2"' EXIT
# includes first (one level), then the placeholders
while IFS= read -r line || [ -n "$line" ]; do
if [[ "$line" =~ ^@INCLUDE:([^@]+)@$ ]]; then tr -d '\r' < "$TDIR/${BASH_REMATCH[1]}"; else printf '%s\n' "$line"; fi
done < <(tr -d '\r' < "$TEMPLATE") | sed "s|@APPIMAGE@|$APPIMAGE|g; s|@APP_VERSION@|$APP_VERSION|g" > "$TMP"
# @SHA256:name@ and @SIZE_GB:name@
while IFS= read -r token; do
kind="${token#@}"; kind="${kind%%:*}"; name="${token#@*:}"; name="${name%@}"
f="$(find_file "$name")" || { echo "make-tester-readme: no file named $name in: ${DIRS[*]} (a README must not carry a hash it did not compute)" >&2; exit 1; }
case "$kind" in
SHA256) value="$(sha_of "$f")" ;;
SIZE_GB) value="$(size_gb "$f")" ;;
*) echo "make-tester-readme: unknown placeholder $token" >&2; exit 1 ;;
esac
# replace every occurrence of this exact token (plain text, no pattern characters)
text="$(cat "$TMP"; printf x)"; text="${text%x}"
printf '%s' "${text//"$token"/$value}" > "$TMP"
done < <(grep -Eo '@(SHA256|SIZE_GB):[^@ ]+@' "$TMP" | sort -u)
if grep -Eq '@[A-Z0-9_]+[:@]' "$TMP"; then echo "make-tester-readme: placeholders left over:" >&2; grep -En '@[A-Z0-9_]+[:@]' "$TMP" >&2; exit 1; fi
cp "$TMP" "$OUT"
echo "wrote $OUT"
@@ -0,0 +1,200 @@
#!/usr/bin/env node
/**
* Attached pictures reaching a model, end to end on a test box, through the installed app layout (packaged host + bundled Control + an engine
* component that carries strata-vision):
* 1. the model catalog marks the picture-capable models (images: true) when the picture reader is installed;
* 2. API models: a llama-server with a small picture model (--mmproj) is saved as a Custom model API; the host works out that it reads pictures,
* and a real picture goes out as image_url and is answered. A server without a picture reader, a model set "not to read pictures", and an API
* of another style each get a plain refusal (409) that says how to fix it; ticking "This model reads pictures" lets the picture through;
* 3. a local model (unless --skip-local): Download and prepare with Read pictures ON, load, and a picture through the app's own chat.
*
* node pics-e2e.mjs --install <node/ host/ control/> --components <engine components> --work <scratch> --image shapes.png \
* Also: --silent <url> (a server whose model list says nothing about pictures: ON by default), --agent (the same picture through the agent; needs a Harness)
* --vlm http://127.0.0.1:18090/v1 --vlm-model smolvlm --text-only http://127.0.0.1:18091/v1 [--skip-local --family qwen --model IQ3_XXS --data <folder> --device cpu]
*/
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs';
import { createServer } from 'node:net';
import { join, resolve } from 'node:path';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), []));
for (const need of ['install', 'components', 'work', 'image']) if (!args[need]) { console.error('missing --' + need); process.exit(2); }
const install = resolve(args.install), work = resolve(args.work), components = resolve(args.components);
const want = String(args.match ?? args.model ?? 'IQ3_XXS').toLowerCase(), contextSize = Number(args.context ?? 32768), skipLocal = args['skip-local'] === true, device = String(args.device ?? 'cpu'), family = String(args.family ?? 'qwen'), modelId = String(args.model ?? 'IQ3_XXS');
const node = join(install, 'node', 'node'), hostEntry = join(install, 'host', 'server', 'index.mjs');
const dirs = { models: join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home'), xdg: join(work, 'xdg'), appdata: join(work, 'appdata') };
for (const d of [dirs.models, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true });
const delay = ms => new Promise(r => setTimeout(r, ms));
let failed = false;
const record = (name, ok, detail = '') => { if (!ok) failed = true; console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 600) : ''}`); };
const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
const env = { ...process.env, STRATA_COMPONENTS_DIR: components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.models,
STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models-unused'), APPDATA: dirs.appdata, XDG_CONFIG_HOME: dirs.xdg, PYTHONDONTWRITEBYTECODE: '1' };
delete env.STRATA_API_KEY;
const port = await freePort();
const base = `http://127.0.0.1:${port}`;
const host = spawn(node, [hostEntry], { cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'],
env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1',
STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } });
let hostLog = '';
host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; });
const call = async (path, method = 'GET', body) => {
const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
return { status: response.status, body: await response.json().catch(() => null) };
};
const png = 'data:image/png;base64,' + readFileSync(resolve(args.image)).toString('base64');
const QUESTION = 'Name each shape in this picture with its colour, and read out any text.';
/** One chat turn through the app's own endpoint: the plain-text answer, or the refusal (status + message). */
async function chat(extra, message = QUESTION) {
const response = await fetch(base + '/api/chat/stream', { method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ message, agent: false, images: [{ url: png, name: 'shapes.png' }], ...extra }) });
if (response.status !== 200) { const b = await response.json().catch(() => ({})); return { status: response.status, message: b.error ?? b.message ?? '' }; }
let text = '', error = '';
for (const line of (await response.text()).split('\n')) {
if (!line.trim()) continue;
let f; try { f = JSON.parse(line); } catch { continue; }
if (f.type === 'error') error = f.message ?? 'error';
else if (typeof f.text === 'string' && f.type === 'delta') text += f.text;
}
return { status: 200, text, error };
}
const saveApi = async (name, baseUrl, models, protocol = 'openai-chat') => {
const existing = (await call('/api/model-providers')).body.connections.find(c => c.name === name);
return (await call('/api/model-providers', 'POST', { ...(existing ? { id: existing.id } : {}), kind: 'custom', provider: null, name, baseUrl, protocol, apiKey: '', models })).body;
};
async function readsAfter(connectionName, id, want, seconds = 20) {
for (let i = 0; i < seconds * 2; i++) {
const c = (await call('/api/model-providers')).body.connections.find(x => x.name === connectionName);
const m = c?.models.find(x => x.id === id);
if (m && m.reads === want) return { c, m };
await delay(500);
}
const c = (await call('/api/model-providers')).body.connections.find(x => x.name === connectionName);
return { c, m: c?.models.find(x => x.id === id) };
}
async function waitJob(id, seconds) {
let last = '';
for (let i = 0; i < seconds * 2; i++) {
const state = (await call('/api/native')).body;
const job = state.jobs.find(j => j.id === id);
if (job && job.summary !== last) { last = job.summary; console.log(' ... ' + String(last).slice(0, 120)); }
if (job && job.state !== 'running') return { job, state };
await delay(500);
}
throw new Error('operation did not finish');
}
const names = low => /(red|blue|green|circle|square|triangle|strata|42)/.test(low);
async function main() {
let up = false;
for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { /* not yet */ } if (!up) await delay(150); }
record('host healthy', up, up ? base : hostLog.slice(-500));
if (!up) return;
// ---- 1. the catalog
const packages = existsSync(join(components, 'engine')) ? readdirSync(join(components, 'engine')) : [];
const reader = packages.some(p => existsSync(join(components, 'engine', p, 'strata-vision')));
const native = (await call('/api/native?refresh=1')).body;
record('the engine component carries the picture reader and the host knows it (visionReader)', reader && native.visionReader === true, `component=${reader} host=${native.visionReader}`);
const rows = (native.catalog?.families ?? []).flatMap(f => (f.sizes ?? []).map(s => ({ family: f.title ?? f.family, size: s.id, images: s.images, capable: s.imagesCapable })));
console.log(' catalog (family / size / images / imagesCapable):');
for (const r of rows) console.log(` ${String(r.family).padEnd(26)} ${String(r.size).padEnd(30)} images=${r.images} capable=${r.capable}`);
record('some models in the catalog read pictures', rows.some(r => r.images === true), `${rows.filter(r => r.images).length} of ${rows.length}`);
record('every picture-capable model reads pictures when the reader is installed', rows.every(r => r.capable === r.images), '');
const flash = rows.filter(r => /flash-next/i.test(`${r.family} ${r.size}`) && !/gyro|qad/i.test(`${r.family} ${r.size}`));
record('the Qwen3.8-Flash-Next models are marked images: true', flash.length > 0 && flash.every(r => r.images === true), flash.map(r => r.size + '=' + r.images).join(' '));
// ---- 2. API models
if (args.vlm) {
const smol = args['vlm-model'] ?? 'smolvlm';
await saveApi('Small picture model', args.vlm, [{ id: smol, name: 'SmolVLM' }]);
const found = await readsAfter('Small picture model', smol, true);
record('the host works out that the llama-server reads pictures (no tick needed)', found.m?.reads === true, JSON.stringify(found.m));
const conn = found.c;
const sent = await chat({ remoteModel: { connectionId: conn?.id, modelId: smol } });
console.log(` answer from the API model: ${JSON.stringify((sent.text ?? sent.message ?? '').slice(0, 300))}`);
record('the picture goes to the API model and is answered', sent.status === 200 && !sent.error && (sent.text ?? '').trim().length > 0 && names((sent.text ?? '').toLowerCase()), `status=${sent.status} err=${sent.error ?? ''}`);
if (args['text-only']) {
await saveApi('Text only server', args['text-only'], [{ id: 'plain', name: 'Plain model' }]);
const t = await readsAfter('Text only server', 'plain', false);
record('a server without a picture reader is known not to read pictures', t.m?.reads === false, JSON.stringify(t.m));
const refused = await chat({ remoteModel: { connectionId: t.c.id, modelId: 'plain' } });
console.log(` refusal: ${JSON.stringify(refused.message)}`);
record('a picture for it is refused in plain words that say how to fix it', refused.status === 409 && /Read pictures with this model/.test(refused.message ?? '') && /Settings/.test(refused.message ?? ''), `${refused.status}`);
const ticked = await saveApi('Text only server', args['text-only'], [{ id: 'plain', name: 'Plain model', vision: true }]);
const after = (await call('/api/model-providers')).body.connections.find(x => x.name === 'Text only server');
record('ticking "Read pictures with this model" is saved and makes the model read pictures', after?.models[0]?.vision === true && after?.models[0]?.reads === true, JSON.stringify(after?.models[0]));
const through = await chat({ remoteModel: { connectionId: after.id, modelId: 'plain' } });
record('with the tick the picture is sent on (the server itself decides what to do with it)', through.status === 200 && (through.error ?? '') !== '' ? /turn off/.test(through.error) : through.status === 200, `${through.status} ${through.message ?? through.error ?? ''}`);
}
await saveApi('Small picture model', args.vlm, [{ id: smol, name: 'SmolVLM', vision: false }]);
const off = await readsAfter('Small picture model', smol, false);
const notRead = await chat({ remoteModel: { connectionId: off.c.id, modelId: smol } });
record('a model switched OFF refuses pictures and says where to turn them on again', notRead.status === 409 && /not to read pictures/.test(notRead.message ?? '') && /Settings/.test(notRead.message ?? ''), `${notRead.status} ${notRead.message ?? ''}`);
await saveApi('Small picture model', args.vlm, [{ id: smol, name: 'SmolVLM', vision: null }]);
// unknown is ON by default: a server whose list and /props say nothing is sent the picture
if (args.silent) {
await saveApi('Silent server', args.silent, [{ id: 'quiet', name: 'Quiet model' }]);
const q = await readsAfter('Silent server', 'quiet', true, 8);
record('a server that says nothing about pictures is ON by default', q.m?.reads === true && q.m?.vision === null, JSON.stringify(q.m));
const sentQuiet = await chat({ remoteModel: { connectionId: q.c.id, modelId: 'quiet' } });
record('and the picture is sent to it (not refused)', sentQuiet.status === 200, `${sentQuiet.status} ${sentQuiet.message ?? sentQuiet.error ?? ''}`);
}
await saveApi('Other style', 'https://api.anthropic.com/v1', [{ id: 'claude-x', name: 'Claude' }], 'anthropic');
const other = (await call('/api/model-providers')).body.connections.find(x => x.name === 'Other style');
const style = await chat({ remoteModel: { connectionId: other.id, modelId: 'claude-x' } });
console.log(` other style: ${JSON.stringify(style.message)}`);
record('an API of another style says plainly why pictures stay in the preview', style.status === 409 && /OpenAI/.test(style.message ?? ''), `${style.status}`);
}
if (skipLocal) return;
// ---- 3. a local model
const values = { family, model: modelId, context: contextSize, vision: 'yes', loadVision: device, ...(args.data ? { data_dir: resolve(args.data) } : {}) };
const started = await call('/api/native/operations', 'POST', { kind: 'install', args: values });
record('the install operation starts', started.status === 200 || started.status === 202, JSON.stringify(started.body).slice(0, 200));
const done = await waitJob(started.body.id, 3600);
record('Download and prepare finishes', done.job.state === 'done', `${done.job.state} ${done.job.error ?? done.job.summary}`);
const refreshed = (await call('/api/native?refresh=1')).body;
const model = refreshed.installed?.models?.find(m => [m.id, m.model, m.tag].some(x => String(x ?? '').toLowerCase() === want));
record('the model is prepared with its picture reader', !!model?.visionPrepared, JSON.stringify({ ready: model?.ready, visionPrepared: model?.visionPrepared }));
const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model: model?.model ?? want } });
const loaded = await waitJob(load.body.id, 900);
const instance = loaded.state.instances[0];
record('the model loads with the picture reader', loaded.job.state === 'done' && instance?.status === 'ready' && instance?.vision === true, `${loaded.job.state} ${loaded.job.error ?? ''} vision=${instance?.vision}`);
record('the model loaded with pictures ON without being asked per load (default)', instance?.vision === true, '');
const t0 = Date.now();
let local = { status: 0 };
for (let i = 0; i < 2 && !(local.text ?? '').trim(); i++) local = await chat({ nativeModelId: instance?.id, maxTokens: 4096 });
console.log(` answer from the local model (${Math.round((Date.now() - t0) / 1000)} s): ${JSON.stringify((local.text ?? local.message ?? '').slice(0, 300))}`);
const low = (local.text ?? '').toLowerCase();
record('the local model answers about the picture (names the shapes)', local.status === 200 && /red|circle/.test(low) && /blue|square/.test(low) && /green|triangle/.test(low), `status=${local.status} err=${local.error ?? ''}`);
record('the local model reads STRATA 42', low.includes('42'));
// the same picture through the agent (the Harness route must declare image input: the "does not declare image input" error of the tester)
if (args.agent) { // needs a Harness beside the host (the installed layout has one; a bare test box does not)
const t1 = Date.now(); let a = { status: 0 };
for (let i = 0; i < 2 && !/red|circle|square|triangle/.test((a.text ?? '').toLowerCase()); i++) a = await chat({ nativeModelId: instance?.id, agent: true, sessionId: 'pics-agent-' + i, mode: 'plan', maxTokens: 4096 });
console.log(` answer through the agent (${Math.round((Date.now() - t1) / 1000)} s): ${JSON.stringify((a.text ?? a.message ?? '').slice(0, 300))}`);
record('the agent route reads the picture too', a.status === 200 && /red|circle|square|triangle/.test((a.text ?? '').toLowerCase()) && !/does not declare image input/.test(a.text ?? ''), `status=${a.status} err=${a.error ?? ''}`);
}
// OFF: loading with Read pictures off refuses a picture in plain words and says what to do
await call(`/api/native/instances/${instance?.id}/unload`, 'POST', {});
const loadOff = await call('/api/native/operations', 'POST', { kind: 'load', args: { model: model?.model ?? want, vision: 'no' } });
const loadedOff = await waitJob(loadOff.body.id, 900);
const off2 = loadedOff.state.instances[0];
record('loaded with Read pictures OFF', loadedOff.job.state === 'done' && off2?.vision === false, `${loadedOff.job.state} vision=${off2?.vision}`);
const refusedLocal = await chat({ nativeModelId: off2?.id, maxTokens: 64 });
console.log(` refusal: ${JSON.stringify(refusedLocal.message)}`);
record('a picture for the OFF model is refused with a next step', refusedLocal.status === 409 && /Read pictures/.test(refusedLocal.message ?? '') && /Models/.test(refusedLocal.message ?? ''), `${refusedLocal.status}`);
const unloaded = await call(`/api/native/instances/${off2?.id}/unload`, 'POST', {});
record('unload', unloaded.status === 200, unloaded.status);
}
try { await main(); } catch (e) { record('run', false, e.stack ?? e); }
host.kill();
await delay(1500);
console.log(failed ? 'PICS-E2E FAIL' : 'PICS-E2E PASS');
process.exit(failed ? 1 : 0);
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Put the bundled payloads back to the bytes they were staged with, inside a finished AppImage.
#
# apps/desktop/scripts/repack-appimage.sh <in.AppImage> <out.AppImage> [--resources <src-tauri/resources>] [--check]
#
# Why: Tauri hands the AppDir to linuxdeploy, which treats every ELF file under usr/lib as a library to fix up: it rewrites the RPATH of
# the engine (strata, libstrata_kq.so, libcudart), of the bundled Python and Node and of the Harness's native modules. The files then no
# longer match the SHA-256 and size their manifests list (engine-component.json), so the host refuses the bundled engine, and the
# installer's own integrity promise ("what we staged is what runs") is broken. This script unpacks the AppImage, copies the staged
# folders (control, harness, node, engine-bundle) over the AppDir byte for byte, and packs it again with the same runtime.
#
# --check does not write anything: it lists every engine-bundle file whose bytes differ from the manifest in the AppImage.
set -euo pipefail
IN="$(realpath "${1:?in.AppImage}")"; OUT="${2:-}"
RES="$(cd "$(dirname "${BASH_SOURCE[0]}")/../src-tauri/resources" && pwd)"
CHECK=0
shift 2 || true
while [ $# -gt 0 ]; do
case "$1" in
--resources) RES="$(cd "$2" && pwd)"; shift 2 ;;
--check) CHECK=1; shift ;;
*) echo "unknown option $1" >&2; exit 2 ;;
esac
done
OFFSET="$("$IN" --appimage-offset)"
WORK="$(mktemp -d -t strata-repack.XXXXXX)"
trap 'rm -rf "$WORK"' EXIT
unsquashfs -no-progress -o "$OFFSET" -d "$WORK/AppDir" "$IN" >/dev/null
# the product folder under usr/lib (Tauri names it after productName)
LIB="$(find "$WORK/AppDir/usr/lib" -maxdepth 2 -type d -name engine-bundle -printf '%h\n' | head -1)"
[ -n "$LIB" ] || LIB="$(find "$WORK/AppDir/usr/lib" -maxdepth 2 -type d -name control -printf '%h\n' | head -1)"
[ -n "$LIB" ] || { echo "no Strata resource folder in the AppImage" >&2; exit 1; }
if [ "$CHECK" = 1 ]; then
bad=0
while IFS= read -r f; do
rel="${f#$RES/}"
if ! cmp -s "$f" "$LIB/$rel"; then echo "differs: $rel"; bad=$((bad + 1)); fi
done < <(find "$RES/engine-bundle" "$RES/node" -type f ! -name .gitignore)
echo "$bad file(s) differ from what was staged"
[ "$bad" = 0 ]
exit
fi
[ -n "$OUT" ] || { echo "give out.AppImage" >&2; exit 2; }
for d in control harness node engine-bundle; do
[ -d "$RES/$d" ] || continue
rsync -aL --checksum --delete --exclude .gitignore "$RES/$d/" "$LIB/$d/"
done
# The launcher records the environment the AppImage was started from, before its own hooks add the AppImage's libraries and GTK/GIO
# settings (LD_LIBRARY_PATH, GTK_*, XDG_DATA_DIRS ...). The host gives it back to every program that is not Strata's own (zenity,
# kdialog, xdg-open, the assistant's shell): apps/host/server/external-env.mjs. Without it a system program loads the AppImage's libssl
# and dies ("OPENSSL_3.2.0 not found"). The line goes right after `this_dir=...`, ahead of every hook.
if ! grep -q STRATA_ORIGINAL_ENV "$WORK/AppDir/AppRun"; then
sed -i '/^this_dir=/a # Strata: the environment this AppImage was started from (given back to programs that are not Strata'"'"'s own)\nexport STRATA_ORIGINAL_ENV="$(env -0 | base64 -w0)"' "$WORK/AppDir/AppRun"
grep -q STRATA_ORIGINAL_ENV "$WORK/AppDir/AppRun" || { echo "could not add the environment record to AppRun" >&2; exit 1; }
fi
mksquashfs "$WORK/AppDir" "$WORK/app.squashfs" -root-owned -noappend -comp zstd -b 131072 -no-progress >/dev/null
head -c "$OFFSET" "$IN" > "$OUT"
cat "$WORK/app.squashfs" >> "$OUT"
chmod +x "$OUT"
# The checksum is computed here, from the finished file, every time: a README or a note must take it from this file
# (apps/desktop/scripts/make-tester-readme.sh) and never from an older build.
( cd "$(dirname "$OUT")" && sha256sum "$(basename "$OUT")" > "$(basename "$OUT").sha256" )
echo "repacked: $OUT ($(stat -c %s "$OUT") bytes)"
cat "$OUT.sha256"
@@ -0,0 +1,202 @@
#!/usr/bin/env python3
"""Stage the Control component the installer ships: src-tauri/resources/control.
python apps/desktop/scripts/stage-control.py # build the terminal bundle, stage it
python apps/desktop/scripts/stage-control.py --archive X.zip # stage an archive you already built
python apps/desktop/scripts/stage-control.py --wheelhouse DIR # build with no network (wheels from DIR)
python apps/desktop/scripts/stage-control.py --check # verify what is staged
What lands in `control/`: the pinned CPython 3.12.15 (python-build-standalone, digest-checked), the hash-locked wheels
(`packaging/locks/runtime-<target>-cp312.txt`, installed with --require-hashes at build time), strata_control,
strata_cli, serve, tools/strata_tokenizer.py + gguf_reader.py, and BUNDLE.json (version, interpreter and lock digests,
the digest of the archive it came from). It is the same bundle as the Terminal archive (packaging/package_terminal.py):
one Python runtime-core for both products. The app then never runs pip, npm, git or a compiler to start or serve.
This script is a BUILD step. It may download the interpreter and the wheels (verified); the app never does.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import shutil
import subprocess
import sys
import tempfile
import zipfile
import tarfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
OUT = HERE.parent / "src-tauri" / "resources" / "control"
sys.path.insert(0, str(ROOT / "packaging"))
import package_terminal as pt # noqa: E402
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1 << 20), b""):
digest.update(block)
return digest.hexdigest()
def build_archive(work: Path, wheelhouse: str | None) -> Path:
command = [sys.executable, str(ROOT / "packaging" / "package_terminal.py"), "--out", str(work)]
if wheelhouse:
command += ["--wheelhouse", wheelhouse]
subprocess.run(command, check=True, cwd=str(ROOT))
archives = sorted(work.glob("strata-terminal-*.zip")) + sorted(work.glob("strata-terminal-*.tar.gz"))
if len(archives) != 1:
raise SystemExit(f"expected one archive in {work}, found {archives}")
return archives[0]
def extract(archive: Path, destination: Path) -> Path:
"""Unpack the archive; returns the folder that holds python/ and strata.py."""
scratch = destination.parent / (destination.name + ".incoming")
shutil.rmtree(scratch, ignore_errors=True)
scratch.mkdir(parents=True)
if archive.name.endswith(".zip"):
with zipfile.ZipFile(archive) as zf:
for member in zf.namelist():
target = (scratch / member).resolve()
if scratch.resolve() not in target.parents and target != scratch.resolve():
raise SystemExit(f"unsafe member in {archive.name}: {member}")
zf.extractall(scratch)
else:
with tarfile.open(archive) as tf:
tf.extractall(scratch, filter="data")
(inner,) = [p for p in scratch.iterdir() if p.is_dir()]
return inner
#: What the app's installer needs on top of the Terminal bundle: the model catalog, GPU probe and install job. The list and the copy
#: live in packaging/package_terminal.py (the Terminal archive carries the same files, for `strata launch`).
INSTALLER_FILES, INSTALLER_TOOLS, INSTALLER_DATA = pt.INSTALLER_FILES, pt.INSTALLER_TOOLS, pt.INSTALLER_DATA
local_imports = pt.local_imports
def add_installer(folder: Path) -> dict:
"""Copy the installer's files from the source tree into the staged Control (after the Terminal bundle is in place)."""
return pt.add_installer(folder, ROOT)
#: What the other names of the interpreter become: Tauri copies a symlink as a full copy of its target, so `python`, `python3` and
#: `python3.12` in a bundle would be three real files (68 MB each on Linux). Only `python3.12` stays the real one.
#: The launcher runs inside the AppImage's environment (LD_LIBRARY_PATH holds the bundled libraries), where an external program such as
#: `dirname` can fail to start (Ubuntu 26.04's coreutils: "libsystemd.so.0: version LIBSYSTEMD_254 not found"), so it uses shell built-ins
#: only. The first version called `dirname`; that left the folder empty and "Control stopped" on such a computer.
LAUNCHER = """#!/bin/sh
# Strata: this name only starts the real interpreter beside it (the bundle keeps one copy, not one per name). Built-ins only: no dirname.
case "$0" in */*) dir=${0%%/*} ;; *) dir=. ;; esac
here=$(cd "$dir" && pwd)
exec "$here/%s" "$@"
"""
def dedupe_python(folder: Path) -> list[str]:
"""Make every other name of the interpreter in `python/bin` a small launcher of the real binary (Linux and macOS; Windows has one
python.exe). A symlink would not survive the bundling, and a plain copy is what costs the space. Returns the names changed."""
bindir = folder / "python" / "bin"
if not bindir.is_dir():
return []
real = bindir / f"python{pt.PYTHON_VERSION.rsplit('.', 1)[0]}"
if not real.exists():
return []
if real.is_symlink(): # the real file is a link itself: make the target the real one
target = real.resolve()
real.unlink()
shutil.move(str(target), str(real))
changed = []
for name in ("python", "python3"):
path = bindir / name
if not (path.is_symlink() or (path.is_file() and path.stat().st_size == real.stat().st_size)):
continue
path.unlink()
path.write_bytes((LAUNCHER % real.name).encode("utf-8"))
path.chmod(0o755)
changed.append(name)
return changed
def write_bundle_record(folder: Path, archive: Path) -> dict:
manifest_path = archive.with_name(archive.name.rsplit(".", 2 if archive.name.endswith(".tar.gz") else 1)[0] + ".manifest.json")
manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else {}
target = manifest.get("target") or pt.host_target()
record = {
"schema_version": 1, "component": "strata-control",
"version": (folder / "VERSION").read_text(encoding="utf-8").strip(),
"target": target,
"python": {"version": pt.PYTHON_VERSION, "build": pt.PBS_RELEASE, "sha256": pt.PYTHON_PINS[target]["sha256"]},
"lock": manifest.get("lock"),
"installed": manifest.get("installed"),
"archive": {"name": archive.name, "sha256": sha256(archive), "bytes": archive.stat().st_size},
"acquires_at_runtime": False,
"installer": add_installer(folder),
}
(folder / "BUNDLE.json").write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
return record
def check(folder: Path) -> int:
target = pt.host_target()
python = folder / pt.PYTHON_PINS[target]["python"]
problems = []
for need in (python, folder / "strata.py", folder / "strata_control", folder / "serve" / "server.py", folder / "BUNDLE.json",
folder / "setup.py", folder / "tools" / "strata_mcp.py", folder / "tools" / "iq_pack.py", folder / "data" / "draft_vocab.bin"):
if not need.exists():
problems.append(f"missing {need}")
if problems:
print("\n".join(problems), file=sys.stderr)
return 1
env = {"PYTHONNOUSERSITE": "1", "PYTHONDONTWRITEBYTECODE": "1", "STRATA_NO_ACQUIRE": "1", "SYSTEMROOT": __import__("os").environ.get("SYSTEMROOT", "")}
done = subprocess.run([str(python), str(folder / "strata.py"), "--version"], capture_output=True, text=True, env=env,
cwd=str(folder), timeout=60)
print(done.stdout.strip() or done.stderr.strip())
if done.returncode:
return done.returncode
# the installer: its catalog, a GPU probe and its imports work on the bundled Python alone (nothing is installed or fetched)
probe = ("import sys; sys.path.insert(0, %r); import importlib.util as u; s = u.spec_from_file_location('s', %r); m = u.module_from_spec(s); "
"s.loader.exec_module(m); import iq_pack, strata_pack, pack_index, mtp_fetch; "
"print('installer ok: %%d models, %%d families' %% (len(m.MODELS), len(m.FAMILIES)))") % (str(folder / "tools"), str(folder / "setup.py"))
env["STRATA_CONTROL_INSTALL"] = "1"
again = subprocess.run([str(python), "-c", probe], capture_output=True, text=True, env=env, cwd=str(folder), timeout=120)
print(again.stdout.strip() or again.stderr.strip()[-600:])
return again.returncode
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--archive", type=Path, help="stage this terminal archive instead of building one")
ap.add_argument("--wheelhouse", help="build with the wheels in this folder (no network)")
ap.add_argument("--out", type=Path, default=OUT)
ap.add_argument("--check", action="store_true", help="verify the staged component and exit")
a = ap.parse_args()
if a.check:
return check(a.out)
with tempfile.TemporaryDirectory(prefix="strata-stage-control-") as work:
archive = a.archive.resolve() if a.archive else build_archive(Path(work), a.wheelhouse)
keep = [p for p in a.out.iterdir() if p.name == ".gitignore"] if a.out.exists() else []
if a.out.exists():
for child in a.out.iterdir():
if child.name != ".gitignore":
shutil.rmtree(child, ignore_errors=True) if child.is_dir() else child.unlink()
a.out.mkdir(parents=True, exist_ok=True)
inner = extract(archive, a.out)
record = write_bundle_record(inner, archive)
for child in inner.iterdir():
shutil.move(str(child), str(a.out / child.name))
shutil.rmtree(inner.parent, ignore_errors=True)
launched = dedupe_python(a.out)
if launched:
print(f"python: {', '.join(launched)} are launchers of the one real interpreter")
print(f"staged {record['component']} {record['version']} ({record['target']}) into {a.out}")
return check(a.out)
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,176 @@
#!/usr/bin/env node
/**
* Stage the DeepSeek Harness (pinned, MIT) as the installer's `harness/` folder: a pruned PRODUCTION install, built at
* build time, so nothing is fetched or compiled on the person's PC.
*
* node apps/desktop/scripts/stage-harness.mjs --src <built Harness checkout> [--out apps/desktop/src-tauri/resources/harness]
*
* <built Harness checkout> is a clone of the pinned commit after `pnpm install --frozen-lockfile` and `pnpm run build:artifacts`
* (see phaseA-tests/notes-split-s4a.md, step 1). The script never touches it: it runs `pnpm deploy --legacy --prod` into
* the output folder, removes what a running Harness does not read (sources, tests, maps, docs, other operating systems'
* prebuilt binaries, the LibreOffice document converter and the speech engine, which the app does not use), keeps the
* MIT licence and third-party notices, writes BUNDLE.json, and finally boots the staged copy once as proof.
*
* The host finds the result at `<install>/harness` (server/agent/harness-runtime.mjs), or in the component folder.
*/
import { spawnSync } from 'node:child_process';
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { join, relative, resolve, sep } from 'node:path';
import { createHash } from 'node:crypto';
import { flattenPnpm } from './flatten-pnpm.mjs';
import { isOtherOsBinaryFolder, missingHarnessImports } from './harness-prune.mjs';
const args = process.argv.slice(2);
const opt = (name, fallback) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : fallback; };
const src = resolve(opt('src', process.env.STRATA_HARNESS_SRC ?? ''));
const out = resolve(opt('out', join(import.meta.dirname, '..', 'src-tauri', 'resources', 'harness')));
if (!opt('src', process.env.STRATA_HARNESS_SRC) || !existsSync(join(src, 'apps', 'cli', 'lib', 'bin.js'))) {
console.error('Give --src <a built Harness checkout> (apps/cli/lib/bin.js must exist).');
process.exit(2);
}
const platform = process.platform;
const run = (cmd, argv, cwd, extra = {}) => {
const r = spawnSync(cmd, argv, { cwd, stdio: 'inherit', shell: false, ...extra });
if (r.status !== 0) { console.error(`${cmd} ${argv.join(' ')} failed (${r.status ?? r.error})`); process.exit(1); }
};
// The output folder in the repo carries a .gitignore that keeps the staged files out of git: keep it across the clean-up.
const keepIgnore = existsSync(join(out, '.gitignore')) ? readFileSync(join(out, '.gitignore')) : null;
rmSync(out, { recursive: true, force: true });
mkdirSync(out, { recursive: true });
const pnpm = platform === 'win32' ? ['corepack.cmd', ['pnpm']] : ['corepack', ['pnpm']];
run(pnpm[0], [...pnpm[1], 'deploy', '--legacy', '--prod', '--filter', '@deepseek-ai/dsh', out], src, { shell: platform === 'win32' });
// --- peers -------------------------------------------------------------------------------------------------------------
// `pnpm deploy --prod` leaves out peer dependencies, but the Harness loads some of them by name at run time (for example the
// plugin-group helper that app-boot imports). Walk the installed packages; every dependency or peer that cannot be
// resolved from the output is copied from the source checkout's own node_modules, and its own requirements after it.
function packageJsonsUnder(dir, out2 = []) {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, e.name);
if (e.isSymbolicLink()) continue;
if (e.isDirectory()) packageJsonsUnder(p, out2);
else if (e.name === 'package.json' && p.includes(`${sep}node_modules${sep}`)) out2.push(p);
}
return out2;
}
function requirementsOf(file) {
try { const j = JSON.parse(readFileSync(file, 'utf8')); return [...Object.keys(j.dependencies ?? {}), ...Object.keys(j.peerDependencies ?? {}), ...Object.keys(j.optionalDependencies ?? {})]; } catch { return []; }
}
/** The checkout's own workspace packages (packages/**, vendor/*, apps/*) by name: where a peer that is one of ours comes from. */
const workspace = new Map();
function indexWorkspace(dir, depth = 0) {
if (depth > 4) return;
for (const e of readdirSync(dir, { withFileTypes: true })) {
if (!e.isDirectory() || e.isSymbolicLink() || e.name === 'node_modules' || e.name.startsWith('.')) continue;
const p = join(dir, e.name);
const manifest = join(p, 'package.json');
if (existsSync(manifest)) { try { workspace.set(JSON.parse(readFileSync(manifest, 'utf8')).name, p); } catch { /* not a package */ } }
indexWorkspace(p, depth + 1);
}
}
for (const top of ['packages', 'vendor', 'apps']) if (existsSync(join(src, top))) indexWorkspace(join(src, top));
const resolvable = name => existsSync(join(out, 'node_modules', ...name.split('/')));
const queue = [...new Set(packageJsonsUnder(join(out, 'node_modules')).flatMap(requirementsOf))].filter(n => !resolvable(n));
const added = [];
while (queue.length) {
const name = queue.shift();
if (resolvable(name)) continue;
const from = workspace.get(name) ?? join(src, 'node_modules', ...name.split('/'));
if (!existsSync(from)) continue; // an optional package for another platform, or not installed in the source: nothing to copy
const to = join(out, 'node_modules', ...name.split('/'));
mkdirSync(join(to, '..'), { recursive: true });
const realFrom = realpathSync(from);
cpSync(realFrom, to, { recursive: true, dereference: true, filter: f => !relative(realFrom, f).split(sep).includes('node_modules') });
added.push(name);
queue.push(...requirementsOf(join(to, 'package.json')).filter(n => !resolvable(n)));
}
if (added.length) console.log(`peer packages added: ${added.join(', ')}`);
// --- the browser tool server ---------------------------------------------------------------------------------------------
// Settings -> Tools can switch on a browser the assistant drives (Playwright's MCP server, Apache-2.0) on the person's own Chrome or Edge,
// so no browser is downloaded. The server and the two Playwright libraries it needs are not part of the Harness's production closure;
// they are copied from the source checkout's package store (~20 MB) and the host starts it with Node (server/agent/browser-probe.mjs).
const pnpmStore = join(src, 'node_modules', '.pnpm');
function storePackage(name, version) {
if (!existsSync(pnpmStore)) return null;
const prefix = `${name.replace('/', '+')}@`;
const hit = readdirSync(pnpmStore).filter(n => n.startsWith(prefix) && (!version || n === `${prefix}${version}` || n.startsWith(`${prefix}${version}_`))).sort().at(-1);
const dir = hit ? join(pnpmStore, hit, 'node_modules', ...name.split('/')) : null;
return dir && existsSync(dir) ? dir : null;
}
const browserDir = storePackage('@playwright/mcp');
if (browserDir) {
const wanted = JSON.parse(readFileSync(join(browserDir, 'package.json'), 'utf8')).dependencies ?? {};
const parts = [['@playwright/mcp', browserDir], ...['playwright', 'playwright-core'].map(n => [n, storePackage(n, wanted[n])])];
if (parts.every(([, dir]) => dir)) {
for (const [name, dir] of parts) {
const to = join(out, 'node_modules', ...name.split('/'));
mkdirSync(join(to, '..'), { recursive: true });
cpSync(realpathSync(dir), to, { recursive: true, dereference: true, filter: f => !relative(dir, f).split(sep).includes('node_modules') });
}
console.log(`browser tool server added: ${parts.map(([n]) => n).join(', ')}`);
} else console.log('browser tool server NOT added: Playwright libraries missing from the package store');
} else console.log('browser tool server NOT added: @playwright/mcp is not in the source checkout');
// --- one real folder per package, no links -------------------------------------------------------------------------------
// The installer copies files; pnpm's layout is links. See flatten-pnpm.mjs. The two packages the app does not use are never copied.
const flat = flattenPnpm(out, { skip: /libreoffice-kit|sherpa-onnx/i });
console.log(`flattened: ${flat.packages} placed (${flat.nested} nested for a second version)`);
// --- prune ------------------------------------------------------------------------------------------------------------
/** Whole packages the app never loads: office-document conversion (hundreds of MB) and speech input. */
const DROP_PACKAGES = [/libreoffice-kit/i, /sherpa-onnx/i];
/** Only when sitting directly in a package's root (a library may have a runtime folder called `doc`, e.g. yaml/dist/doc). */
const DROP_DIRS = new Set(['test', 'tests', '__tests__', 'docs', 'website', 'benchmarks', 'examples', '.github']);
const DROP_FILES = /\.(map|md|markdown|pdb|tsbuildinfo)$/i;
/** Licences and notices travel with the files they cover. */
const KEEP_FILES = /^(LICENSE|LICENCE|NOTICE|THIRD_PARTY)/i;
let removed = 0;
function prune(dir) {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, e.name);
if (e.isSymbolicLink()) continue;
if (e.isDirectory()) {
const inLib = p.split(sep).includes('lib');
if ((DROP_DIRS.has(e.name) && !inLib && existsSync(join(dir, 'package.json'))) || DROP_PACKAGES.some(r => r.test(e.name)) || isOtherOsBinaryFolder(platform, e.name, p)) {
rmSync(p, { recursive: true, force: true }); removed++; continue;
}
prune(p);
} else if (DROP_FILES.test(e.name) && !KEEP_FILES.test(e.name)) {
rmSync(p, { force: true }); removed++;
}
}
}
prune(out);
// --- licence: the MIT text and the third-party notices travel with the files ---------------------------------------------
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
if (existsSync(join(src, name))) cpSync(join(src, name), join(out, name));
}
const cli = JSON.parse(readFileSync(join(out, 'package.json'), 'utf8'));
let commit = process.env.STRATA_HARNESS_COMMIT ?? null;
if (!commit) { const r = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: src, encoding: 'utf8' }); if (r.status === 0) commit = r.stdout.trim(); }
function size(dir) { let t = 0, n = 0; for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) { const s = size(p); t += s.bytes; n += s.files; } else if (e.isFile()) { t += statSync(p).size; n++; } } return { bytes: t, files: n }; }
const total = size(out);
writeFileSync(join(out, 'BUNDLE.json'), JSON.stringify({
component: 'deepseek-harness', version: cli.version, commit, license: 'MIT', platform, node: process.version,
bytes: total.bytes, files: total.files, entry: 'apps/cli/lib/bin.js', builtAt: new Date().toISOString(),
note: 'Pruned production install (pnpm deploy --prod). No package manager runs on the user\'s PC.',
}, null, 2));
if (keepIgnore) writeFileSync(join(out, '.gitignore'), keepIgnore);
// --- proof 1: nothing the Harness imports by name was pruned ------------------------------------------------------------
// (2026-10-17: the other-OS rule once removed @deepseek-ai/dsh-win32-process, which every platform imports; Linux/Mac agent chats died.)
const lost = missingHarnessImports(out);
if (lost.length) { console.error(['staged Harness is missing imported packages:', ...lost.map(l => ` ${l.from} -> ${l.missing}`)].join(String.fromCharCode(10))); process.exit(1); }
console.log('import check: every @deepseek-ai package the Harness imports is staged');
// --- proof 2: the staged copy answers --version and boots the web profile once ----------------------------------------
const bin = join(out, 'apps', 'cli', 'lib', 'bin.js');
const entry = existsSync(bin) ? bin : join(out, 'lib', 'bin.js');
const v = spawnSync(process.execPath, [entry, '--version'], { encoding: 'utf8' });
if (v.status !== 0) { console.error('staged Harness does not start:', v.stderr); process.exit(1); }
console.log(`staged ${cli.version} (${commit?.slice(0, 8) ?? 'no commit'}) in ${out}: ${(total.bytes / 1048576).toFixed(0)} MiB, ${total.files} files, ${removed} pruned items; --version -> ${v.stdout.trim()}`);
console.log(`sha256(BUNDLE.json)=${createHash('sha256').update(readFileSync(join(out, 'BUNDLE.json'))).digest('hex')}`);
@@ -0,0 +1,721 @@
#!/usr/bin/env node
/**
* Headless UI flows of the installed app against a packaged host with a FAKE installer and a FAKE engine (nothing is
* downloaded, no real engine runs; the real Control starts the fake engine through the owner runtime):
*
* node apps/desktop/scripts/ui-flows.mjs [--control <staged control>] [--node <node.exe>] [--shots <dir>] [--only download,models,tune,fail,theme]
*
* download the onboarding download: ONE combined bar over both files, an ETA in minutes left of Stop, Finish later closes the
* pop-up with the download still running, the Models screen shows the same progress, Stop stops it
* models an installed model is the one Models selects and loads, without a download pop-up
* tune the tuning step offers no picture reading, tunes, writes a RAM budget for "leave 20%", opens chat; reading size
* fail an engine that stops while loading: the error is in words and the pop-up does not scroll
* theme the app follows the system light/dark setting
* Per-user folders are all under a scratch folder. Exit 1 if a check fails.
*/
import { spawn, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, rmdirSync, symlinkSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') ? true : all[i + 1]]] : acc), []));
const here = dirname(fileURLToPath(import.meta.url));
const repoHost = resolve(here, '../../host');
const staged = resolve(here, '../src-tauri/resources');
const stagedControl = resolve(args.control ?? join(staged, 'control'));
const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node'));
const work = mkdtempSync(join(tmpdir(), 'strata-ui-flows-'));
const shots = resolve(args.shots ?? join(work, 'shots'));
mkdirSync(shots, { recursive: true });
const only = new Set(String(args.only ?? 'download,models,profile,ui2,ui2d,tune,fail,delete,theme,restart,perf,polish,stop,latest').split(','));
const isWin = process.platform === 'win32';
const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
const delay = ms => new Promise(r => setTimeout(r, ms));
const sha = buf => createHash('sha256').update(buf).digest('hex');
const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
let failed = false;
const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); if (!ok) failed = true; };
// ------------------------------------------------------------------ the app folder: the real Control with a fake installer
const control = join(work, 'control');
mkdirSync(control, { recursive: true });
for (const name of ['python', 'strata_control', 'strata_cli', 'serve']) symlinkSync(join(stagedControl, name), join(control, name), 'junction');
for (const name of ['strata.py', 'VERSION', 'BUNDLE.json', 'requirements.txt']) copyFileSync(join(stagedControl, name), join(control, name));
cpSync(join(stagedControl, 'tools'), join(control, 'tools'), { recursive: true });
const python = isWin ? join(control, 'python', 'python.exe') : join(control, 'python', 'bin', 'python3');
const FAKE_INSTALLER = String.raw`
import json, os, sys, time
from pathlib import Path
ROOT = Path(sys.argv[sys.argv.index('--root') + 1]) if '--root' in sys.argv else Path('.')
STATE = Path(os.environ['FAKE_STATE']); STATE.mkdir(parents=True, exist_ok=True)
RATE = float(os.environ.get('FAKE_RATE_GB_S', '0.5'))
def size(model, gb, ram, mid):
return {'model': model, 'about': model, 'download_gb': gb, 'ram_needed_gb': ram, 'experts_gb': ram - 8, 'on_this_pc': 'fits', 'installed': False, 'images': True, 'experimental': False, 'id': mid}
CATALOG = {'summary': 'fake', 'families': [{'family': 'qwen', 'title': 'Qwen3.8-Flash-Next', 'about': 'x', 'experimental': False, 'images': True, 'sizes': [
size('Q2_0', 66.4, 48, 'q2_0'), size('IQ3_XXS', 75.8, 60, 'iq3_xxs'), size('IQ3_S', 83.6, 62, 'iq3_s')]}],
'contexts': [8192, 32768, 65536], 'recommendation': {'family': 'qwen', 'model': 'IQ3_XXS', 'title': 'Qwen3.8-Flash-Next IQ3_XXS', 'context': 32768}, 'context_note': ''}
HARDWARE = {'ram_gb': 63.1, 'cpu': {'name': 'cpu', 'cores': 12}, 'gpus': [{'index': 0, 'name': 'NVIDIA GeForce RTX 5070', 'vram_gb': 11.9, 'usable': True}]}
TOTAL = 83.6
def job():
f = STATE / 'job.json'
if not f.exists(): return None
j = json.loads(f.read_text())
if j.get('cancelled'):
return {'running': False, 'exit_code': 1, 'error': 'stopped', 'result': 'failed'}
done = min(TOTAL, RATE * (time.time() - j['start']))
return {'running': True, 'step': '5/7: downloading Qwen3.8-Flash-Next IQ3_S', 'model': 'IQ3_S',
'download': {'file': 'model files', 'done_gb': round(done, 3), 'total_gb': TOTAL, 'remaining_gb': round(TOTAL - done, 3), 'percent': int(100 * done / TOTAL)}}
def call(name, a):
if name == 'strata_models': return CATALOG
if name == 'strata_remove':
cfg = ROOT / ('strata-%s.json' % a['model'])
if a.get('confirm') and cfg.exists(): cfg.unlink()
return {'summary': 'Deleted', 'plan': {'gb': 83.6}, 'failed': []}
if name == 'strata_status': return {'summary': 'fake', 'installed': {'models': [{'model': 'iq3_s', 'disk_gb': 83.6, 'disk_bytes': 83600000000}]}, 'hardware': HARDWARE, 'recommendation': CATALOG['recommendation'], 'install': job(), 'running': []}
if name == 'strata_install':
if a.get('cancel'):
f = STATE / 'job.json'
if f.exists(): j = json.loads(f.read_text()); j['cancelled'] = True; f.write_text(json.dumps(j))
return {'summary': 'stopped', 'install': job()}
if a.get('confirm'):
(STATE / 'job.json').write_text(json.dumps({'start': time.time()}))
return {'summary': 'started', 'plan': {'download_gb': TOTAL}, 'install': job()}
if not a: return {'summary': 'progress', 'install': job()}
return {'summary': 'Plan', 'plan': {'title': 'Qwen3.8-Flash-Next IQ3_S', 'download_gb': TOTAL, 'disk_short': None}}
raise Exception('unknown tool ' + name)
for line in sys.stdin:
line = line.strip()
if not line: continue
m = json.loads(line)
if 'id' not in m: continue
method = m.get('method')
if method == 'initialize': res = {'protocolVersion': '2024-11-05'}
elif method == 'tools/list': res = {'tools': [{'name': n} for n in ('strata_models', 'strata_status', 'strata_install', 'strata_remove')]}
else:
p = m['params']
res = {'structuredContent': call(p['name'], p.get('arguments') or {})}
sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': m['id'], 'result': res}) + '\n'); sys.stdout.flush()
`;
writeFileSync(join(control, 'tools', 'strata_mcp.py'), FAKE_INSTALLER);
const FAKE_ENGINE = `import os, sys, json, time
from pathlib import Path
if os.environ.get('FAKE_ENGINE_FAIL'):
print('memory guard: 5.1 GiB of RAM free is under the 6 GiB limit (limit 63.1 GiB)', flush=True)
sys.exit(3)
ctx = '4096'
if '--max-context' in sys.argv: ctx = sys.argv[sys.argv.index('--max-context') + 1]
print('READY %s stop' % ctx, flush=True)
for line in sys.stdin:
if line.strip() == 'QUIT': break
if line.startswith(('GEN ', 'BGEN ')):
slot = int(line.split()[1]) if line.startswith('BGEN ') else None
t0 = time.time(); n = 0
for ch in os.environ.get('FAKE_REPLY', 'a'):
print('T %d' % ord(ch), flush=True); n += 1
if os.environ.get('FAKE_TOKEN_DELAY'): time.sleep(float(os.environ['FAKE_TOKEN_DELAY']))
print('DONE %d 12 300.0 %.1f length 0 0 0' % (n, max(1.0, (time.time() - t0) * 1000)), flush=True)
if slot is not None: print(f'BADM {slot} 0', flush=True)
`;
// one scenario = one fresh host with its own per-user folders
async function scenario(name, { installed = false, env = {} } = {}, body) {
if (!only.has(name)) return;
console.log(`--- ${name}`);
const dir = join(work, name);
const dirs = { home: join(dir, 'home'), appdata: join(dir, 'appdata'), local: join(dir, 'local'), components: join(dir, 'local', 'Strata', 'components'), install: join(dir, 'local', 'Strata', 'install'), state: join(dir, 'fake-state'), profiles: join(dir, 'profiles'), runtime: join(dir, 'runtime') };
for (const d of [dirs.home, dirs.appdata, dirs.local, dirs.components, dirs.install, dirs.state, join(dir, 'models')]) mkdirSync(d, { recursive: true });
const baseEnv = { ...process.env, STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(dir, 'models'), APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, USERPROFILE: dirs.home, XDG_CONFIG_HOME: join(dir, 'xdg'), XDG_DATA_HOME: join(dir, 'xdgdata'), PYTHONDONTWRITEBYTECODE: '1', STRATA_ENGINE_BACKEND: 'cuda', FAKE_STATE: dirs.state, ...env };
delete baseEnv.STRATA_API_KEY; delete baseEnv.STRATA_INSTALL_DIR;
if (installed) {
const platform = isWin ? 'windows-x86_64' : 'linux-x86_64';
const folder = join(dirs.components, 'engine', `0.1.45-${platform}-cuda`);
mkdirSync(folder, { recursive: true });
writeFileSync(join(folder, 'engine_main.py'), FAKE_ENGINE);
const entry = isWin ? 'engine.cmd' : 'engine';
writeFileSync(join(folder, entry), isWin ? `@echo off\r\n"${python}" "%~dp0engine_main.py" %*\r\n` : `#!/bin/sh\nexec "${python}" "$(dirname "$0")/engine_main.py" "$@"\n`);
const files = [entry, 'engine_main.py'].map(p => { const b = readFileSync(join(folder, p)); return { path: p, sha256: sha(b), bytes: b.length }; });
writeFileSync(join(folder, 'engine-component.json'), JSON.stringify({ schema_version: 1, id: 'strata-engine', version: '0.1.45', platform, backend: 'cuda', entrypoint: entry, files }));
const tok = join(dirs.install, 'tokenizer');
mkdirSync(tok, { recursive: true });
const script = `import json, sys\nfrom tools.strata_tokenizer import BYTE_TO_UNICODE\ntok = sys.argv[1]\ntokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ['ab', '<|im_start|>', '<|im_end|>', '<|endoftext|>']\njson.dump({t: i for i, t in enumerate(tokens)}, open(tok + '/vocab.json', 'w'))\nopen(tok + '/merges.txt', 'w').write('a b')\njson.dump([0] * 257 + [3, 3, 3], open(tok + '/token_type.json', 'w'))\n`;
const made = spawnSync(python, ['-c', script, tok], { cwd: control, env: { ...baseEnv, PYTHONNOUSERSITE: '1' }, encoding: 'utf8' });
if (made.status !== 0) throw new Error('tokenizer fixture: ' + made.stderr);
writeFileSync(join(dirs.install, 'strata-iq3_s.json'), JSON.stringify({ exe: 'component:strata-engine', backend: 'cuda', tokenizer: tok, args: ['--max-context', '32768', '--pool-workers', '12'], cwd: dir, model_name: 'stub', host: '127.0.0.1', port: 0, kv: 'int8' }));
}
const port = env.FIXED_PORT ? Number(env.FIXED_PORT) : await freePort(), base = `http://127.0.0.1:${port}`;
const host = spawn(nodeExe, [join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', STRATA_CONTROL_DIR: control, STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } });
let log = ''; host.stdout.on('data', c => { log += c; }); host.stderr.on('data', c => { log += c; });
const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; };
const browser = await chromium.launch({ executablePath: CHROME, headless: true });
try {
let up = false;
for (let i = 0; i < 200 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(150); } }
check(up, `${name}: the packaged host starts`);
await api('/api/native?refresh=1');
await body({ base, api, browser, dirs, shot: (page, n) => page.screenshot({ path: join(shots, `${name}-${n}.png`) }), log: () => log });
} catch (error) {
check(false, `${name}: the flow`, String(error?.stack ?? error).slice(0, 700) + '\n' + log.slice(-600));
} finally {
await browser.close().catch(() => {});
host.kill(); await new Promise(r => host.once('exit', r));
}
}
const newPage = async (browser, base, options = {}) => {
const context = await browser.newContext({ viewport: { width: 1400, height: 950 }, ...(process.env.SCHEME ? { colorScheme: process.env.SCHEME } : {}), ...options });
const page = await context.newPage();
const problems = [];
page.on('pageerror', e => problems.push(e.message));
page.problems = problems;
await page.goto(base, { waitUntil: 'domcontentloaded' });
return page;
};
const clickText = async (page, re, timeout = 30000) => { const b = page.getByRole('button', { name: re }).first(); await b.waitFor({ timeout }); await b.click(); };
const noScroll = async page => page.evaluate(() => {
const root = document.querySelector('.guided-onboarding');
const bad = [];
for (let el = document.querySelector('.onboard-tune-stage, .onboard-prepare-stage, .onboard-model-stage') ?? root; el && el !== document.body; el = el.parentElement) {
const style = getComputedStyle(el);
if (/(auto|scroll)/.test(style.overflowY) && el.scrollHeight > el.clientHeight + 1) bad.push(`${el.className || el.tagName}: ${el.scrollHeight} > ${el.clientHeight}`);
}
return bad;
});
// ------------------------------------------------------------------------------------------------ download
await scenario('download', {}, async ({ base, api, browser, shot }) => {
const page = await newPage(browser, base);
await clickText(page, /get started/i);
await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 });
await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click();
await clickText(page, /^Continue/);
await clickText(page, /Download model/i, 60000);
await page.locator('.onboard-progress progress').waitFor({ timeout: 30000 });
// ONE bar: sample the percent while it runs, it only goes up
const samples = [];
let eta = '';
for (let i = 0; i < 40 && !eta; i++) {
const state = (await api('/api/native')).body;
const d = state.jobs.at(-1)?.result?.install?.download;
if (d) samples.push(d.done_gb);
eta = (await page.locator('.onboard-progress-actions span').first().textContent({ timeout: 1000 }).catch(() => '')) ?? '';
await delay(1000);
}
await shot(page, '1-wizard-progress');
check(/About \d+ (min left|h)/.test(eta), 'the wizard shows about how many minutes are left', eta.trim());
const order = await page.evaluate(() => { const a = document.querySelector('.onboard-progress-actions'); const kids = a ? [...a.children].map(k => k.tagName + ':' + Math.round(k.getBoundingClientRect().left)) : []; return kids; });
check(order.length === 2 && order[0].startsWith('SPAN') && order[1].startsWith('BUTTON') && Number(order[0].split(':')[1]) < Number(order[1].split(':')[1]), 'the time left sits left of Stop', order.join(' '));
check(samples.length >= 3 && samples.every((v, i) => i === 0 || v >= samples[i - 1]), 'one combined count that only goes up', samples.map(v => v.toFixed(1)).join(', '));
const meta = await page.locator('.onboard-progress-meta span').first().textContent();
check(/GB/.test(meta ?? '') && /83\.6/.test(meta ?? ''), 'the bar says done / total over the whole model', meta);
// close the pop-up while it downloads
await clickText(page, /Finish later/i);
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
await page.getByText(/Preparing your model/i).waitFor({ timeout: 15000 }).catch(() => {});
await delay(1500);
await shot(page, '2-models-progress');
await page.locator('.native-progress').first().screenshot({ path: join(shots, 'download-3-models-progress-card.png') }).catch(() => {});
check(await page.locator('.guided-onboarding').count() === 0, 'the setup pop-up closed');
check(await page.getByText(/Preparing your model/i).count() > 0, 'the Models screen shows the running download');
const still = (await api('/api/native')).body.jobs.at(-1);
check(still?.state === 'running', 'the download keeps running in the background', still?.state);
const modelsEta = await page.locator('.native-progress .onboard-progress-actions span').first().textContent({ timeout: 15000 }).catch(() => '');
check(/About \d+ (min left|h)/.test(modelsEta ?? ''), 'the Models screen shows the time left too', (modelsEta ?? '').trim());
await clickText(page, /^Stop$/);
await delay(2500);
check((await api('/api/native')).body.jobs.at(-1)?.state !== 'running', 'Stop stops it');
check(page.problems.length === 0, 'no page error', page.problems.join('; '));
});
// ------------------------------------------------------------------------------------------------ models
await scenario('models', { installed: true }, async ({ base, api, browser, shot }) => {
const page = await newPage(browser, base);
await clickText(page, /Go straight to the app/i);
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
await delay(1500);
await shot(page, '1-models');
await page.locator('.version-trigger').first().waitFor({ timeout: 20000 }).catch(async () => { await shot(page, '0-models-missing-summary'); console.log('info page text:', JSON.stringify((await page.locator('body').innerText()).slice(0, 500))); });
const summary = await page.locator('.version-trigger').first().textContent({ timeout: 5000 }).catch(() => '');
// the Models tab fits the first view: nothing to scroll while no list is open and Expert mode is closed
if (await page.getByRole('button', { name: /^Close expert mode$/ }).count()) { await page.getByRole('button', { name: /^Close expert mode$/ }).click(); await delay(500); }
await shot(page, '1b-models-one-view');
const overflow = await page.evaluate(() => { const el = document.querySelector('.main__body'); return el ? el.scrollHeight - el.clientHeight : 0; });
check(overflow <= 2, 'the Models tab fits the first view without scrolling', String(overflow) + ' px over');
check(await page.locator('.family-switch').count() === 1, 'the model family switch is in the navbar');
check(await page.locator('h1').filter({ hasText: /^Model$/ }).count() === 0, 'and the navbar does not say "Model"');
check(/IQ3_S|High quality/.test(summary ?? ''), 'Models selects the model that is on this PC, not the recommendation', (summary ?? '').replace(/\s+/g, ' ').trim());
check(!/IQ3_XXS|Balanced/.test(summary ?? ''), 'the recommendation (IQ3_XXS) is not what is selected');
const load = page.getByRole('button', { name: /^Load model$/ }).first();
await load.click();
await delay(1200);
check(await page.getByRole('dialog').filter({ hasText: /Download and prepare/i }).count() === 0, 'loading an installed model opens no download pop-up');
let ready = false;
for (let i = 0; i < 90 && !ready; i++) { const s = (await api('/api/native')).body; ready = s.instances.some(x => x.status === 'ready'); const err = s.instances.find(x => x.status === 'error'); if (err) throw new Error('load failed: ' + err.error); await delay(1000); }
if (!ready) { const st = (await api('/api/native')).body; console.log('info jobs', JSON.stringify(st.jobs.map(j => [j.kind, j.state, j.error ?? j.summary])), 'instances', JSON.stringify(st.instances.map(i => [i.status, i.error]))); await shot(page, '2-models-after-click'); }
check(ready, 'the model loads (a fake engine under the real Control)');
await page.reload({ waitUntil: 'domcontentloaded' });
await page.getByRole('button', { name: /^Unload$/ }).first().waitFor({ timeout: 30000 }).catch(() => {});
await shot(page, '3-models-loaded');
check(await page.getByRole('button', { name: /^Unload$/ }).count() > 0, 'after a reload the Models screen shows the model as loaded, with Unload');
check(await page.getByRole('button', { name: /^Load model$/ }).count() === 0, 'and no longer offers Load model');
await page.getByRole('button', { name: /^Unload$/ }).first().click();
let gone = false;
for (let i = 0; i < 40 && !gone; i++) { gone = (await api('/api/native')).body.instances.length === 0; await delay(500); }
check(gone, 'Unload stops the engine');
await page.getByRole('button', { name: /^Load model$/ }).first().waitFor({ timeout: 15000 }).catch(() => {});
check(await page.getByRole('button', { name: /^Load model$/ }).count() > 0, 'and Load model is back');
check(page.problems.length === 0, 'no page error', page.problems.join('; '));
});
// ------------------------------------------------------------------------------------------------ the profile used, the popover, the pop-up
await scenario('profile', { installed: true }, async ({ base, api, browser, shot }) => {
const page = await newPage(browser, base);
await clickText(page, /Go straight to the app/i);
await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
await delay(1500);
const work = () => page.getByRole('button', { name: /Leave 20% for my work/ }).first();
const full = () => page.getByRole('button', { name: /Full performance/ }).first();
await work().click();
check(await work().getAttribute('aria-pressed') === 'true', 'Leave 20% is chosen before loading');
await page.getByRole('button', { name: /^Load model$/ }).first().click();
let ready = false;
for (let i = 0; i < 90 && !ready; i++) { const s = (await api('/api/native')).body; ready = s.instances.some(x => x.status === 'ready'); await delay(500); }
check(ready, 'the model loads');
const inst = (await api('/api/native')).body.instances.find(x => x.status === 'ready');
check(inst?.resourceProfile === 'work', 'the running model reports the profile it was started with', String(inst?.resourceProfile));
await delay(1500);
check(await work().getAttribute('aria-pressed') === 'true' && await full().getAttribute('aria-pressed') === 'false', 'after the load the page still shows Leave 20%, not Full performance');
await page.reload({ waitUntil: 'domcontentloaded' });
await page.getByRole('button', { name: /^Unload$/ }).first().waitFor({ timeout: 30000 });
await delay(1000);
check(await work().getAttribute('aria-pressed') === 'true', 'and after a reload it is still the profile in use');
await shot(page, '1-profile-used');
// the reasoning popover names the loaded model
await page.evaluate(() => { location.hash = '#/chat'; });
const effort = page.getByRole('button', { name: /^Reasoning effort/ }).first();
await effort.waitFor({ timeout: 30000 });
await effort.click();
const header = await page.locator('.reasoning-menu-model strong').first().textContent({ timeout: 10000 });
check(header && !/No model loaded/i.test(header), 'the Reasoning popover names the loaded model, not "No model loaded"', String(header));
await shot(page, '2-reasoning-popover');
await page.keyboard.press('Escape');
// an installed model asked for with other settings: the pop-up never speaks of downloading
await page.evaluate(() => { location.hash = '#/models'; });
await page.getByRole('button', { name: /^Unload$/ }).first().waitFor({ timeout: 30000 });
await page.getByRole('button', { name: /^Unload$/ }).first().click();
await page.getByRole('button', { name: /^Load model$/ }).first().waitFor({ timeout: 30000 });
await page.getByRole('combobox', { name: 'Conversation context' }).first().click();
const options = page.getByRole('option');
const pick = (await options.allTextContents()).findIndex(t => /^8K$/.test(t.trim()));
if (pick >= 0) await options.nth(pick).click();
await page.getByRole('button', { name: /^Load model$|^Checking/ }).first().click();
const dialog = page.getByRole('dialog').first();
await dialog.waitFor({ timeout: 15000 }).catch(() => {});
const text = (await dialog.textContent().catch(() => '')) ?? '';
await shot(page, '3-apply-dialog');
if (text) {
check(!/Download and prepare|Download . load|approximately|[0-9] GB/i.test(text), 'for a downloaded model the pop-up has no download wording or size', text.replace(/\s+/g, ' ').slice(0, 600));
check(/Apply/.test(text), 'it says what happens: apply settings and load');
} else console.log('info the settings were the saved ones, so loading needed no pop-up at all');
check(page.problems.length === 0, 'no page error', page.problems.join('; '));
});
// ------------------------------------------------------------------------------------------------ version list, This computer, Tune, a task
for (const scheme of ['light', 'dark']) await scenario(scheme === 'light' ? 'ui2' : 'ui2d', { installed: true, env: { FAKE_TOKEN_DELAY: '0.02', FAKE_REPLY: 'I am thinking about it. </think> ' + 'Here is the answer, word by word. '.repeat(12), STRATA_TUNE_NO_QUIET_CHECK: '1' } }, async ({ base, api, browser, shot }) => {
const page = await newPage(browser, base, { colorScheme: scheme });
await clickText(page, /Go straight to the app/i);
await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
await delay(1500);
// the version list: Recommended (the fixed four), then folded groups, one line per model
console.log('info triggers', await page.locator('.version-trigger').count(), await page.getByRole('button', { name: 'Model version' }).count());
await page.locator('.version-trigger').first().click();
await delay(300);
console.log('info expanded after click', await page.locator('.version-trigger').first().getAttribute('aria-expanded'));
await delay(800); await shot(page, `0-after-click-${scheme}`);
console.log('info menu', await page.evaluate(() => { const m = document.querySelector('.version-menu'); const t = document.querySelector('.version-trigger'); return JSON.stringify({ menu: m ? m.getBoundingClientRect() : null, parent: m ? [m.parentElement.className, getComputedStyle(m.parentElement).display, getComputedStyle(m.parentElement).visibility, m.parentElement.style.cssText.slice(0, 120)] : null, expanded: t?.getAttribute('aria-expanded'), roles: [...document.querySelectorAll('[role=menu]')].length }); }));
await page.locator('.version-menu').waitFor({ timeout: 10000 });
const heads = await page.locator('.version-head span:first-child, .version-group__head').allTextContents();
const names = await page.locator('.version-menu > .version-row .version-row__name strong').allTextContents();
console.log('info version list', JSON.stringify(heads.map(t => t.replace(/\s+/g, ' ').trim())), JSON.stringify(names));
check(heads[0]?.trim() === 'Recommended', `${scheme}: the list starts with Recommended`);
check(names.length >= 1 && names.length <= 4, `${scheme}: Recommended shows only the picks this catalog has (at most the fixed four)`, names.join(' | '));
check(heads.some(t => /Swift models|GSQ-RCO models|Gyro models|NVFP4 models|Unsloth models/.test(t)), `${scheme}: the other models are in folded groups`);
check(heads.at(-1)?.includes('Use your own GGUF'), `${scheme}: the last row is Use your own GGUF`);
const tall = await page.locator('.version-row').evaluateAll(els => els.filter(e => e.getBoundingClientRect().height > 44).length);
check(tall === 0, `${scheme}: every model is one line`, String(tall));
await shot(page, `1-versions-${scheme}`);
await page.keyboard.press('Escape');
// This computer
const pc = page.locator('.pc-card');
await pc.waitFor({ timeout: 10000 });
const pcText = ((await pc.textContent()) ?? '').replace(/\s+/g, ' ');
check(/This computer/.test(pcText) && /(Fits fully in memory|read from the SSD)/.test(pcText), `${scheme}: This computer says in one line whether it fits`, pcText.slice(0, 200));
check(await pc.locator('.pc-meter').count() >= 1, `${scheme}: it shows the memory bars`);
check(await pc.locator('.chip, .st-pill, [class*="badge"]').count() === 0, `${scheme}: no chips or badges in it`);
await shot(page, `2-computer-${scheme}`);
// Tune: five steps, a live speed, a result card
await page.getByRole('button', { name: /^Tune model$/ }).first().click({ timeout: 10000 });
await delay(1500); await shot(page, `2b-tune-dialog-${scheme}`);
// The fake engine has no other setting worth trying, so its tune passes through "trying" too fast to be seen. The page is shown the progress a
// real tune reports (Control's status file: stage, speeds) for the running view; the start, the result and every other call are real.
let fakePhase = 'run';
await page.route('**/api/native*', async route => {
const response = await route.fetch(); let json = null;
try { json = await response.json(); } catch { return route.fulfill({ response }); }
for (const job of json?.jobs ?? []) if (job.kind === 'autotune' && fakePhase === 'done') { job.state = 'done'; job.progress = null; job.result = { outcome: 'improved', gain_pct: 18, base: { decode_tok_s: 41.2 }, chosen: { decode_tok_s: 48.6 }, preset: { id: 'fast', name: 'Fast · 64K' }, answers: { class: 'exact', fields: [] } }; } else if (job.kind === 'autotune' && job.state === 'running') job.progress = { stage: 'rounds', text: null, minutesLeft: 9, runsDone: 3, runsPlanned: 6, elapsedS: 300, step: 'Trying: more experts kept in memory (round 1 of 2)', speeds: [{ label: 'base', tok_s: 41.2 }, { label: 'Fewer helper threads', tok_s: 40.1 }, { label: 'More experts kept in memory', tok_s: 46.8 }] };
return route.fulfill({ response, json });
});
await page.getByRole('button', { name: /Start tuning|Tune again/ }).first().click({ timeout: 15000 });
await page.locator('.tune-step').first().waitFor({ timeout: 60000 });
check(await page.locator('.tune-step').count() === 5, `${scheme}: the tuner shows its five steps`);
let sawRun = false, sawSpeed = false;
for (let i = 0; i < 400; i++) {
const done = await page.locator('.tune-result, .tune-progress').count();
if (i % 4 === 0) { const jobs = (await api('/api/native')).body?.jobs ?? []; const j = jobs.find(x => x.kind === 'autotune'); if (j) console.log('info tune job', j.state, JSON.stringify(j.progress ?? null).slice(0, 300)); }
if (await page.locator('.tune-step[data-s=run]').count()) sawRun = true;
const big = await page.locator('.tune-live__big').first().textContent().catch(() => '');
if (/[0-9]/.test(big ?? '')) sawSpeed = true;
if (sawRun && sawSpeed) { await delay(700); await shot(page, `3-tune-running-${scheme}`); break; }
if (done) break;
await delay(600);
}
check(sawRun, `${scheme}: a step is shown as running`);
check(sawSpeed, `${scheme}: the live speed shows a number while it runs`);
if (sawSpeed) { fakePhase = 'done'; await page.locator('.tune-outcome').waitFor({ timeout: 15000 }).catch(() => {}); check(/18% faster/.test((await page.locator('.tune-outcome__body h3').textContent().catch(() => '')) ?? ''), `${scheme}: the result card shows the gain as its headline`); check(/Fast/.test((await page.locator('.tune-outcome__facts').textContent().catch(() => '')) ?? ''), `${scheme}: and what it was saved as`); }
await shot(page, `4-tune-result-${scheme}`);
await page.getByRole('button', { name: /^Close$/ }).first().click({ timeout: 10000 }).catch(() => {});
// a task: the opened task is skimmable, with pause / delete / Edit / Run now
const made = await api('/api/tasks', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'Open Downloads folder', prompt: 'Open my Downloads folder and tell me what is new.', frequency: 'weekdays', at: '08:00', weekday: 1, timeZone: 'Europe/Ljubljana', mode: 'manual', enabled: true }) });
const id = made.body?.id ?? made.body?.task?.id;
check(!!id, `${scheme}: a task is created`, JSON.stringify(made.body).slice(0, 120));
await page.evaluate(i => { location.hash = '#/tasks/' + i; }, id);
await page.getByRole('button', { name: /^Edit$/ }).first().waitFor({ timeout: 15000 });
console.log('info header buttons', await page.getByRole('button', { name: /^Pause / }).count(), await page.getByRole('button', { name: /^Delete / }).count(), await page.getByRole('button', { name: /Run now/ }).count(), JSON.stringify(await page.locator('.task-header-actions button').evaluateAll(b => b.map(x => (x.getAttribute('aria-label') ?? x.textContent ?? '').trim()))));
check(await page.getByRole('button', { name: /^Pause / }).count() === 1 && await page.getByRole('button', { name: /^Delete / }).count() >= 1 && await page.getByRole('button', { name: /Run now/ }).count() >= 1, `${scheme}: pause, delete, Edit and Run now are in the header`);
check(await page.locator('.main__back').count() === 0 && await page.locator('.main__title-line .task-state').count() === 0, `${scheme}: nothing sits on the left of an opened task's navbar`);
const factsText = ((await page.locator('.task-facts').textContent()) ?? '').replace(/\s+/g, ' ');
check(/Weekdays/.test(factsText) && /Schedule/i.test(factsText) && /Last result/i.test(factsText), `${scheme}: schedule, what it may do and the last result are at the top`, factsText.slice(0, 160));
await shot(page, `5-task-${scheme}`);
await page.getByRole('button', { name: /^Pause / }).first().click();
await page.getByRole('button', { name: /^Resume / }).first().waitFor({ timeout: 10000 });
check(true, `${scheme}: Pause becomes Resume`);
check(page.problems.length === 0, `${scheme}: no page error`, page.problems.join('; '));
});
// ------------------------------------------------------------------------------------------------ tune + reading size
await scenario('tune', { installed: true, env: { FAKE_TOKEN_DELAY: '0.02', FAKE_REPLY: ['I am thinking about it.', '</think>', '', 'Here is a list:', '', '- one', '- two', '', '## Heading', '', 'Some `code` and **bold** text.', '', '| a | b |', '|---|---|', '| 1 | 2 |', '', '```', 'code line', '```', ''].join(String.fromCharCode(10)) } }, async ({ base, api, browser, dirs, shot }) => {
const page = await newPage(browser, base);
await clickText(page, /get started/i);
await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 });
await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click();
await clickText(page, /^Continue/);
await page.getByText(/Leave 20% for my work/i).waitFor({ timeout: 30000 });
await delay(800);
await shot(page, '1-tune-step');
check(await page.getByText(/Read pictures when this model loads/i).count() === 0, 'the tuning step offers no picture reading for an app install');
await clickText(page, /Tune & start chatting/i);
let done = false, job = null;
for (let i = 0; i < 120 && !done; i++) { job = (await api('/api/native')).body.jobs.findLast?.(j => j.kind === 'tune') ?? null; done = !!job && job.state !== 'running'; await delay(1000); }
check(job?.state === 'done', 'tuning finishes without a vision error', job?.error ?? job?.state);
const cfg = JSON.parse(readFileSync(join(dirs.install, 'strata-iq3_s.json'), 'utf8'));
check(cfg.args.includes('--resident-budget-gib'), '"leave 20%" wrote a RAM budget for the experts', cfg.args.join(' '));
const gib = Number(cfg.args[cfg.args.indexOf('--resident-budget-gib') + 1]);
check(gib + 10 <= 63.1 * 0.8, 'the budget keeps the model within 80% of the PC RAM', `${gib} GiB`);
// chat + reading size
await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 60000 });
await page.getByRole('textbox', { name: /Message Strata/i }).fill('hello');
await page.keyboard.press('Enter');
await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 60000 });
await page.locator('.st-msg--assistant .st-bubble p').first().waitFor({ timeout: 60000 }).catch(async () => console.log('info reply so far:', JSON.stringify(await page.locator('.st-msg--assistant').first().innerText()).slice(0, 300)));
await page.waitForFunction(() => !document.querySelector('.st-msg--assistant .caret'), null, { timeout: 90000 }).catch(() => {});
// the chat's telemetry chips: speed and context
const chips = page.locator('.telemetry__chip');
const chipTexts = await chips.allInnerTexts();
console.log('info chips', JSON.stringify(chipTexts));
let speedText = '', contextText = '';
for (let i = 0; i < await chips.count(); i++) {
await chips.nth(i).click();
await delay(400);
const pop = await page.locator('.telepop').last().innerText().catch(() => '');
if (/tok\/s|speed/i.test(pop) && !speedText) speedText = pop;
if (/context/i.test(pop) && !contextText) contextText = pop;
await page.keyboard.press('Escape');
}
const tps = Number(speedText.match(/([\d.]+)\s*tok(?:ens)?\/s/)?.[1] ?? NaN);
check(tps > 15 && tps < 120, 'the speed shown is the decode speed (the engine paced at ~50 tokens a second)', speedText.replace(/\s+/g, ' ').slice(0, 160));
check(/32\.8K|32K|32,768|32768/.test(contextText) && !/128K/.test(contextText), 'the context shown is the one the model runs with (32K), not 128K', contextText.replace(/\s+/g, ' ').slice(0, 160));
const sizes = [];
for (const px of [12, 14, 16, 22]) {
await page.evaluate(v => { const k = 'strata.prefs.v2'; const cur = JSON.parse(localStorage.getItem(k) || '{}'); localStorage.setItem(k, JSON.stringify({ ...cur, contentFontSize: v })); }, px);
await page.reload({ waitUntil: 'domcontentloaded' });
await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 });
await page.screenshot({ path: join(shots, `tune-3-chat-${px}px.png`) });
sizes.push(await page.evaluate(() => { const b = document.querySelector('.st-msg--assistant .st-bubble'); const t = b.querySelector('p, .md-li, span') ?? b; const u = document.querySelector('.st-msg--user .st-bubble'); const all = {}; for (const el of b.querySelectorAll('*')) { if (!el.childNodes.length || ![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) continue; all[el.tagName.toLowerCase() + (el.className ? '.' + String(el.className).split(' ')[0] : '')] = parseFloat(getComputedStyle(el).fontSize); } const extra = {}; for (const [k, q] of Object.entries({ reasoning: '.st-msg--assistant .st-collapse__body', codeblock: '.st-msg--assistant .st-code pre', codehead: '.st-msg--assistant .st-code__head' })) { const e = document.querySelector(q); if (e) extra[k] = parseFloat(getComputedStyle(e).fontSize); } Object.assign(all, extra); const chain = []; for (let e = b.querySelector('p'); e && e !== b; e = e.parentElement) chain.push(e.tagName + '.' + String(e.className).split(' ')[0] + '=' + getComputedStyle(e).fontSize); all.chain = chain; globalThis.__all = all; return [parseFloat(getComputedStyle(b).fontSize), parseFloat(getComputedStyle(t).fontSize), parseFloat(getComputedStyle(u).fontSize), all]; }));
}
console.log('info chain', JSON.stringify(await page.evaluate(() => { const el = document.querySelector('.st-msg--assistant .st-bubble p'); const out = []; for (let e = el; e && !e.classList.contains('st-msg'); e = e.parentElement) out.push(e.tagName + '.' + String(e.className).split(' ')[0] + '=' + getComputedStyle(e).fontSize); return out; })));
// which visible text does NOT follow the reading size? (same elements at 12 and 22)
const survey = async px => { await page.evaluate(v => { const k = 'strata.prefs.v2'; const cur = JSON.parse(localStorage.getItem(k) || '{}'); localStorage.setItem(k, JSON.stringify({ ...cur, contentFontSize: v })); }, px); await page.reload({ waitUntil: 'domcontentloaded' }); await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 }); await delay(600);
return page.evaluate(() => { const out = {}; for (const el of document.querySelectorAll('main *, .chat *, textarea')) { if (![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim()) && el.tagName !== 'TEXTAREA') continue; const r = el.getBoundingClientRect(); if (!r.width || !r.height) continue; const key = el.tagName.toLowerCase() + '.' + String(el.className).split(' ')[0] + ' <' + (el.parentElement?.className ?? '').toString().split(' ')[0] + '>'; out[key] = parseFloat(getComputedStyle(el).fontSize); } return out; }); };
const a = await survey(12), b = await survey(22);
// a fresh app (nothing saved) uses 14 px
await page.evaluate(() => localStorage.removeItem('strata.prefs.v2'));
await page.reload({ waitUntil: 'domcontentloaded' });
await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 });
check(await page.evaluate(() => getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble')).fontSize) === '14px', 'the default reading size is 14 px');
const fixed = Object.keys(a).filter(k => k in b && a[k] === b[k]);
console.log('info text that does not follow the reading size:', JSON.stringify(fixed.map(k => k + '=' + a[k])));
await shot(page, '2-chat-22px');
console.log('info sizes', JSON.stringify(sizes), JSON.stringify(await page.locator('.st-msg--assistant .st-bubble').first().innerHTML()).slice(0, 400));
check(sizes[0][1] === 12 && sizes[1][1] === 14 && sizes[2][1] === 16 && sizes[3][1] === 22 && sizes[0][2] === 12 && sizes[3][2] === 22, 'the reading size changes the text size of the conversation', JSON.stringify(sizes));
// the slider itself
await page.evaluate(() => { location.hash = '#/chat?settings=1'; });
const slider = page.getByLabel('Reading text size');
if (await slider.count()) {
await slider.first().focus();
for (let i = 0; i < 4; i++) await page.keyboard.press('ArrowRight');
await delay(500);
const now = await page.evaluate(() => getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble') ?? document.body).fontSize);
check(parseFloat(now) === 18, 'moving the slider changes the conversation text at once', now);
const box = await slider.first().boundingBox();
await page.mouse.click(box.x + box.width * 0.9, box.y + box.height / 2);
await delay(400);
const dragged = await page.evaluate(() => [getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble') ?? document.body).fontSize, getComputedStyle(document.documentElement).getPropertyValue('--st-content-fs'), JSON.parse(localStorage.getItem('strata.prefs.v2') || '{}').contentFontSize]);
check(parseFloat(dragged[0]) >= 20 && parseFloat(dragged[2]) >= 20, 'clicking the slider with the mouse changes it too, and it is saved', dragged.join(' '));
} else console.log('info the settings slider was not reachable by hash here; the stored size was checked above');
check(page.problems.length === 0, 'no page error', page.problems.join('; '));
});
// ------------------------------------------------------------------------------------------------ delete
await scenario('delete', { installed: true }, async ({ base, api, browser, dirs, shot }) => {
const page = await newPage(browser, base);
await clickText(page, /Go straight to the app/i);
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
await page.getByRole('button', { name: /^Load model$/ }).first().click();
let ready = false;
for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }
check(ready, 'a model is loaded');
await clickText(page, /Manage models/i);
await page.getByRole('button', { name: /^Delete$/ }).first().click();
await delay(600);
await shot(page, '1-delete-confirm');
const dialog = await page.getByRole('dialog').last().innerText();
check(/Delete this version\?/.test(dialog) && /Remove 83\.6 GB of downloaded files\. You can download this version again\./.test(dialog), 'the confirm dialog uses the existing words and the real size', dialog.replace(/\s+/g, ' ').slice(0, 600));
check(/running model will be unloaded/i.test(dialog), 'and says the loaded model is unloaded first');
await page.getByRole('button', { name: /^Delete version$/ }).click();
let state = null;
for (let i = 0; i < 40; i++) { state = (await api('/api/native')).body; if (state.instances.length === 0 && !state.installed?.models?.some(m => m.model === 'iq3_s')) break; await delay(500); }
check(state.instances.length === 0, 'the loaded model was unloaded');
check(!existsSync(join(dirs.install, 'strata-iq3_s.json')), 'the installer removed the run config of the model');
check(!state.installed?.models?.some(m => m.model === 'iq3_s'), 'the model is no longer listed as downloaded');
await shot(page, '2-after-delete');
});
// ------------------------------------------------------------------------------------------------ perf
await scenario('perf', { installed: true }, async ({ base, api, browser, shot }) => {
const page = await newPage(browser, base);
await clickText(page, /Go straight to the app/i);
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
await page.getByRole('button', { name: /^Load model$/ }).first().click();
let ready = false;
for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }
check(ready, 'a model is loaded');
await delay(2500);
const requests = [];
const started = new Map();
page.on('request', r => started.set(r, Date.now()));
page.on('requestfinished', r => requests.push([r.url().replace(base, '').slice(0, 60), Date.now() - (started.get(r) ?? Date.now())]));
await page.evaluate(() => { window.__long = []; new PerformanceObserver(l => { for (const e of l.getEntries()) window.__long.push(Math.round(e.duration)); }).observe({ entryTypes: ['longtask'] }); });
const t0 = Date.now();
await page.evaluate(() => { location.hash = '#/chat'; });
await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 30000 });
const open = Date.now() - t0;
await delay(1500);
const long = await page.evaluate(() => window.__long);
console.log('info chat opened in', open, 'ms; long tasks', JSON.stringify(long), 'requests', JSON.stringify(requests.filter(r => r[1] > 100)), 'all', requests.length);
check(open < 1500 && Math.max(0, ...long) < 300, 'Models to Chat opens at once, with no long block', open + ' ms, longest task ' + Math.max(0, ...long) + ' ms');
});
// ------------------------------------------------------------------------------------------------ polish
await scenario('polish', { installed: true }, async ({ base, api, browser, dirs, shot }) => {
const page = await newPage(browser, base);
await clickText(page, /Go straight to the app/i);
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
check(await page.getByRole('button', { name: /^Tune model$/ }).count() === 1, 'the Models tab has the Tune model button (the real tuner, not the old short benchmark)');
await clickText(page, /Manage models/i);
await delay(500);
const rows = await page.locator('.native-manage-row').count();
check(rows === 1, 'Manage models lists only the downloaded model, not the catalog', rows + ' row(s)');
await shot(page, '1-manage-models');
await page.getByRole('button', { name: /^Done$/ }).click();
await page.getByRole('button', { name: /Other local models/i }).click().catch(async () => { await clickText(page, /Manage models/i); await clickText(page, /Use a local GGUF/i); });
await page.getByText(/Folder with the GGUF files/i).first().waitFor({ timeout: 15000 }).catch(() => {});
await shot(page, '2-local-gguf');
check(await page.getByText(/Folder with the GGUF files/i).count() > 0, 'the local GGUF page opens in the same design as Models');
await page.getByPlaceholder(/Full path to the folder/i).fill(join(dirs.install, 'does-not-exist'));
await page.getByRole('button', { name: /^Check files$/ }).click();
await delay(3000);
check(await page.locator('.error-notice').count() > 0, 'a folder that cannot be used says so in words');
await shot(page, '2b-local-gguf-problem');
await page.evaluate(() => { location.hash = '#/chat?settings=1'; });
await delay(1500);
const text = await page.locator('body').innerText();
check(!/Contrast/.test(text), 'Settings has no Contrast option');
check(!/View request log/.test(text), 'and no "View request log" button');
await page.getByText(/^Engine$/).first().click().catch(() => {});
await delay(1500);
await shot(page, '3-settings-engine');
const engine = await page.locator('body').innerText();
check(/Update component/.test(engine) && /Diagnostics/.test(engine), 'Settings > Engine has Update component and Diagnostics');
check(!/Performance|Model settings|Calibrate|Engine installation/.test(engine), 'and nothing else');
await page.getByRole('button', { name: /^View logs$/ }).click(); // the logs open in a pop-up that holds Save logs
await page.getByRole('button', { name: /^Save logs$/ }).click();
await page.getByText(/Saved to/).first().waitFor({ timeout: 15000 }).catch(() => {});
const savedText = await page.getByText(/Saved to/).first().innerText().catch(() => '');
const savedPath = savedText.replace(/^Saved to\s*/, '').trim();
check(!!savedPath && existsSync(savedPath), 'Save logs writes a file to Downloads and says where', savedPath);
await shot(page, '4-logs-saved');
await page.evaluate(() => { location.hash = '#/monitor'; });
await delay(6000);
await shot(page, '5-monitor');
const mon = await page.locator('body').innerText();
check(/°C/.test(mon), 'the Monitor shows GPU data with no model loaded', (mon.match(/.{0,30}°C.{0,20}/)?.[0] ?? 'no temperature text').replace(/\s+/g, ' '));
});
// ------------------------------------------------------------------------------------------------ stop
await scenario('stop', { installed: true, env: { FAKE_TOKEN_DELAY: '0.1', FAKE_REPLY: 'thinking '.repeat(30) } }, async ({ base, api, browser, shot }) => {
const page = await newPage(browser, base);
await clickText(page, /Go straight to the app/i);
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
await page.getByRole('button', { name: /^Load model$/ }).first().click();
let ready = false;
for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }
if (!ready) { const st = (await api('/api/native')).body; console.log('info jobs', JSON.stringify(st.jobs.map(j => [j.kind, j.state, j.error ?? j.summary])), JSON.stringify(st.instances.map(i => [i.status, i.error]))); await shot(page, '0-stop-notloaded'); }
check(ready, 'a model is loaded');
await page.evaluate(() => { location.hash = '#/chat'; });
const box = page.getByRole('textbox', { name: /Message Strata/i });
await box.waitFor({ timeout: 30000 });
await box.fill('hello');
await page.keyboard.press('Enter');
await page.locator('.typing').first().waitFor({ timeout: 30000 });
await delay(1500);
await page.getByRole('button', { name: /^Stop/i }).first().click().catch(async () => { await page.keyboard.press('Escape'); });
await delay(4000);
const dots = await page.locator('.typing').count();
await shot(page, '1-after-stop');
check(dots === 0, 'after Stop in the middle of thinking the three dots are gone', dots + ' left');
});
// ------------------------------------------------------------------------------------------------ latest
await scenario('latest', {}, async ({ base, browser, shot }) => {
const page = await newPage(browser, base);
const now = Date.now();
await page.evaluate(now => {
const messages = [];
for (let i = 0; i < 40; i++) { messages.push({ id: 'u' + i, role: 'user', content: 'question ' + i, at: now }, { id: 'a' + i, role: 'assistant', content: 'answer number ' + i + ' with some text to fill the line and more of it.', at: now, tokens: 20, inputTokens: 5 }); }
localStorage.setItem('strata.sessions.v1', JSON.stringify([{ id: 's_latest', title: 'long', updatedAt: now, createdAt: now, messages }]));
localStorage.setItem('strata.active-session.v1', 's_latest');
}, now);
await page.reload({ waitUntil: 'domcontentloaded' });
await delay(1500);
if (await page.getByRole('button', { name: /Go straight to the app/i }).count()) { await clickText(page, /Go straight to the app/i); await delay(1500); }
await page.goto(base + '/#/chat', { waitUntil: 'domcontentloaded' });
await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 30000 });
await delay(800);
await page.locator('.main__body.chat').first().waitFor({ timeout: 15000 }).catch(async () => { await shot(page, '0-latest-missing'); console.log('info body', JSON.stringify((await page.locator('body').innerText()).slice(0, 300))); });
await page.locator('.main__body.chat').first().evaluate(el => { el.scrollTop = 3000; });
await delay(600);
await page.mouse.wheel(0, -400);
await delay(600);
await page.locator('.main__body.chat').first().evaluate(el => { el.scrollTop = 0; });
await delay(800);
const gaps = await page.evaluate(() => { const b = document.querySelector('.jumplatest'), c = document.querySelector('.main__body.chat'); if (!b || !c) return null; const r = b.getBoundingClientRect(), cr = c.getBoundingClientRect(); return { top: Math.round(r.top - cr.top), bottom: Math.round(cr.bottom - r.bottom) }; });
console.log('info chat dom', JSON.stringify(await page.evaluate(() => { const c = document.querySelector('.main__body.chat'); return { msgs: document.querySelectorAll('.st-msg').length, scrollH: c?.scrollHeight, clientH: c?.clientHeight, top: c?.scrollTop, jump: document.querySelectorAll('.jumplatest').length }; })));
await shot(page, '1-latest-button');
check(!!gaps && gaps.top >= 12 && gaps.bottom >= 12, 'the Latest button keeps a gap from the top navigation and from the bottom', JSON.stringify(gaps));
});
// ------------------------------------------------------------------------------------------------ fail
await scenario('fail', { installed: true, env: { FAKE_ENGINE_FAIL: '1' } }, async ({ base, api, browser, shot }) => {
const page = await newPage(browser, base);
await clickText(page, /get started/i);
await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 });
await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click();
await clickText(page, /^Continue/);
await clickText(page, /Tune & start chatting/i, 30000);
await page.getByText(/ran low on memory/i).first().waitFor({ timeout: 120000 });
await delay(1000);
await shot(page, '1-tune-error');
const text = await page.locator('.guided-onboarding').innerText();
check(/ran low on memory/.test(text), 'the error says in words that the PC ran low on memory');
check(/Leave 20% for my work/.test(text) && /low-RAM/.test(text), 'and what to try');
check(!/server_exited|memory guard/.test(text), 'no code or log line in the main text');
check(!/vision files/i.test(text), 'no picture-reading error');
const bad = await noScroll(page);
check(bad.length === 0, 'the tuning pop-up does not scroll when an error shows', bad.join('; '));
await page.locator('.error-notice summary').first().click();
await delay(500);
await shot(page, '2-tune-error-details');
const details = await page.locator('.error-notice pre').first().innerText();
check(/server_exited/.test(details) && /exited before/.test(details), 'Details holds the code and the reason the server logged', details.replace(/\s+/g, ' ').slice(0, 120));
const badOpen = await noScroll(page);
check(badOpen.length === 0, 'and the pop-up still does not scroll with Details open', badOpen.join('; '));
await page.setViewportSize({ width: 1280, height: 700 });
await delay(600);
const small = await noScroll(page);
check(small.length === 0, 'nor in a small window (1280x700), Details open', small.join('; '));
await shot(page, '3-tune-error-small-window');
void api;
});
// ------------------------------------------------------------------------------------------------ restart
// The app keeps its theme, text size, language and chat list in the browser's storage, which belongs to the window's origin
// (127.0.0.1:<port>). The shell now uses the same port every launch: stop the host, start it again on that port, reopen the
// window with the same browser profile, and everything is still there.
if (only.has('restart')) {
console.log('--- restart');
const fixed = await freePort();
const profile = join(work, 'browser-profile');
const run = async (body) => scenario('restart', { env: { FIXED_PORT: String(fixed) } }, async ctx => {
const context = await chromium.launchPersistentContext(profile, { executablePath: CHROME, headless: true, viewport: { width: 1200, height: 800 } });
try { await body(context, ctx); } finally { await context.close(); }
});
only.add('restart');
await run(async (context, { base }) => {
const page = context.pages()[0] ?? await context.newPage();
await page.goto(base, { waitUntil: 'domcontentloaded' });
await page.evaluate(() => { localStorage.setItem('strata.prefs.v2', JSON.stringify({ theme: 'dark', contentFontSize: 19, language: 'de' })); localStorage.setItem('strata.sessions.v1', JSON.stringify([{ id: 'chat-1', title: 'My chat' }])); });
});
await run(async (context, { base }) => {
const page = context.pages()[0] ?? await context.newPage();
await page.goto(base, { waitUntil: 'domcontentloaded' });
const saved = await page.evaluate(() => ({ prefs: JSON.parse(localStorage.getItem('strata.prefs.v2') || '{}'), chats: localStorage.getItem('strata.sessions.v1'), theme: document.documentElement.dataset.theme }));
check(saved.prefs.contentFontSize === 19 && saved.prefs.language === 'de', 'text size and language survive a restart on the same port', JSON.stringify(saved.prefs));
check(saved.theme === 'dark', 'the theme survives too', saved.theme);
check(/My chat/.test(saved.chats ?? ''), 'and the chat list', saved.chats);
});
}
// ------------------------------------------------------------------------------------------------ theme
await scenario('theme', {}, async ({ base, browser, shot }) => {
for (const scheme of ['dark', 'light']) {
const page = await newPage(browser, base, { colorScheme: scheme });
await delay(1500);
const theme = await page.evaluate(() => document.documentElement.dataset.theme);
check(theme === scheme, `a fresh app follows the system (${scheme})`, theme);
await shot(page, `1-${scheme}`);
await page.context().close();
}
});
// the junctions into the staged Control go first (rmdir on a junction removes only the link)
for (const name of ['python', 'strata_control', 'strata_cli', 'serve']) { try { rmdirSync(join(control, name)); } catch { /* already gone */ } }
try { rmSync(work, { recursive: true, force: true, maxRetries: 3 }); } catch (e) { console.log('info scratch folder left behind:', work); }
console.log(`shots in ${shots}`);
process.exit(failed ? 1 : 0);
@@ -0,0 +1,121 @@
#!/usr/bin/env node
/**
* Picture reading in the APP, end to end on a test box, through the installed app layout (packaged host + bundled Control + a real engine component
* that carries strata-vision):
* Download and prepare with "Read pictures" ON (the picture-reader file is fetched, the vision settings are written), load the model with the picture
* reader, send a real picture through the host's own /v1 endpoint and check that the answer names what is in it, unload, shut down.
*
* node vision-e2e.mjs --install <folder with node/ host/ control/> --components <folder holding engine/<package with strata-vision>> \
* --work <scratch> --family qwen --model IQ3_XXS --data <data folder that has (or will get) the model files> --image shapes.png [--device cpu|gpu]
*
* The picture has a red circle, a blue square, a green triangle and the text "STRATA 42". The run exits 1 if any step fails.
*/
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { createServer } from 'node:net';
import { join, resolve } from 'node:path';
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), []));
for (const need of ['install', 'components', 'work', 'model', 'image']) if (!args[need]) { console.error('missing --' + need); process.exit(2); }
const install = resolve(args.install), work = resolve(args.work), components = resolve(args.components), family = String(args.family ?? 'qwen'), modelId = String(args.model);
const device = String(args.device ?? 'cpu');
const node = join(install, 'node', 'node'), hostEntry = join(install, 'host', 'server', 'index.mjs'), controlDir = join(install, 'control');
const dirs = { models: join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home'), xdg: join(work, 'xdg'), appdata: join(work, 'appdata') };
for (const d of [dirs.models, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true });
const delay = ms => new Promise(r => setTimeout(r, ms));
let failed = false;
const record = (name, ok, detail = '') => { if (!ok) failed = true; console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 600) : ''}`); };
const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
const env = { ...process.env, STRATA_COMPONENTS_DIR: components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.models,
STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models-unused'), APPDATA: dirs.appdata, XDG_CONFIG_HOME: dirs.xdg, PYTHONDONTWRITEBYTECODE: '1' };
delete env.STRATA_API_KEY;
const port = await freePort();
const base = `http://127.0.0.1:${port}`;
const host = spawn(node, [hostEntry], { cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'],
env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1',
STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } });
let hostLog = '';
host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; });
const call = async (path, method = 'GET', body) => {
const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
return { status: response.status, body: await response.json().catch(() => null) };
};
async function waitJob(id, seconds) {
let last = '';
for (let i = 0; i < seconds * 2; i++) {
const state = (await call('/api/native')).body;
const job = state.jobs.find(j => j.id === id);
if (job && job.summary !== last) { last = job.summary; console.log(' ... ' + String(last).slice(0, 120)); }
if (job && job.state !== 'running') return { job, state };
await delay(500);
}
throw new Error('operation did not finish');
}
async function main() {
let up = false;
for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { /* not yet */ } if (!up) await delay(150); }
record('host healthy', up, up ? base : hostLog.slice(-500));
if (!up) return;
const packages = existsSync(join(components, 'engine')) ? readdirSync(join(components, 'engine')) : [];
const reader = packages.some(p => existsSync(join(components, 'engine', p, 'strata-vision')));
record('the engine component carries the picture reader (strata-vision)', reader, packages.join(', '));
const status = (await call('/api/control/status')).body;
record('Control: engine usable', status.engine?.usable === true, `engine=${status.engine?.engine?.version}`);
// ---- Download and prepare, "Read pictures" on (the app sends vision "yes" for the download)
const values = { family, model: modelId, context: 32768, vision: 'yes', loadVision: device, ...(args.data ? { data_dir: resolve(args.data) } : {}) };
const plan = await call('/api/native/plan', 'POST', values);
record('the plan for the download is made', plan.status === 200, JSON.stringify(plan.body).slice(0, 300));
const started = await call('/api/native/operations', 'POST', { kind: 'install', args: values });
record('the install operation starts', started.status === 200 || started.status === 202, JSON.stringify(started.body).slice(0, 200));
const done = await waitJob(started.body.id, 3600);
record('Download and prepare finishes', done.job.state === 'done', `${done.job.state} ${done.job.error ?? done.job.summary}`);
const native = (await call('/api/native?refresh=1')).body;
console.log(' installed models: ' + JSON.stringify((native.installed?.models ?? []).map(m => ({ id: m.id, model: m.model, ready: m.ready, visionPrepared: m.visionPrepared, images: m.images, config: m.config }))));
const want = modelId.toLowerCase();
const model = native.installed?.models?.find(m => [m.id, m.model, m.tag].some(x => String(x ?? '').toLowerCase() === want));
record('the model is installed with the picture reader prepared (visionPrepared)', !!model?.visionPrepared, JSON.stringify({ ready: model?.ready, visionPrepared: model?.visionPrepared, images: model?.images }));
const configFile = model?.configPath ?? (model?.config ? join(dirs.models, model.config) : null);
let cfg = {};
try { cfg = JSON.parse(readFileSync(configFile, 'utf8')); } catch { /* reported below */ }
const mm = cfg.vision?.mmproj;
record('the run settings carry the vision entry and --vision, and the mmproj file is on disk',
!!cfg.vision && (cfg.args ?? []).includes('--vision') && !!mm && existsSync(mm) && statSync(mm).size > 800e6,
`vision=${cfg.vision ? 'yes' : 'no'} --vision=${(cfg.args ?? []).includes('--vision')} mmproj=${mm ? Math.round(statSync(mm).size / 1048576) + ' MB' : 'none'}`);
// ---- load with the picture reader
const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model: model?.model ?? modelId.toLowerCase(), vision: device } });
const loaded = await waitJob(load.body.id, 900);
const instance = loaded.state.instances[0];
record('load starts the engine with the picture reader', loaded.job.state === 'done' && instance?.status === 'ready', `${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}; vision=${instance?.vision}`);
record('the host says the loaded model reads pictures', !!instance?.vision, `vision=${instance?.vision}`);
// ---- a real picture through the host's own /v1 endpoint
const png = readFileSync(resolve(args.image)).toString('base64');
const t = Date.now();
let answer = '', finish = '';
for (const budget of [1536, 4096]) {
const chat = await call('/v1/chat/completions', 'POST', { model: instance?.apiModelId ?? modelId, max_tokens: budget, stream: false, messages: [{ role: 'user', content: [
{ type: 'text', text: 'Describe this picture: name each shape with its colour and read out any text.' },
{ type: 'image_url', image_url: { url: 'data:image/png;base64,' + png } }] }] });
const choice = chat.body?.choices?.[0] ?? {};
answer = choice.message?.content ?? '';
finish = choice.finish_reason ?? String(chat.status);
if (answer.trim() || finish !== 'length') break;
}
console.log(` answer (${Math.round((Date.now() - t) / 1000)} s, finish=${finish}): ${JSON.stringify(answer.slice(0, 300))}`);
const low = answer.toLowerCase();
record('the answer names the red circle', /red|circle/.test(low));
record('the answer names the blue square', /blue|square/.test(low));
record('the answer names the green triangle', /green|triangle/.test(low));
record('the answer reads STRATA 42', low.includes('42'));
// ---- unload
const unloaded = await call(`/api/native/instances/${instance?.id}/unload`, 'POST', {});
record('unload', unloaded.status === 200, unloaded.status);
}
try { await main(); } catch (e) { record('run', false, e.stack ?? e); }
host.kill();
await delay(1500);
console.log(failed ? 'VISION-E2E FAIL' : 'VISION-E2E PASS');
process.exit(failed ? 1 : 0);
@@ -0,0 +1,2 @@
# Rust build output. Regenerated by `cargo tauri build`; never committed.
/target/
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,30 @@
[package]
name = "strata-desktop"
version = "0.2.5"
description = "Strata Desktop — local AI, tuned to one model."
edition = "2021"
rust-version = "1.77"
license = "MIT"
# Linux: the drop of a file on the window is read straight from the GTK drag signals (see hook_linux_drops in main.rs); the versions are the ones Tauri itself uses.
[target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.18"
webkit2gtk = "2.0"
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-shell = "2"
tauri-plugin-updater = "2"
tauri-plugin-single-instance = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[profile.release]
codegen-units = 1
lto = true
opt-level = "s"
panic = "abort"
strip = true
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- Tauri uses the system WKWebView, so this bundle needs no JIT entitlement of its own;
the web content process gets what it needs from the OS. The App Host runs as an ordinary
child process and needs no special rights. Kept minimal on purpose. -->
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
</dict>
</plist>
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,3 @@
# built by apps/desktop/scripts/stage-control.py, never committed
*
!.gitignore
@@ -0,0 +1,2 @@
*
!.gitignore
@@ -0,0 +1,6 @@
# The private Node runtime is a build input, not source.
#
# It is a 117 MB platform binary that would bloat every clone and cannot be reviewed in a diff.
# `packaging/README.md` and `apps/desktop/scripts/fetch-node.sh` record exactly how to obtain it:
# the official nodejs.org build for the target, verified against its published SHA-256.
/node
@@ -0,0 +1,600 @@
//! The desktop shell's own logs (Linux): what the host and the window process printed, a crash log when the window dies, and
//! `--save-logs`, which collects everything a person can send us without the window (the window is what may be crashing).
//!
//! Files, in `<data>/logs` (`$XDG_DATA_HOME/strata/logs`, usually `~/.local/share/strata/logs`; the newest ten of each kind are kept):
//! desktop-<UTC time>.log one per start: the shell's lines, and every line the host (`[host]`) and the window (`[window]`) printed
//! desktop-crash-<UTC time>.log written when the window process dies without being closed: what happened in plain words, the system,
//! the graphics session, the last lines of the window and of the host, and a backtrace when the system keeps one
//!
//! `strata-desktop --save-logs` puts the newest crash log, the tails of the newest shell logs and the engine server logs into one text file
//! in the Downloads folder. The same pieces go into Settings > Engine > Diagnostics > Save logs (the host reads this folder).
//!
//! Windows and macOS (one process owns the host and the window) use the same folder and file names for what happens while the app starts:
//! `init_startup` opens the run log first thing in `main`, before anything that can fail, and installs a panic hook; a start that fails
//! (the host does not come up, the window cannot be made, any panic) ends in `startup_failed`: the reason goes into the run log and a
//! `desktop-crash-` file, and the person sees a plain message box instead of a process that vanished with no trace. On Windows the folder
//! is `%LOCALAPPDATA%\Strata\logs`, next to the components folder.
// Linux uses the shell log, the crash log and --save-logs; Windows and macOS use the start-up half. Each side leaves the other unused.
#![allow(dead_code)]
use std::collections::VecDeque;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const KEEP: usize = 10;
const RING_LINES: usize = 300;
/// `<data>/` : where Strata keeps its engine, runtime and logs on this system.
pub fn data_dir() -> PathBuf {
if let Some(dir) = std::env::var_os("STRATA_DESKTOP_DATA_DIR") {
return PathBuf::from(dir);
}
platform_data_dir()
}
/// Windows: `%LOCALAPPDATA%\Strata`, the folder the host and Control already use for the components and the install.
#[cfg(windows)]
fn platform_data_dir() -> PathBuf {
std::env::var_os("LOCALAPPDATA")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.or_else(|| std::env::var_os("USERPROFILE").map(|h| PathBuf::from(h).join("AppData").join("Local")))
.unwrap_or_else(std::env::temp_dir)
.join("Strata")
}
/// Linux and macOS: `$XDG_DATA_HOME/strata`, usually `~/.local/share/strata`.
#[cfg(not(windows))]
fn platform_data_dir() -> PathBuf {
let base = std::env::var_os("XDG_DATA_HOME")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))
.unwrap_or_else(std::env::temp_dir);
base.join("strata")
}
pub fn logs_dir() -> PathBuf {
data_dir().join("logs")
}
/// "20261018-014503" in UTC, from the system clock (no time crate).
pub fn stamp(now: SystemTime) -> String {
let secs = now.duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) as i64;
let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
// civil-from-days (Howard Hinnant), proleptic Gregorian
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!("{y:04}{m:02}{d:02}-{:02}{:02}{:02}", rem / 3600, rem % 3600 / 60, rem % 60)
}
/// Keep the newest `KEEP` files whose name starts with `prefix` and ends with `.log` (names sort by their time stamp).
fn prune(dir: &Path, prefix: &str, skip_crash: bool) {
let Ok(read) = std::fs::read_dir(dir) else { return };
let mut names: Vec<String> = read
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| n.starts_with(prefix) && n.ends_with(".log") && !(skip_crash && n.starts_with("desktop-crash-")))
.collect();
names.sort();
while names.len() > KEEP {
let _ = std::fs::remove_file(dir.join(names.remove(0)));
}
}
/// The last lines a process printed (kept in memory for the crash log).
#[derive(Clone, Default)]
pub struct Ring(Arc<Mutex<VecDeque<String>>>);
impl Ring {
pub fn push(&self, line: String) {
let mut q = self.0.lock().unwrap();
if q.len() >= RING_LINES {
q.pop_front();
}
q.push_back(line);
}
pub fn tail(&self, n: usize) -> Vec<String> {
let q = self.0.lock().unwrap();
q.iter().skip(q.len().saturating_sub(n)).cloned().collect()
}
}
/// This run's log file, shared by the shell and the threads that copy the children's output.
#[derive(Clone)]
pub struct Log {
file: Arc<Mutex<Option<std::fs::File>>>,
pub path: Option<PathBuf>,
}
impl Log {
pub fn open() -> Log {
let dir = logs_dir();
let _ = std::fs::create_dir_all(&dir);
prune(&dir, "desktop-", true);
prune(&dir, "desktop-crash-", false);
let path = dir.join(format!("desktop-{}.log", stamp(SystemTime::now())));
let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok();
let log = Log { file: Arc::new(Mutex::new(file)), path: Some(path) };
log.line("shell", &format!("Strata desktop {} starting (pid {})", env!("CARGO_PKG_VERSION"), std::process::id()));
log
}
pub fn line(&self, who: &str, text: &str) {
// never panics: this runs inside the panic hook too
if let Ok(mut guard) = self.file.lock() {
if let Some(f) = guard.as_mut() {
let _ = writeln!(f, "[{who}] {text}");
}
}
}
}
/// Print what the shell says (terminal and log).
pub fn say(log: &Log, text: &str) {
eprintln!("[strata] {text}");
log.line("shell", text);
}
/// Copy a child's output line by line: to our own stdout/stderr (as before), to the log file, and into the ring.
pub fn tee<R: Read + Send + 'static>(reader: R, who: &'static str, to_stderr: bool, ring: Ring, log: Log) {
std::thread::spawn(move || {
let mut r = BufReader::new(reader);
let mut buf = Vec::new();
loop {
buf.clear();
match r.read_until(b'\n', &mut buf) {
Ok(0) | Err(_) => break,
Ok(_) => {
let text = String::from_utf8_lossy(&buf);
let text = text.trim_end_matches(['\r', '\n']);
if to_stderr {
eprintln!("{text}");
} else {
println!("{text}");
}
ring.push(text.to_string());
log.line(who, text);
}
}
}
});
}
fn first_line(path: &str) -> Option<String> {
std::fs::read_to_string(path).ok().and_then(|t| t.lines().next().map(str::to_string))
}
fn os_pretty_name() -> String {
std::fs::read_to_string("/etc/os-release")
.ok()
.and_then(|t| t.lines().find_map(|l| l.strip_prefix("PRETTY_NAME=").map(|v| v.trim_matches('"').to_string())))
.unwrap_or_else(|| "unknown".into())
}
/// The environment variables that decide how the window draws; nothing private.
fn graphics_environment() -> Vec<String> {
const NAMES: &[&str] = &[
"XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP", "DESKTOP_SESSION", "DISPLAY", "WAYLAND_DISPLAY", "GDK_BACKEND", "GTK_THEME",
"WEBKIT_DISABLE_DMABUF_RENDERER", "WEBKIT_DISABLE_COMPOSITING_MODE", "WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS", "LIBGL_ALWAYS_SOFTWARE",
"GALLIUM_DRIVER", "__GLX_VENDOR_LIBRARY_NAME", "__NV_PRIME_RENDER_OFFLOAD", "MESA_LOADER_DRIVER_OVERRIDE", "APPIMAGE", "APPDIR",
];
NAMES.iter().filter_map(|n| std::env::var(n).ok().map(|v| format!(" {n}={v}"))).collect()
}
/// The WebKitGTK files inside the AppImage (the version is in the file name or its link target).
fn bundled_webkit() -> String {
let Some(appdir) = std::env::var_os("APPDIR") else { return "not an AppImage (the system's WebKitGTK is used)".into() };
let lib = PathBuf::from(appdir).join("usr").join("lib");
let mut found = Vec::new();
if let Ok(read) = std::fs::read_dir(&lib) {
for e in read.flatten() {
let n = e.file_name().to_string_lossy().into_owned();
if n.starts_with("libwebkit2gtk-4.1.so") || n.starts_with("libjavascriptcoregtk-4.1.so") {
let target = std::fs::read_link(e.path()).map(|t| format!(" -> {}", t.display())).unwrap_or_default();
found.push(format!("{n}{target}"));
}
}
}
found.sort();
if found.is_empty() { "no WebKitGTK file found in the AppImage".into() } else { found.join("; ") }
}
/// A backtrace of the dead window process when the system keeps one (systemd-coredump); None when it does not.
fn system_backtrace(pid: u32) -> Option<String> {
let mut child = std::process::Command::new("coredumpctl")
.args(["info", &pid.to_string(), "--no-pager"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.ok()?;
let deadline = std::time::Instant::now() + Duration::from_secs(4);
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
_ => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
}
let mut out = String::new();
child.stdout.take()?.read_to_string(&mut out).ok()?;
let out = out.trim().to_string();
if out.is_empty() || out.contains("No coredumps found") { None } else { Some(out) }
}
/// What the crash log says, as text (so it can be tested without a crash).
#[allow(clippy::too_many_arguments)]
pub fn crash_report(what: &str, pid: u32, window_tail: &[String], host_tail: &[String], backtrace: Option<&str>, app_version: &str, log_path: Option<&Path>) -> String {
let mut t = String::new();
t.push_str("Strata app window crash\n=======================\n\n");
t.push_str(&format!("When: {} UTC\n", stamp(SystemTime::now())));
t.push_str(&format!("What: the app window process (pid {pid}) stopped without being closed: {what}\n"));
t.push_str("Effect: Strata kept running and opened in the web browser instead (browser mode); nothing was lost.\n");
t.push_str(&format!("App: Strata desktop {app_version}\n"));
t.push_str(&format!("System: {} / {}\n", os_pretty_name(), first_line("/proc/version").unwrap_or_default()));
if let Some(v) = first_line("/proc/driver/nvidia/version") {
t.push_str(&format!("NVIDIA: {v}\n"));
}
t.push_str(&format!("WebKit: {}\n", bundled_webkit()));
t.push_str("Graphics session:\n");
for l in graphics_environment() {
t.push_str(&l);
t.push('\n');
}
if let Some(p) = log_path {
t.push_str(&format!("\nFull log of this run: {}\n", p.display()));
}
t.push_str("\n== Backtrace ==\n");
match backtrace {
Some(b) => t.push_str(b),
None => t.push_str("none kept by this system (no systemd-coredump). To get one: run coredumpctl gdb or start the AppImage under gdb --args ./<file>.AppImage --appimage-extract-and-run --window-child and type bt after the crash.\n"),
}
t.push_str("\n\n== Last lines of the window process ==\n");
for l in window_tail {
t.push_str(l);
t.push('\n');
}
t.push_str("\n== Last lines of the host ==\n");
for l in host_tail {
t.push_str(l);
t.push('\n');
}
t
}
/// Write the crash log; returns where it is.
pub fn write_crash_log(what: &str, pid: u32, window: &Ring, host: &Ring, log: &Log) -> Option<PathBuf> {
let dir = logs_dir();
std::fs::create_dir_all(&dir).ok()?;
prune(&dir, "desktop-crash-", false);
let path = dir.join(format!("desktop-crash-{}.log", stamp(SystemTime::now())));
let text = crash_report(what, pid, &window.tail(120), &host.tail(80), system_backtrace(pid).as_deref(), env!("CARGO_PKG_VERSION"), log.path.as_deref());
std::fs::write(&path, text).ok()?;
Some(path)
}
fn newest(dir: &Path, prefix: &str, crash: bool) -> Vec<PathBuf> {
let Ok(read) = std::fs::read_dir(dir) else { return Vec::new() };
let mut names: Vec<String> = read
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| n.starts_with(prefix) && n.ends_with(".log") && (n.starts_with("desktop-crash-") == crash))
.collect();
names.sort();
names.reverse();
names.into_iter().map(|n| dir.join(n)).collect()
}
fn tail_lines(path: &Path, n: usize) -> String {
let text = std::fs::read_to_string(path).unwrap_or_default();
let lines: Vec<&str> = text.lines().collect();
lines[lines.len().saturating_sub(n)..].join("\n")
}
/// `--save-logs`: one text file with what we need to look at a crash. Returns its path.
pub fn save_logs(out_dir: &Path) -> std::io::Result<PathBuf> {
std::fs::create_dir_all(out_dir)?;
let path = out_dir.join(format!("strata-logs-{}.txt", stamp(SystemTime::now())));
let mut t = String::new();
t.push_str(&format!("Strata desktop logs {} UTC\nApp {}\nSystem: {} / {}\n", stamp(SystemTime::now()), env!("CARGO_PKG_VERSION"), os_pretty_name(), first_line("/proc/version").unwrap_or_default()));
if let Some(v) = first_line("/proc/driver/nvidia/version") {
t.push_str(&format!("NVIDIA: {v}\n"));
}
t.push_str(&format!("WebKit: {}\nGraphics session:\n{}\n", bundled_webkit(), graphics_environment().join("\n")));
let dir = logs_dir();
let crashes = newest(&dir, "desktop-crash-", true);
t.push_str(&format!("\n\n##### Window crash logs ({} found, newest first, at most 3 shown)\n", crashes.len()));
for p in crashes.iter().take(3) {
t.push_str(&format!("\n----- {}\n{}\n", p.display(), std::fs::read_to_string(p).unwrap_or_default()));
}
let runs = newest(&dir, "desktop-", false);
t.push_str(&format!("\n\n##### Shell logs ({} found, last 300 lines of the newest 2)\n", runs.len()));
for p in runs.iter().take(2) {
t.push_str(&format!("\n----- {}\n{}\n", p.display(), tail_lines(p, 300)));
}
let runtime = data_dir().join("runtime");
if let Ok(read) = std::fs::read_dir(&runtime) {
let mut files: Vec<PathBuf> = read.flatten().map(|e| e.path()).filter(|p| p.to_string_lossy().ends_with(".server.log")).collect();
files.sort();
t.push_str(&format!("\n\n##### Engine server logs ({} found, last 200 lines each)\n", files.len()));
for p in files {
t.push_str(&format!("\n----- {}\n{}\n", p.display(), tail_lines(&p, 200)));
}
}
std::fs::write(&path, t)?;
Ok(path)
}
// ---------------------------------------------------------------------------------------------------------------------------------
// Start-up failures (Windows and macOS)
// ---------------------------------------------------------------------------------------------------------------------------------
/// The run log and whether a failure may show a message box. Set once, first thing in `main`.
struct Run {
log: Log,
dialog: bool,
}
static RUN: OnceLock<Run> = OnceLock::new();
/// One message box per run: a failure inside the panic hook and the abort that follows must not show two.
static REPORTED: AtomicBool = AtomicBool::new(false);
/// This run's log, once `init_startup` has opened it.
pub fn run_log() -> Option<Log> {
RUN.get().map(|r| r.log.clone())
}
/// Open the run log and install the panic hook. Call it first in `main`: nothing that can fail runs before it. `dialog` is false for
/// the self-test (no person to read a message box); `STRATA_NO_DIALOG` does the same for scripted runs.
pub fn init_startup(dialog: bool) {
let dialog = dialog && std::env::var_os("STRATA_NO_DIALOG").is_none();
let log = Log::open();
log.line("shell", &system_line());
if RUN.set(Run { log, dialog }).is_ok() {
install_panic_hook();
}
}
/// "Windows 10.0.26300 (64-bit)" or the name of the system; one line for the log and the crash file.
pub fn system_line() -> String {
format!("System: {} {}", std::env::consts::OS, system_version())
}
#[cfg(windows)]
fn system_version() -> String {
#[repr(C)]
struct OsVersionInfo {
size: u32,
major: u32,
minor: u32,
build: u32,
platform: u32,
csd: [u16; 128],
}
#[link(name = "ntdll")]
extern "system" {
fn RtlGetVersion(info: *mut OsVersionInfo) -> i32;
}
let mut info = OsVersionInfo { size: std::mem::size_of::<OsVersionInfo>() as u32, major: 0, minor: 0, build: 0, platform: 0, csd: [0; 128] };
// RtlGetVersion reports the real version (GetVersionEx lies to apps without a manifest entry)
if unsafe { RtlGetVersion(&mut info) } == 0 {
format!("{}.{}.{}", info.major, info.minor, info.build)
} else {
"version unknown".into()
}
}
#[cfg(not(windows))]
fn system_version() -> String {
first_line("/etc/os-release").unwrap_or_default()
}
/// What to tell a person, in plain words, for a technical reason. Always ends with the one next step.
pub fn plain_reason(detail: &str) -> String {
let lower = detail.to_ascii_lowercase();
if lower.contains("webview2") || lower.contains("webview") {
"Strata shows its window with Microsoft's WebView2 component, and it could not be started. \
Update or repair \"Microsoft Edge WebView2 Runtime\" (Settings > Apps > Installed apps), or install it from \
https://go.microsoft.com/fwlink/p/?LinkId=2124703, then start Strata again."
.into()
} else if lower.contains("app host") || lower.contains("node runtime") || lower.contains("could not start the app host") {
"Strata's background program did not start. Security software may have blocked a file in the Strata folder. \
Allow the Strata folder in it (or reinstall Strata) and start Strata again."
.into()
} else {
"Strata stopped while it was starting. Starting it again may work; if it does not, please send us the log file named below.".into()
}
}
/// The text of the crash file for a failed start, as text (so it can be tested without a failure).
pub fn startup_report(detail: &str, app_version: &str, log_path: Option<&Path>) -> String {
let mut t = String::new();
t.push_str("Strata app start failure\n========================\n\n");
t.push_str(&format!("When: {} UTC\n", stamp(SystemTime::now())));
t.push_str(&format!("App: Strata desktop {app_version}\n"));
t.push_str(&format!("{}\n", system_line()));
t.push_str(&format!("What: {detail}\n"));
t.push_str(&format!("Meaning: {}\n", plain_reason(detail)));
if let Some(p) = log_path {
t.push_str(&format!("\nFull log of this run: {}\n", p.display()));
}
t
}
/// Write the crash file of a failed start into `dir`; returns where it is.
pub fn write_startup_failure(dir: &Path, detail: &str, log_path: Option<&Path>) -> Option<PathBuf> {
std::fs::create_dir_all(dir).ok()?;
prune(dir, "desktop-crash-", false);
let path = dir.join(format!("desktop-crash-{}.log", stamp(SystemTime::now())));
std::fs::write(&path, startup_report(detail, env!("CARGO_PKG_VERSION"), log_path)).ok()?;
Some(path)
}
/// The message box (Windows). Elsewhere the text goes to the terminal only.
#[cfg(windows)]
fn show_error(text: &str) {
use std::os::windows::ffi::OsStrExt;
#[link(name = "user32")]
extern "system" {
fn MessageBoxW(window: *mut std::ffi::c_void, text: *const u16, caption: *const u16, kind: u32) -> i32;
}
const MB_ICONERROR: u32 = 0x10;
const MB_SETFOREGROUND: u32 = 0x1_0000;
const MB_TOPMOST: u32 = 0x4_0000;
let wide = |s: &str| std::ffi::OsStr::new(s).encode_wide().chain(std::iter::once(0)).collect::<Vec<u16>>();
let (text, caption) = (wide(text), wide("Strata"));
unsafe {
MessageBoxW(std::ptr::null_mut(), text.as_ptr(), caption.as_ptr(), MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST);
}
}
#[cfg(not(windows))]
fn show_error(text: &str) {
eprintln!("[strata] {text}");
}
/// Record a failed start (run log and crash file) and tell the person. Runs inside the panic hook as well, so it cannot panic.
fn report_failure(detail: &str) {
let Some(run) = RUN.get() else {
eprintln!("[strata] {detail}");
return;
};
run.log.line("shell", &format!("START FAILED: {detail}"));
let dir = logs_dir();
let saved = write_startup_failure(&dir, detail, run.log.path.as_deref());
if let Some(p) = &saved {
run.log.line("shell", &format!("The crash file is {}", p.display()));
}
if run.dialog && !REPORTED.swap(true, Ordering::SeqCst) {
let short: String = detail.chars().take(400).collect();
let place = saved.or_else(|| run.log.path.clone()).map(|p| p.display().to_string()).unwrap_or_else(|| dir.display().to_string());
show_error(&format!("Strata could not start.\n\n{}\n\nWhat happened: {short}\n\nA log was saved here, please send it to us:\n{place}", plain_reason(detail)));
}
}
/// A start that cannot go on: say why (log, crash file, message box) and end the process with a failure code. Never returns.
pub fn startup_failed(detail: &str) -> ! {
report_failure(detail);
std::process::exit(1)
}
/// Every panic in the app (a Tauri setup error is one) ends in an abort with panic = "abort", which Windows reports as 0xc0000409 with
/// nothing else. The hook runs before the abort: it writes what the panic said and where, and shows the message box.
fn install_panic_hook() {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
previous(info);
let message = if let Some(s) = info.payload().downcast_ref::<&str>() {
(*s).to_string()
} else if let Some(s) = info.payload().downcast_ref::<String>() {
s.clone()
} else {
"a panic without a message".to_string()
};
let place = info.location().map(|l| format!("{}:{}", l.file(), l.line())).unwrap_or_else(|| "an unknown place".into());
let thread = std::thread::current().name().unwrap_or("unnamed").to_string();
report_failure(&format!("the app stopped unexpectedly: {message} (at {place}, thread {thread})"));
}));
}
pub fn downloads_dir() -> PathBuf {
std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(|h| PathBuf::from(h).join("Downloads")).unwrap_or_else(std::env::temp_dir)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_time_stamp_is_utc_civil_time() {
assert_eq!(stamp(UNIX_EPOCH), "19700101-000000");
assert_eq!(stamp(UNIX_EPOCH + Duration::from_secs(1_800_000_000)), "20270115-080000");
assert_eq!(stamp(UNIX_EPOCH + Duration::from_secs(1_760_751_903)), "20251018-014503");
}
#[test]
fn the_ring_keeps_the_last_lines() {
let ring = Ring::default();
for i in 0..(RING_LINES + 50) {
ring.push(format!("line {i}"));
}
let tail = ring.tail(3);
assert_eq!(tail, vec![format!("line {}", RING_LINES + 47), format!("line {}", RING_LINES + 48), format!("line {}", RING_LINES + 49)]);
assert_eq!(ring.tail(10_000).len(), RING_LINES);
}
#[test]
fn the_crash_report_says_what_happened_in_plain_words_and_has_the_tails() {
let text = crash_report("signal 11 (segmentation fault)", 4242, &["window said a".into(), "window said b".into()], &["host said x".into()], None, "0.2.0-beta", Some(Path::new("/x/desktop-1.log")));
for needle in ["signal 11 (segmentation fault)", "pid 4242", "opened in the web browser instead", "0.2.0-beta", "window said b", "host said x", "/x/desktop-1.log", "none kept by this system"] {
assert!(text.contains(needle), "{needle}");
}
let with = crash_report("x", 1, &[], &[], Some("#0 AcceleratedBackingStore::update"), "1", None);
assert!(with.contains("#0 AcceleratedBackingStore::update") && !with.contains("none kept"));
}
#[test]
fn logs_are_pruned_and_saved_into_one_file() {
let dir = std::env::temp_dir().join(format!("strata-desktoplog-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::env::set_var("STRATA_DESKTOP_DATA_DIR", &dir);
let logs = logs_dir();
std::fs::create_dir_all(&logs).unwrap();
for i in 0..14 {
std::fs::write(logs.join(format!("desktop-20260101-0000{i:02}.log")), format!("run {i}\n")).unwrap();
std::fs::write(logs.join(format!("desktop-crash-20260101-0000{i:02}.log")), format!("crash {i}\n")).unwrap();
}
prune(&logs, "desktop-", true);
prune(&logs, "desktop-crash-", false);
assert_eq!(newest(&logs, "desktop-", false).len(), KEEP);
assert_eq!(newest(&logs, "desktop-", true).len(), KEEP);
assert!(newest(&logs, "desktop-", false)[0].to_string_lossy().ends_with("000013.log"), "the newest are kept");
std::fs::create_dir_all(dir.join("runtime")).unwrap();
std::fs::write(dir.join("runtime").join("app-1.server.log"), "engine line\n").unwrap();
let saved = save_logs(&dir.join("out")).unwrap();
let text = std::fs::read_to_string(saved).unwrap();
assert!(text.contains("crash 13") && text.contains("run 13") && text.contains("engine line"));
std::env::remove_var("STRATA_DESKTOP_DATA_DIR");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_failed_start_is_explained_in_plain_words_and_written_to_a_crash_file() {
let webview = plain_reason("Failed to setup app: error encountered during setup hook: WebView2 error: 0x8007139F");
assert!(webview.contains("WebView2") && webview.contains("go.microsoft.com"));
assert!(plain_reason("the Strata App Host did not become healthy at http://127.0.0.1:47831/api/health").contains("background program"));
assert!(plain_reason("something else").contains("log file"));
let dir = std::env::temp_dir().join(format!("strata-startlog-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = write_startup_failure(&dir, "the app stopped unexpectedly: boom (at main.rs:1, thread main)", Some(Path::new("/x/desktop-1.log"))).unwrap();
assert!(path.file_name().unwrap().to_string_lossy().starts_with("desktop-crash-"));
let text = std::fs::read_to_string(&path).unwrap();
for needle in ["boom", "main.rs:1", "/x/desktop-1.log", "0.2.0", "System:", "Meaning:"] {
assert!(text.contains(needle), "{needle}");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(windows)]
#[test]
fn on_windows_the_logs_sit_in_the_local_app_data_strata_folder() {
let dir = platform_data_dir();
assert!(dir.ends_with("Strata"), "{}", dir.display());
assert!(system_version().split('.').count() == 3, "{}", system_version());
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,497 @@
//! Linux: the process that owns the host, and what it does when the app window cannot run.
//!
//! WebKitGTK can crash the process that shows the window (a null pointer deep inside libwebkit2gtk was seen on Ubuntu 26.04 with
//! NVIDIA on Wayland, and on Ubuntu 24.04 under Xvfb). When the window and the host lived in one process, that crash took the host
//! and the engine down with it. So on Linux the work is split in two processes of this one executable:
//!
//! shell (this module; no GTK, no WebKit) starts the host, writes the session file, starts the window process, and watches both
//! window (`--window-child`; Tauri + WebKitGTK) shows the page, registers the app updater with the host, and nothing else
//!
//! If the window process dies for any reason except the person closing the window (a signal such as SIGSEGV, an abort, a failed
//! start, a missing library), the shell keeps the host running, tells the host to open the page in the default browser and to
//! show one notification, and prints the same sentence on the terminal. This is "browser mode"; `--browser` or STRATA_UI=browser
//! starts in it on purpose. In browser mode closing the tab does not stop the engine: the page has "Quit Strata", and `--quit`
//! ends a running Strata from the command line. The host listens on 127.0.0.1 only (the shell sets STRATA_BIND itself).
//!
//! The session file (`~/.strata/app-session.json`, mode 0600: process id, port, the secret only this user can read, the mode) is how
//! a second start finds the first one: it focuses the window (window mode) or opens another tab (browser mode) instead of
//! starting a second host.
use std::io::Write;
use std::path::PathBuf;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::time::{Duration, Instant};
use crate::desktoplog::{self, say, Log, Ring};
pub const BROWSER_NOTICE: &str = "Strata opened in your browser because the app window couldn't start on this computer.";
/// What the command line asked for.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Options {
/// `--browser` or STRATA_UI=browser: no app window, the page opens in the default browser.
pub browser: bool,
/// `--quit`: end a running Strata and leave.
pub quit: bool,
/// `--window-child`: the window process (started by the shell, not by a person).
pub window_child: bool,
/// `--save-logs`: collect the logs into one file in Downloads and leave.
pub save_logs: bool,
pub help: bool,
}
pub fn parse_args(args: &[String], ui_env: Option<&str>) -> Options {
let mut o = Options { browser: matches!(ui_env.map(|v| v.trim().to_ascii_lowercase()).as_deref(), Some("browser")), ..Options::default() };
for a in args.iter().skip(1) {
match a.as_str() {
"--browser" => o.browser = true,
"--quit" => o.quit = true,
"--window-child" => o.window_child = true,
"--save-logs" => o.save_logs = true,
"--help" | "-h" => o.help = true,
_ => {}
}
}
o
}
pub const HELP: &str = "Strata\n\
(no option) open the Strata app window\n\
--browser open Strata in your default browser instead of the app window (same as STRATA_UI=browser)\n\
--quit stop a running Strata (its engine too) and leave\n\
--save-logs put the logs (including the log of an app window crash) into one file in your Downloads folder, to send to us\n\
Closing the browser tab does not stop Strata in browser mode: use Quit Strata in the menu, or --quit.\n";
/// The command a person types to run this app again, for the messages ("run: Strata.AppImage --quit").
pub fn command_name() -> String {
if let Ok(image) = std::env::var("APPIMAGE") {
if let Some(name) = std::path::Path::new(&image).file_name() {
return format!("./{}", name.to_string_lossy());
}
}
std::env::current_exe().ok().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_else(|| "strata-desktop".into())
}
pub fn browser_chosen_line(port: u16) -> String {
format!(
"Strata is open in your browser at http://127.0.0.1:{port}/. Closing the tab does not stop Strata: choose Quit Strata in the menu, or run {} --quit.",
command_name()
)
}
pub fn open_by_hand_line(port: u16) -> String {
format!("No browser could be opened. Open http://127.0.0.1:{port}/ in your browser.")
}
// ------------------------------------------------------------------------------------------------ the session file
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Session {
pub pid: u32,
pub port: u16,
pub token: String,
pub mode: String,
}
fn session_path() -> PathBuf {
if let Some(p) = std::env::var_os("STRATA_APP_SESSION_FILE") {
return PathBuf::from(p);
}
let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(std::env::temp_dir);
home.join(".strata").join("app-session.json")
}
pub fn write_session(s: &Session) {
let path = session_path();
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
let text = serde_json::json!({ "pid": s.pid, "port": s.port, "token": s.token, "mode": s.mode }).to_string();
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
match options.open(&path) {
Ok(mut f) => {
let _ = f.write_all(text.as_bytes());
}
Err(e) => eprintln!("[strata] could not write {}: {e}", path.display()),
}
}
pub fn read_session() -> Option<Session> {
let text = std::fs::read_to_string(session_path()).ok()?;
let v: serde_json::Value = serde_json::from_str(&text).ok()?;
Some(Session {
pid: v["pid"].as_u64()? as u32,
port: v["port"].as_u64()? as u16,
token: v["token"].as_str()?.to_string(),
mode: v["mode"].as_str().unwrap_or("window").to_string(),
})
}
pub fn remove_session(only_if_pid: u32) {
if read_session().map(|s| s.pid == only_if_pid).unwrap_or(false) {
let _ = std::fs::remove_file(session_path());
}
}
fn pid_alive(pid: u32) -> bool {
#[cfg(target_os = "linux")]
{
std::path::Path::new(&format!("/proc/{pid}")).exists()
}
#[cfg(not(target_os = "linux"))]
{
let _ = pid;
true
}
}
/// A Strata that is really running: its shell process exists and its host answers.
pub fn live_session() -> Option<Session> {
let s = read_session()?;
if s.pid != std::process::id() && pid_alive(s.pid) && crate::ureq_get_ok(&format!("http://127.0.0.1:{}/api/health", s.port)).unwrap_or(false) {
Some(s)
} else {
None
}
}
// ------------------------------------------------------------------------------------------------ talking to the host
/// POST to the host as the shell (the secret in the header). Returns the response body.
fn host_post(port: u16, token: &str, path: &str, body: &serde_json::Value) -> Result<String, String> {
let (status, text) = crate::http_request_body("POST", &format!("http://127.0.0.1:{port}{path}"), &[("x-strata-shutdown", token), ("content-type", "application/json")], Some(&body.to_string()))?;
if status.contains(" 200") || status.contains(" 202") {
Ok(text)
} else {
Err(format!("{status}: {text}"))
}
}
/// Did the host manage to open the page (the "opened" flag in its answer)?
fn opened(answer: &str) -> bool {
let body = answer.rsplit("\r\n\r\n").next().unwrap_or(answer);
serde_json::from_str::<serde_json::Value>(body.trim()).ok().and_then(|v| v["opened"].as_bool()).unwrap_or(false)
}
/// Tell the host: everyone uses a browser tab now (and open it, and show `notice`). Prints what happened.
pub fn switch_host_to_browser(port: u16, token: &str, reason: &str, notice: &str) {
let body = serde_json::json!({ "mode": "browser", "reason": reason, "notice": notice, "open": true });
match host_post(port, token, "/api/control/ui", &body) {
Ok(answer) => {
if !opened(&answer) {
eprintln!("[strata] {}", open_by_hand_line(port));
}
}
Err(e) => eprintln!("[strata] could not tell the host to open your browser ({e}). Open http://127.0.0.1:{port}/ in your browser."),
}
}
/// Open the page in the default browser without changing the host's mode (a second start while Strata runs).
fn open_page_only(port: u16, token: &str) {
match host_post(port, token, "/api/control/ui", &serde_json::json!({ "open": true })) {
Ok(answer) if opened(&answer) => {}
_ => eprintln!("[strata] {}", open_by_hand_line(port)),
}
}
pub fn describe_exit(status: &ExitStatus) -> String {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
if let Some(sig) = status.signal() {
let name = match sig {
6 => " (abort)",
11 => " (segmentation fault)",
7 => " (bus error)",
9 => " (killed)",
15 => " (terminated)",
_ => "",
};
return format!("signal {sig}{name}");
}
}
match status.code() {
Some(127) => "exit code 127: a program file it needs is missing".into(),
Some(126) => "exit code 126: a program file it needs could not be run".into(),
Some(c) => format!("exit code {c}"),
None => "ended without a code".into(),
}
}
// ------------------------------------------------------------------------------------------------ the shell
fn spawn_window(port: u16, token: &str) -> std::io::Result<Child> {
let exe = std::env::current_exe()?;
Command::new(exe)
.arg("--window-child")
.env("STRATA_WINDOW_PORT", port.to_string())
.env("STRATA_SHUTDOWN_TOKEN", token)
.stdin(Stdio::null())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.spawn()
}
/// `--quit`: end a running Strata (the window, the host, the engines it started) and wait for it.
pub fn quit_running() -> i32 {
let Some(s) = live_session() else {
println!("Strata is not running.");
let _ = std::fs::remove_file(session_path());
return 0;
};
match host_post(s.port, &s.token, "/api/control/shutdown", &serde_json::json!({})) {
Ok(_) => {}
Err(e) => {
eprintln!("[strata] could not ask Strata to stop ({e}).");
return 1;
}
}
let deadline = Instant::now() + Duration::from_secs(crate::HOST_STOP_SECONDS + 10);
while Instant::now() < deadline {
if !pid_alive(s.pid) {
println!("Strata has stopped.");
return 0;
}
std::thread::sleep(Duration::from_millis(200));
}
eprintln!("[strata] Strata is still stopping its engine. Try again in a moment.");
1
}
/// A second start while Strata already runs: focus the window, or open another tab. Starts no second host.
fn join_running(s: &Session, browser: bool) -> i32 {
if browser || s.mode == "browser" {
println!("Strata is already running. Opening it in your browser.");
open_page_only(s.port, &s.token);
return 0;
}
// window mode: the window process's single-instance check brings the open window forward and exits at once
match spawn_window(s.port, &s.token).and_then(|mut c| c.wait()) {
Ok(status) if status.success() => 0,
Ok(status) => {
eprintln!("[strata] The app window stopped ({}). Opening Strata in your browser.", describe_exit(&status));
open_page_only(s.port, &s.token);
0
}
Err(e) => {
eprintln!("[strata] could not start the app window ({e}). Opening Strata in your browser.");
open_page_only(s.port, &s.token);
0
}
}
}
/// Start a child with its output copied to the terminal, the log and a ring (for the crash log).
fn spawn_logged(cmd: &mut Command, who: &'static str, ring: &Ring, log: &Log) -> std::io::Result<Child> {
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn()?;
if let Some(out) = child.stdout.take() {
desktoplog::tee(out, who, false, ring.clone(), log.clone());
}
if let Some(err) = child.stderr.take() {
desktoplog::tee(err, who, true, ring.clone(), log.clone());
}
Ok(child)
}
/// The window process died without being closed: say so in plain words, write the crash log, move everyone to the browser.
fn window_failed(why: &str, window_pid: u32, window_ring: &Ring, host_ring: &Ring, log: &Log, port: u16, token: &str) {
say(log, &format!("The app window crashed ({why})."));
// let the copy threads read the last lines the dead process wrote
std::thread::sleep(Duration::from_millis(300));
match desktoplog::write_crash_log(why, window_pid, window_ring, host_ring, log) {
Some(path) => say(log, &format!("The crash log is {}. To collect the logs for us: {} --save-logs", path.display(), command_name())),
None => say(log, &format!("The crash log could not be written. To collect the logs for us: {} --save-logs", command_name())),
}
say(log, BROWSER_NOTICE);
switch_host_to_browser(port, token, "window-failed", BROWSER_NOTICE);
}
/// The shell. Returns the process exit code.
pub fn run(opts: &Options) -> i32 {
if opts.help {
print!("{HELP}");
return 0;
}
if opts.save_logs {
return match desktoplog::save_logs(&desktoplog::downloads_dir()) {
Ok(path) => {
println!("Saved to {}. Please send this file to us.", path.display());
0
}
Err(e) => {
eprintln!("[strata] could not save the logs: {e}");
1
}
};
}
if opts.quit {
return quit_running();
}
if let Some(s) = live_session() {
return join_running(&s, opts.browser);
}
let log = Log::open();
let (host_ring, window_ring) = (Ring::default(), Ring::default());
let exe = std::env::current_exe().unwrap_or_default();
let res = crate::packaged_resource_dir(&exe).unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")));
let port = match crate::pick_stable_port() {
Ok(p) => p,
Err(e) => {
say(&log, &e);
return 1;
}
};
let token = crate::random_token();
let mode = if opts.browser { "browser" } else { "window" };
let mut cmd = match crate::host_command(&res, port, &token) {
Ok(c) => c,
Err(e) => {
say(&log, &e);
return 1;
}
};
cmd.env("STRATA_UI_MODE", mode).env("STRATA_APP_VERSION", env!("CARGO_PKG_VERSION"));
if opts.browser {
cmd.env("STRATA_UI_REASON", "chosen");
}
let mut host = match spawn_logged(&mut cmd, "host", &host_ring, &log) {
Ok(c) => c,
Err(e) => {
say(&log, &format!("could not start the App Host: {e}"));
return 1;
}
};
let health = crate::wait_for_health(port, Duration::from_secs(60), || match host.try_wait() {
Ok(Some(status)) => Some(format!("exit status {status}")),
_ => None,
});
if let Err(e) = health {
say(&log, &e);
let _ = host.kill();
let _ = host.wait();
return 1;
}
let me = std::process::id();
write_session(&Session { pid: me, port, token: token.clone(), mode: mode.into() });
let mut window: Option<Child> = None;
if opts.browser {
say(&log, &browser_chosen_line(port));
switch_host_to_browser(port, &token, "chosen", "");
} else {
let started = std::env::current_exe().and_then(|exe| {
let mut c = Command::new(exe);
c.arg("--window-child").env("STRATA_WINDOW_PORT", port.to_string()).env("STRATA_SHUTDOWN_TOKEN", &token).stdin(Stdio::null());
spawn_logged(&mut c, "window", &window_ring, &log)
});
match started {
Ok(c) => window = Some(c),
Err(e) => {
window_failed(&format!("it could not be started: {e}"), 0, &window_ring, &host_ring, &log, port, &token);
write_session(&Session { pid: me, port, token: token.clone(), mode: "browser".into() });
}
}
}
let code = loop {
std::thread::sleep(Duration::from_millis(200));
// The host ended (Quit Strata, a crash, someone killed it): nothing is left to show.
if let Ok(Some(status)) = host.try_wait() {
if let Some(w) = window.as_mut() {
let _ = w.kill();
let _ = w.wait();
}
if status.success() {
log.line("shell", "the host stopped (Quit Strata or the window was closed)");
break 0;
}
say(&log, &format!("The App Host stopped ({}). The last lines it printed are in {}.", describe_exit(&status), log.path.as_ref().map(|p| p.display().to_string()).unwrap_or_default()));
break 1;
}
let Some(w) = window.as_mut() else { continue };
let window_pid = w.id();
let Ok(Some(status)) = w.try_wait() else { continue };
window = None;
if status.success() {
// the person closed the window: stop the host and the engines this app started, as before
log.line("shell", "the window was closed: stopping the host");
crate::stop_host_child(&mut host, Some(port), Some(&token));
break 0;
}
// The window stopped without being closed: keep Strata running and move to the browser.
window_failed(&describe_exit(&status), window_pid, &window_ring, &host_ring, &log, port, &token);
write_session(&Session { pid: me, port, token: token.clone(), mode: "browser".into() });
};
remove_session(me);
code
}
#[cfg(test)]
mod tests {
use super::*;
fn args(list: &[&str]) -> Vec<String> {
std::iter::once("strata-desktop").chain(list.iter().copied()).map(String::from).collect()
}
#[test]
fn the_command_line_picks_browser_quit_and_the_window_child() {
assert_eq!(parse_args(&args(&[]), None), Options::default());
assert!(parse_args(&args(&["--browser"]), None).browser);
assert!(parse_args(&args(&[]), Some("browser")).browser);
assert!(parse_args(&args(&[]), Some(" Browser ")).browser);
assert!(!parse_args(&args(&[]), Some("window")).browser);
assert!(parse_args(&args(&["--quit"]), None).quit);
assert!(parse_args(&args(&["--window-child"]), None).window_child);
assert!(parse_args(&args(&["--save-logs"]), None).save_logs);
assert!(parse_args(&args(&["-h"]), None).help);
// anything else (a file the desktop hands over, an AppImage option) is ignored
assert_eq!(parse_args(&args(&["--appimage-extract-and-run", "x.gguf"]), None), Options::default());
}
#[test]
fn the_browser_message_is_the_plain_sentence_and_names_the_way_out() {
assert_eq!(BROWSER_NOTICE, "Strata opened in your browser because the app window couldn't start on this computer.");
let line = browser_chosen_line(47831);
assert!(line.contains("http://127.0.0.1:47831/") && line.contains("--quit") && line.contains("Quit Strata"));
assert!(open_by_hand_line(47831).contains("127.0.0.1:47831"));
}
#[test]
fn a_session_round_trips_and_is_private() {
let dir = std::env::temp_dir().join(format!("strata-session-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::env::set_var("STRATA_APP_SESSION_FILE", dir.join("s.json"));
assert!(read_session().is_none());
let s = Session { pid: 4242, port: 47831, token: "ab".repeat(32), mode: "browser".into() };
write_session(&s);
assert_eq!(read_session(), Some(s.clone()));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(dir.join("s.json")).unwrap().permissions().mode() & 0o777, 0o600);
}
// only the owner removes it
remove_session(1);
assert!(read_session().is_some());
remove_session(4242);
assert!(read_session().is_none());
std::env::remove_var("STRATA_APP_SESSION_FILE");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_hosts_answer_tells_whether_a_browser_opened() {
assert!(opened("HTTP/1.1 200 OK\r\n\r\n{\"mode\":\"browser\",\"opened\":true}"));
assert!(!opened("HTTP/1.1 200 OK\r\n\r\n{\"mode\":\"browser\",\"opened\":false}"));
assert!(!opened("not json"));
}
}
@@ -0,0 +1,278 @@
//! The shell's half of the app update: Tauri's signed updater behind a loopback bridge for the App Host.
//!
//! The UI is served by the App Host, so it cannot call Tauri's updater plugin; and the host is Node, which has no updater.
//! The shell therefore opens one loopback listener, protected by a random token it hands only to the host it started
//! (`STRATA_SHELL_BRIDGE`, `STRATA_SHELL_TOKEN`), and the host's `app-updater.mjs` talks to it:
//!
//! GET /app-update/check -> { available, version, current, notes } (signature-verified metadata from the feed)
//! POST /app-update/install -> starts download + install in the background
//! GET /app-update/status -> { state: idle|downloading|installing|done|error, downloaded, total, version, error }
//!
//! The update itself is Tauri's: it downloads the installer, checks its minisign signature against the public key in
//! `tauri.conf.json` (`plugins.updater.pubkey`, the owner's separate updater key) and installs. A check or an install happens
//! only when the user presses "Check for updates" / "Update Strata"; nothing here runs on start, and nothing here touches
//! engines or models (those are Control's component updater: `strata update`).
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tauri::AppHandle;
use tauri_plugin_updater::UpdaterExt;
/// Where an endpoint other than the one in `tauri.conf.json` may come from: a local test feed. Only loopback or https.
const ENDPOINT_ENV: &str = "STRATA_UPDATE_APP_ENDPOINT";
#[derive(Clone, Default)]
struct Progress {
state: &'static str,
downloaded: u64,
total: u64,
version: Option<String>,
error: Option<String>,
}
impl Progress {
fn json(&self) -> serde_json::Value {
serde_json::json!({
"state": if self.state.is_empty() { "idle" } else { self.state },
"downloaded": self.downloaded, "total": self.total, "version": self.version, "error": self.error,
})
}
}
/// What the host needs to find the bridge.
pub struct Bridge {
pub url: String,
pub token: String,
}
fn endpoint_override() -> Option<String> {
let url = std::env::var(ENDPOINT_ENV).ok()?;
if url.starts_with("https://") || url.starts_with("http://127.0.0.1:") || url.starts_with("http://localhost:") {
Some(url)
} else {
None
}
}
fn updater_for(app: &AppHandle) -> Result<tauri_plugin_updater::Updater, String> {
match endpoint_override() {
Some(url) => {
let url: tauri::Url = url.parse().map_err(|e| format!("bad update endpoint: {e}"))?;
app.updater_builder().endpoints(vec![url]).map_err(|e| e.to_string())?.build().map_err(|e| e.to_string())
}
None => app.updater().map_err(|e| e.to_string()),
}
}
async fn check(app: &AppHandle) -> Result<serde_json::Value, String> {
let updater = updater_for(app)?;
match updater.check().await.map_err(|e| e.to_string())? {
Some(update) => Ok(serde_json::json!({
"available": true, "version": update.version, "current": update.current_version, "notes": update.body,
})),
None => Ok(serde_json::json!({ "available": false, "current": app.package_info().version.to_string() })),
}
}
async fn install(app: AppHandle, progress: Arc<Mutex<Progress>>) {
let fail = |message: String| {
let mut p = progress.lock().unwrap();
p.state = "error";
p.error = Some(message);
};
let updater = match updater_for(&app) {
Ok(u) => u,
Err(e) => return fail(e),
};
let update = match updater.check().await {
Ok(Some(update)) => update,
Ok(None) => return fail("There is no newer version of the Strata app.".into()),
Err(e) => return fail(e.to_string()),
};
{
let mut p = progress.lock().unwrap();
*p = Progress { state: "downloading", version: Some(update.version.clone()), ..Default::default() };
}
let on_chunk = {
let progress = progress.clone();
move |chunk: usize, total: Option<u64>| {
let mut p = progress.lock().unwrap();
p.downloaded += chunk as u64;
p.total = total.unwrap_or(p.total);
}
};
let on_finish = {
let progress = progress.clone();
move || progress.lock().unwrap().state = "installing"
};
// Tauri checks the installer's minisign signature when it downloads it. Installing is done here, not by the plugin's
// download_and_install: on Windows this app lives in a kill-on-close Job Object, and an installer the plugin starts is in
// that job, so it is ended the moment the app exits and the update never happens. `launch_installer` starts it outside
// the job; the app then exits and the installer (passive: a progress window, no questions) replaces it and starts it again.
let bytes = match update.download(on_chunk, on_finish).await {
Ok(bytes) => bytes,
Err(e) => return fail(e.to_string()),
};
progress.lock().unwrap().state = "installing";
match launch_installer(&update.version, &bytes) {
Ok(()) => {
progress.lock().unwrap().state = "done";
app.exit(0);
}
Err(first) => match update.install(&bytes) {
Ok(()) => {
progress.lock().unwrap().state = "done";
app.restart();
}
Err(e) => fail(format!("{first}; {e}")),
},
}
}
/// Windows: write the verified installer to a temp folder and start it detached and outside the app's Job Object.
#[cfg(windows)]
fn launch_installer(version: &str, bytes: &[u8]) -> Result<(), String> {
use std::os::windows::process::CommandExt;
const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
const DETACHED_PROCESS: u32 = 0x0000_0008;
let dir = std::env::temp_dir().join(format!("strata-app-update-{version}"));
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let installer = dir.join("installer.exe");
std::fs::write(&installer, bytes).map_err(|e| e.to_string())?;
std::process::Command::new(&installer)
.args(["/P", "/R", "/UPDATE"])
.creation_flags(CREATE_BREAKAWAY_FROM_JOB | DETACHED_PROCESS)
.spawn()
.map(|_| ())
.map_err(|e| format!("could not start the installer outside the app: {e}"))
}
/// Elsewhere the plugin's own install is used (the installer replaces the app in place).
#[cfg(not(windows))]
fn launch_installer(_version: &str, _bytes: &[u8]) -> Result<(), String> {
Err("not Windows".into())
}
fn respond(stream: &mut TcpStream, status: &str, body: &serde_json::Value) {
let text = body.to_string();
let _ = stream.write_all(
format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{text}",
text.len()
)
.as_bytes(),
);
}
fn same(a: &str, b: &str) -> bool {
a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
fn handle(mut stream: TcpStream, app: &AppHandle, token: &str, progress: &Arc<Mutex<Progress>>) {
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let mut buf = Vec::new();
let mut chunk = [0u8; 1024];
while !buf.windows(4).any(|w| w == b"\r\n\r\n") && buf.len() < 8192 {
match stream.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => buf.extend_from_slice(&chunk[..n]),
}
}
let head = String::from_utf8_lossy(&buf).to_string();
let mut lines = head.lines();
let request = lines.next().unwrap_or_default().to_string();
let supplied = lines
.find_map(|l| l.strip_prefix("authorization: ").or_else(|| l.strip_prefix("Authorization: ")))
.map(|v| v.trim().trim_start_matches("Bearer ").to_string())
.unwrap_or_default();
if !same(&supplied, token) {
return respond(&mut stream, "401 Unauthorized", &serde_json::json!({ "error": "not allowed" }));
}
let mut parts = request.split_whitespace();
let (method, path) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
match (method, path) {
("GET", "/app-update/check") => match tauri::async_runtime::block_on(check(app)) {
Ok(value) => respond(&mut stream, "200 OK", &value),
Err(e) => respond(&mut stream, "502 Bad Gateway", &serde_json::json!({ "error": e })),
},
("POST", "/app-update/install") => {
{
let mut p = progress.lock().unwrap();
if p.state == "downloading" || p.state == "installing" {
return respond(&mut stream, "409 Conflict", &serde_json::json!({ "error": "An app update is already running." }));
}
*p = Progress { state: "downloading", ..Default::default() };
}
tauri::async_runtime::spawn(install(app.clone(), progress.clone()));
respond(&mut stream, "202 Accepted", &progress.lock().unwrap().json());
}
("GET", "/app-update/status") => respond(&mut stream, "200 OK", &progress.lock().unwrap().json()),
_ => respond(&mut stream, "404 Not Found", &serde_json::json!({ "error": "unknown route" })),
}
}
/// Open the bridge on a free loopback port. Returns None if the listener cannot be bound (the app then simply has no
/// in-app update; the Terminal's `strata update --app` still works).
pub fn start(app: &AppHandle, token: String) -> Option<Bridge> {
let listener = TcpListener::bind(("127.0.0.1", 0)).ok()?;
let port = listener.local_addr().ok()?.port();
let progress = Arc::new(Mutex::new(Progress::default()));
let app = app.clone();
let secret = token.clone();
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
handle(stream, &app, &secret, &progress);
}
});
Some(Bridge { url: format!("http://127.0.0.1:{port}"), token })
}
/// Environment for the App Host: where the bridge is, which app version this is.
#[allow(dead_code)]
pub fn apply_env(cmd: &mut std::process::Command, app: &AppHandle, bridge: Option<&Bridge>) {
cmd.env("STRATA_APP_VERSION", app.package_info().version.to_string());
if let Some(bridge) = bridge {
cmd.env("STRATA_SHELL_BRIDGE", &bridge.url).env("STRATA_SHELL_TOKEN", &bridge.token);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn token_comparison_needs_every_byte() {
assert!(same("abc123", "abc123"));
assert!(!same("abc123", "abc124"));
assert!(!same("abc123", "abc12"));
assert!(!same("", "x"));
}
#[test]
fn progress_reports_idle_until_something_starts() {
let idle = Progress::default().json();
assert_eq!(idle["state"], "idle");
let p = Progress { state: "downloading", downloaded: 10, total: 100, version: Some("0.2.0".into()), error: None };
assert_eq!(p.json()["downloaded"], 10);
assert_eq!(p.json()["version"], "0.2.0");
}
#[test]
fn only_https_or_loopback_endpoints_may_override_the_configured_one() {
for (value, ok) in [
("https://updates.example.com/latest.json", true),
("http://127.0.0.1:19080/app/latest.json", true),
("http://localhost:19080/latest.json", true),
("http://example.com/latest.json", false),
("file:///etc/passwd", false),
] {
std::env::set_var(ENDPOINT_ENV, value);
assert_eq!(endpoint_override().is_some(), ok, "{value}");
}
std::env::remove_var(ENDPOINT_ENV);
assert!(endpoint_override().is_none());
}
}
@@ -0,0 +1,76 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Strata",
"identifier": "ai.strata.desktop",
"build": {
"frontendDist": "../../host/dist"
},
"app": {
"withGlobalTauri": false,
"windows": [],
"security": {
"csp": null,
"dangerousDisableAssetCspModification": false
}
},
"bundle": {
"active": true,
"targets": [
"dmg",
"app",
"nsis",
"appimage",
"deb"
],
"icon": [
"icons/icon.png",
"icons/icon.ico"
],
"category": "DeveloperTool",
"shortDescription": "Local AI, tuned to one model.",
"longDescription": "Strata runs one local model, tuned to your machine. Desktop and Terminal share the same model inventory, profiles, runtime and agent sessions.",
"resources": {
"../../host/dist": "host/dist",
"../../host/server": "host/server",
"../../host/package.json": "host/package.json",
"resources/node": "node",
"resources/control": "control",
"resources/harness": "harness",
"resources/engine-bundle": "engine-bundle"
},
"linux": {
"appimage": {
"bundleMediaFramework": true
}
},
"macOS": {
"minimumSystemVersion": "15.0",
"entitlements": "entitlements.plist"
},
"createUpdaterArtifacts": false,
"windows": {
"nsis": {
"installMode": "currentUser",
"template": "nsis/installer.nsi",
"headerImage": "nsis/header.bmp",
"sidebarImage": "nsis/sidebar.bmp",
"installerIcon": "icons/icon.ico",
"compression": "lzma",
"languages": [
"English"
]
}
}
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEI2QjA5OTk5MDU1MjFGNUUKUldSZUgxSUZtWm13dHNGRU40N2xOUjdZZGpvcGl0NTB2WGxnS3VTc2RlakpSbnBxUkxndHNFY0oK",
"endpoints": [
"https://github.com/Niko1221/Strata/releases/latest/download/latest.json"
],
"windows": {
"installMode": "passive"
}
}
}
}
@@ -0,0 +1,5 @@
{
"bundle": {
"createUpdaterArtifacts": true
}
}
@@ -0,0 +1,7 @@
{
"bundle": {
"resources": {
"resources/engine-bundle": "engine-bundle"
}
}
}
@@ -0,0 +1,7 @@
{
"bundle": {
"resources": {
"resources/engine-bundle": null
}
}
}
@@ -0,0 +1,98 @@
STRATA @APP_VERSION@ FOR LINUX - TESTER BUILD FOR AMD RX 7000 (RDNA3) CARDS (RX 7900 XTX)
=====================================================================
This is a private test version of Strata for Linux with an AMD graphics card. Please keep it to yourself: it is not a public release.
THIS BUILD IS FOR AMD RX 7000 (RDNA3) CARDS ONLY (RX 7900 XTX, RX 7900 XT, RX 7800 XT, RX 7700 XT, RX 7600; gfx1100 / gfx1101 / gfx1102). If your card is from another family the engine will not start and says
so in one line; ask for the other build (the RX 9000 build: Strata-tester-linux-amd-rx9070.AppImage).
You have two programs; try either or both:
1. The desktop app: @APPIMAGE@ (about @SIZE_GB:@APPIMAGE@@ GB)
2. The terminal app: Strata-Terminal-Linux-tester-amd-rx7900.zip (about @SIZE_GB:Strata-Terminal-Linux-tester-amd-rx7900.zip@ GB)
Each one carries its own AI engine, so there is no engine to download. Only the AI model itself is downloaded when you pick one.
Checks (sha256; to check your copy type sha256sum <file> - the long number must be the same):
@APPIMAGE@ @SHA256:@APPIMAGE@@
Strata-Terminal-Linux-tester-amd-rx7900.zip @SHA256:Strata-Terminal-Linux-tester-amd-rx7900.zip@
WHAT YOU NEED
-------------
* Ubuntu 22.04 or newer, 64-bit.
* An AMD RX 7000 (RDNA3) graphics card (RX 7900 XTX, RX 7900 XT, RX 7800 XT, RX 7700 XT, RX 7600; gfx1100 / gfx1101 / gfx1102). No ROCm and no extra driver to install: the engine brings its own ROCm libraries, and the AMD
kernel driver (amdgpu) is already part of the Linux kernel. To check that the kernel sees your card, type: ls /dev/kfd /dev/dri
You should see /dev/kfd and a renderD128 line. If /dev/kfd is missing, tell us your kernel (uname -r) and what "lspci | grep -i vga" prints.
* Your user must be in the groups "render" and "video". This is the one setting the engine needs. Type once:
sudo usermod -aG render,video $USER
then LOG OUT AND LOG IN AGAIN (or reboot). Check with the command id - it must list render and video. Without this the engine says
something like "No device of requested type available" or cannot open /dev/kfd.
* 32 GB of RAM or more is best (the model list shows what fits your computer). The AI model's big parts live in your RAM; your card
holds the rest. Your RX 7900 XTX has 24 GB: the 32K or 64K context the app suggests is a good start.
* Disk: about 3 GB for the program and engine, plus 40 to 70 GB for each model you download (a fast NVMe disk is best).
THE DESKTOP APP (AppImage)
--------------------------
1. Save the file somewhere you can find it, for example your Downloads folder.
2. Make it runnable: right-click > Properties > Permissions > "Allow executing file as program", or in a terminal:
chmod +x @APPIMAGE@
3. Install FUSE 2 once, if your system does not have it (AppImages need it; Ubuntu 26.04 does not install it any more):
Ubuntu 22.04: sudo apt install libfuse2 Ubuntu 24.04 and 26.04: sudo apt install libfuse2t64
Without FUSE you can still run it with: ./@APPIMAGE@ --appimage-extract-and-run
4. Start it by double-click, or from a terminal (a terminal also shows messages if something goes wrong):
./@APPIMAGE@
The very first start takes about a minute longer: the engine that came with the app is unpacked into ~/.local/share/strata.
Then open the Models page, pick a model and press the install button. A model download is big; it carries on where it stopped if it is interrupted.
Closing the window stops Strata and the engine. To stop a running Strata from a terminal: ./@APPIMAGE@ --quit
For the assistant (chat that works on files and runs tools) choose a context of 32K or more when you load the model; a smaller context is too small for the assistant's instructions.
@INCLUDE:common-troubleshoot.txt@
Please tell us about the window: which Linux and desktop (for example "Ubuntu 24.04, GNOME, Wayland"), your graphics driver, and whether the Strata window showed up
and worked: yes / opened in the browser instead / blank / closed by itself.
THE TERMINAL APP (zip)
----------------------
unzip Strata-Terminal-Linux-tester-amd-rx7900.zip
cd strata-tester-linux-amd-rx7900
sh install-tester.sh
strata launch
It needs python3, curl and tar (normally present). Everything is explained in README-TESTER.md inside the zip (AI-SETUP.md is the same for an AI assistant:
give it that file and it can do the setup for you). The installer starts a tiny web server on your own computer only and stops it again; nothing is sent anywhere.
WHAT TO SEND BACK
-----------------
* The desktop app: Settings > Engine > Diagnostics > View logs > Save logs. Send the saved file. If the window crashed or would not open, run
./@APPIMAGE@ --save-logs in a terminal instead and send the file it writes in your Downloads folder (it includes the crash log).
* The terminal app: the output of strata doctor (and uname -r , id , ls /dev/kfd /dev/dri ).
* The speed: the tokens-per-second numbers. The app shows "generating - N tok/s" while it answers. In the terminal app,
with the server running: strata bench run --url http://127.0.0.1:8080 --suite serving-smoke --repeat 2 --out ~/strata-bench-1
prints "output ... tok/s" lines; please send ~/strata-bench-1/results.json too.
A line like "model iq2_xs, 32K context, RX 7900 XTX: 40 tok/s" is perfect.
* A few words about what you did and what you saw (a photo of the screen is fine).
Please do not send API keys.
WHAT WE TESTED AND WHAT WE DID NOT
----------------------------------
* NOT TESTED by us on any RDNA3 card (RX 7000 series): we have no such card. The engine and the libraries inside contain code for gfx1100, gfx1101 and
gfx1102 (we checked the files), but this packaged build has never run on real hardware. Earlier engines built from source were run by community
members on an RX 7900 XTX and an RX 7800 XT (see docs/AMD_HIP.md in the Strata repository), which is why we expect it to work. Expect problems; every
report helps. This is the most important thing to know.
* The same program was tested on an RDNA4 card (AMD Radeon AI PRO R9700) under Ubuntu 24.04: it loads a model, answers, runs tool calls and stops cleanly.
The RDNA3 code is the same source compiled for your card.
* NOT tested by us either: the app window on a real desktop (our test box has no screen).
* Pictures (image input) are on by default. The picture reader runs on the processor (CPU) for a card under 24 GB and on the graphics card from 24 GB, so
your 24 GB RX 7900 XTX uses the card's reader (strata-vision-hip, for gfx1100 / gfx1101 / gfx1102) and a 20 GB RX 7900 XT or a 16 GB RX 7800 XT uses the CPU
reader. The card's reader compiles for RDNA3 but has never run on an RDNA3 card here (we ran it on an R9700, RDNA4). If it cannot start, Strata uses the
CPU reader by itself. You can switch it per model. Please tell us whether pictures worked.
* Speed is not final; treat the numbers as a baseline.
WHERE THINGS ARE (to remove Strata completely, delete the files and these folders)
---------------------------------------------------------------------------------
~/.strata settings, chats, prepared model files
~/.local/share/strata the unpacked engine and the terminal app, and logs/ (what the app printed, and a crash log if the window ever crashes)
~/.local/bin/strata the terminal app's command
~/Documents/Strata downloaded models (Models) and your work folder (Workspace)
@@ -0,0 +1,94 @@
STRATA @APP_VERSION@ FOR LINUX - TESTER BUILD FOR AMD RX 9000 (RDNA4) CARDS (RX 9070 XT)
=====================================================================
This is a private test version of Strata for Linux with an AMD graphics card. Please keep it to yourself: it is not a public release.
THIS BUILD IS FOR AMD RX 9000 (RDNA4) CARDS ONLY (RX 9070 XT, RX 9070, RX 9060 XT, AI PRO R9700; gfx1200 / gfx1201). If your card is from another family the engine will not start and says
so in one line; ask for the other build (the RX 7000 build: Strata-tester-linux-amd-rx7900.AppImage).
You have two programs; try either or both:
1. The desktop app: @APPIMAGE@ (about @SIZE_GB:@APPIMAGE@@ GB)
2. The terminal app: Strata-Terminal-Linux-tester-amd-rx9070.zip (about @SIZE_GB:Strata-Terminal-Linux-tester-amd-rx9070.zip@ GB)
Each one carries its own AI engine, so there is no engine to download. Only the AI model itself is downloaded when you pick one.
Checks (sha256; to check your copy type sha256sum <file> - the long number must be the same):
@APPIMAGE@ @SHA256:@APPIMAGE@@
Strata-Terminal-Linux-tester-amd-rx9070.zip @SHA256:Strata-Terminal-Linux-tester-amd-rx9070.zip@
WHAT YOU NEED
-------------
* Ubuntu 22.04 or newer, or CachyOS / Arch Linux (rolling), 64-bit.
* An AMD RX 9000 (RDNA4) graphics card (RX 9070 XT, RX 9070, RX 9060 XT, AI PRO R9700; gfx1200 / gfx1201). No ROCm and no extra driver to install: the engine brings its own ROCm libraries, and the AMD
kernel driver (amdgpu) is already part of the Linux kernel. To check that the kernel sees your card, type: ls /dev/kfd /dev/dri
You should see /dev/kfd and a renderD128 line. If /dev/kfd is missing, tell us your kernel (uname -r) and what "lspci | grep -i vga" prints.
* Your user must be in the groups "render" and "video". This is the one setting the engine needs. Type once:
sudo usermod -aG render,video $USER
then LOG OUT AND LOG IN AGAIN (or reboot). Check with the command id - it must list render and video. Without this the engine says
something like "No device of requested type available" or cannot open /dev/kfd.
* 32 GB of RAM or more is best (the model list shows what fits your computer). The AI model's big parts live in your RAM; your card
holds the rest. Your RX 9070 XT has 16 GB: start with the 32K context the app suggests.
* Disk: about 3 GB for the program and engine, plus 40 to 70 GB for each model you download (a fast NVMe disk is best).
THE DESKTOP APP (AppImage)
--------------------------
1. Save the file somewhere you can find it, for example your Downloads folder.
2. Make it runnable: right-click > Properties > Permissions > "Allow executing file as program", or in a terminal:
chmod +x @APPIMAGE@
3. Install FUSE 2 once, if your system does not have it (AppImages need it; Ubuntu 26.04 does not install it any more):
CachyOS / Arch: sudo pacman -S fuse2 Ubuntu 22.04: sudo apt install libfuse2 Ubuntu 24.04 and 26.04: sudo apt install libfuse2t64
Without FUSE you can still run it with: ./@APPIMAGE@ --appimage-extract-and-run
4. Start it by double-click, or from a terminal (a terminal also shows messages if something goes wrong):
./@APPIMAGE@
The very first start takes about a minute longer: the engine that came with the app is unpacked into ~/.local/share/strata.
Then open the Models page, pick a model and press the install button. A model download is big; it carries on where it stopped if it is interrupted.
Closing the window stops Strata and the engine. To stop a running Strata from a terminal: ./@APPIMAGE@ --quit
For the assistant (chat that works on files and runs tools) choose a context of 32K or more when you load the model; a smaller context is too small for the assistant's instructions.
@INCLUDE:common-troubleshoot.txt@
Please tell us about the window: which Linux and desktop (for example "CachyOS, KDE Plasma, Wayland"), your graphics driver, and whether the Strata window showed up
and worked: yes / opened in the browser instead / blank / closed by itself.
THE TERMINAL APP (zip)
----------------------
unzip Strata-Terminal-Linux-tester-amd-rx9070.zip
cd strata-tester-linux-amd-rx9070
sh install-tester.sh
strata launch
It needs python3, curl and tar (normally present). Everything is explained in README-TESTER.md inside the zip (AI-SETUP.md is the same for an AI assistant:
give it that file and it can do the setup for you). The installer starts a tiny web server on your own computer only and stops it again; nothing is sent anywhere.
WHAT TO SEND BACK
-----------------
* The desktop app: Settings > Engine > Diagnostics > View logs > Save logs. Send the saved file. If the window crashed or would not open, run
./@APPIMAGE@ --save-logs in a terminal instead and send the file it writes in your Downloads folder (it includes the crash log).
* The terminal app: the output of strata doctor (and uname -r , id , ls /dev/kfd /dev/dri ).
* The speed: the tokens-per-second numbers. The app shows "generating - N tok/s" while it answers. In the terminal app,
with the server running: strata bench run --url http://127.0.0.1:8080 --suite serving-smoke --repeat 2 --out ~/strata-bench-1
prints "output ... tok/s" lines; please send ~/strata-bench-1/results.json too.
A line like "model iq2_xs, 32K context, RX 9070 XT: 40 tok/s" is perfect.
* A few words about what you did and what you saw (a photo of the screen is fine).
Please do not send API keys.
WHAT WE TESTED AND WHAT WE DID NOT
----------------------------------
* TESTED by us: this engine on an AMD Radeon AI PRO R9700 (RDNA4, the same chip family, gfx1201, as the RX 9070 XT) under Ubuntu 24.04: it loads a
model, answers, runs tool calls, and stops cleanly, from the app's host and from the terminal app.
* NOT tested by us: an RX 9070 XT itself, CachyOS, the app window on a real desktop (our test box has no screen). A failure on your computer is a finding we want.
* Pictures (image input) are on by default. The picture reader runs on the processor (CPU) for a card under 24 GB, so your 16 GB RX 9070 XT
uses the CPU reader (a few seconds per picture, nothing taken from the card's memory). The graphics-card reader (strata-vision-hip, for
gfx1200 / gfx1201) is in this build for cards of 24 GB and up; we tested it on the 32 GB R9700 (0.06 s for a small picture against 3.1 s on the
CPU) and tested the CPU reader. If the card's reader cannot start, Strata uses the CPU reader by itself. You can switch it per model.
* Speed is not final; treat the numbers as a baseline.
WHERE THINGS ARE (to remove Strata completely, delete the files and these folders)
---------------------------------------------------------------------------------
~/.strata settings, chats, prepared model files
~/.local/share/strata the unpacked engine and the terminal app, and logs/ (what the app printed, and a crash log if the window ever crashes)
~/.local/bin/strata the terminal app's command
~/Documents/Strata downloaded models (Models) and your work folder (Workspace)
@@ -0,0 +1,72 @@
STRATA FOR LINUX - TESTER BUILD (Strata @APP_VERSION@)
=====================================================
This is a test version of the Strata desktop app for Linux. The AI engine is already inside the file, so there is nothing to
install for it and no engine to download. Only the AI model itself is downloaded (from Hugging Face), when you pick one.
Please keep this file to yourself: it is not a public release.
File: @APPIMAGE@ (about @SIZE_GB:@APPIMAGE@@ GB)
Checks: sha256 @SHA256:@APPIMAGE@@
To check your copy: sha256sum @APPIMAGE@ - the long number must be the same.
WHAT YOU NEED
-------------
* Ubuntu 22.04 or newer (22.04, 24.04 and 26.04 are what it was built for), or Fedora 44. 64-bit, on a normal desktop session.
* An NVIDIA graphics card, RTX 20 series or newer (built and checked for RTX 30 cards; the RTX 40 and RTX 50 series are inside too).
If the computer also has AMD or Intel graphics (for example a Ryzen with built-in graphics), Strata ignores them and uses the NVIDIA card.
* The NVIDIA driver, version 580.65 or newer (the CUDA 13 engine in this file needs it).
To see yours, open a terminal and type: nvidia-smi - the number next to "Driver Version" is it.
If the driver is older, Strata tells you in one line which version to install. To install a newer one:
Ubuntu: open "Software & Updates" > "Additional Drivers", or run: sudo ubuntu-drivers install and restart.
Fedora: use the NVIDIA driver from RPM Fusion (akmod-nvidia), and sudo dnf install xorg-x11-drv-nvidia-cuda so that nvidia-smi exists.
* 32 GB of RAM or more is best (the model list shows what fits your computer).
* Disk: about 3 GB for the app and its engine, plus 40 to 70 GB for each model you download.
* FUSE 2 (libfuse2). Ubuntu 26.04 does not have it by default; install it once:
Ubuntu 22.04: sudo apt install libfuse2 Ubuntu 24.04 / 26.04: sudo apt install libfuse2t64
(or skip it by running the file with --appimage-extract-and-run , see "IF IT DOES NOT START" below).
START IT
--------
1. Save the file somewhere you can find it, for example your Downloads folder.
2. Make it runnable. Either right-click the file > Properties > Permissions > "Allow executing file as program",
or in a terminal:
chmod +x @APPIMAGE@
3. Double-click it, or start it from a terminal (a terminal also shows messages if something goes wrong):
./@APPIMAGE@
The very first start takes about a minute longer: the engine that came with the app is unpacked into your home folder
(~/.local/share/strata). Later starts are quick. Then open the Models page, pick a model and press the install button.
A model download is big; it carries on where it stopped if it is interrupted.
Closing the window stops Strata and the engine. (In browser mode closing the tab does not: see BROWSER MODE below.)
To stop a running Strata from a terminal: ./@APPIMAGE@ --quit
@INCLUDE:common-troubleshoot.txt@
PLEASE TELL US ABOUT THE WINDOW
-------------------------------
This is one of the first times the Linux window runs on real graphics desktops. In your report please say:
- which Linux and which desktop (for example "Ubuntu 26.04, GNOME, Wayland" or "Fedora 44, GNOME, Wayland"),
- your graphics card and driver version (nvidia-smi),
- whether the Strata window showed up and worked: yes / opened in the browser instead / blank / closed by itself,
- for a blank or closed window: what you typed (any of the lines above) and what changed.
If you started it from a terminal, copy what it printed there.
WHAT TO SEND BACK
-----------------
Open Settings > Engine > Diagnostics > View logs > Save logs. Send the saved file, plus a few words about what you did and what you saw
(a photo of the screen is fine).
If the window crashed or would not open, the app window is not available for that: run ./@APPIMAGE@ --save-logs in a terminal instead.
It writes strata-logs-<date>.txt in your Downloads folder (including the crash log of the window); send that file.
WHERE THINGS ARE (to remove Strata completely, delete the file and these folders)
--------------------------------------------------------------------------------
~/.strata settings, chats, prepared model files
~/.local/share/strata the unpacked engine, and logs/ (what the app printed, and a crash log if the window ever crashes)
~/Documents/Strata downloaded models (Models) and your work folder (Workspace)
@@ -0,0 +1,39 @@
STRATA FOR MAC - APP (Strata @APP_VERSION@)
==========================================
This is the Strata desktop app for Macs with Apple silicon (M1 or newer). The AI engine (it runs on the Mac's graphics processor through
Metal) is already inside the app, so there is nothing to install for it and no engine to download. Only the AI model itself is
downloaded (from Hugging Face), when you pick one.
File: @APPIMAGE@ (about @SIZE_GB:@APPIMAGE@@ GB)
Checks: sha256 @SHA256:@APPIMAGE@@
To check your copy, in the Terminal app: shasum -a 256 @APPIMAGE@ - the long number must be the same.
WHAT YOU NEED
-------------
* A Mac with Apple silicon (M1 or newer) and macOS 15 or newer (the engine needs macOS 15). Intel Macs are not supported.
* Memory: 32 GB or more is best. The model list shows what fits your Mac.
* Disk: about 1 GB for the app, plus 40 to 70 GB for each model you download.
START IT
--------
1. Double-click @APPIMAGE@. A window opens with Strata and the Applications folder.
2. Drag Strata onto Applications.
3. Open Strata from Applications (or Launchpad). The first start takes a little longer, because the engine inside the app is copied
into your home folder. Then open the Models page, pick a model and press the install button. A model download is big; it carries
on where it stopped if it is interrupted.
Closing the window stops Strata and its engine.
Pictures: on by default. This Mac build reads them on the Mac's GPU (under a second for a small picture on an M4).
@INCLUDE:common-gatekeeper-mac.txt@
WHAT TO SEND BACK
-----------------
Open Settings > Engine > Diagnostics > View logs > Save logs. Send the saved file, plus a few words about what you did and what you saw
(a photo of the screen is fine).
@@ -0,0 +1,27 @@
IF MACOS WILL NOT OPEN IT ("damaged", "cannot be opened", "unidentified developer")
----------------------------------------------------------------------------------
Nothing is wrong with the file. macOS puts a "downloaded from the internet" mark (the quarantine flag) on everything a browser or
Mail saves, and it only lets a marked program run if Apple has checked it. There are two kinds of build:
* A NOTARISED build (Apple has checked it; Strata signs and notarises its release builds). It just opens:
double-click the .dmg, drag Strata onto Applications, open Strata. The first time, macOS says "Strata is an app downloaded from
the Internet. Are you sure you want to open it?" - press Open. That is the same for every app you download; there is nothing to
type and no setting to change. A notarised .zip of the Terminal works the same way: unzip it and run it.
To see which kind you have: spctl -a -vv /Applications/Strata.app
A notarised build answers "accepted" and "source=Notarized Developer ID".
* A build that is NOT notarised (a test build sent to you before it was signed, or one you built yourself). macOS may say
"Strata is damaged and can't be opened. You should move it to the Trash" or "Apple could not verify Strata is free of malware".
Do NOT move it to the Trash. The file is fine; you tell macOS once that you trust it by removing the download mark.
Open the Terminal app (Finder, Applications, Utilities, Terminal) and type ONE of these, matching what you have:
the .dmg file, before opening it: xattr -dr com.apple.quarantine ~/Downloads/@APPIMAGE@
the app, after dragging it over: xattr -dr com.apple.quarantine /Applications/Strata.app
an unzipped Terminal folder: xattr -dr com.apple.quarantine <the folder you unzipped>
(If the file is somewhere other than Downloads, type the path to it; you can drag the file from Finder into the Terminal window to
write its path for you.) Then open it again as usual. If macOS only says "cannot be opened because the developer cannot be
verified" (not "damaged"), there is a second way without the Terminal: try to open it once, then System Settings > Privacy &
Security, scroll down to the message about Strata and press "Open Anyway".
Installs that use "curl ... | sh" never get the download mark, so they need none of this.
@@ -0,0 +1,42 @@
IF IT DOES NOT START
--------------------
* A message about "FUSE" or "libfuse.so.2". AppImages need FUSE 2, and Ubuntu 26.04 does not install it any more
(this is what happens on a fresh Ubuntu 26.04: "dlopen(): error loading libfuse.so.2"). Install it once:
Ubuntu 22.04: sudo apt install libfuse2
Ubuntu 24.04 and 26.04: sudo apt install libfuse2t64
Fedora: sudo dnf install fuse fuse-libs
CachyOS / Arch: sudo pacman -S fuse2
Then start it again. Without FUSE you can still run it, a little slower to start because it unpacks itself first:
./@APPIMAGE@ --appimage-extract-and-run
* The app window does not open, or it closes by itself. This build does not give up: Strata keeps running and opens in your web
browser instead ("browser mode"). You will see a notification and, in a terminal, this line:
Strata opened in your browser because the app window couldn't start on this computer.
The terminal also says "The app window crashed (signal 11 ...)" and where the crash log is. Everything works in the browser tab except
updating the app itself (see BROWSER MODE below). Please tell us it happened, with your Linux, desktop and graphics driver, and run
./@APPIMAGE@ --save-logs
which puts the crash log and the other logs into one file in your Downloads folder (it needs no window). Send us that file.
A crash during the very first start does not stop the engine's unpacking: Strata keeps working in the browser.
* The window opens but stays blank or white: this build already switches off WebKit's DMA-BUF drawing, which is the usual cause.
If it is still blank, try these one at a time, and tell us which one (if any) helped:
WEBKIT_DISABLE_COMPOSITING_MODE=1 ./@APPIMAGE@
GDK_BACKEND=x11 ./@APPIMAGE@
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./@APPIMAGE@
or just use browser mode (next section).
* Inside a virtual machine or a remote desktop without graphics acceleration the window may be blank or may close at once.
Run Strata on the computer's own desktop, not through a remote session.
BROWSER MODE (Strata in your web browser instead of the app window)
------------------------------------------------------------------
Start it on purpose with:
./@APPIMAGE@ --browser (or: STRATA_UI=browser ./@APPIMAGE@)
Strata starts its engine and opens http://127.0.0.1:47831/ in your default browser. The address works on your own computer only; nothing is
reachable from the network.
* Closing the browser tab does NOT stop Strata or its engine, because the tab is only a view. To stop everything, use the menu
(the "More" entry at the bottom left) > "Quit Strata", or in a terminal: ./@APPIMAGE@ --quit
* Starting the AppImage again while Strata runs does not start a second copy: it opens another tab (browser mode) or brings the window forward.
* What works in a browser tab as in the window: chat, models, Monitor, Settings, choosing a folder (a folder dialog needs zenity or kdialog;
without one Strata asks you to type the folder path), "open file" and "show in folder" (Strata opens them for you), downloads, the assistant.
* What does NOT work in browser mode: updating the app itself (Settings > Updates says so in plain words; the engine updates still work and
you can update the app by starting it from its icon without --browser), and the app window's own title bar and window buttons (your
browser has its own). There is no desktop notification from the page itself; Strata sends the one it needs.
+8
View File
@@ -0,0 +1,8 @@
node_modules/
.strata/
.strata-ui-preview/
.localhost-*/
.shots/
tmp/
.env*
.DS_Store
+12
View File
@@ -0,0 +1,12 @@
# Strata app source
Start with [the complete developer handoff](../handoff.md) and [the runbook](../docs/RUNBOOK.md).
```sh
npm ci
npm run preview:ui
```
The built UI is included. To rebuild after source edits, run `npm run build`. `preview:ui` uses isolated simulated data; `npm run dev` connects the normal host.
The previous project README is retained in [docs/README-historical.md](docs/README-historical.md). It contains older implementation status and is historical reference.
@@ -0,0 +1,183 @@
# Finding dispositions — 7 October 2026
Stable `F001`–`F177` IDs follow the original `findings.json` order. The task reference also gives the number within its required or optional table.
| ID | Task finding | Priority | State | Disposition | Resolution |
|---|---|---|---|---|---|
| F001 | T01 required #1 | H | chat-empty | implemented | Formatter reads the actual loaded record; simulated preview uses the design family, real-engine mode retains its verified catalog. |
| F002 | T11 required #1 | M | chat-empty | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F003 | T05 required #1 | M | chat-empty | implemented | Hide idle chat statistics; show live estimated speed/tokens until reported usage arrives. Context comes from engine config. Clamp and flag impossible memory readings without asserting unobserved swapping. |
| F004 | T11 required #2 | M | chat-empty | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F005 | T11 optional #1 | L | chat-empty | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F006 | T05 required #2 | H | chat-generating | implemented | Hide idle chat statistics; show live estimated speed/tokens until reported usage arrives. Context comes from engine config. Clamp and flag impossible memory readings without asserting unobserved swapping. |
| F007 | T11 required #3 | M | chat-generating | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F008 | T05 optional #1 | L | chat-generating | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F009 | T11 optional #2 | L | chat-generating | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F010 | T11 optional #3 | L | chat-generating | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F011 | T01 required #2 | H | chat-model-picker | closed-by-removal | Closed by removal: chat version chip links to Model; no multi-model picker remains. |
| F012 | T11 required #4 | M | chat-model-picker | closed-by-removal | Closed by removal of the model-picker surface; running status is a non-action status on Model. |
| F013 | T11 required #5 | M | chat-template | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F014 | T11 optional #4 | L | chat-template | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F015 | T11 required #6 | M | chat-session-log | closed-by-removal | Closed by hiding session-log export until it is implemented. |
| F016 | T07 optional #1 | L | chat-session-log | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F017 | T11 required #7 | M | chat-slash-commands | implemented | Removed duplicate /clear; /new is the single new-chat command. |
| F018 | T11 required #8 | M | chat-slash-commands | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F019 | T11 optional #5 | L | chat-slash-commands | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F020 | T11 optional #6 | L | chat-slash-commands | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F021 | T04 required #1 | M | chat-open-website-invalid | implemented | Shared ErrorNotice sanitizes Fixture prefixes and supports cause, recovery text and retry. Applied to composer/website, models, skills, tasks, setup, Serving and Cloudflare. Request states have semantic colors. |
| F022 | T11 optional #7 | L | chat-open-website-invalid | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F023 | T05 required #3 | M | chat-showcase-code | implemented | Hide idle chat statistics; show live estimated speed/tokens until reported usage arrives. Context comes from engine config. Clamp and flag impossible memory readings without asserting unobserved swapping. |
| F024 | T11 optional #8 | L | chat-showcase-code | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F025 | T03 required #1 | H | GLOBAL | implemented | Adapted colors to measured contrast: light #10b981 uses dark ink; dark uses #087654 with white ink to meet both text contrast and the app surface-luminance budget. |
| F026 | T11 required #9 | M | chat-subagents-statuses | implemented | View log exposes the recorded failure. No unsupported backend retry is implied. |
| F027 | T11 optional #9 | L | chat-session-statistics | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F028 | T11 required #10 | M | chat-context-length | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F029 | T11 optional #10 | L | chat-context-length | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F030 | T11 required #11 | M | chat-approval-collapsed | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F031 | T11 optional #11 | L | chat-approval-collapsed | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F032 | T11 required #12 | M | chat-approval-approved | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F033 | T11 optional #12 | L | chat-approval-approved | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F034 | T06 required #1 | H | chat-response-actions | implemented | Response actions use a horizontal row below content and a portaled floating menu, so opening More never reflows or clips the response. |
| F035 | T03 required #2 | M | GLOBAL-chat | implemented | Empty textarea is one line and grows to 180px. Three stats chips remain one compact row directly below it, preserving the prior requested separate popovers. |
| F036 | T11 optional #13 | L | chat-gif-paused | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F037 | T04 optional #1 | L | chat-markdown-table | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F038 | T11 optional #14 | L | chat-artifact-cards | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F039 | T11 required #13 | M | chat-artifact-cards | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F040 | T11 optional #15 | L | chat-artifact-actions | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F041 | T11 required #14 | M | chat-message-actions | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F042 | T11 optional #16 | L | chat-message-actions | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F043 | T11 required #15 | M | chat-edit-branch | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F044 | T11 optional #17 | L | chat-edit-branch | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F045 | T12 required #1 | M | timeskip-building | implemented | Stable Version A/B labels, readable amber status text, primary Open version B and secondary Compare at completion. The selected example result opens in the preview. |
| F046 | T12 optional #1 | L | timeskip-building | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F047 | T12 required #2 | M | timeskip-* | implemented | Stable Version A/B labels, readable amber status text, primary Open version B and secondary Compare at completion. The selected example result opens in the preview. |
| F048 | T12 required #3 | M | timeskip-complete | implemented | Stable Version A/B labels, readable amber status text, primary Open version B and secondary Compare at completion. The selected example result opens in the preview. |
| F049 | T12 optional #2 | L | timeskip-* | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F050 | T12 optional #3 | L | timeskip-inspect-original | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F051 | T07 required #1 | M | GLOBAL | implemented | Unbuilt controls hidden. Preview badge is shared; estimated/simulated per-value labels remain where removing them would misrepresent data. |
| F052 | T11 required #16 | M | chat-add-menu | implemented | Attach text file inserts inspected text/code into the visible prompt. Binary media remains preview-only because the inference endpoint accepts text. Showcase links moved to Settings About. |
| F053 | T04 required #2 | M | chat-composer-error | implemented | Shared ErrorNotice sanitizes Fixture prefixes and supports cause, recovery text and retry. Applied to composer/website, models, skills, tasks, setup, Serving and Cloudflare. Request states have semantic colors. |
| F054 | T11 optional #18 | L | chat-thinking-menu | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F055 | T11 required #17 | M | chat-tool-access | closed-by-removal | Closed by hiding unbuilt tool-access choices behind a disabled feature flag (T07). |
| F056 | T11 required #18 | M | chat-no-conversations | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F057 | T11 required #19 | M | chat-response-complete | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F058 | T11 required #20 | M | chat-response-complete | implemented | Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About. |
| F059 | T01 required #3 | H | chat-response-complete | implemented | New demo replies use the loaded identity. Existing saved historical messages are preserved. |
| F060 | T01 required #4 | H | models-* | implemented | Loaded-model identity now uses formatModelName. Removed the chat model catalog and multi-model profile flow; Model and Setup share a version ladder. |
| F061 | T09 required #1 | M | models-overview | implemented | Single-model hero, seven version rows, detail action, installed list and shared Setup selection. Fit uses detected memory and context, with only the highest-quality fast fit recommended. Repeated profile warnings and compare trays were removed. |
| F062 | T09 optional #1 | L | models-overview | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F063 | T09 optional #2 | L | models-overview | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F064 | T09 required #2 | M | models-recommendation-details | implemented | Single-model hero, seven version rows, detail action, installed list and shared Setup selection. Fit uses detected memory and context, with only the highest-quality fast fit recommended. Repeated profile warnings and compare trays were removed. |
| F065 | T09 optional #3 | L | models-recommendation-details | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F066 | T09 optional #4 | L | models-filters | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F067 | T09 optional #5 | L | models-filters | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F068 | T01 optional #1 | L | models-file-details | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F069 | T09 optional #6 | L | models-storage | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F070 | T09 required #3 | M | models-context-64k | implemented | One consolidated memory warning and Use shorter context action replace repeated profile dead ends; budgets derive from hardware, not sample 2.1 GB numbers. |
| F071 | T09 required #4 | M | models-none-installed | closed-by-removal | Closed by removing the multi-select compare tray and profile filters. |
| F072 | T09 required #5 | M | models-hardware-unavailable | implemented | Single-model hero, seven version rows, detail action, installed list and shared Setup selection. Fit uses detected memory and context, with only the highest-quality fast fit recommended. Repeated profile warnings and compare trays were removed. |
| F073 | T09 required #6 | M | models-hardware-unavailable-dialog | implemented | Single-model hero, seven version rows, detail action, installed list and shared Setup selection. Fit uses detected memory and context, with only the highest-quality fast fit recommended. Repeated profile warnings and compare trays were removed. |
| F074 | T09 required #7 | M | models-load-confirmation | implemented | Plain switch sentence plus a disclosure of saved Engine context. No unmeasured five-second loading promise. |
| F075 | T09 optional #7 | L | models-large-catalog | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F076 | T09 required #8 | M | models-load-error | implemented | One retry action in the switch dialog and shared sanitized error. Synthetic failed-load visual capture was unavailable; source path reviewed. |
| F077 | T01 required #5 | H | engine-* | implemented | Loaded-model identity now uses formatModelName. Removed the chat model catalog and multi-model profile flow; Model and Setup share a version ladder. |
| F078 | T10 required #1 | M | engine-beginner | implemented | Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar. |
| F079 | T10 required #2 | M | engine-beginner | implemented | Range is filtered against model capabilities, including 1M for the design preview. |
| F080 | T10 required #3 | M | engine-beginner | implemented | Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar. |
| F081 | T10 required #4 | M | engine-* | implemented | Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar. |
| F082 | T10 required #5 | M | engine-resource-controls | implemented | Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar. |
| F083 | T10 optional #1 | L | engine-prompt-batch | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F084 | T10 required #6 | M | engine-expert | implemented | Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar. |
| F085 | T10 optional #2 | L | engine-raw-config | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F086 | T10 optional #3 | L | engine-* | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F087 | T10 required #7 | H | engine-config-invalid | implemented | Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar. |
| F088 | T10 optional #4 | L | engine-discard-confirmation | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F089 | T10 optional #5 | L | engine-actions | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F090 | T01 required #6 | M | engine-adapter-details | implemented | Header uses the actual loaded record; a real adapter may correctly report the original Qwen2.5 test model. |
| F091 | T10 optional #6 | L | engine-adapter-details | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F092 | T10 required #8 | M | engine-expert-advanced | implemented | Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar. |
| F093 | T10 required #9 | M | engine-expert-changed-only-empty | implemented | Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar. |
| F094 | T03 required #3 | M | GLOBAL | implemented | Enabled primary buttons, neutral disabled controls, bright on toggles, brand checkboxes, a compact growing composer, and labelled task actions/detail chrome. |
| F095 | T09 optional #8 | L | models-context-options | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F096 | T10 required #10 | H | engine-expert-* | implemented | Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar. |
| F097 | T10 required #11 | M | engine-expert-server | closed-by-removal | Removed the duplicated unsupported Server access editor; Expert links to Serving. |
| F098 | T04 required #3 | M | serving-requests-all | implemented | Shared ErrorNotice sanitizes Fixture prefixes and supports cause, recovery text and retry. Applied to composer/website, models, skills, tasks, setup, Serving and Cloudflare. Request states have semantic colors. |
| F099 | T13 optional #1 | L | serving-requests-all | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F100 | T13 optional #2 | L | serving-requests-all | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F101 | T01 optional #2 | L | serving-requests-all | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F102 | T04 required #4 | M | serving-request-error | implemented | Shared sanitizer removes Fixture prefix. Synthetic upstream-error visual capture was unavailable. |
| F103 | T13 required #1 | M | serving-request-queued | implemented | Queued cancellation, generated key dialog with copy only for a value, explicit local-network status/action and URL copy, and Connect an app in the empty state. |
| F104 | T13 optional #3 | L | serving-request-done | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F105 | T03 optional #1 | L | GLOBAL-sidebar | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F106 | T13 optional #4 | L | serving-guide-* | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F107 | T13 optional #5 | L | serving-guide-* | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F108 | T13 required #2 | M | serving-key-empty | implemented | Key is generated in the editor draft on open; copy appears only for non-empty text. No key was saved during this review. |
| F109 | T13 optional #6 | L | serving-key-remove-confirmation | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F110 | T13 optional #7 | L | serving-cloudflare-address | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F111 | T04 required #5 | M | serving-cloudflare-error | implemented | Shared ErrorNotice and one retry path; synthetic connector-error visual capture was unavailable. |
| F112 | T13 optional #8 | L | serving-cloudflare-review-quick | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F113 | T13 optional #9 | L | serving-cloudflare-connector-missing | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F114 | T13 optional #10 | L | serving-cloudflare-connected | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F115 | T13 optional #11 | L | serving-tunnel-active | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F116 | T13 optional #12 | L | serving-cloudflare-domain-empty | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F117 | T13 required #3 | M | serving-local-sharing-* | implemented | Queued cancellation, generated key dialog with copy only for a value, explicit local-network status/action and URL copy, and Connect an app in the empty state. |
| F118 | T13 required #4 | M | serving-local-sharing-manage | implemented | Queued cancellation, generated key dialog with copy only for a value, explicit local-network status/action and URL copy, and Connect an app in the empty state. |
| F119 | T13 required #5 | M | serving-local-sharing-active | implemented | Shared local-network state has an amber dot, explicit status and Stop action. Public/local sharing was not enabled for screenshots. |
| F120 | T13 optional #13 | L | serving-key-change | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F121 | T05 required #4 | H | monitor-generating | implemented | Used memory is clamped to total with a warning when the source reports an overflow. The UI does not claim swapping without a signal proving it. |
| F122 | T14 required #1 | M | monitor-* | implemented | Shared-memory labels explain pool overlap and idle states are clear. Memory validation is shared with T05. |
| F123 | T01 required #7 | M | monitor-* | implemented | Loaded-model identity now uses formatModelName. Removed the chat model catalog and multi-model profile flow; Model and Setup share a version ladder. |
| F124 | T14 optional #1 | L | monitor-computer | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F125 | T05 optional #2 | L | monitor-* | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F126 | T03 required #4 | M | skills-* | implemented | Enabled primary buttons, neutral disabled controls, bright on toggles, brand checkboxes, a compact growing composer, and labelled task actions/detail chrome. |
| F127 | T04 required #6 | M | skills-refresh-error | implemented | Retry ErrorNotice sits under the page header. Synthetic service-outage visual capture was unavailable. |
| F128 | T15 optional #1 | L | skills-added | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F129 | T15 optional #2 | L | skills-edit | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F130 | T15 optional #3 | L | skills-overview | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F131 | T04 required #7 | M | GLOBAL | implemented | Central userError sanitization is used by ErrorNotice, including shared ActionError; source review plus unit coverage. |
| F132 | T13 required #6 | M | serving-empty | implemented | Added empty-state Connect an app. Header remains icon-only with an accessible label, honoring the user’s earlier explicit annotation. |
| F133 | T03 required #5 | M | tasks-populated | implemented | Enabled primary buttons, neutral disabled controls, bright on toggles, brand checkboxes, a compact growing composer, and labelled task actions/detail chrome. |
| F134 | T04 required #8 | M | tasks-populated | implemented | Last run failed opens a sanitized ErrorNotice. Synthetic failed-run visual capture was unavailable. |
| F135 | T15 optional #4 | L | tasks-populated | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F136 | T15 required #1 | M | tasks-create-* | implemented | Sans-serif instruction fields; scheduling state distinguishes scheduled and paused tasks; skills scope is explicit. Shared errors, toggles and dropdown layering cover related findings. |
| F137 | T01 optional #3 | L | tasks-new-menu | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F138 | T15 optional #5 | L | tasks-empty | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F139 | T15 optional #6 | L | tasks-ai-blank | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F140 | T02 required #1 | H | tasks-repeat-options | implemented | Opaque dialogs and palettes, explicit overlay layers, dropdowns above their parent dialog, dark scrims and stable scroll gutters. |
| F141 | T15 required #2 | M | tasks-created | implemented | Scheduled creation shows next run or Scheduled while the scheduler computes it, never Paused solely because nextRun is initially empty. |
| F142 | T03 required #6 | M | tasks-detail-* | implemented | Enabled primary buttons, neutral disabled controls, bright on toggles, brand checkboxes, a compact growing composer, and labelled task actions/detail chrome. |
| F143 | T15 optional #7 | L | tasks-result | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F144 | T16 required #1 | M | settings-search | implemented | Settings index follows the visible/search-result section. Setup context controls are inline, and its opaque bounded dialog retains a sticky footer. |
| F145 | T16 optional #1 | L | settings-general | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F146 | T16 optional #2 | L | settings-general | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F147 | T16 optional #3 | L | settings-reading-focus | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F148 | T16 optional #4 | L | settings-storage | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F149 | T02 required #2 | H | setup-computer | implemented | Opaque dialogs and palettes, explicit overlay layers, dropdowns above their parent dialog, dark scrims and stable scroll gutters. |
| F150 | T01 required #8 | H | setup-model | implemented | Setup shares the version ladder and fit recommendation; when no version fits fast, it does not falsely tag a slow version Recommended. |
| F151 | T16 required #2 | M | setup-advanced | implemented | Settings index follows the visible/search-result section. Setup context controls are inline, and its opaque bounded dialog retains a sticky footer. |
| F152 | T09 required #9 | M | setup-model | implemented | Bounded opaque setup with scrollable body and persistent header/footer verified at 1280×720. |
| F153 | T04 required #9 | M | setup-prepare-error | implemented | Preparation error heading and ErrorNotice replace raw fixture text; synthetic prepare-failure visual capture was unavailable. |
| F154 | T16 optional #5 | L | setup-prepare | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F155 | T02 required #3 | M | navigation-rename-chat | implemented | Opaque dialogs and palettes, explicit overlay layers, dropdowns above their parent dialog, dark scrims and stable scroll gutters. |
| F156 | T17 required #1 | M | navigation-rename-chat | implemented | Rename uses a stacked full-width selected input; deletion offers Archive instead; shared overlay/gutter fixes prevent page movement. |
| F157 | T17 required #2 | M | navigation-delete-chat-confirmation | implemented | Rename uses a stacked full-width selected input; deletion offers Archive instead; shared overlay/gutter fixes prevent page movement. |
| F158 | T02 required #4 | M | navigation-command-palette | implemented | Opaque dialogs and palettes, explicit overlay layers, dropdowns above their parent dialog, dark scrims and stable scroll gutters. |
| F159 | T08 required #1 | H | navigation-more | implemented | Engine and singular Model are primary navigation destinations. More contains Serving and Settings. |
| F160 | T17 optional #1 | L | navigation-command-search | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F161 | T17 optional #2 | L | navigation-sidebar-collapsed | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F162 | T18 required #1 | M | preview-* | implemented | Active tabs scroll within their strip with edge fades. Narrow windows use an overlay; wide windows retain enough chat width. Images/PDF share Fit/100% controls and PDF uses icon paging. |
| F163 | T18 required #2 | M | preview-* | implemented | Preview switches to overlay below 1120px available main width; wide-screen chat was measured at 644.6px at a 1654px viewport. |
| F164 | T18 required #3 | M | preview-pdf-* | implemented | Active tabs scroll within their strip with edge fades. Narrow windows use an overlay; wide windows retain enough chat width. Images/PDF share Fit/100% controls and PDF uses icon paging. |
| F165 | T18 optional #1 | L | preview-pdf-actual | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F166 | T18 optional #2 | L | preview-full-screen | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F167 | T18 optional #3 | L | preview-* | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F168 | T18 optional #4 | L | preview-table | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F169 | T02 required #5 | M | dark-* | implemented | Opaque dialogs and palettes, explicit overlay layers, dropdowns above their parent dialog, dark scrims and stable scroll gutters. |
| F170 | T03 required #7 | M | dark-* | implemented | Dark primary is #087654 with white ink: verified contrast and luminance requirements both pass. |
| F171 | T03 optional #2 | L | dark-* | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F172 | T19 optional #1 | L | dark-models-overview | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F173 | T19 required #1 | M | dark-chat-open-website-invalid | implemented | Shared field ErrorNotice + aria-invalid and red field border, captured in both themes. |
| F174 | T03 optional #3 | L | dark-preview-pdf / dark-preview-website | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F175 | T19 optional #2 | L | dark-monitor-generating | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
| F176 | T03 required #8 | M | dark-skills-overview / dark-skills-edit | implemented | Enabled primary buttons, neutral disabled controls, bright on toggles, brand checkboxes, a compact growing composer, and labelled task actions/detail chrome. |
| F177 | T19 optional #3 | L | dark-setup-model | optional-not-scheduled | Optional low-priority polish was not scheduled in this first pass. Shared/rebuilt surfaces may also resolve this incidentally; no separate closure is claimed. |
@@ -0,0 +1,202 @@
# Strata audit fixes — implementation and review
Executed by Codex on 7 October 2026. No Claude process or Claude subagent was used.
## Scope and setup
- Package extracted to `audit-fixes/`; bundled agent definition copied unchanged to `.claude/agents/strata-fixer.md`.
- Original 420 audit PNGs remain in `docs/evidence/audit-2026-10-07/`.
- All 19 tasks were handled in dependency order. The required scope was **15 high + 82 medium findings**. The 80 optional low findings were not scheduled for a separate polish pass; some disappeared as a consequence of rebuilding the affected surfaces.
- Every required finding has a disposition in [FINDING-STATUS.md](FINDING-STATUS.md), with a machine-readable copy in [finding-status.json](finding-status.json).
- This app and its parent folder have no Git repository. No branches/commits were invented. Original source and preview state were saved in `baseline-source.tar.gz` and `baseline-preview-state.json`. [changed-files.txt](changed-files.txt) records the source comparison.
- Design-kit files under `src/styles/kit/` were not changed.
## Phase 1 — shared fixes
### T01 · One model identity
Loaded-model identity now uses formatModelName. Removed the chat model catalog and multi-model profile flow; Model and Setup share a version ladder.
- Required findings: F001, F011, F059, F060, F077, F090, F123, F150.
- Main files: `src/lib/format.ts; src/app/Sidebar.tsx; src/components/ComposerControls.tsx; src/screens/{Models,Setup,Tuning,Monitor}.tsx; server/catalog.mjs`.
- Dispositions and qualifications: see the T01 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T02 · Overlay layering
Opaque dialogs and palettes, explicit overlay layers, dropdowns above their parent dialog, dark scrims and stable scroll gutters.
- Required findings: F140, F149, F155, F158, F169.
- Main files: `src/components/{ui,Popover,FloatingMenu}.tsx; src/styles/app.css; src/screens/Chat.tsx`.
- Dispositions and qualifications: see the T02 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T03 · Control states
Enabled primary buttons, neutral disabled controls, bright on toggles, brand checkboxes, a compact growing composer, and labelled task actions/detail chrome.
- Required findings: F025, F035, F094, F126, F133, F142, F170, F176.
- Main files: `src/styles/app.css; src/screens/{Chat,Tasks}.tsx`.
- Dispositions and qualifications: see the T03 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T04 · Errors
Shared ErrorNotice sanitizes Fixture prefixes and supports cause, recovery text and retry. Applied to composer/website, models, skills, tasks, setup, Serving and Cloudflare. Request states have semantic colors.
- Required findings: F021, F053, F098, F102, F111, F127, F131, F134, F153.
- Main files: `src/components/{ui,CloudflareDialog,ComposerControls}.tsx; src/lib/format.ts; src/screens/{Models,Skills,Tasks,Serving,Setup,Chat}.tsx`.
- Dispositions and qualifications: see the T04 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T05 · Live numbers
Hide idle chat statistics; show live estimated speed/tokens until reported usage arrives. Context comes from engine config. Clamp and flag impossible memory readings without asserting unobserved swapping.
- Required findings: F003, F006, F023, F121.
- Main files: `src/lib/{chat-metrics,hardware-summary,store}.ts; src/components/TelemetryPopover.tsx; src/screens/Monitor.tsx; server/monitor.mjs`.
- Dispositions and qualifications: see the T05 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T06 · Response hover layout
Response actions use a horizontal row below content and a portaled floating menu, so opening More never reflows or clips the response.
- Required findings: F034.
- Main files: `src/screens/Chat.tsx; src/styles/app.css`.
- Dispositions and qualifications: see the T06 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T07 · Unbuilt controls
Feature flags hide unfinished access modes, thinking levels and session-log export. A single Preview build badge identifies simulated mode; provenance remains where otherwise misleading.
- Required findings: F051.
- Main files: `src/lib/features.ts; src/components/{ComposerControls,ChatToolbar,layout,ui}.tsx; src/components/TelemetryPopover.tsx`.
- Dispositions and qualifications: see the T07 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T08 · Primary navigation
Engine and singular Model are primary navigation destinations. More contains Serving and Settings.
- Required findings: F159.
- Main files: `src/app/Sidebar.tsx; src/lib/commands.ts`.
- Dispositions and qualifications: see the T08 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
## Phase 2 — Model and Engine
### T09 · Model page
Single-model hero, seven version rows, detail action, installed list and shared Setup selection. Fit uses detected memory and context, with only the highest-quality fast fit recommended. Repeated profile warnings and compare trays were removed.
- Required findings: F061, F064, F070, F071, F072, F073, F074, F076, F152.
- Main files: `src/screens/{Models,Setup}.tsx; src/components/VersionLadder.tsx; src/lib/model-versions.ts; server/{catalog,models}.mjs`.
- Dispositions and qualifications: see the T09 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T10 · Engine v3
Simple workloads/headroom and capability-aware context slider; animated auto-tune recommendation; compact grouped Expert parameters with unsupported inputs hidden/disabled; underline sub-tabs; inline JSON line/column errors; dirty-only action bar.
- Required findings: F078, F079, F080, F081, F082, F084, F087, F092, F093, F096, F097.
- Main files: `src/screens/Tuning.tsx; src/components/{AutoTune,EngineExperience}.tsx; src/lib/config.ts; src/styles/app.css`.
- Dispositions and qualifications: see the T10 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
## Phase 3 — remaining screen fixes
### T11 · Chat
Zero-agent menus hidden; title truncation signalled; explicit template selection; approval summaries; failed-agent log; simplified slash commands; branch-aware empty state; inline emphasis; file actions; text attachment support; demos moved to Settings About.
- Required findings: F002, F004, F007, F012, F013, F015, F017, F018, F026, F028, F030, F032, F039, F041, F043, F052, F055, F056, F057, F058.
- Main files: `src/screens/Chat.tsx; src/components/{ChatToolbar,SubagentRow,ArtifactCard,ComposerControls,Markdown}.tsx; src/lib/{store,commands}.ts`.
- Dispositions and qualifications: see the T11 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T12 · Time-skip
Stable Version A/B labels, readable amber status text, primary Open version B and secondary Compare at completion. The selected example result opens in the preview.
- Required findings: F045, F047, F048.
- Main files: `src/components/TimeSkipPanel.tsx; src/screens/Chat.tsx; src/styles/app.css`.
- Dispositions and qualifications: see the T12 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T13 · Serving
Queued cancellation, generated key dialog with copy only for a value, explicit local-network status/action and URL copy, and Connect an app in the empty state.
- Required findings: F103, F108, F117, F118, F119, F132.
- Main files: `src/screens/Serving.tsx; src/components/CloudflareDialog.tsx`.
- Dispositions and qualifications: see the T13 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T14 · Monitor
Shared-memory labels explain pool overlap and idle states are clear. Memory validation is shared with T05.
- Required findings: F122.
- Main files: `src/screens/Monitor.tsx; src/lib/hardware-summary.ts`.
- Dispositions and qualifications: see the T14 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T15 · Skills and Tasks
Sans-serif instruction fields; scheduling state distinguishes scheduled and paused tasks; skills scope is explicit. Shared errors, toggles and dropdown layering cover related findings.
- Required findings: F136, F141.
- Main files: `src/screens/{Skills,Tasks}.tsx; src/components/TaskEditor.tsx; src/styles/app.css`.
- Dispositions and qualifications: see the T15 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T16 · Settings and Setup
Settings index follows the visible/search-result section. Setup context controls are inline, and its opaque bounded dialog retains a sticky footer.
- Required findings: F144, F151.
- Main files: `src/screens/{Settings,Setup}.tsx; src/styles/app.css`.
- Dispositions and qualifications: see the T16 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T17 · Navigation dialogs
Rename uses a stacked full-width selected input; deletion offers Archive instead; shared overlay/gutter fixes prevent page movement.
- Required findings: F156, F157.
- Main files: `src/app/Sidebar.tsx; src/styles/app.css`.
- Dispositions and qualifications: see the T17 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T18 · Preview panel
Active tabs scroll within their strip with edge fades. Narrow windows use an overlay; wide windows retain enough chat width. Images/PDF share Fit/100% controls and PDF uses icon paging.
- Required findings: F162, F163, F164.
- Main files: `src/components/{ArtifactPanel,PreviewControls,PdfPreview}.tsx; src/screens/Chat.tsx; src/styles/app.css`.
- Dispositions and qualifications: see the T18 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
### T19 · Dark theme
Shared field-error style is visible in dark mode; opaque overlays and dark scrims preserve depth. Primary/toggle changes pass contrast and surface-luminance checks.
- Required findings: F173.
- Main files: `src/styles/app.css; src/components/ComposerControls.tsx`.
- Dispositions and qualifications: see the T19 entries in [FINDING-STATUS.md](FINDING-STATUS.md).
## Verification
| Check | Result | Evidence |
|---|---|---|
| Baseline unit suite | 34 passed | Existing suite before changes |
| Final unit suite | 39 passed; 0 failed, skipped or cancelled | [tests.log](tests.log) |
| Production build | Passed | [build.log](build.log) |
| TypeScript, UI audit, WCAG contrast, reading measure, dark-surface luminance | Passed | [check-final.log](check-final.log) |
| Motion/reduced motion | Passed | [motion.log](motion.log) |
| Quantified motion budget | **Not measured**: harness self-check could not detect its deliberately expensive control effect | [motion-budget.log](motion-budget.log) |
The package command `node --test tests/` is not accepted as a directory entry point by the installed Node version. Used `node --test tests/*.test.mjs` instead. Existing tests were retained. Fixture IDs and stale UI selectors were updated to the new single-model catalog and current accessible control labels; five logic tests were added (identity, memory, model fit, usage, JSON diagnostics).
Interactive checks covered Repeat above the task modal; dark/light enabled and disabled controls; settings search; failed-agent logs; website validation; active-tab closing and scrolling; PDF/image controls; Time-skip completion and opening its selected result; JSON error placement; and reply menu layout. A reply rectangle stayed exactly 864 × 298.8px before/after opening More at the wide viewport. Expert now shows five parameter rows and the next section heading at 1280×720.
The screenshot set is a **targeted regression review**, not a replacement capture of all 210 old states. Retired model pickers/profile/compare surfaces cannot be recaptured. An isolated read-only synthetic fixture endpoint was blocked by the browser (`ERR_BLOCKED_BY_CLIENT`); it was stopped without attempting a bypass. Synthetic hardware-unavailable, model-load/prepare failure, service-outage, queued and active-sharing states are source/logic reviewed but not all visually recaptured. No API key or network exposure was enabled during review.
## Product qualifications
- The seven Qwen3.8 versions are **design-preview data** from the supplied reference, explicitly marked Preview build. They are not claims of available downloadable model files. Real-engine mode retains the original verified model catalog and real download sources; this is why a literal source grep still finds Qwen2.5 in `server/real-model-catalog.mjs`.
- Model fit uses detected hardware. The current 16GB computer cannot run the preview Balanced weights within the estimated budget; the UI correctly warns even though the simulated preview marks that version Running.
- Numerical per-version benchmark speeds are not invented. Model says Not measured; Engine labels its demo estimates. Auto-tune animates checking/recommending supported settings and asks to review/save; it does not claim to have executed a benchmark.
- Primary colors were adjusted to satisfy measured text contrast and the existing dark-surface budget. Literal white on #10b981 in light mode would fail text contrast.
- The Serving guide header stays icon-only because the user explicitly requested that earlier. Its empty state now includes a labelled Connect an app action.
- Text/code attachment is supported in the visible prompt. Image/video/GIF previews remain available; binary model input is outside the current text inference API.
- Time-skip is still the scripted two-version prototype. Open version B opens the actual selected example summary; it does not imply a generated OMP artifact.
- Setup/preview popovers are suppressed when setup is open. HMR edits to the central store require a browser reload during development; a normal fresh page load initializes correctly.
## Evidence and follow-up
See [the screenshot gallery](../docs/evidence/audit-fixes-2026-10-07/index.html) and [its coverage notes](../docs/evidence/audit-fixes-2026-10-07/README.md). Optional low-priority work remains listed in the supplied task files and finding ledger. Examples include richer raw-config syntax highlighting, advanced storage actions, and minor copy/spacing polish.
@@ -0,0 +1,35 @@
# Prompts for Claude Code
## 1. Run one task (simplest)
Start a new session in the repo for each task and paste:
```
Use the strata-fixer subagent to complete audit-fixes/tasks/T01-one-model-name.md.
High and medium findings only. Follow the task's "How to check" and "Done when" sections.
```
Change the file name for each task. Set the effort to medium for the subagent (for example with /model, or in your settings) to keep costs down.
## 2. Run a whole phase (orchestrated)
Paste into one session:
```
Read audit-fixes/README.md. Run Phase 1: for each task T01–T08, launch the strata-fixer
subagent with its task file, high and medium findings only. Run tasks whose
dependencies are met in parallel; wait for T01 before T05 and T08.
Each subagent works on its own branch. When all are done, merge the branches into
fix/phase-1 in task order, resolve conflicts, and run npm run check, node --test tests/
and npm run build. Then stop and summarise PROGRESS.md for me.
```
Use the same prompt for Phase 2 (T09–T10) and Phase 3 (T11–T19).
## 3. Review after each phase
Run this in a fresh session, ideally on a stronger model:
```
Review the fix/phase-1 branch against audit-fixes/REVIEW.md and the task files for T01–T08.
For each finding, check the change in the code and, for the states listed, re-capture the
screen and compare it with docs/evidence/audit-2026-10-07/. Report, per task: fixed, not
fixed, regressions. Don't fix anything yourself, just list what to send back.
```
@@ -0,0 +1,71 @@
# Strata UI fixes — handoff for Claude Code
This package comes from the Strata UI audit of 7 October 2026: 177 findings across 210 screen states. Here they are split into 19 tasks. Each task file lists the findings it covers, the files to change, and how to check the result.
## What's inside
- `tasks/` has one file per task, ready to give to a subagent.
- `findings.json` has all 177 findings with severity, state, issue, suggested fix and assigned task.
- `designs/` holds the reference designs for T09 (Model) and T10 (Engine v3). They are design-component source files: read them for structure, copy, colours and behaviour. They won't run on their own.
- `.claude/agents/strata-fixer.md` is a subagent definition (Sonnet, focused on one task).
- `PROMPTS.md` has the prompts to paste into Claude Code.
- `REVIEW.md` is the checklist for the review after each phase.
- `PROGRESS.md` is the log that each task appends to.
## Setup
1. Copy this folder into the repo root as `audit-fixes/` (so paths read `audit-fixes/tasks/T01-…`).
2. Copy `audit-fixes/.claude/agents/strata-fixer.md` to `.claude/agents/strata-fixer.md` in the repo.
3. Make sure `docs/evidence/audit-2026-10-07/` (the screenshots) is in the repo, because the task files point to it.
4. Run `npm install`, then `npm run check` and `node --test tests/` once. Note anything that already fails, so it isn't blamed on a task.
## Order
Phase 1 fixes shared components, so later tasks get smaller. Tasks in the same phase with no dependency between them can run in parallel on separate branches.
### Phase 1 — root causes (shared components)
| Task | Title | Findings | High / Med / Low | Depends on |
|---|---|---|---|---|
| T01 | One model, one name | 11 | 6 / 2 / 3 | — |
| T02 | Overlay layering and dialogs | 5 | 2 / 3 / 0 | — |
| T03 | Primary, disabled and on states | 11 | 1 / 7 / 3 | — |
| T04 | One error component, no fixture text | 10 | 0 / 9 / 1 | — |
| T05 | Show numbers when they matter | 6 | 2 / 2 / 2 | T01 |
| T06 | Fix the response hover layout | 1 | 1 / 0 / 0 | — |
| T07 | Hide what is not built | 2 | 0 / 1 / 1 | — |
| T08 | Engine and Model in the main nav | 1 | 1 / 0 / 0 | T01 |
### Phase 2 — rebuild Model and Engine
| Task | Title | Findings | High / Med / Low | Depends on |
|---|---|---|---|---|
| T09 | Build the single-model Model page | 17 | 0 / 9 / 8 | T01, T03, T04 |
| T10 | Build Engine v3 | 17 | 2 / 9 / 6 | T01, T02, T03 |
### Phase 3 — remaining findings per screen
| Task | Title | Findings | High / Med / Low | Depends on |
|---|---|---|---|---|
| T11 | Chat: remaining findings | 38 | 0 / 20 / 18 | T01, T05, T06, T07 |
| T12 | Time-skip: remaining findings | 6 | 0 / 3 / 3 | — |
| T13 | Serving: remaining findings | 19 | 0 / 6 / 13 | T04 |
| T14 | Monitor: remaining findings | 2 | 0 / 1 / 1 | T05 |
| T15 | Skills and Tasks: remaining findings | 9 | 0 / 2 / 7 | T02, T03, T04 |
| T16 | Settings and Setup: remaining findings | 7 | 0 / 2 / 5 | T02, T09 |
| T17 | Navigation and overlays: remaining findings | 4 | 0 / 2 / 2 | T02, T08 |
| T18 | Preview panel: remaining findings | 7 | 0 / 3 / 4 | — |
| T19 | Dark mode: remaining findings | 4 | 0 / 1 / 3 | T02, T03 |
## Running it cheaply
- Do high and medium first. Every task file puts low findings under "Optional polish". Skip them in the first pass. That cuts about a third of the work.
- Use a fresh session per task. Each subagent starts clean with only its task file, so context stays small.
- Check with tests first, and use screenshots only for the states listed in the task.
- After each phase, run one review (see REVIEW.md) instead of reviewing after every task.
Rough cost at API list prices (Sonnet 5.5, medium effort, for the subagents; one review per phase):
- Phase 1 (8 tasks): $10–20
- Phase 2 (2 large tasks): $8–16
- Phase 3 (9 tasks): $10–20, or about half that if you skip the low findings
- Reviews: $8–15
## Ground rules for every task
- Stay within the task's scope. If a fix needs a file that another task owns, make the smallest change and note it in PROGRESS.md.
- Don't change the design kit tokens in `src/styles/kit/` unless the task says so. Run `npm run sync:kit` if you do.
- Keep both themes working. Check light and dark.
- Existing tests must stay green. Add tests for new logic (formatters, clamping, fit rules).
- A finding can be closed as "already fixed by Txx" or "not reproducible", with a one-line reason.
@@ -0,0 +1,47 @@
# Review checklist — completed 7 October 2026
The final review covers all three phases together. See PROGRESS.md for each task and FINDING-STATUS.md for every finding. Checkboxes are intentionally left open where evidence is incomplete or the requested literal check was adapted.
## Every phase
- [x] `npm run check` passes (typecheck, UI audit, contrast, measure, luminance). Final log: `check-final.log`.
- [x] `node --test tests/*.test.mjs` passes: 39 tests, none skipped or removed. The package's directory form is incompatible with the installed Node version.
- [x] `npm run build` succeeds.
- [x] Every high/medium finding is implemented or closed with a documented reason in PROGRESS.md / FINDING-STATUS.md.
- [ ] Every listed state re-captured in both themes. **Partial:** 87 targeted screenshots; obsolete screens removed; the read-only synthetic fixture endpoint was blocked by the browser. No bypass attempted.
- [x] Dialog/menu/response checks show no unintended content movement; response menu geometry was measured unchanged.
- [x] Source compared with the baseline archive; changes belong to the audit fixes or supporting tests. Design-kit token files unchanged.
## Phase 1
- [x] One formatter supplies loaded-model identity throughout the UI.
- [ ] Literal no-Qwen2.5 source grep. **Intentional exception:** `server/real-model-catalog.mjs` retains the verified real-engine model/download source. The design preview uses the supplied Qwen3.8 family. Do not rename a real model into a fictional one.
- [x] No multi-model pickers remain; Model owns version selection and Setup reuses the same ladder.
- [x] Repeat listbox works above the task dialog in both themes.
- [x] Enabled/disabled primary states and on/off toggles are visually distinct.
- [x] Shared ErrorNotice strips Fixture prefixes; error fields have clear state and recovery paths.
- [x] Composer shows live estimated speed during streaming; Monitor clamps/flags impossible memory values.
- [x] Engine and Model are primary navigation destinations.
## Phase 2
- [x] Model follows the reference structure: running hero, version ladder, details/actions and installed versions.
- [x] Fit/recommendation derives from detected hardware and context, not reference placeholder numbers.
- [x] Model lifecycle action mapping is implemented. Some synthetic lifecycle states were source-reviewed rather than captured.
- [x] Engine follows the reference structure with compact Expert parameters and inline JSON diagnostics.
- [x] Motion/reduced-motion checks pass (`motion.log`).
- [ ] Quantified motion budget passes. **Not measured:** harness self-check could not detect a known-expensive effect (`motion-budget.log`). No performance claim made.
## Phase 3
- [x] All required screen findings have a disposition.
- [x] Dark mode passes contrast and luminance checks.
- [x] Time-skip completion opens the selected example result; A/B names stay stable.
- [x] Optional low-priority polish remains explicitly unscheduled rather than silently claimed complete.
## Delivery
- [x] Package extracted; requested agent file copied unchanged.
- [x] Original evidence preserved; targeted review evidence in `docs/evidence/audit-fixes-2026-10-07/`.
- [x] No Git metadata exists here; baseline archive and changed-file inventory supplied instead of branch commits.
- [x] No external publishing, API-key save, model-weight download or network exposure performed for the review.
@@ -0,0 +1,32 @@
exec((__import__('pathlib').Path(__file__).parent/'apply-shared.py').read_text().split("append('src/lib/format.ts'")[0])
p=root/'src/components/ComposerControls.tsx';s=p.read_text();s=s.replace("import { Btn, Dialog, Icon }", "import { Btn, Dialog, Icon, ErrorNotice }");s="import { formatModelName } from '../lib/format';\nimport { features } from '../lib/features';\n"+s
start=s.index(' <button ref={accessTrigger}');end=s.index(' <span className="spacer"/>',start);s=s[:start]+s[start:end].replace('<button','{features.toolAccess&&<button',1).replace('</button>','</button>}')+s[end:]
start=s.index(' <button className="composer-choice composer-model"');end=s.index(' {menu?',start)
s=s[:start]+''' <button className="composer-choice composer-model" onClick={()=>go('models')} title={formatModelName(loaded)}><span>{formatModelName(loaded)}</span></button>
{features.thinkingLevels&&<button ref={thinkingTrigger} className="composer-choice composer-effort" onClick={()=>setPreferences('thinking')} title="Thinking level"><Icon name="thinking" size={16}/><span>{session?.preferences?.thinking??'Auto'}</span></button>}
'''+s[end:]
start=s.index('<button role="menuitem" className="menu__item" onClick={()=>{setMenu(false);createPreviewExamples();}}');end=s.index('</FloatingMenu>',start);s=s[:start]+'{features.demosInComposer&&<>'+s[start:end]+'</>}' +s[end:]
start=s.index(' <Dialog open={models}');end=s.index(' <Dialog open={urlOpen}',start);s=s[:start]+s[end:]
s=s.replace('Open a file<span className="xs muted">Preview only</span>','Open a file preview')
s=s.replace('type="url" value={url}', 'type="url" aria-invalid={!!error} aria-describedby={error?"website-error":undefined} value={url}')
s=s.replace('<p className="small muted">Some sites block embedded views. You can open them in your browser instead.</p>{error?<p role="alert" className="inline-error">{error}</p>:null}', '{error?<div id="website-error"><ErrorNotice message={error}/></div>:null}<p className="small muted">Some sites block embedded views. You can open them in your browser instead.</p>')
s=s.replace("onChange={e=>setUrl(e.target.value)}", "onChange={e=>{setUrl(e.target.value);setError('');}}")
s=s.replace("<p className=\"composer-menu-note xs muted\">Saved for this chat. {preferences==='access'?'Tool execution':'Adjustable thinking'} isn’t connected in this preview.</p>", '')
s=s.replace("{value:'read',label:'Read only'},{value:'write',label:'Workspace write'},{value:'full',label:'Full access'}", "{value:'read',label:'Read only — inspect files'},{value:'write',label:'Workspace write — edit project files'},{value:'full',label:'Full access — can change your computer'}")
s=s.replace("{error&&!models&&!urlOpen?<button className=\"composer-file-error\" onClick={()=>setError('')} title=\"Dismiss file error\">{error}</button>:null}", "{error&&!urlOpen?<ErrorNotice message={error} action=\"Dismiss\" onRetry={()=>setError('')}/>:null}")
p.write_text(s)
# Usage is calculated from streaming stats or explicitly marked estimates, never a fabricated rate.
p=root/'src/lib/chat-metrics.ts';s=p.read_text();s=s.replace("const speed=[...replies].reverse().find(m=>m.tps!==undefined)?.tps??null;", "const streaming=replies.find(m=>m.streaming);\n const speed=streaming?.tps??[...replies].reverse().find(m=>m.tps!==undefined)?.tps??null;")
s=s.replace('total:hasUsage?session.tokensIn+session.tokensOut:messages.length?null:0,', 'total:hasUsage?session.tokensIn+session.tokensOut+(streaming?.tokens??0):replies.every(m=>m.inputTokens!==undefined&&m.tokens!==undefined)?replies.reduce((n,m)=>n+m.inputTokens!+m.tokens!,0):null,')
s=s.replace('return {example:', "return {streaming:!!streaming,estimated:streaming?.usageSource==='estimated',hasReplies:replies.length>0,example:")
p.write_text(s)
edit('src/lib/types.ts',"usageSource?: 'reported' | 'demo' | 'unavailable';", "usageSource?: 'reported' | 'demo' | 'unavailable' | 'estimated';")
edit('src/lib/store.ts',"statsAvailable: sess.statsAvailable !== false && typeof frame.tokensIn === 'number' && typeof frame.tokensOut === 'number',", "statsAvailable: typeof frame.tokensIn === 'number' && typeof frame.tokensOut === 'number' && sess.messages.filter(m=>m.role==='assistant'&&!m.streaming).every(m=>typeof m.inputTokens==='number'),")
edit('src/lib/store.ts',"patchAssistant((m) => ({ ...m, content: m.content + String(frame.text ?? '') }));", "patchAssistant((m) => { const content=m.content+String(frame.text??''); const count=Math.max(1,Math.ceil(content.length/4)); const seconds=Math.max(.1,(performance.now()-started)/1000); return {...m,content,tokens:count,tps:count/seconds,usageSource:'estimated'}; });")
p=root/'src/components/TelemetryPopover.tsx';s=p.read_text();s=s.replace('const note=m.example?', 'if(!m.hasReplies)return null;\n const note=m.example?');s=s.replace("`${m.speed===null?'—':Math.round(m.speed)} tokens/s`", "`${m.estimated?'≈ ':''}${m.speed===null?'—':Math.round(m.speed)} tok/s${m.streaming?'':' · last reply'}`");s=s.replace('label="LLM time"','label="Thinking & writing"');s=s.replace('title="Session statistics"><Row', 'title="Session statistics">{m.estimated?<p className="xs muted">Live estimate from response length and elapsed time. Final usage comes from the engine.</p>:null}<Row');s=s.replace('`${Math.round(m.pct)}%`} title="Context length"','`${Math.round(m.pct)}% of context`} title="Context length"');s=s.replace('Includes the latest prompt and response. Automatic compaction is not connected in this build.','Includes the latest prompt and response.');p.write_text(s)
edit('src/components/ArtifactCard.tsx','<Icon name="chevron" size={16}/>','<Icon name="ellipsis" size={16}/>')
p=root/'src/components/Markdown.tsx';s=p.read_text();s=s.replace(r'\*\*[^*]+\*\*|',r'\*\*[^*]+\*\*|\*[^*\n]+\*|');s=s.replace(' const link =', " if (part.startsWith('*') && part.endsWith('*')) return <em key={i}>{part.slice(1,-1)}</em>;\n const link =");p.write_text(s)
p=root/'src/screens/Chat.tsx';s=p.read_text();s=s.replace('Btn, Empty, Icon, IconBtn,','Btn, Empty, Icon, IconBtn, ErrorNotice,');s=s.replace('clockTime, cx, duration, tokens, tps','clockTime, cx, duration, tokens, tps, formatModelName');s=s.replace('const inlinePreview = splitWidth >= (selectedRun ? 720 : 900);','const inlinePreview = splitWidth >= (selectedRun ? 960 : 1120);');start=s.index(' <Empty\n');end=s.index('\n </div>',start);s=s[:start]+' <ChatIntro modelLabel={formatModelName(loaded)} onPick={updateDraft}/>'+s[end:];s=s.replace('Try the two-stream UI demo · add a prompt','Try two versions and keep the better one');s=s.replace('!draft.trim() || (!loaded',"!draft.trim() || draft.trim()==='/' || (!loaded");s=s.replace(' value={draft}\n', ' rows={1}\n value={draft}\n');s=s.replace(' onChange={(e) => setDraft(e.target.value)}',' onChange={(e) => {setDraft(e.target.value);e.currentTarget.style.height="auto";e.currentTarget.style.height=`${Math.min(180,e.currentTarget.scrollHeight)}px`;}}');s=s.replace("{m.example?'Design example':'Demo response · simulated inference'}", "{m.example?'Design example':'Preview build'}");s=s.replace('<summary aria-label="More response actions">More</summary>', '<summary aria-label="More response actions"><Icon name="ellipsis" size={16}/></summary>');s=s.replace('<summary>{t.name} · {t.state}</summary>', '<summary><Icon name="chevron" size={14}/>{t.name}<span>·</span><Icon name={t.state===\'denied\'?\'x\':\'check\'} size={14}/>{t.state===\'done\'&&t.scope!==\'read\'?\'Approved\':t.state===\'denied\'?\'Denied\':t.state===\'done\'?\'Done\':t.state}</summary>');s=s.replace('B selected · inspect the two passes','Version B selected · compare versions');p.write_text(s)
# A failed example agent has an inspectable log; do not invent a working retry API.
p=root/'src/components/SubagentRow.tsx';s=p.read_text();s="import { useState } from 'react';\n"+s;s=s.replace("import { Icon, type IconName }", "import { Btn, Dialog, Icon, type IconName }");s=s.replace(' const state=',' const [log,setLog]=useState(false);\n const state=');s=s.replace('</p></div>', '</p>{a.status===\'failed\'?<button className="text-action" onClick={()=>setLog(true)}>View log</button>:null}</div>');s=s.replace(' </div>;',' <Dialog open={log} title={`${a.name} · log`} onClose={()=>setLog(false)} actions={<Btn onClick={()=>setLog(false)}>Done</Btn>}><p>{a.description}</p><p className="small muted">Status: {state.label} · {elapsed(a.durationMs)} · {compactTokens(a.tokens)} tokens</p></Dialog></div>;');p.write_text(s)
append('src/styles/app.css','\n.text-action { padding:0; border:0; background:none; color:var(--st-accent-text); cursor:pointer; font:inherit; font-size:12px; text-decoration:underline; }\n')
@@ -0,0 +1,52 @@
exec((__import__('pathlib').Path(__file__).parent/'apply-shared.py').read_text().split("append('src/lib/format.ts'")[0])
p=root/'src/screens/Tuning.tsx';s=p.read_text();s=s.replace("import { ModelPicker, ModelAction } from '../components/ModelCatalog';", "import { formatModelName } from '../lib/format';\nimport { AutoTune } from '../components/AutoTune';")
s=s.replace('DemoTest, PerformancePreview, TuningDials','DemoTest, PerformancePreview')
s=s.replace("import type { ModelVariant } from '../lib/types';\n",'');s=s.replace('ActionError, Btn, Dialog, Field, Icon, Seg, Select','ActionError, Btn, Dialog, ErrorNotice, Icon, Select');s=s.replace('useStore, setConfigDraft','go, useStore, setConfigDraft');s=s.replace(" const [pickerOpen, setPickerOpen] = useState(false);\n const [picked, setPicked] = useState<ModelVariant | null>(null);", " const [tuneOpen,setTuneOpen]=useState(false);\n const [unsupported,setUnsupported]=useState(false);")
start=s.index('const PRIORITIES');end=s.index('type Issue',start);s=s[:start]+s[end:]
s=s.replace('const dirty = rawDraft !== null;', 'const dirty = rawDraft !== null && (!doc || JSON.stringify(doc)!==JSON.stringify(saved));')
s=s.replace("const rows = params.filter(p =>", "const rows = params.filter(p => p.id!=='server.host' && (unsupported || !!p.applies&&!p.applies.startsWith('Preserved'))).filter(p =>")
s=s.replace("v.id === engine?.variantId", "v.id === library?.loaded")
start=s.index(' function changeBeginner');end=s.index(' function changeParam',start);s=s[:start]+s[end:]
s=s.replace(" const batchSupported = !!engine.expert.find(p => p.id === 'perf.batch' && p.applies === 'Next model load');\n",'')
s=s.replace("sub={current ? `${current.family} · ${current.quant}` : 'Choose a model to explore its setup.'} actions={<Btn onClick={() => setPickerOpen(true)}>Change model</Btn>}", "sub={formatModelName(current)} actions={<><Btn size=\"sm\" onClick={()=>go('models')}>Model version</Btn><button className=\"st-btn st-btn--secondary\" aria-pressed={mode==='expert'} onClick={()=>setMode(mode==='expert'?'beginner':'expert')}>Expert mode</button></>}")
start=s.index(' <div className="section-toolbar">');end=s.index(' <ActionError />',start)
s=s[:start]+''' <div className="section-toolbar"><span className="small muted">{dirty?'Unsaved changes':engine.dirty?'Saved for next load':'Saved settings'}</span><div className="row"><Btn size="sm" disabled={!doc} onClick={resetDraft}>Reset to recommended</Btn><Btn size="sm" disabled={!doc} onClick={()=>setTestOpen(true)}>Run speed test</Btn></div></div>
'''+s[end:]
start=s.index(' {mode === \'beginner\'');end=s.index(' <details className="disclosure"><summary>Expected experience',start)
s=s[:start]+''' {mode === 'beginner' && doc ? <div className="instrument-layout">
<section className="instrument-controls simple-engine"><div className="auto-tune-card"><Icon name="gauge" size={28}/><h2 className="h3">Make the most of this computer</h2><p className="small muted">Find a starting point for your hardware, then review before saving.</p><Btn variant="primary" disabled={!hardware||!current} onClick={()=>setTuneOpen(true)}>Auto-tune for my PC</Btn></div>
<section><h2 className="h4">What are you working on?</h2><div className="workload-cards">{[{id:'short',title:'Everyday chat',detail:'Quick questions and short text',context:8192},{id:'document',title:'Documents & code',detail:'Room for longer files',context:32768},{id:'agent',title:'Long projects',detail:'Keep more of the conversation',context:131072}].map(w=><button key={w.id} aria-pressed={workload===w.id} onClick={()=>{setWorkload(w.id as Workload);const n=Math.min(w.context,current?.contextMax??32768);update({...doc,beginner:{...doc.beginner,contextLength:`${n/1024}k` as BeginnerConfig['contextLength']},expert:{...doc.expert,'ctx.length':`${n/1024}K`}});}}><strong>{w.title}</strong><span>{w.detail}</span></button>)}</div></section>
<section><h2 className="h4">Resources</h2><div className="workload-cards">{[{id:'shared',title:'Leave room for other apps',detail:'Keep this computer responsive'},{id:'full',title:'Full speed',detail:'Give the engine more CPU threads'}].map(h=><button key={h.id} aria-pressed={(doc.headroom??'shared')===h.id} onClick={()=>update({...doc,headroom:h.id,expert:{...doc.expert,'perf.threads':Math.max(1,(hardware?.cpu.cores??4)-(h.id==='shared'?2:0))}})}><strong>{h.title}</strong><span>{h.detail}</span></button>)}</div></section>
<label className="input-field"><span>Conversation context · {cfg.context/1024}K</span><input type="range" aria-label="Conversation context" min={0} max={[4096,8192,16384,32768,65536,131072,262144,524288,1048576].filter(n=>n<=(current?.contextMax??32768)).length-1} value={Math.max(0,[4096,8192,16384,32768,65536,131072,262144,524288,1048576].indexOf(cfg.context))} onChange={e=>changeParam('ctx.length',`${[4,8,16,32,64,128,256,512,1024][Number(e.target.value)]}K`)} /><span className="xs muted">4K — {(current?.contextMax??32768)/1024}K supported · larger context uses more memory</span></label>
</section>{showPreview}
</div> : <div className="stack expert-engine">
<div className="engine-subtabs" role="tablist" aria-label="Expert editor">{(['parameters','raw'] as const).map(v=><button role="tab" aria-selected={view===v} key={v} onClick={()=>setView(v)}>{v==='raw'?'Raw config':'Parameters'}</button>)}</div>
'''+s[end:]
s=s.replace('<textarea className="st-input config-editor"', '{parsed.error?<ErrorNotice message={parsed.error} next="Correct the JSON before saving or applying."/>:null}<textarea className="st-input config-editor"')
s=s.replace(' <div className="parameter-toolbar">', ''' <div className="row small muted"><a href="#/serving">Server access is managed in Serving</a><label className="check-label"><input type="checkbox" checked={unsupported} onChange={e=>setUnsupported(e.target.checked)}/>Show unsupported</label></div><div className="parameter-toolbar">''')
s=s.replace("{p.id.startsWith('sample.') ? 'Next request · all requests' : g === 'Additional settings' ? 'Preserved only' : p.applies ?? 'Preserved only'}", "{!p.applies||p.applies.startsWith('Preserved')?'Not used by this engine':p.applies}")
s=s.replace('<ExpertInput param={p} onChange=', "<ExpertInput param={p} disabled={!p.applies||p.applies.startsWith('Preserved')} onChange=")
start=s.index(' <div className="config-savebar">');end=s.index('\n </div>',start);s=s[:start]+''' {dirty?<div className="config-savebar"><span className="small">{changed.length || 'Configuration'} {changed.length===1?'change':'changes'}</span><Btn size="sm" variant="ghost" disabled={pending} onClick={()=>setDiscardOpen(true)}>Discard</Btn><span className="spacer"/>{library?.loaded&&library.mode!=='simulated'?<Btn size="sm" disabled={invalid||pending||!connected||!lifecycle.allowed} onClick={()=>setApplyOpen(true)}>Apply now…</Btn>:null}<Btn size="sm" variant="primary" disabled={invalid||pending||!connected} onClick={()=>void save()}>{pending?'Saving…':'Save'}</Btn></div>:null}
'''+s[end:]
start=s.index(' <ModelPicker ');end=s.index(' <Dialog open={discardOpen}',start);s=s[:start]+''' <AutoTune open={tuneOpen} onClose={()=>setTuneOpen(false)} onDone={()=>{resetDraft();setTuneOpen(false);}}/>
'''+s[end:]
s=s.replace('Return all three editors to the saved configuration. The running model is unaffected.','Discard all unsaved engine changes and return to the saved configuration.')
s=s.replace('function ExpertInput({ param, onChange }: { param: ExpertParam; onChange:', 'function ExpertInput({ param, onChange, disabled=false }: { param: ExpertParam; disabled?:boolean; onChange:');s=s.replace('<Select value={String(param.value)}','<Select disabled={disabled} value={String(param.value)}');s=s.replace('<button className="st-toggle" type="button"','<button disabled={disabled} className="st-toggle" type="button"');s=s.replace('<input id={`param-${param.id}`}','<input disabled={disabled} id={`param-${param.id}`}');p.write_text(s)
(root/'src/components/AutoTune.tsx').write_text('''import { useEffect, useState } from 'react';
import { Btn, Dialog, Icon } from './ui';
const stages=['Checking hardware','Reviewing supported parameters','Choosing recommended settings','Ready to review'];
/** Proposes catalog defaults; the animation never represents a measured benchmark. */
export function AutoTune({open,onClose,onDone}:{open:boolean;onClose:()=>void;onDone:()=>void}){
const [step,setStep]=useState(0);
useEffect(()=>{if(!open)return;setStep(0);const timer=setInterval(()=>setStep(s=>Math.min(3,s+1)),900);return()=>clearInterval(timer);},[open]);
return <Dialog open={open} title="Auto-tune for this computer" onClose={onClose} actions={<><Btn onClick={onClose}>Close</Btn><Btn variant="primary" disabled={step<3} onClick={onDone}>Review recommended settings</Btn></>}><div className="tune-progress"><div className="tune-orbit" data-complete={step===3}><svg viewBox="0 0 120 120" aria-hidden="true"><circle cx="60" cy="60" r="50"/><circle cx="60" cy="60" r="50" pathLength="100" strokeDasharray={`${(step+1)*25} 100`}/></svg><Icon name={step===3?'check':'gauge'} size={42}/></div><h3 role="status">{stages[step]}</h3><p className="small muted">A recommendation based on detected hardware and supported defaults. Save to apply it; speed has not been benchmarked.</p><div className="tune-steps">{stages.map((s,i)=><span key={s} data-done={i<=step}/>)}</div></div></Dialog>;
}
''')
append('src/styles/app.css','''
.simple-engine { display:flex; flex-direction:column; gap:24px; }.auto-tune-card { padding:24px; background:var(--st-surface); border:1px solid var(--st-line); border-radius:18px; }.auto-tune-card > svg { color:var(--st-accent-text); }.auto-tune-card h2 { margin-top:12px; }
.workload-cards { display:flex; gap:8px; }.workload-cards button { flex:1; min-width:0; padding:12px; text-align:left; border:1px solid var(--st-line); border-radius:12px; background:var(--st-surface); color:var(--st-ink); font:inherit; cursor:pointer; }.workload-cards button[aria-pressed='true'] { border-color:var(--st-accent-text); background:var(--st-accent-surface); }.workload-cards span { display:block; font-size:12px; color:var(--st-ink-soft); margin-top:6px; }.simple-engine input[type='range'] { width:100%; accent-color:var(--st-accent); }
.engine-subtabs { display:flex; gap:24px; border-bottom:1px solid var(--st-line); }.engine-subtabs button { padding:10px 0; border:0; border-bottom:2px solid transparent; background:none; font:inherit; color:var(--st-ink-muted); cursor:pointer; }.engine-subtabs button[aria-selected='true'] { color:var(--st-ink); border-bottom-color:var(--st-accent); }
.expert-engine { gap:12px; }.parameter-group { margin:0; }.parameter-group > h2 { margin:12px 0 4px; }.parameter-row { display:grid; grid-template-columns:minmax(220px,1fr) minmax(230px,1fr); gap:20px; padding:10px 0; }.parameter-key { display:inline; margin-left:8px; font-size:11px; }.parameter-row .xs { display:none; }.parameter-toolbar { gap:12px; padding:8px 0; }.parameter-control { display:flex; align-items:center; gap:8px; }.parameter-control > :first-child { flex:1; }.parameter-control .st-input { min-height:32px; }.config-savebar { display:flex; flex-wrap:nowrap; align-items:center; gap:12px; padding:10px 14px; margin-top:12px; min-height:0; position:sticky; bottom:0; background:var(--st-surface); }.config-editor { min-height:320px; font-family:var(--st-font-mono); }.tuning { padding-bottom:24px; }
.tune-progress { text-align:center; padding:10px 20px 24px; }.tune-orbit { width:180px; height:180px; margin:0 auto 20px; display:grid; place-items:center; position:relative; color:var(--st-accent-text); }.tune-orbit > svg:first-child { position:absolute; inset:0; width:100%; height:100%; transform:rotate(-90deg); }.tune-orbit circle { fill:none; stroke:var(--st-line); stroke-width:3; }.tune-orbit circle+circle { stroke:var(--st-accent); stroke-linecap:round; transition:stroke-dasharray var(--st-t-local) var(--st-ease-standard); }.tune-orbit[data-complete='true'] { color:var(--st-accent-text); }.tune-steps { display:flex; justify-content:center; gap:6px; margin-top:24px; }.tune-steps span { width:22px; height:5px; border-radius:3px; background:var(--st-line); }.tune-steps span[data-done='true'] { background:var(--st-accent); }
@media(prefers-reduced-motion:reduce) { .tune-orbit circle+circle { transition:none; } }[data-motion='reduced'] .tune-orbit circle+circle { transition:none; }
''')
@@ -0,0 +1,31 @@
exec((__import__('pathlib').Path(__file__).parent/'apply-shared.py').read_text().split("append('src/lib/format.ts'")[0])
# Remove obsolete state after model-picker removal.
edit('src/app/Sidebar.tsx',' const serving = useStore(s => s.serving);\n','')
p=root/'src/components/ComposerControls.tsx';s=p.read_text().replace('go, loadVariant,','go,').replace('{session,onPreview,streaming}', '{session,onPreview}').replace(',[models,setModels]=useState(false)','').replace(",[pending,setPending]=useState(false)",'');p.write_text(s)
p=root/'src/screens/Chat.tsx';s=p.read_text().replace('Btn, Empty, Icon, IconBtn, ErrorNotice,','Btn, Icon, IconBtn, ErrorNotice,').replace(' newSession,\n','');s=s.replace("{m.demo || m.example ? (", "{m.example ? (");a=s.index(' <span className="row" role="alert"');b=s.index('\n ) : null}',a);s=s[:a]+' <ErrorNotice message={m.error} next="Try sending the message again."/>'+s[b:];s=s.replace('<ChatIntro modelLabel={loaded?.label ?? null}', '<ChatIntro modelLabel={loaded ? formatModelName(loaded) : null}');s=s.replace('session.messages.length === 0 ? (', "session.messages.length === 0 ? (session.statsAvailable===false ? <p className=\"small muted\">Editing from an earlier message. Update the prompt below.</p> :");s=s.replace('inline={inlinePreview} onClose={()=>{setSelectedPreview(null);setExpanded(false);}}/> : null}', 'inline={inlinePreview} onPreview={openPreview} onClose={()=>{setSelectedPreview(null);setExpanded(false);}}/> : null}');p.write_text(s)
# Unified preview toolbar.
(root/'src/components/PreviewControls.tsx').write_text('''import { IconBtn, Seg } from './ui';
export function PreviewControls({zoom,onZoom,page,pages,onPage,label}:{zoom:string;onZoom:(v:string)=>void;page?:number;pages?:number;onPage?:(n:number)=>void;label:string}) {return <div className="preview-controls">{page!==undefined&&onPage?<><IconBtn name="chevron" title="Previous page" disabled={page<=1} onClick={()=>onPage(page-1)}/><span className="small num">{page} / {pages??'—'}</span><IconBtn name="chevron" title="Next page" disabled={!pages||page>=pages} onClick={()=>onPage(page+1)}/></>:null}<Seg ariaLabel={`${label} zoom`} value={zoom} onChange={onZoom} options={[{value:'fit',label:'Fit'},{value:'1',label:'100%'}]}/></div>;}
''')
p=root/'src/components/ArtifactPanel.tsx';s=p.read_text();s="import { PreviewControls } from './PreviewControls';\n"+s;s=s.replace("{current.demo?'Example · ':''}{artifactLabel(current.kind)}", "{artifactFilename(current)} · {artifactLabel(current.kind)}");s=s.replace('<Seg ariaLabel="Image zoom" value={imageSize} options={[{value:\'fit\',label:\'Fit\'},{value:\'actual\',label:\'100%\'}]} onChange={setImageSize}/>', '<PreviewControls label="Image" zoom={imageSize} onZoom={setImageSize}/>');s=s.replace('data-size={imageSize}', 'data-size={imageSize===\'1\'?\'actual\':\'fit\'}');s=s.replace(" tab?.scrollIntoView({block:'nearest',inline:'nearest'});", " const strip=ref.current;if(tab&&strip){const r=tab.getBoundingClientRect(),box=strip.getBoundingClientRect();if(r.left<box.left)strip.scrollLeft-=box.left-r.left+20;else if(r.right>box.right-28)strip.scrollLeft+=r.right-box.right+48;}");p.write_text(s)
p=root/'src/components/PdfPreview.tsx';s=p.read_text().replace("import { Btn, Select } from './ui';", "import { PreviewControls } from './PreviewControls';");a=s.index('<Btn size="sm"');b=s.index('</div><div ref={container}',a);s=s[:a]+'<PreviewControls label="PDF" zoom={zoom} onZoom={setZoom} page={page} pages={doc?.numPages} onPage={setPage}/>'+s[b:];s=s.replace("'str' in item?item.str:''", "'str' in item?item.str+('hasEOL' in item&&item.hasEOL?'\\n':''):''");p.write_text(s)
p=root/'src/components/TimeSkipPanel.tsx';s=p.read_text();s=s.replace("import { Dialog, Icon, IconBtn }", "import type { PreviewArtifact } from '../lib/artifacts';\nimport { Btn, Dialog, Icon, IconBtn }");s=s.replace('{ run, sessionId, inline, onClose }', '{ run, sessionId, inline, onClose, onPreview }').replace('onClose: () => void })','onClose: () => void; onPreview:(a:PreviewArtifact)=>void })');s=s.replace("const version = original ? 'Original A' : inspect === 'a' ? revision ? 'Revision A' : 'Original A' : 'Candidate B';", "const version = original || inspect==='a' ? 'Version A' : 'Version B';");s=s.replace("const label = isA ? revision ? 'Revision' : 'Original' : 'Alternative';", "const label = isA ? 'Version A' : 'Version B';");s=s.replace("'Demo complete · B kept'", "'Version B kept'")
a=s.index(' <footer className="timeskip-footer">');b=s.index('\n </aside>',a);s=s[:a]+''' <footer className="timeskip-footer"><span>Pass {frame.pass} of 2 · {frame.done?'Finished':'Sequential passes'}</span>{frame.done?<div className="row"><Btn size="sm" onClick={()=>{setInspect('a');setOriginal(false);}}>Compare</Btn><Btn size="sm" variant="primary" onClick={()=>onPreview({id:`${run.id}-version-b`,kind:'markdown',title:'version-b.md',content:`# Version B\\n\\n${run.prompt}\\n\\nThis is the kept result from the Time-skip UI example.\\n\\n${example.improved.map((v,i)=>`- **${example.labels[i]}:** ${v}`).join('\\n')}\\n\\n${example.correction}`,demo:true})}>Open version B</Btn><IconBtn name="refresh" title="Replay demo" onClick={()=>replayTimeSkip(sessionId,run.id)}/></div>:<span className="timeskip-dots" aria-hidden="true"><i data-on/><i data-on={frame.pass===2||undefined}/></span>}</footer>
'''+s[b:];p.write_text(s)
# Format and clamp telemetry once.
append('src/lib/hardware-summary.ts','''
export function memoryReading(used:number,total:number){const safeTotal=Number.isFinite(total)?Math.max(0,total):0;const safeUsed=Number.isFinite(used)?Math.max(0,used):0;return {used:Math.min(safeUsed,safeTotal),total:safeTotal,free:Math.max(0,safeTotal-safeUsed),over:Math.max(0,safeUsed-safeTotal)};}
''')
p=root/'src/screens/Monitor.tsx';s=p.read_text();s="import { memoryReading } from '../lib/hardware-summary';\n"+s;s=s.replace('contextLabel, duration, tokens, tps','contextLabel, duration, tokens, tps, formatModelName');s=s.replace("currentModel?.family ?? 'No model loaded'", 'formatModelName(currentModel)');s=s.replace("const model = library?.variants.find(v => v.id === data.variantId);", "const model = library?.variants.find(v => v.id === library.loaded);\n const ram=memoryReading(data.hardware.ramUsedGb,data.hardware.ramTotalGb);")
s=s.replace("demo ? 'Demo'", "demo ? 'Illustrative'");s=s.replace("'Demo session'", "'This session'");s=s.replace("sub={model?.label ?? 'Engine and computer activity'}", 'sub={formatModelName(model)}');s=s.replace('data.hardware.ramUsedGb.toFixed(1)', 'ram.used.toFixed(1)');s=s.replace("`Demo${unified ? ' · do not add these pools' : ''}`", "ram.over>0?`Reading exceeds capacity by ${ram.over.toFixed(1)} GB`:unified?'Shared with model memory — count this pool once':'System memory'")
s=s.replace("`${hardware.memory.freeGb.toFixed(1)} GB available at last check`", "`${(demo?ram.free:memoryReading(hardware.memory.usedGb,hardware.memory.totalGb).free).toFixed(1)} GB available${demo?'':' at last check'}`")
s=s.replace("`${tps(s.current)} tok/s`", "data.phase==='idle'?'Idle':`${tps(s.current)} tok/s`");p.write_text(s)
# Clamp telemetry at the host boundary too; UI still flags inconsistent fixture readings.
p=root/'server/monitor.mjs';s=p.read_text().replace('ramUsedGb: round(state.hardware.ramUsedGb, 1),','ramUsedGb: round(clamp(state.hardware.ramUsedGb, 0, Math.max(0,state.hardware.ramTotalGb)), 1),');p.write_text(s)
edit('src/components/CloudflareDialog.tsx',"pending?'Connecting…':mode==='quick'", "pending?'Connecting…':(error||tunnel?.error)?'Try again':mode==='quick'")
# Sanitize transport error prefixes once; shared notices also handle fixture payload fields.
p=root/'src/lib/client.ts';s=p.read_text();s="import { userError } from './format';\n"+s;s=s.replace('super(message);','super(userError(message));');p.write_text(s)
append('src/styles/app.css','''
.preview-controls { display:flex; align-items:center; gap:8px; }.preview-controls > .st-btn:first-child svg { transform:rotate(90deg); }.preview-controls > .st-btn:nth-of-type(2) svg { transform:rotate(-90deg); }.pdf-controls .preview-controls { width:100%; }.preview-controls > .st-tabs { margin-left:auto; }.pdf-canvas-wrap { overflow:auto; align-items:normal; }.pdf-canvas-wrap > canvas { flex-shrink:0; margin:0 auto; }.pdf-text { white-space:pre-wrap; }.artifact-tabs { overflow-x:auto; min-width:0; flex:1; mask-image:linear-gradient(to right,#000 calc(100% - 18px),transparent); padding-right:18px; }.preview-window-actions { flex-shrink:0; }.timeskip-checkpoint[data-tone='gap'] > span:last-child { color:#8a5a00; }.timeskip-topline { border-bottom:1px solid var(--st-line); }.timeskip-footer { flex-wrap:wrap; gap:10px; }.timeskip-footer .st-btn { padding:6px 10px; }.timeskip-footer .st-btn--primary { color:#0b1f17; }
[data-theme='dark'] .timeskip-checkpoint[data-tone='gap'] > span:last-child { color:#edc66b; }
''')
@@ -0,0 +1,98 @@
exec((__import__('pathlib').Path(__file__).parent/'apply-shared.py').read_text().split("append('src/lib/format.ts'")[0])
p=root/'server/catalog.mjs';s=p.read_text();a=s.index('export const VARIANTS = [');b=s.index('\nexport function variant',a);real=s[a:b].replace('export const VARIANTS','export const REAL_VARIANTS');(root/'server/real-model-catalog.mjs').write_text('/** Verified file identities for the optional real engine. Never relabel these as demo weights. */\n'+real+'\n');s=s[:a]+'''import { REAL_VARIANTS } from './real-model-catalog.mjs';
// Design model versions are isolated from real downloadable artifacts.
const DESIGN_VERSIONS = [
['Q2_K','Smallest',2.9], ['Q3_K_M','Compact',3.9], ['Q4_K_M','Balanced',4.9],
['Q5_K_M','High quality',5.7], ['Q6_K','Very high',6.6], ['Q8_0','Near-original',8.5], ['BF16','Original',16],
];
export const VARIANTS = process.env.STRATA_REAL_ENGINE === '1' ? REAL_VARIANTS : DESIGN_VERSIONS.map(([quant,name,bits])=>{
const diskGb=Math.round(30.5*bits/8*10)/10;
return {id:`qwen38-${quant.toLowerCase()}`,name,family:'Qwen3.8-Flash-Next',quant,label:`Qwen3.8-Flash-Next · ${name} (${quant})`,params:'30.5B',
blurb:'The same model at a different precision.',role:quant==='Q4_K_M'?'best-fit':'option',tier:quant==='Q2_K'?'starter':'balanced',
ramClass:{minGb:diskGb+3,maxGb:diskGb+6,label:`${Math.ceil(diskGb+6)} GB memory`},diskGb,downloadGb:diskGb,contextMax:1048576,
layerCount:48,experts:128,kvKbPerToken:24,hasDraft:true,kvModes:['INT8','FP16'],tags:[],minMemoryGb:diskGb+3,
source:{repo:'design-preview',file:`${quant}.gguf`,bytes:Math.round(diskGb*1024**3)},designOnly:true};
});
''' +s[b:];s=s.replace("return `https://huggingface.co/", "if (v.designOnly) return undefined;\n return `https://huggingface.co/");s=s.replace("'64K', '128K']", "'64K', '128K', '256K', '512K', '1024K']");s=s.replace(" '128k': 131072,", " '128k': 131072,\n '256k': 262144,\n '512k': 524288,\n '1024k': 1048576,");p.write_text(s)
# Existing preview state is migrated without changing real-engine files.
p=root/'server/models.mjs';s=p.read_text();s=s.replace(' supervisor.init(hub);',''' supervisor.init(hub);
if (!REAL) {
const previous = getStore();
const old = Object.keys(previous.installed ?? {}).filter(id => !VARIANTS.some(v=>v.id===id));
if (old.length) {
const balanced=VARIANTS.find(v=>v.quant==='Q4_K_M').id;
update({installed:{...previous.installed,[balanced]:{installedAt:nowIso(),simulated:true}},
...(old.includes(previous.loaded)?{loaded:balanced}:{}),...(old.includes(previous.current)?{current:balanced}: {})});
}
}''');s=s.replace('const totalSec = 11 + v.downloadGb * 0.55;', 'const totalSec = 10; // Preview timing is independent of fictional file sizes.');p.write_text(s)
for p in (root/'tests').glob('*.test.mjs'):
s=p.read_text().replace('qwen2.5-0.5b-q4km','qwen38-q4_k_m');p.write_text(s)
edit('src/lib/types.ts',"'64k' | '128k';", "'64k' | '128k' | '256k' | '512k' | '1024k';")
edit('src/components/EngineExperience.tsx','32768, 65536, 131072]', '32768, 65536, 131072, 262144, 524288, 1048576]')
(root/'src/lib/model-versions.ts').write_text('''import type { Hardware, ModelVariant, ModelLibrary } from './types';
export type VersionFit = {zone:'fast'|'slower'|'too-big'|'unknown';needed:number;fastBudget:number;budget:number;over:number};
/** Fit uses detected pools without double-counting unified memory. No speed benchmark is implied. */
export function versionFit(v:ModelVariant, hardware:Hardware|null, context=32768):VersionFit {
const needed=v.diskGb+(v.kvKbPerToken??0)*context/1024**2+(v.experts?2.5:1.2);
if(!hardware)return {zone:'unknown',needed,fastBudget:0,budget:0,over:0};
const ram=Math.max(0,hardware.memory.totalGb),gpu=Math.max(0,hardware.accelerator.usableVramGb);
const unified=hardware.accelerator.unified;
const fastBudget=unified?ram*.72:hardware.accelerator.backend==='cpu'?0:gpu*.92;
const budget=unified?ram*.9:gpu+ram*.6;
const zone=context>v.contextMax||needed>budget?'too-big':needed<=fastBudget?'fast':'slower';
return {zone,needed,fastBudget,budget,over:Math.max(0,needed-budget)};
}
export function modelVersions(library:ModelLibrary){const family=library.mode==='simulated'?'Qwen3.8-Flash-Next':library.variants.find(v=>v.id===(library.loaded??library.current))?.family??library.variants[0]?.family;return library.variants.filter(v=>v.family===family).sort((a,b)=>a.diskGb-b.diskGb);}
export function recommendedVersion(versions:ModelVariant[],hardware:Hardware|null,context=32768){return versions.filter(v=>versionFit(v,hardware,context).zone==='fast').at(-1)??versions.find(v=>versionFit(v,hardware,context).zone==='slower');}
export const VERSION_FIT_LABEL={fast:'Fast fit',slower:'Slower · system memory','too-big':'Too big','unknown':'Fit unknown'};
''')
(root/'src/components/VersionLadder.tsx').write_text('''import type { Hardware, ModelVariant } from '../lib/types';
import { versionFit, VERSION_FIT_LABEL } from '../lib/model-versions';
import { sizeGb } from '../lib/format';
import { Icon } from './ui';
export function VersionLadder({versions,hardware,context,selected,recommended,onSelect}:{versions:ModelVariant[];hardware:Hardware|null;context:number;selected?:string;recommended?:string;onSelect:(id:string)=>void}){
return <div className="version-ladder" role="group" aria-label="Model versions">{versions.map(v=>{const fit=versionFit(v,hardware,context);return <button key={v.id} className="version-rung" data-fit={fit.zone} aria-pressed={selected===v.id} onClick={()=>onSelect(v.id)}><span className="version-rung__node"><Icon name={v.state==='loaded'?'check':'layers'} size={16}/></span><span><strong>{v.name}</strong><small>{v.quant} · {sizeGb(v.diskGb)}</small></span><span className="version-rung__state">{v.state==='loaded'?'Running':v.state==='downloading'?`${Math.round(v.progress?.pct??0)}%`:recommended===v.id?'Recommended':v.state==='installed'?'Downloaded':VERSION_FIT_LABEL[fit.zone]}</span></button>;})}</div>;
}
''')
(root/'src/screens/Models.tsx').write_text('''import { useState } from 'react';
import { ActionError, Bar, Btn, Dialog, ErrorNotice, Icon, Select } from '../components/ui';
import { Screen } from '../components/layout';
import { VersionLadder } from '../components/VersionLadder';
import { LifecycleNotice } from '../components/LifecycleNotice';
import { modelVersions, recommendedVersion, versionFit, VERSION_FIT_LABEL } from '../lib/model-versions';
import { formatModelName, sizeGb } from '../lib/format';
import { cancelInstall, go, installVariant, loadVariant, removeVariant, unloadModel, useStore, lifecycleStatus } from '../lib/store';
export function ModelsScreen(){
const library=useStore(s=>s.library),hardware=useStore(s=>s.hardware),engine=useStore(s=>s.engine);const lifecycle=lifecycleStatus(useStore(s=>s));
const [selected,setSelected]=useState(''),[context,setContext]=useState(32768),[confirm,setConfirm]=useState<'switch'|'delete'|null>(null),[pending,setPending]=useState(false),[error,setError]=useState('');
if(!library)return <Screen title="Model"><p>Loading model versions…</p></Screen>;
const versions=modelVersions(library),recommended=recommendedVersion(versions,hardware,context),running=library.variants.find(v=>v.id===library.loaded);
const version=versions.find(v=>v.id===selected)??running??recommended??versions[0];
if(!version)return <Screen title="Model"><p>No model versions are available.</p></Screen>;
const fit=versionFit(version,hardware,context),loaded=version.id===library.loaded,installed=['loaded','installed'].includes(version.state),working=['loading','downloading','unloading'].includes(version.state);
const contexts=[4096,8192,16384,32768,65536,131072,262144,524288,1048576].filter(n=>n<=version.contextMax);
async function act(action:()=>Promise<boolean|void>){setPending(true);setError('');try{const ok=await action();if(ok===false)throw new Error('The operation could not finish. Check the engine connection and try again.');setConfirm(null);}catch(e){setError(e instanceof Error?e.message:String(e));}finally{setPending(false);}}
return <Screen title="Model" sub="One model. A version that fits your computer." actions={<Btn icon="gauge" onClick={()=>go('tuning')}>Engine</Btn>}><div className="stack stack--lg model-page"><ActionError/>
<section className="model-hero"><span className="model-hero__icon"><Icon name="layers" size={28}/></span><div><span className="eyebrow">{running?'RUNNING':'YOUR MODEL'}</span><h2>{running?formatModelName(running):versions[0].family}</h2><p className="small muted">{running?'Shared by all chats':'Pick a version below to get started.'}</p></div><span className="model-status">{running?'Ready':'Not loaded'}</span></section>
{!hardware?<ErrorNotice message="Hardware has not been detected." next="Check this computer to see which versions fit." action="Run guided setup" onRetry={()=>go('setup')}/>:null}
<div className="section-toolbar"><div><h2 className="h3">Choose a version</h2><p className="small muted">Smaller versions use less memory. Larger versions preserve more precision.</p></div><Select ariaLabel="Version context" value={String(context)} onChange={v=>setContext(Number(v))} options={contexts.map(n=>({value:String(n),label:`${n/1024}K context`}))}/></div>
{!recommended&&hardware?<ErrorNotice message={`${context/1024}K context exceeds the available model budget.`} next="A shorter context may make room for a smaller version." action={context>4096?'Use shorter context':'Review computer'} onRetry={()=>context>4096?setContext(context/2):go('setup')}/>:null}
<div className="model-version-layout"><VersionLadder versions={versions} hardware={hardware} context={context} selected={version.id} recommended={recommended?.id} onSelect={id=>{setSelected(id);setError('');}}/>
<section className="version-detail" aria-label="Version details"><div className="section-toolbar"><span className="eyebrow">{version.quant}</span><span className="model-status">{loaded?'Running':installed?'Downloaded':VERSION_FIT_LABEL[fit.zone]}</span></div><h2>{version.name}</h2><p className="small muted">{formatModelName(version)}</p><div className="version-numbers"><div><strong>{sizeGb(version.diskGb)}</strong><span>Download size</span></div><div><strong>{sizeGb(fit.needed)}</strong><span>Estimated memory</span></div></div><p className="small">{fit.zone==='unknown'?'Check your computer to estimate fit.':fit.zone==='too-big'?`${sizeGb(fit.over)} over the estimated memory budget at this context.`:fit.zone==='fast'?'Fits the fast memory budget with room for other apps.':'Fits with less headroom or with weights in slower system memory.'}</p><p className="xs muted">Speed on this PC: {version.performance?.[0]?.source==='measured'?`${version.performance[0].answer.low}–${version.performance[0].answer.high} tok/s`:'Run a speed test in Engine'}</p>
{working?<><Bar value={version.progress?.pct??0} label={version.state}/><p className="small" role="status">{version.progress?.stage??'Working…'}</p>{version.state==='downloading'?<Btn disabled={pending} onClick={()=>void act(()=>cancelInstall(version.id))}>Cancel download</Btn>:null}</>:loaded?<Btn disabled={pending||!lifecycle.allowed} onClick={()=>void act(unloadModel)}>Unload version</Btn>:installed?<div className="row"><Btn variant="primary" disabled={pending||!lifecycle.allowed||fit.zone==='too-big'} onClick={()=>setConfirm('switch')}>Switch to {version.name}</Btn><Btn icon="trash" disabled={pending} onClick={()=>setConfirm('delete')}>Delete</Btn></div>:<Btn variant="primary" icon="download" disabled={pending||fit.zone==='too-big'} onClick={()=>void act(()=>installVariant(version.id))}>{fit.zone==='too-big'?'Too big for this PC':`Download · ${sizeGb(version.downloadGb)}`}</Btn>}
{version.error||error?<ErrorNotice message={error||version.error!} next="Your downloaded files are retained."/>:null}<LifecycleNotice/>
</section></div>
<section><h2 className="h3">On this computer</h2>{versions.filter(v=>['installed','loaded'].includes(v.state)).map(v=><div className="installed-version" key={v.id}><span><strong>{v.name}</strong><small>{v.quant} · {sizeGb(v.diskGb)}</small></span><Btn size="sm" onClick={()=>setSelected(v.id)}>{v.state==='loaded'?'View running version':'View version'}</Btn></div>)}{!versions.some(v=>['installed','loaded'].includes(v.state))?<p className="small muted">No versions downloaded yet. Choose one above to get started.</p>:null}<p className="small muted">{sizeGb(library.disk.usedGb)} model files · {sizeGb(library.disk.freeGb)} free</p></section>
</div><Dialog open={!!confirm} title={confirm==='delete'?'Delete this version?':`Switch to ${version.name}?`} onClose={()=>!pending&&setConfirm(null)} actions={<><Btn disabled={pending} onClick={()=>setConfirm(null)}>Cancel</Btn><Btn variant={confirm==='delete'?'danger':'primary'} disabled={pending} onClick={()=>void act(()=>confirm==='delete'?removeVariant(version.id):loadVariant(version.id))}>{pending?'Working…':error?'Try again':confirm==='delete'?'Delete version':'Switch version'}</Btn></>}><p>{confirm==='delete'?`Remove ${sizeGb(version.diskGb)} of downloaded files. You can download this version again.`:`Switch all chats to ${version.name} (${sizeGb(version.diskGb)}). Loading may take a few moments.`}</p>{confirm==='switch'?<details className="disclosure"><summary>Engine settings</summary><p className="small muted">Uses your saved {engine?.beginner.contextLength??'recommended'} context. Change settings in Engine.</p></details>:null}{error?<ErrorNotice message={error}/>:null}</Dialog></Screen>;
}
''')
append('src/styles/app.css','''
.model-hero { display:flex; align-items:center; gap:20px; border:1px solid var(--st-line); border-radius:20px; padding:26px; background:var(--st-surface); }
.model-hero > div { flex:1; min-width:0; }.model-hero h2 { margin:6px 0; font-size:24px; letter-spacing:-.5px; }.model-hero p { margin:0; }
.model-hero__icon { color:var(--st-accent-text); }.model-status { font-size:12px; color:var(--st-ink-soft); white-space:nowrap; }
.model-version-layout { display:grid; grid-template-columns:minmax(260px,1fr) minmax(320px,1fr); gap:28px; align-items:start; }
.version-ladder { display:flex; flex-direction:column; gap:5px; }.version-rung { display:flex; gap:12px; align-items:center; width:100%; text-align:left; padding:13px; background:var(--st-surface); border:1px solid var(--st-line); border-radius:12px; font:inherit; color:var(--st-ink); cursor:pointer; }
.version-rung[aria-pressed='true'] { border-color:var(--st-accent-text); background:var(--st-accent-surface); }.version-rung small { display:block; color:var(--st-ink-muted); font-size:12px; margin-top:4px; }.version-rung__node { color:var(--st-accent-text); }.version-rung__state { margin-left:auto; font-size:11px; color:var(--st-ink-soft); text-align:right; }.version-rung[data-fit='too-big'] .version-rung__node { color:var(--st-ink-muted); }
.version-detail { border:1px solid var(--st-line); border-radius:18px; padding:24px; background:var(--st-surface); position:sticky; top:12px; }.version-detail h2 { font-size:28px; margin:20px 0 4px; }.version-numbers { display:flex; gap:28px; margin:24px 0; }.version-numbers strong { font-size:22px; }.version-numbers span { display:block; font-size:12px; color:var(--st-ink-muted); margin-top:6px; }.installed-version { display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--st-line); padding:14px 0; }.installed-version small { display:block; color:var(--st-ink-muted); margin-top:4px; }
@media(max-width:850px) { .model-version-layout { grid-template-columns:1fr; }.model-hero { padding:18px; }.model-hero h2 { font-size:19px; }.version-detail { position:static; } }
''')
@@ -0,0 +1,45 @@
exec((__import__('pathlib').Path(__file__).parent/'apply-shared.py').read_text().split("append('src/lib/format.ts'")[0])
p=root/'src/screens/Setup.tsx';s=p.read_text();s=s.replace('Bar, Btn, Dialog, Icon, Pill, Steps','Bar, Btn, Icon, Pill, Steps, ErrorNotice, PreviewBadge');s=s.replace('DemoTest, MemoryBudget, PerformancePreview, ProfileChoice, TuningDials','DemoTest, MemoryBudget');s=s.replace("import { ModelPicker } from '../components/ModelCatalog';", "import { VersionLadder } from '../components/VersionLadder';\nimport { modelVersions, recommendedVersion, versionFit } from '../lib/model-versions';\nimport { Select } from '../components/ui';")
s=s.replace('estimate, recommend','estimate');s=s.replace('import { sizeGb }','import { sizeGb, formatModelName }');s=s.replace("const [profile, setProfile]", "const [profile, setProfile]")
s=s.replace("const [adjust, setAdjust] = useState(false); const [picker, setPicker] = useState(false); ", '');s=s.replace("const [workload, setWorkload] = useState<Workload>('document');", "const workload:Workload='document';")
a=s.index(' const recommendations =');b=s.index(' const experience',a);s=s[:a]+''' const versions=library?modelVersions(library):[];
const recommended=recommendedVersion(versions,hardware,config.context);
const candidate=versions.find(v=>v.id===picked)??recommended??versions[0];
'''+s[b:];a=s.index(' const modelTitle =');b=s.index(' const choices',a);s=s[:a]+" const modelTitle=formatModelName(candidate);\n"+s[b:];s=s.replace('[4096, 8192, 16384, 32768, 65536, 131072]','[4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576]');s=s.replace("experience.fit === 'too-large' || experience.fit === 'unsupported'", "!!candidate && versionFit(candidate,hardware,config.context).zone === 'too-big'")
s=s.replace('<h1 className="h2">Set up Strata</h1>','<h1 className="h2">Set up Strata <PreviewBadge/></h1>');s=s.replace('{demo ? <p className="demo-strip"><Icon name="info" size={16} />Demo · downloads and answers are simulated.</p> : null}', '');s=s.replace('Find my models','Pick a version').replace('Browse models','View versions')
a=s.index(" {step === 2 ?");b=s.index(" {step === 3 ?",a);s=s[:a]+''' {step === 2 ? <section className="stack"><h2 className="setup-headline" tabIndex={-1}>Pick a version</h2><p className="small muted">{versions[0]?.family} · the same model at different sizes.</p><VersionLadder versions={versions} hardware={hardware} context={config.context} selected={candidate?.id} recommended={recommended?.id} onSelect={setPicked}/><details className="disclosure"><summary>Conversation context</summary><div className="input-field"><span>Context length</span><Select ariaLabel="Setup context" value={context} onChange={setContext} options={[{value:'recommended',label:'Recommended (32K)'},...[4,8,16,32,64,128,256,512,1024].filter(n=>n*1024<=(candidate?.contextMax??32768)).map(n=>({value:`${n}k` as BeginnerConfig['contextLength'],label:`${n}K`}))]}/></div></details>{blocked?<ErrorNotice message="This version needs more memory at this context." next="Choose a smaller version or shorten the conversation context."/>:null}<div className="setup-actions"><Btn disabled={pending} onClick={()=>void advance(1)}>Back</Btn><Btn variant="primary" disabled={!candidate||blocked||pending} onClick={()=>void run()}>{pending?'Preparing…':installed?'Load version':'Download and continue'}</Btn></div></section>:null}
'''+s[b:];s=s.replace('tabIndex={-1}>Preparing your model</h2>', 'tabIndex={-1}>{error?"Couldn’t prepare the model":"Preparing your model"}</h2>');s=s.replace('{error ? <p role="alert" className="inline-error small">{error}</p> : null}', '{error ? <ErrorNotice message={error} next="Your choices have been saved. Use Retry to continue."/> : null}')
a=s.index(' </div><Dialog open={adjust}');b=s.index('<DemoTest open={testOpen}',a);s=s[:a]+' </div>'+s[b:];p.write_text(s)
# Errors and task controls.
p=root/'src/components/TaskEditor.tsx';s=p.read_text().replace('Btn, Dialog, Select','Btn, Dialog, Select, ErrorNotice');s=s.replace(" const modelName=library?.variants.find(v=>v.id===library.loaded)?.family.split('-')[0]??'model';\n",'');s=s.replace("assistant?'Create with '+modelName", "assistant?'Create with AI'");s=s.replace('<p role="alert" className="inline-error">{error}</p>', '<ErrorNotice message={error}/>');p.write_text(s)
p=root/'src/screens/Tasks.tsx';s=p.read_text().replace('IconBtn, Select','IconBtn, Select, ErrorNotice');s=s.replace(" const modelName=loaded?.family.split('-')[0] ?? 'model';\n",'');s=s.replace('Create with {modelName}', 'Create with AI');s=s.replace('title={currentTask?.title??"Tasks"}', 'title={currentTask?<><button className="text-action" onClick={()=>navigate(\'tasks\')}>Tasks</button> › {currentTask.title}</>:"Tasks"}');s=s.replace('sub="Run a prompt on a schedule, or whenever you need it." actions={<div', 'sub={currentTask?undefined:"Run a prompt on a schedule, or whenever you need it."} actions={currentTask?undefined:<div');s=s.replace('{location.param?<button className="text-action" onClick={()=>navigate(\'tasks\')}>All tasks</button>:null}', '');s=s.replace('<p className="task-runtime small muted">','{!currentTask&&<p className="task-runtime small muted">').replace('file and web tools aren’t connected.</p>','the instructions you save.</p>}');s=s.replace('<label className="row small muted"><input type="checkbox" checked={archived}', '{!currentTask&&<label className="row small muted"><input type="checkbox" checked={archived}').replace('/>Deleted tasks</label>','/>Deleted tasks</label>}');s=s.replace('<p role="alert" className="inline-error">{error}</p>', '<ErrorNotice message={error} onRetry={()=>void refresh()}/>');s=s.replace('<p className="small inline-error">{t.error}</p>', '<button className="task-failed text-action" onClick={()=>setResult(t.id!)}>Last run failed · View</button>');s=s.replace("t.enabled&&t.nextRunAt?`Next: ${new Date(t.nextRunAt).toLocaleString(undefined,{dateStyle:'medium',timeStyle:'short'})}`:'Paused'", "t.enabled?(t.nextRunAt?`Next: ${new Date(t.nextRunAt).toLocaleString(undefined,{dateStyle:'medium',timeStyle:'short'})}`:'Scheduled · calculating next run'):'Paused'")
s=s.replace('<IconBtn name={t.status===\'running\'?\'stop\':\'send\'}', '<Btn size="sm" icon={t.status===\'running\'?\'stop\':\'bolt\'}');s=s.replace('`))}/><button className="st-toggle"', '`))}>{t.status===\'running\'?\'Stop\':\'Run now\'}</Btn><label className="row small"><span>On schedule</span><button className="st-toggle"');s=s.replace('{enabled:!t.enabled}))}/></>', '{enabled:!t.enabled}))}/></label></>');s=s.replace("<Markdown text={selected.output??'No result yet.'}/>", "{selected.error?<ErrorNotice message={selected.error} next=\"Try running this task again.\"/>:<Markdown text={selected.output??'No result yet.'}/>}");p.write_text(s)
p=root/'src/screens/Skills.tsx';s=p.read_text().replace('Select, type IconName','Select, ErrorNotice, type IconName');s=s.replace('<p role="alert" className="inline-error">{error}</p>', '<ErrorNotice message={error} action="Retry" onRetry={()=>void action(\'refresh\',loadSkills)}/>');s=s.replace('enabled here','enabled in this workspace');p.write_text(s)
# Error consistency and sharing discoverability.
p=root/'src/screens/Serving.tsx';s=p.read_text().replace('IconBtn, Seg','IconBtn, Seg, ErrorNotice');s=s.replace(" function closeKey()", " function generateKey(){const bytes=crypto.getRandomValues(new Uint8Array(32));setKeyDraft('sk-strata-'+Array.from(bytes,v=>v.toString(16).padStart(2,'0')).join(''));setGenerated(true);}\n function closeKey()")
s=s.replace("setKeyDraft(''); setGenerated(false);", 'generateKey();');s=s.replace('<p role="alert" className="inline-error">{error}</p>', '<ErrorNotice message={error}/>');s=s.replace('<p ref={cancelResult} tabIndex={-1} role="alert">{selected.error}</p>', '<div ref={cancelResult} tabIndex={-1}><ErrorNotice message={selected.error} next="Check the client connection and try the request again."/></div>');s=s.replace('useRef<HTMLParagraphElement>', 'useRef<HTMLDivElement>')
s=s.replace("{selected.cancellable ? <Btn", "{selected.cancellable!==false&&['queued','generating'].includes(selected.state) ? <Btn")
s=s.replace("r.cancelRequested ? r.cancellable ? 'Cancelling…' : 'Cancelled' : r.state", "<span className=\"request-status\" data-state={r.state}>{r.cancelRequested ? r.cancellable ? 'Cancelling…' : 'Cancelled' : r.state.charAt(0).toUpperCase()+r.state.slice(1)}</span>")
s=s.replace(" : undefined} />}</section>", " : <Btn onClick={()=>setGuide(true)}>Connect an app</Btn>} />}</section>")
old='<IconBtn name="link" title={serving.sharing?.active ? \'Manage local sharing\' : \'Start local sharing\'} active={!!serving.sharing?.active} onClick={() => { setError(\'\'); setSharingOpen(true); }} />'
s=s.replace(old,'');s=s.replace('</dd></div>{serving.tunnel?.status', '</dd></div><div><dt>Local network</dt><dd className="row"><span className="request-status" data-state={serving.sharing?.active?"shared":"queued"}>{serving.sharing?.active?"Shared on local network":"Off"}</span><Btn size="sm" onClick={()=>{setError(\'\');setSharingOpen(true);}}>{serving.sharing?.active?"Manage / stop":"Share"}</Btn></dd></div>{serving.tunnel?.status')
s=s.replace('<code className="key-url">{serving.sharing.url}</code>', '<div className="row"><code className="key-url">{serving.sharing.url}</code><IconBtn name="copy" title="Copy local network URL" onClick={()=>void navigator.clipboard.writeText(serving.sharing!.url!)}/></div>')
s=s.replace('<IconBtn name="copy" title="Copy new API key" disabled={!keyDraft} onClick={() => void navigator.clipboard.writeText(keyDraft)} />', '{keyDraft?<IconBtn name="copy" title="Copy new API key" onClick={() => void navigator.clipboard.writeText(keyDraft)} />:null}')
s=s.replace('Generate a key for me</Btn>', 'Generate another key</Btn><button className="text-action" onClick={()=>{setKeyDraft(\'\');setGenerated(false);}}>Use my own key</button>')
s=s.replace("'Demo model ready'", "'Model ready'");p.write_text(s)
p=root/'src/components/CloudflareDialog.tsx';s=p.read_text().replace("from './ui';", "from './ui';")
s=s.replace('Btn, Dialog,', 'Btn, ErrorNotice, Dialog,');s=s.replace('<p className="inline-error" role="alert">{error||tunnel?.error}</p>', '<ErrorNotice message={error||tunnel?.error||\'Connection failed\'} next="Check the connector and network, then try connecting again."/>');p.write_text(s)
# Settings index follows the actual scroll container and filtered sections.
p=root/'src/screens/Settings.tsx';s=p.read_text().replace('useState, type ReactNode','useState, useEffect, useRef, type ReactNode');s=s.replace('CONTENT_FONT_RANGE, go,','CONTENT_FONT_RANGE, createChatShowcase, createPreviewExamples, go,');s=s.replace(" const fields:", " const bodyRef=useRef<HTMLDivElement>(null);\n const fields:");s=s.replace(" { section: 'About', label: 'Version'", " {section:'About',label:'Design examples',hint:'Explore code, media, approvals and file previews.',aliases:'help demo showcase',control:<div className=\"row\"><Btn size=\"sm\" onClick={createChatShowcase}>Chat showcase</Btn><Btn size=\"sm\" onClick={createPreviewExamples}>Preview examples</Btn></div>},\n { section: 'About', label: 'Version'")
s=s.replace('Manage models','Manage model versions');s=s.replace(' return <Screen', ''' useEffect(()=>{
const body=bodyRef.current,scroll=body?.closest('.main__body');if(!body||!scroll)return;
const sections=[...body.querySelectorAll<HTMLElement>('.settings-section')];
const update=()=>{const top=scroll.getBoundingClientRect().top+80;const current=sections.filter(s=>s.getBoundingClientRect().top<=top).at(-1)??sections[0];setActive(current?.id.replace('settings-','')??'');};
const observer=new IntersectionObserver(update,{root:scroll,rootMargin:'-70px 0px -55% 0px'});sections.forEach(s=>observer.observe(s));scroll.addEventListener('scroll',update,{passive:true});update();return()=>{observer.disconnect();scroll.removeEventListener('scroll',update);};
},[query]);
return <Screen''');s=s.replace("document.getElementById(`settings-${section}`)?.scrollIntoView({ block: 'start', behavior: scrollBehavior() });", "const target=document.getElementById(`settings-${section}`);const container=bodyRef.current?.closest('.main__body');if(target&&container)container.scrollTo({top:container.scrollTop+target.getBoundingClientRect().top-container.getBoundingClientRect().top-72,behavior:scrollBehavior()});")
s=s.replace('<div className="stack stack--lg settings-body">','<div ref={bodyRef} className="stack stack--lg settings-body">');p.write_text(s)
append('src/styles/app.css','''
.request-status { display:inline-flex; padding:3px 8px; border-radius:6px; background:var(--st-surface-2); color:var(--st-ink-soft); font-size:12px; white-space:nowrap; }.request-status[data-state='generating'] { color:var(--st-info-text); }.request-status[data-state='done'] { color:var(--st-accent-text); }.request-status[data-state='error'],.task-failed { color:var(--st-danger-text); }.request-status[data-state='shared'] { color:var(--st-warn-text); }
.setupmodal__surface { max-height:calc(100dvh - 48px); overflow:auto; background:var(--st-surface); opacity:1; animation:none; }.setup-redesign .setup-actions { position:sticky; bottom:0; padding:16px 0; background:var(--st-surface); z-index:2; }.setup-headline:focus { outline:none; }.setup-redesign .version-rung { padding:9px 12px; }.settings-body output { white-space:nowrap; min-width:44px; }
''')
@@ -0,0 +1,88 @@
from pathlib import Path
root=Path(__file__).resolve().parent.parent
def edit(file,old,new):
p=root/file;s=p.read_text();assert old in s,(file,old[:100]);p.write_text(s.replace(old,new))
def append(file,text):
p=root/file;p.write_text(p.read_text()+text)
append('src/lib/format.ts','''
/** Identity comes from the host; never substitute a different real model. */
export function formatModelName(model: {family:string;quant:string;name?:string}|null|undefined): string {
if (!model) return 'No model loaded';
const version = ({Q2_K:'Smallest',Q3_K_M:'Compact',Q4_K_M:'Balanced',Q5_K_M:'High quality',Q6_K:'Very high',Q8_0:'Near-original',BF16:'Original'} as Record<string,string>)[model.quant] ?? model.name;
return `${model.family} · ${version ? `${version} (${model.quant})` : model.quant}`;
}
export function userError(message: string): string {
return message.replace(/^\\s*Fixture:\\s*/i, '').replace(/^./, c => c.toUpperCase());
}
''')
edit('src/components/ui.tsx',"import { cx } from '../lib/format';","import { cx, userError } from '../lib/format';")
append('src/components/ui.tsx','''
/** Shared, announced error with a cause and a concrete recovery action. */
export function ErrorNotice({message, next, action, onRetry}: {message:string;next?:string;action?:string;onRetry?:()=>void}) {
return <div className="error-notice" role="alert"><Icon name="error" size={18}/><div><strong>{userError(message)}</strong>{next?<p>{next}</p>:null}</div>{onRetry?<Btn size="sm" onClick={onRetry}>{action??'Try again'}</Btn>:null}</div>;
}
export function PreviewBadge(){const demo=useStore(s=>s.library?.mode==='simulated');return demo?<span className="preview-badge">Preview build</span>:null;}
''')
edit('src/components/ui.tsx','style={{ left: placed.left, top: placed.top, width: placed.width }}',"style={{ left: placed.left, top: placed.top, width: placed.width, zIndex: triggerRef.current?.closest('[role=\"dialog\"]') ? 'var(--layer-dialog-popover)' : 'var(--layer-popover)' }}")
edit('src/components/Popover.tsx','style={{...position,width,',"style={{...position,zIndex:anchor?.closest('[role=\"dialog\"]')?'var(--layer-dialog-popover)':'var(--layer-popover)',width,")
edit('src/components/FloatingMenu.tsx','style={{ ...placed, width:',"style={{ ...placed, zIndex:anchor?.closest('[role=\"dialog\"]')?'var(--layer-dialog-popover)':'var(--layer-popover)', width:")
edit('src/components/layout.tsx',"import type { ReactNode } from 'react';","import type { ReactNode } from 'react';\nimport { PreviewBadge } from './ui';")
edit('src/components/layout.tsx','{title}</h1>','{title} <PreviewBadge/></h1>')
edit('src/app/Sidebar.tsx',"import { cx, relTime }", "import { cx, relTime, formatModelName }")
p=root/'src/app/Sidebar.tsx';s=p.read_text();start=s.index(' const modelName=');end=s.index(' const phase',start);s=s[:start]+" const modelName=formatModelName(current);\n const modelQuant=current ? 'Shared by all chats' : 'View model versions';\n"+s[end:];s=s.replace('<NavLink route="monitor"', '<NavLink route="skills" label="Skills" icon="thinking" current={location.route} />\n <NavLink route="monitor"');s=s.replace('<NavLink route="serving" label="Serving" icon="link" current={location.route} meta={serving?.stats.running ? String(serving.stats.running) : undefined} />','<NavLink route="tuning" label="Engine" icon="gauge" current={location.route} /><NavLink route="models" label="Model" icon="layers" current={location.route} />');s=s.replace('More — Skills, Models, Engine and Settings','More — Serving and Settings').replace("['skills', 'models', 'tuning', 'settings']","['serving', 'settings']");s=s.replace("{ route: 'skills', label: 'Skills', icon: 'thinking' }, { route: 'models', label: 'Models', icon: 'layers' }, { route: 'tuning', label: 'Engine', icon: 'gauge' },", "{ route: 'serving', label: 'Serving', icon: 'link' },");s=s.replace('<label className="strong" htmlFor="chat-name">Chat name</label><input className="st-input" id="chat-name" value={name} onChange={e => setName(e.target.value)} />','<label className="input-field" htmlFor="chat-name"><span>Chat name</span><input className="st-input" id="chat-name" value={name} onFocus={e=>e.currentTarget.select()} onChange={e => setName(e.target.value)} /></label>');s=s.replace('<Btn variant="danger" onClick={() => { if (deleteId) deleteSession(deleteId);','<Btn onClick={() => { if (deleteId) toggleArchive(deleteId); setDeleteId(null); }}>Archive instead</Btn><Btn variant="danger" onClick={() => { if (deleteId) deleteSession(deleteId);');p.write_text(s)
edit('src/lib/commands.ts',"label: 'Models'", "label: 'Model'")
edit('src/lib/commands.ts',"slash: ['new', 'clear']", "slash: ['new']")
edit('src/lib/commands.ts',"Check computer, choose model and load", "Check computer, pick a version and load")
# Flags retain unfinished controls without presenting them as working features.
(root/'src/lib/features.ts').write_text("export const features = { toolAccess: false, thinkingLevels: false, sessionLog: false, chatAttachments: false, demosInComposer: false } as const;\n")
edit('src/components/ChatToolbar.tsx',"import { Btn, Dialog, Icon, IconBtn }", "import { Btn, Dialog, Icon, IconBtn, PreviewBadge }")
edit('src/components/ChatToolbar.tsx',"import { SubagentRow }", "import { features } from '../lib/features';\nimport { SubagentRow }")
edit('src/components/ChatToolbar.tsx','</h1><button ref={agentsRef}', '</h1><PreviewBadge/>{!!session?.agents?.length&&<button ref={agentsRef}')
edit('src/components/ChatToolbar.tsx','size={13}/></button><span className="spacer"/>', 'size={13}/></button>}<span className="spacer"/>')
edit('src/components/ChatToolbar.tsx','</button><button role="menuitem" className="menu__item" onClick={()=>{setMenu(false);setLog(true);}}>', '</button>{features.sessionLog&&<button role="menuitem" className="menu__item" onClick={()=>{setMenu(false);setLog(true);}}>')
edit('src/components/ChatToolbar.tsx','Download Session Log</button></FloatingMenu>','Download session log</button>}</FloatingMenu>')
edit('src/components/ChatToolbar.tsx','<Icon name="chevron" size={16}/></button>)}</div></Dialog>', '<span className="xs muted">Use template</span></button>)}</div></Dialog>')
append('src/styles/app.css','''
/* Audit fixes: shared states and overlay ownership. */
:root { --layer-base: 0; --layer-sticky: 10; --layer-sidebar: 20; --layer-popover: 100; --layer-dialog: 160; --layer-dialog-popover: 180; --layer-toast: 200; }
html, body { overflow: hidden; }
.main__body, .dialog-body { scrollbar-gutter: stable; }
.dialog-layer { z-index: var(--layer-dialog); }
.dialog-scrim, .scrim { background: rgb(0 0 0 / .36); }
[data-theme='dark'] .dialog-scrim, [data-theme='dark'] .scrim { background: rgb(0 0 0 / .55); }
.dialog-surface, .palette, .setup__panel { opacity: 1; background: var(--st-surface); animation: none; }
.dialog-head, .dialog-actions { flex-shrink: 0; }
.select__pop { z-index: var(--layer-dialog-popover); background: var(--st-surface); }
.menu, .anchored-popover { z-index: var(--layer-popover); background: var(--st-surface); }
.st-btn--primary, .nav-new.st-btn--primary { background: #10b981; color: #0b1f17; border-color: #10b981; }
.st-btn--primary:hover:not(:disabled), .nav-new.st-btn--primary:hover:not(:disabled) { background: #22ce95; color: #0b1f17; border-color: #22ce95; }
.st-btn:disabled { background: var(--st-surface-2); border-color: var(--st-line); color: var(--st-ink-muted); opacity: .65; box-shadow: none; }
.st-toggle[aria-checked='true'] { background: #10b981; border-color: #10b981; }
.st-toggle[aria-checked='true']::after { background: #fff; }
input[type='checkbox'], input[type='radio'] { accent-color: #10b981; }
textarea { font-family: inherit; }
.error-notice { display:flex; gap:10px; align-items:flex-start; padding:12px 14px; margin:12px 0; border:1px solid var(--st-danger-text); border-radius:12px; background:var(--st-surface); color:var(--st-danger-text); font-size:13px; }
.error-notice > svg { flex-shrink:0; margin-top:2px; }
.error-notice > div { flex:1; min-width:0; }
.error-notice p { margin:4px 0 0; color:var(--st-ink-soft); }
.st-input[aria-invalid='true'] { border-color:var(--st-danger-text); }
.preview-badge { display:inline-flex; flex-shrink:0; align-items:center; border:1px solid var(--st-line); border-radius:6px; color:var(--st-ink-muted); padding:3px 6px; font-size:10px; font-weight:500; white-space:nowrap; }
.st-msg { min-width:0; }
.st-msg__meta { display:flex; flex-direction:row; flex-wrap:nowrap; min-width:0; width:100%; gap:8px; }
.st-msg__actions { display:flex; flex-wrap:nowrap; opacity:0; }
.st-msg:hover .st-msg__actions, .st-msg:focus-within .st-msg__actions { opacity:1; }
.message-overflow { position:relative; }
.message-overflow > div { position:absolute; top:100%; bottom:auto; left:0; min-width:240px; width:max-content; max-width:calc(100vw - 40px); background:var(--st-surface); border:1px solid var(--st-line); border-radius:12px; padding:10px; z-index:5; display:flex; flex-direction:column; align-items:stretch; box-shadow:var(--st-sh-pop); }
.st-msg--user .message-overflow > div { left:auto; right:0; }
.response-stats { white-space:nowrap; }
.composer .st-composer textarea { min-height:44px; height:44px; max-height:180px; padding:12px 16px; }
.composer { padding-top:10px; padding-bottom:10px; }
.composer-model { max-width:270px; }
.composer-model span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.chat-toolbar__conversation h1 { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.tool-summary { font-size:13px; color:var(--st-ink-soft); }
.tool-summary summary { display:flex; align-items:center; gap:6px; font-weight:500; list-style:none; }
.tool-summary summary::-webkit-details-marker { display:none; }
.tool-summary[open] summary > svg:first-child { transform:rotate(180deg); }
@media (hover:none) { .st-msg__actions { opacity:1; } }
''')
@@ -0,0 +1,120 @@
{
"version": 1,
"setup": {
"complete": true,
"flowVersion": 2,
"step": 4,
"history": [
{
"step": 1,
"at": "2026-10-05T18:00:10.057Z"
},
{
"step": 2,
"at": "2026-10-05T18:51:53.450Z"
},
{
"step": 2,
"at": "2026-10-05T18:51:53.886Z"
},
{
"step": 2,
"at": "2026-10-05T18:52:00.541Z"
},
{
"step": 2,
"at": "2026-10-05T18:52:02.205Z"
},
{
"step": 2,
"at": "2026-10-05T18:52:04.790Z"
},
{
"step": 2,
"at": "2026-10-05T18:52:05.651Z"
},
{
"step": 2,
"at": "2026-10-05T18:52:06.436Z"
},
{
"step": 2,
"at": "2026-10-05T18:52:07.787Z"
},
{
"step": 2,
"at": "2026-10-05T18:52:08.814Z"
},
{
"step": 2,
"at": "2026-10-05T18:52:09.420Z"
},
{
"step": 2,
"at": "2026-10-05T18:53:03.761Z"
},
{
"step": 3,
"at": "2026-10-05T18:55:28.371Z"
},
{
"step": 4,
"at": "2026-10-05T18:55:41.653Z"
}
],
"dismissed": false,
"choices": {
"variantId": "qwen2.5-0.5b-q4km",
"contextLength": "32k",
"profile": "balanced",
"batch": 2048,
"batchAuto": true
},
"completedAt": "2026-10-05T19:15:31.747Z"
},
"installed": {
"qwen2.5-0.5b-q4km": {
"installedAt": "2026-10-05T18:55:39.914Z",
"simulated": true
}
},
"current": "qwen2.5-0.5b-q4km",
"loaded": "qwen2.5-0.5b-q4km",
"beginner": {
"priority": "balanced",
"contextLength": "32k",
"readImages": false,
"gpuIdle": "never"
},
"expert": {
"ctx.length": "32K",
"perf.batch": 2048,
"perf.threads": 2,
"ctx.kvMode": "INT8",
"gpu.layers": "Automatic"
},
"serving": {
"otherDevices": false,
"apiKey": null,
"pauseServing": true
},
"configExtra": {
"batchAutomatic": true
},
"tasks": [
{
"title": "new test task",
"prompt": "do this",
"frequency": "daily",
"at": "09:00",
"weekday": 1,
"timeZone": "Europe/Zagreb",
"enabled": true,
"id": "4d1dd4be-830d-438b-8d9a-58a20245f031",
"createdAt": "2026-10-06T20:00:52.943Z",
"status": "idle",
"archived": false,
"nextRunAt": "2026-10-07T07:00:00.000Z"
}
]
}
@@ -0,0 +1,54 @@
changed: src/app/Sidebar.tsx
changed: src/components/ArtifactCard.tsx
changed: src/components/ArtifactPanel.tsx
changed: src/components/ChatToolbar.tsx
changed: src/components/CloudflareDialog.tsx
changed: src/components/ComposerControls.tsx
changed: src/components/EngineExperience.tsx
changed: src/components/FloatingMenu.tsx
changed: src/components/Markdown.tsx
removed: src/components/ModelCatalog.tsx
changed: src/components/PdfPreview.tsx
changed: src/components/Popover.tsx
changed: src/components/SubagentRow.tsx
changed: src/components/TaskEditor.tsx
changed: src/components/TelemetryPopover.tsx
changed: src/components/TimeSkipPanel.tsx
changed: src/components/layout.tsx
changed: src/components/ui.tsx
changed: src/lib/chat-metrics.ts
changed: src/lib/client.ts
changed: src/lib/commands.ts
changed: src/lib/config.ts
changed: src/lib/format.ts
changed: src/lib/hardware-summary.ts
changed: src/lib/store.ts
changed: src/lib/types.ts
changed: src/screens/Chat.tsx
changed: src/screens/Models.tsx
changed: src/screens/Monitor.tsx
changed: src/screens/Serving.tsx
changed: src/screens/Settings.tsx
changed: src/screens/Setup.tsx
changed: src/screens/Skills.tsx
changed: src/screens/Tasks.tsx
changed: src/screens/Tuning.tsx
changed: src/styles/app.css
changed: server/catalog.mjs
changed: server/models.mjs
changed: server/monitor.mjs
changed: scripts/contrast.mjs
changed: scripts/luminance.mjs
changed: scripts/measure.mjs
changed: scripts/motion.mjs
changed: scripts/motionbudget.mjs
changed: tests/reliability.test.mjs
changed: tests/request-flow.test.mjs
changed: tests/ui-fixture-host.mjs
added: src/components/PreviewControls.tsx
added: src/components/VersionLadder.tsx
added: src/components/AutoTune.tsx
added: src/lib/model-versions.ts
added: src/lib/features.ts
added: server/real-model-catalog.mjs
added: tests/audit-fixes.test.mjs

Some files were not shown because too many files have changed in this diff Show More