The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(install-e2e): macOS packaged-app open-app-update arm on real signed bundles
ethernet17a81734e807
diff --git a/.github/workflows/install-e2e-macos-run.yml b/.github/workflows/install-e2e-macos-run.ymlindex 46245b73c54..89b42a79641 100644--- a/.github/workflows/install-e2e-macos-run.yml+++ b/.github/workflows/install-e2e-macos-run.yml@@ -47,6 +47,16 @@ on:required: falsetype: stringdefault: https://hermes-assets.nousresearch.com/Hermes-Setup.dmg+ bundle-manifest-url:+ description: 'URL of the JSON schema-1 bundle manifest for the packaged-app arm. Empty (default) means the bundled arm does not run — native packaged coverage only runs when the caller pins a real signed OLD/NEW pair.'+ required: false+ type: string+ default: ''+ bundle-arch:+ description: 'Architecture of the bundled pair: arm64 (macos-15) or x64 (macos-15-intel).'+ required: false+ type: string+ default: arm64timeout-minutes:description: 'Job timeout. App-update legs do a full Electron build.'required: false@@ -160,3 +170,72 @@ jobs:path: ${{ runner.temp }}/e2e-logsretention-days: 14if-no-files-found: ignore++ # ---- arm 3: the real signed bundle pair, in-app update ------------------+ # Runs ONLY when the caller passes a bundle-manifest-url: the parent's+ # matrix job owns resolving + pinning the OLD/NEW signed release pair.+ # The driver itself re-guards on Darwin + GITHUB_ACTIONS and refuses to+ # run anywhere native coverage would be fake.+ bundled-e2e:+ name: packaged bundle (open-app-update)+ if: inputs.bundle-manifest-url != ''+ runs-on: ${{ inputs.bundle-arch == 'x64' && 'macos-15-intel' || 'macos-15' }}+ timeout-minutes: ${{ inputs.timeout-minutes }}++ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2++ - name: Start screen recording+ uses: ./.github/actions/e2e-screen-record+ with:+ mode: start+ output: ${{ runner.temp }}/e2e-logs/recording.mkv++ - name: Install OLD signed bundle (${{ inputs.install-ref }})+ run: |+ set -euo pipefail+ tests/install/macos-bundled-e2e.sh --phase install \+ --manifest-url '${{ inputs.bundle-manifest-url }}' \+ --arch '${{ inputs.bundle-arch }}'+ env:+ HERMES_E2E_LOG_DIR: ${{ runner.temp }}/e2e-logs++ - name: Update to NEW via About -> Update now (${{ inputs.bundle-arch }})+ run: |+ set -euo pipefail+ tests/install/macos-bundled-e2e.sh --phase update \+ --manifest-url '${{ inputs.bundle-manifest-url }}' \+ --arch '${{ inputs.bundle-arch }}'+ env:+ HERMES_E2E_LOG_DIR: ${{ runner.temp }}/e2e-logs++ - name: Stop screen recording+ if: always()+ uses: ./.github/actions/e2e-screen-record+ with:+ mode: stop+ output: ${{ runner.temp }}/e2e-logs/recording.mkv++ - name: Remux recording for browser playback+ if: always()+ run: |+ set -euo pipefail+ if [ -f "${{ runner.temp }}/e2e-logs/recording.mkv" ]; then+ ffmpeg -y -hide_banner -loglevel error -i "${{ runner.temp }}/e2e-logs/recording.mkv" \+ -c copy "${{ runner.temp }}/e2e-logs/recording.mp4"+ fi++ - name: Build artifact name+ id: artifact+ if: always()+ run: |+ echo "name=install-e2e-logs-${{ inputs.leg-id }}-bundle-${{ inputs.bundle-arch }}" >> "$GITHUB_OUTPUT"++ - name: Upload logs+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: ${{ steps.artifact.outputs.name }}+ path: ${{ runner.temp }}/e2e-logs+ retention-days: 14+ if-no-files-found: ignorediff --git a/tests-js/macos-bundled-helpers.test.mjs b/tests-js/macos-bundled-helpers.test.mjsnew file mode 100644index 00000000000..eab98c70017--- /dev/null+++ b/tests-js/macos-bundled-helpers.test.mjs@@ -0,0 +1,158 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { createRequire } from 'node:module'++import { expect, it, describe } from 'vitest'++const require = createRequire(import.meta.url)+const {+ validateBundleManifest,+ codesignTeam,+ stampAssertions,+} = require('../tests/install/e2e-assets/mac-bundled-manifest.cjs')++const side = (over = {}) => ({+ tag: 'v0.28.0',+ version: '0.28.0',+ commit: 'a'.repeat(40),+ identity: 'TEAM1234',+ artifact: { url: 'https://example.com/HermesBundled-0.28.0-mac-arm64.zip', sha256: 'b'.repeat(64), path: '/tmp/old.zip' },+ ...over,+})+const manifest = (over = {}) => ({+ schema: 1,+ platform: 'macos',+ arch: 'arm64',+ old: side(),+ new: side({+ tag: 'v0.29.0',+ version: '0.29.0',+ commit: 'c'.repeat(40),+ artifact: { url: 'https://example.com/HermesBundled-0.29.0-mac-arm64.zip', sha256: 'd'.repeat(64), path: '/tmp/new.zip' },+ }),+ ...over,+})+const want = { platform: 'macos', arch: 'arm64' }++describe('validateBundleManifest', () => {+ it('accepts a well-formed schema-1 pair', () => {+ expect(() => validateBundleManifest(manifest(), want)).not.toThrow()+ })++ it('rejects wrong schema, platform and arch', () => {+ expect(() => validateBundleManifest(manifest({ schema: 2 }), want)).toThrow(/schema/)+ expect(() => validateBundleManifest(manifest({ platform: 'windows' }), want)).toThrow(/platform/)+ expect(() => validateBundleManifest(manifest({ arch: 'x64' }), want)).toThrow(/arch/)+ expect(() => validateBundleManifest(manifest(), { platform: 'macos', arch: 'riscv' })).toThrow(/arch/)+ })++ it('rejects version/tag and commit-shaped lies', () => {+ expect(() => validateBundleManifest(manifest({ old: side({ version: '0.99.0' }) }), want)).toThrow(/version/)+ expect(() => validateBundleManifest(manifest({ old: side({ tag: 'notatag' }) }), want)).toThrow(/tag/)+ expect(() => validateBundleManifest(manifest({ old: side({ commit: 'zz' }) }), want)).toThrow(/commit/)+ })++ it('requires the resolver to have downloaded the artifact', () => {+ expect(() => validateBundleManifest(+ manifest({ old: side({ artifact: { url: 'x', sha256: 'b'.repeat(64) } }) }), want,+ )).toThrow(/artifact.path/)+ expect(() => validateBundleManifest(+ manifest({ old: side({ artifact: { url: 'x', sha256: 'nothex', path: '/tmp/x' } }) }), want,+ )).toThrow(/sha256/)+ })++ it('rejects a no-op pair and a team-changing pair (Squirrel gate)', () => {+ expect(() => validateBundleManifest(manifest({ new: side() }), want)).toThrow(/no update/)+ expect(() => validateBundleManifest(+ manifest({ new: side({ commit: 'c'.repeat(40), identity: 'OTHER999', tag: 'v0.29.0', version: '0.29.0', artifact: { url: 'u', sha256: 'd'.repeat(64), path: '/tmp/n' } }) }), want,+ )).toThrow(/Squirrel/)+ })+})++describe('codesignTeam', () => {+ it('parses the team from codesign -dv output', () => {+ const out = [+ 'Executable=/tmp/Hermes.app/Contents/MacOS/Hermes',+ 'Identifier=com.nousresearch.hermes-bundled',+ 'TeamIdentifier=TEAM1234',+ ].join('\n')+ expect(codesignTeam(out)).toBe('TEAM1234')+ })+ it('returns null when unsigned', () => {+ expect(codesignTeam('Identifier=com.x\nTeamIdentifier=not set')).toBeNull()+ })+})++describe('stampAssertions', () => {+ const sideArg = { commit: 'a'.repeat(40), tag: 'v0.28.0' }+ const good = {+ schemaVersion: 2,+ commit: 'a'.repeat(40),+ branch: 'main',+ payload: 'bundled',+ store: false,+ distribution: 'desktop-app',+ updateMechanism: 'electron-updater',+ tag: 'v0.28.0',+ }+ it('accepts the bundled electron-updater stamp', () => {+ expect(stampAssertions(good, sideArg)).toEqual([])+ })+ it('flags wrong mechanism, payload, commit and tag', () => {+ const problems = stampAssertions(+ { ...good, updateMechanism: 'external', payload: 'light', commit: 'b'.repeat(40), tag: null },+ sideArg,+ )+ expect(problems).toHaveLength(4)+ })+ it('rejects non-objects and store submissions', () => {+ expect(stampAssertions(null, sideArg)).toHaveLength(1)+ expect(stampAssertions({ ...good, store: true }, sideArg).join(' ')).toMatch(/store/)+ })+})++describe('mac-bundled-feed materializer', () => {+ it('emits the production update-feed contract for the real NEW zip', async () => {+ const { materializeFeed, feedFileNames } = await import('../tests/install/e2e-assets/mac-bundled-feed.mjs')+ const { createHash } = await import('node:crypto')++ // The feed layout comes from the ONE production contract, not a copy.+ const { darwinFeed } = require('../apps/desktop/update-feed.cjs')+ expect(darwinFeed('stable').directory).toBe('releases/darwin/stable')+ expect(feedFileNames('arm64').prefixed).toBe('arm64-stable-mac.yml')+ expect(feedFileNames('x64').prefixed).toBe('stable-mac.yml')++ const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mac-feed-'))+ const zip = path.join(outDir, 'HermesBundled-0.29.0-mac-arm64.zip')+ const zipBytes = Buffer.from('fake signed zip for feed shape tests')+ fs.writeFileSync(zip, zipBytes)+ const expectedSha512 = createHash('sha512').update(zipBytes).digest('base64')++ const receipt = materializeFeed({+ outDir,+ zipPath: zip,+ version: '0.29.0',+ tag: 'v0.29.0',+ arch: 'arm64',+ releaseDate: '2026-09-07T00:00:00.000Z',+ })++ // The artifact is served under the merged production URL shape.+ expect(receipt.artifactUrlPath).toBe('/releases/tag/v0.29.0/HermesBundled-0.29.0-mac-arm64.zip')+ expect(receipt.written).toEqual([+ 'releases/darwin/stable/arm64-stable-mac.yml',+ 'releases/darwin/stable/stable-mac.yml',+ ])+ const yml = fs.readFileSync(path.join(outDir, 'releases/darwin/stable/arm64-stable-mac.yml'), 'utf8')+ expect(yml).toContain('version: 0.29.0')+ expect(yml).toContain(' - url: /releases/tag/v0.29.0/HermesBundled-0.29.0-mac-arm64.zip')+ expect(yml).toContain(` sha512: ${expectedSha512}`)+ expect(yml).toContain(` size: ${zipBytes.length}`)+ expect(yml).toContain(`path: /releases/tag/v0.29.0/HermesBundled-0.29.0-mac-arm64.zip`)+ expect(yml).toContain(`sha512: ${expectedSha512}`)+ // The served artifact bytes are the real NEW zip, copied verbatim.+ expect(fs.readFileSync(path.join(outDir, 'releases/tag/v0.29.0/HermesBundled-0.29.0-mac-arm64.zip')))+ .toEqual(zipBytes)+ })+})diff --git a/tests/install/e2e-assets/mac-bundled-feed.mjs b/tests/install/e2e-assets/mac-bundled-feed.mjsnew file mode 100644index 00000000000..3e30f28d078--- /dev/null+++ b/tests/install/e2e-assets/mac-bundled-feed.mjs@@ -0,0 +1,116 @@+'use strict'+// mac-bundled-feed.mjs — build the loopback static update feed for the+// macOS packaged-app -> open-app-update E2E arm from the REAL signed NEW+// zip downloaded by the parent resolver. Dependency-free (runs on the mac+// CI runner with no npm install), pure where possible so tests-js can+// assert the generated bytes.+//+// Production contract (scripts/darwin-feed.mjs + apps/desktop/update-feed.cjs):+// feed key releases/darwin/<channel>/<channel>-mac.yml+// merged url /releases/tag/<tag>/<artifact>.zip+// A release publishes the MERGED feed (both arches merged by+// r2-release.mjs finalize). electron-updater on arm64 requests+// arm64-stable-mac.yml; on x64 it requests stable-mac.yml. This controlled+// single-arch loopback feed emits the same merged shape and serves both+// request names with identical bytes.++import { createHash } from 'node:crypto'+import fs from 'node:fs'+import path from 'node:path'+import { createRequire } from 'node:module'++const require = createRequire(import.meta.url)+// The one feed-layout contract, straight from the production source.+const { darwinFeed } = require('../../../apps/desktop/update-feed.cjs')++export function sha512Base64(filePath) {+ return createHash('sha512').update(fs.readFileSync(filePath)).digest('base64')+}++/**+ * The electron-updater yml for one arch leg, in the shape electron-builder+ * writes per arch and r2-release.mjs merges: per-arch top-level path/sha512+ * plus files[] (url/sha512/size), releaseDate. Arch metadata names differ+ * by design; nothing here assumes they are equal across arches.+ */+export function buildMacFeedText({ version, tag, zipName, sha512, size, releaseDate }) {+ const lines = [+ `version: ${version}`,+ 'files:',+ ` - url: /releases/tag/${tag}/${zipName}`,+ ` sha512: ${sha512}`,+ ` size: ${size}`,+ `path: /releases/tag/${tag}/${zipName}`,+ `sha512: ${sha512}`,+ `releaseDate: '${releaseDate}'`,+ ''+ ]+ return lines.join('\n')+}++/** The feed file names electron-updater asks for on this arch (and the+ * un-prefixed name, served too so the merged-feed contract holds). */+export function feedFileNames(arch) {+ const feed = darwinFeed('stable')+ const prefixed = arch === 'x64' ? feed.fileName : `${arch}-${feed.fileName}`+ return { feed, prefixed, plain: feed.fileName, directory: feed.directory }+}++/**+ * Materialize the loopback feed directory:+ * <out>/releases/darwin/stable/{arm64-,}stable-mac.yml+ * <out>/releases/tag/<tag>/<zipName> (copy of the real NEW zip)+ * Returns a receipt for the driver to assert.+ */+export function materializeFeed({ outDir, zipPath, version, tag, arch, releaseDate }) {+ const zipStat = fs.statSync(zipPath)+ if (zipStat.size <= 0) throw new Error(`feed: empty zip at ${zipPath}`)+ const zipName = path.basename(zipPath)+ if (!zipName.endsWith('.zip')) {+ throw new Error(`feed: expected a .zip artifact, got ${zipName}`)+ }+ const sha512 = sha512Base64(zipPath)+ const text = buildMacFeedText({ version, tag, zipName, sha512, size: zipStat.size, releaseDate })++ const { prefixed, plain, directory } = feedFileNames(arch)+ const feedDir = path.join(outDir, directory)+ fs.mkdirSync(feedDir, { recursive: true })+ const written = []+ for (const name of [prefixed, plain]) {+ const file = path.join(feedDir, name)+ fs.writeFileSync(file, text)+ // URL-style keys (portable across the mac runner and CI logs)+ written.push(`${directory}/${name}`)+ }++ const artifactDir = path.join(outDir, 'releases', 'tag', tag)+ fs.mkdirSync(artifactDir, { recursive: true })+ const artifactDest = path.join(artifactDir, zipName)+ fs.copyFileSync(zipPath, artifactDest)++ return { feedKey: `${directory}/${prefixed}`, written, artifactUrlPath: `/releases/tag/${tag}/${zipName}`, sha512, size: zipStat.size, version, tag }+}++// CLI entry: node mac-bundled-feed.mjs --out DIR --zip FILE --version V \+// --tag vX.Y.Z --arch arm64|x64+if (process.argv.length > 2 && process.argv[1].endsWith('mac-bundled-feed.mjs')) {+ const { parseArgs } = await import('node:util')+ const { values } = parseArgs({+ options: {+ out: { type: 'string' },+ zip: { type: 'string' },+ version: { type: 'string' },+ tag: { type: 'string' },+ arch: { type: 'string' },+ },+ })+ const receipt = materializeFeed({+ outDir: values.out,+ zipPath: values.zip,+ version: values.version,+ tag: values.tag,+ arch: values.arch,+ releaseDate: new Date().toISOString(),+ })+ console.log(JSON.stringify(receipt, null, 2))+}diff --git a/tests/install/e2e-assets/mac-bundled-manifest.cjs b/tests/install/e2e-assets/mac-bundled-manifest.cjsnew file mode 100644index 00000000000..1172a341e03--- /dev/null+++ b/tests/install/e2e-assets/mac-bundled-manifest.cjs@@ -0,0 +1,128 @@+'use strict'+// mac-bundled-manifest.cjs — pure validation/assertion helpers for the+// macOS packaged-app -> open-app-update E2E arm+// (tests/install/macos-bundled-e2e.sh). No dependencies, no side effects:+// everything here is requireable from vitest (tests-js) and from the+// driver's node invocations on the macOS runner.+//+// The bundle manifest itself is resolved by the PARENT-owned common+// resolver: tests/install/e2e-assets/bundle-inputs.mjs+// --manifest-url URL --platform macos --arch arm64|x64 --out WORKROOT+// which validates remote bytes (commits, versions, sha256) and writes+// WORKROOT/bundle-inputs.json with old/new.artifact.path added (local+// downloaded artifact). This module only asserts the normalized result.++const ARCHES = ['arm64', 'x64']+const SHA256_RE = /^[0-9a-f]{64}$/+// stable tags: vX.Y.Z; canary: vX.Y.Z-canary.YYYYMMDDHHMMSS+const TAG_RE = /^v\d+\.\d+\.\d+(?:-canary\.20\d{6}(?:\d{6})?)?$/++function validateSide(side, label) {+ if (!side || typeof side !== 'object') {+ throw new Error(`${label}: missing side object`)+ }+ for (const key of ['tag', 'version', 'commit', 'identity']) {+ if (typeof side[key] !== 'string' || !side[key]) {+ throw new Error(`${label}.${key}: expected a non-empty string`)+ }+ }+ if (!TAG_RE.test(side.tag)) {+ throw new Error(`${label}.tag: ${JSON.stringify(side.tag)} is not a release tag`)+ }+ if (side.version !== side.tag.slice(1)) {+ throw new Error(`${label}: version ${side.version} does not match tag ${side.tag}`)+ }+ if (!/^[0-9a-f]{40}$/.test(side.commit)) {+ throw new Error(`${label}.commit: expected a 40-hex SHA, got ${JSON.stringify(side.commit)}`)+ }+ const artifact = side.artifact+ if (!artifact || typeof artifact !== 'object') {+ throw new Error(`${label}.artifact: missing object`)+ }+ if (typeof artifact.url !== 'string' || !artifact.url) {+ throw new Error(`${label}.artifact.url: expected a non-empty string`)+ }+ if (typeof artifact.path !== 'string' || !artifact.path) {+ throw new Error(`${label}.artifact.path: missing; the parent resolver must download the artifact first`)+ }+ if (!SHA256_RE.test(String(artifact.sha256 || '').toLowerCase())) {+ throw new Error(`${label}.artifact.sha256: expected 64 hex chars`)+ }+}++/**+ * Validate the normalized bundle-inputs.json for this arm.+ * @param {{schema?: unknown, platform?: unknown, arch?: unknown,+ * old?: unknown, new?: unknown}} manifest+ * @param {{platform: 'macos', arch: 'arm64'|'x64'}} want+ */+function validateBundleManifest(manifest, want) {+ if (!manifest || typeof manifest !== 'object') {+ throw new Error('bundle-inputs.json: not an object')+ }+ if (manifest.schema !== 1) {+ throw new Error(`bundle-inputs.json: unsupported schema ${JSON.stringify(manifest.schema)}`)+ }+ if (manifest.platform !== want.platform) {+ throw new Error(`bundle-inputs.json: platform ${JSON.stringify(manifest.platform)} != ${want.platform}`)+ }+ if (!ARCHES.includes(want.arch)) {+ throw new Error(`arch: ${JSON.stringify(want.arch)} is not one of ${ARCHES.join('|')}`)+ }+ if (manifest.arch !== want.arch) {+ throw new Error(`bundle-inputs.json: arch ${JSON.stringify(manifest.arch)} != ${want.arch}`)+ }+ validateSide(manifest.old, 'old')+ validateSide(manifest.new, 'new')+ if (manifest.old.commit === manifest.new.commit) {+ throw new Error('old.commit == new.commit: no update would be available')+ }+ if (manifest.old.identity !== manifest.new.identity) {+ // Squirrel.Mac refuses an update whose code signature changes team.+ throw new Error(+ `old.identity ${manifest.old.identity} != new.identity ${manifest.new.identity}: ` ++ 'Squirrel.Mac would reject this pair (signature gate)')+ }+ return manifest+}++/** Parse the TeamIdentifier line out of `codesign -dv` output. */+function codesignTeam(codesignOutput) {+ const match = /TeamIdentifier=(?:not set|=)?\s*([A-Z0-9]+)/.exec(codesignOutput)+ return match ? match[1] : null+}++/** True when `codesign --verify` output reports a valid signature. */+function codesignValid(verifyOutput) {+ return /validated/.test(verifyOutput)+}++/**+ * Assertions for an installed bundle's install-stamp.json+ * (Contents/Resources/install-stamp.json) against a manifest side.+ * Mirrors apps/desktop/scripts/write-build-stamp.mjs's bundled shape.+ */+function stampAssertions(stamp, side) {+ const problems = []+ if (!stamp || typeof stamp !== 'object') {+ return ['install-stamp.json: not an object']+ }+ if (stamp.payload !== 'bundled') {+ problems.push(`stamp.payload ${JSON.stringify(stamp.payload)} != 'bundled'`)+ }+ if (stamp.updateMechanism !== 'electron-updater') {+ problems.push(`stamp.updateMechanism ${JSON.stringify(stamp.updateMechanism)} != 'electron-updater'`)+ }+ if (stamp.commit !== side.commit) {+ problems.push(`stamp.commit ${JSON.stringify(stamp.commit)} != ${side.commit}`)+ }+ if (stamp.tag !== side.tag) {+ problems.push(`stamp.tag ${JSON.stringify(stamp.tag)} != ${side.tag}`)+ }+ if (stamp.store === true) {+ problems.push('stamp.store must not be true for a release bundle')+ }+ return problems+}++module.exports = { ARCHES, validateBundleManifest, codesignTeam, codesignValid, stampAssertions }diff --git a/tests/install/e2e-assets/mac-bundled-relaunch-watch.cjs b/tests/install/e2e-assets/mac-bundled-relaunch-watch.cjsnew file mode 100644index 00000000000..1f4ace32efc--- /dev/null+++ b/tests/install/e2e-assets/mac-bundled-relaunch-watch.cjs@@ -0,0 +1,113 @@+#!/usr/bin/env node+'use strict'+// mac-bundled-relaunch-watch.cjs — the EXTERNAL relaunch witness for the+// macOS packaged-app -> open-app-update E2E arm.+//+// Runs as a detached process owned by the DRIVER'S SHELL (never a child of+// Playwright or of the app), so its proof survives Playwright teardown and+// the app's quit-and-install. It launches nothing: it only observes.+//+// Proof this process owns (everything else in the arm defers to it):+// 1. the OLD app process appeared under <app-bin> (pid + birth recorded),+// 2. that exact pid EXITED (Squirrel.Mac replaced it),+// 3. a NEW process appeared at the same executable path with a+// DIFFERENT pid and its own birth time — the automatic relaunch,+// observed without any driver action starting it.+//+// Output: --out JSON file with the observation record (rewritten as state+// advances); exit 0 on a full proof, 2 on timeout, 3 on usage error.++const { execFileSync } = require('node:child_process')+const fs = require('node:fs')++function usage(message) {+ console.error(message)+ console.error('usage: node mac-bundled-relaunch-watch.cjs --app-bin <path> --out <proof.json> ' ++ '[--timeout-ms 600000] [--poll-ms 1000] [--old-pid-file <path>] [--new-pid-file <path>]')+ process.exit(3)+}++const args = {}+for (let i = 2; i < process.argv.length; i += 2) {+ const key = process.argv[i]+ if (!key.startsWith('--')) usage(`unexpected argument: ${key}`)+ args[key.slice(2)] = process.argv[i + 1]+}+if (!args['app-bin'] || !args.out) usage('--app-bin and --out are required')+const timeoutMs = Number(args['timeout-ms'] || 600_000)+const pollMs = Number(args['poll-ms'] || 1_000)+if (!Number.isFinite(timeoutMs) || !Number.isFinite(pollMs)) usage('timeouts must be numbers')++const appBin = fs.realpathSync(args['app-bin'])+const record = { appBin, startedAt: new Date().toISOString(), oldPid: null, oldBirth: null, oldSeenAt: null, oldExitedAt: null, newPid: null, newBirth: null, newSeenAt: null }++function writeRecord() {+ fs.writeFileSync(args.out, JSON.stringify(record, null, 2) + '\n')+ if (args['old-pid-file'] && record.oldPid) {+ fs.writeFileSync(args['old-pid-file'], `${record.oldPid}\n`)+ }+ if (args['new-pid-file'] && record.newPid) {+ fs.writeFileSync(args['new-pid-file'], `${record.newPid}\n`)+ }+}++// One ps pass: pid, birth time, and the executable path. On macOS `comm`+// is the real executable path; Electron helpers carry their own paths and+// never match <app-bin>, so this sees only the main app process.+function psSnapshot() {+ const out = execFileSync('ps', ['-axo', 'pid=,lstart=,comm='], { encoding: 'utf8' })+ const rows = []+ for (const line of out.split('\n')) {+ const match = /^\s*(\d+)\s+(.+?)\s+((?:\/[^/]+)+)$/.exec(line)+ if (match) rows.push({ pid: Number(match[1]), birth: match[2].trim(), comm: match[3] })+ }+ return rows+}++let oldGoneSince = 0+const startedAt = Date.now()+const timer = setInterval(() => {+ if (Date.now() - startedAt > timeoutMs) {+ clearInterval(timer)+ writeRecord()+ console.error(JSON.stringify(record))+ process.exit(2)+ }+ let rows+ try {+ rows = psSnapshot()+ } catch {+ return // transient ps failure; keep polling+ }+ if (!record.oldPid) {+ const old = rows.find(row => row.comm === appBin)+ if (old) {+ record.oldPid = old.pid+ record.oldBirth = old.birth+ record.oldSeenAt = new Date().toISOString()+ writeRecord()+ }+ return+ }+ if (!record.oldExitedAt) {+ if (rows.some(row => row.pid === record.oldPid)) {+ oldGoneSince = 0+ } else if (!oldGoneSince) {+ oldGoneSince = Date.now() // one miss may be a ps hiccup; need two+ } else if (Date.now() - oldGoneSince > pollMs) {+ record.oldExitedAt = new Date().toISOString()+ writeRecord()+ }+ return+ }+ const next = rows.find(row => row.comm === appBin && row.pid !== record.oldPid)+ if (next) {+ record.newPid = next.pid+ record.newBirth = next.birth+ record.newSeenAt = new Date().toISOString()+ writeRecord()+ console.log(JSON.stringify(record))+ process.exit(0)+ }+}, pollMs)+writeRecord()diff --git a/tests/install/e2e-assets/mac-bundled-serve.mjs b/tests/install/e2e-assets/mac-bundled-serve.mjsnew file mode 100644index 00000000000..b028da89c3f--- /dev/null+++ b/tests/install/e2e-assets/mac-bundled-serve.mjs@@ -0,0 +1,61 @@+#!/usr/bin/env node+'use strict'+// mac-bundled-serve.mjs — loopback-only static file server for the macOS+// bundled-update E2E feed. Serves the directory produced by+// mac-bundled-feed.mjs over 127.0.0.1, logs every request to a JSONL file+// (the proof the app really fetched THIS feed), and stays up until killed.+//+// Usage: node mac-bundled-serve.mjs --dir <feed-dir> --port <port> \+// --log <requests.jsonl> [--health /__healthz]++import http from 'node:http'+import fs from 'node:fs'+import path from 'node:path'+import { parseArgs } from 'node:util'++const { values } = parseArgs({+ options: {+ dir: { type: 'string' },+ port: { type: 'string' },+ log: { type: 'string' },+ health: { type: 'string', default: '/__healthz' }+ }+})++const root = path.resolve(values.dir)+if (!fs.existsSync(root)) {+ console.error(`feed dir not found: ${root}`)+ process.exit(1)+}+const logStream = values.log ? fs.createWriteStream(values.log, { flags: 'a' }) : null++const server = http.createServer((req, res) => {+ const url = new URL(req.url, `http://127.0.0.1:${values.port}`)+ if (logStream) {+ logStream.write(JSON.stringify({ t: Date.now(), path: url.pathname, ua: req.headers['user-agent'] || '' }) + '\n')+ }+ if (url.pathname === values.health) {+ res.writeHead(200, { 'content-type': 'text/plain' })+ res.end('ok\n')+ return+ }+ const target = path.resolve(root, '.' + decodeURIComponent(url.pathname))+ if (!target.startsWith(root) || !fs.existsSync(target) || !fs.statSync(target).isFile()) {+ res.writeHead(404, { 'content-type': 'text/plain' })+ res.end('not found\n')+ return+ }+ // no-store: the updater must always see the live feed, never a cache.+ res.writeHead(200, {+ 'content-type': target.endsWith('.yml') ? 'text/yaml; charset=utf-8' : 'application/zip',+ 'content-length': fs.statSync(target).size,+ 'cache-control': 'no-store'+ })+ fs.createReadStream(target).pipe(res)+})++// Loopback only, by construction and by policy: the production updater+// accepts loopback HTTP overrides exclusively (mac-client.ts).+server.listen(Number(values.port), '127.0.0.1', () => {+ console.log(`serving ${root} on http://127.0.0.1:${values.port}`)+})diff --git a/tests/install/e2e-assets/mac-bundled-update-driver.mjs b/tests/install/e2e-assets/mac-bundled-update-driver.mjsnew file mode 100644index 00000000000..984a28f24e7--- /dev/null+++ b/tests/install/e2e-assets/mac-bundled-update-driver.mjs@@ -0,0 +1,193 @@+// @ts-check+// mac-bundled-update-driver.mjs — click the REAL in-app update flow on the+// macOS packaged app: launch the installed OLD bundle binary under+// Playwright, reach Settings -> About, click "Update now", and wait for the+// app process to close.+//+// What this driver deliberately does NOT do:+// - no internal apply call (no window.hermesDesktop.updates.apply or any+// bridge invocation that would bypass the user trigger);+// - no relaunch of the NEW app — Squirrel.Mac owns the swap and the+// relaunch, and the external watcher+// (mac-bundled-relaunch-watch.cjs) owns that proof;+// - no killing of anything. The process-close contract from+// process-close.cjs releases our stdio pipes instead of tree-killing,+// so ShipIt's detached relaunch of the NEW bundle survives our exit.+//+// Usage (from the scratch dir with the driver's own @playwright/test):+// node mac-bundled-update-driver.mjs --app-bin <.app/Contents/MacOS/Hermes> \+// --shots <dir> --close-timeout-ms 420000++import fs from 'node:fs';+import path from 'node:path';+import { parseArgs } from 'node:util';+import { _electron } from '@playwright/test';+import { createRequire } from 'node:module';++const require = createRequire(import.meta.url);+const { observeProcessClose } = require('./process-close.cjs');+const { prepareWindowForInput } = require('./window-input.cjs');++const { values } = parseArgs({+ options: {+ 'app-bin': { type: 'string' },+ shots: { type: 'string', default: '.' },+ 'close-timeout-ms': { type: 'string', default: '420000' },+ },+});++const log = message => console.log(`[mac-bundled-update] ${message}`);+const shot = async (page, name) => {+ try { await page.screenshot({ path: path.join(values.shots, `${name}.png`), fullPage: true }); } catch { /* window may be gone */ }+};++const appBin = values['app-bin'];+fs.mkdirSync(values.shots, { recursive: true });++log(`launching ${appBin}`);+const app = await _electron.launch({+ executablePath: appBin,+ // Inherit the driver env: HERMES_HOME / HOME / updates feed config must+ // reach the main process exactly as a user's double-click would.+ env: { ...process.env },+ timeout: 120_000,+});+const child = app.process();+const oldPid = child.pid;+log(`launched Electron pid=${oldPid}`);+fs.writeFileSync(path.join(values.shots, 'old-pid'), `${oldPid}\n`);++const waitForProcessClose = observeProcessClose(child);++await app.firstWindow({ timeout: 120_000 });+let page = null;+const windowDeadline = Date.now() + 120_000;+while (!page) {+ for (const candidate of app.windows()) {+ const hasUi = await candidate.evaluate(() => document.querySelector('button') !== null).catch(() => false);+ if (hasUi) { page = candidate; break; }+ }+ if (!page) {+ if (Date.now() > windowDeadline) throw new Error('no window with app UI (a <button>) appeared within 120s');+ await new Promise(r => setTimeout(r, 1_000));+ }+}+log(`window picked (url=${page.url()})`);++await prepareWindowForInput(app, page);++// Boot: the shell is mounted once the composer exists.+await page.waitForSelector('textarea, [contenteditable="true"]', { state: 'attached', timeout: 300_000 });+log('renderer booted (composer attached)');+await page.waitForTimeout(3_000);+await shot(page, '01-app-booted');++// Reach Settings through the onboarding overlay, if it shows. A click that+// LANDS is proof the overlay is gone (Playwright checks the hit target).+const clickFirstVisible = async (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 { /* state moved on; try the next */ }+ }+ if (Date.now() > deadline) return false;+ await page.waitForTimeout(500);+ }+};++const laterLocators = [+ p => p.getByRole('button', { name: /choose a provider later/i }),+ p => p.getByText(/choose a provider later/i),+ p => p.getByRole('button', { name: /skip/i }),+];+const settingsLocators = [+ 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' }),+];++let openedSettings = false;+const overlayDeadline = Date.now() + 180_000;+while (!openedSettings) {+ await prepareWindowForInput(app, page);+ for (const make of laterLocators) {+ try {+ await make(page).first().click({ timeout: 1_500 });+ log('dismissed onboarding overlay');+ await page.waitForTimeout(2_500);+ await shot(page, '01b-onboarding-dismissed');+ break;+ } catch { /* not up yet */ }+ }+ for (const make of settingsLocators) {+ try {+ await make(page).first().click({ timeout: 2_500 });+ openedSettings = true;+ log('clicked: Open settings');+ break;+ } catch { /* try again next pass */ }+ }+ if (!openedSettings && Date.now() > overlayDeadline) break;+}+if (!openedSettings) {+ await shot(page, 'ERROR-no-settings-button');+ throw new Error('could not find the Open settings control');+}+await page.waitForTimeout(1_500);+await shot(page, '02-settings-open');++if (!await clickFirstVisible([+ p => p.getByRole('tab', { name: 'About' }),+ p => p.getByRole('button', { name: 'About' }),+ p => p.getByText('About', { exact: true }),+], 'About section', 30_000)) {+ await shot(page, 'ERROR-no-about-tab');+ throw new Error('could not find the About section in Settings');+}+await page.waitForTimeout(1_500);+await shot(page, '03-about-panel');++// Wait for "Update now" (the loopback feed reports NEW as available). If+// the boot check has not landed yet, press "Check now" like a 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 — nudging Check now');+ const deadline = Date.now() + 180_000;+ while (!visible && Date.now() < deadline) {+ await page.getByRole('button', { name: 'Check now' }).first()+ .click({ timeout: 5_000 })+ .then(() => log('nudged Check now'))+ .catch(() => {});+ await page.waitForTimeout(15_000);+ visible = await updateNow.isVisible().catch(() => false);+ }+}+if (!visible) {+ await shot(page, 'ERROR-no-update-now');+ throw new Error('"Update now" never appeared — the loopback feed check did not report an update');+}+await shot(page, '04-update-available');++// ── The click under test ────────────────────────────────────────────────+await updateNow.click();+log('clicked: Update now');+await new Promise(resolve => setTimeout(resolve, 1_200));+await shot(page, '05-updating-overlay');++// The MacStrategy signs off with quitAndInstall: the app quits and+// Squirrel.Mac swaps the bundle and relaunches. Wait for the native close+// (never the renderer's close event) and exit WITHOUT killing anything —+// observeProcessClose released our pipes, so ShipIt's relaunch survives.+await waitForProcessClose(Number(values['close-timeout-ms']));+log('old Electron process closed — Squirrel.Mac owns the swap and relaunch');+fs.writeFileSync(path.join(values.shots, 'old-exited'), new Date().toISOString() + '\n');+process.exit(0);diff --git a/tests/install/e2e-assets/mac-bundled-verify.mjs b/tests/install/e2e-assets/mac-bundled-verify.mjsnew file mode 100644index 00000000000..0a51e8519a1--- /dev/null+++ b/tests/install/e2e-assets/mac-bundled-verify.mjs@@ -0,0 +1,104 @@+#!/usr/bin/env node+'use strict'+// mac-bundled-verify.mjs — verify an INSTALLED macOS bundle on the runner:+// real codesign validation, team identity, bundle version, and the baked+// install stamp, against a manifest side from bundle-inputs.json. Parses+// success receipts — file existence is never success.+//+// macOS-only (codesign/plutil). Pure assertion logic lives in+// mac-bundled-manifest.cjs and is covered by tests-js.+//+// Usage:+// node mac-bundled-verify.mjs verify-app --app <path> \+// --expect-version 1.2.3 --expect-commit <sha> --expect-tag vX.Y.Z \+// --expect-identity <team-id> [--out <receipt.json>]++import { execFileSync } from 'node:child_process'+import fs from 'node:fs'+import path from 'node:path'+import { parseArgs } from 'node:util'+import { createRequire } from 'node:module'++const require = createRequire(import.meta.url)+const { codesignTeam, codesignValid, stampAssertions } = require('./mac-bundled-manifest.cjs')++const [, , command, ...rest] = process.argv++function fail(message) {+ console.error(`E2E ASSERTION FAILED: ${message}`)+ process.exit(1)+}++function verifyApp() {+ const { values } = parseArgs({+ strict: false,+ args: rest,+ options: {+ app: { type: 'string' },+ 'expect-version': { type: 'string' },+ 'expect-commit': { type: 'string' },+ 'expect-tag': { type: 'string' },+ 'expect-identity': { type: 'string' },+ out: { type: 'string' },+ },+ })+ const app = values.app+ if (!app || !fs.existsSync(path.join(app, 'Contents', 'Info.plist'))) {+ fail(`not a .app bundle: ${app}`)+ }++ // 1. The signature is valid, intact, and satisfies its own designated+ // requirement — Squirrel's gate will re-run this at install time.+ try {+ execFileSync('codesign', ['--verify', '--deep', '--strict', '--verbose=2', app], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })+ } catch (error) {+ fail(`codesign --verify rejected ${app}: ${String(error.stderr || error)}`)+ }++ // 2. The signing team matches the manifest identity. Squirrel.Mac only+ // accepts an update signed by the SAME team — this assertion is what+ // makes the pair updatable at all.+ const displayOut = execFileSync('codesign', ['-dv', app], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })+ const team = codesignTeam(displayOut)+ if (!team) fail(`no TeamIdentifier in codesign -dv output for ${app}`)+ if (team !== values['expect-identity']) {+ fail(`codesign TeamIdentifier ${team} != manifest identity ${values['expect-identity']}`)+ }++ // 3. Bundle version and identifier from the real Info.plist.+ const plist = JSON.parse(execFileSync('plutil', ['-convert', 'json', '-o', '-', path.join(app, 'Contents', 'Info.plist')], { encoding: 'utf8' }))+ const receipt = {+ app,+ teamIdentifier: team,+ bundleVersion: plist.CFBundleShortVersionString,+ bundleIdentifier: plist.CFBundleIdentifier,+ verifiedAt: new Date().toISOString(),+ }+ if (receipt.bundleVersion !== values['expect-version']) {+ fail(`CFBundleShortVersionString ${receipt.bundleVersion} != expected ${values['expect-version']}`)+ }+ if (!String(receipt.bundleIdentifier).startsWith('com.nousresearch.')) {+ fail(`CFBundleIdentifier ${receipt.bundleIdentifier} is not a Hermes product bundle id`)+ }++ // 4. The baked install stamp (provenance: commit, tag, payload, mechanism).+ const stampPath = path.join(app, 'Contents', 'Resources', 'install-stamp.json')+ if (!fs.existsSync(stampPath)) fail(`no install stamp at ${stampPath}`)+ const stamp = JSON.parse(fs.readFileSync(stampPath, 'utf8'))+ receipt.stamp = stamp+ const problems = stampAssertions(stamp, {+ commit: values['expect-commit'],+ tag: values['expect-tag'],+ })+ if (problems.length) fail(`install stamp disagrees: ${problems.join('; ')}`)++ console.log(JSON.stringify(receipt, null, 2))+ if (values.out) fs.writeFileSync(values.out, JSON.stringify(receipt, null, 2) + '\n')+}++switch (command) {+ case 'verify-app': verifyApp(); break+ default:+ console.error(`unknown command: ${command}`)+ process.exit(3)+}diff --git a/tests/install/macos-bundled-e2e.sh b/tests/install/macos-bundled-e2e.shnew file mode 100644index 00000000000..cd52caacadc--- /dev/null+++ b/tests/install/macos-bundled-e2e.sh@@ -0,0 +1,336 @@+#!/usr/bin/env bash+# Prove the macOS packaged-app update route: a user on a REAL signed OLD+# bundle, installed in an isolated location, clicks About -> "Update now"+# and Squirrel.Mac swaps in a REAL signed NEW bundle and relaunches it —+# with no driver help and no source artifacts anywhere.+#+# Sibling of tests/install/macos-desktop-e2e.sh (the dmg/source arm). This+# arm has NO git redirect, NO staging, NO patching or re-signing: both+# bundles are the actual release zips resolved by the PARENT-owned common+# manifest resolver (tests/install/e2e-assets/bundle-inputs.mjs), which+# validates commits, versions and sha256 and downloads the artifacts.+#+# Phases (state shared via the workroot):+# install resolve the bundle manifest, verify artifact sha256, unzip the+# REAL signed OLD zip into an isolated .app location, verify+# codesign / team identity / version / stamp, seed isolated user+# state + plugin fixtures+# update build the loopback static feed from the REAL signed NEW zip in+# the production update-feed contract, configure+# updates.desktop_feed_base_url, start the external relaunch+# watcher, click the real About -> "Update now" under Playwright,+# then verify the automatic relaunch (new pid/birth/path), the+# NEW bundle's codesign/version/stamp, backend health, plugin+# and user-state survival+#+# Usage:+# tests/install/macos-bundled-e2e.sh --phase install|update|all+# --manifest-url URL --arch arm64|x64+#+# CI-only native guard: macOS host + GITHUB_ACTIONS. Nothing here writes to+# a public feed, dispatches a release, or drives a local GUI outside the+# runner session.++set -euo pipefail++PHASE="all"+MANIFEST_URL=""+ARCH="arm64"+PLAYWRIGHT_VERSION="1.58.2"+UPDATE_WATCH_TIMEOUT_MS=900000++while [ "$#" -gt 0 ]; do+ case "$1" in+ --phase)+ [ "$#" -ge 2 ] || { echo 'error: --phase needs a value' >&2; exit 1; }+ PHASE="$2"; shift 2 ;;+ --manifest-url)+ [ "$#" -ge 2 ] || { echo 'error: --manifest-url needs a value' >&2; exit 1; }+ MANIFEST_URL="$2"; shift 2 ;;+ --arch)+ [ "$#" -ge 2 ] || { echo 'error: --arch needs a value' >&2; exit 1; }+ ARCH="$2"; shift 2 ;;+ -h|--help) sed -n '2,30p' "$0"; exit 0 ;;+ *) echo "error: unknown argument: $1" >&2; exit 1 ;;+ esac+done+case "$ARCH" in arm64|x64) ;; *) echo "error: --arch must be arm64 or x64" >&2; exit 1 ;; esac++# Native CI-only guard: this leg runs real signed bundles, real codesign+# and real Squirrel.Mac, so it is meaningful only on a macOS CI runner.+[ "$(uname -s)" = "Darwin" ] || { echo "error: this driver runs on macOS only" >&2; exit 1; }+[ -n "${GITHUB_ACTIONS:-}" ] || { echo "error: this driver is CI-only (GITHUB_ACTIONS required)" >&2; exit 1; }++REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"+ASSETS="$REPO_ROOT/tests/install/e2e-assets"+export TS_BASE=$SECONDS++WORK_ROOT="${HERMES_E2E_WORKROOT:-${RUNNER_TEMP:-${TMPDIR:-/tmp}}/hermes-bundled-e2e}"+LOG_DIR="${HERMES_E2E_LOG_DIR:-$WORK_ROOT/logs}"+export HOME_SANDBOX="$WORK_ROOT/home"+export HERMES_HOME="$HOME_SANDBOX/.hermes"++step() { printf '\n=== %s ===\n' "$*"; }+ok() { printf ' OK %s\n' "$*"; }+fail() { printf 'E2E ASSERTION FAILED: %s\n' "$*" >&2; exit 1; }+# shellcheck source=../e2e-assets/ts-prefix.sh+source "$(dirname "$0")/e2e-assets/ts-prefix.sh" 2>/dev/null || ts_prefix() { cat; }+# shellcheck source=../e2e-assets/preserve-plugins.sh+source "$(dirname "$0")/e2e-assets/preserve-plugins.sh"+log_group() {+ printf '::group::%s\n' "$1"+ cat "$2"+ printf '::endgroup::\n'+}++MANIFEST="$WORK_ROOT/bundle-inputs.json"+OLD_APP="$WORK_ROOT/apps/Hermes.app"+OLD_APP_BIN="$OLD_APP/Contents/MacOS/Hermes"+FEED_DIR="$WORK_ROOT/feed"+FEED_PORT="${HERMES_E2E_FEED_PORT:-8791}"+FEED_URL="http://127.0.0.1:$FEED_PORT"+CONFIG_FEED_LINE=" desktop_feed_base_url: $FEED_URL"++export E2E_ARCH="$ARCH"++manifest_side() { # $1: old|new, $2: field+ node -e '+ const fs = require("node:fs")+ const m = JSON.parse(fs.readFileSync(process.argv[1], "utf8"))+ const side = m[process.argv[2]]+ console.log(process.argv[3] === "artifact" ? side.artifact.path : side[process.argv[3]])+ ' "$MANIFEST" "$1" "$2"+}++require_manifest() {+ [ -f "$MANIFEST" ] || fail "no bundle manifest at $MANIFEST — run the install phase first"+ # Validate the parent resolver's output shape for this arm (schema 1,+ # platform macos, this arch, real paths present, old != new, same team).+ node -e '+ const fs = require("node:fs")+ const { validateBundleManifest } = require(process.argv[2])+ const m = JSON.parse(fs.readFileSync(process.argv[1], "utf8"))+ validateBundleManifest(m, { platform: "macos", arch: process.env.E2E_ARCH })+ console.log("bundle manifest valid: " + m.old.tag + " -> " + m.new.tag)+ ' "$MANIFEST" "$ASSETS/mac-bundled-manifest.cjs"+}++phase_install() {+ require_manifest+ local old_tag old_version old_commit old_identity old_zip+ old_tag="$(manifest_side old tag)"; old_version="$(manifest_side old version)"+ old_commit="$(manifest_side old commit)"; old_identity="$(manifest_side old identity)"+ old_zip="$(manifest_side old artifact)"+ step "installing OLD bundle $old_tag ($old_version, team $old_identity)"++ # Artifact bytes: the parent resolver verified the remote sha256; we+ # re-verify the local file so the unzipped bundle provably IS the release.+ local got+ got="$(shasum -a 256 "$old_zip" | awk '{print $1}')"+ local want+ want="$(node -e 'const m=require(process.argv[1]); console.log(m.old.artifact.sha256.toLowerCase())' "$MANIFEST")"+ [ "$got" = "$want" ] || fail "OLD zip sha256 $got != manifest $want"+ ok "OLD zip sha256 verified"++ # Install into an ISOLATED .app location (not /Applications): unzip the+ # real release zip. No patching, no re-signing, no fakes.+ rm -rf "$WORK_ROOT/apps" "$WORK_ROOT/install-old"+ mkdir -p "$WORK_ROOT/install-old" "$WORK_ROOT/apps"+ unzip -q "$old_zip" -d "$WORK_ROOT/install-old"+ local found+ found="$(find "$WORK_ROOT/install-old" -maxdepth 2 -name '*.app' -type d | head -1)"+ [ -n "$found" ] || fail "no .app inside the OLD release zip"+ mv "$found" "$OLD_APP"+ # curl/unzip'd files carry no quarantine attr, but belt and braces.+ xattr -dr com.apple.quarantine "$OLD_APP" 2>/dev/null || true+ [ -x "$OLD_APP_BIN" ] || fail "no executable at $OLD_APP_BIN"+ ok "OLD bundle installed at $OLD_APP"++ node "$ASSETS/mac-bundled-verify.mjs" verify-app \+ --app "$OLD_APP" \+ --expect-version "$old_version" \+ --expect-commit "$old_commit" \+ --expect-tag "$old_tag" \+ --expect-identity "$old_identity" \+ --out "$LOG_DIR/old-bundle-verify.json" 2>&1 | ts_prefix | tee "$LOG_DIR/old-bundle-verify.log"+ ok "OLD bundle: codesign, team, version and stamp all match the manifest"++ # Isolated user state: a private HOME/HERMES_HOME plus one profile marker+ # file the update must leave untouched.+ mkdir -p "$HERMES_HOME"+ printf 'user_state_marker=%s\n' "$old_commit" > "$HERMES_HOME/desktop-bundled-marker.txt"+ ok "isolated user state seeded at $HERMES_HOME"+}++ensure_playwright() {+ local pw_dir="$WORK_ROOT/playwright"+ [ -d "$pw_dir/node_modules/@playwright/test" ] && { printf '%s' "$pw_dir"; return 0; }+ mkdir -p "$pw_dir"+ (cd "$pw_dir" && npm install --no-save --no-audit --no-fund \+ "@playwright/test@$PLAYWRIGHT_VERSION" 2>&1 | ts_prefix > "$LOG_DIR/playwright-install.log") \+ || { log_group "playwright install transcript" "$LOG_DIR/playwright-install.log"; fail "playwright install failed"; }+ printf '%s' "$pw_dir"+}++phase_update() {+ require_manifest+ local new_tag new_version new_commit new_identity new_zip+ new_tag="$(manifest_side new tag)"; new_version="$(manifest_side new version)"+ new_commit="$(manifest_side new commit)"; new_identity="$(manifest_side new identity)"+ new_zip="$(manifest_side new artifact)"++ # Snapshot + seed plugin fixtures BEFORE anything moves (shared owner).+ preserve_before_upgrade++ # The app must boot configured or the onboarding overlay (a fullscreen+ # div) eats every click: configure the mock inference server exactly like+ # the dev:mock flow does (shared owner: mock-provider.sh). It writes+ # $HERMES_HOME/config.yaml; the feed base URL below is appended after.+ # shellcheck source=../e2e-assets/mock-provider.sh+ source "$ASSETS/mock-provider.sh"+ mock_start "$WORK_ROOT"++ # ── the controlled loopback feed ──────────────────────────────────────+ step "building the loopback feed from the REAL NEW signed zip"+ local got want+ got="$(shasum -a 256 "$new_zip" | awk '{print $1}')"+ want="$(node -e 'const m=require(process.argv[1]); console.log(m.new.artifact.sha256.toLowerCase())' "$MANIFEST")"+ [ "$got" = "$want" ] || fail "NEW zip sha256 $got != manifest $want"+ rm -rf "$FEED_DIR"+ node "$ASSETS/mac-bundled-feed.mjs" \+ --out "$FEED_DIR" --zip "$new_zip" \+ --version "$new_version" --tag "$new_tag" --arch "$ARCH" \+ 2>&1 | ts_prefix | tee "$LOG_DIR/feed-build.json"+ ok "feed materialized at $FEED_DIR"++ local serve_pid+ node "$ASSETS/mac-bundled-serve.mjs" --dir "$FEED_DIR" --port "$FEED_PORT" \+ --log "$LOG_DIR/feed-requests.jsonl" > "$LOG_DIR/feed-server.log" 2>&1 &+ serve_pid=$!+ trap 'mock_stop 2>/dev/null || true; kill "$serve_pid" 2>/dev/null || true' EXIT+ for _ in 1 2 3 4 5 6 7 8 9 10; do+ curl -fsS "$FEED_URL/__healthz" >/dev/null 2>&1 && break+ sleep 0.3+ done+ curl -fsS "$FEED_URL/__healthz" >/dev/null 2>&1 || fail "loopback feed server did not come up on $FEED_URL"+ ok "loopback feed serving on $FEED_URL"++ # ── configure the app like a user: config.yaml ────────────────────────+ # The production resolution order is config updates.desktop_feed_base_url+ # first (main.ts resolveDesktopFeedBaseUrl). Loopback HTTP is the one+ # non-HTTPS override the production client accepts (mac-client.ts).+ step "configuring updates.desktop_feed_base_url in the isolated config"+ grep -q '^updates:' "$HERMES_HOME/config.yaml" 2>/dev/null || printf '\nupdates:\n' >> "$HERMES_HOME/config.yaml"+ grep -qF "$CONFIG_FEED_LINE" "$HERMES_HOME/config.yaml" || printf '%s\n' "$CONFIG_FEED_LINE" >> "$HERMES_HOME/config.yaml"+ cat "$HERMES_HOME/config.yaml" | ts_prefix | tee "$LOG_DIR/config.yaml"+ ok "feed base URL configured: $FEED_URL"++ # ── the external relaunch watcher ─────────────────────────────────────+ # Started by THIS shell, detached from Playwright and from the app. It+ # owns the automatic-relaunch proof end to end.+ step "starting the external relaunch watcher"+ node "$ASSETS/mac-bundled-relaunch-watch.cjs" \+ --app-bin "$OLD_APP_BIN" \+ --out "$LOG_DIR/relaunch-proof.json" \+ --old-pid-file "$LOG_DIR/old-pid" \+ --new-pid-file "$LOG_DIR/new-pid" \+ --timeout-ms "$UPDATE_WATCH_TIMEOUT_MS" > "$LOG_DIR/relaunch-watch.log" 2>&1 &+ local watcher_pid=$!+ ok "watcher running (pid $watcher_pid)"++ # ── the real user trigger ─────────────────────────────────────────────+ step "launching the OLD app and clicking About -> Update now"+ local pw_dir+ pw_dir="$(ensure_playwright)"+ cp "$ASSETS/mac-bundled-update-driver.mjs" \+ "$ASSETS/process-close.cjs" \+ "$ASSETS/window-input.cjs" \+ "$pw_dir/"+ local rc=0+ (cd "$pw_dir" && node mac-bundled-update-driver.mjs \+ --app-bin "$OLD_APP_BIN" \+ --shots "$LOG_DIR/shots" \+ --close-timeout-ms 420000 2>&1 | ts_prefix | tee "$LOG_DIR/app-update.log") || rc=$?+ log_group "in-app update (Playwright) transcript" "$LOG_DIR/app-update.log"+ [ "$rc" -eq 0 ] || fail "in-app update driver exited $rc; transcript above"++ step "waiting for Squirrel.Mac to swap and relaunch (watcher owns the proof)"+ if ! wait "$watcher_pid"; then+ cat "$LOG_DIR/relaunch-proof.json" 2>/dev/null | ts_prefix || true+ fail "relaunch watcher did not observe the automatic relaunch within ${UPDATE_WATCH_TIMEOUT_MS}ms"+ fi+ log_group "relaunch watcher record" "$LOG_DIR/relaunch-proof.json"++ local old_pid new_pid+ old_pid="$(cat "$LOG_DIR/old-pid")"+ new_pid="$(cat "$LOG_DIR/new-pid")"+ [ "$old_pid" != "$new_pid" ] || fail "relaunch proof shows the SAME pid ($new_pid); no replacement happened"+ node -e '+ const r = require(process.argv[1])+ if (r.newBirth && r.oldBirth && r.newBirth === r.oldBirth) process.exit(1)+ ' "$LOG_DIR/relaunch-proof.json" || fail "old and new processes report the same birth time"+ # The relaunch must be at the SAME installed path: Squirrel replaces the+ # bundle in place; a different path would mean something else started it.+ node -e '+ const r = require(process.argv[1])+ if (!r.oldPid || !r.newPid || !r.oldExitedAt || !r.newSeenAt) process.exit(1)+ ' "$LOG_DIR/relaunch-proof.json" || fail "incomplete relaunch proof record"+ ok "automatic relaunch: old pid $old_pid exited, new pid $new_pid at $OLD_APP_BIN (no driver launch)"++ # ── the NEW bundle in place ───────────────────────────────────────────+ step "verifying the NEW bundle Squirrel installed"+ node "$ASSETS/mac-bundled-verify.mjs" verify-app \+ --app "$OLD_APP" \+ --expect-version "$new_version" \+ --expect-commit "$new_commit" \+ --expect-tag "$new_tag" \+ --expect-identity "$new_identity" \+ --out "$LOG_DIR/new-bundle-verify.json" 2>&1 | ts_prefix | tee "$LOG_DIR/new-bundle-verify.log"+ ok "NEW bundle: codesign, team ($new_identity), version $new_version, stamp commit $new_commit"++ # ── old processes are gone, new backend healthy ───────────────────────+ if pgrep -f "$OLD_APP_BIN" | grep -qvw "$new_pid"; then+ fail "old bundle processes still running after the update"+ fi+ ok "no stale bundle processes"++ step "probing the relaunched app's backend health"+ local backend_pid backend_port health+ backend_pid="$(ps -axo pid=,ppid=,command= | awk -v p="$new_pid" '$2==p && /serve/ && /hermes/ {print $1; exit}')"+ if [ -n "$backend_pid" ]; then+ backend_port="$(lsof -nP -a -p "$backend_pid" -iTCP -sTCP:LISTEN | awk 'NR>1{sub(".*:","",$9); print $9; exit}')"+ fi+ if [ -z "${backend_port:-}" ]; then+ # Fallback: the newest listening 127.0.0.1 port owned by any descendant+ # of the relaunched app (helper wrappers can reparent the backend).+ backend_port="$(lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null | awk '/127\.0\.0\.1/ {print $1, $2, $9}' \+ | while read -r _ pid addr; do+ if ps -o ppid= -p "$pid" 2>/dev/null | grep -qw "$new_pid" || [ "$pid" = "$new_pid" ]; then+ printf '%s\n' "${addr##*:}"; break+ fi+ done)"+ fi+ [ -n "$backend_port" ] || fail "could not discover the relaunched backend's listening port"+ for _ in $(seq 1 30); do+ health="$(curl -fsS "http://127.0.0.1:$backend_port/api/health" 2>/dev/null)" && break+ sleep 2+ done+ [ -n "${health:-}" ] || fail "backend /api/health never answered on 127.0.0.1:$backend_port"+ printf '%s\n' "$health" | ts_prefix | tee "$LOG_DIR/backend-health.json"+ ok "backend healthy on 127.0.0.1:$backend_port"++ # ── user state survived ───────────────────────────────────────────────+ preserve_after_upgrade+ grep -qF "user_state_marker=$(manifest_side old commit)" "$HERMES_HOME/desktop-bundled-marker.txt" \+ || fail "isolated user-state marker did not survive the update"+ ok "isolated user state survived"++ step "PASS: packaged $old_tag -> $new_version via the real About -> Update now route"+}++case "$PHASE" in+ install) phase_install ;;+ update) phase_update ;;+ all) phase_install; phase_update ;;+ *) echo "error: --phase must be install, update or all" >&2; exit 1 ;;+esac