The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Share desktop shutdown completion and SQLite snapshot ownership
ethernet4e198ec6f809
diff --git a/apps/desktop/electron/backend-child.ts b/apps/desktop/electron/backend-child.tsindex 46c901ddf1f..34eb0cc0ea3 100644--- a/apps/desktop/electron/backend-child.ts+++ b/apps/desktop/electron/backend-child.ts@@ -33,13 +33,6 @@ export interface StopBackendChildDeps {killGroup?: (pgid: number, signal: string) => void}-export interface StopBackendTreesForUpdateDeps {- /** Synchronous Windows taskkill /T /F implementation. */- forceKillProcessTree: (pid: number) => void- /** Clears and stops the desktop's pooled backends. */- stopAllPoolBackends: () => void-}-export interface BackendProcessRoot {pid?: number | null}@@ -122,13 +115,13 @@ export async function waitForBackendExit(* throws (the process may already be gone) -- mirrors the original inline* best-effort semantics in main.ts.*/-export function stopBackendChild(child: KillableChild | null | undefined, deps: StopBackendChildDeps) {+export function stopBackendChild(child: KillableChild | null | undefined, deps: StopBackendChildDeps): void {if (!child || child.killed) {return}const isWindows = deps.isWindows ?? process.platform === 'win32'- const killGroup = deps.killGroup ?? ((pgid: number, signal: string) => process.kill(pgid, signal))+ const killGroup = deps.killGroup ?? ((pgid: number, signal: string): boolean => process.kill(pgid, signal))try {if (isWindows && Number.isInteger(child.pid)) {@@ -148,23 +141,3 @@ export function stopBackendChild(child: KillableChild | null | undefined, deps:// Already gone.}}--/**- * Stop every backend tree owned by a Windows Desktop update hand-off.- *- * Tree-kill the primary root while its PID is still live, then delegate pool- * teardown to the existing routine that tree-kills each pooled root exactly- * once before mutating its registry. In particular, do not signal the primary- * first: if that root exits before taskkill /T runs, Windows can no longer- * enumerate its MCP grandchildren and they survive with the venv locked.- */-export function stopBackendTreesForUpdate(- primary: BackendProcessRoot | null | undefined,- deps: StopBackendTreesForUpdateDeps-): void {- if (primary && Number.isInteger(primary.pid)) {- deps.forceKillProcessTree(primary.pid as number)- }-- deps.stopAllPoolBackends()-}diff --git a/apps/desktop/electron/backend-stop-overlap.test.ts b/apps/desktop/electron/backend-stop-overlap.test.tsnew file mode 100644index 00000000000..09eaca82ad0--- /dev/null+++ b/apps/desktop/electron/backend-stop-overlap.test.ts@@ -0,0 +1,89 @@+import assert from 'node:assert/strict'+import { type ChildProcess, spawn } from 'node:child_process'+import { once } from 'node:events'++import { test } from 'vitest'++import { stopBackendChild, waitForBackendExit } from './backend-child'+import { createLocalBackendLifecycle } from './local-backend-lifecycle'+import { releaseLocalBackendSlotAfterExit } from './pool-spawn-coordinator'+import { createPoolStopper } from './pool-stop'++test.skipIf(process.platform === 'win32')(+ 'eviction, update and quit share physical exit before releasing a slot',+ async (): Promise<void> => {+ let signals = 0+ let released = false++ const physical = {+ forceKillProcessTree: (): never => {+ throw new Error('POSIX test')+ }+ }++ const lifecycle = createLocalBackendLifecycle<ChildProcess>({+ cancelSetup: (): void => {},+ stopChild: (child: ChildProcess): void => {+ signals+++ stopBackendChild(child, physical)+ },+ waitForExit: (child: ChildProcess): Promise<void> => waitForBackendExit(child, physical)+ })++ const child = lifecycle.spawn((): ChildProcess =>+ spawn(+ process.execPath,+ [+ '-e',+ `+ process.on('SIGTERM', () => process.send('stopping'));+ process.on('message', () => process.exit(0));+ setInterval(() => {}, 1000);+ process.send('ready');+ `+ ],+ { detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }+ )+ )++ child.once('exit', (): boolean => lifecycle.release(child))++ const deps = {+ pool: new Map([['profile', { process: child }]]),+ stopChild: lifecycle.stop+ }++ const pool = createPoolStopper(deps)++ try {+ await once(child, 'message')+ const signalled = once(child, 'message')++ const eviction = releaseLocalBackendSlotAfterExit(+ (): void => {+ released = true+ },+ (): Promise<void> => pool.stop('profile')+ )++ const update = lifecycle.stop(child)+ const quit = lifecycle.shutdown()+ await signalled+ assert.equal(signals, 1)+ assert.equal(released, false, 'a pool slot must remain occupied while its process is alive')+ assert.ok(pool.inFlight('profile'))+ assert.throws((): ChildProcess => lifecycle.spawn((): ChildProcess => child))+ child.send('exit')+ await Promise.all([eviction, update, quit])+ assert.equal(child.exitCode, 0)+ assert.equal(released, true)+ assert.equal(pool.inFlight('profile'), undefined)+ assert.equal(lifecycle.hasPending(), false)+ } finally {+ if (child.exitCode === null && child.signalCode === null) {+ child.kill('SIGKILL')+ await once(child, 'exit')+ }+ }+ }+)diff --git a/apps/desktop/electron/local-backend-lifecycle.ts b/apps/desktop/electron/local-backend-lifecycle.tsindex 49f52d54760..fecacb3707b 100644--- a/apps/desktop/electron/local-backend-lifecycle.ts+++ b/apps/desktop/electron/local-backend-lifecycle.ts@@ -7,7 +7,7 @@ export async function waitForTeardown(tasks: readonly Promise<unknown>[], timeoutry {await Promise.race([Promise.allSettled(tasks),- new Promise<void>(resolve => {+ new Promise<void>((resolve: () => void): void => {timer = setTimeout(resolve, timeoutMs)})])@@ -29,7 +29,20 @@ interface LocalBackendLifecycleDeps<Child> {* shutdown signal and synchronous spawn fence make bounded waiting safe: a late* resolver can finish, but can never create another owned backend.*/-export function createLocalBackendLifecycle<Child>(deps: LocalBackendLifecycleDeps<Child>) {+export interface LocalBackendLifecycle<Child> {+ signal: AbortSignal+ assertCanStart: () => void+ hasPending: () => boolean+ start: <T>(run: () => Promise<T>) => Promise<T>+ spawn: (create: () => Child) => Child+ release: (child: Child) => boolean+ stop: (child: Child | null | undefined) => Promise<void>+ shutdown: () => Promise<void>+}++export function createLocalBackendLifecycle<Child>(+ deps: LocalBackendLifecycleDeps<Child>+): LocalBackendLifecycle<Child> {const controller = new AbortController()const starts = new Set<Promise<unknown>>()const children = new Set<Child>()@@ -46,21 +59,21 @@ export function createLocalBackendLifecycle<Child>(deps: LocalBackendLifecycleDereturn existing}- const stopping = (async () => {+ const stopping = (async (): Promise<void> => {deps.stopChild(child)await deps.waitForExit(child)})()stops.set(child, stopping)void stopping.then(- () => stops.delete(child),- () => stops.delete(child)+ (): boolean => stops.delete(child),+ (): boolean => stops.delete(child))return stopping}- const shutdown = createBackendShutdownCoordinator(() => {+ const shutdown = createBackendShutdownCoordinator((): Promise<void> => {controller.abort(new Error('Hermes Desktop is quitting.'))deps.cancelSetup()@@ -69,15 +82,15 @@ export function createLocalBackendLifecycle<Child>(deps: LocalBackendLifecycleDereturn {signal: controller.signal,- assertCanStart: () => controller.signal.throwIfAborted(),- hasPending: () => starts.size > 0 || children.size > 0 || stops.size > 0 || shutdown.isPending(),+ assertCanStart: (): void => controller.signal.throwIfAborted(),+ hasPending: (): boolean => starts.size > 0 || children.size > 0 || stops.size > 0 || shutdown.isPending(),start<T>(run: () => Promise<T>): Promise<T> {if (controller.signal.aborted) {return Promise.reject(controller.signal.reason)}// Defer invocation one microtask so the inventory precedes all work.- const promise = Promise.resolve().then(() => {+ const promise = Promise.resolve().then((): Promise<T> => {controller.signal.throwIfAborted()return run()@@ -85,8 +98,8 @@ export function createLocalBackendLifecycle<Child>(deps: LocalBackendLifecycleDestarts.add(promise)void promise.then(- () => starts.delete(promise),- () => starts.delete(promise)+ (): boolean => starts.delete(promise),+ (): boolean => starts.delete(promise))return promise@@ -98,7 +111,7 @@ export function createLocalBackendLifecycle<Child>(deps: LocalBackendLifecycleDereturn child},- release: (child: Child) => children.delete(child),+ release: (child: Child): boolean => children.delete(child),stop,shutdown: shutdown.run}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex d802875b697..a735fc591a8 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -37,7 +37,7 @@ import { appIconCandidates, resolveAppIcon } from './app-icon'import { stageAppInstallerFile } from './app-installer-file'import { appVersionInfo, type AppVersionInfo, assertSourceUpdateChannel, packagedReleaseChannel } from './app-version'import { runAppInstallerChecker } from './appinstaller-checker'-import { stopBackendChild as stopBackendChildImpl, stopBackendTreesForUpdate, waitForBackendExit as waitForBackendExitImpl } from './backend-child'+import { stopBackendChild as stopBackendChildImpl, waitForBackendExit } from './backend-child'import {type BackendOutputTail,claimDecision,@@ -59,7 +59,7 @@ import {makeUnsignedOauthError,waitForHermesReady} from './backend-health'-import { backendCommandMatches, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'+import { backendCommandMatches, type BackendOwnershipEntry, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'import {canImportHermesCli,execProbeSync,@@ -433,6 +433,7 @@ import { ExternalStrategy } from './updater/external'import { createMacStrategy } from './updater/mac-client'import { type ConsumedRelaunch, consumePendingRelaunch, registerUpdateRelaunch, type RelaunchRegistration } from './updater/relaunch'import { startRelaunchWaiter } from './updater/relaunch-waiter'+import { preflightStateDb } from './updater/state-db-preflight'import { createStoreStrategy } from './updater/store-client'import { isHermesOwnedVenvDaemon } from './venv-holder-select'import { fetchMarketplaceThemes, searchMarketplaceThemes } from './vscode-marketplace'@@ -1317,7 +1318,7 @@ const localBackendLifecycle = createLocalBackendLifecycle<ChildProcess>({stopBackendChildImpl(child, { forceKillProcessTree, isWindows: IS_WINDOWS })}},- waitForExit: (child: ChildProcess): Promise<void> => waitForBackendExit(child),+ waitForExit: (child: ChildProcess): Promise<void> => waitForBackendExit(child, { forceKillProcessTree, isWindows: IS_WINDOWS }),cancelSetup: (): void => {firstRunSetupGate?.resetForRetry()bootstrapAbortController?.abort()@@ -3159,7 +3160,10 @@ function resolveCheckoutUpdateStrategy(): UpdaterStrategy {startHermes,stopBackendsForUpdate,repairMacUpdaterHelper,- preflightStateDb,+ preflightStateDb: (home: string, log: (message: string) => void): void => {+ const root: string = resolveUpdateRoot()+ preflightStateDb({ python: findPythonForRoot(root), script: path.join(root, 'hermes_cli', 'backup_sqlite.py'), home, log })+ },runningAppBundle,markQuittingForHandoff: () => {isQuittingForHandoff = true@@ -3591,7 +3595,13 @@ const desktopParentStartMarker = createParentStartMarkerResolver({}})-async function claimBackendChild(child, command, profile, nonce, outputTail: BackendOutputTail | null = null) {+async function claimBackendChild(+ child: ChildProcess & { hermesBackendIdentity?: BackendOwnershipEntry },+ command: string,+ profile: string,+ nonce: string,+ outputTail: BackendOutputTail | null = null+): Promise<BackendOwnershipEntry> {// Probe/claim policy lives in backend-claim.ts (#93608): a marker probe// that fails against a LIVE child degrades to PID-only identity — matching// createParentStartMarkerResolver — instead of killing a healthy backend@@ -3601,8 +3611,7 @@ async function claimBackendChild(child, command, profile, nonce, outputTail: Bacconst decision = claimDecision(child.exitCode === null && !child.killed, probe)if (decision.action === 'fail') {- stopBackendChild(child)- await waitForBackendExit(child)+ await localBackendLifecycle.stop(child)throw new Error(`Hermes backend (PID ${child.pid}) died before its identity could be recorded: ${decision.reason}${outputTail?.describe() ?? ''}`)@@ -3638,8 +3647,7 @@ async function claimBackendChild(child, command, profile, nonce, outputTail: Bacreturn identity} catch (error) {- stopBackendChild(child)- await waitForBackendExit(child)+ await localBackendLifecycle.stop(child)throw new Error(`Could not persist ownership for the Hermes backend: ${error.message}${outputTail?.describe() ?? ''}`)@@ -3683,16 +3691,13 @@ function reapOrphanedBackendsOnce() {// `hermes update`; neither venv scans nor a second fleet stop belong here.async function stopBackendsForUpdate(): Promise<void> {if (IS_WINDOWS) {- stopBackendTreesForUpdate(backendConnectionState.getProcess(), {- forceKillProcessTree,- stopAllPoolBackends- })+ await Promise.all([teardownPrimaryBackendAndWait(), stopAllPoolBackends()])}}// Uninstall still deletes the installation and its historical venv. Unlike// generation updates, deletion must wait for those old files to be released.-async function releaseBackendLock(updateRoot, tag) {+async function releaseBackendLock(updateRoot: string, tag: string): Promise<{ unlocked: boolean }> {if (!IS_WINDOWS) {return { unlocked: true }}@@ -3717,10 +3722,7 @@ async function releaseBackendLock(updateRoot, tag) {}}- stopBackendTreesForUpdate(hermesProcess, {- forceKillProcessTree,- stopAllPoolBackends- })+ await Promise.all([teardownPrimaryBackendAndWait(), stopAllPoolBackends()])// Uninstall deletes the whole runtime. Drain separately-running gateways// through the CLI, rather than targeting a gateway worker by PID.@@ -3934,92 +3936,6 @@ function runningAppBundle() {return dir.endsWith('.app') ? dir : null}-// ── Pre-flight state.db integrity guard (#68474) ─────────────────────-// Take an emergency snapshot of state.db and verify the live copy is-// intact before any update process mutates the install. Runs in the-// desktop Electron process itself, before the backend is killed and-// before the updater is spawned — a separate safety net from the-// Python-level pre-update snapshot inside `hermes update`.-function preflightStateDb(hermesHome, rememberLog) {- const stateDbPath = path.join(hermesHome, 'state.db')-- if (!fileExists(stateDbPath)) {- rememberLog('[updates] state.db pre-flight: not found (fresh install?)')-- return- }-- try {- const stat = fs.statSync(stateDbPath)-- if (stat.size > 100) {- const fd = fs.openSync(stateDbPath, 'r')- const header = Buffer.alloc(16)-- fs.readSync(fd, header, 0, 16, 0)- fs.closeSync(fd)-- const expectedHeader = Buffer.from('SQLite format 3\0')- const headerOk = header.equals(expectedHeader)-- rememberLog(- `[updates] state.db pre-flight: size=${stat.size}, ` +- `headerOk=${headerOk}, headerHex=${header.toString('hex')}`- )-- if (!headerOk) {- rememberLog(- '[updates] state.db header is INVALID before update — ' +- 'this indicates pre-existing corruption or a concurrent write issue'- )- }-- // Emergency timestamped backup, separate from the Python-level snapshot.- const ts = new Date().toISOString().replace(/[:.]/g, '-')-- const emergencyPath = path.join(hermesHome, `state.db.pre-update-emergency-${ts}.bak`)-- try {- fs.copyFileSync(stateDbPath, emergencyPath)- const emergStat = fs.statSync(emergencyPath)-- rememberLog(`[updates] emergency state.db backup: ${emergencyPath} ` + `(${emergStat.size} bytes)`)-- // Prune to the 2 most recent emergency backups.- try {- const homeDir = fs.readdirSync(hermesHome)-- const backups = homeDir- .filter(- f =>- f.startsWith('state.db.pre-update-emergency-') &&- f.endsWith('.bak') &&- f !== path.basename(emergencyPath)- )- .sort()- .reverse()-- for (const old of backups.slice(2)) {- try {- fs.unlinkSync(path.join(hermesHome, old))- } catch {- void 0- }- }- } catch {- void 0- }- } catch (copyErr) {- rememberLog(`[updates] emergency state.db backup failed: ${copyErr.message}`)- }- } else {- rememberLog(`[updates] state.db too small (${stat.size} bytes) for a valid SQLite database`)- }- } catch (statErr) {- rememberLog(`[updates] could not stat state.db before update: ${statErr.message}`)- }-}-// macOS/Linux update hand-off: spawn the repo-owned posix orchestrator// (scripts/desktop-update/posix.sh) detached and QUIT. The script waits us// out, runs `hermes update`, swaps/relaunches the app bundle, and writes@@ -10752,20 +10668,13 @@ function resetBootProgressForReconnect() {)}-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-// reloading the renderer. The shell stays up; the renderer wipes session lists-// (so skeletons retrigger) and re-dials. Distinct from hard re-home (profile-// switch / crash recovery), which still resets boot progress + reloads.-function resetHermesConnection({ soft = false } = {}) {+// Reset routing and UI state only. Local callers must await physical teardown.+// Remote revalidation has no local child and can reset this state directly.+function resetHermesConnectionState({ soft = false }: { soft?: boolean } = {}): void {backendStartFailure = nullremoteReauthFailure = nullremoteLiveness.clear()- const hermesProcess = backendConnectionState.invalidate()- stopBackendChild(hermesProcess)+ backendConnectionState.invalidate()if (!soft) {resetBootProgressForReconnect()@@ -10784,7 +10693,7 @@ async function teardownPrimaryBackendAndWait({ soft = false }: { soft?: boolean}try {- resetHermesConnection({ soft })+ resetHermesConnectionState({ soft })await stopping} finally {if (soft) {@@ -10822,29 +10731,6 @@ function broadcastConnectionsChanged(payload: { connectionId: string; reason: 'r}}-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()// returns the desktop's stored preference, or null when unset (legacy launch// that defers to active_profile / default).@@ -11897,14 +11783,9 @@ function teardownFailedLocalBackend(poolKey: string, entry: any): Promise<void>const child = entry.processconst teardown = releaseLocalBackendSlotAfterExit(- () => releaseLocalBackendSlot(entry),- async () => {- stopBackendChild(child)- await waitForBackendExit(child)-- if (child && child.exitCode === null && child.signalCode === null) {- throw new Error(`Profile backend for "${poolKey}" did not exit; keeping the local slot occupied.`)- }+ (): void => releaseLocalBackendSlot(entry),+ async (): Promise<void> => {+ await localBackendLifecycle.stop(child)releaseBackendChild(child)}@@ -12190,13 +12071,12 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po// Bounded, deduplicated pool teardown (see pool-stop.ts): every stop path —// idle reaper, LRU eviction, profile delete/rename, quit — shares one// in-flight stop per key and retains the process handle until the bounded-// SIGTERM -> SIGKILL escalation in waitForBackendExit() resolves. Previously+// physical shutdown promise resolves. Previously// SIGTERM + immediate entry delete dropped the handle and a slow child// survived detached under PID 1.const poolStopper = createPoolStopper<ChildProcess>({pool: backendPool,- stopChild: child => stopBackendChild(child),- waitForExit: child => waitForBackendExit(child)+ stopChild: localBackendLifecycle.stop})async function stopPoolBackend(profile: string) {@@ -12333,7 +12213,7 @@ async function prepareProfileRenameRequest(request) {})}-async function startHermes() {+async function startHermes(): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {// Only the single-instance lock holder may reap/spawn/claim the desktop// backend. A lock-losing instance must stay inert even if some path reaches// here (e.g. the deferred-quit window before `ready`): its reapOrphans()@@ -12588,8 +12468,7 @@ async function startHermes() {))if (!processOwner) {- stopBackendChild(hermesProcess)- await waitForBackendExit(hermesProcess)+ await localBackendLifecycle.stop(hermesProcess)releaseBackendChild(hermesProcess)throw new Error('Hermes backend start was superseded by a newer connection attempt.')}@@ -14421,7 +14300,7 @@ ipcMain.handle('hermes:connection:revalidate', async () => {currentConnectionPromise: () => backendConnectionState.getPromise(),log: rememberLog,probe: (connection, path, options) => fetchJsonForBackend(connection, path, options),- resetConnection: () => resetHermesConnection({ soft: true }),+ resetConnection: () => resetHermesConnectionState({ soft: true }),tracker: remoteLiveness}),revalidatePool()@@ -14686,7 +14565,7 @@ ipcMain.handle('hermes:bootstrap:reset', async () => {return { ok: true }})-ipcMain.handle('hermes:bootstrap:repair', async () => {+ipcMain.handle('hermes:bootstrap:repair', async (): Promise<{ ok: boolean; bundled?: boolean; error?: string }> => {// A bundled install's payload is immutable and sealed at build time —// "repair" would re-run the installer against a separate// %LOCALAPPDATA%\hermes tree the app doesn't own. The only repair for a@@ -14745,7 +14624,7 @@ ipcMain.handle('hermes:bootstrap:repair', async () => {backendStartFailure = nullremoteReauthFailure = nullgetFirstRunSetupGate().resetForRepair()- resetHermesConnection()+ await teardownPrimaryBackendAndWait()return { ok: true }})diff --git a/apps/desktop/electron/pool-stop.test.ts b/apps/desktop/electron/pool-stop.test.tsindex ce497cbad0e..c6cc06c63c0 100644--- a/apps/desktop/electron/pool-stop.test.ts+++ b/apps/desktop/electron/pool-stop.test.ts@@ -13,25 +13,31 @@ interface Child {killed: boolean}-function harness() {- const pool = new Map<string, PoolStopEntry>()+function harness(): {+ addChild: (key: string) => Child+ events: string[]+ exitResolvers: Map<Child, () => void>+ pool: Map<string, PoolStopEntry<Child>>+ stopper: ReturnType<typeof createPoolStopper<Child>>+} {+ const pool = new Map<string, PoolStopEntry<Child>>()const events: string[] = []const exitResolvers = new Map<Child, () => void>()const stopper = createPoolStopper({pool,- stopChild: child => {+ stopChild: (child: Child | undefined): Promise<void> => {;(child as Child).killed = trueevents.push('stop')- },- waitForExit: child =>- new Promise<void>(resolve => {- exitResolvers.set(child as Child, () => {++ return new Promise<void>((resolve: () => void): void => {+ exitResolvers.set(child as Child, (): void => {;(child as Child).exited = trueevents.push('exit')resolve()})})+ }})function addChild(key: string): Child {@@ -181,9 +187,13 @@ test('failed stops block respawn and retain the child for a later stop retry', aconst stopper = createPoolStopper({pool,- stopChild: current => { attempts.push(current!) },- waitForExit: async current => {- if (refuses) { throw failure }+ stopChild: async (current: Child | undefined): Promise<void> => {+ attempts.push(current!)++ if (refuses) {+ throw failure+ }+current!.exited = true}})diff --git a/apps/desktop/electron/pool-stop.ts b/apps/desktop/electron/pool-stop.tsindex beca9466c5f..551c67f7b2c 100644--- a/apps/desktop/electron/pool-stop.ts+++ b/apps/desktop/electron/pool-stop.ts@@ -29,10 +29,8 @@ export interface PoolStopEntry<Process = unknown> {export interface PoolStopperDeps<Process> {/** The live backend pool. Entries are evicted synchronously on stop. */pool: Map<string, PoolStopEntry<Process>>- /** Signal the child (tree/group kill per platform). Synchronous. */- stopChild: (child: Process | undefined) => void- /** Bounded wait: resolves when the child exits, escalating to SIGKILL. */- waitForExit: (child: Process | undefined) => Promise<void>+ /** The physical lifecycle owns signalling, escalation and confirmed exit. */+ stopChild: (child: Process | undefined) => Promise<void>}export interface PoolStopper {@@ -73,8 +71,7 @@ export function createPoolStopper<Process>(deps: PoolStopperDeps<Process>): Pooldeps.pool.delete(key)const stopping = (async (): Promise<void> => {- deps.stopChild(entry.process)- await deps.waitForExit(entry.process)+ await deps.stopChild(entry.process)})().then((): void => {stops.delete(key)diff --git a/apps/desktop/electron/updater/app-installer.ts b/apps/desktop/electron/updater/app-installer.tsindex edaba628b81..21c86c0452a 100644--- a/apps/desktop/electron/updater/app-installer.ts+++ b/apps/desktop/electron/updater/app-installer.ts@@ -19,6 +19,7 @@ import {win32AppInstallerFeedPath} from '../app-updater'+import { applyPackagedHandoff } from './packaged-handoff'import type { RelaunchRegistration } from './relaunch'import type { UpdaterApplyResultWire, UpdaterStatusWire } from './index'@@ -106,57 +107,35 @@ export class AppInstallerStrategy {percent: 100})- let registration: RelaunchRegistration | undefined- let teardownStarted = false-- try {- await triggerAppInstallerUpdate(- feedBaseUrl,- this.deps.channel,- this.deps.light,- this.deps.installer,- async () => {- registration = await this.deps.registerPendingRelaunch(this.deps.appVersion)-- if (!registration.automatic) {+ return applyPackagedHandoff(+ {+ teardown: this.deps.teardownBundledBackend,+ restore: this.deps.restoreBundledBackend,+ emitProgress: this.deps.emitUpdateProgress,+ relaunch: {+ register: (): Promise<RelaunchRegistration> => this.deps.registerPendingRelaunch(this.deps.appVersion),+ onManual: (): void =>this.deps.emitUpdateProgress({- stage: 'restart', percent: 100,+ stage: 'restart',+ percent: 100,message: 'Automatic relaunch could not be registered. Reopen Hermes after App Installer finishes.'})- }-- teardownStarted = true- await this.deps.teardownBundledBackend()- },- sourceUri- )-- this.deps.quit()- } catch (error) {- const errors: unknown[] = [error]-- try {- await registration?.cancel()- } catch (cancelError) {- errors.push(cancelError)- }-- if (teardownStarted) {- try {- await this.deps.restoreBundledBackend()- } catch (restoreError) {- errors.push(restoreError)}+ },+ async (stop: () => Promise<void>): Promise<UpdaterApplyResultWire> => {+ await triggerAppInstallerUpdate(+ feedBaseUrl,+ this.deps.channel,+ this.deps.light,+ this.deps.installer,+ stop,+ sourceUri+ )+ this.deps.quit()++ return { ok: true, manual: false, bundled: true, handedOff: true, mechanism: this.mechanism }}-- const message = errors.map(item => item instanceof Error ? item.message : String(item)).join('; ')- this.deps.emitUpdateProgress({ stage: 'error', message, percent: null })-- if (errors.length > 1) { throw new AggregateError(errors, message, { cause: error }) }- throw error- }-- return { ok: true, manual: false, bundled: true, handedOff: true, mechanism: this.mechanism }+ )}}diff --git a/apps/desktop/electron/updater/mac.test.ts b/apps/desktop/electron/updater/mac.test.tsindex 19ec867cb16..c105d042524 100644--- a/apps/desktop/electron/updater/mac.test.ts+++ b/apps/desktop/electron/updater/mac.test.ts@@ -16,18 +16,28 @@ function fixture() {return { isUpdateAvailable: true, updateInfo: info, versionInfo: info }}),- downloadUpdate: vi.fn(async () => { events.push('download');+ downloadUpdate: vi.fn(async () => {+ events.push('download')- return [] }),- quitAndInstall: vi.fn(() => { events.push('install') }),+ return []+ }),+ quitAndInstall: vi.fn(() => {+ events.push('install')+ }),on: emitter.on.bind(emitter) as MacStrategyDeps['updater']['on'],removeListener: emitter.removeListener.bind(emitter) as MacStrategyDeps['updater']['removeListener']},channel: 'canary',appVersion: '0.28.0',- prepareInstall: vi.fn(async () => { events.push('verify') }),- beforeInstall: vi.fn(async () => { events.push('stop') }),- onInstallFailure: vi.fn(async () => { events.push('restore') }),+ prepareInstall: vi.fn(async () => {+ events.push('verify')+ }),+ beforeInstall: vi.fn(async () => {+ events.push('stop')+ }),+ onInstallFailure: vi.fn(async () => {+ events.push('restore')+ }),emitProgress: vi.fn()}@@ -48,8 +58,9 @@ describe('macOS strategy', () => {it.each(['downloadUpdate', 'prepareInstall'] as const)('keeps backends alive on %s failure', async failure => {const { deps, strategy, events, emitter } = fixture()- vi.mocked(failure === 'downloadUpdate' ? deps.updater.downloadUpdate : deps.prepareInstall)- .mockRejectedValueOnce(new Error('invalid update'))+ vi.mocked(failure === 'downloadUpdate' ? deps.updater.downloadUpdate : deps.prepareInstall).mockRejectedValueOnce(+ new Error('invalid update')+ )await expect(strategy.apply()).rejects.toThrow('invalid update')expect(events).not.toContain('stop')expect(events).not.toContain('install')@@ -60,7 +71,9 @@ describe('macOS strategy', () => {const { deps, strategy, events } = fixture()const info = { version: '0.27.0', files: [], releaseDate: '', path: '', sha512: '' }vi.mocked(deps.updater.checkForUpdates).mockResolvedValue({- isUpdateAvailable: false, updateInfo: info, versionInfo: info+ isUpdateAvailable: false,+ updateInfo: info,+ versionInfo: info})await strategy.apply()expect(events).toEqual([])@@ -69,15 +82,39 @@ describe('macOS strategy', () => {it('restores the backend if install handoff throws', async () => {const { deps, strategy, events } = fixture()- vi.mocked(deps.updater.quitAndInstall).mockImplementation(() => { throw new Error('handoff failed') })+ vi.mocked(deps.updater.quitAndInstall).mockImplementation(() => {+ throw new Error('handoff failed')+ })await expect(strategy.apply()).rejects.toThrow('handoff failed')expect(events.slice(-2)).toEqual(['stop', 'restore'])})+ it('preserves the handoff error when backend recovery also fails', async (): Promise<void> => {+ const { deps, strategy, emitter } = fixture()+ const handoff = new Error('native handoff failed')+ const recovery = new Error('backend recovery failed')+ vi.mocked(deps.updater.quitAndInstall).mockImplementation((): never => {+ throw handoff+ })+ vi.mocked(deps.onInstallFailure).mockRejectedValue(recovery)+ await expect(strategy.apply()).rejects.toMatchObject({ cause: handoff, errors: [handoff, recovery] })+ expect(deps.emitProgress).toHaveBeenLastCalledWith({+ stage: 'error',+ message: 'native handoff failed; backend recovery failed',+ percent: null+ })+ expect(emitter.listenerCount('download-progress')).toBe(0)+ })+it('rejects simultaneous apply calls', async () => {const { deps, strategy } = fixture()let release!: () => void- vi.mocked(deps.prepareInstall).mockImplementation(() => new Promise(resolve => { release = resolve }))+ vi.mocked(deps.prepareInstall).mockImplementation(+ () =>+ new Promise(resolve => {+ release = resolve+ })+ )const applying = strategy.apply()await vi.waitFor(() => expect(deps.prepareInstall).toHaveBeenCalledOnce())await expect(strategy.apply()).rejects.toThrow('already in progress')@@ -91,7 +128,11 @@ describe('native signature verification', () => {it('waits for native readiness and removes both listeners', async () => {const native = Object.assign(new EventEmitter(), { checkForUpdates: vi.fn() })let ready = false- const pending = prepareMacInstall(native).then(() => { ready = true })++ const pending = prepareMacInstall(native).then(() => {+ ready = true+ })+await Promise.resolve()expect(ready).toBe(false)native.emit('update-downloaded')diff --git a/apps/desktop/electron/updater/mac.ts b/apps/desktop/electron/updater/mac.tsindex 12ddfc17f71..03a4df8f7bb 100644--- a/apps/desktop/electron/updater/mac.ts+++ b/apps/desktop/electron/updater/mac.ts@@ -1,5 +1,7 @@import type { AppUpdater } from 'electron-updater'+import { applyPackagedHandoff } from './packaged-handoff'+import type { UpdaterApplyResultWire, UpdaterStatusWire, UpdaterStrategy } from './index'export interface MacStrategyDeps {@@ -20,7 +22,9 @@ export class MacStrategy implements UpdaterStrategy {constructor(private readonly deps: MacStrategyDeps) {}async check(): Promise<UpdaterStatusWire> {- if (this.applying) { throw new Error('An update is already in progress.') }+ if (this.applying) {+ throw new Error('An update is already in progress.')+ }return this.checkRelease()}@@ -28,7 +32,9 @@ export class MacStrategy implements UpdaterStrategy {private async checkRelease(): Promise<UpdaterStatusWire> {const result = await this.deps.updater.checkForUpdates()- if (!result) { throw new Error('The macOS updater is not active for this app.') }+ if (!result) {+ throw new Error('The macOS updater is not active for this app.')+ }return {supported: true,@@ -42,9 +48,11 @@ export class MacStrategy implements UpdaterStrategy {}async apply(): Promise<UpdaterApplyResultWire> {- if (this.applying) { throw new Error('An update is already in progress.') }+ if (this.applying) {+ throw new Error('An update is already in progress.')+ }+this.applying = true- let stopped = falseconst progress = ({ percent }: { percent: number }): void => {this.deps.emitProgress({ stage: 'fetch', message: 'Downloading the Hermes update.', percent })@@ -53,21 +61,33 @@ export class MacStrategy implements UpdaterStrategy {this.deps.updater.on('download-progress', progress)try {- const status = await this.checkRelease()-- if (!status.updateAvailable) { return { ok: true, mechanism: this.mechanism } }- await this.deps.updater.downloadUpdate()- this.deps.emitProgress({ stage: 'prepare', message: 'Verifying the signed macOS update.', percent: null })- await this.deps.prepareInstall()- stopped = true- await this.deps.beforeInstall()- this.deps.emitProgress({ stage: 'restart', message: 'Restarting Hermes to install the update.', percent: 100 })- this.deps.updater.quitAndInstall()-- return { ok: true, bundled: true, handedOff: true, mechanism: this.mechanism }- } catch (error) {- if (stopped) { await this.deps.onInstallFailure() }- throw error+ return await applyPackagedHandoff(+ {+ teardown: this.deps.beforeInstall,+ restore: this.deps.onInstallFailure,+ emitProgress: this.deps.emitProgress+ },+ async (stop: () => Promise<void>): Promise<UpdaterApplyResultWire> => {+ const status = await this.checkRelease()++ if (!status.updateAvailable) {+ return { ok: true, mechanism: this.mechanism }+ }++ await this.deps.updater.downloadUpdate()+ this.deps.emitProgress({ stage: 'prepare', message: 'Verifying the signed macOS update.', percent: null })+ await this.deps.prepareInstall()+ await stop()+ this.deps.emitProgress({+ stage: 'restart',+ message: 'Restarting Hermes to install the update.',+ percent: 100+ })+ this.deps.updater.quitAndInstall()++ return { ok: true, bundled: true, handedOff: true, mechanism: this.mechanism }+ }+ )} finally {this.deps.updater.removeListener('download-progress', progress)this.applying = false@@ -84,21 +104,32 @@ export interface NativeMacUpdater {}/** Download completion alone does not mean Squirrel accepted the signature. */-export function prepareMacInstall(native: NativeMacUpdater, timeoutMs = 120_000): Promise<void> {- return new Promise((resolve, reject) => {+export function prepareMacInstall(native: NativeMacUpdater, timeoutMs: number = 120_000): Promise<void> {+ return new Promise<void>((resolve: () => void, reject: (error: Error) => void): void => {const cleanup = (): void => {clearTimeout(timer)native.removeListener('error', failed)native.removeListener('update-downloaded', ready)}- const failed = (error: Error): void => { cleanup(); reject(error) }+ const failed = (error: Error): void => {+ cleanup()+ reject(error)+ }++ const ready = (): void => {+ cleanup()+ resolve()+ }- const ready = (): void => { cleanup(); resolve() }- const timer = setTimeout(() => failed(new Error('macOS update verification timed out.')), timeoutMs)+ const timer = setTimeout((): void => failed(new Error('macOS update verification timed out.')), timeoutMs)native.once('error', failed)native.once('update-downloaded', ready)- try { native.checkForUpdates() } catch (error) { failed(error as Error) }+ try {+ native.checkForUpdates()+ } catch (error) {+ failed(error as Error)+ }})}diff --git a/apps/desktop/electron/updater/packaged-handoff.ts b/apps/desktop/electron/updater/packaged-handoff.tsnew file mode 100644index 00000000000..8e0fa62e3c1--- /dev/null+++ b/apps/desktop/electron/updater/packaged-handoff.ts@@ -0,0 +1,62 @@+import type { RelaunchRegistration } from './relaunch'++import type { UpdaterApplyResultWire } from './index'++interface PackagedHandoffDeps {+ teardown: () => void | Promise<void>+ restore: () => Promise<void>+ emitProgress: (progress: { stage: string; message: string; percent: number | null }) => void+ relaunch?: {+ register: () => Promise<RelaunchRegistration>+ onManual: () => void+ }+}++/** Native preparation decides when it is safe to stop. Recovery has one owner. */+export async function applyPackagedHandoff(+ deps: PackagedHandoffDeps,+ apply: (stop: () => Promise<void>) => Promise<UpdaterApplyResultWire>+): Promise<UpdaterApplyResultWire> {+ let registration: RelaunchRegistration | undefined+ let teardownStarted = false++ const stop = async (): Promise<void> => {+ if (deps.relaunch) {+ registration = await deps.relaunch.register()++ if (!registration.automatic) {+ deps.relaunch.onManual()+ }+ }++ teardownStarted = true+ await deps.teardown()+ }++ try {+ return await apply(stop)+ } catch (error) {+ const errors: unknown[] = [error]++ try {+ await registration?.cancel()+ } catch (cancelError) {+ errors.push(cancelError)+ }++ if (teardownStarted) {+ try {+ await deps.restore()+ } catch (restoreError) {+ errors.push(restoreError)+ }+ }++ const message = errors+ .map((item: unknown): string => (item instanceof Error ? item.message : String(item)))+ .join('; ')++ deps.emitProgress({ stage: 'error', message, percent: null })+ throw errors.length > 1 ? new AggregateError(errors, message, { cause: error }) : error+ }+}diff --git a/apps/desktop/electron/updater/state-db-preflight.test.ts b/apps/desktop/electron/updater/state-db-preflight.test.tsnew file mode 100644index 00000000000..8f6a42fcc26--- /dev/null+++ b/apps/desktop/electron/updater/state-db-preflight.test.ts@@ -0,0 +1,88 @@+import assert from 'node:assert/strict'+import { spawn, spawnSync } from 'node:child_process'+import { once } from 'node:events'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++import { test } from 'vitest'++import { preflightStateDb } from './state-db-preflight'++test('the desktop preflight publishes committed WAL rows before its caller can stop the backend', async (): Promise<void> => {+ const home: string = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-db-'))+ const python: string = process.env.HERMES_PYTHON || 'python3'+ const script: string = fileURLToPath(new URL('../../../../hermes_cli/backup_sqlite.py', import.meta.url))++ const child = spawn(+ python,+ [+ '-I',+ '-S',+ '-u',+ '-c',+ `+import sqlite3, sys+c = sqlite3.connect(sys.argv[1])+c.execute('PRAGMA journal_mode=WAL')+c.execute('PRAGMA wal_autocheckpoint=0')+c.execute('CREATE TABLE messages (body TEXT)')+c.commit()+c.execute('PRAGMA wal_checkpoint(TRUNCATE)')+c.execute("INSERT INTO messages VALUES ('pending in WAL')")+c.commit()+print('ready', flush=True)+sys.stdin.readline()+c.close()+`,+ path.join(home, 'state.db')+ ],+ { stdio: ['pipe', 'pipe', 'pipe'] }+ )++ const logs: string[] = []++ try {+ await once(child.stdout!, 'data')+ preflightStateDb({+ python,+ script,+ home,+ log: (message: string): void => {+ logs.push(message)+ }+ })+ assert.equal(child.exitCode, null)+ const backups: string[] = fs.readdirSync(home).filter((name: string): boolean => name.endsWith('.bak'))+ assert.equal(backups.length, 1, logs.join('\n'))++ const verify = spawnSync(+ python,+ [+ '-I',+ '-S',+ '-c',+ `+import sqlite3, sys+with sqlite3.connect(sys.argv[1]) as c:+ assert c.execute('SELECT body FROM messages').fetchall() == [('pending in WAL',)]+`,+ path.join(home, backups[0]!)+ ],+ { encoding: 'utf8' }+ )++ assert.equal(verify.status, 0, verify.stderr)+ const exited = once(child, 'exit')+ child.stdin!.end('\n')+ await exited+ } finally {+ if (child.exitCode === null && child.signalCode === null) {+ child.kill('SIGKILL')+ await once(child, 'exit')+ }++ fs.rmSync(home, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/updater/state-db-preflight.ts b/apps/desktop/electron/updater/state-db-preflight.tsnew file mode 100644index 00000000000..d7c0b5ca626--- /dev/null+++ b/apps/desktop/electron/updater/state-db-preflight.ts@@ -0,0 +1,31 @@+import { execFileSync } from 'node:child_process'++import { hiddenWindowsChildOptions } from '../windows-child-options'++interface StateDbPreflight {+ python: string | null+ script: string+ home: string+ log: (message: string) => void+}++// Synchronous by design: the caller must not stop the backend before the snapshot.+export function preflightStateDb({ python, script, home, log }: StateDbPreflight): void {+ if (!python) {+ log('[updates] state.db pre-flight unavailable: Python not found')++ return+ }++ try {+ const result: string = execFileSync(+ python,+ ['-I', '-S', script, home],+ hiddenWindowsChildOptions({ encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'] })+ )++ log(`[updates] state.db pre-flight: ${result.trim()}`)+ } catch (error: unknown) {+ log(`[updates] state.db pre-flight failed: ${error instanceof Error ? error.message : String(error)}`)+ }+}diff --git a/apps/desktop/electron/updater/store.test.ts b/apps/desktop/electron/updater/store.test.tsindex 3ed532176f3..9098a85fce3 100644--- a/apps/desktop/electron/updater/store.test.ts+++ b/apps/desktop/electron/updater/store.test.ts@@ -38,6 +38,20 @@ function dependencies(failAt?: string): { deps: StoreStrategyDeps; calls: string}describe('Microsoft Store update lifecycle', () => {+ it('requires automatic relaunch and cancels registration without stopping the backend', async (): Promise<void> => {+ const { deps, calls } = dependencies()+ deps.registerPendingRelaunch = async (): Promise<+ Awaited<ReturnType<StoreStrategyDeps['registerPendingRelaunch']>>+ > => ({+ automatic: false,+ cancel: async (): Promise<void> => {+ calls.push('cancel')+ }+ })+ await expect(new StoreStrategy(deps).apply()).rejects.toThrow('Could not register automatic relaunch')+ expect(calls).toEqual(['download', 'cancel'])+ })+it('downloads before shutdown, owns relaunch before install, and keeps no-update non-destructive', async () => {const { deps, calls } = dependencies()const strategy = new StoreStrategy(deps)diff --git a/apps/desktop/electron/updater/store.ts b/apps/desktop/electron/updater/store.tsindex 48a3b7297e5..dd1412c1b49 100644--- a/apps/desktop/electron/updater/store.ts+++ b/apps/desktop/electron/updater/store.ts@@ -1,3 +1,4 @@+import { applyPackagedHandoff } from './packaged-handoff'import type { RelaunchRegistration } from './relaunch'import type { UpdaterApplyResultWire, UpdaterStatusWire, UpdaterStrategy } from './index'@@ -40,63 +41,50 @@ export class StoreStrategy implements UpdaterStrategy {}async apply(): Promise<UpdaterApplyResultWire> {- let registration: RelaunchRegistration | undefined- let stopped = false-- try {- this.deps.emitProgress({ stage: 'fetch', message: 'Downloading the update from Microsoft Store.', percent: null })- const downloaded = await this.deps.run('download')-- if (!downloaded.ok || downloaded.available === null) {- throw new Error(downloaded.error || 'Microsoft Store download did not complete')- }-- if (!downloaded.available) {- return { ok: true, updateAvailable: false, mechanism: this.mechanism }- }-- registration = await this.deps.registerPendingRelaunch(this.deps.appVersion)-- if (!registration.automatic) {- throw new Error('Could not register automatic relaunch for the Store update')- }-- stopped = true- await this.deps.teardown()- this.deps.emitProgress({- stage: 'restart',- message: 'Microsoft Store is installing the update. Hermes will reopen.',- percent: null- })- const installed = await this.deps.run('install')+ return applyPackagedHandoff(+ {+ teardown: this.deps.teardown,+ restore: this.deps.restore,+ emitProgress: this.deps.emitProgress,+ relaunch: {+ register: (): Promise<RelaunchRegistration> => this.deps.registerPendingRelaunch(this.deps.appVersion),+ onManual: (): never => {+ throw new Error('Could not register automatic relaunch for the Store update')+ }+ }+ },+ async (stop: () => Promise<void>): Promise<UpdaterApplyResultWire> => {+ this.deps.emitProgress({+ stage: 'fetch',+ message: 'Downloading the update from Microsoft Store.',+ percent: null+ })+ const downloaded = await this.deps.run('download')++ if (!downloaded.ok || downloaded.available === null) {+ throw new Error(downloaded.error || 'Microsoft Store download did not complete')+ }- if (!installed.ok || installed.available !== true) {- throw new Error(installed.error || 'Microsoft Store did not confirm installation')- }+ if (!downloaded.available) {+ return { ok: true, updateAvailable: false, mechanism: this.mechanism }+ }- this.deps.quit()+ await stop()+ this.deps.emitProgress({+ stage: 'restart',+ message: 'Microsoft Store is installing the update. Hermes will reopen.',+ percent: null+ })+ const installed = await this.deps.run('install')- return { ok: true, bundled: true, handedOff: true, mechanism: this.mechanism }- } catch (error) {- const errors: unknown[] = [error]+ if (!installed.ok || installed.available !== true) {+ throw new Error(installed.error || 'Microsoft Store did not confirm installation')+ }- try {- await registration?.cancel()- } catch (cancelError) {- errors.push(cancelError)- }+ this.deps.quit()- if (stopped) {- try {- await this.deps.restore()- } catch (restoreError) {- errors.push(restoreError)- }+ return { ok: true, bundled: true, handedOff: true, mechanism: this.mechanism }}-- const message = errors.map(item => (item instanceof Error ? item.message : String(item))).join('; ')- this.deps.emitProgress({ stage: 'error', message, percent: null })- throw errors.length > 1 ? new AggregateError(errors, message, { cause: error }) : error- }+ )}}diff --git a/apps/desktop/electron/windows-child-options.test.ts b/apps/desktop/electron/windows-child-options.test.tsindex a68b9dfc5e7..14a6de355c4 100644--- a/apps/desktop/electron/windows-child-options.test.ts+++ b/apps/desktop/electron/windows-child-options.test.ts@@ -2,7 +2,8 @@ import assert from 'node:assert/strict'import { test } from 'vitest'-import { stopBackendChild, stopBackendTreesForUpdate } from './backend-child'+import { stopBackendChild } from './backend-child'+import { createLocalBackendLifecycle } from './local-backend-lifecycle'import { hiddenWindowsChildOptions } from './windows-child-options'test('hiddenWindowsChildOptions adds windowsHide:true on Windows when unset', () => {@@ -148,21 +149,33 @@ test('stopBackendChild swallows errors thrown by the kill strategy', () => {})})-test('Windows update tree-kills captured roots without pre-signalling the primary backend', () => {+test('Windows shutdown tree-kills before waiting, and joins an overlapping stop', async (): Promise<void> => {const primary = makeChild({ pid: 101 })- const pooled = makeChild({ pid: 202 })const events: string[] = []-- stopBackendTreesForUpdate(primary.child, {- forceKillProcessTree: pid => events.push(`tree:${pid}`),- stopAllPoolBackends: () => {- events.push('pool-stop')- // Production stopAllPoolBackends() already tree-kills every pool root.- events.push(`tree:${pooled.child.pid}`)- }+ let exit!: () => void++ const lifecycle = createLocalBackendLifecycle<typeof primary.child>({+ stopChild: (child: typeof primary.child): void =>+ stopBackendChild(child, {+ forceKillProcessTree: (pid: number): void => {+ events.push(`tree:${pid}`)+ },+ isWindows: true+ }),+ waitForExit: (): Promise<void> =>+ new Promise<void>((resolve: () => void): void => {+ events.push('wait')+ exit = resolve+ }),+ cancelSetup: (): void => {}})- assert.deepEqual(events, ['tree:101', 'pool-stop', 'tree:202'])- assert.deepEqual(primary.calls, [], 'the primary root must not be signalled before taskkill /T sees it')- assert.deepEqual(pooled.calls, [])+ const child = lifecycle.spawn((): typeof primary.child => primary.child)+ const stopped = lifecycle.stop(child)+ assert.equal(lifecycle.stop(child), stopped)+ const shutdown = lifecycle.shutdown()+ assert.deepEqual(events, ['tree:101', 'wait'])+ assert.deepEqual(primary.calls, [], 'taskkill must enumerate descendants before the root can exit')+ exit()+ await Promise.all([stopped, shutdown])})diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 0fc4e29bf41..78b67358393 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -25,6 +25,7 @@ from utils import ()from hermes_cli.archive_safe import normalize_archive_parts+from hermes_cli.backup_sqlite import _close_quietly, _safe_copy_dbfrom hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS, profile_root_entryfrom hermes_cli.sizefmt import format_bytes as _format_size@@ -139,10 +140,6 @@ class _SQLiteSnapshotError(RuntimeError):pass-class _SQLiteBackupTimeout(RuntimeError):- """Raised when a SQLite snapshot remains busy past its deadline."""--@contextmanagerdef _backup_operation_lock(hermes_home: Path, timeout_seconds: float = 0.25):"""Acquire one cross-process backup slot for full and quick snapshots."""@@ -286,12 +283,6 @@ def _iter_backup_files(hermes_root: Path, out_path: Path, skipped_dirs: Optional# --- SQLite safe copy ----def _close_quietly(conn: Optional[sqlite3.Connection]) -> None:- if conn is not None:- with suppress(Exception):- conn.close()--def _query_ro_sqlite(path: Path, fn):"""Run ``fn(conn)`` on a read-only connection to *path*; return ``(value, None)`` or ``(None, exc)``."""conn = None@@ -304,43 +295,6 @@ def _query_ro_sqlite(path: Path, fn):_close_quietly(conn)-def _safe_copy_db(src: Path, dst: Path, *, timeout_seconds: float = 10.0) -> bool:- """Copy a SQLite database with the backup() API (WAL-safe consistent snapshot).-- Fails closed when no consistent snapshot can be made: copying only the main file loses WAL data.- """- conn = backup_conn = None- try:- # timeout=0.0 disables sqlite3's implicit busy wait so the progress callback owns the- # full locked-source deadline instead of adding the default timeout before each callback.- conn = sqlite3.connect(f"file:{src}?mode=ro", uri=True, timeout=0.0)- backup_conn = sqlite3.connect(str(dst))- busy_deadline = time.monotonic() + max(0.0, timeout_seconds)-- def _check_backup_progress(status: int, _remaining: int, _total: int) -> None:- nonlocal busy_deadline- now = time.monotonic()- if status in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED):- if now >= busy_deadline:- raise _SQLiteBackupTimeout(f"database remained locked for {timeout_seconds:g} seconds")- else:- busy_deadline = now + max(0.0, timeout_seconds)-- conn.backup(backup_conn, pages=256, progress=_check_backup_progress, sleep=0.1)- return True- except Exception as exc:- logger.warning("SQLite safe copy failed for %s: %s", src, exc)- # Windows won't remove the partial destination while SQLite still has it open.- _close_quietly(backup_conn)- backup_conn = None- with suppress(OSError):- dst.unlink(missing_ok=True)- return False- finally:- _close_quietly(backup_conn)- _close_quietly(conn)--def is_zeroed_sqlite_file(path: Path, *, probe_bytes: int = 100, force: bool = False) -> bool:"""True when *path* looks like the #68474 zeroed-state.db signature.@@ -694,28 +648,8 @@ def _run_backup_locked(args, hermes_root: Path) -> None:) as zf:for i, (abs_path, rel_path) in enumerate(files_to_add, 1):try:- # Safe copy for SQLite databases (handles WAL mode)- if abs_path.suffix == ".db":- # Stage the snapshot alongside the output zip so that the- # temp file lives on the same filesystem. The system- # default (/tmp) may be a small tmpfs that cannot hold- # large databases, causing silent backup incompleteness.- with tempfile.NamedTemporaryFile(- suffix=".db", delete=False, dir=str(out_path.parent)- ) as tmp:- tmp_db = Path(tmp.name)- if _safe_copy_db(abs_path, tmp_db):- zf.write(tmp_db, arcname=str(rel_path))- total_bytes += tmp_db.stat().st_size- tmp_db.unlink(missing_ok=True)- else:- tmp_db.unlink(missing_ok=True)- errors.append(f" {rel_path}: SQLite safe copy failed")- continue- else:- zf.write(abs_path, arcname=str(rel_path))- total_bytes += abs_path.stat().st_size- except (PermissionError, OSError, ValueError) as exc:+ total_bytes += _write_backup_file(zf, abs_path, str(rel_path), out_path.parent)+ except (OSError, ValueError, _SQLiteSnapshotError) as exc:errors.append(f" {rel_path}: {exc}")continue@@ -1113,50 +1047,6 @@ def run_import(args) -> None:# Quick state snapshots (used by /snapshot slash command and hermes backup --quick)# ----------------------------------------------------------------------------# Critical state files to include in quick snapshots (relative to HERMES_HOME).-# Everything else is either regeneratable (logs, cache) or managed separately-# (skills, repo, sessions/).-#-# Entries may be individual files OR directories. Directories are captured-# recursively; missing entries are silently skipped. Pairing data lives in-# platform-specific JSON blobs outside state.db, so it's listed here explicitly-# — `hermes update` snapshots this set before pulling so approved-user lists-# are recoverable if anything goes wrong (issue #15733).-_QUICK_STATE_FILES = (- "state.db",- "config.yaml",- ".env",- "auth.json",- "cron/jobs.json",- "cron/executions.db",- "gateway_state.json",- "channel_directory.json",- "channel_aliases.json",- "processes.json",- "gateway/discord_message_recovery.db", # Discord reconnect replay ledger- # Per-profile user-created stores that live outside the git checkout and- # are therefore destroyed if the update flow removes/replaces the file and- # the post-update schema-init re-creates an empty one (issue #52889). All- # are at $HERMES_HOME/<name> for the default/root profile; on non-root- # profiles the real path is outside HERMES_HOME and the entry is silently- # skipped (best-effort, same as the pairing stores). SQLite DBs are copied- # WAL-safely via _safe_copy_db.- "projects.db", # per-profile project store- "response_store.db", # gateway conversation history / tool payloads- "memory_store.db", # holographic memory facts/entities- "verification_evidence.db", # agent verification audit trail- "kanban.db", # default board (back-compat <root>/kanban.db)- "kanban/boards", # non-default boards: each <slug>/kanban.db + board metadata (workspaces/ + attachments/ are skipped as regenerable)- # Pairing stores (generic + per-platform JSONs outside state.db)- "pairing", # legacy location (gateway/pairing.py)- "platforms/pairing", # new location (gateway/pairing.py)- "feishu_comment_pairing.json", # Feishu comment subscription pairings-)--# ``_QUICK_SNAPSHOTS_DIR`` lives with the exclusion rules at the top of the module.-_QUICK_DEFAULT_KEEP = 20--def create_quick_snapshot(label: Optional[str] = None,hermes_home: Optional[Path] = None,@@ -1507,11 +1397,6 @@ def restore_quick_snapshot(return restored > 0-# Relative path of the cron job database inside HERMES_HOME. Kept in sync with-# the entry in ``_QUICK_STATE_FILES`` and with ``cron/jobs.py``'s ``JOBS_FILE``.-_CRON_JOBS_REL = "cron/jobs.json"--def _count_cron_jobs(path: Path) -> Optional[int]:"""Return the number of cron jobs stored in ``path``.@@ -1934,6 +1819,22 @@ def run_quick_backup(args) -> None:# Shared full-zip backup helper# ---------------------------------------------------------------------------+def _write_backup_file(zf: zipfile.ZipFile, source: Path, arcname: str, staging_dir: Path) -> int:+ """Serialize one file, staging SQLite beside the ZIP rather than in small tmpfs."""+ if source.suffix != ".db":+ zf.write(source, arcname=arcname)+ return source.stat().st_size+ with tempfile.NamedTemporaryFile(suffix=".db", delete=False, dir=str(staging_dir)) as tmp:+ snapshot = Path(tmp.name)+ try:+ if not _safe_copy_db(source, snapshot):+ raise _SQLiteSnapshotError("SQLite safe copy failed")+ zf.write(snapshot, arcname=arcname)+ return snapshot.stat().st_size+ finally:+ snapshot.unlink(missing_ok=True)++def _write_full_zip_backup(out_path: Path, hermes_root: Path) -> Optional[Path]:"""Single-flight wrapper for automatic full zip backups."""try:@@ -1975,27 +1876,7 @@ def _write_full_zip_backup_locked(out_path: Path, hermes_root: Path) -> Optional) as zf:for index, (abs_path, rel_path) in enumerate(files_to_add, 1):try:- if abs_path.suffix == ".db":- # Stage the snapshot alongside the output zip so that the- # temp file lives on the same filesystem. The system- # default (/tmp) may be a small tmpfs that cannot hold- # large databases, causing silent backup incompleteness.- with tempfile.NamedTemporaryFile(- suffix=".db", delete=False, dir=str(out_path.parent)- ) as tmp:- tmp_db = Path(tmp.name)- try:- if not _safe_copy_db(abs_path, tmp_db):- logger.warning(- "Full-zip backup aborted: SQLite snapshot failed for %s",- rel_path,- )- raise _SQLiteSnapshotError(str(rel_path))- zf.write(tmp_db, arcname=str(rel_path))- finally:- tmp_db.unlink(missing_ok=True)- else:- zf.write(abs_path, arcname=str(rel_path))+ _write_backup_file(zf, abs_path, str(rel_path), out_path.parent)except (PermissionError, OSError, ValueError) as exc:logger.debug("Skipping %s in zip backup: %s", rel_path, exc)continuediff --git a/hermes_cli/backup_sqlite.py b/hermes_cli/backup_sqlite.pynew file mode 100644index 00000000000..7fa12543228--- /dev/null+++ b/hermes_cli/backup_sqlite.py@@ -0,0 +1,102 @@+"""WAL-safe SQLite snapshots. Direct execution needs only the standard library.++Desktop invokes this file before stopping its backend, even when application+imports cannot load. Full and quick backups use the same SQLite copy operation.+"""+import json+import logging+import os+import sqlite3+import sys+import tempfile+import time+from contextlib import suppress+from datetime import datetime, timezone+from pathlib import Path+from typing import Optional++logger = logging.getLogger(__name__)+++class _SQLiteBackupTimeout(RuntimeError):+ """Raised when a SQLite snapshot remains busy past its deadline."""+++def _close_quietly(conn: Optional[sqlite3.Connection]) -> None:+ if conn is not None:+ with suppress(Exception):+ conn.close()+++def _safe_copy_db(src: Path, dst: Path, *, timeout_seconds: float = 10.0) -> bool:+ """Copy a SQLite database with the backup() API (WAL-safe consistent snapshot).++ Fails closed when no consistent snapshot can be made: copying only the main file loses WAL data.+ """+ conn = backup_conn = None+ try:+ # timeout=0.0 disables sqlite3's implicit busy wait so the progress callback owns the+ # full locked-source deadline instead of adding the default timeout before each callback.+ conn = sqlite3.connect(f"{src.resolve().as_uri()}?mode=ro", uri=True, timeout=0.0)+ backup_conn = sqlite3.connect(str(dst))+ busy_deadline = time.monotonic() + max(0.0, timeout_seconds)++ def _check_backup_progress(status: int, _remaining: int, _total: int) -> None:+ nonlocal busy_deadline+ now = time.monotonic()+ if status in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED):+ if now >= busy_deadline:+ raise _SQLiteBackupTimeout(f"database remained locked for {timeout_seconds:g} seconds")+ else:+ busy_deadline = now + max(0.0, timeout_seconds)++ conn.backup(backup_conn, pages=256, progress=_check_backup_progress, sleep=0.1)+ return True+ except Exception as exc:+ logger.warning("SQLite safe copy failed for %s: %s", src, exc)+ # Windows won't remove the partial destination while SQLite still has it open.+ _close_quietly(backup_conn)+ backup_conn = None+ with suppress(OSError):+ dst.unlink(missing_ok=True)+ return False+ finally:+ _close_quietly(backup_conn)+ _close_quietly(conn)+++def preflight_state_db(home: Path) -> dict:+ """Publish an emergency snapshot; do not prune recovery files on failure."""+ source = home / "state.db"+ if not source.exists():+ return {"path": None, "message": "state.db not found (fresh install?)"}+ prefix = "state.db.pre-update-emergency-"+ stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H-%M-%S-%fZ")+ destination = home / f"{prefix}{stamp}-{os.getpid()}.bak"+ fd, name = tempfile.mkstemp(prefix=prefix, suffix=".partial", dir=home)+ os.close(fd)+ staged = Path(name)+ try:+ if not _safe_copy_db(source, staged):+ raise RuntimeError("SQLite safe copy failed; previous emergency snapshots were retained")+ connection = sqlite3.connect(str(staged))+ try:+ result = connection.execute("PRAGMA quick_check").fetchall()+ if result != [("ok",)]:+ raise RuntimeError(f"SQLite snapshot integrity check failed: {result}")+ finally:+ connection.close()+ size = staged.stat().st_size+ os.replace(staged, destination)+ finally:+ staged.unlink(missing_ok=True)+ for old in sorted(home.glob(f"{prefix}*.bak"), reverse=True)[2:]:+ try:+ old.unlink()+ except OSError as exc:+ logger.warning("Could not prune emergency snapshot %s: %s", old, exc)+ return {"path": str(destination), "bytes": size}+++if __name__ == "__main__":+ print(json.dumps(preflight_state_db(Path(sys.argv[1]))))diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.pyindex fbd08a69773..b0751340b48 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -1152,7 +1152,7 @@ class TestProfileRestoration:class TestSafeCopyDb:def test_copies_valid_database(self, tmp_path):- from hermes_cli.backup import _safe_copy_db+ from hermes_cli.backup_sqlite import _safe_copy_dbsrc = tmp_path / "test.db"dst = tmp_path / "copy.db"@@ -1175,7 +1175,7 @@ class TestSafeCopyDb:):from types import SimpleNamespace- from hermes_cli import backup as backup_mod+ from hermes_cli import backup_sqlite as backup_modsrc = tmp_path / "locked.db"dst = tmp_path / "copy.db"@@ -1228,7 +1228,7 @@ class TestSafeCopyDb:import sysimport time- from hermes_cli.backup import _safe_copy_db+ from hermes_cli.backup_sqlite import _safe_copy_dbsrc = tmp_path / "locked.db"dst = tmp_path / "copy.db"diff --git a/tests/hermes_cli/test_backup_preflight.py b/tests/hermes_cli/test_backup_preflight.pynew file mode 100644index 00000000000..e23e6ea9979--- /dev/null+++ b/tests/hermes_cli/test_backup_preflight.py@@ -0,0 +1,55 @@+"""Preflight must work while the app is broken and its database is still live."""+import json+import sqlite3+import subprocess+import sys+from pathlib import Path+++def test_preflight_captures_committed_wal_without_application_imports(tmp_path):+ home = tmp_path / "home"+ home.mkdir()+ db = home / "state.db"+ script = Path(__file__).resolve().parents[2] / "hermes_cli" / "backup_sqlite.py"+ runner = """+import runpy, sys+class NoApplicationImports:+ def find_spec(self, fullname, path=None, target=None):+ if fullname.startswith(('hermes', 'utils', 'yaml')):+ raise ImportError('application imports are broken')+sys.meta_path.insert(0, NoApplicationImports())+sys.argv = [sys.argv[1], sys.argv[2]]+runpy.run_path(sys.argv[0], run_name='__main__')+"""+ with sqlite3.connect(db) as writer:+ writer.execute("PRAGMA journal_mode=WAL")+ writer.execute("PRAGMA wal_autocheckpoint=0")+ writer.execute("CREATE TABLE messages (body TEXT)")+ writer.commit()+ writer.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ writer.execute("INSERT INTO messages VALUES ('committed only in WAL')")+ writer.commit()+ assert Path(str(db) + "-wal").stat().st_size > 0+ # The control proves a main-file copy loses committed rows.+ control = tmp_path / "raw.db"+ control.write_bytes(db.read_bytes())+ with sqlite3.connect(control) as raw:+ assert raw.execute("SELECT * FROM messages").fetchall() == []+ for _ in range(3):+ result = subprocess.run(+ [sys.executable, "-I", "-S", "-c", runner, str(script), str(home)],+ capture_output=True, text=True, timeout=20,+ )+ assert result.returncode == 0, result.stderr+ backup = Path(json.loads(result.stdout)["path"])+ with sqlite3.connect(backup) as snapshot:+ assert snapshot.execute("SELECT * FROM messages").fetchall() == [("committed only in WAL",)]+ assert snapshot.execute("PRAGMA integrity_check").fetchone() == ("ok",)+ assert len(list(home.glob("state.db.pre-update-emergency-*.bak"))) == 2+ writer.close()+ previous = sorted(home.glob("state.db.pre-update-emergency-*.bak"))+ db.write_bytes(b"broken database")+ result = subprocess.run([sys.executable, "-I", "-S", str(script), str(home)], capture_output=True, text=True, timeout=20)+ assert result.returncode != 0+ assert sorted(home.glob("state.db.pre-update-emergency-*.bak")) == previous+ assert not list(home.glob("*.partial"))diff --git a/tests/hermes_cli/test_backup_zip_serialization.py b/tests/hermes_cli/test_backup_zip_serialization.pynew file mode 100644index 00000000000..9c945c1148e--- /dev/null+++ b/tests/hermes_cli/test_backup_zip_serialization.py@@ -0,0 +1,50 @@+"""The manual and automatic archive paths use the same WAL-safe serialization."""+import sqlite3+import zipfile+from argparse import Namespace+from contextlib import closing+from pathlib import Path++import pytest++from hermes_cli import backup++[email protected]("automatic", [False, True])+def test_zip_captures_live_wal_and_cleans_failed_staging(tmp_path, monkeypatch, automatic):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ output = tmp_path / "archive"+ output.mkdir()+ archive = output / "backup.zip"++ def run():+ if automatic:+ return backup._write_full_zip_backup(archive, home)+ return backup.run_backup(Namespace(output=str(archive)))++ with closing(sqlite3.connect(home / "state.db")) as writer:+ writer.execute("PRAGMA journal_mode=WAL")+ writer.execute("PRAGMA wal_autocheckpoint=0")+ writer.execute("CREATE TABLE messages (body TEXT)")+ writer.commit()+ writer.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ writer.execute("INSERT INTO messages VALUES ('WAL-only row')")+ writer.commit()+ run()+ with zipfile.ZipFile(archive) as zipped:+ assert not any(name.endswith(('-wal', '-shm')) for name in zipped.namelist())+ member = next(name for name in zipped.namelist() if name.endswith('state.db'))+ restored = tmp_path / "restored.db"+ restored.write_bytes(zipped.read(member))+ with closing(sqlite3.connect(restored)) as snapshot:+ assert snapshot.execute("SELECT body FROM messages").fetchall() == [("WAL-only row",)]++ def refuse_write(self, filename, arcname=None, **kwargs):+ raise OSError("archive device full")++ monkeypatch.setattr(zipfile.ZipFile, "write", refuse_write)+ run()+ assert sorted(output.iterdir()) == [archive], "a failed write must not leak a private database snapshot"