Skip to content

The agent that grows with you

refactor(desktop): delete what only the Desktop's own `hermes serve` reached

alt-glitch5e783bdef890
diff --git a/apps/desktop/electron/backend-claim.test.ts b/apps/desktop/electron/backend-claim.test.ts
index 0b2555b86a2..b681c09d78b 100644
--- a/apps/desktop/electron/backend-claim.test.ts
+++ b/apps/desktop/electron/backend-claim.test.ts
@@ -1,56 +1,8 @@
import assert from 'node:assert/strict'
-import { EventEmitter } from 'node:events'
import { test } from 'vitest'
-import {
- claimDecision,
- createBackendOutputTail,
- formatBackendExitLine,
- isPidOnlyStartMarker,
- pidOnlyStartMarker,
- probeStartMarker,
- processStartMarker
-} from './backend-claim'
-
-// --- claimDecision: the #93608 policy ---------------------------------------
-
-test('probe success claims with the full start marker (unchanged behavior)', () => {
- const decision = claimDecision(true, { ok: true, startMarker: 'linux:12345' })
-
- assert.deepEqual(decision, { action: 'claim', startMarker: 'linux:12345' })
-})
-
-test('probe success claims even when the child already exited (ownership records the incarnation)', () => {
- // The claim itself must not invent a failure: the exit handler owns cleanup.
- const decision = claimDecision(false, { ok: true, startMarker: 'win:99' })
-
- assert.deepEqual(decision, { action: 'claim', startMarker: 'win:99' })
-})
-
-test('probe failure on a LIVE child degrades to PID-only identity — never kills a healthy backend (#93608)', () => {
- const decision = claimDecision(true, { ok: false, reason: 'powershell.exe timed out after 30000ms' })
-
- assert.equal(decision.action, 'degrade')
- assert.match((decision as { reason: string }).reason, /timed out/)
-})
-
-test('probe failure on a DEAD child fails closed so the caller can attach the stderr tail', () => {
- const decision = claimDecision(false, { ok: false, reason: 'Get-Process: no process with ID 4242' })
-
- assert.equal(decision.action, 'fail')
- assert.match((decision as { reason: string }).reason, /4242/)
-})
-
-// --- probeStartMarker: throw → value ----------------------------------------
-
-test('probeStartMarker converts a probe throw into { ok: false, reason }', async () => {
- const probe = await probeStartMarker(4242, async () => {
- throw new Error('PowerShell 5.1 cold start exceeded budget')
- })
-
- assert.deepEqual(probe, { ok: false, reason: 'PowerShell 5.1 cold start exceeded budget' })
-})
+import { isPidOnlyStartMarker, processStartMarker } from './backend-claim'
// --- real probe: drives the actual OS helper (PowerShell on the Windows lane) ---
@@ -70,65 +22,8 @@ test('a missing PID is classified as ESRCH so reapOrphans can drop the record',
// --- PID-only marker helpers --------------------------------------------------
-test('pidOnlyStartMarker round-trips through isPidOnlyStartMarker', () => {
- const marker = pidOnlyStartMarker(4242)
-
- assert.equal(isPidOnlyStartMarker(marker), true)
+test('isPidOnlyStartMarker recognizes degraded PID-only ownership records', () => {
+ assert.equal(isPidOnlyStartMarker('pid-only:4242'), true)
assert.equal(isPidOnlyStartMarker('linux:12345'), false)
assert.equal(isPidOnlyStartMarker(undefined), false)
})
-
-// --- output tail ring buffer ----------------------------------------------------
-
-test('output tail keeps only the most recent bytes once past the limit', () => {
- const tail = createBackendOutputTail(16)
-
- tail.append('0123456789')
- tail.append('abcdefghij')
-
- assert.equal(tail.text(), '456789abcdefghij')
- assert.equal(tail.text().length, 16)
-})
-
-test('output tail interleaves stdout and stderr attached from spawn time', () => {
- const child = { stderr: new EventEmitter(), stdout: new EventEmitter() }
- const tail = createBackendOutputTail(64)
-
- tail.attach(child)
- child.stdout.emit('data', Buffer.from('booting\n'))
- child.stderr.emit('data', Buffer.from("ModuleNotFoundError: No module named 'hermes_cli'\n"))
-
- assert.match(tail.text(), /booting/)
- assert.match(tail.text(), /ModuleNotFoundError/)
-})
-
-test('attach tolerates a child with missing stdio streams', () => {
- const tail = createBackendOutputTail(64)
-
- tail.attach({ stderr: null, stdout: null })
- assert.equal(tail.text(), '')
-})
-
-// --- formatBackendExitLine ---------------------------------------------------
-
-test('exit line carries the buffered tail next to the exit code, preferring the signal', () => {
- const tail = createBackendOutputTail(64)
- tail.append('Traceback (most recent call last):\n')
-
- assert.equal(
- formatBackendExitLine('Ignoring stale Hermes backend exit', 1, null, tail),
- 'Ignoring stale Hermes backend exit (1)\nRecent backend output:\nTraceback (most recent call last):'
- )
- assert.equal(
- formatBackendExitLine('Hermes backend exited', null, 'SIGTERM', tail),
- 'Hermes backend exited (SIGTERM)\nRecent backend output:\nTraceback (most recent call last):'
- )
-})
-
-test('exit line stays byte-identical to the legacy shape when the tail is empty or missing', () => {
- assert.equal(
- formatBackendExitLine('Hermes backend exited', 0, null, createBackendOutputTail(64)),
- 'Hermes backend exited (0)'
- )
- assert.equal(formatBackendExitLine('Hermes backend exited', 1, null, null), 'Hermes backend exited (1)')
-})
diff --git a/apps/desktop/electron/backend-claim.ts b/apps/desktop/electron/backend-claim.ts
index fb53d21f7a9..bf60765992f 100644
--- a/apps/desktop/electron/backend-claim.ts
+++ b/apps/desktop/electron/backend-claim.ts
@@ -1,20 +1,10 @@
/**
* backend-claim.ts
*
- * The start-marker probe and the claim decision for a freshly spawned local
- * backend child, extracted from main.ts so the policy is testable without
- * booting Electron — including on a Windows CI lane that drives the probe
- * with REAL PowerShell (`processStartMarker` shells out to powershell.exe).
- *
- * Why this exists (#93608): `claimBackendChild` used to hard-fail on ANY
- * probe error — `Get-Process` timing out on a PowerShell 5.1 cold start
- * (see #87169) killed a perfectly healthy backend, the renderer "repaired"
- * by respawning, and the next probe timeout killed that one too. The rule is
- * now the same one `createParentStartMarkerResolver` already applies to the
- * parent marker: a failed probe against a LIVE child degrades to PID-only
- * identity instead of killing the child; only a child that actually DIED
- * keeps the fail-closed throw (now carrying its stderr tail, so the real
- * exit reason reaches desktop.log and the boot UI).
+ * Process start-marker probes used to match backend ownership records against
+ * live processes, extracted from main.ts so they are testable without booting
+ * Electron — including on a Windows CI lane that drives the probe with REAL
+ * PowerShell (`processStartMarker` shells out to powershell.exe).
*/
import { execFile } from 'node:child_process'
@@ -58,8 +48,7 @@ export const REAP_PROBE_TIMEOUT_MS = 5_000
/**
* Cross-platform process start marker: a value that changes when a PID is
* reused, so `pid + marker` identifies one specific process incarnation.
- * Throws when the probe fails — callers decide what a failure means (see
- * `claimDecision` / `probeStartMarker`).
+ * Throws when the probe fails — callers decide what a failure means.
*/
export async function processStartMarker(pid: number, timeoutMs: number = 30_000): Promise<string> {
// Cheap native dead-PID gate. Windows Get-Process / macOS `ps -p` exit 1
@@ -125,120 +114,13 @@ export async function processStartMarker(pid: number, timeoutMs: number = 30_000
return `ps:${started}`
}
-export type StartMarkerProbe = { ok: true; startMarker: string } | { ok: false; reason: string }
-
-/** Run the marker probe, converting a throw into a value the pure decision can consume. */
-export async function probeStartMarker(
- pid: number,
- probe: (pid: number) => Promise<string> = processStartMarker
-): Promise<StartMarkerProbe> {
- try {
- return { ok: true, startMarker: await probe(pid) }
- } catch (error) {
- return { ok: false, reason: error instanceof Error ? error.message : String(error) }
- }
-}
-
const PID_ONLY_MARKER_PREFIX = 'pid-only:'
/**
- * Degraded identity marker recorded when the start-marker probe failed but
- * the child was verifiably alive. It satisfies the ownership schema (a
- * non-empty startMarker) while telling identity matchers that only PID
- * liveness — plus the command-line check layered on top — can be verified.
+ * Degraded identity marker written by the former local-spawn claim path when
+ * the start-marker probe failed against a live child. Ownership records may
+ * still carry it; identity matchers treat it as PID-liveness only.
*/
-export function pidOnlyStartMarker(pid: number): string {
- return `${PID_ONLY_MARKER_PREFIX}${pid}`
-}
-
export function isPidOnlyStartMarker(startMarker: unknown): boolean {
return typeof startMarker === 'string' && startMarker.startsWith(PID_ONLY_MARKER_PREFIX)
}
-
-export type ClaimDecision =
- { action: 'claim'; startMarker: string } | { action: 'degrade'; reason: string } | { action: 'fail'; reason: string }
-
-/**
- * Pure claim policy for a freshly spawned backend child:
- *
- * - probe succeeded → claim with the full start marker (unchanged).
- * - probe failed, child ALIVE → degrade to PID-only identity; NEVER kill a
- * healthy backend over a flaky identity probe.
- * - probe failed, child DEAD → fail closed; the child's death is the real
- * story and the caller attaches its stderr tail.
- */
-export function claimDecision(childAlive: boolean, probe: StartMarkerProbe): ClaimDecision {
- if (probe.ok === true) {
- return { action: 'claim', startMarker: probe.startMarker }
- }
-
- const { reason } = probe
-
- return childAlive ? { action: 'degrade', reason } : { action: 'fail', reason }
-}
-
-export interface BackendOutputTail {
- /** Attach stdout/stderr data listeners to a just-spawned child. */
- attach(child: {
- stdout?: { on: (event: 'data', listener: (chunk: unknown) => void) => unknown } | null
- stderr?: { on: (event: 'data', listener: (chunk: unknown) => void) => unknown } | null
- }): void
- append(chunk: unknown): void
- /** The buffered tail (most recent `limit` characters), or ''. */
- text(): string
- /** Human-readable suffix for error messages, or '' when nothing buffered. */
- describe(): string
-}
-
-export const DEFAULT_OUTPUT_TAIL_LIMIT = 8192
-
-/**
- * Ring-buffered tail of a child's combined stdout+stderr, attached at SPAWN
- * time — before the claim, before the READY wait — so an early crash's real
- * stderr (traceback, missing module, bad config) survives into the ownership
- * error and the before-ready exit messages instead of a bare exit code.
- */
-export function createBackendOutputTail(limit: number = DEFAULT_OUTPUT_TAIL_LIMIT): BackendOutputTail {
- let buffer = ''
-
- const append = (chunk: unknown) => {
- buffer += String(chunk)
-
- if (buffer.length > limit) {
- buffer = buffer.slice(buffer.length - limit)
- }
- }
-
- return {
- append,
- attach(child) {
- child.stdout?.on('data', append)
- child.stderr?.on('data', append)
- },
- text() {
- return buffer
- },
- describe() {
- const text = buffer.trim()
-
- return text ? `\nRecent backend output:\n${text}` : ''
- }
- }
-}
-
-/**
- * Exit line for a supervised backend child, carrying the buffered output tail
- * so the reason the child died reaches desktop.log. Every exit surface uses
- * this shape — including the "stale" classification, where the line is the
- * only evidence left: the child is gone and nothing else will say why it
- * exited. `signal` wins over `code` (null code on signal death and vice
- * versa); an empty tail keeps the line exactly as it was before.
- */
-export function formatBackendExitLine(
- label: string,
- code: number | null,
- signal: string | null,
- outputTail: BackendOutputTail | null
-): string {
- return `${label} (${signal || code})${outputTail?.describe() ?? ''}`
-}
diff --git a/apps/desktop/electron/backend-command.test.ts b/apps/desktop/electron/backend-command.test.ts
deleted file mode 100644
index 9beca7de082..00000000000
--- a/apps/desktop/electron/backend-command.test.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import assert from 'node:assert/strict'
-
-import { test } from 'vitest'
-
-import { dashboardFallbackArgs, serveBackendArgs, sourceDeclaresServe } from './backend-command'
-
-test('serveBackendArgs pins a profile when provided', () => {
- assert.deepEqual(serveBackendArgs('worker'), ['--profile', 'worker', 'serve', '--host', '127.0.0.1', '--port', '0'])
-})
-
-test('dashboardFallbackArgs preserves a --profile flag ahead of serve', () => {
- const serve = ['-m', 'hermes_cli.main', '--profile', 'worker', 'serve', '--host', '127.0.0.1', '--port', '0']
- assert.deepEqual(dashboardFallbackArgs(serve), [
- '-m',
- 'hermes_cli.main',
- '--profile',
- 'worker',
- 'dashboard',
- '--no-open',
- '--host',
- '127.0.0.1',
- '--port',
- '0'
- ])
-})
-
-test('dashboardFallbackArgs skips a profile named "serve" and rewrites the subcommand', () => {
- // The profile VALUE 'serve' is not the subcommand: rewriting at index 1
- // yields `--profile dashboard --no-open serve`, which still runs `serve`.
- const serve = ['-m', 'hermes_cli.main', '--profile', 'serve', 'serve', '--host', '127.0.0.1', '--port', '0']
- assert.deepEqual(dashboardFallbackArgs(serve), [
- '-m',
- 'hermes_cli.main',
- '--profile',
- 'serve',
- 'dashboard',
- '--no-open',
- '--host',
- '127.0.0.1',
- '--port',
- '0'
- ])
-})
-
-test('dashboardFallbackArgs skips a -p profile value named "serve"', () => {
- const serve = ['-p', 'serve', 'serve', '--host', '127.0.0.1', '--port', '0']
- assert.deepEqual(dashboardFallbackArgs(serve), [
- '-p',
- 'serve',
- 'dashboard',
- '--no-open',
- '--host',
- '127.0.0.1',
- '--port',
- '0'
- ])
-})
-
-test('dashboardFallbackArgs rewrites through a --profile=serve self-contained flag', () => {
- const serve = ['--profile=serve', 'serve', '--host', '127.0.0.1', '--port', '0']
- assert.deepEqual(dashboardFallbackArgs(serve), [
- '--profile=serve',
- 'dashboard',
- '--no-open',
- '--host',
- '127.0.0.1',
- '--port',
- '0'
- ])
-})
-
-test('dashboardFallbackArgs leaves a serve-looking profile value alone when there is no subcommand', () => {
- const args = ['--profile', 'serve']
- assert.deepEqual(dashboardFallbackArgs(args), args)
-})
-
-test('dashboardFallbackArgs is a no-op (copy) when there is no serve token', () => {
- const args = ['-m', 'hermes_cli.main', 'dashboard', '--no-open']
- const out = dashboardFallbackArgs(args)
- assert.deepEqual(out, args)
-})
-
-test('sourceDeclaresServe detects the serve subparser registration', () => {
- assert.equal(sourceDeclaresServe('subparsers.add_parser("serve", help="...")'), true)
- assert.equal(sourceDeclaresServe("subparsers.add_parser('serve')"), true)
- assert.equal(sourceDeclaresServe('subparsers.add_parser(\n "serve",\n)'), true)
-})
-
-test('sourceDeclaresServe does not false-positive on the substring "server"', () => {
- const oldSource = `
- dashboard_parser = subparsers.add_parser("dashboard", help="Start the web UI dashboard")
- from hermes_cli.web_server import start_server # web server
- `
-
- assert.equal(sourceDeclaresServe(oldSource), false)
-})
-
-test('serveBackendArgs drops a profile value that is not a valid profile id', () => {
- // The roster/SSH bridge can hand us unvalidated values (a numeric id, an empty
- // string, a display label): a non-slug must never reach the backend spawn argv,
- // where it would bootstrap a phantom profile directory (#88842).
- const base = ['serve', '--host', '127.0.0.1', '--port', '0']
- assert.deepEqual(serveBackendArgs(0 as unknown as string), base)
- assert.deepEqual(serveBackendArgs(''), base)
- assert.deepEqual(serveBackendArgs(' '), base)
- assert.deepEqual(serveBackendArgs('Not A Slug!'), base)
-})
-
-test('serveBackendArgs keeps a valid profile id pinned, normalized like the CLI', () => {
- assert.deepEqual(serveBackendArgs('worker'), ['--profile', 'worker', 'serve', '--host', '127.0.0.1', '--port', '0'])
- assert.deepEqual(serveBackendArgs('a-1_b'), ['--profile', 'a-1_b', 'serve', '--host', '127.0.0.1', '--port', '0'])
- assert.deepEqual(serveBackendArgs(' Worker '), [
- '--profile',
- 'worker',
- 'serve',
- '--host',
- '127.0.0.1',
- '--port',
- '0'
- ])
- assert.deepEqual(serveBackendArgs('default'), ['--profile', 'default', 'serve', '--host', '127.0.0.1', '--port', '0'])
-})
diff --git a/apps/desktop/electron/backend-command.ts b/apps/desktop/electron/backend-command.ts
deleted file mode 100644
index efeaffea229..00000000000
--- a/apps/desktop/electron/backend-command.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-// Backend subcommand routing for the desktop-managed Hermes process.
-//
-// The desktop app launches its own headless backend via `hermes serve` — it
-// must NEVER depend on or launch the browser `dashboard`. But `serve` is a
-// newer subcommand: a runtime that predates it (an older managed install the
-// app hasn't updated yet, or an older `hermes` resolved from PATH) only knows
-// `dashboard --no-open`. To avoid bricking those users mid-upgrade we detect
-// whether the resolved runtime understands `serve` and, only when it does not,
-// fall back to the legacy `dashboard --no-open` invocation. Both produce the
-// exact same headless gateway; `serve` is just the decoupled name.
-//
-// These helpers are pure so they can be unit-tested without Electron.
-
-import { backendProfileArg } from './profile-id-guard'
-
-/**
- * Build the canonical headless backend argv (always `serve`).
- * @param {string} [profile] optional Hermes profile to pin via `--profile`.
- */
-export function serveBackendArgs(profile?: string) {
- // A non-slug value (numeric roster id, display label) must never cross into
- // spawn argv: the CLI used to str()-coerce it into a phantom profiles/0 dir (#88842).
- const pinned = backendProfileArg(profile)
- const head = pinned ? ['--profile', pinned] : []
-
- return [...head, 'serve', '--host', '127.0.0.1', '--port', '0']
-}
-
-// Flags that consume the next token; the subcommand is the first bare token
-// that is not one of their values. `--profile=serve` never collides (it is a
-// different string), but the two-token `--profile serve` / `-p serve` do.
-const VALUE_FLAGS = new Set(['-m', '--profile', '-p'])
-
-/**
- * Rewrite a resolved backend argv from `serve` to the legacy
- * `dashboard --no-open` form, preserving every other argument (incl. a leading
- * `-m hermes_cli.main` and any `--profile <name>`). Returns a copy; if there is
- * no `serve` subcommand token the argv is returned unchanged.
- */
-export function dashboardFallbackArgs(args) {
- let i = 0
-
- while (i < args.length && args[i] !== 'serve') {
- i += VALUE_FLAGS.has(args[i]) ? 2 : 1
- }
-
- if (i >= args.length) {
- return args.slice()
- }
-
- return [...args.slice(0, i), 'dashboard', '--no-open', ...args.slice(i + 1)]
-}
-
-/**
- * True when a runtime's `hermes_cli/subcommands/dashboard.py` source registers
- * the `serve` subcommand. Matches `add_parser("serve"` / `add_parser('serve'`
- * specifically so the substring "server" (e.g. "start_server", "web server")
- * never produces a false positive.
- */
-export function sourceDeclaresServe(dashboardPySource) {
- return /add_parser\(\s*["']serve["']/.test(String(dashboardPySource || ''))
-}
diff --git a/apps/desktop/electron/backend-serve-support.test.ts b/apps/desktop/electron/backend-serve-support.test.ts
deleted file mode 100644
index 73ae1eba5be..00000000000
--- a/apps/desktop/electron/backend-serve-support.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-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()
- }
-})
-
-test('a probe that fails by timeout is not cached, so the next check re-probes', async () => {
- const probe = vi
- .spyOn(probes, 'execProbe')
- .mockRejectedValueOnce(Object.assign(new Error('timed out'), { killed: true }))
- .mockResolvedValueOnce(undefined)
-
- const supportsServe = createBackendServeSupportResolver('/unused', () => {})
- const backend = { command: '/unused/hermes', args: ['serve'] }
-
- try {
- assert.equal(await supportsServe(backend), false)
- assert.equal(await supportsServe(backend), true)
- assert.equal(probe.mock.calls.length, 2)
- } finally {
- probe.mockRestore()
- }
-})
diff --git a/apps/desktop/electron/backend-serve-support.ts b/apps/desktop/electron/backend-serve-support.ts
deleted file mode 100644
index 0c988c07e26..00000000000
--- a/apps/desktop/electron/backend-serve-support.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { sourceDeclaresServe } from './backend-command'
-import { execProbe, isTimeoutError, PROBE_TIMEOUT_MS } from './backend-probes'
-import { windowsShellCommand } from './windows-child-options'
-
-interface ServeCandidate {
- command?: string | null
- root?: string
- args?: string[]
- env?: Record<string, string>
- shell?: boolean
- label?: string
-}
-
-// Does the resolved runtime understand the `serve` subcommand? The desktop
-// spawns `hermes serve`; runtimes older than serve only have `dashboard`, so
-// main.ts routes those through the legacy `dashboard --no-open` form instead
-// of crashing on an unknown subcommand.
-//
-// Fast path: read the runtime's own dashboard.py (instant, covers managed
-// 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 — except
-// a probe that failed by timeout, which is evicted so the next start re-probes
-// rather than pinning a cold-AV false negative for the process lifetime.
-//
-// 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 = await fs.promises.readFile(
- 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(
- windowsShellCommand(backend.command, Boolean(backend.shell)),
- [...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 (err) {
- // A timeout says nothing about the runtime, only about this machine
- // right now (cold AV scan, slow disk). Evict so the next call
- // re-probes; a genuine "unknown subcommand" exit stays cached.
- if (isTimeoutError(err) && cache.get(key) === pending) {
- cache.delete(key)
- }
-
- 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/launch-profile.test.ts b/apps/desktop/electron/launch-profile.test.ts
index c7180107c2e..620c3f40fae 100644
--- a/apps/desktop/electron/launch-profile.test.ts
+++ b/apps/desktop/electron/launch-profile.test.ts
@@ -5,7 +5,6 @@ import path from 'node:path'
import { test } from 'vitest'
-import { serveBackendArgs } from './backend-command'
import { createDesktopProfilePreferences } from './desktop-profile'
import { applyLaunchProfileOverride, parseLaunchProfile } from './launch-profile'
@@ -54,7 +53,6 @@ test('a launch --profile is persisted before the backend reads active-profile.js
assert.equal(launched, 'desktop')
assert.equal(restarted.readActive(), 'desktop')
assert.deepEqual(restarted.getDefault(), { connectionId: null, profile: 'stored' })
- assert.deepEqual(serveBackendArgs(restarted.readActive() ?? undefined).slice(0, 2), ['--profile', 'desktop'])
})
})
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 4212fba482e..5f59e065d3c 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -66,16 +66,11 @@ import { runAppInstallerChecker } from './appinstaller-checker'
import { installApplicationMenuAfterFirstWindow } from './application-menu-startup'
import { stopBackendChild as stopBackendChildImpl, waitForBackendExit } from './backend-child'
import {
- type BackendOutputTail,
- claimDecision,
execText,
isPidOnlyStartMarker,
- pidOnlyStartMarker,
- probeStartMarker,
processStartMarker,
REAP_PROBE_TIMEOUT_MS
} from './backend-claim'
-import { dashboardFallbackArgs } from './backend-command'
import { createBackendConnectionState } from './backend-connection-state'
import { assertDescriptorStillOwned, forgetFailedDescriptor } from './backend-descriptor-cache'
import { BackendDialClaims } from './backend-dial-claim'
@@ -83,7 +78,6 @@ import { buildDesktopBackendEnv, profileBackendParentEnv } from './backend-env'
import { isReauthRequiredError, waitForHermesReady } from './backend-health'
import {
backendCommandMatches,
- type BackendOwnershipEntry,
createBackendOwnership,
createBackendShutdownCoordinator
} from './backend-ownership'
@@ -91,7 +85,6 @@ import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verify
import { recycleOwnedBackend } from './backend-recycle'
import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate'
import { createInstalledRuntimeGate } from './backend-resolution'
-import { createBackendServeSupportResolver } from './backend-serve-support'
import { desktopBackendSpawnEnv } from './backend-spawn-env'
import {
isHostKeyChangedBootFailure,
@@ -416,7 +409,6 @@ import {
} from './oauth-rest-request'
import { wireOauthSessionResponse } from './oauth-session-response'
import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'
-import { createParentStartMarkerResolver } from './parent-process-identity'
import {
bundledPayload,
installIdForRoot,
@@ -1932,18 +1924,6 @@ const localBackendLifecycle = createLocalBackendLifecycle<ChildProcess>({
}
})
-function spawnOwnedBackend(...args: Parameters<typeof spawn>): ChildProcess {
- const child = localBackendLifecycle.spawn((): ChildProcess => spawn(...args))
- child.once('exit', (): boolean => localBackendLifecycle.release(child))
- child.once('error', (): void => {
- if (!child.pid) {
- localBackendLifecycle.release(child)
- }
- })
-
- return child
-}
-
const remoteLiveness = new RemoteLivenessTracker()
// Pooled remotes are probed on the renderer reconnect cadence (minutes apart),
@@ -3008,21 +2988,6 @@ async function unwrapWindowsVenvHermesCommand(command, backendArgs) {
})
}
-// Does the resolved runtime understand the `serve` subcommand? The desktop
-// spawns `hermes serve`; runtimes older than serve only have `dashboard`. We
-// detect support so getBackendArgsForRuntime() can route old runtimes through
-// the legacy `dashboard --no-open` form instead of crashing on an unknown
-// subcommand (would brick every user mid-upgrade — #54568 follow-up).
-// Fast-path / probe / cache strategy: see backend-serve-support.ts header.
-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.
-async function getBackendArgsForRuntime(backend) {
- return (await backendSupportsServe(backend)) ? backend.args : dashboardFallbackArgs(backend.args)
-}
-
function normalizeExecutablePathForCompare(commandPath) {
if (!commandPath) {
return null
@@ -4128,7 +4093,7 @@ function writeBackendOwnership(contents) {
}
// execText and processStartMarker moved to backend-claim.ts (#93608) so the
-// claim/probe policy is testable — including on Windows CI with real
+// start-marker probe is testable — including on Windows CI with real
// PowerShell — without booting Electron. main.ts calls through the module.
async function backendCommandForPid(pid) {
@@ -4298,76 +4263,6 @@ const backendOwnership = createBackendOwnership({
}
})
-const desktopParentStartMarker = createParentStartMarkerResolver({
- load: () => processStartMarker(process.pid),
- onError: error => {
- const detail = error instanceof Error ? error.message : String(error)
-
- rememberLog(
- `Could not resolve the Desktop process start marker; starting the backend with PID-only parent tracking: ${detail}`
- )
- }
-})
-
-async function claimBackendChild(
- child: ChildProcess & { hermesBackendIdentity?: BackendOwnershipEntry },
- command: string,
- profile: string,
- nonce: string,
- outputTail: BackendOutputTail | null = null
-): Promise<BackendOwnershipEntry> {
- // Probe/claim policy lives in backend-claim.ts (#93608): a marker probe
- // that fails against a LIVE child degrades to PID-only identity — matching
- // createParentStartMarkerResolver — instead of killing a healthy backend
- // over a flaky Get-Process (PS 5.1 cold starts, #87169). Only a child that
- // actually died keeps the fail-closed throw, now carrying its stderr tail.
- const probe = await probeStartMarker(child.pid)
- const decision = claimDecision(child.exitCode === null && !child.killed, probe)
-
- if (decision.action === 'fail') {
- await localBackendLifecycle.stop(child)
- throw new Error(
- `Hermes backend (PID ${child.pid}) died before its identity could be recorded: ${decision.reason}${outputTail?.describe() ?? ''}`
- )
- }
-
- let startMarker
-
- if (decision.action === 'degrade') {
- startMarker = pidOnlyStartMarker(child.pid)
- rememberLog(
- `WARNING: process start marker probe failed for live Hermes backend PID ${child.pid}; ` +
- `claiming with PID-only identity instead of stopping it: ${decision.reason}`
- )
- } else {
- startMarker = decision.startMarker
- }
-
- try {
- const identity = await backendOwnership.claim({
- command,
- nonce,
- pid: child.pid,
- profile,
- startMarker,
- // Record the spawning Electron so reapOrphans can tell an orphaned
- // backend (parent gone) from one owned by a live instance — a live
- // parent's backend is never reaped (#87295).
- parentPid: process.pid,
- parentStartMarker: await desktopParentStartMarker()
- })
-
- child.hermesBackendIdentity = identity
-
- return identity
- } catch (error) {
- await localBackendLifecycle.stop(child)
- throw new Error(
- `Could not persist ownership for the Hermes backend: ${error.message}${outputTail?.describe() ?? ''}`
- )
- }
-}
-
function reapOrphanedBackendsOnce() {
if (!backendOrphanReapPromise) {
backendOrphanReapPromise = backendOwnership
diff --git a/apps/desktop/electron/parent-process-identity.test.ts b/apps/desktop/electron/parent-process-identity.test.ts
index a1b071c2453..9333cc35787 100644
--- a/apps/desktop/electron/parent-process-identity.test.ts
+++ b/apps/desktop/electron/parent-process-identity.test.ts
@@ -1,9 +1,8 @@
import assert from 'node:assert/strict'
-import { test, vi } from 'vitest'
+import { test } from 'vitest'
import {
- createParentStartMarkerResolver,
electronProcessStartMarker,
parentWatchdogEnv,
spawnTag
@@ -20,43 +19,6 @@ test('electronProcessStartMarker rejects unavailable or invalid creation times',
assert.equal(electronProcessStartMarker(42, 42, 0), null)
})
-test('parent marker resolver shares and caches a successful probe', async () => {
- const load = vi.fn(async () => 'winms:1723456789123')
- const resolve = createParentStartMarkerResolver({ load })
-
- assert.deepEqual(await Promise.all([resolve(), resolve()]), ['winms:1723456789123', 'winms:1723456789123'])
- assert.equal(await resolve(), 'winms:1723456789123')
- assert.equal(load.mock.calls.length, 1)
-})
-
-test('parent marker resolver degrades a failed probe and retries later', async () => {
- const failure = new Error('powershell timed out')
-
- const load = vi
- .fn<() => Promise<string>>()
- .mockRejectedValueOnce(failure)
- .mockResolvedValueOnce('win:638908765432100000')
-
- const onError = vi.fn()
- const resolve = createParentStartMarkerResolver({ load, onError })
-
- assert.equal(await resolve(), null)
- assert.equal(await resolve(), 'win:638908765432100000')
- assert.deepEqual(onError.mock.calls, [[failure]])
- assert.equal(load.mock.calls.length, 2)
-})
-
-test('parent marker resolver reports one diagnostic for a shared failed probe', async () => {
- const failure = new Error('creation time unavailable')
- const load = vi.fn(async () => Promise.reject(failure))
- const onError = vi.fn()
- const resolve = createParentStartMarkerResolver({ load, onError })
-
- assert.deepEqual(await Promise.all([resolve(), resolve()]), [null, null])
- assert.deepEqual(onError.mock.calls, [[failure]])
- assert.equal(load.mock.calls.length, 1)
-})
-
test('parentWatchdogEnv emits an exact identity when the marker is available', () => {
assert.deepEqual(parentWatchdogEnv(42, 'winms:1723456789123', 'nonce-1'), {
HERMES_PARENT_NONCE: 'nonce-1',
diff --git a/apps/desktop/electron/parent-process-identity.ts b/apps/desktop/electron/parent-process-identity.ts
index c67010d329d..0939f55f5e9 100644
--- a/apps/desktop/electron/parent-process-identity.ts
+++ b/apps/desktop/electron/parent-process-identity.ts
@@ -8,11 +8,6 @@ export type ParentWatchdogEnv = {
HERMES_SPAWN?: string
}
-export interface ParentStartMarkerResolverOptions {
- load: () => Promise<string>
- onError?: (error: unknown) => void
-}
-
/**
* Build the cross-runtime marker for Electron's own process without spawning
* an OS helper. Electron reports milliseconds since the Unix epoch; the Python
@@ -32,37 +27,6 @@ export function electronProcessStartMarker(pid: number, ownPid: number, creation
return `winms:${milliseconds}`
}
-/** Cache a successful parent marker while allowing a transient failure to retry. */
-export function createParentStartMarkerResolver(options: ParentStartMarkerResolverOptions) {
- let cached: Promise<string> | null = null
-
- return async (): Promise<string | null> => {
- const attempt = cached ?? Promise.resolve().then(options.load)
- cached = attempt
-
- try {
- return await attempt
- } catch (error) {
- let shouldReport = false
-
- if (cached === attempt) {
- cached = null
- shouldReport = true
- }
-
- if (shouldReport) {
- try {
- options.onError?.(error)
- } catch {
- // Diagnostics must not turn an optional identity probe into a boot gate.
- }
- }
-
- return null
- }
- }
-}
-
/**
* Keep the watchdog's marker and nonce atomic. A failed marker probe degrades
* to the legacy PID-only watchdog instead of preventing the backend spawn.
diff --git a/apps/desktop/electron/source-backend.test.ts b/apps/desktop/electron/source-backend.test.ts
index 5c2fb0fad15..95e92724cd3 100644
--- a/apps/desktop/electron/source-backend.test.ts
+++ b/apps/desktop/electron/source-backend.test.ts
@@ -7,10 +7,12 @@ import path from 'node:path'
import { test, vi } from 'vitest'
import WebSocket from 'ws'
-import { serveBackendArgs } from './backend-command'
import { waitForDashboardPort } from './backend-ready'
import { createSourcePythonBackend, resolveSourceInstallationBackend, type SourceBackend } from './source-backend'
+// The argv the Desktop passes for a source-tree `hermes serve` backend.
+const SERVE_ARGS = ['serve', '--host', '127.0.0.1', '--port', '0']
+
interface Fixture {
root: string
launcher: string
@@ -133,7 +135,7 @@ test.skipIf(process.platform === 'win32')(
}
}
- const backend: SourceBackend | null = await resolveSourceInstallationBackend(fixture.root, serveBackendArgs(), {
+ const backend: SourceBackend | null = await resolveSourceInstallationBackend(fixture.root, SERVE_ARGS, {
hermesHome: env.HERMES_HOME,
env
})
@@ -198,7 +200,7 @@ test.skipIf(process.platform === 'win32')(
fs.unlinkSync(fixture.launcher)
assert.equal(
- await resolveSourceInstallationBackend(fixture.root, serveBackendArgs(), { hermesHome: env.HERMES_HOME, env }),
+ await resolveSourceInstallationBackend(fixture.root, SERVE_ARGS, { hermesHome: env.HERMES_HOME, env }),
null,
'a missing PM command must not fall back to the stale venv'
)
diff --git a/apps/desktop/electron/windows-hermes-path.ts b/apps/desktop/electron/windows-hermes-path.ts
index a48541065be..71fa7d20003 100644
--- a/apps/desktop/electron/windows-hermes-path.ts
+++ b/apps/desktop/electron/windows-hermes-path.ts
@@ -25,8 +25,7 @@
*
* Kept in a standalone ts module (no Electron imports, dependencies passed
* as parameters) so it can be unit-tested with `node --test` without
- * mocking Electron or the filesystem, same pattern as backend-probes.ts and
- * backend-command.ts.
+ * mocking Electron or the filesystem, same pattern as backend-probes.ts.
*/
/**
diff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.py
index 131c983e468..0ed8845bb1c 100644
--- a/hermes_cli/anon_auth.py
+++ b/hermes_cli/anon_auth.py
@@ -200,15 +200,15 @@ def has_guest() -> bool:
def on_local_desktop_backend() -> bool:
- """This process is the backend the desktop app spawned on this machine: never an SSH, URL or
- cloud backend, and never a gateway or shell the desktop merely launched."""
- from hermes_cli.anon_challenge import client_surface
- from hermes_cli.process_identity import is_local_desktop_backend
- return client_surface() == "desktop" and is_local_desktop_backend()
+ """This activity is work for the Desktop app on this machine: a request from, or a turn of a chat
+ created by, a connection ``process_identity.local_desktop_client`` accepted. Never an SSH, URL or
+ cloud backend, a shell the desktop launched, or the gateway's other clients."""
+ from hermes_cli.process_identity import serves_local_desktop_now
+ return serves_local_desktop_now()
def free_inference_active(state: Any = None) -> bool:
- """The welcome trial carries inference: a guest that claimed it (or was grandfathered) and guests
+ """The welcome trial carries inference: a guest that claimed it and guests
still allowed. Only the claim is the local Desktop's (``welcome_trial``); once claimed, every
surface of the install runs on it. *state* defaults to the profile's."""
state = current_nous_state() if state is None else state
@@ -501,7 +501,7 @@ def _mint_locked(client: httpx.Client, portal: str, auth_store: dict[str, Any],
"portal_base_url": portal.rstrip("/"),
"user_id": minted.get("user_id"), "org_id": minted.get("org_id"),
"idle_ttl_days": minted.get("idle_ttl_days"),
- # Always present: an absent key marks a guest minted before the claim existed (grandfathering).
+ # Always present: True only for the welcome trial's own mint.
WELCOME_CLAIM_FLAG: welcome_claim,
}
_store_provider_state(auth_store, "nous", state, set_active=False)
@@ -992,25 +992,6 @@ def set_guest_flag(flag: str) -> Optional[dict[str, Any]]:
return state
-def stamp_legacy_guest_claim() -> Optional[dict[str, Any]]:
- """Grandfathering's write (``welcome_trial.grandfather_existing_guest``): stamp the welcome claim on
- a guest minted before the key existed and publish it to the shared store, in one transaction under
- the auth-then-shared locks. Nothing is written (None) unless, inside the locks, the guest still has
- no key and the shared store is empty or holds that same guest: a sign-in another profile made is
- never overwritten, whenever it landed."""
- from hermes_cli.auth import _provider_state_transaction
- from hermes_cli.auth_nous import _nous_shared_store_lock, _read_shared_nous_state, _write_shared_nous_state
- with _provider_state_transaction("nous") as (auth_store, state, source_path), _nous_shared_store_lock():
- shared = _read_shared_nous_state()
- if (not is_guest_state(state) or source_path is None or WELCOME_CLAIM_FLAG in state
- or (shared and _shared_identity_key(shared) != _shared_identity_key(state))):
- return None
- state = {**state, WELCOME_CLAIM_FLAG: True}
- _save_guest_state(auth_store, state, source_path)
- _write_shared_nous_state(state)
- return state
-
-
def _save_guest_state(auth_store: dict[str, Any], state: dict[str, Any], source_path: Path) -> None:
"""Write the guest's ``providers.nous`` back to the store it was read from (the caller holds its lock)."""
from hermes_cli.auth import _auth_file_path, _load_auth_store, _same_path, _save_auth_store, _store_section
diff --git a/hermes_cli/free_tier_bootstrap.py b/hermes_cli/free_tier_bootstrap.py
index 8da859c8e86..aa58f7012db 100644
--- a/hermes_cli/free_tier_bootstrap.py
+++ b/hermes_cli/free_tier_bootstrap.py
@@ -1,11 +1,11 @@
-"""Serve-start record of who carries inference, for ``setup.status`` and ``setup.ready``.
-
-``hermes serve`` runs this once at boot on a daemon thread. It never creates an identity: the
-desktop's welcome-trial claim (``hermes_cli.welcome_trial``) and the first hosted connector action
-are the only creators. On the desktop's local backend it first records a fresh install's onboarding
-decision (``onboarding_run.latch_first_install``), settles a claim cut off before its marker write
-(``welcome_trial.settle_interrupted_claim``), then keeps the trial for a guest that already ran
-on the free model (``welcome_trial.grandfather_existing_guest``). Then it inventories
+"""Record of who carries inference, for ``setup.status`` and ``setup.ready``.
+
+It runs once per process on a daemon thread: at ``hermes serve`` boot, and on the gateway when the
+local Desktop first connects (``tui_gateway.methods_onboarding.begin_local_desktop_boot``). It never
+creates an identity: the desktop's welcome-trial claim (``hermes_cli.welcome_trial``) and the first
+hosted connector action are the only creators. For the desktop's local backend it first records a
+fresh install's onboarding decision (``onboarding_run.latch_first_install``) and settles a claim cut
+off before its marker write (``welcome_trial.settle_interrupted_claim``). Then it inventories
credentials cheap-first, resolves which provider carries inference, records the answer in process
memory, and tells every connected client with one ``setup.ready`` event. ``free_tier.status`` and
``setup.status`` read the record; provider resolution never reaches the portal.
@@ -207,11 +207,10 @@ def run_bootstrap(*, announce: bool = True) -> SetupRecord:
except Exception: # the next boot tries again; onboarding.state still answers live
logger.warning("onboarding: could not record the first-install decision", exc_info=True)
try:
- from hermes_cli.welcome_trial import grandfather_existing_guest, settle_interrupted_claim
+ from hermes_cli.welcome_trial import settle_interrupted_claim
settle_interrupted_claim()
- grandfather_existing_guest()
except Exception: # the record still says who carries inference without it
- logger.warning("free tier: could not check for an existing free-model guest", exc_info=True)
+ logger.warning("free tier: could not settle an interrupted claim", exc_info=True)
record = _build_record(other=_inventory_other_providers())
with _lock:
_record = record
@@ -251,7 +250,7 @@ def _broadcast(record: SetupRecord) -> None:
def start_background_bootstrap() -> threading.Thread:
- """``hermes serve`` entry: run on a daemon thread so the inventory never delays the socket."""
+ """Run on a daemon thread so the inventory never delays the socket."""
from agent.memory_provider import spawn_context_thread
thread = spawn_context_thread(run_bootstrap, name="free-tier-bootstrap")
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index e597ce70aee..fa950cc6dbb 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2536,19 +2536,8 @@ def _dashboard_sanitize_desktop_env(headless_backend) -> None:
overrides (dev / custom builds) must still work, while headless `serve`
keeps the packaged path used by the Desktop backend. Headless `serve`
re-sets HERMES_SERVE_HEADLESS itself.
-
- The Desktop's legacy fallback spawn (`dashboard --no-open`, taken when the
- `serve --help` probe times out on a cold host) is not headless yet must keep
- its packaged dist: it is told apart by the per-spawn
- HERMES_DASHBOARD_SESSION_TOKEN, which the terminal pane never receives and
- the terminal tool's env policy strips from agent children.
"""
- desktop_owned_child = _is_desktop_owned_backend()
- if (
- not headless_backend
- and not desktop_owned_child
- and _is_electron_packaged_web_dist(os.environ.get("HERMES_WEB_DIST", ""))
- ):
+ if not headless_backend and _is_electron_packaged_web_dist(os.environ.get("HERMES_WEB_DIST", "")):
os.environ.pop("HERMES_WEB_DIST", None)
if not headless_backend:
os.environ.pop("HERMES_SERVE_HEADLESS", None)
diff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.py
index 46b95d94de6..1471c81138f 100644
--- a/hermes_cli/process_identity.py
+++ b/hermes_cli/process_identity.py
@@ -313,15 +313,6 @@ def local_desktop_client(identity: Optional[dict], declared: object) -> bool:
and identity.get("native_bootstrap") is True)
-def is_local_desktop_backend() -> bool:
- """Working for the Desktop on this machine: inside a ``serving_local_desktop`` activity (the unified
- gateway), or the backend the local Desktop spawned (the pool spawn's credential, never the SSH spawn:
- its token arrives as a file on argv, and that host is another computer)."""
- if _SERVING_LOCAL_DESKTOP.get():
- return True
- return os.environ.get("HERMES_DESKTOP") == "1" and os.environ.get("HERMES_DASHBOARD_SESSION_TOKEN", "") != ""
-
-
def _desktop_spawner_identity() -> tuple[Optional[int], Optional[float]]:
"""Spawner ``(pid, create_time)`` from the Electron app's HERMES_PARENT_PID (+ optional
``winms:<ms>`` start marker) parent-death watchdog vars, so ledger lineage works with every
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 52847313c0c..9ff8bbedb0d 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -177,19 +177,6 @@ def _start_desktop_cron_ticker(stop_event: threading.Event, interval: int = 60)
_DESKTOP_MCP_DISCOVERY_DELAY_S = 1.0
-def _probe_install_before_state_db() -> None:
- from hermes_cli.anon_auth import on_local_desktop_backend
-
- if not on_local_desktop_backend():
- return
- try:
- from hermes_cli.install_state import probe
-
- probe()
- except (OSError, ValueError): # what the probe's own guards leave; onboarding.state probes again
- _log.warning("first-install check at boot failed", exc_info=True)
-
-
from hermes_cli.web_server_app import app_lifespan
diff --git a/hermes_cli/web_server_app.py b/hermes_cli/web_server_app.py
index 98099ff5774..720783bb4ec 100644
--- a/hermes_cli/web_server_app.py
+++ b/hermes_cli/web_server_app.py
@@ -30,7 +30,7 @@ async def standalone_lifespan(app: "FastAPI"):
from hermes_cli.web_server import (
_eager_reconcile_own_session_db, _warm_gateway_module,
_start_desktop_cron_ticker, _dashboard_selftest_loop,
- _auto_archive_ticker_loop, _terminate_desktop_managed_gateway, _probe_install_before_state_db,
+ _auto_archive_ticker_loop, _terminate_desktop_managed_gateway,
)
from hermes_cli.web_server_chat import PTY_REGISTRY
@@ -52,10 +52,6 @@ async def standalone_lifespan(app: "FastAPI"):
# connection closed from the main thread mid-probe (pytest's leaked-DB
# sweep) and segfaulted the interpreter. The worker is time-bounded by
# SessionDB's lock patience, so the join cannot hang shutdown.
- # The first-install check reads the default root's state.db: on the desktop's own backend it runs
- # before this process starts creating or healing that database, and its answer is kept.
- _probe_install_before_state_db()
-
eager_reconcile_thread = threading.Thread(
target=_eager_reconcile_own_session_db,
name="statedb-eager-reconcile",
@@ -162,9 +158,6 @@ async def standalone_lifespan(app: "FastAPI"):
from hermes_cli.free_tier_bootstrap import start_background_bootstrap
start_background_bootstrap()
- # The desktop's onboarding due answer, worked out after that bootstrap and before it is asked.
- # Through the server: methods_* functions run with the server's globals (``bind_module``).
- tui_gateway.server.start_due_boot()
try:
yield
diff --git a/hermes_cli/welcome_trial.py b/hermes_cli/welcome_trial.py
index 0a52005bfff..5571724380c 100644
--- a/hermes_cli/welcome_trial.py
+++ b/hermes_cli/welcome_trial.py
@@ -8,18 +8,14 @@ a separate first install. A claim that is lost later (the guest is reaped, ``aut
deleted, the user signs in) is never made again: that user lands on provider setup and sign-in like
anyone else.
-Guests that ran on the free model before the claim existed keep it (:func:`grandfather_existing_guest`).
Enforcement is client-side; the account service's own entitlement check follows separately.
"""
from __future__ import annotations
-import contextlib
import logging
from dataclasses import dataclass
-import sqlite3
from collections.abc import Callable
-from pathlib import Path
from typing import Any, Optional
from hermes_cli import anon_auth
@@ -129,40 +125,3 @@ def settle_interrupted_claim() -> bool:
return True
-def grandfather_existing_guest() -> bool:
- """A guest from before the claim existed keeps the free model when this home already chatted on
- it. Only a guest with no ``welcome_claim`` key qualifies: every guest minted since carries the
- key, so a connector guest (``False``) never does. Records the claim once; True when it did."""
- if not anon_auth.on_local_desktop_backend():
- return False
- state = anon_auth.current_nous_state()
- if not anon_auth.is_guest_state(state) or anon_auth.WELCOME_CLAIM_FLAG in state:
- return False
- from hermes_constants import get_default_hermes_root, get_hermes_home
-
- homes = dict.fromkeys((get_hermes_home(), get_default_hermes_root()))
- if not any(_chatted_on_welcome(home / "state.db") for home in homes):
- return False
- from hermes_cli.install_state import mark_machine_used
-
- if anon_auth.stamp_legacy_guest_claim() is None: # re-checked under the locks, against shared auth
- return False
- mark_machine_used()
- logger.info("Nous free tier: existing free-model guest kept its trial")
- return True
-
-
-def _chatted_on_welcome(db: Path) -> bool:
- """A session on the free model with at least one message. Read-only; a missing or unreadable
- database is no."""
- if not db.is_file():
- return False
- try:
- with contextlib.closing(sqlite3.connect(f"{db.as_uri()}?mode=ro", uri=True, timeout=1)) as conn:
- row = conn.execute(
- "SELECT 1 FROM sessions s WHERE s.model = ? "
- "AND EXISTS (SELECT 1 FROM messages m WHERE m.session_id = s.id) LIMIT 1",
- (anon_auth.GUEST_MODEL,)).fetchone()
- except sqlite3.Error:
- return False
- return row is not None
diff --git a/tests/agent/test_credential_pool_connectors_guest.py b/tests/agent/test_credential_pool_connectors_guest.py
index 939cfef82ae..531d522cc40 100644
--- a/tests/agent/test_credential_pool_connectors_guest.py
+++ b/tests/agent/test_credential_pool_connectors_guest.py
@@ -6,7 +6,7 @@ drop that row instead of handing its welcome-host token to the runtime.
"""
from hermes_cli import anon_auth
-from tests.hermes_cli.anon_portal import claimed_trial, install_portal
+from tests.hermes_cli.anon_portal import claimed_trial, install_portal, off_local_desktop
def test_a_claimed_guest_pool_row_serves_every_surface(monkeypatch, tmp_path):
@@ -18,6 +18,6 @@ def test_a_claimed_guest_pool_row_serves_every_surface(monkeypatch, tmp_path):
resolve_nous_runtime_credentials() # the claimed guest now carries an inference token
assert any(e.source == "device_code" for e in load_pool("nous").entries())
- monkeypatch.delenv("HERMES_DESKTOP") # cron, the CLI, a side agent: not the Desktop
+ off_local_desktop(monkeypatch) # cron, the CLI, a side agent: not the Desktop
assert any(e.source == "device_code" for e in load_pool("nous").entries())
diff --git a/tests/hermes_cli/anon_portal.py b/tests/hermes_cli/anon_portal.py
index 81180e2e4b9..9eb149f9b0a 100644
--- a/tests/hermes_cli/anon_portal.py
+++ b/tests/hermes_cli/anon_portal.py
@@ -148,9 +148,18 @@ def install_portal(monkeypatch, tmp_path, fake: FakePortal | None = None) -> Fak
def as_local_desktop_backend(monkeypatch) -> None:
- """This process is the backend the desktop spawned on this machine (the local spawn's credential)."""
- monkeypatch.setenv("HERMES_DESKTOP", "1")
- monkeypatch.setenv("HERMES_DASHBOARD_SESSION_TOKEN", "test-spawn-token")
+ """Every activity in this test is work for the local Desktop (``process_identity.serving_local_desktop``),
+ threads included."""
+ from contextvars import ContextVar
+ from hermes_cli import process_identity
+ monkeypatch.setattr(process_identity, "_SERVING_LOCAL_DESKTOP", ContextVar("serving_local_desktop_test", default=True))
+
+
+def off_local_desktop(monkeypatch) -> None:
+ """From here on the activity is not the local Desktop's: a CLI shell beside it, another client."""
+ from contextvars import ContextVar
+ from hermes_cli import process_identity
+ monkeypatch.setattr(process_identity, "_SERVING_LOCAL_DESKTOP", ContextVar("serving_local_desktop_test", default=False))
def claimed_trial(monkeypatch) -> dict:
diff --git a/tests/hermes_cli/test_anon_auth_core.py b/tests/hermes_cli/test_anon_auth_core.py
index ce3b9cbe0f4..c66f84dfaa7 100644
--- a/tests/hermes_cli/test_anon_auth_core.py
+++ b/tests/hermes_cli/test_anon_auth_core.py
@@ -16,7 +16,7 @@ import pytest
from hermes_cli import anon_auth
from hermes_cli.auth import _load_auth_store, resolve_provider
-from tests.hermes_cli.anon_portal import PORTAL, WELCOME, claimed_trial, install_portal, make_jwt as _jwt
+from tests.hermes_cli.anon_portal import PORTAL, WELCOME, claimed_trial, install_portal, make_jwt as _jwt, off_local_desktop
@pytest.fixture
@@ -90,7 +90,7 @@ class TestIdentityLifecycle:
def test_a_claimed_trial_carries_inference_on_every_surface(self, portal, monkeypatch):
claimed_trial(monkeypatch)
- monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN") # a CLI shell beside the desktop
+ off_local_desktop(monkeypatch) # a CLI shell beside the desktop
assert anon_auth.free_inference_active() is True
assert resolve_provider("auto") == "nous"
diff --git a/tests/hermes_cli/test_anon_surfaces.py b/tests/hermes_cli/test_anon_surfaces.py
index fe25177ebcc..82599261fcc 100644
--- a/tests/hermes_cli/test_anon_surfaces.py
+++ b/tests/hermes_cli/test_anon_surfaces.py
@@ -28,7 +28,7 @@ from hermes_cli import (
)
from hermes_cli.auth import _load_auth_store
from hermes_constants import get_hermes_home
-from tests.hermes_cli.anon_portal import as_local_desktop_backend
+from tests.hermes_cli.anon_portal import as_local_desktop_backend, off_local_desktop
WELCOME = "https://welcome-api.nousresearch.com/v1"
# Words that must never appear on a user-facing free-tier surface.
@@ -214,8 +214,7 @@ def test_the_paid_tool_notice_switches_wording_inside_a_chat():
def test_a_claimed_guest_reads_as_the_free_tier_on_the_cli_too(isolated_store, monkeypatch, capsys):
"""Once the Desktop claimed the trial, the CLI runs on it as well."""
- monkeypatch.delenv("HERMES_DESKTOP", raising=False)
- monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)
+ off_local_desktop(monkeypatch)
_write_auth(_guest_state())
auth_commands.auth_status_command(SimpleNamespace(provider="nous"))
diff --git a/tests/hermes_cli/test_dashboard_web_dist_validation.py b/tests/hermes_cli/test_dashboard_web_dist_validation.py
index b4e9c772ddf..3717677e99d 100644
--- a/tests/hermes_cli/test_dashboard_web_dist_validation.py
+++ b/tests/hermes_cli/test_dashboard_web_dist_validation.py
@@ -165,17 +165,3 @@ def test_desktop_headless_serve_keeps_packaged_renderer(main_mod, monkeypatch):
main_mod._dashboard_sanitize_desktop_env(headless_backend=True)
assert os.environ["HERMES_WEB_DIST"] == packaged
-
-
-def test_desktop_owned_fallback_dashboard_keeps_packaged_renderer(main_mod, monkeypatch):
- """The Desktop's own legacy `dashboard --no-open` fallback spawn (serve probe
- timed out) is not headless but carries the per-spawn session token; stripping
- its dist would send a packaged install into `_build_web_ui(fatal=True)`."""
- packaged = "/Applications/Hermes.app/Contents/Resources/app.asar.unpacked/dist"
- monkeypatch.setenv("HERMES_DESKTOP", "1")
- monkeypatch.setenv("HERMES_DASHBOARD_SESSION_TOKEN", "desktop-spawn-token")
- monkeypatch.setenv("HERMES_WEB_DIST", packaged)
-
- main_mod._dashboard_sanitize_desktop_env(headless_backend=False)
-
- assert os.environ["HERMES_WEB_DIST"] == packaged
diff --git a/tests/hermes_cli/test_provider_precedence.py b/tests/hermes_cli/test_provider_precedence.py
index 323a204f384..2ae1f70ea86 100644
--- a/tests/hermes_cli/test_provider_precedence.py
+++ b/tests/hermes_cli/test_provider_precedence.py
@@ -127,9 +127,9 @@ class TestFreeTierBeatsImplicitHostCredentials:
assert resolve_provider("auto") == expected
def test_on_the_cli_surface_a_claimed_guest_still_beats_host_credentials(self, portal, monkeypatch):
+ from tests.hermes_cli.anon_portal import off_local_desktop
_claimed_trial_with_aws(monkeypatch)
- monkeypatch.delenv("HERMES_DESKTOP", raising=False)
- monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)
+ off_local_desktop(monkeypatch)
assert resolve_provider("auto") == "nous"
def test_skip_free_tier_answers_what_else_would_carry_inference(self, portal, monkeypatch):
diff --git a/tests/hermes_cli/test_web_server_boot_handshake.py b/tests/hermes_cli/test_web_server_boot_handshake.py
index 39ef9ad9b59..38f90279e60 100644
--- a/tests/hermes_cli/test_web_server_boot_handshake.py
+++ b/tests/hermes_cli/test_web_server_boot_handshake.py
@@ -64,20 +64,17 @@ def test_lifespan_warmup_is_synchronous(monkeypatch):
def test_lifespan_enters_and_exits_as_an_async_context_manager(monkeypatch):
"""FastAPI gets ``app_lifespan`` as an async context manager, never a bare async generator
- (Starlette's deprecated path), and entering it runs the desktop's first-install check."""
- from hermes_cli import anon_auth, install_state
-
- probed: list[bool] = []
+ (Starlette's deprecated path)."""
+ entered: list[bool] = []
monkeypatch.setattr(web_server_mod, "_warm_gateway_module", lambda: None)
monkeypatch.setattr(web_server_mod, "_eager_reconcile_own_session_db", lambda: None)
- monkeypatch.setattr(anon_auth, "on_local_desktop_backend", lambda: True)
- monkeypatch.setattr(install_state, "probe", lambda: probed.append(True))
async def _run() -> None:
async with web_server_mod.app_lifespan(web_server_mod.app):
- assert probed == [True]
+ entered.append(True)
asyncio.run(_run())
+ assert entered == [True]
def test_hosted_room_recovery_cannot_block_or_abort_backend_startup(monkeypatch):
diff --git a/tests/hermes_cli/test_welcome_trial.py b/tests/hermes_cli/test_welcome_trial.py
index de394eee8e0..93ce23b74c1 100644
--- a/tests/hermes_cli/test_welcome_trial.py
+++ b/tests/hermes_cli/test_welcome_trial.py
@@ -6,7 +6,7 @@ import contextlib
import pytest
from hermes_cli import anon_auth, install_state, welcome_trial
-from tests.hermes_cli.anon_portal import as_local_desktop_backend, claimed_trial, install_portal
+from tests.hermes_cli.anon_portal import as_local_desktop_backend, claimed_trial, install_portal, off_local_desktop
@pytest.fixture
@@ -70,7 +70,7 @@ def test_a_connector_guest_neither_claims_nor_carries_inference(portal, monkeypa
def test_a_claimed_trial_carries_inference_outside_the_desktop_too(portal, monkeypatch):
state = claimed_trial(monkeypatch)
- monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN") # the same home, read by a CLI process
+ off_local_desktop(monkeypatch) # the same home, read by a CLI process
assert anon_auth.free_inference_active()
assert not anon_auth.guest_without_free_tier(state)
@@ -85,48 +85,6 @@ def _chat(db_path, model: str) -> None:
db.close()
-def _legacy_guest() -> None:
- """A guest minted before the claim existed: no welcome_claim key at all, in either store."""
- from hermes_cli.auth import _load_auth_store, _load_provider_state, _save_auth_store, _store_provider_state
- from hermes_cli.auth_nous import _write_shared_nous_state
-
- anon_auth.ensure_portal_identity(explicit=True)
- store = _load_auth_store()
- state = dict(_load_provider_state(store, "nous"))
- state.pop(anon_auth.WELCOME_CLAIM_FLAG, None)
- _store_provider_state(store, "nous", state, set_active=False)
- _save_auth_store(store)
- _write_shared_nous_state(state)
-
-
[email protected](("model", "kept"), [(anon_auth.GUEST_MODEL, True), ("anthropic/claude", False)])
-def test_a_guest_that_chatted_on_the_free_model_keeps_it(portal, monkeypatch, model, kept):
- from hermes_constants import get_hermes_home
-
- as_local_desktop_backend(monkeypatch)
- _legacy_guest() # grandfathering is only for guests minted before the key existed
- _chat(get_hermes_home() / "state.db", model)
-
- assert welcome_trial.grandfather_existing_guest() is kept
- assert anon_auth.free_inference_active() is kept
-
-
-def test_grandfathering_never_overwrites_a_sign_in_from_another_profile(portal, monkeypatch):
- from hermes_cli.auth_nous import _read_shared_nous_state, _write_shared_nous_state
- from hermes_constants import get_hermes_home
- from tests.hermes_cli.anon_portal import PORTAL
-
- as_local_desktop_backend(monkeypatch)
- _legacy_guest() # this profile still holds the old guest
- _chat(get_hermes_home() / "state.db", anon_auth.GUEST_MODEL)
- _write_shared_nous_state({"auth_method": "oauth_device_code", "portal_base_url": PORTAL,
- "access_token": "at-signed-in", "refresh_token": "rt-signed-in"})
-
- assert welcome_trial.grandfather_existing_guest() is False
- assert _read_shared_nous_state()["refresh_token"] == "rt-signed-in"
- assert anon_auth.WELCOME_CLAIM_FLAG not in anon_auth.current_nous_state()
-
-
def test_a_lost_claim_is_not_replaced(portal, monkeypatch):
claimed_trial(monkeypatch)
anon_auth.clear_dead_guest("anon_credential_dead")
@@ -135,33 +93,19 @@ def test_a_lost_claim_is_not_replaced(portal, monkeypatch):
assert portal.creates() == 1
-def test_a_reaped_claimant_replaced_by_a_connector_guest_is_not_grandfathered(portal, monkeypatch):
- from hermes_constants import get_hermes_home
-
- claimed_trial(monkeypatch)
- _chat(get_hermes_home() / "state.db", anon_auth.GUEST_MODEL)
- anon_auth.clear_dead_guest("anon_credential_dead")
- anon_auth.ensure_portal_identity(explicit=True) # a connector action mints the replacement
-
- assert welcome_trial.grandfather_existing_guest() is False
- assert not anon_auth.free_inference_active()
-
-
-def test_a_connector_guest_adopted_from_the_shared_store_is_not_grandfathered(portal, monkeypatch):
+def test_a_connector_guest_adopted_from_the_shared_store_carries_no_trial(portal, monkeypatch):
from hermes_cli.auth import _load_auth_store, _save_auth_store
- from hermes_constants import get_hermes_home
as_local_desktop_backend(monkeypatch)
anon_auth.ensure_portal_identity(explicit=True) # connector mint: welcome_claim False, mirrored
store = _load_auth_store()
store["providers"].pop("nous") # a profile whose own identity differs adopts the shared one
_save_auth_store(store)
- _chat(get_hermes_home() / "state.db", anon_auth.GUEST_MODEL)
adopted = anon_auth.ensure_portal_identity(explicit=True)
assert adopted[anon_auth.WELCOME_CLAIM_FLAG] is False
- assert welcome_trial.grandfather_existing_guest() is False
+ assert not anon_auth.free_inference_active()
assert portal.creates() == 1
@@ -189,7 +133,6 @@ def test_a_lost_trial_is_never_claimed_again_after_a_relaunch(portal, monkeypatc
assert welcome_trial.claim_desktop_free_tier() is None
assert portal.creates() == creates
- assert welcome_trial.grandfather_existing_guest() is False
assert not anon_auth.free_inference_active()
with pytest.raises(AuthError):
resolve_provider("auto")
diff --git a/tui_gateway/methods_onboarding.py b/tui_gateway/methods_onboarding.py
index babdf88f338..4ff53f659dc 100644
--- a/tui_gateway/methods_onboarding.py
+++ b/tui_gateway/methods_onboarding.py
@@ -86,14 +86,11 @@ def _stat(path):
def start_due_boot() -> None:
- """Serve boot, desktop's local backend: work out the due answer off the RPC path, after the setup
- bootstrap has recorded a fresh install and kept an existing guest's trial."""
+ """Work out the local Desktop's due answer off the RPC path, after the setup bootstrap has recorded
+ a fresh install (``begin_local_desktop_boot``)."""
from agent.memory_provider import spawn_context_thread
from hermes_cli import free_tier_bootstrap, onboarding_due
- from hermes_cli.anon_auth import on_local_desktop_backend
- if not on_local_desktop_backend():
- return
finish = onboarding_due.begin_boot(_due_stamp)
def compute() -> dict[str, bool]: