Skip to content

The agent that grows with you

test(desktop): keep PM-clean update contracts

ethernet86f24e869ea6
diff --git a/apps/desktop/electron/gateway-stop-before-update.test.ts b/apps/desktop/electron/gateway-stop-before-update.test.ts
index 400addbd397..bf692971ff9 100644
--- a/apps/desktop/electron/gateway-stop-before-update.test.ts
+++ b/apps/desktop/electron/gateway-stop-before-update.test.ts
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
-import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gateway-stop-before-update'
+import { GATEWAY_STOP_TIMEOUT_MS, stopGatewayBeforeUpdate } from './gateway-stop-before-update'
const CLI = 'C:\\Users\\x\\hermes\\hermes-agent\\venv\\Scripts\\hermes.exe'
const HOME = 'C:\\Users\\x\\hermes'
@@ -75,33 +75,21 @@ test('Windows with failing CLI returns false (best-effort, never throws)', () =>
assert.equal(ran, false)
})
-test('abort-path counterpart invokes "gateway start --all" (drain-semantics restore)', () => {
- let seenArgs: string[] = []
-
- const ran = startGatewaysAfterUpdateAbort(CLI, {
+test('passes a generous timeout with hidden console (taskkill window suppression)', () => {
+ let seenOptions: unknown
+ stopGatewayBeforeUpdate(CLI, HOME, {
isWindows: true,
existsSync: () => true,
- execFileSync: ((_c: string, args: string[]) => {
- seenArgs = args
+ execFileSync: ((_c: string, _a: string[], options: unknown) => {
+ seenOptions = options
return Buffer.from('')
}) as never
})
-
- assert.equal(ran, true)
- assert.deepEqual(seenArgs, ['gateway', 'start', '--all'])
-})
-
-test('abort-path counterpart is a no-op off Windows', () => {
- const calls: Array<[string, string[]]> = []
-
- const ran = startGatewaysAfterUpdateAbort(CLI, {
- isWindows: false,
- existsSync: () => true,
- execFileSync: fakeExec(true) as never,
- spy: (c, a) => calls.push([c, a])
+ assert.deepEqual(seenOptions, {
+ timeout: GATEWAY_STOP_TIMEOUT_MS,
+ windowsHide: true,
+ stdio: 'ignore',
+ encoding: 'utf8'
})
-
- assert.equal(ran, false)
- assert.deepEqual(calls, [])
})
diff --git a/apps/desktop/electron/github-api-auth.test.ts b/apps/desktop/electron/github-api-auth.test.ts
deleted file mode 100644
index a441662097f..00000000000
--- a/apps/desktop/electron/github-api-auth.test.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-import assert from 'node:assert/strict'
-
-import { beforeEach, test } from 'vitest'
-
-import {
- findGhCli,
- forgetGhCliToken,
- GH_CLI_TIMEOUT_MS,
- githubApiHeaders,
- githubTokenFromEnv,
- githubTokenRejected,
- resolveGitHubCredential
-} from './github-api-auth'
-
-// The exact headers the anonymous update check sends today; the change must
-// leave this shape byte-identical when no token is configured.
-const UPDATE_CHECK_HEADERS = {
- Accept: 'application/vnd.github.sha',
- 'User-Agent': 'hermes-desktop-update-check'
-}
-
-beforeEach(() => {
- forgetGhCliToken()
-})
-
-/** execFile stand-in that records every spawn and answers with a scripted result. */
-function fakeExecFile(result: { error?: Error | null; stdout?: string }) {
- const calls: Array<{ file: string; args: string[]; options: Record<string, unknown> }> = []
- let stdinEnded = 0
-
- const execFileFn = ((file, args, options, callback) => {
- calls.push({ file, args, options })
- queueMicrotask(() => callback(result.error ?? null, result.stdout ?? '', ''))
-
- return {
- stdin: {
- end() {
- stdinEnded += 1
- }
- }
- }
- }) as any
-
- return { calls, execFileFn, stdinEnded: () => stdinEnded }
-}
-
-test('GITHUB_TOKEN wins over GH_TOKEN, blanks fall through, values are trimmed', () => {
- assert.equal(githubTokenFromEnv({ GITHUB_TOKEN: 'pat-a', GH_TOKEN: 'pat-b' }), 'pat-a')
- assert.equal(githubTokenFromEnv({ GITHUB_TOKEN: ' ', GH_TOKEN: ' pat-b ' }), 'pat-b')
- assert.equal(githubTokenFromEnv({ GITHUB_TOKEN: '', GH_TOKEN: '' }), null)
- assert.equal(githubTokenFromEnv({}), null)
-})
-
-test('anonymous sends no Authorization key at all; a token adds the `token` scheme without touching the base', () => {
- const anonymous = githubApiHeaders(UPDATE_CHECK_HEADERS, null)
-
- assert.deepEqual(anonymous, UPDATE_CHECK_HEADERS)
- assert.equal('Authorization' in anonymous, false)
-
- const authed = githubApiHeaders(UPDATE_CHECK_HEADERS, 'pat-a')
-
- assert.equal(authed.Authorization, 'token pat-a')
- assert.equal(authed['User-Agent'], 'hermes-desktop-update-check')
- // The caller's base object is a constant; mutating it would leak the token
- // into every later request that builds from it.
- assert.equal('Authorization' in UPDATE_CHECK_HEADERS, false)
-})
-
-test('only an authenticated 401 counts as the credential being rejected', () => {
- // The anonymous-retry gate: a stale GITHUB_TOKEN or gh login must fall back
- // to the anonymous request that worked before credentials were wired in.
- assert.equal(githubTokenRejected({ statusCode: 401, authenticated: true }), true)
- assert.equal(githubTokenRejected({ statusCode: 401, authenticated: false }), false)
- assert.equal(githubTokenRejected({ statusCode: 403, authenticated: true }), false)
- assert.equal(githubTokenRejected({ statusCode: 429, authenticated: true }), false)
- assert.equal(githubTokenRejected(null), false)
-})
-
-// #112615: a Finder/launcher-started app inherits /usr/bin:/bin:/usr/sbin:/sbin,
-// so `gh` from Homebrew (macOS) or the GitHub CLI installer (Windows) is
-// invisible on PATH — the rung must look where those installers put it.
-test('gh is found in the GUI-safe install locations a minimal launch PATH omits', () => {
- const brewGh = '/opt/homebrew/bin/gh'
- const macos = findGhCli({ PATH: '/usr/bin:/bin:/usr/sbin:/sbin' }, 'darwin', p => p === brewGh)
-
- assert.equal(macos, brewGh)
-
- const winGh = 'C:\\Program Files\\GitHub CLI\\gh.exe'
-
- const windows = findGhCli(
- { Path: 'C:\\Windows\\System32', ProgramFiles: 'C:\\Program Files' },
- 'win32',
- p => p === winGh
- )
-
- assert.equal(windows, winGh)
-
- // PATH still wins over the fallbacks when both have one.
- const pathGh = '/usr/local/bin/gh'
- const both = findGhCli({ PATH: '/usr/local/bin' }, 'darwin', p => p === pathGh || p === brewGh)
-
- assert.equal(both, pathGh)
- assert.equal(
- findGhCli({ PATH: '/usr/bin' }, 'linux', () => false),
- null
- )
-})
-
-test('gh rung: argv-only spawn, stdin closed, bounded, cached for the process, and after the env rung', async () => {
- const exists = (p: string) => p === '/opt/homebrew/bin/gh'
- const env = { PATH: '/usr/bin:/bin' }
- const logged = fakeExecFile({ stdout: 'gho_from_gh\n' })
-
- const first = await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: logged.execFileFn })
-
- assert.deepEqual(first, { token: 'gho_from_gh', source: 'gh-cli' })
- assert.equal(logged.calls.length, 1)
- assert.equal(logged.calls[0].file, '/opt/homebrew/bin/gh')
- assert.deepEqual(logged.calls[0].args, ['auth', 'token'])
- assert.equal(logged.calls[0].options.shell, undefined)
- assert.equal(logged.calls[0].options.windowsHide, true)
- assert.equal(logged.calls[0].options.timeout, GH_CLI_TIMEOUT_MS)
- assert.equal(logged.stdinEnded(), 1)
-
- // Process-lifetime cache: the second check does not spawn gh again.
- await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: logged.execFileFn })
- assert.equal(logged.calls.length, 1)
-
- // Env token outranks gh and never spawns it.
- forgetGhCliToken()
-
- const fromEnv = await resolveGitHubCredential({
- env: { ...env, GH_TOKEN: 'pat-env' },
- platform: 'darwin',
- exists,
- execFileFn: logged.execFileFn
- })
-
- assert.deepEqual(fromEnv, { token: 'pat-env', source: 'env' })
- assert.equal(logged.calls.length, 1)
-
- // Logged-out gh (exit 1, empty stdout) and a missing gh both mean anonymous.
- forgetGhCliToken()
- const loggedOut = fakeExecFile({ error: Object.assign(new Error('exit 1'), { code: 1 }), stdout: '' })
-
- assert.equal(
- await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: loggedOut.execFileFn }),
- null
- )
-
- // "none" is not cached: a `gh auth login` after launch is picked up by the next check without a restart.
- const nowLogged = fakeExecFile({ stdout: 'gho_after_login\n' })
-
- assert.deepEqual(
- await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: nowLogged.execFileFn }),
- {
- token: 'gho_after_login',
- source: 'gh-cli'
- }
- )
-
- forgetGhCliToken()
- assert.equal(
- await resolveGitHubCredential({ env, platform: 'darwin', exists: () => false, execFileFn: logged.execFileFn }),
- null
- )
- assert.equal(logged.calls.length, 1)
-})
diff --git a/apps/desktop/electron/update-api-check.test.ts b/apps/desktop/electron/update-api-check.test.ts
deleted file mode 100644
index aece7168c17..00000000000
--- a/apps/desktop/electron/update-api-check.test.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-/**
- * Tests for electron/update-api-check.ts — the API-first passive update check.
- *
- * Why this exists: every desktop client used to `git fetch` twice every 30
- * minutes. GitHub measured tens of millions of fetch/clone requests per day
- * from the install base and asked us to poll via the API instead. These pin
- * the two load-bearing contracts: the cache answers passive checks for a full
- * day but invalidates the moment HEAD moves, and the compare payload maps to
- * an honest behind count (never a fabricated one).
- */
-
-import assert from 'node:assert/strict'
-
-import { test } from 'vitest'
-
-import {
- branchTipApiUrl,
- cacheIsFresh,
- describeUpdateCheckFailure,
- githubRepoSlug,
- listLocalCommits,
- parseCompare,
- rateLimitFromHeaders,
- resolveBehindLocally,
- UPDATE_CHECK_FAILURE_TTL_MS,
- UPDATE_CHECK_TTL_MS
-} from './update-api-check'
-
-const SHA_A = 'a'.repeat(40)
-const SHA_B = 'b'.repeat(40)
-const HOUR = 60 * 60 * 1000
-
-test('cache serves a passive check for 24h, but not once HEAD or the branch changes', () => {
- const cached = { fetchedAt: 0, currentSha: SHA_A, branch: 'main', status: { behind: 0 } }
-
- assert.equal(cacheIsFresh(cached, { branch: 'main', currentSha: SHA_A, now: UPDATE_CHECK_TTL_MS - 1 }), true)
- assert.equal(cacheIsFresh(cached, { branch: 'main', currentSha: SHA_A, now: UPDATE_CHECK_TTL_MS }), false)
- // Applying an update moves HEAD: a stale "update available" must never survive it.
- assert.equal(cacheIsFresh(cached, { branch: 'main', currentSha: SHA_B, now: 1 }), false)
- assert.equal(cacheIsFresh(cached, { branch: 'bb/gui', currentSha: SHA_A, now: 1 }), false)
-
- // Failures retry sooner than successes, but still not on every tick.
- const failed = { ...cached, status: { error: 'fetch-failed' } }
- assert.equal(cacheIsFresh(failed, { branch: 'main', currentSha: SHA_A, now: UPDATE_CHECK_FAILURE_TTL_MS - 1 }), true)
- assert.equal(cacheIsFresh(failed, { branch: 'main', currentSha: SHA_A, now: 2 * HOUR }), false)
-})
-
-test('compare payload maps to the behind count and a newest-first commit list; malformed = null', () => {
- const payload = {
- ahead_by: 2,
- status: 'ahead',
- commits: [
- {
- sha: SHA_A,
- commit: { message: 'fix: older\n\nbody', author: { name: 'A' }, committer: { date: '2026-09-10T00:00:00Z' } }
- },
- {
- sha: SHA_B,
- commit: { message: 'feat: newer', author: { name: 'B' }, committer: { date: '2026-09-10T01:00:00Z' } }
- }
- ]
- }
-
- const parsed = parseCompare(payload)
- assert.equal(parsed?.behind, 2)
- assert.deepEqual(
- parsed?.commits.map(c => [c.sha, c.summary, c.author]),
- [
- [SHA_B, 'feat: newer', 'B'],
- [SHA_A, 'fix: older', 'A']
- ]
- )
-
- assert.equal(parseCompare({ ahead_by: -1 }), null)
- assert.equal(parseCompare({ status: 'ahead' }), null)
- assert.equal(parseCompare('nope'), null)
-
- // Forks and SSH forms hit the API for their own repo; non-GitHub origins don't.
- assert.equal(githubRepoSlug('[email protected]:Someone/hermes-agent.git'), 'someone/hermes-agent')
- assert.equal(githubRepoSlug('https://gitlab.example/x/y.git'), null)
- assert.equal(
- branchTipApiUrl('nousresearch/hermes-agent', 'bb/gui'),
- 'https://api.github.com/repos/nousresearch/hermes-agent/commits/bb%2Fgui'
- )
-})
-
-// #112615: behind a shared exit IP the anonymous 60/hour budget is spent by
-// neighbours, so "try again in an hour" is advice the user cannot act on. A
-// genuine rate limit (x-ratelimit-remaining: 0) must name the shared-address
-// cause, the real reset time and the GITHUB_TOKEN remedy; any other 403 must
-// not be reported as a rate limit.
-test('a rate-limited 403 names the reset time and GITHUB_TOKEN; a plain 403 is not a rate limit', () => {
- const now = 1_700_000_000_000
-
- const limited = {
- statusCode: 403,
- ...rateLimitFromHeaders({ 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': String(now / 1000 + 25 * 60) }),
- authenticated: false
- }
-
- const message = describeUpdateCheckFailure(limited, now)
-
- assert.match(message, /in about 25 minutes/)
- assert.match(message, /GITHUB_TOKEN/)
-
- assert.match(describeUpdateCheckFailure({ ...limited, authenticated: true }, now), /for your GITHUB_TOKEN/)
-
- // Missing or non-zero rate-limit headers: an ordinary 403, reported as such.
- assert.doesNotMatch(describeUpdateCheckFailure({ statusCode: 403 }), /GITHUB_TOKEN/)
- assert.doesNotMatch(
- describeUpdateCheckFailure({ statusCode: 403, ...rateLimitFromHeaders({ 'x-ratelimit-remaining': '57' }) }),
- /GITHUB_TOKEN/
- )
-})
-
-/**
- * Fake runGit keyed on the subcommand. Records every call so tests can pin
- * that a stale tip short-circuits before any graph walk.
- */
-function fakeGit(responses: Record<string, { code: number; stdout?: string }>) {
- const calls: string[][] = []
-
- return {
- calls,
- runGit: async (args: string[]) => {
- calls.push(args)
- const canned = responses[args[0]] ?? { code: 0 }
-
- return { code: canned.code, stdout: canned.stdout ?? '', stderr: '' }
- }
- }
-}
-
-test('resolveBehindLocally: unreachable tip is unknown, reachable tip is ahead, otherwise the real gap', async () => {
- // A tip missing from the object database (truly stale checkout) stays unknown.
- const stale = fakeGit({ 'cat-file': { code: 1 } })
- assert.equal(await resolveBehindLocally(stale.runGit, '/repo', SHA_A, SHA_B), null)
- assert.deepEqual(
- stale.calls.map(args => args[0]),
- ['cat-file']
- )
-
- // The remote tip reachable from HEAD is a local commit AHEAD, not an update.
- const ahead = fakeGit({})
- assert.equal(await resolveBehindLocally(ahead.runGit, '/repo', SHA_A, SHA_B), 0)
- assert.deepEqual(
- ahead.calls.map(args => args[0]),
- ['cat-file', 'merge-base']
- )
-
- // Otherwise the honest local count of HEAD..tip (merge-base must fail first).
- const behind = fakeGit({ 'merge-base': { code: 1 }, 'rev-list': { code: 0, stdout: '3\n' } })
- assert.equal(await resolveBehindLocally(behind.runGit, '/repo', SHA_A, SHA_B), 3)
- assert.deepEqual(
- behind.calls.map(args => args[0]),
- ['cat-file', 'merge-base', 'rev-list']
- )
-
- // A git failure mid-walk is never silently read as zero.
- const broken = fakeGit({ 'merge-base': { code: 1 }, 'rev-list': { code: 128 } })
- assert.equal(await resolveBehindLocally(broken.runGit, '/repo', SHA_A, SHA_B), null)
-})
-
-test('listLocalCommits renders the local gap newest-first in the parseCompare shape', async () => {
- const OLDEST = '1'.repeat(40)
- const NEWEST = '2'.repeat(40)
-
- const gitLog = fakeGit({
- log: {
- code: 0,
- stdout: [
- [OLDEST, 'Old Hand', '2026-09-10T00:00:00+00:00', 'fix: older'].join('\x1f'),
- [NEWEST, 'New Face', '2026-09-11T00:00:00+00:00', 'feat: newer'].join('\x1f'),
- ''
- ].join('\n')
- }
- })
-
- const commits = await listLocalCommits(gitLog.runGit, '/repo', SHA_A, SHA_B)
- assert.deepEqual(
- commits.map(c => [c.sha, c.summary, c.author]),
- [
- [NEWEST, 'feat: newer', 'New Face'],
- [OLDEST, 'fix: older', 'Old Hand']
- ]
- )
- assert.equal(commits[0].at, Date.parse('2026-09-11T00:00:00+00:00'))
-
- // A failed log renders as "no listed commits", never a fabricated list.
- const failed = fakeGit({ log: { code: 128 } })
- assert.deepEqual(await listLocalCommits(failed.runGit, '/repo', SHA_A, SHA_B), [])
-})
diff --git a/apps/desktop/electron/venv-blocker-scan.test.ts b/apps/desktop/electron/venv-blocker-scan.test.ts
deleted file mode 100644
index e7ed1667de4..00000000000
--- a/apps/desktop/electron/venv-blocker-scan.test.ts
+++ /dev/null
@@ -1,408 +0,0 @@
-'use strict'
-
-/**
- * Tests for apps/desktop/electron/venv-blocker-scan.ts
- *
- * Run with: npx vitest run electron/venv-blocker-scan.test.ts
- * (from apps/desktop; wired into npm test:desktop:platforms)
- */
-
-import assert from 'node:assert/strict'
-import fs from 'node:fs'
-import os from 'node:os'
-import path from 'node:path'
-
-import { describe, it } from 'vitest'
-
-import {
- formatBlockerMessage,
- formatProbeFailedMessage,
- parseVenvBlockerScanOutput,
- resolveVenvDir,
- resolveVenvPython,
- scanVenvBlockers,
- stopSafeVenvBlockers
-} from './venv-blocker-scan'
-
-// ---------------------------------------------------------------------------
-// resolveVenvPython
-// ---------------------------------------------------------------------------
-
-describe('resolveVenvPython', () => {
- it('returns a real path when a temp venv python file exists', () => {
- const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-vt-'))
-
- try {
- const scriptsDir = process.platform === 'win32' ? 'Scripts' : 'bin'
- const pythonName = process.platform === 'win32' ? 'python.exe' : 'python3'
- const dir = path.join(sandbox, 'venv', scriptsDir)
- fs.mkdirSync(dir, { recursive: true })
- const pyPath = path.join(dir, pythonName)
- fs.writeFileSync(pyPath, '', { mode: 0o755 })
- assert.equal(resolveVenvPython(sandbox), pyPath)
- } finally {
- fs.rmSync(sandbox, { recursive: true, force: true })
- }
- })
-
- it('resolves a uv-default .venv python when legacy venv is absent', () => {
- const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-vt-'))
-
- try {
- const scriptsDir = process.platform === 'win32' ? 'Scripts' : 'bin'
- const pythonName = process.platform === 'win32' ? 'python.exe' : 'python3'
- const dir = path.join(sandbox, '.venv', scriptsDir)
- fs.mkdirSync(dir, { recursive: true })
- const pyPath = path.join(dir, pythonName)
- fs.writeFileSync(pyPath, '', { mode: 0o755 })
- assert.equal(resolveVenvPython(sandbox), pyPath)
- } finally {
- fs.rmSync(sandbox, { recursive: true, force: true })
- }
- })
-
- it('keeps legacy venv precedence when both supported layouts exist', () => {
- const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-vt-'))
-
- try {
- fs.mkdirSync(path.join(sandbox, 'venv'), { recursive: true })
- fs.mkdirSync(path.join(sandbox, '.venv'), { recursive: true })
- assert.equal(resolveVenvDir(sandbox), path.join(sandbox, 'venv'))
- } finally {
- fs.rmSync(sandbox, { recursive: true, force: true })
- }
- })
-
- it('returns null for non-existent venv', () => {
- assert.equal(resolveVenvPython('/nonexistent'), null)
- })
-})
-
-// ---------------------------------------------------------------------------
-// formatBlockerMessage / formatProbeFailedMessage
-// ---------------------------------------------------------------------------
-
-describe('formatBlockerMessage', () => {
- it('includes PID, name and cmdline of each blocker', () => {
- const msg = formatBlockerMessage({
- blocked: true,
- processes: [{ pid: 101, name: 'python.exe', cmdline: 'serve --host 10.0.0.1', kind: 'other', safeToStop: false }]
- })
-
- assert.ok(msg.includes('PID 101'))
- assert.ok(msg.includes('python.exe'))
- assert.ok(msg.includes('serve'))
- })
-})
-
-describe('formatProbeFailedMessage', () => {
- it('carries the probe failure detail', () => {
- const msg = formatProbeFailedMessage('timed out after 60 seconds')
- assert.ok(msg.includes('timed out after 60 seconds'))
- })
-})
-
-// ---------------------------------------------------------------------------
-// parseVenvBlockerScanOutput — pure function
-// ---------------------------------------------------------------------------
-
-describe('parseVenvBlockerScanOutput', () => {
- const ok = (over: any = {}) => JSON.stringify({ ok: true, blocked: false, processes: [], ...over })
-
- it('valid clear', () => {
- const o = parseVenvBlockerScanOutput(ok())
- assert.equal(o.kind, 'clear')
- })
-
- it('valid blocked', () => {
- const o = parseVenvBlockerScanOutput(
- ok({
- blocked: true,
- processes: [{ pid: 1, name: 'p', cmdline: 'c' }]
- })
- )
-
- assert.equal(o.kind, 'blocked')
- })
-
- // Contract fixture (#98336/#98350): the scanner reports exemption
- // diagnostics (counts + sanitized evidence) alongside the authoritative
- // blocked/processes fields. The consumer must tolerate those fields today
- // and must keep enforcing blocked/processes consistency — a future parser
- // change that either chokes on the diagnostics or silently reinterprets
- // an exemption as a blocker breaks this fixture.
- it('tolerates exemption diagnostics while enforcing blocked/processes consistency', () => {
- const clear = parseVenvBlockerScanOutput(
- ok({
- pausable_gateways: 2,
- deferred_backends: 1,
- deferred_backend_evidence: [{ pid: 78, purpose: 'serve', port: 9119 }]
- })
- )
-
- assert.equal(clear.kind, 'clear')
-
- const blocked = parseVenvBlockerScanOutput(
- ok({
- blocked: true,
- processes: [{ pid: 79, name: 'python.exe', cmdline: 'c' }],
- pausable_gateways: 1,
- deferred_backends: 1,
- deferred_backend_evidence: [{ pid: 78, purpose: 'serve', port: 9119 }]
- })
- )
-
- assert.equal(blocked.kind, 'blocked')
-
- if (blocked.kind !== 'blocked') {
- return
- }
-
- assert.deepEqual(
- blocked.result.processes.map(p => p.pid),
- [79]
- )
- })
-
- it('classifies Python http.server blockers as safe local previews with a human label', () => {
- const o = parseVenvBlockerScanOutput(
- ok({
- blocked: true,
- processes: [
- {
- pid: 47484,
- name: 'python.exe',
- cmdline: 'C:\\Hermes\\venv\\Scripts\\python.exe -m http.server 8766 --directory C',
- kind: 'local-preview',
- safeToStop: true,
- label: 'Example Preview',
- port: 8766,
- createTime: 1722798000.25
- }
- ]
- })
- )
-
- assert.equal(o.kind, 'blocked')
-
- if (o.kind !== 'blocked') {
- return
- }
-
- assert.deepEqual(o.result.processes[0], {
- pid: 47484,
- name: 'python.exe',
- cmdline: 'C:\\Hermes\\venv\\Scripts\\python.exe -m http.server 8766 --directory C',
- kind: 'local-preview',
- safeToStop: true,
- label: 'Example Preview',
- port: 8766,
- createTime: 1722798000.25
- })
- })
-
- it('does not trust a truncated http.server command line without scanner identity metadata', () => {
- const o = parseVenvBlockerScanOutput(
- ok({
- blocked: true,
- processes: [
- {
- pid: 47484,
- name: 'python.exe',
- cmdline: 'python.exe -m http.server 8766 --directory C'
- }
- ]
- })
- )
-
- assert.equal(o.kind, 'blocked')
-
- if (o.kind !== 'blocked') {
- return
- }
-
- assert.equal(o.result.processes[0]?.kind, 'other')
- assert.equal(o.result.processes[0]?.safeToStop, false)
- })
-
- it('never marks an arbitrary Python process safe to stop', () => {
- const o = parseVenvBlockerScanOutput(
- ok({
- blocked: true,
- processes: [{ pid: 9, name: 'python.exe', cmdline: 'python.exe important-script.py' }]
- })
- )
-
- assert.equal(o.kind, 'blocked')
-
- if (o.kind !== 'blocked') {
- return
- }
-
- assert.equal(o.result.processes[0]?.kind, 'other')
- assert.equal(o.result.processes[0]?.safeToStop, false)
- })
-
- it('malformed JSON', () => {
- assert.equal(parseVenvBlockerScanOutput('not json').kind, 'probe-failure')
- })
-
- it('ok=false is rejected', () => {
- assert.equal(
- parseVenvBlockerScanOutput(JSON.stringify({ ok: false, blocked: false, processes: [] })).kind,
- 'probe-failure'
- )
- })
-
- it('blocked must be boolean', () => {
- assert.equal(parseVenvBlockerScanOutput(ok({ blocked: 'false' })).kind, 'probe-failure')
- })
-
- it('blocked=true with empty processes rejected', () => {
- assert.equal(parseVenvBlockerScanOutput(ok({ blocked: true, processes: [] })).kind, 'probe-failure')
- })
-
- it('blocked=false with non-empty processes rejected', () => {
- assert.equal(
- parseVenvBlockerScanOutput(ok({ processes: [{ pid: 1, name: 'p', cmdline: 'c' }] })).kind,
- 'probe-failure'
- )
- })
-
- it('process pid must be positive integer', () => {
- assert.equal(
- parseVenvBlockerScanOutput(ok({ blocked: true, processes: [{ pid: 0, name: 'p', cmdline: 'c' }] })).kind,
- 'probe-failure'
- )
- })
-
- it('process name must be non-empty string', () => {
- assert.equal(
- parseVenvBlockerScanOutput(ok({ blocked: true, processes: [{ pid: 1, name: '', cmdline: 'c' }] })).kind,
- 'probe-failure'
- )
- })
-
- it('process missing cmdline is rejected', () => {
- assert.equal(
- parseVenvBlockerScanOutput(ok({ blocked: true, processes: [{ pid: 1, name: 'p' }] })).kind,
- 'probe-failure'
- )
- })
-})
-
-// ---------------------------------------------------------------------------
-// scanVenvBlockers — subprocess with injection
-// ---------------------------------------------------------------------------
-
-describe('scanVenvBlockers', () => {
- const stubVenv = () => '/fake/venv/python.exe'
- const okJson = JSON.stringify({ ok: true, blocked: false, processes: [] })
-
- const blockedJson = JSON.stringify({
- ok: true,
- blocked: true,
- processes: [{ pid: 1, name: 'p', cmdline: 'c' }]
- })
-
- function execReturn(json: string): any {
- return (async (...args: any[]) => ({ stdout: json, stderr: '' })) as any
- }
-
- function execThrow(status: number, stderr: string): any {
- return (async (...args: any[]) => {
- const e: any = new Error()
- e.status = status
- e.stderr = Buffer.from(stderr)
- throw e
- }) as any
- }
-
- function execTimeout(): any {
- return (async (...args: any[]) => {
- const e: any = new Error()
- e.killed = true
- e.signal = 'SIGTERM'
- throw e
- }) as any
- }
-
- it('clear scan returns clear', async () => {
- assert.equal((await scanVenvBlockers('/r', execReturn(okJson), stubVenv)).kind, 'clear')
- })
-
- it('blocked scan returns blocked', async () => {
- assert.equal((await scanVenvBlockers('/r', execReturn(blockedJson), stubVenv)).kind, 'blocked')
- })
-
- it('non-zero exit is probe-failure', async () => {
- const o = await scanVenvBlockers('/r', execThrow(2, 'ModuleNotFoundError'), stubVenv)
- assert.equal(o.kind, 'probe-failure')
- })
-
- it('reports a timed-out subprocess explicitly', async () => {
- const o = await scanVenvBlockers('/r', execTimeout(), stubVenv)
- assert.deepEqual(o, {
- kind: 'probe-failure',
- error: 'timed out after 60 seconds'
- })
- })
-
- it('missing venv python is probe-failure', async () => {
- const o = await scanVenvBlockers('/r', execReturn(okJson), () => null)
- assert.equal(o.kind, 'probe-failure')
- })
-
- it('malformed subprocess output is probe-failure', async () => {
- const o = await scanVenvBlockers('/r', execReturn('bad json'), stubVenv)
- assert.equal(o.kind, 'probe-failure')
- })
-})
-
-describe('stopSafeVenvBlockers', () => {
- it('stops only blockers explicitly classified as safe local previews', async () => {
- const calls: Array<{ command: string; args: string[] }> = []
-
- const exec = (async (command: string, args: string[]) => {
- calls.push({ command, args })
-
- return { stdout: '', stderr: '' }
- }) as any
-
- const outcome = await stopSafeVenvBlockers(
- '/update/root',
- {
- blocked: true,
- processes: [
- {
- pid: 47484,
- name: 'python.exe',
- cmdline: 'python.exe -m http.server 8766 --directory C:\\preview',
- kind: 'local-preview',
- safeToStop: true,
- label: 'preview',
- port: 8766,
- createTime: 1722798000.25
- },
- {
- pid: 99,
- name: 'python.exe',
- cmdline: 'python.exe important-script.py',
- kind: 'other',
- safeToStop: false
- }
- ]
- },
- exec,
- () => 'C:\\Hermes\\venv\\Scripts\\python.exe'
- )
-
- assert.deepEqual(calls, [
- {
- command: 'C:\\Hermes\\venv\\Scripts\\python.exe',
- args: ['-m', 'hermes_cli._scan_venv_blockers', '--terminate-safe', '47484', '1722798000.25']
- }
- ])
- assert.deepEqual(outcome, { stopped: [47484], failed: [] })
- })
-})
diff --git a/apps/desktop/src/app/updates-overlay.blockers.test.tsx b/apps/desktop/src/app/updates-overlay.blockers.test.tsx
deleted file mode 100644
index cb85f4e2960..00000000000
--- a/apps/desktop/src/app/updates-overlay.blockers.test.tsx
+++ /dev/null
@@ -1,183 +0,0 @@
-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-
-import { Dialog, DialogContent } from '@/components/ui/dialog'
-import type { DesktopUpdateStatus } from '@/global'
-import { I18nProvider } from '@/i18n/context'
-import {
- $updateApply,
- $updateOverlayOpen,
- $updateOverlayTarget,
- $updateStatus,
- resetUpdateApplyState
-} from '@/store/updates'
-
-import { BlockerView, formatBlockerCommandLine, UpdatesOverlay } from './updates-overlay'
-
-async function renderWithI18n(ui: React.ReactNode) {
- await act(async () => {
- render(
- <I18nProvider configClient={{ getConfig: async () => ({}), saveConfig: async () => ({ ok: true }) }}>
- <Dialog open>
- <DialogContent>{ui}</DialogContent>
- </Dialog>
- </I18nProvider>
- )
- })
-}
-
-async function renderUpdatesOverlay() {
- await act(async () => {
- render(
- <I18nProvider configClient={{ getConfig: async () => ({}), saveConfig: async () => ({ ok: true }) }}>
- <UpdatesOverlay />
- </I18nProvider>
- )
- })
-}
-
-describe('formatBlockerCommandLine', () => {
- it('redacts the full ambiguous tail after a sensitive CLI, environment, or header marker', () => {
- const secretParts = ['first-part', 'second-part']
- const secret = secretParts.join(' ')
-
- const commands = [
- `python.exe watcher.py --token ${secret} --mode inspect`,
- ['python.exe watcher.py --password="', secret, '" --mode inspect'].join(''),
- `AUTH_TOKEN=${secret} python.exe watcher.py --mode inspect`,
- `python.exe watcher.py Authorization: Bearer ${secret} --mode inspect`
- ]
-
- for (const commandLine of commands) {
- const formatted = formatBlockerCommandLine(commandLine)
-
- expect(formatted).not.toContain(secretParts[0])
- expect(formatted).not.toContain(secretParts[1])
- expect(formatted).not.toContain('--mode inspect')
- expect(formatted.endsWith('[REDACTED]')).toBe(true)
- }
- })
-
- it('redacts a sensitive query value and bounds the remaining diagnostic output', () => {
- const queryValue = ['private', 'value'].join('-')
-
- const commandLine =
- `python.exe watcher.py https://example.test/?api_key=${queryValue}&mode=inspect ` + 'x'.repeat(600)
-
- const formatted = formatBlockerCommandLine(commandLine)
-
- expect(formatted).not.toContain(queryValue)
- expect(formatted).toContain('api_key=[REDACTED]&mode=inspect')
- expect(Array.from(formatted).length).toBeLessThanOrEqual(500)
- expect(formatted.endsWith('…')).toBe(true)
- })
-})
-
-describe('BlockerView', () => {
- afterEach(() => {
- cleanup()
- $updateOverlayOpen.set(false)
- $updateOverlayTarget.set('client')
- $updateStatus.set(null)
- resetUpdateApplyState()
- })
-
- it('uses the blocker view for a foreign process instead of the generic update error', async () => {
- $updateOverlayTarget.set('client')
- $updateOverlayOpen.set(true)
- $updateStatus.set({
- supported: true,
- updateAvailable: true,
- behind: 1,
- commits: []
- } as DesktopUpdateStatus)
- $updateApply.set({
- applying: false,
- stage: 'error',
- message: 'Update aborted: another Hermes process is using this installation.',
- percent: null,
- error: 'venv-blocked',
- command: null,
- blockers: [
- {
- pid: 58636,
- name: 'python.exe',
- cmdline: 'python.exe fenbi_session_refresh.py',
- kind: 'other',
- safeToStop: false
- }
- ],
- log: []
- })
-
- await renderUpdatesOverlay()
-
- expect(screen.getByText('Close other processes to update Hermes')).toBeTruthy()
- expect(screen.getByText('python.exe')).toBeTruthy()
- expect(screen.queryByText('Update didn’t finish')).toBeNull()
- })
-
- it('identifies foreign blockers without offering automatic termination', async () => {
- const onStopAndUpdate = vi.fn()
-
- await renderWithI18n(
- <BlockerView
- blockers={[
- {
- pid: 58636,
- name: 'python.exe',
- cmdline: 'python.exe fenbi_session_refresh.py',
- kind: 'other',
- safeToStop: false
- }
- ]}
- onDismiss={() => {}}
- onStopAndUpdate={onStopAndUpdate}
- />
- )
-
- expect(screen.getByText('Close other processes to update Hermes')).toBeTruthy()
- expect(screen.getByText('python.exe')).toBeTruthy()
- expect(screen.getByText('PID 58636')).toBeTruthy()
- expect(screen.getByText(/can’t safely close these processes automatically/i)).toBeTruthy()
- expect(screen.getByText(/python.exe fenbi_session_refresh\.py/i)).toBeTruthy()
- expect(screen.queryByRole('button', { name: /close previews/i })).toBeNull()
- expect(onStopAndUpdate).not.toHaveBeenCalled()
- })
-
- it('keeps mixed blocker cleanup limited to safe previews', async () => {
- const onStopAndUpdate = vi.fn()
-
- await renderWithI18n(
- <BlockerView
- blockers={[
- {
- pid: 47484,
- name: 'python.exe',
- cmdline: 'python.exe -m http.server 8766',
- kind: 'local-preview',
- safeToStop: true,
- label: 'Example Preview',
- port: 8766
- },
- {
- pid: 58636,
- name: 'python.exe',
- cmdline: 'python.exe fenbi_session_refresh.py',
- kind: 'other',
- safeToStop: false
- }
- ]}
- onDismiss={() => {}}
- onStopAndUpdate={onStopAndUpdate}
- />
- )
-
- expect(screen.getByText(/can close the local previews listed below/i)).toBeTruthy()
- expect(screen.getByText('Example Preview')).toBeTruthy()
- expect(screen.getByText('python.exe')).toBeTruthy()
-
- fireEvent.click(screen.getByRole('button', { name: 'Close previews and check again' }))
- expect(onStopAndUpdate).toHaveBeenCalledTimes(1)
- })
-})