The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
test: exercise isolated desktop backend and daemon lifecycles
deef5371781ced0
diff --git a/cli/scripts/local-stack-peer.ts b/cli/scripts/local-stack-peer.tsnew file mode 100644index 000000000..92487aad7--- /dev/null+++ b/cli/scripts/local-stack-peer.ts@@ -0,0 +1,232 @@+/** Disposable backend + daemon for Desktop's local_stack_e2e_test.dart.+ * Real Mongo/Redis, SSO validation boundary, WebSockets, E2EE and tmux. Only the+ * identity provider and model CLI are deterministic fixtures; no real account.+ */+import { spawn, execFile, type ChildProcess } from 'node:child_process'+import { createServer } from 'node:http'+import { createServer as netServer, createConnection } from 'node:net'+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'+import { createWriteStream } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'+import { promisify } from 'node:util'+import { randomUUID } from 'node:crypto'+import { WebSocket, WebSocketServer } from 'ws'+import { newIdentity, b64e } from '../src/lib/e2ee/core.js'+import { RelaySessionCrypto } from '../src/lib/e2ee/relayClient.js'+import { decodeTerminalLocal, encodeTerminalLocal } from '../src/lib/terminalBinary.js'++if (process.env.HARNESS_STACK_E2E !== '1') throw new Error('Opt in with HARNESS_STACK_E2E=1')+const exec = promisify(execFile)+const repo = resolve(dirname(fileURLToPath(import.meta.url)), '../..')+const root = await mkdtemp(join(tmpdir(), 'harness-stack-'))+const socket = join(root, 'tmux.sock')+const docker = process.env.HARNESS_E2E_DOCKER_CONTEXT+ ? ['--context', process.env.HARNESS_E2E_DOCKER_CONTEXT] : []+const containers: string[] = []+const children: ChildProcess[] = []+const token = `fixture-${randomUUID()}`+const computerId = randomUUID().replaceAll('-', '')+const clientIdentity = newIdentity()+const machineIdentity = newIdentity()+let daemon: ChildProcess | undefined+let stopping = false+const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))+async function until(label: string, check: () => Promise<boolean>, ms = 30_000) {+ const end = Date.now() + ms+ while (Date.now() < end) {+ if (await check().catch(() => false)) return+ await delay(150)+ }+ throw new Error(`Timed out: ${label}; logs: ${root}`)+}+async function freePort() {+ const server = netServer()+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))+ const port = (server.address() as { port: number }).port+ await new Promise<void>(resolve => server.close(() => resolve()))+ return port+}+function run(name: string, cwd: string, args: string[], env: NodeJS.ProcessEnv) {+ const child = spawn(process.execPath, args, { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] })+ const log = createWriteStream(join(root, `${name}.log`), { flags: 'a' })+ child.stdout!.pipe(log)+ child.stderr!.pipe(log)+ children.push(child)+ return child+}+async function stop(child: ChildProcess | undefined) {+ if (!child?.pid || child.exitCode != null) return+ try { process.kill(-child.pid, 'SIGTERM') } catch { return }+ await until('child exit', async () => child.exitCode != null || child.signalCode != null, 5000)+ .catch(() => { try { process.kill(-child.pid!, 'SIGKILL') } catch { /* exited */ } })+}+async function cleanup(code: number) {+ if (stopping) return+ stopping = true+ for (const child of children.reverse()) await stop(child)+ await exec('tmux', ['-S', socket, 'kill-server']).catch(() => {})+ for (const name of containers) await exec('docker', [...docker, 'rm', '-f', name]).catch(() => {})+ if (code === 0 && process.env.HARNESS_STACK_KEEP !== '1') await rm(root, { recursive: true, force: true })+ else console.error(`Stack fixture logs retained at ${root}`)+ process.exit(code)+}+process.on('SIGTERM', () => { void cleanup(0) })+process.on('SIGINT', () => { void cleanup(0) })+process.stdin.resume()+process.stdin.on('end', () => { void cleanup(0) })+process.on('uncaughtException', error => { console.error(error); void cleanup(1) })+process.on('unhandledRejection', error => { console.error(error); void cleanup(1) })++try {+ const [mongoPort, redisPort, backendPort, proxyPort, cliPort] = await Promise.all(Array.from({ length: 5 }, freePort))+ const sso = createServer((req, res) => {+ res.setHeader('content-type', 'application/json')+ if (req.headers.authorization !== `Bearer ${token}`) { res.writeHead(401); res.end('{}'); return }+ res.end(JSON.stringify({ status: 1, data: { id: computerId, email: `${computerId}@local.invalid` } }))+ })+ await new Promise<void>(resolve => sso.listen(0, '127.0.0.1', resolve))+ const ssoPort = (sso.address() as { port: number }).port+ for (const [kind, port, image, args] of [+ ['mongo', mongoPort, 'mongo:7', ['--replSet', 'rs0', '--bind_ip_all']],+ ['redis', redisPort, 'redis:7-alpine', []],+ ] as const) {+ const name = `harness-stack-${kind}-${process.pid}`+ containers.push(name)+ await exec('docker', [...docker, 'run', '--rm', '-d', '--name', name,+ '-p', `127.0.0.1:${port}:${kind === 'mongo' ? 27017 : 6379}`, image, ...args], { timeout: 120_000 })+ }+ await until('Mongo replica set', async () => {+ await exec('docker', [...docker, 'exec', containers[0]!, 'mongosh', '--quiet', '--eval',+ 'try { if (rs.status().ok === 1) quit(0) } catch (_) { try { rs.initiate({_id:"rs0",members:[{_id:0,host:"127.0.0.1:27017"}]}) } catch (_) {} } quit(1)'])+ return true+ }, 60_000)+ await until('Redis published port', () => new Promise<boolean>(resolve => {+ const client = createConnection({ host: '127.0.0.1', port: redisPort })+ const finish = (ok: boolean) => { client.destroy(); resolve(ok) }+ client.setTimeout(1000)+ client.on('connect', () => client.write('PING\r\n'))+ client.on('data', data => finish(data.toString().includes('PONG')))+ client.on('error', () => finish(false))+ client.on('timeout', () => finish(false))+ }))+ const backendEnv = { ...process.env, NODE_ENV: 'test', PORT: String(backendPort), PORT_APP_PROXY: String(proxyPort),+ DATABASE_URL: `mongodb://127.0.0.1:${mongoPort}/harness?replicaSet=rs0&directConnection=true`,+ REDIS_URL: `redis://127.0.0.1:${redisPort}`, HARNESS_BILLING_ENABLED: 'false', MESH_ENABLED: 'false',+ SSO_PROFILE_URL: `http://127.0.0.1:${ssoPort}/profile`, TERMINAL_P2P_ROLLOUT_PERCENT: '0',+ HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' }+ await exec(join(repo, 'backend/node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'],+ { cwd: join(repo, 'backend'), env: backendEnv, timeout: 60_000 })+ run('backend', join(repo, 'backend'), ['--import', 'tsx', 'src/server.ts'], backendEnv)+ const backendUrl = `http://127.0.0.1:${backendPort}`+ await until('backend health', async () => (await fetch(`${backendUrl}/api/health`)).ok)+ const resolved = await fetch(`${backendUrl}/api/machines/resolve-computer`, { method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${token}`, 'x-autonomous-env': 'prod' },+ body: JSON.stringify({ computerId, label: 'E2E fixture' }) })+ const body = await resolved.json() as { data?: { machine?: { machineId?: string } } }+ const machineId = body.data?.machine?.machineId+ if (!resolved.ok || !machineId) throw new Error(`Fixture machine registration failed (${resolved.status})`)+ const dataDir = join(root, 'data'), authDir = join(root, 'auth'), workspace = join(root, 'project')+ for (const path of [join(dataDir, 'e2e'), authDir, workspace, join(root, 'bin')]) await mkdir(path, { recursive: true })+ await writeFile(join(authDir, 'session.json'), JSON.stringify({ version: 1, accessToken: token,+ refreshToken: 'fixture-refresh', expiresAt: Date.now() + 3_600_000, autonomousEnv: 'prod', computerId, machineId, updatedAt: Date.now() }), { mode: 0o600 })+ await writeFile(join(dataDir, 'e2e/identity.json'), JSON.stringify({ priv: b64e(machineIdentity.priv), pub: b64e(machineIdentity.pub) }), { mode: 0o600 })+ await writeFile(join(dataDir, 'e2e/paired.json'), JSON.stringify([{ identityPub: b64e(clientIdentity.pub), label: 'E2E client', pairedAt: Date.now(), role: 'web' }]), { mode: 0o600 })+ const engine = join(root, 'bin/codex')+ await writeFile(engine, `#!${process.execPath}+if (process.argv.includes('--version')) { console.log('codex-cli 1.0.0'); process.exit(0) }+process.title = 'codex';+process.stdin.setRawMode?.(true);+console.log('STACK_READY pid=' + process.pid);+process.stdin.on('data', chunk => process.stdout.write('ECHO:' + chunk.toString() + '\\r\\n'));+setInterval(() => {}, 1000);+`, { mode: 0o700 })+ await exec('tmux', ['-S', socket, '-f', '/dev/null', 'new-session', '-d', '-s', 'fixture-keeper'])+ const daemonEnv = { ...process.env, NODE_ENV: 'test', TMUX: `${socket},0,0`, PORT: String(cliPort),+ HARNESS_AUTH_DIR: authDir, ADAPTER_COMPUTER_ID: computerId, ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),+ ADAPTER_DATA_DIR: dataDir, DSH_DIR: join(root, 'dsh'), CODEX_PATH: engine,+ BACKEND_WS_URL: `ws://127.0.0.1:${backendPort}`, WEB_URL: backendUrl,+ DISABLE_HOOK_INSTALL: 'true', ADAPTER_UPDATE_DISABLE: 'true', ANALYTICS_ENABLED: 'false', RECAP_FORCE: 'false',+ RECAP_WITHOUT_DEVICE: 'false', CABLE_DISABLE: 'true', CABLE_FW_DISABLE: 'true',+ TMUX_REAP_INTERVAL_MS: '5000', TERMINAL_RECONCILE_INTERVAL_MS: '5000', TERMINAL_BACKENDS: 'tmux', CLAUDE_PROJECTS_DIR: join(root, 'claude-projects') }+ const dshSource = join(root, 'harness-source')+ await mkdir(join(dshSource, 'template'), { recursive: true })+ await mkdir(join(dshSource, 'skills/example'), { recursive: true })+ await writeFile(join(dshSource, 'harness.json'), JSON.stringify({+ spec: 1, id: 'fixture/example', name: 'Example', engine: 'codex',+ workspace: { template: 'template', marker: 'example.txt' },+ agent: { instructions: 'AGENTS.md', skills: ['skills'] },+ viewer: { command: './viewer.mjs', url: 'http://127.0.0.1:${port}/' },+ verdict: '.harness/verdict.json',+ }))+ await writeFile(join(dshSource, 'AGENTS.md'), 'Fixture instructions.\n')+ await writeFile(join(dshSource, 'skills/example/SKILL.md'), '---\nname: example\ndescription: Fixture skill.\n---\nFixture.\n')+ await writeFile(join(dshSource, 'template/example.txt'), 'Fixture artifact\n')+ await writeFile(join(dshSource, 'viewer.mjs'), `#!${process.execPath}+import { createServer } from 'node:http';+createServer((_, res) => res.end('Fixture viewer')).listen(Number(process.env.HARNESS_VIEWER_PORT), '127.0.0.1');+`, { mode: 0o700 })+ await exec(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'dsh', 'install', dshSource, '--link'],+ { cwd: join(repo, 'cli'), env: daemonEnv, timeout: 30_000 })+ async function bootDaemon() {+ daemon = run('daemon', join(repo, 'cli'), ['--import', 'tsx', 'src/cli.ts', '__run'], daemonEnv)+ await until('daemon connection', async () => {+ const status = await fetch(`http://127.0.0.1:${cliPort}/api/status`, { headers: { 'x-adapter-local': '1' } }).then(r => r.json()) as { connected?: boolean }+ return status.connected === true+ })+ }+ await bootDaemon()++ // Desktop sees its normal loopback protocol; the other leg uses the real+ // backend plus the production signed handshake and encrypted terminal codec.+ const bridge = new WebSocketServer({ host: '127.0.0.1', port: 0 })+ await new Promise<void>(resolve => bridge.once('listening', resolve))+ let encryptedFrames = 0+ bridge.on('connection', local => {+ const crypto = new RelaySessionCrypto({ machineId, selfIdentity: clientIdentity, peerPub: machineIdentity.pub })+ const remote = new WebSocket(`ws://127.0.0.1:${backendPort}/api/web-ws`, [token])+ remote.on('open', () => remote.send(JSON.stringify({ type: 'machine_select', payload: { machineId } })))+ remote.on('error', () => local.close())+ remote.on('close', () => local.close())+ local.on('close', () => remote.close())+ remote.on('message', (raw, binary) => {+ if (local.readyState !== WebSocket.OPEN) return+ if (binary) {+ const clear = crypto.decryptTerminal(new Uint8Array(raw as Buffer))+ if (clear) { encryptedFrames++; local.send(encodeTerminalLocal(clear)) }+ return+ }+ const frame = JSON.parse(raw.toString())+ if (frame.type === 'connected') { remote.send(JSON.stringify(crypto.helloFrame())); return }+ if (frame.type === 'e2e_welcome') {+ if (!crypto.handleWelcome(frame.payload)) throw new Error('E2EE welcome authentication failed')+ local.send(JSON.stringify({ type: 'connected', payload: { machineId } }))+ return+ }+ const decoded = crypto.unwrapIncoming(frame)+ if (decoded) local.send(JSON.stringify(decoded))+ })+ local.on('message', (raw, binary) => {+ if (binary) {+ const clear = decodeTerminalLocal(new Uint8Array(raw as Buffer))+ const sealed = clear && crypto.encryptTerminal(clear)+ if (sealed) { encryptedFrames++; remote.send(sealed) }+ } else {+ const frame = JSON.parse(raw.toString())+ if (frame.type !== 'machine_select') remote.send(JSON.stringify(crypto.wrapOutgoing(frame)))+ }+ })+ })+ const control = createServer((req, res) => {+ void (async () => {+ if (req.url === '/restart') { await stop(daemon); await bootDaemon() }+ res.setHeader('content-type', 'application/json')+ res.end(JSON.stringify({ encryptedFrames }))+ })().catch(error => { res.writeHead(500); res.end(String(error)) })+ })+ await new Promise<void>(resolve => control.listen(0, '127.0.0.1', resolve))+ console.log(JSON.stringify({ machineId, workspace, localPort: cliPort,+ remotePort: (bridge.address() as { port: number }).port,+ controlPort: (control.address() as { port: number }).port, logs: root }))+} catch (error) { console.error(error); await cleanup(1) }diff --git a/cli/vitest.config.ts b/cli/vitest.config.tsindex d22a55b92..55bd13d77 100644--- a/cli/vitest.config.ts+++ b/cli/vitest.config.ts@@ -5,5 +5,8 @@ export default defineConfig({environment: 'node',setupFiles: ['./vitest.setup.ts'],include: ['src/**/*.test.ts', 'src/**/*.spec.ts'],+ // These suites spawn real shells, hooks and tmux helpers with bounded+ // deadlines. One worker per CPU starves those children on busy hosts.+ maxWorkers: 4,},})diff --git a/desktop/scripts/test-terminal-local-e2e.sh b/desktop/scripts/test-terminal-local-e2e.shindex 14ceac5a2..bc13f3c1a 100755--- a/desktop/scripts/test-terminal-local-e2e.sh+++ b/desktop/scripts/test-terminal-local-e2e.sh@@ -2,216 +2,16 @@set -euo pipefailDESKTOP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"-AUTONOMOUS_CODE_ROOT="${AUTONOMOUS_CODE_ROOT:-$DESKTOP_ROOT/../../autonomous-code}"-[[ -d "$AUTONOMOUS_CODE_ROOT/apps/backend" ]] \- || { echo "MISSING AUTONOMOUS_CODE_ROOT: $AUTONOMOUS_CODE_ROOT" >&2; exit 69; }-AUTONOMOUS_CODE_ROOT="$(cd "$AUTONOMOUS_CODE_ROOT" && pwd)"-HARNESS_ROOT="${HARNESS_REPO_ROOT:-$DESKTOP_ROOT/..}"--for command in docker redis-server node curl jq tmux flutter openssl; do- command -v "$command" >/dev/null || { echo "MISSING TOOL: $command" >&2; exit 69; }-done-for path in \- "$AUTONOMOUS_CODE_ROOT/apps/backend/node_modules/.bin/prisma" \- "$AUTONOMOUS_CODE_ROOT/apps/backend/node_modules/.bin/tsx" \- "$HARNESS_ROOT/cli/node_modules/.bin/tsx"; do- [[ -x "$path" ]] || { echo "MISSING LOCAL DEPENDENCY: $path" >&2; exit 69; }+for command in docker node tmux flutter; do+ command -v "$command" >/dev/null || { echo "Missing tool: $command" >&2; exit 69; }done--RUN_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/terminal-local-e2e.XXXXXX")"-MONGO_CONTAINER="terminal-local-e2e-${$}"-TMUX_SESSION="terminal-local-e2e-${$}"-BACKEND_PID=""-REDIS_PID=""-HARNESS_PID=""-PANE_ID=""--cleanup() {- local exit_code=$?- trap - EXIT INT TERM- for pid in "$HARNESS_PID" "$BACKEND_PID" "$REDIS_PID"; do- if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then- kill "$pid" 2>/dev/null || true- for _ in 1 2 3 4 5 6 7 8 9 10; do- kill -0 "$pid" 2>/dev/null || break- sleep 0.1- done- kill -KILL "$pid" 2>/dev/null || true- fi- wait "$pid" 2>/dev/null || true- done- tmux kill-session -t "$TMUX_SESSION" 2>/dev/null || true- docker rm -f "$MONGO_CONTAINER" >/dev/null 2>&1 || true- if [[ "${LOCAL_TERMINAL_E2E_KEEP:-0}" == "1" ]]; then- echo "Local E2E artifacts kept at $RUN_ROOT"- else- rm -rf "$RUN_ROOT"- fi- exit "$exit_code"-}-trap cleanup EXIT INT TERM--read -r BACKEND_PORT APP_PROXY_PORT REDIS_PORT MONGO_PORT CLI_PORT <<<"$(node --input-type=module -e '- import net from "node:net";- const servers = [];- for (let i = 0; i < 5; i++) {- const server = net.createServer();- await new Promise((resolve, reject) => server.once("error", reject).listen(0, "127.0.0.1", resolve));- servers.push(server);+for package in cli backend; do+ [[ -x "$DESKTOP_ROOT/../$package/node_modules/.bin/tsx" ]] || {+ echo "Run npm ci in $package first." >&2; exit 69;}- console.log(servers.map((server) => server.address().port).join(" "));- await Promise.all(servers.map((server) => new Promise((resolve) => server.close(resolve))));-')"--API_KEY="$(openssl rand -hex 32)"-MACHINE_ID="$(printf '%s' "$API_KEY" | shasum -a 256 | cut -c1-32)"-MARKER="LOCAL_TERMINAL_E2E_READY_${$}"-DATABASE_URL="mongodb://127.0.0.1:${MONGO_PORT}/harness?replicaSet=rs0&directConnection=true"-WS_BASE_URL="ws://127.0.0.1:${BACKEND_PORT}"-mkdir -p "$RUN_ROOT/adapter-data" "$RUN_ROOT/bin" "$RUN_ROOT/workspace"--docker run --rm -d \- --name "$MONGO_CONTAINER" \- -p "127.0.0.1:${MONGO_PORT}:27017" \- mongo:7 --replSet rs0 --bind_ip_all >"$RUN_ROOT/mongo-container-id"--mongo_ready=0-for _ in $(seq 1 60); do- docker exec "$MONGO_CONTAINER" mongosh --quiet --eval \- 'try { if (rs.status().ok === 1) quit(0) } catch (_) { try { rs.initiate({_id:"rs0",members:[{_id:0,host:"127.0.0.1:27017"}]}) } catch (_) {} } quit(1)' \- >/dev/null 2>&1 && { mongo_ready=1; break; }- sleep 0.5-done-[[ "$mongo_ready" == "1" ]] || { echo "Mongo replica set did not become ready" >&2; exit 75; }--redis-server \- --bind 127.0.0.1 \- --port "$REDIS_PORT" \- --save '' \- --appendonly no \- --daemonize no >"$RUN_ROOT/redis.log" 2>&1 &-REDIS_PID=$!--redis_ready=0-for _ in $(seq 1 40); do- node --input-type=module -e '- import net from "node:net";- const socket = net.connect(Number(process.argv[1]), "127.0.0.1");- socket.setTimeout(300);- socket.once("connect", () => { socket.end(); process.exit(0) });- socket.once("timeout", () => process.exit(1));- socket.once("error", () => process.exit(1));- ' "$REDIS_PORT" && { redis_ready=1; break; }- sleep 0.25-done-[[ "$redis_ready" == "1" ]] || { echo "Redis did not become ready" >&2; exit 75; }--(- cd "$AUTONOMOUS_CODE_ROOT/apps/backend"- DATABASE_URL="$DATABASE_URL" ./node_modules/.bin/prisma db push --skip-generate-) >"$RUN_ROOT/prisma.log" 2>&1-LOCAL_TERMINAL_E2E_API_KEY="$API_KEY" DATABASE_URL="$DATABASE_URL" \- node "$AUTONOMOUS_CODE_ROOT/scripts/terminal-local-db-fixture.mjs" >"$RUN_ROOT/db-fixture.json"-jq -e --arg machine "$MACHINE_ID" '.machineId == $machine' "$RUN_ROOT/db-fixture.json" >/dev/null--(- cd "$AUTONOMOUS_CODE_ROOT/apps/backend"- exec env \- NODE_ENV=test \- PORT="$BACKEND_PORT" \- PORT_APP_PROXY="$APP_PROXY_PORT" \- DATABASE_URL="$DATABASE_URL" \- REDIS_URL="redis://127.0.0.1:${REDIS_PORT}" \- HARNESS_BILLING_ENABLED=false \- MESH_ENABLED=false \- ./node_modules/.bin/tsx src/server.ts-) >"$RUN_ROOT/backend.log" 2>&1 &-BACKEND_PID=$!--backend_ready=0-for _ in $(seq 1 80); do- if curl --silent --fail "http://127.0.0.1:${BACKEND_PORT}/api/health" \- | jq -e '.success == true and .data.status == "ok"' >/dev/null 2>&1; then- backend_ready=1- break- fi- kill -0 "$BACKEND_PID" 2>/dev/null || { echo "Backend exited during startup" >&2; tail -80 "$RUN_ROOT/backend.log" >&2; exit 75; }- sleep 0.25-done-[[ "$backend_ready" == "1" ]] || { echo "Backend did not become ready" >&2; tail -80 "$RUN_ROOT/backend.log" >&2; exit 75; }--ln -s "$AUTONOMOUS_CODE_ROOT/scripts/fixtures/terminal-e2e-agent.mjs" "$RUN_ROOT/bin/codex"-PANE_ID="$(tmux new-session -d -P -F '#{pane_id}' \- -s "$TMUX_SESSION" -c "$RUN_ROOT/workspace" -x 92 -y 27 \- "env LOCAL_TERMINAL_E2E_MARKER=$MARKER $RUN_ROOT/bin/codex")"-[[ "$PANE_ID" =~ ^%[0-9]+$ ]] || { echo "Could not create disposable tmux pane" >&2; exit 70; }--(- cd "$HARNESS_ROOT/cli"- exec env \- PATH="$RUN_ROOT/bin:$PATH" \- NODE_ENV=test \- BACKEND_WS_URL="$WS_BASE_URL" \- WEB_URL="http://127.0.0.1:${BACKEND_PORT}" \- ADAPTER_DATA_DIR="$RUN_ROOT/adapter-data" \- PORT="$CLI_PORT" \- TERMINAL_BACKENDS=tmux \- TERMINAL_RECONCILE_INTERVAL_MS=5000 \- TMUX_REAP_INTERVAL_MS=500 \- DISABLE_HOOK_INSTALL=true \- ANALYTICS_ENABLED=false \- ADAPTER_UPDATE_DISABLE=true \- LOG_FRAMES=true \- ./node_modules/.bin/tsx src/cli.ts join -f "$API_KEY"-) >"$RUN_ROOT/harness.log" 2>&1 &-HARNESS_PID=$!--harness_ready=0-for _ in $(seq 1 120); do- if curl --silent --fail -H 'x-adapter-local: 1' "http://127.0.0.1:${CLI_PORT}/api/status" \- | jq -e '.connected == true' >/dev/null 2>&1; then- harness_ready=1- break- fi- kill -0 "$HARNESS_PID" 2>/dev/null || { echo "Harness CLI exited during startup" >&2; tail -120 "$RUN_ROOT/harness.log" >&2; exit 75; }- sleep 0.25done-[[ "$harness_ready" == "1" ]] || { echo "Harness CLI did not connect" >&2; tail -120 "$RUN_ROOT/harness.log" >&2; exit 75; }--browser_link_output="$(- cd "$HARNESS_ROOT/cli"- env \- BACKEND_WS_URL="$WS_BASE_URL" \- WEB_URL="http://127.0.0.1:${BACKEND_PORT}" \- ADAPTER_DATA_DIR="$RUN_ROOT/adapter-data" \- PORT="$CLI_PORT" \- ANALYTICS_ENABLED=false \- ADAPTER_UPDATE_DISABLE=true \- ./node_modules/.bin/tsx src/cli.ts browser-link-)"-setup_url="$(printf '%s\n' "$browser_link_output" | sed -nE 's/^[[:space:]]*(http[^[:space:]]+)[[:space:]]*$/\1/p' | head -1)"-[[ -n "$setup_url" ]] || { echo "Harness did not return a setup link" >&2; exit 75; }-SETUP_TOKEN="$(node -e 'const u=new URL(process.argv[1]); const t=new URLSearchParams(u.hash.slice(1)).get("t"); if (!t) process.exit(1); process.stdout.write(t)' "$setup_url")"--(- cd "$DESKTOP_ROOT"- flutter test integration_test/local_terminal_e2e_test.dart -d macos \- --dart-define=LOCAL_TERMINAL_E2E=true \- --dart-define=LOCAL_E2E_WS_BASE_URL="$WS_BASE_URL" \- --dart-define=LOCAL_E2E_API_KEY="$API_KEY" \- --dart-define=LOCAL_E2E_MACHINE_ID="$MACHINE_ID" \- --dart-define=LOCAL_E2E_SETUP_TOKEN="$SETUP_TOKEN" \- --dart-define=LOCAL_E2E_TMUX_PANE="$PANE_ID" \- --dart-define=LOCAL_E2E_TERMINAL_MARKER="$MARKER"-)--restored_size="$(tmux display-message -p -t "$PANE_ID" '#{pane_width}x#{pane_height}')"-[[ "$restored_size" == "92x27" ]] || { echo "Pane size was not restored after terminal_close: $restored_size" >&2; exit 1; }--if grep -F "$MARKER" "$RUN_ROOT/backend.log" "$RUN_ROOT/redis.log" >/dev/null; then- echo "PLAINTEXT LEAK: terminal marker appeared in Backend/Redis logs" >&2- exit 1-fi--echo "PASS: local Desktop -> local Backend -> local Harness CLI -> tmux terminal E2E"-echo " machine=${MACHINE_ID:0:12} pane=$PANE_ID backend=$WS_BASE_URL"+# HARNESS_E2E_DOCKER_CONTEXT optionally selects an existing test Docker context.+# The fixture owns its containers, auth, ports, workspace and dedicated tmux socket.+cd "$DESKTOP_ROOT"+HARNESS_STACK_CLI_ROOT="$DESKTOP_ROOT/../cli" \+ flutter test --no-pub test/local_stack_e2e_test.dart --reporter expandeddiff --git a/desktop/test/local_stack_e2e_test.dart b/desktop/test/local_stack_e2e_test.dartnew file mode 100644index 000000000..8d11c8eb3--- /dev/null+++ b/desktop/test/local_stack_e2e_test.dart@@ -0,0 +1,348 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/ws/ws_conn.dart';++/// Run through scripts/test-terminal-local-e2e.sh. The fixture owns every+/// service, identity, container and tmux session and cleans them up on stdin EOF.+void main() {+ final cli = Platform.environment['HARNESS_STACK_CLI_ROOT'];+ if (cli == null) {+ test(+ 'isolated local and cloud terminal stack',+ () {},+ skip: 'Run scripts/test-terminal-local-e2e.sh with Docker and tmux.',+ );+ return;+ }+ late Process fixture;+ late Map<String, dynamic> config;+ final errors = StringBuffer();+ WsConn? connection;+ TerminalSession? terminal;+ final keyframes = <TerminalBinaryFrame>[];++ Future<void> until(String label, FutureOr<bool> Function() check) async {+ final deadline = DateTime.now().add(const Duration(seconds: 25));+ while (DateTime.now().isBefore(deadline)) {+ if (await check()) return;+ await Future<void>.delayed(const Duration(milliseconds: 50));+ }+ fail('Timed out: $label; fixture logs: ${config['logs']}\n$errors');+ }++ setUpAll(() async {+ fixture = await Process.start(+ 'node',+ ['--import', 'tsx', 'scripts/local-stack-peer.ts'],+ workingDirectory: cli,+ environment: {'HARNESS_STACK_E2E': '1'},+ );+ fixture.stderr.transform(utf8.decoder).listen(errors.write);+ final ready = Completer<Map<String, dynamic>>();+ fixture.stdout+ .transform(utf8.decoder)+ .transform(const LineSplitter())+ .listen(+ (line) {+ try {+ final value = jsonDecode(line);+ if (value is Map<String, dynamic> &&+ value.containsKey('localPort') &&+ !ready.isCompleted) {+ ready.complete(value);+ }+ } on FormatException {+ /* dependency diagnostics */+ }+ },+ onDone: () {+ if (!ready.isCompleted) {+ ready.completeError(StateError('Fixture exited: $errors'));+ }+ },+ );+ config = await ready.future.timeout(const Duration(minutes: 3));+ });+ tearDownAll(() async {+ await fixture.stdin.close();+ await fixture.exitCode.timeout(+ const Duration(seconds: 30),+ onTimeout: () {+ fixture.kill();+ return -1;+ },+ );+ });+ tearDown(() async {+ await terminal?.close();+ terminal?.dispose();+ terminal = null;+ await connection?.close();+ connection = null;+ });++ Future<void> connect(String route) async {+ var connected = false;+ connection = WsConn(+ wsBaseUrl: '',+ autonomousEnv: 'prod',+ machineId: config['machineId'] as String,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: fail,+ onStatus: (status) => connected = status == ConnectionStatus.connected,+ onEvent: (event) async {+ await terminal?.handleFrame(+ event['type'] as String,+ event['payload'] as Map<String, dynamic>,+ );+ },+ transportKind: WsTransportKind.localPlaintext,+ localWsUri: Uri.parse(+ route == 'local'+ ? 'ws://127.0.0.1:${config['localPort']}/api/local-ws'+ : 'ws://127.0.0.1:${config['remotePort']}',+ ),+ );+ connection!.onBinaryFrame = (bytes) async {+ final frame = decodeTerminalLocal(bytes);+ if (frame != null) {+ if (frame.kind == TerminalBinaryKind.keyframe) keyframes.add(frame);+ await terminal?.handleBinary(frame);+ }+ };+ await connection!.connect();+ await until('$route connection', () => connected);+ }++ Future<Map<String, dynamic>> rpc(+ String type, [+ Map<String, dynamic> payload = const {},+ ]) => connection!.request(+ type,+ payload: payload,+ timeout: const Duration(seconds: 30),+ );+ Future<void> attach(String agentId) async {+ terminal?.dispose();+ terminal = TerminalSession(+ machineId: config['machineId'] as String,+ agentId: agentId,+ agentName: 'stack fixture',+ engineId: 'codex',+ send: (type, payload) => connection!.sendTerminalFrame(type, payload),+ sendBinary: (frame) =>+ connection!.sendTerminalBinary(encodeTerminalLocal(frame)!),+ );+ await terminal!.open(initialCols: 90, initialRows: 28);+ await until(+ 'terminal keyframe',+ () =>+ terminal!.acceptsInput &&+ terminal!.terminal.buffer.getText().contains('STACK_READY'),+ );+ }++ Future<void> echo(String text) async {+ terminal!.terminal.onOutput?.call('$text\r');+ await until(+ 'typed text echoed',+ () => terminal!.terminal.buffer.getText().contains('ECHO:$text'),+ );+ }++ Future<void> restartDaemon(String route) async {+ final http = HttpClient();+ try {+ final restart = await http.postUrl(+ Uri.parse('http://127.0.0.1:${config['controlPort']}/restart'),+ );+ final response = await restart.close();+ expect(response.statusCode, 200);+ await response.drain<void>();+ } finally {+ http.close(force: true);+ }+ await connection!.close();+ await connect(route);+ }++ for (final route in ['local', 'remote']) {+ test(+ '$route create, idempotent retry, input, resize, reconnect, restart and delete',+ () async {+ await connect(route);+ final request = <String, dynamic>{+ 'creationId': '$route-stack-${DateTime.now().microsecondsSinceEpoch}',+ 'engine': 'codex',+ 'cwd': config['workspace'],+ };+ final created = await rpc('agent_create', request);+ expect(created['state'], 'created');+ final id = (created['agent'] as Map)['id'] as String;+ final retry = await rpc('agent_create', request);+ expect(+ (retry['agent'] as Map)['id'],+ id,+ reason: 'A retry must not spawn a second agent',+ );+ expect((await rpc('agents_list'))['agents'], hasLength(1));+ await attach(id);+ await echo('hello-$route-世界');+ keyframes.clear();+ terminal!.resize(110, 33);+ await until(+ 'resized keyframe',+ () => keyframes.any((frame) => frame.cols == 110 && frame.rows == 33),+ );++ // Abrupt transport loss must release the old controller's lease.+ await connection!.close();+ await connect(route);+ await attach(id);+ await echo('reconnected-$route');+ final restarted = await rpc('agent_restart', {'agentId': id});+ expect((restarted['agent'] as Map)['id'], id);+ await terminal!.close();+ await attach(id);+ await echo('restarted-$route');++ // Restart only the disposable daemon. The pane and its identity survive.+ await restartDaemon(route);+ await until('agent restored after daemon restart', () async {+ final agents = (await rpc('agents_list'))['agents'] as List;+ return agents.length == 1 && (agents.single as Map)['id'] == id;+ });+ await attach(id);+ await echo('daemon-restored-$route');+ await terminal!.close();+ expect((await rpc('agent_delete', {'agentId': id}))['deleted'], isTrue);+ await until(+ 'agent deleted',+ () async => ((await rpc('agents_list'))['agents'] as List).isEmpty,+ );+ },+ timeout: const Timeout(Duration(minutes: 4)),+ );+ }+ test(+ 'domain harness materializes its workspace, viewer and verdict',+ () async {+ await connect('local');+ final catalog = (await rpc('dsh_list'))['dsh'] as List;+ expect(+ catalog.any(+ (row) =>+ (row as Map)['id'] == 'fixture/example' &&+ row['installed'] == true,+ ),+ isTrue,+ );+ final created = await rpc('agent_create', {+ 'creationId': 'dsh-stack-${DateTime.now().microsecondsSinceEpoch}',+ 'engine': 'codex',+ 'cwd': config['workspace'],+ 'dsh': 'fixture/example',+ });+ final id = (created['agent'] as Map)['id'] as String;+ final project = config['workspace'] as String;+ expect(+ await File('$project/example.txt').readAsString(),+ contains('Fixture artifact'),+ );+ expect(+ await File('$project/AGENTS.md').readAsString(),+ contains('Fixture instructions'),+ );+ expect(await Link('$project/.agents/skills/example').exists(), isTrue);+ Map<String, dynamic>? harness;+ await until('domain viewer advertised', () async {+ final agent =+ ((await rpc('agents_list'))['agents'] as List).single as Map;+ harness = Map<String, dynamic>.from(agent);+ return harness!['viewerUrl'] != null;+ });+ final http = HttpClient();+ try {+ final request = await http.getUrl(+ Uri.parse(harness!['viewerUrl'] as String),+ );+ final response = await request.close();+ expect(await response.transform(utf8.decoder).join(), 'Fixture viewer');+ } finally {+ http.close(force: true);+ }+ await Directory('$project/.harness').create(recursive: true);+ await File('$project/.harness/verdict.json').writeAsString(+ jsonEncode({+ 'spec': 1,+ 'ready': true,+ 'summary': 'Fixture checked',+ 'artifact': 'example.txt',+ 'findings': [],+ 'phases': [+ {+ 'id': 'build',+ 'name': 'Build',+ 'state': 'done',+ 'artifact': 'example.txt',+ },+ ],+ }),+ );+ await until('verdict propagated', () async {+ final agent =+ ((await rpc('agents_list'))['agents'] as List).single as Map;+ final verdict = agent['verdict'] as Map?;+ return verdict?['ready'] == true &&+ (verdict?['phases'] as List?)?.length == 1;+ });+ await restartDaemon('local');+ await until('harness restored after daemon restart', () async {+ final agents = (await rpc('agents_list'))['agents'] as List;+ if (agents.length != 1) return false;+ final agent = agents.single as Map;+ return agent['id'] == id &&+ agent['dsh'] == 'fixture/example' &&+ agent['viewerUrl'] != null &&+ (agent['verdict'] as Map?)?['ready'] == true;+ });+ final restarted = await rpc('agent_restart', {'agentId': id});+ expect((restarted['agent'] as Map)['dsh'], 'fixture/example');+ await attach(id);+ await echo('harness-restarted');+ await terminal!.close();+ await rpc('agent_delete', {'agentId': id});+ await until(+ 'harness deleted',+ () async => ((await rpc('agents_list'))['agents'] as List).isEmpty,+ );+ },+ timeout: const Timeout(Duration(minutes: 2)),+ );++ test('remote terminal traffic crossed the encrypted backend path', () async {+ final http = HttpClient();+ try {+ final request = await http.getUrl(+ Uri.parse('http://127.0.0.1:${config['controlPort']}/stats'),+ );+ final response = await request.close();+ final stats =+ jsonDecode(await response.transform(utf8.decoder).join()) as Map;+ expect(stats['encryptedFrames'], greaterThan(10));+ } finally {+ http.close(force: true);+ }+ });++ test('daemon restarts have no uncaught exceptions', () async {+ final log = await File('${config['logs']}/daemon.log').readAsString();+ expect(log, isNot(contains('[fatal-guard]')));+ });+}