The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): correlate handoff receipts with stable run identity
Tekniumb5852b3187e6
diff --git a/apps/desktop/electron/handoff-result-producer.test.ts b/apps/desktop/electron/handoff-result-producer.test.tsnew file mode 100644index 00000000000..38341d6bd81--- /dev/null+++ b/apps/desktop/electron/handoff-result-producer.test.ts@@ -0,0 +1,143 @@+import assert from 'node:assert/strict'+import { type ChildProcess, spawn } from 'node:child_process'+import { once } from 'node:events'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { setTimeout as sleep } from 'node:timers/promises'++import { test } from 'vitest'++import { handoffResultPath, readAndConsumeHandoffResult } from './handoff-result'+import { claimBridgeMarker, markerPath, parseUpdateMarker } from './update-marker'+import { liveMarkerProbe } from './update-marker-gate'++async function stop(child: ChildProcess) {+ if (child.exitCode !== null || child.signalCode !== null) {+ return+ }++ const exited = once(child, 'exit')+ child.kill('SIGKILL')+ await exited+}++test.skipIf(process.platform === 'win32').each(['legacy', 'protocol-2'])(+ '%s POSIX producer receipt survives heartbeat and a newly opened gate',+ async mode => {+ const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'handoff-correlation-'))+ const home = path.join(fixture, 'home')+ const root = path.join(fixture, 'checkout')+ const temp = path.join(fixture, 'temp')++ for (const dir of [home, temp, path.join(root, 'pm')]) {+ fs.mkdirSync(dir, { recursive: true })+ }++ // No launcher: the actual hand-off fails without invoking an update, gateway or app.+ const script = path.resolve(__dirname, '../../../scripts/desktop-update/posix.sh')+ const desktop = spawn('sleep', ['60'])+ const startedAt = Math.floor(Date.now() / 1000) - 10+ const runId = mode === 'protocol-2' ? 'receipt-test.bridge-2' : undefined+ const bridge = await claimBridgeMarker(home, { pid: desktop.pid, startedAt, runId })+ assert.equal(bridge.ok, true)++ const child = spawn(+ 'bash',+ [+ script,+ '--daemonized',+ '--install-root',+ root,+ '--desktop-pid',+ String(desktop.pid),+ '--no-ui',+ '--self-test-refresh-every',+ '1',+ ...(runId ? ['--handoff-run', runId] : [])+ ],+ {+ env: {+ ...process.env,+ HOME: fixture,+ HERMES_HOME: home,+ TMPDIR: temp,+ HERMES_UPDATE_STARTED_AT: String(startedAt),+ HERMES_UPDATE_SHIM_GRACE_SECONDS: '0'+ },+ stdio: ['ignore', 'pipe', 'pipe']+ }+ )++ let output = ''+ child.stdout!.on('data', chunk => {+ output += chunk+ })+ child.stderr!.on('data', chunk => {+ output += chunk+ })+ const exited = once(child, 'exit')+ const observed: { startedAt: number | null; runId?: string | null }[] = []+ const probe = liveMarkerProbe({ hermesHome: home, reclaim: null, onLiveMarker: marker => observed.push(marker) })++ try {+ const deadline = Date.now() + 15_000++ while (Date.now() < deadline) {+ await probe()+ const marker = parseUpdateMarker(fs.readFileSync(markerPath(home), 'utf8'))++ if (marker?.pid === child.pid && marker.startedAt! > startedAt) {+ break+ }++ await sleep(50)+ }++ const refreshed = parseUpdateMarker(fs.readFileSync(markerPath(home), 'utf8'))!+ assert.equal(refreshed.pid, child.pid, output)+ assert.ok(refreshed.startedAt! > startedAt, 'the actual refresher must advance line 2')+ await probe()+ // No remembered first observation: this is a Desktop opened AFTER the refresh.+ let reopened: { startedAt: number | null; runId?: string | null } = { startedAt: null }++ const reopenedGate = liveMarkerProbe({+ hermesHome: home,+ reclaim: null,+ onLiveMarker: marker => {+ reopened = marker+ }+ })++ assert.equal(await reopenedGate(), true)+ await stop(desktop)+ const [code] = await exited+ assert.equal(code, 3, output)+ const receipt = JSON.parse(fs.readFileSync(handoffResultPath(home), 'utf8'))+ assert.equal(receipt.started_at, startedAt)++ const result = readAndConsumeHandoffResult(home, {+ expectedStartedAt: reopened.startedAt,+ expectedRunId: reopened.runId+ })++ assert.equal(result?.ok, false, `own failure must not be discarded: ${JSON.stringify(receipt)}`)+ assert.equal(result?.exitCode, 3)+ assert.match(receipt.run_id, /^[A-Za-z0-9._-]{1,128}$/)+ assert.equal(receipt.run_id, refreshed.run)+ assert.equal(reopened.runId, receipt.run_id)+ assert.equal(observed.at(-1)?.runId, receipt.run_id)++ if (runId) {+ assert.equal(receipt.run_id, runId, 'adoption preserves the Desktop identity')+ }++ assert.equal(readAndConsumeHandoffResult(home), null, 'reported once')+ } finally {+ await stop(desktop)+ await stop(child)+ fs.rmSync(fixture, { recursive: true, force: true })+ }+ },+ 30_000+)diff --git a/apps/desktop/electron/handoff-result.test.ts b/apps/desktop/electron/handoff-result.test.tsindex ec016438c2f..c88fea897a0 100644--- a/apps/desktop/electron/handoff-result.test.ts+++ b/apps/desktop/electron/handoff-result.test.ts@@ -69,8 +69,43 @@ test('malformed JSON is logged and kept as .corrupt, not reported', () => {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('stable run identity outranks heartbeat time; only legacy receipts use timestamp correlation', () => {+ const home = tempHome()+ const finished_at = Math.floor(Date.now() / 1000)++ const outcomes = [+ { ok: false, exit_code: 3, message: 'failed' },+ { ok: true, exit_code: 0, manual: true, message: 'reopen manually' },+ { ok: true, exit_code: 0, warnings: ['gateway restart'] }+ ]++ for (const outcome of outcomes) {+ const receipt = { ...outcome, started_at: 100, finished_at }+ write(home, { ...receipt, run_id: 'own-run' })+ assert.ok(readAndConsumeHandoffResult(home, { expectedRunId: 'own-run', expectedStartedAt: 200 }))++ for (const run_id of ['foreign-run', '', null, 42, 'bad run', 'own-run\n']) {+ write(home, { ...receipt, run_id })+ assert.equal(readAndConsumeHandoffResult(home, { expectedRunId: 'own-run', expectedStartedAt: 100 }), null)+ }++ // An older script has no run_id, even if its marker carried a run: line.+ write(home, receipt)+ assert.ok(readAndConsumeHandoffResult(home, { expectedRunId: 'own-run', expectedStartedAt: 100 }))+ write(home, receipt)+ assert.equal(readAndConsumeHandoffResult(home, { expectedRunId: 'own-run', expectedStartedAt: 200 }), null)+ // Older markers and post-update boots have no expected stable identity.+ write(home, { ...receipt, run_id: 'own-run' })+ assert.ok(readAndConsumeHandoffResult(home, { expectedStartedAt: 100 }))+ write(home, { ...receipt, run_id: 'own-run' })+ assert.ok(readAndConsumeHandoffResult(home))+ }++ fs.rmSync(home, { recursive: true, force: true })+})++// Legacy producers correlate 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)diff --git a/apps/desktop/electron/handoff-result.ts b/apps/desktop/electron/handoff-result.tsindex aeccb140509..6f7ecf37702 100644--- a/apps/desktop/electron/handoff-result.ts+++ b/apps/desktop/electron/handoff-result.ts@@ -26,6 +26,8 @@import fs from 'fs'import path from 'path'+import { RUN_ID_RE } from './update-marker-judge'+export const HANDOFF_RESULT_MAX_AGE_MS = 30 * 60 * 1000export interface HandoffResult {@@ -49,9 +51,9 @@ export function handoffResultPath(hermesHome: string): string {/*** 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.+ * inspectable. Match the stable marker run ID, not line 2 (a heartbeat that+ * can change before this Desktop even opens). Only older producers without+ * run_id, or boots without an identified marker, use started_at correlation.*/export function readAndConsumeHandoffResult(hermesHome: string,@@ -59,8 +61,15 @@ export function readAndConsumeHandoffResult(now = Date.now,maxAgeMs = HANDOFF_RESULT_MAX_AGE_MS,expectedStartedAt = null,+ expectedRunId = null,log = () => {}- }: { now?: () => number; maxAgeMs?: number; expectedStartedAt?: number | null; log?: (line: string) => void } = {}+ }: {+ now?: () => number+ maxAgeMs?: number+ expectedStartedAt?: number | null+ expectedRunId?: string | null+ log?: (line: string) => void+ } = {}): HandoffResult | null {const file = handoffResultPath(hermesHome)let raw: string@@ -105,7 +114,23 @@ export function readAndConsumeHandoffResult(return null}- if (expectedStartedAt !== null && Number.isFinite(startedAt) && startedAt !== expectedStartedAt) {+ const runId = parsed?.run_id++ // Missing means legacy. A present but malformed ID must not downgrade to+ // weaker timestamp matching (nor be normalized into another run).+ if (runId !== undefined && (typeof runId !== 'string' || RUN_ID_RE.exec(runId)?.[0] !== runId)) {+ log('[updates] hand-off result has an invalid run_id; discarded')++ return null+ }++ if (expectedRunId !== null && runId !== undefined) {+ if (runId !== expectedRunId) {+ log(`[updates] hand-off result is for run ${runId}, not ${expectedRunId}; discarded`)++ return null+ }+ } else if (expectedStartedAt !== null && Number.isFinite(startedAt) && startedAt !== expectedStartedAt) {log(`[updates] hand-off result is for the run started at ${startedAt}, not ${expectedStartedAt}; discarded`)return nulldiff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 011f30b780b..2f41dde722b 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -3027,9 +3027,9 @@ const showUpdateHold = updateHoldScreen.showasync function waitForUpdateToFinish() {let announced = falselet 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+ // Stable across heartbeat refreshes, including when first opened mid-update.+ // Keep line 2 only for compatibility with older result producers.+ let parkedRun: { startedAt: number | null; runId: string | null } = { startedAt: null, runId: null }// A dead marker whose checkout a leftover process still holds (R6), or whose// ownership the helper could not establish (the blocked screen, R8 D3).const hold = holdTicker({ show: state => showUpdateHold(state), clear: () => clearUpdateHold() })@@ -3039,7 +3039,7 @@ async function waitForUpdateToFinish() {const gateDeps = updateGateDeps({onLiveMarker: marker => {- parkedRunStartedAt = marker.startedAt+ parkedRun = markeroverridden = false},onHeld: hold.onHeld,@@ -3105,7 +3105,8 @@ async function waitForUpdateToFinish() {// failed: consumed once, here, where boot passes the update gate.reportHandoffResult({hermesHome: HERMES_HOME,- expectedStartedAt: parkedRunStartedAt,+ expectedStartedAt: parkedRun.startedAt,+ expectedRunId: parkedRun.runId,log: rememberLog,dialog,shell,diff --git a/apps/desktop/electron/update-handoff-report.ts b/apps/desktop/electron/update-handoff-report.tsindex 8018950e051..a616d8f4f4d 100644--- a/apps/desktop/electron/update-handoff-report.ts+++ b/apps/desktop/electron/update-handoff-report.ts@@ -10,6 +10,8 @@ export interface HandoffReportHost {hermesHome: string/** Marker line 2 of the run this boot parked on (C2 started_at match), else null. */expectedStartedAt: number | null+ /** Stable run id of that marker (survives heartbeat refreshes), else null. */+ expectedRunId: string | nulllog: (line: string) => voiddialog: Pick<Dialog, 'showMessageBox'>shell: Pick<Shell, 'showItemInFolder'>@@ -29,6 +31,7 @@ export function reportHandoffResult(host: HandoffReportHost): void {try {const result = readAndConsumeHandoffResult(host.hermesHome, {expectedStartedAt: host.expectedStartedAt,+ expectedRunId: host.expectedRunId,log: host.log})diff --git a/apps/desktop/electron/update-hold-wiring.ts b/apps/desktop/electron/update-hold-wiring.tsindex 2601f19b47c..0e423655a09 100644--- a/apps/desktop/electron/update-hold-wiring.ts+++ b/apps/desktop/electron/update-hold-wiring.ts@@ -24,7 +24,7 @@ import {import { runMarkerHelper } from './updater/marker-helper'export interface MarkerGateCallbacks {- onLiveMarker?: (marker: { startedAt: number | null }) => void+ onLiveMarker?: (marker: { startedAt: number | null; runId: string | null }) => voidonHeld?: (state: HeldState) => voidonOverride?: (holdId: string) => void}diff --git a/apps/desktop/electron/update-marker-gate.ts b/apps/desktop/electron/update-marker-gate.tsindex 4d22f10a6e5..3a97a86619c 100644--- a/apps/desktop/electron/update-marker-gate.ts+++ b/apps/desktop/electron/update-marker-gate.ts@@ -81,7 +81,7 @@ export interface LiveMarkerProbeOptions {/** The script helper `reclaim`, or null when the checkout's script predates protocol 2. */reclaim: (() => Promise<MarkerHelperVerdict>) | nullcreateTime?: CreateTimeProbe- onLiveMarker?: (marker: { startedAt: number | null }) => void+ onLiveMarker?: (marker: { startedAt: number | null; runId: string | 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. */@@ -353,7 +353,7 @@ export function liveMarkerProbe({return false}- onLiveMarker?.({ startedAt: inspection.marker?.startedAt ?? null })+ onLiveMarker?.({ startedAt: inspection.marker?.startedAt ?? null, runId: inspection.marker?.run ?? null })return true}@@ -401,7 +401,7 @@ export function liveMarkerProbe({}onHeld?.(state)- onLiveMarker?.({ startedAt: inspection.marker?.startedAt ?? null })+ onLiveMarker?.({ startedAt: inspection.marker?.startedAt ?? null, runId: inspection.marker?.run ?? null })return true}diff --git a/scripts/desktop-update/marker-claim.ps1 b/scripts/desktop-update/marker-claim.ps1index f905b3d53bf..02f7b8dfa94 100644--- a/scripts/desktop-update/marker-claim.ps1+++ b/scripts/desktop-update/marker-claim.ps1@@ -14,8 +14,8 @@function Write-MarkerOwnClaim([bool]$Exists, [int64]$Started, $Run, [string]$Verb) {# Caller holds the lock. Our canonical claim, published or rewritten.- $runs = @()- if ($Run) { $runs = @("run:$Run") }+ if (-not $Run) { $Run = $script:ResultRunId }+ $runs = @("run:$Run")$body = Format-MarkerBody $PID $Started $script:MarkerOwnCtText $null $runs$ok = if ($Exists) { Set-MarkerBodyLocked $body } else { (Publish-MarkerNew $body) -eq 'published' }if (-not $ok) {@@ -135,6 +135,9 @@ function Invoke-MarkerAdoptLegacy($Read, [int]$Desktop) {function Invoke-MarkerClaim {# The FIRST act of windows.ps1. Returns claimed | adopted | refused.+ # Keep adopt-only HandoffRun separate: old Desktop / direct launches also+ # need a stable result identity, but must retain their legacy claim rules.+ $script:ResultRunId = if ($HandoffRun) { $HandoffRun } else { [Guid]::NewGuid().ToString("N") }$epoch = Get-UnixNow$startedAt = 0L$hasStartedAt = [int64]::TryParse($env:HERMES_UPDATE_STARTED_AT, [ref]$startedAt)diff --git a/scripts/desktop-update/marker.sh b/scripts/desktop-update/marker.shindex 591a98769c4..2318129ffc4 100644--- a/scripts/desktop-update/marker.sh+++ b/scripts/desktop-update/marker.sh@@ -267,10 +267,11 @@ marker_young_empty() { # A3 fallback writers create then write: a fresh empty fi[ -n "$mtime" ] && [ $(( $(marker_now) - mtime )) -lt 5 ]}-marker_own_body() { # started -> our canonical claim (run line = the Desktop's hand-off run)+marker_own_body() { # started -> our canonical claim (stable result / hand-off identity)[ -n "$MY_CT" ] || MY_CT="$(proc_ct "$MY_PID")"M_RUNS=""- [ -z "$HANDOFF_RUN" ] || M_RUNS="run:$HANDOFF_RUN"$'\n'+ local run="${RESULT_RUN_ID:-$HANDOFF_RUN}"+ [ -z "$run" ] || M_RUNS="run:$run"$'\n'MARKER_BODY="$(marker_canonical "$MY_PID" "$1" "$MY_CT")"$'\n'}diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.shindex b0459e472c4..39be9246fb9 100755--- a/scripts/desktop-update/posix.sh+++ b/scripts/desktop-update/posix.sh@@ -100,6 +100,9 @@ LOG="$LOG_DIR/desktop-update-handoff.log"RESULT="$HERMES_HOME/.hermes-update-result.json"STATUS="${TMPDIR:-/tmp}/hermes-update-status.$$"STARTED_AT="$(date +%s)" # the shim's elapsed clock; see serve-ui.py+# Separate identity from both heartbeat time and adopt-only HANDOFF_RUN.+# Old Desktop / direct launches need an ID too, without changing claim rules.+RESULT_RUN_ID="${HANDOFF_RUN:-posix-$$-${STARTED_AT}-${RANDOM}}"UI_SERVER_PID="" UI_BROWSER_PID="" UI_PANEL_PID="" UI_PROFILE_DIR="" FINAL_CODE=1FINAL_MSG="update did not complete"@@ -618,16 +621,16 @@ launch_app() { # attempted BEFORE the terminal event (launch acceptance isMANUAL=0 # 1 = update landed but the user must act (result protocol field)-write_result() { # atomic (tmp + rename); started_at ties it to marker line 2+write_result() { # atomic (tmp + rename); run_id survives marker line-2 heartbeatslocal w="" itemfor item in ${WARNINGS[@]+"${WARNINGS[@]}"}; dow="$w${w:+,}\"$(json_escape "$item")\""done- printf '{"ok":%s,"exit_code":%s,"manual":%s,"message":"%s","branch":"%s","channel":"%s","started_at":%s,"finished_at":%s,"warnings":[%s]}' \+ printf '{"ok":%s,"exit_code":%s,"manual":%s,"message":"%s","branch":"%s","channel":"%s","run_id":"%s","started_at":%s,"finished_at":%s,"warnings":[%s]}' \"$([ "$FINAL_CODE" -eq 0 ] && echo true || echo false)" "$FINAL_CODE" \"$([ "$MANUAL" -eq 1 ] && echo true || echo false)" \"$(json_escape "$FINAL_MSG")" "$(json_escape "$BRANCH")" "$(json_escape "$CHANNEL")" \- "${STARTED_AT:-0}" "$(date +%s)" "$w" \+ "$RESULT_RUN_ID" "${STARTED_AT:-0}" "$(date +%s)" "$w" \> "$RESULT.$$.tmp" 2>/dev/null && mv -f "$RESULT.$$.tmp" "$RESULT" 2>/dev/nullrm -f "$RESULT.$$.tmp" 2>/dev/null || true}diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1index 53a33c89381..35599783428 100644--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@ -676,8 +676,8 @@ function Write-Result([bool]$Ok, [int]$Code, [string]$Message, [bool]$ManualActi# ok result the user still must act on -- the Desktop surfaces those in# a dialog, not just the log (same protocol as posix.sh).# Atomic (tmp + rename over): a reader never sees a torn file, and the- # previous result survives until this one is complete. started_at equals- # marker line 2 so the Desktop can match the result to its run.+ # previous result survives until this one is complete. run_id matches the+ # marker across heartbeat rewrites; started_at stays for older consumers.try {$obj = @{ok = $Ok@@ -686,6 +686,7 @@ function Write-Result([bool]$Ok, [int]$Code, [string]$Message, [bool]$ManualActimessage = $Messagebranch = $Branchchannel = $Channel+ run_id = $script:ResultRunIdstarted_at = $script:StartedAtwarnings = @($script:Warnings)finished_at = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()diff --git a/tests/scripts/desktop_update/test_desktop_update_posix_marker.py b/tests/scripts/desktop_update/test_desktop_update_posix_marker.pyindex e927a3bbd1f..5f39d75ce00 100644--- a/tests/scripts/desktop_update/test_desktop_update_posix_marker.py+++ b/tests/scripts/desktop_update/test_desktop_update_posix_marker.py@@ -209,7 +209,8 @@ def test_desktop_bridge_marker_is_adopted_with_its_started_at(tmp_path, sleeper)result = _run(tmp_path, home, install, "--desktop-pid", str(desktop.pid), "--self-test-marker")assert result.returncode == 0, result.stdout + result.stderr- pid, started_at, ct = marker.read_text(encoding="utf-8-sig").splitlines()+ pid, started_at, ct, *tags = marker.read_text(encoding="utf-8-sig").splitlines()+ assert any(tag.startswith("run:") for tag in tags)assert pid != str(desktop.pid) and int(pid) > 0assert started_at == str(started)assert ct.startswith("ct:") and len(ct.split(".")[-1]) == 3@@ -275,14 +276,16 @@ def test_script_killed_right_after_spawning_the_update_leaves_a_live_marker(tmp_time.sleep(0.01)# Kill the script the moment the delegate line is there (at most 3 s after the spawn).settle = time.monotonic() + 3- while time.monotonic() < settle and len(marker.read_text(encoding="utf-8-sig").splitlines()) < 4:+ while time.monotonic() < settle and not any(+ line.startswith("delegate:") for line in marker.read_text(encoding="utf-8-sig").splitlines()+ ):time.sleep(0.005)script.kill()script.wait(timeout=10)child = int(child_pid_file.read_text(encoding="utf-8-sig"))lines = marker.read_text(encoding="utf-8-sig").splitlines()assert lines[0] == str(script.pid)- assert len(lines) == 4 and lines[3].startswith("delegate:"), lines+ assert lines[3].startswith("delegate:"), linesdelegate = int(lines[3].split()[0].split(":")[1])assert delegate in _ancestry(child) # the update process (or its exec-ing launcher)assert lines[3] == f"delegate:{delegate} ct:{_ct(delegate)}"diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_marker.py b/tests/scripts/desktop_update/test_desktop_update_windows_marker.pyindex 06316faf280..430af7c8b56 100644--- a/tests/scripts/desktop_update/test_desktop_update_windows_marker.py+++ b/tests/scripts/desktop_update/test_desktop_update_windows_marker.py@@ -324,14 +324,14 @@ def test_script_killed_right_after_spawning_the_update_leaves_a_live_marker(tmp_time.sleep(0.02)# Kill the script the moment the delegate line is there (at most 3 s after the spawn).settle = time.monotonic() + 3- while time.monotonic() < settle and len(_marker_lines(marker)) < 4:+ while time.monotonic() < settle and not any(line.startswith('delegate:') for line in _marker_lines(marker)):time.sleep(0.01)subprocess.run(['taskkill', '/F', '/PID', str(script.pid)], capture_output=True, check=True)script.wait(timeout=30)child = int(child_pid_file.read_text(encoding='utf-8-sig'))lines = marker.read_bytes().decode().splitlines()assert lines[0] == str(script.pid)- assert len(lines) == 4 and lines[3].startswith('delegate:'), lines+ assert lines[3].startswith('delegate:'), linesdelegate = int(lines[3].split()[0].split(':')[1])assert delegate in (child, _parent_pid(child), _parent_pid(_parent_pid(child))) # update or its launcherassert lines[3] == f'delegate:{delegate} ct:{_creation_time(delegate)}'diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_marker_lock.py b/tests/scripts/desktop_update/test_desktop_update_windows_marker_lock.pyindex f8cf44132b5..362946b8105 100644--- a/tests/scripts/desktop_update/test_desktop_update_windows_marker_lock.py+++ b/tests/scripts/desktop_update/test_desktop_update_windows_marker_lock.py@@ -141,7 +141,8 @@ def test_script_killed_before_publishing_the_delegate_runs_no_update(tmp_path: Passert not ran.exists(), 'the update child ran before it was published as the delegate'assert not _alive(child_pid), 'the never-resumed update child outlived its script'lines = marker.read_bytes().decode().split('\n')- assert lines[0] == str(script.pid) and len(lines) == 4 and lines[3] == '', lines # no delegate line+ assert lines[0] == str(script.pid), lines+ assert not any(line.startswith('delegate:') for line in lines), linesfinally:if lock:lock.release()diff --git a/tests/scripts/desktop_update/test_handoff_result_identity.py b/tests/scripts/desktop_update/test_handoff_result_identity.pynew file mode 100644index 00000000000..6055094cafa--- /dev/null+++ b/tests/scripts/desktop_update/test_handoff_result_identity.py@@ -0,0 +1,72 @@+"""Real PowerShell producer/heartbeat/result contract (portable, not native UI proof)."""+from __future__ import annotations++import json+import os+from pathlib import Path+import shutil+import subprocess++import pytest+++ROOT = Path(__file__).resolve().parents[3]+POWERSHELL = shutil.which("powershell") or shutil.which("pwsh")++[email protected]("any")[email protected]("run_id", ["", "receipt-test.bridge-2"])+def test_powershell_result_keeps_identity_after_actual_heartbeat(tmp_path: Path, run_id: str) -> None:+ if not POWERSHELL:+ pytest.skip("PowerShell is not installed")+ home = tmp_path / "home"+ home.mkdir()+ install = tmp_path / "checkout"+ (install / "pm").mkdir(parents=True)+ harness = tmp_path / "receipt.ps1"+ harness.write_text(r'''+param([string]$HandoffPath, [string]$Install, [string]$Run)+$started = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() - 10+$env:HERMES_UPDATE_STARTED_AT = [string]$started+$marker = Join-Path $env:HERMES_HOME '.hermes-update-in-progress'+$invoke = @{ InstallRoot = $Install; NoUi = $true }+if ($Run) {+ $ct = [DateTimeOffset]::new([Diagnostics.Process]::GetCurrentProcess().StartTime.ToUniversalTime()).ToUnixTimeMilliseconds() / 1000.0+ $ctText = $ct.ToString('F3', [Globalization.CultureInfo]::InvariantCulture)+ [IO.File]::WriteAllText($marker, "$PID`n$started`nct:$ctText`nrun:$Run`n")+ $invoke.DesktopPid = $PID+ $invoke.HandoffRun = $Run+}+# Schedule a real heartbeat immediately before the real result writer. No+# function replacement, result JSON fabrication, or Windows-host emulation.+$breakpoint = Set-PSBreakpoint -Command Write-Result -Action {+ $script:MarkerLastHeartbeat = (Get-Date).AddMinutes(-10)+ Update-MarkerHeartbeat+ [IO.File]::Copy($MarkerPath, "$MarkerPath.observed", $true)+}+& $HandoffPath @invoke+Remove-PSBreakpoint $breakpoint+''', encoding="utf-8")+ result = subprocess.run(+ [POWERSHELL, "-NoProfile", "-NonInteractive", "-File", str(harness),+ "-HandoffPath", str(ROOT / "scripts/desktop-update/windows.ps1"),+ "-Install", str(install), "-Run", run_id],+ env={**os.environ, "HOME": str(home), "HERMES_HOME": str(home),+ "TEMP": str(tmp_path), "TMP": str(tmp_path)},+ capture_output=True, text=True, timeout=60,+ )+ receipt = json.loads((home / ".hermes-update-result.json").read_text(encoding="utf-8"))+ assert receipt["ok"] is False, (receipt, result.stdout, result.stderr)+ # Native Windows reaches the missing-launcher refusal. PowerShell on POSIX+ # cannot call the Win32 console APIs, but its real finally writer still runs.+ if os.name == "nt":+ assert receipt["exit_code"] == 3, (receipt, result.stdout, result.stderr)+ else:+ assert receipt["exit_code"] == 1 and "DisableQuickEdit" in result.stderr+ lines = (home / ".hermes-update-in-progress.observed").read_text().splitlines()+ assert int(lines[1]) > receipt["started_at"], "actual heartbeat must change line 2"+ assert receipt.get("run_id"), receipt+ assert f"run:{receipt['run_id']}" in lines+ if run_id:+ assert receipt["run_id"] == run_id+ assert not (home / ".hermes-update-in-progress").exists(), "normal release still runs"