From f95fb3e0743ac06c654a0714b49ee384de07fd10 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 17 Oct 2026 18:54:11 +0200 Subject: [PATCH 1/9] Fix agent chat on Linux and Mac: keep the Harness's own dsh-* packages when pruning other-OS binaries, verify imports at staging, plain start-failure message --- apps/desktop/scripts/harness-prune.mjs | 79 ++++++++++++++++++++++++ apps/desktop/scripts/stage-harness.mjs | 18 +++--- apps/host/server/agent/agent-bridge.mjs | 18 ++++++ apps/host/server/index.mjs | 7 ++- apps/host/tests/agent-status.test.mjs | 11 ++++ apps/host/tests/harness-staging.test.mjs | 48 ++++++++++++++ 6 files changed, 171 insertions(+), 10 deletions(-) create mode 100644 apps/desktop/scripts/harness-prune.mjs create mode 100644 apps/host/tests/harness-staging.test.mjs diff --git a/apps/desktop/scripts/harness-prune.mjs b/apps/desktop/scripts/harness-prune.mjs new file mode 100644 index 00000000..35b81124 --- /dev/null +++ b/apps/desktop/scripts/harness-prune.mjs @@ -0,0 +1,79 @@ +/** + * Which files and folders of the staged Harness are dropped, and the check that nothing the Harness imports is gone. + * + * The 2026-10-17 tester report: on Linux and Mac every agent chat failed ("session/create ... waiting for workflowEngine"). + * Cause: the old rule "drop any folder named after another operating system" also removed the Harness's own JavaScript package + * `@deepseek-ai/dsh-win32-process`. It is plain JS (no binary), and `dsh-subprocess-local` and `dsh-sandbox-local` import it by + * name on every platform, so those two plugins failed to load, and everything waiting on them (shell, subprocess, ptcRuntime, + * workflowEngine) never started. Windows kept it (the rule differs there), so the Windows tests passed. + */ +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { join, sep } from 'node:path'; + +export const OTHER_OS = { + win32: /(^|[\\/._-])(darwin|linux|android|freebsd|musl)([\\/._-]|$)/i, + darwin: /(^|[\\/._-])(win32|linux|android|freebsd|musl)([\\/._-]|$)/i, + // Linux: the AppImage bundler (linuxdeploy) resolves the libraries of every ELF file under resources and stops on one it + // cannot satisfy (koffi's musl build wants libc.musl). The app is glibc x86_64, so musl and other-CPU builds are dropped. + linux: /(^|[\\/._-])(win32|darwin|android|freebsd|musl|arm64|aarch64|armv7|arm|ia32|riscv64|ppc64|s390x|loong64)([\\/._-]|$)/i, +}; +const NATIVE_FOLDER = /prebuild|bin|native|platform|-(win32|darwin|linux)/i; + +/** The Harness's own JavaScript packages (`@deepseek-ai/dsh-*`) are code every platform imports by name; never drop one. */ +export function isHarnessCodePackage(path) { + const parts = path.split(sep); + const i = parts.lastIndexOf('@deepseek-ai'); + return i >= 0 && i === parts.length - 2 && parts[i + 1].startsWith('dsh-'); +} + +/** True when the folder `path` (a directory named `name`) is another operating system's prebuilt binary and can go. */ +export function isOtherOsBinaryFolder(platform, name, path) { + const rule = OTHER_OS[platform] ?? OTHER_OS.linux; + if (isHarnessCodePackage(path)) return false; + return rule.test(name) && NATIVE_FOLDER.test(path); +} + +/** Imports the Windows copy (which works) is also without: browser-side or dev-only bundles, and the document converter the app drops on purpose. */ +const KNOWN_ABSENT = new Set([ + '@deepseek-ai/libreoffice-kit', '@deepseek-ai/dsh-client-ui-dockkit', '@deepseek-ai/dsh-client-web', + '@deepseek-ai/dsh-experimental-webworker-runtime', '@deepseek-ai/dsh-remote-mock', '@deepseek-ai/dsh-client-test-runtime', +]); + +function jsFiles(dir, out = []) { + for (const e of readdirSync(dir, { withFileTypes: true })) { + const p = join(dir, e.name); + if (e.isSymbolicLink()) continue; + if (e.isDirectory()) jsFiles(p, out); + else if (/\.(m?js|cjs)$/.test(e.name)) out.push(p); + } + return out; +} + +/** + * Every bare `@deepseek-ai/` the staged Harness's own packages import (static `from "x"` and `import("x")`) must exist + * in the staged node_modules. Returns the list of `{from, missing}` problems (empty = good). Plugins that are only loaded on + * another platform still count: Node resolves a static import whether or not the code runs. + */ +export function missingHarnessImports(harnessDir) { + const scope = join(harnessDir, 'node_modules', '@deepseek-ai'); + if (!existsSync(scope)) return [{ from: scope, missing: '@deepseek-ai (no installed packages)' }]; + const problems = []; + const seen = new Set(); + const re = /(?:from|import)\s*\(?\s*["'](@deepseek-ai\/[^"'/]+)(?:\/[^"']*)?["']/g; + for (const pkg of readdirSync(scope)) { + const lib = join(scope, pkg, 'lib'); + if (!existsSync(lib)) continue; + for (const file of jsFiles(lib)) { + const text = readFileSync(file, 'utf8'); + for (const m of text.matchAll(re)) { + const name = m[1]; + const key = `${pkg}>${name}`; + if (seen.has(key) || KNOWN_ABSENT.has(name)) continue; + seen.add(key); + if (!existsSync(join(harnessDir, 'node_modules', ...name.split('/'))) + && !existsSync(join(scope, pkg, 'node_modules', ...name.split('/')))) problems.push({ from: `${pkg}`, missing: name }); + } + } + } + return problems; +} diff --git a/apps/desktop/scripts/stage-harness.mjs b/apps/desktop/scripts/stage-harness.mjs index 7ea86c34..74d9b960 100644 --- a/apps/desktop/scripts/stage-harness.mjs +++ b/apps/desktop/scripts/stage-harness.mjs @@ -18,6 +18,7 @@ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, import { join, relative, resolve, sep } from 'node:path'; import { createHash } from 'node:crypto'; import { flattenPnpm } from './flatten-pnpm.mjs'; +import { isOtherOsBinaryFolder, missingHarnessImports } from './harness-prune.mjs'; const args = process.argv.slice(2); const opt = (name, fallback) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : fallback; }; @@ -118,11 +119,6 @@ const flat = flattenPnpm(out, { skip: /libreoffice-kit|sherpa-onnx/i }); console.log(`flattened: ${flat.packages} placed (${flat.nested} nested for a second version)`); // --- prune ------------------------------------------------------------------------------------------------------------ -const OTHER_OS = platform === 'win32' ? /(^|[\\/._-])(darwin|linux|android|freebsd|musl)([\\/._-]|$)/i - : platform === 'darwin' ? /(^|[\\/._-])(win32|linux|android|freebsd|musl)([\\/._-]|$)/i - : /(^|[\\/._-])(win32|darwin|android|freebsd|musl|arm64|aarch64|armv7|arm|ia32|riscv64|ppc64|s390x|loong64)([\\/._-]|$)/i; -// Linux: the AppImage bundler (linuxdeploy) resolves the libraries of every ELF file under resources and stops on one it -// cannot satisfy (koffi's musl build wants libc.musl). The app is glibc x86_64, so musl and other-CPU builds are dropped. /** Whole packages the app never loads: office-document conversion (hundreds of MB) and speech input. */ const DROP_PACKAGES = [/libreoffice-kit/i, /sherpa-onnx/i]; /** Only when sitting directly in a package's root (a library may have a runtime folder called `doc`, e.g. yaml/dist/doc). */ @@ -137,7 +133,7 @@ function prune(dir) { if (e.isSymbolicLink()) continue; if (e.isDirectory()) { const inLib = p.split(sep).includes('lib'); - if ((DROP_DIRS.has(e.name) && !inLib && existsSync(join(dir, 'package.json'))) || DROP_PACKAGES.some(r => r.test(e.name)) || (OTHER_OS.test(e.name) && /prebuild|bin|native|platform|-(win32|darwin|linux)/i.test(p))) { + if ((DROP_DIRS.has(e.name) && !inLib && existsSync(join(dir, 'package.json'))) || DROP_PACKAGES.some(r => r.test(e.name)) || isOtherOsBinaryFolder(platform, e.name, p)) { rmSync(p, { recursive: true, force: true }); removed++; continue; } prune(p); @@ -165,7 +161,15 @@ writeFileSync(join(out, 'BUNDLE.json'), JSON.stringify({ if (keepIgnore) writeFileSync(join(out, '.gitignore'), keepIgnore); -// --- proof: the staged copy answers --version and boots the web profile once ---------------------------------------- +// --- proof 1: nothing the Harness imports by name was pruned ------------------------------------------------------------ +// (2026-10-17: the other-OS rule once removed @deepseek-ai/dsh-win32-process, which every platform imports; Linux/Mac agent chats died.) +const lost = missingHarnessImports(out); +if (lost.length) { console.error('staged Harness is missing imported packages: +' + lost.map(l => ` ${l.from} -> ${l.missing}`).join(' +')); process.exit(1); } +console.log('import check: every @deepseek-ai package the Harness imports is staged'); + +// --- proof 2: the staged copy answers --version and boots the web profile once ---------------------------------------- const bin = join(out, 'apps', 'cli', 'lib', 'bin.js'); const entry = existsSync(bin) ? bin : join(out, 'lib', 'bin.js'); const v = spawnSync(process.execPath, [entry, '--version'], { encoding: 'utf8' }); diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index 07ceed36..e3e2c308 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -44,6 +44,24 @@ export function plainAgentFailure(raw) { return text; } +/** + * A failure thrown while a turn starts, as `{ message, details, code }` for the chat's error card. The agent's own errors read like + * `session/create: tool-bash (...): waiting for shell ...` (a plugin chain that never started): never shown raw. The plain sentence + * goes in `message`; the technical text goes in `details`, which the app shows only behind Details. + */ +export function plainTurnFailure(err) { + const raw = String(err?.message ?? err ?? ''); + const details = typeof err?.details === 'string' && err.details ? err.details : raw; + if (err instanceof AgentUnavailable) return { message: err.message, details, code: err.code ?? 'AGENT_ERROR' }; + if (err?.code === 'agent-preset/invalid' || /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)|failed to import|did not activate/i.test(raw)) { + return { message: 'The coding assistant is missing a part it needs, so it cannot work on files yet. Close and reopen Strata. If it keeps happening, reinstall Strata. Chatting without tools still works.', details, code: 'AGENT_INCOMPLETE' }; + } + if (/^[a-z][a-z-]*\/[a-z][a-z-]*: /i.test(raw) || /^(gateway|rpc)/i.test(raw)) { + return { message: 'The coding assistant could not start this message. Try again. If it keeps happening, close and reopen Strata.', details, code: err?.code ?? 'AGENT_ERROR' }; + } + return { message: plainAgentFailure(raw), details, code: err?.code ?? 'AGENT_ERROR' }; +} + /** Attached pictures (data addresses) as the Harness's image prompt parts. */ export function imageParts(images) { return (Array.isArray(images) ? images : []).map(i => { diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index c7ed4a88..dae32222 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -13,7 +13,7 @@ import { skillEdit } from './skill-edits.mjs'; import { materializeSkills, parseSkillFile, skillSlug, writeCreatedSkill } from './skill-files.mjs'; import { systemFonts } from './fonts.mjs'; import { tuningDir } from './platform-paths.mjs'; -import { createAgentBridge } from './agent/agent-bridge.mjs'; +import { createAgentBridge, plainTurnFailure } from './agent/agent-bridge.mjs'; import { createAgentTools } from './agent/tools-settings.mjs'; import { withPlainStatus } from './agent/status.mjs'; import { findBrowser, findPlaywrightMcp } from './agent/browser-probe.mjs'; @@ -563,8 +563,9 @@ async function runAgentTurn({ res, controller, chatId, body, message, workspaceI if (result?.detached) void result.ended.then(r => settle(r?.tokensOut ?? null), () => settle(null)); else settle(result?.tokensOut ?? null, result?.error ? 'The agent turn failed.' : undefined); } catch (err) { - write({ type: 'error', message: err.message, ...(err.details ? { details: err.details } : {}), code: err.code ?? 'AGENT_ERROR' }); - settle(null, err.message); + const plain = plainTurnFailure(err); + write({ type: 'error', message: plain.message, ...(plain.details ? { details: plain.details } : {}), code: plain.code }); + settle(null, plain.message); } } diff --git a/apps/host/tests/agent-status.test.mjs b/apps/host/tests/agent-status.test.mjs index 5ebd2cd9..db6f5b5a 100644 --- a/apps/host/tests/agent-status.test.mjs +++ b/apps/host/tests/agent-status.test.mjs @@ -176,3 +176,14 @@ test('a goal step is always sent, even right after another status (it used to be advance(400); assert.ok(frames.some(f => f.phase === 'goal' && f.args.round === 1), frames.map(f => f.phase).join(',')); }); + +import { plainTurnFailure } from '../server/agent/agent-bridge.mjs'; +test('a start failure from the agent reads in plain words and keeps the raw text for Details', () => { + const raw = new Error('session/create: tool-bash (@deepseek-ai/dsh-tool-bash): waiting for shell\ntool-workflow: waiting for workflowEngine'); + raw.code = 'agent-preset/invalid'; + const f = plainTurnFailure(raw); + assert.doesNotMatch(f.message, /session\/create|waiting for|@deepseek-ai|workflowEngine/); + assert.match(f.message, /reinstall|reopen/i); + assert.match(f.details, /waiting for workflowEngine/); + assert.doesNotMatch(plainTurnFailure(new Error('turn/start: boom')).message, /turn\/start/); +}); diff --git a/apps/host/tests/harness-staging.test.mjs b/apps/host/tests/harness-staging.test.mjs new file mode 100644 index 00000000..70993fe0 --- /dev/null +++ b/apps/host/tests/harness-staging.test.mjs @@ -0,0 +1,48 @@ +/** + * The staged Harness keeps every package its plugins import (tester report 2026-10-17: Linux and Mac agent chats failed with + * "session/create ... waiting for workflowEngine" because the other-OS prune removed @deepseek-ai/dsh-win32-process). + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, sep } from 'node:path'; +import { isHarnessCodePackage, isOtherOsBinaryFolder, missingHarnessImports } from '../../desktop/scripts/harness-prune.mjs'; + +const nm = (...p) => ['harness', 'node_modules', ...p].join(sep); + +test('the Harness own code packages are never pruned, on any platform', () => { + for (const platform of ['linux', 'darwin', 'win32']) { + for (const name of ['dsh-win32-process', 'dsh-darwin-thing', 'dsh-linux-thing', 'dsh-sandbox-windows-acl']) { + assert.equal(isOtherOsBinaryFolder(platform, name, nm('@deepseek-ai', name)), false, `${platform}: ${name}`); + } + } + assert.equal(isHarnessCodePackage(nm('@deepseek-ai', 'dsh-win32-process')), true); + assert.equal(isHarnessCodePackage(nm('@deepseek-ai', 'dsh-win32-process', 'lib')), false); +}); + +test('other systems prebuilt binaries are still dropped', () => { + assert.equal(isOtherOsBinaryFolder('linux', 'sharp-win32-x64', nm('@img', 'sharp-win32-x64')), true); + assert.equal(isOtherOsBinaryFolder('linux', 'musl', nm('@deepseek-ai', 'node-addon-system-linux-x64', 'bin', 'musl')), true); + assert.equal(isOtherOsBinaryFolder('darwin', 'win32-x64', nm('node-pty', 'prebuilds', 'win32-x64')), true); + assert.equal(isOtherOsBinaryFolder('win32', 'linux-x64', nm('node-pty', 'prebuilds', 'linux-x64')), true); + // this platform's own binaries stay + assert.equal(isOtherOsBinaryFolder('linux', 'linux-x64', nm('node-pty', 'prebuilds', 'linux-x64')), false); +}); + +test('missingHarnessImports names a package a plugin imports that is not staged', () => { + const root = mkdtempSync(join(tmpdir(), 'strata-stage-')); + try { + const scope = join(root, 'node_modules', '@deepseek-ai'); + mkdirSync(join(scope, 'dsh-subprocess-local', 'lib'), { recursive: true }); + writeFileSync(join(scope, 'dsh-subprocess-local', 'lib', 'index.js'), 'import { x } from "@deepseek-ai/dsh-win32-process";\nawait import("@deepseek-ai/dsh-here");\n'); + mkdirSync(join(scope, 'dsh-here'), { recursive: true }); + assert.deepEqual(missingHarnessImports(root), [{ from: 'dsh-subprocess-local', missing: '@deepseek-ai/dsh-win32-process' }]); + mkdirSync(join(scope, 'dsh-win32-process'), { recursive: true }); + assert.deepEqual(missingHarnessImports(root), []); + } finally { rmSync(root, { recursive: true, force: true }); } +}); + +test('a staged Harness (STRATA_HARNESS_DIR) has every package its plugins import', { skip: !process.env.STRATA_HARNESS_DIR }, () => { + assert.deepEqual(missingHarnessImports(process.env.STRATA_HARNESS_DIR), []); +}); From 37f7f03cd2a50d98f2be1bfaef09bc33d2f863dc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 17 Oct 2026 18:59:45 +0200 Subject: [PATCH 2/9] Engine packages: bundle every imported non-system library, refuse a package a clean PC could not start, PE/ELF/Mach-O import scanner and tests --- packaging/binary_deps.py | 236 +++++++++++++++++++++++++++++ packaging/package_engine.py | 64 +++++++- tests/terminal/test_engine_deps.py | 124 +++++++++++++++ 3 files changed, 422 insertions(+), 2 deletions(-) create mode 100644 packaging/binary_deps.py create mode 100644 tests/terminal/test_engine_deps.py diff --git a/packaging/binary_deps.py b/packaging/binary_deps.py new file mode 100644 index 00000000..0c222732 --- /dev/null +++ b/packaging/binary_deps.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""What an engine file needs from the machine it runs on: PE (Windows), ELF (Linux) and Mach-O (macOS) import lists, read +with no tools and no third-party packages, and the rule "everything imported is bundled or belongs to the OS or the GPU driver". + +Why: on 2026-10-17 a tester's clean Windows 11 PC failed to start the engine with 0xC0000135 (a DLL was not found): the +package held strata.exe and strata_kq.dll but not cublas64_13.dll / cublasLt64_13.dll, which strata.exe imports. Our own +clean-profile test passed only because the build PC has the CUDA Toolkit on PATH. The packager now refuses a package whose imports +are not covered, and `--check-deps` / the test suite run the same rule on any finished package. + + python packaging/binary_deps.py # exit 0 when every import is bundled or system, 1 with the list + +Library names are compared case-insensitively on Windows and by soname elsewhere. +""" + +from __future__ import annotations + +import fnmatch +import struct +import sys +from pathlib import Path + +# ---- Windows --------------------------------------------------------------------------------------------------------------- +# Libraries Windows itself ships (a clean Windows 10/11 has them) or the GPU driver installs in System32. Anything else an +# engine file imports (the Visual C++ runtime, CUDA, HIP, SYCL/Level Zero loaders, OpenMP...) must travel in the package. +WINDOWS_OS = ( + "kernel32.dll", "kernelbase.dll", "user32.dll", "gdi32.dll", "advapi32.dll", "shell32.dll", "ole32.dll", "oleaut32.dll", + "ws2_32.dll", "wsock32.dll", "mswsock.dll", "iphlpapi.dll", "bcrypt.dll", "crypt32.dll", "secur32.dll", "sechost.dll", + "ntdll.dll", "msvcrt.dll", "ucrtbase.dll", "rpcrt4.dll", "shlwapi.dll", "setupapi.dll", "cfgmgr32.dll", "version.dll", + "winmm.dll", "imm32.dll", "comctl32.dll", "comdlg32.dll", "dbghelp.dll", "psapi.dll", "pdh.dll", "powrprof.dll", + "userenv.dll", "netapi32.dll", "wininet.dll", "winhttp.dll", "dxgi.dll", "d3d11.dll", "d3d12.dll", "dwmapi.dll", + "dxcore.dll", "wtsapi32.dll", "ncrypt.dll", "normaliz.dll", "api-ms-win-*.dll", "ext-ms-win-*.dll", "hid.dll", + "opengl32.dll", "glu32.dll", "wldap32.dll", "authz.dll", "msi.dll", "propsys.dll", "uxtheme.dll", "dnsapi.dll", +) +# Installed by the GPU driver into System32 (never redistributable by us): the CUDA driver API, the NVIDIA management library, +# and the AMD / Intel user-mode driver pieces the driver package owns. +WINDOWS_DRIVER = ( + "nvcuda.dll", "nvml.dll", "nvapi64.dll", "nvapi.dll", "nvcuvid.dll", "nvEncodeAPI64.dll", "nvfatbinaryloader.dll", + "amdxx64.dll", "amdhip64_*.dll", "amdhip64.dll", "atiadlxx.dll", "atiadlxy.dll", "amdadlx64.dll", + "igdrcl64.dll", "ze_intel_gpu64.dll", "ze_loader.dll", "OpenCL.dll", "vulkan-1.dll", +) + +# ---- Linux ----------------------------------------------------------------------------------------------------------------- +# Every distribution has these (glibc and the compiler runtime). Names are sonames or glob patterns. +LINUX_OS = ( + "linux-vdso.so.1", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1", "libc.so.6", "libm.so.6", "libdl.so.2", "libpthread.so.0", + "librt.so.1", "libutil.so.1", "libresolv.so.2", "libnss_*.so.*", "libgcc_s.so.1", "libstdc++.so.6", "libgomp.so.1", + "libatomic.so.1", "libz.so.1", "libnuma.so.1", "libdrm.so.2", "libdrm_amdgpu.so.1", "libelf.so.1", "libtinfo.so.*", + "libcrypt.so.1", "libffi.so.*", "libpci.so.3", "libudev.so.1", "libX11.so.6", "libxcb.so.1", +) +# From the GPU driver package: never bundled. +LINUX_DRIVER = ( + "libcuda.so.1", "libcuda.so", "libnvidia-*.so*", "libnvcuvid.so*", "libze_intel_gpu.so*", "libze_loader.so*", + "libOpenCL.so*", "libvulkan.so*", "libGLX*.so*", "libEGL*.so*", "libamdgpu*.so*", "libhsa-runtime64.so*", + "libdrm_amdgpu.so*", "libigdrcl.so*", "libnvidia-ml.so*", +) + +# ---- macOS ----------------------------------------------------------------------------------------------------------------- +MAC_OS_PREFIXES = ("/usr/lib/", "/System/Library/") + + +def _match(name: str, patterns: tuple[str, ...], fold: bool) -> bool: + n = name.lower() if fold else name + return any(fnmatch.fnmatchcase(n, (p.lower() if fold else p)) for p in patterns) + + +# ---- readers --------------------------------------------------------------------------------------------------------------- +def pe_imports(path: Path) -> list[str]: + """DLL names a PE file imports at load time (import table) plus delay-load imports (loaded at first call).""" + data = path.read_bytes() + if data[:2] != b"MZ": + raise ValueError(f"{path}: not a PE file") + pe = struct.unpack_from(" int: + for va, size, raw in sections: + if va <= rva < va + size: + return raw + rva - va + raise ValueError(f"{path}: RVA {rva:#x} is outside every section") + + def cstr(o: int) -> str: + end = data.index(b"\0", o) + return data[o:end].decode("ascii", "replace") + + names: list[str] = [] + imp_rva, imp_size = struct.unpack_from(" list[str]: + """DT_NEEDED sonames of an ELF file (what ldd lists); libraries opened with dlopen are not visible here.""" + data = path.read_bytes() + if data[:4] != b"\x7fELF": + raise ValueError(f"{path}: not an ELF file") + is64 = data[4] == 2 + le = "<" if data[5] == 1 else ">" + if is64: + shoff, = struct.unpack_from(le + "Q", data, 0x28) + shentsize, shnum = struct.unpack_from(le + "HH", data, 0x3A) + else: + shoff, = struct.unpack_from(le + "I", data, 0x20) + shentsize, shnum = struct.unpack_from(le + "HH", data, 0x2E) + out: list[str] = [] + for i in range(shnum): + base = shoff + i * shentsize + if is64: + stype, = struct.unpack_from(le + "I", data, base + 4) + offset, size, link = struct.unpack_from(le + "QQI", data, base + 0x18) + else: + stype, = struct.unpack_from(le + "I", data, base + 4) + offset, size, link = struct.unpack_from(le + "III", data, base + 0x10) + if stype != 6: # SHT_DYNAMIC + continue + sbase = shoff + link * shentsize + stroff = struct.unpack_from(le + ("Q" if is64 else "I"), data, sbase + (0x18 if is64 else 0x10))[0] + step = 16 if is64 else 8 + for o in range(offset, offset + size, step): + tag, val = struct.unpack_from(le + ("qQ" if is64 else "iI"), data, o) + if tag == 0: + break + if tag == 1: + s = stroff + val + out.append(data[s:data.index(b"\0", s)].decode("ascii", "replace")) + return out + + +def macho_dylibs(path: Path) -> list[str]: + """Install names a Mach-O file loads (LC_LOAD_DYLIB, weak, reexport). A fat file reads its first slice.""" + data = path.read_bytes() + magic = struct.unpack_from(">I", data, 0)[0] + base = 0 + if magic in (0xCAFEBABE, 0xCAFEBABF): + base = struct.unpack_from(">I", data, 16)[0] if magic == 0xCAFEBABE else struct.unpack_from(">Q", data, 24)[0] + magic = struct.unpack_from(">I", data, base)[0] + if struct.unpack_from(" tuple[str, list[str]]: + """(kind, names) for a binary, or ("", []) when it is not an executable format this module reads.""" + with path.open("rb") as f: + head = f.read(4) + if head[:2] == b"MZ": + return "pe", pe_imports(path) + if head == b"\x7fELF": + return "elf", elf_needed(path) + if head in (b"\xcf\xfa\xed\xfe", b"\xce\xfa\xed\xfe", b"\xca\xfe\xba\xbe", b"\xbe\xba\xfe\xca"): + return "macho", macho_dylibs(path) + return "", [] + + +# ---- the rule -------------------------------------------------------------------------------------------------------------- +def uncovered(folder: Path, files: list[str] | None = None) -> list[tuple[str, str]]: + """(file, imported library) pairs that are neither in the package nor the OS's nor the GPU driver's. Empty = a clean PC runs it.""" + folder = Path(folder) + rels = files if files is not None else [p.relative_to(folder).as_posix() for p in sorted(folder.rglob("*")) if p.is_file() and not p.is_symlink()] + bundled_win = {Path(r).name.lower() for r in rels} + bundled = {Path(r).name for r in rels} + problems: list[tuple[str, str]] = [] + for rel in rels: + p = folder / rel + if p.suffix.lower() in (".json", ".txt", ".md", ".cu", ".h", ".py", ".yaml", ".yml", ".metallib", ".bin"): + continue + try: + kind, names = imports(p) + except (ValueError, OSError, struct.error): + continue + for name in names: + if kind == "pe": + if name.lower() in bundled_win or _match(name, WINDOWS_OS, True) or _match(name, WINDOWS_DRIVER, True): + continue + elif kind == "elf": + if name in bundled or _match(name, LINUX_OS, False) or _match(name, LINUX_DRIVER, False): + continue + else: + base = name.rsplit("/", 1)[-1] + if name.startswith(MAC_OS_PREFIXES) or base in bundled: + continue + problems.append((rel, name)) + return problems + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + print(__doc__) + return 2 + bad = uncovered(Path(argv[1])) + for rel, name in bad: + print(f"{rel}: needs {name}, which is not in the package and not an OS or driver library") + if not bad: + print(f"{argv[1]}: every imported library is bundled or belongs to the OS / GPU driver") + return 1 if bad else 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/packaging/package_engine.py b/packaging/package_engine.py index 1b6c33c7..15820294 100644 --- a/packaging/package_engine.py +++ b/packaging/package_engine.py @@ -35,6 +35,9 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import binary_deps # noqa: E402 from strata_control import engine_component as ec # noqa: E402 from strata_control.components import BACKEND_MATRIX, host_platform # noqa: E402 @@ -84,7 +87,7 @@ def select(src: Path, entrypoint: str, *, tree: bool, include: list[str]) -> lis def build(src: Path, backend: str, version: str, target: str, out: Path, *, entry: str | None = None, archs: tuple[str, ...] = (), min_driver: dict | None = None, build_id: str | None = None, min_runtime: str | None = None, notes: str = "", tree: bool = False, include: list[str] | None = None, - variant: str = "") -> Path: + variant: str = "", search: list[Path] | None = None, allow_libs: list[str] | None = None) -> Path: if backend not in BACKEND_MATRIX: raise SystemExit(f"unknown backend {backend!r}") if backend != "cpu" and not archs: @@ -106,6 +109,7 @@ def build(src: Path, backend: str, version: str, target: str, out: Path, *, entr destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src / rel, destination) files.append({"path": rel, "sha256": sha256(destination), "bytes": destination.stat().st_size}) + files += _bundle_missing_libraries(staging, target, [f["path"] for f in files], search or [], allow_libs or []) manifest = {"schema_version": ec.SCHEMA_VERSION, "id": ec.COMPONENT_ID, "name": ec.COMPONENT_ID, "version": version, "platform": target, "backend": backend, "archs": list(archs), "min_driver": dict(min_driver or {}), "build_id": build_id or git_build_id(), @@ -127,6 +131,52 @@ def build(src: Path, backend: str, version: str, target: str, out: Path, *, entr return folder +def _default_search(target: str) -> list[Path]: + """Where a Windows build finds the redistributable DLLs its engine imports: the CUDA/HIP toolkits and PATH.""" + if not target.startswith("windows"): + return [] + found: list[Path] = [] + for var in ("CUDA_PATH", "HIP_PATH"): + root = os.environ.get(var) + if root: + found += [Path(root) / "bin" / "x64", Path(root) / "bin"] + found += [Path(x) for x in os.environ.get("PATH", "").split(os.pathsep) if x] + return [d for d in found if d.is_dir()] + + +def _bundle_missing_libraries(staging: Path, target: str, rels: list[str], search: list[Path], allow: list[str]) -> list[dict]: + """Every library the package's binaries import must be in the package, or belong to the OS or the GPU driver + (binary_deps.py). Windows builds copy a missing one from the search folders (the CUDA toolkit's bin/x64, PATH): the packager + runs on a PC that has the toolkit, the person's PC does not. Anything still missing refuses the package.""" + added: list[dict] = [] + roots = search or _default_search(target) + for _ in range(8): # a copied DLL can import more DLLs + missing = [(f, n) for f, n in binary_deps.uncovered(staging) if n.lower() not in {a.lower() for a in allow}] + if not missing: + return added + progressed = False + for _file, name in sorted(set(missing), key=lambda x: x[1].lower()): + if not target.startswith("windows"): + continue + hit = next((d / name for d in roots if (d / name).is_file()), None) + if hit is None: + hit = next((c for d in roots for c in d.glob("*") if c.name.lower() == name.lower() and c.is_file()), None) + if hit is None or (staging / hit.name).exists(): + continue + shutil.copy2(hit, staging / hit.name) + added.append({"path": hit.name, "sha256": sha256(staging / hit.name), "bytes": (staging / hit.name).stat().st_size}) + progressed = True + print(f"bundled {hit.name} (imported by the engine; from {hit.parent})") + if not progressed: + break + left = [(f, n) for f, n in binary_deps.uncovered(staging) if n.lower() not in {a.lower() for a in allow}] + if left: + lines = "\n".join(f" {f} needs {n}" for f, n in sorted(set(left))) + raise SystemExit("refusing to package: these libraries are neither bundled nor part of the OS or the GPU driver, so a clean PC could not " + f"start the engine (0xC0000135 / 'library not found'):\n{lines}\nGive --search or fix the build.") + return added + + def package_sha256(folder: Path) -> str: """One digest for the whole package: SHA-256 of the manifest file (it holds every file's hash).""" return sha256(folder / ec.MANIFEST) @@ -150,6 +200,10 @@ def main(argv: list[str] | None = None) -> int: ap.add_argument("--min-runtime", default=None) ap.add_argument("--notes", default="") ap.add_argument("--tree", action="store_true", help="every regular file under --src, recursively") + ap.add_argument("--search", action="append", default=[], type=Path, metavar="DIR", + help="folder to copy a missing imported DLL from (default on Windows: CUDA_PATH/bin/x64, HIP_PATH/bin, PATH)") + ap.add_argument("--allow-lib", action="append", default=[], metavar="NAME", + help="an imported library that really is provided by the target system (rare; named so the check passes)") ap.add_argument("--include", action="append", default=[], metavar="GLOB", help="more files, relative to --src") a = ap.parse_args(argv) if a.verify: @@ -159,6 +213,11 @@ def main(argv: list[str] | None = None) -> int: except ec.ComponentProblem as exc: print(f"{a.verify}: REFUSED: {exc}") return 1 + bad = binary_deps.uncovered(a.verify) + if bad: + for rel, name in bad: + print(f"{a.verify}: REFUSED: {rel} needs {name}, which is neither bundled nor an OS / GPU driver library") + return 1 print(f"{a.verify}: ok ({len(component.files)} files, manifest sha256 {package_sha256(a.verify)})") return 0 for needed in ("src", "backend", "version", "out"): @@ -173,7 +232,8 @@ def main(argv: list[str] | None = None) -> int: a.out.mkdir(parents=True, exist_ok=True) folder = build(a.src, a.backend, a.version, a.platform or host_platform(), a.out, entry=a.entrypoint, archs=tuple(a.arch), min_driver=drivers, build_id=a.build_id, min_runtime=a.min_runtime, - notes=a.notes, tree=a.tree, include=a.include, variant=a.variant) + notes=a.notes, tree=a.tree, include=a.include, variant=a.variant, + search=a.search, allow_libs=a.allow_lib) entries = [p for p in folder.rglob("*") if p.is_file()] total = sum(p.stat().st_size for p in entries) print(f"{folder} ({total / (1 << 20):.1f} MiB, {len(entries)} files, manifest sha256 {package_sha256(folder)})") diff --git a/tests/terminal/test_engine_deps.py b/tests/terminal/test_engine_deps.py new file mode 100644 index 00000000..66d6b4eb --- /dev/null +++ b/tests/terminal/test_engine_deps.py @@ -0,0 +1,124 @@ +"""An engine package must carry every library its binaries import, except the OS's and the GPU driver's. + +Tester report 2026-10-17: a clean Windows 11 PC failed with 0xC0000135 because strata.exe imports cublas64_13.dll and the package +did not hold it (the build PC had the CUDA Toolkit on PATH, which hid the problem). These tests build tiny real PE files, so they +run anywhere and need no GPU or toolkit.""" + +import os +import struct +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "packaging")) +import binary_deps # noqa: E402 +import package_engine # noqa: E402 + + +def make_pe(imports, delay=()): + """A minimal PE32+ file with a .idata section that imports the named DLLs (and delay-loads `delay`).""" + va, raw = 0x1000, 0x400 + body = bytearray() + descriptors = (len(imports) + 1) * 20 + delays = (len(delay) + 1) * 32 + names_at = descriptors + delays + name_rvas = [] + blob = bytearray() + for n in list(imports) + list(delay): + name_rvas.append(va + names_at + len(blob)) + blob += n.encode("ascii") + b"\0" + for i, _ in enumerate(imports): + body += struct.pack(" Date: Sat, 17 Oct 2026 19:02:17 +0200 Subject: [PATCH 3/9] App never adopts an older CLI install: own settings file for Control and the installer, explicit install folder, tests --- apps/host/server/control-runtime.mjs | 3 + apps/host/server/native-control.mjs | 10 ++-- apps/host/tests/packaged-control.test.mjs | 15 ++++- setup.py | 12 +++- strata_control/models.py | 6 +- tests/terminal/test_app_isolation.py | 68 +++++++++++++++++++++++ tools/strata_mcp.py | 2 + 7 files changed, 108 insertions(+), 8 deletions(-) create mode 100644 tests/terminal/test_app_isolation.py diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index 4f7fc610..6f352b54 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -82,6 +82,9 @@ export function controlEnvironment(control, { env = process.env, components = co ...next, PYTHONNOUSERSITE: '1', PYTHONUTF8: '1', PYTHONUNBUFFERED: '1', PYTHONIOENCODING: 'utf-8', STRATA_NO_ACQUIRE: '1', STRATA_COMPONENTS_DIR: components, + // The app's own settings file, beside its components: Control and the installer never read or write the file an older + // command-line Strata keeps in %APPDATA% / ~/.config (its list of Strata folders), so an old install is never adopted. + ...(components ? { STRATA_SETTINGS_FILE: env.STRATA_SETTINGS_FILE || join(dirname(components), 'app-settings.json') } : {}), ...(control?.dir ? { STRATA_CONTROL_DIR: control.dir } : {}), }; // Only the explicit update step (`strata update`) may acquire; every other Control process keeps the switch on. diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 196aa65a..8a3ce5e0 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -38,7 +38,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp /* In the packaged app the model catalog, the GPU probe and the install job are Control's bundled tools/strata_mcp.py and setup.py, run on Control's own Python in the installer's mode (STRATA_CONTROL_INSTALL: no pip, no engine, no compiler). The install only runs when the user clicks Download; starting and serving (control.start) keep STRATA_NO_ACQUIRE. */ - const defaultInstall=()=>join(dirname(componentsDirectory()),'install'); + const defaultInstall=()=>process.env.STRATA_INSTALL_DIR?resolve(process.env.STRATA_INSTALL_DIR):join(dirname(componentsDirectory()),'install'); let packagedInstall=null; const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.'; let defaultId=null,timer=null,closing=false,polling=false; @@ -63,7 +63,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp const next={...config,...(config.cwd!==undefined?{cwd:fix(config.cwd)}:{}),...(Array.isArray(config.args)?{args:config.args.map(fix)}:{})}; if(JSON.stringify(next)!==JSON.stringify(config)){try{writeModelConfig(path,next);}catch{/* read-only folder: the load reports it */}}}} function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,dataFolder,visionPrepared:!!cfg.vision,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} - function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} + function installRoot(){const found=[preferences.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} function python(){return resolvePython({repo:preferences.repo});} function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});} @@ -85,9 +85,9 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp async function controlTool(name){ if(name==='strata_status'){ for(const dir of [preferences.installDir,packagedInstall,installRoot()])repairControlPaths(dir); - let list=await control.installedModels({installDir:preferences.installDir&&existsSync(preferences.installDir)?preferences.installDir:null}); - if(!preferences.installDir&&!(list.models??[]).length){const own=installRoot();if(realpathSync(list.install_dir)!==own)list=await control.installedModels({installDir:own});} - if(!preferences.installDir&&list.install_dir&&![preferences.installDir,packagedInstall,installRoot()].some(d=>d&&resolve(d).toLowerCase()===resolve(list.install_dir).toLowerCase())){repairControlPaths(list.install_dir);list=await control.installedModels({installDir:list.install_dir});} + // Always the app's own install folder (or the one the person chose in Settings): Control is told explicitly, so it never falls + // back to an older command-line Strata's folder remembered in %APPDATA% (tester report 2026-10-17: logs landed in T:\Strata). + const list=await control.installedModels({installDir:installRoot()}); packagedInstall=list.install_dir; const engine=await control.engine(); const installer=await mcpCall('strata_status',{hardware:true}).catch(error=>({error:error.message})); diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjs index b4a98cc2..5677980a 100644 --- a/apps/host/tests/packaged-control.test.mjs +++ b/apps/host/tests/packaged-control.test.mjs @@ -89,6 +89,8 @@ function packagedFixture({ engineUsable = true, updater = null, repair = false } const root = mkdtempSync(join(tmpdir(), 'strata-packaged-test-')); const install = join(root, 'install'), data = join(root, 'data'); mkdirSync(install, { recursive: true }); + const earlierInstallEnv = process.env.STRATA_INSTALL_DIR; + process.env.STRATA_INSTALL_DIR = install; // the app's own install folder (the host always tells Control which one; it never falls back to an older CLI folder) const configs = ['iq2_xs', 'iq3_s'].map(id => { const path = join(install, `strata-${id}.json`); writeFileSync(path, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(install, 'tok'), args: ['--max-context', '32768'], model_name: `Qwen ${id}`, port: 8080 })); @@ -148,7 +150,7 @@ function packagedFixture({ engineUsable = true, updater = null, repair = false } }; const native = createNativeControl({ control, directory: data, spawnProcess, fetcher, requests: () => requests }); const others = () => spawned.filter(s => !String(s.args[0]).endsWith('strata_mcp.py')); - return { native, calls, saved, spawned, others, rpc, failStart: (v, times = Infinity) => { startFailure = v; startFailureLeft = times; }, catalog, hardware, install, root, cleanup: () => { rmSync(root, { recursive: true, force: true }); } }; + return { native, calls, saved, spawned, others, rpc, failStart: (v, times = Infinity) => { startFailure = v; startFailureLeft = times; }, catalog, hardware, install, root, cleanup: () => { if (earlierInstallEnv === undefined) delete process.env.STRATA_INSTALL_DIR; else process.env.STRATA_INSTALL_DIR = earlierInstallEnv; rmSync(root, { recursive: true, force: true }); } }; } const finish = async (native, id) => { for (let i = 0; i < 400; i++) { const job = native.state().jobs.find(j => j.id === id); if (job.state !== 'running') return job; await new Promise(r => setTimeout(r, 10)); } throw new Error('job did not finish'); }; @@ -521,3 +523,14 @@ test("preparing an adopted GGUF folder again never takes the folder's parent for assert.equal(sent.gguf_dir, join(own, 'models', 'IQ3_S')); } finally { await f.native.close(); f.cleanup(); } }); + +test('the app never adopts an older command-line install: Control is always told the app\'s own folder, and has its own settings file', async () => { + const f = packagedFixture(); + try { + await f.native.refresh(true); + const asked = f.calls.filter(c => c[0] === 'installedModels').map(c => c[1]); + assert.ok(asked.length > 0 && asked.every(dir => dir === f.install || (dir && dir.toLowerCase() === f.install.toLowerCase())), `Control was asked about ${JSON.stringify(asked)}`); + } finally { f.cleanup(); } + const env = controlEnvironment({ dir: '/c' }, { env: { APPDATA: '/old/appdata' }, components: join(tmpdir(), 'Strata', 'components') }); + assert.equal(env.STRATA_SETTINGS_FILE, join(tmpdir(), 'Strata', 'app-settings.json')); +}); diff --git a/setup.py b/setup.py index 60663fc3..9e11b8f1 100644 --- a/setup.py +++ b/setup.py @@ -4551,7 +4551,17 @@ def ram_ctx(model, ram, low_ram=False) -> int: return max(c for c in CONTEXTS if c <= 131072 or (c != 204800 and (ctx_ram_need(model, c, low_ram) or 0) <= ram)) +def app_settings_file() -> Path | None: + """The desktop app keeps its own settings file (STRATA_SETTINGS_FILE, in the app's data folder) and never reads or writes the + one an older command-line Strata uses, so an old install is never adopted or moved.""" + raw = os.environ.get("STRATA_SETTINGS_FILE") + return Path(raw) if raw else None + + def settings_path() -> Path: + own = app_settings_file() + if own is not None: + return own if WIN: return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "Strata" / "settings.json" return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "settings.json" @@ -4586,7 +4596,7 @@ def other_installs(settings: dict) -> list: """Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* folders next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`).""" cands = [Path(p) for p in settings.get("installs", [])] - for base in dict.fromkeys((home().parent, home().parent.parent)): + for base in dict.fromkeys(() if app_settings_file() else (home().parent, home().parent.parent)): try: for d in base.iterdir(): if d.is_dir() and d.name.lower().startswith("strata"): diff --git a/strata_control/models.py b/strata_control/models.py index eec730d6..c5daeab0 100644 --- a/strata_control/models.py +++ b/strata_control/models.py @@ -38,7 +38,11 @@ SUPPORTED_SELECTIONS = frozenset({"qwen/Q2_0", "qwen/IQ2_XS", "qwen/IQ3_XXS", "q def settings_path() -> Path: """The user's Strata settings file: the same place setup.py writes it (%APPDATA%\\Strata\\settings.json, or - $XDG_CONFIG_HOME/strata/settings.json).""" + $XDG_CONFIG_HOME/strata/settings.json). The desktop app sets STRATA_SETTINGS_FILE to a file of its own (in its data folder), so it + never reads an older command-line install's list of Strata folders.""" + own = os.environ.get("STRATA_SETTINGS_FILE") + if own: + return Path(own) if os.name == "nt": return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "Strata" / "settings.json" return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "settings.json" diff --git a/tests/terminal/test_app_isolation.py b/tests/terminal/test_app_isolation.py new file mode 100644 index 00000000..1c9f5baf --- /dev/null +++ b/tests/terminal/test_app_isolation.py @@ -0,0 +1,68 @@ +"""The desktop app never adopts an older command-line Strata install (tester report 2026-10-17: the app wrote +strata-gyro-gyro-s.log/.json into the tester's old T:\\Strata). The app points Control and the installer at a settings file of its +own (STRATA_SETTINGS_FILE); the shared %APPDATA% / ~/.config file with the old install's folders is not read.""" + +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +from strata_control import models # noqa: E402 +import setup as strata_setup # noqa: E402 + + +class AppIsolation(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + base = Path(self.dir.name) + self.old = base / "T-Strata" + self.old.mkdir() + (self.old / "strata-gyro-gyro-s.json").write_text(json.dumps({"exe": "strata.exe", "tokenizer": "t", "args": []})) + shared = base / "appdata" / "Strata" + shared.mkdir(parents=True) + (shared / "settings.json").write_text(json.dumps({"installs": [str(self.old)], "data_dir": str(base / "T-data")})) + (base / "xdg" / "strata").mkdir(parents=True) + (base / "xdg" / "strata" / "settings.json").write_text(json.dumps({"installs": [str(self.old)], "data_dir": str(base / "T-data")})) + self.app_data = base / "app" / "Strata" + self.app_data.mkdir(parents=True) + self.env = {"APPDATA": str(base / "appdata"), "XDG_CONFIG_HOME": str(base / "xdg")} + self.base = base + self.terminal = base / "terminal" + self.terminal.mkdir() + + def test_the_terminal_still_remembers_the_old_install(self): + with mock.patch.dict(os.environ, self.env), mock.patch.dict(os.environ, {}, clear=False), mock.patch.object(models, "ROOT", self.terminal): + os.environ.pop("STRATA_SETTINGS_FILE", None) + os.environ.pop("STRATA_INSTALL_DIR", None) + self.assertEqual(models.resolve_install(), (self.old.resolve(), "remembered")) + + def test_the_app_does_not(self): + env = {**self.env, "STRATA_SETTINGS_FILE": str(self.app_data / "app-settings.json")} + with mock.patch.dict(os.environ, env), mock.patch.object(models, "ROOT", self.terminal): + os.environ.pop("STRATA_INSTALL_DIR", None) + self.assertEqual(models.settings_path(), self.app_data / "app-settings.json") + self.assertEqual(models.remembered_installs(), []) + self.assertEqual(models.resolve_install(), (self.terminal, "default")) + self.assertEqual(strata_setup.settings_path(), self.app_data / "app-settings.json") + self.assertEqual(strata_setup.load_settings(), {}) + # the installer's own list of "other installs" has no sibling scan and no shared settings + self.assertEqual(strata_setup.other_installs(strata_setup.load_settings()), []) + + def test_saving_settings_goes_to_the_app_file_only(self): + env = {**self.env, "STRATA_SETTINGS_FILE": str(self.app_data / "app-settings.json")} + shared = self.base / "appdata" / "Strata" / "settings.json" + before = shared.read_bytes() + with mock.patch.dict(os.environ, env): + strata_setup.save_settings({"data_dir": str(self.app_data / "data")}) + self.assertEqual(shared.read_bytes(), before) + self.assertIn("data_dir", json.loads((self.app_data / "app-settings.json").read_text())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 93fb8f9b..a0eec205 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -483,6 +483,8 @@ class Strata: # ---- paths def settings_path(self) -> Path: + if os.environ.get("STRATA_SETTINGS_FILE"): + return Path(os.environ["STRATA_SETTINGS_FILE"]) if WIN: return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "Strata" / "settings.json" return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "settings.json" From d7347cdde6c6a0ab6dfba9a8c67a7d5c17c17115 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 17 Oct 2026 19:07:42 +0200 Subject: [PATCH 4/9] Start failures: plain, correct messages from the engine's exit code (missing DLL, bad DLL, crash, blocked, file missing); low memory only with evidence; no memory retry for non-memory failures --- apps/host/server/native-control.mjs | 3 ++- apps/host/server/native-resources.mjs | 7 +++++-- apps/host/src/lib/plain-errors.ts | 11 ++++++++++- apps/host/src/locales/de.json | 15 ++++++++++++++- apps/host/src/locales/en.json | 15 ++++++++++++++- apps/host/src/locales/es.json | 15 ++++++++++++++- apps/host/src/locales/ja.json | 15 ++++++++++++++- apps/host/src/locales/ko.json | 15 ++++++++++++++- apps/host/src/locales/pt.json | 15 ++++++++++++++- apps/host/src/locales/ru.json | 15 ++++++++++++++- apps/host/src/locales/zh.json | 15 ++++++++++++++- apps/host/tests/component-updates.test.mjs | 1 + apps/host/tests/parallel-default.test.mjs | 1 + apps/host/tests/plain-errors.test.mjs | 15 ++++++++++++--- strata_control/runtime.py | 4 +++- 15 files changed, 146 insertions(+), 16 deletions(-) diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 8a3ce5e0..f4b114c3 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -51,7 +51,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp const modelArena=id=>({arenaGb:(snapshot.catalog?.families??[]).flatMap(f=>f.sizes??[]).find(s=>s.id===id)?.experts_gb}); /* A start that ends with `server_exited` carries the engine's last log line with it; the app turns the code into words and keeps this text under "Details" (src/lib/plain-errors.ts). */ - function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail;return tail&&!text.includes(tail)?`${text}: ${tail}`:text;} + function exitCodeText(code){const n=Number(code);if(!Number.isFinite(n)||n===0)return '';const u=n<0?n+2**32:n;return u>=0x80000000?`exit code 0x${u.toString(16).toUpperCase().padStart(8,'0')}`:`exit code ${u}`;} + function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail,code=exitCodeText(error?.output?.engine_exit_code);const head=code&&!text.includes(code)?`${text} (${code})`:text;return tail&&!head.includes(tail)?`${head}: ${tail}`:head;} /* A run config the app's install job wrote names files inside the app's own Control folder (`cwd`, `--expert-profile`). When the app is reinstalled to another folder, or an update moves Control, those absolute paths point at nothing and every installed model breaks. At every read of the installed models, a path that ends up inside a folder called `control` that no longer diff --git a/apps/host/server/native-resources.mjs b/apps/host/server/native-resources.mjs index 519d020c..5dcf7baa 100644 --- a/apps/host/server/native-resources.mjs +++ b/apps/host/server/native-resources.mjs @@ -45,6 +45,9 @@ export function resourceSettings(config,hardware,profile,model={}){ technical line for Details. The caller tries once and never again, and does not save this config. */ export function saferStart(config,hardware,model,failure){ const text=String(failure??''); + // A start that died for a reason that is not memory (a missing or bad DLL, a crash, a blocked file) is not helped by a memory setting, and must not be called a memory failure. + if(/0xC0000135|0xC000007B|0xC0000142|0xC000001D|0xC0000005|0xC0000409|0xC0000022|error while loading shared libraries|cannot open shared object file|\bENOENT\b|exit code 127|exit code 139|illegal instruction/i.test(text))return null; + const ranOut=/out of memory|memory guard|\boom\b|\bkilled\b|exit code 137|cannot allocate|not enough memory|bad_alloc|insufficient memory/i.test(text),first=ranOut?'The first start ran out of memory':'The first start did not finish'; if(!/server_exited|exited before|died before|engine stopped|pinned-memory-exhausted|mapped staging|out of memory|memory guard|\bkilled\b/i.test(text))return null; const args=[...(config.args??[])],env={...(config.env??{})}; const ram=Number(hardware?.ram_gb)||0,arena=Number(model?.arenaGb)||0; @@ -61,10 +64,10 @@ export function saferStart(config,hardware,model,failure){ if(at>=0){ const next=Math.floor((Number(args[at+1])||0)*.7);if(next<8)return null; args[at+1]=String(next); - return {config:{...config,args},words:`The first start ran out of memory, so Strata started again and keeps less of the model in RAM (${next} GB); more of it is read from the SSD, which is slower.`,detail:`--resident-budget-gib ${next}`}; + return {config:{...config,args},words:`${first}, so Strata started again and keeps less of the model in RAM (${next} GB); more of it is read from the SSD, which is slower.`,detail:`--resident-budget-gib ${next}`}; } if(!(ram>0&&arena>0))return null; const budget=Math.max(8,Math.floor(ram*.5)-4);if(budget>=arena)return null; args.push('--resident-budget-gib',String(budget)); - return {config:{...config,args},words:`The first start ran out of memory, so Strata started again in low-memory mode: ${budget} GB of the model stays in RAM and the rest is read from the SSD. It is slower, but it should load.`,detail:`--resident-budget-gib ${budget}`}; + return {config:{...config,args},words:`${first}, so Strata started again in low-memory mode: ${budget} GB of the model stays in RAM and the rest is read from the SSD. It is slower, but it should load.`,detail:`--resident-budget-gib ${budget}`}; } diff --git a/apps/host/src/lib/plain-errors.ts b/apps/host/src/lib/plain-errors.ts index ecbed5e8..a08f28a3 100644 --- a/apps/host/src/lib/plain-errors.ts +++ b/apps/host/src/lib/plain-errors.ts @@ -17,7 +17,16 @@ const MEMORY_NEXT = 'Close other programs and try again, or choose “Leave 20% const RULES: Rule[] = [ { 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.' }, - { kind: 'memory', match: /server_exited|engine stopped|exited before|died before|out of memory|memory guard|\boom\b|killed/i, message: MEMORY, next: MEMORY_NEXT }, + // 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 there + // (2026-10-17: a missing DLL, 0xC0000135, was reported as "ran low on memory" and told the tester to free RAM). + { kind: 'dll-missing', match: /0xC0000135|3221225781|-1073741515|STATUS_DLL_NOT_FOUND|error while loading shared libraries|cannot open shared object file|Library not loaded/i, message: 'The engine could not start because one of its program files is missing on this computer.', next: 'Reinstall Strata (the installer includes it) or press Repair. Closing other programs will not help.' }, + { kind: 'dll-bad', match: /0xC000007B|3221225595|-1073741701|0xC0000142|3221225794|0xC000012F|bad image/i, message: 'The engine could not start because one of its program files does not fit this computer or is damaged.', next: 'Reinstall Strata or press Repair. If it keeps happening, update your graphics driver.' }, + { kind: 'cpu-unsupported', match: /0xC000001D|3221225501|illegal instruction|SIGILL/i, message: 'The engine needs a newer processor feature than this computer has.', next: 'Open Details and share them when you ask for help.' }, + { kind: 'crash', match: /0xC0000005|3221225477|0xC0000409|3221226505|segmentation fault|SIGSEGV|exit code 139/i, message: 'The engine crashed while starting.', next: 'Restart the PC and try again. If it keeps happening, update your graphics driver and open Details when you ask for help.' }, + { kind: 'blocked', match: /0xC0000022|3221225506|\bEACCES\b|\bEPERM\b|operation not permitted/i, message: 'Windows or your security software stopped the engine from starting.', next: 'Allow Strata in your security software, then try again.' }, + { kind: 'file-missing', match: /\bENOENT\b|no such file or directory|cannot find the (?:file|path)|0x80070002|exit code 127|file not found/i, message: 'Strata could not find a file it needs to start the engine.', next: 'Reinstall Strata or press Repair.' }, + { kind: 'memory', match: /out of memory|memory guard|\boom\b|\bkilled\b|exit code 137|cannot allocate memory|not enough memory|bad_alloc|pinned-memory-exhausted|mapped staging|cudaErrorMemoryAllocation|insufficient memory/i, message: MEMORY, next: MEMORY_NEXT }, + { kind: 'start-failed', match: /server_exited|engine stopped|exited before|died before/i, message: 'The model stopped while starting.', next: 'Try again. If it keeps happening, open Details and share them when you ask for help.' }, { kind: 'slow-load', match: /loading took more than/i, message: 'Loading is taking too long.', next: 'The PC may be short on memory. Close other programs and try again.' }, { kind: 'engine-missing', match: /no engine for this pc|engine component|never downloads an engine|engine .*not installed|no strata engine/i, message: 'Strata’s engine for this computer isn’t installed yet.', next: 'It is added when you download a model. Download your model again to add it.' }, { kind: 'network', match: /cannot reach|could not reach|can't reach|timed out|econn|enotfound|getaddrinfo|urlopen|connection (?:reset|refused|aborted)|network is unreachable/i, message: 'The download couldn’t reach the internet.', next: 'Check your connection, then press Resume download.' }, diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 423ad693..c1e525bb 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -3125,5 +3125,18 @@ "s3129": "Das war ein Beispieldurchlauf, während die App ihren Host nicht erreichen konnte.", "s3130": "Startet noch", "s3131": "Time-skip braucht eine fertig gestartete App. Versuche es gleich noch einmal.", - "s3132": "Arbeitet an einer Kopie deiner Dateien." + "s3132": "Arbeitet an einer Kopie deiner Dateien.", + "s3133": "Die Engine konnte nicht starten, weil auf diesem Computer eine ihrer Programmdateien fehlt.", + "s3134": "Installiere Strata neu (das Installationsprogramm enthält die Datei) oder drücke auf Reparieren. Andere Programme zu schließen hilft nicht.", + "s3135": "Die Engine konnte nicht starten, weil eine ihrer Programmdateien nicht zu diesem Computer passt oder beschädigt ist.", + "s3136": "Installiere Strata neu oder drücke auf Reparieren. Wenn es weiter passiert, aktualisiere den Grafiktreiber.", + "s3137": "Die Engine braucht eine neuere Prozessorfunktion, als dieser Computer hat.", + "s3138": "Öffne die Details und teile sie mit, wenn du um Hilfe bittest.", + "s3139": "Die Engine ist beim Starten abgestürzt.", + "s3140": "Starte den Computer neu und versuche es erneut. Wenn es weiter passiert, aktualisiere den Grafiktreiber und öffne die Details, wenn du um Hilfe bittest.", + "s3141": "Windows oder deine Sicherheitssoftware hat den Start der Engine verhindert.", + "s3142": "Erlaube Strata in deiner Sicherheitssoftware und versuche es dann erneut.", + "s3143": "Strata hat eine Datei nicht gefunden, die zum Starten der Engine nötig ist.", + "s3144": "Installiere Strata neu oder drücke auf Reparieren.", + "s3145": "Das Modell wurde beim Starten angehalten." } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index 6bea2920..33a2d9c5 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -3125,5 +3125,18 @@ "s3129": "This was a sample run made while the app could not reach its host.", "s3130": "Still starting up", "s3131": "Time-skip needs the app to finish starting. Try again in a moment.", - "s3132": "Working on a copy of your files." + "s3132": "Working on a copy of your files.", + "s3133": "The engine could not start because one of its program files is missing on this computer.", + "s3134": "Reinstall Strata (the installer includes it) or press Repair. Closing other programs will not help.", + "s3135": "The engine could not start because one of its program files does not fit this computer or is damaged.", + "s3136": "Reinstall Strata or press Repair. If it keeps happening, update your graphics driver.", + "s3137": "The engine needs a newer processor feature than this computer has.", + "s3138": "Open Details and share them when you ask for help.", + "s3139": "The engine crashed while starting.", + "s3140": "Restart the PC and try again. If it keeps happening, update your graphics driver and open Details when you ask for help.", + "s3141": "Windows or your security software stopped the engine from starting.", + "s3142": "Allow Strata in your security software, then try again.", + "s3143": "Strata could not find a file it needs to start the engine.", + "s3144": "Reinstall Strata or press Repair.", + "s3145": "The model stopped while starting." } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index 028e39a7..78cd5092 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -3125,5 +3125,18 @@ "s3129": "Esto fue una ejecución de ejemplo hecha cuando la app no podía conectar con su host.", "s3130": "Todavía arrancando", "s3131": "Time-skip necesita que la app termine de arrancar. Inténtalo de nuevo en un momento.", - "s3132": "Trabajando en una copia de tus archivos." + "s3132": "Trabajando en una copia de tus archivos.", + "s3133": "El motor no pudo iniciarse porque falta uno de sus archivos de programa en este equipo.", + "s3134": "Reinstala Strata (el instalador lo incluye) o pulsa Reparar. Cerrar otros programas no ayudará.", + "s3135": "El motor no pudo iniciarse porque uno de sus archivos de programa no es compatible con este equipo o está dañado.", + "s3136": "Reinstala Strata o pulsa Reparar. Si sigue pasando, actualiza el controlador de la tarjeta gráfica.", + "s3137": "El motor necesita una función de procesador más reciente que la de este equipo.", + "s3138": "Abre Detalles y compártelos cuando pidas ayuda.", + "s3139": "El motor se bloqueó al iniciarse.", + "s3140": "Reinicia el equipo e inténtalo de nuevo. Si sigue pasando, actualiza el controlador de la tarjeta gráfica y abre Detalles cuando pidas ayuda.", + "s3141": "Windows o tu software de seguridad impidió que el motor se iniciara.", + "s3142": "Permite Strata en tu software de seguridad y vuelve a intentarlo.", + "s3143": "Strata no encontró un archivo que necesita para iniciar el motor.", + "s3144": "Reinstala Strata o pulsa Reparar.", + "s3145": "El modelo se detuvo al iniciarse." } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index 5fbbc1ed..fa3a3d14 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3125,5 +3125,18 @@ "s3129": "これは、アプリがホストに接続できなかったときに作られたサンプル実行です。", "s3130": "まだ起動中です", "s3131": "Time-skip を使うには、アプリの起動が終わっている必要があります。少し待ってからもう一度お試しください。", - "s3132": "ファイルのコピーで作業しています。" + "s3132": "ファイルのコピーで作業しています。", + "s3133": "このパソコンでエンジンのプログラムファイルが1つ見つからないため、エンジンを起動できませんでした。", + "s3134": "Strata を再インストールするか(インストーラーに含まれています)、「修復」を押してください。他のプログラムを閉じても解決しません。", + "s3135": "エンジンのプログラムファイルの1つがこのパソコンに合っていないか、破損しているため、起動できませんでした。", + "s3136": "Strata を再インストールするか「修復」を押してください。それでも直らない場合は、グラフィックドライバーを更新してください。", + "s3137": "エンジンには、このパソコンのプロセッサにない新しい機能が必要です。", + "s3138": "「詳細」を開き、ヘルプを求めるときに共有してください。", + "s3139": "エンジンの起動中にクラッシュしました。", + "s3140": "パソコンを再起動してもう一度お試しください。それでも直らない場合は、グラフィックドライバーを更新し、ヘルプを求めるときに「詳細」を開いてください。", + "s3141": "Windows またはセキュリティソフトがエンジンの起動を止めました。", + "s3142": "セキュリティソフトで Strata を許可してから、もう一度お試しください。", + "s3143": "エンジンの起動に必要なファイルが Strata に見つかりませんでした。", + "s3144": "Strata を再インストールするか「修復」を押してください。", + "s3145": "モデルの起動中に停止しました。" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index bfd95bc6..64913883 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3125,5 +3125,18 @@ "s3129": "앱이 호스트에 연결할 수 없을 때 만들어진 예시 실행입니다.", "s3130": "아직 시작하는 중입니다", "s3131": "Time-skip을 쓰려면 앱이 완전히 시작되어야 합니다. 잠시 후 다시 시도해 주세요.", - "s3132": "파일 사본으로 작업하고 있습니다." + "s3132": "파일 사본으로 작업하고 있습니다.", + "s3133": "이 컴퓨터에 엔진의 프로그램 파일 하나가 없어서 엔진을 시작하지 못했습니다.", + "s3134": "Strata를 다시 설치하거나(설치 프로그램에 포함되어 있습니다) '복구'를 누르세요. 다른 프로그램을 닫아도 도움이 되지 않습니다.", + "s3135": "엔진의 프로그램 파일 하나가 이 컴퓨터와 맞지 않거나 손상되어 엔진을 시작하지 못했습니다.", + "s3136": "Strata를 다시 설치하거나 '복구'를 누르세요. 계속되면 그래픽 드라이버를 업데이트하세요.", + "s3137": "엔진에는 이 컴퓨터의 프로세서에 없는 더 새로운 기능이 필요합니다.", + "s3138": "'세부 정보'를 열어 도움을 요청할 때 함께 공유하세요.", + "s3139": "엔진이 시작하는 중에 충돌했습니다.", + "s3140": "PC를 다시 시작한 뒤 다시 시도하세요. 계속되면 그래픽 드라이버를 업데이트하고, 도움을 요청할 때 '세부 정보'를 여세요.", + "s3141": "Windows 또는 보안 소프트웨어가 엔진 시작을 막았습니다.", + "s3142": "보안 소프트웨어에서 Strata를 허용한 뒤 다시 시도하세요.", + "s3143": "엔진을 시작하는 데 필요한 파일을 Strata가 찾지 못했습니다.", + "s3144": "Strata를 다시 설치하거나 '복구'를 누르세요.", + "s3145": "모델이 시작하는 중에 멈췄습니다." } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 0ecef265..d088dd87 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -3125,5 +3125,18 @@ "s3129": "Esta foi uma execução de exemplo feita quando o app não conseguia alcançar o host.", "s3130": "Ainda iniciando", "s3131": "O Time-skip precisa que o app termine de iniciar. Tente de novo em instantes.", - "s3132": "Trabalhando em uma cópia dos seus arquivos." + "s3132": "Trabalhando em uma cópia dos seus arquivos.", + "s3133": "O motor não pôde iniciar porque falta um dos seus arquivos de programa neste computador.", + "s3134": "Reinstale o Strata (o instalador o inclui) ou clique em Reparar. Fechar outros programas não ajuda.", + "s3135": "O motor não pôde iniciar porque um dos seus arquivos de programa não serve para este computador ou está danificado.", + "s3136": "Reinstale o Strata ou clique em Reparar. Se continuar acontecendo, atualize o driver da placa de vídeo.", + "s3137": "O motor precisa de um recurso de processador mais novo do que o deste computador.", + "s3138": "Abra os Detalhes e compartilhe-os ao pedir ajuda.", + "s3139": "O motor travou ao iniciar.", + "s3140": "Reinicie o computador e tente de novo. Se continuar acontecendo, atualize o driver da placa de vídeo e abra os Detalhes ao pedir ajuda.", + "s3141": "O Windows ou o seu software de segurança impediu o motor de iniciar.", + "s3142": "Permita o Strata no seu software de segurança e tente de novo.", + "s3143": "O Strata não encontrou um arquivo de que precisa para iniciar o motor.", + "s3144": "Reinstale o Strata ou clique em Reparar.", + "s3145": "O modelo parou ao iniciar." } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index f2d6266c..7659e6cd 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3125,5 +3125,18 @@ "s3129": "Это был пробный запуск, сделанный, когда приложение не могло связаться со своим хостом.", "s3130": "Приложение ещё запускается", "s3131": "Для Time-skip приложение должно полностью запуститься. Повторите попытку через минуту.", - "s3132": "Работаю над копией ваших файлов." + "s3132": "Работаю над копией ваших файлов.", + "s3133": "Движок не удалось запустить: на этом компьютере отсутствует один из его программных файлов.", + "s3134": "Переустановите Strata (установщик включает этот файл) или нажмите «Восстановить». Закрытие других программ не поможет.", + "s3135": "Движок не удалось запустить: один из его программных файлов не подходит этому компьютеру или повреждён.", + "s3136": "Переустановите Strata или нажмите «Восстановить». Если это повторяется, обновите драйвер видеокарты.", + "s3137": "Движку нужна более новая функция процессора, чем есть у этого компьютера.", + "s3138": "Откройте «Подробности» и приложите их, когда будете просить о помощи.", + "s3139": "Движок аварийно завершился при запуске.", + "s3140": "Перезагрузите компьютер и попробуйте снова. Если это повторяется, обновите драйвер видеокарты и откройте «Подробности», когда будете просить о помощи.", + "s3141": "Windows или ваша защитная программа не дала движку запуститься.", + "s3142": "Разрешите Strata в защитной программе и попробуйте снова.", + "s3143": "Strata не нашла файл, нужный для запуска движка.", + "s3144": "Переустановите Strata или нажмите «Восстановить».", + "s3145": "Модель остановилась при запуске." } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index 17d7c365..48007894 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3125,5 +3125,18 @@ "s3129": "这是应用无法连接主机时生成的示例运行。", "s3130": "仍在启动", "s3131": "Time-skip 需要应用先完成启动。请稍后再试。", - "s3132": "正在处理你的文件副本。" + "s3132": "正在处理你的文件副本。", + "s3133": "引擎无法启动,因为这台电脑上缺少它的一个程序文件。", + "s3134": "请重新安装 Strata(安装程序包含该文件)或点击“修复”。关闭其他程序没有帮助。", + "s3135": "引擎无法启动,因为它的某个程序文件与这台电脑不匹配或已损坏。", + "s3136": "请重新安装 Strata 或点击“修复”。如果问题仍然出现,请更新显卡驱动。", + "s3137": "引擎需要这台电脑的处理器所没有的较新功能。", + "s3138": "请打开“详细信息”,并在求助时一并提供。", + "s3139": "引擎在启动时崩溃了。", + "s3140": "请重启电脑后重试。如果问题仍然出现,请更新显卡驱动,并在求助时打开“详细信息”。", + "s3141": "Windows 或您的安全软件阻止了引擎启动。", + "s3142": "请在安全软件中允许 Strata,然后重试。", + "s3143": "Strata 找不到启动引擎所需的文件。", + "s3144": "请重新安装 Strata 或点击“修复”。", + "s3145": "模型在启动时停止了。" } diff --git a/apps/host/tests/component-updates.test.mjs b/apps/host/tests/component-updates.test.mjs index 86eaaaea..d0d3c3f8 100644 --- a/apps/host/tests/component-updates.test.mjs +++ b/apps/host/tests/component-updates.test.mjs @@ -164,6 +164,7 @@ function fixture({ withApp = false, update } = {}) { const root = mkdtempSync(join(tmpdir(), 'strata-update-ops-')); const install = join(root, 'install'), data = join(root, 'data'); mkdirSync(install, { recursive: true }); + process.env.STRATA_INSTALL_DIR = install; // the app's own install folder: the host always names it to Control const config = join(install, 'strata-iq2_xs.json'); writeFileSync(config, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(install, 'tok'), args: ['--max-context', '32768'], model_name: 'Qwen', port: 8080 })); const calls = []; diff --git a/apps/host/tests/parallel-default.test.mjs b/apps/host/tests/parallel-default.test.mjs index 79a2cafe..0253c010 100644 --- a/apps/host/tests/parallel-default.test.mjs +++ b/apps/host/tests/parallel-default.test.mjs @@ -92,6 +92,7 @@ function fixture({ failStarts = 0, config = {} } = {}) { const root = mkdtempSync(join(tmpdir(), 'strata-par-test-')); const install = join(root, 'install'), data = join(root, 'data'); mkdirSync(install, { recursive: true }); + process.env.STRATA_INSTALL_DIR = install; // the app's own install folder: the host always names it to Control const path = join(install, 'strata-iq3_s.json'); writeFileSync(path, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(install, 'tok'), args: ['--max-context', '32768', '--mtp', '/m', '--spec', '4'], model_name: 'Qwen iq3_s', port: 8080, ...config })); const saved = []; const calls = []; diff --git a/apps/host/tests/plain-errors.test.mjs b/apps/host/tests/plain-errors.test.mjs index fbb9c840..b77a8de1 100644 --- a/apps/host/tests/plain-errors.test.mjs +++ b/apps/host/tests/plain-errors.test.mjs @@ -9,9 +9,16 @@ const built = await build({ stdin: { contents: "export * from './src/lib/plain-e const { plainFailure, plainFailureText, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`); const cases = [ - ['server_exited', 'memory', /ran low on memory/], + ['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/], + ['server_exited (exit code 0xC0000005)', 'crash', /crashed while starting/], + ['server_exited (exit code 0xC000001D)', 'cpu-unsupported', /newer processor feature/], + ['spawn C:/x/strata.exe ENOENT', 'file-missing', /could not find a file/], + ['server_exited (exit code 0xC0000022)', 'blocked', /security software stopped/], ['server_exited: memory guard: 5.1 GiB of RAM free is under the 6 GiB limit', 'memory', /ran low on memory/], - ['Engine stopped (exit 3). Open diagnostics or reload.', 'memory', /ran low on memory/], + ['server_exited (exit code 137): Killed', 'memory', /ran low on memory/], + ['Engine stopped (exit 3). Open diagnostics or reload.', 'start-failed', /model stopped while starting\./], ['Loading took more than five minutes. Check the engine log and free memory.', 'slow-load', /taking too long/], ['No engine for this PC was found in C:/x/components: the component folder holds no engine package. The app never downloads an engine while it starts or serves.', 'engine-missing', /engine for this computer isn’t installed yet/], ['cannot reach huggingface.co ()', 'network', /couldn’t reach the internet/], @@ -30,7 +37,7 @@ for (const [raw, kind, message] of cases) { assert.match(f.message, message); assert.ok(f.next, 'a next step'); assert.equal(f.detail, raw.trim(), 'the original text stays for Details'); - assert.doesNotMatch(f.message, /server_exited|exit \d|component-missing|Traceback/); + assert.doesNotMatch(f.message, /server_exited|exit \d|component-missing|Traceback|0x[0-9A-F]{8}/); }); } @@ -53,5 +60,7 @@ test('every plain message and next step is translated in all eight languages', ( } setTranslationLanguage('de'); assert.notEqual(plainFailureText('server_exited').message, plainFailure('server_exited').message); + // a missing DLL is never described as low memory + assert.doesNotMatch(plainFailure('server_exited (exit code 0xC0000135)').message + plainFailure('server_exited (exit code 0xC0000135)').next, /memory|Leave 20/i); setTranslationLanguage('en'); }); diff --git a/strata_control/runtime.py b/strata_control/runtime.py index a5837537..c88a9455 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -823,7 +823,9 @@ class Host: return {**base, "ok": False, "state": "failed", "error": self.last_error, "exit_code": 6} return {**base, "state": "stopped"} if child.poll() is not None: - return {**base, "ok": False, "state": "failed", "exit_code": child.returncode, + # engine_exit_code: how the engine process ended (Windows: 0xC0000135 = a DLL was not found); `exit_code` is + # Control's own and the start command overwrites it with 6, so the engine's code travels under its own name. + return {**base, "ok": False, "state": "failed", "exit_code": child.returncode, "engine_exit_code": child.returncode, "error": self.last_error or "server_exited", "log_tail": self._log_tail()} if self.ready_path is not None: try: From d85bb21c6b03cfaa3c31e1f2cbdfd2583857ee45 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 17 Oct 2026 19:11:09 +0200 Subject: [PATCH 5/9] Linux: programs that are not Strata's own get the AppImage's original environment; folder chooser tries zenity, kdialog, portal and never fails silently --- apps/desktop/scripts/repack-appimage.sh | 8 ++ apps/host/server/agent/harness-runtime.mjs | 5 +- apps/host/server/artifacts.mjs | 3 +- apps/host/server/chat-files.mjs | 4 +- apps/host/server/external-env.mjs | 71 +++++++++++++ apps/host/server/folder-dialog.mjs | 87 ++++++++++++++-- apps/host/server/index.mjs | 8 +- apps/host/tests/external-env.test.mjs | 116 +++++++++++++++++++++ 8 files changed, 288 insertions(+), 14 deletions(-) create mode 100644 apps/host/server/external-env.mjs create mode 100644 apps/host/tests/external-env.test.mjs diff --git a/apps/desktop/scripts/repack-appimage.sh b/apps/desktop/scripts/repack-appimage.sh index c0fe4d8a..d7b36c14 100755 --- a/apps/desktop/scripts/repack-appimage.sh +++ b/apps/desktop/scripts/repack-appimage.sh @@ -49,6 +49,14 @@ for d in control harness node engine-bundle; do [ -d "$RES/$d" ] || continue rsync -aL --checksum --delete --exclude .gitignore "$RES/$d/" "$LIB/$d/" done +# The launcher records the environment the AppImage was started from, before its own hooks add the AppImage's libraries and GTK/GIO +# settings (LD_LIBRARY_PATH, GTK_*, XDG_DATA_DIRS ...). The host gives it back to every program that is not Strata's own (zenity, +# kdialog, xdg-open, the assistant's shell): apps/host/server/external-env.mjs. Without it a system program loads the AppImage's libssl +# and dies ("OPENSSL_3.2.0 not found"). The line goes right after `this_dir=...`, ahead of every hook. +if ! grep -q STRATA_ORIGINAL_ENV "$WORK/AppDir/AppRun"; then + sed -i '/^this_dir=/a # Strata: the environment this AppImage was started from (given back to programs that are not Strata'"'"'s own)\nexport STRATA_ORIGINAL_ENV="$(env -0 | base64 -w0)"' "$WORK/AppDir/AppRun" + grep -q STRATA_ORIGINAL_ENV "$WORK/AppDir/AppRun" || { echo "could not add the environment record to AppRun" >&2; exit 1; } +fi mksquashfs "$WORK/AppDir" "$WORK/app.squashfs" -root-owned -noappend -comp zstd -b 131072 -no-progress >/dev/null head -c "$OFFSET" "$IN" > "$OUT" cat "$WORK/app.squashfs" >> "$OUT" diff --git a/apps/host/server/agent/harness-runtime.mjs b/apps/host/server/agent/harness-runtime.mjs index 4a1b0d8b..5093e54c 100644 --- a/apps/host/server/agent/harness-runtime.mjs +++ b/apps/host/server/agent/harness-runtime.mjs @@ -12,6 +12,7 @@ import { spawn, spawnSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; +import { externalEnvironment } from '../external-env.mjs'; const URL_PATTERN = /http:\/\/127\.0\.0\.1:(\d+)\/\?token=([A-Za-z0-9_-]+)/; @@ -23,7 +24,9 @@ const KEEP = /^(PATH|PATHEXT|SYSTEMROOT|WINDIR|COMSPEC|TEMP|TMP|TMPDIR|HOME|USER /** The environment the agent gets: a filtered copy of the host's, plus exactly the names passed in `extra`. */ export function agentEnvironment(base = process.env, extra = {}) { const out = {}; - for (const [k, v] of Object.entries(base)) { + // The shell and tools the assistant runs for the person are the person's own programs: they get the environment the AppImage was + // started from, never Strata's bundled libraries and GTK/GIO settings (external-env.mjs). Outside an AppImage this is `base`. + for (const [k, v] of Object.entries(externalEnvironment(base))) { if (v === undefined || !KEEP.test(k) || SECRET_NAME.test(k)) continue; out[k] = v; } diff --git a/apps/host/server/artifacts.mjs b/apps/host/server/artifacts.mjs index fc8e9cb7..ac42c728 100644 --- a/apps/host/server/artifacts.mjs +++ b/apps/host/server/artifacts.mjs @@ -2,7 +2,8 @@ import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; import { mkdir, mkdtemp, realpath, stat, writeFile } from 'node:fs/promises'; import { basename, dirname, extname, join, resolve, sep } from 'node:path'; -const run=promisify(execFile); +import { externalEnvironment } from './external-env.mjs'; +const run=(command,args)=>promisify(execFile)(command,args,{env:externalEnvironment()}); // xdg-open and the apps it starts: the environment the AppImage was started from const extensions=new Set(['.md','.txt','.pdf','.html','.htm','.png','.jpg','.jpeg','.webp','.gif','.svg','.csv','.ts','.tsx','.js','.jsx','.py','.json','.css','.rs','.go','.sh','.mp4','.webm']); export async function openArtifact(body,{examplesDir,previewsDir,platform=process.platform,launch=run}) { if(!['open','reveal'].includes(body.action))throw new Error('Choose Open or Show in file explorer.'); diff --git a/apps/host/server/chat-files.mjs b/apps/host/server/chat-files.mjs index 1c182804..eb6320b1 100644 --- a/apps/host/server/chat-files.mjs +++ b/apps/host/server/chat-files.mjs @@ -12,6 +12,7 @@ import { spawn } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, realpathSync } from 'node:fs'; import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path'; import { pathToFileURL } from 'node:url'; +import { externalEnvironment } from './external-env.mjs'; /** A folder no chat may use as its project: the top of a drive, or the system's own folders. */ export function refusedFolder(dir) { @@ -74,7 +75,8 @@ export function resolveChatFile(root, rawPath) { */ export function launch(command, args, { recorder = null } = {}) { if (process.env.STRATA_OPENER === 'record' || recorder) { (recorder ?? launch.recorded).push([command, ...args]); return; } - const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: false }); + // xdg-open and the browser it starts are the system's programs: they get the environment the AppImage was started from, not Strata's libraries. + const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: false, env: externalEnvironment() }); child.on('error', () => {}); child.unref(); } diff --git a/apps/host/server/external-env.mjs b/apps/host/server/external-env.mjs new file mode 100644 index 00000000..169191ae --- /dev/null +++ b/apps/host/server/external-env.mjs @@ -0,0 +1,71 @@ +/** + * The environment for programs that are NOT part of Strata: the folder chooser (zenity, kdialog, gdbus), xdg-open and the browser it + * starts, and the shell and tools the coding assistant runs for the person. + * + * Why: the Linux AppImage starts Strata with its own libraries and settings in the environment (LD_LIBRARY_PATH, GTK_*, GIO_*, + * GSETTINGS_SCHEMA_DIR, XDG_DATA_DIRS, PYTHONHOME, ...). A system program that inherits them loads Strata's copies of libssl, GTK and + * GLib instead of its own and dies (tester report 2026-10-17: zenity "libssl.so.3: version OPENSSL_3.2.0 not found", so the folder + * picker did nothing). Programs Strata ships itself (its Python, Node and engine) keep the environment they were built for; everything + * else gets the environment the AppImage was started from. + * + * The AppImage's launcher records that original environment in STRATA_ORIGINAL_ENV (repack-appimage.sh adds the hook). An older + * AppImage without the record is cleaned instead: every variable that points into the AppImage's own folder is dropped, and its + * folders are removed from the path lists. + */ +const RECORD = 'STRATA_ORIGINAL_ENV'; + +/** Variables the AppImage tooling sets only for itself; never meant for another program. */ +const APPIMAGE_ONLY = [ + 'APPDIR', 'APPIMAGE', 'ARGV0', 'OWD', 'APPIMAGE_SILENT_INSTALL', 'APPIMAGE_EXTRACT_AND_RUN', + 'GTK_DATA_PREFIX', 'GTK_EXE_PREFIX', 'GTK_PATH', 'GTK_IM_MODULE_FILE', 'GTK_THEME', 'GDK_PIXBUF_MODULE_FILE', 'GDK_PIXBUF_MODULEDIR', + 'GSETTINGS_SCHEMA_DIR', 'GI_TYPELIB_PATH', 'GIO_MODULE_DIR', 'GIO_EXTRA_MODULES', + 'GST_REGISTRY_REUSE_PLUGIN_SCANNER', 'GST_PLUGIN_SYSTEM_PATH_1_0', 'GST_PLUGIN_PATH_1_0', 'GST_PLUGIN_SCANNER_1_0', 'GST_PTP_HELPER_1_0', + 'WEBKIT_EXEC_PATH', 'WEBKIT_INJECTED_BUNDLE_PATH', 'STRATA_ORIGINAL_ENV', 'STRATA_APPDIR', +]; +/** Lists of folders: the AppImage prepends its own; only its entries are removed. */ +const PATH_LISTS = ['PATH', 'XDG_DATA_DIRS', 'XDG_CONFIG_DIRS', 'LD_LIBRARY_PATH', 'LD_PRELOAD', 'LIBRARY_PATH', 'PYTHONPATH', 'PYTHONHOME', 'PERLLIB', 'PERL5LIB', 'QT_PLUGIN_PATH', 'QML2_IMPORT_PATH', 'GST_PLUGIN_PATH', 'GTK_PATH', 'GIO_MODULE_DIR']; + +/** The environment the program was started from, decoded from the launcher's record, or null when there is none. */ +export function recordedOriginal(env = process.env) { + const raw = env[RECORD]; + if (!raw) return null; + try { + const text = Buffer.from(raw, 'base64').toString('utf8'); + const out = {}; + for (const entry of text.split('\0')) { + const at = entry.indexOf('='); + if (at > 0) out[entry.slice(0, at)] = entry.slice(at + 1); + } + return Object.keys(out).length ? out : null; + } catch { return null; } +} + +/** `env` with everything that belongs to a running AppImage removed (no record needed). */ +export function withoutAppImage(env = process.env) { + const dir = env.APPDIR || ''; + const out = { ...env }; + const inside = value => !!dir && (value === dir || value.startsWith(`${dir}/`) || value.startsWith(`${dir}//`)); + for (const name of APPIMAGE_ONLY) delete out[name]; + if (dir) { + for (const name of Object.keys(out)) if (/^(GTK|GDK|GIO|GST|GI_|GSETTINGS|WEBKIT)/.test(name) && typeof out[name] === 'string' && out[name].includes(dir)) delete out[name]; + for (const name of PATH_LISTS) { + if (typeof out[name] !== 'string') continue; + const kept = out[name].split(':').filter(part => part && !inside(part)); + if (kept.length) out[name] = kept.join(':'); else delete out[name]; + } + } + return out; +} + +/** True when this process was started from an AppImage. */ +export const insideAppImage = (env = process.env) => !!(env.APPIMAGE || env.APPDIR); + +/** + * The environment for an external program (see the top of this file). Outside an AppImage it is `env` unchanged. + * `extra` is added last (a variable the caller really means to pass). + */ +export function externalEnvironment(env = process.env, extra = {}) { + if (!insideAppImage(env) && !env[RECORD]) return { ...env, ...extra }; + const original = recordedOriginal(env); + return { ...(original ?? withoutAppImage(env)), ...extra }; +} diff --git a/apps/host/server/folder-dialog.mjs b/apps/host/server/folder-dialog.mjs index 1748373b..ea81f95a 100644 --- a/apps/host/server/folder-dialog.mjs +++ b/apps/host/server/folder-dialog.mjs @@ -2,11 +2,13 @@ * 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. + * Linux zenity, then kdialog, then the desktop portal (gdbus), all with the environment the AppImage was started from + * Where no dialog works the caller gets { unavailable: true } and the app shows a plain message and a field for the path. */ +import { spawn } from 'node:child_process'; import { stat } from 'node:fs/promises'; import { exec } from './util.mjs'; +import { externalEnvironment } from './external-env.mjs'; const MAC_SCRIPT = prompt => `POSIX path of (choose folder with prompt "${prompt.replace(/["\\]/g, '')}")`; @@ -44,7 +46,7 @@ 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 } = {}) { +export async function chooseFolder(prompt, { platform = process.platform, run = exec, portal = portalFolder } = {}) { if (platform === 'darwin') { try { const { stdout } = await run('osascript', ['-e', MAC_SCRIPT(prompt)]); @@ -63,25 +65,96 @@ export async function chooseFolder(prompt, { platform = process.platform, run = throw new Error('The folder chooser could not open.'); } } + return chooseLinuxFolder(prompt, { run, portal }); +} + +/** A chooser that is there but broke (the display is missing, a library does not load) must say so; a bare exit 1 is a cancel. */ +const BROKEN = /unable to init server|cannot open display|can't open display|no protocol specified|error while loading shared libraries|symbol lookup error|version `[^']*' not found|cannot connect to|failed to connect|could not connect/i; +const firstLine = text => String(text ?? '').split(/\r?\n/).map(l => l.trim()).find(Boolean)?.slice(0, 160) ?? ''; + +/** + * Linux: zenity, then kdialog, then the desktop portal's file chooser through gdbus. Every one of them runs with the environment the + * AppImage was started from (external-env.mjs), not Strata's own libraries. A chooser that is missing is skipped; one that fails is + * remembered and the next is tried; when none works the answer says why and the person types the path. + */ +async function chooseLinuxFolder(prompt, { run, portal }) { + const env = externalEnvironment(); const candidates = [ ['zenity', ['--file-selection', '--directory', `--title=${prompt}`]], ['kdialog', ['--getexistingdirectory', '.', '--title', prompt]], ]; + const failures = []; for (const [command, args] of candidates) { try { - const { stdout } = await run(command, args); + const { stdout } = await run(command, args, { env }); 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.'); + const detail = `${error?.stderr ?? ''}`; + if (error?.code === 1 && !BROKEN.test(detail)) return { cancelled: true }; // both tools exit 1 when the dialog is dismissed + failures.push(`${command}: ${firstLine(detail) || firstLine(error?.message) || `exit ${error?.code}`}`); } } - return { unavailable: true, reason: 'No folder chooser is installed (install zenity or kdialog).' }; + try { + const picked = await portal(prompt, { run, env }); + if (picked) return picked; + } catch (error) { + failures.push(`portal: ${firstLine(error?.message)}`); + } + return { + unavailable: true, failed: failures.length > 0, ...(failures.length ? { detail: failures.join('; ') } : {}), + reason: failures.length + ? `The folder chooser could not open (${failures[0]}). Install zenity or kdialog to pick a folder, or type the path.` + : 'No folder chooser was found. Install zenity or kdialog to pick a folder, or type the path.', + }; +} + +/** + * xdg-desktop-portal FileChooser through gdbus. Resolves { path } | { cancelled: true } | null when there is no portal or no gdbus. + * The answer arrives as a Response signal on the request the call returns, so a monitor is started first. + */ +export async function portalFolder(prompt, { run = exec, env = externalEnvironment(), spawnProcess = spawn, timeoutMs = 10 * 60_000 } = {}) { + const monitor = spawnProcess('gdbus', ['monitor', '--session', '--dest', 'org.freedesktop.portal.Desktop'], { env, stdio: ['ignore', 'pipe', 'ignore'] }); + let seen = ''; + let ended = false; + monitor.on('error', () => { ended = true; }); + monitor.on('close', () => { ended = true; }); + monitor.stdout?.on('data', chunk => { seen += chunk; }); + try { + let call; + try { + call = await run('gdbus', ['call', '--session', '--dest', 'org.freedesktop.portal.Desktop', '--object-path', '/org/freedesktop/portal/desktop', + '--method', 'org.freedesktop.portal.FileChooser.OpenFile', '', prompt, "{'directory': , 'modal': }"], { env }); + } catch { + return null; // no gdbus, or no portal on the session bus + } + const handle = /'(\/org\/freedesktop\/portal\/desktop\/request\/[^']+)'/.exec(call.stdout)?.[1]; + if (!handle) return null; + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const line = seen.split('\n').find(l => l.startsWith(`${handle}: org.freedesktop.portal.Request.Response`)); + if (line) { + const m = /\(uint32 (\d+), (.*)\)\s*$/.exec(line); + if (!m || m[1] !== '0') return { cancelled: true }; + const uri = /'(file:\/\/[^']*)'/.exec(m[2])?.[1]; + return uri ? { path: cleanChosenPath(decodeURIComponent(uri.replace(/^file:\/\//, ''))) } : { cancelled: true }; + } + if (ended) return null; + await new Promise(r => setTimeout(r, 100)); + } + return { cancelled: true }; + } finally { + try { monitor.kill(); } catch { /* already gone */ } + } } export const TYPE_A_PATH = 'No folder chooser is available on this system, so type the folder path instead.'; +/** The host's answer when no chooser works: a plain sentence and a code the app turns into a field for typing the path. */ +export function chooserUnavailable(picked) { + return { message: picked.failed ? picked.reason : `${TYPE_A_PATH} ${picked.reason}`, code: 'folder-chooser-unavailable', details: picked.detail }; +} + /** 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() : ''; diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index dae32222..63210c21 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -4,7 +4,7 @@ import { createConnectorInstaller } from './cloudflared-install.mjs'; import { openArtifact } from './artifacts.mjs'; import { saveSnapshot } from './snapshot.mjs'; import { resolvePython, shellPrefix } from './python-resolver.mjs'; -import { chooseFolder, typedFolder, TYPE_A_PATH } from './folder-dialog.mjs'; +import { chooseFolder, chooserUnavailable, typedFolder } from './folder-dialog.mjs'; import { createLocalShare } from './local-share.mjs'; import { createTaskService, validateTask } from './tasks.mjs'; import { createAgentTaskRunner } from './agent/task-run.mjs'; @@ -935,7 +935,7 @@ async function api(req, res, path, method, url) { /* "Use a local GGUF": pick (or type) the folder, and Control says what is in it. Nothing is copied or changed. */ const typed=await typedFolder((await readBody(req)).path,{isAbsolute}); const picked=typed?{path:typed}:await chooseFolder('Choose the folder that holds your GGUF files'); - if(picked.unavailable)return error(res,501,`${TYPE_A_PATH} ${picked.reason}`); + if(picked.unavailable){const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});}; if(picked.cancelled)return json(res,200,{cancelled:true}); return json(res,200,{path:picked.path,preview:await native.localPreview(picked.path)});} if(path==='/api/native/benchmark'&&method==='GET')return json(res,200,native.benchmarkReport()); @@ -1680,7 +1680,7 @@ async function api(req, res, path, method, url) { // 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.unavailable) {const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});}; if (picked.cancelled) return json(res, 200, { cancelled: true }); const chosen = picked.path; const base = basename(chosen); @@ -1705,7 +1705,7 @@ async function api(req, res, path, method, url) { try { 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.unavailable) {const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});}; if (picked.cancelled) return json(res, 200, { cancelled: true }); return json(res, 200, { path: picked.path }); } catch (e) { diff --git a/apps/host/tests/external-env.test.mjs b/apps/host/tests/external-env.test.mjs new file mode 100644 index 00000000..80a8ac75 --- /dev/null +++ b/apps/host/tests/external-env.test.mjs @@ -0,0 +1,116 @@ +/** + * Programs that are not Strata's own (zenity, kdialog, xdg-open, the assistant's shell) get the environment the Linux AppImage was + * started from, not the AppImage's libraries and settings (tester report 2026-10-17: zenity died with + * "libssl.so.3: version OPENSSL_3.2.0 not found" and the folder picker did nothing). + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { externalEnvironment, recordedOriginal, withoutAppImage } from '../server/external-env.mjs'; +import { chooseFolder, chooserUnavailable, portalFolder } from '../server/folder-dialog.mjs'; +import { agentEnvironment } from '../server/agent/harness-runtime.mjs'; + +const APPDIR = '/tmp/.mount_StrataAbc'; +const leaky = { + APPDIR, APPIMAGE: '/home/u/Strata.AppImage', ARGV0: 'Strata', + LD_LIBRARY_PATH: `${APPDIR}/usr/lib:${APPDIR}/usr/lib/x86_64-linux-gnu:/opt/cuda/lib64`, + PATH: `${APPDIR}/usr/bin:/usr/local/bin:/usr/bin`, + XDG_DATA_DIRS: `${APPDIR}/usr/share:/usr/share:/usr/local/share`, + GTK_PATH: `${APPDIR}//usr/lib/gtk-3.0`, GIO_MODULE_DIR: `${APPDIR}//usr/lib/gio/modules`, GDK_PIXBUF_MODULE_FILE: `${APPDIR}//usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache`, + GSETTINGS_SCHEMA_DIR: `${APPDIR}//usr/share/glib-2.0/schemas`, PYTHONHOME: `${APPDIR}/usr/python`, HOME: '/home/u', DISPLAY: ':0', +}; + +test('without a record, everything that points into the AppImage is removed and the user\'s own entries stay', () => { + const env = externalEnvironment(leaky); + assert.equal(env.APPDIR, undefined); + assert.equal(env.APPIMAGE, undefined); + assert.equal(env.LD_LIBRARY_PATH, '/opt/cuda/lib64', 'only the AppImage\'s folders go from the list'); + assert.equal(env.PATH, '/usr/local/bin:/usr/bin'); + assert.equal(env.XDG_DATA_DIRS, '/usr/share:/usr/local/share'); + for (const name of ['GTK_PATH', 'GIO_MODULE_DIR', 'GDK_PIXBUF_MODULE_FILE', 'GSETTINGS_SCHEMA_DIR', 'PYTHONHOME']) assert.equal(env[name], undefined, name); + assert.equal(env.HOME, '/home/u'); + assert.equal(env.DISPLAY, ':0'); +}); + +test('with the launcher\'s record, the original environment is restored exactly', () => { + const original = { PATH: '/usr/bin', LD_LIBRARY_PATH: '/mine', HOME: '/home/u', DISPLAY: ':1' }; + const record = Buffer.from(Object.entries(original).map(([k, v]) => `${k}=${v}`).join('\0') + '\0').toString('base64'); + const env = externalEnvironment({ ...leaky, STRATA_ORIGINAL_ENV: record }); + assert.deepEqual(env, original); + assert.deepEqual(recordedOriginal({ STRATA_ORIGINAL_ENV: record }), original); + assert.equal(recordedOriginal({ STRATA_ORIGINAL_ENV: '!!!' }), null); +}); + +test('outside an AppImage nothing changes', () => { + const plain = { PATH: '/usr/bin', LD_LIBRARY_PATH: '/opt/x/lib', HOME: '/h' }; + assert.deepEqual(externalEnvironment(plain), plain); + assert.deepEqual(externalEnvironment(plain, { A: '1' }), { ...plain, A: '1' }); + assert.deepEqual(withoutAppImage(plain), plain); +}); + +test('the coding assistant\'s shell does not inherit the AppImage\'s settings either', () => { + const env = agentEnvironment({ ...leaky, SOME_TOKEN: 'x' }, { DSH_HOME: '/h' }); + assert.equal(env.LD_LIBRARY_PATH, undefined); + assert.ok(!/\.mount_/.test(JSON.stringify(env)), JSON.stringify(env)); + assert.equal(env.DSH_HOME, '/h'); + assert.equal(env.SOME_TOKEN, undefined); +}); + +const failure = (code, stderr = '') => Object.assign(new Error(`exit ${code}`), { code, stderr }); + +test('Linux folder chooser: a zenity that breaks is reported, not taken for a cancel, and the next chooser is tried', async () => { + const seen = []; + const libssl = failure(127, 'zenity: error while loading shared libraries: libssl.so.3: version `OPENSSL_3.2.0\' not found'); + const run = async (command, args, options) => { seen.push({ command, env: options?.env }); if (command === 'zenity') throw libssl; return { stdout: '/home/u/Models/\n' }; }; + const old = { ...process.env }; + Object.assign(process.env, leaky); + try { + const picked = await chooseFolder('Pick', { platform: 'linux', run, portal: async () => null }); + assert.deepEqual(picked, { path: '/home/u/Models' }); + assert.deepEqual(seen.map(s => s.command), ['zenity', 'kdialog']); + for (const s of seen) { assert.equal(s.env.LD_LIBRARY_PATH, '/opt/cuda/lib64'); assert.equal(s.env.APPDIR, undefined); } + // every chooser broken or missing: a plain sentence that names what to do, never a silent nothing + const none = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw libssl; }, portal: async () => null }); + assert.equal(none.unavailable, true); + assert.equal(none.failed, true); + assert.match(none.reason, /Install zenity or kdialog to pick a folder, or type the path/); + const answer = chooserUnavailable(none); + assert.equal(answer.code, 'folder-chooser-unavailable'); + const missingAll = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure('ENOENT'); }, portal: async () => null }); + assert.equal(missingAll.unavailable, true); + assert.match(missingAll.reason, /zenity or kdialog/); + // a plain exit 1 is still a cancel; so is exit 1 with harmless warnings + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure(1, 'Gtk-Message: Failed to load module "canberra-gtk-module"'); }, portal: async () => null }), { cancelled: true }); + // a zenity that cannot reach the display exits 1 too: that is a failure + const noDisplay = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure(1, 'Unable to init server: Could not connect: Connection refused'); }, portal: async () => null }); + assert.equal(noDisplay.unavailable, true); + } finally { for (const k of Object.keys(leaky)) { if (old[k] === undefined) delete process.env[k]; else process.env[k] = old[k]; } } +}); + +test('Linux folder chooser: the desktop portal answers when zenity and kdialog are not installed', async () => { + const run = async () => { throw failure('ENOENT'); }; + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run, portal: async () => ({ path: '/home/u/Pics' }) }), { path: '/home/u/Pics' }); + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run, portal: async () => ({ cancelled: true }) }), { cancelled: true }); +}); + +test('portalFolder reads the Response signal of its request', async () => { + const handle = '/org/freedesktop/portal/desktop/request/1_42/t1'; + const monitor = new EventEmitter(); + monitor.stdout = new EventEmitter(); + monitor.kill = () => { monitor.exitCode = 0; }; + monitor.exitCode = null; + const spawnProcess = () => monitor; + const run = async (command, args) => { + assert.equal(command, 'gdbus'); + assert.ok(args.includes('org.freedesktop.portal.FileChooser.OpenFile')); + queueMicrotask(() => monitor.stdout.emit('data', `${handle}: org.freedesktop.portal.Request.Response (uint32 0, {'uris': <['file:///home/u/My%20Models']>})\n`)); + return { stdout: `(objectpath '${handle}',)\n` }; + }; + assert.deepEqual(await portalFolder('Pick', { run, env: {}, spawnProcess }), { path: '/home/u/My Models' }); + const cancel = new EventEmitter(); + cancel.stdout = new EventEmitter(); cancel.kill = () => {}; cancel.exitCode = null; + const run2 = async () => { queueMicrotask(() => cancel.stdout.emit('data', `${handle}: org.freedesktop.portal.Request.Response (uint32 1, {})\n`)); return { stdout: `(objectpath '${handle}',)\n` }; }; + assert.deepEqual(await portalFolder('Pick', { run: run2, env: {}, spawnProcess: () => cancel }), { cancelled: true }); + const none = new EventEmitter(); none.stdout = new EventEmitter(); none.kill = () => {}; none.exitCode = null; + assert.equal(await portalFolder('Pick', { run: async () => { throw failure('ENOENT'); }, env: {}, spawnProcess: () => none }), null); +}); From 447b99ba3820367b4a12a5384537ec322c16e3cd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 17 Oct 2026 19:12:09 +0200 Subject: [PATCH 6/9] Folder chooser fallback in the app: plain message and a field for the path --- apps/host/server/folder-dialog.mjs | 4 +- apps/host/src/app/App.tsx | 2 + apps/host/src/components/FolderPathDialog.tsx | 21 +++++++++ apps/host/src/lib/chat-folder.ts | 3 +- apps/host/src/lib/folder-pick.ts | 45 +++++++++++++++++++ apps/host/src/lib/store.ts | 3 +- apps/host/src/locales/de.json | 7 ++- apps/host/src/locales/en.json | 7 ++- apps/host/src/locales/es.json | 7 ++- apps/host/src/locales/ja.json | 7 ++- apps/host/src/locales/ko.json | 7 ++- apps/host/src/locales/pt.json | 7 ++- apps/host/src/locales/ru.json | 7 ++- apps/host/src/locales/zh.json | 7 ++- apps/host/src/screens/Skills.tsx | 8 +++- 15 files changed, 128 insertions(+), 14 deletions(-) create mode 100644 apps/host/src/components/FolderPathDialog.tsx create mode 100644 apps/host/src/lib/folder-pick.ts diff --git a/apps/host/server/folder-dialog.mjs b/apps/host/server/folder-dialog.mjs index ea81f95a..bb2a9d36 100644 --- a/apps/host/server/folder-dialog.mjs +++ b/apps/host/server/folder-dialog.mjs @@ -104,7 +104,7 @@ async function chooseLinuxFolder(prompt, { run, portal }) { return { unavailable: true, failed: failures.length > 0, ...(failures.length ? { detail: failures.join('; ') } : {}), reason: failures.length - ? `The folder chooser could not open (${failures[0]}). Install zenity or kdialog to pick a folder, or type the path.` + ? 'The folder chooser could not open. Install zenity or kdialog to pick a folder, or type the path.' : 'No folder chooser was found. Install zenity or kdialog to pick a folder, or type the path.', }; } @@ -152,7 +152,7 @@ export const TYPE_A_PATH = 'No folder chooser is available on this system, so ty /** The host's answer when no chooser works: a plain sentence and a code the app turns into a field for typing the path. */ export function chooserUnavailable(picked) { - return { message: picked.failed ? picked.reason : `${TYPE_A_PATH} ${picked.reason}`, code: 'folder-chooser-unavailable', details: picked.detail }; + return { message: picked.reason, code: 'folder-chooser-unavailable', details: picked.detail }; } /** A typed path stands in for the dialog: it must be an absolute directory that exists. */ diff --git a/apps/host/src/app/App.tsx b/apps/host/src/app/App.tsx index 92e06536..7604306c 100644 --- a/apps/host/src/app/App.tsx +++ b/apps/host/src/app/App.tsx @@ -8,6 +8,7 @@ import { bootOnce, bootstrap, setNavOpen, setFocus, useStore, } from '../lib/sto import { Sidebar } from './Sidebar'; import { CommandPalette } from './CommandPalette'; import { ShortcutsDialog } from './Shortcuts'; +import { FolderPathDialog } from '../components/FolderPathDialog'; import { handleAppShortcut, runCommand } from '../lib/commands'; import { useMedia } from '../lib/responsive'; import { Btn, Dialog, IconBtn, Toasts } from '../components/ui'; @@ -66,6 +67,7 @@ function AppShell() { + {tr(setupOpen ? (