Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Desktop: agents from version managers are found, and closing a chat stops all an agent started (#238)

riverisbuildingfce7879e1e5a
diff --git a/.changeset/agents-found-and-stopped.md b/.changeset/agents-found-and-stopped.md
new file mode 100644
index 0000000..1298541
--- /dev/null
+++ b/.changeset/agents-found-and-stopped.md
@@ -0,0 +1,5 @@
+---
+"@openfilm/desktop": patch
+---
+
+Agents installed with nvm, fnm, mise, Volta, asdf, Bun or pnpm are found even when the login shell does not answer, and on Windows those installed under fnm. Closing a chat stops the agent's own program and its MCP servers too, not only its adapter. On Windows, a `%` in a word given to a `.cmd` agent stays as it is.
diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjs
index fa39328..7c10a08 100644
--- a/apps/desktop/src/agents.mjs
+++ b/apps/desktop/src/agents.mjs
@@ -264,8 +264,12 @@ function run(cmd, args, timeoutMs = 10_000, { cwd, env, options } = {}) {
});
}
-/* one word of a cmd.exe command line: quoted when it has to be */
-const winArg = (a) => (/^[\w.:\\/=+@-]+$/.test(a) ? a : `"${String(a).replace(/"/g, '""')}"`);
+/**
+ * One word of a cmd.exe command line: quoted when it has to be. cmd.exe expands `%NAME%` inside quotes too, so each `%`
+ * is closed out of the quotes and escaped (`"^%"`): the program is given the word as it was, with no variable's value
+ * in it.
+ */
+export const winArg = (a) => (/^[\w.:\\/=+@-]+$/.test(a) ? a : `"${String(a).replace(/"/g, '""').replace(/%/g, '"^%"')}"`);
/** The app's own Node running a script, through as-node.mjs: what the script starts does not run Electron as Node. */
const AS_NODE = fileURLToPath(new URL('./as-node.mjs', import.meta.url));
@@ -1114,8 +1118,8 @@ export class AgentSession {
const script = harness ? fileURLToPath(new URL('./pi-agent.mjs', import.meta.url)) : native ? null : adapterScript(this.spec.adapter);
this.child = native
- ? spawn(native.cmd, native.args, { ...native.options, cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
- : spawn(node.command, node.env.ELECTRON_RUN_AS_NODE ? asNode(script) : [script], { cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
+ ? spawn(native.cmd, native.args, { ...native.options, ...OWN_GROUP, cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
+ : spawn(node.command, node.env.ELECTRON_RUN_AS_NODE ? asNode(script) : [script], { ...OWN_GROUP, cwd: this.opts.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
this.child.stderr.on('data', (d) => { this.stderr = (this.stderr + String(d)).slice(-16_000); });
LIVE.add(this);
this.child.once('exit', (code) => { LIVE.delete(this); this.exited = { code }; this.opts.onExit?.({ code, stderr: this.stderr }); });
@@ -1320,11 +1324,35 @@ export class AgentSession {
close() {
LIVE.delete(this);
try { this.conn?.close(); } catch { /* gone already */ }
- if (this.child && this.child.exitCode === null) this.child.kill('SIGTERM');
+ stopTree(this.child);
this.logging?.close();
}
}
+/**
+ * An agent's process and what it starts (the program under its adapter, its MCP servers, a command it runs) as one:
+ * a process group of its own on macOS and Linux. On Windows taskkill follows the tree instead.
+ */
+export const OWN_GROUP = windows ? {} : { detached: true };
+
+/**
+ * Stop a process started with OWN_GROUP and everything it started. Stopping it alone (the adapter, or cmd.exe in front
+ * of a .cmd) left the agent's own program and its MCP servers running, on Windows always.
+ */
+export function stopTree(child, { win = windows } = {}) {
+ if (!child?.pid || child.exitCode !== null || child.signalCode !== null) return;
+ if (win) {
+ try {
+ const taskkill = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'taskkill.exe');
+ spawn(taskkill, ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }).once('error', () => child.kill());
+ return;
+ } catch { /* taskkill could not start: the process alone, below */ }
+ } else {
+ try { process.kill(-child.pid, 'SIGTERM'); return; } catch { /* not a group of its own: the process alone, below */ }
+ }
+ try { child.kill('SIGTERM'); } catch { /* gone already */ }
+}
+
/** Every agent process this app started and has not closed: a chat's, or one opened only to ask. */
const LIVE = new Set();
diff --git a/apps/desktop/src/agents.test.mjs b/apps/desktop/src/agents.test.mjs
index 60f3782..c49c7d5 100644
--- a/apps/desktop/src/agents.test.mjs
+++ b/apps/desktop/src/agents.test.mjs
@@ -1,6 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { AgentSession, CLIENT_CAPABILITIES, agentDefaults, closeEverySession, planProblem, probeFolder, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, distinctOptions, errorCause, legacyOptions, powerShellScript, powerShellLine, powerShellWindowLaunch, terminalScript, checkAgentProgram, readAgentStatus, setChosenPaths, signInScript, turnError, signInError, codexTooOld, AGENTS, ownSignIn, codexServiceError, codexRefusal, codexNotice, explainFailure, stderrReason, withToolKind } from './agents.mjs';
+import { AgentSession, CLIENT_CAPABILITIES, agentDefaults, closeEverySession, planProblem, probeFolder, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, distinctOptions, errorCause, legacyOptions, powerShellScript, powerShellLine, powerShellWindowLaunch, terminalScript, checkAgentProgram, readAgentStatus, setChosenPaths, signInScript, turnError, signInError, codexTooOld, AGENTS, ownSignIn, codexServiceError, codexRefusal, codexNotice, explainFailure, stderrReason, withToolKind, OWN_GROUP, stopTree, winArg } from './agents.mjs';
+import { spawn } from 'node:child_process';
test('an agent that asks: yes for good where it offers that, else yes this once; nothing to say yes with is null', () => {
const options = [
@@ -536,3 +537,37 @@ test("a script the app's own Node starts runs as the main module, without ELECTR
writeFileSync(bin, "if (import.meta.main) console.log(`0.2.1 ${process.env.ELECTRON_RUN_AS_NODE ?? 'clean'} ${process.argv.slice(2).join(' ')}`);\n");
assert.deepEqual(await checkAgentProgram('deepseek', bin), { ok: true, path: bin, version: '0.2.1 clean --version' });
});
+
+test("closing an agent stops what it started too: its own program under the adapter, its MCP servers", async () => {
+ /* an adapter (the child) that starts the agent's program (the grandchild) and says its pid */
+ const adapter = `const c = require('node:child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' });
+ console.log(c.pid); setInterval(() => {}, 1000);`;
+ const child = spawn(process.execPath, ['-e', adapter], { ...OWN_GROUP, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
+ const grandchild = Number(await new Promise((done) => child.stdout.once('data', (d) => done(String(d).trim()))));
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } };
+ assert.ok(alive(grandchild));
+ const exited = new Promise((done) => child.once('exit', done));
+ stopTree(child);
+ await exited;
+ for (let i = 0; i < 50 && alive(grandchild); i += 1) await new Promise((done) => setTimeout(done, 100));
+ assert.equal(alive(grandchild), false, 'the program under the adapter is stopped with it');
+ stopTree(child);
+});
+
+test("a word for cmd.exe keeps its % as it is: no variable's value is put in its place", async () => {
+ assert.equal(winArg('C:\\Users\\someone\\codex.cmd'), 'C:\\Users\\someone\\codex.cmd');
+ assert.equal(winArg('open film'), '"open film"');
+ assert.equal(winArg('say "hi"'), '"say ""hi"""');
+ assert.equal(winArg('50% of %PATH%'), '"50"^%" of "^%"PATH"^%""');
+ if (process.platform !== 'win32') return;
+ const { spawnSync } = await import('node:child_process');
+ const { mkdtempSync, writeFileSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ /* a shim as npm writes one: it hands its words on to a program, which says what it was given */
+ const shim = join(mkdtempSync(join(tmpdir(), 'of shim ')), 'echo.cmd');
+ writeFileSync(shim, `@"${process.execPath}" -e "console.log(JSON.stringify(process.argv.slice(1)))" %*\r\n`);
+ const words = ['50% of %PATH%', 'open "film"', '%USERNAME%'];
+ const r = spawnSync(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${[shim, ...words].map(winArg).join(' ')}"`], { encoding: 'utf8', windowsVerbatimArguments: true, windowsHide: true });
+ assert.deepEqual(JSON.parse(r.stdout.trim()), words);
+});
diff --git a/apps/desktop/src/environment.mjs b/apps/desktop/src/environment.mjs
index 1f5e9ab..d281103 100644
--- a/apps/desktop/src/environment.mjs
+++ b/apps/desktop/src/environment.mjs
@@ -14,6 +14,7 @@
* can use it.
*/
import { execFile, spawn } from 'node:child_process';
+import { existsSync, readdirSync } from 'node:fs';
import { homedir, userInfo } from 'node:os';
import { isAbsolute, join } from 'node:path';
@@ -45,15 +46,52 @@ function accountShell() {
try { return userInfo().shell || null; } catch { return null; }
}
-/** Directories searched even when the login shell gives nothing usable. */
+/** A folder's subfolders named as versions (18.20.4, v22.1.0), newest first. */
+function versionsIn(root) {
+ let names;
+ try { names = readdirSync(root); } catch { return []; }
+ const parts = (name) => /^v?(\d+)\.(\d+)\.(\d+)$/.exec(name)?.slice(1).map(Number) ?? null;
+ return names.filter(parts).sort((a, b) => {
+ const [x, y] = [parts(a), parts(b)];
+ return y[0] - x[0] || y[1] - x[1] || y[2] - x[2];
+ });
+}
+
+/**
+ * The folder of each Node a version manager installed, newest first, where `npm i -g` puts an agent's command: nvm's,
+ * fnm's and mise's (on Windows fnm's, in %FNM_DIR%, %APPDATA% or %LOCALAPPDATA%). Only the shell's own files put one on
+ * the PATH, so with the login shell not answering (on Windows fnm sets it in each terminal, never in the registry) an
+ * agent installed there was not found.
+ */
+export function nodeVersionDirs(home = homedir(), { win = windows, env = process.env } = {}) {
+ const fnm = (root) => ({ root: join(root, 'node-versions'), sub: win ? ['installation'] : ['installation', 'bin'] });
+ const roots = win
+ ? (env.FNM_DIR ? [env.FNM_DIR] : [env.APPDATA, env.LOCALAPPDATA].filter(Boolean).map((d) => join(d, 'fnm'))).map(fnm)
+ : [
+ { root: join(home, '.nvm', 'versions', 'node'), sub: ['bin'] },
+ ...[join(home, '.local', 'share', 'fnm'), join(home, 'Library', 'Application Support', 'fnm'), join(home, '.fnm')].map(fnm),
+ { root: join(home, '.local', 'share', 'mise', 'installs', 'node'), sub: ['bin'] },
+ ];
+ return roots.flatMap(({ root, sub }) => versionsIn(root).map((v) => join(root, v, ...sub))).filter((d) => existsSync(d));
+}
+
+/**
+ * Directories searched even when the login shell gives nothing usable: the usual ones, the shims of version managers
+ * and package managers that install commands in the home folder (Volta, asdf, mise, Bun, pnpm, npm's own prefix), and
+ * each Node a version manager installed.
+ */
export function fallbackPathDirs(home = homedir()) {
- return [join(home, '.local', 'bin'), '/opt/homebrew/bin', '/opt/homebrew/sbin', '/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin'];
+ const managed = [join(home, '.volta', 'bin'), join(home, '.asdf', 'shims'), join(home, '.local', 'share', 'mise', 'shims'), join(home, '.bun', 'bin'),
+ join(home, 'Library', 'pnpm'), join(home, '.local', 'share', 'pnpm'), join(home, '.npm-global', 'bin'), join(home, '.nodenv', 'shims')].filter((d) => existsSync(d));
+ return [join(home, '.local', 'bin'), '/opt/homebrew/bin', '/opt/homebrew/sbin', '/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin',
+ ...managed, ...nodeVersionDirs(home, { win: false })];
}
/** The login shell's PATH first, then the fallback directories it lacks; relative and repeated entries dropped. */
export function mergePath(primary, home = homedir()) {
if (windows) {
- const dirs = [...String(primary ?? '').split(';'), join(home, '.local', 'bin'), ...(process.env.APPDATA ? [join(process.env.APPDATA, 'npm')] : [])].filter((d) => d && isAbsolute(d));
+ const dirs = [...String(primary ?? '').split(';'), join(home, '.local', 'bin'), ...(process.env.APPDATA ? [join(process.env.APPDATA, 'npm')] : []),
+ ...nodeVersionDirs(home, { win: true })].filter((d) => d && isAbsolute(d));
return [...new Map(dirs.map((d) => [d.toLowerCase(), d])).values()].join(';');
}
const dirs = [...String(primary ?? '').split(':'), ...fallbackPathDirs(home)].filter((d) => d && isAbsolute(d));
diff --git a/apps/desktop/src/environment.test.mjs b/apps/desktop/src/environment.test.mjs
index 80a360a..8e224c2 100644
--- a/apps/desktop/src/environment.test.mjs
+++ b/apps/desktop/src/environment.test.mjs
@@ -1,10 +1,13 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
-import { existsSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import {
- childEnvironment, environmentCache, expandWindowsVars, lastPathSource, loginShellVariables, macProxy, noProxyList, parseRegQuery,
- parseScutilProxy, proxyVariables, regQuery, registryVariables, shellSubset, shellVariables, windowsFreshPath, windowsProxy, withSystemProxy,
+ childEnvironment, environmentCache, expandWindowsVars, lastPathSource, loginShellVariables, macProxy, mergePath,
+ nodeVersionDirs, noProxyList, parseRegQuery, parseScutilProxy, proxyVariables, registryVariables, regQuery,
+ shellSubset, shellVariables, windowsFreshPath, windowsProxy, withSystemProxy,
} from './environment.mjs';
const PROFILE = ['C:', 'Users', 'someone'].join('\\');
@@ -155,6 +158,33 @@ test("the agents get all the person's shell sets, but what the shell and its ter
assert.deepEqual(Object.keys(shellSubset(all, '/home/me/')).sort(), ['HTTPS_PROXY', 'PATH']);
});
+test("each Node a version manager installed is searched, newest first: nvm's, fnm's and mise's; on Windows fnm's", () => {
+ const home = mkdtempSync(join(tmpdir(), 'of-nodes-'));
+ const dir = (...p) => { mkdirSync(join(home, ...p), { recursive: true }); return join(home, ...p); };
+ const nvm18 = dir('.nvm', 'versions', 'node', 'v18.20.4', 'bin');
+ const nvm22 = dir('.nvm', 'versions', 'node', 'v22.1.0', 'bin');
+ const nvm9 = dir('.nvm', 'versions', 'node', 'v9.11.2', 'bin');
+ dir('.nvm', 'versions', 'node', 'system');
+ const fnm = dir('Library', 'Application Support', 'fnm', 'node-versions', 'v20.3.0', 'installation', 'bin');
+ const mise = dir('.local', 'share', 'mise', 'installs', 'node', '24.0.1', 'bin');
+ assert.deepEqual(nodeVersionDirs(home, { win: false }), [nvm22, nvm18, nvm9, fnm, mise]);
+ /* fnm on Windows: no bin folder, the commands sit beside node.exe */
+ const winFnm = dir('Roaming', 'fnm', 'node-versions', 'v20.3.0', 'installation');
+ assert.deepEqual(nodeVersionDirs(home, { win: true, env: { APPDATA: join(home, 'Roaming'), LOCALAPPDATA: join(home, 'Local') } }), [winFnm]);
+ assert.deepEqual(nodeVersionDirs(home, { win: true, env: { FNM_DIR: join(home, 'elsewhere'), APPDATA: join(home, 'Roaming') } }), [], "FNM_DIR is fnm's only folder");
+});
+
+test("with the login shell giving nothing, the PATH still has the version managers' folders, after the usual ones", { skip: process.platform === 'win32' }, () => {
+ const home = mkdtempSync(join(tmpdir(), 'of-nodes-'));
+ const nvm = join(home, '.nvm', 'versions', 'node', 'v22.1.0', 'bin');
+ const volta = join(home, '.volta', 'bin');
+ for (const d of [nvm, volta]) mkdirSync(d, { recursive: true });
+ const dirs = mergePath('', home).split(':');
+ assert.ok(dirs.indexOf('/usr/bin') < dirs.indexOf(volta) && dirs.indexOf(volta) < dirs.indexOf(nvm), dirs.join(':'));
+ assert.ok(!dirs.includes(join(home, '.asdf', 'shims')), 'a manager not installed adds nothing');
+ assert.equal(mergePath('/mine/bin', home).split(':')[0], '/mine/bin', "the shell's own PATH comes first");
+});
+
const SCUTIL = `<dictionary> {
ExceptionsList : <array> {
0 : *.local