Skip to content

The agent that grows with you

fix(desktop): clear a stale Linux SingletonLock instead of silently exiting

Brooklyn Nicholson1177cfef4c1e
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index d7e911f298c..c63831c9527 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -204,6 +204,7 @@ import type { RosterProfileMetadata } from './connection-registry'
import { liveWindowState, overlayWindowState } from './connection-window-state'
import { describeCrashReason, installCrashForensics } from './crash-forensics'
import { adoptServedDashboardToken, resolveServedDashboardToken } from './dashboard-token'
+import { removeStaleSingletonLock } from './singleton-lock'
import { resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths'
import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'
import { formatDesktopLogLine, formatLogStamp } from './desktop-log-line'
@@ -951,9 +952,27 @@ 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.
-const isPrimaryInstance: boolean = app.requestSingleInstanceLock()
+// #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)
}
diff --git a/apps/desktop/electron/singleton-lock.test.ts b/apps/desktop/electron/singleton-lock.test.ts
new file mode 100644
index 00000000000..2ca97bfaeb5
--- /dev/null
+++ b/apps/desktop/electron/singleton-lock.test.ts
@@ -0,0 +1,88 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { test } from 'vitest'
+
+import {
+ isStaleSingletonLockOwner,
+ parseProcStateField,
+ parseSingletonLockPid,
+ removeStaleSingletonLock
+} from './singleton-lock'
+
+test('parseSingletonLockPid reads the owning PID only for this hostname', () => {
+ assert.equal(parseSingletonLockPid('myhost-4711', 'myhost'), 4711)
+ // A shared home directory can carry another machine's lock; never judge it.
+ assert.equal(parseSingletonLockPid('otherhost-4711', 'myhost'), null)
+ assert.equal(parseSingletonLockPid('myhost-4711-extra', 'myhost'), null)
+ assert.equal(parseSingletonLockPid('myhost-0', 'myhost'), null)
+ assert.equal(parseSingletonLockPid('myhost-notapid', 'myhost'), null)
+ assert.equal(parseSingletonLockPid('', 'myhost'), null)
+ assert.equal(parseSingletonLockPid(undefined, 'myhost'), null)
+})
+
+test('parseProcStateField survives a comm containing spaces and parentheses', () => {
+ const stat = '4711 (Hermes Desktop (zygote)) Z 1 1 0 0 -1 4194560'
+ assert.equal(parseProcStateField(stat), 'Z')
+ assert.equal(parseProcStateField('4711 (node) S 1 1 0 0 -1'), 'S')
+ assert.equal(parseProcStateField('no parentheses at all'), null)
+})
+
+test('a zombie or missing owner is stale; kill(pid,0) alone would say alive', () => {
+ // #78101: a defunct process still answers kill(pid, 0) until reaped, so the
+ // state field — not a signal probe — is the boundary.
+ assert.equal(isStaleSingletonLockOwner('Z'), true)
+ assert.equal(isStaleSingletonLockOwner(null), true)
+ assert.equal(isStaleSingletonLockOwner(undefined), true)
+ assert.equal(isStaleSingletonLockOwner('S'), false)
+ assert.equal(isStaleSingletonLockOwner('R'), false)
+ assert.equal(isStaleSingletonLockOwner(''), false)
+})
+
+test('removeStaleSingletonLock unlinks only a provably-dead owner', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-singleton-lock-'))
+ try {
+ const lockPath = path.join(root, 'SingletonLock')
+
+ // Live owner (state S): lock stays, nothing reported.
+ fs.symlinkSync('myhost-4711', lockPath, 'file')
+ assert.equal(
+ removeStaleSingletonLock(root, { platform: 'linux', hostname: 'myhost', readProcState: () => 'S' }),
+ null
+ )
+ assert.equal(fs.readlinkSync(lockPath), 'myhost-4711')
+
+ // Zombie owner (#78101): lock removed, PID reported.
+ assert.equal(
+ removeStaleSingletonLock(root, { platform: 'linux', hostname: 'myhost', readProcState: () => 'Z' }),
+ 4711
+ )
+ assert.equal(fs.existsSync(lockPath), false)
+
+ // Dead owner (no /proc entry): lock removed too.
+ fs.symlinkSync('myhost-4711', lockPath, 'file')
+ assert.equal(
+ removeStaleSingletonLock(root, { platform: 'linux', hostname: 'myhost', readProcState: () => null }),
+ 4711
+ )
+
+ // Another machine's lock on a shared home: never touched.
+ fs.symlinkSync('otherhost-4711', lockPath, 'file')
+ assert.equal(
+ removeStaleSingletonLock(root, { platform: 'linux', hostname: 'myhost', readProcState: () => 'Z' }),
+ null
+ )
+ assert.equal(fs.readlinkSync(lockPath), 'otherhost-4711')
+
+ // No lock at all: nothing happens.
+ fs.unlinkSync(lockPath)
+ assert.equal(
+ removeStaleSingletonLock(root, { platform: 'linux', hostname: 'myhost', readProcState: () => null }),
+ null
+ )
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/singleton-lock.ts b/apps/desktop/electron/singleton-lock.ts
new file mode 100644
index 00000000000..a1378f6c3b7
--- /dev/null
+++ b/apps/desktop/electron/singleton-lock.ts
@@ -0,0 +1,106 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+/**
+ * Parse the PID encoded in Electron's Linux SingletonLock symlink.
+ *
+ * Chromium's ProcessSingleton on Linux/X11 owns `<userData>/SingletonLock`, a
+ * symlink whose target is `<hostname>-<pid>` (#78101). The hostname prefix is
+ * the guard against removing a lock owned from a different machine on a
+ * shared home directory: a target that does not start with this host's
+ * name is not ours to judge, so it parses to null and stays in place.
+ */
+export function parseSingletonLockPid(
+ linkTarget: string | null | undefined,
+ hostname: string
+): number | null {
+ if (typeof linkTarget !== 'string' || linkTarget === '') return null
+ const prefix = `${hostname}-`
+ if (!linkTarget.startsWith(prefix)) return null
+ const tail = linkTarget.slice(prefix.length)
+ const pid = Number.parseInt(tail, 10)
+ // Reject `123junk` / `+4`-style targets: only a bare decimal PID counts.
+ if (!Number.isInteger(pid) || pid <= 0 || String(pid) !== tail) return null
+ return pid
+}
+
+/**
+ * Field 3 of `/proc/<pid>/stat` is the process state — but field 2, the comm,
+ * is parenthesized and may contain spaces AND parentheses (`(hermes (v8))`),
+ * so splitting on whitespace is wrong. The state is the first token after the
+ * final `)`. Returns null for an unparseable line.
+ */
+export function parseProcStateField(statLine: string): string | null {
+ const close = statLine.lastIndexOf(')')
+ if (close === -1) return null
+ const state = statLine
+ .slice(close + 2)
+ .split(' ')[0]
+ .trim()
+ return state === '' ? null : state
+}
+
+/**
+ * Decide whether a SingletonLock owner is stale, from its `/proc` state.
+ *
+ * `kill(pid, 0)` succeeds for a zombie (the PID exists until its parent reaps
+ * it), which is exactly the stale-owner case in #78101: Chromium's liveness
+ * probe sees the defunct owner as alive, `requestSingleInstanceLock()`
+ * returns false, and every later launch silently exits. A null state (no
+ * `/proc` entry at all) is a dead owner and equally stale.
+ */
+export function isStaleSingletonLockOwner(procState: string | null | undefined): boolean {
+ if (procState === null || procState === undefined) return true
+ return procState.trim() === 'Z'
+}
+
+/** Read `/proc/<pid>/stat`'s state field, or null when the entry is gone. */
+export function readLinuxProcState(pid: number): string | null {
+ try {
+ return parseProcStateField(fs.readFileSync(`/proc/${pid}/stat`, 'utf8'))
+ } catch {
+ return null
+ }
+}
+
+/**
+ * Remove a provably-stale SingletonLock (Linux only) and return the dead
+ * owner's PID, or null when the lock must be left alone: another machine's
+ * lock (hostname mismatch), an unparseable target, or a live-looking owner.
+ *
+ * Live-looking means `/proc/<pid>/stat` shows a state other than Z — never
+ * `kill(pid, 0)`, which reports zombies as alive.
+ */
+export function removeStaleSingletonLock(
+ userDataDir: string,
+ deps: {
+ platform?: NodeJS.Platform
+ hostname?: string
+ readProcState?: (pid: number) => string | null
+ } = {}
+): number | null {
+ if ((deps.platform ?? process.platform) !== 'linux') return null
+ const hostname = deps.hostname ?? os.hostname()
+ const readProcState = deps.readProcState ?? readLinuxProcState
+
+ let target: string
+ try {
+ target = fs.readlinkSync(path.join(userDataDir, 'SingletonLock'))
+ } catch {
+ // No lock (ENOENT), not a symlink (EINVAL), or unreadable: nothing to do.
+ return null
+ }
+
+ const pid = parseSingletonLockPid(target, hostname)
+ if (pid === null) return null
+
+ if (!isStaleSingletonLockOwner(readProcState(pid))) return null
+
+ try {
+ fs.unlinkSync(path.join(userDataDir, 'SingletonLock'))
+ } catch {
+ return null
+ }
+ return pid
+}