Skip to content

The agent that grows with you

fix(desktop): probe selected dependencies and retain repair errors

ethernet14669e7c193f
diff --git a/apps/desktop/electron/backend-probes-runtime.test.ts b/apps/desktop/electron/backend-probes-runtime.test.ts
new file mode 100644
index 00000000000..33119b71350
--- /dev/null
+++ b/apps/desktop/electron/backend-probes-runtime.test.ts
@@ -0,0 +1,88 @@
+import assert from 'node:assert/strict'
+import { execFileSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { test } from 'vitest'
+
+import { canImportHermesCli } from './backend-probes'
+
+const REPO = path.resolve(import.meta.dirname, '../../..')
+const PYTHON = process.env.HERMES_PYTHON || process.env.UV_PYTHON || (process.platform === 'win32' ? 'python' : 'python3')
+
+interface RuntimeFixture {
+ python: string
+ site: string
+ dependencies: string
+}
+
+test('the real bootstrap supplies selected dependencies and rejects foreign-path rescue', () => {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-probe-runtime-'))
+ const home = path.join(temp, 'home')
+
+ const env = {
+ ...process.env,
+ HERMES_HOME: home,
+ HERMES_RUNTIME_DIR: path.join(temp, 'tools'),
+ HERMES_DISABLE_LAZY_INSTALLS: '1',
+ UV_CACHE_DIR: path.join(temp, 'cache'),
+ UV_NO_CONFIG: '1',
+ PYTHONPATH: '',
+ PYTHONHOME: '',
+ PYTHONDONTWRITEBYTECODE: '1'
+ }
+
+ const setup = `
+import json, os, re, shutil, subprocess, sys, tomllib, venv
+from pathlib import Path
+root, temp = map(Path, sys.argv[1:])
+sys.path.insert(0, str(root))
+from hermes_cli.runtime_paths import install_state_dir, runtime_facts_path, site_packages
+seed = temp / 'seed'
+venv.EnvBuilder(with_pip=False).create(seed)
+dependencies = temp / 'dependencies'
+manifest = tomllib.loads((root / 'pyproject.toml').read_text(encoding='utf-8'))
+specs = [spec for spec in manifest['project']['dependencies']
+ if re.split(r'[<>=;\\[]', spec, maxsplit=1)[0].lower() in ('pyyaml', 'python-dotenv')]
+assert len(specs) == 2, specs
+subprocess.run([shutil.which('uv'), 'pip', 'install', '--python', sys.executable,
+ '--target', str(dependencies), '--no-deps', *specs],
+ check=True, stdout=sys.stderr, timeout=60)
+selected = install_state_dir(root) / 'environments' / 'selected' / 'venv'
+site = site_packages(selected)
+site.mkdir(parents=True)
+(selected / 'pyvenv.cfg').write_text('home = fixture\\n', encoding='utf-8')
+(site / 'selected-dependencies.pth').write_text(str(dependencies) + '\\n', encoding='utf-8')
+from pm.lock import Facts
+Facts(runtime_facts_path(root)).record_state('venv', 'fixture', [], environment=selected)
+python = seed / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')
+print(json.dumps({'python': str(python), 'site': str(site), 'dependencies': str(dependencies)}))
+`
+
+ try {
+ const fixture = JSON.parse(execFileSync(PYTHON, ['-I', '-c', setup, REPO, temp], {
+ cwd: temp, env, encoding: 'utf8', timeout: 90_000, windowsHide: true
+ })) as RuntimeFixture
+
+ assert.equal(canImportHermesCli(fixture.python, { cwd: REPO, env }), true)
+ assert.equal(canImportHermesCli(fixture.python, {
+ cwd: REPO,
+ env: { ...env, PYTHONHOME: path.join(temp, 'foreign-home') }
+ }), true, 'Python home overrides must be scrubbed before the interpreter starts')
+
+ fs.unlinkSync(path.join(fixture.site, 'selected-dependencies.pth'))
+ const foreign = path.join(temp, 'foreign-packages')
+ fs.symlinkSync(fixture.dependencies, foreign, process.platform === 'win32' ? 'junction' : 'dir')
+ assert.equal(canImportHermesCli(fixture.python, {
+ cwd: REPO,
+ env: { ...env, PYTHONPATH: foreign }
+ }), false, 'foreign dependencies must not conceal an empty selected environment')
+ assert.equal(canImportHermesCli(fixture.python, {
+ cwd: REPO,
+ env: { ...env, PYTHONHOME: path.join(temp, 'foreign-home') }
+ }), false)
+ } finally {
+ fs.rmSync(temp, { recursive: true, force: true, maxRetries: 3 })
+ }
+}, 120_000)
diff --git a/apps/desktop/electron/backend-probes.test.ts b/apps/desktop/electron/backend-probes.test.ts
index 2ff97814e61..6703baf4385 100644
--- a/apps/desktop/electron/backend-probes.test.ts
+++ b/apps/desktop/electron/backend-probes.test.ts
@@ -15,7 +15,6 @@ import { test } from 'vitest'
import {
canImportHermesCli,
DEFAULT_PROBE_TIMEOUT_MS,
- hermesRuntimeImportProbe,
PROBE_TIMEOUT_MS,
resolveProbeTimeoutMs,
shouldTrustHermesOverride,
@@ -49,16 +48,6 @@ test('canImportHermesCli returns false when binary does not exist', () => {
assert.equal(canImportHermesCli(ghost), false)
})
-test('hermes runtime import probe checks config dependencies', () => {
- const probe = hermesRuntimeImportProbe()
- assert.match(probe, /\bimport yaml\b/)
- // dotenv is the first third-party import on the CLI boot path
- // (hermes_cli/env_loader.py); a mid-update venv missing python-dotenv
- // passed the old probe and produced an unrecoverable boot loop.
- assert.match(probe, /\bimport dotenv\b/)
- assert.match(probe, /\bimport hermes_cli\.config\b/)
-})
-
test('explicit Hermes override is authoritative', () => {
assert.equal(shouldTrustHermesOverride('/nix/store/abc/bin/hermes'), true)
})
diff --git a/apps/desktop/electron/backend-probes.ts b/apps/desktop/electron/backend-probes.ts
index 144a3f30fa1..23cf7cb6393 100644
--- a/apps/desktop/electron/backend-probes.ts
+++ b/apps/desktop/electron/backend-probes.ts
@@ -1,40 +1,9 @@
-/**
- * backend-probes.ts
- *
- * Cheap "does this candidate backend actually work" checks used by
- * resolveHermesBackend (main.ts). The resolver walks a ladder of
- * candidates -- bootstrap marker, `hermes` on PATH, system Python with
- * hermes_cli installed -- and historically returned the first candidate
- * whose binary existed on disk. That assumption breaks when a user has
- * a pre-installed Python 3.11-3.13 (so findSystemPython() returns a
- * path) but no hermes_cli in its site-packages: the resolver hands back
- * a backend the spawn step can't actually run, and the user gets a
- * dead-on-arrival "ModuleNotFoundError: No module named 'hermes_cli'"
- * instead of the first-launch installer.
- *
- * These probes give the resolver a way to verify a candidate before
- * trusting it. Failure (non-zero exit, exception, timeout) means "skip
- * this rung, try the next one"; success means "spawn this for real."
- * Falling off the bottom of the ladder lands on the bootstrap-needed
- * sentinel, which is exactly what we want when nothing pre-existing
- * actually works.
- *
- * Both probes are deliberately fast and forgiving:
- * - default 15s timeout (5s was too short on cold Windows disks / AV;
- * issue #61764 death-loop) with HERMES_PROBE_TIMEOUT_MS override
- * - one automatic retry after a timeout before declaring the runtime dead
- * - stdio ignored (we only care about exit code; stdout/stderr are
- * not surfaced to the user, just to recentHermesLog for forensics
- * via the caller's catch block if it chooses)
- * - any throw -> false (never propagate -- resolver wants a boolean)
- *
- * Kept in a standalone ts module so it can be unit-tested with
- * `node --test` without dragging in the electron runtime (same pattern
- * as bootstrap-platform.ts and hardening.ts).
- */
+/** Bounded backend probes. A file on disk is not proof of a usable runtime. */
import { execFileSync } from 'node:child_process'
+import { buildDesktopBackendEnv } from './backend-env'
+
/** Default probe budget. 5s false-negativeed healthy Windows cold starts (#61764). */
const DEFAULT_PROBE_TIMEOUT_MS = 15_000
@@ -112,44 +81,19 @@ function execProbeSync(
}
}
-/**
- * Return the Python snippet used to verify Hermes can import far enough to
- * launch the CLI. Kept exported for tests so dependency regressions are
- * caught without needing a real broken venv fixture.
- *
- * @returns {string}
- */
-function hermesRuntimeImportProbe() {
- return 'import yaml; import dotenv; import hermes_cli.config'
-}
-
-/**
- * Return true iff the Hermes runtime import probe exits 0.
- *
- * Used to gate the "fallback to system Python with hermes_cli installed"
- * rung of resolveHermesBackend. Without this, a system Python 3.11-3.13
- * registered in PEP 514 makes findSystemPython() succeed regardless of
- * whether hermes_cli has actually been pip-installed into its
- * site-packages -- and the resolver returns a backend that immediately
- * dies on spawn.
- *
- * The probe intentionally imports hermes_cli.config, not just the top-level
- * package: a broken/empty Windows launcher venv can still see the source tree
- * through PYTHONPATH but lack PyYAML, then die on the first real CLI import.
- *
- * @param {string} pythonPath - Absolute path to a python.exe / python.
- * @param {object} [opts.env] - Additional environment for the probe.
- * @returns {boolean}
- */
-function canImportHermesCli(pythonPath: string, opts: { env?: Record<string, string>; cwd?: string } = {}) {
+/** Probe the checkout at cwd with the same dependency activation as launch. */
+function canImportHermesCli(pythonPath: string, opts: { env?: NodeJS.ProcessEnv; cwd?: string } = {}): boolean {
if (!pythonPath) {
return false
}
try {
- execProbeSync(pythonPath, ['-c', hermesRuntimeImportProbe()], {
+ const env = { ...process.env, ...opts.env }
+
+ // Bootstrap selects the committed generation before any dependency import.
+ execProbeSync(pythonPath, ['-c', 'import hermes_bootstrap; import yaml; import dotenv; import hermes_cli.config'], {
cwd: opts.cwd,
- env: { ...process.env, ...(opts.env || {}) },
+ env: { ...env, ...buildDesktopBackendEnv({ currentEnv: env }) },
stdio: 'ignore',
timeout: PROBE_TIMEOUT_MS,
windowsHide: true
@@ -214,7 +158,6 @@ export {
canImportHermesCli,
DEFAULT_PROBE_TIMEOUT_MS,
execProbeSync,
- hermesRuntimeImportProbe,
PROBE_TIMEOUT_MS,
resolveProbeTimeoutMs,
shouldTrustHermesOverride,
diff --git a/apps/desktop/electron/bootstrap-state.test.ts b/apps/desktop/electron/bootstrap-state.test.ts
new file mode 100644
index 00000000000..67ea76b8f9e
--- /dev/null
+++ b/apps/desktop/electron/bootstrap-state.test.ts
@@ -0,0 +1,22 @@
+import { expect, test } from 'vitest'
+
+import { bootstrapSnapshot } from './bootstrap-state'
+import { type InstallStamp } from './install-stamp'
+
+function stamp(payload: InstallStamp['payload']): InstallStamp {
+ return {
+ schemaVersion: 2, commit: null, commitDate: null, branch: null,
+ builtAt: null, dirty: false, source: 'build', distribution: 'desktop-app',
+ updateMechanism: 'self', baseVersion: null, displayVersion: null,
+ distance: null, payload, tag: null
+ }
+}
+
+test.each(['bundled', 'bootstrap', 'light'] as const)('bootstrap state retains the %s artifact fact across failure and reset', payload => {
+ const artifact = stamp(payload)
+ const state = { error: 'backend exited before setup', setupChoice: null }
+ expect(bootstrapSnapshot(state, artifact)).toEqual({ ...state, bundled: payload === 'bundled' })
+ expect(bootstrapSnapshot({ error: null, setupChoice: null }, artifact).bundled).toBe(payload === 'bundled')
+ expect(state).not.toHaveProperty('bundled')
+ expect(bootstrapSnapshot({ ...state, bundled: payload !== 'bundled' }, artifact).bundled).toBe(payload === 'bundled')
+})
diff --git a/apps/desktop/electron/bootstrap-state.ts b/apps/desktop/electron/bootstrap-state.ts
new file mode 100644
index 00000000000..090466275ed
--- /dev/null
+++ b/apps/desktop/electron/bootstrap-state.ts
@@ -0,0 +1,8 @@
+import { INSTALL_STAMP, installShape, type InstallStamp } from './install-stamp'
+
+export function bootstrapSnapshot<State>(
+ state: State,
+ stamp: Readonly<InstallStamp> | null = INSTALL_STAMP
+): State & { bundled: boolean } {
+ return { ...state, bundled: installShape(stamp) === 'bundled' }
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 3ce8728b56a..bf010568501 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -83,6 +83,7 @@ import {
} from './bootstrap-platform'
import { decideBootstrapRepair } from './bootstrap-repair-guard'
import { runBootstrap } from './bootstrap-runner'
+import { bootstrapSnapshot } from './bootstrap-state'
import {
BROWSER_WINDOW_HEIGHT,
BROWSER_WINDOW_MIN_HEIGHT,
@@ -1950,8 +1951,7 @@ let bootstrapState = {
startedAt: null,
completedAt: null,
setupChoice: null,
- unsupportedPlatform: null,
- bundled: false
+ unsupportedPlatform: null
}
let firstRunSetupGate = null
@@ -2008,11 +2008,10 @@ function broadcastBootstrapEvent(ev) {
platform: ev.platform,
activeRoot: ev.activeRoot,
local: ev.local || 'none',
- bundled: Boolean(ev.bundled)
+ bundled: installShape() === 'bundled'
}
: null
bootstrapState.unsupportedPlatform = null
- bootstrapState.bundled = Boolean(ev.bundled)
} else if (ev.type === 'dismissed') {
resetBootstrapSnapshot()
}
@@ -2031,10 +2030,10 @@ function broadcastBootstrapEvent(ev) {
}
function getBootstrapState() {
- return bootstrapState
+ return bootstrapSnapshot(bootstrapState)
}
-function resetBootstrapSnapshot() {
+function resetBootstrapSnapshot(): void {
bootstrapState = {
active: false,
manifest: null,
@@ -2044,8 +2043,7 @@ function resetBootstrapSnapshot() {
startedAt: null,
completedAt: null,
setupChoice: null,
- unsupportedPlatform: null,
- bundled: false
+ unsupportedPlatform: null
}
}
@@ -4197,9 +4195,8 @@ function isActiveRuntimeUsable() {
isHermesSourceRoot(ACTIVE_HERMES_ROOT) &&
fileExists(venvPython) &&
canImportHermesCli(venvPython, {
- env: {
- PYTHONPATH: [ACTIVE_HERMES_ROOT, process.env.PYTHONPATH].filter(Boolean).join(path.delimiter)
- }
+ cwd: ACTIVE_HERMES_ROOT,
+ env: { HERMES_HOME }
})
)
}
diff --git a/apps/desktop/src/components/boot-failure-overlay.test.tsx b/apps/desktop/src/components/boot-failure-overlay.test.tsx
index 37e432146eb..da126965d2a 100644
--- a/apps/desktop/src/components/boot-failure-overlay.test.tsx
+++ b/apps/desktop/src/components/boot-failure-overlay.test.tsx
@@ -2,6 +2,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/re
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { $desktopBoot } from '@/store/boot'
+import { $notifications } from '@/store/notifications'
import { $desktopOnboarding } from '@/store/onboarding'
import { BootFailureOverlay } from './boot-failure-overlay'
@@ -281,4 +282,70 @@ describe('BootFailureOverlay', () => {
restore()
}
})
+
+ it.each(['refused', 'thrown', 'unavailable'])('preserves a %s repair failure without reloading', async failure => {
+ const reload = vi.fn()
+ const originalLocation = Object.getOwnPropertyDescriptor(window, 'location')!
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { ...window.location, reload }
+ })
+
+ const repair = failure === 'unavailable' ? undefined : vi.fn(async () => {
+ if (failure === 'thrown') {
+ throw new Error('installer permission denied')
+ }
+
+ return { ok: false, error: 'bundled-immutable' }
+ })
+
+ const restore = stubDesktop(
+ { mode: 'local' },
+ { repairBootstrap: repair }
+ )
+
+ try {
+ render(<BootFailureOverlay />)
+ fireEvent.click(await screen.findByRole('button', { name: /repair install/i }))
+
+ const message = failure === 'thrown' ? 'installer permission denied'
+ : failure === 'refused' ? 'bundled-immutable' : 'Desktop IPC bridge is unavailable.'
+
+ await waitFor(() => expect($notifications.get()).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: 'error', message })
+ ])))
+ expect(reload).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: /repair install/i }).hasAttribute('disabled')).toBe(false)
+ } finally {
+ restore()
+ Object.defineProperty(window, 'location', originalLocation)
+ $notifications.set([])
+ }
+ })
+
+ it('reloads after an accepted repair', async () => {
+ const reload = vi.fn()
+ const originalLocation = Object.getOwnPropertyDescriptor(window, 'location')!
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { ...window.location, reload }
+ })
+
+ const restore = stubDesktop(
+ { mode: 'local' },
+ { repairBootstrap: vi.fn().mockResolvedValue({ ok: true }) }
+ )
+
+ try {
+ render(<BootFailureOverlay />)
+ fireEvent.click(await screen.findByRole('button', { name: /repair install/i }))
+
+ await waitFor(() => expect(reload).toHaveBeenCalled())
+ expect($notifications.get().some(n => n.kind === 'error')).toBe(false)
+ } finally {
+ restore()
+ Object.defineProperty(window, 'location', originalLocation)
+ $notifications.set([])
+ }
+ })
})
diff --git a/apps/desktop/src/components/boot-failure-overlay.tsx b/apps/desktop/src/components/boot-failure-overlay.tsx
index c3186c0d244..a96fb63e54b 100644
--- a/apps/desktop/src/components/boot-failure-overlay.tsx
+++ b/apps/desktop/src/components/boot-failure-overlay.tsx
@@ -84,8 +84,7 @@ export function BootFailureOverlay() {
// Bundled installs carry their runtime as an immutable payload — repair
// would re-run an installer that must never fire for them. Resolve the
- // artifact kind from the bootstrap snapshot (set by main.ts on setup-choice
- // broadcast) so the recovery actions swap Repair → "Reinstall the app".
+ // artifact kind from the bootstrap snapshot, including failures before setup.
useEffect(() => {
if (!visible) {
return
@@ -180,10 +179,26 @@ export function BootFailureOverlay() {
window.location.reload()
}
- const repair = async () => {
+ const repair = async (): Promise<void> => {
setBusy('repair')
- await window.hermesDesktop?.repairBootstrap().catch(() => undefined)
- window.location.reload()
+
+ try {
+ if (!window.hermesDesktop?.repairBootstrap) {
+ throw new Error(t.boot.errors.ipcBridgeUnavailable)
+ }
+
+ const result = await window.hermesDesktop.repairBootstrap()
+
+ if (!result?.ok) {
+ throw new Error(result?.error || t.boot.errors.desktopBootFailed)
+ }
+
+ window.location.reload()
+ } catch (error) {
+ notifyError(error, t.boot.failure.repairInstall)
+ } finally {
+ setBusy(null)
+ }
}
const switchToLocalGateway = async () => {
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 9bba9ab34f6..60a6c6238d3 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -518,7 +518,7 @@ declare global {
continueBootstrapLocal: () => Promise<{ ok: boolean }>
recycleBackend?: (profile?: null | string) => Promise<{ ok: boolean }>
resetBootstrap: () => Promise<{ ok: boolean }>
- repairBootstrap: () => Promise<{ ok: boolean }>
+ repairBootstrap: () => Promise<{ ok: boolean; error?: string }>
cancelBootstrap: () => Promise<{ ok: boolean; cancelled: boolean }>
onBootstrapEvent: (callback: (payload: DesktopBootstrapEvent) => void) => () => void
getVersion: () => Promise<DesktopVersionInfo>