Skip to content

The agent that grows with you

fix(desktop-update): a close-holder consent covers exactly the retry it started

Teknium719b4c32204a
diff --git a/apps/desktop/electron/handoff-result.ts b/apps/desktop/electron/handoff-result.ts
index 0b97a9fa4bf..5ff34a5386f 100644
--- a/apps/desktop/electron/handoff-result.ts
+++ b/apps/desktop/electron/handoff-result.ts
@@ -48,7 +48,10 @@ export interface HandoffResult {
export interface ReleaseHolder {
pid: number
+ /** Process start time (epoch seconds, as the CLI read it): with the pid, names this exact process. */
+ startTime: number
name: string
+ /** Empty when Windows would not reveal the program path (a protected process): it cannot be closed from here. */
exe: string
}
@@ -59,8 +62,15 @@ function toReleaseHolders(raw: unknown): ReleaseHolder[] {
return raw
.filter(item => item && typeof item === 'object')
- .map(item => ({ pid: Number(item.pid), name: String(item.name ?? ''), exe: String(item.exe ?? '') }))
- .filter(holder => Number.isInteger(holder.pid) && holder.pid > 0 && holder.name && holder.exe)
+ .map(item => ({
+ pid: Number(item.pid),
+ startTime: Number(item.start_time),
+ name: String(item.name ?? ''),
+ exe: String(item.exe ?? '')
+ }))
+ .filter(
+ holder => Number.isInteger(holder.pid) && holder.pid > 0 && Number.isFinite(holder.startTime) && holder.name
+ )
}
export function handoffResultPath(hermesHome: string): string {
diff --git a/apps/desktop/electron/release-holder-consent.test.ts b/apps/desktop/electron/release-holder-consent.test.ts
index 54c69d126d1..b9b11ac9a96 100644
--- a/apps/desktop/electron/release-holder-consent.test.ts
+++ b/apps/desktop/electron/release-holder-consent.test.ts
@@ -6,26 +6,31 @@ import path from 'node:path'
import { test } from 'vitest'
import { handoffResultPath, type ReleaseHolder } from './handoff-result'
-import { releaseHolderConsentPath, releaseHolderRetry } from './release-holder-consent'
+import { bindReleaseHolderConsent, releaseHolderConsentPath, releaseHolderRetry } from './release-holder-consent'
import { reportHandoffResult } from './update-handoff-report'
const SOGOU: ReleaseHolder = {
pid: 4242,
+ startTime: 1761470000.125,
name: 'SogouCloud.exe',
exe: 'D:\\Program Files (x86)\\SogouInput\\16.7.0.4912\\SogouCloud.exe'
}
-function writeHeldResult(home: string) {
+// A protected process: Windows would not reveal its program path, so it cannot be closed from here.
+const PROTECTED: ReleaseHolder = { pid: 5151, startTime: 1761470001.5, name: 'AVHelper.exe', exe: '' }
+
+function writeHeldResult(home: string, holders: ReleaseHolder[]) {
fs.writeFileSync(
handoffResultPath(home),
JSON.stringify({
ok: true,
exit_code: 0,
manual: true,
- message: 'the Desktop app could not be replaced because SogouCloud.exe (pid 4242) is using its folder.',
+ message: 'the Desktop app could not be replaced because a program outside Hermes is using its folder.',
branch: 'main',
- warnings: ['build: the Desktop app folder is in use by SogouCloud.exe (pid 4242)'],
- release_holders: [SOGOU],
+ warnings: ['build: the Desktop app folder is in use'],
+ // windows.ps1's wire shape: the start time stays the CLI's text
+ release_holders: holders.map(({ startTime, ...holder }) => ({ ...holder, start_time: startTime.toFixed(3) })),
finished_at: Math.floor(Date.now() / 1000)
})
)
@@ -55,10 +60,32 @@ async function reportWithAnswer(home: string, response: number) {
return { boxes, consented }
}
+function updateRoot(): string {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'release-holder-root-'))
+ fs.mkdirSync(path.join(root, 'apps', 'desktop', 'release'), { recursive: true })
+
+ return root
+}
+
+/** The dialog's click, with an apply that hands off as the Windows script path does (or not). */
+async function retry(root: string, holders: ReleaseHolder[], outcome: { ok: boolean; handedOff?: boolean }) {
+ releaseHolderRetry({
+ isWindows: true,
+ resolveUpdateRoot: () => root,
+ applyUpdates: async () => {
+ bindReleaseHolderConsent(root, 'desktop-retry-1', () => undefined) // checkout.ts, once the hand-off run id exists
+
+ return outcome
+ },
+ log: () => undefined
+ })!(holders)
+ await new Promise(resolve => setTimeout(resolve, 0))
+}
+
test('#101789: a swap blocked by a program outside Hermes names it and closes it only on an explicit click', async () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'release-holder-'))
- writeHeldResult(home)
+ writeHeldResult(home, [SOGOU])
const dismissed = await reportWithAnswer(home, 1)
assert.equal(dismissed.boxes.length, 1)
assert.match(dismissed.boxes[0].message, /SogouCloud\.exe is blocking the Desktop app update/)
@@ -67,30 +94,45 @@ test('#101789: a swap blocked by a program outside Hermes names it and closes it
assert.equal(dismissed.boxes[0].cancelId, 1, 'closing the dialog never consents')
assert.deepEqual(dismissed.consented, [], 'dismissing must not close the program')
- writeHeldResult(home)
+ writeHeldResult(home, [SOGOU])
const accepted = await reportWithAnswer(home, 0)
assert.deepEqual(accepted.consented, [[SOGOU]])
})
-test('the consent names the programs for the next swap, then the update runs again', async () => {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'release-holder-root-'))
- fs.mkdirSync(path.join(root, 'apps', 'desktop', 'release'), { recursive: true })
- let applied = 0
+test('review N3: a holder that cannot be closed from here is named for the user, with no Close button', async () => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'release-holder-'))
- releaseHolderRetry({
- isWindows: true,
- resolveUpdateRoot: () => root,
- applyUpdates: async () => {
- applied += 1
+ writeHeldResult(home, [PROTECTED])
+ const alone = await reportWithAnswer(home, 0)
+ assert.deepEqual(alone.boxes[0].buttons, ['OK'])
+ assert.match(alone.boxes[0].detail, /AVHelper\.exe \(pid 5151\)\n {3}Close this one yourself/)
+ assert.deepEqual(alone.consented, [], 'no retry that would only show the same dialog again')
- return { ok: true }
- },
- log: () => undefined
- })!([SOGOU])
- await new Promise(resolve => setTimeout(resolve, 0))
+ writeHeldResult(home, [SOGOU, PROTECTED])
+ const mixed = await reportWithAnswer(home, 0)
+ assert.deepEqual(mixed.boxes[0].buttons, ['Close SogouCloud.exe and retry', 'Not now'])
+ assert.deepEqual(mixed.consented, [[SOGOU]])
+})
+
+test('review N1: the consent is bound to the retry run and the exact processes the user saw', async () => {
+ const root = updateRoot()
+
+ await retry(root, [SOGOU, PROTECTED], { ok: true, handedOff: true })
const consent = JSON.parse(fs.readFileSync(releaseHolderConsentPath(root), 'utf8'))
- assert.deepEqual(consent.exes, [SOGOU.exe])
- assert.ok(Math.abs(consent.written_at - Date.now() / 1000) < 60)
- assert.equal(applied, 1)
+ assert.equal(consent.run_id, 'desktop-retry-1')
+ assert.deepEqual(consent.holders, [{ pid: 4242, start_time: 1761470000.125, exe: SOGOU.exe }])
+})
+
+test('review N1: a retry that does not hand off leaves no consent, and a later update records none', async () => {
+ for (const outcome of [{ ok: false }, { ok: true }]) {
+ const root = updateRoot()
+
+ await retry(root, [SOGOU], outcome)
+ assert.equal(fs.existsSync(releaseHolderConsentPath(root)), false, JSON.stringify(outcome))
+
+ // The next apply, started from the Updates page and not from the dialog, consents to nothing.
+ bindReleaseHolderConsent(root, 'manual-update-2', () => undefined)
+ assert.equal(fs.existsSync(releaseHolderConsentPath(root)), false, JSON.stringify(outcome))
+ }
})
diff --git a/apps/desktop/electron/release-holder-consent.ts b/apps/desktop/electron/release-holder-consent.ts
index d99d24e6ddd..1380988b6e2 100644
--- a/apps/desktop/electron/release-holder-consent.ts
+++ b/apps/desktop/electron/release-holder-consent.ts
@@ -1,7 +1,9 @@
// The Desktop half of the consented "close it and retry" for a Desktop app swap blocked by a
-// program outside Hermes (#101789). The next promotion swap (hermes_cli/desktop_release_holders.py)
-// reads this file, closes only processes running one of these programs whose working folder is
-// still inside release/, and removes the file: one consent, one retry. Without it nothing is closed.
+// program outside Hermes (#101789). The consent is bound to the ONE hand-off run the retry starts
+// (its run id reaches the swap as HERMES_UPDATE_CORRELATION_ID) and to the exact processes the
+// user saw (pid + start time + program). The next promotion swap (hermes_cli/desktop_release_holders.py)
+// removes the file whatever its source and acts on it only in that run; a retry that never hands
+// off removes it here, and the hand-off script removes one its run never used.
import fs from 'node:fs'
import path from 'node:path'
@@ -14,29 +16,58 @@ export function releaseHolderConsentPath(updateRoot: string): string {
return path.join(updateRoot, 'apps', 'desktop', 'release', RELEASE_HOLDER_CONSENT_FILE)
}
-export function writeReleaseHolderConsent(
+/** Holders the user can close from here: a protected process (no readable program path) cannot be. */
+export function closableReleaseHolders(holders: ReleaseHolder[]): ReleaseHolder[] {
+ return holders.filter(holder => holder.exe)
+}
+
+// Set by the dialog's click for the apply it starts; taken by that apply's hand-off plan.
+let pendingConsent: ReleaseHolder[] | null = null
+
+/**
+ * Called by the Windows script hand-off once its run id exists, before the script is spawned:
+ * writes the consent given for this apply (if any) bound to that run, at most once. A consent
+ * that cannot be recorded is logged; the retry then closes nothing.
+ */
+export function bindReleaseHolderConsent(
updateRoot: string,
- holders: ReleaseHolder[],
+ runId: string | null,
+ log: (line: string) => void,
now: () => number = Date.now
-): string {
- const file = releaseHolderConsentPath(updateRoot)
- const exes = [...new Set(holders.map(holder => holder.exe).filter(Boolean))]
- fs.writeFileSync(file, JSON.stringify({ written_at: now() / 1000, exes }), 'utf8')
+): void {
+ const holders = pendingConsent
+ pendingConsent = null
- return file
+ if (!holders?.length || !runId) {
+ return // a legacy (run-id-less) hand-off cannot be told apart from any other update
+ }
+
+ try {
+ fs.writeFileSync(
+ releaseHolderConsentPath(updateRoot),
+ JSON.stringify({
+ written_at: now() / 1000,
+ run_id: runId,
+ holders: holders.map(holder => ({ pid: holder.pid, start_time: holder.startTime, exe: holder.exe }))
+ }),
+ 'utf8'
+ )
+ } catch (error) {
+ log(`[updates] could not record the consent to close a Desktop folder holder: ${(error as Error).message}`)
+ }
}
export interface ReleaseHolderRetryDeps {
isWindows: boolean
resolveUpdateRoot: () => string
- applyUpdates: () => Promise<{ ok: boolean; error?: string; message?: string }>
+ applyUpdates: () => Promise<{ ok: boolean; handedOff?: boolean; error?: string; message?: string }>
log: (line: string) => void
}
/**
- * The dialog's "Close <program> and retry": record the consent, then run the update hand-off
- * again, which rebuilds and promotes the owed app (applyBody runs even when the checkout is
- * already current). A consent that cannot be written starts no retry.
+ * The dialog's "Close <program> and retry": arm the consent, then run the update hand-off again,
+ * which rebuilds and promotes the owed app (applyBody runs even when the checkout is already
+ * current). An apply that does not hand off leaves no consent behind.
*/
export function releaseHolderRetry(deps: ReleaseHolderRetryDeps): ((holders: ReleaseHolder[]) => void) | undefined {
if (!deps.isWindows) {
@@ -44,27 +75,30 @@ export function releaseHolderRetry(deps: ReleaseHolderRetryDeps): ((holders: Rel
}
return holders => {
- const names = holders.map(holder => holder.name).join(', ')
+ const closable = closableReleaseHolders(holders)
+ const names = closable.map(holder => holder.name).join(', ')
+ const updateRoot = deps.resolveUpdateRoot()
+ pendingConsent = closable
+
+ const forget = (reason: string) => {
+ pendingConsent = null
- try {
- writeReleaseHolderConsent(deps.resolveUpdateRoot(), holders)
- } catch (error) {
- deps.log(`[updates] could not record consent to close ${names}: ${(error as Error).message}`)
+ try {
+ fs.rmSync(releaseHolderConsentPath(updateRoot), { force: true })
+ } catch (error) {
+ deps.log(`[updates] could not remove the consent to close ${names}: ${(error as Error).message}`)
+ }
- return
+ deps.log(`[updates] retry after consenting to close ${names} ${reason}`)
}
deps
.applyUpdates()
.then(result => {
- if (!result.ok) {
- deps.log(
- `[updates] retry after consenting to close ${names} did not start: ${result.error ?? result.message}`
- )
+ if (!result.ok || !result.handedOff) {
+ forget(`did not hand off: ${result.error ?? result.message ?? 'no hand-off'}`)
}
})
- .catch(error =>
- deps.log(`[updates] retry after consenting to close ${names} failed: ${(error as Error).message}`)
- )
+ .catch(error => forget(`failed: ${(error as Error).message}`))
}
}
diff --git a/apps/desktop/electron/update-handoff-report.ts b/apps/desktop/electron/update-handoff-report.ts
index 9e16a4f4ee1..fce19a1a2e3 100644
--- a/apps/desktop/electron/update-handoff-report.ts
+++ b/apps/desktop/electron/update-handoff-report.ts
@@ -5,6 +5,7 @@ import path from 'node:path'
import type { Dialog, Shell } from 'electron'
import { readAndConsumeHandoffResult, type ReleaseHolder } from './handoff-result'
+import { closableReleaseHolders } from './release-holder-consent'
export interface HandoffReportHost {
hermesHome: string
@@ -121,11 +122,25 @@ export function reportHandoffResult(host: HandoffReportHost): void {
/**
* #101789: the update landed, but a program outside Hermes holds the Desktop app's folder. Name it
- * and offer to close it, only on an explicit click; dismissing leaves it running.
+ * and offer to close it, only on an explicit click; dismissing leaves it running. A holder whose
+ * program path Windows would not reveal cannot be closed from here: it is named for the user to
+ * close, with no Close button that could never work.
*/
function reportReleaseHolders(host: HandoffReportHost, holders: ReleaseHolder[], message: string): void {
const names = holders.map(holder => holder.name).join(', ')
- const listed = holders.map(holder => `• ${holder.name} (pid ${holder.pid})\n ${holder.exe}`).join('\n')
+ const closable = closableReleaseHolders(holders)
+ const closableNames = closable.map(holder => holder.name).join(', ')
+
+ const listed = holders
+ .map(
+ holder => `• ${holder.name} (pid ${holder.pid})\n ${holder.exe || 'Close this one yourself (Task Manager).'}`
+ )
+ .join('\n')
+
+ const action = closable.length
+ ? 'Hermes did not close it. Close it and retry the update now, or keep using the current app and update later.'
+ : 'Hermes cannot close it. Close it yourself (Task Manager), then run the update again.'
+
host.log(`[updates] Desktop app swap blocked by programs outside Hermes: ${names}`)
void host.dialog
.showMessageBox({
@@ -134,16 +149,16 @@ function reportReleaseHolders(host: HandoffReportHost, holders: ReleaseHolder[],
message: `${names} is blocking the Desktop app update`,
detail:
`Hermes updated, but Windows would not replace the Desktop app because this program, which is not part of Hermes, is using its folder:\n\n${listed}\n\n` +
- `Hermes did not close it. Close it and retry the update now, or keep using the current app and update later.\n\nDetails: ${message}`,
- buttons: [`Close ${names} and retry`, 'Not now'],
- defaultId: 1,
- cancelId: 1,
+ `${action}\n\nDetails: ${message}`,
+ buttons: closable.length ? [`Close ${closableNames} and retry`, 'Not now'] : ['OK'],
+ defaultId: closable.length ? 1 : 0,
+ cancelId: closable.length ? 1 : 0,
noLink: true
})
.then(({ response }) => {
- if (response === 0) {
- host.log(`[updates] user consented to closing ${names}; retrying the update`)
- host.closeHoldersAndRetry?.(holders)
+ if (closable.length && response === 0) {
+ host.log(`[updates] user consented to closing ${closableNames}; retrying the update`)
+ host.closeHoldersAndRetry?.(closable)
}
})
}
diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.ts
index 544d72e8502..08c8cee9d7a 100644
--- a/apps/desktop/electron/updater/checkout.ts
+++ b/apps/desktop/electron/updater/checkout.ts
@@ -3,6 +3,7 @@
import { existsSync, readFileSync } from 'node:fs'
import * as path from 'node:path'
+import { bindReleaseHolderConsent } from '../release-holder-consent'
import {
claimBridgeMarker,
describeSkippedPrewrite,
@@ -555,6 +556,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): CheckoutStra
}
plan = planned.plan
+ bindReleaseHolderConsent(updateRoot, plan.runId, deps.rememberLog)
// A bare detached+hidden powershell spawn silently dies before -File
// processing (console-subsystem init failure — see
diff --git a/hermes_cli/desktop_release_holders.py b/hermes_cli/desktop_release_holders.py
index b891b14cc98..aeaba51b070 100644
--- a/hermes_cli/desktop_release_holders.py
+++ b/hermes_cli/desktop_release_holders.py
@@ -9,8 +9,10 @@ exe-under-release stop never sees it.
These holders belong to the user, not to Hermes: they are NAMED in the failure and closed
only with the user's consent, given either at an interactive terminal prompt or through the
-Desktop's "close it and retry" choice, which leaves a one-retry consent file in ``release/``.
-A non-interactive run with no consent never closes anything.
+Desktop's "close it and retry" choice. That choice leaves a consent file in ``release/`` bound
+to the hand-off run it starts and to the exact processes (pid + start time) the user saw; the
+next swap attempt consumes it whatever its source, and only that run's swap may act on it.
+A non-interactive run with no matching consent never closes anything.
"""
from __future__ import annotations
@@ -27,10 +29,11 @@ from typing import Callable, Optional
# windows.ps1 parses this exact prefix out of the update output (one line per holder).
HOLDER_LINE_PREFIX = "Desktop app folder held by: "
-# Written by the Desktop when the user chooses "Close <program> and retry"; read and removed
-# by the next promotion swap, so a consent covers exactly one retry.
+# Written by the Desktop when the user chooses "Close <program> and retry"; removed at the start
+# of the next promotion swap attempt, so a consent covers exactly one retry.
CONSENT_FILE_NAME = ".close-holders-consent.json"
-CONSENT_MAX_AGE_S = 3600
+# psutil create_time is a float rebuilt from the OS on each read: equal within this tolerance.
+_START_TIME_TOLERANCE_S = 0.5
_CLOSE_WAIT_S = 5
@@ -45,6 +48,27 @@ class ReleaseHolder:
def describe(self) -> str:
return f"{self.name} (pid {self.pid}, {self.exe or 'path unreadable'})"
+ def holder_line(self) -> str:
+ """The machine-read line windows.ps1 hands to the Desktop (pid + start time identify it)."""
+ return (f"{HOLDER_LINE_PREFIX}{self.name} (pid {self.pid}, started {self.create_time:.3f}, "
+ f"{self.exe or 'path unreadable'})")
+
+
+@dataclass(frozen=True)
+class HolderConsent:
+ """The processes the user agreed to close, as (pid, start time, normalized exe)."""
+ holders: frozenset[tuple[int, float, str]] = frozenset()
+
+ def covers(self, holder: ReleaseHolder) -> bool:
+ return bool(holder.exe) and any(
+ pid == holder.pid and abs(start - holder.create_time) <= _START_TIME_TOLERANCE_S
+ and exe == _norm(holder.exe)
+ for pid, start, exe in self.holders
+ )
+
+
+NO_CONSENT = HolderConsent()
+
def _norm(path: str) -> str:
return os.path.normcase(os.path.abspath(path))
@@ -101,34 +125,32 @@ def find_release_cwd_holders(release_dir: Path) -> list[ReleaseHolder]:
return holders
-def take_consent(release_dir: Path, *, now: Callable[[], float] = time.time) -> frozenset[str]:
- """The program paths the user agreed to close for this one retry; the file is consumed."""
+def take_consent(release_dir: Path, run_id: Optional[str]) -> HolderConsent:
+ """Consume the Desktop's consent at the start of a swap attempt: the file is removed whether
+ or not it applies, and it applies only to the hand-off run that the Desktop started for it."""
path = release_dir / CONSENT_FILE_NAME
try:
raw = path.read_text(encoding="utf-8-sig")
except OSError:
- return frozenset()
+ return NO_CONSENT
with contextlib.suppress(OSError):
path.unlink()
try:
data = json.loads(raw)
- written_at = float(data["written_at"])
- exes = [e for e in data["exes"] if isinstance(e, str) and e]
- except (ValueError, TypeError, KeyError):
- return frozenset()
- if not 0 <= now() - written_at <= CONSENT_MAX_AGE_S:
- return frozenset()
- return frozenset(_norm(e) for e in exes)
-
-
-def discard_consent(release_dir: Path) -> None:
- with contextlib.suppress(OSError):
- (release_dir / CONSENT_FILE_NAME).unlink()
+ if not run_id or data.get("run_id") != run_id:
+ return NO_CONSENT
+ holders = frozenset(
+ (int(h["pid"]), float(h["start_time"]), _norm(h["exe"]))
+ for h in data["holders"] if isinstance(h.get("exe"), str) and h["exe"]
+ )
+ except (ValueError, TypeError, KeyError, AttributeError):
+ return NO_CONSENT
+ return HolderConsent(holders)
def _ask_at_terminal(holders: list[ReleaseHolder], input_fn: Callable[[str], str]) -> bool:
"""Only a person at a terminal can answer; a hidden hand-off or a pipe never consents."""
- if not (sys.stdin and sys.stdin.isatty() and sys.stdout and sys.stdout.isatty()):
+ if not holders or not (sys.stdin and sys.stdin.isatty() and sys.stdout and sys.stdout.isatty()):
return False
names = ", ".join(h.describe() for h in holders)
try:
@@ -171,19 +193,25 @@ def close_holders(holders: list[ReleaseHolder], release_dir: Path) -> list[int]:
def release_after_refused_rename(
- release_dir: Path, *, input_fn: Callable[[str], str] = input,
+ release_dir: Path, *, consent: HolderConsent = NO_CONSENT, input_fn: Callable[[str], str] = input,
) -> tuple[list[ReleaseHolder], list[int]]:
"""After Windows refused a rename under ``release_dir``: name every cwd holder, then close
- the ones the user consented to. Returns (holders found, pids closed)."""
+ the ones covered by ``consent`` (taken at the start of this swap attempt) or agreed to at the
+ terminal. Returns (holders found, pids closed)."""
holders = find_release_cwd_holders(release_dir)
if not holders:
return [], []
for holder in holders:
- print(f" {HOLDER_LINE_PREFIX}{holder.describe()}")
- consented = take_consent(release_dir)
- chosen = [h for h in holders if h.exe and _norm(h.exe) in consented]
- if not chosen and _ask_at_terminal(holders, input_fn):
- chosen = holders
+ print(f" {holder.holder_line()}")
+ chosen = [h for h in holders if consent.covers(h)]
+ # A holder whose program path cannot be read is usually protected (another user, elevated):
+ # it cannot be closed from here either, so the user closes it themselves.
+ closable = [h for h in holders if h.exe]
+ for holder in holders:
+ if not holder.exe:
+ print(f" Close {holder.name} (pid {holder.pid}) yourself: Hermes cannot close it.")
+ if not chosen and _ask_at_terminal(closable, input_fn):
+ chosen = closable
if not chosen:
return holders, []
closed = close_holders(chosen, release_dir)
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index d193b953d6a..f243d22b568 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -254,7 +254,7 @@ def _recover_interrupted_swap(live: Path, aside: Path) -> None:
shutil.rmtree(aside, ignore_errors=True)
-def _move_live_app_aside(live_root: Path, previous: Path, release_dir: Path, held_by: Optional[list]) -> None:
+def _move_live_app_aside(live_root: Path, previous: Path, release_dir: Path, held_by: Optional[list], consent) -> None:
"""First swap rename. On Windows a refusal names the programs whose working folder is inside
``release/`` (#101789) and retries once only after the user consented to closing them."""
try:
@@ -264,7 +264,7 @@ def _move_live_app_aside(live_root: Path, previous: Path, release_dir: Path, hel
if sys.platform != "win32":
raise
from hermes_cli.desktop_release_holders import find_release_cwd_holders, release_after_refused_rename
- holders, closed = release_after_refused_rename(release_dir)
+ holders, closed = release_after_refused_rename(release_dir, consent=consent)
if not closed:
if held_by is not None:
held_by.extend(holders)
@@ -283,11 +283,15 @@ def _swap_staged_desktop_app(
"""Promote a VERIFIED staged pack over ``release/`` by two renames (live → ``.previous``, staged →
live); a failure between them rolls back. Returns the live exe or None (live app kept). Never raises.
``held_by`` collects the named programs that blocked the swap (Windows cwd holders)."""
+ from hermes_cli.desktop_release_holders import take_consent
+ from hermes_cli.update_receipt import _launcher_correlation_id
+ release_dir = desktop_dir / "release"
+ # A "close and retry" consent covers this one attempt of the run it was given for (#101789).
+ consent = take_consent(release_dir, _launcher_correlation_id())
staged_exe = _desktop_packaged_executable_in(staging_dir)
if staged_exe is None:
shutil.rmtree(staging_dir, ignore_errors=True)
return None
- release_dir = desktop_dir / "release"
try:
staged_root = _desktop_unpacked_root(staged_exe, staging_dir)
live_root = release_dir / staged_root.name
@@ -304,7 +308,7 @@ def _swap_staged_desktop_app(
stopped = _stop_desktop_processes_locking_build(desktop_dir, also_posix=True)
if stopped:
logger.info("stopped desktop processes before staged app promotion: %s", stopped)
- _move_live_app_aside(live_root, previous, release_dir, held_by)
+ _move_live_app_aside(live_root, previous, release_dir, held_by, consent)
try:
_rename_riding_out_file_lock(staged_root, live_root)
except OSError:
@@ -318,9 +322,6 @@ def _swap_staged_desktop_app(
return None
finally:
shutil.rmtree(staging_dir, ignore_errors=True)
- if sys.platform == "win32":
- from hermes_cli.desktop_release_holders import discard_consent
- discard_consent(release_dir) # a consent covers exactly one swap attempt
return live_root / staged_exe.relative_to(staged_root)
diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1
index 4fa7e8bed7c..49e5e1eb948 100644
--- a/scripts/desktop-update/windows.ps1
+++ b/scripts/desktop-update/windows.ps1
@@ -1723,8 +1723,12 @@ try {
# component) has its working folder inside release\ and Windows refuses the swap.
# hermes_cli/desktop_release_holders.py names each one on its own line; the
# relaunched Desktop offers to close exactly those and retry, never silently.
- foreach ($m in [regex]::Matches(($res.Output -join "`n"), '(?m)^\s*Desktop app folder held by: (.+?) \(pid (\d+), (.+)\)\s*$')) {
- $script:ReleaseHolders += [pscustomobject]@{ name = $m.Groups[1].Value; pid = [int]$m.Groups[2].Value; exe = $m.Groups[3].Value }
+ # pid + start time identify the exact process the user is asked about; the start time
+ # stays the CLI's invariant text (no locale-dependent number parsing here). An exe of
+ # 'path unreadable' (a protected process) becomes empty: the Desktop offers no Close for it.
+ foreach ($m in [regex]::Matches(($res.Output -join "`n"), '(?m)^\s*Desktop app folder held by: (.+?) \(pid (\d+), started ([0-9.]+), (.+)\)\s*$')) {
+ $holderExe = if ($m.Groups[4].Value -eq 'path unreadable') { '' } else { $m.Groups[4].Value }
+ $script:ReleaseHolders += [pscustomobject]@{ name = $m.Groups[1].Value; pid = [int]$m.Groups[2].Value; start_time = $m.Groups[3].Value; exe = $holderExe }
}
if ($script:ReleaseHolders.Count -gt 0) {
$holderNames = (@($script:ReleaseHolders) | ForEach-Object { "$($_.name) (pid $($_.pid))" }) -join ', '
@@ -1802,6 +1806,11 @@ try {
$finalCode = 0
}
} finally {
+ if (@('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.
+ Remove-Item -LiteralPath (Join-Path $InstallRoot 'apps\desktop\release\.close-holders-consent.json') -Force -ErrorAction SilentlyContinue
+ }
# Truth ordering (sibling contract to posix.sh finish()):
# 1. durable result + marker removal (the relaunched Desktop consumes
# the result on boot and must not park on our marker);
diff --git a/tests/hermes_cli/test_desktop_release_holder_windows_live.py b/tests/hermes_cli/test_desktop_release_holder_windows_live.py
index 79e2c735449..d73c560f07f 100644
--- a/tests/hermes_cli/test_desktop_release_holder_windows_live.py
+++ b/tests/hermes_cli/test_desktop_release_holder_windows_live.py
@@ -71,13 +71,35 @@ def test_blocked_swap_names_the_foreign_holder_and_leaves_it_running(swap_fixtur
assert (live_root / "Hermes.exe").read_text(encoding="utf-8") == "old"
-def test_consented_retry_closes_exactly_the_holder_and_promotes(swap_fixture, capsys):
- desktop_dir, staging, live_root, helper = swap_fixture
+def _consent_for_run(desktop_dir: Path, helper, run_id: str) -> tuple[Path, list]:
# The venv python.exe may be a launcher with the real interpreter as its child, both inside
- # the folder; the Desktop consents to every program the failure named, so this does too.
+ # the folder; the Desktop consents to every process the failure named, so this does too.
tree = [psutil.Process(helper.pid), *psutil.Process(helper.pid).children(recursive=True)]
consent = desktop_dir / "release" / ".close-holders-consent.json"
- consent.write_text(json.dumps({"written_at": time.time(), "exes": [p.exe() for p in tree]}), encoding="utf-8")
+ seen = [{"pid": p.pid, "start_time": p.create_time(), "exe": p.exe()} for p in tree]
+ consent.write_text(json.dumps({"written_at": time.time(), "run_id": run_id,
+ "exes": [s["exe"] for s in seen], "holders": seen}), encoding="utf-8")
+ return consent, tree
+
+
+def test_a_consent_given_for_another_run_closes_nothing_and_is_used_up(swap_fixture, monkeypatch):
+ """Review N1: a gateway /update (or any swap not started by the consented retry) never closes."""
+ desktop_dir, staging, live_root, helper = swap_fixture
+ consent, _tree = _consent_for_run(desktop_dir, helper, "desktop-retry-1")
+ monkeypatch.setenv("HERMES_UPDATE_CORRELATION_ID", "gateway-update-7")
+
+ promoted, error = _promote(desktop_dir, staging)
+
+ assert promoted is None and f"pid {helper.pid}" in error, error
+ assert helper.poll() is None, "closed on a consent given for another run"
+ assert not consent.exists(), "the swap attempt consumes the consent, matching or not"
+ assert (live_root / "Hermes.exe").read_text(encoding="utf-8") == "old"
+
+
+def test_consented_retry_closes_exactly_the_holder_and_promotes(swap_fixture, capsys, monkeypatch):
+ desktop_dir, staging, live_root, helper = swap_fixture
+ consent, tree = _consent_for_run(desktop_dir, helper, "desktop-retry-1")
+ monkeypatch.setenv("HERMES_UPDATE_CORRELATION_ID", "desktop-retry-1") # windows.ps1 exports its run id
promoted, error = _promote(desktop_dir, staging)
diff --git a/tests/hermes_cli/test_desktop_release_holders.py b/tests/hermes_cli/test_desktop_release_holders.py
index 93826ee7e1a..3beec947858 100644
--- a/tests/hermes_cli/test_desktop_release_holders.py
+++ b/tests/hermes_cli/test_desktop_release_holders.py
@@ -15,7 +15,8 @@ import time
import psutil
import pytest
-from hermes_cli.desktop_release_holders import CONSENT_FILE_NAME, release_after_refused_rename
+from hermes_cli import desktop_release_holders, main_desktop
+from hermes_cli.desktop_release_holders import CONSENT_FILE_NAME, release_after_refused_rename, take_consent
_HELPER = "import time\nprint('ready', flush=True)\ntime.sleep(300)\n"
@@ -37,39 +38,83 @@ def holder(tmp_path):
proc.wait(10)
-def _consent(release, exes, written_at=None):
- (release / CONSENT_FILE_NAME).write_text(
- json.dumps({"written_at": time.time() if written_at is None else written_at, "exes": exes}),
- encoding="utf-8")
+def _desktop_consent(release, proc, run_id, **override):
+ """What the Desktop's "Close <program> and retry" writes for the retry run it starts."""
+ ps = psutil.Process(proc.pid)
+ seen = {"pid": proc.pid, "start_time": ps.create_time(), "exe": ps.exe(), **override}
+ (release / CONSENT_FILE_NAME).write_text(json.dumps({
+ "written_at": time.time(), "run_id": run_id, "exes": [seen["exe"]], "holders": [seen],
+ }), encoding="utf-8")
def _never_asked(_prompt):
raise AssertionError("a non-interactive run must never prompt")
-def test_holder_is_named_and_left_running_without_a_matching_fresh_consent(holder, capsys):
+def test_a_retry_that_fails_before_the_swap_leaves_no_consent_for_a_later_update(holder, tmp_path, monkeypatch):
+ """Review N1: the consent belongs to one retry. Once that retry's swap attempt has run, a
+ later update from any source (gateway /update, cron) must not close the program unasked."""
release, proc = holder
- exe = psutil.Process(proc.pid).exe()
+ _desktop_consent(release, proc, run_id="desktop-retry-1")
- for consent in (None, ["C:/elsewhere/other.exe"], "stale"):
- if consent == "stale":
- _consent(release, [exe], written_at=time.time() - 2 * 3600)
- elif consent is not None:
- _consent(release, consent)
- holders, closed = release_after_refused_rename(release, input_fn=_never_asked)
+ # The consented retry runs, but its swap fails before the rename (no launchable staged app).
+ monkeypatch.setenv("HERMES_UPDATE_CORRELATION_ID", "desktop-retry-1")
+ staging = tmp_path / "apps" / "desktop" / ".staging-failed"
+ staging.mkdir()
+ assert main_desktop._swap_staged_desktop_app(tmp_path / "apps" / "desktop", staging) is None
+ assert not (release / CONSENT_FILE_NAME).exists(), "the swap attempt consumes the consent, failed or not"
- assert proc.pid in [h.pid for h in holders], consent
- assert closed == [], consent
- assert proc.poll() is None, f"closed without consent ({consent})"
- assert not (release / CONSENT_FILE_NAME).exists(), "a consent is consumed by the attempt that read it"
- assert f"Desktop app folder held by: {psutil.Process(proc.pid).name()} (pid {proc.pid}, {exe})" in capsys.readouterr().out
+ # Later, a non-interactive gateway /update hits the refused rename.
+ monkeypatch.delenv("HERMES_UPDATE_CORRELATION_ID")
+ holders, closed = release_after_refused_rename(release, input_fn=_never_asked)
+ assert proc.pid in [h.pid for h in holders]
+ assert closed == []
+ assert proc.poll() is None, "closed without asking, on a consent given for another run"
-def test_consented_holder_is_closed(holder):
- release, proc = holder
- _consent(release, [psutil.Process(proc.pid).exe()])
- _holders, closed = release_after_refused_rename(release, input_fn=_never_asked)
+def test_a_consent_closes_only_what_the_user_saw_in_the_run_it_was_given_for(holder, capsys):
+ release, proc = holder
+ started = psutil.Process(proc.pid).create_time()
+ refused = {
+ "another run's swap": ("desktop-retry-1", "gateway-update-7", {}),
+ "a swap with no run id": ("desktop-retry-1", None, {}),
+ "a recycled pid": ("desktop-retry-1", "desktop-retry-1", {"start_time": started - 60}),
+ "another program": ("desktop-retry-1", "desktop-retry-1", {"exe": "C:/elsewhere/other.exe"}),
+ }
+ for case, (consented_run, swap_run, override) in refused.items():
+ _desktop_consent(release, proc, consented_run, **override)
+ consent = take_consent(release, swap_run)
+ assert not (release / CONSENT_FILE_NAME).exists(), f"{case}: the attempt consumes the consent"
+ holders, closed = release_after_refused_rename(release, consent=consent, input_fn=_never_asked)
+ assert proc.pid in [h.pid for h in holders], case
+ assert closed == [] and proc.poll() is None, f"closed without consent ({case})"
+ line = f"Desktop app folder held by: {psutil.Process(proc.pid).name()} (pid {proc.pid}, started {started:.3f}, "
+ assert line in capsys.readouterr().out
+
+ _desktop_consent(release, proc, "desktop-retry-1")
+ _holders, closed = release_after_refused_rename(
+ release, consent=take_consent(release, "desktop-retry-1"), input_fn=_never_asked)
assert proc.pid in closed
assert proc.wait(10) is not None
+
+
+def test_a_holder_whose_program_path_is_unreadable_is_left_for_the_user(holder, monkeypatch, capsys):
+ """Review N3: no close offer that can never be honoured, at the terminal or in the Desktop
+ (windows.ps1 hands the Desktop an empty exe for it, which gets no Close button)."""
+ release, proc = holder
+ # What psutil answers for a protected process (another user's, elevated): no program path.
+ monkeypatch.setattr(desktop_release_holders, "_exe_or_empty", lambda _proc: "")
+ monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False)
+ monkeypatch.setattr(sys.stdout, "isatty", lambda: True, raising=False)
+ _desktop_consent(release, proc, "desktop-retry-1", exe="")
+
+ holders, closed = release_after_refused_rename(
+ release, consent=take_consent(release, "desktop-retry-1"), input_fn=_never_asked)
+
+ assert [h.pid for h in holders] == [proc.pid] and closed == []
+ assert proc.poll() is None
+ out = capsys.readouterr().out
+ assert f"(pid {proc.pid}, started " in out and "path unreadable)" in out
+ assert f"(pid {proc.pid}) yourself" in out
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.py
index ad10447bf5e..339b338462f 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
@@ -29,7 +29,8 @@ def main():
print('--keep-stash'); return 0
if sys.argv[1:2] != ['update']:
return 0
- print(' Desktop app folder held by: SogouCloud.exe (pid 4242, EXE_PATH)', flush=True)
+ 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)
print('Update complete!', flush=True)
return 0
@@ -45,6 +46,10 @@ def test_blocked_swap_result_names_the_holder_for_the_desktop(tmp_path: Path) ->
(install / 'hermes_cli/desktop_update_verify.py').write_text('pass\n', encoding='utf-8')
home = tmp_path / 'home'
home.mkdir()
+ # The consent the Desktop recorded for this retry; its swap is never reached (the build failed).
+ consent = install / 'apps/desktop/release/.close-holders-consent.json'
+ consent.parent.mkdir(parents=True, exist_ok=True)
+ consent.write_text('{"run_id": "r", "holders": []}', encoding='utf-8')
proc = subprocess.run(
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(SCRIPT),
'-InstallRoot', str(install), '-NoUi', '-NoGateway'],
@@ -58,6 +63,10 @@ def test_blocked_swap_result_names_the_holder_for_the_desktop(tmp_path: Path) ->
result = json.loads(result_path.read_text(encoding='utf-8-sig'))
assert (result['ok'], result['manual']) == (True, True), (proc.stdout, result)
- assert result['release_holders'] == [{'name': 'SogouCloud.exe', 'pid': 4242, 'exe': EXE}], result
+ assert result['release_holders'] == [
+ {'name': 'SogouCloud.exe', 'pid': 4242, 'start_time': '1761470000.125', 'exe': EXE},
+ {'name': 'AVHelper.exe', 'pid': 5151, 'start_time': '1761470001.500', 'exe': ''},
+ ], result
+ assert not consent.exists(), 'a consent the run never used ends with the run'
assert 'SogouCloud.exe (pid 4242)' in result['message'], result
assert 'not part of Hermes' in result['message'], result