feat: attach Desktop local launches to canonical gateway
This commit is contained in:
24
apps/desktop/electron/local-gateway.test.ts
Normal file
24
apps/desktop/electron/local-gateway.test.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { test, expect } from 'vitest'
|
||||
import { ensureLocalGateway, createLocalGatewayDials } from './local-gateway'
|
||||
|
||||
test('ensure consumes structured readiness without acquiring a child owner', async () => {
|
||||
const endpoint = { profile_id: '/private/profile', instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
|
||||
const connection = await ensureLocalGateway(async () => ({ code: 0, stdout: JSON.stringify({ state: 'ready', endpoint }) }))
|
||||
expect(connection.baseUrl).toBe(endpoint.api_origin)
|
||||
expect(connection.gatewayEndpoint).toEqual(endpoint)
|
||||
expect(connection).not.toHaveProperty('process')
|
||||
expect(connection.token).toBe('')
|
||||
await expect(ensureLocalGateway(async () => ({ code: 5, stdout: JSON.stringify({ state: 'starting', reason_code: 'deadline' }) }))).rejects.toThrow('starting')
|
||||
})
|
||||
|
||||
test('private dial credential is one-use and bound to the requesting native window', () => {
|
||||
const dials = createLocalGatewayDials()
|
||||
const url = dials.prepare('http://127.0.0.1:1234', 'private-ticket', 7)
|
||||
expect(url).not.toContain('private-ticket')
|
||||
const details = { url, webContentsId: 8, resourceType: 'webSocket', requestHeaders: { Origin: 'http://renderer', 'Sec-WebSocket-Protocol': 'hermes-gateway-v1' } }
|
||||
expect(dials.headers(details)).toBeNull()
|
||||
const headers = dials.headers({ ...details, webContentsId: 7 })!
|
||||
expect(headers).not.toHaveProperty('Origin')
|
||||
expect(headers['Sec-WebSocket-Protocol']).toBe('hermes-gateway-v1, hermes-gateway-ticket.private-ticket')
|
||||
expect(dials.headers({ ...details, webContentsId: 7 })).toBeNull()
|
||||
})
|
||||
117
apps/desktop/electron/local-gateway.ts
Normal file
117
apps/desktop/electron/local-gateway.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import crypto from 'node:crypto'
|
||||
import { hiddenWindowsChildOptions } from './windows-child-options'
|
||||
|
||||
export function runGatewayEnsure(backend, cwd: string, home: string): Promise<{ code: number; stdout: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(backend.command, backend.args, hiddenWindowsChildOptions({ cwd, env: { ...process.env, HERMES_HOME: home, ...backend.env }, shell: backend.shell, stdio: ['ignore', 'pipe', 'pipe'] }))
|
||||
let stdout = ''
|
||||
// Only the bounded ensure client is ours. Never retain/kill its detached owner.
|
||||
const timer = setTimeout(() => child.kill(), 40_000)
|
||||
child.stdout.on('data', data => { stdout += data.toString(); if (stdout.length > 65536) child.kill() })
|
||||
child.stderr.resume()
|
||||
child.on('error', () => { clearTimeout(timer); reject(new Error('Could not run hermes gateway ensure')) })
|
||||
child.on('close', code => { clearTimeout(timer); resolve({ code: code ?? 7, stdout }) })
|
||||
})
|
||||
}
|
||||
import fs from 'node:fs/promises'
|
||||
import net from 'node:net'
|
||||
import path from 'node:path'
|
||||
|
||||
export interface GatewayEndpoint {
|
||||
profile_id: string
|
||||
instance_id: string
|
||||
authority_epoch: number
|
||||
runtime_protocol: number
|
||||
api_origin: string
|
||||
capabilities: string[]
|
||||
supervisor: string
|
||||
}
|
||||
|
||||
export async function ensureLocalGateway(run: () => Promise<{ code: number; stdout: string }>) {
|
||||
const result = await run()
|
||||
const payload = JSON.parse(result.stdout)
|
||||
if (result.code !== 0 || payload.state !== 'ready') {
|
||||
throw new Error(`Gateway ${payload.state || 'inaccessible'} (${payload.reason_code || 'ensure_failed'}). Use hermes gateway status for recovery.`)
|
||||
}
|
||||
const endpoint: GatewayEndpoint = payload.endpoint
|
||||
const origin = new URL(endpoint.api_origin)
|
||||
if (!['http:', 'https:'].includes(origin.protocol) || !['127.0.0.1', '[::1]'].includes(origin.hostname)
|
||||
|| origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash
|
||||
|| !origin.port || endpoint.runtime_protocol !== 1 || !endpoint.instance_id || !endpoint.profile_id
|
||||
|| !endpoint.capabilities.includes('session-authority-v1')) {
|
||||
throw new Error('Invalid local gateway endpoint')
|
||||
}
|
||||
return { baseUrl: endpoint.api_origin, wsUrl: `${endpoint.api_origin.replace(/^http/, 'ws')}/api/ws?native_dial=unminted`, mode: 'local', source: 'local', authMode: 'native', token: '', gatewayEndpoint: endpoint }
|
||||
}
|
||||
|
||||
// Credentials never enter public descriptors, logs, renderer URLs or persisted state.
|
||||
export function createLocalGatewayDials() {
|
||||
const pending = new Map<string, { ticket: string; webContentsId: number; expires: number }>()
|
||||
return {
|
||||
prepare(origin: string, ticket: string, webContentsId: number) {
|
||||
for (const [key, value] of pending) if (value.expires <= Date.now()) pending.delete(key)
|
||||
if (pending.size >= 100) throw new Error('Too many pending gateway dials')
|
||||
const url = `${origin.replace(/^http/, 'ws')}/api/ws?native_dial=${crypto.randomUUID()}`
|
||||
pending.set(url, { ticket, webContentsId, expires: Date.now() + 25_000 })
|
||||
return url
|
||||
},
|
||||
headers(details: { url: string; webContentsId?: number; resourceType: string; requestHeaders?: Record<string, string> }) {
|
||||
const grant = pending.get(details.url)
|
||||
if (!grant || grant.webContentsId !== details.webContentsId || details.resourceType !== 'webSocket') return null
|
||||
pending.delete(details.url)
|
||||
if (grant.expires <= Date.now()) return null
|
||||
const headers = { ...details.requestHeaders }
|
||||
for (const key of Object.keys(headers)) if (['origin', 'sec-websocket-protocol'].includes(key.toLowerCase())) delete headers[key]
|
||||
headers['Sec-WebSocket-Protocol'] = `hermes-gateway-v1, hermes-gateway-ticket.${grant.ticket}`
|
||||
return headers
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function privateNode(file: string, kind: 'directory' | 'socket' | 'file') {
|
||||
const node = await fs.lstat(file)
|
||||
const valid = { directory: node.isDirectory(), socket: node.isSocket(), file: node.isFile() }[kind]
|
||||
if (!valid || node.uid !== process.getuid?.() || (node.mode & 0o077)) throw new Error('Unsafe gateway control path')
|
||||
}
|
||||
|
||||
export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint): Promise<string> {
|
||||
// Named-pipe bootstrap needs the same server-identity validation as Python's
|
||||
// native bootstrap. Refuse rather than silently use an unauthenticated pipe.
|
||||
if (process.platform === 'win32') throw new Error('Native gateway bootstrap on Windows requires the validated named-pipe client')
|
||||
const home = endpoint.profile_id
|
||||
if (await fs.realpath(home) !== home) throw new Error('Noncanonical gateway profile')
|
||||
await privateNode(home, 'directory')
|
||||
let socketPath = path.join(home, 'gateway.sock')
|
||||
try { await privateNode(socketPath, 'socket') } catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
||||
const pointer = path.join(home, 'gateway.sock.path')
|
||||
await privateNode(pointer, 'file')
|
||||
const target = (await fs.readFile(pointer, 'utf8')).trim()
|
||||
const hash = crypto.createHash('sha256').update(home).digest('hex').slice(0, 16)
|
||||
if (!path.isAbsolute(target) || path.basename(path.dirname(target)) !== `hermes-gw-${hash}` || path.basename(target) !== 'control.sock') throw new Error('Invalid gateway control pointer')
|
||||
await privateNode(path.dirname(target), 'directory')
|
||||
await privateNode(target, 'socket')
|
||||
socketPath = target
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.createConnection(socketPath)
|
||||
let buffer = ''
|
||||
const deadline = setTimeout(() => socket.destroy(new Error('Gateway ticket deadline')), 5000)
|
||||
socket.on('error', () => reject(new Error('Gateway ticket bootstrap failed')))
|
||||
socket.on('close', () => { clearTimeout(deadline); reject(new Error('Gateway ticket connection closed')) })
|
||||
socket.on('connect', () => socket.write(JSON.stringify({ protocol: 1, id: 1, verb: 'session-ticket', params: { profile_id: home, instance_id: endpoint.instance_id, purpose: 'interactive' } }) + '\n'))
|
||||
socket.on('data', chunk => {
|
||||
buffer += chunk.toString()
|
||||
if (buffer.length > 65536) return socket.destroy(new Error('Oversized gateway ticket response'))
|
||||
if (!buffer.includes('\n')) return
|
||||
try {
|
||||
const reply = JSON.parse(buffer.split('\n')[0])
|
||||
const grant = reply.result
|
||||
if (!reply.ok || reply.protocol !== 1 || reply.id !== 1 || grant?.instance_id !== endpoint.instance_id || grant?.profile_id !== home || typeof grant?.ticket !== 'string') throw new Error('Invalid gateway ticket')
|
||||
resolve(grant.ticket)
|
||||
} catch { reject(new Error('Invalid gateway ticket response')) }
|
||||
socket.destroy()
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { execFileSync, spawn } from 'node:child_process'
|
||||
import { ensureLocalGateway, runGatewayEnsure, mintLocalGatewayTicket, createLocalGatewayDials } from './local-gateway'
|
||||
const localGatewayDials = createLocalGatewayDials()
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import http from 'node:http'
|
||||
@@ -8331,7 +8333,7 @@ async function mintGatewayWsTicket(baseUrl, headers = {}) {
|
||||
// calls this immediately before every gateway.connect() so each WS upgrade
|
||||
// carries a freshly-minted ticket. For local/token connections this just
|
||||
// reuses the static token (no minting needed).
|
||||
async function freshGatewayWsUrl(profile) {
|
||||
async function freshGatewayWsUrl(profile, webContentsId) {
|
||||
// Mint for the requested profile's backend, NOT always the primary. The
|
||||
// renderer re-mints right before every gateway.connect(); when swapping to a
|
||||
// pooled profile we must return THAT backend's ws URL, otherwise the connect
|
||||
@@ -8340,6 +8342,11 @@ async function freshGatewayWsUrl(profile) {
|
||||
// legacy callers and single-profile users are unchanged.
|
||||
const connection = await ensureBackend(profile)
|
||||
|
||||
if (connection.gatewayEndpoint) {
|
||||
const ticket = await mintLocalGatewayTicket(connection.gatewayEndpoint)
|
||||
return localGatewayDials.prepare(connection.baseUrl, ticket, webContentsId)
|
||||
}
|
||||
|
||||
if (connection.authMode === 'oauth') {
|
||||
const ticket = await mintGatewayWsTicket(connection.baseUrl, connection.headers)
|
||||
const wsUrl = buildGatewayWsUrlWithTicket(connection.baseUrl, ticket)
|
||||
@@ -9261,6 +9268,8 @@ function installRemoteHeaderRules() {
|
||||
|
||||
remoteHeaderRulesInstalled = true
|
||||
session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
|
||||
const nativeHeaders = localGatewayDials.headers(details)
|
||||
if (nativeHeaders) { callback({ requestHeaders: nativeHeaders }); return }
|
||||
applyRemoteRequestHeaders(details, callback, headersForRemoteRequest)
|
||||
})
|
||||
}
|
||||
@@ -12563,226 +12572,13 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
|
||||
}
|
||||
}
|
||||
|
||||
// Bound the slot wait BELOW the renderer's backend-boot budget (45s): once
|
||||
// the renderer has given up on this spawn, a ticket still queued for the
|
||||
// pool-idle window (10 min) would hold the pool key hostage and every
|
||||
// later click on the profile would join that stale wait. Failing here
|
||||
// surfaces the "all N slots busy" reason instead of a generic boot timeout.
|
||||
// The caller stamped entry.spawnPriority from its own request; a foreground
|
||||
// dial that joined the claim before this entry existed left a mark instead.
|
||||
if (takeForegroundSpawn(poolKey, profile)) {
|
||||
entry.spawnPriority = 'foreground'
|
||||
}
|
||||
|
||||
const spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(entry.spawnPriority)
|
||||
|
||||
const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {
|
||||
timeoutMs: POOL_SLOT_WAIT_MS,
|
||||
priority: spawnPriority
|
||||
})
|
||||
|
||||
entry.localBackendSlotKey = poolKey
|
||||
entry.localBackendSpawnRequest = spawnRequest
|
||||
|
||||
if (spawnRequest.queued) {
|
||||
rememberLog(
|
||||
`Profile backend "${profile}" waiting for a free local slot (${localBackendSpawnCoordinator.activeCount}/${poolMaxBackends()} busy, ${localBackendSpawnCoordinator.queuedCount} queued)`
|
||||
)
|
||||
}
|
||||
|
||||
entry.releaseLocalBackendSlot = await spawnRequest.acquired
|
||||
|
||||
if (entry.localBackendSpawnRequest === spawnRequest) {
|
||||
entry.localBackendSpawnRequest = null
|
||||
}
|
||||
|
||||
assertPoolEntryStillOwned(poolKey, entry)
|
||||
|
||||
const token = crypto.randomBytes(32).toString('base64url')
|
||||
|
||||
// Same update mutual exclusion as the primary window's waitForLocalStart
|
||||
// (#73822): pool backends spawn from the same venv, so an ungated respawn
|
||||
// during applyUpdates' critical section re-locks the venv and trips the
|
||||
// venv-blocker preflight. No boot-progress UI here — pool backends boot
|
||||
// silently for background profiles — so we only log while parked.
|
||||
{
|
||||
let poolAnnounced = false
|
||||
|
||||
await waitForUpdateClearance(updateGateDeps(), {
|
||||
onWaitTick: reason => {
|
||||
if (!poolAnnounced) {
|
||||
poolAnnounced = true
|
||||
rememberLog(`[updates] update in progress (${reason}); deferring pool backend start for profile "${profile}"`)
|
||||
}
|
||||
},
|
||||
pollMs: UPDATE_WAIT_POLL_MS,
|
||||
timeoutMs: UPDATE_WAIT_TIMEOUT_MS
|
||||
})
|
||||
}
|
||||
|
||||
profileDeletionGate.assertCanStart(profile)
|
||||
|
||||
// --profile wins over the inherited HERMES_HOME env (see _apply_profile_override
|
||||
// step 3 in hermes_cli/main.py), so the child re-homes to this profile.
|
||||
// --port 0: the OS assigns an ephemeral port; the child announces it on stdout.
|
||||
const backendArgs = ['--profile', profile, 'serve', '--host', '127.0.0.1', '--port', '0']
|
||||
const backend = await ensureRuntime(resolveHermesBackend(backendArgs))
|
||||
// Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.
|
||||
backend.args = getBackendArgsForRuntime(backend)
|
||||
const hermesCwd = resolveHermesCwd()
|
||||
const webDist = resolveWebDist()
|
||||
const readyFile = backend.readyFile ? makeDashboardReadyFile() : null
|
||||
|
||||
// Guard BEFORE the "Starting" line: a profile that only exists on a remote
|
||||
// backend (remote-primary desktop asked for a forced-local child) rejects
|
||||
// here, and logging "Starting" first left an orphaned line with no READY
|
||||
// and no exit — the exact undiagnosable burst signature in remote-gateway
|
||||
// user bundles (Aug 2026, Dash's report).
|
||||
assertLocalProfileCanStart(profile, profileDeletionGate, key =>
|
||||
directoryExists(path.join(HERMES_HOME, 'profiles', key))
|
||||
)
|
||||
rememberLog(`Starting Hermes backend for profile "${profile}" via ${backend.label}`)
|
||||
|
||||
const parentStartMarker = await desktopParentStartMarker()
|
||||
const backendNonce = crypto.randomBytes(16).toString('hex')
|
||||
const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)
|
||||
const backend = await ensureRuntime(resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']))
|
||||
const connection = await ensureLocalGateway(() => runGatewayEnsure(backend, resolveHermesCwd(), HERMES_HOME))
|
||||
assertPoolEntryStillOwned(poolKey, entry)
|
||||
|
||||
const child = spawn(
|
||||
backend.command,
|
||||
backend.args,
|
||||
hiddenWindowsChildOptions({
|
||||
cwd: hermesCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
HERMES_HOME,
|
||||
...backend.env,
|
||||
// Pin the gateway's tool/terminal cwd to the same directory we chose for
|
||||
// the child process. Inherited TERMINAL_CWD (or a stale config bridge)
|
||||
// can still point at the install dir even when spawn cwd is home.
|
||||
TERMINAL_CWD: hermesCwd,
|
||||
HERMES_DASHBOARD_SESSION_TOKEN: token,
|
||||
// Marks this dashboard backend as desktop-spawned so it runs the cron
|
||||
// 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. If the
|
||||
// optional marker probe fails, retain legacy PID-only tracking.
|
||||
...parentIdentityEnv,
|
||||
HERMES_WEB_DIST: webDist,
|
||||
...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
|
||||
},
|
||||
shell: backend.shell,
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
})
|
||||
)
|
||||
|
||||
entry.process = child
|
||||
entry.token = token
|
||||
// Buffer stdout+stderr from the instant of spawn (#93608): an early crash's
|
||||
// traceback must survive into the claim error and the before-ready exit
|
||||
// message instead of a bare exit code. rememberLog attaches later, after
|
||||
// the claim, and would miss anything printed before it.
|
||||
const outputTail = createBackendOutputTail()
|
||||
outputTail.attach(child)
|
||||
|
||||
// Start watching for the READY announcement BEFORE any await (#60323):
|
||||
// stdout is already flowing into the tail, and Node streams never replay
|
||||
// consumed chunks to late listeners — a sentinel printed while
|
||||
// claimBackendChild runs would otherwise be lost forever, timing out a
|
||||
// healthy backend. The tail-buffer accessor covers any residual gap.
|
||||
const portAnnouncement = waitForDashboardPortAnnouncement(child, {
|
||||
bufferedOutput: () => outputTail.text(),
|
||||
describeOutputTail: () => outputTail.describe(),
|
||||
readyFile
|
||||
})
|
||||
|
||||
// Mark handled so an early rejection (child dies during the claim) can't
|
||||
// surface as an unhandled rejection before the Promise.race below attaches.
|
||||
portAnnouncement.catch(() => {})
|
||||
await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)
|
||||
assertPoolEntryStillOwned(poolKey, entry)
|
||||
|
||||
child.stdout.on('data', rememberLog)
|
||||
child.stderr.on('data', rememberLog)
|
||||
|
||||
let ready = false
|
||||
let rejectStart = null
|
||||
|
||||
const startFailed = new Promise((_resolve, reject) => {
|
||||
rejectStart = reject
|
||||
})
|
||||
|
||||
child.once('error', error => {
|
||||
rememberLog(`Hermes backend for profile "${profile}" failed to start: ${error.message}`)
|
||||
void teardownFailedLocalBackend(poolKey, entry).catch(cleanupError => {
|
||||
rememberLog(
|
||||
`Hermes backend for profile "${profile}" cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`
|
||||
)
|
||||
})
|
||||
rejectStart?.(error)
|
||||
})
|
||||
child.once('exit', (code, signal) => {
|
||||
rememberLog(`Hermes backend for profile "${profile}" exited (${signal || code})`)
|
||||
releaseLocalBackendSlot(entry)
|
||||
releaseBackendChild(child)
|
||||
|
||||
if (backendPool.get(poolKey) === entry) {
|
||||
backendPool.delete(poolKey)
|
||||
}
|
||||
|
||||
if (!ready) {
|
||||
rejectStart?.(
|
||||
new Error(
|
||||
`Hermes backend for profile "${profile}" exited before it became ready (${signal || code}).${outputTail.describe()}`
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
// Discover the ephemeral port the child bound to
|
||||
const port = await Promise.race([portAnnouncement, startFailed])
|
||||
|
||||
if (readyFile) {
|
||||
fs.unlink(readyFile, () => {})
|
||||
}
|
||||
|
||||
entry.port = port
|
||||
|
||||
const baseUrl = `http://127.0.0.1:${port}`
|
||||
await Promise.race([waitForHermes(baseUrl, token), startFailed])
|
||||
ready = true
|
||||
|
||||
const authToken = await adoptServedDashboardToken(baseUrl, token, {
|
||||
childAlive: () => child.exitCode === null && !child.killed,
|
||||
label: `Hermes backend for profile "${profile}"`,
|
||||
rememberLog
|
||||
})
|
||||
|
||||
entry.token = authToken
|
||||
|
||||
// Verify the WebSocket session token before declaring backend ready.
|
||||
// HTTP /api/status can pass while WS auth fails (separate transport, separate guards).
|
||||
const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`
|
||||
const wsProbe = await probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket })
|
||||
|
||||
if (!wsProbe.ok) {
|
||||
throw new Error(
|
||||
`Hermes backend for profile "${profile}" is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
baseUrl,
|
||||
mode: 'local',
|
||||
source: 'local',
|
||||
authMode: 'token',
|
||||
token: authToken,
|
||||
profile,
|
||||
wsUrl,
|
||||
logs: hermesLog.slice(-80),
|
||||
...getWindowState()
|
||||
}
|
||||
return { ...connection, profile, logs: hermesLog.slice(-80), ...getWindowState() }
|
||||
}
|
||||
|
||||
// Bounded, deduplicated pool teardown (see pool-stop.ts): every stop path —
|
||||
@@ -13002,9 +12798,7 @@ async function startHermes() {
|
||||
rememberLog(`[env] login-shell PATH resolution unavailable (${loginShellPath.reason}); keeping inherited PATH`)
|
||||
}
|
||||
|
||||
const token = crypto.randomBytes(32).toString('base64url')
|
||||
// --port 0: the OS assigns an ephemeral port; the child announces it on stdout.
|
||||
const backendArgs = ['serve', '--host', '127.0.0.1', '--port', '0']
|
||||
const backendArgs = ['gateway', 'ensure', '--json']
|
||||
// Pin the desktop's chosen profile via the global --profile flag. This is
|
||||
// deterministic (it wins over the sticky ~/.hermes/active_profile file) and
|
||||
// resolves HERMES_HOME the same way `hermes -p <name>` does on the CLI. An
|
||||
@@ -13050,221 +12844,14 @@ async function startHermes() {
|
||||
// Local WSL backend — paths are bridgeable.
|
||||
setWslBridgeProfileState(primaryProfile, true)
|
||||
|
||||
const backend = setup.backend
|
||||
// Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.
|
||||
backend.args = getBackendArgsForRuntime(backend)
|
||||
const hermesCwd = resolveHermesCwd()
|
||||
const webDist = resolveWebDist()
|
||||
const readyFile = backend.readyFile ? makeDashboardReadyFile() : null
|
||||
|
||||
await advanceBootProgress('backend.spawn', `Starting Hermes backend via ${backend.label}`, 84)
|
||||
rememberLog(`Starting Hermes backend via ${backend.label}`)
|
||||
|
||||
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,
|
||||
backend.args,
|
||||
hiddenWindowsChildOptions({
|
||||
cwd: hermesCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
// Explicitly pin HERMES_HOME for the child so Python's get_hermes_home()
|
||||
// resolves to the SAME location our resolveHermesHome() picked. Without
|
||||
// this pin, Python falls back to ~/.hermes on every platform — fine on
|
||||
// mac/linux (where our default matches), but on Windows our default is
|
||||
// %LOCALAPPDATA%\hermes, which differs from C:\Users\<u>\.hermes.
|
||||
// Mismatch would split config / sessions / .env / logs across two
|
||||
// directories. install.ps1 sets HERMES_HOME via setx; the desktop
|
||||
// can't reliably do that, so we set it inline for every spawn.
|
||||
HERMES_HOME,
|
||||
...backend.env,
|
||||
TERMINAL_CWD: hermesCwd,
|
||||
HERMES_DASHBOARD_SESSION_TOKEN: token,
|
||||
// Marks this dashboard backend as desktop-spawned so it runs the cron
|
||||
// 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. If the
|
||||
// optional marker probe fails, retain legacy PID-only tracking.
|
||||
...parentIdentityEnv,
|
||||
HERMES_WEB_DIST: webDist,
|
||||
...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
|
||||
},
|
||||
shell: backend.shell,
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
})
|
||||
)
|
||||
|
||||
// Buffer stdout+stderr from the instant of spawn (#93608): an early
|
||||
// crash's traceback must survive into the claim error and the
|
||||
// before-ready exit message shown by the boot UI. rememberLog attaches
|
||||
// later, after the claim, and would miss anything printed before it.
|
||||
const primaryOutputTail = createBackendOutputTail()
|
||||
primaryOutputTail.attach(hermesProcess)
|
||||
|
||||
// Start watching for the READY announcement BEFORE any await (#60323):
|
||||
// claimBackendChild can take seconds (its Windows Get-Process probe cold
|
||||
// start alone runs 2-8s) and advanceBootProgress awaits renderer IPC.
|
||||
// stdout is already flowing into the tail, and Node streams never replay
|
||||
// consumed chunks to late listeners, so a sentinel printed during that
|
||||
// window was lost forever — the wait then hit its 90s timeout and a
|
||||
// healthy backend was killed (deterministic on Windows, racy on
|
||||
// macOS/Linux). The tail-buffer accessor covers any residual gap.
|
||||
const portAnnouncement = waitForDashboardPortAnnouncement(hermesProcess, {
|
||||
bufferedOutput: () => primaryOutputTail.text(),
|
||||
describeOutputTail: () => primaryOutputTail.describe(),
|
||||
readyFile
|
||||
})
|
||||
|
||||
// Mark handled so an early rejection (child dies during the claim) can't
|
||||
// surface as an unhandled rejection before the Promise.race below attaches.
|
||||
portAnnouncement.catch(() => {})
|
||||
await claimBackendChild(
|
||||
hermesProcess,
|
||||
`${backend.command} ${backend.args.join(' ')}`,
|
||||
profile,
|
||||
backendNonce,
|
||||
primaryOutputTail
|
||||
)
|
||||
const processOwner = backendConnectionState.attachProcess(connectionAttempt, hermesProcess)
|
||||
|
||||
if (!processOwner) {
|
||||
stopBackendChild(hermesProcess)
|
||||
await waitForBackendExit(hermesProcess)
|
||||
releaseBackendChild(hermesProcess)
|
||||
const connection = await ensureLocalGateway(() => runGatewayEnsure(setup.backend, resolveHermesCwd(), HERMES_HOME))
|
||||
if (!backendConnectionState.isCurrentAttempt(connectionAttempt)) {
|
||||
throw new Error('Hermes backend start was superseded by a newer connection attempt.')
|
||||
}
|
||||
|
||||
hermesProcess.stdout.on('data', rememberLog)
|
||||
hermesProcess.stderr.on('data', rememberLog)
|
||||
let backendReady = false
|
||||
let rejectBackendStart = null
|
||||
|
||||
const backendStartFailed = new Promise((_resolve, reject) => {
|
||||
rejectBackendStart = reject
|
||||
})
|
||||
|
||||
hermesProcess.once('error', error => {
|
||||
releaseBackendChild(hermesProcess)
|
||||
|
||||
if (!backendConnectionState.clearForCurrentProcess(processOwner)) {
|
||||
rememberLog(`Ignoring stale Hermes backend error: ${error.message}`)
|
||||
rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rememberLog(`Hermes backend failed to start: ${error.message}`)
|
||||
updateBootProgress(
|
||||
{
|
||||
error: error.message,
|
||||
message: `Hermes backend failed to start: ${error.message}`,
|
||||
phase: 'backend.error',
|
||||
running: false
|
||||
},
|
||||
{ allowDecrease: true }
|
||||
)
|
||||
sendBackendExit({ code: null, signal: null, error: error.message })
|
||||
rejectBackendStart?.(error)
|
||||
})
|
||||
hermesProcess.once('exit', (code, signal) => {
|
||||
releaseBackendChild(hermesProcess)
|
||||
|
||||
if (!backendConnectionState.clearForCurrentProcess(processOwner)) {
|
||||
rememberLog(`Ignoring stale Hermes backend exit (${signal || code})`)
|
||||
|
||||
if (!backendReady) {
|
||||
rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rememberLog(`Hermes backend exited (${signal || code})`)
|
||||
sendBackendExit({ code, signal })
|
||||
|
||||
if (!backendReady) {
|
||||
const message = `Hermes backend exited before it became ready (${signal || code}).${primaryOutputTail.describe()}`
|
||||
updateBootProgress(
|
||||
{
|
||||
error: message,
|
||||
message,
|
||||
phase: 'backend.error',
|
||||
running: false
|
||||
},
|
||||
{ allowDecrease: true }
|
||||
)
|
||||
rejectBackendStart?.(
|
||||
new Error(
|
||||
`Hermes backend exited before it became ready (${signal || code}). Log: ${DESKTOP_LOG_PATH}\n${recentHermesLog()}`
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
await advanceBootProgress('backend.port', 'Waiting for Hermes backend to launch', 86)
|
||||
|
||||
// Discover the ephemeral port the child bound to
|
||||
const port = await Promise.race([portAnnouncement, backendStartFailed])
|
||||
|
||||
if (readyFile) {
|
||||
fs.unlink(readyFile, () => {})
|
||||
}
|
||||
|
||||
const baseUrl = `http://127.0.0.1:${port}`
|
||||
await advanceBootProgress('backend.wait', 'Waiting for Hermes backend to become ready', 90)
|
||||
await Promise.race([waitForHermes(baseUrl, token), backendStartFailed])
|
||||
backendReady = true
|
||||
backendStartFailure = null
|
||||
|
||||
const authToken = await adoptServedDashboardToken(baseUrl, token, {
|
||||
childAlive: () => hermesProcess.exitCode === null && !hermesProcess.killed,
|
||||
rememberLog
|
||||
})
|
||||
|
||||
// Verify the WebSocket session token before declaring backend ready.
|
||||
const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`
|
||||
const wsProbe = await probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket })
|
||||
|
||||
if (!wsProbe.ok) {
|
||||
throw new Error(
|
||||
`Local Hermes backend is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`
|
||||
)
|
||||
}
|
||||
|
||||
updateBootProgress({
|
||||
phase: 'backend.ready',
|
||||
message: 'Hermes backend is ready. Finalizing desktop startup',
|
||||
progress: 94,
|
||||
running: true,
|
||||
error: null
|
||||
})
|
||||
|
||||
// A successful boot (including a soft restart that the repair-guard
|
||||
// chose over a hard reinstall, see #74874) means any in-flight repair
|
||||
// attempt counter has been honoured — reset it so the next genuine
|
||||
// failure starts fresh from attempt 1 instead of inheriting the
|
||||
// accumulated count of the resolved episode.
|
||||
updateBootProgress({ phase: 'backend.ready', message: 'Hermes gateway is ready', progress: 94, running: true, error: null })
|
||||
bootstrapRepairAttempt = 0
|
||||
|
||||
// The backend's plugin discovery just ran and refreshed HERMES_HOME/.plugin-compat-report.json.
|
||||
// Surface it once (per distinct set of affected plugins) after the window is up; never block boot.
|
||||
setTimeout(() => void showPluginCompatNoticeOnce(), 1500)
|
||||
|
||||
return {
|
||||
baseUrl,
|
||||
mode: 'local',
|
||||
source: 'local',
|
||||
authMode: 'token',
|
||||
token: authToken,
|
||||
wsUrl,
|
||||
logs: hermesLog.slice(-80),
|
||||
...getWindowState()
|
||||
}
|
||||
return { ...connection, logs: hermesLog.slice(-80), ...getWindowState() }
|
||||
})().catch(async error => {
|
||||
if (!backendConnectionState.clearPromiseForAttempt(connectionAttempt)) {
|
||||
throw error
|
||||
@@ -15047,7 +14634,7 @@ ipcMain.handle('hermes:pool-limits:set', async (_event, raw) => {
|
||||
return { ok: true, limits: next }
|
||||
})
|
||||
ipcMain.handle('hermes:gateway:ws-url', async (_event, profile) => {
|
||||
return gatewayWsUrlIpcResult(() => freshGatewayWsUrl(profile))
|
||||
return gatewayWsUrlIpcResult(() => freshGatewayWsUrl(profile, _event.sender.id))
|
||||
})
|
||||
ipcMain.handle('hermes:window:openSession', async (_event, sessionId, opts) => {
|
||||
if (typeof sessionId !== 'string' || !sessionId.trim()) {
|
||||
@@ -15839,7 +15426,14 @@ const registryGatewayWsUrlHandler = createRegistryGatewayWsUrlHandler({
|
||||
})
|
||||
|
||||
ipcMain.handle('hermes:gateway:ws-url-for', async (_event, payload) => {
|
||||
return gatewayWsUrlIpcResult(() => registryGatewayWsUrlHandler(payload))
|
||||
return gatewayWsUrlIpcResult(async () => {
|
||||
const connection = await ensureRegistryBackend(payload?.connectionId, payload?.profile)
|
||||
if (connection.gatewayEndpoint) {
|
||||
const ticket = await mintLocalGatewayTicket(connection.gatewayEndpoint)
|
||||
return localGatewayDials.prepare(connection.baseUrl, ticket, _event.sender.id)
|
||||
}
|
||||
return registryGatewayWsUrlHandler(payload)
|
||||
})
|
||||
})
|
||||
|
||||
// Transactional update for a Desktop-managed SSH install. Unlike the generic
|
||||
|
||||
@@ -32,7 +32,8 @@ export class HermesGateway extends JsonRpcGatewayClient {
|
||||
connectErrorMessage: 'Could not connect to Hermes gateway',
|
||||
createRequestId: nextId => nextId,
|
||||
notConnectedErrorMessage: 'Hermes gateway is not connected',
|
||||
requestTimeoutMs: DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS
|
||||
requestTimeoutMs: DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS,
|
||||
socketFactory: url => new WebSocket(url, new URL(url).searchParams.has('native_dial') ? ['hermes-gateway-v1'] : [])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user