The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): update gate and hand-off follow owner liveness (marker v2)
Tekniuma285f6413388
diff --git a/apps/desktop/electron/desktop-installation.test.ts b/apps/desktop/electron/desktop-installation.test.tsindex 47d20265e92..6efc9e425c9 100644--- a/apps/desktop/electron/desktop-installation.test.ts+++ b/apps/desktop/electron/desktop-installation.test.ts@@ -1,6 +1,7 @@import assert from 'node:assert/strict'import fs from 'node:fs'import os from 'node:os'+import { spawnSync } from 'node:child_process'import path from 'node:path'import { test } from 'vitest'@@ -106,3 +107,21 @@ test('sshOwnershipId is stable, scoped, and does not disclose the UUID', () => {assert.ok(!global.includes(ID_A.slice(0, 8)))assert.throws(() => sshOwnershipId('bad', ''))})++// V20: a repair lock left by a crashed launch used to make every later launch+// throw at module init. It now names its holder and is reclaimed by liveness.+test('a repair lock whose holder died is reclaimed instead of bricking launch', () =>+ withTempDir(directory => {+ const filePath = path.join(directory, 'desktop-installation.json')+ // A REAL process that ran and exited: its pid now names nobody.+ const gone = spawnSync(process.execPath, ['-e', 'process.stdout.write(String(process.pid))'], { encoding: 'utf8' })+ fs.writeFileSync(`${filePath}.repair.lock`, `${gone.stdout}\n`)++ assert.equal(loadOrCreateInstallationId(filePath, () => ID_A), ID_A)+ assert.equal(fs.existsSync(`${filePath}.repair.lock`), false)++ // A pre-fix crash left an EMPTY lock (no owner to probe): reclaimed too.+ fs.rmSync(filePath)+ fs.writeFileSync(`${filePath}.repair.lock`, '')+ assert.equal(loadOrCreateInstallationId(filePath, () => ID_B), ID_B)+ }))diff --git a/apps/desktop/electron/desktop-installation.ts b/apps/desktop/electron/desktop-installation.tsindex 2a067ca96df..b1182437544 100644--- a/apps/desktop/electron/desktop-installation.ts+++ b/apps/desktop/electron/desktop-installation.ts@@ -2,6 +2,8 @@ import crypto from 'node:crypto'import fs from 'node:fs'import path from 'node:path'+import { formatCreateTime, processCreateTimeSync, processIsLiveSync } from './update-marker'+const INSTALLATION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ifunction parseInstallationId(raw) {@@ -41,6 +43,55 @@ function waitForRepair() {Atomics.wait(new Int32Array(buffer), 0, 0, 25)}+/**+ * The repair lock names its holder (`<pid>\nct:<creation time>\n`), so a lock+ * left by a crashed launch is reclaimed by owner liveness instead of making+ * every later launch throw at module init (desktop V20). An EMPTY lock is a+ * pre-fix holder (or one between create and write): reclaimed only after it+ * stayed empty for many polls, since it can name no owner to probe.+ */+const EMPTY_LOCK_RECLAIM_POLLS = 20++function repairLockBody(): string {+ const ct = processCreateTimeSync(process.pid)++ return `${process.pid}\n${ct === null ? '' : `ct:${formatCreateTime(ct)}\n`}`+}++function reclaimDeadRepairLock(repairPath: string, emptyPolls: number): boolean {+ let raw: Buffer++ try {+ raw = fs.readFileSync(repairPath)+ } catch {+ return false+ }++ const lines = raw.toString('utf8').split('\n')+ const pid = /^\d+$/.test(lines[0] || '') ? Number(lines[0]) : null+ const ctMatch = /^ct:(\d+(?:\.\d+)?)$/.exec(lines[1] || '')++ const dead =+ pid === null ? emptyPolls >= EMPTY_LOCK_RECLAIM_POLLS : !processIsLiveSync(pid, ctMatch ? Number(ctMatch[1]) : null)++ if (!dead) {+ return false+ }++ try {+ // Compare-and-delete: only the bytes judged dead.+ if (fs.readFileSync(repairPath).equals(raw)) {+ fs.unlinkSync(repairPath)++ return true+ }+ } catch {+ void 0+ }++ return false+}+function loadOrCreateInstallationId(filePath, randomUUID = crypto.randomUUID) {const existing = readInstallationId(filePath)@@ -57,6 +108,9 @@ function loadOrCreateInstallationId(filePath, randomUUID = crypto.randomUUID) {const repairPath = `${filePath}.repair.lock`+ let emptyPolls = 0+ let ownedBody: Buffer | null = null+for (let attempt = 0; attempt < 40; attempt++) {let repairFd@@ -73,12 +127,23 @@ function loadOrCreateInstallationId(filePath, randomUUID = crypto.randomUUID) {return winner}- waitForRepair()+ try {+ emptyPolls = fs.statSync(repairPath).size === 0 ? emptyPolls + 1 : 0+ } catch {+ emptyPolls = 0+ }++ if (!reclaimDeadRepairLock(repairPath, emptyPolls)) {+ waitForRepair()+ }continue}try {+ ownedBody = Buffer.from(repairLockBody(), 'utf8')+ fs.writeSync(repairFd, ownedBody)+const winner = readInstallationId(filePath)if (winner) {@@ -112,7 +177,10 @@ function loadOrCreateInstallationId(filePath, randomUUID = crypto.randomUUID) {}try {- fs.unlinkSync(repairPath)+ // Compare-and-delete: never unlink a lock a reclaimer handed to someone else.+ if (ownedBody && fs.readFileSync(repairPath).equals(ownedBody)) {+ fs.unlinkSync(repairPath)+ }} catch {void 0}diff --git a/apps/desktop/electron/handoff-result.test.ts b/apps/desktop/electron/handoff-result.test.tsindex d71a6e9ef16..ec016438c2f 100644--- a/apps/desktop/electron/handoff-result.test.ts+++ b/apps/desktop/electron/handoff-result.test.ts@@ -56,12 +56,29 @@ test('discards stale results but still consumes the file', () => {assert.equal(fs.existsSync(handoffResultPath(home)), false)})-test('malformed JSON is consumed silently', () => {+// V19: a torn/malformed result is never dropped silently — it is logged and+// kept as `.corrupt` (it used to be unlinked before parsing).+test('malformed JSON is logged and kept as .corrupt, not reported', () => {const home = tempHome()+ const logs: string[] = []write(home, '{nope')- assert.equal(readAndConsumeHandoffResult(home), null)+ assert.equal(readAndConsumeHandoffResult(home, { log: line => logs.push(line) }), null)assert.equal(fs.existsSync(handoffResultPath(home)), false)+ assert.equal(fs.readFileSync(`${handoffResultPath(home)}.corrupt`, 'utf8'), '{nope')+ assert.match(logs.join('\n'), /not valid JSON/)+})++// C2: the result carries marker line 2 as started_at; a result from another+// run is not reported as the one this boot waited on.+test('a result whose started_at differs from the parked run is discarded; a match is reported with warnings', () => {+ const home = tempHome()+ const finished_at = Math.floor(Date.now() / 1000)+ write(home, { ok: false, exit_code: 1, message: 'old run', branch: 'main', started_at: 100, finished_at })+ assert.equal(readAndConsumeHandoffResult(home, { expectedStartedAt: 200 }), null)++ write(home, { ok: true, exit_code: 0, message: '', branch: 'main', started_at: 200, finished_at, warnings: ['gateway restart'] })+ assert.deepEqual(readAndConsumeHandoffResult(home, { expectedStartedAt: 200 })?.warnings, ['gateway restart'])})test('absent file returns null', () => {diff --git a/apps/desktop/electron/handoff-result.ts b/apps/desktop/electron/handoff-result.tsindex ada072b5178..aeccb140509 100644--- a/apps/desktop/electron/handoff-result.ts+++ b/apps/desktop/electron/handoff-result.ts@@ -17,6 +17,10 @@* Dropping it as stale strands exactly the machine it exists to serve. It is* still consumed once (the file is unlinked before any age check), so it* cannot resurface on a later boot.+ *+ * Vocabulary (C2): `ok:false` ONLY when the install is still on the previous+ * version; `ok:true` + `warnings` when the update committed but follow-up work+ * failed.*/import fs from 'fs'@@ -34,15 +38,29 @@ export interface HandoffResult {manual: booleanmessage: stringbranch: string+ /** C2: `ok:true` with follow-up work that failed after the commit point. */+ warnings: string[]}export function handoffResultPath(hermesHome: string): string {return path.join(hermesHome, '.hermes-update-result.json')}+/**+ * Parse first, then consume (desktop V19): an unparseable file is renamed to+ * `.corrupt` and logged — never silently dropped — so a torn result stays+ * inspectable. `expectedStartedAt` is marker line 2 of the run this boot+ * parked on; a result carrying a different `started_at` belongs to another+ * run and is discarded with a log line instead of being reported as this one.+ */export function readAndConsumeHandoffResult(hermesHome: string,- { now = Date.now, maxAgeMs = HANDOFF_RESULT_MAX_AGE_MS }: { now?: () => number; maxAgeMs?: number } = {}+ {+ now = Date.now,+ maxAgeMs = HANDOFF_RESULT_MAX_AGE_MS,+ expectedStartedAt = null,+ log = () => {}+ }: { now?: () => number; maxAgeMs?: number; expectedStartedAt?: number | null; log?: (line: string) => void } = {}): HandoffResult | null {const file = handoffResultPath(hermesHome)let raw: string@@ -53,26 +71,43 @@ export function readAndConsumeHandoffResult(return null}- // Consume unconditionally — even a malformed/stale file must not be- // re-reported on every subsequent boot.- try {- fs.unlinkSync(file)- } catch {- // Best-effort; a locked file just gets consumed on the next boot.- }-let parsed: anytry {parsed = JSON.parse(raw)- } catch {+ } catch (error) {+ log(`[updates] hand-off result is not valid JSON (${(error as Error).message}); kept as ${path.basename(file)}.corrupt`)++ try {+ fs.renameSync(file, `${file}.corrupt`)+ } catch {+ void 0+ }+return null}+ // Consumed once parsed — a stale or foreign result must not be re-reported+ // on every later boot.+ try {+ fs.unlinkSync(file)+ } catch {+ // Best-effort; a locked file just gets consumed on the next boot.+ }+const manual = Boolean(parsed?.manual)const finishedAt = Number(parsed?.finished_at)+ const startedAt = Number(parsed?.started_at)if (!Number.isFinite(finishedAt)) {+ log('[updates] hand-off result has no finished_at; discarded')++ return null+ }++ if (expectedStartedAt !== null && Number.isFinite(startedAt) && startedAt !== expectedStartedAt) {+ log(`[updates] hand-off result is for the run started at ${startedAt}, not ${expectedStartedAt}; discarded`)+return null}@@ -88,6 +123,7 @@ export function readAndConsumeHandoffResult(exitCode: Number.isFinite(Number(parsed?.exit_code)) ? Number(parsed.exit_code) : 1,manual,message: typeof parsed?.message === 'string' ? parsed.message : '',- branch: typeof parsed?.branch === 'string' ? parsed.branch : ''+ branch: typeof parsed?.branch === 'string' ? parsed.branch : '',+ warnings: Array.isArray(parsed?.warnings) ? parsed.warnings.map(String).filter(Boolean) : []}}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 9c7dd53430f..3e672026aba 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -590,8 +590,8 @@ import {windowOpacityFor,windowOpacityOptions} from './translucency'-import { updateGateReason, waitForUpdateClearance } from './update-gate'-import { readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from './update-marker'+import { waitForUpdateClearance } from './update-gate'+import { markerPath, readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from './update-marker'import { updateConnectionsBeforeLocal } from './update-order'import {resolveUpdaterMechanism,@@ -2964,9 +2964,10 @@ function directoryExists(filePath) {// own relaunch hits our single-instance lock and quits). Marker parsing +// staleness self-heal live in update-marker.ts (unit-tested).-// How long we'll park the launch waiting for a live update to finish before-// giving up and starting the backend anyway (belt-and-suspenders alongside the-// marker's own age ceiling; covers a stuck-but-alive updater).+// How long the launch parks on an in-process update signal (in-flight /+// hand-off) before starting the backend anyway. A LIVE marker owner is waited+// out with no deadline (owner liveness, never age); past this the boot copy+// says the update is still running.const UPDATE_WAIT_TIMEOUT_MS = 20 * 60 * 1000const UPDATE_WAIT_POLL_MS = 1000// How long the desktop lingers on the "updating, don't reopen" overlay after@@ -2988,20 +2989,22 @@ const UPDATE_HANDOFF_DWELL_MS = 2500// The hand-off state closes the later Windows `cmd start` wrapper gap: the// wrapper exits 0 before the real PowerShell script claims the marker, and// `finally` clears updateInFlight immediately after the hand-off is accepted.-function updateGateDeps() {+function updateGateDeps(onLiveMarker?: (marker: { startedAt: number | null }) => void) {return {- hasLiveMarker: () => Boolean(readLiveUpdateMarker(HERMES_HOME)),- isUpdateInFlight: () => updateInFlight,- isHandoffActive: () => isQuittingForHandoff,- // The latest receipt is cross-process truth: a `hermes update` that failed- // records outcome "failed" even when its marker write/release raced a- // crash (#122206). Only a TERMINAL failure counts — "running" must keep- // parking, and "partial" kept the install usable.- hasFailedReceipt: () => {- const receipt = readLatestSyncReceipt()+ // Owner liveness (pid + creation time) only: a failed receipt never+ // outranks a live marker — `latest.json` is written at finalize, so a retry+ // after a failed update still reads "failed" while the new one runs (V2).+ hasLiveMarker: async () => {+ const marker = await readLiveUpdateMarker(HERMES_HOME)++ if (marker) {+ onLiveMarker?.(marker)+ }- return receipt?.outcome === 'failed'- }+ return Boolean(marker)+ },+ isUpdateInFlight: () => updateInFlight,+ isHandoffActive: () => isQuittingForHandoff}}@@ -3063,33 +3066,37 @@ function relaunchIntoSwappedBundle() {// rather than a frozen splash. Returns true if it parked at all.async function waitForUpdateToFinish() {let announced = false- let parkedOnFailedReceipt = false+ let longWaitAnnounced = false+ // Marker line 2 of the run this boot parked on: the result we report is that+ // run's, never an older one (C2 started_at match).+ let parkedRunStartedAt: number | null = null- const outcome = await waitForUpdateClearance(updateGateDeps(), {+ const outcome = await waitForUpdateClearance(updateGateDeps(marker => (parkedRunStartedAt = marker.startedAt)), {signal: localBackendLifecycle.signal,- abandonOn: reason => {- // The update that owns the gate already recorded a terminal failure- // (#122206): parking the full 20-minute budget on a receipt that says- // "failed" strands the window behind a dead updater (486 silent polls- // measured). Stop waiting; the failure dialog below carries the- // recovery guidance and the backend's own launch path finishes only- // what is safely retryable, bounded by venv_sync's completion-retry- // backoff.- if (reason === 'failed-receipt') {- parkedOnFailedReceipt = true- rememberLog('[updates] latest update receipt records a failure; not parking the boot on it')-- return true- }-- return false- },- onWaitTick: async reason => {+ onWaitTick: async (reason, waitedMs) => {if (!announced) {announced = truerememberLog(`[updates] update in progress (${reason}); deferring backend start until it finishes`)}+ // A live update owner is waited out, never aged out (C1 rule 3): booting+ // a backend into a half-replaced runtime is the failure this gate exists+ // for. Past the old ceiling, say so instead of silently counting down.+ if (reason === 'marker' && waitedMs >= UPDATE_WAIT_TIMEOUT_MS) {+ if (!longWaitAnnounced) {+ longWaitAnnounced = true+ rememberLog('[updates] update still running past 20 minutes; its owner is alive, so the boot keeps waiting')+ }++ await advanceBootProgress(+ 'backend.update-wait',+ 'An update is still running — Hermes will start automatically when it finishes. Its progress is in logs/update.log.',+ 12+ )++ return+ }+await advanceBootProgress('backend.update-wait','An update is finishing — Hermes will start automatically when it completes…',@@ -3107,9 +3114,22 @@ async function waitForUpdateToFinish() {// (previously a failed detached update was indistinguishable from// "nothing happened").try {- const result = readAndConsumeHandoffResult(HERMES_HOME)+ const result = readAndConsumeHandoffResult(HERMES_HOME, {+ expectedStartedAt: parkedRunStartedAt,+ log: rememberLog+ })- if (result && result.ok && result.manual) {+ if (result && result.ok && result.warnings.length && !result.manual) {+ // Committed, but follow-up work failed (C2/C3): the user IS on the new+ // version, so this is a non-blocking notice, never "previous version".+ rememberLog(`[updates] detached update finished with warnings: ${result.warnings.join(' | ')}`)+ void dialog.showMessageBox({+ type: 'info',+ title: 'Hermes update',+ message: 'Hermes updated, but some follow-up steps need another try',+ detail: `${result.warnings.join('\n')}\n\nHermes retries them on the next launch or the next update.`+ })+ } else if (result && result.ok && result.manual) {// Update landed but the user must act (reopen/reinstall/sandbox). On// machines with no shim browser and no notifier this dialog is the// FIRST time the message is visible — it must not be a log line.@@ -3164,11 +3184,6 @@ async function waitForUpdateToFinish() {if (outcome === 'timeout') {rememberLog('[updates] update still in progress after wait timeout; starting backend anyway')- } else if (parkedOnFailedReceipt) {- // The gate closed on a terminal failure, not a live update: no swap to- // relaunch into (the update never succeeded), so boot the current build- // and let the failure dialog above carry the recovery guidance.- rememberLog('[updates] proceeding with backend start despite the failed update receipt')} else if (relaunchIntoSwappedBundle()) {await advanceBootProgress('backend.update-restart', 'Restarting Hermes to load the updated app…', 14)// Park while the scheduled exit lands so this stale build never starts a@@ -4868,7 +4883,7 @@ async function handOffWindowsBootstrapRecovery(reason) {return false}- const handoffConflict = updateHandoffConflict(HERMES_HOME)+ const handoffConflict = await updateHandoffConflict(HERMES_HOME)if (handoffConflict) {// Same hazard as applyUpdates (#75778): a live foreign updater already@@ -4913,7 +4928,7 @@ async function handOffWindowsBootstrapRecovery(reason) {// exclusion: a pre-#74782 binary would refuse its own pre-written claim and// strand the very recovery meant to heal the install.if (Number.isInteger(child.pid) && stagedUpdaterSupportsPrewrittenMarker(updater)) {- writeUpdateMarker(HERMES_HOME, child.pid)+ await writeUpdateMarker(HERMES_HOME, child.pid)} else if (Number.isInteger(child.pid)) {rememberLog(`[bootstrap] skipping marker pre-write: staged updater predates self-adopt (${updater}); it would refuse its own claim`@@ -18786,7 +18801,9 @@ function resolveHermesVersion(scope: { connectionId?: string; profile?: string }const checkRendererSkew = createBundleSkewChecker(INSTALL_STAMP,(args, options) => execGit(resolveGitBinary(), args, options),- { isUpdating: () => updateGateReason(updateGateDeps()) !== null }+ // Sync and conservative: any marker file defers the skew warning; the async+ // owner-liveness verdict belongs to the boot gate.+ { isUpdating: () => updateInFlight || isQuittingForHandoff || fs.existsSync(markerPath(HERMES_HOME)) })async function detectRendererSkew() {diff --git a/apps/desktop/electron/update-gate.test.ts b/apps/desktop/electron/update-gate.test.tsindex b02f738dc56..4912629e1eb 100644--- a/apps/desktop/electron/update-gate.test.ts+++ b/apps/desktop/electron/update-gate.test.ts@@ -27,20 +27,20 @@ function deps(marker: boolean, inFlight: boolean, handoffActive = false) {// updateGateReason// ----------------------------------------------------------------------------test('gate open when neither marker nor flag is set', () => {- assert.equal(updateGateReason(deps(false, false)), null)+test('gate open when neither marker nor flag is set', async () => {+ assert.equal(await updateGateReason(deps(false, false)), null)})-test('marker alone closes the gate', () => {- assert.equal(updateGateReason(deps(true, false)), 'marker')+test('marker alone closes the gate', async () => {+ assert.equal(await updateGateReason(deps(true, false)), 'marker')})-test('updateInFlight alone closes the gate (#73822 — the pre-marker window)', () => {- assert.equal(updateGateReason(deps(false, true)), 'update-in-flight')+test('updateInFlight alone closes the gate (#73822 — the pre-marker window)', async () => {+ assert.equal(await updateGateReason(deps(false, true)), 'update-in-flight')})-test('marker wins as the reported reason when both are set', () => {- assert.equal(updateGateReason(deps(true, true)), 'marker')+test('marker wins as the reported reason when both are set', async () => {+ assert.equal(await updateGateReason(deps(true, true)), 'marker')})test('handoff remains closed after the detached wrapper exits', async () => {@@ -157,10 +157,10 @@ test('parks across the flag→marker handoff without a gap', async () => {assert.deepEqual(reasons, ['update-in-flight', 'update-in-flight', 'marker', 'marker', 'marker'])})-test('returns timeout when the gate never opens', async () => {+test('an in-process signal times out when it never clears', async () => {let clock = 0- const outcome = await waitForUpdateClearance(deps(true, false), {+ const outcome = await waitForUpdateClearance(deps(false, true), {now: () => clock,pollMs: 10,sleep: async ms => {@@ -172,98 +172,41 @@ test('returns timeout when the gate never opens', async () => {assert.equal(outcome, 'timeout')})-// ----------------------------------------------------------------------------// failed-receipt signal (#122206)-// -----------------------------------------------------------------------------test('a failed receipt outranks a live marker as the reported reason', () => {- assert.equal(updateGateReason({ ...deps(true, false), hasFailedReceipt: () => true }), 'failed-receipt')-})--test('a failed receipt without a live marker keeps the gate open', () => {- // The receipt only RECLASSIFIES a closed gate; it must not close an open- // one — a failed update from last week must not defer any boot.- assert.equal(updateGateReason({ ...deps(false, false), hasFailedReceipt: () => true }), null)-})--test('a running or partial receipt keeps the marker reason', () => {- // Only a TERMINAL failure is actionable: "running" must keep parking.- assert.equal(updateGateReason({ ...deps(true, false), hasFailedReceipt: () => false }), 'marker')-})--test('abandonOn returns abandoned instead of parking on a failed receipt', async () => {- let slept = 0-- const outcome = await waitForUpdateClearance(- { ...deps(true, false), hasFailedReceipt: () => true },- {- abandonOn: reason => reason === 'failed-receipt',- pollMs: 10,- sleep: async () => {- slept += 1- },- timeoutMs: 10_000- }- )-- assert.equal(outcome, 'abandoned')- assert.equal(slept, 0)-})--test('a mid-wait receipt finalization abandons the park', async () => {- // The gate closed on a live marker (update running); the update then fails- // and finalizes its receipt while we are parked. The wait must abandon on- // the next poll instead of counting down to the 20-minute deadline.- let failedReceipt = false- let polls = 0-- const outcome = await waitForUpdateClearance(- { ...deps(true, false), hasFailedReceipt: () => failedReceipt },- {- abandonOn: reason => reason === 'failed-receipt',- onWaitTick: () => {- polls += 1-- if (polls === 3) {- failedReceipt = true- }- },- pollMs: 1,- sleep: async () => {},- timeoutMs: 10_000- }- )-- assert.equal(outcome, 'abandoned')- assert.equal(polls, 3)-})--test('abandonOn declining keeps the historical parking', async () => {- let ticks = 0+// A live marker owner is waited out, never aged out (C1 rule 3, desktop V3):+// the old 20-minute deadline booted a backend into a half-replaced runtime.+test('a live marker keeps parking past the deadline until its owner finishes', async () => {+ let clock = 0let marker = true+ let ticks = 0const outcome = await waitForUpdateClearance(+ { hasLiveMarker: async () => marker, isUpdateInFlight: () => false, isHandoffActive: () => false },{- hasLiveMarker: () => marker,- isUpdateInFlight: () => false,- isHandoffActive: () => false,- hasFailedReceipt: () => true- },- {- abandonOn: () => false,+ now: () => clock,onWaitTick: () => {ticks += 1- if (ticks === 2) {+ if (ticks === 50) {marker = false}},- pollMs: 1,- sleep: async () => {},- timeoutMs: 10_000+ pollMs: 10,+ sleep: async ms => {+ clock += ms+ },+ timeoutMs: 50})assert.equal(outcome, 'finished')- assert.equal(ticks, 2)+ assert.equal(ticks, 50, 'parked ten times past the deadline')+})++// A failed receipt never outranks a live marker (desktop V2): latest.json is+// written only at finalize, so a retry after a failed update still reads+// "failed" while the new update runs.+test('a failed receipt does not open the gate while a live marker exists', async () => {+ const withFailedReceipt = { ...deps(true, false), hasFailedReceipt: () => true }++ assert.equal(await updateGateReason(withFailedReceipt), 'marker')})diff --git a/apps/desktop/electron/update-gate.ts b/apps/desktop/electron/update-gate.tsindex a8db9719b92..3b1563787e3 100644--- a/apps/desktop/electron/update-gate.ts+++ b/apps/desktop/electron/update-gate.ts@@ -8,7 +8,7 @@ import { runBackendStartStep } from './backend-start-cancellation'* Pure, dependency-injected gate that parks local backend spawns while an* in-app update is running (#73822, #50238).*- * Four independent signals mean "an update owns the local runtime right now":+ * Three independent signals mean "an update owns the local runtime right now":** - the on-disk marker (`HERMES_HOME/.hermes-update-in-progress`), written* by the updater — and by the desktop itself just before hand-off — and@@ -25,46 +25,28 @@ import { runBackendStartStep } from './backend-start-cancellation'* `finally`, so there is no instant where both signals are false and a* waiter could slip through mid-update.*- * The fourth signal is different in kind: `failedReceipt` names a FINISHED,- * failed update. A failed `hermes update` releases the marker in its `finally`- * only when the failure happened after the lock was claimed; preparation-stage- * failures (uv sync network errors) can exit with the marker left pointing at- * a dead or recycled pid while `readLiveUpdateMarker`'s liveness probe keeps- * answering true on Windows, and even a cleanly released marker leaves the- * boot nothing to wait for. Parking the full 20-minute budget on a receipt- * that already says `failed` strands the window (#122206: 486 polls /- * 20 minutes after a receipt-marked failure). The gate reports it separately- * so the boot path can surface the terminal failure instead of silently- * counting down.+ * A finished, failed update (`logs/update_receipts/latest.json` says `failed`)+ * never outranks a live marker: `latest.json` is written only at finalize, so a+ * retry after a failed update still reads `failed` while the new update runs+ * (desktop V2). The marker's owner liveness (pid + creation time, see+ * update-marker.ts) is the only signal for "an update is running"; a crashed+ * updater's marker reads dead and opens the gate by itself.*/-export type UpdateGateReason = 'marker' | 'update-in-flight' | 'handoff' | 'failed-receipt' | null+export type UpdateGateReason = 'marker' | 'update-in-flight' | 'handoff' | nullexport interface UpdateGateDeps {/** True when a live on-disk update marker exists (see update-marker.ts). */- hasLiveMarker: () => boolean+ hasLiveMarker: () => boolean | Promise<boolean>/** True while this process is inside applyUpdates()' critical section. */isUpdateInFlight: () => boolean/** True after a detached updater hand-off is viable and this Desktop will quit. */isHandoffActive: () => boolean- /**- * True when the latest update receipt records a terminal failure (see- * main.ts readLatestSyncReceipt). Optional: older callers (and the pool- * spawn path, which is not user-visible) may omit it, in which case a- * live marker keeps the historical parking behavior.- */- hasFailedReceipt?: () => boolean}/** Why the gate is closed right now, or null when it is open. */-export function updateGateReason(deps: UpdateGateDeps): UpdateGateReason {- if (deps.hasLiveMarker()) {- // A failed receipt with a live marker is still the marker's wait — but the- // receipt is what the boot path needs to know about, so it wins here.- if (deps.hasFailedReceipt?.()) {- return 'failed-receipt'- }-+export async function updateGateReason(deps: UpdateGateDeps): Promise<UpdateGateReason> {+ if (await deps.hasLiveMarker()) {return 'marker'}@@ -79,7 +61,7 @@ export function updateGateReason(deps: UpdateGateDeps): UpdateGateReason {return null}-export type UpdateClearanceOutcome = 'clear' | 'finished' | 'timeout' | 'cancelled' | 'abandoned'+export type UpdateClearanceOutcome = 'clear' | 'finished' | 'timeout' | 'cancelled'export interface WaitForUpdateClearanceOptions {signal?: AbortSignal@@ -87,27 +69,20 @@ export interface WaitForUpdateClearanceOptions {timeoutMs: numberpollMs: number/** Invoked once per poll while parked (boot progress / logging). */- onWaitTick?: (reason: Exclude<UpdateGateReason, null>) => void | Promise<void>- /**- * Consulted whenever the gate is closed. Returning true makes the wait- * return 'abandoned' immediately instead of parking. The primary boot path- * uses this for the terminal failed-receipt signal (#122206): a receipt- * that already says "failed" must not consume the parking budget.- */- abandonOn?: (reason: Exclude<UpdateGateReason, null>) => boolean+ onWaitTick?: (reason: Exclude<UpdateGateReason, null>, waitedMs: number) => void | Promise<void>now?: () => numbersleep?: (ms: number) => Promise<void>}/**- * Park until no update signal remains, or the deadline passes.+ * Park until no update signal remains.** Returns 'clear' when the gate was already open (no wait happened),- * 'finished' when it opened during the wait, 'abandoned' when `abandonOn`- * accepted the closed-gate reason, and 'timeout' when the deadline- * expired with the gate still closed (callers proceed anyway — matching the- * long-standing marker-gate behavior, since a wedged updater must not brick- * the app forever).+ * 'finished' when it opened during the wait, and 'timeout' when the deadline+ * expired with an in-process signal (in-flight / hand-off) still set. A LIVE+ * marker owner has no deadline: owner liveness, never age, decides when an+ * update is over (C1 rule 3) — booting into a half-replaced runtime at minute+ * 21 of a slow Windows update is exactly the failure the gate exists for.*/export async function waitForUpdateClearance(deps: UpdateGateDeps,@@ -122,19 +97,16 @@ export async function waitForUpdateClearance(return 'cancelled'}- let reason = updateGateReason(deps)+ let reason = await updateGateReason(deps)if (!reason) {return 'clear'}- if (options.abandonOn?.(reason)) {- return 'abandoned'- }-- const deadline = now() + options.timeoutMs+ const startedAt = now()+ const deadline = startedAt + options.timeoutMs- while (reason && now() < deadline) {+ while (reason && (reason === 'marker' || now() < deadline)) {if (isCancelled()) {return 'cancelled'}@@ -143,7 +115,8 @@ export async function waitForUpdateClearance(try {if (options.onWaitTick) {- await runBackendStartStep(options.signal, () => options.onWaitTick!(reason!))+ const tickReason = reason+ await runBackendStartStep(options.signal, () => options.onWaitTick!(tickReason, now() - startedAt))}if (isCancelled()) {@@ -171,11 +144,7 @@ export async function waitForUpdateClearance(return 'cancelled'}- reason = updateGateReason(deps)-- if (reason && options.abandonOn?.(reason)) {- return 'abandoned'- }+ reason = await updateGateReason(deps)}return reason ? 'timeout' : 'finished'diff --git a/apps/desktop/electron/update-marker.test.ts b/apps/desktop/electron/update-marker.test.tsindex a470de58376..a53bcac78b5 100644--- a/apps/desktop/electron/update-marker.test.ts+++ b/apps/desktop/electron/update-marker.test.ts@@ -1,243 +1,262 @@/**- * Tests for electron/update-marker.ts — the in-app update mutual-exclusion- * marker that prevents a desktop relaunched mid-update from spawning a backend- * the updater then kills in a loop (#50238).+ * Tests for electron/update-marker.ts — the update marker (contract C1, v2)+ * that keeps a Desktop reopened mid-update from booting a backend onto the+ * runtime being replaced, and keeps two updaters off one checkout.*- * Run with: node --test electron/update-marker.test.ts- * (Wired into npm test:desktop:platforms in package.json.)- *- * Why this matters: the gate must (a) report a live update only when the- * updater pid is alive AND the marker is fresh, (b) treat absent/malformed/- * dead-pid/expired markers as "no live update" so a crashed updater can't- * strand future launches, and (c) self-heal by deleting a stale marker file.+ * The liveness cells use REAL processes: a sleeping node child as the owner,+ * its real creation time (or a deliberately wrong one for pid reuse), and a+ * real child that takes the marker over for the hand-off cells.*/import fs from 'fs'import assert from 'node:assert/strict'+import { type ChildProcess, spawn } from 'node:child_process'import os from 'os'import path from 'path'-import { test } from 'vitest'+import { afterEach, test } from 'vitest'import {+ claimBridgeMarker,+ compareAndDeleteMarker,+ formatCreateTime,isPidAlive,markerPath,+ parseUpdateMarker,posixProcessState,+ processCreateTime,readLiveUpdateMarker,UPDATE_MARKER_MAX_AGE_MS,updateHandoffConflict,+ waitForHandoffClaim,writeUpdateMarker} from './update-marker'-function tmpHome(tag) {+const homes: string[] = []+const children: ChildProcess[] = []++afterEach(() => {+ for (const child of children.splice(0)) {+ child.kill('SIGKILL')+ }++ for (const home of homes.splice(0)) {+ fs.rmSync(home, { recursive: true, force: true })+ }+})++function tmpHome(tag: string) {const dir = fs.mkdtempSync(path.join(os.tmpdir(), `hermes-marker-${tag}-`))+ homes.push(dir)return dir}-function writeMarker(home, pid, startedAtSec) {- fs.writeFileSync(markerPath(home), `${pid}\n${startedAtSec}`)+/** A real, live owner process (sleeps until killed). */+async function liveOwner(): Promise<ChildProcess & { pid: number }> {+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })+ children.push(child)+ await new Promise(resolve => child.once('spawn', resolve))++ return child as ChildProcess & { pid: number }}-const ALIVE: typeof process.kill = () => true // injected kill that "succeeds" => pid alive+/** A pid that existed and is now gone (reaped). */+async function deadPid(): Promise<number> {+ const child = spawn(process.execPath, ['-e', ''], { stdio: 'ignore' })+ await new Promise(resolve => child.once('exit', resolve))-const DEAD: typeof process.kill = () => {- const err = new Error('no such process')+ return child.pid as number+}- ;(err as any).code = 'ESRCH'- throw err+function minutesAgo(minutes: number) {+ return Math.floor(Date.now() / 1000) - minutes * 60}-test('absent marker => no live update', () => {- const home = tmpHome('absent')- assert.equal(readLiveUpdateMarker(home, { kill: ALIVE }), null)-})+const HAS_CT_PROBE = process.platform === 'linux' || process.platform === 'darwin' || process.platform === 'win32'-test('live pid within age ceiling => live update reported', () => {- const home = tmpHome('live')- const now = 1_000_000_000_000- writeMarker(home, 4242, Math.floor(now / 1000) - 5) // 5s old- const res = readLiveUpdateMarker(home, { kill: ALIVE, now: () => now })- assert.ok(res, 'a fresh, alive marker is a live update')- assert.equal(res.pid, 4242)- assert.ok(res.ageMs >= 0 && res.ageMs < 10_000)- assert.ok(fs.existsSync(markerPath(home)), 'a live marker is NOT deleted')-})+// ---------------------------------------------------------------------------+// Parse+// ----------------------------------------------------------------------------test('dead pid => no live update and marker is pruned', () => {- const home = tmpHome('dead')- writeMarker(home, 999999, Math.floor(Date.now() / 1000))- assert.equal(readLiveUpdateMarker(home, { kill: DEAD }), null)- assert.ok(!fs.existsSync(markerPath(home)), 'a dead-pid marker self-heals (deleted)')+test('parses v1, v2 and the delegate line; garbage is null', () => {+ assert.deepEqual(parseUpdateMarker('42\n100\n'), { pid: 42, startedAt: 100, ct: null, delegate: null })+ assert.deepEqual(parseUpdateMarker('42\n100\nct:1700000000.125\ndelegate:77 ct:1700000001.500\n'), {+ pid: 42,+ startedAt: 100,+ ct: 1700000000.125,+ delegate: { pid: 77, ct: 1700000001.5 }+ })+ assert.equal(parseUpdateMarker('not-a-pid\nnonsense'), null)})-test('zombie pid => no live update and marker is pruned', () => {- // The kill(pid, 0) false positive: a process that exited but is still in the- // table (parent has not reaped it) answers signal 0 like a live one. The- // state probe must turn that into "dead" so the boot gate self-heals in- // seconds instead of parking for the whole 20-minute ceiling.- const home = tmpHome('zombie')- const now = 1_000_000_000_000- writeMarker(home, 4242, Math.floor(now / 1000) - 5)- const res = readLiveUpdateMarker(home, { kill: ALIVE, now: () => now, processState: () => 'Z' })- assert.equal(res, null, 'a zombie owner is not a live update')- assert.ok(!fs.existsSync(markerPath(home)), 'a zombie-owned marker self-heals (deleted)')-})+// ---------------------------------------------------------------------------+// Liveness against REAL processes (C1 rule 3, desktop V3/V22)+// ----------------------------------------------------------------------------test('a live state keeps the marker (probe answers non-Z)', () => {- const home = tmpHome('state-live')- const now = 1_000_000_000_000- writeMarker(home, 4242, Math.floor(now / 1000) - 5)- const res = readLiveUpdateMarker(home, { kill: ALIVE, now: () => now, processState: () => 'S' })- assert.ok(res, 'an alive, non-zombie owner keeps the gate closed')- assert.ok(fs.existsSync(markerPath(home)), 'a live marker is NOT deleted')-})+test.skipIf(!HAS_CT_PROBE)('a LIVE v2 owner past 20 minutes stays live and is NOT deleted (V3)', async () => {+ const home = tmpHome('v2-old-live')+ const owner = await liveOwner()+ const ct = await processCreateTime(owner.pid)+ assert.ok(ct, 'the real owner has a probeable creation time')+ fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(25)}\nct:${formatCreateTime(ct!)}\n`)++ const live = await readLiveUpdateMarker(home)-test('an unknown process state fails open to alive (keeps the marker)', () => {- const home = tmpHome('state-unknown')- const now = 1_000_000_000_000- writeMarker(home, 4242, Math.floor(now / 1000) - 5)- const res = readLiveUpdateMarker(home, { kill: ALIVE, now: () => now, processState: () => null })- assert.ok(res, 'probe failure must keep the conservative signal-0 verdict')- assert.ok(fs.existsSync(markerPath(home)))+ assert.ok(live, 'a 25-minute-old update whose owner is alive is still running')+ assert.equal(live!.pid, owner.pid)+ assert.ok(fs.existsSync(markerPath(home)), 'a live owner is never aged out')})-test('expired marker (past age ceiling) => no live update and pruned', () => {- const home = tmpHome('expired')- const now = 1_000_000_000_000- writeMarker(home, 4242, Math.floor((now - UPDATE_MARKER_MAX_AGE_MS - 60_000) / 1000))- // Even though the pid is "alive", the marker is too old to trust.- assert.equal(readLiveUpdateMarker(home, { kill: ALIVE, now: () => now }), null)- assert.ok(!fs.existsSync(markerPath(home)), 'an expired marker self-heals (deleted)')+test.skipIf(!HAS_CT_PROBE)('a reused pid (creation time mismatch) is dead and compare-deleted (V22)', async () => {+ const home = tmpHome('v2-reused')+ const owner = await liveOwner()+ const ct = await processCreateTime(owner.pid)+ // The marker names the pid the live process now holds, but a creation time+ // an hour earlier: the original owner died and the OS recycled its pid.+ fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(2)}\nct:${formatCreateTime(ct! - 3600)}\n`)++ assert.equal(await readLiveUpdateMarker(home), null)+ assert.ok(!fs.existsSync(markerPath(home)), 'a reused-pid marker self-heals')})-test('malformed marker => no live update and pruned', () => {- const home = tmpHome('malformed')- fs.writeFileSync(markerPath(home), 'not-a-pid\nnonsense')- assert.equal(readLiveUpdateMarker(home, { kill: ALIVE }), null)+test('a v1 marker (no creation time) keeps the legacy 20-minute ceiling', async () => {+ const home = tmpHome('v1-old')+ const owner = await liveOwner()+ fs.writeFileSync(markerPath(home), `${owner.pid}\n${Math.floor((Date.now() - UPDATE_MARKER_MAX_AGE_MS) / 1000) - 60}\n`)++ assert.equal(await readLiveUpdateMarker(home), null, 'v1 pid reuse must still self-heal')assert.ok(!fs.existsSync(markerPath(home)))})-test('isPidAlive: own pid is alive, impossible pid is dead', () => {- assert.equal(isPidAlive(process.pid), true)- assert.equal(isPidAlive(-1), false)- assert.equal(isPidAlive(0), false)- assert.equal(isPidAlive(NaN), false)+test('a dead owner with a LIVE delegate keeps the marker live (C1 rule 6)', async () => {+ const home = tmpHome('delegate')+ const gone = await deadPid()+ const delegate = await liveOwner()+ const delegateCt = await processCreateTime(delegate.pid)+ const ctPart = delegateCt === null ? '' : ` ct:${formatCreateTime(delegateCt)}`+ fs.writeFileSync(markerPath(home), `${gone}\n${minutesAgo(1)}\nct:1.000\ndelegate:${delegate.pid}${ctPart}\n`)++ const live = await readLiveUpdateMarker(home)++ assert.ok(live, 'a killed hand-off script must not hide a still-running hermes update')+ assert.equal(live!.pid, delegate.pid)+ delegate.kill('SIGKILL')+ await new Promise(resolve => delegate.once('exit', resolve))+ assert.equal(await readLiveUpdateMarker(home), null, 'both gone => dead')})-test('isPidAlive: EPERM counts as alive (process owned by another user)', () => {- const eperm = () => {- const err = new Error('operation not permitted')+test('dead pid / zombie => no live update; unknown state fails open', async () => {+ const home = tmpHome('dead')+ fs.writeFileSync(markerPath(home), `${await deadPid()}\n${minutesAgo(0)}\n`)+ assert.equal(await readLiveUpdateMarker(home), null)+ assert.ok(!fs.existsSync(markerPath(home)))- ;(err as any).code = 'EPERM'- throw err- }+ fs.writeFileSync(markerPath(home), `4242\n${minutesAgo(0)}\n`)+ assert.equal(await readLiveUpdateMarker(home, { kill: () => true, processState: () => 'Z' }), null)- assert.equal(isPidAlive(4242, eperm), true)+ fs.writeFileSync(markerPath(home), `4242\n${minutesAgo(0)}\n`)+ assert.ok(await readLiveUpdateMarker(home, { kill: () => true, processState: () => null }))})-test('posixProcessState: own pid is probeable and not a zombie; dead pid is unknown', () => {- if (process.platform === 'win32') {- // Windows has no zombie state and no ps stat lane; the probe is a no-op.- assert.equal(posixProcessState(process.pid), null)+test('compare-and-delete never removes a claim written after the dead verdict (C1 rule 5)', () => {+ const home = tmpHome('cas')+ fs.writeFileSync(markerPath(home), '999999\n1\n')+ const judgedDead = fs.readFileSync(markerPath(home))+ fs.writeFileSync(markerPath(home), `${process.pid}\n2\nct:3.000\n`)- return- }-- const own = posixProcessState(process.pid)- assert.ok(own, 'a live pid must be probeable on linux/darwin')- assert.ok(!own.toUpperCase().startsWith('Z'), 'this process is not a zombie')-- // A pid nothing owns (and that kill(0) would reject) is simply unknowable —- // callers keep their signal-0 verdict in that case.- assert.equal(posixProcessState(2147483647), null)+ assert.equal(compareAndDeleteMarker(home, judgedDead), false)+ assert.ok(fs.existsSync(markerPath(home)), 'the newer claim survives')})-test('writeUpdateMarker writes a marker that readLiveUpdateMarker accepts', () => {- const home = tmpHome('write')- const now = 1_000_000_000_000- writeUpdateMarker(home, 4242, { now: () => now })- // The marker should be readable and report the same pid.- const res = readLiveUpdateMarker(home, { kill: ALIVE, now: () => now })- assert.ok(res, 'marker written by writeUpdateMarker should be detected as live')- assert.equal(res.pid, 4242)- assert.ok(fs.existsSync(markerPath(home)), 'marker file should exist after write')+test('isPidAlive / posixProcessState basics', () => {+ assert.equal(isPidAlive(process.pid), true)+ assert.equal(isPidAlive(-1), false)+ assert.equal(+ isPidAlive(4242, () => {+ throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' })+ }),+ true+ )++ if (process.platform !== 'win32') {+ assert.ok(!String(posixProcessState(process.pid)).toUpperCase().startsWith('Z'))+ assert.equal(posixProcessState(2147483647), null)+ }})-test('writeUpdateMarker preserves a live holder age across pid hand-off', () => {- const home = tmpHome('write-handoff-age')- const now = 1_000_000_000_000- const startedAt = Math.floor(now / 1000) - 300+// ---------------------------------------------------------------------------+// Writers (C1 rule 4, C2 bridge)+// ---------------------------------------------------------------------------++test('the bridge marker names THIS process with its creation time (V4)', async () => {+ const home = tmpHome('bridge')+ const claim = await claimBridgeMarker(home, { startedAt: 1234 })- writeMarker(home, 1010, startedAt)- writeUpdateMarker(home, 2020, { kill: ALIVE, now: () => now })+ assert.ok(claim.ok)+ const marker = parseUpdateMarker(fs.readFileSync(markerPath(home), 'utf8'))!+ assert.equal(marker.pid, process.pid)+ assert.equal(marker.startedAt, 1234)++ if (HAS_CT_PROBE) {+ assert.ok(marker.ct !== null && Math.abs(marker.ct - (await processCreateTime(process.pid))!) <= 2)+ }- const [pidLine, startedLine] = fs.readFileSync(markerPath(home), 'utf8').split('\n')- assert.equal(Number.parseInt(pidLine, 10), 2020, 'the hand-off records the new owner')- assert.equal(Number.parseInt(startedLine, 10), startedAt, 'the holder age must not restart during hand-off')+ assert.ok(await readLiveUpdateMarker(home), 'our own bridge claim reads live')})-test('writeUpdateMarker uses the acquisition time passed to a detached script', () => {- const home = tmpHome('write-script-acquired-at')- const now = 1_000_000_000_000- const startedAt = Math.floor(now / 1000) - 300+test('the bridge claim refuses a LIVE foreign owner and reclaims a dead one', async () => {+ const home = tmpHome('bridge-conflict')+ const owner = await liveOwner()+ fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(30)}\nct:${formatCreateTime((await processCreateTime(owner.pid)) ?? 0)}\n`)- writeUpdateMarker(home, 2020, { now: () => now, startedAt })+ const refused = await claimBridgeMarker(home, { startedAt: 1 })+ assert.equal(refused.ok, false)+ assert.equal(!refused.ok && refused.conflict?.pid, owner.pid)+ assert.match(String(!refused.ok && refused.conflict?.message), /already running/)+ assert.equal(parseUpdateMarker(fs.readFileSync(markerPath(home), 'utf8'))!.pid, owner.pid, 'never overwritten')- const [, startedLine] = fs.readFileSync(markerPath(home), 'utf8').split('\n')- assert.equal(Number.parseInt(startedLine, 10), startedAt)+ fs.writeFileSync(markerPath(home), `${await deadPid()}\n${minutesAgo(1)}\n`)+ assert.ok((await claimBridgeMarker(home, { startedAt: 2 })).ok, 'a dead claim is reclaimed')})-test('writeUpdateMarker is best-effort (no throw on bad path)', () => {- // A non-existent directory should not throw.- const badHome = path.join(os.tmpdir(), 'hermes-marker-nonexistent-' + Date.now())- assert.doesNotThrow(() => writeUpdateMarker(badHome, 4242))-})+test('writeUpdateMarker (staged updater) never overwrites a live claim', async () => {+ const home = tmpHome('write-live')+ const owner = await liveOwner()+ fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(1)}\n`)++ await writeUpdateMarker(home, 2020)-test('writeUpdateMarker + dead pid => self-heals on read', () => {- const home = tmpHome('write-dead')- writeUpdateMarker(home, 999999, { now: () => Date.now() })- // PID 999999 is almost certainly not alive.- const res = readLiveUpdateMarker(home, { kill: DEAD })- assert.equal(res, null, 'a dead-pid marker from writeUpdateMarker self-heals')- assert.ok(!fs.existsSync(markerPath(home)), 'marker file is pruned')+ assert.equal(parseUpdateMarker(fs.readFileSync(markerPath(home), 'utf8'))!.pid, owner.pid)+ assert.ok(await updateHandoffConflict(home), 'the live owner still blocks a new hand-off')})// ----------------------------------------------------------------------------// updateHandoffConflict (#75778)-//-// A retried "Update" click must not spawn a second updater over a still-live-// one — writeUpdateMarker unconditionally overwrites the marker, so an-// unchecked hand-off clobbers the original updater's claim while it is still-// alive and mutating the checkout.+// Hand-off confirmation (C2, desktop V7)// ----------------------------------------------------------------------------test('no marker => hand-off is not blocked', () => {- const home = tmpHome('conflict-none')- assert.equal(updateHandoffConflict(home, { kill: ALIVE }), null)+test('the hand-off counts as started only when a real script process takes the marker', async () => {+ const home = tmpHome('handoff-taken')+ await claimBridgeMarker(home, { startedAt: 5 })+ const file = markerPath(home)+ // A real "script": waits, then claims the marker in its own name.+ const script = spawn(+ process.execPath,+ ['-e', `setTimeout(() => { require('fs').writeFileSync(${JSON.stringify(file)}, process.pid + '\\n5\\n'); setInterval(() => {}, 1000) }, 300)`],+ { stdio: 'ignore' }+ )+ children.push(script)++ const taken = await waitForHandoffClaim(home, process.pid, { timeoutMs: 10_000, pollMs: 50 })++ assert.deepEqual(taken, { taken: true, pid: script.pid })})-test('a different live updater already owns the marker => hand-off is blocked', () => {- const home = tmpHome('conflict-live')- const now = 1_000_000_000_000- writeMarker(home, 1010, Math.floor(now / 1000) - 6) // 6s old- const conflict = updateHandoffConflict(home, { kill: ALIVE, now: () => now })- assert.ok(conflict, 'a live foreign updater must block a new hand-off')- assert.equal(conflict.pid, 1010)- assert.match(conflict.message, /already running/)- assert.match(conflict.message, /PID 1010/)- assert.match(conflict.message, /6s/)-})--test('a dead-pid marker does not block a hand-off (self-heals)', () => {- const home = tmpHome('conflict-dead')- writeMarker(home, 999999, Math.floor(Date.now() / 1000))- assert.equal(updateHandoffConflict(home, { kill: DEAD }), null)-})+test('a wrapper that exits 0 without the script ever claiming is NOT a hand-off', async () => {+ const home = tmpHome('handoff-never')+ await claimBridgeMarker(home, { startedAt: 5 })+ const wrapper = spawn(process.execPath, ['-e', 'process.exit(0)'], { stdio: 'ignore' })+ await new Promise(resolve => wrapper.once('exit', resolve))-test('an expired marker does not block a hand-off (self-heals)', () => {- const home = tmpHome('conflict-expired')- const now = 1_000_000_000_000- writeMarker(home, 1010, Math.floor((now - UPDATE_MARKER_MAX_AGE_MS - 60_000) / 1000))- assert.equal(updateHandoffConflict(home, { kill: ALIVE, now: () => now }), null)+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { timeoutMs: 400, pollMs: 50 }), { taken: false })})diff --git a/apps/desktop/electron/update-marker.ts b/apps/desktop/electron/update-marker.tsindex 11ab809c656..0195a82a545 100644--- a/apps/desktop/electron/update-marker.ts+++ b/apps/desktop/electron/update-marker.ts@@ -1,49 +1,54 @@/**- * In-app update mutual-exclusion marker (#50238).+ * The update marker `HERMES_HOME/.hermes-update-in-progress` (#50238), format v2.*- * The Tauri updater writes HERMES_HOME/.hermes-update-in-progress for the whole- * duration of an `--update` run (see apps/bootstrap-installer/src-tauri/src/- * update.rs `UpdateMarkerGuard`). The marker body is two lines: the updater's- * pid and the unix-seconds it started.+ * One file, shared by every updater (Python `hermes_cli/update_lock.py`, the Rust+ * `UpdateMarkerGuard`, `scripts/desktop-update/{windows.ps1,posix.sh}`) and this+ * Desktop. While it names a LIVE owner, a Desktop reopened mid-update must not+ * spawn a backend on the runtime being replaced, and no second update may start.*- * Why: if the user relaunches the desktop mid-update — the window vanished with- * no progress and looks crashed — a fresh instance must NOT spawn its own local- * backend. That backend re-locks the venv shim, the updater's straggler cleanup- * (`force_kill_other_hermes`, taskkill /IM hermes.exe) kills it, the launch- * fails with the 45s "backend didn't come up" timeout, and the user relaunches- * into the same trap — an infinite respawn/kill loop. The desktop gates local- * backend startup on this marker and parks until the update finishes.+ * Body (UTF-8, `\n` line ends):*- * This module holds the PURE, side-effect-light logic (path, pid liveness,- * parse + staleness) so it is unit-testable without booting Electron. The- * polling/boot-progress wrapper lives in main.ts where the boot-progress and- * log sinks are.+ * <pid>+ * <started_at unix seconds>+ * ct:<owner creation time, unix seconds, 3 decimals> (absent in v1 writers)+ * delegate:<pid> ct:<creation time> (optional, see below)+ *+ * Liveness: the owner is LIVE iff its pid is alive (not a zombie) and its+ * creation time matches the recorded one within 2 s (an unprobeable creation+ * time counts as live). A LIVE v2 owner stays live regardless of age: a Windows+ * update is routinely 25-40 minutes. Only a v1 marker (no `ct:` line) keeps the+ * legacy 20-minute ceiling, since without a creation time it is the only thing+ * that tells a reused pid from the original owner. The marker is LIVE when the+ * owner OR the delegate (`hermes update` running under a hand-off script's+ * claim) is live, so a killed script cannot hide a still-mutating update.+ *+ * Deletes are compare-and-delete: re-read the bytes and unlink only when they+ * still equal the bytes judged dead (or the bytes we wrote). A verdict from an+ * earlier read never unlinks a newer claim.*/import fs from 'fs'-import { execFileSync } from 'node:child_process'+import { execFile, execFileSync } from 'node:child_process'import path from 'path'-// Even with a live-looking PID, never treat a marker older than this as a live-// update. A full update (git pull + pip + desktop rebuild) is minutes, not tens-// of minutes; past this the marker is almost certainly stale (e.g. the OS-// recycled the pid onto an unrelated process), so the gate self-heals.+/** Legacy ceiling, applied ONLY to v1 markers (no creation time recorded). */export const UPDATE_MARKER_MAX_AGE_MS = 20 * 60 * 1000-export function markerPath(hermesHome) {+/** |recorded - actual| creation-time slack, in seconds (C1 rule 3). */+export const CREATE_TIME_TOLERANCE_S = 2.0++/** How long a hand-off script has to take the bridge marker (C2). */+export const HANDOFF_CLAIM_TIMEOUT_MS = 20_000++export function markerPath(hermesHome: string) {return path.join(hermesHome, '.hermes-update-in-progress')}// True only if a host process with this pid is currently alive. Signal 0 does// not deliver a signal — it just probes existence/permission. ESRCH => dead;// EPERM => alive but owned by another user (still "alive" for our purposes).-// Injectable `kill` keeps it unit-testable.-//-// NOT zombie-aware on its own: signal 0 also succeeds for a process that-// exited but whose parent has not reaped it. Callers deciding whether an-// update marker's owner is still running must layer `posixProcessState` on-// top (see `readLiveUpdateMarker`).-export function isPidAlive(pid, kill: typeof process.kill = process.kill.bind(process)) {+// NOT zombie-aware on its own; see `posixProcessState`.+export function isPidAlive(pid: number, kill: typeof process.kill = process.kill.bind(process)) {if (!Number.isInteger(pid) || pid <= 0) {return false}@@ -52,22 +57,15 @@ export function isPidAlive(pid, kill: typeof process.kill = process.kill.bind(prkill(pid, 0)return true- } catch (err) {+ } catch (err: any) {return Boolean(err && err.code === 'EPERM')}}/*** Single-letter process state (`ps` style) for a kill(0)-alive pid, or null- * when it cannot be determined.- *- * A ZOMBIE — exited, still in the table because its parent has not reaped- * it — answers signal 0 like a live process. A crashed updater lingering- * that way would keep its update marker "live" and park the desktop boot- * gate for the whole 20-minute ceiling (#77259, #120635, #125932). Linux- * exposes the state via /proc; on macOS `ps -o stat=` does. Failures return- * null so callers keep their signal-0 verdict (fail-open to alive, matching- * the EPERM behavior above).+ * when it cannot be determined. A ZOMBIE answers signal 0 like a live process+ * (#77259, #120635, #125932). Failures return null (fail-open to alive).*/export function posixProcessState(pid: number): string | null {if (process.platform === 'linux') {@@ -98,164 +96,464 @@ export function posixProcessState(pid: number): string | null {return null}-// A state of 'Z'/'Z+' (and friends) means the process exited and only its-// unreaped table entry remains — dead for every liveness decision here.function isZombieState(state: string | null | undefined): boolean {return Boolean(state && state.toUpperCase().startsWith('Z'))}+let linuxClockTicks: number | null = null++function linuxCreateTime(pid: number): number | null {+ try {+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')+ const fields = stat.slice(stat.lastIndexOf(')') + 1).trim().split(/\s+/)+ // Field 22 of /proc/<pid>/stat (starttime, clock ticks since boot) is index+ // 19 once pid and comm are stripped.+ const ticks = Number(fields[19])+ const btime = Number(/^btime\s+(\d+)/m.exec(fs.readFileSync('/proc/stat', 'utf8'))?.[1])++ if (!Number.isFinite(ticks) || !Number.isFinite(btime)) {+ return null+ }++ if (linuxClockTicks === null) {+ try {+ linuxClockTicks = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 2000 }).trim()) || 100+ } catch {+ linuxClockTicks = 100+ }+ }++ return btime + ticks / linuxClockTicks+ } catch {+ return null+ }+}++function darwinCreateTime(pid: number): number | null {+ try {+ const out = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {+ encoding: 'utf8',+ env: { ...process.env, LC_ALL: 'C', LANG: 'C' },+ timeout: 5000+ }).trim()++ const ms = Date.parse(out.replace(/\s+/g, ' '))++ return Number.isFinite(ms) ? ms / 1000 : null+ } catch {+ return null+ }+}++function ownCreateTime(): number | null {+ const ms = (process as { getCreationTime?: () => number | null }).getCreationTime?.()++ return typeof ms === 'number' && Number.isFinite(ms) && ms > 0 ? ms / 1000 : null+}+/**- * Read + interpret the marker.- *- * Returns `{ pid, ageMs }` only when an update is GENUINELY still running- * (parseable pid that is alive, within the age ceiling). Returns `null` for- * every "no live update" case — absent, unreadable, malformed, dead pid, or- * past the ceiling — and, when a stale marker file exists, deletes it so it- * cannot strand future launches.- *- * Pure-ish: file I/O against the given path, plus an injectable pid probe and- * clock for tests.+ * Creation time (unix seconds) of a live pid, or null when it cannot be read.+ * Same sources as the Python/Rust/script writers: Linux /proc starttime ++ * btime, macOS `ps -o lstart=`, Windows `GetProcessTimes` (Electron's own+ * `process.getCreationTime()` for this process; `Get-Process` otherwise).*/-export function readLiveUpdateMarker(- hermesHome,- {- kill,- now = Date.now,- maxAgeMs = UPDATE_MARKER_MAX_AGE_MS,- processState = posixProcessState- }: {- now?: () => number- maxAgeMs?: number- kill?: typeof process.kill- /** Injectable override of the zombie/state probe (see posixProcessState). */- processState?: (pid: number) => string | null- } = {}-) {+export async function processCreateTime(pid: number): Promise<number | null> {+ if (!isPidAlive(pid)) {+ return null+ }++ if (process.platform === 'linux') {+ return linuxCreateTime(pid)+ }++ if (process.platform === 'darwin') {+ return darwinCreateTime(pid)+ }++ if (process.platform !== 'win32') {+ return null+ }++ if (pid === process.pid) {+ return ownCreateTime()+ }++ return new Promise(resolve => {+ execFile(+ 'powershell.exe',+ [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`+ ],+ { encoding: 'utf8', timeout: 15_000, windowsHide: true },+ (error, stdout) => {+ const ticks = Number(String(stdout || '').trim())++ // .NET ticks (100 ns since 0001-01-01) → unix seconds.+ resolve(!error && Number.isFinite(ticks) && ticks > 0 ? (ticks - 621_355_968_000_000_000) / 1e7 : null)+ }+ ).stdin?.end()+ })+}++/**+ * Synchronous variant for module-init callers (desktop-installation's repair+ * lock). On Windows a foreign pid costs one blocking `Get-Process`, so only use+ * it on a rare path.+ */+export function processCreateTimeSync(pid: number): number | null {+ if (!isPidAlive(pid)) {+ return null+ }++ if (process.platform === 'linux') {+ return linuxCreateTime(pid)+ }++ if (process.platform === 'darwin') {+ return darwinCreateTime(pid)+ }++ if (process.platform !== 'win32') {+ return null+ }++ if (pid === process.pid) {+ return ownCreateTime()+ }++ try {+ const ticks = Number(+ execFileSync(+ 'powershell.exe',+ [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`+ ],+ { encoding: 'utf8', timeout: 15_000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }+ ).trim()+ )++ return Number.isFinite(ticks) && ticks > 0 ? (ticks - 621_355_968_000_000_000) / 1e7 : null+ } catch {+ return null+ }+}++/** C1 rule 3 for a (pid, recorded ct) pair, synchronously. */+export function processIsLiveSync(pid: number, recordedCt: number | null): boolean {+ if (!isPidAlive(pid) || isZombieState(posixProcessState(pid))) {+ return false+ }++ if (recordedCt === null) {+ return true+ }++ const actual = processCreateTimeSync(pid)++ return actual === null || Math.abs(actual - recordedCt) <= CREATE_TIME_TOLERANCE_S+}++export function formatCreateTime(seconds: number): string {+ return seconds.toFixed(3)+}++export interface UpdateMarker {+ pid: number+ /** Unix seconds; null when line 2 is missing/garbled. */+ startedAt: number | null+ /** Recorded owner creation time; null for a v1 marker. */+ ct: number | null+ delegate: { pid: number; ct: number | null } | null+}++const CT_RE = /^ct:(\d+(?:\.\d+)?)$/+const DELEGATE_RE = /^delegate:(\d+)(?:\s+ct:(\d+(?:\.\d+)?))?$/++export function parseUpdateMarker(raw: string): UpdateMarker | null {+ const lines = String(raw).split('\n').map(line => line.trim())++ if (!/^\d+$/.test(lines[0] || '')) {+ return null+ }++ const pid = Number(lines[0])+ const startedAt = /^\d+$/.test(lines[1] || '') ? Number(lines[1]) : null+ let ct: number | null = null+ let delegate: UpdateMarker['delegate'] = null++ for (const line of lines.slice(2)) {+ const ctMatch = CT_RE.exec(line)+ const delegateMatch = DELEGATE_RE.exec(line)++ if (ctMatch && ct === null) {+ ct = Number(ctMatch[1])+ } else if (delegateMatch && !delegate) {+ delegate = { pid: Number(delegateMatch[1]), ct: delegateMatch[2] ? Number(delegateMatch[2]) : null }+ }+ }++ return { pid, startedAt, ct, delegate }+}++export interface MarkerProbeDeps {+ kill?: typeof process.kill+ now?: () => number+ maxAgeMs?: number+ processState?: (pid: number) => string | null+ createTime?: (pid: number) => number | null | Promise<number | null>+}++/** C1 rule 3 for one (pid, recorded ct) pair. Age is the caller's business. */+async function processIsLive(pid: number, recordedCt: number | null, deps: MarkerProbeDeps): Promise<boolean> {+ if (!isPidAlive(pid, deps.kill) || isZombieState((deps.processState || posixProcessState)(pid))) {+ return false+ }++ if (recordedCt === null) {+ return true+ }++ const actual = await (deps.createTime || processCreateTime)(pid)++ return actual === null || Math.abs(actual - recordedCt) <= CREATE_TIME_TOLERANCE_S+}++export type MarkerInspection =+ | { state: 'absent' }+ | { state: 'live'; raw: Buffer; marker: UpdateMarker; ageMs: number; livePid: number }+ | { state: 'dead'; raw: Buffer; marker: UpdateMarker | null }++/** Read and judge the marker without touching it. */+export async function inspectUpdateMarker(hermesHome: string, deps: MarkerProbeDeps = {}): Promise<MarkerInspection> {+ let raw: Buffer++ try {+ raw = fs.readFileSync(markerPath(hermesHome))+ } catch {+ return { state: 'absent' }+ }++ const marker = parseUpdateMarker(raw.toString('utf8'))++ if (!marker) {+ return { state: 'dead', raw, marker: null }+ }++ const now = deps.now || Date.now+ const ageMs = marker.startedAt === null ? Infinity : now() - marker.startedAt * 1000+ const v1Expired = marker.ct === null && ageMs > (deps.maxAgeMs ?? UPDATE_MARKER_MAX_AGE_MS)++ if (!v1Expired && (await processIsLive(marker.pid, marker.ct, deps))) {+ return { state: 'live', raw, marker, ageMs, livePid: marker.pid }+ }++ if (marker.delegate && (await processIsLive(marker.delegate.pid, marker.delegate.ct, deps))) {+ return { state: 'live', raw, marker, ageMs, livePid: marker.delegate.pid }+ }++ return { state: 'dead', raw, marker }+}++/** C1 rule 5: unlink only while the file still holds exactly `expected`. */+export function compareAndDeleteMarker(hermesHome: string, expected: Buffer | string): boolean {const file = markerPath(hermesHome)- let rawtry {- raw = fs.readFileSync(file, 'utf8')+ if (!fs.readFileSync(file).equals(Buffer.isBuffer(expected) ? expected : Buffer.from(expected, 'utf8'))) {+ return false+ }++ fs.unlinkSync(file)++ return true} catch {- return null // absent or unreadable => no live update+ return false}+}- const [pidLine, startedLine] = String(raw).split('\n')- const pid = Number.parseInt((pidLine || '').trim(), 10)- const startedAt = Number.parseInt((startedLine || '').trim(), 10)- const ageMs = Number.isFinite(startedAt) ? now() - startedAt * 1000 : Infinity- const alive = Number.isInteger(pid) && isPidAlive(pid, kill)+/**+ * `{ pid, ageMs }` while an update is genuinely running, else null. A dead+ * marker is compare-and-deleted so it cannot strand future launches.+ */+export async function readLiveUpdateMarker(hermesHome: string, deps: MarkerProbeDeps = {}) {+ const inspection = await inspectUpdateMarker(hermesHome, deps)- if (!alive || isZombieState(processState(pid)) || ageMs > maxAgeMs) {- try {- fs.unlinkSync(file)- } catch {- void 0+ if (inspection.state === 'live') {+ return {+ pid: inspection.livePid,+ ownerPid: inspection.marker.pid,+ ageMs: inspection.ageMs,+ startedAt: inspection.marker.startedAt}+ }- return null+ if (inspection.state === 'dead') {+ compareAndDeleteMarker(hermesHome, inspection.raw)}- return { pid, ageMs }+ return null}/**- * Write the update-in-progress marker *from the desktop* before handing off- * to the detached updater.- *- * The Tauri-based hermes-setup.exe takes several seconds to initialise its- * window and reach the Rust `run_update` entry point where it writes the- * marker itself. During that gap the desktop's `app.quit()` teardown kills- * the backend child, the renderer's WebSocket drops, and the renderer- * immediately calls `ensureBackend()` → `waitForUpdateToFinish()`. Because- * the updater hasn't written the marker yet, the gate sees no live update- * and spawns a *new* backend — which re-locks `.pyd` files in the venv.- * When the updater finally reaches the venv-rebuild stage it finds those- * files locked and the update bricks.- *- * Fix: the desktop writes the marker itself, using the spawned updater's- * PID, immediately after `spawn()`. The updater's `UpdateMarkerGuard` will- * later adopt it or another hand-off stage may replace the PID. A live- * holder's original timestamp is preserved across those transfers so retries- * cannot keep resetting the 20-minute stale ceiling. When the updater finishes- * it deletes the marker as before.- * If the updater never starts (spawn failure) the marker still contains a- * real PID, so `readLiveUpdateMarker` will self-heal once that PID exits.+ * Legacy pre-write for the staged Tauri updater (`hermes-setup.exe --update`):+ * the child IS the updater there, so naming its pid is correct, and frozen+ * builds read only lines 1-2. Exclusive create — a live claim is never+ * overwritten; a dead one is compare-and-deleted first.*/-export function writeUpdateMarker(- hermesHome,- pid,- {- kill,- now = Date.now,- maxAgeMs = UPDATE_MARKER_MAX_AGE_MS,- startedAt- }: {- now?: () => number- maxAgeMs?: number- kill?: typeof process.kill- startedAt?: number- } = {}+export async function writeUpdateMarker(+ hermesHome: string,+ pid: number,+ { startedAt, ...deps }: MarkerProbeDeps & { startedAt?: number } = {}) {- const file = markerPath(hermesHome)- const nowMs = now()- const owner = readLiveUpdateMarker(hermesHome, { kill, maxAgeMs, now: () => nowMs })-const acquiredAt =typeof startedAt === 'number' && Number.isInteger(startedAt)? startedAt- : owner- ? Math.floor((nowMs - owner.ageMs) / 1000)- : Math.floor(nowMs / 1000)+ : Math.floor((deps.now || Date.now)() / 1000)- try {- fs.writeFileSync(file, `${pid}\n${acquiredAt}\n`, 'utf8')- } catch {- // Best-effort: if we can't write the marker, proceed anyway. The- // updater will write its own when it reaches run_update.+ await createMarkerExclusive(hermesHome, `${pid}\n${acquiredAt}\n`, deps)+}++interface ClaimResult {+ ok: boolean+ body?: string+ /** Set when a LIVE claim blocks ours. */+ owner?: { pid: number; ageMs: number } | null+ error?: string+}++async function createMarkerExclusive(hermesHome: string, body: string, deps: MarkerProbeDeps): Promise<ClaimResult> {+ const file = markerPath(hermesHome)++ for (let attempt = 0; attempt < 2; attempt++) {+ try {+ const fd = fs.openSync(file, 'wx', 0o644)++ try {+ fs.writeSync(fd, body)+ fs.fsyncSync(fd)+ } finally {+ fs.closeSync(fd)+ }++ return { ok: true, body }+ } catch (error: any) {+ if (error?.code !== 'EEXIST') {+ return { ok: false, owner: null, error: error?.message || String(error) }+ }+ }++ const inspection = await inspectUpdateMarker(hermesHome, deps)++ if (inspection.state === 'live') {+ return { ok: false, owner: { pid: inspection.livePid, ageMs: inspection.ageMs } }+ }++ if (inspection.state === 'dead') {+ compareAndDeleteMarker(hermesHome, inspection.raw)+ }}++ const inspection = await inspectUpdateMarker(hermesHome, deps)++ return inspection.state === 'live'+ ? { ok: false, owner: { pid: inspection.livePid, ageMs: inspection.ageMs } }+ : { ok: false, owner: null, error: 'lost the marker claim race twice' }+}++function conflictMessage(owner: { pid: number; ageMs: number }): string {+ const ageMs = Number.isFinite(owner.ageMs) ? Math.max(0, owner.ageMs) : 0+ const mins = Math.floor(ageMs / 60_000)+ const secs = Math.floor((ageMs % 60_000) / 1000)+ const elapsed = mins > 0 ? `${mins}m ${secs}s` : `${secs}s`++ return `An update is already running (PID ${owner.pid}, started ${elapsed} ago). Wait for it to finish, then try again.`}/**- * Whether a NEW updater hand-off must be refused because a different,- * already-alive updater currently owns the marker (#75778).- *- * `writeUpdateMarker` unconditionally overwrites the marker file. Called- * before every hand-off with no conflict check, a user who clicks "Update"- * again while a prior updater is still parked mid-run (e.g. "waiting for- * Hermes to exit…") clobbers that still-running updater's claim: the- * retry's pre-write now names the NEW child, so the OLD process — alive- * and mutating the checkout — is no longer recorded as the owner. A second- * live updater can then run over the same tree unrecorded, the exact- * two-updaters-at-once hazard `UpdateMarkerGuard` in the Rust updater- * exists to prevent (apps/bootstrap-installer/src-tauri/src/update.rs).- *- * Returns the live foreign owner (with a ready-to-show message) when the- * hand-off must be refused, or `null` when it's safe to spawn — no marker,- * or the existing one is stale/dead and self-heals via- * `readLiveUpdateMarker`.+ * C2 bridge claim: the Desktop claims the marker in ITS OWN name (pid ++ * creation time) before spawning the hand-off script. Electron is alive until+ * it quits, so the claim never names a short-lived `cmd.exe`/launcher wrapper.+ * A live foreign owner refuses the hand-off (#75778).*/-export function updateHandoffConflict(- hermesHome,- opts: {- now?: () => number- maxAgeMs?: number- kill?: typeof process.kill- } = {}-) {- const owner = readLiveUpdateMarker(hermesHome, opts)+export async function claimBridgeMarker(+ hermesHome: string,+ {+ pid = process.pid,+ createTime,+ startedAt,+ ...deps+ }: MarkerProbeDeps & { pid?: number; startedAt?: number } = {}+): Promise<{+ ok: boolean+ body?: string+ conflict?: { pid: number; ageMs: number; message: string } | null+ error?: string+}> {+ const ct = await (createTime || processCreateTime)(pid)+ const acquiredAt = Number.isInteger(startedAt) ? startedAt : Math.floor((deps.now || Date.now)() / 1000)+ const body = `${pid}\n${acquiredAt}\n${ct === null ? '' : `ct:${formatCreateTime(ct)}\n`}`- if (!owner) {- return null+ fs.mkdirSync(hermesHome, { recursive: true })+ const result = await createMarkerExclusive(hermesHome, body, { ...deps, createTime })++ if (result.ok || !result.owner) {+ return result}- const mins = Math.floor(owner.ageMs / 60_000)- const secs = Math.floor((owner.ageMs % 60_000) / 1000)- const elapsed = mins > 0 ? `${mins}m ${secs}s` : `${secs}s`+ return { ok: false, conflict: { ...result.owner, message: conflictMessage(result.owner) } }+}++/**+ * C2: the hand-off has started only once the script took the marker — its+ * owner pid is no longer ours. A wrapper's exit code says nothing about+ * whether the script ever ran (#66753: CLM-blocked Add-Type, a missing+ * /usr/bin/python3 for the posix daemonizer).+ */+export async function waitForHandoffClaim(+ hermesHome: string,+ ownPid: number,+ {+ timeoutMs = HANDOFF_CLAIM_TIMEOUT_MS,+ pollMs = 200,+ now = Date.now,+ sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))+ }: { timeoutMs?: number; pollMs?: number; now?: () => number; sleep?: (ms: number) => Promise<void> } = {}+): Promise<{ taken: true; pid: number } | { taken: false }> {+ const deadline = now() + timeoutMs++ for (;;) {+ let marker: UpdateMarker | null = null++ try {+ marker = parseUpdateMarker(fs.readFileSync(markerPath(hermesHome), 'utf8'))+ } catch {+ marker = null+ }++ if (marker && marker.pid !== ownPid) {+ return { taken: true, pid: marker.pid }+ }++ if (now() >= deadline) {+ return { taken: false }+ }- return {- pid: owner.pid,- ageMs: owner.ageMs,- message: `An update is already running (PID ${owner.pid}, started ${elapsed} ago). Wait for it to finish, then try again.`+ await sleep(pollMs)}}++/**+ * Whether a NEW updater hand-off must be refused because a different, live+ * updater owns the marker (#75778). Null when it is safe to spawn.+ */+export async function updateHandoffConflict(hermesHome: string, deps: MarkerProbeDeps = {}) {+ const owner = await readLiveUpdateMarker(hermesHome, deps)++ return owner ? { pid: owner.pid, ageMs: owner.ageMs, message: conflictMessage(owner) } : null+}diff --git a/apps/desktop/electron/updater/checkout-handoff.test.ts b/apps/desktop/electron/updater/checkout-handoff.test.tsindex 34d925b4949..f4a9191c02c 100644--- a/apps/desktop/electron/updater/checkout-handoff.test.ts+++ b/apps/desktop/electron/updater/checkout-handoff.test.ts@@ -5,6 +5,7 @@ import * as path from 'node:path'import { afterEach, expect, it, vi } from 'vitest'+import { markerPath } from '../update-marker'import * as updaterProcess from '../updater-process'import { type CheckoutStrategyDeps, createCheckoutStrategy } from './checkout'@@ -38,6 +39,7 @@ function handoffFixture(remote: boolean): { root: string; deps: CheckoutStrategyisMac: process.platform === 'darwin',defaultUpdateBranch: 'main',updateHandoffDwellMs: 0,+ handoffClaimTimeoutMs: 2000,resolveUpdateRoot: (): string => root,resolveUpdaterBinary: (): null => null,remoteGatewayActive: (): boolean => remote,@@ -55,6 +57,11 @@ function handoffFixture(remote: boolean): { root: string; deps: CheckoutStrategyreturn { root, deps }}+/** The hand-off script's first act (C2): it takes the Desktop's bridge marker. */+function scriptTakesMarker(home: string): void {+ fs.writeFileSync(markerPath(home), `${process.ppid}\n${Math.floor(Date.now() / 1000)}\n`)+}+// One gateway per host (#117529): a Desktop served by a remote gateway must// tell the hand-off script not to (re)start a local one, and a locally-owned// Desktop must keep the default so its gateway comes back after the update.@@ -72,6 +79,7 @@ it.each([true, false])(): updaterProcess.UpdaterChild => {spawned.push(args)spawnOptions.push(options)+ scriptTakesMarker(deps.hermesHome)return { unref: (): void => {} }}@@ -111,6 +119,7 @@ it('the Windows hand-off wrapper is spawned non-detached so the script shares itvi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation((command: string, args: string[], options: { detached?: boolean }): updaterProcess.UpdaterChild => {spawned.push({ command, args, detached: options.detached })+ scriptTakesMarker(deps.hermesHome)return { unref: (): void => {} }}@@ -157,3 +166,27 @@ it('a failed hand-off spawn keeps the app alive and reports the failure in plainfs.rmSync(root, { recursive: true, force: true })}})++// V7: the wrapper's exit 0 is not a hand-off. Without the script taking the+// bridge marker the Desktop stays up, restarts its backend, reports the+// failure, and compare-deletes its own bridge marker.+it('a hand-off whose script never takes the marker keeps the app alive and clears the bridge', async (): Promise<void> => {+ const { root, deps } = handoffFixture(false)+ vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation(+ (): updaterProcess.UpdaterChild => ({ unref: (): void => {} })+ )++ try {+ const result = await createCheckoutStrategy({ ...deps, handoffClaimTimeoutMs: 300 }).apply()++ expect(result).toMatchObject({ ok: false, error: 'updater-spawn-failed' })+ expect(result.message).toMatch(/previous version/)+ expect(deps.quit).not.toHaveBeenCalled()+ expect(deps.markQuittingForHandoff).not.toHaveBeenCalled()+ // Windows stopped its backends before spawning; POSIX never did.+ expect(vi.mocked(deps.startHermes).mock.calls.length > 0).toBe(IS_WINDOWS)+ expect(fs.existsSync(markerPath(deps.hermesHome))).toBe(false)+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.tsindex 32d07e6030c..95403bf11cc 100644--- a/apps/desktop/electron/updater/checkout.ts+++ b/apps/desktop/electron/updater/checkout.ts@@ -3,7 +3,14 @@import { existsSync, readFileSync } from 'node:fs'import * as path from 'node:path'-import { updateHandoffConflict, writeUpdateMarker } from '../update-marker'+import {+ claimBridgeMarker,+ compareAndDeleteMarker,+ HANDOFF_CLAIM_TIMEOUT_MS,+ updateHandoffConflict,+ waitForHandoffClaim,+ writeUpdateMarker+} from '../update-marker'import {collectRelaunchArgs,describeUpdaterHandoffFailure,@@ -34,6 +41,8 @@ export interface CheckoutStrategyDeps {isMac: booleandefaultUpdateBranch: stringupdateHandoffDwellMs: number+ /** How long the hand-off script has to take the bridge marker (C2); default 20 s. */+ handoffClaimTimeoutMs?: numberresolveUpdaterBinary: () => string | null/*** True when one remote gateway serves this Desktop (app-global remote /@@ -88,6 +97,69 @@ export function readStampedCommit(root: string): string | null {* every result the way the wire contract expects.*/export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrategy {+ /**+ * C2 bridge: claim the marker in this Desktop's own name before spawning the+ * hand-off script, so it never names the short-lived cmd.exe/launcher+ * wrapper (V4). Returns the refusal result on a live foreign owner.+ */+ async function claimBridge(updateStartedAt: number): Promise<{ body: string | null; refusal?: UpdaterApplyResultWire }> {+ const bridge = await claimBridgeMarker(deps.hermesHome, { startedAt: updateStartedAt })++ if (bridge.ok) {+ return { body: bridge.body ?? null }+ }++ if (bridge.conflict) {+ deps.rememberLog(`[updates] refusing hand-off: ${bridge.conflict.message}`)+ deps.emitUpdateProgress({ stage: 'error', message: bridge.conflict.message, percent: null })++ return {+ body: null,+ refusal: { ok: false, error: 'update-already-running', message: bridge.conflict.message }+ }+ }++ // The script claims with a fresh exclusive create in that case; the+ // owner-change check below still proves it started.+ deps.rememberLog(`[updates] could not write the bridge marker (${bridge.error}); continuing without it`)++ return { body: null }+ }++ /**+ * C2: the hand-off started only when the script took the marker (its owner+ * is no longer this pid) — not when a wrapper exited 0 (V7). Returns an+ * error message when it did not; the caller stays up.+ */+ async function confirmScriptHandoff(child, bridgeBody: string | null, startedAtMs: number): Promise<string | null> {+ const outcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)+ let failure: string | null = outcome.ok ? null : describeUpdaterHandoffFailure(outcome)++ if (!failure) {+ const claim = await waitForHandoffClaim(deps.hermesHome, process.pid, {+ timeoutMs: Math.max(0, (deps.handoffClaimTimeoutMs ?? HANDOFF_CLAIM_TIMEOUT_MS) - (Date.now() - startedAtMs))+ })++ if (claim.taken) {+ deps.rememberLog(`[updates] hand-off script took the update marker (pid ${claim.pid})`)++ return null+ }++ failure =+ 'The updater did not start, so nothing was changed. Hermes keeps running on the previous version — try the update again.\n\n' ++ `Details: the hand-off script never took the update lock within ${Math.round((deps.handoffClaimTimeoutMs ?? HANDOFF_CLAIM_TIMEOUT_MS) / 1000)} s.`+ }++ deps.rememberLog(`[updates] hand-off not viable, aborting quit: ${failure}`)++ if (bridgeBody) {+ compareAndDeleteMarker(deps.hermesHome, bridgeBody)+ }++ return failure+ }+const mechanism: UpdaterMechanism = deps.isWindows ? 'windows-handoff' : 'posix-handoff'async function check(opts: { force?: boolean } = {}): Promise<UpdaterStatusWire> {@@ -201,7 +273,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStratdeps.rememberLog('[updates] no staged updater; using repo hand-off script for CLI install')}- const handoffConflict = updateHandoffConflict(deps.hermesHome)+ const handoffConflict = await updateHandoffConflict(deps.hermesHome)if (handoffConflict) {// A different updater already owns the marker — most often a previous@@ -261,19 +333,29 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat// next one. Checkouts that predate the script fall back to the binary// path unchanged.const scriptHandoff = resolveUpdateScriptHandoff(updateRoot)+ const handoffStartedAt = Date.now()let child+ let bridgeBody: string | null = nullif (scriptHandoff) {const updateStartedAt = Math.floor(Date.now() / 1000)+ const bridge = await claimBridge(updateStartedAt)++ if (bridge.refusal) {+ deps.startHermes().catch(() => {})++ return bridge.refusal+ }++ bridgeBody = bridge.body// A bare detached+hidden powershell spawn silently dies before -File// processing (console-subsystem init failure — see// wrapHandoffForDetachedConsole). Spawn the cmd wrapper non-detached// so windowsHide gives it a hidden console that `start /b` shares with- // PowerShell; the script still outlives us. The wrapper cmd.exe exits- // immediately, so child.pid is NOT the script's- // pid — the script claims the update marker itself with its own $PID- // as its first action, and a relaunched Desktop parks on that.+ // PowerShell; the script still outlives us. The wrapper exits at once,+ // so its pid means nothing: the bridge marker above names THIS process,+ // and the script takes it over (adopting -DesktopPid) as its first act.const wrappedArgs: string[] = ['-InstallRoot',updateRoot,@@ -305,17 +387,6 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStratstdio: 'ignore'})- // Bridge marker: child.pid is the short-lived cmd.exe WRAPPER, not the- // script (see wrapHandoffForDetachedConsole). Write it anyway to cover- // the first moments of the hand-off — the script's step 0 overwrites it- // with its own live $PID, and if the script never starts the wrapper's- // dead pid makes the marker read as stale and self-delete (no wedge).- // The `hermes update` child adopts the SCRIPT's claim via- // update_lock.py's process-ancestry rule; no mtime heuristics needed.- if (Number.isInteger(child.pid)) {- writeUpdateMarker(deps.hermesHome, child.pid, { startedAt: updateStartedAt })- }-deps.rememberLog(`[updates] launched repo hand-off script: ${scriptHandoff.scriptPath} (${targetLabel}); exiting desktop for application replacement`)@@ -345,7 +416,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat// strictly better than never updating again, and the updater still writes// its own marker moments later.if (Number.isInteger(child.pid) && stagedUpdaterSupportsPrewrittenMarker(updater)) {- writeUpdateMarker(deps.hermesHome, child.pid)+ await writeUpdateMarker(deps.hermesHome, child.pid)} else if (Number.isInteger(child.pid)) {deps.rememberLog(`[updates] skipping marker pre-write: staged updater predates self-adopt (${updater}); it would refuse its own claim`@@ -367,19 +438,28 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat// detached child for an async spawn `error` (ENOENT/EACCES) or an early// non-zero/signal exit. On failure, DON'T quit — the user would be left// with no app, no updater, and no evidence. Restart our backend and- // surface the error instead. The pre-written marker names the dead child- // pid, so readLiveUpdateMarker self-heals it; no cleanup needed.+ // surface the error instead. A script hand-off additionally has to take+ // the bridge marker within 20 s (C2); the staged binary IS the updater, so+ // its own exit status is meaningful.const dwellStartedAt = Date.now()- const handoffOutcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)+ let failure: string | null++ if (scriptHandoff) {+ failure = await confirmScriptHandoff(child, bridgeBody, handoffStartedAt)+ } else {+ const handoffOutcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)+ failure = handoffOutcome.ok ? null : describeUpdaterHandoffFailure(handoffOutcome)- if (!handoffOutcome.ok) {- const message: string = describeUpdaterHandoffFailure(handoffOutcome)+ if (failure) {+ deps.rememberLog(`[updates] hand-off not viable, aborting quit: ${handoffOutcome.message}`)+ }+ }- deps.rememberLog(`[updates] hand-off not viable, aborting quit: ${handoffOutcome.message}`)- deps.emitUpdateProgress({ stage: 'error', message, percent: null })+ if (failure) {+ deps.emitUpdateProgress({ stage: 'error', message: failure, percent: null })deps.startHermes().catch(() => {})- return { ok: false, error: 'updater-spawn-failed', message }+ return { ok: false, error: 'updater-spawn-failed', message: failure }}deps.markQuittingForHandoff()@@ -407,7 +487,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStratreturn { ok: true, manual: true, command: manualCommand, hermesRoot: updateRoot }}- const handoffConflict = updateHandoffConflict(deps.hermesHome)+ const handoffConflict = await updateHandoffConflict(deps.hermesHome)if (handoffConflict) {// Same hazard as the Windows path (#75778): a live foreign updater@@ -438,7 +518,13 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStratargs.push('--no-gateway')}- const updateStartedAt = Math.floor(Date.now() / 1000)+ const handoffStartedAt = Date.now()+ const updateStartedAt = Math.floor(handoffStartedAt / 1000)+ const bridge = await claimBridge(updateStartedAt)++ if (bridge.refusal) {+ return bridge.refusal+ }// Relaunch target: the running .app bundle on mac (script swaps the// rebuilt bundle over it), the running binary elsewhere. The script's gate@@ -476,13 +562,6 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStratstdio: 'ignore'})- // Bridge marker (same contract as the Windows hand-off): cover the gap- // until the script claims the marker with its own pid as step 0. If the- // script never starts, the dead pid reads as stale and self-deletes.- if (Number.isInteger(child.pid)) {- writeUpdateMarker(deps.hermesHome, child.pid, { startedAt: updateStartedAt })- }-deps.rememberLog(`[updates] launched posix hand-off: ${handoff.scriptPath} (${targetLabel}); quitting to hand off`)deps.emitUpdateProgress({stage: 'restart',@@ -496,16 +575,15 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat// and the user is left with no app, no updater, and no relaunch. Watch the// child through the dwell; on spawn error or early death, stay alive and// surface the failure instead of quitting into nothing.+ // The launcher always exits 0 after daemonizing, so only the daemon taking+ // the bridge marker proves an update is running (C2, V7).const dwellStartedAt = Date.now()- const handoffOutcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)-- if (!handoffOutcome.ok) {- const message: string = describeUpdaterHandoffFailure(handoffOutcome)+ const failure = await confirmScriptHandoff(child, bridge.body, handoffStartedAt)- deps.rememberLog(`[updates] posix hand-off not viable, aborting quit: ${handoffOutcome.message}`)- deps.emitUpdateProgress({ stage: 'error', message, percent: null })+ if (failure) {+ deps.emitUpdateProgress({ stage: 'error', message: failure, percent: null })- return { ok: false, error: 'updater-spawn-failed', message }+ return { ok: false, error: 'updater-spawn-failed', message: failure }}deps.markQuittingForHandoff()