The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep runtime discovery off the main event loop
jango5d9f83253f68
diff --git a/apps/desktop/electron/backend-connection-state.ts b/apps/desktop/electron/backend-connection-state.tsindex fdbe6dea263..a9c916f6dc5 100644--- a/apps/desktop/electron/backend-connection-state.ts+++ b/apps/desktop/electron/backend-connection-state.ts@@ -48,6 +48,12 @@ export function createBackendConnectionState<TProcess, TConnection>() {return attempt.generation === generation},+ assertCurrentAttempt(attempt: BackendConnectionAttempt<TConnection>): void {+ if (attempt.generation !== generation) {+ throw new Error('Hermes backend start was superseded by a newer connection attempt.')+ }+ },+attachProcess(attempt: BackendConnectionAttempt<TConnection>,nextProcess: TProcessdiff --git a/apps/desktop/electron/backend-probes.test.ts b/apps/desktop/electron/backend-probes.test.tsindex 2ff97814e61..db743fd6df3 100644--- a/apps/desktop/electron/backend-probes.test.ts+++ b/apps/desktop/electron/backend-probes.test.ts@@ -7,6 +7,7 @@import assert from 'node:assert/strict'import fs from 'node:fs'+import { createServer } from 'node:net'import os from 'node:os'import path from 'node:path'@@ -15,6 +16,7 @@ import { test } from 'vitest'import {canImportHermesCli,DEFAULT_PROBE_TIMEOUT_MS,+ execProbe,hermesRuntimeImportProbe,PROBE_TIMEOUT_MS,resolveProbeTimeoutMs,@@ -29,24 +31,53 @@ import {// (a tiny script we write to disk that exits 0 on --version).const NODE_BIN = process.execPath-test('canImportHermesCli returns false when path is falsy', () => {- assert.equal(canImportHermesCli(''), false)- assert.equal(canImportHermesCli(null), false)- assert.equal(canImportHermesCli(undefined), false)+test('runtime probe lets the parent service IO while its child is running', async () => {+ let accepted = 0++ const server = createServer(socket => {+ accepted += 1+ socket.on('error', () => {})+ socket.end('ready')+ })++ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))+ const address = server.address()+ assert.ok(address && typeof address !== 'string')++ const script = `+ const socket = require('node:net').connect(${address.port}, '127.0.0.1');+ socket.on('data', () => socket.destroy());+ socket.on('error', () => process.exit(1));+ `++ try {+ // A synchronous probe prevents the parent from accepting this connection,+ // so both timeout attempts fail even though the child is healthy (#103786).+ await execProbe(NODE_BIN, ['-e', script], { stdio: 'ignore', timeout: 2000 })+ assert.equal(accepted, 1)+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()))+ }+}, 10_000)++test('canImportHermesCli returns false when path is falsy', async () => {+ assert.equal(await canImportHermesCli(''), false)+ assert.equal(await canImportHermesCli(null), false)+ assert.equal(await canImportHermesCli(undefined), false)})-test('canImportHermesCli returns false when interpreter cannot run -c', () => {+test('canImportHermesCli returns false when interpreter cannot run -c', async () => {// node IS an interpreter, but `node -c "import hermes_cli"` is a// SyntaxError -- different exit reason from a real Python's// ModuleNotFoundError, but the predicate is "exit 0 or not" and// both land on "not", which is exactly what we want for the// resolver fall-through.- assert.equal(canImportHermesCli(NODE_BIN), false)+ assert.equal(await canImportHermesCli(NODE_BIN), false)})-test('canImportHermesCli returns false when binary does not exist', () => {+test('canImportHermesCli returns false when binary does not exist', async () => {const ghost = path.join(os.tmpdir(), 'hermes-probes-ghost-' + Date.now() + '.exe')- assert.equal(canImportHermesCli(ghost), false)+ assert.equal(await canImportHermesCli(ghost), false)})test('hermes runtime import probe checks config dependencies', () => {@@ -68,18 +99,18 @@ test('empty Hermes override is not authoritative', () => {assert.equal(shouldTrustHermesOverride(undefined), false)})-test('verifyHermesCli returns false when command is falsy', () => {- assert.equal(verifyHermesCli(''), false)- assert.equal(verifyHermesCli(null), false)- assert.equal(verifyHermesCli(undefined), false)+test('verifyHermesCli returns false when command is falsy', async () => {+ assert.equal(await verifyHermesCli(''), false)+ assert.equal(await verifyHermesCli(null), false)+ assert.equal(await verifyHermesCli(undefined), false)})-test('verifyHermesCli returns false when binary does not exist', () => {+test('verifyHermesCli returns false when binary does not exist', async () => {const ghost = path.join(os.tmpdir(), 'hermes-probes-ghost-' + Date.now() + '.exe')- assert.equal(verifyHermesCli(ghost), false)+ assert.equal(await verifyHermesCli(ghost), false)})-test('verifyHermesCli returns true when --version exits 0', () => {+test('verifyHermesCli returns true when --version exits 0', async () => {// Write a tiny script that exits 0 regardless of args, then invoke// it through node. This stands in for a working hermes binary --// verifyHermesCli only cares about the exit code.@@ -92,7 +123,7 @@ test('verifyHermesCli returns true when --version exits 0', () => {// execFileSync passes ['--version'] as args, which node ignores// gracefully (well, it prints its version and exits 0, which is// perfect -- exit code 0 is the only signal we read).- assert.equal(verifyHermesCli(NODE_BIN), true)+ assert.equal(await verifyHermesCli(NODE_BIN), true)} finally {try {fs.unlinkSync(scriptPath)@@ -102,13 +133,37 @@ test('verifyHermesCli returns true when --version exits 0', () => {}})-test('verifyHermesCli swallows timeouts (does not throw)', () => {- // We can't easily provoke a real hang in CI without slowing the- // suite, but we CAN confirm that an invocation that DOES throw- // (because the binary is missing) returns false rather than- // propagating. Same code path the timeout case takes.- assert.equal(verifyHermesCli('/definitely/not/a/real/binary/anywhere'), false)-})+test('probe retries only timeouts, including a child that exits zero when terminated', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-probe-retry-'))++ try {+ for (const mode of ['recover', 'timeout', 'nonzero', 'clean-timeout']) {+ const record = path.join(root, mode)++ const script = `+ const fs = require('node:fs');+ fs.appendFileSync(${JSON.stringify(record)}, 'attempt\\n');+ const count = fs.readFileSync(${JSON.stringify(record)}, 'utf8').trim().split('\\n').length;+ if (${JSON.stringify(mode)} === 'nonzero') process.exit(1);+ if (${JSON.stringify(mode)} === 'recover' && count === 2) process.exit(0);+ process.on('SIGTERM', () => process.exit(${mode === 'clean-timeout' ? 0 : 1}));+ setInterval(() => {}, 1000);+ `++ const result = execProbe(NODE_BIN, ['-e', script], { stdio: 'ignore', timeout: 2000 })++ if (mode === 'recover') {+ await result+ } else {+ await assert.rejects(result, undefined, mode)+ }++ assert.equal(fs.readFileSync(record, 'utf8').trim().split('\n').length, mode === 'nonzero' ? 1 : 2, mode)+ }+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+}, 20_000)test('default probe timeout is 15s (not the old 5s death-loop value)', () => {assert.equal(DEFAULT_PROBE_TIMEOUT_MS, 15_000)diff --git a/apps/desktop/electron/backend-probes.ts b/apps/desktop/electron/backend-probes.tsindex 7133342141e..96be14fc14e 100644--- a/apps/desktop/electron/backend-probes.ts+++ b/apps/desktop/electron/backend-probes.ts@@ -33,7 +33,7 @@* as bootstrap-platform.ts and hardening.ts).*/-import { execFileSync } from 'node:child_process'+import { spawn } from 'node:child_process'/** Default probe budget. 5s false-negativeed healthy Windows cold starts (#61764). */const DEFAULT_PROBE_TIMEOUT_MS = 15_000@@ -85,10 +85,10 @@ function isTimeoutError(err: unknown): boolean {}/**- * Run execFileSync; on timeout only, retry once before failing.+ * Run without blocking the event loop; on timeout only, retry once before failing.* Non-timeout failures (ENOENT, non-zero exit) fail immediately.*/-function execProbeSync(+async function execProbe(command: string,args: string[],options: {@@ -99,16 +99,36 @@ function execProbeSync(shell?: booleanwindowsHide?: boolean}-): void {+): Promise<void> {+ const run = () =>+ new Promise<void>((resolve, reject) => {+ const child = spawn(command, args, options)+ child.once('error', reject)+ child.once('close', (code, signal) => {+ // A timed-out probe may handle SIGTERM and exit zero; it is still a timeout.+ if (code === 0 && !child.killed) {+ resolve()+ } else {+ reject(+ Object.assign(new Error(`Runtime probe failed: ${command} (${signal || code})`), {+ code,+ signal,+ killed: child.killed+ })+ )+ }+ })+ })+try {- execFileSync(command, args, options)+ await run()} catch (err) {if (!isTimeoutError(err)) {throw err}// One cold-cache / AV miss should not force hermes-setup --update (#61764).- execFileSync(command, args, options)+ await run()}}@@ -141,13 +161,13 @@ function hermesRuntimeImportProbe() {* @param {object} [opts.env] - Additional environment for the probe.* @returns {boolean}*/-function canImportHermesCli(pythonPath: string, opts: { env?: Record<string, string> } = {}) {+async function canImportHermesCli(pythonPath: string, opts: { env?: Record<string, string> } = {}) {if (!pythonPath) {return false}try {- execProbeSync(pythonPath, ['-c', hermesRuntimeImportProbe()], {+ await execProbe(pythonPath, ['-c', hermesRuntimeImportProbe()], {env: { ...process.env, ...(opts.env || {}) },stdio: 'ignore',timeout: PROBE_TIMEOUT_MS,@@ -175,7 +195,7 @@ function canImportHermesCli(pythonPath: string, opts: { env?: Record<string, str* @param {string} hermesCommand - Resolved absolute path to a hermes* executable (or an interpreter+script wrapper).* @param {boolean} [opts.shell] - Whether to run through a shell. For- * .cmd/.bat shims on Windows execFileSync needs shell:true to find+ * .cmd/.bat shims on Windows spawn needs shell:true to find* the cmd interpreter; mirrors the same flag isCommandScript() drives* in resolveHermesBackend.* @returns {boolean}@@ -190,13 +210,13 @@ function shouldTrustHermesOverride(hermesOverride?: string) {return typeof hermesOverride === 'string' && hermesOverride.trim().length > 0}-function verifyHermesCli(hermesCommand: string, opts?: { shell?: boolean }) {+async function verifyHermesCli(hermesCommand: string, opts?: { shell?: boolean }) {if (!hermesCommand) {return false}try {- execProbeSync(hermesCommand, ['--version'], {+ await execProbe(hermesCommand, ['--version'], {stdio: 'ignore',timeout: PROBE_TIMEOUT_MS,shell: Boolean(opts?.shell),@@ -212,7 +232,7 @@ function verifyHermesCli(hermesCommand: string, opts?: { shell?: boolean }) {export {canImportHermesCli,DEFAULT_PROBE_TIMEOUT_MS,- execProbeSync,+ execProbe,hermesRuntimeImportProbe,PROBE_TIMEOUT_MS,resolveProbeTimeoutMs,diff --git a/apps/desktop/electron/backend-serve-support.test.ts b/apps/desktop/electron/backend-serve-support.test.tsnew file mode 100644index 00000000000..b775f944534--- /dev/null+++ b/apps/desktop/electron/backend-serve-support.test.ts@@ -0,0 +1,31 @@+import assert from 'node:assert/strict'++import { test, vi } from 'vitest'++import * as probes from './backend-probes'+import { createBackendServeSupportResolver } from './backend-serve-support'++test('concurrent serve checks share one pending probe and retain its negative result', async () => {+ let fail!: (error: Error) => void++ const pending = new Promise<void>((_resolve, reject) => {+ fail = reject+ })++ const probe = vi.spyOn(probes, 'execProbe').mockReturnValue(pending)+ const supportsServe = createBackendServeSupportResolver('/unused', () => {})+ const backend = { command: '/unused/hermes', args: ['serve'] }++ try {+ const first = supportsServe(backend)+ const second = supportsServe(backend)+ const callsWhilePending = probe.mock.calls.length+ fail(new Error('unsupported'))+ assert.deepEqual(await Promise.all([first, second]), [false, false])+ assert.equal(callsWhilePending, 1)+ assert.equal(await supportsServe(backend), false)+ assert.equal(probe.mock.calls.length, 1)+ } finally {+ probe.mockRestore()+ }+})diff --git a/apps/desktop/electron/backend-serve-support.ts b/apps/desktop/electron/backend-serve-support.tsnew file mode 100644index 00000000000..175e6fa8875--- /dev/null+++ b/apps/desktop/electron/backend-serve-support.ts@@ -0,0 +1,82 @@+import fs from 'node:fs'+import path from 'node:path'++import { sourceDeclaresServe } from './backend-command'+import { execProbe, PROBE_TIMEOUT_MS } from './backend-probes'++interface ServeCandidate {+ command?: string | null+ root?: string+ args?: string[]+ env?: Record<string, string>+ shell?: boolean+ label?: string+}++// One cache per desktop runtime context; source inspection precedes a CLI probe.+export function createBackendServeSupportResolver(hermesHome: string, rememberLog: (message: string) => void) {+ const cache = new Map<string, Promise<boolean>>()++ return async function backendSupportsServe(backend: ServeCandidate): Promise<boolean> {+ if (!backend || !backend.command) {+ return true+ }++ const key = `${backend.command}::${backend.root || ''}`++ if (cache.has(key)) {+ return cache.get(key)!+ }++ const pending = (async () => {+ let supported: boolean | null = null++ if (backend.root) {+ try {+ const src = fs.readFileSync(path.join(backend.root, 'hermes_cli', 'subcommands', 'dashboard.py'), 'utf8')+ supported = sourceDeclaresServe(src)+ } catch {+ supported = null // source unreadable — fall through to the probe+ }+ }++ if (supported === null) {+ try {+ const prefix = backend.args && backend.args[0] === '-m' ? backend.args.slice(0, 2) : []+ // Same cold-Windows Python-startup class as the runtime probes+ // (#61764/#72632/#72707): `serve --help` imports at least as much as+ // `hermes --version` (~10.5s measured cold), and a false negative here+ // is cached for the process lifetime, silently routing a modern+ // runtime through the legacy `dashboard` form. Share the probe budget+ // and its timeout-only retry instead of a thinner local bound.+ await execProbe(backend.command, [...prefix, 'serve', '--help'], {+ cwd: backend.root || undefined,+ env: { ...process.env, HERMES_HOME: hermesHome, ...(backend.env || {}) },+ timeout: PROBE_TIMEOUT_MS,+ stdio: 'ignore',+ // `.cmd`/`.bat` shim backends carry shell: true in their descriptor+ // (see resolveHermesBackend step 4); execFileSync of a .cmd without+ // shell throws EINVAL on modern Node, which the catch below would+ // mis-cache as "serve unsupported" for the process lifetime.+ shell: Boolean(backend.shell),+ windowsHide: true+ })+ supported = true+ } catch {+ supported = false+ }+ }++ rememberLog(+ `[backend] \`serve\` ${supported ? 'supported' : 'unsupported → routing via legacy `dashboard`'} for ${backend.label || key}`+ )++ return supported+ })()++ // Publish the promise before yielding; late results never overwrite a newer entry.+ cache.set(key, pending)++ return pending+ }+}diff --git a/apps/desktop/electron/first-run-setup-main-process.test.ts b/apps/desktop/electron/first-run-setup-main-process.test.tsindex 1dc1b920ef6..ba453ba3a38 100644--- a/apps/desktop/electron/first-run-setup-main-process.test.ts+++ b/apps/desktop/electron/first-run-setup-main-process.test.ts@@ -45,6 +45,7 @@ test('a first-run bootstrap-needed remote apply connects without ensuring or booconst prepareLocalBackend = vi.fn(async () => bootstrapBackend)const pendingConnection = runPrimaryBackendStartup({+ assertCurrentAttempt: () => {},connectRemote,ensureLocalRuntime,prepareLocalBackend,diff --git a/apps/desktop/electron/local-backend-lifecycle.test.ts b/apps/desktop/electron/local-backend-lifecycle.test.tsindex 7485c1e8c97..af0cead5001 100644--- a/apps/desktop/electron/local-backend-lifecycle.test.ts+++ b/apps/desktop/electron/local-backend-lifecycle.test.ts@@ -104,6 +104,7 @@ test('the quit barrier cancels real first-run startup and waits for both local aconst startup = lifecycle.start(() =>runPrimaryBackendStartup({+ assertCurrentAttempt: () => {},signal: lifecycle.signal,resolveRemote: async () => null,connectRemote: async () => ({}),diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 7bf419e310e..4bb53a90f2b 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -55,22 +55,17 @@ import {processStartMarker,REAP_PROBE_TIMEOUT_MS} from './backend-claim'-import { dashboardFallbackArgs, sourceDeclaresServe } from './backend-command'+import { dashboardFallbackArgs } from './backend-command'import { createBackendConnectionState } from './backend-connection-state'import { BackendDialClaims } from './backend-dial-claim'import { buildDesktopBackendEnv, hermesManagedNodePathEntries, normalizeHermesHomeRoot } from './backend-env'import { isReauthRequiredError, waitForHermesReady } from './backend-health'import { backendCommandMatches, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'-import {- canImportHermesCli,- execProbeSync,- PROBE_TIMEOUT_MS,- shouldTrustHermesOverride,- verifyHermesCli-} from './backend-probes'+import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyHermesCli } from './backend-probes'import { waitForDashboardPortAnnouncement } from './backend-ready'import { recycleOwnedBackend } from './backend-recycle'import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate'+import { createBackendServeSupportResolver } from './backend-serve-support'import {isHostKeyChangedBootFailure,isRetryableRemoteBootFailure,@@ -2591,70 +2586,13 @@ function unwrapWindowsVenvHermesCommand(command, backendArgs) {// installs, dev checkouts, and the Windows venv). Fallback: probe the CLI once// (covers a bare `hermes` resolved from PATH with no known source root). Result// is cached per resolved runtime so we probe at most once per backend.-const _serveSupportCache = new Map()--function backendSupportsServe(backend) {- if (!backend || !backend.command) {- return true- }-- const key = `${backend.command}::${backend.root || ''}`-- if (_serveSupportCache.has(key)) {- return _serveSupportCache.get(key)- }-- let supported = null-- if (backend.root) {- try {- const src = fs.readFileSync(path.join(backend.root, 'hermes_cli', 'subcommands', 'dashboard.py'), 'utf8')- supported = sourceDeclaresServe(src)- } catch {- supported = null // source unreadable — fall through to the probe- }- }-- if (supported === null) {- try {- const prefix = backend.args && backend.args[0] === '-m' ? backend.args.slice(0, 2) : []- // Same cold-Windows Python-startup class as the runtime probes- // (#61764/#72632/#72707): `serve --help` imports at least as much as- // `hermes --version` (~10.5s measured cold), and a false negative here- // is cached for the process lifetime, silently routing a modern- // runtime through the legacy `dashboard` form. Share the probe budget- // and its timeout-only retry instead of a thinner local bound.- execProbeSync(backend.command, [...prefix, 'serve', '--help'], {- cwd: backend.root || undefined,- env: { ...process.env, HERMES_HOME, ...(backend.env || {}) },- timeout: PROBE_TIMEOUT_MS,- stdio: 'ignore',- // `.cmd`/`.bat` shim backends carry shell: true in their descriptor- // (see resolveHermesBackend step 4); execFileSync of a .cmd without- // shell throws EINVAL on modern Node, which the catch below would- // mis-cache as "serve unsupported" for the process lifetime.- shell: Boolean(backend.shell),- windowsHide: true- })- supported = true- } catch {- supported = false- }- }-- _serveSupportCache.set(key, supported)- rememberLog(- `[backend] \`serve\` ${supported ? 'supported' : 'unsupported → routing via legacy `dashboard`'} for ${backend.label || key}`- )-- return supported-}+const backendSupportsServe = createBackendServeSupportResolver(HERMES_HOME, rememberLog)// Given a resolved backend whose args target `serve`, return the args the// runtime actually understands: unchanged when `serve` is supported, or// rewritten to `dashboard --no-open` for older runtimes.-function getBackendArgsForRuntime(backend) {- return backendSupportsServe(backend) ? backend.args : dashboardFallbackArgs(backend.args)+async function getBackendArgsForRuntime(backend) {+ return (await backendSupportsServe(backend)) ? backend.args : dashboardFallbackArgs(backend.args)}function normalizeExecutablePathForCompare(commandPath) {@@ -2704,7 +2642,7 @@ function isHermesSourceRoot(root) {return directoryExists(root) && fileExists(path.join(root, 'hermes_cli', 'main.py'))}-function findPythonForRoot(root) {+async function findPythonForRoot(root) {const override = process.env.HERMES_DESKTOP_PYTHONif (override && fileExists(override)) {@@ -2726,7 +2664,7 @@ function findPythonForRoot(root) {return findSystemPython()}-function findSystemPython() {+async function findSystemPython() {if (!IS_WINDOWS) {// POSIX systems: PATH lookup is safe.for (const command of ['python3', 'python']) {@@ -2787,13 +2725,10 @@ function findSystemPython() {for (const hive of ['HKLM', 'HKCU']) {for (const version of SUPPORTED_VERSIONS) {try {- const out = execFileSync(+ const out = await execText('reg',['query', `${hive}\\SOFTWARE\\Python\\PythonCore\\${version}\\InstallPath`, '/ve', '/reg:64'],- // Registry reads are near-instant; the bound only exists so a- // pathologically wedged reg.exe can't hang the synchronous boot- // resolver forever (this ran unbounded before).- hiddenWindowsChildOptions({ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5_000 })+ { timeout: 5_000 })// Output format: " (Default) REG_SZ C:\Path\To\Python\"@@ -2843,19 +2778,9 @@ function findSystemPython() {if (pyExe) {for (const version of SUPPORTED_VERSIONS) {try {- const out = execFileSync(- pyExe,- [`-${version}`, '-c', 'import sys; print(sys.executable)'],- hiddenWindowsChildOptions({- encoding: 'utf8',- stdio: ['ignore', 'pipe', 'ignore'],- // Bare interpreter startup — much lighter than the hermes-import- // probes, but still python.exe under cold cache / AV scan, so- // share the probe budget rather than running unbounded (this- // synchronous exec previously had no timeout at all).- timeout: PROBE_TIMEOUT_MS- })- )+ const out = await execText(pyExe, [`-${version}`, '-c', 'import sys; print(sys.executable)'], {+ timeout: PROBE_TIMEOUT_MS+ })const candidate = out.trim()@@ -4743,7 +4668,7 @@ function readBootstrapMarker() {// or a DMG launch over a prior CLI install satisfies this WITHOUT the desktop// ever having written the bootstrap marker -- so we must be able to recognise// "already installed" off the filesystem alone, not just the marker.-function isActiveRuntimeUsable() {+async function isActiveRuntimeUsable() {const venvPython = getVenvPython(VENV_ROOT)return (@@ -4757,13 +4682,13 @@ function isActiveRuntimeUsable() {)}-function activeRuntimeState() {+async function activeRuntimeState() {// We DELIBERATELY do NOT verify that the checkout is currently at the// pinned commit -- users update via the in-app update path or `hermes// update`, which moves HEAD legitimately. The marker only attests "a// desktop-managed bootstrap ran here at least once"; runtime usability is// what decides whether we can actually launch.- return classifyActiveRuntime(readBootstrapMarker(), BOOTSTRAP_MARKER_SCHEMA_VERSION, isActiveRuntimeUsable())+ return classifyActiveRuntime(readBootstrapMarker(), BOOTSTRAP_MARKER_SCHEMA_VERSION, await isActiveRuntimeUsable())}function writeBootstrapMarker(payload) {@@ -4989,8 +4914,8 @@ function writeDefaultProjectDir(dir) {}}-function createPythonBackend(root, label, backendArgs, options: any = {}) {- const python = findPythonForRoot(root)+async function createPythonBackend(root, label, backendArgs, options: any = {}) {+ const python = await findPythonForRoot(root)if (!python) {return null@@ -5025,9 +4950,9 @@ function createPythonBackend(root, label, backendArgs, options: any = {}) {// canonical install location shared with the CLI installer. The venv at// VENV_ROOT may not exist yet on first run; bootstrap=true tells// ensureRuntime() to create / refresh it before launch.-function createActiveBackend(backendArgs) {+async function createActiveBackend(backendArgs) {const venvPython = getVenvPython(VENV_ROOT)- const command = fileExists(venvPython) ? venvPython : findSystemPython()+ const command = fileExists(venvPython) ? venvPython : await findSystemPython()return {kind: 'python',@@ -5045,13 +4970,13 @@ function createActiveBackend(backendArgs) {}}-function resolveHermesBackend(backendArgs) {+async function resolveHermesBackend(backendArgs) {// 1. Explicit override -- HERMES_DESKTOP_HERMES_ROOT points at a developer// checkout. Honour it as-is (no bootstrap; the user is driving).const overrideRoot = process.env.HERMES_DESKTOP_HERMES_ROOT && path.resolve(process.env.HERMES_DESKTOP_HERMES_ROOT)if (overrideRoot && isHermesSourceRoot(overrideRoot)) {- const backend = createPythonBackend(overrideRoot, `Hermes source at ${overrideRoot}`, backendArgs)+ const backend = await createPythonBackend(overrideRoot, `Hermes source at ${overrideRoot}`, backendArgs)if (backend) {return backend@@ -5063,7 +4988,7 @@ function resolveHermesBackend(backendArgs) {// installed `hermes` on PATH so local Python edits are actually exercised.// (In dev with no checkout, SOURCE_REPO_ROOT won't pass isHermesSourceRoot.)if (!IS_PACKAGED && isHermesSourceRoot(SOURCE_REPO_ROOT)) {- const backend = createPythonBackend(SOURCE_REPO_ROOT, `Hermes source at ${SOURCE_REPO_ROOT}`, backendArgs)+ const backend = await createPythonBackend(SOURCE_REPO_ROOT, `Hermes source at ${SOURCE_REPO_ROOT}`, backendArgs)if (backend) {return backend@@ -5078,7 +5003,7 @@ function resolveHermesBackend(backendArgs) {// builds could leave a healthy install behind without the marker. If the// active runtime is usable, launch it directly; only fall through to// bootstrap when the runtime itself is unusable.- const activeRuntime = activeRuntimeState()+ const activeRuntime = await activeRuntimeState()if (activeRuntime.shouldUseActiveRuntime && !bootstrapRepairRequested) {if (!activeRuntime.hasValidMarker) {@@ -5125,7 +5050,7 @@ function resolveHermesBackend(backendArgs) {}if (hermesCommand) {- const unwrapped = unwrapWindowsVenvHermesCommand(hermesCommand, backendArgs)+ const unwrapped = await unwrapWindowsVenvHermesCommand(hermesCommand, backendArgs)if (unwrapped) {return unwrapped@@ -5144,7 +5069,10 @@ function resolveHermesBackend(backendArgs) {// the Nix wrapper), not a discovered PATH candidate. It must not fall// through to the install-script bootstrap if the optional probe times// out under load; the pinned backend is the only valid runtime there.- if (shouldTrustHermesOverride(hermesOverride) || verifyHermesCli(hermesCommand, { shell: shellForProbe })) {+ if (+ shouldTrustHermesOverride(hermesOverride) ||+ (await verifyHermesCli(hermesCommand, { shell: shellForProbe }))+ ) {// `unwrapped` above already answered "is this a Windows venv shim?" —// it was null (not a shim, or its import probe failed). Do NOT re-run// unwrapWindowsVenvHermesCommand here: the second call repeats the@@ -5170,7 +5098,7 @@ function resolveHermesBackend(backendArgs) {// 5. Last-ditch: pip-installed hermes_cli module via system Python.// Same rationale as #4 -- the user installed this; we use it but don't// take ownership.- const python = findSystemPython()+ const python = await findSystemPython()if (python) {// Same smoke-test rationale as step 4: a system Python in the@@ -5181,7 +5109,7 @@ function resolveHermesBackend(backendArgs) {// Verify the import works before trusting the candidate; on// failure, fall through to step 6 so the bootstrap runner pulls// a uv-managed 3.11 into %LOCALAPPDATA%\hermes\hermes-agent\venv.- if (canImportHermesCli(python)) {+ if (await canImportHermesCli(python)) {return {kind: 'python',label: `installed hermes_cli module via ${python}`,@@ -5222,12 +5150,13 @@ function resolveHermesBackend(backendArgs) {}}-function ensureRuntime(backend: any): Promise<any> {- return localBackendLifecycle.start(() => runEnsureRuntime(backend))+function ensureRuntime(backend: any, assertStillOwned: () => void): Promise<any> {+ return localBackendLifecycle.start(() => runEnsureRuntime(backend, assertStillOwned))}-async function runEnsureRuntime(backend: any): Promise<any> {+async function runEnsureRuntime(backend: any, assertStillOwned: () => void): Promise<any> {localBackendLifecycle.assertCanStart()+ assertStillOwned()if (!backend.bootstrap) {await advanceBootProgress('runtime.external', `Using ${backend.label}`, 32)@@ -5339,7 +5268,7 @@ async function runEnsureRuntime(backend: any): Promise<any> {// Re-resolve now that the install exists. The new resolution lands in// step 3 (bootstrap-complete marker) and we recurse to wire venvPython.- return ensureRuntime(resolveHermesBackend(backend.args))+ return ensureRuntime(await resolveHermesBackend(backend.args), assertStillOwned)}// bootstrap=true with a real backend (createActiveBackend path) means we@@ -12566,9 +12495,14 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;// step 3 in hermes_cli/main.py), so the child re-homes to this profile.// --port 0: the OS assigns an ephemeral port; the child announces it on stdout.const backendArgs = ['--profile', profile, 'serve', '--host', '127.0.0.1', '--port', '0']- const backend = await ensureRuntime(resolveHermesBackend(backendArgs))++ const backend = await ensureRuntime(await resolveHermesBackend(backendArgs), () =>+ assertPoolEntryStillOwned(poolKey, entry)+ )+// Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.- backend.args = getBackendArgsForRuntime(backend)+ backend.args = await getBackendArgsForRuntime(backend)+ assertPoolEntryStillOwned(poolKey, entry)const hermesCwd = resolveHermesCwd()const webDist = resolveWebDist()const readyFile = backend.readyFile ? makeDashboardReadyFile() : null@@ -12996,8 +12930,10 @@ async function runHermesStart() {const setup = await runPrimaryBackendStartup({signal: localBackendLifecycle.signal,+ assertCurrentAttempt: () => backendConnectionState.assertCurrentAttempt(connectionAttempt),connectRemote,- ensureLocalRuntime: ensureRuntime,+ ensureLocalRuntime: backend =>+ ensureRuntime(backend, () => backendConnectionState.assertCurrentAttempt(connectionAttempt)),prepareLocalBackend: async () => {await advanceBootProgress('backend.runtime', 'Resolving Hermes runtime', 28)@@ -13016,6 +12952,8 @@ async function runHermesStart() {waitForLocalStart: waitForUpdateToFinish})+ backendConnectionState.assertCurrentAttempt(connectionAttempt)+if (setup.kind === 'remote') {// Paths from the remote backend belong to a host the Windows desktop// cannot open via wsl.exe — disable WSL path bridging so native dialogs@@ -13031,7 +12969,8 @@ async function runHermesStart() {const backend = setup.backend// Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.- backend.args = getBackendArgsForRuntime(backend)+ backend.args = await getBackendArgsForRuntime(backend)+ backendConnectionState.assertCurrentAttempt(connectionAttempt)const hermesCwd = resolveHermesCwd()const webDist = resolveWebDist()const readyFile = backend.readyFile ? makeDashboardReadyFile() : null@@ -13044,9 +12983,7 @@ async function runHermesStart() {const backendNonce = crypto.randomBytes(16).toString('hex')const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)- if (!backendConnectionState.isCurrentAttempt(connectionAttempt)) {- throw new Error('Hermes backend start was superseded by a newer connection attempt.')- }+ backendConnectionState.assertCurrentAttempt(connectionAttempt)const hermesProcess = spawnOwnedBackend(backend.command,@@ -15121,7 +15058,7 @@ ipcMain.handle('hermes:window:openInTerminal', async (_event, sessionId, opts) =try {const profile = typeof opts?.profile === 'string' ? opts.profile.trim() : ''- const backend = resolveHermesBackend(tuiResumeArgs(sessionId.trim(), profile || undefined))+ const backend = await resolveHermesBackend(tuiResumeArgs(sessionId.trim(), profile || undefined))if (!backend.command) {return { ok: false, error: 'Hermes is not installed yet' }@@ -17846,7 +17783,7 @@ async function runDesktopUninstall(mode) {let pythonPath = nullif (modeRemovesAgent(mode)) {- const sysPy = findSystemPython()+ const sysPy = await findSystemPython()if (sysPy) {py = sysPydiff --git a/apps/desktop/electron/primary-backend-cancellation.test.ts b/apps/desktop/electron/primary-backend-cancellation.test.tsindex e50e4c9c57f..c20cd26ab7e 100644--- a/apps/desktop/electron/primary-backend-cancellation.test.ts+++ b/apps/desktop/electron/primary-backend-cancellation.test.ts@@ -11,6 +11,7 @@ test('quit cancels first-run startup without entering the installer', async () =let installed = falseconst startup = runPrimaryBackendStartup({+ assertCurrentAttempt: () => {},signal: controller.signal,resolveRemote: async () => null,connectRemote: async () => ({}),diff --git a/apps/desktop/electron/primary-backend-startup.test.ts b/apps/desktop/electron/primary-backend-startup.test.tsindex 72cb072e60b..de94ddee78a 100644--- a/apps/desktop/electron/primary-backend-startup.test.ts+++ b/apps/desktop/electron/primary-backend-startup.test.ts@@ -2,6 +2,7 @@ import assert from 'node:assert/strict'import { test, vi } from 'vitest'+import { createBackendConnectionState } from './backend-connection-state'import { createFirstRunSetupGate } from './first-run-setup-gate'import {createPrimaryRemoteConnection,@@ -17,6 +18,7 @@ const bootstrapBackend = {function startupOptions(overrides: Record<string, unknown> = {}) {return {+ assertCurrentAttempt: () => {},connectRemote: vi.fn(async remote => ({ baseUrl: remote.baseUrl, mode: 'remote' as const })),ensureLocalRuntime: vi.fn(async backend => ({ ...backend, command: 'hermes' })),prepareLocalBackend: vi.fn(async () => bootstrapBackend),@@ -161,6 +163,36 @@ test('continue local waits for update exclusion and ensures the prepared runtimeassert.deepEqual(options.resolveRemote.mock.calls, [[]])})+test('invalidating a pending runtime discovery prevents setup and bootstrap', async () => {+ const state = createBackendConnectionState()+ const attempt = state.startAttempt()+ let finish!: (backend: typeof bootstrapBackend) => void+ let started!: () => void++ const resolving = new Promise<void>(resolve => {+ started = resolve+ })++ const options = startupOptions({+ assertCurrentAttempt: () => state.assertCurrentAttempt(attempt),+ prepareLocalBackend: async () => {+ started()++ return new Promise<typeof bootstrapBackend>(resolve => {+ finish = resolve+ })+ }+ })++ const pending = runPrimaryBackendStartup(options)+ await resolving+ state.invalidate()+ finish(bootstrapBackend)+ await assert.rejects(pending, /superseded/)+ assert.equal(options.waitForDecision.mock.calls.length, 0)+ assert.equal(options.ensureLocalRuntime.mock.calls.length, 0)+})+test('reset rejects with a typed error and never enters either backend', async () => {const gate = createFirstRunSetupGate({ stuckAfterMs: 0 })const options = startupOptions({ waitForDecision: gate.wait })diff --git a/apps/desktop/electron/primary-backend-startup.ts b/apps/desktop/electron/primary-backend-startup.tsindex 6c3a87352dd..37996bcb9d2 100644--- a/apps/desktop/electron/primary-backend-startup.ts+++ b/apps/desktop/electron/primary-backend-startup.ts@@ -2,6 +2,7 @@ import { runBackendStartStep } from './backend-start-cancellation'import type { FirstRunSetupDecision } from './first-run-setup-gate'export interface PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, Connection> {+ assertCurrentAttempt: () => voidsignal?: AbortSignalconnectRemote: (remote: Remote) => Promise<Connection>ensureLocalRuntime: (backend: Backend) => Promise<RuntimeBackend>@@ -77,6 +78,7 @@ export class FirstRunSetupResetError extends Error {// and local backend resolution happen before the setup gate, and a remote Apply// re-resolves persisted config without ever entering ensureRuntime/bootstrap.export async function runPrimaryBackendStartup<Backend, RuntimeBackend, Remote, Connection>({+ assertCurrentAttempt,connectRemote,ensureLocalRuntime,prepareLocalBackend,@@ -87,7 +89,13 @@ export async function runPrimaryBackendStartup<Backend, RuntimeBackend, Remote,}: PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, Connection>): Promise<PrimaryBackendStartupResult<RuntimeBackend, Connection>> {- const step = <T>(run: () => T | Promise<T>) => runBackendStartStep(signal, run)+ const step = async <T>(run: () => T | Promise<T>) => {+ const result = await runBackendStartStep(signal, run)+ assertCurrentAttempt()++ return result+ }+const savedRemote = await step(resolveRemote)if (savedRemote) {diff --git a/apps/desktop/electron/windows-hermes-path.test.ts b/apps/desktop/electron/windows-hermes-path.test.tsindex 0c49b4a2ac9..8b9b636f998 100644--- a/apps/desktop/electron/windows-hermes-path.test.ts+++ b/apps/desktop/electron/windows-hermes-path.test.ts@@ -90,7 +90,7 @@ function makeDeps(overrides: Partial<Parameters<typeof resolveVenvHermesCommand>isCommandScript: () => false,fileExists: () => true,directoryExists: () => false,- canImportHermesCli: () => true,+ canImportHermesCli: async () => true,getVenvPython: (venvRoot: string) => `${venvRoot}/Scripts/python.exe`,getVenvSitePackagesEntries: () => [],buildDesktopBackendEnv: () => ({ FAKE_ENV: '1' }),@@ -103,41 +103,41 @@ function makeDeps(overrides: Partial<Parameters<typeof resolveVenvHermesCommand>}}-test('resolveVenvHermesCommand: returns null off Windows', () => {+test('resolveVenvHermesCommand: returns null off Windows', async () => {const deps = makeDeps({ isWindows: false })- assert.equal(resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', [], deps), null)+ assert.equal(await resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', [], deps), null)})-test('resolveVenvHermesCommand: returns null for a .cmd/.bat script command', () => {+test('resolveVenvHermesCommand: returns null for a .cmd/.bat script command', async () => {const deps = makeDeps({ isCommandScript: () => true })- assert.equal(resolveVenvHermesCommand('/root/venv/Scripts/hermes.cmd', [], deps), null)+ assert.equal(await resolveVenvHermesCommand('/root/venv/Scripts/hermes.cmd', [], deps), null)})-test('resolveVenvHermesCommand: returns null when the basename is not hermes/hermes.exe', () => {+test('resolveVenvHermesCommand: returns null when the basename is not hermes/hermes.exe', async () => {const deps = makeDeps()- assert.equal(resolveVenvHermesCommand('/root/venv/Scripts/python.exe', [], deps), null)+ assert.equal(await resolveVenvHermesCommand('/root/venv/Scripts/python.exe', [], deps), null)})-test('resolveVenvHermesCommand: returns null when the parent dir is not Scripts', () => {+test('resolveVenvHermesCommand: returns null when the parent dir is not Scripts', async () => {const deps = makeDeps()- assert.equal(resolveVenvHermesCommand('/root/venv/bin/hermes.exe', [], deps), null)+ assert.equal(await resolveVenvHermesCommand('/root/venv/bin/hermes.exe', [], deps), null)})-test('resolveVenvHermesCommand: returns null when the venv python does not exist on disk', () => {+test('resolveVenvHermesCommand: returns null when the venv python does not exist on disk', async () => {const deps = makeDeps({ fileExists: () => false })- assert.equal(resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', [], deps), null)+ assert.equal(await resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', [], deps), null)})-test('resolveVenvHermesCommand: probes the venv python before trusting it (returns null on failed probe)', () => {+test('resolveVenvHermesCommand: probes the venv python before trusting it (returns null on failed probe)', async () => {let probed = falseconst deps = makeDeps({- canImportHermesCli: (python: string) => {+ canImportHermesCli: async (python: string) => {probed = trueassert.equal(python, '/root/venv/Scripts/python.exe')@@ -145,15 +145,15 @@ test('resolveVenvHermesCommand: probes the venv python before trusting it (retur}})- const result = resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', ['serve'], deps)+ const result = await resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', ['serve'], deps)assert.equal(probed, true, 'must probe the venv interpreter; a broken venv must not be re-selected forever')assert.equal(result, null, 'a failed probe must fall through (return null) so the resolver reaches bootstrap')})-test('resolveVenvHermesCommand: returns the resolved python backend descriptor when the probe passes', () => {+test('resolveVenvHermesCommand: returns the resolved python backend descriptor when the probe passes', async () => {const deps = makeDeps()- const result = resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', ['serve', '--port', '0'], deps)+ const result = await resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', ['serve', '--port', '0'], deps)assert.ok(result, 'a passing probe must return a backend descriptor, not null')assert.equal(result.command, '/root/venv/Scripts/python.exe')@@ -164,11 +164,11 @@ test('resolveVenvHermesCommand: returns the resolved python backend descriptor wassert.deepEqual(result.env, { FAKE_ENV: '1' })})-test('resolveVenvHermesCommand: is case-insensitive on hermes.exe and the Scripts dir name', () => {+test('resolveVenvHermesCommand: is case-insensitive on hermes.exe and the Scripts dir name', async () => {const deps = makeDeps()- assert.ok(resolveVenvHermesCommand('/root/venv/Scripts/HERMES.EXE', [], deps))- assert.ok(resolveVenvHermesCommand('/root/venv/SCRIPTS/hermes.exe', [], deps))+ assert.ok(await resolveVenvHermesCommand('/root/venv/Scripts/HERMES.EXE', [], deps))+ assert.ok(await resolveVenvHermesCommand('/root/venv/SCRIPTS/hermes.exe', [], deps))})// ── getVenvSitePackagesEntries ─────────────────────────────────────────────diff --git a/apps/desktop/electron/windows-hermes-path.ts b/apps/desktop/electron/windows-hermes-path.tsindex f94d4b2c390..09b4c37550a 100644--- a/apps/desktop/electron/windows-hermes-path.ts+++ b/apps/desktop/electron/windows-hermes-path.ts@@ -171,7 +171,7 @@ export interface ResolveVenvHermesCommandDeps {isCommandScript: (command: string) => booleanfileExists: (filePath: string) => booleandirectoryExists: (filePath: string) => boolean- canImportHermesCli: (python: string, opts?: { env?: Record<string, string> }) => boolean+ canImportHermesCli: (python: string, opts?: { env?: Record<string, string> }) => Promise<boolean>getVenvPython: (venvRoot: string) => stringgetVenvSitePackagesEntries: (venvRoot: string) => string[]buildDesktopBackendEnv: (opts: {@@ -205,11 +205,11 @@ export interface ResolveVenvHermesCommandDeps {* python doesn't exist, or the import probe fails. Otherwise returns the* resolved backend descriptor.*/-export function resolveVenvHermesCommand(+export async function resolveVenvHermesCommand(command: string,backendArgs: string[],deps: ResolveVenvHermesCommandDeps-): {+): Promise<{label: stringcommand: stringargs: string[]@@ -218,7 +218,7 @@ export function resolveVenvHermesCommand(kind: 'python'root: stringshell: false-} | null {+} | null> {const {isWindows,isCommandScript,@@ -261,13 +261,13 @@ export function resolveVenvHermesCommand(const root = dirname(venvRoot)if (- !canImportHermesCli(python, {+ !(await canImportHermesCli(python, {env: {PYTHONPATH: [...(directoryExists(root) ? [root] : []), process.env.PYTHONPATH].filter((entry): entry is string => Boolean(entry)).join(path.delimiter)}- })+ }))) {rememberLog?.(`Ignoring venv Hermes at ${python}: runtime import probe failed (broken/partial venv); falling through to bootstrap.`diff --git a/apps/desktop/src/AGENTS.md b/apps/desktop/src/AGENTS.mdindex 48d4d65b4ba..7c642586a84 100644--- a/apps/desktop/src/AGENTS.md+++ b/apps/desktop/src/AGENTS.md@@ -15,7 +15,7 @@ The desktop has **no build/runtime dependency on the dashboard frontend**: it spNOT embed `hermes --tui` — own composer, transcript, slash pipeline.**One backward-compat fallback:** `serve` is newer, so the spawn (`electron/backend-command.ts` +-`backendSupportsServe()` in `electron/main.ts`) checks whether the resolved runtime registers `serve`+`createBackendServeSupportResolver()` in `electron/backend-serve-support.ts`) checks whether the runtime registers `serve`and ONLY when it does not (older managed install / PATH `hermes` not yet updated) rewrites argv tolegacy `dashboard --no-open`. Without it a new app against an un-upgraded runtime crashes on anunknown subcommand and bricks every mid-upgrade user. Keep it narrow and tested.