Skip to content

The agent that grows with you

test: cold-profile archive/unarchive through one multiplexing gateway is an acceptance case

teknium1dfbb91424481
diff --git a/evals/desktop_gateway_ticket_native/README.md b/evals/desktop_gateway_ticket_native/README.md
index e9a84ca2b21..612bfd36e92 100644
--- a/evals/desktop_gateway_ticket_native/README.md
+++ b/evals/desktop_gateway_ticket_native/README.md
@@ -27,6 +27,10 @@ Assertions:
`workflow.yml` is deliberately outside `.github`. The parent can copy it to `.github/workflows/native-ticket-temp.yml` on an `e2e/native-ticket-*` branch. Its push trigger runs actual `windows-latest` and `macos-latest` jobs; dispatch on a new nondefault workflow alone is insufficient. It uses `uv sync --locked` and root `npm ci`, uploads per-OS receipts, and needs no secrets. Never merge the temporary workflow. Inspect both downloaded receipts, not just job conclusions.
+## Multiplex attach + cold-profile mutation probe
+
+`run_multiplex.py` (same flags) starts ONE `gateway.run` with `gateway.multiplex_profiles: true` serving default + `warm` + `cold`, then in real Electron main runs the production Desktop attach path per profile (`runGatewayEnsure` → `ensureLocalGateway`, the exact `hermes --profile <p> gateway ensure --json` child, `mintLocalGatewayTicket`, `nativeGatewayHttpHeaders`) and the exact `PATCH /api/sessions/{id}` shape `src/api/sessions.ts::mutateSessionHttp` sends. Assertions: every profile resolves to the one multiplexer instance and served secondaries carry `control_home` = the root; a session created in `cold` and detached is archived and unarchived (revision N → N+1) while `default` and `warm` hold live interactive attachments; the default profile's descriptor gets 403 on the cold profile's rows; the warm attachment survives. This is the acceptance case for the local-pool cutover (PR #106742, cold-profile archive report).
+
## Explicit limits
Linux execution does not validate the Windows named-pipe branch or macOS Unix-socket permissions; run the native jobs. The wrong-profile combination tests descriptor binding against a real other owner, not a fabricated owner subject. A Windows **wrong OS-owner SID** negative is not implemented: it requires an actual second-account process/token serving a permissive decoy pipe under an owned profile name (and an OS-verified differing SID), rather than the normal daemon's same-user DACL. The Linux host has no such Windows identity. Do not interpret same-user wrong-instance/profile checks, a mocked SID, or a DACL-only refusal as proof of the Python client's server-SID check. The receipt preserves `wrongOsOwnerSid.status = not_exercised` even when all implemented checks pass.
diff --git a/evals/desktop_gateway_ticket_native/build.mjs b/evals/desktop_gateway_ticket_native/build.mjs
index e12ca3b4882..11e085447d1 100644
--- a/evals/desktop_gateway_ticket_native/build.mjs
+++ b/evals/desktop_gateway_ticket_native/build.mjs
@@ -5,7 +5,7 @@ const directory = path.dirname(fileURLToPath(import.meta.url))
const require = createRequire(path.resolve(directory, '../../apps/desktop/package.json'))
const { build } = require('esbuild')
await build({
- entryPoints: [path.join(directory, 'electron-main.ts')], outfile: process.argv[2],
+ entryPoints: [process.argv[3] ? path.resolve(process.argv[3]) : path.join(directory, 'electron-main.ts')], outfile: process.argv[2],
bundle: true, platform: 'node', format: 'cjs', target: 'node22', external: ['electron'],
nodePaths: [path.resolve(directory, '../../node_modules'), path.resolve(directory, '../../apps/desktop/node_modules')]
})
diff --git a/evals/desktop_gateway_ticket_native/electron-main-multiplex.ts b/evals/desktop_gateway_ticket_native/electron-main-multiplex.ts
new file mode 100644
index 00000000000..8dca88c4ab9
--- /dev/null
+++ b/evals/desktop_gateway_ticket_native/electron-main-multiplex.ts
@@ -0,0 +1,120 @@
+import { app } from 'electron'
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import WebSocket from 'ws'
+import { configureWindowsGatewayTicketClient, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, runGatewayEnsure } from '../../apps/desktop/electron/local-gateway'
+import { mintGatewayTicketWithPython } from '../../apps/desktop/electron/local-gateway-python'
+
+/**
+ * Multiplex attach + cold-profile sidebar mutation, in real Electron main against one
+ * `gateway.run` that serves default + warm + cold. Every step is the production Desktop
+ * code path: `runGatewayEnsure` → `ensureLocalGateway` (the child main.ts spawns per
+ * profile), `mintLocalGatewayTicket` (WS attach), `nativeGatewayHttpHeaders` (REST), and
+ * the exact request shape `src/api/sessions.ts::mutateSessionHttp` sends for archive.
+ */
+const input = JSON.parse(fs.readFileSync(process.env.NATIVE_MUX_INPUT!, 'utf8'))
+const receipt: Record<string, unknown> = { platform: process.platform, electron: process.versions.electron, processType: process.type, checks: {}, passed: false }
+const checks = receipt.checks as Record<string, unknown>
+const watchdog = setTimeout(() => { console.error('Native probe deadline'); app.exit(2) }, 150_000)
+app.setPath('userData', input.userData)
+app.disableHardwareAcceleration()
+
+const backend = (profile: string) => ({ command: input.python, args: ['-m', 'hermes_cli.main', '--profile', profile, 'gateway', 'ensure', '--json', '--timeout', '30'], env: { PYTHONPATH: input.repo, HOME: input.home, USERPROFILE: input.home }, shell: false })
+
+async function attach(connection: any) {
+ const ticket = await mintLocalGatewayTicket(connection.gatewayEndpoint)
+
+ return new Promise<{ ws: WebSocket; call: (method: string, params: any) => Promise<any> }>((resolve, reject) => {
+ const ws = new WebSocket(connection.baseUrl.replace(/^http/, 'ws') + '/api/ws', ['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket], { handshakeTimeout: 10_000 })
+ let next = 1
+ const pending = new Map<number, (frame: any) => void>()
+ ws.on('unexpected-response', (_r, response) => reject(new Error(`WS ${response.statusCode} for ${connection.profile}`)))
+ ws.on('error', reject)
+ ws.on('message', raw => { const frame = JSON.parse(raw.toString()); if (frame.id && pending.has(frame.id)) { pending.get(frame.id)!(frame); pending.delete(frame.id) } })
+ ws.on('open', () => resolve({ ws, call: (method, params) => new Promise(done => { const id = next++; pending.set(id, done); ws.send(JSON.stringify({ jsonrpc: '2.0', id, method, params })) }) }))
+ })
+}
+
+async function rest(connection: any, method: string, path: string, body?: unknown) {
+ const url = connection.baseUrl + path
+ const headers: Record<string, string> = { ...(await nativeGatewayHttpHeaders({ gatewayEndpoint: connection.gatewayEndpoint, baseUrl: connection.baseUrl }, url)) }
+ if (body !== undefined) headers['Content-Type'] = 'application/json'
+ const response = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(20_000) })
+ const text = await response.text()
+ return { status: response.status, json: text ? JSON.parse(text) : null }
+}
+
+/** Byte-for-byte `mutateSessionHttp(id, 'PATCH', payload, profile)`. */
+async function sidebarPatch(connection: any, profile: string, sid: string, payload: Record<string, unknown>, requestId: string) {
+ const query = `?profile=${encodeURIComponent(profile)}`
+ const snapshot = await rest(connection, 'GET', `/api/sessions/${encodeURIComponent(sid)}/mutation-snapshot${query}`)
+ assert.equal(snapshot.status, 200, JSON.stringify(snapshot.json))
+ const identity = { request_id: requestId, expected_revision: snapshot.json.runtime_revision, expected_generation: snapshot.json.runtime_generation }
+ return rest(connection, 'PATCH', `/api/sessions/${encodeURIComponent(sid)}${query}`, { ...payload, ...identity, profile })
+}
+
+async function main() {
+ assert.ok(process.versions.electron, 'Must execute inside real Electron, not Node')
+ assert.equal(process.type, 'browser', 'Must execute in Electron main')
+ configureWindowsGatewayTicketClient((endpoint, purpose) => mintGatewayTicketWithPython({ command: input.python, env: { PYTHONPATH: input.repo } }, input.repo, endpoint, purpose))
+
+ // 1. Desktop-side discovery for every profile: same instance, secondaries via the root's control socket.
+ const connections: Record<string, any> = {}
+ for (const profile of ['default', 'warm', 'cold']) {
+ connections[profile] = { ...(await ensureLocalGateway(() => runGatewayEnsure(backend(profile), input.repo, input.state))), profile }
+ }
+ const instances = new Set(Object.values(connections).map(c => c.gatewayEndpoint.instance_id))
+ assert.equal(instances.size, 1, 'every profile attaches to the one multiplexer')
+ assert.equal(connections.cold.gatewayEndpoint.control_home, input.state)
+ assert.equal(connections.default.gatewayEndpoint.control_home, null)
+ checks.ensure = Object.fromEntries(Object.entries(connections).map(([p, c]) => [p, { profile_id: c.gatewayEndpoint.profile_id, control_home: c.gatewayEndpoint.control_home, api_origin: c.baseUrl }]))
+
+ // 2. Cold profile: create a GUI session over an interactive attach, then detach (it goes cold).
+ const coldAttach = await attach(connections.cold)
+ const created = await coldAttach.call('session.create', { request_id: 'cold-create', source: 'gui' })
+ assert.ok(created.result?.session_id, JSON.stringify(created))
+ const coldSid: string = created.result.session_id
+ coldAttach.ws.terminate()
+ await new Promise(resolve => setTimeout(resolve, 300))
+
+ // 3. Warm stays attached while default + warm are "active"; archive/unarchive cold over the Desktop REST shape.
+ const warmAttach = await attach(connections.warm)
+ const warmDescribe = await warmAttach.call('runtime.describe', {})
+ assert.equal(warmDescribe.result.profile_id, connections.warm.gatewayEndpoint.profile_id)
+ const defaultAttach = await attach(connections.default)
+ try {
+ const archived = await sidebarPatch(connections.cold, 'cold', coldSid, { archived: true }, 'archive')
+ assert.equal(archived.status, 200, JSON.stringify(archived.json))
+ assert.equal(archived.json.archived, true)
+ const afterArchive = await rest(connections.cold, 'GET', `/api/sessions/${encodeURIComponent(coldSid)}?profile=cold`)
+ assert.equal(afterArchive.json.archived, 1)
+ assert.equal(afterArchive.json.profile, 'cold')
+ const restored = await sidebarPatch(connections.cold, 'cold', coldSid, { archived: false }, 'unarchive')
+ assert.equal(restored.status, 200, JSON.stringify(restored.json))
+ assert.equal(restored.json.archived, false)
+ assert.equal(restored.json.revision, archived.json.revision + 1)
+ const afterRestore = await rest(connections.cold, 'GET', `/api/sessions/${encodeURIComponent(coldSid)}?profile=cold`)
+ assert.equal(afterRestore.json.archived, 0)
+ checks.coldArchive = { session_id: coldSid, archive: archived.json, unarchive: restored.json }
+
+ // 4. Boundary: the default profile's descriptor cannot read the cold profile's rows.
+ const foreign = await rest(connections.default, 'GET', `/api/sessions/${encodeURIComponent(coldSid)}/mutation-snapshot?profile=cold`)
+ assert.equal(foreign.status, 403)
+ checks.foreignProfileSnapshot = foreign.status
+ // 5. The attached siblings are still live after the cold mutation.
+ const stillWarm = await warmAttach.call('runtime.describe', {})
+ assert.equal(stillWarm.result.instance_id, connections.warm.gatewayEndpoint.instance_id)
+ checks.warmStillAttached = true
+ } finally {
+ warmAttach.ws.terminate()
+ defaultAttach.ws.terminate()
+ }
+ receipt.passed = true
+}
+
+app.whenReady().then(main).catch(error => { receipt.error = String(error?.stack || error) }).finally(() => {
+ clearTimeout(watchdog)
+ fs.writeFileSync(input.receipt, JSON.stringify(receipt, null, 2) + '\n')
+ console.log(JSON.stringify(receipt))
+ app.exit(receipt.passed ? 0 : 1)
+})
diff --git a/evals/desktop_gateway_ticket_native/run_multiplex.py b/evals/desktop_gateway_ticket_native/run_multiplex.py
new file mode 100644
index 00000000000..837dec59efe
--- /dev/null
+++ b/evals/desktop_gateway_ticket_native/run_multiplex.py
@@ -0,0 +1,117 @@
+"""Real Electron main against one multiplexing gateway (default + warm + cold): Desktop attach
+for every profile through the production ensure/ticket code, then archive/unarchive of a
+COLD profile's session over the exact REST shape the renderer sends, while the other two
+profiles hold live attachments. Companion to run.py (single-profile ticket probe)."""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import time
+
+REPO = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(REPO))
+from evals.desktop_gateway_ticket_native.run import stop_owned # noqa: E402
+from hermes_cli.gateway_runtime_discovery import query_identify # noqa: E402
+
+
+def ready(process, home, wanted):
+ deadline = time.monotonic() + 90
+ last = None
+ while time.monotonic() < deadline and process.poll() is None:
+ try:
+ endpoint = query_identify(home, timeout=2)
+ served = {Path(item['home']).resolve() for item in endpoint.get('served_profiles', [])}
+ if endpoint.get('state') == 'ready' and endpoint.get('api_origin') and wanted <= served:
+ return endpoint
+ except (OSError, ValueError) as error:
+ last = type(error).__name__
+ time.sleep(0.2)
+ raise RuntimeError(f'Multiplexer not ready: exit={process.poll()}, last={last}')
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--python', default=sys.executable)
+ parser.add_argument('--electron', help='Native Electron binary, not electron/index.js')
+ parser.add_argument('--output', type=Path, required=True)
+ args = parser.parse_args()
+ python = os.path.abspath(args.python)
+ from hermes_constants import find_node_executable
+ node = find_node_executable('node')
+ if not node:
+ parser.error('node is required')
+ electron = args.electron or subprocess.check_output(
+ [node, '-e', 'console.log(require("electron"))'], cwd=REPO / 'apps/desktop',
+ stdin=subprocess.DEVNULL, text=True, encoding='utf-8', errors='replace', timeout=15).strip()
+ output = args.output.resolve()
+ output.mkdir(parents=True, exist_ok=True)
+ receipt = {'passed': False, 'host': sys.platform}
+ processes, logs = [], []
+ temporary_directory = tempfile.TemporaryDirectory(prefix='h-mux-')
+ try:
+ base = Path(temporary_directory.name).resolve()
+ home, state = base / 'home', base / 'state'
+ profiles = {name: state / 'profiles' / name for name in ('warm', 'cold')}
+ for directory in (home, state, *profiles.values(), base / 'user-data', base / 'tmp'):
+ directory.mkdir(parents=True, mode=0o700, exist_ok=True)
+ env = {key: value for key, value in os.environ.items() if key.upper() in {
+ 'PATH', 'DISPLAY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR', 'XAUTHORITY', 'LD_LIBRARY_PATH', 'LANG', 'TZ'}}
+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state),
+ XDG_CONFIG_HOME=str(home / '.config'), XDG_CACHE_HOME=str(home / '.cache'),
+ TEMP=str(base / 'tmp'), TMP=str(base / 'tmp'), TMPDIR=str(base / 'tmp'),
+ PYTHONPATH=str(REPO), PYTHONUNBUFFERED='1', PYTHONUTF8='1', PYTHONIOENCODING='utf-8')
+ (state / 'config.yaml').write_text(json.dumps({
+ 'gateway': {'multiplex_profiles': True},
+ 'model': {'provider': 'custom', 'default': 'launch-model', 'base_url': 'http://127.0.0.1:1/v1'},
+ 'auxiliary': {'title_generation': {'enabled': False}}}), encoding='utf-8')
+ for name, profile in profiles.items():
+ (profile / 'config.yaml').write_text(json.dumps({'model': {
+ 'provider': 'custom', 'default': name + '-model', 'base_url': 'http://127.0.0.1:1/v1'}}), encoding='utf-8')
+ log = (output / 'multiplexer.log').open('w', encoding='utf-8')
+ logs.append(log)
+ process = subprocess.Popen([python, '-m', 'gateway.run'], cwd=REPO, env=env,
+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
+ processes.append(process)
+ identity = ready(process, state, {state.resolve(), *(p.resolve() for p in profiles.values())})
+ bundle = base / 'electron-main-multiplex.cjs'
+ subprocess.run([node, str(Path(__file__).with_name('build.mjs')), str(bundle),
+ str(Path(__file__).with_name('electron-main-multiplex.ts'))],
+ cwd=REPO, stdin=subprocess.DEVNULL, check=True, timeout=60)
+ input_file = base / 'input.json'
+ input_file.write_text(json.dumps({
+ 'repo': str(REPO), 'python': python, 'home': str(home), 'state': str(state),
+ 'identity': {k: identity.get(k) for k in ('instance_id', 'api_origin', 'served_profiles')},
+ 'userData': str(base / 'user-data'), 'receipt': str(output / 'receipt.json')}), encoding='utf-8')
+ electron_log = (output / 'electron.log').open('w', encoding='utf-8')
+ logs.append(electron_log)
+ flags = ['--ozone-platform=headless', '--no-sandbox'] if sys.platform == 'linux' else []
+ native = subprocess.Popen([electron, *flags, str(bundle)], cwd=REPO,
+ env={**env, 'NATIVE_MUX_INPUT': str(input_file)},
+ stdin=subprocess.DEVNULL, stdout=electron_log, stderr=subprocess.STDOUT)
+ processes.append(native)
+ status = native.wait(timeout=180)
+ receipt = json.loads((output / 'receipt.json').read_text(encoding='utf-8'))
+ if status or not receipt.get('passed'):
+ raise RuntimeError(f'Electron probe failed: exit={status}')
+ except Exception as error:
+ receipt['passed'] = False
+ receipt['harnessError'] = str(error)
+ finally:
+ for process in reversed(processes):
+ stop_owned(process)
+ for log in logs:
+ log.close()
+ temporary_directory.cleanup()
+ receipt['ownedProcessesStopped'] = all(process.poll() is not None for process in processes)
+ (output / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n', encoding='utf-8')
+ print(json.dumps(receipt, indent=2))
+ return 0 if receipt['passed'] else 1
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())