Skip to content

The agent that grows with you

ci(windows): REAL-flow GUI E2E — website setup.exe, headed clicks, GUI updater

Teknium381cc65c78be
diff --git a/.github/workflows/desktop-windows-e2e.yml b/.github/workflows/desktop-windows-e2e.yml
index 74a0509aaa3..26243856dd7 100644
--- a/.github/workflows/desktop-windows-e2e.yml
+++ b/.github/workflows/desktop-windows-e2e.yml
@@ -30,7 +30,10 @@ on:
# Nightly, off the hour to dodge the top-of-hour runner crunch.
- cron: '40 6 * * *'
push:
- branches: [main]
+ branches:
+ - main
+ # TEMPORARY pre-merge validation of the gui-e2e job: remove before merge.
+ - hermes/hermes-76e68435
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'
- 'v[0-9]+.[0-9]+.[0-9]+.[0-9]+'
@@ -102,3 +105,73 @@ jobs:
path: e2e-logs
retention-days: 7
if-no-files-found: ignore
+
+ # ── The REAL user flow ──────────────────────────────────────────────────
+ # Same staging, but every leg is the surface a user touches: the website's
+ # Hermes-Setup.exe run HEADED with AutoHotkey clicking Install/Launch, then
+ # the installed Electron app driven by Playwright clicking Settings →
+ # About → "Update now" twice (→ CURRENT, → synthetic NEXT), asserting the
+ # detached updater chain end-to-end (result JSON, marker, sha, relaunch).
+ # Proof artifacts: per-step renderer screenshots, full-desktop frames every
+ # 3s, ahk.log, bootstrap-installer.log, desktop-update-handoff.log.
+ #
+ # GitHub's windows-latest runners have an interactive desktop session, so
+ # headed GUI automation works without RDP tricks (same substrate the prior
+ # AutoHotkey attempt in #68183 targeted).
+ gui-e2e:
+ name: "REAL flow: website setup.exe → GUI update → GUI update"
+ runs-on: windows-latest
+ timeout-minutes: 180
+ # Deliberately NOT `needs: e2e` — the jobs run independently, so each
+ # provides rollback coverage for the other and a GUI-layer flake cannot
+ # mask a machinery regression.
+
+ env:
+ HERMES_E2E_WORKROOT: ${{ github.workspace }}\..\hermes-desktop-gui-e2e
+
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ fetch-depth: 0
+
+ - name: Stage serve repo (BASE / CURRENT / NEXT)
+ shell: powershell
+ run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\install\windows-desktop-gui-e2e.ps1 -Phase stage
+
+ - name: Install via website Hermes-Setup.exe (headed, AHK-clicked)
+ shell: powershell
+ run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\install\windows-desktop-gui-e2e.ps1 -Phase install-gui
+
+ - name: GUI update to CURRENT (real Update-now click)
+ shell: powershell
+ run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\install\windows-desktop-gui-e2e.ps1 -Phase update-gui-to-current
+
+ - name: GUI update to NEXT (real Update-now click)
+ shell: powershell
+ run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\install\windows-desktop-gui-e2e.ps1 -Phase update-gui-to-next
+
+ - name: Collect proof + logs
+ if: always()
+ shell: powershell
+ run: |
+ $out = "gui-e2e-proof"
+ New-Item -ItemType Directory -Path $out -Force | Out-Null
+ $work = $env:HERMES_E2E_WORKROOT
+ $home_ = Join-Path $work "hermes-home"
+ foreach ($pair in @(
+ @{ src = (Join-Path $work "proof"); dst = "proof" },
+ @{ src = (Join-Path $work "shas.json"); dst = "shas.json" },
+ @{ src = (Join-Path $home_ "logs"); dst = "logs" },
+ @{ src = (Join-Path $home_ ".hermes-update-result.json"); dst = ".hermes-update-result.json" }
+ )) {
+ if (Test-Path $pair.src) { Copy-Item $pair.src (Join-Path $out $pair.dst) -Recurse -Force }
+ }
+
+ - name: Upload proof + logs
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: desktop-windows-gui-e2e-proof-${{ github.sha }}
+ path: gui-e2e-proof
+ retention-days: 14
+ if-no-files-found: ignore
diff --git a/tests/install/e2e-assets/drive-update.cjs b/tests/install/e2e-assets/drive-update.cjs
new file mode 100644
index 00000000000..c328ff89380
--- /dev/null
+++ b/tests/install/e2e-assets/drive-update.cjs
@@ -0,0 +1,203 @@
+// drive-update.cjs — launch the INSTALLED Hermes.exe (real Electron desktop
+// app) under Playwright's Electron driver and perform the update the way a
+// user does: Settings -> About -> "Update now". Screenshots at every step.
+//
+// Run from the installed checkout's apps/desktop directory (so
+// @playwright/test resolves from ITS node_modules — the same deps the
+// installed app was built with):
+//
+// node <this file> <path-to-Hermes.exe> <proof-dir>
+//
+// Exit codes: 0 = update hand-off started and the app quit (the detached
+// updater takes it from there — the PowerShell driver polls for the result);
+// 1 = any step failed. The driver treats nonzero as leg failure.
+//
+// This intentionally does NOT call any store/bridge function directly: only
+// real clicks on the real UI, so a regression in the button, the About
+// panel, the overlay, or the renderer->main bridge fails the test.
+
+const path = require('node:path')
+const fs = require('node:fs')
+
+const { _electron } = require('@playwright/test')
+
+const exePath = process.argv[2]
+const proofDir = process.argv[3]
+
+if (!exePath || !proofDir) {
+ console.error('usage: node drive-update.cjs <Hermes.exe> <proof-dir>')
+ process.exit(1)
+}
+
+fs.mkdirSync(proofDir, { recursive: true })
+
+function log(msg) {
+ console.log(`[drive-update] ${new Date().toISOString()} ${msg}`)
+}
+
+async function shot(page, name) {
+ const file = path.join(proofDir, `${name}.png`)
+
+ try {
+ await page.screenshot({ path: file })
+ log(`screenshot: ${file}`)
+ } catch (err) {
+ log(`screenshot ${name} failed: ${err.message}`)
+ }
+}
+
+// Hard ceiling so a hung renderer can't wedge the CI job; the driver's own
+// step timeout is the real guard, this is belt-and-braces.
+const KILL_AFTER_MS = 15 * 60 * 1000
+const killer = setTimeout(() => {
+ console.error('[drive-update] global timeout — aborting')
+ process.exit(1)
+}, KILL_AFTER_MS)
+killer.unref()
+
+async function clickFirstVisible(page, locators, description, timeoutMs) {
+ const deadline = Date.now() + timeoutMs
+
+ for (;;) {
+ for (const make of locators) {
+ const locator = make(page).first()
+
+ try {
+ if (await locator.isVisible()) {
+ await locator.click()
+ log(`clicked: ${description}`)
+
+ return true
+ }
+ } catch {
+ // locator invalid in this state; try the next
+ }
+ }
+ if (Date.now() > deadline) {
+ return false
+ }
+ await page.waitForTimeout(500)
+ }
+}
+
+async function main() {
+ log(`launching ${exePath}`)
+
+ const app = await _electron.launch({
+ executablePath: exePath,
+ args: ['--disable-gpu', '--no-sandbox'],
+ // Inherit the driver's env: HERMES_HOME (isolated install) and
+ // GIT_CONFIG_GLOBAL (URL redirect to the staged serve repo) MUST reach
+ // the main process so its update check fetches from the staged repo.
+ env: { ...process.env },
+ timeout: 120_000
+ })
+
+ const page = await app.firstWindow({ timeout: 120_000 })
+ log('first window acquired')
+
+ // Boot: wait for the composer to exist — the shell is mounted by then.
+ // The real backend (`hermes serve`) is booting underneath; give it time.
+ await page.waitForSelector('textarea, [contenteditable="true"]', {
+ state: 'attached',
+ timeout: 300_000
+ })
+ log('renderer booted (composer attached)')
+ await page.waitForTimeout(3000)
+ await shot(page, '01-app-booted')
+
+ // ── Open Settings (titlebar gear) ─────────────────────────────────────
+ const openedSettings = await clickFirstVisible(
+ page,
+ [
+ p => p.getByLabel('Open settings'),
+ p => p.locator('[aria-label="Open settings"]'),
+ p => p.locator('[title="Open settings"]'),
+ p => p.getByRole('button', { name: 'Open settings' })
+ ],
+ 'Open settings',
+ 60_000
+ )
+
+ if (!openedSettings) {
+ await shot(page, 'ERROR-no-settings-button')
+ throw new Error('could not find the Open settings control')
+ }
+ await page.waitForTimeout(1500)
+ await shot(page, '02-settings-open')
+
+ // ── Go to the About section ───────────────────────────────────────────
+ const openedAbout = await clickFirstVisible(
+ page,
+ [
+ p => p.getByRole('tab', { name: 'About' }),
+ p => p.getByRole('button', { name: 'About' }),
+ p => p.getByText('About', { exact: true })
+ ],
+ 'About section',
+ 30_000
+ )
+
+ if (!openedAbout) {
+ await shot(page, 'ERROR-no-about-tab')
+ throw new Error('could not find the About section in Settings')
+ }
+ await page.waitForTimeout(1500)
+ await shot(page, '03-about-panel')
+
+ // ── Wait for "Update now" (appears when behind > 0) ──────────────────
+ // checkUpdates() runs at boot; if its result hasn't landed yet, press
+ // "Check now" like an impatient user would.
+ const updateNow = page.getByRole('button', { name: 'Update now' }).first()
+ let visible = await updateNow.isVisible().catch(() => false)
+
+ if (!visible) {
+ log('Update now not visible yet — clicking Check now')
+ await clickFirstVisible(page, [p => p.getByRole('button', { name: 'Check now' })], 'Check now', 20_000)
+
+ try {
+ await updateNow.waitFor({ state: 'visible', timeout: 120_000 })
+ visible = true
+ } catch {
+ visible = false
+ }
+ }
+
+ if (!visible) {
+ await shot(page, 'ERROR-no-update-now')
+ throw new Error('"Update now" never appeared — update check did not report behind > 0')
+ }
+ await shot(page, '04-update-available')
+
+ // ── The click under test ──────────────────────────────────────────────
+ await updateNow.click()
+ log('clicked: Update now')
+
+ // The "Updating Hermes — this window will close" overlay should appear,
+ // then the app quits (hand-off dwell). Screenshot the overlay while the
+ // window is still alive.
+ await page.waitForTimeout(1200)
+ await shot(page, '05-updating-overlay')
+
+ // ── Wait for the app to quit for the hand-off ─────────────────────────
+ await new Promise((resolve, reject) => {
+ const t = setTimeout(
+ () => reject(new Error('app did not quit within 120s of Update now — hand-off did not start')),
+ 120_000
+ )
+
+ app.on('close', () => {
+ clearTimeout(t)
+ resolve()
+ })
+ })
+
+ log('app quit for updater hand-off — success, the detached updater owns the rest')
+}
+
+main()
+ .then(() => process.exit(0))
+ .catch(err => {
+ console.error(`[drive-update] FAILED: ${err.message}`)
+ process.exit(1)
+ })
diff --git a/tests/install/e2e-assets/install-and-launch.ahk b/tests/install/e2e-assets/install-and-launch.ahk
new file mode 100644
index 00000000000..0b6ec05aa5f
--- /dev/null
+++ b/tests/install/e2e-assets/install-and-launch.ahk
@@ -0,0 +1,126 @@
+#Requires AutoHotkey v2.0
+#SingleInstance Force
+
+; Drive the REAL Hermes-Setup.exe (Tauri bootstrap installer) window:
+; click Install, wait for the install to finish, click Launch, and wait for
+; the real Hermes.exe (Electron desktop) window to appear.
+;
+; Adapted from @ethernet8023's e2e/windows/install-hermes-desktop.ahk
+; (PR #68183) — same ImageSearch approach and button templates; this
+; variant targets windows by process name (ahk_exe) so the installer
+; window and the launched app window (both titled "Hermes") can't be
+; confused, and it actually clicks Launch instead of closing the window,
+; because the Launch hand-off is part of the flow under test.
+;
+; Args: [1] log path [2] setup exe name (default Hermes-Setup.exe)
+
+logPath := A_Args.Length >= 1 ? A_Args[1] : "ahk.log"
+setupExe := A_Args.Length >= 2 ? A_Args[2] : "Hermes-Setup.exe"
+
+Log(text) {
+ msg := Format("[autohotkey] {}`n", text)
+ ToolTip(text)
+ FileAppend(msg, '*')
+ FileAppend(msg, logPath)
+}
+
+OnError(LogError)
+
+LogError(err, mode) {
+ Log(Format("Unhandled error: {}", err.Message))
+ ExitApp(1)
+ return -1 ; suppress the standard error dialog
+}
+
+SetWorkingDir(A_ScriptDir)
+CoordMode("Pixel", "Screen")
+CoordMode("Mouse", "Screen")
+
+ClickWithMarker(x, y, button := "Left") {
+ Click(x, y, button)
+ Sleep(10)
+ MouseMove(30, 30)
+ Log(Format("Clicked at {1}, {2}", x, y))
+}
+
+FindImageInWindow(winTitle, imageFile, &outX, &outY, timeoutMs := 10000, intervalMs := 250)
+{
+ WinGetPos(&wx, &wy, &ww, &wh, winTitle)
+
+ hBitmap := LoadPicture(imageFile)
+ if !hBitmap {
+ throw Error("LoadPicture failed: " imageFile)
+ }
+ bm := Buffer(32, 0) ; BITMAP structure on x64
+ DllCall("GetObject", "Ptr", hBitmap, "Int", bm.Size, "Ptr", bm)
+ width := NumGet(bm, 4, "Int")
+ height := NumGet(bm, 8, "Int")
+
+ startTime := A_TickCount
+ timeLeft := 1
+ Log(Format("Searching for {} in {} ...", imageFile, winTitle))
+ searchImage := Format("*10 {}", imageFile)
+ while (timeLeft > 0)
+ {
+ ; Refresh the window rect each pass — the installer window can move
+ ; or resize between stages.
+ try WinGetPos(&wx, &wy, &ww, &wh, winTitle)
+ if ImageSearch(&x, &y, wx, wy, wx + ww, wy + wh, searchImage)
+ {
+ outX := x + Floor(width / 2)
+ outY := y + Floor(height / 2)
+ Log("Found " imageFile)
+ return
+ }
+ Sleep intervalMs
+ timeLeft := timeoutMs - (A_TickCount - startTime)
+ ToolTip(Format("Searching {} in {} ... {}s left", imageFile, winTitle, Round(timeLeft / 1000, 2)))
+ }
+ throw Error(Format("Failed to find {} in window {}", imageFile, winTitle))
+}
+
+ClickCenterOfImageInWindow(winTitle, imageFile, timeoutMs := 10000, intervalMs := 250)
+{
+ FindImageInWindow(winTitle, imageFile, &x, &y, timeoutMs, intervalMs)
+ ClickWithMarker(x, y)
+}
+
+installerWin := "ahk_exe " setupExe
+appWin := "ahk_exe Hermes.exe"
+
+Log("Waiting for the installer window (" installerWin ") ...")
+try {
+ WinWait(installerWin, , 60)
+} catch {
+ throw Error("installer window did not appear within 60s")
+}
+WinGetPos(&x, &y, &w, &h, installerWin)
+Log(Format("Window found at x={1} y={2} w={3} h={4}", x, y, w, h))
+
+; ── Step 1: click Install ───────────────────────────────────────────────
+ClickCenterOfImageInWindow(installerWin, A_ScriptDir "\install-button.png", 60000)
+Log("Install clicked; waiting for the Launch button (install can take a while)")
+
+; ── Step 2: wait for install to finish (Launch button appears) ──────────
+FindImageInWindow(installerWin, A_ScriptDir "\launch-button.png", &launchX, &launchY, 1000 * 60 * 45)
+Log("Install finished (Launch button visible)")
+
+; ── Step 3: click Launch — the hand-off under test ──────────────────────
+ClickWithMarker(launchX, launchY)
+Log("Launch clicked; waiting for the Hermes desktop app window")
+
+; The installer spawns Hermes.exe detached and exits itself.
+try {
+ WinWait(appWin, , 120)
+} catch {
+ throw Error("Hermes.exe window did not appear within 120s of clicking Launch")
+}
+WinGetPos(&ax, &ay, &aw, &ah, appWin)
+Log(Format("App window appeared at x={1} y={2} w={3} h={4}", ax, ay, aw, ah))
+
+; Give the renderer a few seconds on screen (recorded as proof), then hand
+; control back to the PowerShell driver, which closes the app and re-launches
+; it under Playwright for the update legs.
+Sleep(8000)
+Log("done")
+ExitApp(0)
diff --git a/tests/install/e2e-assets/install-button.png b/tests/install/e2e-assets/install-button.png
new file mode 100644
index 00000000000..feed47bd98f
Binary files /dev/null and b/tests/install/e2e-assets/install-button.png differ
diff --git a/tests/install/e2e-assets/launch-button.png b/tests/install/e2e-assets/launch-button.png
new file mode 100644
index 00000000000..6ab89a75ca3
Binary files /dev/null and b/tests/install/e2e-assets/launch-button.png differ
diff --git a/tests/install/windows-desktop-gui-e2e.ps1 b/tests/install/windows-desktop-gui-e2e.ps1
new file mode 100644
index 00000000000..57cbe2bf24b
--- /dev/null
+++ b/tests/install/windows-desktop-gui-e2e.ps1
@@ -0,0 +1,499 @@
+# ============================================================================
+# Windows Desktop GUI install + update E2E driver (the REAL user flow)
+# ============================================================================
+# Same before -> current -> next staging as windows-desktop-e2e.ps1, but every
+# leg goes through the surfaces a real user touches:
+#
+# INSTALL - downloads the production Hermes-Setup.exe from the website,
+# launches it HEADED, and AutoHotkey clicks Install, waits,
+# then clicks Launch. The real Electron Hermes.exe must appear.
+# The exe runs EXACTLY as shipped: it downloads its own pinned
+# install.ps1 from GitHub raw and installs its baked
+# BUILD_PIN_COMMIT — so the "before" version in this harness is
+# the website release pin, the literal starting point of every
+# real GUI user. (The strict HEAD~1 -> HEAD guarantee is the
+# contract harness's job; this one covers the production pin.)
+# UPDATE x2 - launches the installed Hermes.exe under Playwright's Electron
+# driver and CLICKS Settings -> About -> "Update now". That
+# spawns the production hand-off (desktop-update.ps1 via
+# cmd start, or the staged hermes-setup.exe on old checkouts),
+# the app quits, the detached updater runs `hermes update`,
+# rebuilds the desktop, and RELAUNCHES Hermes.exe. We assert
+# the whole chain: target sha, marker cleanup, working hermes,
+# and the relaunched app window. Leg 1 lands on CURRENT, leg 2
+# on the synthetic NEXT.
+#
+# PROOF: screenshots at every renderer step (Playwright), full-desktop
+# screenshots around the installer/AHK phases, a rolling desktop capture
+# (every 3s) for the whole run, ahk.log, and the hand-off log. All uploaded
+# as CI artifacts.
+#
+# DEVIATIONS FROM PRODUCTION (each one deliberate and small):
+# * git URL redirect (GIT_CONFIG_GLOBAL) routes the canonical repo URLs
+# to the staged serve.git — the staging requirement itself. The
+# installer's raw.githubusercontent install.ps1 download and the pinned
+# ZIP fallback are NOT redirected (real network, as shipped).
+# * serve.git gets uploadpack.allowAnySHA1InWant=true so the installer's
+# baked -Commit pin can be fetched from the redirected clone the same
+# way GitHub's upload-pack allows it.
+# * A dummy provider key is seeded after install so the update legs see
+# the ready app shell instead of the onboarding overlay (a real
+# updating user has a configured provider).
+#
+# Usage mirrors windows-desktop-e2e.ps1:
+# powershell -File tests\install\windows-desktop-gui-e2e.ps1 -Phase all
+# ... -Phase stage / install-gui / update-gui-to-current / update-gui-to-next
+# ============================================================================
+
+param(
+ [ValidateSet("stage", "install-gui", "update-gui-to-current", "update-gui-to-next", "all")]
+ [string]$Phase = "all",
+ [string]$RepoRoot = "",
+ [string]$WorkRoot = $(if ($env:HERMES_E2E_WORKROOT) { $env:HERMES_E2E_WORKROOT } else { Join-Path $env:TEMP "hermes-desktop-gui-e2e" }),
+ [string]$SetupExeUrl = "https://hermes-assets.nousresearch.com/Hermes-Setup.exe"
+)
+
+$ErrorActionPreference = "Stop"
+$ProgressPreference = "SilentlyContinue"
+
+if (-not $RepoRoot) {
+ $RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
+}
+
+$ServeRepo = Join-Path $WorkRoot "serve.git"
+$HermesHome = Join-Path $WorkRoot "hermes-home"
+$InstallDir = Join-Path $HermesHome "hermes-agent"
+$StatePath = Join-Path $WorkRoot "shas.json"
+$ProofRoot = Join-Path $WorkRoot "proof"
+$AhkDir = Join-Path $WorkRoot "ahk"
+$AssetsDir = Join-Path $PSScriptRoot "e2e-assets"
+
+$RepoUrlHttps = "https://github.com/NousResearch/hermes-agent.git"
+$RepoUrlSsh = "[email protected]:NousResearch/hermes-agent.git"
+
+function Write-Step([string]$Message) {
+ Write-Host ""
+ Write-Host ("=" * 74)
+ Write-Host "== $Message"
+ Write-Host ("=" * 74)
+}
+
+function Assert-True([bool]$Condition, [string]$Message) {
+ if (-not $Condition) {
+ throw "E2E ASSERTION FAILED: $Message"
+ }
+ Write-Host " [ok] $Message"
+}
+
+function Invoke-Git([string[]]$GitArgs) {
+ $prevEap = $ErrorActionPreference
+ $ErrorActionPreference = "Continue"
+ try {
+ $output = & git @GitArgs 2>&1
+ if ($LASTEXITCODE -ne 0) {
+ throw "git $($GitArgs -join ' ') failed (exit $LASTEXITCODE): $output"
+ }
+ return ($output | Out-String).Trim()
+ } finally {
+ $ErrorActionPreference = $prevEap
+ }
+}
+
+function Set-GitRedirect {
+ # Same mechanism (and same install.ps1-clobber rationale) as
+ # windows-desktop-e2e.ps1: a driver-owned gitconfig via GIT_CONFIG_GLOBAL.
+ $fileUrl = "file:///" + ($ServeRepo -replace "\\", "/")
+ $gitCfg = Join-Path $WorkRoot "e2e-gitconfig"
+ if (-not (Test-Path -LiteralPath $WorkRoot)) {
+ New-Item -ItemType Directory -Path $WorkRoot -Force | Out-Null
+ }
+ @"
+[url "$fileUrl"]
+ insteadOf = $RepoUrlHttps
+ insteadOf = $RepoUrlSsh
+"@ | Set-Content -LiteralPath $gitCfg -Encoding ASCII
+ $env:GIT_CONFIG_GLOBAL = $gitCfg
+ Write-Host " git URL redirect via GIT_CONFIG_GLOBAL=$gitCfg"
+}
+
+function Read-State {
+ if (-not (Test-Path -LiteralPath $StatePath)) {
+ throw "State file not found: $StatePath -- run '-Phase stage' first."
+ }
+ return Get-Content -LiteralPath $StatePath -Raw | ConvertFrom-Json
+}
+
+function Get-InstalledHead {
+ return Invoke-Git @("-C", $InstallDir, "rev-parse", "HEAD")
+}
+
+function Get-DesktopExe {
+ foreach ($c in @(
+ (Join-Path $InstallDir "apps\desktop\release\win-unpacked\Hermes.exe"),
+ (Join-Path $InstallDir "apps\desktop\release\win-arm64-unpacked\Hermes.exe")
+ )) {
+ if (Test-Path -LiteralPath $c) { return $c }
+ }
+ return $null
+}
+
+function Test-HermesRuns([string]$Label) {
+ $hermesExe = Join-Path $InstallDir "venv\Scripts\hermes.exe"
+ Assert-True (Test-Path -LiteralPath $hermesExe) "$Label -- venv\Scripts\hermes.exe exists"
+ & $hermesExe --version 2>&1 | ForEach-Object { Write-Host " hermes --version| $_" }
+ Assert-True ($LASTEXITCODE -eq 0) "$Label -- hermes --version exits 0"
+}
+
+function Save-DesktopScreenshot([string]$OutFile) {
+ # Single full-desktop screenshot (all monitors' primary screen).
+ try {
+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing
+ $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
+ $bmp = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)
+ $gfx = [System.Drawing.Graphics]::FromImage($bmp)
+ $gfx.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)
+ $bmp.Save($OutFile, [System.Drawing.Imaging.ImageFormat]::Png)
+ $gfx.Dispose(); $bmp.Dispose()
+ Write-Host " desktop screenshot: $OutFile"
+ } catch {
+ Write-Host " WARNING: desktop screenshot failed: $($_.Exception.Message)"
+ }
+}
+
+function Start-DesktopRecorder([string]$OutDir) {
+ # Rolling desktop capture: one PNG every 3s from a detached PowerShell,
+ # capped at 800 frames (~40 min). Proof that survives any step failure.
+ New-Item -ItemType Directory -Path $OutDir -Force | Out-Null
+ $script = Join-Path $WorkRoot "recorder.ps1"
+ @'
+param([string]$OutDir)
+Add-Type -AssemblyName System.Windows.Forms, System.Drawing
+for ($i = 0; $i -lt 800; $i++) {
+ if (Test-Path (Join-Path $OutDir "STOP")) { break }
+ try {
+ $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
+ $bmp = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)
+ $gfx = [System.Drawing.Graphics]::FromImage($bmp)
+ $gfx.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)
+ $bmp.Save((Join-Path $OutDir ("frame-{0:D4}.png" -f $i)), [System.Drawing.Imaging.ImageFormat]::Png)
+ $gfx.Dispose(); $bmp.Dispose()
+ } catch {}
+ Start-Sleep -Seconds 3
+}
+'@ | Set-Content -LiteralPath $script -Encoding UTF8
+ $proc = Start-Process -FilePath "powershell.exe" `
+ -ArgumentList "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $script, "-OutDir", $OutDir `
+ -WindowStyle Hidden -PassThru
+ Write-Host " desktop recorder started (pid $($proc.Id)) -> $OutDir"
+ return $proc
+}
+
+function Stop-DesktopRecorder($proc, [string]$OutDir) {
+ try { Set-Content -LiteralPath (Join-Path $OutDir "STOP") -Value "stop" } catch {}
+ if ($proc) {
+ try { $proc.WaitForExit(8000) | Out-Null } catch {}
+ try { if (-not $proc.HasExited) { Stop-Process -Id $proc.Id -Force } } catch {}
+ }
+}
+
+function Stop-HermesAppProcesses([string]$Label) {
+ # Close the desktop app the blunt way between legs (a user quitting).
+ # Only Hermes.exe (Electron) — never hermes.exe (the venv CLI shim).
+ $procs = @(Get-Process -Name "Hermes" -ErrorAction SilentlyContinue)
+ foreach ($p in $procs) {
+ try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {}
+ }
+ if ($procs.Count -gt 0) {
+ Write-Host " [$Label] stopped $($procs.Count) Hermes.exe process(es)"
+ Start-Sleep -Seconds 3
+ }
+}
+
+function Get-ManagedNode {
+ # `hermes update`/desktop builds use the Hermes-managed Node; use the same
+ # one to run the Playwright driver so no system Node is required.
+ $candidates = @(
+ (Join-Path $HermesHome "node\node.exe"),
+ (Join-Path $HermesHome "bin\node\node.exe"),
+ (Join-Path $InstallDir "node\node.exe")
+ )
+ foreach ($c in $candidates) {
+ if (Test-Path -LiteralPath $c) { return $c }
+ }
+ $fromPath = Get-Command node -ErrorAction SilentlyContinue
+ if ($fromPath) { return $fromPath.Source }
+ throw "No node.exe found (managed or on PATH)"
+}
+
+# ----------------------------------------------------------------------------
+# Phase: stage — reuse the contract driver's stage (identical staging)
+# ----------------------------------------------------------------------------
+function Invoke-PhaseStage {
+ Write-Step "STAGE (gui): delegating to windows-desktop-e2e.ps1 -Phase stage"
+ & powershell.exe -NoProfile -ExecutionPolicy Bypass `
+ -File (Join-Path $PSScriptRoot "windows-desktop-e2e.ps1") `
+ -Phase stage -RepoRoot $RepoRoot -WorkRoot $WorkRoot
+ if ($LASTEXITCODE -ne 0) { throw "stage phase failed" }
+ # The website installer pins a specific release commit (-Commit <sha>).
+ # That sha is in serve.git's history but not at a ref tip, so the
+ # redirected fetch needs any-SHA1 upload-pack permission (GitHub grants
+ # the equivalent for archive/fetch of reachable commits).
+ Invoke-Git @("-C", $ServeRepo, "config", "uploadpack.allowAnySHA1InWant", "true") | Out-Null
+ Write-Host " serve.git: uploadpack.allowAnySHA1InWant=true (installer commit pin)"
+ New-Item -ItemType Directory -Path $ProofRoot -Force | Out-Null
+}
+
+# ----------------------------------------------------------------------------
+# Phase: install-gui — website Hermes-Setup.exe, headed, AHK-driven
+# ----------------------------------------------------------------------------
+function Invoke-PhaseInstallGui {
+ $state = Read-State
+ Write-Step "INSTALL (GUI): Hermes-Setup.exe from the website, headed, AHK clicks"
+ $proof = Join-Path $ProofRoot "install-gui"
+ New-Item -ItemType Directory -Path $proof -Force | Out-Null
+
+ # The production installer, from the website. This is the binary users
+ # double-click, run EXACTLY as shipped: its own pinned install.ps1, its
+ # own baked BUILD_PIN_COMMIT. The only environmental difference is the
+ # git URL redirect to serve.git.
+ $setupExe = Join-Path $WorkRoot "Hermes-Setup.exe"
+ if (-not (Test-Path -LiteralPath $setupExe)) {
+ Write-Host " downloading $SetupExeUrl"
+ Invoke-WebRequest -Uri $SetupExeUrl -OutFile $setupExe
+ }
+ Assert-True ((Get-Item $setupExe).Length -gt 1MB) "Hermes-Setup.exe downloaded ($([math]::Round((Get-Item $setupExe).Length / 1MB, 1)) MB)"
+
+ # AutoHotkey v2, portable zip (no installer, no winget flakes).
+ $ahkExe = Join-Path $AhkDir "AutoHotkey64.exe"
+ if (-not (Test-Path -LiteralPath $ahkExe)) {
+ $zip = Join-Path $WorkRoot "ahk.zip"
+ Invoke-WebRequest -Uri "https://github.com/AutoHotkey/AutoHotkey/releases/download/v2.0.19/AutoHotkey_2.0.19.zip" -OutFile $zip
+ Expand-Archive -Path $zip -DestinationPath $AhkDir -Force
+ }
+ Assert-True (Test-Path -LiteralPath $ahkExe) "AutoHotkey64.exe available"
+
+ # AHK script + button templates side by side (ImageSearch resolves
+ # relative to the script dir).
+ Copy-Item -Path (Join-Path $AssetsDir "install-and-launch.ahk"), (Join-Path $AssetsDir "install-button.png"), (Join-Path $AssetsDir "launch-button.png") -Destination $AhkDir -Force
+
+ $env:HERMES_HOME = $HermesHome
+ # As shipped: NO dev-root override, no pin override. Ensure a stray
+ # local dev checkout can't hijack resolution.
+ Remove-Item Env:HERMES_SETUP_DEV_REPO_ROOT -ErrorAction SilentlyContinue
+ New-Item -ItemType Directory -Path $HermesHome -Force | Out-Null
+
+ $recorder = Start-DesktopRecorder (Join-Path $proof "desktop-frames")
+ $ahkLog = Join-Path $proof "ahk.log"
+ try {
+ Save-DesktopScreenshot (Join-Path $proof "00-before-installer.png")
+
+ # Launch the REAL installer, headed — exactly a double-click.
+ $installer = Start-Process -FilePath $setupExe -PassThru
+ Write-Host " Hermes-Setup.exe launched (pid $($installer.Id))"
+
+ # Drive it: Install click -> wait -> Launch click -> Hermes.exe window.
+ $ahk = Start-Process -FilePath $ahkExe `
+ -ArgumentList (Join-Path $AhkDir "install-and-launch.ahk"), $ahkLog `
+ -PassThru
+ # Install on a cold runner takes a while; the AHK script's own inner
+ # timeout (45 min on the Launch wait) is the effective budget.
+ if (-not $ahk.WaitForExit(50 * 60 * 1000)) {
+ Stop-Process -Id $ahk.Id -Force -ErrorAction SilentlyContinue
+ throw "AutoHotkey driver did not finish within 50 minutes"
+ }
+ if (Test-Path -LiteralPath $ahkLog) {
+ Get-Content -LiteralPath $ahkLog | ForEach-Object { Write-Host " ahk| $_" }
+ }
+ Assert-True ($ahk.ExitCode -eq 0) "AutoHotkey driver exited 0 (Install clicked, Launch clicked, app window seen)"
+
+ Save-DesktopScreenshot (Join-Path $proof "01-app-launched.png")
+
+ # The Launch hand-off under test: the app the installer spawned must
+ # actually be running.
+ Assert-True ($null -ne (Get-Process -Name "Hermes" -ErrorAction SilentlyContinue)) "Hermes.exe process is running (installer Launch hand-off worked)"
+
+ # Installer should have exited after Launch.
+ if (-not $installer.HasExited) {
+ Start-Sleep -Seconds 10
+ }
+ Assert-True $installer.HasExited "Hermes-Setup.exe exited after Launch"
+ }
+ finally {
+ Stop-DesktopRecorder $recorder (Join-Path $proof "desktop-frames")
+ # Surface the installer's own log win or lose.
+ $bootLog = Join-Path $HermesHome "logs\bootstrap-installer.log"
+ if (Test-Path -LiteralPath $bootLog) {
+ Write-Host " --- bootstrap-installer.log (tail) ---"
+ Get-Content -LiteralPath $bootLog -Tail 40 | ForEach-Object { Write-Host " | $_" }
+ Copy-Item $bootLog $proof -Force -ErrorAction SilentlyContinue
+ }
+ }
+
+ # Close the freshly launched app (user quits after first look).
+ Stop-HermesAppProcesses "post-install"
+
+ # The website exe installs its baked release pin — record it as the
+ # "before" version. Must be an ancestor of CURRENT (i.e. genuinely
+ # "before" this commit) and must not already BE CURRENT.
+ $installedSha = Get-InstalledHead
+ Write-Host " installer landed on: $installedSha (website release pin)"
+ Assert-True ($installedSha -ne $state.current) "installed pin differs from CURRENT (an update is genuinely available)"
+ $prevEap = $ErrorActionPreference; $ErrorActionPreference = "Continue"
+ & git -C $InstallDir merge-base --is-ancestor $installedSha $state.current 2>&1 | Out-Null
+ $isAncestor = ($LASTEXITCODE -eq 0)
+ $ErrorActionPreference = $prevEap
+ Assert-True $isAncestor "installed pin is an ancestor of CURRENT (before -> current is a forward update)"
+ Test-HermesRuns "post-install-gui"
+ Assert-True ($null -ne (Get-DesktopExe)) "packaged Desktop Hermes.exe exists"
+
+ # Seed a provider so the update legs meet the ready app shell, not the
+ # onboarding overlay (an updating user has a configured provider).
+ $envFile = Join-Path $HermesHome ".env"
+ if (-not (Test-Path -LiteralPath $envFile) -or -not ((Get-Content $envFile -Raw -ErrorAction SilentlyContinue) -match "OPENROUTER_API_KEY")) {
+ Add-Content -LiteralPath $envFile -Value "OPENROUTER_API_KEY=sk-or-e2e-placeholder-not-a-real-key"
+ }
+ Write-Host " seeded placeholder provider key for update legs"
+}
+
+# ----------------------------------------------------------------------------
+# Update legs: real app, real clicks (Playwright Electron driver)
+# ----------------------------------------------------------------------------
+function Invoke-GuiUpdateLeg([string]$TargetSha, [string]$LegName, [string]$LegSlug) {
+ Write-Step "UPDATE GUI ($LegName): advance served main -> $TargetSha, click Update now"
+ $proof = Join-Path $ProofRoot $LegSlug
+ New-Item -ItemType Directory -Path $proof -Force | Out-Null
+
+ $env:HERMES_HOME = $HermesHome
+ Invoke-Git @("-C", $ServeRepo, "update-ref", "refs/heads/main", $TargetSha) | Out-Null
+
+ $desktopExe = Get-DesktopExe
+ Assert-True ($null -ne $desktopExe) "$LegName -- packaged Hermes.exe present before update"
+
+ $resultPath = Join-Path $HermesHome ".hermes-update-result.json"
+ $markerPath = Join-Path $HermesHome ".hermes-update-in-progress"
+ Remove-Item -LiteralPath $resultPath -Force -ErrorAction SilentlyContinue
+
+ $node = Get-ManagedNode
+ $appsDesktop = Join-Path $InstallDir "apps\desktop"
+ Assert-True (Test-Path -LiteralPath (Join-Path $appsDesktop "node_modules\@playwright\test")) "$LegName -- @playwright/test present in installed checkout"
+
+ $recorder = Start-DesktopRecorder (Join-Path $proof "desktop-frames")
+ try {
+ # Launch the installed app and click through Settings -> About ->
+ # Update now. Exit 0 = the app quit for the updater hand-off.
+ # Copy the driver INTO the installed apps/desktop first: Node resolves
+ # require('@playwright/test') from the SCRIPT's own directory upward,
+ # so running it from the CI checkout would resolve the wrong (or no)
+ # node_modules.
+ $driver = Join-Path $appsDesktop "e2e-drive-update.cjs"
+ Copy-Item (Join-Path $AssetsDir "drive-update.cjs") $driver -Force
+ Push-Location $appsDesktop
+ try {
+ & $node $driver $desktopExe $proof 2>&1 |
+ ForEach-Object { Write-Host " $_" }
+ $driveExit = $LASTEXITCODE
+ } finally {
+ Pop-Location
+ Remove-Item -LiteralPath $driver -Force -ErrorAction SilentlyContinue
+ }
+ Assert-True ($driveExit -eq 0) "$LegName -- GUI driver clicked Update now and the app quit for hand-off"
+
+ # The detached updater (spawned by the app, NOT by us) now runs
+ # `hermes update` + desktop rebuild + relaunch. Which updater depends
+ # on the installed checkout, and BOTH are production paths:
+ # * checkouts shipping scripts/desktop-update.ps1 -> that script,
+ # which writes .hermes-update-result.json on every exit;
+ # * older checkouts -> the staged hermes-setup.exe --update flow,
+ # which does NOT write the result JSON.
+ # So: poll for COMPLETION = (result JSON) OR (checkout reached the
+ # target sha AND the marker is gone). The sha/marker/hermes/relaunch
+ # asserts below are the hard gate either way; the JSON is asserted
+ # only when the script path produced it.
+ Write-Host " waiting for the detached updater to finish ..."
+ $deadline = (Get-Date).AddMinutes(40)
+ while ((Get-Date) -lt $deadline) {
+ if (Test-Path -LiteralPath $resultPath) { break }
+ $head = ""
+ try { $head = Get-InstalledHead } catch {}
+ if ($head -eq $TargetSha -and -not (Test-Path -LiteralPath $markerPath)) { break }
+ Start-Sleep -Seconds 10
+ }
+ if (Test-Path -LiteralPath $resultPath) {
+ $result = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json
+ Write-Host " updater result: ok=$($result.ok) code=$($result.exit_code) msg=$($result.message)"
+ Assert-True ([bool]$result.ok) "$LegName -- updater result ok=true"
+ } else {
+ Write-Host " (no result JSON -- staged-binary updater path; relying on sha/marker/relaunch asserts)"
+ }
+
+ # Marker may briefly outlive the result write; allow it a moment.
+ $mDeadline = (Get-Date).AddMinutes(2)
+ while ((Get-Date) -lt $mDeadline -and (Test-Path -LiteralPath $markerPath)) { Start-Sleep -Seconds 5 }
+ Assert-True (-not (Test-Path -LiteralPath $markerPath)) "$LegName -- update marker cleaned up"
+
+ Assert-True ((Get-InstalledHead) -eq $TargetSha) "$LegName -- checkout landed on target commit"
+ Test-HermesRuns $LegName
+ Assert-True ($null -ne (Get-DesktopExe)) "$LegName -- Hermes.exe still present after update"
+
+ # The production hand-off relaunches the desktop (RelaunchExe).
+ # A relaunched window is the user-visible proof the update loop closed.
+ Write-Host " waiting for the relaunched Hermes.exe ..."
+ $rDeadline = (Get-Date).AddMinutes(5)
+ $relaunched = $null
+ while ((Get-Date) -lt $rDeadline) {
+ $relaunched = Get-Process -Name "Hermes" -ErrorAction SilentlyContinue
+ if ($relaunched) { break }
+ Start-Sleep -Seconds 5
+ }
+ Assert-True ($null -ne $relaunched) "$LegName -- updater relaunched the desktop app"
+ Start-Sleep -Seconds 12 # let the window paint for the screenshot
+ Save-DesktopScreenshot (Join-Path $proof "99-relaunched-desktop.png")
+ }
+ finally {
+ Stop-DesktopRecorder $recorder (Join-Path $proof "desktop-frames")
+ $handoffLog = Join-Path $HermesHome "logs\desktop-update-handoff.log"
+ if (Test-Path -LiteralPath $handoffLog) {
+ Write-Host " --- desktop-update-handoff.log (tail) ---"
+ Get-Content -LiteralPath $handoffLog -Tail 60 | ForEach-Object { Write-Host " | $_" }
+ Copy-Item $handoffLog (Join-Path $proof "desktop-update-handoff.log") -Force -ErrorAction SilentlyContinue
+ }
+ # Quit the relaunched app so the next leg (or job teardown) is clean.
+ Stop-HermesAppProcesses $LegName
+ }
+}
+
+function Invoke-PhaseUpdateGuiToCurrent {
+ $state = Read-State
+ Invoke-GuiUpdateLeg $state.current "BASE -> CURRENT (GUI)" "update-gui-to-current"
+}
+
+function Invoke-PhaseUpdateGuiToNext {
+ $state = Read-State
+ Invoke-GuiUpdateLeg $state.next "CURRENT -> NEXT (GUI)" "update-gui-to-next"
+}
+
+# ----------------------------------------------------------------------------
+# Dispatch
+# ----------------------------------------------------------------------------
+Write-Host "Windows Desktop GUI E2E driver (real user flow)"
+Write-Host " phase: $Phase"
+Write-Host " repo: $RepoRoot"
+Write-Host " workroot: $WorkRoot"
+
+Set-GitRedirect
+
+switch ($Phase) {
+ "stage" { Invoke-PhaseStage }
+ "install-gui" { Invoke-PhaseInstallGui }
+ "update-gui-to-current" { Invoke-PhaseUpdateGuiToCurrent }
+ "update-gui-to-next" { Invoke-PhaseUpdateGuiToNext }
+ "all" {
+ Invoke-PhaseStage
+ Invoke-PhaseInstallGui
+ Invoke-PhaseUpdateGuiToCurrent
+ Invoke-PhaseUpdateGuiToNext
+ }
+}
+
+Write-Host ""
+Write-Host "Phase '$Phase' completed successfully."