The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Desktop: on Windows, the apps the registry lists are read in the background, so looking at the agents does not hold the windows (#281)
WEBGRS74b5c06cedb7
diff --git a/.changeset/installed-apps-in-background.md b/.changeset/installed-apps-in-background.mdnew file mode 100644index 0000000..4225e10--- /dev/null+++ b/.changeset/installed-apps-in-background.md@@ -0,0 +1,5 @@+---+"@openfilm/desktop": patch+---++On Windows, opening Settings or the chat's agent menu no longer holds the app for a second or two each time: the apps Windows has registered are read in the background, and the last reading is used meanwhile.diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjsindex 16b8cc3..3a55e3a 100644--- a/apps/desktop/src/agents.mjs+++ b/apps/desktop/src/agents.mjs@@ -38,6 +38,7 @@ import * as acp from '@agentclientprotocol/sdk';import { PATH_SEP, childEnvironment, lastPathSource, loginShellEnvironment, loginShellVariables, shellSubset } from './environment.mjs';import { AGENT_PROGRAMS, HOME_BIN_CANDIDATES, chosenProgram, claudeUpdate, claudeVersion, codexAppCopies, codexVersion, desktopApp, detectAgentInstallation, installCommand, laterVersion, notTheAgent, searchReport } from './agent-installation.mjs';import { logSwitches } from './agent-logs.mjs';+import { afterFirstReading, firstWindowsApps, refreshWindowsApps } from './windows-apps.mjs';import { mergeConfig, sessionSkills } from './agent-skills.mjs';import { nodeBinary } from './node-runtime.mjs';import { outOfBalance } from './pi-config.mjs';@@ -240,6 +241,16 @@ function windowsSlowSearch({ fresh = false } = {}) {return value;}+/**+ * The slower search and the apps Windows has registered, waited for three seconds at most: what comes later is there on+ * the next look. The first reading of the registrations is waited for however long it takes (it holds nothing): the+ * chat asks for the agents once as it loads, and one known only from its registration would stay not installed there.+ */+const windowsSlowerLook = () => Promise.all([+ firstWindowsApps(),+ Promise.race([Promise.all([windowsSlowSearch(), refreshWindowsApps()]), new Promise((done) => setTimeout(done, 3000).unref?.())]),+]);+/** Where this agent was looked for, beyond the PATH. */const searchDirs = () => [...HOME_BIN_CANDIDATES(), ...(slowFound.npmPrefix ? [slowFound.npmPrefix] : [])];@@ -257,6 +268,9 @@ export function resolveAgentCli(id, { pathDirs = [] } = {}) {return found.cli ? { path: found.cli, source: found.source } : null;}+/** resolveAgentCli, for starting, signing in or out: right after launch, it waits for Windows' registrations when the program is not found without them. */+const findAgentCli = (id, options) => afterFirstReading(() => resolveAgentCli(id, options));+function run(cmd, args, timeoutMs = 10_000, { cwd, env, options } = {}) {return new Promise((resolve) => {try {@@ -336,7 +350,7 @@ export async function diagnoseAgent(id, { appVersion = '' } = {}) {const spec = AGENTS[id];if (!spec) return null;const shell = await loginShellEnvironment({ maxAgeMs: 0 });- const slow = await windowsSlowSearch({ fresh: true });+ const [slow] = await Promise.all([windowsSlowSearch({ fresh: true }), refreshWindowsApps({ maxAge: 0 })]);const pathDirs = shell.PATH.split(PATH_SEP);const found = resolveAgentCli(id, { pathDirs });const names = AGENT_PROGRAMS[id]?.names ?? [id];@@ -562,7 +576,7 @@ export async function agentSignInMethods(id) {const spec = AGENTS[id];if (!spec?.acpSignIn) return [];const shell = agentShell(id, await loginShellVariables());- const cli = resolveAgentCli(id, { pathDirs: shell.PATH.split(PATH_SEP) });+ const cli = await findAgentCli(id, { pathDirs: shell.PATH.split(PATH_SEP) });if (!cli) return [];const launch = adapterLaunch(id, cli.path);const child = spawn(launch.cmd, launch.args, { ...OWN_GROUP, env: childEnvironment({ shell, extra: launch.env }), stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });@@ -599,7 +613,7 @@ const SIGN_IN_DIR = () => join(tmpdir(), 'openfilm-sign-in');export async function openAgentSignIn(id, { track = false } = {}) {const spec = AGENTS[id];const pathDirs = (await loginShellEnvironment()).PATH.split(PATH_SEP);- const cli = spec ? resolveAgentCli(id, { pathDirs }) : null;+ const cli = spec ? await findAgentCli(id, { pathDirs }) : null;if (!spec || !cli) return { ok: false, error: `${spec?.label ?? id} is not installed on this computer.` };if (spec.login === null) return { ok: false, error: `Sign in in ${spec.label} itself.` };asked.delete(id);@@ -651,7 +665,7 @@ export async function openAgentSignIn(id, { track = false } = {}) {export async function signOutAgent(id) {const spec = AGENTS[id];if (!spec?.logout) return { ok: false, error: `${spec?.label ?? id} has no sign-out command: switch accounts in ${spec?.label ?? id} itself.` };- const cli = resolveAgentCli(id, { pathDirs: (await loginShellEnvironment()).PATH.split(PATH_SEP) });+ const cli = await findAgentCli(id, { pathDirs: (await loginShellEnvironment()).PATH.split(PATH_SEP) });if (!cli) return { ok: false, error: `${spec.label} is not installed on this computer.` };const shell = agentShell(id, await loginShellVariables());const how = starting(cli.path, spec.logout);@@ -696,7 +710,7 @@ export async function listAgents({ ids = Object.keys(AGENTS), statusIds = ids, f// 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?.())]);+ await windowsSlowerLook();}const agent = await agentOnComputer(id, pathDirs, { fresh, checkSignIn });onAgent(agent);@@ -709,7 +723,7 @@ export async function localAgent(id, { fresh = false } = {}) {if (!isAgentId(id)) throw new Error(`No agent ${id}`);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?.())]);+ await windowsSlowerLook();}return agentOnComputer(id, pathDirs, { fresh });}@@ -1176,7 +1190,7 @@ export class AgentSession {this.step = 'start';const shell = agentShell(this.opts.agent, await loginShellVariables({ staleOk: true }));const harness = this.opts.harness ?? null;- const cli = harness ? null : resolveAgentCli(this.opts.agent, { pathDirs: shell.PATH.split(PATH_SEP) });+ const cli = harness ? null : await findAgentCli(this.opts.agent, { pathDirs: shell.PATH.split(PATH_SEP) });if (!harness && !cli) throw Object.assign(new Error(`${this.spec.label} is not installed on this computer.`), { code: 'not-installed' });this.cli = cli;/* one whose ACP sign-in takes up its own (Cursor's `authenticate`) opens the maker's sign-in page in the browser anddiff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjsindex 3fc3081..190008d 100644--- a/apps/desktop/src/main.mjs+++ b/apps/desktop/src/main.mjs@@ -34,6 +34,7 @@ import { startUpdates } from './updates.mjs';import { stepAside } from './update-launch.mjs';import { ensureFfmpeg, ffmpegDir, ffmpegDownloadable, ffmpegIn, ffmpegOnPath } from './ffmpeg-runtime.mjs';import { PATH_SEP } from './environment.mjs';+import { firstWindowsApps } from './windows-apps.mjs';import { createTabs } from './tabs.mjs';const here = (path) => fileURLToPath(new URL(path, import.meta.url));@@ -450,6 +451,8 @@ async function start() {/* an update quitting did not install is installed now, before anything else opens (update-launch.mjs) */const launch = await updates.installAtLaunch({ language: state.language });if (launch.installing) return;+ /* Windows' registered apps, read from now on: the first look at the agents and a conversation reopened at once wait for them */+ if (windows) void firstWindowsApps();const shellEnv = await loginShellEnvironment();const env = childEnvironment({diff --git a/apps/desktop/src/windows-apps.mjs b/apps/desktop/src/windows-apps.mjsindex 33aa962..37e0821 100644--- a/apps/desktop/src/windows-apps.mjs+++ b/apps/desktop/src/windows-apps.mjs@@ -1,5 +1,5 @@/** Windows' installed desktop apps, including user-selected folders outside Programs. */-import { execFileSync } from 'node:child_process';+import { execFile } 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. */@@ -26,27 +26,73 @@ export function parseWindowsApps(text, env = process.env) {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 UNINSTALL_KEYS = [+ 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',+ 'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',+ 'HKLM\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall',+];++/** One uninstall key with its subkeys (`reg query /s`), or null when it is missing, unreadable or too slow. */+function queryKey(key) {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;+ return new Promise((resolve) => {+ // Chinese Windows uses GBK by default; read paths in UTF-8, as environment.mjs does.+ execFile(join(system, 'cmd.exe'), ['/d', '/s', '/c', `chcp 65001 >nul && "${join(system, 'reg.exe')}" query "${key}" /s`], {+ encoding: 'utf8', timeout: 15_000, maxBuffer: 8 * 1024 * 1024, windowsHide: true, windowsVerbatimArguments: true,+ }, (error, stdout) => resolve(error ? null : stdout));+ });+}++/**+ * The registrations, read in the background. Reading all three keys takes a second or more on a computer with many+ * apps, and the agents' status is looked at on the main process each time Settings or the chat's menu opens: read+ * synchronously there, it held every window (Windows called them "Not Responding"). `installed()` answers at once+ * with what was read last, and has them read again when that is older than `maxAgeMs`; `refresh()` is for a caller+ * that waits for them (the first look, a diagnosis). One reading at a time.+ */+export function windowsAppsReader({ query = queryKey, platform = process.platform, env = process.env, now = Date.now, maxAgeMs = 10_000 } = {}) {+ let read = { at: -Infinity, apps: [] };+ let reading = null;+ const refresh = ({ maxAge = maxAgeMs } = {}) => {+ if (platform !== 'win32') return Promise.resolve([]);+ if (now() - read.at < maxAge) return Promise.resolve(read.apps);+ reading ??= Promise.all(UNINSTALL_KEYS.map((key) => new Promise((done) => done(query(key))).catch(() => null)))+ .then((texts) => {+ read = { at: now(), apps: texts.flatMap((text) => (typeof text === 'string' ? parseWindowsApps(text, env) : [])) };+ return read.apps;+ })+ .finally(() => { reading = null; });+ return reading;+ };+ const installed = () => {+ if (platform !== 'win32') return [];+ void refresh();+ return read.apps;+ };+ /* the first reading, waited for however long it takes; at once after that, however old the last one is */+ const first = () => refresh({ maxAge: Infinity });+ /* off Windows there is nothing to read */+ const wasRead = () => platform !== 'win32' || read.at > -Infinity;+ return { installed, refresh, first, wasRead };+}++const reader = windowsAppsReader();+/** What was read last, at once; registration alone does not prove the folder still exists. */+export const installedWindowsApps = () => reader.installed();+/** Read again unless read within `maxAge` ms, and wait for it. */+export const refreshWindowsApps = (options) => reader.refresh(options);+/** The first reading, waited for; started at launch (main.mjs), it is often in before anything asks. */+export const firstWindowsApps = () => reader.first();++/**+ * `find()`, and once more when the first reading comes in if it found nothing before it. Until then a program known+ * only from its registration (DeepSeek Harness on D:\) is not found: a conversation reopened right after launch would+ * say it is not installed.+ * @template T @param {() => T} find @param {{ reader?: ReturnType<typeof windowsAppsReader> }} [o] @returns {Promise<T>}+ */+export async function afterFirstReading(find, { reader: apps = reader } = {}) {+ const found = find();+ if (found || apps.wasRead()) return found;+ await apps.first();+ return find();}diff --git a/apps/desktop/src/windows-apps.test.mjs b/apps/desktop/src/windows-apps.test.mjsindex 6423650..1fe06c2 100644--- a/apps/desktop/src/windows-apps.test.mjs+++ b/apps/desktop/src/windows-apps.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { parseWindowsApps } from './windows-apps.mjs';+import { afterFirstReading, parseWindowsApps, windowsAppsReader } from './windows-apps.mjs';test('Windows app registrations retain custom folders, quoted paths, spaces and non-ASCII names', () => {const apps = parseWindowsApps(String.raw`@@ -37,3 +37,101 @@ HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\nameless`, { LocalAppData: String.raw`D:\Local` });assert.deepEqual(apps, [{ name: 'GitHub Copilot', directories: [String.raw`D:\Local\Programs\GitHub Copilot`] }]);});++const REGISTERED = (name, dir) => `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\${name}\n DisplayName REG_SZ ${name}\n InstallLocation REG_SZ ${dir}\n`;+/** A reg query whose answers the test gives: each key's call waits until `answer()` */+function slowRegistry(texts) {+ const calls = [];+ let release;+ let gate = new Promise((done) => { release = done; });+ const query = (key) => { calls.push(key); return gate.then(() => texts[calls.length % texts.length] ?? texts[0]); };+ return { calls, query, answer: () => { release(); gate = new Promise((done) => { release = done; }); } };+}++test('the registrations are read in the background: the look answers at once, with what was read last', async () => {+ const registry = slowRegistry([REGISTERED('DeepSeek Harness', String.raw`D:\Apps\DeepSeek Harness`)]);+ const reader = windowsAppsReader({ query: registry.query, platform: 'win32', env: {} });+ assert.deepEqual(reader.installed(), [], 'nothing read yet, and nothing waited for');+ assert.equal(registry.calls.length, 3, 'the three uninstall keys');+ assert.deepEqual(reader.installed(), [], 'still reading: not asked again');+ assert.equal(registry.calls.length, 3);+ registry.answer();+ const apps = await reader.refresh();+ assert.equal(apps.length, 3);+ assert.deepEqual(reader.installed()[0], { name: 'DeepSeek Harness', directories: [String.raw`D:\Apps\DeepSeek Harness`] });+});++test('registrations older than their age are read again while the old ones are still answered', async () => {+ let clock = 0;+ const texts = { now: REGISTERED('OpenCode', String.raw`D:\Old`) };+ const reader = windowsAppsReader({ query: async () => texts.now, platform: 'win32', env: {}, now: () => clock, maxAgeMs: 10_000 });+ await reader.refresh();+ texts.now = REGISTERED('OpenCode', String.raw`D:\New`);+ clock = 5_000;+ assert.equal(reader.installed()[0].directories[0], String.raw`D:\Old`, 'young enough: kept');+ clock = 11_000;+ assert.equal(reader.installed()[0].directories[0], String.raw`D:\Old`, 'too old: answered, and read again behind it');+ await reader.refresh({ maxAge: 10_000 });+ assert.equal(reader.installed()[0].directories[0], String.raw`D:\New`);+ clock = 12_000;+ await reader.refresh({ maxAge: 0 });+ assert.equal(reader.installed()[0].directories[0], String.raw`D:\New`, 'read at once when asked to');+});++test('a key that is missing, unreadable or too slow leaves out only its own apps', async () => {+ const reader = windowsAppsReader({+ platform: 'win32', env: {},+ query: async (key) => (key.startsWith('HKCU') ? REGISTERED('Kimi Code', String.raw`D:\Kimi`) : key.includes('WOW6432Node') ? null : Promise.reject(new Error('Access is denied'))),+ });+ assert.deepEqual(await reader.refresh(), [{ name: 'Kimi Code', directories: [String.raw`D:\Kimi`] }]);+});++test('only Windows has the registrations read', async () => {+ let asked = 0;+ const reader = windowsAppsReader({ query: async () => { asked += 1; return ''; }, platform: 'darwin' });+ assert.deepEqual(reader.installed(), []);+ assert.deepEqual(await reader.refresh(), []);+ assert.equal(asked, 0);+});++test('the first reading is waited for however long it takes, and only that one', async () => {+ let clock = 0;+ const registry = slowRegistry([REGISTERED('DeepSeek Harness', String.raw`D:\Apps\DeepSeek Harness`)]);+ const reader = windowsAppsReader({ query: registry.query, platform: 'win32', env: {}, now: () => clock });+ assert.equal(reader.wasRead(), false);+ let done = false;+ const first = reader.first().then((apps) => { done = true; return apps; });+ await new Promise((settle) => setTimeout(settle, 20));+ assert.equal(done, false, 'still reading: waited for, with no cap');+ registry.answer();+ assert.equal((await first).length, 3);+ assert.equal(reader.wasRead(), true);+ clock = 60_000;+ const calls = registry.calls.length;+ assert.equal((await reader.first()).length, 3, 'read a minute ago: answered at once');+ assert.equal(registry.calls.length, calls, 'and not read again');+});++test('a program not found before the first reading is looked for again once it is in', async () => {+ const registry = slowRegistry([REGISTERED('DeepSeek Harness', String.raw`D:\Apps\DeepSeek Harness`)]);+ const reader = windowsAppsReader({ query: registry.query, platform: 'win32', env: {} });+ let looks = 0;+ const find = () => { looks += 1; return reader.installed().find((app) => app.name === 'DeepSeek Harness') ?? null; };+ const found = afterFirstReading(find, { reader });+ registry.answer();+ assert.equal((await found)?.name, 'DeepSeek Harness');+ assert.equal(looks, 2, 'before the reading, and after it');+ looks = 0;+ assert.equal((await afterFirstReading(find, { reader }))?.name, 'DeepSeek Harness');+ assert.equal(looks, 1, 'found: looked once');+ looks = 0;+ assert.equal(await afterFirstReading(() => { looks += 1; return null; }, { reader }), null);+ assert.equal(looks, 1, 'read already: not found is not found');+});++test('off Windows a program is looked for once', async () => {+ const reader = windowsAppsReader({ query: async () => '', platform: 'darwin' });+ let looks = 0;+ assert.equal(await afterFirstReading(() => { looks += 1; return null; }, { reader }), null);+ assert.equal(looks, 1);+});