The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): take the single-instance lock before launch recovery persists, drop the queued writer
Teknium2e2618faef27
diff --git a/apps/desktop/electron/fixtures/nvidia-recovery.ts b/apps/desktop/electron/fixtures/nvidia-recovery.tsindex 9b150c38fca..67940936ecc 100644--- a/apps/desktop/electron/fixtures/nvidia-recovery.ts+++ b/apps/desktop/electron/fixtures/nvidia-recovery.ts@@ -6,7 +6,6 @@ import { app } from 'electron'import { INSTALL_STAMP } from '../install-stamp'import { launchBuildIdentity } from '../launch-build-identity'-import { createLaunchMarkerWriter } from '../launch-marker-writer'import { readNvidiaEglMarker } from '../linux-nvidia-egl-fallback'import { createNvidiaEglRecovery } from '../linux-nvidia-egl-recovery'@@ -22,7 +21,7 @@ const options: { userData: string; eventsFile: string; commandFile: string; quitapp.setPath('userData', options.userData)app.disableHardwareAcceleration()-const writer = createLaunchMarkerWriter()+const primary = app.requestSingleInstanceLock()const report = (event: string, data: Record<string, unknown> = {}) => {appendFileSync(options.eventsFile, `${JSON.stringify({ event, ...data })}\n`, 'utf8')@@ -36,14 +35,11 @@ const recovery = createNvidiaEglRecovery({driverMajor: 600,driverVersion: '600.1.2',env: {},- queueMarker: write => writer.queue(write),+ primary,relaunch: () => report('relaunch'),log: message => report('log', { message })})-const primary = app.requestSingleInstanceLock()-writer.flush(primary)-if (!primary) {report('secondary', { marker: readNvidiaEglMarker(options.userData) })app.exit(0)diff --git a/apps/desktop/electron/launch-marker-writer.test.ts b/apps/desktop/electron/launch-marker-writer.test.tsdeleted file mode 100644index 322f0af973a..00000000000--- a/apps/desktop/electron/launch-marker-writer.test.ts+++ /dev/null@@ -1,53 +0,0 @@-import assert from 'node:assert/strict'--import { test } from 'vitest'--import { createLaunchMarkerWriter } from './launch-marker-writer'--test('a primary instance persists every queued marker write', () => {- const writer = createLaunchMarkerWriter()- const written: string[] = []-- writer.queue(() => written.push('linux-gpu'))- writer.queue(() => written.push('sandbox'))-- assert.equal(writer.flush(true), 2)- assert.deepEqual(written, ['linux-gpu', 'sandbox'])-})--test('a second launch that loses the lock writes no marker at all', () => {- const writer = createLaunchMarkerWriter()- const written: string[] = []-- writer.queue(() => written.push('booting'))- writer.queue(() => written.push('booting'))-- // #131055: the launch exits at the lock without ever starting a GPU or- // sandbox child. Its `booting` write is what the next launch would read as- // an aborted boot, so nothing may be persisted — and the running instance's- // markers must be left exactly as they are.- assert.equal(writer.flush(false), 0)- assert.deepEqual(written, [])-})--test('a marker write that throws does not strand the ones behind it', () => {- const writer = createLaunchMarkerWriter()- const written: string[] = []-- writer.queue(() => {- throw new Error('EACCES')- })- writer.queue(() => written.push('sandbox'))-- assert.equal(writer.flush(true), 1)- assert.deepEqual(written, ['sandbox'])-})--test('a dropped launch cannot flush twice', () => {- const writer = createLaunchMarkerWriter()-- writer.queue(() => undefined)-- assert.equal(writer.flush(false), 0)- assert.equal(writer.flush(false), 0)-})diff --git a/apps/desktop/electron/launch-marker-writer.ts b/apps/desktop/electron/launch-marker-writer.tsdeleted file mode 100644index b296028454e..00000000000--- a/apps/desktop/electron/launch-marker-writer.ts+++ /dev/null@@ -1,30 +0,0 @@-/** Lock-owned recovery writes, adapted from kokhlo's #131067. */-export function createLaunchMarkerWriter() {- const queued: Array<() => void> = []-- return {- queue(write: () => void): void {- queued.push(write)- },- flush(isPrimaryInstance: boolean): number {- const writes = queued.splice(0)-- if (!isPrimaryInstance) {- return 0- }-- let written = 0-- for (const write of writes) {- try {- write()- written++- } catch (error) {- console.warn('[hermes] could not persist a recovery marker:', error)- }- }-- return written- }- }-}diff --git a/apps/desktop/electron/linux-nvidia-egl-recovery.test.ts b/apps/desktop/electron/linux-nvidia-egl-recovery.test.tsindex 35e015fb0f8..4178588df06 100644--- a/apps/desktop/electron/linux-nvidia-egl-recovery.test.ts+++ b/apps/desktop/electron/linux-nvidia-egl-recovery.test.ts@@ -5,7 +5,6 @@ import path from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { launchBuildIdentity } from './launch-build-identity'-import { createLaunchMarkerWriter } from './launch-marker-writer'import { linuxGpuChildDeathPath } from './linux-gpu-fallback'import { nvidiaEglMarkerPath, readNvidiaEglMarker, writeNvidiaEglMarker } from './linux-nvidia-egl-fallback'import { createNvidiaEglRecovery, NVIDIA_GPU_DEATH_WITNESS_GRACE_MS } from './linux-nvidia-egl-recovery'@@ -20,7 +19,6 @@ const build = (commit = 'a'.repeat(40)) =>})function launch(overrides: Partial<Parameters<typeof createNvidiaEglRecovery>[0]> = {}, primary = true) {- const writer = createLaunchMarkerWriter()const relaunch = vi.fn()const log = vi.fn()@@ -32,14 +30,12 @@ function launch(overrides: Partial<Parameters<typeof createNvidiaEglRecovery>[0]buildIdentity: build(),platform: 'linux',env: {},- queueMarker: write => writer.queue(write),+ primary,relaunch,log,...overrides})- writer.flush(primary)-return { ...recovery, relaunch, log }}diff --git a/apps/desktop/electron/linux-nvidia-egl-recovery.ts b/apps/desktop/electron/linux-nvidia-egl-recovery.tsindex a98ff378e4e..b609dc073e3 100644--- a/apps/desktop/electron/linux-nvidia-egl-recovery.ts+++ b/apps/desktop/electron/linux-nvidia-egl-recovery.ts@@ -13,7 +13,8 @@ import {interface NvidiaEglRecoveryOptions extends Omit<NvidiaEglFallbackOptions, 'marker'> {userData: string- queueMarker: (write: () => void) => void+ /** This process owns the single-instance lock; a secondary launch never persists. */+ primary: boolean/** Extra argv for the relaunch; non-empty only when the witness could not be persisted. */relaunch: (extraArgs: readonly string[]) => voidargv?: readonly string[]@@ -37,7 +38,7 @@ export function createNvidiaEglRecovery(options: NvidiaEglRecoveryOptions) {const previous = readNvidiaEglMarker(options.userData)const decision = decideNvidiaEglFallback({ ...options, marker: previous })const supported = (options.platform ?? process.platform) === 'linux' && options.driverMajor !== null- let primary = false+ const primary = supported && options.primarylet quitting = falselet relaunchAttempted = falselet healthyAt: number | null = null@@ -59,11 +60,9 @@ export function createNvidiaEglRecovery(options: NvidiaEglRecoveryOptions) {}}- if (supported) {- options.queueMarker(() => {- primary = true- persist(decision.nextMarker)- })+ // Before GPU children start: a `booting` record left by an abort is itself the witness.+ if (primary) {+ persist(decision.nextMarker)}return {diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex cd3fbc96d75..ccde52f2924 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -323,7 +323,6 @@ import { INSTALL_STAMP, installShape } from './install-stamp'import type { InstallStamp } from './install-stamp'import { createKeepAwakeController } from './keep-awake-controller'import { launchBuildIdentity } from './launch-build-identity'-import { createLaunchMarkerWriter } from './launch-marker-writer'import { applyLaunchProfileOverride } from './launch-profile'import { fetchLinkTitle, resolveFaviconCached } from './link-metadata'import { CHROMIUM_LOG_FILENAME, enableLinuxCrashDiagnostics, linuxCrashDiagnostics } from './linux-crash-diagnostics'@@ -722,6 +721,43 @@ if (USER_DATA_OVERRIDE || process.env.HERMES_DATA_DIR_SUFFIX) {app.setPath('userData', resolvedUserData)}+// Only the lock owner may persist launch recovery markers, adopt a workspace or start a+// backend, so the lock is taken as soon as userData is final (#131055, #143056).+// #78101: on Linux/X11 a zombie/defunct Electron process leaves the+// SingletonLock symlink behind with a PID that still answers kill(pid, 0),+// so Chromium's own liveness probe keeps refusing every later launch and the+// app silently exits. Clear a provably-dead owner and retry once; always log+// when the lock is legitimately lost so the exit is diagnosable.+function acquireSingleInstanceLock(): boolean {+ if (app.requestSingleInstanceLock()) {+ return true+ }++ const stalePid = removeStaleSingletonLock(app.getPath('userData'))++ if (stalePid !== null) {+ console.error(`[hermes] removed stale SingletonLock (owner ${stalePid} dead); retrying launch`)++ return app.requestSingleInstanceLock()+ }++ return false+}++const isPrimaryInstance: boolean = acquireSingleInstanceLock()++if (!isPrimaryInstance) {+ console.error('[hermes] another Hermes Desktop instance holds the single-instance lock; exiting')+ app.exit(0)+}++// `hermes desktop` shortens TMPDIR only so the lock above can bind its socket (#124688). The+// backend and every other child get the real one (the profile scratch dir) back.+if (process.env.HERMES_DESKTOP_TMPDIR) {+ process.env.TMPDIR = process.env.HERMES_DESKTOP_TMPDIR+ delete process.env.HERMES_DESKTOP_TMPDIR+}+const DEV_SERVER = process.env.HERMES_DESKTOP_DEV_SERVERconst IS_PACKAGED = app.isPackaged || Boolean(process.env.HERMES_DESKTOP_IS_PACKAGED)const IS_MAC = process.platform === 'darwin'@@ -782,8 +818,6 @@ if (REMOTE_DISPLAY_REASON) {// (that path stays owned by STATUS_BREAKPOINT / #38216). Must run before app// `ready`. Skip applying switches when the remote-display block above already// did; still honor a sticky per-version marker so Start Menu launches recover.-const launchMarkerWriter = createLaunchMarkerWriter()-let windowsGpuStackCookieFallbackActive = falselet windowsGpuStackCookieFallbackSticky = falselet windowsGpuStackCookieRelaunchAttempted = false@@ -801,7 +835,13 @@ if (IS_WINDOWS) {windowsGpuStackCookieFallbackActive = gpuStackCookieDecision.enablewindowsGpuStackCookieFallbackSticky = gpuStackCookieDecision.nextMarker.state === 'fallback'- launchMarkerWriter.queue(() => writeGpuStackCookieMarker(windowsGpuUserData, gpuStackCookieDecision.nextMarker))+ if (isPrimaryInstance) {+ try {+ writeGpuStackCookieMarker(windowsGpuUserData, gpuStackCookieDecision.nextMarker)+ } catch {+ void 0+ }+ }if (gpuStackCookieDecision.enable && !REMOTE_DISPLAY_REASON) {app.disableHardwareAcceleration()@@ -875,7 +915,7 @@ const nvidiaEglRecovery = createNvidiaEglRecovery({platform: process.platform,isWsl: IS_WSL,remoteDisplayReason: REMOTE_DISPLAY_REASON,- queueMarker: write => launchMarkerWriter.queue(write),+ primary: isPrimaryInstance,log: message => {console.warn(`[hermes] ${message}`)void app.whenReady().then(() => {@@ -926,7 +966,13 @@ if (process.platform === 'linux') {linuxGpuFallbackActive = linuxGpuDecision.enablelinuxGpuFallbackSticky = linuxGpuDecision.nextMarker.state === 'fallback'- launchMarkerWriter.queue(() => writeLinuxGpuMarker(linuxGpuUserData, linuxGpuDecision.nextMarker))+ if (isPrimaryInstance) {+ try {+ writeLinuxGpuMarker(linuxGpuUserData, linuxGpuDecision.nextMarker)+ } catch {+ void 0+ }+ }if (linuxGpuDecision.enable && linuxGpuDecision.reason !== 'already-enabled' && !LINUX_GPU_SOFTWARE_ACTIVE) {app.disableHardwareAcceleration()@@ -1024,7 +1070,9 @@ if (IS_WINDOWS || process.platform === 'linux') {)}- launchMarkerWriter.queue(() => writeSandboxMarker(windowsUserData, sandboxDecision.nextMarker))+ if (isPrimaryInstance) {+ writeSandboxMarker(windowsUserData, sandboxDecision.nextMarker)+ }// One coalesced Linux GPU-child recovery (#86073, #124843, #121954): the// sandbox signature is tried first (that host's matrix shows --disable-gpu@@ -1185,45 +1233,6 @@ if (INSTALL_STAMP) {const DESKTOP_PROFILE_CONFIG_PATH: string = path.join(app.getPath('userData'), 'active-profile.json')-// Only the lock-owning destination may adopt a workspace or start a backend.-// #78101: on Linux/X11 a zombie/defunct Electron process leaves the-// SingletonLock symlink behind with a PID that still answers kill(pid, 0),-// so Chromium's own liveness probe keeps refusing every later launch and the-// app silently exits. Clear a provably-dead owner and retry once; always log-// when the lock is legitimately lost so the exit is diagnosable.-function acquireSingleInstanceLock(): boolean {- if (app.requestSingleInstanceLock()) {- return true- }-- const stalePid = removeStaleSingletonLock(app.getPath('userData'))-- if (stalePid !== null) {- console.error(`[hermes] removed stale SingletonLock (owner ${stalePid} dead); retrying launch`)-- return app.requestSingleInstanceLock()- }-- return false-}--const isPrimaryInstance: boolean = acquireSingleInstanceLock()--if (!isPrimaryInstance) {- console.error('[hermes] another Hermes Desktop instance holds the single-instance lock; exiting')- launchMarkerWriter.flush(false)- app.exit(0)-} else {- launchMarkerWriter.flush(true)-}--// `hermes desktop` shortens TMPDIR only so the lock above can bind its socket (#124688). The-// backend and every other child get the real one (the profile scratch dir) back.-if (process.env.HERMES_DESKTOP_TMPDIR) {- process.env.TMPDIR = process.env.HERMES_DESKTOP_TMPDIR- delete process.env.HERMES_DESKTOP_TMPDIR-}-const HERMES_HOME: string = resolveDesktopHermesHome({home: app.getPath('home'),directoryExists,