Skip to content

The agent that grows with you

test(desktop-smoke): bind ledger-attached backends to their own evidence

Teknium1946a105b25a
diff --git a/tests-js/scripts/desktop-smoke-process.ts b/tests-js/scripts/desktop-smoke-process.ts
index ae24965e34d..33f84997b92 100644
--- a/tests-js/scripts/desktop-smoke-process.ts
+++ b/tests-js/scripts/desktop-smoke-process.ts
@@ -1,10 +1,12 @@
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
+import os from 'node:os'
import path from 'node:path'
import { z } from 'zod'
-import { parseSpawnLedger } from '../../apps/desktop/electron/backend-discovery.ts'
+import { parseSpawnLedger, SPAWN_LEDGER_FILENAME } from '../../apps/desktop/electron/backend-discovery.ts'
+import { resolveDesktopHermesHome } from '../../apps/desktop/electron/data-paths.mjs'
import { within } from '../../tests/install/e2e-assets/smoke-env.mjs'
export interface NativeProcess {
@@ -141,6 +143,40 @@ function linuxListeningPid(port: number, candidates: NativeProcess[]): number[]
}).map((candidate: NativeProcess): number => candidate.pid)
}
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
+
+/** Epoch seconds a live process started (psutil's `create_time` basis), or null when unreadable. */
+function processStartTime(pid: number): number | null {
+ try {
+ if (process.platform === 'linux') {
+ // psutil: boot time + field 22 (starttime, clock ticks), read after the `(comm)` field.
+ const fields = fs.readFileSync(`/proc/${pid}/stat`, 'utf8').split(')').pop()!.trim().split(/\s+/)
+ const bootTime = Number(/^btime\s+(\d+)$/m.exec(fs.readFileSync('/proc/stat', 'utf8'))?.[1])
+ const ticks = Number(nativeText('getconf', ['CLK_TCK']))
+
+ return bootTime + Number(fields[19]) / ticks
+ }
+
+ if (process.platform === 'darwin') {
+ // `Sun Oct 4 15:20:01 2026`, local time, whole seconds.
+ const lstart = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='],
+ { encoding: 'utf8', timeout: 30_000, env: { ...process.env, LC_ALL: 'C' }, stdio: ['ignore', 'pipe', 'pipe'] }).trim()
+
+ const match = /^\w{3}\s+(\w{3})\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d{4})$/.exec(lstart)
+
+ return match ? new Date(Number(match[6]), MONTHS.indexOf(match[1]), Number(match[2]), Number(match[3]),
+ Number(match[4]), Number(match[5])).getTime() / 1000 : null
+ }
+
+ const ms = nativeText('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
+ `([DateTimeOffset](Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}' -ErrorAction Stop).CreationDate).ToUnixTimeMilliseconds()`])
+
+ return /^\d+$/.test(ms) ? Number(ms) / 1000 : null
+ } catch {
+ return null
+ }
+}
+
/** Identify the actual listener, not a healthy helper or a command recorded before spawn. */
export function localBackendProcess(port: number, electronPid: number, hermesHome?: string): NativeProcess {
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
@@ -156,9 +192,27 @@ export function localBackendProcess(port: number, electronPid: number, hermesHom
let registered: number[] = []
if (hermesHome) {
+ // The product writes one machine-root ledger for every profile, and the app
+ // reads it at its own resolved root (`main.ts` -> `spawnLedgerPath(HERMES_HOME)`,
+ // where a `<root>/profiles/<name>` home resolves to `<root>`).
+ const ledgerRoot = resolveDesktopHermesHome({ home: os.homedir(), env: { HERMES_HOME: hermesHome } })
+
try {
- registered = parseSpawnLedger(fs.readFileSync(path.join(hermesHome, 'spawn-ledger.json'), 'utf8'))
- .filter(record => record.port === port).map(record => record.pid)
+ registered = parseSpawnLedger(fs.readFileSync(path.join(ledgerRoot, SPAWN_LEDGER_FILENAME), 'utf8'))
+ .filter(record => record.port === port && processes.some(candidate => candidate.pid === record.pid))
+ // A record names a (pid, create_time) incarnation; a reused PID is a different
+ // process. Same 2 s tolerance as the product's `_same_incarnation`; a record
+ // without a create_time (no psutil) carries only its PID, as in the product.
+ .filter((record) => {
+ if (record.createTime === null) {
+ return true
+ }
+
+ const started = processStartTime(record.pid)
+
+ return started !== null && Math.abs(started - record.createTime) < 2
+ })
+ .map(record => record.pid)
} catch { /* Missing/unreadable ledger provides no attachment evidence. */ }
}
@@ -271,15 +325,16 @@ export function assertBackendOrigin(backend: NativeProcess, root: string, origin
// Some platforms expose no way to read another process's environment or cwd, so a
// module-launched backend there can never name its tree in argv (Windows: the venv
- // launcher hands the interpreter over as a system python). The listener has already
- // been tied to the app process that owns it, and the caller has already asserted the
- // root that app reported resolving, so those two facts together are the evidence.
- // Requiring the process evidence to be absent keeps this from loosening a platform
- // that can read one.
+ // launcher hands the interpreter over as a system python). When the listener is a
+ // descendant of the app, and the caller has already asserted the root that app
+ // reported resolving, those two facts together are the evidence. A ledger-registered
+ // host backend is not tied to this app by ancestry, so the app's report says nothing
+ // about it; it must carry its own argv/env/cwd evidence. Requiring the process
+ // evidence to be absent keeps this from loosening a platform that can read one.
const processEvidenceUnreadable = backend.cwd === undefined
&& backend.pythonPath === undefined && backend.virtualEnv === undefined
- const appOwnsBackend = processEvidenceUnreadable
+ const appOwnsBackend = processEvidenceUnreadable && backend.ownership !== 'host-ledger'
&& evidence.appReportedRoot !== undefined && sameTree(evidence.appReportedRoot)
if (!sameTree(backend.cwd) && !namesInstallRoot && !usesInstallEnvironment && !appOwnsBackend) {
diff --git a/tests-js/scripts/desktop-smoke.test.ts b/tests-js/scripts/desktop-smoke.test.ts
index a74533f51a3..abc5d532785 100644
--- a/tests-js/scripts/desktop-smoke.test.ts
+++ b/tests-js/scripts/desktop-smoke.test.ts
@@ -185,6 +185,38 @@ test.runIf(process.platform === 'linux' || process.platform === 'darwin')('a sha
}
})
+test.runIf(process.platform === 'linux' || process.platform === 'darwin')('a host ledger record proves only its own incarnation, read at the machine root', async (): Promise<void> => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-host-root-'))
+ // A profile home: the product writes the ledger at the machine root above it.
+ const home = path.join(root, 'profiles', 'work')
+ fs.mkdirSync(home, { recursive: true })
+ const spawnedAt = Date.now() / 1000
+ const child = spawn(process.execPath, ['-e', 'const s=require("node:net").createServer();s.listen(0,"127.0.0.1",()=>console.log(s.address().port))'], { stdio: ['ignore', 'pipe', 'pipe'] })
+
+ try {
+ const port = await new Promise<number>((resolve, reject): void => {
+ child.once('error', reject)
+ child.stdout.once('data', (data: Buffer): void => resolve(Number(data.toString().trim())))
+ })
+
+ const record = { pid: child.pid, purpose: 'serve', host: '127.0.0.1', port, create_time: spawnedAt }
+ // The profile directory is not where the product writes the ledger.
+ fs.writeFileSync(path.join(home, 'spawn-ledger.json'), JSON.stringify([record]))
+ expect(() => localBackendProcess(port, child.pid!, home)).toThrow('found 0')
+ fs.rmSync(path.join(home, 'spawn-ledger.json'))
+ const ledger = path.join(root, 'spawn-ledger.json')
+ // A stale record whose PID now names a different process (reused PID) is no evidence.
+ fs.writeFileSync(ledger, JSON.stringify([{ ...record, create_time: spawnedAt - 3600 }]))
+ expect(() => localBackendProcess(port, child.pid!, home)).toThrow('found 0')
+ fs.writeFileSync(ledger, JSON.stringify([record]))
+ expect(localBackendProcess(port, child.pid!, home).ownership).toBe('host-ledger')
+ } finally {
+ child.kill()
+ await new Promise<void>((resolve): void => { child.once('exit', (): void => resolve()) })
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
test('a backend bound to the tree by environment needs no root in argv', (): void => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-env-origin-'))
@@ -255,6 +287,14 @@ test('a platform that cannot read the backend environment proves ownership by th
expect((): void => {
assertBackendOrigin({ ...backend, cwd: other, pythonPath: other }, root, 'source', { appReportedRoot: root })
}).toThrow('source tree')
+ // A ledger-registered host backend is not tied to this app by ancestry, so the
+ // app's report is no evidence for it: it needs its own argv/env evidence.
+ expect((): void => {
+ assertBackendOrigin({ ...backend, ownership: 'host-ledger' }, root, 'source', { appReportedRoot: root })
+ }).toThrow('source tree')
+ expect((): void => {
+ assertBackendOrigin({ ...backend, ownership: 'child' }, root, 'source', { appReportedRoot: root })
+ }).not.toThrow()
} finally { fs.rmSync(home, { recursive: true, force: true }) }
})
diff --git a/tests/install/e2e-assets/desktop-smoke.ts b/tests/install/e2e-assets/desktop-smoke.ts
index 741c8f2d7cd..391002a646c 100644
--- a/tests/install/e2e-assets/desktop-smoke.ts
+++ b/tests/install/e2e-assets/desktop-smoke.ts
@@ -330,13 +330,14 @@ export async function runInstalledDesktopSmoke(options: SmokeOptions, launchApp:
}
}
// The ordinary host-attach path may reuse the updater's relaunched app's
- // backend. Observe its ledger in the same isolated home, not an arbitrary
- // listener, and retain the OS listener + installed-tree proof below.
+ // backend. Observe the ledger the app reads for this home (its machine root),
+ // not an arbitrary listener, and retain the OS listener + installed-tree proof below.
fs.writeFileSync(path.join(out, `desktop-backend-${options.phase}.log`), connection.logs.map(redact).join('\n'))
const backend = localBackendProcess(Number(base.port), running.pid, predictedHome ?? options.home)
- // `identity.hermesRoot` was asserted against options.root above, and the listener was
- // tied to this app process when it was identified, so on a platform that cannot read
- // the backend's own environment those two facts are the available evidence.
+ // `identity.hermesRoot` was asserted against options.root above. For a listener that
+ // descends from this app process, on a platform that cannot read the backend's own
+ // environment, those two facts are the available evidence; a ledger-attached host
+ // backend is not tied to the app by ancestry and must prove its tree itself.
assertBackendOrigin(backend, options.root, options.origin, { appReportedRoot: identity.hermesRoot })
const provenanceCommit = readInstallationCommit(options.root, options.origin)
if (provenanceCommit !== options['expect-commit']) { throw new Error('Installed commit differs from --expect-commit') }