The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: consolidate installer acceptance contracts and drivers
ethernet3f521a02e9c9
diff --git a/tests-js/bundle-inputs.test.mjs b/tests-js/bundle-inputs.test.mjsindex 7c20ee3b1e5..92ddf044986 100644--- a/tests-js/bundle-inputs.test.mjs+++ b/tests-js/bundle-inputs.test.mjs@@ -6,7 +6,9 @@ import os from 'node:os'import path from 'node:path'import { fileURLToPath } from 'node:url'import { afterEach, expect, test } from 'vitest'-import { stageBundleInputs, validateBundleInputs } from '../tests/install/e2e-assets/bundle-inputs.mjs'+import { stageBundleInputs } from '../tests/install/e2e-assets/bundle-inputs.mjs'+import { validateBundleInputs, validateDownloadedBundle } from '../tests/install/e2e-assets/bundle-manifest.cjs'+import { validateBundledManifest } from '../tests/install/e2e-assets/windows-bundled-helpers.mjs'import { bundledMatrix, renderMarkdownResults } from '../scripts/sandbox/generate-e2e-matrix.mjs'const cleanup = []@@ -28,18 +30,8 @@ test('package transitions are ordered, identity-preserving, and report through tfor (const platform of ['windows', 'macos']) {const manifest = fixture(platform)expect(validateBundleInputs(manifest, platform, 'x64')).toBe(manifest)- for (const change of [- value => { value.new.version = value.old.version },- value => { value.new.identity = 'other' },- value => { value.new.commit = 'not-a-commit' },- value => { value.new.artifact.sha256 = 'not-a-digest' },- value => { value.new.artifact.url = 'http://example.com/package.zip' },- value => { value.arch = 'arm64' }- ]) {- const bad = structuredClone(manifest)- change(bad)- expect(() => validateBundleInputs(bad, platform, 'x64')).toThrow()- }+ const arm = { ...manifest, arch: 'arm64' }+ expect(validateBundleInputs(arm, platform, 'arm64')).toBe(arm)const { include } = bundledMatrix(platform, manifest.old.tag)expect(include).toHaveLength(1)expect(include[0].update_method).toBe('open-app-update')@@ -47,10 +39,54 @@ test('package transitions are ordered, identity-preserving, and report through t}})-test('staging streams actual bytes, verifies hashes and removes rejected partial downloads', async () => {+// Independent fault inputs apply to remote admission and resumed phases alike.+test.each(['windows', 'macos'])('%s rejects malformed and incompatible pairs', platform => {+ const cases = [+ ['schema', 2, /schema/], ['platform', 'linux', /platform/], ['arch', 'riscv', /architecture/],+ ['new', null, /tag/], ['new.tag', 'main', /tag/], ['new.commit', 'not-a-commit', /commit/],+ ['new.identity', 4, /identity/], ['new.identity', 'other.bundle', /identity/],+ ['new.commit', 'a'.repeat(40), /commit/], ['new.artifact', null, /SHA-256/],+ ['new.artifact.sha256', ['b'.repeat(64)], /SHA-256/],+ ['new.artifact.sha256', 'A'.repeat(64), /SHA-256/], ['new.artifact.sha256', 'a'.repeat(64), /differ/],+ ['new.artifact.url', '', /url/], ['new.artifact.url', 'http://example.com/new.zip', /HTTPS/],+ ['new.artifact.url', 'https://user:[email protected]/new.zip', /credentials/],+ ['new.artifact.url', 'https://example.com/new.exe', /artifact/],+ ...(platform === 'windows' ? [+ ['new.version', '1.2.0.0', /increase/], ['new.version', '1.1.9.9', /increase/],+ ['new.version', '1.3.0', /four numeric/], ['new.version', '1.3.65536.0', /16 bits/],+ ['new.publisher', '', /publisher/], ['new.publisher', 'CN=Other', /publisher/],+ ['new.applicationId', 7, /applicationId/], ['new.applicationId', 'Other', /applicationId/],+ ] : [+ ['new.identity', 'TEAM123456', /CFBundleIdentifier/], ['new.version', '1.9.0', /match/],+ ['new.teamId', ['ABCDEFGHIJ'], /teamId/], ['new.teamId', '', /teamId/], ['new.teamId', 'OTHER12345', /signing team/],+ ]),+ ]+ for (const [field, value, diagnostic] of cases) {+ const bad = fixture(platform), keys = field.split('.')+ const last = keys.pop()+ keys.reduce((object, key) => object[key], bad)[last] = value+ expect(() => validateBundleInputs(bad, platform, 'x64'), field).toThrow(diagnostic)+ expect(() => validateDownloadedBundle(bad, platform, 'x64'), field).toThrow(diagnostic)+ }+ expect(() => validateBundleInputs(fixture(platform), platform, 'riscv')).toThrow('Unsupported')+ const pair = fixture(platform)+ if (platform === 'macos') {+ pair.new.tag = 'v1.3.0-canary.20260907000000'; pair.new.version = pair.new.tag.slice(1)+ expect(() => validateBundleInputs(pair, platform, 'x64')).toThrow('channel')+ pair.new.tag = pair.old.tag; pair.new.version = pair.old.version+ expect(() => validateBundleInputs(pair, platform, 'x64')).toThrow('increase')+ } else {+ for (const [old, newer] of [['1.2.3.9', '1.2.3.10'], ['1.2.65535.0', '1.3.0.0']]) {+ pair.old.version = old; pair.new.version = newer+ expect(validateBundleInputs(pair, platform, 'x64')).toBe(pair)+ }+ }+})++test.each(['windows', 'macos'])('%s staging and resumed validation use actual files and reject tampering', async platform => {// These bytes test download integrity only, not native package acceptance.const bytes = { old: Buffer.from('old transport payload'), new: Buffer.from('new transport payload') }- const manifest = fixture()+ const manifest = fixture(platform)const server = createServer((req, res) => {res.end(req.url === '/manifest.json' ? JSON.stringify(manifest) : bytes[req.url.slice(1).split('.')[0]])})@@ -60,18 +96,35 @@ test('staging streams actual bytes, verifies hashes and removes rejected partialcleanup.push(() => rm(directory, { recursive: true, force: true }))const base = `http://127.0.0.1:${server.address().port}`for (const slot of ['old', 'new']) {- manifest[slot].artifact.url = `${base}/${slot}.msixbundle`+ manifest[slot].artifact.url = `${base}/${slot}.${platform === 'windows' ? 'msixbundle' : 'zip'}`manifest[slot].artifact.sha256 = createHash('sha256').update(bytes[slot]).digest('hex')}const out = path.join(directory, 'good')const manifestSha256 = createHash('sha256').update(JSON.stringify(manifest)).digest('hex')- await expect(stageBundleInputs({ manifestUrl: `${base}/manifest.json`, platform: 'windows', arch: 'x64', out, manifestSha256: '0'.repeat(64) })).rejects.toThrow('manifest SHA-256')- const filename = await stageBundleInputs({ manifestUrl: `${base}/manifest.json`, platform: 'windows', arch: 'x64', out, manifestSha256 })+ await expect(stageBundleInputs({ manifestUrl: `${base}/manifest.json`, platform, arch: 'x64', out, manifestSha256: '0'.repeat(64) })).rejects.toThrow('manifest SHA-256')+ await expect(stageBundleInputs({ manifestUrl: `${base}/manifest.json`, platform, arch: 'x64', out, expectedCommit: 'c'.repeat(40) })).rejects.toThrow('workflow SHA')+ const filename = await stageBundleInputs({ manifestUrl: `${base}/manifest.json`, platform, arch: 'x64', out, manifestSha256 })const result = JSON.parse(await readFile(filename, 'utf8'))+ expect(validateDownloadedBundle(result, platform, 'x64')).toBe(result)+ if (platform === 'windows') {+ expect(validateBundledManifest(result, { expectedPublisher: 'CN=Test' })).toEqual({ ok: true, errors: [] })+ expect(validateBundledManifest(result, { expectedPublisher: 'CN=Other' }).errors.join()).toContain('OUT_OF_STORE_PUBLISHER')+ }+ // Native Mac resume uses require(), not an ESM-only import.+ const validator = fileURLToPath(new URL('../tests/install/e2e-assets/bundle-manifest.cjs', import.meta.url))+ execFileSync(process.execPath, ['-e', 'require(process.argv[1]).validateDownloadedBundle(require(process.argv[2]), process.argv[3], "x64")', validator, filename, platform])+ for (const missing of [undefined, path.join(directory, 'missing'), directory]) {+ const bad = structuredClone(result); bad.new.artifact.path = missing+ expect(() => validateDownloadedBundle(bad, platform, 'x64')).toThrow('artifact.path')+ if (platform === 'windows') expect(validateBundledManifest(bad, { expectedPublisher: 'CN=Test' }).ok).toBe(false)+ }+ const altered = structuredClone(result); altered.new.commit = altered.old.commit+ expect(() => validateDownloadedBundle(altered, platform, 'x64')).toThrow('commit')+ if (platform === 'windows') expect(validateBundledManifest(altered, { expectedPublisher: 'CN=Test' }).ok).toBe(false)for (const slot of ['old', 'new']) expect(await readFile(result[slot].artifact.path)).toEqual(bytes[slot])manifest.old.artifact.sha256 = 'c'.repeat(64)const bad = path.join(directory, 'bad')- await expect(stageBundleInputs({ manifestUrl: `${base}/manifest.json`, platform: 'windows', arch: 'x64', out: bad })).rejects.toThrow('SHA-256')+ await expect(stageBundleInputs({ manifestUrl: `${base}/manifest.json`, platform, arch: 'x64', out: bad })).rejects.toThrow('SHA-256')expect(await readdir(bad)).toEqual([])})diff --git a/tests-js/desktop-mac-usage-descriptions.test.ts b/tests-js/desktop-mac-usage-descriptions.test.tsindex e94a6c0fbf6..e7c0ab47643 100644--- a/tests-js/desktop-mac-usage-descriptions.test.ts+++ b/tests-js/desktop-mac-usage-descriptions.test.ts@@ -42,9 +42,6 @@* established that the right fix shape is: add the key + pin it in a test.* This file is the canonical test for that pattern at the Desktop layer.*- * When adding a new NS*UsageDescription key to `build.mac.extendInfo`, add a- * matching row to EXPECTED_USAGE_DESCRIPTIONS below. The drift-protection- * assertion at the bottom of this file will fail otherwise.*/import assert from 'node:assert/strict'@@ -216,25 +213,3 @@ test('every extendInfo value is free of leading/trailing whitespace and newlines)}})--test('every NS*UsageDescription in extendInfo is pinned in this test', () => {- const info = extendInfo()- const declaredKeys = new Set(EXPECTED_USAGE_DESCRIPTIONS.map((row) => row.key))-- // Non-privacy keys (CFBundleDisplayName etc.) are exempt — this test- // only governs NS*UsageDescription entries.- const privacyKeysInPlist = new Set(- Object.keys(info).filter(- (k) => k.startsWith('NS') && k.endsWith('UsageDescription')- )- )-- const missing = [...privacyKeysInPlist].filter((k) => !declaredKeys.has(k))- assert.deepEqual(- missing,- [],- `extendInfo declares privacy usage keys ${JSON.stringify(missing.sort())} ` +- 'that this test does not pin. Add them to EXPECTED_USAGE_DESCRIPTIONS ' +- 'with a reason, or remove them from the build config.'- )-})\ No newline at end of filediff --git a/tests-js/macos-bundled-helpers.test.mjs b/tests-js/macos-bundled-helpers.test.mjsindex 34e075712fd..964abb9d6ca 100644--- a/tests-js/macos-bundled-helpers.test.mjs+++ b/tests-js/macos-bundled-helpers.test.mjs@@ -1,221 +1,64 @@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,- channelFromTag,- 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: 'com.nousresearch.hermes-bundled',- teamId: 'TEAM123456',- 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 an explicit teamId on BOTH sides (10-char signing team)', () => {- expect(() => validateBundleManifest(manifest({ old: side({ teamId: undefined }) }), want)).toThrow(/teamId/)- expect(() => validateBundleManifest(manifest({ old: side({ teamId: 'tooshort' }) }), want)).toThrow(/teamId/)- expect(() => validateBundleManifest(manifest({ new: side({ teamId: 'OTHER99999', commit: 'c'.repeat(40) }) }), want)).toThrow(/Squirrel/)- })-- it('treats identity as the exact CFBundleIdentifier, not a namespace', () => {- expect(() => validateBundleManifest(manifest({ old: side({ identity: 'TEAM123456' }) }), want)).toThrow(/CFBundleIdentifier/)- expect(() => validateBundleManifest(manifest({ old: side({ identity: 'com.nousresearch.hermes-bundled' }) }), want)).not.toThrow()- expect(() => validateBundleManifest(- manifest({ new: side({ identity: 'com.nousresearch.hermes-other', tag: 'v0.29.0', version: '0.29.0', commit: 'c'.repeat(40), artifact: { url: 'u', sha256: 'd'.repeat(64), path: '/tmp/n' } }) }),- want,- )).toThrow(/same application bundle/)- })-- 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 channel-crossing pair', () => {- expect(() => validateBundleManifest(manifest({ new: side() }), want)).toThrow(/no update/)- expect(() => validateBundleManifest(- manifest({ new: side({ tag: 'v0.29.0-canary.20260907000000', version: '0.29.0-canary.20260907000000', commit: 'c'.repeat(40), artifact: { url: 'u', sha256: 'd'.repeat(64), path: '/tmp/n' } }) }),- want,- )).toThrow(/channel/)- })-})--describe('channelFromTag', () => {- it('maps canary tags to the canary channel, everything else to stable', () => {- expect(channelFromTag('v0.29.0-canary.20260907000000')).toBe('canary')- expect(channelFromTag('v0.29.0')).toBe('stable')- })-})--describe('codesignTeam', () => {- it('parses the team from codesign -dv STDERR output', () => {- const out = [- 'Executable=/tmp/Hermes Bundled.app/Contents/MacOS/Hermes Bundled',- 'Identifier=com.nousresearch.hermes-bundled',- 'TeamIdentifier=TEAM123456',- ].join('\n')- expect(codesignTeam(out)).toBe('TEAM123456')- })- it('returns null for unsigned / ad-hoc signatures', () => {- expect(codesignTeam('Identifier=com.x\nTeamIdentifier=not set')).toBeNull()- expect(codesignTeam('Identifier=com.x\nTeamIdentifier=')).toBeNull()- expect(codesignTeam('')).toBeNull()- })- it('never matches the word "not" as a team id', () => {- expect(codesignTeam('TeamIdentifier=not set\nFoo=not')).toBeNull()- })+import { createHash } from 'node:crypto'+import yaml from 'js-yaml'+import { afterEach, expect, test } from 'vitest'+import { codesignTeam, stampAssertions } from '../tests/install/e2e-assets/mac-bundled-manifest.cjs'+import { materializeFeed } from '../tests/install/e2e-assets/mac-bundled-feed.mjs'+import { safeJoin } from '../tests/install/e2e-assets/mac-bundled-serve.mjs'++const directories = []+afterEach(() => { for (const dir of directories.splice(0)) fs.rmSync(dir, { recursive: true, force: true }) })+function scratch() {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mac-feed-'))+ directories.push(dir)+ return dir+}++test('codesign stderr identifies the team but never blesses an unsigned/ad-hoc signature', () => {+ expect(codesignTeam('Identifier=com.x\nTeamIdentifier=TEAM123456')).toBe('TEAM123456')+ for (const output of ['', 'Identifier=com.x', 'TeamIdentifier=', 'TeamIdentifier=not set\nFoo=not', 'TeamIdentifier=-']) {+ expect(codesignTeam(output)).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',- distribution: 'desktop-app',- updateMechanism: 'electron-updater',- tag: 'v0.28.0',+test('installed stamp independently binds payload, mechanism, commit and tag', () => {+ const side = { commit: 'a'.repeat(40), tag: 'v0.28.0' }+ const good = { ...side, payload: 'bundled', updateMechanism: 'electron-updater' }+ expect(stampAssertions(good, side)).toEqual([])+ expect(stampAssertions(null, side)).toEqual(['install-stamp.json: not an object'])+ for (const [key, value] of [['payload', 'light'], ['updateMechanism', 'external'], ['commit', 'b'.repeat(40)], ['tag', null]]) {+ const problems = stampAssertions({ ...good, [key]: value }, side)+ expect(problems).toHaveLength(1)+ expect(problems[0]).toContain(`stamp.${key}`)}- 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, updateMechanism: 'external' }, sideArg).join(' ')).toMatch(/updateMechanism/)- })})-describe('mac-bundled-feed materializer', () => {- it('emits the production update-feed contract for the real NEW zip', async () => {- const { materializeFeed, feedFileNames, sha512Base64 } = 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', 'stable').prefixed).toBe('arm64-stable-mac.yml')- expect(feedFileNames('x64', 'stable').prefixed).toBe('stable-mac.yml')- expect(feedFileNames('arm64', 'canary').directory).toBe('releases/darwin/canary')- expect(feedFileNames('arm64', 'canary').prefixed).toBe('arm64-canary-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')- // The streamed hash matches a whole-buffer hash (streams, no full read).- expect(await sha512Base64(zip)).toBe(expectedSha512)-- const receipt = await materializeFeed({- outDir,- zipPath: zip,- version: '0.29.0',- tag: 'v0.29.0',- arch: 'arm64',- releaseDate: '2026-09-07T00:00:00.000Z',- })-- // The channel comes from the tag, never a hard-coded 'stable'.- expect(receipt.channel).toBe('stable')- 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)- })-- it('serves canary tags from the canary channel directory', async () => {- const { materializeFeed } = await import('../tests/install/e2e-assets/mac-bundled-feed.mjs')- const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mac-feed-canary-'))- const zip = path.join(outDir, 'HermesBundled-0.30.0-canary-mac-arm64.zip')- fs.writeFileSync(zip, 'canary zip')- const receipt = await materializeFeed({- outDir, zipPath: zip, version: '0.30.0',- tag: 'v0.30.0-canary.20260907000000', arch: 'x64',- releaseDate: '2026-09-07T00:00:00.000Z',+test.each([+ ['arm64', 'stable', 'v0.29.0', 'arm64-stable-mac.yml'],+ ['x64', 'canary', 'v0.30.0-canary.20260907000000', 'canary-mac.yml'],+])('%s %s feed binds parsed YAML to copied artifact bytes', async (arch, channel, tag, name) => {+ const outDir = scratch()+ const zip = path.join(outDir, 'payload.zip')+ const bytes = Buffer.from('transport fixture, not a signed native package')+ fs.writeFileSync(zip, bytes)+ const sha512 = createHash('sha512').update(bytes).digest('base64')+ const version = tag.slice(1), releaseDate = '2026-09-07T00:00:00.000Z'+ const receipt = await materializeFeed({ outDir, zipPath: zip, version, tag, arch, releaseDate })+ const directory = `releases/darwin/${channel}`, url = `/releases/tag/${tag}/payload.zip`+ expect(receipt).toMatchObject({ channel, feedKey: `${directory}/${name}`, artifactUrlPath: url, sha512 })+ expect(fs.readdirSync(path.join(outDir, directory)).sort()).toEqual([...new Set([name, `${channel}-mac.yml`])].sort())+ for (const filename of [name, `${channel}-mac.yml`]) {+ expect(yaml.load(fs.readFileSync(path.join(outDir, directory, filename), 'utf8'))).toEqual({+ version, files: [{ url, sha512, size: bytes.length }], path: url, sha512, releaseDate,})- expect(receipt.channel).toBe('canary')- expect(receipt.feedKey).toBe('releases/darwin/canary/canary-mac.yml')- expect(fs.existsSync(path.join(outDir, 'releases/darwin/canary/canary-mac.yml'))).toBe(true)- expect(fs.existsSync(path.join(outDir, 'releases/darwin/canary/arm64-canary-mac.yml'))).toBe(false)- })+ }+ expect(fs.readFileSync(path.join(outDir, url))).toEqual(bytes)})-describe('mac-bundled-serve path safety', () => {- it('resolves in-root paths and rejects traversal outside the feed root', async () => {- const { safeJoin } = await import('../tests/install/e2e-assets/mac-bundled-serve.mjs')- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mac-serve-'))- expect(safeJoin(root, '/releases/darwin/stable/stable-mac.yml'))- .toBe(path.join(root, 'releases/darwin/stable/stable-mac.yml'))- // Classic traversal: the old startsWith(root) check passed these.- expect(safeJoin(root, '/../escape.yml')).toBeNull()- expect(safeJoin(root, '/%2e%2e/escape.yml')).toBeNull()- expect(safeJoin(root, '/..%2fescape.yml')).toBeNull()- })+test('feed server rejects literal and encoded traversal', () => {+ const root = scratch()+ expect(safeJoin(root, '/releases/darwin/stable/stable-mac.yml')).toBe(path.join(root, 'releases/darwin/stable/stable-mac.yml'))+ for (const attack of ['/../escape.yml', '/%2e%2e/escape.yml', '/..%2fescape.yml']) expect(safeJoin(root, attack)).toBeNull()})diff --git a/tests-js/node-engine-alignment.test.ts b/tests-js/node-engine-alignment.test.tsindex a017990712e..0bbb00eb42e 100644--- a/tests-js/node-engine-alignment.test.ts+++ b/tests-js/node-engine-alignment.test.ts@@ -1,114 +1,55 @@import assert from 'node:assert/strict'import fs from 'node:fs'import path from 'node:path'+// semver ships no declarations in this lock; type the two library calls used here.+const semver: { valid(version: string): string | null; satisfies(version: string, range: string): boolean } = require('semver')+import { test } from 'vitest'-import { describe, test } from 'vitest'--const REPO_ROOT = path.resolve(__dirname, '..')--interface Manifest {- engines?: { node?: string }-}--interface Lockfile {- packages?: Record<string, Manifest>-}+interface Engines { node?: string; npm?: string }+interface Manifest { engines?: Engines }+interface Lockfile { packages: Record<string, Manifest> }+interface PmLock { packages: { node: { version: string }; npm: { version: string } } }function readJson<T>(relativePath: string): T {- return JSON.parse(fs.readFileSync(path.join(REPO_ROOT, relativePath), 'utf-8')) as T+ // SAFETY: these are repository-owned manifest/lock inputs, checked below.+ return JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', relativePath), 'utf8')) as T}+const root = readJson<Manifest>('package.json')+const desktop = readJson<Manifest>('apps/desktop/package.json')+const lock = readJson<Lockfile>('package-lock.json')+const pins = readJson<PmLock>('pm/lock.json').packages-function parseVersion(version: string): [number, number, number] {- const [major = 0, minor = 0, patch = 0] = version.split('-', 1)[0].split('.').map(Number)-- return [major, minor, patch]-}--function compare(left: string, right: string): number {- const have = parseVersion(left)- const want = parseVersion(right)-- for (let index = 0; index < have.length; index += 1) {- if (have[index] !== want[index]) {- return have[index] - want[index]- }- }-- return 0-}--function satisfiesClause(version: string, clause: string): boolean {- assert.match(clause, /^(?:\^|>=|<=|>|<|=)?\d+(?:\.\d+){0,2}$/, `unsupported semver clause: ${clause}`)-- if (clause.startsWith('^')) {- const bound = clause.slice(1)-- return parseVersion(version)[0] === parseVersion(bound)[0] && compare(version, bound) >= 0- }-- const match = clause.match(/^(>=|<=|>|<|=)?(.+)$/)- assert.ok(match)- const [, operator = '=', bound] = match- const result = compare(version, bound)-- return operator === '>='- ? result >= 0- : operator === '<='- ? result <= 0- : operator === '>'- ? result > 0- : operator === '<'- ? result < 0- : result === 0-}--function satisfiesRange(version: string, range: string): boolean {- const alternatives = range.split('||').map(alternative => alternative.trim().split(/\s+/))- alternatives.flat().forEach(clause => satisfiesClause(version, clause))-- return alternatives.some(clauses => clauses.every(clause => satisfiesClause(version, clause)))-}--const rootManifest = readJson<Manifest>('package.json')-const desktopManifest = readJson<Manifest>('apps/desktop/package.json')-const lockfile = readJson<Lockfile>('package-lock.json')--function nodeRange(manifest: Manifest, label: string): string {- assert.ok(manifest.engines?.node, `${label} must declare engines.node`)-+function nodeRange(manifest: Manifest): string {+ assert.ok(manifest.engines?.node, 'workspace must declare engines.node')return manifest.engines.node}-describe('Node engine alignment', () => {- const rootRange = nodeRange(rootManifest, 'root package.json')- const desktopRange = nodeRange(desktopManifest, 'apps/desktop/package.json')-- test.each(['22.22.0', '22.23.1', '24.11.0', '24.18.2', '26.0.0'])('all workspace manifests accept supported Node %s', version => {- assert.ok(satisfiesRange(version, rootRange))- assert.ok(satisfiesRange(version, desktopRange))- })-- test.each(['22.21.1', '23.0.0', '24.0.0', '24.10.9', '25.2.1'])(- 'all workspace manifests reject dependency-incompatible Node %s',- version => {- assert.ok(!satisfiesRange(version, rootRange))- assert.ok(!satisfiesRange(version, desktopRange))- }- )+test.each([+ ['22.22.0', true], ['22.23.1', true], ['24.11.0', true], ['24.18.2', true], ['26.0.0', true],+ ['22.21.1', false], ['23.0.0', false], ['24.0.0', false], ['24.10.9', false], ['25.2.1', false], ['26.0.0-rc.1', false],+] as const)('workspace Node policy for %s is %s', (version: string, accepted: boolean): void => {+ for (const manifest of [root, desktop]) assert.equal(semver.satisfies(version, nodeRange(manifest)), accepted)+})- test('lockfile workspace mirrors match their manifests', () => {- assert.equal(nodeRange(lockfile.packages?.[''] ?? {}, 'root lock entry'), rootRange)- assert.equal(nodeRange(lockfile.packages?.['apps/desktop'] ?? {}, 'desktop lock entry'), desktopRange)- })+test.each([+ ['10.9.8', true], ['11.9.9', true], ['11.10.0', false], ['11.12.1', false],+ ['11.16.9', false], ['11.17.0', true], ['12.0.2', true],+] as const)('npm age-exclusion policy for %s is %s', (version: string, accepted: boolean): void => {+ assert.ok(root.engines?.npm)+ assert.equal(semver.satisfies(version, root.engines.npm), accepted)+})- test.each(['~22.22.0', '22.x', '>=26.0.0-rc.1'])(- 'the alignment helper rejects unsupported semver clause %s instead of misclassifying it',- clause => {- assert.throws(() => satisfiesRange('26.0.0', clause), /unsupported semver clause/)+test('exact independently managed Node and npm satisfy all declared lockfile engines', (): void => {+ for (const tool of ['node', 'npm'] as const) assert.ok(semver.valid(pins[tool].version), `${tool} must be an exact pin`)+ for (const [name, manifest] of Object.entries({ ...lock.packages, root, desktop })) {+ for (const tool of ['node', 'npm'] as const) {+ const range = manifest.engines?.[tool]+ if (range) assert.ok(semver.satisfies(pins[tool].version, range), `${name}: pinned ${tool} ${pins[tool].version} violates ${range}`)}- )+ }+})- test('unsupported clauses are rejected even after a matching alternative', () => {- assert.throws(() => satisfiesRange('26.0.0', '>=26.0.0 || ~28.0.0'), /unsupported semver clause/)- })+test('lockfile workspace engine mirrors match their manifests', (): void => {+ assert.deepEqual(lock.packages[''].engines, root.engines)+ assert.deepEqual(lock.packages['apps/desktop'].engines, desktop.engines)})diff --git a/tests/install/e2e-assets/bundle-inputs.mjs b/tests/install/e2e-assets/bundle-inputs.mjsindex 8c867813d1f..a6ad9b3d350 100644--- a/tests/install/e2e-assets/bundle-inputs.mjs+++ b/tests/install/e2e-assets/bundle-inputs.mjs@@ -8,73 +8,7 @@ import { Transform, Readable } from 'node:stream'import { pipeline } from 'node:stream/promises'import { parseArgs } from 'node:util'import { pathToFileURL } from 'node:url'-import semver from 'semver'--const TAG = /^v\d+\.\d+\.\d+(?:-canary\.\d{14})?$/-const COMMIT = /^[0-9a-f]{40}$/-const SHA256 = /^[0-9a-f]{64}$/-const FORMATS = { windows: '.msixbundle', macos: '.zip' }--function artifactUrl(value) {- const url = new URL(value)- const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)- if (url.username || url.password || !(url.protocol === 'https:' || (url.protocol === 'http:' && local))) {- throw new Error('Bundle URLs must use HTTPS or loopback HTTP, without credentials')- }- return url-}--function windowsVersion(version) {- if (typeof version !== 'string' || !/^\d+\.\d+\.\d+\.\d+$/.test(version)) {- throw new Error('Windows package version must have four numeric components')- }- const parts = version.split('.').map(Number)- if (parts.some(n => n > 65535)) throw new Error('Windows package version exceeds 16 bits')- return parts-}--export function validateBundleInputs(value, platform, arch) {- if (!Object.hasOwn(FORMATS, platform) || !['x64', 'arm64'].includes(arch)) {- throw new Error('Unsupported bundled-update platform or architecture')- }- if (value?.schema !== 1 || value.platform !== platform || value.arch !== arch) {- throw new Error('Bundle manifest schema, platform or architecture mismatch')- }- for (const slot of ['old', 'new']) {- const item = value[slot]- if (!item || !TAG.test(item.tag) || !COMMIT.test(item.commit) || !item.identity) {- throw new Error(`${slot}: exact release tag, full commit and package identity are required`)- }- if (!item.artifact || !SHA256.test(item.artifact.sha256)) throw new Error(`${slot}: SHA-256 is required`)- const url = artifactUrl(item.artifact.url)- if (!url.pathname.endsWith(FORMATS[platform])) throw new Error(`${slot}: expected ${FORMATS[platform]} artifact`)- if (platform === 'windows') {- windowsVersion(item.version)- if (!item.publisher || !item.applicationId) throw new Error(`${slot}: publisher and applicationId are required`)- } else {- if (!semver.valid(item.version) || item.version !== item.tag.slice(1)) throw new Error(`${slot}: macOS version must match its release tag`)- if (!/^[A-Z0-9]{10}$/.test(item.teamId)) throw new Error(`${slot}: macOS signing teamId is required`)- }- }- if (value.old.identity !== value.new.identity || value.old.commit === value.new.commit) {- throw new Error('Update must preserve package identity and change the build commit')- }- if (value.old.artifact.sha256 === value.new.artifact.sha256) throw new Error('Update artifacts must differ')- if (platform === 'windows') {- if (value.old.publisher !== value.new.publisher || value.old.applicationId !== value.new.applicationId) {- throw new Error('Update must preserve publisher and applicationId')- }- const old = windowsVersion(value.old.version)- const newer = windowsVersion(value.new.version)- const first = newer.findIndex((n, i) => n !== old[i])- if (first < 0 || newer[first] <= old[first]) throw new Error('New package version must increase')- } else {- if (value.new.teamId !== value.old.teamId) throw new Error('Update must preserve signing team')- if (!semver.gt(value.new.version, value.old.version)) throw new Error('New package version must increase')- if (value.old.tag.includes('-canary.') !== value.new.tag.includes('-canary.')) throw new Error('Bundle transition must stay on one update channel')- }- return value-}+import { FORMATS, SHA256, artifactUrl, validateBundleInputs } from './bundle-manifest.cjs'export async function downloadArtifact(artifact, destination) {const url = artifactUrl(artifact.url)diff --git a/tests/install/e2e-assets/bundle-manifest.cjs b/tests/install/e2e-assets/bundle-manifest.cjsnew file mode 100644index 00000000000..3906ceaa0a3--- /dev/null+++ b/tests/install/e2e-assets/bundle-manifest.cjs@@ -0,0 +1,100 @@+// Shared admission for remote inputs and resumed native acceptance phases.+const fs = require('node:fs')+const semver = require('semver')++const TAG = /^v\d+\.\d+\.\d+(?:-canary\.\d{14})?$/+const COMMIT = /^[0-9a-f]{40}$/+const SHA256 = /^[0-9a-f]{64}$/+const FORMATS = { windows: '.msixbundle', macos: '.zip' }++function artifactUrl(value) {+ // SAFETY: this is the URL input boundary; reject JSON values before URL coercion.+ // eslint-disable-next-line anti-slop/no-runtime-typeof -- Decode untrusted manifest JSON at its input boundary.+ if (typeof value !== 'string' || !value) throw new Error('artifact.url must be a non-empty string')+ const url = new URL(value)+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)+ if (url.username || url.password || !(url.protocol === 'https:' || (url.protocol === 'http:' && local))) {+ throw new Error('Bundle URLs must use HTTPS or loopback HTTP, without credentials')+ }+ return url+}++function windowsVersion(version) {+ // SAFETY: version is untrusted manifest data, not an already typed domain value.+ // eslint-disable-next-line anti-slop/no-runtime-typeof -- Decode untrusted manifest JSON at its input boundary.+ if (typeof version !== 'string' || !/^\d+\.\d+\.\d+\.\d+$/.test(version)) {+ throw new Error('Windows package version must have four numeric components')+ }+ const parts = version.split('.').map(Number)+ if (parts.some(n => n > 65535)) throw new Error('Windows package version exceeds 16 bits')+ return parts+}++function validateSide(item, slot, platform) {+ // SAFETY: validate JSON fields before regexes can coerce objects or numbers.+ // eslint-disable-next-line anti-slop/no-runtime-typeof -- Decode untrusted manifest JSON at its input boundary.+ if (!item || ['tag', 'version', 'commit', 'identity'].some(key => typeof item[key] !== 'string' || !item[key]) ||+ !TAG.test(item.tag) || !COMMIT.test(item.commit)) {+ throw new Error(`${slot}: exact release tag, full commit and package identity are required`)+ }+ // eslint-disable-next-line anti-slop/no-runtime-typeof -- Decode the SHA-256 JSON string before regex coercion.+ if (!item.artifact || typeof item.artifact.sha256 !== 'string' || !SHA256.test(item.artifact.sha256)) throw new Error(`${slot}: SHA-256 is required`)+ const url = artifactUrl(item.artifact.url)+ if (!url.pathname.endsWith(FORMATS[platform])) throw new Error(`${slot}: expected ${FORMATS[platform]} artifact`)+ if (platform === 'windows') {+ windowsVersion(item.version)+ // SAFETY: publisher and applicationId are required string fields at admission.+ // eslint-disable-next-line anti-slop/no-runtime-typeof -- Decode untrusted manifest JSON at its input boundary.+ if (['publisher', 'applicationId'].some(key => typeof item[key] !== 'string' || !item[key])) throw new Error(`${slot}: publisher and applicationId are required`)+ } else {+ if (!/^[A-Za-z][A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/.test(item.identity)) throw new Error(`${slot}: identity must be a CFBundleIdentifier`)+ if (!semver.valid(item.version) || item.version !== item.tag.slice(1)) throw new Error(`${slot}: macOS version must match its release tag`)+ // SAFETY: teamId must be a JSON string, not an array coerced by RegExp.test.+ // eslint-disable-next-line anti-slop/no-runtime-typeof -- Decode untrusted manifest JSON at its input boundary.+ if (typeof item.teamId !== 'string' || !/^[A-Z0-9]{10}$/.test(item.teamId)) throw new Error(`${slot}: macOS signing teamId is required`)+ }+}++function validateBundleInputs(value, platform, arch) {+ if (!Object.hasOwn(FORMATS, platform) || !['x64', 'arm64'].includes(arch)) {+ throw new Error('Unsupported bundled-update platform or architecture')+ }+ if (value?.schema !== 1 || value.platform !== platform || value.arch !== arch) {+ throw new Error('Bundle manifest schema, platform or architecture mismatch')+ }+ for (const slot of ['old', 'new']) validateSide(value[slot], slot, platform)+ if (value.old.identity !== value.new.identity || value.old.commit === value.new.commit) {+ throw new Error('Update must preserve package identity and change the build commit')+ }+ if (value.old.artifact.sha256 === value.new.artifact.sha256) throw new Error('Update artifacts must differ')+ if (platform === 'windows') {+ if (value.old.publisher !== value.new.publisher || value.old.applicationId !== value.new.applicationId) {+ throw new Error('Update must preserve publisher and applicationId')+ }+ const old = windowsVersion(value.old.version)+ const newer = windowsVersion(value.new.version)+ const first = newer.findIndex((n, i) => n !== old[i])+ if (first < 0 || newer[first] <= old[first]) throw new Error('New package version must increase')+ } else {+ if (value.new.teamId !== value.old.teamId) throw new Error('Update must preserve signing team')+ if (!semver.gt(value.new.version, value.old.version)) throw new Error('New package version must increase')+ if (value.old.tag.includes('-canary.') !== value.new.tag.includes('-canary.')) throw new Error('Bundle transition must stay on one update channel')+ }+ return value+}++// Revalidate normalized JSON on every phase; staging is not a durable trust boundary.+function validateDownloadedBundle(value, platform, arch) {+ validateBundleInputs(value, platform, arch)+ for (const slot of ['old', 'new']) {+ const filename = value[slot].artifact.path+ // SAFETY: normalized JSON is re-read between phases; validate before filesystem access.+ // eslint-disable-next-line anti-slop/no-runtime-typeof -- Decode untrusted manifest JSON at its input boundary.+ if (typeof filename !== 'string' || !filename || !fs.statSync(filename, { throwIfNoEntry: false })?.isFile()) {+ throw new Error(`${slot}.artifact.path must name a downloaded file`)+ }+ }+ return value+}++module.exports = { FORMATS, SHA256, artifactUrl, validateBundleInputs, validateDownloadedBundle }diff --git a/tests/install/e2e-assets/bundle-plan.mjs b/tests/install/e2e-assets/bundle-plan.mjsindex 008fc3fbef9..20472959149 100644--- a/tests/install/e2e-assets/bundle-plan.mjs+++ b/tests/install/e2e-assets/bundle-plan.mjs@@ -1,6 +1,6 @@#!/usr/bin/env nodeimport { appendFile } from 'node:fs/promises'-import { validateBundleInputs } from './bundle-inputs.mjs'+import { validateBundleInputs } from './bundle-manifest.cjs'import { bundledMatrix } from '../../../scripts/sandbox/generate-e2e-matrix.mjs'const route = process.env.BUNDLE_ROUTE || 'all'diff --git a/tests/install/e2e-assets/drive-update.cjs b/tests/install/e2e-assets/drive-update.cjsindex e7343a1aa4a..fb8663ce1df 100644--- a/tests/install/e2e-assets/drive-update.cjs+++ b/tests/install/e2e-assets/drive-update.cjs@@ -22,6 +22,7 @@ const fs = require('node:fs')const { _electron } = require('@playwright/test')const { prepareWindowForInput } = require('./window-input.cjs')const { observeProcessClose } = require('./process-close.cjs')+const { pickAppWindow, openAbout, waitForUpdate } = require('./update-ui.cjs')const exePath = process.argv[2]const proofDir = process.argv[3]@@ -57,31 +58,6 @@ const killer = setTimeout(() => {}, KILL_AFTER_MS)killer.unref()-async function clickFirstVisible(page, locators, description, timeoutMs) {- const deadline = Date.now() + timeoutMs-- for (;;) {- for (const make of locators) {- const locator = make(page).first()-- try {- if (await locator.isVisible()) {- await locator.click()- log(`clicked: ${description}`)-- return true- }- } catch {- // locator invalid in this state; try the next- }- }- if (Date.now() > deadline) {- return false- }- await page.waitForTimeout(500)- }-}-async function main() {log(`launching ${exePath}`)@@ -99,29 +75,7 @@ async function main() {const waitForProcessClose = observeProcessClose(child)log(`launched Electron pid=${child.pid}`)- // firstWindow() can grab a helper webContents (wake indicator etc.), not- // the main app window. Pick the window that actually renders UI (has a- // <button>), retrying as windows appear.- 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) {- for (const c of app.windows()) log(` window seen: url=${c.url()}`)- throw new Error('no window with app UI (a <button>) appeared within 120s')- }- await new Promise(r => setTimeout(r, 1_000))- }- }- log(`window picked (${app.windows().length} windows, url=${page.url()})`)- log('first window acquired')+ const page = await pickAppWindow(app, log)await prepareWindowForInput(app, page)log('[zoom] app window prepared at 100%')@@ -136,122 +90,13 @@ async function main() {await page.waitForTimeout(3000)await shot(page, '01-app-booted')- // ── Reach Settings through the onboarding overlay ─────────────────────- // A fresh install with no configured provider shows the onboarding card- // ("Let's get you setup..."). It mounts LATE and in phases: first a- // buttonless boot-progress card ("Starting Hermes... 86%"), then the- // provider picker with "I'll choose a provider later".- // Two traps: a one-shot dismiss probe fires before the picker's button- // exists, and isVisible() on the settings gear reports true while the- // gear sits UNDER the fullscreen overlay that intercepts every click.- // So: alternate short-timeout dismiss clicks with short-timeout settings- // clicks until a settings click actually LANDS - Playwright's click- // checks the hit target, so a landed click is proof the overlay is gone.- // Harmless when onboarding never shows: the first settings click lands.- 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' })- ]-- const overlayDeadline = Date.now() + 180_000- let openedSettings = false- const brief = e => String((e && e.message) || e).split('\n').slice(0, 25).join(' | ')- let iter = 0-- while (!openedSettings) {- // A boot-time restore or focus event can move the scale after preparation.- await prepareWindowForInput(app, page)- iter++- for (const make of laterLocators) {- try {- await make(page).first().click({ timeout: 1_500 })- log('dismissed onboarding overlay')- await page.waitForTimeout(2500)- await shot(page, '01b-onboarding-dismissed')- break- } catch (e) {- log(`[overlay] iter ${iter} dismiss click failed: ${brief(e)}`)- }- }- for (const make of settingsLocators) {- try {- await make(page).first().click({ timeout: 2_500 })- openedSettings = true- log('clicked: Open settings')- break- } catch (e) {- log(`[overlay] iter ${iter} settings click failed: ${brief(e)}`)- }- }- 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(1500)- await shot(page, '02-settings-open')+ await openAbout(page, { log, shot, prepare: () => prepareWindowForInput(app, page) })+ const updateNow = await waitForUpdate(page, { log, shot })- // ── Go to the About section ───────────────────────────────────────────- const openedAbout = await clickFirstVisible(- page,- [- p => p.getByRole('tab', { name: 'About' }),- p => p.getByRole('button', { name: 'About' }),- p => p.getByText('About', { exact: true })- ],- 'About section',- 30_000- )-- if (!openedAbout) {- await shot(page, 'ERROR-no-about-tab')- throw new Error('could not find the About section in Settings')- }- await page.waitForTimeout(1500)- await shot(page, '03-about-panel')-- // ── Wait for "Update now" (appears when behind > 0) ──────────────────- // checkUpdates() runs at boot; if its result hasn't landed yet, press- // "Check now" like an impatient user would.- const updateNow = page.getByRole('button', { name: 'Update now' }).first()- let visible = await updateNow.isVisible().catch(() => false)-- if (!visible) {- // The boot-time auto-check can fail transiently and latch the error- // UI, while a fresh check succeeds. Nudge loop: click Check now when- // clickable, re-test Update now, 3 minute ceiling.- 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) {- // Surface the real git error behind the UI's generic "couldn't reach- // the update server" line.- const status = await page.evaluate(() =>- window.hermesDesktop?.updates?.check?.() ?? Promise.resolve('no updates.check bridge')- ).catch((err) => `updates.check failed: ${err?.message || err}`)- log(`[update-status] ${JSON.stringify(status)}`)- await shot(page, 'ERROR-no-update-now')- throw new Error('"Update now" never appeared — update check did not report behind > 0')- }- await shot(page, '04-update-available')+ let appClosed = false+ app.on('close', () => {+ appClosed = true+ })// ── The click under test ──────────────────────────────────────────────await updateNow.click()@@ -281,11 +126,6 @@ async function main() {const markerPath = hermesHome ? path.join(hermesHome, '.hermes-update-in-progress') : nullconst resultPath = hermesHome ? path.join(hermesHome, '.hermes-update-result.json') : null- let appClosed = false- app.on('close', () => {- appClosed = true- })-const handoffDeadline = Date.now() + 150_000let handoffStarted = falsediff --git a/tests/install/e2e-assets/installer-common.sh b/tests/install/e2e-assets/installer-common.shnew file mode 100644index 00000000000..328230ab5bb--- /dev/null+++ b/tests/install/e2e-assets/installer-common.sh@@ -0,0 +1,59 @@+#!/usr/bin/env bash+# Driver-only setup; these helpers never install into the caller's real HOME.+arm_source_redirect() {+ local repo="$1" work="$2" serve="$3"+ local https='https://github.com/NousResearch/hermes-agent.git'+ local ssh='[email protected]:NousResearch/hermes-agent.git'+ local actual real_git quoted_git cfg="$work/gitconfig" shim="$work/shim"+ actual="$(git -C "$repo" remote get-url origin)"+ real_git="$(command -v git)"+ quoted_git="$(printf '%q' "$real_git")"+ # A global file survives install.sh replacing GIT_CONFIG_COUNT/KEY_n/VALUE_n.+ printf '' > "$cfg"+ for url in "$actual" "$https" "$ssh"; do+ "$real_git" config --file "$cfg" --add "url.file://$serve.insteadOf" "$url"+ done+ export GIT_CONFIG_GLOBAL="$cfg"+ [ "$(git -C "$repo" remote get-url origin)" = "file://$serve" ] \+ || fail 'git URL redirect did not reach the staged repository'++ # Transport is local, but fork detection must still see the official origin.+ mkdir -p "$shim"+ cat > "$shim/git" <<EOF+#!/usr/bin/env bash+prev2=""+prev1=""+for arg in "\$@"; do+ if [ "\$prev2" = remote ] && [ "\$prev1" = get-url ] && [ "\$arg" = origin ]; then+ printf '%s\n' '$https'+ exit 0+ fi+ prev2="\$prev1"+ prev1="\$arg"+done+exec $quoted_git "\$@"+EOF+ chmod +x "$shim/git"+ export PATH="$shim:$PATH"+ [ "$(git -C "$repo" remote get-url origin)" = "$https" ] \+ || fail 'git origin shim did not report the official repository'+ ok "git transport redirected via $cfg; origin reported by $shim/git"+}++run_source_installer() {+ local repo="$1" work="$2" logs="$3" ref="$4" label="$5" desktop="${6:-}"+ local script="$work/install-$label.sh" text rc=0+ # Buffer before grep: git show | grep -q can lose to SIGPIPE under pipefail.+ text="$(git -C "$repo" show "$ref:scripts/install.sh")" || return+ git -C "$repo" show "$ref:scripts/install.sh" > "$script" || return+ local flags=(--skip-setup)+ if grep -qF -- --skip-browser <<< "$text"; then flags+=(--skip-browser); fi+ if [ "$desktop" = desktop ]; then+ grep -qF -- --include-desktop <<< "$text" \+ || { fail "ref $ref does not support --include-desktop; this leg cannot mean what it claims"; return 1; }+ flags+=(--include-desktop)+ fi+ bash "$script" "${flags[@]}" < /dev/null 2>&1 | ts_prefix > "$logs/install-$label.log" || rc=$?+ log_group "install.sh ($label) transcript" "$logs/install-$label.log"+ [ "$rc" -eq 0 ] || { fail "install.sh ($label) exited $rc; log at $logs/install-$label.log"; return "$rc"; }+}diff --git a/tests/install/e2e-assets/launch-from-spec.mjs b/tests/install/e2e-assets/launch-from-spec.mjsindex 9522f1b8821..cdd8a29996f 100644--- a/tests/install/e2e-assets/launch-from-spec.mjs+++ b/tests/install/e2e-assets/launch-from-spec.mjs@@ -30,6 +30,7 @@ import { execFileSync } from 'node:child_process';import { parseArgs } from 'node:util';import { _electron } from '@playwright/test';import { prepareWindowForInput } from './window-input.cjs';+import { pickAppWindow, openAbout, waitForUpdate } from './update-ui.cjs';import { observeSourceUpdate } from './source-update-observer.mjs';/**@@ -122,31 +123,7 @@ async function main() {cwd: launch.cwd,env: launch.env,});- // The app spawns several BrowserWindows (wake indicator, helper surfaces)- // and firstWindow() grabs whichever webContents came first, which is not- // always the main app window. Pick the window that actually renders the- // app UI (a button renders only in the real renderer), retrying as- // windows appear.- await app.firstWindow({ timeout: 120_000 });- let window = null;- const windowDeadline = Date.now() + 120_000;- while (!window) {- for (const candidate of app.windows()) {- const hasUi = await candidate- .evaluate(() => document.querySelector('button') !== null)- .catch(() => false);- if (hasUi) { window = candidate; break; }- }- if (!window) {- if (Date.now() > windowDeadline) {- for (const c of app.windows()) log(` window seen: url=${c.url()}`);- throw new Error('no window with app UI (a <button>) appeared within 120s');- }- await new Promise((r) => setTimeout(r, 1_000));- }- }- await window.waitForLoadState('domcontentloaded');- log(`window up: ${await window.title()} (${app.windows().length} windows, picked url=${window.url()})`);+ const window = await pickAppWindow(app, log);await window.screenshot({ path: `${values.spec}.window.png` }).catch(() => {});await prepareWindowForInput(app, window);@@ -164,29 +141,7 @@ async function main() {const deadline = Date.now() + Number(values['timeout-ms']);- // Dismiss the onboarding overlay when present. The drivers seed a- // provider so the overlay SHOULD never mount, but it has a real boot- // window: the renderer inits `configured` from a localStorage cache- // (null on a fresh install) and only flips after gateway probes, so the- // overlay can mount late - first as a buttonless boot-progress card,- // then as the provider picker with the real escape hatch, "I'll choose- // a provider later" (i18n en: chooseLater). Two traps this loop avoids:- // a one-shot dismiss probe loses to the late mount, and visibility is- // the wrong readiness signal - the settings gear is "visible" UNDER the- // fullscreen overlay while the overlay intercepts every click. So:- // alternate short-timeout dismiss clicks with short-timeout settings- // clicks until a settings click actually LANDS (Playwright's hit-target- // check makes a landed click proof the overlay is gone).phase('overlay-loop');- const later = window.getByRole('button', { name: /choose a provider later|skip/i }).first()- const settingsButton = window.getByRole('button', { name: /open settings|settings/i }).first()-- const overlayDeadline = Date.now() + 180_000- let settingsOpened = false- const brief = (e) => String(e && e.message || e).split('\n').slice(0, 25).join(' | ')- // When a settings click fails, record what wins the hit-test at the- // button's center plus the titlebar geometry, so a CI-only interception- // is attributable from the log alone.const hitDump = () => window.evaluate(() => {const describe = (el) => el ? {tag: el.tagName,@@ -213,70 +168,13 @@ async function main() {win: `${window.innerWidth}x${window.innerHeight} dpr=${window.devicePixelRatio}`,}}).then((d) => JSON.stringify(d)).catch((e) => `hit-dump failed: ${e.message}`)- for (let iter = 1; ; iter++) {- await prepareWindowForInput(app, window);- await later- .click({ timeout: 2_000 })- .then(async () => {- log('dismissed onboarding overlay')- await later.waitFor({ state: 'hidden', timeout: 15_000 }).catch(() => {})- })- .catch((e) => log(`[overlay] iter ${iter} chooseLater click failed: ${brief(e)}`))- try {- await settingsButton.click({ timeout: 4_000 })- // A landed click during shell hydration can be lost on a remount.- // Confirm the destination before looking for its About control.- await window.waitForURL(/[#/]settings(?:[/?]|$)/, { timeout: 4_000 })- settingsOpened = true- break- } catch (e) {- log(`[overlay] iter ${iter} settings click failed: ${brief(e)}`)- // Every 5th failure, log the hit-test stack (every iteration would be- // noise; the interceptor identity is what matters, not its frequency).- if (iter === 1 || iter % 5 === 0) {- log(`[overlay] iter ${iter} hit-test: ${await hitDump()}`)- }- }- if (Date.now() > overlayDeadline) break- }- if (!settingsOpened) {- await window.screenshot({ path: `${values.spec}.overlay-stuck.png` }).catch(() => {})- throw new Error('onboarding overlay never cleared: Settings not clickable within 180s')- }-+ const ui = {+ log,+ shot: (page, name) => page.screenshot({ path: `${values.spec}.${name}.png` }).catch(() => {}),+ };+ await openAbout(window, { ...ui, prepare: () => prepareWindowForInput(app, window), confirmSettings: true, hitDump });phase('about-update');- // Settings is open: About -> Update now.- await window.getByRole('tab', { name: /about/i }).or(- window.getByRole('button', { name: /about/i })).first().click();- const updateNow = window.getByRole('button', { name: /update now/i }).first();- // "Update now" only renders once a check reports behind > 0, and the- // About panel starts at "Last checked: never". The boot-time auto-check- // can also fail transiently and latch the error UI, while a fresh check- // succeeds. Nudge like an impatient user: click Check now whenever it is- // clickable (not a spinner), re-test Update now, 3 minute ceiling.- const checkNow = window.getByRole('button', { name: /check now/i }).first();- const nudgeDeadline = Date.now() + 180_000;- let updateVisible = await updateNow.isVisible().catch(() => false);- while (!updateVisible && Date.now() < nudgeDeadline) {- await checkNow.click({ timeout: 5_000 })- .then(() => log('nudged Check now'))- .catch(() => {}); // spinner or mid-transition - fine, just wait- await window.waitForTimeout(15_000);- updateVisible = await updateNow.isVisible().catch(() => false);- }- try {- await updateNow.waitFor({ state: 'visible', timeout: 15_000 });- } catch (e) {- // The About UI flattens every check failure to a generic "couldn't- // reach the update server", hiding the git stderr the main process- // captured. Pull the full status over the same IPC the panel uses so- // the log names the real error.- const status = await window.evaluate(() =>- window.hermesDesktop?.updates?.check?.() ?? Promise.resolve('no updates.check bridge')- ).catch((err) => `updates.check failed: ${err?.message || err}`);- log(`[update-status] ${JSON.stringify(status)}`);- throw e;- }+ const updateNow = await waitForUpdate(window, ui);const observe = observeSourceUpdate({home: spec.env.HERMES_HOME,resultPath: values.result,diff --git a/tests/install/e2e-assets/mac-bundled-feed.mjs b/tests/install/e2e-assets/mac-bundled-feed.mjsindex 5b0d7c59f69..c5a3d27199c 100644--- a/tests/install/e2e-assets/mac-bundled-feed.mjs+++ b/tests/install/e2e-assets/mac-bundled-feed.mjs@@ -14,7 +14,7 @@// <arch>-<channel>-mac.yml; on x64 it requests <channel>-mac.yml. The// channel comes from the release TAG (canary tags serve canary feeds) —// never hard-coded — and must be identical on both manifest sides-// (validated in mac-bundled-manifest.cjs).+// (validated in bundle-manifest.cjs).import { createHash } from 'node:crypto'import fs from 'node:fs'diff --git a/tests/install/e2e-assets/mac-bundled-manifest.cjs b/tests/install/e2e-assets/mac-bundled-manifest.cjsindex e292f24b4e0..a2662f92b63 100644--- a/tests/install/e2e-assets/mac-bundled-manifest.cjs+++ b/tests/install/e2e-assets/mac-bundled-manifest.cjs@@ -1,122 +1,4 @@-#!/usr/bin/env node-'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 (schema/commit/-// sha256/semver validation + artifact download). This module asserts the-// macOS-specific semantics on the resolver's normalized output-// (WORKROOT/bundle-inputs.json): per-side teamId + CFBundleIdentifier,-// exact-identity update rules, and channel consistency.--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})?)?$/-// CFBundleIdentifier shape (exact match is enforced at verify time; this-// only rejects obvious junk).-const BUNDLE_ID_RE = /^[A-Za-z][A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/--/** The update channel a release tag publishes to (the production- * darwinFeed channel). Canary tags feed the canary channel. */-function channelFromTag(tag) {- return /-canary\./.test(String(tag)) ? 'canary' : 'stable'-}--function validateSide(side, label) {- if (!side || typeof side !== 'object') {- throw new Error(`${label}: missing side object`)- }- for (const key of ['tag', 'version', 'commit', 'identity', 'teamId']) {- 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)}`)- }- // identity IS the CFBundleIdentifier (not the team): verified exactly,- // never by namespace prefix.- if (!BUNDLE_ID_RE.test(side.identity)) {- throw new Error(`${label}.identity: ${JSON.stringify(side.identity)} is not a CFBundleIdentifier`)- }- // Same rule the common resolver enforces (bundle-inputs.mjs): an exact- // 10-char Apple signing team id.- if (!/^[A-Z0-9]{10}$/.test(side.teamId)) {- throw new Error(`${label}.teamId: ${JSON.stringify(side.teamId)} is not a 10-char signing team id`)- }- 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) {- // The updater only replaces a bundle whose CFBundleIdentifier matches.- throw new Error(- `old.identity ${manifest.old.identity} != new.identity ${manifest.new.identity}: ` +- 'not the same application bundle')- }- if (manifest.old.teamId !== manifest.new.teamId) {- // Squirrel.Mac refuses an update whose code signature changes team.- throw new Error(- `old.teamId ${manifest.old.teamId} != new.teamId ${manifest.new.teamId}: ` +- 'Squirrel.Mac would reject this pair (signature gate)')- }- if (channelFromTag(manifest.old.tag) !== channelFromTag(manifest.new.tag)) {- throw new Error(- `channel mismatch: old tag ${manifest.old.tag} vs new tag ${manifest.new.tag} — ` +- 'the update must stay on one feed channel')- }- return manifest-}-+// Independent native signature and installed-stamp assertions./*** Parse the TeamIdentifier out of `codesign -dv` output. codesign prints* display output on STDERR, so pass stderr (or combined output) here.@@ -153,10 +35,4 @@ function stampAssertions(stamp, side) {return problems}-module.exports = {- ARCHES,- channelFromTag,- validateBundleManifest,- codesignTeam,- stampAssertions,-}+module.exports = { codesignTeam, stampAssertions }diff --git a/tests/install/e2e-assets/mac-bundled-update-driver.mjs b/tests/install/e2e-assets/mac-bundled-update-driver.mjsindex 984a28f24e7..c537d99448f 100644--- a/tests/install/e2e-assets/mac-bundled-update-driver.mjs+++ b/tests/install/e2e-assets/mac-bundled-update-driver.mjs@@ -27,6 +27,7 @@ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);const { observeProcessClose } = require('./process-close.cjs');const { prepareWindowForInput } = require('./window-input.cjs');+const { pickAppWindow, openAbout, waitForUpdate } = require('./update-ui.cjs');const { values } = parseArgs({options: {@@ -59,20 +60,7 @@ 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()})`);+const page = await pickAppWindow(app, log);await prepareWindowForInput(app, page);@@ -82,100 +70,8 @@ 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');+await openAbout(page, { log, shot, prepare: () => prepareWindowForInput(app, page) });+const updateNow = await waitForUpdate(page, { log, shot });// ── The click under test ────────────────────────────────────────────────await updateNow.click();diff --git a/tests/install/e2e-assets/update-ui.cjs b/tests/install/e2e-assets/update-ui.cjsnew file mode 100644index 00000000000..21be3bfdc48--- /dev/null+++ b/tests/install/e2e-assets/update-ui.cjs@@ -0,0 +1,101 @@+// Shared clicks only. Each route owns its receipt/process/relaunch observer.+async function pickAppWindow(app, log) {+ await app.firstWindow({ timeout: 120_000 })+ const deadline = Date.now() + 120_000+ for (;;) {+ for (const page of app.windows()) {+ if (await page.evaluate(() => document.querySelector('button') !== null).catch(() => false)) {+ await page.waitForLoadState('domcontentloaded')+ log(`window picked: ${page.url()}`)+ return page+ }+ }+ if (Date.now() > deadline) {+ for (const page of app.windows()) log(`window seen: ${page.url()}`)+ throw new Error('no window with app UI (a <button>) appeared within 120s')+ }+ await new Promise(resolve => setTimeout(resolve, 1_000))+ }+}++async function openAbout(page, { prepare, log, shot, confirmSettings = false, hitDump }) {+ const later = [+ page.getByRole('button', { name: /choose a provider later|skip/i }),+ page.getByText(/choose a provider later/i),+ ]+ const settings = [+ page.getByRole('button', { name: /open settings|settings/i }),+ page.getByLabel('Open settings'), page.locator('[aria-label="Open settings"]'),+ page.locator('[title="Open settings"]'),+ ]+ const deadline = Date.now() + 180_000+ let opened = false+ for (let attempt = 1; !opened; attempt++) {+ await prepare()+ for (const locator of later) {+ try {+ await locator.first().click({ timeout: 1_500 })+ log('dismissed onboarding overlay')+ await locator.first().waitFor({ state: 'hidden', timeout: 15_000 }).catch(() => {})+ await shot(page, '01b-onboarding-dismissed')+ break+ } catch { /* the overlay may still be mounting */ }+ }+ for (const locator of settings) {+ try {+ await locator.first().click({ timeout: 2_500 })+ // Source shells can remount during hydration and lose a landed click.+ if (confirmSettings) await page.waitForURL(/[#/]settings(?:[/?]|$)/, { timeout: 4_000 })+ opened = true+ break+ } catch (error) { log(`[overlay] settings click failed: ${String(error).split('\n')[0]}`) }+ }+ if (!opened && hitDump && (attempt === 1 || attempt % 5 === 0)) log(`[overlay] hit-test: ${await hitDump()}`)+ if (!opened && Date.now() > deadline) {+ await shot(page, 'ERROR-no-settings-button')+ throw new Error('Settings not clickable within 180s')+ }+ }+ await page.waitForTimeout(1_500)+ await shot(page, '02-settings-open')+ const about = [page.getByRole('tab', { name: /about/i }), page.getByRole('button', { name: /about/i }), page.getByText('About', { exact: true })]+ const aboutDeadline = Date.now() + 30_000+ for (;;) {+ for (const locator of about) {+ try {+ if (!await locator.first().isVisible()) continue+ await locator.first().click({ timeout: 2_500 })+ await page.waitForTimeout(1_500)+ await shot(page, '03-about-panel')+ return+ } catch { /* old releases use different controls */ }+ }+ if (Date.now() > aboutDeadline) {+ await shot(page, 'ERROR-no-about-tab')+ throw new Error('could not find the About section in Settings')+ }+ await page.waitForTimeout(500)+ }+}++async function waitForUpdate(page, { log, shot }) {+ const update = page.getByRole('button', { name: /update now/i }).first()+ const deadline = Date.now() + 180_000+ while (!await update.isVisible().catch(() => false) && Date.now() < deadline) {+ await page.getByRole('button', { name: /check now/i }).first().click({ timeout: 5_000 })+ .then(() => log('nudged Check now')).catch(() => {})+ await page.waitForTimeout(15_000)+ }+ if (!await update.isVisible().catch(() => false)) {+ const status = await page.evaluate(() =>+ window.hermesDesktop?.updates?.check?.() ?? Promise.resolve('no updates.check bridge')+ ).catch(error => `updates.check failed: ${error.message}`)+ log(`[update-status] ${JSON.stringify(status)}`)+ await shot(page, 'ERROR-no-update-now')+ throw new Error('"Update now" never appeared — update check did not report an update')+ }+ await shot(page, '04-update-available')+ return update+}++module.exports = { pickAppWindow, openAbout, waitForUpdate }diff --git a/tests/install/e2e-assets/windows-bundled-helpers.mjs b/tests/install/e2e-assets/windows-bundled-helpers.mjsindex ef19feacc4f..69672e61929 100644--- a/tests/install/e2e-assets/windows-bundled-helpers.mjs+++ b/tests/install/e2e-assets/windows-bundled-helpers.mjs@@ -16,140 +16,19 @@ import path from 'node:path'import http from 'node:http'import { pathToFileURL, fileURLToPath } from 'node:url'-// ── pure helpers (unit-tested in windows-bundled-helpers.test.mjs) ──────────--const MANIFEST_SIDES = ['old', 'new']-const REQUIRED_SIDE_FIELDS = ['tag', 'version', 'commit', 'identity', 'publisher', 'applicationId']-const REQUIRED_ARTIFACT_FIELDS = ['url', 'sha256']-const SUPPORTED_ARCHES = ['x64', 'arm64']-const COMMIT_RE = /^[0-9a-f]{40}$/-const SHA256_RE = /^[0-9a-fA-F]{64}$/-const FOUR_PART_RE = /^\d{1,5}\.\d{1,5}\.\d{1,5}\.\d{1,5}$/--/**- * True when 4-part MSIX version `a` is strictly newer than `b`- * (numeric, component-wise; MSIX swaps require strict monotonicity).- * @param {string} a- * @param {string} b- * @returns {boolean}- */-export function fourPartNewer(a, b) {- if (!FOUR_PART_RE.test(a) || !FOUR_PART_RE.test(b)) return false- const pa = a.split('.').map(Number)- const pb = b.split('.').map(Number)- for (let i = 0; i < 4; i++) {- if (pa[i] !== pb[i]) return pa[i] > pb[i]- }- return false-}--/**- * Validate the parent-owned resolver's normalized bundle-inputs manifest- * (schema1). `expectedPublisher` is injected by the caller from the- * production OUT_OF_STORE_PUBLISHER so the rule binds at runtime, and- * `artifactPathsExist` (default true) lets unit tests pass without files.- *- * @param {unknown} raw parsed manifest JSON- * @param {{ expectedPublisher: string, arch?: string, artifactPathsExist?: boolean }} o- * @returns {{ ok: boolean, errors: string[] }}- */-export function validateBundledManifest(raw, o) {- const errors = []- const arch = o.arch || 'x64'- const m = raw- if (!m || typeof m !== 'object' || Array.isArray(m)) {- return { ok: false, errors: ['manifest is not an object'] }- }- if (m.schema !== 1) errors.push(`schema: expected 1, got ${JSON.stringify(m.schema)}`)- if (m.platform !== 'windows') errors.push(`platform: expected "windows", got ${JSON.stringify(m.platform)}`)- if (!SUPPORTED_ARCHES.includes(arch)) errors.push(`arch "${arch}" not supported (${SUPPORTED_ARCHES.join('|')})`)- if (m.arch !== arch) errors.push(`arch: expected "${arch}", got ${JSON.stringify(m.arch)}`)-- for (const side of MANIFEST_SIDES) {- const s = m?.[side]- if (!s || typeof s !== 'object') {- errors.push(`${side}: missing`)- continue- }- for (const f of REQUIRED_SIDE_FIELDS) {- if (typeof s[f] !== 'string' || !s[f]) errors.push(`${side}.${f}: missing or not a string`)- }- if (typeof s.version === 'string' && !FOUR_PART_RE.test(s.version)) {- errors.push(`${side}.version: "${s.version}" is not a 4-part MSIX version`)- }- if (typeof s.commit === 'string' && !COMMIT_RE.test(s.commit)) {- errors.push(`${side}.commit: "${s.commit}" is not a 40-hex commit`)- }- const art = s.artifact- if (!art || typeof art !== 'object') {- errors.push(`${side}.artifact: missing`)- } else {- for (const f of REQUIRED_ARTIFACT_FIELDS) {- if (typeof art[f] !== 'string' || !art[f]) errors.push(`${side}.artifact.${f}: missing or not a string`)- }- if (typeof art.sha256 === 'string' && !SHA256_RE.test(art.sha256)) {- errors.push(`${side}.artifact.sha256: not 64 hex chars`)- }- if (typeof art.path !== 'string' || !art.path) {- // The parent resolver writes artifact.path (the downloaded, verified- // local file). Its absence means the contract regressed — fail loudly- // rather than serving an unverified package.- errors.push(`${side}.artifact.path: missing (parent resolver must write the downloaded local path)`)- } else if (o.artifactPathsExist !== false && !fs.existsSync(art.path)) {- errors.push(`${side}.artifact.path: "${art.path}" does not exist`)+import { validateDownloadedBundle } from './bundle-manifest.cjs'++export function validateBundledManifest(manifest, { expectedPublisher, arch = 'x64' }) {+ try {+ validateDownloadedBundle(manifest, 'windows', arch)+ for (const side of ['old', 'new']) {+ if (manifest[side].publisher !== expectedPublisher) {+ throw new Error(`${side}.publisher does not equal the production OUT_OF_STORE_PUBLISHER`)}}- }-- if (m?.old?.publisher && m?.new?.publisher && m.old.publisher !== m.new.publisher) {- errors.push('old.publisher and new.publisher disagree — one manifest, one identity')- }- for (const side of MANIFEST_SIDES) {- if (m?.[side]?.publisher && m[side].publisher !== o.expectedPublisher) {- errors.push(`${side}.publisher does not equal the production OUT_OF_STORE_PUBLISHER — refusing to serve a package the OS would reject`)- }- }- if (m?.old?.identity && m?.new?.identity && m.old.identity !== m.new.identity) {- errors.push('old.identity and new.identity disagree — an App Installer update swaps within ONE identity')- }- if (m?.old?.applicationId && m?.new?.applicationId && m.old.applicationId !== m.new.applicationId) {- errors.push('old.applicationId and new.applicationId disagree')- }- if (- m?.old?.version && m?.new?.version &&- FOUR_PART_RE.test(m.old.version) && FOUR_PART_RE.test(m.new.version) &&- !fourPartNewer(m.new.version, m.old.version)- ) {- errors.push(`new.version ${m.new.version} is not strictly newer than old.version ${m.old.version}`)- }- if (m?.old?.commit && m?.old?.commit === m?.new?.commit) {- errors.push('old.commit equals new.commit — no update to prove')- }-- return { ok: errors.length === 0, errors }-}--/**- * The feed layout for one manifest: per-side bundle file name (served under- * <feedUrl>/<side>/) and the single swapped descriptor path.- * @param {string} feedDir- * @param {{ old: { artifact: { path: string } }, new: { artifact: { path: string } } }} manifest- * @returns {{ oldBundlePath: string, newBundlePath: string, oldBundleName: string, newBundleName: string, descriptorPath: string }}- */-export function feedLayout(feedDir, manifest) {- const oldBundleName = path.basename(manifest.old.artifact.path)- const newBundleName = path.basename(manifest.new.artifact.path)- if (oldBundleName === newBundleName) {- // Same filename at the same URL would leave App Installer's cache (and- // any human reading the feed) unable to tell the swap happened.- throw new Error(`old and new bundle filenames collide: ${oldBundleName} — stage per-side dirs`)- }- return {- oldBundlePath: path.join(feedDir, 'old', oldBundleName),- newBundlePath: path.join(feedDir, 'new', newBundleName),- oldBundleName,- newBundleName,- descriptorPath: path.join(feedDir, 'update.appinstaller')+ return { ok: true, errors: [] }+ } catch (error) {+ return { ok: false, errors: [error.message] }}}diff --git a/tests/install/e2e-assets/windows-bundled-helpers.test.mjs b/tests/install/e2e-assets/windows-bundled-helpers.test.mjsindex a062cb229a7..cccca8aa8f2 100644--- a/tests/install/e2e-assets/windows-bundled-helpers.test.mjs+++ b/tests/install/e2e-assets/windows-bundled-helpers.test.mjs@@ -11,127 +11,6 @@ import fs from 'node:fs'import os from 'node:os'import path from 'node:path'-import { validateBundledManifest, fourPartNewer, feedLayout } from './windows-bundled-helpers.mjs'--const PUB = 'CN=Nous Research Inc., O=Nous Research Inc., L=Austin, S=Texas, C=US'-const OTHER_PUB = 'CN=Someone Else'--function side(over = {}) {- return {- tag: 'v0.3.0',- version: '0.3.0.0',- commit: 'a'.repeat(40),- identity: 'NousResearch.HermesBundled',- publisher: PUB,- applicationId: 'Hermes',- artifact: {- url: 'https://example.invalid/HermesBundled-0.3.0.0-win.msixbundle',- sha256: 'b'.repeat(64),- path: 'C:/staging/old/HermesBundled-0.3.0.0-win.msixbundle'- },- ...over- }-}--function manifest(over = {}) {- return { schema: 1, platform: 'windows', arch: 'x64', old: side(), new: side({ tag: 'v0.4.0', version: '0.4.0.0', commit: 'c'.repeat(40), artifact: { url: 'https://example.invalid/HermesBundled-0.4.0.0-win.msixbundle', sha256: 'd'.repeat(64), path: 'C:/staging/new/HermesBundled-0.4.0.0-win.msixbundle' } }), ...over }-}--function validate(m, extra = {}) {- return validateBundledManifest(m, { expectedPublisher: PUB, artifactPathsExist: false, ...extra })-}--test('a well-formed schema1 windows manifest validates', () => {- const r = validate(manifest())- assert.deepEqual(r, { ok: true, errors: [] })-})--test('rejects wrong schema, platform, and arch', () => {- assert.ok(!validate(manifest({ schema: 2 })).ok)- assert.ok(!validate(manifest({ platform: 'macos' })).ok)- assert.ok(!validate(manifest({ arch: 'arm64' })).ok)- assert.ok(validate(manifest({ arch: 'arm64' }), { arch: 'arm64' }).ok)-})--test('rejects a publisher that is not the production OUT_OF_STORE_PUBLISHER', () => {- const m = manifest()- m.old.publisher = OTHER_PUB- const r = validate(m)- assert.ok(!r.ok)- assert.ok(r.errors.some(e => e.includes('OUT_OF_STORE_PUBLISHER')))-})--test('rejects side/identity/applicationId disagreement', () => {- const m = manifest()- m.new.identity = 'NousResearch.Other'- assert.ok(!validate(m).ok)- const m2 = manifest()- m2.new.applicationId = 'Other'- assert.ok(!validate(m2).ok)- const m3 = manifest()- m3.new.publisher = OTHER_PUB- const r3 = validate(m3)- assert.ok(r3.errors.some(e => e.includes('old.publisher and new.publisher disagree')))-})--test('rejects non-monotonic versions and 3-part versions', () => {- const m = manifest()- m.new.version = '0.3.0.0'- assert.ok(validate(m).errors.some(e => e.includes('strictly newer')))- const m2 = manifest()- m2.old.version = '0.3.0'- assert.ok(validate(m2).errors.some(e => e.includes('4-part')))-})--test('rejects missing artifact fields and a fabricated artifact (no path)', () => {- const m = manifest()- delete m.new.artifact.path- assert.ok(validate(m).errors.some(e => e.includes('artifact.path')))- const m2 = manifest()- m2.old.artifact.sha256 = 'zz'- assert.ok(validate(m2).errors.some(e => e.includes('sha256')))- const m3 = manifest()- m3.new.artifact.url = ''- assert.ok(validate(m3).errors.some(e => e.includes('artifact.url')))-})--test('rejects old == new commit', () => {- const m = manifest()- m.new.commit = m.old.commit- assert.ok(validate(m).errors.some(e => e.includes('no update to prove')))-})--test('artifactPathsExist=true requires the downloaded file on disk', () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbh-'))- const p = path.join(dir, 'bundle.msixbundle')- fs.writeFileSync(p, 'x')- const m = manifest()- m.old.artifact.path = p- m.new.artifact.path = path.join(dir, 'new.msixbundle')- fs.writeFileSync(m.new.artifact.path, 'x')- assert.ok(validate(m, { artifactPathsExist: true }).ok)- m.old.artifact.path = path.join(dir, 'missing.msixbundle')- assert.ok(!validate(m, { artifactPathsExist: true }).ok)-})--test('fourPartNewer: numeric, component-wise, strict', () => {- assert.equal(fourPartNewer('0.4.0.0', '0.3.9.9'), true)- assert.equal(fourPartNewer('1.2.3.10', '1.2.3.9'), true)- assert.equal(fourPartNewer('0.3.0.0', '0.3.0.0'), false)- assert.equal(fourPartNewer('0.2.9.9', '0.3.0.0'), false)- assert.equal(fourPartNewer('0.3.0', '0.2.0.0'), false)-})--test('feedLayout stages per-side bundles and one swapped descriptor, rejecting collisions', () => {- const l = feedLayout('feed', manifest())- assert.ok(l.oldBundlePath.includes(`${path.sep}old${path.sep}`))- assert.ok(l.newBundlePath.includes(`${path.sep}new${path.sep}`))- assert.ok(l.descriptorPath.endsWith(`update.appinstaller`) || l.descriptorPath.endsWith('update.appinstaller'))- const m = manifest()- m.new.artifact.path = m.old.artifact.path- assert.throws(() => feedLayout('feed', m), /collide/)-})-test('native acceptance descriptor CLI uses explicit publisher and a stable subscription across upgrades', () => {const feed = fs.mkdtempSync(path.join(os.tmpdir(), 'wbh-descriptor-'))try {diff --git a/tests/install/installer-script-e2e.sh b/tests/install/installer-script-e2e.shindex e6a4df1d20c..2eecf3d0096 100755--- a/tests/install/installer-script-e2e.sh+++ b/tests/install/installer-script-e2e.sh@@ -85,8 +85,6 @@ case "$UPDATE_METHOD" inesacREPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"-REPO_URL_SSH="[email protected]:NousResearch/hermes-agent.git"-REPO_URL_HTTPS="https://github.com/NousResearch/hermes-agent.git"# Everything lives OUTSIDE the checkout; an untracked dir inside the repo# would make later dirty-tree checks lie.@@ -103,6 +101,8 @@ source "$(dirname "$0")/e2e-assets/ts-prefix.sh" 2>/dev/null || ts_prefix() { casource "$(dirname "$0")/e2e-assets/preserve-plugins.sh"# shellcheck source=e2e-assets/source-driver.shsource "$(dirname "$0")/e2e-assets/source-driver.sh"+# shellcheck source=e2e-assets/installer-common.sh+source "$(dirname "$0")/e2e-assets/installer-common.sh"# Full transcript in the job log, collapsed (GitHub renders ::group:: as a# fold; plain text anywhere else). Win or lose -- a green install's log is# how you diagnose the leg that fails next.@@ -150,69 +150,9 @@ git -C "$SERVE_REPO" symbolic-ref HEAD refs/heads/maingit -C "$SERVE_REPO" config uploadpack.allowAnySHA1InWant trueok "serve.git main = $OLD_SHA ($INSTALL_REF), update target $HEAD_SHA"-arm_redirect() {- # --- the git URL redirect ------------------------------------------------------ # we redirect to our own repo so we can play around with what commit hermes thinks we're on.- # A driver-owned global gitconfig, NOT GIT_CONFIG_COUNT/KEY_n/VALUE_n env- # config: install.sh sets those itself and would clobber ours.- actual_git_url="$(git -C "$REPO_ROOT" remote get-url origin)"- GIT_CFG="$WORK_ROOT/gitconfig"- cat > "$GIT_CFG" <<EOF-[url "file://$SERVE_REPO"]- insteadOf = $actual_git_url- insteadOf = $REPO_URL_HTTPS- insteadOf = $REPO_URL_SSH-EOF- export GIT_CONFIG_GLOBAL="$GIT_CFG"-- # check it worked- expected_git_url="file://$SERVE_REPO"- actual_git_url="$(git -C "$REPO_ROOT" remote get-url origin)"- if [[ "$actual_git_url" != "$expected_git_url" ]]; then- fail "failed git remote get-url shim: origin resolves to '$actual_git_url', expected '$expected_git_url'"- fi- ok "git URL redirect via GIT_CONFIG_GLOBAL=$GIT_CFG"--- # shim git and make 'git remote get-url origin' report the actual HA upstream-- # insteadOf is transparent for transport but `git remote get-url origin` gives you the- # replacement, so _get_origin_url() sees file://$SERVE_REPO and _is_fork() would return true.- # we check for the arguments "remote get-url origin" in order in any position- # to allow for e.g. -c with some config being passed.- # if we didn't do this, we'd need the .skip_upstream_prompt file to prevent a hang in headless,"add the- # official repo as upstream?" prompt would hang a headless run. But we don't anymore :D- REAL_GIT="$(command -v git)"- REAL_GIT_QUOTED="$(printf '%q' "$REAL_GIT")"- SHIM_DIR="$WORK_ROOT/shim"- mkdir -p "$SHIM_DIR"- cat > "$SHIM_DIR/git" <<EOF-#!/usr/bin/env bash-prev2=""-prev1=""-for arg in "\$@"; do- if [ "\$prev2" = "remote" ] && [ "\$prev1" = "get-url" ] && [ "\$arg" = "origin" ]; then- echo "$REPO_URL_HTTPS"- exit 0- fi- prev2="\$prev1"- prev1="\$arg"-done-exec "$REAL_GIT_QUOTED" "\$@"-EOF- chmod +x "$SHIM_DIR/git"- export PATH="$SHIM_DIR:$PATH"-- # check it worked- observed_git_url="$(git -C "$REPO_ROOT" remote get-url origin)"- if [[ "$observed_git_url" != "$REPO_URL_HTTPS" ]]; then- fail "failed git remote get-url shim: origin resolves to '$observed_git_url', expected '$REPO_URL_HTTPS'"- fi- ok "git remote get-url shim: $SHIM_DIR/git -> $REAL_GIT (origin reports $REPO_URL_HTTPS)"-}-# later, we might factor this out into a separate step like the macos desktop one.-arm_redirect++arm_source_redirect "$REPO_ROOT" "$WORK_ROOT" "$SERVE_REPO"# Isolated HOME: the runner's real one may carry a preinstalled hermes or a# developer config, and old installer scripts hardcode $HOME/.hermes (the@@ -226,50 +166,7 @@ mkdir -p "$HERMES_HOME"INSTALL_DIR="$HERMES_HOME/hermes-agent"-# Does the installer script at REF accept FLAG? Read that ref's own-# install.sh rather than assuming this checkout's flag set: the point of the-# matrix is to install releases from months back, whose installers predate-# options we take for granted.-#-# Buffered through a variable, NOT `git show | grep -q`: under pipefail,-# grep -q exits at the first match (install.sh is ~140KB, the flags appear-# in the first few KB), git show takes SIGPIPE on its next write, and the-# pipeline reports 141 -- the probe answers NO for a flag the ref HAS.-installer_supports() {- local text- text="$(git -C "$REPO_ROOT" show "$1:scripts/install.sh")"- grep -qF -- "$2" <<< "$text"-}-run_installer() {- # $1: ref whose scripts/install.sh to run; $2: log name; $3: "desktop" to- # opt the desktop stage in (--include-desktop)- local script="$WORK_ROOT/install-$2.sh"- git -C "$REPO_ROOT" show "$1:scripts/install.sh" > "$script"- chmod +x "$script"- # Installer flags have to match the installer being run, not this- # checkout's: older releases reject options added later. --skip-setup goes- # back further than any tag we sample; anything newer is probed for.- local flags=(--skip-setup)- if installer_supports "$1" "--skip-browser"; then- flags+=(--skip-browser)- fi- if [ "${3:-}" = "desktop" ]; then- # The desktop stage is the point of this leg, so a ref without the- # flag is a hard failure, not a silent downgrade to a plain install.- # (Releases that predate apps/desktop are already skipped upstream by- # the tag-has-desktop gate; the flag shipped with the app.)- installer_supports "$1" "--include-desktop" \- || fail "ref $1 does not support --include-desktop; this leg cannot mean what it claims"- flags+=(--include-desktop)- fi- # </dev/null: the script reads prompts from stdin when a tty is absent;- # EOF makes every remaining prompt take its default.- local rc=0- bash "$script" "${flags[@]}" < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/install-$2.log" || rc=$?- log_group "install.sh ($2) transcript" "$LOG_DIR/install-$2.log"- [ "$rc" -eq 0 ] || fail "install.sh ($2) exited $rc; transcript above, log at $LOG_DIR/install-$2.log"-}assert_desktop_artifact() {# $1: label. After a +desktop install the built app must exist under the@@ -313,11 +210,11 @@ step "installing OLD ($INSTALL_REF) via its own scripts/install.sh ($INSTALL_METEXPECT_DESKTOP=absentif [ "$INSTALL_METHOD" = "installer-script+desktop" ]; thenEXPECT_DESKTOP=present- run_installer "$OLD_SHA" old desktop+ run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$OLD_SHA" old desktopassert_checkout "$OLD_SHA" OLDassert_desktop_artifact OLDelse- run_installer "$OLD_SHA" old+ run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$OLD_SHA" oldassert_checkout "$OLD_SHA" OLDfipreserve_before_upgrade@@ -348,11 +245,11 @@ case "$UPDATE_METHOD" in;;installer-script)# A user re-running the one-liner today gets the CURRENT script.- run_installer "$TARGET_SHA" "$TARGET_LABEL"+ run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" "$TARGET_LABEL";;installer-script+desktop)EXPECT_DESKTOP=present- run_installer "$TARGET_SHA" "$TARGET_LABEL" desktop+ run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" "$TARGET_LABEL" desktopassert_desktop_artifact "$TARGET_LABEL";;hermes-desktop-app-update)@@ -399,7 +296,7 @@ case "$UPDATE_METHOD" in(cd "$PW_DIR" && npm install --no-save --no-audit --no-fund \"@playwright/[email protected]" 2>&1 | ts_prefix > "$LOG_DIR/playwright-install.log") \|| { log_group "playwright install transcript" "$LOG_DIR/playwright-install.log"; fail "playwright install failed"; }- cp "$ASSETS/launch-from-spec.mjs" "$ASSETS/source-update-observer.mjs" "$ASSETS/window-input.cjs" "$PW_DIR/"+ cp "$ASSETS/launch-from-spec.mjs" "$ASSETS/source-update-observer.mjs" "$ASSETS/window-input.cjs" "$ASSETS/update-ui.cjs" "$PW_DIR/"rc=0(cd "$PW_DIR" && node launch-from-spec.mjs \--spec "$SPEC" \diff --git a/tests/install/macos-bundled-e2e.sh b/tests/install/macos-bundled-e2e.shindex 3c19bee15fb..0e660b19d57 100644--- a/tests/install/macos-bundled-e2e.sh+++ b/tests/install/macos-bundled-e2e.sh@@ -123,18 +123,15 @@ manifest_side() { # $1: old|new, $2: fieldrequire_manifest() {[ -f "$MANIFEST" ] || fail "no bundle manifest at $MANIFEST — run the install phase first"- # Assert the common resolver's normalized output for this arm (schema 1,- # platform macos, this arch, downloaded artifacts, old != new, SAME- # CFBundleIdentifier, SAME teamId, same feed channel). The heavy schema/- # semver/sha256 validation already happened inside bundle-inputs.mjs.+ # Revalidate normalized inputs and downloaded files before every phase."$NODE_BIN" -e 'const fs = require("node:fs")- const { validateBundleManifest } = require(process.argv[2])+ const { validateDownloadedBundle } = require(process.argv[2])const m = JSON.parse(fs.readFileSync(process.argv[1], "utf8"))- validateBundleManifest(m, { platform: "macos", arch: process.env.E2E_ARCH })+ validateDownloadedBundle(m, "macos", process.env.E2E_ARCH)console.log("bundle manifest valid: " + m.old.tag + " -> " + m.new.tag +" (identity " + m.old.identity + ", team " + m.old.teamId + ")")- ' "$MANIFEST" "$ASSETS/mac-bundled-manifest.cjs" 2>&1 | ts_prefix+ ' "$MANIFEST" "$ASSETS/bundle-manifest.cjs" 2>&1 | ts_prefix}stage_bundle_inputs() {@@ -321,7 +318,7 @@ phase_update() {pw_dir="$(ensure_playwright)"cp "$ASSETS/mac-bundled-update-driver.mjs" \"$ASSETS/process-close.cjs" \- "$ASSETS/window-input.cjs" \+ "$ASSETS/window-input.cjs" "$ASSETS/update-ui.cjs" \"$pw_dir/"local rc=0(cd "$pw_dir" && node mac-bundled-update-driver.mjs \diff --git a/tests/install/macos-desktop-e2e.sh b/tests/install/macos-desktop-e2e.shindex 60c93a9ef9e..b105fab6cf6 100755--- a/tests/install/macos-desktop-e2e.sh+++ b/tests/install/macos-desktop-e2e.sh@@ -76,8 +76,6 @@ esac[ "$(uname -s)" = "Darwin" ] || { echo "error: this driver runs on macOS only" >&2; exit 1; }REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"-REPO_URL_SSH="[email protected]:NousResearch/hermes-agent.git"-REPO_URL_HTTPS="https://github.com/NousResearch/hermes-agent.git"ASSETS="$REPO_ROOT/tests/install/e2e-assets"WORK_ROOT="${HERMES_E2E_WORKROOT:-${RUNNER_TEMP:-${TMPDIR:-/tmp}}/hermes-macos-desktop-e2e}"@@ -95,6 +93,8 @@ source "$(dirname "$0")/e2e-assets/ts-prefix.sh" 2>/dev/null || ts_prefix() { casource "$(dirname "$0")/e2e-assets/preserve-plugins.sh"# shellcheck source=e2e-assets/source-driver.shsource "$(dirname "$0")/e2e-assets/source-driver.sh"+# shellcheck source=e2e-assets/installer-common.sh+source "$(dirname "$0")/e2e-assets/installer-common.sh"log_group() {printf '::group::%s\n' "$1"cat "$2"@@ -104,67 +104,7 @@ log_group() {# Every phase runs in its own process (separate CI steps), so the redirect# env is re-established here, not inherited.arm_redirect() {- # --- the git URL redirect ------------------------------------------------------- # we redirect to our own repo so we can play around with what commit hermes thinks we're on.- # A driver-owned global gitconfig, NOT GIT_CONFIG_COUNT/KEY_n/VALUE_n env- # config: install.sh sets those itself and would clobber ours.- actual_git_url="$(git -C "$REPO_ROOT" remote get-url origin)"- GIT_CFG="$WORK_ROOT/gitconfig"- cat > "$GIT_CFG" <<EOF-[url "file://$SERVE_REPO"]- insteadOf = $actual_git_url- insteadOf = $REPO_URL_HTTPS- insteadOf = $REPO_URL_SSH-EOF- export GIT_CONFIG_GLOBAL="$GIT_CFG"-- # check it worked- expected_git_url="file://$SERVE_REPO"- actual_git_url="$(git -C "$REPO_ROOT" remote get-url origin)"- if [[ "$actual_git_url" != "$expected_git_url" ]]; then- fail "failed git remote get-url shim: origin resolves to '$actual_git_url', expected '$expected_git_url'"- fi- ok "git URL redirect via GIT_CONFIG_GLOBAL=$GIT_CFG"--- # shim git and make 'git remote get-url origin' report the actual HA upstream-- # insteadOf is transparent for transport but `git remote get-url origin` gives you the- # replacement, so _get_origin_url() sees file://$SERVE_REPO and _is_fork() would return true.- # we check for the arguments "remote get-url origin" in order in any position- # to allow for e.g. -c with some config being passed.- # if we didn't do this, we'd need the .skip_upstream_prompt file to prevent a hang in headless,"add the- # official repo as upstream?" prompt would hang a headless run. But we don't anymore :D- REAL_GIT="$(command -v git)"- REAL_GIT_QUOTED="$(printf '%q' "$REAL_GIT")"- SHIM_DIR="$WORK_ROOT/shim"- mkdir -p "$SHIM_DIR"- cat > "$SHIM_DIR/git" <<EOF-#!/usr/bin/env bash-prev2=""-prev1=""-for arg in "\$@"; do- if [ "\$prev2" = "remote" ] && [ "\$prev1" = "get-url" ] && [ "\$arg" = "origin" ]; then- echo "$REPO_URL_HTTPS"- exit 0- fi- prev2="\$prev1"- prev1="\$arg"-done-exec "$REAL_GIT_QUOTED" "\$@"-EOF- chmod +x "$SHIM_DIR/git"- export PATH="$SHIM_DIR:$PATH"-- # check it worked- observed_git_url="$(git -C "$REPO_ROOT" remote get-url origin)"- if [[ "$observed_git_url" != "$REPO_URL_HTTPS" ]]; then- fail "failed git remote get-url shim: origin resolves to '$observed_git_url', expected '$REPO_URL_HTTPS'"- fi- ok "git remote get-url shim: $SHIM_DIR/git -> $REAL_GIT (origin reports $REPO_URL_HTTPS)"-- # -------+ arm_source_redirect "$REPO_ROOT" "$WORK_ROOT" "$SERVE_REPO"export HOME="$HOME_SANDBOX"export PATH="$HOME/.local/bin:$PATH"export HERMES_HOME="$HOME/.hermes"@@ -290,45 +230,14 @@ ensure_playwright() {printf '%s' "$pw_dir"}-installer_supports() {- # $1: ref; $2: flag. Installer flags must match the installer being run,- # not this checkout's: older releases reject options added later.- # Capture before grepping: a `git show | grep -q` pipe takes SIGPIPE- # under pipefail when grep exits at first match, so a supported flag- # would read as unsupported.- local text- text="$(git -C "$REPO_ROOT" show "$1:scripts/install.sh")"- grep -qF -- "$2" <<< "$text"-}-run_installer() {- # $1: ref whose scripts/install.sh to run; $2: log name; $3: "desktop" to- # opt the desktop stage in (--include-desktop). Mirrors the POSIX driver.- local script="$WORK_ROOT/install-$2.sh"- git -C "$REPO_ROOT" show "$1:scripts/install.sh" > "$script"- chmod +x "$script"- local flags=(--skip-setup)- if installer_supports "$1" "--skip-browser"; then- flags+=(--skip-browser)- fi- if [ "${3:-}" = "desktop" ]; then- installer_supports "$1" "--include-desktop" \- || fail "ref $1 does not support --include-desktop; this leg cannot mean what it claims"- flags+=(--include-desktop)- fi- # </dev/null: EOF makes every prompt take its default.- local rc=0- bash "$script" "${flags[@]}" < /dev/null 2>&1 | ts_prefix > "$LOG_DIR/install-$2.log" || rc=$?- log_group "installer ($2) transcript" "$LOG_DIR/install-$2.log"- [ "$rc" -eq 0 ] || fail "installer ($2) exited $rc; transcript above"-}run_playwright_update() {# $1: spec file to launch from.local spec="$1"local pw_dirpw_dir="$(ensure_playwright)"- cp "$ASSETS/launch-from-spec.mjs" "$ASSETS/source-update-observer.mjs" "$ASSETS/window-input.cjs" "$pw_dir/"+ cp "$ASSETS/launch-from-spec.mjs" "$ASSETS/source-update-observer.mjs" "$ASSETS/window-input.cjs" "$ASSETS/update-ui.cjs" "$pw_dir/"local rc=0(cd "$pw_dir" && node launch-from-spec.mjs \--spec "$spec" \@@ -377,10 +286,10 @@ phase_update() {;;installer-script)# A dmg user re-running today's install one-liner.- run_installer "$TARGET_SHA" head+ run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" head;;installer-script+desktop)- run_installer "$TARGET_SHA" head desktop+ run_source_installer "$REPO_ROOT" "$WORK_ROOT" "$LOG_DIR" "$TARGET_SHA" head desktop# The desktop stage is this leg's claim: the rebuilt app must exist.head_app=""for cand in \diff --git a/tests/install/windows-e2e.ps1 b/tests/install/windows-e2e.ps1index a6ee3093162..26795a004d3 100644--- a/tests/install/windows-e2e.ps1+++ b/tests/install/windows-e2e.ps1@@ -461,6 +461,7 @@ function Invoke-HermesDesktopAppUpdate([string]$TargetSha) {Copy-Item (Join-Path $AssetsDir "launch-from-spec.mjs") (Join-Path $driverDir "launch-from-spec.mjs") -ForceCopy-Item (Join-Path $AssetsDir "source-update-observer.mjs") (Join-Path $driverDir "source-update-observer.mjs") -ForceCopy-Item (Join-Path $AssetsDir "window-input.cjs") (Join-Path $driverDir "window-input.cjs") -Force+ Copy-Item (Join-Path $AssetsDir "update-ui.cjs") (Join-Path $driverDir "update-ui.cjs") -Force$prevEap = $ErrorActionPreference; $ErrorActionPreference = "Continue"Push-Location $driverDirtry {@@ -789,6 +790,7 @@ function Invoke-GuiUpdateDesktopRoute([string]$TargetSha) {$driver = Join-Path $driverDir "e2e-drive-update.cjs"Copy-Item (Join-Path $AssetsDir "drive-update.cjs") $driver -ForceCopy-Item (Join-Path $AssetsDir "window-input.cjs") (Join-Path $driverDir "window-input.cjs") -Force+ Copy-Item (Join-Path $AssetsDir "update-ui.cjs") (Join-Path $driverDir "update-ui.cjs") -ForceCopy-Item (Join-Path $AssetsDir "process-close.cjs") (Join-Path $driverDir "process-close.cjs") -ForcePush-Location $driverDir$prevEap = $ErrorActionPreferencediff --git a/tests/installation/test_installer_common.py b/tests/installation/test_installer_common.pynew file mode 100644index 00000000000..750c54837f4--- /dev/null+++ b/tests/installation/test_installer_common.py@@ -0,0 +1,63 @@+"""Driver setup against private Git/script artifacts, never an installed app."""+import os+import subprocess+from pathlib import Path++import pytest++HELPER = Path(__file__).resolve().parents[1] / "install/e2e-assets/installer-common.sh"++[email protected]("posix")+def test_redirect_and_historical_installer_keep_transport_flags_and_exit(tmp_path):+ env = {**os.environ, "HOME": str(tmp_path), "GIT_CONFIG_GLOBAL": os.devnull,+ "GIT_CONFIG_NOSYSTEM": "1", "GIT_AUTHOR_NAME": "Fixture", "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "Fixture", "GIT_COMMITTER_EMAIL": "[email protected]"}+ repo, work, serve = (tmp_path / name for name in ("repo", "work", "serve.git"))+ work.mkdir()++ def git(*args):+ return subprocess.check_output(["git", "-C", str(repo), *args], env=env, text=True).strip()++ subprocess.run(["git", "init", "-q", str(repo)], env=env, check=True)+ git("remote", "add", "origin", "https://example.invalid/fork.git")+ script = repo / "scripts/install.sh"+ script.parent.mkdir()+ script.write_text('printf "%s\\n" "$@"\nread -r value && exit 99\nexit 0\n', encoding="utf-8")+ git("add", ".")+ git("commit", "-qm", "old")+ old = git("rev-parse", "HEAD")+ script.write_text('# --skip-browser --include-desktop\n' + script.read_text(encoding="utf-8"), encoding="utf-8")+ git("commit", "-qam", "new")+ new = git("rev-parse", "HEAD")+ subprocess.run(["git", "clone", "--bare", "-q", str(repo), str(serve)], env=env, check=True)+ setup = '''set -euo pipefail+source "$1"+fail() { printf '%s\n' "$*" >&2; exit 1; }+ok() { :; }+ts_prefix() { cat; }+log_group() { :; }+arm_source_redirect "$2" "$3" "$4"+'''++ def run(body):+ return subprocess.run(["bash", "-c", setup + body, "bash", str(HELPER), str(repo), str(work), str(serve), old, new],+ env=env, text=True, capture_output=True, timeout=30)++ result = run('''[ "$(git -C "$2" remote get-url origin)" = 'https://github.com/NousResearch/hermes-agent.git' ]+git clone -q https://github.com/NousResearch/hermes-agent.git "$3/clone"+[ "$(git -C "$3/clone" rev-parse HEAD)" = "$6" ]+run_source_installer "$2" "$3" "$3" "$5" old+run_source_installer "$2" "$3" "$3" "$6" new desktop+''')+ assert result.returncode == 0, result.stderr+ assert (work / "install-old.log").read_text(encoding="utf-8").splitlines() == ["--skip-setup"]+ assert (work / "install-new.log").read_text(encoding="utf-8").splitlines() == ["--skip-setup", "--skip-browser", "--include-desktop"]+ assert (work / "install-new.sh").read_bytes() == script.read_bytes()+ refused = run('run_source_installer "$2" "$3" "$3" "$5" unavailable desktop')+ assert refused.returncode != 0 and "does not support --include-desktop" in refused.stderr+ assert not (work / "install-unavailable.log").exists()+ script.write_text("exit 23\n", encoding="utf-8")+ git("commit", "-qam", "failed installer")+ failed = run('run_source_installer "$2" "$3" "$3" HEAD broken')+ assert failed.returncode != 0 and "exited 23" in failed.stderr