The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop-update): a Close-and-retry runs under its own hand-off run, not an inherited one
Tekniumc0016c3cb59c
diff --git a/apps/desktop/electron/updater/checkout-handoff.test.ts b/apps/desktop/electron/updater/checkout-handoff.test.tsindex 62ca7f9e68b..a8f34e52d5f 100644--- a/apps/desktop/electron/updater/checkout-handoff.test.ts+++ b/apps/desktop/electron/updater/checkout-handoff.test.ts@@ -519,19 +519,27 @@ it('the Windows protocol-2 hand-off passes -HandoffRun with the bridged run id',)const helper = vi.fn(async () => ({ kind: 'withdrawn' as const }))const runs: string[][] = []+ const envs: NodeJS.ProcessEnv[] = []let bridge: string | null = null- vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation((_command: string, args: string[]) => {- runs.push(args)- bridge = fs.readFileSync(markerPath(deps.hermesHome), 'utf8')+ vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation(+ (_command: string, args: string[], options: { env?: NodeJS.ProcessEnv }) => {+ runs.push(args)+ envs.push(options.env ?? {})+ bridge = fs.readFileSync(markerPath(deps.hermesHome), 'utf8')- return { unref: (): void => {} }- })+ return { unref: (): void => {} }+ }+ )+ // This Desktop was relaunched by the previous hand-off and inherited its run id.+ vi.stubEnv('HERMES_UPDATE_CORRELATION_ID', 'desk-1-previous-run')try {await createCheckoutStrategy({ ...deps, isWindows: true, markerHelper: helper, handoffClaimTimeoutMs: 200 }).apply()const runId = argAfter(runs[0]!, '-HandoffRun')expect(runId).toMatch(/^desk-\d+-[0-9a-z]+-[0-9a-f]{4}$/)expect(parseUpdateMarker(bridge ?? '')?.run).toBe(runId)+ // The update runs under THIS run's id, the one its close-holder consent is bound to.+ expect(envs[0]!.HERMES_UPDATE_CORRELATION_ID).toBe(runId)expect(argAfter(runs[0]!, '-DesktopPid')).toBe(String(process.pid))// Nothing adopted it: the bridge is withdrawn through the helper, with the run.expect(helper).toHaveBeenCalledWith(@@ -539,6 +547,7 @@ it('the Windows protocol-2 hand-off passes -HandoffRun with the bridged run id',expect.objectContaining({ runId, desktopPid: process.pid, isWindows: true }))} finally {+ vi.unstubAllEnvs()fs.rmSync(root, { recursive: true, force: true })}})diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.tsindex 08c8cee9d7a..56451b8a26d 100644--- a/apps/desktop/electron/updater/checkout.ts+++ b/apps/desktop/electron/updater/checkout.ts@@ -138,6 +138,31 @@ export interface CheckoutStrategy extends UpdaterStrategy {check(opts?: { force?: boolean; setChannel?: 'main' | 'stable' }): Promise<UpdaterStatusWire>}+/**+ * The Windows script hand-off's environment. Its `hermes update` runs under the run the+ * close-holder consent is bound to: an id this Desktop inherited from the hand-off that+ * relaunched it names the previous run, under which that consent never matches (#101789).+ */+function windowsHandoffEnvironment(+ updateRoot: string,+ hermesHome: string,+ updateStartedAt: number,+ runId: string | null+): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = {+ ...sourceUpdateEnvironment(updateRoot, hermesHome),+ HERMES_UPDATE_STARTED_AT: String(updateStartedAt)+ }++ delete env.HERMES_UPDATE_CORRELATION_ID++ if (runId) {+ env.HERMES_UPDATE_CORRELATION_ID = runId+ }++ return env+}+export function createCheckoutStrategy(deps: CheckoutStrategyDeps): CheckoutStrategy {function markerHelper(op: MarkerHelperOp, runId: string | null): Promise<MarkerHelperVerdict> {return (deps.markerHelper ?? runMarkerHelper)(op, {@@ -589,10 +614,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): CheckoutStrachild = spawnUpdaterProcess(wrapped.command, wrapped.args, {cwd: deps.hermesHome,- env: {- ...sourceUpdateEnvironment(updateRoot, deps.hermesHome),- HERMES_UPDATE_STARTED_AT: String(updateStartedAt)- },+ env: windowsHandoffEnvironment(updateRoot, deps.hermesHome, updateStartedAt, plan.runId),// Never `true` here: DETACHED_PROCESS leaves the wrapper console-less, so// `start /b` hands PowerShell a new VISIBLE console whose QuickEdit// selection can freeze the hand-off before relaunch (#103222).diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1index 760358dc995..9a3b4bc76d1 100644--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@ -1642,8 +1642,11 @@ try {Write-HandoffLog "could not probe update --help; running without --keep-stash"}# The update's receipt carries this id (update_receipt._launcher_correlation_id):- # Get-CommittedReceiptOutcome finds THIS run's receipt by it.- $script:UpdateCorrelation = if ($env:HERMES_UPDATE_CORRELATION_ID) { $env:HERMES_UPDATE_CORRELATION_ID } else { $script:ResultRunId }+ # Get-CommittedReceiptOutcome finds THIS run's receipt by it, and the Desktop's+ # close-holder consent is bound to -HandoffRun. That run id beats an inherited+ # one: a Desktop the Start-Process rung relaunched carried the previous run's+ # id, under which its next retry's consent could never match (#101789).+ $script:UpdateCorrelation = if ($HandoffRun) { $HandoffRun } elseif ($env:HERMES_UPDATE_CORRELATION_ID) { $env:HERMES_UPDATE_CORRELATION_ID } else { $script:ResultRunId }$env:HERMES_UPDATE_CORRELATION_ID = $script:UpdateCorrelationWrite-HandoffLog ("running: python " + ($updateArgs -join " "))Publish-UiProgress "Updating code and dependencies"@@ -1808,6 +1811,9 @@ try {$finalCode = 0}} finally {+ # This run's id is ours, not the relaunched Desktop's: the Start-Process rung+ # would hand it on to every update that Desktop starts.+ Remove-Item -LiteralPath Env:HERMES_UPDATE_CORRELATION_ID -ErrorAction SilentlyContinueif (@('claimed', 'adopted') -contains $script:MarkerClaim -and $InstallRoot) {# #101789: a Desktop "close and retry" consent belongs to this run alone. One its swap# never reached (a failed build) must not let a later update close the program unasked.diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_release_holders.py b/tests/scripts/desktop_update/test_desktop_update_windows_release_holders.pyindex 339b338462f..00fcb9c6f4c 100644--- a/tests/scripts/desktop_update/test_desktop_update_windows_release_holders.py+++ b/tests/scripts/desktop_update/test_desktop_update_windows_release_holders.py@@ -3,7 +3,8 @@A real ``windows.ps1`` drives a published launcher whose ``hermes update`` is a scripted stand-inprinting exactly what ``hermes_cli.desktop_release_holders`` prints when Windows refused thepromotion rename. The result the relaunched Desktop reads must name that program (message and a-structured ``release_holders`` list), so the Desktop can offer to close exactly it.+structured ``release_holders`` list), so the Desktop can offer to close exactly it, and the retry+that click starts must run under the run id its consent is bound to."""from __future__ import annotations@@ -11,16 +12,21 @@ import jsonimport osfrom pathlib import Pathimport subprocess+import sys+import time+import psutilimport pytest+from hermes_cli.desktop_release_holders import ReleaseHolder, take_consentfrom tests.installation_launcher_fixture import publish_fixture_launcher+from tests.scripts.desktop_update.windows_handoff_support import MARKER, POWERSHELL, _creation_timeROOT = Path(__file__).resolve().parent.parent.parent.parentSCRIPT = ROOT / 'scripts/desktop-update/windows.ps1'EXE = r'D:\Program Files (x86)\SogouInput\16.7.0.4912\SogouCloud.exe'CLI = """-import sys+import os, sysfrom pathlib import Pathdef main():if '--version' in sys.argv:@@ -29,6 +35,8 @@ def main():print('--keep-stash'); return 0if sys.argv[1:2] != ['update']:return 0+ if os.environ.get('CORRELATION_OUT'): # the id update_receipt and take_consent read+ Path(os.environ['CORRELATION_OUT']).write_text(os.environ.get('HERMES_UPDATE_CORRELATION_ID', ''))print(' Desktop app folder held by: SogouCloud.exe (pid 4242, started 1761470000.125, EXE_PATH)', flush=True)print(' Desktop app folder held by: AVHelper.exe (pid 5151, started 1761470001.500, path unreadable)', flush=True)print(' Desktop app build owed: desktop app build failed', flush=True)@@ -70,3 +78,84 @@ def test_blocked_swap_result_names_the_holder_for_the_desktop(tmp_path: Path) ->assert not consent.exists(), 'a consent the run never used ends with the run'assert 'SogouCloud.exe (pid 4242)' in result['message'], resultassert 'not part of Hermes' in result['message'], result+++# A relaunched Desktop: records the correlation id it inherited, but only when it was started by a+# rung that hands on the hand-off's own environment (the tethered Start-Process fallback). The WMI+# and explorer rungs start it without RELAUNCH_PROBE_OUT, so it exits at once and they fall through.+RELAUNCHED_DESKTOP = """+using System; using System.IO; using System.Threading;+public static class RelaunchedDesktop {+ public static int Main() {+ string probe = Environment.GetEnvironmentVariable("RELAUNCH_PROBE_OUT");+ if (String.IsNullOrEmpty(probe)) { return 0; }+ string corr = Environment.GetEnvironmentVariable("HERMES_UPDATE_CORRELATION_ID");+ File.WriteAllText(probe, System.Diagnostics.Process.GetCurrentProcess().Id + " " + (corr ?? "<unset>"));+ Thread.Sleep(90000);+ return 0;+ }+}+"""++[email protected]('windows')+def test_close_and_retry_runs_under_its_own_run_even_from_a_relaunched_desktop(tmp_path: Path) -> None:+ # The Desktop clicking "Close X and retry" was itself relaunched by the previous hand-off's+ # Start-Process rung, so it inherited that run's HERMES_UPDATE_CORRELATION_ID. Its retry binds+ # the consent to the NEW run (-HandoffRun); the update must look the consent up by that run, and+ # this hand-off's id must not reach the Desktop it relaunches in turn.+ install = tmp_path / 'checkout'+ publish_fixture_launcher(install, CLI)+ (install / 'hermes_cli/desktop_update_verify.py').write_text('pass\n', encoding='utf-8')+ home = tmp_path / 'home'+ home.mkdir()+ source = tmp_path / 'desktop.cs'+ source.write_text(RELAUNCHED_DESKTOP, encoding='utf-8')+ relaunch = tmp_path / 'release' / 'win-unpacked' / 'Hermes.exe'+ relaunch.parent.mkdir(parents=True)+ subprocess.run([POWERSHELL, '-NoProfile', '-Command',+ f"Add-Type -Path '{source}' -OutputAssembly '{relaunch}' -OutputType ConsoleApplication"],+ check=True, capture_output=True, timeout=120)+ # The quitting Desktop's protocol-2 bridge for this run (checkout.ts claimBridgeMarker), and the+ # program the user agreed to close in that run.+ run = 'desk-2-retry-ab12'+ desktop = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(15)'])+ holder = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(300)'])+ corr_out, relaunch_out = tmp_path / 'corr.txt', tmp_path / 'relaunched.txt'+ relaunched = None+ try:+ (home / MARKER).write_bytes(+ f'{desktop.pid}\n{int(time.time())}\nct:{_creation_time(desktop.pid)}\nrun:{run}\n'.encode())+ proc = subprocess.run(+ [POWERSHELL, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(SCRIPT),+ '-InstallRoot', str(install), '-NoUi', '-NoGateway', '-DesktopPid', str(desktop.pid),+ '-HandoffRun', run, '-RelaunchExe', str(relaunch)],+ check=False, cwd=tmp_path, capture_output=True, text=True, timeout=240,+ env={**os.environ, 'HERMES_HOME': str(home), 'HERMES_RUNTIME_DIR': str(tmp_path / 'empty-store'),+ 'PYTHONIOENCODING': 'utf-8', 'HERMES_UPDATE_CORRELATION_ID': 'desk-1-previous-run',+ 'CORRELATION_OUT': str(corr_out), 'RELAUNCH_PROBE_OUT': str(relaunch_out)},+ )+ log = home / 'logs' / 'desktop-update-handoff.log'+ detail = (proc.returncode, proc.stdout[-2000:], log.read_text(encoding='utf-8', errors='replace')[-4000:]+ if log.is_file() else '')+ assert corr_out.is_file() and relaunch_out.is_file(), detail+ relaunched_pid, relaunched_corr = relaunch_out.read_text(encoding='utf-8').split(' ', 1)+ relaunched = int(relaunched_pid)+ corr = corr_out.read_text(encoding='utf-8')++ # The real consumer of that id: the consent the Desktop bound to this run.+ live = psutil.Process(holder.pid)+ consent_dir = tmp_path / 'consent'+ consent_dir.mkdir()+ (consent_dir / '.close-holders-consent.json').write_text(json.dumps(+ {'run_id': run, 'holders': [{'pid': live.pid, 'start_time': live.create_time(), 'exe': live.exe()}]}),+ encoding='utf-8')+ covered = take_consent(consent_dir, corr).covers(+ ReleaseHolder(pid=live.pid, name=live.name(), exe=live.exe(), create_time=live.create_time()))+ finally:+ desktop.kill()+ holder.kill()+ if relaunched:+ subprocess.run(['taskkill', '/T', '/F', '/PID', str(relaunched)], capture_output=True, check=False)+ assert (corr, covered) == (run, True), detail+ assert relaunched_corr == '<unset>', detail