The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): marker liveness never waits forever, never sees half a claim
Teknium10d866b0d361
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 3e672026aba..aa7c6d9820f 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -591,7 +591,13 @@ import {windowOpacityOptions} from './translucency'import { waitForUpdateClearance } from './update-gate'-import { markerPath, readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from './update-marker'+import {+ cachedCreateTimeProbe,+ markerPath,+ readLiveUpdateMarker,+ updateHandoffConflict,+ writeUpdateMarker+} from './update-marker'import { updateConnectionsBeforeLocal } from './update-order'import {resolveUpdaterMechanism,@@ -2990,12 +2996,16 @@ const UPDATE_HANDOFF_DWELL_MS = 2500// wrapper exits 0 before the real PowerShell script claims the marker, and// `finally` clears updateInFlight immediately after the hand-off is accepted.function updateGateDeps(onLiveMarker?: (marker: { startedAt: number | null }) => void) {+ // One creation-time probe per pid for this wait: on Windows each probe is a+ // powershell spawn and the gate polls every second.+ const createTime = cachedCreateTimeProbe()+return {// 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)+ const marker = await readLiveUpdateMarker(HERMES_HOME, { createTime })if (marker) {onLiveMarker?.(marker)diff --git a/apps/desktop/electron/update-gate.ts b/apps/desktop/electron/update-gate.tsindex 3b1563787e3..d176de80bb3 100644--- a/apps/desktop/electron/update-gate.ts+++ b/apps/desktop/electron/update-gate.ts@@ -80,9 +80,12 @@ export interface WaitForUpdateClearanceOptions {* Returns 'clear' when the gate was already open (no wait happened),* '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.+ * marker has no deadline here: owner liveness 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. The marker reader+ * still bounds the wait: an owner whose creation time cannot be read stops+ * reading live at the 20-minute ceiling (A1), so a reused pid never parks+ * boot forever.*/export async function waitForUpdateClearance(deps: UpdateGateDeps,diff --git a/apps/desktop/electron/update-marker.test.ts b/apps/desktop/electron/update-marker.test.tsindex 19cb2f33f96..e9be5276d40 100644--- a/apps/desktop/electron/update-marker.test.ts+++ b/apps/desktop/electron/update-marker.test.ts@@ -17,14 +17,17 @@ import path from 'path'import { afterEach, test } from 'vitest'import {+ cachedCreateTimeProbe,claimBridgeMarker,compareAndDeleteMarker,+ EMPTY_MARKER_GRACE_MS,formatCreateTime,isPidAlive,markerPath,parseUpdateMarker,posixProcessState,processCreateTime,+ psCreateTime,readLiveUpdateMarker,UPDATE_MARKER_MAX_AGE_MS,updateHandoffConflict,@@ -90,6 +93,25 @@ test('parses v1, v2 and the delegate line; garbage is null', () => {assert.equal(parseUpdateMarker('not-a-pid\nnonsense'), null)})+// A2: one positional parse in every language (Python, Rust, PowerShell, bash, TS).+test.each([+ ['BOM + CRLF v2', '\uFEFF42\r\n100\r\nct:5.250\r\n', { pid: 42, startedAt: 100, ct: 5.25, delegate: null }],+ ['fractional started_at is MALFORMED', '42\n100.5\nct:5.000\n', null],+ ['missing started_at is MALFORMED', '42\n', null],+ ['garbled started_at is MALFORMED', '42\nsoon\n', null],+ ['garbage ct => v1', '42\n100\nct:abc\n', { pid: 42, startedAt: 100, ct: null, delegate: null }],+ ['delegate on line 3 is ignored', '42\n100\ndelegate:77 ct:1.000\n', { pid: 42, startedAt: 100, ct: null, delegate: null }],+ ['space after delegate: is ignored', '42\n100\nct:1.000\ndelegate: 77 ct:1.000\n', { pid: 42, startedAt: 100, ct: 1, delegate: null }],+ ['delegate without ct is ignored', '42\n100\nct:1.000\ndelegate:77\n', { pid: 42, startedAt: 100, ct: 1, delegate: null }],+ [+ 'empty ct line (Python probe failure) + delegate on line 4',+ '42\n100\n\ndelegate:77 ct:2.500\n',+ { pid: 42, startedAt: 100, ct: null, delegate: { pid: 77, ct: 2.5 } }+ ]+])('A2 parse: %s', (_name, body, expected) => {+ assert.deepEqual(parseUpdateMarker(body), expected)+})+// ---------------------------------------------------------------------------// Liveness against REAL processes (C1 rule 3, desktop V3/V22)// ---------------------------------------------------------------------------@@ -129,6 +151,67 @@ test('a v1 marker (no creation time) keeps the legacy 20-minute ceiling', asyncassert.ok(!fs.existsSync(markerPath(home)))})+// A1: Windows refuses creation-time queries for SYSTEM/elevated/other-user+// pids. A live pid whose ct cannot be read must not be live forever: a reused+// pid would park every Desktop boot. It is live only inside the v1 ceiling.+test('a v2 owner whose creation time is UNREADABLE is live only inside the 20-minute ceiling (A1)', async () => {+ const home = tmpHome('v2-unreadable')+ const owner = await liveOwner()+ const accessDenied = () => null++ fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(5)}\nct:1700000000.000\n`)+ assert.ok(await readLiveUpdateMarker(home, { createTime: accessDenied }), 'young: unknown ct + live pid reads live')++ fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(25)}\nct:1700000000.000\n`)+ assert.equal(await readLiveUpdateMarker(home, { createTime: accessDenied }), null, 'past the ceiling it is dead')+ assert.ok(!fs.existsSync(markerPath(home)), 'and compare-deleted, so boot is never parked forever')+})++test('a gate wait probes each pid creation time ONCE (A1: no powershell spawn per poll)', async () => {+ const home = tmpHome('ct-cache')+ const owner = await liveOwner()+ const ct = await processCreateTime(owner.pid)+ let probes = 0++ const createTime = cachedCreateTimeProbe(pid => {+ probes += 1++ return processCreateTime(pid)+ })++ fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(1)}\nct:${formatCreateTime(ct ?? 0)}\n`)++ for (let poll = 0; poll < 5; poll++) {+ assert.ok(await readLiveUpdateMarker(home, { createTime }))+ }++ assert.equal(probes, 1)+})++// A1 (macOS source): `ps -o lstart` is local time. Parsed by a different TZ+// engine (or in the DST fall-back hour) a live owner reads hours off its own+// record and is judged a reused pid. Printed and parsed as UTC it cannot drift.+test.skipIf(process.platform === 'win32')('ps lstart creation time is TZ-independent (A1)', async () => {+ const owner = await liveOwner()+ const savedTz = process.env.TZ++ try {+ // glibc honours this POSIX offset; V8's ICU does not and falls back.+ process.env.TZ = '<+0530>-5:30'+ const viaPs = psCreateTime(owner.pid)+ const reference = process.platform === 'linux' ? await processCreateTime(owner.pid) : Date.now() / 1000++ assert.ok(viaPs !== null && reference !== null)+ assert.ok(Math.abs(viaPs - reference) <= 2, `ps says ${viaPs}, the kernel says ${reference}`)+ } finally {+ if (savedTz === undefined) {+ delete process.env.TZ+ } else {+ process.env.TZ = savedTz+ }+ }+})+test('a dead owner with a LIVE delegate keeps the marker live (C1 rule 6)', async () => {const home = tmpHome('delegate')const gone = await deadPid()@@ -220,6 +303,55 @@ test('the bridge claim refuses a LIVE foreign owner and reclaims a dead one', asassert.ok((await claimBridgeMarker(home, { startedAt: 2 })).ok, 'a dead claim is reclaimed')})+// r1 M1: the staged Tauri updater path pre-writes the marker for the spawned+// updater. As v1 it stayed under the 20-minute ceiling (a live 25-minute+// update was aged out and deleted) and blocked the delegate line.+test.skipIf(!HAS_CT_PROBE)('writeUpdateMarker names the spawned updater with its creation time (v2)', async () => {+ const home = tmpHome('write-v2')+ const updater = await liveOwner()++ await writeUpdateMarker(home, updater.pid, { startedAt: minutesAgo(25) })++ const marker = parseUpdateMarker(fs.readFileSync(markerPath(home), 'utf8'))!+ assert.equal(marker.pid, updater.pid)+ assert.ok(marker.ct !== null && Math.abs(marker.ct - (await processCreateTime(updater.pid))!) <= 2)+ assert.ok(await readLiveUpdateMarker(home), 'a 25-minute-old live updater is still running')+ assert.ok(fs.existsSync(markerPath(home)))+})++// A3: a claim is never visible half-written, and a 0-byte claim being written+// by an O_EXCL-only writer is not mistaken for garbage and deleted.+test('a fresh 0-byte marker reads LIVE and survives; a stale one is reclaimed (A3)', async () => {+ const home = tmpHome('empty')+ const file = markerPath(home)+ fs.writeFileSync(file, '')++ assert.ok(await readLiveUpdateMarker(home), 'a claim being written blocks')+ assert.ok(fs.existsSync(file), 'and is never deleted')+ assert.equal((await claimBridgeMarker(home, { startedAt: 1 })).ok, false, 'no claim races past it')++ const old = (Date.now() - EMPTY_MARKER_GRACE_MS - 5000) / 1000+ fs.utimesSync(file, old, old)+ assert.equal(await readLiveUpdateMarker(home), null)+ assert.ok(!fs.existsSync(file))+})++test('claims publish by hard link and leave no tmp litter; a dead writer tmp is reclaimed (A3)', async () => {+ const home = tmpHome('link')+ const deadTmp = path.join(home, `.hermes-update-in-progress.${await deadPid()}.tmp`)+ fs.writeFileSync(deadTmp, 'half')++ const claim = await claimBridgeMarker(home, { startedAt: 7 })++ assert.ok(claim.ok)+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), claim.body)+ assert.deepEqual(+ fs.readdirSync(home).filter(name => name !== '.hermes-update-in-progress'),+ [],+ 'no tmp sibling survives the claim'+ )+})+test('writeUpdateMarker (staged updater) never overwrites a live claim', async () => {const home = tmpHome('write-live')const owner = await liveOwner()diff --git a/apps/desktop/electron/update-marker.ts b/apps/desktop/electron/update-marker.tsindex 0195a82a545..9bb216c6293 100644--- a/apps/desktop/electron/update-marker.ts+++ b/apps/desktop/electron/update-marker.ts@@ -13,14 +13,24 @@* 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.+ * Parsing is positional and identical in every language (contract A2): a+ * leading BOM and `\r\n` are accepted; line 2 must be an integer or the marker+ * is malformed (dead); a line 3 that is not `ct:<n>` makes it v1; a line 4+ * that is not `delegate:<pid> ct:<n>` is ignored.+ *+ * Liveness: a pid that is alive (not a zombie) with a creation time MATCHING+ * the recorded one within 2 s is live regardless of age — a Windows update is+ * routinely 25-40 minutes. A live pid whose creation time is unknown (v1+ * marker, or the probe was refused) is live only inside the legacy 20-minute+ * ceiling (A1): without a creation time nothing else 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.+ *+ * Claims publish a complete body with an exclusive hard link (A3), so a+ * reader never sees a half-written claim; where links are unsupported the+ * O_EXCL fallback can expose an empty file for an instant, and readers treat+ * a 0-byte marker younger than 5 s as live.** 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@@ -40,6 +50,12 @@ 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+/** A 0-byte marker this young is a claim being written, not garbage (A3). */+export const EMPTY_MARKER_GRACE_MS = 5_000++/** .NET ticks (100 ns since 0001-01-01) at the unix epoch. */+const DOTNET_UNIX_EPOCH_TICKS = 621_355_968_000_000_000+export function markerPath(hermesHome: string) {return path.join(hermesHome, '.hermes-update-in-progress')}@@ -129,15 +145,20 @@ function linuxCreateTime(pid: number): number | null {}}-function darwinCreateTime(pid: number): number | null {+/**+ * `ps -o lstart=` creation time (the macOS source; procps prints the same).+ * Printed in UTC and parsed as UTC (A1): local time is ambiguous for an hour+ * at every DST fall-back and can put a live owner 3600 s off its record.+ */+export function psCreateTime(pid: number): number | null {try {const out = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {encoding: 'utf8',- env: { ...process.env, LC_ALL: 'C', LANG: 'C' },+ env: { ...process.env, LC_ALL: 'C', LANG: 'C', TZ: 'UTC0' },timeout: 5000}).trim()- const ms = Date.parse(out.replace(/\s+/g, ' '))+ const ms = out ? Date.parse(`${out.replace(/\s+/g, ' ')} GMT`) : NaNreturn Number.isFinite(ms) ? ms / 1000 : null} catch {@@ -145,6 +166,26 @@ function darwinCreateTime(pid: number): number | null {}}+/**+ * Windows creation time through CIM (A1): `Win32_Process.CreationDate` is read+ * with limited query rights, so it answers for SYSTEM, elevated and other-user+ * processes where `Get-Process .StartTime` is access-denied.+ */+function windowsCreateTimeCommand(pid: number): string[] {+ return [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}' -ErrorAction Stop).CreationDate.ToUniversalTime().Ticks`+ ]+}++function dotnetTicksToUnix(stdout: unknown): number | null {+ const ticks = Number(String(stdout ?? '').trim())++ return Number.isFinite(ticks) && ticks > 0 ? (ticks - DOTNET_UNIX_EPOCH_TICKS) / 1e7 : null+}+function ownCreateTime(): number | null {const ms = (process as { getCreationTime?: () => number | null }).getCreationTime?.()@@ -154,54 +195,34 @@ function ownCreateTime(): number | null {/*** 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).+ * btime, macOS `ps -o lstart=` (UTC), Windows `GetProcessTimes` (Electron's own+ * `process.getCreationTime()` for this process; CIM `CreationDate` otherwise).+ * A Windows foreign pid costs one powershell spawn: pollers wrap this in+ * `cachedCreateTimeProbe`.*/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()+ if (process.platform !== 'win32' || pid === process.pid) {+ return processCreateTimeSync(pid)}return new Promise(resolve => {execFile('powershell.exe',- [- '-NoProfile',- '-NonInteractive',- '-Command',- `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`- ],+ windowsCreateTimeCommand(pid),{ 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)- }+ (error, stdout) => resolve(error ? null : dotnetTicksToUnix(stdout))).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.+ * lock). On Windows a foreign pid costs one blocking powershell spawn, so only+ * use it on a rare path.*/export function processCreateTimeSync(pid: number): number | null {if (!isPidAlive(pid)) {@@ -213,7 +234,7 @@ export function processCreateTimeSync(pid: number): number | null {}if (process.platform === 'darwin') {- return darwinCreateTime(pid)+ return psCreateTime(pid)}if (process.platform !== 'win32') {@@ -225,25 +246,42 @@ export function processCreateTimeSync(pid: number): number | null {}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 dotnetTicksToUnix(+ execFileSync('powershell.exe', windowsCreateTimeCommand(pid), {+ encoding: 'utf8',+ timeout: 15_000,+ windowsHide: true,+ stdio: ['ignore', 'pipe', 'ignore']+ }))-- return Number.isFinite(ticks) && ticks > 0 ? (ticks - 621_355_968_000_000_000) / 1e7 : null} catch {return null}}+export type CreateTimeProbe = (pid: number) => number | null | Promise<number | null>++/**+ * One creation-time probe per pid for the life of ONE waiter (A1) — on Windows+ * each probe is a powershell spawn, and the update gate polls every second.+ * Scope it to a single wait, never module-wide: only a fresh probe tells a+ * pid reused since the last wait from the owner it replaced.+ */+export function cachedCreateTimeProbe(probe: CreateTimeProbe = processCreateTime): CreateTimeProbe {+ const memo = new Map<number, Promise<number | null>>()++ return pid => {+ let hit = memo.get(pid)++ if (!hit) {+ hit = Promise.resolve(probe(pid))+ memo.set(pid, hit)+ }++ return hit+ }+}+/** 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))) {@@ -265,40 +303,43 @@ export function formatCreateTime(seconds: number): string {export interface UpdateMarker {pid: number- /** Unix seconds; null when line 2 is missing/garbled. */- startedAt: number | null+ /** Unix seconds (line 2; an integer, or the marker is malformed). */+ startedAt: number/** Recorded owner creation time; null for a v1 marker. */ct: number | null- delegate: { pid: number; ct: number | null } | null+ delegate: { pid: number; ct: number } | null}-const CT_RE = /^ct:(\d+(?:\.\d+)?)$/-const DELEGATE_RE = /^delegate:(\d+)(?:\s+ct:(\d+(?:\.\d+)?))?$/+const INT_LINE_RE = /^\d+$/+const CT_LINE_RE = /^ct:(\d+(?:\.\d+)?)$/+const DELEGATE_LINE_RE = /^delegate:(\d+) ct:(\d+(?:\.\d+)?)$/+/**+ * Positional parse, identical in every reader (A2). Null = MALFORMED (dead):+ * line 1 not a pid or line 2 not an integer. A bad line 3 means v1; a bad+ * line 4 is ignored.+ */export function parseUpdateMarker(raw: string): UpdateMarker | null {- const lines = String(raw).split('\n').map(line => line.trim())+ const lines = String(raw)+ .replace(/^\uFEFF/, '')+ .split('\n')+ .map(line => line.trim())++ const [pidLine = '', startedLine = '', ctLine = '', delegateLine = ''] = lines- if (!/^\d+$/.test(lines[0] || '')) {+ if (!INT_LINE_RE.test(pidLine) || !INT_LINE_RE.test(startedLine)) {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)+ const ct = CT_LINE_RE.exec(ctLine)+ const delegate = DELEGATE_LINE_RE.exec(delegateLine)- 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: Number(pidLine),+ startedAt: Number(startedLine),+ ct: ct ? Number(ct[1]) : null,+ delegate: delegate ? { pid: Number(delegate[1]), ct: Number(delegate[2]) } : null}-- return { pid, startedAt, ct, delegate }}export interface MarkerProbeDeps {@@ -306,54 +347,86 @@ export interface MarkerProbeDeps {now?: () => numbermaxAgeMs?: numberprocessState?: (pid: number) => string | null- createTime?: (pid: number) => number | null | Promise<number | null>+ createTime?: CreateTimeProbe}-/** 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> {+/**+ * C1 rule 3 identity of one (pid, recorded ct) pair: `match` = alive with the+ * recorded creation time; `unknown` = alive but no creation time to compare+ * (v1, or the probe was refused); `dead` = gone, a zombie, or a reused pid.+ */+async function processIdentity(+ pid: number,+ recordedCt: number | null,+ deps: MarkerProbeDeps+): Promise<'match' | 'unknown' | 'dead'> {if (!isPidAlive(pid, deps.kill) || isZombieState((deps.processState || posixProcessState)(pid))) {- return false+ return 'dead'}if (recordedCt === null) {- return true+ return 'unknown'}const actual = await (deps.createTime || processCreateTime)(pid)- return actual === null || Math.abs(actual - recordedCt) <= CREATE_TIME_TOLERANCE_S+ if (actual === null) {+ return 'unknown'+ }++ return Math.abs(actual - recordedCt) <= CREATE_TIME_TOLERANCE_S ? 'match' : 'dead'}export type MarkerInspection =| { state: 'absent' }- | { state: 'live'; raw: Buffer; marker: UpdateMarker; ageMs: number; livePid: number }+ /** `marker` is null for a 0-byte claim still being written (A3). */+ | { state: 'live'; raw: Buffer; marker: UpdateMarker | null; 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> {+ const file = markerPath(hermesHome)+ const now = deps.now || Date.nowlet raw: Buffertry {- raw = fs.readFileSync(markerPath(hermesHome))+ raw = fs.readFileSync(file)} catch {return { state: 'absent' }}+ if (raw.length === 0) {+ let ageMs = Infinity++ try {+ ageMs = now() - fs.statSync(file).mtimeMs+ } catch {+ // Gone since the read: nothing to judge.+ }++ return ageMs < EMPTY_MARKER_GRACE_MS+ ? { state: 'live', raw, marker: null, ageMs: Math.max(0, ageMs), livePid: 0 }+ : { state: 'dead', raw, marker: null }+ }+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)+ const ageMs = now() - marker.startedAt * 1000+ const withinCeiling = ageMs <= (deps.maxAgeMs ?? UPDATE_MARKER_MAX_AGE_MS)++ // A1: only a MATCHING creation time is live regardless of age.+ const isLive = (identity: 'match' | 'unknown' | 'dead') =>+ identity === 'match' || (identity === 'unknown' && withinCeiling)- if (!v1Expired && (await processIsLive(marker.pid, marker.ct, deps))) {+ if (isLive(await processIdentity(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))) {+ if (marker.delegate && isLive(await processIdentity(marker.delegate.pid, marker.delegate.ct, deps))) {return { state: 'live', raw, marker, ageMs, livePid: marker.delegate.pid }}@@ -387,9 +460,9 @@ export async function readLiveUpdateMarker(hermesHome: string, deps: MarkerProbeif (inspection.state === 'live') {return {pid: inspection.livePid,- ownerPid: inspection.marker.pid,+ ownerPid: inspection.marker?.pid ?? 0,ageMs: inspection.ageMs,- startedAt: inspection.marker.startedAt+ startedAt: inspection.marker?.startedAt ?? null}}@@ -400,23 +473,32 @@ export async function readLiveUpdateMarker(hermesHome: string, deps: MarkerProbereturn null}+function markerBody(pid: number, startedAt: number, ct: number | null): string {+ return `${pid}\n${startedAt}\n${ct === null ? '' : `ct:${formatCreateTime(ct)}\n`}`+}+/**- * 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+ * Pre-write for the staged Tauri updater (`hermes-setup.exe --update`): the+ * child IS the updater there, so the marker names its pid AND its creation+ * time. A v2 body takes this path off the v1 20-minute ceiling, lets the+ * updater adopt it as its own claim, and lets the `hermes update` it runs add+ * its delegate line (frozen updaters read only lines 1-2). An unreadable ct+ * falls back to a v1 body. Exclusive publish — a live claim is never* overwritten; a dead one is compare-and-deleted first.*/export async function writeUpdateMarker(hermesHome: string,pid: number,{ startedAt, ...deps }: MarkerProbeDeps & { startedAt?: number } = {}-) {+): Promise<ClaimResult> {const acquiredAt =typeof startedAt === 'number' && Number.isInteger(startedAt)? startedAt: Math.floor((deps.now || Date.now)() / 1000)- await createMarkerExclusive(hermesHome, `${pid}\n${acquiredAt}\n`, deps)+ const ct = await (deps.createTime || processCreateTime)(pid)++ return createMarkerExclusive(hermesHome, markerBody(pid, acquiredAt, ct), deps)}interface ClaimResult {@@ -427,25 +509,96 @@ interface ClaimResult {error?: string}+const TMP_SIBLING_RE = /^\.hermes-update-in-progress\.(\d+)(?:\.\d+)?\.tmp$/+let tmpSequence = 0++/** Drop publish/CAS tmp siblings whose writer died between write and link/rename. */+function reclaimDeadTmpSiblings(hermesHome: string) {+ try {+ for (const name of fs.readdirSync(hermesHome)) {+ const pid = Number(TMP_SIBLING_RE.exec(name)?.[1])++ if (pid && !isPidAlive(pid)) {+ fs.rmSync(path.join(hermesHome, name), { force: true })+ }+ }+ } catch {+ // Best effort: litter never blocks a claim.+ }+}++/**+ * Publish `body` at `file` only if nothing is there (A3): write a complete tmp+ * sibling, then hard-link it into place — link(2)/CreateHardLink fail with+ * EEXIST instead of replacing, and a reader never sees a partial body. A+ * filesystem without hard links falls back to O_EXCL create + write.+ */+function publishExclusive(file: string, body: string): 'published' | 'exists' {+ const tmp = `${file}.${process.pid}.${++tmpSequence}.tmp`+ let linked: boolean++ try {+ const fd = fs.openSync(tmp, 'wx', 0o644)++ try {+ fs.writeSync(fd, body)+ fs.fsyncSync(fd)+ } finally {+ fs.closeSync(fd)+ }++ try {+ fs.linkSync(tmp, file)+ linked = true+ } catch (error: any) {+ if (error?.code === 'EEXIST') {+ return 'exists'+ }++ linked = false+ }+ } finally {+ fs.rmSync(tmp, { force: true })+ }++ if (linked) {+ return 'published'+ }++ let fd: number++ try {+ fd = fs.openSync(file, 'wx', 0o644)+ } catch (error: any) {+ if (error?.code === 'EEXIST') {+ return 'exists'+ }++ throw error+ }++ try {+ fs.writeSync(fd, body)+ fs.fsyncSync(fd)+ } finally {+ fs.closeSync(fd)+ }++ return 'published'+}+async function createMarkerExclusive(hermesHome: string, body: string, deps: MarkerProbeDeps): Promise<ClaimResult> {const file = markerPath(hermesHome)+ reclaimDeadTmpSiblings(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)+ if (publishExclusive(file, body) === 'published') {+ return { ok: true, body }}-- return { ok: true, body }} catch (error: any) {- if (error?.code !== 'EEXIST') {- return { ok: false, owner: null, error: error?.message || String(error) }- }+ return { ok: false, owner: null, error: error?.message || String(error) }}const inspection = await inspectUpdateMarker(hermesHome, deps)@@ -467,6 +620,10 @@ async function createMarkerExclusive(hermesHome: string, body: string, deps: Mar}function conflictMessage(owner: { pid: number; ageMs: number }): string {+ if (!owner.pid) {+ return 'Another update is starting right now. Wait for it to finish, then try again.'+ }+const ageMs = Number.isFinite(owner.ageMs) ? Math.max(0, owner.ageMs) : 0const mins = Math.floor(ageMs / 60_000)const secs = Math.floor((ageMs % 60_000) / 1000)@@ -496,8 +653,13 @@ export async function claimBridgeMarker(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`}`++ const acquiredAt =+ typeof startedAt === 'number' && Number.isInteger(startedAt)+ ? startedAt+ : Math.floor((deps.now || Date.now)() / 1000)++ const body = markerBody(pid, acquiredAt, ct)fs.mkdirSync(hermesHome, { recursive: true })const result = await createMarkerExclusive(hermesHome, body, { ...deps, createTime })diff --git a/apps/desktop/electron/updater-process.ts b/apps/desktop/electron/updater-process.tsindex 94cd54700b2..d51aa340c3b 100644--- a/apps/desktop/electron/updater-process.ts+++ b/apps/desktop/electron/updater-process.ts@@ -498,6 +498,67 @@ export function spawnUpdaterProcess(return child}+/**+ * Stop a hand-off the Desktop has given up on (C2 timeout), so a script that+ * starts late cannot run an update the UI already reported as "did not start".+ * POSIX: the detached launcher leads its own process group — kill the group.+ * Windows: the `cmd start /b` wrapper exits at once and PowerShell outlives it,+ * so stop the wrapper's recorded children that carry this Desktop's+ * `-DesktopPid` (a reused pid never matches both), then the wrapper's tree if+ * it is still running. Best effort; the script is adopt-only besides (A4).+ */+export function killHandoffTree(+ child: UpdaterChild & { exitCode?: number | null; signalCode?: string | null },+ {+ isWindows = process.platform === 'win32',+ desktopPid = process.pid,+ kill = process.kill.bind(process),+ spawnProcess = spawn+ }: {+ isWindows?: boolean+ desktopPid?: number+ kill?: typeof process.kill+ spawnProcess?: typeof spawn+ } = {}+): void {+ const pid = child.pid++ if (!Number.isInteger(pid) || !pid || pid <= 0) {+ return+ }++ if (!isWindows) {+ try {+ kill(-pid, 'SIGKILL')+ } catch {+ try {+ kill(pid, 'SIGKILL')+ } catch {+ // Already gone.+ }+ }++ return+ }++ const wrapperRunning = child.exitCode == null && child.signalCode == null++ const command =+ `Get-CimInstance Win32_Process -Filter 'ParentProcessId=${pid}' | ` ++ `Where-Object { $_.CommandLine -match '-DesktopPid\\s+${desktopPid}(\\s|$)' } | ` ++ `ForEach-Object { taskkill.exe /PID $_.ProcessId /T /F | Out-Null }` ++ (wrapperRunning ? `; taskkill.exe /PID ${pid} /T /F | Out-Null` : '')++ try {+ spawnProcess('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], {+ stdio: 'ignore',+ windowsHide: true+ }).on('error', () => {})+ } catch {+ // Best effort.+ }+}+export interface UpdaterHandoffOutcome {ok: boolean/** Set when ok is false. */diff --git a/apps/desktop/electron/updater/checkout-handoff.test.ts b/apps/desktop/electron/updater/checkout-handoff.test.tsindex f4a9191c02c..7f1c19bacc3 100644--- a/apps/desktop/electron/updater/checkout-handoff.test.ts+++ b/apps/desktop/electron/updater/checkout-handoff.test.ts@@ -1,3 +1,4 @@+import type { spawn } from 'node:child_process'import { EventEmitter } from 'node:events'import * as fs from 'node:fs'import * as os from 'node:os'@@ -190,3 +191,65 @@ it('a hand-off whose script never takes the marker keeps the app alive and clearfs.rmSync(root, { recursive: true, force: true })}})++function pidAlive(pid: number): boolean {+ try {+ process.kill(pid, 0)++ return true+ } catch {+ return false+ }+}++// MINOR-3: after the 20 s claim wait gives up, the UI says "the updater did+// not start". A script that starts late must not then run an update anyway:+// the Desktop withdraws its bridge AND kills the launcher tree it spawned.+it.skipIf(IS_WINDOWS)('a timed-out hand-off kills the real script tree it spawned', async (): Promise<void> => {+ const { root, deps } = handoffFixture(false)+ const grandchildPidFile: string = path.join(root, 'late-script.pid')+ let launcherPid: number | undefined+ const realSpawn: typeof updaterProcess.spawnUpdaterProcess = updaterProcess.spawnUpdaterProcess++ vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation(+ (_command: string, _args: string[], options: Parameters<typeof updaterProcess.spawnUpdaterProcess>[2]) => {+ // A real launcher (detached, own process group) whose "script" is slow+ // to start: it would claim the marker 30 s later.+ const child = realSpawn(+ 'bash',+ ['-c', `sleep 30 & echo $! > ${JSON.stringify(grandchildPidFile)}; wait`],+ options+ ) as ReturnType<typeof spawn>++ launcherPid = child.pid++ return child+ }+ )++ try {+ const result = await createCheckoutStrategy({ ...deps, handoffClaimTimeoutMs: 600 }).apply()++ expect(result).toMatchObject({ ok: false, error: 'updater-spawn-failed' })+ expect(fs.existsSync(markerPath(deps.hermesHome))).toBe(false)+ const latePid: number = Number(fs.readFileSync(grandchildPidFile, 'utf8').trim())+ const deadline: number = Date.now() + 3000++ while ((pidAlive(launcherPid!) || pidAlive(latePid)) && Date.now() < deadline) {+ await new Promise(resolve => setTimeout(resolve, 50))+ }++ expect(pidAlive(latePid)).toBe(false)+ expect(pidAlive(launcherPid!)).toBe(false)+ } finally {+ for (const pid of [launcherPid]) {+ try {+ process.kill(-pid!, 'SIGKILL')+ } catch {+ // gone+ }+ }++ fs.rmSync(root, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.tsindex 95403bf11cc..14cd8014644 100644--- a/apps/desktop/electron/updater/checkout.ts+++ b/apps/desktop/electron/updater/checkout.ts@@ -14,6 +14,7 @@ import {import {collectRelaunchArgs,describeUpdaterHandoffFailure,+ killHandoffTree,observeUpdaterHandoff,resolveInstallationLauncher,resolvePosixScriptHandoff,@@ -153,10 +154,23 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStratdeps.rememberLog(`[updates] hand-off not viable, aborting quit: ${failure}`)- if (bridgeBody) {- compareAndDeleteMarker(deps.hermesHome, bridgeBody)+ // Withdraw the bridge first: an adopt-only script that starts late then+ // finds nothing to adopt (A4). If the compare-and-delete misses because+ // the script took the marker at the deadline, the update IS running.+ if (bridgeBody && !compareAndDeleteMarker(deps.hermesHome, bridgeBody)) {+ const late = await waitForHandoffClaim(deps.hermesHome, process.pid, { timeoutMs: 0 })++ if (late.taken) {+ deps.rememberLog(`[updates] hand-off script took the update marker at the deadline (pid ${late.pid})`)++ return null+ }}+ // MINOR-3: and stop the script tree we spawned, so nothing the UI just+ // reported as "did not start" can go on to run.+ killHandoffTree(child)+return failure}@@ -406,7 +420,9 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat// can reconnect into an update still replacing application files.// By writing the marker ourselves the renderer's// waitForUpdateToFinish() gate sees a live update and parks instead.- // The updater overwrites this with its own PID later; same format.+ // The marker names the updater's pid AND creation time (v2): the updater+ // adopts it as its own claim, so no age ceiling applies to a slow update+ // and the `hermes update` it runs can add its delegate line.//// SKIPPED for pre-#74782 staged updaters: those have no self-PID// exclusion, so they read this very marker as a foreign live owner and