hermes-agent/apps/desktop/electron/updater/state-db-preflight.test.ts
Hermes Agent e33fd7e09b fix(desktop): run updater state.db pre-flight through the installation launcher
PM-managed checkouts retire the in-tree `venv` once a generation is committed,
so `findPythonForRoot` returns null there and the desktop Update button refused
every hand-off with:

  state.db pre-flight failed: Python not found. Update cancelled before
  backend shutdown. Update the selected installation with its hermes update
  command, then retry.

The pre-flight was the only remaining update-path consumer of the checkout-venv
resolution — the source check (`readSourceUpdate`) and the hand-off script
(`scripts/desktop-update/runtime.ps1`) already resolve the installation
launcher for managed checkouts.

`preflightStateDb` now accepts the launcher and runs the emergency snapshot
through it (`--run-module hermes_cli.backup_sqlite`, mirroring the update
check), keeping the legacy `python -I -S <script>` shape for pre-PM installs
and the update check's fail-closed ComSpec wrapping for a `.cmd` launcher. The
composition resolves the launcher off the same `pm` marker as `readSourceUpdate`
and surfaces a repair message before the backend stops when it is missing.

Test: apps/desktop/electron/updater/state-db-preflight.test.ts gains a managed
case that drives the launcher shape end-to-end (shim launcher -> snapshot
published); the legacy-path cases are unchanged.
2026-09-27 01:16:32 -07:00

164 lines
4.7 KiB
TypeScript

import assert from 'node:assert/strict'
import { spawn, spawnSync } 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 { fileURLToPath } from 'node:url'
import { test } from 'vitest'
import { preflightStateDb } from './state-db-preflight'
test('the desktop preflight publishes committed WAL rows before its caller can stop the backend', async (): Promise<void> => {
const home: string = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-db-'))
const python: string = process.env.HERMES_PYTHON || 'python3'
const script: string = fileURLToPath(new URL('../../../../hermes_cli/backup_sqlite.py', import.meta.url))
const child = spawn(
python,
[
'-I',
'-S',
'-u',
'-c',
`
import sqlite3, sys
c = sqlite3.connect(sys.argv[1])
c.execute('PRAGMA journal_mode=WAL')
c.execute('PRAGMA wal_autocheckpoint=0')
c.execute('CREATE TABLE messages (body TEXT)')
c.commit()
c.execute('PRAGMA wal_checkpoint(TRUNCATE)')
c.execute("INSERT INTO messages VALUES ('pending in WAL')")
c.commit()
print('ready', flush=True)
sys.stdin.readline()
c.close()
`,
path.join(home, 'state.db')
],
{ stdio: ['pipe', 'pipe', 'pipe'] }
)
const logs: string[] = []
try {
await once(child.stdout!, 'data')
preflightStateDb({
python,
script,
home,
log: (message: string): void => {
logs.push(message)
}
})
assert.equal(child.exitCode, null)
const backups: string[] = fs.readdirSync(home).filter((name: string): boolean => name.endsWith('.bak'))
assert.equal(backups.length, 1, logs.join('\n'))
const verify = spawnSync(
python,
[
'-I',
'-S',
'-c',
`
import sqlite3, sys
with sqlite3.connect(sys.argv[1]) as c:
assert c.execute('SELECT body FROM messages').fetchall() == [('pending in WAL',)]
`,
path.join(home, backups[0]!)
],
{ encoding: 'utf8' }
)
assert.equal(verify.status, 0, verify.stderr)
const exited = once(child, 'exit')
child.stdin!.end('\n')
await exited
} finally {
if (child.exitCode === null && child.signalCode === null) {
child.kill('SIGKILL')
await once(child, 'exit')
}
fs.rmSync(home, { recursive: true, force: true })
}
})
test('a managed installation runs the snapshot through the installation launcher', (): void => {
const home: string = fs.mkdtempSync(path.join(os.tmpdir(), 'managed-preflight-'))
const shims: string = fs.mkdtempSync(path.join(os.tmpdir(), 'launcher-shim-'))
const python: string = process.env.HERMES_PYTHON || 'python3'
const script: string = fileURLToPath(new URL('../../../../hermes_cli/backup_sqlite.py', import.meta.url))
// Stand-in for the installation launcher under `.hermes/bin`: it must accept
// exactly what the runtime passes it — `--run-module hermes_cli.backup_sqlite
// <home>` — and publish the snapshot like the real launcher does.
const shim: string = path.join(shims, process.platform === 'win32' ? 'hermes.cmd' : 'hermes')
fs.writeFileSync(
shim,
process.platform === 'win32'
? `@echo off\r\n"${python}" -I -S "${script}" %3\r\n`
: `#!/bin/sh\nexec "${python}" -I -S "${script}" "$3"\n`
)
if (process.platform !== 'win32') {
fs.chmodSync(shim, 0o755)
}
const logs: string[] = []
try {
const created = spawnSync(
python,
[
'-I',
'-S',
'-c',
"import sqlite3, sys; c = sqlite3.connect(sys.argv[1]); c.execute('CREATE TABLE t (x)'); c.commit(); c.close()",
path.join(home, 'state.db')
],
{ encoding: 'utf8' }
)
assert.equal(created.status, 0, created.stderr)
preflightStateDb({
python: null,
launcher: shim,
script,
home,
log: (message: string): void => {
logs.push(message)
}
})
const backups: string[] = fs.readdirSync(home).filter((name: string): boolean => name.endsWith('.bak'))
assert.equal(backups.length, 1, logs.join('\n'))
} finally {
fs.rmSync(home, { recursive: true, force: true })
fs.rmSync(shims, { recursive: true, force: true })
}
})
test('an older selected checkout without the snapshot helper refuses before backend stop', (): void => {
const oldRoot: string = fs.mkdtempSync(path.join(os.tmpdir(), 'old-preflight-'))
let stopped = false
try {
assert.throws((): void => {
preflightStateDb({
python: process.env.HERMES_PYTHON || 'python3',
script: path.join(oldRoot, 'hermes_cli', 'backup_sqlite.py'),
home: oldRoot,
log: (): void => {}
})
stopped = true
}, /snapshot|pre-flight/)
assert.equal(stopped, false)
} finally {
fs.rmSync(oldRoot, { recursive: true, force: true })
}
})