Merge branch 'ethie/pm-test-audit' into ethie/pm-clean

# Conflicts:
#	tests/scripts/test_bundle_native.py
#	tests/scripts/test_pm_runtime_bundle.py
This commit is contained in:
ethernet committed 2026-09-13 18:03:57 -04:00
commit f8bdc96033
324 files changed
+7458 -27011

No files matched your search

-95
View File
@@ -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/)
})
@@ -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<void> => {
const state = createBackendConnectionState<FakeProcess, string>()
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<void> => {
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<void> => {
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<void> => {
const state = createBackendConnectionState<FakeProcess, string>()
const child: FakeProcess = { id: 'claiming' }
const claim = deferred<void>()
const claiming = state.claimProcess(state.startAttempt(), child, (): Promise<void> => claim.promise)
assert.equal(state.getProcess(), child)
await state.stopProcess(async (current: FakeProcess): Promise<void> => {
assert.equal(current, child)
})
claim.resolve()
assert.equal(await claiming, null)
assert.equal(state.getProcess(), null)
})
+2 -30
View File
@@ -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)', () => {
@@ -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')
})
+11 -42
View File
@@ -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[] = []
+10 -19
View File
@@ -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)
})
@@ -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
+37 -63
View File
@@ -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<void> => {
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', () => {
+7 -22
View File
@@ -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<void> => {
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<void>(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<unknown> => {
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<void>((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 () => {
@@ -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>): 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')
})
})
@@ -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 / <root>\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<string, unknown> = {}) {
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<string | null>
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<typeof reapPackageRootedProcesses> = 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 <hermes root>\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<typeof reapPackageRootedProcesses>[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', () => {
+1 -24
View File
@@ -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)
})
+48 -108
View File
@@ -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<void> => {
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<void> => {
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<void> => {
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<void> => {
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<void> => {
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<void> => {
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<void> => {
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<void> => {
@@ -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<void> => {
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<void> => {
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<void> => {
const bundled: ProductIdentity = await identityForVariant('bundled')
const store: ProductIdentity = await identityForVariant('store')
@@ -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<AppInstallerStrategyDeps> = {}) {
interface StrategyFixture { deps: AppInstallerStrategyDeps; calls: string[] }
function makeDeps(over: Partial<AppInstallerStrategyDeps> = {}): StrategyFixture {
const calls: string[] = []
const deps: AppInstallerStrategyDeps = {
@@ -40,15 +42,6 @@ function makeDeps(over: Partial<AppInstallerStrategyDeps> = {}) {
}
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<void> => {
const { deps }: ReturnType<typeof makeDeps> = 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<void> => {
const { deps, calls }: ReturnType<typeof makeDeps> = makeDeps({ channel, light,
installer: {
prepare: async (url: string): Promise<string> => {
expect(url).toBe(`https://updates.example/hermes-desktop/${suffix}`)
return 'update.appinstaller'
},
open: async (file: string): Promise<string> => {
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'])
})
@@ -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<void> => {
@@ -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<void> => {
cancelled++
}
}
: undefined
let resolveReady!: (handle: RelaunchWaiterHandle | undefined) => void
const ready: Promise<RelaunchWaiterHandle | undefined> = new Promise((resolve: (handle: RelaunchWaiterHandle | undefined) => void): void => { resolveReady = resolve })
let registered: boolean = false
const pending: Promise<RelaunchRegistration> = registerUpdateRelaunch(canary, 'canary-old', {
relaunch: (): Promise<RelaunchWaiterHandle | undefined> => 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<void> => { 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<never> => {
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<never> => { 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')
})
@@ -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<RelaunchWaiterHandle | undefined>(resolve => { resolveReady = resolve })
let cancelled = 0
let registered = false
try {
const pending: Promise<RelaunchRegistration> = registerUpdateRelaunch({ getPath: (): string => home }, '1.0', { relaunch: (): Promise<RelaunchWaiterHandle | undefined> => 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 })
}
})
@@ -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<void> {
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<void> => {
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<SpawnWaiter>[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<RelaunchWaiterHandle | undefined> = 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<void> => {
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)
})
@@ -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<string> {
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)
})
})
+5 -141
View File
@@ -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<typeof buildStampPayload> = 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<string, string>) {
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<string, string> = {}
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<string, string> = {}
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<string, string> = {}
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<string, string> = {}
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<string, string> = {}
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)
})
})
+67 -98
View File
@@ -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 }) }
})
@@ -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')
})
@@ -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)
+39 -119
View File
@@ -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/)
})
@@ -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('')
})
})
@@ -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, [])
})
@@ -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, {
+33 -43
View File
@@ -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')
})
@@ -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',
@@ -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'
@@ -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<void> => {
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')
})
-54
View File
@@ -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')
})
})
@@ -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' }))
@@ -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'), [
{
@@ -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')
})
@@ -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<DesktopConnectionProbeResult>(resolve => {
resolveProbe = resolve
})
desktop.probeConnectionConfig.mockReturnValue(pendingProbe)
render(<DesktopInstallOverlay />)
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(<DesktopInstallOverlay />)
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(<DesktopInstallOverlay />)
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(<DesktopInstallOverlay />)
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<void> => {
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(<DesktopInstallOverlay />)
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() }
})
@@ -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<void> => {
const { onExternalOpenFailed, writeClipboard }: ReturnType<typeof installBridge> = installBridge()
render(<ExternalOpenFailedDialog />)
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(<ExternalOpenFailedDialog />)
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(<ExternalOpenFailedDialog />)
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(<ExternalOpenFailedDialog />)
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', () => {
@@ -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<RemoteSetupHost>(['first-run', 'settings', 'registry'])('stale probes and credential tests cannot authorize %s', async (host: RemoteSetupHost): Promise<void> => {
const probe: ReturnType<typeof deferred<DesktopConnectionProbeResult>> = deferred<DesktopConnectionProbeResult>()
const tested: ReturnType<typeof deferred<Awaited<ReturnType<Window['hermesDesktop']['testConnectionConfig']>>>> = deferred()
const bridge = {
probeConnectionConfig: vi.fn<Window['hermesDesktop']['probeConnectionConfig']>().mockReturnValue(probe.promise),
testConnectionConfig: vi.fn<Window['hermesDesktop']['testConnectionConfig']>().mockReturnValue(tested.promise)
} satisfies Pick<Window['hermesDesktop'], 'probeConnectionConfig' | 'testConnectionConfig'>
Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: bridge })
const { result }: RenderHookResult<ReturnType<typeof useRemoteSetup>, void> = renderHook((): ReturnType<typeof useRemoteSetup> => useRemoteSetup({ host }))
act((): void => { result.current.setAuthMode('oauth'); result.current.setUrl('https://a.example') })
await act(async (): Promise<void> => { await vi.advanceTimersByTimeAsync(500) })
act((): void => { result.current.setUrl('not-a-url') })
await act(async (): Promise<void> => { 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<void> => { await vi.advanceTimersByTimeAsync(500) })
expect(result.current.canTest).toBe(true)
let pending!: Promise<void>
await act(async (): Promise<void> => { 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<void> => { 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')
})
@@ -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<DesktopSyncReceipt | null>, 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(<SyncStatusCard />)
})
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<void> => {
vi.stubGlobal('hermesDesktop', {
getSyncStatus: async (): Promise<DesktopSyncReceipt | null> => receipt
} satisfies Pick<Window['hermesDesktop'], 'getSyncStatus'>)
await act(async (): Promise<void> => { render(<SyncStatusCard />) })
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(<SyncStatusCard />)
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(<SyncStatusCard />)
await act(async () => {})
expect(container.textContent).toBe('')
})
it('a rejected bridge leaves the overlay usable', async (): Promise<void> => {
vi.stubGlobal('hermesDesktop', {
getSyncStatus: async (): Promise<never> => { throw new Error('bridge gone') }
} satisfies Pick<Window['hermesDesktop'], 'getSyncStatus'>)
await act(async (): Promise<void> => { render(<SyncStatusCard />) })
expect(screen.queryByTestId('sync-status-card')).toBeNull()
})
@@ -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()
})
})
@@ -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(
<I18nProvider configClient={null} initialLocale="en">
<VersionDetails version={{ ...baseVersion, distribution: 'desktop-app', updateMechanism: 'microsoft-store' }} />
</I18nProvider>
)
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(
<I18nProvider configClient={null} initialLocale="en">
<VersionDetails version={{ ...baseVersion, distribution: 'desktop-app', updateMechanism: 'app-installer' }} />
</I18nProvider>
)
expect(screen.getByText('Desktop app (MSIX)')).toBeTruthy()
expect(screen.queryByText('Microsoft Store')).toBeNull()
})
})
@@ -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(
<I18nProvider configClient={null} initialLocale="en">
<VersionDetails version={{ ...baseVersion, source: 'ci', branch: null }} />
</I18nProvider>
)
interface VersionCase { version: Partial<DesktopVersionInfo>; 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(
<I18nProvider configClient={null} initialLocale="en">
<VersionDetails version={{ ...baseVersion, source: 'ci', branch: 'unknown' }} />
</I18nProvider>
)
it.each(cases)('renders $version', ({ version, visible, absent = [] }: VersionCase): void => {
render(<I18nProvider configClient={null} initialLocale="en"><VersionDetails version={{ ...baseVersion, ...version }} /></I18nProvider>)
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(
<I18nProvider configClient={null} initialLocale="en">
<VersionDetails version={{ ...baseVersion, source: 'nix', distribution: 'nix' }} />
</I18nProvider>
)
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(
<I18nProvider configClient={null} initialLocale="en">
<VersionDetails version={{ ...baseVersion, source: 'ci', distribution: 'docker' }} />
</I18nProvider>
)
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(
<I18nProvider configClient={null} initialLocale="en">
<VersionDetails
version={{
...baseVersion,
distribution: 'desktop-app',
hermesRuntime: { type: 'embedded' }
}}
/>
</I18nProvider>
)
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(
<I18nProvider configClient={null} initialLocale="en">
<VersionDetails
version={{
...baseVersion,
hermesRuntime: { type: 'external', source: { type: 'git', root: '/home/u/.hermes/hermes-agent' } }
}}
/>
</I18nProvider>
)
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(
<I18nProvider configClient={null} initialLocale="en">
<VersionDetails version={{ ...baseVersion, hermesRuntime: { type: 'external' } }} />
</I18nProvider>
)
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<Window['hermesDesktop']['openExternal']> = vi.fn<Window['hermesDesktop']['openExternal']>().mockResolvedValue(undefined)
vi.stubGlobal('hermesDesktop', { openExternal } satisfies Pick<Window['hermesDesktop'], 'openExternal'>)
render(
<I18nProvider configClient={null} initialLocale="en">
-152
View File
@@ -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<string, string>`
* 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<string, unknown>
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<LeafKey> {
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')}`)
}
})
})
@@ -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<object> => ({
...(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<unknown> => {
if (request.path.endsWith('/status')) {
@@ -86,13 +92,21 @@ const api = vi.fn(async (request: HermesApiRequest): Promise<unknown> => {
}
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<void> => {
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)
})
@@ -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<readonly LocalRuntimeJob[]>(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<readonly LocalRuntimeJob[]>(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<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])[0]
?.status
).toBe('running')
})
it('publishes a pinned job response into an injected QueryClient observer', async (): Promise<void> => {
const client: QueryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const owner: LocalModelsOwner = { connectionId: 'A', profile: 'work' }
+84 -19
View File
@@ -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([])
})
@@ -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.'
)
})
+15 -102
View File
@@ -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)
+51 -208
View File
@@ -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()
})
+39 -98
View File
@@ -1,114 +1,55 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
// semver ships no declarations in this lock; type the two library calls used here.
const semver: { valid(version: string): string | null; satisfies(version: string, range: string): boolean } = require('semver')
import { test } from 'vitest'
import { describe, test } from 'vitest'
const REPO_ROOT = path.resolve(__dirname, '..')
interface Manifest {
engines?: { node?: string }
}
interface Lockfile {
packages?: Record<string, Manifest>
}
interface Engines { node?: string; npm?: string }
interface Manifest { engines?: Engines }
interface Lockfile { packages: Record<string, Manifest> }
interface PmLock { packages: { node: { version: string }; npm: { version: string } } }
function readJson<T>(relativePath: string): T {
return JSON.parse(fs.readFileSync(path.join(REPO_ROOT, relativePath), 'utf-8')) as T
// SAFETY: these are repository-owned manifest/lock inputs, checked below.
return JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', relativePath), 'utf8')) as T
}
const root = readJson<Manifest>('package.json')
const desktop = readJson<Manifest>('apps/desktop/package.json')
const lock = readJson<Lockfile>('package-lock.json')
const pins = readJson<PmLock>('pm/lock.json').packages
function parseVersion(version: string): [number, number, number] {
const [major = 0, minor = 0, patch = 0] = version.split('-', 1)[0].split('.').map(Number)
return [major, minor, patch]
}
function compare(left: string, right: string): number {
const have = parseVersion(left)
const want = parseVersion(right)
for (let index = 0; index < have.length; index += 1) {
if (have[index] !== want[index]) {
return have[index] - want[index]
}
}
return 0
}
function satisfiesClause(version: string, clause: string): boolean {
assert.match(clause, /^(?:\^|>=|<=|>|<|=)?\d+(?:\.\d+){0,2}$/, `unsupported semver clause: ${clause}`)
if (clause.startsWith('^')) {
const bound = clause.slice(1)
return parseVersion(version)[0] === parseVersion(bound)[0] && compare(version, bound) >= 0
}
const match = clause.match(/^(>=|<=|>|<|=)?(.+)$/)
assert.ok(match)
const [, operator = '=', bound] = match
const result = compare(version, bound)
return operator === '>='
? result >= 0
: operator === '<='
? result <= 0
: operator === '>'
? result > 0
: operator === '<'
? result < 0
: result === 0
}
function satisfiesRange(version: string, range: string): boolean {
const alternatives = range.split('||').map(alternative => alternative.trim().split(/\s+/))
alternatives.flat().forEach(clause => satisfiesClause(version, clause))
return alternatives.some(clauses => clauses.every(clause => satisfiesClause(version, clause)))
}
const rootManifest = readJson<Manifest>('package.json')
const desktopManifest = readJson<Manifest>('apps/desktop/package.json')
const lockfile = readJson<Lockfile>('package-lock.json')
function nodeRange(manifest: Manifest, label: string): string {
assert.ok(manifest.engines?.node, `${label} must declare engines.node`)
function nodeRange(manifest: Manifest): string {
assert.ok(manifest.engines?.node, 'workspace must declare engines.node')
return manifest.engines.node
}
describe('Node engine alignment', () => {
const rootRange = nodeRange(rootManifest, 'root package.json')
const desktopRange = nodeRange(desktopManifest, 'apps/desktop/package.json')
test.each([
['22.22.0', 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)
})
+21 -1
View File
@@ -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',
+1 -39
View File
@@ -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):
+5 -77
View File
@@ -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)],
+21
View File
@@ -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
+53 -273
View File
@@ -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"]
+10 -101
View File
@@ -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
# =========================================================================
+23 -8
View File
@@ -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"
-19
View File
@@ -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
+19 -70
View File
@@ -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:
+8 -9
View File
@@ -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):
+25 -21
View File
@@ -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:
+24 -98
View File
@@ -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
+18 -3
View File
@@ -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()
@@ -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 = {
+26 -158
View File
@@ -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
+51 -176
View File
@@ -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": ["<no-needs>"], "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
-25
View File
@@ -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()
+42
View File
@@ -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
+7 -72
View File
@@ -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))
@@ -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"
+17 -41
View File
@@ -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")
+1 -1
View File
@@ -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):
+9 -87
View File
@@ -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
+52 -166
View File
@@ -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):
+65 -179
View File
@@ -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
+13
View File
@@ -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)
+21
View File
@@ -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
-32
View File
@@ -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)"
)
# ---------------------------------------------------------------------------
+6 -37
View File
@@ -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)
+24 -53
View File
@@ -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)
+23 -104
View File
@@ -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]
+2 -94
View File
@@ -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)
+19
View File
@@ -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
-159
View File
@@ -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()
@@ -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."""
@@ -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]
-689
View File
@@ -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 <name>`` 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 <target>`` returns non-zero
(simulates branch absent locally; code should retry with -B)
- ``track_fails`` if True, ``git checkout -B <target> origin/<target>`` 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 <name>`` honors the branch override.
The check path used to call ``git rev-list HEAD..origin/<branch> --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/<branch>`` 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/<branch> 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=<non-main>`` 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).
+2 -1
View File
@@ -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")
-65
View File
@@ -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)
@@ -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 -------------------------------------------------
+13 -112
View File
@@ -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
# --------------------------------------------------------------------------
+24 -166
View File
@@ -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)
@@ -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:
+21 -142
View File
@@ -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
+7 -18
View File
@@ -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):
+5 -42
View File
@@ -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
):
@@ -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"]]
@@ -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)
process.communicate(timeout=10)
+38 -73
View File
@@ -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
+10 -91
View File
@@ -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
assert (plugins / ".install-metadata.json").read_text(encoding="utf-8") == before
+9 -54
View File
@@ -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 ──────────────────────────────────────────
Loaded 100 of 324 files, more files were not shown because too many files have changed in this diff. Show more