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: fix Windows agent discovery and connection setup (#271)

riverisbuildinge7541420eba3
diff --git a/.changeset/agent-setup-guidance.md b/.changeset/agent-setup-guidance.md
new file mode 100644
index 0000000..9249cca
--- /dev/null
+++ b/.changeset/agent-setup-guidance.md
@@ -0,0 +1,6 @@
+---
+"@openfilm/desktop": patch
+"openfilm": patch
+---
+
+Identify connection components separately from installed desktop apps, open Claude for Code setup, and use a single installation-folder picker to find an existing connection program. Put a help icon at the end of each agent's description, opening connection instructions, manual location and opt-in diagnostics in a dialog. Keep connection actions and visibility switches directly accessible. Discover agents in the background and publish each result immediately, prioritizing enabled agents and checking sign-in only for those in use. Load model options only for the selected agent. Refresh connections re-reads configuration, renews idle sessions and model menus, and clears errors from the previous configuration without interrupting running turns. Discovery and protocol checks do not send model test requests.
diff --git a/.changeset/windows-desktop-agent-discovery.md b/.changeset/windows-desktop-agent-discovery.md
new file mode 100644
index 0000000..cda502d
--- /dev/null
+++ b/.changeset/windows-desktop-agent-discovery.md
@@ -0,0 +1,6 @@
+---
+"@openfilm/desktop": patch
+"openfilm": patch
+---
+
+Find the agent programs bundled with OpenCode and GitHub Copilot on Windows, and DeepSeek Harness installed in a custom folder. Recognize registered desktop apps outside their default folders, including MiniMax's icon-only registration, so an installed editor is distinguished from a missing command-line agent. Choosing the DeepSeek Harness, OpenCode, or GitHub Copilot desktop executable now locates its bundled or app-managed agent. Find MiniMax's Windows CLI at its install root and keep its own launcher so native SQLite uses the correct Node runtime. An agent that cannot be found is no longer described as not installed.
diff --git a/apps/desktop/bench/agent-setup.test.mjs b/apps/desktop/bench/agent-setup.test.mjs
new file mode 100644
index 0000000..0c7efce
--- /dev/null
+++ b/apps/desktop/bench/agent-setup.test.mjs
@@ -0,0 +1,137 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import { chromium } from 'playwright-core';
+import shellConfig from '../shell/vite.config.ts';
+
+test('agent setup guides desktop-only installs, folder selection and model failures without losing a working program', { timeout: 90_000 }, async () => {
+ const server = await createServer({
+ ...shellConfig, configFile: false, root: fileURLToPath(new URL('..', import.meta.url)),
+ server: { host: '127.0.0.1', port: 0 }, logLevel: 'error',
+ plugins: [...shellConfig.plugins, { name: 'agent-setup-fixture', configureServer(app) {
+ app.middlewares.use('/agent-setup-ui', (_req, res, next) => {
+ res.setHeader('content-type', 'text/html');
+ void app.transformIndexHtml('/agent-setup-ui', '<!doctype html><html><body><div id="root"></div><script type="module" src="/bench/agent-sign-in.tsx"></script></body></html>')
+ .then((html) => res.end(html), next);
+ });
+ } }],
+ });
+ let browser;
+ try {
+ await server.listen();
+ browser = await chromium.launch({ headless: true });
+ for (const locale of ['en', 'zh-CN']) {
+ const page = await browser.newPage({ viewport: { width: 1100, height: 780 } });
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.addInitScript((locale) => {
+ localStorage.setItem('openfilm.language', locale);
+ let agents = [
+ { id: 'claude', name: 'Claude Code', shown: true, status: 'missing', setupRequired: 'code-tab' },
+ { id: 'cursor', name: 'Cursor', shown: false, status: 'missing', app: 'Cursor', installer: 'official-install-command' },
+ { id: 'opencode', name: 'OpenCode', shown: true, status: 'ready', path: 'C:/Apps/OpenCode/resources/opencode-cli.exe', connectionIssue: { kind: 'quota', message: 'Free usage limit reached. Raw quota fixture.' } },
+ { id: 'deepseek', name: 'DeepSeek Harness', shown: true, status: 'ready', path: 'D:/Apps/DeepSeek/resources/runtime/cli/bin/dsh.cmd', connectionIssue: { kind: 'credentials', message: 'no API key for provider route "deepseek-official"' } },
+ ];
+ const listeners = new Set();
+ const calls = { setup: [], locate: [], connect: [], install: [], refresh: 0, parentEscape: 0, diagnose: 0 };
+ window.addEventListener('keydown', (event) => { if (event.key === 'Escape' && !event.defaultPrevented) calls.parentEscape++; });
+ const publish = (id, patch) => { agents = agents.map((a) => a.id === id ? { ...a, ...patch } : a); for (const listener of listeners) listener(agents); };
+ window.openfilmHost = { version: 1, agents: {
+ list: async () => agents,
+ refresh: async () => { calls.refresh++; publish('opencode', { connectionIssue: undefined }); publish('deepseek', { connectionIssue: undefined }); return agents; },
+ connect: async (id) => { calls.connect.push(id); return { ok: true }; },
+ disconnect: async () => {}, setShown: async () => {},
+ openSetup: async (id) => { calls.setup.push(id); return { ok: true }; },
+ install: async (id) => { calls.install.push(id); return { ok: true }; },
+ locate: async (id, words) => {
+ calls.locate.push({ id, kind: words.kind });
+ if (calls.locate.length === 1) return { ok: false, code: 'not-a-program', error: 'no component in folder' };
+ publish(id, { status: 'off', path: 'D:/Custom Agent/bin/agent.cmd' });
+ return { ok: true, path: 'D:/Custom Agent/bin/agent.cmd', version: '1.2.3' };
+ },
+ diagnose: async () => { calls.diagnose++; return { found: 'D:/Custom Agent/bin/agent.cmd', hint: null, text: 'Agent diagnostic fixture: custom folder discovered' }; },
+ onChange: (listener) => { listeners.add(listener); return () => listeners.delete(listener); },
+ } };
+ window.agentSetupFixture = { calls, publish };
+ }, locale);
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/agent-setup-ui`);
+ const zh = locale === 'zh-CN';
+ await page.evaluate((dark) => { document.documentElement.dataset.theme = dark ? 'dark' : 'light'; }, zh);
+ const row = (name) => page.locator('div.py-4').filter({ has: page.getByText(name, { exact: true }) });
+ const helpButton = (name) => row(name).getByRole('button', { name: zh ? `${name} 的连接帮助` : `Connection help for ${name}`, exact: true });
+ const helpDialog = () => page.getByRole('dialog');
+ const closeHelp = () => helpDialog().getByRole('button', { name: zh ? '知道了' : 'Got it', exact: true }).click();
+ const manual = () => helpDialog().getByRole('button', { name: zh ? '手动选择安装文件夹…' : 'Choose installation folder…', exact: true });
+ await helpButton('Cursor').waitFor();
+ assert.equal(await page.getByRole('button', { name: zh ? '手动选择安装文件夹…' : 'Choose installation folder…', exact: true }).count(), 0, 'folder selection is only offered inside diagnosis details');
+ assert.equal(await page.getByRole('button', { name: zh ? '手动选择…' : 'Locate…', exact: true }).count(), 0, 'manual selection is only available inside help');
+ const description = row('Cursor').getByText(zh ? '已发现 Cursor 桌面应用,需要补充连接组件。' : 'Found the Cursor desktop app. A connection component is needed.', { exact: true });
+ const descriptionBounds = await description.boundingBox();
+ const helpBounds = await helpButton('Cursor').boundingBox();
+ assert.ok(helpBounds.x >= descriptionBounds.x + descriptionBounds.width - 1, 'help icon follows the description text');
+ assert.ok(helpBounds.y < descriptionBounds.y + descriptionBounds.height && helpBounds.y + helpBounds.height > descriptionBounds.y, 'help stays on the description line without an extra row');
+ assert.equal(await page.getByRole('button', { name: zh ? '为什么检测不到?' : 'Why isn’t it found?', exact: true }).count(), 0);
+ if (zh && process.env.OPENFILM_HELP_LIST_PREVIEW) await page.screenshot({ path: process.env.OPENFILM_HELP_LIST_PREVIEW, fullPage: true });
+ await helpButton('Cursor').click();
+ await helpDialog().getByRole('heading', { name: zh ? '如何连接' : 'How to connect', exact: true }).waitFor();
+ assert.equal(await manual().count(), 1, 'manual location remains available in the help dialog');
+ assert.equal(await helpDialog().getByRole('button', { name: zh ? '手动选择…' : 'Locate…', exact: true }).count(), 0, 'the separate program-file selector has been removed');
+ assert.equal(await helpDialog().getByRole('heading', { name: zh ? '检测不到怎么办' : 'If the agent is not found', exact: true }).isVisible(), true);
+ assert.equal(await page.evaluate(() => window.agentSetupFixture.calls.diagnose), 0, 'opening instructions does not start a diagnostic process');
+ if (zh && process.env.OPENFILM_HELP_PREVIEW) await page.screenshot({ path: process.env.OPENFILM_HELP_PREVIEW, fullPage: true });
+ await page.keyboard.press('Tab');
+ assert.equal(await helpDialog().evaluate((dialog) => dialog.contains(document.activeElement)), true, 'keyboard focus stays inside connection help');
+ await page.keyboard.press('Escape');
+ await helpDialog().waitFor({ state: 'hidden' });
+ assert.equal(await page.evaluate(() => window.agentSetupFixture.calls.parentEscape), 0, 'Escape closes only connection help, not the parent settings');
+ assert.equal(await helpButton('Cursor').evaluate((button) => button === document.activeElement), true, 'focus returns to the help icon');
+ await page.getByRole('button', { name: zh ? '打开 Claude' : 'Open Claude', exact: true }).click();
+ assert.deepEqual(await page.evaluate(() => window.agentSetupFixture.calls.setup), ['claude']);
+ await page.getByRole('button', { name: zh ? '安装连接组件' : 'Install connection component', exact: true }).click();
+ assert.equal(await page.getByText('official-install-command', { exact: true }).isVisible(), true);
+ assert.deepEqual(await page.evaluate(() => window.agentSetupFixture.calls.install), [], 'the install command still needs an explicit user action');
+ await page.getByRole('button', { name: zh ? '取消' : 'Cancel', exact: true }).click();
+ assert.equal(await page.getByRole('switch').count(), 4, 'visibility switches remain directly accessible');
+ assert.equal(await page.getByRole('button', { name: /More actions for|的更多操作/ }).count(), 0);
+ await helpButton('Cursor').click();
+ await manual().click();
+ await helpDialog().waitFor();
+ await helpDialog().getByRole('status').filter({ hasText: zh ? '所选文件夹中未找到 Cursor 的连接组件' : 'No Cursor connection component was found in this folder' }).waitFor();
+ await closeHelp();
+ await page.getByRole('status').filter({ hasText: zh ? '所选文件夹中未找到 Cursor 的连接组件' : 'No Cursor connection component was found in this folder' }).waitFor();
+ assert.equal(await page.getByRole('alert').count(), 0, 'a folder without a component gets setup guidance');
+ await helpButton('Cursor').click();
+ await manual().click();
+ await helpDialog().waitFor({ state: 'hidden' });
+ await page.getByRole('status').filter({ hasText: zh ? '连接程序已就绪' : 'Connection program is ready' }).waitFor();
+ assert.deepEqual(await page.evaluate(() => window.agentSetupFixture.calls.locate), [{ id: 'cursor', kind: 'folder' }, { id: 'cursor', kind: 'folder' }], 'the single location action always opens a folder picker');
+ await helpButton('Cursor').click();
+ await helpDialog().getByText('D:/Custom Agent/bin/agent.cmd', { exact: true }).waitFor();
+ await helpDialog().getByRole('button', { name: zh ? '重新检测' : 'Check again', exact: true }).click();
+ const summary = helpDialog().locator('summary').filter({ hasText: zh ? '技术详情' : 'Technical details' });
+ await summary.waitFor();
+ assert.equal(await page.getByText('Agent diagnostic fixture: custom folder discovered', { exact: true }).isVisible(), false);
+ await summary.click();
+ assert.equal(await page.getByText('Agent diagnostic fixture: custom folder discovered', { exact: true }).isVisible(), true);
+ await closeHelp();
+ await helpButton('OpenCode').click();
+ await page.getByText('C:/Apps/OpenCode/resources/opencode-cli.exe', { exact: true }).waitFor();
+ assert.equal(await page.getByText(/Raw quota fixture/).isVisible(), false, 'raw provider errors start collapsed');
+ assert.equal(await page.getByRole('button', { name: zh ? '安装连接组件' : 'Install connection component', exact: true }).count(), 0, 'a model failure does not suggest reinstalling a found agent');
+ await closeHelp();
+ await helpButton('DeepSeek Harness').click();
+ await page.getByText('D:/Apps/DeepSeek/resources/runtime/cli/bin/dsh.cmd', { exact: true }).waitFor();
+ assert.equal(await helpDialog().getByText(zh ? '当前模型需要配置凭据' : 'The current model needs credentials', { exact: true }).isVisible(), true);
+ assert.equal(await page.getByText(zh ? /在 DeepSeek Harness 的模型设置中/ : /Configure credentials for the current provider in DeepSeek Harness/).isVisible(), true);
+ await closeHelp();
+ await page.getByRole('button', { name: zh ? '刷新检查' : 'Refresh connections', exact: true }).click();
+ assert.equal(await page.getByText(zh ? '当前模型额度已用完' : 'The current model has no quota left', { exact: true }).count(), 0);
+ assert.equal(await page.getByText(zh ? '当前模型需要配置凭据' : 'The current model needs credentials', { exact: true }).count(), 0);
+ assert.equal(await page.evaluate(() => window.agentSetupFixture.calls.refresh), 1);
+ assert.deepEqual(await page.evaluate(() => window.agentSetupFixture.calls.connect), [], 'rendering and checking setup never submit model requests or reconnect automatically');
+ assert.deepEqual(errors, []);
+ await page.close();
+ }
+ } finally { await browser?.close(); await server.close(); }
+});
diff --git a/apps/desktop/bench/agent-sign-in.test.mjs b/apps/desktop/bench/agent-sign-in.test.mjs
index e09ee9f..e3dc5cc 100644
--- a/apps/desktop/bench/agent-sign-in.test.mjs
+++ b/apps/desktop/bench/agent-sign-in.test.mjs
@@ -49,7 +49,7 @@ test('Settings allows cancelling sign-in and restores the login button on termin
}, locale);
await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/agent-sign-in-ui`);
const cancel = page.getByRole('button', { name: locale === 'en' ? 'Cancel' : '取消', exact: true });
- const login = page.getByRole('button', { name: locale === 'en' ? 'Sign in' : '登录', exact: true });
+ const login = page.getByRole('button', { name: locale === 'en' ? 'Sign in and connect' : '登录并连接', exact: true });
await cancel.click();
await login.waitFor();
assert.equal(await login.isEnabled(), true);
diff --git a/apps/desktop/bench/agent-startup.test.mjs b/apps/desktop/bench/agent-startup.test.mjs
new file mode 100644
index 0000000..dd56822
--- /dev/null
+++ b/apps/desktop/bench/agent-startup.test.mjs
@@ -0,0 +1,46 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import { chromium } from 'playwright-core';
+import shellConfig from '../shell/vite.config.ts';
+
+test('selected model loads before background discovery, ignores an older roster and refreshes after configuration changes', { timeout: 60_000 }, async () => {
+ const server = await createServer({
+ ...shellConfig, configFile: false, root: fileURLToPath(new URL('..', import.meta.url)), server: { host: '127.0.0.1', port: 0 }, logLevel: 'error',
+ plugins: [...shellConfig.plugins, { name: 'agent-startup-fixture', configureServer(app) {
+ app.middlewares.use('/agent-startup-ui', (_req, res, next) => {
+ res.setHeader('content-type', 'text/html');
+ void app.transformIndexHtml('/agent-startup-ui', '<!doctype html><html><body><div id="root"></div><script type="module" src="/bench/agent-startup.tsx"></script></body></html>').then((html) => res.end(html), next);
+ });
+ } }],
+ });
+ let browser;
+ try {
+ await server.listen();
+ browser = await chromium.launch({ headless: true });
+ const page = await browser.newPage({ viewport: { width: 1000, height: 650 } });
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(e.message));
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/agent-startup-ui`);
+ await page.waitForFunction(() => window.agentStartupFixture && window.agentStartupFixture.state() === null);
+ await page.evaluate(() => window.agentStartupFixture.checking());
+ assert.deepEqual(await page.evaluate(() => window.agentStartupFixture.calls), [], 'the saved selection is kept while it is checking, instead of probing a different ready agent');
+ await page.evaluate(() => window.agentStartupFixture.ready());
+ await page.getByRole('button', { name: 'Codex Ready Model', exact: true }).waitFor();
+ assert.deepEqual(await page.evaluate(() => window.agentStartupFixture.calls), ['codex']);
+ assert.equal(await page.evaluate(() => window.agentStartupFixture.state().find((a) => a.id === 'cursor').status), 'checking');
+ await page.evaluate(() => window.agentStartupFixture.release());
+ await page.waitForTimeout(30);
+ assert.equal(await page.evaluate(() => window.agentStartupFixture.state().find((a) => a.id === 'codex').status), 'ready', 'an old checking snapshot cannot replace a newer ready update');
+ await page.locator('[data-model-picker] button').first().click();
+ assert.deepEqual(await page.evaluate(() => window.agentStartupFixture.calls), ['codex'], 'opening the menu does not prefetch other agents');
+ await page.getByRole('button', { name: 'OpenCode', exact: true }).click();
+ await page.getByRole('button', { name: 'OpenCode Ready Model', exact: true }).waitFor();
+ assert.deepEqual(await page.evaluate(() => window.agentStartupFixture.calls), ['codex', 'opencode']);
+ await page.evaluate(() => window.agentStartupFixture.refresh());
+ await page.getByRole('button', { name: 'OpenCode Updated Model', exact: true }).waitFor();
+ assert.deepEqual(await page.evaluate(() => window.agentStartupFixture.calls), ['codex', 'opencode', 'opencode']);
+ assert.deepEqual(errors, []);
+ } finally { await browser?.close(); await server.close(); }
+});
diff --git a/apps/desktop/bench/agent-startup.tsx b/apps/desktop/bench/agent-startup.tsx
new file mode 100644
index 0000000..16fc0b5
--- /dev/null
+++ b/apps/desktop/bench/agent-startup.tsx
@@ -0,0 +1,50 @@
+/** Startup/model refresh fixture: no agent process or model request is started. */
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { ModelPopover } from '../chat/src/components/ModelPopover';
+import { useLocalAgents } from '../chat/src/state/local-agent-store';
+import type { RosterAgent } from '../chat/src/lib/desktop-bridge';
+import '../shell/shell.css';
+import '../chat/src/chat.css';
+
+localStorage.setItem('openfilm.language', 'en');
+localStorage.setItem('openfilm.local-agents.v2', JSON.stringify({ picked: 'codex', prefs: {}, options: {} }));
+let roster: RosterAgent[] = [
+ { id: 'codex', name: 'Codex', shown: true, status: 'checking' },
+ { id: 'opencode', name: 'OpenCode', shown: true, status: 'ready' },
+ { id: 'cursor', name: 'Cursor', shown: false, status: 'checking' },
+];
+const initial = structuredClone(roster);
+const listeners = new Set<(list: RosterAgent[]) => void>();
+const calls: string[] = [];
+let release: (list: RosterAgent[]) => void = () => {};
+let released = false;
+const oldList = new Promise<RosterAgent[]>((done) => { release = done; });
+const publish = () => { for (const listener of listeners) listener(roster); };
+(window as any).openfilmDesktop = {
+ agents: {
+ list: async () => released ? roster : oldList,
+ onChange: (listener: (list: RosterAgent[]) => void) => { listeners.add(listener); return () => listeners.delete(listener); },
+ },
+ localAgents: {
+ probe: async (id: string) => {
+ calls.push(id);
+ const revision = roster.find((a) => a.id === id)?.configurationRevision ?? 0;
+ const name = `${id === 'codex' ? 'Codex' : 'OpenCode'} ${revision ? 'Updated' : 'Ready'} Model`;
+ return { ok: true, info: { configOptions: [{ id: 'model', category: 'model', name: 'Model', currentValue: 'model', options: [{ name, value: 'model' }] }] } };
+ },
+ },
+};
+(window as any).agentStartupFixture = {
+ checking: () => publish(),
+ ready: () => { roster = roster.map((a) => a.id === 'codex' ? { ...a, status: 'ready' } : a); publish(); },
+ release: () => { released = true; release(initial); },
+ refresh: () => { roster = roster.map((a) => ({ ...a, configurationRevision: 1 })); publish(); },
+ calls,
+ state: () => useLocalAgents.getState().roster,
+};
+createRoot(document.getElementById('root')!).render(
+ <div className="of-chat" style={{ padding: 40, width: 520 }}>
+ <div data-model-picker><ModelPopover /></div><div id="of-chat-layer" className="of-chat" />
+ </div>,
+);
diff --git a/apps/desktop/chat/src/App.tsx b/apps/desktop/chat/src/App.tsx
index 585248e..901d5e0 100644
--- a/apps/desktop/chat/src/App.tsx
+++ b/apps/desktop/chat/src/App.tsx
@@ -253,7 +253,7 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
/* ── the agent ── */
const la = useLocalAgents();
- React.useEffect(() => { la.hydrate(); void la.refresh(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
+ React.useEffect(() => { la.hydrate(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
/* the agent this conversation used and its options, whatever was picked since in another one; a new conversation
takes the one picked last (lib/conversation-agent). A conversation from before they kept it: its last turn's agent */
const shownSessionItem = sessions.find((s) => s.id === sessionId);
diff --git a/apps/desktop/chat/src/components/ModelPopover.tsx b/apps/desktop/chat/src/components/ModelPopover.tsx
index 7c0e283..edaba69 100644
--- a/apps/desktop/chat/src/components/ModelPopover.tsx
+++ b/apps/desktop/chat/src/components/ModelPopover.tsx
@@ -104,13 +104,14 @@ export function ModelPopover({ placement = 'bottom', align = 'start', agent: con
const agent = conversationAgent ?? currentAgent(la);
const shown = shownAgents(la.roster);
const ready = (id: LocalAgentId) => shown.find((a) => a.id === id)?.status === 'ready';
- React.useEffect(() => { if (ready(agent)) void ensureOptions(agent); });
+ const selectedReady = ready(agent);
+ const configurationRevision = la.roster?.find((a) => a.id === agent)?.configurationRevision;
+ React.useEffect(() => { if (selectedReady) void ensureOptions(agent); }, [agent, selectedReady, configurationRevision, ensureOptions]);
React.useEffect(() => {
if (!open) return;
- void refresh().then(() => {
- for (const a of shownAgents(useLocalAgents.getState().roster)) if (a.status === 'ready') void ensureOptions(a.id, { retry: true });
- });
- }, [open, refresh, ensureOptions]);
+ void refresh();
+ if (useLocalAgents.getState().roster?.some((a) => a.id === agent && a.shown && a.status === 'ready')) void ensureOptions(agent, { retry: true });
+ }, [open, agent, refresh, ensureOptions]);
const picked = conversationPrefs ?? la.prefs;
const options = agentOptions({ ...la, prefs: picked }, agent);
diff --git a/apps/desktop/chat/src/lib/desktop-bridge.ts b/apps/desktop/chat/src/lib/desktop-bridge.ts
index ede1d4b..caa5419 100644
--- a/apps/desktop/chat/src/lib/desktop-bridge.ts
+++ b/apps/desktop/chat/src/lib/desktop-bridge.ts
@@ -23,6 +23,7 @@ export interface RosterAgent {
status: 'ready' | 'off' | 'sign-in' | 'waiting' | 'missing' | 'key' | 'checking';
install?: string | null;
setupRequired?: string | null;
+ configurationRevision?: number;
error?: string;
/** Whose sign-in it uses, when the agent tells (no key or token). */
account?: { method: string; email?: string; org?: string; plan?: string };
diff --git a/apps/desktop/chat/src/state/local-agent-store.ts b/apps/desktop/chat/src/state/local-agent-store.ts
index 69e3bb4..9950249 100644
--- a/apps/desktop/chat/src/state/local-agent-store.ts
+++ b/apps/desktop/chat/src/state/local-agent-store.ts
@@ -64,7 +64,7 @@ function probeModel(state: Persisted, agent: LocalAgentId): string | undefined {
return typeof model === 'string' && option?.options?.some((o) => o.value === model) ? model : undefined;
}
-const probeKey = (agent: LocalAgentId, model: string | undefined) => JSON.stringify([agent, model]);
+const probeKey = (agent: LocalAgentId, model: string | undefined, revision = 0) => JSON.stringify([agent, model, revision]);
const KEY = 'openfilm.local-agents.v2';
@@ -166,11 +166,12 @@ export function shownAgents(roster: RosterAgent[] | null): RosterAgent[] {
export function currentAgent(state: Pick<LocalAgentStore, 'picked' | 'roster'>): LocalAgentId {
const shown = shownAgents(state.roster);
const picked = shown.find((a) => a.id === state.picked);
- if (picked?.status === 'ready' || !state.roster) return state.picked;
+ if (picked && ['ready', 'checking', 'waiting'].includes(picked.status) || !state.roster) return state.picked;
return shown.find((a) => a.status === 'ready')?.id ?? picked?.id ?? shown[0]?.id ?? state.picked;
}
let listening = false;
+let rosterRevision = 0;
export const useLocalAgents = create<LocalAgentStore>((set, get) => ({
picked: 'claude',
@@ -186,9 +187,12 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({
if (api && !listening) {
listening = true;
api.onChange((roster) => {
+ rosterRevision++;
/* an agent that stopped being ready: what its sessions held goes (it may be another account next time) */
for (const before of get().roster ?? []) {
const now = roster.find((a) => a.id === before.id);
+ if (before.configurationRevision !== now?.configurationRevision || before.status !== 'ready' && now?.status === 'ready') askedThisLaunch.delete(before.id);
+ if (before.configurationRevision !== now?.configurationRevision) forgetLocalAgentSessions(before.id);
if (before.status === 'ready' && now?.status !== 'ready') forgetLocalAgentSessions(before.id);
/* other models (the own key's): its sessions were closed for the next ones to use them */
else if (JSON.stringify(byokModels([before])) !== JSON.stringify(byokModels(now ? [now] : []))) forgetLocalAgentSessions(before.id);
@@ -199,8 +203,9 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({
void get().refresh();
},
async refresh() {
+ const revision = rosterRevision;
const roster = await desktopBridge()?.agents?.list().catch(() => null);
- if (roster) set({ roster });
+ if (roster && revision === rosterRevision) set({ roster });
},
pick(picked) {
set({ picked });
@@ -238,8 +243,10 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({
/* the own key's are known from Settings (agentOptions); a failed probe is not tried again on every render, each
try being a whole session of the agent's */
if (agent === 'byok' || probing.has(agent)) return;
+ if (!get().roster?.some((a) => a.id === agent && a.shown && a.status === 'ready')) return;
const model = probeModel(get(), agent);
- const key = probeKey(agent, model);
+ const currentKey = () => probeKey(agent, probeModel(get(), agent), get().roster?.find((a) => a.id === agent)?.configurationRevision ?? 0);
+ const key = currentKey();
const kept = Boolean(get().options[agent]);
const matched = model == null || get().options[agent]?.find((o) => o.category === 'model')?.currentValue === model;
if (askedThisLaunch.get(agent) === key && (matched || get().optionsError[agent]) && (!retry || !get().optionsError[agent])) return;
@@ -251,14 +258,14 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({
try {
const r = await api.probe(agent, model).catch((e: unknown) => ({ ok: false as const, error: e instanceof Error ? e.message : String(e), code: undefined }));
// A newer model pick wins; an older response must not replace its effort list.
- if (probeKey(agent, probeModel(get(), agent)) !== key) return;
+ if (currentKey() !== key || !get().roster?.some((a) => a.id === agent && a.shown && a.status === 'ready')) return;
if (r.ok && r.info.commands?.length) keepCommands(agent, readCommands({ availableCommands: r.info.commands }));
if (r.ok && r.info.configOptions?.length) get().noteOptions(agent, r.info.configOptions);
/* the ones kept from before stay when this launch's ask fails */
else if (!kept || model != null) set({ optionsError: { ...get().optionsError, [agent]: r.ok ? { text: 'no options' } : { text: r.error, ...(r.code ? { code: r.code } : {}) } } });
} finally {
probing.delete(agent);
- if (probeKey(agent, probeModel(get(), agent)) !== key) void get().ensureOptions(agent);
+ if (currentKey() !== key) void get().ensureOptions(agent);
}
},
}));
diff --git a/apps/desktop/src/agent-connection-issue.mjs b/apps/desktop/src/agent-connection-issue.mjs
new file mode 100644
index 0000000..987820e
--- /dev/null
+++ b/apps/desktop/src/agent-connection-issue.mjs
@@ -0,0 +1,10 @@
+/** Actionable model failures, kept separately from program discovery and the person's connection choices. */
+export function agentConnectionIssue(error) {
+ const message = String(error?.message ?? error ?? '').trim();
+ if (!message) return null;
+ // A temporary rate limit (429) is not evidence that a plan or balance is exhausted.
+ const quota = /free usage limit reached|quota (?:exceeded|exhausted)|insufficient[_ ](?:quota|balance|credits)|(?:usage|spending|credit) limit (?:reached|exceeded)|(?:额度|余额)(?:已)?(?:用尽|耗尽|不足)/i;
+ const credentials = /no API key for provider route|missing[_ ]api[_ ]key|API key (?:is )?(?:missing|not (?:set|configured)|required)|(?:no|missing) credentials for (?:provider|model)|(?:模型|提供商).*(?:缺少|未配置).*(?:凭据|密钥)/i;
+ const kind = quota.test(message) ? 'quota' : credentials.test(message) ? 'credentials' : null;
+ return kind ? { kind, message: message.slice(0, 2000) } : null;
+}
diff --git a/apps/desktop/src/agent-connection-issue.test.mjs b/apps/desktop/src/agent-connection-issue.test.mjs
new file mode 100644
index 0000000..8132e01
--- /dev/null
+++ b/apps/desktop/src/agent-connection-issue.test.mjs
@@ -0,0 +1,13 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { agentConnectionIssue } from './agent-connection-issue.mjs';
+
+test('model quota and provider credentials are distinguished from discovery, authentication and temporary rate limits', () => {
+ assert.equal(agentConnectionIssue(new Error('Internal error: Free usage limit reached. Connect a provider or switch models.')).kind, 'quota');
+ assert.equal(agentConnectionIssue('insufficient_quota').kind, 'quota');
+ assert.equal(agentConnectionIssue('余额不足').kind, 'quota');
+ assert.equal(agentConnectionIssue(new Error('llm-deepseek: no API key for provider route "deepseek-official"')).kind, 'credentials');
+ for (const error of ['429 Too many requests', 'rate limit exceeded', 'not signed in', 'This is a desktop app', 'API key rejected', '', null]) {
+ assert.equal(agentConnectionIssue(error), null, String(error));
+ }
+});
diff --git a/apps/desktop/src/agent-installation.mjs b/apps/desktop/src/agent-installation.mjs
index fdf4252..2e1290f 100644
--- a/apps/desktop/src/agent-installation.mjs
+++ b/apps/desktop/src/agent-installation.mjs
@@ -8,9 +8,10 @@
import { execFileSync } from 'node:child_process';
import { accessSync, closeSync, constants, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
-import { delimiter, dirname, isAbsolute, join } from 'node:path';
+import { basename, delimiter, dirname, isAbsolute, join } from 'node:path';
import { AGENT_DEFINITIONS, OWN_AGENT_IDS } from './agent-definitions.mjs';
+import { installedWindowsApps } from './windows-apps.mjs';
export const AGENT_DOWNLOADS = Object.freeze(Object.fromEntries(OWN_AGENT_IDS.map((id) => [id, AGENT_DEFINITIONS[id].install])));
/**
@@ -33,7 +34,7 @@ export const AGENT_PROGRAMS = Object.freeze({
/* 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')] },
+ minimax: { names: ['mcode'], dirs: (home, win) => [...(win ? [join(home, '.minimax-code')] : []), join(home, '.minimax-code', 'bin')] },
/* DeepSeek Harness's desktop app carries the command (its own setting only links it into the PATH): inside
DeepSeek Harness.app on a Mac, in its install folder's resources on Windows */
deepseek: { names: ['dsh'], dirs: (home, win, apps = ['/Applications', join(home, 'Applications')]) => (win
@@ -45,7 +46,8 @@ export const AGENT_PROGRAMS = Object.freeze({
const DSH_IN_APP = 'Contents/Resources/runtime/cli/bin/dsh';
/** %LOCALAPPDATA% (Windows). */
-const localAppData = (home) => process.env.LOCALAPPDATA || join(home, 'AppData', 'Local');
+const localAppData = (home) => (home === homedir() && process.env.LOCALAPPDATA) || join(home, 'AppData', 'Local');
+const roamingAppData = (home) => (home === homedir() && process.env.APPDATA) || join(home, 'AppData', 'Roaming');
/**
* Whether a program is in Cursor's own folder (…/cursor-agent/…, or Homebrew's cursor-cli), followed through its link.
@@ -156,7 +158,7 @@ export function claudeAppCli(home = homedir(), { win = windows } = {}) {
/** 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 appData = roamingAppData(home);
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 */ }
@@ -213,10 +215,12 @@ function programVersion(file, { ours, ask }) {
}
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 */ }
+ for (const file of new Set([`${real}.version`, `${real.replace(/\.exe$/i, '')}.version`])) {
+ try {
+ const beside = readFileSync(file, '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 (!versionsAsked.has(key)) versionsAsked.set(key, ask(real));
@@ -242,6 +246,11 @@ export function opencodeVersion(file, { ask = askVersion } = {}) {
return programVersion(file, { ours: (name) => name === 'opencode-ai' || name.startsWith('opencode-'), ask });
}
+/** The desktop SDK's Copilot CLI, or a standalone npm installation. */
+export function copilotVersion(file, { ask = askVersion } = {}) {
+ return programVersion(file, { ours: (name) => name === '@github/copilot', ask });
+}
+
/** Whether version `a` is later than `b` (dotted numbers); false when either is unknown. */
export function laterVersion(a, b) {
if (!a || !b) return false;
@@ -346,6 +355,8 @@ export function cmdTarget(cmd, depth = 0) {
if (next) return next;
continue;
}
+ // MiniMax's SQLite is built for the installer's Node, which can differ from Electron's module ABI.
+ if (/[\\/]@minimax-ai[\\/]code[\\/]/i.test(target) && existsFile(target)) return null;
if (/[\\/]@openai[\\/]codex[\\/]/i.test(target) && /\.js$/i.test(target)) {
const triple = process.arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc';
const pkg = target.replace(/[\\/]bin[\\/][^\\/]+$/, '');
@@ -398,14 +409,78 @@ function opencodeInApps(/** @type {string[]} */ applicationDirs) {
return applicationDirs.map((dir) => join(dir, 'OpenCode.app', OPENCODE_IN_APP)).filter(executableFile);
}
+const WINDOWS_APP_NAMES = {
+ codex: /^(?:OpenAI\s+)?Codex(?:\s|$)/i,
+ claude: /^Claude(?:\s|$)/i,
+ copilot: /^GitHub Copilot(?:\s|$)/i,
+ cursor: /^Cursor(?:\s|$)/i,
+ opencode: /^OpenCode(?:\s|$)/i,
+ codebuddy: /^CodeBuddy(?:\s|$)/i,
+ kimi: /^Kimi(?:\s|$)/i,
+ minimax: /^MiniMax(?:\s|$)/i,
+ deepseek: /^DeepSeek Harness(?:\s|$)/i,
+};
+const WINDOWS_APP_FOLDERS = {
+ copilot: /^GitHub Copilot$/i, cursor: /^cursor$/i, opencode: /^(?:@opencodedesktop|OpenCode)$/i,
+ codebuddy: /^CodeBuddy/i, kimi: /^Kimi/i, minimax: /^MiniMax/i, deepseek: /^DeepSeek Harness$/i,
+};
+const directoryExists = (dir) => { try { return statSync(dir).isDirectory(); } catch { return false; } };
+/** Registered custom folders and the maker's default folders. Stale registry entries never count. */
+function windowsAppDirs(id, home, apps) {
+ const entries = apps ?? (process.platform === 'win32' && home === homedir() ? installedWindowsApps() : []);
+ return unique([
+ ...entries.filter((app) => WINDOWS_APP_NAMES[id]?.test(app.name)).flatMap((app) => app.directories),
+ ...(WINDOWS_APP_FOLDERS[id] ? folders(join(localAppData(home), 'Programs'), WINDOWS_APP_FOLDERS[id]) : []),
+ ], true).filter(directoryExists);
+}
+/** App-managed runtimes use one directory per version. Only real console programs count. */
+function versionedPrograms(root, name) {
+ return [...folders(root, /./).sort((a, b) => b.localeCompare(a, undefined, { numeric: true })).map((dir) => join(dir, name)), join(root, name)]
+ .filter((file) => presentFile(file) && !notTheAgent('', file, { win: true }));
+}
+/** Windows OpenCode Desktop's packaged CLI and the running copy it keeps outside its installation folder. */
+export function opencodeAppCopies(home = homedir(), { windowsApps } = {}) {
+ return [...windowsAppDirs('opencode', home, windowsApps).map((dir) => join(dir, 'resources', 'opencode-cli.exe')),
+ ...versionedPrograms(join(roamingAppData(home), 'ai.opencode.desktop', 'cli'), 'opencode-cli.exe')]
+ .filter((file) => presentFile(file) && !notTheAgent('opencode', file, { win: true }));
+}
+/** The CLI unpacked by GitHub Copilot Desktop's SDK, also usable by ACP clients. */
+export function copilotAppCopies(home = homedir()) {
+ const sdk = join(localAppData(home), 'github-copilot-sdk');
+ return [...versionedPrograms(join(sdk, 'cli'), 'copilot.exe'), ...versionedPrograms(join(sdk, 'runtime'), 'copilot.exe')];
+}
+
/**
* 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.
*/
-export function chosenProgram(path, { names = [], win = windows } = {}) {
+export function chosenProgram(path, { names = [], win = windows, home = homedir() } = {}) {
if (typeof path !== 'string' || !isAbsolute(path)) return null;
let folder = false;
try { folder = statSync(path).isDirectory(); } catch { /* a file, or not there */ }
+ if (win && (folder || presentFile(path))) {
+ // Selecting a maker's app means its bundled agent, when one exists, as with a macOS .app.
+ const root = folder ? path : dirname(path);
+ if (names.includes('copilot') && (folder || /^github\.exe$/i.test(basename(path))) && existsFile(join(root, 'copilot-sdk', 'index.js'))) {
+ const copies = copilotAppCopies(home);
+ let best = copies[0];
+ let version = best ? copilotVersion(best) : null;
+ for (const copy of copies.slice(1)) {
+ const next = copilotVersion(copy);
+ if (laterVersion(next, version)) { best = copy; version = next; }
+ }
+ if (best) return best;
+ }
+ const app = folder || (names.includes('dsh') && /^DeepSeek Harness\.exe$/i.test(basename(path)))
+ || (names.includes('opencode') && /^OpenCode\.exe$/i.test(basename(path)));
+ if (app) {
+ const bundled = [
+ ...(names.includes('dsh') ? [join(root, 'resources', 'runtime', 'cli', 'bin', 'dsh.cmd')] : []),
+ ...(names.includes('opencode') ? [join(root, 'resources', 'opencode-cli.exe')] : []),
+ ].find((file) => presentFile(file) && !notTheAgent('', file, { win: true }));
+ if (bundled) return isCmdScript(bundled) ? cmdTarget(bundled) ?? bundled : bundled;
+ }
+ }
if (folder) {
const inApp = /\.app$/i.test(path) ? [...CODEX_IN_APP, OPENCODE_IN_APP, DSH_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;
@@ -430,12 +505,13 @@ export function chosenProgram(path, { names = [], win = windows } = {}) {
*/
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,
- opencodeVersionOf = opencodeVersion } = {}) {
+ opencodeVersionOf = opencodeVersion, copilotVersionOf = copilotVersion, windowsApps } = {}) {
const program = AGENT_PROGRAMS[id] ?? { names: [id] };
const install = AGENT_DOWNLOADS[id] ?? null;
- const picked = chosen ? chosenProgram(chosen, { names: program.names, win }) : null;
+ const picked = chosen ? chosenProgram(chosen, { names: program.names, win, home }) : null;
if (picked && !notTheAgent(id, picked, { chosen, win })) return { installed: true, cli: picked, source: 'chosen', install };
- const dirs = [...pathDirs, ...(program.dirs?.(home, win, applicationDirs) ?? [])];
+ const dirs = [...pathDirs, ...(program.dirs?.(home, win, applicationDirs) ?? []),
+ ...(win && id === 'deepseek' ? windowsAppDirs(id, home, windowsApps).map((dir) => join(dir, 'resources', 'runtime', 'cli', 'bin')) : [])];
let cli = null;
for (const name of program.names) {
if (cli) break;
@@ -449,8 +525,10 @@ export function detectAgentInstallation(id, { home = homedir(), env = process.en
const usable = (file) => (win ? presentFile(file) : executableFile(file));
/* copies kept up to date by the maker's app (Codex: the Mac apps', or the one the Windows app starts), and how their
version is told */
- const copies = id === 'codex' ? [...codexInApps(applicationDirs), ...(win ? codexAppCopies(home) : []), ...others.filter((f) => usable(f) && !notTheAgent(id, f, { win }))] : id === 'opencode' ? opencodeInApps(applicationDirs) : [];
- const versionOf = id === 'opencode' ? opencodeVersionOf : codexVersionOf;
+ const copies = id === 'codex' ? [...codexInApps(applicationDirs), ...(win ? codexAppCopies(home) : []), ...others.filter((f) => usable(f) && !notTheAgent(id, f, { win }))]
+ : id === 'opencode' ? [...opencodeInApps(applicationDirs), ...(win ? opencodeAppCopies(home, { windowsApps }) : [])]
+ : id === 'copilot' && win ? copilotAppCopies(home) : [];
+ const versionOf = id === 'opencode' ? opencodeVersionOf : id === 'copilot' ? copilotVersionOf : codexVersionOf;
if (cli) {
/* Claude Code both on the PATH (an npm install that is never updated, say) and in the Claude app, which keeps its
own up to date: the later one, whose models are the current ones. One whose version can't be told stays. */
@@ -468,6 +546,13 @@ export function detectAgentInstallation(id, { home = homedir(), env = process.en
return { installed: true, cli, source: 'path', install };
}
cli = copies[0] ?? null;
+ if (cli && (id === 'opencode' || id === 'copilot')) {
+ let version = versionOf(cli);
+ for (const copy of copies.slice(1)) {
+ const next = versionOf(copy);
+ if (laterVersion(next, version)) { cli = copy; version = next; }
+ }
+ }
if (!cli && id === 'claude') cli = claudeAppCli(home, { win });
if (!cli) cli = others.find((f) => usable(f) && !notTheAgent(id, f, { win })) ?? null;
return { installed: Boolean(cli), cli, source: cli ? 'app' : null, install };
@@ -498,7 +583,9 @@ function folders(dir, re) {
* 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 } = {}) {
+export function desktopApp(id, { home = homedir(), applicationDirs = ['/Applications', join(home, 'Applications')], win = windows, windowsApps } = {}) {
+ if (win && windowsAppDirs(id, home, windowsApps).length) return id === 'copilot' ? 'GitHub Copilot' : DESKTOP_APPS[id]?.name ?? AGENT_DEFINITIONS[id]?.name ?? null;
+ if (!win && id === 'copilot' && applicationDirs.some((dir) => folders(dir, /^GitHub Copilot\.app$/i).length)) return 'GitHub Copilot';
const app = DESKTOP_APPS[id];
if (!app) return null;
const here = win
@@ -541,9 +628,11 @@ export function installCommand(id, { win = windows } = {}) {
* 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 } = {}) {
+export function searchReport(id, { home = homedir(), env = process.env, pathDirs = HOME_BIN_CANDIDATES(home), win = windows, windowsApps } = {}) {
const program = AGENT_PROGRAMS[id] ?? { names: [id] };
- const searched = unique([...pathIn(env).split(win ? ';' : delimiter), ...pathDirs, ...(program.dirs?.(home, win) ?? [])], win);
+ const copies = win ? id === 'opencode' ? opencodeAppCopies(home, { windowsApps }) : id === 'copilot' ? copilotAppCopies(home) : [] : [];
+ const registered = win && (id === 'deepseek' || id === 'opencode') ? windowsAppDirs(id, home, windowsApps).map((dir) => id === 'deepseek' ? join(dir, 'resources', 'runtime', 'cli', 'bin') : join(dir, 'resources')) : [];
+ const searched = unique([...pathIn(env).split(win ? ';' : delimiter), ...pathDirs, ...(program.dirs?.(home, win) ?? []), ...registered, ...copies.map(dirname)], win);
const files = [];
for (const dir of searched) {
for (const name of program.names) {
@@ -556,5 +645,8 @@ export function searchReport(id, { home = homedir(), env = process.env, pathDirs
}
}
}
+ for (const file of copies) {
+ if (!files.some((entry) => entry.file.toLowerCase() === file.toLowerCase())) files.push({ file, runs: file, usable: true });
+ }
return { searched, files };
}
diff --git a/apps/desktop/src/agent-installation.test.mjs b/apps/desktop/src/agent-installation.test.mjs
index 62df813..719dec0 100644
--- a/apps/desktop/src/agent-installation.test.mjs
+++ b/apps/desktop/src/agent-installation.test.mjs
@@ -202,7 +202,7 @@ test('the report: every folder searched, each file with the name, what a shim ru
put(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 });
- const own = join(process.env.LOCALAPPDATA || join(home, 'AppData', 'Local'), 'qwen-code', 'bin');
+ const own = 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 },
@@ -384,7 +384,6 @@ test("DeepSeek Harness's Windows shim runs a script inside its app's archive on
});
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'));
@@ -395,7 +394,6 @@ test("Cursor's agent on Windows: found in %LOCALAPPDATA%\\cursor-agent, started
});
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'));
@@ -441,8 +439,9 @@ test("the maker's desktop app is told without its agent: by its bundle on a Mac,
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');
+ mkdirSync(join(apps, 'GitHub Copilot.app'));
+ assert.equal(desktopApp('copilot', mac), 'GitHub Copilot');
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 });
@@ -473,8 +472,135 @@ test('the report says which file is not the agent, and why', () => {
assert.equal(report.files[0].usable, false);
});
+test('choosing an installation folder finds standalone connection programs at its root or in bin', () => {
+ const home = mkdtempSync(join(tmpdir(), 'of-install-folders-'));
+ for (const name of ['codex', 'claude', 'qwen', 'kimi', 'mcode', 'codebuddy']) {
+ for (const subdir of ['', 'bin']) {
+ const folder = join(home, `${name}-${subdir || 'root'}`);
+ const cli = put(join(folder, subdir, `${name}.exe`), peProgram(3));
+ assert.equal(chosenProgram(folder, { home, names: [name], win: true }), cli);
+ }
+ }
+ assert.equal(chosenProgram(home, { home, names: ['copilot'], win: true }), null, 'an unrelated folder does not silently choose another installation');
+});
+
+test('OpenCode Desktop on Windows: the packaged CLI and its newer running copy, without a PATH entry', () => {
+ const home = mkdtempSync(join(tmpdir(), 'of-opencode-win-'));
+ const root = join(home, 'apps', 'OpenCode');
+ const gui = put(join(root, 'OpenCode.exe'), peProgram(2));
+ const packaged = put(join(root, 'resources', 'opencode-cli.exe'), peProgram(3));
+ put(join(root, 'resources', 'opencode-cli.version'), '2.1.4\n');
+ assert.equal(opencodeVersion(packaged, { ask: () => assert.fail('read the packaged version') }), '2.1.4');
+ const opts = { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [], win: true,
+ windowsApps: [{ name: 'OpenCode 2.1.4', directories: [root] }] };
+ assert.equal(detectAgentInstallation('opencode', opts).cli, packaged);
+ const report = searchReport('opencode', opts);
+ assert.ok(report.searched.includes(join(root, 'resources')));
+ assert.ok(report.files.some((entry) => entry.file === packaged && entry.usable), 'diagnostics include the same bundled runtime as discovery');
+ assert.equal(chosenProgram(root, { names: ['opencode'], win: true }), packaged);
+ assert.equal(chosenProgram(gui, { names: ['opencode'], win: true }), packaged);
+ const running = put(join(home, 'AppData', 'Roaming', 'ai.opencode.desktop', 'cli', '2.1.5-x64', 'opencode-cli.exe'), peProgram(3));
+ put(`${running}.version`, '2.1.5');
+ assert.equal(detectAgentInstallation('opencode', opts).cli, running, 'the newer app-managed copy');
+ assert.equal(detectAgentInstallation('opencode', { ...opts, chosen: gui }).cli, packaged, 'the explicit choice wins');
+ const mine = put(join(home, 'bin', 'opencode.exe'), peProgram(3));
+ put(`${mine}.version`, '2.1.6');
+ assert.equal(detectAgentInstallation('opencode', { ...opts, env: { PATH: join(home, 'bin') } }).cli, mine, 'a newer independent CLI stays');
+});
+
+test('GitHub Copilot Desktop on Windows: its SDK CLI is found, but GUI programs and incomplete copies are not', () => {
+ const home = mkdtempSync(join(tmpdir(), 'of-copilot-win-'));
+ const root = join(home, 'AppData', 'Local', 'github-copilot-sdk');
+ const opts = { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [], windowsApps: [], win: true };
+ mkdirSync(join(root, 'cli', 'copilot-sdk-runtime-1.0.100'), { recursive: true });
+ assert.equal(detectAgentInstallation('copilot', opts).cli, null, 'a cache directory alone is not installed');
+ const older = put(join(root, 'cli', 'copilot-sdk-runtime-1.0.100', 'copilot.exe'), peProgram(3));
+ put(`${older}.version`, '1.0.100');
+ const newer = put(join(root, 'runtime', 'copilot-sdk-runtime-1.0.102', 'copilot.exe'), peProgram(3));
+ put(`${newer}.version`, '1.0.102');
+ put(join(root, 'cli', 'copilot-sdk-runtime-9.0.0', 'copilot.exe'), peProgram(2));
+ const found = detectAgentInstallation('copilot', opts);
+ assert.equal(found.cli, newer);
+ assert.equal(found.source, 'app');
+ const app = join(home, 'custom apps', 'GitHub Copilot');
+ const gui = put(join(app, 'github.exe'), peProgram(2));
+ put(join(app, 'copilot-sdk', 'index.js'));
+ assert.equal(chosenProgram(gui, { home, names: ['copilot'], win: true }), newer);
+ assert.equal(chosenProgram(app, { home, names: ['copilot'], win: true }), newer);
+ assert.equal(detectAgentInstallation('copilot', { ...opts, chosen: gui }).cli, newer);
+ const chosen = put(join(home, 'bin', 'copilot.exe'), peProgram(3));
+ put(`${chosen}.version`, '2.0.0');
+ assert.equal(detectAgentInstallation('copilot', { ...opts, env: { PATH: join(home, 'bin') } }).cli, chosen);
+});
+
+test('custom Windows app registrations identify the desktop app without making its GUI an agent', () => {
+ const home = mkdtempSync(join(tmpdir(), 'of-custom-apps-'));
+ const opts = { home, applicationDirs: [], win: true, windowsApps: [] };
+ for (const [id, name, label] of [
+ ['cursor', 'Cursor (User)', 'Cursor'], ['codebuddy', 'CodeBuddy CN (User)', 'CodeBuddy'],
+ ['copilot', 'GitHub Copilot', 'GitHub Copilot'], ['kimi', 'Kimi Code', 'Kimi'],
+ ['minimax', 'MiniMax Code', 'MiniMax'], ['deepseek', 'DeepSeek Harness 0.2.1-rc.3', 'DeepSeek Harness'],
+ ]) {
+ const dir = join(home, 'custom apps', id);
+ assert.equal(desktopApp(id, { ...opts, windowsApps: [{ name, directories: [dir] }] }), null, 'stale registration');
+ mkdirSync(dir, { recursive: true });
+ const windowsApps = [{ name, directories: [dir] }];
+ assert.equal(desktopApp(id, { ...opts, windowsApps }), label);
+ assert.equal(detectAgentInstallation(id, { ...opts, windowsApps, env: { PATH: '' }, pathDirs: [] }).cli, null);
+ }
+});
+
+test('DeepSeek Harness in a custom Windows folder: automatic discovery and choosing the app both retain its own shim', () => {
+ const home = mkdtempSync(join(tmpdir(), 'of-dsh-custom-'));
+ const root = join(home, 'custom apps', 'DeepSeek Harness');
+ const gui = put(join(root, 'DeepSeek Harness.exe'), peProgram(2));
+ const shim = put(join(root, 'resources', 'runtime', 'cli', 'bin', 'dsh.cmd'), '@echo off\r\nset "ELECTRON_RUN_AS_NODE=1"\r\n"%~dp0..\\..\\..\\..\\DeepSeek Harness.exe" "%~dp0..\\..\\..\\app.asar\\dsh\\cli.js" %*\r\n');
+ const opts = { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [], win: true,
+ windowsApps: [{ name: 'DeepSeek Harness 0.2.1-rc.3', directories: [root] }] };
+ assert.equal(detectAgentInstallation('deepseek', opts).cli, shim);
+ assert.equal(chosenProgram(root, { names: ['dsh'], win: true }), shim);
+ assert.equal(chosenProgram(gui, { names: ['dsh'], win: true }), shim);
+ assert.equal(detectAgentInstallation('deepseek', { ...opts, chosen: gui }).source, 'chosen');
+ assert.equal(notTheAgent('deepseek', shim, { chosen: gui, win: true }), null);
+});
+
+test('the remaining Windows CLI installers are found outside PATH without counting desktop executables', () => {
+ const home = mkdtempSync(join(tmpdir(), 'of-cli-installers-'));
+ const local = join(home, 'AppData', 'Local');
+ for (const [id, file] of [
+ ['qwen', join(local, 'qwen-code', 'bin', 'qwen.exe')],
+ ['kimi', join(home, '.kimi-code', 'bin', 'kimi.exe')],
+ ['minimax', join(home, '.minimax-code', 'bin', 'mcode.exe')],
+ ['codebuddy', join(local, 'codebuddy', 'bin', 'codebuddy.exe')],
+ ['cursor', join(local, 'cursor-agent', 'agent.exe')],
+ ]) {
+ const opts = { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [], windowsApps: [], win: true };
+ put(file, peProgram(2));
+ assert.equal(detectAgentInstallation(id, opts).cli, null, `${id}: a GUI does not count`);
+ put(file, peProgram(3));
+ assert.equal(detectAgentInstallation(id, opts).cli, file, `${id}: the installer's CLI does`);
+ }
+});
+
+test('MiniMax official Windows installer keeps mcode.cmd at its install root, off PATH', () => {
+ const home = mkdtempSync(join(tmpdir(), 'of-mcode-root-'));
+ const root = join(home, '.minimax-code');
+ put(join(root, 'runtime', 'node.exe'));
+ put(join(root, 'node_modules', '@minimax-ai', 'code', 'cli.js'));
+ const shim = put(join(root, 'mcode.cmd'), '@echo off\r\n"%~dp0runtime\\node.exe" "%~dp0node_modules\\@minimax-ai\\code\\cli.js" %*\r\n');
+ assert.equal(detectAgentInstallation('minimax', { home, env: { PATH: '' }, pathDirs: [], applicationDirs: [], windowsApps: [], win: true }).cli, shim);
+});
+
+test('MiniMax npm CLI keeps its launcher so native SQLite uses the installing Node, not Electron', () => {
+ const root = mkdtempSync(join(tmpdir(), 'of-mcode-npm-'));
+ put(join(root, 'node_modules', '@minimax-ai', 'code', 'cli.js'));
+ const shim = put(join(root, 'mcode.cmd'), npmShim('node_modules\\@minimax-ai\\code\\cli.js'));
+ assert.equal(cmdTarget(shim), null);
+ assert.equal(findExecutable('mcode', [], { PATH: root }, { win: true }), shim);
+ assert.equal(chosenProgram(shim, { names: ['mcode'], win: true }), shim);
+});
+
test("Codex on Windows: never the copy in the Store app's own folder, which Windows won't start; the copy the Codex app starts", () => {
- if (process.platform === 'win32') return;
const home = mkdtempSync(join(tmpdir(), 'of-home-'));
const store = put(join(home, 'Program Files', 'WindowsApps', 'OpenAI.Codex_26.1002.7124.0_x64__2p2nqsd0c76g0', 'app', 'resources', 'codex.exe'));
assert.equal(notTheAgent('codex', store, { win: true }), 'app');
diff --git a/apps/desktop/src/agent-roster.mjs b/apps/desktop/src/agent-roster.mjs
index 81136f0..8732331 100644
--- a/apps/desktop/src/agent-roster.mjs
+++ b/apps/desktop/src/agent-roster.mjs
@@ -41,6 +41,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { PI_APIS, contextLength, modelEffort } from './pi-config.mjs';
+import { agentConnectionIssue } from './agent-connection-issue.mjs';
import { AGENT_DEFINITIONS, AGENT_IDS, OWN_AGENT_IDS, isAgentId } from './agent-definitions.mjs';
export { AGENT_IDS, OWN_AGENT_IDS } from './agent-definitions.mjs';
@@ -212,16 +213,17 @@ 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, app?: string | null, installer?: string | null }>>,
+ * localAgents: (options?: { ids?: string[], statusIds?: string[], fresh?: boolean, onAgent?: (agent: any) => void }) => 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, options?: { fresh?: boolean }) => 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, isOpen?: () => Promise<boolean | null> }>,
* signOut?: (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 }>,
+ * pickProgram?: (id: string, words?: { title?: string, button?: string, kind?: 'file' | 'folder' }) => Promise<string | null>,
+ * checkProgram?: (id: string, path: string) => Promise<{ ok: boolean, error?: string, code?: string, path?: string, version?: string }>,
* diagnose?: (id: string) => Promise<{ found: string | null, hint: string | null, text: string } | null>,
* closeSessions: (id: string) => void,
+ * resetAgent?: (id: string) => void,
* seal: (text: string) => Buffer, unseal: (data: Buffer) => string,
* onChange: (list: any[]) => void,
* fetch?: typeof fetch,
@@ -235,9 +237,10 @@ export function createRoster(deps) {
let choices = readChoices(dataDir);
deps.usePaths?.(choices.paths);
/** 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: {} };
+ const live = { waiting: {}, installing: {}, errors: {}, connectionIssues: {} };
let local = null;
const revision = new Map();
+ const configurationRevision = new Map();
const checking = new Map();
let refreshing = null;
@@ -258,6 +261,7 @@ export function createRoster(deps) {
};
/** The own models that have a key: the ones the agent can use. */
const keyed = () => (choices.byok?.models ?? []).filter((m) => keyOf(m.id));
+ const enabled = (id) => Boolean(choices.shown[id]) && !choices.disconnected.includes(id);
function stateOf(id) {
if (isOwn(id)) {
@@ -268,7 +272,7 @@ export function createRoster(deps) {
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 (choices.disconnected.includes(id) || !choices.shown[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 } : {}),
...(found.signOut && deps.signOut ? { signOut: true } : {}) };
@@ -285,6 +289,8 @@ export function createRoster(deps) {
shown: choices.shown[id] ?? false,
...stateOf(id),
...(live.errors[id] ? { error: live.errors[id] } : {}),
+ ...(live.connectionIssues[id] ? { connectionIssue: { ...live.connectionIssues[id] } } : {}),
+ ...(configurationRevision.has(id) ? { configurationRevision: configurationRevision.get(id) } : {}),
...(id === 'byok' && choices.byok ? { byok: { models: choices.byok.models.map((m) => ({ ...m, levels: [...m.levels] })) } } : {}),
}));
}
@@ -292,7 +298,7 @@ export function createRoster(deps) {
const changed = () => deps.onChange(list());
const save = (next) => { choices = next; writeChoices(dataDir, choices); changed(); };
- async function refresh() {
+ async function refresh({ fresh = false, only = null } = {}) {
// Focus after signing in should not wait for every other agent to finish its own status command. Only the agent
// being signed in is asked fresh; the others keep their cached answers in the full scan.
if (deps.localAgent) {
@@ -301,23 +307,49 @@ export function createRoster(deps) {
void lookAgain(id, () => !choices.disconnected.includes(id) && live.waiting[id] === waiting && !waiting.signal.aborted);
}
}
- if (!refreshing) {
+ if (!refreshing || fresh || only) {
const started = new Map(revision);
- refreshing = (async () => {
- const found = await deps.localAgents().catch(() => null);
+ const ids = (only ?? [...OWN_AGENT_IDS]).filter(isOwn).sort((a, b) => Number(enabled(b)) - Number(enabled(a)));
+ const statusIds = ids.filter((id) => enabled(id) || live.waiting[id] || live.installing[id] || Boolean(only));
+ const wanted = new Set(ids);
+ const accept = (agent) => {
+ if (!wanted.has(agent.id) || revision.get(agent.id) !== started.get(agent.id)) return;
+ local = [...(local ?? []).filter((a) => a.id !== agent.id), agent];
+ changed();
+ };
+ const pending = (async () => {
+ const found = await deps.localAgents({ ids, statusIds, fresh, onAgent: accept }).catch(() => null);
if (found) {
- const current = local ?? [];
- // A full scan started before a fresh sign-in check must not overwrite its newer result.
- local = found.map((a) => revision.get(a.id) !== started.get(a.id) ? current.find((v) => v.id === a.id) ?? a : a);
- local.push(...current.filter((a) => revision.get(a.id) !== started.get(a.id) && !found.some((v) => v.id === a.id)));
+ local ??= [];
+ for (const agent of found) {
+ // A late result cannot overwrite a newer sign-in or re-enable an agent switched off during the scan.
+ if (revision.get(agent.id) !== started.get(agent.id)) continue;
+ local = [...local.filter((a) => a.id !== agent.id), agent];
+ }
} else local ??= [];
changed();
return list();
- })().finally(() => { refreshing = null; });
+ })().finally(() => { if (refreshing === pending) refreshing = null; });
+ refreshing = pending;
}
return refreshing;
}
+ /** Re-read settings after an external configuration change; idle sessions and model menus are renewed. */
+ async function recheck(id) {
+ if (id != null && !isOwn(id)) return list();
+ for (const target of id ? [id] : OWN_AGENT_IDS) {
+ revision.set(target, (revision.get(target) ?? 0) + 1);
+ configurationRevision.set(target, (configurationRevision.get(target) ?? 0) + 1);
+ checking.delete(target);
+ delete live.errors[target];
+ delete live.connectionIssues[target];
+ deps.resetAgent?.(target);
+ }
+ changed();
+ return refresh({ fresh: true, only: id ? [id] : null });
+ }
+
/** The one agent signed in to, asked again: alone when it can be, not every agent every few seconds. */
async function lookAgain(id, current) {
let pending = checking.get(id);
@@ -384,18 +416,36 @@ export function createRoster(deps) {
return {
list,
refresh,
+ recheck,
cancelSignIn,
+ /** An actual model request failed or succeeded. Refreshing discovery does not erase a model failure. */
+ recordConnectionResult(id, error) {
+ if (!isOwn(id)) return;
+ if (error == null) delete live.connectionIssues[id];
+ else {
+ const issue = agentConnectionIssue(error);
+ if (!issue) return;
+ live.connectionIssues[id] = issue;
+ }
+ changed();
+ },
+
/** Connect: back on here; its own sign-in when it needs one. */
async connect(id) {
if (!isAgentId(id)) return { ok: false, error: `No agent ${id}` };
delete live.errors[id];
+ const wasDisconnected = choices.disconnected.includes(id);
/* connecting one is choosing it: it is shown in the chat (and among the person's agents in Settings) */
save({ ...choices, shown: { ...choices.shown, [id]: true }, disconnected: choices.disconnected.filter((a) => a !== id) });
try {
if (isOwn(id)) {
deps.closeSessions(id);
- const [now] = (await refresh()).filter((a) => a.id === id);
+ // A known sign-in wait can be restarted immediately, even if its previous status probe is still pending.
+ if (deps.localAgent) {
+ if (wasDisconnected || !local?.some((a) => a.id === id && a.signedIn === false)) await lookAgain(id, () => enabled(id));
+ } else await refresh();
+ const now = list().find((a) => a.id === id);
/* signed out; or signing in already, its window closed before it was done (Start again): opened again */
if (now?.status !== 'sign-in' && now?.status !== 'waiting') return { ok: true };
const opened = await deps.openSignIn(id);
@@ -403,7 +453,7 @@ export function createRoster(deps) {
void waitForSignIn(id, opened.isOpen);
return { ok: true };
}
- await refresh();
+ changed();
return { ok: true };
} catch (e) {
live.errors[id] = e instanceof Error ? e.message : String(e);
@@ -424,6 +474,7 @@ export function createRoster(deps) {
deps.closeSessions(id);
const out = await deps.signOut(id).catch((e) => ({ ok: false, error: e instanceof Error ? e.message : String(e) }));
if (!out.ok) { live.errors[id] = out.error || `${AGENT_NAMES[id]} did not sign out.`; changed(); return { ok: false, error: live.errors[id] }; }
+ delete live.connectionIssues[id];
/* signed out now: said at once, and kept over an older answer still on its way */
local = (local ?? []).map((a) => (a.id === id ? { ...a, signedIn: false, account: null } : a));
revision.set(id, (revision.get(id) ?? 0) + 1);
@@ -454,12 +505,14 @@ export function createRoster(deps) {
const checked = await deps.checkProgram(id, path);
if (!checked.ok) return { ok: false, error: checked.error ?? '', ...(checked.code ? { code: checked.code } : {}) };
delete live.errors[id];
+ delete live.connectionIssues[id];
deps.closeSessions(id);
choices = { ...choices, paths: { ...choices.paths, [id]: path }, shown: { ...choices.shown, [id]: true } };
deps.usePaths?.(choices.paths);
save(choices);
- await refresh();
- return { ok: true };
+ if (deps.localAgent) await lookAgain(id, () => true);
+ else await refresh();
+ return { ok: true, ...(checked.path ? { path: checked.path } : {}), ...(checked.version ? { version: checked.version } : {}) };
},
/**
@@ -479,11 +532,13 @@ export function createRoster(deps) {
async useAutomatic(id) {
if (!Object.hasOwn(choices.paths, id)) return { ok: true };
const { [id]: _gone, ...paths } = choices.paths;
+ delete live.connectionIssues[id];
deps.closeSessions(id);
choices = { ...choices, paths };
deps.usePaths?.(choices.paths);
save(choices);
- await refresh();
+ if (deps.localAgent) await lookAgain(id, () => true);
+ else await refresh();
return { ok: true };
},
@@ -491,13 +546,16 @@ export function createRoster(deps) {
async diagnose(id) {
if (!isOwn(id) || !deps.diagnose) return null;
const report = await deps.diagnose(id);
- void refresh();
+ if (deps.localAgent) await lookAgain(id, () => true);
+ else void refresh();
return report;
},
setShown(id, shown) {
if (!isAgentId(id)) return;
+ revision.set(id, (revision.get(id) ?? 0) + 1);
save({ ...choices, shown: { ...choices.shown, [id]: shown === true } });
+ if (shown && enabled(id) && deps.localAgent) void lookAgain(id, () => enabled(id));
},
/**
diff --git a/apps/desktop/src/agent-roster.test.mjs b/apps/desktop/src/agent-roster.test.mjs
index 1ee25ff..7dd8242 100644
--- a/apps/desktop/src/agent-roster.test.mjs
+++ b/apps/desktop/src/agent-roster.test.mjs
@@ -19,6 +19,100 @@ const roster = (dataDir, fetch, extra = {}) => createRoster({
...extra,
});
+test('startup publishes each result before a slow background discovery ends; only enabled agents need sign-in checks', async () => {
+ const slow = Promise.withResolvers();
+ let requested;
+ const r = roster(mkdtempSync(join(tmpdir(), 'of-progressive-agents-')), undefined, {
+ localAgents: async (options) => {
+ requested = options;
+ return Promise.all(options.ids.map(async (id) => {
+ if (id === 'cursor') await slow.promise;
+ const fact = { id, cli: { path: `/bin/${id}` }, signedIn: true };
+ options.onAgent(fact);
+ return fact;
+ }));
+ },
+ });
+ const pending = r.refresh();
+ try {
+ await new Promise((done) => setImmediate(done));
+ assert.deepEqual(requested.statusIds, ['codex']);
+ assert.equal(requested.ids.length, 10, 'disabled agents are still discovered automatically');
+ assert.equal(requested.ids[0], 'codex', 'enabled agents are scheduled first');
+ assert.equal(r.list().find((a) => a.id === 'codex').status, 'ready');
+ assert.equal(r.list().find((a) => a.id === 'cursor').status, 'checking');
+ } finally { slow.resolve(); await pending; }
+ assert.equal(r.list().find((a) => a.id === 'cursor').status, 'off');
+});
+
+test('connecting one agent does not wait for a pending background scan or accept its stale result', async () => {
+ const slow = Promise.withResolvers();
+ const checked = [];
+ const r = roster(mkdtempSync(join(tmpdir(), 'of-connect-priority-')), undefined, {
+ localAgents: async ({ ids, onAgent }) => {
+ await slow.promise;
+ return ids.map((id) => { const fact = { id, cli: null, signedIn: null }; onAgent(fact); return fact; });
+ },
+ localAgent: async (id) => { checked.push(id); return { id, cli: { path: `/bin/${id}` }, signedIn: true }; },
+ });
+ const scan = r.refresh();
+ let connected = false;
+ const connect = r.connect('deepseek').then(() => { connected = true; });
+ try {
+ await new Promise((done) => setImmediate(done));
+ assert.equal(connected, true);
+ assert.deepEqual(checked, ['deepseek']);
+ } finally { slow.resolve(); await Promise.all([scan, connect]); }
+ assert.equal(r.list().find((a) => a.id === 'deepseek').status, 'ready');
+});
+
+test('explicit refresh renews configuration and clears stale model errors without signing out or closing active sessions', async () => {
+ const reset = [], closed = [], scans = [];
+ const dir = mkdtempSync(join(tmpdir(), 'of-settings-refresh-'));
+ const r = roster(dir, undefined, {
+ localAgents: async (options) => { scans.push(options); return [{ id: 'deepseek', cli: { path: '/bin/dsh' }, signedIn: null }]; },
+ resetAgent: (id) => reset.push(id), closeSessions: (id) => closed.push(id),
+ });
+ await r.connect('deepseek');
+ r.recordConnectionResult('deepseek', new Error('no API key for provider route "deepseek-official"'));
+ const before = readChoices(dir);
+ const closedBefore = closed.length;
+ await r.recheck('deepseek');
+ const agent = r.list().find((a) => a.id === 'deepseek');
+ assert.equal(agent.connectionIssue, undefined, 'the error from the previous configuration is no longer current');
+ assert.equal(agent.configurationRevision, 1);
+ assert.equal(agent.path, '/bin/dsh');
+ assert.deepEqual(scans.at(-1).ids, ['deepseek']);
+ assert.deepEqual(scans.at(-1).statusIds, ['deepseek']);
+ assert.equal(scans.at(-1).fresh, true);
+ assert.deepEqual(reset, ['deepseek']);
+ assert.equal(closed.length, closedBefore, 'refresh uses idle-session renewal, not forced session closure');
+ assert.deepEqual(readChoices(dir), before);
+});
+
+test('model failures survive discovery and reconnects without changing paths, visibility or sign-in; actual success clears them', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-model-issue-'));
+ const r = roster(dir, undefined, {
+ localAgents: async () => [{ id: 'opencode', cli: { path: 'C:\\Apps\\OpenCode\\resources\\opencode-cli.exe' }, signedIn: null }],
+ });
+ await r.connect('opencode');
+ const before = readChoices(dir);
+ const read = () => r.list().find((a) => a.id === 'opencode');
+ r.recordConnectionResult('opencode', new Error('Free usage limit reached.'));
+ await r.refresh();
+ await r.connect('opencode');
+ assert.equal(read().status, 'ready');
+ assert.equal(read().connectionIssue.kind, 'quota');
+ assert.equal(read().path, 'C:\\Apps\\OpenCode\\resources\\opencode-cli.exe');
+ assert.deepEqual(readChoices(dir), before);
+ r.recordConnectionResult('opencode', new Error('429 Too many requests'));
+ assert.equal(read().connectionIssue.kind, 'quota', 'an unrelated transient error does not dismiss the known issue');
+ r.recordConnectionResult('opencode', null);
+ assert.equal(read().connectionIssue, undefined);
+ r.recordConnectionResult('deepseek', new Error('no API key for provider route "deepseek-official"'));
+ assert.equal(r.list().find((a) => a.id === 'deepseek').connectionIssue.kind, 'credentials');
+});
+
test('focus publishes a fresh login before a slow full scan and ignores the scan\'s older signed-out result', async () => {
const qwen = (signedIn) => ({ id: 'qwen', cli: { path: '/bin/qwen' }, signedIn });
const scan = Promise.withResolvers();
@@ -31,6 +125,7 @@ test('focus publishes a fresh login before a slow full scan and ignores the scan
signInWait: { ms: 10_000, pollMs: 5000 },
});
try {
+ await r.refresh();
await r.connect('qwen');
await new Promise((done) => setImmediate(done));
assert.equal(checks.length, 1, 'the first login check starts immediately, before the poll delay');
@@ -83,6 +178,7 @@ test('focus and login polling share a status check, and cancelling ignores its l
signInWait: { ms: 10_000, pollMs: 5000 },
});
try {
+ await r.refresh();
await r.connect('qwen');
await Promise.all([r.refresh(), r.refresh(), r.refresh()]);
assert.equal(checks, 1);
@@ -300,7 +396,7 @@ test("Codex and Claude Code are shown in the chat from the start, the person's o
const list = await r.refresh();
const of = (id) => list.find((a) => a.id === id);
assert.equal(of('codex').shown, true, 'not installed, still shown');
- assert.equal(of('qwen').status, 'ready');
+ assert.equal(of('qwen').status, 'off');
assert.equal(of('qwen').shown, false, 'installed, not chosen yet');
assert.equal(of('kimi').status, 'missing');
await r.connect('qwen');
@@ -331,7 +427,7 @@ test('an agent not found can be pointed at: the program is tried first, kept, an
assert.deepEqual(readChoices(dir).paths, {}, 'a program that does not start is not kept');
picked = 'C:\\tools\\codex.exe';
check = { ok: true, version: 'codex-cli 1.0.0' };
- assert.deepEqual(await r.locate('codex'), { ok: true });
+ assert.deepEqual(await r.locate('codex'), { ok: true, version: 'codex-cli 1.0.0' });
assert.deepEqual(readChoices(dir).paths, { codex: 'C:\\tools\\codex.exe' });
assert.deepEqual(used.at(-1), { codex: 'C:\\tools\\codex.exe' });
assert.equal(r.list().find((a) => a.id === 'codex').chosen, 'C:\\tools\\codex.exe');
@@ -530,6 +626,7 @@ test('closing the login terminal restores sign-in even while an authentication p
});
const status = () => r.list().find((a) => a.id === 'qwen').status;
try {
+ await r.refresh();
await r.connect('qwen');
await started.promise;
assert.equal(status(), 'waiting');
@@ -556,6 +653,7 @@ test('cancelling sign-in restores the login state without disconnecting or waiti
localAgent: async () => { started.resolve(); return pending.promise; },
signInWait: { ms: 2000, pollMs: 5 },
});
+ await r.refresh();
await r.connect('qwen');
await started.promise;
r.cancelSignIn('qwen');
@@ -617,7 +715,7 @@ test("an agent found only as its maker's app: the app said, and its installer ru
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.status, 'off', 'installation is detected without enabling or signing in to a disabled agent');
assert.equal(after.installing, undefined);
assert.deepEqual(await r.install('byok'), { ok: false, error: 'No agent byok' });
diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjs
index e818756..152af78 100644
--- a/apps/desktop/src/agents.mjs
+++ b/apps/desktop/src/agents.mjs
@@ -351,6 +351,7 @@ export async function diagnoseAgent(id, { appVersion = '' } = {}) {
`PATH from: ${lastPathSource() ?? 'unknown'}`,
`Chosen: ${chosen ?? '(none)'}`,
`Found: ${found ? `${found.path} (${found.source})` : '(not found)'}`,
+ `Desktop app: ${desktopApp(id) ?? '(not found)'}`,
...(windows ? [
`npm global folder: ${slow.npmPrefix ?? '(unknown)'}`,
...(id === 'codex' ? [`Codex the Codex app starts: ${codexAppCopies()[0] ?? '(none)'}`] : []),
@@ -424,6 +425,8 @@ export function readAgentStatus(id, stdout, out) {
* is learnt anyway, from a message refused for it (noteSignedOut) or when the person signs in from Settings.
*/
const asked = new Map();
+/** Explicit settings refresh: the next sign-in/options check must read the current configuration. */
+export function forgetAgentStatus(id) { asked.delete(id); }
const ASKED_FOR_MS = 15_000;
const SIGNED_IN_FOR_MS = 10 * 60_000;
@@ -681,29 +684,39 @@ export async function openAgentInstaller(id) {
* 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() {
+export async function listAgents({ ids = Object.keys(AGENTS), statusIds = ids, fresh = false, onAgent = () => {} } = {}) {
+ const wanted = [...new Set(ids)].filter((id) => Object.hasOwn(AGENTS, id));
+ if (!wanted.length) return [];
/* looked at as the person comes back from installing one: a PATH from a few seconds ago at most */
- const pathDirs = (await loginShellEnvironment({ maxAgeMs: 10_000 })).PATH.split(PATH_SEP);
+ const pathDirs = (await loginShellEnvironment({ maxAgeMs: fresh ? 0 : 10_000 })).PATH.split(PATH_SEP);
/* the slower search (Windows): waited for, a few seconds at most, when one is not found the quick way. What it finds
later is there on the next look */
- if (windows) {
- const slow = windowsSlowSearch();
- if (Object.keys(AGENTS).some((id) => !resolveAgentCli(id, { pathDirs }))) {
- await Promise.race([slow, new Promise((done) => setTimeout(done, 3000).unref?.())]);
+ return Promise.all(wanted.map(async (id) => {
+ const checkSignIn = statusIds.includes(id);
+ // Enabled agents start first. Background discovery never opens a disabled agent's ACP/auth session.
+ if (!checkSignIn) await new Promise((done) => setImmediate(done));
+ if (windows && !resolveAgentCli(id, { pathDirs })) {
+ await Promise.race([windowsSlowSearch(), new Promise((done) => setTimeout(done, 3000).unref?.())]);
}
- }
- return Promise.all(Object.keys(AGENTS).map((id) => agentOnComputer(id, pathDirs)));
+ const agent = await agentOnComputer(id, pathDirs, { fresh, checkSignIn });
+ onAgent(agent);
+ return agent;
+ }));
}
-/** One agent as listAgents has it, asked alone: while the person signs in to it, only it is asked again. */
+/** One agent as listAgents has it, asked alone when connecting, diagnosing or waiting for sign-in. */
export async function localAgent(id, { fresh = false } = {}) {
if (!isAgentId(id)) throw new Error(`No agent ${id}`);
- return agentOnComputer(id, (await loginShellEnvironment({ maxAgeMs: 10_000 })).PATH.split(PATH_SEP), { fresh });
+ const pathDirs = (await loginShellEnvironment({ maxAgeMs: 10_000 })).PATH.split(PATH_SEP);
+ if (windows && !resolveAgentCli(id, { pathDirs })) {
+ await Promise.race([windowsSlowSearch(), new Promise((done) => setTimeout(done, 3000).unref?.())]);
+ }
+ return agentOnComputer(id, pathDirs, { fresh });
}
-async function agentOnComputer(id, pathDirs, { fresh = false } = {}) {
+async function agentOnComputer(id, pathDirs, { fresh = false, checkSignIn = true } = {}) {
const cli = resolveAgentCli(id, { pathDirs });
- const { install } = detectAgentInstallation(id);
+ const install = AGENT_DEFINITIONS[id]?.install ?? null;
const app = cli ? null : desktopApp(id);
const claudeApp = id === 'claude' && Boolean(app);
return {
@@ -711,7 +724,7 @@ async function agentOnComputer(id, pathDirs, { fresh = false } = {}) {
label: AGENTS[id].label,
cli: cli ? { path: cli.path, source: cli.source } : null,
chosen: chosenPaths[id] ?? null,
- ...(cli ? ownSignIn(AGENTS[id], await agentStatus(id, cli.path, { fresh })) : { signedIn: null, account: null }),
+ ...(cli && checkSignIn ? ownSignIn(AGENTS[id], await agentStatus(id, cli.path, { fresh })) : { signedIn: null, account: null }),
/* it signs out with its own command: Switch account signs in to another account from Settings */
...(cli && AGENTS[id].logout ? { signOut: true } : {}),
install,
diff --git a/apps/desktop/src/folder-dialog.mjs b/apps/desktop/src/folder-dialog.mjs
index d59ffec..0d4b3cc 100644
--- a/apps/desktop/src/folder-dialog.mjs
+++ b/apps/desktop/src/folder-dialog.mjs
@@ -39,7 +39,7 @@ export function programDialogOptions(options, platform = process.platform) {
title,
message: title,
buttonLabel: text(o.button) ?? 'Choose',
- ...(platform === 'win32' ? { filters: [{ name: 'Programs', extensions: ['exe', 'cmd', 'bat', 'ps1', 'js'] }, { name: 'All files', extensions: ['*'] }] } : {}),
- properties: ['openFile', 'showHiddenFiles'],
+ ...(platform === 'win32' && o.kind !== 'folder' ? { filters: [{ name: 'Programs', extensions: ['exe', 'cmd', 'bat', 'ps1', 'js'] }, { name: 'All files', extensions: ['*'] }] } : {}),
+ properties: [o.kind === 'folder' ? 'openDirectory' : 'openFile', 'showHiddenFiles', ...(o.kind === 'folder' && platform === 'darwin' ? ['treatPackageAsDirectory'] : [])],
};
}
diff --git a/apps/desktop/src/folder-dialog.test.mjs b/apps/desktop/src/folder-dialog.test.mjs
index a855967..5dcd3ac 100644
--- a/apps/desktop/src/folder-dialog.test.mjs
+++ b/apps/desktop/src/folder-dialog.test.mjs
@@ -33,3 +33,14 @@ test("an agent's program: Studio's words; on Windows only programs and shims are
assert.ok(win.properties?.includes('openFile'));
assert.equal(programDialogOptions(null, 'darwin').filters, undefined, 'on a Mac an app can be chosen too');
});
+
+test('choosing an agent installation folder opens a directory picker without file filters on Windows', () => {
+ const options = programDialogOptions({ title: 'Choose installation folder', kind: 'folder' }, 'win32');
+ assert.deepEqual(options.properties, ['openDirectory', 'showHiddenFiles']);
+ assert.equal(options.filters, undefined);
+ assert.equal(options.title, 'Choose installation folder');
+});
+
+test('the installation-folder picker accepts macOS app bundles as directories', () => {
+ assert.deepEqual(programDialogOptions({ kind: 'folder' }, 'darwin').properties, ['openDirectory', 'showHiddenFiles', 'treatPackageAsDirectory']);
+});
diff --git a/apps/desktop/src/local-agents-ipc.mjs b/apps/desktop/src/local-agents-ipc.mjs
index 854055b..c2b551e 100644
--- a/apps/desktop/src/local-agents-ipc.mjs
+++ b/apps/desktop/src/local-agents-ipc.mjs
@@ -150,10 +150,10 @@ export function agentProblem(entry, step, e, turnId = null) {
* `skills`: where the app keeps its record of skills (`dataDir`) and the person's own skills (`mine`): each session has its maker's skills and MCP servers, OpenFilm's skills, and of the person's own those let
* in (agent-skills.mjs).
* @param {{ trusted: (event: any) => boolean, binDir?: string | null, fallbackDir?: string | null, env?: Record<string, string>,
- * harness?: (id: string) => Promise<any>, onWorking?: (folders: string[]) => void, onAsking?: (folders: string[]) => void, logDir?: () => string | null,
+ * harness?: (id: string) => Promise<any>, onWorking?: (folders: string[]) => void, onAsking?: (folders: string[]) => void, onConnectionResult?: (id: string, error: unknown | null) => void, logDir?: () => string | null,
* skills?: { dataDir: string, mine: string } | null }} opts
*/
-export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbackDir = null, env = {}, harness = async () => null, log = () => {}, onWorking = () => {}, onAsking = () => {}, logDir = () => null, skills = null }) {
+export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbackDir = null, env = {}, harness = async () => null, log = () => {}, onWorking = () => {}, onAsking = () => {}, onConnectionResult = (_agent, _error) => {}, logDir = () => null, skills = null }) {
const harnessFor = async (agent) => (HARNESS_AGENTS.includes(agent) ? harness(agent) : undefined);
const skillRecord = skills ? skillStore(skills.dataDir) : null;
/* what went wrong, kept in Studio's home with Studio's own problems (openfilm's problems.mjs), for its report */
@@ -243,6 +243,7 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
const error = e instanceof Error ? e.message : String(e);
/* the model menu says only that it could not start: what went wrong is kept here (logs/studio.log) */
log(`probe ${agent}: ${error.replace(/\s+/g, ' ').slice(0, 500)}\n`);
+ onConnectionResult(agent, e);
return { ok: false, error, ...(e?.code ? { code: String(e.code) } : {}) };
} finally {
session?.close();
@@ -309,6 +310,7 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
return { ok: true, key, info: { ...info, authMethods: [], mcp: false } };
} catch (e) {
const result = { ok: false, error: e instanceof Error ? e.message : String(e), ...(e?.code ? { code: String(e.code) } : {}) };
+ onConnectionResult(agent, e);
if (meta?.turnId) {
const raw = sentError(e);
const file = openLog(cwd, meta.turnId, (err) => log(`turn log ${meta.turnId}: ${err.message}\n`));
@@ -342,11 +344,13 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
entry.running = (entry.running ?? 0) + 1;
onWorking(working());
let result;
+ let connectionError = null;
/* the error as the agent sent it (ACP's code, message and data), for the turn log */
let raw = null;
try {
result = { ok: true, stopReason: await entry.session.prompt([{ type: 'text', text }, ...images], { turnId: meta?.turnId }) };
} catch (e) {
+ connectionError = e;
/* `balance`: the service the app's own agent runs on has no balance left (agents.mjs), and where to top it up */
result = { ok: false, error: e instanceof Error ? e.message : String(e), ...(e?.balance ? { balance: e.balance } : {}) };
raw = sentError(e);
@@ -356,6 +360,7 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
entry.running -= 1;
onWorking(working());
}
+ if (!result.ok || (result.stopReason?.stopReason !== 'cancelled' && result.stopReason !== 'cancelled')) onConnectionResult(entry.agent, connectionError);
/* GitHub Copilot, its session naming no model (on some accounts): the one that answered, as its own record says,
for the turn's footer */
if (result.ok && entry.agent === 'copilot' && !entry.info?.configOptions?.some((o) => o?.category === 'model')) {
diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs
index 1e655ef..3fc3081 100644
--- a/apps/desktop/src/main.mjs
+++ b/apps/desktop/src/main.mjs
@@ -27,7 +27,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, openAgentInstaller, openAgentSignIn, setChosenPaths, signOutAgent } from './agents.mjs';
+import { checkAgentProgram, closeEverySession, diagnoseAgent, forgetAgentStatus, listAgents, localAgent, openAgentInstaller, openAgentSignIn, setChosenPaths, signOutAgent } from './agents.mjs';
import { agentUsage, forgetAgentUsage } from './agent-usage.mjs';
import { installOpenfilmCommand } from './openfilm-command.mjs';
import { startUpdates } from './updates.mjs';
@@ -584,6 +584,7 @@ async function start() {
onWorking: tellWorking,
/* a tab says when its agent waits for the person's answer */
onAsking: (folders) => void tellTabsWorking({ asking: folders }),
+ onConnectionResult: (id, error) => roster?.recordConnectionResult(id, error),
/* the `openfilm` command first (with the app's ffmpeg and browser in it); the app's ffmpeg last, for a computer
that has none of its own: the person's own ffmpeg and browsers are what the agent's commands use */
binDir: installOpenfilmCommand(DATA, { ffmpeg: ffmpegHere, env: browsers }),
@@ -625,6 +626,7 @@ async function start() {
/* sessions closed on connecting, disconnecting and switching account: the next look at its usage is for whichever
account is used now */
closeSessions: (id) => { forgetAgentUsage(id); localAgents?.closeAgent(id); },
+ resetAgent: (id) => { forgetAgentStatus(id); forgetAgentUsage(id); localAgents?.refreshSkills(id); },
seal,
unseal,
onChange: (list) => broadcast('desktop:agents', list),
@@ -642,6 +644,7 @@ async function start() {
return fn(opts ?? {});
});
agentHandle('desktop:agents:list', () => { void roster.refresh(); return roster.list(); });
+ agentHandle('desktop:agents:refresh', () => roster.recheck());
agentHandle('desktop:agents:connect', ({ id }) => roster.connect(String(id)));
agentHandle('desktop:agents:cancel-sign-in', ({ id }) => { roster.cancelSignIn(String(id)); return { ok: true }; });
agentHandle('desktop:agents:disconnect', ({ id }) => { roster.disconnect(String(id)); return { ok: true }; });
@@ -652,6 +655,11 @@ async function start() {
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)));
+ agentHandle('desktop:agents:setup', async ({ id }) => {
+ if (id !== 'claude') return { ok: false, error: 'No desktop setup for this agent.' };
+ try { await shell.openExternal('claude://'); return { ok: true }; }
+ catch (error) { return { ok: false, error: error instanceof Error ? error.message : String(error) }; }
+ });
/* 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 }, {
version: app.getVersion(), flavor: FLAVOR, packaged: app.isPackaged, channel: updates?.snapshot()?.channel ?? null,
diff --git a/apps/desktop/src/preload.cjs b/apps/desktop/src/preload.cjs
index f4d85fe..c076104 100644
--- a/apps/desktop/src/preload.cjs
+++ b/apps/desktop/src/preload.cjs
@@ -45,6 +45,7 @@ contextBridge.exposeInMainWorld('openfilmNative', {
/* the roster (agent-roster.mjs): Settings → Agents and the chat's menu */
agents: {
list: () => ipcRenderer.invoke('desktop:agents:list'),
+ refresh: () => ipcRenderer.invoke('desktop:agents:refresh'),
connect: (id) => ipcRenderer.invoke('desktop:agents:connect', { id }),
cancelSignIn: (id) => ipcRenderer.invoke('desktop:agents:cancel-sign-in', { id }),
disconnect: (id) => ipcRenderer.invoke('desktop:agents:disconnect', { id }),
@@ -56,6 +57,7 @@ contextBridge.exposeInMainWorld('openfilmNative', {
useAutomatic: (id) => ipcRenderer.invoke('desktop:agents:automatic', { id }),
install: (id) => ipcRenderer.invoke('desktop:agents:install', { id }),
diagnose: (id) => ipcRenderer.invoke('desktop:agents:diagnose', { id }),
+ openSetup: (id) => ipcRenderer.invoke('desktop:agents:setup', { id }),
report: () => ipcRenderer.invoke('desktop:agents:report'),
/* the whole diagnostic report on the clipboard (main.mjs): the chat's, by a turn that failed */
copyReport: () => ipcRenderer.invoke('desktop:diagnostics:copy'),
diff --git a/apps/desktop/src/windows-apps.mjs b/apps/desktop/src/windows-apps.mjs
new file mode 100644
index 0000000..33aa962
--- /dev/null
+++ b/apps/desktop/src/windows-apps.mjs
@@ -0,0 +1,52 @@
+/** Windows' installed desktop apps, including user-selected folders outside Programs. */
+import { execFileSync } from 'node:child_process';
+import { dirname, isAbsolute, join, win32 } from 'node:path';
+
+/** The uninstall keys' display names and folders; never run a command taken from the registry. */
+export function parseWindowsApps(text, env = process.env) {
+ const apps = [];
+ let item = {};
+ const expand = (value) => value.replace(/%([^%]+)%/g, (whole, name) => Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1] ?? whole);
+ const keep = () => {
+ if (!item.DisplayName) return;
+ const dirs = [];
+ const location = expand(item.InstallLocation ?? '').trim().replace(/^"(.*)"$/, '$1');
+ if (isAbsolute(location) || win32.isAbsolute(location)) dirs.push(location);
+ const icon = expand(item.DisplayIcon ?? '').trim();
+ const iconFile = /^"([^"]+\.(?:exe|ico))"(?:\s*,\s*-?\d+)?$/i.exec(icon)?.[1] ?? /^(.*\.(?:exe|ico))(?:\s*,\s*-?\d+)?$/i.exec(icon)?.[1];
+ if (iconFile && (isAbsolute(iconFile) || win32.isAbsolute(iconFile))) dirs.push(win32.isAbsolute(iconFile) ? win32.dirname(iconFile) : dirname(iconFile));
+ if (dirs.length) apps.push({ name: item.DisplayName, directories: [...new Set(dirs)] });
+ };
+ for (const line of text.split(/\r?\n/)) {
+ if (/^HKEY_/i.test(line.trim())) { keep(); item = {}; continue; }
+ const match = /^\s+(DisplayName|InstallLocation|DisplayIcon)\s+REG_(?:EXPAND_)?SZ\s+(.*)$/.exec(line);
+ if (match) item[match[1]] = match[2].trim();
+ }
+ keep();
+ return apps;
+}
+
+let cached = { at: -Infinity, apps: [] };
+/** Cached because agent status is polled; registration alone does not prove the folder still exists. */
+export function installedWindowsApps() {
+ if (process.platform !== 'win32') return [];
+ if (Date.now() - cached.at < 10_000) return cached.apps;
+ const system = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32');
+ const keys = [
+ 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
+ 'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
+ 'HKLM\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
+ ];
+ const apps = [];
+ for (const key of keys) {
+ try {
+ // Chinese Windows uses GBK by default; read paths in UTF-8, as environment.mjs does.
+ const text = execFileSync(join(system, 'cmd.exe'), ['/d', '/s', '/c', `chcp 65001 >nul && "${join(system, 'reg.exe')}" query "${key}" /s`], {
+ encoding: 'utf8', timeout: 2000, maxBuffer: 8 * 1024 * 1024, windowsHide: true, windowsVerbatimArguments: true, stdio: ['ignore', 'pipe', 'ignore'],
+ });
+ apps.push(...parseWindowsApps(text));
+ } catch { /* a key can be missing or unreadable */ }
+ }
+ cached = { at: Date.now(), apps };
+ return apps;
+}
diff --git a/apps/desktop/src/windows-apps.test.mjs b/apps/desktop/src/windows-apps.test.mjs
new file mode 100644
index 0000000..6423650
--- /dev/null
+++ b/apps/desktop/src/windows-apps.test.mjs
@@ -0,0 +1,39 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { parseWindowsApps } from './windows-apps.mjs';
+
+test('Windows app registrations retain custom folders, quoted paths, spaces and non-ASCII names', () => {
+ const apps = parseWindowsApps(String.raw`
+HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\deepseek
+ DisplayName REG_SZ DeepSeek Harness 0.2.1-rc.3
+ InstallLocation REG_SZ "D:\Apps\DeepSeek Harness"
+ DisplayIcon REG_SZ "D:\Apps\DeepSeek Harness\DeepSeek Harness.exe",0
+
+HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\opencode
+ DisplayName REG_SZ OpenCode 2.1.4
+ DisplayIcon REG_SZ D:\Apps\视频工具\OpenCode.exe,0
+HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\minimax
+ DisplayName REG_SZ MiniMax Code 3.1.4
+ DisplayIcon REG_SZ D:\Apps\MiniMax Code\uninstallerIcon.ico
+`);
+ assert.deepEqual(apps, [
+ { name: 'DeepSeek Harness 0.2.1-rc.3', directories: [String.raw`D:\Apps\DeepSeek Harness`] },
+ { name: 'OpenCode 2.1.4', directories: [String.raw`D:\Apps\视频工具`] },
+ { name: 'MiniMax Code 3.1.4', directories: [String.raw`D:\Apps\MiniMax Code`] },
+ ]);
+});
+
+test('registrations expand environment paths without treating uninstall commands as locations', () => {
+ const apps = parseWindowsApps(String.raw`
+HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\copilot
+ DisplayName REG_SZ GitHub Copilot
+ InstallLocation REG_EXPAND_SZ %LOCALAPPDATA%\Programs\GitHub Copilot
+ UninstallString REG_SZ "D:\Other\uninstall.exe" --remove
+HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\incomplete
+ DisplayName REG_SZ Cursor
+ InstallLocation REG_SZ relative\folder
+HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\nameless
+ DisplayIcon REG_SZ D:\Other\Other.exe,0
+`, { LocalAppData: String.raw`D:\Local` });
+ assert.deepEqual(apps, [{ name: 'GitHub Copilot', directories: [String.raw`D:\Local\Programs\GitHub Copilot`] }]);
+});
diff --git a/packages/openfilm/studio/ui/src/components/settings/AgentConnectionHelp.tsx b/packages/openfilm/studio/ui/src/components/settings/AgentConnectionHelp.tsx
new file mode 100644
index 0000000..9552a2a
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/settings/AgentConnectionHelp.tsx
@@ -0,0 +1,94 @@
+import React from 'react';
+import { createPortal } from 'react-dom';
+import { Check, Copy, Loader2, X } from 'lucide-react';
+import { useT } from '@/i18n';
+import type { HostAgent, HostAgentDiagnosis } from '@/lib/host';
+import { SettingsButton, SettingsLinkButton } from './ui';
+
+/** Connection instructions and opt-in diagnostics, above Settings without closing the parent dialog on Escape. */
+export function AgentConnectionHelp({ agent, status, report, checking, hint, error, notice, copied, onClose, onCheck, onLocate, onCopy }: {
+ agent: HostAgent;
+ status: string | null;
+ report: HostAgentDiagnosis | null;
+ checking: boolean;
+ hint: string | null;
+ error?: string;
+ notice?: string;
+ copied?: boolean;
+ onClose: () => void;
+ onCheck?: () => void;
+ onLocate?: () => void;
+ onCopy?: () => void;
+}) {
+ const t = useT();
+ const dialog = React.useRef<HTMLDialogElement>(null);
+ const titleId = React.useId();
+ React.useLayoutEffect(() => {
+ const node = dialog.current;
+ if (!node) return undefined;
+ const overflow = document.body.style.overflow;
+ document.body.style.overflow = 'hidden';
+ node.showModal();
+ return () => { node.close(); document.body.style.overflow = overflow; };
+ }, []);
+
+ const setup = agent.setupRequired === 'code-tab' ? 'claudeSetup' : agent.path ? 'helpFound'
+ : agent.app ? 'helpDesktopOnly' : ['codex', 'copilot', 'opencode', 'deepseek'].includes(agent.id) ? 'helpBundled' : 'helpInstall';
+ const words = (key: string) => t(`settings.agents.${key}`).replaceAll('{name}', agent.name);
+ const raw = [error, agent.connectionIssue?.message, report?.text].filter(Boolean).join('\n\n');
+
+ return createPortal(
+ <dialog ref={dialog} aria-labelledby={titleId} aria-modal="true"
+ className="m-auto max-h-[85vh] overflow-hidden rounded-[14px] border border-[var(--border)] bg-[var(--dock-pane)] p-0 text-[var(--text)] shadow-[0_24px_64px_-12px_rgba(0,0,0,0.5)] backdrop:bg-black/50 open:flex open:flex-col"
+ style={{ width: 'min(640px, calc(100vw - 32px))' }}
+ onCancel={(event) => { event.preventDefault(); onClose(); }}
+ onKeyDown={(event) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); onClose(); } }}
+ onClick={(event) => {
+ if (event.target !== event.currentTarget) return;
+ const bounds = event.currentTarget.getBoundingClientRect();
+ if (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom) onClose();
+ }}>
+ <header className="flex shrink-0 items-center justify-between gap-4 border-b border-[var(--border)] px-6 py-4">
+ <h3 id={titleId} className="text-[18px] font-semibold">{words('helpTitle')}</h3>
+ <button type="button" onClick={onClose} aria-label={words('close')} className="flex h-8 w-8 shrink-0 items-center justify-center rounded-[6px] text-[var(--text-muted)] hover:bg-[var(--bg-hover)]"><X size={18} /></button>
+ </header>
+ <div className="min-h-0 overflow-y-auto overscroll-contain px-6 py-5 text-[14px] leading-relaxed text-[var(--text-muted)]">
+ <section>
+ <h4 className="mb-2 font-medium text-[var(--text)]">{words('helpConnect')}</h4>
+ <ol className="ml-5 list-decimal space-y-2">
+ <li>{words(setup)}</li><li>{words('helpLogin')}</li><li>{words('helpRefresh')}</li>
+ </ol>
+ </section>
+ <section className="mt-5">
+ <h4 className="mb-2 font-medium text-[var(--text)]">{words('helpMissingTitle')}</h4>
+ <p>{words('helpMissingBody')}</p>
+ <p className="mt-2">{words('helpDesktop')}</p>
+ {onLocate ? <button type="button" onClick={() => { onClose(); onLocate(); }} className="mt-2 text-[13px] underline underline-offset-2 hover:text-[var(--text)]">{words('locateFolder')}</button> : null}
+ </section>
+ {agent.connectionIssue ? <p className="mt-4">{words(agent.connectionIssue.kind === 'quota' ? 'quotaHelp' : 'credentialsHelp')}</p> : null}
+ <section className="mt-5 border-t border-[var(--border)] pt-4">
+ <div className="mb-2 flex items-center justify-between gap-3">
+ <h4 className="font-medium text-[var(--text)]">{words('helpCheckTitle')}</h4>
+ {onCheck ? <SettingsButton variant="quiet" disabled={checking} onClick={onCheck}>{checking ? <Loader2 size={14} className="animate-spin" /> : null}{words(checking ? 'searching' : 'recheck')}</SettingsButton> : null}
+ </div>
+ {status ? <p>{status}</p> : null}
+ {notice ? <p role="status" className="mt-2">{notice}</p> : null}
+ {agent.path ? <p className="mt-1 break-all font-mono text-[12px]">{agent.path}</p> : null}
+ {hint ? <p role="status" className="mt-2">{hint}</p> : null}
+ {raw ? <details className="mt-3 text-[13px]">
+ <summary className="cursor-pointer py-1">{words('technicalDetails')}</summary>
+ <pre className="mt-1 max-h-52 overflow-auto whitespace-pre-wrap break-words rounded-[6px] bg-[var(--fill-tsp)] p-3 font-mono text-[12px]">{raw}</pre>
+ </details> : null}
+ {report && onCopy ? <div className="mt-3 flex flex-col gap-2 text-[12px]">
+ <p>{words('reportNote')}</p>
+ <SettingsButton variant="quiet" onClick={onCopy}>{copied ? <Check size={14} /> : <Copy size={14} />}{words(copied ? 'copied' : 'copyReport')}</SettingsButton>
+ </div> : null}
+ </section>
+ </div>
+ <footer className="flex shrink-0 items-center justify-between gap-4 border-t border-[var(--border)] px-6 py-4">
+ {agent.install ? <SettingsLinkButton href={agent.install}>{words('helpOfficial')}</SettingsLinkButton> : <span />}
+ <SettingsButton autoFocus onClick={onClose}>{words('helpDone')}</SettingsButton>
+ </footer>
+ </dialog>, document.body,
+ );
+}
diff --git a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
index 1f9a135..80e8d0d 100644
--- a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
+++ b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
@@ -11,9 +11,9 @@
* are always listed under the person's agents, with the person's own key; the others there once switched on (connecting
* 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); 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
+ * One not found, or one disconnected, can be pointed at: connection help opens the system's folder dialog, and the
+ * app finds and tries its connection program before using it (Find automatically goes back). An app with a bundled
+ * agent resolves to that agent. Connection actions stay beside the visibility switch. 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.
*
@@ -21,7 +21,7 @@
* let in (its maker's own are always on).
*/
import React from 'react';
-import { Check, Copy, Download, KeyRound, Loader2, Plus, X } from 'lucide-react';
+import { Check, CircleHelp, Download, KeyRound, Loader2, Plus, RefreshCw, X } from 'lucide-react';
import { useLanguage, useT } from '@/i18n';
import { BYOK_EFFORTS, studioHost, type HostAgent, type HostAgentDiagnosis, type HostAgentId, type HostAgentUsage, type HostByokEffort, type HostByokEffortLevel, type HostByokFormat, type HostOwnModel } from '@/lib/host';
import { parseContextLength } from '@/lib/context-length';
@@ -35,7 +35,7 @@ import { ProviderMark } from './ProviderMark';
import { agentMark } from '@/lib/provider-marks';
import { SettingsSelect } from './SettingsSelect';
import { SettingsButton, SettingsField, SettingsGroup, SettingsInset, SettingsItem, SettingsLinkButton, SettingsPage, SettingsStatus, SettingsSwitch, settingsError } from './ui';
-import { ReportLink } from './DiagnosticsGroup';
+import { AgentConnectionHelp } from './AgentConnectionHelp';
function useHostAgents(): HostAgent[] | null {
const [agents, setAgents] = React.useState<HostAgent[] | null>(null);
@@ -43,10 +43,15 @@ function useHostAgents(): HostAgent[] | null {
const host = studioHost?.agents;
if (!host) return undefined;
let live = true;
- void host.list().then((list) => { if (live) setAgents(list); }).catch(() => {});
- const stop = host.onChange((list) => setAgents(list));
+ let revision = 0;
+ const read = (ask: () => Promise<HostAgent[]>) => {
+ const started = revision;
+ void ask().then((list) => { if (live && revision === started) setAgents(list); }).catch(() => {});
+ };
+ const stop = host.onChange((list) => { revision++; if (live) setAgents(list); });
+ read(() => host.list());
/* a sign-in finished in Terminal: coming back is the moment to look again */
- const onFocus = () => { void host.list().then((list) => { if (live) setAgents(list); }).catch(() => {}); };
+ const onFocus = () => read(() => host.list());
window.addEventListener('focus', onFocus);
return () => { live = false; stop(); window.removeEventListener('focus', onFocus); };
}, []);
@@ -117,40 +122,68 @@ export function AgentsSection() {
const host = studioHost?.agents;
const [busy, setBusy] = React.useState<HostAgentId | null>(null);
const [error, setError] = React.useState<{ id: HostAgentId; text: string } | null>(null);
+ const [help, setHelp] = React.useState<HostAgentId | null>(null);
+ const [notice, setNotice] = React.useState<{ id: HostAgentId; text: string } | null>(null);
+ const [refreshing, setRefreshing] = React.useState(false);
+ const [refreshError, setRefreshError] = React.useState<string | null>(null);
const [keyOpen, setKeyOpen] = React.useState(false);
- const [diagnosis, setDiagnosis] = React.useState<{ id: HostAgentId; report: HostAgentDiagnosis | null; copied?: boolean } | null>(null);
+ const [diagnosis, setDiagnosis] = React.useState<{ id: HostAgentId; report: HostAgentDiagnosis | null; checking?: boolean; copied?: boolean } | null>(null);
/* the agent whose installer the person is asked about */
const [confirming, setConfirming] = React.useState<HostAgentId | null>(null);
/* the agent whose account the person is switching: asked first, or told where it switches */
const [switching, setSwitching] = React.useState<HostAgentId | null>(null);
if (!host) return null;
const offerSwitch = (agent: HostAgent) => switchOffer(agent, { switchAccount: Boolean(host.switchAccount) });
+ const refreshAgents = () => {
+ setRefreshing(true);
+ setRefreshError(null);
+ setError(null);
+ setNotice(null);
+ setDiagnosis(null);
+ void (host.refresh ? host.refresh() : host.list())
+ .catch((e: unknown) => setRefreshError(e instanceof Error ? e.message : String(e)))
+ .finally(() => setRefreshing(false));
+ };
const act = (id: HostAgentId, run: () => Promise<{ ok?: boolean; error?: string } | unknown>) => {
setBusy(id);
setError(null);
+ setNotice(null);
+ const failed = (text: string) => { setError({ id, text }); if (id !== 'byok') setHelp(id); };
void run()
- .then((r) => { const res = r as { ok?: boolean; error?: string } | undefined; if (res && res.ok === false) setError({ id, text: res.error ?? t('settings.agents.failed') }); })
- .catch((e: unknown) => setError({ id, text: e instanceof Error ? e.message : String(e) }))
+ .then((r) => { const res = r as { ok?: boolean; error?: string } | undefined; if (res && res.ok === false) failed(res.error ?? t('settings.agents.failed')); })
+ .catch((e: unknown) => failed(e instanceof Error ? e.message : String(e)))
.finally(() => setBusy(null));
};
- /* the person points at the program: tried by the app before it is used; cancelling says nothing */
+ /* find and try the connection program in the chosen installation folder; cancelling says nothing */
const locate = (agent: HostAgent) => act(agent.id, async () => {
- const r = await host.locate!(agent.id, { title: t('settings.agents.locateTitle').replace('{name}', agent.name), button: t('settings.agents.locateButton') });
+ const r = await host.locate!(agent.id, { title: t('settings.agents.locateFolderTitle').replace('{name}', agent.name), button: t('settings.agents.locateButton'), kind: 'folder' });
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.ok) {
+ setNotice({ id: agent.id, text: `${t('settings.agents.programReady')}${r.version ? ` · ${r.version}` : ''}` });
+ return { ok: true };
+ }
+ if (!r.error && !r.code) return { ok: true };
+ if (r.code === 'not-a-program') {
+ setHelp(agent.id);
+ setNotice({ id: agent.id, text: t('settings.agents.folderNoAgent').replaceAll('{name}', agent.name) });
+ return { ok: true };
+ }
+ if (r.code === 'app' || r.code === 'not-cursor-agent') {
+ setHelp(agent.id);
+ setNotice({ id: agent.id, text: t('settings.agents.appNeedsComponent').replaceAll('{name}', agent.name) });
+ return { ok: true };
+ }
if (r.code === 'did-not-start') return { ok: false, error: `${t('settings.agents.didNotStart')} ${r.error ?? ''}`.trim() };
return r;
});
const diagnose = (agent: HostAgent) => {
- setDiagnosis({ id: agent.id, report: null });
+ setHelp(agent.id);
+ setDiagnosis({ id: agent.id, report: null, checking: true });
void host.diagnose!(agent.id)
- .then((report) => setDiagnosis((d) => (d?.id === agent.id ? { id: agent.id, report } : d)))
+ .then((report) => setDiagnosis((d) => (d?.id === agent.id ? { id: agent.id, report, checking: false } : d)))
.catch((e: unknown) => { setDiagnosis(null); setError({ id: agent.id, text: e instanceof Error ? e.message : String(e) }); });
};
@@ -171,8 +204,9 @@ export function AgentsSection() {
};
const statusLine = (agent: HostAgent) => {
+ if (agent.connectionIssue && (agent.status === 'ready' || agent.status === 'off')) return t(`settings.agents.${agent.connectionIssue.kind === 'quota' ? 'quotaReached' : 'modelCredentials'}`);
switch (agent.status) {
- case 'off': return t('settings.agents.off');
+ case 'off': return t(agent.shown ? 'settings.agents.off' : 'settings.agents.available');
case 'sign-in': return t('settings.agents.signedOut');
case 'waiting': return t('settings.agents.waiting');
case 'missing':
@@ -203,37 +237,25 @@ export function AgentsSection() {
const action = (agent: HostAgent, chosen = true) => {
const working = busy === agent.id;
if (agent.status === 'ready' && chosen) {
- return (
- <>
- {offerSwitch(agent) ? (
- <SettingsButton variant="quiet" disabled={working || switching === agent.id} onClick={() => setSwitching(agent.id)}>
- {t('settings.agents.switchAccount')}
- </SettingsButton>
- ) : null}
- <SettingsButton variant="quiet" disabled={working} title={agent.id === 'byok' ? undefined : t('settings.agents.disconnectHint').replaceAll('{name}', agent.name)}
- onClick={() => act(agent.id, () => host.disconnect(agent.id))}>
- {t('settings.agents.disconnect')}
- </SettingsButton>
- </>
- );
+ return <>
+ {offerSwitch(agent) ? <SettingsButton variant="quiet" disabled={working || switching === agent.id} onClick={() => setSwitching(agent.id)}>{t('settings.agents.switchAccount')}</SettingsButton> : null}
+ <SettingsButton variant="quiet" disabled={working} title={t('settings.agents.disconnectHint')} onClick={() => act(agent.id, () => host.disconnect(agent.id))}>{t('settings.agents.disconnect')}</SettingsButton>
+ </>;
}
if (agent.status === 'missing') {
+ if (agent.setupRequired === 'code-tab') return host.openSetup ? (
+ <SettingsButton disabled={working} onClick={() => act(agent.id, () => host.openSetup!(agent.id))}>{t('settings.agents.openClaude')}</SettingsButton>
+ ) : null;
const offer = missingActions(agent, { locate: Boolean(host.locate), install: Boolean(host.install) });
- if (!offer.locate && !offer.install) return null;
+ if (!offer.install) return null;
return (
<>
- {offer.locate ? (
- <SettingsButton variant="quiet" disabled={working} onClick={() => locate(agent)}>
- {working ? <Loader2 size={16} className="animate-spin" aria-hidden /> : null}
- {t('settings.agents.locate')}
- </SettingsButton>
- ) : null}
{/* its official installer, run once the person agrees to the command; else its install page */}
{offer.install === 'run' ? (
<SettingsButton disabled={working || agent.installing || confirming === agent.id} onClick={() => setConfirming(agent.id)}>
- <Download size={16} />{t('settings.agents.install')}
+ <Download size={16} />{t('settings.agents.installComponent')}
</SettingsButton>
- ) : offer.install === 'page' && agent.install ? <SettingsLinkButton href={agent.install}><Download size={16} />{t('settings.agents.install')}</SettingsLinkButton> : null}
+ ) : offer.install === 'page' && agent.install ? <SettingsLinkButton href={agent.install}><Download size={16} />{t('settings.agents.installComponent')}</SettingsLinkButton> : null}
</>
);
}
@@ -245,19 +267,12 @@ export function AgentsSection() {
{t('settings.agents.cancel')}
</SettingsButton>
);
- /* disconnected: the program it runs can be pointed at before connecting again (a particular version, another
- install); a connected one keeps the program it found. The own key has none */
- const canLocate = agent.status === 'off' && host.locate && agent.id !== 'byok';
+ /* Manual location is in connection help. Connecting reuses an existing sign-in. */
return (
<>
- {canLocate ? (
- <SettingsButton variant="quiet" disabled={working} onClick={() => locate(agent)}>
- {t('settings.agents.locate')}
- </SettingsButton>
- ) : null}
<SettingsButton disabled={working} onClick={() => act(agent.id, () => host.connect(agent.id))}>
{working ? <Loader2 size={16} className="animate-spin" aria-hidden /> : null}
- {agent.status === 'sign-in' ? t('settings.agents.signIn') : t('settings.agents.connect')}
+ {t(agent.status === 'sign-in' ? 'settings.agents.signInConnect' : 'settings.agents.connect')}
</SettingsButton>
</>
);
@@ -270,12 +285,11 @@ export function AgentsSection() {
const said = error?.id === agent.id ? error.text : agent.error ?? (problem ? `${t('settings.agents.unreadable')} ${problem}` : undefined);
const open = agent.id === 'byok' && keyOpen;
/* where it is not found: why, on asking (Claude Code waiting for its app's Code tab is not lost) */
- const lost = agent.status === 'missing' && agent.setupRequired !== 'code-tab' && Boolean(host.diagnose);
- const diag = diagnosis?.id === agent.id ? diagnosis : null;
+ const showHelper = agent.id !== 'byok' && (['missing', 'off', 'sign-in', 'waiting'].includes(agent.status) || Boolean(said) || Boolean(agent.connectionIssue));
+ const description = agent.connectionIssue ? statusLine(agent) : agent.status === 'ready' ? chosen ? accountLine(agent) : t('settings.agents.available') : statusLine(agent);
/* what is left of its plan: while being asked, and once told (an agent that can't say shows nothing) */
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;
/* Switch account: here, once the person agrees to the sign-out; elsewhere, where (in its maker's app or itself) */
const switchHow = chosen && switching === agent.id ? offerSwitch(agent) : null;
@@ -295,10 +309,14 @@ export function AgentsSection() {
{t('settings.agents.recommended')}
</span>
) : null}
- {agent.status === 'ready' && chosen && !problem ? <SettingsStatus>{ownKey ? agent.byok!.models.map((m) => m.name).join(', ') : t('settings.agents.ready')}</SettingsStatus> : null}
+ {agent.status === 'ready' && chosen && !problem && !agent.connectionIssue ? <SettingsStatus>{ownKey ? agent.byok!.models.map((m) => m.name).join(', ') : t('settings.agents.ready')}</SettingsStatus> : null}
</>
)}
- description={agent.status === 'ready' ? accountLine(agent) : statusLine(agent)}
+ description={description || showHelper ? <div className="flex items-center gap-1">
+ {description ? <span className="min-w-0">{description}</span> : null}
+ {showHelper ? <button type="button" aria-label={t('settings.agents.helpFor').replace('{name}', agent.name)} title={t('settings.agents.helpFor').replace('{name}', agent.name)}
+ onClick={() => setHelp(agent.id)} className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"><CircleHelp size={15} aria-hidden /></button> : null}
+ </div> : null}
control={(
<>
{ownKey && !open ? <SettingsButton variant="quiet" onClick={() => setKeyOpen(true)}>{t('settings.agents.change')}</SettingsButton> : null}
@@ -308,8 +326,10 @@ export function AgentsSection() {
</>
)}
>
- {agent.status === 'waiting' || open || said || agent.chosen || lost || meter || asking || switchHow || (chosen && agent.status === 'ready' && (host.mcp || host.skills)) ? (
+ {agent.status === 'waiting' || open || said || asking || switchHow || agent.chosen || meter || notice?.id === agent.id || (chosen && agent.status === 'ready' && (host.mcp || host.skills)) ? (
<div className="flex flex-col gap-1.5 pl-[34px]">
+ {notice?.id === agent.id ? <p role="status" className="text-[13.5px] leading-relaxed text-[var(--text-muted)]">{notice.text}</p> : null}
+ {said ? <p role="alert" className={settingsError}>{said}</p> : null}
{meter ? (
<div className="flex flex-col gap-1.5" aria-label={t('settings.agents.usage')}>
{plan === undefined ? (
@@ -355,27 +375,6 @@ export function AgentsSection() {
</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>
- </p>
- ) : null}
- {lost && diag && !diag.report ? (
- <p className="flex items-center gap-1.5 text-[13.5px] text-[var(--text-muted)]"><Loader2 size={14} className="animate-spin" aria-hidden />{t('settings.agents.searching')}</p>
- ) : null}
- {lost && diag?.report ? (
- <SettingsInset>
- {hint ? <p className="break-words text-[14px] leading-relaxed text-[var(--text)]">{hint}</p> : null}
- <p className="text-[13px] leading-relaxed text-[var(--text-faint)]">{t('settings.agents.reportNote')}</p>
- <div className="flex justify-end gap-1.5">
- <SettingsButton variant="quiet" onClick={() => setDiagnosis(null)}>{t('settings.agents.close')}</SettingsButton>
- <SettingsButton onClick={() => copyReport(diag.report!, agent.id)}>
- {diag.copied ? <Check size={15} aria-hidden /> : <Copy size={15} aria-hidden />}
- {diag.copied ? t('settings.agents.copied') : t('settings.agents.copyReport')}
- </SettingsButton>
- </div>
- </SettingsInset>
- ) : null}
{agent.status === 'waiting' ? (
<p className="text-[14.5px] leading-relaxed text-[var(--text-muted)]">
{t(WAITING_HINTS[agent.id] ?? 'settings.agents.waitingHint')}{' '}
@@ -383,9 +382,6 @@ export function AgentsSection() {
</p>
) : null}
{open ? <OwnModels agent={agent} onDone={() => setKeyOpen(false)} /> : null}
- {said ? <p className={settingsError}>{said}</p> : null}
- {/* what to send when it keeps failing */}
- {said ? <ReportLink /> : null}
</div>
) : null}
</SettingsItem>
@@ -393,6 +389,9 @@ export function AgentsSection() {
};
const list = agents ?? [];
+ const helpAgent = list.find((agent) => agent.id === help);
+ const helpDiagnosis = diagnosis?.id === help ? diagnosis : null;
+ const helpError = helpAgent ? error?.id === help ? error.text : helpAgent.error ?? (helpAgent.problem ? `${t('settings.agents.unreadable')} ${helpAgent.problem}` : undefined) : undefined;
const byId = (id: HostAgentId) => list.find((a) => a.id === id);
/* always yours: Codex, Claude Code and your own key; then the others switched on, the rest under "More" */
const always = (['codex', 'claude', 'byok'] as const).map(byId).filter((a): a is HostAgent => Boolean(a));
@@ -400,10 +399,21 @@ export function AgentsSection() {
const more = others.filter((a) => !a.shown);
return (
<SettingsPage note={t('settings.agents.intro')}>
+ <div className="mb-3 flex justify-end">
+ <SettingsButton variant="quiet" disabled={refreshing} aria-busy={refreshing} onClick={refreshAgents}><RefreshCw size={15} className={refreshing ? 'animate-spin' : ''} />{t('settings.agents.refreshCheck')}</SettingsButton>
+ </div>
+ {refreshError ? <p role="alert" className={settingsError}>{refreshError}</p> : null}
<SettingsGroup title={t('settings.agents.groupYours')} footnote={t('settings.agents.showHint')}>
{[...always, ...others.filter((a) => a.shown)].map((a) => row(a))}
</SettingsGroup>
{more.length ? <SettingsGroup title={t('settings.agents.groupMore')}>{more.map((a) => row(a, false))}</SettingsGroup> : null}
+ {helpAgent ? <AgentConnectionHelp key={helpAgent.id} agent={helpAgent}
+ status={helpAgent.status === 'ready' && !helpAgent.connectionIssue ? t('settings.agents.ready') : statusLine(helpAgent)}
+ report={helpDiagnosis?.report ?? null} checking={Boolean(helpDiagnosis?.checking)}
+ hint={helpDiagnosis?.report ? hintOf(helpDiagnosis.report) : null} error={helpError} notice={notice?.id === helpAgent.id ? notice.text : undefined} copied={helpDiagnosis?.copied}
+ onClose={() => setHelp(null)} onCheck={host.diagnose ? () => diagnose(helpAgent) : undefined}
+ onLocate={host.locate && ['missing', 'off'].includes(helpAgent.status) ? () => locate(helpAgent) : undefined}
+ onCopy={helpDiagnosis?.report ? () => copyReport(helpDiagnosis.report!, helpAgent.id) : undefined} /> : null}
</SettingsPage>
);
}
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index ee7393e..cdd8173 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -1729,17 +1729,52 @@ export const en = {
waitingHintMinimax: 'Finish signing in in the window that opened, then come back. An international MiniMax account can’t pick its site there: in a terminal, run mcode login --region global, then Start again.',
waitingHintCodebuddy: 'Finish signing in in the window that opened, then come back. That window is CodeBuddy’s own and is titled CodeBuddy, not OpenFilm or a terminal.',
startAgain: 'Start again',
- missing: 'Not installed on this computer',
- claudeSetup: 'Open the Claude app’s Code tab once to install Claude Code',
+ available: "Connection component found. Ready to connect.",
+ helpTitle: "Connect {name}",
+ helpFor: "Connection help for {name}",
+ helpConnect: "How to connect",
+ helpFound: "OpenFilm found the connection component for {name}. Use Connect in the list.",
+ helpDesktopOnly: "The {name} desktop app may need an additional connection component. Use Install connection component in the list, then connect.",
+ helpBundled: "OpenFilm looks for the component bundled with or maintained by the {name} app. Use Refresh connections after installing or updating it.",
+ helpInstall: "Install the connection component for {name}, then return to the list and connect.",
+ helpLogin: "When sign-in is needed, finish it in the agent’s own app or sign-in window, then return to OpenFilm.",
+ helpRefresh: "After changing models or credentials, use Refresh connections. Model availability is confirmed by your next message.",
+ helpMissingTitle: "If the agent is not found",
+ helpMissingBody: "For a custom installation location, use Choose installation folder… and select the folder where {name} is installed. OpenFilm will look for its connection component there.",
+ helpDesktop: "Finding a desktop editor alone does not mean its connection component is available. If the list asks for a component, use Install connection component.",
+ helpCheckTitle: "On this computer",
+ helpOfficial: "Official website",
+ helpDone: "Got it",
+ refreshCheck: 'Refresh connections',
+ installComponent: "Install connection component",
+ openClaude: "Open Claude",
+ signInConnect: "Sign in and connect",
+ locateFolder: "Choose installation folder…",
+ folderNoAgent: "No {name} connection component was found in this folder. Check the installation location, or install the component if you only have the desktop editor.",
+ locateFolderTitle: "Choose the {name} installation folder",
+ programReady: "Connection program is ready",
+ appNeedsComponent: "Found the {name} desktop app. This version needs a separate connection component. Install it, or choose the folder containing an existing component.",
+ moreFor: "More actions for {name}",
+ quotaReached: "The current model has no quota left",
+ modelCredentials: "The current model needs credentials",
+ resolveIssue: "How to resolve",
+ quotaHelp: "Choose an available model from the model selector below the conversation, or check usage in {name}. Then retry your message.",
+ credentialsHelp: "Configure credentials for the current provider in {name}, or choose a configured model in the conversation. Then retry your message.",
+ connectionNote: "Connecting checks the program and sign-in. Model availability is confirmed by an actual reply.",
+ programLocation: "Connection program in use:",
+ recheck: "Check again",
+ technicalDetails: "Technical details",
+ missing: "Connection component not found",
+ claudeSetup: "Open the Code tab in Claude to initialize its connection component.",
locate: 'Locate…',
- locateTitle: 'Choose the {name} program',
+ locateTitle: "Choose the {name} app or connection program",
locateButton: 'Use this',
- chosenAt: 'Using the program you chose: {path}',
+ chosenAt: "Installation location 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:',
+ appOnly: "Found the {app} desktop app. A connection component is needed.",
+ installing: "Installing the connection component… It will be detected automatically.",
+ installConfirm: "Run the official {name} installer to add its connection component:",
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.',
@@ -1747,10 +1782,10 @@ export const en = {
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?',
searching: 'Searching…',
- hintChosenMissing: 'The program you chose is not there any more. Choose it again, or find it automatically.',
+ hintChosenMissing: "The selected installation location or its connection program is no longer there. Choose it again or return to automatic detection.",
hintWsl: 'It is installed in WSL (Linux on Windows), which OpenFilm cannot use. Install it in Windows too, then come back.',
- hintUnusable: 'Files with its name were found, but none of them can be started. Use Locate… to choose the program itself.',
- hintNone: 'It is not in any of the folders searched. If {program} works in your terminal, find where it is there (“where {program}” on Windows, “which {program}” on a Mac) and choose that file with Locate….',
+ hintUnusable: "Files with the right name were found, but none can start. Choose the installation folder of the connection component again.",
+ hintNone: "No connection component was found in the searched locations. Choose its installation folder, or install the component first.",
hintFound: 'Found: {path}',
reportNote: 'If it still is not found, copy the report and send it with an issue. It lists folders on this computer.',
copyReport: 'Copy report',
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index 27382e0..9faa14a 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -1728,17 +1728,52 @@ export const es: Words = {
waitingHintMinimax: 'Termina de iniciar sesión en la ventana que se abrió y vuelve aquí. Una cuenta internacional de MiniMax no puede elegir su sitio ahí: en una terminal, ejecuta mcode login --region global y luego pulsa Volver a empezar.',
waitingHintCodebuddy: 'Termina de iniciar sesión en la ventana que se abrió y vuelve aquí. Esa ventana es de CodeBuddy y su título es CodeBuddy, no OpenFilm ni una terminal.',
startAgain: 'Volver a empezar',
- missing: 'No está instalado en este equipo',
- claudeSetup: 'Abre una vez la pestaña Code de la app de Claude para instalar Claude Code',
- locate: 'Elegir…',
- locateTitle: 'Elige el programa de {name}',
+ available: "Componente de conexión encontrado. Listo para conectar.",
+ helpTitle: "Conectar {name}",
+ helpFor: "Ayuda para conectar {name}",
+ helpConnect: "Cómo conectar",
+ helpFound: "OpenFilm encontró el componente de conexión de {name}. Pulsa Conectar en la lista.",
+ helpDesktopOnly: "La app de escritorio de {name} puede necesitar un componente de conexión adicional. Instálalo desde la lista y después conecta.",
+ helpBundled: "OpenFilm busca el componente incluido o gestionado por la app de {name}. Actualiza las conexiones tras instalarla o actualizarla.",
+ helpInstall: "Instala el componente de conexión de {name}, vuelve a la lista y conecta.",
+ helpLogin: "Si se solicita iniciar sesión, complétala en la app correspondiente o en su ventana de acceso y vuelve a OpenFilm.",
+ helpRefresh: "Después de cambiar modelos o credenciales, pulsa Actualizar conexiones. La disponibilidad del modelo se confirma con la respuesta al siguiente mensaje.",
+ helpMissingTitle: "Si no se detecta el agente",
+ helpMissingBody: "Si está instalado en otra ubicación, pulsa Elegir carpeta de instalación… y selecciona la carpeta de {name}. OpenFilm buscará el componente de conexión dentro de ella.",
+ helpDesktop: "Detectar un editor de escritorio no garantiza que su componente de conexión esté disponible. Si la lista lo solicita, instala el componente.",
+ helpCheckTitle: "En este equipo",
+ helpOfficial: "Sitio oficial",
+ helpDone: "Entendido",
+ refreshCheck: 'Actualizar conexiones',
+ installComponent: "Instalar componente de conexión",
+ openClaude: "Abrir Claude",
+ signInConnect: "Iniciar sesión y conectar",
+ locateFolder: "Elegir carpeta de instalación…",
+ folderNoAgent: "No se encontró el componente de conexión de {name} en esta carpeta. Comprueba la ubicación o instala el componente si solo tienes el editor de escritorio.",
+ locateFolderTitle: "Elegir la carpeta de instalación de {name}",
+ programReady: "El programa de conexión está listo",
+ appNeedsComponent: "Se encontró la app de escritorio de {name}. Esta versión necesita un componente de conexión independiente. Instálalo o elige la carpeta de un componente existente.",
+ moreFor: "Más acciones de {name}",
+ quotaReached: "El modelo actual ha agotado su cuota",
+ modelCredentials: "El modelo actual necesita credenciales",
+ resolveIssue: "Cómo resolverlo",
+ quotaHelp: "Elige un modelo disponible en el selector situado debajo de la conversación o revisa el uso en {name}. Después, reintenta el mensaje.",
+ credentialsHelp: "Configura las credenciales del proveedor actual en {name} o elige un modelo configurado en la conversación. Después, reintenta el mensaje.",
+ connectionNote: "La conexión comprueba el programa y la sesión. La disponibilidad del modelo se confirma con una respuesta real.",
+ programLocation: "Programa de conexión en uso:",
+ recheck: "Volver a detectar",
+ technicalDetails: "Detalles técnicos",
+ missing: "No se encontró el componente de conexión",
+ claudeSetup: "Abre la pestaña Code de Claude para inicializar su componente de conexión.",
+ locate: 'Elegir ubicación…',
+ locateTitle: "Elegir la app o el programa de conexión de {name}",
locateButton: 'Usar este',
- chosenAt: 'Usando el programa que elegiste: {path}',
+ chosenAt: "Ubicación de instalación elegida: {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}:',
+ appOnly: "Se encontró la app de escritorio de {app}. Hace falta un componente de conexión.",
+ installing: "Instalando el componente de conexión… Se detectará automáticamente.",
+ installConfirm: "Ejecutar el instalador oficial de {name} para añadir su componente de conexión:",
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.',
@@ -1746,10 +1781,10 @@ export const es: Words = {
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?',
searching: 'Buscando…',
- hintChosenMissing: 'El programa que elegiste ya no está. Elígelo de nuevo o vuelve a detectarlo automáticamente.',
+ hintChosenMissing: "La ubicación seleccionada o su programa de conexión ya no está disponible. Vuelve a elegirla o usa la detección automática.",
hintWsl: 'Está instalado en WSL (Linux en Windows), que OpenFilm no puede usar. Instálalo también en Windows y vuelve.',
- hintUnusable: 'Se encontraron archivos con su nombre, pero ninguno se puede iniciar. Usa Elegir… para seleccionar el programa.',
- hintNone: 'No está en ninguna de las carpetas revisadas. Si {program} funciona en tu terminal, busca allí dónde está («where {program}» en Windows, «which {program}» en Mac) y elige ese archivo con Elegir….',
+ hintUnusable: "Se encontraron archivos con el nombre esperado, pero ninguno se puede iniciar. Vuelve a elegir la carpeta del componente de conexión.",
+ hintNone: "No se encontró el componente en las ubicaciones consultadas. Elige su carpeta de instalación o instala el componente primero.",
hintFound: 'Encontrado: {path}',
reportNote: 'Si sigue sin encontrarse, copia el informe y envíalo con un issue. Incluye rutas de carpetas de este equipo.',
copyReport: 'Copiar informe',
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index 1ce1fd8..b26d2c6 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -1728,17 +1728,52 @@ export const ja: Words = {
waitingHintMinimax: '開いたウィンドウでサインインを完了してから、戻ってきてください。海外版の MiniMax アカウントは、そのウィンドウでサイトを選べません。ターミナルで mcode login --region global を実行し、「やり直す」を押してください。',
waitingHintCodebuddy: '開いたウィンドウでサインインを完了してから、戻ってきてください。このウィンドウは CodeBuddy 自身のもので、タイトルは CodeBuddy です(OpenFilm やターミナルではありません)。',
startAgain: 'やり直す',
- missing: 'このコンピューターにインストールされていません',
- claudeSetup: 'Claude アプリの Code タブを一度開くと Claude Code がインストールされます',
- locate: '場所を指定…',
- locateTitle: '{name} のプログラムを選択',
+ available: "接続コンポーネントを検出しました。接続できます。",
+ helpTitle: "{name} の接続ガイド",
+ helpFor: "{name} の接続ヘルプ",
+ helpConnect: "接続方法",
+ helpFound: "{name} の接続コンポーネントを検出しました。一覧から接続できます。",
+ helpDesktopOnly: "{name} のデスクトップアプリとは別に接続コンポーネントが必要な場合があります。一覧の「接続コンポーネントをインストール」を使い、完了後に接続してください。",
+ helpBundled: "OpenFilm は {name} アプリに同梱または管理される接続コンポーネントを探します。アプリのインストールや更新後は「接続を再確認」を使ってください。",
+ helpInstall: "{name} の接続コンポーネントをインストールし、一覧に戻って接続してください。",
+ helpLogin: "ログインを求められたら、各アプリまたはログイン画面で完了してから OpenFilm に戻ってください。",
+ helpRefresh: "モデルや認証情報を変更した後は「接続を再確認」を使ってください。モデルの利用可否は次のメッセージへの応答で確認されます。",
+ helpMissingTitle: "検出されない場合",
+ helpMissingBody: "既定以外の場所にインストールした場合は「インストール先を手動で選択…」で {name} のフォルダーを指定してください。OpenFilm がその中の接続コンポーネントを探します。",
+ helpDesktop: "デスクトップエディターの検出だけでは、接続コンポーネントの準備完了は確認できません。一覧で追加を求められたら「接続コンポーネントをインストール」を使ってください。",
+ helpCheckTitle: "このコンピューターでの検出",
+ helpOfficial: "公式サイト",
+ helpDone: "閉じる",
+ refreshCheck: '接続を再確認',
+ installComponent: "接続コンポーネントをインストール",
+ openClaude: "Claude を開く",
+ signInConnect: "ログインして接続",
+ locateFolder: "インストール先を手動で選択…",
+ folderNoAgent: "このフォルダーに {name} の接続コンポーネントが見つかりません。インストール先を確認してください。デスクトップエディターのみの場合は接続コンポーネントを追加してください。",
+ locateFolderTitle: "{name} のインストール先を選択",
+ programReady: "接続プログラムの準備ができました",
+ appNeedsComponent: "{name} のデスクトップアプリを検出しました。このバージョンには別の接続コンポーネントが必要です。追加するか、既存のコンポーネントのインストール先を選択してください。",
+ moreFor: "{name} のその他の操作",
+ quotaReached: "現在のモデルの利用枠を使い切りました",
+ modelCredentials: "現在のモデルには認証情報が必要です",
+ resolveIssue: "解決方法を見る",
+ quotaHelp: "会話下部のモデル選択で利用可能なモデルに切り替えるか、{name} で利用状況を確認してからメッセージを再試行してください。",
+ credentialsHelp: "{name} で現在のプロバイダーの認証情報を設定するか、会話で設定済みのモデルを選択してからメッセージを再試行してください。",
+ connectionNote: "接続時はプログラムとログイン状態を確認します。モデルの利用可否は実際の応答で確認されます。",
+ programLocation: "使用中の接続プログラム:",
+ recheck: "再検出",
+ technicalDetails: "技術的な詳細",
+ missing: "接続コンポーネントが見つかりません",
+ claudeSetup: "Claude の Code タブを開き、接続コンポーネントを初期化してください。",
+ locate: '手動で選択…',
+ locateTitle: "{name} のアプリまたは接続プログラムを選択",
locateButton: 'これを使う',
- chosenAt: '選択したプログラムを使用中:{path}',
+ chosenAt: "手動で指定したインストール先:{path}",
automatic: '自動検出に戻す',
notAProgram: 'このコンピュータで起動できるプログラムではありません。エージェントのプログラム自体を選んでください(Windows では .exe または .cmd ファイル)。',
- appOnly: '{app} アプリはインストールされていますが、接続には {name} のコマンドラインエージェントが必要です。',
- installing: 'ターミナルウィンドウでインストール中… 終わると OpenFilm が見つけます。',
- installConfirm: 'OpenFilm はターミナルウィンドウを開き、{name} の公式インストーラーを実行します:',
+ appOnly: "{app} のデスクトップアプリを検出しました。接続コンポーネントが必要です。",
+ installing: "接続コンポーネントをインストール中…完了後に自動で検出します。",
+ installConfirm: "{name} の公式インストーラーで接続コンポーネントを追加します:",
installRun: 'インストーラーを実行',
notTheAgentApp: 'これはエディターかデスクトップアプリで、{name} のコマンドラインエージェントではありません。接続には {name} のコマンドラインエージェントが必要です。',
notCursorAgent: 'これは Cursor のコマンドラインエージェントではありません(cursor-agent フォルダーにインストールされます)。接続には Cursor のコマンドラインエージェントが必要です。',
@@ -1746,10 +1781,10 @@ export const ja: Words = {
unreadable: '自分の設定を読み込めないため起動できません。設定ファイルの該当箇所を直すか、更新してください:',
whyMissing: '見つからない理由は?',
searching: '検索中…',
- hintChosenMissing: '選択したプログラムが見つかりません。もう一度選ぶか、自動検出に戻してください。',
+ hintChosenMissing: "指定したインストール先または接続プログラムが見つかりません。再選択するか、自動検出に戻してください。",
hintWsl: 'WSL(Windows 上の Linux)にインストールされていますが、OpenFilm からは使えません。Windows にもインストールしてから戻ってください。',
- hintUnusable: '同じ名前のファイルはありましたが、どれも起動できません。「場所を指定…」でプログラム自体を選んでください。',
- hintNone: '検索したフォルダのどこにもありません。ターミナルで {program} が使えるなら、そこで場所を調べ(Windows は「where {program}」、Mac は「which {program}」)、そのファイルを「場所を指定…」で選んでください。',
+ hintUnusable: "同名のファイルは見つかりましたが起動できません。接続コンポーネントのインストール先を選び直してください。",
+ hintNone: "検索した場所に接続コンポーネントが見つかりません。インストール先を選択するか、先にコンポーネントをインストールしてください。",
hintFound: '見つかりました:{path}',
reportNote: 'それでも見つからない場合は、レポートをコピーして issue に添えて送ってください。このコンピュータのフォルダのパスが含まれます。',
copyReport: 'レポートをコピー',
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 983be6d..91ace62 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -1724,17 +1724,52 @@ export const ko: Words = {
waitingHintMinimax: '열린 창에서 로그인을 완료한 뒤 돌아오세요. 해외 MiniMax 계정은 그 창에서 사이트를 고를 수 없습니다. 터미널에서 mcode login --region global 을 실행한 뒤 다시 시작을 누르세요.',
waitingHintCodebuddy: '열린 창에서 로그인을 완료한 뒤 돌아오세요. 이 창은 CodeBuddy 자체 창이며 제목이 CodeBuddy입니다(OpenFilm이나 터미널이 아닙니다).',
startAgain: '다시 시작',
- missing: '이 컴퓨터에 설치되어 있지 않음',
- claudeSetup: 'Claude 앱의 Code 탭을 한 번 열면 Claude Code가 설치됩니다',
+ available: "연결 구성 요소를 찾았습니다. 연결할 수 있습니다.",
+ helpTitle: "{name} 연결 안내",
+ helpFor: "{name} 연결 도움말",
+ helpConnect: "연결 방법",
+ helpFound: "{name}의 연결 구성 요소를 찾았습니다. 목록에서 바로 연결할 수 있습니다.",
+ helpDesktopOnly: "{name} 데스크톱 앱 외에 연결 구성 요소가 필요할 수 있습니다. 목록에서 연결 구성 요소를 설치한 후 연결하세요.",
+ helpBundled: "OpenFilm은 {name} 앱에 포함되거나 앱에서 관리하는 연결 구성 요소를 찾습니다. 앱을 설치하거나 업데이트한 후 연결 다시 확인을 누르세요.",
+ helpInstall: "{name}의 연결 구성 요소를 설치한 후 목록으로 돌아와 연결하세요.",
+ helpLogin: "로그인이 필요하면 해당 앱이나 로그인 창에서 완료한 후 OpenFilm으로 돌아오세요.",
+ helpRefresh: "모델이나 인증 정보를 변경한 후 연결 다시 확인을 누르세요. 모델 사용 가능 여부는 다음 메시지의 응답으로 확인됩니다.",
+ helpMissingTitle: "검색되지 않을 때",
+ helpMissingBody: "다른 위치에 설치했다면 설치 폴더 직접 선택을 눌러 {name}의 설치 폴더를 지정하세요. OpenFilm이 해당 폴더에서 연결 구성 요소를 찾습니다.",
+ helpDesktop: "데스크톱 편집기를 찾았다는 것만으로 연결 구성 요소가 준비된 것은 아닙니다. 목록에서 구성 요소가 필요하다고 안내하면 설치하세요.",
+ helpCheckTitle: "이 컴퓨터의 검색 결과",
+ helpOfficial: "공식 사이트",
+ helpDone: "확인",
+ refreshCheck: '연결 다시 확인',
+ installComponent: "연결 구성 요소 설치",
+ openClaude: "Claude 열기",
+ signInConnect: "로그인하고 연결",
+ locateFolder: "설치 폴더 직접 선택…",
+ folderNoAgent: "이 폴더에서 {name} 연결 구성 요소를 찾지 못했습니다. 설치 위치를 확인하세요. 데스크톱 편집기만 설치했다면 연결 구성 요소를 먼저 설치하세요.",
+ locateFolderTitle: "{name} 설치 폴더 선택",
+ programReady: "연결 프로그램이 준비되었습니다",
+ appNeedsComponent: "{name} 데스크톱 앱을 찾았습니다. 이 버전에는 별도의 연결 구성 요소가 필요합니다. 구성 요소를 설치하거나 기존 구성 요소의 설치 폴더를 선택하세요.",
+ moreFor: "{name} 추가 작업",
+ quotaReached: "현재 모델의 사용량을 모두 소진했습니다",
+ modelCredentials: "현재 모델에 인증 정보가 필요합니다",
+ resolveIssue: "해결 방법 보기",
+ quotaHelp: "대화 아래의 모델 선택기에서 사용 가능한 모델로 바꾸거나 {name}에서 사용량을 확인한 후 메시지를 다시 보내세요.",
+ credentialsHelp: "{name}에서 현재 공급자의 인증 정보를 설정하거나 대화에서 설정된 모델을 선택한 후 메시지를 다시 보내세요.",
+ connectionNote: "연결 시 프로그램과 로그인 상태를 확인합니다. 모델 사용 가능 여부는 실제 응답으로 확인됩니다.",
+ programLocation: "사용 중인 연결 프로그램:",
+ recheck: "다시 검색",
+ technicalDetails: "기술 세부 정보",
+ missing: "연결 구성 요소를 찾지 못했습니다",
+ claudeSetup: "Claude의 Code 탭을 열어 연결 구성 요소를 초기화하세요.",
locate: '직접 선택…',
- locateTitle: '{name} 프로그램 선택',
+ locateTitle: "{name} 앱 또는 연결 프로그램 선택",
locateButton: '이것 사용',
- chosenAt: '선택한 프로그램 사용 중: {path}',
+ chosenAt: "직접 지정한 설치 위치: {path}",
automatic: '자동 감지로 되돌리기',
notAProgram: '이 컴퓨터에서 실행할 수 있는 프로그램이 아닙니다. 에이전트 프로그램 자체를 선택하세요(Windows에서는 .exe 또는 .cmd 파일).',
- appOnly: '{app} 앱은 설치되어 있지만, 연결하려면 {name}의 명령줄 에이전트가 필요합니다.',
- installing: '터미널 창에서 설치하는 중… 끝나면 OpenFilm이 찾습니다.',
- installConfirm: 'OpenFilm이 터미널 창을 열고 {name}의 공식 설치 프로그램을 실행합니다:',
+ appOnly: "{app} 데스크톱 앱을 찾았습니다. 연결 구성 요소가 필요합니다.",
+ installing: "연결 구성 요소 설치 중… 완료되면 자동으로 검색합니다.",
+ installConfirm: "{name} 공식 설치 명령으로 연결 구성 요소를 추가합니다:",
installRun: '설치 프로그램 실행',
notTheAgentApp: '이것은 편집기나 데스크톱 앱이며, {name}의 명령줄 에이전트가 아닙니다. 연결하려면 {name}의 명령줄 에이전트가 필요합니다.',
notCursorAgent: '이것은 Cursor의 명령줄 에이전트가 아닙니다(cursor-agent 폴더에 설치됩니다). 연결하려면 Cursor의 명령줄 에이전트가 필요합니다.',
@@ -1742,10 +1777,10 @@ export const ko: Words = {
unreadable: '자체 설정을 읽지 못해 시작할 수 없습니다. 설정 파일에서 지적된 부분을 고치거나 업데이트하세요:',
whyMissing: '왜 찾지 못하나요?',
searching: '찾는 중…',
- hintChosenMissing: '선택한 프로그램이 더 이상 없습니다. 다시 선택하거나 자동 감지로 되돌리세요.',
+ hintChosenMissing: "선택한 설치 위치나 연결 프로그램을 더 이상 찾을 수 없습니다. 다시 선택하거나 자동 검색으로 돌아가세요.",
hintWsl: 'WSL(Windows의 Linux)에 설치되어 있어 OpenFilm에서 사용할 수 없습니다. Windows에도 설치한 뒤 돌아오세요.',
- hintUnusable: '같은 이름의 파일은 찾았지만 실행할 수 있는 것이 없습니다. “직접 선택…”으로 프로그램 자체를 선택하세요.',
- hintNone: '검색한 폴더 어디에도 없습니다. 터미널에서 {program}이(가) 실행된다면 그곳에서 위치를 확인하고(Windows는 “where {program}”, Mac은 “which {program}”) 그 파일을 “직접 선택…”으로 선택하세요.',
+ hintUnusable: "이름이 같은 파일을 찾았지만 실행할 수 없습니다. 연결 구성 요소의 설치 폴더를 다시 선택하세요.",
+ hintNone: "검색한 위치에서 연결 구성 요소를 찾지 못했습니다. 설치 폴더를 선택하거나 먼저 구성 요소를 설치하세요.",
hintFound: '찾았습니다: {path}',
reportNote: '그래도 찾지 못하면 보고서를 복사해 issue에 첨부해 보내 주세요. 이 컴퓨터의 폴더 경로가 포함됩니다.',
copyReport: '보고서 복사',
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index 1f50301..4147f83 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -1729,17 +1729,52 @@ export const zhCN: Words = {
waitingHintMinimax: '请在刚打开的窗口中完成登录,然后回到这里。国际版账号无法在该窗口选择站点:请在终端中运行 mcode login --region global,再点「重新开始」。',
waitingHintCodebuddy: '请在刚打开的窗口中完成登录,然后回到这里。该窗口是 CodeBuddy 自己的,标题为 CodeBuddy,不是 OpenFilm 或终端。',
startAgain: '重新开始',
- missing: '这台电脑上尚未安装',
- claudeSetup: '打开一次 Claude 应用的 Code 标签页即可安装 Claude Code',
+ available: "已发现连接组件,可连接",
+ helpTitle: "{name} 连接说明",
+ helpFor: "{name} 的连接帮助",
+ helpConnect: "如何连接",
+ helpFound: "本机已找到 {name} 的连接组件,可在列表中直接连接。",
+ helpDesktopOnly: "已安装 {name} 桌面应用时,仍可能需要补充连接组件。请在列表中点击“安装连接组件”,装好后再连接。",
+ helpBundled: "OpenFilm 会查找 {name} 客户端内置或维护的连接组件。安装或更新客户端后,可点击“刷新检查”。",
+ helpInstall: "先安装 {name} 的连接组件,再回到列表连接。",
+ helpLogin: "提示登录时,在对应客户端或登录窗口完成登录,然后回到 OpenFilm。",
+ helpRefresh: "更换模型或添加凭据后,点击“刷新检查”。模型能否使用,以接下来的实际消息回复为准。",
+ helpMissingTitle: "检测不到怎么办",
+ helpMissingBody: "如果安装在自定义位置,点击“手动选择安装文件夹…”,选择 {name} 的安装文件夹,OpenFilm 会在其中查找连接组件。",
+ helpDesktop: "只检测到桌面编辑器,并不代表连接组件已就绪。如果列表提示需要组件,请使用“安装连接组件”。",
+ helpCheckTitle: "本机检测",
+ helpOfficial: "官方页面",
+ helpDone: "知道了",
+ refreshCheck: '刷新检查',
+ installComponent: "安装连接组件",
+ openClaude: "打开 Claude",
+ signInConnect: "登录并连接",
+ locateFolder: "手动选择安装文件夹…",
+ folderNoAgent: "所选文件夹中未找到 {name} 的连接组件。请确认安装位置;仅安装桌面编辑器时,需要先安装连接组件。",
+ locateFolderTitle: "选择 {name} 的安装文件夹",
+ programReady: "连接程序已就绪",
+ appNeedsComponent: "已找到 {name} 桌面应用。这个版本还需要独立的连接组件,请使用“安装连接组件”,或选择连接组件所在的安装文件夹。",
+ moreFor: "{name} 的更多操作",
+ quotaReached: "当前模型额度已用完",
+ modelCredentials: "当前模型需要配置凭据",
+ resolveIssue: "查看解决方法",
+ quotaHelp: "在对话底部的模型选择器中更换可用模型,或在 {name} 中检查用量。配置完成后重试消息。",
+ credentialsHelp: "在 {name} 的模型设置中为当前提供商配置凭据,或在对话中选择已配置的模型,然后重试消息。",
+ connectionNote: "连接检查程序和登录状态;模型能否使用,以实际回复为准。",
+ programLocation: "正在使用的连接程序:",
+ recheck: "重新检测",
+ technicalDetails: "技术详情",
+ missing: "尚未找到连接组件",
+ claudeSetup: "打开 Claude 的 Code 页面,完成连接组件初始化。",
locate: '手动选择…',
- locateTitle: '选择 {name} 程序',
+ locateTitle: "选择 {name} 的应用或连接程序",
locateButton: '使用这个',
- chosenAt: '正在使用你选择的程序:{path}',
+ chosenAt: "手动指定的安装位置:{path}",
automatic: '改回自动检测',
notAProgram: '这不是这台电脑能启动的程序。请选择智能体程序本身(Windows 上是 .exe 或 .cmd 文件)。',
- appOnly: '已安装 {app} 应用,但连接需要 {name} 的命令行智能体。',
- installing: '正在终端窗口中安装… 装好后 OpenFilm 会找到它。',
- installConfirm: 'OpenFilm 会打开一个终端窗口,运行 {name} 的官方安装命令:',
+ appOnly: "已发现 {app} 桌面应用,需要补充连接组件。",
+ installing: "正在安装连接组件…完成后会自动检测。",
+ installConfirm: "将运行 {name} 的官方安装命令,补充连接组件:",
installRun: '运行安装',
notTheAgentApp: '这是编辑器或桌面应用,不是 {name} 的命令行智能体。连接需要 {name} 的命令行智能体。',
notCursorAgent: '这不是 Cursor 的命令行智能体(它安装在 cursor-agent 文件夹里)。连接需要 Cursor 的命令行智能体。',
@@ -1747,10 +1782,10 @@ export const zhCN: Words = {
unreadable: '它读不了自己的设置,所以无法启动。请修改它的配置文件里提到的那一项,或更新它:',
whyMissing: '为什么检测不到?',
searching: '正在查找…',
- hintChosenMissing: '你选择的程序已经不在了。重新选择,或改回自动检测。',
+ hintChosenMissing: "你选择的安装位置或其中的连接程序已经不在了。重新选择,或改回自动检测。",
hintWsl: '它装在 WSL(Windows 里的 Linux)中,OpenFilm 用不了。请在 Windows 里也装一份,然后回到这里。',
- hintUnusable: '找到了同名文件,但都无法启动。请用“手动选择…”选中程序本身。',
- hintNone: '在查找过的文件夹里都没有找到。如果 {program} 在你的终端里能用,在终端里查出它的位置(Windows 用“where {program}”,Mac 用“which {program}”),再用“手动选择…”选中那个文件。',
+ hintUnusable: "找到了同名文件,但都无法启动。请重新选择连接组件的安装文件夹。",
+ hintNone: "在查找过的位置没有找到连接组件。请手动选择它的安装文件夹;如果尚未安装,请先安装连接组件。",
hintFound: '已找到:{path}',
reportNote: '如果还是检测不到,复制诊断信息,附在 issue 里发给我们。里面有这台电脑上的文件夹路径。',
copyReport: '复制诊断信息',
diff --git a/packages/openfilm/studio/ui/src/lib/agent-row.test.ts b/packages/openfilm/studio/ui/src/lib/agent-row.test.ts
index b557a29..aa068c3 100644
--- a/packages/openfilm/studio/ui/src/lib/agent-row.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/agent-row.test.ts
@@ -10,8 +10,8 @@ test('an agent not found offers Locate and its installer, or its install page',
assert.deepEqual(missingActions({ installer: 'x', install: 'https://example.test' }, { locate: false, install: false }), { locate: false, install: 'page' });
});
-test("Claude Code waiting in the Claude app offers no Install or Locate: opening the app's Code tab downloads it", () => {
- assert.deepEqual(missingActions({ setupRequired: 'code-tab', install: 'https://example.test' }, { locate: true, install: true }), { locate: false, install: null });
+test("Claude Code setup avoids reinstalling the app and still lets an existing CLI be selected", () => {
+ assert.deepEqual(missingActions({ setupRequired: 'code-tab', install: 'https://example.test' }, { locate: true, install: true }), { locate: true, install: null });
});
test("an account's organization is named unless it only repeats the email, as a personal Claude account's does", () => {
diff --git a/packages/openfilm/studio/ui/src/lib/agent-row.ts b/packages/openfilm/studio/ui/src/lib/agent-row.ts
index 8956741..492a2b9 100644
--- a/packages/openfilm/studio/ui/src/lib/agent-row.ts
+++ b/packages/openfilm/studio/ui/src/lib/agent-row.ts
@@ -3,10 +3,10 @@ import type { HostAgent } from '@/lib/host';
/**
* What Settings › Agents offers for an agent that is not found: Locate (the program is somewhere else), and Install,
* either its official installer run here (`run`) or its install page (`page`). Claude Code waiting in the Claude app
- * gets neither: the app downloads it once its Code tab is opened, as the row says.
+ * gets no installer: the app downloads it once its Code tab is opened. An existing CLI can still be selected.
*/
export function missingActions(agent: Pick<HostAgent, 'setupRequired' | 'install' | 'installer'>, host: { locate: boolean; install: boolean }) {
- if (agent.setupRequired === 'code-tab') return { locate: false, install: null };
+ if (agent.setupRequired === 'code-tab') return { locate: host.locate, install: null };
const install: 'run' | 'page' | null = agent.installer && host.install ? 'run' : agent.install ? 'page' : null;
return { locate: host.locate, install };
}
diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.ts
index d417d68..397ac78 100644
--- a/packages/openfilm/studio/ui/src/lib/host.ts
+++ b/packages/openfilm/studio/ui/src/lib/host.ts
@@ -90,6 +90,8 @@ export interface StudioHost {
*/
agents?: {
list: () => Promise<HostAgent[]>;
+ /** Explicitly reload local configuration and idle sessions; no model prompt is sent. */
+ refresh?: () => Promise<HostAgent[]>;
connect: (id: HostAgentId) => Promise<{ ok: boolean; error?: string }>;
/** Stop waiting for terminal sign-in without disconnecting the agent or changing its own sign-in. */
cancelSignIn?: (id: HostAgentId) => Promise<unknown>;
@@ -99,10 +101,12 @@ 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' | 'app' | 'not-cursor-agent' | string }>;
+ locate?: (id: HostAgentId, words?: { title?: string; button?: string; kind?: 'file' | 'folder' }) => Promise<{ ok: boolean; error?: string; path?: string; version?: 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>;
+ /** Open the installed desktop app to complete its Code component setup. */
+ openSetup?: (id: HostAgentId) => Promise<{ ok: boolean; error?: string }>;
/** The app's part of Settings → Developer's diagnostic report: the app, and each agent's program, version and state, as text. */
report?: () => Promise<string>;
/**
@@ -228,7 +232,7 @@ export type HostByokFormat = 'responses' | 'chat' | 'anthropic';
/**
* One agent as the app has it. `status`: ready · off (disconnected in the app; its own sign-in is kept) · sign-in (its
- * own sign-in is needed) · waiting (signing in, in Terminal) · missing (not installed: `install` says where from) ·
+ * own sign-in is needed) · waiting (signing in, in Terminal) · missing (connection component not found) ·
* key (no key set up) · unavailable (not offered yet) · checking. `account`: whose sign-in it uses, as the program says
* (no key or token).
*/
@@ -240,7 +244,7 @@ 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. */
+ /** The desktop app when only that is here (`Cursor`), and the official command that installs the connection component. */
app?: string | null;
installer?: string | null;
/** Its installer is running in a terminal window: it is looked for again until it is there. */
@@ -248,7 +252,11 @@ export interface HostAgent {
/** 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;
+ /** Changes when configuration is explicitly refreshed, so model menus discard older probes. */
+ configurationRevision?: number;
error?: string;
+ /** Last actionable model failure; finding a program or opening a protocol session does not clear it. */
+ connectionIssue?: { kind: 'quota' | 'credentials'; message: string };
/** Found, but it cannot read its own settings (Codex's config file), as it says: no session starts until fixed. */
problem?: string;
account?: HostAgentAccount;