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 the makers' desktop apps, and never an editor in their place (#110)
riverisbuilding7d352837b967
diff --git a/.changeset/agents-from-desktop-apps.md b/.changeset/agents-from-desktop-apps.mdnew file mode 100644index 0000000..8091fd2--- /dev/null+++ b/.changeset/agents-from-desktop-apps.md@@ -0,0 +1,6 @@+---+"@openfilm/desktop": patch+"openfilm": patch+---++Desktop: agents work for people who installed only the maker's app: Claude Code and OpenCode from inside their apps, and an Install button that runs the official installer for the others. The Cursor editor is never started in place of Cursor's agent.diff --git a/apps/desktop/src/agent-installation.mjs b/apps/desktop/src/agent-installation.mjsindex 15312d5..8d53739 100644--- a/apps/desktop/src/agent-installation.mjs+++ b/apps/desktop/src/agent-installation.mjs@@ -21,69 +21,128 @@ export const AGENT_PROGRAMS = Object.freeze({claude: { names: ['claude'] },codex: { names: ['codex'] },copilot: { names: ['copilot'] },- /* Cursor's installer names it `agent`, and `cursor-agent` as before; a program called `agent` counts only when it is- Cursor's (its own folder is cursor-agent), as other tools are called that too */- cursor: { names: ['cursor-agent', 'agent'], ours: (file, name) => name === 'cursor-agent' || inCursorFolder(file) },+ /* Cursor's installer names it `agent`, and `cursor-agent` as before; either counts only in Cursor's own folder+ (notTheAgent), as other tools are called `agent` too. On Windows that folder is %LOCALAPPDATA%\cursor-agent */+ cursor: { names: ['cursor-agent', 'agent'], dirs: (home, win) => (win ? [join(localAppData(home), 'cursor-agent')] : []) },opencode: { names: ['opencode'], dirs: (home) => [join(home, '.opencode', 'bin')] },- codebuddy: { names: ['codebuddy', 'cbc'] },- qwen: { names: ['qwen'] },+ /* CodeBuddy's own installer keeps it in %LOCALAPPDATA%\codebuddy\bin on Windows */+ codebuddy: { names: ['codebuddy', 'cbc'], dirs: (home, win) => (win ? [join(localAppData(home), 'codebuddy', 'bin')] : []) },+ /* Qwen Code's own installer keeps it in %LOCALAPPDATA%\qwen-code\bin on Windows */+ qwen: { names: ['qwen'], dirs: (home, win) => (win ? [join(localAppData(home), 'qwen-code', 'bin')] : []) },/* Kimi Code's own installer keeps it in ~/.kimi-code/bin; kimi-cli (uv) puts it in ~/.local/bin */kimi: { names: ['kimi'], dirs: (home) => [join(home, '.kimi-code', 'bin')] },/* MiniMax Code's own installer keeps it in ~/.minimax-code/bin */minimax: { names: ['mcode'], dirs: (home) => [join(home, '.minimax-code', 'bin')] },});-/** Whether a program is the one in Cursor's own folder (…/cursor-agent/…), followed through its link. */+/** %LOCALAPPDATA% (Windows). */+const localAppData = (home) => process.env.LOCALAPPDATA || join(home, 'AppData', 'Local');++/**+ * Whether a program is in Cursor's own folder (…/cursor-agent/…, or Homebrew's cursor-cli), followed through its link.+ */export function inCursorFolder(file) {let real = file;try { real = realpathSync(file); } catch { /* as it is */ }- return /[\\/]cursor-agent[\\/]/i.test(real);+ return /[\\/](?:cursor-agent|Caskroom[\\/]cursor-cli)[\\/]/i.test(real);+}++/**+ * Where editors keep their own launchers, never an agent: VS Code, Cursor and the like keep their command (`code`,+ * `cursor`) in resources/app/bin (inside the .app on a Mac). The Windows .cmd there runs resources/app/out/cli.js,+ * which opens the editor with whatever it is given as files to open.+ */+const LAUNCHERS = [+ /[\\/]resources[\\/]app[\\/]bin[\\/]/i,+ /[\\/]app[\\/]out[\\/]cli\.js$/i,+ /[\\/]Programs[\\/]cursor[\\/]/i,+ /[\\/](?:Microsoft VS Code|Visual Studio Code)[^\\/]*[\\/]/i,+];++/**+ * Why a program found or chosen for an agent is not the agent, or null: `app`, an editor's or a desktop app's own+ * launcher (on Windows, a window program too); `not-cursor-agent`, one for Cursor outside Cursor's own folder.+ * `chosen`: what the person chose, when `file` is what it runs.+ * @returns {'app' | 'not-cursor-agent' | null}+ */+export function notTheAgent(id, file, { chosen = null, win = windows } = {}) {+ const real = (p) => { try { return realpathSync(p); } catch { return p; } };+ const paths = [file, real(file), ...(chosen ? [chosen, real(chosen)] : [])];+ if (paths.some((p) => LAUNCHERS.some((re) => re.test(p)))) return 'app';+ if (win && /\.exe$/i.test(file) && exeSubsystem(real(file)) === WINDOW_SUBSYSTEM) return 'app';+ if (id === 'cursor' && !inCursorFolder(file)) return 'not-cursor-agent';+ return null;}export function executableFile(path) {try { accessSync(path, constants.X_OK); return statSync(path).isFile(); } catch { return false; }}-/**- * Whether a file is a Windows program for the console, by its header and without starting it: a window program (a- * desktop app's own, as `app\Codex.exe` in the Codex Store app is) would open its window, and answers nothing.- */-export function consoleProgram(path) {+/* a Windows program's subsystem: 3 is the console, 2 a window */+const CONSOLE_SUBSYSTEM = 3;+const WINDOW_SUBSYSTEM = 2;++/** A Windows program's subsystem, read from its header without starting it; null when it is not one or can't be read. */+function exeSubsystem(path) {let fd;try {fd = openSync(path, 'r');const head = Buffer.alloc(4096);const read = readSync(fd, head, 0, head.length, 0);- if (read < 64 || head.toString('latin1', 0, 2) !== 'MZ') return false;+ if (read < 64 || head.toString('latin1', 0, 2) !== 'MZ') return null;const pe = head.readUInt32LE(0x3c);- /* the subsystem sits at the same place in 32- and 64-bit headers: 3 is the console, 2 a window */- if (pe + 0x5e > read || head.toString('latin1', pe, pe + 4) !== 'PE\0\0') return false;- return head.readUInt16LE(pe + 0x5c) === 3;+ /* the subsystem sits at the same place in 32- and 64-bit headers */+ if (pe + 0x5e > read || head.toString('latin1', pe, pe + 4) !== 'PE\0\0') return null;+ return head.readUInt16LE(pe + 0x5c);} catch {- return false;+ return null;} finally {if (fd !== undefined) closeSync(fd);}}/**- * Claude Code as the Claude app keeps it: one folder per version under Application Support, newest first, the program- * either straight inside (`<version>/claude.app`) or one folder down (`<version>/<build>/claude.app`, newer apps).+ * Whether a file is a Windows program for the console, by its header and without starting it: a window program (a+ * desktop app's own, as `app\Codex.exe` in the Codex Store app is) would open its window, and answers nothing.+ */+export function consoleProgram(path) {+ return exeSubsystem(path) === CONSOLE_SUBSYSTEM;+}++/**+ * Claude Code as the Claude app keeps it: one folder per version, newest first, the program either straight inside+ * (`<version>/claude.app`) or one folder down (`<version>/<build>/claude.app`, newer apps). On a Mac under+ * Application Support; on Windows `claude.exe` under %APPDATA%\Claude, or the same folder of the app from the+ * Microsoft Store (its own copy of %APPDATA% under Packages\Claude_…): the newest of them.*/-export function claudeAppCli(home = homedir()) {- const root = join(home, 'Library/Application Support/Claude/claude-code');+export function claudeAppCli(home = homedir(), { win = windows } = {}) {+ const program = win ? 'claude.exe' : 'claude.app/Contents/MacOS/claude';+ const usable = win ? existsFile : executableFile;const inside = (dir) => {- const direct = join(dir, 'claude.app/Contents/MacOS/claude');- if (executableFile(direct)) return direct;+ const direct = join(dir, program);+ if (usable(direct)) return direct;let builds = [];try { builds = readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && d.name !== 'claude.app').map((d) => d.name); } catch { return null; }- return builds.map((b) => join(dir, b, 'claude.app/Contents/MacOS/claude')).find(executableFile) ?? null;+ return builds.map((b) => join(dir, b, program)).find(usable) ?? null;};- try {- return readdirSync(root).filter((v) => /^\d+(\.\d+)*$/.test(v))- .sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))- .map((v) => inside(join(root, v))).find(Boolean) ?? null;- } catch { return null; /* the Claude app has not downloaded Claude Code */ }+ const found = [];+ for (const root of claudeAppRoots(home, win)) {+ let versions = [];+ try { versions = readdirSync(root).filter((v) => /^\d+(\.\d+)*$/.test(v)); } catch { continue; /* the Claude app has not downloaded Claude Code */ }+ for (const version of versions) found.push({ version, root });+ }+ return found.sort((a, b) => b.version.localeCompare(a.version, undefined, { numeric: true }))+ .map(({ version, root }) => inside(join(root, version))).find(Boolean) ?? null;+}++/** Where the Claude app keeps Claude Code's versions. */+function claudeAppRoots(home, win) {+ if (!win) return [join(home, 'Library/Application Support/Claude/claude-code')];+ const appData = process.env.APPDATA || join(home, 'AppData', 'Roaming');+ const packages = join(localAppData(home), 'Packages');+ let store = [];+ try { store = readdirSync(packages).filter((d) => /^Claude_/i.test(d)).map((d) => join(packages, d, 'LocalCache', 'Roaming', 'Claude', 'claude-code')); } catch { /* none */ }+ return [join(appData, 'Claude', 'claude-code'), ...store];}/**@@ -104,11 +163,11 @@ export function claudeVersion(file) {return real.split(/[\\/]/).reverse().find((part) => /^\d+\.\d+\.\d+$/.test(part)) ?? null;}-/** What versions of Codex said of themselves (`codex --version`), by program and its time: each asked once. */-const codexAsked = new Map();+/** What programs said of their version (`--version`), by program and its time: each asked once. */+const versionsAsked = new Map();-/** What a Codex program says its version is (`codex-cli 0.163.0`); null when it says nothing in two seconds. */-function askCodexVersion(/** @type {string} */ file) {+/** What a program says its version is (`codex-cli 0.163.0`, `opencode v2.0.24`); null when it says nothing in two seconds. */+function askVersion(/** @type {string} */ file) {/* a `.cmd` shim cannot be started without a shell; npm's says its version in its package.json anyway */if (/\.(cmd|bat)$/i.test(file)) return null;try {@@ -120,26 +179,49 @@ function askCodexVersion(/** @type {string} */ file) {}/**- * Which Codex a program is: npm's says it in its package.json (`@openai/codex`, or the platform package its program- * is in), Homebrew's folder is named for it (`Caskroom/codex/0.163.0/…`); a copy inside an app (Codex.app,- * ChatGPT.app, a Store app) says it when asked (`--version`), once. Null when it can't be told.- * @param {string} file @param {{ ask?: (file: string) => string | null }} [o]+ * Which version a program is: npm's says it in its package.json (`ours`: the package's names), a folder can be named+ * for it (Homebrew's `Caskroom/codex/0.163.0/…`), an app can keep it in a file beside it (`opencode-cli.version`);+ * else it says when asked (`--version`), once. Null when it can't be told.+ * @param {string} file @param {{ ours: (name: string) => boolean, ask: (file: string) => string | null }} o*/-export function codexVersion(file, { ask = askCodexVersion } = {}) {+function programVersion(file, { ours, ask }) {let real;try { real = realpathSync(file); } catch { return null; }for (let dir = dirname(real), up = 0; up < 6; dir = dirname(dir), up += 1) {try {const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));- if (typeof pkg.name === 'string' && pkg.name.startsWith('@openai/codex') && typeof pkg.version === 'string') return pkg.version.replace(/-.*$/, '');+ if (typeof pkg.name === 'string' && ours(pkg.name) && typeof pkg.version === 'string') return pkg.version.replace(/-.*$/, '');} catch { /* not here */ }}const named = real.split(/[\\/]/).reverse().find((part) => /^\d+\.\d+\.\d+$/.test(part));if (named) return named;+ try {+ const beside = readFileSync(`${real}.version`, 'utf8').trim();+ if (/^\d+\.\d+\.\d+$/.test(beside)) return beside;+ } catch { /* none */ }let key;try { key = `${real}\0${statSync(real).mtimeMs}`; } catch { return null; }- if (!codexAsked.has(key)) codexAsked.set(key, ask(real));- return codexAsked.get(key) ?? null;+ if (!versionsAsked.has(key)) versionsAsked.set(key, ask(real));+ return versionsAsked.get(key) ?? null;+}++/**+ * Which Codex a program is: npm's says it in its package.json (`@openai/codex`, or the platform package its program+ * is in), Homebrew's folder is named for it (`Caskroom/codex/0.163.0/…`); a copy inside an app (Codex.app,+ * ChatGPT.app, a Store app) says it when asked (`--version`), once. Null when it can't be told.+ * @param {string} file @param {{ ask?: (file: string) => string | null }} [o]+ */+export function codexVersion(file, { ask = askVersion } = {}) {+ return programVersion(file, { ours: (name) => name.startsWith('@openai/codex'), ask });+}++/**+ * Which OpenCode a program is: npm's package (`opencode-ai`, or its platform package), Homebrew's folder, the file+ * OpenCode.app keeps beside its copy (`opencode-cli.version`), else what it says when asked.+ * @param {string} file @param {{ ask?: (file: string) => string | null }} [o]+ */+export function opencodeVersion(file, { ask = askVersion } = {}) {+ return programVersion(file, { ours: (name) => name === 'opencode-ai' || name.startsWith('opencode-'), ask });}/** Whether version `a` is later than `b` (dotted numbers); false when either is unknown. */@@ -223,12 +305,17 @@ const scriptFirst = (rel) => (/\.(?:c|m)?js$/i.test(rel) ? 0 : /\.exe$/i.test(re* What a `.cmd` shim runs (Windows): the package's script or program, which can be started without a shell (a `.cmd`* cannot be). Yarn's shim runs another shim, which is read in turn. Codex's script only starts its own program, so* the program itself, for this machine's chip; when there is none, not the script (the chat starts Codex as a shell- * command, which a script is not): the shim it came from instead. Null when the shim says nothing that is there.+ * command, which a script is not): the shim it came from instead. Null when the shim says nothing that is there, or+ * runs a Node of the package's own.*/export function cmdTarget(cmd, depth = 0) {let text = '';try { text = readFileSync(cmd, 'utf8'); } catch { return null; }- const rels = [...new Set([...text.matchAll(SHIM_TARGET)].map((m) => m[1]))]+ const named = [...new Set([...text.matchAll(SHIM_TARGET)].map((m) => m[1]))];+ /* a package that runs on a Node of its own (Cursor's agent: its native parts are built for it), not one npm may put+ beside the shim: the shim itself, which starts that Node */+ if (named.some((rel) => /[\\/]node\.exe$/i.test(rel))) return null;+ const rels = named.filter((rel) => !/(?:^|[\\/])node\.exe$/i.test(rel)).sort((a, b) => scriptFirst(a) - scriptFirst(b));for (const rel of rels) {@@ -271,6 +358,14 @@ function codexInApps(/** @type {string[]} */ applicationDirs) {return applicationDirs.flatMap((dir) => ['Codex.app', 'ChatGPT.app'].flatMap((app) => CODEX_IN_APP.map((p) => join(dir, app, p)))).filter(executableFile);}+/* where OpenCode is inside OpenCode.app, its desktop app (macOS) */+const OPENCODE_IN_APP = 'Contents/Resources/opencode-cli';++/** The copies of OpenCode inside OpenCode.app in these folders. */+function opencodeInApps(/** @type {string[]} */ applicationDirs) {+ return applicationDirs.map((dir) => join(dir, 'OpenCode.app', OPENCODE_IN_APP)).filter(executableFile);+}+/*** The program the person chose for an agent, as it can be started: a `.cmd` shim's target, the `.cmd` beside a* PowerShell shim (`.ps1`), the program inside a folder or an app chosen instead of it. Null when it is not there.@@ -280,7 +375,7 @@ export function chosenProgram(path, { names = [], win = windows } = {}) {let folder = false;try { folder = statSync(path).isDirectory(); } catch { /* a file, or not there */ }if (folder) {- const inApp = /\.app$/i.test(path) ? [...CODEX_IN_APP, ...names.map((n) => `Contents/MacOS/${n}`)].map((p) => join(path, p)).find(executableFile) : null;+ const inApp = /\.app$/i.test(path) ? [...CODEX_IN_APP, OPENCODE_IN_APP, ...names.map((n) => `Contents/MacOS/${n}`)].map((p) => join(path, p)).find(executableFile) : null;return inApp ?? names.map((n) => findExecutable(n, [path, join(path, 'bin')], { PATH: '' }, { win })).find(Boolean) ?? null;}if (win) {@@ -296,59 +391,126 @@ export function chosenProgram(path, { names = [], win = windows } = {}) {/*** The command line program, or the copy inside the maker's own desktop app (many people only ever installed the- * app): Codex ships inside Codex.app and ChatGPT.app; the Claude app keeps Claude Code under Application Support, one- * folder per version, the newest used. `chosen`: the program the person chose, first. `others`: programs found some- * other way (a Store app's own copy, agents.mjs), after the rest. `source` says which it is: chosen · path · app.+ * app): Codex ships inside Codex.app and ChatGPT.app, OpenCode inside OpenCode.app; the Claude app keeps Claude Code+ * in its own folder, one folder per version, the newest used. `chosen`: the program the person chose, first.+ * `others`: programs found some other way (a Store app's own copy, agents.mjs), after the rest. `source` says which it+ * is: chosen · path · app. An editor's or a desktop app's own launcher is never taken for the agent (notTheAgent).*/export function detectAgentInstallation(id, { home = homedir(), env = process.env, pathDirs = HOME_BIN_CANDIDATES(home),- applicationDirs = ['/Applications', join(home, 'Applications')], chosen = null, others = [], win = windows, codexVersionOf = codexVersion } = {}) {+ applicationDirs = ['/Applications', join(home, 'Applications')], chosen = null, others = [], win = windows, codexVersionOf = codexVersion,+ opencodeVersionOf = opencodeVersion } = {}) {const program = AGENT_PROGRAMS[id] ?? { names: [id] };const install = AGENT_DOWNLOADS[id] ?? null;const picked = chosen ? chosenProgram(chosen, { names: program.names, win }) : null;- if (picked) return { installed: true, cli: picked, source: 'chosen', install };- const dirs = [...pathDirs, ...(program.dirs?.(home) ?? [])];+ if (picked && !notTheAgent(id, picked, { chosen, win })) return { installed: true, cli: picked, source: 'chosen', install };+ const dirs = [...pathDirs, ...(program.dirs?.(home, win) ?? [])];let cli = null;for (const name of program.names) {if (cli) break;- if (!program.ours) { cli = findExecutable(name, dirs, env, { win }); continue; }- /* each folder in turn: another program by that name earlier on the PATH does not hide the agent's */+ /* each folder in turn: a program by that name that is not the agent (an editor's launcher, another tool's+ `agent`) does not hide the agent's own in a later folder */for (const dir of unique([...pathIn(env).split(win ? ';' : delimiter), ...dirs], win)) {const file = findExecutable(name, [dir], { PATH: '' }, { win });- if (file && program.ours(file, name)) { cli = file; break; }+ if (file && !notTheAgent(id, file, { win })) { cli = file; break; }}}+ const usable = (file) => (win ? presentFile(file) : executableFile(file));+ /* copies kept up to date by the maker's app (Codex: or a Store app), and how their version is told */+ const copies = id === 'codex' ? [...codexInApps(applicationDirs), ...others.filter(usable)] : id === 'opencode' ? opencodeInApps(applicationDirs) : [];+ const versionOf = id === 'opencode' ? opencodeVersionOf : codexVersionOf;if (cli) {/* Claude Code both on the PATH (an npm install that is never updated, say) and in the Claude app, which keeps itsown up to date: the later one, whose models are the current ones. One whose version can't be told stays. */- const inApp = id === 'claude' ? claudeAppCli(home) : null;+ const inApp = id === 'claude' ? claudeAppCli(home, { win }) : null;if (inApp && laterVersion(claudeVersion(inApp), claudeVersion(cli))) return { installed: true, cli: inApp, source: 'app', install };- /* Codex the same: one installed by npm long ago beside the copy in Codex.app, ChatGPT.app or a Store app, which- keep theirs up to date. Its models are the ones its version is offered, so the later one is used */- if (id === 'codex') {- const copies = [...codexInApps(applicationDirs), ...others.filter((file) => (win ? presentFile(file) : executableFile(file)))];- const mine = copies.length ? codexVersionOf(cli) : null;- let newest = null;- for (const copy of copies) {- const version = codexVersionOf(copy);- if (laterVersion(version, newest?.version ?? mine)) newest = { copy, version };- }- if (newest) return { installed: true, cli: newest.copy, source: 'app', install };+ /* Codex and OpenCode the same: one installed long ago beside the copy in their app (Codex: or a Store app), which+ keeps its own up to date. Its models are the ones its version is offered, so the later one is used */+ const mine = copies.length ? versionOf(cli) : null;+ let newest = null;+ for (const copy of copies) {+ const version = versionOf(copy);+ if (laterVersion(version, newest?.version ?? mine)) newest = { copy, version };}+ if (newest) return { installed: true, cli: newest.copy, source: 'app', install };return { installed: true, cli, source: 'path', install };}- if (id === 'codex') cli = codexInApps(applicationDirs)[0] ?? null;- if (!cli && id === 'claude') cli = claudeAppCli(home);- if (!cli) cli = others.find((file) => (win ? presentFile(file) : executableFile(file))) ?? null;+ cli = copies[0] ?? null;+ if (!cli && id === 'claude') cli = claudeAppCli(home, { win });+ if (!cli) cli = others.find(usable) ?? null;return { installed: Boolean(cli), cli, source: cli ? 'app' : null, install };}+/**+ * The maker's desktop apps an agent's own program does not come with (an editor among them), by agent: their bundle on+ * a Mac, and on Windows their folder (under %LOCALAPPDATA%\Programs, most of them); `name` is what the person knows+ * them by. VS Code counts for GitHub Copilot only with its Copilot extension. Claude's: Claude Code comes once its+ * Code tab is opened.+ */+const DESKTOP_APPS = {+ claude: { name: 'Claude', mac: /^Claude\.app$/i, win: (local) => [join(local, 'AnthropicClaude'), ...folders(join(local, 'Packages'), /^Claude_/i)] },+ copilot: { name: 'VS Code', mac: /^Visual Studio Code.*\.app$/i, win: (local) => folders(join(local, 'Programs'), /^Microsoft VS Code/i),+ with: (home) => folders(join(home, '.vscode', 'extensions'), /^github\.copilot/i).length > 0 },+ cursor: { name: 'Cursor', mac: /^Cursor\.app$/i, win: (local) => folders(join(local, 'Programs'), /^cursor$/i) },+ codebuddy: { name: 'CodeBuddy', mac: /^CodeBuddy.*\.app$/i, win: (local) => folders(join(local, 'Programs'), /^CodeBuddy/i) },+ kimi: { name: 'Kimi', mac: /^Kimi.*\.app$/i, win: (local) => folders(join(local, 'Programs'), /^Kimi/i) },+ minimax: { name: 'MiniMax', mac: /^MiniMax.*\.app$/i, win: (local) => folders(join(local, 'Programs'), /^MiniMax/i) },+};++/** The folders in a folder whose names match. */+function folders(dir, re) {+ try { return readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && re.test(d.name)).map((d) => join(dir, d.name)); } catch { return []; }+}++/**+ * The name of the maker's desktop app when it is installed (DESKTOP_APPS), or null: told from where it is, nothing+ * started. For an agent whose own program is not found: the app is here, its command-line agent is not.+ */+export function desktopApp(id, { home = homedir(), applicationDirs = ['/Applications', join(home, 'Applications')], win = windows } = {}) {+ const app = DESKTOP_APPS[id];+ if (!app) return null;+ const here = win+ ? app.win(localAppData(home)).some((dir) => { try { return statSync(dir).isDirectory(); } catch { return false; } })+ : applicationDirs.some((dir) => folders(dir, app.mac).length > 0);+ return here && (!app.with || app.with(home)) ? app.name : null;+}++/**+ * Each agent's official installer, as its maker's install page gives it, run in a terminal window the person sees+ * once they agree to it: `sh` on a Mac (and Linux), `ps` in PowerShell on Windows. The others are installed from their+ * install page (AGENT_DOWNLOADS).+ */+export const AGENT_INSTALLERS = Object.freeze({+ /* cursor.com/docs/cli/installation */+ cursor: { sh: 'curl https://cursor.com/install -fsS | bash', ps: "irm 'https://cursor.com/install?win32=true' | iex" },+ /* docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli */+ copilot: { sh: 'curl -fsSL https://gh.io/copilot-install | bash', ps: 'winget install GitHub.Copilot' },+ /* www.codebuddy.cn/docs/cli/installation */+ codebuddy: { sh: 'curl -fsSL https://www.codebuddy.cn/cli/install.sh | bash', ps: 'irm https://www.codebuddy.cn/cli/install.ps1 | iex' },+ /* github.com/QwenLM/qwen-code */+ qwen: {+ sh: 'curl -fsSL https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.sh | bash',+ ps: 'irm https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.ps1 | iex',+ },+ /* www.kimi.com/code/docs/en/kimi-code-cli/guides/getting-started.html */+ kimi: { sh: 'curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash', ps: 'irm https://code.kimi.com/kimi-code/install.ps1 | iex' },+ /* agent.minimax.io/docs/cli/quick-start */+ minimax: { sh: 'curl -fsSL https://filecdn.minimax.chat/public/install.sh | bash', ps: 'irm https://filecdn.minimax.chat/public/install.ps1 | iex' },+});++/** The command that installs an agent on this system (AGENT_INSTALLERS), or null when it has none. */+export function installCommand(id, { win = windows } = {}) {+ const installer = AGENT_INSTALLERS[id];+ return installer ? (win ? installer.ps : installer.sh) : null;+}+/*** For a person whose agent is not found, what was looked at: every folder searched, and each file there with one of- * the agent's names (any suffix, a PowerShell shim too) with what it runs, if that can be told.+ * the agent's names (any suffix, a PowerShell shim too) with what it runs, if that can be told, and why it is not the+ * agent when it is not (`refused`, notTheAgent).*/export function searchReport(id, { home = homedir(), env = process.env, pathDirs = HOME_BIN_CANDIDATES(home), win = windows } = {}) {const program = AGENT_PROGRAMS[id] ?? { names: [id] };- const searched = unique([...pathIn(env).split(win ? ';' : delimiter), ...pathDirs, ...(program.dirs?.(home) ?? [])], win);+ const searched = unique([...pathIn(env).split(win ? ';' : delimiter), ...pathDirs, ...(program.dirs?.(home, win) ?? [])], win);const files = [];for (const dir of searched) {for (const name of program.names) {@@ -356,7 +518,8 @@ export function searchReport(id, { home = homedir(), env = process.env, pathDirsconst file = join(dir, name + suffix);if (!presentFile(file)) continue;const runs = isCmdScript(file) ? cmdTarget(file) : /\.ps1$/i.test(file) ? null : file;- files.push({ file, runs, usable: win ? suffix !== '' && suffix !== '.ps1' : executableFile(file) });+ const refused = runs ? notTheAgent(id, runs, { chosen: file, win }) : null;+ files.push({ file, runs, usable: !refused && (win ? suffix !== '' && suffix !== '.ps1' : executableFile(file)), ...(refused ? { refused } : {}) });}}}diff --git a/apps/desktop/src/agent-installation.test.mjs b/apps/desktop/src/agent-installation.test.mjsindex 15c0777..267a722 100644--- a/apps/desktop/src/agent-installation.test.mjs+++ b/apps/desktop/src/agent-installation.test.mjs@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { chosenProgram, claudeAppCli, claudeVersion, cmdTarget, codexVersion, consoleProgram, detectAgentInstallation, findExecutable, laterVersion, searchReport, windowsBinDirs } from './agent-installation.mjs';+import { AGENT_INSTALLERS, chosenProgram, claudeAppCli, claudeVersion, cmdTarget, codexVersion, consoleProgram, desktopApp, detectAgentInstallation, findExecutable, installCommand, laterVersion, notTheAgent, opencodeVersion, searchReport, windowsBinDirs } from './agent-installation.mjs';test("an npm .cmd shim (Windows) runs its package's script: that is what gets started", () => {const npm = mkdtempSync(join(tmpdir(), 'of-npm-'));@@ -19,11 +19,11 @@ test("an npm .cmd shim (Windows) runs its package's script: that is what gets sttest('Claude Code as the Claude app keeps it: straight in a version folder, or one build folder down; newest first', () => {const home = mkdtempSync(join(tmpdir(), 'of-home-'));const root = join(home, 'Library/Application Support/Claude/claude-code');- assert.equal(claudeAppCli(home), null);+ assert.equal(claudeAppCli(home, { win: false }), null);const old = join(root, '2.1.9', 'claude.app/Contents/MacOS/claude');const recent = join(root, '2.1.10', 'f2326db61802', 'claude.app/Contents/MacOS/claude');for (const file of [old, recent]) { mkdirSync(join(file, '..'), { recursive: true }); writeFileSync(file, '', { mode: 0o755 }); }- assert.equal(claudeAppCli(home), recent);+ assert.equal(claudeAppCli(home, { win: false }), recent);});test("an agent is found by any of its names, and in its own installer's folder off the PATH (Kimi Code's ~/.kimi-code/bin)", () => {@@ -184,7 +184,8 @@ test('the report: every folder searched, each file with the name, what a shim ruput(join(npm, 'qwen.cmd'), npmShim('node_modules\\@qwen-code\\qwen-code\\cli.js'));put(join(npm, 'qwen.ps1'), '');const report = searchReport('qwen', { home, env: { PATH: `${npm};${npm.toUpperCase()}` }, pathDirs: [join(home, 'other')], win: true });- assert.deepEqual(report.searched, [npm, join(home, 'other')], 'each folder once, whatever its case');+ const own = join(process.env.LOCALAPPDATA || join(home, 'AppData', 'Local'), 'qwen-code', 'bin');+ assert.deepEqual(report.searched, [npm, join(home, 'other'), own], 'each folder once, whatever its case, its own installer\'s last');assert.deepEqual(report.files, [{ file: join(npm, 'qwen'), runs: join(npm, 'qwen'), usable: false },{ file: join(npm, 'qwen.cmd'), runs: script, usable: true },@@ -282,3 +283,164 @@ test("Cursor installed as `agent` alone is found; another program called `agent`symlinkSync(real, join(bin, 'cursor-agent'));assert.equal(detectAgentInstallation('cursor', { home, env: { PATH: '' }, pathDirs: [bin] }).cli, join(bin, 'cursor-agent'));});++/* the .cmd an editor keeps in resources\app\bin (Windows): it runs the editor with Node, its arguments files to open */+const editorShim = (exe) => `@echo off\r\nsetlocal\r\nset ELECTRON_RUN_AS_NODE=1\r\n"%~dp0..\\..\\..\\${exe}" "%~dp0..\\out\\cli.js" %*\r\nendlocal\r\n`;++test("an editor's own launcher is never taken for an agent: a .cmd running its out/cli.js, or anything in its resources/app/bin", () => {+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ /* the Cursor editor on Windows, its launcher picked or found as Cursor's agent */+ const root = join(home, 'AppData', 'Local', 'Programs', 'cursor');+ const cli = put(join(root, 'resources', 'app', 'out', 'cli.js'));+ const bin = join(root, 'resources', 'app', 'bin');+ const cursorCmd = put(join(bin, 'cursor.cmd'), editorShim('Cursor.exe'));+ assert.equal(chosenProgram(cursorCmd, { names: ['cursor-agent', 'agent'], win: true }), cli, 'what the shim runs: the editor');+ assert.equal(notTheAgent('cursor', cli, { chosen: cursorCmd, win: true }), 'app');+ assert.equal(detectAgentInstallation('cursor', { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [], chosen: cursorCmd, win: true }).cli, null,+ 'a launcher chosen before is not used');+ /* one named like the agent in an editor's bin folder is not it either */+ put(join(bin, 'agent.cmd'), editorShim('Cursor.exe'));+ assert.equal(detectAgentInstallation('cursor', { home, env: { PATH: bin }, pathDirs: [], applicationDirs: [], win: true }).cli, null);+ /* VS Code's own `code` launcher on Windows, under Microsoft VS Code */+ const code = put(join(home, 'AppData', 'Local', 'Programs', 'Microsoft VS Code', 'bin', 'copilot.cmd'), '@echo off\r\n');+ assert.equal(notTheAgent('copilot', code, { win: true }), 'app');+ /* a program of the agent's own is never refused */+ const npm = join(home, 'npm');+ const script = put(join(npm, 'node_modules', '@github', 'copilot', 'npm-loader.js'));+ put(join(npm, 'copilot.cmd'), npmShim('node_modules\\@github\\copilot\\npm-loader.js'));+ assert.equal(notTheAgent('copilot', script, { chosen: join(npm, 'copilot.cmd'), win: true }), null);+});++test("on a Mac an editor's launcher in its app, or linked from a bin folder, is skipped for the agent's own further on", () => {+ if (process.platform === 'win32') return;+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const inApp = put(join(home, 'Applications', 'Visual Studio Code.app', 'Contents', 'Resources', 'app', 'bin', 'copilot'), '', 0o755);+ const linked = join(home, 'linked');+ mkdirSync(linked);+ symlinkSync(inApp, join(linked, 'copilot'));+ const mine = put(join(home, '.local', 'bin', 'copilot'), '', 0o755);+ const opts = { home, env: { PATH: [join(inApp, '..'), linked].join(':') }, pathDirs: [join(home, '.local', 'bin')], applicationDirs: [] };+ assert.equal(notTheAgent('copilot', join(linked, 'copilot')), 'app', 'followed through its link');+ assert.equal(detectAgentInstallation('copilot', opts).cli, mine);+ assert.equal(detectAgentInstallation('copilot', { ...opts, chosen: join(linked, 'copilot') }).cli, mine, 'chosen, and refused');+});++test('on Windows a window program (a desktop app) is never an agent; one whose header cannot be read still is', () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-pe-'));+ const app = join(dir, 'app');+ mkdirSync(app);+ writeFileSync(join(app, 'kimi.exe'), peProgram(2));+ assert.equal(notTheAgent('kimi', join(app, 'kimi.exe'), { win: true }), 'app');+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ assert.equal(detectAgentInstallation('kimi', { home, env: { PATH: app }, pathDirs: [], applicationDirs: [], win: true }).cli, null);+ const cli = join(dir, 'cli');+ mkdirSync(cli);+ writeFileSync(join(cli, 'kimi.exe'), peProgram(3));+ assert.equal(detectAgentInstallation('kimi', { home, env: { PATH: `${app};${cli}` }, pathDirs: [], applicationDirs: [], win: true }).cli, join(cli, 'kimi.exe'));+ /* a Store app's command cannot be read as a file: it is not refused for that */+ writeFileSync(join(dir, 'codex.exe'), '');+ assert.equal(notTheAgent('codex', join(dir, 'codex.exe'), { win: true }), null);+});++test("Cursor's agent counts only in its own folder (or Homebrew's cursor-cli), whatever it is called", () => {+ if (process.platform === 'win32') return;+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const stray = put(join(home, 'bin', 'cursor-agent'), '', 0o755);+ assert.equal(notTheAgent('cursor', stray), 'not-cursor-agent');+ assert.equal(detectAgentInstallation('cursor', { home, env: { PATH: '' }, pathDirs: [join(home, 'bin')], applicationDirs: [] }).cli, null);+ const brew = put(join(home, 'Caskroom', 'cursor-cli', '2026.10.16-e3cb207', 'dist-package', 'cursor-agent'), '', 0o755);+ const links = join(home, 'brew-bin');+ mkdirSync(links);+ symlinkSync(brew, join(links, 'cursor-agent'));+ assert.equal(detectAgentInstallation('cursor', { home, env: { PATH: '' }, pathDirs: [join(home, 'bin'), links], applicationDirs: [] }).cli, join(links, 'cursor-agent'));+});++test("Cursor's agent on Windows: found in %LOCALAPPDATA%\\cursor-agent, started by its own shim, which runs its own Node", () => {+ if (process.platform === 'win32') return;+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const root = join(home, 'AppData', 'Local', 'cursor-agent');+ put(join(root, 'versions', '2026.10.16-e3cb207', 'index.js'));+ put(join(root, 'versions', '2026.10.16-e3cb207', 'node.exe'));+ const shim = put(join(root, 'agent.cmd'), '@echo off\r\n"%~dp0versions\\2026.10.16-e3cb207\\node.exe" "%~dp0versions\\2026.10.16-e3cb207\\index.js" %*\r\n');+ assert.equal(cmdTarget(shim), null, 'never its script with another Node');+ assert.equal(detectAgentInstallation('cursor', { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [], win: true }).cli, shim);+});++test('Claude Code in the Claude app on Windows: under %APPDATA%\\Claude, or the Store app\'s own copy of it; the newest', () => {+ if (process.platform === 'win32') return;+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ assert.equal(claudeAppCli(home, { win: true }), null);+ const roaming = put(join(home, 'AppData', 'Roaming', 'Claude', 'claude-code', '2.1.290', 'claude.exe'));+ assert.equal(claudeAppCli(home, { win: true }), roaming);+ const store = put(join(home, 'AppData', 'Local', 'Packages', 'Claude_pzs8sxrjxfjjc', 'LocalCache', 'Roaming', 'Claude', 'claude-code', '2.1.300', 'b1', 'claude.exe'));+ assert.equal(claudeAppCli(home, { win: true }), store);+ assert.equal(claudeVersion(store), '2.1.300');+ assert.deepEqual(detectAgentInstallation('claude', { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [], win: true }).cli, store);+});++test("OpenCode inside OpenCode.app: used when it is the only one, or the later than the one on the PATH", () => {+ if (process.platform === 'win32') return;+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const apps = join(home, 'Applications');+ const inApp = put(join(apps, 'OpenCode.app', 'Contents', 'Resources', 'opencode-cli'), '', 0o755);+ writeFileSync(`${inApp}.version`, '2.0.24\n');+ assert.equal(opencodeVersion(inApp, { ask: () => assert.fail('read from the file beside it') }), '2.0.24');+ const opts = { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [apps] };+ assert.deepEqual(detectAgentInstallation('opencode', opts), { installed: true, cli: inApp, source: 'app', install: 'https://opencode.ai/download' });+ const bin = join(home, 'bin');+ const onPath = put(join(bin, 'opencode'), '', 0o755);+ const versions = (map) => (file) => map[file] ?? null;+ assert.equal(detectAgentInstallation('opencode', { ...opts, pathDirs: [bin], opencodeVersionOf: versions({ [onPath]: '1.0.0', [inApp]: '2.0.24' }) }).cli, inApp);+ assert.equal(detectAgentInstallation('opencode', { ...opts, pathDirs: [bin], opencodeVersionOf: versions({ [onPath]: '2.1.0', [inApp]: '2.0.24' }) }).cli, onPath);+ assert.equal(chosenProgram(join(apps, 'OpenCode.app'), { names: ['opencode'] }), inApp, 'the app chosen: the OpenCode inside it');+ /* npm's says it in its package.json */+ const pkg = join(home, 'npm', 'node_modules', 'opencode-ai');+ put(join(pkg, 'package.json'), JSON.stringify({ name: 'opencode-ai', version: '1.4.2' }));+ assert.equal(opencodeVersion(put(join(pkg, 'bin', 'opencode'))), '1.4.2');+});++test("the maker's desktop app is told without its agent: by its bundle on a Mac, its folder on Windows; VS Code with Copilot only", () => {+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const apps = join(home, 'Applications');+ const mac = { home, applicationDirs: [apps], win: false };+ assert.equal(desktopApp('cursor', mac), null);+ mkdirSync(join(apps, 'Cursor.app'), { recursive: true });+ mkdirSync(join(apps, 'CodeBuddy CN.app'));+ mkdirSync(join(apps, 'Visual Studio Code.app'));+ assert.equal(desktopApp('cursor', mac), 'Cursor');+ assert.equal(desktopApp('codebuddy', mac), 'CodeBuddy');+ assert.equal(desktopApp('kimi', mac), null);+ assert.equal(desktopApp('copilot', mac), null, 'VS Code without the Copilot extension');+ mkdirSync(join(home, '.vscode', 'extensions', 'github.copilot-chat-0.30.0'), { recursive: true });+ assert.equal(desktopApp('copilot', mac), 'VS Code');+ assert.equal(desktopApp('qwen', mac), null, 'no desktop app');+ if (process.platform === 'win32') return;+ const win = { home, applicationDirs: [], win: true };+ assert.equal(desktopApp('minimax', win), null);+ mkdirSync(join(home, 'AppData', 'Local', 'Programs', 'MiniMax Agent'), { recursive: true });+ assert.equal(desktopApp('minimax', win), 'MiniMax');+ mkdirSync(join(home, 'AppData', 'Local', 'AnthropicClaude'), { recursive: true });+ assert.equal(desktopApp('claude', win), 'Claude');+});++test("each official installer: the maker's command for this system, the others none", () => {+ assert.equal(installCommand('cursor', { win: false }), 'curl https://cursor.com/install -fsS | bash');+ assert.equal(installCommand('cursor', { win: true }), "irm 'https://cursor.com/install?win32=true' | iex");+ assert.equal(installCommand('copilot', { win: true }), 'winget install GitHub.Copilot');+ for (const id of ['codex', 'claude', 'opencode', 'byok']) assert.equal(installCommand(id, { win: false }), null, id);+ for (const [id, { sh, ps }] of Object.entries(AGENT_INSTALLERS)) {+ assert.match(sh, /^curl .*https:\/\/\S+.*\| bash$/, id);+ assert.match(ps, /^(?:irm '?https:\/\/\S+'? \| iex|winget install \S+)$/, id);+ }+});++test('the report says which file is not the agent, and why', () => {+ const home = mkdtempSync(join(tmpdir(), 'of-home-'));+ const bin = join(home, 'Programs', 'cursor', 'resources', 'app', 'bin');+ put(join(home, 'Programs', 'cursor', 'resources', 'app', 'out', 'cli.js'));+ put(join(bin, 'agent.cmd'), editorShim('Cursor.exe'));+ const report = searchReport('cursor', { home, env: { PATH: bin }, pathDirs: [], win: true });+ assert.equal(report.files.length, 1);+ assert.equal(report.files[0].refused, 'app');+ assert.equal(report.files[0].usable, false);+});diff --git a/apps/desktop/src/agent-roster.mjs b/apps/desktop/src/agent-roster.mjsindex a452cd8..1b145f8 100644--- a/apps/desktop/src/agent-roster.mjs+++ b/apps/desktop/src/agent-roster.mjs@@ -20,6 +20,8 @@** One of the person's own agents not found where it is looked for can be pointed at (`locate`): the program they choose* is tried (it has to answer `--version`) and used from then on, until they go back to finding it (`useAutomatic`).+ * One with an official installer can be installed (`install`): it runs in a terminal window, and the agent is looked+ * for again until it is there.* `diagnose` says what was searched, for them to read or send with an issue.** Each has a switch for whether the chat's menu shows it. Kept in the app's data folder: agents.json (the choices) and@@ -27,7 +29,9 @@* the one key of a version before, is the key of the models set up then).** State per agent: ready · off (disconnected here) · sign-in (its own sign-in is needed) · waiting (signing in, in- * Terminal) · missing (not installed; `install` says where from) · key (no key set up) · checking (not known yet).+ * Terminal) · missing (not installed; `install` says where from, `installer` the command that installs it, `app` the+ * maker's desktop app when only that is here, `installing` while its installer runs) · key (no key set up) · checking+ * (not known yet).** Reads no Electron module, so `node --test` can use it.*/@@ -184,9 +188,10 @@ export async function probeModel({ format, baseUrl, key, model, fetch: fetchImpl** @param {{* dataDir: string,- * localAgents: () => Promise<Array<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, problem?: string, install: string | null, setupRequired: string | null }>>,- * localAgent?: (id: string) => Promise<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, problem?: string, install: string | null, setupRequired: string | null }>,+ * localAgents: () => Promise<Array<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, problem?: string, install: string | null, setupRequired: string | null, app?: string | null, installer?: string | null }>>,+ * localAgent?: (id: string) => Promise<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, problem?: string, install: string | null, setupRequired: string | null, app?: string | null, installer?: string | null }>,* openSignIn: (id: string) => Promise<{ ok: boolean, error?: string }>,+ * openInstaller?: (id: string) => Promise<{ ok: boolean, error?: string }>,* usePaths?: (paths: Record<string, string>) => void,* pickProgram?: (id: string, words?: { title?: string, button?: string }) => Promise<string | null>,* checkProgram?: (id: string, path: string) => Promise<{ ok: boolean, error?: string, code?: string }>,@@ -197,14 +202,15 @@ export async function probeModel({ format, baseUrl, key, model, fetch: fetchImpl* fetch?: typeof fetch,* signInWait?: { ms: number, pollMs: number },* }} deps- * `localAgent(id)`: one agent as `localAgents` has it, asked alone while its sign-in is waited for (`signInWait`).+ * `localAgent(id)`: one agent as `localAgents` has it, asked alone while its sign-in or its install is waited for+ * (`signInWait`).*/export function createRoster(deps) {const { dataDir } = deps;let choices = readChoices(dataDir);deps.usePaths?.(choices.paths);- /** what is happening now, beyond what is kept: a sign-in waited for, an error to show */- const live = { waiting: {}, errors: {} };+ /** what is happening now, beyond what is kept: a sign-in or an install waited for, an error to show */+ const live = { waiting: {}, installing: {}, errors: {} };let local = null;/* each own model's key by its id; the one key of a version before is the key of the models set up then */@@ -230,7 +236,10 @@ export function createRoster(deps) {const found = local?.find((a) => a.id === id);if (!found) return { status: 'checking' };const where = { path: found.cli?.path ?? null, chosen: choices.paths[id] ?? null };- if (!found.cli) return { status: 'missing', install: found.install ?? null, setupRequired: found.setupRequired ?? null, ...where };+ if (!found.cli) {+ return { status: 'missing', install: found.install ?? null, setupRequired: found.setupRequired ?? null, app: found.app ?? null, installer: found.installer ?? null,+ ...(live.installing[id] ? { installing: true } : {}), ...where };+ }if (choices.disconnected.includes(id)) return { status: 'off', ...where };if (found.signedIn === false) return { status: live.waiting[id] ? 'waiting' : 'sign-in', ...where };return { status: 'ready', ...where, ...(found.account ? { account: { ...found.account } } : {}), ...(found.problem ? { problem: found.problem } : {}) };@@ -270,19 +279,21 @@ export function createRoster(deps) {changed();}- async function waitForSignIn(id) {- live.waiting[id] = true;+ /** Looked at again every few seconds until `done` says so, or for as long as a sign-in is waited for. */+ async function waitFor(id, kind, done) {+ live[kind][id] = true;changed();const wait = deps.signInWait ?? SIGN_IN_WAIT;const until = Date.now() + wait.ms;- while (Date.now() < until && live.waiting[id]) {- await new Promise((done) => setTimeout(done, wait.pollMs));+ while (Date.now() < until && live[kind][id]) {+ await new Promise((resolve) => setTimeout(resolve, wait.pollMs));await lookAgain(id);- if (local?.find((a) => a.id === id)?.signedIn !== false) break;+ if (done(local?.find((a) => a.id === id))) break;}- delete live.waiting[id];+ delete live[kind][id];changed();}+ const waitForSignIn = (id) => waitFor(id, 'waiting', (a) => a?.signedIn !== false);return {list,@@ -341,6 +352,19 @@ export function createRoster(deps) {return { ok: true };},+ /**+ * Install one of the person's own agents with its official installer, in a terminal window (the person agreed to+ * the command first), then look for it every few seconds until it is there.+ */+ async install(id) {+ if (!isOwn(id) || !deps.openInstaller) return { ok: false, error: `No agent ${id}` };+ delete live.errors[id];+ const opened = await deps.openInstaller(id);+ if (!opened.ok) { live.errors[id] = opened.error ?? 'Terminal did not open.'; changed(); return { ok: false, error: live.errors[id] }; }+ void waitFor(id, 'installing', (a) => Boolean(a?.cli));+ return { ok: true };+ },+/** Back to finding the program where it is installed. */async useAutomatic(id) {if (!Object.hasOwn(choices.paths, id)) return { ok: true };diff --git a/apps/desktop/src/agent-roster.test.mjs b/apps/desktop/src/agent-roster.test.mjsindex 96d9ccb..37780ce 100644--- a/apps/desktop/src/agent-roster.test.mjs+++ b/apps/desktop/src/agent-roster.test.mjs@@ -274,3 +274,39 @@ test('a sign-in in Terminal is waited for asking only that agent, until it is siawait new Promise((done) => setTimeout(done, 120));assert.equal(late.list().find((a) => a.id === 'cursor').status, 'sign-in');});++test("an agent found only as its maker's app: the app said, and its installer run in a terminal and waited for until it is there", async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));+ const missing = { id: 'cursor', cli: null, signedIn: null, install: 'https://cursor.com/cli', setupRequired: null, app: 'Cursor', installer: 'curl https://cursor.com/install -fsS | bash' };+ let installed = false;+ const opened = [];+ const r = roster(dir, undefined, {+ localAgents: async () => [missing],+ localAgent: async () => (installed ? { ...missing, cli: { path: '/bin/cursor-agent' }, signedIn: false, app: undefined, installer: undefined } : missing),+ openInstaller: async (id) => { opened.push(id); return { ok: true }; },+ signInWait: { ms: 2000, pollMs: 10 },+ });+ await r.refresh();+ const before = r.list().find((a) => a.id === 'cursor');+ assert.equal(before.status, 'missing');+ assert.equal(before.app, 'Cursor');+ assert.equal(before.installer, 'curl https://cursor.com/install -fsS | bash');+ assert.deepEqual(await r.install('cursor'), { ok: true });+ assert.deepEqual(opened, ['cursor']);+ await new Promise((done) => setTimeout(done, 30));+ assert.equal(r.list().find((a) => a.id === 'cursor').installing, true);+ installed = true;+ await new Promise((done) => setTimeout(done, 60));+ const after = r.list().find((a) => a.id === 'cursor');+ assert.equal(after.status, 'sign-in');+ assert.equal(after.installing, undefined);+ assert.deepEqual(await r.install('byok'), { ok: false, error: 'No agent byok' });++ /* a terminal that did not open says why */+ const failed = roster(mkdtempSync(join(tmpdir(), 'of-roster-')), undefined, {+ localAgents: async () => [missing], openInstaller: async () => ({ ok: false, error: 'Terminal did not open.' }),+ });+ await failed.refresh();+ assert.deepEqual(await failed.install('cursor'), { ok: false, error: 'Terminal did not open.' });+ assert.equal(failed.list().find((a) => a.id === 'cursor').error, 'Terminal did not open.');+});diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjsindex 7902727..12719c3 100644--- a/apps/desktop/src/agents.mjs+++ b/apps/desktop/src/agents.mjs@@ -33,7 +33,7 @@ import { Readable, Writable } from 'node:stream';import { fileURLToPath } from 'node:url';import * as acp from '@agentclientprotocol/sdk';import { PATH_SEP, childEnvironment, lastPathSource, loginShellEnvironment, loginShellVariables, shellSubset } from './environment.mjs';-import { AGENT_PROGRAMS, HOME_BIN_CANDIDATES, chosenProgram, codexVersion, consoleProgram, detectAgentInstallation, laterVersion, searchReport } from './agent-installation.mjs';+import { AGENT_PROGRAMS, HOME_BIN_CANDIDATES, chosenProgram, codexVersion, consoleProgram, desktopApp, detectAgentInstallation, installCommand, laterVersion, notTheAgent, searchReport } from './agent-installation.mjs';import { logSwitches } from './agent-logs.mjs';import { mergeConfig, sessionSkills } from './agent-skills.mjs';import { nodeBinary } from './node-runtime.mjs';@@ -270,15 +270,24 @@ function starting(cliPath, args) {return { cmd: cliPath, args, env: {}, options: {} };}+/** Why a program is not the agent (notTheAgent), in words. */+const NOT_THE_AGENT = Object.freeze({+ app: 'This is an editor or a desktop app, not the agent\'s command-line program.',+ 'not-cursor-agent': 'This is not Cursor\'s command-line agent, which installs in a cursor-agent folder.',+});+/*** A program the person chose for an agent, tried: it has to start and answer `--version`. `{ ok, version }`, or why- * not: `code` 'not-a-program' (nothing there this computer can start) or 'did-not-start' (with what it said).+ * not: `code` 'not-a-program' (nothing there this computer can start), 'app' or 'not-cursor-agent' (not the agent:+ * an editor or a desktop app, never started) or 'did-not-start' (with what it said).*/export async function checkAgentProgram(id, path) {const spec = AGENTS[id];if (!spec) return { ok: false, error: `No agent ${id}`, code: 'not-a-program' };const cli = chosenProgram(path, { names: AGENT_PROGRAMS[id]?.names ?? [id] });if (!cli) return { ok: false, error: 'That is not a program this computer can start.', code: 'not-a-program' };+ const refused = notTheAgent(id, cli, { chosen: path });+ if (refused) return { ok: false, error: NOT_THE_AGENT[refused], code: refused };const how = starting(cli, ['--version']);const r = await run(how.cmd, how.args, 20_000, { env: childEnvironment({ shell: await loginShellVariables(), extra: how.env }), options: how.options });if (!r.ok) return { ok: false, error: r.out.trim().slice(0, 400), code: 'did-not-start' };@@ -325,7 +334,7 @@ export async function diagnoseAgent(id, { appVersion = '' } = {}) {] : []),'',`Files named ${names.join(', ')}:`,- ...(report.files.length ? report.files.map((f) => ` ${f.file}${f.runs && f.runs !== f.file ? ` -> ${f.runs}` : ''}${f.usable ? '' : ' (cannot be started)'}`) : [' (none)']),+ ...(report.files.length ? report.files.map((f) => ` ${f.file}${f.runs && f.runs !== f.file ? ` -> ${f.runs}` : ''}${f.refused ? ` (not the agent: ${f.refused})` : f.usable ? '' : ' (cannot be started)'}`) : [' (none)']),'',`Folders searched (${report.searched.length}):`,...report.searched.map((d) => ` ${d}`),@@ -442,7 +451,11 @@ const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;* folder a new window opens in).*/export function signInScript(cliPath, args, { cwd } = {}) {- const command = `${cwd ? `cd ${shq(cwd)} && ` : ''}${[cliPath, ...args].map(shq).join(' ')}`;+ return terminalScript(`${cwd ? `cd ${shq(cwd)} && ` : ''}${[cliPath, ...args].map(shq).join(' ')}`);+}++/** The AppleScript that has Terminal run a command line, as it is, in a new window. */+export function terminalScript(command) {return `tell application "Terminal"\nactivate\ndo script "${command.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"\nend tell`;}@@ -451,8 +464,30 @@ export function signInScript(cliPath, args, { cwd } = {}) {* PowerShell quotes): Windows sign-in. With a BOM, so Windows PowerShell reads a path with Chinese in it as UTF-8.*/export function powerShellScript(title, cmd, args) {- const q = (s) => `'${String(s).replace(/'/g, "''")}'`;- return `\ufeff$Host.UI.RawUI.WindowTitle = ${q(title)}\r\n& ${[cmd, ...args].map(q).join(' ')}\r\n`;+ return powerShellLine(title, `& ${[cmd, ...args].map(psq).join(' ')}`);+}++/** The same for a command line as it is (an installer's). */+export function powerShellLine(title, line) {+ return `\ufeff$Host.UI.RawUI.WindowTitle = ${psq(title)}\r\n${line}\r\n`;+}+const psq = (s) => `'${String(s).replace(/'/g, "''")}'`;++/**+ * A PowerShell window of its own running a script (a sign-in, an installer), left open so what it says can be read+ * and answered.+ */+async function powerShellWindow(name, script, env) {+ const dir = SIGN_IN_DIR();+ mkdirSync(dir, { recursive: true });+ const file = join(dir, name);+ writeFileSync(file, script, 'utf8');+ const powershell = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');+ const child = spawn(powershell, ['-NoLogo', '-NoExit', '-ExecutionPolicy', 'Bypass', '-File', file], {+ cwd: dir, detached: true, stdio: 'ignore', windowsHide: false, env,+ });+ await new Promise((done, fail) => { child.once('spawn', done); child.once('error', fail); });+ child.unref();}/** The person's shell variables as this agent is given them (`fromShell`; all of them, for most). */@@ -526,16 +561,8 @@ export async function openAgentSignIn(id) {how ??= /\.(?:cmd|bat)$/i.test(cli.path) ? { cmd: cli.path, args: spec.login, env: {} } : starting(cli.path, spec.login);how = { ...how, env: { ...defaults, ...how.env } };try {- const dir = SIGN_IN_DIR();- mkdirSync(dir, { recursive: true });- const file = join(dir, `${id}.ps1`);- writeFileSync(file, powerShellScript(`${spec.label} sign-in`, how.cmd, how.args), 'utf8');- const powershell = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');- const child = spawn(powershell, ['-NoLogo', '-NoExit', '-ExecutionPolicy', 'Bypass', '-File', file], {- cwd: dir, detached: true, stdio: 'ignore', windowsHide: false, env: childEnvironment({ shell: agentShell(id, await loginShellVariables()), extra: how.env }),- });- await new Promise((done, fail) => { child.once('spawn', done); child.once('error', fail); });- child.unref();+ await powerShellWindow(`${id}.ps1`, powerShellScript(`${spec.label} sign-in`, how.cmd, how.args),+ childEnvironment({ shell: agentShell(id, await loginShellVariables()), extra: how.env }));return { ok: true };} catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; }}@@ -549,9 +576,29 @@ export async function openAgentSignIn(id) {return r.ok ? { ok: true } : { ok: false, error: r.out.trim() || 'Terminal did not open.' };}+/**+ * Install an agent with its maker's official installer (installCommand), in a window the person sees: Terminal on a+ * Mac, PowerShell on Windows. The person agreed to that exact command in Settings → Agents first. Whether it worked is+ * learnt by looking for the agent again (agent-roster.mjs).+ */+export async function openAgentInstaller(id) {+ const spec = AGENTS[id];+ const command = spec ? installCommand(id) : null;+ if (!command) return { ok: false, error: `${spec?.label ?? id} has no installer to run here.` };+ if (windows) {+ try {+ await powerShellWindow(`${id}-install.ps1`, powerShellLine(`${spec.label} install`, command), childEnvironment({ shell: await loginShellVariables() }));+ return { ok: true };+ } catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; }+ }+ const r = await run('/usr/bin/osascript', ['-e', terminalScript(command)], 15_000);+ return r.ok ? { ok: true } : { ok: false, error: r.out.trim() || 'Terminal did not open.' };+}+/*** The agents as they are on this machine, for the chat's picker. `setupRequired: 'code-tab'`: the Claude app is- * here but has not downloaded Claude Code yet (opening its Code tab does).+ * here but has not downloaded Claude Code yet (opening its Code tab does). One not found: `app`, the maker's desktop+ * app when it is here without the agent's program; `installer`, the official command that installs it, when it has one.*/export async function listAgents() {/* looked at as the person comes back from installing one: a PATH from a few seconds ago at most */@@ -577,7 +624,8 @@ export async function localAgent(id) {async function agentOnComputer(id, pathDirs) {const cli = resolveAgentCli(id, { pathDirs });const { install } = detectAgentInstallation(id);- const claudeApp = id === 'claude' && !cli && ['/Applications', join(homedir(), 'Applications')].some((dir) => existsSync(join(dir, 'Claude.app')));+ const app = cli ? null : desktopApp(id);+ const claudeApp = id === 'claude' && Boolean(app);return {id,label: AGENTS[id].label,@@ -586,6 +634,7 @@ async function agentOnComputer(id, pathDirs) {...(cli ? ownSignIn(AGENTS[id], await agentStatus(id, cli.path)) : { signedIn: null, account: null }),install,setupRequired: claudeApp ? 'code-tab' : null,+ ...(cli ? {} : { app: claudeApp ? null : app, installer: installCommand(id) }),};}diff --git a/apps/desktop/src/agents.test.mjs b/apps/desktop/src/agents.test.mjsindex c15986d..a505dfe 100644--- a/apps/desktop/src/agents.test.mjs+++ b/apps/desktop/src/agents.test.mjs@@ -1,6 +1,6 @@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, readAgentStatus, setChosenPaths, signInScript, turnError, signInError, codexTooOld, AGENTS, ownSignIn, codexServiceError, codexRefusal, codexNotice, explainFailure, stderrReason } from './agents.mjs';+import { AgentSession, CLIENT_CAPABILITIES, agentDefaults, closeEverySession, planProblem, probeFolder, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, distinctOptions, errorCause, legacyOptions, powerShellScript, powerShellLine, terminalScript, checkAgentProgram, readAgentStatus, setChosenPaths, signInScript, turnError, signInError, codexTooOld, AGENTS, ownSignIn, codexServiceError, codexRefusal, codexNotice, explainFailure, stderrReason } from './agents.mjs';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 = [@@ -189,12 +189,13 @@ test('on Windows, Codex is started through a script that turns the console to UT});test('a signed-out Cursor is said to need its sign-in at once, without the session that would open its sign-in page', async () => {- const { mkdtempSync, writeFileSync } = await import('node:fs');+ const { mkdirSync, mkdtempSync, writeFileSync } = await import('node:fs');const { tmpdir } = await import('node:os');const { join } = await import('node:path');const dir = mkdtempSync(join(tmpdir(), 'of-cursor-'));- /* says it is signed out, and never answers over ACP (Cursor waits on its sign-in page there) */- const program = join(dir, 'cursor-agent.mjs');+ /* says it is signed out, and never answers over ACP (Cursor waits on its sign-in page there); in Cursor's own folder */+ mkdirSync(join(dir, 'cursor-agent'));+ const program = join(dir, 'cursor-agent', 'cursor-agent.mjs');writeFileSync(program, "if (process.argv.includes('status')) console.log('Not logged in'); else setInterval(() => {}, 1000);\n");setChosenPaths({ cursor: program });const session = new AgentSession({ agent: 'cursor', cwd: dir });@@ -398,3 +399,26 @@ test("what an agent's stderr says: the lines that name an error, else its last lassert.equal(stderrReason('ok\nError: cannot read config.toml\n at load (x.js:1:1)\ndone'), 'Error: cannot read config.toml');assert.equal(stderrReason(''), '');});++test('an installer runs as its maker wrote it: in Terminal on a Mac, in a PowerShell window of its own on Windows', () => {+ assert.equal(terminalScript('curl https://cursor.com/install -fsS | bash'),+ 'tell application "Terminal"\nactivate\ndo script "curl https://cursor.com/install -fsS | bash"\nend tell');+ const lines = powerShellLine('Cursor install', "irm 'https://cursor.com/install?win32=true' | iex").slice(1).split('\r\n');+ assert.deepEqual(lines.slice(0, 2), ["$Host.UI.RawUI.WindowTitle = 'Cursor install'", "irm 'https://cursor.com/install?win32=true' | iex"]);+});++test('a program chosen that is an editor, or not Cursor\'s own agent, is refused without being started', async () => {+ if (process.platform === 'win32') return;+ const { mkdtempSync, mkdirSync, writeFileSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const home = mkdtempSync(join(tmpdir(), 'of-check-'));+ /* it would leave a mark if it were started */+ const exe = (file) => { mkdirSync(join(file, '..'), { recursive: true }); writeFileSync(file, `#!/bin/sh\ntouch "${file}.ran"\n`, { mode: 0o755 }); return file; };+ const code = exe(join(home, 'Visual Studio Code.app', 'Contents', 'Resources', 'app', 'bin', 'copilot'));+ assert.deepEqual(await checkAgentProgram('copilot', code), { ok: false, error: "This is an editor or a desktop app, not the agent's command-line program.", code: 'app' });+ const stray = exe(join(home, 'bin', 'agent'));+ assert.equal((await checkAgentProgram('cursor', stray)).code, 'not-cursor-agent');+ const { existsSync } = await import('node:fs');+ assert.equal(existsSync(`${code}.ran`) || existsSync(`${stray}.ran`), false);+});diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjsindex 9ac6f87..feec43c 100644--- a/apps/desktop/src/main.mjs+++ b/apps/desktop/src/main.mjs@@ -26,7 +26,7 @@ import { registerLocalAgentIpc } from './local-agents-ipc.mjs';import { readPreferences, registerChatIpc } from './chat-ipc.mjs';import { registerSkillsIpc } from './skills-ipc.mjs';import { createRoster } from './agent-roster.mjs';-import { checkAgentProgram, closeEverySession, diagnoseAgent, listAgents, localAgent, openAgentSignIn, setChosenPaths } from './agents.mjs';+import { checkAgentProgram, closeEverySession, diagnoseAgent, listAgents, localAgent, openAgentInstaller, openAgentSignIn, setChosenPaths } from './agents.mjs';import { agentUsage, forgetAgentUsage } from './agent-usage.mjs';import { installOpenfilmCommand } from './openfilm-command.mjs';import { startUpdates } from './updates.mjs';@@ -571,6 +571,8 @@ async function start() {localAgents: listAgents,localAgent,openSignIn: openAgentSignIn,+ /* an agent's official installer, in a terminal window, once the person agreed to it in Settings → Agents */+ openInstaller: openAgentInstaller,/* sessions closed on connecting and disconnecting: the next look at its usage is for whichever account is used now */closeSessions: (id) => { forgetAgentUsage(id); localAgents?.closeAgent(id); },seal,@@ -596,6 +598,7 @@ async function start() {agentHandle('desktop:agents:usage', ({ id, fresh }) => agentUsage(String(id), { fresh: fresh === true }));agentHandle('desktop:agents:locate', ({ id, words }) => roster.locate(String(id), words));agentHandle('desktop:agents:automatic', ({ id }) => roster.useAutomatic(String(id)));+ agentHandle('desktop:agents:install', ({ id }) => roster.install(String(id)));agentHandle('desktop:agents:diagnose', ({ id }) => roster.diagnose(String(id)));/* the app's part of Studio's diagnostic report (app-report.mjs): the agents as found now, each one's --version */const appReport = () => gatherAppReport({ list: () => roster.refresh(), check: checkAgentProgram }, {diff --git a/apps/desktop/src/preload.cjs b/apps/desktop/src/preload.cjsindex e5ced4b..a7fbde7 100644--- a/apps/desktop/src/preload.cjs+++ b/apps/desktop/src/preload.cjs@@ -49,6 +49,7 @@ contextBridge.exposeInMainWorld('openfilmNative', {setShown: (id, shown) => ipcRenderer.invoke('desktop:agents:shown', { id, shown: shown === true }),locate: (id, words) => ipcRenderer.invoke('desktop:agents:locate', { id, words }),useAutomatic: (id) => ipcRenderer.invoke('desktop:agents:automatic', { id }),+ install: (id) => ipcRenderer.invoke('desktop:agents:install', { id }),diagnose: (id) => ipcRenderer.invoke('desktop:agents:diagnose', { id }),report: () => ipcRenderer.invoke('desktop:agents:report'),/* the whole diagnostic report on the clipboard (main.mjs): the chat's, by a turn that failed */diff --git a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsxindex cd6f483..83e45e0 100644--- a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx+++ b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx@@ -10,8 +10,10 @@* one does), else under "More agents", with where to get them when they are not installed. The person's own key is on a service of theirs, with a model that reads pictures (the agent looks at its own frames).** One not found, or one disconnected, can be pointed at: Locate… opens the system's file dialog, the program chosen is- * tried and used from then on (Find automatically goes back). A connected one keeps the program it found. "Why isn't- * it found?" says what was searched, with a report to copy.+ * tried and used from then on (Find automatically goes back); an editor or a desktop app is refused. A connected one+ * keeps the program it found. "Why isn't it found?" says what was searched, with a report to copy. One not found that+ * has an official installer is installed from here: Install shows the exact command, which runs in a terminal window+ * once the person agrees; the row says when only the maker's desktop app is here.** Under a connected agent: the skills and the MCP servers the person added to it themselves, each off in the app until* let in (its maker's own are always on).@@ -112,6 +114,8 @@ export function AgentsSection() {const [error, setError] = React.useState<{ id: HostAgentId; text: string } | null>(null);const [keyOpen, setKeyOpen] = React.useState(false);const [diagnosis, setDiagnosis] = React.useState<{ id: HostAgentId; report: HostAgentDiagnosis | null; copied?: boolean } | null>(null);+ /* the agent whose installer the person is asked about */+ const [confirming, setConfirming] = React.useState<HostAgentId | null>(null);if (!host) return null;const act = (id: HostAgentId, run: () => Promise<{ ok?: boolean; error?: string } | unknown>) => {@@ -129,6 +133,8 @@ export function AgentsSection() {if (r.ok) setDiagnosis(null);if (r.ok || (!r.error && !r.code)) return { ok: true };if (r.code === 'not-a-program') return { ok: false, error: t('settings.agents.notAProgram') };+ if (r.code === 'app') return { ok: false, error: t('settings.agents.notTheAgentApp').replaceAll('{name}', agent.name) };+ if (r.code === 'not-cursor-agent') return { ok: false, error: t('settings.agents.notCursorAgent') };if (r.code === 'did-not-start') return { ok: false, error: `${t('settings.agents.didNotStart')} ${r.error ?? ''}`.trim() };return r;});@@ -161,7 +167,10 @@ export function AgentsSection() {case 'off': return t('settings.agents.off');case 'sign-in': return t('settings.agents.signedOut');case 'waiting': return t('settings.agents.waiting');- case 'missing': return agent.setupRequired === 'code-tab' ? t('settings.agents.claudeSetup') : t('settings.agents.missing');+ case 'missing':+ if (agent.setupRequired === 'code-tab') return t('settings.agents.claudeSetup');+ if (agent.installing) return t('settings.agents.installing');+ return agent.app ? t('settings.agents.appOnly').replace('{app}', agent.app).replaceAll('{name}', agent.name) : t('settings.agents.missing');case 'key': return t('settings.agents.needsKey');case 'unavailable': return t('settings.agents.unavailable');case 'checking': return t('settings.agents.checking');@@ -204,7 +213,12 @@ export function AgentsSection() {{t('settings.agents.locate')}</SettingsButton>) : null}- {agent.install ? <SettingsLinkButton href={agent.install}><Download size={16} />{t('settings.agents.install')}</SettingsLinkButton> : null}+ {/* its official installer, run once the person agrees to the command; else its install page */}+ {agent.installer && host.install ? (+ <SettingsButton disabled={working || agent.installing || confirming === agent.id} onClick={() => setConfirming(agent.id)}>+ <Download size={16} />{t('settings.agents.install')}+ </SettingsButton>+ ) : agent.install ? <SettingsLinkButton href={agent.install}><Download size={16} />{t('settings.agents.install')}</SettingsLinkButton> : null}</>);}@@ -242,6 +256,7 @@ export function AgentsSection() {const plan = usage[agent.id];const meter = chosen && agent.status === 'ready' && PLAN_AGENTS.includes(agent.id) && Boolean(host.usage) && (plan === undefined || Boolean(plan?.windows.length));const hint = diag?.report ? hintOf(diag.report) : null;+ const asking = confirming === agent.id && agent.status === 'missing' && agent.installer && host.install ? agent.installer : null;return (<SettingsItemkey={agent.id}@@ -269,7 +284,7 @@ export function AgentsSection() {</>)}>- {agent.status === 'waiting' || open || said || agent.chosen || lost || meter || (chosen && agent.status === 'ready' && (host.mcp || host.skills)) ? (+ {agent.status === 'waiting' || open || said || agent.chosen || lost || meter || asking || (chosen && agent.status === 'ready' && (host.mcp || host.skills)) ? (<div className="flex flex-col gap-1.5 pl-[34px]">{meter ? (<div className="flex flex-col gap-1.5" aria-label={t('settings.agents.usage')}>@@ -288,6 +303,16 @@ export function AgentsSection() {) : null}</p>) : null}+ {asking ? (+ <SettingsInset>+ <p className="text-[14px] leading-relaxed text-[var(--text)]">{t('settings.agents.installConfirm').replace('{name}', agent.name)}</p>+ <code className="block break-all rounded-[6px] bg-[var(--fill-tsp)] px-2.5 py-2 font-mono text-[12.5px] text-[var(--text)]">{asking}</code>+ <div className="flex justify-end gap-1.5">+ <SettingsButton variant="quiet" onClick={() => setConfirming(null)}>{t('settings.agents.cancel')}</SettingsButton>+ <SettingsButton variant="primary" onClick={() => { setConfirming(null); act(agent.id, () => host.install!(agent.id)); }}>{t('settings.agents.installRun')}</SettingsButton>+ </div>+ </SettingsInset>+ ) : null}{lost && !diag ? (<p className="text-[13.5px] leading-relaxed text-[var(--text-muted)]"><button type="button" onClick={() => diagnose(agent)} className="underline underline-offset-2 hover:text-[var(--text)]">{t('settings.agents.whyMissing')}</button>diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.tsindex 4b796a1..55d5763 100644--- a/packages/openfilm/studio/ui/src/i18n/en.ts+++ b/packages/openfilm/studio/ui/src/i18n/en.ts@@ -1580,6 +1580,12 @@ export const en = {chosenAt: 'Using the program you chose: {path}',automatic: 'Find it automatically',notAProgram: 'That is not a program this computer can start. Choose the agent’s program itself (on Windows, the .exe or .cmd file).',+ appOnly: 'The {app} app is installed, but connecting needs {name}’s command-line agent.',+ installing: 'Installing in a terminal window… OpenFilm finds it once it’s done.',+ installConfirm: 'OpenFilm opens a terminal window and runs {name}’s official installer:',+ installRun: 'Run installer',+ notTheAgentApp: 'This is an editor or a desktop app, not {name}’s command-line agent. Connecting needs {name}’s command-line agent.',+ notCursorAgent: 'This is not Cursor’s command-line agent, which installs in a cursor-agent folder. Connecting needs Cursor’s command-line agent.',didNotStart: 'It did not start from there:',unreadable: 'It can’t read its own settings, so it can’t start. Fix what it names in its config file, or update it:',whyMissing: 'Why isn’t it found?',diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.tsindex 4d4ed6c..a59f8c9 100644--- a/packages/openfilm/studio/ui/src/i18n/es.ts+++ b/packages/openfilm/studio/ui/src/i18n/es.ts@@ -1579,6 +1579,12 @@ export const es: Words = {chosenAt: 'Usando el programa que elegiste: {path}',automatic: 'Detectarlo automáticamente',notAProgram: 'Ese archivo no es un programa que este equipo pueda abrir. Elige el programa del agente (en Windows, el archivo .exe o .cmd).',+ appOnly: 'La app {app} está instalada, pero para conectar hace falta el agente de línea de comandos de {name}.',+ installing: 'Instalando en una ventana de terminal… OpenFilm lo encontrará al terminar.',+ installConfirm: 'OpenFilm abre una ventana de terminal y ejecuta el instalador oficial de {name}:',+ installRun: 'Ejecutar instalador',+ notTheAgentApp: 'Esto es un editor o una app de escritorio, no el agente de línea de comandos de {name}. Para conectar hace falta el agente de línea de comandos de {name}.',+ notCursorAgent: 'Esto no es el agente de línea de comandos de Cursor, que se instala en una carpeta cursor-agent. Para conectar hace falta el agente de línea de comandos de Cursor.',didNotStart: 'No se pudo iniciar desde ahí:',unreadable: 'No puede leer su propia configuración, así que no puede iniciarse. Corrige lo que indica en su archivo de configuración o actualízalo:',whyMissing: '¿Por qué no se encuentra?',diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.tsindex b7e5f60..dda10a8 100644--- a/packages/openfilm/studio/ui/src/i18n/ja.ts+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts@@ -1579,6 +1579,12 @@ export const ja: Words = {chosenAt: '選択したプログラムを使用中:{path}',automatic: '自動検出に戻す',notAProgram: 'このコンピュータで起動できるプログラムではありません。エージェントのプログラム自体を選んでください(Windows では .exe または .cmd ファイル)。',+ appOnly: '{app} アプリはインストールされていますが、接続には {name} のコマンドラインエージェントが必要です。',+ installing: 'ターミナルウィンドウでインストール中… 終わると OpenFilm が見つけます。',+ installConfirm: 'OpenFilm はターミナルウィンドウを開き、{name} の公式インストーラーを実行します:',+ installRun: 'インストーラーを実行',+ notTheAgentApp: 'これはエディターかデスクトップアプリで、{name} のコマンドラインエージェントではありません。接続には {name} のコマンドラインエージェントが必要です。',+ notCursorAgent: 'これは Cursor のコマンドラインエージェントではありません(cursor-agent フォルダーにインストールされます)。接続には Cursor のコマンドラインエージェントが必要です。',didNotStart: 'ここからは起動できませんでした:',unreadable: '自分の設定を読み込めないため起動できません。設定ファイルの該当箇所を直すか、更新してください:',whyMissing: '見つからない理由は?',diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.tsindex 6057bf3..87bfd1d 100644--- a/packages/openfilm/studio/ui/src/i18n/ko.ts+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts@@ -1578,6 +1578,12 @@ export const ko: Words = {chosenAt: '선택한 프로그램 사용 중: {path}',automatic: '자동 감지로 되돌리기',notAProgram: '이 컴퓨터에서 실행할 수 있는 프로그램이 아닙니다. 에이전트 프로그램 자체를 선택하세요(Windows에서는 .exe 또는 .cmd 파일).',+ appOnly: '{app} 앱은 설치되어 있지만, 연결하려면 {name}의 명령줄 에이전트가 필요합니다.',+ installing: '터미널 창에서 설치하는 중… 끝나면 OpenFilm이 찾습니다.',+ installConfirm: 'OpenFilm이 터미널 창을 열고 {name}의 공식 설치 프로그램을 실행합니다:',+ installRun: '설치 프로그램 실행',+ notTheAgentApp: '이것은 편집기나 데스크톱 앱이며, {name}의 명령줄 에이전트가 아닙니다. 연결하려면 {name}의 명령줄 에이전트가 필요합니다.',+ notCursorAgent: '이것은 Cursor의 명령줄 에이전트가 아닙니다(cursor-agent 폴더에 설치됩니다). 연결하려면 Cursor의 명령줄 에이전트가 필요합니다.',didNotStart: '여기서 실행하지 못했습니다:',unreadable: '자체 설정을 읽지 못해 시작할 수 없습니다. 설정 파일에서 지적된 부분을 고치거나 업데이트하세요:',whyMissing: '왜 찾지 못하나요?',diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.tsindex 9cab804..10b7e61 100644--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts@@ -1580,6 +1580,12 @@ export const zhCN: Words = {chosenAt: '正在使用你选择的程序:{path}',automatic: '改回自动检测',notAProgram: '这不是这台电脑能启动的程序。请选择智能体程序本身(Windows 上是 .exe 或 .cmd 文件)。',+ appOnly: '已安装 {app} 应用,但连接需要 {name} 的命令行智能体。',+ installing: '正在终端窗口中安装… 装好后 OpenFilm 会找到它。',+ installConfirm: 'OpenFilm 会打开一个终端窗口,运行 {name} 的官方安装命令:',+ installRun: '运行安装',+ notTheAgentApp: '这是编辑器或桌面应用,不是 {name} 的命令行智能体。连接需要 {name} 的命令行智能体。',+ notCursorAgent: '这不是 Cursor 的命令行智能体(它安装在 cursor-agent 文件夹里)。连接需要 Cursor 的命令行智能体。',didNotStart: '从这里启动失败:',unreadable: '它读不了自己的设置,所以无法启动。请修改它的配置文件里提到的那一项,或更新它:',whyMissing: '为什么检测不到?',diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.tsindex e739ff1..f8bb03f 100644--- a/packages/openfilm/studio/ui/src/lib/host.ts+++ b/packages/openfilm/studio/ui/src/lib/host.ts@@ -80,7 +80,8 @@ export interface StudioHost {* and returns a way to stop listening. One of the person's own agents, found or not, can be pointed at a program* of the person's choosing (`locate`: the system's file dialog, with Studio's words; `{ ok: false }` and no error* when cancelled) and set back to being found (`useAutomatic`); `diagnose` says what was searched (an older app- * has none of these).+ * has none of these). One not found that has an official installer (`HostAgent.installer`) can be installed:+ * `install` runs it in a terminal window, once the person agreed to that command (an older app has none).*/agents?: {list: () => Promise<HostAgent[]>;@@ -89,7 +90,8 @@ export interface StudioHost {/** Codex: what is left of its plan, as it says for the account signed in (null: it can't say; other agents, null) */usage?: (id: HostAgentId, fresh?: boolean) => Promise<HostAgentUsage | null>;setShown: (id: HostAgentId, shown: boolean) => Promise<unknown>;- locate?: (id: HostAgentId, words?: { title?: string; button?: string }) => Promise<{ ok: boolean; error?: string; code?: 'not-a-program' | 'did-not-start' | string }>;+ locate?: (id: HostAgentId, words?: { title?: string; button?: string }) => Promise<{ ok: boolean; error?: string; code?: 'not-a-program' | 'did-not-start' | 'app' | 'not-cursor-agent' | string }>;+ install?: (id: HostAgentId) => Promise<{ ok: boolean; error?: string }>;useAutomatic?: (id: HostAgentId) => Promise<unknown>;diagnose?: (id: HostAgentId) => Promise<HostAgentDiagnosis | null>;/** The app's part of Settings → Developer's diagnostic report: the app, and each agent's program, version and state, as text. */@@ -225,6 +227,11 @@ export interface HostAgent {install?: string | null;/** What installing it takes, when `install` is not a download: 'code-tab', Claude Code comes with the Claude app (its Code tab). */setupRequired?: string | null;+ /** Not installed: the maker's desktop app when only that is here (`Cursor`), and the official command that installs it. */+ app?: string | null;+ installer?: string | null;+ /** Its installer is running in a terminal window: it is looked for again until it is there. */+ installing?: boolean;/** The program used (the person's own agents), and the one the person chose for it, if they did. */path?: string | null;chosen?: string | null;