Skip to content

The agent that grows with you

fix(desktop): reconcile runtime wiring after the PM merge

ethernetbfabc23f7fe4
diff --git a/apps/desktop/electron/backend-child.ts b/apps/desktop/electron/backend-child.ts
index 725561a9ef7..46c901ddf1f 100644
--- a/apps/desktop/electron/backend-child.ts
+++ b/apps/desktop/electron/backend-child.ts
@@ -20,8 +20,6 @@
* the function body.
*/
-import type { ChildProcess } from 'node:child_process'
-
export interface StopBackendChildDeps {
/** Defaults to the real platform check; injectable for tests. */
isWindows?: boolean
@@ -62,23 +60,23 @@ export interface WaitableChild extends KillableChild {
export async function waitForBackendExit(
child: WaitableChild | null | undefined,
deps: StopBackendChildDeps,
- timeoutMs = 5000
+ timeoutMs: number = 5000
): Promise<void> {
if (!child || child.exitCode !== null || child.signalCode !== null) {
return
}
- const exited = () => child.exitCode !== null || child.signalCode !== null
+ const exited = (): boolean => child.exitCode !== null || child.signalCode !== null
- const wait = (delay: number) =>
- new Promise<void>(resolve => {
+ const wait = (delay: number): Promise<void> =>
+ new Promise<void>((resolve: () => void): void => {
if (exited()) {
resolve()
return
}
- const finish = () => {
+ const finish = (): void => {
clearTimeout(timer)
child.removeListener('exit', finish)
resolve()
@@ -99,7 +97,7 @@ export async function waitForBackendExit(
deps.forceKillProcessTree(child.pid as number)
} else if (Number.isInteger(child.pid)) {
try {
- const killGroup = deps.killGroup ?? ((pid, signal) => process.kill(pid, signal))
+ const killGroup = deps.killGroup ?? ((pid: number, signal: string): boolean => process.kill(pid, signal))
killGroup(-(child.pid as number), 'SIGKILL')
} catch {
child.kill('SIGKILL')
@@ -108,10 +106,14 @@ export async function waitForBackendExit(
child.kill('SIGKILL')
}
} catch {
- return
+ // The process may have exited while the signal was sent. Verify below.
}
await wait(1000)
+
+ if (!exited()) {
+ throw new Error(`Backend PID ${child.pid} did not exit after escalation`)
+ }
}
/**
@@ -166,39 +168,3 @@ export function stopBackendTreesForUpdate(
deps.stopAllPoolBackends()
}
-
-export async function waitForBackendExit(
- child: ChildProcess | null | undefined,
- escalate: (child: ChildProcess) => void,
- timeoutMs = 5000
-): Promise<void> {
- if (!child || child.exitCode !== null || child.signalCode !== null) { return }
-
- const exited = (): boolean => child.exitCode !== null || child.signalCode !== null
-
- const wait = (delay: number): Promise<void> => new Promise(resolve => {
- if (exited()) {
- resolve()
-
- return
- }
-
- const finish = (): void => {
- clearTimeout(timer)
- child.removeListener('exit', finish)
- resolve()
- }
-
- const timer = setTimeout(finish, delay)
- child.once('exit', finish)
- })
-
- await wait(timeoutMs)
-
- if (exited()) { return }
-
- escalate(child)
- await wait(1000)
-
- if (!exited()) { throw new Error(`Backend PID ${child.pid} did not exit after escalation`) }
-}
diff --git a/apps/desktop/electron/backend-connection-state.test.ts b/apps/desktop/electron/backend-connection-state.test.ts
index 55ee25856e1..674b96a8197 100644
--- a/apps/desktop/electron/backend-connection-state.test.ts
+++ b/apps/desktop/electron/backend-connection-state.test.ts
@@ -121,3 +121,47 @@ test('distinguishes a pending connection attempt from a cached settled descripto
assert.equal(state.getPromise(), connection.promise)
assert.equal(state.getPendingPromise(), null)
})
+
+test('a failed primary stop retains its child and blocks replacement until retry', async (): Promise<void> => {
+ const state = createBackendConnectionState<FakeProcess, string>()
+ const child: FakeProcess = { id: 'primary' }
+ const attempt = state.startAttempt()
+ state.attachProcess(attempt, child)
+ state.setPromise(attempt, Promise.resolve('ready'))
+ const failure = new Error('still running')
+ const calls: FakeProcess[] = []
+
+ const fail = async (current: FakeProcess): Promise<void> => {
+ calls.push(current)
+ throw failure
+ }
+
+ const stopping = state.stopProcess(fail)
+ assert.equal(state.getProcess(), null)
+ assert.equal(state.getPendingPromise(), null)
+ assert.equal(state.stopProcess(fail), stopping)
+ assert.throws((): unknown => state.startAttempt(), /has not stopped/)
+ await assert.rejects(stopping, failure)
+ state.invalidate()
+ assert.throws((): unknown => state.startAttempt(), /has not stopped/)
+ await state.stopProcess(async (current: FakeProcess): Promise<void> => {
+ calls.push(current)
+ })
+ assert.deepEqual(calls, [child, child])
+ assert.doesNotThrow((): unknown => state.startAttempt())
+})
+
+test('shutdown owns a child before its persistent claim completes', async (): Promise<void> => {
+ const state = createBackendConnectionState<FakeProcess, string>()
+ const child: FakeProcess = { id: 'claiming' }
+ const claim = deferred<void>()
+ const claiming = state.claimProcess(state.startAttempt(), child, (): Promise<void> => claim.promise)
+
+ assert.equal(state.getProcess(), child)
+ await state.stopProcess(async (current: FakeProcess): Promise<void> => {
+ assert.equal(current, child)
+ })
+ claim.resolve()
+ assert.equal(await claiming, null)
+ assert.equal(state.getProcess(), null)
+})
diff --git a/apps/desktop/electron/backend-connection-state.ts b/apps/desktop/electron/backend-connection-state.ts
index fdbe6dea263..55cc6bc6161 100644
--- a/apps/desktop/electron/backend-connection-state.ts
+++ b/apps/desktop/electron/backend-connection-state.ts
@@ -8,14 +8,54 @@ export type BackendProcessOwner<TProcess> = {
process: TProcess
}
-export function createBackendConnectionState<TProcess, TConnection>() {
+interface PendingBackendStop<TProcess> {
+ process: TProcess
+ completion: Promise<void>
+ failed: boolean
+}
+
+export interface BackendConnectionState<TProcess, TConnection> {
+ startAttempt(): BackendConnectionAttempt<TConnection>
+ setPromise(attempt: BackendConnectionAttempt<TConnection>, promise: Promise<TConnection>): boolean
+ isCurrentAttempt(attempt: BackendConnectionAttempt<TConnection>): boolean
+ attachProcess(attempt: BackendConnectionAttempt<TConnection>, process: TProcess): BackendProcessOwner<TProcess> | null
+ claimProcess(
+ attempt: BackendConnectionAttempt<TConnection>,
+ process: TProcess,
+ claim: (current: TProcess) => Promise<unknown>
+ ): Promise<BackendProcessOwner<TProcess> | null>
+ clearForCurrentProcess(owner: BackendProcessOwner<TProcess>): boolean
+ clearPromiseForAttempt(attempt: BackendConnectionAttempt<TConnection>): boolean
+ getProcess(): TProcess | null
+ getPromise(): Promise<TConnection> | null
+ getPendingPromise(): Promise<TConnection> | null
+ invalidate(): TProcess | null
+ stopProcess(stop: (current: TProcess) => Promise<void>): Promise<void>
+}
+
+export function createBackendConnectionState<TProcess, TConnection>(): BackendConnectionState<TProcess, TConnection> {
let generation = 0
let process: TProcess | null = null
let promise: Promise<TConnection> | null = null
let pendingPromise: Promise<TConnection> | null = null
+ let stopping: PendingBackendStop<TProcess> | null = null
+
+ function invalidate(): TProcess | null {
+ const currentProcess = process
+ generation += 1
+ process = null
+ promise = null
+ pendingPromise = null
+
+ return currentProcess
+ }
return {
startAttempt(): BackendConnectionAttempt<TConnection> {
+ if (stopping) {
+ throw new Error('The previous backend has not stopped. Retry its shutdown before starting a replacement.')
+ }
+
return { generation, promise: null }
},
@@ -61,6 +101,22 @@ export function createBackendConnectionState<TProcess, TConnection>() {
return { generation, process: nextProcess }
},
+ async claimProcess(
+ attempt: BackendConnectionAttempt<TConnection>,
+ nextProcess: TProcess,
+ claim: (current: TProcess) => Promise<unknown>
+ ): Promise<BackendProcessOwner<TProcess> | null> {
+ const owner = this.attachProcess(attempt, nextProcess)
+
+ if (!owner) {
+ return null
+ }
+
+ await claim(nextProcess)
+
+ return owner.generation === generation && process === nextProcess ? owner : null
+ },
+
clearForCurrentProcess(owner: BackendProcessOwner<TProcess>): boolean {
if (owner.generation !== generation || owner.process !== process) {
return false
@@ -96,15 +152,35 @@ export function createBackendConnectionState<TProcess, TConnection>() {
return pendingPromise
},
- invalidate(): TProcess | null {
- const currentProcess = process
+ invalidate,
- generation += 1
- process = null
- promise = null
- pendingPromise = null
+ stopProcess(stop: (current: TProcess) => Promise<void>): Promise<void> {
+ if (stopping && !stopping.failed) {
+ return stopping.completion
+ }
+
+ const current = stopping?.process ?? invalidate()
+
+ if (current === null) {
+ return Promise.resolve()
+ }
+
+ const completion = Promise.resolve()
+ .then((): Promise<void> => stop(current))
+ .then(
+ (): void => {
+ stopping = null
+ },
+ (error: unknown): never => {
+ pending.failed = true
+ throw error
+ }
+ )
+
+ const pending: PendingBackendStop<TProcess> = { process: current, completion, failed: false }
+ stopping = pending
- return currentProcess
+ return completion
}
}
}
diff --git a/apps/desktop/electron/backend-exit.test.ts b/apps/desktop/electron/backend-exit.test.ts
index 4380dc8c984..b4eb416085b 100644
--- a/apps/desktop/electron/backend-exit.test.ts
+++ b/apps/desktop/electron/backend-exit.test.ts
@@ -5,14 +5,18 @@ import { test, vi } from 'vitest'
import { waitForBackendExit } from './backend-child'
-test('backend exit escalation remains bounded when no exit or close arrives', async () => {
+test('backend exit escalation rejects within its bound when no exit or close arrives', async (): Promise<void> => {
vi.useFakeTimers()
try {
const child = Object.assign(new EventEmitter(), { exitCode: null, signalCode: null, kill: vi.fn() })
- const waiting = waitForBackendExit(child, { forceKillProcessTree: () => {} }, 20)
- await vi.advanceTimersByTimeAsync(1020)
- await waiting
+
+ const waiting = assert.rejects(
+ waitForBackendExit(child, { forceKillProcessTree: (): void => {} }, 20),
+ /did not exit after escalation/
+ )
+
+ await Promise.all([waiting, vi.advanceTimersByTimeAsync(1020)])
assert.equal(child.kill.mock.calls.length, 1)
assert.equal(child.kill.mock.calls[0][0], 'SIGKILL')
assert.equal(child.listenerCount('exit'), 0)
diff --git a/apps/desktop/electron/machine-profile.test.ts b/apps/desktop/electron/machine-profile.test.ts
new file mode 100644
index 00000000000..a329f3c79e6
--- /dev/null
+++ b/apps/desktop/electron/machine-profile.test.ts
@@ -0,0 +1,59 @@
+import { statSync } from 'node:fs'
+import * as os from 'node:os'
+
+import { beforeEach, expect, it, vi } from 'vitest'
+
+const host = vi.hoisted(() => ({
+ getGPUInfo: vi.fn(),
+ getLocale: vi.fn((): string => 'fr-CA'),
+ handle: vi.fn()
+}))
+
+vi.mock('electron', () => ({
+ app: { getGPUInfo: host.getGPUInfo, getLocale: host.getLocale },
+ ipcMain: { handle: host.handle }
+}))
+
+import type { MachineProfile } from './machine-profile'
+import { registerMachineProfile } from './machine-profile'
+
+beforeEach((): void => {
+ host.handle.mockReset()
+ host.getGPUInfo.mockReset()
+ host.getLocale.mockClear()
+})
+
+function handler(): () => Promise<MachineProfile> {
+ registerMachineProfile()
+ const registration = host.handle.mock.calls.find(([channel]): boolean => channel === 'hermes:machine:profile')
+ expect(registration).toBeDefined()
+
+ return registration![1] as () => Promise<MachineProfile>
+}
+
+it('registers the renderer channel and reports native machine facts with the OS locale and GPU', async (): Promise<void> => {
+ host.getGPUInfo.mockResolvedValue({ gpuDevice: [{ vendorId: 0x8086 }, { vendorId: 0x10de }] })
+ const result = await handler()()
+ const { birthtimeMs } = statSync(os.homedir())
+
+ expect(result).toMatchObject({
+ ageDays: birthtimeMs > 0 ? Math.max(0, Math.floor((Date.now() - birthtimeMs) / 86_400_000)) : null,
+ arch: process.arch,
+ locale: 'fr-CA',
+ nvidia: true,
+ platform: process.platform,
+ release: os.release(),
+ username: os.userInfo().username
+ })
+ expect(typeof result.model).toBe('string')
+ expect(host.getGPUInfo).toHaveBeenCalledWith('basic')
+})
+
+it('keeps machine facts available when Chromium cannot enumerate GPUs', async (): Promise<void> => {
+ host.getGPUInfo.mockRejectedValue(new Error('GPU info unavailable'))
+ const result = await handler()()
+
+ expect(result.nvidia).toBe(false)
+ expect(result.platform).toBe(process.platform)
+ expect(result.locale).toBe('fr-CA')
+})
diff --git a/apps/desktop/electron/machine-profile.ts b/apps/desktop/electron/machine-profile.ts
new file mode 100644
index 00000000000..98c7b3e8c3a
--- /dev/null
+++ b/apps/desktop/electron/machine-profile.ts
@@ -0,0 +1,72 @@
+import * as fs from 'node:fs'
+import * as os from 'node:os'
+
+import { app, ipcMain } from 'electron'
+
+export interface MachineProfile {
+ ageDays: number | null
+ arch: string
+ locale: string
+ model: string
+ nvidia: boolean
+ platform: NodeJS.Platform
+ release: string
+ username: string
+}
+
+export function registerMachineProfile(): void {
+ ipcMain.handle('hermes:machine:profile', readMachineProfile)
+}
+
+async function readMachineProfile(): Promise<MachineProfile> {
+ let ageDays: number | null = null
+ let username = ''
+
+ // Home birthtime approximates account age. Unsupported filesystems leave it unknown.
+ try {
+ const { birthtimeMs } = fs.statSync(os.homedir())
+
+ if (birthtimeMs > 0) {
+ ageDays = Math.max(0, Math.floor((Date.now() - birthtimeMs) / 86_400_000))
+ }
+ } catch {
+ // Unknown age must not make a daily-use machine look newly set up.
+ }
+
+ try {
+ username = os.userInfo().username
+ } catch {
+ // The guide can ask for a name without suggesting an OS login.
+ }
+
+ return {
+ ageDays,
+ arch: process.arch,
+ locale: app.getLocale() || '',
+ model: readHardwareModel(),
+ nvidia: await hasNvidiaGpu(),
+ platform: process.platform,
+ release: os.release(),
+ username
+ }
+}
+
+function readHardwareModel(): string {
+ try {
+ // ARM firmware supplies model names such as NVIDIA_DGX_Spark here.
+ return fs.readFileSync('/proc/device-tree/model', 'utf8').replace(/\0/g, '').trim()
+ } catch {
+ return ''
+ }
+}
+
+async function hasNvidiaGpu(): Promise<boolean> {
+ try {
+ // Chromium already enumerates GPUs; no vendor tools or subprocess are needed.
+ const info = await app.getGPUInfo('basic') as { gpuDevice?: { vendorId?: number }[] }
+
+ return (info.gpuDevice ?? []).some((device): boolean => device.vendorId === 0x10de)
+ } catch {
+ return false
+ }
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 4bded3df2d9..f3a3bb8e7c8 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -17,9 +17,10 @@ import {
webContents as electronWebContents,
globalShortcut,
ipcMain,
+ type IpcMainEvent,
+ type IpcMainInvokeEvent,
Menu,
nativeTheme,
- Notification,
powerMonitor,
powerSaveBlocker,
protocol,
@@ -93,8 +94,9 @@ import {
} from './browser-windows'
import { detectBundleSkew } from './bundle-skew'
import { detectBundleSwap, readBundleSwapStamp } from './bundle-swap'
+import { registerChatOnboardingWindow } from './chat-onboarding-window'
import { provisionCliLinks } from './cli-provision'
-import { applyConnectionChange, sshQuitShouldBlock, teardownSshState } from './connection-apply'
+import { applyConnectionChange, teardownSshState } from './connection-apply'
import {
apiRequestRegistryConnectionId,
authModeFromStatus,
@@ -174,7 +176,7 @@ import {
} from './desktop-uninstall'
import { describeDevCdpDecision, resolveDevCdpPort } from './dev-cdp'
import { installEmbedReferer } from './embed-referer'
-import { createEventDeduper } from './event-dedupe'
+import { createAmbientClaimArbiter } from './event-dedupe'
import { openExternalUrl as externalOpen, type ExternalOpenDeps } from './external-open'
import {
buildTerminalScript,
@@ -208,6 +210,7 @@ import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gatewa
import { resolveGatewayVersion } from './gateway-version'
import { probeGatewayWebSocket } from './gateway-ws-probe'
import { registerGitIpc } from './git-ipc'
+import { desktopBackendSpawnEnv, guestOnboardingEnabled } from './guest-onboarding'
import { readAndConsumeHandoffResult } from './handoff-result'
import {
ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,
@@ -238,7 +241,10 @@ import { buildHudWindowUrl } from './hud-url'
import { resolveHudWindowing } from './hud-windowing'
import { INSTALL_STAMP, installShape } from './install-stamp'
import type { InstallStamp } from './install-stamp'
+import { createIntroRevealWindowController } from './intro-reveal-window'
import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window'
+import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle'
+import { registerMachineProfile } from './machine-profile'
import { ensureMainWindow } from './main-window-lifecycle'
import {
assertManagedUpdatePreflightClear,
@@ -277,6 +283,7 @@ import {
} from './native-oauth'
import { runNativeLogin } from './native-oauth-login'
import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } from './native-token-store'
+import { registerNativeNotifications } from './notification-ipc'
import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'
import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'
@@ -338,6 +345,7 @@ import {
} from './profile-session-routing'
import { createQuickEntryShortcut, quickEntryWindowBounds, sanitizeQuickEntrySettings } from './quick-entry'
import { type ActiveWork, mergeActiveWork, normalizeActiveWork, quitPromptFor } from './quit-guard'
+import { backendQuitNeedsWait, createQuitTeardownCoordinator, type QuitTeardownTask } from './quit-teardown'
import * as remoteLifecycle from './remote-lifecycle'
import {
attachPowerResumeRemoteRevalidation,
@@ -377,6 +385,7 @@ import { ensureLoginShellPath } from './shell-path'
import { createBootstrapCoordinator, sshConfigFingerprint } from './ssh-bootstrap-coordinator'
import { collectSshConfigHosts, parseSshGOutput } from './ssh-config'
import { createSshProbeConnection, pickLocalPort, redactSecrets, SshConnection } from './ssh-connection'
+import { createSshTeardownTracker } from './ssh-teardown'
import { createStreamThrottle } from './stream-throttle'
import { registerTerminalIpc } from './terminal-ipc'
import { nativeOverlayWidth as computeNativeOverlayWidth, macTitleBarOverlayHeight } from './titlebar-overlay-width'
@@ -393,16 +402,12 @@ import {
windowOpacityFor,
windowOpacityOptions
} from './translucency'
-import {
- compareApiUrl,
- parseCompareBehindCount,
- resolveCommitLogSelection
-} from './update-count'
import { waitForUpdateClearance } from './update-gate'
import { readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from './update-marker'
import { isOfficialSshRemote, OFFICIAL_REPO_HTTPS_URL } from './update-remote'
import {
resolveUpdaterMechanism,
+ type UpdaterStatusWire,
type UpdaterStrategy
} from './updater'
import {
@@ -852,6 +857,8 @@ const BOOT_FAKE_ERROR = process.env.HERMES_DESKTOP_BOOT_FAKE_ERROR || ''
// nobody to answer a modal, so the active-work confirmation would hang the
// caller instead of letting the process exit. Force quits set this.
const SKIP_QUIT_CONFIRM = process.env.HERMES_DESKTOP_SKIP_QUIT_CONFIRM === '1'
+// One launch decision must reach both the renderer and every backend spawn.
+const GUEST_ONBOARDING: boolean = guestOnboardingEnabled()
const BOOT_FAKE_STEP_MS = (() => {
const raw = Number.parseInt(String(process.env.HERMES_DESKTOP_BOOT_FAKE_STEP_MS || ''), 10)
@@ -1352,6 +1359,32 @@ function registerMediaProtocol() {
let mainWindow = null
const backendConnectionState = createBackendConnectionState<ReturnType<typeof spawn>, any>()
+
+const localBackendLifecycle = createLocalBackendLifecycle<ChildProcess>({
+ stopChild: (child: ChildProcess): void => {
+ if (child.exitCode === null && child.signalCode === null) {
+ stopBackendChildImpl(child, { forceKillProcessTree, isWindows: IS_WINDOWS })
+ }
+ },
+ waitForExit: (child: ChildProcess): Promise<void> => waitForBackendExit(child),
+ cancelSetup: (): void => {
+ firstRunSetupGate?.resetForRetry()
+ bootstrapAbortController?.abort()
+ }
+})
+
+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()
const remoteRevalidation = new RemoteRevalidationCoordinator()
const registryDispatchRevalidation = new RemoteRevalidationCoordinator()
@@ -2179,6 +2212,10 @@ function fileExists(filePath) {
}
}
+function isGitCheckout(root: string): boolean {
+ return fs.existsSync(path.join(root, '.git'))
+}
+
function directoryExists(filePath) {
try {
return fs.statSync(filePath).isDirectory()
@@ -2288,6 +2325,7 @@ async function waitForUpdateToFinish() {
let announced = false
const outcome = await waitForUpdateClearance(updateGateDeps(), {
+ signal: localBackendLifecycle.signal,
onWaitTick: async reason => {
if (!announced) {
announced = true
@@ -2337,6 +2375,10 @@ async function waitForUpdateToFinish() {
rememberLog(`[updates] could not read hand-off result: ${err.message}`)
}
+ if (outcome === 'cancelled') {
+ localBackendLifecycle.assertCanStart()
+ }
+
if (outcome === 'clear') {
return false
}
@@ -2948,7 +2990,7 @@ function resolveUpdateRoot() {
isHermesSourceRoot(ACTIVE_HERMES_ROOT) ? ACTIVE_HERMES_ROOT : null
].filter(Boolean)
- return candidates.find(c => directoryExists(path.join(c, '.git'))) || candidates[0] || ACTIVE_HERMES_ROOT
+ return candidates.find(isGitCheckout) || candidates[0] || ACTIVE_HERMES_ROOT
}
function runGit(args, options: any = {}): Promise<{ code: number; stdout: string; stderr: string }> {
@@ -2976,7 +3018,7 @@ function runGit(args, options: any = {}): Promise<{ code: number; stdout: string
options.onLine?.('stderr', text)
})
child.once('error', reject)
- child.once('exit', code => resolve({ code, stdout, stderr }))
+ child.once('close', (code: number): void => resolve({ code, stdout, stderr }))
})
}
@@ -3026,14 +3068,14 @@ async function resolveHealedBranch(updateRoot, branch) {
return 'main'
}
-async function checkUpdates() {
+async function checkUpdates(opts: { force?: boolean } = {}): Promise<UpdaterStatusWire> {
// A packaged install delegates to the update owner named by its stamp.
let strategy: UpdaterStrategy | null = null
try {
strategy = resolvePackagedUpdateStrategy()
- if (strategy) { return await strategy.check() }
+ if (strategy) { return await strategy.check(opts) }
} catch (error) {
return {
supported: true,
@@ -3047,82 +3089,20 @@ async function checkUpdates() {
// Checkout install: dispatch through the strategy layer — one mechanism,
// one stamp, no direct body path. The flow lives in updater/checkout.ts;
// this is the only production door to the checkout arms.
- return resolveCheckoutUpdateStrategy().check()
+ return resolveCheckoutUpdateStrategy().check(opts)
}
-// Best-effort exact behind-count for graphs the local clone can't measure.
-// Delegates URL building + response parsing to update-count.ts (pure, unit
-// tested); this wrapper only does the bounded network call. Any failure —
-// offline, 4xx/5xx, rate limit, shape surprise — returns null so callers keep
-// the honest "update available, count unknown" state.
-async function fetchCompareBehindCount({ currentSha, originUrl, targetSha }) {
- const url = compareApiUrl({ currentSha, originUrl, targetSha })
+async function fetchGitHubApi(url: string, accept: string = 'application/vnd.github+json'): Promise<unknown> {
+ const response = await fetch(url, {
+ headers: { Accept: accept, 'User-Agent': 'hermes-desktop-update-check' },
+ signal: AbortSignal.timeout(10_000)
+ })
- if (!url) {
- return null
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`)
}
- try {
- const payload = await new Promise((resolve, reject) => {
- const req = https.get(
- url,
- {
- headers: {
- Accept: 'application/vnd.github+json',
- // GitHub requires a UA on api.github.com; requests without one 403.
- 'User-Agent': 'hermes-desktop-update-check'
- },
- timeout: 10_000
- },
- res => {
- const chunks = []
- res.on('error', reject)
- res.on('data', chunk => chunks.push(chunk))
- res.on('end', () => {
- if ((res.statusCode || 500) >= 400) {
- reject(new Error(`compare API ${res.statusCode}`))
-
- return
- }
-
- try {
- resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
- } catch (error) {
- reject(error)
- }
- })
- }
- )
-
- req.on('timeout', () => req.destroy(new Error('compare API timeout')))
- req.on('error', reject)
- })
-
- return parseCompareBehindCount(payload)
- } catch {
- return null
- }
-}
-
-async function readCommitLog(cwd, branch, isShallow) {
- const SEP = '\x1f'
- const REC = '\x1e'
- const { limit, revision } = resolveCommitLogSelection({ branch, isShallow })
-
- const { stdout } = await runGit(
- ['log', revision, `--pretty=format:%H${SEP}%s${SEP}%an${SEP}%at${REC}`, '-n', String(limit)],
- { cwd }
- )
-
- return stdout
- .split(REC)
- .map(line => line.trim())
- .filter(Boolean)
- .map(line => {
- const [sha, summary, author, at] = line.split(SEP)
-
- return { sha, summary, author, at: Number.parseInt(at, 10) * 1000 }
- })
+ return accept === 'application/vnd.github.sha' ? response.text() : response.json()
}
let updateInFlight = false
@@ -3266,8 +3246,10 @@ function resolveCheckoutUpdateStrategy(): UpdaterStrategy {
getOriginUrl,
runGit,
firstLine,
- readCommitLog,
- fetchCompareBehindCount,
+ fetchGitHubApi,
+ isGitCheckout,
+ updateCheckCachePath: path.join(app.getPath('userData'), 'update-check-cache.json'),
+ writeFileAtomic,
pathWithVenvBin,
venvHermesShimPath,
emitUpdateProgress,
@@ -3998,7 +3980,7 @@ async function handOffWindowsBootstrapRecovery(reason) {
const updateRoot = resolveUpdateRoot()
const { branch: configuredBranch } = readDesktopUpdateConfig()
- const branch = directoryExists(path.join(updateRoot, '.git'))
+ const branch = isGitCheckout(updateRoot)
? await resolveHealedBranch(updateRoot, configuredBranch || DEFAULT_UPDATE_BRANCH)
: configuredBranch || DEFAULT_UPDATE_BRANCH
@@ -4711,7 +4693,24 @@ function resolveHermesBackend(backendArgs) {
}
}
-async function ensureRuntime(backend) {
+interface ResolvedHermesBackend {
+ kind: string
+ label: string
+ command: string | null
+ args: string[]
+ env: NodeJS.ProcessEnv
+ bootstrap: boolean
+ shell: boolean
+ local?: string
+ root?: string
+ installStamp?: Readonly<InstallStamp> | null
+ activeRoot?: string
+ readyFile?: boolean
+}
+
+async function ensureRuntime(backend: ResolvedHermesBackend): Promise<ResolvedHermesBackend> {
+ localBackendLifecycle.assertCanStart()
+
if (!backend.bootstrap) {
await advanceBootProgress('runtime.external', `Using ${backend.label}`, 32)
@@ -4771,6 +4770,7 @@ async function ensureRuntime(backend) {
void 0
}
+ localBackendLifecycle.assertCanStart()
bootstrapAbortController = new AbortController()
// The repair request has been honoured by reaching the installer; clear it
@@ -9903,9 +9903,7 @@ function clearManagedSshRecovery(connectionId, correlationId) {
const sshBootstrapCoordinator = createBootstrapCoordinator()
-let sshQuitTeardownDone = false
-let sshQuitTeardownPromise: Promise<void> | null = null
-let backendQuitTeardownDone = false
+const sshTeardowns = createSshTeardownTracker()
function sshScopeKey(profile) {
return connectionScopeKey(profile) || ''
@@ -9950,7 +9948,7 @@ async function teardownSshConnection(profile) {
// alone leaves the backend at pid 1 holding state.db (#91668).
// Windows remotes use a different lifecycle (connectWindowsRemote) and
// are left to a follow-up; POSIX is the leak that OOM'd gateways.
- await teardownSshState(
+ await sshTeardowns.track(state.ssh, (): Promise<void> => teardownSshState(
{
...state,
ownershipId: state.ownershipId || sshOwnershipKey(profile)
@@ -9966,7 +9964,7 @@ async function teardownSshConnection(profile) {
}
: remoteLifecycle.disconnect
}
- )
+ ))
}
// CRITICAL: this must mirror resolveRemoteBackend's precedence, not just return
@@ -10284,6 +10282,7 @@ async function bootstrapSshConnectionInner(profile, sshConfig, reuseToken, sourc
probeReuseProof: sshProbeReuseProof,
adoptServedToken: adoptServedDashboardToken,
rememberLog: sshRememberLog,
+ guestOnboarding: GUEST_ONBOARDING,
signal: lease.signal
})
} catch (error: any) {
@@ -10893,8 +10892,8 @@ function resetBootProgressForReconnect() {
)
}
-function stopBackendChild(child) {
- stopBackendChildImpl(child, { forceKillProcessTree, isWindows: IS_WINDOWS })
+function stopBackendChild(child: ChildProcess | null | undefined): void {
+ void localBackendLifecycle.stop(child).catch((error: unknown): void => rememberLog(`Backend teardown failed: ${error instanceof Error ? error.message : String(error)}`))
}
// Soft gateway-mode apply: tear down the primary without resetting boot UI or
@@ -10918,10 +10917,7 @@ function resetHermesConnection({ soft = false } = {}) {
// startHermes() spawns fresh instead of racing the dying one. Shared by the
// connection-config and profile switch flows.
async function teardownPrimaryBackendAndWait({ soft = false }: { soft?: boolean } = {}): Promise<void> {
- const stopping = backendConnectionState.stopProcess(async child => {
- stopBackendChild(child)
- await waitForBackendExit(child)
- })
+ const stopping = backendConnectionState.stopProcess(localBackendLifecycle.stop)
if (soft) {
softRehomeInProgress = true
@@ -10966,20 +10962,27 @@ function broadcastConnectionsChanged(payload: { connectionId: string; reason: 'r
}
}
-async function waitForBackendExit(child: ChildProcess | null | undefined, timeoutMs = 5000): Promise<void> {
- await waitForBackendExitImpl(child, processToStop => {
- if (IS_WINDOWS && Number.isInteger(processToStop.pid)) {
- forceKillProcessTree(processToStop.pid)
- } else if (Number.isInteger(processToStop.pid)) {
- try {
- process.kill(-processToStop.pid!, 'SIGKILL')
- } catch {
- processToStop.kill('SIGKILL')
- }
- } else {
- processToStop.kill('SIGKILL')
- }
- }, timeoutMs)
+const backendExitWaits = new Map<ChildProcess, Promise<void>>()
+
+function waitForBackendExit(child: ChildProcess | null | undefined, timeoutMs: number = 5000): Promise<void> {
+ if (!child) {
+ return Promise.resolve()
+ }
+
+ const existing = backendExitWaits.get(child)
+
+ if (existing) {
+ return existing
+ }
+
+ const waiting = waitForBackendExitImpl(child, { forceKillProcessTree, isWindows: IS_WINDOWS }, timeoutMs)
+ backendExitWaits.set(child, waiting)
+ void waiting.then(
+ (): boolean => backendExitWaits.delete(child),
+ (): boolean => backendExitWaits.delete(child)
+ )
+
+ return waiting
}
// The profile the primary (window) backend runs as. readActiveDesktopProfile()
@@ -12011,8 +12014,8 @@ function releaseLocalBackendSlot(entry: any) {
}
}
-function assertPoolEntryStillOwned(poolKey: string, entry: any) {
- if (backendPool.get(poolKey) !== entry) {
+function assertPoolEntryStillOwned(poolKey: string, entry: any): void {
+ if (localBackendLifecycle.signal.aborted || backendPool.get(poolKey) !== entry) {
releaseLocalBackendSlot(entry)
throw new Error(`Profile backend start for "${poolKey}" was cancelled before spawn.`)
}
@@ -12104,6 +12107,8 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
const spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(entry.spawnPriority)
+ assertPoolEntryStillOwned(poolKey, entry)
+
const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {
timeoutMs: POOL_SLOT_WAIT_MS,
priority: spawnPriority
@@ -12118,7 +12123,14 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
)
}
- entry.releaseLocalBackendSlot = await spawnRequest.acquired
+ const cancelRequest = (): void => { spawnRequest.cancel() }
+ localBackendLifecycle.signal.addEventListener('abort', cancelRequest, { once: true })
+
+ try {
+ entry.releaseLocalBackendSlot = await spawnRequest.acquired
+ } finally {
+ localBackendLifecycle.signal.removeEventListener('abort', cancelRequest)
+ }
if (entry.localBackendSpawnRequest === spawnRequest) {
entry.localBackendSpawnRequest = null
@@ -12137,6 +12149,8 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
let poolAnnounced = false
await waitForUpdateClearance(updateGateDeps(), {
+ signal: localBackendLifecycle.signal,
+ isCancelled: (): boolean => backendPool.get(poolKey) !== entry,
onWaitTick: reason => {
if (!poolAnnounced) {
poolAnnounced = true
@@ -12176,12 +12190,12 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)
assertPoolEntryStillOwned(poolKey, entry)
- const child = spawn(
+ const child = spawnOwnedBackend(
backend.command,
backend.args,
hiddenWindowsChildOptions({
cwd: hermesCwd,
- env: {
+ env: desktopBackendSpawnEnv({
...process.env,
HERMES_HOME,
...backend.env,
@@ -12199,7 +12213,7 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po
...parentIdentityEnv,
HERMES_WEB_DIST: webDist,
...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
- },
+ }, GUEST_ONBOARDING),
shell: backend.shell,
stdio: ['ignore', 'pipe', 'pipe']
})
@@ -12376,7 +12390,8 @@ function reapInstallRootedStragglers(excludePids: number[]): void {
}
}
-const backendShutdown = createBackendShutdownCoordinator(async () => {
+const backendShutdown = createBackendShutdownCoordinator(async (): Promise<void> => {
+ const localShutdown = localBackendLifecycle.shutdown()
const primary = backendConnectionState.getProcess()
const primaryStop = teardownPrimaryBackendAndWait()
const pooledStops = stopAllPoolBackends()
@@ -12386,11 +12401,21 @@ const backendShutdown = createBackendShutdownCoordinator(async () => {
poolIdleReaper = null
}
- await Promise.all([primaryStop, pooledStops])
+ await waitForTeardown([localShutdown, primaryStop, pooledStops], 7_000)
reapInstallRootedStragglers(Number.isInteger(primary?.pid) ? [primary.pid] : [])
})
+const quitTeardown = createQuitTeardownCoordinator((): void => app.quit())
+
+async function teardownSshForQuit(): Promise<void> {
+ for (const scope of sshConnections.keys()) {
+ void teardownSshConnection(scope || null).catch((error: unknown): void => rememberLog(`SSH teardown failed: ${error instanceof Error ? error.message : String(error)}`))
+ }
+
+ await sshTeardowns.finish(sshBootstrapCoordinator.promises(), (): Promise<void> => sshBootstrapCoordinator.forceCleanupAll())
+}
+
async function exitAfterBackendShutdown(code) {
await backendShutdown.run()
app.exit(code)
@@ -12459,6 +12484,7 @@ async function startHermes() {
}
await reapOrphanedBackendsOnce()
+ localBackendLifecycle.assertCanStart()
// Latched-failure short-circuit: once bootstrap has failed in this
// process, every subsequent startHermes() call re-throws the same error
@@ -12581,6 +12607,7 @@ async function startHermes() {
}
const setup = await runPrimaryBackendStartup({
+ signal: localBackendLifecycle.signal,
connectRemote,
ensureLocalRuntime: ensureRuntime,
prepareLocalBackend: async () => {
@@ -12633,12 +12660,12 @@ async function startHermes() {
throw new Error('Hermes backend start was superseded by a newer connection attempt.')
}
- const hermesProcess = spawn(
+ const hermesProcess = spawnOwnedBackend(
backend.command,
backend.args,
hiddenWindowsChildOptions({
cwd: hermesCwd,
- env: {
+ env: desktopBackendSpawnEnv({
...process.env,
// Explicitly pin HERMES_HOME for the child so Python's get_hermes_home()
// resolves to the SAME location our resolveHermesHome() picked. Without
@@ -12661,7 +12688,7 @@ async function startHermes() {
...parentIdentityEnv,
HERMES_WEB_DIST: webDist,
...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
- },
+ }, GUEST_ONBOARDING),
shell: backend.shell,
stdio: ['ignore', 'pipe', 'pipe']
})
@@ -12692,7 +12719,7 @@ async function startHermes() {
// surface as an unhandled rejection before the Promise.race below attaches.
portAnnouncement.catch(() => {})
- const processOwner = await backendConnectionState.claimProcess(connectionAttempt, hermesProcess, child => claimBackendChild(
+ const processOwner = await backendConnectionState.claimProcess(connectionAttempt, hermesProcess, (child: ChildProcess): ReturnType<typeof claimBackendChild> => claimBackendChild(
child,
`${backend.command} ${backend.args.join(' ')}`,
profile,
@@ -12838,10 +12865,7 @@ async function startHermes() {
throw error
}
- await backendConnectionState.stopProcess(async failedProcess => {
- stopBackendChild(failedProcess)
- await waitForBackendExit(failedProcess)
- })
+ await backendConnectionState.stopProcess(localBackendLifecycle.stop)
if (error instanceof FirstRunSetupResetError) {
throw error
@@ -13293,6 +13317,25 @@ const wakeIndicatorController = createWakeIndicatorWindowController({
wireWindow: window => wireCommonWindowHandlers(window, zoomWiringForWindowKind('wakeIndicator'))
})
+const introRevealController: ReturnType<typeof createIntroRevealWindowController> = createIntroRevealWindowController({
+ devServer: DEV_SERVER,
+ enabled: GUEST_ONBOARDING,
+ isMac: IS_MAC,
+ loadWindowUrl,
+ log: rememberLog,
+ mainWindow: (): BrowserWindow | null => mainWindow,
+ preloadPath: PRELOAD_PATH,
+ rendererIndex: resolveRendererIndex,
+ showMain: (): void => {
+ mainWindow.show()
+ mainWindow.focus()
+ },
+ wireWindow: (window: BrowserWindow): void => wireCommonWindowHandlers(window, zoomWiringForWindowKind('petOverlay'))
+})
+
+registerChatOnboardingWindow({ enabled: GUEST_ONBOARDING, mainWindow: (): BrowserWindow | null => mainWindow })
+registerMachineProfile()
+
// The pet overlay: a single transparent, frameless, always-on-top window that
// hosts ONLY the floating mascot. Shift-clicking the in-window pet "pops it out"
// here so it can leave the app's bounds and stay visible while Hermes is
@@ -14274,6 +14317,7 @@ function createWindow() {
mainWindow.on('closed', () => {
closePetOverlay()
wakeIndicatorController.close()
+ introRevealController.destroy()
if (mainWindow === createdMainWindow) {
mainWindow = null
@@ -16388,92 +16432,11 @@ ipcMain.handle('hermes:api', async (_event, request) => {
}
})
-// One deduper per cross-window cue — the choke point every window shares. Main
-// handles IPC serially, so the first window to claim a key wins with no race.
-const isDuplicateNotification = createEventDeduper()
-const claimedAmbientCue = createEventDeduper()
+// Speech claims outlive instant cues so throttled peer windows cannot replay a reply.
+const ownsAmbientCue: ReturnType<typeof createAmbientClaimArbiter> = createAmbientClaimArbiter()
+ipcMain.handle('hermes:ambient:claim', (_event: IpcMainInvokeEvent, key: unknown): boolean => ownsAmbientCue(String(key ?? '')))
-// A window asks "do I own this ambient cue (turn-end sound / spoken reply)?".
-// The first caller within the window gets true; peers get false and stay quiet.
-ipcMain.handle('hermes:ambient:claim', (_event, key) => !claimedAmbientCue(String(key ?? '')))
-
-ipcMain.handle('hermes:notify', (_event, payload) => {
- if (!Notification.isSupported()) {
- return false
- }
-
- // Multiple full windows each run their own renderer throttle, so the same
- // kind+session can arrive here twice. Collapse it at this single choke point.
- // Return true (not false): a notification for the event IS being shown by the
- // first caller, so the settings "send test" success probe stays honest.
- if (isDuplicateNotification(`${payload?.kind ?? ''}:${payload?.sessionId ?? payload?.tag ?? ''}`)) {
- return true
- }
-
- // Action buttons render only on signed macOS builds; elsewhere they're dropped
- // and the body click still works.
- const actions = Array.isArray(payload?.actions) ? payload.actions : []
- const icon = typeof payload?.icon === 'string' && payload.icon.trim() ? payload.icon.trim() : undefined
-
- const notification = new Notification({
- title: payload?.title || 'Hermes',
- body: payload?.body || '',
- silent: Boolean(payload?.silent),
- ...(icon ? { icon } : {}),
- actions: actions.map(action => ({ type: 'button', text: String(action?.text || '') }))
- })
-
- notification.on('click', () => {
- if (!mainWindow || mainWindow.isDestroyed()) {
- return
- }
-
- focusWindow(mainWindow)
-
- if (payload?.sessionId) {
- mainWindow.webContents.send('hermes:focus-session', payload.sessionId)
- }
-
- // Plugin / session-less activation — serializable path (+ optional notifyId
- // for renderer callbacks). Same vocabulary as hermes://index-network/….
- if (payload?.activate || payload?.notifyId) {
- mainWindow.webContents.send('hermes:notification-activate', {
- activate: payload?.activate,
- notifyId: payload?.notifyId,
- tag: payload?.tag
- })
- }
- })
- notification.on('action', (_actionEvent, index) => {
- if (!mainWindow || mainWindow.isDestroyed()) {
- return
- }
-
- const action = actions[index]
-
- if (!action?.id) {
- return
- }
-
- // Approvals keep the existing session-scoped channel.
- if (payload?.sessionId && !payload?.notifyId && !payload?.activate) {
- mainWindow.webContents.send('hermes:notification-action', { sessionId: payload.sessionId, actionId: action.id })
-
- return
- }
-
- focusWindow(mainWindow)
- mainWindow.webContents.send('hermes:notification-activate', {
- actionId: action.id,
- activate: action.activate || payload?.activate,
- notifyId: payload?.notifyId,
- tag: payload?.tag
- })
- })
- notification.show()
-
- return true
-})
+registerNativeNotifications({ getMainWindow: (): BrowserWindow | null => mainWindow, focusWindow })
// Data-URL file load cap (composer attach + local previews). Main owns the
// persisted MB value so every IPC read honours Settings → Chat without the
@@ -16871,11 +16834,14 @@ ipcMain.on('hermes:translucency:support', event => {
// stable builds, and canary builds get the same surfaces by default. Launch
// flags survive self-relaunches because collectRelaunchArgs only strips
// internal flags.
-ipcMain.on('hermes:feature-flags', event => {
- event.returnValue = resolveFeatureFlags({
- argv: process.argv,
- canary: resolveUpdaterChannelFromStamp() === 'canary'
- })
+ipcMain.on('hermes:feature-flags', (event: IpcMainEvent): void => {
+ event.returnValue = {
+ ...resolveFeatureFlags({
+ argv: process.argv,
+ canary: resolveUpdaterChannelFromStamp() === 'canary'
+ }),
+ guestOnboarding: GUEST_ONBOARDING
+ }
})
ipcMain.on('hermes:translucency', (_event, payload) => {
@@ -17232,8 +17198,8 @@ const terminalIpc = registerTerminalIpc({
const disposeTerminalSession = terminalIpc.disposeTerminalSession
-ipcMain.handle('hermes:updates:check', async () =>
- checkUpdates().catch(error => ({
+ipcMain.handle('hermes:updates:check', async (_event: Electron.IpcMainInvokeEvent, opts?: { force?: boolean }): Promise<UpdaterStatusWire> =>
+ checkUpdates({ force: Boolean(opts?.force) }).catch((error: Error): UpdaterStatusWire => ({
supported: true,
branch: readDesktopUpdateConfig().branch,
error: 'check-failed',
@@ -18037,50 +18003,22 @@ app.on('before-quit', event => {
// already quitting (#91668).
sshBootstrapCoordinator.shutdown()
- if (!backendQuitTeardownDone) {
- event.preventDefault()
- void backendShutdown.run().finally(() => {
- backendQuitTeardownDone = true
- app.quit()
- })
- }
-
- // backendShutdown.finally() re-enters before-quit. teardownSshConnection
- // already deleted the map entries, so size===0 would skip the kill wait
- // and let window-X quit finish while SSH exec is still running (#91668).
- if (
- sshQuitShouldBlock({
- teardownDone: sshQuitTeardownDone,
- connectionCount: sshConnections.size,
- bootstrapPending: sshBootstrapCoordinator.promises().length,
- inFlight: sshQuitTeardownPromise
- })
- ) {
- event.preventDefault()
-
- if (!sshQuitTeardownPromise) {
- const scopes = [...sshConnections.keys()]
+ const backendNeedsWait = backendQuitNeedsWait({
+ connectionPending: backendConnectionState.getPendingPromise() !== null || localBackendLifecycle.hasPending(),
+ poolPending: poolStopper.hasPending(),
+ processAttached: backendConnectionState.getProcess() !== null,
+ shutdownPending: backendShutdown.isPending()
+ })
- const pending = Promise.allSettled([
- ...scopes.map(scope => teardownSshConnection(scope || null)),
- ...sshBootstrapCoordinator.promises()
- ])
+ const sshNeedsWait = sshConnections.size > 0 || sshBootstrapCoordinator.promises().length > 0 || sshTeardowns.hasPending()
+ const teardownTasks: QuitTeardownTask[] = [{ run: (): Promise<void> => backendShutdown.run(), waitForCompletion: backendNeedsWait }]
- // cleanupStale waits up to 5s for the owned pid to exit (50 * 100ms).
- // The previous 4s race could close SSH first and leave serve --isolated
- // reparented to pid 1. Latch this promise BEFORE those deletes land so
- // a re-entrant quit still waits.
- sshQuitTeardownPromise = Promise.race([pending, new Promise<void>(resolve => setTimeout(resolve, 6_000))]).then(
- async () => {
- await sshBootstrapCoordinator.forceCleanupAll()
- }
- )
- }
+ if (sshNeedsWait) {
+ teardownTasks.push({ run: teardownSshForQuit, waitForCompletion: true })
+ }
- void sshQuitTeardownPromise.then(() => {
- sshQuitTeardownDone = true
- app.quit()
- })
+ if (quitTeardown.begin(teardownTasks)) {
+ event.preventDefault()
}
// Clean quit mid-boot should not trip next-launch --no-sandbox (#38216).
@@ -18099,6 +18037,7 @@ app.on('before-quit', event => {
// pet can't keep the process alive or float over a quit app.
closePetOverlay()
wakeIndicatorController.close()
+ introRevealController.destroy()
// Same for the HUD — an always-on-top panel outliving the app would leave a
// floating composer with nothing behind it. Close it directly rather than via
diff --git a/apps/desktop/electron/pool-stop.ts b/apps/desktop/electron/pool-stop.ts
index 2ba33640af1..beca9466c5f 100644
--- a/apps/desktop/electron/pool-stop.ts
+++ b/apps/desktop/electron/pool-stop.ts
@@ -22,17 +22,17 @@
* directly instead of grepping main.ts source text.
*/
-export interface PoolStopEntry {
- process?: unknown
+export interface PoolStopEntry<Process = unknown> {
+ process?: Process
}
-export interface PoolStopperDeps {
+export interface PoolStopperDeps<Process> {
/** The live backend pool. Entries are evicted synchronously on stop. */
- pool: Map<string, PoolStopEntry>
+ pool: Map<string, PoolStopEntry<Process>>
/** Signal the child (tree/group kill per platform). Synchronous. */
- stopChild: (child: unknown) => void
+ stopChild: (child: Process | undefined) => void
/** Bounded wait: resolves when the child exits, escalating to SIGKILL. */
- waitForExit: (child: unknown) => Promise<void>
+ waitForExit: (child: Process | undefined) => Promise<void>
}
export interface PoolStopper {
@@ -46,17 +46,23 @@ export interface PoolStopper {
stopAll: () => Promise<void>
}
-export function createPoolStopper(deps: PoolStopperDeps): PoolStopper {
- const stops = new Map<string, Promise<void>>()
+interface PendingStop<Process> {
+ entry: PoolStopEntry<Process>
+ completion: Promise<void>
+ failed: boolean
+}
+
+export function createPoolStopper<Process>(deps: PoolStopperDeps<Process>): PoolStopper {
+ const stops = new Map<string, PendingStop<Process>>()
function stop(key: string): Promise<void> {
const inFlight = stops.get(key)
- if (inFlight) {
- return inFlight
+ if (inFlight && !inFlight.failed) {
+ return inFlight.completion
}
- const entry = deps.pool.get(key)
+ const entry = inFlight?.entry ?? deps.pool.get(key)
if (!entry) {
return Promise.resolve()
@@ -66,26 +72,41 @@ export function createPoolStopper(deps: PoolStopperDeps): PoolStopper {
// below retains the process handle until the bounded exit completes.
deps.pool.delete(key)
- const stopping = (async () => {
+ const stopping = (async (): Promise<void> => {
deps.stopChild(entry.process)
await deps.waitForExit(entry.process)
- })().finally(() => {
- stops.delete(key)
- })
+ })().then(
+ (): void => {
+ stops.delete(key)
+ },
+ (error: unknown): never => {
+ pending.failed = true
+ throw error
+ }
+ )
- stops.set(key, stopping)
+ const pending: PendingStop<Process> = { entry, completion: stopping, failed: false }
+ stops.set(key, pending)
return stopping
}
return {
- inFlight: key => stops.get(key),
- hasPending: () => stops.size > 0 || [...deps.pool.values()].some(entry => entry.process != null),
+ inFlight: (key: string): Promise<void> | undefined => stops.get(key)?.completion,
+ hasPending: (): boolean =>
+ stops.size > 0 || [...deps.pool.values()].some((entry: PoolStopEntry<Process>): boolean => entry.process != null),
stop,
- stopAll: async () => {
- const currentStops = [...deps.pool.keys()].map(stop)
+ stopAll: async (): Promise<void> => {
+ const pending = new Set([...deps.pool.keys(), ...stops.keys()])
+ const results = await Promise.allSettled([...pending].map(stop))
+
+ const errors = results
+ .filter((result: PromiseSettledResult<void>): result is PromiseRejectedResult => result.status === 'rejected')
+ .map((result: PromiseRejectedResult): unknown => result.reason)
- await Promise.all(new Set([...stops.values(), ...currentStops]))
+ if (errors.length) {
+ throw new AggregateError(errors, 'Backend pool shutdown failed')
+ }
}
}
}
diff --git a/apps/desktop/electron/preload-flags.test.ts b/apps/desktop/electron/preload-flags.test.ts
new file mode 100644
index 00000000000..81fc510ea06
--- /dev/null
+++ b/apps/desktop/electron/preload-flags.test.ts
@@ -0,0 +1,24 @@
+import { expect, it, vi } from 'vitest'
+
+const host = vi.hoisted(() => ({
+ exposeInMainWorld: vi.fn(),
+ sendSync: vi.fn((channel: string): unknown => channel === 'hermes:feature-flags'
+ ? { localModels: true, guestOnboarding: true }
+ : {})
+}))
+
+vi.mock('electron', () => ({
+ contextBridge: { exposeInMainWorld: host.exposeInMainWorld },
+ ipcRenderer: { sendSync: host.sendSync },
+ webFrame: {},
+ webUtils: {}
+}))
+
+it('publishes the feature flags answered by main before the renderer starts', async (): Promise<void> => {
+ await import('./preload')
+ const registration = host.exposeInMainWorld.mock.calls.find(([name]): boolean => name === 'hermesDesktop')
+
+ expect(registration).toBeDefined()
+ expect(registration![1]).toMatchObject({ localModelsEnabled: true, guestOnboardingEnabled: true })
+ expect(host.sendSync).toHaveBeenCalledWith('hermes:feature-flags')
+})
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 1acd7040a81..0e3581f6db2 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -10,7 +10,7 @@ import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'
const translucencySupport = ipcRenderer.sendSync('hermes:translucency:support')
const hudWindowing = ipcRenderer.sendSync('hermes:hud:windowing')
const hudNativeDrag = hudWindowing?.nativeDrag === true
-const launchFlags = ipcRenderer.sendSync('hermes:launch-flags')
+const launchFlags: { localModels?: boolean; guestOnboarding?: boolean } | undefined = ipcRenderer.sendSync('hermes:feature-flags')
contextBridge.exposeInMainWorld('hermesDesktop', {
glassSupported: translucencySupport?.glass === true,
diff --git a/apps/desktop/electron/updater/checkout-check-live.test.ts b/apps/desktop/electron/updater/checkout-check-live.test.ts
new file mode 100644
index 00000000000..e1948b9717f
--- /dev/null
+++ b/apps/desktop/electron/updater/checkout-check-live.test.ts
@@ -0,0 +1,90 @@
+import { execFileSync } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as http from 'node:http'
+import type { AddressInfo } from 'node:net'
+import * as os from 'node:os'
+import * as path from 'node:path'
+
+import { expect, it } from 'vitest'
+
+import { checkCheckoutUpdates, type CheckoutCheckDeps } from './checkout-check'
+
+it('checks a real linked worktree through HTTP and reuses the disk cache until forced or HEAD changes', async (): Promise<void> => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-update-worktree-'))
+ const checkout = path.join(root, 'source')
+ const worktree = path.join(root, 'worktree')
+ const requests: string[] = []
+
+ const server = http.createServer((request: http.IncomingMessage, response: http.ServerResponse): void => {
+ requests.push(request.url ?? '')
+ response.end(targetSha)
+ })
+
+ let targetSha = ''
+
+ function git(args: string[], cwd: string = checkout): string {
+ return execFileSync('git', ['-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args], {
+ cwd,
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe']
+ }).trim()
+ }
+
+ try {
+ fs.mkdirSync(checkout)
+ git(['init', '--initial-branch=main'])
+ git(['commit', '--allow-empty', '-m', 'initial'])
+ git(['remote', 'add', 'origin', 'https://github.com/example/test.git'])
+ git(['worktree', 'add', '--detach', worktree])
+ targetSha = git(['rev-parse', 'HEAD'])
+ await new Promise<void>((resolve: () => void): void => { server.listen(0, '127.0.0.1', resolve) })
+ const address = server.address() as AddressInfo
+
+ const deps: CheckoutCheckDeps = {
+ updateCheckCachePath: path.join(root, 'cache.json'),
+ writeFileAtomic: (filePath: string, contents: string): void => {
+ fs.writeFileSync(`${filePath}.tmp`, contents)
+ fs.renameSync(`${filePath}.tmp`, filePath)
+ },
+ isGitCheckout: (directory: string): boolean => fs.existsSync(path.join(directory, '.git')),
+ readCanonicalInstallStamp: (): null => null,
+ readDesktopUpdateConfig: (): { branch: string } => ({ branch: 'main' }),
+ resolveUpdateRoot: (): string => worktree,
+ resolveHealedBranch: async (_directory: string, branch: string): Promise<string> => branch,
+ getOriginUrl: async (directory: string): Promise<string> => git(['remote', 'get-url', 'origin'], directory),
+ runGit: async (args: string[], options?: { cwd?: string }): Promise<{ code: number; stdout: string; stderr: string }> => {
+ // A passive check must not use git to contact the configured remote.
+ expect(['rev-parse', 'status']).toContain(args[0])
+
+ return { code: 0, stdout: git(args, options?.cwd), stderr: '' }
+ },
+ fetchGitHubApi: async (url: string, accept?: string): Promise<unknown> => {
+ const parsed = new URL(url)
+ expect(parsed.hostname).toBe('api.github.com')
+
+ const response = await fetch(`http://127.0.0.1:${address.port}${parsed.pathname}`, {
+ headers: { Accept: accept ?? 'application/json' }
+ })
+
+ return response.text()
+ },
+ rememberLog: (message: unknown): void => { throw new Error(String(message)) }
+ }
+
+ expect(fs.statSync(path.join(worktree, '.git')).isFile()).toBe(true)
+ expect(await checkCheckoutUpdates(deps)).toMatchObject({ supported: true, currentSha: targetSha, updateAvailable: false })
+ expect(requests).toHaveLength(1)
+ await checkCheckoutUpdates({ ...deps })
+ expect(requests).toHaveLength(1)
+ await checkCheckoutUpdates(deps, { force: true })
+ expect(requests).toHaveLength(2)
+ git(['commit', '--allow-empty', '-m', 'advance'], worktree)
+ targetSha = git(['rev-parse', 'HEAD'], worktree)
+ expect(await checkCheckoutUpdates(deps)).toMatchObject({ currentSha: targetSha, updateAvailable: false })
+ expect(requests).toHaveLength(3)
+ } finally {
+ server.closeAllConnections()
+ await new Promise<void>((resolve: () => void): void => { server.close((): void => resolve()) })
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/updater/checkout-check.test.ts b/apps/desktop/electron/updater/checkout-check.test.ts
new file mode 100644
index 00000000000..aac2bc03021
--- /dev/null
+++ b/apps/desktop/electron/updater/checkout-check.test.ts
@@ -0,0 +1,105 @@
+import * as fs from 'node:fs'
+import * as os from 'node:os'
+import * as path from 'node:path'
+
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { checkCheckoutUpdates, type CheckoutCheckDeps } from './checkout-check'
+
+const roots: string[] = []
+afterEach((): void => {
+ for (const root of roots.splice(0)) {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+function fixture(): CheckoutCheckDeps {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'checkout-check-'))
+ roots.push(root)
+
+ return {
+ writeFileAtomic: (filePath: string, contents: string): void => fs.writeFileSync(filePath, contents),
+ updateCheckCachePath: path.join(root, 'cache.json'),
+ isGitCheckout: (): boolean => true,
+ readCanonicalInstallStamp: (): null => null,
+ readDesktopUpdateConfig: (): { branch: string } => ({ branch: 'main' }),
+ resolveUpdateRoot: (): string => root,
+ resolveHealedBranch: async (_root: string, branch: string): Promise<string> => branch,
+ getOriginUrl: async (): Promise<string> => '[email protected]:NousResearch/hermes-agent.git',
+ runGit: vi.fn(async (args: string[]): Promise<{ code: number; stdout: string; stderr: string }> => {
+ const key = args.join(' ')
+
+ if (key === 'rev-parse HEAD') {
+ return { code: 0, stdout: 'a'.repeat(40), stderr: '' }
+ }
+
+ if (key === 'rev-parse --abbrev-ref HEAD') {
+ return { code: 0, stdout: 'main', stderr: '' }
+ }
+
+ if (key === 'status --porcelain') {
+ return { code: 0, stdout: '', stderr: '' }
+ }
+
+ throw new Error(`Unexpected git operation: ${key}`)
+ }),
+ fetchGitHubApi: vi.fn(async (url: string): Promise<unknown> =>
+ url.includes('/commits/') ? 'b'.repeat(40) : { ahead_by: 3, commits: [] }
+ ),
+ rememberLog: vi.fn()
+ }
+}
+
+it('uses API checks and a disk cache while a forced check bypasses the cache', async (): Promise<void> => {
+ const deps = fixture()
+ const first = await checkCheckoutUpdates(deps)
+ expect(first.behind).toBe(3)
+ expect(first.updateAvailable).toBe(true)
+ expect(deps.fetchGitHubApi).toHaveBeenCalledTimes(2)
+ expect(await checkCheckoutUpdates(deps)).toEqual(first)
+ expect(deps.fetchGitHubApi).toHaveBeenCalledTimes(2)
+ await checkCheckoutUpdates(deps, { force: true })
+ expect(deps.fetchGitHubApi).toHaveBeenCalledTimes(4)
+})
+
+it('does not report locally ahead commits as an update', async (): Promise<void> => {
+ const deps = fixture()
+ deps.fetchGitHubApi = async (url: string): Promise<unknown> =>
+ url.includes('/commits/') ? 'b'.repeat(40) : { ahead_by: 0 }
+ expect(await checkCheckoutUpdates(deps)).toMatchObject({ behind: 0, updateAvailable: false, commits: [] })
+})
+
+it('keeps an unknown count when the compare API fails', async (): Promise<void> => {
+ const deps = fixture()
+
+ deps.fetchGitHubApi = async (url: string): Promise<unknown> => {
+ if (url.includes('/commits/')) {
+ return 'b'.repeat(40)
+ }
+
+ throw new Error('rate limited')
+ }
+
+ expect(await checkCheckoutUpdates(deps)).toMatchObject({ behind: null, updateAvailable: true })
+})
+
+it('uses only ls-remote for non-GitHub network checks', async (): Promise<void> => {
+ const deps = fixture()
+ const localGit = deps.runGit
+ deps.getOriginUrl = async (): Promise<string> => 'https://git.example/repo.git'
+ deps.runGit = vi.fn(
+ async (args: string[], options: { cwd?: string }): Promise<{ code: number; stdout: string; stderr: string }> => {
+ if (args[0] === 'ls-remote') {
+ return { code: 0, stdout: `${'b'.repeat(40)}\trefs/heads/main`, stderr: '' }
+ }
+
+ if (args[0] === 'cat-file') {
+ return { code: 1, stdout: '', stderr: '' }
+ }
+
+ return localGit(args, options)
+ }
+ )
+ expect(await checkCheckoutUpdates(deps)).toMatchObject({ behind: null, updateAvailable: true })
+ expect(deps.fetchGitHubApi).not.toHaveBeenCalled()
+})
diff --git a/apps/desktop/electron/updater/checkout-check.ts b/apps/desktop/electron/updater/checkout-check.ts
new file mode 100644
index 00000000000..e0397fd184b
--- /dev/null
+++ b/apps/desktop/electron/updater/checkout-check.ts
@@ -0,0 +1,177 @@
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+import type { InstallStamp } from '../install-stamp'
+import { branchTipApiUrl, cacheIsFresh, compareApiUrl, githubRepoSlug, parseCompare } from '../update-api-check'
+import { classifyUpdateRoot } from '../update-root-policy'
+
+import type { UpdaterStatusWire } from './index'
+
+export interface CheckoutCheckDeps {
+ writeFileAtomic: (filePath: string, contents: string) => void
+ updateCheckCachePath: string
+ isGitCheckout: (root: string) => boolean
+ readCanonicalInstallStamp: () => { updateMechanism?: InstallStamp['updateMechanism'] } | null
+ readDesktopUpdateConfig: () => { branch: string }
+ resolveUpdateRoot: () => string
+ resolveHealedBranch: (root: string, branch: string) => Promise<string>
+ getOriginUrl: (root: string) => Promise<string>
+ runGit: (args: string[], options?: { cwd?: string }) => Promise<{ code: number; stdout: string; stderr: string }>
+ fetchGitHubApi: (url: string, accept?: string) => Promise<unknown>
+ rememberLog: (chunk: unknown) => void
+}
+
+interface CachedCheckoutCheck {
+ fetchedAt: number
+ currentSha: string
+ branch: string
+ originUrl: string
+ updateRoot: string
+ status: UpdaterStatusWire & Record<string, unknown>
+}
+
+function readCache(filePath: string): CachedCheckoutCheck | null {
+ try {
+ const cached: CachedCheckoutCheck = JSON.parse(fs.readFileSync(filePath, 'utf8'))
+
+ return cached?.status?.supported === true ? cached : null
+ } catch {
+ return null
+ }
+}
+
+async function checkApi(
+ deps: CheckoutCheckDeps,
+ slug: string,
+ branch: string,
+ currentSha: string
+): Promise<Partial<UpdaterStatusWire>> {
+ let targetSha: string
+
+ try {
+ targetSha = String(await deps.fetchGitHubApi(branchTipApiUrl(slug, branch), 'application/vnd.github.sha')).trim()
+ } catch (error: unknown) {
+ return { error: 'fetch-failed', message: `GitHub API: ${error instanceof Error ? error.message : String(error)}` }
+ }
+
+ if (!/^[0-9a-f]{40}$/i.test(targetSha)) {
+ return { error: 'fetch-failed', message: 'GitHub API returned no tip SHA.' }
+ }
+
+ if (targetSha === currentSha) {
+ return { behind: 0, updateAvailable: false, targetSha, commits: [] }
+ }
+
+ const compared = await deps
+ .fetchGitHubApi(compareApiUrl(slug, currentSha, targetSha))
+ .then(parseCompare)
+ .catch((): null => null)
+
+ return {
+ behind: compared?.behind ?? null,
+ updateAvailable: compared?.behind !== 0,
+ targetSha,
+ commits: compared?.behind === 0 ? [] : (compared?.commits ?? [])
+ }
+}
+
+async function checkLsRemote(
+ deps: CheckoutCheckDeps,
+ updateRoot: string,
+ branch: string,
+ currentSha: string
+): Promise<Partial<UpdaterStatusWire>> {
+ const target = await deps.runGit(['ls-remote', 'origin', `refs/heads/${branch}`], { cwd: updateRoot })
+ const targetSha = target.stdout.trim().split(/\s+/)[0] || ''
+
+ if (target.code !== 0 || !targetSha) {
+ return { error: 'fetch-failed', message: target.stderr.split('\n')[0] || 'git ls-remote failed.' }
+ }
+
+ if (targetSha === currentSha) {
+ return { behind: 0, updateAvailable: false, targetSha, commits: [] }
+ }
+
+ const known = (await deps.runGit(['cat-file', '-e', `${targetSha}^{commit}`], { cwd: updateRoot })).code === 0
+
+ const isAncestor =
+ known && (await deps.runGit(['merge-base', '--is-ancestor', targetSha, 'HEAD'], { cwd: updateRoot })).code === 0
+
+ return { behind: isAncestor ? 0 : null, updateAvailable: !isAncestor, targetSha, commits: [] }
+}
+
+/** Passive checks must not fetch packs or mutate a steward-owned checkout. */
+export async function checkCheckoutUpdates(
+ deps: CheckoutCheckDeps,
+ { force = false }: { force?: boolean } = {}
+): Promise<UpdaterStatusWire> {
+ const updateRoot = deps.resolveUpdateRoot()
+ let { branch } = deps.readDesktopUpdateConfig()
+
+ const policy = classifyUpdateRoot({
+ isGitTree: deps.isGitCheckout(updateRoot),
+ updateMechanism: deps.readCanonicalInstallStamp()?.updateMechanism ?? null
+ })
+
+ if (!policy.updatable) {
+ return {
+ supported: false,
+ reason: policy.verdict === 'not-a-checkout' ? 'not-a-git-checkout' : `update-root-${policy.verdict}`,
+ message: policy.message,
+ advice: policy.advice,
+ hermesRoot: updateRoot,
+ branch
+ }
+ }
+
+ const git = async (args: string[]): Promise<string> => (await deps.runGit(args, { cwd: updateRoot })).stdout.trim()
+
+ const [currentSha, dirty, currentBranch, originUrl] = await Promise.all([
+ git(['rev-parse', 'HEAD']),
+ git(['status', '--porcelain']),
+ git(['rev-parse', '--abbrev-ref', 'HEAD']),
+ deps.getOriginUrl(updateRoot)
+ ])
+
+ const cached = readCache(deps.updateCheckCachePath)
+ const now = Date.now()
+
+ if (
+ !force &&
+ cached?.updateRoot === updateRoot &&
+ cached.originUrl === originUrl &&
+ cacheIsFresh(cached, { branch, currentSha, now })
+ ) {
+ return { ...cached.status, dirty: dirty.length > 0, currentBranch }
+ }
+
+ branch = await deps.resolveHealedBranch(updateRoot, branch)
+ const slug = githubRepoSlug(originUrl)
+
+ const status = slug
+ ? await checkApi(deps, slug, branch, currentSha)
+ : await checkLsRemote(deps, updateRoot, branch, currentSha)
+
+ const result: UpdaterStatusWire & Record<string, unknown> = {
+ supported: true,
+ branch,
+ currentBranch,
+ currentSha,
+ dirty: dirty.length > 0,
+ hermesRoot: updateRoot,
+ fetchedAt: now,
+ ...status
+ }
+
+ try {
+ fs.mkdirSync(path.dirname(deps.updateCheckCachePath), { recursive: true })
+ const entry: CachedCheckoutCheck = { fetchedAt: now, currentSha, branch, originUrl, updateRoot, status: result }
+ deps.writeFileAtomic(deps.updateCheckCachePath, JSON.stringify(entry))
+ } catch (error: unknown) {
+ deps.rememberLog(
+ `[updates] could not persist check cache: ${error instanceof Error ? error.message : String(error)}`
+ )
+ }
+
+ return result
+}
diff --git a/apps/desktop/electron/updater/checkout-ownership.test.ts b/apps/desktop/electron/updater/checkout-ownership.test.ts
index cc5d7258d6b..dfb1d1fe3c4 100644
--- a/apps/desktop/electron/updater/checkout-ownership.test.ts
+++ b/apps/desktop/electron/updater/checkout-ownership.test.ts
@@ -4,6 +4,10 @@ import { type CheckoutStrategyDeps, createCheckoutStrategy } from './checkout'
function dependencies(): CheckoutStrategyDeps {
return {
+ isGitCheckout: (): boolean => true,
+ updateCheckCachePath: 'unused-cache.json',
+ writeFileAtomic: vi.fn(),
+ fetchGitHubApi: vi.fn(),
hermesHome: 'home',
isWindows: process.platform === 'win32',
isMac: process.platform === 'darwin',
@@ -18,8 +22,7 @@ function dependencies(): CheckoutStrategyDeps {
getOriginUrl: async () => '',
runGit: vi.fn(async () => { throw new Error('unexpected git invocation') }),
firstLine: text => text.split('\n')[0],
- readCommitLog: async () => [],
- fetchCompareBehindCount: async () => null,
+
pathWithVenvBin: () => '',
venvHermesShimPath: () => '',
emitUpdateProgress: vi.fn(),
@@ -36,7 +39,7 @@ function dependencies(): CheckoutStrategyDeps {
}
describe('checkout update admission', () => {
- it.each(['external', 'app-installer', 'electron-updater'])('refuses %s-owned code without fetching or stopping the backend', async updateMechanism => {
+ it.each(['external', 'app-installer', 'electron-updater'] as const)('refuses %s-owned code without fetching or stopping the backend', async updateMechanism => {
const deps = dependencies()
deps.readCanonicalInstallStamp = () => ({ updateMechanism })
const strategy = createCheckoutStrategy(deps)
@@ -51,7 +54,7 @@ describe('checkout update admission', () => {
it('rejects a missing source checkout without attempting git', async () => {
const deps = dependencies()
- deps.directoryExists = () => false
+ deps.isGitCheckout = (): boolean => false
const result = await createCheckoutStrategy(deps).check()
expect(result.reason).toBe('not-a-git-checkout')
diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.ts
index da91db47b6d..6dc31967393 100644
--- a/apps/desktop/electron/updater/checkout.ts
+++ b/apps/desktop/electron/updater/checkout.ts
@@ -2,11 +2,7 @@
import * as path from 'node:path'
-import { clearStaleGitLocks } from '../gitlock'
-import { resolveBehindCount, shouldCountCommits } from '../update-count'
import { updateHandoffConflict, writeUpdateMarker } from '../update-marker'
-import { isOfficialSshRemote, OFFICIAL_REPO_HTTPS_URL } from '../update-remote'
-import { classifyUpdateRoot } from '../update-root-policy'
import {
collectRelaunchArgs,
observeUpdaterHandoff,
@@ -20,33 +16,23 @@ import {
} from '../updater-process'
import { formatBlockerMessage, formatProbeFailedMessage, scanVenvBlockers, stopSafeVenvBlockers } from '../venv-blocker-scan'
+import { checkCheckoutUpdates, type CheckoutCheckDeps } from './checkout-check'
+
import type { UpdaterApplyResultWire, UpdaterMechanism, UpdaterStatusWire, UpdaterStrategy } from './index'
/**
* Everything the checkout flow needs from the app shell. These are the
* impure edges only — all update logic lives here.
*/
-export interface CheckoutStrategyDeps {
+export interface CheckoutStrategyDeps extends CheckoutCheckDeps {
hermesHome: string
isWindows: boolean
isMac: boolean
defaultUpdateBranch: string
updateHandoffDwellMs: number
directoryExists: (filePath: string) => boolean
- readCanonicalInstallStamp: () => { updateMechanism?: string } | null
- readDesktopUpdateConfig: () => { branch: string }
- resolveUpdateRoot: () => string
resolveUpdaterBinary: () => string | null
- resolveHealedBranch: (updateRoot: string, branch: string) => Promise<string>
- getOriginUrl: (updateRoot: string) => Promise<string>
- runGit: (args: string[], options?: { cwd?: string }) => Promise<{ code: number; stdout: string; stderr: string }>
firstLine: (text: string) => string
- readCommitLog: (
- cwd: string,
- branch: string,
- isShallow: boolean
- ) => Promise<{ sha: string; summary: string; author: string; at: number }[]>
- fetchCompareBehindCount: (input: { currentSha: string; originUrl: string; targetSha: string }) => Promise<number | null>
pathWithVenvBin: (...entries: string[]) => string
venvHermesShimPath: (updateRoot: string) => string
emitUpdateProgress: (payload: { stage: string; message: string; percent: number | null }) => void
@@ -81,8 +67,8 @@ export function buildManualUpdateCommand(currentBranch: string | null | undefine
export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrategy {
const mechanism: UpdaterMechanism = deps.isWindows ? 'windows-handoff' : 'posix-handoff'
- async function check(): Promise<UpdaterStatusWire> {
- const status = await checkBody()
+ async function check(opts: { force?: boolean } = {}): Promise<UpdaterStatusWire> {
+ const status = await checkCheckoutUpdates(deps, opts)
status.mechanism = mechanism
return status
@@ -97,179 +83,6 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
return { mechanism, check, apply }
- async function checkBody(): Promise<UpdaterStatusWire> {
- const updateRoot = deps.resolveUpdateRoot()
- let { branch } = deps.readDesktopUpdateConfig()
- const gitDir = path.join(updateRoot, '.git')
-
- if (!deps.directoryExists(gitDir)) {
- return {
- supported: false,
- reason: 'not-a-git-checkout',
- message: `${updateRoot} isn't a git checkout — desktop self-update only runs against a source install.`,
- hermesRoot: updateRoot,
- branch
- }
- }
-
- // The update-root policy (update-root-policy.ts): a `.git` tree the install
- // contract does not manage with updateMechanism "self" (or one with no
- // stamp at all — a dev checkout) is the only legitimate git-update
- // territory. A steward-owned tree (external / electron-updater) must not be
- // pulled into from the desktop.
- const rootStamp = deps.readCanonicalInstallStamp()
-
- const rootPolicy = classifyUpdateRoot({
- isGitTree: true,
- updateMechanism: (rootStamp?.updateMechanism as any) ?? null
- })
-
- if (!rootPolicy.updatable) {
- return {
- supported: false,
- reason: `update-root-${rootPolicy.verdict}`,
- message: rootPolicy.message || `${updateRoot} is not desktop-updatable.`,
- advice: rootPolicy.advice,
- hermesRoot: updateRoot,
- branch
- }
- }
-
- branch = await deps.resolveHealedBranch(updateRoot, branch)
- const originUrl = await deps.getOriginUrl(updateRoot)
-
- if (isOfficialSshRemote(originUrl)) {
- const git = args => deps.runGit(args, { cwd: updateRoot }).then(r => r.stdout.trim())
-
- const [currentSha, target, dirtyStr, currentBranch] = await Promise.all([
- git(['rev-parse', 'HEAD']),
- deps.runGit(['ls-remote', OFFICIAL_REPO_HTTPS_URL, `refs/heads/${branch}`], { cwd: updateRoot }),
- git(['status', '--porcelain']),
- git(['rev-parse', '--abbrev-ref', 'HEAD'])
- ])
-
- const targetSha = deps.firstLine(target.stdout).split(/\s+/)[0] || ''
-
- if (target.code !== 0 || !targetSha) {
- return {
- supported: true,
- branch,
- error: 'fetch-failed',
- message: deps.firstLine(target.stderr) || 'git ls-remote failed.',
- hermesRoot: updateRoot,
- fetchedAt: Date.now()
- }
- }
-
- // Passive SSH-official checks only know tip SHAs (ls-remote) — never
- // fabricate a "1 commit behind". Recover the exact count via the GitHub
- // compare API when possible; otherwise behind stays null ("update
- // available, count unknown") and updateAvailable carries the signal.
- // ahead_by === 0 with differing tips means the remote tip is reachable
- // from our HEAD — a local carried commit sitting AHEAD, not behind:
- // flagging that as an update nudges the user into wiping their work.
- const tipsEqual = Boolean(currentSha && currentSha === targetSha)
-
- const sshBehind = tipsEqual
- ? 0
- : await deps.fetchCompareBehindCount({ currentSha, originUrl: OFFICIAL_REPO_HTTPS_URL, targetSha })
-
- const upToDate = tipsEqual || sshBehind === 0
-
- return {
- supported: true,
- branch,
- currentBranch,
- behind: upToDate ? 0 : sshBehind,
- updateAvailable: !upToDate,
- currentSha,
- targetSha,
- commits: [],
- dirty: dirtyStr.length > 0,
- hermesRoot: updateRoot,
- fetchedAt: Date.now()
- }
- }
-
- // Self-heal abandoned git lock files before fetching. A stale
- // .git/shallow.lock from a crashed/interrupted fetch otherwise fails every
- // later fetch ("Unable to create '.git/shallow.lock': File exists") and this
- // check reports 'fetch-failed' forever — git never removes these itself.
- await clearStaleGitLocks(updateRoot)
-
- const fetched = await deps.runGit(['fetch', '--quiet', 'origin', branch], { cwd: updateRoot })
-
- if (fetched.code !== 0) {
- return {
- supported: true,
- branch,
- error: 'fetch-failed',
- message: deps.firstLine(fetched.stderr) || 'git fetch failed.',
- hermesRoot: updateRoot,
- fetchedAt: Date.now()
- }
- }
-
- const git = args => deps.runGit(args, { cwd: updateRoot }).then(r => r.stdout.trim())
-
- const [currentSha, targetSha, dirtyStr, currentBranch, shallowStr] = await Promise.all([
- git(['rev-parse', 'HEAD']),
- git(['rev-parse', `origin/${branch}`]),
- git(['status', '--porcelain']),
- git(['rev-parse', '--abbrev-ref', 'HEAD']),
- git(['rev-parse', '--is-shallow-repository'])
- ])
-
- const isShallow = shallowStr === 'true'
-
- // A shallow graph cannot provide a trustworthy exact count, even when it has
- // a visible merge-base. Skip the ancestry walk and use the SHA fallback.
- const countStr = shouldCountCommits({ isShallow }) ? await git(['rev-list', `HEAD..origin/${branch}`, '--count']) : ''
-
- // A positive directional ancestry result remains trustworthy in a shallow
- // graph and prevents a local commit on top of origin from looking outdated.
- const targetIsAncestorOfHead =
- isShallow &&
- currentSha !== targetSha &&
- (await deps.runGit(['merge-base', '--is-ancestor', `origin/${branch}`, 'HEAD'], { cwd: updateRoot })).code === 0
-
- let behind = resolveBehindCount({
- countStr,
- currentSha,
- targetSha,
- isShallow,
- targetIsAncestorOfHead
- })
-
- // Recover the exact count a shallow clone can't compute: the GitHub compare
- // API knows the full graph regardless of local clone depth. Best-effort —
- // offline, rate-limited, or non-GitHub origins keep the honest null
- // ("update available", no fabricated number).
- if (behind === null) {
- behind = await deps.fetchCompareBehindCount({ currentSha, originUrl, targetSha })
- }
-
- // behind === null means "update available, exact count unknown" (shallow
- // clone): still list what origin offers — resolveCommitLogSelection keeps
- // the shallow log to the fetched tip so the range walk can't enumerate the
- // contaminated ancestry — so "See what's new" stays useful and honest.
- const commits = behind !== 0 ? await deps.readCommitLog(updateRoot, branch, isShallow) : []
-
- return {
- supported: true,
- branch,
- currentBranch,
- behind,
- updateAvailable: behind === null || behind > 0,
- currentSha,
- targetSha,
- commits,
- dirty: dirtyStr.length > 0,
- hermesRoot: updateRoot,
- fetchedAt: Date.now()
- }
- }
-
async function applyBody(opts: { stopSafeBlockers?: boolean } = {}): Promise<UpdaterApplyResultWire> {
const updater = deps.resolveUpdaterBinary()
diff --git a/apps/desktop/electron/updater/index.ts b/apps/desktop/electron/updater/index.ts
index 08ffdf9979d..09140096b1d 100644
--- a/apps/desktop/electron/updater/index.ts
+++ b/apps/desktop/electron/updater/index.ts
@@ -84,6 +84,6 @@ export interface UpdaterApplyResultWire {
export interface UpdaterStrategy {
readonly mechanism: UpdaterMechanism
- check(): Promise<UpdaterStatusWire>
+ check(opts?: { force?: boolean }): Promise<UpdaterStatusWire>
apply(opts: { stopSafeBlockers?: boolean }): Promise<UpdaterApplyResultWire>
}
diff --git a/apps/desktop/src/app/settings/about-settings.test.tsx b/apps/desktop/src/app/settings/about-settings.test.tsx
new file mode 100644
index 00000000000..697542dd363
--- /dev/null
+++ b/apps/desktop/src/app/settings/about-settings.test.tsx
@@ -0,0 +1,130 @@
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { DesktopUpdateStatus, DesktopVersionInfo, HermesConnection } from '@/global'
+import { en } from '@/i18n/en'
+import { $connection } from '@/store/session'
+import {
+ $backendUpdateStatus,
+ $desktopVersion,
+ $updateStatus,
+ checkBackendUpdates,
+ checkUpdates,
+ refreshDesktopVersion,
+ type UpdateApplyState
+} from '@/store/updates'
+
+import { AboutSettings } from './about-settings'
+
+vi.mock('@/store/session', async (): Promise<Record<string, unknown>> => {
+ const { atom } = await import('nanostores')
+
+ return { $connection: atom<HermesConnection | null>(null) }
+})
+
+vi.mock('@/store/updates', async (): Promise<Record<string, unknown>> => {
+ const { atom } = await import('nanostores')
+
+ const idle: UpdateApplyState = {
+ applying: false,
+ stage: 'idle',
+ message: '',
+ percent: null,
+ error: null,
+ command: null,
+ log: []
+ }
+
+ return {
+ $desktopVersion: atom<DesktopVersionInfo | null>(null),
+ $backendUpdateApply: atom<UpdateApplyState>(idle),
+ $backendUpdateChecking: atom<boolean>(false),
+ $backendUpdateStatus: atom<DesktopUpdateStatus | null>(null),
+ $updateApply: atom<UpdateApplyState>(idle),
+ $updateChecking: atom<boolean>(false),
+ $updateStatus: atom<DesktopUpdateStatus | null>(null),
+ checkBackendUpdates: vi.fn<() => Promise<DesktopUpdateStatus | null>>().mockResolvedValue(null),
+ checkUpdates: vi.fn<() => Promise<DesktopUpdateStatus | null>>().mockResolvedValue(null),
+ refreshDesktopVersion: vi.fn<() => Promise<DesktopVersionInfo | null>>().mockResolvedValue(null),
+ openUpdateOverlayFor: vi.fn(),
+ openUpdatesWindow: vi.fn(),
+ startActiveUpdate: vi.fn()
+ }
+})
+
+function connection(mode: 'local' | 'remote'): HermesConnection {
+ return {
+ baseUrl: 'http://gateway:9119',
+ isFullscreen: false,
+ mode,
+ nativeOverlayWidth: 0,
+ token: 'test-token',
+ wsUrl: 'ws://gateway:9119',
+ logs: [],
+ windowButtonPosition: null
+ }
+}
+
+describe('AboutSettings', (): void => {
+ beforeEach((): void => {
+ vi.clearAllMocks()
+ $connection.set(connection('local'))
+ $desktopVersion.set({
+ appVersion: '1.2.3',
+ electronVersion: '40',
+ nodeVersion: '26',
+ platform: 'linux',
+ hermesRoot: '/test/hermes',
+ installId: 'test-install'
+ })
+ $updateStatus.set({ supported: true, behind: 0 })
+ $backendUpdateStatus.set({ supported: true, behind: 0 })
+ })
+
+ afterEach((): void => {
+ cleanup()
+ })
+
+ it('shows shared version details and refreshes each remote gateway independently', (): void => {
+ const { rerender } = render(<AboutSettings />)
+
+ expect(screen.getByRole('heading', { name: en.updates.appName })).toBeTruthy()
+ expect(screen.getByText(en.updates.versionDetailsInstallId)).toBeTruthy()
+ expect(screen.getByText(en.updates.latestBody)).toBeTruthy()
+ expect(screen.queryByText(en.updates.latestBodyBackend)).toBeNull()
+ expect(refreshDesktopVersion).toHaveBeenCalledTimes(1)
+ expect(checkBackendUpdates).not.toHaveBeenCalled()
+
+ $connection.set(connection('remote'))
+ rerender(<AboutSettings />)
+
+ expect(screen.getByText(en.updates.latestBodyBackend)).toBeTruthy()
+ expect(checkBackendUpdates).toHaveBeenCalledTimes(1)
+ expect(screen.getAllByRole('link', { name: en.updates.releaseNotes })).toHaveLength(1)
+
+ $connection.set({ ...connection('remote'), baseUrl: 'http://other-gateway:9119' })
+ rerender(<AboutSettings />)
+
+ expect(refreshDesktopVersion).toHaveBeenCalledTimes(3)
+ expect(checkBackendUpdates).toHaveBeenCalledTimes(2)
+ })
+
+ it('forces a fresh check only for the card the user checks', async (): Promise<void> => {
+ $connection.set(connection('remote'))
+ render(<AboutSettings />)
+ vi.mocked(checkBackendUpdates).mockClear()
+
+ const buttons = screen.getAllByRole('button', { name: en.updates.checkNow })
+ fireEvent.click(buttons[0])
+ await waitFor((): void => {
+ expect(checkUpdates).toHaveBeenCalledWith({ force: true })
+ })
+ expect(checkBackendUpdates).not.toHaveBeenCalled()
+
+ fireEvent.click(buttons[1])
+ await waitFor((): void => {
+ expect(checkBackendUpdates).toHaveBeenCalledWith({ force: true })
+ })
+ expect(checkUpdates).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/apps/desktop/src/app/settings/about-settings.tsx b/apps/desktop/src/app/settings/about-settings.tsx
index 81f797078ce..d3ee52e31d5 100644
--- a/apps/desktop/src/app/settings/about-settings.tsx
+++ b/apps/desktop/src/app/settings/about-settings.tsx
@@ -1,235 +1,48 @@
import { useStore } from '@nanostores/react'
-import { useEffect, useState } from 'react'
+import { type ReactElement, useEffect } from 'react'
-import { BrandMark } from '@/components/brand-mark'
-import { Button } from '@/components/ui/button'
-import { Codicon } from '@/components/ui/codicon'
-import { type Translations, useI18n } from '@/i18n'
-import { AlertTriangle, CheckCircle2, ExternalLink, Loader2, RefreshCw } from '@/lib/icons'
-import { cn } from '@/lib/utils'
-import {
- $desktopVersion,
- $updateApply,
- $updateChecking,
- $updateStatus,
- checkUpdates,
- openUpdatesWindow,
- refreshDesktopVersion,
- startActiveUpdate
-} from '@/store/updates'
+import { UpdateStatusCard, VersionHero } from '@/components/update-status'
+import { VersionDetails } from '@/components/version-details'
+import { useI18n } from '@/i18n'
+import { RefreshCw } from '@/lib/icons'
+import { $connection } from '@/store/session'
+import { $desktopVersion, checkBackendUpdates, refreshDesktopVersion } from '@/store/updates'
-import { ListRow, SectionHeading, SettingsContent } from './primitives'
+import { SectionHeading, SettingsContent } from './primitives'
import { UninstallSection } from './uninstall-section'
-const RELEASE_NOTES_URL = 'https://github.com/NousResearch/hermes-agent/releases'
-const INSTALLER_URL = 'https://hermes-agent.nousresearch.com/'
-
-function relativeTime(ms: number | undefined, a: Translations['settings']['about']) {
- if (!ms) {
- return a.never
- }
-
- const diff = Date.now() - ms
-
- if (diff < 60_000) {
- return a.justNow
- }
-
- if (diff < 3_600_000) {
- return a.minAgo(Math.round(diff / 60_000))
- }
-
- if (diff < 86_400_000) {
- return a.hoursAgo(Math.round(diff / 3_600_000))
- }
-
- return a.daysAgo(Math.round(diff / 86_400_000))
-}
-
-export function AboutSettings() {
+export function AboutSettings(): ReactElement {
const { t } = useI18n()
- const a = t.settings.about
const version = useStore($desktopVersion)
- const status = useStore($updateStatus)
- const apply = useStore($updateApply)
- const checking = useStore($updateChecking)
- const [justChecked, setJustChecked] = useState(false)
+ const connection = useStore($connection)
+ const remote = connection?.mode === 'remote'
- // The version atom is loaded once at app boot, which makes About show a
- // stale number after a self-update (the running binary is current, the
- // displayed string is not). Re-read on mount so opening About always
- // reflects the running build.
- useEffect(() => {
+ // Refresh the running version when About opens or the active gateway changes.
+ useEffect((): void => {
void refreshDesktopVersion()
- }, [])
-
- const behind = status?.behind ?? 0
- // behind is null when the exact count is unknowable (shallow clone): the
- // backend flags that case via updateAvailable instead of a number.
- const updateAvailable = behind > 0 || Boolean(status?.updateAvailable)
- const supported = status?.supported !== false
- const applying = apply.applying || apply.stage === 'restart'
- const handleCheck = async () => {
- setJustChecked(false)
- const next = await checkUpdates({ force: true })
- setJustChecked(Boolean(next))
- }
-
- let statusLine: string
- let statusTone: 'idle' | 'available' | 'error' = 'idle'
-
- if (!supported) {
- statusLine = status?.message ?? a.cantUpdate
- statusTone = 'error'
- } else if (status?.error) {
- statusLine = status.message ? `${a.cantReach} ${status.message}` : a.cantReach
- statusTone = 'error'
- } else if (applying) {
- statusLine = a.installing
- statusTone = 'available'
- } else if (updateAvailable) {
- statusLine = behind > 0 ? a.updateReady(behind) : a.updateReadyUnknown
- statusTone = 'available'
- } else if (status) {
- statusLine = a.onLatest
- } else {
- statusLine = a.tapCheck
- }
+ if (remote) {
+ void checkBackendUpdates()
+ }
+ }, [connection, remote])
return (
<SettingsContent>
- <div className="flex flex-col items-center gap-3 pt-6 pb-2 text-center">
- <BrandMark className="size-16" />
- <div>
- <h2 className="text-lg font-semibold tracking-tight">{a.heading}</h2>
- <p className="mt-1 text-xs text-muted-foreground">
- {version?.appVersion ? a.version(version.appVersion) : a.versionUnavailable}
- </p>
- </div>
- {(version?.bundleOutOfSync || version?.bundleSwapPending) && (
- <div className="mx-auto w-full max-w-2xl rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-left text-sm">
- <div className="flex items-start gap-2">
- <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
- <div className="min-w-0">
- {version?.bundleSwapPending ? (
- // The updated app is already on disk — the updater swapped it
- // under this running process — so a restart loads it. Saying
- // "App build out of date" here would repeat the contradiction
- // this banner is meant to resolve: the Updates card below
- // already reports the runtime as current.
- <>
- <p className="font-medium">{a.bundleSwapPending}</p>
- <p className="mt-1 text-xs text-muted-foreground">{a.bundleSwapPendingDesc}</p>
- <Button
- className="mt-2"
- onClick={() => void window.hermesDesktop?.relaunchApp?.()}
- size="sm"
- variant="textStrong"
- >
- <RefreshCw className="size-3" />
- {a.bundleSwapPendingAction}
- </Button>
- </>
- ) : (
- <>
- <p className="font-medium">{a.bundleOutOfSync}</p>
- <p className="mt-1 text-xs text-muted-foreground">{a.bundleOutOfSyncDesc}</p>
- <Button asChild className="mt-2" size="sm" variant="textStrong">
- <a
- href={INSTALLER_URL}
- onClick={event => {
- event.preventDefault()
- void window.hermesDesktop?.openExternal?.(INSTALLER_URL)
- }}
- rel="noreferrer"
- target="_blank"
- >
- <ExternalLink className="size-3" />
- {a.bundleOutOfSyncAction}
- </a>
- </Button>
- </>
- )}
- </div>
- </div>
- </div>
- )}
- </div>
+ <VersionHero version={version} />
<div className="mx-auto mt-4 w-full max-w-2xl">
- <SectionHeading icon={RefreshCw} title={a.updates} />
-
- <div
- className={cn(
- 'rounded-xl border px-4 py-3 text-sm',
- statusTone === 'available' && 'border-primary/30 bg-primary/5 text-foreground',
- statusTone === 'error' && 'border-destructive/35 bg-destructive/5 text-destructive',
- statusTone === 'idle' && 'border-border/70 bg-muted/20 text-foreground'
- )}
- >
- <div className="flex items-start gap-2">
- {statusTone === 'available' ? (
- <Codicon className="mt-0.5 size-4 shrink-0 text-primary" name="cloud-download" size="1rem" />
- ) : statusTone === 'error' ? null : (
- <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
- )}
- <div className="min-w-0">
- <p className="font-medium">{statusLine}</p>
- <p className="mt-1 text-xs text-muted-foreground">
- {a.lastChecked(relativeTime(status?.fetchedAt, a))}
- {justChecked && !checking ? a.justNowSuffix : ''}
- </p>
- </div>
- </div>
-
- <div className="mt-3 flex flex-wrap items-center gap-4">
- <Button
- disabled={checking || applying || !supported}
- onClick={() => void handleCheck()}
- size="sm"
- variant="textStrong"
- >
- {checking ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}
- {checking ? a.checking : a.checkNow}
- </Button>
-
- {updateAvailable && supported && !applying && (
- <>
- <Button onClick={() => startActiveUpdate()} size="sm">
- {a.updateNow}
- </Button>
- <Button onClick={() => openUpdatesWindow('client')} size="sm" variant="textStrong">
- {a.seeWhatsNew}
- </Button>
- </>
- )}
+ <SectionHeading icon={RefreshCw} title={t.settings.about.updates} />
- <Button asChild className="ml-auto" size="sm" variant="text">
- <a
- href={RELEASE_NOTES_URL}
- onClick={event => {
- event.preventDefault()
- void window.hermesDesktop?.openExternal?.(RELEASE_NOTES_URL)
- }}
- rel="noreferrer"
- target="_blank"
- >
- <ExternalLink className="size-3" />
- {a.releaseNotes}
- </a>
- </Button>
- </div>
+ <div className="grid gap-3">
+ <UpdateStatusCard target="client" />
+ {/* Client and remote backend updates are independent. Only the client has release notes. */}
+ {remote && <UpdateStatusCard showReleaseNotes={false} target="backend" />}
</div>
- <ListRow
- description={a.automaticUpdatesDesc}
- hint={a.branchCommit(status?.branch ?? 'unknown', status?.currentSha?.slice(0, 7) ?? 'unknown')}
- title={a.automaticUpdates}
- />
+ {version && <VersionDetails version={version} />}
<UninstallSection />
</div>
</SettingsContent>
)
-}
+}
\ No newline at end of file
diff --git a/apps/desktop/src/components/update-status.tsx b/apps/desktop/src/components/update-status.tsx
index 368f45480d4..caf563050d9 100644
--- a/apps/desktop/src/components/update-status.tsx
+++ b/apps/desktop/src/components/update-status.tsx
@@ -1,5 +1,5 @@
import { useStore } from '@nanostores/react'
-import { type ReactNode, useState } from 'react'
+import { type ReactElement, type ReactNode, useState } from 'react'
import { BrandMark } from '@/components/brand-mark'
import { Button } from '@/components/ui/button'
@@ -210,20 +210,20 @@ export function UpdateStatusCard({
}: {
showReleaseNotes?: boolean
target: UpdateTarget
-}) {
+}): ReactElement {
const { t } = useI18n()
const u = t.updates
const isBackend = target === 'backend'
const status = useStore(isBackend ? $backendUpdateStatus : $updateStatus)
const checking = useStore(isBackend ? $backendUpdateChecking : $updateChecking)
const apply = useStore(isBackend ? $backendUpdateApply : $updateApply)
- const [justChecked, setJustChecked] = useState(false)
+ const [justChecked, setJustChecked] = useState<boolean>(false)
const view = deriveUpdateStatus({ apply, checking, status, target, u })
const handleCheck = async (): Promise<void> => {
setJustChecked(false)
- const next = await (isBackend ? checkBackendUpdates() : checkUpdates())
+ const next = await (isBackend ? checkBackendUpdates({ force: true }) : checkUpdates({ force: true }))
setJustChecked(Boolean(next))
}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 76d24256110..3afbd1b603f 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -1,7 +1,10 @@
import type { GatewayWsUrlResult } from '@hermes/shared'
import type { TranslucencyState } from '@hermes/shared/translucency'
+import type { MachineProfile } from '../electron/machine-profile'
+import type { HermesNotification } from '../electron/notification-types'
import type { PoolLimits } from '../electron/pool-limits'
+import type { GrowRequest } from '../electron/window-growth'
import type { WakeIndicatorState } from './lib/wake-indicator'
import type {
@@ -14,6 +17,8 @@ import type { QuickEntryStatePush, QuickEntryStatus, QuickEntrySubmitPayload } f
export {}
+export type DesktopMachineProfile = MachineProfile
+
declare global {
interface Window {
hermesDesktop: {
@@ -94,6 +99,18 @@ declare global {
setState: (state: WakeIndicatorState) => void
onState: (callback: (state: WakeIndicatorState) => void) => () => void
}
+ chatOnboarding?: {
+ grow: (request: GrowRequest) => void
+ soloBoot: () => void
+ }
+ introReveal?: {
+ open: (payload?: { hideMain?: boolean }) => Promise<{ ok: boolean }>
+ close: (payload?: { showMain?: boolean }) => Promise<{ ok: boolean }>
+ skip: () => void
+ ready: () => void
+ onSkip: (callback: () => void) => () => void
+ onClosed: (callback: () => void) => () => void
+ }
// The pop-out pet overlay: a transparent always-on-top window hosting only
// the mascot. The main renderer drives it (open/close/drag + state push);
// the overlay sends control messages back (pop-in, composer submit).
@@ -321,6 +338,8 @@ declare global {
translucencySupported?: boolean
/** Feature flag: the local-models UI is enabled. */
localModelsEnabled?: boolean
+ /** Launch flag shared with every backend the app starts. */
+ guestOnboardingEnabled?: boolean
setTranslucency?: (payload: TranslucencyState) => void
setKeepAwake?: (on: boolean) => void
setDisableF12?: (blocked: boolean) => void
@@ -378,6 +397,8 @@ declare global {
// resolved by Electron independently of the connected backend (#66899).
// Created on demand; returns the normalized absolute path.
desktopPluginsRoot?: () => Promise<string>
+ /** Refresh unified packages' desktop halves and return the touched paths. */
+ reconcileDesktopPlugins?: () => Promise<string[]>
/** LOCAL `<HERMES_HOME>/logs` (profile-aware) — error card "Open Logs". */
logsRoot?: () => Promise<string>
// Local AGENT-plugin root (<HERMES_HOME>/plugins), same Electron-local
@@ -522,6 +543,7 @@ declare global {
cancelBootstrap: () => Promise<{ ok: boolean; cancelled: boolean }>
onBootstrapEvent: (callback: (payload: DesktopBootstrapEvent) => void) => () => void
getVersion: (scope?: { connectionId?: string; profile?: string }) => Promise<DesktopVersionInfo>
+ getMachineProfile?: () => Promise<DesktopMachineProfile>
/** The latest pm/venv/plugin-operation receipt (machine-readable):
* bisect disables, failed rebuilds, update-check results. null when
* no venv operation has run yet. */
@@ -530,7 +552,7 @@ declare global {
relaunchApp?: () => Promise<void>
getRemoteDisplayReason?: () => Promise<string | null>
updates: {
- check: () => Promise<DesktopUpdateStatus>
+ check: (opts?: { force?: boolean }) => Promise<DesktopUpdateStatus>
apply: (opts?: DesktopUpdateApplyOptions) => Promise<DesktopUpdateApplyResult>
getBranch: () => Promise<{ branch: string }>
setBranch: (name: string) => Promise<{ branch: string }>
@@ -1347,23 +1369,6 @@ export interface HermesApiRequest {
connectionId?: string | null
}
-export interface HermesNotification {
- title?: string
- body?: string
- silent?: boolean
- kind?: string
- sessionId?: string
- /** Dedupe discriminator for session-less notifications (e.g. plugin id). */
- tag?: string
- /** Absolute icon path for Electron `Notification`. */
- icon?: string
- /** Resolved hash-router path opened on body click (plugin / deeplink-compatible). */
- activate?: string
- /** Renderer handle for onActivate / onAction callbacks. */
- notifyId?: string
- actions?: { id: string; text: string; activate?: string }[]
-}
-
export interface HermesPreviewTarget {
binary?: boolean
byteSize?: number
diff --git a/apps/desktop/src/store/updates.test.ts b/apps/desktop/src/store/updates.test.ts
index a8d6d21ec1c..047527e92f9 100644
--- a/apps/desktop/src/store/updates.test.ts
+++ b/apps/desktop/src/store/updates.test.ts
@@ -86,6 +86,7 @@ const {
$desktopVersion,
maybeNotifyUpdateAvailable,
checkBackendUpdates,
+ checkUpdates,
$backendUpdateStatus,
applyBackendUpdate,
$backendUpdateApply,
@@ -325,7 +326,7 @@ describe('checkBackendUpdates', () => {
vi.useRealTimers()
})
- it('maps the backend /update/check onto the backend status, including commits', async () => {
+ it('maps the backend /update/check onto the backend status, including commits', async (): Promise<void> => {
setRemote(true)
checkHermesUpdateSpy.mockResolvedValue({
install_method: 'git',
@@ -340,12 +341,15 @@ describe('checkBackendUpdates', () => {
const result = await checkBackendUpdates()
- expect(checkHermesUpdateSpy).toHaveBeenCalled()
+ expect(checkHermesUpdateSpy).toHaveBeenCalledWith(false)
expect(result?.behind).toBe(2)
expect(result?.updateAvailable).toBe(true)
expect(result?.commits?.[0]?.sha).toBe('abc1234')
expect(result?.supported).toBe(true)
expect($backendUpdateStatus.get()?.commits?.[0]?.summary).toBe('feat: x')
+
+ await checkBackendUpdates({ force: true })
+ expect(checkHermesUpdateSpy).toHaveBeenLastCalledWith(true)
})
it('preserves backend update_available when the backend cannot count commits', async () => {
@@ -1461,6 +1465,11 @@ describe('startUpdatePoller', () => {
expect(checkMock).toHaveBeenCalledTimes(1)
})
+ it('passes an explicit manual check through to the main process', async (): Promise<void> => {
+ await checkUpdates({ force: true })
+ expect(checkMock).toHaveBeenCalledWith({ force: true })
+ })
+
it('window focus only re-checks once the daily cadence has elapsed', async () => {
startUpdatePoller()
await vi.advanceTimersByTimeAsync(0)
diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.ts
index 58f9eb6a012..79f17b7463a 100644
--- a/apps/desktop/src/store/updates.ts
+++ b/apps/desktop/src/store/updates.ts
@@ -13,7 +13,8 @@ import type {
DesktopUpdateProgress,
DesktopUpdateStage,
DesktopUpdateStatus,
- DesktopVersionInfo
+ DesktopVersionInfo,
+ HermesConnection
} from '@/global'
import { checkHermesUpdate, getActionStatus, updateHermes } from '@/hermes'
import { translateNow } from '@/i18n'
@@ -64,10 +65,10 @@ export const $updateOverlayTarget = atom<UpdateTarget>('client')
export const setUpdateOverlayOpen = (open: boolean) => $updateOverlayOpen.set(open)
-export const openUpdateOverlayFor = (target: UpdateTarget) => {
+export const openUpdateOverlayFor = (target: UpdateTarget): void => {
$updateOverlayTarget.set(target)
$updateOverlayOpen.set(true)
- void (target === 'backend' ? checkBackendUpdates() : checkUpdates())
+ void (target === 'backend' ? checkBackendUpdates({ force: true }) : checkUpdates({ force: true }))
}
export const resetUpdateApplyState = () => {
@@ -396,7 +397,14 @@ function mapBackendCheck(res: BackendUpdateCheckResponse): DesktopUpdateStatus {
}
}
-export async function checkBackendUpdates(): Promise<DesktopUpdateStatus | null> {
+/** Only explicit user checks and post-update refreshes bypass the caches. */
+export interface UpdateCheckOptions {
+ force?: boolean
+}
+
+export async function checkBackendUpdates({
+ force = false
+}: UpdateCheckOptions = {}): Promise<DesktopUpdateStatus | null> {
if (!isRemoteMode() || $backendUpdateChecking.get()) {
return $backendUpdateStatus.get()
}
@@ -404,7 +412,7 @@ export async function checkBackendUpdates(): Promise<DesktopUpdateStatus | null>
$backendUpdateChecking.set(true)
try {
- const status = mapBackendCheck(await checkHermesUpdate(true))
+ const status = mapBackendCheck(await checkHermesUpdate(force))
$backendUpdateStatus.set(status)
maybeNotifyUpdateAvailable(status, 'backend')
@@ -425,7 +433,7 @@ export async function checkBackendUpdates(): Promise<DesktopUpdateStatus | null>
}
}
-export async function checkUpdates(): Promise<DesktopUpdateStatus | null> {
+export async function checkUpdates({ force = false }: UpdateCheckOptions = {}): Promise<DesktopUpdateStatus | null> {
const bridge = window.hermesDesktop?.updates
if (!bridge || $updateChecking.get()) {
@@ -435,7 +443,7 @@ export async function checkUpdates(): Promise<DesktopUpdateStatus | null> {
$updateChecking.set(true)
try {
- const status = await bridge.check()
+ const status = await bridge.check({ force })
$updateStatus.set(status)
maybeNotifyUpdateAvailable(status, 'client')
void refreshDesktopVersion()
@@ -574,7 +582,7 @@ function finishBackendApply(returned: boolean): DesktopUpdateApplyResult {
if (returned) {
$backendUpdateApply.set(IDLE)
setUpdateOverlayOpen(false)
- void checkBackendUpdates()
+ void checkBackendUpdates({ force: true })
// The update restarted the gateway process, which strands this window's
// WebSocket: over SSH/tailscale tunnels the old TCP connection often dies
// without a close event, so connectionState still reads 'open' while every
@@ -835,7 +843,7 @@ async function maybeNudgeClientAfterBackendUpdate(): Promise<void> {
return
}
- const status = (await checkUpdates().catch(() => null)) ?? $updateStatus.get()
+ const status = (await checkUpdates({ force: true }).catch((): null => null)) ?? $updateStatus.get()
if (!status || status.error || (!status.updateAvailable && (status.behind ?? 0) <= 0)) {
return
@@ -953,12 +961,12 @@ async function runEverythingUpdate(): Promise<void> {
// 3. The client last — its apply relaunches or hands off the app, so it
// must come after every dispatch above. Skipped when already current.
// Re-check rather than trusting `$updateStatus`: the cached value can be
- // up to a poll interval (30 min) old and was captured BEFORE the backend
+ // up to a poll interval (24h) old and was captured BEFORE the backend
// update above, so a cached `behind: 0` would skip the client leg and
// leave the app stale — the exact failure this flow exists to prevent.
// `checkUpdates()` resolves with an error-status rather than rejecting,
// so fall back to the pre-flow snapshot when the live check can't answer.
- const freshClientStatus = await checkUpdates().catch(() => null)
+ const freshClientStatus = await checkUpdates({ force: true }).catch((): null => null)
const clientStatus = freshClientStatus?.error ? cachedClientStatus : (freshClientStatus ?? cachedClientStatus)
if ((clientStatus?.behind ?? 0) > 0 || clientStatus?.updateAvailable) {
@@ -997,10 +1005,24 @@ function ingestProgress(payload: DesktopUpdateProgress): void {
let pollerStarted = false
let backgroundTimer: ReturnType<typeof setInterval> | null = null
-let lastFocusAt = 0
let connectionUnsub: (() => void) | null = null
let lastConnectionMode: string | undefined
+export const BACKGROUND_UPDATE_CHECK_MS = 24 * 60 * 60 * 1000
+const FOCUS_RECHECK_KEY = 'hermes.updates.last-passive-check'
+
+function passiveCheckDue(now: number): boolean {
+ const last = Number(storedString(FOCUS_RECHECK_KEY) ?? 0)
+
+ return !Number.isFinite(last) || now - last >= BACKGROUND_UPDATE_CHECK_MS
+}
+
+function runPassiveChecks(): void {
+ persistString(FOCUS_RECHECK_KEY, String(Date.now()))
+ void checkUpdates()
+ void checkBackendUpdates()
+}
+
/** Wire up background polling + progress streaming. Idempotent. */
export function startUpdatePoller(): void {
if (pollerStarted || typeof window === 'undefined') {
@@ -1014,15 +1036,14 @@ export function startUpdatePoller(): void {
}
pollerStarted = true
- void checkUpdates()
- void checkBackendUpdates()
+ runPassiveChecks()
void refreshDesktopVersion()
bridge.onProgress(ingestProgress)
// The poller starts at mount, before the gateway connects — so the first
// backend check above sees mode≠remote and no-ops. Re-check once the
// connection resolves to remote.
- connectionUnsub = $connection.subscribe(conn => {
+ connectionUnsub = $connection.subscribe((conn: HermesConnection | null): void => {
if (conn?.mode === lastConnectionMode) {
return
}
@@ -1035,13 +1056,7 @@ export function startUpdatePoller(): void {
})
window.addEventListener('focus', onFocus)
- backgroundTimer = setInterval(
- () => {
- void checkUpdates()
- void checkBackendUpdates()
- },
- 30 * 60 * 1000
- )
+ backgroundTimer = setInterval(runPassiveChecks, BACKGROUND_UPDATE_CHECK_MS)
}
export function stopUpdatePoller(): void {
@@ -1057,15 +1072,10 @@ export function stopUpdatePoller(): void {
pollerStarted = false
}
-function onFocus() {
- const now = Date.now()
+function onFocus(): void {
+ void refreshDesktopVersion()
- if (now - lastFocusAt < 5 * 60 * 1000) {
- return
+ if (passiveCheckDue(Date.now())) {
+ runPassiveChecks()
}
-
- lastFocusAt = now
- void checkUpdates()
- void checkBackendUpdates()
- void refreshDesktopVersion()
}