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
Share exact pane layouts between desktop and hn (#546)
Dee982061bdb108
diff --git a/.github/assets/shared-pane-layout/desktop-five.png b/.github/assets/shared-pane-layout/desktop-five.pngnew file mode 100644index 000000000..2b29abc37Binary files /dev/null and b/.github/assets/shared-pane-layout/desktop-five.png differdiff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 81b6bdc3b..cf8417aae 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -12439,6 +12439,44 @@ class AppNotifier extends ChangeNotifier {);}+ /// Freeze a shared tab's geometry once. Window dimensions, font size and+ /// zoom only scale/scroll these slots; they never choose a new arrangement.+ /// A preset choice clears the current count's sizes and resolves here again.+ void _freezeDeskLayouts() {+ if (!_desk.enabled) return;+ for (final swarm in swarms) {+ final count = swarm.panes.length;+ // Viewers and drafts are local. Their slots cannot be assigned to the+ // desk's agent-only pane list. The desk currently accepts up to 9 panes.+ if (!_deskTracks(swarm) ||+ count < 2 ||+ count > 9 ||+ swarm.panes.any((pane) => pane.agentId == null)) {+ continue;+ }+ final manual = swarm.manualLayout;+ if (manual != null) {+ final filled = manual.fillRowEnds();+ if (!identical(filled, manual)) {+ swarm.savePaneSizes('$count:manual', filled);+ }+ continue;+ }+ final preset = swarm.presets[count] ?? PanePreset.defaultFor(count)!;+ final rendered = swarm.arranged?.tiles.length == count+ ? swarm.arranged+ : null;+ final saved = swarm.paneSizes.entries+ .where((e) => e.key.startsWith('$count:${preset.id}:'))+ .map((e) => e.value)+ .firstOrNull;+ final arrangement =+ (rendered ?? saved ?? PaneArrangement(preset.tilesFor(count)))+ .fillRowEnds();+ swarm.savePaneSizes('$count:manual', arrangement);+ }+ }+/// The desk's layout for a tab, made this window's: presets the shape/// supports, arrangements whose tile count matches their key. Replaces/// what was there — a layout is one thing, not a merge of two.@@ -12665,7 +12703,7 @@ class AppNotifier extends ChangeNotifier {/// Make `swarms` say what [target] says, and no more: tabs the desk closed go/// (their streams released unless another tab still shows them), tabs it/// opened arrive as intent and attach as their machines answer, names the- /// person chose follow, order follows. Focus, zoom, sizes, pins, viewers and+ /// person chose follow, order follows. Focus, zoom, pins, viewers and/// this window's own local-only tabs are left exactly where they were.////// [believed] is the desk as this window last knew it. A tab's pane order is@@ -12918,6 +12956,7 @@ class AppNotifier extends ChangeNotifier {});_layoutRevision++;_announceOpenPanesToDial();+ _freezeDeskLayouts();_deskQueueDiff();final saved = swarms.where((swarm) => !isDraftSwarm(swarm.id)).toList();if (saved.isEmpty) return;diff --git a/desktop/lib/state/desk_sync.dart b/desktop/lib/state/desk_sync.dartindex c33e8d494..c3dbbb688 100644--- a/desktop/lib/state/desk_sync.dart+++ b/desktop/lib/state/desk_sync.dart@@ -9,8 +9,9 @@/// turning `swarms` into a snapshot and a snapshot back into `swarms`.////// What is NOT on the desk, by decision (owner, 2026-09-21): the active tab,-/// focus, zoom, pinned slots, presets, pane sizes, composer visibility, drafts,-/// Recently Closed, the Store tab and orchestrator tabs. Windows differ.+/// focus, zoom, pinned slots, composer visibility, drafts, Recently Closed,+/// the Store tab and orchestrator tabs. Pane order, presets and divider+/// proportions are shared; viewport dimensions and terminal metrics stay local.library;import 'dart:math';@@ -48,6 +49,10 @@ class DeskPaneRef {/// shape's id; `sizes` is the window's arrangement keys → tiles as fractions of/// the canvas, which is what lets a window of any size draw them. Kept as the/// wire's JSON: the window turns it into `presets`/`paneSizes` and back.+/// `sizes["N:manual"]` is the common desktop/hn geometry: ordered+/// [left, top, right, bottom] slots corresponding to the tab's pane references.+/// Explicit edits replace it; a viewport resize only scales it. Older render+/// keys and presets remain readable for migration.class DeskLayout {const DeskLayout({this.presets = const {}, this.sizes = const {}});final Map<String, String> presets;diff --git a/desktop/lib/state/pane_arrangement.dart b/desktop/lib/state/pane_arrangement.dartindex 710d0f6a7..9386a2e8b 100644--- a/desktop/lib/state/pane_arrangement.dart+++ b/desktop/lib/state/pane_arrangement.dart@@ -23,6 +23,29 @@ class PaneArrangement {late final List<PaneDivider> dividers = _findDividers();+ /// Older lattice presets left an empty tail in the last row. A shared split+ /// canvas has no empty panes: let that row's last pane use the remaining room.+ /// Existing cuts and the identity/order of every slot stay intact.+ PaneArrangement fillRowEnds() {+ var changed = false;+ final filled = <Rect>[];+ for (final tile in tiles) {+ final emptyTail =+ tile.right < 1 - _epsilon &&+ !tiles.any(+ (other) =>+ other.left >= tile.right - _epsilon &&+ other.top < tile.bottom - _epsilon &&+ other.bottom > tile.top + _epsilon,+ );+ changed |= emptyTail;+ filled.add(+ emptyTail ? Rect.fromLTRB(tile.left, tile.top, 1, tile.bottom) : tile,+ );+ }+ return changed ? PaneArrangement(filled) : this;+ }+PaneArrangement? split(int index,PaneResizeAxis axis, {diff --git a/desktop/test/desk_sync_test.dart b/desktop/test/desk_sync_test.dartindex 269e57e92..93d43c34b 100644--- a/desktop/test/desk_sync_test.dart+++ b/desktop/test/desk_sync_test.dart@@ -2,8 +2,11 @@// (diff and replay) and the window's half (a document becomes `swarms`, an// edit becomes ops, and what a window keeps for itself stays put).import 'dart:async';-import 'dart:ui' show Rect;+import 'dart:io';+import 'dart:ui' as ui;+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/api/api_client.dart';import 'package:harness/auth/auth_session.dart';@@ -14,9 +17,14 @@ import 'package:harness/state/pane_layout_store.dart';import 'package:harness/state/pane_preset.dart';import 'package:harness/state/swarm.dart';import 'package:harness/state/terminal_pane.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/widgets/pane_grid.dart';+import 'package:xterm/xterm.dart';import 'swarm_state_test.dart' show MemoryStore, createApp;+import 'swarm_screen_test.dart' show terminal;+import 'box_render_preview_test.dart' show loadPreviewFonts;DeskTab tab(String id, {@@ -66,6 +74,128 @@ class _DeskApi extends ApiClient {}void main() {+ final captureDir = Platform.environment['HARNESS_SHARED_LAYOUT_CAPTURE_DIR'];+ setUpAll(() async {+ if (captureDir != null) await loadPreviewFonts();+ });+ testWidgets(+ 'shared slots survive viewport, focus and zoom changes without writes or terminal remounts',+ (tester) async {+ final api = _DeskApi();+ final app = createApp()..api = api;+ app.machineStates['m']!.nodeOnline = true;+ for (var i = 0; i < 5; i++) {+ final session = terminal('Shared pane ${i + 1}', []);+ session.terminal.write(+ 'Shared pane ${i + 1}\r\n\r\nSame position and proportions\r\non desktop and hn.\r\n',+ );+ app.adoptSessionForTest(session);+ }+ await app.deskStartForTest();+ app.setPreset(5, PanePreset.middleMain);+ app.focusPane(app.panes[1].id);+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1600, 1000);+ addTearDown(tester.view.reset);+ final capture = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: capture,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ backgroundColor: grid.AppPalette.swarmField,+ body: PaneGrid(notifier: app, swarmMode: true),+ ),+ ),+ ),+ );+ await tester.pump();+ if (captureDir != null) {+ await tester.runAsync(() async {+ final boundary =+ capture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage();+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(captureDir).create(recursive: true);+ await File('$captureDir/desktop-five.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }+ final swarm = app.activeSwarm;+ final source = swarm.manualLayout!.tiles;+ final views = [+ for (final pane in app.panes)+ find.byWidgetPredicate(+ (w) => w is TerminalView && w.terminal == pane.session!.terminal,+ ),+ ];+ final states = [for (final view in views) tester.state(view)];+ api.batches.clear();+ for (final size in [+ const Size(800, 1200),+ const Size(2400, 800),+ const Size(1600, 1000),+ ]) {+ tester.view.physicalSize = size;+ await tester.pump();+ expect(swarm.arranged?.tiles, source);+ expect(swarm.manualLayout!.tiles, source);+ for (var i = 0; i < views.length; i++) {+ expect(tester.state(views[i]), same(states[i]));+ }+ }+ app.focusPane(app.panes.last.id);+ app.toggleZoomPane();+ await tester.pump();+ app.toggleZoomPane();+ await tester.pump();+ expect(swarm.arranged?.tiles, source);+ expect(api.batches, isEmpty);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );++ test(+ 'shared defaults and presets freeze for every supported count',+ () async {+ for (var count = 2; count <= 9; count++) {+ final id = 'shared-$count';+ final api = _DeskApi()+ ..doc = DeskDoc(+ revision: 1,+ tabs: [tab(id, agents: List.generate(count, (i) => 'a$i'))],+ );+ final app = createApp()..api = api;+ await app.deskStartForTest();+ app.selectSwarm(id);+ expect(app.activeSwarm.manualLayout, isNotNull);+ for (final preset in PanePreset.forCount(count)) {+ app.setPreset(count, preset);+ await Future<void>.delayed(Duration.zero);+ final expected = PaneArrangement(preset.tilesFor(count)).toJson();+ expect(+ api.doc!.tabs+ .singleWhere((tab) => tab.id == id)+ .layout+ ?.sizes['$count:manual'],+ expected,+ );+ expect(app.activeSwarm.manualLayout?.toJson(), expected);+ }+ api.batches.clear();+ await app.deskFetchForTest();+ expect(api.batches, isEmpty);+ app.dispose();+ }+ },+ );+group('deskDiff', () {test('creates a tab with its panes, closes, renames only what the person named, and reorders', () {final before = [@@ -331,7 +461,14 @@ void main() {isTrue,reason: 'the local tab was given a desk id',);- expect(api.batches.single.single['op'], 'seed');+ expect(api.batches.expand((batch) => batch).map((op) => op['op']), [+ 'seed',+ 'tab.layout',+ ]);+ expect(api.doc!.tabs.first.layout?.sizes['2:manual'], [+ [0.0, 0.0, .5, 1.0],+ [.5, 0.0, 1.0, 1.0],+ ]);// The desk's own tabs first, this computer's after them — that is where the seed puts them.expect(app.swarms.map((s) => s.id), ['d1', own.id]);final remote = app.swarms.first;@@ -561,11 +698,11 @@ void main() {expect(d1.name, 'One, really');expect(d1.panes.map((p) => p.agentId), ['a1', 'a2', 'a4']);expect(d1.focusedPaneId, second.id, reason: 'focus is this window\'s');- expect(- api.batches,- isEmpty,- reason: 'applying the desk sends nothing back',- );+ expect(api.batches.expand((batch) => batch).map((op) => op['op']), ['tab.layout'],+ reason: 'the legacy new pane count gets shared geometry once');+ api.batches.clear();+ await app.deskFetchForTest();+ expect(api.batches, isEmpty, reason: 'canonical geometry never echoes');});test('a document that did not move a tab\'s order leaves this window\'s tiles, sizes and pins alone', () async {@@ -903,9 +1040,9 @@ void main() {await Future<void>.delayed(Duration.zero);expect(work.presets[2], PanePreset.rows);expect(- work.paneSizes,- isEmpty,- reason: 'the preset replaced the split, as choosing it here would',+ work.manualLayout?.tiles,+ PanePreset.rows.tilesFor(2),+ reason: 'the preset replaces the split with shared normalized slots',);});diff --git a/desktop/test/shared_pane_layout_test.dart b/desktop/test/shared_pane_layout_test.dartnew file mode 100644index 000000000..b8a608a68--- /dev/null+++ b/desktop/test/shared_pane_layout_test.dart@@ -0,0 +1,65 @@+// Wire fixtures are generated from desktop's real layout catalogue and consumed+// by hn's independent cell renderer. Regenerate only for an intentional change:+// UPDATE_SHARED_LAYOUT_FIXTURES=1 flutter test test/shared_pane_layout_test.dart+import 'dart:convert';+import 'dart:io';+import 'dart:ui';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/state/pane_arrangement.dart';+import 'package:harness/state/pane_preset.dart';++void main() {+ test('desktop and hn share the complete layout catalogue and slot order', () {+ final cases = <Map<String, Object>>[];+ for (var count = 2; count <= 9; count++) {+ for (final preset in PanePreset.forCount(count)) {+ cases.add({+ 'count': count,+ 'preset': preset.id,+ 'label': preset.label,+ 'offered': true,+ 'tiles': PaneArrangement(preset.tilesFor(count)).toJson(),+ });+ }+ for (final preset in [+ PanePreset.defaultFor(count)!,+ PanePreset.cols2,+ PanePreset.cols3,+ PanePreset.cols4,+ PanePreset.cols5,+ ]) {+ cases.add({+ 'count': count,+ 'preset': preset.id,+ 'offered': false,+ 'tiles': PaneArrangement(preset.tilesFor(count))+ .fillRowEnds()+ .toJson(),+ });+ }+ }+ final fixture = File('../tests/fixtures/shared-pane-layouts.json');+ if (Platform.environment['UPDATE_SHARED_LAYOUT_FIXTURES'] == '1') {+ fixture.writeAsStringSync('[\n${cases.map(jsonEncode).join(',\n')}\n]\n');+ }+ expect(jsonDecode(fixture.readAsStringSync()), cases);+ });++ test(+ 'legacy empty row ends fill without changing other cuts or pane order',+ () {+ final old = PaneArrangement(PanePreset.cols3.tilesFor(5));+ final next = old.fillRowEnds();+ expect(next.tiles.take(4), old.tiles.take(4));+ expect(next.tiles.last, const Rect.fromLTRB(1 / 3, .5, 1, 1));+ expect(identical(next.fillRowEnds(), next), isTrue);+ for (var count = 2; count <= 9; count++) {+ for (final preset in PanePreset.forCount(count)) {+ final layout = PaneArrangement(preset.tilesFor(count));+ expect(identical(layout.fillRowEnds(), layout), isTrue);+ }+ }+ },+ );+}diff --git a/tests/fixtures/shared-pane-layouts.json b/tests/fixtures/shared-pane-layouts.jsonnew file mode 100644index 000000000..5192032d7--- /dev/null+++ b/tests/fixtures/shared-pane-layouts.json@@ -0,0 +1,80 @@+[+{"count":2,"preset":"columns","label":"Columns","offered":true,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,1.0,1.0]]},+{"count":2,"preset":"rows","label":"Rows","offered":true,"tiles":[[0.0,0.0,1.0,0.5],[0.0,0.5,1.0,1.0]]},+{"count":2,"preset":"splitLong","offered":false,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,1.0,1.0]]},+{"count":2,"preset":"cols2","offered":false,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,1.0,1.0]]},+{"count":2,"preset":"cols3","offered":false,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,1.0,1.0]]},+{"count":2,"preset":"cols4","offered":false,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,1.0,1.0]]},+{"count":2,"preset":"cols5","offered":false,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,1.0,1.0]]},+{"count":3,"preset":"cols3","label":"3 columns","offered":true,"tiles":[[0.0,0.0,0.3333333333333333,1.0],[0.3333333333333333,0.0,0.6666666666666666,1.0],[0.6666666666666666,0.0,1.0,1.0]]},+{"count":3,"preset":"twoOverOne","label":"Main bottom","offered":true,"tiles":[[0.0,0.0,0.5,0.5],[0.5,0.0,1.0,0.5],[0.0,0.5,1.0,1.0]]},+{"count":3,"preset":"oneOverTwo","label":"Main top","offered":true,"tiles":[[0.0,0.0,1.0,0.5],[0.0,0.5,0.5,1.0],[0.5,0.5,1.0,1.0]]},+{"count":3,"preset":"mainLeft","label":"Main left","offered":true,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,1.0,0.5],[0.5,0.5,1.0,1.0]]},+{"count":3,"preset":"mainRight","label":"Main right","offered":true,"tiles":[[0.0,0.0,0.5,0.5],[0.5,0.0,1.0,1.0],[0.0,0.5,0.5,1.0]]},+{"count":3,"preset":"rows","label":"Rows","offered":true,"tiles":[[0.0,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,1.0,1.0]]},+{"count":3,"preset":"cols3","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,1.0],[0.3333333333333333,0.0,0.6666666666666666,1.0],[0.6666666666666666,0.0,1.0,1.0]]},+{"count":3,"preset":"cols2","offered":false,"tiles":[[0.0,0.0,0.5,0.5],[0.5,0.0,1.0,0.5],[0.0,0.5,1.0,1.0]]},+{"count":3,"preset":"cols3","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,1.0],[0.3333333333333333,0.0,0.6666666666666666,1.0],[0.6666666666666666,0.0,1.0,1.0]]},+{"count":3,"preset":"cols4","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,1.0],[0.3333333333333333,0.0,0.6666666666666666,1.0],[0.6666666666666666,0.0,1.0,1.0]]},+{"count":3,"preset":"cols5","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,1.0],[0.3333333333333333,0.0,0.6666666666666666,1.0],[0.6666666666666666,0.0,1.0,1.0]]},+{"count":4,"preset":"quad","label":"Grid","offered":true,"tiles":[[0.0,0.0,0.5,0.5],[0.5,0.0,1.0,0.5],[0.0,0.5,0.5,1.0],[0.5,0.5,1.0,1.0]]},+{"count":4,"preset":"mainAndStack","label":"Main left","offered":true,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,1.0,0.3333333333333333],[0.5,0.3333333333333333,1.0,0.6666666666666666],[0.5,0.6666666666666666,1.0,1.0]]},+{"count":4,"preset":"mainOverGrid","label":"Main top","offered":true,"tiles":[[0.0,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,1.0],[0.3333333333333333,0.5,0.6666666666666666,1.0],[0.6666666666666666,0.5,1.0,1.0]]},+{"count":4,"preset":"cols4","label":"4 columns","offered":true,"tiles":[[0.0,0.0,0.25,1.0],[0.25,0.0,0.5,1.0],[0.5,0.0,0.75,1.0],[0.75,0.0,1.0,1.0]]},+{"count":4,"preset":"rows","label":"Rows","offered":true,"tiles":[[0.0,0.0,1.0,0.25],[0.0,0.25,1.0,0.5],[0.0,0.5,1.0,0.75],[0.0,0.75,1.0,1.0]]},+{"count":4,"preset":"quad","offered":false,"tiles":[[0.0,0.0,0.5,0.5],[0.5,0.0,1.0,0.5],[0.0,0.5,0.5,1.0],[0.5,0.5,1.0,1.0]]},+{"count":4,"preset":"cols2","offered":false,"tiles":[[0.0,0.0,0.5,0.5],[0.5,0.0,1.0,0.5],[0.0,0.5,0.5,1.0],[0.5,0.5,1.0,1.0]]},+{"count":4,"preset":"cols3","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,0.5],[0.3333333333333333,0.0,0.6666666666666666,0.5],[0.6666666666666666,0.0,1.0,0.5],[0.0,0.5,1.0,1.0]]},+{"count":4,"preset":"cols4","offered":false,"tiles":[[0.0,0.0,0.25,1.0],[0.25,0.0,0.5,1.0],[0.5,0.0,0.75,1.0],[0.75,0.0,1.0,1.0]]},+{"count":4,"preset":"cols5","offered":false,"tiles":[[0.0,0.0,0.25,1.0],[0.25,0.0,0.5,1.0],[0.5,0.0,0.75,1.0],[0.75,0.0,1.0,1.0]]},+{"count":5,"preset":"middleMain","label":"Middle + sides","offered":true,"tiles":[[0.0,0.0,0.3333333333333333,0.5],[0.3333333333333333,0.0,0.6666666666666666,1.0],[0.6666666666666666,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,1.0],[0.6666666666666666,0.5,1.0,1.0]]},+{"count":5,"preset":"balanced3","label":"3 columns","offered":true,"tiles":[[0.0,0.0,0.3333333333333333,0.5],[0.3333333333333333,0.0,0.6666666666666666,0.5],[0.6666666666666666,0.0,1.0,0.5],[0.0,0.5,0.5,1.0],[0.5,0.5,1.0,1.0]]},+{"count":5,"preset":"twoOverThree","label":"Two over three","offered":true,"tiles":[[0.0,0.0,0.5,0.5],[0.5,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,1.0],[0.3333333333333333,0.5,0.6666666666666666,1.0],[0.6666666666666666,0.5,1.0,1.0]]},+{"count":5,"preset":"mainAndGrid","label":"Main left","offered":true,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,0.75,0.5],[0.75,0.0,1.0,0.5],[0.5,0.5,0.75,1.0],[0.75,0.5,1.0,1.0]]},+{"count":5,"preset":"mainOverGrid","label":"Main top","offered":true,"tiles":[[0.0,0.0,1.0,0.5],[0.0,0.5,0.5,0.75],[0.5,0.5,1.0,0.75],[0.0,0.75,0.5,1.0],[0.5,0.75,1.0,1.0]]},+{"count":5,"preset":"cols5","label":"5 columns","offered":true,"tiles":[[0.0,0.0,0.2,1.0],[0.2,0.0,0.4,1.0],[0.4,0.0,0.6,1.0],[0.6,0.0,0.8,1.0],[0.8,0.0,1.0,1.0]]},+{"count":5,"preset":"middleMain","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,0.5],[0.3333333333333333,0.0,0.6666666666666666,1.0],[0.6666666666666666,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,1.0],[0.6666666666666666,0.5,1.0,1.0]]},+{"count":5,"preset":"cols2","offered":false,"tiles":[[0.0,0.0,0.5,0.3333333333333333],[0.5,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.5,0.6666666666666666],[0.5,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,1.0,1.0]]},+{"count":5,"preset":"cols3","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,0.5],[0.3333333333333333,0.0,0.6666666666666666,0.5],[0.6666666666666666,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,1.0],[0.3333333333333333,0.5,1.0,1.0]]},+{"count":5,"preset":"cols4","offered":false,"tiles":[[0.0,0.0,0.25,0.5],[0.25,0.0,0.5,0.5],[0.5,0.0,0.75,0.5],[0.75,0.0,1.0,0.5],[0.0,0.5,1.0,1.0]]},+{"count":5,"preset":"cols5","offered":false,"tiles":[[0.0,0.0,0.2,1.0],[0.2,0.0,0.4,1.0],[0.4,0.0,0.6,1.0],[0.6,0.0,0.8,1.0],[0.8,0.0,1.0,1.0]]},+{"count":6,"preset":"balanced2","label":"2 columns","offered":true,"tiles":[[0.0,0.0,0.5,0.3333333333333333],[0.5,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.5,0.6666666666666666],[0.5,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,0.5,1.0],[0.5,0.6666666666666666,1.0,1.0]]},+{"count":6,"preset":"balanced3","label":"3 columns","offered":true,"tiles":[[0.0,0.0,0.3333333333333333,0.5],[0.3333333333333333,0.0,0.6666666666666666,0.5],[0.6666666666666666,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,1.0],[0.3333333333333333,0.5,0.6666666666666666,1.0],[0.6666666666666666,0.5,1.0,1.0]]},+{"count":6,"preset":"mainAndGrid","label":"Main left","offered":true,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,0.75,0.3333333333333333],[0.75,0.0,1.0,0.3333333333333333],[0.5,0.3333333333333333,0.75,0.6666666666666666],[0.75,0.3333333333333333,1.0,0.6666666666666666],[0.5,0.6666666666666666,1.0,1.0]]},+{"count":6,"preset":"mainOverGrid","label":"Main top","offered":true,"tiles":[[0.0,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,0.75],[0.3333333333333333,0.5,0.6666666666666666,0.75],[0.6666666666666666,0.5,1.0,0.75],[0.0,0.75,0.5,1.0],[0.5,0.75,1.0,1.0]]},+{"count":6,"preset":"auto","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,0.5],[0.3333333333333333,0.0,0.6666666666666666,0.5],[0.6666666666666666,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,1.0],[0.3333333333333333,0.5,0.6666666666666666,1.0],[0.6666666666666666,0.5,1.0,1.0]]},+{"count":6,"preset":"cols2","offered":false,"tiles":[[0.0,0.0,0.5,0.3333333333333333],[0.5,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.5,0.6666666666666666],[0.5,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,0.5,1.0],[0.5,0.6666666666666666,1.0,1.0]]},+{"count":6,"preset":"cols3","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,0.5],[0.3333333333333333,0.0,0.6666666666666666,0.5],[0.6666666666666666,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,1.0],[0.3333333333333333,0.5,0.6666666666666666,1.0],[0.6666666666666666,0.5,1.0,1.0]]},+{"count":6,"preset":"cols4","offered":false,"tiles":[[0.0,0.0,0.25,0.5],[0.25,0.0,0.5,0.5],[0.5,0.0,0.75,0.5],[0.75,0.0,1.0,0.5],[0.0,0.5,0.25,1.0],[0.25,0.5,1.0,1.0]]},+{"count":6,"preset":"cols5","offered":false,"tiles":[[0.0,0.0,0.2,0.5],[0.2,0.0,0.4,0.5],[0.4,0.0,0.6,0.5],[0.6,0.0,0.8,0.5],[0.8,0.0,1.0,0.5],[0.0,0.5,1.0,1.0]]},+{"count":7,"preset":"balanced2","label":"2 columns","offered":true,"tiles":[[0.0,0.0,0.5,0.25],[0.5,0.0,1.0,0.25],[0.0,0.25,0.5,0.5],[0.5,0.25,1.0,0.5],[0.0,0.5,0.5,0.75],[0.5,0.5,1.0,0.75],[0.0,0.75,1.0,1.0]]},+{"count":7,"preset":"balanced3","label":"3 columns","offered":true,"tiles":[[0.0,0.0,0.3333333333333333,0.3333333333333333],[0.3333333333333333,0.0,0.6666666666666666,0.3333333333333333],[0.6666666666666666,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.5,0.6666666666666666],[0.5,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,0.5,1.0],[0.5,0.6666666666666666,1.0,1.0]]},+{"count":7,"preset":"balanced4","label":"4 columns","offered":true,"tiles":[[0.0,0.0,0.25,0.5],[0.25,0.0,0.5,0.5],[0.5,0.0,0.75,0.5],[0.75,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,1.0],[0.3333333333333333,0.5,0.6666666666666666,1.0],[0.6666666666666666,0.5,1.0,1.0]]},+{"count":7,"preset":"mainAndGrid","label":"Main left","offered":true,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,0.75,0.3333333333333333],[0.75,0.0,1.0,0.3333333333333333],[0.5,0.3333333333333333,0.75,0.6666666666666666],[0.75,0.3333333333333333,1.0,0.6666666666666666],[0.5,0.6666666666666666,0.75,1.0],[0.75,0.6666666666666666,1.0,1.0]]},+{"count":7,"preset":"mainOverGrid","label":"Main top","offered":true,"tiles":[[0.0,0.0,1.0,0.5],[0.0,0.5,0.3333333333333333,0.75],[0.3333333333333333,0.5,0.6666666666666666,0.75],[0.6666666666666666,0.5,1.0,0.75],[0.0,0.75,0.3333333333333333,1.0],[0.3333333333333333,0.75,0.6666666666666666,1.0],[0.6666666666666666,0.75,1.0,1.0]]},+{"count":7,"preset":"auto","offered":false,"tiles":[[0.0,0.0,0.25,0.5],[0.25,0.0,0.5,0.5],[0.5,0.0,0.75,0.5],[0.75,0.0,1.0,0.5],[0.0,0.5,0.25,1.0],[0.25,0.5,0.5,1.0],[0.5,0.5,1.0,1.0]]},+{"count":7,"preset":"cols2","offered":false,"tiles":[[0.0,0.0,0.5,0.25],[0.5,0.0,1.0,0.25],[0.0,0.25,0.5,0.5],[0.5,0.25,1.0,0.5],[0.0,0.5,0.5,0.75],[0.5,0.5,1.0,0.75],[0.0,0.75,1.0,1.0]]},+{"count":7,"preset":"cols3","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,0.3333333333333333],[0.3333333333333333,0.0,0.6666666666666666,0.3333333333333333],[0.6666666666666666,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.3333333333333333,0.6666666666666666],[0.3333333333333333,0.3333333333333333,0.6666666666666666,0.6666666666666666],[0.6666666666666666,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,1.0,1.0]]},+{"count":7,"preset":"cols4","offered":false,"tiles":[[0.0,0.0,0.25,0.5],[0.25,0.0,0.5,0.5],[0.5,0.0,0.75,0.5],[0.75,0.0,1.0,0.5],[0.0,0.5,0.25,1.0],[0.25,0.5,0.5,1.0],[0.5,0.5,1.0,1.0]]},+{"count":7,"preset":"cols5","offered":false,"tiles":[[0.0,0.0,0.2,0.5],[0.2,0.0,0.4,0.5],[0.4,0.0,0.6,0.5],[0.6,0.0,0.8,0.5],[0.8,0.0,1.0,0.5],[0.0,0.5,0.2,1.0],[0.2,0.5,1.0,1.0]]},+{"count":8,"preset":"balanced2","label":"2 columns","offered":true,"tiles":[[0.0,0.0,0.5,0.25],[0.5,0.0,1.0,0.25],[0.0,0.25,0.5,0.5],[0.5,0.25,1.0,0.5],[0.0,0.5,0.5,0.75],[0.5,0.5,1.0,0.75],[0.0,0.75,0.5,1.0],[0.5,0.75,1.0,1.0]]},+{"count":8,"preset":"balanced3","label":"3 columns","offered":true,"tiles":[[0.0,0.0,0.3333333333333333,0.3333333333333333],[0.3333333333333333,0.0,0.6666666666666666,0.3333333333333333],[0.6666666666666666,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.3333333333333333,0.6666666666666666],[0.3333333333333333,0.3333333333333333,0.6666666666666666,0.6666666666666666],[0.6666666666666666,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,0.5,1.0],[0.5,0.6666666666666666,1.0,1.0]]},+{"count":8,"preset":"balanced4","label":"4 columns","offered":true,"tiles":[[0.0,0.0,0.25,0.5],[0.25,0.0,0.5,0.5],[0.5,0.0,0.75,0.5],[0.75,0.0,1.0,0.5],[0.0,0.5,0.25,1.0],[0.25,0.5,0.5,1.0],[0.5,0.5,0.75,1.0],[0.75,0.5,1.0,1.0]]},+{"count":8,"preset":"mainAndGrid","label":"Main left","offered":true,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,0.75,0.25],[0.75,0.0,1.0,0.25],[0.5,0.25,0.75,0.5],[0.75,0.25,1.0,0.5],[0.5,0.5,0.75,0.75],[0.75,0.5,1.0,0.75],[0.5,0.75,1.0,1.0]]},+{"count":8,"preset":"mainOverGrid","label":"Main top","offered":true,"tiles":[[0.0,0.0,1.0,0.5],[0.0,0.5,0.25,0.75],[0.25,0.5,0.5,0.75],[0.5,0.5,0.75,0.75],[0.75,0.5,1.0,0.75],[0.0,0.75,0.3333333333333333,1.0],[0.3333333333333333,0.75,0.6666666666666666,1.0],[0.6666666666666666,0.75,1.0,1.0]]},+{"count":8,"preset":"auto","offered":false,"tiles":[[0.0,0.0,0.25,0.5],[0.25,0.0,0.5,0.5],[0.5,0.0,0.75,0.5],[0.75,0.0,1.0,0.5],[0.0,0.5,0.25,1.0],[0.25,0.5,0.5,1.0],[0.5,0.5,0.75,1.0],[0.75,0.5,1.0,1.0]]},+{"count":8,"preset":"cols2","offered":false,"tiles":[[0.0,0.0,0.5,0.25],[0.5,0.0,1.0,0.25],[0.0,0.25,0.5,0.5],[0.5,0.25,1.0,0.5],[0.0,0.5,0.5,0.75],[0.5,0.5,1.0,0.75],[0.0,0.75,0.5,1.0],[0.5,0.75,1.0,1.0]]},+{"count":8,"preset":"cols3","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,0.3333333333333333],[0.3333333333333333,0.0,0.6666666666666666,0.3333333333333333],[0.6666666666666666,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.3333333333333333,0.6666666666666666],[0.3333333333333333,0.3333333333333333,0.6666666666666666,0.6666666666666666],[0.6666666666666666,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,0.3333333333333333,1.0],[0.3333333333333333,0.6666666666666666,1.0,1.0]]},+{"count":8,"preset":"cols4","offered":false,"tiles":[[0.0,0.0,0.25,0.5],[0.25,0.0,0.5,0.5],[0.5,0.0,0.75,0.5],[0.75,0.0,1.0,0.5],[0.0,0.5,0.25,1.0],[0.25,0.5,0.5,1.0],[0.5,0.5,0.75,1.0],[0.75,0.5,1.0,1.0]]},+{"count":8,"preset":"cols5","offered":false,"tiles":[[0.0,0.0,0.2,0.5],[0.2,0.0,0.4,0.5],[0.4,0.0,0.6,0.5],[0.6,0.0,0.8,0.5],[0.8,0.0,1.0,0.5],[0.0,0.5,0.2,1.0],[0.2,0.5,0.4,1.0],[0.4,0.5,1.0,1.0]]},+{"count":9,"preset":"balanced2","label":"2 columns","offered":true,"tiles":[[0.0,0.0,0.5,0.2],[0.5,0.0,1.0,0.2],[0.0,0.2,0.5,0.4],[0.5,0.2,1.0,0.4],[0.0,0.4,0.5,0.6],[0.5,0.4,1.0,0.6],[0.0,0.6,0.5,0.8],[0.5,0.6,1.0,0.8],[0.0,0.8,1.0,1.0]]},+{"count":9,"preset":"balanced3","label":"3 columns","offered":true,"tiles":[[0.0,0.0,0.3333333333333333,0.3333333333333333],[0.3333333333333333,0.0,0.6666666666666666,0.3333333333333333],[0.6666666666666666,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.3333333333333333,0.6666666666666666],[0.3333333333333333,0.3333333333333333,0.6666666666666666,0.6666666666666666],[0.6666666666666666,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,0.3333333333333333,1.0],[0.3333333333333333,0.6666666666666666,0.6666666666666666,1.0],[0.6666666666666666,0.6666666666666666,1.0,1.0]]},+{"count":9,"preset":"balanced5","label":"5 columns","offered":true,"tiles":[[0.0,0.0,0.2,0.5],[0.2,0.0,0.4,0.5],[0.4,0.0,0.6,0.5],[0.6,0.0,0.8,0.5],[0.8,0.0,1.0,0.5],[0.0,0.5,0.25,1.0],[0.25,0.5,0.5,1.0],[0.5,0.5,0.75,1.0],[0.75,0.5,1.0,1.0]]},+{"count":9,"preset":"mainAndGrid","label":"Main left","offered":true,"tiles":[[0.0,0.0,0.5,1.0],[0.5,0.0,0.75,0.25],[0.75,0.0,1.0,0.25],[0.5,0.25,0.75,0.5],[0.75,0.25,1.0,0.5],[0.5,0.5,0.75,0.75],[0.75,0.5,1.0,0.75],[0.5,0.75,0.75,1.0],[0.75,0.75,1.0,1.0]]},+{"count":9,"preset":"mainOverGrid","label":"Main top","offered":true,"tiles":[[0.0,0.0,1.0,0.5],[0.0,0.5,0.25,0.75],[0.25,0.5,0.5,0.75],[0.5,0.5,0.75,0.75],[0.75,0.5,1.0,0.75],[0.0,0.75,0.25,1.0],[0.25,0.75,0.5,1.0],[0.5,0.75,0.75,1.0],[0.75,0.75,1.0,1.0]]},+{"count":9,"preset":"auto","offered":false,"tiles":[[0.0,0.0,0.25,0.3333333333333333],[0.25,0.0,0.5,0.3333333333333333],[0.5,0.0,0.75,0.3333333333333333],[0.75,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.25,0.6666666666666666],[0.25,0.3333333333333333,0.5,0.6666666666666666],[0.5,0.3333333333333333,0.75,0.6666666666666666],[0.75,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,1.0,1.0]]},+{"count":9,"preset":"cols2","offered":false,"tiles":[[0.0,0.0,0.5,0.2],[0.5,0.0,1.0,0.2],[0.0,0.2,0.5,0.4],[0.5,0.2,1.0,0.4],[0.0,0.4,0.5,0.6],[0.5,0.4,1.0,0.6],[0.0,0.6,0.5,0.8],[0.5,0.6,1.0,0.8],[0.0,0.8,1.0,1.0]]},+{"count":9,"preset":"cols3","offered":false,"tiles":[[0.0,0.0,0.3333333333333333,0.3333333333333333],[0.3333333333333333,0.0,0.6666666666666666,0.3333333333333333],[0.6666666666666666,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.3333333333333333,0.6666666666666666],[0.3333333333333333,0.3333333333333333,0.6666666666666666,0.6666666666666666],[0.6666666666666666,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,0.3333333333333333,1.0],[0.3333333333333333,0.6666666666666666,0.6666666666666666,1.0],[0.6666666666666666,0.6666666666666666,1.0,1.0]]},+{"count":9,"preset":"cols4","offered":false,"tiles":[[0.0,0.0,0.25,0.3333333333333333],[0.25,0.0,0.5,0.3333333333333333],[0.5,0.0,0.75,0.3333333333333333],[0.75,0.0,1.0,0.3333333333333333],[0.0,0.3333333333333333,0.25,0.6666666666666666],[0.25,0.3333333333333333,0.5,0.6666666666666666],[0.5,0.3333333333333333,0.75,0.6666666666666666],[0.75,0.3333333333333333,1.0,0.6666666666666666],[0.0,0.6666666666666666,1.0,1.0]]},+{"count":9,"preset":"cols5","offered":false,"tiles":[[0.0,0.0,0.2,0.5],[0.2,0.0,0.4,0.5],[0.4,0.0,0.6,0.5],[0.6,0.0,0.8,0.5],[0.8,0.0,1.0,0.5],[0.0,0.5,0.2,1.0],[0.2,0.5,0.4,1.0],[0.4,0.5,0.6,1.0],[0.6,0.5,1.0,1.0]]}+]diff --git a/tui/README.md b/tui/README.mdindex 4fa880f01..5a403c634 100644--- a/tui/README.md+++ b/tui/README.md@@ -85,6 +85,13 @@ whole file checked first, so a bad line is `file:line: why` and none of that filtmux. `run-shell` lines run too: a plugin's `tmux …` reaches hn (the `tmux` on its PATH is hn),never a tmux server you have running.+Shared tabs use the same ordered pane rectangles as desktop, including custom divider+proportions. The layout picker offers desktop's shapes for the current pane count;+`C-b Space` still cycles tmux's seven layouts and shares their exact geometry.+Window resizing scales the saved arrangement without rearranging panes or publishing+an edit. Selected tab, focus and zoom remain local to each client. Standalone tmux+sessions retain tmux's resize behavior.+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 split sizes, the samepane numbers and the same active pane after each. hn draws these layouts as pane surfacesdiff --git a/tui/src/app.rs b/tui/src/app.rsindex 36acc4c44..31ed80b6e 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -322,8 +322,8 @@ pub struct Tab {/// automatic-rename off: the window has had the name tmux gives one when it is made/// (default_window_name: a shell by its command), and keeps it.pub first_named: bool,- /// The desk's layout document for this tab, kept whole: a preset chosen here updates its entry- /// and leaves the sizes other windows saved alone.+ /// The desk's complete layout document. An explicit edit replaces the+ /// current count's normalized slots, retaining other counts' saved layouts.pub layout: Value,/// Last layout observed on the desk, separate from the local edit awaiting its reply.pub desk_layout: Value,@@ -331,6 +331,9 @@ pub struct Tab {desk_panes: Vec<(String, String)>,/// A named choice awaiting publication, separate from the last observed desk document.desk_preset: Option<(usize, &'static str)>,+ /// Unrounded shared slots and their local pane identities, independent of+ /// tmux pane numbering and the current terminal dimensions.+ shared_geometry: Option<crate::desk_layout::Geometry>,}impl Tab {@@ -342,7 +345,23 @@ 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!({}), desk_panes: Vec::new(), desk_preset: None }+ 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_panes: Vec::new(), desk_preset: None, shared_geometry: None }+ }+ fn fit_layout(&mut self, size: (u16, u16), status: layout::Status) -> bool {+ let Some(root) = self.root.as_mut() else { return false };+ let changed = root.size() != size || root.status != status;+ root.status = status;+ if changed && !self.shared_geometry.as_mut().is_some_and(|g| g.fit(root, size.0, size.1, status)) {+ root.resize(size.0, size.1);+ }+ changed+ }++ fn read_shared_layout(&mut self, ids: &[u64], w: u16, h: u16) {+ let preset = preset_from_desk(crate::desk_layout::preset_id(&self.layout, ids.len()), ids.len());+ let (root, geometry) = desk_geometry(&self.layout, preset, ids, w, h).unzip();+ self.root = root;+ self.shared_geometry = geometry;}/// Its @N, numbered now if it has none yet.pub fn wid(&self) -> u64 {@@ -1984,9 +2003,8 @@ impl App {if !own && tab.size.is_none() { return }let status = app.pane_status(tab);let size = tab.size.unwrap_or(default);- let Some(root) = tab.root.as_mut() else { return };- root.status = status;- if root.size() != size { root.resize(size.0, size.1) }+ tab.fit_layout(size, status);+ let Some(root) = tab.root.as_ref() else { return };let area = Rect::new(0, 0, size.0, size.1);let mut out = Vec::new();match tab.focus.filter(|_| tab.zoomed) { Some(f) => out.push((f, area)), None => root.rects(area, &mut out) }@@ -2034,10 +2052,9 @@ impl App {let size = if manual { self.tabs[i].size.or_else(|| self.tabs[i].root.as_ref().map(|r| r.size())) }else if creating && self.tabs[i].size.is_some() { self.tabs[i].size }else { self.tabs[i].size = None; (onscreen && i == self.active).then_some((body.width, body.height)) };- if let Some(root) = self.tabs[i].root.as_mut() {- root.status = status;- if let Some(size) = size { if root.size() != size { root.resize(size.0, size.1); resized.push(i) } }- }+ if let Some(size) = size {+ if self.tabs[i].fit_layout(size, status) { resized.push(i) }+ } else if let Some(root) = self.tabs[i].root.as_mut() { root.status = status; }}for i in resized {let id = self.tabs[i].id.clone();@@ -4587,11 +4604,24 @@ impl App {pub fn layout_changed(&mut self, t: usize) {// A desk window's layout changed here: every terminal lays it out so (sent once the// loop comes round).- if self.session_desk { if let Some(tab) = self.tabs.get(t).filter(|t| t.on_desk) { self.desk_layouts.insert(tab.id.clone()); } }+ if self.session_desk { if let Some(tab) = self.tabs.get_mut(t).filter(|t| t.on_desk) {+ if let Some(root) = &tab.root {+ if !tab.shared_geometry.as_ref().is_some_and(|g| g.matches(root)) {+ tab.shared_geometry = Some(crate::desk_layout::Geometry::capture(root));+ }+ }+ self.desk_layouts.insert(tab.id.clone());+ } }+ self.view_layout_changed(t)+ }++ /// Zoom, theme and viewport dimensions affect this client only.+ pub fn view_layout_changed(&mut self, t: usize) {crate::commands::notify(self, "window-layout-changed", Some(t), None)}- /// The desk windows whose layout changed here: their tmux layout to the desk (tab.layout).+ /// Publish explicit geometry and its matching pane-reference order together.+ /// The tmux string remains as a fallback for older hn clients.pub fn send_desk_layouts(&mut self) {if self.desk_layouts.is_empty() || !self.session_desk { return }let mut ops = Vec::new();@@ -4601,6 +4631,11 @@ impl App {if !tab.layout.is_object() { tab.layout = json!({}) }let before = tab.layout.clone();tab.layout["tmux"] = json!(root.to_tmux());+ let geometry = tab.shared_geometry.get_or_insert_with(|| crate::desk_layout::Geometry::capture(root));+ // Shell panes are local; do not assign their slots to remote harnesses.+ let shared = geometry.slots.iter().all(|(id, _)| self.panes.get(id)+ .is_some_and(|p| !crate::local::is_local(&p.machine_id)));+ if shared { geometry.write(&mut tab.layout); }// 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() {@@ -4608,9 +4643,9 @@ impl App {tab.layout["presets"][count.to_string()] = json!(preset);}if tab.layout != before { ops.push(json!({ "op": "tab.layout", "id": tab.id, "layout": tab.layout })); }- // Desktop uses the shared list in screen order, not our stable pane numbers.- // Publish both together, including swaps, rotations and mirrored layouts.- let panes: Vec<_> = desk_pane_ids(root).iter().filter_map(|id| self.panes.get(id))+ // The slot order and the shared reference order must agree, even+ // for non-spatial desktop splits or mirrored tmux layouts.+ let panes: Vec<_> = geometry.slots.iter().filter_map(|(id, _)| self.panes.get(id)).filter(|p| !crate::local::is_local(&p.machine_id)).map(|p| (p.machine_id.clone(), p.agent_id.clone())).collect();if panes != tab.desk_panes {@@ -4958,10 +4993,9 @@ impl App {fn fit_panes_of(&mut self, tab: usize) -> bool {let body = self.body();let status = self.tabs.get(tab).map(|t| self.pane_status(t)).unwrap_or_default();- match self.tabs.get_mut(tab).and_then(|t| t.root.as_mut()) {- Some(root) => { root.status = status; if root.size() != (body.width, body.height) { root.resize(body.width, body.height) } true }- None => false,- }+ let Some(tab) = self.tabs.get_mut(tab).filter(|t| t.root.is_some()) else { return false };+ tab.fit_layout((body.width, body.height), status);+ true}/// resize-pane -x/-y: the pane made that many cells wide or lines tall (its title row, when@@ -5086,11 +5120,23 @@ impl App {self.arrange_tab(index, layout::Named::ALL[at]);}- pub fn apply_preset(&mut self, preset: Preset) { let i = self.active; self.apply_preset_at(i, preset) }-- /// 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));+ /// The same concrete choices as the desktop palette. Native select-layout+ /// and C-b Space keep tmux's own catalogue and publish their exact geometry.+ pub fn apply_shared_preset(&mut self, id: &str) {+ let ids = self.tab().panes();+ let Some(preset) = crate::desk_layout::choices(ids.len()).into_iter().find(|p| *p == id) else { return };+ let Some(tiles) = crate::desk_layout::preset_tiles(preset, ids.len()) else { return };+ let body = self.body();+ let status = self.pane_status(self.tab());+ let Some((root, geometry)) = crate::desk_layout::Geometry::from_tiles(tiles, &ids, body.width, body.height, status) else { return };+ let tab = self.tab_mut();+ tab.root = Some(root);+ tab.shared_geometry = Some(geometry);+ tab.zoomed = false;+ tab.layout_at = None;+ tab.desk_preset = Some((ids.len(), preset));+ self.fit_panes();+ self.layout_changed(self.active);}/// `tui.toml`'s `[look]` table: set each choice as a global option, so `hn show` reflects it@@ -5151,7 +5197,7 @@ impl App {let _ = self.options.set("@hn-theme", None, &unset, "", 0);self.sync_accent();let i = self.active;- self.layout_changed(i);+ self.view_layout_changed(i);self.persist_look();return "theme: the terminal's own".into();}@@ -5175,7 +5221,7 @@ impl App {// (The bar and the frames change the panes' room: every program is told its size.)if matches!(knob, "status_bar" | "border_style") { self.redraw_all = true; self.fit_panes() }let i = self.active;- self.layout_changed(i);+ self.view_layout_changed(i);self.persist_look();message}@@ -5270,7 +5316,6 @@ impl App {seen.push(id.clone());let name = row.get("name").and_then(Value::as_str).unwrap_or("tab").to_string();let named = row.get("nameIsCustom").and_then(Value::as_bool).unwrap_or(false);- let preset = preset_from_desk(row.pointer(&format!("/layout/presets/{}", panes.len())).and_then(Value::as_str).unwrap_or(""), panes.len());let layout_doc = row.get("layout").cloned().unwrap_or(json!({}));match self.tabs.iter().position(|t| t.id == id) {Some(index) => {@@ -5300,13 +5345,23 @@ impl App {let ids: Vec<u64> = panes.iter().filter_map(|key| have.iter().find(|(_, k)| k == key).map(|(id, _)| *id)).collect();if relayout {let (w, h) = (self.size.0, self.size.1.saturating_sub(2));- tab.root = desk_root(&tab.layout, preset, &ids, w, h);+ tab.read_shared_layout(&ids, w, h);if reordered { tab.order = ids; }} else if reordered {// A desktop drag changes only the sequence. Keep our exact// split sizes and the focused harness while changing places.if let Some(root) = &mut tab.root {- if desk_pane_ids(root) != ids { desk_reorder(root, &ids); tab.order = ids; }+ if let Some(tiles) = tab.shared_geometry.as_ref().map(|g| g.slots.iter().map(|(_, t)| *t).collect())+ .or_else(|| crate::desk_layout::saved_tiles(&tab.layout, ids.len())) {+ if let Some((next, geometry)) = crate::desk_layout::Geometry::from_tiles(tiles, &ids, root.size().0, root.size().1, root.status) {+ *root = next;+ tab.shared_geometry = Some(geometry);+ }+ } else {+ desk_reorder(root, &ids);+ tab.shared_geometry = Some(crate::desk_layout::Geometry::capture(root));+ }+ tab.order = ids;}}continue;@@ -5324,7 +5379,7 @@ impl App {}).collect();let tab = &mut self.tabs[index];let (w, h) = (self.size.0, self.size.1.saturating_sub(2));- tab.root = desk_root(&tab.layout, preset, &ids, w, h);+ tab.read_shared_layout(&ids, w, h);tab.order = ids.clone();if tab.focus.map(|f| !ids.contains(&f)).unwrap_or(true) { tab.focus = ids.first().copied() }}@@ -5337,13 +5392,14 @@ impl App {let have = tab.panes();let ids: Vec<_> = panes.iter().filter_map(|(m, a)| have.iter().copied().find(|id|self.panes.get(id).is_some_and(|p| &p.machine_id == m && &p.agent_id == a))).collect();- if ids.len() == have.len() && ids.len() == panes.len() {- if let Some(root) = &mut tab.root { desk_reorder(root, &ids); }- tab.order = ids;- }tab.desk_panes = panes.clone();tab.desk_layout = layout_doc.clone();tab.layout = layout_doc;+ if ids.len() == have.len() && ids.len() == panes.len() {+ let (w, h) = tab.root.as_ref().unwrap().size();+ tab.read_shared_layout(&ids, w, h);+ tab.order = ids;+ }if named { tab.name = name; tab.named = true }let at = rows.iter().position(|r| r.get("id").and_then(Value::as_str) == Some(tab.id.as_str())).unwrap_or(self.tabs.len()).min(self.tabs.len());self.tabs.insert(at, tab);@@ -5360,7 +5416,7 @@ impl App {tab.desk_layout = layout_doc.clone();tab.layout = layout_doc;let (w, h) = (self.size.0, self.size.1.saturating_sub(2));- tab.root = desk_root(&tab.layout, preset, &ids, w, h);+ tab.read_shared_layout(&ids, w, h);tab.order = ids.clone();tab.focus = ids.first().copied();let at = rows.iter().position(|r| r.get("id").and_then(Value::as_str) == Some(tab.id.as_str())).unwrap_or(self.tabs.len()).min(self.tabs.len());@@ -5767,13 +5823,29 @@ pub const DESK_MAIN: (&str, &str) = ("50%", "50%");/// A desk tab's panes laid out: as another terminal left them (its tmux layout, fitted to this/// one's size), else its preset for that many panes.+#[cfg(test)]fn desk_root(doc: &Value, preset: Preset, ids: &[u64], w: u16, h: u16) -> Option<Node> {- let mut root = doc.get("tmux").and_then(Value::as_str).and_then(|l| Node::from_tmux(l, ids, w, h))- .or_else(|| layout::arrange(layout::Named::of(preset), ids, w, h, layout::Status::Top, DESK_MAIN, ("0", "0")))?;+ desk_geometry(doc, preset, ids, w, h).map(|(root, _)| root)+}++fn desk_geometry(doc: &Value, preset: Preset, ids: &[u64], w: u16, h: u16) -> Option<(Node, crate::desk_layout::Geometry)> {+ use crate::desk_layout::{self, Geometry};+ let status = layout::Status::Top;+ if let Some(geometry) = desk_layout::saved_tiles(doc, ids.len())+ .and_then(|tiles| Geometry::from_tiles(tiles, ids, w, h, status)) { return Some(geometry) }+ if let Some(mut root) = doc.get("tmux").and_then(Value::as_str).and_then(|l| Node::from_tmux(l, ids, w, h)) {+ desk_reorder(&mut root, ids);+ let geometry = Geometry::capture(&root);+ return Some((root, geometry));+ }+ if let Some(geometry) = desk_layout::preset_tiles(desk_layout::preset_id(doc, ids.len()), ids.len())+ .and_then(|tiles| Geometry::from_tiles(tiles, ids, w, h, status)) { return Some(geometry) }+ let mut root = layout::arrange(layout::Named::of(preset), ids, w, h, status, DESK_MAIN, ("0", "0"))?;// Numeric pane IDs belong to one hn server. The desk's ordered identities are// authoritative even if a saved native layout has stale or coincidentally matching IDs.desk_reorder(&mut root, ids);- Some(root)+ let geometry = Geometry::capture(&root);+ Some((root, geometry))}/// Desktop numbers its tiles across the top, then down; tmux tree traversal and@@ -5803,15 +5875,19 @@ fn preset_from_desk(id: &str, count: usize) -> Preset {}}-/// 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.+/// Compare only this pane count's consumed geometry. Normalized slots take+/// precedence; native strings and presets support clients predating them.fn desk_layout_changed(before: &Value, after: &Value, count: usize) -> bool {+ let tiles = |doc| crate::desk_layout::saved_tiles(doc, count);+ if tiles(after).is_some() { return tiles(before) != tiles(after) }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)+ // Older desktop versions can omit sizes/tmux on an unrelated save. Only+ // their changed preset is an edit; new clients send geometry for resets too.+ let shape = |doc: &Value| doc.get("presets").and_then(|p| p.get(count.to_string()))+ .and_then(Value::as_str).and_then(|id| crate::desk_layout::preset_tiles(id, count));+ shape(before) != shape(after)}/// Desktop presets with the same split topology. Unsupported shapes retain their@@ -6301,4 +6377,83 @@ mod desk_layout_tests {app.apply_desk(&desk(4, json!({"presets":{"3":"columns"}})));assert_ne!(geometry(&app), chosen);}++ #[test]+ fn desktop_manual_slot_order_survives_resize_focus_zoom_and_remote_moves() {+ let mut app = fixture();+ app.tabs[0].focus = Some(2);+ app.tabs[0].zoomed = true;+ // Splitting the first column makes slots 1 and 2 vertical siblings;+ // slot 3 is on the right. Index order is not screen reading order.+ let tiles = json!([[0.0,0.0,0.3,0.7],[0.0,0.7,0.3,1.0],[0.3,0.0,1.0,1.0]]);+ let layout = json!({"presets":{"3":"cols3"},"sizes":{"3:manual":tiles},"tmux":"obsolete"});+ let mut update = desk(2, layout.clone());+ app.apply_desk(&update);+ let original = geometry(&app);+ assert_eq!(desk_pane_ids(app.tabs[0].root.as_ref().unwrap()), [1, 3, 2]);+ assert_eq!(app.tabs[0].focus, Some(2));+ assert!(app.tabs[0].zoomed);+ for size in [(80, 24), (240, 80), (100, 30), (120, 36)] {+ app.size = size;+ app.fit_panes();+ app.notify_changes();+ }+ assert_eq!(geometry(&app), original);+ assert!(app.desk_layouts.is_empty());+ assert_eq!(app.tabs[0].layout, layout);+ update["revision"] = json!(3);+ update["tabs"][0]["panes"].as_array_mut().unwrap().swap(0, 1);+ app.apply_desk(&update);+ assert_eq!(desk_pane_ids(app.tabs[0].root.as_ref().unwrap()), [2, 3, 1]);+ assert_eq!(app.tabs[0].focus, Some(2));+ assert!(app.panes.values().all(|p| matches!(p.phase, Phase::Live)));+ }++ #[test]+ fn exact_local_preset_survives_queued_resize_and_old_snapshot() {+ let mut app = fixture();+ app.desk_mode = DeskMode::Read;+ app.apply_shared_preset("mainRight");+ app.size = (83, 27);+ app.fit_panes();+ app.apply_desk(&desk(2, json!({"presets":{"3":"rows"}})));+ app.send_desk_layouts();+ assert_eq!(app.tabs[0].layout["presets"]["3"], "mainRight");+ assert_eq!(crate::desk_layout::saved_tiles(&app.tabs[0].layout, 3), crate::desk_layout::preset_tiles("mainRight", 3));+ assert_eq!(desk_pane_ids(app.tabs[0].root.as_ref().unwrap()), [1, 2, 3]);+ let sent = app.tabs[0].layout.clone();+ app.apply_desk(&desk(3, sent.clone()));+ app.apply_desk(&desk(4, json!({"presets":{"3":"mainRight"},"sizes":{}})));+ // Old desktop metadata cannot reset the exact cut. An explicit new+ // desktop divider edit, even with the same preset, still applies.+ let mut resized = sent;+ resized["sizes"]["3:manual"] = json!([[0.0,0.0,0.2,0.6],[0.2,0.0,1.0,1.0],[0.0,0.6,0.2,1.0]]);+ app.apply_desk(&desk(5, resized));+ assert_eq!(app.tabs[0].shared_geometry.as_ref().unwrap().slots[0].1[2], 0.2);+ }++ #[test]+ fn zoom_and_local_chrome_never_publish_layouts() {+ let mut app = fixture();+ crate::input::run(&mut app, "zoom");+ assert!(app.tabs[0].zoomed);+ app.view_layout_changed(0);+ assert!(app.desk_layouts.is_empty());+ crate::input::run(&mut app, "zoom");+ assert!(!app.tabs[0].zoomed);+ assert!(app.desk_layouts.is_empty());+ }++ #[test]+ fn an_explicit_remote_default_replaces_a_read_only_clients_local_choice() {+ let mut app = fixture();+ app.desk_mode = DeskMode::Read;+ app.tabs[0].layout = json!({});+ app.tabs[0].desk_layout = json!({});+ app.apply_shared_preset("rows");+ app.send_desk_layouts();+ app.apply_desk(&desk(2, json!({"presets":{"3":"cols3"}})));+ let slots = app.tabs[0].shared_geometry.as_ref().unwrap();+ assert!(slots.slots.iter().all(|(_, tile)| tile[1] == 0.0 && tile[3] == 1.0));+ }}diff --git a/tui/src/commands.rs b/tui/src/commands.rsindex 24fcc8f6c..3538eae53 100644--- a/tui/src/commands.rs+++ b/tui/src/commands.rs@@ -2056,7 +2056,7 @@ fn run_words_in(app: &mut App, words: &[String]) {// that window made current by nothing (tmux zooms it where it is).if w != app.active {app.tabs[w].set_active(p);- if app.tabs[w].panes().len() > 1 { app.tabs[w].zoomed = !app.tabs[w].zoomed; app.fit_panes(); app.layout_changed(w) }+ if app.tabs[w].panes().len() > 1 { app.tabs[w].zoomed = !app.tabs[w].zoomed; app.fit_panes(); app.view_layout_changed(w) }return;}if app.focused() != Some(p) { app.focus_pane(w, p) }@@ -2898,7 +2898,7 @@ fn run_words_in(app: &mut App, words: &[String]) {app.tabs[w].size = Some(size);app.options.windows.entry(app.tabs[w].id.clone()).or_default().insert("window-size".into(), "manual".into());app.fit_panes();- if app.headless && old != size { app.layout_changed(w) }+ if app.headless && old != size { app.view_layout_changed(w) }}"respawn-window" => {// tmux's respawn-window: refused while anything runs in the window, unless -k.diff --git a/tui/src/desk_layout.rs b/tui/src/desk_layout.rsnew file mode 100644index 000000000..11d6a4ce3--- /dev/null+++ b/tui/src/desk_layout.rs@@ -0,0 +1,233 @@+//! The desktop/hn wire contract: ordered normalized pane rectangles in `sizes["N:manual"]`.+//! Presets are a legacy fallback and the user's label; explicit geometry always wins.+use serde_json::{json, Value};+use crate::layout::{Node, Status};++pub type Tile = [f64; 4];++/// Migration for the unused tail of a legacy desktop lattice row. Matches+/// PaneArrangement.fillRowEnds; no slot is added or reordered.+pub fn fill_row_ends(mut tiles: Vec<Tile>) -> Vec<Tile> {+ let before = tiles.clone();+ for tile in &mut tiles {+ if tile[2] < 1.0 - 0.000001 && !before.iter().any(|other|+ other[0] >= tile[2] - 0.000001 && other[1] < tile[3] - 0.000001 && other[3] > tile[1] + 0.000001) {+ tile[2] = 1.0;+ }+ }+ tiles+}++/// Keep the unrounded source between terminal resizes. `rendered` distinguishes a+/// viewport resize from a tmux command that has just edited the cell tree.+#[derive(Clone, Debug)]+pub struct Geometry {+ pub slots: Vec<(u64, Tile)>,+ rendered: String,+}++impl Geometry {+ pub fn capture(root: &Node) -> Self {+ Self { slots: root.normalized_tiles(), rendered: root.to_tmux() }+ }++ pub fn from_tiles(tiles: Vec<Tile>, ids: &[u64], w: u16, h: u16, status: Status) -> Option<(Node, Self)> {+ let tiles = fill_row_ends(tiles);+ let root = Node::from_tiles(&tiles, ids, w, h, status)?;+ let geometry = Self { slots: ids.iter().copied().zip(tiles).collect(), rendered: root.to_tmux() };+ Some((root, geometry))+ }++ pub fn matches(&self, root: &Node) -> bool { self.rendered == root.to_tmux() }++ pub fn fit(&mut self, root: &mut Node, w: u16, h: u16, status: Status) -> bool {+ if !self.matches(root) { return false }+ let (ids, tiles): (Vec<_>, Vec<_>) = self.slots.iter().copied().unzip();+ let Some(next) = Node::from_tiles(&tiles, &ids, w, h, status) else { return false };+ self.rendered = next.to_tmux();+ *root = next;+ true+ }++ pub fn write(&self, doc: &mut Value) {+ if !doc.is_object() { *doc = json!({}) }+ if !doc.get("sizes").is_some_and(Value::is_object) { doc["sizes"] = json!({}) }+ let count = self.slots.len();+ // One active arrangement per count; stale rendered-preset keys must not+ // compete with it or crowd it out of the server's 16-entry limit.+ let sizes = doc["sizes"].as_object_mut().unwrap();+ sizes.retain(|key, _| !key.starts_with(&format!("{count}:")));+ if count >= 2 {+ while sizes.len() >= 16 { let key = sizes.keys().next().unwrap().clone(); sizes.remove(&key); }+ sizes.insert(format!("{count}:manual"), json!(self.slots.iter().map(|(_, tile)| tile).collect::<Vec<_>>()));+ }+ }+}++pub fn saved_tiles(doc: &Value, count: usize) -> Option<Vec<Tile>> {+ let sizes = doc.get("sizes")?.as_object()?;+ let key = format!("{count}:manual");+ let value = sizes.get(&key).or_else(|| {+ // Desktop builds before the common contract stored a dragged preset under its render key.+ let preset = preset_id(doc, count);+ let prefix = format!("{count}:{preset}:");+ sizes.iter().find(|(key, _)| key.starts_with(&prefix)).map(|(_, value)| value)+ })?;+ let rows = value.as_array().filter(|rows| rows.len() == count)?;+ rows.iter().map(|row| {+ let row = row.as_array().filter(|row| row.len() == 4)?;+ let mut tile = [0.0; 4];+ for (i, value) in row.iter().enumerate() { tile[i] = value.as_f64()?; }+ Some(tile)+ }).collect()+}++pub fn preset_id(doc: &Value, count: usize) -> &str {+ doc.get("presets").and_then(|p| p.get(count.to_string())).and_then(Value::as_str)+ .unwrap_or_else(|| default_preset(count))+}++pub fn default_preset(count: usize) -> &'static str {+ match count { 2 => "splitLong", 3 => "cols3", 4 => "quad", 5 => "middleMain", _ => "auto" }+}++fn lattice(count: usize, columns: usize, balanced: bool, extra_last: bool) -> Vec<Tile> {+ let columns = columns.clamp(1, count);+ let rows = count.div_ceil(columns);+ (0..rows).flat_map(|row| {+ let n = if balanced { count / rows + usize::from(if extra_last { row >= rows - count % rows } else { row < count % rows }) }+ else { columns.min(count - row * columns) };+ let width = if balanced { n } else { columns } as f64;+ (0..n).map(move |col| [col as f64 / width, row as f64 / rows as f64,+ (col + 1) as f64 / width, (row + 1) as f64 / rows as f64])+ }).collect()+}++/// Matches PanePreset.tilesFor. The shared fixtures exercise every offered shape at each count.+pub fn preset_tiles(id: &str, count: usize) -> Option<Vec<Tile>> {+ if !(1..=64).contains(&count) { return None }+ if count == 1 { return Some(vec![[0.0, 0.0, 1.0, 1.0]]) }+ Some(match id {+ // `columns` was used for 3+ panes by older hn builds.+ "columns" | "splitLong" => lattice(count, count, false, false),+ "rows" => lattice(count, 1, false, false),+ "cols2" => lattice(count, 2, false, false),+ "cols3" | "threeColumns" => lattice(count, 3, false, false),+ "cols4" | "fourColumns" => lattice(count, 4, false, false),+ "cols5" => lattice(count, 5, false, false),+ "balanced2" => lattice(count, 2, true, false),+ "balanced3" => lattice(count, 3, true, false),+ "balanced4" => lattice(count, 4, true, false),+ "balanced5" => lattice(count, 5, true, false),+ "auto" => lattice(count, if count <= 6 { 3 } else { 4 }, false, false),+ "twoOverOne" if count == 3 => vec![[0.0,0.0,0.5,0.5], [0.5,0.0,1.0,0.5], [0.0,0.5,1.0,1.0]],+ "oneOverTwo" if count == 3 => vec![[0.0,0.0,1.0,0.5], [0.0,0.5,0.5,1.0], [0.5,0.5,1.0,1.0]],+ "mainLeft" if count == 3 => vec![[0.0,0.0,0.5,1.0], [0.5,0.0,1.0,0.5], [0.5,0.5,1.0,1.0]],+ "mainRight" if count == 3 => vec![[0.0,0.0,0.5,0.5], [0.5,0.0,1.0,1.0], [0.0,0.5,0.5,1.0]],+ "quad" if count == 4 => lattice(count, 2, false, false),+ "mainAndStack" if count == 4 => vec![[0.0,0.0,0.5,1.0], [0.5,0.0,1.0,1.0/3.0], [0.5,1.0/3.0,1.0,2.0/3.0], [0.5,2.0/3.0,1.0,1.0]],+ "middleMain" if count == 5 => vec![[0.0,0.0,1.0/3.0,0.5], [1.0/3.0,0.0,2.0/3.0,1.0], [2.0/3.0,0.0,1.0,0.5], [0.0,0.5,1.0/3.0,1.0], [2.0/3.0,0.5,1.0,1.0]],+ "twoOverThree" if count == 5 => lattice(count, 3, true, true),+ "mainAndGrid" if count >= 5 => {+ let mut tiles = vec![[0.0,0.0,0.5,1.0]];+ tiles.extend(lattice(count - 1, 2, true, false).into_iter().map(|t| [0.5+t[0]/2.0,t[1],0.5+t[2]/2.0,t[3]]));+ tiles+ }+ "mainOverGrid" if count >= 4 => {+ let mut tiles = vec![[0.0,0.0,1.0,0.5]];+ tiles.extend(lattice(count - 1, if count == 4 { 3 } else { (count - 1).div_ceil(2).clamp(2, 5) }, true, false)+ .into_iter().map(|t| [t[0],0.5+t[1]/2.0,t[2],0.5+t[3]/2.0]));+ tiles+ }+ _ => return None,+ })+}++pub fn label(id: &str) -> &str {+ match id {+ "columns" => "Columns", "rows" => "Rows", "cols3" => "3 columns", "cols4" => "4 columns", "cols5" => "5 columns",+ "twoOverOne" => "Main bottom", "oneOverTwo" | "mainOverGrid" => "Main top",+ "mainLeft" | "mainAndStack" | "mainAndGrid" => "Main left", "mainRight" => "Main right",+ "quad" => "Grid", "middleMain" => "Middle + sides", "twoOverThree" => "Two over three",+ "balanced2" => "2 columns", "balanced3" => "3 columns", "balanced4" => "4 columns", "balanced5" => "5 columns", _ => id,+ }+}++pub fn choices(count: usize) -> Vec<&'static str> {+ let candidates: &[&str] = match count {+ 0 | 1 => &[], 2 => &["columns", "rows"],+ 3 => &["cols3", "twoOverOne", "oneOverTwo", "mainLeft", "mainRight", "rows"],+ 4 => &["quad", "mainAndStack", "mainOverGrid", "cols4", "rows"],+ 5 => &["middleMain", "balanced3", "twoOverThree", "mainAndGrid", "mainOverGrid", "cols5"],+ 6..=9 => &["balanced2", "balanced3", "balanced4", "balanced5", "mainAndGrid", "mainOverGrid"],+ _ => &["balanced2", "balanced3", "balanced4", "balanced5"],+ };+ let mut shapes = Vec::new();+ candidates.iter().copied().filter(|id| {+ let Some(tiles) = preset_tiles(id, count) else { return false };+ if shapes.contains(&tiles) { false } else { shapes.push(tiles); true }+ }).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn fixtures() -> Vec<Value> {+ serde_json::from_str(include_str!("../../tests/fixtures/shared-pane-layouts.json")).unwrap()+ }++ #[test]+ fn desktop_catalogue_and_every_slot_render_identically_in_cells() {+ let fixtures = fixtures();+ for count in 2..=9 {+ let offered: Vec<_> = fixtures.iter().filter(|f| f["count"] == count && f["offered"] == true)+ .map(|f| f["preset"].as_str().unwrap()).collect();+ assert_eq!(choices(count as usize), offered);+ }+ for case in fixtures {+ let count = case["count"].as_u64().unwrap() as usize;+ let id = case["preset"].as_str().unwrap();+ if case["offered"] == true { assert_eq!(label(id), case["label"]); }+ let expected: Vec<Tile> = serde_json::from_value(case["tiles"].clone()).unwrap();+ assert_eq!(fill_row_ends(preset_tiles(id, count).unwrap()), expected, "{count} {id}");+ // Pane IDs deliberately differ from both spatial and tree traversal order.+ let ids: Vec<_> = (0..count).map(|i| (100 - i * 3) as u64).collect();+ for (w, h) in [(80, 24), (161, 51), (320, 90)] {+ let (root, _) = Geometry::from_tiles(expected.clone(), &ids, w, h, Status::Top)+ .unwrap_or_else(|| panic!("{count} {id}"));+ let actual = root.normalized_tiles();+ for (pane, tile) in ids.iter().zip(&expected) {+ let got = actual.iter().find(|t| t.0 == *pane).unwrap().1;+ for axis in 0..4 {+ let tolerance = 1.0 / if axis % 2 == 0 { w as f64 } else { h as f64 };+ assert!((tile[axis] - got[axis]).abs() <= tolerance, "{count} {id} pane {pane}, axis {axis}: {tile:?} != {got:?}");+ }+ }+ }+ }+ }++ #[test]+ fn repeated_resizing_does_not_accumulate_rounding_or_overwrite_source() {+ let tiles = vec![[0.0, 0.0, 0.23, 1.0], [0.23, 0.0, 1.0, 0.71], [0.23, 0.71, 1.0, 1.0]];+ let (mut root, mut geometry) = Geometry::from_tiles(tiles.clone(), &[9, 6, 3], 137, 43, Status::Top).unwrap();+ let original = root.to_tmux();+ for (w, h) in [(80, 20), (1, 1), (300, 100), (37, 9), (137, 43)] {+ assert!(geometry.fit(&mut root, w, h, Status::Top));+ }+ assert_eq!(root.to_tmux(), original);+ let mut doc = json!({});+ geometry.write(&mut doc);+ assert_eq!(saved_tiles(&doc, 3), Some(tiles));+ }++ #[test]+ fn fitting_never_overwrites_a_native_edit_waiting_for_publication() {+ let (mut root, mut geometry) = Geometry::from_tiles(preset_tiles("mainRight", 3).unwrap(), &[1, 2, 3], 120, 40, Status::Top).unwrap();+ root.swap(1, 2);+ let edited = root.to_tmux();+ assert!(!geometry.fit(&mut root, 180, 60, Status::Top));+ assert_eq!(root.to_tmux(), edited);+ }+}diff --git a/tui/src/input.rs b/tui/src/input.rsindex 5af4e4b83..d315f1439 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -12,7 +12,7 @@ use serde_json::json;use crate::app::{App, Placement};use crate::commands;use crate::keys;-use crate::layout::{Dir, Preset, Toward};+use crate::layout::{Dir, Toward};use crate::modal::{self, Filter, Modal, PickerKind, Prompt, PromptKind, What};use crate::pane::{encode_key, encode_mouse, Phase};use crate::picker::Picker;@@ -693,7 +693,7 @@ fn fill_rows(app: &App, kind: &PickerKind, picker: &mut Picker) {picker.status = format!("{up}/{} connected", app.fleet.visible_machines().count());picker.hints = vec![("enter", "its harnesses"), ("M-n", "new there"), ("C-t", "terminal there"), ("M-l", "link")];}- PickerKind::Layout => { picker.set_rows(modal::layout_rows()); picker.hints = vec![("enter", "apply")] }+ PickerKind::Layout => { picker.keep_order = true; picker.set_rows(modal::layout_rows(app.tab().panes().len())); picker.hints = vec![("enter", "apply")] }PickerKind::Theme => {picker.keep_order = true;picker.theme_in = None;@@ -915,9 +915,9 @@ pub fn run(app: &mut App, command: &str) {"close-pane" => { if let Some(f) = app.focused() { app.close_pane(f) } else if app.tabs.len() > 1 { let i = app.active; app.close_tab(i) } }"zoom" => {let tab = app.tab_mut();- if tab.panes().len() > 1 { tab.zoomed = !tab.zoomed; app.fit_panes(); let t = app.active; app.layout_changed(t) } else { app.fit_panes() }+ if tab.panes().len() > 1 { tab.zoomed = !tab.zoomed; app.fit_panes(); let t = app.active; app.view_layout_changed(t) } else { app.fit_panes() }}- "equalize" => { if let Some(f) = app.focused() { if let Some(root) = app.tab_mut().root.as_mut() { root.spread_out(f) } } app.fit_panes() }+ "equalize" => { if let Some(f) = app.focused() { if let Some(root) = app.tab_mut().root.as_mut() { root.spread_out(f) } } app.fit_panes(); app.layout_changed(app.active) }"pane-tab" => {let Some(f) = app.focused() else { return };if app.tab().panes().len() < 2 { return }@@ -2773,7 +2773,7 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {});}PickerKind::Layout => {- if let Some(index) = id.and_then(|i| i.parse::<usize>().ok()) { app.apply_preset(Preset::ALL[index].0) }+ if let Some(id) = id { app.apply_shared_preset(&id) }}PickerKind::Theme => {if choice == Choice::Enter {diff --git a/tui/src/layout.rs b/tui/src/layout.rsindex 36ae6f934..62bd16370 100644--- a/tui/src/layout.rs+++ b/tui/src/layout.rs@@ -10,6 +10,8 @@use ratatui::layout::Rect;+mod shared;+/// tmux's PANE_MINIMUM.pub const PANE_MINIMUM: u32 = 1;@@ -39,16 +41,6 @@ pub enum Preset {MainRow,}-impl Preset {- pub const ALL: [(Preset, &'static str, &'static str); 5] = [- (Preset::Grid, "Grid", "every pane the same size"),- (Preset::MainStack, "Main + stack", "one big on the left, the rest stacked"),- (Preset::MainRow, "Main + row", "one big on top, the rest in a row"),- (Preset::Columns, "Columns", "side by side"),- (Preset::Rows, "Rows", "one above the other"),- ];-}-/// tmux's named layouts, in its order (select-layout, next-layout, M-1 … M-7).#[derive(Clone, Copy, PartialEq, Eq, Debug)]pub enum Named { EvenHorizontal, EvenVertical, MainHorizontal, MainHorizontalMirrored, MainVertical, MainVerticalMirrored, Tiled }diff --git a/tui/src/layout/shared.rs b/tui/src/layout/shared.rsnew file mode 100644index 000000000..3afe9c001--- /dev/null+++ b/tui/src/layout/shared.rs@@ -0,0 +1,178 @@+//! The desk describes pane slots as fractions of one canvas, independently of pixels/cells.+//! Borders occupy the last cell before a cut: f maps to f * (extent + 1), as desktop's gap does.+use super::{Cell, Dir, Node, Status};++const EPS: f64 = 0.000001;+type Tile = [f64; 4];++enum Split {+ Pane(usize),+ Cut(Dir, f64, Box<Split>, Box<Split>),+}++fn partition(tiles: &[Tile], indices: &[usize], bounds: Tile) -> Option<Split> {+ if indices.len() == 1 {+ return tiles[indices[0]].iter().zip(bounds).all(|(a, b)| (a - b).abs() < EPS)+ .then_some(Split::Pane(indices[0]));+ }+ // A complete cut is required; this rejects holes, overlaps and malformed remote layouts.+ for (dir, axis) in [(Dir::Vertical, 1), (Dir::Horizontal, 0)] {+ for &i in indices {+ let at = tiles[i][axis + 2];+ if at <= bounds[axis] + EPS || at >= bounds[axis + 2] - EPS { continue }+ let mut before = Vec::new();+ let mut after = Vec::new();+ for &j in indices {+ if tiles[j][axis + 2] <= at + EPS { before.push(j) }+ else if tiles[j][axis] >= at - EPS { after.push(j) }+ }+ if before.is_empty() || after.is_empty() || before.len() + after.len() != indices.len() { continue }+ let mut left = bounds;+ let mut right = bounds;+ left[axis + 2] = at;+ right[axis] = at;+ let a = partition(tiles, &before, left)?;+ let b = partition(tiles, &after, right)?;+ return Some(Split::Cut(dir, (at - bounds[axis]) / (bounds[axis + 2] - bounds[axis]), Box::new(a), Box::new(b)));+ }+ }+ None+}++impl Split {+ fn minimum(&self, tiles: &[Tile], status: Status) -> (u32, u32) {+ match self {+ Split::Pane(i) => (1, 1 + u32::from(match status {+ Status::Top => tiles[*i][1] < EPS,+ Status::Bottom => tiles[*i][3] > 1.0 - EPS,+ Status::Off => false,+ })),+ Split::Cut(dir, _, a, b) => {+ let (aw, ah) = a.minimum(tiles, status);+ let (bw, bh) = b.minimum(tiles, status);+ if *dir == Dir::Horizontal { (aw + bw + 1, ah.max(bh)) }+ else { (aw.max(bw), ah + bh + 1) }+ }+ }+ }++ fn build(&self, tiles: &[Tile], ids: &[u64], status: Status, size: (u32, u32), parent: Option<usize>, cells: &mut Vec<Cell>) -> usize {+ let index = cells.len();+ let dir = match self { Split::Cut(dir, ..) => Some(*dir), _ => None };+ let pane = match self { Split::Pane(i) => ids[*i], _ => 0 };+ cells.push(Cell { dir, pane, sx: size.0, sy: size.1, xoff: 0, yoff: 0, parent, cells: Vec::new() });+ if let Split::Cut(dir, ratio, a, b) = self {+ let horizontal = *dir == Dir::Horizontal;+ let extent = if horizontal { size.0 } else { size.1 };+ let amin = a.minimum(tiles, status);+ let bmin = b.minimum(tiles, status);+ let low = if horizontal { amin.0 } else { amin.1 };+ let high = extent - 1 - if horizontal { bmin.0 } else { bmin.1 };+ let first = (((extent + 1) as f64 * ratio).round() as u32).saturating_sub(1).clamp(low, high);+ let second = extent - first - 1;+ let a_size = if horizontal { (first, size.1) } else { (size.0, first) };+ let b_size = if horizontal { (second, size.1) } else { (size.0, second) };+ let left = a.build(tiles, ids, status, a_size, Some(index), cells);+ let right = b.build(tiles, ids, status, b_size, Some(index), cells);+ cells[index].cells = vec![left, right];+ }+ index+ }+}++impl Node {+ /// Adjacent cuts on one axis are one tmux group. Keeping arbitrary binary+ /// parsing groups would make equalize/resize treat three columns as 1 + 2.+ fn flatten_shared(&mut self, i: usize) {+ let mut children = Vec::new();+ for k in self.c[i].cells.clone() {+ self.flatten_shared(k);+ if self.c[k].dir.is_some() && self.c[k].dir == self.c[i].dir {+ children.extend(self.c[k].cells.iter().copied());+ } else { children.push(k); }+ }+ for &k in &children { self.c[k].parent = Some(i); }+ self.c[i].cells = children;+ }++ /// Restore ordered, normalized slots without importing another client's numeric pane IDs.+ pub fn from_tiles(tiles: &[Tile], ids: &[u64], width: u16, height: u16, status: Status) -> Option<Self> {+ if tiles.len() != ids.len() || tiles.is_empty() || tiles.len() > 64 { return None }+ if tiles.iter().any(|t| t.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v))+ || t[2] - t[0] < EPS || t[3] - t[1] < EPS) { return None }+ let tree = partition(tiles, &(0..tiles.len()).collect::<Vec<_>>(), [0.0, 0.0, 1.0, 1.0])?;+ let minimum = tree.minimum(tiles, status);+ let mut cells = Vec::new();+ let root = tree.build(tiles, ids, status, ((width as u32).max(minimum.0), (height as u32).max(minimum.1)), None, &mut cells);+ let mut node = Node { c: cells, root, status };+ node.flatten_shared(root);+ node.fix_offsets();+ Some(node.compact())+ }++ /// Full tile bounds, before title rows/chrome are removed, in desktop's reading order.+ pub fn normalized_tiles(&self) -> Vec<(u64, Tile)> {+ let (w, h) = self.size();+ let mut cells: Vec<_> = self.walk(self.root).into_iter().map(|i| &self.c[i]).collect();+ cells.sort_by_key(|c| (c.yoff, c.xoff));+ cells.into_iter().map(|c| (c.pane, [+ c.xoff as f64 / (w as f64 + 1.0),+ c.yoff as f64 / (h as f64 + 1.0),+ (c.xoff + c.sx + 1) as f64 / (w as f64 + 1.0),+ (c.yoff + c.sy + 1) as f64 / (h as f64 + 1.0),+ ])).collect()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn normalized_slots_preserve_right_main_identity_and_proportions_at_every_size() {+ let tiles = [[0.0, 0.0, 0.3, 0.6], [0.3, 0.0, 1.0, 1.0], [0.0, 0.6, 0.3, 1.0]];+ for (w, h) in [(80, 24), (200, 60), (400, 100), (1, 1)] {+ let root = Node::from_tiles(&tiles, &[71, 4, 29], w, h, Status::Top).unwrap();+ let actual = root.normalized_tiles();+ assert_eq!(actual.iter().map(|t| t.0).collect::<Vec<_>>(), [71, 4, 29]);+ if w > 1 {+ for ((_, got), want) in actual.iter().zip(tiles) {+ for axis in 0..4 { assert!((got[axis] - want[axis]).abs() <= 1.0 / if axis % 2 == 0 { w as f64 } else { h as f64 }); }+ }+ }+ }+ }++ #[test]+ fn every_tmux_shape_can_be_exchanged_as_normalized_slots() {+ for count in 2..=9 {+ let ids: Vec<_> = (1..=count).collect();+ for shape in crate::layout::Named::ALL {+ let original = crate::layout::arrange(shape, &ids, 160, 60, Status::Top, ("80", "24"), ("0", "0")).unwrap();+ let shared = original.normalized_tiles();+ let order: Vec<_> = shared.iter().map(|r| r.0).collect();+ let tiles: Vec<_> = shared.iter().map(|r| r.1).collect();+ let restored = Node::from_tiles(&tiles, &order, 160, 60, Status::Top).unwrap();+ assert_eq!(restored.normalized_tiles(), shared, "{shape:?} / {count}");+ }+ }+ }++ #[test]+ fn malformed_geometry_is_rejected_without_losing_panes() {+ for tiles in [+ vec![[0.0, 0.0, 0.4, 1.0], [0.5, 0.0, 1.0, 1.0]],+ vec![[0.0, 0.0, 0.6, 1.0], [0.5, 0.0, 1.0, 1.0]],+ vec![[0.0, 0.0, f64::NAN, 1.0], [0.5, 0.0, 1.0, 1.0]],+ vec![[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]],+ ] { assert!(Node::from_tiles(&tiles, &[1, 2], 80, 24, Status::Top).is_none()); }+ }++ #[test]+ fn imported_columns_keep_tmux_equalize_grouping() {+ let mut root = Node::from_tiles(&[[0.0,0.0,0.2,1.0], [0.2,0.0,0.75,1.0], [0.75,0.0,1.0,1.0]], &[1,2,3], 122, 40, Status::Top).unwrap();+ root.spread_out(1);+ let widths: Vec<_> = root.normalized_tiles().iter().map(|(_, t)| t[2] - t[0]).collect();+ assert!(widths.iter().all(|w| (w - 1.0 / 3.0).abs() < 0.01), "{widths:?}");+ }+}diff --git a/tui/src/main.rs b/tui/src/main.rsindex 7b40c74c0..eb7e5dbb4 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -33,6 +33,7 @@ mod fzf;mod terminal_themes;mod input;mod layout;+mod desk_layout;mod local;mod modal;mod new_harness;diff --git a/tui/src/modal.rs b/tui/src/modal.rsindex fcebdb55a..0845076ed 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -9,7 +9,6 @@ use serde_json::Value;use crate::app::App;use crate::terminal_themes::TERMINAL_THEMES;use crate::fleet::{ago, Reach, State};-use crate::layout::Preset;use crate::picker::{Picker, Row};use crate::theme::{self, engine_label, engine_mark, fg, state_mark};@@ -669,8 +668,9 @@ pub fn machine_rows(app: &App) -> Vec<Row> {}).collect()}-pub fn layout_rows() -> Vec<Row> {- Preset::ALL.iter().enumerate().map(|(i, (_, name, detail))| Row::new(i.to_string(), *name).detail(vec![span(*detail, fg(theme::MUTED))])).collect()+pub fn layout_rows(count: usize) -> Vec<Row> {+ crate::desk_layout::choices(count).into_iter()+ .map(|id| Row::new(id, crate::desk_layout::label(id))).collect()}/// `hn theme`: every choice in the config file's `[look]` table, one per row, the current valuediff --git a/tui/tests/layout-sync.py b/tui/tests/layout-sync.pyindex 7dd180616..7725deada 100644--- a/tui/tests/layout-sync.py+++ b/tui/tests/layout-sync.py@@ -33,7 +33,7 @@ def scenario(mode, port, read_only=False):env.update(HOME=str(base), HN_TMPDIR=str(base), HN_SOCKET_NAME=prefix, PORT=str(port),ADAPTER_DATA_DIR=str(base / 'data'),TERM='xterm-256color', SHELL='/bin/sh', HARNESS_TUI_DESK='read' if read_only else 'sync',- HN_DESKTOP='off', HARNESS_TUI_NOTIFY='off', MOCK_DEMO='1', MOCK_LAYOUT='1', MOCK_DESK=mode)+ HN_DESKTOP='off', HARNESS_TUI_NOTIFY='off', MOCK_DEMO='1', MOCK_LAYOUT='1', MOCK_SHARED_LAYOUT='1', MOCK_DESK=mode)peer_env = dict(env, HOME=str(base / 'peer'), HN_SOCKET_NAME=prefix + '-peer')(base / 'peer').mkdir()config = base / 'tmux.conf'@@ -73,15 +73,16 @@ def scenario(mode, port, read_only=False):time.sleep(.05)raise AssertionError(label + '\n' + tmux('capture-pane', '-p', '-t', 'main', ok=False))- def start(peer=False):+ def start(peer=False, count=3):client_env = peer_env if peer else envcommand = shlex.join(['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',*[f'{k}={v}' for k, v in client_env.items()], str(binary), '-L',client_env['HN_SOCKET_NAME'], '--port', str(port), '-f', str(config)])tmux('-f', '/dev/null', 'new-session', '-d', '-s', 'peer' if peer else 'main','-x', '96' if peer else '120', '-y', '32' if peer else '36', command)- wait(lambda: 'api/handler.ts' in tmux('capture-pane', '-p', '-t', 'peer' if peer else 'main') or 'Fix flaky login test' in tmux('capture-pane', '-p', '-t', 'peer' if peer else 'main'), 'initial desk')- wait(lambda: hn('display-message', '-p', '#{window_panes}', peer=peer) == '3', 'three desk panes')+ if count == 3:+ wait(lambda: 'api/handler.ts' in tmux('capture-pane', '-p', '-t', 'peer' if peer else 'main') or 'Fix flaky login test' in tmux('capture-pane', '-p', '-t', 'peer' if peer else 'main'), 'initial desk')+ wait(lambda: hn('display-message', '-p', '#{window_panes}', peer=peer, ok=False) == str(count), f'{count} desk panes')def layout(peer=False):return hn('display-message', '-p', '#{window_layout}', peer=peer)@@ -331,6 +332,54 @@ def scenario(mode, port, read_only=False):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)++ if mode == 'normal' and not read_only:+ fixtures = json.loads((ROOT.parent / 'tests/fixtures/shared-pane-layouts.json').read_text())+ local = initial[0]['machineId']++ def exact_geometry(tiles, peer=False):+ native = layout(peer)+ w, h = map(int, re.match(r'[^,]+,(\d+)x(\d+)', native).groups())+ ids = {int(r.split('|')[0][1:]): r.split('|')[1] for r in hn('list-panes', '-F', '#{pane_id}|#{pane_title}', peer=peer).splitlines()}+ cells = re.findall(r'(\d+)x(\d+),(\d+),(\d+),(\d+)(?=[,}\]]|$)', native)+ if len(cells) != len(tiles):+ return False+ for sx, sy, x, y, pane in (map(int, cell) for cell in cells):+ index = int(ids[pane].rsplit(' ', 1)[1]) - 1+ got = [x / (w + 1), y / (h + 1), (x + sx + 1) / (w + 1), (y + sy + 1) / (h + 1)]+ if any(abs(a - b) > 1.01 / (w if axis % 2 == 0 else h) for axis, (a, b) in enumerate(zip(got, tiles[index]))):+ return False+ return True++ for count, preset in [(5, 'middleMain'), (6, 'mainAndGrid'), (9, 'balanced5')]:+ tiles = next(f['tiles'] for f in fixtures if f['count'] == count and f['preset'] == preset)+ wire = {'presets': {str(count): preset}, 'sizes': {f'{count}:manual': tiles}, 'tmux': 'stale-native-layout'}+ ops = [{'op': 'pane.remove', 'tabId': 'demo-1', **p} for p in api()['tabs'][0]['panes']]+ ops += [{'op': 'pane.add', 'tabId': 'demo-1', 'machineId': local, 'agentId': f'shared-layout-{i + 1}', 'index': i} for i in range(count)]+ ops.append({'op': 'tab.layout', 'id': 'demo-1', 'layout': wire})+ api('/api/desk/ops', {'ops': ops})+ wait(lambda: exact_geometry(tiles), f'{count} panes match desktop rectangles and identities')+ writes = len(api('/test/layout')['writes'])+ original = layout()+ for width, height in [(84, 30), (180, 60), (120, 36)]:+ tmux('resize-window', '-t', 'main', '-x', str(width), '-y', str(height))+ wait(lambda: exact_geometry(tiles), f'{count} pane ratios survive {width}x{height}')+ wait(lambda: layout() == original, 'returning to original dimensions restores exact cells')+ hn('resize-pane', '-Z')+ hn('resize-pane', '-Z')+ assert len(api('/test/layout')['writes']) == writes, 'viewport or zoom published a layout'+ assert api()['tabs'][0]['layout'] == wire, 'rendering overwrote normalized ratios'+ print(f'PASS normal: {count} panes use desktop slots at three viewport sizes, with no resize/zoom writes', flush=True)++ start(peer=True, count=9)+ wait(lambda: exact_geometry(tiles, peer=True), 'fresh smaller client receives all nine desktop slots')+ source = hn('list-panes', '-F', '#{pane_id}').splitlines()[0]+ hn('resize-pane', '-t', source, '-R', '4')+ wait(lambda: api()['tabs'][0]['layout']['sizes']['9:manual'] != tiles, 'TUI divider publishes normalized slots')+ changed = api()['tabs'][0]['layout']['sizes']['9:manual']+ wait(lambda: exact_geometry(changed, peer=True), 'TUI divider reaches peer at different dimensions')+ hn('kill-server', peer=True, ok=False)+ print('PASS normal: nine-pane divider edit reaches another client without preset approximation', flush=True)finally:if started:hn('kill-server', ok=False)diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjsindex 7728f9430..a1b91306c 100644--- a/tui/tests/mock-daemon.mjs+++ b/tui/tests/mock-daemon.mjs@@ -54,6 +54,9 @@ if (process.env.MOCK_PROJECT_SEARCH === '1') {`autonomous-harness-2026-${String(i).padStart(3, '0')}`, 'main'))}}+if (process.env.MOCK_SHARED_LAYOUT === '1') {+ for (let i = 1; i <= 9; i++) agents[LOCAL].push(agent(`shared-layout-${i}`, `Shared pane ${i}`, 'terminal'))+}// Opt-in viewer fixtures, so the normal terminal roster and its tests keep their identities.if (process.env.MOCK_VIEWER === '1') {