The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): scope NVIDIA recovery to the owning launch and build
Gillebcd4980826db
diff --git a/apps/desktop/electron/fixtures/nvidia-recovery.ts b/apps/desktop/electron/fixtures/nvidia-recovery.tsnew file mode 100644index 00000000000..9b150c38fca--- /dev/null+++ b/apps/desktop/electron/fixtures/nvidia-recovery.ts@@ -0,0 +1,71 @@+import { appendFileSync, existsSync, readFileSync } from 'node:fs'++// No windows, gateway, credentials, or real Hermes home. This fixture exercises+// native Electron locking with the production Linux recovery policy and test driver facts.+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'++const argument = process.argv.find(arg => arg.startsWith('--recovery-fixture='))++if (!argument) {+ throw new Error('Missing isolated fixture options')+}++const options: { userData: string; eventsFile: string; commandFile: string; quitBeforeReveal?: boolean } = JSON.parse(+ argument.slice('--recovery-fixture='.length)+)++app.setPath('userData', options.userData)+app.disableHardwareAcceleration()+const writer = createLaunchMarkerWriter()++const report = (event: string, data: Record<string, unknown> = {}) => {+ appendFileSync(options.eventsFile, `${JSON.stringify({ event, ...data })}\n`, 'utf8')+}++const recovery = createNvidiaEglRecovery({+ userData: options.userData,+ appVersion: app.getVersion(),+ buildIdentity: launchBuildIdentity({ appVersion: app.getVersion(), installStamp: INSTALL_STAMP }),+ platform: 'linux',+ driverMajor: 600,+ driverVersion: '600.1.2',+ env: {},+ queueMarker: write => writer.queue(write),+ 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)+} else {+ app.on('before-quit', () => recovery.cleanExit())+ void app.whenReady().then(() => {+ if (options.quitBeforeReveal) {+ recovery.cleanExit()+ report('early-exit', { marker: readNvidiaEglMarker(options.userData) })+ app.exit(0)++ return+ }++ recovery.healthy()+ report('ready', { software: recovery.decision.enable, marker: readNvidiaEglMarker(options.userData) })++ const control = setInterval(() => {+ if (existsSync(options.commandFile) && readFileSync(options.commandFile, 'utf8') === 'quit') {+ clearInterval(control)+ app.quit()+ }+ }, 50)+ })+}diff --git a/apps/desktop/electron/launch-build-identity.test.ts b/apps/desktop/electron/launch-build-identity.test.tsnew file mode 100644index 00000000000..ec7e5872cc5--- /dev/null+++ b/apps/desktop/electron/launch-build-identity.test.ts@@ -0,0 +1,110 @@+import assert from 'node:assert/strict'++import { test } from 'vitest'++import { launchBuildIdentity, launchMarkerNeedsReprobe } from './launch-build-identity'++const stamp = (+ overrides: Record<string, unknown> = {}+): { commit: string | null; builtAt: string | null; dirty: boolean } => ({+ commit: '357f51c491063f8a1b2c3d4e5f60718293a4b5c6',+ builtAt: '2026-09-28T10:11:12Z',+ dirty: false,+ ...overrides+})++test('launchBuildIdentity retains version labels and qualifies stamped artifacts', () => {+ assert.equal(launchBuildIdentity({ appVersion: '0.21.5' }), '0.21.5')+ assert.equal(+ launchBuildIdentity({ appVersion: '0.21.5', installStamp: stamp() }),+ '0.21.5+g357f51c49106@2026-09-28T10:11:12Z'+ )+ assert.equal(launchBuildIdentity({ appVersion: '1.2.3', installStamp: null }), '1.2.3')+})++test('launchBuildIdentity falls back to the install stamp on a source install', () => {+ // A source/`hermes update` install reports 0.0.0 on every build, so the+ // stamp's commit is the only thing that differs between two of them.+ assert.equal(+ launchBuildIdentity({ appVersion: '0.0.0', installStamp: stamp() }),+ '0.0.0+g357f51c49106@2026-09-28T10:11:12Z'+ )++ assert.equal(+ launchBuildIdentity({ appVersion: '0.0.0', installStamp: stamp({ dirty: true }) }),+ '0.0.0+g357f51c49106-dirty@2026-09-28T10:11:12Z'+ )++ // No stamp at all: a dev run, nothing better to compare on.+ assert.equal(launchBuildIdentity({ appVersion: '0.0.0', installStamp: null }), '0.0.0')++ // A commit without a build time still identifies the build.+ assert.equal(+ launchBuildIdentity({ appVersion: '0.0.0', installStamp: stamp({ builtAt: null }) }),+ '0.0.0+g357f51c49106'+ )+})++test('launchBuildIdentity moves between two source builds of the same version', () => {+ const before = launchBuildIdentity({ appVersion: '0.0.0', installStamp: stamp() })++ const after = launchBuildIdentity({+ appVersion: '0.0.0',+ installStamp: stamp({ commit: 'aabbccddeeff00112233445566778899aabbccdd' })+ })++ assert.notEqual(before, after)+})++test('a version change re-probes, as it always has', () => {+ assert.equal(launchMarkerNeedsReprobe({ version: '0.21.5' }, { appVersion: '0.22.0', buildIdentity: '0.22.0' }), true)++ assert.equal(+ launchMarkerNeedsReprobe({ version: '0.21.5' }, { appVersion: '0.21.5', buildIdentity: '0.21.5' }),+ false+ )+})++test('a build change re-probes on a source install whose version never moves', () => {+ const promoted = { version: '0.0.0', build: '0.0.0+gaaaaaaaaaaaa@2026-09-20T00:00:00Z' }++ assert.equal(+ launchMarkerNeedsReprobe(promoted, {+ appVersion: '0.0.0',+ buildIdentity: '0.0.0+gaaaaaaaaaaaa@2026-09-20T00:00:00Z'+ }),+ false+ )++ // The next source build is a different build identity at the same 0.0.0 —+ // this is the case the version check alone could never clear.+ assert.equal(+ launchMarkerNeedsReprobe(promoted, {+ appVersion: '0.0.0',+ buildIdentity: '0.0.0+gbbbbbbbbbbbb@2026-10-02T00:00:00Z'+ }),+ true+ )+})++test('a promoted marker with no build identity is re-probed once on a source install', () => {+ // Marker written by an older build, which recorded only the 0.0.0 version.+ // Nothing can distinguish it from the current build, so it gets exactly one+ // re-probe rather than staying degraded forever.+ assert.equal(+ launchMarkerNeedsReprobe({ version: '0.0.0' }, { appVersion: '0.0.0', buildIdentity: '0.0.0+gnew' }),+ true+ )++ // A real release version keeps the old contract: same version stays sticky.+ assert.equal(launchMarkerNeedsReprobe({ version: '0.21.5' }, { appVersion: '0.21.5' }), false)+})++test('launchMarkerNeedsReprobe is inert without a marker or a version', () => {+ assert.equal(launchMarkerNeedsReprobe(null, { appVersion: '0.0.0' }), false)+ assert.equal(launchMarkerNeedsReprobe({ version: '0.21.5' }, { appVersion: '' }), false)+})++test('an unstamped development launch does not re-probe a legacy fallback forever', () => {+ assert.equal(launchMarkerNeedsReprobe({ version: '0.0.0' }, { appVersion: '0.0.0', buildIdentity: '0.0.0' }), false)+})diff --git a/apps/desktop/electron/launch-build-identity.ts b/apps/desktop/electron/launch-build-identity.tsnew file mode 100644index 00000000000..8d5bb6dbbf9--- /dev/null+++ b/apps/desktop/electron/launch-build-identity.ts@@ -0,0 +1,38 @@+/** Artifact identity for recovery witnesses, adapted from kokhlo's #131067. */+import type { InstallStamp } from './install-stamp'++/** Version labels alone cannot distinguish source builds or same-version rebuilds. */+export function launchBuildIdentity(options: {+ appVersion?: string | null+ installStamp?: Readonly<Pick<InstallStamp, 'commit' | 'builtAt' | 'dirty'>> | null+}): string {+ const appVersion = String(options.appVersion ?? '').trim() || '0.0.0'+ const stamp = options.installStamp+ const commit = String(stamp?.commit ?? '').trim()+ const builtAt = String(stamp?.builtAt ?? '').trim()++ if (!commit && !builtAt) {+ return appVersion+ }++ return `${appVersion}+${commit ? `g${commit.slice(0, 12)}` : 'unknown'}${stamp?.dirty ? '-dirty' : ''}${builtAt ? `@${builtAt}` : ''}`+}++/** Legacy witnesses get one probe only when this build can record a real identity. */+export function launchMarkerNeedsReprobe(+ marker: { version?: string | null; build?: string | null } | null | undefined,+ options: { appVersion?: string | null; buildIdentity?: string | null }+): boolean {+ const appVersion = String(options.appVersion ?? '').trim()+ const buildIdentity = String(options.buildIdentity ?? '').trim()++ if (!marker || !appVersion) {+ return false+ }++ if (marker.version && marker.version !== appVersion) {+ return true+ }++ return Boolean(buildIdentity && buildIdentity !== appVersion) && marker.build !== buildIdentity+}diff --git a/apps/desktop/electron/launch-marker-writer.test.ts b/apps/desktop/electron/launch-marker-writer.test.tsnew file mode 100644index 00000000000..322f0af973a--- /dev/null+++ b/apps/desktop/electron/launch-marker-writer.test.ts@@ -0,0 +1,53 @@+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.tsnew file mode 100644index 00000000000..b296028454e--- /dev/null+++ b/apps/desktop/electron/launch-marker-writer.ts@@ -0,0 +1,30 @@+/** 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-fallback.test.ts b/apps/desktop/electron/linux-nvidia-egl-fallback.test.tsindex d5d96740715..7ebf8704bd2 100644--- a/apps/desktop/electron/linux-nvidia-egl-fallback.test.ts+++ b/apps/desktop/electron/linux-nvidia-egl-fallback.test.ts@@ -101,7 +101,10 @@ describe('decideNvidiaEglFallback — behavioral probe', () => {// Chromium's "GPU process isn't usable" FATAL abort can kill the process// before the child-process-gone handler runs; the unresolved `booting`// marker is the evidence it leaves behind.- const decision = decideNvidiaEglFallback({ ...PROBE, marker: { state: 'booting' } })+ const decision = decideNvidiaEglFallback({+ ...PROBE,+ marker: { state: 'booting', version: PROBE.appVersion, driverVersion: PROBE.driverVersion }+ })expect(decision.enable).toBe(true)expect(decision.reason).toContain('aborted')@@ -170,7 +173,7 @@ describe('shouldRelaunchForNvidiaGpuDeath', () => {})it('relaunches on a GPU launch failure', () => {- expect(shouldRelaunchForNvidiaGpuDeath({ ...BASE, details: { type: 'GPU', reason: 'launch-failure' } })).toBe(true)+ expect(shouldRelaunchForNvidiaGpuDeath({ ...BASE, details: { type: 'GPU', reason: 'launch-failed' } })).toBe(true)})it("counts `killed`: the #40077 GPU process died to Chromium's health-check SIGTERM (exit_code=15)", () => {@@ -179,7 +182,7 @@ describe('shouldRelaunchForNvidiaGpuDeath', () => {})it('never relaunches twice in one process, or when the fallback is already active', () => {- const details = { type: 'GPU', reason: 'crashed' }+ const details = { type: 'GPU', reason: 'crashed' as const }expect(shouldRelaunchForNvidiaGpuDeath({ ...BASE, details, relaunchAttempted: true })).toBe(false)expect(shouldRelaunchForNvidiaGpuDeath({ ...BASE, details, fallbackActive: true })).toBe(false)@@ -226,3 +229,42 @@ describe('marker persistence', () => {).toEqual(nvidiaEglFallbackMarker('0.21.5', '580.178.04'))})})++describe('qualified NVIDIA witnesses across source updates', () => {+ const buildIdentity = '0.0.0+gsynthetic-new@2026-10-23T00:00:00Z'+ const source = { ...PROBE, appVersion: '0.0.0', buildIdentity }++ it('re-probes a legacy fallback on a source build instead of keeping 0.0.0 forever', () => {+ const marker = nvidiaEglFallbackMarker('0.0.0', PROBE.driverVersion)+ expect(decideNvidiaEglFallback({ ...source, marker }).enable).toBe(false)+ })++ it('re-probes both fallback and interrupted-boot records from a previous source build', () => {+ for (const state of ['fallback', 'booting'] as const) {+ const marker = { state, version: '0.0.0', driverVersion: PROBE.driverVersion, build: 'older-source-build' }+ expect(decideNvidiaEglFallback({ ...source, marker }).enable).toBe(false)+ }+ })++ it('does not trust an unqualified legacy booting marker as a failure of this build', () => {+ expect(decideNvidiaEglFallback({ ...source, marker: { state: 'booting' } }).enable).toBe(false)+ })++ it('retains a genuine failed probe only within the same build and driver', () => {+ const probe = decideNvidiaEglFallback(source)+ const retry = decideNvidiaEglFallback({ ...source, marker: probe.nextMarker })+ expect(retry.enable).toBe(true)+ expect(retry.nextMarker.build).toBe(buildIdentity)+ expect(decideNvidiaEglFallback({ ...source, marker: retry.nextMarker }).enable).toBe(true)+ expect(decideNvidiaEglFallback({ ...source, marker: retry.nextMarker, driverVersion: '600.2.3' }).enable).toBe(+ false+ )+ })++ it('does not discard a real release fallback or spin when no source identity is available', () => {+ const marker = nvidiaEglFallbackMarker(PROBE.appVersion, PROBE.driverVersion)+ expect(decideNvidiaEglFallback({ ...PROBE, marker }).enable).toBe(true)+ const unknown = nvidiaEglFallbackMarker('0.0.0', PROBE.driverVersion)+ expect(decideNvidiaEglFallback({ ...source, marker: unknown, buildIdentity: '0.0.0' }).enable).toBe(true)+ })+})diff --git a/apps/desktop/electron/linux-nvidia-egl-fallback.ts b/apps/desktop/electron/linux-nvidia-egl-fallback.tsindex 527d3482aa9..3295c6a9ad6 100644--- a/apps/desktop/electron/linux-nvidia-egl-fallback.ts+++ b/apps/desktop/electron/linux-nvidia-egl-fallback.ts@@ -43,6 +43,10 @@import fs from 'node:fs'import path from 'node:path'+import type { Details } from 'electron'++import { launchMarkerNeedsReprobe } from './launch-build-identity'+const OVERRIDE_ON = new Set(['1', 'true', 'yes', 'on'])const OVERRIDE_OFF = new Set(['0', 'false', 'no', 'off'])@@ -53,7 +57,11 @@ export const NVIDIA_EGL_FALLBACK_MARKER_FILENAME = 'nvidia-egl-fallback.json'* included on purpose: in #40077 the GPU process exited with exit_code=15 —* Chromium's own GPU health check SIGTERM — not a crash reason.*/-export const NVIDIA_GPU_DEATH_REASONS: ReadonlySet<string> = new Set(['crashed', 'launch-failure', 'killed'])+export const NVIDIA_GPU_DEATH_REASONS: ReadonlySet<Details['reason']> = new Set<Details['reason']>([+ 'crashed',+ 'launch-failed',+ 'killed'+])export type NvidiaEglMarkerState = 'booting' | 'fallback' | 'ok'@@ -63,6 +71,8 @@ export interface NvidiaEglMarker {version?: string/** Full driver version (e.g. "580.178.04") the fallback was witnessed on. */driverVersion?: string+ /** Source builds can share 0.0.0, so retain their immutable build identity. */+ build?: string}export function nvidiaEglMarkerPath(userDataDir: string): string {@@ -91,6 +101,10 @@ export function parseNvidiaEglMarker(raw: unknown): NvidiaEglMarker | null {marker.driverVersion = record.driverVersion}+ if (typeof record.build === 'string' && record.build) {+ marker.build = record.build+ }+return marker}@@ -126,8 +140,17 @@ export function writeNvidiaEglMarker(writeFileSync(nvidiaEglMarkerPath(dir), `${JSON.stringify(marker)}\n`, 'utf8')}-export function nvidiaEglFallbackMarker(appVersion: string, driverVersion: string): NvidiaEglMarker {- return { state: 'fallback', version: appVersion, driverVersion }+export function nvidiaEglFallbackMarker(+ appVersion: string,+ driverVersion: string,+ buildIdentity?: string+): NvidiaEglMarker {+ return {+ state: 'fallback',+ version: appVersion,+ driverVersion,+ ...(buildIdentity && buildIdentity !== appVersion ? { build: buildIdentity } : {})+ }}/**@@ -159,7 +182,7 @@ export function parseNvidiaDriverVersion(procVersion: string): string | null {export interface NvidiaEglFallbackDecision {enable: booleanreason: string | null- /** Marker to persist immediately, before GPU children start. */+ /** Marker to persist only after acquiring the single-instance lock. */nextMarker: NvidiaEglMarker}@@ -167,110 +190,106 @@ export interface NvidiaEglFallbackDecision {* Single launch-time transition: whether this Linux launch routes ANGLE* through SwiftShader, and what the marker becomes. The probe shape:*- * - `fallback` marker matching this app version AND driver version → enable,- * keep the marker (sticky until either version changes).- * - `fallback` marker for a different app or driver version → re-probe once:+ * - `fallback` marker matching this artifact build AND driver version → enable,+ * keep the marker until the artifact build or driver changes.+ * - `fallback` or `booting` marker for an older build/driver → re-probe once:* boot with hardware GL, write `booting`.- * - `booting` marker left behind by a launch that died before it could mark+ * - `booting` marker for this same build/driver left by a launch that died before it could mark* `ok` (the "GPU process isn't usable" FATAL abort) → enable; the previous* boot witnessed a GPU death by not surviving.* - `ok` or no marker → boot with hardware GL, write `booting` so a death* mid-boot is attributable.** The env override `HERMES_DESKTOP_NVIDIA_SWIFTSHADER=1` forces the fallback- * on regardless of the marker; `=0` keeps it off and clears the marker.+ * on regardless of the marker; `=0` keeps it off during startup and GPU death.+ * The lock owner records a healthy boot or clean exit before removing the override.*/-export function decideNvidiaEglFallback(options: {+export interface NvidiaEglFallbackOptions {driverMajor: number | nulldriverVersion?: string | nullmarker?: NvidiaEglMarker | nullappVersion?: string+ buildIdentity?: stringenv?: NodeJS.ProcessEnvplatform?: NodeJS.PlatformisWsl?: booleanremoteDisplayReason?: string | null-}): NvidiaEglFallbackDecision {+}++/** The same exclusions govern startup and later GPU-death recovery. */+export function nvidiaEglFallbackAllowed(options: NvidiaEglFallbackOptions): boolean {const env = options.env ?? process.env- const platform = options.platform ?? process.platform- const isWsl = options.isWsl ?? false- const remoteDisplayReason = options.remoteDisplayReason ?? null- const driverMajor = options.driverMajor- const driverVersion = options.driverVersion ?? null- const appVersion = options.appVersion ?? ''- const marker = options.marker ?? null- const bootMarker: NvidiaEglMarker = { state: 'booting' }+ const off = (key: string): boolean =>+ OVERRIDE_OFF.has(+ String(env[key] || '')+ .trim()+ .toLowerCase()+ )++ return (+ (options.platform ?? process.platform) === 'linux' &&+ options.driverMajor !== null &&+ !options.isWsl &&+ !options.remoteDisplayReason &&+ !off('HERMES_DESKTOP_NVIDIA_SWIFTSHADER') &&+ !off('HERMES_DESKTOP_DISABLE_GPU')+ )+}- const nvidiaOverride = String(env.HERMES_DESKTOP_NVIDIA_SWIFTSHADER || '')- .trim()- .toLowerCase()+export function decideNvidiaEglFallback(options: NvidiaEglFallbackOptions): NvidiaEglFallbackDecision {+ const env = options.env ?? process.env+ const appVersion = options.appVersion ?? ''+ const driverVersion = options.driverVersion ?? String(options.driverMajor ?? '')+ const buildIdentity = options.buildIdentity ?? ''+ const marker = options.marker ?? null- if (OVERRIDE_OFF.has(nvidiaOverride)) {- return { enable: false, reason: null, nextMarker: bootMarker }+ const bootMarker: NvidiaEglMarker = {+ ...nvidiaEglFallbackMarker(appVersion, driverVersion, buildIdentity),+ state: 'booting'}- if (platform !== 'linux' || driverMajor === null) {- // No NVIDIA driver to probe — nothing to persist either.+ if (!nvidiaEglFallbackAllowed(options)) {return { enable: false, reason: null, nextMarker: bootMarker }}- // A user who forced GPU back on (HERMES_DESKTOP_DISABLE_GPU=0) owns that call.- const gpuOverride = String(env.HERMES_DESKTOP_DISABLE_GPU || '')+ const nvidiaOverride = String(env.HERMES_DESKTOP_NVIDIA_SWIFTSHADER || '').trim().toLowerCase()- if (OVERRIDE_OFF.has(gpuOverride)) {- return { enable: false, reason: null, nextMarker: bootMarker }- }-- // The remote-display path already forces full software rendering; don't pile- // ANGLE switches on top of `disableHardwareAcceleration`.- if (remoteDisplayReason) {- return { enable: false, reason: null, nextMarker: bootMarker }- }-- // WSLg reports a healthy vGPU; NVIDIA EGL probing hasn't been reported- // broken there. Keep the WSL GPU passthrough path untouched.- if (isWsl) {- return { enable: false, reason: null, nextMarker: bootMarker }- }-if (OVERRIDE_ON.has(nvidiaOverride)) {return { enable: true, reason: 'override (HERMES_DESKTOP_NVIDIA_SWIFTSHADER)', nextMarker: bootMarker }}- // Witnessed brokenness: sticky only for the same app AND driver version.- if (- marker?.state === 'fallback' &&- marker.version === (appVersion || marker.version) &&- marker.driverVersion === (driverVersion ?? marker.driverVersion)- ) {+ const sameBuild =+ marker?.version === appVersion &&+ marker.driverVersion === driverVersion &&+ !launchMarkerNeedsReprobe(marker, { appVersion, buildIdentity })++ if (marker?.state === 'fallback' && sameBuild) {return {enable: true,- reason: `witnessed GPU-process death (app ${marker.version ?? '?'}, driver ${marker.driverVersion ?? '?'})`,+ reason: `witnessed GPU-process death (app ${marker.version}, driver ${marker.driverVersion})`,nextMarker: marker}}- // A booting marker that never resolved: the previous launch died before it- // could mark a healthy boot — on this driver that means the GPU process- // took the app down (the "GPU process isn't usable" FATAL abort wins the- // race against our relaunch handler). Trust it and engage.- if (marker?.state === 'booting') {+ // An abort is evidence only for the build and driver that actually attempted it.+ // Legacy unqualified booting records get one fresh probe, as do stale fallbacks.+ if (marker?.state === 'booting' && sameBuild) {return {enable: true,reason: 'previous launch aborted mid-boot with the GPU probe live',- nextMarker: nvidiaEglFallbackMarker(appVersion, driverVersion ?? String(driverMajor))+ nextMarker: nvidiaEglFallbackMarker(appVersion, driverVersion, buildIdentity)}}- // ok, stale fallback (app or driver updated), or first boot: probe the GPU.return { enable: false, reason: null, nextMarker: bootMarker }}export interface NvidiaGpuDeathOptions {platform?: NodeJS.Platform | string- details: { type?: string; reason?: string } | null+ details: { type?: string; reason?: Details['reason'] } | null/** The fallback is already active this launch (sticky marker or override). */fallbackActive: boolean/** This process already attempted the one-shot relaunch. */@@ -294,9 +313,9 @@ export function shouldRelaunchForNvidiaGpuDeath({}const type = String(details?.type ?? '').toLowerCase()- const reason = String(details?.reason ?? '').toLowerCase()+ const reason = details?.reason- return (type === 'gpu' || type === 'gpu-process') && NVIDIA_GPU_DEATH_REASONS.has(reason)+ return (type === 'gpu' || type === 'gpu-process') && Boolean(reason && NVIDIA_GPU_DEATH_REASONS.has(reason))}/**@@ -308,9 +327,10 @@ export function nvidiaEglMarkerAfterSuccessfulBoot(options: {fallbackActive: booleanappVersion?: stringdriverVersion?: string | null+ buildIdentity?: string}): NvidiaEglMarker {if (options.fallbackActive) {- return nvidiaEglFallbackMarker(options.appVersion ?? '', options.driverVersion ?? '')+ return nvidiaEglFallbackMarker(options.appVersion ?? '', options.driverVersion ?? '', options.buildIdentity)}return { state: 'ok' }diff --git a/apps/desktop/electron/linux-nvidia-egl-recovery.native.test.ts b/apps/desktop/electron/linux-nvidia-egl-recovery.native.test.tsnew file mode 100644index 00000000000..3c9d83a6371--- /dev/null+++ b/apps/desktop/electron/linux-nvidia-egl-recovery.native.test.ts@@ -0,0 +1,194 @@+import { execFileSync, spawn } from 'node:child_process'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import path from 'node:path'++import electron from 'electron'+import { buildSync } from 'esbuild'+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'++import { launchBuildIdentity } from './launch-build-identity'+import { nvidiaEglMarkerPath, readNvidiaEglMarker, writeNvidiaEglMarker } from './linux-nvidia-egl-fallback'++interface FixtureEvent {+ event: string+ software?: boolean+ marker?: unknown+}++const nativeAvailable = process.platform !== 'linux' || Boolean(process.env.DISPLAY)+const children: Array<ReturnType<typeof spawn>> = []+const stamp = (commit: string) => ({ commit, builtAt: '2026-10-23T00:00:00Z', dirty: false })+let root: string+let firstArtifact: string+let updatedArtifact: string++function buildArtifact(name: string, commit: string): string {+ const artifact = path.join(root, name)+ mkdirSync(artifact)+ writeFileSync(+ path.join(artifact, 'package.json'),+ JSON.stringify({+ name: 'hermes-recovery-fixture',+ version: '0.0.0',+ main: 'main.mjs',+ type: 'module'+ })+ )+ buildSync({+ entryPoints: [path.join(import.meta.dirname, 'fixtures/nvidia-recovery.ts')],+ outfile: path.join(artifact, 'main.mjs'),+ bundle: true,+ platform: 'node',+ format: 'esm',+ external: ['electron'],+ define: { __HERMES_INSTALL_STAMP__: JSON.stringify(stamp(commit)) }+ })++ return artifact+}++function start(artifact: string, userData: string, quitBeforeReveal = false) {+ const env = { ...process.env }+ delete env.ELECTRON_RUN_AS_NODE+ const nonce = `${Date.now()}-${children.length}`+ const eventsFile = path.join(userData, `events-${nonce}.jsonl`)+ const commandFile = path.join(userData, `command-${nonce}`)+ const options = { userData, eventsFile, commandFile, quitBeforeReveal }++ const child = spawn(String(electron), [artifact, `--recovery-fixture=${JSON.stringify(options)}`], {+ env,+ windowsHide: true,+ stdio: ['ignore', 'ignore', 'pipe']+ })++ children.push(child)+ let output = ''+ let failed = false+ child.stderr!.on('data', data => {+ output += String(data)+ })+ child.on('error', error => {+ failed = true+ output += String(error)+ })+ const exited = new Promise<void>(resolve => child.once('exit', () => resolve()))++ return {+ child,+ exited,+ async event(name: string): Promise<FixtureEvent> {+ const deadline = Date.now() + 15_000++ while (Date.now() < deadline) {+ const events: FixtureEvent[] = existsSync(eventsFile)+ ? readFileSync(eventsFile, 'utf8')+ .trim()+ .split('\n')+ .filter(Boolean)+ .map(line => JSON.parse(line))+ : []++ const event = events.find(event => event.event === name)++ if (event) {+ return event+ }++ if (failed || child.exitCode !== null || child.signalCode !== null) {+ throw new Error(`Fixture exited: ${output}`)+ }++ await new Promise(resolve => setTimeout(resolve, 75))+ }++ throw new Error(`Fixture timed out waiting for ${name}: ${output}`)+ },+ async quit(): Promise<void> {+ writeFileSync(commandFile, 'quit')+ await Promise.race([+ exited,+ new Promise<never>((_, reject) => {+ const timer = setTimeout(() => reject(new Error(`Fixture did not quit: ${output}`)), 10_000)+ timer.unref()+ })+ ])+ }+ }+}++describe.skipIf(!nativeAvailable)('native Electron locking and persisted NVIDIA recovery policy (no rendering)', () => {+ beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'nvidia-native-'))+ firstArtifact = buildArtifact('first', 'a'.repeat(40))+ updatedArtifact = buildArtifact('updated', 'b'.repeat(40))+ })+ afterEach(async () => {+ for (const child of children.splice(0)) {+ if (child.pid && child.exitCode === null && child.signalCode === null) {+ const exited = new Promise<void>(resolve => child.once('exit', () => resolve()))++ if (process.platform === 'win32') {+ execFileSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true, stdio: 'ignore' })+ } else {+ child.kill('SIGKILL')+ }++ await exited+ }+ }+ })+ afterAll(() => {+ if (root) {+ rmSync(root, { recursive: true, force: true })+ }+ })++ it('a secondary Electron process leaves state intact, then a normal restart stays native', async () => {+ const userData = path.join(root, 'second-launch')+ mkdirSync(userData)+ const primary = start(firstArtifact, userData)+ expect((await primary.event('ready')).software).toBe(false)+ const before = readFileSync(nvidiaEglMarkerPath(userData), 'utf8')+ const secondary = start(firstArtifact, userData)+ await secondary.event('secondary')+ await secondary.exited+ expect(readFileSync(nvidiaEglMarkerPath(userData), 'utf8')).toBe(before)+ await primary.quit()+ const restarted = start(firstArtifact, userData)+ expect((await restarted.event('ready')).software).toBe(false)+ await restarted.quit()+ })++ it.each(['booting', 'fallback'] as const)(+ 'a new stamped artifact recovers old %s state at the same app version',+ async state => {+ const userData = path.join(root, `update-${state}`)+ mkdirSync(userData)+ writeNvidiaEglMarker(userData, {+ state,+ version: '0.0.0',+ driverVersion: '600.1.2',+ build: launchBuildIdentity({ appVersion: '0.0.0', installStamp: stamp('a'.repeat(40)) })+ })+ const updated = start(updatedArtifact, userData)+ expect((await updated.event('ready')).software).toBe(false)+ await updated.quit()+ const restarted = start(updatedArtifact, userData)+ expect((await restarted.event('ready')).software).toBe(false)+ await restarted.quit()+ expect(readNvidiaEglMarker(userData)).toEqual({ state: 'ok' })+ }+ )++ it('a clean exit before reveal does not poison the next process', async () => {+ const userData = path.join(root, 'early-quit')+ mkdirSync(userData)+ const early = start(firstArtifact, userData, true)+ await early.event('early-exit')+ await early.exited+ const restarted = start(firstArtifact, userData)+ expect((await restarted.event('ready')).software).toBe(false)+ await restarted.quit()+ })+})diff --git a/apps/desktop/electron/linux-nvidia-egl-recovery.test.ts b/apps/desktop/electron/linux-nvidia-egl-recovery.test.tsnew file mode 100644index 00000000000..cee43c85dfa--- /dev/null+++ b/apps/desktop/electron/linux-nvidia-egl-recovery.test.ts@@ -0,0 +1,162 @@+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+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 { nvidiaEglMarkerPath, readNvidiaEglMarker, writeNvidiaEglMarker } from './linux-nvidia-egl-fallback'+import { createNvidiaEglRecovery } from './linux-nvidia-egl-recovery'++let userData: string+const driverVersion = '600.1.2'++const build = (commit = 'a'.repeat(40)) =>+ launchBuildIdentity({+ appVersion: '0.0.0',+ installStamp: { commit, builtAt: '2026-10-23T00:00:00Z', dirty: false }+ })++function launch(overrides: Partial<Parameters<typeof createNvidiaEglRecovery>[0]> = {}, primary = true) {+ const writer = createLaunchMarkerWriter()+ const relaunch = vi.fn()+ const log = vi.fn()++ const recovery = createNvidiaEglRecovery({+ userData,+ driverMajor: 600,+ driverVersion,+ appVersion: '0.0.0',+ buildIdentity: build(),+ platform: 'linux',+ env: {},+ queueMarker: write => writer.queue(write),+ relaunch,+ log,+ ...overrides+ })++ writer.flush(primary)++ return { ...recovery, relaunch, log }+}++beforeEach(() => {+ userData = mkdtempSync(path.join(tmpdir(), 'nvidia-recovery-'))+})+afterEach(() => {+ rmSync(userData, { recursive: true, force: true })+})++describe('NVIDIA persisted recovery lifecycle', () => {+ it('a successful native launch stays native through an ordinary restart without an override', () => {+ const first = launch()+ expect(first.decision.enable).toBe(false)+ first.healthy()+ first.cleanExit()+ const restarted = launch()+ expect(restarted.decision.enable).toBe(false)+ restarted.healthy()+ expect(readNvidiaEglMarker(userData)).toEqual({ state: 'ok' })+ })++ it('secondary launches leave the running primary marker unchanged and cannot force the next restart', () => {+ const first = launch()+ first.healthy()+ const before = readFileSync(nvidiaEglMarkerPath(userData), 'utf8')++ for (let i = 0; i < 3; i++) {+ const secondary = launch({}, false)+ secondary.healthy()+ secondary.cleanExit()+ expect(secondary.gpuDied({ type: 'GPU', reason: 'crashed', exitCode: 1 })).toBe(false)+ expect(readFileSync(nvidiaEglMarkerPath(userData), 'utf8')).toBe(before)+ }++ first.cleanExit()+ expect(launch().decision.enable).toBe(false)+ })++ it('a secondary launch during primary startup cannot persist its tentative fallback', () => {+ const first = launch()+ const before = readFileSync(nvidiaEglMarkerPath(userData), 'utf8')+ const secondary = launch({}, false)+ expect(secondary.decision.enable).toBe(true)+ expect(readFileSync(nvidiaEglMarkerPath(userData), 'utf8')).toBe(before)+ first.healthy()+ first.cleanExit()+ expect(launch().decision.enable).toBe(false)+ })++ it('clean restart or update handoff before first paint does not leave a false aborted probe', () => {+ const first = launch()+ expect(readNvidiaEglMarker(userData)?.state).toBe('booting')+ first.cleanExit()+ expect(first.gpuDied({ type: 'GPU', reason: 'killed', exitCode: 0 })).toBe(false)+ expect(first.relaunch).not.toHaveBeenCalled()+ expect(launch().decision.enable).toBe(false)+ })++ it.each(['booting', 'fallback'] as const)(+ 'a source update re-probes an old %s record even when app version stays 0.0.0',+ state => {+ writeNvidiaEglMarker(userData, { state, version: '0.0.0', driverVersion, build: build() })+ const updated = launch({ buildIdentity: build('b'.repeat(40)) })+ expect(updated.decision.enable).toBe(false)+ updated.healthy()+ updated.cleanExit()+ expect(launch({ buildIdentity: build('b'.repeat(40)) }).decision.enable).toBe(false)+ }+ )++ it('recovers existing unqualified state, records the new probe, and retains a genuine failure of that probe', () => {+ writeNvidiaEglMarker(userData, { state: 'booting' })+ expect(launch().decision.enable).toBe(false)+ // No healthy/clean-exit event: this process actually aborted during the new probe.+ const retry = launch()+ expect(retry.decision.enable).toBe(true)+ retry.cleanExit()+ expect(launch().decision.enable).toBe(true)+ })++ it('uses the real Electron launch-failed event, bounds relaunch, and preserves its fallback through teardown', () => {+ const first = launch()+ const details = { type: 'GPU' as const, reason: 'launch-failed' as const, exitCode: 1 }+ expect(first.gpuDied(details)).toBe(true)+ expect(first.gpuDied(details)).toBe(false)+ first.healthy()+ first.cleanExit()+ expect(first.relaunch).toHaveBeenCalledTimes(1)+ expect(readNvidiaEglMarker(userData)?.state).toBe('fallback')+ expect(launch().decision.enable).toBe(true)+ })++ it('does not interpret a GPU child killed by an in-progress update as a new failure', () => {+ const first = launch()+ first.healthy()+ expect(first.gpuDied({ type: 'GPU', reason: 'killed', exitCode: 0 }, true)).toBe(false)+ first.cleanExit()+ expect(first.relaunch).not.toHaveBeenCalled()+ expect(launch().decision.enable).toBe(false)+ })++ it.each(['HERMES_DESKTOP_NVIDIA_SWIFTSHADER', 'HERMES_DESKTOP_DISABLE_GPU'])(+ 'honors %s=0 throughout GPU-death handling',+ key => {+ const first = launch({ env: { [key]: '0' } })+ expect(first.gpuDied({ type: 'GPU', reason: 'crashed', exitCode: 1 })).toBe(false)+ first.healthy()+ expect(first.relaunch).not.toHaveBeenCalled()+ expect(readNvidiaEglMarker(userData)?.state).toBe('ok')+ }+ )++ it('keeps an explicitly forced SwiftShader launch in software after successful startup and exit', () => {+ const first = launch({ env: { HERMES_DESKTOP_NVIDIA_SWIFTSHADER: '1' } })+ expect(first.decision.enable).toBe(true)+ first.healthy()+ first.cleanExit()+ expect(readNvidiaEglMarker(userData)?.state).toBe('fallback')+ })+})diff --git a/apps/desktop/electron/linux-nvidia-egl-recovery.ts b/apps/desktop/electron/linux-nvidia-egl-recovery.tsnew file mode 100644index 00000000000..c209e67c3b4--- /dev/null+++ b/apps/desktop/electron/linux-nvidia-egl-recovery.ts@@ -0,0 +1,111 @@+import type { Details } from 'electron'++import type { NvidiaEglFallbackOptions, NvidiaEglMarker } from './linux-nvidia-egl-fallback'+import {+ decideNvidiaEglFallback,+ nvidiaEglFallbackAllowed,+ nvidiaEglFallbackMarker,+ nvidiaEglMarkerAfterSuccessfulBoot,+ readNvidiaEglMarker,+ shouldRelaunchForNvidiaGpuDeath,+ writeNvidiaEglMarker+} from './linux-nvidia-egl-fallback'++interface NvidiaEglRecoveryOptions extends Omit<NvidiaEglFallbackOptions, 'marker'> {+ userData: string+ queueMarker: (write: () => void) => void+ relaunch: () => void+ log: (message: string) => void+}++/** Persist only for the lock owner, and never turn intentional teardown into GPU failure. */+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+ let quitting = false+ let relaunchAttempted = false++ const persist = (marker: NvidiaEglMarker): void => {+ try {+ writeNvidiaEglMarker(options.userData, marker)+ } catch (error) {+ options.log(`[gpu] could not persist NVIDIA recovery state: ${String(error)}`)+ }+ }++ if (supported) {+ options.queueMarker(() => {+ primary = true+ persist(decision.nextMarker)+ })+ }++ return {+ decision,+ startupMessage: `[gpu] NVIDIA ANGLE fallback=${decision.enable} (${decision.reason ?? 'not selected'}); previous=${previous?.state ?? 'none'}; build=${options.buildIdentity ?? options.appVersion}; driver=${options.driverVersion}`,+ healthy(): void {+ if (!primary || quitting || relaunchAttempted) {+ return+ }++ persist(nvidiaEglMarkerAfterSuccessfulBoot({ ...options, fallbackActive: decision.enable }))+ },+ cleanExit(): void {+ quitting = true++ if (!primary || decision.enable || relaunchAttempted) {+ return+ }++ const marker = readNvidiaEglMarker(options.userData)++ // Do not erase a fallback written by a recovery relaunch or a different build.+ if (+ marker?.state === 'booting' &&+ marker.version === decision.nextMarker.version &&+ marker.driverVersion === decision.nextMarker.driverVersion &&+ marker.build === decision.nextMarker.build+ ) {+ persist({ state: 'ok' })+ }+ },+ gpuDied(details: Pick<Details, 'type' | 'reason' | 'exitCode'>, teardownInProgress = false): boolean {+ if (+ !primary ||+ quitting ||+ teardownInProgress ||+ !nvidiaEglFallbackAllowed(options) ||+ !shouldRelaunchForNvidiaGpuDeath({+ platform: options.platform,+ details,+ fallbackActive: decision.enable,+ relaunchAttempted+ })+ ) {+ return false+ }++ relaunchAttempted = true+ persist(+ nvidiaEglFallbackMarker(+ options.appVersion ?? '',+ options.driverVersion ?? String(options.driverMajor),+ options.buildIdentity+ )+ )+ options.log(+ `[gpu] NVIDIA GPU process died (${details.reason}, exit=${details.exitCode}); relaunching with SwiftShader`+ )++ try {+ options.relaunch()+ } catch (error) {+ options.log(`[gpu] NVIDIA SwiftShader relaunch failed: ${String(error)}`)+ }++ return true+ }+ }+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 2749248739d..097495c7d2f 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -322,6 +322,8 @@ import { linuxOzoneBackend, resolveHudWindowing } from './hud-windowing'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'@@ -337,16 +339,8 @@ import {writeLinuxGpuMarker} from './linux-gpu-fallback'import { notifyLauncherWindowRevealed } from './linux-launcher-ready'-import {- decideNvidiaEglFallback,- nvidiaEglFallbackMarker,- nvidiaEglMarkerAfterSuccessfulBoot,- parseNvidiaDriverMajor,- parseNvidiaDriverVersion,- readNvidiaEglMarker,- shouldRelaunchForNvidiaGpuDeath,- writeNvidiaEglMarker-} from './linux-nvidia-egl-fallback'+import { parseNvidiaDriverMajor, parseNvidiaDriverVersion } from './linux-nvidia-egl-fallback'+import { createNvidiaEglRecovery } from './linux-nvidia-egl-recovery'import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle'import { resolveIpcFileReadPath, resolveMediaStreamFile, resolvePreviewTargetPath } from './local-read-path'import { localSkinProfileKey, readLocalSkinPayload } from './local-skin'@@ -787,6 +781,8 @@ 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@@ -804,11 +800,7 @@ if (IS_WINDOWS) {windowsGpuStackCookieFallbackActive = gpuStackCookieDecision.enablewindowsGpuStackCookieFallbackSticky = gpuStackCookieDecision.nextMarker.state === 'fallback'- try {- writeGpuStackCookieMarker(windowsGpuUserData, gpuStackCookieDecision.nextMarker)- } catch {- void 0- }+ launchMarkerWriter.queue(() => writeGpuStackCookieMarker(windowsGpuUserData, gpuStackCookieDecision.nextMarker))if (gpuStackCookieDecision.enable && !REMOTE_DISPLAY_REASON) {app.disableHardwareAcceleration()@@ -858,18 +850,9 @@ if (console.log('[hermes] WSL GPU passthrough (/dev/dxg) detected; enabling GPU acceleration')}-// #40077 / #124255: NVIDIA driver 580.x breaks ANGLE's EGL probing (Invalid-// visual ID), killing the GPU process at startup. Route ANGLE through its-// SwiftShader backend when the breakage is WITNESSED, not assumed: the same-// point release breaks hosts where NVIDIA drives the display and renders fine-// on hybrid hosts whose session EGL lands on the iGPU, so a driver-series gate-// burns 4-9 CPU cores on healthy hosts (#124255). The gate is now behavioral —-// boot with hardware GL and a marker; a GPU-process death before the first-// window flips the marker sticky (per app + full driver version) and relaunches-// once with SwiftShader. Deliberately NOT disableHardwareAcceleration(): on-// 580.173.02 + Electron 40 that SIGKILLs the renderer (see the closed #40119).-// Must run before app `ready` — the switch only applies pre-launch. Override-// with HERMES_DESKTOP_NVIDIA_SWIFTSHADER (1/true → force on, 0/false → never).+// NVIDIA EGL failures use a build-qualified, lock-owned recovery witness.+// Healthy launches retain hardware rendering; source rebuilds re-probe old failures.+// Keep this before app ready because ANGLE switches apply only at startup.const NVIDIA_PROC_VERSION = (() => {try {return fs.readFileSync('/proc/driver/nvidia/version', 'utf8')@@ -881,85 +864,37 @@ const NVIDIA_PROC_VERSION = (() => {const NVIDIA_DRIVER_MAJOR = parseNvidiaDriverMajor(NVIDIA_PROC_VERSION)const NVIDIA_DRIVER_VERSION = parseNvidiaDriverVersion(NVIDIA_PROC_VERSION)-let nvidiaEglFallbackActive = false-let nvidiaEglRelaunchAttempted = false--const NVIDIA_EGL_FALLBACK = decideNvidiaEglFallback({+const nvidiaEglRecovery = createNvidiaEglRecovery({driverMajor: NVIDIA_DRIVER_MAJOR,driverVersion: NVIDIA_DRIVER_VERSION,- marker: readNvidiaEglMarker(app.getPath('userData')),+ userData: app.getPath('userData'),appVersion: app.getVersion(),+ buildIdentity: launchBuildIdentity({ appVersion: app.getVersion(), installStamp: INSTALL_STAMP }),env: process.env,platform: process.platform,isWsl: IS_WSL,- remoteDisplayReason: REMOTE_DISPLAY_REASON+ remoteDisplayReason: REMOTE_DISPLAY_REASON,+ queueMarker: write => launchMarkerWriter.queue(write),+ log: message => {+ console.warn(`[hermes] ${message}`)+ void app.whenReady().then(() => {+ rememberLog(message)+ flushDesktopLogBufferSync()+ })+ },+ relaunch: () => {+ // The persisted witness selects ANGLE on the next launch. Do not carry an+ // automatic --use-angle flag into later update relaunches.+ app.relaunch({ args: process.argv.slice(1) })+ void exitAfterBackendShutdown(0)+ }})-nvidiaEglFallbackActive = NVIDIA_EGL_FALLBACK.enable--// Persist the launch decision before GPU children start: a `booting` marker-// left behind by a launch that never reached first paint is itself evidence-// of a GPU death (the "GPU process isn't usable" FATAL abort wins the race-// against our relaunch handler), and the next launch engages from it.-if (NVIDIA_DRIVER_MAJOR !== null) {- try {- writeNvidiaEglMarker(app.getPath('userData'), NVIDIA_EGL_FALLBACK.nextMarker)- } catch {- void 0- }-}+const NVIDIA_EGL_FALLBACK = nvidiaEglRecovery.decisionif (NVIDIA_EGL_FALLBACK.enable) {app.commandLine.appendSwitch('use-angle', 'swiftshader')- console.log(- `[hermes] NVIDIA EGL fallback enabled (${NVIDIA_EGL_FALLBACK.reason}); routing ANGLE ` +- 'through SwiftShader. Witnessed GPU-process death probe (#40077, #124255); an app or ' +- 'driver update re-probes hardware GL once. HERMES_DESKTOP_NVIDIA_SWIFTSHADER=0 to opt out.'- )-}--// The behavioral half of the gate: a GPU-process death on a Linux NVIDIA host-// that booted with hardware GL is the #40077 signature. Catch it before-// Chromium's "GPU process isn't usable" FATAL abort ends the process, flip the-// marker sticky, and relaunch once with SwiftShader. `killed` counts (the-// #40077 GPU process died to Chromium's health-check SIGTERM, exit_code=15).-if (NVIDIA_DRIVER_MAJOR !== null && process.platform === 'linux') {- app.on('child-process-gone', (_event, details) => {- if (- !shouldRelaunchForNvidiaGpuDeath({- details,- fallbackActive: nvidiaEglFallbackActive,- relaunchAttempted: nvidiaEglRelaunchAttempted- })- ) {- return- }-- nvidiaEglRelaunchAttempted = true-- try {- writeNvidiaEglMarker(- app.getPath('userData'),- nvidiaEglFallbackMarker(app.getVersion(), NVIDIA_DRIVER_VERSION ?? String(NVIDIA_DRIVER_MAJOR))- )- } catch {- void 0- }-- console.warn(- `[hermes] NVIDIA GPU process died (reason=${details?.reason}, exit=${details?.exitCode}); ` +- 'relaunching once with --use-angle=swiftshader (#40077, #124255)'- )-- try {- app.relaunch({- args: [...process.argv.slice(1), '--use-angle=swiftshader']- })- void exitAfterBackendShutdown(0)- } catch (error) {- console.error(`[hermes] NVIDIA SwiftShader relaunch failed: ${error?.message || error}`)- }- })+ console.log(`[hermes] NVIDIA EGL fallback enabled (${NVIDIA_EGL_FALLBACK.reason}); routing ANGLE through SwiftShader`)}// #124843: on Mesa/Wayland the Chromium GPU child can fail init@@ -991,11 +926,7 @@ if (process.platform === 'linux') {linuxGpuFallbackActive = linuxGpuDecision.enablelinuxGpuFallbackSticky = linuxGpuDecision.nextMarker.state === 'fallback'- try {- writeLinuxGpuMarker(linuxGpuUserData, linuxGpuDecision.nextMarker)- } catch {- void 0- }+ launchMarkerWriter.queue(() => writeLinuxGpuMarker(linuxGpuUserData, linuxGpuDecision.nextMarker))if (linuxGpuDecision.enable && linuxGpuDecision.reason !== 'already-enabled' && !LINUX_GPU_SOFTWARE_ACTIVE) {app.disableHardwareAcceleration()@@ -1093,47 +1024,55 @@ if (IS_WINDOWS || process.platform === 'linux') {)}- writeSandboxMarker(windowsUserData, sandboxDecision.nextMarker)+ launchMarkerWriter.queue(() => 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// still crashes), then the software ladder — including the relapse after a// --no-sandbox boot died again. One death, one bounded relaunch; Windows// keeps its breakpoint-signature fast path unchanged.- app.on('child-process-gone', (_event, details) => {- if (IS_WINDOWS) {- if (- !shouldRelaunchForGpuSandboxCrash({- details,- alreadyNoSandbox: windowsSandboxFallbackActive || alreadyHasNoSandbox(process.argv, process.env),- relaunchAttempted: windowsNoSandboxRelaunchAttempted- })- ) {- return- }+ const recoverWindowsGpuSandbox = (details: Electron.Details): void => {+ if (+ !shouldRelaunchForGpuSandboxCrash({+ details,+ alreadyNoSandbox: windowsSandboxFallbackActive || alreadyHasNoSandbox(process.argv, process.env),+ relaunchAttempted: windowsNoSandboxRelaunchAttempted+ })+ ) {+ return+ }- windowsNoSandboxRelaunchAttempted = true- windowsSandboxFallbackActive = true- windowsSandboxFallbackSticky = true- windowsSandboxFallbackReason = 'gpu-breakpoint'+ windowsNoSandboxRelaunchAttempted = true+ windowsSandboxFallbackActive = true+ windowsSandboxFallbackSticky = true+ windowsSandboxFallbackReason = 'gpu-breakpoint'- try {- writeSandboxMarker(app.getPath('userData'), fallbackMarker('gpu-breakpoint', app.getVersion()))- } catch {- void 0- }+ try {+ writeSandboxMarker(app.getPath('userData'), fallbackMarker('gpu-breakpoint', app.getVersion()))+ } catch {+ void 0+ }- console.warn(- `[hermes] GPU child died with the sandbox signature (exit=${details?.exitCode}); relaunching once with --no-sandbox (#38216)`- )+ console.warn(+ `[hermes] GPU child died with the sandbox signature (exit=${details?.exitCode}); relaunching once with --no-sandbox (#38216)`+ )- try {- app.relaunch({ args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })- void exitAfterBackendShutdown(0)- } catch (error) {- console.error(`[hermes] --no-sandbox relaunch failed: ${error?.message || error}`)- }+ try {+ app.relaunch({ args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })+ void exitAfterBackendShutdown(0)+ } catch (error) {+ console.error(`[hermes] --no-sandbox relaunch failed: ${error?.message || error}`)+ }+ }+ app.on('child-process-gone', (_event, details) => {+ if (IS_WINDOWS) {+ recoverWindowsGpuSandbox(details)++ return+ }++ if (rendererTeardownInProgress() || quitInProgress) {return}@@ -1148,6 +1087,11 @@ if (IS_WINDOWS || process.platform === 'linux') {softwareRelaunchAttempted: linuxGpuRelaunchAttempted})+ // One event must not schedule both ANGLE and disable-gpu relaunches.+ if (path !== 'no-sandbox' && nvidiaEglRecovery.gpuDied(details)) {+ return+ }+if (path === 'no-sandbox') {windowsNoSandboxRelaunchAttempted = truewindowsSandboxFallbackActive = true@@ -1267,7 +1211,10 @@ 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@@ -11732,6 +11679,8 @@ async function teardownSshForQuit(): Promise<void> {}async function exitAfterBackendShutdown(code) {+ nvidiaEglRecovery.cleanExit()+try {await backendShutdown.run()} catch {@@ -13735,23 +13684,7 @@ function createWindow() {// window is on screen (a STARTING gnome-shell app must not see its entry change).notifyLauncherWindowRevealed()- // #124255: the first revealed window means the GPU survived this boot.- // Keep a sticky SwiftShader marker when we launched with the fallback;- // otherwise mark the probe healthy so future launches trust hardware GL.- if (NVIDIA_DRIVER_MAJOR !== null) {- try {- writeNvidiaEglMarker(- app.getPath('userData'),- nvidiaEglMarkerAfterSuccessfulBoot({- fallbackActive: nvidiaEglFallbackActive,- appVersion: app.getVersion(),- driverVersion: NVIDIA_DRIVER_VERSION- })- )- } catch {- void 0- }- }+ nvidiaEglRecovery.healthy()// #38216/#121954: clear the mid-boot marker only after a window is// actually usable. Keep sticky `fallback` when we launched with@@ -17863,6 +17796,10 @@ app.on('open-url', (event, url) => {})app.whenReady().then(() => {+ if (NVIDIA_DRIVER_MAJOR !== null) {+ rememberLog(nvidiaEglRecovery.startupMessage)+ }+// Post-update relaunch detection (App Installer arm): when the previous// version wrote the one-shot pending-relaunch marker before quitting into// an OS package swap, consume it here — the renderer toasts "Hermes@@ -18194,6 +18131,7 @@ app.on('before-quit', event => {// (#55920).appQuitting = truequitInProgress = true+ nvidiaEglRecovery.cleanExit()minimizeToTray.beginQuit()mainProcessLagWatchdog.stop()