Skip to content

The agent that grows with you

fix(desktop): probe a launcher's install root off the main thread

Tekniumecbd3bb69c25
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 7a289dbca93..7736c8f476b 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -5103,7 +5103,7 @@ async function resolveHermesBackend(backendArgs: string[]): Promise<ResolvedHerm
env: {},
kind: 'command',
shell: shellForProbe,
- local: 'installed', root: launcherInstallRoot(hermesCommand) // ticket minting needs it (#138774)
+ local: 'installed', root: await launcherInstallRoot(hermesCommand) // ticket minting needs it (#138774)
}
}
diff --git a/apps/desktop/electron/updater-process.test.ts b/apps/desktop/electron/updater-process.test.ts
index 8018b6c3405..e60a97b4468 100644
--- a/apps/desktop/electron/updater-process.test.ts
+++ b/apps/desktop/electron/updater-process.test.ts
@@ -4,11 +4,12 @@ import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
-import { test } from 'vitest'
+import { test, vi } from 'vitest'
import {
collectRelaunchArgs,
describeUpdaterHandoffFailure,
+ LAUNCHER_ROOT_MISS_TTL_MS,
launcherInstallDirectory,
launcherInstallRoot,
MARKER_SELF_ADOPT_EPOCH_MS,
@@ -500,18 +501,50 @@ test.skipIf(process.platform === 'win32')('launcherInstallDirectory stays null w
}
})
-// A failed probe (timeout, a launcher mid-replacement) must not stick: the ticket resolver retries
-// after a failure, and a cached miss would keep the override rootless until Desktop restarts.
-test.skipIf(process.platform === 'win32')('launcherInstallRoot retries a failed probe and caches the root it then reports', async () => {
+// The backend resolver runs on Electron's main thread, pool resolves included (every tick of
+// reensureDuringRestart): the `--version` probe must not block it, and a launcher that never
+// names its root must not pay a fresh spawn on each resolve.
+test.skipIf(process.platform === 'win32')('launcherInstallRoot probes off the main thread, once for concurrent callers', async () => {
const dir = await realpathMkdtemp('launcher-root-')
const reported = await fs.realpath(await fs.mkdir(path.join(dir, 'hermes-agent')).then(() => path.join(dir, 'hermes-agent')))
- const launcher = await writeLauncher(dir, 'exit 3')
+ const calls = path.join(dir, 'calls')
+ const launcher = await writeLauncher(dir, `echo x >> ${calls}; sleep 0.4; printf 'Install directory: ${reported}\\n'`)
+ let ticked = false
+ const timer = setTimeout(() => { ticked = true }, 50)
+
+ const first = launcherInstallRoot(launcher)
+ const second = launcherInstallRoot(launcher)
+
+ assert.ok(first instanceof Promise, 'the probe must not run synchronously on the caller')
+ assert.deepEqual(await Promise.all([first, second]), [reported, reported])
+ clearTimeout(timer)
+ assert.equal(ticked, true, 'the event loop kept running while the launcher probed')
+ assert.equal((await fs.readFile(calls, 'utf8')).trim().split('\n').length, 1)
+})
- assert.equal(launcherInstallRoot(launcher), undefined)
- await writeLauncher(dir, `printf 'Hermes Agent v0.22.1\\nInstall directory: ${reported}\\n'`)
- assert.equal(launcherInstallRoot(launcher), reported)
- await writeLauncher(dir, 'exit 3')
- assert.equal(launcherInstallRoot(launcher), reported)
+// A miss is cached briefly, not forever: the ticket resolver retries after a failure, and a
+// permanent miss would keep the override rootless until Desktop restarts.
+test.skipIf(process.platform === 'win32')('launcherInstallRoot caches a miss for a short window, then retries and keeps the root', async () => {
+ const dir = await realpathMkdtemp('launcher-root-')
+ const reported = await fs.realpath(await fs.mkdir(path.join(dir, 'hermes-agent')).then(() => path.join(dir, 'hermes-agent')))
+ const calls = path.join(dir, 'calls')
+ const launcher = await writeLauncher(dir, `echo x >> ${calls}; printf 'Hermes Agent v0.22.1\\n'`)
+ const count = async () => (await fs.readFile(calls, 'utf8')).trim().split('\n').length
+ const now = vi.spyOn(Date, 'now')
+
+ try {
+ now.mockReturnValue(1_000_000)
+ assert.equal(await launcherInstallRoot(launcher), undefined)
+ assert.equal(await launcherInstallRoot(launcher), undefined)
+ assert.equal(await count(), 1, 'a miss inside the window does not spawn again')
+
+ await writeLauncher(dir, `echo x >> ${calls}; printf 'Install directory: ${reported}\\n'`)
+ now.mockReturnValue(1_000_000 + LAUNCHER_ROOT_MISS_TTL_MS + 1)
+ assert.equal(await launcherInstallRoot(launcher), reported)
+ await writeLauncher(dir, 'exit 3')
+ assert.equal(await launcherInstallRoot(launcher), reported)
+ assert.equal(await count(), 2)
+ } finally { now.mockRestore() }
})
async function realpathMkdtemp(prefix: string): Promise<string> {
diff --git a/apps/desktop/electron/updater-process.ts b/apps/desktop/electron/updater-process.ts
index a7f05cd0408..e744e89471a 100644
--- a/apps/desktop/electron/updater-process.ts
+++ b/apps/desktop/electron/updater-process.ts
@@ -1,4 +1,13 @@
-import { execFileSync, spawn, type SpawnOptions, spawnSync, type SpawnSyncReturns } from 'node:child_process'
+import {
+ execFile,
+ type ExecFileOptions,
+ execFileSync,
+ spawn,
+ type SpawnOptions,
+ spawnSync,
+ type SpawnSyncOptions,
+ type SpawnSyncReturns
+} from 'node:child_process'
import { existsSync, realpathSync, statSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
@@ -113,62 +122,114 @@ export function launcherTargetsInstallation(launcher: string, root: string): boo
}
// A launcher's install directory cannot move while this process lives, and the
-// backend resolver runs once per surface (startup, TUI resume, pool backends),
-// so the HERMES_DESKTOP_HERMES rung memoizes each launcher's root. Only a root is
-// cached: a failed or timed-out probe is retried on the next call, matching the
-// ticket resolver's own retry after a failure.
-const launcherInstallRoots = new Map<string, string>()
+// backend resolver runs once per surface (startup, TUI resume, pool backends, and
+// every tick of reensureDuringRestart), so the HERMES_DESKTOP_HERMES rung memoizes
+// each launcher's root. The probe is async: `--version` may take seconds (it also
+// runs the passive update check) and must never stall Electron's main thread.
+// Concurrent resolves share one in-flight probe. A miss (no `Install directory:`
+// line, a timeout, a launcher mid-replacement) is cached only briefly, so it is
+// neither permanent nor re-spawned on every resolve.
+export const LAUNCHER_ROOT_MISS_TTL_MS = 60_000
+const launcherInstallRoots = new Map<string, Promise<string | undefined>>()
+const launcherRootMisses = new Map<string, number>()
/** The root a launcher reports, memoized: ticketRuntimeFor() mints gateway
* tickets from a command backend only when it names its installation root. */
-export function launcherInstallRoot(launcher: string): string | undefined {
+export function launcherInstallRoot(launcher: string): Promise<string | undefined> {
+ const missedAt = launcherRootMisses.get(launcher)
+
+ if (missedAt !== undefined && Date.now() - missedAt < LAUNCHER_ROOT_MISS_TTL_MS) {
+ return Promise.resolve(undefined)
+ }
+
const cached = launcherInstallRoots.get(launcher)
- if (cached !== undefined) {return cached}
- const root = launcherInstallDirectory(launcher) ?? undefined
+ if (cached) {return cached}
+ const flight = launcherInstallDirectoryAsync(launcher).then(root => {
+ if (root === null) {
+ launcherInstallRoots.delete(launcher)
+ launcherRootMisses.set(launcher, Date.now())
+
+ return undefined
+ }
+
+ launcherRootMisses.delete(launcher)
+
+ return root
+ })
- if (root !== undefined) {launcherInstallRoots.set(launcher, root)}
+ launcherInstallRoots.set(launcher, flight)
- return root
+ return flight
}
-/** The real install directory a launcher's `--version` reports, or null. */
-export function launcherInstallDirectory(launcher: string, root?: string): string | null {
- try {
- // Node refuses to exec a .cmd directly (CVE-2024-27980), and `shell:true`
- // would hand an interpolated path to cmd.exe wholesale. Invoke cmd.exe
- // explicitly instead: a fixed argv, the path quoted verbatim and screened
- // for cmd metacharacters, and nothing else for the shell to interpret.
- const viaCmd: boolean = process.platform === 'win32' && /\.cmd$/i.test(launcher)
-
- if (viaCmd && CMD_UNSAFE_PATH.test(launcher)) {
- return null
- }
+interface LauncherVersionProbe { command: string; args: string[]; options: SpawnSyncOptions }
+
+// Node refuses to exec a .cmd directly (CVE-2024-27980), and `shell:true`
+// would hand an interpolated path to cmd.exe wholesale. Invoke cmd.exe
+// explicitly instead: a fixed argv, the path quoted verbatim and screened
+// for cmd metacharacters, and nothing else for the shell to interpret.
+function launcherVersionProbe(launcher: string, root?: string): LauncherVersionProbe | null {
+ const viaCmd: boolean = process.platform === 'win32' && /\.cmd$/i.test(launcher)
- const command: string = viaCmd ? (process.env.ComSpec ?? 'cmd.exe') : launcher
- const args: string[] = viaCmd ? ['/d', '/s', '/c', `""${launcher}" --version"`] : ['--version']
+ if (viaCmd && CMD_UNSAFE_PATH.test(launcher)) {
+ return null
+ }
- const probe: SpawnSyncReturns<string> = spawnSync(command, args, {
+ return {
+ command: viaCmd ? (process.env.ComSpec ?? 'cmd.exe') : launcher,
+ args: viaCmd ? ['/d', '/s', '/c', `""${launcher}" --version"`] : ['--version'],
+ options: {
cwd: root,
- encoding: 'utf8',
timeout: 15000,
windowsHide: true,
windowsVerbatimArguments: viaCmd,
env: root ? { ...process.env, HERMES_INSTALL_ROOT: root } : process.env
- })
-
- if (probe.error || probe.status !== 0) {
- return null
}
+ }
+}
+
+function reportedInstallDirectory(stdout: string): string | null {
+ const reported: string | undefined = /^Install directory: (.+)$/m.exec(stdout)?.[1]?.trim()
- const reported: string | undefined = /^Install directory: (.+)$/m.exec(probe.stdout)?.[1]?.trim()
+ return reported ? realpathSync(reported) : null
+}
- return reported ? realpathSync(reported) : null
+/** The real install directory a launcher's `--version` reports, or null. */
+export function launcherInstallDirectory(launcher: string, root?: string): string | null {
+ try {
+ const probe: LauncherVersionProbe | null = launcherVersionProbe(launcher, root)
+
+ if (!probe) {return null}
+ const result: SpawnSyncReturns<string> = spawnSync(probe.command, probe.args, { ...probe.options, encoding: 'utf8' })
+
+ return result.error || result.status !== 0 ? null : reportedInstallDirectory(result.stdout)
} catch {
return null
}
}
+/** launcherInstallDirectory without blocking the caller's event loop. */
+function launcherInstallDirectoryAsync(launcher: string): Promise<string | null> {
+ const probe: LauncherVersionProbe | null = launcherVersionProbe(launcher)
+
+ if (!probe) {return Promise.resolve(null)}
+
+ return new Promise(resolve => {
+ try {
+ execFile(probe.command, probe.args, { ...probe.options, encoding: 'utf8' } as ExecFileOptions, (error, stdout) => {
+ try {
+ resolve(error ? null : reportedInstallDirectory(String(stdout)))
+ } catch {
+ resolve(null)
+ }
+ })
+ } catch {
+ resolve(null)
+ }
+ })
+}
+
/** File prerequisites only: dependency recovery remains reachable through update. */
export function windowsUpdatePrerequisiteError(updateRoot: string, hermesHome?: string): string | null {
if (!resolveInstallationLauncher(updateRoot, true, hermesHome)) {