Skip to content

The agent that grows with you

test: recognize shared host backends in desktop update smoke

Teknium35d0cb86e0cc
diff --git a/tests-js/scripts/desktop-smoke-process.ts b/tests-js/scripts/desktop-smoke-process.ts
index d5dc632b921..d8600805cbf 100644
--- a/tests-js/scripts/desktop-smoke-process.ts
+++ b/tests-js/scripts/desktop-smoke-process.ts
@@ -4,6 +4,8 @@ import path from 'node:path'
import { z } from 'zod'
+import { parseSpawnLedger } from '../../apps/desktop/electron/backend-discovery.ts'
+
import { within } from '../../tests/install/e2e-assets/smoke-env.mjs'
export interface NativeProcess {
@@ -11,6 +13,7 @@ export interface NativeProcess {
parentPid: number
executable: string
command: string
+ ownership?: 'child' | 'host-ledger'
sourceRoot?: string
// The app binds its backend to a tree by environment, not only by argv: the
// installation root leads PYTHONPATH and VIRTUAL_ENV names the venv. Only the
@@ -140,12 +143,25 @@ function linuxListeningPid(port: number, candidates: NativeProcess[]): number[]
}
/** Identify the actual listener, not a healthy helper or a command recorded before spawn. */
-export function localBackendProcess(port: number, electronPid: number): NativeProcess {
+export function localBackendProcess(port: number, electronPid: number, hermesHome?: string): NativeProcess {
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
throw new Error('Invalid backend port')
}
- const children = descendants(readNativeProcesses(), electronPid)
+ const processes = readNativeProcesses()
+ const children = descendants(processes, electronPid)
+ // An update can automatically reopen the app before this smoke starts. The
+ // new window legitimately attaches to that host backend instead of spawning
+ // its own child. Registration is only a candidate: the OS listener and the
+ // caller's existing installed-tree checks must independently agree.
+ let registered: number[] = []
+ if (hermesHome) {
+ try {
+ registered = parseSpawnLedger(fs.readFileSync(path.join(hermesHome, 'spawn-ledger.json'), 'utf8'))
+ .filter(record => record.port === port).map(record => record.pid)
+ } catch { /* Missing/unreadable ledger provides no attachment evidence. */ }
+ }
+ const candidates = processes.filter(candidate => children.includes(candidate) || registered.includes(candidate.pid))
let pids: number[]
if (process.platform === 'win32') {
@@ -155,16 +171,17 @@ export function localBackendProcess(port: number, electronPid: number): NativePr
pids = nativeText('/usr/sbin/lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fp']).split('\n')
.filter((line: string): boolean => /^p\d+$/.test(line)).map((line: string): number => Number(line.slice(1)))
} else {
- pids = linuxListeningPid(port, children)
+ pids = linuxListeningPid(port, candidates)
}
- const matches = children.filter((child: NativeProcess): boolean => pids.includes(child.pid))
+ const matches = candidates.filter((child: NativeProcess): boolean => pids.includes(child.pid))
if (matches.length !== 1) {
- throw new Error(`Expected one Electron-owned backend listener on port ${port}; found ${matches.length}`)
+ throw new Error(`Expected one Desktop-owned or registered host backend listener on port ${port}; found ${matches.length}`)
}
const backend = matches[0]
+ backend.ownership = children.includes(backend) ? 'child' : 'host-ledger'
if (process.platform === 'linux') {
backend.executable = fs.readlinkSync(`/proc/${backend.pid}/exe`)
diff --git a/tests-js/scripts/desktop-smoke.test.ts b/tests-js/scripts/desktop-smoke.test.ts
index cd4521a3970..d2f86ce6dbe 100644
--- a/tests-js/scripts/desktop-smoke.test.ts
+++ b/tests-js/scripts/desktop-smoke.test.ts
@@ -148,6 +148,39 @@ test.runIf(process.platform === 'linux')('origin proof finds the live child list
} finally { child.kill(); await new Promise<void>((resolve): void => { child.once('exit', (): void => resolve()) }) }
})
+test.runIf(process.platform === 'linux' || process.platform === 'darwin')('a shared host listener is proven by this home ledger, not Electron ancestry', async (): Promise<void> => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-host-listener-'))
+ 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())))
+ })
+ // A reused host backend is not a descendant of the newly opened Desktop.
+ // Here the real listener itself is outside that descendant set.
+ const ledger = path.join(home, 'spawn-ledger.json')
+ const record = { pid: child.pid, purpose: 'serve', host: '127.0.0.1', port }
+ expect(() => localBackendProcess(port, child.pid!, home)).toThrow('found 0')
+ for (const invalid of [{ ...record, port: port + 1 }, { ...record, pid: process.pid },
+ { ...record, isolated: true }, { ...record, purpose: 'update' }]) {
+ fs.writeFileSync(ledger, JSON.stringify([invalid]))
+ expect(() => localBackendProcess(port, child.pid!, home)).toThrow('found 0')
+ }
+ fs.writeFileSync(ledger, JSON.stringify([record]))
+ const backend = localBackendProcess(port, child.pid!, home)
+ expect(backend.pid).toBe(child.pid)
+ expect(backend.ownership).toBe('host-ledger')
+ // Registration does not waive the installed-tree provenance check.
+ expect(() => assertBackendOrigin(backend, home, 'bundled')).toThrow('agent-payload')
+ fs.writeFileSync(ledger, 'invalid')
+ expect(() => localBackendProcess(port, child.pid!, home)).toThrow('found 0')
+ } finally {
+ child.kill()
+ await new Promise<void>((resolve): void => { child.once('exit', (): void => resolve()) })
+ fs.rmSync(home, { 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-'))
diff --git a/tests/install/e2e-assets/desktop-smoke.ts b/tests/install/e2e-assets/desktop-smoke.ts
index 11d353f6983..741c8f2d7cd 100644
--- a/tests/install/e2e-assets/desktop-smoke.ts
+++ b/tests/install/e2e-assets/desktop-smoke.ts
@@ -329,18 +329,17 @@ export async function runInstalledDesktopSmoke(options: SmokeOptions, launchApp:
throw new Error(`Desktop resolved Hermes home ${identity.hermesHome ?? '(unreported)'} instead of the predicted ${predictedHome}`)
}
}
- const backend = localBackendProcess(Number(base.port), running.pid)
- // Evidence before assertions: the backend's identity must be on disk when
- // assertBackendOrigin fails, or the leg reports a mismatch with nothing to
- // inspect.
+ // 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.
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.
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') }
- fs.writeFileSync(path.join(out, `desktop-backend-${options.phase}.log`), connection.logs.map(redact).join('\n'))
// Trace only chat actions. Connection probes can return credential-bearing logs.
await app.context().tracing.start({ screenshots: true, snapshots: false, sources: false })
const chat = await runDesktopChatSmoke(page, { mockUrl, phase: options.phase, outDir: out, expectCommit: options['expect-commit'], provenanceCommit })