The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a held update never opens on a missing script or a misplaced verdict
Tekniumdcc43f695073
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 6dc68c096ab..a4de7acc409 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -634,7 +634,7 @@ import { readSourceUpdate, type SourceUpdate } from './updater/checkout-source'import { ExternalStrategy } from './updater/external'import { readUpdatesFeedBaseFromConfig, resolveFeedBaseUrl } from './updater/feed-config'import { createChannelMacStrategy, createMacStrategy } from './updater/mac-client'-import { handoffScriptPath, readHandoffProtocol, runMarkerHelper } from './updater/marker-helper'+import { runMarkerHelper } from './updater/marker-helper'import { UpdateOperation } from './updater/operation'import {type ConsumedRelaunch,@@ -3010,7 +3010,8 @@ const UPDATE_HANDOFF_DWELL_MS = 2500// `finally` clears updateInFlight immediately after the hand-off is accepted.function updateGateDeps(onLiveMarker?: (marker: { startedAt: number | null }) => void,- onHeld?: (state: HeldState) => void+ onHeld?: (state: HeldState) => void,+ onOverride?: (holdId: string) => void) {// One creation-time probe per pid for this wait: on Windows each probe is a// powershell spawn and the gate polls every second.@@ -3028,16 +3029,12 @@ function updateGateDeps(createTime,onLiveMarker,onHeld,+ onOverride,log: rememberLog,- reclaim: async () => {- const updateRoot = resolveUpdateRoot()-- if (readHandoffProtocol(handoffScriptPath(updateRoot, IS_WINDOWS)) < 2) {- return { kind: 'unsupported' }- }-- return runMarkerHelper('reclaim', { updateRoot, hermesHome: HERMES_HOME, isWindows: IS_WINDOWS })- }+ // A missing or pre-protocol-2 script answers `unsupported`; one that+ // exists but cannot be read answers `error` (R8 M5).+ reclaim: () =>+ runMarkerHelper('reclaim', { updateRoot: resolveUpdateRoot(), hermesHome: HERMES_HOME, isWindows: IS_WINDOWS })}),isUpdateInFlight: () => updateInFlight,isHandoffActive: () => isQuittingForHandoff@@ -3175,11 +3172,20 @@ async function waitForUpdateToFinish() {// when it has blocked this wait (the blocked screen's grace, R8 D3).let held: HeldState | null = nulllet blockedSince: number | null = null+ // The wait ended because the user chose Start anyway, not because the+ // update finished (R8 m7): no bundle-swap relaunch mid-hold.+ let overridden = falseconst gateDeps = updateGateDeps(- marker => (parkedRunStartedAt = marker.startedAt),+ marker => {+ parkedRunStartedAt = marker.startedAt+ overridden = false+ },state => {held = state+ },+ () => {+ overridden = true})@@ -3322,6 +3328,8 @@ async function waitForUpdateToFinish() {if (outcome === 'timeout') {rememberLog('[updates] update still in progress after wait timeout; starting backend anyway')+ } else if (overridden) {+ rememberLog('[updates] proceeding with backend start over a held update (user chose Start anyway); no relaunch')} 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 adiff --git a/apps/desktop/electron/update-marker-gate.test.ts b/apps/desktop/electron/update-marker-gate.test.tsindex 3308efc6e7e..0abb1d68068 100644--- a/apps/desktop/electron/update-marker-gate.test.ts+++ b/apps/desktop/electron/update-marker-gate.test.ts@@ -46,7 +46,11 @@ describe.skipIf(process.platform === 'win32')('gate over a dead marker (R6)', ()root: string,home: string,now?: () => number,- extra: { onHeld?: (state: HeldState) => void; log?: (line: string) => void } = {}+ extra: {+ onHeld?: (state: HeldState) => void+ log?: (line: string) => void+ onOverride?: (holdId: string) => void+ } = {}) {return liveMarkerProbe({hermesHome: home,@@ -93,12 +97,23 @@ describe.skipIf(process.platform === 'win32')('gate over a dead marker (R6)', ()fs.writeFileSync(path.join(home, 'helper-verdict'), 'held')const states: HeldState[] = []const logs: string[] = []- const primary = gate(root, home, undefined, { onHeld: s => states.push(s), log: l => logs.push(l) })+ const overrides: string[] = []++ const primary = gate(root, home, undefined, {+ onHeld: s => states.push(s),+ log: l => logs.push(l),+ onOverride: id => overrides.push(id)+ })assert.equal(await primary(), true)allowStartOverHold(states[0].holdId)assert.equal(await primary(), false, 'the confirmed hold no longer blocks this wait')assert.equal(await primary(), false)+ assert.deepEqual(+ overrides,+ [states[0].holdId, states[0].holdId],+ 'the waiter learns it ended by override, not finish'+ )assert.equal(await gate(root, home)(), false, 'nor a pool backend wait in the same process')assert.equal(logs.filter(l => l.includes('chose Start anyway')).length, 1, 'the override is logged once per wait')assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body, 'the marker stays in place')@@ -107,6 +122,49 @@ describe.skipIf(process.platform === 'win32')('gate over a dead marker (R6)', ()assert.equal(await primary(), true, 'a different marker body is a different hold: blocked again')})+ test('a held body never opens on `unsupported`: a script missing mid-update blocks and is re-asked (R8 M5)', async () => {+ const { root, home } = fakeHelperCheckout()+ fs.writeFileSync(markerPath(home), `${await deadPid()}\n${minutesAgo(1)}\nct:1.000\n`)+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'held')+ const script = path.join(root, 'scripts', 'desktop-update', 'posix.sh')+ const text = fs.readFileSync(script, 'utf8')+ const states: HeldState[] = []+ const probe = gate(root, home, undefined, { onHeld: s => states.push(s) })++ assert.equal(await probe(), true)+ fs.rmSync(script) // git unlinks a changed script before writing the new one+ requestHoldRecheck()+ assert.equal(await probe(), true, 'the body that was held stays blocked')+ assert.deepEqual([states.at(-1)!.verdict, states.at(-1)!.blocking], ['error', true])+ fs.writeFileSync(script, text)+ requestHoldRecheck()+ assert.equal(await probe(), true)+ assert.equal(states.at(-1)!.verdict, 'held', 're-asked once the script is back')+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'reclaimed')+ requestHoldRecheck()+ assert.equal(await probe(), false, 'only the script reclaiming opens it')+ })++ test('two empty dead markers are two holds: Start anyway over one does not pass the next (R8 m7)', async () => {+ const { root, home } = fakeHelperCheckout()+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'held')++ const emptyMarker = (agoS: number) => {+ fs.rmSync(markerPath(home), { force: true })+ fs.writeFileSync(markerPath(home), '')+ const at = Date.now() / 1000 - agoS+ fs.utimesSync(markerPath(home), at, at)+ }++ const states: HeldState[] = []+ emptyMarker(600)+ assert.equal(await gate(root, home, undefined, { onHeld: s => states.push(s) })(), true)+ allowStartOverHold(states[0].holdId)+ assert.equal(await gate(root, home)(), false, 'the confirmed empty marker passes')+ emptyMarker(300) // a later update's empty claim, also past the grace+ assert.equal(await gate(root, home)(), true, 'a different marker file is a different hold')+ })+test('a failing protocol-2 helper keeps the gate parked and is retried after recovery', async () => {const { root, home } = fakeHelperCheckout()const body = `${await deadPid()}\n${minutesAgo(1)}\nct:1.000\n`diff --git a/apps/desktop/electron/update-marker-gate.ts b/apps/desktop/electron/update-marker-gate.tsindex 049eba2994e..6a539628bc5 100644--- a/apps/desktop/electron/update-marker-gate.ts+++ b/apps/desktop/electron/update-marker-gate.ts@@ -11,7 +11,10 @@* - `held` / `busy` / `live <pid>` => an update still owns the checkout: keep waiting;* - `reclaimed` / `absent` => nothing runs: proceed;* - `unsupported` (older checkout, no helper) => proceed without deleting- * (dead = not running, as before minus the deletion).+ * (dead = not running, as before minus the deletion) — unless this process+ * already saw the same body block: then the script is only missing or+ * unreadable for a moment (git rewriting it mid-update), so the answer counts+ * as `error` and is re-asked (review R8 M5).** The helper is asked once per distinct dead marker body per wait; a `held` /* `busy` / `error` / `live` answer is re-asked every `reprobeMs` (5 s), or on@@ -31,8 +34,9 @@*/import { createHash } from 'node:crypto'+import fs from 'node:fs'-import { type CreateTimeProbe, inspectUpdateMarker } from './update-marker'+import { type CreateTimeProbe, inspectUpdateMarker, markerPath } from './update-marker'import type { MarkerHelperVerdict } from './updater/marker-helper'export const HELD_REPROBE_MS = 5_000@@ -65,6 +69,8 @@ export interface LiveMarkerProbeOptions {onLiveMarker?: (marker: { startedAt: number | null }) => void/** Every answer that comes from a running helper verdict (boot progress, the blocked screen). */onHeld?: (state: HeldState) => void+ /** The gate let this wait through over a blocking hold because the user chose Start anyway. */+ onOverride?: (holdId: string) => voidlog?: (line: string) => voidnow?: () => numberreprobeMs?: number@@ -96,9 +102,20 @@ const startAnywayHolds = new Set<string>()// Bumped by an explicit Retry: every probe re-asks the helper on its next poll.let recheckGeneration = 0-/** The stable id of a marker body (what `HeldState.holdId` carries). */-export function markerHoldId(raw: Buffer): string {- return createHash('sha256').update(raw).digest('hex').slice(0, 16)+/**+ * The stable id of one marker file's body (what `HeldState.holdId` carries).+ * The file's inode and mtime are mixed in so two byte-identical bodies — every+ * empty marker, say — written by different updates are different holds+ * (review R8 m7).+ */+export function markerHoldId(raw: Buffer, file?: { ino: number; mtimeMs: number } | null): string {+ const hash = createHash('sha256').update(raw)++ if (file) {+ hash.update(`\0${file.ino}:${file.mtimeMs}`)+ }++ return hash.digest('hex').slice(0, 16)}/**@@ -128,6 +145,7 @@ export function liveMarkerProbe({createTime,onLiveMarker,onHeld,+ onOverride,log,now = Date.now,reprobeMs = HELD_REPROBE_MS@@ -150,7 +168,15 @@ export function liveMarkerProbe({return false}- const holdId = markerHoldId(inspection.raw)+ let file: fs.Stats | null = null++ try {+ file = fs.statSync(markerPath(hermesHome))+ } catch {+ // Gone since the read: the body alone names it until the next poll.+ }++ const holdId = markerHoldId(inspection.raw, file)const previous = asked.get(holdId)let entry = previous@@ -161,7 +187,16 @@ export function liveMarkerProbe({if (due) {const generation = recheckGeneration- const verdict = await reclaim()+ let verdict = await reclaim()++ // A body that blocked never clears on `unsupported`: the checkout's+ // script went missing or unreadable after answering for it (R8 M5).+ if (+ verdict.kind === 'unsupported' &&+ (STILL_RUNNING.has(previous?.verdict.kind ?? '') || firstHeldAt.has(holdId))+ ) {+ verdict = { kind: 'error' }+ }if (!previous || STILL_RUNNING.has(previous.verdict.kind) !== STILL_RUNNING.has(verdict.kind)) {log?.(@@ -198,6 +233,8 @@ export function liveMarkerProbe({)}+ onOverride?.(holdId)+return false}diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.tsindex 6e01ef7a5aa..e1c04658d61 100644--- a/apps/desktop/electron/updater/checkout.ts+++ b/apps/desktop/electron/updater/checkout.ts@@ -144,7 +144,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStratscriptPath: string,updateStartedAt: number): Promise<{ plan: HandoffPlan } | { refusal: UpdaterApplyResultWire }> {- const protocol = readHandoffProtocol(scriptPath)+ const protocol = readHandoffProtocol(scriptPath) ?? 1if (protocol < 2) {deps.rememberLog('[updates] hand-off script predates protocol 2; legacy acknowledgment (live owner + started_at)')diff --git a/apps/desktop/electron/updater/marker-helper.test.ts b/apps/desktop/electron/updater/marker-helper.test.tsindex 61d0749146c..4d2ee652083 100644--- a/apps/desktop/electron/updater/marker-helper.test.ts+++ b/apps/desktop/electron/updater/marker-helper.test.ts@@ -68,9 +68,8 @@ test.each([describe.skipIf(process.platform === 'win32')('runMarkerHelper against a real script process', () => {test.each([- ['reclaimed', { kind: 'reclaimed' }],- ['held', { kind: 'held' }],- ['live 31337', { kind: 'live', pid: 31337 }],+ ['foreign', { kind: 'foreign' }],+ ['busy', { kind: 'busy' }],['taken 99', { kind: 'taken', pid: 99 }],['withdrawn', { kind: 'withdrawn' }]])('prints %j', async (verdict, expected) => {@@ -118,6 +117,39 @@ describe.skipIf(process.platform === 'win32')('runMarkerHelper against a real sc})})+ test('a verdict only the other op can give is an error, never clearance (R8 m7)', async () => {+ const { root, home } = fakeHelperCheckout()+ const opts = { updateRoot: root, hermesHome: home, desktopPid: 4242, runId: 'desk-4242-abc-0001', isWindows: false }++ for (const [op, verdict, expected] of [+ ['reclaim', 'live 31337', 'live'],+ ['reclaim', 'held', 'held'],+ ['reclaim', 'reclaimed', 'reclaimed'],+ ['reclaim', 'foreign', 'error'],+ ['reclaim', 'withdrawn', 'error'],+ ['reclaim', 'taken 99', 'error'],+ ['withdraw', 'held', 'error'],+ ['withdraw', 'reclaimed', 'error'],+ ['withdraw', 'live 31337', 'error']+ ] as const) {+ fs.writeFileSync(path.join(home, 'helper-verdict'), verdict)+ assert.equal((await runMarkerHelper(op, opts)).kind, expected, `${op} => ${verdict}`)+ }+ })++ test.skipIf(process.getuid?.() === 0)(+ 'a script that exists but cannot be read is an error, never an older checkout (R8 M5)',+ async () => {+ const { root, home } = fakeHelperCheckout()+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'reclaimed')+ fs.chmodSync(path.join(root, 'scripts', 'desktop-update', 'posix.sh'), 0o000)++ assert.deepEqual(await runMarkerHelper('reclaim', { updateRoot: root, hermesHome: home, isWindows: false }), {+ kind: 'error'+ })+ }+ )+test('a helper past its timeout is killed and reports error', async () => {const { root, home } = fakeHelperCheckout()fs.writeFileSync(path.join(home, 'helper-verdict'), 'reclaimed')diff --git a/apps/desktop/electron/updater/marker-helper.ts b/apps/desktop/electron/updater/marker-helper.tsindex 2f9ba42dc59..19940e8cddf 100644--- a/apps/desktop/electron/updater/marker-helper.ts+++ b/apps/desktop/electron/updater/marker-helper.ts@@ -9,10 +9,12 @@* Windows: powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File windows.ps1* -MarkerOp <op> -InstallRoot <root> [-DesktopPid P] [-HandoffRun R]*- * One stdout line: `absent | reclaimed | held | busy | live <pid> | withdrawn |- * taken <pid> | foreign`. Anything else, a nonzero exit, a timeout or- * malformed output is `error` (retry without clearance). Only a missing or- * pre-protocol-2 script is `unsupported` (an older checkout).+ * One stdout line: reclaim `absent | reclaimed | held | busy | live <pid>`,+ * withdraw `absent | busy | withdrawn | taken <pid> | foreign`. Anything else+ * (another op's word included), a nonzero exit, a timeout, malformed output+ * or a script that exists but cannot be read is `error` (retry without+ * clearance). Only a missing or pre-protocol-2 script is `unsupported` (an+ * older checkout).*/import { type ChildProcess, spawn } from 'node:child_process'@@ -65,8 +67,13 @@ export function handoffScriptPath(updateRoot: string, isWindows: boolean): strinreturn existsSync(posix) ? posix : null}-/** Hand-off protocol a script speaks: 2+ from its protocol line, else 1 (legacy). */-export function readHandoffProtocol(scriptPath: string | null | undefined): number {+/**+ * Hand-off protocol a script speaks: 2+ from its protocol line, else 1+ * (legacy, a missing script included). Null when the script exists but cannot+ * be read right now (a sharing violation, permissions): that is not an older+ * checkout (review R8 M5).+ */+export function readHandoffProtocol(scriptPath: string | null | undefined): number | null {if (!scriptPath) {return 1}@@ -76,8 +83,8 @@ export function readHandoffProtocol(scriptPath: string | null | undefined): numbconst version = match ? Number(match[1]) : 1return Number.isSafeInteger(version) && version >= 2 ? version : 1- } catch {- return 1+ } catch (error) {+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT' ? 1 : null}}@@ -136,6 +143,12 @@ const defaultSpawn: HelperSpawn = (command, args, { env, timeout, windowsHide })const BARE_VERDICTS = new Set(['absent', 'reclaimed', 'held', 'busy', 'withdrawn', 'foreign'])+/** The words each op can answer (marker.sh marker_op, marker-claim.ps1 Invoke-MarkerOp). */+const OP_VERDICTS: Record<MarkerHelperOp, ReadonlySet<string>> = {+ reclaim: new Set(['absent', 'reclaimed', 'held', 'busy', 'live']),+ withdraw: new Set(['absent', 'busy', 'withdrawn', 'taken', 'foreign'])+}+/** Parse the helper's one verdict line; anything else is an operational error. */export function parseMarkerHelperVerdict(stdout: string): MarkerHelperVerdict {const lines = stdout.split(/\r?\n/).map(line => line.trim()).filter(Boolean)@@ -208,8 +221,13 @@ export function markerHelperCommand(/** Run one marker op through the checkout's script under its sidecar lock. */export async function runMarkerHelper(op: MarkerHelperOp, options: MarkerHelperOptions): Promise<MarkerHelperVerdict> {const scriptPath = handoffScriptPath(options.updateRoot, options.isWindows)+ const protocol = readHandoffProtocol(scriptPath)- if (!scriptPath || readHandoffProtocol(scriptPath) < 2) {+ if (protocol === null) {+ return { kind: 'error' }+ }++ if (!scriptPath || protocol < 2) {return { kind: 'unsupported' }}@@ -222,7 +240,9 @@ export async function runMarkerHelper(op: MarkerHelperOp, options: MarkerHelperOwindowsHide: true})- return result.code === 0 ? parseMarkerHelperVerdict(result.stdout) : { kind: 'error' }+ const verdict: MarkerHelperVerdict = result.code === 0 ? parseMarkerHelperVerdict(result.stdout) : { kind: 'error' }++ return OP_VERDICTS[op].has(verdict.kind) || verdict.kind === 'error' ? verdict : { kind: 'error' }} catch {return { kind: 'error' }}