Merge commit 'e77e5550d' into f-split-int
This commit is contained in:
commit
c7f803d0db
46 files changed
+1349
-90
No files matched your search
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Which files and folders of the staged Harness are dropped, and the check that nothing the Harness imports is gone.
|
||||
*
|
||||
* The 2026-10-17 tester report: on Linux and Mac every agent chat failed ("session/create ... waiting for workflowEngine").
|
||||
* Cause: the old rule "drop any folder named after another operating system" also removed the Harness's own JavaScript package
|
||||
* `@deepseek-ai/dsh-win32-process`. It is plain JS (no binary), and `dsh-subprocess-local` and `dsh-sandbox-local` import it by
|
||||
* name on every platform, so those two plugins failed to load, and everything waiting on them (shell, subprocess, ptcRuntime,
|
||||
* workflowEngine) never started. Windows kept it (the rule differs there), so the Windows tests passed.
|
||||
*/
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
||||
import { join, sep } from 'node:path';
|
||||
|
||||
export const OTHER_OS = {
|
||||
win32: /(^|[\\/._-])(darwin|linux|android|freebsd|musl)([\\/._-]|$)/i,
|
||||
darwin: /(^|[\\/._-])(win32|linux|android|freebsd|musl)([\\/._-]|$)/i,
|
||||
// Linux: the AppImage bundler (linuxdeploy) resolves the libraries of every ELF file under resources and stops on one it
|
||||
// cannot satisfy (koffi's musl build wants libc.musl). The app is glibc x86_64, so musl and other-CPU builds are dropped.
|
||||
linux: /(^|[\\/._-])(win32|darwin|android|freebsd|musl|arm64|aarch64|armv7|arm|ia32|riscv64|ppc64|s390x|loong64)([\\/._-]|$)/i,
|
||||
};
|
||||
const NATIVE_FOLDER = /prebuild|bin|native|platform|-(win32|darwin|linux)/i;
|
||||
|
||||
/** The Harness's own JavaScript packages (`@deepseek-ai/dsh-*`) are code every platform imports by name; never drop one. */
|
||||
export function isHarnessCodePackage(path) {
|
||||
const parts = path.split(sep);
|
||||
const i = parts.lastIndexOf('@deepseek-ai');
|
||||
return i >= 0 && i === parts.length - 2 && parts[i + 1].startsWith('dsh-');
|
||||
}
|
||||
|
||||
/** True when the folder `path` (a directory named `name`) is another operating system's prebuilt binary and can go. */
|
||||
export function isOtherOsBinaryFolder(platform, name, path) {
|
||||
const rule = OTHER_OS[platform] ?? OTHER_OS.linux;
|
||||
if (isHarnessCodePackage(path)) return false;
|
||||
return rule.test(name) && NATIVE_FOLDER.test(path);
|
||||
}
|
||||
|
||||
/** Imports the Windows copy (which works) is also without: browser-side or dev-only bundles, and the document converter the app drops on purpose. */
|
||||
const KNOWN_ABSENT = new Set([
|
||||
'@deepseek-ai/libreoffice-kit', '@deepseek-ai/dsh-client-ui-dockkit', '@deepseek-ai/dsh-client-web',
|
||||
'@deepseek-ai/dsh-experimental-webworker-runtime', '@deepseek-ai/dsh-remote-mock', '@deepseek-ai/dsh-client-test-runtime',
|
||||
]);
|
||||
|
||||
function jsFiles(dir, out = []) {
|
||||
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = join(dir, e.name);
|
||||
if (e.isSymbolicLink()) continue;
|
||||
if (e.isDirectory()) jsFiles(p, out);
|
||||
else if (/\.(m?js|cjs)$/.test(e.name)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every bare `@deepseek-ai/<package>` the staged Harness's own packages import (static `from "x"` and `import("x")`) must exist
|
||||
* in the staged node_modules. Returns the list of `{from, missing}` problems (empty = good). Plugins that are only loaded on
|
||||
* another platform still count: Node resolves a static import whether or not the code runs.
|
||||
*/
|
||||
export function missingHarnessImports(harnessDir) {
|
||||
const scope = join(harnessDir, 'node_modules', '@deepseek-ai');
|
||||
if (!existsSync(scope)) return [{ from: scope, missing: '@deepseek-ai (no installed packages)' }];
|
||||
const problems = [];
|
||||
const seen = new Set();
|
||||
const re = /(?:from|import)\s*\(?\s*["'](@deepseek-ai\/[^"'/]+)(?:\/[^"']*)?["']/g;
|
||||
for (const pkg of readdirSync(scope)) {
|
||||
const lib = join(scope, pkg, 'lib');
|
||||
if (!existsSync(lib)) continue;
|
||||
for (const file of jsFiles(lib)) {
|
||||
const text = readFileSync(file, 'utf8');
|
||||
for (const m of text.matchAll(re)) {
|
||||
const name = m[1];
|
||||
const key = `${pkg}>${name}`;
|
||||
if (seen.has(key) || KNOWN_ABSENT.has(name)) continue;
|
||||
seen.add(key);
|
||||
if (!existsSync(join(harnessDir, 'node_modules', ...name.split('/')))
|
||||
&& !existsSync(join(scope, pkg, 'node_modules', ...name.split('/')))) problems.push({ from: `${pkg}`, missing: name });
|
||||
}
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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,13 @@ 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(String.fromCharCode(10))); process.exit(1); }
|
||||
console.log('import check: every @deepseek-ai package the Harness imports is staged');
|
||||
|
||||
// --- proof 2: the staged copy answers --version and boots the web profile once ----------------------------------------
|
||||
const bin = join(out, 'apps', 'cli', 'lib', 'bin.js');
|
||||
const entry = existsSync(bin) ? bin : join(out, 'lib', 'bin.js');
|
||||
const v = spawnSync(process.execPath, [entry, '--version'], { encoding: 'utf8' });
|
||||
|
||||
@@ -202,6 +202,9 @@ ShowInstDetails nevershow
|
||||
; 4. Custom page to ask user if he wants to reinstall/uninstall
|
||||
; only if a previous installation was detected
|
||||
Var ReinstallPageCheck
|
||||
; 1 when this installer was started on an installed copy of the SAME version and the person chose Uninstall: after it ran the
|
||||
; uninstaller this installer ends. (Stock Tauri goes on to the install pages, so Uninstall reinstalled Strata at once; tester report 2026-10-17.)
|
||||
Var UninstallOnly
|
||||
Page custom PageReinstall PageLeaveReinstall
|
||||
Function PageReinstall
|
||||
; Uninstall previous WiX installation if exists.
|
||||
@@ -346,6 +349,7 @@ Function PageLeaveReinstall
|
||||
${If} $R1 = 1 ; User chose to add/reinstall
|
||||
Goto reinst_done
|
||||
${Else} ; User chose to uninstall
|
||||
StrCpy $UninstallOnly 1
|
||||
Goto reinst_uninstall
|
||||
${EndIf}
|
||||
${ElseIf} $R0 = 1 ; Upgrading
|
||||
@@ -408,6 +412,12 @@ Function PageLeaveReinstall
|
||||
Delete "$4\uninstall.exe"
|
||||
RMDir "$4"
|
||||
${EndIf}
|
||||
|
||||
; Uninstall means uninstall: do not go on to the install pages.
|
||||
${If} $UninstallOnly = 1
|
||||
MessageBox MB_OK|MB_ICONINFORMATION "Strata was uninstalled."
|
||||
Quit
|
||||
${EndIf}
|
||||
reinst_done:
|
||||
FunctionEnd
|
||||
|
||||
@@ -451,45 +461,33 @@ FunctionEnd
|
||||
; 1. Confirm uninstall page
|
||||
Var DeleteAppDataCheckbox
|
||||
Var DeleteAppDataCheckboxState
|
||||
!define /ifndef WS_EX_LAYOUTRTL 0x00400000
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow
|
||||
Function un.ConfirmShow ; Add add a `Delete app data` check box
|
||||
; $1 inner dialog HWND
|
||||
; $2 window DPI
|
||||
; $3 style
|
||||
; $4 x
|
||||
; $5 y
|
||||
; $6 width
|
||||
; $7 height
|
||||
FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog
|
||||
System::Call "user32::GetDpiForWindow(p r1) i .r2"
|
||||
${If} $(^RTL) = 1
|
||||
StrCpy $3 "${__NSD_CheckBox_EXSTYLE} | ${WS_EX_LAYOUTRTL}"
|
||||
IntOp $4 50 * $2
|
||||
${Else}
|
||||
StrCpy $3 "${__NSD_CheckBox_EXSTYLE}"
|
||||
IntOp $4 0 * $2
|
||||
${EndIf}
|
||||
IntOp $5 100 * $2
|
||||
IntOp $6 400 * $2
|
||||
IntOp $7 25 * $2
|
||||
IntOp $4 $4 / 96
|
||||
IntOp $5 $5 / 96
|
||||
IntOp $6 $6 / 96
|
||||
IntOp $7 $7 / 96
|
||||
System::Call 'user32::CreateWindowEx(i r3, w "${__NSD_CheckBox_CLASS}", w "$(deleteAppData)", i ${__NSD_CheckBox_STYLE}, i r4, i r5, i r6, i r7, p r1, i0, i0, i0) i .s'
|
||||
Pop $DeleteAppDataCheckbox
|
||||
SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1
|
||||
SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1
|
||||
FunctionEnd
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave
|
||||
Function un.ConfirmLeave
|
||||
SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState
|
||||
FunctionEnd
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive
|
||||
!insertmacro MUI_UNPAGE_CONFIRM
|
||||
|
||||
; 2. Uninstalling Page
|
||||
; 2. "Also remove my Strata data": unticked by default, and it says exactly what it deletes. Skipped when updating or in passive mode
|
||||
; (an update never deletes anything). Model folders the person chose themselves are never touched.
|
||||
UninstPage custom un.DataPage un.DataPageLeave
|
||||
Function un.DataPage
|
||||
${If} $PassiveMode = 1
|
||||
${OrIf} $UpdateMode = 1
|
||||
Abort
|
||||
${EndIf}
|
||||
!insertmacro MUI_HEADER_TEXT "Remove your Strata data too?" "Your models, chats and settings stay on this PC unless you tick the box."
|
||||
nsDialogs::Create 1018
|
||||
Pop $0
|
||||
${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|}
|
||||
${NSD_CreateCheckBox} 0 0 100% 12u "Also remove my Strata data (models, chats, settings)"
|
||||
Pop $DeleteAppDataCheckbox
|
||||
${NSD_CreateLabel} 12u 18u -12u 96u "If you tick it, these folders are deleted, and nothing else:$\r$\n$\r$\n$LOCALAPPDATA\Strata (engine, installed copy, tunings)$\r$\n$APPDATA\Strata (settings)$\r$\n$PROFILE\.strata (your chats, app settings)$\r$\n$DOCUMENTS\Strata\Models (models Strata downloaded into its own folder)$\r$\n$\r$\nA model folder you chose yourself is never deleted."
|
||||
Pop $0
|
||||
${NSD_SetFocus} $DeleteAppDataCheckbox
|
||||
nsDialogs::Show
|
||||
FunctionEnd
|
||||
Function un.DataPageLeave
|
||||
${NSD_GetState} $DeleteAppDataCheckbox $DeleteAppDataCheckboxState
|
||||
FunctionEnd
|
||||
|
||||
; 3. Uninstalling Page
|
||||
!insertmacro MUI_UNPAGE_INSTFILES
|
||||
|
||||
;Languages
|
||||
@@ -931,6 +929,21 @@ Section Uninstall
|
||||
SetShellVarContext current
|
||||
RmDir /r "$APPDATA\${BUNDLEID}"
|
||||
RmDir /r "$LOCALAPPDATA\${BUNDLEID}"
|
||||
|
||||
; Strata's own data, for a fresh start: the folders listed on the page, nothing else. Each path is checked first.
|
||||
${If} "$LOCALAPPDATA" != ""
|
||||
RmDir /r "$LOCALAPPDATA\Strata"
|
||||
${EndIf}
|
||||
${If} "$APPDATA" != ""
|
||||
RmDir /r "$APPDATA\Strata"
|
||||
${EndIf}
|
||||
${If} "$PROFILE" != ""
|
||||
RmDir /r "$PROFILE\.strata"
|
||||
${EndIf}
|
||||
${If} "$DOCUMENTS" != ""
|
||||
RmDir /r "$DOCUMENTS\Strata\Models"
|
||||
RmDir "$DOCUMENTS\Strata" ; only if it is empty now
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
|
||||
!ifmacrodef NSIS_HOOK_POSTUNINSTALL
|
||||
|
||||
@@ -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 => {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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.');
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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. 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': <true>, 'modal': <true>}"], { 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.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() : '';
|
||||
|
||||
@@ -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';
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -934,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());
|
||||
@@ -1679,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);
|
||||
@@ -1704,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) {
|
||||
|
||||
@@ -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;
|
||||
@@ -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
|
||||
@@ -63,7 +64,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 +86,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}));
|
||||
|
||||
@@ -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}`};
|
||||
}
|
||||
@@ -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() {
|
||||
<CommandPalette open={paletteOpen}/>
|
||||
<Dialog open={location.query.get('settings') === '1'} title={tr("Settings")} className="settings-dialog" onClose={closeSettings}><SettingsScreen /></Dialog>
|
||||
<ShortcutsDialog />
|
||||
<FolderPathDialog />
|
||||
{tr(setupOpen ? (<div className="setupmodal" role="dialog" aria-modal="true" aria-label={tr("Set up Strata")}>
|
||||
<div className="scrim" data-open="true" aria-hidden="true"/>
|
||||
<div className="setupmodal__surface" ref={setupRef}>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { tr } from '../lib/i18n';
|
||||
import { useFolderPrompt } from '../lib/folder-pick';
|
||||
import { Btn, Dialog } from './ui';
|
||||
|
||||
/** The fallback for a system without a folder chooser: say so in plain words and take the folder's path as text. */
|
||||
export function FolderPathDialog() {
|
||||
const prompt = useFolderPrompt();
|
||||
const [path, setPath] = useState('');
|
||||
useEffect(() => { if (prompt) setPath(''); }, [prompt]);
|
||||
const submit = () => { const text = path.trim(); if (text) prompt?.resolve(text); };
|
||||
return <Dialog open={!!prompt} compact title={tr("Type the folder path")} onClose={() => prompt?.resolve(null)}
|
||||
actions={<><Btn onClick={() => prompt?.resolve(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!path.trim()} onClick={submit}>{tr("Use this folder")}</Btn></>}>
|
||||
<form className="stack" onSubmit={event => { event.preventDefault(); submit(); }}>
|
||||
<p className="small" role="status">{tr(prompt?.message ?? '')}</p>
|
||||
<label className="input-field"><span>{tr("Folder path")}</span>
|
||||
<input className="st-input" autoFocus value={path} onChange={event => setPath(event.target.value)} placeholder={tr("/home/you/Documents")} spellCheck={false} aria-label={tr("Folder path")}/>
|
||||
</label>
|
||||
</form>
|
||||
</Dialog>;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useSyncExternalStore } from 'react';
|
||||
import { api } from './client';
|
||||
import { postWithFolderFallback } from './folder-pick';
|
||||
|
||||
/** A chat's project folder (notes-split-agent8.md, item 4): the assistant works inside it and can only touch files in it. */
|
||||
export interface ChatFolder { path: string; name: string; exists: boolean }
|
||||
@@ -35,7 +36,7 @@ export async function loadFolder(chatId: string) {
|
||||
|
||||
/** Ask the system for a folder (null when the person closes the dialog), then make it this chat's. */
|
||||
export async function chooseChatFolder(chatId: string): Promise<'chosen' | 'cancelled'> {
|
||||
const picked = await api.post<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick', {});
|
||||
const picked = await postWithFolderFallback<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick') as { path?: string };
|
||||
if (!picked.path) return 'cancelled';
|
||||
await setChatFolder(chatId, picked.path);
|
||||
return 'chosen';
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import { ApiError, api } from './client';
|
||||
|
||||
/**
|
||||
* Picking a folder when the system has no working chooser (Linux without zenity, kdialog or a desktop portal, or one that fails).
|
||||
* The host answers 501 with code `folder-chooser-unavailable` and a plain sentence; the app then asks for the path in a small dialog
|
||||
* and sends it back as `{ path }`, which the host checks the same way as a picked folder. Closing the dialog is a cancel.
|
||||
*/
|
||||
export interface FolderPrompt { message: string; resolve: (path: string | null) => void }
|
||||
|
||||
let current: FolderPrompt | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
const subscribe = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };
|
||||
const emit = () => listeners.forEach(fn => fn());
|
||||
|
||||
export function useFolderPrompt() { return useSyncExternalStore(subscribe, () => current, () => null); }
|
||||
|
||||
/** Ask for a folder path in words; resolves with the typed text, or null when the person cancels. */
|
||||
export function askForFolderPath(message: string): Promise<string | null> {
|
||||
return new Promise(resolve => {
|
||||
current?.resolve(null);
|
||||
current = { message, resolve: path => { current = null; emit(); resolve(path); } };
|
||||
emit();
|
||||
});
|
||||
}
|
||||
|
||||
export const isChooserUnavailable = (e: unknown) => e instanceof ApiError && (e.body as { code?: string } | undefined)?.code === 'folder-chooser-unavailable';
|
||||
|
||||
/** POST to a host route that opens the system folder chooser; if there is none, ask for the path and POST it instead. */
|
||||
export async function postWithFolderFallback<T>(url: string): Promise<T | { cancelled: true }> {
|
||||
try { return await api.post<T>(url, {}); }
|
||||
catch (e) {
|
||||
if (!isChooserUnavailable(e)) throw e;
|
||||
for (;;) {
|
||||
const typed = await askForFolderPath((e as ApiError).message);
|
||||
if (!typed) return { cancelled: true };
|
||||
try { return await api.post<T>(url, { path: typed }); }
|
||||
catch (again) {
|
||||
// A path the host refuses ("That folder does not exist.") is shown and asked for again; anything else is a real failure.
|
||||
if (!(again instanceof ApiError) || again.status !== 400) throw again;
|
||||
e = Object.assign(new ApiError(again.message, 501, { code: 'folder-chooser-unavailable' }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.' },
|
||||
|
||||
@@ -12,6 +12,7 @@ import { lifecyclePolicy } from './lifecycle';
|
||||
import { newestServingState } from './serving-state';
|
||||
import { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos';
|
||||
import { nativeState } from './native';
|
||||
import { postWithFolderFallback } from './folder-pick';
|
||||
import { setTranslationLanguage, tr, validLanguage, type Language } from './i18n';
|
||||
/**
|
||||
* Strata app store.
|
||||
@@ -548,7 +549,7 @@ export const CONTENT_FONT_RANGE = { min: CONTENT_FS_MIN, max: CONTENT_FS_MAX };
|
||||
|
||||
/** Opens the system folder chooser. Returns null when it is dismissed. */
|
||||
export async function pickWorkspace(): Promise<string | null> {
|
||||
const res = await api.post<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick', {});
|
||||
const res = await postWithFolderFallback<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick') as { path?: string };
|
||||
return res.path ?? null;
|
||||
}
|
||||
|
||||
|
||||
@@ -3125,5 +3125,23 @@
|
||||
"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.",
|
||||
"s3146": "Es wurde kein Ordner-Auswahldialog gefunden. Installiere zenity oder kdialog, um einen Ordner auszuwählen, oder gib den Pfad ein.",
|
||||
"s3147": "Der Ordner-Auswahldialog konnte nicht geöffnet werden. Installiere zenity oder kdialog, um einen Ordner auszuwählen, oder gib den Pfad ein.",
|
||||
"s3148": "Ordnerpfad eingeben",
|
||||
"s3149": "Ordnerpfad",
|
||||
"s3150": "/home/du/Dokumente"
|
||||
}
|
||||
@@ -3125,5 +3125,23 @@
|
||||
"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.",
|
||||
"s3146": "No folder chooser was found. Install zenity or kdialog to pick a folder, or type the path.",
|
||||
"s3147": "The folder chooser could not open. Install zenity or kdialog to pick a folder, or type the path.",
|
||||
"s3148": "Type the folder path",
|
||||
"s3149": "Folder path",
|
||||
"s3150": "/home/you/Documents"
|
||||
}
|
||||
@@ -3125,5 +3125,23 @@
|
||||
"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.",
|
||||
"s3146": "No se encontró ningún selector de carpetas. Instala zenity o kdialog para elegir una carpeta, o escribe la ruta.",
|
||||
"s3147": "No se pudo abrir el selector de carpetas. Instala zenity o kdialog para elegir una carpeta, o escribe la ruta.",
|
||||
"s3148": "Escribe la ruta de la carpeta",
|
||||
"s3149": "Ruta de la carpeta",
|
||||
"s3150": "/home/tu/Documentos"
|
||||
}
|
||||
@@ -3125,5 +3125,23 @@
|
||||
"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": "モデルの起動中に停止しました。",
|
||||
"s3146": "フォルダー選択ツールが見つかりません。zenity か kdialog をインストールしてフォルダーを選ぶか、パスを入力してください。",
|
||||
"s3147": "フォルダー選択ツールを開けませんでした。zenity か kdialog をインストールしてフォルダーを選ぶか、パスを入力してください。",
|
||||
"s3148": "フォルダーのパスを入力",
|
||||
"s3149": "フォルダーのパス",
|
||||
"s3150": "/home/you/Documents"
|
||||
}
|
||||
@@ -3125,5 +3125,23 @@
|
||||
"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": "모델이 시작하는 중에 멈췄습니다.",
|
||||
"s3146": "폴더 선택 도구를 찾지 못했습니다. zenity 또는 kdialog를 설치해 폴더를 고르거나, 경로를 직접 입력하세요.",
|
||||
"s3147": "폴더 선택 도구를 열지 못했습니다. zenity 또는 kdialog를 설치해 폴더를 고르거나, 경로를 직접 입력하세요.",
|
||||
"s3148": "폴더 경로 입력",
|
||||
"s3149": "폴더 경로",
|
||||
"s3150": "/home/you/Documents"
|
||||
}
|
||||
@@ -3125,5 +3125,23 @@
|
||||
"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.",
|
||||
"s3146": "Nenhum seletor de pastas foi encontrado. Instale o zenity ou o kdialog para escolher uma pasta, ou digite o caminho.",
|
||||
"s3147": "Não foi possível abrir o seletor de pastas. Instale o zenity ou o kdialog para escolher uma pasta, ou digite o caminho.",
|
||||
"s3148": "Digite o caminho da pasta",
|
||||
"s3149": "Caminho da pasta",
|
||||
"s3150": "/home/voce/Documentos"
|
||||
}
|
||||
@@ -3125,5 +3125,23 @@
|
||||
"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": "Модель остановилась при запуске.",
|
||||
"s3146": "Окно выбора папки не найдено. Установите zenity или kdialog, чтобы выбрать папку, или введите путь.",
|
||||
"s3147": "Не удалось открыть окно выбора папки. Установите zenity или kdialog, чтобы выбрать папку, или введите путь.",
|
||||
"s3148": "Введите путь к папке",
|
||||
"s3149": "Путь к папке",
|
||||
"s3150": "/home/you/Documents"
|
||||
}
|
||||
@@ -3125,5 +3125,23 @@
|
||||
"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": "模型在启动时停止了。",
|
||||
"s3146": "没有找到文件夹选择器。请安装 zenity 或 kdialog 来选择文件夹,或直接输入路径。",
|
||||
"s3147": "无法打开文件夹选择器。请安装 zenity 或 kdialog 来选择文件夹,或直接输入路径。",
|
||||
"s3148": "输入文件夹路径",
|
||||
"s3149": "文件夹路径",
|
||||
"s3150": "/home/you/Documents"
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useState } from 'react';
|
||||
import { Btn, Dialog, Empty, Icon, IconBtn, Select, ErrorNotice } from '../components/ui';
|
||||
import { Screen } from '../components/layout';
|
||||
import { api } from '../lib/client';
|
||||
import { postWithFolderFallback } from '../lib/folder-pick';
|
||||
import { editSkill, loadSkills, toggleSkill, useStore } from '../lib/store';
|
||||
import type { Skill } from '../lib/types';
|
||||
export function SkillsScreen() {
|
||||
@@ -31,10 +32,13 @@ export function SkillsScreen() {
|
||||
}
|
||||
}
|
||||
async function add() {
|
||||
const result = await api.post<{
|
||||
const result = await postWithFolderFallback<{
|
||||
cancelled?: boolean;
|
||||
added?: string;
|
||||
}>('/api/skills/add');
|
||||
}>('/api/skills/add') as {
|
||||
cancelled?: boolean;
|
||||
added?: string;
|
||||
};
|
||||
if (!result.cancelled)
|
||||
await loadSkills();
|
||||
}
|
||||
|
||||
@@ -7383,6 +7383,15 @@ textarea {
|
||||
.native-choice__col .native-resource-choice button[data-selected="true"] { background: var(--st-surface); color: var(--st-ink); box-shadow: var(--st-sh-card); }
|
||||
.native-choice__col .native-resource-choice button:focus-visible { outline: 2px solid var(--st-accent); outline-offset: 1px; }
|
||||
|
||||
/* Context dropdown and the two Computer use buttons share one line, the buttons level with the dropdown (tester report 2026-10-17: they sat
|
||||
16px lower, from the 16px top margin of the onboarding version of this control, and touched the separator under the row). They wrap
|
||||
below the dropdown only when the card is too narrow for both. */
|
||||
.native-choice__row { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 14px 20px; margin-bottom: 4px; }
|
||||
.native-choice__row > .native-choice__col:first-child { flex: 0 1 240px; min-width: 200px; }
|
||||
.native-choice__row > .native-choice__col:last-child { flex: 0 1 auto; }
|
||||
.native-choice__col .native-resource-choice { margin-top: 0; height: 44px; box-sizing: border-box; align-items: center; align-self: flex-start; }
|
||||
.native-choice__col .native-resource-choice button { height: 36px; }
|
||||
|
||||
/* the version dropdown's chevron turns when it opens (round 8, item 7) */
|
||||
.version-trigger__chev { transition: transform var(--st-t-local, 160ms) var(--st-ease-in-out, ease); }
|
||||
.version-trigger[aria-expanded="true"] .version-trigger__chev { transform: rotate(180deg); }
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
@@ -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 = [];
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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), []);
|
||||
});
|
||||
@@ -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'));
|
||||
});
|
||||
@@ -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 = [];
|
||||
|
||||
@@ -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 (<urlopen error [Errno 11001] getaddrinfo failed>)', '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');
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Every build and staging script must at least parse. A string literal broken over two lines in stage-harness.mjs (2026-10-17) made
|
||||
* every Harness staging fail with a SyntaxError, on every operating system, and nothing noticed until a build was started.
|
||||
*/
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readdirSync } from 'node:fs';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { join, resolve } from 'node:path';
|
||||
|
||||
const scripts = resolve(import.meta.dirname, '..', '..', 'desktop', 'scripts');
|
||||
const packaging = resolve(import.meta.dirname, '..', '..', '..', 'packaging');
|
||||
|
||||
for (const file of readdirSync(scripts).filter(f => f.endsWith('.mjs'))) {
|
||||
test(`node --check ${file}`, () => {
|
||||
const r = spawnSync(process.execPath, ['--check', join(scripts, file)], { encoding: 'utf8' });
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
});
|
||||
}
|
||||
|
||||
for (const file of readdirSync(scripts).filter(f => f.endsWith('.sh'))) {
|
||||
test(`bash -n ${file}`, t => {
|
||||
const probe = spawnSync('bash', ['--version'], { encoding: 'utf8' });
|
||||
if (probe.error || probe.status !== 0) { t.skip('no bash here'); return; }
|
||||
const r = spawnSync('bash', ['-n', join(scripts, file)], { encoding: 'utf8' });
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
});
|
||||
}
|
||||
|
||||
for (const dir of [scripts, packaging]) {
|
||||
for (const file of readdirSync(dir).filter(f => f.endsWith('.py'))) {
|
||||
test(`python compile ${file}`, t => {
|
||||
const python = process.platform === 'win32' ? 'python' : 'python3';
|
||||
const probe = spawnSync(python, ['--version'], { encoding: 'utf8' });
|
||||
if (probe.error || probe.status !== 0) { t.skip('no python here'); return; }
|
||||
const r = spawnSync(python, ['-c', 'import ast,sys; ast.parse(open(sys.argv[1], encoding="utf-8").read())', join(dir, file)], { encoding: 'utf8' });
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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 <package folder> # 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("<I", data, 0x3C)[0]
|
||||
if data[pe:pe + 4] != b"PE\0\0":
|
||||
raise ValueError(f"{path}: bad PE header")
|
||||
nsec, = struct.unpack_from("<H", data, pe + 6)
|
||||
opt_size, = struct.unpack_from("<H", data, pe + 20)
|
||||
opt = pe + 24
|
||||
magic, = struct.unpack_from("<H", data, opt)
|
||||
dd = opt + (112 if magic == 0x20B else 96)
|
||||
sections = []
|
||||
sec = opt + opt_size
|
||||
for i in range(nsec):
|
||||
vsize, va, rsize, raw = struct.unpack_from("<IIII", data, sec + i * 40 + 8)
|
||||
sections.append((va, max(vsize, rsize), raw))
|
||||
|
||||
def off(rva: int) -> 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("<II", data, dd + 8)
|
||||
if imp_rva and imp_size:
|
||||
o = off(imp_rva)
|
||||
while True:
|
||||
_, _, _, name_rva, _ = struct.unpack_from("<IIIII", data, o)
|
||||
if not name_rva:
|
||||
break
|
||||
names.append(cstr(off(name_rva)))
|
||||
o += 20
|
||||
delay_rva, delay_size = struct.unpack_from("<II", data, dd + 13 * 8)
|
||||
if delay_rva and delay_size:
|
||||
o = off(delay_rva)
|
||||
while True:
|
||||
attrs, name_rva = struct.unpack_from("<II", data, o)
|
||||
if not name_rva:
|
||||
break
|
||||
names.append(cstr(off(name_rva)))
|
||||
o += 32
|
||||
return names
|
||||
|
||||
|
||||
def elf_needed(path: Path) -> 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("<I", data, base)[0] not in (0xFEEDFACF, 0xFEEDFACE):
|
||||
raise ValueError(f"{path}: not a Mach-O file")
|
||||
is64 = struct.unpack_from("<I", data, base)[0] == 0xFEEDFACF
|
||||
ncmds, = struct.unpack_from("<I", data, base + 16)
|
||||
o = base + (32 if is64 else 28)
|
||||
out = []
|
||||
for _ in range(ncmds):
|
||||
cmd, size = struct.unpack_from("<II", data, o)
|
||||
if cmd in (0xC, 0x80000018, 0x8000001F): # LOAD_DYLIB, LOAD_WEAK_DYLIB, REEXPORT_DYLIB
|
||||
name_off, = struct.unpack_from("<I", data, o + 8)
|
||||
s = o + name_off
|
||||
out.append(data[s:data.index(b"\0", s)].decode("utf-8", "replace"))
|
||||
o += size
|
||||
return out
|
||||
|
||||
|
||||
def imports(path: Path) -> 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))
|
||||
@@ -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 <folder holding them> 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)})")
|
||||
|
||||
@@ -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"):
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
@@ -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("<IIIII", 0, 0, 0, name_rvas[i], 0)
|
||||
body += b"\0" * 20
|
||||
for j, _ in enumerate(delay):
|
||||
body += struct.pack("<II", 1, name_rvas[len(imports) + j]) + b"\0" * 24
|
||||
body += b"\0" * 32
|
||||
body += blob
|
||||
size = len(body)
|
||||
dos = bytearray(0x40)
|
||||
dos[:2] = b"MZ"
|
||||
struct.pack_into("<I", dos, 0x3C, 0x40)
|
||||
coff = b"PE\0\0" + struct.pack("<HHIIIHH", 0x8664, 1, 0, 0, 0, 240, 0x22)
|
||||
opt = bytearray(240)
|
||||
struct.pack_into("<H", opt, 0, 0x20B)
|
||||
struct.pack_into("<II", opt, 112 + 8, va if imports else 0, descriptors if imports else 0)
|
||||
struct.pack_into("<II", opt, 112 + 13 * 8, va + descriptors if delay else 0, delays if delay else 0)
|
||||
section = b".idata\0\0" + struct.pack("<IIIIIIHHI", size, va, size, raw, 0, 0, 0, 0, 0x40000040)
|
||||
head = bytes(dos) + coff + bytes(opt) + section
|
||||
return head + b"\0" * (raw - len(head)) + bytes(body)
|
||||
|
||||
|
||||
class Imports(unittest.TestCase):
|
||||
def test_pe_reader_lists_load_time_and_delay_load_imports(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = Path(d) / "a.exe"
|
||||
p.write_bytes(make_pe(["cublas64_13.dll", "KERNEL32.dll"], delay=["cudart64_13.dll"]))
|
||||
self.assertEqual(binary_deps.pe_imports(p), ["cublas64_13.dll", "KERNEL32.dll", "cudart64_13.dll"])
|
||||
|
||||
@unittest.skipUnless(sys.platform.startswith("linux"), "needs a real ELF")
|
||||
def test_elf_reader_on_a_system_binary(self):
|
||||
names = binary_deps.elf_needed(Path("/bin/ls") if Path("/bin/ls").exists() else Path(sys.executable))
|
||||
self.assertTrue(any(n.startswith("libc.so") for n in names), names)
|
||||
|
||||
|
||||
class Rule(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.dir.cleanup)
|
||||
self.pkg = Path(self.dir.name) / "pkg"
|
||||
self.pkg.mkdir()
|
||||
|
||||
def test_a_missing_cuda_dll_is_reported_and_the_driver_and_os_are_not(self):
|
||||
(self.pkg / "strata.exe").write_bytes(make_pe(["cublas64_13.dll", "KERNEL32.dll", "ADVAPI32.dll", "nvcuda.dll", "api-ms-win-crt-heap-l1-1-0.dll"]))
|
||||
self.assertEqual(binary_deps.uncovered(self.pkg), [("strata.exe", "cublas64_13.dll")])
|
||||
|
||||
def test_the_visual_cpp_runtime_is_not_an_os_library(self):
|
||||
(self.pkg / "strata.exe").write_bytes(make_pe(["VCRUNTIME140.dll", "MSVCP140.dll"]))
|
||||
self.assertEqual({n for _, n in binary_deps.uncovered(self.pkg)}, {"VCRUNTIME140.dll", "MSVCP140.dll"})
|
||||
|
||||
def test_bundled_libraries_count_and_their_own_imports_are_checked(self):
|
||||
(self.pkg / "strata.exe").write_bytes(make_pe(["cublas64_13.dll"]))
|
||||
(self.pkg / "cublas64_13.dll").write_bytes(make_pe(["cublasLt64_13.dll", "KERNEL32.dll"]))
|
||||
self.assertEqual(binary_deps.uncovered(self.pkg), [("cublas64_13.dll", "cublasLt64_13.dll")])
|
||||
(self.pkg / "CUBLASLT64_13.DLL").write_bytes(make_pe(["KERNEL32.dll"]))
|
||||
self.assertEqual(binary_deps.uncovered(self.pkg), [])
|
||||
|
||||
|
||||
@unittest.skipUnless(os.name == "nt", "the packager only copies DLLs for Windows targets")
|
||||
class Packager(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.dir.cleanup)
|
||||
self.root = Path(self.dir.name)
|
||||
self.src = self.root / "src"
|
||||
self.src.mkdir()
|
||||
(self.src / "strata.exe").write_bytes(make_pe(["cublas64_13.dll", "KERNEL32.dll"]))
|
||||
self.toolkit = self.root / "toolkit"
|
||||
self.toolkit.mkdir()
|
||||
(self.toolkit / "cublas64_13.dll").write_bytes(make_pe(["cublasLt64_13.dll", "KERNEL32.dll"]))
|
||||
(self.toolkit / "cublasLt64_13.dll").write_bytes(make_pe(["KERNEL32.dll"]))
|
||||
self.out = self.root / "out"
|
||||
self.out.mkdir()
|
||||
|
||||
def build(self, search):
|
||||
return package_engine.build(self.src, "cuda", "0.1.45.1", "windows-x86_64", self.out, archs=("sm_86",), build_id="t", search=search)
|
||||
|
||||
def test_it_bundles_the_imported_dlls_and_what_they_import(self):
|
||||
folder = self.build([self.toolkit])
|
||||
self.assertTrue((folder / "cublas64_13.dll").is_file() and (folder / "cublasLt64_13.dll").is_file())
|
||||
self.assertEqual(binary_deps.uncovered(folder), [])
|
||||
self.assertEqual(package_engine.main(["--verify", str(folder)]), 0)
|
||||
|
||||
def test_it_refuses_when_a_dll_cannot_be_found(self):
|
||||
empty = self.root / "empty"
|
||||
empty.mkdir()
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self.build([empty])
|
||||
self.assertIn("cublas64_13.dll", str(raised.exception))
|
||||
self.assertFalse(any(self.out.iterdir()) and any(p.name.startswith("0.1.45.1") for p in self.out.iterdir()))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user