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++
cloudflared: find a system install (PATH and the usual places), check its version, say which one is used, and never start a second connector next to a running one
Niko122131f225e4fb36
diff --git a/apps/host/server/cloudflare.mjs b/apps/host/server/cloudflare.mjsindex 6a65c51aa..88b047477 100644--- a/apps/host/server/cloudflare.mjs+++ b/apps/host/server/cloudflare.mjs@@ -1,18 +1,23 @@/** A supervised Cloudflare connector with a private, inference-only origin. */import { spawn } from 'node:child_process';import { probe, which } from './util.mjs';+import { describeConnector, runningMessage } from './cloudflared-find.mjs';export function tunnelHostname(value) {const hostname = String(value ?? '').trim().toLowerCase();if (hostname.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(hostname)) throw new Error('Enter a hostname such as ai.example.com, without https:// or a path.');return hostname;}-export function createCloudflare({ origin, originUrl, hasKey, changed = () => {}, launch = spawn, locate = async () => process.platform === 'win32' ? (await probe('where.exe', ['cloudflared'])).split(/\r?\n/)[0] || null : which('cloudflared'), prepareConnector = null, timeoutMs = 45000 }) {- let binary = null, child = null, timer = null, busy = false, generation = 0;+export function createCloudflare({ origin, originUrl, hasKey, changed = () => {}, launch = spawn, locate = async () => process.platform === 'win32' ? (await probe('where.exe', ['cloudflared'])).split(/\r?\n/)[0] || null : which('cloudflared'), prepareConnector = null, connectorInfo = () => null, findRunning = async () => ({ running: false, kind: null, pids: [] }), timeoutMs = 45000 }) {+ let binary = null, other = null, child = null, timer = null, busy = false, generation = 0;let value = { status: 'idle', mode: null, url: null, error: null };- const state = () => ({ ...value, installed: !!binary, originUrl });+ const state = () => {+ const info = binary ? connectorInfo() : null;+ return { ...value, installed: !!binary, originUrl, connector: info ? { path: info.path, version: info.version, source: info.source, label: info.label, summary: describeConnector(info) } : null, external: other?.running ? { kind: other.kind, message: runningMessage(other) } : null };+ };const update = patch => { value = { ...value, ...patch }; changed(state()); };- async function inspect() { binary = await locate(); changed(state()); return state(); }+ async function lookForOther() { try { other = await findRunning({ exclude: [child?.pid] }); } catch { other = null; } return other; }+ async function inspect() { binary = await locate(); await lookForOther(); changed(state()); return state(); }async function prepare() {if (busy) throw new Error('Connector setup is already in progress.');busy = true;@@ -54,6 +59,8 @@ export function createCloudflare({ origin, originUrl, hasKey, changed = () => {}binary = await locate();if (!binary && prepareConnector) binary = await prepareConnector();if (!binary) throw new Error('The connector could not be prepared automatically. Retry connector setup.');+ // A cloudflared that is already running here (a system service, or one the person started) is never doubled up.+ if ((await lookForOther())?.running) throw new Error(runningMessage(other));await origin.start();// Tokens never appear in command arguments, logs, saved settings, or API responses.const env = { ...process.env };diff --git a/apps/host/server/cloudflared-find.mjs b/apps/host/server/cloudflared-find.mjsnew file mode 100644index 000000000..ef639624e--- /dev/null+++ b/apps/host/server/cloudflared-find.mjs@@ -0,0 +1,167 @@+/**+ * Finding the Cloudflare connector (cloudflared) that is already on this computer.+ *+ * Strata used to look only in its own folders, so a cloudflared installed by the system (apt, brew, winget, a .deb) was+ * reported as "not installed" (Linux tester, cloudflared 2026.5.0 in /usr/bin). Now the places are, in this order:+ * 1. Strata's own connector folder+ * 2. the optional connector component folder+ * 3. every folder on PATH+ * 4. the usual install places (/usr/bin, /usr/local/bin, ~/.local/bin, Homebrew, Program Files, winget/choco/scoop)+ * The first one that runs `cloudflared --version` and is new enough is used; the answer says which one and from where.+ * Nothing here downloads or installs anything.+ */+import { execFile } from 'node:child_process';+import { access, stat } from 'node:fs/promises';+import { constants } from 'node:fs';+import { homedir } from 'node:os';+import { win32, posix } from 'node:path';++/** The quick tunnel flags Strata passes (tunnel --url, --no-autoupdate, --grace-period) and the "Registered tunnel connection" log line it waits for exist from 2022.1.0. */+export const MIN_VERSION = '2022.1.0';++export function parseVersion(text) {+ const m = /(\d{4})\.(\d{1,2})\.(\d{1,3})/.exec(String(text ?? ''));+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;+}+export function versionAtLeast(found, minimum = MIN_VERSION) {+ const a = Array.isArray(found) ? found : parseVersion(found), b = Array.isArray(minimum) ? minimum : parseVersion(minimum);+ if (!a || !b) return true; // an unreadable version (a custom build) is not a reason to refuse it+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];+ return true;+}++const SOURCE_LABEL = {+ strata: 'Strata’s own connector folder',+ component: 'the optional connector component',+ path: 'found on your PATH',+ system: 'a usual install location',+ setting: 'chosen with the STRATA_CLOUDFLARED setting',+};++/** Candidate paths in search order, each as { path, source }. Pure: no disk access. */+export function connectorCandidates({ directory, componentDirectory = null, platform = process.platform, env = process.env, home = homedir(), search = true } = {}) {+ // STRATA_CLOUDFLARED=<file> uses exactly that connector; STRATA_CLOUDFLARED_SEARCH=own keeps the search to Strata's own folders.+ const windows = platform === 'win32', p = windows ? win32 : posix;+ const name = windows ? 'cloudflared.exe' : 'cloudflared';+ if (env.STRATA_CLOUDFLARED) return [{ path: env.STRATA_CLOUDFLARED, source: 'setting' }];+ if (env.STRATA_CLOUDFLARED_SEARCH === 'own') search = false;+ const out = [], seen = new Set();+ const add = (dir, source) => {+ if (!dir) return;+ const path = p.join(dir, name), key = windows ? path.toLowerCase() : path;+ if (!seen.has(key)) { seen.add(key); out.push({ path, source }); }+ };+ add(directory, 'strata');+ add(componentDirectory, 'component');+ if (!search) return out;+ const pathVariable = windows ? (env.Path ?? env.PATH ?? '') : (env.PATH ?? '');+ for (const dir of pathVariable.split(windows ? ';' : ':')) add(dir.replace(/^"|"$/g, '').trim(), 'path');+ if (windows) {+ const roots = [env.ProgramFiles ?? 'C:\\Program Files', env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)'];+ for (const root of roots) add(win32.join(root, 'cloudflared'), 'system');+ if (env.LOCALAPPDATA) add(win32.join(env.LOCALAPPDATA, 'Microsoft', 'WinGet', 'Links'), 'system');+ add(win32.join(env.ProgramData ?? 'C:\\ProgramData', 'chocolatey', 'bin'), 'system');+ if (home) add(win32.join(home, 'scoop', 'shims'), 'system');+ } else {+ for (const dir of ['/usr/bin', '/usr/local/bin', '/opt/homebrew/bin', '/home/linuxbrew/.linuxbrew/bin', '/snap/bin', '/opt/cloudflared']) add(dir, 'system');+ if (home) { add(posix.join(home, '.local', 'bin'), 'system'); add(posix.join(home, 'bin'), 'system'); add(posix.join(home, '.cloudflared'), 'system'); }+ }+ return out;+}++/** Runs `<path> --version`; resolves to the combined output, rejects when it does not run. */+export function runVersion(path) {+ return new Promise((resolve, reject) => {+ execFile(path, ['--version'], { timeout: 10000, windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {+ if (error) reject(error); else resolve(`${stdout}\n${stderr}`.trim());+ });+ });+}++async function isRunnableFile(path, platform) {+ try {+ if (!(await stat(path)).isFile()) return false;+ await access(path, platform === 'win32' ? constants.F_OK : constants.X_OK);+ return true;+ } catch { return false; }+}++/**+ * The connector to use, and what was seen on the way.+ * Resolves to { found: { path, version, source, label } | null, skipped: [{ path, source, reason, version? }] }.+ * `tooOld` is set when something was found but every copy is older than the minimum version.+ */+export async function findConnector(options = {}) {+ const platform = options.platform ?? process.platform;+ const run = options.run ?? runVersion;+ const usable = options.usable ?? (path => isRunnableFile(path, platform));+ const skipped = [];+ for (const candidate of connectorCandidates(options)) {+ if (!(await usable(candidate.path))) continue;+ let output;+ try { output = await run(candidate.path); }+ catch { skipped.push({ ...candidate, reason: 'does-not-run' }); continue; }+ if (!/cloudflared/i.test(output) && !parseVersion(output)) { skipped.push({ ...candidate, reason: 'not-cloudflared' }); continue; }+ const parsed = parseVersion(output), version = parsed ? parsed.join('.') : null;+ if (!versionAtLeast(parsed)) { skipped.push({ ...candidate, reason: 'too-old', version }); continue; }+ return { found: { path: candidate.path, version, source: candidate.source, label: SOURCE_LABEL[candidate.source] }, skipped };+ }+ return { found: null, skipped };+}++/** A person-readable sentence about what was found (shown in the Connector step and the review). */+export function describeConnector(found) {+ if (!found) return null;+ return `${found.version ? `cloudflared ${found.version}` : 'cloudflared'} · ${found.path} (${found.label})`;+}++/** A person-readable reason when nothing usable was found but something unusable was. Null when nothing was seen. */+export function skippedMessage(skipped) {+ const old = skipped.find(s => s.reason === 'too-old');+ if (old) return `The cloudflared at ${old.path} is version ${old.version}, which is too old. Strata needs ${MIN_VERSION} or newer. Update cloudflared, then retry.`;+ const broken = skipped.find(s => s.reason === 'does-not-run' || s.reason === 'not-cloudflared');+ if (broken) return `The file at ${broken.path} did not run as cloudflared. Reinstall cloudflared, then retry.`;+ return null;+}++/**+ * Is another cloudflared already running on this computer (a system service, or one the person started)?+ * `exclude` is the list of pids that belong to Strata itself. Resolves to { running, kind: 'service' | 'process' | null, pids }.+ * Failing to look is "not running": a missing pgrep must never block the tunnel.+ */+export async function findRunningConnector({ platform = process.platform, exclude = [], run = defaultProbe } = {}) {+ const skip = new Set(exclude.filter(Number.isInteger));+ let pids = [];+ if (platform === 'win32') {+ const out = await run('tasklist', ['/FI', 'IMAGENAME eq cloudflared.exe', '/NH', '/FO', 'CSV']);+ pids = [...out.matchAll(/"cloudflared\.exe","(\d+)"/gi)].map(m => Number(m[1]));+ } else {+ const out = await run('pgrep', ['-x', 'cloudflared']);+ pids = out.split(/\s+/).filter(Boolean).map(Number).filter(Number.isInteger);+ }+ pids = pids.filter(pid => !skip.has(pid));+ if (!pids.length) return { running: false, kind: null, pids: [] };+ let kind = 'process';+ if (platform === 'linux') {+ const active = (await run('systemctl', ['is-active', 'cloudflared'])).trim();+ if (active === 'active') kind = 'service';+ } else if (platform === 'win32') {+ const service = await run('sc.exe', ['query', 'Cloudflared']);+ if (/RUNNING/.test(service)) kind = 'service';+ }+ return { running: true, kind, pids };+}++function defaultProbe(cmd, args) {+ return new Promise(resolve => {+ execFile(cmd, args, { timeout: 4000, windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout) => resolve(error ? '' : String(stdout)));+ });+}++/** The plain sentence for a connector that is already running, with the one next step. */+export function runningMessage(running) {+ if (!running?.running) return null;+ return running.kind === 'service'+ ? 'Cloudflare’s connector is already running on this computer as a system service, so Strata did not start a second one. Stop that service first (or use its tunnel as it is), then connect again here.'+ : 'Cloudflare’s connector (cloudflared) is already running on this computer, so Strata did not start a second one. Close it first (or use its tunnel as it is), then connect again here.';+}diff --git a/apps/host/server/cloudflared-install.mjs b/apps/host/server/cloudflared-install.mjsindex fe45df562..3716ba7cf 100644--- a/apps/host/server/cloudflared-install.mjs+++ b/apps/host/server/cloudflared-install.mjs@@ -6,6 +6,7 @@ import { constants } from 'node:fs';import { join } from 'node:path';import { promisify } from 'node:util';import { require as requireAcquisition } from './acquisition.mjs';+import { findConnector, skippedMessage } from './cloudflared-find.mjs';const run = promisify(execFile);const RELEASES = 'https://api.github.com/repos/cloudflare/cloudflared/releases/latest';@@ -30,20 +31,23 @@ export function verifyConnector(bytes, digest) {* component folder). A connector found there is used as it is; one that is not there is never fetched while the app* runs (acquisition.mjs), it is a notice.*/-export function createConnectorInstaller({ directory, componentDirectory = null, platform = process.platform, arch = process.arch, fetchImpl = fetch }) {+export function createConnectorInstaller({ directory, componentDirectory = null, platform = process.platform, arch = process.arch, fetchImpl = fetch, env = process.env, home, run: runVersion, usable, search }) {const name = platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';const binary = join(directory, name);- let installing = null;- async function locate() {- for (const candidate of [binary, componentDirectory && join(componentDirectory, name)].filter(Boolean)) {- try { await access(candidate, platform === 'win32' ? constants.F_OK : constants.X_OK); return candidate; }- catch { /* try the next place */ }- }- return null;+ let installing = null, last = { found: null, skipped: [] };+ /** Strata's own folder first, then the component folder, PATH and the usual install places (cloudflared-find.mjs). */+ async function look() {+ last = await findConnector({ directory, componentDirectory, platform, env, home, run: runVersion, usable, search });+ return last;}+ async function locate() { return (await look()).found?.path ?? null; }+ /** What is in use ({ path, version, source, label }), or null; set by the last look. */+ const connector = () => last.found;async function install() {const existing = await locate();if (existing) return existing;+ const unusable = skippedMessage(last.skipped);+ if (unusable) throw new Error(unusable);requireAcquisition('The Cloudflare connector (cloudflared)', 'the optional connector component');const name = connectorAsset(platform, arch);await mkdir(directory, { recursive: true });@@ -83,7 +87,7 @@ export function createConnectorInstaller({ directory, componentDirectory = null,return binary;} finally { await rm(stage, { recursive: true, force: true }); }}- return { locate, ensure() {+ return { locate, connector, async inspect() { await look(); return last; }, ensure() {if (!installing) installing = install().finally(() => { installing = null; });return installing;} };diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjsindex cf3c83367..9d50f448e 100644--- a/apps/host/server/index.mjs+++ b/apps/host/server/index.mjs@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { createCloudflare } from './cloudflare.mjs';import { createConnectorInstaller } from './cloudflared-install.mjs';+import { findRunningConnector } from './cloudflared-find.mjs';import { openArtifact } from './artifacts.mjs';import { saveSnapshot } from './snapshot.mjs';import { resolvePython, shellPrefix } from './python-resolver.mjs';@@ -893,7 +894,7 @@ const localShare = createLocalShare({ handle: openai, hasKey: () => !!store.get(const tunnelPort = Number(process.env.STRATA_TUNNEL_PORT ?? PORT + 2);const tunnelOrigin = createLocalShare({ handle: openai, hasKey: () => !!store.get().serving?.apiKey, host: '127.0.0.1', port: tunnelPort });const connector = createConnectorInstaller({ directory: join(store.HOME, 'engine', 'cloudflare'), componentDirectory: join(componentsDirectory(), 'cloudflared') });-const cloudflare = createCloudflare({ origin: tunnelOrigin, originUrl: `http://127.0.0.1:${tunnelPort}`, hasKey: () => !!store.get().serving?.apiKey, changed: serving.setTunnel, locate: connector.locate, prepareConnector: connector.ensure });+const cloudflare = createCloudflare({ origin: tunnelOrigin, originUrl: `http://127.0.0.1:${tunnelPort}`, hasKey: () => !!store.get().serving?.apiKey, changed: serving.setTunnel, locate: connector.locate, prepareConnector: connector.ensure, connectorInfo: connector.connector, findRunning: findRunningConnector });await cloudflare.inspect();/* --------------------------------------------------------------- routing --- */diff --git a/apps/host/src/components/CloudflareDialog.tsx b/apps/host/src/components/CloudflareDialog.tsxindex 18caf25bf..90d96d8eb 100644--- a/apps/host/src/components/CloudflareDialog.tsx+++ b/apps/host/src/components/CloudflareDialog.tsx@@ -18,8 +18,8 @@ export function CloudflareDialog({ open, onClose, onCreateKey }: {const active = !!tunnel && ['starting', 'connected', 'stopping'].includes(tunnel.status);const steps = mode === 'quick' ? ['Address', 'Connector', 'API key', 'Connect'] : ['Address', 'Connector', 'API key', 'Domain', 'Connect'];const last = steps.length - 1;- const installed = !!tunnel?.installed, keyReady = !!serving?.access.apiKeySet;- const canContinue = step === 1 ? installed : step === 2 ? keyReady : step === 3 && mode === 'domain' ? !!hostname.trim() && !!token.trim() : true;+ const installed = !!tunnel?.installed, keyReady = !!serving?.access.apiKeySet, other = tunnel?.external ?? null;+ const canContinue = step === 1 ? installed && !other : step === 2 ? keyReady : step === 3 && mode === 'domain' ? !!hostname.trim() && !!token.trim() : true;async function inspect() { setPending(true); setError(''); try {setDetected(await api.get<TunnelState>('/api/serving/tunnel'));}@@ -91,10 +91,10 @@ export function CloudflareDialog({ open, onClose, onCreateKey }: {setMode(mode === 'quick' ? 'domain' : 'quick');(e.currentTarget.parentElement?.children[mode === 'quick' ? 1 : 0] as HTMLElement)?.focus();} }} onClick={() => setMode(choice.value)}><Icon name={choice.icon} size={20}/><span><strong>{tr(choice.title)}</strong><small>{tr(choice.detail)}</small></span><span className="tunnel-choice-dot">{tr(mode === choice.value ? <Icon name="check" size={13}/> : null)}</span></button>))}</div></> : null)}- {tr(step === 1 ? <div className="tunnel-automatic" data-ready={installed || undefined} aria-live="polite" aria-busy={pending}><span className="tunnel-stage__symbol"><Icon name={installed ? 'check' : error ? 'warning' : 'refresh'} size={28}/></span><p className="small muted">{tr(installed ? 'Your Cloudflare connector is installed and ready.' : error ? 'Automatic setup needs another try.' : 'Strata downloads and sets up the Cloudflare connector for you.')}</p>{tr(installed ? null : error ? <Btn onClick={() => setRetry(v => v + 1)}>{tr("Retry setup")}</Btn> : <span className="small muted" role="status">{tr("Setting up\u2026")}</span>)}</div> : null)}+ {tr(step === 1 ? <div className="tunnel-automatic" data-ready={installed || undefined} aria-live="polite" aria-busy={pending}><span className="tunnel-stage__symbol"><Icon name={installed ? 'check' : error ? 'warning' : 'refresh'} size={28}/></span><p className="small muted">{tr(installed ? 'Your Cloudflare connector is installed and ready.' : error ? 'Automatic setup needs another try.' : 'Strata downloads and sets up the Cloudflare connector for you.')}</p>{tr(installed ? <>{tr(tunnel?.connector ? <p className="xs muted">{tr("Using {0}", [tunnel.connector.summary])}</p> : null)}{tr(other ? <><p className="small" role="status">{tr(other.message)}</p><Btn disabled={pending} onClick={() => void inspect()}>{tr("Check again")}</Btn></> : null)}</> : error ? <Btn onClick={() => setRetry(v => v + 1)}>{tr("Retry setup")}</Btn> : <span className="small muted" role="status">{tr("Setting up\u2026")}</span>)}</div> : null)}{tr(step === 2 ? <><p className="small muted">{tr("Only apps with your Strata API key can use this connection.")}</p>{tr(keyReady ? <div className="tunnel-check"><Icon name="shield"/><div><strong>{tr("API key ready")}</strong><span>{tr("Use your existing key in the app you connect.")}</span></div></div> : <div className="tunnel-key-step"><Icon name="shield" size={30}/><p className="small">{tr("Create a key to protect your API. You\u2019ll return here when it\u2019s ready.")}</p><Btn onClick={onCreateKey}>{tr("Create an API key")}</Btn></div>)}</> : null)}{tr(mode === 'domain' && step === 3 ? <><p className="small muted">{tr("Create a tunnel in your ")}<a href="https://dash.cloudflare.com/" target="_blank" rel="noreferrer">{tr("Cloudflare dashboard \u2197")}</a>{tr(". Copy the token from its connector setup.")}</p><label className="input-field"><span>{tr("Tunnel token")}</span><input type="password" className="st-input" autoComplete="off" spellCheck={false} value={token} onChange={e => setToken(e.target.value)} placeholder={tr("Paste only the token after --token")}/></label><label className="input-field"><span>{tr("Your hostname")}</span><input className="st-input" autoComplete="off" spellCheck={false} value={hostname} onChange={e => setHostname(e.target.value)} placeholder={tr("ai.example.com")}/></label><div><p className="small muted">{tr("Add a published application route for this hostname with this service URL:")}</p><div className="install-command"><code>{tunnel?.originUrl ?? 'Loading…'}</code><IconBtn name="copy" title={tr("Copy tunnel service URL")} disabled={!tunnel?.originUrl} onClick={() => void navigator.clipboard.writeText(tunnel!.originUrl)}/></div></div><p className="xs muted">{tr("The token is used for this connection only and is not saved.")}</p></> : null)}- {tr(step === last ? <><p className="small muted">{tr(mode === 'quick' ? 'Cloudflare will create your address when you connect.' : 'Start the connector for the domain you configured.')}</p><dl className="tunnel-review"><div><dt>{tr("Address")}</dt><dd>{tr(mode === 'quick' ? 'Free temporary URL' : hostname)}</dd></div><div><dt>{tr("Connector")}</dt><dd><Icon name="check" size={14}/>{tr("Installed")}</dd></div><div><dt>{tr("Access")}</dt><dd><Icon name="shield" size={14}/>{tr("API key required")}</dd></div></dl><p className="small muted">{tr(mode === 'quick' ? 'The address changes each time. Turn off streaming in your client; replies arrive all at once.' : 'Use this hostname and your Strata API key in your client. Streaming is supported.')}</p><p className="xs muted">{tr("Only the inference API is shared. Your computer and Strata must stay on.")}</p></> : null)}+ {tr(step === last ? <><p className="small muted">{tr(mode === 'quick' ? 'Cloudflare will create your address when you connect.' : 'Start the connector for the domain you configured.')}</p><dl className="tunnel-review"><div><dt>{tr("Address")}</dt><dd>{tr(mode === 'quick' ? 'Free temporary URL' : hostname)}</dd></div><div><dt>{tr("Connector")}</dt><dd><Icon name="check" size={14}/>{tr(tunnel?.connector?.version ? "Installed · cloudflared {0}" : "Installed", tunnel?.connector?.version ? [tunnel.connector.version] : undefined)}</dd></div><div><dt>{tr("Access")}</dt><dd><Icon name="shield" size={14}/>{tr("API key required")}</dd></div></dl><p className="small muted">{tr(mode === 'quick' ? 'The address changes each time. Turn off streaming in your client; replies arrive all at once.' : 'Use this hostname and your Strata API key in your client. Streaming is supported.')}</p><p className="xs muted">{tr("Only the inference API is shared. Your computer and Strata must stay on.")}</p></> : null)}</section>)}{tr(error || tunnel?.error ? <ErrorNotice message={error || tunnel?.error || 'Connection failed'} next={tr("Check your internet connection, then retry.")}/> : null)}</div>diff --git a/apps/host/src/lib/plain-errors.ts b/apps/host/src/lib/plain-errors.tsindex a08f28a3b..0c191037a 100644--- a/apps/host/src/lib/plain-errors.ts+++ b/apps/host/src/lib/plain-errors.ts@@ -15,6 +15,9 @@ const MEMORY_NEXT = 'Close other programs and try again, or choose “Leave 20%/** Order matters: the first rule that matches wins. */const RULES: Rule[] = [+ { kind: 'connector-missing', match: /connector \(cloudflared\) is not installed/i, message: 'Strata could not find Cloudflare’s connector (cloudflared) on this computer.', next: 'Install cloudflared (with your package manager, or from Cloudflare’s website), then press Retry setup. Strata finds it on your PATH and in the usual places.' },+ { kind: 'connector-old', match: /cloudflared at .* is version .* too old/i, message: 'The Cloudflare connector on this computer is too old.', next: 'Update cloudflared to a newer version, then press Retry setup.' },+ { kind: 'connector-broken', match: /did not run as cloudflared/i, message: 'The file found as cloudflared did not run.', next: 'Reinstall cloudflared, then press Retry setup.' },{ kind: 'picture-reading', match: /vision files|picture reading/i, message: 'Picture reading isn’t available for this model.', next: 'Turn off picture reading and try again.' },{ kind: 'access', match: /PermissionError|access is denied|can.t open its settings file/i, message: 'Strata can’t open its settings file.', next: 'Run Strata once as yourself (not as administrator) or press Repair.' },// A start that died: the exit code or the engine's own last line says why. Say "low on memory" only when that evidence is therediff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.tsindex 3fd645047..0297135fd 100644--- a/apps/host/src/lib/types.ts+++ b/apps/host/src/lib/types.ts@@ -223,7 +223,7 @@ export interface ServeRequest {finishReason?: string | null;}-export interface TunnelState { status: 'idle' | 'starting' | 'connected' | 'stopping' | 'error'; mode: 'quick' | 'domain' | null; url: string | null; error: string | null; installed: boolean; originUrl: string; }+export interface TunnelState { status: 'idle' | 'starting' | 'connected' | 'stopping' | 'error'; mode: 'quick' | 'domain' | null; url: string | null; error: string | null; installed: boolean; originUrl: string; connector?: { path: string; version: string | null; source: string; label: string; summary: string } | null; external?: { kind: 'service' | 'process'; message: string } | null; }export interface ServingState {tunnel?: TunnelState;diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.jsonindex 10640289d..81f48bb29 100644--- a/apps/host/src/locales/de.json+++ b/apps/host/src/locales/de.json@@ -3151,5 +3151,15 @@"s3155": "Strata wurde beendet. Du kannst diesen Tab schließen. Um es wieder zu nutzen, starte Strata über sein Symbol.","s3156": "Strata konnte von hier aus nicht beendet werden. Starte die App im Terminal mit --quit oder versuche es erneut.","s3157": "Wird beendet …",- "s3158": "Die mit der App gelieferte Engine wird entpackt. Beim ersten Start dauert das etwa eine Minute."+ "s3158": "Die mit der App gelieferte Engine wird entpackt. Beim ersten Start dauert das etwa eine Minute.",+ "s3159": "Verwendet wird: {0}",+ "s3160": "Installiert · cloudflared {0}",+ "s3161": "Der Cloudflare-Connector läuft auf diesem Computer bereits als Systemdienst, deshalb hat Strata keinen zweiten gestartet. Beende zuerst diesen Dienst (oder nutze seinen Tunnel, wie er ist) und verbinde dich dann hier erneut.",+ "s3162": "Der Cloudflare-Connector (cloudflared) läuft auf diesem Computer bereits, deshalb hat Strata keinen zweiten gestartet. Beende ihn zuerst (oder nutze seinen Tunnel, wie er ist) und verbinde dich dann hier erneut.",+ "s3163": "Strata hat den Cloudflare-Connector (cloudflared) auf diesem Computer nicht gefunden.",+ "s3164": "Installiere cloudflared (mit deiner Paketverwaltung oder von der Cloudflare-Website) und drücke dann „Einrichtung erneut versuchen“. Strata findet es im PATH und an den üblichen Orten.",+ "s3165": "Der Cloudflare-Connector auf diesem Computer ist zu alt.",+ "s3166": "Aktualisiere cloudflared auf eine neuere Version und drücke dann „Einrichtung erneut versuchen“.",+ "s3167": "Die als cloudflared gefundene Datei ließ sich nicht ausführen.",+ "s3168": "Installiere cloudflared neu und drücke dann „Einrichtung erneut versuchen“."}diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.jsonindex e5643af80..88bbab521 100644--- a/apps/host/src/locales/en.json+++ b/apps/host/src/locales/en.json@@ -3151,5 +3151,15 @@"s3155": "Strata has stopped. You can close this tab. To use it again, start Strata from its icon.","s3156": "Strata could not be stopped from here. Run the app with --quit in a terminal, or try again.","s3157": "Quitting…",- "s3158": "Unpacking the engine that came with the app. This takes about a minute the first time."+ "s3158": "Unpacking the engine that came with the app. This takes about a minute the first time.",+ "s3159": "Using {0}",+ "s3160": "Installed · cloudflared {0}",+ "s3161": "Cloudflare’s connector is already running on this computer as a system service, so Strata did not start a second one. Stop that service first (or use its tunnel as it is), then connect again here.",+ "s3162": "Cloudflare’s connector (cloudflared) is already running on this computer, so Strata did not start a second one. Close it first (or use its tunnel as it is), then connect again here.",+ "s3163": "Strata could not find Cloudflare’s connector (cloudflared) on this computer.",+ "s3164": "Install cloudflared (with your package manager, or from Cloudflare’s website), then press Retry setup. Strata finds it on your PATH and in the usual places.",+ "s3165": "The Cloudflare connector on this computer is too old.",+ "s3166": "Update cloudflared to a newer version, then press Retry setup.",+ "s3167": "The file found as cloudflared did not run.",+ "s3168": "Reinstall cloudflared, then press Retry setup."}diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.jsonindex a9559c76b..c92e13889 100644--- a/apps/host/src/locales/es.json+++ b/apps/host/src/locales/es.json@@ -3151,5 +3151,15 @@"s3155": "Strata se ha detenido. Puedes cerrar esta pestaña. Para volver a usarlo, inicia Strata desde su icono.","s3156": "No se pudo detener Strata desde aquí. Ejecuta la app con --quit en una terminal o inténtalo de nuevo.","s3157": "Saliendo…",- "s3158": "Se está descomprimiendo el motor incluido con la app. La primera vez tarda aproximadamente un minuto."+ "s3158": "Se está descomprimiendo el motor incluido con la app. La primera vez tarda aproximadamente un minuto.",+ "s3159": "En uso: {0}",+ "s3160": "Instalado · cloudflared {0}",+ "s3161": "El conector de Cloudflare ya se está ejecutando en este equipo como servicio del sistema, así que Strata no ha iniciado un segundo. Detén primero ese servicio (o usa su túnel tal como está) y vuelve a conectar aquí.",+ "s3162": "El conector de Cloudflare (cloudflared) ya se está ejecutando en este equipo, así que Strata no ha iniciado un segundo. Ciérralo primero (o usa su túnel tal como está) y vuelve a conectar aquí.",+ "s3163": "Strata no encontró el conector de Cloudflare (cloudflared) en este equipo.",+ "s3164": "Instala cloudflared (con tu gestor de paquetes o desde el sitio web de Cloudflare) y pulsa «Reintentar configuración». Strata lo encuentra en el PATH y en los lugares habituales.",+ "s3165": "El conector de Cloudflare de este equipo es demasiado antiguo.",+ "s3166": "Actualiza cloudflared a una versión más reciente y pulsa «Reintentar configuración».",+ "s3167": "El archivo encontrado como cloudflared no se pudo ejecutar.",+ "s3168": "Reinstala cloudflared y pulsa «Reintentar configuración»."}diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.jsonindex 235e60f84..dd644d271 100644--- a/apps/host/src/locales/ja.json+++ b/apps/host/src/locales/ja.json@@ -3151,5 +3151,15 @@"s3155": "Strata を停止しました。このタブを閉じて構いません。もう一度使うには、アイコンから Strata を起動してください。","s3156": "ここから Strata を停止できませんでした。ターミナルで --quit を付けてアプリを実行するか、もう一度お試しください。","s3157": "終了しています…",- "s3158": "アプリに付属のエンジンを展開しています。初回は1分ほどかかります。"+ "s3158": "アプリに付属のエンジンを展開しています。初回は1分ほどかかります。",+ "s3159": "使用中: {0}",+ "s3160": "インストール済み · cloudflared {0}",+ "s3161": "Cloudflareのコネクターはこのコンピューターですでにシステムサービスとして動作しているため、Strataは2つ目を起動しませんでした。先にそのサービスを停止する(またはそのトンネルをそのまま使う)か、その後でここから再度接続してください。",+ "s3162": "Cloudflareのコネクター(cloudflared)はこのコンピューターですでに動作しているため、Strataは2つ目を起動しませんでした。先にそれを終了する(またはそのトンネルをそのまま使う)か、その後でここから再度接続してください。",+ "s3163": "StrataはこのコンピューターでCloudflareのコネクター(cloudflared)を見つけられませんでした。",+ "s3164": "cloudflaredをインストールしてください(パッケージマネージャーまたはCloudflareのサイトから)。その後「セットアップを再試行」を押してください。StrataはPATHと一般的な場所から自動で見つけます。",+ "s3165": "このコンピューターのCloudflareコネクターは古すぎます。",+ "s3166": "cloudflaredを新しいバージョンに更新してから、「セットアップを再試行」を押してください。",+ "s3167": "cloudflaredとして見つかったファイルは実行できませんでした。",+ "s3168": "cloudflaredを再インストールしてから、「セットアップを再試行」を押してください。"}diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.jsonindex 663d9a60a..5f3d74cb3 100644--- a/apps/host/src/locales/ko.json+++ b/apps/host/src/locales/ko.json@@ -3151,5 +3151,15 @@"s3155": "Strata가 종료되었습니다. 이 탭을 닫아도 됩니다. 다시 사용하려면 아이콘에서 Strata를 실행하세요.","s3156": "여기서는 Strata를 종료하지 못했습니다. 터미널에서 --quit 옵션으로 앱을 실행하거나 다시 시도하세요.","s3157": "종료하는 중…",- "s3158": "앱에 포함된 엔진의 압축을 푸는 중입니다. 처음에는 약 1분이 걸립니다."+ "s3158": "앱에 포함된 엔진의 압축을 푸는 중입니다. 처음에는 약 1분이 걸립니다.",+ "s3159": "사용 중: {0}",+ "s3160": "설치됨 · cloudflared {0}",+ "s3161": "Cloudflare 커넥터가 이 컴퓨터에서 이미 시스템 서비스로 실행 중이라 Strata는 두 번째 커넥터를 시작하지 않았습니다. 먼저 해당 서비스를 중지하거나 그 터널을 그대로 사용한 뒤, 여기서 다시 연결하세요.",+ "s3162": "Cloudflare 커넥터(cloudflared)가 이 컴퓨터에서 이미 실행 중이라 Strata는 두 번째 커넥터를 시작하지 않았습니다. 먼저 그것을 종료하거나 그 터널을 그대로 사용한 뒤, 여기서 다시 연결하세요.",+ "s3163": "Strata가 이 컴퓨터에서 Cloudflare 커넥터(cloudflared)를 찾지 못했습니다.",+ "s3164": "cloudflared를 설치한 뒤(패키지 관리자 또는 Cloudflare 웹사이트) '설정 다시 시도'를 누르세요. Strata는 PATH와 일반적인 위치에서 자동으로 찾습니다.",+ "s3165": "이 컴퓨터의 Cloudflare 커넥터가 너무 오래되었습니다.",+ "s3166": "cloudflared를 최신 버전으로 업데이트한 뒤 '설정 다시 시도'를 누르세요.",+ "s3167": "cloudflared로 찾은 파일이 실행되지 않았습니다.",+ "s3168": "cloudflared를 다시 설치한 뒤 '설정 다시 시도'를 누르세요."}diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.jsonindex e60522102..29408073d 100644--- a/apps/host/src/locales/pt.json+++ b/apps/host/src/locales/pt.json@@ -3151,5 +3151,15 @@"s3155": "O Strata parou. Pode fechar este separador. Para o usar de novo, inicie o Strata a partir do seu ícone.","s3156": "Não foi possível parar o Strata a partir daqui. Execute a app com --quit num terminal ou tente novamente.","s3157": "A sair…",- "s3158": "A descompactar o motor que veio com a app. Na primeira vez leva cerca de um minuto."+ "s3158": "A descompactar o motor que veio com a app. Na primeira vez leva cerca de um minuto.",+ "s3159": "Em uso: {0}",+ "s3160": "Instalado · cloudflared {0}",+ "s3161": "O conector da Cloudflare já está em execução neste computador como serviço do sistema, por isso o Strata não iniciou um segundo. Pare esse serviço primeiro (ou use o túnel dele como está) e conecte novamente aqui.",+ "s3162": "O conector da Cloudflare (cloudflared) já está em execução neste computador, por isso o Strata não iniciou um segundo. Feche-o primeiro (ou use o túnel dele como está) e conecte novamente aqui.",+ "s3163": "O Strata não encontrou o conector da Cloudflare (cloudflared) neste computador.",+ "s3164": "Instale o cloudflared (com o gerenciador de pacotes ou pelo site da Cloudflare) e depois toque em «Tentar configurar novamente». O Strata o encontra no PATH e nos locais habituais.",+ "s3165": "O conector da Cloudflare deste computador é muito antigo.",+ "s3166": "Atualize o cloudflared para uma versão mais nova e depois toque em «Tentar configurar novamente».",+ "s3167": "O arquivo encontrado como cloudflared não foi executado.",+ "s3168": "Reinstale o cloudflared e depois toque em «Tentar configurar novamente»."}diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.jsonindex 69f37eff2..6748a9ac6 100644--- a/apps/host/src/locales/ru.json+++ b/apps/host/src/locales/ru.json@@ -3151,5 +3151,15 @@"s3155": "Strata остановлена. Эту вкладку можно закрыть. Чтобы снова пользоваться, запустите Strata по её значку.","s3156": "Не удалось остановить Strata отсюда. Запустите приложение с --quit в терминале или повторите попытку.","s3157": "Выход…",- "s3158": "Распаковывается движок, поставляемый с приложением. При первом запуске это занимает около минуты."+ "s3158": "Распаковывается движок, поставляемый с приложением. При первом запуске это занимает около минуты.",+ "s3159": "Используется: {0}",+ "s3160": "Установлено · cloudflared {0}",+ "s3161": "Коннектор Cloudflare уже работает на этом компьютере как системная служба, поэтому Strata не стала запускать второй. Сначала остановите эту службу (или используйте её туннель как есть), затем подключитесь здесь снова.",+ "s3162": "Коннектор Cloudflare (cloudflared) уже работает на этом компьютере, поэтому Strata не стала запускать второй. Сначала закройте его (или используйте его туннель как есть), затем подключитесь здесь снова.",+ "s3163": "Strata не нашла коннектор Cloudflare (cloudflared) на этом компьютере.",+ "s3164": "Установите cloudflared (через менеджер пакетов или с сайта Cloudflare), затем нажмите «Повторить настройку». Strata находит его в PATH и в обычных местах.",+ "s3165": "Коннектор Cloudflare на этом компьютере слишком старый.",+ "s3166": "Обновите cloudflared до более новой версии, затем нажмите «Повторить настройку».",+ "s3167": "Файл, найденный как cloudflared, не запустился.",+ "s3168": "Переустановите cloudflared, затем нажмите «Повторить настройку»."}diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.jsonindex 877612abc..84f971ac9 100644--- a/apps/host/src/locales/zh.json+++ b/apps/host/src/locales/zh.json@@ -3151,5 +3151,15 @@"s3155": "Strata 已停止。你可以关闭此标签页。要再次使用,请从图标启动 Strata。","s3156": "无法在这里停止 Strata。请在终端中用 --quit 运行应用,或再试一次。","s3157": "正在退出…",- "s3158": "正在解压随应用附带的引擎。首次启动大约需要一分钟。"+ "s3158": "正在解压随应用附带的引擎。首次启动大约需要一分钟。",+ "s3159": "正在使用:{0}",+ "s3160": "已安装 · cloudflared {0}",+ "s3161": "Cloudflare 连接器已作为系统服务在这台电脑上运行,因此 Strata 没有再启动第二个。请先停止该服务(或直接使用它的隧道),然后在这里重新连接。",+ "s3162": "Cloudflare 连接器(cloudflared)已在这台电脑上运行,因此 Strata 没有再启动第二个。请先关闭它(或直接使用它的隧道),然后在这里重新连接。",+ "s3163": "Strata 在这台电脑上找不到 Cloudflare 连接器(cloudflared)。",+ "s3164": "请安装 cloudflared(通过包管理器或 Cloudflare 网站),然后点击“重试设置”。Strata 会在 PATH 和常见位置中自动找到它。",+ "s3165": "这台电脑上的 Cloudflare 连接器版本太旧。",+ "s3166": "请将 cloudflared 更新到较新版本,然后点击“重试设置”。",+ "s3167": "找到的 cloudflared 文件无法运行。",+ "s3168": "请重新安装 cloudflared,然后点击“重试设置”。"}diff --git a/apps/host/tests/cloudflared-find.test.mjs b/apps/host/tests/cloudflared-find.test.mjsnew file mode 100644index 000000000..c59255035--- /dev/null+++ b/apps/host/tests/cloudflared-find.test.mjs@@ -0,0 +1,127 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { connectorCandidates, describeConnector, findConnector, findRunningConnector, MIN_VERSION, parseVersion, runningMessage, skippedMessage, versionAtLeast } from '../server/cloudflared-find.mjs';+import { createConnectorInstaller } from '../server/cloudflared-install.mjs';+import { createCloudflare } from '../server/cloudflare.mjs';++test('version text is read and compared against the minimum', () => {+ assert.deepEqual(parseVersion('cloudflared version 2026.5.0 (built 2026-05-12 )'), [2026, 5, 0]);+ assert.equal(parseVersion('no digits here'), null);+ assert.equal(versionAtLeast('2026.5.0'), true);+ assert.equal(versionAtLeast('2022.1.0'), true);+ assert.equal(versionAtLeast('2021.12.2'), false);+ assert.equal(versionAtLeast(null), true, 'a build with no readable version is not refused');+ assert.equal(MIN_VERSION, '2022.1.0');+});++test('Linux search order: own folder, component, PATH, then the usual places', () => {+ const list = connectorCandidates({ directory: '/h/engine/cloudflare', componentDirectory: '/h/components/cloudflared', platform: 'linux', env: { PATH: '/usr/bin:/opt/x/bin:/usr/bin' }, home: '/home/tester' });+ assert.deepEqual(list.slice(0, 4).map(c => [c.path, c.source]), [+ ['/h/engine/cloudflare/cloudflared', 'strata'], ['/h/components/cloudflared/cloudflared', 'component'],+ ['/usr/bin/cloudflared', 'path'], ['/opt/x/bin/cloudflared', 'path']]);+ const places = list.filter(c => c.source === 'system').map(c => c.path);+ for (const want of ['/usr/local/bin/cloudflared', '/opt/homebrew/bin/cloudflared', '/home/tester/.local/bin/cloudflared']) assert.ok(places.includes(want), want);+ assert.equal(list.filter(c => c.path === '/usr/bin/cloudflared').length, 1, '/usr/bin is listed once (PATH wins)');+});++test('Windows and Mac usual places', () => {+ const win = connectorCandidates({ directory: 'C:\\h\\cf', platform: 'win32', env: { Path: 'C:\\tools', ProgramFiles: 'C:\\Program Files', 'ProgramFiles(x86)': 'C:\\Program Files (x86)', LOCALAPPDATA: 'C:\\Users\\a\\AppData\\Local' }, home: 'C:\\Users\\a' }).map(c => c.path);+ assert.ok(win.includes('C:\\tools\\cloudflared.exe'));+ assert.ok(win.includes('C:\\Program Files\\cloudflared\\cloudflared.exe'));+ assert.ok(win.includes('C:\\Program Files (x86)\\cloudflared\\cloudflared.exe'));+ assert.ok(win.includes('C:\\Users\\a\\AppData\\Local\\Microsoft\\WinGet\\Links\\cloudflared.exe'));+ const mac = connectorCandidates({ directory: '/h/cf', platform: 'darwin', env: { PATH: '' }, home: '/Users/a' }).map(c => c.path);+ assert.ok(mac.includes('/opt/homebrew/bin/cloudflared') && mac.includes('/usr/local/bin/cloudflared'));+});++test('a system cloudflared 2026.5.0 in /usr/bin is used, with its version and where it came from', async () => {+ const there = new Set(['/usr/bin/cloudflared']);+ const result = await findConnector({ directory: '/h/engine/cloudflare', platform: 'linux', env: { PATH: '/usr/bin:/bin' }, home: '/home/t', usable: async p => there.has(p), run: async () => 'cloudflared version 2026.5.0 (built 2026-05-12-1234 UTC)' });+ assert.deepEqual(result.found, { path: '/usr/bin/cloudflared', version: '2026.5.0', source: 'path', label: 'found on your PATH' });+ assert.match(describeConnector(result.found), /cloudflared 2026\.5\.0 · \/usr\/bin\/cloudflared \(found on your PATH\)/);+});++test('Strata’s own copy wins over a system one; an old or broken copy is skipped, with a plain reason', async () => {+ const there = new Set(['/h/cf/cloudflared', '/usr/local/bin/cloudflared']);+ const versions = { '/h/cf/cloudflared': 'cloudflared version 2021.3.0', '/usr/local/bin/cloudflared': 'cloudflared version 2025.8.1' };+ const both = await findConnector({ directory: '/h/cf', platform: 'linux', env: { PATH: '' }, home: '/h', usable: async p => there.has(p), run: async p => versions[p] });+ assert.equal(both.found.path, '/usr/local/bin/cloudflared', 'the too-old own copy is passed over');+ assert.equal(both.skipped[0].reason, 'too-old');+ const onlyOld = await findConnector({ directory: '/h/cf', platform: 'linux', env: { PATH: '' }, home: '/h', usable: async p => p === '/h/cf/cloudflared', run: async () => 'cloudflared version 2021.3.0' });+ assert.equal(onlyOld.found, null);+ assert.match(skippedMessage(onlyOld.skipped), /version 2021\.3\.0, which is too old\. Strata needs 2022\.1\.0 or newer/);+ const broken = await findConnector({ directory: '/h/cf', platform: 'linux', env: { PATH: '' }, home: '/h', usable: async p => p === '/h/cf/cloudflared', run: async () => { throw new Error('exec format error'); } });+ assert.equal(broken.found, null);+ assert.match(skippedMessage(broken.skipped), /did not run as cloudflared/);+ const none = await findConnector({ directory: '/h/cf', platform: 'linux', env: { PATH: '' }, home: '/h', usable: async () => false, run: async () => '' });+ assert.deepEqual(none, { found: null, skipped: [] });+ assert.equal(skippedMessage(none.skipped), null);+});++test('STRATA_CLOUDFLARED picks exactly one file; STRATA_CLOUDFLARED_SEARCH=own keeps to Strata’s folders', async () => {+ const one = connectorCandidates({ directory: '/h/cf', platform: 'linux', env: { PATH: '/usr/bin', STRATA_CLOUDFLARED: '/opt/mine/cloudflared' }, home: '/h' });+ assert.deepEqual(one, [{ path: '/opt/mine/cloudflared', source: 'setting' }]);+ const own = connectorCandidates({ directory: '/h/cf', componentDirectory: '/h/c', platform: 'linux', env: { PATH: '/usr/bin', STRATA_CLOUDFLARED_SEARCH: 'own' }, home: '/h' });+ assert.deepEqual(own.map(c => c.source), ['strata', 'component']);+});++test('a real executable on PATH is found and run (a user-local copy, never a system install)', { skip: process.platform === 'win32' }, async () => {+ const dir = await mkdtemp(join(tmpdir(), 'strata-cf-path-'));+ try {+ const bin = join(dir, 'bin'); await mkdir(bin);+ await writeFile(join(bin, 'cloudflared'), '#!/bin/sh\necho "cloudflared version 2026.5.0 (built 2026-05-12)"\n');+ await chmod(join(bin, 'cloudflared'), 0o755);+ const installer = createConnectorInstaller({ directory: join(dir, 'own'), platform: process.platform, env: { PATH: bin }, home: dir, search: undefined });+ assert.equal(await installer.locate(), join(bin, 'cloudflared'));+ assert.equal(installer.connector().version, '2026.5.0');+ assert.equal(await installer.ensure(), join(bin, 'cloudflared'), 'nothing is fetched when one is found');+ } finally { await rm(dir, { recursive: true, force: true }); }+});++test('running detection: our own pid is ignored; a system service is called a service; failing to look is not a block', async () => {+ const run = async (cmd, args) => cmd === 'pgrep' ? '4242\n77\n' : cmd === 'systemctl' ? 'active\n' : '';+ assert.deepEqual(await findRunningConnector({ platform: 'linux', run }), { running: true, kind: 'service', pids: [4242, 77] });+ assert.deepEqual(await findRunningConnector({ platform: 'linux', run, exclude: [4242, 77] }), { running: false, kind: null, pids: [] });+ const user = async cmd => cmd === 'pgrep' ? '9\n' : 'inactive\n';+ assert.equal((await findRunningConnector({ platform: 'linux', run: user })).kind, 'process');+ assert.equal((await findRunningConnector({ platform: 'darwin', run: user })).kind, 'process');+ assert.equal((await findRunningConnector({ platform: 'linux', run: async () => '' })).running, false);+ const win = async cmd => cmd === 'tasklist' ? '"cloudflared.exe","8864","Console","1","28,756 K"\r\n' : 'STATE : 4 RUNNING';+ assert.deepEqual(await findRunningConnector({ platform: 'win32', run: win }), { running: true, kind: 'service', pids: [8864] });+ assert.match(runningMessage({ running: true, kind: 'service' }), /already running on this computer as a system service, so Strata did not start a second one/);+ assert.equal(runningMessage({ running: false }), null);+});++function fakeOrigin() { return { started: 0, async start() { this.started++; }, async stop() {} }; }++test('the tunnel does not start a second connector next to a running one, and says so plainly', async () => {+ const origin = fakeOrigin(); let launched = 0;+ const cf = createCloudflare({ origin, originUrl: 'http://127.0.0.1:1', hasKey: () => true, locate: async () => '/usr/bin/cloudflared',+ connectorInfo: () => ({ path: '/usr/bin/cloudflared', version: '2026.5.0', source: 'path', label: 'found on your PATH' }),+ findRunning: async () => ({ running: true, kind: 'service', pids: [12] }), launch: () => { launched++; throw new Error('must not launch'); } });+ const seen = await cf.inspect();+ assert.equal(seen.installed, true);+ assert.equal(seen.connector.version, '2026.5.0');+ assert.match(seen.connector.summary, /cloudflared 2026\.5\.0 · \/usr\/bin\/cloudflared/);+ assert.equal(seen.external.kind, 'service');+ await assert.rejects(cf.start({ mode: 'quick' }), /already running on this computer as a system service/);+ assert.equal(launched, 0);+ assert.equal(origin.started, 0, 'the private origin is not opened either');+ assert.equal(cf.state().status, 'error');+});++test('with nothing else running the tunnel starts as before and the state names the connector in use', async () => {+ const origin = fakeOrigin(); const spawned = [];+ const fake = { stdout: { on() {} }, stderr: { on() {} }, once() {}, kill() {}, pid: 55 };+ const cf = createCloudflare({ origin, originUrl: 'http://127.0.0.1:1', hasKey: () => true, locate: async () => '/usr/bin/cloudflared',+ connectorInfo: () => ({ path: '/usr/bin/cloudflared', version: '2026.5.0', source: 'path', label: 'found on your PATH' }),+ findRunning: async ({ exclude }) => { assert.ok(Array.isArray(exclude)); return { running: false, kind: null, pids: [] }; },+ launch: (bin, args) => { spawned.push([bin, args]); return fake; }, timeoutMs: 50 });+ await cf.start({ mode: 'quick' });+ assert.equal(spawned[0][0], '/usr/bin/cloudflared');+ assert.equal(cf.state().external, null);+ await cf.stop();+});diff --git a/apps/host/tests/no-acquire.test.mjs b/apps/host/tests/no-acquire.test.mjsindex 77982540e..be714dfaf 100644--- a/apps/host/tests/no-acquire.test.mjs+++ b/apps/host/tests/no-acquire.test.mjs@@ -36,7 +36,7 @@ test('the llama.cpp and cloudflared fetches refuse before any request is made',await assert.rejects(engineInstall.install({ force: true }), err => err instanceof AcquisitionRefused && /llama\.cpp/.test(err.message) && err.status === 409);await assert.rejects(engineInstall.findRelease(), AcquisitionRefused);let connectorRequests = 0;- const installer = createConnectorInstaller({ directory, platform: 'linux', arch: 'x64', fetchImpl: async () => { connectorRequests++; return { ok: false }; } });+ const installer = createConnectorInstaller({ directory, platform: 'linux', arch: 'x64', env: { STRATA_CLOUDFLARED_SEARCH: 'own' }, fetchImpl: async () => { connectorRequests++; return { ok: false }; } });await assert.rejects(installer.ensure(), err => err instanceof AcquisitionRefused && /optional connector component/.test(err.message));assert.equal(requests + connectorRequests, 0, 'nothing was requested');assert.equal(existsSync(join(directory, '.install-')), false);@@ -54,7 +54,7 @@ test('a connector placed in the component folder is used as it is; it is never fconst name = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';await writeFile(join(components, name), 'binary', { mode: 0o755 });try {- const installer = createConnectorInstaller({ directory: join(directory, 'own'), componentDirectory: components, fetchImpl: async () => { throw new Error('no network'); } });+ const installer = createConnectorInstaller({ directory: join(directory, 'own'), componentDirectory: components, env: { STRATA_CLOUDFLARED_SEARCH: 'own' }, run: async () => 'cloudflared version 2026.5.0', fetchImpl: async () => { throw new Error('no network'); } });assert.equal(await installer.locate(), join(components, name));assert.equal(await installer.ensure(), join(components, name));} finally { await rm(directory, { recursive: true, force: true }); }@@ -67,7 +67,7 @@ async function runHost({ env, calls }) {const port = await freePort(), base = `http://127.0.0.1:${port}`;const host = spawn(process.execPath, ['--import', spy, '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_REAL_ENGINE: '1', ACQUIRE_SPY_LOG: log, ...env },+ 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_REAL_ENGINE: '1', STRATA_CLOUDFLARED_SEARCH: 'own', ACQUIRE_SPY_LOG: log, ...env },});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) });diff --git a/apps/host/tests/plain-errors.test.mjs b/apps/host/tests/plain-errors.test.mjsindex b77a8de19..b09cf8c33 100644--- a/apps/host/tests/plain-errors.test.mjs+++ b/apps/host/tests/plain-errors.test.mjs@@ -9,6 +9,9 @@ const built = await build({ stdin: { contents: "export * from './src/lib/plain-econst { plainFailure, plainFailureText, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`);const cases = [+ ['The Cloudflare connector (cloudflared) is not installed here, and the app never downloads it while it runs. Install it from the optional connector component.', 'connector-missing', /could not find Cloudflare’s connector/],+ ['The cloudflared at /usr/bin/cloudflared is version 2021.3.0, which is too old. Strata needs 2022.1.0 or newer. Update cloudflared, then retry.', 'connector-old', /connector on this computer is too old/],+ ['The file at /x/cloudflared did not run as cloudflared. Reinstall cloudflared, then retry.', 'connector-broken', /did not run/],['server_exited', 'start-failed', /model stopped while starting\./],['server_exited (exit code 0xC0000135)', 'dll-missing', /program files is missing/],['server_exited (exit code 0xC000007B)', 'dll-bad', /does not fit this computer or is damaged/],diff --git a/strata_cli/launch/access.py b/strata_cli/launch/access.pyindex 759a66796..05a108a77 100644--- a/strata_cli/launch/access.py+++ b/strata_cli/launch/access.py@@ -63,17 +63,104 @@ def _is_private(address: str) -> bool:return a == 10 or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or (a == 100 and 64 <= b <= 127)-def find_cloudflared() -> str | None:- found = shutil.which("cloudflared")- if found:- return found- for guess in ("/usr/local/bin/cloudflared", "/opt/homebrew/bin/cloudflared", r"C:\Program Files (x86)\cloudflared\cloudflared.exe",- r"C:\Program Files\cloudflared\cloudflared.exe"):- if Path(guess).is_file():- return guess+CLOUDFLARED_MIN = (2022, 1, 0) # the quick-tunnel flags and the "Registered tunnel connection" line Strata waits for+_cf_seen: dict[tuple[str, float], str | None] = {}+++def _cloudflared_places() -> list[str]:+ """Where a cloudflared might be: STRATA_CLOUDFLARED if set, then PATH, then the usual install places."""+ explicit = os.environ.get("STRATA_CLOUDFLARED", "").strip()+ if explicit:+ return [explicit]+ name = "cloudflared.exe" if WINDOWS else "cloudflared"+ out: list[str] = []+ for d in os.environ.get("PATH", "").split(os.pathsep):+ if d.strip():+ out.append(str(Path(d.strip().strip('"')) / name))+ home = Path.home()+ if WINDOWS:+ env = os.environ+ for root in (env.get("ProgramFiles", r"C:\Program Files"), env.get("ProgramFiles(x86)", r"C:\Program Files (x86)")):+ out.append(str(Path(root) / "cloudflared" / name))+ if env.get("LOCALAPPDATA"):+ out.append(str(Path(env["LOCALAPPDATA"]) / "Microsoft" / "WinGet" / "Links" / name))+ out.append(str(Path(env.get("ProgramData", r"C:\ProgramData")) / "chocolatey" / "bin" / name))+ out.append(str(home / "scoop" / "shims" / name))+ else:+ for d in ("/usr/bin", "/usr/local/bin", "/opt/homebrew/bin", "/home/linuxbrew/.linuxbrew/bin", "/snap/bin",+ str(home / ".local" / "bin"), str(home / "bin")):+ out.append(str(Path(d) / name))+ seen: set[str] = set()+ return [p for p in out if not (p in seen or seen.add(p))]+++def cloudflared_version(path: str) -> str | None:+ """`cloudflared --version` of this file as 'YYYY.M.P', '' when it runs but prints no version, None when it does not run."""+ try:+ key = (path, os.stat(path).st_mtime)+ except OSError:+ return None+ if key in _cf_seen:+ return _cf_seen[key]+ try:+ r = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=10,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if WINDOWS else 0)+ text = (r.stdout or "") + (r.stderr or "")+ except (OSError, subprocess.SubprocessError):+ _cf_seen[key] = None+ return None+ m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,3})", text)+ ok = r.returncode == 0 and ("cloudflared" in text.lower() or bool(m))+ _cf_seen[key] = (".".join(m.groups()) if m else "") if ok else None+ return _cf_seen[key]+++def _cf_new_enough(version: str) -> bool:+ if not version:+ return True # a custom build with no readable version is not refused+ return tuple(int(x) for x in version.split(".")) >= CLOUDFLARED_MIN+++def cloudflared_info() -> dict | None:+ """The cloudflared Strata would use: {'path', 'version'}, found on PATH or in the usual places and new enough."""+ for place in _cloudflared_places():+ if not os.path.isfile(place) or (not WINDOWS and not os.access(place, os.X_OK)):+ continue+ version = cloudflared_version(place)+ if version is not None and _cf_new_enough(version):+ return {"path": place, "version": version}return None+def find_cloudflared() -> str | None:+ info = cloudflared_info()+ return info["path"] if info else None+++def cloudflared_running(exclude: tuple[int, ...] = ()) -> str | None:+ """'service' or 'process' when a cloudflared that is not in `exclude` already runs on this computer, else None."""+ try:+ if WINDOWS:+ out = subprocess.run(["tasklist", "/FI", "IMAGENAME eq cloudflared.exe", "/NH", "/FO", "CSV"], capture_output=True,+ text=True, timeout=5, creationflags=subprocess.CREATE_NO_WINDOW).stdout+ pids = [int(p) for p in re.findall(r'"cloudflared\.exe","(\d+)"', out, re.I)]+ else:+ out = subprocess.run(["pgrep", "-x", "cloudflared"], capture_output=True, text=True, timeout=5).stdout+ pids = [int(p) for p in out.split() if p.isdigit()]+ except (OSError, subprocess.SubprocessError):+ return None+ if not [p for p in pids if p not in exclude]:+ return None+ try:+ if sys.platform.startswith("linux"):+ active = subprocess.run(["systemctl", "is-active", "cloudflared"], capture_output=True, text=True, timeout=5).stdout.strip()+ if active == "active":+ return "service"+ except (OSError, subprocess.SubprocessError):+ pass+ return "process"++def find_tailscale() -> str | None:found = shutil.which("tailscale")if found:@@ -242,6 +329,10 @@ def start_tunnel(name: str, port: int, *, wait: float = 45.0) -> tuple[str | Nonexisting = tunnel_info(name)if existing and existing.get("url") and existing.get("port") == port:return existing["url"], "The tunnel was already running."+ other = cloudflared_running(exclude=(int(existing["pid"]),) if existing else ())+ if other:+ return None, ("Cloudflare’s connector is already running on this computer" + (" as a system service" if other == "service" else "") ++ ", so Strata did not start a second one. Stop it first (or use its tunnel as it is), then connect again here.")stop_tunnel(name)log = _state_dir() / f"{Path(name).name}.tunnel.log"argv = [exe, "tunnel", "--no-autoupdate", "--url", f"http://127.0.0.1:{port}"]diff --git a/tests/terminal/test_cloudflared_find.py b/tests/terminal/test_cloudflared_find.pynew file mode 100644index 000000000..6e9d7c3cb--- /dev/null+++ b/tests/terminal/test_cloudflared_find.py@@ -0,0 +1,126 @@+"""The Terminal finds a cloudflared that the system installed (PATH, /usr/bin, ~/.local/bin, Homebrew, Program Files), checks its+version, and does not start a second connector next to one that is already running."""++from __future__ import annotations++import os+import stat+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++from strata_cli.launch import access+++def fake_cloudflared(directory: Path, version: str = "2026.5.0", name: str = "cloudflared") -> Path:+ path = directory / name+ path.write_text(f'#!/bin/sh\necho "cloudflared version {version} (built 2026-05-12)"\n')+ path.chmod(path.stat().st_mode | stat.S_IXUSR)+ return path++[email protected](os.name == "nt", "the fixture is a shell script")+class FindOnPath(unittest.TestCase):+ def setUp(self):+ access._cf_seen.clear()+ self.tmp = tempfile.TemporaryDirectory()+ self.dir = Path(self.tmp.name)++ def tearDown(self):+ self.tmp.cleanup()++ def env(self, **extra):+ return mock.patch.dict(os.environ, {"PATH": str(self.dir / "bin"), "HOME": str(self.dir), **extra}, clear=False)++ def test_a_user_local_copy_on_path_is_found_with_its_version(self):+ (self.dir / "bin").mkdir()+ exe = fake_cloudflared(self.dir / "bin")+ with self.env():+ info = access.cloudflared_info()+ self.assertEqual(info, {"path": str(exe), "version": "2026.5.0"})+ self.assertEqual(access.find_cloudflared(), str(exe))++ def test_the_local_bin_folder_is_searched_when_path_misses_it(self):+ (self.dir / ".local" / "bin").mkdir(parents=True)+ exe = fake_cloudflared(self.dir / ".local" / "bin")+ with self.env(PATH=str(self.dir / "empty")), mock.patch.object(Path, "home", return_value=self.dir):+ self.assertEqual(access.find_cloudflared(), str(exe))++ def test_a_too_old_copy_is_passed_over(self):+ (self.dir / "bin").mkdir()+ fake_cloudflared(self.dir / "bin", version="2021.3.0")+ with self.env(), mock.patch.object(Path, "home", return_value=self.dir / "nohome"):+ places = [p for p in access._cloudflared_places() if str(self.dir) in p]+ with mock.patch.object(access, "_cloudflared_places", return_value=places):+ self.assertIsNone(access.find_cloudflared())++ def test_a_file_that_does_not_run_is_passed_over(self):+ (self.dir / "bin").mkdir()+ bad = self.dir / "bin" / "cloudflared"+ bad.write_text("#!/bin/sh\nexit 3\n")+ bad.chmod(0o755)+ with self.env(), mock.patch.object(access, "_cloudflared_places", return_value=[str(bad)]):+ self.assertIsNone(access.find_cloudflared())++ def test_strata_cloudflared_picks_exactly_that_file(self):+ exe = fake_cloudflared(self.dir, version="2025.1.2", name="mine")+ with self.env(STRATA_CLOUDFLARED=str(exe)):+ self.assertEqual(access._cloudflared_places(), [str(exe)])+ self.assertEqual(access.cloudflared_info()["version"], "2025.1.2")+++class Places(unittest.TestCase):+ def test_the_usual_places_are_listed(self):+ with mock.patch.dict(os.environ, {"PATH": "/opt/x/bin"}, clear=False), mock.patch.object(access, "WINDOWS", False), \+ mock.patch.dict(os.environ, {}, clear=False):+ os.environ.pop("STRATA_CLOUDFLARED", None)+ places = [p.replace("\\", "/") for p in access._cloudflared_places()]+ for want in ("/opt/x/bin/cloudflared", "/usr/bin/cloudflared", "/usr/local/bin/cloudflared", "/opt/homebrew/bin/cloudflared"):+ self.assertIn(want, places)+ self.assertTrue(any(p.endswith(".local/bin/cloudflared") for p in places))+ self.assertEqual(len(places), len(set(places)))++ def test_windows_places_include_program_files(self):+ env = {"PATH": "", "ProgramFiles": r"C:\Program Files", "ProgramFiles(x86)": r"C:\Program Files (x86)"}+ with mock.patch.dict(os.environ, env, clear=False), mock.patch.object(access, "WINDOWS", True):+ os.environ.pop("STRATA_CLOUDFLARED", None)+ places = access._cloudflared_places()+ self.assertTrue(any("Program Files" in p and p.endswith("cloudflared.exe") for p in places))++ def test_version_rule(self):+ self.assertTrue(access._cf_new_enough("2026.5.0"))+ self.assertTrue(access._cf_new_enough("2022.1.0"))+ self.assertFalse(access._cf_new_enough("2021.12.2"))+ self.assertTrue(access._cf_new_enough(""))+++class NoSecondConnector(unittest.TestCase):+ def test_a_running_connector_is_reported_and_not_doubled(self):+ with mock.patch.object(access, "find_cloudflared", return_value="/usr/bin/cloudflared"), \+ mock.patch.object(access, "tunnel_info", return_value=None), \+ mock.patch.object(access, "cloudflared_running", return_value="service"), \+ mock.patch.object(access.subprocess, "Popen") as popen:+ url, message = access.start_tunnel("demo", 8080)+ self.assertIsNone(url)+ popen.assert_not_called()+ self.assertIn("already running on this computer as a system service", message)+ self.assertIn("did not start a second one", message)++ def test_running_detection_ignores_strata_own_pid_and_names_a_service(self):+ def fake_run(argv, **kw):+ out = {"pgrep": "4242\n", "systemctl": "active\n"}[argv[0]]+ return mock.Mock(stdout=out, returncode=0)+ with mock.patch.object(access, "WINDOWS", False), mock.patch.object(access.sys, "platform", "linux"), \+ mock.patch.object(access.subprocess, "run", side_effect=fake_run):+ self.assertEqual(access.cloudflared_running(), "service")+ self.assertIsNone(access.cloudflared_running(exclude=(4242,)))++ def test_a_missing_pgrep_is_never_a_block(self):+ with mock.patch.object(access, "WINDOWS", False), mock.patch.object(access.subprocess, "run", side_effect=FileNotFoundError):+ self.assertIsNone(access.cloudflared_running())+++if __name__ == "__main__":+ unittest.main()