From d85bb21c6b03cfaa3c31e1f2cbdfd2583857ee45 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 17 Oct 2026 19:11:09 +0200 Subject: [PATCH] Linux: programs that are not Strata's own get the AppImage's original environment; folder chooser tries zenity, kdialog, portal and never fails silently --- apps/desktop/scripts/repack-appimage.sh | 8 ++ apps/host/server/agent/harness-runtime.mjs | 5 +- apps/host/server/artifacts.mjs | 3 +- apps/host/server/chat-files.mjs | 4 +- apps/host/server/external-env.mjs | 71 +++++++++++++ apps/host/server/folder-dialog.mjs | 87 ++++++++++++++-- apps/host/server/index.mjs | 8 +- apps/host/tests/external-env.test.mjs | 116 +++++++++++++++++++++ 8 files changed, 288 insertions(+), 14 deletions(-) create mode 100644 apps/host/server/external-env.mjs create mode 100644 apps/host/tests/external-env.test.mjs diff --git a/apps/desktop/scripts/repack-appimage.sh b/apps/desktop/scripts/repack-appimage.sh index c0fe4d8a..d7b36c14 100755 --- a/apps/desktop/scripts/repack-appimage.sh +++ b/apps/desktop/scripts/repack-appimage.sh @@ -49,6 +49,14 @@ for d in control harness node engine-bundle; do [ -d "$RES/$d" ] || continue rsync -aL --checksum --delete --exclude .gitignore "$RES/$d/" "$LIB/$d/" done +# The launcher records the environment the AppImage was started from, before its own hooks add the AppImage's libraries and GTK/GIO +# settings (LD_LIBRARY_PATH, GTK_*, XDG_DATA_DIRS ...). The host gives it back to every program that is not Strata's own (zenity, +# kdialog, xdg-open, the assistant's shell): apps/host/server/external-env.mjs. Without it a system program loads the AppImage's libssl +# and dies ("OPENSSL_3.2.0 not found"). The line goes right after `this_dir=...`, ahead of every hook. +if ! grep -q STRATA_ORIGINAL_ENV "$WORK/AppDir/AppRun"; then + sed -i '/^this_dir=/a # Strata: the environment this AppImage was started from (given back to programs that are not Strata'"'"'s own)\nexport STRATA_ORIGINAL_ENV="$(env -0 | base64 -w0)"' "$WORK/AppDir/AppRun" + grep -q STRATA_ORIGINAL_ENV "$WORK/AppDir/AppRun" || { echo "could not add the environment record to AppRun" >&2; exit 1; } +fi mksquashfs "$WORK/AppDir" "$WORK/app.squashfs" -root-owned -noappend -comp zstd -b 131072 -no-progress >/dev/null head -c "$OFFSET" "$IN" > "$OUT" cat "$WORK/app.squashfs" >> "$OUT" diff --git a/apps/host/server/agent/harness-runtime.mjs b/apps/host/server/agent/harness-runtime.mjs index 4a1b0d8b..5093e54c 100644 --- a/apps/host/server/agent/harness-runtime.mjs +++ b/apps/host/server/agent/harness-runtime.mjs @@ -12,6 +12,7 @@ import { spawn, spawnSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; +import { externalEnvironment } from '../external-env.mjs'; const URL_PATTERN = /http:\/\/127\.0\.0\.1:(\d+)\/\?token=([A-Za-z0-9_-]+)/; @@ -23,7 +24,9 @@ const KEEP = /^(PATH|PATHEXT|SYSTEMROOT|WINDIR|COMSPEC|TEMP|TMP|TMPDIR|HOME|USER /** The environment the agent gets: a filtered copy of the host's, plus exactly the names passed in `extra`. */ export function agentEnvironment(base = process.env, extra = {}) { const out = {}; - for (const [k, v] of Object.entries(base)) { + // The shell and tools the assistant runs for the person are the person's own programs: they get the environment the AppImage was + // started from, never Strata's bundled libraries and GTK/GIO settings (external-env.mjs). Outside an AppImage this is `base`. + for (const [k, v] of Object.entries(externalEnvironment(base))) { if (v === undefined || !KEEP.test(k) || SECRET_NAME.test(k)) continue; out[k] = v; } diff --git a/apps/host/server/artifacts.mjs b/apps/host/server/artifacts.mjs index fc8e9cb7..ac42c728 100644 --- a/apps/host/server/artifacts.mjs +++ b/apps/host/server/artifacts.mjs @@ -2,7 +2,8 @@ import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; import { mkdir, mkdtemp, realpath, stat, writeFile } from 'node:fs/promises'; import { basename, dirname, extname, join, resolve, sep } from 'node:path'; -const run=promisify(execFile); +import { externalEnvironment } from './external-env.mjs'; +const run=(command,args)=>promisify(execFile)(command,args,{env:externalEnvironment()}); // xdg-open and the apps it starts: the environment the AppImage was started from const extensions=new Set(['.md','.txt','.pdf','.html','.htm','.png','.jpg','.jpeg','.webp','.gif','.svg','.csv','.ts','.tsx','.js','.jsx','.py','.json','.css','.rs','.go','.sh','.mp4','.webm']); export async function openArtifact(body,{examplesDir,previewsDir,platform=process.platform,launch=run}) { if(!['open','reveal'].includes(body.action))throw new Error('Choose Open or Show in file explorer.'); diff --git a/apps/host/server/chat-files.mjs b/apps/host/server/chat-files.mjs index 1c182804..eb6320b1 100644 --- a/apps/host/server/chat-files.mjs +++ b/apps/host/server/chat-files.mjs @@ -12,6 +12,7 @@ import { spawn } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, realpathSync } from 'node:fs'; import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path'; import { pathToFileURL } from 'node:url'; +import { externalEnvironment } from './external-env.mjs'; /** A folder no chat may use as its project: the top of a drive, or the system's own folders. */ export function refusedFolder(dir) { @@ -74,7 +75,8 @@ export function resolveChatFile(root, rawPath) { */ export function launch(command, args, { recorder = null } = {}) { if (process.env.STRATA_OPENER === 'record' || recorder) { (recorder ?? launch.recorded).push([command, ...args]); return; } - const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: false }); + // xdg-open and the browser it starts are the system's programs: they get the environment the AppImage was started from, not Strata's libraries. + const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: false, env: externalEnvironment() }); child.on('error', () => {}); child.unref(); } diff --git a/apps/host/server/external-env.mjs b/apps/host/server/external-env.mjs new file mode 100644 index 00000000..169191ae --- /dev/null +++ b/apps/host/server/external-env.mjs @@ -0,0 +1,71 @@ +/** + * The environment for programs that are NOT part of Strata: the folder chooser (zenity, kdialog, gdbus), xdg-open and the browser it + * starts, and the shell and tools the coding assistant runs for the person. + * + * Why: the Linux AppImage starts Strata with its own libraries and settings in the environment (LD_LIBRARY_PATH, GTK_*, GIO_*, + * GSETTINGS_SCHEMA_DIR, XDG_DATA_DIRS, PYTHONHOME, ...). A system program that inherits them loads Strata's copies of libssl, GTK and + * GLib instead of its own and dies (tester report 2026-10-17: zenity "libssl.so.3: version OPENSSL_3.2.0 not found", so the folder + * picker did nothing). Programs Strata ships itself (its Python, Node and engine) keep the environment they were built for; everything + * else gets the environment the AppImage was started from. + * + * The AppImage's launcher records that original environment in STRATA_ORIGINAL_ENV (repack-appimage.sh adds the hook). An older + * AppImage without the record is cleaned instead: every variable that points into the AppImage's own folder is dropped, and its + * folders are removed from the path lists. + */ +const RECORD = 'STRATA_ORIGINAL_ENV'; + +/** Variables the AppImage tooling sets only for itself; never meant for another program. */ +const APPIMAGE_ONLY = [ + 'APPDIR', 'APPIMAGE', 'ARGV0', 'OWD', 'APPIMAGE_SILENT_INSTALL', 'APPIMAGE_EXTRACT_AND_RUN', + 'GTK_DATA_PREFIX', 'GTK_EXE_PREFIX', 'GTK_PATH', 'GTK_IM_MODULE_FILE', 'GTK_THEME', 'GDK_PIXBUF_MODULE_FILE', 'GDK_PIXBUF_MODULEDIR', + 'GSETTINGS_SCHEMA_DIR', 'GI_TYPELIB_PATH', 'GIO_MODULE_DIR', 'GIO_EXTRA_MODULES', + 'GST_REGISTRY_REUSE_PLUGIN_SCANNER', 'GST_PLUGIN_SYSTEM_PATH_1_0', 'GST_PLUGIN_PATH_1_0', 'GST_PLUGIN_SCANNER_1_0', 'GST_PTP_HELPER_1_0', + 'WEBKIT_EXEC_PATH', 'WEBKIT_INJECTED_BUNDLE_PATH', 'STRATA_ORIGINAL_ENV', 'STRATA_APPDIR', +]; +/** Lists of folders: the AppImage prepends its own; only its entries are removed. */ +const PATH_LISTS = ['PATH', 'XDG_DATA_DIRS', 'XDG_CONFIG_DIRS', 'LD_LIBRARY_PATH', 'LD_PRELOAD', 'LIBRARY_PATH', 'PYTHONPATH', 'PYTHONHOME', 'PERLLIB', 'PERL5LIB', 'QT_PLUGIN_PATH', 'QML2_IMPORT_PATH', 'GST_PLUGIN_PATH', 'GTK_PATH', 'GIO_MODULE_DIR']; + +/** The environment the program was started from, decoded from the launcher's record, or null when there is none. */ +export function recordedOriginal(env = process.env) { + const raw = env[RECORD]; + if (!raw) return null; + try { + const text = Buffer.from(raw, 'base64').toString('utf8'); + const out = {}; + for (const entry of text.split('\0')) { + const at = entry.indexOf('='); + if (at > 0) out[entry.slice(0, at)] = entry.slice(at + 1); + } + return Object.keys(out).length ? out : null; + } catch { return null; } +} + +/** `env` with everything that belongs to a running AppImage removed (no record needed). */ +export function withoutAppImage(env = process.env) { + const dir = env.APPDIR || ''; + const out = { ...env }; + const inside = value => !!dir && (value === dir || value.startsWith(`${dir}/`) || value.startsWith(`${dir}//`)); + for (const name of APPIMAGE_ONLY) delete out[name]; + if (dir) { + for (const name of Object.keys(out)) if (/^(GTK|GDK|GIO|GST|GI_|GSETTINGS|WEBKIT)/.test(name) && typeof out[name] === 'string' && out[name].includes(dir)) delete out[name]; + for (const name of PATH_LISTS) { + if (typeof out[name] !== 'string') continue; + const kept = out[name].split(':').filter(part => part && !inside(part)); + if (kept.length) out[name] = kept.join(':'); else delete out[name]; + } + } + return out; +} + +/** True when this process was started from an AppImage. */ +export const insideAppImage = (env = process.env) => !!(env.APPIMAGE || env.APPDIR); + +/** + * The environment for an external program (see the top of this file). Outside an AppImage it is `env` unchanged. + * `extra` is added last (a variable the caller really means to pass). + */ +export function externalEnvironment(env = process.env, extra = {}) { + if (!insideAppImage(env) && !env[RECORD]) return { ...env, ...extra }; + const original = recordedOriginal(env); + return { ...(original ?? withoutAppImage(env)), ...extra }; +} diff --git a/apps/host/server/folder-dialog.mjs b/apps/host/server/folder-dialog.mjs index 1748373b..ea81f95a 100644 --- a/apps/host/server/folder-dialog.mjs +++ b/apps/host/server/folder-dialog.mjs @@ -2,11 +2,13 @@ * The host's native "choose a folder" dialog, one per platform: * macOS osascript (choose folder) -- unchanged * Windows PowerShell FolderBrowserDialog (STA, topmost owner so it never opens behind the app) - * Linux zenity, then kdialog - * Where no dialog exists the caller gets { unavailable: true } and tells the person to type a path. + * Linux zenity, then kdialog, then the desktop portal (gdbus), all with the environment the AppImage was started from + * Where no dialog works the caller gets { unavailable: true } and the app shows a plain message and a field for the path. */ +import { spawn } from 'node:child_process'; import { stat } from 'node:fs/promises'; import { exec } from './util.mjs'; +import { externalEnvironment } from './external-env.mjs'; const MAC_SCRIPT = prompt => `POSIX path of (choose folder with prompt "${prompt.replace(/["\\]/g, '')}")`; @@ -44,7 +46,7 @@ const missing = error => error?.code === 'ENOENT'; * Ask for a folder. Resolves { path } | { cancelled: true } | { unavailable: true, reason }. * `run` is injectable for tests: (command, args) => Promise<{ stdout }>. */ -export async function chooseFolder(prompt, { platform = process.platform, run = exec } = {}) { +export async function chooseFolder(prompt, { platform = process.platform, run = exec, portal = portalFolder } = {}) { if (platform === 'darwin') { try { const { stdout } = await run('osascript', ['-e', MAC_SCRIPT(prompt)]); @@ -63,25 +65,96 @@ export async function chooseFolder(prompt, { platform = process.platform, run = throw new Error('The folder chooser could not open.'); } } + return chooseLinuxFolder(prompt, { run, portal }); +} + +/** A chooser that is there but broke (the display is missing, a library does not load) must say so; a bare exit 1 is a cancel. */ +const BROKEN = /unable to init server|cannot open display|can't open display|no protocol specified|error while loading shared libraries|symbol lookup error|version `[^']*' not found|cannot connect to|failed to connect|could not connect/i; +const firstLine = text => String(text ?? '').split(/\r?\n/).map(l => l.trim()).find(Boolean)?.slice(0, 160) ?? ''; + +/** + * Linux: zenity, then kdialog, then the desktop portal's file chooser through gdbus. Every one of them runs with the environment the + * AppImage was started from (external-env.mjs), not Strata's own libraries. A chooser that is missing is skipped; one that fails is + * remembered and the next is tried; when none works the answer says why and the person types the path. + */ +async function chooseLinuxFolder(prompt, { run, portal }) { + const env = externalEnvironment(); const candidates = [ ['zenity', ['--file-selection', '--directory', `--title=${prompt}`]], ['kdialog', ['--getexistingdirectory', '.', '--title', prompt]], ]; + const failures = []; for (const [command, args] of candidates) { try { - const { stdout } = await run(command, args); + const { stdout } = await run(command, args, { env }); return stdout.trim() ? { path: cleanChosenPath(stdout) } : { cancelled: true }; } catch (error) { if (missing(error)) continue; - if (error?.code === 1) return { cancelled: true }; // both tools exit 1 when the dialog is dismissed - throw new Error('The folder chooser could not open.'); + const detail = `${error?.stderr ?? ''}`; + if (error?.code === 1 && !BROKEN.test(detail)) return { cancelled: true }; // both tools exit 1 when the dialog is dismissed + failures.push(`${command}: ${firstLine(detail) || firstLine(error?.message) || `exit ${error?.code}`}`); } } - return { unavailable: true, reason: 'No folder chooser is installed (install zenity or kdialog).' }; + try { + const picked = await portal(prompt, { run, env }); + if (picked) return picked; + } catch (error) { + failures.push(`portal: ${firstLine(error?.message)}`); + } + return { + unavailable: true, failed: failures.length > 0, ...(failures.length ? { detail: failures.join('; ') } : {}), + reason: failures.length + ? `The folder chooser could not open (${failures[0]}). Install zenity or kdialog to pick a folder, or type the path.` + : 'No folder chooser was found. Install zenity or kdialog to pick a folder, or type the path.', + }; +} + +/** + * xdg-desktop-portal FileChooser through gdbus. Resolves { path } | { cancelled: true } | null when there is no portal or no gdbus. + * The answer arrives as a Response signal on the request the call returns, so a monitor is started first. + */ +export async function portalFolder(prompt, { run = exec, env = externalEnvironment(), spawnProcess = spawn, timeoutMs = 10 * 60_000 } = {}) { + const monitor = spawnProcess('gdbus', ['monitor', '--session', '--dest', 'org.freedesktop.portal.Desktop'], { env, stdio: ['ignore', 'pipe', 'ignore'] }); + let seen = ''; + let ended = false; + monitor.on('error', () => { ended = true; }); + monitor.on('close', () => { ended = true; }); + monitor.stdout?.on('data', chunk => { seen += chunk; }); + try { + let call; + try { + call = await run('gdbus', ['call', '--session', '--dest', 'org.freedesktop.portal.Desktop', '--object-path', '/org/freedesktop/portal/desktop', + '--method', 'org.freedesktop.portal.FileChooser.OpenFile', '', prompt, "{'directory': , 'modal': }"], { env }); + } catch { + return null; // no gdbus, or no portal on the session bus + } + const handle = /'(\/org\/freedesktop\/portal\/desktop\/request\/[^']+)'/.exec(call.stdout)?.[1]; + if (!handle) return null; + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const line = seen.split('\n').find(l => l.startsWith(`${handle}: org.freedesktop.portal.Request.Response`)); + if (line) { + const m = /\(uint32 (\d+), (.*)\)\s*$/.exec(line); + if (!m || m[1] !== '0') return { cancelled: true }; + const uri = /'(file:\/\/[^']*)'/.exec(m[2])?.[1]; + return uri ? { path: cleanChosenPath(decodeURIComponent(uri.replace(/^file:\/\//, ''))) } : { cancelled: true }; + } + if (ended) return null; + await new Promise(r => setTimeout(r, 100)); + } + return { cancelled: true }; + } finally { + try { monitor.kill(); } catch { /* already gone */ } + } } export const TYPE_A_PATH = 'No folder chooser is available on this system, so type the folder path instead.'; +/** The host's answer when no chooser works: a plain sentence and a code the app turns into a field for typing the path. */ +export function chooserUnavailable(picked) { + return { message: picked.failed ? picked.reason : `${TYPE_A_PATH} ${picked.reason}`, code: 'folder-chooser-unavailable', details: picked.detail }; +} + /** A typed path stands in for the dialog: it must be an absolute directory that exists. */ export async function typedFolder(value, { isAbsolute }) { const text = typeof value === 'string' ? value.trim() : ''; diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index dae32222..63210c21 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -4,7 +4,7 @@ import { createConnectorInstaller } from './cloudflared-install.mjs'; import { openArtifact } from './artifacts.mjs'; import { saveSnapshot } from './snapshot.mjs'; import { resolvePython, shellPrefix } from './python-resolver.mjs'; -import { chooseFolder, typedFolder, TYPE_A_PATH } from './folder-dialog.mjs'; +import { chooseFolder, chooserUnavailable, typedFolder } from './folder-dialog.mjs'; import { createLocalShare } from './local-share.mjs'; import { createTaskService, validateTask } from './tasks.mjs'; import { createAgentTaskRunner } from './agent/task-run.mjs'; @@ -935,7 +935,7 @@ async function api(req, res, path, method, url) { /* "Use a local GGUF": pick (or type) the folder, and Control says what is in it. Nothing is copied or changed. */ const typed=await typedFolder((await readBody(req)).path,{isAbsolute}); const picked=typed?{path:typed}:await chooseFolder('Choose the folder that holds your GGUF files'); - if(picked.unavailable)return error(res,501,`${TYPE_A_PATH} ${picked.reason}`); + if(picked.unavailable){const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});}; if(picked.cancelled)return json(res,200,{cancelled:true}); return json(res,200,{path:picked.path,preview:await native.localPreview(picked.path)});} if(path==='/api/native/benchmark'&&method==='GET')return json(res,200,native.benchmarkReport()); @@ -1680,7 +1680,7 @@ async function api(req, res, path, method, url) { // The dialog is the normal path; a typed `path` in the body stands in where none exists. const typed = await typedFolder((await readBody(req)).path, { isAbsolute }); const picked = typed ? { path: typed } : await chooseFolder('Choose a skill folder (it should contain SKILL.md)'); - if (picked.unavailable) return error(res, 501, `${TYPE_A_PATH} ${picked.reason}`); + if (picked.unavailable) {const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});}; if (picked.cancelled) return json(res, 200, { cancelled: true }); const chosen = picked.path; const base = basename(chosen); @@ -1705,7 +1705,7 @@ async function api(req, res, path, method, url) { try { const typed = await typedFolder((await readBody(req)).path, { isAbsolute }); const picked = typed ? { path: typed } : await chooseFolder('Choose a folder for Strata'); - if (picked.unavailable) return error(res, 501, `${TYPE_A_PATH} ${picked.reason}`); + if (picked.unavailable) {const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});}; if (picked.cancelled) return json(res, 200, { cancelled: true }); return json(res, 200, { path: picked.path }); } catch (e) { diff --git a/apps/host/tests/external-env.test.mjs b/apps/host/tests/external-env.test.mjs new file mode 100644 index 00000000..80a8ac75 --- /dev/null +++ b/apps/host/tests/external-env.test.mjs @@ -0,0 +1,116 @@ +/** + * Programs that are not Strata's own (zenity, kdialog, xdg-open, the assistant's shell) get the environment the Linux AppImage was + * started from, not the AppImage's libraries and settings (tester report 2026-10-17: zenity died with + * "libssl.so.3: version OPENSSL_3.2.0 not found" and the folder picker did nothing). + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { externalEnvironment, recordedOriginal, withoutAppImage } from '../server/external-env.mjs'; +import { chooseFolder, chooserUnavailable, portalFolder } from '../server/folder-dialog.mjs'; +import { agentEnvironment } from '../server/agent/harness-runtime.mjs'; + +const APPDIR = '/tmp/.mount_StrataAbc'; +const leaky = { + APPDIR, APPIMAGE: '/home/u/Strata.AppImage', ARGV0: 'Strata', + LD_LIBRARY_PATH: `${APPDIR}/usr/lib:${APPDIR}/usr/lib/x86_64-linux-gnu:/opt/cuda/lib64`, + PATH: `${APPDIR}/usr/bin:/usr/local/bin:/usr/bin`, + XDG_DATA_DIRS: `${APPDIR}/usr/share:/usr/share:/usr/local/share`, + GTK_PATH: `${APPDIR}//usr/lib/gtk-3.0`, GIO_MODULE_DIR: `${APPDIR}//usr/lib/gio/modules`, GDK_PIXBUF_MODULE_FILE: `${APPDIR}//usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache`, + GSETTINGS_SCHEMA_DIR: `${APPDIR}//usr/share/glib-2.0/schemas`, PYTHONHOME: `${APPDIR}/usr/python`, HOME: '/home/u', DISPLAY: ':0', +}; + +test('without a record, everything that points into the AppImage is removed and the user\'s own entries stay', () => { + const env = externalEnvironment(leaky); + assert.equal(env.APPDIR, undefined); + assert.equal(env.APPIMAGE, undefined); + assert.equal(env.LD_LIBRARY_PATH, '/opt/cuda/lib64', 'only the AppImage\'s folders go from the list'); + assert.equal(env.PATH, '/usr/local/bin:/usr/bin'); + assert.equal(env.XDG_DATA_DIRS, '/usr/share:/usr/local/share'); + for (const name of ['GTK_PATH', 'GIO_MODULE_DIR', 'GDK_PIXBUF_MODULE_FILE', 'GSETTINGS_SCHEMA_DIR', 'PYTHONHOME']) assert.equal(env[name], undefined, name); + assert.equal(env.HOME, '/home/u'); + assert.equal(env.DISPLAY, ':0'); +}); + +test('with the launcher\'s record, the original environment is restored exactly', () => { + const original = { PATH: '/usr/bin', LD_LIBRARY_PATH: '/mine', HOME: '/home/u', DISPLAY: ':1' }; + const record = Buffer.from(Object.entries(original).map(([k, v]) => `${k}=${v}`).join('\0') + '\0').toString('base64'); + const env = externalEnvironment({ ...leaky, STRATA_ORIGINAL_ENV: record }); + assert.deepEqual(env, original); + assert.deepEqual(recordedOriginal({ STRATA_ORIGINAL_ENV: record }), original); + assert.equal(recordedOriginal({ STRATA_ORIGINAL_ENV: '!!!' }), null); +}); + +test('outside an AppImage nothing changes', () => { + const plain = { PATH: '/usr/bin', LD_LIBRARY_PATH: '/opt/x/lib', HOME: '/h' }; + assert.deepEqual(externalEnvironment(plain), plain); + assert.deepEqual(externalEnvironment(plain, { A: '1' }), { ...plain, A: '1' }); + assert.deepEqual(withoutAppImage(plain), plain); +}); + +test('the coding assistant\'s shell does not inherit the AppImage\'s settings either', () => { + const env = agentEnvironment({ ...leaky, SOME_TOKEN: 'x' }, { DSH_HOME: '/h' }); + assert.equal(env.LD_LIBRARY_PATH, undefined); + assert.ok(!/\.mount_/.test(JSON.stringify(env)), JSON.stringify(env)); + assert.equal(env.DSH_HOME, '/h'); + assert.equal(env.SOME_TOKEN, undefined); +}); + +const failure = (code, stderr = '') => Object.assign(new Error(`exit ${code}`), { code, stderr }); + +test('Linux folder chooser: a zenity that breaks is reported, not taken for a cancel, and the next chooser is tried', async () => { + const seen = []; + const libssl = failure(127, 'zenity: error while loading shared libraries: libssl.so.3: version `OPENSSL_3.2.0\' not found'); + const run = async (command, args, options) => { seen.push({ command, env: options?.env }); if (command === 'zenity') throw libssl; return { stdout: '/home/u/Models/\n' }; }; + const old = { ...process.env }; + Object.assign(process.env, leaky); + try { + const picked = await chooseFolder('Pick', { platform: 'linux', run, portal: async () => null }); + assert.deepEqual(picked, { path: '/home/u/Models' }); + assert.deepEqual(seen.map(s => s.command), ['zenity', 'kdialog']); + for (const s of seen) { assert.equal(s.env.LD_LIBRARY_PATH, '/opt/cuda/lib64'); assert.equal(s.env.APPDIR, undefined); } + // every chooser broken or missing: a plain sentence that names what to do, never a silent nothing + const none = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw libssl; }, portal: async () => null }); + assert.equal(none.unavailable, true); + assert.equal(none.failed, true); + assert.match(none.reason, /Install zenity or kdialog to pick a folder, or type the path/); + const answer = chooserUnavailable(none); + assert.equal(answer.code, 'folder-chooser-unavailable'); + const missingAll = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure('ENOENT'); }, portal: async () => null }); + assert.equal(missingAll.unavailable, true); + assert.match(missingAll.reason, /zenity or kdialog/); + // a plain exit 1 is still a cancel; so is exit 1 with harmless warnings + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure(1, 'Gtk-Message: Failed to load module "canberra-gtk-module"'); }, portal: async () => null }), { cancelled: true }); + // a zenity that cannot reach the display exits 1 too: that is a failure + const noDisplay = await chooseFolder('Pick', { platform: 'linux', run: async () => { throw failure(1, 'Unable to init server: Could not connect: Connection refused'); }, portal: async () => null }); + assert.equal(noDisplay.unavailable, true); + } finally { for (const k of Object.keys(leaky)) { if (old[k] === undefined) delete process.env[k]; else process.env[k] = old[k]; } } +}); + +test('Linux folder chooser: the desktop portal answers when zenity and kdialog are not installed', async () => { + const run = async () => { throw failure('ENOENT'); }; + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run, portal: async () => ({ path: '/home/u/Pics' }) }), { path: '/home/u/Pics' }); + assert.deepEqual(await chooseFolder('Pick', { platform: 'linux', run, portal: async () => ({ cancelled: true }) }), { cancelled: true }); +}); + +test('portalFolder reads the Response signal of its request', async () => { + const handle = '/org/freedesktop/portal/desktop/request/1_42/t1'; + const monitor = new EventEmitter(); + monitor.stdout = new EventEmitter(); + monitor.kill = () => { monitor.exitCode = 0; }; + monitor.exitCode = null; + const spawnProcess = () => monitor; + const run = async (command, args) => { + assert.equal(command, 'gdbus'); + assert.ok(args.includes('org.freedesktop.portal.FileChooser.OpenFile')); + queueMicrotask(() => monitor.stdout.emit('data', `${handle}: org.freedesktop.portal.Request.Response (uint32 0, {'uris': <['file:///home/u/My%20Models']>})\n`)); + return { stdout: `(objectpath '${handle}',)\n` }; + }; + assert.deepEqual(await portalFolder('Pick', { run, env: {}, spawnProcess }), { path: '/home/u/My Models' }); + const cancel = new EventEmitter(); + cancel.stdout = new EventEmitter(); cancel.kill = () => {}; cancel.exitCode = null; + const run2 = async () => { queueMicrotask(() => cancel.stdout.emit('data', `${handle}: org.freedesktop.portal.Request.Response (uint32 1, {})\n`)); return { stdout: `(objectpath '${handle}',)\n` }; }; + assert.deepEqual(await portalFolder('Pick', { run: run2, env: {}, spawnProcess: () => cancel }), { cancelled: true }); + const none = new EventEmitter(); none.stdout = new EventEmitter(); none.kill = () => {}; none.exitCode = null; + assert.equal(await portalFolder('Pick', { run: async () => { throw failure('ENOENT'); }, env: {}, spawnProcess: () => none }), null); +});