Skip to content

The agent that grows with you

feat(desktop): repo-owned Windows update hand-off script - stop depending on the frozen hermes-setup binary

Teknium92be912d7355
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 5e84f722ce5..a7c248b26bc 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -204,6 +204,7 @@ import {
import { isOfficialSshRemote, OFFICIAL_REPO_HTTPS_URL } from './update-remote'
import {
resolveStagedUpdaterBinary,
+ resolveUpdateScriptHandoff,
spawnUpdaterProcess,
stagedUpdaterSupportsPrewrittenMarker
} from './updater-process'
@@ -2847,35 +2848,45 @@ async function applyUpdates(opts = {}) {
if (!updater) {
// No staged updater binary — this is a CLI-installed user (they ran
// `hermes desktop`, never the Tauri installer that self-copies
- // hermes-setup.exe into HERMES_HOME). They DO have a working `hermes`
- // on PATH / in the venv, so the correct path is the one-liner in their
- // native medium. We show the EXACT command, branch-pinned to the
- // checkout they're on — bare `hermes update` defaults to main and would
- // silently switch a bb/gui (or any non-main) install off-branch. Mirror
- // the GUI button's contract: append --branch <current> for non-main
- // checkouts, keep it bare for main so the card stays clean.
+ // hermes-setup.exe into HERMES_HOME). On Windows the repo hand-off
+ // script serves them just as well as installer users — it only needs
+ // PowerShell and the checkout — so fall through to the normal hand-off
+ // when the script exists. Only when the checkout predates the script do
+ // we surface the manual one-liner.
const updateRoot = resolveUpdateRoot()
- let command = 'hermes update'
- try {
- const head = await runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: updateRoot })
- const current = (head.stdout || '').trim()
+ if (!resolveUpdateScriptHandoff(updateRoot)) {
+ // They DO have a working `hermes` on PATH / in the venv, so the
+ // correct path is the one-liner in their native medium. We show the
+ // EXACT command, branch-pinned to the checkout they're on — bare
+ // `hermes update` defaults to main and would silently switch a
+ // bb/gui (or any non-main) install off-branch. Mirror the GUI
+ // button's contract: append --branch <current> for non-main
+ // checkouts, keep it bare for main so the card stays clean.
+ let command = 'hermes update'
+
+ try {
+ const head = await runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: updateRoot })
+ const current = (head.stdout || '').trim()
- if (head.code === 0 && current && current !== 'HEAD') {
- const branch = await resolveHealedBranch(updateRoot, current)
+ if (head.code === 0 && current && current !== 'HEAD') {
+ const branch = await resolveHealedBranch(updateRoot, current)
- if (branch !== 'main') {
- command = `hermes update --branch ${branch}`
+ if (branch !== 'main') {
+ command = `hermes update --branch ${branch}`
+ }
}
+ } catch {
+ // Best-effort: fall back to bare `hermes update` if branch detection fails.
}
- } catch {
- // Best-effort: fall back to bare `hermes update` if branch detection fails.
- }
- rememberLog(`[updates] no staged updater; surfacing manual \`${command}\` for CLI install at ${updateRoot}`)
- emitUpdateProgress({ stage: 'manual', message: command, percent: null })
+ rememberLog(`[updates] no staged updater; surfacing manual \`${command}\` for CLI install at ${updateRoot}`)
+ emitUpdateProgress({ stage: 'manual', message: command, percent: null })
+
+ return { ok: true, manual: true, command, hermesRoot: updateRoot }
+ }
- return { ok: true, manual: true, command, hermesRoot: updateRoot }
+ rememberLog('[updates] no staged updater; using repo hand-off script for CLI install')
}
const handoffConflict = updateHandoffConflict(HERMES_HOME)
@@ -2973,41 +2984,91 @@ async function applyUpdates(opts = {}) {
// Detached so the updater outlives this process — it needs us GONE before
// `hermes update` will run (the venv shim is locked while we live).
- const child = spawnUpdaterProcess(updater, updaterArgs, {
- cwd: HERMES_HOME,
- env: {
- ...process.env,
- HERMES_HOME,
- PATH: pathWithHermesManagedNode(venvBin)
- },
- detached: true,
- stdio: 'ignore'
- })
-
- // Write the update-in-progress marker IMMEDIATELY — before the 2.5s
- // quit dwell. The Tauri updater won't write its own marker for several
- // seconds (window init + manifest), and during that gap our renderer
- // can reconnect and spawn a fresh backend that re-locks .pyd files in
- // the venv. By writing the marker ourselves the renderer's
- // waitForUpdateToFinish() gate sees a live update and parks instead.
- // The updater overwrites this with its own PID later; same format.
//
- // SKIPPED for pre-#74782 staged updaters: those have no self-PID
- // exclusion, so they read this very marker as a foreign live owner and
- // abort with "Another Hermes update is already running (PID <itself>)" —
- // an unbreakable loop, because the update that would replace the stale
- // binary is the one being refused. Losing the anti-respawn hardening is
- // strictly better than never updating again, and the updater still writes
- // its own marker moments later.
- if (Number.isInteger(child.pid) && stagedUpdaterSupportsPrewrittenMarker(updater)) {
- writeUpdateMarker(HERMES_HOME, child.pid)
- } else if (Number.isInteger(child.pid)) {
+ // Prefer the repo-owned hand-off script over the staged Tauri binary.
+ // The staged binary is frozen (no self-update path) and historically runs
+ // months-stale updater logic — pre-#67369 cache resolver, pre-#74782
+ // marker adoption — producing failures that were fixed on main long ago
+ // (2026-08-09 incident). scripts/desktop-update.ps1 ships WITH the
+ // checkout, so each `hermes update` refreshes the code that drives the
+ // next one. Checkouts that predate the script fall back to the binary
+ // path unchanged.
+ const scriptHandoff = resolveUpdateScriptHandoff(updateRoot)
+ let child
+
+ if (scriptHandoff) {
+ const scriptArgs = [
+ ...scriptHandoff.args,
+ '-InstallRoot',
+ updateRoot,
+ '-Branch',
+ branch,
+ '-DesktopPid',
+ String(process.pid),
+ '-RelaunchExe',
+ process.execPath
+ ]
+
+ child = spawnUpdaterProcess(scriptHandoff.command, scriptArgs, {
+ cwd: HERMES_HOME,
+ env: {
+ ...process.env,
+ HERMES_HOME,
+ PATH: pathWithHermesManagedNode(venvBin)
+ },
+ detached: true,
+ stdio: 'ignore'
+ })
+
+ // The script's own pid owns the marker. Unlike the stale-binary path
+ // there is NO adoption hazard: hermes_cli/update_lock.py accepts a live
+ // marker held by a process ANCESTOR (the script is the `hermes update`
+ // child's parent), so the pre-write is always safe here — no
+ // stagedUpdaterSupportsPrewrittenMarker() mtime heuristics needed.
+ if (Number.isInteger(child.pid)) {
+ writeUpdateMarker(HERMES_HOME, child.pid)
+ }
+
rememberLog(
- `[updates] skipping marker pre-write: staged updater predates self-adopt (${updater}); it would refuse its own claim`
+ `[updates] launched repo hand-off script: ${scriptHandoff.scriptPath} (branch ${branch}); exiting desktop to release venv shim`
)
- }
+ } else {
+ child = spawnUpdaterProcess(updater, updaterArgs, {
+ cwd: HERMES_HOME,
+ env: {
+ ...process.env,
+ HERMES_HOME,
+ PATH: pathWithHermesManagedNode(venvBin)
+ },
+ detached: true,
+ stdio: 'ignore'
+ })
- rememberLog(`[updates] launched updater: ${updater} ${updaterArgs.join(' ')}; exiting desktop to release venv shim`)
+ // Write the update-in-progress marker IMMEDIATELY — before the 2.5s
+ // quit dwell. The Tauri updater won't write its own marker for several
+ // seconds (window init + manifest), and during that gap our renderer
+ // can reconnect and spawn a fresh backend that re-locks .pyd files in
+ // the venv. By writing the marker ourselves the renderer's
+ // waitForUpdateToFinish() gate sees a live update and parks instead.
+ // The updater overwrites this with its own PID later; same format.
+ //
+ // SKIPPED for pre-#74782 staged updaters: those have no self-PID
+ // exclusion, so they read this very marker as a foreign live owner and
+ // abort with "Another Hermes update is already running (PID <itself>)" —
+ // an unbreakable loop, because the update that would replace the stale
+ // binary is the one being refused. Losing the anti-respawn hardening is
+ // strictly better than never updating again, and the updater still writes
+ // its own marker moments later.
+ if (Number.isInteger(child.pid) && stagedUpdaterSupportsPrewrittenMarker(updater)) {
+ writeUpdateMarker(HERMES_HOME, child.pid)
+ } else if (Number.isInteger(child.pid)) {
+ rememberLog(
+ `[updates] skipping marker pre-write: staged updater predates self-adopt (${updater}); it would refuse its own claim`
+ )
+ }
+
+ rememberLog(`[updates] launched updater: ${updater} ${updaterArgs.join(' ')}; exiting desktop to release venv shim`)
+ }
// Linger on the "updating — don't reopen" overlay long enough for the user
// to actually read it (and to bridge the gap until the updater's own window
diff --git a/apps/desktop/electron/updater-process.test.ts b/apps/desktop/electron/updater-process.test.ts
index e781fe3efa3..d6bda4e91a9 100644
--- a/apps/desktop/electron/updater-process.test.ts
+++ b/apps/desktop/electron/updater-process.test.ts
@@ -7,6 +7,7 @@ import { test } from 'vitest'
import {
MARKER_SELF_ADOPT_EPOCH_MS,
resolveStagedUpdaterBinary,
+ resolveUpdateScriptHandoff,
spawnUpdaterProcess,
stagedUpdaterSupportsPrewrittenMarker
} from './updater-process'
@@ -165,3 +166,36 @@ test('resolveStagedUpdaterBinary returns null on Windows when nothing is staged'
assert.equal(resolved, null)
})
+
+test('resolveUpdateScriptHandoff prefers the repo script on Windows when present', () => {
+ const root = String.raw`C:\Users\hermes\AppData\Local\hermes\hermes-agent`
+ const expected = path.join(root, 'scripts', 'desktop-update.ps1')
+
+ const handoff = resolveUpdateScriptHandoff(root, {
+ isWindows: true,
+ fileExists: candidate => candidate === expected
+ })
+
+ assert.ok(handoff)
+ assert.equal(handoff.command, 'powershell')
+ assert.equal(handoff.scriptPath, expected)
+ assert.deepEqual(handoff.args, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', expected])
+})
+
+test('resolveUpdateScriptHandoff returns null when the checkout predates the script', () => {
+ const handoff = resolveUpdateScriptHandoff(String.raw`C:\Users\hermes\AppData\Local\hermes\hermes-agent`, {
+ isWindows: true,
+ fileExists: () => false
+ })
+
+ assert.equal(handoff, null)
+})
+
+test('resolveUpdateScriptHandoff is Windows-only (POSIX updates in place)', () => {
+ const handoff = resolveUpdateScriptHandoff('/home/hermes/.hermes/hermes-agent', {
+ isWindows: false,
+ fileExists: () => true
+ })
+
+ assert.equal(handoff, null)
+})
diff --git a/apps/desktop/electron/updater-process.ts b/apps/desktop/electron/updater-process.ts
index 97b1d9651af..66faf9316b4 100644
--- a/apps/desktop/electron/updater-process.ts
+++ b/apps/desktop/electron/updater-process.ts
@@ -9,6 +9,58 @@ export interface UpdaterChild {
unref: () => void
}
+export interface ResolveUpdateScriptHandoffDeps {
+ isWindows?: boolean
+ fileExists?: (candidate: string) => boolean
+}
+
+export interface UpdateScriptHandoff {
+ command: string
+ args: string[]
+ scriptPath: string
+}
+
+/**
+ * Repo-owned Windows update hand-off (frozen-binary escape hatch).
+ *
+ * The staged Tauri `hermes-setup.exe` has no self-update path, so every
+ * updater-side fix only reaches users when a new binary is built, signed and
+ * published — which historically lags main by months and strands users on
+ * long-fixed bugs (cache resolver #67369, marker self-adopt #74782; the
+ * 2026-08-09 incident chain). `scripts/desktop-update.ps1` lives in the repo
+ * checkout instead: every `hermes update` refreshes the code that drives the
+ * NEXT update, and only PowerShell itself is frozen.
+ *
+ * Returns the spawn recipe when the script exists in the checkout, or null
+ * (caller falls back to the staged binary — old checkouts that predate the
+ * script keep working unchanged). Windows-only by the same policy as
+ * resolveStagedUpdaterBinary: POSIX updates in place via
+ * applyUpdatesPosixInApp and needs no hand-off at all.
+ */
+export function resolveUpdateScriptHandoff(
+ updateRoot: string,
+ deps: ResolveUpdateScriptHandoffDeps = {}
+): UpdateScriptHandoff | null {
+ const isWindows = deps.isWindows ?? process.platform === 'win32'
+
+ if (!isWindows) {
+ return null
+ }
+
+ const scriptPath = path.join(updateRoot, 'scripts', 'desktop-update.ps1')
+ const exists = deps.fileExists ?? stagedFileExists
+
+ if (!exists(scriptPath)) {
+ return null
+ }
+
+ return {
+ command: 'powershell',
+ args: ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
+ scriptPath
+ }
+}
+
export interface ResolveStagedUpdaterBinaryDeps {
isWindows?: boolean
fileExists?: (candidate: string) => boolean
diff --git a/scripts/desktop-update.ps1 b/scripts/desktop-update.ps1
new file mode 100644
index 00000000000..fe90707975e
--- /dev/null
+++ b/scripts/desktop-update.ps1
@@ -0,0 +1,149 @@
+# desktop-update.ps1 -- repo-owned Windows Desktop update hand-off.
+#
+# WHY THIS EXISTS (the frozen-binary problem): the Desktop's Update button
+# used to hand off exclusively to the staged Tauri binary
+# (%HERMES_HOME%\hermes-setup.exe). That binary has no self-update path --
+# copy_self_to_hermes_home deliberately no-ops during --update -- so every
+# updater-side fix (cache refresh #67369, marker self-adopt #74782, straggler
+# handling) only reaches users when a new installer is built, signed, and
+# published. In practice binaries go months stale and users hit long-fixed
+# bugs on every update (the 2026-08-09 incident chain).
+#
+# This script inverts that: it lives in the repo checkout, so EVERY
+# `hermes update` refreshes the very code that drives the next update. The
+# Desktop spawns it detached (see resolveUpdateScriptHandoff in
+# apps/desktop/electron/main.ts) and exits; only PowerShell itself -- an OS
+# component -- is "frozen".
+#
+# CONTRACT (keep in sync with apps/desktop/electron/main.ts):
+# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\desktop-update.ps1
+# -InstallRoot <path> repo checkout (HERMES_HOME\hermes-agent)
+# -Branch <ref> branch to update against
+# -DesktopPid <pid> the Electron main process to wait out
+# [-RelaunchExe <path>] Hermes.exe to start when done (omit = no relaunch)
+# [-NoMarkerCleanup] leave .hermes-update-in-progress in place (tests)
+#
+# The Desktop pre-writes HERMES_HOME\.hermes-update-in-progress with THIS
+# process's pid before quitting. Contracts that already exist make that safe:
+# * hermes_cli/update_lock.py `acquire` treats a live marker owned by a
+# process ANCESTOR as its own orchestrator -- our `hermes update` child
+# adopts the claim instead of refusing (no HANDOFF_PID_ENV needed).
+# * electron/update-marker.ts gates backend startup on the marker, so a
+# relaunched Desktop parks instead of spawning a venv-locking backend
+# into the update window.
+# We delete the marker on every exit path; a crash self-heals via the
+# 20-minute staleness ceiling both readers enforce.
+
+param(
+ [Parameter(Mandatory = $true)][string]$InstallRoot,
+ [string]$Branch = "main",
+ [int]$DesktopPid = 0,
+ [string]$RelaunchExe = "",
+ [switch]$NoMarkerCleanup
+)
+
+$ErrorActionPreference = "Continue"
+$HermesHome = Split-Path -Parent $InstallRoot
+$MarkerPath = Join-Path $HermesHome ".hermes-update-in-progress"
+$LogPath = Join-Path $HermesHome "logs\desktop-update-handoff.log"
+
+function Write-HandoffLog([string]$Message) {
+ $line = "{0:yyyy-MM-ddTHH:mm:ssK} {1}" -f (Get-Date), $Message
+ try { Add-Content -LiteralPath $LogPath -Value $line -Encoding UTF8 } catch {}
+ Write-Host $line
+}
+
+function Remove-Marker {
+ if ($NoMarkerCleanup) { return }
+ try {
+ if (Test-Path -LiteralPath $MarkerPath) {
+ Remove-Item -LiteralPath $MarkerPath -Force -ErrorAction SilentlyContinue
+ Write-HandoffLog "removed update marker"
+ }
+ } catch {}
+}
+
+try {
+ Write-HandoffLog "hand-off start: root=$InstallRoot branch=$Branch desktopPid=$DesktopPid pid=$PID"
+
+ # -- 1. Wait for the Desktop to actually exit -------------------------
+ # The Desktop quits right after spawning us, but Electron teardown is
+ # asynchronous. Bounded wait; a Desktop that never exits is a bug we
+ # surface rather than fight.
+ if ($DesktopPid -gt 0) {
+ $deadline = (Get-Date).AddSeconds(30)
+ while ((Get-Date) -lt $deadline) {
+ $proc = Get-Process -Id $DesktopPid -ErrorAction SilentlyContinue
+ if (-not $proc) { break }
+ Start-Sleep -Milliseconds 300
+ }
+ $still = Get-Process -Id $DesktopPid -ErrorAction SilentlyContinue
+ if ($still) {
+ Write-HandoffLog "WARNING: desktop pid $DesktopPid still alive after 30s; proceeding (hermes update has its own guards)"
+ } else {
+ Write-HandoffLog "desktop exited"
+ }
+ }
+
+ # -- 2. Wait for the venv shim to unlock ------------------------------
+ # Mirrors the Rust updater's is_locked(): a running exe refuses O_RDWR.
+ $shim = Join-Path $InstallRoot "venv\Scripts\hermes.exe"
+ if (Test-Path -LiteralPath $shim) {
+ $deadline = (Get-Date).AddSeconds(20)
+ while ((Get-Date) -lt $deadline) {
+ try {
+ $fs = [System.IO.File]::Open($shim, 'Open', 'ReadWrite', 'None')
+ $fs.Close()
+ Write-HandoffLog "venv shim unlocked"
+ break
+ } catch {
+ Start-Sleep -Milliseconds 400
+ }
+ }
+ }
+
+ # -- 3. Run the update from the CURRENT checkout ----------------------
+ # hermes update handles everything downstream: gateway pause, venv-holder
+ # guard (with orphan reap), dep sync, desktop rebuild, skills/config sync,
+ # gateway restart. --force skips only the hermes.exe shim guard, which by
+ # this point is provably unlocked (step 2); the venv-python holder guard
+ # stays active. Our marker claim is adopted by the child via the
+ # process-ancestry rule in hermes_cli/update_lock.py.
+ $hermesExe = Join-Path $InstallRoot "venv\Scripts\hermes.exe"
+ if (-not (Test-Path -LiteralPath $hermesExe)) {
+ Write-HandoffLog "ERROR: $hermesExe missing - install too broken for the script hand-off; falling back is the Desktop's job"
+ exit 3
+ }
+ Write-HandoffLog "running: hermes update --yes --gateway --force --branch $Branch"
+ & $hermesExe update --yes --gateway --force --branch $Branch 2>&1 | ForEach-Object {
+ Write-HandoffLog ("update| " + $_)
+ }
+ $updateExit = $LASTEXITCODE
+ Write-HandoffLog "hermes update exit code: $updateExit"
+
+ if ($updateExit -ne 0) {
+ # One retry for the update-boundary class (fresh code on disk, stale
+ # code in memory -- same rationale as the Tauri updater's retry).
+ # Skip for exit 2: "close all Hermes windows" is not retryable.
+ if ($updateExit -ne 2) {
+ Write-HandoffLog "first attempt failed; retrying once (freshly pulled fix loads on the second run)"
+ & $hermesExe update --yes --gateway --force --branch $Branch 2>&1 | ForEach-Object {
+ Write-HandoffLog ("update| " + $_)
+ }
+ $updateExit = $LASTEXITCODE
+ Write-HandoffLog "retry exit code: $updateExit"
+ }
+ }
+
+ # -- 4. Relaunch the Desktop ------------------------------------------
+ # Marker must be gone BEFORE relaunch or the new Desktop parks on it.
+ Remove-Marker
+ if ($RelaunchExe -and (Test-Path -LiteralPath $RelaunchExe)) {
+ Write-HandoffLog "relaunching desktop: $RelaunchExe"
+ Start-Process -FilePath $RelaunchExe -WorkingDirectory (Split-Path -Parent $RelaunchExe) | Out-Null
+ }
+
+ exit $updateExit
+} finally {
+ Remove-Marker
+}