Skip to content

The agent that grows with you

test(e2e/desktop): PR-time Desktop install/update suite on a real install

Teknium183e0d4adc67
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index a445f7542a7..ff1121887c7 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -189,6 +189,14 @@ jobs:
if: ${{ needs.detect.outputs.python_prod == 'true' || needs.detect.outputs.frontend == 'true' }}
uses: ./.github/workflows/e2e-desktop-core.yml
+ e2e-desktop-update:
+ name: Desktop update E2E
+ needs: detect
+ # apps/desktop/e2e/update: a real install.sh install + packaged Desktop,
+ # first run, "Update now" hand-off/relaunch, concurrent-update refusal.
+ if: ${{ needs.detect.outputs.python_prod == 'true' || needs.detect.outputs.frontend == 'true' }}
+ uses: ./.github/workflows/e2e-desktop-update.yml
+
docs-site:
name: Docs Site
needs: detect
@@ -304,6 +312,7 @@ jobs:
- bootstrap-installer
- e2e-desktop
- e2e-desktop-core
+ - e2e-desktop-update
- docs-site
- history-check
- contributor-check
diff --git a/.github/workflows/e2e-desktop-update.yml b/.github/workflows/e2e-desktop-update.yml
new file mode 100644
index 00000000000..688e356aee1
--- /dev/null
+++ b/.github/workflows/e2e-desktop-update.yml
@@ -0,0 +1,107 @@
+name: E2E Desktop update
+
+# The Desktop install/update suite (apps/desktop/e2e/update): the packaged app
+# a REAL local install built (scripts/install.sh + `hermes desktop
+# --build-only`, inside the upgrade suite's sandbox machinery), driven through
+# the flows Desktop users hit and the CLI suites cannot see:
+# - first run on a healthy install (no setup chooser, no bootstrap installer);
+# - "Update now" in Settings → About: hand-off, update, relaunch, chat after;
+# - a Desktop build failure inside that update reaches the user as a failure;
+# - a second update while one runs is refused and the panel stays truthful.
+# External edges only are faked: the git server (a local bare origin behind a
+# url.insteadOf rewrite), api.github.com (a local stand-in behind an HTTPS
+# proxy) and the LLM provider (a scripted loopback model). Open bugs are
+# message-gated (e2e/update/gates.ts), never statically xfailed.
+
+on:
+ workflow_call:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: e2e-desktop-update-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ update:
+ name: Desktop install/update E2E (Linux, ${{ matrix.cell }})
+ runs-on: ubuntu-latest-32-core
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ # One install per shard (every spec restores it; paths are baked in, so
+ # shards cannot share one), so each job stays well inside 15 minutes.
+ matrix:
+ include:
+ - cell: first-run
+ specs: e2e/update/first-run.spec.ts e2e/update/gates.spec.ts
+ - cell: app-update
+ specs: e2e/update/app-update.spec.ts
+ - cell: build-fail
+ specs: e2e/update/build-fail.spec.ts
+ - cell: update-concurrency
+ specs: e2e/update/update-concurrency.spec.ts
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ # The seeded install clones this checkout through a local bare origin.
+ fetch-depth: 0
+
+ - name: Install system dependencies for Electron and the sandbox
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y -qq \
+ xvfb bubblewrap \
+ libgtk-3-0 libnotify4 libnss3 libxss1 libxtst6 \
+ xdg-utils libatspi2.0-0 libdrm2 libgbm1 libasound2t64
+ # bwrap (the installer/updater sandbox) needs unprivileged user namespaces.
+ sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 || true
+
+ - name: Prepare locked toolchain and test environment
+ id: pm
+ uses: ./.github/actions/setup-pm
+ with:
+ toolchain: all
+ extras: '[]'
+ test-environment: 'true'
+
+ # The Playwright runner and its Electron driver. The install under test
+ # runs its own npm install inside the sandbox.
+ - uses: ./.github/actions/retry
+ with:
+ command: npm ci
+
+ - name: Run the update suite under xvfb
+ working-directory: apps/desktop
+ run: |
+ xvfb-run -a --server-args="-screen 0 1280x1024x24" \
+ npx playwright test -c e2e/update/playwright.config.ts ${{ matrix.specs }}
+ env:
+ CI: 'true'
+ HERMES_E2E_PYTHON: ${{ steps.pm.outputs.python-path }}
+ # Short on purpose: the install bakes this path into AF_UNIX socket paths.
+ HERMES_E2E_UPDATE_ROOT: ${{ runner.temp }}/hdu
+ OPENROUTER_API_KEY: ''
+ OPENAI_API_KEY: ''
+ NOUS_API_KEY: ''
+ ANTHROPIC_API_KEY: ''
+
+ - name: Collect the install's logs
+ if: failure() || cancelled()
+ run: |
+ mkdir -p apps/desktop/test-results/update/install-logs
+ cp -r "${{ runner.temp }}/hdu/sb/home/.hermes/logs" apps/desktop/test-results/update/install-logs/ 2>/dev/null || true
+ cp "${{ runner.temp }}/hdu/sb/terminal-update.log" apps/desktop/test-results/update/install-logs/ 2>/dev/null || true
+
+ - name: Upload failure artifacts
+ if: failure() || cancelled()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: desktop-update-e2e-${{ matrix.cell }}-${{ github.sha }}
+ path: |
+ apps/desktop/test-results/update
+ apps/desktop/playwright-report/update
+ retention-days: 14
+ overwrite: true
+ if-no-files-found: ignore
diff --git a/apps/desktop/e2e/update/app-update.spec.ts b/apps/desktop/e2e/update/app-update.spec.ts
new file mode 100644
index 00000000000..432640b24b9
--- /dev/null
+++ b/apps/desktop/e2e/update/app-update.spec.ts
@@ -0,0 +1,148 @@
+/**
+ * Failure class: APP-DRIVEN UPDATE completes.
+ *
+ * A user on a healthy local install (scripts/install.sh + `hermes desktop`)
+ * sees "Update now" in Settings → About when upstream main moves, clicks it,
+ * and the app hands off to the updater, quits, updates, and comes back:
+ * - the backend checkout is on the new upstream commit, clean;
+ * - the app relaunched by itself (a new Desktop process from the rebuilt
+ * package, with its own backend) and logged the update as finished OK;
+ * - the updated app boots to chat and a chat turn completes;
+ * - the updated app reports itself current (no update offered again).
+ *
+ * Real entry points only: the About panel's button and the app's own
+ * hand-off (scripts/desktop-update/posix.sh → `hermes update`). Fakes: the git
+ * server (local bare origin) and the LLM provider.
+ */
+
+import * as fs from 'node:fs'
+
+import { expect, test } from '@playwright/test'
+
+import { recordWebSockets, send, waitForInteractive } from '../core/harness'
+
+import {
+ backendServeProcesses,
+ clickUpdateNowAndExpectHandoff,
+ currentAs,
+ desktopLog,
+ desktopMainProcesses,
+ diagnostics,
+ git,
+ handoffLog,
+ installProcesses,
+ launchInstalledApp,
+ openAbout,
+ publishUpstream,
+ startInstallSession,
+ waitFor,
+ waitForUpdateOffer,
+ closeQuietly
+} from './harness'
+
+const RUN = Date.now().toString(36)
+const U = (n: number) => `U${n}-${RUN}`
+const A = (n: number) => `A${n}-${RUN}`
+
+test('clicking Update now moves the backend to the new commit, relaunches the app, and chat works after', async () => {
+ test.setTimeout(20 * 60_000)
+ const session = await startInstallSession()
+ const { facts, provider, env } = session
+ const before = git(facts.checkout, 'rev-parse', 'HEAD')
+ const target = publishUpstream('release: next upstream main', 'UPSTREAM_RELEASE.md', `next release ${RUN}\n`)
+ const explain = (extra = '') => diagnostics(facts, extra)
+
+ try {
+ let firstMainPid = 0
+
+ await test.step('the running app offers the new upstream commit and hands off on click', async () => {
+ const launched = await launchInstalledApp(facts, env)
+ firstMainPid = launched.app.process().pid ?? 0
+ await waitForInteractive(launched.app, launched.page).catch(error => {
+ throw new Error(`${(error as Error).message}\n${explain(launched.logTail())}`)
+ })
+ await openAbout(launched.page)
+ await waitForUpdateOffer(launched.page, target)
+ await clickUpdateNowAndExpectHandoff(launched, facts)
+ })
+
+ await test.step('the update lands and the app relaunches itself', async () => {
+ await waitFor(
+ 'the updater to finish `hermes update`',
+ () => /hermes update exit code: \d+/.test(handoffLog(facts)),
+ {
+ timeout: 8 * 60_000,
+ interval: 2_000,
+ explain: () => explain(`handoff log:\n${handoffLog(facts)}`)
+ }
+ )
+ expect(handoffLog(facts), `the updater's hermes update succeeded\n${explain()}`).toMatch(
+ /hermes update exit code: 0\s*$|retry exit code: 0/m
+ )
+ expect(git(facts.checkout, 'rev-parse', 'HEAD'), 'the backend checkout is on the new upstream commit').toBe(
+ target
+ )
+ // The updater's progress window can be the same Electron binary (--app=http://127.0.0.1:...): not a relaunch.
+ const relaunched = await waitFor(
+ 'the app to relaunch itself',
+ () =>
+ desktopMainProcesses(facts).find(
+ proc => proc.pid !== firstMainPid && !/--app=|https?:\/\/127\.0\.0\.1/.test(proc.cmdline)
+ ),
+ { timeout: 3 * 60_000, interval: 1_000, explain: () => explain(`handoff log:\n${handoffLog(facts)}`) }
+ )
+ await waitFor(
+ 'the relaunched app to log the update result',
+ () => /\[updates\] detached update (finished|FAILED)/.test(desktopLog(facts)),
+ {
+ timeout: 3 * 60_000,
+ explain
+ }
+ )
+ expect(desktopLog(facts), `the relaunched app reports the update as finished OK\n${explain()}`).toMatch(
+ /\[updates\] detached update finished OK/
+ )
+ await waitFor('the relaunched app to start its backend', () => backendServeProcesses(facts).length > 0, {
+ timeout: 3 * 60_000,
+ explain
+ })
+ expect(
+ git(facts.checkout, 'status', '--porcelain', '--untracked-files=no'),
+ 'the updated checkout is clean'
+ ).toBe('')
+
+ // Hand the machine back to Playwright: quit the relaunched app the way the OS asks it to.
+ process.kill(relaunched.pid, 'SIGTERM')
+ await expect
+ .poll(() => installProcesses(facts).map(p => `${p.pid} ${p.cmdline.slice(0, 160)}`), {
+ timeout: 60_000,
+ message: 'the relaunched app quits cleanly on SIGTERM'
+ })
+ .toEqual([])
+ })
+
+ await test.step('the updated app boots to chat, a turn completes, and it reports itself current', async () => {
+ const { app, page, logTail } = await launchInstalledApp(facts, env)
+
+ try {
+ const ws = recordWebSockets(page)
+ await waitForInteractive(app, page).catch(error => {
+ throw new Error(`${(error as Error).message}\n${explain(logTail())}`)
+ })
+ provider.script(U(1), [{ text: [`${A(1)} `, 'after ', 'update'] }])
+ await send(page, `${U(1)} hello after the update`, 'Enter', ws)
+ await expect(page.getByText(`${A(1)} after update`)).toBeVisible({ timeout: 120_000 })
+ expect(await currentAs(page), `the updated app is current (was ${before})`).toEqual({
+ currentSha: target,
+ updateAvailable: false
+ })
+ } finally {
+ await closeQuietly(app)
+ }
+ })
+
+ expect(fs.existsSync(facts.checkout)).toBe(true)
+ } finally {
+ await session.close()
+ }
+})
diff --git a/apps/desktop/e2e/update/build-fail.spec.ts b/apps/desktop/e2e/update/build-fail.spec.ts
new file mode 100644
index 00000000000..9bb9a291876
--- /dev/null
+++ b/apps/desktop/e2e/update/build-fail.spec.ts
@@ -0,0 +1,81 @@
+/**
+ * Failure class: APP-DRIVEN UPDATE whose Desktop build fails.
+ *
+ * #124040: the Desktop build failed inside the update takeover's completion
+ * stage and the failure was swallowed / kept looping instead of reaching the
+ * user. Here upstream main carries a Desktop source file that does not
+ * compile; the user clicks "Update now". The update must end with the app
+ * telling the user the update FAILED (the relaunched app's result dialog is
+ * logged as `[updates] detached update FAILED`), never "finished OK", and the
+ * updater must not be left running.
+ */
+
+import * as path from 'node:path'
+
+import { expect, test } from '@playwright/test'
+
+import { waitForInteractive } from '../core/harness'
+
+import {
+ clickUpdateNowAndExpectHandoff,
+ desktopLog,
+ diagnostics,
+ git,
+ handoffLog,
+ installProcesses,
+ launchInstalledApp,
+ openAbout,
+ publishUpstream,
+ readText,
+ startInstallSession,
+ waitFor,
+ waitForUpdateOffer
+} from './harness'
+
+test('a Desktop build failure during Update now is reported to the user as a failed update', async () => {
+ test.setTimeout(20 * 60_000)
+ const session = await startInstallSession()
+ const { facts, env } = session
+ const rel = 'apps/desktop/src/main.tsx'
+ const broken = `${readText(path.join(facts.checkout, rel))}\nexport const brokenRelease = (\n`
+ const target = publishUpstream('release: next upstream main (desktop does not compile)', rel, broken)
+ const explain = (extra = '') => diagnostics(facts, `${extra}\n── handoff log ──\n${handoffLog(facts)}`)
+
+ try {
+ await test.step('the user clicks Update now', async () => {
+ const launched = await launchInstalledApp(facts, env)
+ await waitForInteractive(launched.app, launched.page).catch(error => {
+ throw new Error(`${(error as Error).message}\n${explain(launched.logTail())}`)
+ })
+ await openAbout(launched.page)
+ await waitForUpdateOffer(launched.page, target)
+ await clickUpdateNowAndExpectHandoff(launched, facts)
+ })
+
+ await test.step('the failed build reaches the user as a failed update', async () => {
+ await waitFor(
+ 'the relaunched app to report the update outcome',
+ () => /\[updates\] detached update (finished|FAILED)/.test(desktopLog(facts)),
+ { timeout: 12 * 60_000, interval: 2_000, explain }
+ )
+ const outcome = desktopLog(facts)
+ .split('\n')
+ .filter(line => /\[updates\] detached update/.test(line))
+ .join('\n')
+ expect(outcome, `the update is reported as FAILED, not finished\n${explain()}`).toMatch(/detached update FAILED/)
+ expect(outcome).not.toMatch(/detached update finished OK/)
+ expect(
+ installProcesses(facts)
+ .filter(proc => /desktop-update\/posix\.sh| update --yes/.test(proc.cmdline))
+ .map(p => p.cmdline),
+ 'no updater is left running after the failure'
+ ).toEqual([])
+ // What the user is left on: record it for triage (the checkout moved; the app bundle did not).
+ test
+ .info()
+ .annotations.push({ type: 'checkout-after-failure', description: git(facts.checkout, 'rev-parse', 'HEAD') })
+ })
+ } finally {
+ await session.close()
+ }
+})
diff --git a/apps/desktop/e2e/update/first-run.spec.ts b/apps/desktop/e2e/update/first-run.spec.ts
new file mode 100644
index 00000000000..b38c39f5372
--- /dev/null
+++ b/apps/desktop/e2e/update/first-run.spec.ts
@@ -0,0 +1,122 @@
+/**
+ * Failure class: FIRST RUN on a healthy install.
+ *
+ * A user who installed Hermes with scripts/install.sh and built the Desktop
+ * app with `hermes desktop` opens the app. It must find that install and go
+ * straight to chat — on the first launch and on every later one — and never
+ * show the first-run setup chooser or start the bootstrap installer
+ * (#123888, #123800: the chooser / installer came back on every launch while
+ * the local install was healthy).
+ *
+ * Real entry point: the packaged app the install built, launched with the
+ * install's environment and no HERMES_DESKTOP_HERMES_ROOT override, so the app
+ * resolves the backend the way it does for a user ($HERMES_HOME/hermes-agent).
+ */
+
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+import { expect, test } from '@playwright/test'
+
+import { recordWebSockets, send, waitForInteractive } from '../core/harness'
+
+import {
+ backendServeProcesses,
+ diagnostics,
+ firstRunScreensSeen,
+ type InstallFacts,
+ installFirstRunSampler,
+ installProcesses,
+ launchInstalledApp,
+ startInstallSession,
+ closeQuietly
+} from './harness'
+
+const RUN = Date.now().toString(36)
+const U = (n: number) => `U${n}-${RUN}`
+const A = (n: number) => `A${n}-${RUN}`
+
+/** Every process of the install that is a bootstrap/installer run, sampled for the whole boot. */
+function startInstallerSampler(facts: InstallFacts): { stop: () => string[] } {
+ const seen = new Set<string>()
+
+ const scan = () => {
+ for (const proc of installProcesses(facts)) {
+ if (/install\.sh|install\.ps1|bootstrap-runner|\bpm (bootstrap|install)\b/.test(proc.cmdline)) {
+ seen.add(proc.cmdline.slice(0, 240))
+ }
+ }
+ }
+
+ const timer = setInterval(scan, 100)
+
+ return {
+ stop: () => {
+ clearInterval(timer)
+ scan()
+
+ return [...seen]
+ }
+ }
+}
+
+test('a healthy local install opens straight to chat on every launch: no setup chooser, no bootstrap installer', async () => {
+ const session = await startInstallSession()
+ const { facts, provider, env } = session
+
+ try {
+ for (const launch of [1, 2]) {
+ await test.step(`launch ${launch}`, async () => {
+ const installer = startInstallerSampler(facts)
+ const { app, page, logTail } = await launchInstalledApp(facts, env)
+
+ try {
+ await installFirstRunSampler(page)
+ const ws = recordWebSockets(page)
+ await waitForInteractive(app, page, 180_000).catch(error => {
+ throw new Error(`${(error as Error).message}\n${diagnostics(facts, logTail())}`)
+ })
+
+ // The backend the app started is the user's install, not something it provisioned.
+ const serve = backendServeProcesses(facts)
+ expect(serve.length, `one backend for the install\n${diagnostics(facts)}`).toBe(1)
+ const cwd = fs.realpathSync(`/proc/${serve[0].pid}/cwd`)
+ expect(
+ [serve[0].cmdline, cwd].some(s => s.includes(facts.hermesHome)),
+ `backend runs from the install under ${facts.hermesHome}: ${serve[0].cmdline} (cwd ${cwd})`
+ ).toBe(true)
+
+ provider.script(U(launch), [{ text: [`${A(launch)} `, 'healthy ', 'install'] }])
+ await send(page, `${U(launch)} hello`, 'Enter', ws)
+ await expect(page.getByText(`${A(launch)} healthy install`)).toBeVisible({ timeout: 120_000 })
+
+ expect(
+ await firstRunScreensSeen(page),
+ `launch ${launch} of a healthy install showed the first-run setup chooser\n${diagnostics(facts, logTail())}`
+ ).toEqual([])
+ expect(
+ installer.stop(),
+ `launch ${launch} of a healthy install started the bootstrap installer\n${diagnostics(facts, logTail())}`
+ ).toEqual([])
+ } finally {
+ installer.stop()
+ await closeQuietly(app)
+ }
+
+ await expect
+ .poll(() => installProcesses(facts).map(p => `${p.pid} ${p.cmdline.slice(0, 160)}`), {
+ timeout: 30_000,
+ message: 'quitting the app leaves nothing of the install running'
+ })
+ .toEqual([])
+ })
+ }
+
+ expect(
+ fs.existsSync(path.join(facts.hermesHome, 'hermes-agent', '.git')),
+ 'the install is still the git checkout the installer made'
+ ).toBe(true)
+ } finally {
+ await session.close()
+ }
+})
diff --git a/apps/desktop/e2e/update/gates.spec.ts b/apps/desktop/e2e/update/gates.spec.ts
new file mode 100644
index 00000000000..42b0044bffe
--- /dev/null
+++ b/apps/desktop/e2e/update/gates.spec.ts
@@ -0,0 +1,27 @@
+/**
+ * The gates' signatures are part of the suite's contract: each must match the
+ * exact failing assertion its bug produces and nothing else, or a gate turns
+ * an unrelated regression into a silent expected-failure.
+ */
+
+import { expect, test } from '@playwright/test'
+
+import { gateMatches, KNOWN } from './gates'
+
+test('gate signatures match their bug and not neighbouring failures', () => {
+ const real =
+ '"Update now" hands off to the updater and the app quits for it; the app logged:\n' +
+ '[2026-09-27T01:19:44.583Z] [hermes] [updates] state.db pre-flight failed: Python not found. Update cancelled before backend shutdown.'
+
+ expect(gateMatches(KNOWN.preflightPython, real)).toBe(true)
+
+ for (const decoy of [
+ '[updates] refusing posix hand-off: An update is already running (PID 670, started 2s ago).',
+ '[updates] state.db pre-flight failed: database disk image is malformed. Update cancelled before backend shutdown.',
+ '[updates] detached update FAILED',
+ 'Timed out 120000ms waiting for the app to quit for the update hand-off',
+ 'Python not found'
+ ]) {
+ expect(gateMatches(KNOWN.preflightPython, decoy), decoy).toBe(false)
+ }
+})
diff --git a/apps/desktop/e2e/update/gates.ts b/apps/desktop/e2e/update/gates.ts
new file mode 100644
index 00000000000..bbf042c6d0e
--- /dev/null
+++ b/apps/desktop/e2e/update/gates.ts
@@ -0,0 +1,49 @@
+/**
+ * Message-gated gaps for open bugs (the Playwright twin of
+ * tests/e2e/core/_pending_fixes.py::known_failure).
+ *
+ * Wrap ONLY a final assertion, after every wait has settled. When it fails and
+ * the failure text matches the bug's signature, the test is marked
+ * expected-failing at run time; any other failure (a timeout, a boot failure,
+ * the opposite symptom) propagates; a clean pass stays a pass once the fix
+ * lands, and the gate is then deleted. No static test.fail(), no tables.
+ */
+
+import { test } from '@playwright/test'
+
+export interface KnownBug {
+ /** `#N` of the open issue. */
+ issue: string
+ /** Matches the failing assertion's message ONLY when it shows this bug's symptom. */
+ signature: RegExp
+ summary: string
+}
+
+export const KNOWN = {
+ /** Desktop "Update now" on a PM-managed install is cancelled: the state.db pre-flight looks for an in-tree venv PM deleted. */
+ preflightPython: {
+ issue: '#122991',
+ signature: /state\.db pre-flight failed: Python not found/,
+ summary: "Desktop update preflight 'Python not found' cancels every update on PM-managed installs"
+ }
+} satisfies Record<string, KnownBug>
+
+export function gateMatches(bug: KnownBug, message: string): boolean {
+ return bug.signature.test(message)
+}
+
+/** Run `check`; its failure becomes an expected failure only when it carries `bug`'s signature. */
+export async function gatedOn(bug: KnownBug | undefined, check: () => void | Promise<void>): Promise<void> {
+ try {
+ await check()
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+
+ if (bug && gateMatches(bug, message)) {
+ test.info().annotations.push({ type: 'known-bug', description: `gated on ${bug.issue}: ${bug.summary}` })
+ test.fail(true, `gated on ${bug.issue}`)
+ }
+
+ throw error
+ }
+}
diff --git a/apps/desktop/e2e/update/github-edge.ts b/apps/desktop/e2e/update/github-edge.ts
new file mode 100644
index 00000000000..954ab445615
--- /dev/null
+++ b/apps/desktop/e2e/update/github-edge.ts
@@ -0,0 +1,253 @@
+/**
+ * The GitHub edge for the Desktop update suite: a local stand-in for the two
+ * api.github.com resources the source update check reads, answered from the
+ * local bare origin, behind an HTTPS forward proxy the install is pointed at
+ * (HTTPS_PROXY + a CA bundle that trusts this run's own root, i.e. a
+ * TLS-inspecting corporate proxy).
+ *
+ * GET /repos/<owner>/<repo>/commits/<branch> (Accept: application/vnd.github.sha)
+ * GET /repos/<owner>/<repo>/compare/<base>...<head>
+ *
+ * Every other CONNECT target is tunnelled through unchanged and recorded, so a
+ * failing cell can list every host the product reached.
+ */
+
+import { execFileSync, spawnSync } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as http from 'node:http'
+import * as net from 'node:net'
+import * as path from 'node:path'
+import * as tls from 'node:tls'
+
+export interface GithubEdge {
+ proxyUrl: string
+ caBundle: string
+ /** host:port of every CONNECT the proxy saw, in order. */
+ connects: string[]
+ /** method + path of every request the fake api.github.com answered. */
+ apiHits: string[]
+ env: Record<string, string>
+ close: () => Promise<void>
+}
+
+function openssl(args: string[], cwd: string): void {
+ execFileSync('openssl', args, { cwd, stdio: 'pipe' })
+}
+
+/** A throwaway root + an api.github.com leaf signed by it. */
+function makeCerts(dir: string): { key: Buffer; cert: Buffer; caPem: string } {
+ fs.mkdirSync(dir, { recursive: true })
+ // Python >= 3.13 verifies with X509_STRICT: the root needs keyUsage, the leaf an AKI.
+ openssl(
+ [
+ 'req',
+ '-x509',
+ '-newkey',
+ 'rsa:2048',
+ '-nodes',
+ '-keyout',
+ 'ca.key',
+ '-out',
+ 'ca.pem',
+ '-days',
+ '2',
+ '-subj',
+ '/CN=hermes-update-e2e-root',
+ '-addext',
+ 'basicConstraints=critical,CA:TRUE',
+ '-addext',
+ 'keyUsage=critical,keyCertSign,cRLSign',
+ '-addext',
+ 'subjectKeyIdentifier=hash'
+ ],
+ dir
+ )
+ openssl(
+ ['req', '-newkey', 'rsa:2048', '-nodes', '-keyout', 'leaf.key', '-out', 'leaf.csr', '-subj', '/CN=api.github.com'],
+ dir
+ )
+ fs.writeFileSync(
+ path.join(dir, 'leaf.ext'),
+ 'basicConstraints=CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n' +
+ 'subjectAltName=DNS:api.github.com\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\n'
+ )
+ openssl(
+ [
+ 'x509',
+ '-req',
+ '-in',
+ 'leaf.csr',
+ '-CA',
+ 'ca.pem',
+ '-CAkey',
+ 'ca.key',
+ '-CAcreateserial',
+ '-out',
+ 'leaf.pem',
+ '-days',
+ '2',
+ '-extfile',
+ 'leaf.ext'
+ ],
+ dir
+ )
+
+ return {
+ key: fs.readFileSync(path.join(dir, 'leaf.key')),
+ cert: fs.readFileSync(path.join(dir, 'leaf.pem')),
+ caPem: fs.readFileSync(path.join(dir, 'ca.pem'), 'utf8')
+ }
+}
+
+function gitIn(repo: string, args: string[]): { ok: boolean; out: string } {
+ const cp = spawnSync('git', args, { cwd: repo, encoding: 'utf8', env: { ...process.env, GIT_NO_LAZY_FETCH: '1' } })
+
+ return { ok: cp.status === 0, out: (cp.stdout ?? '').trim() }
+}
+
+/** The GitHub REST shapes the check reads, computed from the bare origin at request time. */
+function apiHandler(origin: string, hits: string[]) {
+ return (req: http.IncomingMessage, res: http.ServerResponse) => {
+ const url = new URL(req.url ?? '/', 'https://api.github.com')
+ hits.push(`${req.method} ${url.pathname}`)
+ const send = (status: number, body: string, type = 'application/json') => {
+ res.writeHead(status, { 'content-type': type })
+ res.end(body)
+ }
+
+ const commit = /^\/repos\/[^/]+\/[^/]+\/commits\/(.+)$/.exec(url.pathname)
+
+ if (commit) {
+ const tip = gitIn(origin, ['rev-parse', '--verify', `refs/heads/${decodeURIComponent(commit[1])}^{commit}`])
+
+ if (!tip.ok) {
+ return send(404, JSON.stringify({ message: 'No commit found for SHA' }))
+ }
+
+ return /vnd\.github\.sha/.test(String(req.headers.accept))
+ ? send(200, tip.out, 'application/vnd.github.sha')
+ : send(200, JSON.stringify({ sha: tip.out }))
+ }
+
+ const compare = /^\/repos\/[^/]+\/[^/]+\/compare\/([0-9a-f]{40})\.\.\.([0-9a-f]{40})$/.exec(url.pathname)
+
+ if (compare) {
+ const [, base, head] = compare
+ const log = gitIn(origin, ['log', '--reverse', '--format=%H%x1f%an%x1f%cI%x1f%s', `${base}..${head}`])
+
+ if (!log.ok) {
+ return send(404, JSON.stringify({ message: 'Not Found' }))
+ }
+
+ const behind = gitIn(origin, ['rev-list', '--count', `${head}..${base}`])
+ const commits = log.out
+ ? log.out.split('\n').map(line => {
+ const [sha, author, date, message] = line.split('\x1f')
+
+ return { sha, commit: { message, author: { name: author, date }, committer: { name: author, date } } }
+ })
+ : []
+
+ return send(
+ 200,
+ JSON.stringify({
+ status: commits.length ? 'ahead' : 'identical',
+ ahead_by: commits.length,
+ behind_by: Number(behind.out || 0),
+ total_commits: commits.length,
+ commits
+ })
+ )
+ }
+
+ send(404, JSON.stringify({ message: 'Not Found' }))
+ }
+}
+
+export async function startGithubEdge(
+ workDir: string,
+ origin: string,
+ baseCaBundle: string | undefined
+): Promise<GithubEdge> {
+ const { key, cert, caPem } = makeCerts(path.join(workDir, 'edge-ca'))
+ const caBundle = path.join(workDir, 'edge-ca', 'bundle.pem')
+ const systemBundle = [baseCaBundle, '/etc/ssl/certs/ca-certificates.crt'].find(p => p && fs.existsSync(p))
+ fs.writeFileSync(caBundle, `${systemBundle ? fs.readFileSync(systemBundle, 'utf8') : ''}\n${caPem}`)
+
+ const connects: string[] = []
+ const apiHits: string[] = []
+ const api = http.createServer(apiHandler(origin, apiHits))
+ const sockets = new Set<net.Socket>()
+
+ const proxy = http.createServer((_req, res) => {
+ res.writeHead(405)
+ res.end('CONNECT only')
+ })
+
+ proxy.on('connection', socket => {
+ sockets.add(socket)
+ socket.on('close', () => sockets.delete(socket))
+ })
+
+ proxy.on('connect', (req: http.IncomingMessage, client: net.Socket, head: Buffer) => {
+ const target = req.url ?? ''
+ connects.push(target)
+ const [host, portText] = target.split(':')
+ const port = Number(portText || 443)
+ client.on('error', () => undefined)
+
+ if (host === 'api.github.com') {
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n')
+
+ if (head.length) {
+ client.unshift(head)
+ }
+
+ const secure = new tls.TLSSocket(client, { isServer: true, key, cert })
+ secure.on('error', () => undefined)
+ api.emit('connection', secure)
+
+ return
+ }
+
+ const upstream = net.connect(port, host, () => {
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n')
+
+ if (head.length) {
+ upstream.write(head)
+ }
+
+ upstream.pipe(client)
+ client.pipe(upstream)
+ })
+
+ sockets.add(upstream)
+ upstream.on('close', () => sockets.delete(upstream))
+ upstream.on('error', () => client.destroy())
+ })
+
+ await new Promise<void>(resolve => proxy.listen(0, '127.0.0.1', resolve))
+ const proxyUrl = `http://127.0.0.1:${(proxy.address() as net.AddressInfo).port}`
+
+ return {
+ proxyUrl,
+ caBundle,
+ connects,
+ apiHits,
+ env: {
+ HTTPS_PROXY: proxyUrl,
+ https_proxy: proxyUrl,
+ NO_PROXY: '127.0.0.1,localhost,::1',
+ no_proxy: '127.0.0.1,localhost,::1',
+ SSL_CERT_FILE: caBundle
+ },
+ close: async () => {
+ for (const socket of sockets) {
+ socket.destroy()
+ }
+
+ await new Promise<void>(resolve => proxy.close(() => resolve()))
+ api.close()
+ }
+ }
+}
diff --git a/apps/desktop/e2e/update/global-setup.ts b/apps/desktop/e2e/update/global-setup.ts
new file mode 100644
index 00000000000..6f4e4ac4b26
--- /dev/null
+++ b/apps/desktop/e2e/update/global-setup.ts
@@ -0,0 +1,51 @@
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+import { seedInstall, UPDATE_ROOT } from './harness'
+
+/**
+ * Refuse to run where an update could reach the developer's own Hermes. The
+ * cells run `hermes update --gateway`, which stops gateways it can see; CI
+ * runners have none, and locally the suite must run in its own PID namespace
+ * (e.g. `bwrap --dev-bind / / --unshare-pid --proc /proc ...` with the user
+ * bus hidden), where PID 1 is not the host's init.
+ */
+function assertIsolated(): void {
+ if (process.env.CI === 'true' || process.env.HERMES_E2E_UPDATE_ISOLATED === '1') {
+ return
+ }
+
+ let init = ''
+
+ try {
+ init = fs.readFileSync('/proc/1/comm', 'utf8').trim()
+ } catch {
+ // no procfs: not Linux, the suite does not run here anyway
+ }
+
+ if (init === 'systemd' || init === 'init') {
+ throw new Error(
+ 'The Desktop update suite runs real `hermes update --gateway` hand-offs. Run it on CI, or locally inside ' +
+ 'its own PID namespace with the user bus hidden (PID 1 here is the host init).'
+ )
+ }
+}
+
+/**
+ * Build the real install every spec starts from. HERMES_E2E_UPDATE_REUSE=1
+ * keeps an existing one (local iteration only: it must have been built from
+ * the current HEAD, which is what the install clones).
+ */
+export default function globalSetup(): void {
+ assertIsolated()
+
+ if (process.env.HERMES_E2E_UPDATE_REUSE === '1' && fs.existsSync(path.join(UPDATE_ROOT, 'golden'))) {
+ return
+ }
+
+ const started = Date.now()
+ const facts = seedInstall()
+ console.log(
+ `[update-e2e] seeded install at ${facts.checkout} (${facts.headSha}) in ${Math.round((Date.now() - started) / 1000)} s`
+ )
+}
diff --git a/apps/desktop/e2e/update/harness.ts b/apps/desktop/e2e/update/harness.ts
new file mode 100644
index 00000000000..d93ab1c9876
--- /dev/null
+++ b/apps/desktop/e2e/update/harness.ts
@@ -0,0 +1,525 @@
+/**
+ * Harness for the Desktop install/update suite: a REAL local install (made by
+ * scripts/install.sh + `hermes desktop --build-only` in the upgrade suite's
+ * sandbox, see seed.py), a local bare origin standing in for GitHub, the
+ * packaged app that install built, and the core suite's scripted provider.
+ *
+ * The one fake per external edge: the git server (a local bare repo behind a
+ * url.insteadOf rewrite) and the LLM provider (e2e/core/provider.ts). Nothing
+ * inside Hermes is mocked.
+ *
+ * Synchronisation rule (same as e2e/core): wait on an observable fact — a log
+ * line, a pid, a file, a DOM state — with a deadline, never a fixed sleep.
+ */
+
+import { spawnSync } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as os from 'node:os'
+import * as path from 'node:path'
+
+import { _electron, type ElectronApplication, expect, type Page } from '@playwright/test'
+
+import { type CoreSandbox, providerConfigYaml, sandboxProcesses, type ProcInfo } from '../core/harness'
+import { type ScriptedProvider, startScriptedProvider } from '../core/provider'
+
+import { gatedOn, KNOWN } from './gates'
+import { type GithubEdge, startGithubEdge } from './github-edge'
+
+export const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..', '..')
+export const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..')
+const SEED = path.join(import.meta.dirname, 'seed.py')
+
+/** Where the seeded install lives. Short on purpose: the install bakes it into AF_UNIX socket paths. */
+export const UPDATE_ROOT = process.env.HERMES_E2E_UPDATE_ROOT || path.join(os.tmpdir(), 'hdu-e2e')
+
+export interface InstallFacts {
+ sandboxRoot: string
+ home: string
+ hermesHome: string
+ checkout: string
+ hermes: string
+ origin: string
+ env: Record<string, string>
+ headSha: string
+}
+
+function python(): string {
+ return process.env.HERMES_E2E_PYTHON || 'python3'
+}
+
+function seed(args: string[], timeoutMs = 60_000): string {
+ const cp = spawnSync(python(), [SEED, ...args], {
+ cwd: REPO_ROOT,
+ encoding: 'utf8',
+ timeout: timeoutMs,
+ maxBuffer: 64 * 1024 * 1024
+ })
+
+ if (cp.status !== 0) {
+ throw new Error(`seed.py ${args[0]} failed (status ${cp.status}, signal ${cp.signal}):\n${cp.stderr?.slice(-6000)}`)
+ }
+
+ return cp.stdout.trim()
+}
+
+/** Build the install once per run (Playwright globalSetup). */
+export function seedInstall(): InstallFacts {
+ return JSON.parse(
+ seed(['install', UPDATE_ROOT], 40 * 60_000)
+ .split('\n')
+ .pop()!
+ )
+}
+
+/** Put the pristine install + origin back (every spec starts from the same healthy install). */
+export function restoreInstall(): InstallFacts {
+ killInstallProcesses(readFacts())
+ const facts = JSON.parse(seed(['restore', UPDATE_ROOT], 10 * 60_000)) as InstallFacts
+ fs.rmSync(userDataDir(facts), { recursive: true, force: true })
+
+ return facts
+}
+
+export function readFacts(): InstallFacts {
+ return JSON.parse(fs.readFileSync(path.join(UPDATE_ROOT, 'install.json'), 'utf8'))
+}
+
+/** One new upstream commit on origin/main (the release the user updates to); returns its sha. */
+export function publishUpstream(message: string, relPath: string, content: string): string {
+ const file = path.join(UPDATE_ROOT, 'publish-content')
+ fs.writeFileSync(file, content)
+
+ return seed(['publish', UPDATE_ROOT, message, relPath, file]).split('\n').pop()!
+}
+
+export function git(cwd: string, ...args: string[]): string {
+ const cp = spawnSync('git', args, { cwd, encoding: 'utf8', env: { ...process.env, GIT_NO_LAZY_FETCH: '1' } })
+
+ if (cp.status !== 0) {
+ throw new Error(`git ${args.join(' ')} failed in ${cwd}: ${cp.stderr}`)
+ }
+
+ return cp.stdout.trim()
+}
+
+// ─── One spec's world ──────────────────────────────────────────────────
+
+export interface InstallSession {
+ facts: InstallFacts
+ provider: ScriptedProvider
+ edge: GithubEdge
+ /** The environment the user's desktop session starts the app with. */
+ env: Record<string, string>
+ close: () => Promise<void>
+}
+
+/**
+ * The pristine install, the scripted provider configured as the user's
+ * endpoint, and the GitHub edge the install's update check goes through.
+ */
+export async function startInstallSession(): Promise<InstallSession> {
+ const facts = restoreInstall()
+ const provider = await startScriptedProvider()
+ configureProvider(facts, provider.url)
+ const edge = await startGithubEdge(facts.sandboxRoot, facts.origin, facts.env.SSL_CERT_FILE)
+ // The install's own shell env (a user who works behind the proxy) sees the same edge.
+ const env = appEnv(facts, edge.env)
+
+ return {
+ facts,
+ provider,
+ edge,
+ env,
+ close: async () => {
+ killInstallProcesses(facts)
+ await provider.close()
+ await edge.close()
+ }
+ }
+}
+
+// ─── The installed app ─────────────────────────────────────────────────
+
+export function releaseDir(facts: InstallFacts): string {
+ return path.join(facts.checkout, 'apps', 'desktop', 'release', 'linux-unpacked')
+}
+
+/** The packaged executable `hermes desktop` built into the install (electron-builder names it after productName). */
+export function packagedExe(facts: InstallFacts): string {
+ const dir = releaseDir(facts)
+ const name = fs.readdirSync(dir).find(entry => /^hermes$/i.test(entry))
+
+ if (!name) {
+ throw new Error(`no packaged Hermes executable in ${dir}: ${fs.readdirSync(dir).join(', ')}`)
+ }
+
+ return path.join(dir, name)
+}
+
+export function userDataDir(facts: InstallFacts): string {
+ return path.join(facts.sandboxRoot, 'user-data')
+}
+
+/** Display vars the runner provides (xvfb in CI, the live Wayland session locally). */
+function displayEnv(): Record<string, string> {
+ const out: Record<string, string> = {}
+
+ for (const key of ['DISPLAY', 'XAUTHORITY', 'XDG_SESSION_TYPE', 'ELECTRON_OZONE_PLATFORM_HINT']) {
+ if (process.env[key]) {
+ out[key] = process.env[key]!
+ }
+ }
+
+ // The install's XDG_RUNTIME_DIR is sandbox-private, so a Wayland socket name is made absolute.
+ const wayland = process.env.WAYLAND_DISPLAY
+
+ if (wayland) {
+ out.WAYLAND_DISPLAY = path.isAbsolute(wayland)
+ ? wayland
+ : path.join(process.env.XDG_RUNTIME_DIR || `/run/user/${process.getuid?.()}`, wayland)
+ }
+
+ return out
+}
+
+/**
+ * The environment a user's desktop session hands the app: the install's HOME /
+ * HERMES_HOME / PATH (with the git URL rewrite that points "GitHub" at the
+ * local origin) plus the display. No HERMES_DESKTOP_HERMES_ROOT: the app must
+ * find the install the way it does for a real user.
+ */
+export function appEnv(facts: InstallFacts, extra: Record<string, string> = {}): Record<string, string> {
+ fs.mkdirSync(userDataDir(facts), { recursive: true })
+ const windowState = path.join(userDataDir(facts), 'window-state.json')
+
+ if (!fs.existsSync(windowState)) {
+ fs.writeFileSync(windowState, JSON.stringify({ x: 0, y: 0, width: 1280, height: 860, isMaximized: false }))
+ }
+
+ return {
+ ...facts.env,
+ ...displayEnv(),
+ HERMES_DESKTOP_USER_DATA_DIR: userDataDir(facts),
+ HERMES_DESKTOP_SKIP_QUIT_CONFIRM: '1',
+ HERMES_DESKTOP_CDP_PORT: 'off',
+ ...extra
+ }
+}
+
+/** A user who configured a custom OpenAI-compatible endpoint (the scripted provider). */
+export function configureProvider(facts: InstallFacts, providerUrl: string): void {
+ fs.writeFileSync(path.join(facts.hermesHome, 'config.yaml'), providerConfigYaml(providerUrl))
+ fs.writeFileSync(path.join(facts.hermesHome, '.env'), 'MOCK_API_KEY=update-e2e-key\n')
+}
+
+export interface LaunchedApp {
+ app: ElectronApplication
+ page: Page
+ logs: string[]
+ logTail: () => string
+}
+
+export async function launchInstalledApp(facts: InstallFacts, env: Record<string, string>): Promise<LaunchedApp> {
+ const logs: string[] = []
+
+ const app = await _electron.launch({
+ executablePath: packagedExe(facts),
+ args: ['--disable-gpu', '--no-sandbox'],
+ env,
+ cwd: facts.home
+ })
+
+ const collect = (chunk: Buffer) => {
+ logs.push(...chunk.toString('utf8').split('\n').filter(Boolean))
+ logs.splice(0, Math.max(0, logs.length - 300))
+ }
+
+ app.process().stdout?.on('data', collect)
+ app.process().stderr?.on('data', collect)
+ const logTail = () => logs.slice(-80).join('\n')
+
+ const page = await app.firstWindow().catch(async error => {
+ await app.close().catch(() => undefined)
+
+ throw new Error(`installed app never opened a window: ${(error as Error).message.split('\n')[0]}\n${logTail()}`)
+ })
+
+ return { app, page, logs, logTail }
+}
+
+// ─── Observation ───────────────────────────────────────────────────────
+
+export function installProcesses(facts: InstallFacts): ProcInfo[] {
+ return sandboxProcesses({ hermesHome: facts.hermesHome } as CoreSandbox)
+}
+
+function exeOf(pid: number): string {
+ try {
+ return fs.readlinkSync(`/proc/${pid}/exe`)
+ } catch {
+ return ''
+ }
+}
+
+/** Live Desktop main processes of this install (the packaged exe, not its zygote/renderer/gpu children). */
+export function desktopMainProcesses(facts: InstallFacts): ProcInfo[] {
+ const exe = fs.realpathSync(path.dirname(packagedExe(facts)))
+
+ return installProcesses(facts).filter(
+ proc => exeOf(proc.pid).startsWith(exe + path.sep) && !/--type=/.test(proc.cmdline)
+ )
+}
+
+/** The `hermes serve` backend(s) of this install (children of the backend excluded). */
+export function backendServeProcesses(facts: InstallFacts): ProcInfo[] {
+ const serve = installProcesses(facts).filter(
+ proc =>
+ / serve( |$)/.test(proc.cmdline) && !/--type=/.test(proc.cmdline) && !exeOf(proc.pid).includes('linux-unpacked')
+ )
+
+ const pids = new Set(serve.map(proc => proc.pid))
+
+ return serve.filter(proc => !pids.has(proc.ppid))
+}
+
+export function readText(file: string): string {
+ try {
+ return fs.readFileSync(file, 'utf8')
+ } catch {
+ return ''
+ }
+}
+
+export function desktopLog(facts: InstallFacts): string {
+ return readText(path.join(facts.hermesHome, 'logs', 'desktop.log'))
+}
+
+export function handoffLog(facts: InstallFacts): string {
+ return readText(path.join(facts.hermesHome, 'logs', 'desktop-update-handoff.log'))
+}
+
+function tail(text: string, n: number): string {
+ return text.split('\n').slice(-n).join('\n')
+}
+
+/** Everything a red cell needs to explain itself. */
+export function diagnostics(facts: InstallFacts, extra = ''): string {
+ const logsDir = path.join(facts.hermesHome, 'logs')
+ const parts: string[] = [extra]
+
+ try {
+ parts.push(`checkout HEAD: ${git(facts.checkout, 'rev-parse', 'HEAD')}`)
+ parts.push(`git status:\n${git(facts.checkout, 'status', '--short')}`)
+ } catch (error) {
+ parts.push(String(error))
+ }
+
+ for (const name of fs.existsSync(logsDir) ? fs.readdirSync(logsDir) : []) {
+ if (/\.log$/.test(name)) {
+ parts.push(`── ${name} (tail) ──\n${tail(readText(path.join(logsDir, name)), 40)}`)
+ }
+ }
+
+ const receipts = path.join(facts.hermesHome, 'update-receipts')
+
+ if (fs.existsSync(receipts)) {
+ for (const name of fs.readdirSync(receipts).slice(-3)) {
+ parts.push(`── receipt ${name} ──\n${tail(readText(path.join(receipts, name)), 30)}`)
+ }
+ }
+
+ parts.push(
+ `── processes of this install ──\n${installProcesses(facts)
+ .map(proc => `${proc.pid} (ppid ${proc.ppid}) ${proc.cmdline.slice(0, 200)}`)
+ .join('\n')}`
+ )
+
+ return parts.filter(Boolean).join('\n')
+}
+
+/** SIGKILL every process that carries this install's HERMES_HOME (end of every spec). */
+export function killInstallProcesses(facts: InstallFacts | null): void {
+ if (!facts) {
+ return
+ }
+
+ for (const proc of installProcesses(facts)) {
+ try {
+ process.kill(proc.pid, 'SIGKILL')
+ } catch {
+ /* already gone */
+ }
+ }
+}
+
+export async function waitFor<T>(
+ what: string,
+ probe: () => T | Promise<T>,
+ { timeout, interval = 500, explain }: { timeout: number; interval?: number; explain?: () => string }
+): Promise<NonNullable<T>> {
+ const deadline = Date.now() + timeout
+
+ for (;;) {
+ const value = await probe()
+
+ if (value) {
+ return value as NonNullable<T>
+ }
+
+ if (Date.now() > deadline) {
+ throw new Error(`timed out after ${timeout} ms waiting for ${what}\n${explain?.() ?? ''}`)
+ }
+
+ await new Promise(resolve => setTimeout(resolve, interval))
+ }
+}
+
+// ─── UI steps ──────────────────────────────────────────────────────────
+
+/** Copy of the first-run chooser / bootstrap installer overlay (the screens a healthy install must never show). */
+export const FIRST_RUN_SCREENS = [
+ 'Set up Hermes Desktop',
+ 'Hermes needs a one-time install',
+ 'Setting up Hermes Agent',
+ 'Install Hermes locally',
+ 'Use Hermes on this computer'
+]
+
+/**
+ * Record every first-run/bootstrap screen that is ever painted, even for a
+ * frame (the #123888 chooser flashed before the backend won on some boots).
+ */
+export async function installFirstRunSampler(page: Page): Promise<void> {
+ await page.evaluate(screens => {
+ const w = window as unknown as { __firstRunSeen?: string[] }
+ w.__firstRunSeen = []
+
+ const scan = () => {
+ const text = document.body?.innerText ?? ''
+
+ for (const screen of screens) {
+ if (text.includes(screen) && !w.__firstRunSeen!.includes(screen)) {
+ w.__firstRunSeen!.push(screen)
+ }
+ }
+ }
+
+ scan()
+ new MutationObserver(scan).observe(document.documentElement, {
+ childList: true,
+ subtree: true,
+ characterData: true
+ })
+ }, FIRST_RUN_SCREENS)
+}
+
+export async function firstRunScreensSeen(page: Page): Promise<string[]> {
+ return page.evaluate(() => (window as unknown as { __firstRunSeen?: string[] }).__firstRunSeen ?? [])
+}
+
+export async function openAbout(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ location.hash = '#/settings?tab=about'
+ })
+ await expect(page.getByRole('button', { name: /check now|update now/i }).first()).toBeVisible({ timeout: 60_000 })
+}
+
+/** Force a check against the (local) origin and wait until the About panel offers "Update now". */
+export async function waitForUpdateOffer(page: Page, targetSha: string): Promise<void> {
+ await expect
+ .poll(
+ async () => {
+ const status = await checkForUpdates(page).catch(e => ({ e: String(e) }))
+
+ return JSON.stringify(status)
+ },
+ { timeout: 120_000, intervals: [2_000], message: `Desktop update check offers ${targetSha}` }
+ )
+ .toContain(targetSha)
+ await expect(page.getByRole('button', { name: /^update now$/i }).first()).toBeVisible({ timeout: 60_000 })
+}
+
+/** The `[updates]` lines the app logged after `offset` (what it told the user about this update). */
+export function updateLogLines(facts: InstallFacts, offset = 0): string {
+ return desktopLog(facts)
+ .slice(offset)
+ .split('\n')
+ .filter(line => line.includes('[updates]'))
+ .join('\n')
+}
+
+/**
+ * Click the About panel's "Update now" and wait until the app either quits for
+ * the hand-off or logs why it did not. The final assertion is gated on the
+ * open PM-install pre-flight bug (#122991) by its exact message.
+ */
+export async function clickUpdateNowAndExpectHandoff(launched: LaunchedApp, facts: InstallFacts): Promise<void> {
+ const offset = desktopLog(facts).length
+ let quit = false
+ launched.app.process().once('exit', () => {
+ quit = true
+ })
+ await launched.page
+ .getByRole('button', { name: /^update now$/i })
+ .first()
+ .click()
+ await waitFor(
+ 'the app to quit for the update hand-off, or to log why it did not',
+ () => quit || /\[updates\] .*(fail|cancel|refus|could not|already running)/i.test(updateLogLines(facts, offset)),
+ { timeout: 120_000, explain: () => diagnostics(facts, launched.logTail()) }
+ )
+ await gatedOn(KNOWN.preflightPython, () => {
+ expect(
+ quit,
+ `"Update now" hands off to the updater and the app quits for it; the app logged:\n${updateLogLines(facts, offset)}`
+ ).toBe(true)
+ })
+}
+
+export function isAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0)
+
+ return !/^\S+ \(.*\) Z /.test(readText(`/proc/${pid}/stat`))
+ } catch {
+ return false
+ }
+}
+
+/** The fields of the Desktop update status these specs read. */
+export interface UpdateStatus {
+ currentSha?: string
+ targetSha?: string
+ updateAvailable?: boolean
+ behind?: null | number
+}
+
+/** A forced update check through the app's own preload bridge (what the About panel calls). */
+export async function checkForUpdates(page: Page): Promise<null | UpdateStatus> {
+ return page.evaluate(() => {
+ const bridge = (
+ window as unknown as { hermesDesktop: { updates: { check(o: { force: boolean }): Promise<unknown> } } }
+ ).hermesDesktop
+
+ return bridge.updates.check({ force: true }) as Promise<null | UpdateStatus>
+ })
+}
+
+/** "Is this install current on `sha`?" as the app reports it. */
+export async function currentAs(page: Page): Promise<{ currentSha?: string; updateAvailable: boolean }> {
+ const status = await checkForUpdates(page)
+
+ return {
+ currentSha: status?.currentSha,
+ updateAvailable: Boolean(status?.updateAvailable ?? (status?.behind ?? 0) > 0)
+ }
+}
+
+/** Close an app whose process may already be gone (Playwright's handle throws synchronously then). */
+export async function closeQuietly(app: ElectronApplication): Promise<void> {
+ try {
+ await app.close()
+ } catch {
+ // already exited
+ }
+}
diff --git a/apps/desktop/e2e/update/playwright.config.ts b/apps/desktop/e2e/update/playwright.config.ts
new file mode 100644
index 00000000000..190117f4b18
--- /dev/null
+++ b/apps/desktop/e2e/update/playwright.config.ts
@@ -0,0 +1,36 @@
+import '../fix-electron-tracing'
+
+import { defineConfig } from '@playwright/test'
+
+/**
+ * Desktop install/update suite (PR-time, Linux).
+ *
+ * Every spec drives the packaged app a real install built, against that
+ * install's real backend, and updates it through the app's own "Update now".
+ * globalSetup builds the install once (scripts/install.sh + `hermes desktop
+ * --build-only`); each spec restores that snapshot, so specs run serially.
+ *
+ * - retries: 0 (a required lane must expose flake, not hide it);
+ * - one worker: specs share one install path (absolute paths are baked in);
+ * - per-test budget covers a real `hermes update` (git pull + product builds +
+ * packaging) and the app's relaunch.
+ */
+// Local parallel runs against different install roots need separate output dirs.
+const OUT = process.env.HERMES_E2E_UPDATE_OUT ?? 'update'
+
+export default defineConfig({
+ testDir: '.',
+ testMatch: '*.spec.ts',
+ globalSetup: './global-setup.ts',
+ timeout: 12 * 60_000,
+ expect: { timeout: 60_000 },
+ retries: 0,
+ workers: 1,
+ fullyParallel: false,
+ reporter: [['list'], ['html', { open: 'never', outputFolder: `../../playwright-report/${OUT}` }]],
+ outputDir: `../../test-results/${OUT}`,
+ use: {
+ screenshot: 'only-on-failure',
+ trace: 'retain-on-failure'
+ }
+})
diff --git a/apps/desktop/e2e/update/seed.py b/apps/desktop/e2e/update/seed.py
new file mode 100644
index 00000000000..c068333426d
--- /dev/null
+++ b/apps/desktop/e2e/update/seed.py
@@ -0,0 +1,114 @@
+"""Seed and reset the real local install the Desktop update suite drives.
+
+The install is made by the real entry points a Linux user runs (``scripts/install.sh`` and then
+``hermes desktop --build-only``) against a local bare origin, inside the upgrade suite's sandbox
+machinery (``tests/e2e/core/upgrade``). Building it takes minutes, so it is built once per run into
+``<root>/sb`` and snapshotted; each spec restores the snapshot back into the SAME path (the install
+bakes absolute paths into launchers and PM facts, so a copy elsewhere would not be the same install).
+
+ python seed.py install <root> -> JSON {home, hermesHome, checkout, origin, env, headSha}
+ python seed.py restore <root> -> the snapshot back in place (install + origin)
+ python seed.py publish <root> <message> <relpath> <content-file> -> sha of the new origin/main
+
+HERMES_E2E_UPDATE_INSTALL_REF=<sha> installs that commit instead of HEAD (local A/B against an open
+fix, or a sabotage commit, without touching the checkout the suite runs from).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[4]
+sys.path.insert(0, str(REPO_ROOT))
+
+from tests.e2e.core.upgrade import _helpers as H # noqa: E402
+from tests.e2e.core.upgrade import _install_helpers as I # noqa: E402
+
+
+def _paths(root: Path) -> dict[str, Path]:
+ return {
+ "sb": root / "sb",
+ "origin": root / "origin.git",
+ "golden": root / "golden",
+ "facts": root / "install.json",
+ }
+
+
+def _sandbox(root: Path) -> I.Sandbox:
+ facts = json.loads(_paths(root)["facts"].read_text(encoding="utf-8"))
+ return I.Sandbox(root=Path(facts["sandboxRoot"]), env=facts["env"])
+
+
+def _fail(what: str, cp: subprocess.CompletedProcess) -> None:
+ sys.stderr.write(f"{what} failed:\n{H.describe(cp)}\n")
+ raise SystemExit(1)
+
+
+def install(root: Path) -> None:
+ p = _paths(root)
+ root.mkdir(parents=True, exist_ok=True)
+ for key in ("sb", "origin", "golden"):
+ shutil.rmtree(p[key], ignore_errors=True)
+ head = os.environ.get("HERMES_E2E_UPDATE_INSTALL_REF") or I.head_sha()
+ origin = I.make_origin(root, head)
+ sb = I.new_sandbox(p["sb"], origin)
+ cp = I.run_installer(sb)
+ if cp.returncode != 0:
+ _fail("scripts/install.sh --non-interactive", cp)
+ # The real way a CLI install gets the Desktop app on Linux: build + package into
+ # apps/desktop/release/linux-unpacked, the tree the Desktop updater swaps in place.
+ cp = sb.cli("desktop", "--build-only", timeout=1800)
+ if cp.returncode != 0:
+ _fail("hermes desktop --build-only", cp)
+ facts = {
+ "sandboxRoot": str(sb.root),
+ "home": str(sb.home),
+ "hermesHome": str(sb.hermes_home),
+ "checkout": str(sb.checkout),
+ "hermes": sb.hermes,
+ "origin": str(origin),
+ "env": sb.env,
+ "headSha": head,
+ }
+ p["facts"].write_text(json.dumps(facts, indent=1), encoding="utf-8")
+ p["golden"].mkdir()
+ for key in ("sb", "origin"):
+ subprocess.run(["cp", "-a", str(p[key]), str(p["golden"] / key)], check=True)
+ print(json.dumps(facts))
+
+
+def restore(root: Path) -> None:
+ p = _paths(root)
+ for key in ("sb", "origin"):
+ shutil.rmtree(p[key], ignore_errors=True)
+ subprocess.run(["cp", "-a", str(p["golden"] / key), str(p[key])], check=True)
+ print(p["facts"].read_text(encoding="utf-8"))
+
+
+def publish(root: Path, message: str, rel: str, content_file: str) -> None:
+ p = _paths(root)
+ scratch = root / "publish"
+ scratch.mkdir(exist_ok=True)
+ text = Path(content_file).read_text(encoding="utf-8")
+ print(I.publish_commit(p["origin"], scratch, message, {rel: text}))
+
+
+def main(argv: list[str]) -> None:
+ cmd, root = argv[0], Path(argv[1]).resolve()
+ if cmd == "install":
+ install(root)
+ elif cmd == "restore":
+ restore(root)
+ elif cmd == "publish":
+ publish(root, argv[2], argv[3], argv[4])
+ else:
+ raise SystemExit(f"unknown command {cmd!r}")
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
diff --git a/apps/desktop/e2e/update/update-concurrency.spec.ts b/apps/desktop/e2e/update/update-concurrency.spec.ts
new file mode 100644
index 00000000000..f8f60d7e900
--- /dev/null
+++ b/apps/desktop/e2e/update/update-concurrency.spec.ts
@@ -0,0 +1,168 @@
+/**
+ * Failure class: ABOUT PANEL / UPDATE UX — one update at a time, and the
+ * panel tells the truth afterwards.
+ *
+ * #123117: the About panel's update buttons let a second update start while
+ * one was already running, and the panel's state stopped matching the
+ * install. Here the user starts `hermes update` in a terminal, then clicks
+ * "Update now" in the running app before the terminal update is done:
+ * - the app refuses and says an update is already running (no second
+ * updater process is started, the app stays up);
+ * - the terminal update finishes successfully;
+ * - afterwards the same running app reports the install as current on the
+ * new commit (no stale "Update now") and a chat turn completes.
+ */
+
+import { spawn } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+import { expect, test } from '@playwright/test'
+
+import { recordWebSockets, send, waitForInteractive } from '../core/harness'
+
+import {
+ backendServeProcesses,
+ closeQuietly,
+ currentAs,
+ diagnostics,
+ isAlive,
+ git,
+ installProcesses,
+ launchInstalledApp,
+ openAbout,
+ publishUpstream,
+ readText,
+ startInstallSession,
+ updateLogLines,
+ desktopLog,
+ waitFor,
+ waitForUpdateOffer
+} from './harness'
+
+const RUN = Date.now().toString(36)
+const U = (n: number) => `U${n}-${RUN}`
+const A = (n: number) => `A${n}-${RUN}`
+
+test('Update now while a terminal update runs is refused, and the panel is truthful once that update lands', async () => {
+ test.setTimeout(20 * 60_000)
+ const session = await startInstallSession()
+ const { facts, provider, env } = session
+ const target = publishUpstream('release: next upstream main', 'UPSTREAM_RELEASE.md', `next release ${RUN}\n`)
+ const marker = path.join(facts.hermesHome, '.hermes-update-in-progress')
+ const cliLog = path.join(facts.sandboxRoot, 'terminal-update.log')
+ let cliExit: null | number = null
+
+ try {
+ const launched = await launchInstalledApp(facts, env)
+ const { app, page, logTail } = launched
+ // Track the app's exit ourselves: once the terminal update stops it, Playwright's handle is dead.
+ let appExited = false
+ app.process().once('exit', () => {
+ appExited = true
+ })
+ const explain = (extra = '') =>
+ diagnostics(
+ facts,
+ `${extra}\n── terminal hermes update (tail) ──\n${readText(cliLog).split('\n').slice(-40).join('\n')}\n${logTail()}`
+ )
+
+ try {
+ const ws = recordWebSockets(page)
+ await waitForInteractive(app, page).catch(error => {
+ throw new Error(`${(error as Error).message}\n${explain()}`)
+ })
+ const oldBackends = backendServeProcesses(facts).map(proc => proc.pid)
+ await openAbout(page)
+ await waitForUpdateOffer(page, target)
+
+ await test.step('a terminal `hermes update` is running', async () => {
+ const out = fs.openSync(cliLog, 'w')
+ const cli = spawn(facts.hermes, ['update', '--yes'], {
+ cwd: facts.home,
+ env: { ...env, TERM: 'dumb' },
+ stdio: ['ignore', out, out]
+ })
+ cli.once('exit', code => {
+ cliExit = code ?? -1
+ })
+ await waitFor('the terminal update to own the update marker', () => fs.existsSync(marker) || cliExit !== null, {
+ timeout: 120_000,
+ interval: 100,
+ explain
+ })
+ expect(cliExit, `the terminal update is still running when the user clicks\n${explain()}`).toBeNull()
+ })
+
+ await test.step('clicking Update now is refused while it runs', async () => {
+ const offset = desktopLog(facts).length
+ await page
+ .getByRole('button', { name: /^update now$/i })
+ .first()
+ .click()
+ await expect(page.getByText(/An update is already running/).first()).toBeVisible({ timeout: 30_000 })
+ expect(appExited, 'the app stays up').toBe(false)
+ expect(updateLogLines(facts, offset), 'the app refused the hand-off').toMatch(
+ /refusing (posix )?hand-off: An update is already running/
+ )
+ expect(
+ installProcesses(facts)
+ .filter(proc => /desktop-update\/posix\.sh|hermes-desktop-update/.test(proc.cmdline))
+ .map(p => p.cmdline),
+ 'no second updater was started'
+ ).toEqual([])
+ })
+
+ await test.step('the terminal update lands', async () => {
+ await waitFor('the terminal update to finish', () => cliExit !== null, {
+ timeout: 8 * 60_000,
+ interval: 1_000,
+ explain
+ })
+ expect(cliExit, `terminal hermes update exits 0\n${explain()}`).toBe(0)
+ expect(git(facts.checkout, 'rev-parse', 'HEAD'), 'the checkout is on the new commit').toBe(target)
+ })
+
+ await test.step('reopened after the terminal update, the app is truthful: current, no stale Update now, chat works', async () => {
+ // The terminal update's stage-and-swap stops a Desktop running from the release tree it
+ // replaces (#109643); if it did not, the user quits it. Either way nothing from before
+ // the update may keep running.
+ if (!appExited) {
+ await closeQuietly(app)
+ }
+ await waitFor(
+ 'the pre-update backend to be gone once its app is',
+ () => oldBackends.every(pid => !isAlive(pid)),
+ { timeout: 60_000, explain }
+ )
+ const reopened = await launchInstalledApp(facts, env)
+ try {
+ const ws2 = recordWebSockets(reopened.page)
+ await waitForInteractive(reopened.app, reopened.page).catch(error => {
+ throw new Error(`${(error as Error).message}\n${explain(reopened.logTail())}`)
+ })
+ await expect
+ .poll(() => currentAs(reopened.page), {
+ timeout: 120_000,
+ intervals: [2_000],
+ message: 'the app reports the install current on the new commit'
+ })
+ .toEqual({ currentSha: target, updateAvailable: false })
+ await openAbout(reopened.page)
+ await expect(reopened.page.getByRole('button', { name: /^update now$/i })).toHaveCount(0, { timeout: 60_000 })
+ provider.script(U(1), [{ text: [`${A(1)} `, 'after ', 'terminal ', 'update'] }])
+ await send(reopened.page, `${U(1)} still here?`, 'Enter', ws2)
+ await expect(reopened.page.getByText(`${A(1)} after terminal update`)).toBeVisible({ timeout: 120_000 })
+ } finally {
+ await closeQuietly(reopened.app)
+ }
+ })
+ } finally {
+ if (!appExited) {
+ await closeQuietly(app)
+ }
+ }
+ } finally {
+ await session.close()
+ }
+})
diff --git a/apps/desktop/playwright.config.ts b/apps/desktop/playwright.config.ts
index bc3fd9e6b82..71b67a8139d 100644
--- a/apps/desktop/playwright.config.ts
+++ b/apps/desktop/playwright.config.ts
@@ -32,7 +32,7 @@ export default defineConfig({
* app) and is owned by the vitest `electron` project. Without this the
* default testMatch would claim those files too and run them twice.
* e2e/core/ has its own config (retries 0, one worker) and CI job. */
- testIgnore: ['**/*.unit.test.ts', 'core/**'],
+ testIgnore: ['**/*.unit.test.ts', 'core/**', 'update/**'],
/* The desktop app can take a while to bootstrap on cold CI runners — 90 s
* per test gives us headroom without masking real hangs. */
timeout: 90_000,