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: folder picker and skill-add work on Windows (PowerShell FolderBrowserDialog) and Linux (zenity, kdialog); a typed path replaces the dialog where none exists
Niko1221decb3f3f8d7c
diff --git a/apps/host/server/folder-dialog.mjs b/apps/host/server/folder-dialog.mjsnew file mode 100644index 000000000..1748373b4--- /dev/null+++ b/apps/host/server/folder-dialog.mjs@@ -0,0 +1,94 @@+/**+ * The host's native "choose a folder" dialog, one per platform:+ * macOS osascript (choose folder) -- unchanged+ * Windows PowerShell FolderBrowserDialog (STA, topmost owner so it never opens behind the app)+ * Linux zenity, then kdialog+ * Where no dialog exists the caller gets { unavailable: true } and tells the person to type a path.+ */+import { stat } from 'node:fs/promises';+import { exec } from './util.mjs';++const MAC_SCRIPT = prompt => `POSIX path of (choose folder with prompt "${prompt.replace(/["\\]/g, '')}")`;++export function windowsFolderScript(prompt) {+ const text = prompt.replace(/'/g, "''");+ return [+ 'Add-Type -AssemblyName System.Windows.Forms',+ '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',+ '$owner = New-Object System.Windows.Forms.Form',+ '$owner.TopMost = $true; $owner.ShowInTaskbar = $false; $owner.StartPosition = "CenterScreen"; $owner.Size = New-Object System.Drawing.Size(0, 0)',+ '$owner.Show(); $owner.Activate()',+ '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog',+ `$dialog.Description = '${text}'`,+ '$dialog.ShowNewFolderButton = $true',+ 'if ($dialog.ShowDialog($owner) -eq "OK") { [Console]::Out.Write($dialog.SelectedPath) }',+ '$owner.Close()',+ ].join('; ');+}++/** powershell.exe takes the script as UTF-16LE base64, so no quoting survives to be mangled. */+export function windowsFolderArgs(prompt) {+ return ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(windowsFolderScript(prompt), 'utf16le').toString('base64')];+}++/** Strip trailing separators, but leave a drive or filesystem root intact. */+export function cleanChosenPath(value) {+ const text = String(value ?? '').trim();+ if (/^[A-Za-z]:[\\/]*$/.test(text)) return text.slice(0, 2) + '\\';+ return text.length > 1 ? text.replace(/[\\/]+$/, '') || text.slice(0, 1) : text;+}++const missing = error => error?.code === 'ENOENT';++/**+ * Ask for a folder. Resolves { path } | { cancelled: true } | { unavailable: true, reason }.+ * `run` is injectable for tests: (command, args) => Promise<{ stdout }>.+ */+export async function chooseFolder(prompt, { platform = process.platform, run = exec } = {}) {+ if (platform === 'darwin') {+ try {+ const { stdout } = await run('osascript', ['-e', MAC_SCRIPT(prompt)]);+ return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true };+ } catch {+ return { cancelled: true }; // dismissing the dialog is an exit code, not a failure+ }+ }+ if (platform === 'win32') {+ const shell = `${process.env.SystemRoot || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;+ try {+ const { stdout } = await run(shell, windowsFolderArgs(prompt));+ return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true };+ } catch (error) {+ if (missing(error)) return { unavailable: true, reason: 'Windows PowerShell was not found.' };+ throw new Error('The folder chooser could not open.');+ }+ }+ const candidates = [+ ['zenity', ['--file-selection', '--directory', `--title=${prompt}`]],+ ['kdialog', ['--getexistingdirectory', '.', '--title', prompt]],+ ];+ for (const [command, args] of candidates) {+ try {+ const { stdout } = await run(command, args);+ return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true };+ } catch (error) {+ if (missing(error)) continue;+ if (error?.code === 1) return { cancelled: true }; // both tools exit 1 when the dialog is dismissed+ throw new Error('The folder chooser could not open.');+ }+ }+ return { unavailable: true, reason: 'No folder chooser is installed (install zenity or kdialog).' };+}++export const TYPE_A_PATH = 'No folder chooser is available on this system, so type the folder path instead.';++/** A typed path stands in for the dialog: it must be an absolute directory that exists. */+export async function typedFolder(value, { isAbsolute }) {+ const text = typeof value === 'string' ? value.trim() : '';+ if (!text || text.includes('\0')) return null;+ if (!isAbsolute(text)) throw new Error('Enter the full path of the folder.');+ let info;+ try { info = await stat(text); } catch { throw new Error('That folder does not exist.'); }+ if (!info.isDirectory()) throw new Error('Choose a folder, not a file.');+ return cleanChosenPath(text);+}diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex df7be28b2..09695db4e 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -3,6 +3,7 @@ import { createCloudflare } from './cloudflare.mjs';import { createConnectorInstaller } from './cloudflared-install.mjs';import { openArtifact } from './artifacts.mjs';import { saveSnapshot } from './snapshot.mjs';+import { chooseFolder, typedFolder, TYPE_A_PATH } from './folder-dialog.mjs';import { createLocalShare } from './local-share.mjs';import { createTaskService, validateTask } from './tasks.mjs';import { migrateSetup } from './setup.mjs';@@ -22,7 +23,7 @@ import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSimport { spawn } from 'node:child_process';import { execFile } from 'node:child_process';import { promisify } from 'node:util';-import { basename, extname, join, normalize, resolve } from 'node:path';+import { basename, extname, isAbsolute, join, normalize, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import * as hardware from './hardware.mjs';@@ -1240,11 +1241,12 @@ async function api(req, res, path, method, url) {looks like a skill, copy it into the workspace's skills directory. */if (path === '/api/skills/add' && method === 'POST') {try {- const { stdout } = await execFileAsync('osascript', [- '-e',- 'POSIX path of (choose folder with prompt "Choose a skill folder (it should contain SKILL.md)")',- ]);- const chosen = stdout.trim().replace(/\/$/, '');+ // The dialog is the normal path; a typed `path` in the body stands in where none exists.+ const typed = await typedFolder((await readBody(req)).path, { isAbsolute });+ const picked = typed ? { path: typed } : await chooseFolder('Choose a skill folder (it should contain SKILL.md)');+ if (picked.unavailable) return error(res, 501, `${TYPE_A_PATH} ${picked.reason}`);+ if (picked.cancelled) return json(res, 200, { cancelled: true });+ const chosen = picked.path;const base = basename(chosen);const mdPath = join(chosen, 'SKILL.md');if (!existsSync(mdPath)) {@@ -1257,22 +1259,21 @@ async function api(req, res, path, method, url) {mkdirSync(join(WORKSPACE, 'skills'), { recursive: true });cpSync(chosen, dest, { recursive: true });return json(res, 200, { added: base });- } catch {- // Dismissing the dialog is an exit code, not a failure.- return json(res, 200, { cancelled: true });+ } catch (e) {+ // Dismissing the dialog is { cancelled: true } above; anything thrown here is a real problem.+ return error(res, 400, e.message);}}if (path === '/api/workspaces/pick' && method === 'POST') {try {- const { stdout } = await execFileAsync('osascript', [- '-e',- 'POSIX path of (choose folder with prompt "Choose a folder for Strata")',- ]);- return json(res, 200, { path: stdout.trim().replace(/\/$/, '') });- } catch {- // Dismissing the dialog is an exit code, not a failure.- return json(res, 200, { cancelled: true });+ const typed = await typedFolder((await readBody(req)).path, { isAbsolute });+ const picked = typed ? { path: typed } : await chooseFolder('Choose a folder for Strata');+ if (picked.unavailable) return error(res, 501, `${TYPE_A_PATH} ${picked.reason}`);+ if (picked.cancelled) return json(res, 200, { cancelled: true });+ return json(res, 200, { path: picked.path });+ } catch (e) {+ return error(res, 400, e.message);}}diff --git a/apps/host/tests/folder-dialog.test.mjs b/apps/host/tests/folder-dialog.test.mjsnew file mode 100644index 000000000..5c41dba78--- /dev/null+++ b/apps/host/tests/folder-dialog.test.mjs@@ -0,0 +1,121 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { spawn, execFileSync } from 'node:child_process';+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, resolve, isAbsolute } from 'node:path';+import { fileURLToPath } from 'node:url';+import { chooseFolder, cleanChosenPath, typedFolder, windowsFolderScript } from '../server/folder-dialog.mjs';++const HOST_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));+const failure = (code) => Object.assign(new Error(`exit ${code}`), { code });+const recorder = () => {+ const seen = [];+ return { seen, run: (outcome) => async (command, args) => { seen.push({ command, args }); if (outcome instanceof Error) throw outcome; return { stdout: outcome }; } };+};++test('macOS keeps the osascript chooser and treats any dismissal as a cancel', async () => {+ const c = recorder();+ assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run('/Users/me/skills/\n') }), { path: '/Users/me/skills' });+ assert.equal(c.seen[0].command, 'osascript');+ assert.equal(c.seen[0].args[1], 'POSIX path of (choose folder with prompt "Pick")');+ assert.deepEqual(await chooseFolder('Pick', { platform: 'darwin', run: c.run(failure(1)) }), { cancelled: true });+});++test('Windows uses a PowerShell FolderBrowserDialog passed as an encoded command', async () => {+ const c = recorder();+ const result = await chooseFolder("Don't panic", { platform: 'win32', run: c.run('C:\\Users\\me\\Skills\r\n') });+ assert.deepEqual(result, { path: 'C:\\Users\\me\\Skills' });+ assert.match(c.seen[0].command, /powershell\.exe$/i);+ assert.ok(c.seen[0].args.includes('-STA'));+ const script = Buffer.from(c.seen[0].args.at(-1), 'base64').toString('utf16le');+ assert.equal(script, windowsFolderScript("Don't panic"));+ assert.match(script, /FolderBrowserDialog/);+ assert.match(script, /Description = 'Don''t panic'/);+ assert.deepEqual(await chooseFolder('Pick', { platform: 'win32', run: c.run('') }), { cancelled: true });+ const missing = await chooseFolder('Pick', { platform: 'win32', run: c.run(failure('ENOENT')) });+ assert.equal(missing.unavailable, true);+ await assert.rejects(chooseFolder('Pick', { platform: 'win32', run: c.run(failure(2)) }), /could not open/);+});++test('the generated PowerShell parses without errors', { skip: process.platform !== 'win32' }, () => {+ const shell = join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');+ const out = execFileSync(shell,+ ['-NoProfile', '-NonInteractive', '-Command', '$e=$null; [void][System.Management.Automation.Language.Parser]::ParseInput($env:SCRIPT,[ref]$null,[ref]$e); $e.Count'],+ { encoding: 'utf8', env: { ...process.env, SCRIPT: windowsFolderScript('Choose a folder for Strata') }, windowsHide: true }).trim();+ assert.equal(out, '0');+});++test('Linux tries zenity, falls back to kdialog, then reports that none exists', async () => {+ const order = [];+ const run = async (command) => { order.push(command); if (command === 'zenity') throw failure('ENOENT'); return { stdout: '/home/me/skills/\n' }; };+ assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run }), { path: '/home/me/skills' });+ assert.deepEqual(order, ['zenity', 'kdialog']);+ const none = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure('ENOENT'); } });+ assert.equal(none.unavailable, true);+ assert.match(none.reason, /zenity or kdialog/);+ assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure(1); } }), { cancelled: true });+ assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => ({ stdout: '' }) }), { cancelled: true });+});++test('chosen paths lose trailing separators but roots survive', () => {+ assert.equal(cleanChosenPath('/a/b/\n'), '/a/b');+ assert.equal(cleanChosenPath('/'), '/');+ assert.equal(cleanChosenPath('C:\\Users\\me\\'), 'C:\\Users\\me');+ assert.equal(cleanChosenPath('C:\\'), 'C:\\');+});++test('a typed path must be an absolute existing directory', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'strata-typed-'));+ try {+ await writeFile(join(dir, 'file.txt'), 'x');+ assert.equal(await typedFolder(dir, { isAbsolute }), dir);+ assert.equal(await typedFolder(undefined, { isAbsolute }), null);+ await assert.rejects(typedFolder('relative/dir', { isAbsolute }), /full path/);+ await assert.rejects(typedFolder(join(dir, 'missing'), { isAbsolute }), /does not exist/);+ await assert.rejects(typedFolder(join(dir, 'file.txt'), { isAbsolute }), /not a file/);+ } finally { await rm(dir, { recursive: true, force: true }); }+});++async function startHost() {+ const home = await mkdtemp(join(tmpdir(), 'strata-folder-home-'));+ const net = await import('node:net');+ const probe = net.createServer();+ await new Promise(r => probe.listen(0, '127.0.0.1', r));+ const { port } = probe.address();+ await new Promise(r => probe.close(r));+ const child = spawn(process.execPath, [join(HOST_ROOT, 'server', 'index.mjs'), '--dist', join(HOST_ROOT, 'dist')], {+ cwd: HOST_ROOT, env: { ...process.env, STRATA_HOME: home, STRATA_WORKSPACE: home, STRATA_PORT: String(port), STRATA_REAL_ENGINE: '0' }, stdio: 'ignore',+ });+ const base = `http://127.0.0.1:${port}`;+ for (let i = 0; i < 150; i++) {+ try { if ((await fetch(`${base}/api/health`)).ok) return { child, base, home }; } catch { /* not up yet */ }+ await new Promise(r => setTimeout(r, 100));+ }+ child.kill();+ throw new Error('the host did not become healthy');+}++test('the host accepts a typed folder path for the picker and for adding a skill, on every OS', { timeout: 60000 }, async () => {+ const { child, base, home } = await startHost();+ const skill = await mkdtemp(join(tmpdir(), 'strata-skill-'));+ try {+ const post = (path, body) => fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });+ let r = await post('/api/workspaces/pick', { path: skill });+ assert.deepEqual(await r.json(), { path: skill });+ r = await post('/api/workspaces/pick', { path: join(skill, 'nope') });+ assert.equal(r.status, 400);+ assert.match((await r.json()).error, /does not exist/);+ r = await post('/api/skills/add', { path: skill });+ assert.equal(r.status, 400);+ assert.match((await r.json()).error, /no SKILL\.md/);+ await writeFile(join(skill, 'SKILL.md'), '---\nname: Typed\n---\nbody\n');+ r = await post('/api/skills/add', { path: skill });+ assert.equal(r.status, 200);+ assert.ok((await r.json()).added);+ } finally {+ child.kill();+ await rm(skill, { recursive: true, force: true });+ await rm(home, { recursive: true, force: true }).catch(() => {});+ }+});