Skip to content

The agent that grows with you

fix(desktop): avoid PowerShell parent marker boot gate

yu-xin-cc3d74603aa31
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index e43ba19f288..38ccf1eb093 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -207,6 +207,11 @@ import {
import { runNativeLogin } from './native-oauth-login'
import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } from './native-token-store'
import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
+import {
+ createParentStartMarkerResolver,
+ electronProcessStartMarker,
+ parentWatchdogEnv
+} from './parent-process-identity'
import { createKeepAwake } from './power-save'
import { FirstRunSetupResetError, runPrimaryBackendStartup } from './primary-backend-startup'
import { rehomePrimaryConnection } from './primary-connection-rehome'
@@ -2986,6 +2991,15 @@ async function processStartMarker(pid) {
}
if (IS_WINDOWS) {
+ const electronMarker =
+ pid === process.pid
+ ? electronProcessStartMarker(pid, process.pid, process.getCreationTime?.())
+ : null
+
+ if (electronMarker) {
+ return electronMarker
+ }
+
const ticks = await execText('powershell.exe', [
'-NoProfile',
'-NonInteractive',
@@ -3127,13 +3141,16 @@ const backendOwnership = createBackendOwnership({
}
})
-let desktopParentStartMarkerPromise = null
-
-function desktopParentStartMarker() {
- desktopParentStartMarkerPromise ??= processStartMarker(process.pid)
+const desktopParentStartMarker = createParentStartMarkerResolver({
+ load: () => processStartMarker(process.pid),
+ onError: error => {
+ const detail = error instanceof Error ? error.message : String(error)
- return desktopParentStartMarkerPromise
-}
+ rememberLog(
+ `Could not resolve the Desktop process start marker; starting the backend with PID-only parent tracking: ${detail}`
+ )
+ }
+})
async function claimBackendChild(child, command, profile, nonce) {
try {
@@ -9517,6 +9534,7 @@ async function spawnPoolBackend(profile, entry) {
const parentStartMarker = await desktopParentStartMarker()
const backendNonce = crypto.randomBytes(16).toString('hex')
+ const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)
const child = spawn(
backend.command,
@@ -9536,10 +9554,9 @@ async function spawnPoolBackend(profile, entry) {
// scheduler tick loop (the gateway isn't running under the app).
HERMES_DESKTOP: '1',
// Exact parent identity lets the backend self-exit after an unclean
- // Desktop death without mistaking a reused PID for its owner.
- HERMES_PARENT_PID: String(process.pid),
- HERMES_PARENT_START_MARKER: parentStartMarker,
- HERMES_PARENT_NONCE: backendNonce,
+ // Desktop death without mistaking a reused PID for its owner. If the
+ // optional marker probe fails, retain legacy PID-only tracking.
+ ...parentIdentityEnv,
HERMES_WEB_DIST: webDist,
...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
},
@@ -9848,6 +9865,7 @@ async function startHermes() {
const profile = primaryProfileKey()
const parentStartMarker = await desktopParentStartMarker()
const backendNonce = crypto.randomBytes(16).toString('hex')
+ const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)
const hermesProcess = spawn(
backend.command,
@@ -9872,10 +9890,9 @@ async function startHermes() {
// scheduler tick loop (the gateway isn't running under the app).
HERMES_DESKTOP: '1',
// Exact parent identity lets the backend self-exit after an unclean
- // Desktop death without mistaking a reused PID for its owner.
- HERMES_PARENT_PID: String(process.pid),
- HERMES_PARENT_START_MARKER: parentStartMarker,
- HERMES_PARENT_NONCE: backendNonce,
+ // Desktop death without mistaking a reused PID for its owner. If the
+ // optional marker probe fails, retain legacy PID-only tracking.
+ ...parentIdentityEnv,
HERMES_WEB_DIST: webDist,
...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
},
diff --git a/apps/desktop/electron/parent-process-identity.test.ts b/apps/desktop/electron/parent-process-identity.test.ts
new file mode 100644
index 00000000000..107f1825a46
--- /dev/null
+++ b/apps/desktop/electron/parent-process-identity.test.ts
@@ -0,0 +1,75 @@
+import assert from 'node:assert/strict'
+
+import { test, vi } from 'vitest'
+
+import {
+ createParentStartMarkerResolver,
+ electronProcessStartMarker,
+ parentWatchdogEnv
+} from './parent-process-identity'
+
+test('electronProcessStartMarker uses Electron creation time only for its own PID', () => {
+ assert.equal(electronProcessStartMarker(42, 42, 1_723_456_789_123.75), 'winms:1723456789123')
+ assert.equal(electronProcessStartMarker(43, 42, 1_723_456_789_123), null)
+})
+
+test('electronProcessStartMarker rejects unavailable or invalid creation times', () => {
+ assert.equal(electronProcessStartMarker(42, 42, null), null)
+ assert.equal(electronProcessStartMarker(42, 42, Number.NaN), null)
+ 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',
+ HERMES_PARENT_PID: '42',
+ HERMES_PARENT_START_MARKER: 'winms:1723456789123'
+ })
+})
+
+test('parentWatchdogEnv atomically falls back to PID-only identity', () => {
+ assert.deepEqual(parentWatchdogEnv(42, null, 'unused-nonce'), {
+ HERMES_PARENT_PID: '42'
+ })
+ assert.throws(() => parentWatchdogEnv(42, '', 'nonce-1'), /marker and nonce must be non-empty/)
+ assert.throws(() => parentWatchdogEnv(42, 'winms:1723456789123', ''), /marker and nonce must be non-empty/)
+})
diff --git a/apps/desktop/electron/parent-process-identity.ts b/apps/desktop/electron/parent-process-identity.ts
new file mode 100644
index 00000000000..954a8901200
--- /dev/null
+++ b/apps/desktop/electron/parent-process-identity.ts
@@ -0,0 +1,89 @@
+export type ParentWatchdogEnv = {
+ HERMES_PARENT_PID: string
+ HERMES_PARENT_START_MARKER?: string
+ HERMES_PARENT_NONCE?: 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
+ * watchdog converts its exact Windows FILETIME to the same representation.
+ */
+export function electronProcessStartMarker(
+ pid: number,
+ ownPid: number,
+ creationTime: unknown
+): string | null {
+ if (pid !== ownPid || typeof creationTime !== 'number' || !Number.isFinite(creationTime)) {
+ return null
+ }
+
+ const milliseconds = Math.trunc(creationTime)
+
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {
+ return null
+ }
+
+ 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.
+ */
+export function parentWatchdogEnv(pid: number, startMarker: string | null, nonce: string): ParentWatchdogEnv {
+ if (!Number.isInteger(pid) || pid <= 0) {
+ throw new Error('Parent watchdog requires a positive process ID.')
+ }
+
+ const env: ParentWatchdogEnv = { HERMES_PARENT_PID: String(pid) }
+
+ if (startMarker === null) {
+ return env
+ }
+
+ if (!startMarker || !nonce) {
+ throw new Error('Parent watchdog marker and nonce must be non-empty.')
+ }
+
+ env.HERMES_PARENT_START_MARKER = startMarker
+ env.HERMES_PARENT_NONCE = nonce
+
+ return env
+}
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index b3048cc1e6b..2cc53ece62d 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -220,11 +220,35 @@ def _valid_parent_start_marker(marker: str) -> bool:
prefix, separator, value = marker.partition(":")
if not separator or not value or value != value.strip():
return False
- if prefix in ("linux", "win"):
+ if prefix in ("linux", "win", "winms"):
return value.isdigit()
return prefix == "ps"
+def _parent_start_markers_match(actual: str, expected: str) -> bool:
+ """Compare parent markers across Desktop protocol generations.
+
+ Older Windows Desktop builds send .NET ticks (``win:``). New builds use
+ Electron's native process creation time in Unix milliseconds (``winms:``)
+ so startup does not need to launch PowerShell. The backend still reads the
+ exact FILETIME and normalizes it only when the expected marker is ``winms``.
+ """
+ if actual == expected:
+ return True
+ if not actual.startswith("win:") or not expected.startswith("winms:"):
+ return False
+
+ try:
+ dotnet_ticks = int(actual.removeprefix("win:"))
+ expected_unix_ms = int(expected.removeprefix("winms:"))
+ except ValueError:
+ return False
+
+ dotnet_ticks_at_unix_epoch = 621_355_968_000_000_000
+ actual_unix_ms = (dotnet_ticks - dotnet_ticks_at_unix_epoch) // 10_000
+ return actual_unix_ms == expected_unix_ms
+
+
# ---------------------------------------------------------------------------
# Per-channel subscriber registry used by /api/pub (PTY-side gateway → dashboard)
# and /api/events (dashboard → browser sidebar). Keyed by an opaque channel id
@@ -18277,7 +18301,9 @@ def _is_serve_orphaned(
try:
if expected_start_marker is not None:
probe = process_start_marker or _process_start_marker
- return probe(int(desktop_pid)) != expected_start_marker
+ return not _parent_start_markers_match(
+ probe(int(desktop_pid)), expected_start_marker
+ )
if pid_exists is None:
from gateway.status import _pid_exists
diff --git a/tests/hermes_cli/test_serve_parent_watchdog.py b/tests/hermes_cli/test_serve_parent_watchdog.py
index 81d6e990464..102fad4f858 100644
--- a/tests/hermes_cli/test_serve_parent_watchdog.py
+++ b/tests/hermes_cli/test_serve_parent_watchdog.py
@@ -1,6 +1,6 @@
"""Regression tests for Desktop-owned ``hermes serve`` lifecycle tracking."""
-from hermes_cli.web_server import _is_serve_orphaned
+from hermes_cli.web_server import _is_serve_orphaned, _valid_parent_start_marker
def test_parent_watchdog_tracks_recorded_desktop_pid_not_immediate_ppid():
@@ -15,3 +15,45 @@ def test_parent_watchdog_fails_safe_when_liveness_probe_errors():
raise OSError("process table temporarily unavailable")
assert _is_serve_orphaned(4242, pid_exists=broken_probe) is False
+
+
+def test_parent_watchdog_accepts_electron_windows_creation_time_marker():
+ unix_ms = 1_723_456_789_123
+ dotnet_ticks = 621_355_968_000_000_000 + unix_ms * 10_000 + 9_999
+
+ assert _valid_parent_start_marker(f"winms:{unix_ms}") is True
+ assert (
+ _is_serve_orphaned(
+ 4242,
+ f"winms:{unix_ms}",
+ process_start_marker=lambda _pid: f"win:{dotnet_ticks}",
+ )
+ is False
+ )
+
+
+def test_parent_watchdog_rejects_reused_pid_with_different_windows_creation_time():
+ unix_ms = 1_723_456_789_123
+ next_process_ticks = 621_355_968_000_000_000 + (unix_ms + 1) * 10_000
+
+ assert (
+ _is_serve_orphaned(
+ 4242,
+ f"winms:{unix_ms}",
+ process_start_marker=lambda _pid: f"win:{next_process_ticks}",
+ )
+ is True
+ )
+
+
+def test_parent_watchdog_preserves_legacy_exact_windows_marker():
+ marker = "win:638908765432109876"
+
+ assert (
+ _is_serve_orphaned(
+ 4242,
+ marker,
+ process_start_marker=lambda _pid: marker,
+ )
+ is False
+ )