Skip to content

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.

feat(desk): a tab's layout — presets and dragged splits — is the same on every Mac

0xdiego2571e5d2a81e57
diff --git a/backend/src/lib/desk.ts b/backend/src/lib/desk.ts
index aa10d09d4..c859006e0 100644
--- a/backend/src/lib/desk.ts
+++ b/backend/src/lib/desk.ts
@@ -19,11 +19,24 @@ const agentId = z.string().min(1).max(160)
const name = z.string().trim().min(1).max(DESK_NAME_MAX)
export const deskPaneSchema = z.object({ machineId, agentId }).strict()
+/**
+ * How the tab's tiles are laid out — the same on every computer since 2026-09-22 (owner: "máy kia không
+ * có layout"). `presets` is pane-count → the named shape chosen; `sizes` is the window's arrangement
+ * keys → tiles as fractions of the canvas (`[left, top, right, bottom]`, 0..1), which is why they travel:
+ * a window of any size draws them. Focus, zoom and pins stay each window's own.
+ */
+const tile = z.tuple([z.number().min(0).max(1), z.number().min(0).max(1), z.number().min(0).max(1), z.number().min(0).max(1)])
+export const deskLayoutSchema = z.object({
+ presets: z.record(z.string().regex(/^[2-9]$/), z.string().min(1).max(32)).optional(),
+ sizes: z.record(z.string().min(1).max(80), z.array(tile).min(2).max(DESK_MAX_PANES)).optional(),
+}).strict()
+export type DeskLayout = z.infer<typeof deskLayoutSchema>
export const deskTabSchema = z.object({
id,
name,
nameIsCustom: z.boolean().optional(),
panes: z.array(deskPaneSchema).max(DESK_MAX_PANES),
+ layout: deskLayoutSchema.optional(),
}).strict()
export type DeskPane = z.infer<typeof deskPaneSchema>
@@ -38,6 +51,8 @@ export const deskOpSchema = z.discriminatedUnion('op', [
z.object({ op: z.literal('pane.add'), tabId: id, machineId, agentId, index: z.number().int().min(0).optional() }).strict(),
z.object({ op: z.literal('pane.remove'), tabId: id, machineId, agentId }).strict(),
z.object({ op: z.literal('pane.move'), tabId: id, machineId, agentId, index: z.number().int().min(0) }).strict(),
+ // The whole layout at once, replacing what was there: a drag on one computer is the layout everywhere.
+ z.object({ op: z.literal('tab.layout'), id, layout: deskLayoutSchema }).strict(),
// First sync from a computer that already had tabs of its own: every tab whose id the desk does
// not know is appended, as it was. The person closes the extras; nothing of theirs is dropped.
z.object({ op: z.literal('seed'), tabs: z.array(deskTabSchema).max(DESK_MAX_TABS) }).strict(),
@@ -63,6 +78,18 @@ export function parseTabs(raw: unknown): DeskTab[] {
return out
}
+/** At most 16 arrangements per tab — a window keeps 64 of its own, but the desk carries what matters. */
+const DESK_MAX_SIZES = 16
+function sizesCapped(layout: DeskLayout): DeskLayout {
+ const out: DeskLayout = {}
+ if (layout.presets && Object.keys(layout.presets).length) out.presets = layout.presets
+ if (layout.sizes) {
+ const entries = Object.entries(layout.sizes).slice(-DESK_MAX_SIZES)
+ if (entries.length) out.sizes = Object.fromEntries(entries)
+ }
+ return out
+}
+
const clampIndex = (index: number | undefined, length: number): number =>
index === undefined ? length : Math.max(0, Math.min(index, length))
@@ -136,6 +163,14 @@ export function applyDeskOp(tabs: DeskTab[], op: DeskOp): { tabs: DeskTab[]; cha
panes.splice(dest, 0, pane)
return { tabs: next, changed: dest !== j }
}
+ case 'tab.layout': {
+ const i = at(op.id)
+ if (i < 0) return { tabs: next, changed: false }
+ const layout = sizesCapped(op.layout)
+ if (JSON.stringify(next[i].layout ?? null) === JSON.stringify(layout)) return { tabs: next, changed: false }
+ next[i] = { ...next[i], layout }
+ return { tabs: next, changed: true }
+ }
case 'seed': {
let changed = false
for (const tab of op.tabs) {
diff --git a/backend/src/routes/desk.test.ts b/backend/src/routes/desk.test.ts
index 402f18d8a..99b277ecd 100644
--- a/backend/src/routes/desk.test.ts
+++ b/backend/src/routes/desk.test.ts
@@ -8,7 +8,7 @@ vi.mock('../lib/prisma.js', () => ({ prisma: mocks.prisma }))
vi.mock('../lib/bus.js', () => ({ publishDeskChanged: mocks.changed }))
vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: mocks.auth }))
import { deskRoutes } from './desk.js'
-import { applyDeskOp, applyDeskOps, parseTabs, DESK_MAX_TABS, type DeskTab } from '../lib/desk.js'
+import { applyDeskOp, applyDeskOps, deskTabSchema, parseTabs, DESK_MAX_TABS, type DeskLayout, type DeskTab } from '../lib/desk.js'
import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
import { errorHandler } from '../middlewares/errorHandler.js'
@@ -60,6 +60,19 @@ describe('desk ops — the merge rule', () => {
expect(replayed.tabs.map(t => t.id)).toEqual(['b'])
})
+ it('carries a tab\'s layout as one value: replaced whole, idempotent, dropped for a tab that is gone', () => {
+ const layout: DeskLayout = { presets: { '2': 'rows' }, sizes: { '2:manual': [[0, 0, 0.3, 1], [0.3, 0, 1, 1]] } }
+ let r = applyDeskOp([tab('a')], { op: 'tab.layout', id: 'a', layout })
+ expect(r.changed).toBe(true)
+ expect(r.tabs[0].layout).toEqual(layout)
+ expect(applyDeskOp(r.tabs, { op: 'tab.layout', id: 'a', layout }).changed).toBe(false)
+ r = applyDeskOp(r.tabs, { op: 'tab.layout', id: 'a', layout: { presets: { '2': 'columns' } } })
+ expect(r.tabs[0].layout).toEqual({ presets: { '2': 'columns' } }) // replaced, not merged
+ expect(applyDeskOp(r.tabs, { op: 'tab.layout', id: 'gone', layout }).changed).toBe(false)
+ expect(deskTabSchema.safeParse({ ...tab('a'), layout }).success).toBe(true)
+ expect(deskTabSchema.safeParse({ ...tab('a'), layout: { sizes: { k: [[0, 0, 2, 1], [0, 0, 1, 1]] } } }).success).toBe(false)
+ })
+
it('seeds a computer\'s own tabs once, by id, and never past the cap', () => {
const local = [tab('l1', [['m1', 'x']]), tab('l2')]
let r = applyDeskOp([tab('a')], { op: 'seed', tabs: local })
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 8c7789954..e10aca447 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -684,6 +684,8 @@ class AppNotifier extends ChangeNotifier {
Future<void> deskFetchForTest() => _deskFetch();
@visibleForTesting
Future<void> deskFlushForTest() => _deskFlush();
+ @visibleForTesting
+ void persistLayoutForTest() => _persistLayout();
String _activeSwarmId = 'swarm-1';
int _nextSwarmId = 2;
// No tab cap, as in Chrome: only the visible tab's panes are built, so a background tab costs its
@@ -3065,8 +3067,7 @@ class AppNotifier extends ChangeNotifier {
final updater = _updater;
final staged = await updater.downloadAndStage(info);
if (staged == null) {
- updateError =
- 'Could not download and verify Harness ${info.version}.';
+ updateError = 'Could not download and verify Harness ${info.version}.';
return false;
}
final applied = await updater.applyStaged(staged, selfPid: pid);
@@ -8624,9 +8625,52 @@ class AppNotifier extends ChangeNotifier {
if (pane.agentId != null)
DeskPaneRef(machineId: pane.machineId, agentId: pane.agentId!),
],
+ layout: _deskLayoutOf(swarm),
),
];
+ /// The tab's layout as the desk holds it: the chosen presets and the
+ /// arrangements the window keeps (`paneSizes`), tiles as fractions. The
+ /// desk carries at most 16 arrangements; the newest are the ones a hand
+ /// just made, so those are what travel.
+ static DeskLayout _deskLayoutOf(Swarm swarm) {
+ final sizes = swarm.paneSizes.entries.toList();
+ return DeskLayout(
+ presets: {for (final e in swarm.presets.entries) '${e.key}': e.value.id},
+ sizes: {
+ for (final e in sizes.skip((sizes.length - 16).clamp(0, sizes.length)))
+ e.key: e.value.toJson(),
+ },
+ );
+ }
+
+ /// 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.
+ static void _applyDeskLayout(Swarm swarm, DeskLayout? layout) {
+ swarm.presets.clear();
+ swarm.paneSizes.clear();
+ if (layout == null) return;
+ for (final e in layout.presets.entries) {
+ final count = int.tryParse(e.key);
+ final preset = PanePreset.byId(e.value);
+ if (count != null &&
+ count >= 2 &&
+ count <= maxPanes &&
+ preset != null &&
+ preset.supportsCount(count)) {
+ swarm.presets[count] = preset;
+ }
+ }
+ swarm.paneSizes.addAll(
+ PaneArrangement.readSaved({
+ for (final e in layout.sizes.entries) e.key: e.value,
+ }),
+ );
+ swarm.arranged = null;
+ swarm.arrangedKey = null;
+ }
+
/// First contact with the desk after sign-in. A daemon that predates the
/// desk, or a signed-out one, answers null and this window keeps its tabs to
/// itself. Otherwise the desk is read, this computer's own tabs from before
@@ -8700,10 +8744,13 @@ class AppNotifier extends ChangeNotifier {
'desk',
'joined at rev ${doc.revision} · ${doc.tabs.length} on the desk · ${unknown.length} of ours to seed',
);
- _deskApply(doc);
+ _deskApply(doc, joining: true);
await _deskFlush();
}
+ static String _layoutFingerprintOf(DeskLayout? layout) =>
+ layout == null || layout.isEmpty ? '' : layout.fingerprint;
+
static bool _sameKeys(List<String> a, List<String> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
@@ -8797,13 +8844,13 @@ class AppNotifier extends ChangeNotifier {
/// Reconcile `swarms` to [doc], with this window's unacknowledged ops laid
/// over it. Ignores a document older than one already applied.
- void _deskApply(DeskDoc doc) {
+ void _deskApply(DeskDoc doc, {bool joining = false}) {
if (doc.revision < _desk.revision) return;
_desk.revision = doc.revision;
final target = applyDeskOps(doc.tabs, _desk.pending);
final believed = _desk.synced;
_desk.synced = target;
- _deskReconcile(target, believed: believed);
+ _deskReconcile(target, believed: believed, joining: joining);
}
/// Make `swarms` say what [target] says, and no more: tabs the desk closed go
@@ -8821,6 +8868,7 @@ class AppNotifier extends ChangeNotifier {
void _deskReconcile(
List<DeskTab> target, {
List<DeskTab> believed = const [],
+ bool joining = false,
}) {
final targetById = {for (final t in target) t.id: t};
final believedById = {for (final t in believed) t.id: t};
@@ -8939,6 +8987,26 @@ class AppNotifier extends ChangeNotifier {
}
}
}
+ // The layout: the desk's, but — like the order — only where the desk's
+ // own layout moved since this window last agreed with it, so a drag in
+ // progress here is not undone by a document that merely arrived. A tab
+ // this window has never known takes the desk's layout as it is.
+ final knownLayout = believedById.containsKey(tab.id)
+ ? believedById[tab.id]!.layout
+ : null;
+ final layoutMoved =
+ !believedById.containsKey(tab.id) ||
+ _layoutFingerprintOf(knownLayout) != _layoutFingerprintOf(tab.layout);
+ // At the join a desk that holds no layout for a tab this window has one
+ // for learns this window's (the diff sends it up); it does not wipe it.
+ final deskHasOne = tab.layout != null && !tab.layout!.isEmpty;
+ if (layoutMoved &&
+ (deskHasOne || !joining) &&
+ _layoutFingerprintOf(tab.layout) !=
+ _layoutFingerprintOf(_deskLayoutOf(swarm))) {
+ _applyDeskLayout(swarm, tab.layout);
+ _paneLayoutRequest++;
+ }
if (!swarm.nameIsCustom &&
swarm.titleAgentId == null &&
swarm.panes.isNotEmpty) {
diff --git a/desktop/lib/state/desk_sync.dart b/desktop/lib/state/desk_sync.dart
index 2d2f58138..c33e8d494 100644
--- a/desktop/lib/state/desk_sync.dart
+++ b/desktop/lib/state/desk_sync.dart
@@ -43,27 +43,93 @@ class DeskPaneRef {
int get hashCode => Object.hash(machineId, agentId);
}
+/// How a tab's tiles are laid out, the same on every computer (owner,
+/// 2026-09-22: "máy kia không có layout"). `presets` is pane count → the named
+/// 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.
+class DeskLayout {
+ const DeskLayout({this.presets = const {}, this.sizes = const {}});
+ final Map<String, String> presets;
+ final Map<String, List<List<double>>> sizes;
+
+ bool get isEmpty => presets.isEmpty && sizes.isEmpty;
+
+ Map<String, dynamic> toJson() => {
+ if (presets.isNotEmpty) 'presets': Map<String, String>.from(presets),
+ if (sizes.isNotEmpty)
+ 'sizes': {
+ for (final e in sizes.entries)
+ e.key: [
+ for (final tile in e.value) [...tile],
+ ],
+ },
+ };
+
+ static DeskLayout? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final presets = <String, String>{};
+ if (raw['presets'] is Map) {
+ for (final e in (raw['presets'] as Map).entries) {
+ if (e.key is String && e.value is String) presets[e.key] = e.value;
+ }
+ }
+ final sizes = <String, List<List<double>>>{};
+ if (raw['sizes'] is Map) {
+ for (final e in (raw['sizes'] as Map).entries) {
+ if (e.key is! String || e.value is! List) continue;
+ final tiles = <List<double>>[];
+ for (final tile in e.value as List) {
+ if (tile is! List || tile.length != 4 || tile.any((v) => v is! num)) {
+ tiles.clear();
+ break;
+ }
+ tiles.add([for (final v in tile) (v as num).toDouble()]);
+ }
+ if (tiles.isNotEmpty) sizes[e.key] = tiles;
+ }
+ }
+ return DeskLayout(presets: presets, sizes: sizes);
+ }
+
+ /// The comparison the diff makes: the JSON, key order fixed.
+ String get fingerprint => _canonical(toJson());
+
+ static String _canonical(Object? value) {
+ if (value is Map) {
+ final keys = value.keys.map((k) => k.toString()).toList()..sort();
+ return '{${keys.map((k) => '$k:${_canonical(value[k])}').join(',')}}';
+ }
+ if (value is List) return '[${value.map(_canonical).join(',')}]';
+ return '$value';
+ }
+}
+
class DeskTab {
const DeskTab({
required this.id,
required this.name,
this.nameIsCustom = false,
this.panes = const [],
+ this.layout,
});
final String id;
final String name;
final bool nameIsCustom;
final List<DeskPaneRef> panes;
+ final DeskLayout? layout;
DeskTab copyWith({
String? name,
bool? nameIsCustom,
List<DeskPaneRef>? panes,
+ DeskLayout? layout,
}) => DeskTab(
id: id,
name: name ?? this.name,
nameIsCustom: nameIsCustom ?? this.nameIsCustom,
panes: panes ?? this.panes,
+ layout: layout ?? this.layout,
);
Map<String, dynamic> toJson() => {
@@ -71,6 +137,7 @@ class DeskTab {
'name': name,
if (nameIsCustom) 'nameIsCustom': true,
'panes': [for (final p in panes) p.toJson()],
+ if (layout != null && !layout!.isEmpty) 'layout': layout!.toJson(),
};
static DeskTab? fromJson(Object? raw) {
@@ -91,10 +158,14 @@ class DeskTab {
name: name,
nameIsCustom: raw['nameIsCustom'] == true,
panes: panes,
+ layout: DeskLayout.fromJson(raw['layout']),
);
}
}
+String _layoutFingerprint(DeskLayout? layout) =>
+ layout == null || layout.isEmpty ? '' : layout.fingerprint;
+
class DeskDoc {
const DeskDoc({required this.revision, required this.tabs});
final int revision;
@@ -160,6 +231,13 @@ List<Map<String, dynamic>> deskDiff(List<DeskTab> before, List<DeskTab> after) {
'index': j,
});
}
+ if (tab.layout != null && !tab.layout!.isEmpty) {
+ ops.add({
+ 'op': 'tab.layout',
+ 'id': tab.id,
+ 'layout': tab.layout!.toJson(),
+ });
+ }
}
for (final tab in after) {
final old = beforeById[tab.id];
@@ -172,6 +250,14 @@ List<Map<String, dynamic>> deskDiff(List<DeskTab> before, List<DeskTab> after) {
'nameIsCustom': true,
});
}
+ // The layout travels whole: one drag on this computer is the layout on the others.
+ if (_layoutFingerprint(tab.layout) != _layoutFingerprint(old.layout)) {
+ ops.add({
+ 'op': 'tab.layout',
+ 'id': tab.id,
+ 'layout': (tab.layout ?? const DeskLayout()).toJson(),
+ });
+ }
final oldKeys = old.panes.map((p) => p.key).toSet();
final newKeys = tab.panes.map((p) => p.key).toSet();
for (final p in old.panes) {
@@ -293,6 +379,12 @@ List<DeskTab> applyDeskOps(List<DeskTab> tabs, List<Map<String, dynamic>> ops) {
if (j < 0) break;
next[i].panes.removeAt(j);
next[i].panes.insert(clamp(op['index'], next[i].panes.length), pane);
+ case 'tab.layout':
+ final i = at(op['id'] as String);
+ if (i < 0) break;
+ next[i] = next[i].copyWith(
+ layout: DeskLayout.fromJson(op['layout']) ?? const DeskLayout(),
+ );
case 'seed':
for (final raw in (op['tabs'] as List? ?? const [])) {
final tab = DeskTab.fromJson(raw);
diff --git a/desktop/test/desk_sync_test.dart b/desktop/test/desk_sync_test.dart
index b725de807..5ab451f2b 100644
--- a/desktop/test/desk_sync_test.dart
+++ b/desktop/test/desk_sync_test.dart
@@ -9,9 +9,12 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/state/desk_sync.dart';
import 'package:harness/state/pane_arrangement.dart';
+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 'swarm_state_test.dart' show createApp;
+import 'swarm_state_test.dart' show MemoryStore, createApp;
DeskTab tab(
String id, {
@@ -373,11 +376,12 @@ void main() {
await Future<void>.delayed(Duration.zero);
api.batches.clear();
- // The 15 s poll, and a push about another tab: the same order for this one.
+ // The 15 s poll, and a push about another tab: the same order for this one
+ // (and, as the server would, the layout this window already sent up).
api.doc = DeskDoc(
revision: 5,
tabs: [
- tab('d1', name: 'One', custom: true, agents: ['a1', 'a2']),
+ api.doc!.tabs.firstWhere((t) => t.id == 'd1'),
tab('d2', name: 'Two', custom: true, agents: ['a3']),
],
);
@@ -431,11 +435,18 @@ void main() {
await Future<void>.delayed(Duration.zero);
api.batches.clear();
- // The other Mac dragged a3 to the front.
+ // The other Mac dragged a3 to the front (the layout as the server holds it rides along).
api.doc = DeskDoc(
revision: 7,
tabs: [
- tab('d1', name: 'One', custom: true, agents: ['a3', 'a1', 'a2']),
+ api.doc!.tabs
+ .firstWhere((t) => t.id == 'd1')
+ .copyWith(
+ panes: [
+ for (final a in ['a3', 'a1', 'a2'])
+ DeskPaneRef(machineId: 'm', agentId: a),
+ ],
+ ),
],
);
await app.handleEventForTest('m', {
@@ -494,6 +505,185 @@ void main() {
},
);
+ test('a restart keeps the window\'s layout: preset, sizes, pins, focus and zoom survive the join', () async {
+ // The desk holds membership, order and names; everything else is this
+ // window's and lives in its saved layout. Restoring that layout and then
+ // joining a desk that already has the tab must change none of it.
+ final id = newDeskId();
+ final storage = MemoryStore();
+ final store = PaneLayoutStore(storage: storage);
+ final sizes = PaneArrangement([
+ Rect.fromLTWH(0, 0, 0.3, 1),
+ Rect.fromLTWH(0.3, 0, 0.7, 1),
+ ]);
+ final saved = Swarm(id: id, name: 'Work', nameIsCustom: true)
+ ..panes.addAll([
+ TerminalPane(id: 1, machineId: 'm', agentId: 'a1'),
+ TerminalPane(id: 2, machineId: 'm', agentId: 'a2'),
+ ])
+ ..presets[2] = PanePreset.rows
+ ..savePaneSizes('2:manual', sizes)
+ ..focusedPaneId = 2
+ ..zoomedPaneId = 2;
+ saved.pinnedSlots[2] = 1;
+ await store.saveSwarms([saved], id);
+
+ final api = _DeskApi()
+ ..doc = DeskDoc(
+ revision: 20,
+ tabs: [
+ tab(id, name: 'Work', custom: true, agents: ['a1', 'a2']),
+ ],
+ );
+ final app = createApp(store: storage)..api = api;
+ addTearDown(app.dispose);
+ await app.restorePaneLayoutForTest();
+ final work = app.swarms.singleWhere((s) => s.id == id);
+ expect(work.presets[2], PanePreset.rows);
+ final focused = work.focusedPaneId, zoomed = work.zoomedPaneId;
+ expect(focused, isNotNull);
+ expect(zoomed, isNotNull);
+
+ await app.deskStartForTest();
+ await Future<void>.delayed(Duration.zero);
+
+ expect(app.swarms.map((s) => s.id), [id]);
+ expect(work.panes.map((p) => p.agentId), ['a1', 'a2']);
+ expect(
+ work.presets[2],
+ PanePreset.rows,
+ reason: 'the preset is the window\'s',
+ );
+ expect(work.paneSizes['2:manual']?.tiles, sizes.tiles);
+ expect(work.focusedPaneId, focused);
+ expect(work.zoomedPaneId, zoomed);
+ expect(work.pinnedSlots.values, [1]);
+ // The desk held no layout for the tab: it learns this window's, once.
+ final sent = api.batches.expand((b) => b).toList();
+ expect(sent.map((o) => o['op']), ['tab.layout']);
+ expect(api.doc!.tabs.single.layout?.presets, {'2': 'rows'});
+ });
+
+ test('a preset chosen or a split dragged here is the layout on the other Mac too', () async {
+ // The desk carries presets and arrangements since 2026-09-22 ("máy kia
+ // không có layout"). Focus, zoom and pins stay this window's.
+ final api = _DeskApi();
+ final app = createApp()..api = api;
+ addTearDown(app.dispose);
+ await app.deskStartForTest();
+ app.newSwarm(name: 'Work');
+ final work = app.activeSwarm;
+ await app.addAgentToSwarm('m', 'a1', swarmId: work.id);
+ await app.addAgentToSwarm('m', 'a2', swarmId: work.id);
+ await Future<void>.delayed(Duration.zero);
+ api.batches.clear();
+
+ app.setPreset(2, PanePreset.rows);
+ await Future<void>.delayed(Duration.zero);
+ final onDesk = () =>
+ api.doc!.tabs.singleWhere((t) => t.id == work.id).layout;
+ expect(onDesk()?.presets, {'2': 'rows'});
+ expect(
+ api.batches.expand((b) => b).where((o) => o['op'] == 'tab.layout'),
+ hasLength(1),
+ );
+
+ // A drag: the arrangement travels as fractions of the canvas.
+ final sizes = PaneArrangement([
+ Rect.fromLTWH(0, 0, 0.3, 1),
+ Rect.fromLTWH(0.3, 0, 0.7, 1),
+ ]);
+ work.savePaneSizes('2:manual', sizes);
+ app.persistLayoutForTest();
+ await Future<void>.delayed(Duration.zero);
+ expect(onDesk()?.sizes['2:manual'], sizes.toJson());
+
+ // The other Mac, joining: the same tab with the same preset and split.
+ final other = createApp()..api = api;
+ addTearDown(other.dispose);
+ await other.deskStartForTest();
+ final theirs = other.swarms.singleWhere((s) => s.id == work.id);
+ expect(theirs.presets[2], PanePreset.rows);
+ expect(theirs.paneSizes['2:manual']?.tiles, sizes.tiles);
+ expect(
+ theirs.focusedPaneId,
+ isNot(work.focusedPaneId),
+ reason: 'focus is each window\'s own',
+ );
+ });
+
+ test('a document that did not move the layout leaves a drag in progress alone; one that did applies it', () async {
+ final id = newDeskId();
+ final api = _DeskApi()
+ ..doc = DeskDoc(
+ revision: 1,
+ tabs: [
+ tab(id, name: 'Work', custom: true, agents: ['a1', 'a2']),
+ ],
+ );
+ final app = createApp()..api = api;
+ addTearDown(app.dispose);
+ await app.deskStartForTest();
+ app.selectSwarm(id);
+ final work = app.activeSwarm;
+ // This window drags while the backend is unreachable: the op waits, the
+ // arrangement stands.
+ api.failWith = StateError('offline');
+ final mine = PaneArrangement([
+ Rect.fromLTWH(0, 0, 0.6, 1),
+ Rect.fromLTWH(0.6, 0, 0.4, 1),
+ ]);
+ work.savePaneSizes('2:manual', mine);
+ app.persistLayoutForTest();
+ await Future<void>.delayed(Duration.zero);
+ api.failWith = null;
+ // A push about something else (a new tab) — the layout on the desk for this tab did not move.
+ api.doc = DeskDoc(
+ revision: 3,
+ tabs: [
+ tab(id, name: 'Work', custom: true, agents: ['a1', 'a2']),
+ tab('other', name: 'Other', custom: true),
+ ],
+ );
+ await app.handleEventForTest('m', {
+ 'type': 'desk_changed',
+ 'payload': {'revision': 3},
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(work.paneSizes['2:manual']?.tiles, mine.tiles);
+ await app.deskFlushForTest();
+ expect(api.doc!.tabs.first.layout?.sizes['2:manual'], mine.toJson());
+
+ // The other Mac chose a preset for this tab: it applies here.
+ api.doc = DeskDoc(
+ revision: 9,
+ tabs: [
+ DeskTab(
+ id: id,
+ name: 'Work',
+ nameIsCustom: true,
+ panes: [
+ const DeskPaneRef(machineId: 'm', agentId: 'a1'),
+ const DeskPaneRef(machineId: 'm', agentId: 'a2'),
+ ],
+ layout: const DeskLayout(presets: {'2': 'rows'}),
+ ),
+ tab('other', name: 'Other', custom: true),
+ ],
+ );
+ await app.handleEventForTest('m', {
+ 'type': 'desk_changed',
+ 'payload': {'revision': 9},
+ });
+ 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',
+ );
+ });
+
test('keeps its ops while the backend is unreachable and sends them once it is back', () async {
final api = _DeskApi();
final app = createApp()..api = api;