diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.sh index 1459fe6aa7..1ad37ecdb6 100755 --- a/scripts/desktop-update/posix.sh +++ b/scripts/desktop-update/posix.sh @@ -22,7 +22,8 @@ # [-- ] linux: filtered launch args to replay # # The shim (ui.html in a chromeless browser app window) is decoration: it -# polls /progress for `done` or `error` and reacts. It owns nothing -- +# polls /progress for the current stage or a terminal event and reacts. The +# stages come from the gates below, never from child output. It owns nothing -- # relaunch, result file, marker hygiene all happen here, identically, when # no renderer exists. No chromium-family browser found = no UI, fine. # @@ -64,6 +65,7 @@ LOG_DIR="$HERMES_HOME/logs"; mkdir -p "$LOG_DIR" 2>/dev/null || true LOG="$LOG_DIR/desktop-update-handoff.log" RESULT="$HERMES_HOME/.hermes-update-result.json" STATUS="${TMPDIR:-/tmp}/hermes-update-status.$$" +STARTED_AT="$(date +%s)" # the shim's elapsed clock; see serve-ui.py UI_SERVER_PID="" UI_BROWSER_PID="" FINAL_CODE=1 FINAL_MSG="update did not complete" @@ -147,9 +149,19 @@ notify_fallback() { # status message — renderer-free recovery surface. log "NOTICE: no notification surface accepted; outcome reaches the user via the result dialog on next launch: $2" } -publish() { # status message -- atomic replace; the server reads per poll +write_status() { # status message -- atomic replace; the server reads per poll printf '{"status":"%s","message":"%s"}' "$(json_escape "$1")" "$(json_escape "$2")" > "$STATUS.tmp" \ && mv -f "$STATUS.tmp" "$STATUS" 2>/dev/null || true +} + +publish_stage() { # a long wait the orchestrator is already gating on. No poll + # beat (that would add a second per stage to every update) and no + # notification fallback (there is nothing here for the user to act on). + write_status "running" "$1" +} + +publish() { # terminal event -- the page must render it before teardown + write_status "$1" "$2" [ -n "$UI_SERVER_PID" ] && sleep 1 # one poll beat to render the state [ -z "$UI_SERVER_PID" ] && notify_fallback "$1" "$2" } @@ -178,7 +190,7 @@ start_ui() { browser="$(find_browser)" { [ -f "$html" ] && [ -n "$py" ] && [ -n "$browser" ]; } || { log "shim: no renderer; skipping UI"; return; } - publish "running" "" + publish_stage "" # The Desktop's final teardown targets the updater process group. Put both # UI processes in their own sessions so neither the HTTP server nor a Chrome # renderer becomes collateral damage (Chrome surfaces that renderer death as @@ -190,7 +202,7 @@ start_ui() { # window showed ERR_CONNECTION_REFUSED for the whole run; upstream #66753). # stop_ui ends the server with SIGKILL instead — it is stateless HTTP. "$py" -c 'import os, signal, sys; os.setsid(); signal.signal(signal.SIGTERM, signal.SIG_IGN); signal.signal(signal.SIGHUP, signal.SIG_IGN); os.execv(sys.argv[1], sys.argv[1:])' \ - "$py" "$SCRIPT_DIR/serve-ui.py" "$html" "$STATUS" > "$LOG_DIR/desktop-update-ui-port" 2>>"$LOG" & + "$py" "$SCRIPT_DIR/serve-ui.py" "$html" "$STATUS" "$STARTED_AT" > "$LOG_DIR/desktop-update-ui-port" 2>>"$LOG" & UI_SERVER_PID=$! for i in $(seq 1 10); do port="$(tr -cd '0-9' < "$LOG_DIR/desktop-update-ui-port" 2>/dev/null)" @@ -264,6 +276,7 @@ mac_swap() { # the copy in. Every step checked; a failed final move ROLLS BACK so the # user always has a launchable app, and the result file tells the truth. if [ "$FINAL_CODE" -eq 0 ] && [ -n "$rebuilt" ] && [ -d "$RELAUNCH_TARGET" ] && [ "$rebuilt" != "$RELAUNCH_TARGET" ]; then + publish_stage "Installing the new app" rm -rf "$RELAUNCH_TARGET.new" "$RELAUNCH_TARGET.old" 2>/dev/null || true if ! /usr/bin/ditto "$rebuilt" "$RELAUNCH_TARGET.new"; then rm -rf "$RELAUNCH_TARGET.new" 2>/dev/null || true @@ -486,6 +499,7 @@ cd "$INSTALL_ROOT" || { } export PYTHONUNBUFFERED=1 log "running: hermes update --yes --gateway --branch $BRANCH" +publish_stage "Updating code and dependencies" OUT="$("$HERMES_BIN" update --yes --gateway --branch "$BRANCH" 2>&1)"; CODE=$? printf '%s\n' "$OUT" >> "$LOG" 2>/dev/null log "hermes update exit code: $CODE" @@ -494,6 +508,7 @@ if [ "$CODE" -ne 0 ] && [ "$CODE" -ne 2 ]; then # Retry once: update-boundary class (fresh code on disk, stale in memory). # Exit 2 ("close all Hermes windows") is not retryable. log "retrying once (freshly pulled fix loads on the second run)" + publish_stage "Retrying update" OUT="$("$HERMES_BIN" update --yes --gateway --branch "$BRANCH" 2>&1)"; CODE=$? printf '%s\n' "$OUT" >> "$LOG" 2>/dev/null log "retry exit code: $CODE" @@ -505,6 +520,7 @@ trap 'on_signal TERM' TERM # and call it success -- retry the build once, propagate honestly. if [ "$CODE" -eq 0 ] && printf '%s' "$OUT" | grep -q "Desktop build failed"; then log "desktop build failed inside hermes update; retrying build" + publish_stage "Rebuilding Desktop" "$HERMES_BIN" desktop --force-build --build-only >> "$LOG" 2>&1 || { FINAL_CODE=6 FINAL_MSG="Code and dependencies updated, but the Desktop app rebuild failed - you are running the previous build. Run hermes desktop --force-build from a terminal to retry." exit 6 diff --git a/scripts/desktop-update/serve-ui.py b/scripts/desktop-update/serve-ui.py index 8d0a6bfe61..87801df099 100644 --- a/scripts/desktop-update/serve-ui.py +++ b/scripts/desktop-update/serve-ui.py @@ -4,30 +4,45 @@ Two GET routes: / serves ui.html, /progress serves the status file the orchestrator script writes ({"status": "running"|"done"|"error", ...}). Exists because a file:// page cannot receive events from a detached process. Prints the chosen ephemeral port on stdout, serves until killed. + +`elapsed_seconds` is stamped per request, not read from the status file: +stages are minutes apart, so a value frozen at the last publish would sit +still through the longest waits -- exactly the stall the page exists to +disprove. Windows' in-process listener computes it the same way. """ import http.server import json import socketserver import sys +import time html_path, status_path = sys.argv[1], sys.argv[2] +started_at = float(sys.argv[3]) if len(sys.argv) > 3 else time.time() with open(html_path, "rb") as f: HTML = f.read() +def progress_body(): + try: + with open(status_path, "rb") as f: + state = json.loads(f.read()) + if not isinstance(state, dict): + raise ValueError(state) + except Exception: + state = {"status": "running", "message": ""} + state["elapsed_seconds"] = max(0, int(time.time() - started_at)) + + return json.dumps(state).encode("utf-8") + + class Handler(http.server.BaseHTTPRequestHandler): def log_message(self, format, *args): # noqa: A002 - base class signature pass def do_GET(self): if self.path.startswith("/progress"): - try: - with open(status_path, "rb") as f: - body = f.read() - json.loads(body) - except Exception: - body = b'{"status":"running","message":""}' + body = progress_body() ctype = "application/json; charset=utf-8" elif self.path == "/": body, ctype = HTML, "text/html; charset=utf-8" diff --git a/scripts/desktop-update/ui.html b/scripts/desktop-update/ui.html index 0009a98e52..6e55cb694c 100644 --- a/scripts/desktop-update/ui.html +++ b/scripts/desktop-update/ui.html @@ -3,17 +3,20 @@ Quiet shim page for the desktop update hand-off (Windows + POSIX). Served over loopback by the orchestrator (windows.ps1 / posix.sh) into a - chromeless browser app window. Pure veneer: polls /progress for `done` or - `error` and reacts; owns nothing (relaunch, result file, marker hygiene - all live in the orchestrator, which runs identically with no UI at all). + chromeless browser app window. Pure veneer: polls /progress for the current + hand-off stage or a terminal event and reacts; owns nothing (relaunch, + result file, marker hygiene all live in the orchestrator, which runs + identically with no UI at all). The visual is PR #75895's update hand-off screen, ported verbatim: - Loader: the desktop's "Fourier Flow" curve. Math + tuning lifted from apps/bootstrap-installer/src/components/loader.tsx (itself lifted from apps/desktop/src/components/ui/loader.tsx 'fourier-flow'). Keep the constants in sync if the desktop's curve is retuned. - - Layout: loader (size-20) + one title + one muted line. No progress bar, - no stage list, no log pane, no cancel (see #75895 for the arguments). + - Layout: loader (size-20) + one title + one muted stage/elapsed line. No + progress bar, stage list, log pane, or cancel (see #75895 for the + arguments). Elapsed comes from the orchestrator or is omitted -- a clock + started here would measure when this window painted, not the update. - Appearance follows the OS. Dark seeds are the installer's neutral charcoal (#232323 base, foreground #d6d6d6) — never brand blue. --> @@ -89,6 +92,7 @@ font-size: 12px; line-height: 1.5; color: var(--muted-foreground); + white-space: pre-line; } p code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; @@ -195,12 +199,16 @@ render(performance.now()) - /* ── Event listener: done | error, nothing else ───────────────────────── */ + /* ── Event listener: running stage or terminal outcome ───────────────── */ const titleEl = document.getElementById('title') const lineEl = document.getElementById('line') const glyphEl = document.getElementById('glyph') + const defaultLine = lineEl.textContent /* what a stage-less run says */ let settled = false + const elapsedText = s => + s < 60 ? `${s}s elapsed` : `${Math.floor(s / 60)}m ${s % 60}s elapsed` + function settle(state) { settled = true window.cancelAnimationFrame(frame) @@ -209,7 +217,13 @@ function apply(state) { if (settled) return - if (state.status === 'done') { + if (state.status === 'running') { + const stage = state.message || defaultLine + const elapsed = Number(state.elapsed_seconds) + lineEl.textContent = Number.isFinite(elapsed) && elapsed >= 0 + ? `${stage}\n${elapsedText(Math.floor(elapsed))}` + : stage + } else if (state.status === 'done') { settle('done') glyphEl.textContent = '\u2713' lineEl.textContent = 'Opening Hermes\u2026' diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1 index c5e68f85cd..8bb2956c74 100644 --- a/scripts/desktop-update/windows.ps1 +++ b/scripts/desktop-update/windows.ps1 @@ -83,6 +83,8 @@ $LogDir = Join-Path $HermesHome "logs" $LogPath = Join-Path $LogDir "desktop-update-handoff.log" $ResultPath = Join-Path $HermesHome ".hermes-update-result.json" $script:Ui = $null +$script:UiStage = "Hermes will open once done." # until the first gate; matches ui.html +$script:UiStopwatch = [System.Diagnostics.Stopwatch]::StartNew() function Write-HandoffLog([string]$Message) { $line = "{0:yyyy-MM-ddTHH:mm:ssK} {1}" -f (Get-Date), $Message @@ -93,15 +95,16 @@ function Write-HandoffLog([string]$Message) { # ── The shim: repo-owned HTML in a chromeless Edge app window ────────────── # The window is a veneer, not a participant: the update runs identically with # or without it (Edge missing/failed degrades to the WinForms card below, -# then log-only). It streams nothing and knows nothing — it polls /progress -# for one of two events, `done` or `error`, and reacts. The loopback listener +# then log-only). It never consumes child output; it polls /progress for the +# current hand-off stage or a terminal event and reacts. The loopback listener # is not a web server in any meaningful sense; it exists because file:// pages # cannot receive events from a detached process. Salvaged from the web-shell # spike (Co-authored-by: teknium1), reshaped to the quiet update-surface # contract (#75895/#83634): loader, one title, one line, no dashboard. $script:UiState = [hashtable]::Synchronized(@{ - status = "running" # running | done | error - message = "" + status = "running" # running | done | manual | error + message = $script:UiStage + clock = $script:UiStopwatch }) $script:UiServer = $null # @{ Listener; Runspace; PowerShell; Port; EdgeProc } @@ -158,9 +161,11 @@ function Start-UiServer([string]$HtmlPath) { # Drain headers so the client doesn't see a reset mid-send. while ($true) { $h = $reader.ReadLine(); if ($null -eq $h -or $h -eq "") { break } } if ($request -match "^GET /progress") { + $elapsed = [Math]::Floor($State.clock.Elapsed.TotalSeconds) $snapshot = @{ - status = $State.status - message = $State.message + status = $State.status + message = $State.message + elapsed_seconds = $elapsed } | ConvertTo-Json -Compress Send-Response $stream "200 OK" "application/json; charset=utf-8" ([System.Text.Encoding]::UTF8.GetBytes($snapshot)) } elseif ($request -match "^GET / ") { @@ -210,9 +215,36 @@ function Publish-UiEvent([string]$Status, [string]$Message) { if ($script:UiServer) { Start-Sleep -Milliseconds 900 } } +function Get-UiElapsedText { + $elapsed = [Math]::Floor($script:UiStopwatch.Elapsed.TotalSeconds) + if ($elapsed -lt 60) { return "${elapsed}s elapsed" } + $minutes = [Math]::Floor($elapsed / 60) + $seconds = $elapsed % 60 + return "${minutes}m ${seconds}s elapsed" +} + +function Get-UiProgressLine { + return "$script:UiStage`r`n$(Get-UiElapsedText)" +} + +function Publish-UiProgress([string]$Message) { + # Stages come from the orchestrator's own control flow. Child stdout and + # stderr remain asynchronously drained in Invoke-HermesStep and are never + # read or parsed for UI updates. + $script:UiStage = $Message + $script:UiState.message = $Message + $script:UiState.status = "running" + if ($script:Ui) { + try { + $script:Ui.Sub.Text = Get-UiProgressLine + [System.Windows.Forms.Application]::DoEvents() + } catch {} + } +} + # ── Fallback card (no Edge / no HTML): same shape in WinForms ────────────── -# Matches the shim pixel-for-pixel in spirit -- loader, one title, one static -# line, OS light/dark -- so degrading is invisible to the user. +# Matches the shim pixel-for-pixel in spirit -- loader, one title, one live +# stage/elapsed line, OS light/dark -- so degrading is invisible to the user. function Get-AppsUseLightTheme { try { $v = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" -Name AppsUseLightTheme -ErrorAction Stop @@ -291,7 +323,7 @@ function Show-ProgressWindow { $title.TextAlign = "MiddleCenter" $title.SetBounds(16, 156, 248, 28) $sub = New-Object System.Windows.Forms.Label - $sub.Text = "Hermes will open once done." + $sub.Text = Get-UiProgressLine $sub.Font = New-Object System.Drawing.Font("Segoe UI", 9) $sub.ForeColor = $mute $sub.TextAlign = "TopCenter" @@ -309,7 +341,16 @@ function Show-ProgressWindow { if ($script:Win32) { [HermesHandoff.Win32]::SetForegroundWindow($form.Handle) | Out-Null } } catch {} [System.Windows.Forms.Application]::DoEvents() - $script:Ui = [pscustomobject]@{ Form = $form; Bar = $bar; Title = $title; Sub = $sub } + $script:Ui = [pscustomobject]@{ Form = $form; Bar = $bar; Title = $title; Sub = $sub; Timer = $null } + $timer = New-Object System.Windows.Forms.Timer + $timer.Interval = 1000 + $timer.Add_Tick({ + if ($script:Ui -and $script:Ui.Sub) { + $script:Ui.Sub.Text = Get-UiProgressLine + } + }) + $script:Ui.Timer = $timer + $timer.Start() } catch { # Headless session / WinForms unavailable: degrade to log-only. $script:Ui = $null @@ -331,6 +372,7 @@ function Show-ErrorFinale([string]$Message) { if (-not $script:Ui) { return } try { $ui = $script:Ui + if ($ui.Timer) { $ui.Timer.Stop() } $ui.Bar.Visible = $false $ui.Title.Text = "Failed to update" $ui.Sub.Text = "Run `"hermes debug share`" in a terminal to send a report." @@ -372,6 +414,7 @@ function Show-ManualFinale([string]$Message) { if (-not $script:Ui) { return } try { $ui = $script:Ui + if ($ui.Timer) { $ui.Timer.Stop() } $ui.Bar.Visible = $false $ui.Title.Text = "Update complete" $ui.Sub.Text = $Message @@ -404,7 +447,13 @@ function Close-ProgressWindow { Stop-UiServer } if ($script:Ui) { - try { $script:Ui.Form.Close() } catch {} + try { + if ($script:Ui.Timer) { + $script:Ui.Timer.Stop() + $script:Ui.Timer.Dispose() + } + $script:Ui.Form.Close() + } catch {} $script:Ui = $null } } @@ -535,8 +584,8 @@ function Start-DesktopRelaunch { } function Invoke-HermesStep([string]$Exe, [string[]]$HermesArgs, [string]$Tag) { - # The window shows nothing live, so no line-pump: both pipes drain - # asynchronously (no deadlock however chatty the child) while a small + # The window does not stream child output, so no line-pump: both pipes + # drain asynchronously (no deadlock however chatty the child) while a small # DoEvents loop keeps the marquee animating through long silent # stretches (pip installs) -- the old EndOfStream pump blocked on quiet # children and froze it. Full output still lands in the hand-off log @@ -606,6 +655,7 @@ if ($SelfTestUi) { Write-HandoffLog "SELF-TEST: shim simulation (no update will run)" $hold = 6 if ($env:HERMES_SELFTEST_HOLD_SECONDS) { $hold = [int]$env:HERMES_SELFTEST_HOLD_SECONDS } + Publish-UiProgress "Testing quiet update" Start-Sleep -Seconds $hold if ($env:HERMES_SELFTEST_FAIL) { Show-ErrorFinale "self-test error state" @@ -633,6 +683,7 @@ try { } # -- 1. Wait for the Desktop to exit (FAIL CLOSED) ---------------------- + Publish-UiProgress "Waiting for Hermes to close" if ($DesktopPid -gt 0) { $deadline = (Get-Date).AddSeconds(30) while ((Get-Date) -lt $deadline) { @@ -653,6 +704,7 @@ try { } # -- 2. Wait for the venv shim to unlock (FAIL CLOSED) ------------------ + Publish-UiProgress "Preparing Hermes files" $shim = Join-Path $InstallRoot "venv\Scripts\hermes.exe" if (Test-Path -LiteralPath $shim) { $unlocked = $false @@ -725,6 +777,7 @@ try { } $updateArgs = @("-m", "hermes_cli.main", "update", "--yes", "--gateway", "--force", "--branch", $Branch) Write-HandoffLog ("running: python " + ($updateArgs -join " ")) + Publish-UiProgress "Updating code and dependencies" $res = Invoke-HermesStep $pythonExe $updateArgs "update" Write-HandoffLog "hermes update exit code: $($res.Code)" @@ -732,6 +785,7 @@ try { # One retry for the update-boundary class (fresh code on disk, stale # code in memory). Exit 2 ("close all Hermes windows") is not retryable. Write-HandoffLog "first attempt failed; retrying once (freshly pulled fix loads on the second run)" + Publish-UiProgress "Retrying update" $res = Invoke-HermesStep $pythonExe $updateArgs "update" Write-HandoffLog "retry exit code: $($res.Code)" } @@ -744,6 +798,7 @@ try { $desktopBuildFailed = $false if ($res.Code -eq 0 -and $res.Output -match "Desktop build failed") { Write-HandoffLog "hermes update reported a desktop build failure (non-fatal there, fatal here); retrying build" + Publish-UiProgress "Rebuilding Desktop" $rebuild = Invoke-HermesStep $pythonExe @("-m", "hermes_cli.main", "desktop", "--force-build", "--build-only") "rebuild" Write-HandoffLog "desktop rebuild exit code: $($rebuild.Code)" if ($rebuild.Code -ne 0) { $desktopBuildFailed = $true } @@ -775,6 +830,7 @@ try { Close-ProgressWindow [void](Start-DesktopRelaunch) } else { + Publish-UiProgress "Opening Hermes" $cameBack = Start-DesktopRelaunch if (-not $cameBack -and $RelaunchExe) { # Launch was due and did not verifiably land: truthful result diff --git a/tests/test_desktop_update_shim_progress.py b/tests/test_desktop_update_shim_progress.py new file mode 100644 index 0000000000..bf6bf6b712 --- /dev/null +++ b/tests/test_desktop_update_shim_progress.py @@ -0,0 +1,195 @@ +"""The shim's /progress contract, exercised against the real posix hand-off. + +`ui.html` is one page for three operating systems, so the stage-and-elapsed +line it renders is only as good as the weakest orchestrator behind it. These +drive the real `posix.sh` and the real `serve-ui.py` -- no mocks, no source +reading -- because the posix half is the one that had no coverage. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from urllib.request import urlopen + +import pytest + +REPO_ROOT = Path(__file__).resolve().parent.parent +SHIM_DIR = REPO_ROOT / "scripts" / "desktop-update" + +# posix.sh re-execs itself through these to detach from Electron's process +# group; without them the hand-off never reaches its own main flow. +requires_posix_handoff = pytest.mark.skipif( + not (os.path.exists("/bin/bash") and os.path.exists("/usr/bin/python3")), + reason="posix.sh detaches through /bin/bash and /usr/bin/python3", +) + + +# ── serve-ui.py: what the page actually receives ─────────────────────────── + + +@pytest.fixture +def progress(tmp_path): + """The real loopback server, over a status file the test drives.""" + status = tmp_path / "hermes-update-status" + proc = subprocess.Popen( + [ + sys.executable, + str(SHIM_DIR / "serve-ui.py"), + str(SHIM_DIR / "ui.html"), + str(status), + str(time.time()), + ], + stdout=subprocess.PIPE, + text=True, + ) + try: + port = int(proc.stdout.readline().strip()) + + class Progress: + def publish(self, state: str, message: str) -> None: + status.write_text(json.dumps({"status": state, "message": message})) + + def corrupt(self) -> None: + status.write_text("}not json{") + + def poll(self) -> dict: + with urlopen(f"http://127.0.0.1:{port}/progress", timeout=5) as r: + return json.loads(r.read()) + + yield Progress() + finally: + proc.kill() + proc.wait(timeout=5) + + +def test_elapsed_advances_between_publishes(progress): + """The clock is stamped per request, not frozen at the last publish. + + Stages are minutes apart during a real update, so a value written into + the status file would sit still through exactly the long waits this line + exists to disprove. + """ + progress.publish("running", "Updating code and dependencies") + first = progress.poll() + time.sleep(1.2) + second = progress.poll() + + assert first["status"] == "running" + assert second["message"] == first["message"] == "Updating code and dependencies" + assert second["elapsed_seconds"] > first["elapsed_seconds"] + + +def test_every_state_carries_a_clock(progress): + """Including the stage-less running state posix publishes at window open.""" + for state, message in [ + ("running", ""), + ("running", "Installing the new app"), + ("done", ""), + ("manual", "Reopen Hermes to finish."), + ("error", "Update failed."), + ]: + progress.publish(state, message) + served = progress.poll() + + assert served["status"] == state + assert served["message"] == message + assert served["elapsed_seconds"] >= 0 + + +def test_unreadable_status_still_serves_a_running_state(progress): + """A window frozen on its last frame is the bug being fixed here.""" + progress.corrupt() + served = progress.poll() + + assert served["status"] == "running" + assert served["elapsed_seconds"] >= 0 + + +# ── posix.sh: the stages it publishes at its own gates ───────────────────── + +# Stands in for `hermes update`, and reports the stage that was on screen +# while it ran -- the update child is the only thing that can observe the +# window's state at the exact moment of the longest wait in the hand-off. +FAKE_HERMES = """#!/bin/bash +n="$(cat "$HERMES_TEST_CALLS" 2>/dev/null || echo 0)"; n=$((n + 1)) +printf '%s' "$n" > "$HERMES_TEST_CALLS" +for f in "$TMPDIR"/hermes-update-status.[0-9]*; do + case "$f" in *.tmp) continue ;; esac + cp "$f" "$HERMES_TEST_CAPTURE.$n" 2>/dev/null +done +exit "$(cat "$HERMES_TEST_EXITS.$n" 2>/dev/null || echo 0)" +""" + + +def _run_handoff(tmp_path, exits: dict[int, int]) -> list[dict]: + """Run the real hand-off end to end; return the stage seen at each call.""" + install_root = tmp_path / "hermes-agent" + (install_root / "venv" / "bin").mkdir(parents=True) + hermes = install_root / "venv" / "bin" / "hermes" + hermes.write_text(FAKE_HERMES) + hermes.chmod(0o755) + + capture = tmp_path / "seen" + calls = tmp_path / "calls" + for call, code in exits.items(): + (tmp_path / f"exits.{call}").write_text(str(code)) + + env = { + **os.environ, + "TMPDIR": str(tmp_path), + "HERMES_TEST_CAPTURE": str(capture), + "HERMES_TEST_CALLS": str(calls), + "HERMES_TEST_EXITS": str(tmp_path / "exits"), + } + # The hand-off daemonizes and the launcher exits immediately; the result + # file is the orchestrator's own completion signal. + subprocess.run( + [ + "/bin/bash", + str(SHIM_DIR / "posix.sh"), + "--install-root", + str(install_root), + "--no-ui", + ], + env=env, + timeout=60, + check=True, + ) + + result = tmp_path / ".hermes-update-result.json" + deadline = time.monotonic() + 45 + while time.monotonic() < deadline and not result.exists(): + time.sleep(0.1) + assert result.exists(), "hand-off never wrote its result file" + + seen = sorted(tmp_path.glob("seen.*"), key=lambda p: int(p.suffix[1:])) + + return [json.loads(p.read_text()) for p in seen] + + +@requires_posix_handoff +def test_update_gate_publishes_its_stage_before_running(tmp_path): + """`hermes update` is the longest wait in the hand-off and the one the + Discord report sat through; the window must name it while it happens.""" + stages = _run_handoff(tmp_path, {1: 0}) + + assert len(stages) == 1 + assert stages[0]["status"] == "running" + assert stages[0]["message"] == "Updating code and dependencies" + + +@requires_posix_handoff +def test_retry_gate_publishes_a_distinct_stage(tmp_path): + """A failed first attempt doubles the wait -- the second pass must not + look like the first one hanging.""" + stages = _run_handoff(tmp_path, {1: 1, 2: 0}) + + assert [s["message"] for s in stages] == [ + "Updating code and dependencies", + "Retrying update", + ] diff --git a/tests/test_desktop_update_windows_progress.py b/tests/test_desktop_update_windows_progress.py new file mode 100644 index 0000000000..d3f67a07e1 --- /dev/null +++ b/tests/test_desktop_update_windows_progress.py @@ -0,0 +1,93 @@ +"""The Windows hand-off keeps serving progress while its main thread blocks. + +windows.ps1 answers /progress from a dedicated runspace precisely so the +window keeps moving through the long silent stretches (`hermes update`, pip, +the desktop rebuild) that made an 18-minute update look hung. This drives the +real script and polls the real listener; the posix half of the same contract +is covered in test_desktop_update_shim_progress.py. +""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import time +from pathlib import Path +from urllib.request import urlopen + +import pytest + +pytestmark = pytest.mark.windows_only + +REPO_ROOT = Path(__file__).resolve().parent.parent +WINDOWS_UPDATE_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1" + + +def _read_progress(url: str) -> dict[str, object]: + with urlopen(f"{url}progress", timeout=5) as response: + return json.loads(response.read().decode("utf-8")) + + +def test_progress_advances_while_the_orchestrator_blocks(tmp_path: Path) -> None: + powershell = shutil.which("powershell.exe") + assert powershell, "Windows updater tests require Windows PowerShell." + + output_path = tmp_path / "self-test-output.log" + env = os.environ.copy() + env["TEMP"] = str(tmp_path) + env["TMP"] = str(tmp_path) + env["HERMES_SELFTEST_HOLD_SECONDS"] = "4" + + with output_path.open("wb") as output: + process = subprocess.Popen( + [ + powershell, + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + str(WINDOWS_UPDATE_PS1), + "-SelfTestUi", + "-NoUi", + ], + stdout=output, + stderr=subprocess.STDOUT, + env=env, + ) + + try: + deadline = time.monotonic() + 20 + shim_url = None + while time.monotonic() < deadline: + text = output_path.read_text(encoding="utf-8", errors="replace") + match = re.search(r"SELF-TEST: shim at (http://127\.0\.0\.1:\d+/)", text) + if match: + shim_url = match.group(1) + break + if process.poll() is not None: + break + time.sleep(0.1) + + assert shim_url, output_path.read_text(encoding="utf-8", errors="replace") + first = _read_progress(shim_url) + time.sleep(1.5) + second = _read_progress(shim_url) + + # The stage is whatever the orchestrator last published -- it must + # reach the page verbatim and must not churn on its own. + assert first["status"] == "running" + assert first["message"] + assert second["message"] == first["message"] + # The main thread is asleep for the whole window above. If elapsed + # only moved when the orchestrator published, it would be frozen here + # -- which is what a stalled update looks like to the user. + assert int(second["elapsed_seconds"]) > int(first["elapsed_seconds"]) + + assert process.wait(timeout=20) == 0 + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5)