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
fix(hn): recover panes after terminal timeouts (#463)
Dee36ad6a9d1830
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 31fbbda44..746bbf0ae 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -99,7 +99,12 @@ jobs:# 1,871 tests over 144 files, ~30s. The four `*.real.spec.ts` / `localE2e.spec.ts` suites that# need a live tmux or Cursor are gated behind RUN_* env vars and stay skipped here —# `npm run test:tmux-real` and friends are how those are run, on a machine that has them.- - run: npx vitest run+ # The guard fuzz suite measures a wall-clock CPU budget. Sibling workers running+ # subprocess fixtures can deschedule it past that bound on a shared runner.+ # Run it separately with the same assertions and deadline; every test still runs.+ - run: npx vitest run --exclude src/pair/learn/guard.fuzz.spec.ts+ - name: Guard fuzz and bounded hostile-input time+ run: npx vitest run src/pair/learn/guard.fuzz.spec.ts- name: Verify hn launcher repair in an existing installationrun: |@@ -149,6 +154,11 @@ jobs:E2E_PORT: 19297HN_SOCKET_NAME: hn-ci-e2erun: bash tests/e2e.sh+ - name: Terminal lease expiry and stalled-open recovery+ env:+ HN_RECONNECT_TEST_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tui+ HN_RECONNECT_TEST_PORT: 19781+ run: python3 -u tests/reconnect.py- name: Browser viewer commands and SSH handoffenv:HN_VIEWER_TEST_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tuidiff --git a/cli/src/dsh/portability.integration.spec.ts b/cli/src/dsh/portability.integration.spec.tsindex e7e464bdb..cee48e96c 100644--- a/cli/src/dsh/portability.integration.spec.ts+++ b/cli/src/dsh/portability.integration.spec.ts@@ -14,7 +14,8 @@ import { buildLaunchOverrides } from '../lib/launchOverrides.js'import { createAndRegisterPane } from '../lib/createAgentPane.js'import type { RegisteredSession } from '../lib/registry.js'import type { InstalledDsh } from './installed.js'-import { readDshManifest, dshSupportedEngines } from './manifest.js'+import { readDshManifest, dshSupportedEngines, expandDshValue } from './manifest.js'+import { harnessAdapter } from './adapters.js'import { materializeWorkspace, skillDirsIn } from './materialize.js'import { prepareHarnessLaunch } from './runtime.js'import { dshListRows } from './wire.js'@@ -38,7 +39,6 @@ describe('the whole store × engine matrix', () => {for (const name of readdirSync(store).sort().filter(name => existsSync(join(store, name, 'harness.json')))) {it(`${name} exposes its content on every integrated engine without an opt-in`, () => {const original = installed(join(store, name))- expect(original.manifest.agent?.args ?? []).toEqual([])const dir = join(root, name)write(join(dir, 'harness.json'), JSON.stringify(original.manifest))if (original.manifest.agent?.instructions) {@@ -65,6 +65,13 @@ describe('the whole store × engine matrix', () => {for (const engine of PROCESS_ENGINES) {const launch = prepareHarnessLaunch(pkg, workspace, engine, engine)launches.set(engine, launch)+ // Packages may configure their default engine (KiCad does). Those flags must survive+ // its launch, but never leak into another engine; only its context flags belong there.+ const packageArgs = engine === original.manifest.engine ? original.manifest.agent?.args ?? [] : []+ expect(launch.args).toEqual([+ ...packageArgs.map(arg => expandDshValue(arg, { dsh: dir, workspace })),+ ...(harnessAdapter(engine).contextArgs?.(launch.env.HARNESS_CONTEXT_FILE!) ?? []),+ ])expect(launch.env.HARNESS_DSH).toBe(pkg.id)const context = readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')expect(context).toContain(pkg.id)diff --git a/docs/research/2026-09-29-hn-terminal-recovery.md b/docs/research/2026-09-29-hn-terminal-recovery.mdnew file mode 100644index 000000000..ab702bd5d--- /dev/null+++ b/docs/research/2026-09-29-hn-terminal-recovery.md@@ -0,0 +1,77 @@+# hn terminal recovery — 2026-09-29++The reported screens showed `The terminal closed / heartbeat timeout` and+`Could not open the terminal / TIMEOUT: no terminal_open answer within 45s`.+The original interruption is unknown. Both stuck states were reproduced with+an isolated, pre-fix hn binary; heartbeat expiry also removed a background shell.++## Change++A heartbeat lease expiry or disconnected backend now renews the affected machine's+connection and reopens its panes. An open RPC that times out or disconnects uses+the same recovery. All panes on that machine participate, including inactive+windows and split shells. Other machines keep their connections. Recovery asks+for `takeover: false`; it does not restart programs or claim another client's+keyboard. Genuine process exits, paused harnesses and permanent refusals remain+closed.++The old connection is explicitly cancelled, including RPC-held clones. Pending+requests are released on every exit, even selection failure or cancellation.+Queued events and replies from the cancelled connection cannot overwrite the+recovering panes. Opens wait until machine selection succeeds.++## Verification++- Release build and 129 Rust tests passed. New tests exercise cancellation with+ outstanding RPCs, selection refusal, stale events/replies, hidden shells,+ timeout versus permanent refusal, and selection readiness.+- `tests/reconnect.py` passed with a real hn client in a private tmux PTY. It+ reproduces expired leases across foreground/background panes, socket loss,+ real process exit, watch-only recovery, and the actual 45-second open deadline+ while WebSocket pongs still arrive. It verifies fresh connections, no leaked+ old connection, no automatic takeover/restart, and input/output after recovery.+ Both `--repro-heartbeat` and `--repro-open` failed on the pre-fix binary with+ the reported screen text.+- Existing `tests/e2e.sh`, `tests/native-terminal.py`, `tests/local-shells.py`+ and `tests/viewer.py` passed.+- `tests/viewer-live.mjs` passed all nine checks on a physical Mac with isolated+ real hn, daemon, backend, Mongo, Redis, tmux and Chrome. Its new terminal check+ suspends only its verified fixture hn process, waits for the real daemon to log+ heartbeat expiry, resumes hn, verifies an input/output round trip, and compares+ all private tmux pane IDs/process IDs before and after. OAuth and the model+ process are deterministic fixtures. Existing browser/viewer checks also passed.+- The reconnect PTY test is included in both Linux architecture jobs in CI.+- Initial full CI passed both Linux architecture jobs and the backend job. The CLI+ job found an existing store-matrix assertion requiring all package arguments to+ be empty, contradicted by KiCad's current default-engine arguments. The failure+ reproduced locally with CLI/store files identical to the base branch. The test+ now checks actual arguments on every engine, preserving default-engine flags+ and verifying they do not leak to other engines. No launch behavior changes.+ The other initial failure exceeded a 1.5-second fuzz-test budget by 10 ms; its+ unchanged targeted rerun passed. Another full run exceeded the bound by 12 ms+ on a different input. CI now runs that suite separately from sibling workers;+ all tests and the timing bound remain unchanged. A Linux viewer-fixture cleanup+ race also surfaced after its assertions passed: deleting its home could race+ the final headless-client save. Both viewer and reconnect fixtures now wait for+ their own clients to exit before removing the test home.++## Reproduce++From `tui/`, after building:++```sh+cargo build --release --offline+cargo test --release --offline+HN_RECONNECT_TEST_PORT=19781 python3 -u tests/reconnect.py+```++`HN_RECONNECT_TEST_BINARY` selects a frozen build. Ports are restricted to+19780–19789; the runner creates a disposable home, a private mock and named+hn/tmux sockets, and removes its processes afterward. `--repro-heartbeat` and+`--repro-open` isolate the original failures.++The real-daemon check uses the dependencies and isolated launch described in+[the browser integration record](2026-09-28-hn-browser-viewer.md). It does not use+an existing account, daemon, tmux server, or harness. This validates recovery on+one physical machine; it does not establish which interruption triggered the+reported remote sessions or provide exhaustive network-fault coverage.diff --git a/tui/src/app.rs b/tui/src/app.rsindex f8f77e77a..3a461b3d3 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -1185,7 +1185,7 @@ impl App {fn schedule_reconnect(&mut self, machine_id: &str) {let Some(state) = self.links.get_mut(machine_id) else { return };- state.link = None;+ if let Some(link) = state.link.take() { link.close(); }state.attempts += 1;let wait = Duration::from_millis((500 * 2u64.pow(state.attempts.min(5))).min(15_000));state.retry_at = Some(Instant::now() + wait);@@ -1194,7 +1194,9 @@ impl App {// ── machine events ───────────────────────────────────────────────────────pub fn on_machine(&mut self, machine_id: String, generation: u64, event: MachineEvent) {- let current = self.links.get(&machine_id).map(|s| s.generation) == Some(generation);+ // A cancelled link can already have queued events. Ignore them during backoff too,+ // before the replacement connection has a new generation.+ let current = self.links.get(&machine_id).is_some_and(|s| s.generation == generation && s.link.is_some());if !current { return }match event {MachineEvent::Connected => {@@ -1243,7 +1245,7 @@ impl App {}pane.dirty = true;}- if needs_link { if let Some(state) = self.links.get_mut(&machine_id) { state.link = None } }+ if needs_link { if let Some(state) = self.links.get_mut(&machine_id) { if let Some(link) = state.link.take() { link.close(); } state.retry_at = None; } }else { self.schedule_reconnect(&machine_id) }}MachineEvent::Terminal(frame) => self.on_terminal(frame),@@ -1507,7 +1509,15 @@ impl App {self.open_stream(id, false);} else {let id = pane.id;- self.after_end(id, payload.get("reason").and_then(Value::as_str).unwrap_or("the terminal closed").to_string());+ let reason = payload.get("reason").and_then(Value::as_str).unwrap_or("the terminal closed");+ if matches!(reason, "heartbeat timeout" | "backend disconnected") {+ // A lease expiry says nothing about the process. Renew the machine route+ // and all its panes, including hidden windows and split shells, without+ // restarting anything or taking the keyboard from another client.+ self.recover_streams(machine_id, reason);+ } else {+ self.after_end(id, reason.to_string());+ }}}"terminal_error" => {@@ -1607,6 +1617,13 @@ impl App {// ── streams ─────────────────────────────────────────────────────────────+ fn recover_streams(&mut self, machine_id: &str, detail: &str) {+ if let Some(state) = self.links.get(machine_id) {+ self.on_machine(machine_id.to_string(), state.generation,+ MachineEvent::Closed(RpcError::new("TERMINAL_CONNECTION_LOST", detail)));+ }+ }+/// Open (or re-open) a pane's terminal. [takeover]: take the keyboard from any other window.pub fn open_stream(&mut self, pane_id: u64, takeover: bool) {let content = self.content_size(pane_id);@@ -1624,7 +1641,10 @@ impl App {}let Some(pane) = self.panes.get_mut(&pane_id) else { return };if pane.opening { return }- let Some(link) = self.links.get(&pane.machine_id).and_then(|s| s.link.clone()) else {+ // Do not send an open before machine_select has succeeded: its reply could otherwise+ // be discarded by the selecting link, leaving this pane waiting for 45 seconds.+ let Some(link) = self.links.get(&pane.machine_id).and_then(|s| s.link.clone())+ .filter(|_| self.fleet.machine(&pane.machine_id).is_some_and(Machine::usable)) else {pane.phase = Phase::Connecting("Connecting…".into());return;};@@ -1713,6 +1733,11 @@ impl App {pane.phase = Phase::Card { title: "Could not open the terminal".into(), detail: code, keys: vec![("enter".into(), "retry".into()), (self.keymap.hint("confirm-before -p \"kill-pane #P? (y/n)\" kill-pane").unwrap_or_else(|| "C-b x".into()), "close pane".into())] };}}+ Err(error) if matches!(error.code.as_str(), "TIMEOUT" | "DISCONNECTED") => {+ // A local WebSocket pong cannot establish that the remote terminal route is+ // healthy. Drop that route so retrying cannot wait on the same stuck request.+ self.recover_streams(machine_id, &error.to_string());+ }Err(error) => {pane.phase = Phase::Card { title: "Could not open the terminal".into(), detail: error.to_string(), keys: vec![("enter".into(), "retry".into()), (self.keymap.hint("confirm-before -p \"kill-pane #P? (y/n)\" kill-pane").unwrap_or_else(|| "C-b x".into()), "close pane".into())] };}@@ -5520,3 +5545,89 @@ pub fn hostname() -> String {if raw.is_empty() { "this computer".into() } else { raw }}).clone()}++#[cfg(test)]+mod recovery_tests {+ use super::*;++ // Current-thread tests never yield to this link: it is cancelled before it can connect.+ // No daemon, disk cache, real pane or server socket is used.+ fn fixture() -> App {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, (80, 24));+ app.fleet.machines.push(Machine { id: "test-peer".into(), name: "Peer".into(), local: false, status: "running".into(), reach: Reach::Ready });+ let link = Link::spawn(app.port, "test-peer", 1, app.sink.clone());+ app.links.insert("test-peer".into(), LinkState { link: Some(link), generation: 1, attempts: 0, retry_at: None });+ for id in 1..=4 {+ let mut pane = Pane::new(id, if id == 4 { "other-peer" } else { "test-peer" }, &format!("agent-{id}"), 80, 24);+ pane.phase = Phase::Live;+ pane.stream = Some(Uuid::new_v4());+ pane.open_token = 7;+ app.panes.insert(id, pane);+ }+ app.panes.get_mut(&3).unwrap().phase = Phase::Card { title: "Paused".into(), detail: String::new(), keys: Vec::new() };+ app.panes.get_mut(&3).unwrap().stream = None;+ app.shells.insert(("test-peer".into(), "agent-2".into()));+ app+ }++ #[tokio::test]+ async fn expired_lease_recovers_hidden_shells_and_ignores_cancelled_events() {+ let mut app = fixture();+ let other = app.panes[&4].stream;+ let expired = app.panes[&2].stream.unwrap();+ app.on_machine("test-peer".into(), 1, MachineEvent::Frame { ty: "terminal_closed".into(), payload: json!({"streamId":expired.to_string(),"reason":"heartbeat timeout"}) });+ assert_eq!(app.panes.len(), 4);+ assert!(app.shells.contains(&("test-peer".into(), "agent-2".into())));+ for id in [1, 2] {+ assert!(matches!(app.panes[&id].phase, Phase::Connecting(_)));+ assert!(app.panes[&id].stream.is_none());+ assert_eq!(app.panes[&id].open_token, 8);+ }+ assert!(matches!(app.panes[&3].phase, Phase::Card { .. }));+ assert_eq!(app.panes[&4].stream, other);+ assert!(app.links["test-peer"].link.is_none());+ let retry = app.links["test-peer"].retry_at;+ assert!(retry.is_some());+ // Events already queued by the cancelled task cannot resurrect it or delay the retry.+ app.on_machine("test-peer".into(), 1, MachineEvent::Connected);+ app.on_machine("test-peer".into(), 1, MachineEvent::Closed(RpcError::new("DISCONNECTED", "")));+ assert_eq!(app.links["test-peer"].retry_at, retry);+ assert!(matches!(app.fleet.machines[0].reach, Reach::Error(_)));+ let late = Uuid::new_v4();+ app.opened(1, "test-peer", 7, (80, 24), Ok(("terminal_ready".into(), json!({"streamId":late.to_string()}))));+ assert!(app.panes[&1].stream.is_none());+ assert!(matches!(app.panes[&1].phase, Phase::Connecting(_)));+ }++ #[tokio::test]+ async fn open_timeout_and_disconnect_recover_but_protocol_refusals_do_not() {+ for code in ["TIMEOUT", "DISCONNECTED", "TERMINAL_PROTOCOL_UNSUPPORTED"] {+ let mut app = fixture();+ app.panes.get_mut(&1).unwrap().phase = Phase::Connecting("Opening…".into());+ app.panes.get_mut(&1).unwrap().opening = true;+ app.opened(1, "test-peer", 7, (80, 24), Err(RpcError::new(code, "test failure")));+ assert!(!app.panes[&1].opening);+ if code == "TERMINAL_PROTOCOL_UNSUPPORTED" {+ assert!(matches!(app.panes[&1].phase, Phase::Card { .. }));+ assert!(app.links["test-peer"].retry_at.is_none());+ app.links["test-peer"].link.as_ref().unwrap().close();+ } else {+ assert!(matches!(app.panes[&1].phase, Phase::Connecting(_)));+ assert!(app.links["test-peer"].retry_at.is_some());+ assert!(app.links["test-peer"].link.is_none());+ }+ }+ }++ #[tokio::test]+ async fn pane_waits_for_machine_selection_before_opening() {+ let mut app = fixture();+ app.fleet.machines[0].reach = Reach::Connecting;+ app.panes.get_mut(&1).unwrap().stream = None;+ app.open_stream(1, false);+ assert!(!app.panes[&1].opening);+ assert_eq!(app.panes[&1].open_token, 7);+ app.links["test-peer"].link.as_ref().unwrap().close();+ }+}diff --git a/tui/src/daemon.rs b/tui/src/daemon.rsindex 9188c62e1..c6ab56b9c 100644--- a/tui/src/daemon.rs+++ b/tui/src/daemon.rs@@ -45,12 +45,20 @@ impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send> SocketIo fotype Pending = Arc<Mutex<HashMap<String, (String, oneshot::Sender<(String, Value)>)>>>;+// Clear requests on every exit, including cancellation and failures before selection.+// Otherwise RPC clones can keep their own waiters alive until the full request deadline.+struct PendingGuard(Pending);+impl Drop for PendingGuard {+ fn drop(&mut self) { self.0.lock().unwrap().clear(); }+}+#[derive(Clone)]pub struct Link {#[allow(dead_code)]pub machine_id: String,tx: mpsc::UnboundedSender<Out>,pending: Pending,+ task: tokio::task::AbortHandle,/// Bumped per connection so the app can tell a stale link's events from the live one's.#[allow(dead_code)]pub generation: u64,@@ -61,9 +69,12 @@ impl Link {pub fn spawn(port: u16, machine_id: &str, generation: u64, sink: mpsc::UnboundedSender<Event>) -> Link {let (tx, mut rx) = mpsc::unbounded_channel::<Out>();let pending: Pending = Arc::new(Mutex::new(HashMap::new()));- let link = Link { machine_id: machine_id.to_string(), tx, pending: pending.clone(), generation };+ let guard = PendingGuard(pending.clone());+ let requests = pending.clone();let id = machine_id.to_string();- tokio::spawn(async move {+ let task = tokio::spawn(async move {+ let _guard = guard;+ let pending = requests;let emit = |event: MachineEvent| {let _ = sink.send(Event::Machine { machine_id: id.clone(), generation, event });};@@ -186,12 +197,13 @@ impl Link {}}}- // Anyone still waiting learns the socket is gone.- pending.lock().unwrap().clear();});- link+ Link { machine_id: machine_id.to_string(), tx, pending, task: task.abort_handle(), generation }}+ /// Close a failed route even when in-flight RPCs still hold clones of this link.+ pub fn close(&self) { self.task.abort(); }+pub fn send(&self, ty: &str, payload: Value) -> bool {self.tx.send(Out::Text(json!({ "type": ty, "payload": payload }).to_string())).is_ok()}@@ -272,3 +284,58 @@ fn dechunk(body: &[u8]) -> Vec<u8> {}out}++#[cfg(test)]+mod recovery_tests {+ use super::*;++ #[tokio::test]+ async fn cancel_closes_socket_and_releases_rpc_clones() {+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let (sink, mut events) = mpsc::unbounded_channel();+ let (requested, request_seen) = oneshot::channel();+ let server = tokio::spawn(async move {+ let (socket, _) = listener.accept().await.unwrap();+ let mut ws = tokio_tungstenite::accept_async(socket).await.unwrap();+ let _select = ws.next().await.unwrap().unwrap();+ ws.send(Message::text(json!({"type":"connected", "payload":{}}).to_string())).await.unwrap();+ let mut requested = Some(requested);+ while let Some(Ok(message)) = ws.next().await {+ if let Message::Text(text) = message {+ if text.contains("terminal_open") { if let Some(tx) = requested.take() { let _ = tx.send(()); } }+ }+ }+ });+ let link = Link::spawn(port, "test-peer", 1, sink);+ assert!(matches!(tokio::time::timeout(Duration::from_secs(2), events.recv()).await.unwrap(), Some(Event::Machine { event: MachineEvent::Connected, .. })));+ let clone = link.clone();+ let rpc = tokio::spawn(async move { clone.request("terminal_open", json!({}), Duration::from_secs(45)).await });+ tokio::time::timeout(Duration::from_secs(2), request_seen).await.unwrap().unwrap();+ link.close();+ link.close(); // repeated cancellation is harmless+ let result = tokio::time::timeout(Duration::from_secs(2), rpc).await.unwrap().unwrap();+ assert_eq!(result.unwrap_err().code, "DISCONNECTED");+ assert!(link.pending.lock().unwrap().is_empty());+ tokio::time::timeout(Duration::from_secs(2), server).await.unwrap().unwrap();+ assert!(!link.send("terminal_alive", json!({})));+ }++ #[tokio::test]+ async fn selection_failure_releases_pending_requests_immediately() {+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let (sink, _events) = mpsc::unbounded_channel();+ let server = tokio::spawn(async move {+ let (socket, _) = listener.accept().await.unwrap();+ let mut ws = tokio_tungstenite::accept_async(socket).await.unwrap();+ let _select = ws.next().await;+ ws.send(Message::text(json!({"type":"machine_select_error", "payload":{"error":"NO_PEER_LINK"}}).to_string())).await.unwrap();+ });+ let link = Link::spawn(port, "test-peer", 1, sink);+ let result = tokio::time::timeout(Duration::from_secs(2), link.request("agents_list", json!({}), Duration::from_secs(20))).await.unwrap();+ assert_eq!(result.unwrap_err().code, "DISCONNECTED");+ assert!(link.pending.lock().unwrap().is_empty());+ server.await.unwrap();+ }+}diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjsindex 5a54389fe..25db81422 100644--- a/tui/tests/mock-daemon.mjs+++ b/tui/tests/mock-daemon.mjs@@ -149,6 +149,14 @@ const dial = { said: {}, replies: [], messages: [] }// How many of each request the windows made (GET /test/counts), for tests of what hn asks.const counts = {}const windows = new Set()+// Opt-in faults for reconnect.py. No real daemon or agent is involved.+const reconnect = process.env.MOCK_RECONNECT === '1'+if (reconnect && !(port >= 19780 && port <= 19789)) throw new Error('unsafe reconnect test port')+const connections = new Map()+const opens = []+const inputs = []+const readOnly = new Set()+let nextConnection = 0// The questions open on this computer, as the daemon keeps them: replayed to a window as it// connects, then their ids (commander_questions_open).const openQs = new Map()@@ -156,6 +164,30 @@ let demoAsked = falseconst json = (res, body) => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ success: true, data: body })) }const server = http.createServer((req, res) => {+ if (reconnect && req.url === '/test/reconnect') {+ if (req.method === 'GET') return json(res, { opens, inputs, counts, connections: [...connections.values()].map(c => ({+ id: c.id, machine: c.machine, streams: [...c.streams].map(([id, s]) => ({ id, agent: s.agent.id })),+ })) })+ let body = ''+ req.on('data', c => { body += c })+ req.on('end', () => {+ const f = JSON.parse(body)+ if (f.action === 'watch') readOnly.add(f.agent)+ for (const c of connections.values()) {+ if (f.machine && c.machine !== f.machine) continue+ if (f.action === 'hang') c.hang = true+ if (f.action === 'disconnect') c.ws.terminate()+ if (f.action === 'close') for (const [id, s] of c.streams) {+ if (f.agent && s.agent.id !== f.agent) continue+ c.streams.delete(id)+ c.ws.send(JSON.stringify({ type: 'terminal_closed', payload: { streamId: id, reason: f.reason,+ ...(f.takenBy ? { takenBy: { name: f.takenBy } } : {}) } }))+ }+ }+ json(res, { ok: true })+ })+ return+ }if (req.url === '/api/status') return json(res, { machineId: LOCAL, signedIn: true, version: 'mock', webUrl: process.env.MOCK_WEB_URL || 'https://harness.example' })if (req.url === '/api/machines') return json(res, { machines: [{ machineId: LOCAL, name: DEMO ? 'studio' : 'mock-local', status: 'running' },@@ -238,6 +270,11 @@ const wss = new WebSocketServer({ server, path: '/api/local-ws' })wss.on('connection', (ws) => {let machine = nullconst streams = new Map() // streamId → { seq, agent }+ const connection = { id: ++nextConnection, ws, streams, machine: null, hang: false }+ if (reconnect) {+ connections.set(connection.id, connection)+ ws.on('close', () => connections.delete(connection.id))+ }const send = (type, payload) => ws.send(JSON.stringify({ type, payload }))ws.on('message', (raw, isBinary) => {if (isBinary) {@@ -246,6 +283,7 @@ wss.on('connection', (ws) => {const streamId = bytes.subarray(12, 28).toString('hex').replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5')const stream = streams.get(streamId)if (!stream) return+ if (reconnect) inputs.push({ connection: connection.id, agent: stream.agent.id, text: bytes.subarray(36).toString() })// Echo: what was typed comes back as output, Enter as a new prompt line.const text = bytes.subarray(36).toString('utf8').replace(/\r/g, '\r\n$ ')stream.screen += text@@ -255,6 +293,7 @@ wss.on('connection', (ws) => {const { type, payload = {} } = JSON.parse(String(raw))if (type === 'machine_select') {machine = payload.machineId+ connection.machine = machineif (!agents[machine]) return ws.close(4403, 'machine mismatch')send('connected', { machineId: machine, transport: 'local', localProtocolVersion: 1 })// This machine's own connections are the daemon's windows (backend.sendLocal's audience).@@ -372,6 +411,8 @@ wss.on('connection', (ws) => {return}case 'terminal_open': {+ if (reconnect) opens.push({ connection: connection.id, machine, agent: payload.agentId, takeover: payload.takeover, hung: connection.hang, at: Date.now() })+ if (reconnect && connection.hang) return // WS still answers pings; application requests do not.const target = agents[machine].find((a) => a.id === payload.agentId)if (!target || target.status !== 'active') return send('terminal_error', { requestId: payload.requestId, code: 'TERMINAL_AGENT_NOT_FOUND' })const streamId = randomUUID()@@ -380,7 +421,7 @@ wss.on('connection', (ws) => {// MOCK_PLAIN: a terminal that is only its prompt.const screen = DEMO ? demoScreen(target) : process.env.MOCK_PLAIN ? '\x1bc$ ' : `\x1bc${target.name} (mock)\r\n${banner}$ `streams.set(streamId, { seq: 1, agent: target, screen })- send('terminal_ready', { requestId: payload.requestId, streamId, agentId: target.id, readOnly: false })+ send('terminal_ready', { requestId: payload.requestId, streamId, agentId: target.id, readOnly: reconnect && readOnly.has(target.id), heldBy: { name: 'test observer' } })ws.send(frame(3, streamId, 0, Buffer.from(screen), [payload.cols, payload.rows]))return}diff --git a/tui/tests/reconnect.py b/tui/tests/reconnect.pynew file mode 100644index 000000000..e67552202--- /dev/null+++ b/tui/tests/reconnect.py@@ -0,0 +1,219 @@+#!/usr/bin/env python3+"""Real hn in a private tmux PTY, with controlled stream/connection failures.++HN_RECONNECT_TEST_BINARY overrides the build. Ports are restricted to 19780..19789.+--repro-heartbeat and --repro-open isolate the two original regressions.+"""+import json+import os+from pathlib import Path+import re+import shlex+import shutil+import socket+import subprocess+import sys+import tempfile+import time+import urllib.request++ROOT = Path(__file__).resolve().parents[1]+PORT = int(os.environ.get('HN_RECONNECT_TEST_PORT', '19781'))+PREFIX = f'hn-reconnect-{os.getpid()}'+if not 19780 <= PORT <= 19789:+ raise SystemExit('refusing non-test reconnect port')+TMUX = shutil.which('tmux')+if not TMUX:+ raise SystemExit('tmux is required')+LOCAL = 'mock0000000000000000000000000001'+REMOTE = 'mock0000000000000000000000000002'+BASE = Path(tempfile.mkdtemp(prefix='hnrc-', dir='/tmp')).resolve()+HN = BASE / 'hn'+shutil.copy2(os.environ.get('HN_RECONNECT_TEST_BINARY', ROOT / 'target/release/harness-tui'), HN)+ENV = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'TZ') if k in os.environ}+ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(PORT),+ TERM='xterm-256color', SHELL='/bin/sh', HARNESS_TUI_DESK='off',+ HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off', MOCK_RECONNECT='1')+CONF = BASE / 'tmux.conf'+CONF.write_text('set -g automatic-rename off\nset -g pane-border-status off\n')+++def hn(*args, ok=True):+ assert 19780 <= PORT <= 19789 and PREFIX.startswith('hn-reconnect-')+ p = subprocess.run([str(HN), '-L', PREFIX, '--port', str(PORT), '-f', str(CONF), *args],+ env=ENV, cwd=BASE, text=True, capture_output=True, timeout=12)+ if ok and p.returncode:+ raise AssertionError((args, p.returncode, p.stdout, p.stderr))+ return p.stdout.strip()+++def tmux(*args, ok=True):+ p = subprocess.run([TMUX, '-L', PREFIX + '-outer', *args], env=ENV, cwd=BASE,+ text=True, capture_output=True, timeout=10)+ if ok and p.returncode:+ raise AssertionError((args, p.stderr))+ return p.stdout+++def api(path='/test/reconnect', body=None):+ req = urllib.request.Request(f'http://127.0.0.1:{PORT}{path}',+ data=None if body is None else json.dumps(body).encode(),+ headers={'Content-Type': 'application/json'})+ with urllib.request.urlopen(req, timeout=2) as response:+ return json.load(response)['data']+++def fault(action, **kw):+ return api(body={'action': action, **kw})+++def wait(fn, label, seconds=8):+ end = time.monotonic() + seconds+ while time.monotonic() < end:+ if fn():+ return+ time.sleep(.05)+ raise AssertionError(label + '\n' + tmux('capture-pane', '-p', '-t', 'test'))+++def live(machine=None):+ return {s['agent'] for c in api()['connections'] if machine is None or c['machine'] == machine for s in c['streams']}+++def screen():+ return tmux('capture-pane', '-p', '-t', 'test')+++panes = {}+++def pane_for(agent):+ return panes[agent]+++def echo(agent, marker):+ pane = pane_for(agent)+ hn('select-window', '-t', pane)+ hn('select-pane', '-t', pane)+ hn('send-keys', '-t', pane, '-l', marker)+ wait(lambda: marker in hn('capture-pane', '-p', '-t', pane), 'input should echo after recovery')+++mock = None+try:+ # Binding first catches another test using our port, before any request is made.+ with socket.socket() as probe:+ probe.bind(('127.0.0.1', PORT))+ mock = subprocess.Popen(['node', str(ROOT / 'tests/mock-daemon.mjs'), str(PORT)], env=ENV,+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)+ for _ in range(100):+ if mock.poll() is not None:+ raise AssertionError(mock.stderr.read().decode())+ try:+ api('/api/status')+ break+ except OSError:+ time.sleep(.05)+ else:+ raise AssertionError('mock startup timeout')+ command = shlex.join(['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',+ *[f'{k}={v}' for k, v in ENV.items()], str(HN), '-L', PREFIX,+ '--port', str(PORT), '-f', str(CONF)])+ tmux('-f', '/dev/null', 'new-session', '-d', '-s', 'test', '-x', '120', '-y', '36', command)+ wait(lambda: 'Mock terminal (mock)' in screen(), 'initial shell')+ agents = {a['name']: a['id'] for a in api('/test/dial')['agents']}+ shell, claude, codex, remote = (agents[n] for n in ('Mock terminal', 'Mock Claude', 'Mock Codex', 'Remote shell'))++ panes[shell] = hn('display-message', '-p', '#{pane_id}')+ if '--repro-open' not in sys.argv:+ hn('open-harness', '-s', 'Mock Claude')+ panes[claude] = hn('display-message', '-p', '#{pane_id}')+ hn('open-harness', '-h', '-s', 'Mock Codex')+ panes[codex] = hn('display-message', '-p', '#{pane_id}')+ hn('open-harness', '-d', '-s', 'Remote shell')+ panes[remote] = next(p for p in hn('list-panes', '-a', '-F', '#{pane_id}').splitlines() if p not in panes.values())+ wait(lambda: {shell, claude, codex, remote} <= live(), 'all foreground/background panes live')+ before = api()+ fault('close', machine=LOCAL, reason='heartbeat timeout')+ wait(lambda: {shell, claude, codex} <= live(LOCAL), 'heartbeat expiry should reopen every pane, including inactive shell')+ after = api()+ assert [c['id'] for c in before['connections'] if c['machine'] == REMOTE] == [c['id'] for c in after['connections'] if c['machine'] == REMOTE], 'unrelated machine was redialled'+ assert len([c for c in after['connections'] if c['machine'] == LOCAL]) == 1, 'old connection leaked'+ retries = after['opens'][len(before['opens']):]+ assert retries and all(o['takeover'] is False for o in retries), retries+ echo(claude, 'RECOVERED_HEARTBEAT')+ assert set(panes.values()) == set(hn('list-panes', '-a', '-F', '#{pane_id}').splitlines()), 'recovery lost a pane'+ print('PASS: heartbeat expiry, all panes, inactive shell, machine isolation, no takeover, input echo', flush=True)+ if '--repro-heartbeat' in sys.argv:+ sys.exit(0)++ # A connection reset uses the same recovery; a stale stream event must not win later.+ fault('disconnect', machine=LOCAL)+ wait(lambda: {shell, claude, codex} <= live(LOCAL), 'socket close should recover')+ echo(codex, 'RECOVERED_SOCKET')+ print('PASS: dropped socket recovery', flush=True)++ # Genuine terminal/process closure remains a card; it must not restart the program.+ before_count = len(api()['opens'])+ fault('close', machine=LOCAL, agent=claude, reason='process exited')+ hn('select-window', '-t', pane_for(claude))+ wait(lambda: 'The terminal closed' in screen(), 'real exit should remain closed')+ time.sleep(1.5)+ assert len(api()['opens']) == before_count, 'real exit retried automatically'+ assert claude not in live()+ print('PASS: genuine process exit stays closed', flush=True)++ # Reconnect a watch-only pane and ensure it never asks for control.+ fault('watch', agent=codex)+ before_count = len(api()['opens'])+ fault('close', machine=LOCAL, agent=codex, reason='heartbeat timeout')+ wait(lambda: {shell, codex} <= live(LOCAL), 'watch-only recovery')+ assert claude not in live(), 'reconnect reopened a genuinely closed pane'+ assert all(o['takeover'] is False for o in api()['opens'][before_count:])+ assert hn('display-message', '-p', '-t', pane_for(codex), '#{pane_dead}') == '0'+ print('PASS: recovery preserves ended panes and watch-only ownership', flush=True)++ # Hold terminal_open while the WebSocket continues answering pings. A fresh connection+ # is required; reopening against the old route would just hit the same 45-second stall.+ fault('hang', machine=REMOTE)+ if '--repro-open' not in sys.argv:+ hn('kill-pane', '-t', pane_for(remote))+ before = api()+ hn('open-harness', '-s', 'Remote shell')+ panes[remote] = hn('display-message', '-p', '#{pane_id}')+ wait(lambda: any(o['hung'] for o in api()['opens'][len(before['opens']):]), 'stalled open requested')+ started = time.monotonic()+ wait(lambda: remote in live(REMOTE), 'timed-out open should redial and recover', seconds=55)+ assert time.monotonic() - started >= 40, 'test did not exercise the real 45-second deadline'+ retries = api()['opens'][len(before['opens']):]+ assert retries[-1]['connection'] != retries[0]['connection']+ assert retries[-1]['takeover'] is False+ assert len([c for c in api()['connections'] if c['machine'] == REMOTE]) == 1+ echo(remote, 'RECOVERED_OPEN_TIMEOUT')+ assert not api()['counts'].get('agent_restart', 0), 'transport recovery restarted a program'+ print('PASS: real 45-second timeout despite live WS pongs, fresh route, no restart, input echo', flush=True)+finally:+ hn('kill-server', ok=False)+ tmux('kill-server', ok=False)+ # Kill only processes using this test's frozen binary and explicit socket prefix.+ for row in subprocess.check_output(['ps', '-ax', '-o', 'pid=,command='], text=True).splitlines():+ match = re.match(r'\s*(\d+)\s+(.*)', row)+ if match and match[2].startswith(str(HN) + ' ') and f'-L {PREFIX} ' in match[2]:+ try:+ os.kill(int(match[1]), 15)+ except ProcessLookupError:+ pass+ def clients():+ rows = subprocess.check_output(['ps', '-ax', '-o', 'pid=,command='], text=True).splitlines()+ return [row for row in rows if len(parts := row.strip().split(None, 1)) == 2+ and parts[1].startswith(str(HN) + ' ') and f'-L {PREFIX} ' in parts[1]]+ try:+ deadline = time.monotonic() + 5+ while clients() and time.monotonic() < deadline:+ time.sleep(.05)+ assert not clients(), 'recovery test clients did not exit'+ finally:+ if mock is not None:+ mock.terminate()+ mock.wait(timeout=5)+ shutil.rmtree(BASE)diff --git a/tui/tests/viewer-live.mjs b/tui/tests/viewer-live.mjsindex d46410c63..73a3fed67 100644--- a/tui/tests/viewer-live.mjs+++ b/tui/tests/viewer-live.mjs@@ -298,6 +298,35 @@ try {await page.close()assert.ok((await owner.rpc('agents_list')).agents.some(a => a.id === agentId))pass('closing the browser leaves the harness running')++ // A real daemon expires the stream if this disposable hn process stops sending alive/acks.+ // Its tmux program must survive; waking the client must restore the existing pane and input.+ await hn('new-session', '-d', '-s', 'recovery')+ await hn('open-harness', '-s', agentId)+ const terminalPane = (await hn('display-message', '-p', '#{pane_id}')).stdout.trim()+ await until('real terminal before pause', async () => (await hn('capture-pane', '-p', '-t', terminalPane)).stdout.includes('HN_VIEWER_ENGINE_READY'))+ const terminalBefore = (await exec(tmux, ['-L', prefix, 'list-panes', '-a', '-F', '#{pane_id} #{pane_pid}'], { env: daemonEnv })).stdout+ const hnPid = Number((await hn('display-message', '-p', '#{pid}')).stdout.trim())+ assert.ok(Number.isInteger(hnPid) && hnPid > 1)+ const command = (await exec('ps', ['-p', String(hnPid), '-o', 'command='])).stdout.trim()+ assert.ok(command.startsWith(hnBinary + ' ') && command.includes(`-L ${prefix} `), 'only stop this fixture hn')+ const daemonLog = join(root, 'daemon.log')+ const logStart = (await readFile(daemonLog, 'utf8')).length+ process.kill(hnPid, 'SIGSTOP')+ try {+ await until('actual daemon heartbeat expiry', async () => (await readFile(daemonLog, 'utf8')).slice(logStart).includes("reason: 'heartbeat timeout'"), 45000)+ } finally {+ process.kill(hnPid, 'SIGCONT')+ }+ // capture-pane contains the previous screen during reconnect; the input round trip proves live I/O.+ await until('real terminal accepts input after lease expiry', async () => {+ await hn('send-keys', '-t', terminalPane, '-l', 'HN_LEASE_RECOVERED')+ return (await hn('capture-pane', '-p', '-t', terminalPane)).stdout.includes('ECHO:HN_LEASE_RECOVERED')+ }, 15000)+ const terminalAfter = (await exec(tmux, ['-L', prefix, 'list-panes', '-a', '-F', '#{pane_id} #{pane_pid}'], { env: daemonEnv })).stdout+ assert.equal(terminalAfter, terminalBefore, 'recovery must keep the same programs')+ assert.equal((await hn('display-message', '-p', '-t', terminalPane, '#{pane_id}')).stdout.trim(), terminalPane)+ pass('real daemon lease expiry recovers the same hn pane and process with working terminal input')await owner.rpc('agent_delete', { agentId: controlsId }); controlsId = nullawait owner.rpc('agent_delete', { agentId }); agentId = nullcomplete = truediff --git a/tui/tests/viewer.py b/tui/tests/viewer.pyindex d80efd45d..aa2e3a9f7 100644--- a/tui/tests/viewer.py+++ b/tui/tests/viewer.py@@ -2,6 +2,7 @@"""Exercise hn's public viewer commands against a private mock and a recording browser opener."""import jsonimport os+import signalfrom pathlib import Pathimport shutilimport shlex@@ -188,7 +189,26 @@ with tempfile.TemporaryDirectory(prefix='hnv-', dir='/tmp') as tmp:mux('kill-server', ok=False)finally:- hn('kill-server', ok=False)- mock.terminate()- try: mock.wait(timeout=5)- except subprocess.TimeoutExpired: mock.kill(); mock.wait(timeout=5)+ try:+ hn('kill-server', ok=False)+ # kill-server acknowledges before the headless client finishes saving. Deleting+ # HOME then races its final writes (rmtree: directory not empty on Linux).+ def clients():+ rows = subprocess.check_output(['ps', '-ax', '-o', 'pid=,command='], text=True).splitlines()+ return [int(pid) for row in rows if len(parts := row.strip().split(None, 1)) == 2+ for pid, command in [parts] if any(command.startswith(str(path) + ' ') for path in (binary, binary.resolve()))+ and f'-L {prefix} ' in command]+ deadline = time.monotonic() + 5+ while clients() and time.monotonic() < deadline:+ time.sleep(.05)+ for pid in clients():+ try: os.kill(pid, signal.SIGTERM)+ except ProcessLookupError: pass+ deadline = time.monotonic() + 5+ while clients() and time.monotonic() < deadline:+ time.sleep(.05)+ assert not clients(), 'viewer test clients did not exit'+ finally:+ mock.terminate()+ try: mock.wait(timeout=5)+ except subprocess.TimeoutExpired: mock.kill(); mock.wait(timeout=5)