diff --git a/apps/desktop/electron/app-updater.test.ts b/apps/desktop/electron/app-updater.test.ts deleted file mode 100644 index 9ae9e70475..0000000000 --- a/apps/desktop/electron/app-updater.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import assert from 'node:assert/strict' - -import { test } from 'vitest' - -import { - checkAppInstallerUpdate, - triggerAppInstallerUpdate, - win32AppInstallerFeedPath -} from './app-updater' - -// ── feed hosting + paths ──────────────────────────────────────────── - -test('win32 App Installer feed paths are per-channel and per-variant', () => { - assert.equal(win32AppInstallerFeedPath('stable', false), 'win32/stable/') - assert.equal(win32AppInstallerFeedPath('canary', false), 'win32/canary/') - assert.equal(win32AppInstallerFeedPath('stable', true), 'win32/light/stable/') - assert.equal(win32AppInstallerFeedPath('canary', true), 'win32/light/canary/') -}) - -// ── win32 arm (OS App Installer checker + trigger) ───────────────── - -function fakePayloadRunner(stdout: string, code = 0) { - const calls: string[] = [] - - return { - runner: { - python: 'C:\\payload\\tools\\cpython\\python.exe', - script: 'C:\\payload\\scripts\\check-appinstaller-update.py', - run: async (python: string, script: string) => { - calls.push(`${python} ${script}`) - - return { code, stdout } - } - } as any, - calls - } -} - -test('win32 check reports available when the OS says a newer package exists', async () => { - const { runner } = fakePayloadRunner(JSON.stringify({ available: true, availability: 'Available' })) - const result = await checkAppInstallerUpdate(runner) - - assert.equal(result.available, true) - assert.equal(result.availability, 'Available') -}) - -test('win32 check reports not-available cleanly', async () => { - const { runner } = fakePayloadRunner(JSON.stringify({ available: false, availability: 'NoApplicableUpdate' })) - const result = await checkAppInstallerUpdate(runner) - - assert.equal(result.available, false) -}) - -test('win32 check surfaces an unknown verdict (missing winrt) without crashing', async () => { - const { runner } = fakePayloadRunner(JSON.stringify({ available: null, error: 'winrt import failed' }), 1) - const result = await checkAppInstallerUpdate(runner) - - assert.equal(result.available, null) - assert.match(result.error || '', /winrt import failed/) -}) - -test('win32 trigger prepares a local descriptor before teardown and file activation', async () => { - const calls: string[] = [] - - const installer = { - prepare: async (url: string) => { calls.push(`download:${url}`); - - return 'update.appinstaller' }, - open: async (file: string) => { calls.push(`open:${file}`); - - return '' } - } - - const result = await triggerAppInstallerUpdate( - 'https://updates.example.com/', 'stable', false, installer, - () => void calls.push('teardown') - ) - - assert.equal(result.ok, true) - assert.deepEqual(calls, [ - 'download:https://updates.example.com/win32/stable/stable.appinstaller', - 'teardown', 'open:update.appinstaller' - ]) -}) - -test('win32 trigger refuses failed downloads before teardown and surfaces file-open errors', async () => { - const teardown = () => { throw new Error('unexpected teardown') } - await assert.rejects(triggerAppInstallerUpdate('https://updates.example.com', 'canary', true, { - prepare: async url => { assert.match(url, /win32\/light\/canary\/canary.appinstaller$/); throw new Error('download failed') }, - open: async () => '' - }, teardown), /download failed/) - await assert.rejects(triggerAppInstallerUpdate('https://updates.example.com', 'stable', false, { - prepare: async () => 'update.appinstaller', open: async () => 'No file association' - }), /No file association/) -}) diff --git a/apps/desktop/electron/backend-connection-state.test.ts b/apps/desktop/electron/backend-connection-state.test.ts index c4cf43c0ce..5bd6c72afc 100644 --- a/apps/desktop/electron/backend-connection-state.test.ts +++ b/apps/desktop/electron/backend-connection-state.test.ts @@ -134,6 +134,7 @@ test('a failed primary stop retains its child and blocks a replacement until ret const stopping = state.stopProcess(fail) assert.equal(state.getProcess(), null) assert.equal(state.getPromise(), null) + assert.equal(state.getPendingPromise(), null) assert.throws(() => state.startAttempt(), /has not stopped/) assert.equal(state.stopProcess(fail), stopping) await assert.rejects(stopping, error => error === failure) @@ -234,47 +235,3 @@ test('distinguishes a pending connection attempt from a cached settled descripto assert.equal(state.getPromise(), connection.promise) assert.equal(state.getPendingPromise(), null) }) - -test('a failed primary stop retains its child and blocks replacement until retry', async (): Promise => { - const state = createBackendConnectionState() - const child: FakeProcess = { id: 'primary' } - const attempt = state.startAttempt() - state.attachProcess(attempt, child) - state.setPromise(attempt, Promise.resolve('ready')) - const failure = new Error('still running') - const calls: FakeProcess[] = [] - - const fail = async (current: FakeProcess): Promise => { - calls.push(current) - throw failure - } - - const stopping = state.stopProcess(fail) - assert.equal(state.getProcess(), null) - assert.equal(state.getPendingPromise(), null) - assert.equal(state.stopProcess(fail), stopping) - assert.throws((): unknown => state.startAttempt(), /has not stopped/) - await assert.rejects(stopping, failure) - state.invalidate() - assert.throws((): unknown => state.startAttempt(), /has not stopped/) - await state.stopProcess(async (current: FakeProcess): Promise => { - calls.push(current) - }) - assert.deepEqual(calls, [child, child]) - assert.doesNotThrow((): unknown => state.startAttempt()) -}) - -test('shutdown owns a child before its persistent claim completes', async (): Promise => { - const state = createBackendConnectionState() - const child: FakeProcess = { id: 'claiming' } - const claim = deferred() - const claiming = state.claimProcess(state.startAttempt(), child, (): Promise => claim.promise) - - assert.equal(state.getProcess(), child) - await state.stopProcess(async (current: FakeProcess): Promise => { - assert.equal(current, child) - }) - claim.resolve() - assert.equal(await claiming, null) - assert.equal(state.getProcess(), null) -}) diff --git a/apps/desktop/electron/backend-probes.test.ts b/apps/desktop/electron/backend-probes.test.ts index 6703baf438..00f0ab4b76 100644 --- a/apps/desktop/electron/backend-probes.test.ts +++ b/apps/desktop/electron/backend-probes.test.ts @@ -6,7 +6,6 @@ */ import assert from 'node:assert/strict' -import fs from 'node:fs' import os from 'node:os' import path from 'node:path' @@ -68,35 +67,8 @@ test('verifyHermesCli returns false when binary does not exist', () => { assert.equal(verifyHermesCli(ghost), false) }) -test('verifyHermesCli returns true when --version exits 0', () => { - // Write a tiny script that exits 0 regardless of args, then invoke - // it through node. This stands in for a working hermes binary -- - // verifyHermesCli only cares about the exit code. - const scriptPath = path.join(os.tmpdir(), `hermes-probes-ok-${Date.now()}-${process.pid}.cjs`) - fs.writeFileSync(scriptPath, 'process.exit(0)\n') - - try { - // Use node as the launcher and our script as the "command". Pass - // shell:false (default) -- node is a real binary, no shim. - // execFileSync passes ['--version'] as args, which node ignores - // gracefully (well, it prints its version and exits 0, which is - // perfect -- exit code 0 is the only signal we read). - assert.equal(verifyHermesCli(NODE_BIN), true) - } finally { - try { - fs.unlinkSync(scriptPath) - } catch { - void 0 - } - } -}) - -test('verifyHermesCli swallows timeouts (does not throw)', () => { - // We can't easily provoke a real hang in CI without slowing the - // suite, but we CAN confirm that an invocation that DOES throw - // (because the binary is missing) returns false rather than - // propagating. Same code path the timeout case takes. - assert.equal(verifyHermesCli('/definitely/not/a/real/binary/anywhere'), false) +test('verifyHermesCli accepts an actual zero-exit executable', (): void => { + assert.equal(verifyHermesCli(NODE_BIN), true) }) test('default probe timeout is 15s (not the old 5s death-loop value)', () => { diff --git a/apps/desktop/electron/bootstrap-state.test.ts b/apps/desktop/electron/bootstrap-state.test.ts index 67ea76b8f9..08b7484175 100644 --- a/apps/desktop/electron/bootstrap-state.test.ts +++ b/apps/desktop/electron/bootstrap-state.test.ts @@ -18,5 +18,6 @@ test.each(['bundled', 'bootstrap', 'light'] as const)('bootstrap state retains t expect(bootstrapSnapshot(state, artifact)).toEqual({ ...state, bundled: payload === 'bundled' }) expect(bootstrapSnapshot({ error: null, setupChoice: null }, artifact).bundled).toBe(payload === 'bundled') expect(state).not.toHaveProperty('bundled') + expect(bootstrapSnapshot(state, null).bundled).toBe(false) expect(bootstrapSnapshot({ ...state, bundled: payload !== 'bundled' }, artifact).bundled).toBe(payload === 'bundled') }) diff --git a/apps/desktop/electron/connection-apply.test.ts b/apps/desktop/electron/connection-apply.test.ts index 2fe3a57ce6..329ae2b47a 100644 --- a/apps/desktop/electron/connection-apply.test.ts +++ b/apps/desktop/electron/connection-apply.test.ts @@ -19,8 +19,8 @@ function deferred() { } describe('applyConnectionChange', () => { - it.each([['SSH A to SSH B'], ['SSH to Cloud'], ['Cloud to SSH']])( - 'serializes %s behind bootstrap rollback before teardown and apply', + it( + 'serializes connection changes behind bootstrap rollback before teardown and apply', async () => { const gate = deferred() const events: string[] = [] @@ -92,48 +92,17 @@ describe('resolveTerminalConnection', () => { }) }) -describe('sshQuitShouldBlock', () => { - it('waits when connections exist and teardown has not finished', () => { - expect(sshQuitShouldBlock({ teardownDone: false, connectionCount: 1, bootstrapPending: 0, inFlight: null })).toBe( - true - ) +it.each([ + [false, 1, 0, false, true], + [false, 0, 1, false, true], + [false, 0, 0, true, true], + [true, 1, 1, true, false], + [false, 0, 0, false, false] +] as const)('quit guard: done=%s connections=%s bootstrap=%s stopping=%s → %s', + (teardownDone: boolean, connectionCount: number, bootstrapPending: number, stopping: boolean, expected: boolean): void => { + expect(sshQuitShouldBlock({ teardownDone, connectionCount, bootstrapPending, inFlight: stopping ? Promise.resolve() : null })).toBe(expected) }) - it('waits when bootstrap is still running', () => { - expect(sshQuitShouldBlock({ teardownDone: false, connectionCount: 0, bootstrapPending: 1, inFlight: null })).toBe( - true - ) - }) - - it('waits when the map is empty but a remote kill is already in flight', () => { - expect( - sshQuitShouldBlock({ - teardownDone: false, - connectionCount: 0, - bootstrapPending: 0, - inFlight: Promise.resolve() - }) - ).toBe(true) - }) - - it('does not block a second quit after teardown finished', () => { - expect( - sshQuitShouldBlock({ - teardownDone: true, - connectionCount: 1, - bootstrapPending: 1, - inFlight: Promise.resolve() - }) - ).toBe(false) - }) - - it('does not block quit when there is nothing to tear down', () => { - expect(sshQuitShouldBlock({ teardownDone: false, connectionCount: 0, bootstrapPending: 0, inFlight: null })).toBe( - false - ) - }) -}) - describe('teardownSshState', () => { it('terminates the owned remote backend before closing its tunnel and SSH transport', async () => { const events: string[] = [] diff --git a/apps/desktop/electron/deep-link-route.test.ts b/apps/desktop/electron/deep-link-route.test.ts index 31f5a93525..8c1c513557 100644 --- a/apps/desktop/electron/deep-link-route.test.ts +++ b/apps/desktop/electron/deep-link-route.test.ts @@ -1,23 +1,14 @@ -import { describe, expect, it } from 'vitest' +import { expect, it } from 'vitest' import { routeDeepLink } from './deep-link-route' -describe('routeDeepLink', () => { - it('summons quick entry for the Copilot key press', () => { - expect(routeDeepLink('copilot-key', 'start')).toBe('quick-entry') - }) - - it('ignores the Copilot key release so a tap does not undo the summon', () => { - expect(routeDeepLink('copilot-key', 'stop')).toBe('ignore') - }) - - it('ignores unknown copilot-key paths instead of leaking them to the renderer', () => { - expect(routeDeepLink('copilot-key', '')).toBe('ignore') - expect(routeDeepLink('copilot-key', 'toggle')).toBe('ignore') - }) - - it('routes every other deep link to the renderer', () => { - expect(routeDeepLink('blueprint', 'morning-brief')).toBe('renderer') - expect(routeDeepLink('', '')).toBe('renderer') - }) +it.each([ + ['copilot-key', 'start', 'quick-entry'], + ['copilot-key', 'stop', 'ignore'], + ['copilot-key', '', 'ignore'], + ['copilot-key', 'toggle', 'ignore'], + ['blueprint', 'morning-brief', 'renderer'], + ['', '', 'renderer'] +] as const)('%s/%s → %s', (host: string, pathname: string, expected: string): void => { + expect(routeDeepLink(host, pathname)).toBe(expected) }) diff --git a/apps/desktop/electron/desktop-electron-pin.test.ts b/apps/desktop/electron/desktop-electron-pin.test.ts index 8a27b26d6d..33e983bf74 100644 --- a/apps/desktop/electron/desktop-electron-pin.test.ts +++ b/apps/desktop/electron/desktop-electron-pin.test.ts @@ -19,14 +19,12 @@ * * 1. the Electron dependency is an *exact* version (Electron Builder needs the * installed binary to match ``electronVersion`` / ``electronDist``), and - * 2. the dependency, electron-builder.config.cjs ``electronVersion``, and the - * resolved lockfile entry all agree — so ``npm ci`` installs exactly what + * 2. the dependency and the independently resolved lockfile entry agree — so ``npm ci`` installs exactly what * the build packages. */ import assert from 'node:assert/strict' import fs from 'node:fs' -import { createRequire } from 'node:module' import path from 'node:path' import { test } from 'vitest' @@ -69,21 +67,6 @@ test('electron dependency is exactly pinned', () => { ) }) -test('electron dependency matches electron-builder.config.cjs', () => { - const spec = electronSpec(desktopPkg()) - const require = createRequire(import.meta.url) - const config = require('../electron-builder.config.cjs') as { electronVersion?: string } - const builderVersion = config.electronVersion - assert.ok(builderVersion, 'electron-builder.config.cjs electronVersion is missing') - assert.equal( - spec, - builderVersion, - `electron dependency ("${spec}") must equal electron-builder.config.cjs ` + - `electronVersion ("${builderVersion}"); otherwise electron-builder packages ` + - 'a different version than npm installs.' - ) -}) - test('lockfile resolves the pinned electron', () => { if (!fs.existsSync(ROOT_LOCK)) { return diff --git a/apps/desktop/electron/desktop-uninstall.test.ts b/apps/desktop/electron/desktop-uninstall.test.ts index a7a6186c94..6ef1d3127f 100644 --- a/apps/desktop/electron/desktop-uninstall.test.ts +++ b/apps/desktop/electron/desktop-uninstall.test.ts @@ -10,6 +10,11 @@ */ import assert from 'node:assert/strict' +import { type ChildProcess, spawn } from 'node:child_process' +import { once } from 'node:events' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' import { test } from 'vitest' @@ -159,7 +164,38 @@ test('shouldRemoveAppBundle requires packaged AND a resolved path', () => { assert.equal(shouldRemoveAppBundle(false, null), false) }) -// --- buildPosixCleanupScript --- +test.skipIf(process.platform === 'win32').each(['gui', 'lite', 'full'] as const)('POSIX cleanup executes %s in its sandbox and preserves its sibling', async (mode: string): Promise => { + const root: string = fs.mkdtempSync(path.join(os.tmpdir(), "uninstall-o'brien-")) + const app: string = path.join(root, 'App with spaces') + const sibling: string = path.join(root, 'App with spaces-other') + const recorder: string = path.join(root, "recorder's.cjs") + const resultFile: string = path.join(root, 'observed.json') + const script: string = path.join(root, 'cleanup.sh') + let child: ChildProcess | undefined + + try { + fs.mkdirSync(app); fs.mkdirSync(sibling) + fs.writeFileSync(recorder, `require('node:fs').writeFileSync(${JSON.stringify(resultFile)}, JSON.stringify({argv:process.argv.slice(2), home:process.env.HERMES_HOME, pythonPath:process.env.PYTHONPATH, cwd:process.cwd()}))`) + fs.writeFileSync(script, buildPosixCleanupScript({ + desktopPid: 0, pythonExe: process.execPath, pythonPath: mode === 'gui' ? null : root, + agentRoot: root, uninstallArgs: [recorder, ...uninstallArgsForMode(mode)], + appPath: mode === 'lite' ? null : app, hermesHome: root + })) + child = spawn('bash', [script], { env: { ...process.env, PYTHONPATH: 'inherited', HERMES_HOME: root }, stdio: 'ignore' }) + await once(child, 'close') + assert.equal(child.exitCode, 0) + assert.deepEqual(JSON.parse(fs.readFileSync(resultFile, 'utf8')), { + argv: ['-m', 'hermes_cli.uninstall', '--mode', mode], home: root, + pythonPath: mode === 'gui' ? 'inherited' : `${root}:inherited`, cwd: root + }) + assert.equal(fs.existsSync(app), mode === 'lite') + assert.equal(fs.existsSync(sibling), true) + assert.equal(fs.existsSync(script), false) + } finally { + if (child && child.exitCode === null && child.signalCode === null) { child.kill(); await once(child, 'close') } + fs.rmSync(root, { recursive: true, force: true }) + } +}) test('buildPosixCleanupScript waits for the PID, runs the uninstall module, removes bundle', (): void => { const script = buildPosixCleanupScript({ @@ -182,68 +218,6 @@ test('buildPosixCleanupScript waits for the PID, runs the uninstall module, remo assert.match(script, /export HERMES_HOME='\/home\/x\/\.hermes'/) }) -test('buildPosixCleanupScript exports PYTHONPATH when pythonPath is set (lite/full)', () => { - const script = buildPosixCleanupScript({ - desktopPid: 1, - pythonExe: '/usr/bin/python3', - pythonPath: '/home/x/.hermes/hermes-agent', - agentRoot: '/home/x/.hermes/hermes-agent', - uninstallArgs: ['-m', 'hermes_cli.uninstall', '--mode', 'full'], - appPath: null, - hermesHome: '/home/x/.hermes' - }) - - // System python + source on PYTHONPATH so import hermes_cli works while the - // venv is torn down. - assert.match(script, /export PYTHONPATH='\/home\/x\/\.hermes\/hermes-agent'/) - assert.match(script, /'\/usr\/bin\/python3' '-m' 'hermes_cli\.uninstall' '--mode' 'full'/) -}) - -test('buildPosixCleanupScript omits PYTHONPATH when pythonPath is null (gui)', () => { - const script = buildPosixCleanupScript({ - desktopPid: 1, - pythonExe: '/p/python', - pythonPath: null, - agentRoot: '/a', - uninstallArgs: ['-m', 'hermes_cli.uninstall', '--mode', 'gui'], - appPath: null, - hermesHome: '/h' - }) - - assert.doesNotMatch(script, /export PYTHONPATH/) -}) - -test('buildPosixCleanupScript omits the bundle rm when appPath is null', () => { - const script = buildPosixCleanupScript({ - desktopPid: 1, - pythonExe: '/p/python', - pythonPath: null, - agentRoot: '/a', - uninstallArgs: ['-m', 'hermes_cli.uninstall', '--mode', 'lite'], - appPath: null, - hermesHome: '/h' - }) - - assert.doesNotMatch(script, /rm -rf '\//) - // Still runs the uninstall. - assert.match(script, /'-m' 'hermes_cli\.uninstall' '--mode' 'lite'/) -}) - -test('buildPosixCleanupScript single-quote-escapes paths with apostrophes', () => { - const script = buildPosixCleanupScript({ - desktopPid: 1, - pythonExe: "/home/o'brien/python", - pythonPath: null, - agentRoot: '/a', - uninstallArgs: ['-m', 'hermes_cli.uninstall', '--mode', 'gui'], - appPath: null, - hermesHome: '/h' - }) - - // The apostrophe is closed-escaped-reopened so the shell sees the literal. - assert.match(script, /'\/home\/o'\\''brien\/python'/) -}) - // --- buildWindowsCleanupScript --- test('buildWindowsCleanupScript waits (bounded) for PID, runs uninstall, rmdir bundle', () => { diff --git a/apps/desktop/electron/gateway-version.test.ts b/apps/desktop/electron/gateway-version.test.ts index b9860bb91d..aa4619d2c6 100644 --- a/apps/desktop/electron/gateway-version.test.ts +++ b/apps/desktop/electron/gateway-version.test.ts @@ -1,36 +1,21 @@ import assert from 'node:assert/strict' -import { createServer } from 'node:http' import { test } from 'vitest' import { resolveGatewayVersion } from './gateway-version' -test('version follows the gateway response across runtime changes', async () => { - let version = '1.2.3' +test('version follows each supplied gateway response without caching', async (): Promise => { + let version: string = '1.2.3' - const server = createServer((_request, response) => { - response.setHeader('Content-Type', 'application/json') - response.end(JSON.stringify({ ok: true, version })) - }) - - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - assert.ok(address && typeof address !== 'string') - const baseUrl = `http://127.0.0.1:${address.port}` - - const request = async (endpoint: string): Promise => { + const request: (endpoint: string) => Promise<{ version: string }> = async (endpoint: string): Promise<{ version: string }> => { assert.equal(endpoint, '/api/health') - return (await fetch(`${baseUrl}${endpoint}`)).json() + return { version } } - try { - assert.equal(await resolveGatewayVersion(request), version) - version = '4.5.6' - assert.equal(await resolveGatewayVersion(request), version) - } finally { - await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())) - } + assert.equal(await resolveGatewayVersion(request), '1.2.3') + version = '4.5.6' + assert.equal(await resolveGatewayVersion(request), '4.5.6') }) test('unavailable gateway version stays unknown instead of using another install', async () => { diff --git a/apps/desktop/electron/install-stamp.test.ts b/apps/desktop/electron/install-stamp.test.ts deleted file mode 100644 index 6cdc282a76..0000000000 --- a/apps/desktop/electron/install-stamp.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -// installShape() — the ONE split every desktop lifecycle decision gates on. -// -// The stamp is a constant of the artifact; the shape is derived from it -// and never from filesystem probes. These tests pin the derivation table -// and the probe-independence (a stamp object is enough — no fs access). - -import { describe, expect, test } from 'vitest' - -import { installShape, type InstallStamp } from './install-stamp' - -function stamp(overrides: Partial): InstallStamp { - return { - schemaVersion: 2, - commit: 'a'.repeat(40), - commitDate: 1755000000, - branch: 'main', - builtAt: '2026-08-14T00:00:00Z', - dirty: false, - source: 'ci', - distribution: 'desktop-app', - updateMechanism: 'electron-updater', - baseVersion: '0.21.0', - displayVersion: '0.21.0', - distance: 0, - payload: 'bootstrap', - tag: null, - ...overrides - } -} - -describe('installShape', () => { - test('a bundled stamp is the bundled shape', () => { - expect(installShape(stamp({ payload: 'bundled', tag: 'v0.21.0' }))).toBe('bundled') - }) - - test('a bootstrap stamp is a checkout — its runtime is a local install', () => { - expect(installShape(stamp({ payload: 'bootstrap' }))).toBe('checkout') - }) - - test('a light stamp is not bundled (no runtime to run at all)', () => { - // Light artifacts never resolve a local backend; what matters here is - // that they can never be told to run venv machinery as "bundled". - expect(installShape(stamp({ payload: 'light' }))).toBe('checkout') - }) - - test('a dev run (null stamp) is a checkout', () => { - expect(installShape(null)).toBe('checkout') - }) - - -}) diff --git a/apps/desktop/electron/package-process-reap.test.ts b/apps/desktop/electron/package-process-reap.test.ts index b9b9019872..d20b1f38f1 100644 --- a/apps/desktop/electron/package-process-reap.test.ts +++ b/apps/desktop/electron/package-process-reap.test.ts @@ -3,57 +3,23 @@ import { describe, expect, it, vi } from 'vitest' import { isUnderInstallRoot, listWindowsProcesses, - protectedRuntimePids, reapPackageRootedProcesses, type RunningProcess } from './package-process-reap' const ROOT = 'C:\\Program Files\\WindowsApps\\NousResearch.HermesBundled_0.21.20.25635_arm64__e60prshbsznhj' -/** A mutable install's managed tool store: HERMES_RUNTIME_DIR / \tools. */ -const TOOLS_ROOT = 'C:\\Users\\arilo\\AppData\\Local\\hermes\\tools' - -/** The live-observed pinner: payload git's gpg-agent, daemonized out of our tree. */ -const GPG_AGENT = `${ROOT}\\app\\resources\\agent-payload\\tools\\git-2.53.0+3-win32-arm64\\usr\\bin\\gpg-agent.exe` -const PAYLOAD_PYTHON = `${ROOT}\\app\\resources\\agent-payload\\tools\\python-3.11.16+20260814-win32-arm64\\python.exe` -const MAIN_EXE = `${ROOT}\\app\\Hermes.exe` - -/** Live-observed daemon command line (payload git gpg-agent, C09). */ -const DAEMON_CMDLINE = `"${GPG_AGENT}" --use-standard-socket --daemon` - -/** Same class, mutable install: pm-staged node holding its own image open. */ -const STORE_NODE = `${TOOLS_ROOT}\\node-26.7.0-win32-arm64\\node.exe` - -/** - * The gateway that survives desktop quit: payload python running the Hermes - * gateway under the user-logon Scheduled Task (bundled installs run it out - * of the payload, so its image IS under the artifact root). - */ -const GATEWAY_CMDLINE = `"${PAYLOAD_PYTHON}" -m hermes_cli.main gateway run` -/** Legacy/alternate module launcher of the same runtime. */ -const GATEWAY_RUN_MODULE_CMDLINE = `"${PAYLOAD_PYTHON}" -m gateway.run --profile work` -/** Script-path launcher of the same runtime. */ -const GATEWAY_RUN_SCRIPT_CMDLINE = `"${PAYLOAD_PYTHON}" C:\\Hermes\\hermes-agent\\gateway\\run.py --profile work` - -function reap(processes: RunningProcess[], overrides: Record = {}) { - const killProcess = vi.fn() - - const outcome = reapPackageRootedProcesses({ - installRoots: [ROOT], - listProcesses: () => processes, - killProcess, - selfPid: 1, - isWindows: true, - ...overrides - }) - - return { outcome, killProcess } -} +const GPG_AGENT: string = `${ROOT}\\app\\tools\\git\\gpg-agent.exe` +const PAYLOAD_PYTHON: string = `${ROOT}\\app\\tools\\python\\python.exe` +const MAIN_EXE: string = `${ROOT}\\app\\Hermes.exe` +const TOOLS_ROOT: string = 'C:\\Hermes\\tools' +const STORE_NODE: string = `${TOOLS_ROOT}\\node\\node.exe` +const DAEMON_CMDLINE: string = 'gpg-agent --daemon' function proc( pid: number, path: string | null, - commandLine: string | null = null, + commandLine: string | null = DAEMON_CMDLINE, parentPid: number | null = null ): RunningProcess { return { pid, parentPid, path, commandLine } @@ -105,254 +71,58 @@ describe('isUnderInstallRoot', () => { }) }) -describe('reapPackageRootedProcesses', () => { - it('kills a detached package-rooted daemon that a tree-kill cannot reach', () => { - // The regression: gpg-agent reparented away from us, so it is in no tree we - // own. Path scoping is what catches it. - const { outcome, killProcess } = reap([proc(48236, GPG_AGENT, DAEMON_CMDLINE)]) +interface SelectionCase { + name: string + processes: RunningProcess[] + roots?: Array + selfPid?: number + excludePids?: number[] + killed: number[] +} - expect(outcome.matched).toBe(1) - expect(outcome.killed).toEqual([48236]) - expect(killProcess).toHaveBeenCalledWith(48236) +const cases: SelectionCase[] = [ + { name: 'owned daemon', processes: [proc(10, GPG_AGENT)], killed: [10] }, + { name: 'self daemon', processes: [proc(10, GPG_AGENT)], selfPid: 10, killed: [] }, + { name: 'excluded daemon', processes: [proc(10, GPG_AGENT), proc(11, GPG_AGENT)], excludePids: [10], killed: [11] }, + { name: 'sibling-prefix daemon', processes: [proc(10, `${ROOT}-other\\gpg-agent.exe`)], killed: [] }, + { name: 'external daemon', processes: [proc(10, 'C:\\Git\\gpg-agent.exe'), proc(11, GPG_AGENT)], killed: [11] }, + { name: 'unidentified parent and daemon descendants', processes: [proc(12, GPG_AGENT, DAEMON_CMDLINE, 11), proc(11, GPG_AGENT, DAEMON_CMDLINE, 10), proc(10, null)], killed: [] }, + { name: 'shared runtime and daemon descendants', processes: [proc(12, GPG_AGENT, DAEMON_CMDLINE, 11), proc(11, GPG_AGENT, DAEMON_CMDLINE, 10), proc(10, PAYLOAD_PYTHON, '-u -X utf8 -m gateway.run')], killed: [] }, + { name: 'shared entrypoints irrespective of argv', processes: [proc(10, MAIN_EXE, '--app'), proc(11, PAYLOAD_PYTHON, null), proc(12, STORE_NODE, 'daemon.js'), proc(13, GPG_AGENT)], roots: [ROOT, TOOLS_ROOT], killed: [13] }, + { name: 'mutable tool roots', processes: [proc(10, `${TOOLS_ROOT}\\git\\gpg-agent.exe`), proc(11, GPG_AGENT)], roots: [null, TOOLS_ROOT], killed: [10] }, + { name: 'unreadable path', processes: [proc(10, null)], killed: [] } +] + +it.each(cases)('safe kill selection: $name', ({ processes, roots = [ROOT], selfPid = 1, excludePids = [], killed }: SelectionCase): void => { + const signalled: number[] = [] + + const outcome: ReturnType = reapPackageRootedProcesses({ + installRoots: roots, selfPid, excludePids, isWindows: true, + listProcesses: (): RunningProcess[] => processes, + killProcess: (pid: number): void => { signalled.push(pid) } }) - it('leaves shared interpreters and entry points to their lifecycle owners', () => { - const { outcome } = reap([ - proc(10, MAIN_EXE, `${MAIN_EXE} --app`), - proc(11, PAYLOAD_PYTHON, 'idle-python'), - proc(12, GPG_AGENT, DAEMON_CMDLINE) - ]) - - expect(outcome.matched).toBe(1) - expect(outcome.killed).toEqual([12]) - }) - - it('never kills processes outside the install root', () => { - const { outcome, killProcess } = reap([ - proc(20, 'C:\\Program Files\\Git\\usr\\bin\\gpg-agent.exe', 'gpg-agent --daemon'), - proc(21, 'C:\\Users\\arilo\\AppData\\Local\\Programs\\HermesBundled\\app\\Hermes.exe'), - proc(22, GPG_AGENT, DAEMON_CMDLINE) - ]) - - // The user's OWN gpg-agent is exactly what a GNUPGHOME-scoped - // `gpgconf --kill all` would have taken out. Path scoping leaves it alone. - expect(outcome.killed).toEqual([22]) - expect(killProcess).not.toHaveBeenCalledWith(20) - expect(killProcess).not.toHaveBeenCalledWith(21) - }) - - it('reaps a mutable install: pm-staged tooling under the managed store', () => { - // No MSIX here. A daemonized node/git under \tools keeps its - // image open, and on Windows a running image cannot be overwritten — so - // the next `hermes update` fails to replace exactly those files. - const { outcome, killProcess } = reap( - [ - proc(70, STORE_NODE, `${STORE_NODE} daemon.js`), - proc(71, `${TOOLS_ROOT}\\git-2.53.0+3-win32-arm64\\usr\\bin\\gpg-agent.exe`, DAEMON_CMDLINE), - proc(72, 'C:\\Windows\\System32\\node.exe', 'node server.js') - ], - { installRoots: [null, TOOLS_ROOT] } - ) - - expect(outcome.killed).toEqual([71]) - expect(killProcess).not.toHaveBeenCalledWith(72) - }) - - it('reaps both roots in one pass when an install has both', () => { - const { outcome } = reap( - [proc(80, GPG_AGENT, DAEMON_CMDLINE), proc(81, STORE_NODE, `${STORE_NODE} daemon.js`)], - { installRoots: [ROOT, TOOLS_ROOT] } - ) - - expect(outcome.matched).toBe(1) - expect(outcome.killed).toEqual([80]) - }) - - it('never reaps a live Hermes runtime process rooted in the payload', () => { - // Bundled installs run the surviving gateway out of the payload, so its - // image IS under the artifact root — but the gateway survives desktop - // quit by contract. The `-m hermes_cli.main` invocation is what proves a - // process is a legitimate Hermes surface rather than an orphan. - const { outcome, killProcess } = reap([ - proc(90, PAYLOAD_PYTHON, GATEWAY_CMDLINE), - proc(91, PAYLOAD_PYTHON, `"${PAYLOAD_PYTHON}" -m hermes_cli.main serve --port 8080`) - ]) - - expect(outcome.matched).toBe(0) - expect(killProcess).not.toHaveBeenCalled() - }) - - it('the ordinary-quit selector kills the daemon but not the gateway or shared-store consumers', () => { - // Recorder for the wired quit call (roots = the artifact root only): a - // store-python gateway session and a store-node process are unrelated - // users of the machine-scoped store; the payload gateway survives the - // quit. Only the daemonized tool is selected. - const storePython = 'C:\\Users\\arilo\\AppData\\Local\\hermes\\tools\\python-3.11.16\\python.exe' - - const { outcome, killProcess } = reap( - [ - proc(100, storePython, `"${storePython}" -m hermes_cli.main gateway run`), - proc(101, STORE_NODE, `${STORE_NODE} script.js`), - proc(102, PAYLOAD_PYTHON, GATEWAY_CMDLINE), - proc(103, GPG_AGENT, `"${GPG_AGENT}" --use-standard-socket --daemon`) - ], - { installRoots: [ROOT] } - ) - - expect(outcome.killed).toEqual([103]) - expect(killProcess).toHaveBeenCalledTimes(1) - expect(killProcess).toHaveBeenCalledWith(103) - }) - - it('protects the alternate runtime launcher shapes: -m gateway.run and gateway/run.py', () => { - // The Scheduled-Task launcher, elevated-handoff respawn and older - // releases do not all use `-m hermes_cli.main`; every launcher of the - // live runtime is protected (C06-09 review). - const { outcome, killProcess } = reap([ - proc(91, PAYLOAD_PYTHON, GATEWAY_RUN_MODULE_CMDLINE), - proc(92, PAYLOAD_PYTHON, GATEWAY_RUN_SCRIPT_CMDLINE) - ]) - - expect(outcome.matched).toBe(0) - expect(killProcess).not.toHaveBeenCalled() - }) - - it('protects the live runtime DESCENDANTS (venv launcher / worker / tool chain)', () => { - // gateway -> venv launcher shim -> worker python -> payload git: every - // one is a legitimate user of the payload while its ancestor lives. - const launcher = `${ROOT}\\app\\resources\\agent-payload\\venv\\Scripts\\python.exe` - const worker = `${launcher} -c "import worker"` - const git = `${ROOT}\\app\\resources\\agent-payload\\tools\\git-2.53.0+3-win32-arm64\\bin\\git.exe status` - - const { outcome, killProcess } = reap([ - proc(120, PAYLOAD_PYTHON, GATEWAY_CMDLINE), - proc(121, launcher, worker, 120), - proc(122, launcher, null, 121), // unreadable cmdline, but runtime-descended - proc(123, `${ROOT}\\app\\resources\\agent-payload\\tools\\git\\bin\\git.exe`, git, 121) - ]) - - expect(outcome.matched).toBe(0) - expect(killProcess).not.toHaveBeenCalled() - }) - - it('protects flagged interpreters and children of unidentified processes', () => { - const { outcome } = reap([ - proc(130, PAYLOAD_PYTHON, `"${PAYLOAD_PYTHON}" -u -X utf8 -m gateway.run`), - proc(131, GPG_AGENT, DAEMON_CMDLINE, 130), - proc(140, null, null), - proc(141, GPG_AGENT, DAEMON_CMDLINE, 140), - proc(150, GPG_AGENT, DAEMON_CMDLINE) - ]) - - expect(outcome.killed).toEqual([150]) - }) - - it('conservatively skips a process whose command line cannot be read', () => { - // An unreadable cmdline cannot prove the process is not a live runtime. - // Missing one pinner reproduces a bug we already have; killing an - // unidentified process is unbounded damage. - const { outcome, killProcess } = reap([proc(40, PAYLOAD_PYTHON, null), proc(41, PAYLOAD_PYTHON, '')]) - - expect(outcome.matched).toBe(0) - expect(killProcess).not.toHaveBeenCalled() - }) - - it('never kills itself', () => { - const { outcome, killProcess } = reap([proc(99, MAIN_EXE, `${MAIN_EXE} --app`)], { selfPid: 99 }) - - expect(outcome.matched).toBe(0) - expect(killProcess).not.toHaveBeenCalled() - }) - - it('skips pids the graceful backend teardown already owns', () => { - const { outcome } = reap( - [proc(30, MAIN_EXE, `${MAIN_EXE} --app`), proc(31, PAYLOAD_PYTHON, 'idle-python')], - { excludePids: [30] } - ) - - expect(outcome.killed).toEqual([]) - }) - - it('leaves a process whose path cannot be read alone', () => { - // Missing one pinner reproduces a bug we already have; killing an - // unidentified process is unbounded damage. - const { outcome, killProcess } = reap([proc(40, null)]) - - expect(outcome.matched).toBe(0) - expect(killProcess).not.toHaveBeenCalled() - }) - - it('keeps going when one kill throws, and reports it', () => { - const killProcess = vi.fn((pid: number) => { - if (pid === 50) { - throw new Error('Access is denied') - } - }) - - const outcome = reapPackageRootedProcesses({ - installRoots: [ROOT], - listProcesses: () => [proc(50, GPG_AGENT, DAEMON_CMDLINE), proc(51, GPG_AGENT, DAEMON_CMDLINE)], - killProcess, - selfPid: 1, - isWindows: true - }) - - expect(outcome.failed).toEqual([50]) - expect(outcome.killed).toEqual([51]) - }) - - it('never lets a failed enumeration break quit', () => { - const outcome = reapPackageRootedProcesses({ - installRoots: [ROOT], - listProcesses: () => { - throw new Error('enumeration failed') - }, - killProcess: vi.fn(), - selfPid: 1, - isWindows: true - }) - - expect(outcome.skipped).toBe(true) - expect(outcome.killed).toEqual([]) - }) - - it('is a no-op on POSIX and when no install root resolves', () => { - const killProcess = vi.fn() - - const posix = reapPackageRootedProcesses({ - installRoots: [ROOT], - listProcesses: () => [proc(60, MAIN_EXE, `${MAIN_EXE} --app`)], - killProcess, - selfPid: 1, - isWindows: false - }) - - const rootless = reapPackageRootedProcesses({ - installRoots: [null, ''], - listProcesses: () => [proc(61, MAIN_EXE, `${MAIN_EXE} --app`)], - killProcess, - selfPid: 1, - isWindows: true - }) - - expect(posix.skipped).toBe(true) - expect(rootless.skipped).toBe(true) - expect(killProcess).not.toHaveBeenCalled() - }) + expect(outcome.killed).toEqual(killed) + expect(outcome.matched).toBe(killed.length) + expect(signalled).toEqual(killed) }) -describe('protectedRuntimePids', () => { - it('extends protection transitively through parentage and stays empty with no runtime', () => { - const running = [ - proc(10, PAYLOAD_PYTHON, GATEWAY_CMDLINE, 2), - proc(11, PAYLOAD_PYTHON, 'worker', 10), - proc(12, PAYLOAD_PYTHON, 'grandchild', 11), - proc(13, GPG_AGENT, 'gpg-agent --daemon', null) - ] +it('continues after kill failure and refuses absent roots or failed enumeration', (): void => { + const processes: RunningProcess[] = [proc(50, GPG_AGENT), proc(51, GPG_AGENT)] - expect(protectedRuntimePids(running)).toEqual(new Set([10, 11, 12])) - expect(protectedRuntimePids([proc(14, GPG_AGENT, 'gpg-agent --daemon')])).toEqual(new Set()) - }) + const base: Parameters[0] = { + installRoots: [ROOT], isWindows: true, selfPid: 1, + listProcesses: (): RunningProcess[] => processes, + killProcess: (pid: number): void => { if (pid === 50) { throw new Error('Access denied') } } + } + + expect(reapPackageRootedProcesses(base)).toMatchObject({ failed: [50], killed: [51] }) + + for (const overrides of [{ isWindows: false }, { installRoots: [null, ''] }, { listProcesses: (): never => { throw new Error('enumeration failed') } }]) { + const killProcess = vi.fn<(pid: number) => void>() + expect(reapPackageRootedProcesses({ ...base, ...overrides, killProcess })).toMatchObject({ skipped: true, killed: [] }) + expect(killProcess).not.toHaveBeenCalled() + } }) describe('listWindowsProcesses', () => { diff --git a/apps/desktop/electron/pool-stop.test.ts b/apps/desktop/electron/pool-stop.test.ts index c6cc06c63c..abad62d556 100644 --- a/apps/desktop/electron/pool-stop.test.ts +++ b/apps/desktop/electron/pool-stop.test.ts @@ -116,6 +116,7 @@ test('stopAll waits for current and already-stopping backends', async () => { }) assert.equal(pool.size, 0) + assert.equal(stopper.hasPending(), true) assert.equal(a.killed, true) assert.equal(b.killed, true) @@ -127,30 +128,6 @@ test('stopAll waits for current and already-stopping backends', async () => { exitResolvers.get(a)?.() await Promise.all([all, priorStop]) assert.equal(settled, true) -}) - -test('stopAll joins a stop whose pool entry was already evicted', async () => { - const { addChild, exitResolvers, pool, stopper } = harness() - const child = addChild('already-stopping') - - const first = stopper.stop('already-stopping') - - assert.equal(pool.size, 0) - assert.equal(stopper.hasPending(), true) - - let settled = false - - const all = stopper.stopAll().then(() => { - settled = true - }) - - await Promise.resolve() - - assert.equal(settled, false) - - exitResolvers.get(child)?.() - await Promise.all([first, all]) - assert.equal(settled, true) assert.equal(stopper.hasPending(), false) }) diff --git a/apps/desktop/electron/product-identity.test.ts b/apps/desktop/electron/product-identity.test.ts index 1876ea3bdc..b287ebaada 100644 --- a/apps/desktop/electron/product-identity.test.ts +++ b/apps/desktop/electron/product-identity.test.ts @@ -117,104 +117,63 @@ test('nonstable runtime pins userData before the app name can change', async (): } }) -test('light identity is fully distinct from the full identity', async (): Promise => { - const full: ProductIdentity = await identityForVariant(undefined) - const light: ProductIdentity = await identityForVariant('light') +test.each([ + [undefined, 'Hermes', 'hermes', 'latest', 'canary'], + ['bundled', 'Hermes Agent', 'hermes', 'latest', 'canary'], + ['light', 'Hermes Light', 'hermes-light', 'light', 'light-canary'] +] as const)('%s separates stable, canary and independent commits', async (variant: string | undefined, display: string, cli: string, channel: string, canaryChannel: string): Promise => { + const stable: ProductIdentity = await identityForVariant(variant) + assert.equal(stable.displayName, display) + assert.equal(stable.channel, channel) + assert.equal(stable.light, variant === 'light') + assert.equal(stable.storeMsix, undefined) + const identities: ProductIdentity[] = [stable] - assert.equal(light.light, true) + for (const [tag, commit, expectedCli, expectedChannel] of [ + ['v1.2.3-canary.20260818', '', `${cli}-canary`, canaryChannel], + ['', 'abcdef1234567890abcdef1234567890abcdef12', `${cli}-abcdef1`, null], + ['', '1234567890abcdef1234567890abcdef12345678', `${cli}-1234567`, null] + ] as const) { + process.env.HERMES_PAYLOAD_TAG = tag + process.env.HERMES_BUILD_COMMIT = commit + const current: ProductIdentity = await identityForVariant(variant) + assert.equal(current.channel, expectedChannel) + assert.equal(current.cliName, expectedCli) + assert.equal(current.windowsExecutableName, expectedCli) + assert.equal(current.artifactNamePascal, stable.artifactNamePascal) + assert.deepEqual(current, await identityForVariant(variant)) - // Enumerate the OS-visible identity markers explicitly rather than looping - // Object.keys: `store` is a build-mode flag, legitimately equal (false) - // across variants, so a keys-loop would fail for the wrong reason. Only the - // markers Windows/electron keys on must differ for side-by-side installs. - for (const prop of ['displayName', 'appId', 'appNamePascal', 'msixAppIdWithOrg', 'channel'] as const) { - assert.notEqual(light[prop], full[prop], `${prop} must differ between light and full`) - } -}) + if (commit) { assert.equal(current.displayName, `${display} ${commit.slice(0, 7)}`) } -test('a canary payload tag moves BOTH variants onto their canary feed channel', async (): Promise => { - process.env.HERMES_PAYLOAD_TAG = 'v0.28.0-canary.20260818' - const full: ProductIdentity = await identityForVariant(undefined) - assert.equal(full.channel, 'canary') + for (const previous of identities) { + for (const field of ['displayName', 'appId', 'appNamePascal', 'msixAppIdWithOrg', 'windowsExecutableName', 'cliName'] as const) { + assert.notEqual(current[field], previous[field], `${field} must isolate installations`) - process.env.HERMES_PAYLOAD_TAG = 'v0.28.0-canary.20260818' - const light: ProductIdentity = await identityForVariant('light') - assert.equal(light.channel, 'light-canary') -}) - -test('canary installs alongside stable with its own GUI and CLI names', async (): Promise => { - for (const variant of [undefined, 'bundled', 'light']) { - delete process.env.HERMES_PAYLOAD_TAG - const stable: ProductIdentity = await identityForVariant(variant) - process.env.HERMES_PAYLOAD_TAG = 'v0.28.0-canary.20260818' - const canary: ProductIdentity = await identityForVariant(variant) - - for (const prop of [ - 'displayName', - 'appId', - 'appNamePascal', - 'msixAppIdWithOrg', - 'windowsExecutableName', - 'cliName' - ] as const) { - assert.notEqual(canary[prop], stable[prop], `${prop} must isolate canary`) + if (commit) { assert.ok(current[field].includes(commit.slice(0, 7))) } + } } - assert.equal(canary.artifactNamePascal, stable.artifactNamePascal) - assert.equal(canary.cliName, variant === 'light' ? 'hermes-light-canary' : 'hermes-canary') - assert.equal(canary.windowsExecutableName, canary.cliName) + identities.push(current) } -}) -test('each commit owns a deterministic identity and has no release channel', async (): Promise => { - const firstSha: string = 'abcdef1234567890abcdef1234567890abcdef12' - const secondSha: string = '1234567890abcdef1234567890abcdef12345678' - - for (const variant of [undefined, 'bundled', 'light']) { - delete process.env.HERMES_BUILD_COMMIT - const stable: ProductIdentity = await identityForVariant(variant) - process.env.HERMES_BUILD_COMMIT = firstSha - const first: ProductIdentity = await identityForVariant(variant) - assert.deepEqual(first, await identityForVariant(variant)) - process.env.HERMES_BUILD_COMMIT = secondSha - const second: ProductIdentity = await identityForVariant(variant) - - for (const prop of [ - 'displayName', - 'appId', - 'appNamePascal', - 'msixAppIdWithOrg', - 'windowsExecutableName', - 'cliName' - ] as const) { - assert.notEqual(first[prop], stable[prop], `${prop} must isolate commit from stable`) - assert.notEqual(first[prop], second[prop], `${prop} must isolate two commits`) - assert.ok(first[prop].includes(firstSha.slice(0, 7))) - } - - assert.equal(first.channel, null) - assert.equal(first.cliName, `${variant === 'light' ? 'hermes-light' : 'hermes'}-${firstSha.slice(0, 7)}`) - assert.equal(first.artifactNamePascal, stable.artifactNamePascal) - } -}) - -test('a commit build names the SHA in the display name', async (): Promise => { - process.env.HERMES_BUILD_COMMIT = 'abcdef1234567890abcdef1234567890abcdef12' - const full: ProductIdentity = await identityForVariant(undefined) - assert.equal(full.displayName, 'Hermes abcdef1') - - const bundled: ProductIdentity = await identityForVariant('bundled') - assert.equal(bundled.displayName, 'Hermes Agent abcdef1') - - delete process.env.HERMES_BUILD_COMMIT - const plain: ProductIdentity = await identityForVariant(undefined) - assert.equal(plain.displayName, 'Hermes') - - // Malformed commit values must not leak into the name (commit builds - // validate the full SHA elsewhere; the display derivation stays total). process.env.HERMES_BUILD_COMMIT = 'not-a-sha' - const malformed: ProductIdentity = await identityForVariant(undefined) - assert.equal(malformed.displayName, 'Hermes') + process.env.HERMES_PAYLOAD_TAG = 'v1.2.3' + assert.deepEqual(await identityForVariant(variant), stable) +}) + +test('light and bundled retain distinct OS markers from the full client', async (): Promise => { + const full: ProductIdentity = await identityForVariant(undefined) + + for (const variant of ['bundled', 'light']) { + const other: ProductIdentity = await identityForVariant(variant) + + for (const field of ['displayName', 'appId', 'appNamePascal'] as const) { assert.notEqual(other[field], full[field]) } + + if (variant === 'light') { + assert.notEqual(other.msixAppIdWithOrg, full.msixAppIdWithOrg) + assert.notEqual(other.channel, full.channel) + } + } }) test('packaging isolates boot metadata and executable names without renaming release artifacts', async (): Promise => { @@ -277,25 +236,6 @@ test('packaging isolates boot metadata and executable names without renaming rel } }) -test('stable tags and tagless dev builds publish to the stable channels', async (): Promise => { - process.env.HERMES_PAYLOAD_TAG = 'v0.28.0' - assert.equal((await identityForVariant(undefined)).channel, 'latest') - - delete process.env.HERMES_PAYLOAD_TAG - assert.equal((await identityForVariant('light')).channel, 'light') -}) - -test('bundled variant has a distinct identity from the full variant', async (): Promise => { - const full: ProductIdentity = await identityForVariant(undefined) - const bundled: ProductIdentity = await identityForVariant('bundled') - - assert.equal(bundled.light, false) - assert.notEqual(bundled.displayName, full.displayName) - assert.notEqual(bundled.appNamePascal, full.appNamePascal) - assert.notEqual(bundled.appId, full.appId) - assert.equal(bundled.channel, 'latest') -}) - test('store inherits the bundled app identity (shared userData) but swaps the MSIX packaging identity', async (): Promise => { const bundled: ProductIdentity = await identityForVariant('bundled') const store: ProductIdentity = await identityForVariant('store') diff --git a/apps/desktop/electron/updater/app-installer-strategy.test.ts b/apps/desktop/electron/updater/app-installer-strategy.test.ts index aa9ccfe373..0a887c66e3 100644 --- a/apps/desktop/electron/updater/app-installer-strategy.test.ts +++ b/apps/desktop/electron/updater/app-installer-strategy.test.ts @@ -7,7 +7,9 @@ import { describe, expect, it } from 'vitest' import { AppInstallerStrategy } from './app-installer' import type { AppInstallerStrategyDeps } from './app-installer' -function makeDeps(over: Partial = {}) { +interface StrategyFixture { deps: AppInstallerStrategyDeps; calls: string[] } + +function makeDeps(over: Partial = {}): StrategyFixture { const calls: string[] = [] const deps: AppInstallerStrategyDeps = { @@ -40,15 +42,6 @@ function makeDeps(over: Partial = {}) { } describe('AppInstallerStrategy.apply', () => { - it('writes the relaunch marker before teardown, trigger, and quit — order is the contract', async () => { - const { deps, calls } = makeDeps() - const strategy = new AppInstallerStrategy(deps) - const result = await strategy.apply() - - expect(result).toEqual({ ok: true, manual: false, bundled: true, handedOff: true, mechanism: 'app-installer' }) - expect(calls).toEqual(['prepare', 'relaunch-marker', 'teardown', 'open', 'quit']) - }) - it('fails open: a marker-write failure never blocks the update', async () => { const progress: string[] = [] @@ -90,19 +83,48 @@ describe('AppInstallerStrategy.apply', () => { }) }) -describe('AppInstallerStrategy.check', () => { - it('threads the OS checker result onto the mechanism wire', async () => { - const { deps } = makeDeps({ run: async () => ({ code: 0, stdout: '{"available": true}' }) }) - const status = await new AppInstallerStrategy(deps).check() - expect(status.mechanism).toBe('app-installer') - expect(status.updateAvailable).toBe(true) - expect(status.error).toBeUndefined() +it.each([ + [0, '{"available":true,"availability":"Available"}', true, undefined], + [0, '{"available":false}', false, undefined], + [2, '{"available":null,"error":"winrt missing"}', false, 'winrt missing'], + [0, '', false, 'checker returned no availability'], + [1, 'boom', false, 'checker exited 1'], + [0, '{"available":"yes"}', false, 'checker returned no availability'] +] as const)('checker %s %s → available=%s error=%s', async (code: number, stdout: string, available: boolean, error: string | undefined): Promise => { + const { deps }: ReturnType = makeDeps({ + run: async (python: string, script: string): Promise<{ code: number; stdout: string }> => { + expect([python, script]).toEqual(['python.exe', 'check.py']) + + return { code, stdout } + } }) - it('unknown availability is an error on the wire, never "no update"', async () => { - const { deps } = makeDeps({ run: async () => ({ code: 1, stdout: '{"available": null, "error": "winrt missing"}' }) }) - const status = await new AppInstallerStrategy(deps).check() - expect(status.updateAvailable).toBe(false) - expect(status.error).toBe('winrt missing') + expect(await new AppInstallerStrategy(deps).check()).toMatchObject({ + supported: true, mechanism: 'app-installer', currentVersion: '0.18.2', updateAvailable: available, error }) }) + +it.each([ + ['stable', false, 'win32/stable/stable.appinstaller'], + ['canary', false, 'win32/canary/canary.appinstaller'], + ['stable', true, 'win32/light/stable/stable.appinstaller'], + ['canary', true, 'win32/light/canary/canary.appinstaller'] +] as const)('stages %s light=%s from its feed and reports open errors', async (channel: 'stable' | 'canary', light: boolean, suffix: string): Promise => { + const { deps, calls }: ReturnType = makeDeps({ channel, light, + installer: { + prepare: async (url: string): Promise => { + expect(url).toBe(`https://updates.example/hermes-desktop/${suffix}`) + + return 'update.appinstaller' + }, + open: async (file: string): Promise => { + expect(file).toBe('update.appinstaller') + + return 'No file association' + } + } + }) + + await expect(new AppInstallerStrategy(deps).apply()).rejects.toThrow('No file association') + expect(calls).toEqual(['relaunch-marker', 'teardown', 'restore']) +}) diff --git a/apps/desktop/electron/updater/relaunch-isolation.test.ts b/apps/desktop/electron/updater/relaunch-isolation.test.ts index 80bc8041f8..faf4765d23 100644 --- a/apps/desktop/electron/updater/relaunch-isolation.test.ts +++ b/apps/desktop/electron/updater/relaunch-isolation.test.ts @@ -87,6 +87,9 @@ test('writes and startup consumption stay in each installation despite a shared assert.equal(fs.existsSync(marker(stable)), false) assert.equal(fs.readFileSync(marker(canary), 'utf8'), nextCanaryContents) assert.equal(fs.readFileSync(globalMarker, 'utf8'), legacyContents) + fs.writeFileSync(marker(commit), 'not json') + assert.deepEqual(consumePendingRelaunch(commit, 'commit-build'), { wasUpdateRelaunch: false, fromVersion: undefined }) + assert.equal(fs.existsSync(marker(commit)), false) }) test('cancellation and failed registration remove only their own installation marker', async (): Promise => { @@ -98,18 +101,24 @@ test('cancellation and failed registration remove only their own installation ma let cancelled: number = 0 for (const automatic of [true, false]) { - const registration: RelaunchRegistration = await registerUpdateRelaunch(canary, 'canary-old', { - relaunch: (): RelaunchWaiterHandle | undefined => - automatic - ? { - cancel: async (): Promise => { - cancelled++ - } - } - : undefined + let resolveReady!: (handle: RelaunchWaiterHandle | undefined) => void + const ready: Promise = new Promise((resolve: (handle: RelaunchWaiterHandle | undefined) => void): void => { resolveReady = resolve }) + let registered: boolean = false + + const pending: Promise = registerUpdateRelaunch(canary, 'canary-old', { + relaunch: (): Promise => ready + }).then((result: RelaunchRegistration): RelaunchRegistration => { + registered = true + + return result }) + await new Promise(setImmediate) + assert.equal(registered, false) assert.equal(fs.existsSync(marker(canary)), true) + resolveReady(automatic ? { cancel: async (): Promise => { cancelled++ } } : undefined) + const registration: RelaunchRegistration = await pending + assert.equal(registration.automatic, automatic) await Promise.all([registration.cancel(), registration.cancel()]) assert.equal(fs.existsSync(marker(canary)), false) assert.equal(fs.readFileSync(marker(stable), 'utf8'), stableContents) @@ -128,15 +137,20 @@ test('cancellation and failed registration remove only their own installation ma assert.equal(fs.existsSync(marker(canary)), false) assert.equal(fs.readFileSync(marker(stable), 'utf8'), stableContents) + let attempts: number = 0 + const failedCancellation: RelaunchRegistration = await registerUpdateRelaunch(canary, 'canary-old', { relaunch: (): RelaunchWaiterHandle => ({ cancel: async (): Promise => { + attempts++ throw failure } }) }) await assert.rejects(failedCancellation.cancel(), AggregateError) + await assert.rejects(failedCancellation.cancel(), AggregateError) + assert.equal(attempts, 1) assert.equal(fs.existsSync(marker(canary)), false) assert.equal(fs.readFileSync(marker(stable), 'utf8'), stableContents) assert.equal(fs.existsSync(path.join(hermesHome, PENDING_RELAUNCH_FILENAME)), false) @@ -150,4 +164,20 @@ test('cancellation and failed registration remove only their own installation ma assert.equal(fs.existsSync(marker(stable)), false) assert.equal(fs.readFileSync(marker(canary), 'utf8'), siblingContents) await sibling.cancel() + + const blocked: RelaunchRegistration = await registerUpdateRelaunch(canary, 'old', { + relaunch: (): RelaunchWaiterHandle => ({ cancel: async (): Promise => { throw failure } }) + }) + + fs.unlinkSync(marker(canary)) + fs.mkdirSync(marker(canary)) + fs.writeFileSync(path.join(marker(canary), 'foreign-data'), 'keep') + await assert.rejects(blocked.cancel(), (error: Error): boolean => { + assert.ok(error instanceof AggregateError) + assert.equal(error.errors[0], failure) + assert.equal(error.errors.length, 2) + + return true + }) + assert.equal(fs.readFileSync(path.join(marker(canary), 'foreign-data'), 'utf8'), 'keep') }) diff --git a/apps/desktop/electron/updater/relaunch-registration.test.ts b/apps/desktop/electron/updater/relaunch-registration.test.ts deleted file mode 100644 index da2aa112c8..0000000000 --- a/apps/desktop/electron/updater/relaunch-registration.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' - -import { test } from 'vitest' - -import { PENDING_RELAUNCH_FILENAME, registerUpdateRelaunch, type RelaunchRegistration } from './relaunch' -import type { RelaunchWaiterHandle } from './relaunch-waiter' - -for (const automatic of [true, false]) { - test(`registration owns its marker and cancellation (automatic=${automatic})`, async () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), 'relaunch-registration-')) - const marker = path.join(home, PENDING_RELAUNCH_FILENAME) - let resolveReady!: (handle: RelaunchWaiterHandle | undefined) => void - const ready = new Promise(resolve => { resolveReady = resolve }) - let cancelled = 0 - let registered = false - - try { - const pending: Promise = registerUpdateRelaunch({ getPath: (): string => home }, '1.0', { relaunch: (): Promise => ready }) - .then(result => { registered = true; - - return result }) - - await new Promise(setImmediate) - assert.equal(registered, false) - assert.equal(JSON.parse(fs.readFileSync(marker, 'utf8')).fromVersion, '1.0') - resolveReady(automatic ? { cancel: async () => { cancelled++ } } : undefined) - const registration = await pending - assert.equal(registration.automatic, automatic) - assert.equal(fs.existsSync(marker), true) - await Promise.all([registration.cancel(), registration.cancel()]) - await registration.cancel() - assert.equal(cancelled, automatic ? 1 : 0) - assert.equal(fs.existsSync(marker), false) - } finally { - fs.rmSync(home, { recursive: true, force: true }) - } - }) -} - -test('start and cancellation failures preserve the cause and still clean owned markers', async () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), 'relaunch-failures-')) - const marker = path.join(home, PENDING_RELAUNCH_FILENAME) - const failure = new Error('owned child refused to stop') - - try { - await assert.rejects(registerUpdateRelaunch({ getPath: (): string => home }, '1.0', { - relaunch: async () => { throw failure } - }), error => error === failure) - assert.equal(fs.existsSync(marker), false) - - let attempts = 0 - - const registration: RelaunchRegistration = await registerUpdateRelaunch({ getPath: (): string => home }, '1.0', { - relaunch: async () => ({ cancel: async () => { attempts++; throw failure } }) - }) - - await assert.rejects(registration.cancel(), error => error instanceof AggregateError && error.errors.includes(failure)) - await assert.rejects(registration.cancel(), error => error instanceof AggregateError && error.errors.includes(failure)) - assert.equal(attempts, 1) - assert.equal(fs.existsSync(marker), false) - - const blocked: RelaunchRegistration = await registerUpdateRelaunch({ getPath: (): string => home }, '1.0', { - relaunch: async () => ({ cancel: async () => { throw failure } }) - }) - - fs.unlinkSync(marker) - fs.mkdirSync(marker) - fs.writeFileSync(path.join(marker, 'foreign-data'), 'keep') - await assert.rejects(blocked.cancel(), error => { - assert.ok(error instanceof AggregateError) - assert.equal(error.errors[0], failure) - assert.equal(error.errors.length, 2) - - return true - }) - assert.equal(fs.readFileSync(path.join(marker, 'foreign-data'), 'utf8'), 'keep') - } finally { - fs.rmSync(home, { recursive: true, force: true }) - } -}) diff --git a/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts b/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts index a7b75f2f34..9bca5a65dd 100644 --- a/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts +++ b/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts @@ -6,9 +6,9 @@ import path from 'node:path' import { test, vi } from 'vitest' -import { type SpawnWaiter, startRelaunchWaiter } from './relaunch-waiter' +import { type RelaunchWaiterHandle, type SpawnWaiter, startRelaunchWaiter } from './relaunch-waiter' -const scriptPath = path.resolve(import.meta.dirname, '../../scripts/update-relaunch-waiter.ps1') +const scriptPath: string = path.resolve(import.meta.dirname, '../../scripts/update-relaunch-waiter.ps1') async function stop(child: ChildProcess | undefined): Promise { if (child?.pid && child.exitCode === null && child.signalCode === null) { @@ -22,27 +22,39 @@ for (const mode of [ { name: 'ready', ready: true }, { name: 'silent', ready: false }, { name: 'spawn-error', ready: false, missing: true }, + { name: 'early-exit', ready: false, earlyExit: true }, { name: 'cancel-timeout', ready: true, refuseKill: true }, { name: 'startup-cancel-timeout', ready: false, refuseKill: true }, { name: 'cleanup-error', ready: true, refuseCleanup: true } ]) { - test(`waiter ownership survives its complete lifecycle (${mode.name})`, async () => { + test(`waiter ownership survives its complete lifecycle (${mode.name})`, async (): Promise => { let child: ChildProcess | undefined let originalKill: ChildProcess['kill'] | undefined - let stage = '' - let closed = false - const cleanupError = new Error('fixture staging cleanup refused') + let stage: string = '' + let closed: boolean = false + const cleanupError: Error = new Error('fixture staging cleanup refused') - const start: SpawnWaiter = (_command, args, options) => { + const start: SpawnWaiter = (command: string, args: string[], options: Parameters[2]): ChildProcess => { stage = options.cwd - const readyFile = args[args.indexOf('-ReadyFile') + 1] + const readyFile: string = path.join(stage, 'ready.txt') + assert.equal(command, path.win32.join(process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')) + assert.deepEqual(options, { cwd: stage, detached: true, stdio: 'ignore', windowsHide: true }) + assert.notEqual(stage, path.dirname(scriptPath)) + assert.deepEqual(fs.readFileSync(path.join(stage, 'update-relaunch-waiter.ps1')), fs.readFileSync(scriptPath)) + assert.deepEqual(args, [ + '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', + '-File', path.join(stage, 'update-relaunch-waiter.ps1'), + '-ProcessId', String(process.pid), '-ProcessStartTimeMs', '1000000', + '-IdentityName', 'disposable-waiter-test', '-ReadyFile', readyFile, '-TimeoutSeconds', '900' + ]) child = spawn(mode.missing ? path.join(stage, 'missing.exe') : process.execPath, ['-e', ` const fs = require('node:fs'); + if (process.env.TEST_EXIT === 'yes') process.exit(3); if (process.env.TEST_READY === 'yes') fs.writeFileSync(process.env.READY_FILE, 'ready'); setInterval(() => {}, 1000); `], { ...options, - env: { ...process.env, READY_FILE: readyFile, TEST_READY: mode.ready ? 'yes' : 'no' } + env: { ...process.env, READY_FILE: readyFile, TEST_READY: mode.ready ? 'yes' : 'no', TEST_EXIT: mode.earlyExit ? 'yes' : 'no' } }) originalKill = child.kill.bind(child) @@ -53,9 +65,9 @@ for (const mode of [ } try { - const starting = startRelaunchWaiter({ + const starting: Promise = startRelaunchWaiter({ processId: process.pid, - processStartTimeMs: Date.now(), + processStartTimeMs: 1_000_000, identityName: 'disposable-waiter-test', scriptPath }, { spawn: start, handshakeTimeoutMs: mode.ready ? 10_000 : 2_000, cancelTimeoutMs: 2_000, pollMs: 20 }) @@ -113,3 +125,12 @@ for (const mode of [ } }, 20_000) } + +test('missing scripts refuse startup before spawning a waiter', async (): Promise => { + let spawned: boolean = false + assert.equal(await startRelaunchWaiter({ + processId: process.pid, processStartTimeMs: 1_000_000, + identityName: 'disposable-waiter-test', scriptPath: path.join(scriptPath, 'absent.ps1') + }, { spawn: (): never => { spawned = true; throw new Error('missing scripts must not spawn') } }), undefined) + assert.equal(spawned, false) +}) diff --git a/apps/desktop/electron/updater/relaunch-waiter.test.ts b/apps/desktop/electron/updater/relaunch-waiter.test.ts deleted file mode 100644 index 3913bb326d..0000000000 --- a/apps/desktop/electron/updater/relaunch-waiter.test.ts +++ /dev/null @@ -1,199 +0,0 @@ -// updater/relaunch-waiter.test.ts — staging, argv, and the ready/error -// handshake contract. No PowerShell is spawned: the spawn point is injected -// and the handshake file is written by the test (as the real script would), -// so the parent-side race contract is exercised without touching a package. - -import { EventEmitter } from 'node:events' -import * as fs from 'node:fs' -import * as os from 'node:os' -import * as path from 'node:path' - -import { afterEach, describe, expect, it } from 'vitest' - -import { - buildRelaunchWaiterArgs, - POWERSHELL_PATH, - RELAUNCH_WAITER_READY_FILENAME, - RELAUNCH_WAITER_SCRIPT, - type SpawnWaiter, - startRelaunchWaiter -} from './relaunch-waiter' - -const OPTIONS = { - processId: 4242, - processStartTimeMs: 1_000_000, - identityName: 'NousResearch.HermesBundled', - scriptPath: '/payload/apps/desktop/scripts/update-relaunch-waiter.ps1' -} - -const tempDirs: string[] = [] - -afterEach(() => { - for (const dir of tempDirs.splice(0)) { - fs.rmSync(dir, { recursive: true, force: true }) - } -}) - -function fakeSpawn(handshake: 'ready' | 'error' | 'exit-nonzero' | 'none'): { spawn: SpawnWaiter; seen: any } { - const seen: any = {} - - const spawn: SpawnWaiter = (_command, args, opts) => { - seen.command = _command - seen.args = args - seen.opts = opts - tempDirs.push(opts.cwd) - - const child: any = new EventEmitter() - - child.pid = handshake === 'error' ? undefined : 123 - - child.unref = () => {} - - child.kill = () => { - seen.killed = true - child.emit('exit', null) - child.emit('close', null) - } - - const readyFile = args[args.indexOf('-ReadyFile') + 1] - - queueMicrotask(() => { - if (handshake === 'ready') { - fs.mkdirSync(path.dirname(readyFile), { recursive: true }) - fs.writeFileSync(readyFile, '0.18.1|Family|App') - } else if (handshake === 'error') { - child.emit('error', new Error('spawn ENOENT')) - child.emit('close', -1) - } else if (handshake === 'exit-nonzero') { - child.emit('exit', 3) - child.emit('close', 3) - } - }) - - return child - } - - return { spawn, seen } -} - -async function stageScript(): Promise { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'relaunch-waiter-test-')) - tempDirs.push(dir) - const file = path.join(dir, RELAUNCH_WAITER_SCRIPT) - fs.writeFileSync(file, '# stub\n') - - return file -} - -describe('buildRelaunchWaiterArgs', () => { - it('carries pid, start time, identity, ready file, and timeout as named parameters', () => { - const args = buildRelaunchWaiterArgs(OPTIONS, 'C:\\temp\\ready.txt') - - expect(args).toEqual([ - '-NoProfile', - '-NonInteractive', - '-ExecutionPolicy', - 'Bypass', - '-File', - OPTIONS.scriptPath, - '-ProcessId', - '4242', - '-ProcessStartTimeMs', - '1000000', - '-IdentityName', - 'NousResearch.HermesBundled', - '-ReadyFile', - 'C:\\temp\\ready.txt', - '-TimeoutSeconds', - '900' - ]) - }) -}) - -describe('startRelaunchWaiter', () => { - it('stages the script into a fresh temp dir and spawns the absolute PowerShell from there', async () => { - const scriptPath = await stageScript() - const { spawn, seen } = fakeSpawn('ready') - - const result = await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 }) - - expect(result).toHaveProperty('cancel') - expect(seen.command).toBe(POWERSHELL_PATH) - expect(seen.opts.detached).toBe(true) - expect(seen.opts.stdio).toBe('ignore') - expect(seen.opts.windowsHide).toBe(true) - // The child runs from the staged dir, not the payload — nothing - // inherited from the package may hold the swap open. - expect(seen.opts.cwd).not.toBe(path.dirname(scriptPath)) - expect(seen.args).toContain('-File') - const stagedScript = seen.args[seen.args.indexOf('-File') + 1] - expect(stagedScript).not.toBe(scriptPath) - expect(fs.existsSync(stagedScript)).toBe(true) - }) - - it('retains cancellation after the ready-file handshake', async () => { - const scriptPath = await stageScript() - const { spawn } = fakeSpawn('ready') - - const result = await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 }) - - expect(result).toHaveProperty('cancel') - await result!.cancel() - }) - - it('returns no handle after a failed spawn closes', async () => { - const scriptPath = await stageScript() - const { spawn } = fakeSpawn('error') - - const result = await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 }) - - expect(result).toBeUndefined() - }) - - it('returns no handle on an early exit without readiness', async () => { - const scriptPath = await stageScript() - const { spawn } = fakeSpawn('exit-nonzero') - - const result = await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 }) - - expect(result).toBeUndefined() - }) - - it('stops the child before returning when readiness times out', async () => { - const scriptPath = await stageScript() - const { spawn, seen } = fakeSpawn('none') - - const result = await startRelaunchWaiter( - { ...OPTIONS, scriptPath }, - { spawn, handshakeTimeoutMs: 80, pollMs: 20 } - ) - - expect(result).toBeUndefined() - expect(seen.killed).toBe(true) - expect(fs.existsSync(seen.opts.cwd)).toBe(false) - }, 5_000) - - it('returns no handle when a missing script leaves no staging', async () => { - const spawn = (() => { - throw new Error('should not be reached') - }) as unknown as SpawnWaiter - - const result = await startRelaunchWaiter( - { ...OPTIONS, scriptPath: path.join(os.tmpdir(), 'definitely-missing.ps1') }, - { spawn } - ) - - expect(result).toBeUndefined() - }) - - it('the staged handshake file uses the reserved ready filename', async () => { - const scriptPath = await stageScript() - const { spawn, seen } = fakeSpawn('ready') - - await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 }) - - const readyFile = seen.args[seen.args.indexOf('-ReadyFile') + 1] - - expect(path.basename(readyFile)).toBe(RELAUNCH_WAITER_READY_FILENAME) - }) -}) diff --git a/apps/desktop/electron/updater/updater.test.ts b/apps/desktop/electron/updater/updater.test.ts index ea04bff9f5..42645eb049 100644 --- a/apps/desktop/electron/updater/updater.test.ts +++ b/apps/desktop/electron/updater/updater.test.ts @@ -5,9 +5,7 @@ import { describe, expect, it } from 'vitest' import { buildStampPayload } from '../../scripts/write-build-stamp.mjs' -import { appInstallerCheckToStatus, parseCheckOutput } from './app-installer' import { buildManualUpdateCommand } from './checkout' -import { type ConsumedRelaunch, consumePendingRelaunch, PENDING_RELAUNCH_FILENAME, registerUpdateRelaunch, type RelaunchRegistration, writePendingRelaunch } from './relaunch' import { resolveUpdaterMechanism } from './index' @@ -25,15 +23,19 @@ describe('build stamp → update ownership', () => { ['win32', 'light', 'external', 'external'], ['darwin', 'bundled', 'electron-updater', 'electron-updater'], ['darwin', 'light', 'electron-updater', 'electron-updater'], + ['darwin', 'store', 'microsoft-store', 'microsoft-store'], ['linux', 'bundled', 'external', 'external'], ['linux', 'light', 'external', 'external'], ['win32', '', 'self', 'windows-handoff'], ['darwin', '', 'self', 'posix-handoff'], ['linux', '', 'self', 'posix-handoff'] ] as const)('%s %s dispatches its declared owner without a Store flag', (platform, variant, declared, strategy) => { - const stamp = buildStampPayload(provenance, { HERMES_DESKTOP_VARIANT: variant }, platform, { runtime }) + const stamp: ReturnType = buildStampPayload(provenance, { HERMES_DESKTOP_VARIANT: variant, HERMES_PAYLOAD_TAG: 'v1.2.3' }, platform, { runtime }) expect(stamp.updateMechanism).toBe(declared) + expect(stamp.payload).toBe(variant === 'store' ? 'bundled' : variant || 'bootstrap') + expect(stamp.tag).toBe('v1.2.3') + expect(stamp.distribution).toBe('desktop-app') expect(stamp).not.toHaveProperty('store') expect(resolveUpdaterMechanism({ platform, updateMechanism: stamp.updateMechanism })).toBe(strategy) }) @@ -44,54 +46,6 @@ describe('build stamp → update ownership', () => { }) }) -describe('app-installer check → status wire', () => { - it('available true → updateAvailable, no error', () => { - const s = appInstallerCheckToStatus({ available: true }, '0.18.2') - expect(s.supported).toBe(true) - expect(s.mechanism).toBe('app-installer') - expect(s.updateAvailable).toBe(true) - expect(s.error).toBeUndefined() - }) - - it('available false → updateAvailable false, NO error (honest no-update)', () => { - const s = appInstallerCheckToStatus({ available: false }, '0.18.2') - expect(s.updateAvailable).toBe(false) - expect(s.error).toBeUndefined() - }) - - it('available null → updateAvailable false WITH error (honest unknown, never "no update")', () => { - const s = appInstallerCheckToStatus({ available: null, error: 'no winrt' }, '0.18.2') - expect(s.updateAvailable).toBe(false) - expect(s.error).toBe('no winrt') - }) -}) - -describe('parseCheckOutput', () => { - it('parses boolean true/false availability', () => { - expect(parseCheckOutput(0, '{"available": true, "availability": "Available"}')).toEqual({ - available: true, - availability: 'Available', - error: undefined - }) - expect(parseCheckOutput(0, '{"available": false}')).toEqual({ available: false, availability: undefined, error: undefined }) - }) - - it('available null surfaces the checker error', () => { - expect(parseCheckOutput(2, '{"available": null, "error": "winrt import failed"}')).toEqual({ - available: null, - error: 'winrt import failed' - }) - }) - - it('non-zero exit without parseable output names the exit code', () => { - expect(parseCheckOutput(1, 'boom')).toEqual({ available: null, error: 'checker exited 1' }) - }) - - it('exit 0 with no availability is unknown, not no-update', () => { - expect(parseCheckOutput(0, '')).toEqual({ available: null, error: 'checker returned no availability' }) - }) -}) - describe('buildManualUpdateCommand', () => { it('bare command on main and detached HEAD', () => { expect(buildManualUpdateCommand('main')).toBe('hermes update') @@ -103,93 +57,3 @@ describe('buildManualUpdateCommand', () => { expect(buildManualUpdateCommand('ethie/pm')).toBe('hermes update --branch ethie/pm') }) }) - -describe('pending relaunch marker', () => { - const KEY = PENDING_RELAUNCH_FILENAME - - function fakeFs(files: Record) { - const has = (f: string) => f.replace(/\\/g, '/').endsWith(`/${KEY}`) || f === KEY - - return { - existsSync: (f: string) => has(f), - readFileSync: (f: string) => files[Object.keys(files).find(k => k.replace(/\\/g, '/') === f.replace(/\\/g, '/')) ?? f], - unlinkSync: (f: string) => { - const key = Object.keys(files).find(k => k.replace(/\\/g, '/') === f.replace(/\\/g, '/')) - - if (key) {delete files[key]} - } - } - } - - it('write then consume on a different version = update relaunch', () => { - const files: Record = {} - expect(writePendingRelaunch({ getPath: (): string => '/home' }, '0.18.2', (f: string, c: string): void => { files[f] = c })).toBe(true) - expect(JSON.parse(Object.values(files)[0]).fromVersion).toBe('0.18.2') - - const r: ConsumedRelaunch = consumePendingRelaunch({ getPath: (): string => '/home' }, '0.18.3', fakeFs(files)) - expect(r.wasUpdateRelaunch).toBe(true) - expect(r.fromVersion).toBe('0.18.2') - // one-shot: consumed - expect(Object.keys(files)).toHaveLength(0) - }) - - it('same version = update never landed; marker consumed silently', () => { - const files: Record = {} - writePendingRelaunch({ getPath: (): string => '/home' }, '0.18.2', (f: string, c: string): void => { files[f] = c }) - - const r: ConsumedRelaunch = consumePendingRelaunch({ getPath: (): string => '/home' }, '0.18.2', fakeFs(files)) - expect(r.wasUpdateRelaunch).toBe(false) - expect(Object.keys(files)).toHaveLength(0) - }) - - it('no marker = normal launch', () => { - expect(consumePendingRelaunch({ getPath: (): string => '/home' }, '0.18.3', fakeFs({})).wasUpdateRelaunch).toBe(false) - }) - - it('corrupt marker is consumed and treated as unknown', () => { - const files: Record = {} - writePendingRelaunch({ getPath: (): string => '/home' }, '0.18.2', (f: string, c: string): void => { files[f] = c }) - - // corrupt the contents under the same key - for (const k of Object.keys(files)) {files[k] = 'not json'} - - const r: ConsumedRelaunch = consumePendingRelaunch({ getPath: (): string => '/home' }, '0.18.3', fakeFs(files)) - expect(r.wasUpdateRelaunch).toBe(false) - expect(Object.keys(files)).toHaveLength(0) - }) -}) - -describe('registerUpdateRelaunch — the mechanism, not just the marker', () => { - it('writes the marker AND starts the relaunch mechanism', async () => { - const files: Record = {} - let started = 0 - - const ok: RelaunchRegistration = await registerUpdateRelaunch( - { getPath: (): string => '/home' }, - '0.18.2', - { relaunch: () => { started += 1; - - return { cancel: async () => {} } } }, - (f: string, c: string): void => { files[f] = c } - ) - - expect(ok.automatic).toBe(true) - expect(started).toBe(1) - expect(Object.keys(files)).toHaveLength(1) - }) - - it('retains the marker when a safely failed waiter requires manual relaunch', async () => { - const files: Record = {} - - const ok: RelaunchRegistration = await registerUpdateRelaunch( - { getPath: (): string => '/home' }, - '0.18.2', - { relaunch: async () => undefined }, - (f: string, c: string): void => { files[f] = c } - ) - - expect(ok.automatic).toBe(false) - expect(Object.keys(files)).toHaveLength(1) - }) - -}) diff --git a/apps/desktop/scripts/audit-bundle-arch.test.mjs b/apps/desktop/scripts/audit-bundle-arch.test.mjs index ebcf8fdd87..4f479f5699 100644 --- a/apps/desktop/scripts/audit-bundle-arch.test.mjs +++ b/apps/desktop/scripts/audit-bundle-arch.test.mjs @@ -1,7 +1,11 @@ import assert from 'node:assert/strict' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { spawnSync } from 'node:child_process' import { test } from 'vitest' -import { archMatches, classifyHeader, findUnpackedDirs, isExemptPath, peArch } from '../scripts/audit-bundle-arch.mjs' +import { auditTree, archMatches, classifyHeader, findUnpackedDirs, isExemptPath, peArch } from '../scripts/audit-bundle-arch.mjs' // ─── header builders: the smallest buffers each format needs ─────────────── @@ -96,103 +100,68 @@ test('findUnpackedDirs matches electron-builder output shapes only', () => { ]) }) -// ─── the git exemption is PortableGit-shaped, not git-shaped ─────────────── - -test('PortableGit internals stay exempt under the payload store', () => { - // .NET assemblies report ia32 because they are format-neutral. - for (const relPath of [ - 'resources/agent-payload/tools/git-2.53.0-win32-x64/mingw64/bin/Avalonia.dll', - 'resources\\agent-payload\\tools\\git-2.53.0-win32-x64\\mingw64\\libexec\\git-core\\GitHub.dll', - 'resources\\agent-payload\\tools\\git-2.53.0-win32-x64\\usr\\libexec\\getprocaddr32.exe', - 'resources/agent-payload/tools/git-2.54.0-win32-arm64/clangarm64/libexec/git-core/msalruntime.dll' - ]) { - assert.equal(isExemptPath(relPath), true, relPath) - } +test.each([ + ['resources/agent-payload/tools/git-2.53.0-win32-x64/mingw64/bin/Avalonia.dll', true], + ['resources\\agent-payload\\tools\\git-2.53.0-win32-x64\\mingw64\\libexec\\git-core\\GitHub.dll', true], + ['resources\\agent-payload\\tools\\git-2.53.0-win32-x64\\usr\\libexec\\getprocaddr32.exe', true], + ['resources/agent-payload/tools/git-2.54.0-win32-arm64/clangarm64/libexec/git-core/msalruntime.dll', true], + ['resources/agent-payload/tools/git-2.53.0-linux-x64/bin/git', false], + ['resources/agent-payload/tools/git-2.53.0-darwin-arm64/libexec/git-core/git-remote-https', false], + ['resources/agent-payload/tools/python-3.11.16+20260814-linux-x64/lib/python3.11/site-packages/pip/_vendor/distlib/t32.exe', true], + ['resources/agent-payload/tools/python-3.11.16+20260814-linux-x64/lib/python3.11/site-packages/setuptools/cli.exe', true], + ['resources/agent-payload/venv/lib/python3.11/site-packages/setuptools/cli-32.exe', true], + ['resources/agent-payload/venv/Lib/site-packages/setuptools/cli.exe', true], + ['resources/agent-payload/venv/lib/python3.11/site-packages/discord/bin/libopus-0.x86.dll', true], + ['resources/agent-payload/venv/lib/python3.11/site-packages/discord/bin/libopus-0.x64.dll', true], + ['resources/agent-payload/venv/lib/python3.11/site-packages/pvporcupine/lib/mac/arm64/libpv_porcupine.dylib', true], + ['resources/agent-payload/venv/lib/python3.11/site-packages/pvporcupine/lib/raspberry-pi/arm11/libpv_porcupine.so', true], + ['resources/agent-payload/venv/lib/python3.11/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/attach_linux_amd64.so', true], + ['resources/agent-payload/venv/lib/python3.11/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/inject_dll_x86.exe', true], + ['resources/agent-payload/tools/agent-browser-0.35.1-win32-arm64/bin/agent-browser-win32-x64.exe', true], + ['resources\\agent-payload\\tools\\agent-browser-0.26.0-win32-arm64\\bin\\agent-browser-win32-x64.exe', true], + ['resources/agent-payload/tools/chromium-1208/chrome-win64/chrome.exe', true], + ['resources\\agent-payload\\tools\\chromium-1208\\chrome-win64\\chrome.dll', true], + ['resources/agent-payload/tools/chromium-1208/chrome-linux/chrome', false], + ['resources/agent-payload/tools/chromium-1208/chrome-mac-arm64/chrome', false], + ['resources/agent-payload/tools/chromium_headless_shell-1208/chrome-headless-shell-win64/chrome-headless-shell.exe', false], + ['resources/agent-payload/tools/chromium-1208/chrome-headless-shell-win64/chrome-headless-shell.exe', false], + ['resources/agent-payload/uv-cache/archive-v0/abc/setuptools/cli.exe', true], + ['resources\\agent-payload\\uv-cache\\archive-v0\\abc\\discord\\bin\\libopus-0.x64.dll', true], + ['resources/agent-payload/uv-cache/builds-v0/whatever/build.exe', true], + ['resources/agent-payload/tools/something-1.0-win32-arm64/bin/thing.exe', false], + ['resources/agent-payload/tools/uv-cache-1.0/tool.exe', false], + ['resources/agent-payload/hermes-agent/something.exe', false], +])('foreign architecture exemption %s → %s', (file, exempt) => { + assert.equal(isExemptPath(file), exempt) }) -test('a POSIX git store entry is audited', () => { - // posix uses system git; a linux/darwin git store has no mingw64/usr/cmd - // segment, so a wrong-arch binary there must fail the audit. - for (const relPath of [ - 'resources/agent-payload/tools/git-2.53.0-linux-x64/bin/git', - 'resources/agent-payload/tools/git-2.53.0-darwin-arm64/libexec/git-core/git-remote-https' - ]) { - assert.equal(isExemptPath(relPath), false, relPath) - } -}) - -test('pip and setuptools launcher stubs are exempt in the store and the venv', () => { - for (const relPath of [ - 'resources/agent-payload/tools/python-3.11.16+20260814-linux-x64/lib/python3.11/site-packages/pip/_vendor/distlib/t32.exe', - 'resources/agent-payload/tools/python-3.11.16+20260814-linux-x64/lib/python3.11/site-packages/setuptools/cli.exe', - 'resources/agent-payload/venv/lib/python3.11/site-packages/setuptools/cli-32.exe', - 'resources/agent-payload/venv/Lib/site-packages/setuptools/cli.exe' - ]) { - assert.equal(isExemptPath(relPath), true, relPath) - } -}) - -test('discord opus and pvporcupine multi-arch siblings are exempt', () => { - for (const relPath of [ - 'resources/agent-payload/venv/lib/python3.11/site-packages/discord/bin/libopus-0.x86.dll', - 'resources/agent-payload/venv/lib/python3.11/site-packages/discord/bin/libopus-0.x64.dll', - 'resources/agent-payload/venv/lib/python3.11/site-packages/pvporcupine/lib/mac/arm64/libpv_porcupine.dylib', - 'resources/agent-payload/venv/lib/python3.11/site-packages/pvporcupine/lib/raspberry-pi/arm11/libpv_porcupine.so', - 'resources/agent-payload/venv/lib/python3.11/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/attach_linux_amd64.so', - 'resources/agent-payload/venv/lib/python3.11/site-packages/debugpy/_vendored/pydevd/pydevd_attach_to_process/inject_dll_x86.exe' - ]) { - assert.equal(isExemptPath(relPath), true, relPath) - } -}) - -test('the emulated x64 agent-browser exe is exempt in a win32-arm64 payload', () => { - for (const relPath of [ - 'resources/agent-payload/tools/agent-browser-0.35.1-win32-arm64/bin/agent-browser-win32-x64.exe', - 'resources\\agent-payload\\tools\\agent-browser-0.26.0-win32-arm64\\bin\\agent-browser-win32-x64.exe' - ]) { - assert.equal(isExemptPath(relPath), true, relPath) - } - // A non-chromium x64 binary in the payload store still fails: the - // chromium exemption is scoped to the store entries' -win64 trees, not - // to "any x64 exe under tools/". - assert.equal(isExemptPath('resources/agent-payload/tools/something-1.0-win32-arm64/bin/thing.exe'), false) -}) - -test('only the emulated full Chromium win64 tree is exempt', () => { - // CfT has no native win-arm64 build. The x64 zip extracts into - // chrome-win64 inside the revision-named Chromium store entry. - for (const relPath of [ - 'resources/agent-payload/tools/chromium-1208/chrome-win64/chrome.exe', - 'resources\\agent-payload\\tools\\chromium-1208\\chrome-win64\\chrome.dll' - ]) { - assert.equal(isExemptPath(relPath), true, relPath) - } - // Other platforms and obsolete shell payloads have no exemption. - for (const relPath of [ - 'resources/agent-payload/tools/chromium-1208/chrome-linux/chrome', - 'resources/agent-payload/tools/chromium-1208/chrome-mac-arm64/chrome', - 'resources/agent-payload/tools/chromium_headless_shell-1208/chrome-headless-shell-win64/chrome-headless-shell.exe', - 'resources/agent-payload/tools/chromium-1208/chrome-headless-shell-win64/chrome-headless-shell.exe' - ]) { - assert.equal(isExemptPath(relPath), false, relPath) - } -}) - -test('the uv wheel/build cache is exempt in the payload', () => { - // pm bundle deliberately ships uv-cache/ for warm venv rebuilds; it - // holds cached sdists/archives uv may have built for ANY arch (x64/ia32 - // PEs on an arm64 payload) — inert cache bytes, never loaded at runtime. - for (const relPath of [ - 'resources/agent-payload/uv-cache/archive-v0/abc/setuptools/cli.exe', - 'resources\\agent-payload\\uv-cache\\archive-v0\\abc\\discord\\bin\\libopus-0.x64.dll', - 'resources/agent-payload/uv-cache/builds-v0/whatever/build.exe' - ]) { - assert.equal(isExemptPath(relPath), true, relPath) - } - // Anything outside the cache stays audited. - assert.equal(isExemptPath('resources/agent-payload/tools/uv-cache-1.0/tool.exe'), false) -}) - -test('a random payload binary is not exempt', () => { - assert.equal(isExemptPath('resources/agent-payload/hermes-agent/something.exe'), false) +test('tree and CLI audit real second-read PE bytes and fail closed on absent artifacts', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'arch-tree-')) + const cli = () => spawnSync(process.execPath, [path.resolve(import.meta.dirname, 'audit-bundle-arch.mjs'), '--arch=arm64', `--root=${root}`], { encoding: 'utf8' }) + try { + assert.match(cli().stderr, /no unpacked app directory/) + const app = path.join(root, 'win-arm64-unpacked') + fs.mkdirSync(app) + assert.match(cli().stderr, /no native binaries/) + fs.writeFileSync(path.join(app, 'elf'), elfHeader(0xb7)) + fs.writeFileSync(path.join(app, 'macho'), machoThin(0x0100000c)) + const pe = Buffer.alloc(8198) + mzStub(8192).copy(pe) + pe.writeUInt32LE(0x4550, 8192) + pe.writeUInt16LE(0xa641, 8196) + fs.writeFileSync(path.join(app, 'arm64ec.exe'), pe) + assert.deepEqual(auditTree(app, 'arm64'), { binaries: 3, exempted: 0, mismatches: [] }) + assert.equal(cli().status, 0) + pe.writeUInt16LE(0x8664, 8196) + const cache = path.join(app, 'resources/agent-payload/uv-cache/builds-v0') + fs.mkdirSync(cache, { recursive: true }) + fs.writeFileSync(path.join(cache, 'cached.exe'), pe) + fs.writeFileSync(path.join(app, 'wrong-arch.dat'), pe) + assert.deepEqual(auditTree(app, 'arm64'), { + binaries: 5, exempted: 1, mismatches: [{ file: 'wrong-arch.dat', format: 'pe', arches: ['x64'] }] + }) + const failed = cli() + assert.equal(failed.status, 1) + assert.match(failed.stderr, /wrong-arch.dat/) + } finally { fs.rmSync(root, { recursive: true, force: true }) } }) diff --git a/apps/desktop/scripts/batch-sign-binaries.test.mjs b/apps/desktop/scripts/batch-sign-binaries.test.mjs index 1fad4d5739..16e5591943 100644 --- a/apps/desktop/scripts/batch-sign-binaries.test.mjs +++ b/apps/desktop/scripts/batch-sign-binaries.test.mjs @@ -9,7 +9,6 @@ import { afterEach, test } from 'vitest' import builderConfig from '../electron-builder.config.cjs' import { - azureSigningConfigured, batchSignAppTree, chunk, customSign, @@ -35,7 +34,7 @@ test('getBinaries collects .exe and .dll recursively, case-insensitive, sorted', fs.mkdirSync(path.join(root, 'resources', 'agent-payload', 'tools', 'python', 'bin'), { recursive: true }) fs.mkdirSync(path.join(root, 'resources', 'agent-payload', 'tools', 'chromium-1', 'meep'), { recursive: true }) fs.writeFileSync(path.join(root, 'Hermes.exe'), 'x') - fs.writeFileSync(path.join(root, 'ffmpeg.dll'), 'x') + fs.writeFileSync(path.join(root, 'FFMPEG.DLL'), 'x') fs.writeFileSync(path.join(root, 'resources', 'agent-payload', 'tools', 'python', 'bin', 'node.exe'), 'x') fs.writeFileSync(path.join(root, 'resources', 'agent-payload', 'tools', 'chromium-1', 'meep', 'chrome.dll'), 'x') fs.writeFileSync(path.join(root, 'resources', 'README.md'), 'x') @@ -43,8 +42,8 @@ test('getBinaries collects .exe and .dll recursively, case-insensitive, sorted', const files = getBinaries(root).map(f => path.relative(root, f)) assert.deepEqual(files, [ + path.join('FFMPEG.DLL'), path.join('Hermes.exe'), - path.join('ffmpeg.dll'), path.join('resources', 'agent-payload', 'tools', 'chromium-1', 'meep', 'chrome.dll'), path.join('resources', 'agent-payload', 'tools', 'python', 'bin', 'node.exe') ]) @@ -90,37 +89,6 @@ test('chunk splits into ~100-file batches with no leftovers', () => { assert.deepEqual(chunk(exact).map(b => b.length), [100, 100]) }) -test('azureSigningConfigured requires endpoint, account, and profile together', () => { - assert.equal(azureSigningConfigured({}), false) - assert.equal(azureSigningConfigured({ AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net' }), false) - assert.equal( - azureSigningConfigured({ - AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net', - AZURE_SIGN_ACCOUNT: 'codesign2' - }), - false - ) - assert.equal( - azureSigningConfigured({ - AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net', - AZURE_SIGN_ACCOUNT: 'codesign2', - AZURE_SIGN_PROFILE: 'hermesagent' - }), - true - ) -}) - -test('customSign returns true for batch-covered payload files without touching Azure', async () => { - let azureTouched = 0 - const result = await customSign( - { path: 'C:/out/win-unpacked/resources/agent-payload/tools/node.exe' }, - { appInfo: { productFilename: 'Hermes' } }, - { azureSignFile: async () => { azureTouched += 1 } } - ) - assert.equal(result, true) - assert.equal(azureTouched, 0) -}) - test('customSign skips Store- submission packages (Partner Center signs)', async () => { const result = await customSign( { path: 'C:/out/Store-HermesBundled-0.28.0-win-x64.msix' }, @@ -163,7 +131,7 @@ test('customSign delegates only the msix package and root product exe to the Azu const exe = path.join(root, exeName) delegated.length = 0 // Same basename is not enough: payload copies wait for the afterPack batch. - for (const file of [path.join(root, 'resources', 'agent-payload', 'bin', exeName), path.join(`${root}-other`, exeName)]) { + for (const file of [path.join(root, 'resources', 'agent-payload', 'bin', exeName), path.join(`${root}-other`, exeName), path.join(root, 'resources', 'Hermes-helper.exe')]) { assert.equal(await customSign({ path: file }, packager, deps), true) } assert.deepEqual(delegated, []) @@ -174,27 +142,13 @@ test('customSign delegates only the msix package and root product exe to the Azu } }) -test('customSign does not mistake a similarly-named payload exe for the product exe', async () => { - const deps = { - azureSignFile: async () => { throw new Error('must not be called') } - } - assert.equal( - await customSign( - { path: 'C:/out/win-unpacked/resources/Hermes-helper.exe' }, - { appInfo: { productFilename: 'Hermes' } }, - deps - ), - true - ) -}) - test('batchSignAppTree is a no-op (skipped=true) without the Azure env, and signs via chunked argv-array invocations when set', async () => { const root = tmpTree() fs.mkdirSync(path.join(root, 'tools'), { recursive: true }) const exe = path.join(root, 'Hermes.exe') fs.writeFileSync(exe, 'x') fs.writeFileSync(path.join(root, 'tools', 'node.exe'), 'x') - fs.writeFileSync(path.join(root, 'tools', 'ffmpeg.dll'), 'x') + fs.writeFileSync(path.join(root, 'tools', 'FFMPEG.DLL'), 'x') // The shipped uv-cache holds inert sdist/archive artifacts — the arch // audit exempts it and batch-sign must never sign it (wasted Azure // round-trips; locally it can even reference files since removed). @@ -202,8 +156,9 @@ test('batchSignAppTree is a no-op (skipped=true) without the Azure env, and sign fs.writeFileSync(path.join(root, 'uv-cache', 'archive-v0', 'setuptools', 'cli.exe'), 'x') // Unsigned lane: loud no-op, nothing invoked. - const skipped = await batchSignAppTree(root, exe, { env: {} }) - assert.deepEqual(skipped, { signed: 0, chunks: 0, skipped: true }) + for (const env of [{}, { AZURE_SIGN_ENDPOINT: 'https://test.invalid' }, { AZURE_SIGN_ENDPOINT: 'https://test.invalid', AZURE_SIGN_ACCOUNT: 'account' }]) { + assert.deepEqual(await batchSignAppTree(root, exe, { env }), { signed: 0, chunks: 0, skipped: true }) + } // Signed lane: product exe excluded, chunked argv arrays. Two passes per // chunk: 'sign' (Azure, no timestamp) then 'timestamp' (RFC3161, no dlib). @@ -235,7 +190,7 @@ test('batchSignAppTree is a no-op (skipped=true) without the Azure env, and sign assert.ok(!args.some(arg => typeof arg === 'string' && arg.includes(' '))) assert.equal(args.includes(exe), false, 'product exe excluded — signed per-file after rcedit') assert.equal(args.includes(path.join(root, 'tools', 'node.exe')), true) - assert.equal(args.includes(path.join(root, 'tools', 'ffmpeg.dll')), true) + assert.equal(args.includes(path.join(root, 'tools', 'FFMPEG.DLL')), true) assert.equal(args[args.indexOf('/dlib') + 1], 'azure.codesigning.dlib.dll') assert.ok(args[args.indexOf('/dmdf') + 1].endsWith('batch-sign.json')) assert.equal(args[args.indexOf('/fd') + 1], 'SHA256') @@ -249,7 +204,7 @@ test('batchSignAppTree is a no-op (skipped=true) without the Azure env, and sign assert.equal(tsArgs.includes('/dlib'), false) assert.equal(tsArgs.includes('/dmdf'), false) assert.ok(tsArgs.includes(path.join(root, 'tools', 'node.exe')), 'timestamp pass covers the same files') - assert.ok(tsArgs.includes(path.join(root, 'tools', 'ffmpeg.dll'))) + assert.ok(tsArgs.includes(path.join(root, 'tools', 'FFMPEG.DLL'))) }) test('batchSignAppTree chunks large trees into ~100-file signtool invocations, sign + timestamp passes', async () => { @@ -329,7 +284,7 @@ test('sign chunks run concurrently, capped at the configured concurrency', async assert.equal(maxInFlight, 3, 'never more than the configured concurrency in flight') }) -test('timestamp pass retries a flaky server before giving up', async () => { +test.each([false, true])('timestamp retry is bounded; permanent failure=%s', async permanent => { const root = tmpTree() fs.mkdirSync(path.join(root, 'tools'), { recursive: true }) fs.writeFileSync(path.join(root, 'tools', 'node.exe'), 'x') @@ -338,10 +293,10 @@ test('timestamp pass retries a flaky server before giving up', async () => { const fakeExec = (tool, args) => { if (args[0] === 'sign') return calls += 1 - if (calls < 3) throw new Error('Invalid Time Stamp Request Length:-1') + if (permanent || calls < 3) throw new Error('Invalid Time Stamp Request Length:-1') } - await batchSignAppTree(root, path.join(root, 'Hermes.exe'), { + const signing = batchSignAppTree(root, path.join(root, 'Hermes.exe'), { env: { AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net', AZURE_SIGN_ACCOUNT: 'codesign2', @@ -354,6 +309,7 @@ test('timestamp pass retries a flaky server before giving up', async () => { timestampRetryDelayMs: 0 }) + if (permanent) await assert.rejects(signing, /Invalid Time Stamp/); else await signing assert.equal(calls, 3, 'timestamp pass retried until the server succeeded') }) diff --git a/apps/desktop/scripts/commit-stamp-identity.test.mjs b/apps/desktop/scripts/commit-stamp-identity.test.mjs index 72d13ccfc8..7e66f7694e 100644 --- a/apps/desktop/scripts/commit-stamp-identity.test.mjs +++ b/apps/desktop/scripts/commit-stamp-identity.test.mjs @@ -36,12 +36,14 @@ test('desktop stamp uses the admitted checkout rather than the dispatch SHA', () fs.writeFileSync(path.join(build, 'agent-payload/manifest.json'), JSON.stringify({ target: 'darwin-arm64', launchers: ['hermes'], runtime })) const out = path.join(build, 'install-stamp.json') const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GITHUB_') && !key.startsWith('HERMES_PAYLOAD_') && !key.startsWith('HERMES_BUILD_'))) - Object.assign(env, { GITHUB_SHA: main, GITHUB_REF_NAME: 'main', HERMES_BUILD_COMMIT: feature, HERMES_DESKTOP_VARIANT: 'bundled' }) + Object.assign(env, { GITHUB_SHA: main, GITHUB_REF_NAME: 'main', HERMES_BUILD_COMMIT: feature, HERMES_DESKTOP_VARIANT: 'bundled', HERMES_PAYLOAD_VERSION: '0.28.0' }) const run = override => spawnSync(process.execPath, [path.join(scripts, 'write-build-stamp.mjs')], { cwd: temp, env: { ...env, ...override }, encoding: 'utf8', timeout: 30000 }) const result = run({}) assert.equal(result.status, 0, result.stderr) const stamp = JSON.parse(fs.readFileSync(out, 'utf8')) assert.equal(stamp.commit, feature) + assert.equal(stamp.baseVersion, '0.28.0') + assert.equal(stamp.displayVersion, '0.28.0') assert.equal(stamp.branch, null) assert.equal(stamp.source, 'commit-build') assert.equal(stamp.tag, null) diff --git a/apps/desktop/scripts/local-pack-publish.test.mjs b/apps/desktop/scripts/local-pack-publish.test.mjs index 7cc2ba8e0c..c6c9e9a493 100644 --- a/apps/desktop/scripts/local-pack-publish.test.mjs +++ b/apps/desktop/scripts/local-pack-publish.test.mjs @@ -1,127 +1,47 @@ -/** - * Regression #87758: a local desktop pack must never enter electron-builder's - * publish path, and publish resolution must succeed when something else does - * enter it. - * - * These call the real app-builder-lib resolver rather than asserting on the - * text of the pack script, so they fail if electron-builder changes the - * behavior we depend on — not when someone reformats package.json. - */ import assert from 'node:assert/strict' -import { createRequire } from 'node:module' +import fs from 'node:fs' +import os from 'node:os' import path from 'node:path' -import { fileURLToPath } from 'node:url' -import { afterEach, beforeEach, describe, test } from 'vitest' -import hostedGitInfo from 'hosted-git-info' +import { createRequire } from 'node:module' +import { LinuxPackager, Packager } from 'app-builder-lib' +import { afterEach, test, vi } from 'vitest' const require = createRequire(import.meta.url) -const desktopDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') -const desktopPkg = require(path.join(desktopDir, 'package.json')) +const lib = path.dirname(path.dirname(require.resolve('app-builder-lib'))) +const { getPublishConfigs } = require(path.join(lib, 'dist/publish/PublishManager.js')) +afterEach(() => vi.unstubAllEnvs()) -// app-builder-lib@27 tightened its "exports" map (deep subpaths are no -// longer exported) and moved out/ -> dist/. Resolve the package root from -// its main entry, then reach the real resolver files by absolute path so -// the behavior under test is the actual installed library. -const appBuilderLibDir = path.dirname(path.dirname(require.resolve('app-builder-lib'))) -const { getPublishConfigs } = require(path.join(appBuilderLibDir, 'dist/publish/PublishManager.js')) -const { getRepositoryInfo } = require(path.join(appBuilderLibDir, 'dist/util/repositoryInfo.js')) - -/** - * The slice of PlatformPackager that getPublishConfigs actually reads. The - * repositoryInfo getter mirrors what electron-builder does for real: resolve - * from THIS package's metadata with projectDir = apps/desktop. - */ -function fakePackager(metadata) { - const info = { - appInfo: { version: '0.0.0', channel: null, updaterCacheDirName: 'hermes' }, - config: {}, - options: {} +test.each([['repository', true, true], ['missing repository', false, true], ['no token', true, false]])( + 'real supplier publish resolution: %s', async (_name, repository, token) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'publish-resolution-')) + for (const key of ['GH_TOKEN', 'GITHUB_TOKEN', 'GITLAB_TOKEN', 'KEYGEN_TOKEN', 'BITBUCKET_TOKEN']) vi.stubEnv(key, '') + vi.stubEnv('GITHUB_TOKEN', token ? 'fixture-not-a-real-token' : '') + for (const key of ['TRAVIS_REPO_SLUG', 'APPVEYOR_REPO_NAME', 'CIRCLE_PROJECT_USERNAME', 'CIRCLE_PROJECT_REPONAME']) vi.stubEnv(key, undefined) + // No .git parent and no production metadata resolver replaced. Only resolution, never publish. + try { + /** @type {import('app-builder-lib').Metadata} */ + const metadata = { name: 'fixture', version: '1.0.0', description: 'fixture', author: 'Fixture' } + if (repository) metadata.repository = 'https://github.com/NousResearch/hermes-agent' + fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify(metadata)) + const info = new Packager({ projectDir: root, config: {} }) + await info.validateConfig() + const packager = new LinuxPackager(info) + if (!token) { + assert.deepEqual(await getPublishConfigs(packager, null, null, true), []) + } else if (!repository) { + await assert.rejects(getPublishConfigs(packager, null, null, true), /Cannot detect repository/) + } else { + const repositoryInfo = await packager.repositoryInfo + assert.equal(repositoryInfo.user, 'NousResearch') + assert.equal(repositoryInfo.project, 'hermes-agent') + assert.deepEqual(await getPublishConfigs(packager, null, null, true), [{ owner: 'NousResearch', repo: 'hermes-agent', provider: 'github' }]) + } + } finally { fs.rmSync(root, { recursive: true, force: true }) } } - return { - platformSpecificBuildOptions: {}, - platformOptions: {}, // v27 API: getPublishConfigs reads platformOptions.publish - config: {}, - info, - platform: { name: 'linux' }, - appInfo: info.appInfo, - expandMacro: value => value, - // v27 API: getPublishConfigs awaits `packager.repositoryInfo` (top-level), - // not the v26 `packager.info.repositoryInfo` nesting. app-builder-lib@27's - // own getRepositoryInfo returns {} in this environment (hosted-git-info - // named-import interop), so parse metadata.repository directly. - get repositoryInfo() { - const repo = metadata && metadata.repository - if (!repo) return null - const parsed = hostedGitInfo.fromUrl(typeof repo === 'string' ? repo : repo.url) - if (!parsed) return null - return { user: parsed.user, project: parsed.project } - } - } -} +) -const TOKEN_VARS = ['GH_TOKEN', 'GITHUB_TOKEN', 'GITLAB_TOKEN', 'KEYGEN_TOKEN', 'BITBUCKET_TOKEN'] -let savedEnv - -beforeEach(() => { - savedEnv = {} - for (const key of TOKEN_VARS) { - savedEnv[key] = process.env[key] - delete process.env[key] - } -}) - -afterEach(() => { - for (const key of TOKEN_VARS) { - if (savedEnv[key] === undefined) delete process.env[key] - else process.env[key] = savedEnv[key] - } -}) - -describe('local desktop pack stays out of the publish path', () => { - test('the pack script pins an explicit publish policy', () => { - // electron-builder 26 infers `onTagOrDraft` from CI when --publish is - // absent, and `hermes desktop` runs the pack with CI=1 (_npm_lifecycle_env). - // v27 drops the implicit behavior, so being explicit is also forward-safe. - const pack = desktopPkg.scripts.pack - assert.match(pack, /--dir\b/) - assert.match(pack, /--publish\s+never\b/) - }) - - test('publish resolution succeeds with a GitHub token present', async () => { - // The #87758 failure mode: CI=1 makes isPublish true, a GITHUB_TOKEN in the - // environment auto-selects the github provider, and the provider needs a - // repository it cannot find — apps/desktop has no .git/config of its own - // and app-builder-lib does not walk up to the workspace root. - process.env.GITHUB_TOKEN = 'x' - - const configs = await getPublishConfigs( - fakePackager(desktopPkg), - null, - null, - /* errorIfCannot */ true - ) - - assert.ok(Array.isArray(configs) && configs.length > 0) - assert.equal(configs[0].provider, 'github') - assert.equal(configs[0].owner, 'NousResearch') - assert.equal(configs[0].repo, 'hermes-agent') - }) - - test('a package without the repository field is what breaks resolution', async () => { - // Guards the fix itself: proves the assertion above passes because of the - // repository field, not because the throw is unreachable. - process.env.GITHUB_TOKEN = 'x' - const { repository, ...withoutRepository } = desktopPkg - assert.ok(repository, 'apps/desktop/package.json must declare a repository') - - await assert.rejects( - () => getPublishConfigs(fakePackager(withoutRepository), null, null, true), - /Cannot detect repository by \.git\/config/ - ) - }) - - test('resolution is quiet when no publish token is configured', async () => { - const configs = await getPublishConfigs(fakePackager(desktopPkg), null, null, true) - assert.deepEqual(configs, []) - }) +test('the pack script pins an explicit publish policy', () => { + const pack = require('../package.json').scripts.pack + assert.match(pack, /--dir\b/) + assert.match(pack, /--publish\s+never\b/) }) diff --git a/apps/desktop/scripts/msix-alias-population.test.mjs b/apps/desktop/scripts/msix-alias-population.test.mjs deleted file mode 100644 index 1159832204..0000000000 --- a/apps/desktop/scripts/msix-alias-population.test.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { appExecutionAliasExtensions } from './before-build.mjs' - -describe('MSIX alias population', () => { - it('omits execution aliases when no payload launchers are present', () => { - expect(appExecutionAliasExtensions([])).toBe('') - }) -}) diff --git a/apps/desktop/scripts/sanitize-pe-signatures.test.mjs b/apps/desktop/scripts/sanitize-pe-signatures.test.mjs index f72d6ea35d..43780f7960 100644 --- a/apps/desktop/scripts/sanitize-pe-signatures.test.mjs +++ b/apps/desktop/scripts/sanitize-pe-signatures.test.mjs @@ -2,159 +2,54 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' +import { test } from 'vitest' -import { afterEach, beforeEach, test } from 'vitest' +import { sanitizeTree } from './sanitize-pe-signatures.mjs' -import { - classifySecurityDirectory, - clearSecurityDirectory, - numberOfRvaAndSizesOffset, - readSecurityDirectory, - sanitizeTree, -} from '../scripts/sanitize-pe-signatures.mjs' - -// ─── fixture builder: a PE with a chosen security directory ──────────────── - -const PE_HEADER_OFFSET = 0x80 -const OPTIONAL_HEADER_SIZE = 240 // enough for 16 data directories in either width - -/** - * Build the smallest byte sequence that parses as a PE with data - * directories, then append `trailing` bytes to stand in for a signature. - * certOffset/certSize are written verbatim so a test can describe a valid - * table, a dangling one, or none at all. - */ -function peFile({ magic = 0x20b, certOffset = 0, certSize = 0, trailing = 0 } = {}) { - const headerEnd = PE_HEADER_OFFSET + 24 + OPTIONAL_HEADER_SIZE - const buf = Buffer.alloc(headerEnd + trailing) - buf.write('MZ', 0, 'latin1') - buf.writeUInt32LE(PE_HEADER_OFFSET, 0x3c) - buf.writeUInt32LE(0x00004550, PE_HEADER_OFFSET) // "PE\0\0" - buf.writeUInt16LE(magic === 0x20b ? 0xaa64 : 0x014c, PE_HEADER_OFFSET + 4) // machine - buf.writeUInt16LE(OPTIONAL_HEADER_SIZE, PE_HEADER_OFFSET + 20) - buf.writeUInt16LE(magic, PE_HEADER_OFFSET + 24) - const rvaCount = numberOfRvaAndSizesOffset(magic) - buf.writeUInt32LE(16, PE_HEADER_OFFSET + 24 + rvaCount) - const secOff = PE_HEADER_OFFSET + 24 + rvaCount + 4 + 4 * 8 - buf.writeUInt32LE(certOffset, secOff) - buf.writeUInt32LE(certSize, secOff + 4) - return { buf, securityDirectoryOffset: secOff, headerEnd } +for (const [magic, countOffset, securityOffset] of [[0x10b, 244, 280], [0x20b, 260, 296]]) { + test(`tree sanitization preserves all bytes except dangling PE ${magic.toString(16)} directories`, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pe-sanitize-')) + // Independent PE specification offsets: e_lfanew=128; optional header=152. + const rows = [ + ['inside', 400, 32, false], ['at-eof', 400, 64, false], ['absent', 0, 0, false], + ['starts-at-eof', 464, 24, true], ['crosses-eof', 450, 24, true], + ['size-only', 0, 24, true], ['offset-only', 400, 0, true] + ] + const expected = new Map() + try { + for (const [name, offset, size, repair] of rows) { + const bytes = Buffer.alloc(464, 0xa5) + bytes.write('MZ', 0, 'latin1') + bytes.writeUInt32LE(128, 0x3c) + bytes.writeUInt32LE(0x4550, 128) + bytes.writeUInt16LE(240, 148) + bytes.writeUInt16LE(magic, 152) + bytes.writeUInt32LE(16, countOffset) + bytes.writeUInt32LE(offset, securityOffset) + bytes.writeUInt32LE(size, securityOffset + 4) + fs.writeFileSync(path.join(root, `${name}.dll`), bytes) + const after = Buffer.from(bytes) + if (repair) after.fill(0, securityOffset, securityOffset + 8) + expected.set(`${name}.dll`, after) + } + const dos = Buffer.alloc(256) + dos.write('MZ', 0) + dos.writeUInt32LE(128, 0x3c) + for (const [name, bytes] of [['notes.txt', Buffer.from('not PE')], ['dos.exe', dos]]) { + fs.writeFileSync(path.join(root, name), bytes) + expected.set(name, bytes) + } + const unsupported = Buffer.from(expected.get('inside.dll')) + unsupported.writeUInt16LE(0x107, 152) + fs.writeFileSync(path.join(root, 'unsupported.exe'), unsupported) + expected.set('unsupported.exe', unsupported) + const result = sanitizeTree(root) + assert.equal(result.scanned, 7) + assert.deepEqual(result.repaired.sort(), ['crosses-eof.dll', 'offset-only.dll', 'size-only.dll', 'starts-at-eof.dll']) + for (const [name, bytes] of expected) assert.deepEqual(fs.readFileSync(path.join(root, name)), bytes, name) + assert.deepEqual(sanitizeTree(root).repaired, []) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) } - -let dir -beforeEach(() => { - dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pe-sanitize-')) -}) -afterEach(() => { - fs.rmSync(dir, { recursive: true, force: true }) -}) - -/** @returns {string} absolute path of the written fixture */ -function write(name, spec) { - const file = path.join(dir, name) - fs.mkdirSync(path.dirname(file), { recursive: true }) - fs.writeFileSync(file, peFile(spec).buf) - return file -} - -// ─── header arithmetic ────────────────────────────────────────────────────── - -test('NumberOfRvaAndSizes sits at 92 for PE32 and 108 for PE32+', () => { - // The whole repair keys off this offset: read it wrong and a valid - // signature looks dangling (or the reverse). - assert.equal(numberOfRvaAndSizesOffset(0x10b), 92) - assert.equal(numberOfRvaAndSizesOffset(0x20b), 108) - assert.equal(numberOfRvaAndSizesOffset(0x107), null) -}) - -// ─── classification ───────────────────────────────────────────────────────── - -test('a table wholly inside the file is a real signature', () => { - assert.equal(classifySecurityDirectory({ certOffset: 100, certSize: 24, fileSize: 200 }), 'present') - // Exactly reaching EOF is the normal shape: signatures live at the end. - assert.equal(classifySecurityDirectory({ certOffset: 100, certSize: 100, fileSize: 200 }), 'present') -}) - -test('a table that cannot fit in the file is dangling', () => { - // The stripped-DLL shape: offset equals the (now truncated) file size. - assert.equal(classifySecurityDirectory({ certOffset: 200, certSize: 24, fileSize: 200 }), 'dangling') - assert.equal(classifySecurityDirectory({ certOffset: 190, certSize: 24, fileSize: 200 }), 'dangling') - // Half-populated entries name no readable region either. - assert.equal(classifySecurityDirectory({ certOffset: 0, certSize: 24, fileSize: 200 }), 'dangling') - assert.equal(classifySecurityDirectory({ certOffset: 100, certSize: 0, fileSize: 200 }), 'dangling') -}) - -test('an all-zero table means no signature and needs no repair', () => { - assert.equal(classifySecurityDirectory({ certOffset: 0, certSize: 0, fileSize: 200 }), 'absent') -}) - -// ─── reading and clearing ─────────────────────────────────────────────────── - -test('readSecurityDirectory locates the entry in both PE widths', () => { - for (const magic of [0x10b, 0x20b]) { - const spec = { magic, certOffset: 1234, certSize: 16 } - const file = write(`w${magic}.dll`, spec) - const entry = readSecurityDirectory(file) - assert.equal(entry.certOffset, 1234) - assert.equal(entry.certSize, 16) - assert.equal(entry.offsetInFile, peFile(spec).securityDirectoryOffset) - } -}) - -test('readSecurityDirectory ignores files that are not PEs with directories', () => { - const plain = path.join(dir, 'notes.txt') - fs.writeFileSync(plain, 'hello') - assert.equal(readSecurityDirectory(plain), null) - - // MZ with no PE signature: a DOS-era stub, not a PE. - const stub = path.join(dir, 'stub.exe') - const buf = Buffer.alloc(0x100) - buf.write('MZ', 0, 'latin1') - buf.writeUInt32LE(0x80, 0x3c) - fs.writeFileSync(stub, buf) - assert.equal(readSecurityDirectory(stub), null) -}) - -test('clearSecurityDirectory zeroes the entry and changes nothing else', () => { - const spec = { magic: 0x20b, certOffset: 4096, certSize: 40 } - const file = write('cleared.dll', spec) - const before = fs.readFileSync(file) - - clearSecurityDirectory(file, peFile(spec).securityDirectoryOffset) - - const after = fs.readFileSync(file) - assert.equal(after.length, before.length) - const entry = readSecurityDirectory(file) - assert.equal(entry.certOffset, 0) - assert.equal(entry.certSize, 0) - // Byte-for-byte identical everywhere except the eight-byte entry. - const off = entry.offsetInFile - assert.deepEqual(after.subarray(0, off), before.subarray(0, off)) - assert.deepEqual(after.subarray(off + 8), before.subarray(off + 8)) -}) - -// ─── the tree pass ────────────────────────────────────────────────────────── - -test('sanitizeTree repairs dangling tables and leaves real signatures alone', () => { - // The payload shape that broke the Windows bundled release: a stripped - // DLL whose table starts exactly at EOF, beside correctly signed files. - const stripped = write('python/DLLs/tcl86t.dll', { certOffset: 464, certSize: 12056 }) - const signed = write('python/python.exe', { certOffset: 400, certSize: 64, trailing: 200 }) - const unsigned = write('python/DLLs/_socket.pyd', {}) - fs.writeFileSync(path.join(dir, 'python', 'LICENSE.txt'), 'not a PE') - - const { scanned, repaired } = sanitizeTree(dir) - - assert.equal(scanned, 3) // the three PEs; the text file is skipped - assert.deepEqual(repaired, [path.join('python', 'DLLs', 'tcl86t.dll')]) - assert.equal(readSecurityDirectory(stripped).certSize, 0) - assert.equal(readSecurityDirectory(signed).certSize, 64) // untouched - assert.equal(readSecurityDirectory(unsigned).certSize, 0) -}) - -test('sanitizeTree is idempotent', () => { - write('DLLs/tk86t.dll', { certOffset: 464, certSize: 12064 }) - - assert.equal(sanitizeTree(dir).repaired.length, 1) - assert.deepEqual(sanitizeTree(dir).repaired, []) -}) diff --git a/apps/desktop/scripts/side-by-side-launchers.test.mjs b/apps/desktop/scripts/side-by-side-launchers.test.mjs index 3a98f18144..a49eadbccf 100644 --- a/apps/desktop/scripts/side-by-side-launchers.test.mjs +++ b/apps/desktop/scripts/side-by-side-launchers.test.mjs @@ -18,28 +18,6 @@ test('the Store bundler rejects nonstable selectors before platform tools or sta } }) -test('the embedded Python checkout receives the same commit provenance as Electron', () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-stamp-')) - try { - const commit = 'a'.repeat(40) - const repo = path.join(root, 'agent-payload/hermes-agent') - fs.mkdirSync(repo, { recursive: true }) - const built = stamps.buildStampPayload({ commit, source: 'local', branch: 'main' }, { - HERMES_DESKTOP_VARIANT: 'bundled', HERMES_BUILD_COMMIT: commit, HERMES_PAYLOAD_VERSION: '0.28.0' - }, 'win32', { runtime: { repoDir: 'hermes-agent', commands: { hermes: 'bin/hermes-aaaaaaa.exe' } } }) - stamps.writeDesktopStamp(root, built) - const pythonStamp = JSON.parse(fs.readFileSync(path.join(repo, 'install-stamp.json'), 'utf8')) - assert.deepEqual(pythonStamp, JSON.parse(fs.readFileSync(path.join(root, 'install-stamp.json'), 'utf8'))) - assert.equal(pythonStamp.source, 'commit-build') - assert.equal(pythonStamp.commit, commit) - assert.equal(pythonStamp.tag, null) - assert.equal(pythonStamp.baseVersion, '0.28.0') - assert.equal(pythonStamp.displayVersion, '0.28.0') - } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - test('nonstable MSIX CLI aliases each activate their own entrypoint, never the GUI', () => { const launchers = ['hermes-canary', 'hermes-canary-acp'] const applications = msix.appExecutionAliasApplications(launchers, { diff --git a/apps/desktop/scripts/sign-msix.test.mjs b/apps/desktop/scripts/sign-msix.test.mjs index 02825140a0..06a9e1c53e 100644 --- a/apps/desktop/scripts/sign-msix.test.mjs +++ b/apps/desktop/scripts/sign-msix.test.mjs @@ -2,10 +2,11 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import { createRequire } from 'node:module' import path from 'node:path' +import os from 'node:os' import { pathToFileURL } from 'node:url' -import { test } from 'vitest' +import { test, vi } from 'vitest' -import { azureConfigFromEnv, shouldSignFile } from './sign-msix.mjs' +import { azureConfigFromEnv, azureSignFile, shouldSignFile } from './sign-msix.mjs' const require = createRequire(import.meta.url) @@ -75,46 +76,35 @@ test('azureConfigFromEnv composes the Azure signing config from the environment' }) }) -// ─── builder-bump tripwire ────────────────────────────────────────────────── -// sign-msix.mjs deep-imports app-builder-lib's WindowsSignAzureManager by -// file path (the package exports map exposes only "." and "./internal", so -// the dist path is reached the same way run-electron-builder.mjs finds the -// CLI: resolve the entry, walk up to the package root, then direct-file -// import). If an electron-builder/app-builder-lib bump moves or renames the -// class, THIS test is what fails in js-tests — before a release build does. -// 60s timeout: the direct-file import drags in app-builder-lib's whole -// module graph (toolsets, electronGet, vm), which takes ~30s on a cold -// disk cache — far past vitest's 5s default. -test('the real WindowsSignAzureManager resolves and constructs against a packager shim', { timeout: 60_000 }, async () => { - const entry = require.resolve('app-builder-lib') - let root = path.dirname(entry) - while (!fs.existsSync(path.join(root, 'package.json'))) { - const parent = path.dirname(root) - assert.notEqual(parent, root, 'app-builder-lib package root not found') - root = parent +test('azureSignFile calls the real supplier through a prepared local toolset', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'sign-supplier-')) + const lib = path.dirname(path.dirname(require.resolve('app-builder-lib'))) + const { VmManager } = await import(pathToFileURL(path.join(lib, 'dist/vm/vm.js')).href) + const { WineVmManager } = await import(pathToFileURL(path.join(lib, 'dist/vm/WineVm.js')).href) + const native = process.platform === 'win32' ? VmManager : WineVmManager + const calls = [] + // Only the final native execution is intercepted; manager init, dispatch and metadata are real. + const execution = vi.spyOn(native.prototype, 'exec').mockImplementation(async (file, args) => { calls.push({ file, args }) }) + const kits = path.join(root, 'kits') + const kit = path.join(kits, process.arch === 'ia32' ? 'x86' : 'x64') + fs.mkdirSync(kit, { recursive: true }) + const metadata = path.join(root, 'metadata.json') + for (const [name, value] of Object.entries({ AZURE_SIGN_ENDPOINT: 'https://test.invalid', AZURE_SIGN_ACCOUNT: 'account', AZURE_SIGN_PROFILE: 'profile', AZURE_SIGN_PUBLISHER: 'CN=Fixture' })) vi.stubEnv(name, value) + try { + await azureSignFile(path.join(root, 'fixture.msix'), { + platformOptions: { sign: { type: 'signtool' } }, + config: { toolsets: { winCodeSign: { url: `file://${kits}` } } }, + buildResourcesDir: root, + getTempFile: async () => metadata + }) + assert.deepEqual(JSON.parse(fs.readFileSync(metadata, 'utf8')), { Endpoint: 'https://test.invalid', CodeSigningAccountName: 'account', CertificateProfileName: 'profile' }) + assert.equal(calls.length, 1) + assert.equal(calls[0].file, path.join(kit, 'signtool.exe')) + assert.deepEqual(calls[0].args.slice(0, 7), ['sign', '/fd', 'SHA256', '/tr', 'http://timestamp.acs.microsoft.com', '/td', 'SHA256']) + assert.ok(calls[0].args[calls[0].args.indexOf('/dlib') + 1].endsWith('Azure.CodeSigning.Dlib.dll')) + assert.ok(calls[0].args.at(-1).endsWith('fixture.msix')) + } finally { + execution.mockRestore(); vi.unstubAllEnvs() + fs.rmSync(root, { recursive: true, force: true }) } - const mod = await import( - pathToFileURL(path.join(root, 'dist', 'codeSign', 'win', 'windowsSignAzureManager.js')).href - ) - assert.equal(typeof mod.WindowsSignAzureManager, 'function') - - // Constructor contract (verified against 27.0.0-alpha.6): reads - // packager.platformOptions.sign (throws unless type === 'azure'), - // packager.config.toolsets (optional), and packager.buildResourcesDir - // (only stored — WineVmManager's constructor touches no filesystem). - const mgr = new mod.WindowsSignAzureManager({ - platformOptions: { - sign: { - type: 'azure', - endpoint: 'x', - codeSigningAccountName: 'y', - certificateProfileName: 'z', - publisherName: 'p' - } - }, - config: {}, - buildResourcesDir: '/tmp' - }) - assert.equal(typeof mgr.signFile, 'function') - assert.equal(typeof mgr.initialize, 'function') }) diff --git a/apps/desktop/scripts/sign-nested-chromium.test.mjs b/apps/desktop/scripts/sign-nested-chromium.test.mjs index a6d5dfb43b..cf25439f31 100644 --- a/apps/desktop/scripts/sign-nested-chromium.test.mjs +++ b/apps/desktop/scripts/sign-nested-chromium.test.mjs @@ -5,10 +5,6 @@ import path from 'node:path' import { test } from 'vitest' import { - chromiumRoots, - isMachO, - listLooseMachO, - listTopLevelApps, parseDeveloperId, repairFrameworkLinks, resolveSigningIdentity, @@ -25,48 +21,6 @@ function machoBuf() { return buf } -test('isMachO accepts a 64-bit Mach-O magic and rejects text', () => { - const dir = tempRoot() - try { - const bin = path.join(dir, 'a') - const txt = path.join(dir, 'b.txt') - fs.writeFileSync(bin, machoBuf()) - fs.writeFileSync(txt, 'not a binary') - assert.equal(isMachO(bin), true) - assert.equal(isMachO(txt), false) - } finally { - fs.rmSync(dir, { recursive: true, force: true }) - } -}) - -test('chromiumRoots only names full Chromium store entries', () => { - const payload = tempRoot() - try { - fs.mkdirSync(path.join(payload, 'tools', 'chromium-1208'), { recursive: true }) - fs.mkdirSync(path.join(payload, 'tools', 'chromium_headless_shell-1208'), { recursive: true }) - fs.mkdirSync(path.join(payload, 'tools', 'uv-0.12.3-darwin-arm64'), { recursive: true }) - const roots = chromiumRoots(payload).map(p => path.basename(p)).sort() - assert.deepEqual(roots, ['chromium-1208']) - } finally { - fs.rmSync(payload, { recursive: true, force: true }) - } -}) - -test('listTopLevelApps finds .app dirs and listLooseMachO skips them', () => { - const root = tempRoot() - try { - const app = path.join(root, 'Google Chrome for Testing.app') - fs.mkdirSync(path.join(app, 'Contents', 'MacOS'), { recursive: true }) - fs.writeFileSync(path.join(app, 'Contents', 'MacOS', 'Chrome'), machoBuf()) - const loose = path.join(root, 'libEGL.dylib') - fs.writeFileSync(loose, machoBuf()) - assert.deepEqual(listTopLevelApps(root), [app]) - assert.deepEqual(listLooseMachO(root), [loose]) - } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - test('repairFrameworkLinks turns a flattened Foo.framework/Foo into a symlink', () => { if (process.platform === 'win32') return const root = tempRoot() @@ -120,6 +74,12 @@ test('signNestedChromium --deep signs the .app and file-signs loose Mach-O', () fs.writeFileSync(path.join(app, 'Contents', 'MacOS', 'Chrome'), machoBuf()) const loose = path.join(payload, 'tools', 'chromium-1208', 'libEGL.dylib') fs.writeFileSync(loose, machoBuf()) + fs.writeFileSync(path.join(path.dirname(loose), 'README'), 'not Mach-O') + for (const name of ['chromium_headless_shell-1208', 'uv-0.12.3-darwin-arm64']) { + const other = path.join(payload, 'tools', name) + fs.mkdirSync(other, { recursive: true }) + fs.writeFileSync(path.join(other, 'binary'), machoBuf()) + } const calls = [] const r = signNestedChromium(payload, { identity: 'Developer ID Application: Test', diff --git a/apps/desktop/scripts/write-build-stamp.test.mjs b/apps/desktop/scripts/write-build-stamp.test.mjs index 8223fbe8d9..9b0dffc2ec 100644 --- a/apps/desktop/scripts/write-build-stamp.test.mjs +++ b/apps/desktop/scripts/write-build-stamp.test.mjs @@ -120,40 +120,6 @@ test('source builds declare the same artifact schema, without a payload', () => assert.equal(stamp.commit, baseStamp.commit) }) -test('buildStampPayload with bundled variant declares the App Installer owner', () => { - const payload = buildStampPayload(baseStamp, { - HERMES_DESKTOP_VARIANT: 'bundled', - HERMES_PAYLOAD_TAG: 'v0.27.1-canary.20260901072553' - }, 'win32', { runtime }) - assert.equal(payload.payload, 'bundled') - assert.equal(payload.distribution, 'desktop-app') - assert.equal(payload.updateMechanism, 'app-installer') - assert.equal(payload.tag, 'v0.27.1-canary.20260901072553') -}) - -test('macOS bundles and Light declare app-owned updates; the win32 store variant is Store owned', () => { - for (const variant of ['bundled', 'light', 'store']) { - const stamp = buildStampPayload(baseStamp, { HERMES_DESKTOP_VARIANT: variant }, 'darwin', { runtime }) - assert.equal(stamp.updateMechanism, variant === 'store' ? 'microsoft-store' : 'electron-updater') - } -}) - -test('buildStampPayload with store variant declares external ownership', () => { - const payload = buildStampPayload(baseStamp, { - HERMES_DESKTOP_VARIANT: 'store', - HERMES_PAYLOAD_TAG: 'v0.27.1' - }, 'win32', { runtime }) - assert.equal(payload.payload, 'bundled') -}) - -test('buildStampPayload with light variant stamps payload light', () => { - const payload = buildStampPayload(baseStamp, { - HERMES_DESKTOP_VARIANT: 'light', - HERMES_PAYLOAD_TAG: 'v0.27.1' - }) - assert.equal(payload.payload, 'light') -}) - test('buildStampPayload keeps schemaVersion + provenance in the staged shape', () => { const payload = buildStampPayload(baseStamp, { HERMES_DESKTOP_VARIANT: 'bundled' diff --git a/apps/desktop/src/api/local-models-owner.test.ts b/apps/desktop/src/api/local-models-owner.test.ts index 3ee2149da5..91d5533ae2 100644 --- a/apps/desktop/src/api/local-models-owner.test.ts +++ b/apps/desktop/src/api/local-models-owner.test.ts @@ -1,7 +1,9 @@ import { beforeEach, expect, it, vi } from 'vitest' +import type { LocalModelsOwner } from '@/store/local-runtime-jobs' + import { setApiRequestConnection, setApiRequestProfile } from './client' -import { getLocalModelsJobs, getLocalModelsStatus, pauseLocalDownload } from './local-models' +import { getLocalModelsJobs, getLocalModelsStatus, pauseLocalDownload, resumeLocalDownload } from './local-models' beforeEach((): void => { Object.defineProperty(window, 'hermesDesktop', { @@ -22,3 +24,17 @@ it('pins delayed reads and controls to their captured connection and profile', a expect(request).toMatchObject(owner) } }) + +it.each([ + ['pause', pauseLocalDownload, { ok: true, paused: true }], + ['resume', resumeLocalDownload, { ok: true, resumed: false }] +] as const)('%s preserves the captured owner, request body and backend verdict', async (action: string, control: typeof pauseLocalDownload | typeof resumeLocalDownload, response: { ok: boolean; paused?: boolean; resumed?: boolean }): Promise => { + const owner: LocalModelsOwner = { connectionId: 'background', profile: 'work' } + vi.mocked(window.hermesDesktop.api).mockResolvedValue(response) + expect(await control('download', owner)).toEqual(response) + expect(window.hermesDesktop.api).toHaveBeenCalledExactlyOnceWith({ + ...owner, method: 'POST', path: `/api/local-models/download/${action}`, body: { job_id: 'download' } + }) + vi.mocked(window.hermesDesktop.api).mockRejectedValue(new Error('unknown download job')) + await expect(control('gone', owner)).rejects.toThrow('unknown download job') +}) diff --git a/apps/desktop/src/api/local-models.test.ts b/apps/desktop/src/api/local-models.test.ts deleted file mode 100644 index 373e45d128..0000000000 --- a/apps/desktop/src/api/local-models.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('./client', () => ({ - hermesApi: vi.fn(), - profileScoped: vi.fn(() => ({})) -})) - -const client = await import('./client') - -const { pauseLocalDownload, resumeLocalDownload } = await import('./local-models') - -const hermesApi = vi.mocked(client.hermesApi) - -beforeEach(() => { - vi.clearAllMocks() -}) - -describe('local download pause/resume API', () => { - it('pauseLocalDownload posts {job_id} to the existing pause route and returns the {ok,paused} contract', async () => { - hermesApi.mockResolvedValue({ ok: true, paused: true } as never) - - const res = await pauseLocalDownload('job-7') - - expect(hermesApi).toHaveBeenCalledTimes(1) - expect(hermesApi.mock.calls[0][0]).toMatchObject({ - body: { job_id: 'job-7' }, - method: 'POST', - path: '/api/local-models/download/pause' - }) - expect(res).toEqual({ ok: true, paused: true }) - }) - - it('resumeLocalDownload posts {job_id} to the existing resume route and returns the {ok,resumed} contract', async () => { - hermesApi.mockResolvedValue({ ok: true, resumed: false } as never) - - const res = await resumeLocalDownload('job-8') - - expect(hermesApi).toHaveBeenCalledTimes(1) - expect(hermesApi.mock.calls[0][0]).toMatchObject({ - body: { job_id: 'job-8' }, - method: 'POST', - path: '/api/local-models/download/resume' - }) - // A false resumed flag (no parked download) reaches the caller so the - // UI can report "couldn't resume" rather than silently claiming success. - expect(res).toEqual({ ok: true, resumed: false }) - }) - - it('a failed pause propagates as a rejection — never a silent success', async () => { - hermesApi.mockRejectedValue(new Error('unknown download job')) - - await expect(pauseLocalDownload('gone')).rejects.toThrow('unknown download job') - }) -}) diff --git a/apps/desktop/src/app/settings/local-model-download-progress.test.tsx b/apps/desktop/src/app/settings/local-model-download-progress.test.tsx index 269d49c352..92a513b118 100644 --- a/apps/desktop/src/app/settings/local-model-download-progress.test.tsx +++ b/apps/desktop/src/app/settings/local-model-download-progress.test.tsx @@ -60,19 +60,6 @@ afterEach(() => { }) describe('LocalModelDownloadActions', () => { - it('running download with can_pause:true renders Pause; clicking sends pauseLocalDownload exactly once with the job id', async () => { - renderActions(job({ can_pause: true })) - - const pause = screen.getByRole('button', { name: /pause/i }) - fireEvent.click(pause) - - await waitFor(() => { - expect(pauseLocalDownload).toHaveBeenCalledTimes(1) - }) - expect(pauseLocalDownload).toHaveBeenCalledWith('j1', undefined) - expect(resumeLocalDownload).not.toHaveBeenCalled() - }) - it('running download without explicit can_pause shows NO control (no guessing about old backends)', () => { renderActions(job({})) @@ -92,21 +79,6 @@ describe('LocalModelDownloadActions', () => { expect((pending as HTMLButtonElement).disabled).toBe(true) }) - it('paused job renders the Paused label + Resume (can_resume:true); clicking sends resumeLocalDownload with the job id', async () => { - renderActions(job({ can_resume: true, status: 'paused' })) - - expect(screen.getByText(/paused/i)).toBeTruthy() - - const resume = screen.getByRole('button', { name: /resume/i }) - fireEvent.click(resume) - - await waitFor(() => { - expect(resumeLocalDownload).toHaveBeenCalledTimes(1) - }) - expect(resumeLocalDownload).toHaveBeenCalledWith('j1', undefined) - expect(pauseLocalDownload).not.toHaveBeenCalled() - }) - it('paused hides Resume when can_resume is not explicitly true', () => { renderActions(job({ status: 'paused' })) diff --git a/apps/desktop/src/app/settings/local-models-settings.test.tsx b/apps/desktop/src/app/settings/local-models-settings.test.tsx index 1db6e8f480..4799ee791b 100644 --- a/apps/desktop/src/app/settings/local-models-settings.test.tsx +++ b/apps/desktop/src/app/settings/local-models-settings.test.tsx @@ -660,179 +660,7 @@ describe('quickstart completion navigation', () => { }) }) -describe('pause / resume integration', () => { - beforeEach((): void => { - queryClient.clear() - queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, retry: false } }) - vi.mocked(hermes.pauseLocalDownload).mockResolvedValue({ ok: true, paused: true }) - vi.mocked(hermes.resumeLocalDownload).mockResolvedValue({ ok: true, resumed: true }) - }) - - it('a running catalog download shows Pause; clicking sends the job id once', async () => { - mocked.getLocalModelsStatus.mockResolvedValue({ - ...BASE_STATUS, - runtime_installed: true, - runtime_backend: 'cuda' - }) - queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [ - { - job_id: 'j1', - kind: 'model-download', - target: 'Qwen3.6 27B', - model_id: FITTING_MODEL.id, - status: 'running', - phase: 'downloading', - detail: 'Qwen3.6 27B — 17.6 GB', - total_bytes: 100, - can_pause: true, - done_bytes: 40, - percent: 40, - error: null - } - ]) - - await renderFullPane() - await screen.findByText('Qwen3.6 27B') - - fireEvent.click(screen.getByRole('button', { name: /pause/i })) - - await waitFor(() => { - expect(hermes.pauseLocalDownload).toHaveBeenCalledTimes(1) - }) - expect(hermes.pauseLocalDownload).toHaveBeenCalledWith('j1', { connectionId: null, profile: 'default' }) - expect(hermes.resumeLocalDownload).not.toHaveBeenCalled() - }) - - it('a paused catalog download keeps its row: Paused label, Resume button, progress bar retained', async () => { - mocked.getLocalModelsStatus.mockResolvedValue({ - ...BASE_STATUS, - runtime_installed: true, - runtime_backend: 'cuda' - }) - queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [ - { - job_id: 'j1', - kind: 'model-download', - target: 'Qwen3.6 27B', - model_id: FITTING_MODEL.id, - can_resume: true, - phase: 'downloading', - status: 'paused', - detail: 'Qwen3.6 27B — 17.6 GB', - total_bytes: 100, - done_bytes: 40, - percent: 40, - error: null - } - ]) - - await renderFullPane() - await screen.findByText('Qwen3.6 27B') - - // Row survives with an honest parked label and a way forward. - expect(screen.getAllByText(/paused/i).length).toBeGreaterThan(0) - expect(screen.getByRole('button', { name: /resume/i })).toBeTruthy() - - fireEvent.click(screen.getByRole('button', { name: /resume/i })) - await waitFor(() => { - expect(hermes.resumeLocalDownload).toHaveBeenCalledWith('j1', { connectionId: null, profile: 'default' }) - }) - - // The watcher re-kicked: an authoritative re-read happens after resume. - await waitFor(() => { - expect(mocked.getLocalModelsJobs.mock.calls.length).toBeGreaterThanOrEqual(2) - }) - }) - - it('a paused quickstart stays pinned in the hero with a Resume control', async () => { - queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [ - { - job_id: 'q1', - kind: 'quickstart', - target: 'Qwen3.6 27B', - model_id: 'qwen3.6-27b', - can_resume: true, - phase: 'downloading', - status: 'paused', - detail: '', - total_bytes: 100, - done_bytes: 30, - percent: 30, - error: null - } - ]) - - renderPane() - await screen.findAllByText(/paused/i) - - expect(screen.getByRole('button', { name: /resume/i })).toBeTruthy() - // Hero is pinned — no quickstart action button competes with it. - expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull() - - fireEvent.click(screen.getByRole('button', { name: /resume/i })) - await waitFor(() => { - expect(hermes.resumeLocalDownload).toHaveBeenCalledWith('q1', { connectionId: null, profile: 'default' }) - }) - }) - - it('a running quickstart hero shows Pause during the download stage', async () => { - queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [ - { - job_id: 'q1', - kind: 'quickstart', - target: 'Qwen3.6 27B', - model_id: 'qwen3.6-27b', - can_pause: true, - phase: 'downloading', - status: 'running', - detail: '', - total_bytes: 100, - done_bytes: 30, - percent: 30, - error: null - } - ]) - - renderPane() - await screen.findByText('Qwen3.6 27B') - - expect(screen.getByRole('button', { name: /pause/i })).toBeTruthy() - }) - - it('a running runtime install row shows Pause when the engine leg can park', async () => { - mocked.getLocalModelsStatus.mockResolvedValue({ - ...BASE_STATUS, - runtime_installed: false, - update_available: false - }) - queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [ - { - job_id: 'r1', - kind: 'runtime-install', - target: 'llamacpp', - model_id: null, - can_pause: true, - phase: 'downloading-runtime', - status: 'running', - detail: 'llamacpp b10290', - total_bytes: 100, - done_bytes: 10, - percent: 10, - error: null - } - ]) - - renderPane() - await screen.findByText(/installing/i) - - const pause = screen.getByRole('button', { name: /pause/i }) - fireEvent.click(pause) - - await waitFor(() => { - expect(hermes.pauseLocalDownload).toHaveBeenCalledWith('r1', { connectionId: null, profile: 'default' }) - }) - }) - +describe('quickstart finalization', (): void => { it('quickstart hero suppresses the byte counter outside download phases', async () => { queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [ { diff --git a/apps/desktop/src/components/desktop-install-local-card.test.ts b/apps/desktop/src/components/desktop-install-local-card.test.ts deleted file mode 100644 index d8ad468b36..0000000000 --- a/apps/desktop/src/components/desktop-install-local-card.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import assert from 'node:assert/strict' - -import { test } from 'vitest' - -import { localCardPresentation } from './desktop-install-local-card' - -test('none is the installer offer with the install-to footer', () => { - assert.deepEqual(localCardPresentation('none'), { - title: 'installLocalTitle', - desc: 'installLocalDesc', - showInstallTo: true - }) -}) - -test('installed uses the existing-runtime copy and hides the install-to footer', () => { - assert.deepEqual(localCardPresentation('installed'), { - title: 'useLocalTitle', - desc: 'useLocalDesc', - showInstallTo: false - }) -}) - -test('bundled uses the bundled flavor of the existing-runtime copy', () => { - assert.deepEqual(localCardPresentation('bundled'), { - title: 'useLocalTitle', - desc: 'bundledLocalDesc', - showInstallTo: false - }) -}) - -test('an absent local field falls back to the installer offer (old backends)', () => { - assert.equal(localCardPresentation(undefined).title, 'installLocalTitle') -}) diff --git a/apps/desktop/src/components/desktop-install-overlay.test.tsx b/apps/desktop/src/components/desktop-install-overlay.test.tsx index ba98301881..c1ee6e615a 100644 --- a/apps/desktop/src/components/desktop-install-overlay.test.tsx +++ b/apps/desktop/src/components/desktop-install-overlay.test.tsx @@ -2,7 +2,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { DesktopBootstrapEvent, DesktopBootstrapState, DesktopConnectionProbeResult } from '@/global' +import type { DesktopBootstrapEvent, DesktopBootstrapState } from '@/global' import { DesktopInstallOverlay } from './desktop-install-overlay' @@ -303,103 +303,6 @@ describe('DesktopInstallOverlay first-run setup', () => { await waitFor(() => expect(screen.queryByText('Gateway URL')).toBeNull()) }) - it('ignores a completed probe after the gateway URL becomes invalid', async () => { - const desktop = installDesktopMock( - bootstrapState({ - setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false } - }) - ) - - let resolveProbe: ((result: DesktopConnectionProbeResult) => void) | undefined - - const pendingProbe = new Promise(resolve => { - resolveProbe = resolve - }) - - desktop.probeConnectionConfig.mockReturnValue(pendingProbe) - - render() - - fireEvent.click(await screen.findByText('Connect to existing Hermes')) - const urlInput = await screen.findByPlaceholderText('https://gateway.example.com/hermes') - fireEvent.change(urlInput, { target: { value: 'https://gateway.example.com/hermes' } }) - - await act(async () => { - await new Promise(resolve => setTimeout(resolve, 550)) - }) - expect(desktop.probeConnectionConfig).toHaveBeenCalledTimes(1) - - fireEvent.change(urlInput, { target: { value: 'not-a-url' } }) - await act(async () => { - resolveProbe?.({ - authMode: 'token', - baseUrl: 'https://gateway.example.com/hermes', - error: null, - providers: [], - reachable: true, - version: '0.17.0' - }) - await pendingProbe - }) - - expect(screen.queryByPlaceholderText('Paste session token')).toBeNull() - expect((screen.getByText('Test connection').closest('button') as HTMLButtonElement).disabled).toBe(true) - expect((screen.getByText('Apply and reconnect').closest('button') as HTMLButtonElement).disabled).toBe(true) - }) - - it('does not enable Apply when credentials change during a connection test', async () => { - const desktop = installDesktopMock( - bootstrapState({ - setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false } - }) - ) - - desktop.probeConnectionConfig.mockResolvedValue({ - authMode: 'token', - baseUrl: 'https://gateway.example.com/hermes', - error: null, - providers: [], - reachable: true, - version: '0.17.0' - }) - - let resolveTest: ((result: { baseUrl: string; ok: boolean; version: string }) => void) | undefined - - const pendingTest = new Promise<{ baseUrl: string; ok: boolean; version: string }>(resolve => { - resolveTest = resolve - }) - - desktop.testConnectionConfig.mockReturnValue(pendingTest) - - render() - - fireEvent.click(await screen.findByText('Connect to existing Hermes')) - fireEvent.change(await screen.findByPlaceholderText('https://gateway.example.com/hermes'), { - target: { value: 'https://gateway.example.com/hermes' } - }) - - await act(async () => { - await new Promise(resolve => setTimeout(resolve, 550)) - }) - - const tokenInput = await screen.findByPlaceholderText('Paste session token') - const apply = screen.getByText('Apply and reconnect').closest('button') as HTMLButtonElement - - fireEvent.change(tokenInput, { target: { value: 'token-a' } }) - fireEvent.click(screen.getByText('Test connection')) - await waitFor(() => expect(desktop.testConnectionConfig).toHaveBeenCalledTimes(1)) - - fireEvent.change(tokenInput, { target: { value: 'token-b' } }) - - await act(async () => { - resolveTest?.({ baseUrl: 'https://gateway.example.com/hermes', ok: true, version: '0.17.0' }) - await pendingTest - }) - - expect(screen.queryByText('Connected to https://gateway.example.com/hermes (0.17.0).')).toBeNull() - expect(apply.disabled).toBe(true) - }) - it('restores remote apply controls when applying the tested connection fails', async () => { const desktop = installDesktopMock( bootstrapState({ @@ -610,45 +513,19 @@ describe('DesktopInstallOverlay first-run setup', () => { }) }) -describe('DesktopInstallOverlay bundled / already-installed cards', () => { - it('shows the use-existing card for an installed runtime and hides the install-to footer', async () => { - installDesktopMock( - bootstrapState({ - setupChoice: { - platform: 'win32', - activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', - local: 'installed', - bundled: false - } - }) - ) - - render() - - expect(await screen.findByText('Use Hermes on this computer')).toBeTruthy() - expect(screen.getByText(/already installed here/i)).toBeTruthy() - expect(screen.queryByText(/Will install to/i)).toBeNull() - expect(screen.queryByText('Install Hermes locally')).toBeNull() - }) - - it('shows the bundled flavor for a healthy bundled install', async () => { - installDesktopMock( - bootstrapState({ - setupChoice: { - platform: 'win32', - activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', - local: 'bundled', - bundled: true - } - }) - ) - - render() - - expect(await screen.findByText('Use Hermes on this computer')).toBeTruthy() - expect(screen.getByText(/included with this app/i)).toBeTruthy() - expect(screen.queryByText(/Will install to/i)).toBeNull() - }) +it.each([ + ['installed', false, 'Use Hermes on this computer', /already installed here/i, false], + ['bundled', true, 'Use Hermes on this computer', /included with this app/i, false], + [undefined, false, 'Install Hermes locally', /Will install to/i, true] +] as const)('local presentation for %s (including old backends)', async (local: 'installed' | 'bundled' | undefined, bundled: boolean, title: string, description: RegExp, footer: boolean): Promise => { + const state: DesktopBootstrapState = bootstrapState({ setupChoice: { platform: 'win32', activeRoot: 'C:\\Hermes', local: local ?? 'none', bundled } }) + if (local === undefined && state.setupChoice) { Reflect.deleteProperty(state.setupChoice, 'local') } + installDesktopMock(state) + render() + expect(await screen.findByText(title)).toBeTruthy() + expect(screen.getByText(description)).toBeTruthy() + expect(screen.queryByText(/Will install to/i) !== null).toBe(footer) + if (!footer) { expect(screen.queryByText('Install Hermes locally')).toBeNull() } }) diff --git a/apps/desktop/src/components/external-open-failed-dialog.test.tsx b/apps/desktop/src/components/external-open-failed-dialog.test.tsx index 38226d71c2..0e6ab1336c 100644 --- a/apps/desktop/src/components/external-open-failed-dialog.test.tsx +++ b/apps/desktop/src/components/external-open-failed-dialog.test.tsx @@ -45,45 +45,18 @@ afterEach(() => { }) describe('ExternalOpenFailedDialog', () => { - it('subscribes to open-failure events on mount', () => { - const { onExternalOpenFailed } = installBridge() + it('subscribes, displays, copies and dismisses an external-open failure', async (): Promise => { + const { onExternalOpenFailed, writeClipboard }: ReturnType = installBridge() render() expect(onExternalOpenFailed).toHaveBeenCalledTimes(1) - expect(typeof onExternalOpenFailed.mock.calls[0][0]).toBe('function') - }) - - it('shows the URL when an open-failure event fires', () => { - const { onExternalOpenFailed } = installBridge() - render() - - const listener = onExternalOpenFailed.mock.calls[0][0] expect(screen.queryByText('https://example.com/dead')).toBeNull() + const listener: (payload: { url: string; message?: string }) => void = onExternalOpenFailed.mock.calls[0][0] fail(listener, 'https://example.com/dead') - expect(screen.getByText('https://example.com/dead')).not.toBeNull() - }) - - it('copies the URL when the copy action is used', async () => { - const { onExternalOpenFailed, writeClipboard } = installBridge() - render() - - const listener = onExternalOpenFailed.mock.calls[0][0] - fail(listener, 'https://example.com/dead') - + expect(screen.getByText('https://example.com/dead')).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: /copy/i })) - - await waitFor(() => expect(writeClipboard).toHaveBeenCalledWith('https://example.com/dead')) - }) - - it('closes when dismissed', async () => { - const { onExternalOpenFailed } = installBridge() - render() - - const listener = onExternalOpenFailed.mock.calls[0][0] - fail(listener, 'https://example.com/dead') - + await waitFor((): void => { expect(writeClipboard).toHaveBeenCalledWith('https://example.com/dead') }) fireEvent.click(screen.getByRole('button', { name: 'Close' })) - - await waitFor(() => expect(screen.queryByText('https://example.com/dead')).toBeNull()) + await waitFor((): void => { expect(screen.queryByText('https://example.com/dead')).toBeNull() }) }) it('renders nothing in a HUD window', () => { diff --git a/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx b/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx index 50d33c812e..5c4d9838cf 100644 --- a/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx +++ b/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx @@ -1,4 +1,4 @@ -import { act, cleanup, renderHook } from '@testing-library/react' +import { act, cleanup, renderHook, type RenderHookResult } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { DesktopConnectionProbeResult } from '@/global' @@ -88,3 +88,36 @@ describe('remote setup owner', () => { expect(onNotice).not.toHaveBeenCalled() }) }) + +it.each(['first-run', 'settings', 'registry'])('stale probes and credential tests cannot authorize %s', async (host: RemoteSetupHost): Promise => { + const probe: ReturnType> = deferred() + const tested: ReturnType>>> = deferred() + + const bridge = { + probeConnectionConfig: vi.fn().mockReturnValue(probe.promise), + testConnectionConfig: vi.fn().mockReturnValue(tested.promise) + } satisfies Pick + + Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: bridge }) + const { result }: RenderHookResult, void> = renderHook((): ReturnType => useRemoteSetup({ host })) + act((): void => { result.current.setAuthMode('oauth'); result.current.setUrl('https://a.example') }) + await act(async (): Promise => { await vi.advanceTimersByTimeAsync(500) }) + act((): void => { result.current.setUrl('not-a-url') }) + await act(async (): Promise => { probe.resolve(probeResult('token', 'old')) }) + expect(result.current.probeStatus).not.toBe('done') + expect(result.current.canTest).toBe(false) + expect(result.current.credentials.authMode).toBe('oauth') + + bridge.probeConnectionConfig.mockResolvedValue(probeResult('token', 'new')) + act((): void => { result.current.setAuthMode('token'); result.current.setUrl('https://b.example'); result.current.setToken('token-a') }) + await act(async (): Promise => { await vi.advanceTimersByTimeAsync(500) }) + expect(result.current.canTest).toBe(true) + let pending!: Promise + await act(async (): Promise => { pending = result.current.test() }) + expect(bridge.testConnectionConfig).toHaveBeenCalledExactlyOnceWith({ mode: 'remote', remoteUrl: 'https://b.example', remoteAuthMode: 'token', remoteToken: 'token-a' }) + act((): void => { result.current.setToken('token-b') }) + await act(async (): Promise => { tested.resolve({ ok: true, baseUrl: 'https://b.example', version: null }); await pending }) + expect(result.current.success).toBeNull() + expect(result.current.testing).toBe(false) + expect(result.current.canCommit).toBe(host !== 'first-run') +}) diff --git a/apps/desktop/src/components/sync-status-card.test.tsx b/apps/desktop/src/components/sync-status-card.test.tsx index 06ee1c7ef5..79120cee26 100644 --- a/apps/desktop/src/components/sync-status-card.test.tsx +++ b/apps/desktop/src/components/sync-status-card.test.tsx @@ -1,88 +1,68 @@ import { act, cleanup, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, expect, it, vi } from 'vitest' import type { DesktopSyncReceipt } from '@/global' import { SyncStatusCard } from './sync-status-card' -function setBridge(receipt: DesktopSyncReceipt | null | Promise, failing = false) { - ;(window as any).hermesDesktop = { - getSyncStatus: failing - ? vi.fn(() => Promise.reject(new Error('bridge gone'))) - : vi.fn(() => Promise.resolve(receipt)) - } +afterEach((): void => { cleanup(); vi.unstubAllGlobals() }) + +const details: DesktopSyncReceipt = { + plugin_bisect: [ + { plugin: 'conflictor', action: 'disabled', reason: 'conflicts with core pin' }, + { plugin: 'kept', action: 'kept', reason: '' } + ], + plugin_checks: [ + { name: 'bad-url', needs_fixing: 'update_url points at a fork', update_available: false }, + { name: 'grower', update_available: true, current: '1.0.0', latest: '1.1.0' }, + { name: 'fine', update_available: false } + ] } -afterEach(() => { - cleanup() - delete (window as any).hermesDesktop -}) - -async function renderCard() { - await act(async () => { - render() - }) +interface ReceiptCase { + name: string + receipt: DesktopSyncReceipt | null + headline: RegExp | null + tone?: string } -describe("SyncStatusCard — the renderer's getSyncStatus warning surface", () => { - it('renders the needs-fixing warning headline and per-plugin reasons', async () => { - setBridge({ - kind: 'sync', - outcome: 'checked', - plugin_checks: [ - { name: 'bad-url', needs_fixing: 'update_url points at a fork', update_available: false }, - { name: 'fine', update_available: false } - ] - }) - await renderCard() +const cases: ReceiptCase[] = [ + { name: 'missing', receipt: null, headline: null }, + { name: 'empty', receipt: {}, headline: null }, + { name: 'healthy no-op', receipt: { outcome: 'ok', venv_rebuild: { ok: false, reason: 'already in sync' } }, headline: null }, + { name: 'unknown availability', receipt: { plugin_checks: [{ name: 'mystery', update_available: null }] }, headline: null }, + { name: 'embedded failed', receipt: { ...details, outcome: 'ok', pm_sync_outcome: 'failed', pm_steps: [{ name: 'sync', ok: false, detail: 'network unavailable' }] }, headline: /rebuild failed — network unavailable/, tone: 'text-destructive' }, + { name: 'embedded refused', receipt: { ...details, pm_sync_outcome: 'refused' }, headline: /rebuild failed/, tone: 'text-destructive' }, + { name: 'legacy failed', receipt: { ...details, outcome: 'failed', venv_rebuild: { ok: false, reason: 'uv sync exited 1' } }, headline: /rebuild failed — uv sync exited 1/, tone: 'text-destructive' }, + { name: 'review beats bisect and updates', receipt: details, headline: /need update-url review/, tone: 'text-amber-600' }, + { name: 'bisect beats updates', receipt: { ...details, plugin_checks: details.plugin_checks?.slice(1) }, headline: /disabled by dependency conflicts/, tone: 'text-amber-600' }, + { name: 'updates only', receipt: { plugin_checks: details.plugin_checks?.slice(1) }, headline: /Plugin updates available/, tone: 'text-muted-foreground' } +] - expect(screen.getByTestId('sync-status-card')).toBeTruthy() - expect(screen.getByText(/need update-url review/)).toBeTruthy() - expect(screen.getByText(/bad-url: update_url points at a fork/)).toBeTruthy() - expect(screen.queryByText(/fine/)).toBeNull() - }) +it.each(cases)('$name receipt paints the dominant warning and subordinate rows', async ({ receipt, headline, tone }: ReceiptCase): Promise => { + vi.stubGlobal('hermesDesktop', { + getSyncStatus: async (): Promise => receipt + } satisfies Pick) + await act(async (): Promise => { render() }) - it('renders bisect disables and available updates', async () => { - setBridge({ - kind: 'sync', - outcome: 'bisected', - plugin_bisect: [{ plugin: 'conflictor', action: 'disabled', reason: 'conflicts with core pin' }], - plugin_checks: [{ name: 'grower', update_available: true, current: '1.0.0', latest: '1.1.0' }] - }) - await renderCard() + if (!headline) { expect(screen.queryByTestId('sync-status-card')).toBeNull(); - expect(screen.getByText(/disabled by dependency conflicts/)).toBeTruthy() - expect(screen.getByText(/conflictor: conflicts with core pin/)).toBeTruthy() - expect(screen.getByText(/grower: 1.0.0 → 1.1.0/)).toBeTruthy() - }) + return } - it('renders a failed venv rebuild as the top signal', async () => { - setBridge({ - kind: 'sync', - outcome: 'failed', - venv_rebuild: { ok: false, reason: 'uv sync exited 1' } - }) - await renderCard() + expect(screen.getByText(headline).className).toContain(tone) - expect(screen.getByText(/rebuild failed/)).toBeTruthy() - }) + if (receipt?.plugin_bisect) { expect(screen.getByText('conflictor: conflicts with core pin')).toBeTruthy() } - it('renders nothing without a receipt and nothing on a healthy receipt', async () => { - setBridge(null) - const { container } = render() - await act(async () => {}) - expect(container.textContent).toBe('') + if (receipt?.plugin_checks?.some(row => row.needs_fixing)) { expect(screen.getByText('bad-url: update_url points at a fork')).toBeTruthy() } + expect(screen.getByText('grower: 1.0.0 → 1.1.0')).toBeTruthy() + expect(screen.queryByText('fine')).toBeNull() + expect(screen.queryByText('kept')).toBeNull() +}) - cleanup() - setBridge({ kind: 'sync', outcome: 'ok' }) - await renderCard() - expect(screen.queryByTestId('sync-status-card')).toBeNull() - }) - - it('a broken bridge degrades to nothing instead of breaking the updates overlay', async () => { - setBridge(null, true) - const { container } = render() - await act(async () => {}) - expect(container.textContent).toBe('') - }) +it('a rejected bridge leaves the overlay usable', async (): Promise => { + vi.stubGlobal('hermesDesktop', { + getSyncStatus: async (): Promise => { throw new Error('bridge gone') } + } satisfies Pick) + await act(async (): Promise => { render() }) + expect(screen.queryByTestId('sync-status-card')).toBeNull() }) diff --git a/apps/desktop/src/components/sync-status.test.ts b/apps/desktop/src/components/sync-status.test.ts deleted file mode 100644 index 1c3cd72df0..0000000000 --- a/apps/desktop/src/components/sync-status.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { describe, expect, test } from 'vitest' - -import type { DesktopSyncReceipt } from '@/global' - -import { deriveSyncStatusSummary } from './sync-status' - -describe('deriveSyncStatusSummary', () => { - test('a no-op sync is healthy, while an embedded failed sync is visible', () => { - expect(deriveSyncStatusSummary({ outcome: 'ok', venv_rebuild: { ok: false, reason: 'already in sync' } }).headline).toBeNull() - - const receipt = { - outcome: 'failed', pm_sync_outcome: 'failed', - pm_steps: [{ name: 'dependency-sync', ok: false, detail: 'network unavailable' }] - } - - const summary = deriveSyncStatusSummary(receipt) - expect(summary.level).toBe('error') - expect(summary.headline).toContain('network unavailable') - }) - - test('null receipt degrades to nothing-to-show', () => { - const summary = deriveSyncStatusSummary(null) - expect(summary.headline).toBeNull() - expect(summary.level).toBe('ok') - expect(summary.disabledPlugins).toEqual([]) - }) - - test('empty receipt degrades the same', () => { - const summary = deriveSyncStatusSummary({}) - expect(summary.headline).toBeNull() - }) - - test('failed rebuild is the top signal (error level)', () => { - const receipt: DesktopSyncReceipt = { - kind: 'sync', - outcome: 'failed', - venv_rebuild: { ok: false, reason: 'uv sync exited 1: unsatisfiable' } - } - - const summary = deriveSyncStatusSummary(receipt) - expect(summary.level).toBe('error') - expect(summary.headline).toContain('rebuild failed') - }) - - test('bisect disables surface as warn with reasons', () => { - const receipt: DesktopSyncReceipt = { - kind: 'sync', - outcome: 'bisected', - plugin_bisect: [ - { plugin: 'bad-plug', action: 'disabled', reason: 'conflicts with core pin' }, - { plugin: 'kept-plug', action: 'kept', reason: '' } - ] - } - - const summary = deriveSyncStatusSummary(receipt) - expect(summary.level).toBe('warn') - expect(summary.disabledPlugins).toEqual([ - { plugin: 'bad-plug', reason: 'conflicts with core pin' } - ]) - expect(summary.headline).toContain('disabled') - }) - - test('needs-fixing beats updates in priority', () => { - const receipt: DesktopSyncReceipt = { - kind: 'plugin-check', - outcome: 'updates-available', - plugin_checks: [ - { - name: 'plug', - needs_fixing: 'update_url mismatch: saved vs manifest' - }, - { name: 'other', update_available: true, current: '1.0', latest: '2.0' } - ] - } - - const summary = deriveSyncStatusSummary(receipt) - expect(summary.level).toBe('warn') - expect(summary.headline).toContain('update-url') - expect(summary.needsFixing).toHaveLength(1) - expect(summary.updatesAvailable).toEqual([ - { name: 'other', current: '1.0', latest: '2.0' } - ]) - }) - - test('plain updates-available is info, not warn', () => { - const receipt: DesktopSyncReceipt = { - kind: 'plugin-check', - outcome: 'updates-available', - plugin_checks: [{ name: 'plug', update_available: true, current: '1.0', latest: '1.1' }] - } - - const summary = deriveSyncStatusSummary(receipt) - expect(summary.level).toBe('info') - expect(summary.headline).toContain('updates available') - }) - - test('unknown update_available (null) is not an update', () => { - const receipt: DesktopSyncReceipt = { - kind: 'plugin-check', - plugin_checks: [{ name: 'mystery', update_available: null, reason: 'not on PyPI' }] - } - - const summary = deriveSyncStatusSummary(receipt) - expect(summary.updatesAvailable).toEqual([]) - expect(summary.headline).toBeNull() - }) -}) diff --git a/apps/desktop/src/components/version-details-store.test.tsx b/apps/desktop/src/components/version-details-store.test.tsx deleted file mode 100644 index cf97d70936..0000000000 --- a/apps/desktop/src/components/version-details-store.test.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { cleanup, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it } from 'vitest' - -import type { DesktopVersionInfo } from '@/global' -import { I18nProvider } from '@/i18n' - -import { VersionDetails } from './version-details' - -const baseVersion: DesktopVersionInfo = { - appVersion: '0.19.0', - electronVersion: '37.0.0', - hermesRoot: '/tmp/hermes', - nodeVersion: '22.0.0', - platform: 'linux' -} - -afterEach(cleanup) - -describe('VersionDetails Store identity label', () => { - it('labels a Store-identity build from the stamp mechanism, not windowsStore', () => { - render( - - - - ) - - expect(screen.getByText('Distribution')).toBeTruthy() - expect(screen.getByText('Microsoft Store')).toBeTruthy() - expect(screen.queryByText('Desktop app (MSIX)')).toBeNull() - }) - - it('keeps the MSIX label for the out-of-store app-installer build', () => { - render( - - - - ) - - expect(screen.getByText('Desktop app (MSIX)')).toBeTruthy() - expect(screen.queryByText('Microsoft Store')).toBeNull() - }) -}) diff --git a/apps/desktop/src/components/version-details.test.tsx b/apps/desktop/src/components/version-details.test.tsx index 4b697f2563..86b9b4d83c 100644 --- a/apps/desktop/src/components/version-details.test.tsx +++ b/apps/desktop/src/components/version-details.test.tsx @@ -1,5 +1,5 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, type Mock, vi } from 'vitest' import type { DesktopVersionInfo } from '@/global' import { I18nProvider } from '@/i18n' @@ -7,29 +7,10 @@ import { $previewTabs, closeRightRail } from '@/store/preview' import { VersionDetails } from './version-details' -const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] } -const initialHermesDesktop = desktopWindow.hermesDesktop - -function installDesktopBridge() { - const openExternal = vi.fn().mockResolvedValue(undefined) - - desktopWindow.hermesDesktop = { - openExternal - } as unknown as Window['hermesDesktop'] - - return openExternal -} - -afterEach(() => { +afterEach((): void => { cleanup() closeRightRail() - vi.restoreAllMocks() - - if (initialHermesDesktop) { - desktopWindow.hermesDesktop = initialHermesDesktop - } else { - delete desktopWindow.hermesDesktop - } + vi.unstubAllGlobals() }) const baseVersion: DesktopVersionInfo = { @@ -41,98 +22,36 @@ const baseVersion: DesktopVersionInfo = { } describe('VersionDetails', () => { - it('omits the branch suffix when no branch is present', () => { - render( - - - - ) + interface VersionCase { version: Partial; visible: string[]; absent?: string[] } - expect(screen.getByText('Build Origin')).toBeTruthy() - expect(screen.getByText('CI')).toBeTruthy() - }) + const cases: VersionCase[] = [ + { version: { source: 'ci', branch: null }, visible: ['Build Origin', 'CI'] }, + { version: { source: 'ci', branch: 'unknown' }, visible: ['CI (unknown)'] }, + { version: { source: 'nix', distribution: 'nix' }, visible: ['Build Origin', 'Nix', 'Distribution'] }, + { version: { source: 'ci', distribution: 'docker' }, visible: ['CI', 'Distribution', 'Docker'] }, + { version: { distribution: 'desktop-app', hermesRuntime: { type: 'embedded' } }, visible: ['Runtime', 'Embedded runtime'] }, + { version: { hermesRuntime: { type: 'external', source: { type: 'git', root: '/home/u/.hermes/hermes-agent' } } }, + visible: ['Runtime', 'git (/home/u/.hermes/hermes-agent)'], absent: ['External (uses the machine runtime)'] }, + { version: { hermesRuntime: { type: 'external' } }, visible: ['Runtime', 'External (uses the machine runtime)'] }, + { version: { distribution: 'desktop-app', updateMechanism: 'microsoft-store' }, + visible: ['Distribution', 'Microsoft Store'], absent: ['Desktop app (MSIX)'] }, + { version: { distribution: 'desktop-app', updateMechanism: 'app-installer' }, + visible: ['Desktop app (MSIX)'], absent: ['Microsoft Store'] } + ] - it('shows a literal branch named unknown inline', () => { - render( - - - - ) + it.each(cases)('renders $version', ({ version, visible, absent = [] }: VersionCase): void => { + render() - expect(screen.getByText('CI (unknown)')).toBeTruthy() - }) + for (const text of visible) { expect(screen.getAllByText(text).length).toBeGreaterThan(0) } - it('shows the Nix source and distribution from the stamp', () => { - render( - - - - ) + for (const text of absent) { expect(screen.queryByText(text)).toBeNull() } - expect(screen.getByText('Build Origin')).toBeTruthy() - expect(screen.getAllByText('Nix')).toHaveLength(2) - expect(screen.getByText('Distribution')).toBeTruthy() - }) - - it('distinguishes CI provenance from the Docker distribution', () => { - render( - - - - ) - - expect(screen.getByText('CI')).toBeTruthy() - expect(screen.getByText('Distribution')).toBeTruthy() - expect(screen.getByText('Docker')).toBeTruthy() - }) - - it('shows the runtime row for an embedded build running its payload', () => { - render( - - - - ) - - expect(screen.getByText('Runtime')).toBeTruthy() - expect(screen.getByText('Embedded runtime')).toBeTruthy() - }) - - it('shows the runtime source with its location when an external build runs a machine runtime', () => { - render( - - - - ) - - expect(screen.getByText('Runtime')).toBeTruthy() - expect(screen.getByText('git (/home/u/.hermes/hermes-agent)')).toBeTruthy() - expect(screen.queryByText('External (uses the machine runtime)')).toBeNull() - }) - - it('shows the generic external label before the first backend spawn', () => { - render( - - - - ) - - expect(screen.getByText('Runtime')).toBeTruthy() - expect(screen.getByText('External (uses the machine runtime)')).toBeTruthy() + if (version.source === 'nix') { expect(screen.getAllByText('Nix')).toHaveLength(2) } }) it('opens the commit URL via the system-browser bridge without opening a preview tab', async () => { - const openExternal = installDesktopBridge() + const openExternal: Mock = vi.fn().mockResolvedValue(undefined) + vi.stubGlobal('hermesDesktop', { openExternal } satisfies Pick) render( diff --git a/apps/desktop/src/i18n/key-parity.test.ts b/apps/desktop/src/i18n/key-parity.test.ts deleted file mode 100644 index 98a2a7b366..0000000000 --- a/apps/desktop/src/i18n/key-parity.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { ar } from './ar' -import { en } from './en' -import { ja } from './ja' -import { ru } from './ru' -import { zh } from './zh' -import { zhHant } from './zh-hant' - -/** - * Locale key-parity guard — the class-fix for the recurring "missed locale" - * bug family: a key renamed in en.ts but left stale in a partial locale - * (e.g. `view.terminalSelection` → `view.selectionToComposer`, which missed - * ru.ts for weeks and made the renamed row fall back to English for ru - * users). - * - * `defineLocale()` locales are PARTIAL by design — missing keys fall back to - * English at runtime (that's the documented contract). What must never - * happen is a locale carrying a *stale* key: en renamed or removed a leaf - * while the locale kept the old name. The old key is dead weight at best - * and a silently-lost translation at worst. - * - * Invariant (one-directional): when en has a NON-EMPTY section, every - * locale key under that section must still exist in en. Sections en emptied - * entirely (`platformIntro: {}` — free-form `Record` - * overrides read before a code-level fallback const) are exempt: a locale - * may legitimately carry extra free-form keys en leaves empty. - */ - -type LeafKey = string - -type Obj = Record - -function asObj(value: unknown): Obj | null { - return typeof value === 'object' && value !== null && !Array.isArray(value) - ? (value as Obj) - : null -} - -function leafEntries(value: unknown, prefix = ''): LeafKey[] { - const obj = asObj(value) - - if (obj === null) { - return prefix ? [prefix] : [] - } - - const out: LeafKey[] = [] - - for (const [key, child] of Object.entries(obj)) { - const path = prefix ? `${prefix}.${key}` : key - out.push(...leafEntries(child, path)) - } - - return out -} - -function keySet(obj: unknown): Set { - return new Set(leafEntries(obj)) -} - -/** Value at a dot-path in the en tree, or undefined. */ -function enAt(path: string): unknown { - let node: unknown = en - - for (const part of path.split('.')) { - const obj = asObj(node) - - if (obj === null) {return undefined} - node = obj[part] - - if (node === undefined) {return undefined} - } - - return node -} - -/** - * Stale = a locale key whose en counterpart is gone while its enclosing en - * section is still live. Walks ancestor paths from longest to shortest: - * - ancestor exists in en as an EMPTY object → free-form section en - * intentionally leaves empty (platformIntro: {} with a code fallback - * const); locale overrides are legitimate → EXEMPT - * - ancestor exists in en as a live (non-empty) object → the leaf should - * exist in en too; if it doesn't, the key was renamed/removed in en but - * left behind in the locale → STALE - * - ancestor not in en at all → keep walking up (the section may have - * moved wholesale into a live grandparent) - */ -function staleUnderLiveParents(locale: unknown): LeafKey[] { - const enKeys = keySet(en) - - return [...keySet(locale)].filter((k) => { - if (enKeys.has(k)) {return false} - const parts = k.split('.') - - for (let i = parts.length - 1; i >= 1; i -= 1) { - const parent = parts.slice(0, i).join('.') - const enValue = enAt(parent) - - if (enValue === undefined) {continue} // keep walking up - const obj = asObj(enValue) - - if (obj !== null && Object.keys(obj).length === 0) { - return false // en emptied this whole section → locale extras are legit - } - - return true // live section (or scalar) → leaf should still exist in en - } - - return false - }).sort() -} - -const LOCALES: Array<[string, unknown]> = [ - ['zh', zh], - ['zh-hant', zhHant], - ['ja', ja], - ['ar', ar], - ['ru', ru], -] - -describe('desktop i18n key parity with en', () => { - it.each(LOCALES)('%s has no stale keys under live en sections', (_name, locale) => { - const stale = staleUnderLiveParents(locale) - expect( - stale, - `stale keys in ${_name} — renamed/removed in en.ts but still declared here` - ).toEqual([]) - }) - - it('reports partial-locale coverage so the translation backlog is visible', () => { - // Visibility only — NOT a failure. Partial locales are a supported state - // (defineLocale falls back to English for missing keys), so a missing - // key is a translation backlog item, not a bug. This just forces the - // counts into CI output so a locale quietly losing coverage shows up. - const enKeys = keySet(en) - const missing: string[] = [] - - for (const [name, locale] of LOCALES) { - const localeSet = keySet(locale) - const absent = [...enKeys].filter((k) => !localeSet.has(k)) - - if (absent.length > 0) { - missing.push(`${name}: ${absent.length} keys fall back to English (${absent.slice(0, 3).join(', ')}…)`) - } - } - - if (missing.length > 0) { - console.info(`[i18n key-parity] partial-locale coverage:\n${missing.join('\n')}`) - } - }) -}) diff --git a/apps/desktop/src/store/local-models-surfaces.test.tsx b/apps/desktop/src/store/local-models-surfaces.test.tsx index d5ab528c6b..2d126b793b 100644 --- a/apps/desktop/src/store/local-models-surfaces.test.tsx +++ b/apps/desktop/src/store/local-models-surfaces.test.tsx @@ -4,7 +4,7 @@ import { MemoryRouter } from 'react-router' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import type { HermesApiRequest, HermesConnection } from '@/global' -import type { LocalModelsStatus, LocalRuntimeJob, ModelOptionsResponse } from '@/types/hermes' +import type { LocalCatalogModel, LocalModelsStatus, LocalRuntimeJob, ModelOptionsResponse } from '@/types/hermes' vi.mock('@/hermes', async (): Promise => ({ ...(await import('@/api/local-models')), @@ -31,7 +31,7 @@ import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu import { I18nProvider } from '@/i18n' import { queryClient } from '@/lib/query-client' import { $localModelsEnabled } from '@/store/local-models-flag' -import { notify } from '@/store/notifications' +import { notify, notifyError } from '@/store/notifications' import { $activeGatewayProfile } from '@/store/profile' import { $connection } from '@/store/session' import { deferred } from '@/test/deferred' @@ -79,6 +79,12 @@ const running: LocalRuntimeJob = { } let jobs: LocalRuntimeJob[] = [] +let catalog: LocalCatalogModel[] = [] + +const model: LocalCatalogModel = { + id: 'model', display_name: 'Download A', description: '', size_bytes: 2, size_label: '2 B', + native_context: 4096, native_context_label: '4K', recommended: true, downloaded: false, fits: true, mtp: false, fit_summary: 'fits' +} const api = vi.fn(async (request: HermesApiRequest): Promise => { if (request.path.endsWith('/status')) { @@ -86,13 +92,21 @@ const api = vi.fn(async (request: HermesApiRequest): Promise => { } if (request.path.endsWith('/catalog')) { - return { models: [] } + return { models: catalog } } if (request.path.endsWith('/jobs')) { return { jobs: structuredClone(jobs) } } + if (request.path.endsWith('/download/pause') || request.path.endsWith('/download/resume')) { + expect(request).toMatchObject({ connectionId: 'A', profile: 'work', method: 'POST', body: { job_id: 'same-id' } }) + const paused: boolean = request.path.endsWith('/pause') + jobs = jobs.map((job: LocalRuntimeJob): LocalRuntimeJob => ({ ...job, status: paused ? 'paused' : 'running', can_pause: !paused, can_resume: paused })) + + return paused ? { ok: true, paused: true } : { ok: true, resumed: true } + } + if (request.path.endsWith('/hardware')) { return {} } @@ -112,9 +126,11 @@ beforeEach((): void => { vi.useFakeTimers() queryClient.clear() jobs = [] + catalog = [] api.mockClear() $connection.set(null) vi.mocked(notify).mockClear() + vi.mocked(notifyError).mockClear() Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { api } }) setApiRequestConnection('A') setApiRequestProfile('work') @@ -357,3 +373,33 @@ it('keeps menu focus and its scalar selection stable across byte updates and out expect(screen.getByText('75%')).toBeTruthy() expect(window.document.activeElement).toBe(input) }) + +it.each(['model-download', 'quickstart', 'runtime-install'] as const)('%s pause and resume travel through the owner API and publish server truth', async (kind: LocalRuntimeJob['kind']): Promise => { + catalog = [model] + jobs = [{ ...running, kind, can_pause: true, phase: kind === 'runtime-install' ? 'downloading-runtime' : 'downloading' }] + const settings: RenderResult = mountSettings() + await tick() + fireEvent.click(screen.getByRole('button', { name: /pause/i })) + await tick() + expect(jobs[0].status).toBe('paused') + expect(screen.getByRole('button', { name: /resume/i })).toBeTruthy() + expect(screen.getAllByText(/paused/i).length).toBeGreaterThan(0) + expect(screen.getAllByRole('progressbar').some((bar: HTMLElement): boolean => bar.getAttribute('aria-valuenow') === '50')).toBe(true) + expect(notify).not.toHaveBeenCalled() + expect(notifyError).not.toHaveBeenCalled() + + if (kind === 'quickstart') { expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull() } + fireEvent.click(screen.getByRole('button', { name: /resume/i })) + await tick() + expect(jobs[0].status).toBe('running') + expect(api.mock.calls.filter(([request]): boolean => request.method === 'POST').map(([request]): string => request.path)) + .toEqual(['/api/local-models/download/pause', '/api/local-models/download/resume']) + jobs = [{ ...jobs[0], status: 'done' }] + await tick(3_000) + expect(notify).toHaveBeenCalledTimes(1) + settings.unmount() + watchLocalRuntimeJobs({ connectionId: 'A', profile: 'work' }) + await tick() + expect(notify).toHaveBeenCalledTimes(1) + expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status')).length).toBeGreaterThan(1) +}) diff --git a/apps/desktop/src/store/local-runtime-jobs.test.ts b/apps/desktop/src/store/local-runtime-jobs.test.ts index 6ebe5f1c62..a3b0236a45 100644 --- a/apps/desktop/src/store/local-runtime-jobs.test.ts +++ b/apps/desktop/src/store/local-runtime-jobs.test.ts @@ -85,47 +85,6 @@ async function pollTick() { } describe('local runtime jobs store — pause/settle contract', () => { - it('running→paused settles NOTHING: no error toast, job stays visible', async () => { - backend.jobs = [job({ done_bytes: 40 })] - await pollTick() - expect( - (queryClient.getQueryData(localModelsKey(localModelsOwner(), 'jobs')) ?? [])[0] - ?.status - ).toBe('running') - - // Backend pauses the job (status='paused', error=null). - backend.jobs = [job({ done_bytes: 40, status: 'paused' })] - await pollTick() - await pollTick() - - expect(notifyError).not.toHaveBeenCalled() - expect(notify).not.toHaveBeenCalled() - - const snapshot = - queryClient.getQueryData(localModelsKey(localModelsOwner(), 'jobs')) ?? [] - - expect(snapshot).toHaveLength(1) - expect(snapshot[0]?.status).toBe('paused') - }) - - it('a paused job that resumes and finishes notifies done exactly once (paused→done still notifies)', async () => { - backend.jobs = [job({ done_bytes: 40 })] - await pollTick() - - backend.jobs = [job({ done_bytes: 40, status: 'paused' })] - await pollTick() - - backend.jobs = [job({ done_bytes: 60 })] - await pollTick() - - backend.jobs = [job({ done_bytes: 100, percent: 100, status: 'done', total_bytes: 100 })] - await pollTick() - - expect(notify).toHaveBeenCalledTimes(1) - expect(vi.mocked(notify).mock.calls[0][0]).toMatchObject({ kind: 'success' }) - expect(notifyError).not.toHaveBeenCalled() - }) - it('running→error still toasts exactly once', async () => { backend.jobs = [job({ done_bytes: 10, job_id: 'j-err' })] await pollTick() @@ -137,28 +96,6 @@ describe('local runtime jobs store — pause/settle contract', () => { expect(notify).not.toHaveBeenCalled() }) - it('keeps polling while a job is paused (a resume from another surface is witnessed)', async () => { - backend.jobs = [job({ status: 'paused' })] - await pollTick() - - const callsAfterPause = vi.mocked(getLocalModelsJobs).mock.calls.length - expect(callsAfterPause).toBeGreaterThan(0) - - // The paused cadence is slower (3s), not dead: wait past it and the - // poll fires again WITHOUT any new kick. - await settle(3_400) - - expect(vi.mocked(getLocalModelsJobs).mock.calls.length).toBeGreaterThan(callsAfterPause) - - // And a backend-side resume IS picked up with no local kick at all. - backend.jobs = [job({ done_bytes: 90 })] - await pollTick() - expect( - (queryClient.getQueryData(localModelsKey(localModelsOwner(), 'jobs')) ?? [])[0] - ?.status - ).toBe('running') - }) - it('publishes a pinned job response into an injected QueryClient observer', async (): Promise => { const client: QueryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) const owner: LocalModelsOwner = { connectionId: 'A', profile: 'work' } diff --git a/tests-js/bundle-inputs.test.mjs b/tests-js/bundle-inputs.test.mjs index 7c20ee3b1e..501f2253d6 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 t for (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,64 @@ 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/], + ['arch', 'arm64', /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:pass@example.com/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/], + ]), + ] + const oldCases = cases.filter(([field]) => field.startsWith('new') && field !== 'new.version') + .map(([field, value, diagnostic]) => [field.replace(/^new/, 'old'), + field === 'new.commit' && value === 'a'.repeat(40) ? 'b'.repeat(40) : + field === 'new.artifact.sha256' && value === 'a'.repeat(64) ? 'b'.repeat(64) : value, diagnostic]) + oldCases.push(...(platform === 'windows' ? [ + ['old.version', '1.3.0.0', /increase/], ['old.version', '1.4.0.0', /increase/], + ['old.version', '1.2.0', /four numeric/], ['old.version', '1.2.65536.0', /16 bits/], + ] : [['old.version', '1.9.0', /match/]])) + for (const [field, value, diagnostic] of [...cases, ...oldCases]) { + 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') + expect(() => validateBundleInputs(fixture(platform), platform, 'arm64')).toThrow('architecture') + 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 +106,37 @@ test('staging streams actual bytes, verifies hashes and removes rejected partial cleanup.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 slot of ['old', 'new']) { + for (const missing of [undefined, path.join(directory, 'missing'), directory]) { + const bad = structuredClone(result); bad[slot].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.ts index e94a6c0fbf..e7c0ab4764 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 file diff --git a/tests-js/generate-icons.test.mjs b/tests-js/generate-icons.test.mjs index 28ab64ef12..9649b779f5 100644 --- a/tests-js/generate-icons.test.mjs +++ b/tests-js/generate-icons.test.mjs @@ -1,114 +1,27 @@ -import { spawnSync } from 'node:child_process' -import path from 'node:path' import fs from 'node:fs' import os from 'node:os' +import path from 'node:path' import { fileURLToPath } from 'node:url' import { expect, test, vi } from 'vitest' import { generateIcons } from '../scripts/generate-icons.mjs' -test('icon builds delegate environment preparation to PM using the prepared Python', () => { - const run = vi.fn(() => ({ status: 0 })) - const root = path.resolve('icon-build-fixture') - const env = { PATH: 'tools', HERMES_PYTHON: 'prepared-python', VIRTUAL_ENV: 'runtime-venv', PYTHONPATH: 'payload-libraries', PYTHONHOME: 'payload-python' } - expect(generateIcons(['--check'], { root, run, env })).toBe(0) - expect(run).toHaveBeenCalledExactlyOnceWith(env.HERMES_PYTHON, [ - path.join(root, 'scripts', 'build', 'icon_environment.py'), '--source', root, '--out', root, '--check' - ], { cwd: root, stdio: 'inherit', windowsHide: true, env: { PATH: 'tools', HERMES_PYTHON: env.HERMES_PYTHON, VIRTUAL_ENV: 'runtime-venv' } }) - expect(env.PYTHONPATH).toBe('payload-libraries') -}) - -test('icon preparation passes explicit source and independent output roots', () => { - const run = vi.fn(() => ({ status: 0 })) - const source = path.resolve('source with spaces') - const out = path.resolve('icon outputs') - expect(generateIcons(['--source', source, '--out', out], { run, env: {} })).toBe(0) - const [python, args, options] = run.mock.calls[0] - expect(python).toBe('python') - expect(args.slice(-4)).toEqual(['--source', source, '--out', out]) - expect(options.cwd).toBe(source) -}) - -test('on-demand icon preparation preserves admission intent at the PM boundary', () => { - const run = vi.fn(() => ({ status: 0 })) - expect(generateIcons(['--on-demand'], { run, env: {} })).toBe(0) - expect(run.mock.calls[0][1]).toContain('--on-demand') -}) - -test('the PM driver owns a temporary group-only environment and preserves generator argv and status', () => { - const result = spawnSync(process.env.HERMES_PYTHON || 'python', ['-c', ` -from pathlib import Path -import subprocess -import sys -from tempfile import TemporaryDirectory -from unittest.mock import patch -from scripts.build import icon_environment - -with TemporaryDirectory() as directory: - source = Path(directory) / 'source with spaces' - source.mkdir() - argv = ['--source', str(source), '--out', str(Path(directory) / 'icon outputs'), '--check'] - outputs = [] - explicit = True - def build(**options): - output = options.pop('out') - assert output.parent.is_dir() and not output.exists() - assert output.name == 'venv' - assert options == dict(source=source, groups=['icon-build'], only_groups=True, - explicit=explicit, cache=source / '.cache/icon-build') - outputs.append(output) - return Path(sys.executable) - def generate(command, **options): - assert outputs[0].parent.is_dir() - assert command == [sys.executable, '-I', str(Path(icon_environment.__file__).resolve().parents[1] / 'generate_icons.py'), *argv] - assert options == dict(cwd=source) - return subprocess.CompletedProcess(command, 7) - with patch.object(icon_environment.pm, 'build_environment', side_effect=build) as prepare, patch.object(icon_environment.subprocess, 'run', side_effect=generate) as run: - assert icon_environment.main(argv) == 7 - prepare.assert_called_once() - run.assert_called_once() - explicit = False - outputs.clear() - assert icon_environment.main([*argv, '--on-demand']) == 7 - assert not outputs[0].parent.exists() -`], { cwd: fileURLToPath(new URL('..', import.meta.url)), encoding: 'utf8' }) - expect(result.error).toBeUndefined() - expect(result.status, result.stderr).toBe(0) -}) - -test.each([ - { HERMES_PAYLOAD_TAG: 'v1.2.3', HERMES_BUILD_COMMIT: '' }, - { HERMES_PAYLOAD_TAG: 'v1.2.3-canary.20260911010203', HERMES_BUILD_COMMIT: '' }, - { HERMES_PAYLOAD_TAG: '', HERMES_BUILD_COMMIT: 'abcdef0'.padEnd(40, '1') } -])('build identity reaches the child unchanged with separate source/output roots: %j', (identity) => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-icon-env-')) +test('the real wrapper builds and checks native icon artifacts in an independent output', () => { + const out = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-icons-')) + const env = { ...process.env, HERMES_HOME: path.join(out, 'home'), + HERMES_RUNTIME_DIR: path.join(out, 'tools'), HERMES_PAYLOAD_TAG: 'v1.2.3', HERMES_BUILD_COMMIT: '', + PYTHONPATH: path.join(out, 'foreign-site'), PYTHONHOME: path.join(out, 'foreign-python') } try { - const source = path.join(root, 'separate source') - const out = path.join(root, 'generated output') - const driver = path.join(root, 'scripts', 'build') - fs.mkdirSync(driver, { recursive: true }) - fs.mkdirSync(source) - // Observe the real subprocess environment at the PM-driver boundary. - fs.writeFileSync(path.join(driver, 'icon_environment.py'), ` -import json, os, pathlib, sys -out = pathlib.Path(sys.argv[sys.argv.index('--out') + 1]) -out.mkdir() -(out / 'child.json').write_text(json.dumps({ - 'identity': {key: os.environ.get(key) for key in ['HERMES_PAYLOAD_TAG', 'HERMES_BUILD_COMMIT']}, - 'source': sys.argv[sys.argv.index('--source') + 1], - 'cwd': os.getcwd(), -})) -`) - expect(generateIcons(['--source', source, '--out', out], { - root, env: { ...process.env, ...identity } - })).toBe(0) - expect(JSON.parse(fs.readFileSync(path.join(out, 'child.json'), 'utf8'))).toEqual({ - identity, source, cwd: source - }) - expect(fs.readdirSync(source)).toEqual([]) + const args = ['--source', fileURLToPath(new URL('..', import.meta.url)), '--out', out] + expect(generateIcons(args, { env })).toBe(0) + const png = fs.readFileSync(path.join(out, 'apps/desktop/assets/icon.png')) + expect(png.subarray(0, 8)).toEqual(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) + expect([png.readUInt32BE(16), png.readUInt32BE(20)]).toEqual([1024, 1024]) + expect(generateIcons([...args, '--check'], { env })).toBe(0) + expect(env.PYTHONPATH).toBe(path.join(out, 'foreign-site')) } finally { - fs.rmSync(root, { recursive: true, force: true }) + fs.rmSync(out, { recursive: true, force: true }) } -}) +}, 180_000) test('failed icon processes cannot report a successful build', () => { expect(generateIcons([], { run: () => ({ status: 7 }), env: {} })).toBe(7) diff --git a/tests-js/macos-bundled-helpers.test.mjs b/tests-js/macos-bundled-helpers.test.mjs index 34e075712f..964abb9d6c 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 { 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' -import { expect, it, describe } from 'vitest' +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 +} -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() - }) -}) - -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('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() } - 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') +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}`) + } +}) - // 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', +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, }) - - // 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', - }) - 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.ts index a017990712..0bbb00eb42 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 -} +interface Engines { node?: string; npm?: string } +interface Manifest { engines?: Engines } +interface Lockfile { packages: Record } +interface PmLock { packages: { node: { version: string }; npm: { version: string } } } function readJson(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('package.json') +const desktop = readJson('apps/desktop/package.json') +const lock = readJson('package-lock.json') +const pins = readJson('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('package.json') -const desktopManifest = readJson('apps/desktop/package.json') -const lockfile = readJson('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', 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.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([ + ['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.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('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('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(['~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('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-js/product-builders.test.mjs b/tests-js/product-builders.test.mjs index 0c01b96fea..4ad12cf460 100644 --- a/tests-js/product-builders.test.mjs +++ b/tests-js/product-builders.test.mjs @@ -1,5 +1,5 @@ import { execFileSync } from 'node:child_process' -import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, symlinkSync } from 'node:fs' +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, symlinkSync, statSync, utimesSync } from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' import { createRequire } from 'node:module' @@ -288,9 +288,29 @@ test('TUI freshness invalidates source, configuration and compiler inputs and da put(source, 'ui-tui/src/value.ts', 'export const value: string = "shared source";') put(source, 'apps/shared/src/value.ts', 'export { value } from "../../../ui-tui/src/value";') put(source, 'ui-tui/src/entry.tsx', 'import { value } from "../../apps/shared/src/value"; console.log(value);') + put(source, 'package-lock.json', '{"lockfileVersion":3}') + const preservedTimes = new Date('2020-01-01T00:00:00Z') + const sameLengthChanges = [ + ['ui-tui/src/value.ts', 'shared', 'edited'], + ['apps/shared/src/value.ts', 'value', 'VALUE'], + ['package.json', 'true', 'null'], + ['package-lock.json', ':3', ':2'], + ] + for (const [name] of sameLengthChanges) utimesSync(path.join(source, name), preservedTimes, preservedTimes) await buildTui({ source, out }) const current = () => productCurrent({ source, product: 'tui', out: path.join(out, 'dist') }) expect(current()).toBe(true) + for (const [name, from, to] of sameLengthChanges) { + const file = path.join(source, name), previous = readFileSync(file, 'utf8'), before = statSync(file) + expect(previous).toContain(from) + writeFileSync(file, previous.replace(from, to)) + utimesSync(file, preservedTimes, preservedTimes) + expect([statSync(file).size, statSync(file).mtimeMs]).toEqual([before.size, before.mtimeMs]) + expect(current(), `same-size and same-mtime change in ${name}`).toBe(false) + writeFileSync(file, previous) + utimesSync(file, preservedTimes, preservedTimes) + expect(current(), `restored ${name}`).toBe(true) + } for (const name of [ 'ui-tui/src/value.ts', 'apps/shared/src/value.ts', 'ui-tui/packages/hermes-ink/src/entry-exports.ts', diff --git a/tests/agent/lsp/test_install_and_lint_fixes.py b/tests/agent/lsp/test_install_and_lint_fixes.py index e6f0e3f74e..c3c61e5283 100644 --- a/tests/agent/lsp/test_install_and_lint_fixes.py +++ b/tests/agent/lsp/test_install_and_lint_fixes.py @@ -45,32 +45,6 @@ def test_install_python_server_uses_pm_tool_environment(tmp_path, monkeypatch): assert install_mod.detect_status("fake-lsp") == "installed" -# --------------------------------------------------------------------------- -# Fix 2: ``hermes lsp status`` surfaces shellcheck-missing for bash -# --------------------------------------------------------------------------- - - - - - - -def test_backend_warnings_fires_when_bash_installed_but_shellcheck_missing(tmp_path, monkeypatch): - """The exact scenario from the bug report.""" - monkeypatch.setenv("HERMES_HOME", str(tmp_path)) - from agent.lsp import cli as lsp_cli - - def which(name): - if name == "bash-language-server": - return "/fake/bin/bash-language-server" - return None # shellcheck missing - - with patch("shutil.which", side_effect=which): - notes = lsp_cli._backend_warnings() - assert len(notes) == 1 - assert "shellcheck" in notes[0].lower() - assert "bash-language-server" in notes[0].lower() - - def test_status_output_includes_backend_warnings_section(tmp_path, monkeypatch): """End-to-end: status command output includes the warning section.""" monkeypatch.setenv("HERMES_HOME", str(tmp_path)) @@ -90,19 +64,7 @@ def test_status_output_includes_backend_warnings_section(tmp_path, monkeypatch): output = buf.getvalue() assert "Backend warnings" in output assert "shellcheck" in output - - -# --------------------------------------------------------------------------- -# Fix 3: tier-1 lint treats unusable linters as ``skipped``, not ``error`` -# --------------------------------------------------------------------------- - - - - - - - - + assert "bash-language-server" in output def test_check_lint_returns_error_for_real_ts_type_errors(tmp_path, monkeypatch): diff --git a/tests/agent/lsp/test_python_discovery.py b/tests/agent/lsp/test_python_discovery.py index 5cd716e1ad..0c95c1d2d9 100644 --- a/tests/agent/lsp/test_python_discovery.py +++ b/tests/agent/lsp/test_python_discovery.py @@ -1,19 +1,15 @@ """Pyright uses the project environment before the Hermes runtime fallback.""" -import json import os import subprocess import sys from pathlib import Path -import pm from pm import paths from pm.lock import Facts, Lockfile from pm.registry import get_package from pm.store import current_target -from agent.lsp.servers import _detect_python - def _seed_pm_python(tmp_path, monkeypatch): """Stage a pm bundled-install layout: HERMES_RUNTIME_DIR -> store with a @@ -41,79 +37,6 @@ def _seed_pm_python(tmp_path, monkeypatch): return exe -def test_pyright_respects_pm_writable_selection_over_old_bundle(tmp_path, monkeypatch): - monkeypatch.delenv("VIRTUAL_ENV", raising=False) - bundled = _seed_pm_python(tmp_path, monkeypatch) - bundled_facts = Facts(paths.facts_path()) - old = bundled_facts.get("python") - assert old is not None - store = paths.writable_store_root() - package = get_package("python") - target = current_target() - entry = store / old["entry"] - binary = package.binary(entry, target) - assert binary is not None - binary.parent.mkdir(parents=True) - binary.write_text("", encoding="utf-8") - Facts(store / "facts.json").record( - "python", old["version"], entry.name, package.env(entry, target), store, - target=target, artifacts=old["artifacts"], - ) - bundled_facts.record( - "python", "old-bundle", old["entry"], {}, paths.store_root(), - target=target, artifacts=old["artifacts"], - ) - before = paths.facts_path().read_bytes(), (store / "facts.json").read_bytes() - selected = pm.installed_package("python") - assert selected is not None and selected.binary == binary - assert _detect_python(str(tmp_path / "workspace")) == str(binary) - assert (paths.facts_path().read_bytes(), (store / "facts.json").read_bytes()) == before - assert bundled.is_file() - - -def test_pm_store_python_resolved_without_virtual_env(tmp_path, monkeypatch): - """No VIRTUAL_ENV anywhere — the pm store interpreter is the answer.""" - monkeypatch.delenv("VIRTUAL_ENV", raising=False) - exe = _seed_pm_python(tmp_path, monkeypatch) - - assert _detect_python(str(tmp_path / "some-workspace")) == str(exe) - - -def test_no_pm_python_falls_back_to_project_layouts(tmp_path, monkeypatch): - """Without a pm python fact, project .venv candidates still resolve.""" - monkeypatch.delenv("VIRTUAL_ENV", raising=False) - monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "no-such-store")) - - dot_venv_bin = tmp_path / "proj" / ".venv" / "bin" - dot_venv_bin.mkdir(parents=True) - python = dot_venv_bin / "python" - python.write_text("", encoding="utf-8") - - assert Path(_detect_python(str(tmp_path / "proj"))) == python - - -def test_missing_store_entry_is_not_an_answer(tmp_path, monkeypatch): - """A python fact whose store entry is gone resolves to None (pm only - vouches for what is on disk).""" - monkeypatch.delenv("VIRTUAL_ENV", raising=False) - payload = tmp_path / "payload" - store = payload / "tools" - store.mkdir(parents=True) - (payload / "manifest.json").write_text("{}", encoding="utf-8") - (store / "facts.json").write_text( - json.dumps( - { - "schema": 1, - "packages": {"python": {"entry": "python-3.11.13", "version": "3.11.13"}}, - } - ), - encoding="utf-8", - ) - monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store)) - - assert _detect_python(str(tmp_path / "some-workspace")) is None - - def test_pyright_uses_the_project_interpreter_before_hermes(tmp_path, monkeypatch): from agent.lsp import servers @@ -131,6 +54,11 @@ def test_pyright_uses_the_project_interpreter_before_hermes(tmp_path, monkeypatc assert spec is not None assert spec.initialization_options["python"]["pythonPath"] == str(pm_python) + pm_python.unlink() + spec = server.build_spawn(str(project), context) + assert spec is not None + assert "pythonPath" not in spec.initialization_options.get("python", {}) + for environment in (project / ".venv", tmp_path / "explicit-environment"): subprocess.run( [sys.executable, "-m", "venv", "--without-pip", str(environment)], diff --git a/tests/agent/metadata_transport.py b/tests/agent/metadata_transport.py new file mode 100644 index 0000000000..075778dfc7 --- /dev/null +++ b/tests/agent/metadata_transport.py @@ -0,0 +1,21 @@ +"""Socket-free response data for tests that exercise the real metadata transport.""" +import httpx +import pytest + + +@pytest.fixture +def metadata_transport(monkeypatch): + from agent import model_metadata + + responses, requests = [], [] + real_client = httpx.Client + + def handle(request): + requests.append(request) + return responses.pop(0) + + monkeypatch.setattr(httpx, "Client", lambda **kw: real_client( + **kw, transport=httpx.MockTransport(handle), + )) + monkeypatch.setattr(model_metadata, "detect_local_server_type", lambda *a, **kw: None) + return responses, requests diff --git a/tests/agent/test_custom_provider_ca_probes.py b/tests/agent/test_custom_provider_ca_probes.py index 155200cb86..ab83eeacef 100644 --- a/tests/agent/test_custom_provider_ca_probes.py +++ b/tests/agent/test_custom_provider_ca_probes.py @@ -1,299 +1,79 @@ -"""Custom-provider TLS settings must reach the /models and pricing probes. - -Regression coverage for provider-scoped ``ssl_ca_cert`` / ``ssl_verify`` being -ignored by the discovery/pricing probes. Two probe families share the root -cause and are covered here: - -* HTTPX endpoint metadata / pricing probe - (``agent.model_metadata.fetch_endpoint_model_metadata`` via - ``resolve_verify``). -* ``urllib``-based ``/models`` catalog discovery probe - (``hermes_cli.models.probe_api_models`` via ``_custom_provider_ssl_context``). - -Both previously resolved TLS from process-wide env vars only, so a custom -endpoint whose chain verifies against the provider's configured bundle (but not -``SSL_CERT_FILE``) logged a spurious CERTIFICATE_VERIFY_FAILED on every probe -even though the chat client succeeded. - -No network I/O: real CA-bundle stand-in files via ``tmp_path`` plus a patched -provider list and a patched request seam. -""" - -from __future__ import annotations - -from contextlib import contextmanager +"""Probe-specific policy edges; real TLS handshakes live in test_ssl_transport_contracts.""" import ssl -import urllib.error from unittest.mock import MagicMock, patch -import certifi import pytest from agent.model_metadata_http import resolve_verify -from agent.ssl_verify import resolve_httpx_verify from hermes_cli.models import _custom_provider_ssl_context -_CA_ENV_VARS = ( - "HERMES_CA_BUNDLE", - "REQUESTS_CA_BUNDLE", - "SSL_CERT_FILE", - "CURL_CA_BUNDLE", -) - _BASE = "https://relay.example.invalid/v1" @pytest.fixture def clean_env(monkeypatch): - """Clear the CA env vars so each test starts from a known state.""" - for var in _CA_ENV_VARS: - monkeypatch.delenv(var, raising=False) + for key in ("HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "SSL_CERT_FILE", "SSL_CERT_DIR", "CURL_CA_BUNDLE"): + monkeypatch.delenv(key, raising=False) return monkeypatch -@pytest.fixture -def bundle_file(tmp_path): - path = tmp_path / "provider-ca.pem" - from pathlib import Path - path.write_bytes(Path(certifi.where()).read_bytes()) - return str(path) +@pytest.mark.parametrize("case", ["no-url", "unmatched", "missing-ca", "config-error"]) +@pytest.mark.parametrize("ambient", [False, True]) +def test_probe_policy_edges(clean_env, case, ambient): + if ambient: + clean_env.setenv("SSL_CERT_FILE", "/does/not/exist.pem") + providers = MagicMock(return_value=[{ + "name": "test", "base_url": _BASE if case != "unmatched" else "https://other.invalid", + "ssl_ca_cert": "/missing-provider.pem", + }]) + if case == "config-error": + providers.side_effect = RuntimeError("config unavailable") + url = "" if case == "no-url" else _BASE + with patch("hermes_cli.config.get_compatible_custom_providers", providers): + verify = resolve_verify(url) + context = _custom_provider_ssl_context(url) + assert context is (verify if ambient else None) + if ambient: + assert verify.verify_mode == ssl.CERT_REQUIRED and verify.check_hostname + else: + assert verify is True + if not url: + providers.assert_not_called() -@pytest.fixture -def real_ca(): - """Both probe transports parse this actual bundle before connecting.""" - return certifi.where() +def test_public_endpoint_calls_seam_without_ssl_context_kwarg(clean_env): + """A public endpoint must not pass ssl_context to the call seam. + Regression guard: threading ssl_context unconditionally broke existing + call-seam mocks whose signature is ``(req, timeout=...)``. The probe + must keep the original 2-arg call shape when no per-provider override + applies, so a strict 2-arg mock still works. + """ + import hermes_cli.models as models -def _providers(base_url, **tls): - entry = {"name": "relay", "base_url": base_url} - entry.update(tls) - return [entry] + class _Resp: + def __enter__(self): + return self + def __exit__(self, exc_type, exc, tb): + return False -class TestResolveVerifyProviderScoped: - """Provider configuration resolves before the probe's transport is built.""" + def read(self): + return b'{"data": [{"id": "local-model"}]}' - def test_provider_ca_used_for_matching_base_url(self, clean_env, bundle_file): - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=_providers(_BASE, ssl_ca_cert=bundle_file), - ): - assert resolve_verify(_BASE) is resolve_httpx_verify(ca_bundle=bundle_file) + calls = [] - def test_provider_ca_overrides_env_ssl_cert_file(self, clean_env, tmp_path, bundle_file): - env_bundle = tmp_path / "env-ca.pem" - env_bundle.write_text("stub") - clean_env.setenv("SSL_CERT_FILE", str(env_bundle)) - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=_providers(_BASE, ssl_ca_cert=bundle_file), - ): - assert resolve_verify(_BASE) is resolve_httpx_verify(ca_bundle=bundle_file) + def _strict_two_arg(req, timeout=5.0): + calls.append(req.full_url) + return _Resp() - def test_provider_ssl_verify_false_disables(self, clean_env): - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=_providers(_BASE, ssl_verify=False), - ): - assert resolve_verify(_BASE) is False + with patch( + "hermes_cli.config.get_compatible_custom_providers", + return_value=[], + ), patch.object( + models, "_urlopen_model_catalog_request", side_effect=_strict_two_arg + ): + probe = models.probe_api_models("key", "http://localhost:8000", timeout=1) - def test_no_base_url_does_not_consult_config(self, clean_env, bundle_file): - """Existing callers pass no base_url — no config read, and env never steers trust.""" - clean_env.setenv("HERMES_CA_BUNDLE", bundle_file) - probe = MagicMock(return_value=[]) - with patch("hermes_cli.config.get_compatible_custom_providers", probe): - assert resolve_verify() is True - probe.assert_not_called() - - def test_unmatched_base_url_env_ignored_returns_true(self, clean_env, bundle_file): - """An unmatched base_url and an ambient CA env var both leave trust at the OS store.""" - clean_env.setenv("REQUESTS_CA_BUNDLE", bundle_file) - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=_providers("https://other.example.invalid/v1", ssl_ca_cert="/nope.pem"), - ): - assert resolve_verify(_BASE) is True - - def test_unmatched_base_url_no_env_returns_true(self, clean_env): - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=[], - ): - assert resolve_verify(_BASE) is True - - def test_provider_ca_missing_file_keeps_platform_trust(self, clean_env): - """A configured bundle that does not exist warns and verifies against the OS store — - an ambient ``SSL_CERT_FILE`` does not become the fallback authority.""" - clean_env.setenv("SSL_CERT_FILE", "/does/not/matter.pem") - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=_providers(_BASE, ssl_ca_cert="/does/not/exist.pem"), - ): - context = resolve_verify(_BASE) - assert type(context).__module__.startswith("truststore") - assert context.verify_mode == ssl.CERT_REQUIRED - - def test_config_lookup_failure_keeps_platform_trust(self, clean_env): - """A config crash must not silently swap in an ambient env var as trust authority.""" - clean_env.setenv("SSL_CERT_FILE", "/does/not/matter.pem") - with patch( - "hermes_cli.config.get_compatible_custom_providers", - side_effect=RuntimeError("config boom"), - ): - context = resolve_verify(_BASE) - assert type(context).__module__.startswith("truststore") - assert context.verify_mode == ssl.CERT_REQUIRED - - -class TestCustomProviderSSLContext: - """``_custom_provider_ssl_context`` — the urllib /models discovery path.""" - - def test_returns_verifying_context_with_provider_ca(self, real_ca): - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=_providers(_BASE, ssl_ca_cert=real_ca), - ): - ctx = _custom_provider_ssl_context(_BASE) - assert ctx is resolve_httpx_verify(ca_bundle=real_ca) - assert ctx.verify_mode == ssl.CERT_REQUIRED - - def test_ssl_verify_false_returns_unverified_context(self): - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=_providers(_BASE, ssl_verify=False), - ): - ctx = _custom_provider_ssl_context(_BASE) - assert isinstance(ctx, ssl.SSLContext) - assert ctx.check_hostname is False - assert ctx.verify_mode == ssl.CERT_NONE - - def test_no_base_url_returns_none(self): - assert _custom_provider_ssl_context("") is None - - def test_unmatched_returns_none(self): - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=[], - ): - assert _custom_provider_ssl_context(_BASE) is None - - def test_missing_ca_file_returns_none(self): - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=_providers(_BASE, ssl_ca_cert="/does/not/exist.pem"), - ): - assert _custom_provider_ssl_context(_BASE) is None - - def test_config_lookup_failure_returns_none(self): - with patch( - "hermes_cli.config.get_compatible_custom_providers", - side_effect=RuntimeError("config boom"), - ): - assert _custom_provider_ssl_context(_BASE) is None - - -class TestMetadataProbeThreadsProviderCA: - @pytest.mark.parametrize("pinned", [False, True]) - def test_provider_policy_reaches_the_transport(self, clean_env, real_ca, pinned): - import httpx - from agent import model_metadata as mm - from agent import model_metadata_http - from agent.ssl_verify import resolve_httpx_verify - - @contextmanager - def response(*args, **kwargs): - yield httpx.Response(200, json={"data": []}, request=httpx.Request("GET", args[0])) - - mm._endpoint_model_metadata_cache.clear() - mm._endpoint_model_metadata_cache_time.clear() - providers = _providers(_BASE, ssl_ca_cert=real_ca) if pinned else [] - with patch("hermes_cli.config.get_compatible_custom_providers", return_value=providers), \ - patch.object(model_metadata_http, "stream", side_effect=response) as stream: - assert mm.fetch_endpoint_model_metadata(_BASE, force_refresh=True) == {} - expected = resolve_httpx_verify(ca_bundle=real_ca) if pinned else True - assert stream.call_args.kwargs["verify"] is expected - - -class TestCatalogProbeThreadsSSLContext: - """End-to-end: the urllib catalog probe carries the provider SSL context.""" - - @pytest.fixture(autouse=True) - def _clear_probe_neg_cache(self): - import hermes_cli.models as models - - models._probe_neg_cache.clear() - yield - models._probe_neg_cache.clear() - - def test_probe_api_models_passes_ssl_context(self, clean_env, real_ca): - import hermes_cli.models as models - - captured = {} - - def fake_open(req, *, timeout, ssl_context=None): - captured["ssl_context"] = ssl_context - raise urllib.error.URLError("stop after capture") - - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=_providers(_BASE, ssl_ca_cert=real_ca), - ), patch.object(models, "open_credentialed_url", side_effect=fake_open): - models.probe_api_models(None, _BASE, timeout=1) - - assert captured["ssl_context"] is resolve_httpx_verify(ca_bundle=real_ca) - assert captured["ssl_context"].verify_mode == ssl.CERT_REQUIRED - - def test_probe_api_models_public_endpoint_uses_default_policy(self, clean_env): - import hermes_cli.models as models - - captured = {} - - def fake_open(req, *, timeout, ssl_context=None): - captured["ssl_context"] = ssl_context - raise urllib.error.URLError("stop after capture") - - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=[], - ), patch.object(models, "open_credentialed_url", side_effect=fake_open): - models.probe_api_models(None, _BASE, timeout=1) - - assert captured["ssl_context"] is None - - def test_public_endpoint_calls_seam_without_ssl_context_kwarg(self, clean_env): - """A public endpoint must not pass ssl_context to the call seam. - - Regression guard: threading ssl_context unconditionally broke existing - call-seam mocks whose signature is ``(req, timeout=...)``. The probe - must keep the original 2-arg call shape when no per-provider override - applies, so a strict 2-arg mock still works. - """ - import hermes_cli.models as models - - class _Resp: - def __enter__(self): - return self - - def __exit__(self, exc_type, exc, tb): - return False - - def read(self): - return b'{"data": [{"id": "local-model"}]}' - - calls = [] - - def _strict_two_arg(req, timeout=5.0): - calls.append(req.full_url) - return _Resp() - - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=[], - ), patch.object( - models, "_urlopen_model_catalog_request", side_effect=_strict_two_arg - ): - probe = models.probe_api_models("key", "http://localhost:8000", timeout=1) - - assert probe["models"] == ["local-model"] - assert calls == ["http://localhost:8000/models"] + assert probe["models"] == ["local-model"] + assert calls == ["http://localhost:8000/models"] diff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.py index 0bb0e19773..927e748bb1 100644 --- a/tests/agent/test_model_metadata.py +++ b/tests/agent/test_model_metadata.py @@ -11,7 +11,7 @@ Coverage levels: """ import time -from contextlib import contextmanager +from tests.agent.metadata_transport import metadata_transport # noqa: F401 import pytest import hermes_yaml as yaml @@ -752,117 +752,26 @@ class TestCodexOAuthContextLength: # ========================================================================= class TestFetchEndpointModelMetadata: - @pytest.fixture(autouse=True) - def streamed_responses(self, monkeypatch): - from agent import model_metadata_http - - @contextmanager - def stream(*args, **kwargs): - response = model_metadata_http.get(*args, **kwargs) - try: - yield response - finally: - response.close() - - monkeypatch.setattr(model_metadata_http, "stream", stream) - def setup_method(self): import agent.model_metadata as mm mm._endpoint_model_metadata_cache.clear() mm._endpoint_model_metadata_cache_time.clear() - @pytest.mark.parametrize("status_code", [401, 403]) - def test_auth_failure_stops_after_first_candidate(self, status_code): + def test_remote_probe_is_memoized_on_disk_across_processes(self, tmp_path, monkeypatch, metadata_transport): + import httpx import agent.model_metadata as mm - response = MagicMock() - response.status_code = status_code - response.raise_for_status.side_effect = RuntimeError(str(status_code)) - - with patch("agent.model_metadata_http.get", return_value=response) as mock_get: - result = mm.fetch_endpoint_model_metadata("https://custom.example/v1") - - assert result == {} - mock_get.assert_called_once() - response.read.assert_not_called() - response.raise_for_status.assert_not_called() - response.json.assert_not_called() - response.close.assert_called_once() - - def test_auth_failure_empty_result_is_cached(self): - import agent.model_metadata as mm - - response = MagicMock() - response.status_code = 401 - response.raise_for_status.side_effect = RuntimeError("401") - - with patch("agent.model_metadata_http.get", return_value=response) as mock_get: - first = mm.fetch_endpoint_model_metadata("https://custom.example/v1") - second = mm.fetch_endpoint_model_metadata("https://custom.example/v1") - - assert first == second == {} - mock_get.assert_called_once() - response.close.assert_called_once() - - def test_not_found_still_tries_alternate_candidate(self): - import agent.model_metadata as mm - - not_found = MagicMock() - not_found.status_code = 404 - not_found.raise_for_status.side_effect = RuntimeError("404") - success = MagicMock() - success.status_code = 200 - success.json.return_value = { - "data": [{"id": "test/model", "context_length": 32768}] - } - - with patch( - "agent.model_metadata_http.get", - side_effect=[not_found, success], - ) as mock_get: - result = mm.fetch_endpoint_model_metadata("https://custom.example/v1") - - assert result["test/model"]["context_length"] == 32768 - assert mock_get.call_count == 2 - assert [call.args[0] for call in mock_get.call_args_list] == [ - "https://custom.example/v1/models", - "https://custom.example/models", - ] - not_found.read.assert_not_called() - success.read.assert_called_once() - not_found.json.assert_not_called() - not_found.close.assert_called_once() - success.close.assert_called_once() - - def test_remote_probe_is_memoized_on_disk_across_processes(self, tmp_path, monkeypatch): - """A fresh process (cleared in-memory cache) must answer from the disk - memo within the TTL instead of re-probing the endpoint — the cost every - one-shot Bot Mode DM hop paid on startup. Expired memos re-probe.""" - import agent.model_metadata as mm - - monkeypatch.setattr( - mm, "_get_endpoint_metadata_cache_path", lambda: tmp_path / "endpoint_model_metadata.json" - ) - success = MagicMock() - success.status_code = 200 - success.json.return_value = {"data": [{"id": "test/model", "context_length": 32768}]} - - with patch("agent.model_metadata_http.get", return_value=success) as mock_get: + monkeypatch.setattr(mm, "_get_endpoint_metadata_cache_path", lambda: tmp_path / "endpoint.json") + responses, requests = metadata_transport + responses.extend(httpx.Response(200, json={"data": [{"id": "test/model", "context_length": 32768}]}) for _ in range(2)) + for _ in range(2): assert mm.fetch_endpoint_model_metadata("https://custom.example/v1")["test/model"]["context_length"] == 32768 - # "New process": drop the in-memory cache only. mm._endpoint_model_metadata_cache.clear() mm._endpoint_model_metadata_cache_time.clear() - assert mm.fetch_endpoint_model_metadata("https://custom.example/v1")["test/model"]["context_length"] == 32768 - mock_get.assert_called_once() - - # Past the TTL the memo is stale and the endpoint is probed again. - mm._endpoint_model_metadata_cache.clear() - mm._endpoint_model_metadata_cache_time.clear() - with patch("agent.model_metadata.time.time", return_value=time.time() + mm._ENDPOINT_MODEL_CACHE_TTL + 1), patch( - "agent.model_metadata_http.get", return_value=success - ) as mock_get: + assert len(requests) == 1 + with patch("agent.model_metadata.time.time", return_value=time.time() + mm._ENDPOINT_MODEL_CACHE_TTL + 1): mm.fetch_endpoint_model_metadata("https://custom.example/v1") - mock_get.assert_called_once() + assert len(requests) == 2 # ========================================================================= diff --git a/tests/agent/test_model_metadata_http.py b/tests/agent/test_model_metadata_http.py index e81b08b9ca..811f369497 100644 --- a/tests/agent/test_model_metadata_http.py +++ b/tests/agent/test_model_metadata_http.py @@ -67,7 +67,7 @@ def test_redirect_credentials_and_proxy_routing_are_preserved(servers, monkeypat assert seen[-1][0] == "http://probe.invalid/models" -@pytest.mark.parametrize("status", [401, 403]) +@pytest.mark.parametrize("status", [401, 403, 404]) def test_metadata_auth_failure_closes_without_reading_body(servers, monkeypatch, status): requests = [] @@ -76,9 +76,16 @@ def test_metadata_auth_failure_closes_without_reading_body(servers, monkeypatch, def do_GET(self): requests.append(self.path) - self.send_response(status) - self.send_header("Content-Length", "1000000") - self.end_headers() + if status == 404 and self.path == "/models": + body = b'{"data":[{"id":"test/model","context_length":32768}]}' + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + else: + self.send_response(status) + self.send_header("Content-Length", "1000000") + self.end_headers() # Intentionally send no body. The client must close on the headers, # not wait for a read timeout or try the alternate /v1 URL. @@ -98,7 +105,15 @@ def test_metadata_auth_failure_closes_without_reading_body(servers, monkeypatch, return original_client(**{**kwargs, "timeout": 2.0}) monkeypatch.setattr(httpx, "Client", recorded_client) - assert model_metadata.fetch_endpoint_model_metadata(url, force_refresh=True) == {} - assert requests == ["/models"] - assert len(responses) == 1 and responses[0].is_closed - assert not responses[0].is_stream_consumed, "auth rejection read the absent body" + url += "/v1" + result = model_metadata.fetch_endpoint_model_metadata(url, force_refresh=True) + if status == 404: + assert result["test/model"]["context_length"] == 32768 + assert requests == ["/v1/models", "/models"] + assert responses[1].is_stream_consumed + else: + assert result == {} + assert model_metadata.fetch_endpoint_model_metadata(url) == {} + assert requests == ["/v1/models"] + assert all(response.is_closed for response in responses) + assert not responses[0].is_stream_consumed, "rejection read the absent body" diff --git a/tests/agent/test_model_metadata_ssl.py b/tests/agent/test_model_metadata_ssl.py deleted file mode 100644 index 5639a56964..0000000000 --- a/tests/agent/test_model_metadata_ssl.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Metadata discovery uses chat's resolved TLS policy without ambient CA files.""" -from __future__ import annotations - -import ssl - -import httpx -import pytest - -from agent.model_metadata_http import resolve_verify - - -@pytest.mark.parametrize("variable", ["HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "SSL_CERT_FILE", "SSL_CERT_DIR"]) -def test_ambient_ca_paths_do_not_break_metadata_clients(monkeypatch, tmp_path, variable): - monkeypatch.setenv(variable, str(tmp_path / "missing-ca")) - verify = resolve_verify() - with httpx.Client(verify=verify) as client: - context = client._transport._pool._ssl_context - assert context.verify_mode == ssl.CERT_REQUIRED - assert context.check_hostname diff --git a/tests/agent/test_probe_cache_followups.py b/tests/agent/test_probe_cache_followups.py index 57e9a938e4..485fe11dc0 100644 --- a/tests/agent/test_probe_cache_followups.py +++ b/tests/agent/test_probe_cache_followups.py @@ -7,7 +7,7 @@ Covers: from __future__ import annotations -from contextlib import contextmanager +from tests.agent.metadata_transport import metadata_transport # noqa: F401 from unittest.mock import MagicMock, patch import pytest @@ -165,21 +165,6 @@ class TestLocalhostIPv4SiblingSites: """#37595 widened: every probe helper rewrites localhost→127.0.0.1, not just detect_local_server_type.""" - @pytest.fixture(autouse=True) - def streamed_responses(self, monkeypatch): - from agent import model_metadata_http - - @contextmanager - def stream(*args, **kwargs): - response = model_metadata_http.get(*args, **kwargs) - try: - yield response - finally: - response.close() - - monkeypatch.setattr(model_metadata_http, "stream", stream) - - def test_rewrite_is_host_only_not_substring(self): """A URL that merely EMBEDS 'http://localhost' in its path/query must not be corrupted — only the URL's own host is rewritten.""" @@ -201,61 +186,25 @@ class TestLocalhostIPv4SiblingSites: assert client.post.call_args[0][0].startswith("http://127.0.0.1:11434") - def test_fetch_endpoint_model_metadata_generic_probe_uses_ipv4(self): - """The generic (non-LM-Studio) /models fetch loop must also rewrite - localhost->127.0.0.1 before probing, like the LM Studio branch above.""" - from agent import model_metadata - from agent.model_metadata import fetch_endpoint_model_metadata - - model_metadata._endpoint_model_metadata_cache.clear() - model_metadata._endpoint_model_metadata_cache_time.clear() - - resp = MagicMock() - resp.status_code = 200 - resp.raise_for_status = MagicMock() - resp.json.return_value = {"data": []} - - with patch("agent.model_metadata.detect_local_server_type", return_value=None), \ - patch("agent.model_metadata_http.get", return_value=resp) as mock_get: - fetch_endpoint_model_metadata("http://localhost:8000/v1") - - assert mock_get.call_args[0][0].startswith("http://127.0.0.1:8000") - - def test_fetch_endpoint_model_metadata_llamacpp_props_followup_uses_ipv4(self): - """The llama.cpp /props context-length follow-up must also rewrite - localhost->127.0.0.1 before probing, not just the initial /models call.""" - from agent import model_metadata - from agent.model_metadata import fetch_endpoint_model_metadata - - model_metadata._endpoint_model_metadata_cache.clear() - model_metadata._endpoint_model_metadata_cache_time.clear() - - models_resp = MagicMock() - models_resp.status_code = 200 - models_resp.raise_for_status = MagicMock() - models_resp.json.return_value = { - "data": [{"id": "llama-3-8b", "owned_by": "llamacpp"}], - } - - props_resp = MagicMock() - props_resp.is_error = False - props_resp.json.return_value = { - "default_generation_settings": {"n_ctx": 32768}, - "model_alias": "llama-3-8b", - } - - with patch("agent.model_metadata.detect_local_server_type", return_value=None), \ - patch( - "agent.model_metadata_http.get", - side_effect=[models_resp, props_resp], - ) as mock_get: - result = fetch_endpoint_model_metadata("http://localhost:8000/v1") - - assert mock_get.call_count == 2 - props_call_url = mock_get.call_args_list[1][0][0] - assert props_call_url.startswith("http://127.0.0.1:8000") - assert result["llama-3-8b"]["context_length"] == 32768 + @pytest.mark.parametrize("llamacpp", [False, True]) + def test_endpoint_and_props_followup_use_ipv4(self, metadata_transport, llamacpp): + import httpx + from agent import model_metadata as mm + mm._endpoint_model_metadata_cache.clear() + mm._endpoint_model_metadata_cache_time.clear() + responses, requests = metadata_transport + models = [{"id": "llama-3-8b", "owned_by": "llamacpp"}] if llamacpp else [] + responses.extend([ + httpx.Response(200, json={"data": models}), + httpx.Response(200, json={"default_generation_settings": {"n_ctx": 32768}, "model_alias": "llama-3-8b"}), + ]) + result = mm.fetch_endpoint_model_metadata("http://localhost:8000/v1", force_refresh=True) + assert len(requests) == (2 if llamacpp else 1) + assert all(request.url.host == "127.0.0.1" for request in requests) + if llamacpp: + assert requests[1].url.path == "/v1/props" + assert result["llama-3-8b"]["context_length"] == 32768 class TestContextCacheKeyNormalization: diff --git a/tests/agent/test_skill_utils.py b/tests/agent/test_skill_utils.py index 82d9350cdd..e048563bc4 100644 --- a/tests/agent/test_skill_utils.py +++ b/tests/agent/test_skill_utils.py @@ -246,21 +246,20 @@ def test_skill_support_path_uses_explicit_discovery_root_not_cwd(tmp_path, monke class TestSkillMatchesPlatform: + @pytest.mark.platforms("any") def test_no_platforms_field_matches_everywhere(self): # Backward-compat default — skills without a platforms tag load # on any OS. - with patch("agent.skill_utils.sys.platform", "linux"): - assert skill_matches_platform({}) is True - assert skill_matches_platform({"name": "foo"}) is True + assert skill_matches_platform({}) is True + assert skill_matches_platform({"name": "foo"}) is True + @pytest.mark.platforms("any") def test_linux_skill_matches_only_linux(self): fm = {"platforms": ["linux"]} - with patch("agent.skill_utils.sys.platform", "linux"): - assert skill_matches_platform(fm) is True - assert skill_matches_platform_list(fm["platforms"]) is True - with patch("agent.skill_utils.sys.platform", "darwin"): - assert skill_matches_platform(fm) is False - assert skill_matches_platform_list(fm["platforms"]) is False + import sys + + assert skill_matches_platform(fm) is sys.platform.startswith("linux") + assert skill_matches_platform_list(fm["platforms"]) is sys.platform.startswith("linux") def test_relative_path_unchanged(self, tmp_path, monkeypatch): diff --git a/tests/agent/test_ssl_transport_contracts.py b/tests/agent/test_ssl_transport_contracts.py index 3a36b1fac9..d8bac8372a 100644 --- a/tests/agent/test_ssl_transport_contracts.py +++ b/tests/agent/test_ssl_transport_contracts.py @@ -74,8 +74,9 @@ def test_provider_ca_reaches_the_real_probe_transport(local_tls, monkeypatch, pr url, bundle = local_tls monkeypatch.setattr(model_metadata, "detect_local_server_type", lambda *args, **kwargs: None) - settings = {"ssl_ca_cert": certifi.where()} - monkeypatch.setattr("hermes_cli.config.get_custom_provider_tls_settings", lambda base_url: dict(settings)) + settings = {"name": "loopback", "base_url": url, "ssl_ca_cert": certifi.where()} + monkeypatch.setattr("hermes_cli.config.get_compatible_custom_providers", lambda config=None: [dict(settings)]) + monkeypatch.setenv("SSL_CERT_FILE", "/missing-ambient.pem") def discover(): if probe == "metadata": @@ -86,38 +87,41 @@ def test_provider_ca_reaches_the_real_probe_transport(local_tls, monkeypatch, pr settings["ssl_ca_cert"] = str(bundle) assert discover() == ["test-model"] - # Model probing must use the same resolver as chat, not a path whose TLS - # semantics change after truststore's process-wide injection. - seen = [] - original = ssl_verify.resolve_httpx_verify - - def record(**kwargs): - context = original(**kwargs) - seen.append(context) - return context - - monkeypatch.setattr(ssl_verify, "resolve_httpx_verify", record) + settings["ssl_ca_cert"] = certifi.where() + settings["ssl_verify"] = False assert discover() == ["test-model"] - assert seen and seen[-1] is original(ca_bundle=str(bundle)) -@pytest.mark.parametrize("variable", ["SSL_CERT_FILE", "SSL_CERT_DIR"]) +@pytest.mark.parametrize("variable", ["HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "SSL_CERT_FILE", "SSL_CERT_DIR"]) def test_ambient_ca_cannot_break_the_shared_client(variable, tmp_path, monkeypatch): + from run_agent import AIAgent + monkeypatch.setenv(variable, str(tmp_path / "missing-ca")) + for _ in range(2): + assert ssl_verify.install_truststore() is True verify = ssl_verify.resolve_httpx_verify() with httpx.Client(verify=verify) as client: - assert not client.is_closed - client = process_bootstrap.build_keepalive_http_client("https://example.invalid", verify=verify) + context = client._transport._pool._ssl_context + assert context.verify_mode == ssl.CERT_REQUIRED and context.check_hostname + assert type(context).__module__.startswith("truststore") + client = AIAgent._build_keepalive_http_client("https://example.invalid", verify=verify) assert client is not None client.close() -def test_pinned_clients_share_transport_not_close_state(local_tls): +@pytest.mark.parametrize("insecure", [False, True]) +def test_pinned_clients_share_transport_not_close_state(local_tls, insecure): + from run_agent import AIAgent url, bundle = local_tls - first = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle)) - second = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle)) + first = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle), ssl_verify=not insecure) + second = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle), ssl_verify=not insecure) + if not insecure: + assert isinstance(first, _original_SSLContext) + assert not type(first).__module__.startswith("truststore") + assert first.verify_mode == ssl.CERT_REQUIRED and first.check_hostname + assert len(first.get_ca_certs()) == 1 assert first is second - a = process_bootstrap.build_keepalive_http_client(url, verify=first) + a = AIAgent._build_keepalive_http_client(url, verify=first) b = process_bootstrap.build_keepalive_http_client(url, verify=second) assert a is not None and b is not None try: diff --git a/tests/agent/test_ssl_verify.py b/tests/agent/test_ssl_verify.py index a6b1ce4e6c..361b322223 100644 --- a/tests/agent/test_ssl_verify.py +++ b/tests/agent/test_ssl_verify.py @@ -4,90 +4,9 @@ These are behavior contracts, not snapshots — they assert WHERE trust comes from and that explicit per-provider settings still beat it. """ -import ssl - import pytest -from agent import ssl_verify -from agent.ssl_verify import ( - install_truststore, - resolve_httpx_verify, -) - - -@pytest.fixture(autouse=True) -def _reset_install_cache(): - ssl_verify._installed = None - yield - ssl_verify._installed = None - - -def test_install_truststore_puts_the_platform_verifier_in_charge(): - assert install_truststore() is True - # Every default context built anywhere in the process is now - # platform-verified — including stdlib urllib call sites. - assert ssl.SSLContext.__module__.startswith("truststore") - - -def test_install_truststore_is_idempotent(): - assert install_truststore() is True - assert install_truststore() is True - - -def test_default_verify_defers_to_the_platform_store(): - # True means "verify normally", which after the install means the OS - # store. No CA bundle path is threaded through. - assert resolve_httpx_verify() is True - - -def test_env_ca_bundle_vars_no_longer_steer_trust(monkeypatch, tmp_path): - """The old SSL_CERT_FILE/REQUESTS_CA_BUNDLE ladders are gone. - - Trust is the machine's, and a stale env var pointing at a bundle (or at - nothing) must not silently redirect or break verification — the exact - failure the removed gateway/auth/urllib ladders each hand-rolled a - workaround for. - """ - import certifi - - import httpx - - for path in (certifi.where(), str(tmp_path / "does-not-exist.pem")): - for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"): - monkeypatch.setenv(var, path) - verify = resolve_httpx_verify() - with httpx.Client(verify=verify) as client: - context = client._transport._pool._ssl_context - assert type(context).__module__.startswith("truststore") - assert context.verify_mode == ssl.CERT_REQUIRED - assert context.check_hostname - - -def test_explicit_ca_bundle_replaces_the_platform_store(): - """A pinned ssl_ca_cert must verify against THAT bundle only. - - Tripwire: truststore's injected SSLContext ignores load_verify_locations - and verifies against the OS store regardless, so this context has to come - from the original class. If a truststore bump moves - ``_ssl_constants._original_SSLContext``, this fails here instead of - silently degrading a pinned corporate bundle into "trust the machine". - """ - import certifi - from truststore._ssl_constants import _original_SSLContext - - ctx = resolve_httpx_verify(ca_bundle=certifi.where()) - - # NOT isinstance(ctx, ssl.SSLContext): that name is the patched class - # now, and this context deliberately is not one. - assert isinstance(ctx, _original_SSLContext) - assert not type(ctx).__module__.startswith("truststore") - # PROTOCOL_TLS_CLIENT's own defaults — asserted, not assigned: setting - # them on this context recurses forever through the patched module - # global (super(SSLContext, SSLContext) resolves to truststore's class). - assert ctx.verify_mode == ssl.CERT_REQUIRED - assert ctx.check_hostname is True - # Introspectable precisely because it is NOT truststore-backed. - assert len(ctx.get_ca_certs()) > 0 +from agent.ssl_verify import resolve_httpx_verify def test_missing_explicit_bundle_falls_back_to_the_platform_store(tmp_path, caplog): @@ -108,20 +27,27 @@ def test_insecure_beats_an_explicit_bundle(): assert resolve_httpx_verify(ca_bundle=certifi.where(), ssl_verify=False) is False -def test_truststore_failure_degrades_to_openssl_defaults(monkeypatch, caplog): - """No truststore (stripped env, odd platform) must not break startup.""" - import builtins +def test_truststore_failure_degrades_to_openssl_defaults(): + import subprocess + import sys - real_import = builtins.__import__ - - def _boom(name, *args, **kwargs): - if name == "truststore": - raise ImportError("no truststore here") - return real_import(name, *args, **kwargs) - - monkeypatch.setattr(builtins, "__import__", _boom) - assert install_truststore() is False - assert "truststore unavailable" in caplog.text - # Still resolves to a usable verify value rather than raising. - monkeypatch.undo() - assert resolve_httpx_verify() is True + child = subprocess.run([sys.executable, "-c", """ +import builtins, ssl +original = ssl.SSLContext +real_import = builtins.__import__ +def no_truststore(name, *args, **kwargs): + if name == 'truststore': + raise ImportError('unavailable fixture') + return real_import(name, *args, **kwargs) +builtins.__import__ = no_truststore +from agent.ssl_verify import install_truststore, resolve_httpx_verify +assert install_truststore() is False +assert install_truststore() is False +assert ssl.SSLContext is original +import httpx +with httpx.Client(verify=resolve_httpx_verify()) as client: + ctx = client._transport._pool._ssl_context + assert ctx.verify_mode == ssl.CERT_REQUIRED and ctx.check_hostname +"""], capture_output=True, text=True, timeout=30) + assert child.returncode == 0, child.stderr + assert "truststore unavailable" in child.stderr diff --git a/tests/ci/test_commit_build_staging.py b/tests/ci/test_commit_build_staging.py index 540b40d71f..33a81e5a01 100644 --- a/tests/ci/test_commit_build_staging.py +++ b/tests/ci/test_commit_build_staging.py @@ -8,6 +8,7 @@ import shlex import subprocess import sys from urllib.request import urlopen +from urllib.parse import quote, unquote import pytest @@ -159,7 +160,7 @@ def test_commit_staging_and_summary_bind_every_produced_file_without_channels(tm missing = shell_step(tmp_path, r2_server, 'termux-deb', termux_name, env) assert missing.returncode != 0 assert r2_server.store == before - deb = tmp_path / 'termux-build/deb/hermes-agent_0.33.0~commit.aaaaaaaaaaaa_aarch64.deb' + deb = tmp_path / 'termux-build/deb/hermes agent_0.33.0~commit.aaaaaaaaaaaa_aarch64.deb' deb.parent.mkdir(parents=True) deb.write_bytes(b'transport fixture, not a native Debian package') staged = shell_step(tmp_path, r2_server, 'termux-deb', termux_name, env) @@ -180,16 +181,30 @@ def test_commit_staging_and_summary_bind_every_produced_file_without_channels(tm text = summary.read_text(encoding='utf-8') links = re.findall(r'\]\((http[^)]+)\)', text) # Blockmaps are receipt inputs; every other staged product has a download row. - expected = {f'{base}/{key}' for key in artifact_keys if not key.endswith('.blockmap')} + expected = {f'{base}/{quote(key, safe="/")}' for key in artifact_keys if not key.endswith('.blockmap')} assert set(links) == expected assert len(links) == len(expected) for url in links: with urlopen(url, timeout=5) as response: - key = url.removeprefix(base + '/') + key = unquote(url.removeprefix(base + '/')) assert response.read() == r2_server.store[key][0] + page_key = f'releases/commit/{sha}/index.html' + page = r2_server.store[page_key][0].decode() + assert all(f'href="{url}"' in page for url in expected) + assert 'Store' not in page and 'Linux x64' in page and 'Linux ARM64' in page assert all(key.startswith(f'releases/commit/{sha}/') for key in r2_server.store) assert not any(method == 'DELETE' for method, _, _ in r2_server.requests) + receipt_key = f'releases/commit/{sha}/handoff-win32-x64.json' + original = r2_server.store[receipt_key] + r2_server.store[receipt_key] = (b'not-json', '"invalid"') + failed = shell_step(tmp_path, r2_server, 'commit-builds-summary', + 'Render the full expected-binary matrix', summary_env) + assert failed.returncode != 0 + assert summary.read_text(encoding='utf-8') == text + assert r2_server.store[page_key][0].decode() == page + r2_server.store[receipt_key] = original + # The actual summary command remains useful after an admitted matrix failure. r2_server.store.pop(f'releases/commit/{sha}/handoff-darwin-x64.json') summary.unlink() diff --git a/tests/ci/test_desktop_release_tag_admission.py b/tests/ci/test_desktop_release_tag_admission.py index cb6e7c319b..00707b3dae 100644 --- a/tests/ci/test_desktop_release_tag_admission.py +++ b/tests/ci/test_desktop_release_tag_admission.py @@ -59,14 +59,6 @@ def test_validate_exports_the_admitted_sha_as_a_job_output(): assert "steps.admission.outputs.sha" in outputs["sha"] -def test_admission_script_requires_ancestry_on_origin_main(): - script = _admission_script() - assert "merge-base --is-ancestor" in script - assert "origin/main" in script - assert "::error::" in script, "the refusal must be a loud, greppable error" - assert "GITHUB_OUTPUT" in script, "the resolved SHA must be exported" - - def test_every_signing_job_checks_out_the_admitted_sha_not_the_tag(): wf = _workflow() privileged = { diff --git a/tests/ci/test_list_os_marked_tests.py b/tests/ci/test_list_os_marked_tests.py index 3e46c8e904..0827069408 100644 --- a/tests/ci/test_list_os_marked_tests.py +++ b/tests/ci/test_list_os_marked_tests.py @@ -35,148 +35,30 @@ def _write(root: Path, relpath: str, body: str) -> Path: return path -@pytest.mark.parametrize("platform", ["linux", "macos", "windows"]) -def test_finds_decorator_and_pytestmark_forms(tmp_path, platform): - """Both the decorator form and module-level ``pytestmark`` are detected.""" - _write( - tmp_path, - "test_decorated.py", - f'import pytest\n\n\n@pytest.mark.platforms("{platform}")\ndef test_x():\n pass\n', - ) - _write( - tmp_path, - "nested/test_module_level.py", - f'import pytest\n\npytestmark = pytest.mark.platforms("{platform}")\n\n\ndef test_y():\n pass\n', - ) - # A file with no gate at all must not be selected. - _write(tmp_path, "test_plain.py", "def test_z():\n pass\n") - # A platforms() file gating a DIFFERENT platform must not be selected. - other = "windows" if platform != "windows" else "linux" - _write( - tmp_path, - "test_other_platform.py", - f'import pytest\n\n\n@pytest.mark.platforms("{other}")\ndef test_w():\n pass\n', - ) - # A bare identifier that merely LOOKS like the platform name must not - # match — the spec has to appear inside the quoted string literal. - _write( - tmp_path, - "test_bare_identifier.py", - f"import pytest\n\n\n@pytest.mark.parametrize(\"kind\", [\"{platform}\"])\ndef test_v():\n assert kind\n", - ) - +@pytest.mark.parametrize("platform,expected", [ + ("linux", {"linux", "posix", "any", "not_macos", "not_linux", "unknown", "dynamic", "empty"}), + ("macos", {"module", "single", "posix", "any", "not_macos", "not_linux", "unknown", "dynamic", "empty"}), + ("windows", {"arch", "multiline", "any", "not_macos", "not_linux", "unknown", "dynamic", "empty"}), +]) +def test_selector_corpus(tmp_path, platform, expected): + # Selection deliberately overselects negated/unknown inputs; the runtime + # marker, not this file selector, decides whether each test runs. + calls = { + "linux": '"linux"', "single": "'macos'", "posix": '"posix"', + "any": '"any"', "not_macos": '"not macos"', "not_linux": '"not linux"', + "arch": '"windows", arch="arm64"', + "multiline": '\n"windows",\narch="arm64",\n', + "unknown": '"amiga"', "dynamic": 'PLATFORM', "empty": '', + } + for name, arguments in calls.items(): + _write(tmp_path, f"test_{name}.py", + f"@pytest.mark.platforms({arguments})\ndef test_x(): pass\n") + _write(tmp_path, "nested/test_module.py", 'pytestmark = pytest.mark.platforms("macos")\n') + _write(tmp_path, "test_plain.py", "def test_x(): pass\n") + _write(tmp_path, "test_identifier.py", '@pytest.mark.parametrize("kind", ["linux", "macos", "windows"])\ndef test_x(): pass\n') result = _run(platform, str(tmp_path)) - assert result.returncode == 0, result.stderr - listed = result.stdout.split() - assert any(p.endswith("test_decorated.py") for p in listed) - assert any(p.endswith("test_module_level.py") for p in listed) - assert not any(p.endswith("test_plain.py") for p in listed) - assert not any(p.endswith("test_other_platform.py") for p in listed) - assert not any(p.endswith("test_bare_identifier.py") for p in listed) - - -def test_negated_spec_lists_for_that_lane(tmp_path): - """``platforms("not macos")`` lists the file for the macOS lane import. - - The script only decides which files are IMPORTED; the per-test host - skips remain authoritative. A negated-spec file may still contain other - tests, so it must be imported on the macOS lane — under-selecting is - the failure mode this tool exists to prevent. - """ - _write( - tmp_path, - "test_negated.py", - 'import pytest\n\n\n@pytest.mark.platforms("not macos")\ndef test_x():\n pass\n', - ) - - result = _run("macos", str(tmp_path)) - - assert result.returncode == 0, result.stderr - listed = result.stdout.split() - assert any(p.endswith("test_negated.py") for p in listed) - - -def test_posix_spec_lists_for_both_posix_lanes_only(tmp_path): - """``platforms("posix")`` runs on linux+macos hosts, not windows. - - The file must be listed for the macos lane (its tests RUN there); - under-selecting it would silently drop that coverage. - """ - _write( - tmp_path, - "test_posix.py", - "import pytest\n\n\n@pytest.mark.platforms(\"posix\")\ndef test_x():\n pass\n", - ) - for platform, expected in [("macos", True), ("linux", True), ("windows", False)]: - result = _run(platform, str(tmp_path)) - listed = result.stdout.split() - assert any(p.endswith("test_posix.py") for p in listed) is expected, platform - - -def test_any_spec_lists_for_every_lane(tmp_path): - _write( - tmp_path, - "test_any.py", - "import pytest\n\n\n@pytest.mark.platforms(\"any\")\ndef test_x():\n pass\n", - ) - for platform in ("linux", "macos", "windows"): - result = _run(platform, str(tmp_path)) - assert result.returncode == 0, result.stderr - assert any(p.endswith("test_any.py") for p in result.stdout.split()), platform - - -def test_arch_filter_still_lists_the_file(tmp_path): - """arch= narrows per-test skips, not file selection. - - The lane's machine is not statically known here; over-selecting is - corrected by the per-test host skip, so an arch-filtered file must - still be listed for its platform's lane. - """ - _write( - tmp_path, - "test_arch.py", - 'import pytest\n\n\n@pytest.mark.platforms("windows", arch="arm64")\n' - "def test_x():\n pass\n", - ) - result = _run("windows", str(tmp_path)) - assert result.returncode == 0, result.stderr - assert any(p.endswith("test_arch.py") for p in result.stdout.split()) - - -def test_multiline_and_single_quoted_spec_lists(tmp_path): - """Real call shapes: multiline decorator args and single-quoted specs.""" - _write( - tmp_path, - "test_multiline.py", - "import pytest\n\n\n" - '@pytest.mark.platforms(\n "windows",\n arch="arm64",\n)\n' - "def test_x():\n pass\n", - ) - _write( - tmp_path, - "test_single_quote.py", - "import pytest\n\n\n@pytest.mark.platforms('macos')\ndef test_y():\n pass\n", - ) - result = _run("windows", str(tmp_path)) - listed = result.stdout.split() - assert any(p.endswith("test_multiline.py") for p in listed) - result = _run("macos", str(tmp_path)) - assert any(p.endswith("test_single_quote.py") for p in result.stdout.split()) - - -def test_negated_exclusive_spec_still_lists_other_lanes(tmp_path): - """``platforms("not linux")`` runs on macos+windows — list it there.""" - _write( - tmp_path, - "test_not_linux.py", - 'import pytest\n\n\n@pytest.mark.platforms("not linux")\ndef test_x():\n pass\n', - ) - for platform in ("macos", "windows"): - result = _run(platform, str(tmp_path)) - assert any(p.endswith("test_not_linux.py") for p in result.stdout.split()), ( - platform - ) + assert {Path(p).stem.removeprefix("test_") for p in result.stdout.split()} == expected def test_unknown_platform_is_rejected(tmp_path): @@ -206,30 +88,16 @@ def test_rejects_missing_root(): assert "no such directory" in result.stderr -def test_emits_repo_relative_posix_paths(): - """Output feeds a bash command line on the Windows runner, so separators - must be POSIX and paths repo-relative. - - Asserted against the real ``tests/`` tree, which is the only case CI - exercises — an out-of-repo root can't be made repo-relative and is - emitted absolute instead. - """ - result = _run("windows") - - assert result.returncode == 0, result.stderr - listed = result.stdout.split() - assert listed - for line in listed: - assert "\\" not in line - assert not Path(line).is_absolute() - - def test_real_tree_selects_files_for_every_platform(): """Against the actual ``tests/`` tree each platform resolves to real files.""" for platform in ("linux", "macos", "windows"): result = _run(platform) assert result.returncode == 0, (platform, result.stderr) assert result.stdout.split(), f"{platform} selected nothing in the real tree" + for line in result.stdout.split(): + assert "\\" not in line + assert not Path(line).is_absolute() + assert (REPO_ROOT / line).is_file() def test_unparseable_file_is_still_listed(tmp_path): """A file the selector cannot parse is conservatively listed so the lane diff --git a/tests/ci/test_required_results.py b/tests/ci/test_required_results.py index 4b96feaed3..813112455d 100644 --- a/tests/ci/test_required_results.py +++ b/tests/ci/test_required_results.py @@ -14,187 +14,62 @@ required_results = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(required_results) evaluate_gate = required_results.evaluate_gate -PR_ONLY_JOBS = required_results.PR_ONLY_JOBS -DEFERRED_JOBS = required_results.DEFERRED_JOBS -EXCLUDED_JOBS = required_results.EXCLUDED_JOBS -def needs_of(entries): - """Build the needs-context shape ci.yaml's all-checks-pass receives.""" - return {name: {"result": result} for name, result in entries} +import pytest -def test_non_release_failure_fails_gate_skip_counts_as_success(): - base = [("detect", "success"), ("tests", "success"), ("lint", "success")] +@pytest.mark.parametrize("release", [False, True]) +@pytest.mark.parametrize("job", ["tests", "osv-scanner", "history-check", "e2e-desktop"]) +@pytest.mark.parametrize("result,ordinary,excluded", [ + ("success", True, True), ("skipped", False, True), ("failure", False, False), + ("cancelled", False, False), ("with-status", False, False), + ("action_required", False, False), ("unknown", False, False), (None, False, False), +]) +def test_status_policy(job, result, ordinary, excluded, release): + expected = excluded if job in ("history-check", "e2e-desktop") else ordinary + if result == "skipped" and not release: + expected = True + verdict = evaluate_gate({job: {} if result is None else {"result": result}}, release=release) + assert verdict == {"ok": expected, "failed": [] if expected else [job], + "allowed_skips": [job] if expected and result == "skipped" else []} - assert evaluate_gate(needs_of(base))["ok"] is True - with_failure = evaluate_gate(needs_of([*base, ("js-tests", "failure")])) - assert with_failure["ok"] is False - assert with_failure["failed"] == ["js-tests"] +def test_release_exclusion_policy(): + assert required_results.EXCLUDED_JOBS == { + "history-check", "lockfile-diff", "supply-chain", "review-labels", "e2e-desktop", + } - # Skipped lanes are fine when not releasing (e.g. docs-only PR). - with_skips = evaluate_gate( - needs_of([("detect", "success"), ("tests", "skipped"), ("rust-tests", "skipped"), ("lint", "success")]) + +@pytest.mark.parametrize("needs", [{}, None]) +@pytest.mark.parametrize("release", [False, True]) +def test_empty_needs_fails_closed(needs, release): + assert evaluate_gate(needs, release=release) == { + "ok": False, "failed": [""], "allowed_skips": [], + } + assert required_results.compact_results(needs) == {} + + +@pytest.mark.parametrize("release,results,code,report", [ + (True, {"detect": "success", "e2e-desktop": "skipped"}, 0, "All checks passed"), + (True, {"tests": "skipped", "history-check": "skipped", "lint": "failure"}, + 1, "::error::2 job(s) failed: lint, tests"), + (False, {"tests": "failure"}, 1, "::error::1 job(s) failed: tests"), +]) +def test_cli_stdin_exit_codes_and_output(tmp_path, release, results, code, report): + output = tmp_path / "github-output.txt" + needs = {name: {"result": result, "outputs": {"detail": "kept"}} + for name, result in results.items()} + child = subprocess.run( + [sys.executable, str(SCRIPT), *(["--release"] if release else [])], + input=json.dumps(needs), capture_output=True, text=True, timeout=30, + env={**os.environ, "GITHUB_OUTPUT": str(output)}, ) - assert with_skips["ok"] is True - assert with_skips["allowed_skips"] == ["rust-tests", "tests"] - - -def test_exclusion_sets_name_exactly_pr_only_and_deferred_jobs(): - assert PR_ONLY_JOBS == ("history-check", "lockfile-diff", "supply-chain", "review-labels") - assert DEFERRED_JOBS == ("e2e-desktop",) - assert EXCLUDED_JOBS == set(PR_ONLY_JOBS) | set(DEFERRED_JOBS) - - -def test_release_only_excluded_jobs_may_skip(): - needs = needs_of( - [ - ("detect", "success"), - ("tests", "success"), - ("js-tests", "success"), - ("osv-scanner", "success"), - # PR-only: never ran — release runs are push/tag events. - ("history-check", "skipped"), - ("lockfile-diff", "skipped"), - ("supply-chain", "skipped"), - ("review-labels", "skipped"), - # Deferred: Desktop E2E stays disabled. - ("e2e-desktop", "skipped"), - ] - ) - verdict = evaluate_gate(needs, release=True) - assert verdict["ok"] is True - assert verdict["allowed_skips"] == ["e2e-desktop", "history-check", "lockfile-diff", "review-labels", "supply-chain"] - - -def test_release_osv_skipped_is_a_failure_not_advisory(): - # Advisory FINDINGS do not make the EXECUTION advisory: the OSV scan - # must run to success on a release candidate. - verdict = evaluate_gate(needs_of([("detect", "success"), ("osv-scanner", "skipped")]), release=True) - assert verdict["ok"] is False - assert verdict["failed"] == ["osv-scanner"] - - -def test_release_skipped_required_job_fails_gate(): - needs = needs_of( - [ - ("detect", "success"), - ("tests", "success"), - # Everything tagged python (and python_prod/frontend) skipped on - # the release run: the strict gate must not wave this through. - ("tests-os", "skipped"), - ("lint", "skipped"), - ("js-tests", "skipped"), - ("infographic-check", "success"), - ] - ) - verdict = evaluate_gate(needs, release=True) - assert verdict["ok"] is False - assert verdict["failed"] == ["js-tests", "lint", "tests-os"] - - -def test_every_non_success_result_fails_in_release_mode(): - # cancelled / with-status / action_required / unknown / missing all - # fail; only `success` passes and only `skipped` on an excluded job - # is tolerated. - needs = needs_of( - [ - ("a", "cancelled"), - ("b", "with-status"), - ("c", "action_required"), - ("d", "unknown"), - ] - ) - verdict = evaluate_gate(needs, release=True) - assert verdict["ok"] is False - assert verdict["failed"] == ["a", "b", "c", "d"] - - # A needs entry with no result key at all (should never happen, but - # must not silently pass). - verdict = evaluate_gate({"x": {}}, release=True) - assert verdict["ok"] is False - assert verdict["failed"] == ["x"] - - -def test_release_failure_fails_gate_even_beside_allowed_skips(): - needs = needs_of( - [ - ("detect", "success"), - ("tests", "failure"), - ("history-check", "skipped"), - ("e2e-desktop", "skipped"), - ] - ) - verdict = evaluate_gate(needs, release=True) - assert verdict["ok"] is False - assert verdict["failed"] == ["tests"] - - -def test_empty_needs_fails_closed(): - assert evaluate_gate({}, release=True)["ok"] is False - assert evaluate_gate({}, release=False)["ok"] is False - assert evaluate_gate(None, release=True)["ok"] is False - - -def test_release_full_pipeline_all_green_passes(): - # What ci.yaml's all-checks-pass actually needs. A release run forces - # the classifier lanes true, so a healthy candidate looks like this. - all_green = [ - "detect", "tests", "tests-os", "lint", "js-tests", "installer-tests", - "rust-tests", "bootstrap-installer", "e2e-desktop", "docs-site", - "history-check", "contributor-check", "uv-lockfile", "infographic-check", - "case-collision-check", "lazy-deps-guard", "lockfile-diff", - "docker-lint", "profile-artifact-check", "icons-freshness-check", - "supply-chain", "review-labels", "osv-scanner", - ] - needs = needs_of((name, "success") for name in all_green) - assert evaluate_gate(needs, release=True)["ok"] is True - assert evaluate_gate(needs, release=False)["ok"] is True - - -def test_compact_results_maps_every_job_to_its_result(): - needs = needs_of([("detect", "success"), ("tests", "skipped")]) - assert required_results.compact_results(needs) == {"detect": "success", "tests": "skipped"} - assert required_results.compact_results(None) == {} - - -def test_render_report_reports_honest_skip_counts(): - needs = needs_of([("tests", "skipped"), ("lint", "failure"), ("detect", "success")]) - verdict = evaluate_gate(needs, release=True) - lines = "\n".join(required_results.render_report(needs, verdict)) - assert "⏭️ tests: skipped" in lines - assert "❌ lint: failure" in lines - assert "::error::2 job(s) failed: lint, tests" in lines - - -def test_cli_stdin_exit_codes_and_output(tmp_path): - gh_output = tmp_path / "github-output.txt" - green = needs_of([("detect", "success"), ("tests", "success"), ("e2e-desktop", "skipped")]) - - def run(needs, release, env_file): - # Inherit the full environment: on Windows a stripped env breaks - # subprocess startup (SystemRoot etc.). - env = dict(os.environ) - env.pop("GITHUB_OUTPUT", None) - if env_file is not None: - env["GITHUB_OUTPUT"] = str(env_file) - return subprocess.run( - [sys.executable, str(SCRIPT)] + (["--release"] if release else []), - input=json.dumps(needs), - capture_output=True, - text=True, - env=env, - ) - - ok = run(green, release=True, env_file=gh_output) - assert ok.returncode == 0 - assert "All checks passed" in ok.stdout - assert "needs-json=" in ok.stdout - assert "needs-json=" in gh_output.read_text(encoding="utf-8") - - bad = run(needs_of([("tests", "skipped")]), release=True, env_file=None) - assert bad.returncode == 1 - - failed = run(needs_of([("tests", "failure")]), release=False, env_file=None) - assert failed.returncode == 1 + assert child.returncode == code, child.stderr + assert report in child.stdout + key, value = output.read_text(encoding="utf-8").strip().split("=", 1) + assert key == "needs-json" + assert json.loads(value) == results + assert f"{key}={value}" in child.stdout + for name, result in results.items(): + assert f"{name}: {result}" in child.stdout diff --git a/tests/ci/test_termux_input_archive.py b/tests/ci/test_termux_input_archive.py index beb99b8ff2..d2a6fc6255 100644 --- a/tests/ci/test_termux_input_archive.py +++ b/tests/ci/test_termux_input_archive.py @@ -1,6 +1,5 @@ """CI runs archival before the exact tool and payload consumers.""" from pathlib import Path -import shlex from ruamel.yaml import YAML @@ -12,30 +11,6 @@ def load(name): return YAML(typ="base").load((ROOT / ".github/workflows" / name).read_text(encoding="utf-8")) -def test_termux_and_desktop_stagers_consume_archive_seeds(): - release = load("desktop-bundled-release.yml") - for file, job_name in (("desktop-bundled-release.yml", "termux-deb"), ("termux-verify.yml", "native-runtime")): - job = load(file)["jobs"][job_name] - steps = job["steps"] - index, step = next((i, s) for i, s in enumerate(steps) if "scripts.ci.archive_inputs" in s.get("run", "")) - args = shlex.split(step["run"]) - assert args[args.index("--target") + 1] == "linux-arm64-bionic" - assert args[args.index("--store") + 1] == "$HERMES_RUNTIME_DIR" - assert args[args.index("--payload") + 1] == "termux-build/payload" - assert "if" not in step and "continue-on-error" not in step - assert R2_ENV <= (job.get("env", {}).keys() | step.get("env", {}).keys()) - first_stage = next(i for i, s in enumerate(steps) if "scripts/termux/build_cpython.sh" in s.get("run", "")) - assert index < first_stage - for name in ("build-win32", "build-darwin"): - steps = release["jobs"][name]["steps"] - index, step = next((i, s) for i, s in enumerate(steps) if "scripts.ci.archive_inputs" in s.get("run", "")) - assert "--target '${{ matrix.target.label }}'" in step["run"] - assert "--store apps/desktop/build/agent-payload/tools" in step["run"] - assert index < next(i for i, s in enumerate(steps) if "scripts/bundles/desktop.py" in s.get("run", "")) - setup = next(s for s in steps if s.get("uses") == "./.github/actions/setup-pm") - assert setup["with"]["archive-inputs"] == "true" - - def test_archive_gate_uses_bootstrap_python_and_trusted_exact_revision(): workflow = load("archive-inputs.yml") assert not {"pull_request", "pull_request_target"} & workflow["on"].keys() diff --git a/tests/computer_use/driver_fixture.py b/tests/computer_use/driver_fixture.py new file mode 100644 index 0000000000..bfc9453190 --- /dev/null +++ b/tests/computer_use/driver_fixture.py @@ -0,0 +1,42 @@ +"""Independent CUA process fixture shared by selection and doctor callers.""" +import sys +from pathlib import Path + + +def record_driver(version="0.20.0", *, manifest=False): + from pm import Facts, Lockfile, current_target, get_package, paths + from pm.store import tree_digest + + package, target, root = get_package("cua-driver"), current_target(), paths.store_root() + entry = root / package.store_entry(version, target) + binary = package.binary(entry, target) + assert binary is not None + binary.parent.mkdir(parents=True, exist_ok=True) + if manifest: + capabilities = { + "mcp": ["--socket", "--grant"], + "serve": ["--socket", "--permission-mode", "--capability-manifest", + "--approve-capability-manifest", "--embedded"], + "stop": ["--socket"], + } + payload = { + "binary_version": version, + "mcp_invocation": {"command": str(binary), "args": ["mcp"]}, + "subcommands": [{"name": name, "args": [{"name": arg} for arg in args]} + for name, args in capabilities.items()], + } + binary.write_text(f"#!{sys.executable}\nimport json, sys\nmanifest = {payload!r}\n" + "if sys.argv[1:] == ['manifest']:\n print(json.dumps(manifest))\n" + "else:\n assert sys.argv[1] in ('status', 'stop')\n", encoding="utf-8") + else: + binary.write_bytes(Path(sys.executable).read_bytes()) + binary.chmod(0o755) + artifact = {"url": "https://example.invalid/cua-fixture", "sha256": "a" * 64} + lock = Lockfile(paths.lockfile_path()) + lock.set_pin(package.name, version, {target: artifact}) + lock.save() + Facts(paths.facts_path()).record( + package.name, version, entry.name, package.env(entry, target), root, + target=target, artifacts=[artifact["sha256"]], digest=tree_digest(entry), + ) + return binary diff --git a/tests/computer_use/test_cua_pm_selection.py b/tests/computer_use/test_cua_pm_selection.py index 8e2343edd9..9b9f34521e 100644 --- a/tests/computer_use/test_cua_pm_selection.py +++ b/tests/computer_use/test_cua_pm_selection.py @@ -5,6 +5,8 @@ from pathlib import Path import pytest +from tests.computer_use.driver_fixture import record_driver + @pytest.fixture def cua_home(tmp_path, monkeypatch): @@ -21,31 +23,6 @@ def cua_home(tmp_path, monkeypatch): return tmp_path -def _record_driver(version="0.20.0"): - from pm import Facts, Lockfile, current_target, get_package, paths - from pm.store import tree_digest - - package = get_package("cua-driver") - target = current_target() - root = paths.store_root() - entry = root / package.store_entry(version, target) - entry.mkdir(parents=True) - binary = package.binary(entry, target) - assert binary is not None - binary.parent.mkdir(parents=True, exist_ok=True) - binary.write_bytes(Path(sys.executable).read_bytes()) - binary.chmod(0o755) - artifact = {"url": "https://example.invalid/cua-fixture", "sha256": "a" * 64} - lock = Lockfile(paths.lockfile_path()) - lock.set_pin(package.name, version, {target: artifact}) - lock.save() - Facts(paths.facts_path()).record( - package.name, version, entry.name, package.env(entry, target), root, - target=target, artifacts=[artifact["sha256"]], digest=tree_digest(entry), - ) - return binary - - def test_pm_selection_ignores_vendor_tree_and_is_passive(cua_home, monkeypatch): import pm from pm import paths @@ -55,7 +32,7 @@ def test_pm_selection_ignores_vendor_tree_and_is_passive(cua_home, monkeypatch): pytest.fail("passive CUA lookup attempted acquisition") monkeypatch.setattr(pm, "ensure", no_install) - binary = _record_driver() + binary = record_driver() legacy = cua_home / ".local" / "bin" / binary.name legacy.parent.mkdir(parents=True) legacy.write_bytes(binary.read_bytes()) @@ -67,46 +44,20 @@ def test_pm_selection_ignores_vendor_tree_and_is_passive(cua_home, monkeypatch): assert resolve_cua_driver_cmd(str(legacy)) == str(legacy) assert resolve_cua_driver_cmd(str(cua_home / "missing")) is None assert paths.facts_path().read_bytes() == before - lock = pm.Lockfile(paths.lockfile_path()) - lock.set_pin("cua-driver", "0.21.0", lock.pinned_artifacts("cua-driver")) - lock.save() - assert resolve_cua_driver_cmd() is None - previous = pm.installed_package("cua-driver", allow_outdated=True) - assert previous is not None and previous.binary == binary - binary.unlink() - assert resolve_cua_driver_cmd() is None @pytest.mark.platforms("linux") def test_setup_acquires_through_pm_and_validates_real_manifest(cua_home, monkeypatch): import pm from hermes_cli.tools_config_cua import install_cua_driver - from tools.computer_use.cua_backend_driver import ( - _CUA_DRIVER_RUNTIME_CONTRACT_ARGS, cua_driver_runtime_contract_status, - ) + from tools.computer_use.cua_backend_driver import cua_driver_runtime_contract_status monkeypatch.setenv("PATH", "") calls = [] def acquire(name, *, explicit): calls.append((name, explicit)) - binary = _record_driver() - # A local process fixture, not an upstream CUA installation. - manifest = { - "binary_version": "0.20.0", - "mcp_invocation": {"command": str(binary), "args": ["mcp"]}, - "subcommands": [ - {"name": verb, "args": [{"name": arg} for arg in sorted(args)]} - for verb, args in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items() - ], - } - binary.write_text( - f"#!{sys.executable}\nimport json, sys\n" - f"manifest = {manifest!r}\n" - "assert sys.argv[1:] == ['manifest']\n" - "print(json.dumps(manifest))\n", - encoding="utf-8", - ) + record_driver(manifest=True) return pm.Runner(name, pm.env_for(name)) monkeypatch.setattr(pm, "ensure", acquire) @@ -129,7 +80,6 @@ def test_private_start_uses_post_ensure_binary(cua_home, monkeypatch, permission import pm from tools.computer_use import cua_backend as backend_module - from tools.computer_use.cua_backend_driver import _CUA_DRIVER_RUNTIME_CONTRACT_ARGS monkeypatch.setenv("PATH", "") manifest_path = cua_home / "capabilities.yaml" @@ -138,7 +88,7 @@ def test_private_start_uses_post_ensure_binary(cua_home, monkeypatch, permission "capability_manifest": str(manifest_path), "no_overlay": False, }) if preinstalled: - previous = _record_driver() + previous = record_driver() previous.write_text(f"#!{sys.executable}\nprint('{{}}')\n", encoding="utf-8") backend = backend_module.CuaDriverBackend(permission_mode=permission_mode) assert backend._embedded_daemon is not None @@ -148,22 +98,7 @@ def test_private_start_uses_post_ensure_binary(cua_home, monkeypatch, permission def acquire(name, **kwargs): assert name == "cua-driver" and not kwargs.get("explicit", False) version = next(versions) - binary = _record_driver(version) - manifest = { - "binary_version": version, - "mcp_invocation": {"command": str(binary), "args": ["mcp"]}, - "subcommands": [ - {"name": verb, "args": [{"name": arg} for arg in sorted(args)]} - for verb, args in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items() - ], - } - binary.write_text( - f"#!{sys.executable}\nimport json, sys\n" - f"manifest = {manifest!r}\n" - "if sys.argv[1:] == ['manifest']:\n print(json.dumps(manifest))\n" - "else:\n assert sys.argv[1] in ('status', 'stop')\n", - encoding="utf-8", - ) + binary = record_driver(version, manifest=True) acquired.append(str(binary)) return pm.Runner(name, pm.env_for(name)) diff --git a/tests/computer_use/test_cua_spawn_env_sanitization.py b/tests/computer_use/test_cua_spawn_env_sanitization.py index 8177cfd255..e742646116 100644 --- a/tests/computer_use/test_cua_spawn_env_sanitization.py +++ b/tests/computer_use/test_cua_spawn_env_sanitization.py @@ -199,41 +199,3 @@ def test_doctor_spawn_sanitizes_env_and_hides_console_on_windows(monkeypatch): assert report["overall"] == "ok" _assert_sanitized(captured) assert captured["creationflags"] == CREATE_NO_WINDOW - - -def test_doctor_sanitized_env_helper(monkeypatch): - """The doctor MCP spawn site must pass the sanitized env to Popen. - - Behavioral check: intercept subprocess.Popen at the `_open_mcp` spawn - seam and assert the env it receives strips secrets and applies the - telemetry opt-out (no source-text inspection — that breaks on any - refactor with identical runtime behavior).""" - monkeypatch.setenv("ANTHROPIC_API_KEY", SECRET) - monkeypatch.setenv("PATH", "/usr/bin:/bin") - monkeypatch.delenv("HERMES_CUA_TELEMETRY", raising=False) - - from tools.computer_use import doctor - - env = doctor._sanitized_cua_env() - assert "ANTHROPIC_API_KEY" not in env - _assert_path_preserved(env) - assert env.get("CUA_DRIVER_RS_TELEMETRY_ENABLED") == "0" - - # The Popen spawn site must actually use the sanitized helper. - captured = {} - - class _FakeProc: - stdin = None - stdout = None - stderr = None - - def _fake_popen(*args, **kwargs): - captured["env"] = kwargs.get("env") - return _FakeProc() - - monkeypatch.setattr(doctor.subprocess, "Popen", _fake_popen) - doctor._open_mcp("cua-driver") - spawn_env = captured["env"] - assert spawn_env is not None, "_open_mcp must pass an explicit env" - assert "ANTHROPIC_API_KEY" not in spawn_env - assert spawn_env.get("CUA_DRIVER_RS_TELEMETRY_ENABLED") == "0" diff --git a/tests/computer_use/test_doctor.py b/tests/computer_use/test_doctor.py index 2798ca25c8..a1e4310fad 100644 --- a/tests/computer_use/test_doctor.py +++ b/tests/computer_use/test_doctor.py @@ -82,34 +82,25 @@ def _degraded_report() -> dict: -@pytest.fixture(autouse=True) +@pytest.fixture def pm_driver(tmp_path, monkeypatch): - """Exercise real passive PM selection; native driver probes are mocked below.""" import pm from pm import paths - from pm.store import tree_digest + from tests.computer_use.driver_fixture import record_driver monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "tools")) + monkeypatch.setattr(paths, "lockfile_path", lambda: tmp_path / "lock.json") monkeypatch.delenv("HERMES_CUA_DRIVER_CMD", raising=False) - monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1") monkeypatch.setattr(pm, "ensure", MagicMock(side_effect=AssertionError("doctor must not install"))) - package, target = pm.get_package("cua-driver"), pm.current_target() - lock = pm.Lockfile(paths.lockfile_path()) - version = lock.version(package.name) - assert version is not None - root = paths.store_root() - entry = root / package.store_entry(version, target) - binary = package.binary(entry, target) - assert binary is not None - binary.parent.mkdir(parents=True) - binary.write_bytes(Path(sys.executable).read_bytes()) - binary.chmod(0o755) - pm.Facts(paths.facts_path()).record( - package.name, version, entry.name, package.env(entry, target), root, - target=target, artifacts=[a["sha256"] for a in lock.artifacts(package.name, target)], - digest=tree_digest(entry), - ) - return binary + return record_driver() + + +@pytest.fixture(autouse=True) +def protocol_driver(request, monkeypatch): + # Only selection tests need a real PM store; protocol/rendering tests + # begin after binary selection and never execute the copied interpreter. + if request.cls is not TestDriverCmdResolution: + monkeypatch.setattr("tools.computer_use.cua_backend_driver.resolve_cua_driver_cmd", lambda cmd=None: "fixture-driver") @pytest.fixture(autouse=True) @@ -292,36 +283,21 @@ class TestJsonOutput: class TestDriverCmdResolution: - def test_explicit_driver_cmd_arg_wins(self, pm_driver, tmp_path, monkeypatch): - from tools.computer_use import doctor - - explicit = tmp_path / pm_driver.name - explicit.write_bytes(pm_driver.read_bytes()) - explicit.chmod(0o755) - monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(pm_driver)) - proc = _fake_proc_with_responses( - {"jsonrpc": "2.0", "id": 1, "result": {}}, - {"jsonrpc": "2.0", "id": 2, "result": {"structuredContent": _ok_report()}}, - ) - with patch.object(doctor, "_open_mcp", return_value=proc) as spawn, \ - patch("sys.stdout", new_callable=StringIO): - assert doctor.run_doctor(driver_cmd=str(explicit)) == 0 - spawn.assert_called_once_with(str(explicit)) - - def test_env_var_used_when_no_arg_given(self, pm_driver, tmp_path, monkeypatch): + @pytest.mark.parametrize("explicit", [False, True]) + def test_override_selection(self, pm_driver, tmp_path, monkeypatch, explicit): from tools.computer_use import doctor external = tmp_path / pm_driver.name external.write_bytes(pm_driver.read_bytes()) external.chmod(0o755) - monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(external)) + monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(pm_driver if explicit else external)) proc = _fake_proc_with_responses( {"jsonrpc": "2.0", "id": 1, "result": {}}, {"jsonrpc": "2.0", "id": 2, "result": {"structuredContent": _ok_report()}}, ) with patch.object(doctor, "_open_mcp", return_value=proc) as spawn, \ patch("sys.stdout", new_callable=StringIO): - assert doctor.run_doctor() == 0 + assert doctor.run_doctor(driver_cmd=str(external) if explicit else None) == 0 spawn.assert_called_once_with(str(external)) def test_pm_driver_is_found_when_path_omits_it(self, pm_driver, monkeypatch): @@ -339,7 +315,7 @@ class TestDriverCmdResolution: assert paths.facts_path().read_bytes() == before @pytest.mark.parametrize("use_env", [False, True], ids=["argument", "environment"]) - def test_missing_override_does_not_fall_back_to_pm(self, tmp_path, monkeypatch, use_env, capsys): + def test_missing_override_does_not_fall_back_to_pm(self, pm_driver, tmp_path, monkeypatch, use_env, capsys): from tools.computer_use import doctor missing = str(tmp_path / "missing-driver") diff --git a/tests/cron/test_file_permissions.py b/tests/cron/test_file_permissions.py index 2068990b2e..6244246805 100644 --- a/tests/cron/test_file_permissions.py +++ b/tests/cron/test_file_permissions.py @@ -15,7 +15,7 @@ from unittest.mock import patch import pytest -pytestmark = pytest.mark.platforms("linux") +pytestmark = pytest.mark.platforms("posix") class TestCronFilePermissions(unittest.TestCase): diff --git a/tests/cron/test_parallel_pool.py b/tests/cron/test_parallel_pool.py index 978b490c73..76ac6537a5 100644 --- a/tests/cron/test_parallel_pool.py +++ b/tests/cron/test_parallel_pool.py @@ -46,7 +46,8 @@ class TestPersistentPool: class TestRunningJobGuard: """_running_job_ids prevents double-dispatch of active jobs.""" - def test_running_set_prevents_double_dispatch(self, tmp_path, monkeypatch): + @pytest.mark.parametrize("with_workdir", [False, True]) + def test_running_set_prevents_double_dispatch(self, tmp_path, monkeypatch, with_workdir): """A job already in _running_job_ids is skipped on the next tick.""" import cron.scheduler as sched @@ -65,6 +66,9 @@ class TestRunningJobGuard: "deliver": "local", } + if with_workdir: + job["workdir"] = str(tmp_path) + # Simulate the job already running. sched._running_job_ids.add("guard-job") @@ -229,7 +233,8 @@ class TestSyncMode: sched._shutdown_parallel_pool() - def test_sync_false_returns_immediately(self, tmp_path, monkeypatch): + @pytest.mark.parametrize("with_workdir", [False, True]) + def test_sync_false_returns_immediately(self, tmp_path, monkeypatch, with_workdir): """The ticker returns while its dispatched worker is still blocked.""" import cron.scheduler as sched @@ -247,55 +252,8 @@ class TestSyncMode: "deliver": "local", } - worker_started = threading.Event() - release = threading.Event() - worker_finished = threading.Event() - - def slow_run(j, *, defer_agent_teardown=None, **_kw): - worker_started.set() - try: - assert release.wait(timeout=10), "test never released the worker" - finally: - worker_finished.set() - return True, "out", "resp", None - - monkeypatch.setattr(sched, "get_due_jobs", lambda: [job]) - monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True) - monkeypatch.setattr(sched, "run_job", slow_run) - monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: "/tmp/out") - monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None) - monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None) - - try: - assert sched.tick(verbose=False, sync=False) == 1 - assert worker_started.wait(timeout=10) - assert not worker_finished.is_set() - finally: - release.set() - sched._shutdown_parallel_pool() - - -class TestWorkdirParallelPool: - """Task-scoped workdir jobs use the normal persistent parallel pool.""" - - def test_workdir_job_does_not_block_ticker(self, tmp_path, monkeypatch): - """The ticker returns while its dispatched worker is still blocked.""" - import cron.scheduler as sched - - sched._parallel_pool = None - sched._parallel_pool_max_workers = None - sched._running_job_ids.clear() - - job = { - "id": "slow-workdir", - "name": "slow-workdir", - "prompt": "test", - "schedule": "every 5m", - "enabled": True, - "next_run_at": "2020-01-01T00:00:00", - "deliver": "local", - "workdir": str(tmp_path), - } + if with_workdir: + job["workdir"] = str(tmp_path) worker_started = threading.Event() release = threading.Event() @@ -324,42 +282,6 @@ class TestWorkdirParallelPool: release.set() sched._shutdown_parallel_pool() - def test_workdir_running_guard_prevents_double_dispatch(self, tmp_path, monkeypatch): - """A workdir job already in _running_job_ids is skipped on next tick.""" - import cron.scheduler as sched - - sched._parallel_pool = None - sched._parallel_pool_max_workers = None - sched._running_job_ids.clear() - - job = { - "id": "guard-seq", - "name": "guard-seq", - "prompt": "test", - "schedule": "every 5m", - "enabled": True, - "next_run_at": "2020-01-01T00:00:00", - "deliver": "local", - "workdir": str(tmp_path), - } - - # Simulate the job already running. - sched._running_job_ids.add("guard-seq") - - dispatched = [] - monkeypatch.setattr(sched, "get_due_jobs", lambda: [job]) - monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True) - monkeypatch.setattr(sched, "run_job", lambda j, **_kw: dispatched.append(j["id"]) or (True, "out", "resp", None)) - monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: None) - monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None) - monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None) - - n = sched.tick(verbose=False) - assert n == 0 # skipped, not dispatched - assert dispatched == [] - - sched._running_job_ids.discard("guard-seq") - sched._shutdown_parallel_pool() class TestTickBatchAdvance: """The tick's pre-dispatch advance must go through advance_next_runs diff --git a/tests/cron/test_script_claim_heartbeat.py b/tests/cron/test_script_claim_heartbeat.py index 7849a1e3b5..bc9c409c6e 100644 --- a/tests/cron/test_script_claim_heartbeat.py +++ b/tests/cron/test_script_claim_heartbeat.py @@ -2,7 +2,6 @@ from datetime import datetime, timedelta, timezone import contextlib -import sys import threading import time from unittest.mock import MagicMock, patch @@ -10,178 +9,65 @@ from unittest.mock import MagicMock, patch import pytest -_SPAWNABLE_PY: "str | None" = None - - -def _spawnable_python() -> str: - global _SPAWNABLE_PY - if _SPAWNABLE_PY is not None: - return _SPAWNABLE_PY - - """An interpreter that can actually CreateProcess children. The hermetic - runner's sys.executable can be an emulated x64 binary on an arm64 host - (WinError 5 on every spawn); the WindowsApps packaged python works by - full path. Falls back to sys.executable.""" +@pytest.mark.platforms("posix") +@pytest.mark.live_system_guard_bypass +@pytest.mark.parametrize("trigger", ["cancel", "timeout"]) +@pytest.mark.parametrize("topology", ["detached", "stubborn-pipe"]) +def test_script_termination_reaps_descendants(tmp_path, monkeypatch, trigger, topology): import os - import subprocess as sp - - for cand in (os.environ.get("HERMES_TEST_PYTHON"), sys.executable): - if not cand: - continue - try: - # The candidate must run AND spawn its own child — these tests - # execute scripts that Popen grandchildren, and an emulated - # interpreter can run -c while its own subprocess.Popen fails. - r = sp.run( - [cand, "-c", "import subprocess; subprocess.run(['cmd','/c','exit 0'] if __import__('os').name=='nt' else ['true'])"], - capture_output=True, timeout=30, - ) - if r.returncode == 0: - _SPAWNABLE_PY = cand - return cand - except Exception: - continue - _SPAWNABLE_PY = sys.executable - return _SPAWNABLE_PY - -@pytest.mark.platforms("linux") -def test_cancel_event_terminates_script_process_tree(tmp_path, monkeypatch): - """Losing a fire claim must stop both the script and its descendants.""" - import cron.scheduler as scheduler - from cron import scheduler_script as sched_script + import psutil + from cron import scheduler, scheduler_script monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path) - # Under the hermetic runner sys.executable can be an emulated binary - # whose children fail to spawn; cron resolves the script interpreter - # from sys.executable, so pin it to one that actually works here. - monkeypatch.setattr(scheduler.sys, "executable", _spawnable_python()) - scripts_dir = tmp_path / "scripts" - scripts_dir.mkdir() - PY = _spawnable_python() # interpreter the spawned script uses for grandchildren - started = tmp_path / "started" - child_done = tmp_path / "child-done" - script = scripts_dir / "blocking.py" - child_code = ( - "import time; from pathlib import Path; " - # Long sleep: the descendant must outlive the tree-kill's worst-case - # latency under load — child_done within the assertion window can - # then ONLY mean the kill missed it, never that it finished on its - # own (which a 1s sleep would allow under 36-way CPU contention). - f"time.sleep(10); Path({str(child_done)!r}).write_text('done')" - ) - script.write_text( - "import subprocess, sys, time\n" - f"subprocess.Popen([{PY!r}, '-c', {child_code!r}])\n" - f"open({str(started)!r}, 'w').close()\n" - "time.sleep(30)\n", - encoding="utf-8", - ) - - cancel = threading.Event() - result = [] - errors = [] - - def _run() -> None: + monkeypatch.setattr(scheduler_script, "_get_script_timeout", lambda: 3 if trigger == "timeout" else 60) + scripts = tmp_path / "scripts" + scripts.mkdir() + ready = tmp_path / "child.pid" + child = ("import os, signal, time; from pathlib import Path; " + + ("signal.signal(signal.SIGTERM, signal.SIG_IGN); " if topology == "stubborn-pipe" else "") + + f"Path({str(ready)!r}).write_text(str(os.getpid())); time.sleep(60)") + script = scripts / "blocking.py" + script.write_text("import subprocess, sys, time\n" + + f"subprocess.Popen([sys.executable, '-c', {child!r}], start_new_session={topology == 'detached'})\n" + + "time.sleep(60)\n", encoding="utf-8") + cancel, results, errors = threading.Event(), [], [] + def run(): try: - result.append( - sched_script._run_job_script( - str(script), - workdir=str(tmp_path), - cancel_event=cancel, - ) - ) - except Exception as exc: + results.append(scheduler_script._run_job_script(str(script), workdir=str(tmp_path), cancel_event=cancel)) + except BaseException as exc: errors.append(exc) - - thread = threading.Thread(target=_run) - thread.start() - # Generous deadline: under 36-way parallel load the spawned - # interpreter's cold start can exceed 5s on first attempt. - deadline = time.monotonic() + 15 - while not started.exists() and not errors and time.monotonic() < deadline: - time.sleep(0.01) - assert errors == [] - assert started.exists(), "script did not start" - - cancel.set() - # The tree-kill (taskkill /T under load) can take several seconds when - # 36 parallel test workers compete for the CPU — generous join bound. - thread.join(timeout=15) - - assert errors == [] - assert not thread.is_alive(), "script ignored cancellation" - assert result and result[0][0] is False - assert "cancel" in result[0][1].lower() - time.sleep(1.2) - assert not child_done.exists(), "script descendant survived cancellation" - - -@pytest.mark.skipif(sys.platform == "win32", reason="POSIX process-group semantics") -def test_cancel_event_kills_sigterm_ignoring_descendant(tmp_path, monkeypatch): - """A SIGTERM-ignoring grandchild must not wedge the cancellation path: - the tree kill escalates to SIGKILL for surviving group members, and the - pipe drain is bounded even if a descendant still holds the write ends.""" - import cron.scheduler as scheduler - from cron import scheduler_script as sched_script - - monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path) - # Under the hermetic runner sys.executable can be an emulated binary - # whose children fail to spawn; cron resolves the script interpreter - # from sys.executable, so pin it to one that actually works here. - monkeypatch.setattr(scheduler.sys, "executable", _spawnable_python()) - scripts_dir = tmp_path / "scripts" - scripts_dir.mkdir() - PY = _spawnable_python() # interpreter the spawned script uses for grandchildren - started = tmp_path / "started" - script = scripts_dir / "stubborn.py" - child_code = ( - "import signal, time; " - "signal.signal(signal.SIGTERM, signal.SIG_IGN); " - f"open({str(started)!r}, 'w').close(); " - "time.sleep(60)" - ) - script.write_text( - "import subprocess, sys, time\n" - f"subprocess.Popen([{PY!r}, '-c', {child_code!r}])\n" - "time.sleep(60)\n", - encoding="utf-8", - ) - - cancel = threading.Event() - result = [] - errors = [] - - def _run() -> None: + def live(pid): try: - result.append( - sched_script._run_job_script( - str(script), - workdir=str(tmp_path), - cancel_event=cancel, - ) - ) - except Exception as exc: - errors.append(exc) - - thread = threading.Thread(target=_run) + return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE + except psutil.NoSuchProcess: + return False + thread = threading.Thread(target=run) thread.start() - # Generous deadline: under 36-way parallel load the spawned - # interpreter's cold start can exceed 5s on first attempt. - deadline = time.monotonic() + 15 - while not started.exists() and not errors and time.monotonic() < deadline: - time.sleep(0.01) - assert errors == [] - assert started.exists(), "script did not spawn its descendant" - - cancel.set() - # TERM grace (1s) + KILL + bounded drain (5s) + margin: must return well - # before the unbounded-communicate hang this regresses against. - thread.join(timeout=10) - - assert errors == [] - assert not thread.is_alive(), "cancellation wedged on a SIGTERM-ignoring descendant" - assert result and result[0][0] is False - assert "cancel" in result[0][1].lower() + pid = None + try: + deadline = time.monotonic() + 10 + while not ready.exists() and not errors and time.monotonic() < deadline: + time.sleep(0.01) + assert ready.exists() and not errors, errors + pid = int(ready.read_text(encoding="utf-8")) + assert live(pid), "child must acknowledge readiness before termination" + if trigger == "cancel": + cancel.set() + thread.join(timeout=15) + assert not thread.is_alive() and not errors, errors + assert results[0][0] is False + assert ("cancelled" if trigger == "cancel" else "timed out") in results[0][1] + deadline = time.monotonic() + 5 + while live(pid) and time.monotonic() < deadline: + time.sleep(0.05) + assert not live(pid), f"descendant {pid} survived {trigger}" + finally: + cancel.set() + if pid is None and ready.exists(): + pid = int(ready.read_text(encoding="utf-8")) + if pid is not None and live(pid): + os.kill(pid, 9) + thread.join(timeout=15) def test_no_agent_forwards_cancel_event_to_script_runner(monkeypatch): diff --git a/tests/desktop/test_appinstaller_check_script.py b/tests/desktop/test_appinstaller_check_script.py index 3b465cbaaf..db68412c11 100644 --- a/tests/desktop/test_appinstaller_check_script.py +++ b/tests/desktop/test_appinstaller_check_script.py @@ -29,100 +29,73 @@ SCRIPT = ( / "apps/desktop/scripts/check-appinstaller-update.py" ) -_NO_PACKAGE_IDENTITY_HRESULT = -2147009196 # 0x80073D54 +@pytest.mark.parametrize("state,code,available", [ + ("not-packaged", 0, False), ("AVAILABLE", 2, True), ("REQUIRED", 2, True), + ("NO_UPDATES", 0, False), ("UNKNOWN", 1, None), ("ERROR", 1, None), + ("no-source", 1, None), ("check-error", 1, None), ("identity-error", 1, None), + ("missing-projection", 1, None), ("missing-current", 1, None), +]) +def test_projection_outcomes(monkeypatch, capsys, state, code, available): + import enum + import runpy + from types import SimpleNamespace + + main = runpy.run_path(str(SCRIPT))["main"] + availability = enum.IntEnum("Availability", "UNKNOWN NO_UPDATES AVAILABLE REQUIRED ERROR", start=0) + class PackageInstance: + def get_app_installer_info(self): + return None if state == "no-source" else SimpleNamespace( + uri=SimpleNamespace(absolute_uri="https://registered.example/updates.appinstaller")) + + def check_update_availability_async(self): + def get(): + if state == "check-error": + raise RuntimeError("rpc boom") + return SimpleNamespace(availability=availability[state]) + return SimpleNamespace(get=get) + + class PackageMeta(type): + @property + def current(cls): + if state in ("not-packaged", "identity-error"): + error = OSError("identity failure") + error.winerror = -2147009196 if state == "not-packaged" else -2147024891 + raise error + return PackageInstance() + + class Package(metaclass=PackageMeta): + pass + + def load(): + if state == "missing-projection": + raise ImportError("missing winrt") + return (object if state == "missing-current" else Package), availability + + monkeypatch.setitem(main.__globals__, "_load_projection", load) + assert main() == code + payload = json.loads(capsys.readouterr().out) + assert payload["available"] is available + if state == "not-packaged": + assert payload == {"available": False, "reason": "not-packaged"} + elif state in ("AVAILABLE", "REQUIRED", "NO_UPDATES"): + assert payload["availability"] == state + assert payload["source_uri"] == "https://registered.example/updates.appinstaller" + else: + assert payload["error"] + if state == "no-source": + assert payload["reason"] == "no-app-installer-source" + assert ".appinstaller" in payload["error"] -def _stub_module(*, identity_error: bool, availability: str | None, check_raises: bool) -> str: - current_body = ( - " exc = OSError('The process has no package identity.')\n" - f" exc.winerror = {_NO_PACKAGE_IDENTITY_HRESULT}\n" - " raise exc" - if identity_error - else " return _FakePackage()" - ) - get_body = ( - ' raise RuntimeError("rpc boom")' - if check_raises - else " return _AvailabilityResult(self._availability)" - ) - check_body = ( - ' raise RuntimeError("winrt blew up")' - if check_raises - else f" return _AsyncOp({availability!r})" - ) - return "\n".join( - [ - "import enum", - "", - "class PackageUpdateAvailability(enum.Enum):", - ' UNKNOWN = "unknown"', - ' NO_UPDATES = "noUpdates"', - ' AVAILABLE = "available"', - ' REQUIRED = "required"', - ' ERROR = "error"', - "", - "class _AvailabilityResult:", - " def __init__(self, availability):", - " self.availability = availability", - "", - "class _AsyncOp:", - " def __init__(self, availability):", - " self._availability = availability", - "", - " def get(self):", - get_body, - "", - "class _FakePackage:", - " def get_app_installer_info(self):", - " from types import SimpleNamespace", - " return SimpleNamespace(uri=SimpleNamespace(absolute_uri='https://registered.example/updates.appinstaller'))", - " def check_update_availability_async(self):", - check_body, - "", - "class _PackageMeta(type):", - " @property", - " def current(cls):", - current_body, - "", - "class Package(metaclass=_PackageMeta):", - " pass", - "", - ] - ) - - -def _stub_winrt(tmp_path: Path, package_module: str) -> Path: - """Render a stub winrt tree whose Package comes from ``package_module``. - PackageManager deliberately has NO check_package_update_availability_async: - the real projection's shape is part of the contract under test.""" - root = tmp_path / "stub" - appmodel = root / "winrt/windows/applicationmodel" - deployment = root / "winrt/windows/management/deployment" - for d in (appmodel, deployment): - d.mkdir(parents=True) - (root / "winrt/__init__.py").write_text("") - (root / "winrt/windows/__init__.py").write_text("") - (root / "winrt/windows/management/__init__.py").write_text("") - (deployment / "__init__.py").write_text("from .deployment import PackageManager\n") - (deployment / "deployment.py").write_text( - "class PackageManager:\n" - " # No check_package_update_availability_async — it does not exist in\n" - " # the real projection; the method lives on Package instances.\n" - " pass\n" - ) - (appmodel / "__init__.py").write_text(package_module) - return root - - -def _run(root: Path) -> tuple[int, dict]: - env = {"PYTHONPATH": str(root)} - if os.environ.get("SYSTEMROOT"): - env["SYSTEMROOT"] = os.environ["SYSTEMROOT"] - proc = subprocess.run( - [HERMES_PYTHON, str(SCRIPT)], - capture_output=True, text=True, timeout=60, env=env, - ) - return proc.returncode, json.loads(proc.stdout.strip().splitlines()[-1]) +def test_script_import_failure_json_and_exit(tmp_path): + # A real subprocess executes __main__ and imports the absent projection. + (tmp_path / "winrt.py").write_text("raise ImportError('fixture unavailable')", encoding="utf-8") + child = subprocess.run([HERMES_PYTHON, str(SCRIPT)], capture_output=True, + text=True, timeout=30, env={**os.environ, "PYTHONPATH": str(tmp_path)}) + assert child.returncode == 1, child.stderr + payload = json.loads(child.stdout) + assert payload["available"] is None + assert "fixture unavailable" in payload["error"] @pytest.mark.platforms("windows") @@ -142,90 +115,3 @@ def test_installed_winrt_projects_checker_uri_and_async_types(tmp_path): ) assert probe.returncode == 0, probe.stderr assert probe.stdout.strip() == "WINRT_CHECKER_TYPES_OK" - - -def test_not_packaged_is_reported_as_not_packaged(tmp_path): - root = _stub_winrt(tmp_path, _stub_module(identity_error=True, availability=None, check_raises=False)) - code, payload = _run(root) - assert code == 0 - assert payload == {"available": False, "reason": "not-packaged"} - - -def test_update_available_exit_2(tmp_path): - root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="available", check_raises=False)) - code, payload = _run(root) - assert code == 2 - assert payload["available"] is True - assert payload["availability"] == "AVAILABLE" - assert payload["source_uri"] == "https://registered.example/updates.appinstaller" - - -def test_no_update_exit_0(tmp_path): - root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="noUpdates", check_raises=False)) - code, payload = _run(root) - assert code == 0 - assert payload["available"] is False - - -def test_unknown_availability_is_not_no_update(tmp_path): - """UNKNOWN (enum 0) is an unknown, never available:false (C06-09 review).""" - root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="unknown", check_raises=False)) - code, payload = _run(root) - assert code == 1 - assert payload["available"] is None - assert "error" in payload - - -def test_error_availability_is_not_no_update(tmp_path): - """ERROR (enum 4) is an unknown with an extended error, never available:false.""" - root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="error", check_raises=False)) - code, payload = _run(root) - assert code == 1 - assert payload["available"] is None - assert "error" in payload - - -def test_missing_appinstaller_source_explains_the_remedy(tmp_path): - module = _stub_module(identity_error=False, availability="unknown", check_raises=False).replace( - "return SimpleNamespace(uri=SimpleNamespace(absolute_uri='https://registered.example/updates.appinstaller'))", - "return None", - ) - root = _stub_winrt(tmp_path, module) - code, payload = _run(root) - assert code == 1 - assert payload["available"] is None - assert payload["reason"] == "no-app-installer-source" - assert ".appinstaller" in payload["error"] - - -def test_check_failure_is_unknown_not_no_update(tmp_path): - root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability=None, check_raises=True)) - code, payload = _run(root) - assert code == 1 - assert payload["available"] is None - assert "error" in payload - - -def test_unexpected_package_identity_error_is_unknown(tmp_path): - """A non-identity failure while reading the current package is a real - error — it must never masquerade as not-packaged (available:false).""" - module = _stub_module(identity_error=False, availability="available", check_raises=False).replace( - " return _FakePackage()", - ' raise OSError(5, "access denied", None, -2147024891)', - ) - root = _stub_winrt(tmp_path, module) - code, payload = _run(root) - assert code == 1 - assert payload["available"] is None - - -def test_projection_without_current_property_is_unknown(tmp_path): - """A projection that does not expose the current-package static must - degrade to unknown — the checker may not guess an API shape.""" - module = _stub_module(identity_error=False, availability="available", check_raises=False).replace( - "class Package(metaclass=_PackageMeta):", "class PackageNotProjected(metaclass=_PackageMeta):" - ) - root = _stub_winrt(tmp_path, module) - code, payload = _run(root) - assert code == 1 - assert payload["available"] is None diff --git a/tests/docker/test_dump_build_sha.py b/tests/docker/test_dump_build_sha.py index 56a2dbaea7..9932e83950 100644 --- a/tests/docker/test_dump_build_sha.py +++ b/tests/docker/test_dump_build_sha.py @@ -21,6 +21,8 @@ This test asserts both cases: from __future__ import annotations import json +import os +from pathlib import Path import re import subprocess @@ -81,6 +83,17 @@ def test_dump_reports_stamp_commit_when_present(built_image: str) -> None: that breaks the stamp -> dump pipeline will fail CI here. """ stamped = _read_stamp_commit_from_image(built_image) + # docker.yml writes this build input before building and testing the image. + # Read the independent input: the canonical runner scrubs CI/GITHUB_SHA. + source_stamp = Path(__file__).resolve().parents[2] / "install-stamp.json" + if os.environ.get("HERMES_TEST_IMAGE"): + assert source_stamp.is_file(), "prebuilt image requires its checkout build stamp" + if source_stamp.is_file(): + expected = json.loads(source_stamp.read_text(encoding="utf-8-sig"))["commit"] + assert re.fullmatch(r"[0-9a-f]{40}", expected), "invalid expected build commit" + assert stamped == expected, "image lost or changed its build provenance" + if stamped is not None: + assert re.fullmatch(r"[0-9a-f]{40}", stamped), "malformed image stamp commit" stdout = _run_dump(built_image) match = _VERSION_LINE.search(stdout) diff --git a/tests/docker/test_immutable_install.py b/tests/docker/test_immutable_install.py index e2fae89e08..824eab3ce9 100644 --- a/tests/docker/test_immutable_install.py +++ b/tests/docker/test_immutable_install.py @@ -29,6 +29,27 @@ def test_install_tree_not_writable_by_hermes( """ start_container(built_image, container_name) + probe = docker_exec(container_name, "/opt/hermes/.venv/bin/python", "-c", """ +import os +from pathlib import Path +from hermes_cli.config import detect_install_method +assert os.geteuid() != 0 +code = Path('/opt/hermes/.install_method') +home = Path('/opt/data/.install_method') +assert code.read_text().strip() == 'docker' +assert detect_install_method(Path('/opt/hermes')) == 'docker' +assert not home.exists() or home.read_text().strip() != 'docker' +try: + with code.open('a'): + pass +except PermissionError: + pass +else: + raise AssertionError('runtime user can alter installation method') +assert code.read_text().strip() == 'docker' +""") + assert probe.returncode == 0, probe.stdout + probe.stderr + r = docker_exec_sh( container_name, # Try to create a file under /opt/hermes as the hermes user diff --git a/tests/gateway/test_matrix.py b/tests/gateway/test_matrix.py index 063c8c8673..1e250231c0 100644 --- a/tests/gateway/test_matrix.py +++ b/tests/gateway/test_matrix.py @@ -874,38 +874,6 @@ class TestMatrixRequirements: with patch.object(builtins, "__import__", _blocking_import): assert _check_e2ee_deps() is False - def test_check_requirements_runs_lazy_install_when_partial(self, monkeypatch): - """When mautrix is installed but asyncpg/aiosqlite are missing, - check_matrix_requirements must still run the lazy installer. - - Regression for #31116: the previous ``try: import mautrix`` gate - short-circuited the install of the OTHER 4 platform.matrix packages, - so a partial install (mautrix only) was treated as fully installed. - """ - monkeypatch.setenv("MATRIX_ACCESS_TOKEN", "syt_test") - monkeypatch.setenv("MATRIX_HOMESERVER", "https://matrix.example.org") - monkeypatch.delenv("MATRIX_ENCRYPTION", raising=False) - - import plugins.platforms.matrix.adapter as matrix_mod - - # Simulate "mautrix installed, asyncpg missing" → feature_missing - # returns a non-empty tuple → ensure_and_bind MUST be called. - called = {"ensure_and_bind": False} - - def _fake_ensure_and_bind(feature, importer, target_globals, **kwargs): - called["ensure_and_bind"] = True - assert feature == "matrix" - return True # Pretend install succeeded. - - with patch("pm.extras.missing", return_value=("asyncpg==0.31.0",)), \ - patch("pm.extras.ensure_and_bind", side_effect=_fake_ensure_and_bind): - matrix_mod.check_matrix_requirements() - - assert called["ensure_and_bind"], ( - "check_matrix_requirements must call ensure_and_bind whenever ANY " - "platform.matrix dep is missing, not just when mautrix itself is " - "missing (#31116)" - ) # --------------------------------------------------------------------------- diff --git a/tests/gateway/test_matrix_deps_rebind.py b/tests/gateway/test_matrix_deps_rebind.py index 5825ba0e7b..7e848c8a78 100644 --- a/tests/gateway/test_matrix_deps_rebind.py +++ b/tests/gateway/test_matrix_deps_rebind.py @@ -22,46 +22,15 @@ def _fake_mautrix_types(): """Minimal mautrix.types with the 8 names the adapter imports/binds.""" mod = types.ModuleType("mautrix.types") - class EventType: - ROOM_MESSAGE = "m.room.message" - REACTION = "m.reaction" - - class UserID(str): - pass - - class RoomID(str): - pass - - class EventID(str): - pass - - class ContentURI(str): - pass - - class RoomCreatePreset: - PRIVATE = "private_chat" - - class PresenceState: - ONLINE = "online" - - class TrustState: - UNVERIFIED = 0 - - mod.EventType = EventType - mod.UserID = UserID - mod.RoomID = RoomID - mod.EventID = EventID - mod.ContentURI = ContentURI - mod.RoomCreatePreset = RoomCreatePreset - mod.PresenceState = PresenceState - mod.TrustState = TrustState + for name in ("EventType", "UserID", "RoomID", "EventID", "ContentURI", + "RoomCreatePreset", "PresenceState", "TrustState"): + setattr(mod, name, object()) return mod -@pytest.fixture(params=[(), ("asyncpg",)], ids=["installed", "fresh"]) -def fresh_dependency_boundary(monkeypatch, request): - """Installed and fresh dependencies both bind through PM's single operation.""" - monkeypatch.setattr(pm_extras, "missing", lambda extra: request.param) +@pytest.fixture +def fresh_dependency_boundary(monkeypatch): + """Exercise the real importer after PM admits the SDK.""" monkeypatch.setattr(pm_extras, "ensure_import", lambda *a, **kw: None) monkeypatch.delenv("MATRIX_E2EE_MODE", raising=False) monkeypatch.delenv("MATRIX_ENCRYPTION", raising=False) diff --git a/tests/gateway/test_matrix_mention.py b/tests/gateway/test_matrix_mention.py index 54fe03ef30..65c893a780 100644 --- a/tests/gateway/test_matrix_mention.py +++ b/tests/gateway/test_matrix_mention.py @@ -329,58 +329,29 @@ async def test_dm_mention_thread_creates_thread(monkeypatch): assert msg.text == "help me" -# --------------------------------------------------------------------------- -# YAML config bridge -# --------------------------------------------------------------------------- +@pytest.mark.parametrize("existing", [None, "operator"]) +@pytest.mark.parametrize("secondary", [False, True]) +def test_yaml_bridge_respects_scope_and_existing_env(monkeypatch, existing, secondary): + import os + from agent.secret_scope import set_multiplex_active, set_secret_scope, reset_secret_scope + from plugins.platforms.matrix.adapter import _apply_yaml_config - -class TestMatrixConfigBridge: - def test_yaml_bridge_sets_env_vars(self, monkeypatch, tmp_path): - """Matrix YAML config should bridge to env vars.""" - monkeypatch.delenv("MATRIX_REQUIRE_MENTION", raising=False) - monkeypatch.delenv("MATRIX_FREE_RESPONSE_ROOMS", raising=False) - monkeypatch.delenv("MATRIX_AUTO_THREAD", raising=False) - - yaml_content = { - "matrix": { - "require_mention": False, - "free_response_rooms": ["!room1:example.org", "!room2:example.org"], - "auto_thread": False, - } - } - - import os - - import hermes_yaml as yaml - - config_file = tmp_path / "config.yaml" - config_file.write_text(yaml.safe_dump(yaml_content)) - - # Simulate the bridge logic from gateway/config.py - yaml_cfg = yaml.safe_load(config_file.read_text()) - matrix_cfg = yaml_cfg.get("matrix", {}) - if isinstance(matrix_cfg, dict): - if "require_mention" in matrix_cfg and not os.getenv( - "MATRIX_REQUIRE_MENTION" - ): - monkeypatch.setenv( - "MATRIX_REQUIRE_MENTION", str(matrix_cfg["require_mention"]).lower() - ) - frc = matrix_cfg.get("free_response_rooms") - if frc is not None and not os.getenv("MATRIX_FREE_RESPONSE_ROOMS"): - if isinstance(frc, list): - frc = ",".join(str(v) for v in frc) - monkeypatch.setenv("MATRIX_FREE_RESPONSE_ROOMS", str(frc)) - if "auto_thread" in matrix_cfg and not os.getenv("MATRIX_AUTO_THREAD"): - monkeypatch.setenv( - "MATRIX_AUTO_THREAD", str(matrix_cfg["auto_thread"]).lower() - ) - - assert os.getenv("MATRIX_REQUIRE_MENTION") == "false" - assert ( - os.getenv("MATRIX_FREE_RESPONSE_ROOMS") - == "!room1:example.org,!room2:example.org" + expected = {"MATRIX_REQUIRE_MENTION": "false", "MATRIX_AUTO_THREAD": "false", + "MATRIX_FREE_RESPONSE_ROOMS": "!one:example.org,!two:example.org"} + config = {"require_mention": False, "auto_thread": False, + "free_response_rooms": ["!one:example.org", "!two:example.org"]} + for key in expected: + monkeypatch.delenv(key, raising=False) + if existing is not None: + monkeypatch.setenv(key, existing) + token = set_secret_scope({}) if secondary else None + set_multiplex_active(secondary) + try: + assert _apply_yaml_config({"matrix": config}, config) == config + assert {key: os.environ.get(key) for key in expected} == ( + dict.fromkeys(expected, existing) if secondary or existing else expected ) - assert os.getenv("MATRIX_AUTO_THREAD") == "false" - - + finally: + if token is not None: + reset_secret_scope(token) + set_multiplex_active(False) diff --git a/tests/gateway/test_pm_activation.py b/tests/gateway/test_pm_activation.py index 632f02f53b..ca7c56c302 100644 --- a/tests/gateway/test_pm_activation.py +++ b/tests/gateway/test_pm_activation.py @@ -1,112 +1,31 @@ -"""Gateway main() must run the pm startup contract (gateway/run.py). +"""Gateway startup remains fail-open when PM admission itself fails. -The gateway daemon boots via its own entrypoint and never passes through the -CLI dispatch in hermes_cli/main.py — without an explicit call here the -gateway's os.environ PATH would lack the pm store's tool dirs (git/bash/ -ffmpeg/...), so every reactive ``shutil.which`` inside the daemon resolves -system binaries (or nothing) instead of the pinned store ones. - -Behavior contract (mirrors the CLI-dispatch block, hermes_cli/main.py): -- healthy store → ``pm.activate()`` provisions PATH -- out-of-sync store → warning, boot continues (never blocks) -- pm import/lookup failure → debug-logged, boot continues +Healthy/damaged real-store activation belongs to tests/pm/test_startup_activation.py. """ - -from __future__ import annotations - -import os -from unittest.mock import patch +from unittest.mock import AsyncMock import pytest -@pytest.fixture -def gateway_main(monkeypatch, tmp_path): - """Import gateway.run.main with the heavy boot machinery neutralized.""" - # The real main() advertises env vars, registers process identity, runs - # boot bootstrap, and FORCE-EXITS via _exit_after_graceful_shutdown - # (os._exit — wedge-proof by design, #53107) — none of it is what we - # assert on. Neutralize the exit + the async boot; keep the pm block's - # imports real. - import gateway.run as gr +@pytest.mark.parametrize("boundary", ["adopt", "activate"]) +def test_gateway_main_survives_pm_failure(monkeypatch, boundary): + import pm + import gateway.run as gateway - async def _no_gateway(_config=None, **_kwargs): - return True + failed = [] + def broken(): + failed.append(boundary) + raise RuntimeError("PM unavailable") - exited: list[int] = [] - - def _fake_exit(code): - exited.append(code) - - monkeypatch.setattr(gr, "start_gateway", _no_gateway) - monkeypatch.setattr(gr, "_exit_after_graceful_shutdown", _fake_exit) - monkeypatch.setattr( - "hermes_cli.boot_bootstrap.maybe_run_boot_bootstrap", lambda _root: None - ) - - def _main(): - gr.main() - return exited - - return _main - - -def test_gateway_main_activates_pm_store(gateway_main, tmp_path, monkeypatch): - """A healthy store: main() provisions PATH before starting adapters.""" - calls: list[str] = [] - - class _FakePm: - @staticmethod - def adopt(): - calls.append("adopt") - - @staticmethod - def activate(): - calls.append("activate") - return [] # healthy - - import sys - - monkeypatch.setitem(sys.modules, "pm", _FakePm) - with patch("sys.argv", ["gateway"]): - gateway_main() - assert calls == ["adopt", "activate"] - - -def test_gateway_main_warns_but_boots_when_store_out_of_sync( - gateway_main, monkeypatch, caplog -): - """An out-of-sync store surfaces a warning and NEVER blocks the boot.""" - - class _FakePm: - @staticmethod - def adopt(): - pass - - @staticmethod - def activate(): - return ["uv not installed", "ffmpeg outdated"] - - import sys - - monkeypatch.setitem(sys.modules, "pm", _FakePm) - with patch("sys.argv", ["gateway"]): - gateway_main() - assert any( - "install out of sync" in rec.message for rec in caplog.records - ), "the out-of-sync warning must be logged" - - -def test_gateway_main_survives_pm_failure(gateway_main, monkeypatch): - """A broken pm import is debug-logged; the gateway still boots.""" - - class _ExplodingPm: - @staticmethod - def adopt(): - raise RuntimeError("pm exploded") - - import sys - - monkeypatch.setitem(sys.modules, "pm", _ExplodingPm) - with patch("sys.argv", ["gateway"]): - gateway_main() # must not raise + monkeypatch.setattr(pm, "adopt", lambda: None) + monkeypatch.setattr(pm, boundary, broken) + started = AsyncMock(return_value=True) + exited = [] + monkeypatch.setattr(gateway, "start_gateway", started) + monkeypatch.setattr(gateway, "_exit_after_graceful_shutdown", exited.append) + monkeypatch.setattr("hermes_cli.boot_bootstrap.maybe_run_boot_bootstrap", lambda root: None) + monkeypatch.setattr("sys.argv", ["gateway"]) + gateway.main() + started.assert_awaited_once() + assert exited == [0] + assert failed == [boundary] diff --git a/tests/hermes_cli/test_boot_bootstrap.py b/tests/hermes_cli/test_boot_bootstrap.py index 23aaeda439..e83b9ca780 100644 --- a/tests/hermes_cli/test_boot_bootstrap.py +++ b/tests/hermes_cli/test_boot_bootstrap.py @@ -57,10 +57,6 @@ def _head_sha(root): # ── read_git_head ──────────────────────────────────────────────────── -def test_read_git_head_branch_ref(repo): - assert read_git_head(repo) == _head_sha(repo) - - def test_git_selection_uses_pm_public_package_reader(repo, monkeypatch): from types import SimpleNamespace import pm @@ -134,18 +130,6 @@ def test_read_git_head_missing_and_garbage(tmp_path): # ── current_install_identity ───────────────────────────────────────── -def test_identity_prefers_git(repo): - assert current_install_identity(repo) == _head_sha(repo) - - -def test_identity_sealed_stamp(tmp_path): - (tmp_path / "install-stamp.json").write_text( - json.dumps({"commit": "a" * 40, "distribution": "desktop-app", "updateMechanism": "electron-updater"}), - encoding="utf-8", - ) - assert current_install_identity(tmp_path) == "a" * 40 - - def test_identity_broken_tree_is_none(tmp_path): assert current_install_identity(tmp_path) is None (tmp_path / "install-stamp.json").write_text("garbage", encoding="utf-8") @@ -167,21 +151,6 @@ def test_record_paths_key_on_install_root(tmp_path, monkeypatch): assert a.name == b.name # the profile filename is the shared part -def test_home_records_differ_per_profile(tmp_path, monkeypatch): - monkeypatch.setattr(Path, "home", lambda: tmp_path) - base = tmp_path / ".hermes" - profile = base / "profiles" / "coder" - install = tmp_path / "install" - - monkeypatch.setenv("HERMES_HOME", str(base)) - home_default = record_path(install) - - monkeypatch.setenv("HERMES_HOME", str(profile)) - home_profile = record_path(install) - - assert home_default != home_profile # each profile bootstraps its own home - - @pytest.mark.skipif( os.name == "nt", reason="requires symlink privilege on Windows" ) @@ -197,26 +166,11 @@ def test_symlinked_root_canonicalizes(tmp_path, monkeypatch): # ── needs_bootstrap ────────────────────────────────────────────────── -def test_needs_bootstrap_lifecycle(repo, tmp_path, monkeypatch): - monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home")) - sha = _head_sha(repo) - - # No record yet → identity returned. - assert needs_bootstrap(repo) == sha - - _write_record(record_path(repo), sha, {}) - assert needs_bootstrap(repo) is None - - # New commit → mismatch again. - (repo / "f.txt").write_text("2", encoding="utf-8") - _git(["add", "."], repo) - _git(["commit", "-m", "two"], repo) - assert needs_bootstrap(repo) == _head_sha(repo) - - def test_needs_bootstrap_broken_tree_never_fires(tmp_path, monkeypatch): monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home")) assert needs_bootstrap(tmp_path / "nope") is None + assert run_boot_bootstrap(tmp_path / "nope") == {"home": "skipped"} + assert not record_path(tmp_path / "nope").exists() # ── lock protocol ──────────────────────────────────────────────────── @@ -272,52 +226,6 @@ def fake_steps(monkeypatch): return calls -def test_run_boot_bootstrap_runs_then_noops(repo, tmp_path, monkeypatch, fake_steps): - monkeypatch.setattr(Path, "home", lambda: tmp_path) - monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) - - first = run_boot_bootstrap(repo) - assert fake_steps == {"home": 1} - assert first["home"] == {"h": {"ok": True}} - - second = run_boot_bootstrap(repo) - assert fake_steps == {"home": 1} # no re-run - assert second == {"home": "skipped"} - - -def test_each_profile_runs_its_own_home_steps(repo, tmp_path, monkeypatch, fake_steps): - monkeypatch.setattr(Path, "home", lambda: tmp_path) - base = tmp_path / ".hermes" - - monkeypatch.setenv("HERMES_HOME", str(base)) - run_boot_bootstrap(repo) - monkeypatch.setenv("HERMES_HOME", str(base / "profiles" / "coder")) - run_boot_bootstrap(repo) - - # Each home bootstraps itself. - assert fake_steps == {"home": 2} - - -def test_step_failure_still_writes_record(repo, tmp_path, monkeypatch): - monkeypatch.setattr(Path, "home", lambda: tmp_path) - monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) - - from hermes_cli import post_update - - def boom(): - raise RuntimeError("step exploded") - - monkeypatch.setattr(post_update, "BOOT_HOME_STEPS", (("boom", boom),)) - - run_boot_bootstrap(repo) - record = read_last_known(record_path(repo)) - assert record["identity"] == _head_sha(repo) - assert record["results"]["boom"]["ok"] is False - - # A broken step must not retrigger the slow path every boot. - assert needs_bootstrap(repo) is None - - def test_double_check_under_lock(repo, tmp_path, monkeypatch, fake_steps): """A racer that finished between our read and our acquire wins.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) diff --git a/tests/hermes_cli/test_boot_convergence.py b/tests/hermes_cli/test_boot_convergence.py index 1dcb16069a..30d31edfbf 100644 --- a/tests/hermes_cli/test_boot_convergence.py +++ b/tests/hermes_cli/test_boot_convergence.py @@ -152,6 +152,22 @@ print(json.dumps(boot_bootstrap.run_boot_bootstrap(root))) assert len(list(directory.glob("config.yaml.bak-*"))) == 1 with sqlite3.connect(directory / "state.db") as db: assert db.execute("SELECT value FROM retained").fetchall() == [("before",)] + # A changed artifact or Git identity must run the real migration again. + for revision in ('sealed', 'git'): + (home / 'config.yaml').write_text(f"_config_version: {DEFAULT_CONFIG['_config_version'] - 1}\n") + if revision == 'sealed': + (root / 'install-stamp.json').write_text(json.dumps({ + 'commit': 'fedcba987654', 'updateMechanism': 'external'})) + else: + subprocess.run(['git', 'init', '-q', str(root)], check=True) + subprocess.run(['git', '-c', 'user.name=Fixture', '-c', 'user.email=t@example.invalid', + '-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'revision'], + cwd=root, check=True) + changed = subprocess.run([*command, 'go'], env=env, capture_output=True, text=True, timeout=30) + assert changed.returncode == 0, changed.stderr + assert json.loads(changed.stdout.splitlines()[-1])['home']['migrate']['ok'] + import hermes_yaml + assert hermes_yaml.safe_load((home / 'config.yaml').read_text())['_config_version'] == DEFAULT_CONFIG['_config_version'] finally: release.touch() if first.poll() is None: @@ -190,3 +206,6 @@ def test_failed_migration_is_restored_and_not_retried(tmp_path, monkeypatch): assert {p: p.read_bytes() for p in original} == original assert boot_bootstrap.run_boot_bootstrap(root) == {"home": "skipped"} assert calls == [True] + record = boot_bootstrap.read_last_known(boot_bootstrap.record_path(root)) + assert record['identity'] == 'abcdef012345' + assert record['results']['migrate']['ok'] is False diff --git a/tests/hermes_cli/test_boot_wiring.py b/tests/hermes_cli/test_boot_wiring.py index f212687469..f53dc5ecfb 100644 --- a/tests/hermes_cli/test_boot_wiring.py +++ b/tests/hermes_cli/test_boot_wiring.py @@ -68,165 +68,6 @@ def test_cli_main_skips_boot_bootstrap_during_update(hermes_home, boot_probe): assert boot_probe == [], "the update flow owns its own maintenance pass" -def test_boot_bootstrap_reaches_post_update_registry(hermes_home, tmp_path, monkeypatch): - """The real maybe_run_boot_bootstrap runs due steps from ONE registry - (no inline duplicate maintenance in the boot path).""" - import sys - - from hermes_cli import boot_bootstrap, post_update - - ran: list[str] = [] - monkeypatch.setattr( - post_update, - "BOOT_HOME_STEPS", - (("probe_home", lambda: (ran.append("home"), {"ok": True})[1]),), - ) - - root = tmp_path / "install" - root.mkdir() - (root / ".git").mkdir(parents=True) - import subprocess as sp - - head = sp.run( - ["git", "init", "-q", "-b", "main"], cwd=root, capture_output=True - ) - assert head.returncode == 0 - (root / "f.txt").write_text("1", encoding="utf-8") - for args in (["add", "."], ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "one"]): - sp.run(["git", *args], cwd=root, capture_output=True, check=True) - - boot_bootstrap.maybe_run_boot_bootstrap(root) - - assert sorted(ran) == ["home"] - # second boot: record-gated no-op, no doubled maintenance - boot_bootstrap.maybe_run_boot_bootstrap(root) - assert sorted(ran) == ["home"] - - # ── gateway entry point reaches the registry ───────────────────────── # (the gr.main() contract is tests/gateway/test_pm_activation.py; here we # prove the wiring call exists on the real function's module) - - -# ── the cadence tick on the existing housekeeping loop ─────────────── - - -def test_housekeeping_chore_delegates_to_cadence(hermes_home, monkeypatch): - import gateway.run as gr - import hermes_cli.plugins_cadence as cad - - called: list = [] - monkeypatch.setattr( - cad, "maybe_run_gateway_check", lambda **kw: called.append(kw) - ) - - gr._housekeeping_chore("Plugin update check", gr._housekeeping_plugin_update_check) - - assert len(called) == 1 - - -# ── the production cadence wrapper ─────────────────────────────────── - - -class _Result: - def __init__(self, name, klass="git", update_available=None, needs_fixing=None): - self.name = name - self.klass = klass - self.update_available = update_available - self.needs_fixing = needs_fixing - - -def _write_fresh_marker(): - import hermes_constants - - d = hermes_constants.get_hermes_home() / "plugin-update-checks" - d.mkdir(parents=True, exist_ok=True) - marker = d / "last-run" - marker.write_text(str(int(time.time())), encoding="utf-8") - - -def test_gateway_check_not_due_makes_no_request(hermes_home, monkeypatch): - import hermes_cli.plugins_cadence as cad - - _write_fresh_marker() - - def _explode(*_a, **_kw): - raise AssertionError("network must not be touched when not due") - - assert ( - cad.maybe_run_gateway_check( - run_checks_fn=_explode, plugins_dir=hermes_home / "plugins" - ) - is None - ) - - -def test_gateway_check_disabled_makes_no_request(hermes_home, monkeypatch): - import hermes_cli.plugins_cadence as cad - - monkeypatch.setattr( - cad, "check_interval_hours", lambda config_get=None: 0.0 - ) - - def _explode(*_a, **_kw): - raise AssertionError("disabled cadence must not request") - - assert ( - cad.maybe_run_gateway_check(run_checks_fn=_explode, plugins_dir=None) is None - ) - - -def test_gateway_check_due_runs_and_defaults_apply_seam(hermes_home, monkeypatch): - import hermes_cli.plugins_cadence as cad - import hermes_cli.plugins_cmd as plugins_cmd - - results = [_Result("plug", update_available=True)] - seen: dict = {} - - def _checks(plugins_dir): - seen["dir"] = plugins_dir - return results - - applied: list[str] = [] - monkeypatch.setattr( - plugins_cmd, "cmd_update", lambda name, **kw: applied.append(name), raising=True - ) - monkeypatch.setattr(cad, "auto_apply_enabled", lambda config_get=None: True) - - out = cad.maybe_run_gateway_check( - run_checks_fn=_checks, plugins_dir=hermes_home / "plugins", now=time.time() - ) - - assert out == results - assert applied == ["plug"], "git-class updates apply through the manual update flow" - # the marker was stamped - import hermes_constants - - marker = hermes_constants.get_hermes_home() / "plugin-update-checks" / "last-run" - assert marker.is_file() - - -def test_gateway_check_network_error_never_applies(hermes_home, monkeypatch): - import hermes_cli.plugins_cadence as cad - import hermes_cli.plugins_cmd as plugins_cmd - - def _checks(_plugins_dir): - raise OSError("network unreachable") - - applied: list[str] = [] - monkeypatch.setattr( - plugins_cmd, "cmd_update", lambda name, **kw: applied.append(name), raising=True - ) - monkeypatch.setattr(cad, "auto_apply_enabled", lambda config_get=None: True) - - out = cad.maybe_run_gateway_check( - run_checks_fn=_checks, plugins_dir=hermes_home / "plugins", now=time.time() - ) - - assert out == [] - assert applied == [], "a failed check must never trigger an apply" - # and the failed tick is stamped so it does not hammer the network - import hermes_constants - - marker = hermes_constants.get_hermes_home() / "plugin-update-checks" / "last-run" - assert marker.is_file() diff --git a/tests/hermes_cli/test_bundled_desktop_launch.py b/tests/hermes_cli/test_bundled_desktop_launch.py index 0e63cc923a..dcc23873f2 100644 --- a/tests/hermes_cli/test_bundled_desktop_launch.py +++ b/tests/hermes_cli/test_bundled_desktop_launch.py @@ -100,6 +100,8 @@ def _host_bundle(tmp_path: Path) -> tuple[Path, Path]: if sys.platform == "win32": repo = _windows_bundle(tmp_path) return repo, tmp_path / "Hermes" / "Hermes.exe" + if sys.platform == "darwin": + return _macos_bundle(tmp_path), tmp_path / "Hermes.app/Contents/MacOS/Hermes" repo = _linux_bundle(tmp_path) return repo, tmp_path / "linux-unpacked" / "Hermes" @@ -177,7 +179,7 @@ class TestShapePredicate: class TestLaunchDetached: - def test_the_child_outlives_this_process_and_owns_no_stdio(self): + def test_detach_flags_and_unowned_stdio_are_forwarded(self): seen = {} def fake_popen(argv, **kwargs): @@ -198,7 +200,7 @@ class TestLaunchDetached: detach_key = "creationflags" if sys.platform == "win32" else "start_new_session" assert seen["kwargs"][detach_key] - def test_a_real_child_survives_and_is_reachable(self, tmp_path): + def test_a_real_detached_child_runs(self, tmp_path): """The one E2E rung: spawn a real process and prove it ran.""" marker = tmp_path / "ran.txt" pid = launch_detached( @@ -214,6 +216,7 @@ class TestLaunchDetached: assert marker.read_text() == "yes" +@pytest.mark.platforms("windows", "linux", "macos") class TestCmdGuiOnABundle: """The behavior the checkout ladder got wrong: never build in a bundle.""" diff --git a/tests/hermes_cli/test_cadence_failure_receipt.py b/tests/hermes_cli/test_cadence_failure_receipt.py deleted file mode 100644 index b11371fb2d..0000000000 --- a/tests/hermes_cli/test_cadence_failure_receipt.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Cadence failures retain the same warning shown to the operator.""" -from unittest.mock import Mock - -from hermes_cli.plugins_cadence import run_scheduled_check -from pm import receipt - - -def test_failed_check_records_warning_and_nonzero_exit(tmp_path, monkeypatch): - monkeypatch.setenv("HERMES_HOME", str(tmp_path)) - log = Mock() - - def fail(_): - raise OSError("offline") - - run_scheduled_check(run_checks_fn=fail, plugins_dir=tmp_path / "plugins", log=log) - saved = receipt.latest() - assert saved["outcome"] == "failed" - assert saved["exit_code"] != 0 - assert saved["warnings"][0]["message"] == log.warning.call_args_list[0].args[0] diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py index 9be93fcc4e..8b14ab2213 100644 --- a/tests/hermes_cli/test_cmd_update.py +++ b/tests/hermes_cli/test_cmd_update.py @@ -18,8 +18,6 @@ def _isolate_venv_holders(monkeypatch): monkeypatch.setattr("hermes_cli.update_cmd_windows._detect_venv_python_processes", lambda: []) - - def _make_run_side_effect(branch="main", verify_ok=True, commit_count="0"): """Build a side_effect function for subprocess.run that simulates git commands.""" @@ -59,127 +57,6 @@ class TestCmdUpdateBranchFallback: """cmd_update falls back to main when current branch has no remote counterpart.""" - - - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_update_on_fork_checks_upstream_when_origin_up_to_date( - self, mock_run, _mock_which, mock_args, capsys - ): - """Regression for issue #26172: forks whose local HEAD already matches - origin/main must still consult upstream/main before printing - "Already up to date!" — otherwise a fork that's caught up to its own - origin but behind NousResearch/hermes-agent silently misses updates. - """ - from hermes_cli import main as hm - from hermes_cli import update_cmd - - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="0" - ) - - with patch.object( - hm, - "_get_origin_url", - return_value="https://github.com/example/hermes-agent.git", - ), patch.object(hm, "_sync_with_upstream_if_needed") as sync_mock, patch.object( - update_cmd, "_check_and_apply_config_migration" - ): - cmd_update(mock_args) - - expected_git_cmd = ( - ["git", "-c", "windows.appendAtomically=false"] if hm._is_windows() else ["git"] - ) - sync_mock.assert_called_once_with( - expected_git_cmd, - # Resolved live: the module autouse fixture pins PROJECT_ROOT to - # tmp_path, so the imported constant would be stale here. - hm.PROJECT_ROOT, - assume_yes=False, - input_fn=None, - ) - captured = capsys.readouterr() - assert "Already up to date!" in captured.out - - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_yes_on_fork_without_upstream_does_not_claim_up_to_date( - self, mock_run, _mock_which, capsys - ): - """#97052 review: genuine fork, no upstream remote, HEAD == origin/main, - --yes. The prompt is skipped without mutating remotes, and because the - official repo was never consulted the completion line must not claim - plain "Already up to date!".""" - from hermes_cli import main as hm - from hermes_cli import update_cmd - - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="0" - ) - - with patch.object( - hm, - "_get_origin_url", - return_value="https://github.com/example/hermes-agent.git", - ), patch.object( - update_cmd, "_has_upstream_remote", return_value=False - ), patch.object( - update_cmd, "_should_skip_upstream_prompt", return_value=False - ), patch.object( - update_cmd, "_add_upstream_remote" - ) as add_remote, patch.object( - update_cmd, "_mark_skip_upstream_prompt" - ) as mark_skip, patch("builtins.input") as stdin_input: - cmd_update(SimpleNamespace(yes=True)) - - stdin_input.assert_not_called() - add_remote.assert_not_called() - mark_skip.assert_not_called() - captured = capsys.readouterr() - assert "Skipping upstream setup (non-interactive run)." in captured.out - assert "official repo not checked" in captured.out - assert "Already up to date!" not in captured.out - - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_current_checkout_runtime_verification_failure_is_durable( - self, - mock_run, - _mock_which, - mock_args, - ): - """Prepared products must still pass runtime and durable outcome checks.""" - from hermes_cli import main as hm - from hermes_cli import update_cmd - - mock_args.gateway = True - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="0" - ) - - with patch.object( - hm, - "_get_origin_url", - return_value="https://github.com/example/hermes-agent.git", - ), patch.object(hm, "_sync_with_upstream_if_needed"), patch.object( - update_cmd, - "_post_update_sqlite_runtime_status", - return_value=(False, SimpleNamespace(sqlite_version_string="3.46.1")), - ) as runtime_check, patch.object( - update_cmd, "_write_gateway_update_exit_code" - ) as write_gateway_exit, patch( - "hermes_cli.update_receipt.finalize_update_receipt" - ) as finalize_receipt, patch( - "hermes_cli.update_receipt.finalize_pending_update_receipt" - ): - with pytest.raises(SystemExit) as exit_info: - cmd_update(mock_args) - - assert exit_info.value.code == 1 - runtime_check.assert_called_once_with() - write_gateway_exit.assert_called_once_with(False) - assert finalize_receipt.call_args.args[0] == "partial" - @patch("shutil.which", return_value=None) @patch("subprocess.run") def test_fork_upstream_sync_that_moves_head_runs_post_update_steps( @@ -226,572 +103,6 @@ class TestCmdUpdateBranchFallback: captured = capsys.readouterr() assert "Already up to date!" not in captured.out - def test_update_non_interactive_runs_safe_config_migrations(self, mock_args, capsys): - """Dashboard/web updates apply non-interactive migrations before restart.""" - with patch("shutil.which", return_value=None), patch( - "subprocess.run" - ) as mock_run, patch("builtins.input") as mock_input, patch( - "hermes_cli.config.get_missing_env_vars", return_value=["MISSING_KEY"] - ), patch( - "hermes_cli.config.get_missing_config_fields", - return_value=[{"key": "new.option", "default": True}], - ), patch( - "hermes_cli.update_cmd._reload_config_modules" - ), patch( - "hermes_cli.config.check_config_version", return_value=(1, 2) - ), patch( - "hermes_cli.config.migrate_config", - return_value={"env_added": [], "config_added": ["new.option"]}, - ) as migrate_config, patch("hermes_cli.main.sys") as mock_sys: - mock_sys.stdin.isatty.return_value = False - mock_sys.stdout.isatty.return_value = False - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1" - ) - - cmd_update(mock_args) - - mock_input.assert_not_called() - migrate_config.assert_called_once_with(interactive=False, quiet=False) - captured = capsys.readouterr() - assert "applying safe config migrations" in captured.out - assert "API keys require manual entry" in captured.out - - -class TestCmdUpdateMigrationPrompt: - """The config-migration prompt names what changed and skips the prompt - entirely when only the config format version moved. - - Regression guard for the contentless-prompt report (ScottFive / Tt2021): - previously the prompt printed only counts ("1 new config option") and - asked "configure them now?" even for pure version bumps, where saying - yes looked like a no-op. - """ - - def test_version_bump_only_applies_silently_without_prompt( - self, mock_args, capsys - ): - """Only the version moved → apply non-interactively, never prompt.""" - with patch("shutil.which", return_value=None), patch( - "subprocess.run" - ) as mock_run, patch("builtins.input") as mock_input, patch( - "hermes_cli.config.get_missing_env_vars", return_value=[] - ), patch( - "hermes_cli.config.get_missing_config_fields", return_value=[] - ), patch( - "hermes_cli.update_cmd._reload_config_modules" - ), patch( - "hermes_cli.config.check_config_version", return_value=(5, 24) - ), patch( - "hermes_cli.config.migrate_config", - return_value={"env_added": [], "config_added": [], "warnings": []}, - ) as mock_migrate: - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1" - ) - - cmd_update(mock_args) - - mock_input.assert_not_called() - mock_migrate.assert_called_once_with(interactive=False, quiet=True) - out = capsys.readouterr().out - assert "Updating config format (v5 → v24)" in out - assert "no new settings to configure" in out - # The misleading question must NOT appear for a pure version bump. - assert "configure them now" not in out.lower() - - def test_version_bump_only_surfaces_migration_resets( - self, mock_args, capsys - ): - """A quiet version-bump migration that RESETS a user setting must say so. - - Regression for #86656: the v33→v34 personality reset ran with - quiet=True and its results dict was discarded, so the update printed - "no new settings to configure" while silently wiping - display.personality. Migration-step mutations (config_added) and - warnings must be re-surfaced even in the silent branch. - """ - with patch("shutil.which", return_value=None), patch( - "subprocess.run" - ) as mock_run, patch("builtins.input") as mock_input, patch( - "hermes_cli.config.get_missing_env_vars", return_value=[] - ), patch( - "hermes_cli.config.get_missing_config_fields", return_value=[] - ), patch( - "hermes_cli.update_cmd._reload_config_modules" - ), patch( - "hermes_cli.config.check_config_version", return_value=(33, 34) - ), patch( - "hermes_cli.config.migrate_config", - return_value={ - "env_added": [], - "config_added": ["display.personality=none (one-time reset)"], - "warnings": ["Disabled suspicious MCP server 'evil'"], - }, - ): - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1" - ) - - cmd_update(mock_args) - - mock_input.assert_not_called() - out = capsys.readouterr().out - assert "Updating config format (v33 → v34)" in out - assert "no new settings to configure" in out - # The migration's mutation note and warning must NOT be swallowed. - assert "display.personality=none (one-time reset)" in out - assert "Disabled suspicious MCP server 'evil'" in out - - def test_new_options_are_listed_by_name_before_prompt( - self, mock_args, capsys - ): - """New env/config keys are printed by name so the user can decide.""" - env_items = [ - {"name": "FOO_API_KEY", "description": "Foo service API key"}, - ] - cfg_items = [ - {"key": "display.new_widget", "description": "New config option: display.new_widget"}, - ] - with patch("shutil.which", return_value=None), patch( - "subprocess.run" - ) as mock_run, patch("builtins.input", return_value="n"), patch( - "hermes_cli.config.get_missing_env_vars", return_value=env_items - ), patch( - "hermes_cli.config.get_missing_config_fields", return_value=cfg_items - ), patch( - "hermes_cli.update_cmd._reload_config_modules" - ), patch( - "hermes_cli.config.check_config_version", return_value=(1, 24) - ), patch( - "hermes_cli.config.migrate_config", - return_value={"env_added": [], "config_added": [], "warnings": []}, - ), patch("hermes_cli.main.sys") as mock_sys: - mock_sys.stdin.isatty.return_value = True - mock_sys.stdout.isatty.return_value = True - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1" - ) - - cmd_update(mock_args) - - out = capsys.readouterr().out - # Names, not just counts. - assert "FOO_API_KEY" in out - assert "Foo service API key" in out - assert "display.new_widget" in out - - - - -class TestCmdUpdateProfileSkillSync: - """cmd_update syncs bundled skills to all profiles, including the active one. - - Regression guard for #16176: previously the active profile was excluded - from the seed_profile_skills loop, leaving it on stale skill content. - """ - - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_active_profile_included_in_skill_sync( - self, mock_run, _mock_which, mock_args, capsys - ): - from pathlib import Path - - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1" - ) - - default_p = SimpleNamespace(name="default", path=Path("/fake/.hermes")) - active_p = SimpleNamespace(name="bit", path=Path("/fake/.hermes/profiles/bit")) - other_p = SimpleNamespace(name="work", path=Path("/fake/.hermes/profiles/work")) - all_profiles = [default_p, active_p, other_p] - - synced_paths = [] - - def fake_seed(path, quiet=False): - synced_paths.append(path) - return {"copied": [], "updated": [], "user_modified": []} - - empty_sync = {"copied": [], "updated": [], "user_modified": [], "cleaned": []} - - with ( - patch("hermes_cli.profiles.list_profiles", return_value=all_profiles), - patch("hermes_cli.profiles.seed_profile_skills", side_effect=fake_seed), - patch("tools.skills_sync.sync_skills", return_value=empty_sync), - ): - cmd_update(mock_args) - - assert active_p.path in synced_paths, ( - f"Active profile 'bit' must be included in skill sync; got: {synced_paths}" - ) - assert set(synced_paths) == {p.path for p in all_profiles}, ( - f"All profiles must be synced; got: {synced_paths}" - ) - - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_single_profile_default_is_synced( - self, mock_run, _mock_which, mock_args, capsys - ): - from pathlib import Path - - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1" - ) - - default_p = SimpleNamespace(name="default", path=Path("/fake/.hermes")) - synced_paths = [] - - def fake_seed(path, quiet=False): - synced_paths.append(path) - return {"copied": [], "updated": [], "user_modified": []} - - empty_sync = {"copied": [], "updated": [], "user_modified": [], "cleaned": []} - - with ( - patch("hermes_cli.profiles.list_profiles", return_value=[default_p]), - patch("hermes_cli.profiles.seed_profile_skills", side_effect=fake_seed), - patch("tools.skills_sync.sync_skills", return_value=empty_sync), - ): - cmd_update(mock_args) - - assert default_p.path in synced_paths - - -class TestCmdUpdateBranchFlag: - """``hermes update --branch `` targets the requested branch. - - The CLI default stays 'main'; --branch lets callers pick a different - target without monkey-patching the implementation. - """ - - def _branch_side_effect(self, current_branch, target_branch, *, checkout_fails=False, track_fails=False, commit_count="0"): - """Mock side-effect that knows about checkout/track behavior. - - - ``current_branch`` what ``git rev-parse --abbrev-ref HEAD`` returns - - ``target_branch`` passed via --branch; what we expect the code to switch to - - ``checkout_fails`` if True, ``git checkout `` returns non-zero - (simulates branch absent locally; code should retry with -B) - - ``track_fails`` if True, ``git checkout -B origin/`` ALSO fails - (simulates branch absent on origin too) - - ``commit_count`` rev-list count returned (0 = up-to-date, >0 = behind) - """ - - def side_effect(cmd, **kwargs): - joined = " ".join(str(c) for c in cmd) - - if "rev-parse" in joined and "--abbrev-ref" in joined: - return subprocess.CompletedProcess(cmd, 0, stdout=f"{current_branch}\n", stderr="") - - if "checkout" in joined and "-B" in joined: - rc = 128 if track_fails else 0 - err = f"fatal: '{target_branch}' did not match any file(s) known to git\n" if track_fails else "" - return subprocess.CompletedProcess(cmd, rc, stdout="", stderr=err) - - if "checkout" in joined and "-B" not in joined and "rev-parse" not in joined: - rc = 128 if checkout_fails else 0 - err = f"error: pathspec '{target_branch}' did not match\n" if checkout_fails else "" - return subprocess.CompletedProcess(cmd, rc, stdout="", stderr=err) - - if "rev-list" in joined: - return subprocess.CompletedProcess(cmd, 0, stdout=f"{commit_count}\n", stderr="") - - return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="") - - return side_effect - - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_branch_flag_pulls_against_named_branch(self, mock_run, _mock_which, capsys): - """--branch bb/gui makes rev-list and pull target origin/bb/gui.""" - mock_run.side_effect = self._branch_side_effect( - current_branch="bb/gui", target_branch="bb/gui", commit_count="3" - ) - args = SimpleNamespace(branch="bb/gui") - - cmd_update(args) - - commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list] - - # rev-list must compare against origin/bb/gui, not origin/main - rev_list_cmds = [c for c in commands if "rev-list" in c] - assert any("origin/bb/gui" in c for c in rev_list_cmds), rev_list_cmds - assert not any("origin/main" in c for c in rev_list_cmds), rev_list_cmds - - # the ff-only merge must target origin/bb/gui - merge_cmds = [c for c in commands if "merge --ff-only" in c] - assert any("origin/bb/gui" in c and "origin/main" not in c for c in merge_cmds), merge_cmds - - - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_branch_flag_fails_when_branch_missing_everywhere(self, mock_run, _mock_which, capsys): - """If branch doesn't exist locally OR on origin, exit non-zero with clear error.""" - mock_run.side_effect = self._branch_side_effect( - current_branch="main", - target_branch="nonexistent", - checkout_fails=True, - track_fails=True, - commit_count="0", - ) - args = SimpleNamespace(branch="nonexistent") - - with pytest.raises(SystemExit) as exc_info: - cmd_update(args) - assert exc_info.value.code == 1 - - out = capsys.readouterr().out - assert "does not exist locally or on origin" in out - assert "nonexistent" in out - - -class TestCmdUpdateCheckBranchFlag: - """``hermes update --check --branch `` honors the branch override. - - The check path used to call ``git rev-list HEAD..origin/ --count`` - with ``check=True``. When the branch didn't exist on origin, the fetch - silently succeeded (no refspec) but rev-list exited 128 and a raw - ``CalledProcessError`` propagated to the user. These tests pin the - friendlier behavior: detect-the-missing-ref before rev-list, exit 1 - with a clear message. - """ - - def _check_side_effect( - self, - target_branch: str, - *, - verify_ok: bool = True, - commit_count: str = "0", - upstream_fetch_ok: bool = True, - ): - """Mock side-effect for the _cmd_update_check git pipeline. - - - ``target_branch`` what we expect compare ref to point at - - ``verify_ok`` if False, ``git rev-parse --verify --quiet - origin/`` fails (branch missing - on origin) - - ``commit_count`` rev-list count (0 = up-to-date) - - ``upstream_fetch_ok`` if False, ``git fetch upstream`` fails - (forces fallback to origin on branch==main) - """ - - def side_effect(cmd, **kwargs): - joined = " ".join(str(c) for c in cmd) - - if "fetch" in joined and "upstream" in joined: - rc = 0 if upstream_fetch_ok else 128 - err = "" if upstream_fetch_ok else "fatal: 'upstream' does not appear to be a git repository\n" - return subprocess.CompletedProcess(cmd, rc, stdout="", stderr=err) - - if "fetch" in joined and "origin" in joined: - return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="") - - if "rev-parse" in joined and "--verify" in joined: - rc = 0 if verify_ok else 1 - return subprocess.CompletedProcess(cmd, rc, stdout="", stderr="") - - if "rev-list" in joined: - return subprocess.CompletedProcess(cmd, 0, stdout=f"{commit_count}\n", stderr="") - - return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="") - - return side_effect - - @patch("hermes_cli.config.detect_install_method", return_value="git") - @patch("subprocess.run") - def test_check_branch_compares_against_named_origin_branch( - self, mock_run, _mock_method, capsys - ): - """--check --branch bb/gui compares against origin/bb/gui, never origin/main.""" - mock_run.side_effect = self._check_side_effect( - target_branch="bb/gui", verify_ok=True, commit_count="2" - ) - args = SimpleNamespace(check=True, branch="bb/gui") - - cmd_update(args) - - commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list] - # Non-main branch skips upstream probe entirely. - assert not any("fetch" in c and "upstream" in c for c in commands), commands - # Verify and rev-list both target origin/bb/gui. - verify_cmds = [c for c in commands if "rev-parse" in c and "--verify" in c] - assert any("origin/bb/gui" in c for c in verify_cmds), verify_cmds - rev_list_cmds = [c for c in commands if "rev-list" in c] - assert any("origin/bb/gui" in c for c in rev_list_cmds), rev_list_cmds - assert not any("origin/main" in c for c in rev_list_cmds), rev_list_cmds - - @patch("hermes_cli.config.detect_install_method", return_value="git") - @patch("subprocess.run") - def test_check_branch_missing_on_origin_exits_cleanly( - self, mock_run, _mock_method, capsys - ): - """If origin/ doesn't exist, surface a friendly error and exit 1. - - Pre-fix this case raised CalledProcessError from rev-list's check=True - and dumped a Python traceback to stdout. - """ - mock_run.side_effect = self._check_side_effect( - target_branch="ghost", verify_ok=False - ) - args = SimpleNamespace(check=True, branch="ghost") - - with pytest.raises(SystemExit) as exc_info: - cmd_update(args) - assert exc_info.value.code == 1 - - out = capsys.readouterr().out - # No raw Python traceback. - assert "Traceback" not in out - assert "CalledProcessError" not in out - # Friendly message naming the branch. - assert "ghost" in out - assert "not found" in out - - # rev-list must never have been called once verify failed. - commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list] - assert not any("rev-list" in c for c in commands), commands - - @patch("hermes_cli.config.detect_install_method", return_value="git") - @patch("subprocess.run") - def test_check_default_main_still_prefers_upstream( - self, mock_run, _mock_method, capsys - ): - """No --branch (or --branch=None) preserves the upstream-then-origin probe.""" - mock_run.side_effect = self._check_side_effect( - target_branch="main", verify_ok=True, commit_count="0" - ) - args = SimpleNamespace(check=True, branch=None) - - cmd_update(args) - - commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list] - # Should have tried upstream first. - assert any("fetch" in c and "upstream" in c for c in commands), commands - # Compare ref is upstream/main (upstream fetch succeeded). - rev_list_cmds = [c for c in commands if "rev-list" in c] - assert any("upstream/main" in c for c in rev_list_cmds), rev_list_cmds - - -class TestCmdUpdateZipBranchRefusal: - """``hermes update --branch=`` must refuse on the ZIP fallback path. - - The ZIP fallback hard-codes a GitHub archive URL for main.zip; honoring - --branch arbitrarily would require remote-branch existence checks the - fallback can't easily do. Refusing is the right move — silently lying - about which branch got installed is the bug --branch was meant to prevent. - """ - - def test_zip_fallback_refuses_non_main_branch(self, capsys): - from hermes_cli.update_cmd_zip import _update_via_zip - - args = SimpleNamespace(branch="bb/gui") - with pytest.raises(SystemExit) as exc_info: - _update_via_zip(args, completion_request={}) - assert exc_info.value.code == 1 - - out = capsys.readouterr().out - assert "bb/gui" in out - assert "not supported" in out - # No actual download attempted. - assert "Downloading latest version" not in out - - -class TestZipDesktopPreservation: - def test_git_failure_zip_fallback_preserves_desktop(self, tmp_path, monkeypatch): - """The Windows ZIP fallback keeps Desktop intact when replacing ``apps/``. - - The built app survives the source swap and preparation retains the - pre-update desktop selection (#70337/#87331). - """ - import zipfile - from pathlib import Path - - from hermes_cli import main as hm - from hermes_cli import update_cmd - from hermes_cli import update_cmd_maint, update_cmd_zip - - project_root = tmp_path / "hermes-agent" - (project_root / ".git").mkdir(parents=True) - desktop_dir = project_root / "apps" / "desktop" - packaged_exe = desktop_dir / "release" / "win-unpacked" / "Hermes.exe" - packaged_exe.parent.mkdir(parents=True) - packaged_exe.write_bytes(b"desktop") - - def write_source_zip(_url, destination): - with zipfile.ZipFile(destination, "w") as archive: - archive.writestr("hermes-agent-main/apps/desktop/package.json", "{}") - - def fail_git_fetch(command, **_kwargs): - if "fetch" in command: - raise subprocess.CalledProcessError(1, command) - return subprocess.CompletedProcess(command, 0, stdout="", stderr="") - - preparations = [] - - def prepare_checkout(request): - preparations.append((Path(request["source"]), request["desktop"], packaged_exe.read_bytes())) - - monkeypatch.setattr(hm, "PROJECT_ROOT", project_root) - monkeypatch.setattr(hm, "_is_windows", lambda: True) - monkeypatch.setattr(hm, "_run_pre_update_backup", lambda _args: None) - monkeypatch.setattr(hm, "_pause_windows_gateways_for_update", lambda: None) - monkeypatch.setattr(hm, "_get_origin_url", lambda *_args: "") - monkeypatch.setattr( - hm, - "_desktop_packaged_executable", - lambda _desktop_dir: packaged_exe if packaged_exe.exists() else None, - ) - monkeypatch.setattr(hm, "_desktop_dist_exists", lambda _desktop_dir: False) - monkeypatch.setattr(update_cmd, "_complete_source_update", prepare_checkout) - monkeypatch.setattr(hm, "_clear_bytecode_cache", lambda *_args: 0) - monkeypatch.setattr(hm, "_record_bytecode_fingerprint", lambda: None) - monkeypatch.setattr(hm, "_refresh_bootstrap_cache_scripts", lambda _branch: None) - - monkeypatch.setattr(update_cmd, "_discard_lockfile_churn", lambda *_args: None) - monkeypatch.setattr(update_cmd, "_normalize_managed_eol", lambda *_args: None) - monkeypatch.setattr( - update_cmd, - "_validate_critical_modules_import", - lambda *_args: (True, None, None), - ) - - monkeypatch.setattr(update_cmd, "_print_curator_first_run_notice", lambda: None) - monkeypatch.setattr(update_cmd, "_print_curator_recent_run_notice", lambda: None) - monkeypatch.setattr("hermes_cli.update_cmd_maint._refresh_dashboard_after_update", lambda **kwargs: None) - monkeypatch.setattr(update_cmd, "get_hermes_home", lambda: tmp_path / "hermes-home") - - with ( - patch("hermes_cli.config.load_config", return_value={}), - # This test legitimately exercises the real ZIP fallback; undo the - # module autouse fixture's fail-fast tripwire for exactly this run. - patch( - "hermes_cli.update_cmd._update_via_zip", - update_cmd_zip._update_via_zip, - ), - patch("subprocess.run", side_effect=fail_git_fetch), - patch("urllib.request.urlretrieve", side_effect=write_source_zip), - patch( - "tools.skills_sync.sync_skills", - return_value={ - "copied": [], - "updated": [], - "user_modified": [], - "cleaned": [], - "relocated": [], - }, - ), - patch("hermes_cli.model_catalog.seed_cache_from_checkout", return_value=False), - ): - update_cmd._cmd_update_impl( - SimpleNamespace(yes=True, force=True, force_venv=True, branch=None), - gateway_mode=False, - ) - - assert preparations == [(project_root, True, b"desktop")] - assert packaged_exe.exists() - assert packaged_exe.read_bytes() == b"desktop" - class TestGitTrampolineSelfHeal: """Proactive Git-for-Windows trampoline self-heal (#87876). diff --git a/tests/hermes_cli/test_data_uninstall.py b/tests/hermes_cli/test_data_uninstall.py index fc0edcb8e6..bc4920cf00 100644 --- a/tests/hermes_cli/test_data_uninstall.py +++ b/tests/hermes_cli/test_data_uninstall.py @@ -24,7 +24,8 @@ def layout(tmp_path, monkeypatch): for path in witnesses: path.parent.mkdir(parents=True, exist_ok=True) path.write_text("keep", encoding="utf-8") - data = [home / "config.yaml", home / "sessions" / "session.json", home / "workspace" / "notes.txt"] + data = [home / "config.yaml", home / "sessions" / "session.json", home / "workspace" / "notes.txt", + home / ".env", home / "logs" / "file"] for path in data: path.parent.mkdir(parents=True, exist_ok=True) path.write_text("{}" if path.suffix in {".yaml", ".json"} else "user data", encoding="utf-8") diff --git a/tests/hermes_cli/test_doctor.py b/tests/hermes_cli/test_doctor.py index ba74f5512f..bf25c1407b 100644 --- a/tests/hermes_cli/test_doctor.py +++ b/tests/hermes_cli/test_doctor.py @@ -318,8 +318,6 @@ class TestDoctorToolAvailabilityOverrides: assert unavailable == [kanban_entry] - - class TestHonchoDoctorConfigDetection: def test_reports_configured_when_enabled_with_api_key(self, monkeypatch): fake_config = SimpleNamespace(enabled=True, api_key="***") @@ -332,12 +330,6 @@ class TestHonchoDoctorConfigDetection: assert doctor_state._honcho_is_configured_for_doctor() - - - - - - def test_doctor_reports_vercel_backend_diagnostics(monkeypatch, tmp_path): monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox") monkeypatch.setenv("TERMINAL_VERCEL_RUNTIME", "python3.13") @@ -766,8 +758,6 @@ def test_run_doctor_accepts_vendor_slugs_for_named_custom_provider(monkeypatch, assert "Either set model.provider to 'openrouter', or drop the vendor prefix." not in out - - def test_run_doctor_accepts_kimi_coding_cn_provider(monkeypatch, tmp_path): home = tmp_path / ".hermes" home.mkdir(parents=True, exist_ok=True) @@ -1496,15 +1486,12 @@ class TestDoctorStaleMaxIterationsDrift: assert "shadows" not in out - - class TestDoctorDeprecatedConfigAndEnv: """Doctor must surface deprecated/legacy config keys and env vars with modern replacements as non-failing warnings — without auto-migrating. """ - def test_collect_deprecated_env_vars_ignores_empty(self): assert doctor_config.collect_deprecated_env_vars({"TERMINAL_CWD": " "}) == [] assert doctor_config.collect_deprecated_env_vars({}) == [] @@ -1558,8 +1545,6 @@ class TestDoctorDeprecatedConfigAndEnv: return buf.getvalue(), hermes_home - - def test_report_does_not_count_as_blocking_issue(self, monkeypatch, tmp_path, capsys): """report_deprecated_config_and_env is warn-only — no issues list mutation.""" findings = doctor_config.report_deprecated_config_and_env( @@ -1740,17 +1725,6 @@ class TestStagedRuntimeVenv: # --- _staged_venv_dir: pm authority + provisioned-venv marker --- - def test_staged_venv_dir_returns_provisioned_venv(self, tmp_path, monkeypatch): - import pm.packages as pm_packages - - venv = tmp_path / "venv" - venv.mkdir() - (venv / "pyvenv.cfg").write_text("home = /usr\n", encoding="utf-8") - self._stub_venv(monkeypatch, venv) - - assert doctor_platform._staged_venv_dir() == venv - # Sanity: the stub really replaced pm's own Venv (no real-repo read). - assert pm_packages.Venv is not None def test_resolved_path_without_venv_marker_is_not_staged(self, tmp_path, monkeypatch): empty = tmp_path / "venv" @@ -1770,45 +1744,6 @@ class TestStagedRuntimeVenv: # --- the check's staged-vs-active rows --- - def test_staged_but_not_active_reports_staged_dependencies(self, monkeypatch, capsys): - monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: Path("/payload/venv")) - monkeypatch.setattr(doctor_platform.sys, "prefix", "/usr") - monkeypatch.setattr(doctor_platform.sys, "base_prefix", "/usr") - - doctor_platform._check_python_environment(False) - - out = capsys.readouterr().out - assert "Runtime venv staged" in out - assert "runs outside it" in out - assert "Not in virtual environment" not in out # dependencies exist; no false alarm - - def test_unrelated_active_venv_is_not_claimed_as_the_staged_one(self, monkeypatch, capsys): - """A process running in some OTHER venv must not be labeled active-in - the staged one: the comparison is resolved prefix vs staged dir.""" - monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: Path("/payload/venv")) - monkeypatch.setattr(doctor_platform.sys, "prefix", "/some/other/venv") - monkeypatch.setattr(doctor_platform.sys, "base_prefix", "/usr") - - doctor_platform._check_python_environment(False) - - out = capsys.readouterr().out - assert "Runtime venv staged" in out - assert "runs outside it" in out - assert "active in this process" not in out - - def test_staged_and_active_names_both_facts(self, monkeypatch, capsys, tmp_path): - from hermes_cli.runtime_paths import site_packages - - staged = tmp_path / "venv" - site_packages(staged).mkdir(parents=True) - monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: staged) - monkeypatch.syspath_prepend(str(site_packages(staged))) - - doctor_platform._check_python_environment(False) - - out = capsys.readouterr().out - assert "Runtime venv staged" in out - assert "active in this process" in out def test_nothing_staged_keeps_legacy_interpreter_probe(self, monkeypatch, capsys): monkeypatch.setattr(doctor_platform, "_staged_venv_dir", lambda: None) diff --git a/tests/hermes_cli/test_doctor_update_provenance.py b/tests/hermes_cli/test_doctor_update_provenance.py index d61c6a1598..c673f7f9a8 100644 --- a/tests/hermes_cli/test_doctor_update_provenance.py +++ b/tests/hermes_cli/test_doctor_update_provenance.py @@ -45,52 +45,30 @@ def test_no_plugins_dir_is_info(tmp_path): assert rows == [("info", "No plugins directory yet (nothing to check provenance for)", "")] -def test_drift_plugin_warns_with_reinstall_remedy(tmp_path): - _make_plugin(tmp_path, "drifty", sidecar={"source": "git", "update_url": "https://example.com/x"}) - rows = ds._plugin_provenance_rows(tmp_path) - warns = [r for r in rows if r[0] == "warn"] - assert len(warns) == 1 - assert "'drifty'" in warns[0][1] and "drift" in warns[0][1] - assert "reinstall" in str(warns[0]) - - -def test_manual_and_self_cloned_are_info(tmp_path): - _make_plugin(tmp_path, "dropped") - _make_plugin(tmp_path, "cloned", git=True) - rows = ds._plugin_provenance_rows(tmp_path) - assert any("manually" in text and kind == "info" for kind, text, _ in rows) - assert any("'cloned'" in text and "adopt" in detail for kind, text, detail in rows if kind == "info") - assert not any(kind == "warn" for kind, _, _ in rows) - - -def test_git_plugin_in_good_standing_is_ok(tmp_path): - _make_plugin( - tmp_path, "fine", - sidecar={"source": "git", "update_url": "https://example.com/x"}, - git=True, manifest_update_url="https://example.com/x", - ) - rows = ds._plugin_provenance_rows(tmp_path) - assert not any(kind == "warn" for kind, _, _ in rows) - assert any(kind == "ok" and "good standing" in text for kind, text, _ in rows) - - -def test_manifest_url_without_saved_url_warns(tmp_path): - _make_plugin(tmp_path, "sneaky", sidecar={"source": "git"}, git=True, - manifest_update_url="https://evil.example/x") - rows = ds._plugin_provenance_rows(tmp_path) - warns = [r for r in rows if r[0] == "warn"] - assert len(warns) == 1 - assert "'sneaky'" in warns[0][1] and "no url was saved" in warns[0][1] - - -@pytest.mark.parametrize("claimed", [None, "https://evil.example/x"]) -def test_manifest_url_mismatch_warns(tmp_path, claimed): - _make_plugin(tmp_path, "swapped", sidecar={"source": "git", "update_url": "https://example.com/x"}, - git=True, manifest_update_url=claimed) - rows = ds._plugin_provenance_rows(tmp_path) - warns = [r for r in rows if r[0] == "warn"] - assert len(warns) == 1 - assert "update_url mismatch" in str(warns[0]) +def test_mixed_provenance_diagnostic_is_read_only(tmp_path, monkeypatch, capsys): + plugins = tmp_path / 'plugins' + url = 'https://example.com/x' + cases = [ + ('drifty', {'source': 'git', 'update_url': url}, False, None, 'warn', 'reinstall'), + ('dropped', None, False, None, 'info', 'manually'), + ('cloned', None, True, None, 'info', 'adopt'), + ('fine', {'source': 'git', 'update_url': url}, True, url, 'ok', 'good standing'), + ('sneaky', {'source': 'git'}, True, 'https://evil.example/x', 'warn', 'no url was saved'), + ('swapped', {'source': 'git', 'update_url': url}, True, 'https://evil.example/x', 'warn', 'update_url mismatch'), + ('removed', {'source': 'git', 'update_url': url}, True, None, 'warn', 'update_url mismatch'), + ] + for name, sidecar, git, manifest, *_ in cases: + _make_plugin(plugins, name, sidecar=sidecar, git=git, manifest_update_url=manifest) + before = {p: p.read_bytes() for p in plugins.rglob('*') if p.is_file()} + rows = ds._plugin_provenance_rows(plugins) + for name, *_, severity, remedy in cases: + assert any(kind == severity and name in text and remedy in text + detail + for kind, text, detail in rows) + monkeypatch.setattr('hermes_constants.get_hermes_home', lambda: tmp_path) + ds._check_update_provenance(False) + output = capsys.readouterr().out + assert all(name in output for name, *_ in cases) + assert {p: p.read_bytes() for p in plugins.rglob('*') if p.is_file()} == before # --- doctor-side wiring ------------------------------------------------- diff --git a/tests/hermes_cli/test_dump_git_commit.py b/tests/hermes_cli/test_dump_git_commit.py index d51c1238f6..e9f57c1ee5 100644 --- a/tests/hermes_cli/test_dump_git_commit.py +++ b/tests/hermes_cli/test_dump_git_commit.py @@ -14,6 +14,8 @@ from pathlib import Path from subprocess import run as _run from unittest.mock import patch +import pytest + from hermes_cli.version_info import VersionInfo, _reset_version_info_cache @@ -21,122 +23,21 @@ def setup_function(): _reset_version_info_cache() -def _patch_running_install(repo_dir): - """Make the requested repo_dir the running install for the fallback path.""" - return patch("hermes_cli.dump.get_project_root", return_value=repo_dir.resolve()) -def test_get_git_commit_uses_live_git_when_available(tmp_path): - """Source install: version_info resolves commit from live git.""" + +@pytest.mark.parametrize('sha,timestamp,expected,date', [ + ('cafef00d' * 5, 1718662620, 'cafef00d', '2024-06-17'), + (None, None, '(unknown)', ''), +]) +def test_dump_uses_running_install_fallback_only(tmp_path, monkeypatch, sha, timestamp, expected, date): from hermes_cli import dump - repo_dir = tmp_path / "repo" - repo_dir.mkdir() - - with _patch_running_install(repo_dir), \ - patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \ - patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \ - patch("hermes_cli.version_info._git_version_info", - return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "deadbeef" * 5, "main", "git")): - commit = dump._get_git_commit(repo_dir) - - assert commit == "deadbeef" - - -def test_get_git_commit_uses_stamp_when_no_git(tmp_path): - """Docker/Nix: version_info resolves commit from the install stamp.""" - from hermes_cli import dump - - repo_dir = tmp_path / "no-git-here" - repo_dir.mkdir() - - with _patch_running_install(repo_dir), \ - patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \ - patch("hermes_cli.version_info._resolve_repo_dir", lambda: None), \ - patch("hermes_cli.version_info._stamp_version_info", - return_value=VersionInfo("0.19.0", "0.19.0", None, "cafef00d" * 5, None, "docker")): - commit = dump._get_git_commit(repo_dir) - - assert commit == "cafef00d" - - -def test_get_git_commit_returns_unknown_when_neither_source_available(tmp_path): - """Pip-installed wheel: no stamp, no git → '(unknown)'.""" - from hermes_cli import dump - - repo_dir = tmp_path / "repo" - repo_dir.mkdir() - - with _patch_running_install(repo_dir), \ - patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \ - patch("hermes_cli.version_info._resolve_repo_dir", lambda: None): - commit = dump._get_git_commit(repo_dir) - - assert commit == "(unknown)" - - -def test_get_git_commit_output_format_identical_between_sources(tmp_path): - """Regression guard: live-git and stamp outputs share the same shape.""" - from hermes_cli import dump - - repo_dir = tmp_path / "repo" - repo_dir.mkdir() - - # Live-git path. - with _patch_running_install(repo_dir), \ - patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \ - patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \ - patch("hermes_cli.version_info._git_version_info", - return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "b2f477a3" * 5, "main", "git")): - _reset_version_info_cache() - live = dump._get_git_commit(repo_dir) - - # Stamp path. - with _patch_running_install(repo_dir), \ - patch("hermes_cli.version_info._resolve_stamp_file", lambda: tmp_path / "stamp.json"), \ - patch("hermes_cli.version_info._resolve_repo_dir", lambda: None), \ - patch("hermes_cli.version_info._stamp_version_info", - return_value=VersionInfo("0.19.0", "0.19.0", None, "b2f477a3" * 5, None, "docker")): - _reset_version_info_cache() - baked = dump._get_git_commit(repo_dir) - - assert live == baked == "b2f477a3" - assert len(live) == 8 - assert all(c in "0123456789abcdef" for c in live) - - -def test_get_git_commit_date_uses_version_info(tmp_path): - """Source install: version_info carries the commit date from live git.""" - from hermes_cli import dump - - repo_dir = tmp_path / "repo" - repo_dir.mkdir() - - with _patch_running_install(repo_dir), \ - patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \ - patch("hermes_cli.version_info._resolve_repo_dir", lambda: repo_dir), \ - patch("hermes_cli.version_info._git_version_info", - return_value=VersionInfo("0.19.0", "0.19.0+3", 3, "deadbeef" * 5, "main", "git", False, 1718662620)): - _reset_version_info_cache() - date = dump._get_git_commit_date(repo_dir) - - assert date == "2024-06-17" - - -def test_get_git_commit_date_empty_when_unknown(tmp_path): - """Docker/pip: no git, no stamp → '' so the dump line drops the date.""" - from hermes_cli import dump - - repo_dir = tmp_path / "no-git-here" - repo_dir.mkdir() - - with _patch_running_install(repo_dir), \ - patch("hermes_cli.version_info._resolve_stamp_file", lambda: None), \ - patch("hermes_cli.version_info._resolve_repo_dir", lambda: None): - _reset_version_info_cache() - date = dump._get_git_commit_date(repo_dir) - - assert date == "" + monkeypatch.setattr(dump, 'get_project_root', lambda: tmp_path) + info = VersionInfo('1.0', '1.0', None, sha, None, 'docker', False, timestamp) + monkeypatch.setattr('hermes_cli.version_info.get_version_info', lambda: info) + assert dump._get_git_commit(tmp_path) == expected + assert dump._get_git_commit_date(tmp_path) == date # -------------------------------------------------------------------------- diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py index d1f51a244a..2f161b9924 100644 --- a/tests/hermes_cli/test_gui_command.py +++ b/tests/hermes_cli/test_gui_command.py @@ -118,7 +118,6 @@ def _staging_dir_from(cmd) -> Path: raise AssertionError(f"no staging output override in {cmd!r}") - def _packaged_exe_rel() -> Path: """Packaged-exe path relative to electron-builder's output dir on THIS host.""" if sys.platform == "darwin": @@ -128,7 +127,6 @@ def _packaged_exe_rel() -> Path: return Path("linux-unpacked") / "hermes" - def _pack_into_staging(root: Path, content: str = "", returncode: int = 0): """``subprocess.run`` side effect mimicking a real ``npm run pack``: lays the packaged app down inside the STAGING dir named on the command line @@ -146,81 +144,21 @@ def _pack_into_staging(root: Path, content: str = "", returncode: int = 0): return _run - # Dependency admission and staging are exercised by test_desktop_source_build.py. - - - - # ── Content-hash stamp tests ────────────────────────────────────────── - - - - - - # ── Electron build-cache recovery tests ─────────────────────────────── - - - - - - - - - - # ── electronDist (re)download helper tests (#47266) ─────────────────── - - - - - - - - - - - - - -class _FakeProc: - """Minimal psutil.Process stand-in for the lock-breaker tests.""" - - def __init__(self, pid: int, exe: str | None): - self.pid = pid - self.info = {"pid": pid, "exe": exe} - self.terminated = False - self.killed = False - - def terminate(self): - self.terminated = True - - def kill(self): - self.killed = True - - - - - - - - - - - - # --- macOS TCC-stable local signing (relaunch fixup) ----------------------- @@ -286,8 +224,6 @@ def test_desktop_macos_local_codesign_signs_native_binaries(tmp_path, monkeypatc assert str(app / "Contents" / "Frameworks" / "chrome_crashpad_handler") in signed - - @pytest.mark.platforms("macos") def test_relaunchable_fixup_falls_back_to_legacy_adhoc_on_failure(tmp_path, monkeypatch, capsys): """A failing stable sign must still leave a launchable (deep ad-hoc) bundle. @@ -579,8 +515,6 @@ def test_cmd_gui_setup_tcc_identity_exits_before_build(tmp_path, monkeypatch): mock_install.assert_not_called() - - @pytest.mark.platforms("macos") def test_relaunchable_fixup_stable_identity_never_touches_keychain(tmp_path, monkeypatch): """A successful stable-identity re-sign must NOT delete the safeStorage item. @@ -747,8 +681,6 @@ def test_relaunchable_fixup_legacy_adhoc_success_still_verifies_and_never_delete # --- desktop.* launch options (config.yaml) ------------------------------- - - # --- Linux launcher entry registration ------------------------------------ @@ -873,49 +805,6 @@ def test_desktop_launch_options_ozone_hint_defaults_auto(): assert main_desktop._desktop_launch_options()[3] == "auto" -@pytest.mark.platforms("linux") -def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch): - """COSMIC HUD: ``desktop.ozone_platform_hint: x11`` sets - ``ELECTRON_OZONE_PLATFORM_HINT`` on the launched Electron process.""" - root = _make_desktop_tree(tmp_path) - monkeypatch.setattr(cli_main, "PROJECT_ROOT", root) - _make_packaged_executable(root, monkeypatch) - - ok = subprocess.CompletedProcess([], 0) - cfg = {"desktop": {"ozone_platform_hint": "x11"}} - - with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \ - patch("hermes_cli.source_build.prepare_source_dependencies", return_value=ok), \ - patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \ - patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \ - patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \ - patch("hermes_cli.config.load_config", return_value=cfg), \ - patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \ - patch("hermes_cli.main_desktop._detect_linux_password_store", return_value=None), \ - patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \ - pytest.raises(SystemExit): - cli_main.cmd_gui(_ns()) - - launch_env = mock_run.call_args_list[-1].kwargs["env"] - assert launch_env.get("ELECTRON_OZONE_PLATFORM_HINT") == "x11" - - monkeypatch.setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland") - with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \ - patch("hermes_cli.source_build.prepare_source_dependencies", return_value=ok), \ - patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \ - patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \ - patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \ - patch("hermes_cli.config.load_config", return_value=cfg), \ - patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \ - patch("hermes_cli.main_desktop._detect_linux_password_store", return_value=None), \ - patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run2, \ - pytest.raises(SystemExit): - cli_main.cmd_gui(_ns()) - - launch_env = mock_run2.call_args_list[-1].kwargs["env"] - assert launch_env.get("ELECTRON_OZONE_PLATFORM_HINT") == "wayland" - - # --- desktop.password_store detection & bridging (linux) ------------------ @@ -997,6 +886,30 @@ def test_gui_linux_packaged_launch_bridges_detected_password_store(tmp_path, mon assert launch_env["HERMES_DESKTOP_PASSWORD_STORE"] == "gnome-libsecret" +@pytest.mark.platforms("linux") +@pytest.mark.parametrize("explicit,configured,detected,expected", [ + (None, "auto", "gnome-libsecret", "gnome-libsecret"), + (None, "kwallet6", None, "kwallet6"), + ("basic", "kwallet6", None, "basic"), +]) +def test_desktop_environment_precedence(monkeypatch, explicit, configured, detected, expected): + _clear_keychain_env(monkeypatch) + monkeypatch.delenv('ELECTRON_OZONE_PLATFORM_HINT', raising=False) + monkeypatch.setattr('hermes_cli.config.load_config', lambda: { + 'desktop': {'password_store': configured, 'ozone_platform_hint': 'x11'}}) + def detect(): + assert configured == 'auto' and explicit is None + return detected + monkeypatch.setattr(main_desktop, '_detect_linux_password_store', detect) + if explicit: + monkeypatch.setenv('HERMES_DESKTOP_PASSWORD_STORE', explicit) + env, _ = main_desktop._desktop_launch_env(_ns()) + assert env['HERMES_DESKTOP_PASSWORD_STORE'] == expected + assert env['ELECTRON_OZONE_PLATFORM_HINT'] == 'x11' + monkeypatch.setenv('ELECTRON_OZONE_PLATFORM_HINT', 'wayland') + assert main_desktop._desktop_launch_env(_ns())[0]['ELECTRON_OZONE_PLATFORM_HINT'] == 'wayland' + + @pytest.mark.platforms("linux") def test_gui_linux_source_launch_bridges_detected_password_store(tmp_path, monkeypatch): _clear_keychain_env(monkeypatch) @@ -1025,61 +938,6 @@ def test_gui_linux_source_launch_bridges_detected_password_store(tmp_path, monke assert launch_env["HERMES_DESKTOP_PASSWORD_STORE"] == "kwallet6" -@pytest.mark.platforms("linux") -def test_gui_config_password_store_skips_detection(tmp_path, monkeypatch): - _clear_keychain_env(monkeypatch) - root = _make_desktop_tree(tmp_path) - monkeypatch.setattr(cli_main, "PROJECT_ROOT", root) - _make_packaged_executable(root, monkeypatch) - - ok = subprocess.CompletedProcess([], 0) - cfg = {"desktop": {"password_store": "kwallet6"}} - - with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \ - patch("hermes_cli.source_build.prepare_source_dependencies", return_value=ok), \ - patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \ - patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \ - patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \ - patch("hermes_cli.config.load_config", return_value=cfg), \ - patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \ - patch("hermes_cli.main_desktop._detect_linux_password_store") as mock_detect, \ - patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \ - pytest.raises(SystemExit): - cli_main.cmd_gui(_ns()) - - mock_detect.assert_not_called() - launch_env = mock_run.call_args_list[-1].kwargs["env"] - assert launch_env["HERMES_DESKTOP_PASSWORD_STORE"] == "kwallet6" - - -@pytest.mark.platforms("linux") -def test_gui_explicit_password_store_env_wins_over_config_and_detection(tmp_path, monkeypatch): - _clear_keychain_env(monkeypatch) - monkeypatch.setenv("HERMES_DESKTOP_PASSWORD_STORE", "basic") - root = _make_desktop_tree(tmp_path) - monkeypatch.setattr(cli_main, "PROJECT_ROOT", root) - _make_packaged_executable(root, monkeypatch) - - ok = subprocess.CompletedProcess([], 0) - cfg = {"desktop": {"password_store": "kwallet6"}} - - with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \ - patch("hermes_cli.source_build.prepare_source_dependencies", return_value=ok), \ - patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \ - patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \ - patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \ - patch("hermes_cli.config.load_config", return_value=cfg), \ - patch("hermes_cli.linux_desktop_entry.install_desktop_entry", return_value=None), \ - patch("hermes_cli.main_desktop._detect_linux_password_store") as mock_detect, \ - patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \ - pytest.raises(SystemExit): - cli_main.cmd_gui(_ns()) - - mock_detect.assert_not_called() - launch_env = mock_run.call_args_list[-1].kwargs["env"] - assert launch_env["HERMES_DESKTOP_PASSWORD_STORE"] == "basic" - - @pytest.mark.platforms("macos") def test_gui_password_store_bridge_is_linux_only(tmp_path, monkeypatch): _clear_keychain_env(monkeypatch) diff --git a/tests/hermes_cli/test_install_bucket_separation.py b/tests/hermes_cli/test_install_bucket_separation.py index cf6d4227e9..849c48427e 100644 --- a/tests/hermes_cli/test_install_bucket_separation.py +++ b/tests/hermes_cli/test_install_bucket_separation.py @@ -13,50 +13,19 @@ import pytest from hermes_cli.uninstall import remove_legacy_runtime_trees -class TestRemoveLegacyRuntimeTrees: - def test_removes_a_pre_split_node_tree(self, tmp_path): - home = tmp_path / "home" - (home / "node" / "bin").mkdir(parents=True) - (home / "node" / "bin" / "node").write_text("#!/bin/sh\n", encoding="utf-8") - - removed = remove_legacy_runtime_trees(home) - - assert (home / "node") not in [p for p in home.iterdir()] - assert removed == [home / "node"] - - def test_removes_only_the_uv_binary_not_the_whole_bin_dir(self, tmp_path): - """A user's own scripts live in bin/ — deleting the directory would - take them with it.""" - home = tmp_path / "home" - (home / "bin").mkdir(parents=True) - (home / "bin" / "uv").write_text("#!/bin/sh\n", encoding="utf-8") - (home / "bin" / "my-script").write_text("#!/bin/sh\n", encoding="utf-8") - - removed = remove_legacy_runtime_trees(home) - - assert removed == [home / "bin" / "uv"] - assert (home / "bin").is_dir() - assert (home / "bin" / "my-script").is_file() - - def test_never_touches_profile_state(self, tmp_path): - home = tmp_path / "home" - home.mkdir() - for name in ("config.yaml", "auth.json", "SOUL.md"): - (home / name).write_text("keep me", encoding="utf-8") - for name in ("sessions", "skills", "memories", "profiles"): - (home / name).mkdir() - - remove_legacy_runtime_trees(home) - - for name in ("config.yaml", "auth.json", "SOUL.md"): - assert (home / name).is_file(), name - for name in ("sessions", "skills", "memories", "profiles"): - assert (home / name).is_dir(), name - - def test_no_runtime_trees_is_a_quiet_no_op(self, tmp_path): - home = tmp_path / "home" - home.mkdir() - assert remove_legacy_runtime_trees(home) == [] +def test_legacy_cleanup_removes_only_runtime_bytes_and_is_idempotent(tmp_path): + runtime = ('node/bin/node', 'bin/uv', 'bin/uv.exe') + user = ('bin/my-script', 'config.yaml', 'auth.json', 'SOUL.md', + 'sessions/session', 'skills/demo/SKILL.md', 'memories/MEMORY.md', 'profiles/other/config.yaml') + for name in (*runtime, *user): + p = tmp_path / name + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(name, encoding='utf-8') + removed = remove_legacy_runtime_trees(tmp_path) + assert set(removed) == {tmp_path / 'node', tmp_path / 'bin/uv', tmp_path / 'bin/uv.exe'} + assert all(not (tmp_path / name).exists() for name in runtime) + assert all((tmp_path / name).read_text(encoding='utf-8') == name for name in user) + assert remove_legacy_runtime_trees(tmp_path) == [] class TestProfileCopyExclusions: diff --git a/tests/hermes_cli/test_local_models_routes.py b/tests/hermes_cli/test_local_models_routes.py index f75f6698be..987320b3d9 100644 --- a/tests/hermes_cli/test_local_models_routes.py +++ b/tests/hermes_cli/test_local_models_routes.py @@ -232,17 +232,24 @@ def test_download_unknown_model_404s(client): assert r.status_code == 404 -def test_download_short_of_server_length_errors_and_cleans_up(client, monkeypatch): +def test_download_short_of_server_length_errors_and_cleans_up(client, monkeypatch, tmp_path): """Catalog sizes are advisory (upstream re-uploads may make them stale — a mismatch against the CATALOG must not fail a download). The server's own declared length is the only completeness check: fewer bytes than the server promised means a dropped connection, so the job errors and nothing is staged.""" - # Body is 17 bytes; the server promises 32 — a truncated stream. - monkeypatch.setattr( - "pm.downloader._OPENER", - _FakeRangeOpener(b"not the real body", content_length=32)) + from hermes_cli.web_routers import local_models as lm + from hermes_cli.local_runtime.bootstrap import models_dir + requests = [] + class Truncated(_FakeRangeOpener): + def open(self, req, timeout=None): + requests.append(req.headers.get('Range')) + return super().open(req, timeout) + monkeypatch.setattr("pm.downloader._OPENER", Truncated(b"not the real body", content_length=32)) + destination = models_dir() / 'truncated.gguf' + monkeypatch.setattr(lm, '_download_plan', lambda *_: [('https://fixture.invalid/model', destination, 32)]) + monkeypatch.setattr('pm.paths.partials_root', lambda: tmp_path / 'partials') # Pin a generous budget: variant selection prices against the machine # running the test, and a GPU-less CI runner honestly refuses every @@ -271,12 +278,11 @@ def test_download_short_of_server_length_errors_and_cleans_up(client, monkeypatc break time.sleep(0.05) assert status is not None and status["status"] == "error" - assert "range body ended before its declared bounds" in status["error"] - - from hermes_cli.local_runtime.bootstrap import models_dir - - assert not (models_dir() / f"{entry_id}.gguf").exists() - assert not (models_dir() / f"{entry_id}.part").exists() + assert 'bytes=0-0' in requests and any(value != 'bytes=0-0' for value in requests) + assert 'IncompleteRead' in status['error'] + assert not destination.exists() + assert job_id not in lm._RUNNING + assert not list(models_dir().glob('*.part')) def test_download_already_downloaded_short_circuits(client, monkeypatch): @@ -398,111 +404,6 @@ def test_download_pause_and_resume_unknown_404(client): json={"job_id": "deadbeef"}).status_code == 404 -def test_download_finished_job_releases_handles(client, monkeypatch): - """A finished download drops its live download + resume handles, so the - job dict stays JSON-serializable and nothing lingers to pause/resume.""" - body = b"x" * 48 - - monkeypatch.setattr("pm.downloader._OPENER", _FakeRangeOpener(body)) - from hermes_cli.local_runtime.estimator import HardwareBudget - - budget = HardwareBudget(usable_vram_bytes=64 << 30, - total_device_bytes=64 << 30, - ram_available_bytes=64 << 30) - monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget", - lambda **kw: budget) - monkeypatch.setattr( - "hermes_cli.local_runtime.bootstrap.refresh_local_runtime", - lambda: False) - from hermes_cli.local_runtime.catalog import CATALOG - - r = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id}) - job_id = r.json()["job_id"] - deadline = time.time() + 10 - status = None - while time.time() < deadline: - status = client.get(f"/api/local-models/jobs/{job_id}").json() - if status["status"] in ("done", "error"): - break - time.sleep(0.05) - assert status is not None and status["status"] == "done" - - from hermes_cli.web_routers import local_models as lm - - assert job_id not in lm._RUNNING - - -def test_download_pause_reaches_paused_status(client, monkeypatch): - """A running download can be paused; the job lands in a 'paused' state - (partials preserved for resume) instead of erroring.""" - import threading - - gate = threading.Event() - - class _BlockingOpener: - """Stands in for pm.downloader._OPENER: the probe answers honestly - (1 MiB, range-supported) and every body read blocks on the gate, so - the worker is mid-download when the test pauses it.""" - - def open(self, req, timeout=None): - rng = req.headers.get("Range") if req.headers else None - if rng == "bytes=0-0": - return _FakeRangeOpener(b"x" * 1048576).open(req, timeout=timeout) - - class _Resp(io.BytesIO): - status = 206 - headers = {"Content-Range": "bytes 0-1048575/1048576", - "Content-Length": "1048576", - "ETag": '"' + hashlib.sha256(b"x" * 1048576).hexdigest() + '"'} - - def __enter__(self): - return self - - def __exit__(self, *a): - return False - - def read(self, size=-1): - gate.wait(timeout=15) # hold the worker until let go - return super().read(size) - - return _Resp(b"x" * 1048576) - - monkeypatch.setattr("pm.downloader._OPENER", _BlockingOpener()) - from hermes_cli.local_runtime.catalog import CATALOG - from hermes_cli.local_runtime.estimator import HardwareBudget - - budget = HardwareBudget(usable_vram_bytes=64 << 30, - total_device_bytes=64 << 30, - ram_available_bytes=64 << 30) - monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget", - lambda **kw: budget) - - r = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id}) - job_id = r.json()["job_id"] - - # Pause as soon as the live download handle is in place (idempotent). - deadline = time.time() + 10 - paused = False - while time.time() < deadline: - pr = client.post("/api/local-models/download/pause", - json={"job_id": job_id}) - if pr.status_code == 200 and pr.json()["paused"] is True: - paused = True - break - time.sleep(0.05) - assert paused - gate.set() - - deadline = time.time() + 10 - status = None - while time.time() < deadline: - status = client.get(f"/api/local-models/jobs/{job_id}").json() - if status["status"] in ("paused", "done", "error"): - break - time.sleep(0.05) - assert status is not None and status["status"] == "paused" - - # ── pause / resume against a real loopback range server ────── @@ -576,32 +477,6 @@ def _pause_when_flowing(client, job_id): _BIG_BODY = bytes(range(256)) * (8 * 1024 * 1024 // 256) # 8 MiB, deterministic -def test_download_pause_parks_job_with_handle_and_partials( - client, monkeypatch, dl_server, tmp_path): - """Mid-flight pause: the job parks as 'paused' (never 'done'/'error'), - the resume handle stays registered, and the downloader's partial - state survives on disk for the later resume.""" - _pin_budget(monkeypatch) - from hermes_cli.local_runtime.catalog import CATALOG - from hermes_cli.web_routers import local_models as lm - - _serve_plan(monkeypatch, dl_server, tmp_path / "partials", - {"PartA": _BIG_BODY}) - - job_id = client.post("/api/local-models/download", - json={"model_id": CATALOG[0].id}).json()["job_id"] - _pause_when_flowing(client, job_id) - - status = _poll_job(client, job_id) - assert status["status"] == "paused", status - assert status["error"] is None - # The resume handle survives the pause — the route can pick it up. - assert lm._RUNNING[job_id].get("resume") is not None - # Partial state is the downloader's own and must be intact. - partials = list(Path(tmp_path / "partials").glob("*.part")) - assert partials and any(p.stat().st_size > 0 for p in partials) - - def test_download_resume_completes_bytes(client, monkeypatch, dl_server, tmp_path): """Resume after a mid-flight pause finishes the remaining ranges and @@ -622,6 +497,10 @@ def test_download_resume_completes_bytes(client, monkeypatch, dl_server, assert status["status"] == "paused", status RangeHandler.slow_per_chunk = 0.0 # let the resume run at full speed + assert status["error"] is None + assert lm._RUNNING[job_id].get("resume") is not None + partials = list((tmp_path / "partials").glob("*.part")) + assert partials and any(p.stat().st_size > 0 for p in partials) assert client.post("/api/local-models/download/resume", json={"job_id": job_id}).json()["resumed"] is True diff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.py index 6dd61c6870..2a5385bf79 100644 --- a/tests/hermes_cli/test_local_runtime.py +++ b/tests/hermes_cli/test_local_runtime.py @@ -31,6 +31,7 @@ class _StubHandler(BaseHTTPRequestHandler): models: dict | None = None require_auth = False chat_answer = "Paris" + reasoning = "" requests_processing = 0 slots: list = [] @@ -73,7 +74,8 @@ class _StubHandler(BaseHTTPRequestHandler): body = json.loads(self.rfile.read(length)) if length else {} if self.path == "/v1/chat/completions": self._send(200, {"choices": [{"message": { - "role": "assistant", "content": self.chat_answer}}]}) + "role": "assistant", "content": self.chat_answer, + "reasoning_content": self.reasoning}}]}) elif self.path == "/models/load": self._send(200, {"success": True}) elif self.path == "/models/unload": @@ -218,24 +220,11 @@ def test_touch_generate_is_the_readiness_proof(stub_server, tmp_path): assert sup.touch_generate("m") is False -def test_touch_generate_scans_reasoning_content(stub_server, tmp_path): - """Reasoning models answer inside reasoning_content (receipted pitfall).""" +@pytest.mark.parametrize('reasoning,ready', [('The capital is Paris.', True), ('', False)]) +def test_touch_generate_scans_reasoning_content(stub_server, tmp_path, reasoning, ready): port, handler = stub_server - sup = _make_supervisor(tmp_path, port) - - class ReasoningHandler(handler): # type: ignore[valid-type] - def do_POST(self): # noqa: N802 - if self.path == "/v1/chat/completions": - self._send(200, {"choices": [{"message": { - "role": "assistant", "content": "", - "reasoning_content": "The capital of France is Paris."}}]}) - else: - self._send(404, {}) - - # Swap handler class on the live stub server socket is overkill; just - # verify the scan logic path via the normal handler with empty content. - handler.chat_answer = "" - assert sup.touch_generate("m") is False # empty content, no reasoning field + handler.chat_answer, handler.reasoning = '', reasoning + assert _make_supervisor(tmp_path, port).touch_generate('m') is ready def test_ensure_model_ready_unknown_model_raises(stub_server, tmp_path): diff --git a/tests/hermes_cli/test_mcp_catalog.py b/tests/hermes_cli/test_mcp_catalog.py index 78fd3d9539..7483d8d0fa 100644 --- a/tests/hermes_cli/test_mcp_catalog.py +++ b/tests/hermes_cli/test_mcp_catalog.py @@ -222,11 +222,6 @@ class TestManifestParsing: _parse_manifest(path) - - - - - def test_tools_default_excluded_parsed(self, catalog_dir): body = _basic_manifest( tools={"default_excluded": ["docs", "*_radar_*"]}, @@ -295,8 +290,9 @@ class TestInstall: assert server["tools"]["exclude"] == ["docs", "*_radar_*"] assert "include" not in server["tools"] + @pytest.mark.parametrize('stale', [False, True]) def test_reinstall_prior_include_wins_over_default_excluded( - self, catalog_dir, monkeypatch + self, catalog_dir, monkeypatch, stale ): """A user's prior include selection survives reinstall of an exclude-mode manifest (prior selection > manifest default).""" @@ -316,6 +312,9 @@ class TestInstall: } save_config(cfg) + if stale: + cfg['mcp_servers']['demo']['tools']['exclude'] = ['tool_a'] + save_config(cfg) import sys as _sys probed = [("tool_a", "a"), ("tool_b", "b")] monkeypatch.setattr(mc, "_probe_tools", lambda name: probed) @@ -359,38 +358,6 @@ class TestInstall: assert server["tools"]["exclude"] == user_exclude assert "include" not in server["tools"] - def test_include_mode_reinstall_ignores_stale_exclude( - self, catalog_dir, monkeypatch - ): - """When the user previously chose an include selection, a leftover - exclude value must not shadow it on reinstall of an exclude-mode - manifest — include (explicit user checklist choice) wins.""" - body = _basic_manifest( - tools={"default_excluded": ["*_radar_*"]}, - ) - _write_manifest(catalog_dir, "demo", body) - import hermes_cli.mcp_catalog as mc - from hermes_cli.config import load_config, save_config - - cfg = load_config() - cfg.setdefault("mcp_servers", {})["demo"] = { - "command": "npx", - "args": ["-y", "demo-mcp"], - "enabled": True, - "tools": {"include": ["tool_a"]}, - } - save_config(cfg) - - import sys as _sys - probed = [("tool_a", "a"), ("tool_b", "b")] - monkeypatch.setattr(mc, "_probe_tools", lambda name: probed) - monkeypatch.setattr(_sys.stdin, "isatty", lambda: False) - - mc.install_entry(_entry("demo"), enable=True) - - server = load_config()["mcp_servers"]["demo"] - assert server["tools"]["include"] == ["tool_a"] - assert "exclude" not in server["tools"] def test_probe_fail_reinstall_preserves_prior_selection(self, catalog_dir): """A failed probe during reinstall (e.g. OAuth not yet completed) @@ -538,8 +505,6 @@ class TestInstall: assert "secret-val" not in raw - - # --------------------------------------------------------------------------- # Uninstall # --------------------------------------------------------------------------- @@ -622,8 +587,6 @@ class TestToolSelection: assert server["tools"]["include"] == ["a", "b", "c"] - - def test_reinstall_preserves_prior_user_selection( self, catalog_dir, monkeypatch ): diff --git a/tests/hermes_cli/test_memory_setup_provider_arg.py b/tests/hermes_cli/test_memory_setup_provider_arg.py index 7dc163e1f4..8aaf9d56aa 100644 --- a/tests/hermes_cli/test_memory_setup_provider_arg.py +++ b/tests/hermes_cli/test_memory_setup_provider_arg.py @@ -31,42 +31,3 @@ class TestMemorySetupProviderRouting: out = capsys.readouterr().out assert "not found" in out assert "hermes memory setup" in out - - -class TestInstallDependenciesRunner: - """`_install_dependencies` routes through pm (venv sync of the declared - extra) — the old uv → pip → ensurepip ladder is gone.""" - - def test_syncs_declared_extra_via_pm(self, tmp_path): - (tmp_path / "plugin.yaml").write_text("extra: mem0\n", encoding="utf-8") - synced = [] - - import pm - - with patch("plugins.memory.find_provider_dir", return_value=tmp_path), \ - patch.object(pm, "available", lambda extra: False), \ - patch.object( - pm, "sync_venv", - lambda extras=None, explicit=False: synced.append( - (list(extras or []), explicit) - ), - ): - memory_setup._install_dependencies("x") - - assert synced == [(["mem0"], True)] - - def test_available_extra_still_goes_through_pm_currency_check(self, tmp_path): - (tmp_path / "plugin.yaml").write_text("extra: mem0\n", encoding="utf-8") - synced = [] - - import pm - - with patch("plugins.memory.find_provider_dir", return_value=tmp_path), \ - patch.object(pm, "available", lambda extra: True), \ - patch.object( - pm, "sync_venv", - lambda extras=None, explicit=False: synced.append(list(extras or [])), - ): - memory_setup._install_dependencies("x") - - assert synced == [["mem0"]] diff --git a/tests/hermes_cli/test_plugin_worker_lifecycle.py b/tests/hermes_cli/test_plugin_worker_lifecycle.py index e25a6f77da..f2f752ea5e 100644 --- a/tests/hermes_cli/test_plugin_worker_lifecycle.py +++ b/tests/hermes_cli/test_plugin_worker_lifecycle.py @@ -20,20 +20,21 @@ def test_declaration_consent_admission_and_resync(plugin_world, monkeypatch, cap world = plugin_world origin, revision = world.origin(surface=surface, suffix=suffix) before = (world.home / "config.yaml").read_bytes() - monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: False) - world.command("install", identifier=origin.as_uri(), ref=revision, enable=True, allow_removed=True) - assert world.enabled() == [], "non-interactive Python admission bypassed consent" - assert (world.home / "config.yaml").read_bytes() == before - assert "skipped (non-interactive)" in " ".join(capsys.readouterr().out.split()) - + if (surface, suffix) == ("pyproject", "yaml"): + monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: False) + world.command("install", identifier=origin.as_uri(), ref=revision, enable=True, allow_removed=True) + assert world.enabled() == [], "non-interactive Python admission bypassed consent" + assert (world.home / "config.yaml").read_bytes() == before + assert "skipped (non-interactive)" in " ".join(capsys.readouterr().out.split()) + monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True) + monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True) + monkeypatch.setattr("builtins.input", lambda prompt: "no") + world.command("install", identifier=origin.as_uri(), force=True, enable=True, allow_removed=True) + assert world.enabled() == [] + assert (world.home / "config.yaml").read_bytes() == before + assert "declined" in capsys.readouterr().out monkeypatch.setattr(plugins_cmd.sys.stdin, "isatty", lambda: True) monkeypatch.setattr(plugins_cmd.sys.stdout, "isatty", lambda: True) - monkeypatch.setattr("builtins.input", lambda prompt: "no") - world.command("install", identifier=origin.as_uri(), force=True, enable=True, allow_removed=True) - assert world.enabled() == [] - assert (world.home / "config.yaml").read_bytes() == before - assert "declined" in capsys.readouterr().out - monkeypatch.setattr("builtins.input", lambda prompt: "yes") world.command("install", identifier=origin.as_uri(), force=True, enable=True, allow_removed=True) assert world.enabled() == ["plugin-worker-proof"] @@ -276,4 +277,4 @@ def test_concurrent_commands_keep_acknowledged_enables(plugin_world, sibling_pro for process in processes: if process.poll() is None: process.kill() - process.communicate(timeout=10) \ No newline at end of file + process.communicate(timeout=10) diff --git a/tests/hermes_cli/test_plugins_cadence.py b/tests/hermes_cli/test_plugins_cadence.py index 28f6e561bd..94222a5eda 100644 --- a/tests/hermes_cli/test_plugins_cadence.py +++ b/tests/hermes_cli/test_plugins_cadence.py @@ -30,8 +30,7 @@ class _Result: return {"name": self.name, "class": self.klass} -def _no_results(plugins_dir, **k): - return [] + def test_clock_gate_due_when_never_run(homed): @@ -74,78 +73,44 @@ def test_run_writes_receipt_and_marker(homed): assert len(calls) == 1 -def test_needs_fixing_logged_not_applied(homed): +@pytest.mark.parametrize('enabled', [False, True]) +def test_auto_apply_selects_only_updateable_git_and_persists_receipt(homed, enabled, caplog): + from pm import receipt applied = [] - - import pm.receipt as receipt_mod - - monkey = pytest.MonkeyPatch() - monkey.setattr(receipt_mod, "begin", lambda kind: None) - monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0, **kwargs: None) - try: - results = cad.run_scheduled_check( - run_checks_fn=lambda d: [_Result("plug", needs_fixing="mismatch")], - plugins_dir=homed / "plugins", - apply_updates_fn=applied.append, - now=time.time(), - ) - assert applied == [] # needs-fixing is never auto-applied - finally: - monkey.undo() + rows = [_Result('gitplug', update_available=True), + _Result('pipplug', klass='pip', update_available=True), + _Result('broken', needs_fixing='mismatch')] + cad.run_scheduled_check(run_checks_fn=lambda _: rows, plugins_dir=homed / 'plugins', + apply_updates_fn=applied.append, + config_get=lambda section, key: enabled if key == 'auto_apply' else 24) + assert applied == (['gitplug'] if enabled else []) + assert receipt.latest()['outcome'] == 'updates-available' + assert 'broken' in caplog.text and 'trust-update-url' in caplog.text -def test_auto_apply_only_git_rows_and_only_when_opted_in(homed): - applied = [] +@pytest.mark.parametrize('failed', [False, True]) +def test_housekeeping_runs_real_cadence_and_backs_off(homed, monkeypatch, caplog, failed): + import gateway.run as gateway + from hermes_cli import plugins_updates, plugins_cmd + from pm import receipt - import pm.receipt as receipt_mod - - monkey = pytest.MonkeyPatch() - monkey.setattr(receipt_mod, "begin", lambda kind: None) - monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0, **kwargs: None) - try: - results = [_Result("gitplug", klass="git", update_available=True), - _Result("pipplug", klass="pip", update_available=True)] - # opted OUT: nothing applied - cad.run_scheduled_check( - run_checks_fn=lambda d: results, - plugins_dir=homed / "plugins", - apply_updates_fn=applied.append, - config_get=lambda s, k: (False if k == "auto_apply" else None), - now=time.time(), - ) - assert applied == [] # auto_apply False → nothing - - # opted IN: only the git row applies - cad._markers_dir().joinpath("last-run").unlink() - cad.run_scheduled_check( - run_checks_fn=lambda d: results, - plugins_dir=homed / "plugins", - apply_updates_fn=applied.append, - config_get=lambda s, k: (True if k == "auto_apply" else None), - now=time.time(), - ) - assert applied == ["gitplug"] - finally: - monkey.undo() - - -def test_check_failure_is_never_fatal_and_stamps_marker(homed): - import pm.receipt as receipt_mod - - monkey = pytest.MonkeyPatch() - monkey.setattr(receipt_mod, "begin", lambda kind: None) - monkey.setattr(receipt_mod, "finalize", lambda outcome, exit_code=0, **kwargs: None) - try: - def boom(d): - raise RuntimeError("network down") - - results = cad.run_scheduled_check( - run_checks_fn=boom, - plugins_dir=homed / "plugins", - now=time.time(), - ) - assert results == [] - # marker stamped → a failing check doesn't hammer the network - assert (homed / "plugin-update-checks" / "last-run").is_file() - finally: - monkey.undo() + calls, applied = [], [] + def checks(directory): + calls.append(directory) + if failed: + raise OSError('offline') + return [_Result('plug', update_available=True)] + monkeypatch.setattr(plugins_updates, 'run_checks', checks) + monkeypatch.setattr(plugins_cmd, '_plugins_dir', lambda: homed / 'plugins') + monkeypatch.setattr(plugins_cmd, 'cmd_update', lambda name, **kwargs: applied.append((name, kwargs))) + monkeypatch.setattr(cad, 'auto_apply_enabled', lambda *_: True) + for _ in range(2): + gateway._housekeeping_chore('Plugin update check', gateway._housekeeping_plugin_update_check) + assert calls == [homed / 'plugins'] + assert applied == ([] if failed else [('plug', {'interactive': False})]) + saved = receipt.latest() + assert saved['outcome'] == ('failed' if failed else 'updates-available') + assert saved['exit_code'] == int(failed) + assert (homed / 'plugin-update-checks/last-run').is_file() + if failed: + assert saved['warnings'][0]['message'] in caplog.text diff --git a/tests/hermes_cli/test_plugins_check_updates.py b/tests/hermes_cli/test_plugins_check_updates.py index c89d33f5db..65932f37ff 100644 --- a/tests/hermes_cli/test_plugins_check_updates.py +++ b/tests/hermes_cli/test_plugins_check_updates.py @@ -180,24 +180,11 @@ def test_matching_tag_fetches_feed(tmp_path): r = check_provenanced(prov, fetch=fetch, ls_remote=_no) assert fetched == ["https://feed.example/f.yml"] assert r.latest == "1.2.0" + assert r.current == "1.0.0" assert r.min_hermes == "0.27.0" assert r.update_available is True # installed 1.0.0 vs feed 1.2.0 -def test_feed_version_equal_to_installed_version_means_no_update(tmp_path): - """C17 convergence: feed semantic version vs installed semantic version.""" - plug = tmp_path / "plug" - plug.mkdir() - (plug / "plugin.yaml").write_text( - "name: plug\nversion: 1.2.0\nupdate_url: https://feed.example/f.yml\n", - encoding="utf-8", - ) - prov = _git_prov(update_url="https://feed.example/f.yml") - prov.path = plug - r = check_provenanced(prov, fetch=lambda u: FEED, ls_remote=_no) - assert r.update_available is False - - def test_feed_version_with_no_installed_version_is_unknown(tmp_path): """A semantic feed vs a versionless manifest cannot be compared — report unknown, never a revision-vs-version inequality.""" @@ -254,25 +241,6 @@ def test_feed_git_sha_case_equivalent_is_not_an_update(tmp_path): assert r.update_available is False -def test_feed_git_tag_artifact_falls_to_semantic_compare(tmp_path): - """A non-sha artifacts.git (repo URL, tag) is not a comparable git - identity — the feed's semantic version is compared against the - installed manifest's version instead.""" - plug = tmp_path / "plug" - plug.mkdir() - (plug / "plugin.yaml").write_text( - "name: plug\nversion: 1.0.0\nupdate_url: https://feed.example/f.yml\n", - encoding="utf-8", - ) - feed = "version: 9.9.9\nartifacts:\n git: https://example/o/r\n" - prov = _git_prov(update_url="https://feed.example/f.yml") - prov.path = plug - r = check_provenanced(prov, fetch=lambda u: feed, ls_remote=_no) - assert r.update_available is True - assert r.current == "1.0.0" - assert r.latest == "9.9.9" - - def test_feed_git_sha_with_no_recorded_revision_is_unknown(tmp_path): plug = tmp_path / "plug" plug.mkdir() @@ -305,23 +273,6 @@ def test_feed_git_sha_against_tagged_revision_is_unknown(tmp_path): assert r.update_available is None -def test_feed_semantic_branch_reports_installed_version_as_current(tmp_path): - """The semantic branch compares version vs version, so the reported - current is the installed version — not the unrelated revision sha.""" - plug = tmp_path / "plug" - plug.mkdir() - (plug / "plugin.yaml").write_text( - "name: plug\nversion: 1.0.0\nupdate_url: https://feed.example/f.yml\n", - encoding="utf-8", - ) - prov = _git_prov(update_url="https://feed.example/f.yml") - prov.path = plug - r = check_provenanced(prov, fetch=lambda u: FEED, ls_remote=_no) - assert r.update_available is True - assert r.current == "1.0.0" - assert r.latest == "1.2.0" - - def test_malformed_yaml_feed_reports_unknown_row(tmp_path): plug = tmp_path / "plug" plug.mkdir() @@ -339,14 +290,16 @@ def test_parse_feed_rejects_non_string_git_artifact(): parse_feed_yml(feed) -def test_ls_remote_lifecycle_current_available_applied(tmp_path): +def test_ls_remote_lifecycle_current_available_applied(tmp_path, monkeypatch): """The git-path gate, end to end against a real local repo: current -> ls-remote sees a new HEAD -> revision recorded -> current. No network, no manual manifest rewriting — every comparison is the real command.""" repo = tmp_path / "repo" run, head = _local_repo(repo, "-b", "main") sha1 = head() - ls_remote = _real_ls_remote() + from hermes_cli.plugins_updates import default_ls_remote + monkeypatch.setattr('hermes_cli.plugins_cmd._resolve_git_executable', _git_exe) + ls_remote = default_ls_remote plug = tmp_path / "plug" plug.mkdir() @@ -373,22 +326,6 @@ def test_ls_remote_lifecycle_current_available_applied(tmp_path): assert check_provenanced(prov3, fetch=_no, ls_remote=ls_remote).update_available is False -def _real_ls_remote(): - git = _git_exe() - env = _git_env() - - def ls_remote(source): - proc = subprocess.run( - [git, "ls-remote", source, "HEAD"], - capture_output=True, text=True, timeout=10, env=env, - ) - if proc.returncode != 0: - raise RuntimeError((proc.stderr or "ls-remote failed").strip()[:200]) - out = (proc.stdout or "").strip() - return out.split("\t")[0] if out else "" - return ls_remote - - def test_feed_fetch_failure_is_row_level_reason(tmp_path): plug = tmp_path / "plug" plug.mkdir() @@ -428,7 +365,7 @@ def test_ls_remote_fallback(tmp_path): # ── the real git ls-remote, against a local bare repo ─────────────── -def test_real_ls_remote_against_bare_repo(tmp_path): +def test_real_ls_remote_against_bare_repo(tmp_path, monkeypatch): source = tmp_path / "bare.git" git = _git_exe() env = _git_env() @@ -436,14 +373,9 @@ def test_real_ls_remote_against_bare_repo(tmp_path): [git, "init", "--bare", "-q", str(source)], check=True, capture_output=True, env=env, ) - # ls-remote on an empty bare repo: exit 0, empty HEAD — the command - # SHAPE works; empty maps to unknown, never a crash - proc = subprocess.run( - [git, "ls-remote", str(source), "HEAD"], - capture_output=True, text=True, timeout=10, env=env, - ) - assert proc.returncode == 0 - assert proc.stdout.strip() == "" + from hermes_cli.plugins_updates import default_ls_remote + monkeypatch.setattr('hermes_cli.plugins_cmd._resolve_git_executable', _git_exe) + assert default_ls_remote(str(source)) == "" # ── feed parsing ──────────────────────────────────────────────────── @@ -465,19 +397,6 @@ class _EP: self.dist_name = dist_name -def test_pip_check_stateless(): - eps = [_EP("mnemosyne", "mnemosyne_hermes:register", "mnemosyne-hermes")] - rs = check_pip_plugins( - installed_version=lambda d: "0.5.0", - pypi_latest=lambda d: "0.6.0", - entry_points=eps, - ) - assert rs[0].klass == "pip" - assert rs[0].current == "0.5.0" - assert rs[0].latest == "0.6.0" - assert rs[0].update_available is True - - def test_pip_not_on_pypi_reports_unknown(): eps = [_EP("local-only", "x:y", "x")] rs = check_pip_plugins( @@ -547,4 +466,4 @@ def test_run_checks_never_mutates(tmp_path): include_pip=False, ) assert results[0].update_available is True - assert (plugins / ".install-metadata.json").read_text(encoding="utf-8") == before \ No newline at end of file + assert (plugins / ".install-metadata.json").read_text(encoding="utf-8") == before diff --git a/tests/hermes_cli/test_plugins_cmd.py b/tests/hermes_cli/test_plugins_cmd.py index 406ad56d5e..9ba46eee6d 100644 --- a/tests/hermes_cli/test_plugins_cmd.py +++ b/tests/hermes_cli/test_plugins_cmd.py @@ -39,20 +39,9 @@ class TestSanitizePluginName: _sanitize_plugin_name("../../etc/passwd", tmp_path) - - - - - # ── allow_subdir=True ── - - - - - - # ── _resolve_git_url ────────────────────────────────────────────────────── @@ -60,16 +49,12 @@ class TestResolveGitUrl: """Shorthand and full-URL resolution, with optional subdirectory.""" - - - def test_url_with_fragment_subdir(self): url, subdir = _resolve_git_url("https://github.com/owner/repo.git#my-plugin") assert url == "https://github.com/owner/repo.git" assert subdir == "my-plugin" - @pytest.mark.parametrize( "identifier", [ @@ -102,7 +87,6 @@ class TestResolveSubdirWithin: assert result == (tmp_path / "a" / "b" / "c").resolve() - def test_rejects_symlink_escape(self, tmp_path): clone = tmp_path / "clone" clone.mkdir() @@ -166,23 +150,6 @@ class TestResolveGitExecutable: assert call.args[0][0] == "/resolved/git" assert run.call_args_list[2].args[0][1:] == ["pull", "--ff-only"] - def test_git_pull_clean_tree_never_stashes(self, tmp_path): - import hermes_cli.plugins_cmd as pc - - _resolve_git_executable.cache_clear() - with patch.object(pc, "_resolve_git_executable", return_value="/g"): - with patch.object(pc.subprocess, "run") as run: - run.side_effect = [ - MagicMock(returncode=0, stdout="", stderr=""), # status - MagicMock(returncode=0, stdout="git@example.com:x.git\n", stderr=""), # remote get-url - MagicMock(returncode=0, stdout="Updated\n", stderr=""), # pull - ] - ok, msg = pc._git_pull_plugin_dir(tmp_path) - assert ok is True - assert msg == "Updated" - commands = [c.args[0][1] for c in run.call_args_list] - assert "stash" not in commands - class TestGitPullPluginDirAutostash: """Real-git E2E: local edits in a plugin checkout must not block updates.""" @@ -294,6 +261,7 @@ class TestGitPullPluginDirAutostash: ok, msg = pc._git_pull_plugin_dir(checkout) assert ok is True assert "Already up to date" in msg + assert git(checkout, "stash", "list").strip() == "" # ── _repo_name_from_url ────────────────────────────────────────────────── @@ -308,8 +276,6 @@ class TestRepoNameFromUrl: ) - - # ── plugins_command dispatch ────────────────────────────────────────────── @@ -455,7 +421,6 @@ class TestCmdRemove: assert exc_info.value.code == 1 - # ── _copy_example_files tests ───────────────────────────────────────────────── @@ -503,8 +468,6 @@ class TestPromptPluginEnvVars: """Tests for _prompt_plugin_env_vars.""" - - def test_prompts_for_missing_var_rich_format(self): from hermes_cli.plugins_cmd import _prompt_plugin_env_vars from unittest.mock import MagicMock, patch @@ -550,8 +513,6 @@ class TestPromptPluginEnvVars: mock_prompt.assert_called_once() - - # ── curses_radiolist ───────────────────────────────────────────────────── @@ -573,7 +534,6 @@ class TestProviderDiscovery: """Test provider plugin discovery and config helpers.""" - def test_save_context_engine(self, tmp_path, monkeypatch): """Saving a context engine persists to config.yaml.""" monkeypatch.setenv("HERMES_HOME", str(tmp_path)) @@ -597,19 +557,14 @@ class TestProviderDiscovery: # ── Auto-activation fix ────────────────────────────────────────────────── -class TestNoAutoActivation: - """Verify that plugin engines don't auto-activate when config says 'compressor'.""" - - def test_compressor_default_ignores_plugin(self): - """When context.engine is 'compressor', a plugin-registered engine should NOT - be used — only explicit config triggers plugin engines.""" - # This tests the run_agent.py logic indirectly by checking that the - # code path for default config doesn't call get_plugin_context_engine. - import run_agent as ra_module - source = Path(ra_module.__file__).read_text(encoding="utf-8") - # The old code had: "Even with default config, check if a plugin registered one" - # The fix removes this. Verify it's gone. - assert "Even with default config, check if a plugin registered one" not in source +def test_default_compressor_does_not_activate_an_offered_plugin(monkeypatch): + from agent.agent_init import _select_context_engine + from types import SimpleNamespace + candidate = SimpleNamespace(name='offered') + monkeypatch.setattr('plugins.context_engine.load_context_engine', lambda _: None) + monkeypatch.setattr('hermes_cli.plugins.get_plugin_context_engine', lambda: candidate) + assert _select_context_engine({'context': {'engine': 'compressor'}}) is None + assert _select_context_engine({'context': {'engine': 'offered'}}).name == 'offered' # ── End-to-end subdirectory install ────────────────────────────────────────── diff --git a/tests/hermes_cli/test_post_update.py b/tests/hermes_cli/test_post_update.py index 0fdf4c2aff..aba2dc101f 100644 --- a/tests/hermes_cli/test_post_update.py +++ b/tests/hermes_cli/test_post_update.py @@ -101,29 +101,6 @@ def test_migrate_config_restores_backup_when_version_does_not_advance( assert backups, "backup file must exist" -def test_migrate_config_restores_backup_on_exception(tmp_path, monkeypatch): - import hermes_cli.config as cfg - import hermes_cli.config_migrations as mig - - config_path = tmp_path / "config.yaml" - config_path.write_text("_config_version: 20\n", encoding="utf-8") - - floor = getattr(mig, "SUPPORT_FLOOR_VERSION", 12) - monkeypatch.setattr(cfg, "check_config_version", lambda: (max(20, floor), 34)) - monkeypatch.setattr(cfg, "get_config_path", lambda: config_path) - monkeypatch.setattr(cfg, "get_env_path", lambda: tmp_path / ".env") - - def exploding_migrate(**kw): - config_path.write_text("half-written garbage", encoding="utf-8") - raise RuntimeError("migration blew up") - - monkeypatch.setattr(cfg, "migrate_config", lambda **kw: exploding_migrate(**kw)) - - with pytest.raises(RuntimeError, match="blew up"): - step_migrate_config() - assert config_path.read_text(encoding="utf-8") == "_config_version: 20\n" - - # ── step_state_db_guard ────────────────────────────────────────────── diff --git a/tests/hermes_cli/test_post_update_expose_cli.py b/tests/hermes_cli/test_post_update_expose_cli.py index fb453400bd..03388b37c8 100644 --- a/tests/hermes_cli/test_post_update_expose_cli.py +++ b/tests/hermes_cli/test_post_update_expose_cli.py @@ -84,21 +84,7 @@ class TestExposeCli: assert str(root / ".hermes" / "bin") in body assert os.access(wrapper, os.X_OK) - @posix_only - def test_second_run_is_a_no_op(self, fake_install): - _launchers.expose_cli() - result = _launchers.expose_cli() - assert result == {"ok": True, "written": []} - @posix_only - def test_repairs_a_stale_same_install_wrapper(self, fake_install): - home, root = fake_install - _launchers.expose_cli() - wrapper = home / ".local" / "bin" / "hermes" - wrapper.write_text(f'#!/bin/sh\nexec "{root}/venv/bin/python" OLD-SHAPE\n') - result = _launchers.expose_cli() - assert "hermes" in result["written"] - assert "OLD-SHAPE" not in wrapper.read_text() @posix_only def test_leaves_another_installs_wrapper_alone(self, fake_install): diff --git a/tests/hermes_cli/test_quarantine_orphan_rescue.py b/tests/hermes_cli/test_quarantine_orphan_rescue.py index 28faa63e11..243d3c1394 100644 --- a/tests/hermes_cli/test_quarantine_orphan_rescue.py +++ b/tests/hermes_cli/test_quarantine_orphan_rescue.py @@ -305,22 +305,3 @@ def test_helper_is_a_noop_when_installer_wrote_a_fresh_shim(tmp_path, capsys): assert failed == [] assert original.read_bytes() == b"MZ-fresh", "must not clobber the fresh shim" assert capsys.readouterr().err == "" - - -def test_restore_reports_on_stderr(tmp_path, capsys): - """Restore diagnostics must not pollute a JSON-RPC stdout stream.""" - scripts = _make_scripts_dir(tmp_path) - quarantined = scripts / "hermes.exe.old.123" - quarantined.write_bytes(b"MZ-old-hermes") - original = scripts / "hermes.exe" - - def always_locked(src, dst): - raise PermissionError(32, "being used by another process") - - with patch.object(er.os, "rename", always_locked): - failed = er.restore_quarantined_shims([(original, quarantined)], backoff_ms=(0,)) - - captured = capsys.readouterr() - assert failed == [(original, quarantined)] - assert "FAILED to restore hermes.exe" in captured.err - assert captured.out == "", "stdout must stay clean for JSON-RPC" diff --git a/tests/hermes_cli/test_run_with_idle_timeout.py b/tests/hermes_cli/test_run_with_idle_timeout.py deleted file mode 100644 index 321543a7fa..0000000000 --- a/tests/hermes_cli/test_run_with_idle_timeout.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Retired build entrypoints stop old in-memory updaters without side effects.""" -import sys - -import pytest - -from hermes_cli.main_web_build import _nixos_build_env, _run_npm_install_deterministic, _run_with_idle_timeout - - -@pytest.mark.parametrize("helper", ["idle", "install", "nixos"]) -def test_retired_build_helper_stops_before_running_any_command(tmp_path, helper, capsys): - marker = tmp_path / "ran" - script = tmp_path / "command.py" - script.write_text(f"from pathlib import Path; Path({str(marker)!r}).touch()") - with pytest.raises(SystemExit) as error: - if helper == "idle": - _run_with_idle_timeout([sys.executable, str(script)], tmp_path, idle_timeout_seconds=10) - elif helper == "install": - _run_npm_install_deterministic(sys.executable, tmp_path, extra_args=(str(script),)) - else: - _nixos_build_env() - assert error.value.code == 0 - assert not marker.exists() - assert "run `hermes` again" in capsys.readouterr().err diff --git a/tests/hermes_cli/test_source_launcher_publication.py b/tests/hermes_cli/test_source_launcher_publication.py index 40d57353ba..7b810f7f71 100644 --- a/tests/hermes_cli/test_source_launcher_publication.py +++ b/tests/hermes_cli/test_source_launcher_publication.py @@ -54,6 +54,17 @@ def fixture_tree(tmp_path, monkeypatch): return repo, home, interpreter +def select_generation(repo, name, value): + selected = install_state_dir(repo) / 'environments' / str(name) / 'venv' + site = site_packages(selected) + site.mkdir(parents=True) + (selected / 'pyvenv.cfg').write_text('home = fixture\n', encoding='utf-8') + (site / 'selected_probe.py').write_text(f'VALUE = {value!r}\n', encoding='utf-8') + (install_state_dir(repo) / 'facts.json').write_text( + json.dumps({'packages': {'venv': {'environment': str(selected)}}}), encoding='utf-8') + return selected + + @pytest.mark.platforms("windows", "posix") @pytest.mark.parametrize("form", ["native", "shell"]) def test_source_launchers_boot_selected_generation_from_custom_home(tmp_path, monkeypatch, form): @@ -73,13 +84,7 @@ def test_source_launchers_boot_selected_generation_from_custom_home(tmp_path, mo ] args = ['spaces and café', 'apostrophe\'s', r'one\two', '$HOME; echo no', ''] for number in (1, 2): - selected = install_state_dir(repo) / "environments" / str(number) / "venv" - site = site_packages(selected) - site.mkdir(parents=True) - (selected / "pyvenv.cfg").write_text("home = fixture\n", encoding="utf-8") - (site / "selected_probe.py").write_text(f"VALUE = {number}\n", encoding="utf-8") - (install_state_dir(repo) / "facts.json").write_text( - json.dumps({"packages": {"venv": {"environment": str(selected)}}}), encoding="utf-8") + select_generation(repo, number, number) env = dict(os.environ) env.pop("HERMES_HOME", None) env.pop("HERMES_RUNTIME_DIR", None) @@ -195,13 +200,7 @@ def test_boot_migrates_legacy_conveniences_to_selected_runtime(tmp_path, monkeyp repo, home, interpreter = fixture_tree(tmp_path, monkeypatch) monkeypatch.setattr(Path, "home", lambda: home) monkeypatch.setenv("HERMES_INSTALL_ROOT", str(repo)) - selected = install_state_dir(repo) / "environments" / "current" / "venv" - site = site_packages(selected) - site.mkdir(parents=True) - (selected / "pyvenv.cfg").write_text("home = fixture\n") - (site / "selected_probe.py").write_text("VALUE = 'migrated'\n") - (install_state_dir(repo) / "facts.json").write_text(json.dumps({ - "schema": 1, "packages": {"venv": {"environment": str(selected)}}})) + select_generation(repo, 'current', 'migrated') out = home / ".local" / "bin" out.mkdir(parents=True) # Old venv and sibling-ACP wrappers, with an unrelated command sharing bin. @@ -239,16 +238,9 @@ def _command_survives_generation_collection(tmp_path, monkeypatch, surface): launcher = next(path for path in out.iterdir() if path.stem == "hermes") args = ["café ' quoted", "", "$HOME; not a shell"] command = [] - selected = install_state_dir(repo) / "environments" / "old" / "venv" for value in ("old", "new"): - selected = selected.parent.parent / value / "venv" - site = site_packages(selected) - site.mkdir(parents=True) - (selected / "pyvenv.cfg").write_text("home = fixture\n", encoding="utf-8") + selected = select_generation(repo, value, value) (selected.parent / ".lease-managed").touch() - (site / "selected_probe.py").write_text(f"VALUE = {value!r}\n", encoding="utf-8") - (install_state_dir(repo) / "facts.json").write_text( - json.dumps({"packages": {"venv": {"environment": str(selected)}}}), encoding="utf-8") if value == "old": if surface == "legacy": command = [sys.executable, "-I", str(repo / "scripts/hermes-gateway"), "--help"] @@ -323,13 +315,7 @@ def test_dashboard_action_boots_selected_dependencies(tmp_path, monkeypatch): from hermes_cli import web_server, web_server_gateway repo, home, _ = fixture_tree(tmp_path, monkeypatch) - selected = install_state_dir(repo) / "environments" / "current" / "venv" - site = site_packages(selected) - site.mkdir(parents=True) - (selected / "pyvenv.cfg").write_text("home = fixture\n", encoding="utf-8") - (site / "selected_probe.py").write_text("VALUE = 'selected'\n", encoding="utf-8") - (install_state_dir(repo) / "facts.json").write_text( - json.dumps({"packages": {"venv": {"environment": str(selected)}}}), encoding="utf-8") + select_generation(repo, 'current', 'selected') monkeypatch.setattr(web_server, "PROJECT_ROOT", repo) monkeypatch.setattr(web_server_gateway, "_ACTION_LOG_DIR", home / "logs") proc = web_server_gateway._spawn_hermes_action(["--version"], "gateway-restart") diff --git a/tests/hermes_cli/test_tools_config.py b/tests/hermes_cli/test_tools_config.py index dd8a6b543c..97d24838f2 100644 --- a/tests/hermes_cli/test_tools_config.py +++ b/tests/hermes_cli/test_tools_config.py @@ -386,28 +386,7 @@ class TestAgentBrowserPostSetup: with patch("pm.ensure") as ensure: yield ensure - def test_browserbase_returns_before_any_chromium_check(self): - with patch("subprocess.run") as run, patch( - "tools.browser_tool_install._chromium_installed" - ) as chromium_check: - _run_post_setup("browserbase") - run.assert_not_called() - chromium_check.assert_not_called() - - def test_docker_with_missing_chromium_warns_instead_of_installing(self, _stub_package_install): - with patch( - "tools.browser_tool_install._find_agent_browser", return_value="/image/agent-browser" - ), patch("subprocess.run") as run, patch( - "tools.browser_tool_install._chromium_installed", return_value=False - ), patch( - "tools.browser_tool_install._running_in_docker", return_value=True - ), patch("hermes_cli.tools_config_post_setup._print_warning") as warn: - _run_post_setup("agent_browser") - - run.assert_not_called() - _stub_package_install.assert_not_called() - assert any("Docker" in c.args[0] for c in warn.call_args_list) @pytest.mark.parametrize("failure", ["pm", "timeout"]) def test_install_failure_reports_error(self, failure): @@ -433,13 +412,6 @@ class TestBrowserUseCliInstalledForAllNonCamofoxBackends: Camofox must attempt the CLI install, not just the explicit "Browser Use" row.""" - @pytest.mark.parametrize("key", ["agent_browser", "browserbase", "browser_use_cli"]) - def test_browser_post_setup_attempts_cli_install(self, key): - with patch("hermes_cli.tools_config_post_setup._ensure_browser_use_cli") as ensure, patch( - "shutil.which", return_value=None - ), patch("subprocess.run"), patch("pm.ensure"): - _run_post_setup(key) - ensure.assert_called_once() def test_camofox_post_setup_never_touches_browser_use(self): """Camofox is Firefox-based with no CDP surface; the CDP-only @@ -671,17 +643,7 @@ def test_vision_picker_custom_endpoint(tmp_path, monkeypatch): # Subscription rows and never-installed KittenTTS/Piper). -def _fake_features(*, logged_in: bool, paid: bool = True): - account = ( - NousPortalAccountInfo( - logged_in=True, source="jwt", fresh=False, paid_service_access=paid - ) - if logged_in - else NousPortalAccountInfo( - logged_in=False, source="none", fresh=False, paid_service_access=None - ) - ) - return SimpleNamespace(nous_auth_present=logged_in, account_info=account) + def test_visible_providers_reuses_logged_out_feature_snapshot(monkeypatch): diff --git a/tests/hermes_cli/test_tools_config_post_setup.py b/tests/hermes_cli/test_tools_config_post_setup.py index 7ab2bd51c6..d3177b51cb 100644 --- a/tests/hermes_cli/test_tools_config_post_setup.py +++ b/tests/hermes_cli/test_tools_config_post_setup.py @@ -13,47 +13,42 @@ import pytest from hermes_cli.tools_config_post_setup import _run_post_setup -def test_cloud_browser_explicit_setup_ensures_managed_driver(): +@pytest.mark.platforms('linux') +@pytest.mark.parametrize('provider,docker,playwright', [ + ('browserbase', False, False), ('agent_browser', False, True), + ('agent_browser', False, False), ('agent_browser', True, False), + ('browser_use_cli', False, False), +]) +def test_browser_setup_respects_provider_and_native_owner(monkeypatch, capsys, provider, docker, playwright): with ( - patch("tools.browser_use_cli.install_cli", return_value=(True, "ready")), - patch("tools.browser_tool_install._find_agent_browser", return_value="/external/agent-browser"), - patch("pm.ensure") as ensure, - patch("subprocess.run") as run, - ): - _run_post_setup("browserbase") - - ensure.assert_called_once_with("agent-browser", explicit=True) - run.assert_not_called() - - -@pytest.mark.platforms("linux") -@pytest.mark.parametrize("playwright_present", [True, False]) -def test_local_setup_uses_pm_dependency_union_and_gives_system_library_guidance( - capsys, playwright_present, -): - with ( - patch("tools.browser_use_cli.install_cli", return_value=(True, "ready")), - patch("tools.browser_tool_install._running_in_docker", return_value=False), - patch("tools.browser_tool_install._chromium_installed", return_value=False), - patch("importlib.util.find_spec", return_value=object() if playwright_present else None), - patch("shutil.which", return_value="/usr/bin/apt-get"), - patch("pm.ensure") as ensure, - patch("subprocess.run") as run, + patch('tools.browser_use_cli.install_cli', return_value=(True, 'ready')) as install, + patch('tools.browser_tool_install._running_in_docker', return_value=docker), + patch('tools.browser_tool_install._find_agent_browser', return_value='/image/agent-browser'), + patch('tools.browser_tool_install._chromium_installed', return_value=False) as chromium, + patch('importlib.util.find_spec', return_value=object() if playwright else None), + patch('shutil.which', return_value='/usr/bin/apt-get'), + patch('pm.ensure') as ensure, patch('subprocess.run') as run, ): before = dict(os.environ) - _run_post_setup("agent_browser") + _run_post_setup(provider) assert dict(os.environ) == before - - ensure.assert_called_once_with("agent-browser", explicit=True) + install.assert_called_once() run.assert_not_called() - output = capsys.readouterr().out - assert "system" in output - if playwright_present: - assert sys.executable in output - assert "-m playwright install-deps chromium" in output + if provider == 'browserbase': + chromium.assert_not_called() + if provider == 'browser_use_cli' or docker: + ensure.assert_not_called() else: - assert "https://playwright.dev/python/docs/browsers#install-system-dependencies" in output - assert "npx" not in output + ensure.assert_called_once_with('agent-browser', explicit=True) + output = capsys.readouterr().out + if docker: + assert 'Docker' in output + elif provider == 'agent_browser': + assert 'system' in output and 'npx' not in output + if playwright: + assert sys.executable in output and '-m playwright install-deps chromium' in output + else: + assert 'https://playwright.dev/python/docs/browsers#install-system-dependencies' in output @pytest.mark.parametrize("status", [200, 503]) diff --git a/tests/hermes_cli/test_tui_npm_install.py b/tests/hermes_cli/test_tui_npm_install.py index 58b20546c4..bebce4d6fd 100644 --- a/tests/hermes_cli/test_tui_npm_install.py +++ b/tests/hermes_cli/test_tui_npm_install.py @@ -166,21 +166,3 @@ def test_tui_rebuild_preserves_the_prepared_desktop_and_web_union(tui_source): assert acquired == ["npm", "npm"] assert (root / "node_modules/web").exists() assert (root / "node_modules/apps-desktop").exists() - - -@pytest.mark.platforms("posix") -@pytest.mark.parametrize("changed", ["ui-tui/src/entry.tsx", "package.json", "package-lock.json", "apps/shared/shared.ts"]) -def test_tui_rebuild_tracks_root_and_shared_inputs(tui_source, changed): - root, _ = tui_source - tui = root / "ui-tui" - changed_file = root / changed - changed_file.parent.mkdir(parents=True, exist_ok=True) - if not changed_file.exists(): - changed_file.write_text("original input\n", encoding="utf-8") - main_tui_launch._make_tui_argv(tui, tui_dev=False) - assert not main_tui_launch._tui_need_rebuild(tui), "must have a current receipt before invalidation" - before = changed_file.stat() - changed_file.write_text(changed_file.read_text(encoding="utf-8") + "\n", encoding="utf-8") - # A content change must invalidate even when mtimes are restored. - os.utime(changed_file, ns=(before.st_atime_ns, before.st_mtime_ns)) - assert main_tui_launch._tui_need_rebuild(tui) diff --git a/tests/hermes_cli/test_uninstall_install_kind.py b/tests/hermes_cli/test_uninstall_install_kind.py index 78b4d823b1..8da30658c8 100644 --- a/tests/hermes_cli/test_uninstall_install_kind.py +++ b/tests/hermes_cli/test_uninstall_install_kind.py @@ -137,24 +137,6 @@ def _make_home(tmp_path: Path) -> Path: return home -def test_run_data_uninstall_removes_data_keeps_code(monkeypatch, tmp_path): - home = _make_home(tmp_path) - monkeypatch.setattr(un, "get_hermes_home", lambda: home) - import hermes_cli.gui_uninstall as gu - - monkeypatch.setattr(gu, "desktop_userdata_dir", lambda: tmp_path / "electron-userdata-none") - - un.run_data_uninstall(SimpleNamespace(yes=True)) - - # Data gone. - assert not (home / "config.yaml").exists() - assert not (home / ".env").exists() - assert not (home / "sessions").exists() - assert not (home / "logs").exists() - # Code untouched — even on a sealed tree the data mode never touches it. - assert (home / "hermes-agent" / "hermes_cli" / "__init__.py").exists() - - def test_run_data_uninstall_removes_electron_userdata(monkeypatch, tmp_path): home = _make_home(tmp_path) userdata = tmp_path / "electron-userdata" diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.py index a36d6313ac..4cdb0f5563 100644 --- a/tests/hermes_cli/test_update_autostash.py +++ b/tests/hermes_cli/test_update_autostash.py @@ -1,579 +1,164 @@ +"""Real Git local-work safety: caller divergence, restore faults and rescue retention.""" from pathlib import Path -from subprocess import CalledProcessError -from types import SimpleNamespace +import subprocess from unittest.mock import patch import pytest -from hermes_cli import config as hermes_config -from hermes_cli import main as hermes_main -from hermes_cli import update_cmd +from hermes_cli import main as hermes_main, update_cmd +from tests.hermes_cli.test_update_target_identity import git, update_tree # noqa: F401 -@pytest.fixture(autouse=True) -def _patch_gateway_discovery(monkeypatch, isolated_source_completion): - """Keep cmd_update's gateway auto-restart phase off this machine's gateways. - - Tests in this file that reach the full success path (e.g. the #87694 - orphan-history rescue-ref tests) would otherwise hit real gateway - discovery: an unmocked ``find_gateway_pids`` on a box with a live gateway - reaches the conftest live-system guard and turns into a spurious - ``sys.exit(1)`` (#78574). Discovery returning nothing makes the phase a - clean no-op — none of the tests here assert on gateway restarts. - - ``_purge_stale_hermes_modules`` must also be stubbed: it evicts - ``hermes_cli.gateway`` from ``sys.modules`` mid-update, and the restart - phase's fresh ``from hermes_cli.gateway import ...`` then loads an - UNPATCHED copy of the module — silently discarding every mock here and - letting real gateway discovery (and real ``os.kill``) run on the dev box. - """ - monkeypatch.setattr(hermes_main, "_pause_windows_gateways_for_update", lambda: None) - monkeypatch.setattr(hermes_main, "_resume_windows_gateways_after_update", lambda *a: None) - monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None) - monkeypatch.setattr(update_cmd, "_prepare_updated_checkout", lambda *a, **kw: None) - monkeypatch.setattr("hermes_cli.update_cmd_maint._run_post_update_maintenance", lambda *a, **k: True) - with patch("hermes_cli.gateway.find_gateway_pids", return_value=[]), \ - patch("hermes_cli.gateway.supports_systemd_services", return_value=False), \ - patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]), \ - patch("hermes_cli.update_inventory.collect_runtime_inventory", return_value=None), \ - patch("hermes_cli.update_inventory.report_unaccounted_runtimes", return_value=False), \ - patch.object(hermes_main, "_fleet_probe_expected_runtimes", lambda *a, **kw: False), \ - patch.object(hermes_main, "_purge_stale_hermes_modules", lambda *a, **kw: None), \ - patch("hermes_cli.update_receipt.collect_fleet_versions", return_value=[]): - yield - - - - - - - - - - - - - -# --------------------------------------------------------------------------- -# Update orchestration fixtures -# --------------------------------------------------------------------------- - -def _setup_update_mocks(monkeypatch, tmp_path): - """Common setup for cmd_update tests.""" - (tmp_path / ".git").mkdir() - monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path) - monkeypatch.setattr(hermes_main, "_stash_local_changes_if_needed", lambda *a, **kw: None) - monkeypatch.setattr(hermes_main, "_restore_stashed_changes", lambda *a, **kw: True) - monkeypatch.setattr(hermes_config, "get_missing_env_vars", lambda required_only=True: []) - monkeypatch.setattr(hermes_config, "get_missing_config_fields", lambda: []) - monkeypatch.setattr(hermes_config, "check_config_version", lambda **_kwargs: (5, 5)) - monkeypatch.setattr(hermes_config, "migrate_config", lambda **kw: {"env_added": [], "config_added": []}) - - - - - - - - - - - - -# --------------------------------------------------------------------------- -# ff-only fallback to reset --hard on diverged history -# --------------------------------------------------------------------------- - -def _make_update_side_effect( - current_branch="main", - commit_count="3", - ff_only_fails=False, - reset_fails=False, - fetch_fails=False, - fetch_stderr="", - merge_base_exists=True, - update_ref_fails=False, - pre_pull_sha_unavailable=False, - existing_rescue_refs=None, +@pytest.mark.parametrize('history,failure,keep', [ + ('ordinary', None, False), ('ordinary', None, True), + ('ordinary', 'reset', False), ('ordinary', 'reset', True), + ('orphan', None, False), ('orphan', 'reset', False), + ('orphan', 'ref', False), ('orphan', 'head', False), +]) +def test_update_preserves_local_work_and_rescues_orphan_before_reset( + update_tree, monkeypatch, capsys, history, failure, keep, ): - """Build a subprocess.run side_effect for cmd_update tests. + t = update_tree + git(t.clone, 'checkout', '-q', 'main') + if history == 'orphan': + git(t.clone, 'checkout', '--orphan', 'fresh') + git(t.clone, 'branch', '-D', 'main') + git(t.clone, 'branch', '-m', 'main') + (t.clone / 'local.txt').write_text('committed\n', encoding='utf-8') + git(t.clone, 'add', 'local.txt') + git(t.clone, '-c', 'commit.gpgsign=false', 'commit', '-qm', 'local history') + before = git(t.clone, 'rev-parse', 'HEAD') + (t.clone / 'untracked.txt').write_text('local edit\n', encoding='utf-8') + t.args.channel, t.args.keep_stash = 'main', keep + monkeypatch.setattr(hermes_main, '_sync_with_upstream_if_needed', update_cmd._sync_with_upstream_if_needed) + monkeypatch.setattr(update_cmd, '_UPDATE_CRITICAL_MODULES', ()) + original = subprocess.run + resets = [] - ``merge_base_exists`` controls the ``git merge-base HEAD origin/`` - probe used by the ff-only-fallback orphan-history guard (#87694): True - (default) simulates ordinary divergence (a common ancestor exists, e.g. - upstream force-push), False simulates orphan/unrelated-history divergence - (no common ancestor at all). + def fault(command, *args, **kwargs): + if 'reset' in command and '--hard' in command: + refs = original(['git', 'for-each-ref', '--format=%(objectname)', + 'refs/hermes-update-backups/'], cwd=t.clone, + check=True, capture_output=True, text=True).stdout.split() + assert refs == ([before] if history == 'orphan' and failure not in {'ref', 'head'} else []) + resets.append(command) + if ((failure == 'ref' and 'update-ref' in command and '-d' not in command) + or (failure == 'reset' and 'reset' in command and '--hard' in command)): + return subprocess.CompletedProcess(command, 128, stdout='', stderr='fixture I/O refusal') + return original(command, *args, **kwargs) - ``update_ref_fails`` simulates ``git update-ref`` itself failing (disk - full, permissions) when writing the orphan rescue ref. - - ``pre_pull_sha_unavailable`` simulates ``_capture_head_sha`` being unable - to resolve HEAD before the pull (empty rev-parse output) — the rescue-ref - guard requires a truthy ``pre_pull_sha`` and must degrade gracefully - without one. - - ``existing_rescue_refs`` simulates the refs already present under - ``refs/hermes-update-backups/orphan--*`` (oldest first) so the - ``_prune_orphan_rescue_refs`` cleanup pass has something to trim. - """ - recorded = [] - head_sha_calls = [] - - def side_effect(cmd, **kwargs): - recorded.append(cmd) - joined = " ".join(str(c) for c in cmd) - if "fetch" in joined and "origin" in joined: - if fetch_fails: - return SimpleNamespace(stdout="", stderr=fetch_stderr, returncode=128) - return SimpleNamespace(stdout="", stderr="", returncode=0) - if "rev-parse" in joined and "--abbrev-ref" in joined: - return SimpleNamespace(stdout=f"{current_branch}\n", stderr="", returncode=0) - if "show-current" in joined: - return SimpleNamespace(stdout=f"{current_branch}\n", stderr="", returncode=0) - if "rev-parse" in joined and "HEAD" in joined: - # First call = pre-pull HEAD, every later call = post-pull HEAD - # (issue #79678's "did HEAD actually move" guard depends on these - # differing after a successful reset/merge). - head_sha_calls.append(1) - if len(head_sha_calls) == 1: - if pre_pull_sha_unavailable: - return SimpleNamespace(stdout="", stderr="", returncode=0) - return SimpleNamespace( - stdout="1111111111111111111111111111111111111beef\n", stderr="", returncode=0 - ) - return SimpleNamespace( - stdout="2222222222222222222222222222222222222cafe\n", stderr="", returncode=0 - ) - if "checkout" in joined and "main" in joined: - return SimpleNamespace(stdout="", stderr="", returncode=0) - if "rev-list" in joined: - return SimpleNamespace(stdout=f"{commit_count}\n", stderr="", returncode=0) - if "merge-base" in joined: - if merge_base_exists: - return SimpleNamespace(stdout="abc123deadbeef\n", stderr="", returncode=0) - return SimpleNamespace( - stdout="", stderr="fatal: Not a valid commit name origin/main\n", returncode=1 - ) - if "for-each-ref" in joined: - refs = existing_rescue_refs or [] - return SimpleNamespace(stdout="\n".join(refs) + ("\n" if refs else ""), stderr="", returncode=0) - if "update-ref" in joined and "-d" in cmd: - return SimpleNamespace(stdout="", stderr="", returncode=0) - if "update-ref" in joined: - if update_ref_fails: - return SimpleNamespace( - stdout="", stderr="fatal: unable to write ref\n", returncode=128 - ) - return SimpleNamespace(stdout="", stderr="", returncode=0) - if "--ff-only" in joined: - if ff_only_fails: - return SimpleNamespace( - stdout="", - stderr="fatal: Not possible to fast-forward, aborting.\n", - returncode=128, - ) - return SimpleNamespace(stdout="Updating abc..def\n", stderr="", returncode=0) - if "reset" in joined and "--hard" in joined: - if reset_fails: - return SimpleNamespace(stdout="", stderr="error: unable to write\n", returncode=1) - return SimpleNamespace(stdout="HEAD is now at abc123\n", stderr="", returncode=0) - return SimpleNamespace(returncode=0, stdout="", stderr="") - - return side_effect, recorded + monkeypatch.setattr(subprocess, 'run', fault) + if failure == 'head': + monkeypatch.setattr(update_cmd, '_capture_head_sha', lambda *_: None) + if failure == 'reset': + with pytest.raises(SystemExit) as error: + hermes_main.cmd_update(t.args) + assert error.value.code == 1 + assert not t.requests + assert git(t.clone, 'rev-parse', 'HEAD') == before + assert not (t.clone / 'untracked.txt').exists() + else: + hermes_main.cmd_update(t.args) + assert len(t.requests) == 1 + assert git(t.clone, 'rev-parse', 'HEAD') == t.newer + assert (t.clone / 'untracked.txt').exists() is (not keep) + assert len(resets) == 1 + stashes = git(t.clone, 'stash', 'list') + assert bool(stashes) is (keep or failure == 'reset') + if stashes: + assert git(t.clone, 'show', 'stash@{0}^3:untracked.txt') == 'local edit' + output = capsys.readouterr().out + if failure == 'ref': + assert 'backup write failed' in output and 'backed up current HEAD' not in output + if failure == 'reset': + assert 'preserved in stash' in output + if history == 'orphan' and failure not in {'ref', 'head'}: + assert f'expires after {update_cmd._ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days' in output -# --------------------------------------------------------------------------- -# Non-main branch → auto-checkout main -# --------------------------------------------------------------------------- - - -# --------------------------------------------------------------------------- -# Fetch failure — friendly error messages -# --------------------------------------------------------------------------- - - -# --------------------------------------------------------------------------- -# reset --hard failure — don't attempt stash restore -# --------------------------------------------------------------------------- - -def test_cmd_update_skips_stash_restore_when_reset_fails(monkeypatch, tmp_path, capsys): - """When reset --hard fails, stash restore is skipped with a helpful message.""" - _setup_update_mocks(monkeypatch, tmp_path) - # Re-enable stash so it actually returns a ref - monkeypatch.setattr( - hermes_main, "_stash_local_changes_if_needed", - lambda *a, **kw: "abc123deadbeef", - ) - restore_calls = [] - monkeypatch.setattr( - hermes_main, "_restore_stashed_changes", - lambda *a, **kw: restore_calls.append(1) or True, - ) - - side_effect, _ = _make_update_side_effect(ff_only_fails=True, reset_fails=True) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - with pytest.raises(SystemExit, match="1"): - hermes_main.cmd_update(SimpleNamespace()) - - # Stash restore should NOT have been called - assert len(restore_calls) == 0 - - out = capsys.readouterr().out - assert "preserved in stash" in out - - -# --------------------------------------------------------------------------- -# #87694: orphan/unrelated-history divergence must be backed up to a rescue -# ref before `reset --hard` discards it (ordinary divergence is unaffected). -# --------------------------------------------------------------------------- - -def test_cmd_update_orphan_history_backs_up_before_reset(monkeypatch, tmp_path, capsys): - """No common ancestor with origin/ → HEAD is parked behind a - ``refs/hermes-update-backups/orphan-*`` ref before the reset proceeds.""" - _setup_update_mocks(monkeypatch, tmp_path) - - side_effect, recorded = _make_update_side_effect( - ff_only_fails=True, merge_base_exists=False, - ) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - hermes_main.cmd_update(SimpleNamespace()) - - update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)] - assert len(update_ref_calls) == 1 - ref_name = update_ref_calls[0][update_ref_calls[0].index("update-ref") + 1] - assert ref_name.startswith("refs/hermes-update-backups/orphan-main-") - assert update_ref_calls[0][update_ref_calls[0].index("update-ref") + 2] == ( - "1111111111111111111111111111111111111beef" - ) - # Ref name carries the pre-pull SHA, not just a second-resolution - # timestamp, so two updates racing within the same second don't collide. - assert ref_name.endswith("-111111111111") - - out = capsys.readouterr().out - assert "orphan divergence" in out - assert ref_name in out - # The user is told the backup is temporary and when it expires. - assert f"expires after {update_cmd._ORPHAN_RESCUE_REF_MAX_AGE_DAYS} days" in out - - -def test_cmd_update_orphan_rescue_ref_write_failure_message_is_honest(monkeypatch, tmp_path, capsys): - """When ``git update-ref`` fails, the printed message must not claim a - backup exists — it should say the write was attempted and failed.""" - _setup_update_mocks(monkeypatch, tmp_path) - - side_effect, recorded = _make_update_side_effect( - ff_only_fails=True, merge_base_exists=False, update_ref_fails=True, - ) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - hermes_main.cmd_update(SimpleNamespace()) - - out = capsys.readouterr().out - assert "orphan divergence" in out - assert "backup write failed" in out - assert "backed up current HEAD" not in out - - -def test_cmd_update_orphan_rescue_refs_pruned_beyond_keep_limit(monkeypatch, tmp_path, capsys): - """Recent orphan rescue refs beyond the retention count are deleted so a - repeatedly corrupted install doesn't pin unbounded objects against gc.""" +@pytest.mark.parametrize('mode', ['count', 'age', 'unparseable']) +def test_rescue_retention_uses_real_refs(tmp_path, monkeypatch, mode): from datetime import datetime, timedelta, timezone - _setup_update_mocks(monkeypatch, tmp_path) - - # All refs are recent (within the age window) so only the count cap - # applies — the age-expiry path is exercised separately below. + git(tmp_path, 'init', '-q', '-b', 'main') + git(tmp_path, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', + '-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'base') now = datetime.now(timezone.utc) - total = update_cmd._ORPHAN_RESCUE_REFS_TO_KEEP + 2 - stale_refs = [ - "refs/hermes-update-backups/orphan-main-" - f"{(now - timedelta(hours=total - i)).strftime('%Y%m%d-%H%M%S')}-abc" - for i in range(total) - ] - side_effect, recorded = _make_update_side_effect( - ff_only_fails=True, merge_base_exists=False, existing_rescue_refs=stale_refs, - ) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - hermes_main.cmd_update(SimpleNamespace()) - - delete_calls = [ - c for c in recorded - if "update-ref" in " ".join(str(x) for x in c) and "-d" in c - ] - assert len(delete_calls) == total - update_cmd._ORPHAN_RESCUE_REFS_TO_KEEP - deleted_refs = {c[c.index("-d") + 1] for c in delete_calls} - assert deleted_refs == set(stale_refs[: total - update_cmd._ORPHAN_RESCUE_REFS_TO_KEEP]) + prefix = 'refs/hermes-update-backups/orphan-main-' + if mode == 'count': + refs = [prefix + (now - timedelta(hours=20-i)).strftime('%Y%m%d-%H%M%S') + '-abc' + for i in range(update_cmd._ORPHAN_RESCUE_REFS_TO_KEEP + 2)] + removed = set(refs[:2]) + elif mode == 'age': + refs = [prefix + '20200101-000000-abc', prefix + now.strftime('%Y%m%d-%H%M%S') + '-abc'] + removed = {refs[0]} + else: + refs, removed = [prefix + 'not-a-timestamp-abc'], set() + for ref in refs: + git(tmp_path, 'update-ref', ref, 'HEAD') + update_cmd._prune_orphan_rescue_refs(['git'], tmp_path, 'main') + assert set(git(tmp_path, 'for-each-ref', '--format=%(refname)', 'refs/hermes-update-backups/').splitlines()) == set(refs) - removed -def test_cmd_update_orphan_rescue_refs_expired_by_age(monkeypatch, tmp_path, capsys): - """Rescue refs older than the max-age window are deleted even when the - count cap alone would have kept them — the age expiry is what bounds a - multi-GB snapshot's lifetime for a user who never runs another orphan - incident past the count cap.""" - from datetime import datetime, timedelta, timezone +@pytest.mark.parametrize('fault,body,modules,message', [ + ('syntax', '<<<<<<< Updated upstream\nVALUE = 2\n', (), 'made the Hermes agent unexecutable'), + ('import', "raise RuntimeError('restored local failure')\n", ('consumer',), 'restored local failure'), + ('preexisting', 'VALUE = 2\n', ('first',), None), + ('later', "raise RuntimeError('restored later failure')\n", ('first', 'consumer'), 'restored later failure'), + ('exit', "raise SystemExit('restored exit')\n", ('first', 'consumer'), 'restored exit'), + ('terminated', 'import os\nos._exit(7)\n', ('consumer',), 'exit code 7'), + ('paths', 'VALUE = 2\n', (), 'restored Python source discovery'), +]) +def test_restore_validates_real_stash_and_each_import(tmp_path, monkeypatch, capsys, fault, body, modules, message): + import hermes_cli.update_cmd_stash as stash - _setup_update_mocks(monkeypatch, tmp_path) - - now = datetime.now(timezone.utc) - old = now - timedelta(days=update_cmd._ORPHAN_RESCUE_REF_MAX_AGE_DAYS + 5) - fresh = now - timedelta(days=1) - expired_ref = ( - "refs/hermes-update-backups/orphan-main-" - f"{old.strftime('%Y%m%d-%H%M%S')}-old1" - ) - fresh_ref = ( - "refs/hermes-update-backups/orphan-main-" - f"{fresh.strftime('%Y%m%d-%H%M%S')}-new1" - ) - side_effect, recorded = _make_update_side_effect( - ff_only_fails=True, merge_base_exists=False, - existing_rescue_refs=[expired_ref, fresh_ref], - ) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - hermes_main.cmd_update(SimpleNamespace()) - - delete_calls = [ - c for c in recorded - if "update-ref" in " ".join(str(x) for x in c) and "-d" in c - ] - deleted_refs = {c[c.index("-d") + 1] for c in delete_calls} - assert deleted_refs == {expired_ref} + git(tmp_path, 'init', '-q', '-b', 'main') + (tmp_path / 'first.py').write_text("raise RuntimeError('missing local config')\n", encoding='utf-8') + source = tmp_path / 'consumer.py' + source.write_text('VALUE = 1\n', encoding='utf-8') + git(tmp_path, 'add', 'first.py', 'consumer.py') + git(tmp_path, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', + '-c', 'commit.gpgsign=false', 'commit', '-qm', 'base') + source.write_text(body, encoding='utf-8') + ref = hermes_main._stash_local_changes_if_needed(['git'], tmp_path) + assert ref + monkeypatch.setattr(update_cmd, '_UPDATE_CRITICAL_MODULES', modules) + if fault == 'paths': + monkeypatch.setattr(stash, '_restored_python_paths', lambda *_: None) + monkeypatch.setattr(update_cmd, '_restored_python_paths', lambda *_: None) + if message is None: + assert hermes_main._restore_stashed_changes(['git'], tmp_path, ref, prompt_user=False) + assert source.read_text(encoding='utf-8') == body + assert not git(tmp_path, 'stash', 'list') + else: + with pytest.raises(SystemExit) as error: + hermes_main._restore_stashed_changes(['git'], tmp_path, ref, prompt_user=False) + assert error.value.code == 1 + assert source.read_text(encoding='utf-8') == 'VALUE = 1\n' + assert not git(tmp_path, 'status', '--porcelain') + assert git(tmp_path, 'stash', 'list') + output = capsys.readouterr().out + assert message in output and 'gateway was not restarted' in output + assert f'git stash apply {ref}' in output -def test_prune_orphan_rescue_refs_leaves_unparseable_names_alone(): - """A ref whose timestamp segment doesn't parse must never be age-deleted - (it can still fall to the count cap, but not to a guessed age).""" - from types import SimpleNamespace as NS - from unittest.mock import patch as mock_patch - - weird = "refs/hermes-update-backups/orphan-main-not-a-timestamp-xyz" - calls = [] - - def fake_run(cmd, **kwargs): - calls.append(cmd) - if "for-each-ref" in cmd: - return NS(stdout=weird + "\n", stderr="", returncode=0) - return NS(stdout="", stderr="", returncode=0) - - with mock_patch.object(hermes_main.subprocess, "run", side_effect=fake_run): - update_cmd._prune_orphan_rescue_refs(["git"], ".", "main") - - delete_calls = [c for c in calls if "update-ref" in c and "-d" in c] - assert delete_calls == [] +@pytest.mark.parametrize('error', [EOFError(), UnicodeDecodeError('utf-8', b'\xff', 0, 1, 'invalid')]) +def test_unreadable_stash_prompt_keeps_work(tmp_path, monkeypatch, capsys, error): + def unreadable(*_): + raise error + monkeypatch.setattr('builtins.input', unreadable) + assert hermes_main._restore_stashed_changes(['git'], tmp_path, 'stash@{0}', prompt_user=True) is False + assert 'git stash apply stash@{0}' in capsys.readouterr().out -def test_cmd_update_ordinary_divergence_skips_rescue_ref(monkeypatch, tmp_path, capsys): - """Common ancestor still exists (e.g. upstream force-push) → no rescue - ref, no orphan messaging, behavior identical to before #87694.""" - _setup_update_mocks(monkeypatch, tmp_path) - - side_effect, recorded = _make_update_side_effect( - ff_only_fails=True, merge_base_exists=True, - ) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - hermes_main.cmd_update(SimpleNamespace()) - - update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)] - assert update_ref_calls == [] - - out = capsys.readouterr().out - assert "orphan divergence" not in out - assert "Fast-forward not possible (history diverged), resetting to match remote" in out - - -def test_cmd_update_orphan_rescue_ref_write_failure_is_non_fatal(monkeypatch, tmp_path, capsys): - """#87694 stress test: ``git update-ref`` itself fails (disk full, - permissions) while parking the orphan rescue ref. The backup attempt is - best-effort — so the reset must still proceed and the update succeed.""" - _setup_update_mocks(monkeypatch, tmp_path) - - side_effect, recorded = _make_update_side_effect( - ff_only_fails=True, merge_base_exists=False, update_ref_fails=True, - ) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - hermes_main.cmd_update(SimpleNamespace()) - - update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)] - assert len(update_ref_calls) == 1 - - reset_calls = [ - c for c in recorded if "reset" in " ".join(str(x) for x in c) and "--hard" in c - ] - assert len(reset_calls) == 1 - - out = capsys.readouterr().out - assert "orphan divergence" in out - - -def test_cmd_update_orphan_guard_skips_rescue_ref_when_pre_pull_sha_missing( - monkeypatch, tmp_path, capsys -): - """#87694 stress test: if capturing the pre-pull HEAD SHA itself fails - (empty ``rev-parse HEAD`` output), the rescue-ref guard requires a - truthy ``pre_pull_sha`` and must skip the backup rather than writing a - ref pointing at nothing — the reset must still proceed without crashing. - """ - _setup_update_mocks(monkeypatch, tmp_path) - - side_effect, recorded = _make_update_side_effect( - ff_only_fails=True, merge_base_exists=False, pre_pull_sha_unavailable=True, - ) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - hermes_main.cmd_update(SimpleNamespace()) - - update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)] - assert update_ref_calls == [] - - out = capsys.readouterr().out - assert "orphan divergence" not in out - - -def test_cmd_update_orphan_rescue_ref_persists_when_reset_fails(monkeypatch, tmp_path, capsys): - """#87694 stress test: even when the subsequent ``reset --hard`` itself - fails, the rescue ref must already have been written — the backup is - not lost just because the overall update aborts.""" - _setup_update_mocks(monkeypatch, tmp_path) - - side_effect, recorded = _make_update_side_effect( - ff_only_fails=True, merge_base_exists=False, reset_fails=True, - ) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - with pytest.raises(SystemExit) as exc_info: - hermes_main.cmd_update(SimpleNamespace()) - assert exc_info.value.code == 1 - - update_ref_calls = [c for c in recorded if "update-ref" in " ".join(str(x) for x in c)] - assert len(update_ref_calls) == 1 - - out = capsys.readouterr().out - assert "orphan divergence" in out - assert "Failed to reset to origin/main" in out - - -# --------------------------------------------------------------------------- -# Non-interactive update.non_interactive_local_changes setting -# (chat app / gateway): "discard" throws stashed changes away, "stash" -# (default) restores them. Interactive terminal updates ignore the setting -# and always go through the restore path. -# --------------------------------------------------------------------------- - -def _setup_setting_test(monkeypatch, tmp_path, mode): - """Common wiring: real stash returns a ref, restore + discard are - recorded, and load_config reports the given non_interactive_local_changes - mode.""" - _setup_update_mocks(monkeypatch, tmp_path) - monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/uv" if name == "uv" else None) - monkeypatch.setattr( - hermes_main, "_stash_local_changes_if_needed", - lambda *a, **kw: "abc123deadbeef", - ) - restore_calls = [] - discard_calls = [] - monkeypatch.setattr( - hermes_main, "_restore_stashed_changes", - lambda *a, **kw: restore_calls.append(1) or True, - ) - monkeypatch.setattr( - hermes_main, "_discard_stashed_changes", - lambda *a, **kw: discard_calls.append(1) or True, - ) - monkeypatch.setattr( - hermes_config, "load_config", - lambda *a, **kw: {"updates": {"non_interactive_local_changes": mode}}, - ) - side_effect, recorded = _make_update_side_effect() - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - return restore_calls, discard_calls, recorded - - -# --------------------------------------------------------------------------- -# --keep-stash (desktop updater): stash for the update, never re-apply. -# --------------------------------------------------------------------------- - -def _setup_keep_stash_test(monkeypatch, tmp_path): - """Wiring for --keep-stash tests: stash returns a ref; restore, discard, - and park are all recorded.""" - _setup_update_mocks(monkeypatch, tmp_path) - monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/uv" if name == "uv" else None) - monkeypatch.setattr( - hermes_main, "_stash_local_changes_if_needed", - lambda *a, **kw: "abc123deadbeef", - ) - restore_calls = [] - discard_calls = [] - park_calls = [] - monkeypatch.setattr( - hermes_main, "_restore_stashed_changes", - lambda *a, **kw: restore_calls.append(1) or True, - ) - monkeypatch.setattr( - hermes_main, "_discard_stashed_changes", - lambda *a, **kw: discard_calls.append(1) or True, - ) - monkeypatch.setattr( - hermes_main, "_park_stashed_changes", - lambda *a, **kw: park_calls.append(a) or None, - ) - # Keep the update flow away from the real gateway fleet on this machine — - # a live gateway PID would trip the test-suite kill guard and turn the - # run into exit 1 (gateway_fleet_restart_incomplete). - monkeypatch.setattr( - "hermes_cli.gateway.find_gateway_pids", lambda **kw: [], raising=False - ) - return restore_calls, discard_calls, park_calls - - -def test_update_keep_stash_parks_instead_of_restoring(monkeypatch, tmp_path): - """--keep-stash: after a successful update, the autostash is parked (left - in git stash) — never re-applied, never discarded.""" - restore_calls, discard_calls, park_calls = _setup_keep_stash_test(monkeypatch, tmp_path) - side_effect, _ = _make_update_side_effect() - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - hermes_main.cmd_update(SimpleNamespace(yes=True, keep_stash=True)) - - assert len(park_calls) == 1 - assert park_calls[0][0] == "abc123deadbeef" - assert restore_calls == [] - assert discard_calls == [] - - -def test_update_without_keep_stash_still_restores(monkeypatch, tmp_path): - """Regression guard: default behavior (no --keep-stash) is unchanged — - the autostash is auto-restored under --yes.""" - restore_calls, discard_calls, park_calls = _setup_keep_stash_test(monkeypatch, tmp_path) - side_effect, _ = _make_update_side_effect() - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - hermes_main.cmd_update(SimpleNamespace(yes=True, keep_stash=False)) - - assert restore_calls == [1] - assert park_calls == [] - assert discard_calls == [] - - -def test_update_keep_stash_failure_path_still_preserves(monkeypatch, tmp_path, capsys): - """--keep-stash + failed update: neither restore nor park runs; the - existing preserved-in-stash message fires (working tree unknown).""" - restore_calls, discard_calls, park_calls = _setup_keep_stash_test(monkeypatch, tmp_path) - side_effect, _ = _make_update_side_effect(ff_only_fails=True, reset_fails=True) - monkeypatch.setattr(hermes_main.subprocess, "run", side_effect) - - with pytest.raises(SystemExit, match="1"): - hermes_main.cmd_update(SimpleNamespace(yes=True, keep_stash=True)) - - assert restore_calls == [] - assert park_calls == [] - assert discard_calls == [] - assert "preserved in stash" in capsys.readouterr().out +def test_unreadable_upstream_prompt_does_not_add_remote(tmp_path, monkeypatch): + git(tmp_path, 'init', '-q', '-b', 'main') + def unreadable(*_): + raise UnicodeDecodeError('utf-8', b'\xff', 0, 1, 'invalid') + monkeypatch.setattr('builtins.input', unreadable) + monkeypatch.setattr(update_cmd, '_should_skip_upstream_prompt', lambda *_: False) + update_cmd._sync_with_upstream_if_needed(['git'], tmp_path) + assert not git(tmp_path, 'remote') def test_update_parser_accepts_keep_stash(): @@ -593,9 +178,6 @@ def test_update_parser_accepts_keep_stash(): - - - def test_bootstrap_marker_not_autostashed_by_update(tmp_path): """#38529: the Desktop bootstrap marker must be git-ignored so that ``hermes update``'s ``git stash push --include-untracked`` does not sweep it @@ -643,15 +225,6 @@ def test_bootstrap_marker_not_autostashed_by_update(tmp_path): assert ".hermes-bootstrap-complete" not in status -# --------------------------------------------------------------------------- -# Permission-denied autostash class: undeletable untracked files (root-owned -# packaging/ etc.) must not abort the update when the stash entry was created. -# --------------------------------------------------------------------------- - - - - - def test_update_autostash_survives_undeletable_untracked_dir(tmp_path): """Behavioral E2E of the whole permission-denied class with real git: @@ -702,267 +275,6 @@ def test_update_autostash_survives_undeletable_untracked_dir(tmp_path): os.chmod(pkg, 0o755) -def test_restore_rejects_invalid_python_and_keeps_clean_updated_tree( - monkeypatch, tmp_path, capsys -): - """A cleanly-applied stash must not be allowed to brick every agent turn.""" - import subprocess - from hermes_cli import update_cmd - - def git(*args, check=True): - return subprocess.run( - ["git", *args], - cwd=tmp_path, - capture_output=True, - text=True, - check=check, - ) - - git("init", "-q", "-b", "main") - git("config", "user.email", "t@example.com") - git("config", "user.name", "t") - source = tmp_path / "tools" / "terminal_tool.py" - source.parent.mkdir() - source.write_text("VALUE = 1\n", encoding="utf-8") - git("add", "-A") - git("commit", "-qm", "init") - - source.write_text("<<<<<<< Updated upstream\nVALUE = 2\n", encoding="utf-8") - stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path) - assert stash_ref - monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ()) - - with pytest.raises(SystemExit) as exc_info: - hermes_main._restore_stashed_changes( - ["git"], tmp_path, stash_ref, prompt_user=False - ) - - assert exc_info.value.code == 1 - assert source.read_text(encoding="utf-8") == "VALUE = 1\n" - assert git("status", "--porcelain").stdout == "" - assert git("stash", "list").stdout.strip() - output = capsys.readouterr().out - assert "made the Hermes agent unexecutable" in output - assert "gateway was not restarted" in output - assert f"git stash apply {stash_ref}" in output - - -def test_restore_rejects_new_import_time_failure_and_preserves_stash( - monkeypatch, tmp_path, capsys -): - """A valid-Python stash must not introduce a critical import failure.""" - import subprocess - from hermes_cli import update_cmd - - def git(*args, check=True): - return subprocess.run( - ["git", *args], - cwd=tmp_path, - capture_output=True, - text=True, - check=check, - ) - - git("init", "-q", "-b", "main") - git("config", "user.email", "t@example.com") - git("config", "user.name", "t") - source = tmp_path / "consumer.py" - source.write_text("VALUE = 1\n", encoding="utf-8") - git("add", "-A") - git("commit", "-qm", "init") - - source.write_text("raise RuntimeError('restored local failure')\n", encoding="utf-8") - stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path) - assert stash_ref - monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",)) - - with pytest.raises(SystemExit) as exc_info: - hermes_main._restore_stashed_changes( - ["git"], tmp_path, stash_ref, prompt_user=False - ) - - assert exc_info.value.code == 1 - assert source.read_text(encoding="utf-8") == "VALUE = 1\n" - assert git("status", "--porcelain").stdout == "" - assert git("stash", "list").stdout.strip() - output = capsys.readouterr().out - assert "agent import consumer" in output - assert "restored local failure" in output - assert "gateway was not restarted" in output - - -def test_restore_allows_preexisting_import_time_failure(monkeypatch, tmp_path): - """A restore may proceed when it does not worsen an environment failure.""" - import subprocess - from hermes_cli import update_cmd - - def git(*args, check=True): - return subprocess.run( - ["git", *args], - cwd=tmp_path, - capture_output=True, - text=True, - check=check, - ) - - git("init", "-q", "-b", "main") - git("config", "user.email", "t@example.com") - git("config", "user.name", "t") - (tmp_path / "consumer.py").write_text( - "raise RuntimeError('missing local config')\n", encoding="utf-8" - ) - local_file = tmp_path / "local.txt" - local_file.write_text("original\n", encoding="utf-8") - git("add", "-A") - git("commit", "-qm", "init") - - local_file.write_text("restored\n", encoding="utf-8") - stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path) - assert stash_ref - monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",)) - - assert hermes_main._restore_stashed_changes( - ["git"], tmp_path, stash_ref, prompt_user=False - ) - assert local_file.read_text(encoding="utf-8") == "restored\n" - assert git("stash", "list").stdout.strip() == "" - - -def test_restore_rejects_later_failure_masked_by_preexisting_failure( - monkeypatch, tmp_path, capsys -): - """Every critical module must be compared, not only the first failure.""" - import subprocess - from hermes_cli import update_cmd - - def git(*args, check=True): - return subprocess.run( - ["git", *args], - cwd=tmp_path, - capture_output=True, - text=True, - check=check, - ) - - git("init", "-q", "-b", "main") - git("config", "user.email", "t@example.com") - git("config", "user.name", "t") - (tmp_path / "first.py").write_text( - "raise RuntimeError('missing local config')\n", encoding="utf-8" - ) - second = tmp_path / "second.py" - second.write_text("VALUE = 1\n", encoding="utf-8") - git("add", "-A") - git("commit", "-qm", "init") - - second.write_text("raise RuntimeError('restored later failure')\n", encoding="utf-8") - stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path) - assert stash_ref - monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("first", "second")) - - with pytest.raises(SystemExit) as exc_info: - hermes_main._restore_stashed_changes( - ["git"], tmp_path, stash_ref, prompt_user=False - ) - - assert exc_info.value.code == 1 - assert second.read_text(encoding="utf-8") == "VALUE = 1\n" - assert git("status", "--porcelain").stdout == "" - assert git("stash", "list").stdout.strip() - output = capsys.readouterr().out - assert "agent import second" in output - assert "restored later failure" in output - assert "gateway was not restarted" in output - - -def test_restore_rejects_system_exit_masked_by_preexisting_failure( - monkeypatch, tmp_path, capsys -): - """A terminating import must be compared instead of hiding the marker.""" - import subprocess - from hermes_cli import update_cmd - - def git(*args, check=True): - return subprocess.run( - ["git", *args], - cwd=tmp_path, - capture_output=True, - text=True, - check=check, - ) - - git("init", "-q", "-b", "main") - git("config", "user.email", "t@example.com") - git("config", "user.name", "t") - (tmp_path / "first.py").write_text( - "raise RuntimeError('missing local config')\n", encoding="utf-8" - ) - second = tmp_path / "second.py" - second.write_text("VALUE = 1\n", encoding="utf-8") - git("add", "-A") - git("commit", "-qm", "init") - - second.write_text("raise SystemExit('restored exit')\n", encoding="utf-8") - stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path) - assert stash_ref - monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("first", "second")) - - with pytest.raises(SystemExit) as exc_info: - hermes_main._restore_stashed_changes( - ["git"], tmp_path, stash_ref, prompt_user=False - ) - - assert exc_info.value.code == 1 - assert second.read_text(encoding="utf-8") == "VALUE = 1\n" - assert git("status", "--porcelain").stdout == "" - assert git("stash", "list").stdout.strip() - output = capsys.readouterr().out - assert "agent import second" in output - assert "restored exit" in output - assert "gateway was not restarted" in output - - -def test_restore_rejects_probe_termination(monkeypatch, tmp_path, capsys): - """A stash cannot bypass import validation by terminating the probe.""" - import subprocess - from hermes_cli import update_cmd - - def git(*args, check=True): - return subprocess.run( - ["git", *args], - cwd=tmp_path, - capture_output=True, - text=True, - check=check, - ) - - git("init", "-q", "-b", "main") - git("config", "user.email", "t@example.com") - git("config", "user.name", "t") - source = tmp_path / "consumer.py" - source.write_text("VALUE = 1\n", encoding="utf-8") - git("add", "-A") - git("commit", "-qm", "init") - - source.write_text("import os\nos._exit(7)\n", encoding="utf-8") - stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path) - assert stash_ref - monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",)) - - with pytest.raises(SystemExit) as exc_info: - hermes_main._restore_stashed_changes( - ["git"], tmp_path, stash_ref, prompt_user=False - ) - - assert exc_info.value.code == 1 - assert source.read_text(encoding="utf-8") == "VALUE = 1\n" - assert git("status", "--porcelain").stdout == "" - assert git("stash", "list").stdout.strip() - output = capsys.readouterr().out - assert "critical-module probe" in output - assert "exit code 7" in output - assert "gateway was not restarted" in output - def test_restore_stays_parked_when_untracked_baseline_is_unknown( monkeypatch, tmp_path, capsys @@ -984,6 +296,7 @@ def test_restore_stays_parked_when_untracked_baseline_is_unknown( assert "git stash apply stash@{0}" in output + def test_reject_does_not_claim_cleanup_when_git_state_is_unknown( monkeypatch, tmp_path, capsys ): @@ -1004,50 +317,6 @@ def test_reject_does_not_claim_cleanup_when_git_state_is_unknown( assert "The clean updated tree has been restored" not in output -def test_restore_rejects_unknown_restored_python_paths( - monkeypatch, tmp_path, capsys -): - """A failed post-apply path query cannot skip restored syntax validation.""" - import subprocess - from hermes_cli import update_cmd - import hermes_cli.update_cmd_stash as update_cmd_stash - - def git(*args, check=True): - return subprocess.run( - ["git", *args], - cwd=tmp_path, - capture_output=True, - text=True, - check=check, - ) - - git("init", "-q", "-b", "main") - git("config", "user.email", "t@example.com") - git("config", "user.name", "t") - source = tmp_path / "consumer.py" - source.write_text("VALUE = 1\n", encoding="utf-8") - git("add", "-A") - git("commit", "-qm", "init") - source.write_text("VALUE = 2\n", encoding="utf-8") - stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path) - assert stash_ref - monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ()) - monkeypatch.setattr(update_cmd, "_restored_python_paths", lambda *_args: None) - monkeypatch.setattr(update_cmd_stash, "_restored_python_paths", lambda *_args: None) - - with pytest.raises(SystemExit) as exc_info: - hermes_main._restore_stashed_changes( - ["git"], tmp_path, stash_ref, prompt_user=False - ) - - assert exc_info.value.code == 1 - assert source.read_text(encoding="utf-8") == "VALUE = 1\n" - assert git("status", "--porcelain").stdout == "" - assert git("stash", "list").stdout.strip() - output = capsys.readouterr().out - assert "restored Python source discovery" in output - assert "gateway was not restarted" in output - def test_gateway_restore_prompt_defaults_to_keep_stash(tmp_path, capsys): prompts = [] @@ -1065,74 +334,6 @@ def test_gateway_restore_prompt_defaults_to_keep_stash(tmp_path, capsys): assert "still preserved in git stash" in capsys.readouterr().out -# --------------------------------------------------------------------------- -# #87694: real-git sanity check for the merge-base premise the orphan guard -# relies on — two independently-initialized repos (no shared history) must -# report no merge-base, while an ordinary branch divergence must report one. -# --------------------------------------------------------------------------- - -def test_merge_base_detects_orphan_vs_ordinary_divergence_with_real_git(tmp_path): - """Anchors the assumption behind the #87694 orphan-history guard: `git - merge-base` fails/empties on truly unrelated histories, and succeeds on - ordinary (e.g. force-pushed) divergence. If a future git version changes - this contract, this test breaks instead of the guard silently going - inert.""" - import shutil - import subprocess - - if shutil.which("git") is None: - pytest.skip("git not available") - - def git(cwd, *args, check=True): - return subprocess.run( - ["git", *args], cwd=cwd, capture_output=True, text=True, check=check - ) - - # Ordinary divergence: two branches of the SAME repo, one reset to an - # earlier point then given a new commit (simulates an upstream force-push). - ordinary = tmp_path / "ordinary" - ordinary.mkdir() - git(ordinary, "init", "-q", "-b", "main") - git(ordinary, "config", "user.email", "t@example.com") - git(ordinary, "config", "user.name", "t") - (ordinary / "f.txt").write_text("v1\n") - git(ordinary, "add", "-A") - git(ordinary, "commit", "-qm", "init") - git(ordinary, "checkout", "-qb", "origin-main") - (ordinary / "f.txt").write_text("v2\n") - git(ordinary, "add", "-A") - git(ordinary, "commit", "-qm", "upstream") - git(ordinary, "checkout", "-q", "main") - result = git(ordinary, "merge-base", "HEAD", "origin-main", check=False) - assert result.returncode == 0 - assert result.stdout.strip() - - # Orphan divergence: two independently-init'd repos wired as remotes, - # sharing zero history. - orphan = tmp_path / "orphan" - orphan.mkdir() - git(orphan, "init", "-q", "-b", "main") - git(orphan, "config", "user.email", "t@example.com") - git(orphan, "config", "user.name", "t") - (orphan / "f.txt").write_text("local\n") - git(orphan, "add", "-A") - git(orphan, "commit", "-qm", "local init") - - remote = tmp_path / "orphan-remote" - remote.mkdir() - git(remote, "init", "-q", "-b", "main") - git(remote, "config", "user.email", "t@example.com") - git(remote, "config", "user.name", "t") - (remote / "f.txt").write_text("remote\n") - git(remote, "add", "-A") - git(remote, "commit", "-qm", "remote init") - - git(orphan, "remote", "add", "origin", str(remote)) - git(orphan, "fetch", "-q", "origin") - result = git(orphan, "merge-base", "HEAD", "origin/main", check=False) - assert result.returncode != 0 - assert not result.stdout.strip() - def test_prune_orphan_rescue_refs_with_real_git_unpins_objects(tmp_path): """End-to-end with real git: an orphan rescue ref pins a snapshot's diff --git a/tests/hermes_cli/test_update_channel.py b/tests/hermes_cli/test_update_channel.py index ea3edceb95..6d6f7a3d5c 100644 --- a/tests/hermes_cli/test_update_channel.py +++ b/tests/hermes_cli/test_update_channel.py @@ -71,11 +71,6 @@ class TestInstallId: class TestResolve: - def test_per_install_record_wins(self, tmp_path): - root = tmp_path / "install" - _stamp(root, "self") - config = _config_for(root, "stable") - assert resolve_update_channel(config, root) == CHANNEL_STABLE def test_multi_install_isolation(self, tmp_path): """Two installs, one config: each resolves its own record and a @@ -88,80 +83,33 @@ class TestResolve: assert resolve_update_channel(config, a) == CHANNEL_STABLE assert resolve_update_channel(config, b) == CHANNEL_MAIN - def test_defaults_by_mechanism(self, tmp_path): - source = tmp_path / "src" - bundle = tmp_path / "bundle" - _stamp(source, "self") - _stamp(bundle, "electron-updater", tag="v0.27.0") - assert default_channel(source) == CHANNEL_MAIN - assert default_channel(bundle) == CHANNEL_STABLE - assert resolve_update_channel({}, source) == CHANNEL_MAIN - assert resolve_update_channel({}, bundle) == CHANNEL_STABLE - - @pytest.mark.parametrize("mechanism", ["electron-updater", "app-installer", "microsoft-store"]) - def test_canary_artifact_defaults_to_its_own_feed(self, tmp_path, mechanism): - """A canary bundle with no per-install record tracks canary. - - The artifact publishes to canary.yml (product-identity.cjs keys the - feed on this same tag). Defaulting it to stable made the updater ask - for canary.yml under the newest STABLE release, which 404s and - leaves a fresh canary install unable to update at all. - """ - root = tmp_path / "canary-bundle" - _stamp(root, mechanism, tag="v0.28.0-canary.20260819171926") - assert default_channel(root) == CHANNEL_CANARY - assert resolve_update_channel({}, root) == CHANNEL_CANARY - - def test_legacy_date_only_canary_tag_is_a_canary(self, tmp_path): - root = tmp_path / "legacy-canary" - _stamp(root, "electron-updater", tag="v0.28.0-canary.20260818") - assert default_channel(root) == CHANNEL_CANARY - - def test_artifact_channel_ignores_obsolete_record(self, tmp_path): - """A record cannot change a separately installed package identity.""" - root = tmp_path / "canary-bundle" - _stamp(root, "electron-updater", tag="v0.28.0-canary.20260819171926") - assert resolve_update_channel(_config_for(root, "stable"), root) == CHANNEL_CANARY - - def test_a_canary_tag_on_a_source_install_is_not_a_canary_channel(self, tmp_path): - """Only electron-updater bundles have release feeds to track.""" - root = tmp_path / "src" - _stamp(root, "self", tag="v0.28.0-canary.20260819171926") - assert default_channel(root) == CHANNEL_MAIN - - def test_stampless_tree_defaults_to_main(self, tmp_path): - root = tmp_path / "bare" - root.mkdir() - assert resolve_update_channel({}, root) == CHANNEL_MAIN - - def test_canary_remains_a_release_channel_for_source(self, tmp_path): - root = tmp_path / "src" - _stamp(root, "self") - config = _config_for(root, "canary") - assert resolve_update_channel(config, root) == CHANNEL_CANARY - - def test_stable_bundle_ignores_canary_record(self, tmp_path): - root = tmp_path / "bundle" - _stamp(root, "electron-updater") - config = _config_for(root, "canary") - assert resolve_update_channel(config, root) == CHANNEL_STABLE - - @pytest.mark.parametrize("payload", ["bundled", "light"]) - @pytest.mark.parametrize("channel, tag", [ - ("stable", "v1.2.3"), ("canary", "v1.2.4-canary.20260911125822"), + @pytest.mark.parametrize('mechanism,tag,payload,record,expected', [ + ('self', None, None, None, 'main'), + ('self', 'v1.2.3-canary.20260818', None, None, 'main'), + (None, None, None, None, 'main'), + ('self', None, None, 'canary', 'canary'), + ('self', None, None, 'yolo', 'main'), + ('electron-updater', 'v1.2.3', None, None, 'stable'), + ('electron-updater', 'v1.2.3-canary.20260819171926', None, 'stable', 'canary'), + ('app-installer', 'v1.2.3-canary.20260819171926', None, None, 'canary'), + ('microsoft-store', 'v1.2.3-canary.20260819171926', None, None, 'canary'), + ('electron-updater', 'v1.2.3-canary.20260818', None, None, 'canary'), + ('electron-updater', None, None, 'canary', 'stable'), + ('external', 'v1.2.3', 'bundled', 'main', 'stable'), + ('external', 'v1.2.3', 'light', 'main', 'stable'), + ('external', 'v1.2.4-canary.20260911125822', 'bundled', 'main', 'canary'), + ('external', 'v1.2.4-canary.20260911125822', 'light', 'main', 'canary'), ]) - def test_external_packages_ignore_source_channel_records(self, tmp_path, payload, channel, tag): - (tmp_path / "install-stamp.json").write_text(json.dumps({ - "payload": payload, "updateMechanism": "external", "tag": tag, - })) - assert resolve_update_channel(_config_for(tmp_path, "main"), tmp_path) == channel - assert default_channel(tmp_path) == channel - - def test_garbage_record_falls_to_default(self, tmp_path): - root = tmp_path / "src" - _stamp(root, "self") - config = _config_for(root, "yolo") - assert resolve_update_channel(config, root) == CHANNEL_MAIN + def test_channel_policy(self, tmp_path, mechanism, tag, payload, record, expected): + if mechanism is not None: + stamp = {'updateMechanism': mechanism, 'tag': tag} + if payload: + stamp['payload'] = payload + (tmp_path / 'install-stamp.json').write_text(json.dumps(stamp), encoding='utf-8') + config = _config_for(tmp_path, record) if record else {} + assert resolve_update_channel(config, tmp_path) == expected + if not (mechanism == 'self' and record == 'canary'): + assert default_channel(tmp_path) == expected class TestSetChannel: @@ -188,55 +136,7 @@ class TestSetChannel: assert record["path"] == str(root) assert resolve_update_channel(written, root) == channel - def test_preserves_other_config_and_other_installs(self, tmp_path, monkeypatch): - import hermes_yaml as yaml - home = self._home(tmp_path, monkeypatch) - other = tmp_path / "other" - other.mkdir() - (home / "config.yaml").write_text( - yaml.safe_dump( - { - "model": {"provider": "nous"}, - "update": { - "installs": { - install_id(other): {"path": str(other), "channel": "canary"} - } - }, - } - ) - ) - root = tmp_path / "install" - _stamp(root, "self") - set_install_channel("stable", root) - - written = yaml.safe_load((home / "config.yaml").read_text()) - assert written["model"] == {"provider": "nous"} - assert written["update"]["installs"][install_id(other)]["channel"] == "canary" - assert written["update"]["installs"][install_id(root)]["channel"] == "stable" - - def test_preserves_comments_in_config(self, tmp_path, monkeypatch): - """Persisting a channel must not strip user comments from - config.yaml — the write goes through the shared comment-preserving - atomic round-trip writer.""" - home = self._home(tmp_path, monkeypatch) - (home / "config.yaml").write_text( - "# my hand-maintained settings\n" - "model:\n" - " provider: nous # keep this\n" - ) - root = tmp_path / "install" - _stamp(root, "self") - set_install_channel("stable", root) - - text = (home / "config.yaml").read_text() - assert "# my hand-maintained settings" in text - assert "# keep this" in text - import hermes_yaml as yaml - - written = yaml.safe_load(text) - assert written["model"] == {"provider": "nous"} - assert written["update"]["installs"][install_id(root)]["channel"] == "stable" @pytest.mark.parametrize("mechanism", ["external", "electron-updater", "app-installer", "microsoft-store"]) def test_os_owned_mechanism_refuses_channel_writes(self, tmp_path, monkeypatch, mechanism): @@ -434,84 +334,24 @@ class TestSetChannelCLI: assert "Back up your data" in out assert "older stable release" in out assert "Wait" not in out - def test_canary_optin_warns_about_forward_incompatible_state(self, capsys): - from unittest.mock import patch - - from hermes_cli.main import cmd_update - - with ( - patch("hermes_cli.config.is_managed", return_value=False), - patch("hermes_cli.config.detect_install_method", return_value="unknown"), - patch("hermes_cli.update_channel.set_install_channel", return_value="a" * 16), - ): - with pytest.raises(SystemExit) as exc: - cmd_update(self._args(set_channel="canary")) - assert exc.value.code == 0 - out = capsys.readouterr().out - assert "forward-incompatible" in out - - def test_install_id_prints_and_exits(self, capsys): - from unittest.mock import patch - - from hermes_cli.main import cmd_update - - with ( - patch("hermes_cli.config.is_managed", return_value=False), - patch("hermes_cli.update_channel.install_id", return_value="b" * 16), - ): - with pytest.raises(SystemExit) as exc: - cmd_update(self._args(install_id=True)) - assert exc.value.code == 0 - assert "b" * 16 in capsys.readouterr().out -class TestDoctorStaleness: - def test_missing_path_flagged(self, tmp_path): - gone = tmp_path / "gone" - config = { - "update": {"installs": {"deadbeefdeadbeef": {"path": str(gone), "channel": "main"}}} - } - stale = stale_channel_records(config) - assert [(sha, reason) for sha, _r, reason in stale] == [ - ("deadbeefdeadbeef", "missing") - ] - def test_replaced_install_flagged(self, tmp_path): - """The recorded path exists but keys to a different sha16 — the - record is a leftover from a tree that used to live elsewhere.""" - root = tmp_path / "install" +@pytest.mark.parametrize('kind,expected', [('missing', 'missing'), ('replaced', 'replaced'), + ('unclaimed', 'unclaimed'), ('healthy', None)]) +def test_doctor_channel_records_are_read_only(tmp_path, monkeypatch, kind, expected): + from copy import deepcopy + home, root = tmp_path / '.hermes', tmp_path / 'install' + monkeypatch.setenv('HERMES_HOME', str(home)) + if kind != 'missing': root.mkdir() - config = { - "update": {"installs": {"0" * 16: {"path": str(root), "channel": "main"}}} - } - stale = stale_channel_records(config) - assert [(sha, reason) for sha, _r, reason in stale] == [("0" * 16, "replaced")] - - def test_unclaimed_record_flagged(self, tmp_path, monkeypatch): - """sha16 matches the path but no installs//install.json exists.""" - home = tmp_path / ".hermes" - home.mkdir() - monkeypatch.setenv("HERMES_HOME", str(home)) - root = tmp_path / "install" - root.mkdir() - config = _config_for(root, "main") - stale = stale_channel_records(config) - assert [(sha, reason) for sha, _r, reason in stale] == [ - (install_id(root), "unclaimed") - ] - - def test_healthy_record_not_flagged(self, tmp_path, monkeypatch): - home = tmp_path / ".hermes" - home.mkdir() - monkeypatch.setenv("HERMES_HOME", str(home)) - root = tmp_path / "install" - _stamp(root, "self") - # The live install-state record the sha16 must be claimed by - # (boot_bootstrap.ensure_install_dir writes this at boot; that - # module is landing in a parallel lane, so write the marker - # directly — the layout IS the contract). - state = home / "installs" / install_id(root) + key = '0' * 16 if kind == 'replaced' else install_id(root) + config = {'update': {'installs': {key: {'path': str(root), 'channel': 'main'}}}} + if kind == 'healthy': + state = home / 'installs' / key state.mkdir(parents=True) - (state / "install.json").write_text(json.dumps({"root": str(root)})) - config = _config_for(root, "main") - assert stale_channel_records(config) == [] + (state / 'install.json').write_text(json.dumps({'root': str(root)}), encoding='utf-8') + before = deepcopy(config) + assert [(key, reason) for key, _, reason in stale_channel_records(config)] == ( + [(key, expected)] if expected else []) + assert config == before diff --git a/tests/hermes_cli/test_update_completion_routing.py b/tests/hermes_cli/test_update_completion_routing.py index 27f4cd2ffd..bf52e0cf15 100644 --- a/tests/hermes_cli/test_update_completion_routing.py +++ b/tests/hermes_cli/test_update_completion_routing.py @@ -4,7 +4,8 @@ from unittest.mock import Mock import pytest -from hermes_cli import update_cmd, update_cmd_zip +from hermes_cli import main, main_web_build, update_cmd, update_cmd_zip, update_cmd_maint +from tests.compat.old_updater_support import fresh_child, no_external_work # noqa: F401 @pytest.mark.parametrize("hook,args,kwargs", [ @@ -12,12 +13,29 @@ from hermes_cli import update_cmd, update_cmd_zip (update_cmd._reload_config_modules, (), {}), (update_cmd._reload_process_scan_modules, (), {}), (update_cmd._run_pending_fleet_restart, (), {}), + (main_web_build._run_with_idle_timeout, (["unused"], "unused"), {"idle_timeout_seconds": 10}), + (main_web_build._run_npm_install_deterministic, ("unused", "unused"), {"extra_args": ("arg",)}), + (main_web_build._nixos_build_env, (), {}), + (main._reexec_dependency_sync_off_windows_shim, (), {}), + (update_cmd_maint._print_update_summary, (), { + "node_failures": [], "desktop_build_ok": True, "pre_update_version": None}), + (update_cmd_maint._print_update_summary, (), { + "node_failures": ["dashboard"], "desktop_build_ok": False, "pre_update_version": "0.20.1"}), + (update_cmd_maint._finish_dashboard_update_cleanup, ([],), {}), + (update_cmd_maint._finish_dashboard_update_cleanup, (["dashboard"],), { + "already_restarted_units": {"hermes-serve"}}), ]) -def test_historical_completion_hook_never_reports_success(hook, args, kwargs, capsys): - with pytest.raises(SystemExit) as error: +def test_historical_completion_hook_never_reports_success(hook, args, kwargs, fresh_child, capsys): + if hook in {update_cmd._prepare_updated_checkout, update_cmd._reload_config_modules, + update_cmd._reload_process_scan_modules, update_cmd._run_pending_fleet_restart}: + with pytest.raises(SystemExit) as error: + hook(*args, **kwargs) + assert error.value.code == 1 + assert fresh_child.requests == [] + assert 'run `hermes update` again' in capsys.readouterr().err + return + with fresh_child.exits(): hook(*args, **kwargs) - assert error.value.code != 0 - assert "update" in capsys.readouterr().err.lower() def test_incomplete_handoff_requires_explicit_update_retry(tmp_path, monkeypatch, capsys): diff --git a/tests/hermes_cli/test_update_config_migration_on_current.py b/tests/hermes_cli/test_update_config_migration_on_current.py index 12175deba6..b7989c7278 100644 --- a/tests/hermes_cli/test_update_config_migration_on_current.py +++ b/tests/hermes_cli/test_update_config_migration_on_current.py @@ -1,123 +1,93 @@ -"""Tests for config migration on the \"Already up to date\" repair path. +"""Migration UX policy; selected-child and real profile writes live in completion tests.""" +import sys -Covers ``_check_and_apply_config_migration`` on the ``commit_count == 0`` -retry paths (#91360): a previous update attempt can pull new code onto disk -and then fail before reaching the config-migration block (e.g. PyPI timeout -during dependency sync); the retry then enters the ``commit_count == 0`` -branch and returns early, skipping config migration entirely. The fresh -code (which may require a newer ``_config_version``) keeps running against -the old config and the next Hermes launch refuses to start. +import pytest -Matrix: config behind / current / ahead of the code's version, plus the -#86656 contract (quiet-migration warnings must be re-surfaced) and the -check-failure contract (a config-check failure must not break the repair -path). -""" - -from __future__ import annotations - -import contextlib -import io -from hermes_cli import config as update_config -from unittest.mock import patch - -import hermes_cli.update_cmd as update_cmd +from hermes_cli import config, update_cmd -def _run(current: int, latest: int): - """Run _check_and_apply_config_migration with mocked config checks. +@pytest.mark.parametrize('case,expected', [ + ('format', [(False, True)]), ('warnings', [(False, True)]), + ('migration-error', [(False, True)]), ('current', []), ('ahead', []), ('read-error', []), + ('yes', [(False, False)]), ('tty-yes', [(True, False)]), ('tty-decline', []), + ('noninteractive', [(False, False)]), ('gateway', [(False, False)]), ('eof', []), ('unicode', []), +]) +def test_migration_policy(monkeypatch, capsys, case, expected): + prompts, calls = [], [] + named = case in {'yes', 'tty-yes', 'tty-decline', 'noninteractive', 'gateway', 'eof', 'unicode'} + monkeypatch.setattr(config, 'get_missing_env_vars', lambda **_: [ + {'name': 'NEW_TOKEN', 'description': 'new credential'}] if named else []) + monkeypatch.setattr(config, 'get_missing_config_fields', lambda: [ + {'key': 'new.option', 'description': 'new option'}] if named else []) - Returns (stdout, migrate_calls). - """ - migrate_calls = [] + def version(**kwargs): + assert kwargs == {'raise_on_parse_error': True} + if case == 'read-error': + raise RuntimeError('cannot read config') + return (4 if case == 'ahead' else 3 if case == 'current' else 2, 3) - def _fake_migrate(interactive=False, quiet=False): - migrate_calls.append((interactive, quiet)) - return {"env_added": [], "config_added": [], "warnings": []} + def migrate(*, interactive, quiet): + calls.append((interactive, quiet)) + if case == 'migration-error': + raise RuntimeError('cannot write config') + return {'env_added': [], 'config_added': ['setting reset'] if case == 'warnings' else [], + 'warnings': ['personality reset'] if case == 'warnings' else []} - with patch.object(update_cmd, "_reload_config_modules"), patch( - "hermes_cli.config.get_missing_env_vars", return_value=[] - ), patch( - "hermes_cli.config.get_missing_config_fields", return_value=[] - ), patch.object( - update_config, "check_config_version", return_value=(current, latest) - ), patch.object( - update_config, "migrate_config", side_effect=_fake_migrate - ), patch.object( - update_cmd, "_migrate_sibling_profile_configs", return_value=[] - ): - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - update_cmd._check_and_apply_config_migration() - return buf.getvalue(), migrate_calls + def prompt(text): + prompts.append(text) + if case == 'eof': + raise EOFError() + if case == 'unicode': + raise UnicodeDecodeError('utf-8', b'\xff', 0, 1, 'invalid') + return 'n' if case == 'tty-decline' else 'y' + + monkeypatch.setattr(config, 'check_config_version', version) + monkeypatch.setattr(config, 'migrate_config', migrate) + monkeypatch.setattr(update_cmd, '_migrate_sibling_profile_configs', lambda: []) + monkeypatch.setattr(sys.stdin, 'isatty', lambda: case != 'noninteractive') + monkeypatch.setattr(sys.stdout, 'isatty', lambda: case != 'noninteractive') + monkeypatch.setattr('builtins.input', prompt) + gateway_prompts = [] + monkeypatch.setattr(update_cmd, '_gateway_prompt', lambda text, default: gateway_prompts.append((text, default)) or 'y') + update_cmd._check_and_apply_config_migration(assume_yes=case == 'yes', gateway_mode=case == 'gateway') + assert calls == expected + assert bool(prompts) is (case in {'tty-yes', 'tty-decline', 'eof', 'unicode'}) + assert bool(gateway_prompts) is (case == 'gateway') + output = capsys.readouterr().out + if named: + assert 'NEW_TOKEN' in output and 'new.option' in output + assert 'new credential' in output and 'new option' in output + if case in {'yes', 'noninteractive', 'gateway'}: + assert 'API keys require manual entry' in output + elif not expected: + assert 'hermes config migrate' in output + elif case in {'current', 'ahead'}: + assert 'Configuration is up to date' in output + elif case == 'read-error': + assert 'Could not check config version' in output + elif case == 'migration-error': + assert 'Config format update failed: cannot write config' in output + else: + assert 'v2 → v3' in output and 'no new settings to configure' in output + if case == 'warnings': + assert 'setting reset' in output and 'personality reset' in output -def test_migrates_when_config_behind(): - """Version bump on the repair path must be applied silently.""" - out, calls = _run(current=37, latest=38) - assert "v37 → v38" in out - assert "Config format updated" in out - assert calls == [(False, True)] # non-interactive, quiet +@pytest.mark.parametrize('named', [False, True]) +def test_update_copies_bundled_skill_bytes_to_default_active_and_sibling(tmp_path, monkeypatch, named): + from pathlib import Path + from hermes_cli import update_cmd_maint - -def test_noop_when_config_current(): - """No migration when the config version is already current.""" - out, calls = _run(current=38, latest=38) - assert "Configuration is up to date" in out - assert calls == [] - - -def test_noop_when_config_ahead(): - """No migration when local config is newer than the code's default.""" - out, calls = _run(current=39, latest=38) - assert "Configuration is up to date" in out - assert calls == [] - - -def test_surfaces_migration_warnings(): - """Warnings from a quiet migration must be re-surfaced (#86656).""" - - def _fake_migrate(interactive=False, quiet=False): - return { - "env_added": [], - "config_added": [], - "warnings": ["personality reset: kawaii → default"], - } - - with patch.object(update_cmd, "_reload_config_modules"), patch( - "hermes_cli.config.get_missing_env_vars", return_value=[] - ), patch( - "hermes_cli.config.get_missing_config_fields", return_value=[] - ), patch.object( - update_config, "check_config_version", return_value=(37, 38) - ), patch.object( - update_config, "migrate_config", side_effect=_fake_migrate - ), patch.object( - update_cmd, "_migrate_sibling_profile_configs", return_value=[] - ): - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - update_cmd._check_and_apply_config_migration() - out = buf.getvalue() - - assert "personality reset" in out - - -def test_check_failure_does_not_break_repair_path(): - """A config-check failure must not break the repair path.""" - with patch.object(update_cmd, "_reload_config_modules"), patch( - "hermes_cli.config.get_missing_env_vars", return_value=[] - ), patch( - "hermes_cli.config.get_missing_config_fields", return_value=[] - ), patch.object( - update_config, "check_config_version", side_effect=RuntimeError("boom") - ), patch.object( - update_config, "migrate_config", return_value={} - ) as mig: - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - # Should not raise and should not attempt migration. - update_cmd._check_and_apply_config_migration() - out = buf.getvalue() - assert "Could not check config version" in out - mig.assert_not_called() + home = tmp_path / '.hermes' + homes = [home, home / 'profiles/active', home / 'profiles/sibling'] if named else [home] + for profile in homes: + profile.mkdir(parents=True, exist_ok=True) + (profile / 'config.yaml').write_text('{}\n', encoding='utf-8') + monkeypatch.setattr(Path, 'home', lambda: tmp_path) + monkeypatch.setenv('HERMES_HOME', str(homes[1] if named else home)) + monkeypatch.setattr('plugins.memory.honcho.cli.sync_honcho_profiles_quiet', lambda: []) + update_cmd_maint._sync_profiles_after_update() + bundled = Path(__file__).resolve().parents[2] / 'skills' + witness = next(bundled.rglob('SKILL.md')) + for profile in homes: + assert (profile / 'skills' / witness.relative_to(bundled)).read_bytes() == witness.read_bytes() diff --git a/tests/hermes_cli/test_update_config_migration_on_current_checkout.py b/tests/hermes_cli/test_update_config_migration_on_current_checkout.py deleted file mode 100644 index ccdb29fdae..0000000000 --- a/tests/hermes_cli/test_update_config_migration_on_current_checkout.py +++ /dev/null @@ -1,74 +0,0 @@ -"""Tests for config migration on the commit_count == 0 / retry path (#91360). - -When an update is interrupted (or dependency install fails) after code has already -been pulled, the subsequent update run takes the 'commit_count == 0' path. -It must run config version checking and migrations before completing so the -install is not left in a non-bootable state with new code on old config version. -""" - -from __future__ import annotations - -from hermes_cli import config as update_config -from unittest.mock import MagicMock, patch - -from hermes_cli import update_cmd - - - - - - -def test_check_and_apply_config_migration_interactive_prompt(): - """When new config options exist in an interactive session, it prompts the user.""" - with ( - patch.object(update_cmd, "_reload_config_modules"), - patch.object(update_config, "check_config_version", return_value=(37, 38)), - patch("hermes_cli.config.get_missing_env_vars", return_value=[{"name": "NEW_KEY", "description": "desc"}]), - patch("hermes_cli.config.get_missing_config_fields", return_value=[]), - patch("sys.stdin.isatty", return_value=True), - patch("sys.stdout.isatty", return_value=True), - patch("builtins.input", return_value="y"), - patch.object( - update_config, "migrate_config", - return_value={"env_added": ["NEW_KEY"], "config_added": [], "warnings": []}, - ) as mock_migrate, - ): - update_cmd._check_and_apply_config_migration(assume_yes=False, gateway_mode=False) - - mock_migrate.assert_called_once_with(interactive=True, quiet=False) - - -def test_check_and_apply_config_migration_assume_yes(): - """When assume_yes=True, it applies migrations non-interactively without prompting.""" - with ( - patch.object(update_cmd, "_reload_config_modules"), - patch.object(update_config, "check_config_version", return_value=(37, 38)), - patch("hermes_cli.config.get_missing_env_vars", return_value=[{"name": "NEW_KEY"}]), - patch("hermes_cli.config.get_missing_config_fields", return_value=[]), - patch.object( - update_config, "migrate_config", - return_value={"env_added": [], "config_added": ["opt"], "warnings": []}, - ) as mock_migrate, - ): - update_cmd._check_and_apply_config_migration(assume_yes=True, gateway_mode=False) - - mock_migrate.assert_called_once_with(interactive=False, quiet=False) - - -def test_check_and_apply_config_migration_non_interactive(): - """In a non-interactive session (e.g. CI/scripts), it applies safe migrations automatically.""" - with ( - patch.object(update_cmd, "_reload_config_modules"), - patch.object(update_config, "check_config_version", return_value=(37, 38)), - patch("hermes_cli.config.get_missing_env_vars", return_value=[]), - patch("hermes_cli.config.get_missing_config_fields", return_value=[{"key": "new_setting"}]), - patch("sys.stdin.isatty", return_value=False), - patch("sys.stdout.isatty", return_value=False), - patch.object( - update_config, "migrate_config", - return_value={"env_added": [], "config_added": ["new_setting"], "warnings": []}, - ) as mock_migrate, - ): - update_cmd._check_and_apply_config_migration(assume_yes=False, gateway_mode=False) - - mock_migrate.assert_called_once_with(interactive=False, quiet=False) diff --git a/tests/hermes_cli/test_update_desktop_stale_warning.py b/tests/hermes_cli/test_update_desktop_stale_warning.py deleted file mode 100644 index 7bef12082e..0000000000 --- a/tests/hermes_cli/test_update_desktop_stale_warning.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Retired soft-build hooks stop old updaters instead of claiming completion. - -Live source builds now raise on failure before maintenance runs. Old updaters -can still import these frozen names after swapping their checkout. -""" - -from types import SimpleNamespace - -import pytest - -from hermes_cli import update_cmd -from hermes_cli import update_cmd_maint - - -@pytest.mark.parametrize( - "name,args,kwargs", - [ - ("_print_update_summary", (), { - "node_failures": [], "desktop_build_ok": True, "pre_update_version": None, - }), - ("_print_update_summary", (), { - "node_failures": ["dashboard"], "desktop_build_ok": False, - "pre_update_version": "0.20.1", - }), - ("_finish_dashboard_update_cleanup", ([],), {}), - ("_finish_dashboard_update_cleanup", (["dashboard"],), { - "already_restarted_units": {"hermes-serve"}, - }), - ], -) -def test_historical_completion_hooks_stop_before_work(name, args, kwargs, monkeypatch, capsys): - def forbidden(*args, **kwargs): - pytest.fail("old updater attempted post-update work") - - monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", forbidden) - monkeypatch.setattr(update_cmd, "_reload_process_scan_modules", forbidden) - monkeypatch.setattr( - update_cmd, "_m", lambda: SimpleNamespace(_kill_stale_dashboard_processes=forbidden), - ) - with pytest.raises(SystemExit) as exc: - getattr(update_cmd_maint, name)(*args, **kwargs) - assert exc.value.code == 0 - output = capsys.readouterr() - assert "run `hermes` again" in output.err - assert "Update complete" not in output.out - - -def test_gateway_exit_code_file_tracks_verified_outcome(tmp_path, monkeypatch): - monkeypatch.setattr(update_cmd, "get_hermes_home", lambda: tmp_path) - update_cmd._write_gateway_update_exit_code(True) - assert (tmp_path / ".update_exit_code").read_text(encoding="utf-8") == "0" - update_cmd._write_gateway_update_exit_code(False) - assert (tmp_path / ".update_exit_code").read_text(encoding="utf-8") == "1" - - -def test_verified_completion_keeps_success_banner(capsys, monkeypatch): - monkeypatch.setattr(update_cmd, "_branch_head_suffix", lambda: "") - monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None)) - - assert update_cmd_maint._print_verified_update_completion("✓ Update complete!") is True - - out = capsys.readouterr().out - assert "✓ Update complete!" in out - assert "partially complete" not in out - assert "desktop" not in out - assert "Node" not in out - assert "=== hermes-update completed" not in out - - -def test_verified_completion_emits_dashboard_receipt_only_on_success(monkeypatch, capsys): - action_id = "a" * 32 - monkeypatch.setenv("HERMES_ACTION_ID", action_id) - monkeypatch.setattr(update_cmd, "_branch_head_suffix", lambda: "") - monkeypatch.setattr( - update_cmd, "_post_update_sqlite_runtime_status", - lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")), - ) - assert update_cmd_maint._print_verified_update_completion("✓ Update complete!") is False - assert f"=== hermes-update completed {action_id} ===" not in capsys.readouterr().out - - monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None)) - assert update_cmd_maint._print_verified_update_completion("✓ Update complete!") is True - assert f"=== hermes-update completed {action_id} ===" in capsys.readouterr().out - - -def test_unavailable_sqlite_probe_retains_existing_nonblocking_behavior(monkeypatch, capsys): - monkeypatch.setattr(update_cmd, "_branch_head_suffix", lambda: "") - monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (False, None)) - - assert update_cmd_maint._print_verified_update_completion("✓ Update complete!") is True - assert "✓ Update complete!" in capsys.readouterr().out - - -def test_maintenance_returns_sqlite_verdict_without_frontend_flags(monkeypatch, tmp_path, capsys): - monkeypatch.setattr(update_cmd, "_m", lambda: SimpleNamespace(PROJECT_ROOT=tmp_path)) - monkeypatch.setattr("hermes_cli.macos_tcc_anchor.ensure_tcc_anchor", lambda: None) - monkeypatch.setattr("hermes_cli.model_catalog.seed_cache_from_checkout", lambda root: False) - monkeypatch.setattr(update_cmd, "_check_and_apply_config_migration", lambda **kwargs: None) - for name in ( - "_verify_and_restore_state_dbs_post_update", "_print_bundled_skills_sync_report", - "_sync_profiles_after_update", "_print_post_update_notices_and_self_heals", - ): - monkeypatch.setattr(update_cmd_maint, name, lambda: None) - monkeypatch.setattr( - update_cmd, "_post_update_sqlite_runtime_status", - lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")), - ) - - complete = update_cmd_maint._run_post_update_maintenance( - assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None, - had_desktop_app_before_update=False, pre_update_version=None, - ) - - assert complete is False - assert "Update complete" not in capsys.readouterr().out - monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None)) - monkeypatch.setattr(update_cmd, "_branch_head_suffix", lambda: "") - assert update_cmd_maint._run_post_update_maintenance( - assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None, - had_desktop_app_before_update=False, pre_update_version=None, - ) is True - assert "✓ Update complete!" in capsys.readouterr().out - - -@pytest.mark.parametrize("already_restarted_units", [None, {"hermes-serve"}]) -def test_dashboard_refresh_preserves_restart_bookkeeping( - already_restarted_units, monkeypatch, capsys, -): - order = [] - monkeypatch.setattr(update_cmd, "_reload_process_scan_modules", lambda: order.append("reload")) - - def kill(**kwargs): - order.append(kwargs) - return {"unrecovered": [1234]} - - monkeypatch.setattr( - update_cmd, "_m", lambda: SimpleNamespace(_kill_stale_dashboard_processes=kill), - ) - update_cmd_maint._refresh_dashboard_after_update(already_restarted_units=already_restarted_units) - - assert order == [{ - "restart_managed": True, "already_restarted_units": already_restarted_units, - }] - assert "could not be auto-restarted" in capsys.readouterr().out diff --git a/tests/hermes_cli/test_update_fleet_check_fail_closed.py b/tests/hermes_cli/test_update_fleet_check_fail_closed.py index 296aa3b983..42dd9aae96 100644 --- a/tests/hermes_cli/test_update_fleet_check_fail_closed.py +++ b/tests/hermes_cli/test_update_fleet_check_fail_closed.py @@ -35,103 +35,6 @@ def _plan(runtimes): return types.SimpleNamespace(runtimes=runtimes) -class TestEmptySnapshotFailClosed: - """Signals under which zero fleet rows means verification failure.""" - - def test_incomplete_when_pre_update_plan_saw_gateway_runtimes(self): - # (a) The plan inventoried a live gateway runtime pre-update but the - # restart phase's POSIX bookkeeping is empty (e.g. Windows, or an - # externally-supervised gateway). Zero rows must fail closed. - assert ( - _fleet_probe_expected_runtimes( - _plan([RuntimeRecord(kind="gateway", profile="default")]), - [], # pre_restart_pids: probe saw nothing - None, # no Windows resume token - [], # restarted_services - set(), # killed_pids - ) - is True - ) - - def test_plan_expectation_keys_on_gateway_kind_only(self): - # #97332: serve/dashboard plan records have no gateway_state.json row, so a - # dashboard-only or serve-only plan must not demand rows (that made a successful - # update exit 1); one gateway record alongside them still carries the expectation. - non_gateway = [RuntimeRecord(kind="dashboard", profile="default"), RuntimeRecord(kind="serve", profile="default")] - assert _fleet_probe_expected_runtimes(_plan(non_gateway), [], None, [], set()) is False - mixed = non_gateway + [RuntimeRecord(kind="gateway", profile="work")] - assert _fleet_probe_expected_runtimes(_plan(mixed), [], None, [], set()) is True - - def test_windows_resume_token_alone_is_not_expected(self): - # (c) The Windows pause/resume token is EXCLUDED from the expectation - # (#93406 residual): it is pause/resume bookkeeping, not a runtime - # inventory, and collect_fleet_versions() cannot return rows for its - # entries (unmapped Scheduled-Task gateways never publish - # gateway_state.json; a resumed profile gateway relaunches detached). - # Counting it made a healthy Windows update wait out the probe window - # and exit 1 on zero rows. Full coverage lives in - # test_update_fleet_probe_resume_token.py. - token = {"resume_needed": False, "profiles": {"default": 4321}} - assert ( - _fleet_probe_expected_runtimes(None, [], token, [], set()) is False - ) - token = {"resume_needed": False, "unmapped": [{"pid": 99, "argv": ["x"]}]} - assert ( - _fleet_probe_expected_runtimes(None, [], token, [], set()) is False - ) - - def test_windows_resume_token_services_do_not_demand_rows(self): - # Deliberately inverted from the original pin (#93406/#95589): SCM - # services the updater itself paused/resumed produce NO probe rows — - # counting them as "expected runtimes" made every healthy Windows - # desktop update stall ~14min in fleet verification and exit 1. - # The token is excluded wholesale; restart-phase and pre-restart - # signals below still fail closed. - token = { - "resume_needed": False, - "profiles": {}, - "unmapped": [], - "services": ["HermesGateway"], - } - assert ( - _fleet_probe_expected_runtimes(None, [], token, [], set()) is False - ) - - def test_incomplete_when_restart_phase_touched_gateways(self): - # The original #93410 signal still counts. - assert ( - _fleet_probe_expected_runtimes(None, [], None, ["hermes-gateway"], set()) - is True - ) - assert _fleet_probe_expected_runtimes(None, [], None, [], {4321}) is True - - def test_incomplete_when_pre_restart_pids_seen(self): - assert _fleet_probe_expected_runtimes(None, [4321], None, [], set()) is True - - def test_incomplete_when_pre_restart_state_unreadable(self): - # None means the pre-state could not be read — cannot prove nothing - # was running, same contract as _restart_phase_failure_is_incomplete. - assert _fleet_probe_expected_runtimes(None, None, None, [], set()) is True - - -class TestEmptySnapshotGenuinelyIdle: - def test_success_when_nothing_was_running_pre_update(self): - # (b) Positive control: no plan runtimes, empty PID snapshot, no - # Windows token, no restart bookkeeping — zero rows stays a success. - assert ( - _fleet_probe_expected_runtimes(_plan([]), [], None, [], set()) is False - ) - - def test_success_with_no_plan_at_all(self): - assert _fleet_probe_expected_runtimes(None, [], None, [], set()) is False - - def test_success_with_empty_windows_token(self): - # A token that paused nothing (e.g. Windows host with no gateways) - # is not a liveness signal. - token = {"resume_needed": False, "profiles": {}, "unmapped": []} - assert _fleet_probe_expected_runtimes(None, [], token, [], set()) is False - - class TestCallSiteWiring: @pytest.mark.parametrize("had_gateway", [False, True], ids=["idle", "plan-saw-gateway"]) def test_empty_probe_settles_and_fails_only_when_rows_expected(self, monkeypatch, tmp_path, capsys, had_gateway): diff --git a/tests/hermes_cli/test_update_fleet_probe_resume_token.py b/tests/hermes_cli/test_update_fleet_probe_resume_token.py index d30835ded0..a9946bfec0 100644 --- a/tests/hermes_cli/test_update_fleet_probe_resume_token.py +++ b/tests/hermes_cli/test_update_fleet_probe_resume_token.py @@ -1,101 +1,27 @@ -"""Regression for #93406 (residual) — the Windows pause/resume token is NOT a -fleet runtime and must not be counted by ``_fleet_probe_expected_runtimes``. +"""Only row-capable runtime evidence can make an empty fleet probe fail.""" +from types import SimpleNamespace -The first #93406 guard counted the ``_windows_gateway_resume`` token -(``profiles`` / ``unmapped`` entries) as an "expected fleet rows" signal. But -the token is pause/resume *bookkeeping*, not a runtime inventory: - -* ``unmapped`` entries (Scheduled-Task gateways) never publish - ``gateway_state.json`` rows at all, and -* a paused-then-resumed profile gateway relaunches DETACHED and may not - republish its identity within the probe's window, - -so ``collect_fleet_versions()`` can legitimately return zero rows for a -perfectly healthy Windows update. With the token counted as an expected -runtime, ``_fleet_rows_expected`` is True, the verification loop silently -waits out its polling window (~14 min wall clock on an end-user report with -the retry loop), prints "Fleet version check returned no rows", and ``hermes -update`` exits 1 — for an update that succeeded. - -The invariant this file pins: ``_fleet_probe_expected_runtimes`` may only -return True for signals that correspond to rows ``collect_fleet_versions()`` -is actually capable of returning (restart-phase bookkeeping, the pre-restart -PID snapshot, the pre-update plan inventory). A genuinely live pre-update -Windows gateway is already covered by ``pre_restart_pids`` and the plan -inventory — the token adds no row-capable information on top. - -Counterfactual: every test in ``TestResumeTokenIsNotARuntime`` FAILS on the -pre-fix ``_fleet_probe_expected_runtimes`` (which returns True for a -token-only signal). -""" - -from __future__ import annotations - -import types +import pytest from hermes_cli.main import _fleet_probe_expected_runtimes from hermes_cli.update_inventory import RuntimeRecord -def _plan(runtimes): - return types.SimpleNamespace(runtimes=runtimes) - - -class TestResumeTokenIsNotARuntime: - """Token-only signals must NOT mark fleet rows as expected (#93406).""" - - def test_token_profiles_alone_do_not_expect_rows(self): - # A paused/resumed profile gateway relaunches detached; its row is - # not guaranteed within the probe window. Token-only == no rows - # expected, so zero rows stays exit 0 instead of a false failure. - token = {"resume_needed": False, "profiles": {"default": 4321}} - assert ( - _fleet_probe_expected_runtimes(None, [], token, [], set()) is False - ) - - def test_token_unmapped_alone_does_not_expect_rows(self): - # Scheduled-Task gateways (token["unmapped"]) never publish - # gateway_state.json rows — collect_fleet_versions() CANNOT return a - # row for them, so they must not be counted as expected rows. - token = {"resume_needed": False, "unmapped": [{"pid": 99, "argv": ["x"]}]} - assert ( - _fleet_probe_expected_runtimes(None, [], token, [], set()) is False - ) - - def test_token_with_empty_pid_snapshot_is_still_not_expected(self): - # Even alongside an affirmatively-empty PID snapshot and an empty - # plan, the token alone must not flip the expectation. - token = {"resume_needed": True, "profiles": {"work": 777}, "unmapped": []} - assert ( - _fleet_probe_expected_runtimes(_plan([]), [], token, [], set()) - is False - ) - - -class TestRowCapableSignalsStillCount: - """The row-capable liveness signals are unaffected by the exclusion.""" - - def test_pre_restart_pids_still_expect_rows_alongside_token(self): - # A live pre-update gateway is covered by the PID snapshot — the - # row-capable signal — regardless of the token riding along. - token = {"resume_needed": False, "profiles": {"default": 4321}} - assert ( - _fleet_probe_expected_runtimes(None, [4321], token, [], set()) - is True - ) - - def test_plan_inventory_still_expects_rows_alongside_token(self): - token = {"resume_needed": False, "unmapped": [{"pid": 99, "argv": ["x"]}]} - assert ( - _fleet_probe_expected_runtimes( - _plan([RuntimeRecord(kind="gateway", profile="default")]), - [], - token, - [], - set(), - ) - is True - ) - - def test_unreadable_pre_state_still_expects_rows(self): - assert _fleet_probe_expected_runtimes(None, None, None, [], set()) is True +@pytest.mark.parametrize('plan,pids,token,services,killed,expected', [ + (None, [], {'profiles': {'default': 4321}}, [], set(), False), + (None, [], {'unmapped': [{'pid': 99}]}, [], set(), False), + ([], [], {'profiles': {'work': 777}}, [], set(), False), + (None, [], {'services': ['HermesGateway']}, [], set(), False), + (None, [], {}, [], set(), False), (None, [], None, [], set(), False), + ([], [], None, [], set(), False), (None, None, None, [], set(), True), + (None, [4321], {'profiles': {'default': 4321}}, [], set(), True), + (['gateway'], [], {'unmapped': [{'pid': 99}]}, [], set(), True), + (['serve', 'dashboard'], [], None, [], set(), False), + (['serve', 'gateway'], [], None, [], set(), True), + (None, [], None, ['hermes-gateway'], set(), True), + (None, [], None, [], {4321}, True), +]) +def test_expected_rows(plan, pids, token, services, killed, expected): + inventory = None if plan is None else SimpleNamespace( + runtimes=[RuntimeRecord(kind=kind, profile='default') for kind in plan]) + assert _fleet_probe_expected_runtimes(inventory, pids, token, services, killed) is expected diff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.py index 7359ea4fe6..ae8c13cb7d 100644 --- a/tests/hermes_cli/test_update_fleet_restart_pending.py +++ b/tests/hermes_cli/test_update_fleet_restart_pending.py @@ -60,28 +60,11 @@ def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"): return side_effect -def _make_up_to_date_side_effect(sha="abc123"): - """Simulate git commands where origin is already at HEAD.""" - def side_effect(cmd, **kwargs): - joined = " ".join(str(c) for c in cmd) - - if "rev-parse" in joined and "--abbrev-ref" in joined: - return SimpleNamespace(returncode=0, stdout="main\n", stderr="") - - if "rev-list" in joined: - return SimpleNamespace(returncode=0, stdout="0\n", stderr="") - - if joined.endswith("rev-parse HEAD"): - return SimpleNamespace(returncode=0, stdout=f"{sha}\n", stderr="") - - return SimpleNamespace(returncode=0, stdout="", stderr="") - - return side_effect def _patch_update_deps(monkeypatch, tmp_path, run_side_effect): - """Patch ``_cmd_update_impl`` helpers. Mirrors test_update_head_moved_gate.""" + """Isolate machine maintenance while exercising interrupted fleet updates.""" monkeypatch.setattr(hermes_main.subprocess, "run", run_side_effect) monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path) monkeypatch.setattr(update_cmd, "_prepare_updated_checkout", lambda *a, **k: None) @@ -376,8 +359,6 @@ def test_stale_fleet_matrix_on_latest_receipt_is_pending(monkeypatch): assert update_cmd._pending_fleet_restart_needed() is True - - # --------------------------------------------------------------------------- # cmd_update integration (mocked git / restart) # --------------------------------------------------------------------------- @@ -406,33 +387,6 @@ def test_marker_written_after_pull_cleared_after_successful_restart( assert "✓ Code updated!" in out -def test_clean_update_warns_about_surviving_pre_update_serve_runtime( - monkeypatch, tmp_path, capsys -): - """The successful update path must surface an inventoried stale serve.""" - args = _update_args() - _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect()) - monkeypatch.setattr( - update_cmd, - "_surviving_pre_update_serve_runtimes", - lambda _plan: [ - { - "pid": 5555, - "kind": "serve", - "profile": "default", - "supervisor": "manual-serve", - } - ], - ) - - hermes_main.cmd_update(args) - - out = capsys.readouterr().out - assert "pid 5555" in out - assert "serve" in out - assert "pre-update code" in out - - def test_clean_update_escalates_surviving_serve_as_unaccounted( monkeypatch, tmp_path, capsys ): @@ -516,79 +470,6 @@ def test_interrupt_between_pull_and_restart_leaves_marker( assert "expected_sha=def456" in marker.read_text(encoding="utf-8") -def test_already_up_to_date_runs_pending_restart_when_marker_present( - monkeypatch, tmp_path, capsys -): - args = _update_args() - _patch_update_deps(monkeypatch, tmp_path, _make_up_to_date_side_effect()) - update_cmd._write_fleet_restart_pending_marker(expected_sha="def456") - - seen = {"ran": False} - - original = update_cmd._restart_gateway_fleet_after_update - def _restart(*args): - seen["ran"] = True - return original(*args) - - monkeypatch.setattr(update_cmd, "_restart_gateway_fleet_after_update", _restart) - - hermes_main.cmd_update(args) - - assert seen["ran"] is True - assert not update_cmd._fleet_restart_pending_marker_path().exists() - out = capsys.readouterr().out - assert "Already up to date!" in out - - -def test_already_up_to_date_runs_pending_restart_when_receipt_skewed( - monkeypatch, tmp_path, capsys -): - args = _update_args() - _patch_update_deps(monkeypatch, tmp_path, _make_up_to_date_side_effect()) - - disk_sha = "e" * 40 - monkeypatch.setattr(update_cmd, "_current_checkout_sha", lambda: disk_sha) - monkeypatch.setattr(update_cmd_fleet, "_current_checkout_sha", lambda: disk_sha) - receipt_dir = get_hermes_home() / "logs" / "update_receipts" - receipt_dir.mkdir(parents=True) - (receipt_dir / "latest.json").write_text( - json.dumps( - { - "exit_code": 1, - "stop_reason": "KeyboardInterrupt: ", - "outcome": "failed", - "plan": { - "expected_sha": disk_sha, - "runtimes": [ - { - "kind": "gateway", - "profile": "default", - "pid": 42, - "code_sha": "7" * 40, - } - ], - }, - } - ), - encoding="utf-8", - ) - - seen = {"ran": False} - original = update_cmd._restart_gateway_fleet_after_update - def restart(*args): - seen["ran"] = True - return original(*args) - monkeypatch.setattr(update_cmd, "_restart_gateway_fleet_after_update", restart) - - hermes_main.cmd_update(args) - - assert seen["ran"] is True - out = capsys.readouterr().out - assert "Already up to date!" in out - - - - def test_startup_warn_prints_when_marker_present(capsys): update_cmd._write_fleet_restart_pending_marker() update_cmd._warn_pending_fleet_restart_on_startup() diff --git a/tests/hermes_cli/test_update_handoff_exit.py b/tests/hermes_cli/test_update_handoff_exit.py deleted file mode 100644 index 255745a52e..0000000000 --- a/tests/hermes_cli/test_update_handoff_exit.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Historical handoff markers cannot bypass normal update cleanup or exits.""" - -from __future__ import annotations - -from types import SimpleNamespace - -import pytest - -import hermes_cli.main as main_mod -from hermes_cli import update_cmd -from hermes_cli.main import cmd_update -from hermes_cli.update_receipt import COMMAND_BOUNDARY_STOP_REASON - - -class _FakeLock: - def __init__(self, events): - self._events = events - - def acquire(self): - self._events.append("acquire") - return True - - def release(self): - self._events.append("release") - - -# Events from the most recent _run_cmd_update call, also filled in when -# cmd_update propagates an exception (the return value is unreachable then). -_LAST = {} - - -def _run_cmd_update(monkeypatch, impl, *, reexec: bool): - """Run cmd_update with everything external mocked; return the events.""" - events = {"order": [], "exit_codes": [], "receipts": []} - - def fake_impl(args, gateway_mode=False): - events["order"].append("impl") - impl(args, gateway_mode=gateway_mode) - - def fake_finalize_io(state): - events["order"].append("restore-stdio") - - def fake_receipt(code, reason): - events["receipts"].append((code, reason)) - - def fake_exit(code): - events["order"].append("hard-exit") - events["exit_codes"].append(code) - - monkeypatch.setattr("hermes_cli.config.is_managed", lambda: False) - monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda root: "git") - monkeypatch.setattr("hermes_cli.update_lock.UpdateLock", lambda: _FakeLock(events["order"])) - monkeypatch.setattr(update_cmd, "_cmd_update_impl", fake_impl) - monkeypatch.setattr(main_mod, "_install_hangup_protection", lambda gateway_mode=False: None) - monkeypatch.setattr(main_mod, "_finalize_update_output", fake_finalize_io) - monkeypatch.setattr("hermes_cli.update_receipt.finalize_pending_update_receipt", fake_receipt) - monkeypatch.setattr("os._exit", fake_exit) - if reexec: - monkeypatch.setenv("HERMES_UPDATE_REEXEC", "1") - else: - monkeypatch.delenv("HERMES_UPDATE_REEXEC", raising=False) - - args = SimpleNamespace(plan=False, check=False, gateway=False, branch=None) - try: - cmd_update(args) - finally: - _LAST.clear() - _LAST.update(events) - return events - - -def _noop_impl(args, gateway_mode=False): - return None - - -def test_historical_handoff_marker_does_not_bypass_normal_shutdown(monkeypatch): - events = _run_cmd_update(monkeypatch, _noop_impl, reexec=True) - assert events["exit_codes"] == [] - assert events["receipts"] == [(0, COMMAND_BOUNDARY_STOP_REASON)] - # Cleanup remains ordered even if an old parent supplied its handoff marker. - assert events["order"] == ["acquire", "impl", "release", "restore-stdio"] - - -def test_non_handoff_run_never_hard_exits(monkeypatch): - events = _run_cmd_update(monkeypatch, _noop_impl, reexec=False) - assert events["exit_codes"] == [] - assert "hard-exit" not in events["order"] - assert events["receipts"] == [(0, COMMAND_BOUNDARY_STOP_REASON)] - - -def test_handoff_child_propagates_early_systemexit_code(monkeypatch): - def early_refusal(args, gateway_mode=False): - raise SystemExit(3) - - with pytest.raises(SystemExit) as excinfo: - _run_cmd_update(monkeypatch, early_refusal, reexec=True) - assert excinfo.value.code == 3 - # The original exception propagates after normal cleanup. - assert _LAST["exit_codes"] == [] - - -def test_handoff_child_systemexit_none_means_zero(monkeypatch): - def bare_exit(args, gateway_mode=False): - raise SystemExit(None) - - with pytest.raises(SystemExit): - _run_cmd_update(monkeypatch, bare_exit, reexec=True) - assert _LAST["exit_codes"] == [] - - -def test_unhandled_exception_keeps_raise_path_no_hard_exit(monkeypatch): - def boom(args, gateway_mode=False): - raise RuntimeError("update tail exploded") - - # With os._exit patched to record, the re-raised RuntimeError reaches - # pytest with the finally block already run — and no hard exit fires. - with pytest.raises(RuntimeError, match="update tail exploded"): - _run_cmd_update(monkeypatch, boom, reexec=True) - assert "hard-exit" not in _LAST["order"] - assert _LAST["receipts"] == [(1, "RuntimeError: update tail exploded")] diff --git a/tests/hermes_cli/test_update_head_moved_gate.py b/tests/hermes_cli/test_update_head_moved_gate.py deleted file mode 100644 index d6d9091a72..0000000000 --- a/tests/hermes_cli/test_update_head_moved_gate.py +++ /dev/null @@ -1,148 +0,0 @@ -"""Tests for the post-pull HEAD-movement gate in ``hermes update``. - -Issue #79678: a detached/pinned checkout can report "N new commit(s)" -against origin, run the ff-only merge successfully, and still sit on the -old commit afterward (the branch-switch step re-detaches to the raw SHA). -Before this guard ``hermes update`` printed "✓ Code updated!" and -reinstalled deps + rebuilt the desktop app against the stale tree — no -error, no warning. The gate compares the pre-pull and post-pull HEAD SHA -and fails loudly when the update was a no-op. -""" - -from types import SimpleNamespace - -from copy import deepcopy - -import pytest - -from hermes_cli import main as hermes_main -from hermes_cli import update_cmd -from hermes_cli.update_inventory import UpdatePlan - - -@pytest.fixture(autouse=True) -def _isolate_venv_holders(monkeypatch): - """The update flow's venv-holder guard sees the live gateway processes on - a dev machine and aborts with SystemExit 2 before reaching the HEAD-move - gate under test. Isolate it so the test exercises the intended path.""" - monkeypatch.setattr("hermes_cli.update_cmd_windows._detect_venv_python_processes", lambda: []) - - -def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"): - """Simulate git commands where HEAD advances from pre_sha to post_sha.""" - calls = {"n": 0} - - def side_effect(cmd, **kwargs): - joined = " ".join(str(c) for c in cmd) - - # git rev-parse --abbrev-ref HEAD (get current branch) - if "rev-parse" in joined and "--abbrev-ref" in joined: - return SimpleNamespace(returncode=0, stdout="main\n", stderr="") - - # git rev-list HEAD..origin/main --count (behind count) - if "rev-list" in joined: - return SimpleNamespace(returncode=0, stdout="3\n", stderr="") - - # git rev-parse HEAD — pre-pull capture (first call) sees pre_sha; - # post-pull capture (second call) sees post_sha. get_version_info - # is mocked in _patch_update_deps so the startup banner makes no - # rev-parse calls of its own. - if joined.endswith("rev-parse HEAD"): - if calls["n"] < 1: - calls["n"] += 1 - return SimpleNamespace(returncode=0, stdout=f"{pre_sha}\n", stderr="") - return SimpleNamespace(returncode=0, stdout=f"{post_sha}\n", stderr="") - - # Everything else (merge, checkout, etc.) succeeds quietly. - return SimpleNamespace(returncode=0, stdout="", stderr="") - - return side_effect - - -def _make_head_pinned_side_effect(sha="abc123"): - """Simulate a detached checkout pinned to ``sha``: HEAD never moves.""" - - def side_effect(cmd, **kwargs): - joined = " ".join(str(c) for c in cmd) - - if "rev-parse" in joined and "--abbrev-ref" in joined: - return SimpleNamespace(returncode=0, stdout="HEAD\n", stderr="") - - if "rev-list" in joined: - return SimpleNamespace(returncode=0, stdout="3\n", stderr="") - - if joined.endswith("rev-parse HEAD"): - return SimpleNamespace(returncode=0, stdout=f"{sha}\n", stderr="") - - return SimpleNamespace(returncode=0, stdout="", stderr="") - - return side_effect - - -def _patch_update_deps(monkeypatch, tmp_path, run_side_effect): - """Exercise the Git gate, capturing the request before the child runs.""" - monkeypatch.setattr(hermes_main.subprocess, "run", run_side_effect) - monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path) - (tmp_path / ".git").mkdir() - monkeypatch.setattr(hermes_main, "_resolve_update_branch", lambda args: "main") - monkeypatch.setattr( - hermes_main, "_get_origin_url", - lambda *a, **k: "https://github.com/NousResearch/hermes-agent.git", - ) - monkeypatch.setattr(update_cmd, "_is_fork", lambda *a, **k: False) - monkeypatch.setattr(hermes_main, "_stash_local_changes_if_needed", lambda *a, **k: None) - monkeypatch.setattr(hermes_main, "_run_pre_update_backup", lambda *a: "snapshot-before-pull") - monkeypatch.setattr(hermes_main, "_pause_windows_gateways_for_update", lambda: None) - monkeypatch.setattr(hermes_main, "_resume_windows_gateways_after_update", lambda *a: None) - monkeypatch.setattr(hermes_main, "_install_hangup_protection", lambda **k: {"installed": False}) - monkeypatch.setattr(hermes_main, "_finalize_update_output", lambda *a: None) - # Keep incidental version/inventory probes out of the mock's pre/post HEAD count. - monkeypatch.setattr( - "hermes_cli.version_info.get_version_info", lambda *a, **k: SimpleNamespace(), - ) - plan = UpdatePlan(install_method="git", expected_sha="abc123", profiles=["default"]) - monkeypatch.setattr("hermes_cli.update_inventory.collect_runtime_inventory", lambda: plan) - monkeypatch.setattr("hermes_cli.update_receipt._code_identity", lambda **k: {"commit": "abc123"}) - requests = [] - - def capture(request): - requests.append(deepcopy(request)) - return {"exit_code": 0, "receipt": None} - - monkeypatch.setattr(update_cmd, "run_completion", capture) - return requests, plan - - -def test_update_hands_off_verified_head_when_it_moves(monkeypatch, tmp_path, capsys): - """Only the verified new tree and its pre-update state reach completion.""" - args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False) - requests, plan = _patch_update_deps(monkeypatch, tmp_path, _make_head_moved_side_effect()) - - hermes_main.cmd_update(args) # completes normally (no SystemExit) - - out = capsys.readouterr().out - assert "Code did not move" not in out - request, = requests - assert request["source"] == str(tmp_path.resolve()) - assert request["branch"] == "main" - assert request["expected_sha"] == "def456" - assert request["plan"] == plan.to_dict() - assert request["receipt"]["plan"] == plan.to_dict() - assert request["snapshot_id"] == "snapshot-before-pull" - - -def test_update_fails_loudly_when_head_pinned(monkeypatch, tmp_path, capsys): - """A detached/pinned HEAD that never moves must fail loudly, not print - '✓ Code updated!' against the stale tree.""" - args = SimpleNamespace(branch=None, yes=False, force=False, force_venv=False) - requests, _ = _patch_update_deps(monkeypatch, tmp_path, _make_head_pinned_side_effect()) - - with pytest.raises(SystemExit) as exc_info: - hermes_main.cmd_update(args) - - assert exc_info.value.code == 1 - assert requests == [] - out = capsys.readouterr().out - assert "Code did not move" in out - assert "✓ Code updated!" not in out - assert "checkout main" in out diff --git a/tests/hermes_cli/test_update_products.py b/tests/hermes_cli/test_update_products.py index a9981e5c3c..3c0d14d421 100644 --- a/tests/hermes_cli/test_update_products.py +++ b/tests/hermes_cli/test_update_products.py @@ -1,8 +1,6 @@ """Update retries use the same dependency transaction as a newly pulled tree.""" -import json import subprocess -import venv from types import SimpleNamespace import pytest @@ -15,34 +13,45 @@ from hermes_cli import main, update_cmd -@pytest.mark.parametrize("failure", [ - pm.InstallError("venv", "conflict"), - subprocess.CalledProcessError(23, ["python", "-m", "hermes_cli.source_build"]), +@pytest.mark.parametrize("failure,exception,code", [ + (None, None, 0), (SystemExit(3), SystemExit, 3), + (SystemExit(None), SystemExit, 1), (RuntimeError("tail exploded"), RuntimeError, 1), + (pm.InstallError("venv", "conflict"), SystemExit, 1), + (subprocess.CalledProcessError(23, ["python", "-m", "hermes_cli.source_build"]), SystemExit, 1), ]) -def test_command_reports_failed_preparation_and_releases_lock(tmp_path, monkeypatch, capsys, failure): +@pytest.mark.parametrize("reexec", [False, True]) +def test_command_reports_outcome_and_releases_real_lock(tmp_path, monkeypatch, failure, exception, code, reexec): from hermes_cli import update_lock, update_receipt monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("HERMES_UPDATE_REEXEC", "1" if reexec else "") + monkeypatch.setattr("os._exit", lambda *_: pytest.fail("normal cleanup bypassed")) monkeypatch.setattr(main, "_update_preflight_handled", lambda args: False) monkeypatch.setattr(main, "_install_hangup_protection", lambda **kw: None) finalized = [] monkeypatch.setattr(main, "_finalize_update_output", finalized.append) def fail(args, gateway_mode): + assert update_lock.update_marker_path().is_file() update_receipt.begin_update_receipt() - raise failure + if failure is not None: + raise failure monkeypatch.setattr(update_cmd, "_cmd_update_impl", fail) - with pytest.raises(SystemExit) as error: + if exception is None: main.cmd_update(SimpleNamespace(gateway=True)) - assert error.value.code == 1 + else: + with pytest.raises(exception) as error: + main.cmd_update(SimpleNamespace(gateway=True)) + if exception is SystemExit: + assert error.value.code == (failure.code if isinstance(failure, SystemExit) else code) receipt = update_receipt.read_latest_receipt() assert receipt is not None - assert receipt["exit_code"] == 1 - assert receipt["outcome"] == "failed" - assert (tmp_path / ".update_exit_code").read_text().strip() == "1" + assert receipt["exit_code"] == code + assert receipt["outcome"] == ("failed" if code else "success") + if code: + assert (tmp_path / ".update_exit_code").read_text().strip() == "1" assert finalized == [None] lock = update_lock.UpdateLock() assert lock.acquire() lock.release() - assert "Update failed" in capsys.readouterr().out diff --git a/tests/hermes_cli/test_update_receipt_pm_embed.py b/tests/hermes_cli/test_update_receipt_pm_embed.py index bcf1175e3e..04dc60aac4 100644 --- a/tests/hermes_cli/test_update_receipt_pm_embed.py +++ b/tests/hermes_cli/test_update_receipt_pm_embed.py @@ -71,6 +71,7 @@ def test_update_receipt_embeds_pm_sections(homed): path = ur.finalize_update_receipt("success") data = json.loads((homed / "logs" / "update_receipts" / "latest.json").read_text(encoding="utf-8")) + assert json.loads(path.read_text(encoding="utf-8")) == data assert data["outcome"] == "success" assert data["pm_venv_rebuild"] == {"ok": True, "reason": ""} assert data["pm_feature_list"] == ["web", "acp"] @@ -91,13 +92,6 @@ def test_legacy_worker_receipt_fields_still_embed(homed): assert data["pm_plugin_bisect"] == legacy["plugin_bisect"] -def test_update_receipt_without_sync_embeds_nothing(homed): - ur.begin_update_receipt() - ur.finalize_update_receipt("success") - data = json.loads((homed / "logs" / "update_receipts" / "latest.json").read_text(encoding="utf-8")) - assert "pm_venv_rebuild" not in data - assert data["outcome"] == "success" - def test_stale_sync_from_before_the_update_is_never_embedded(homed): """The audit defect: an old sync receipt on disk (latest.json's newest) @@ -152,6 +146,7 @@ def test_nested_update_ids_do_not_cross_embed(homed): outer_id = ur.current_correlation_id() pm_receipt_mod.begin("sync") pm_receipt_mod.record_venv_rebuild(True, "outer rebuild") + pm_receipt_mod.record_step("outer-sync", True) pm_receipt_mod.finalize("ok") ur.begin_update_receipt() # nested update — new id, outer preserved behind the token @@ -159,11 +154,15 @@ def test_nested_update_ids_do_not_cross_embed(homed): assert inner_id != outer_id pm_receipt_mod.begin("sync") pm_receipt_mod.record_venv_rebuild(True, "inner rebuild") + pm_receipt_mod.record_step("inner-sync", True) pm_receipt_mod.finalize("ok") inner_path = ur.finalize_update_receipt("success") assert inner_path is not None assert json.loads(inner_path.read_text(encoding="utf-8"))["pm_venv_rebuild"]["reason"] == "inner rebuild" + assert pm_receipt_mod.last_for_update(inner_id) is None + assert ur.current_correlation_id() == outer_id + assert pm_receipt_mod.last_for_update(outer_id)["steps"][0]["name"] == "outer-sync" # outer finalize: the outer sync is STILL its own completion — the # nested update's finalize restored the outer receipt and must not @@ -174,42 +173,20 @@ def test_nested_update_ids_do_not_cross_embed(homed): assert outer_data["update_id"] == outer_id assert outer_data["pm_venv_rebuild"]["reason"] == "outer rebuild" assert "inner rebuild" not in json.dumps(outer_data) + assert outer_data["pm_steps"][0]["name"] == "outer-sync" + assert pm_receipt_mod.last_for_update(outer_id) is None + assert inner_path != outer_path + inner_data = json.loads(inner_path.read_text(encoding="utf-8")) + assert inner_data["update_id"] == inner_id + assert inner_data["pm_steps"][0]["name"] == "inner-sync" + assert inner_data["pm_venv_rebuild"]["reason"] == "inner rebuild" + latest = json.loads((homed / "logs/update_receipts/latest.json").read_text(encoding="utf-8")) + assert latest == outer_data # outermost finalize popped the last receipt: no correlation remains assert ur.current_correlation_id() is None -def test_both_nested_receipts_still_read_correctly_after_all_finalizations(homed): - """Invariant: inner and outer receipts have UNIQUE file names (same - process, possibly the same second) and each exact path still reads its - own story AFTER every finalize — no overwrite, no cross-contamination, - including the latest.json pointer (outer finished last).""" - import pm.receipt as pm_receipt_mod - - ur.begin_update_receipt() - pm_receipt_mod.begin("sync") - pm_receipt_mod.record_venv_rebuild(True, "outer rebuild") - pm_receipt_mod.finalize("ok") - - ur.begin_update_receipt() - pm_receipt_mod.begin("sync") - pm_receipt_mod.record_venv_rebuild(True, "inner rebuild") - pm_receipt_mod.finalize("ok") - - inner_path = ur.finalize_update_receipt("success") - outer_path = ur.finalize_update_receipt("success") - - assert inner_path != outer_path - assert inner_path.is_file() and outer_path.is_file() - inner_data = json.loads(inner_path.read_text(encoding="utf-8")) - outer_data = json.loads(outer_path.read_text(encoding="utf-8")) - assert inner_data["pm_venv_rebuild"]["reason"] == "inner rebuild" - assert outer_data["pm_venv_rebuild"]["reason"] == "outer rebuild" - # latest.json points at the LAST finalization (the outer run) - latest = json.loads((homed / "logs" / "update_receipts" / "latest.json").read_text(encoding="utf-8")) - assert latest["update_id"] == outer_data["update_id"] - assert latest["pm_venv_rebuild"]["reason"] == "outer rebuild" - def test_sync_after_nested_update_finalizes_embeds_into_outer(homed): """Continuing the outer update after the nested one closed: a sync diff --git a/tests/hermes_cli/test_update_secret_import_lock.py b/tests/hermes_cli/test_update_secret_import_lock.py index 3dd95042d5..e175af9235 100644 --- a/tests/hermes_cli/test_update_secret_import_lock.py +++ b/tests/hermes_cli/test_update_secret_import_lock.py @@ -38,7 +38,8 @@ secrets: ) dispatch = ( - "hermes_main.cmd_update = lambda _args: 0\n" + "from hermes_cli import update_cmd\n" + "update_cmd._cmd_update_check = lambda **kwargs: 0\n" "hermes_main.main()\n" if run_main else "" diff --git a/tests/hermes_cli/test_update_self_lock.py b/tests/hermes_cli/test_update_self_lock.py deleted file mode 100644 index 6ce876dcd5..0000000000 --- a/tests/hermes_cli/test_update_self_lock.py +++ /dev/null @@ -1,62 +0,0 @@ -"""CLI metadata dispatch keeps credential implementations lazy.""" -import subprocess -import sys -import textwrap -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] - -class TestUpdateEntrypointImportHygiene: - """Subprocess-verified: the CLI/update path never eagerly loads crypto. - - Empirical sys.modules assertions in a clean interpreter — the technique - that pinned #86735's root cause. If any future module-level import of - cryptography (or another self-locking native module) creeps back into - the startup path, these fail before a Windows user ever hits the loop. - """ - - def _run(self, code: str) -> subprocess.CompletedProcess[str]: - return subprocess.run( - [sys.executable, "-c", code], - capture_output=True, - text=True, - cwd=str(ROOT), - timeout=120, - ) - - def test_import_main_does_not_load_self_locking_modules(self): - result = self._run( - textwrap.dedent( - """ - import sys - import hermes_cli.main - assert "cryptography.hazmat.bindings._rust" not in sys.modules - print("OK") - """ - ) - ) - assert result.returncode == 0, result.stdout + result.stderr - assert "OK" in result.stdout - - def test_update_dispatch_does_not_load_cryptography(self): - result = self._run( - textwrap.dedent( - """ - import sys - from unittest.mock import patch - sys.argv = ["hermes", "update", "--check"] - import hermes_cli.main as m - with patch("hermes_cli.update_cmd._cmd_update_check", lambda *a, **k: 0): - try: - m.main() - except SystemExit: - pass - assert "cryptography.hazmat.bindings._rust" not in sys.modules, ( - "update dispatch eagerly loaded cryptography._rust" - ) - print("OK") - """ - ) - ) - assert result.returncode == 0, result.stdout + result.stderr - assert "OK" in result.stdout diff --git a/tests/hermes_cli/test_update_shim_self_lock.py b/tests/hermes_cli/test_update_shim_self_lock.py index ef2308c60b..3ab6c6992e 100644 --- a/tests/hermes_cli/test_update_shim_self_lock.py +++ b/tests/hermes_cli/test_update_shim_self_lock.py @@ -6,20 +6,6 @@ import pytest from hermes_cli import main as cli_main, main_install_repair -def test_historical_dependency_handoff_stops_for_relaunch(monkeypatch, capsys): - import subprocess - - def forbidden(*args, **kwargs): - pytest.fail("historical sync must not spawn another updater") - - monkeypatch.setattr(subprocess, "Popen", forbidden) - monkeypatch.setenv("HERMES_UPDATE_REEXEC", "1") - with pytest.raises(SystemExit) as stopped: - cli_main._reexec_dependency_sync_off_windows_shim() - assert stopped.value.code == 0 - assert "run `hermes` again" in capsys.readouterr().err - - def test_pending_rename_filter_drops_only_our_shim_pairs(): shims = [Path(r"C:\hermes\venv\Scripts\hermes.exe")] entries = [ @@ -49,4 +35,4 @@ def test_legacy_shim_recovery_finds_both_layouts(tmp_path, monkeypatch, venv_nam scripts = tmp_path / venv_name / "Scripts" scripts.mkdir(parents=True) monkeypatch.setattr(cli_main, "PROJECT_ROOT", tmp_path) - assert main_install_repair._venv_scripts_dir() == scripts \ No newline at end of file + assert main_install_repair._venv_scripts_dir() == scripts diff --git a/tests/hermes_cli/test_update_sqlite_remediation.py b/tests/hermes_cli/test_update_sqlite_remediation.py index 3843dbe0b9..d0f662e61b 100644 --- a/tests/hermes_cli/test_update_sqlite_remediation.py +++ b/tests/hermes_cli/test_update_sqlite_remediation.py @@ -1,93 +1,43 @@ -"""Post-update reporting for unresolved SQLite WAL-reset risk.""" - +"""Selected-runtime admission and dashboard completion bookkeeping.""" from pathlib import Path from types import SimpleNamespace +import sys -from hermes_cli import update_cmd -import hermes_cli.update_cmd_maint as update_cmd_maint +import pytest + +from hermes_cli import update_cmd, update_cmd_maint -def test_runtime_status_probes_running_venv_outside_checkout(tmp_path, monkeypatch): - running_python = tmp_path / "venv312" / "bin" / "python" - observed = [] - vulnerable = SimpleNamespace(wal_reset_vulnerable=True) - monkeypatch.setattr("hermes_constants.project_venv_dir", lambda _root: None) - monkeypatch.setattr(update_cmd.sys, "executable", str(running_python)) - monkeypatch.setattr( - "hermes_cli.sqlite_runtime.probe_sqlite_runtime", - lambda python: observed.append(Path(python)) or vulnerable, - ) - - safe, info = update_cmd._post_update_sqlite_runtime_status() - - assert observed == [running_python] - assert safe is False - assert info is vulnerable +@pytest.mark.parametrize('verdict', ['safe', 'unsafe', 'unavailable']) +@pytest.mark.parametrize('message', ['✓ Update complete!', '✓ Already up to date!']) +@pytest.mark.parametrize('action_id', ['a' * 32, 'invalid']) +def test_selected_sqlite_controls_completion_and_action_receipt(tmp_path, monkeypatch, capsys, verdict, message, action_id): + selected = tmp_path / 'selected/python' + info = None if verdict == 'unavailable' else SimpleNamespace( + wal_reset_vulnerable=verdict == 'unsafe', sqlite_version_string='3.46.1') + probes = [] + monkeypatch.setattr(sys, 'executable', str(selected)) + monkeypatch.setattr('hermes_constants.project_venv_dir', lambda _: tmp_path / 'obsolete-venv') + monkeypatch.setattr('hermes_cli.sqlite_runtime.probe_sqlite_runtime', lambda python: probes.append(python) or info) + monkeypatch.setattr(update_cmd, '_branch_head_suffix', lambda: '') + monkeypatch.setenv('HERMES_ACTION_ID', action_id) + assert update_cmd_maint._print_verified_update_completion(message) is (verdict != 'unsafe') + assert probes == [Path(selected)] + output = capsys.readouterr().out + assert (message in output) is (verdict != 'unsafe') + assert ('=== hermes-update completed' in output) is (verdict != 'unsafe' and action_id != 'invalid') + if verdict == 'unsafe': + for text in ('SQLite 3.46.1', 'WAL-reset', 'uv-managed Python', 'hermes doctor'): + assert text in output + elif action_id != 'invalid': + assert f'=== hermes-update completed {action_id} ===' in output -def test_runtime_status_uses_selected_python_not_legacy_repo_venv(tmp_path, monkeypatch): - selected = tmp_path / "selected/bin/python" - monkeypatch.setattr("hermes_constants.project_venv_dir", lambda root: tmp_path / "obsolete-venv") - monkeypatch.setattr(update_cmd.sys, "executable", str(selected)) - observed = [] - safe = SimpleNamespace(wal_reset_vulnerable=False) - monkeypatch.setattr("hermes_cli.sqlite_runtime.probe_sqlite_runtime", lambda python: observed.append(Path(python)) or safe) - assert update_cmd._post_update_sqlite_runtime_status() == (True, safe) - assert observed == [selected] - - -def test_summary_withholds_success_when_sqlite_remediation_failed(capsys, monkeypatch): - monkeypatch.setattr( - update_cmd, - "_post_update_sqlite_runtime_status", - lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")), - raising=False, - ) - monkeypatch.setattr( - update_cmd_maint, - "_post_update_sqlite_runtime_status", - lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")), - raising=False, - ) - monkeypatch.setattr( - update_cmd, - "_update_complete_message", - lambda _version: "✓ Update complete! (v0.20.5)", - ) - monkeypatch.setattr( - update_cmd_maint, - "_update_complete_message", - lambda _version: "✓ Update complete! (v0.20.5)", - ) - - complete = update_cmd_maint._print_verified_update_completion( - update_cmd_maint._update_complete_message("0.20.4"), - ) - - out = capsys.readouterr().out - assert complete is False - assert "Update complete" not in out - assert "SQLite 3.46.1" in out - assert "WAL-reset" in out - assert "uv-managed Python" in out - assert "hermes doctor" in out - - -def test_current_checkout_completion_is_verified_before_success(capsys, monkeypatch): - monkeypatch.setattr( - update_cmd, - "_post_update_sqlite_runtime_status", - lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")), - ) - monkeypatch.setattr( - update_cmd_maint, - "_post_update_sqlite_runtime_status", - lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")), - ) - - complete = update_cmd._print_verified_update_completion("✓ Already up to date!") - - out = capsys.readouterr().out - assert complete is False - assert "Already up to date" not in out - assert "SQLite 3.46.1" in out +@pytest.mark.parametrize('already_restarted_units', [None, {'hermes-serve'}]) +def test_dashboard_refresh_preserves_restart_bookkeeping(already_restarted_units, monkeypatch, capsys): + calls = [] + monkeypatch.setattr(update_cmd, '_m', lambda: SimpleNamespace( + _kill_stale_dashboard_processes=lambda **kwargs: calls.append(kwargs) or {'unrecovered': [1234]})) + update_cmd_maint._refresh_dashboard_after_update(already_restarted_units=already_restarted_units) + assert calls == [{'restart_managed': True, 'already_restarted_units': already_restarted_units}] + assert 'could not be auto-restarted' in capsys.readouterr().out diff --git a/tests/hermes_cli/test_update_target_identity.py b/tests/hermes_cli/test_update_target_identity.py index d3ced430a3..1047f0bad8 100644 --- a/tests/hermes_cli/test_update_target_identity.py +++ b/tests/hermes_cli/test_update_target_identity.py @@ -14,6 +14,7 @@ import pytest from hermes_cli import main as cli_main, update_cmd, update_receipt from hermes_cli.update_inventory import UpdatePlan +from hermes_cli.update_cmd import _sync_with_upstream_if_needed def git(root, *args): @@ -86,6 +87,77 @@ def update_tree(tmp_path, monkeypatch): args=args, resumed=resumed, requests=requests, plans=plans) +@pytest.mark.parametrize('case', ['main', 'explicit', 'missing', 'no-move', 'wrong-branch', + 'fork-no-upstream', 'fork-upstream', 'check-main', + 'check-explicit', 'check-missing', 'check-upstream']) +def test_branch_update_uses_real_refs_and_completion_request(update_tree, monkeypatch, case, capsys): + t = update_tree + git(t.clone, 'checkout', '-q', 'main') + t.args.channel = 'main' + t.args.gateway = True + t.args.check = case.startswith('check-') + monkeypatch.setattr(cli_main, '_sync_with_upstream_if_needed', _sync_with_upstream_if_needed) + if case in {'explicit', 'check-explicit'}: + git(t.origin, 'branch', 'chosen', t.wanted) + t.args.branch = 'chosen' + if case in {'missing', 'check-missing'}: + t.args.branch = 'absent' + if case.startswith('fork-') or case == 'check-upstream': + # Origin is current; only upstream has the next commit. + git(t.origin, 'reset', '--hard', t.base) + if case in {'fork-upstream', 'check-upstream'}: + upstream = t.origin.parent / 'upstream' + git(t.origin.parent, 'clone', '-q', str(t.origin), str(upstream)) + git(upstream, 'reset', '--hard', t.newer) + git(t.clone, 'remote', 'add', 'upstream', str(upstream)) + run = subprocess.run + + def fault(command, *args, **kwargs): + if 'merge' in command and '--ff-only' in command: + if case == 'no-move': + return subprocess.CompletedProcess(command, 0, stdout='', stderr='') + result = run(command, *args, **kwargs) + if case == 'wrong-branch': + run(['git', 'checkout', '-qb', 'wrong'], cwd=t.clone, check=True, capture_output=True) + return result + return run(command, *args, **kwargs) + + monkeypatch.setattr(subprocess, 'run', fault) + if case == 'fork-upstream': + # The checkout policy must consult upstream even when origin is current. + plan = update_cmd._prepare_checkout_for_update( + ['git'], 'main', 'main', is_fork=True, assume_yes=True, gateway_mode=False, + gw_input_fn=None, switch_branch=False, _windows_gateway_resume=None) + assert plan.commit_count > 0 and plan.upstream_checked + assert git(t.clone, 'rev-parse', 'HEAD') == t.newer + return + fails = case in {'missing', 'check-missing', 'no-move', 'wrong-branch'} + if fails: + with pytest.raises(SystemExit) as error: + cli_main.cmd_update(t.args) + assert error.value.code == 1 + assert t.requests == [] + else: + cli_main.cmd_update(t.args) + if t.args.check: + assert t.requests == [] + assert git(t.clone, 'rev-parse', 'HEAD') == t.base + output = capsys.readouterr().out + assert ('absent' if case == 'check-missing' else 'update') in output.lower() + if case == 'check-upstream': + assert git(t.clone, 'rev-parse', 'upstream/main') == t.newer + else: + request, = t.requests + assert request['assume_yes'] is True + assert request['gateway_mode'] is True + expected = t.base if case == 'fork-no-upstream' else t.wanted if case == 'explicit' else t.newer + assert git(t.clone, 'rev-parse', 'HEAD') == expected + assert request['source'] == str(t.clone) + if case == 'fork-no-upstream': + assert 'official repo not checked' in request['completion_message'] + assert git(t.clone, 'remote') == 'origin' + + @pytest.mark.parametrize('server', ['sha', 'tag-fallback', 'moved-sha', 'moved-fallback', 'at-release', 'ahead-release', 'explicit-branch']) def test_stable_git_uses_remote_identity_without_moving_local_tags(update_tree, monkeypatch, server): diff --git a/tests/hermes_cli/test_update_yes_flag.py b/tests/hermes_cli/test_update_yes_flag.py deleted file mode 100644 index 4ba8774658..0000000000 --- a/tests/hermes_cli/test_update_yes_flag.py +++ /dev/null @@ -1,259 +0,0 @@ -"""Tests for `hermes update --yes / -y` — assume yes for interactive prompts. - -Covers: - 1. argparse parses the flag - 2. Config-migration prompt is auto-answered (no input() call) and migrate_config - runs with interactive=False so API-key prompts are skipped - 3. Autostash restore prompt is auto-answered (prompt_for_restore == False, no - input() call) and the stash is applied automatically -""" - -import subprocess -from types import SimpleNamespace -from unittest.mock import patch - -import pytest - -from hermes_cli.main import cmd_update - -pytestmark = pytest.mark.usefixtures( - "isolated_update_processes", "isolated_update_checkout", -) - - -@pytest.fixture(autouse=True) -def _isolate_venv_holders(monkeypatch): - """The update flow's venv-holder guard sees the live gateway processes on - a dev machine and aborts with SystemExit 2 before reaching the branch - logic under test. Isolate it so the test exercises the intended path.""" - monkeypatch.setattr("hermes_cli.update_cmd_windows._detect_venv_python_processes", lambda: []) - monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None) - - -@pytest.fixture(autouse=True) -def _isolate_update(monkeypatch): - from hermes_cli import update_cmd - - monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None)) - - -def _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1", dirty=False -): - """Minimal subprocess.run side_effect for the update flow.""" - - def side_effect(cmd, **kwargs): - joined = " ".join(str(c) for c in cmd) - - if "rev-parse" in joined and "--abbrev-ref" in joined: - return subprocess.CompletedProcess(cmd, 0, stdout=f"{branch}\n", stderr="") - if "rev-parse" in joined and "--verify" in joined: - return subprocess.CompletedProcess( - cmd, 0 if verify_ok else 128, stdout="", stderr="" - ) - if "rev-list" in joined: - return subprocess.CompletedProcess( - cmd, 0, stdout=f"{commit_count}\n", stderr="" - ) - # `git status --porcelain` for dirty-tree detection during autostash. - if "status" in joined and "--porcelain" in joined: - out = " M hermes_cli/main.py\n" if dirty else "" - return subprocess.CompletedProcess(cmd, 0, stdout=out, stderr="") - # `git stash list` — return a stash ref when dirty (so _stash_local_changes - # gets something to return). _stash_local_changes_if_needed is what we - # actually patch in tests that exercise restore, so this is a catch-all. - if "stash" in joined and "list" in joined: - return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="") - return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="") - - return side_effect - - -class TestUpdateYesConfigMigration: - """--yes auto-answers the config-migration prompt and skips API-key prompts.""" - - @patch("hermes_cli.update_cmd._reload_config_modules") - @patch("hermes_cli.config.migrate_config") - @patch("hermes_cli.config.check_config_version", return_value=(1, 2)) - @patch("hermes_cli.config.get_missing_config_fields", return_value=[]) - @patch("hermes_cli.config.get_missing_env_vars", return_value=["NEW_KEY"]) - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_yes_auto_migrates_without_input( - self, - mock_run, - _mock_which, - _mock_missing_env, - _mock_missing_cfg, - _mock_version, - mock_migrate, - _mock_reload, - capsys, - ): - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1" - ) - mock_migrate.return_value = {"env_added": [], "config_added": []} - - args = SimpleNamespace(yes=True) - - with patch("builtins.input") as mock_input: - cmd_update(args) - # Never prompted the user. - mock_input.assert_not_called() - - # migrate_config was invoked with interactive=False — API-key prompts - # are suppressed, matching gateway-mode semantics. - assert mock_migrate.call_count == 1 - _, kwargs = mock_migrate.call_args - assert kwargs.get("interactive") is False - - out = capsys.readouterr().out - assert "--yes: auto-applying config migration" in out - # The "Would you like to configure them now?" prompt text never appears. - assert "Would you like to configure them now?" not in out - - @patch("hermes_cli.update_cmd._reload_config_modules") - @patch("hermes_cli.config.migrate_config") - @patch("hermes_cli.config.check_config_version", return_value=(1, 2)) - @patch("hermes_cli.config.get_missing_config_fields", return_value=[]) - @patch("hermes_cli.config.get_missing_env_vars", return_value=["NEW_KEY"]) - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_no_yes_flag_still_prompts_in_tty( - self, - mock_run, - _mock_which, - _mock_missing_env, - _mock_missing_cfg, - _mock_version, - mock_migrate, - _mock_reload, - capsys, - ): - """Regression guard: without --yes, the TTY prompt path still fires.""" - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1" - ) - mock_migrate.return_value = {"env_added": [], "config_added": []} - - args = SimpleNamespace(yes=False) - - # Patch ``sys.stdin.isatty`` and ``sys.stdout.isatty`` directly on the - # real ``sys`` module instead of replacing ``hermes_cli.main.sys`` with - # a MagicMock. The MagicMock approach was flaky under parallel test runs - # — a sibling test that imported ``hermes_cli.main`` first could leave - # a different ``sys`` reference resolved inside the function and the - # mock would never be consulted, with CI then taking the - # "Non-interactive session" branch instead of prompting. - import sys as _sys - - with patch("builtins.input", return_value="n") as mock_input, patch.object( - _sys.stdin, "isatty", return_value=True - ), patch.object(_sys.stdout, "isatty", return_value=True): - cmd_update(args) - # The user was actually prompted. - assert mock_input.called - prompts = [c.args[0] if c.args else "" for c in mock_input.call_args_list] - assert any("configure them now" in p for p in prompts) - - -class TestUpdateYesStashRestore: - """--yes auto-restores the pre-update autostash without prompting.""" - - - -class TestUnicodeDecodeErrorInUpdatePrompts: - """Regression tests (review of #68497): input() can raise - UnicodeDecodeError when the terminal encoding can't decode the byte - sequence (e.g. a non-UTF-8 locale, or an embedded terminal). Three - interactive update prompts call input() directly -- the config- - migration prompt, the stash-restore prompt, and the upstream-remote - prompt -- and each must fail safe (skip, don't crash) rather than let - the exception escape and crash `hermes update` mid-flight. - """ - - @patch("hermes_cli.update_cmd._reload_config_modules") - @patch("hermes_cli.config.migrate_config") - @patch("hermes_cli.config.check_config_version", return_value=(1, 2)) - @patch("hermes_cli.config.get_missing_config_fields", return_value=[]) - @patch("hermes_cli.config.get_missing_env_vars", return_value=["NEW_KEY"]) - @patch("shutil.which", return_value=None) - @patch("subprocess.run") - def test_unicode_decode_error_in_tty_skips_and_prints_hint( - self, - mock_run, - _mock_which, - _mock_missing_env, - _mock_missing_cfg, - _mock_version, - mock_migrate, - _mock_reload, - capsys, - ): - mock_run.side_effect = _make_run_side_effect( - branch="main", verify_ok=True, commit_count="1" - ) - mock_migrate.return_value = {"env_added": [], "config_added": []} - args = SimpleNamespace(yes=False) - - import sys as _sys - - with patch( - "builtins.input", - side_effect=UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid byte"), - ), patch.object(_sys.stdin, "isatty", return_value=True), patch.object( - _sys.stdout, "isatty", return_value=True - ): - cmd_update(args) # must not raise - - out = capsys.readouterr().out - assert "hermes config migrate" in out - mock_migrate.assert_not_called() - - def test_stash_restore_unicode_decode_error_falls_through_to_skip(self, tmp_path, capsys): - from hermes_cli.update_cmd import _restore_stashed_changes - - with patch( - "builtins.input", - side_effect=UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid byte"), - ): - result = _restore_stashed_changes( - ["git"], tmp_path, "stash@{0}", prompt_user=True, input_fn=None, - ) # must not raise - - assert result is False - out = capsys.readouterr().out - assert "Skipped restoring local changes" in out - assert "git stash apply stash@{0}" in out - - def test_stash_restore_eof_error_still_falls_through_to_skip(self, tmp_path): - """Sanity: this fix must not regress the pre-existing EOFError case, - which the raw input() path had no guard for at all before this fix.""" - from hermes_cli.update_cmd import _restore_stashed_changes - - with patch("builtins.input", side_effect=EOFError()): - result = _restore_stashed_changes( - ["git"], tmp_path, "stash@{0}", prompt_user=True, input_fn=None, - ) # must not raise - - assert result is False - - def test_upstream_remote_prompt_unicode_decode_error_falls_through_to_skip( - self, tmp_path - ): - from hermes_cli.update_cmd import _sync_with_upstream_if_needed - - with patch( - "hermes_cli.update_cmd._has_upstream_remote", return_value=False - ), patch( - "hermes_cli.update_cmd._should_skip_upstream_prompt", return_value=False - ), patch( - "hermes_cli.update_cmd._add_upstream_remote" - ) as mock_add, patch( - "builtins.input", - side_effect=UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid byte"), - ): - _sync_with_upstream_if_needed(["git"], tmp_path) # must not raise - - mock_add.assert_not_called() diff --git a/tests/hermes_cli/test_update_zip_atomic_replace.py b/tests/hermes_cli/test_update_zip_atomic_replace.py deleted file mode 100644 index 51eaa5ba64..0000000000 --- a/tests/hermes_cli/test_update_zip_atomic_replace.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Regression: the ZIP-update directory replace must never leave a half-deleted tree. - -Issue #49145: on Windows the ZIP-update path did ``rmtree(dst); copytree(...)``. -A copy that failed partway (file locks / flaky I/O — the very conditions the ZIP -path exists to work around) left the directory deleted with nothing copied back, -which broke ``hermes --tui`` because ``ui-tui/`` had vanished. - -``_atomic_replace_dir`` stages the new copy first and only swaps it in on full -success, so a mid-copy failure leaves the original directory intact. -""" - -from __future__ import annotations - -import shutil -from pathlib import Path - -import pytest - -from hermes_cli.update_cmd import _atomic_replace_dir - - -def test_atomic_replace_swaps_content_on_success(tmp_path: Path) -> None: - src = tmp_path / "src" / "ui-tui" - src.mkdir(parents=True) - (src / "new.txt").write_text("NEW") - - dst = tmp_path / "install" / "ui-tui" - dst.mkdir(parents=True) - (dst / "old.txt").write_text("OLD") - - _atomic_replace_dir(str(src), str(dst)) - - assert (dst / "new.txt").read_text() == "NEW" - assert not (dst / "old.txt").exists() - # No staging/backup siblings left behind. - assert not (dst.parent / "ui-tui.hermes-update-staging").exists() - assert not (dst.parent / "ui-tui.hermes-update-old").exists() - - diff --git a/tests/hermes_cli/test_update_zip_completion.py b/tests/hermes_cli/test_update_zip_completion.py index 60542b8838..72e025b432 100644 --- a/tests/hermes_cli/test_update_zip_completion.py +++ b/tests/hermes_cli/test_update_zip_completion.py @@ -41,10 +41,18 @@ def zip_update(tmp_path, monkeypatch, isolated_source_completion): root.mkdir() (root / "pyproject.toml").write_text('[project]\nversion="1.0"\n', encoding="utf-8") (root / "payload.txt").write_text("old", encoding="utf-8") + for name in ("tools/code.py", "apps/desktop/source.js", "apps/desktop/release/Hermes.exe", + "venv/keep", "node_modules/keep", ".env"): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("retained", encoding="utf-8") archive = tmp_path / "source.zip" with zipfile.ZipFile(archive, "w") as out: out.writestr("hermes-agent-main/pyproject.toml", '[project]\nversion="2.0"\n') out.writestr("hermes-agent-main/payload.txt", "new") + for name in ("new-entry/data", "tools/code.py", "apps/desktop/source.js", + "venv/keep", "node_modules/keep", ".env"): + out.writestr("hermes-agent-main/" + name, "new") # Only redirect transport: extraction, staging, dirty recheck and swap run. monkeypatch.setattr("urllib.request.urlretrieve", lambda url, dst: urlretrieve(archive.as_uri(), dst)) monkeypatch.setattr(main, "PROJECT_ROOT", root) @@ -133,6 +141,10 @@ def test_zip_command_migrates_profiles_recovers_snapshot_and_verifies_fleet( assert (state.sibling / ".env").read_bytes() == (state.active / ".env").read_bytes() assert json.loads(state.jobs.read_text()) == state.original_jobs assert (state.root / "payload.txt").read_text() == "new" + for name in ("tools/code.py", "apps/desktop/source.js", "new-entry/data"): + assert (state.root / name).read_text(encoding="utf-8") == "new" + for name in ("apps/desktop/release/Hermes.exe", "venv/keep", "node_modules/keep", ".env"): + assert (state.root / name).read_text(encoding="utf-8") == "retained" assert "v1.0 → v2.0" in capsys.readouterr().out assert state.events == ["prepare", *([("marker", True)] if gateway_mode else []), "restart", "resume", "finalize"] @@ -174,7 +186,7 @@ def test_zip_helper_propagates_completion_status_after_real_verification(zip_upd @pytest.mark.parametrize("route", ["direct", "git-failure"]) -@pytest.mark.parametrize("failure", ["swap", "preparation"]) +@pytest.mark.parametrize("failure", ["swap", "late-swap", "stage", "preparation"]) def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, monkeypatch, route, failure): import os import pm @@ -183,6 +195,8 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon before = {profile: (profile / "config.yaml").read_bytes() for profile in (state.active, state.sibling)} old_project = (state.root / "pyproject.toml").read_bytes() + original_tree = {p.relative_to(state.root): p.read_bytes() + for p in state.root.rglob("*") if p.is_file()} monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (route == "direct", ["git"], False)) monkeypatch.setattr(main, "_warn_orphaned_update_autostashes", lambda *args: None) monkeypatch.setattr(update_cmd, "_should_zip_fallback_on_update_error", lambda exc: True) @@ -191,17 +205,28 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon raise subprocess.CalledProcessError(1, ["git", "fetch"]) monkeypatch.setattr(update_cmd, "_git_run", fail_fetch) installed = [] - if failure == "swap": + if failure in {"swap", "late-swap"}: rename = os.rename def fail_second_swap(src, dst): if str(src).endswith(".hermes-update-staging"): installed.append(dst) - if len(installed) == 2: + if len(installed) == (5 if failure == "late-swap" else 2): raise OSError("locked replacement") return rename(src, dst) monkeypatch.setattr(os, "rename", fail_second_swap) expected = SystemExit + elif failure == "stage": + import shutil + + copytree = shutil.copytree + + def fail_copy(src, dst, *args, **kwargs): + if str(dst).endswith(".hermes-update-staging"): + raise OSError("staging disk full") + return copytree(src, dst, *args, **kwargs) + monkeypatch.setattr(shutil, "copytree", fail_copy) + expected = SystemExit else: def fail_preparation(*args, **kwargs): assert (state.root / "payload.txt").read_text() == "new" @@ -210,11 +235,14 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon expected = pm.InstallError with pytest.raises(expected) as raised: update_cmd._cmd_update_impl(SimpleNamespace(branch="main", yes=True), gateway_mode=True) - if failure == "swap": + if failure in {"swap", "late-swap"}: assert raised.value.code == 1 - assert len(installed) == 2 + assert len(installed) == (5 if failure == "late-swap" else 2) assert (state.root / "pyproject.toml").read_bytes() == old_project assert (state.root / "payload.txt").read_text() == "old" + if failure != "preparation": + assert {p.relative_to(state.root): p.read_bytes() + for p in state.root.rglob("*") if p.is_file()} == original_tree assert state.events == ["resume"] assert state.token["resume_needed"] is False assert {profile: (profile / "config.yaml").read_bytes() for profile in before} == before @@ -222,3 +250,67 @@ def test_zip_failure_recovers_pause_without_completion_mutations(zip_update, mon assert json.loads(state.jobs.read_text()) == state.original_jobs assert not (state.active / "logs/update_receipts/latest.json").exists() assert not list(state.root.glob("*.hermes-update-*")) + + +@pytest.mark.parametrize("entry", ["payload.txt", "tools"]) +def test_zip_recovers_crashed_backup_before_failed_copy_and_retry(zip_update, monkeypatch, entry): + import shutil + + root = zip_update.root + target = root / entry + backup = root / (entry + ".hermes-update-old") + target.rename(backup) + leftover = root / (entry + ".hermes-update-staging") + leftover.write_text("interrupted copy", encoding="utf-8") + function = "copytree" if entry == "tools" else "copy2" + original = getattr(shutil, function) + + def fail(src, dst, *args, **kwargs): + if str(dst) == str(leftover): + raise OSError("copy refused after crash") + return original(src, dst, *args, **kwargs) + + with monkeypatch.context() as fault: + fault.setattr(shutil, function, fail) + with pytest.raises(SystemExit) as error: + update_cmd_zip._download_and_swap_zip("main", "local fixture") + assert error.value.code == 1 + witness = target / "code.py" if entry == "tools" else target + assert witness.read_text(encoding="utf-8") == ("retained" if entry == "tools" else "old") + assert not list(root.glob("*.hermes-update-*")) + update_cmd_zip._download_and_swap_zip("main", "local fixture") + assert witness.read_text(encoding="utf-8") == "new" + assert not list(root.glob("*.hermes-update-*")) + + +def test_atomic_directory_compat_entrypoint(tmp_path): + src, dst = tmp_path / "src", tmp_path / "dst" + src.mkdir() + dst.mkdir() + (src / "new").write_text("new", encoding="utf-8") + (dst / "old").write_text("old", encoding="utf-8") + update_cmd_zip._atomic_replace_dir(str(src), str(dst)) + assert {p.name for p in dst.iterdir()} == {"new"} + assert (dst / "new").read_text(encoding="utf-8") == "new" + assert not list(tmp_path.glob("*.hermes-update-*")) + + +def test_zip_refuses_non_main_before_transport(zip_update, monkeypatch, capsys): + monkeypatch.setattr('urllib.request.urlretrieve', lambda *_: pytest.fail('unsupported branch downloaded')) + before = (zip_update.root / 'payload.txt').read_bytes() + with pytest.raises(SystemExit) as error: + update_cmd_zip._update_via_zip(SimpleNamespace(branch='feature'), completion_request={}) + assert error.value.code == 1 + assert '--branch=feature is not supported' in capsys.readouterr().out + assert (zip_update.root / 'payload.txt').read_bytes() == before + + +@pytest.mark.parametrize("windows,folder,executable", [(True, "Scripts", "python.exe"), (False, "bin", "python")]) +def test_venv_layout_explicit_and_native(tmp_path, windows, folder, executable): + import os + from hermes_constants import venv_bin_dir, venv_python_path + + assert venv_bin_dir(tmp_path, windows=windows) == tmp_path / folder + assert venv_python_path(str(tmp_path), windows=windows) == tmp_path / folder / executable + if windows == (os.name == "nt"): + assert venv_python_path(tmp_path) == tmp_path / folder / executable diff --git a/tests/hermes_cli/test_update_zip_fallback_guards.py b/tests/hermes_cli/test_update_zip_fallback_guards.py index e68cf66a6f..5acb6c8fe6 100644 --- a/tests/hermes_cli/test_update_zip_fallback_guards.py +++ b/tests/hermes_cli/test_update_zip_fallback_guards.py @@ -338,18 +338,6 @@ def test_preserved_filter_does_not_split_non_rename_lines(): ) -def test_swap_preserve_set_is_the_module_constant(): - """The swap loop and the dirty-tree filter must share one source of - truth for the preserved entries (no comment-synced duplicate).""" - import inspect - - from hermes_cli import update_cmd_zip - - # The swap loop lives in the download/swap collaborator the ZIP path calls. - src = inspect.getsource(update_cmd_zip._download_and_swap_zip) - assert "_ZIP_PRESERVED_TOP_LEVEL" in src - - def test_zip_overlay_allows_ignored_preserved_entries(tmp_path, monkeypatch): """venv/node_modules are gitignored on every normal install and the swap preserves them — the ignored probe must not turn them into a false diff --git a/tests/hermes_cli/test_update_zip_release_preserve.py b/tests/hermes_cli/test_update_zip_release_preserve.py deleted file mode 100644 index 61478821a7..0000000000 --- a/tests/hermes_cli/test_update_zip_release_preserve.py +++ /dev/null @@ -1,56 +0,0 @@ -"""#70337/#87331: the ZIP swap must preserve apps/desktop/release/. - -The GitHub source ZIP carries only source; the BUILT desktop app -(release/win-unpacked/Hermes.exe) exists only in the live tree. Swapping -`apps` without grafting the live release dir deletes the desktop build. -""" - -from __future__ import annotations - -import os -import shutil -from pathlib import Path - - -def test_staged_apps_swap_preserves_live_release_dir(tmp_path, monkeypatch): - from hermes_cli import main as hermes_main - from hermes_cli.update_cmd import ( - _commit_staged_replacements, - _stage_replacement, - ) - - # live tree: apps/desktop/release/win-unpacked/Hermes.exe + old source - root = tmp_path / "install" - live_apps = root / "apps" / "desktop" - (live_apps / "release" / "win-unpacked").mkdir(parents=True) - (live_apps / "release" / "win-unpacked" / "Hermes.exe").write_bytes(b"MZbuilt") - (live_apps / "electron").mkdir() - (live_apps / "electron" / "main.ts").write_text("old source") - - # extracted ZIP: new source, NO release dir (GitHub source archive shape) - extracted = tmp_path / "extracted" - zip_apps = extracted / "apps" / "desktop" - (zip_apps / "electron").mkdir(parents=True) - (zip_apps / "electron" / "main.ts").write_text("new source") - - monkeypatch.setattr(hermes_main, "PROJECT_ROOT", root) - - # Reproduce the _update_via_zip staging loop for the `apps` entry, - # including the release-dir graft. - src = str(extracted / "apps") - dst = str(root / "apps") - staged_path = _stage_replacement(src, dst) - live_release = os.path.join(dst, "desktop", "release") - staged_release = os.path.join(staged_path, "desktop", "release") - if os.path.isdir(live_release) and not os.path.exists(staged_release): - os.makedirs(os.path.dirname(staged_release), exist_ok=True) - shutil.copytree(live_release, staged_release) - - _commit_staged_replacements([(staged_path, dst)]) - - # New source landed AND the built desktop app survived. - assert (root / "apps" / "desktop" / "electron" / "main.ts").read_text() == ( - "new source" - ) - exe = root / "apps" / "desktop" / "release" / "win-unpacked" / "Hermes.exe" - assert exe.exists() and exe.read_bytes() == b"MZbuilt" diff --git a/tests/hermes_cli/test_update_zip_two_phase.py b/tests/hermes_cli/test_update_zip_two_phase.py deleted file mode 100644 index e2c40f2970..0000000000 --- a/tests/hermes_cli/test_update_zip_two_phase.py +++ /dev/null @@ -1,411 +0,0 @@ -"""Tests for the two-phase ZIP replace and the shared venv-layout helpers. - -``_atomic_replace_dir`` (#49145) made each *individual* directory swap safe, -but the ZIP update replaced ~70 top-level entries in a loop with no atomicity -across iterations. An interruption partway left some entries at the new -version and the rest at the old one -- every file valid Python, the -combination unbootable. That is the mechanism behind the ``ImportError`` in -#76091 and the field report in #63717. - -Reference: issues #76104 (ZIP atomicity) and #76105 (venv-helper duplication). -""" - -from __future__ import annotations - -import os -from pathlib import Path - -import pytest - -from hermes_cli import update_cmd -from hermes_constants import venv_bin_dir, venv_python_path -from hermes_cli import main_install_repair - - -# --------------------------------------------------------------------------- -# Two-phase replace -# --------------------------------------------------------------------------- - -def _live_tree(root: Path, names: dict[str, str]) -> None: - for name, marker in names.items(): - d = root / name - d.mkdir(parents=True, exist_ok=True) - (d / "version.txt").write_text(marker) - - -def _stage_all(root: Path, new: Path, names: list[str]) -> list[tuple[str, str]]: - return [ - ( - update_cmd._stage_replacement(str(new / n), str(root / n)), - str(root / n), - ) - for n in names - ] - - -def test_staging_touches_nothing_live(tmp_path): - """Phase 1 must not modify the install -- a failure there is a no-op.""" - live, new = tmp_path / "live", tmp_path / "new" - _live_tree(live, {"agent": "old", "tools": "old"}) - _live_tree(new, {"agent": "new", "tools": "new"}) - - _stage_all(live, new, ["agent", "tools"]) - - assert (live / "agent" / "version.txt").read_text() == "old" - assert (live / "tools" / "version.txt").read_text() == "old" - - -def test_commit_swaps_every_entry(tmp_path): - live, new = tmp_path / "live", tmp_path / "new" - _live_tree(live, {"agent": "old", "tools": "old"}) - _live_tree(new, {"agent": "new", "tools": "new"}) - - update_cmd._commit_staged_replacements(_stage_all(live, new, ["agent", "tools"])) - - assert (live / "agent" / "version.txt").read_text() == "new" - assert (live / "tools" / "version.txt").read_text() == "new" - # No staging/backup litter left behind. - assert not [p for p in os.listdir(live) if "hermes-update" in p] - - -def test_failed_swap_rolls_back_every_earlier_swap(tmp_path, monkeypatch): - """The regression: a mid-loop failure must not leave a mixed-version tree. - - Before the two-phase split this produced `agent/` new + `tools/` stale -- - the exact shape that yields - `ImportError: cannot import name 'TODO_INJECTION_HEADER'`. - """ - live, new = tmp_path / "live", tmp_path / "new" - _live_tree(live, {"agent": "old", "tools": "old"}) - _live_tree(new, {"agent": "new", "tools": "new"}) - staged = _stage_all(live, new, ["agent", "tools"]) - - real_rename = os.rename - calls = {"n": 0} - - def flaky_rename(src, dst): - calls["n"] += 1 - # Let the first entry swap fully (2 renames), then break the second. - if calls["n"] == 4: - raise OSError("simulated AV interference") - return real_rename(src, dst) - - monkeypatch.setattr(update_cmd.os, "rename", flaky_rename) - - with pytest.raises(OSError): - update_cmd._commit_staged_replacements(staged) - - monkeypatch.undo() - # Both entries must be back at the OLD version -- not one new, one old. - versions = { - n: (live / n / "version.txt").read_text() for n in ("agent", "tools") - } - assert versions == {"agent": "old", "tools": "old"}, ( - f"mixed-version tree after rollback: {versions}" - ) - - -def test_commit_handles_entries_absent_from_the_install(tmp_path): - """A brand-new top-level dir has no live counterpart to move aside.""" - live, new = tmp_path / "live", tmp_path / "new" - live.mkdir() - _live_tree(new, {"brand_new": "new"}) - - update_cmd._commit_staged_replacements(_stage_all(live, new, ["brand_new"])) - - assert (live / "brand_new" / "version.txt").read_text() == "new" - - -def test_staging_clears_leftovers_from_an_interrupted_run(tmp_path): - live, new = tmp_path / "live", tmp_path / "new" - _live_tree(live, {"agent": "old"}) - _live_tree(new, {"agent": "new"}) - stale = Path(f"{live / 'agent'}.hermes-update-staging") - stale.mkdir() - (stale / "junk.txt").write_text("from a previous crash") - - update_cmd._commit_staged_replacements(_stage_all(live, new, ["agent"])) - - assert (live / "agent" / "version.txt").read_text() == "new" - assert not (live / "agent" / "junk.txt").exists() - - -# --------------------------------------------------------------------------- -# Shared venv helpers (#76105) -# --------------------------------------------------------------------------- - -def test_venv_helpers_agree_with_each_other(): - v = Path("/opt/proj/venv") - assert venv_python_path(v).parent == venv_bin_dir(v) - - -def test_venv_helpers_accept_str_and_path(): - assert venv_python_path("/opt/x/venv") == venv_python_path(Path("/opt/x/venv")) - - -def test_venv_helpers_are_platform_consistent(): - """Whatever the platform, the two halves must not disagree.""" - v = Path("/opt/proj/venv") - bin_name = venv_bin_dir(v).name - exe_name = venv_python_path(v).name - assert (bin_name, exe_name) in {("Scripts", "python.exe"), ("bin", "python")} - - - -def test_top_level_files_are_swapped_atomically(tmp_path): - """The repo root holds 20 first-party modules (run_agent.py, cli.py, - hermes_constants.py, ...). Covering only directories would leave exactly - the bug class this PR closes.""" - live, new = tmp_path / "live", tmp_path / "new" - live.mkdir() - new.mkdir() - (live / "run_agent.py").write_text("old") - (new / "run_agent.py").write_text("new") - - staged = [ - ( - update_cmd._stage_replacement( - str(new / "run_agent.py"), str(live / "run_agent.py") - ), - str(live / "run_agent.py"), - ) - ] - update_cmd._commit_staged_replacements(staged) - - assert (live / "run_agent.py").read_text() == "new" - assert not [p for p in os.listdir(live) if "hermes-update" in p] - - -def test_file_swap_failure_restores_the_original_file(tmp_path, monkeypatch): - """A mid-swap failure must not leave a stale-or-corrupt root module.""" - live, new = tmp_path / "live", tmp_path / "new" - live.mkdir() - new.mkdir() - for name in ("cli.py", "run_agent.py"): - (live / name).write_text("old") - (new / name).write_text("new") - - staged = [ - (update_cmd._stage_replacement(str(new / n), str(live / n)), str(live / n)) - for n in ("cli.py", "run_agent.py") - ] - - real_rename = os.rename - calls = {"n": 0} - - def flaky_rename(src, dst): - calls["n"] += 1 - if calls["n"] == 4: - raise OSError("simulated AV interference") - return real_rename(src, dst) - - monkeypatch.setattr(update_cmd.os, "rename", flaky_rename) - with pytest.raises(OSError): - update_cmd._commit_staged_replacements(staged) - monkeypatch.undo() - - versions = {n: (live / n).read_text() for n in ("cli.py", "run_agent.py")} - assert versions == {"cli.py": "old", "run_agent.py": "old"}, ( - f"mixed/corrupt root modules after rollback: {versions}" - ) - - -def test_failed_staging_leaves_no_orphaned_copies(tmp_path, monkeypatch): - """#76104 review C2: orphaned staging dirs make the retry we recommend - fail harder than the original attempt (less free space each time).""" - live, new = tmp_path / "live", tmp_path / "new" - _live_tree(live, {"agent": "old", "tools": "old", "gateway": "old"}) - _live_tree(new, {"agent": "new", "tools": "new", "gateway": "new"}) - - real_copytree = update_cmd.shutil.copytree - calls = {"n": 0} - - def flaky_copytree(src, dst, *a, **kw): - calls["n"] += 1 - if calls["n"] == 3: - raise OSError(28, "No space left on device") - return real_copytree(src, dst, *a, **kw) - - monkeypatch.setattr(update_cmd.shutil, "copytree", flaky_copytree) - - staged: list[tuple[str, str]] = [] - with pytest.raises(OSError): - try: - for n in ("agent", "tools", "gateway"): - staged.append( - ( - update_cmd._stage_replacement( - str(new / n), str(live / n) - ), - str(live / n), - ) - ) - except Exception: - update_cmd._discard_staged(staged) - raise - monkeypatch.undo() - - leftovers = [p for p in os.listdir(live) if "hermes-update" in p] - assert leftovers == [], f"orphaned staging copies: {leftovers}" - # And nothing live was touched. - for n in ("agent", "tools", "gateway"): - assert (live / n / "version.txt").read_text() == "old" - - -def test_atomic_replace_dir_still_works_as_a_shim(tmp_path): - """W1: it is now an alias over the two-phase helpers; #49145 must hold.""" - live, new = tmp_path / "live", tmp_path / "new" - _live_tree(live, {"ui-tui": "old"}) - _live_tree(new, {"ui-tui": "new"}) - - update_cmd._atomic_replace_dir(str(new / "ui-tui"), str(live / "ui-tui")) - - assert (live / "ui-tui" / "version.txt").read_text() == "new" - assert not [p for p in os.listdir(live) if "hermes-update" in p] - - -def test_venv_helpers_honour_an_explicit_platform_verdict(): - """Callers must be able to override the platform check (#76107 CI). - - The suite exercises Windows paths on Linux CI by patching predicates like - `hermes_main._is_windows`. A helper that reads `sys.platform` - unconditionally silently drops those paths out of coverage -- and broke - `test_verify_core_dependencies.py::test_uses_virtual_env_from_environment`, - which patches `_is_windows` and then asserts on a `Scripts/python.exe` - path. - """ - v = Path("/opt/proj/venv") - assert venv_bin_dir(v, windows=True).name == "Scripts" - assert venv_bin_dir(v, windows=False).name == "bin" - assert venv_python_path(v, windows=True).name == "python.exe" - assert venv_python_path(v, windows=False).name == "python" - # Halves must stay consistent under an explicit verdict. - for flag in (True, False): - assert venv_python_path(v, windows=flag).parent == venv_bin_dir( - v, windows=flag - ) - - - - -# --------------------------------------------------------------------------- -# Crash between "move dst aside" and "move staging in" (Phase 2 review HIGH) -# --------------------------------------------------------------------------- - -def test_staging_restores_backup_when_dst_is_missing(tmp_path, monkeypatch): - """A previous run that died mid-swap leaves dst missing and the backup as - the ONLY copy of that entry. On retry, _stage_replacement must restore - the backup to dst BEFORE clearing leftovers — otherwise a staging failure - right after (disk exhaustion is likeliest exactly then) leaves a hole in - the install with nothing to roll back to.""" - live, new = tmp_path / "live", tmp_path / "new" - live.mkdir() - _live_tree(new, {"agent": "new"}) - # Simulate the crashed state: dst gone, backup holds the old tree. - backup = live / "agent.hermes-update-old" - backup.mkdir() - (backup / "version.txt").write_text("old") - - # Staging fails (disk full) on the fresh copy. - def boom(src, dst, *a, **kw): - raise OSError(28, "No space left on device") - - monkeypatch.setattr(update_cmd.shutil, "copytree", boom) - with pytest.raises(OSError): - update_cmd._stage_replacement(str(new / "agent"), str(live / "agent")) - monkeypatch.undo() - - # The old tree must have been restored to dst before the failure. - assert (live / "agent" / "version.txt").read_text() == "old" - assert not backup.exists() - - # And a clean retry completes the update normally. - staged = _stage_all(live, new, ["agent"]) - update_cmd._commit_staged_replacements(staged) - assert (live / "agent" / "version.txt").read_text() == "new" - assert not [p for p in os.listdir(live) if "hermes-update" in p] - - -def test_commit_failure_plus_discard_leaves_no_staging_litter(tmp_path, monkeypatch): - """Phase-2 failure must not orphan staging copies for unswapped entries. - - _update_via_zip calls _discard_staged when _commit_staged_replacements - raises. The rollback restores every swapped entry, but staging copies for - the not-yet-swapped entries (potentially most of a full tree) would - otherwise survive — and the retry's up-front free-space check runs BEFORE - the lazy per-entry leftover cleanup, so the litter makes the retry fail - harder than the original attempt. This pins the combination: rollback + - discard leaves the old tree intact and ZERO update litter.""" - live, new = tmp_path / "live", tmp_path / "new" - _live_tree(live, {"agent": "old", "tools": "old", "gateway": "old"}) - _live_tree(new, {"agent": "new", "tools": "new", "gateway": "new"}) - staged = _stage_all(live, new, ["agent", "tools", "gateway"]) - - real_rename = os.rename - calls = {"n": 0} - - def flaky_rename(src, dst): - calls["n"] += 1 - if calls["n"] == 4: # first entry fully swapped, second breaks - raise OSError("simulated AV interference") - return real_rename(src, dst) - - monkeypatch.setattr(update_cmd.os, "rename", flaky_rename) - with pytest.raises(OSError): - try: - update_cmd._commit_staged_replacements(staged) - except OSError: - # Mirrors the _update_via_zip wiring. - update_cmd._discard_staged(staged) - raise - monkeypatch.undo() - - # Old tree intact... - for n in ("agent", "tools", "gateway"): - assert (live / n / "version.txt").read_text() == "old" - # ...and zero litter of any kind (staging OR backup). - litter = [p for p in os.listdir(live) if "hermes-update" in p] - assert litter == [], f"orphaned update litter: {litter}" - - -def test_update_via_zip_wires_discard_into_the_commit_failure_path(): - """AST wiring contract: _update_via_zip must call _discard_staged from an - exception handler around _commit_staged_replacements. The behavioral test - above mirrors that wiring; this pins the production function itself so a - refactor can't silently drop the cleanup.""" - import ast - import inspect - import textwrap - - # The swap lives in the download/swap collaborator the ZIP path calls. - from hermes_cli import update_cmd_zip - - src = textwrap.dedent(inspect.getsource(update_cmd_zip._download_and_swap_zip)) - tree = ast.parse(src) - - def _calls(node, name): - return any( - isinstance(n, ast.Call) - and isinstance(n.func, ast.Name) - and n.func.id == name - for n in ast.walk(node) - ) - - wired = False - for node in ast.walk(tree): - if not isinstance(node, ast.Try): - continue - body_commits = any( - _calls(stmt, "_commit_staged_replacements") for stmt in node.body - ) - handler_discards = any( - _calls(handler, "_discard_staged") for handler in node.handlers - ) - if body_commits and handler_discards: - wired = True - break - assert wired, ( - "_update_via_zip no longer discards staging copies when " - "_commit_staged_replacements fails — commit-phase litter will make " - "the retry's free-space check fail harder than the first attempt" - ) diff --git a/tests/hermes_cli/test_venv_sync.py b/tests/hermes_cli/test_venv_sync.py index f07c71294c..b7c66e1ec9 100644 --- a/tests/hermes_cli/test_venv_sync.py +++ b/tests/hermes_cli/test_venv_sync.py @@ -23,75 +23,29 @@ REPO_ROOT = Path(__file__).resolve().parents[2] def _run_bare(snippet: str) -> subprocess.CompletedProcess: - """Run a snippet in an isolated interpreter (-I: no env, no user site) - from the repo root, so a bare import graph is what gets exercised.""" - return subprocess.run( - [sys.executable, "-I", "-c", textwrap.dedent(snippet)], - capture_output=True, - text=True, - cwd=REPO_ROOT, - timeout=120, - ) + program = f"import sys\nsys.path.insert(0, {str(REPO_ROOT)!r})\n" + textwrap.dedent(snippet) + return subprocess.run([sys.executable, '-I', '-S', '-c', program], + capture_output=True, text=True, cwd=REPO_ROOT, timeout=120) -# ── the stdlib-only contract, RUN not parsed ───────────────────────────── +def test_bare_import_and_passive_paths(tmp_path): + result = _run_bare(f""" + from pathlib import Path + from hermes_cli import venv_sync + assert 'pm' not in sys.modules + root = Path({str(tmp_path)!r}) + assert venv_sync.sync(root, check=True)['state'] == 'failed' + (root / 'install-stamp.json').write_text('{{"updateMechanism":"external"}}') + assert venv_sync.sync(root) == {{'state': 'sealed', 'ok': True}} + assert venv_sync.prepare_launch(root, []) is None + assert 'pm' not in sys.modules + """) + assert result.returncode == 0, result.stderr -class TestStdlibOnly: - def test_imports_and_answers_bare(self, tmp_path): - """The whole CLI surface must survive a stripped interpreter.""" - result = _run_bare( - f""" - import sys - sys.path.insert(0, {str(REPO_ROOT)!r}) - from hermes_cli import venv_sync - root = {str(tmp_path)!r} - out = venv_sync.sync(root, check=True) - assert out["state"] == "failed", out # empty dir: no pyproject - print("ok") - """ - ) - assert result.returncode == 0, result.stderr - - def test_no_third_party_module_ends_up_loaded(self): - """Importing it must not drag in ANY non-stdlib module. - - Check sys.modules after import, because a parser cannot see lazy - or conditional imports fire. First-party pm is allowed at SYNC - time but must not load at IMPORT time either — the bare import - happens on trees where even reading pm's ledger is premature. - - Measure the *delta*: snapshot the foreign modules already loaded - before the import and only flag what the import adds. A hardcoded - allowlist of ".pth"-injected bootstrap names is not portable — the - interpreter loads ``.pth`` hooks at startup (setuptools' - ``_distutils_hack``, pywin32's ``pywin32_bootstrap``, the - editable-install ``__editable___…_finder``, ``_virtualenv``…) before - the snippet runs, and that set varies per platform and install - shape. A before/after diff is sensitive to the import and immune to - that harness noise. - """ - result = _run_bare( - f""" - import sys - sys.path.insert(0, {str(REPO_ROOT)!r}) - stdlib = set(sys.stdlib_module_names) - - def _foreign(): - return {{ - name.split(".")[0] - for name, mod in sys.modules.items() - if mod is not None and getattr(mod, "__file__", None) - }} - stdlib - - before = _foreign() - import hermes_cli.venv_sync - dragged_in = {{n for n in _foreign() - before if n != "hermes_cli"}} - assert not dragged_in, f"venv_sync loaded non-stdlib: {{dragged_in}}" - print("ok") - """ - ) - assert result.returncode == 0, result.stderr +def test_bare_harness_rejects_third_party_import(): + result = _run_bare('import requests') + assert result.returncode != 0 and 'ModuleNotFoundError' in result.stderr def _checkout(tmp_path: Path, name: str = "co") -> Path: @@ -126,11 +80,6 @@ class TestCheckoutSync: assert venv_sync.sync(root if foreign else None) == {"state": "synced", "ok": True} assert calls == [(root, True)] - def test_current_selection_needs_no_transaction(self, tmp_path, monkeypatch): - root = _checkout(tmp_path) - calls = _wire_pm(monkeypatch, current=True) - assert venv_sync.sync(root) == {"state": "current", "ok": True} - assert calls == [] def test_check_is_passive(self, tmp_path, monkeypatch): root = _checkout(tmp_path) diff --git a/tests/hermes_cli/test_verify_console_scripts.py b/tests/hermes_cli/test_verify_console_scripts.py index 74346d3c4a..53e9968da7 100644 --- a/tests/hermes_cli/test_verify_console_scripts.py +++ b/tests/hermes_cli/test_verify_console_scripts.py @@ -7,6 +7,8 @@ import textwrap import pytest from hermes_cli import main_install_repair +pytestmark = pytest.mark.platforms("windows") + @pytest.fixture def temp_pyproject(tmp_path, monkeypatch): diff --git a/tests/hermes_cli/test_web_ui_build.py b/tests/hermes_cli/test_web_ui_build.py index 165cc5e257..460b62fe91 100644 --- a/tests/hermes_cli/test_web_ui_build.py +++ b/tests/hermes_cli/test_web_ui_build.py @@ -36,40 +36,6 @@ def _make_web_dir(tmp_path: Path) -> tuple[Path, Path]: -@pytest.mark.platforms("linux") -class TestBuildWebUIFlock: - def test_contended_lock_without_dist_waits_then_skips_fresh_build(self, tmp_path): - """First-ever build race: the waiter blocks, and once it acquires the - lock the callee's own staleness check (running under the lock) sees - the winner's output and skips a duplicate build.""" - import fcntl - import threading - from hermes_cli.main_web_build import _build_web_ui as build - - web_dir, dist_dir = _make_web_dir(tmp_path) - # No dist yet — contender must take the blocking-wait path. - lock_path = tmp_path / ".web_ui_build.lock" - holder = open(lock_path, "a") - fcntl.flock(holder.fileno(), fcntl.LOCK_EX) - - def release_after_building(): - # Simulate the winning process finishing its build. - _touch(dist_dir / "index.html") - stamp_product(tmp_path, "web", dist_dir) - holder.close() # releases the flock - - t = threading.Timer(0.2, release_after_building) - t.start() - try: - with patch("hermes_cli.source_build.source_build_env", side_effect=AssertionError("fresh build must skip preparation")) as mock_run: - result = build(web_dir) - finally: - t.join() - - assert result is True - mock_run.assert_not_called() # fresh after the wait -> no rebuild - - @pytest.mark.platforms("posix") def test_web_build_prepares_once_and_skips_a_current_product(source_products): root, acquired = source_products @@ -122,29 +88,40 @@ def test_web_rebuild_reuses_the_existing_desktop_union(source_products): @pytest.mark.platforms("linux") -def test_contended_stale_dist_waits_for_the_lock_holder(tmp_path): +@pytest.mark.parametrize('existing', [False, True]) +def test_contended_build_waits_and_rechecks_winner(tmp_path, monkeypatch, existing): import fcntl import threading web, dist = _make_web_dir(tmp_path) - dist.mkdir(parents=True) - (dist / "index.html").write_text("stale") - holder = open(tmp_path / ".web_ui_build.lock", "a") + if existing: + _touch(dist / 'index.html') + holder = open(tmp_path / '.web_ui_build.lock', 'a', encoding='utf-8') fcntl.flock(holder, fcntl.LOCK_EX) - - def finish_build(): - (dist / "index.html").write_text("winner") - stamp_product(tmp_path, "web", dist) - holder.close() - - worker = threading.Timer(2, finish_build) + real_flock = fcntl.flock + contended = threading.Event() + def flock(fd, operation): + contended.set() + return real_flock(fd, operation) + monkeypatch.setattr(fcntl, 'flock', flock) + def finish(): + try: + assert contended.wait(10), 'waiter never attempted the lock' + _touch(dist / 'index.html') + (dist / 'index.html').write_text('winner', encoding='utf-8') + stamp_product(tmp_path, 'web', dist) + finally: + holder.close() + worker = threading.Thread(target=finish) worker.start() try: - assert _build_web_ui(web, fatal=True) - at_return = (dist / "index.html").read_text() + with patch('hermes_cli.source_build.source_build_env', side_effect=AssertionError('duplicate preparation')): + assert _build_web_ui(web, fatal=True) + assert (dist / 'index.html').read_text(encoding='utf-8') == 'winner' finally: - worker.join() - assert at_return == "winner", "a contended stale index must not count as success" + worker.join(timeout=15) + holder.close() + assert not worker.is_alive() @pytest.mark.platforms("posix") diff --git a/tests/hermes_cli/test_windows_native_docs.py b/tests/hermes_cli/test_windows_native_docs.py deleted file mode 100644 index 659f586e0a..0000000000 --- a/tests/hermes_cli/test_windows_native_docs.py +++ /dev/null @@ -1,15 +0,0 @@ -from pathlib import Path - - -def test_windows_native_install_path_docs_match_installer() -> None: - doc = Path("website/docs/user-guide/windows-native.md").read_text() - - # The launchers live in the managed binary dir OUTSIDE the git checkout - # (HERMES_HOME\bin, next to the managed uv) — NOT the whole venv\Scripts - # (which would shadow the user's python, #83797) and NOT a dir inside - # the checkout (which `hermes update`'s autostash swept off disk). - assert "%LOCALAPPDATA%\\hermes\\bin" in doc - assert ( - "Get-Command hermes # should print " - "C:\\Users\\\\AppData\\Local\\hermes\\bin\\hermes.exe" - ) in doc diff --git a/tests/install/e2e-assets/bundle-inputs.mjs b/tests/install/e2e-assets/bundle-inputs.mjs index 8c867813d1..a6ad9b3d35 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.cjs new file mode 100644 index 0000000000..3906ceaa0a --- /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.mjs index 008fc3fbef..2047295914 100644 --- a/tests/install/e2e-assets/bundle-plan.mjs +++ b/tests/install/e2e-assets/bundle-plan.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node import { 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.cjs index e7343a1aa4..fb8663ce1d 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 - //