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): keep layout choices stable across desk sync (#466)
Dee249e0f9a1e95
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 746bbf0ae..57dd4bef4 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -154,6 +154,11 @@ jobs:E2E_PORT: 19297HN_SOCKET_NAME: hn-ci-e2erun: bash tests/e2e.sh+ - name: Layout keys and shared desk synchronization+ env:+ HN_LAYOUT_TEST_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tui+ HN_LAYOUT_TEST_PORT: 19801+ run: python3 -u tests/layout-sync.py- name: Terminal lease expiry and stalled-open recoveryenv:HN_RECONNECT_TEST_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tuidiff --git a/docs/research/2026-09-29-hn-layout-sync.md b/docs/research/2026-09-29-hn-layout-sync.mdnew file mode 100644index 000000000..4b1ae7a16--- /dev/null+++ b/docs/research/2026-09-29-hn-layout-sync.md@@ -0,0 +1,47 @@+# hn layout changes survive desk synchronization++C-b Space could briefly select a layout and then return to the previous arrangement. Two+independent reproductions explain this:++- A backend predating `layout.tmux` rejects the field. hn retries without it, then treats its own+ accepted reply as a remote layout change and rebuilds the previous desktop preset.+- Fitting a received layout to a differently sized terminal queued a resize notification that+ also published another desk layout. Two clients could repeatedly send their fitted sizes back.++The fix distinguishes the last observed desk document from a local edit, recognizes accepted+layout writes, and keeps unsent input until it can be saved. Desk writes run in order, including+legacy retries, in batches of at most 200 operations. Only a schema rejection (HTTP 400) triggers+legacy fallback; an outage does not permanently disable native layouts. Terminal fitting still+fires the tmux resize hook, but only explicit arrangement/divider edits publish a desk layout.+Genuine remote layout changes and pane membership changes still reconcile normally.++## Reproduction and verification++`tui/tests/layout-sync.py` runs real hn clients inside private tmux PTYs. It covers the actual+C-b Space sequence, all seven named layouts, divider sizes, delayed older saves, a transient+500, read-only desk mode, unrelated desk updates, intentional remote layouts, large edit bursts,+and differently sized clients without an echo loop. It rejects ports outside 19800–19809, freezes+the tested binary, uses disposable homes and explicit socket names, and waits for its clients to+exit before deleting their homes.++```sh+CARGO_TARGET_DIR=/tmp/hn-layout-target cargo test --manifest-path tui/Cargo.toml --release --offline+CARGO_TARGET_DIR=/tmp/hn-layout-target cargo build --manifest-path tui/Cargo.toml --release --offline+HN_LAYOUT_TEST_BINARY=/tmp/hn-layout-target/release/harness-tui \+ HN_LAYOUT_TEST_PORT=19801 python3 -u tui/tests/layout-sync.py+```++There are 132 Rust tests, including reconciliation, legacy acknowledgements, queued input and+terminal fitting. The existing e2e suite also passed on macOS. The on-demand CI workflow runs the+new layout suite on both Linux x86-64 and ARM64 along with the existing checks.++`tui/tests/viewer-live.mjs` additionally seeds two disposable harnesses in the real backend desk,+opens a real hn PTY over the real daemon, sends C-b Space, verifies the stored native layout, and+checks that a remote rename leaves its geometry and pane identities intact. Its existing browser+and terminal recovery checks remain enabled. The stack is isolated on one physical Mac with real+MongoDB, Redis, backend, daemon, tmux and Chrome; OAuth and the model process are fixtures. This+is not a production-account or separate-physical-computer test.++An old backend still cannot store the exact tmux geometry for a future client. This change keeps+that geometry stable in the current client; full native layout persistence requires a backend+that supports `layout.tmux`. No release or installed hn binary is changed by these tests.diff --git a/tui/src/app.rs b/tui/src/app.rsindex 037b0da58..88673f3b9 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -316,6 +316,8 @@ pub struct Tab {/// The desk's layout document for this tab, kept whole: a preset chosen here updates its entry/// and leaves the sizes other windows saved alone.pub layout: Value,+ /// Last layout observed on the desk, separate from the local edit awaiting its reply.+ pub desk_layout: Value,}impl Tab {@@ -327,7 +329,7 @@ impl Tab {pub fn home() -> Tab { Tab::with_wid("home", NO_WID) }/// A window with the id it had (a session another client kept, the desk's).pub fn with_wid(name: &str, wid: u64) -> Tab {- Tab { id: Uuid::new_v4().simple().to_string(), wid: std::cell::Cell::new(wid), size: None, name: name.to_string(), named: false, home: false, root: None, focus: None, zoomed: false, last: Vec::new(), order: Vec::new(), points: HashMap::new(), alerts: 0, last_output: Instant::now(), activity: crate::format::now_secs(), layout_at: None, on_desk: false, sync: false, first_named: false, layout: json!({}) }+ Tab { id: Uuid::new_v4().simple().to_string(), wid: std::cell::Cell::new(wid), size: None, name: name.to_string(), named: false, home: false, root: None, focus: None, zoomed: false, last: Vec::new(), order: Vec::new(), points: HashMap::new(), alerts: 0, last_output: Instant::now(), activity: crate::format::now_secs(), layout_at: None, on_desk: false, sync: false, first_named: false, layout: json!({}), desk_layout: json!({}) }}/// Its @N, numbered now if it has none yet.pub fn wid(&self) -> u64 {@@ -531,8 +533,12 @@ pub struct App {orphans: HashMap<Uuid, (Instant, Vec<proto::Frame>)>,/// Native exit notices can race the same terminal_ready callback as its first frame.orphan_exits: HashMap<Uuid, (Instant, pane::Exit)>,- /// Desk writes sent and not yet answered; while any are out, the desk is not reconciled.- desk_inflight: u32,+ /// One desk write at a time: an older layout must not land after a newer choice.+ desk_inflight: bool,+ desk_pending: Vec<Value>,+ /// Accepted layouts since the last reconciliation. Their replies acknowledge our local+ /// geometry, including when an older backend can store only the desktop preset.+ desk_acked_layouts: HashMap<String, Value>,/// The desk moved while writes were out: fetch it once they land.desk_stale: bool,/// tmux's s->lastw: the windows current before, the most recent first, by tab id — C-b l goes@@ -959,7 +965,9 @@ impl App {status_ranges: Vec::new(),orphans: HashMap::new(),orphan_exits: HashMap::new(),- desk_inflight: 0,+ desk_inflight: false,+ desk_pending: Vec::new(),+ desk_acked_layouts: HashMap::new(),desk_stale: false,lastw: Vec::new(),terminal_focused: true,@@ -4429,7 +4437,10 @@ impl App {if &old.3 != focus && old.3.is_some() { crate::commands::notify(self, "window-pane-changed", Some(w), None) }}if before.current != now.current && before.current.is_some() { let (sid, name) = (self.session_id, self.session_name()); crate::commands::notify_session(self, "session-window-changed", sid, &name, None) }- for id in resized { if let Some(w) = at(self, &id) { self.layout_changed(w) } }+ // Fitting a shared layout to this terminal fires tmux's resize hook, but is not+ // a new desk arrangement. Publishing it makes differently sized clients resize+ // one another indefinitely. Explicit layout/divider edits use layout_changed.+ for id in resized { if let Some(w) = at(self, &id) { crate::commands::notify(self, "window-layout-changed", Some(w), None) } }// Pane focus (window_pane_update_focus), where tmux looks again: a window's active pane// that changed and a window that became current only with focus-events; a window whose// active pane went away (window_lost_pane), and the client's own focus, always.@@ -5001,10 +5012,10 @@ impl App {}fn fetch_desk(&mut self) {- if self.desk_inflight > 0 { self.desk_stale = true; return }+ if self.desk_inflight { self.desk_stale = true; return }let port = self.port;self.spawn(async move { http_json(port, "GET", "/api/desk", None).await }, |app, desk| {- if app.desk_inflight > 0 { app.desk_stale = true; return }+ if app.desk_inflight { app.desk_stale = true; return }if let Ok(desk) = desk { app.apply_desk(&desk) }if !app.desk_answered { app.desk_answered = true; app.maybe_start_shell() }});@@ -5026,6 +5037,7 @@ impl App {let revision = desk.get("revision").and_then(Value::as_i64).unwrap_or(0);if revision <= self.desk_revision { return }self.desk_revision = revision;+ let acknowledged = std::mem::take(&mut self.desk_acked_layouts);let Some(rows) = desk.get("tabs").and_then(Value::as_array) else { return };let first_load = self.tabs.iter().all(|t| !t.on_desk);let mut seen = Vec::new();@@ -5045,7 +5057,13 @@ impl App {// stays as automatic-rename gives it here, from what the window runs.if named { tab.name = name; tab.named = true } else if tab.named { tab.named = false }tab.on_desk = true;- let relayout = tab.layout != layout_doc;+ // A reply to our own write is an acknowledgement, not a request to+ // arrange again. In particular, a legacy desk omits layout.tmux. Also+ // keep input queued in this event batch until its layout is sent.+ let relayout = tab.desk_layout != layout_doc && tab.layout != layout_doc+ && acknowledged.get(&id) != Some(&layout_doc)+ && !self.desk_layouts.contains(&id);+ tab.desk_layout = layout_doc.clone();tab.layout = layout_doc;if relayout && missing_is_empty(&tab.panes(), &panes, &self.panes) {let ids = tab.panes();@@ -5077,6 +5095,7 @@ impl App {let Some(mut tab) = self.sessions.iter().flat_map(|s| s.tabs.iter()).find(|t| t.id == id && t.root.is_some()).cloned() else { continue };tab.alerts = 0;tab.on_desk = true;+ tab.desk_layout = layout_doc.clone();tab.layout = layout_doc;if named { tab.name = name; tab.named = true }let at = rows.iter().position(|r| r.get("id").and_then(Value::as_str) == Some(tab.id.as_str())).unwrap_or(self.tabs.len()).min(self.tabs.len());@@ -5090,6 +5109,7 @@ impl App {tab.id = id;tab.named = named;tab.on_desk = true;+ tab.desk_layout = layout_doc.clone();tab.layout = layout_doc;let (w, h) = (self.size.0, self.size.1.saturating_sub(2));tab.root = desk_root(&tab.layout, preset, &ids, w, h);@@ -5146,23 +5166,36 @@ impl App {pub fn desk_op(&mut self, op: Value) { self.desk_ops(vec![op]) }- /// Send ops as one write. The reply is the whole desk, other windows' changes included; it is- /// reconciled only when none of this window's writes are still out — reconciling to a desk that- /// has the tab but not yet its pane would close the tab this window just made.+ /// Preserve input order across writes, including the retry for an older desk schema.+ /// Only reconcile once the queue drains, so an earlier reply cannot undo a later edit.pub fn desk_ops(&mut self, ops: Vec<Value>) {if self.desk_mode != DeskMode::Sync || !self.session_desk || ops.is_empty() { return }- // A layout's tmux form (layout.tmux) goes only to a desk that keeps it: one that refuses- // it (a backend from before it) is sent the layout without it from then on.+ self.desk_pending.extend(ops);+ self.send_desk_ops();+ }++ fn send_desk_ops(&mut self) {+ if self.desk_inflight || self.desk_pending.is_empty() { return }let strip = |ops: &[Value]| -> Vec<Value> { ops.iter().cloned().map(|mut o| { if let Some(l) = o.get_mut("layout").and_then(Value::as_object_mut) { l.remove("tmux"); } o }).collect() };+ // The backend accepts at most 200 operations per request.+ let ops: Vec<Value> = self.desk_pending.drain(..self.desk_pending.len().min(200)).collect();let ops = if self.desk_no_tmux { strip(&ops) } else { ops };- let tried_tmux = ops.iter().any(|o| o.pointer("/layout/tmux").is_some());- let again = tried_tmux.then(|| strip(&ops));+ let again = ops.iter().any(|o| o.pointer("/layout/tmux").is_some()).then(|| strip(&ops));+ let layouts: HashMap<String, Value> = ops.iter().filter(|o| o["op"] == "tab.layout")+ .filter_map(|o| Some((o["id"].as_str()?.to_string(), o["layout"].clone()))).collect();let port = self.port;- self.desk_inflight += 1;+ self.desk_inflight = true;self.spawn(async move { http_json(port, "POST", "/api/desk/ops", Some(&json!({ "ops": ops }))).await }, move |app, reply| {- app.desk_inflight = app.desk_inflight.saturating_sub(1);- if let (Err(_), Some(ops)) = (&reply, again) { app.desk_no_tmux = true; return app.desk_ops(ops) }- if app.desk_inflight > 0 { app.desk_stale = true; return }+ app.desk_inflight = false;+ // Network/auth/server failures do not mean the schema lacks tmux layouts.+ if let (Err(error), Some(ops)) = (&reply, again) { if error.code == "HTTP_400" {+ app.desk_no_tmux = true;+ app.desk_pending.splice(0..0, ops);+ app.send_desk_ops();+ return;+ } }+ if reply.is_ok() { app.desk_acked_layouts.extend(layouts) }+ if !app.desk_pending.is_empty() { app.desk_stale = true; app.send_desk_ops(); return }match reply {Ok(desk) => app.apply_desk(&desk),Err(_) => app.fetch_desk(),@@ -5668,3 +5701,87 @@ mod recovery_tests {app.links["test-peer"].link.as_ref().unwrap().close();}}+++#[cfg(test)]+mod desk_layout_tests {+ use super::*;++ fn fixture() -> App {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19809, sink, (120, 36));+ app.session_desk = true;+ let mut tab = Tab::with_wid("Layout test", 1);+ tab.id = "layout-test".into();+ tab.on_desk = true;+ tab.layout = json!({"presets":{"3":"columns"}});+ tab.desk_layout = tab.layout.clone();+ tab.root = layout::arrange(layout::Named::MainHorizontal, &[1, 2, 3], 120, 35, layout::Status::Top, ("80", "12"), ("0", "0"));+ tab.focus = Some(1);+ for id in 1..=3 {+ let mut pane = Pane::new(id, "layout-peer", &format!("agent-{id}"), 120, 35);+ pane.phase = Phase::Live;+ app.panes.insert(id, pane);+ }+ app.tabs = vec![tab];+ app.desk_revision = 1;+ app+ }++ fn desk(revision: i64, layout: Value) -> Value {+ json!({"revision":revision,"tabs":[{"id":"layout-test","name":"Layout test","layout":layout,+ "panes":(1..=3).map(|id| json!({"machineId":"layout-peer","agentId":format!("agent-{id}")})).collect::<Vec<_>>()}]})+ }++ fn geometry(app: &App) -> String { app.tabs[0].root.as_ref().unwrap().to_tmux() }++ #[test]+ fn unchanged_remote_layout_does_not_undo_an_unsaved_local_edit() {+ let mut app = fixture();+ let chosen = geometry(&app);+ app.tabs[0].layout["tmux"] = json!(chosen);+ // A failed save or read-only desk: a rename elsewhere bumps the revision, but this+ // tab's server layout is still what it was before the local change.+ app.apply_desk(&desk(2, json!({"presets":{"3":"columns"}})));+ assert_eq!(geometry(&app), chosen);+ // An actual subsequent layout choice elsewhere still takes effect.+ app.apply_desk(&desk(3, json!({"presets":{"3":"rows"}})));+ assert_ne!(geometry(&app), chosen);+ }++ #[test]+ fn fitting_a_shared_layout_does_not_publish_an_edit() {+ let mut app = fixture();+ app.notify_changes();+ app.size = (96, 28);+ app.fit_panes();+ assert!(!app.pending_resize_hooks.is_empty());+ app.notify_changes();+ assert!(app.pending_resize_hooks.is_empty());+ assert!(app.desk_layouts.is_empty());+ // An intentional edit still marks the window for desk synchronization.+ app.step_layout(0, true);+ assert!(app.desk_layouts.contains("layout-test"));+ }++ #[test]+ fn legacy_acknowledgement_and_queued_input_keep_exact_geometry() {+ let mut app = fixture();+ let chosen = geometry(&app);+ let accepted = json!({"presets":{"3":"mainOverGrid"}});+ app.tabs[0].layout = accepted.clone();+ app.tabs[0].layout["tmux"] = json!(chosen);+ app.desk_acked_layouts.insert("layout-test".into(), accepted.clone());+ // A preset's fallback proportions differ from tmux's explicit 12-row main pane.+ app.apply_desk(&desk(2, accepted));+ assert_eq!(geometry(&app), chosen);+ assert!(app.desk_acked_layouts.is_empty());+ // A reply and a key can be drained in one event batch, before save_if_changed.+ app.desk_layouts.insert("layout-test".into());+ app.apply_desk(&desk(3, json!({"presets":{"3":"rows"}})));+ assert_eq!(geometry(&app), chosen);+ app.desk_layouts.clear();+ app.apply_desk(&desk(4, json!({"presets":{"3":"columns"}})));+ assert_ne!(geometry(&app), chosen);+ }+}diff --git a/tui/tests/layout-sync.py b/tui/tests/layout-sync.pynew file mode 100644index 000000000..494dd7adc--- /dev/null+++ b/tui/tests/layout-sync.py@@ -0,0 +1,253 @@+#!/usr/bin/env python3+"""C-b Space and desk synchronization in real hn clients on private tmux servers.++Tests modern and legacy desk schemas, delayed writes, failures, and other clients.+HN_LAYOUT_TEST_BINARY selects the frozen build; ports are restricted to 19800..19809.+"""+import json+import os+from pathlib import Path+import re+import shlex+import shutil+import socket+import subprocess+import tempfile+import time+import urllib.request++ROOT = Path(__file__).resolve().parents[1]+PORT = int(os.environ.get('HN_LAYOUT_TEST_PORT', '19801'))+assert 19800 <= PORT <= 19807, 'refusing non-test layout ports'+TMUX = shutil.which('tmux')+assert TMUX, 'tmux is required'+BINARY = os.environ.get('HN_LAYOUT_TEST_BINARY', ROOT / 'target/release/harness-tui')+++def scenario(mode, port, read_only=False):+ base = Path(tempfile.mkdtemp(prefix='hnls-', dir='/tmp')).resolve()+ binary = base / 'hn'+ shutil.copy2(BINARY, binary)+ prefix = f'hn-layout-{os.getpid()}-{port}'+ 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='read' if read_only else 'sync',+ HN_DESKTOP='off', HARNESS_TUI_NOTIFY='off', MOCK_DEMO='1', MOCK_LAYOUT='1', MOCK_DESK=mode)+ peer_env = dict(env, HOME=str(base / 'peer'), HN_SOCKET_NAME=prefix + '-peer')+ (base / 'peer').mkdir()+ config = base / 'tmux.conf'+ config.write_text('set -g automatic-rename off\n')+ mock = None+ started = False++ def hn(*args, peer=False, ok=True):+ client_env = peer_env if peer else env+ assert 19800 <= port <= 19809 and client_env['HN_SOCKET_NAME'].startswith('hn-layout-')+ p = subprocess.run([str(binary), '-L', client_env['HN_SOCKET_NAME'], '--port', str(port),+ '-f', str(config), *args], env=client_env, cwd=base, text=True,+ capture_output=True, timeout=12)+ if ok:+ assert p.returncode == 0, (args, 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:+ assert p.returncode == 0, (args, p.stderr)+ return p.stdout.strip()++ def api(path='/api/desk', 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 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', 'main', ok=False))++ def start(peer=False):+ client_env = peer_env if peer else env+ command = shlex.join(['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',+ *[f'{k}={v}' for k, v in client_env.items()], str(binary), '-L',+ client_env['HN_SOCKET_NAME'], '--port', str(port), '-f', str(config)])+ tmux('-f', '/dev/null', 'new-session', '-d', '-s', 'peer' if peer else 'main',+ '-x', '96' if peer else '120', '-y', '32' if peer else '36', command)+ wait(lambda: 'api/handler.ts' in tmux('capture-pane', '-p', '-t', 'peer' if peer else 'main') or 'Fix flaky login test' in tmux('capture-pane', '-p', '-t', 'peer' if peer else 'main'), 'initial desk')+ wait(lambda: hn('display-message', '-p', '#{window_panes}', peer=peer) == '3', 'three desk panes')++ def layout(peer=False):+ return hn('display-message', '-p', '#{window_layout}', peer=peer)++ def columns(peer=False):+ rows = [row.split() for row in hn('list-panes', '-F', '#{pane_left} #{pane_top}', peer=peer).splitlines()]+ return len(rows) == 3 and len({r[0] for r in rows}) == 3 and len({r[1] for r in rows}) == 1++ def rows(peer=False):+ cells = [row.split() for row in hn('list-panes', '-F', '#{pane_left} #{pane_top}', peer=peer).splitlines()]+ return len(cells) == 3 and len({r[0] for r in cells}) == 1 and len({r[1] for r in cells}) == 3++ def unrelated_update():+ # A change on another computer, without changing this tab's layout.+ api('/api/desk/ops', {'ops': [{'op': 'tab.rename', 'id': 'demo-2', 'name': 'Remote rename', 'nameIsCustom': True}]})+ time.sleep(.25)++ def stable(expected, seconds=1):+ end = time.monotonic() + seconds+ while time.monotonic() < end:+ actual = layout()+ assert actual == expected, f'{mode}: layout reverted\nexpected {expected}\nactual {actual}'+ time.sleep(.1)++ try:+ with socket.socket() as probe:+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ 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):+ assert mock.poll() is None, mock.stderr.read().decode() if mock.poll() is not None else ''+ try:+ api('/api/status')+ break+ except OSError:+ time.sleep(.05)+ else:+ raise AssertionError('mock startup timeout')+ started = True+ start()+ before = layout()+ tmux('send-keys', '-t', 'main', 'C-b', 'Space')+ wait(columns, 'C-b Space must select even-horizontal and keep it')+ chosen = layout()+ assert chosen != before+ stable(chosen)+ unrelated_update()+ stable(chosen)+ print(f'PASS {mode}: real C-b Space, saved reply, unrelated desk update', flush=True)++ if read_only:+ assert not any(w for w in api('/test/layout')['writes'] if any(o['op'] == 'tab.layout' for o in w['ops']))+ else:+ for name in ['even-vertical', 'main-horizontal', 'main-horizontal-mirrored',+ 'main-vertical', 'main-vertical-mirrored', 'tiled']:+ hn('select-layout', name)+ chosen = layout()+ stable(chosen, .25)+ print(f'PASS {mode}: all seven named layouts survive acknowledgements', flush=True)++ # The server delays the first save. Without serialization the newer save wins+ # briefly, then the older save lands and puts the previous layout back.+ api('/test/layout', {'delays': [700, 0]})+ count = len(api('/test/layout')['writes'])+ hn('select-layout', 'even-horizontal')+ wait(lambda: len(api('/test/layout')['writes']) > count, 'delayed write began')+ hn('select-layout', 'even-vertical')+ assert rows()+ chosen = layout()+ stable(chosen, 1.5)+ if mode == 'normal':+ assert api()['tabs'][0]['layout']['tmux'] == chosen+ unrelated_update()+ stable(chosen, .3)+ print(f'PASS {mode}: delayed older save cannot replace the last choice', flush=True)++ first = hn('list-panes', '-F', '#{pane_id}').splitlines()[0]+ hn('resize-pane', '-t', first, '-D', '3')+ resized = layout()+ assert resized != chosen+ stable(resized, .5)+ unrelated_update()+ stable(resized, .3)+ print(f'PASS {mode}: manual divider sizes survive sync', flush=True)++ if mode == 'normal':+ # A transient failure must not permanently disable tmux layout support.+ count = len(api('/test/layout')['writes'])+ api('/test/layout', {'failures': [500]})+ hn('select-layout', 'tiled')+ wait(lambda: len(api('/test/layout')['writes']) > count, 'failed save was attempted')+ chosen = layout()+ stable(chosen, .5)+ unrelated_update()+ stable(chosen, .3)+ assert len(api('/test/layout')['writes']) == count + 2, '500 incorrectly retried as legacy schema'+ hn('select-layout', 'even-horizontal')+ chosen = layout()+ wait(lambda: api()['tabs'][0]['layout'].get('tmux') == chosen, 'native layout still sent after 500')+ stable(chosen, .3)+ print('PASS normal: transient 500 keeps local geometry and native layout capability', flush=True)++ # Enough queued edits to cross the real backend's 200-operation limit.+ api('/test/layout', {'delays': [700]})+ count = len(api('/test/layout')['writes'])+ hn('rename-window', 'Queue start')+ wait(lambda: len(api('/test/layout')['writes']) > count, 'queue blocker began')+ commands = []+ for i in range(205):+ if commands:+ commands.append(';')+ commands.extend(['rename-window', f'Queued {i}'])+ hn(*commands)+ wait(lambda: api()['tabs'][0]['name'] == 'Queued 204', 'all queued operations persisted')+ assert all(len(w['ops']) <= 200 for w in api('/test/layout')['writes'][count:])+ stable(chosen, .3)+ print('PASS normal: long edit bursts preserve order within backend batch limit', flush=True)++ count = len(api('/test/layout')['writes'])+ start(peer=True)+ wait(lambda: columns(peer=True), 'second client receives shared columns')+ tmux('resize-window', '-t', 'peer', '-x', '88', '-y', '28')+ stable(chosen, 1)+ assert len(api('/test/layout')['writes']) == count, 'fitting another terminal republished the shared layout'+ hn('select-layout', 'even-vertical', peer=True)+ wait(rows, 'explicit second-client layout reaches first client')+ stable(layout(), 1)+ assert len(api('/test/layout')['writes']) == count + 1, 'remote layout changes bounced between clients'+ print('PASS normal: two clients, different terminal sizes, deliberate remote layout change', flush=True)+ hn('kill-server', peer=True, ok=False)++ # A real remote layout choice must still apply (including in read-only mode).+ remote = {'presets': {'3': 'rows'}}+ api('/api/desk/ops', {'ops': [{'op': 'tab.layout', 'id': 'demo-1', 'layout': remote}]})+ wait(rows, 'remote preset must still apply')+ stable(layout(), .3)+ print(f'PASS {mode}: deliberate remote preset still applies', flush=True)+ finally:+ if started:+ hn('kill-server', ok=False)+ hn('kill-server', peer=True, ok=False)+ tmux('kill-server', ok=False)+ def clients():+ found = []+ 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(binary) + ' ') and f'-L {prefix}' in match[2]:+ found.append(int(match[1]))+ return found+ for pid in clients():+ try:+ os.kill(pid, 15)+ except ProcessLookupError:+ pass+ try:+ deadline = time.monotonic() + 5+ while clients() and time.monotonic() < deadline:+ time.sleep(.05)+ assert not clients(), 'layout test client did not exit'+ finally:+ if mock is not None:+ mock.terminate()+ mock.wait(timeout=5)+ shutil.rmtree(base)+++scenario('strict', PORT)+scenario('normal', PORT + 1)+scenario('normal', PORT + 2, read_only=True)diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjsindex 25db81422..25499b344 100644--- a/tui/tests/mock-daemon.mjs+++ b/tui/tests/mock-daemon.mjs@@ -150,6 +150,10 @@ const dial = { said: {}, replies: [], messages: [] }const counts = {}const windows = new Set()// Opt-in faults for reconnect.py. No real daemon or agent is involved.+// Controlled desk latency/failures for layout reconciliation tests, on private ports only.+const layoutTest = process.env.MOCK_LAYOUT === '1'+if (layoutTest && !(port >= 19800 && port <= 19809)) throw new Error('unsafe layout test port')+const layoutFaults = { delays: [], failures: [], writes: [] }const reconnect = process.env.MOCK_RECONNECT === '1'if (reconnect && !(port >= 19780 && port <= 19789)) throw new Error('unsafe reconnect test port')const connections = new Map()@@ -164,6 +168,17 @@ 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 (layoutTest && req.url === '/test/layout') {+ if (req.method === 'GET') return json(res, layoutFaults)+ let body = ''+ req.on('data', c => { body += c })+ req.on('end', () => {+ const f = JSON.parse(body)+ for (const key of ['delays', 'failures']) if (Array.isArray(f[key])) layoutFaults[key] = f[key]+ json(res, layoutFaults)+ })+ return+ }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 })),@@ -224,7 +239,16 @@ const server = http.createServer((req, res) => {// Applied as the daemon's desk store applies them (MOCK_DESK=fixed: left as it is).let body = ''req.on('data', (c) => { body += c })- req.on('end', () => {+ req.on('end', async () => {+ const delay = layoutTest ? (layoutFaults.delays.shift() || 0) : 0+ const failure = layoutTest ? (layoutFaults.failures.shift() || 0) : 0+ if (layoutTest) layoutFaults.writes.push(JSON.parse(body || '{}'))+ if (delay) await new Promise(resolve => setTimeout(resolve, delay))+ if (failure) {+ res.writeHead(failure, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ success: false, error: 'injected desk failure' }))+ return+ }let ops = []try { ops = JSON.parse(body || '{}').ops || [] } catch {}if (process.env.MOCK_DESK === 'fixed') ops = []diff --git a/tui/tests/viewer-live.mjs b/tui/tests/viewer-live.mjsindex 73a3fed67..3a7d9f0b2 100644--- a/tui/tests/viewer-live.mjs+++ b/tui/tests/viewer-live.mjs@@ -327,6 +327,54 @@ try {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')+ // A second, isolated hn client uses the real shared desk through this daemon/backend.+ // Start with stacked panes, then exercise the actual prefix key through a private PTY.+ const layoutPrefix = prefix + '-layout', outerPrefix = prefix + '-layout-outer'+ const layoutEnv = { ...hnEnv, HN_SOCKET_NAME: layoutPrefix, HARNESS_TUI_DESK: 'sync' }+ const layoutTab = randomUUID().replaceAll('-', '')+ const desk = async ops => {+ const response = await fetch(`http://127.0.0.1:${ports.daemon}/api/desk${ops ? '/ops' : ''}`, {+ method: ops ? 'POST' : 'GET', headers: { 'x-adapter-local': '1', 'content-type': 'application/json' },+ ...(ops ? { body: JSON.stringify({ ops }) } : {}),+ })+ assert.equal(response.status, 200)+ const result = await response.json()+ return result.data ?? result+ }+ const layoutHn = (...args) => {+ assert.equal(layoutEnv.PORT, String(ports.daemon)); assert.equal(layoutEnv.HN_SOCKET_NAME, layoutPrefix)+ return exec(hnBinary, ['-L', layoutPrefix, '--port', String(ports.daemon), '-f', '/dev/null', ...args], { env: layoutEnv, timeout: 15000 })+ }+ const outer = (...args) => exec(tmux, ['-L', outerPrefix, ...args], { env: layoutEnv, timeout: 15000 })+ await desk([+ { op: 'tab.create', id: layoutTab, name: 'Layout fixture', nameIsCustom: true },+ ...[agentId, controlsId].map(id => ({ op: 'pane.add', tabId: layoutTab, machineId, agentId: id })),+ { op: 'tab.layout', id: layoutTab, layout: { presets: { 2: 'rows' } } },+ ])+ cleanups.push(() => outer('kill-server').catch(() => {}))+ cleanups.push(() => layoutHn('kill-server').catch(() => {}))+ await outer('-f', '/dev/null', 'new-session', '-d', '-s', 'layout', '-x', '120', '-y', '36',+ 'env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET', hnBinary, '-L', layoutPrefix,+ '--port', String(ports.daemon), '-f', '/dev/null')+ await until('real desk panes', async () => (await outer('capture-pane', '-p', '-t', 'layout')).stdout.includes('HN_VIEWER_ENGINE_READY'))+ await until('two real desk panes', async () => (await layoutHn('display-message', '-p', '#{window_panes}')).stdout.trim() === '2')+ const paneIds = (await layoutHn('list-panes', '-F', '#{pane_id}')).stdout+ await outer('send-keys', '-t', 'layout', 'C-b', 'Space')+ await until('C-b Space changes real desk to columns', async () => {+ const positions = (await layoutHn('list-panes', '-F', '#{pane_left} #{pane_top}')).stdout.trim().split('\n').map(row => row.split(' '))+ return positions.length === 2 && positions[0][0] !== positions[1][0] && positions[0][1] === positions[1][1]+ })+ const chosen = (await layoutHn('display-message', '-p', '#{window_layout}')).stdout.trim()+ await until('real backend stores native layout', async () => (await desk()).tabs.find(t => t.id === layoutTab)?.layout?.tmux === chosen)+ await desk([{ op: 'tab.rename', id: layoutTab, name: 'Remote rename', nameIsCustom: true }])+ for (let i = 0; i < 12; i++) {+ await new Promise(resolve => setTimeout(resolve, 250))+ assert.equal((await layoutHn('display-message', '-p', '#{window_layout}')).stdout.trim(), chosen, 'real desk reply reverted the layout')+ }+ assert.equal((await layoutHn('list-panes', '-F', '#{pane_id}')).stdout, paneIds)+ pass('real C-b Space persists through daemon/backend save and remote desk updates, preserving both panes')+ await layoutHn('kill-server')+await owner.rpc('agent_delete', { agentId: controlsId }); controlsId = nullawait owner.rpc('agent_delete', { agentId }); agentId = nullcomplete = true