The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): name the program holding release/ and close it only with consent (#101789)
Tekniumef47d951bd72
diff --git a/apps/desktop/electron/fs-probes.ts b/apps/desktop/electron/fs-probes.tsnew file mode 100644index 00000000000..75b6471de21--- /dev/null+++ b/apps/desktop/electron/fs-probes.ts@@ -0,0 +1,24 @@+// Synchronous filesystem probes main.ts uses on its boot and update paths.++import fs from 'node:fs'+import path from 'node:path'++export function fileExists(filePath: string): boolean {+ try {+ return fs.statSync(filePath).isFile()+ } catch {+ return false+ }+}++export function isGitCheckout(root: string): boolean {+ return fs.existsSync(path.join(root, '.git'))+}++export function directoryExists(filePath: string): boolean {+ try {+ return fs.statSync(filePath).isDirectory()+ } catch {+ return false+ }+}diff --git a/apps/desktop/electron/handoff-result.ts b/apps/desktop/electron/handoff-result.tsindex c167d19da04..0b97a9fa4bf 100644--- a/apps/desktop/electron/handoff-result.ts+++ b/apps/desktop/electron/handoff-result.ts@@ -42,6 +42,25 @@ export interface HandoffResult {branch: string/** C2: `ok:true` with follow-up work that failed after the commit point. */warnings: string[]+ /** #101789: programs outside Hermes whose working folder blocked the Desktop app swap. */+ releaseHolders: ReleaseHolder[]+}++export interface ReleaseHolder {+ pid: number+ name: string+ exe: string+}++function toReleaseHolders(raw: unknown): ReleaseHolder[] {+ if (!Array.isArray(raw)) {+ return []+ }++ 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)}export function handoffResultPath(hermesHome: string): string {@@ -137,7 +156,8 @@ function toHandoffResult(parsed: any, manual: boolean): HandoffResult {manual,message: typeof parsed?.message === 'string' ? parsed.message : '',branch: typeof parsed?.branch === 'string' ? parsed.branch : '',- warnings: Array.isArray(parsed?.warnings) ? parsed.warnings.map(String).filter(Boolean) : []+ warnings: Array.isArray(parsed?.warnings) ? parsed.warnings.map(String).filter(Boolean) : [],+ releaseHolders: toReleaseHolders(parsed?.release_holders)}}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex b56aa76723c..2e9751d6827 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -263,6 +263,7 @@ import {} from './find-in-page'import { createFirstRunSetupGate } from './first-run-setup-gate'import { registerFsIpc } from './fs-ipc'+import { directoryExists, fileExists, isGitCheckout } from './fs-probes'import { downloadViaTokenToFile as downloadViaNativeGatewayToFile } from './gateway-download-transport'import type {GatewayFileSaveContext,@@ -504,6 +505,7 @@ import {probeCachedConnectionInstallId,rememberConnectionInstallId} from './registry-backend-identity'+import { releaseHolderRetry } from './release-holder-consent'import * as remoteLifecycle from './remote-lifecycle'import {attachPowerResumeRemoteRevalidation,@@ -2696,26 +2698,6 @@ async function advanceBootProgress(phase, message, progress) {}}-function fileExists(filePath) {- try {- return fs.statSync(filePath).isFile()- } catch {- return false- }-}--function isGitCheckout(root: string): boolean {- return fs.existsSync(path.join(root, '.git'))-}--function directoryExists(filePath) {- try {- return fs.statSync(filePath).isDirectory()- } catch {- return false- }-}-// --- in-app update mutual exclusion (#50238) -------------------------------// The Tauri updater writes HERMES_HOME/.hermes-update-in-progress for the whole// duration of an `--update` run (see update.rs UpdateMarkerGuard). If the user@@ -2846,7 +2828,8 @@ async function waitForUpdateToFinish() {log: rememberLog,dialog,shell,- openUpdates: sendOpenUpdatesRequested+ openUpdates: sendOpenUpdatesRequested,+ closeHoldersAndRetry: releaseHolderRetry({ isWindows: IS_WINDOWS, resolveUpdateRoot, applyUpdates, log: rememberLog })})if (outcome === 'cancelled') {diff --git a/apps/desktop/electron/release-holder-consent.test.ts b/apps/desktop/electron/release-holder-consent.test.tsnew file mode 100644index 00000000000..54c69d126d1--- /dev/null+++ b/apps/desktop/electron/release-holder-consent.test.ts@@ -0,0 +1,96 @@+import assert from 'node:assert/strict'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { test } from 'vitest'++import { handoffResultPath, type ReleaseHolder } from './handoff-result'+import { releaseHolderConsentPath, releaseHolderRetry } from './release-holder-consent'+import { reportHandoffResult } from './update-handoff-report'++const SOGOU: ReleaseHolder = {+ pid: 4242,+ name: 'SogouCloud.exe',+ exe: 'D:\\Program Files (x86)\\SogouInput\\16.7.0.4912\\SogouCloud.exe'+}++function writeHeldResult(home: string) {+ 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.',+ branch: 'main',+ warnings: ['build: the Desktop app folder is in use by SogouCloud.exe (pid 4242)'],+ release_holders: [SOGOU],+ finished_at: Math.floor(Date.now() / 1000)+ })+ )+}++async function reportWithAnswer(home: string, response: number) {+ const boxes: any[] = []+ const consented: ReleaseHolder[][] = []+ reportHandoffResult({+ hermesHome: home,+ expectedStartedAt: null,+ expectedRunId: null,+ log: () => undefined,+ dialog: {+ showMessageBox: async (options: any) => {+ boxes.push(options)++ return { response, checkboxChecked: false }+ }+ },+ shell: { showItemInFolder: () => undefined },+ openUpdates: () => undefined,+ closeHoldersAndRetry: holders => consented.push(holders)+ })+ await new Promise(resolve => setTimeout(resolve, 0))++ return { boxes, consented }+}++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)+ 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/)+ assert.match(dismissed.boxes[0].detail, /pid 4242/)+ assert.deepEqual(dismissed.boxes[0].buttons, ['Close SogouCloud.exe and retry', 'Not now'])+ assert.equal(dismissed.boxes[0].cancelId, 1, 'closing the dialog never consents')+ assert.deepEqual(dismissed.consented, [], 'dismissing must not close the program')++ writeHeldResult(home)+ 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++ releaseHolderRetry({+ isWindows: true,+ resolveUpdateRoot: () => root,+ applyUpdates: async () => {+ applied += 1++ return { ok: true }+ },+ log: () => undefined+ })!([SOGOU])+ await new Promise(resolve => setTimeout(resolve, 0))++ 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)+})diff --git a/apps/desktop/electron/release-holder-consent.ts b/apps/desktop/electron/release-holder-consent.tsnew file mode 100644index 00000000000..d99d24e6ddd--- /dev/null+++ b/apps/desktop/electron/release-holder-consent.ts@@ -0,0 +1,70 @@+// 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.++import fs from 'node:fs'+import path from 'node:path'++import type { ReleaseHolder } from './handoff-result'++export const RELEASE_HOLDER_CONSENT_FILE = '.close-holders-consent.json'++export function releaseHolderConsentPath(updateRoot: string): string {+ return path.join(updateRoot, 'apps', 'desktop', 'release', RELEASE_HOLDER_CONSENT_FILE)+}++export function writeReleaseHolderConsent(+ updateRoot: string,+ holders: ReleaseHolder[],+ 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')++ return file+}++export interface ReleaseHolderRetryDeps {+ isWindows: boolean+ resolveUpdateRoot: () => string+ applyUpdates: () => Promise<{ ok: 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.+ */+export function releaseHolderRetry(deps: ReleaseHolderRetryDeps): ((holders: ReleaseHolder[]) => void) | undefined {+ if (!deps.isWindows) {+ return undefined // the cwd hold is a Windows rename refusal; no other host reports holders+ }++ return holders => {+ const names = holders.map(holder => holder.name).join(', ')++ try {+ writeReleaseHolderConsent(deps.resolveUpdateRoot(), holders)+ } catch (error) {+ deps.log(`[updates] could not record consent to close ${names}: ${(error as Error).message}`)++ return+ }++ deps+ .applyUpdates()+ .then(result => {+ if (!result.ok) {+ deps.log(+ `[updates] retry after consenting to close ${names} did not start: ${result.error ?? result.message}`+ )+ }+ })+ .catch(error =>+ deps.log(`[updates] retry after consenting to close ${names} failed: ${(error as Error).message}`)+ )+ }+}diff --git a/apps/desktop/electron/update-handoff-report.ts b/apps/desktop/electron/update-handoff-report.tsindex ffdb6334c71..9e16a4f4ee1 100644--- a/apps/desktop/electron/update-handoff-report.ts+++ b/apps/desktop/electron/update-handoff-report.ts@@ -4,7 +4,7 @@ import path from 'node:path'import type { Dialog, Shell } from 'electron'-import { readAndConsumeHandoffResult } from './handoff-result'+import { readAndConsumeHandoffResult, type ReleaseHolder } from './handoff-result'export interface HandoffReportHost {hermesHome: string@@ -17,6 +17,8 @@ export interface HandoffReportHost {shell: Pick<Shell, 'showItemInFolder'>/** The menu's open-updates path (queued until the renderer is ready). */openUpdates: () => void+ /** The user consented to closing these programs: record it and run the update again. */+ closeHoldersAndRetry?: (holders: ReleaseHolder[]) => void}/** The run identity a live marker carried when the boot gate saw it. */@@ -69,6 +71,8 @@ export function reportHandoffResult(host: HandoffReportHost): void {message: 'Hermes updated, but some follow-up steps need another try',detail: `${result.warnings.join('\n')}\n\nHermes retries them on the next launch or the next update.`})+ } else if (result && result.ok && result.manual && result.releaseHolders.length && host.closeHoldersAndRetry) {+ reportReleaseHolders(host, result.releaseHolders, result.message)} else if (result && result.ok && result.manual) {// Update landed but the user must act (reopen/reinstall/sandbox). On// machines with no shim browser and no notifier this dialog is the@@ -114,3 +118,32 @@ export function reportHandoffResult(host: HandoffReportHost): void {host.log(`[updates] could not read hand-off result: ${(err as Error).message}`)}}++/**+ * #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.+ */+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')+ host.log(`[updates] Desktop app swap blocked by programs outside Hermes: ${names}`)+ void host.dialog+ .showMessageBox({+ type: 'warning',+ title: 'Hermes update',+ 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,+ noLink: true+ })+ .then(({ response }) => {+ if (response === 0) {+ host.log(`[updates] user consented to closing ${names}; retrying the update`)+ host.closeHoldersAndRetry?.(holders)+ }+ })+}diff --git a/hermes_cli/desktop_release_holders.py b/hermes_cli/desktop_release_holders.pynew file mode 100644index 00000000000..083f558867f--- /dev/null+++ b/hermes_cli/desktop_release_holders.py@@ -0,0 +1,206 @@+"""Name the programs holding ``apps/desktop/release`` open by working directory (#101789).++Windows refuses to rename a directory that a live process uses as its current working+directory. A resident helper that some Hermes window spawned (an IME cloud service such as+Sogou's ``SogouCloud.exe``, an AV or assistant component) inherits that window's cwd inside+``release/win-unpacked`` and keeps it after the app exits, so the stage-and-swap promotion+fails on every retry although the build succeeded. Its exe lives elsewhere, so the+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.+"""++from __future__ import annotations++import contextlib+import json+import os+import sys+import time+from dataclasses import dataclass+from pathlib import Path+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.+CONSENT_FILE_NAME = ".close-holders-consent.json"+CONSENT_MAX_AGE_S = 3600++_CLOSE_WAIT_S = 5+++@dataclass(frozen=True)+class ReleaseHolder:+ pid: int+ name: str+ exe: str+ create_time: float++ def describe(self) -> str:+ return f"{self.name} (pid {self.pid}, {self.exe or 'path unreadable'})"+++def _norm(path: str) -> str:+ return os.path.normcase(os.path.abspath(path))+++def _inside(path: str, root: str) -> bool:+ return path == root or path.startswith(root.rstrip("\\/") + os.sep)+++def _release_root(release_dir: Path) -> Optional[str]:+ try:+ return _norm(str(release_dir.resolve()))+ except OSError:+ return None+++def _exe_or_empty(proc) -> str:+ """Read only for a matched holder: another process's exe is none of our business."""+ try:+ return proc.exe() or ""+ except Exception: # health: allow BLE001 -- access denied for a protected process: named without a path+ return ""+++def find_release_cwd_holders(release_dir: Path) -> list[ReleaseHolder]:+ """Every other process whose working directory is ``release_dir`` or below it.++ A process whose cwd cannot be read (another user's, access denied) is skipped: it cannot+ be shown to hold the tree. Never raises.+ """+ root = _release_root(release_dir)+ try:+ import psutil+ procs = psutil.process_iter(["pid", "name"])+ except Exception: # health: allow BLE001 -- diagnostics on a failure path; no psutil = no names+ return []+ if root is None:+ return []+ me = os.getpid()+ holders: list[ReleaseHolder] = []+ for proc in procs:+ try:+ if proc.pid == me:+ continue+ cwd = proc.cwd()+ if not cwd or not _inside(_norm(cwd), root):+ continue+ holders.append(ReleaseHolder(+ pid=int(proc.pid), name=proc.info.get("name") or "unknown program",+ exe=_exe_or_empty(proc), create_time=float(proc.create_time()),+ ))+ except Exception: # health: allow BLE001 -- psutil raises per-process (gone, denied, zombie)+ continue+ 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."""+ path = release_dir / CONSENT_FILE_NAME+ try:+ raw = path.read_text(encoding="utf-8")+ except OSError:+ return frozenset()+ 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()+++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()):+ return False+ names = ", ".join(h.describe() for h in holders)+ try:+ answer = input_fn(f" Close {names} and retry? [y/N] ")+ except (EOFError, KeyboardInterrupt):+ return False+ return answer.strip().lower() in ("y", "yes")+++def close_holders(holders: list[ReleaseHolder], release_dir: Path) -> list[int]:+ """Terminate exactly these holders, each re-checked right before: same pid AND creation+ time (no recycled pid), cwd still inside ``release_dir``, and not one of our ancestors."""+ root = _release_root(release_dir)+ try:+ import psutil+ ancestors = {p.pid for p in psutil.Process(os.getpid()).parents()}+ except Exception: # health: allow BLE001 -- no process table means nothing can be verified+ return []+ targets = []+ for holder in holders:+ try:+ proc = psutil.Process(holder.pid)+ if proc.pid in ancestors or abs(proc.create_time() - holder.create_time) > 0.5:+ continue+ if root is None or not _inside(_norm(proc.cwd()), root):+ continue+ proc.terminate()+ targets.append(proc)+ except Exception: # health: allow BLE001 -- gone or denied: it is not closed by us+ continue+ if targets:+ with contextlib.suppress(Exception):+ _, alive = psutil.wait_procs(targets, timeout=_CLOSE_WAIT_S)+ for proc in alive:+ with contextlib.suppress(Exception):+ proc.kill()+ if alive:+ psutil.wait_procs(alive, timeout=_CLOSE_WAIT_S)+ return [int(p.pid) for p in targets if not p.is_running()]+++def release_after_refused_rename(+ release_dir: Path, *, 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)."""+ 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+ if not chosen:+ return holders, []+ closed = close_holders(chosen, release_dir)+ if closed:+ print(f" ✓ Closed with your consent: {', '.join(h.describe() for h in chosen if h.pid in closed)}")+ return holders, closed+++def describe_block(holders: list[ReleaseHolder], release_dir: Path) -> str:+ names = ", ".join(h.describe() for h in holders)+ pids = " ".join(f"/PID {h.pid}" for h in holders)+ return (+ f"✗ Windows would not replace the desktop app: {names} is using a folder inside {release_dir}.\n"+ f" It is not part of Hermes, so it was left running. Close it (Task Manager, or `taskkill {pids}`)\n"+ " and run `hermes desktop --force-build`, or run Update now in Hermes Desktop and choose to close it."+ )+++def holder_names(holders: list[ReleaseHolder]) -> str:+ return ", ".join(f"{h.name} (pid {h.pid})" for h in holders)diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.pyindex c6e6c4db854..d193b953d6a 100644--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@ -254,9 +254,35 @@ def _recover_interrupted_swap(live: Path, aside: Path) -> None:shutil.rmtree(aside, ignore_errors=True)-def _swap_staged_desktop_app(desktop_dir: Path, staging_dir: Path) -> Optional[Path]:+def _move_live_app_aside(live_root: Path, previous: Path, release_dir: Path, held_by: Optional[list]) -> 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:+ _rename_riding_out_file_lock(live_root, previous)+ return+ except PermissionError:+ 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)+ if not closed:+ if held_by is not None:+ held_by.extend(holders)+ raise+ try:+ _rename_riding_out_file_lock(live_root, previous)+ except PermissionError:+ if held_by is not None:+ held_by.extend(find_release_cwd_holders(release_dir))+ raise+++def _swap_staged_desktop_app(+ desktop_dir: Path, staging_dir: Path, *, held_by: Optional[list] = None,+) -> Optional[Path]:"""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."""+ 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)."""staged_exe = _desktop_packaged_executable_in(staging_dir)if staged_exe is None:shutil.rmtree(staging_dir, ignore_errors=True)@@ -278,7 +304,7 @@ def _swap_staged_desktop_app(desktop_dir: Path, staging_dir: Path) -> Optional[Pstopped = _stop_desktop_processes_locking_build(desktop_dir, also_posix=True)if stopped:logger.info("stopped desktop processes before staged app promotion: %s", stopped)- _rename_riding_out_file_lock(live_root, previous)+ _move_live_app_aside(live_root, previous, release_dir, held_by)try:_rename_riding_out_file_lock(staged_root, live_root)except OSError:@@ -292,6 +318,9 @@ def _swap_staged_desktop_app(desktop_dir: Path, staging_dir: Path) -> Optional[Preturn Nonefinally: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 attemptreturn live_root / staged_exe.relative_to(staged_root)@@ -541,23 +570,6 @@ def _stop_desktop_processes_locking_build(desktop_dir: Path, *, also_posix: boolcontinueif release_dir in exe_path.parents:victims.append(proc)- continue- # A foreign helper the app spawned (IME/AV/assistant component) keeps the app's- # cwd = release/<name> after the app itself is killed, and Windows refuses to- # rename a directory that is any live process's cwd - the stage-and-swap then- # dies with WinError 32 (2026-09-22: Sogou IME helper blocked win-unpacked).- try:- cwd = proc.cwd()- except Exception:- continue- if not cwd:- continue- try:- cwd_path = Path(cwd).resolve()- except OSError:- continue- if cwd_path == release_dir or release_dir in cwd_path.parents:- victims.append(proc)stopped: list[int] = []for proc in victims:@@ -1420,7 +1432,13 @@ def _promote_staged_desktop_app(print(f"✗ The built {staged_executable.name} failed its integrity check: {error}\n"f" at: {staged_executable}")raise RuntimeError(f"Desktop build produced no launchable app. {_PREVIOUS_APP_KEPT}")- packaged_executable = _swap_staged_desktop_app(desktop_dir, staging_dir)+ held_by: list = []+ packaged_executable = _swap_staged_desktop_app(desktop_dir, staging_dir, held_by=held_by)+ if packaged_executable is None and held_by:+ from hermes_cli.desktop_release_holders import describe_block, holder_names+ print(describe_block(held_by, desktop_dir / "release"))+ raise RuntimeError(+ f"Could not publish the desktop build: {holder_names(held_by)} is using its folder. {_PREVIOUS_APP_KEPT}")if packaged_executable is None:print(f"✗ Could not install the rebuilt desktop app into {desktop_dir / 'release'}")raise RuntimeError(f"Could not publish the desktop build. {_PREVIOUS_APP_KEPT}")diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1index 9e432f67be0..e4508021715 100644--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@ -706,6 +706,7 @@ function Write-Result([bool]$Ok, [int]$Code, [string]$Message, [bool]$ManualActirun_id = $script:ResultRunIdstarted_at = $script:StartedAtwarnings = @($script:Warnings)+ release_holders = @($script:ReleaseHolders)finished_at = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()} | ConvertTo-Json -Compress[System.IO.File]::WriteAllText($tmp, $obj, (New-Object System.Text.UTF8Encoding $false))@@ -724,6 +725,7 @@ function Write-Result([bool]$Ok, [int]$Code, [string]$Message, [bool]$ManualActi# Post-commit follow-ups (contract C3): each failed step after `hermes update`# exited 0 becomes a warning, never a failed update.$script:Warnings = New-Object System.Collections.Generic.List[string]+$script:ReleaseHolders = New-Object System.Collections.Generic.List[object]$script:FollowupText = New-Object System.Collections.Generic.List[string]$script:ManualFollowup = $false$script:Committed = $false@@ -1706,7 +1708,19 @@ try {# (exit 0); the CLI prints one whole "Desktop app build owed:" line for it. The user is on# the new Hermes but this app was not rebuilt: a manual outcome, never plain success.if (-not $desktopBuildFailed -and $res.Output -match '(?m)^\s*Desktop app build owed: ') {- Add-Followup "build: the Desktop app build is owed by the committed update" "the Desktop app could not be rebuilt, so it still runs its old build. Run 'hermes desktop --force-build' in a terminal to rebuild it; the update log has the build error." -Manual+ # #101789: a program that is not part of Hermes (an IME cloud helper, an AV+ # 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.Add(@{ name = $m.Groups[1].Value; pid = [int]$m.Groups[2].Value; exe = $m.Groups[3].Value })+ }+ if ($script:ReleaseHolders.Count -gt 0) {+ $holderNames = (@($script:ReleaseHolders) | ForEach-Object { "$($_.name) (pid $($_.pid))" }) -join ', '+ Add-Followup "build: the Desktop app folder is in use by $holderNames" "the Desktop app could not be replaced because $holderNames is using its folder. It is not part of Hermes, so it was left running. Close it and update again, or choose to close it below." -Manual+ } else {+ Add-Followup "build: the Desktop app build is owed by the committed update" "the Desktop app could not be rebuilt, so it still runs its old build. Run 'hermes desktop --force-build' in a terminal to rebuild it; the update log has the build error." -Manual+ }}# Every other owed follow-up of the committed update (a gateway still on the old code, adiff --git a/tests/hermes_cli/test_desktop_build_lock_cwd.py b/tests/hermes_cli/test_desktop_build_lock_cwd.pydeleted file mode 100644index 1ef6d69c8f3..00000000000--- a/tests/hermes_cli/test_desktop_build_lock_cwd.py+++ /dev/null@@ -1,114 +0,0 @@-"""The build swap must also stop a foreign process whose CWD is inside ``release``.--Windows refuses to rename a directory that is any live process's current working-directory. A third-party resident helper (Sogou IME's ``SogouCloud.exe``, an AV or-assistant component) whose exe lives elsewhere can still hold-``release/win-unpacked`` as its CWD — it inherited it at spawn time while a build-was running — and then every stage-and-swap dies with WinError 32 even though the-build itself succeeded and the app's own processes are gone (#101789).--The stop list used to be "processes whose exe lives under release", which cannot-see that helper. These tests pin the CWD arm of the check.-"""--import sys--import pytest--pytestmark = pytest.mark.platforms("windows")---class _FakeProc:- """Minimal psutil.Process stand-in: info dict, cwd(), terminate()."""-- def __init__(self, pid, exe, cwd, raises_cwd=False):- self.pid = pid- self.info = {"pid": pid, "exe": str(exe)}- self._cwd = str(cwd)- self._raises_cwd = raises_cwd- self.terminated = False-- def cwd(self):- if self._raises_cwd:- raise OSError("access denied")- return self._cwd-- def terminate(self):- self.terminated = True-- def kill(self): # pragma: no cover - only hit when terminate is ignored- self.terminated = True---class _FakeSelf:- def parents(self):- return []---def release_tree(tmp_path):- release = tmp_path / "release"- (release / "win-unpacked").mkdir(parents=True)- return tmp_path---def _run(monkeypatch, procs):- import psutil-- from hermes_cli import main_desktop as md-- monkeypatch.setattr(psutil, "process_iter", lambda attrs=None: iter(procs))- monkeypatch.setattr(psutil, "Process", lambda pid: _FakeSelf())- monkeypatch.setattr(psutil, "wait_procs", lambda procs, timeout=None: ([], []))- return md._stop_desktop_processes_locking_build---def test_stops_foreign_process_whose_cwd_is_inside_release(monkeypatch, release_tree):- """SogouCloud.exe lives outside the tree but sits in win-unpacked -> must be stopped."""- helper = _FakeProc(- 4242,- exe="C:/Program Files (x86)/SogouInput/16.1/SogouCloud.exe",- cwd=release_tree / "release" / "win-unpacked",- )- stop = _run(monkeypatch, [helper])-- stopped = stop(release_tree)-- assert helper.terminated, "a helper holding release/ as CWD must be stopped"- assert stopped == [4242]---def test_stops_foreign_process_whose_cwd_is_the_release_dir_itself(monkeypatch, release_tree):- helper = _FakeProc(4343, exe="C:/Program Files/AV/scanner.exe", cwd=release_tree / "release")- stop = _run(monkeypatch, [helper])-- assert stop(release_tree) == [4343]- assert helper.terminated---def test_leaves_foreign_process_alone_when_its_cwd_is_elsewhere(monkeypatch, release_tree):- """The negative case: an unrelated resident process must not be killed."""- bystander = _FakeProc(- 5151,- exe="C:/Program Files (x86)/SogouInput/16.1/SogouCloud.exe",- cwd="C:/Windows/System32",- )- stop = _run(monkeypatch, [bystander])-- assert stop(release_tree) == []- assert not bystander.terminated---def test_survives_a_process_that_refuses_cwd(monkeypatch, release_tree):- """Access-denied on cwd() must not abort the scan (fail-open, as the whole helper is)."""- locked = _FakeProc(- 6161,- exe="C:/Program Files/x/guard.exe",- cwd="C:/x",- raises_cwd=True,- )- inside = _FakeProc(6262, exe="C:/Program Files/x/guard2.exe", cwd=release_tree / "release" / "win-unpacked")- stop = _run(monkeypatch, [locked, inside])-- assert stop(release_tree) == [6262]- assert not locked.terminateddiff --git a/tests/hermes_cli/test_desktop_release_holder_windows_live.py b/tests/hermes_cli/test_desktop_release_holder_windows_live.pynew file mode 100644index 00000000000..79e2c735449--- /dev/null+++ b/tests/hermes_cli/test_desktop_release_holder_windows_live.py@@ -0,0 +1,90 @@+"""A program outside Hermes whose working folder is inside release/ blocks the Desktop swap (#101789).++Real processes on a real Windows host: a helper started with its cwd inside+``release/win-unpacked`` (the shape of Sogou IME's ``SogouCloud.exe``, spawned from a Hermes+window and inheriting its cwd) makes Windows refuse the promotion rename. The failure must name+that program, must never close it without consent, and a consented retry must close exactly it+and finish the swap.+"""++from __future__ import annotations++import json+import subprocess+import sys+import time+from pathlib import Path++import psutil+import pytest++from hermes_cli import main_desktop++pytestmark = pytest.mark.platforms("windows")++_HELPER = "import sys, time\nprint('ready', flush=True)\ntime.sleep(300)\n"+++def swap_fixture(tmp_path, monkeypatch):+ desktop_dir = tmp_path / "apps" / "desktop"+ live_root = desktop_dir / "release" / "win-unpacked"+ live_root.mkdir(parents=True)+ (live_root / "Hermes.exe").write_text("old", encoding="utf-8")+ staging = main_desktop._desktop_staging_dir(desktop_dir)+ (staging / "win-unpacked").mkdir(parents=True)+ (staging / "win-unpacked" / "Hermes.exe").write_text("new", encoding="utf-8")+ monkeypatch.setattr(main_desktop, "_DESKTOP_SWAP_RENAME_RETRY_DELAYS_S", (0.2,))+ script = tmp_path / "foreign_helper.py"+ script.write_text(_HELPER, encoding="utf-8")+ helper = subprocess.Popen(+ [sys.executable, str(script)], cwd=live_root, stdout=subprocess.PIPE, text=True,+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),+ )+ # The child opens its cwd handle during its own startup: wait for it before asserting the lock.+ assert helper.stdout.readline().strip() == "ready"+ try:+ yield desktop_dir, staging, live_root, helper+ finally:+ if helper.poll() is None:+ helper.kill()+ helper.wait(10)+++def _promote(desktop_dir: Path, staging: Path) -> tuple[Path | None, str]:+ try:+ return main_desktop._promote_staged_desktop_app(desktop_dir, staging, integrity_check=lambda _p: None), ""+ except RuntimeError as exc:+ return None, str(exc)+++def test_blocked_swap_names_the_foreign_holder_and_leaves_it_running(swap_fixture, capsys):+ desktop_dir, staging, live_root, helper = swap_fixture++ promoted, error = _promote(desktop_dir, staging)++ out = capsys.readouterr().out+ assert promoted is None+ assert f"pid {helper.pid}" in error, error # the update failure names the holder+ assert f"Desktop app folder held by: {psutil.Process(helper.pid).name()} (pid {helper.pid}, " in out, out+ assert helper.poll() is None, "a program outside Hermes was closed without consent"+ 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+ # 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.+ 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")++ promoted, error = _promote(desktop_dir, staging)++ assert error == ""+ assert promoted == live_root / "Hermes.exe"+ assert promoted.read_text(encoding="utf-8") == "new"+ assert helper.wait(10) is not None+ assert not [p.pid for p in tree if p.is_running()]+ assert not consent.exists(), "a consent covers one retry only"+ assert "Closed with your consent: " in capsys.readouterr().outdiff --git a/tests/hermes_cli/test_desktop_release_holders.py b/tests/hermes_cli/test_desktop_release_holders.pynew file mode 100644index 00000000000..93826ee7e1a--- /dev/null+++ b/tests/hermes_cli/test_desktop_release_holders.py@@ -0,0 +1,75 @@+"""Release-folder holders are named, and closed only with consent (#101789).++Real child processes on any host: the cwd detection and the consent rules are not+Windows-specific (only the rename refusal is; that half runs in+``test_desktop_release_holder_windows_live.py`` on a Windows runner).+"""++from __future__ import annotations++import json+import subprocess+import sys+import time++import psutil+import pytest++from hermes_cli.desktop_release_holders import CONSENT_FILE_NAME, release_after_refused_rename++_HELPER = "import time\nprint('ready', flush=True)\ntime.sleep(300)\n"+++def holder(tmp_path):+ release = tmp_path / "apps" / "desktop" / "release"+ (release / "win-unpacked").mkdir(parents=True)+ script = tmp_path / "foreign_helper.py"+ script.write_text(_HELPER, encoding="utf-8")+ proc = subprocess.Popen([sys.executable, str(script)], cwd=release / "win-unpacked",+ stdout=subprocess.PIPE, text=True)+ assert proc.stdout.readline().strip() == "ready"+ try:+ yield release, proc+ finally:+ if proc.poll() is None:+ proc.kill()+ 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 _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):+ release, proc = holder+ exe = psutil.Process(proc.pid).exe()++ 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)++ 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+++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)++ assert proc.pid in closed+ assert proc.wait(10) is not Nonediff --git a/tests/scripts/desktop_update/test_desktop_update_windows_release_holders.py b/tests/scripts/desktop_update/test_desktop_update_windows_release_holders.pynew file mode 100644index 00000000000..83e3353ab0c--- /dev/null+++ b/tests/scripts/desktop_update/test_desktop_update_windows_release_holders.py@@ -0,0 +1,60 @@+"""#101789 on the real Windows hand-off script: a Desktop swap blocked by a program outside Hermes.++A real ``windows.ps1`` drives a published launcher whose ``hermes update`` is a scripted stand-in+printing exactly what ``hermes_cli.desktop_release_holders`` prints when Windows refused the+promotion 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.+"""+from __future__ import annotations++import json+import os+from pathlib import Path+import subprocess++import pytest++from tests.installation_launcher_fixture import publish_fixture_launcher++ROOT = Path(__file__).resolve().parent.parent.parent.parent+SCRIPT = ROOT / 'scripts/desktop-update/windows.ps1'+EXE = r'D:\Program Files (x86)\SogouInput\16.7.0.4912\SogouCloud.exe'+CLI = """+import sys+from pathlib import Path+def main():+ if '--version' in sys.argv:+ print('Install directory: ' + str(Path(__file__).resolve().parents[1])); return 0+ if '--help' in sys.argv:+ 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 build owed: desktop app build failed', flush=True)+ print('Update complete!', flush=True)+ return 0+if __name__ == '__main__':+ sys.exit(main())+""".replace('EXE_PATH', EXE.replace('\\', '\\\\'))++[email protected]('windows')+def test_blocked_swap_result_names_the_holder_for_the_desktop(tmp_path: Path) -> None:+ 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()+ proc = subprocess.run(+ ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(SCRIPT),+ '-InstallRoot', str(install), '-NoUi', '-NoGateway'],+ check=False, cwd=tmp_path, capture_output=True, text=True, timeout=150,+ env={**os.environ, 'HERMES_HOME': str(home), 'HERMES_RUNTIME_DIR': str(tmp_path / 'empty-store'),+ 'PYTHONIOENCODING': 'utf-8'},+ )+ result = json.loads((home / '.hermes-update-result.json').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 'SogouCloud.exe (pid 4242)' in result['message'], result+ assert 'not part of Hermes' in result['message'], result