The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: consolidate desktop contracts around real consumers
ethernet41be32c3c07c
diff --git a/apps/desktop/electron/app-updater.test.ts b/apps/desktop/electron/app-updater.test.tsdeleted file mode 100644index 9ae9e70475f..00000000000--- a/apps/desktop/electron/app-updater.test.ts+++ /dev/null@@ -1,95 +0,0 @@-import assert from 'node:assert/strict'--import { test } from 'vitest'--import {- checkAppInstallerUpdate,- triggerAppInstallerUpdate,- win32AppInstallerFeedPath-} from './app-updater'--// ── feed hosting + paths ────────────────────────────────────────────--test('win32 App Installer feed paths are per-channel and per-variant', () => {- assert.equal(win32AppInstallerFeedPath('stable', false), 'win32/stable/')- assert.equal(win32AppInstallerFeedPath('canary', false), 'win32/canary/')- assert.equal(win32AppInstallerFeedPath('stable', true), 'win32/light/stable/')- assert.equal(win32AppInstallerFeedPath('canary', true), 'win32/light/canary/')-})--// ── win32 arm (OS App Installer checker + trigger) ─────────────────--function fakePayloadRunner(stdout: string, code = 0) {- const calls: string[] = []-- return {- runner: {- python: 'C:\\payload\\tools\\cpython\\python.exe',- script: 'C:\\payload\\scripts\\check-appinstaller-update.py',- run: async (python: string, script: string) => {- calls.push(`${python} ${script}`)-- return { code, stdout }- }- } as any,- calls- }-}--test('win32 check reports available when the OS says a newer package exists', async () => {- const { runner } = fakePayloadRunner(JSON.stringify({ available: true, availability: 'Available' }))- const result = await checkAppInstallerUpdate(runner)-- assert.equal(result.available, true)- assert.equal(result.availability, 'Available')-})--test('win32 check reports not-available cleanly', async () => {- const { runner } = fakePayloadRunner(JSON.stringify({ available: false, availability: 'NoApplicableUpdate' }))- const result = await checkAppInstallerUpdate(runner)-- assert.equal(result.available, false)-})--test('win32 check surfaces an unknown verdict (missing winrt) without crashing', async () => {- const { runner } = fakePayloadRunner(JSON.stringify({ available: null, error: 'winrt import failed' }), 1)- const result = await checkAppInstallerUpdate(runner)-- assert.equal(result.available, null)- assert.match(result.error || '', /winrt import failed/)-})--test('win32 trigger prepares a local descriptor before teardown and file activation', async () => {- const calls: string[] = []-- const installer = {- prepare: async (url: string) => { calls.push(`download:${url}`);-- return 'update.appinstaller' },- open: async (file: string) => { calls.push(`open:${file}`);-- return '' }- }-- const result = await triggerAppInstallerUpdate(- 'https://updates.example.com/', 'stable', false, installer,- () => void calls.push('teardown')- )-- assert.equal(result.ok, true)- assert.deepEqual(calls, [- 'download:https://updates.example.com/win32/stable/stable.appinstaller',- 'teardown', 'open:update.appinstaller'- ])-})--test('win32 trigger refuses failed downloads before teardown and surfaces file-open errors', async () => {- const teardown = () => { throw new Error('unexpected teardown') }- await assert.rejects(triggerAppInstallerUpdate('https://updates.example.com', 'canary', true, {- prepare: async url => { assert.match(url, /win32\/light\/canary\/canary.appinstaller$/); throw new Error('download failed') },- open: async () => ''- }, teardown), /download failed/)- await assert.rejects(triggerAppInstallerUpdate('https://updates.example.com', 'stable', false, {- prepare: async () => 'update.appinstaller', open: async () => 'No file association'- }), /No file association/)-})diff --git a/apps/desktop/electron/backend-connection-state.test.ts b/apps/desktop/electron/backend-connection-state.test.tsindex c4cf43c0ceb..5bd6c72afcd 100644--- a/apps/desktop/electron/backend-connection-state.test.ts+++ b/apps/desktop/electron/backend-connection-state.test.ts@@ -134,6 +134,7 @@ test('a failed primary stop retains its child and blocks a replacement until retconst 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 descriptoassert.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)-})diff --git a/apps/desktop/electron/backend-probes.test.ts b/apps/desktop/electron/backend-probes.test.tsindex 6703baf4385..00f0ab4b760 100644--- a/apps/desktop/electron/backend-probes.test.ts+++ b/apps/desktop/electron/backend-probes.test.ts@@ -6,7 +6,6 @@*/import assert from 'node:assert/strict'-import fs from 'node:fs'import os from 'node:os'import path from 'node:path'@@ -68,35 +67,8 @@ test('verifyHermesCli returns false when binary does not exist', () => {assert.equal(verifyHermesCli(ghost), false)})-test('verifyHermesCli returns true when --version exits 0', () => {- // Write a tiny script that exits 0 regardless of args, then invoke- // it through node. This stands in for a working hermes binary --- // verifyHermesCli only cares about the exit code.- const scriptPath = path.join(os.tmpdir(), `hermes-probes-ok-${Date.now()}-${process.pid}.cjs`)- fs.writeFileSync(scriptPath, 'process.exit(0)\n')-- try {- // Use node as the launcher and our script as the "command". Pass- // shell:false (default) -- node is a real binary, no shim.- // execFileSync passes ['--version'] as args, which node ignores- // gracefully (well, it prints its version and exits 0, which is- // perfect -- exit code 0 is the only signal we read).- assert.equal(verifyHermesCli(NODE_BIN), true)- } finally {- try {- fs.unlinkSync(scriptPath)- } catch {- void 0- }- }-})--test('verifyHermesCli swallows timeouts (does not throw)', () => {- // We can't easily provoke a real hang in CI without slowing the- // suite, but we CAN confirm that an invocation that DOES throw- // (because the binary is missing) returns false rather than- // propagating. Same code path the timeout case takes.- assert.equal(verifyHermesCli('/definitely/not/a/real/binary/anywhere'), false)+test('verifyHermesCli accepts an actual zero-exit executable', (): void => {+ assert.equal(verifyHermesCli(NODE_BIN), true)})test('default probe timeout is 15s (not the old 5s death-loop value)', () => {diff --git a/apps/desktop/electron/bootstrap-state.test.ts b/apps/desktop/electron/bootstrap-state.test.tsindex 67ea76b8f9e..08b74841758 100644--- a/apps/desktop/electron/bootstrap-state.test.ts+++ b/apps/desktop/electron/bootstrap-state.test.ts@@ -18,5 +18,6 @@ test.each(['bundled', 'bootstrap', 'light'] as const)('bootstrap state retains texpect(bootstrapSnapshot(state, artifact)).toEqual({ ...state, bundled: payload === 'bundled' })expect(bootstrapSnapshot({ error: null, setupChoice: null }, artifact).bundled).toBe(payload === 'bundled')expect(state).not.toHaveProperty('bundled')+ expect(bootstrapSnapshot(state, null).bundled).toBe(false)expect(bootstrapSnapshot({ ...state, bundled: payload !== 'bundled' }, artifact).bundled).toBe(payload === 'bundled')})diff --git a/apps/desktop/electron/connection-apply.test.ts b/apps/desktop/electron/connection-apply.test.tsindex 2fe3a57ce6e..329ae2b47ae 100644--- a/apps/desktop/electron/connection-apply.test.ts+++ b/apps/desktop/electron/connection-apply.test.ts@@ -19,8 +19,8 @@ function deferred() {}describe('applyConnectionChange', () => {- it.each([['SSH A to SSH B'], ['SSH to Cloud'], ['Cloud to SSH']])(- 'serializes %s behind bootstrap rollback before teardown and apply',+ it(+ 'serializes connection changes behind bootstrap rollback before teardown and apply',async () => {const gate = deferred()const events: string[] = []@@ -92,48 +92,17 @@ describe('resolveTerminalConnection', () => {})})-describe('sshQuitShouldBlock', () => {- it('waits when connections exist and teardown has not finished', () => {- expect(sshQuitShouldBlock({ teardownDone: false, connectionCount: 1, bootstrapPending: 0, inFlight: null })).toBe(- true- )- })-- it('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.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('does not block a second quit after teardown finished', () => {- expect(- sshQuitShouldBlock({- teardownDone: true,- connectionCount: 1,- bootstrapPending: 1,- inFlight: Promise.resolve()- })- ).toBe(false)- })-- it('does not block quit when there is nothing to tear down', () => {- expect(sshQuitShouldBlock({ teardownDone: false, connectionCount: 0, bootstrapPending: 0, inFlight: null })).toBe(- false- )- })-})-describe('teardownSshState', () => {it('terminates the owned remote backend before closing its tunnel and SSH transport', async () => {const events: string[] = []diff --git a/apps/desktop/electron/deep-link-route.test.ts b/apps/desktop/electron/deep-link-route.test.tsindex 31f5a93525b..8c1c5135577 100644--- a/apps/desktop/electron/deep-link-route.test.ts+++ b/apps/desktop/electron/deep-link-route.test.ts@@ -1,23 +1,14 @@-import { describe, expect, it } from 'vitest'+import { expect, it } from 'vitest'import { routeDeepLink } from './deep-link-route'-describe('routeDeepLink', () => {- it('summons quick entry for the Copilot key press', () => {- expect(routeDeepLink('copilot-key', 'start')).toBe('quick-entry')- })-- it('ignores the Copilot key release so a tap does not undo the summon', () => {- expect(routeDeepLink('copilot-key', 'stop')).toBe('ignore')- })-- it('ignores unknown copilot-key paths instead of leaking them to the renderer', () => {- expect(routeDeepLink('copilot-key', '')).toBe('ignore')- expect(routeDeepLink('copilot-key', 'toggle')).toBe('ignore')- })-- it('routes every other deep link to the renderer', () => {- expect(routeDeepLink('blueprint', 'morning-brief')).toBe('renderer')- expect(routeDeepLink('', '')).toBe('renderer')- })+it.each([+ ['copilot-key', 'start', 'quick-entry'],+ ['copilot-key', 'stop', 'ignore'],+ ['copilot-key', '', 'ignore'],+ ['copilot-key', 'toggle', 'ignore'],+ ['blueprint', 'morning-brief', 'renderer'],+ ['', '', 'renderer']+] as const)('%s/%s → %s', (host: string, pathname: string, expected: string): void => {+ expect(routeDeepLink(host, pathname)).toBe(expected)})diff --git a/apps/desktop/electron/desktop-electron-pin.test.ts b/apps/desktop/electron/desktop-electron-pin.test.tsindex 8a27b26d6d6..33e983bf747 100644--- a/apps/desktop/electron/desktop-electron-pin.test.ts+++ b/apps/desktop/electron/desktop-electron-pin.test.ts@@ -19,14 +19,12 @@** 1. the Electron dependency is an *exact* version (Electron Builder needs the* installed binary to match ``electronVersion`` / ``electronDist``), and- * 2. the dependency, electron-builder.config.cjs ``electronVersion``, and the- * resolved lockfile entry all agree — so ``npm ci`` installs exactly what+ * 2. the dependency and the independently resolved lockfile entry agree — so ``npm ci`` installs exactly what* the build packages.*/import assert from 'node:assert/strict'import fs from 'node:fs'-import { createRequire } from 'node:module'import path from 'node:path'import { test } from 'vitest'@@ -69,21 +67,6 @@ test('electron dependency is exactly pinned', () => {)})-test('electron dependency matches electron-builder.config.cjs', () => {- const spec = electronSpec(desktopPkg())- const require = createRequire(import.meta.url)- const config = require('../electron-builder.config.cjs') as { electronVersion?: string }- const builderVersion = config.electronVersion- assert.ok(builderVersion, 'electron-builder.config.cjs electronVersion is missing')- assert.equal(- spec,- builderVersion,- `electron dependency ("${spec}") must equal electron-builder.config.cjs ` +- `electronVersion ("${builderVersion}"); otherwise electron-builder packages ` +- 'a different version than npm installs.'- )-})-test('lockfile resolves the pinned electron', () => {if (!fs.existsSync(ROOT_LOCK)) {returndiff --git a/apps/desktop/electron/desktop-uninstall.test.ts b/apps/desktop/electron/desktop-uninstall.test.tsindex a7a6186c941..6ef1d3127f4 100644--- a/apps/desktop/electron/desktop-uninstall.test.ts+++ b/apps/desktop/electron/desktop-uninstall.test.ts@@ -10,6 +10,11 @@*/import assert from 'node:assert/strict'+import { type ChildProcess, spawn } from 'node:child_process'+import { once } from 'node:events'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'import { test } from 'vitest'@@ -159,7 +164,38 @@ test('shouldRemoveAppBundle requires packaged AND a resolved path', () => {assert.equal(shouldRemoveAppBundle(false, null), false)})-// --- buildPosixCleanupScript ---+test.skipIf(process.platform === 'win32').each(['gui', 'lite', 'full'] as const)('POSIX cleanup executes %s in its sandbox and preserves its sibling', async (mode: string): Promise<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, remoassert.match(script, /export HERMES_HOME='\/home\/x\/\.hermes'/)})-test('buildPosixCleanupScript exports PYTHONPATH when pythonPath is set (lite/full)', () => {- const script = buildPosixCleanupScript({- desktopPid: 1,- pythonExe: '/usr/bin/python3',- pythonPath: '/home/x/.hermes/hermes-agent',- agentRoot: '/home/x/.hermes/hermes-agent',- uninstallArgs: ['-m', 'hermes_cli.uninstall', '--mode', 'full'],- appPath: null,- hermesHome: '/home/x/.hermes'- })-- // System python + source on PYTHONPATH so import hermes_cli works while the- // venv is torn down.- assert.match(script, /export PYTHONPATH='\/home\/x\/\.hermes\/hermes-agent'/)- assert.match(script, /'\/usr\/bin\/python3' '-m' 'hermes_cli\.uninstall' '--mode' 'full'/)-})--test('buildPosixCleanupScript omits PYTHONPATH when pythonPath is null (gui)', () => {- const script = buildPosixCleanupScript({- desktopPid: 1,- pythonExe: '/p/python',- pythonPath: null,- agentRoot: '/a',- uninstallArgs: ['-m', 'hermes_cli.uninstall', '--mode', 'gui'],- appPath: null,- hermesHome: '/h'- })-- assert.doesNotMatch(script, /export PYTHONPATH/)-})--test('buildPosixCleanupScript omits the bundle rm when appPath is null', () => {- const script = buildPosixCleanupScript({- desktopPid: 1,- pythonExe: '/p/python',- pythonPath: null,- agentRoot: '/a',- uninstallArgs: ['-m', 'hermes_cli.uninstall', '--mode', 'lite'],- appPath: null,- hermesHome: '/h'- })-- assert.doesNotMatch(script, /rm -rf '\//)- // Still runs the uninstall.- assert.match(script, /'-m' 'hermes_cli\.uninstall' '--mode' 'lite'/)-})--test('buildPosixCleanupScript single-quote-escapes paths with apostrophes', () => {- const script = buildPosixCleanupScript({- desktopPid: 1,- pythonExe: "/home/o'brien/python",- pythonPath: null,- agentRoot: '/a',- uninstallArgs: ['-m', 'hermes_cli.uninstall', '--mode', 'gui'],- appPath: null,- hermesHome: '/h'- })-- // The apostrophe is closed-escaped-reopened so the shell sees the literal.- assert.match(script, /'\/home\/o'\\''brien\/python'/)-})-// --- buildWindowsCleanupScript ---test('buildWindowsCleanupScript waits (bounded) for PID, runs uninstall, rmdir bundle', () => {diff --git a/apps/desktop/electron/gateway-version.test.ts b/apps/desktop/electron/gateway-version.test.tsindex b9860bb91dd..aa4619d2c60 100644--- a/apps/desktop/electron/gateway-version.test.ts+++ b/apps/desktop/electron/gateway-version.test.ts@@ -1,36 +1,21 @@import assert from 'node:assert/strict'-import { createServer } from 'node:http'import { test } from 'vitest'import { resolveGatewayVersion } from './gateway-version'-test('version follows the gateway response across runtime changes', async () => {- let version = '1.2.3'+test('version follows each supplied gateway response without caching', async (): Promise<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 () => {diff --git a/apps/desktop/electron/install-stamp.test.ts b/apps/desktop/electron/install-stamp.test.tsdeleted file mode 100644index 6cdc282a76a..00000000000--- a/apps/desktop/electron/install-stamp.test.ts+++ /dev/null@@ -1,51 +0,0 @@-// installShape() — the ONE split every desktop lifecycle decision gates on.-//-// The stamp is a constant of the artifact; the shape is derived from it-// and never from filesystem probes. These tests pin the derivation table-// and the probe-independence (a stamp object is enough — no fs access).--import { describe, expect, test } from 'vitest'--import { installShape, type InstallStamp } from './install-stamp'--function stamp(overrides: Partial<InstallStamp>): InstallStamp {- return {- schemaVersion: 2,- commit: 'a'.repeat(40),- commitDate: 1755000000,- branch: 'main',- builtAt: '2026-08-14T00:00:00Z',- dirty: false,- source: 'ci',- distribution: 'desktop-app',- updateMechanism: 'electron-updater',- baseVersion: '0.21.0',- displayVersion: '0.21.0',- distance: 0,- payload: 'bootstrap',- tag: null,- ...overrides- }-}--describe('installShape', () => {- test('a bundled stamp is the bundled shape', () => {- expect(installShape(stamp({ payload: 'bundled', tag: 'v0.21.0' }))).toBe('bundled')- })-- test('a bootstrap stamp is a checkout — its runtime is a local install', () => {- expect(installShape(stamp({ payload: 'bootstrap' }))).toBe('checkout')- })-- test('a light stamp is not bundled (no runtime to run at all)', () => {- // Light artifacts never resolve a local backend; what matters here is- // that they can never be told to run venv machinery as "bundled".- expect(installShape(stamp({ payload: 'light' }))).toBe('checkout')- })-- test('a dev run (null stamp) is a checkout', () => {- expect(installShape(null)).toBe('checkout')- })---})diff --git a/apps/desktop/electron/package-process-reap.test.ts b/apps/desktop/electron/package-process-reap.test.tsindex b9b90198726..d20b1f38f1c 100644--- a/apps/desktop/electron/package-process-reap.test.ts+++ b/apps/desktop/electron/package-process-reap.test.ts@@ -3,57 +3,23 @@ import { describe, expect, it, vi } from 'vitest'import {isUnderInstallRoot,listWindowsProcesses,- protectedRuntimePids,reapPackageRootedProcesses,type RunningProcess} from './package-process-reap'const ROOT = 'C:\\Program Files\\WindowsApps\\NousResearch.HermesBundled_0.21.20.25635_arm64__e60prshbsznhj'-/** A mutable install's managed tool store: HERMES_RUNTIME_DIR / <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)])-- expect(outcome.matched).toBe(1)- expect(outcome.killed).toEqual([48236])- expect(killProcess).toHaveBeenCalledWith(48236)- })-- 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()- })+interface SelectionCase {+ name: string+ processes: RunningProcess[]+ roots?: Array<string | null>+ selfPid?: number+ excludePids?: number[]+ killed: number[]+}- 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] }- )+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) }+ })++ expect(outcome.killed).toEqual(killed)+ expect(outcome.matched).toBe(killed.length)+ expect(signalled).toEqual(killed)+})- expect(outcome.killed).toEqual([])- })+it('continues after kill failure and refuses absent roots or failed enumeration', (): void => {+ const processes: RunningProcess[] = [proc(50, GPG_AGENT), proc(51, GPG_AGENT)]- 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)])+ 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(outcome.matched).toBe(0)- expect(killProcess).not.toHaveBeenCalled()- })+ expect(reapPackageRootedProcesses(base)).toMatchObject({ failed: [50], killed: [51] })- 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)+ 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('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)- ]-- expect(protectedRuntimePids(running)).toEqual(new Set([10, 11, 12]))- expect(protectedRuntimePids([proc(14, GPG_AGENT, 'gpg-agent --daemon')])).toEqual(new Set())- })+ }})describe('listWindowsProcesses', () => {diff --git a/apps/desktop/electron/pool-stop.test.ts b/apps/desktop/electron/pool-stop.test.tsindex c6cc06c63c0..abad62d5561 100644--- a/apps/desktop/electron/pool-stop.test.ts+++ b/apps/desktop/electron/pool-stop.test.ts@@ -116,6 +116,7 @@ test('stopAll waits for current and already-stopping backends', async () => {})assert.equal(pool.size, 0)+ assert.equal(stopper.hasPending(), true)assert.equal(a.killed, true)assert.equal(b.killed, true)@@ -127,30 +128,6 @@ test('stopAll waits for current and already-stopping backends', async () => {exitResolvers.get(a)?.()await Promise.all([all, priorStop])assert.equal(settled, true)-})--test('stopAll joins a stop whose pool entry was already evicted', async () => {- const { addChild, exitResolvers, pool, stopper } = harness()- const child = addChild('already-stopping')-- const first = stopper.stop('already-stopping')-- assert.equal(pool.size, 0)- assert.equal(stopper.hasPending(), true)-- let settled = false-- const all = stopper.stopAll().then(() => {- settled = true- })-- await Promise.resolve()-- assert.equal(settled, false)-- exitResolvers.get(child)?.()- await Promise.all([first, all])- assert.equal(settled, true)assert.equal(stopper.hasPending(), false)})diff --git a/apps/desktop/electron/product-identity.test.ts b/apps/desktop/electron/product-identity.test.tsindex 1876ea3bdc7..b287ebaadae 100644--- a/apps/desktop/electron/product-identity.test.ts+++ b/apps/desktop/electron/product-identity.test.ts@@ -117,104 +117,63 @@ test('nonstable runtime pins userData before the app name can change', async ():}})-test('light identity is fully distinct from the full identity', async (): Promise<void> => {- const full: ProductIdentity = await identityForVariant(undefined)- const light: ProductIdentity = await identityForVariant('light')-- assert.equal(light.light, true)-- // 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`)- }-})--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')-- 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`)+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]++ 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))++ if (commit) { assert.equal(current.displayName, `${display} ${commit.slice(0, 7)}`) }++ 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`)++ 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)- }+ process.env.HERMES_BUILD_COMMIT = 'not-a-sha'+ process.env.HERMES_PAYLOAD_TAG = 'v1.2.3'+ assert.deepEqual(await identityForVariant(variant), stable)})-test('a commit build names the SHA in the display name', async (): Promise<void> => {- process.env.HERMES_BUILD_COMMIT = 'abcdef1234567890abcdef1234567890abcdef12'+test('light and bundled retain distinct OS markers from the full client', async (): Promise<void> => {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')+ for (const variant of ['bundled', 'light']) {+ const other: ProductIdentity = await identityForVariant(variant)- delete process.env.HERMES_BUILD_COMMIT- const plain: ProductIdentity = await identityForVariant(undefined)- assert.equal(plain.displayName, 'Hermes')+ for (const field of ['displayName', 'appId', 'appNamePascal'] as const) { assert.notEqual(other[field], full[field]) }- // 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')+ 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')diff --git a/apps/desktop/electron/updater/app-installer-strategy.test.ts b/apps/desktop/electron/updater/app-installer-strategy.test.tsindex aa9ccfe3737..0a887c66e36 100644--- a/apps/desktop/electron/updater/app-installer-strategy.test.ts+++ b/apps/desktop/electron/updater/app-installer-strategy.test.ts@@ -7,7 +7,9 @@ import { describe, expect, it } from 'vitest'import { AppInstallerStrategy } from './app-installer'import type { AppInstallerStrategyDeps } from './app-installer'-function makeDeps(over: Partial<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 }+ }+ })++ 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}`)- 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')+ 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'])})diff --git a/apps/desktop/electron/updater/relaunch-isolation.test.ts b/apps/desktop/electron/updater/relaunch-isolation.test.tsindex 80bc8041f85..faf4765d23c 100644--- a/apps/desktop/electron/updater/relaunch-isolation.test.ts+++ b/apps/desktop/electron/updater/relaunch-isolation.test.ts@@ -87,6 +87,9 @@ test('writes and startup consumption stay in each installation despite a sharedassert.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 malet cancelled: number = 0for (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 maassert.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 maassert.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')})diff --git a/apps/desktop/electron/updater/relaunch-registration.test.ts b/apps/desktop/electron/updater/relaunch-registration.test.tsdeleted file mode 100644index da2aa112c88..00000000000--- a/apps/desktop/electron/updater/relaunch-registration.test.ts+++ /dev/null@@ -1,83 +0,0 @@-import assert from 'node:assert/strict'-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'--import { test } from 'vitest'--import { PENDING_RELAUNCH_FILENAME, registerUpdateRelaunch, type RelaunchRegistration } from './relaunch'-import type { RelaunchWaiterHandle } from './relaunch-waiter'--for (const automatic of [true, false]) {- test(`registration owns its marker and cancellation (automatic=${automatic})`, async () => {- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'relaunch-registration-'))- const marker = path.join(home, PENDING_RELAUNCH_FILENAME)- let resolveReady!: (handle: RelaunchWaiterHandle | undefined) => void- const ready = new Promise<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 })- }-})diff --git a/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts b/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.tsindex a7b75f2f34d..9bca5a65dd4 100644--- a/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts+++ b/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts@@ -6,9 +6,9 @@ import path from 'node:path'import { test, vi } from 'vitest'-import { type SpawnWaiter, startRelaunchWaiter } from './relaunch-waiter'+import { type RelaunchWaiterHandle, type SpawnWaiter, startRelaunchWaiter } from './relaunch-waiter'-const scriptPath = path.resolve(import.meta.dirname, '../../scripts/update-relaunch-waiter.ps1')+const scriptPath: string = path.resolve(import.meta.dirname, '../../scripts/update-relaunch-waiter.ps1')async function stop(child: ChildProcess | undefined): Promise<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 | undefinedlet 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)+})diff --git a/apps/desktop/electron/updater/relaunch-waiter.test.ts b/apps/desktop/electron/updater/relaunch-waiter.test.tsdeleted file mode 100644index 3913bb326d0..00000000000--- a/apps/desktop/electron/updater/relaunch-waiter.test.ts+++ /dev/null@@ -1,199 +0,0 @@-// updater/relaunch-waiter.test.ts — staging, argv, and the ready/error-// handshake contract. No PowerShell is spawned: the spawn point is injected-// and the handshake file is written by the test (as the real script would),-// so the parent-side race contract is exercised without touching a package.--import { EventEmitter } from 'node:events'-import * as fs from 'node:fs'-import * as os from 'node:os'-import * as path from 'node:path'--import { afterEach, describe, expect, it } from 'vitest'--import {- buildRelaunchWaiterArgs,- POWERSHELL_PATH,- RELAUNCH_WAITER_READY_FILENAME,- RELAUNCH_WAITER_SCRIPT,- type SpawnWaiter,- startRelaunchWaiter-} from './relaunch-waiter'--const OPTIONS = {- processId: 4242,- processStartTimeMs: 1_000_000,- identityName: 'NousResearch.HermesBundled',- scriptPath: '/payload/apps/desktop/scripts/update-relaunch-waiter.ps1'-}--const tempDirs: string[] = []--afterEach(() => {- for (const dir of tempDirs.splice(0)) {- fs.rmSync(dir, { recursive: true, force: true })- }-})--function fakeSpawn(handshake: 'ready' | 'error' | 'exit-nonzero' | 'none'): { spawn: SpawnWaiter; seen: any } {- const seen: any = {}-- const spawn: SpawnWaiter = (_command, args, opts) => {- seen.command = _command- seen.args = args- seen.opts = opts- tempDirs.push(opts.cwd)-- const child: any = new EventEmitter()-- child.pid = handshake === 'error' ? undefined : 123-- child.unref = () => {}-- child.kill = () => {- seen.killed = true- child.emit('exit', null)- child.emit('close', null)- }-- const readyFile = args[args.indexOf('-ReadyFile') + 1]-- queueMicrotask(() => {- if (handshake === 'ready') {- fs.mkdirSync(path.dirname(readyFile), { recursive: true })- fs.writeFileSync(readyFile, '0.18.1|Family|App')- } else if (handshake === 'error') {- child.emit('error', new Error('spawn ENOENT'))- child.emit('close', -1)- } else if (handshake === 'exit-nonzero') {- child.emit('exit', 3)- child.emit('close', 3)- }- })-- return child- }-- return { spawn, seen }-}--async function stageScript(): Promise<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)- })-})diff --git a/apps/desktop/electron/updater/updater.test.ts b/apps/desktop/electron/updater/updater.test.tsindex ea04bff9f56..42645eb0493 100644--- a/apps/desktop/electron/updater/updater.test.ts+++ b/apps/desktop/electron/updater/updater.test.ts@@ -5,9 +5,7 @@ import { describe, expect, it } from 'vitest'import { buildStampPayload } from '../../scripts/write-build-stamp.mjs'-import { appInstallerCheckToStatus, parseCheckOutput } from './app-installer'import { buildManualUpdateCommand } from './checkout'-import { type ConsumedRelaunch, consumePendingRelaunch, PENDING_RELAUNCH_FILENAME, registerUpdateRelaunch, type RelaunchRegistration, writePendingRelaunch } from './relaunch'import { resolveUpdaterMechanism } from './index'@@ -25,15 +23,19 @@ describe('build stamp → update ownership', () => {['win32', 'light', 'external', 'external'],['darwin', 'bundled', 'electron-updater', 'electron-updater'],['darwin', 'light', 'electron-updater', 'electron-updater'],+ ['darwin', 'store', 'microsoft-store', 'microsoft-store'],['linux', 'bundled', 'external', 'external'],['linux', 'light', 'external', 'external'],['win32', '', 'self', 'windows-handoff'],['darwin', '', 'self', 'posix-handoff'],['linux', '', 'self', 'posix-handoff']] as const)('%s %s dispatches its declared owner without a Store flag', (platform, variant, declared, strategy) => {- const stamp = buildStampPayload(provenance, { HERMES_DESKTOP_VARIANT: variant }, platform, { runtime })+ const stamp: ReturnType<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)- })--})diff --git a/apps/desktop/scripts/audit-bundle-arch.test.mjs b/apps/desktop/scripts/audit-bundle-arch.test.mjsindex ebcf8fdd87f..4f479f56993 100644--- a/apps/desktop/scripts/audit-bundle-arch.test.mjs+++ b/apps/desktop/scripts/audit-bundle-arch.test.mjs@@ -1,7 +1,11 @@import assert from 'node:assert/strict'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { spawnSync } from 'node:child_process'import { test } from 'vitest'-import { archMatches, classifyHeader, findUnpackedDirs, isExemptPath, peArch } from '../scripts/audit-bundle-arch.mjs'+import { auditTree, archMatches, classifyHeader, findUnpackedDirs, isExemptPath, peArch } from '../scripts/audit-bundle-arch.mjs'// ─── header builders: the smallest buffers each format needs ───────────────@@ -96,103 +100,68 @@ test('findUnpackedDirs matches electron-builder output shapes only', () => {])})-// ─── the git exemption is PortableGit-shaped, not git-shaped ───────────────--test('PortableGit internals stay exempt under the payload store', () => {- // .NET assemblies report ia32 because they are format-neutral.- for (const relPath of [- 'resources/agent-payload/tools/git-2.53.0-win32-x64/mingw64/bin/Avalonia.dll',- 'resources\\agent-payload\\tools\\git-2.53.0-win32-x64\\mingw64\\libexec\\git-core\\GitHub.dll',- 'resources\\agent-payload\\tools\\git-2.53.0-win32-x64\\usr\\libexec\\getprocaddr32.exe',- 'resources/agent-payload/tools/git-2.54.0-win32-arm64/clangarm64/libexec/git-core/msalruntime.dll'- ]) {- assert.equal(isExemptPath(relPath), true, relPath)- }-})--test('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.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 random payload binary is not exempt', () => {- assert.equal(isExemptPath('resources/agent-payload/hermes-agent/something.exe'), false)+test('tree and CLI audit real second-read PE bytes and fail closed on absent artifacts', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'arch-tree-'))+ const cli = () => spawnSync(process.execPath, [path.resolve(import.meta.dirname, 'audit-bundle-arch.mjs'), '--arch=arm64', `--root=${root}`], { encoding: 'utf8' })+ try {+ assert.match(cli().stderr, /no unpacked app directory/)+ const app = path.join(root, 'win-arm64-unpacked')+ fs.mkdirSync(app)+ assert.match(cli().stderr, /no native binaries/)+ fs.writeFileSync(path.join(app, 'elf'), elfHeader(0xb7))+ fs.writeFileSync(path.join(app, 'macho'), machoThin(0x0100000c))+ const pe = Buffer.alloc(8198)+ mzStub(8192).copy(pe)+ pe.writeUInt32LE(0x4550, 8192)+ pe.writeUInt16LE(0xa641, 8196)+ fs.writeFileSync(path.join(app, 'arm64ec.exe'), pe)+ assert.deepEqual(auditTree(app, 'arm64'), { binaries: 3, exempted: 0, mismatches: [] })+ assert.equal(cli().status, 0)+ pe.writeUInt16LE(0x8664, 8196)+ const cache = path.join(app, 'resources/agent-payload/uv-cache/builds-v0')+ fs.mkdirSync(cache, { recursive: true })+ fs.writeFileSync(path.join(cache, 'cached.exe'), pe)+ fs.writeFileSync(path.join(app, 'wrong-arch.dat'), pe)+ assert.deepEqual(auditTree(app, 'arm64'), {+ binaries: 5, exempted: 1, mismatches: [{ file: 'wrong-arch.dat', format: 'pe', arches: ['x64'] }]+ })+ const failed = cli()+ assert.equal(failed.status, 1)+ assert.match(failed.stderr, /wrong-arch.dat/)+ } finally { fs.rmSync(root, { recursive: true, force: true }) }})diff --git a/apps/desktop/scripts/batch-sign-binaries.test.mjs b/apps/desktop/scripts/batch-sign-binaries.test.mjsindex 1fad4d5739c..16e55919432 100644--- a/apps/desktop/scripts/batch-sign-binaries.test.mjs+++ b/apps/desktop/scripts/batch-sign-binaries.test.mjs@@ -9,7 +9,6 @@ import { afterEach, test } from 'vitest'import builderConfig from '../electron-builder.config.cjs'import {- azureSigningConfigured,batchSignAppTree,chunk,customSign,@@ -35,7 +34,7 @@ test('getBinaries collects .exe and .dll recursively, case-insensitive, sorted',fs.mkdirSync(path.join(root, 'resources', 'agent-payload', 'tools', 'python', 'bin'), { recursive: true })fs.mkdirSync(path.join(root, 'resources', 'agent-payload', 'tools', 'chromium-1', 'meep'), { recursive: true })fs.writeFileSync(path.join(root, 'Hermes.exe'), 'x')- fs.writeFileSync(path.join(root, 'ffmpeg.dll'), 'x')+ fs.writeFileSync(path.join(root, 'FFMPEG.DLL'), 'x')fs.writeFileSync(path.join(root, 'resources', 'agent-payload', 'tools', 'python', 'bin', 'node.exe'), 'x')fs.writeFileSync(path.join(root, 'resources', 'agent-payload', 'tools', 'chromium-1', 'meep', 'chrome.dll'), 'x')fs.writeFileSync(path.join(root, 'resources', 'README.md'), 'x')@@ -43,8 +42,8 @@ test('getBinaries collects .exe and .dll recursively, case-insensitive, sorted',const files = getBinaries(root).map(f => path.relative(root, f))assert.deepEqual(files, [+ path.join('FFMPEG.DLL'),path.join('Hermes.exe'),- path.join('ffmpeg.dll'),path.join('resources', 'agent-payload', 'tools', 'chromium-1', 'meep', 'chrome.dll'),path.join('resources', 'agent-payload', 'tools', 'python', 'bin', 'node.exe')])@@ -90,37 +89,6 @@ test('chunk splits into ~100-file batches with no leftovers', () => {assert.deepEqual(chunk(exact).map(b => b.length), [100, 100])})-test('azureSigningConfigured requires endpoint, account, and profile together', () => {- assert.equal(azureSigningConfigured({}), false)- assert.equal(azureSigningConfigured({ AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net' }), false)- assert.equal(- azureSigningConfigured({- AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net',- AZURE_SIGN_ACCOUNT: 'codesign2'- }),- false- )- assert.equal(- azureSigningConfigured({- AZURE_SIGN_ENDPOINT: 'https://cus.codesigning.azure.net',- AZURE_SIGN_ACCOUNT: 'codesign2',- AZURE_SIGN_PROFILE: 'hermesagent'- }),- true- )-})--test('customSign returns true for batch-covered payload files without touching Azure', async () => {- let azureTouched = 0- const result = await customSign(- { path: 'C:/out/win-unpacked/resources/agent-payload/tools/node.exe' },- { appInfo: { productFilename: 'Hermes' } },- { azureSignFile: async () => { azureTouched += 1 } }- )- assert.equal(result, true)- assert.equal(azureTouched, 0)-})-test('customSign skips Store- submission packages (Partner Center signs)', async () => {const result = await customSign({ path: 'C:/out/Store-HermesBundled-0.28.0-win-x64.msix' },@@ -163,7 +131,7 @@ test('customSign delegates only the msix package and root product exe to the Azuconst 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 signfs.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 signassert.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 signassert.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', asyncassert.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') returncalls += 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 signingassert.equal(calls, 3, 'timestamp pass retried until the server succeeded')})diff --git a/apps/desktop/scripts/commit-stamp-identity.test.mjs b/apps/desktop/scripts/commit-stamp-identity.test.mjsindex 72d13ccfc8a..7e66f7694e9 100644--- a/apps/desktop/scripts/commit-stamp-identity.test.mjs+++ b/apps/desktop/scripts/commit-stamp-identity.test.mjs@@ -36,12 +36,14 @@ test('desktop stamp uses the admitted checkout rather than the dispatch SHA', ()fs.writeFileSync(path.join(build, 'agent-payload/manifest.json'), JSON.stringify({ target: 'darwin-arm64', launchers: ['hermes'], runtime }))const out = path.join(build, 'install-stamp.json')const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GITHUB_') && !key.startsWith('HERMES_PAYLOAD_') && !key.startsWith('HERMES_BUILD_')))- Object.assign(env, { GITHUB_SHA: main, GITHUB_REF_NAME: 'main', HERMES_BUILD_COMMIT: feature, HERMES_DESKTOP_VARIANT: 'bundled' })+ Object.assign(env, { GITHUB_SHA: main, GITHUB_REF_NAME: 'main', HERMES_BUILD_COMMIT: feature, HERMES_DESKTOP_VARIANT: 'bundled', HERMES_PAYLOAD_VERSION: '0.28.0' })const run = override => spawnSync(process.execPath, [path.join(scripts, 'write-build-stamp.mjs')], { cwd: temp, env: { ...env, ...override }, encoding: 'utf8', timeout: 30000 })const result = run({})assert.equal(result.status, 0, result.stderr)const stamp = JSON.parse(fs.readFileSync(out, 'utf8'))assert.equal(stamp.commit, feature)+ assert.equal(stamp.baseVersion, '0.28.0')+ assert.equal(stamp.displayVersion, '0.28.0')assert.equal(stamp.branch, null)assert.equal(stamp.source, 'commit-build')assert.equal(stamp.tag, null)diff --git a/apps/desktop/scripts/local-pack-publish.test.mjs b/apps/desktop/scripts/local-pack-publish.test.mjsindex 7cc2ba8e0cc..c6c9e9a493a 100644--- a/apps/desktop/scripts/local-pack-publish.test.mjs+++ b/apps/desktop/scripts/local-pack-publish.test.mjs@@ -1,127 +1,47 @@-/**- * Regression #87758: a local desktop pack must never enter electron-builder's- * publish path, and publish resolution must succeed when something else does- * enter it.- *- * These call the real app-builder-lib resolver rather than asserting on the- * text of the pack script, so they fail if electron-builder changes the- * behavior we depend on — not when someone reformats package.json.- */import assert from 'node:assert/strict'-import { createRequire } from 'node:module'+import fs from 'node:fs'+import os from 'node:os'import path from 'node:path'-import { fileURLToPath } from 'node:url'-import { afterEach, beforeEach, describe, test } from 'vitest'-import hostedGitInfo from 'hosted-git-info'+import { createRequire } from 'node:module'+import { LinuxPackager, Packager } from 'app-builder-lib'+import { afterEach, test, vi } from 'vitest'const require = createRequire(import.meta.url)-const desktopDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')-const desktopPkg = require(path.join(desktopDir, 'package.json'))--// 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: {}- }- 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]+const lib = path.dirname(path.dirname(require.resolve('app-builder-lib')))+const { getPublishConfigs } = require(path.join(lib, 'dist/publish/PublishManager.js'))+afterEach(() => vi.unstubAllEnvs())++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 }) }}-})--describe('local desktop pack stays out of the publish path', () => {- test('the pack script pins an explicit publish policy', () => {- // electron-builder 26 infers `onTagOrDraft` from CI when --publish is- // absent, and `hermes desktop` runs the pack with CI=1 (_npm_lifecycle_env).- // v27 drops the implicit behavior, so being explicit is also forward-safe.- const pack = desktopPkg.scripts.pack- assert.match(pack, /--dir\b/)- assert.match(pack, /--publish\s+never\b/)- })-- test('publish resolution succeeds with a GitHub token present', async () => {- // The #87758 failure mode: CI=1 makes isPublish true, a GITHUB_TOKEN in the- // environment auto-selects the github provider, and the provider needs a- // repository it cannot find — apps/desktop has no .git/config of its own- // and app-builder-lib does not walk up to the workspace root.- process.env.GITHUB_TOKEN = 'x'-- const configs = await getPublishConfigs(- fakePackager(desktopPkg),- null,- null,- /* errorIfCannot */ true- )-- assert.ok(Array.isArray(configs) && configs.length > 0)- assert.equal(configs[0].provider, 'github')- assert.equal(configs[0].owner, 'NousResearch')- assert.equal(configs[0].repo, 'hermes-agent')- })-- test('a package without the repository field is what breaks resolution', async () => {- // Guards the fix itself: proves the assertion above passes because of the- // repository field, not because the throw is unreachable.- process.env.GITHUB_TOKEN = 'x'- const { repository, ...withoutRepository } = desktopPkg- assert.ok(repository, 'apps/desktop/package.json must declare a repository')-- await assert.rejects(- () => getPublishConfigs(fakePackager(withoutRepository), null, null, true),- /Cannot detect repository by \.git\/config/- )- })+)- test('resolution is quiet when no publish token is configured', async () => {- const configs = await getPublishConfigs(fakePackager(desktopPkg), null, null, true)- assert.deepEqual(configs, [])- })+test('the pack script pins an explicit publish policy', () => {+ const pack = require('../package.json').scripts.pack+ assert.match(pack, /--dir\b/)+ assert.match(pack, /--publish\s+never\b/)})diff --git a/apps/desktop/scripts/msix-alias-population.test.mjs b/apps/desktop/scripts/msix-alias-population.test.mjsdeleted file mode 100644index 11598322045..00000000000--- a/apps/desktop/scripts/msix-alias-population.test.mjs+++ /dev/null@@ -1,8 +0,0 @@-import { describe, expect, it } from 'vitest'-import { appExecutionAliasExtensions } from './before-build.mjs'--describe('MSIX alias population', () => {- it('omits execution aliases when no payload launchers are present', () => {- expect(appExecutionAliasExtensions([])).toBe('')- })-})diff --git a/apps/desktop/scripts/sanitize-pe-signatures.test.mjs b/apps/desktop/scripts/sanitize-pe-signatures.test.mjsindex f72d6ea35de..43780f7960e 100644--- a/apps/desktop/scripts/sanitize-pe-signatures.test.mjs+++ b/apps/desktop/scripts/sanitize-pe-signatures.test.mjs@@ -2,159 +2,54 @@ import assert from 'node:assert/strict'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'--import { afterEach, beforeEach, test } from 'vitest'--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 }-}--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+import { test } from 'vitest'++import { sanitizeTree } from './sanitize-pe-signatures.mjs'++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 })+ }+ })}--// ─── header arithmetic ──────────────────────────────────────────────────────--test('NumberOfRvaAndSizes sits at 92 for PE32 and 108 for PE32+', () => {- // The whole repair keys off this offset: read it wrong and a valid- // signature looks dangling (or the reverse).- assert.equal(numberOfRvaAndSizesOffset(0x10b), 92)- assert.equal(numberOfRvaAndSizesOffset(0x20b), 108)- assert.equal(numberOfRvaAndSizesOffset(0x107), null)-})--// ─── classification ─────────────────────────────────────────────────────────--test('a table wholly inside the file is a real signature', () => {- assert.equal(classifySecurityDirectory({ certOffset: 100, certSize: 24, fileSize: 200 }), 'present')- // Exactly reaching EOF is the normal shape: signatures live at the end.- assert.equal(classifySecurityDirectory({ certOffset: 100, certSize: 100, fileSize: 200 }), 'present')-})--test('a table that cannot fit in the file is dangling', () => {- // The stripped-DLL shape: offset equals the (now truncated) file size.- assert.equal(classifySecurityDirectory({ certOffset: 200, certSize: 24, fileSize: 200 }), 'dangling')- assert.equal(classifySecurityDirectory({ certOffset: 190, certSize: 24, fileSize: 200 }), 'dangling')- // Half-populated entries name no readable region either.- assert.equal(classifySecurityDirectory({ certOffset: 0, certSize: 24, fileSize: 200 }), 'dangling')- assert.equal(classifySecurityDirectory({ certOffset: 100, certSize: 0, fileSize: 200 }), 'dangling')-})--test('an all-zero table means no signature and needs no repair', () => {- assert.equal(classifySecurityDirectory({ certOffset: 0, certSize: 0, fileSize: 200 }), 'absent')-})--// ─── reading and clearing ───────────────────────────────────────────────────--test('readSecurityDirectory locates the entry in both PE widths', () => {- for (const magic of [0x10b, 0x20b]) {- const spec = { magic, certOffset: 1234, certSize: 16 }- const file = write(`w${magic}.dll`, spec)- const entry = readSecurityDirectory(file)- assert.equal(entry.certOffset, 1234)- assert.equal(entry.certSize, 16)- assert.equal(entry.offsetInFile, peFile(spec).securityDirectoryOffset)- }-})--test('readSecurityDirectory ignores files that are not PEs with directories', () => {- const plain = path.join(dir, 'notes.txt')- fs.writeFileSync(plain, 'hello')- assert.equal(readSecurityDirectory(plain), null)-- // MZ with no PE signature: a DOS-era stub, not a PE.- const stub = path.join(dir, 'stub.exe')- const buf = Buffer.alloc(0x100)- buf.write('MZ', 0, 'latin1')- buf.writeUInt32LE(0x80, 0x3c)- fs.writeFileSync(stub, buf)- assert.equal(readSecurityDirectory(stub), null)-})--test('clearSecurityDirectory zeroes the entry and changes nothing else', () => {- const spec = { magic: 0x20b, certOffset: 4096, certSize: 40 }- const file = write('cleared.dll', spec)- const before = fs.readFileSync(file)-- clearSecurityDirectory(file, peFile(spec).securityDirectoryOffset)-- const after = fs.readFileSync(file)- assert.equal(after.length, before.length)- const entry = readSecurityDirectory(file)- assert.equal(entry.certOffset, 0)- assert.equal(entry.certSize, 0)- // Byte-for-byte identical everywhere except the eight-byte entry.- const off = entry.offsetInFile- assert.deepEqual(after.subarray(0, off), before.subarray(0, off))- assert.deepEqual(after.subarray(off + 8), before.subarray(off + 8))-})--// ─── the tree pass ──────────────────────────────────────────────────────────--test('sanitizeTree repairs dangling tables and leaves real signatures alone', () => {- // The payload shape that broke the Windows bundled release: a stripped- // DLL whose table starts exactly at EOF, beside correctly signed files.- const stripped = write('python/DLLs/tcl86t.dll', { certOffset: 464, certSize: 12056 })- const signed = write('python/python.exe', { certOffset: 400, certSize: 64, trailing: 200 })- const unsigned = write('python/DLLs/_socket.pyd', {})- fs.writeFileSync(path.join(dir, 'python', 'LICENSE.txt'), 'not a PE')-- const { scanned, repaired } = sanitizeTree(dir)-- assert.equal(scanned, 3) // the three PEs; the text file is skipped- assert.deepEqual(repaired, [path.join('python', 'DLLs', 'tcl86t.dll')])- assert.equal(readSecurityDirectory(stripped).certSize, 0)- assert.equal(readSecurityDirectory(signed).certSize, 64) // untouched- assert.equal(readSecurityDirectory(unsigned).certSize, 0)-})--test('sanitizeTree is idempotent', () => {- write('DLLs/tk86t.dll', { certOffset: 464, certSize: 12064 })-- assert.equal(sanitizeTree(dir).repaired.length, 1)- assert.deepEqual(sanitizeTree(dir).repaired, [])-})diff --git a/apps/desktop/scripts/side-by-side-launchers.test.mjs b/apps/desktop/scripts/side-by-side-launchers.test.mjsindex 3a98f181447..a49eadbccf4 100644--- a/apps/desktop/scripts/side-by-side-launchers.test.mjs+++ b/apps/desktop/scripts/side-by-side-launchers.test.mjs@@ -18,28 +18,6 @@ test('the Store bundler rejects nonstable selectors before platform tools or sta}})-test('the embedded Python checkout receives the same commit provenance as Electron', () => {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-stamp-'))- try {- const commit = 'a'.repeat(40)- const repo = path.join(root, 'agent-payload/hermes-agent')- fs.mkdirSync(repo, { recursive: true })- const built = stamps.buildStampPayload({ commit, source: 'local', branch: 'main' }, {- HERMES_DESKTOP_VARIANT: 'bundled', HERMES_BUILD_COMMIT: commit, HERMES_PAYLOAD_VERSION: '0.28.0'- }, 'win32', { runtime: { repoDir: 'hermes-agent', commands: { hermes: 'bin/hermes-aaaaaaa.exe' } } })- stamps.writeDesktopStamp(root, built)- const pythonStamp = JSON.parse(fs.readFileSync(path.join(repo, 'install-stamp.json'), 'utf8'))- assert.deepEqual(pythonStamp, JSON.parse(fs.readFileSync(path.join(root, 'install-stamp.json'), 'utf8')))- assert.equal(pythonStamp.source, 'commit-build')- assert.equal(pythonStamp.commit, commit)- assert.equal(pythonStamp.tag, null)- assert.equal(pythonStamp.baseVersion, '0.28.0')- assert.equal(pythonStamp.displayVersion, '0.28.0')- } finally {- fs.rmSync(root, { recursive: true, force: true })- }-})-test('nonstable MSIX CLI aliases each activate their own entrypoint, never the GUI', () => {const launchers = ['hermes-canary', 'hermes-canary-acp']const applications = msix.appExecutionAliasApplications(launchers, {diff --git a/apps/desktop/scripts/sign-msix.test.mjs b/apps/desktop/scripts/sign-msix.test.mjsindex 02825140a07..06a9e1c53ed 100644--- a/apps/desktop/scripts/sign-msix.test.mjs+++ b/apps/desktop/scripts/sign-msix.test.mjs@@ -2,10 +2,11 @@ import assert from 'node:assert/strict'import fs from 'node:fs'import { createRequire } from 'node:module'import path from 'node:path'+import os from 'node:os'import { pathToFileURL } from 'node:url'-import { test } from 'vitest'+import { test, vi } from 'vitest'-import { azureConfigFromEnv, shouldSignFile } from './sign-msix.mjs'+import { azureConfigFromEnv, azureSignFile, shouldSignFile } from './sign-msix.mjs'const require = createRequire(import.meta.url)@@ -75,46 +76,35 @@ test('azureConfigFromEnv composes the Azure signing config from the environment'})})-// ─── builder-bump tripwire ──────────────────────────────────────────────────-// sign-msix.mjs deep-imports app-builder-lib's WindowsSignAzureManager by-// file path (the package exports map exposes only "." and "./internal", so-// the dist path is reached the same way run-electron-builder.mjs finds the-// CLI: resolve the entry, walk up to the package root, then direct-file-// import). If an electron-builder/app-builder-lib bump moves or renames the-// class, THIS test is what fails in js-tests — before a release build does.-// 60s timeout: the direct-file import drags in app-builder-lib's whole-// module graph (toolsets, electronGet, vm), which takes ~30s on a cold-// disk cache — far past vitest's 5s default.-test('the real WindowsSignAzureManager resolves and constructs against a packager shim', { timeout: 60_000 }, async () => {- const entry = require.resolve('app-builder-lib')- let root = path.dirname(entry)- while (!fs.existsSync(path.join(root, 'package.json'))) {- const parent = path.dirname(root)- assert.notEqual(parent, root, 'app-builder-lib package root not found')- root = parent+test('azureSignFile calls the real supplier through a prepared local toolset', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'sign-supplier-'))+ const lib = path.dirname(path.dirname(require.resolve('app-builder-lib')))+ const { VmManager } = await import(pathToFileURL(path.join(lib, 'dist/vm/vm.js')).href)+ const { WineVmManager } = await import(pathToFileURL(path.join(lib, 'dist/vm/WineVm.js')).href)+ const native = process.platform === 'win32' ? VmManager : WineVmManager+ const calls = []+ // Only the final native execution is intercepted; manager init, dispatch and metadata are real.+ const execution = vi.spyOn(native.prototype, 'exec').mockImplementation(async (file, args) => { calls.push({ file, args }) })+ const kits = path.join(root, 'kits')+ const kit = path.join(kits, process.arch === 'ia32' ? 'x86' : 'x64')+ fs.mkdirSync(kit, { recursive: true })+ const metadata = path.join(root, 'metadata.json')+ for (const [name, value] of Object.entries({ AZURE_SIGN_ENDPOINT: 'https://test.invalid', AZURE_SIGN_ACCOUNT: 'account', AZURE_SIGN_PROFILE: 'profile', AZURE_SIGN_PUBLISHER: 'CN=Fixture' })) vi.stubEnv(name, value)+ try {+ await azureSignFile(path.join(root, 'fixture.msix'), {+ platformOptions: { sign: { type: 'signtool' } },+ config: { toolsets: { winCodeSign: { url: `file://${kits}` } } },+ buildResourcesDir: root,+ getTempFile: async () => metadata+ })+ assert.deepEqual(JSON.parse(fs.readFileSync(metadata, 'utf8')), { Endpoint: 'https://test.invalid', CodeSigningAccountName: 'account', CertificateProfileName: 'profile' })+ assert.equal(calls.length, 1)+ assert.equal(calls[0].file, path.join(kit, 'signtool.exe'))+ assert.deepEqual(calls[0].args.slice(0, 7), ['sign', '/fd', 'SHA256', '/tr', 'http://timestamp.acs.microsoft.com', '/td', 'SHA256'])+ assert.ok(calls[0].args[calls[0].args.indexOf('/dlib') + 1].endsWith('Azure.CodeSigning.Dlib.dll'))+ assert.ok(calls[0].args.at(-1).endsWith('fixture.msix'))+ } finally {+ execution.mockRestore(); vi.unstubAllEnvs()+ fs.rmSync(root, { recursive: true, force: true })}- const mod = await import(- pathToFileURL(path.join(root, 'dist', 'codeSign', 'win', 'windowsSignAzureManager.js')).href- )- assert.equal(typeof mod.WindowsSignAzureManager, 'function')-- // Constructor contract (verified against 27.0.0-alpha.6): reads- // packager.platformOptions.sign (throws unless type === 'azure'),- // packager.config.toolsets (optional), and packager.buildResourcesDir- // (only stored — WineVmManager's constructor touches no filesystem).- const mgr = new mod.WindowsSignAzureManager({- platformOptions: {- sign: {- type: 'azure',- endpoint: 'x',- codeSigningAccountName: 'y',- certificateProfileName: 'z',- publisherName: 'p'- }- },- config: {},- buildResourcesDir: '/tmp'- })- assert.equal(typeof mgr.signFile, 'function')- assert.equal(typeof mgr.initialize, 'function')})diff --git a/apps/desktop/scripts/sign-nested-chromium.test.mjs b/apps/desktop/scripts/sign-nested-chromium.test.mjsindex a6d5dfb43b3..cf25439f312 100644--- a/apps/desktop/scripts/sign-nested-chromium.test.mjs+++ b/apps/desktop/scripts/sign-nested-chromium.test.mjs@@ -5,10 +5,6 @@ import path from 'node:path'import { test } from 'vitest'import {- chromiumRoots,- isMachO,- listLooseMachO,- listTopLevelApps,parseDeveloperId,repairFrameworkLinks,resolveSigningIdentity,@@ -25,48 +21,6 @@ function machoBuf() {return buf}-test('isMachO accepts a 64-bit Mach-O magic and rejects text', () => {- const dir = tempRoot()- try {- const bin = path.join(dir, 'a')- const txt = path.join(dir, 'b.txt')- fs.writeFileSync(bin, machoBuf())- fs.writeFileSync(txt, 'not a binary')- assert.equal(isMachO(bin), true)- assert.equal(isMachO(txt), false)- } finally {- fs.rmSync(dir, { recursive: true, force: true })- }-})--test('chromiumRoots only names full Chromium store entries', () => {- const payload = tempRoot()- try {- fs.mkdirSync(path.join(payload, 'tools', 'chromium-1208'), { recursive: true })- fs.mkdirSync(path.join(payload, 'tools', 'chromium_headless_shell-1208'), { recursive: true })- fs.mkdirSync(path.join(payload, 'tools', 'uv-0.12.3-darwin-arm64'), { recursive: true })- const roots = chromiumRoots(payload).map(p => path.basename(p)).sort()- assert.deepEqual(roots, ['chromium-1208'])- } finally {- fs.rmSync(payload, { recursive: true, force: true })- }-})--test('listTopLevelApps finds .app dirs and listLooseMachO skips them', () => {- const root = tempRoot()- try {- const app = path.join(root, 'Google Chrome for Testing.app')- fs.mkdirSync(path.join(app, 'Contents', 'MacOS'), { recursive: true })- fs.writeFileSync(path.join(app, 'Contents', 'MacOS', 'Chrome'), machoBuf())- const loose = path.join(root, 'libEGL.dylib')- fs.writeFileSync(loose, machoBuf())- assert.deepEqual(listTopLevelApps(root), [app])- assert.deepEqual(listLooseMachO(root), [loose])- } finally {- fs.rmSync(root, { recursive: true, force: true })- }-})-test('repairFrameworkLinks turns a flattened Foo.framework/Foo into a symlink', () => {if (process.platform === 'win32') returnconst root = tempRoot()@@ -120,6 +74,12 @@ test('signNestedChromium --deep signs the .app and file-signs loose Mach-O', ()fs.writeFileSync(path.join(app, 'Contents', 'MacOS', 'Chrome'), machoBuf())const loose = path.join(payload, 'tools', 'chromium-1208', 'libEGL.dylib')fs.writeFileSync(loose, machoBuf())+ fs.writeFileSync(path.join(path.dirname(loose), 'README'), 'not Mach-O')+ for (const name of ['chromium_headless_shell-1208', 'uv-0.12.3-darwin-arm64']) {+ const other = path.join(payload, 'tools', name)+ fs.mkdirSync(other, { recursive: true })+ fs.writeFileSync(path.join(other, 'binary'), machoBuf())+ }const calls = []const r = signNestedChromium(payload, {identity: 'Developer ID Application: Test',diff --git a/apps/desktop/scripts/write-build-stamp.test.mjs b/apps/desktop/scripts/write-build-stamp.test.mjsindex 8223fbe8d91..9b0dffc2ec4 100644--- a/apps/desktop/scripts/write-build-stamp.test.mjs+++ b/apps/desktop/scripts/write-build-stamp.test.mjs@@ -120,40 +120,6 @@ test('source builds declare the same artifact schema, without a payload', () =>assert.equal(stamp.commit, baseStamp.commit)})-test('buildStampPayload with bundled variant declares the App Installer owner', () => {- const payload = buildStampPayload(baseStamp, {- HERMES_DESKTOP_VARIANT: 'bundled',- HERMES_PAYLOAD_TAG: 'v0.27.1-canary.20260901072553'- }, 'win32', { runtime })- assert.equal(payload.payload, 'bundled')- assert.equal(payload.distribution, 'desktop-app')- assert.equal(payload.updateMechanism, 'app-installer')- assert.equal(payload.tag, 'v0.27.1-canary.20260901072553')-})--test('macOS bundles and Light declare app-owned updates; the win32 store variant is Store owned', () => {- for (const variant of ['bundled', 'light', 'store']) {- const stamp = buildStampPayload(baseStamp, { HERMES_DESKTOP_VARIANT: variant }, 'darwin', { runtime })- assert.equal(stamp.updateMechanism, variant === 'store' ? 'microsoft-store' : 'electron-updater')- }-})--test('buildStampPayload with store variant declares external ownership', () => {- const payload = buildStampPayload(baseStamp, {- HERMES_DESKTOP_VARIANT: 'store',- HERMES_PAYLOAD_TAG: 'v0.27.1'- }, 'win32', { runtime })- assert.equal(payload.payload, 'bundled')-})--test('buildStampPayload with light variant stamps payload light', () => {- const payload = buildStampPayload(baseStamp, {- HERMES_DESKTOP_VARIANT: 'light',- HERMES_PAYLOAD_TAG: 'v0.27.1'- })- assert.equal(payload.payload, 'light')-})-test('buildStampPayload keeps schemaVersion + provenance in the staged shape', () => {const payload = buildStampPayload(baseStamp, {HERMES_DESKTOP_VARIANT: 'bundled'diff --git a/apps/desktop/src/api/local-models-owner.test.ts b/apps/desktop/src/api/local-models-owner.test.tsindex 3ee2149da59..91d5533ae23 100644--- a/apps/desktop/src/api/local-models-owner.test.ts+++ b/apps/desktop/src/api/local-models-owner.test.ts@@ -1,7 +1,9 @@import { beforeEach, expect, it, vi } from 'vitest'+import type { LocalModelsOwner } from '@/store/local-runtime-jobs'+import { setApiRequestConnection, setApiRequestProfile } from './client'-import { getLocalModelsJobs, getLocalModelsStatus, pauseLocalDownload } from './local-models'+import { getLocalModelsJobs, getLocalModelsStatus, pauseLocalDownload, resumeLocalDownload } from './local-models'beforeEach((): void => {Object.defineProperty(window, 'hermesDesktop', {@@ -22,3 +24,17 @@ it('pins delayed reads and controls to their captured connection and profile', aexpect(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')+})diff --git a/apps/desktop/src/api/local-models.test.ts b/apps/desktop/src/api/local-models.test.tsdeleted file mode 100644index 373e45d1287..00000000000--- a/apps/desktop/src/api/local-models.test.ts+++ /dev/null@@ -1,54 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'--vi.mock('./client', () => ({- hermesApi: vi.fn(),- profileScoped: vi.fn(() => ({}))-}))--const client = await import('./client')--const { pauseLocalDownload, resumeLocalDownload } = await import('./local-models')--const hermesApi = vi.mocked(client.hermesApi)--beforeEach(() => {- vi.clearAllMocks()-})--describe('local download pause/resume API', () => {- it('pauseLocalDownload posts {job_id} to the existing pause route and returns the {ok,paused} contract', async () => {- hermesApi.mockResolvedValue({ ok: true, paused: true } as never)-- const res = await pauseLocalDownload('job-7')-- expect(hermesApi).toHaveBeenCalledTimes(1)- expect(hermesApi.mock.calls[0][0]).toMatchObject({- body: { job_id: 'job-7' },- method: 'POST',- path: '/api/local-models/download/pause'- })- expect(res).toEqual({ ok: true, paused: true })- })-- it('resumeLocalDownload posts {job_id} to the existing resume route and returns the {ok,resumed} contract', async () => {- hermesApi.mockResolvedValue({ ok: true, resumed: false } as never)-- const res = await resumeLocalDownload('job-8')-- expect(hermesApi).toHaveBeenCalledTimes(1)- expect(hermesApi.mock.calls[0][0]).toMatchObject({- body: { job_id: 'job-8' },- method: 'POST',- path: '/api/local-models/download/resume'- })- // A false resumed flag (no parked download) reaches the caller so the- // UI can report "couldn't resume" rather than silently claiming success.- expect(res).toEqual({ ok: true, resumed: false })- })-- it('a failed pause propagates as a rejection — never a silent success', async () => {- hermesApi.mockRejectedValue(new Error('unknown download job'))-- await expect(pauseLocalDownload('gone')).rejects.toThrow('unknown download job')- })-})diff --git a/apps/desktop/src/app/settings/local-model-download-progress.test.tsx b/apps/desktop/src/app/settings/local-model-download-progress.test.tsxindex 269d49c3523..92a513b1188 100644--- a/apps/desktop/src/app/settings/local-model-download-progress.test.tsx+++ b/apps/desktop/src/app/settings/local-model-download-progress.test.tsx@@ -60,19 +60,6 @@ afterEach(() => {})describe('LocalModelDownloadActions', () => {- it('running download with can_pause:true renders Pause; clicking sends pauseLocalDownload exactly once with the job id', async () => {- renderActions(job({ can_pause: true }))-- const pause = screen.getByRole('button', { name: /pause/i })- fireEvent.click(pause)-- await waitFor(() => {- expect(pauseLocalDownload).toHaveBeenCalledTimes(1)- })- expect(pauseLocalDownload).toHaveBeenCalledWith('j1', undefined)- expect(resumeLocalDownload).not.toHaveBeenCalled()- })-it('running download without explicit can_pause shows NO control (no guessing about old backends)', () => {renderActions(job({}))@@ -92,21 +79,6 @@ describe('LocalModelDownloadActions', () => {expect((pending as HTMLButtonElement).disabled).toBe(true)})- it('paused job renders the Paused label + Resume (can_resume:true); clicking sends resumeLocalDownload with the job id', async () => {- renderActions(job({ can_resume: true, status: 'paused' }))-- expect(screen.getByText(/paused/i)).toBeTruthy()-- const resume = screen.getByRole('button', { name: /resume/i })- fireEvent.click(resume)-- await waitFor(() => {- expect(resumeLocalDownload).toHaveBeenCalledTimes(1)- })- expect(resumeLocalDownload).toHaveBeenCalledWith('j1', undefined)- expect(pauseLocalDownload).not.toHaveBeenCalled()- })-it('paused hides Resume when can_resume is not explicitly true', () => {renderActions(job({ status: 'paused' }))diff --git a/apps/desktop/src/app/settings/local-models-settings.test.tsx b/apps/desktop/src/app/settings/local-models-settings.test.tsxindex 1db6e8f480c..4799ee791b6 100644--- a/apps/desktop/src/app/settings/local-models-settings.test.tsx+++ b/apps/desktop/src/app/settings/local-models-settings.test.tsx@@ -660,179 +660,7 @@ describe('quickstart completion navigation', () => {})})-describe('pause / resume integration', () => {- beforeEach((): void => {- queryClient.clear()- queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, retry: false } })- vi.mocked(hermes.pauseLocalDownload).mockResolvedValue({ ok: true, paused: true })- vi.mocked(hermes.resumeLocalDownload).mockResolvedValue({ ok: true, resumed: true })- })-- it('a running catalog download shows Pause; clicking sends the job id once', async () => {- mocked.getLocalModelsStatus.mockResolvedValue({- ...BASE_STATUS,- runtime_installed: true,- runtime_backend: 'cuda'- })- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [- {- job_id: 'j1',- kind: 'model-download',- target: 'Qwen3.6 27B',- model_id: FITTING_MODEL.id,- status: 'running',- phase: 'downloading',- detail: 'Qwen3.6 27B — 17.6 GB',- total_bytes: 100,- can_pause: true,- done_bytes: 40,- percent: 40,- error: null- }- ])-- await renderFullPane()- await screen.findByText('Qwen3.6 27B')-- fireEvent.click(screen.getByRole('button', { name: /pause/i }))-- await waitFor(() => {- expect(hermes.pauseLocalDownload).toHaveBeenCalledTimes(1)- })- expect(hermes.pauseLocalDownload).toHaveBeenCalledWith('j1', { connectionId: null, profile: 'default' })- expect(hermes.resumeLocalDownload).not.toHaveBeenCalled()- })-- it('a paused catalog download keeps its row: Paused label, Resume button, progress bar retained', async () => {- mocked.getLocalModelsStatus.mockResolvedValue({- ...BASE_STATUS,- runtime_installed: true,- runtime_backend: 'cuda'- })- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [- {- job_id: 'j1',- kind: 'model-download',- target: 'Qwen3.6 27B',- model_id: FITTING_MODEL.id,- can_resume: true,- phase: 'downloading',- status: 'paused',- detail: 'Qwen3.6 27B — 17.6 GB',- total_bytes: 100,- done_bytes: 40,- percent: 40,- error: null- }- ])-- await renderFullPane()- await screen.findByText('Qwen3.6 27B')-- // Row survives with an honest parked label and a way forward.- expect(screen.getAllByText(/paused/i).length).toBeGreaterThan(0)- expect(screen.getByRole('button', { name: /resume/i })).toBeTruthy()-- fireEvent.click(screen.getByRole('button', { name: /resume/i }))- await waitFor(() => {- expect(hermes.resumeLocalDownload).toHaveBeenCalledWith('j1', { connectionId: null, profile: 'default' })- })-- // The watcher re-kicked: an authoritative re-read happens after resume.- await waitFor(() => {- expect(mocked.getLocalModelsJobs.mock.calls.length).toBeGreaterThanOrEqual(2)- })- })-- it('a paused quickstart stays pinned in the hero with a Resume control', async () => {- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [- {- job_id: 'q1',- kind: 'quickstart',- target: 'Qwen3.6 27B',- model_id: 'qwen3.6-27b',- can_resume: true,- phase: 'downloading',- status: 'paused',- detail: '',- total_bytes: 100,- done_bytes: 30,- percent: 30,- error: null- }- ])-- renderPane()- await screen.findAllByText(/paused/i)-- expect(screen.getByRole('button', { name: /resume/i })).toBeTruthy()- // Hero is pinned — no quickstart action button competes with it.- expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()-- fireEvent.click(screen.getByRole('button', { name: /resume/i }))- await waitFor(() => {- expect(hermes.resumeLocalDownload).toHaveBeenCalledWith('q1', { connectionId: null, profile: 'default' })- })- })-- it('a running quickstart hero shows Pause during the download stage', async () => {- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [- {- job_id: 'q1',- kind: 'quickstart',- target: 'Qwen3.6 27B',- model_id: 'qwen3.6-27b',- can_pause: true,- phase: 'downloading',- status: 'running',- detail: '',- total_bytes: 100,- done_bytes: 30,- percent: 30,- error: null- }- ])-- renderPane()- await screen.findByText('Qwen3.6 27B')-- expect(screen.getByRole('button', { name: /pause/i })).toBeTruthy()- })-- it('a running runtime install row shows Pause when the engine leg can park', async () => {- mocked.getLocalModelsStatus.mockResolvedValue({- ...BASE_STATUS,- runtime_installed: false,- update_available: false- })- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [- {- job_id: 'r1',- kind: 'runtime-install',- target: 'llamacpp',- model_id: null,- can_pause: true,- phase: 'downloading-runtime',- status: 'running',- detail: 'llamacpp b10290',- total_bytes: 100,- done_bytes: 10,- percent: 10,- error: null- }- ])-- renderPane()- await screen.findByText(/installing/i)-- const pause = screen.getByRole('button', { name: /pause/i })- fireEvent.click(pause)-- await waitFor(() => {- expect(hermes.pauseLocalDownload).toHaveBeenCalledWith('r1', { connectionId: null, profile: 'default' })- })- })-+describe('quickstart finalization', (): void => {it('quickstart hero suppresses the byte counter outside download phases', async () => {queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [{diff --git a/apps/desktop/src/components/desktop-install-local-card.test.ts b/apps/desktop/src/components/desktop-install-local-card.test.tsdeleted file mode 100644index d8ad468b366..00000000000--- a/apps/desktop/src/components/desktop-install-local-card.test.ts+++ /dev/null@@ -1,33 +0,0 @@-import assert from 'node:assert/strict'--import { test } from 'vitest'--import { localCardPresentation } from './desktop-install-local-card'--test('none is the installer offer with the install-to footer', () => {- assert.deepEqual(localCardPresentation('none'), {- title: 'installLocalTitle',- desc: 'installLocalDesc',- showInstallTo: true- })-})--test('installed uses the existing-runtime copy and hides the install-to footer', () => {- assert.deepEqual(localCardPresentation('installed'), {- title: 'useLocalTitle',- desc: 'useLocalDesc',- showInstallTo: false- })-})--test('bundled uses the bundled flavor of the existing-runtime copy', () => {- assert.deepEqual(localCardPresentation('bundled'), {- title: 'useLocalTitle',- desc: 'bundledLocalDesc',- showInstallTo: false- })-})--test('an absent local field falls back to the installer offer (old backends)', () => {- assert.equal(localCardPresentation(undefined).title, 'installLocalTitle')-})diff --git a/apps/desktop/src/components/desktop-install-overlay.test.tsx b/apps/desktop/src/components/desktop-install-overlay.test.tsxindex ba98301881c..c1ee6e615a8 100644--- a/apps/desktop/src/components/desktop-install-overlay.test.tsx+++ b/apps/desktop/src/components/desktop-install-overlay.test.tsx@@ -2,7 +2,7 @@import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { DesktopBootstrapEvent, DesktopBootstrapState, DesktopConnectionProbeResult } from '@/global'+import type { DesktopBootstrapEvent, DesktopBootstrapState } from '@/global'import { DesktopInstallOverlay } from './desktop-install-overlay'@@ -303,103 +303,6 @@ describe('DesktopInstallOverlay first-run setup', () => {await waitFor(() => expect(screen.queryByText('Gateway URL')).toBeNull())})- it('ignores a completed probe after the gateway URL becomes invalid', async () => {- const desktop = installDesktopMock(- bootstrapState({- setupChoice: { platform: 'linux', activeRoot: '/home/me/.hermes/hermes-agent', local: 'none', bundled: false }- })- )-- let resolveProbe: ((result: DesktopConnectionProbeResult) => void) | undefined-- const pendingProbe = new Promise<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() }})diff --git a/apps/desktop/src/components/external-open-failed-dialog.test.tsx b/apps/desktop/src/components/external-open-failed-dialog.test.tsxindex 38226d71c26..0e6ab1336cf 100644--- a/apps/desktop/src/components/external-open-failed-dialog.test.tsx+++ b/apps/desktop/src/components/external-open-failed-dialog.test.tsx@@ -45,45 +45,18 @@ afterEach(() => {})describe('ExternalOpenFailedDialog', () => {- it('subscribes to open-failure events on mount', () => {- const { onExternalOpenFailed } = installBridge()+ it('subscribes, displays, copies and dismisses an external-open failure', async (): Promise<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', () => {diff --git a/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx b/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsxindex 50d33c812eb..5c4d9838cf4 100644--- a/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx+++ b/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx@@ -1,4 +1,4 @@-import { act, cleanup, renderHook } from '@testing-library/react'+import { act, cleanup, renderHook, type RenderHookResult } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { DesktopConnectionProbeResult } from '@/global'@@ -88,3 +88,36 @@ describe('remote setup owner', () => {expect(onNotice).not.toHaveBeenCalled()})})++it.each<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')+})diff --git a/apps/desktop/src/components/sync-status-card.test.tsx b/apps/desktop/src/components/sync-status-card.test.tsxindex 06ee1c7ef5c..79120cee265 100644--- a/apps/desktop/src/components/sync-status-card.test.tsx+++ b/apps/desktop/src/components/sync-status-card.test.tsx@@ -1,88 +1,68 @@import { act, cleanup, render, screen } from '@testing-library/react'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, expect, it, vi } from 'vitest'import type { DesktopSyncReceipt } from '@/global'import { SyncStatusCard } from './sync-status-card'-function setBridge(receipt: DesktopSyncReceipt | null | Promise<DesktopSyncReceipt | null>, failing = false) {- ;(window as any).hermesDesktop = {- getSyncStatus: failing- ? vi.fn(() => Promise.reject(new Error('bridge gone')))- : vi.fn(() => Promise.resolve(receipt))- }-}--afterEach(() => {- cleanup()- delete (window as any).hermesDesktop-})+afterEach((): void => { cleanup(); vi.unstubAllGlobals() })-async function renderCard() {- await act(async () => {- render(<SyncStatusCard />)- })+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 }+ ]}-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()+interface ReceiptCase {+ name: string+ receipt: DesktopSyncReceipt | null+ headline: RegExp | null+ tone?: string+}- 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()- })+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' }+]- 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()+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 />) })- 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()- })+ if (!headline) { expect(screen.queryByTestId('sync-status-card')).toBeNull();- 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()+ return }- expect(screen.getByText(/rebuild failed/)).toBeTruthy()- })+ expect(screen.getByText(headline).className).toContain(tone)- 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_bisect) { expect(screen.getByText('conflictor: conflicts with core pin')).toBeTruthy() }- cleanup()- setBridge({ kind: 'sync', outcome: 'ok' })- await renderCard()- expect(screen.queryByTestId('sync-status-card')).toBeNull()- })+ 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()+})- 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()})diff --git a/apps/desktop/src/components/sync-status.test.ts b/apps/desktop/src/components/sync-status.test.tsdeleted file mode 100644index 1c3cd72df00..00000000000--- a/apps/desktop/src/components/sync-status.test.ts+++ /dev/null@@ -1,107 +0,0 @@-import { describe, expect, test } from 'vitest'--import type { DesktopSyncReceipt } from '@/global'--import { deriveSyncStatusSummary } from './sync-status'--describe('deriveSyncStatusSummary', () => {- test('a no-op sync is healthy, while an embedded failed sync is visible', () => {- expect(deriveSyncStatusSummary({ outcome: 'ok', venv_rebuild: { ok: false, reason: 'already in sync' } }).headline).toBeNull()-- const receipt = {- outcome: 'failed', pm_sync_outcome: 'failed',- pm_steps: [{ name: 'dependency-sync', ok: false, detail: 'network unavailable' }]- }-- const summary = deriveSyncStatusSummary(receipt)- expect(summary.level).toBe('error')- expect(summary.headline).toContain('network unavailable')- })-- test('null receipt degrades to nothing-to-show', () => {- const summary = deriveSyncStatusSummary(null)- expect(summary.headline).toBeNull()- expect(summary.level).toBe('ok')- expect(summary.disabledPlugins).toEqual([])- })-- test('empty receipt degrades the same', () => {- const summary = deriveSyncStatusSummary({})- expect(summary.headline).toBeNull()- })-- test('failed rebuild is the top signal (error level)', () => {- const receipt: DesktopSyncReceipt = {- kind: 'sync',- outcome: 'failed',- venv_rebuild: { ok: false, reason: 'uv sync exited 1: unsatisfiable' }- }-- const summary = deriveSyncStatusSummary(receipt)- expect(summary.level).toBe('error')- expect(summary.headline).toContain('rebuild failed')- })-- test('bisect disables surface as warn with reasons', () => {- const receipt: DesktopSyncReceipt = {- kind: 'sync',- outcome: 'bisected',- plugin_bisect: [- { plugin: 'bad-plug', action: 'disabled', reason: 'conflicts with core pin' },- { plugin: 'kept-plug', action: 'kept', reason: '' }- ]- }-- const summary = deriveSyncStatusSummary(receipt)- expect(summary.level).toBe('warn')- expect(summary.disabledPlugins).toEqual([- { plugin: 'bad-plug', reason: 'conflicts with core pin' }- ])- expect(summary.headline).toContain('disabled')- })-- test('needs-fixing beats updates in priority', () => {- const receipt: DesktopSyncReceipt = {- kind: 'plugin-check',- outcome: 'updates-available',- plugin_checks: [- {- name: 'plug',- needs_fixing: 'update_url mismatch: saved vs manifest'- },- { name: 'other', update_available: true, current: '1.0', latest: '2.0' }- ]- }-- const summary = deriveSyncStatusSummary(receipt)- expect(summary.level).toBe('warn')- expect(summary.headline).toContain('update-url')- expect(summary.needsFixing).toHaveLength(1)- expect(summary.updatesAvailable).toEqual([- { name: 'other', current: '1.0', latest: '2.0' }- ])- })-- test('plain updates-available is info, not warn', () => {- const receipt: DesktopSyncReceipt = {- kind: 'plugin-check',- outcome: 'updates-available',- plugin_checks: [{ name: 'plug', update_available: true, current: '1.0', latest: '1.1' }]- }-- const summary = deriveSyncStatusSummary(receipt)- expect(summary.level).toBe('info')- expect(summary.headline).toContain('updates available')- })-- test('unknown update_available (null) is not an update', () => {- const receipt: DesktopSyncReceipt = {- kind: 'plugin-check',- plugin_checks: [{ name: 'mystery', update_available: null, reason: 'not on PyPI' }]- }-- const summary = deriveSyncStatusSummary(receipt)- expect(summary.updatesAvailable).toEqual([])- expect(summary.headline).toBeNull()- })-})diff --git a/apps/desktop/src/components/version-details-store.test.tsx b/apps/desktop/src/components/version-details-store.test.tsxdeleted file mode 100644index cf97d709362..00000000000--- a/apps/desktop/src/components/version-details-store.test.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { cleanup, render, screen } from '@testing-library/react'-import { afterEach, describe, expect, it } from 'vitest'--import type { DesktopVersionInfo } from '@/global'-import { I18nProvider } from '@/i18n'--import { VersionDetails } from './version-details'--const baseVersion: DesktopVersionInfo = {- appVersion: '0.19.0',- electronVersion: '37.0.0',- hermesRoot: '/tmp/hermes',- nodeVersion: '22.0.0',- platform: 'linux'-}--afterEach(cleanup)--describe('VersionDetails Store identity label', () => {- it('labels a Store-identity build from the stamp mechanism, not windowsStore', () => {- render(- <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()- })-})diff --git a/apps/desktop/src/components/version-details.test.tsx b/apps/desktop/src/components/version-details.test.tsxindex 4b697f25631..86b9b4d83c7 100644--- a/apps/desktop/src/components/version-details.test.tsx+++ b/apps/desktop/src/components/version-details.test.tsx@@ -1,5 +1,5 @@import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it, type Mock, vi } from 'vitest'import type { DesktopVersionInfo } from '@/global'import { I18nProvider } from '@/i18n'@@ -7,29 +7,10 @@ import { $previewTabs, closeRightRail } from '@/store/preview'import { VersionDetails } from './version-details'-const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }-const initialHermesDesktop = desktopWindow.hermesDesktop--function installDesktopBridge() {- const openExternal = vi.fn().mockResolvedValue(undefined)-- desktopWindow.hermesDesktop = {- openExternal- } as unknown as Window['hermesDesktop']-- return openExternal-}--afterEach(() => {+afterEach((): void => {cleanup()closeRightRail()- vi.restoreAllMocks()-- if (initialHermesDesktop) {- desktopWindow.hermesDesktop = initialHermesDesktop- } else {- delete desktopWindow.hermesDesktop- }+ vi.unstubAllGlobals()})const baseVersion: DesktopVersionInfo = {@@ -41,98 +22,36 @@ const baseVersion: DesktopVersionInfo = {}describe('VersionDetails', () => {- it('omits the branch suffix when no branch is present', () => {- render(- <I18nProvider configClient={null} initialLocale="en">- <VersionDetails version={{ ...baseVersion, source: 'ci', branch: null }} />- </I18nProvider>- )-- expect(screen.getByText('Build Origin')).toBeTruthy()- expect(screen.getByText('CI')).toBeTruthy()- })-- it('shows a literal branch named unknown inline', () => {- render(- <I18nProvider configClient={null} initialLocale="en">- <VersionDetails version={{ ...baseVersion, source: 'ci', branch: 'unknown' }} />- </I18nProvider>- )-- expect(screen.getByText('CI (unknown)')).toBeTruthy()- })-- it('shows the Nix source and distribution from the stamp', () => {- render(- <I18nProvider configClient={null} initialLocale="en">- <VersionDetails version={{ ...baseVersion, source: 'nix', distribution: 'nix' }} />- </I18nProvider>- )-- 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()+ interface VersionCase { version: Partial<DesktopVersionInfo>; visible: string[]; absent?: string[] }++ 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.each(cases)('renders $version', ({ version, visible, absent = [] }: VersionCase): void => {+ render(<I18nProvider configClient={null} initialLocale="en"><VersionDetails version={{ ...baseVersion, ...version }} /></I18nProvider>)++ for (const text of visible) { expect(screen.getAllByText(text).length).toBeGreaterThan(0) }++ for (const text of absent) { expect(screen.queryByText(text)).toBeNull() }++ 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">diff --git a/apps/desktop/src/i18n/key-parity.test.ts b/apps/desktop/src/i18n/key-parity.test.tsdeleted file mode 100644index 98a2a7b3667..00000000000--- a/apps/desktop/src/i18n/key-parity.test.ts+++ /dev/null@@ -1,152 +0,0 @@-import { describe, expect, it } from 'vitest'--import { ar } from './ar'-import { en } from './en'-import { ja } from './ja'-import { ru } from './ru'-import { zh } from './zh'-import { zhHant } from './zh-hant'--/**- * Locale key-parity guard — the class-fix for the recurring "missed locale"- * bug family: a key renamed in en.ts but left stale in a partial locale- * (e.g. `view.terminalSelection` → `view.selectionToComposer`, which missed- * ru.ts for weeks and made the renamed row fall back to English for ru- * users).- *- * `defineLocale()` locales are PARTIAL by design — missing keys fall back to- * English at runtime (that's the documented contract). What must never- * happen is a locale carrying a *stale* key: en renamed or removed a leaf- * while the locale kept the old name. The old key is dead weight at best- * and a silently-lost translation at worst.- *- * Invariant (one-directional): when en has a NON-EMPTY section, every- * locale key under that section must still exist in en. Sections en emptied- * entirely (`platformIntro: {}` — free-form `Record<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')}`)- }- })-})diff --git a/apps/desktop/src/store/local-models-surfaces.test.tsx b/apps/desktop/src/store/local-models-surfaces.test.tsxindex d5ab528c6bb..2d126b793b6 100644--- a/apps/desktop/src/store/local-models-surfaces.test.tsx+++ b/apps/desktop/src/store/local-models-surfaces.test.tsx@@ -4,7 +4,7 @@ import { MemoryRouter } from 'react-router'import { afterEach, beforeEach, expect, it, vi } from 'vitest'import type { HermesApiRequest, HermesConnection } from '@/global'-import type { LocalModelsStatus, LocalRuntimeJob, ModelOptionsResponse } from '@/types/hermes'+import type { LocalCatalogModel, LocalModelsStatus, LocalRuntimeJob, ModelOptionsResponse } from '@/types/hermes'vi.mock('@/hermes', async (): Promise<object> => ({...(await import('@/api/local-models')),@@ -31,7 +31,7 @@ import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menuimport { 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 outexpect(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)+})diff --git a/apps/desktop/src/store/local-runtime-jobs.test.ts b/apps/desktop/src/store/local-runtime-jobs.test.tsindex 6ebe5f1c62d..a3b0236a45b 100644--- a/apps/desktop/src/store/local-runtime-jobs.test.ts+++ b/apps/desktop/src/store/local-runtime-jobs.test.ts@@ -85,47 +85,6 @@ async function pollTick() {}describe('local runtime jobs store — pause/settle contract', () => {- it('running→paused settles NOTHING: no error toast, job stays visible', async () => {- backend.jobs = [job({ done_bytes: 40 })]- await pollTick()- expect(- (queryClient.getQueryData<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' }