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
feat(hn): improve pane focus and preserve layout choices (#467)
Dee25acbefd96ba
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 57dd4bef4..48214a5da 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: Pane surfaces, mouse coordinates and layout compatibility+ env:+ HN_PANE_UI_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tui+ HN_PANE_UI_PORT: 19783+ run: python3 -u tests/pane-ui.py- name: Layout keys and shared desk synchronizationenv:HN_LAYOUT_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.mdindex 4b1ae7a16..7f8239e04 100644--- a/docs/research/2026-09-29-hn-layout-sync.md+++ b/docs/research/2026-09-29-hn-layout-sync.md@@ -45,3 +45,19 @@ 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 keepsthat geometry stable in the current client; full native layout persistence requires a backendthat supports `layout.tmux`. No release or installed hn binary is changed by these tests.++## Desktop round-trip follow-up++A further two-pane regression reproduced a reset after a desktop layout save. Desktop's+serializer retains presets and sizes but omits `layout.tmux`; hn previously treated that omission+as a new remote layout. It also reacted to metadata for unrelated pane counts. Reconciliation now+compares the native layout when supplied, otherwise the effective preset for the current pane+count. Metadata-only round-trips preserve the current geometry, including unequal divider sizes.++C-b Space and every named layout use the same publication path. Where desktop has a matching+shape, hn publishes a valid preset for that pane count alongside its native geometry. Queued+choices survive reconciliation; resizing after a genuine remote choice keeps that remote preset.+The regression covers modern and legacy schemas, read-only mode, and real two-pane prefix input.+The isolated real daemon/backend test also drops native geometry as desktop serialization does,+then verifies both preservation and a deliberate subsequent remote change. All 148 Rust tests,+the layout suite, pane UI, local shell lifecycle, complete e2e and real-stack checks pass locally.diff --git a/docs/research/2026-09-29-hn-pane-ui-columns.png b/docs/research/2026-09-29-hn-pane-ui-columns.pngnew file mode 100644index 000000000..c2804d3f2Binary files /dev/null and b/docs/research/2026-09-29-hn-pane-ui-columns.png differdiff --git a/docs/research/2026-09-29-hn-pane-ui-light.png b/docs/research/2026-09-29-hn-pane-ui-light.pngnew file mode 100644index 000000000..2e051e437Binary files /dev/null and b/docs/research/2026-09-29-hn-pane-ui-light.png differdiff --git a/docs/research/2026-09-29-hn-pane-ui-rows.png b/docs/research/2026-09-29-hn-pane-ui-rows.pngnew file mode 100644index 000000000..3b088ab61Binary files /dev/null and b/docs/research/2026-09-29-hn-pane-ui-rows.png differdiff --git a/docs/research/2026-09-29-hn-pane-ui.md b/docs/research/2026-09-29-hn-pane-ui.mdnew file mode 100644index 000000000..955375dbe--- /dev/null+++ b/docs/research/2026-09-29-hn-pane-ui.md@@ -0,0 +1,102 @@+# hn pane surfaces++hn now presents terminal panes as quiet surfaces with space between them. Each pane has+an integrated title, a thin outline around the focused pane, and inset content. The status line stays+at the bottom in muted green, with tabs ordered `number:name* status`. Pane headers put the+name before the state too: `hn ⋮ · project ⑂ branch`. Quota text is compact: `Claude 100%`,+with amber or red only on the percentage. The branch appears only in pane headers; the+bottom right keeps the familiar `machine:folder` location cue. Working and waiting+indicators remain visible. Attention markers, prefix cues, inbox rows, connection notices, preview counters+and marked tree rows use text, symbols and emphasis instead of inverted badges. Cursor and+selection highlights, explicit user styles and program ANSI remain supported. Unread and bell+tabs keep their status symbols with bold text. The status bar has a continuous background;+current `*` and previous-window `-` markers stay directly after the name, before harness status.+Raw tmux format variables keep their flags.+This changes the presentation while preserving tmux keys and split structure.++++++++These images render ANSI cell captures from the real hn binary inside an isolated tmux PTY,+using mock harness output. They are terminal output, not design mockups. The rendering uses+Menlo and a representative ANSI palette; the user's terminal controls its own font and ANSI+colors.++## Geometry and compatibility++The layout tree remains responsible for named layouts, percentages, pane targeting, directional+navigation, resizing, and serialized `window_layout`. Presentation insets are calculated separately+and shared by rendering, cursor placement, PTY sizing, copy mode and application mouse input.+Position targets such as `top-left` and percentage splits use structural dimensions, so changing+the appearance cannot move the split boundaries. The original divider cells are blank gutters+and still support mouse dragging.++At normal sizes there is a one-cell gap around the pane surfaces and between adjacent panes,+one column of content padding on each side, and vertical padding where space permits. Small+panes automatically give these cells back to the program. A one-cell terminal remains responsive+and survives resizing.+The focused pane keeps the terminal's native background and full text contrast. Other panes+use `rgb(64, 64, 64)` surfaces in dark terminals, with softer text so focus reads across the+whole pane. Light terminals retain their light surface counterpart. The focused pane has a thin+outline in the existing gutter cells, which follows keyboard or mouse focus without shrinking+program content or changing its mouse coordinates. Compact panes keep their usable cells. Surface colors follow the terminal's native light/dark theme and update when it changes. The+daemon receives the surface colors so its programs agree with their surrounding padding.+Program ANSI foregrounds, backgrounds and attributes remain intact; only default colors inherit+the pane surface palette. Explicit user styles and title formats still override the defaults.++The default is `set -g @hn-look panes`. `set -g @hn-look classic` selects the previous hn line+borders. `set -g @hn-look tmux` selects tmux's appearance and unpadded content geometry. Switching applies immediately without recreating panes or changing the layout.++## Verification++The release build passes 149 Rust tests, including rectangle containment and usable minimum+sizes, adjacent surfaces, user style overrides, light/dark contrast, foreground inference and+malformed OSC color replies. The new `tui/tests/pane-ui.py`+exercises the running application with actual keys and SGR mouse input:++- Directional navigation and wrap, zoom/unzoom, copy selection, header focus and gutter dragging.+- All seven layouts and eight position targets with top, bottom and disabled pane titles.+- Identical split structure across appearances, including percentage splits on both axes.+- Application mouse coordinates after padding and after adding two status rows at the top.+- Whole-pane focus contrast through keyboard and mouse selection, and name-before-status tabs.+- Live light/dark theme changes, custom style overrides in active and inactive panes, and reported option defaults.+- Explicit program foreground/background colors; 80x24, 24x8, 6x4 and 1x1 terminals.++The main e2e suite, layout synchronization suite, local shell lifecycle suite, native terminal+suite, and terminal attribute comparisons against real tmux also passed on macOS. The full+isolated real-stack suite passed all ten checks: real daemon, backend, MongoDB, Redis, tmux and+Chrome, including viewer input, browser reconnect, terminal lease recovery and C-b Space+persistence. OAuth and model execution are fixtures. No production account, live user pane,+installed hn binary or release was changed.++The full-flow test also exposed a delayed picker refresh consuming a subsequently opened+command prompt. Refresh now checks that a picker is still open before taking the modal; a unit+regression preserves prompts, confirmations and copy mode, and e2e waits for the actual status+prompt rather than matching a colon in a pane title.++Linux CI additionally caught percentage sizes being passed through `strftime`, which rejects+a trailing percent sign on musl. Split and join sizes now expand tmux variables without implicit+time formatting, preserving `35%` and `#{client_width}%` across platforms.++Desktop saves can omit hn's exact layout. Previously that field disappearing, an empty size+map, or a preset changed for another pane count could reset the current window. Reconciliation+now checks the layout relevant to the current panes. C-b Space also publishes a matching desktop+preset when available, and queued choices survive incoming replies. A later divider edit cannot+revive an older local preset after a deliberate remote choice. The two-pane regression exercises+actual prefix keys and unequal pane sizes in modern, legacy and read-only desk modes; the real+backend/daemon check also simulates desktop serialization and a deliberate remote layout change.++The new pane test is part of both Linux x86-64 and ARM64 CI jobs. To repeat it locally:++```sh+CARGO_TARGET_DIR=/tmp/hn-pane-target cargo test --manifest-path tui/Cargo.toml --release --offline+CARGO_TARGET_DIR=/tmp/hn-pane-target cargo build --manifest-path tui/Cargo.toml --release --offline+HN_PANE_UI_BINARY=/tmp/hn-pane-target/release/harness-tui \+ HN_PANE_UI_PORT=19783 python3 -u tui/tests/pane-ui.py+```++The test freezes the binary and uses a disposable home, explicit private hn/tmux sockets and+ports guarded to 19783–19789. Its processes are stopped before the test home is removed.diff --git a/tui/README.md b/tui/README.mdindex 2f8dd303a..3757ca792 100644--- a/tui/README.md+++ b/tui/README.md@@ -69,16 +69,27 @@ tmux. `run-shell` lines run too: a plugin's `tmux …` reaches hn (the `tmux` onnever a tmux server you have running.Splits, `resize-pane`, the seven layouts, `swap-pane`, `rotate-window`, `join-pane`, `break-pane`-and `select-pane` are tmux 3.5a's own arithmetic (layout.c, window.c): the same sizes, the same-pane numbers and the same active pane after each. Use `set -g @hn-animations off` to keep+and `select-pane` are tmux 3.5a's own arithmetic (layout.c, window.c): the same split sizes, the same+pane numbers and the same active pane after each. hn draws these layouts as pane surfaces+with one-cell gaps, inset terminal content and a thin outline around the focused pane. The+surfaces follow the terminal's light/dark theme: the focused pane keeps full contrast;+inactive dark panes use `rgb(64, 64, 64)` with softer text. Light terminals keep a light counterpart.+Explicit program colors and user styles stay intact. The muted green status bar has a continuous+background, with tabs ordered `number:name* status` (previous window: `number:name- status`).+Quota warnings read `Claude 100%`, with amber or red only on the percentage. Padding+shrinks automatically in small panes. The space between panes remains a resize handle; mouse+coordinates, copy selection and PTY dimensions follow the inset content. `window_layout` keeps+the original split structure. Use `set -g @hn-animations off` to keepworking and loading indicators still. Some defaults differ, and your `.tmux.conf`-overrides each: `pane-border-status top` (each pane's title row: its harness's state and name, and+overrides each: `pane-border-status top` (each pane's title row: its harness's name and state, andits project and branch where the pane has room), `allow-set-title off` (a pane's title is itsharness's name, not what the program sets), `history-limit 10000` (agents print a lot; tmux keeps2000), `mouse on`, `set-titles on` (the terminal's title: `?2 Fix flaky login test — Harness`, the-harnesses waiting on you and the one in front; `set-titles-string` changes it), and the status line: each window's most urgent harness state before its name,-and on the right the focused pane's machine (when it is another one), project and branch —-`gpu-box:ml-lab git:(main)` — where tmux shows the pane's title. One key differs on purpose: ⇧⏎+harnesses waiting on you and the one in front; `set-titles-string` changes it), and the status line:+each window's most urgent harness state follows its name and tmux marker. Connection, quota,+fleet counts, `machine:folder` and clock sit on the right. The git branch stays in its pane+header, written `⑂ branch` without redundant punctuation.+One key differs on purpose: ⇧⏎reaches the pane as `CSI 13;2u` (a new line in an agent's prompt; tmux, without `extended-keys`,sends a plain Enter).@@ -179,22 +190,25 @@ pane counts as done and unread (`✓`) until you go to that pane.All of this is in options, which `show -g`, `show -gw` and `C-b C` print as they are:`status-left`, `status-right`, the window formats and each pane's title row(`pane-border-format`). Set them in your `~/.tmux.conf` as you would for tmux; what you set-replaces hn's. `set -g @hn-look tmux` puts back all of tmux's own: no title rows, tmux's status-line and window list.+replaces hn's. The default is `set -g @hn-look panes`. `set -g @hn-look classic` restores hn's+previous line borders. `set -g @hn-look tmux` uses tmux's appearance and+content dimensions: no padding or title rows, and tmux's status line and window list. Changing+the look takes effect immediately and preserves pane identities and the split structure.For your own formats: `#{fleet}` (the status line's counts, ready to drop into your theme) and`#{fleet_needs}` `#{fleet_failed}` `#{fleet_done}` `#{fleet_working}` `#{fleet_idle}`, `#{spinner}`,`#{pane_agent_icon}` and `#{pane_agent_state}` (needs, working, done, idle, starting, failed,paused, offline), `#{pane_agent_mark}` (the icon in its colour, as the title row draws it),`#{window_agent_icon}` and `#{window_agent_state}` (its most urgent pane's), `#{pane_project}`,-`#{pane_branch}`, `#{pane_where}` (`project git:(branch) #123` as far as it fits beside the title),+`#{pane_branch}`, `#{pane_where}` (`project ⑂ branch #123` as far as it fits beside the title),`#{pane_pr}` `#{pane_pr_state}` `#{pane_pr_url}` (the pull request for its branch), `#{pane_tokens}`and `#{fleet_tokens}` (what it, and all of them, have used: `1.2M`), `#{pane_lines}` (`+340 −52`),`#{pane_asked}` and `#{pane_did}` (what it was last asked, and what its last turn came to),`#{pane_todos}` (its plan's progress, `3/7`) and `#{pane_subagents}` (how many it has running),`#{usage}` (the agent accounts' rate limits on the focused pane's machine: `claude 5h 42% week-18% · codex 5h 3%`) and `#{usage_high}` (the one nearest its limit, from 80%; the status line shows-it reversed, so you know before you start more agents),+18% · codex 5h 3%`) and `#{usage_high}` (the one nearest its limit, from 80%). The status line uses+`#{usage_high_mark}`: `Claude 80%`, with amber on the percentage from 80%, red from 100%.+The raw `usage` and `usage_high` formats retain the reset window. Other formats:`#{pane_machine}`, `#{pane_far}` (another machine's), `#{pane_watched}` and `#{pane_watcher}`(another window has the pane to type in, and who), and `#{waiting}` (the harnesses waiting onyou).diff --git a/tui/src/app.rs b/tui/src/app.rsindex 88673f3b9..c68a72108 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -318,6 +318,8 @@ pub struct Tab {pub layout: Value,/// Last layout observed on the desk, separate from the local edit awaiting its reply.pub desk_layout: Value,+ /// A named choice awaiting publication, separate from the last observed desk document.+ desk_preset: Option<(usize, &'static str)>,}impl Tab {@@ -329,7 +331,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!({}), desk_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!({}), desk_preset: None }}/// Its @N, numbered now if it has none yet.pub fn wid(&self) -> u64 {@@ -1204,7 +1206,12 @@ impl App {/// the terminal answers OSC 11 and again when a machine connects; the daemon restyles the/// existing sessions too, as the desktop app's `theme_set` does.pub fn push_theme(&mut self) {- let Some((bg, fg)) = crate::term_out::terminal_colours() else { return };+ let Some((mut bg, mut fg)) = crate::term_out::terminal_colours() else { return };+ if self.options.pane_look() {+ let palette = crate::theme::pane_palette();+ bg = crate::tmuxconf::colour_name(palette.surface);+ fg = crate::tmuxconf::colour_name(palette.foreground);+ }let machines: Vec<String> = self.fleet.machines.iter().filter(|m| self.link(&m.id).is_some()).map(|m| m.id.clone()).collect();@@ -3434,6 +3441,7 @@ impl App {tab.root = layout::arrange(named, &ids, body.width, body.height, status, (&mw, &mh), (&ow, &oh));tab.zoomed = false;tab.layout_at = layout::Named::ALL.iter().position(|n| *n == named);+ if tab.on_desk { tab.desk_preset = named_to_desk(named, ids.len()).map(|preset| (ids.len(), preset)); }self.fit_panes();self.layout_changed(index);}@@ -3637,7 +3645,7 @@ impl App {// takes the theme's own colours — its background the terminal's background, its text the// readable opposite — so it is a visible bar in the theme (a dark bar, light text on a// dark terminal), not a transparent one, and not tmux's stock green.- if !own {+ if !own && !self.options.pane_look() && !self.options.tmux_look() {let (bg, fg, _) = crate::theme::palette();s = s.bg(bg).fg(fg);}@@ -3651,7 +3659,7 @@ impl App {// No message colours of its own and the terminal has told us what it looks like: the// message line shows the theme's readable text on the terminal's own background (left// transparent), so it blends with the theme instead of tmux's stock yellow.- if !own {+ if !own && !self.options.tmux_look() {let (_, fg, _) = crate::theme::palette();s = s.bg(Color::Reset).fg(fg);}@@ -3673,8 +3681,8 @@ impl App {layout::Status::of(&self.options.get("pane-border-status", &tab.id, None).unwrap_or_default())}- /// A pane's own cells within its tile: the status line taken off, above or below.- pub fn content_of(&self, tab: &Tab, r: Rect) -> Rect {+ /// The structural cells used by tmux navigation and divider dragging.+ pub fn layout_content_of(&self, tab: &Tab, r: Rect) -> Rect {match self.pane_status(tab) {layout::Status::Top => Rect::new(r.x, r.y + 1, r.width, r.height.saturating_sub(1)),layout::Status::Bottom => Rect::new(r.x, r.y, r.width, r.height.saturating_sub(1)),@@ -3682,6 +3690,12 @@ impl App {}}+ /// The program's actual viewport, shared by drawing, PTY resizing and mouse coordinates.+ pub fn content_of(&self, tab: &Tab, r: Rect) -> Rect {+ if self.options.pane_look() { crate::pane_frame::frame(r, self.window_area(tab), self.pane_status(tab)).content }+ else { self.layout_content_of(tab, r) }+ }+fn compute_rects(&self) -> Vec<(u64, Rect)> {let tab = self.tab();let mut out = Vec::new();@@ -4027,7 +4041,7 @@ impl App {let (w, h) = self.tabs[t].root.as_ref().map(|r| r.size()).unwrap_or((body.width, body.height));if at.dir == Dir::Horizontal { w } else { h }} else {- at.pane.and_then(|p| crate::format::content_rect(self, t, p)).map(|r| if at.dir == Dir::Horizontal { r.width } else { r.height }).unwrap_or(0)+ at.pane.and_then(|p| crate::format::layout_rect(self, t, p)).map(|r| if at.dir == Dir::Horizontal { r.width } else { r.height }).unwrap_or(0)};let size = at.size.map(|(n, pct)| if pct { cur as u32 * n as u32 / 100 } else { n as u32 });self.fit_panes_of(t);@@ -4490,9 +4504,15 @@ impl App {let Some(tab) = self.tabs.iter_mut().find(|t| t.id == id) else { continue };let Some(root) = tab.root.as_ref() else { continue };if !tab.layout.is_object() { tab.layout = json!({}) }- let now = root.to_tmux();- if tab.layout.get("tmux").and_then(Value::as_str) == Some(now.as_str()) { continue }- tab.layout["tmux"] = json!(now);+ let before = tab.layout.clone();+ tab.layout["tmux"] = json!(root.to_tmux());+ // C-b Space and select-layout use this path too. Keep the desktop's+ // corresponding shape current, instead of leaving an older preset behind.+ if let Some((count, preset)) = tab.desk_preset.take() {+ if !tab.layout.get("presets").map(Value::is_object).unwrap_or(false) { tab.layout["presets"] = json!({}) }+ tab.layout["presets"][count.to_string()] = json!(preset);+ }+ if tab.layout == before { continue }let op = json!({ "op": "tab.layout", "id": tab.id, "layout": tab.layout });self.desk_op(op);}@@ -4725,18 +4745,21 @@ impl App {let mut out = Vec::new();if let Some(root) = tab.root.as_ref() { root.rects(body, &mut out) }tab.panes().into_iter().filter_map(|id| out.iter().find(|(p, _)| *p == id).map(|(_, r)| {- let c = self.content_of(tab, *r);+ let c = self.layout_content_of(tab, *r);(id, layout::Geom { x: (c.x - body.x) as u32, y: (c.y - body.y) as u32, w: c.width as u32, h: c.height as u32 })})).collect()}/// The current window's panes as drawn (a zoomed window's one pane filling it), where their/// contents are in the window: tmux's xoff/yoff/sx/sy for the mouse.- pub fn visible_geoms(&self) -> Vec<(u64, layout::Geom)> {+ pub fn visible_geoms(&self) -> Vec<(u64, layout::Geom)> { self.visible_geoms_for(true) }+ pub fn visible_layout_geoms(&self) -> Vec<(u64, layout::Geom)> { self.visible_geoms_for(false) }++ fn visible_geoms_for(&self, inset: bool) -> Vec<(u64, layout::Geom)> {let body = self.body();let tab = self.tab();tab.panes().into_iter().filter_map(|id| self.rects.iter().find(|(p, _)| *p == id).map(|(_, r)| {- let c = self.content_of(tab, *r);+ let c = if inset { self.content_of(tab, *r) } else { self.layout_content_of(tab, *r) };(id, layout::Geom { x: (c.x - body.x) as u32, y: (c.y.saturating_sub(body.y)) as u32, w: c.width as u32, h: c.height as u32 })})).collect()}@@ -4962,19 +4985,6 @@ impl App {/// select-layout -t: that window's panes in that shape.pub fn apply_preset_at(&mut self, index: usize, preset: Preset) {self.arrange_tab(index, layout::Named::of(preset));- let Some(tab) = self.tabs.get_mut(index) else { return };- let ids = tab.panes();- // The same shape on every window: the desk's layout keys presets by pane count.- if tab.on_desk && !ids.is_empty() {- if !tab.layout.is_object() { tab.layout = json!({}) }- if !tab.layout.get("presets").map(Value::is_object).unwrap_or(false) { tab.layout["presets"] = json!({}) }- tab.layout["presets"][ids.len().to_string()] = json!(preset_to_desk(preset, ids.len()));- // (And as tmux lays it out, which the other terminals take over the preset.)- if let Some(root) = tab.root.as_ref() { tab.layout["tmux"] = json!(root.to_tmux()) }- let op = json!({ "op": "tab.layout", "id": tab.id, "layout": tab.layout });- self.desk_op(op);- }- self.fit_panes();}// ── the desk: tabs shared with every window on the account ─────────────────@@ -5060,7 +5070,11 @@ impl App {// 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+ // Desktop serializes presets/sizes, dropping the tmux-only field.+ // That round-trip, or another pane count's settings, is not a new+ // arrangement. Compare only the geometry this window consumes.+ let relayout = desk_layout_changed(&tab.desk_layout, &layout_doc, panes.len())+ && desk_layout_changed(&tab.layout, &layout_doc, panes.len())&& acknowledged.get(&id) != Some(&layout_doc)&& !self.desk_layouts.contains(&id);tab.desk_layout = layout_doc.clone();@@ -5529,14 +5543,39 @@ fn preset_from_desk(id: &str, count: usize) -> Preset {}}-fn preset_to_desk(preset: Preset, count: usize) -> &'static str {- match preset {- Preset::Columns => match count { 2 => "columns", 3 => "cols3", 4 => "cols4", 5 => "cols5", _ => "columns" },- Preset::Rows => "rows",- Preset::MainStack => "mainAndStack",- Preset::MainRow => "mainOverGrid",- Preset::Grid => if count == 4 { "quad" } else { "auto" },+/// Native layouts take precedence when present. Their omission by a desktop save+/// is not an instruction to reset the terminal; only a changed current-count preset is.+fn desk_layout_changed(before: &Value, after: &Value, count: usize) -> bool {+ if let Some(native) = after.get("tmux").and_then(Value::as_str) {+ return before.get("tmux").and_then(Value::as_str) != Some(native);}+ let path = format!("/presets/{count}");+ let preset = |doc: &Value| preset_from_desk(doc.pointer(&path).and_then(Value::as_str).unwrap_or(""), count);+ preset(before) != preset(after)+}++/// Desktop presets with the same split topology. Unsupported shapes retain their+/// exact native layout without publishing an invalid preset for that pane count.+fn named_to_desk(named: layout::Named, count: usize) -> Option<&'static str> {+ use layout::Named::*;+ Some(match (count, named) {+ (2, EvenHorizontal | MainVertical | MainVerticalMirrored) => "columns",+ (2, _) => "rows",+ (3, EvenHorizontal) => "cols3",+ (4, EvenHorizontal) => "cols4",+ (5, EvenHorizontal) => "cols5",+ (3 | 4, EvenVertical) => "rows",+ (3, MainHorizontal) => "oneOverTwo",+ (3, MainHorizontalMirrored | Tiled) => "twoOverOne",+ (3, MainVertical) => "mainLeft",+ (3, MainVerticalMirrored) => "mainRight",+ (4, MainHorizontal) => "mainOverGrid",+ (4, MainVertical) => "mainAndStack",+ (4, Tiled) => "quad",+ (5 | 6, Tiled) => "balanced2",+ (9, Tiled) => "balanced3",+ _ => return None,+ })}/// Whether a tab already shows exactly the desk's panes (only the layout changed).@@ -5749,6 +5788,83 @@ mod desk_layout_tests {assert_ne!(geometry(&app), chosen);}+ #[test]+ fn a_desktop_round_trip_keeps_a_two_pane_layout_choice() {+ let mut app = fixture();+ app.tabs[0].root = layout::arrange(layout::Named::MainHorizontal, &[1, 2], 120, 35,+ layout::Status::Top, ("80", "12"), ("0", "0"));+ app.panes.remove(&3);+ let chosen = geometry(&app);+ app.tabs[0].layout = json!({"presets":{"2":"columns"},"tmux":chosen});+ app.tabs[0].desk_layout = app.tabs[0].layout.clone();+ let mut update = desk(2, json!({"presets":{"2":"columns"},"sizes":{}}));+ update["tabs"][0]["panes"].as_array_mut().unwrap().pop();+ // Desktop knows presets/sizes, but its serializer drops the terminal-only field.+ app.apply_desk(&update);+ assert_eq!(geometry(&app), chosen);+ // Editing another pane count's preset also leaves this two-pane window alone.+ update["revision"] = json!(3);+ update["tabs"][0]["layout"]["presets"]["3"] = json!("rows");+ app.apply_desk(&update);+ assert_eq!(geometry(&app), chosen);+ // A deliberate remote choice for the current count still applies.+ update["revision"] = json!(4);+ update["tabs"][0]["layout"]["presets"]["2"] = json!("rows");+ app.apply_desk(&update);+ assert_ne!(geometry(&app), chosen);+ }++ #[test]+ fn desktop_metadata_and_preset_aliases_do_not_reset_native_geometry() {+ let mut app = fixture();+ let chosen = geometry(&app);+ app.tabs[0].layout = json!({"presets":{"3":"cols3"},"tmux":chosen});+ app.tabs[0].desk_layout = app.tabs[0].layout.clone();+ app.apply_desk(&desk(2, json!({"presets":{"3":"columns","4":"quad"},"sizes":{"4:quad":[]}})));+ assert_eq!(geometry(&app), chosen);+ // Another hn's explicit native geometry is still authoritative.+ let root = layout::arrange(layout::Named::EvenVertical, &[1, 2, 3], 120, 35,+ layout::Status::Top, DESK_MAIN, ("0", "0")).unwrap();+ app.apply_desk(&desk(3, json!({"presets":{"3":"columns"},"tmux":root.to_tmux()})));+ assert_ne!(geometry(&app), chosen);+ }++ #[test]+ fn queued_preset_survives_reconciliation_without_overwriting_later_remote_choices() {+ let mut app = fixture();+ app.desk_mode = DeskMode::Read; // Inspect publication without any HTTP task.+ app.arrange_tab(0, layout::Named::EvenHorizontal);+ let chosen = geometry(&app);+ app.apply_desk(&desk(2, json!({"presets":{"3":"rows"}})));+ app.send_desk_layouts();+ assert_eq!(geometry(&app), chosen);+ assert_eq!(app.tabs[0].layout["presets"]["3"], "cols3");+ let sent = app.tabs[0].layout.clone();+ app.apply_desk(&desk(3, sent));+ app.apply_desk(&desk(4, json!({"presets":{"3":"rows"}})));+ assert_ne!(geometry(&app), chosen);+ // A divider edit after the remote choice must not revive our old preset.+ app.layout_changed(0);+ app.send_desk_layouts();+ assert_eq!(app.tabs[0].layout["presets"]["3"], "rows");+ }++ #[test]+ fn named_layouts_publish_desktop_presets_valid_for_the_pane_count() {+ use layout::Named::*;+ for named in layout::Named::ALL {+ assert_eq!(named_to_desk(named, 1), None);+ assert!(matches!(named_to_desk(named, 2), Some("columns" | "rows")));+ }+ assert_eq!(named_to_desk(MainHorizontal, 3), Some("oneOverTwo"));+ assert_eq!(named_to_desk(MainHorizontalMirrored, 3), Some("twoOverOne"));+ assert_eq!(named_to_desk(MainVertical, 3), Some("mainLeft"));+ assert_eq!(named_to_desk(MainVerticalMirrored, 3), Some("mainRight"));+ assert_eq!(named_to_desk(MainVertical, 4), Some("mainAndStack"));+ assert_eq!(named_to_desk(EvenHorizontal, 6), None);+ assert_eq!(named_to_desk(EvenVertical, 5), None);+ }+#[test]fn fitting_a_shared_layout_does_not_publish_an_edit() {let mut app = fixture();diff --git a/tui/src/commands.rs b/tui/src/commands.rsindex 182d53512..62710858c 100644--- a/tui/src/commands.rs+++ b/tui/src/commands.rs@@ -214,16 +214,22 @@ fn is_vim_command(cmd: &str) -> bool {/// percentage): the size and whether it is a percentage, or tmux's error ("size invalid").fn split_size(app: &App, words: &Words) -> Result<Option<(u16, bool)>, String> {let fit = |n: i64| n.min(u16::MAX as i64) as u16;+ // args_percentage_and_expand uses format_expand, not format_expand_time. In particular,+ // musl strftime rejects a trailing percent sign and turns an ordinary size into "".+ let expand_size = |value: &str| match app.current() {+ Some((w, p)) => crate::format::expand(app, value, w, Some(p), false),+ None => crate::format::expand(app, value, app.active, None, false),+ };if let Some(l) = opt(words, "-l") {// args_percentage_and_expand: no "empty" here — an empty size is an invalid number.- let l = expand(app, &l);+ let l = expand_size(&l);return match l.strip_suffix('%') {Some(n) => strtonum(n, 0, 100).map(|n| Some((fit(n), true))),None => strtonum(&l, 0, i32::MAX as i64).map(|n| Some((fit(n), false))),}.map_err(|e| format!("size {e}"));}match opt(words, "-p") {- Some(p) => strtonum(&expand(app, &p), 0, 100).map(|n| Some((fit(n), true))).map_err(|e| format!("size {e}")),+ Some(p) => strtonum(&expand_size(&p), 0, 100).map(|n| Some((fit(n), true))).map_err(|e| format!("size {e}")),None => Ok(None),}}@@ -1235,6 +1241,7 @@ fn run_words(app: &mut App, words: &[String]) {/// hn keeps outside the store — the prefix, the mouse, a window's synchronize-panes …fn after_set(app: &mut App, name: &str, now: Option<String>, global: bool, tab: Option<usize>) {let name = name.to_string();+ if name == "@hn-look" { app.redraw_all = true; app.fit_panes(); app.push_theme(); }// alerts_reset_all: every window's silence timer starts again.if name == "monitor-silence" { for t in app.tabs.iter_mut() { t.last_output = std::time::Instant::now() } }if name.starts_with('@') && now.is_none() { app.opts.user.remove(&name); return }@@ -3621,6 +3628,18 @@ mod tests {for no in ["zsh", "bash", "claude", "node", "vite", "vim-server", "less"] { assert!(!is_vim_command(no), "{no}") }}+ #[tokio::test]+ async fn split_percentages_expand_formats_without_strftime() {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let app = App::new(19789, sink, (80, 24));+ let size = |flag: &str, value: &str| split_size(&app, &Words::plain(vec!["split-window".into(), flag.into(), value.into()]));+ assert_eq!(size("-l", "35%"), Ok(Some((35, true))));+ assert_eq!(size("-l", "#{client_width}%"), Ok(Some((80, true))));+ assert_eq!(size("-l", "35"), Ok(Some((35, false))));+ assert_eq!(size("-p", "35"), Ok(Some((35, true))));+ for flag in ["-l", "-p"] { assert_eq!(size(flag, "%H"), Err("size invalid".into())); }+ }+#[test]fn resolves_aliases() {assert_eq!(resolve("splitw"), "split-window");diff --git a/tui/src/format.rs b/tui/src/format.rsindex 2ecfdf6c8..b2ccdeca9 100644--- a/tui/src/format.rs+++ b/tui/src/format.rs@@ -992,17 +992,36 @@ fn tab_rect(app: &App, window: usize, pane: u64) -> Option<ratatui::layout::Rect/// tmux's #{pane_title}: what select-pane -T set, or the program (OSC 0/2) when allow-set-title/// is on (hn's default is off: a harness's name is its title), else the harness's name./// A harness state's symbol with its style, for a format: its colour (the terminal's own 16),-/// dim for the quiet ones (idle, paused, offline), reversed and bold when it needs you; no colour+/// dim for the quiet ones (idle, paused, offline), bold when it needs you; no colour/// under NO_COLOR.pub fn agent_mark(state: crate::fleet::State, tick: u64) -> String {let (glyph, _, colour) = crate::theme::state_mark(state, tick);let (mut on, mut off): (Vec<String>, Vec<&str>) = (Vec::new(), Vec::new());if colour == crate::theme::MUTED { on.push("dim".into()); off.push("nodim") }else if colour != ratatui::style::Color::Reset { on.push(format!("fg={}", crate::tmuxconf::colour_name(colour))); off.push("fg=default") }- if state == crate::fleet::State::NeedsInput { on.extend(["reverse".into(), "bold".into()]); off.extend(["noreverse", "nobold"]) }+ if state == crate::fleet::State::NeedsInput { on.push("bold".into()); off.push("nobold") }if on.is_empty() { glyph.to_string() } else { format!("#[{}]{glyph}#[{}]", on.join(","), off.join(",")) }}++/// Compact quota warning: provider plus percentage, with color only on the number.+/// The raw format retains the reset window for scripts and custom status lines.+fn quota_warning<'a>(readings: impl Iterator<Item = &'a crate::fleet::Usage>, marked: bool) -> String {+ let mut worst: Option<(&crate::fleet::Usage, &crate::fleet::Window)> = None;+ for u in readings { for w in &u.windows {+ if w.used >= 80.0 && worst.map(|(_, old)| w.used > old.used).unwrap_or(true) { worst = Some((u, w)); }+ } }+ let Some((u, w)) = worst else { return String::new() };+ if !marked { return format!("{} {} {:.0}%", u.provider, w.label, w.used) }+ let provider = match u.provider.as_str() { "claude" => "Claude", "codex" => "Codex", p => p };+ let light = crate::term_out::terminal_is_light().unwrap_or(false);+ let color = match (light, w.used >= 100.0) {+ (false, false) => "#f3cc76", (false, true) => "#ff9b8e",+ (true, false) => "#875600", (true, true) => "#a53028",+ };+ format!("{provider} #[fg={color}]{:.0}%#[fg=default]", w.used)+}+pub fn pane_title(app: &App, window: usize, pane: u64) -> String {let Some(p) = app.panes.get(&pane) else { return crate::app::hostname() };let tab_id = app.tabs.get(window).map(|t| t.id.clone()).unwrap_or_default();@@ -1027,6 +1046,16 @@ pub fn pane_title(app: &App, window: usize, pane: u64) -> String {/// another of this client's).fn attached(app: &App) -> usize { app.session_attached(app.session_id) }+/// Structural dimensions for split percentages, including a zoomed pane before it unzooms.+/// Presentation padding must not change the split tree that the same command creates.+pub fn layout_rect(app: &App, window: usize, pane: u64) -> Option<ratatui::layout::Rect> {+ let r = tab_rect(app, window, pane)?;+ let tab = app.tabs.get(window)?;+ let body = app.window_area(tab);+ let c = app.layout_content_of(tab, r);+ Some(ratatui::layout::Rect { x: c.x - body.x, y: c.y - body.y, width: c.width, height: c.height })+}+pub fn content_rect(app: &App, window: usize, pane: u64) -> Option<ratatui::layout::Rect> {let r = tab_rect(app, window, pane)?;let body = app.window_area(app.tabs.get(window)?);@@ -1163,7 +1192,7 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<V"waiting" => app.fleet.waiting().to_string(),// The fleet in counts (shells aside): needs you, failed, done and unread, working, idle —// and #{fleet}, the status line's: the ones that ask something of you, each with its- // symbol (the needs-you count reversed), a state with none left out.+ // symbol (the needs-you count bold), a state with none left out."fleet_needs" => app.fleet.count(crate::fleet::State::NeedsInput).to_string(),"fleet_failed" => app.fleet.count(crate::fleet::State::Failed).to_string(),"fleet_done" => app.fleet.count(crate::fleet::State::Done).to_string(),@@ -1173,7 +1202,7 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<Vuse crate::fleet::State::*;let mut parts = Vec::new();let n = app.fleet.count(NeedsInput);- if n > 0 { parts.push(format!("#[reverse]?{n}#[noreverse]")) }+ if n > 0 { parts.push(format!("#[bold]?{n}#[nobold]")) }for (state, glyph) in [(Failed, "✗"), (Done, "✓"), (Working, crate::theme::spinner(app.tick))] {let n = app.fleet.count(state);if n > 0 { parts.push(format!("{glyph}{n}")) }@@ -1190,11 +1219,11 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<V"pane_watcher" => pane.and_then(|p| match &p.phase { crate::pane::Phase::Watching(who) => Some(who.clone()), _ => None }).unwrap_or_default(),"pane_machine" => pane.map(|p| app.fleet.machine_name(&p.machine_id)).unwrap_or_default(),// The harness's symbol as its title draws it (#{pane_agent_icon}, styled): in its state's- // colour, needs you reversed and bold, idle dim.+ // colour, needs you bold, idle dim."pane_agent_mark" => pane.and_then(|p| app.pane_state(p.id)).map(|s| agent_mark(s, app.tick)).unwrap_or_default(),- // Where the harness works, as zsh's robbyrussell prompt writes it: `project git:(branch)`,- // else `git:(branch)`, else the branch — the longest that fits beside the pane's title (a- // folder with no git: its name).+ // Where the harness works: `project ⑂ branch`, then progressively shorter context+ // as the pane narrows. The Unicode fork needs no patched icon font. A folder with+ // no git shows its name."pane_where" => pane.zip(agent).and_then(|(p, a)| {if a.branch.is_empty() && a.project.is_empty() { return None }let room = content_rect(app, window, p.id)?.width.saturating_sub(4) as usize;@@ -1203,14 +1232,14 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<Vif app.pane_state(p.id).is_some() { left += 2 }if let crate::pane::Phase::Watching(who) = &p.phase { left += width(" [watching]") + if who.is_empty() { 0 } else { width(&format!(" — {who} has it")) } }let pr = a.pr.as_ref().map(|p| format!(" {}", p.label())).unwrap_or_default();- // A pane on another machine says which (scp's way, as the status line: gpu-box:ml-lab).+ // A pane on another machine says which (scp's way: gpu-box:ml-lab).let far = (p.machine_id != app.fleet.local_id && !a.project.is_empty()).then(|| format!("{}:", app.fleet.machine_name(&p.machine_id))).filter(|m| m.len() > 1);let far_project = far.as_ref().map(|m| format!("{m}{}", a.project));// A folder that is not a git repository: its name alone (and the machine's).if a.branch.is_empty() { return [far_project, Some(a.project.clone())].into_iter().flatten().find(|c| room >= left + width(c) + 2 + 4) }- [far_project.as_ref().filter(|_| !pr.is_empty()).map(|fp| format!("{fp} git:({}){pr}", a.branch)), far_project.as_ref().map(|fp| format!("{fp} git:({})", a.branch)),- (!a.project.is_empty() && !pr.is_empty()).then(|| format!("{} git:({}){pr}", a.project, a.branch)), (!a.project.is_empty()).then(|| format!("{} git:({})", a.project, a.branch)),- (!pr.is_empty()).then(|| format!("git:({}){pr}", a.branch)), Some(format!("git:({})", a.branch)), Some(a.branch.clone())]+ [far_project.as_ref().filter(|_| !pr.is_empty()).map(|fp| format!("{fp} ⑂ {}{pr}", a.branch)), far_project.as_ref().map(|fp| format!("{fp} ⑂ {}", a.branch)),+ (!a.project.is_empty() && !pr.is_empty()).then(|| format!("{} ⑂ {}{pr}", a.project, a.branch)), (!a.project.is_empty()).then(|| format!("{} ⑂ {}", a.project, a.branch)),+ (!pr.is_empty()).then(|| format!("⑂ {}{pr}", a.branch)), Some(format!("⑂ {}", a.branch)), Some(a.branch.clone())].into_iter().flatten().find(|c| room >= left + width(c) + 2 + 4)}).unwrap_or_default(),// A pane's harness at a glance, as its title shows it (empty for a plain shell), and what it@@ -1236,13 +1265,7 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<Vlet m = pane.map(|p| p.machine_id.clone()).unwrap_or_else(|| app.fleet.local_id.clone());app.usage.get(&m).map(|u| u.iter().map(|x| x.line()).collect::<Vec<_>>().join(" · ")).unwrap_or_default()}- "usage_high" => {- let mut worst: Option<(f64, String)> = None;- for u in app.usage.values().flatten() {- for w in &u.windows { if w.used >= 80.0 && worst.as_ref().map(|(p, _)| w.used > *p).unwrap_or(true) { worst = Some((w.used, format!("{} {} {:.0}%", u.provider, w.label, w.used))) } }- }- worst.map(|(_, t)| t).unwrap_or_default()- }+ "usage_high" | "usage_high_mark" => quota_warning(app.usage.values().flatten(), name == "usage_high_mark"),"fleet_tokens" => { let t: u64 = app.fleet.agents.values().map(|a| a.tokens).sum(); if t > 0 { crate::fleet::compact(t) } else { String::new() } }"pane_branch" => agent.map(|a| a.branch.clone()).unwrap_or_default(),"window_agent_state" => tab.and_then(|_| app.window_state(window)).map(state_word).unwrap_or("").into(),@@ -1340,7 +1363,7 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<V"next_session_id" => format!("${}", crate::ids::peek(crate::ids::Kind::Session)),"buffer_mode_format" => "#{t/p:buffer_created}: #{buffer_sample}".into(),"client_mode_format" => "#{t/p:client_activity}: session #{session_name}".into(),- "tree_mode_format" => "#{?pane_format,#{?pane_marked,#[reverse],}#{pane_current_command}#{?pane_active,*,}#{?pane_marked,M,}#{?#{&&:#{pane_title},#{!=:#{pane_title},#{host_short}}},: \"#{pane_title}\",},#{?window_format,#{?window_marked_flag,#[reverse],}#{window_name}#{window_flags}#{?#{&&:#{==:#{window_panes},1},#{&&:#{pane_title},#{!=:#{pane_title},#{host_short}}}},: \"#{pane_title}\",},#{session_windows} windows#{?session_grouped, (group #{session_group}: #{session_group_list}),}#{?session_attached, (attached),}}}".into(),+ "tree_mode_format" => crate::tree::default_format(app.options.tmux_look()),"config_files" => app.config_files.join(","),// The file whose commands are running (cfg.c's current_file): a sourced file's, as its// `source -F "#{d:current_file}/…"` reads it.@@ -1540,6 +1563,26 @@ fn restyle(mut style: Style, base: Style, spec: &str) -> Style {#[cfg(test)]mod tests {+ #[test]+ fn quota_warning_marks_only_high_usage_without_reversing_text() {+ let mut u = crate::fleet::Usage { provider: "claude".into(), account: None,+ windows: vec![crate::fleet::Window { label: "week".into(), used: 79.0, resets: None }] };+ assert_eq!(super::quota_warning(std::iter::once(&u), true), "");+ u.windows[0].used = 80.0;+ let warning = super::quota_warning(std::iter::once(&u), true);+ assert!(warning.starts_with("Claude #[fg="));+ assert!(warning.ends_with("]80%#[fg=default]"));+ assert!(!warning.contains("week") && !warning.contains('●'));+ assert!(!warning.contains("reverse") && !warning.contains("bg="));+ u.windows[0].used = 100.0;+ let full = super::quota_warning(std::iter::once(&u), true);+ let indicator_color = |s: &str| s.split("#[fg=").nth(1).unwrap().split(']').next().unwrap().to_owned();+ assert_ne!(indicator_color(&warning), indicator_color(&full));+ assert!(full.starts_with("Claude #[fg="));+ assert!(full.ends_with("]100%#[fg=default]"));+ assert_eq!(super::quota_warning(std::iter::once(&u), false), "claude week 100%");+ }+#[test]fn format_regex_uses_posix_extended_expressions() {assert!(super::posix_match("^(foo|bar)[[:digit:]]+$", "foo12", false));diff --git a/tui/src/input.rs b/tui/src/input.rsindex 874eaf12f..220e08d16 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -1047,6 +1047,9 @@ fn harness_preview(picker: &mut Picker) {/// Rebuild the open overlay's rows (the fleet or a catalog moved under it).pub fn refill(app: &mut App) {+ // A delayed search/catalog reply may arrive after the picker has closed. It must not+ // consume a command prompt, confirmation or copy mode that replaced that picker.+ if !matches!(app.modal, Some(Modal::Picker { .. })) { return }if let Some(Modal::Picker { kind, mut picker }) = app.modal.take() {let was = picker.current_id();if !matches!(kind, PickerKind::Route { .. } | PickerKind::Palette | PickerKind::Help | PickerKind::Layout) { fill(app, &kind, &mut picker) }@@ -3149,6 +3152,21 @@ pub fn menu_mouse(app: &mut App, m: &crate::mouse::Event) {mod tests {use super::*;+ #[tokio::test]+ async fn delayed_picker_refresh_preserves_the_replacement_modal() {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, (80, 24));+ app.modal = Some(Modal::Prompt(Prompt::status(PromptKind::Key { template: String::new() }, ":", "split-window")));+ refill(&mut app);+ assert!(matches!(&app.modal, Some(Modal::Prompt(p)) if p.value == "split-window"));+ app.modal = Some(Modal::Confirm { prompt: "kill pane?".into(), command: "kill-pane".into(), key: 'y', enter_yes: false });+ refill(&mut app);+ assert!(matches!(app.modal, Some(Modal::Confirm { .. })));+ app.modal = Some(Modal::Copy { pane: 1 });+ refill(&mut app);+ assert!(matches!(app.modal, Some(Modal::Copy { pane: 1 })));+ }+#[test]fn prompt_words_as_tmuxs() {// Checked against tmux 3.5a's vi prompt: `display a-b.c d`, then 0 w w e E B b.diff --git a/tui/src/main.rs b/tui/src/main.rsindex bba32c436..11a479b62 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -35,6 +35,7 @@ mod mouse;mod options;mod paste;mod pane;+mod pane_frame;mod picker;mod proto;mod theme;diff --git a/tui/src/modal.rs b/tui/src/modal.rsindex 821d4409d..3df98d366 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -482,7 +482,7 @@ pub fn inbox_rows(app: &App) -> Vec<Row> {let mut detail = vec![span(who.clone(), fg(theme::MUTED))];if !options.is_empty() { detail.push(span(format!(" {options}"), fg(theme::ACCENT))) }rows.push(Row::new(format!("{}:{}#", a.machine_id, a.id), q.prompt.clone()).extra(format!("{who} {} {options}", a.branch))- .lead(vec![span("? ", fg(theme::ATTENTION).add_modifier(ratatui::style::Modifier::REVERSED)), span(mark, fg(mark_color)), span(" ", Style::default())])+ .lead(vec![span("? ", fg(theme::ATTENTION).add_modifier(ratatui::style::Modifier::BOLD)), span(mark, fg(mark_color)), span(" ", Style::default())]).detail(detail).right(ago(since)));}diff --git a/tui/src/mouse.rs b/tui/src/mouse.rsindex 91c681b18..a562a9dd2 100644--- a/tui/src/mouse.rs+++ b/tui/src/mouse.rs@@ -244,7 +244,7 @@ fn check(app: &mut App, m: &mut Event, double: bool) -> Option<Key> {let (px, py) = (x as u32, body_y(m, y) as u32);let body = app.body();if px > body.width as u32 || py > body.height as u32 { return None }- let geoms = app.visible_geoms();+ let geoms = app.visible_layout_geoms();// A border (a zoomed window has none): the column after a pane or the row below it.if !app.tab().zoomed {if let Some((id, _)) = geoms.iter().find(|(_, g)| (g.x + g.w == px && g.y <= 1 + py && g.y + g.h >= py) || (g.y + g.h == py && g.x <= 1 + px && g.x + g.w >= px)) {diff --git a/tui/src/options/mod.rs b/tui/src/options/mod.rsindex f5f7d368b..390e460a6 100644--- a/tui/src/options/mod.rs+++ b/tui/src/options/mod.rs@@ -89,23 +89,27 @@ pub fn defaults() -> &'static BTreeMap<String, String> {D.get_or_init(|| {let mut m = tmux_defaults().clone();m.insert("pane-border-status".into(), "top".into());- // Each pane's title row: the harness's symbol in its state's colour, the pane's title- // (the harness's name), [watching — who has it] when another window has the pane to type- // in, and at the far end, as far as there is room, its project and branch.- m.insert("pane-border-format".into(), " #{?pane_agent_icon,#{pane_agent_mark} ,}#{pane_title}#{?pane_watched, #[fg=yellow][watching#{?pane_watcher, — #{pane_watcher} has it,}]#[fg=default],}#{?pane_where, #[dim]· #{pane_where} #[nodim],}".into());- // The status line: tmux's, with what Harness adds — the name reversed while the prefix- // waits; on the right, the fleet in counts (#{fleet}: ?2 ✗1 ✓5 ⠹41), the focused pane's machine (a far one, as- // scp writes it: gpu-box:ml-lab), project and branch (as zsh's robbyrussell prompt writes- // them) where tmux has the pane's title (in the pane's own title row here), host and clock;- // a space first, so a full window list never runs into it. Narrower than 110 columns only- // the branch: the window list keeps its room.- m.insert("status-left".into(), "#{?client_prefix,#[reverse],}[#{session_name}]#{?client_prefix,#[noreverse],} ".into());- m.insert("status-right".into(), " #{?daemon_down,#[reverse]daemon down#[noreverse] ,}#{?usage_high,#[reverse]#{usage_high}#[noreverse] ,}#{?fleet,#{fleet} ,}#{?pane_watching,[watching] ,}#{?#{e|>=:#{client_width},110},#{?pane_far,#{pane_machine}#{?pane_project,:, },}#{?pane_project,#{=/16/…:pane_project} ,}#{?pane_branch,git:(#{=/24/…:pane_branch}) ,},#{?pane_branch,git:(#{=/16/…:pane_branch}) ,}}#{host_short} %H:%M".into());+ // Each pane's title row: the harness's name, then its state symbol, [watching — who+ // has it] when another window has the pane to type in, and its project and branch+ // where there is room. Git context stays here; the status bar keeps the location cue.+ m.insert("pane-border-format".into(), " #{pane_title}#{?pane_agent_icon, #{pane_agent_mark},}#{?pane_watched, #[fg=yellow][watching#{?pane_watcher, — #{pane_watcher} has it,}]#[fg=default],}#{?pane_where, #[dim]· #{pane_where} #[nodim],}".into());+ // Session and window navigation on the left; connection, quota, fleet, location and+ // clock on the right. A leading space keeps a full window list from running into it.+ m.insert("status-left".into(), "#{?client_prefix,#[bold],}[#{session_name}]#{?client_prefix, ›#[nobold],} ".into());+ m.insert("status-right".into(), " #{?daemon_down,#[bold]daemon down#[nobold] ,}#{?usage_high,#{usage_high_mark} ,}#{?fleet,#{fleet} ,}#{?pane_watching,[watching] ,}#{?pane_machine,#{=/12/…:pane_machine},#{host_short}}#{?pane_current_path,:#{=/18/…:#{b:pane_current_path}},#{?pane_project,:#{=/18/…:pane_project},}} %H:%M".into());// Each window's most urgent harness at a glance (the symbol its pane titles show) and its// name in a few whole words (#{window_short_name}): a harness is named for its task.+ // Keep tmux's familiar current/previous markers beside the name, then any other+ // flags, then the harness state. The selected tab needs no filled badge.for name in ["window-status-format", "window-status-current-format"] {- m.insert(name.into(), "#I:#{?window_agent_icon,#{window_agent_icon} ,}#{window_short_name}#{?window_flags,#{window_flags}, }".into());+ m.insert(name.into(), "#I:#{window_short_name}#{?window_active,*,#{?window_last_flag,-,}}#{s/[*-]//:window_flags}#{?window_agent_icon, #{window_agent_icon},}".into());}+ // Unread activity and bells already carry #/! markers. Keep a continuous status+ // background and emphasize text instead of introducing inverted tab badges.+ for name in ["window-status-activity-style", "window-status-bell-style"] {+ m.insert(name.into(), "bold".into());+ }+ if let Some(line) = m.get_mut("status-format[1]") { *line = line.replace("#[reverse]", "#[bold]"); }// The terminal's title: the harnesses waiting on you, and the one in front with its state,// so a terminal tab says what is in it (the status changing in the title as it works).m.insert("set-titles".into(), "on".into());@@ -143,8 +147,26 @@ pub fn tmux_defaults() -> &'static BTreeMap<String, String> {})}+/// Explicit user styles win; default surfaces follow the terminal's current theme.+fn pane_default(name: &str) -> Option<String> {+ let p = crate::theme::pane_palette();+ let pair = |fg, bg| format!("fg={},bg={}", crate::tmuxconf::colour_name(fg), crate::tmuxconf::colour_name(bg));+ Some(match name {+ "window-style" => pair(p.inactive_foreground, p.inactive_surface),+ "window-active-style" => pair(p.foreground, p.surface),+ "pane-border-style" => pair(p.muted, p.header),+ "pane-active-border-style" => pair(p.active_foreground, p.active_header),+ "status-style" | "window-status-style" => pair(p.status_foreground, p.status),+ "window-status-current-style" => format!("{},bold", pair(p.status_foreground, p.status)),+ "window-status-separator" => " ".into(),+ _ => return None,+ })+}++const PANE_LOOK: [&str; 8] = ["window-style", "window-active-style", "pane-border-style", "pane-active-border-style", "status-style", "window-status-current-style", "window-status-style", "window-status-separator"];+/// hn's look, where its defaults differ from tmux's: what `set -g @hn-look tmux` puts back.-pub const LOOK: [&str; 11] = ["pane-border-status", "pane-border-format", "status-left", "status-right", "status-left-length", "status-right-length", "window-status-format", "window-status-current-format", "set-titles", "set-titles-string", "allow-set-title"];+pub const LOOK: [&str; 14] = ["pane-border-status", "pane-border-format", "status-left", "status-right", "status-left-length", "status-right-length", "window-status-format", "window-status-current-format", "set-titles", "set-titles-string", "allow-set-title", "window-status-activity-style", "window-status-bell-style", "status-format[1]"];/// Where a `set` lands, as tmux's flags choose it.#[derive(Default, Clone, Debug)]@@ -204,19 +226,30 @@ impl Store {/// defaults, as set over them.pub fn array(&self, name: &str) -> Vec<String> {for m in [&self.server, &self.global_session, &self.global_window] { if holds(m, name) { return items(m, name).into_iter().map(|(_, v)| v).collect() } }- items(defaults(), name).into_iter().map(|(_, v)| v).collect()+ let defaults = if self.tmux_look() { tmux_defaults() } else { defaults() };+ items(defaults, name).into_iter().map(|(_, v)| v).collect()}/// `@hn-look tmux`: tmux's own look in place of hn's (the status line, the window list, the/// panes' title rows), where you have not set them yourself.pub fn tmux_look(&self) -> bool { self.get("@hn-look", "", None).as_deref() == Some("tmux") }+ /// The normal hn presentation; classic keeps the earlier line borders.+ pub fn pane_look(&self) -> bool { !matches!(self.get("@hn-look", "", None).as_deref(), Some("tmux" | "classic")) }+/// Reduce motion independently of the status/pane appearance.pub fn animations(&self) -> bool { !matches!(self.get("@hn-animations", "", None).as_deref(), Some("off" | "0" | "no")) }/// The default for a name: hn's, or tmux's under `@hn-look tmux`.- fn default_of(&self, name: &str) -> Option<&'static String> {- if LOOK.contains(&name) && self.tmux_look() { tmux_defaults().get(name) } else { defaults().get(name) }+ fn default_of(&self, name: &str, inherit_window_style: bool) -> Option<String> {+ if LOOK.contains(&name) && self.tmux_look() { tmux_defaults().get(name).cloned() }+ else if PANE_LOOK.contains(&name) && self.pane_look() {+ // A user window-style applies to both active and inactive panes unless they also+ // set window-active-style. The automatic focus palette must not mask their colors.+ if name == "window-active-style" && inherit_window_style { Some("default".into()) }+ else { pane_default(name) }+ }+ else { defaults().get(name).cloned() }}pub fn get(&self, name: &str, window: &str, pane: Option<u64>) -> Option<String> {@@ -234,9 +267,10 @@ impl Store {if find(name).map(|o| o.array).unwrap_or(false) {let (base, index) = split_index(name);index?;- return match layers.into_iter().flatten().find(|m| holds(m, base)) { Some(m) => m.get(name).cloned(), None => defaults().get(name).cloned() };+ return match layers.into_iter().flatten().find(|m| holds(m, base)) { Some(m) => m.get(name).cloned(), None => self.default_of(name, false) };}- layers.into_iter().flatten().find_map(|m| m.get(name).cloned()).or_else(|| self.default_of(name).cloned())+ let inherit_window_style = name == "window-active-style" && layers.iter().flatten().any(|m| m.contains_key("window-style"));+ layers.into_iter().flatten().find_map(|m| m.get(name).cloned()).or_else(|| self.default_of(name, inherit_window_style))}/// As tmux's formats read it (options_to_string, numeric): a flag is 1 or 0; an array its items@@ -367,7 +401,7 @@ impl Store {fn global_rows(&self, scope: Scope) -> BTreeMap<String, String> {let in_scope = |o: &Opt| match scope { Scope::Server => o.scope == Scope::Server, Scope::Session => o.scope == Scope::Session, Scope::Window => matches!(o.scope, Scope::Window | Scope::Pane), Scope::Pane => false };let mut rows: BTreeMap<String, String> = defaults().iter().filter(|(k, _)| find(k).map(in_scope).unwrap_or(false)).map(|(k, v)| (k.clone(), v.clone())).collect();- for n in LOOK { if rows.contains_key(n) { if let Some(v) = self.default_of(n) { rows.insert(n.to_string(), v.clone()); } } }+ for n in LOOK.into_iter().chain(PANE_LOOK) { if rows.contains_key(n) { if let Some(v) = self.default_of(n, self.global_window.contains_key("window-style")) { rows.insert(n.to_string(), v); } } }// (hn's own hooks, harness-*, only once set: the list is tmux's.)for h in table::HOOKS.iter().filter(|o| in_scope(o) && !o.name.starts_with("harness-")) { rows.insert(h.name.to_string(), String::new()); }if let Some(map) = self.map(scope, true, "", 0) { overlay(&mut rows, map) }@@ -561,12 +595,70 @@ mod tests {assert_eq!(s.get("pane-border-status", "", None).as_deref(), Some("top"));}+ #[test]+ fn pane_palette_changes_without_overriding_user_styles() {+ let mut s = Store::default();+ let g = SetFlags { global: true, ..Default::default() };+ let gw = SetFlags { global: true, window: true, ..Default::default() };+ assert!(s.pane_look());+ assert!(s.get("window-style", "", None).unwrap().starts_with("fg=#"));+ s.set("window-style", Some("bg=blue"), &gw, "", 0).unwrap();+ for look in ["classic", "tmux", "panes"] {+ s.set("@hn-look", Some(look), &g, "", 0).unwrap();+ assert_eq!(s.pane_look(), look == "panes");+ assert_eq!(s.get("window-style", "", None).as_deref(), Some("bg=blue"));+ if look != "panes" { assert_eq!(s.get("status-style", "", None), defaults().get("status-style").cloned()); }+ }+ s.set("window-style", None, &SetFlags { unset: true, ..gw }, "", 0).unwrap();+ assert!(s.get("window-style", "", None).unwrap().starts_with("fg=#"));+ }++ #[test]+ fn custom_window_styles_keep_their_active_colors_at_every_scope() {+ for f in [SetFlags { global: true, window: true, ..Default::default() },+ SetFlags { window: true, ..Default::default() },+ SetFlags { pane: true, ..Default::default() }] {+ let mut s = Store::default();+ assert_ne!(s.get("window-style", "w", Some(1)), s.get("window-active-style", "w", Some(1)));+ s.set("window-style", Some("fg=red,bg=blue"), &f, "w", 1).unwrap();+ assert_eq!(s.get("window-active-style", "w", Some(1)).as_deref(), Some("default"));+ if f.global { assert_eq!(s.global_rows(Scope::Window).get("window-active-style").map(String::as_str), Some("default")); }+ s.set("window-active-style", Some("fg=yellow,bg=black"), &f, "w", 1).unwrap();+ assert_eq!(s.get("window-active-style", "w", Some(1)).as_deref(), Some("fg=yellow,bg=black"));+ }+ }++ #[test]+ fn status_alerts_use_emphasis_unless_tmux_or_an_explicit_style_is_requested() {+ let mut s = Store::default();+ for name in ["window-status-activity-style", "window-status-bell-style"] {+ assert_eq!(s.get(name, "w", None).as_deref(), Some("bold"));+ }+ assert!(!s.array("status-format")[1].contains("reverse"));+ assert!(!s.get("status-format[1]", "w", None).unwrap().contains("reverse"));+ assert!(!s.global_rows(Scope::Session)["status-format[1]"].contains("reverse"));+ let global = SetFlags { global: true, ..Default::default() };+ s.set("@hn-look", Some("tmux"), &global, "w", 1).unwrap();+ for name in ["window-status-activity-style", "window-status-bell-style"] {+ assert_eq!(s.get(name, "w", None).as_deref(), Some("reverse"));+ }+ assert!(s.array("status-format")[1].contains("reverse"));+ assert!(s.get("status-format[1]", "w", None).unwrap().contains("reverse"));+ assert!(s.global_rows(Scope::Session)["status-format[1]"].contains("reverse"));+ s.set("@hn-look", Some("panes"), &global, "w", 1).unwrap();+ s.set("window-status-bell-style", Some("fg=red,reverse"),+ &SetFlags { global: true, window: true, ..Default::default() }, "w", 1).unwrap();+ assert_eq!(s.get("window-status-bell-style", "w", None).as_deref(), Some("fg=red,reverse"));+ s.set("status-format[1]", Some("#[reverse]custom"), &global, "w", 1).unwrap();+ assert_eq!(s.get("status-format[1]", "w", None).as_deref(), Some("#[reverse]custom"));+ }+#[test]fn every_default_is_in_the_table() {for name in defaults().keys() { assert!(find(name).is_some(), "{name}") }- // tmux's own default, in the fixture; hn's status-left adds the prefix's reverse.+ // tmux's own default, in the fixture; hn's status-left adds emphasis and a prefix cue.assert!(include_str!("../../tests/fixtures/tmux-3.5a-options.txt").contains("session status-left \"[#{session_name}] \""));- assert_eq!(defaults().get("status-left").map(String::as_str), Some("#{?client_prefix,#[reverse],}[#{session_name}]#{?client_prefix,#[noreverse],} "));+ assert_eq!(defaults().get("status-left").map(String::as_str), Some("#{?client_prefix,#[bold],}[#{session_name}]#{?client_prefix, ›#[nobold],} "));assert_eq!(defaults().get("status-interval").map(String::as_str), Some("15"));}diff --git a/tui/src/pane_frame.rs b/tui/src/pane_frame.rsnew file mode 100644index 000000000..4dc27bed0--- /dev/null+++ b/tui/src/pane_frame.rs@@ -0,0 +1,79 @@+//! Presentation insets live outside the tmux layout tree. Its splits and named layouts+//! remain unchanged; the terminal, cursor, copy mode and mouse share this content rectangle.++use ratatui::layout::Rect;+use crate::layout::Status;++#[derive(Clone, Copy, Debug)]+pub struct Frame { pub surface: Rect, pub content: Rect, pub title: Option<Rect>, pub outline: Option<Rect> }++pub fn frame(tile: Rect, canvas: Rect, status: Status) -> Frame {+ let mut surface = tile;+ // A small pane gives its cells to the program. Larger panes keep one-cell outer space.+ if tile.width >= 12 && canvas.width >= 40 {+ if tile.x == canvas.x { surface.x += 1; surface.width -= 1; }+ if tile.right() == canvas.right() { surface.width = surface.width.saturating_sub(1); }+ }+ if tile.height >= 8 && canvas.height >= 12 {+ // With top/bottom status, tmux borrows the divider row for a pane title. Leave+ // that row as a gutter and draw the title inside the surface instead.+ if tile.y == canvas.y || status == Status::Top { surface.y += 1; surface.height -= 1; }+ if tile.bottom() == canvas.bottom() || status == Status::Bottom { surface.height = surface.height.saturating_sub(1); }+ }+ let title = (surface.height > 1 && status != Status::Off).then(|| Rect::new(surface.x,+ if status == Status::Bottom { surface.bottom() - 1 } else { surface.y }, surface.width, 1));+ let mut content = surface;+ if title.is_some() {+ if status == Status::Top { content.y += 1; }+ content.height -= 1;+ }+ if content.width >= 12 { content.x += 1; content.width -= 2; }+ if content.height >= 10 { content.y += 1; content.height -= 2; }+ // The focus outline occupies existing gutter cells, never a program cell. Compact+ // panes without a complete gutter keep all their space and rely on surface contrast.+ let outline = (tile.width >= 12 && canvas.width >= 40 && tile.height >= 8 && canvas.height >= 12+ && surface.x > canvas.x && surface.y > canvas.y+ && surface.right() < canvas.right() && surface.bottom() < canvas.bottom())+ .then(|| Rect::new(surface.x - 1, surface.y - 1, surface.width + 2, surface.height + 2));+ Frame { surface, content, title, outline }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn small_panes_keep_usable_cells_and_every_rect_stays_inside() {+ for w in 1..=100 { for h in 1..=40 { for status in [Status::Off, Status::Top, Status::Bottom] {+ let tile = Rect::new(3, 2, w, h);+ let f = frame(tile, tile, status);+ assert_eq!(f.surface.intersection(tile), f.surface);+ assert_eq!(f.content.intersection(f.surface), f.content);+ assert!(f.content.width > 0 && f.content.height > 0);+ if let Some(title) = f.title { assert_eq!(title.intersection(f.content).height, 0); }+ if let Some(outline) = f.outline {+ assert_eq!(outline.intersection(tile), outline);+ assert!(outline.x < f.surface.x && outline.y < f.surface.y);+ assert!(outline.right() > f.surface.right() && outline.bottom() > f.surface.bottom());+ }+ } } }+ }++ #[test]+ fn stacked_and_side_by_side_surfaces_leave_divider_gaps() {+ let canvas = Rect::new(0, 0, 120, 40);+ let left = frame(Rect::new(0, 0, 59, 40), canvas, Status::Top);+ let right = frame(Rect::new(60, 0, 60, 40), canvas, Status::Top);+ assert_eq!(right.surface.x - left.surface.right(), 1);+ assert_eq!(left.outline.unwrap().intersection(right.surface).width, 0);+ assert_eq!(right.outline.unwrap().intersection(left.surface).width, 0);+ let top = frame(Rect::new(0, 0, 120, 20), canvas, Status::Top);+ let bottom = frame(Rect::new(0, 20, 120, 20), canvas, Status::Top);+ assert_eq!(bottom.surface.y - top.surface.bottom(), 1);+ assert_eq!(top.outline.unwrap().intersection(bottom.surface).height, 0);+ assert_eq!(bottom.outline.unwrap().intersection(top.surface).height, 0);+ assert!(top.content.y > top.title.unwrap().y);+ // Short inner tiles share a title row without the normal outer gutter.+ assert!(frame(Rect::new(20, 20, 40, 5), canvas, Status::Top).outline.is_none());+ }+}diff --git a/tui/src/term_input.rs b/tui/src/term_input.rsindex e12562848..d426cde85 100644--- a/tui/src/term_input.rs+++ b/tui/src/term_input.rs@@ -87,6 +87,7 @@ fn parse_osc11(body: &str) -> Option<String> {let parts: Vec<&str> = rgb.split('/').collect();if parts.len() == 3 {let conv = |s: &str| -> Option<u8> {+ if !(1..=4).contains(&s.len()) || !s.bytes().all(|b| b.is_ascii_hexdigit()) { return None }let v = u32::from_str_radix(s, 16).ok()?;let max = (1u32 << (4 * s.len())) - 1;Some(((v * 255) / max) as u8)@@ -196,5 +197,8 @@ mod tests {assert_eq!(parse_osc11("#1a1A1a"), Some("#1a1a1a".into()));assert_eq!(parse_osc11("rgb:0000/0000/0000"), Some("#000000".into())); // a terminal's blackassert_eq!(parse_osc11("garbage"), None);+ for bad in ["rgb:/00/00", "rgb:ffffffff/00/00", "rgb:10000/00/00", "rgb:+1/00/00", "rgb:zz/00/00"] {+ assert_eq!(parse_osc11(bad), None, "{bad}");+ }}}diff --git a/tui/src/term_out.rs b/tui/src/term_out.rsindex dc5bfb01b..40b52dbab 100644--- a/tui/src/term_out.rs+++ b/tui/src/term_out.rs@@ -228,7 +228,9 @@ pub fn set_colours(n: u32) { COLOURS.store(n, std::sync::atomic::Ordering::Relax/// The terminal's own default background and foreground, from its OSC 10/11 answers, as/// `#rrggbb` (bg, fg). None until the terminal answers. hn starts on top of the terminal, so/// these are asked directly and answer reliably; the daemon uses them to paint agent panes.-static TERMINAL_FG_BG: std::sync::RwLock<Option<(String, String)>> = std::sync::RwLock::new(None);+#[derive(Clone)]+struct TerminalColours { bg: String, fg: String, foreground_reported: bool }+static TERMINAL_FG_BG: std::sync::RwLock<Option<TerminalColours>> = std::sync::RwLock::new(None);fn hex_rgb(hex: &str) -> Option<(u8, u8, u8)> {let h = hex.trim_start_matches('#');@@ -246,19 +248,38 @@ fn companion_fg(bg: &str) -> String {/// What the terminal answered for its default colours, (bg, fg) hex, when it answered.pub fn terminal_colours() -> Option<(String, String)> {- TERMINAL_FG_BG.read().ok()?.clone()+ TERMINAL_FG_BG.read().ok()?.as_ref().map(|c| (c.bg.clone(), c.fg.clone()))}/// Record an OSC 10/11 answer. A half left blank keeps the other (a terminal may answer bg only);/// a missing foreground is chosen for contrast on the background.pub fn set_terminal_colours(bg: Option<String>, fg: Option<String>) {if let Ok(mut guard) = TERMINAL_FG_BG.write() {- let existing = guard.clone();- let bg = bg.or(existing.as_ref().map(|(b, _)| b.clone()));- let fg = fg.or(existing.as_ref().map(|(_, f)| f.clone()));- if let Some(bg) = bg {- *guard = Some((bg.clone(), fg.unwrap_or_else(|| companion_fg(&bg))));- }+ *guard = updated_terminal_colours(guard.as_ref(), bg, fg);+ }+}++fn updated_terminal_colours(existing: Option<&TerminalColours>, bg: Option<String>, fg: Option<String>) -> Option<TerminalColours> {+ let foreground_reported = fg.is_some() || existing.is_some_and(|c| c.foreground_reported);+ let bg = bg.or_else(|| existing.map(|c| c.bg.clone()))?;+ let fg = fg.or_else(|| existing.filter(|c| c.foreground_reported).map(|c| c.fg.clone()))+ .unwrap_or_else(|| companion_fg(&bg));+ Some(TerminalColours { bg, fg, foreground_reported })+}++#[cfg(test)]+mod terminal_colour_tests {+ use super::*;++ #[test]+ fn a_background_change_recomputes_inferred_foreground_only() {+ let dark = updated_terminal_colours(None, Some("#101010".into()), None).unwrap();+ assert_eq!(dark.fg, "#f5f5f5");+ let light = updated_terminal_colours(Some(&dark), Some("#f7f7f7".into()), None).unwrap();+ assert_eq!(light.fg, "#1a1a1a");+ let own = updated_terminal_colours(Some(&light), None, Some("#202020".into())).unwrap();+ let next = updated_terminal_colours(Some(&own), Some("#eeeeee".into()), None).unwrap();+ assert_eq!(next.fg, "#202020");}}diff --git a/tui/src/theme.rs b/tui/src/theme.rsindex 0fabced67..fb9e94359 100644--- a/tui/src/theme.rs+++ b/tui/src/theme.rs@@ -422,6 +422,46 @@ pub fn palette() -> (Color, Color, bool) {(bg, fg, light)}+/// Surface colors derived from the terminal theme, with a stable fallback before OSC replies.+#[derive(Clone, Copy, Debug)]+pub struct PanePalette {+ pub canvas: Color, pub surface: Color, pub inactive_surface: Color,+ pub foreground: Color, pub inactive_foreground: Color, pub muted: Color,+ pub header: Color, pub active_header: Color, pub active_foreground: Color,+ pub status: Color, pub status_foreground: Color,+}++pub fn pane_palette() -> PanePalette {+ let native = crate::term_out::terminal_colours().and_then(|(bg, fg)|+ Some((crate::tmuxconf::colour(&bg)?, crate::tmuxconf::colour(&fg)?)));+ pane_palette_for(native)+}++fn pane_palette_for(native: Option<(Color, Color)>) -> PanePalette {+ let (bg, foreground) = native.unwrap_or((Color::Rgb(28, 31, 36), Color::Rgb(220, 225, 231)));+ let Color::Rgb(r, g, b) = bg else { unreachable!("terminal background is RGB") };+ let light = 299 * r as u32 + 587 * g as u32 + 114 * b as u32 > 128_000;+ let mix = |a: Color, b: Color, amount: u16| {+ let (Color::Rgb(ar, ag, ab), Color::Rgb(br, bg, bb)) = (a, b) else { return a };+ let c = |a: u8, b: u8| ((a as u16 * (100 - amount) + b as u16 * amount) / 100) as u8;+ Color::Rgb(c(ar, br), c(ag, bg), c(ab, bb))+ };+ let green = if light { Color::Rgb(58, 102, 48) } else { Color::Rgb(133, 181, 105) };+ PanePalette {+ canvas: if light { mix(bg, foreground, 14) } else { mix(bg, Color::Rgb(0, 0, 0), 45) },+ surface: bg,+ inactive_surface: if light { mix(bg, foreground, 8) } else { Color::Rgb(64, 64, 64) },+ foreground, inactive_foreground: mix(foreground, bg, 9),+ muted: mix(foreground, bg, 30),+ header: if light { mix(bg, foreground, 12) } else { Color::Rgb(64, 64, 64) },+ active_header: bg,+ active_foreground: if light { Color::Rgb(74, 89, 105) } else { Color::Rgb(192, 200, 210) },+ // A familiar green anchor, subdued enough that the working pane keeps the attention.+ status: mix(bg, green, if light { 18 } else { 28 }),+ status_foreground: if light { Color::Rgb(35, 62, 29) } else { Color::Rgb(196, 216, 183) },+ }+}+/// fzf's colours — its dark256 default, or what `--color=light|16|bw` in `$FZF_DEFAULT_OPTS` asks/// for (and bw under NO_COLOR), so a list here looks like fzf does on this terminal.#[derive(Clone)]@@ -1227,6 +1267,27 @@ mod opts_tests {#[cfg(test)]mod palette_tests {+ #[test]+ fn pane_surfaces_remain_distinct_on_dark_and_light_terminals() {+ for (bg, fg) in [(Color::Rgb(0, 0, 0), Color::Rgb(245, 245, 245)),+ (Color::Rgb(247, 247, 247), Color::Rgb(26, 26, 26))] {+ let p = super::pane_palette_for(Some((bg, fg)));+ assert_ne!(p.surface, p.inactive_surface);+ assert_ne!(p.inactive_surface, p.canvas);+ assert_eq!(p.surface, bg);+ assert_ne!(p.header, p.active_header);+ assert_eq!(p.foreground, fg);+ let luminance = |c: Color| { let Color::Rgb(r, g, b) = c else { panic!("RGB palette") };+ 299 * r as i32 + 587 * g as i32 + 114 * b as i32 };+ assert!((luminance(p.surface) - luminance(p.foreground)).abs() > 180_000);+ assert!((luminance(p.inactive_surface) - luminance(p.inactive_foreground)).abs() > 150_000);+ assert!((luminance(p.status) - luminance(p.status_foreground)).abs() > 120_000);+ }+ let fallback = super::pane_palette_for(None);+ assert_eq!(fallback.surface, Color::Rgb(28, 31, 36));+ assert_eq!(fallback.inactive_surface, Color::Rgb(64, 64, 64));+ }+use super::palette;use ratatui::style::Color;@@ -1247,7 +1308,8 @@ mod palette_tests {// chrome read as teal on some terminals while the status bar was light.for c in [super::MUTED, super::SOFT] {let s = super::fg(c);- assert_eq!(s.fg, Some(super::depth_fit(fg)), "{c:?} carries the theme's foreground, not the terminal default");+ let expected = (!super::no_color()).then(|| super::depth_fit(fg));+ assert_eq!(s.fg, expected, "{c:?} follows the theme and NO_COLOR");assert!(s.add_modifier.contains(ratatui::style::Modifier::DIM), "{c:?} stays emphasis (dim)");}diff --git a/tui/src/tree.rs b/tui/src/tree.rsindex 5c9f3d289..3121218ae 100644--- a/tui/src/tree.rs+++ b/tui/src/tree.rs@@ -41,6 +41,12 @@ pub const DEFAULT_FORMAT: &str = concat!("}","}",);+/// Marked rows have an explicit marker and emphasis; tmux appearance keeps its original format.+pub fn default_format(tmux_look: bool) -> String {+ if tmux_look { DEFAULT_FORMAT.to_string() }+ else { DEFAULT_FORMAT.replace("#[reverse]", "#[bold]◆ ") }+}+pub const DEFAULT_KEY_FORMAT: &str = "#{?#{e|<:#{line},10},#{line},#{?#{e|<:#{line},36},M-#{a:#{e|+:97,#{e|-:#{line},10}}},}}";const SORTS: [&str; 3] = ["index", "name", "time"];/// window-buffer.c's (choose-buffer): its template, its items' format and its sorts.@@ -214,7 +220,7 @@ impl Tree {let sorts = if a.buffer { &BUFFER_SORTS } else { &SORTS };let sort = a.sort.as_deref().and_then(|s| sorts.iter().position(|x| x.eq_ignore_ascii_case(s))).unwrap_or(0);let tab = app.tabs.get(window).map(|t| t.id.clone()).unwrap_or_default();- let (format, command) = if a.buffer { (BUFFER_FORMAT, BUFFER_COMMAND) } else { (DEFAULT_FORMAT, DEFAULT_COMMAND) };+ let (format, command) = if a.buffer { (BUFFER_FORMAT.to_string(), BUFFER_COMMAND) } else { (default_format(app.options.tmux_look()), DEFAULT_COMMAND) };let mut t = Tree {flavour,pane,@@ -234,7 +240,7 @@ impl Tree {sort,groups: a.groups,reversed: a.reversed,- format: a.format.clone().unwrap_or_else(|| format.to_string()),+ format: a.format.clone().unwrap_or(format),key_format: a.key_format.clone().unwrap_or_else(|| DEFAULT_KEY_FORMAT.to_string()),command: a.command.clone().unwrap_or_else(|| command.to_string()),kind: if a.buffer { Kind::None } else if a.session { Kind::Session } else if a.window { Kind::Window } else { Kind::Pane },diff --git a/tui/src/ui.rs b/tui/src/ui.rsindex 91d982324..84b3808a3 100644--- a/tui/src/ui.rs+++ b/tui/src/ui.rs@@ -1,8 +1,6 @@-//! Drawing, the way tmux and fzf draw. A frame is the active window's panes (edge to edge when-//! there is one; tmux borders with `pane-border-status top` when there are several), then the-//! status line — tmux's: green, at the bottom, `[harness] 0:name* 1:name-`, the pane's title and-//! the time on the right; prompts and messages take it over in yellow. The search is fzf's own-//! layout and colours, with a preview window.+//! Pane surfaces with space between them, integrated titles, and a status line at the bottom.+//! The tmux split tree remains intact beneath presentation insets. Classic and tmux looks+//! retain line borders; the search keeps fzf's layout and colours with a preview window.use std::time::{Duration, SystemTime, UNIX_EPOCH};@@ -233,9 +231,14 @@ fn which_key(buf: &mut Buffer, app: &App, body: Rect) {// ── the window ───────────────────────────────────────────────────────────────-/// The active window's panes, then their borders and status lines as tmux draws them.+/// The active window's programs, then their pane surfaces or classic borders and titles.fn window(buf: &mut Buffer, app: &mut App, body: Rect) -> Option<Position> {let focus = app.focused();+ let surfaces = app.options.pane_look();+ if surfaces {+ crate::term_out::clear_extras(body);+ buf.set_style(body, Style::default().bg(theme::pane_palette().canvas));+ }let rects = app.rects.clone();let mut cursor = None;for (id, rect) in rects.iter() {@@ -246,6 +249,10 @@ fn window(buf: &mut Buffer, app: &mut App, body: Rect) -> Option<Position> {// window-style (both the pane's own, its window's or the global ones).let (a, w) = (app.style_of("window-active-style", app.active, Some(*id)), app.style_of("window-style", app.active, Some(*id)));let window = if active { (a.fg.or(w.fg), a.bg.or(w.bg)) } else { (w.fg, w.bg) };+ if surfaces {+ let f = crate::pane_frame::frame(*rect, app.window_area(app.tab()), app.pane_status(app.tab()));+ buf.set_style(f.surface, Style::default().fg(window.0.unwrap_or(Color::Reset)).bg(window.1.unwrap_or(Color::Reset)));+ }// choose-tree's tree, over the pane.if app.panes.get(id).map(|p| p.tree_top()).unwrap_or(false) {if let Some(bg) = window.1 { buf.set_style(content, Style::default().bg(bg)) }@@ -268,10 +275,40 @@ fn window(buf: &mut Buffer, app: &mut App, body: Rect) -> Option<Position> {pane.dirty = false;}}- borders(buf, app, body);+ if surfaces { pane_chrome(buf, app); } else { borders(buf, app, body); }if app.modal.is_some() && !matches!(app.modal, Some(Modal::Copy { .. })) { None } else { cursor }}+/// Integrated titles and a thin focus outline in the gutters. Program cells retain their+/// ANSI colours; moving focus changes no content dimensions or mouse coordinates.+fn pane_chrome(buf: &mut Buffer, app: &App) {+ let canvas = app.window_area(app.tab());+ for (id, rect) in &app.rects {+ let f = crate::pane_frame::frame(*rect, canvas, app.pane_status(app.tab()));+ let active = Some(*id) == app.focused();+ let style = app.style_of(if active { "pane-active-border-style" } else { "pane-border-style" }, app.active, Some(*id));+ if let Some(outline) = f.outline.filter(|_| active) {+ let lines = app.options.get("pane-border-lines", &app.tab().id, Some(*id)).unwrap_or_default();+ let (tl, tr, bl, br, hz, vt, _, _) = box_set(&lines);+ let border = style.bg(theme::pane_palette().canvas);+ let put = |buf: &mut Buffer, x, y, glyph| {+ if let Some(cell) = buf.cell_mut((x, y)) { cell.set_symbol(glyph).set_style(border); }+ };+ let (right, bottom) = (outline.right() - 1, outline.bottom() - 1);+ for x in outline.x + 1..right { put(buf, x, outline.y, hz); put(buf, x, bottom, hz); }+ for y in outline.y + 1..bottom { put(buf, outline.x, y, vt); put(buf, right, y, vt); }+ put(buf, outline.x, outline.y, tl); put(buf, right, outline.y, tr);+ put(buf, outline.x, bottom, bl); put(buf, right, bottom, br);+ }+ let Some(title) = f.title else { continue };+ buf.set_style(title, style);+ let marker = if app.marked == Some(*id) { "◆" } else { " " };+ if title.width > 0 { if let Some(cell) = buf.cell_mut((title.x, title.y)) { cell.set_symbol(marker).set_style(style); } }+ let text = Rect::new(title.x + 1.min(title.width), title.y, title.width.saturating_sub(2), 1);+ title_line(buf, app, *id, text, style);+ }+}+/// screen-redraw.c over the window: every border cell (its junction, the active pane's in/// pane-active-border-style, the marked pane's reversed, pane-border-indicators' arrows) and each/// pane's status line, the format drawn over border characters from two cells in.@@ -289,7 +326,7 @@ fn borders(buf: &mut Buffer, app: &App, body: Rect) {};for c in frame.cells() {let style = border_style(app, c.paint == crate::borders::Paint::Active);- let style = if c.marked { style.add_modifier(Modifier::REVERSED) } else { style };+ let style = if c.marked { style.add_modifier(if app.options.tmux_look() { Modifier::REVERSED } else { Modifier::BOLD }) } else { style };if let Some(cell) = buf.cell_mut((body.x + c.x as u16, body.y + c.y as u16)) { cell.set_symbol(&c.glyph).set_style(style); }}for t in frame.titles() {@@ -309,7 +346,7 @@ fn borders(buf: &mut Buffer, app: &App, body: Rect) {fn border_style(app: &App, active: bool) -> Style {let mut s = app.style_of(if active { "pane-active-border-style" } else { "pane-border-style" }, app.active, app.focused());let own = if active { app.look.active_border.is_some() } else { app.look.border.is_some() };- if !own {+ if !own && !app.options.tmux_look() {let (_, fg, _) = crate::theme::palette();s = s.fg(fg);if !active { s = s.add_modifier(Modifier::DIM) }@@ -318,7 +355,7 @@ fn border_style(app: &App, active: bool) -> Style {}/// A pane's status line over its border characters: its pane-border-format (hn's: the harness's-/// symbol, its name, and as far as the pane is wide, its project and branch), drawn as+/// name, its state symbol, and as far as the pane is wide, its project and branch), drawn as/// screen_redraw_make_pane_status draws it — format_draw over the border, so #[align=right],/// #[align=centre] and #[fill] place it as tmux does, the border showing wherever the format/// writes nothing.@@ -442,7 +479,7 @@ fn status_line(buf: &mut Buffer, app: &mut App, rect: Rect) -> Option<Position>status_formats(buf, app, rect);let line = app.options.get("message-line", "", None).and_then(|n| n.parse::<u16>().ok()).unwrap_or(0).min(rect.height.saturating_sub(1));let rect = Rect::new(rect.x, rect.y + line, rect.width, 1);- // NO_COLOR (and no colours of your own): reverse video carries the status line and messages.+ // Messages inherit the configured status message colors.let yellow = app.message_style();// (A prompt's completion menu keeps the prompt on the status line under it.)let under_menu = match &app.modal { Some(Modal::Menu(m)) => m.complete.as_ref().map(|c| &c.prompt), _ => None };@@ -2138,10 +2175,10 @@ fn preview(buf: &mut Buffer, app: &App, kind: &PickerKind, picker: &Picker, pb:for i in 0..thumb { bar_cells.1[header + start + i] = true }}if let Some(bar) = &scrollbar { for (row, marked) in bar_cells.1.iter().enumerate() { if *marked { buf.set_string(pb.bar_x, inner.y + row as u16, bar, pal.preview_scrollbar.style()); } } }- // Its offset, N/M, at the top right in the info colour reversed (not with noinfo).+ // The preview offset is a quiet label; exact tmux/fzf appearance keeps its inverse style.let mark = format!("{}/{}", offset + 1, total);if scrollable && pw.info && (mark.width() as u16) < inner.width {- buf.set_string(inner.x + inner.width - mark.width() as u16, inner.y, &mark, pal.info.style().add_modifier(Modifier::REVERSED));+ buf.set_string(inner.x + inner.width - mark.width() as u16, inner.y, &mark, pal.info.style().add_modifier(if app.options.tmux_look() { Modifier::REVERSED } else { Modifier::BOLD }));}}@@ -2475,8 +2512,10 @@ fn pane_body(buf: &mut Buffer, pane: &mut Pane, area: Rect, active: bool, windowlet note = ¬e;buf.set_style(area, Style::default().add_modifier(Modifier::DIM));let row = Rect::new(area.x, area.y, area.width, 1);- buf.set_style(row, Style::default().remove_modifier(Modifier::DIM).add_modifier(Modifier::REVERSED));- buf.set_stringn(area.x, area.y, format!("{:w$}", format!(" {note}"), w = area.width as usize), area.width as usize, Style::default().remove_modifier(Modifier::DIM).add_modifier(Modifier::REVERSED));+ let notice = Style::default().fg(window.0.unwrap_or(Color::Reset)).bg(window.1.unwrap_or(Color::Reset))+ .remove_modifier(Modifier::DIM | Modifier::REVERSED).add_modifier(Modifier::BOLD);+ buf.set_style(row, notice);+ buf.set_stringn(area.x, area.y, format!("{:w$}", format!(" ! {note}"), w = area.width as usize), area.width as usize, notice);return None;}// Local echo, drawn over the grid: underlined until the far side confirms it.diff --git a/tui/tests/e2e.sh b/tui/tests/e2e.shindex 33cc88102..a8e6dfd92 100755--- a/tui/tests/e2e.sh+++ b/tui/tests/e2e.sh@@ -15,7 +15,7 @@ home="$(mktemp -d /tmp/hn-e2e.XXXXXX)"export HN_TMPDIR="$home"tmux_() { tmux -L "$sock" "$@"; }screen() { tmux_ capture-pane -p -t t; }-fail() { echo "✗ $1"; echo "--- screen ---"; screen || true; exit 1; }+fail() { echo "✗ $1"; echo "--- screen ---"; screen || true; hn show-messages || true; hn display -p 'key-table=#{client_key_table} prefix=#{client_prefix} mode=#{pane_mode}' || true; exit 1; }expect() { # expect <what> <text> [timeout-ms]local waited=0 limit="${3:-3000}"until screen | grep -qF -- "$2"; do@@ -61,7 +61,7 @@ tmux_ send-keys -t t 'Mock\ Claude'expect "fuzzy filter narrows" "1/"# Enter, as tmux's chooser: the harness in a window of its own (not a split of this one).tmux_ send-keys -t t Enter-expect "C-b s Enter: a window of its own" "1:· Mock Claude*"+expect "C-b s Enter: a window of its own, name before status" "1:Mock Claude* ·"wait_eq "the harness window's one pane" "1" hn display -p '#{window_panes}'hn kill-windowtmux_ send-keys -t t C-b s@@ -85,18 +85,22 @@ wait_eq "#{pane_mode}" "view-mode" hn display -p '#{pane_mode}'tmux_ send-keys -t t qwait_eq "q leaves view mode" "0" hn display -p '#{pane_in_mode}'tmux_ send-keys -t t C-b ":"-expect "C-b : is the command prompt" ":"+# Titles contain colons too. Wait for the actual status prompt before typing a command.+command_prompt() { screen | tail -n 1 | grep -q '^:' && echo yes; }+wait_eq "C-b : is the command prompt" yes command_prompttmux_ send-keys -t t "split-window -h" Enter# tmux's split: a shell at once, and what is typed straight after it lands in it.tmux_ send-keys -t t "typed-ahead"-expect "split-window -h gives a shell" '── Mock terminal ─'+wait_eq "split-window -h adds a pane" "3" hn display -p '#{window_panes}'+expect "split-window -h gives a shell" 'Mock terminal'expect "keys typed while it starts go into it" "typed-ahead"tmux_ send-keys -t t C-b x ytmux_ send-keys -t t C-b stmux_ send-keys -t t "remote"tmux_ send-keys -t t C-vexpect "C-b s then C-v: a harness beside" "Remote shell (mock)"-expect "pane titles, tmux pane-border-status" '── Remote shell ─'+wait_eq "the remote harness is focused" 'Remote shell' hn display -p '#{pane_title}'+expect "pane header names the focused harness" 'Remote shell'# From a shell, as tmux is scripted: the running client answers.out=$(hn display -p '#{session_windows} #{pane_index}')[ -n "$out" ] || fail "hn display -p from a shell answered nothing"@@ -156,7 +160,7 @@ push "{\"type\":\"dial_swarm\",\"payload\":{\"swarmId\":\"$first\"}}"wait_eq "picking a window on the dial selects it" 0 hn display -p '#{window_index}'tmux_ send-keys -t t C-b 1tmux_ send-keys -t t C-b 0-expect "C-b 0: back to window 0 (its harness idle: ·)" "0:· "+wait_eq "C-b 0: back to window 0 (its harness idle: ·)" "0 ·" hn display -p '#{window_index} #{window_agent_icon}'# A harness at work, then done, as the daemon's events say it: its line, the counts, C-b a.claude=$(dial "d.agents.find(a => a.name === 'Mock Claude').id")csess=$(dial "d.agents.find(a => a.name === 'Mock Claude').sessionId")diff --git a/tui/tests/layout-sync.py b/tui/tests/layout-sync.pyindex 494dd7adc..64c61edbe 100644--- a/tui/tests/layout-sync.py+++ b/tui/tests/layout-sync.py@@ -135,12 +135,16 @@ def scenario(mode, port, read_only=False):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']:+ expected_presets = {'even-vertical': 'rows', 'main-horizontal': 'oneOverTwo',+ 'main-horizontal-mirrored': 'twoOverOne', 'main-vertical': 'mainLeft',+ 'main-vertical-mirrored': 'mainRight', 'tiled': 'twoOverOne'}+ for name, desktop_preset in expected_presets.items():hn('select-layout', name)chosen = layout()stable(chosen, .25)- print(f'PASS {mode}: all seven named layouts survive acknowledgements', flush=True)+ wait(lambda: api()['tabs'][0]['layout'].get('presets', {}).get('3') == desktop_preset,+ f'{name} publishes a desktop-compatible preset')+ print(f'PASS {mode}: all seven named layouts survive acknowledgements and share their presets', 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.@@ -219,6 +223,41 @@ def scenario(mode, port, read_only=False):wait(rows, 'remote preset must still apply')stable(layout(), .3)print(f'PASS {mode}: deliberate remote preset still applies', flush=True)++ # The reported case: a two-pane window, with the desktop serializing only+ # presets/sizes and dropping hn's native geometry a few seconds later.+ removed = api()['tabs'][0]['panes'][-1]+ api('/api/desk/ops', {'ops': [{'op': 'pane.remove', 'tabId': 'demo-1', **removed}]})+ wait(lambda: hn('display-message', '-p', '#{window_panes}') == '2', 'two-pane desk window')+ hn('select-layout', 'even-horizontal')+ tmux('send-keys', '-t', 'main', 'C-b', 'Space')+ def two_rows():+ cells = [r.split() for r in hn('list-panes', '-F', '#{pane_left} #{pane_top}').splitlines()]+ return len(cells) == 2 and len({r[0] for r in cells}) == 1 and len({r[1] for r in cells}) == 2+ wait(two_rows, 'C-b Space changes two panes to rows')+ # An unequal divider makes an accidental reconstruction visible even when+ # desktop's coarse preset describes the same orientation.+ first = hn('list-panes', '-F', '#{pane_id}').splitlines()[0]+ hn('resize-pane', '-t', first, '-D', '3')+ chosen = layout()+ if not read_only:+ wait(lambda: api()['tabs'][0]['layout'].get('presets', {}).get('2') == 'rows',+ 'two-pane rows preset saved')+ if mode == 'normal':+ wait(lambda: api()['tabs'][0]['layout'].get('tmux') == chosen, 'two-pane divider saved')+ stable(chosen, .4)+ desktop = api()['tabs'][0]['layout']+ desktop.pop('tmux', None)+ desktop['sizes'] = {}+ api('/api/desk/ops', {'ops': [{'op': 'tab.layout', 'id': 'demo-1', 'layout': desktop}]})+ stable(chosen, 1)+ desktop.setdefault('presets', {})['4'] = 'quad'+ api('/api/desk/ops', {'ops': [{'op': 'tab.layout', 'id': 'demo-1', 'layout': desktop}]})+ stable(chosen, .5)+ desktop['presets']['2'] = 'columns'+ api('/api/desk/ops', {'ops': [{'op': 'tab.layout', 'id': 'demo-1', 'layout': desktop}]})+ wait(lambda: not two_rows(), 'an intentional two-pane remote layout still applies')+ print(f'PASS {mode}: two-pane C-b Space and unequal divider survive desktop round-trip', flush=True)finally:if started:hn('kill-server', ok=False)diff --git a/tui/tests/local-shells.py b/tui/tests/local-shells.pyindex cb9f0b15a..dc0555aba 100644--- a/tui/tests/local-shells.py+++ b/tui/tests/local-shells.py@@ -116,8 +116,11 @@ try:launch('new-session', '-s', 'work')wait(lambda: hn('list-panes', '-t', 'work', '-F', '#{pane_id}', check=False).stdout.strip() == '%0', 'initial local shell')send("printf 'ENV:%s:%s:%s:%s:%s:%s\\n' \"$$\" \"$SHELL\" \"$HNE_KEEP\" \"${HNE_REMOVE-unset}\" \"${HNE_HIDDEN-unset}\" \"$TMUX_PANE\"; HNE_PERSIST=remembered")- wait(lambda: ':kept:unset:unset:%0' in capture(), 'configured environment and stable pane ID')- pid = int(next(line for line in capture().splitlines() if line.startswith('ENV:')).split(':')[1])+ # An interactive shell may leave its startup prompt before the record. Match every+ # field from one capture instead of assuming that output starts in column zero.+ record = wait(lambda: re.search(r'ENV:(\d+):/bin/sh:kept:unset:unset:%0(?=\s|$)',+ capture()), 'configured environment and stable pane ID')+ pid = int(record.group(1))sockets = list((BASE / f'hn-{os.getuid()}').glob('*.pty'))assert len(sockets) == 1 and stat.S_IMODE(sockets[0].stat().st_mode) == 0o600assert stat.S_IMODE(sockets[0].parent.stat().st_mode) == 0o700diff --git a/tui/tests/pane-ui.py b/tui/tests/pane-ui.pynew file mode 100644index 000000000..942834f0c--- /dev/null+++ b/tui/tests/pane-ui.py@@ -0,0 +1,377 @@+#!/usr/bin/env python3+"""Pane presentation with real hn keys, mouse input, copy mode and tiny PTYs.++Uses only guarded reconnect-fixture ports 19783..19789 and disposable hn/tmux servers.+HN_PANE_UI_OUTPUT optionally keeps ANSI captures for rendering a visual review.+"""+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+import unicodedata++ROOT = Path(__file__).resolve().parents[1]+PORT = int(os.environ.get('HN_PANE_UI_PORT', '19783'))+assert 19783 <= PORT <= 19789, 'refusing non-test pane UI port'+PREFIX = f'hn-pane-ui-{os.getpid()}'+BASE = Path(tempfile.mkdtemp(prefix='hnpu-', dir='/tmp')).resolve()+HN = BASE / 'hn'+shutil.copy2(os.environ.get('HN_PANE_UI_BINARY', ROOT / 'target/release/harness-tui'), HN)+TMUX = shutil.which('tmux')+assert TMUX+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', COLORTERM='truecolor', SHELL='/bin/sh', HARNESS_TUI_DESK='sync',+ HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off', MOCK_DEMO='1', MOCK_RECONNECT='1', MOCK_USAGE='100')+CONF = BASE / 'tmux.conf'+CONF.write_text('set -g automatic-rename off\nset -g status-right "#{usage_high_mark} #{fleet} #{pane_machine}:#{b:pane_current_path} 20:41 "\n')+OUTPUT = Path(os.environ['HN_PANE_UI_OUTPUT']) if os.environ.get('HN_PANE_UI_OUTPUT') else None+if OUTPUT:+ OUTPUT.mkdir(parents=True, exist_ok=True)+++def hn(*args, ok=True):+ assert 19783 <= PORT <= 19789 and PREFIX.startswith('hn-pane-ui-')+ 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:+ 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+++def api():+ with urllib.request.urlopen(f'http://127.0.0.1:{PORT}/test/reconnect', timeout=2) as r:+ return json.load(r)['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', 'test', ok=False))+++def value(fmt, target=None):+ return hn('display-message', '-p', *(['-t', target] if target else []), fmt)+++def keys(*args):+ tmux('send-keys', '-t', 'test', *args)+++def mouse(code, x, y, release=False):+ raw = f'\x1b[<{code};{x + 1};{y + 1}{"m" if release else "M"}'.encode()+ tmux('send-keys', '-H', '-t', 'test', *[f'{b:02x}' for b in raw])+++def background_at(x, y):+ row = tmux('capture-pane', '-p', '-e', '-t', 'test', '-S', str(y), '-E', str(y)).splitlines()[0]+ col, bg = 0, 'default'+ for token in re.findall(r'\x1b\[[0-9;:]*m|.', row):+ if token.startswith('\x1b['):+ codes = [int(v or 0) for v in token[2:-1].split(';')]+ i = 0+ while i < len(codes):+ c = codes[i]+ if c in (0, 49): bg = 'default'+ elif c in (38, 48) and i + 4 < len(codes) and codes[i + 1] == 2:+ if c == 48: bg = '#%02x%02x%02x' % tuple(codes[i + 2:i + 5])+ i += 4+ elif c in (38, 48) and i + 2 < len(codes) and codes[i + 1] == 5:+ if c == 48: bg = f'colour{codes[i + 2]}'+ i += 2+ elif 40 <= c <= 47: bg = f'colour{c - 40}'+ i += 1+ else:+ width = 0 if unicodedata.combining(token) else (2 if unicodedata.east_asian_width(token) in ('W', 'F') else 1)+ if col <= x < col + width: return bg+ col += width+ return bg+++def pane_background(pane):+ x, y, height = map(int, value('#{pane_left} #{pane_top} #{pane_height}', pane).split())+ return background_at(x, y + height - 2)+++def pane_outline(pane):+ x, y, w, h = map(int, value('#{pane_left} #{pane_top} #{pane_width} #{pane_height}', pane).split())+ screen = tmux('capture-pane', '-p', '-t', 'test').splitlines()+ corners = ((x - 2, y - 3, '┌'), (x + w + 1, y - 3, '┐'),+ (x - 2, y + h + 1, '└'), (x + w + 1, y + h + 1, '┘'))+ return all(0 <= row < len(screen) and 0 <= col < len(screen[row]) and screen[row][col] == glyph+ for col, row, glyph in corners)+++def snapshot(name):+ if OUTPUT:+ (OUTPUT / (name + '.ansi')).write_text(tmux('capture-pane', '-p', '-e', '-t', 'test'))+++mock = None+started = False+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()+ 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', '150', '-y', '42', command)+ started = True+ wait(lambda: 'Fix flaky login test' in tmux('capture-pane', '-p', '-t', 'test'), 'demo panes')+ hn('select-layout', 'even-horizontal')+ panes = hn('list-panes', '-F', '#{pane_id}').splitlines()+ assert len(panes) == 3+ first, second, third = panes+ hn('select-pane', '-t', first)+ keys('C-b', 'Right')+ keys('C-b', 'Left')+ wait(lambda: value('#{pane_id}') == first, 'focus before visual capture')+ time.sleep(.2)+ original = value('#{window_layout}')+ active_bg = hn('show', '-gwv', 'window-active-style').split('bg=')[1]+ inactive_bg = hn('show', '-gwv', 'window-style').split('bg=')[1]+ assert active_bg != inactive_bg+ assert inactive_bg == '#404040'+ wait(lambda: pane_outline(first) and not pane_outline(second), 'thin outline only around the focused pane')+ wait(lambda: pane_background(first) == active_bg and pane_background(second) == inactive_bg, 'whole-pane focus contrast')+ tab = value(hn('show', '-gwv', 'window-status-current-format'))+ label = value('#{window_index}:#{window_short_name}')+ assert tab.startswith(label + '* '), (tab, label)+ assert value('#{window_agent_icon}') in tab[len(label):]+ assert '*' in value('#{window_flags}')+ selected_bg = hn('show', '-gwv', 'window-status-current-style').split('bg=')[1].split(',')[0]+ normal_bg = hn('show', '-gwv', 'window-status-style').split('bg=')[1].split(',')[0]+ assert selected_bg == normal_bg, 'the star identifies the active tab without a second filled highlight'+ current = value('#{window_id}')+ other = next(w for w in hn('list-windows', '-F', '#{window_id}').splitlines() if w != current)+ hn('select-window', '-t', other)+ previous = value(hn('show', '-gwv', 'window-status-format'), current)+ assert previous.startswith(label + '-'), (previous, label)+ hn('select-window', '-t', current)+ assert 'reverse' not in value('#{fleet}')+ assert 'reverse' not in value('#{tree_mode_format}')+ assert 'reverse' not in value('#{pane_agent_mark}', second)+ custom_status = hn('show', '-gv', 'status-right')+ assert 'reverse' not in custom_status+ title = value('#{pane_title}', first)+ header = value(hn('show', '-gwv', 'pane-border-format'), first)+ plain_header = re.sub(r'#\[[^]]*\]', '', header).strip()+ assert plain_header.startswith(title + ' '), (title, plain_header)+ hn('set', '-gu', 'status-right')+ default_status = hn('show', '-gv', 'status-right')+ assert all(part not in default_status for part in ('pane_branch', 'pane_where', 'git:'))+ location = value('#{pane_machine}:#{b:pane_current_path}')+ assert location in value(default_status), (location, value(default_status))+ wait(lambda: location in tmux('capture-pane', '-p', '-t', 'test').splitlines()[-1], 'bottom right shows the focused machine and folder')+ hn('set', '-g', 'status-right', custom_status)+ for option in ('window-status-activity-style', 'window-status-bell-style'):+ assert hn('show', '-gwv', option) == 'bold'+ assert 'reverse' not in hn('show', '-gv', 'status-format[1]')+ wait(lambda: 'Claude 100%' in tmux('capture-pane', '-p', '-t', 'test').splitlines()[-1], 'plain quota warning reaches the status row')+ snapshot('panes-columns')+ print('PASS pane UI: whole-pane focus contrast, name before status, compact quota and location', flush=True)++ keys('C-b', 'Right')+ wait(lambda: value('#{pane_id}') == second, 'C-b Right with insets')+ wait(lambda: pane_background(second) == active_bg and pane_background(first) == inactive_bg, 'keyboard focus moves pane contrast')+ wait(lambda: pane_outline(second) and not pane_outline(first), 'keyboard focus moves the outline without stale borders')+ keys('C-b', 'Right')+ wait(lambda: value('#{pane_id}') == third, 'second C-b Right')+ keys('C-b', 'Right')+ wait(lambda: value('#{pane_id}') == first, 'directional wrap')+ keys('C-b', 'z')+ wait(lambda: value('#{window_zoomed_flag}') == '1', 'zoom')+ branch_context = value('#{pane_where}')+ assert '⑂ ' + value('#{pane_branch}') in branch_context, branch_context+ assert 'git:(' not in branch_context+ keys('C-b', 'z')+ wait(lambda: value('#{window_zoomed_flag}') == '0', 'unzoom')+ assert value('#{window_layout}') == original+ print('PASS pane UI: directional keys, wrap, zoom preserve layout structure', flush=True)++ # Switching presentation must not change the serialized split structure.+ hn('set', '-g', '@hn-look', 'classic')+ assert value('#{window_layout}') == original+ border = int(value('#{pane_left}', first)) + int(value('#{pane_width}', first))+ snapshot('classic-columns')+ hn('set', '-g', '@hn-look', 'panes')+ assert value('#{window_layout}') == original+ x, y, w, h = map(int, value('#{pane_left} #{pane_top} #{pane_width} #{pane_height}', first).split())+ assert x > 0 and y > 1 and w > 0 and h > 0+ hn('send-keys', '-t', first, '-l', '\x1b[?1000h\x1b[?1006h')+ wait(lambda: value('#{mouse_sgr_flag}', first) == '1', 'program mouse mode')+ before = len(api()['inputs'])+ mouse(0, x + 3, y + 2)+ mouse(0, x + 3, y + 2, release=True)+ wait(lambda: {'\x1b[<0;4;3M', '\x1b[<0;4;3m'} <= {i['text'] for i in api()['inputs'][before:]}, 'mouse press and release start inside the inset content')+ print('PASS pane UI: same layout across appearances; mouse coordinates match PTY content', flush=True)++ # Titles and padding focus the pane without sending a click to its program.+ before = len(api()['inputs'])+ second_x = int(value('#{pane_left}', second))+ mouse(0, second_x, 1)+ mouse(0, second_x, 1, release=True)+ wait(lambda: value('#{pane_id}') == second, 'click the pane header')+ wait(lambda: pane_background(second) == active_bg and pane_background(first) == inactive_bg, 'mouse focus moves pane contrast')+ wait(lambda: pane_outline(second) and not pane_outline(first), 'mouse focus moves the outline')+ assert len(api()['inputs']) == before, api()['inputs'][before:]+ mouse(0, border, 10)+ mouse(32, border + 3, 10)+ mouse(0, border + 3, 10, release=True)+ wait(lambda: value('#{window_layout}') != original, 'drag the blank divider gutter')+ print('PASS pane UI: header focus and gutter dragging', flush=True)++ hn('select-pane', '-t', first)+ keys('C-b', '[')+ wait(lambda: value('#{pane_in_mode}') == '1', 'copy mode')+ hn('send-keys', '-X', 'history-top')+ hn('send-keys', '-X', 'start-of-line')+ hn('send-keys', '-X', 'begin-selection')+ for _ in range(5):+ hn('send-keys', '-X', 'cursor-right')+ hn('send-keys', '-X', 'copy-selection-and-cancel')+ wait(lambda: value('#{pane_in_mode}') == '0', 'leave copy mode')+ assert hn('show-buffer'), 'copy selection should retain terminal text'+ print('PASS pane UI: copy mode and selection', flush=True)++ # Layout targets and percentages operate on the split tree, not inset content.+ targets = ('top', 'bottom', 'left', 'right', 'top-left', 'top-right', 'bottom-left', 'bottom-right')+ layouts = ('even-horizontal', 'even-vertical', 'main-horizontal', 'main-vertical', 'tiled',+ 'main-horizontal-mirrored', 'main-vertical-mirrored')+ for status in ('top', 'bottom', 'off'):+ hn('set', '-gw', 'pane-border-status', status)+ for layout in layouts:+ hn('set', '-g', '@hn-look', 'classic')+ hn('select-layout', layout)+ shape = value('#{window_layout}')+ expected = [value('#{pane_id}', '.' + t) for t in targets]+ hn('set', '-g', '@hn-look', 'panes')+ assert value('#{window_layout}') == shape, (status, layout)+ assert [value('#{pane_id}', '.' + t) for t in targets] == expected, (status, layout)+ hn('set', '-gw', 'pane-border-status', 'top')+ hn('select-layout', 'even-horizontal')+ shape = value('#{window_layout}')+ def structure(layout):+ return re.sub(r'(\d+x\d+,\d+,\d+),\d+', r'\1,P', layout[5:])+ for axis in ('-h', '-v'):+ resulting = []+ for look in ('classic', 'panes'):+ hn('set', '-g', '@hn-look', look)+ hn('select-layout', shape)+ new_pane = hn('split-window', axis, '-l', '35%', '-t', first, '-P', '-F', '#{pane_id}')+ assert new_pane.startswith('%'), new_pane+ resulting.append(structure(value('#{window_layout}')))+ hn('kill-pane', '-t', new_pane)+ assert resulting[0] == resulting[1], (axis, resulting)+ print('PASS pane UI: seven layouts, eight position targets, top/bottom/off titles, percentage splits', flush=True)++ hn('select-layout', 'even-vertical')+ time.sleep(.2)+ snapshot('panes-rows')+ hn('select-layout', 'main-vertical')+ time.sleep(.2)+ snapshot('panes-main')+ # Extra status rows above the panes must not leak into application mouse coordinates.+ hn('set', '-g', 'status', '2')+ hn('set', '-g', 'status-position', 'top')+ hn('select-pane', '-t', first)+ x, y = map(int, value('#{pane_left} #{pane_top}', first).split())+ # The mock emits a terminal reset on resize, so enable its program mouse mode again.+ hn('send-keys', '-t', first, '-l', '\x1b[?1000h\x1b[?1006h')+ wait(lambda: value('#{mouse_sgr_flag}', first) == '1', 'mouse mode after resized keyframe')+ before = len(api()['inputs'])+ mouse(0, x + 2, y + 2 + 1)+ mouse(0, x + 2, y + 2 + 1, release=True)+ wait(lambda: {'\x1b[<0;3;2M', '\x1b[<0;3;2m'} <= {i['text'] for i in api()['inputs'][before:]}, 'top status rows and program mouse coordinates')+ hn('set', '-g', 'status-position', 'bottom')+ hn('set', '-g', 'status', 'on')+ # OSC replies are metadata, not keystrokes. Surface defaults follow live light/dark changes.+ def background(hex_value):+ raw = f'\x1b]11;{hex_value}\x07'.encode()+ tmux('send-keys', '-H', '-t', 'test', *[f'{b:02x}' for b in raw])+ layout_before_theme = value('#{window_layout}')+ before = len(api()['inputs'])+ background('#f7f7f7')+ wait(lambda: hn('show', '-gwv', 'window-active-style') == 'fg=#1a1a1a,bg=#f7f7f7', 'light surface defaults')+ wait(lambda: pane_background(first) == '#f7f7f7' and pane_background(second) == '#e5e5e5', 'light focus contrast')+ light_status = hn('show', '-gv', 'status-style')+ assert value('#{window_layout}') == layout_before_theme+ snapshot('panes-light')+ hn('set', '-gw', 'window-style', 'fg=red,bg=blue')+ background('#101010')+ wait(lambda: hn('show', '-gv', 'status-style') != light_status, 'green status follows the dark theme')+ assert hn('show', '-gwv', 'window-style') == 'fg=red,bg=blue'+ assert hn('show', '-gwv', 'window-active-style') == 'default'+ wait(lambda: pane_background(first) == 'colour4' and pane_background(second) == 'colour4', 'custom backgrounds win on active and inactive panes')+ assert len(api()['inputs']) == before, 'terminal query replies reached an application'+ hn('set', '-gwu', 'window-style')+ assert hn('show', '-gwv', 'window-active-style').startswith('fg=#f5f5f5,')+ wait(lambda: pane_background(first) == '#101010' and pane_background(second) == '#404040', 'dark focus contrast')+ print('PASS pane UI: live light/dark themes, reported defaults and custom style preservation', flush=True)++ hn('send-keys', '-t', first, '-l', '\x1b[H\x1b[31;44mHN_COLOR\x1b[0m')+ wait(lambda: 'HN_COLOR' in tmux('capture-pane', '-p', '-t', 'test'), 'explicit program colours')+ coloured = next(row for row in tmux('capture-pane', '-p', '-e', '-t', 'test').splitlines() if 'HN_COLOR' in row)+ assert '\x1b[31m' in coloured and '\x1b[44m' in coloured, repr(coloured)+ print('PASS pane UI: top status rows and explicit program foreground/background colours', flush=True)++ for width, height in [(80, 24), (24, 8), (6, 4), (1, 1), (150, 42)]:+ tmux('resize-window', '-t', 'test', '-x', str(width), '-y', str(height))+ wait(lambda: value('#{client_width} #{client_height}') == f'{width} {height}', 'terminal resize')+ assert value('#{window_panes}') == '3'+ print('PASS pane UI: compact and one-cell terminals, return to full size', flush=True)+finally:+ if started:+ if OUTPUT:+ snapshot('last-frame')+ hn('kill-server', ok=False)+ tmux('kill-server', ok=False)+ def clients():+ rows = subprocess.check_output(['ps', '-ax', '-o', 'pid=,command='], text=True).splitlines()+ return [int(parts[0]) 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]]+ 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(), 'pane UI client 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 3a7d9f0b2..eac387c4c 100644--- a/tui/tests/viewer-live.mjs+++ b/tui/tests/viewer-live.mjs@@ -372,7 +372,24 @@ try {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')+ const desktopLayout = structuredClone((await desk()).tabs.find(t => t.id === layoutTab).layout)+ assert.equal(desktopLayout.presets['2'], 'columns', 'C-b Space must update the desktop preset too')+ delete desktopLayout.tmux+ desktopLayout.sizes = {}+ await desk([{ op: 'tab.layout', id: layoutTab, layout: desktopLayout }])+ for (let i = 0; i < 10; i++) {+ await new Promise(resolve => setTimeout(resolve, 150))+ assert.equal((await layoutHn('display-message', '-p', '#{window_layout}')).stdout.trim(), chosen,+ 'desktop layout serialization reset the real terminal')+ }+ desktopLayout.presets['2'] = 'rows'+ await desk([{ op: 'tab.layout', id: layoutTab, layout: desktopLayout }])+ await until('intentional desktop layout reaches hn', 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]+ })+ assert.equal((await layoutHn('list-panes', '-F', '#{pane_id}')).stdout, paneIds)+ pass('real C-b Space survives desktop serialization; deliberate remote changes still apply without replacing panes')await layoutHn('kill-server')await owner.rpc('agent_delete', { agentId: controlsId }); controlsId = null