Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
host: window mode vs browser mode (app-ui.mjs): Quit Strata, the shell's UI route, app updater unavailable in browser mode with a plain message
Niko1221e01f76611892
diff --git a/apps/host/server/app-ui.mjs b/apps/host/server/app-ui.mjsnew file mode 100644index 000000000..5596daa0a--- /dev/null+++ b/apps/host/server/app-ui.mjs@@ -0,0 +1,106 @@+/**+ * Which window the person is using, and what only the app window can do.+ *+ * The Linux app starts the host itself (the "shell" process, which has no window) and shows the page in a separate window+ * process. WebKitGTK can crash that process on some computers; the shell then keeps the host running and opens the same page+ * in the default browser ("browser mode"). A person can also choose browser mode (`--browser`, STRATA_UI=browser).+ *+ * mode 'window' the app window shows the page; the window process registers the app updater here (Tauri's signed updater).+ * mode 'browser' an ordinary browser tab shows the page. There is no window process, so the app cannot update itself, and+ * closing the tab does not stop the engine: the menu has "Quit Strata" (POST /api/app/quit) and the command+ * line has `--quit`.+ * mode null not started by the app (the host run by hand, a test, a source checkout): nothing here applies.+ *+ * What needs the Tauri bridge and what happens without it (browser mode):+ * folder picker works: the host runs zenity / kdialog / the desktop portal itself (folder-dialog.mjs), else the page asks for the path+ * open a file / folder works: the host runs xdg-open itself (chat-files.mjs, artifacts.mjs)+ * window controls none to offer: the browser has its own tab and window; the page never called the shell for them+ * notifications the page does not use the shell for them; the host sends the one desktop notification it needs (notify-send)+ * app updater NOT available: Tauri's updater lives in the window process. Settings says so in plain words and the+ * engine and component updates (Strata Control) still work.+ */+import { execFile, spawn } from 'node:child_process';+import { externalEnvironment } from './external-env.mjs';+import { createAppUpdater } from './app-updater.mjs';++export const APP_UPDATE_UNAVAILABLE = 'app-update-unavailable';+export const BROWSER_UPDATE_MESSAGE = "The Strata app itself can't be updated in browser mode. Start Strata from its icon, without --browser, to update it.";+const BRIDGE_URL = /^http:\/\/127\.0\.0\.1:\d+$/;+const MODES = new Set(['window', 'browser']);++/** Browsers and openers to try, in order, when the address of the page is opened for the person. */+export const OPENERS = [['xdg-open'], ['gio', 'open'], ['sensible-browser'], ['x-www-browser'], ['firefox'], ['chromium'], ['google-chrome']];++/**+ * Start one opener and say whether it took the address: false when the program is missing or ends with an error within a couple of+ * seconds. xdg-open often stays running until the browser closes, so a program that is still running counts as success.+ */+export function startOpener(command, args, { spawnProcess = spawn, env = externalEnvironment(), settleMs = 2500 } = {}) {+ return new Promise(resolve => {+ let child;+ try { child = spawnProcess(command, args, { detached: true, stdio: 'ignore', env }); } catch { return resolve(false); }+ let done = false;+ const finish = value => { if (!done) { done = true; clearTimeout(timer); resolve(value); } };+ const timer = setTimeout(() => { try { child.unref?.(); } catch { /* ignore */ } finish(true); }, settleMs);+ child.on('error', () => finish(false));+ child.on('exit', code => finish(code === 0));+ });+}++export async function openInBrowser(url, { openers = OPENERS, start = startOpener } = {}) {+ for (const [command, ...rest] of openers) if (await start(command, [...rest, url])) return true;+ return false;+}++/** One desktop notification (notify-send), best effort: no notification daemon or no notify-send is not an error. */+export function sendNotification(message, { run = execFile, env = externalEnvironment() } = {}) {+ return new Promise(resolve => {+ try { run('notify-send', ['--app-name=Strata', '--icon=dialog-information', 'Strata', message], { env, timeout: 5000 }, error => resolve(!error)); }+ catch { resolve(false); }+ });+}++export function createAppUi({ env = process.env, shutdown = () => {}, open = openInBrowser, notify = sendNotification, createUpdater = createAppUpdater } = {}) {+ let mode = MODES.has(env.STRATA_UI_MODE) ? env.STRATA_UI_MODE : null;+ let reason = mode === 'browser' ? (env.STRATA_UI_REASON || 'chosen') : null;+ let bridge = null;+ const originalBridge = createUpdater({ env }); // the older way: the shell passed the bridge in the environment++ /** The shell's updater as the rest of the host sees it, or null when no app started this host. */+ const updater = mode === null && !originalBridge ? null : {+ get unavailable() { return mode === 'browser' ? BROWSER_UPDATE_MESSAGE : null; },+ async check() { return (await current()).check(); },+ async install(options) { return (await current()).install(options); },+ };+ async function current() {+ if (bridge) return bridge;+ if (originalBridge) return originalBridge;+ throw Object.assign(new Error(mode === 'browser' ? BROWSER_UPDATE_MESSAGE : 'The app updater is not ready yet. Try again in a moment.'), { code: APP_UPDATE_UNAVAILABLE });+ }++ return {+ updater,+ get mode() { return mode; },+ /** What the page reads to decide what to show. */+ state: () => ({ mode, reason, canQuit: mode === 'browser', appUpdate: mode === 'browser' || mode === null ? 'unavailable' : 'available' }),+ /** The window process hands over its updater bridge (a loopback address and a token). */+ setBridge({ url, token } = {}) {+ if (typeof url !== 'string' || !BRIDGE_URL.test(url) || typeof token !== 'string' || token.length < 16) throw new Error('That is not a bridge address.');+ bridge = createUpdater({ env: { STRATA_SHELL_BRIDGE: url, STRATA_SHELL_TOKEN: token } });+ return true;+ },+ /** The shell moves everyone to a browser tab: the window could not start or has stopped. */+ async switchToBrowser({ url, reason: why = 'window-failed', notice = '', openPage = true } = {}) {+ mode = 'browser'; reason = String(why).slice(0, 40); bridge = null;+ const opened = openPage && url ? await open(url) : false;+ if (notice) void notify(notice);+ return { mode, reason, opened };+ },+ /** The "Quit Strata" menu entry: only in browser mode, where closing the tab leaves the engine running. */+ quit() {+ if (mode !== 'browser') return { ok: false, status: 409, error: 'Close the Strata window to quit.' };+ setImmediate(() => void shutdown());+ return { ok: true, status: 202 };+ },+ };+}diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex 63210c21f..3a4accd43 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -57,7 +57,7 @@ import { createForkTimeskip } from './timeskip-fork.mjs';import { createChatFolders, openFile, resolveChatFile, previewFile, rawFile, createAttachments, withAttachments } from './chat-files.mjs';import { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs';import { checkUpdates, checkComponentUpdates } from './updates.mjs';-import { createAppUpdater } from './app-updater.mjs';+import { createAppUi } from './app-ui.mjs';import { createImageModels } from './image-models.mjs';import { createRuntimeModels } from './runtime-models.mjs';import { createNativeControl } from './native-control.mjs';@@ -111,7 +111,9 @@ const CONTROL = findControl();const control = createControl({ control: CONTROL });// Files a run as administrator made in Strata's own folders (owner Administrators) are given back to the user at every start; best effort, never blocks.if (control && process.platform === 'win32' && !process.env.STRATA_NO_REPAIR_ACCESS) void control.repairAccess().catch(() => {});-const appUpdater = createAppUpdater();+/* Which window shows the page (the app window or, when that cannot run, a browser tab) and what only the app window can do: app-ui.mjs. */+const appUi = createAppUi({ shutdown: () => shutdown() });+const appUpdater = appUi.updater;/* The engine that ships inside the installer is put in the components folder when this PC has none (or an older one); no network, hashes checked. The model list waits for it. */const bundledEngine = control && !process.env.STRATA_NO_BUNDLED_ENGINE? installBundledEngine({ bundleDir: process.env.STRATA_ENGINE_BUNDLE_DIR || resolve(HERE, '..', '..', 'engine-bundle'), components: componentsDirectory(), log: line => console.log(line) })@@ -1207,12 +1209,33 @@ async function api(req, res, path, method, url) {acquisition: { forbidden: acquisitionForbidden(), env: process.env.STRATA_NO_ACQUIRE ?? null },});}- // The shell asks for a clean stop (engines this app started are stopped through Control) before it ends the process.- if (path === '/api/control/shutdown' && method === 'POST') {+ // The shell (and nothing else) holds the secret that lets it end the host or tell it which window is in use.+ const fromShell = () => {const token = process.env.STRATA_SHUTDOWN_TOKEN ?? '';const given = String(req.headers['x-strata-shutdown'] ?? '');- const same = token.length >= 32 && given.length === token.length && timingSafeEqual(Buffer.from(given), Buffer.from(token));- if (!same) return error(res, 403, 'Not allowed.');+ return token.length >= 32 && given.length === token.length && timingSafeEqual(Buffer.from(given), Buffer.from(token));+ };+ // Which window the person is using: the page shows "Quit Strata" in browser mode only.+ if (path === '/api/app/mode' && method === 'GET') return json(res, 200, appUi.state());+ if (path === '/api/app/quit' && method === 'POST') {+ // A web page cannot send this header without the browser asking the host first, and the host refuses pages that are not local (above).+ if (!req.headers['x-strata-client']) return error(res, 403, 'Not allowed.');+ const verdict = appUi.quit();+ return verdict.ok ? json(res, verdict.status, { stopping: true }) : error(res, verdict.status, verdict.error);+ }+ // The shell: the window process registers its updater; or the window could not run and everything moves to a browser tab.+ if (path === '/api/control/ui' && method === 'POST') {+ if (!fromShell()) return error(res, 403, 'Not allowed.');+ const body = await readBody(req);+ try {+ if (body.bridge) appUi.setBridge(body.bridge);+ if (body.mode === 'browser') return json(res, 200, await appUi.switchToBrowser({ url: `http://127.0.0.1:${PORT}/`, reason: body.reason, notice: typeof body.notice === 'string' ? body.notice.slice(0, 300) : '', openPage: body.open !== false }));+ return json(res, 200, appUi.state());+ } catch (err) { return error(res, 400, err.message); }+ }+ // The shell asks for a clean stop (engines this app started are stopped through Control) before it ends the process.+ if (path === '/api/control/shutdown' && method === 'POST') {+ if (!fromShell()) return error(res, 403, 'Not allowed.');json(res, 202, { stopping: true });setImmediate(() => void shutdown());return;diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjsindex f4b114c30..7535432ea 100644--- a/apps/host/server/native-control.mjs+++ b/apps/host/server/native-control.mjs@@ -294,7 +294,8 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}const notes=[updateSummary(done)];if(appUpdater){job.summary='Looking for a new version of the app…';emit();- const verdict=await appUpdater.check();+ let verdict;+ try{verdict=await appUpdater.check();}catch(error){if(error?.code!=='app-update-unavailable')throw error;verdict={available:false};notes.push(appUpdater.unavailable||error.message);}if(verdict.available){await appUpdater.install({signal:job.abort.signal,onProgress:p=>{if(p.total){job.summary=`Downloading the app update: ${Math.round(100*p.downloaded/p.total)}%`;job.result={install:{step:job.summary,download:{file:'Strata app',percent:Math.round(100*p.downloaded/p.total)}}};emit();}}});notes.push('The app update is installed. Strata will restart.');}}return {summary:notes.filter(Boolean).join(' '),result:done};diff --git a/apps/host/server/updates.mjs b/apps/host/server/updates.mjsindex 1f420a29d..1d890b8d4 100644--- a/apps/host/server/updates.mjs+++ b/apps/host/server/updates.mjs@@ -73,16 +73,19 @@ export async function checkComponentUpdates({ control, appUpdater = null, appVerconst app = report.app ?? {};let appNew = app.status === 'available' ? app.offered : null;let appNotes = app.notes ?? '';+ let appCannot = null; // browser mode: the app window's updater is not running, so the app itself cannot be updated from hereif (appUpdater) {try {const verdict = await appUpdater.check();appNew = verdict.available ? verdict.version : null;appNotes = verdict.notes ?? appNotes;- } catch { /* the feed's own view stands */ }+ } catch (error) {+ if (error?.code === 'app-update-unavailable' && appUpdater.unavailable) appCannot = appUpdater.unavailable; // otherwise the feed's own view stands+ }}const controlNew = control_.status === 'available' ? control_.offered : null;- const strata = { installedVersion: appVersion ?? control_.installed ?? control.version ?? null, canInstall: !!(appNew || controlNew) };- if (appNew || controlNew) Object.assign(strata, { status: 'available', latestVersion: appNew ?? controlNew, message: `A new version of Strata is available.${appNotes ? ` ${appNotes}` : ''}` });+ const strata = { installedVersion: appVersion ?? control_.installed ?? control.version ?? null, canInstall: !!((appNew && !appCannot) || controlNew) };+ if (appNew || controlNew) Object.assign(strata, { status: 'available', latestVersion: appNew ?? controlNew, message: `A new version of Strata is available.${appNotes ? ` ${appNotes}` : ''}${appNew && appCannot ? ` ${appCannot}` : ''}` });else Object.assign(strata, { status: 'current', message: 'Strata is up to date.' });return { checkedAt, feed: report.feed, strata, engine: engineView, serving: report.serving ?? [] };}diff --git a/apps/host/tests/app-ui.test.mjs b/apps/host/tests/app-ui.test.mjsnew file mode 100644index 000000000..5b04c8c32--- /dev/null+++ b/apps/host/tests/app-ui.test.mjs@@ -0,0 +1,140 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createServer } from 'node:net';+import { fileURLToPath } from 'node:url';+import { EventEmitter } from 'node:events';+import { createAppUi, openInBrowser, startOpener, APP_UPDATE_UNAVAILABLE, BROWSER_UPDATE_MESSAGE } from '../server/app-ui.mjs';+import { checkComponentUpdates } from '../server/updates.mjs';++const root = fileURLToPath(new URL('..', import.meta.url));+const delay = ms => new Promise(r => setTimeout(r, ms));+const bridgeEnv = { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:5555', STRATA_SHELL_TOKEN: 'a'.repeat(32) };++test('a host nobody started has no window mode, no Quit and no updater', () => {+ const ui = createAppUi({ env: {} });+ assert.deepEqual(ui.state(), { mode: null, reason: null, canQuit: false, appUpdate: 'unavailable' });+ assert.equal(ui.updater, null);+ assert.equal(ui.quit().ok, false);+});++test('window mode: no Quit entry (closing the window ends everything), the updater waits for the window process', async () => {+ const ui = createAppUi({ env: { STRATA_UI_MODE: 'window' } });+ assert.equal(ui.state().canQuit, false);+ assert.equal(ui.state().appUpdate, 'available');+ assert.equal(ui.quit().status, 409);+ await assert.rejects(ui.updater.check(), error => error.code === APP_UPDATE_UNAVAILABLE);+ ui.setBridge({ url: 'http://127.0.0.1:6001', token: 'b'.repeat(32) });+ assert.ok(ui.updater);+ assert.throws(() => ui.setBridge({ url: 'http://example.com:1', token: 'b'.repeat(32) }), /not a bridge/);+ assert.throws(() => ui.setBridge({ url: 'http://127.0.0.1:6001', token: 'short' }), /not a bridge/);+});++test('browser mode (chosen): Quit works once and the app updater says why it is not available', async () => {+ let stopped = 0;+ const ui = createAppUi({ env: { STRATA_UI_MODE: 'browser' }, shutdown: () => { stopped++; } });+ assert.deepEqual(ui.state(), { mode: 'browser', reason: 'chosen', canQuit: true, appUpdate: 'unavailable' });+ assert.equal(ui.updater.unavailable, BROWSER_UPDATE_MESSAGE);+ await assert.rejects(ui.updater.check(), error => error.code === APP_UPDATE_UNAVAILABLE && error.message === BROWSER_UPDATE_MESSAGE);+ assert.equal(ui.quit().status, 202);+ await delay(20);+ assert.equal(stopped, 1);+});++test('the shell moves a window host to a browser tab: opens the page, sends the notice, drops the window updater', async () => {+ const opened = [], notices = [];+ const ui = createAppUi({ env: { STRATA_UI_MODE: 'window' }, open: async url => { opened.push(url); return true; }, notify: async text => { notices.push(text); } });+ ui.setBridge({ url: 'http://127.0.0.1:6001', token: 'b'.repeat(32) });+ const out = await ui.switchToBrowser({ url: 'http://127.0.0.1:47831/', notice: 'Strata opened in your browser because the app window couldn\'t start on this computer.' });+ assert.deepEqual(out, { mode: 'browser', reason: 'window-failed', opened: true });+ assert.deepEqual(opened, ['http://127.0.0.1:47831/']);+ assert.equal(notices.length, 1);+ assert.equal(ui.state().canQuit, true);+ await assert.rejects(ui.updater.check(), error => error.code === APP_UPDATE_UNAVAILABLE);+ // no browser could be opened: the shell is told, it prints the address+ const none = createAppUi({ env: { STRATA_UI_MODE: 'window' }, open: async () => false, notify: async () => false });+ assert.equal((await none.switchToBrowser({ url: 'http://127.0.0.1:1/' })).opened, false);+});++test('openers are tried in order until one takes the address', async () => {+ const tried = [];+ const ok = await openInBrowser('http://127.0.0.1:1/', { openers: [['xdg-open'], ['gio', 'open'], ['firefox']], start: async (cmd, args) => { tried.push([cmd, ...args].join(' ')); return cmd === 'gio'; } });+ assert.equal(ok, true);+ assert.deepEqual(tried, ['xdg-open http://127.0.0.1:1/', 'gio open http://127.0.0.1:1/']);+ assert.equal(await openInBrowser('x', { openers: [['a'], ['b']], start: async () => false }), false);+});++test('an opener that is missing or fails fast is a failure; one still running is a success', async () => {+ const fake = behaviour => () => { const child = new EventEmitter(); child.unref = () => {}; queueMicrotask(() => behaviour(child)); return child; };+ assert.equal(await startOpener('x', [], { env: {}, settleMs: 200, spawnProcess: fake(c => c.emit('error', new Error('ENOENT'))) }), false);+ assert.equal(await startOpener('x', [], { env: {}, settleMs: 200, spawnProcess: fake(c => c.emit('exit', 3)) }), false);+ assert.equal(await startOpener('x', [], { env: {}, settleMs: 200, spawnProcess: fake(c => c.emit('exit', 0)) }), true);+ assert.equal(await startOpener('x', [], { env: {}, settleMs: 50, spawnProcess: fake(() => {}) }), true);+});++test('update check in browser mode: the app part says it cannot be done here, engine/component updates stay possible', async () => {+ const control = { version: '0.1.0', updateCheck: async () => ({ app: { status: 'available', offered: '0.2.0', notes: 'Faster.' }, engine: { status: 'current', installed: { version: '1' } }, control: { status: 'current' } }) };+ const browser = createAppUi({ env: { STRATA_UI_MODE: 'browser' } });+ const inBrowser = await checkComponentUpdates({ control, appUpdater: browser.updater, appVersion: '0.1.0' });+ assert.equal(inBrowser.strata.status, 'available');+ assert.equal(inBrowser.strata.canInstall, false);+ assert.match(inBrowser.strata.message, /can't be updated in browser mode/);+ // the same check with the window's updater in place offers the update as before+ const windowed = createAppUi({ env: { STRATA_UI_MODE: 'window', ...bridgeEnv }, createUpdater: ({ env }) => env.STRATA_SHELL_BRIDGE ? { check: async () => ({ available: true, version: '0.2.0', notes: 'Faster.' }), install: async () => {} } : null });+ const inWindow = await checkComponentUpdates({ control, appUpdater: windowed.updater, appVersion: '0.1.0' });+ assert.equal(inWindow.strata.canInstall, true);+ assert.doesNotMatch(inWindow.strata.message, /browser mode/);+});++async function freePort() { 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; }++async function startHost(extraEnv) {+ const home = await mkdtemp(join(tmpdir(), 'strata-host-appui-'));+ const port = await freePort();+ const host = spawn(process.execPath, ['server/index.mjs'], {+ cwd: root, stdio: 'ignore',+ env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_NO_ACQUIRE: '1', STRATA_NO_BUNDLED_ENGINE: '1', ...extraEnv },+ });+ let up = false;+ for (let i = 0; i < 150 && !up; i++) { try { up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok; } catch { await delay(100); } }+ assert.ok(up, 'the host answers');+ const exited = new Promise(resolve => host.on('exit', code => resolve(code)));+ return { port, host, exited, home, base: `http://127.0.0.1:${port}` };+}++test('browser-mode host over HTTP: mode, Quit needs the client header, then the host stops cleanly and only listens on 127.0.0.1', async () => {+ const { port, host, exited, home, base } = await startHost({ STRATA_UI_MODE: 'browser' });+ try {+ const mode = await (await fetch(`${base}/api/app/mode`)).json();+ assert.equal(mode.mode, 'browser'); assert.equal(mode.canQuit, true);+ // a plain POST (what a web page could send without asking first) is refused, and so is a page from another site+ assert.equal((await fetch(`${base}/api/app/quit`, { method: 'POST' })).status, 403);+ assert.equal((await fetch(`${base}/api/app/quit`, { method: 'POST', headers: { 'x-strata-client': 'ui', origin: 'https://example.com' } })).status, 403);+ // the shell's own routes need the secret+ assert.equal((await fetch(`${base}/api/control/ui`, { method: 'POST', body: '{}' })).status, 403);+ // it is listening on the loopback address only+ const { networkInterfaces } = await import('node:os');+ const other = Object.values(networkInterfaces()).flat().find(i => i && !i.internal && i.family === 'IPv4');+ if (other) await assert.rejects(fetch(`http://${other.address}:${port}/api/health`, { signal: AbortSignal.timeout(2000) }));+ assert.equal((await fetch(`${base}/api/app/quit`, { method: 'POST', headers: { 'x-strata-client': 'ui' } })).status, 202);+ assert.equal(await Promise.race([exited, delay(30000).then(() => 'still running')]), 0);+ } finally { host.kill(); await rm(home, { recursive: true, force: true }); }+});++test('window-mode host over HTTP: Quit is refused; the shell (with its secret) registers the bridge and can move the host to browser mode', async () => {+ const secret = 'c'.repeat(64);+ const { host, home, base } = await startHost({ STRATA_UI_MODE: 'window', STRATA_SHUTDOWN_TOKEN: secret, STRATA_OPENER: 'record' });+ try {+ assert.equal((await fetch(`${base}/api/app/quit`, { method: 'POST', headers: { 'x-strata-client': 'ui' } })).status, 409);+ const as = (body, token = secret) => fetch(`${base}/api/control/ui`, { method: 'POST', headers: { 'x-strata-shutdown': token, 'content-type': 'application/json' }, body: JSON.stringify(body) });+ assert.equal((await as({}, 'd'.repeat(64))).status, 403);+ assert.equal((await as({ bridge: { url: 'http://evil.example:1', token: 'e'.repeat(32) } })).status, 400);+ assert.equal((await as({ bridge: { url: 'http://127.0.0.1:9', token: 'e'.repeat(32) } })).status, 200);+ const moved = await (await as({ mode: 'browser', reason: 'window-failed', open: false })).json();+ assert.equal(moved.mode, 'browser');+ assert.equal((await (await fetch(`${base}/api/app/mode`)).json()).reason, 'window-failed');+ } finally { host.kill(); await rm(home, { recursive: true, force: true }); }+});