The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(desktop): preserve terminal ownership and sessions when moving panes (#291)
Dee534eec6798f6
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 83cd1071c..c026d3aa6 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1474,6 +1474,14 @@ class AppNotifier extends ChangeNotifier {_paneFocusByUser = !_navigatingFromDevice;}+ /// Native focus also changes during reparenting and dialog dismissal. The+ /// model already records a click/shortcut before asking the renderer to+ /// focus, so that echo must not turn a layout change into a terminal claim.+ void focusPaneFromRenderer(int paneId) {+ if (focusedPaneId == paneId) return;+ _fromDevice(() => focusPane(paneId));+ }+/// An explicit relayout reveals live output even in tiles whose rectangle/// does not change. This is view intent, so it is never persisted.int _paneLayoutRequest = 0;@@ -7725,7 +7733,7 @@ class AppNotifier extends ChangeNotifier {retryable: false,);}- final checking = attempt.awaitingConfirmation;+ var checking = attempt.awaitingConfirmation;if (!checking) {attempt._id = _newCreationId();attempt._startedRevision = machine._agentRevision;@@ -7747,6 +7755,22 @@ class AppNotifier extends ChangeNotifier {: 'agent_restart',payload: {'creationId': attempt._id, if (!checking) 'agentId': agentId},);+ if (checking &&+ resuming &&+ result['creationId'] == attempt._id &&+ result['state'] == 'missing' &&+ result['error'] == null &&+ _restartCurrent(attempt)) {+ // The original resume may never have reached the daemon. Checking a+ // missing receipt forever cannot recover it. Replay the SAME intent:+ // the daemon reserves it before launching, so a delayed original or+ // another retry cannot allocate a second terminal.+ checking = false;+ result = await _conn(machineId).request(+ 'agent_resume',+ payload: {'creationId': attempt._id, 'agentId': agentId},+ );+ }} catch (_) {return unknown;}@@ -9379,11 +9403,23 @@ class AppNotifier extends ChangeNotifier {////// A destination already showing this agent takes the move as a plain close/// here — one membership per tab, the rule [assignAgentToPane] keeps.- bool movePaneToSwarm(int paneId, String swarmId, {bool follow = true}) {- final source = activeSwarm;- final pane = source.panes.where((p) => p.id == paneId).firstOrNull;+ bool movePaneToSwarm(+ int paneId,+ String swarmId, {+ bool follow = true,+ String? sourceSwarmId,+ }) {+ final source = sourceSwarmId == null+ ? activeSwarm+ : swarms.where((swarm) => swarm.id == sourceSwarmId).firstOrNull;+ final pane = source?.panes.where((p) => p.id == paneId).firstOrNull;final target = swarms.where((swarm) => swarm.id == swarmId).firstOrNull;- if (pane == null || target == null || target.id == source.id) return false;+ if (source == null ||+ pane == null ||+ target == null ||+ target.id == source.id) {+ return false;+ }final twin = pane.agentId == null? null: target.panes@@ -9462,7 +9498,9 @@ class AppNotifier extends ChangeNotifier {if (follow) {_activeSwarmId = target.id;railFocused = false;- _noteNavigation();+ // Placement changes preserve terminal ownership. In particular, showing+ // the destination must not reclaim every terminal another window holds.+ _paneFocusByUser = false;_paneFocusRequest++;}selectedMachineId = focusedPane?.machineId;@@ -9821,6 +9859,16 @@ class AppNotifier extends ChangeNotifier {final believedById = {for (final t in believed) t.id: t};final before = _deskProjection();final released = <TerminalPane>[];+ final previousFocus = focusedPane;+ final previousTab = activeSwarmId;+ // Keep the objects from the whole document until the move is complete.+ // Iterating source before destination used to remove the only reference,+ // create a replacement tile, and close its still-live terminal below.+ final existingPanes = {+ for (final pane in allPanes)+ if (pane.agentId != null)+ '${pane.machineId}\u0000${pane.agentId}': pane,+ };// Tabs the desk no longer has.final kept = <Swarm>[];@@ -9870,18 +9918,14 @@ class AppNotifier extends ChangeNotifier {if (swarm.panes.any((p) => keyOf(p) == ref.key)) continue;// One TerminalPane per (machine, agent) across tabs — the same rule the// restore keeps — so a second tab showing an agent reuses its stream.- final pane =- allPanes- .where(- (p) =>- p.machineId == ref.machineId && p.agentId == ref.agentId,- )- .firstOrNull ??- TerminalPane(- id: _nextPaneId++,- machineId: ref.machineId,- agentId: ref.agentId,- );+ final pane = existingPanes.putIfAbsent(+ ref.key,+ () => TerminalPane(+ id: _nextPaneId++,+ machineId: ref.machineId,+ agentId: ref.agentId,+ ),+ );// After the agent pane the desk lists before it, whatever else (a// viewer, an empty tile) sits between; at the end when it is first.final after = i == 0@@ -9980,8 +10024,12 @@ class AppNotifier extends ChangeNotifier {if (!swarms.any((s) => s.id == _activeSwarmId)) {_activeSwarmId = swarms.first.id;selectedMachineId = focusedPane?.machineId;- // Another Mac closed the tab this one was on. The tab that comes forward- // instead is nobody's arrival here — see [paneFocusByUser].+ }+ if (activeSwarmId != previousTab ||+ !identical(focusedPane, previousFocus)) {+ // A peer moving the focused pane also focuses its neighbour. That is+ // remote navigation, just like a peer closing this window's active tab.+ // Treating it as a gesture here can start a terminal takeover loop._paneFocusByUser = false;}diff --git a/desktop/lib/widgets/move_pane_palette.dart b/desktop/lib/widgets/move_pane_palette.dartindex 757978f76..6a880396e 100644--- a/desktop/lib/widgets/move_pane_palette.dart+++ b/desktop/lib/widgets/move_pane_palette.dart@@ -16,10 +16,16 @@ import '../state/app_state.dart';/// among them: it holds a storefront, not harnesses, and a terminal dropped/// there would have nowhere to draw.Future<void> showMovePanePalette(BuildContext context, AppNotifier notifier) {- if (notifier.focusedPaneId == null) return Future<void>.value();+ final paneId = notifier.focusedPaneId;+ if (paneId == null) return Future<void>.value();+ final sourceId = notifier.activeSwarmId;return showAppDialog<void>(context: context,- builder: (context) => _MovePanePalette(notifier: notifier),+ builder: (context) => _MovePanePalette(+ notifier: notifier,+ sourceId: sourceId,+ paneId: paneId,+ ),);}@@ -33,9 +39,9 @@ class _Destination {final String detail;}-List<_Destination> _destinationsFor(AppNotifier notifier) => [+List<_Destination> _destinationsFor(AppNotifier notifier, String sourceId) => [for (final swarm in notifier.swarms)- if (swarm.id != notifier.activeSwarmId && !swarm.isStore)+ if (swarm.id != sourceId && !swarm.isStore)_Destination(id: swarm.id,label: swarm.name,@@ -51,9 +57,15 @@ List<_Destination> _destinationsFor(AppNotifier notifier) => [];class _MovePanePalette extends StatefulWidget {- const _MovePanePalette({required this.notifier});+ const _MovePanePalette({+ required this.notifier,+ required this.sourceId,+ required this.paneId,+ });final AppNotifier notifier;+ final String sourceId;+ final int paneId;@overrideState<_MovePanePalette> createState() => _MovePanePaletteState();@@ -82,27 +94,29 @@ class _MovePanePaletteState extends State<_MovePanePalette> {void _take(_Destination destination) {final notifier = widget.notifier;- final paneId = notifier.focusedPaneId;+ final paneId = widget.paneId;+ final sourceId = widget.sourceId;Navigator.of(context).pop();- if (paneId == null) return;+ if (!notifier.swarms.any(+ (swarm) =>+ swarm.id == sourceId && swarm.panes.any((pane) => pane.id == paneId),+ )) {+ return;+ }var targetId = destination.id;if (targetId == null) {- // The tab is made from here, then stepped back out of, because the move- // reads the pane from the tab in front: `newSwarm` selects what it makes.- final source = notifier.activeSwarmId;notifier.newSwarm(newTabPage: true);targetId = notifier.activeSwarmId;- if (targetId == source) return;- notifier.selectSwarm(source);+ if (targetId == sourceId) return;}- notifier.movePaneToSwarm(paneId, targetId);+ notifier.movePaneToSwarm(paneId, targetId, sourceSwarmId: sourceId);}KeyEventResult _onKey(FocusNode node, KeyEvent event) {if (event is! KeyDownEvent && event is! KeyRepeatEvent) {return KeyEventResult.ignored;}- final destinations = _destinationsFor(widget.notifier);+ final destinations = _destinationsFor(widget.notifier, widget.sourceId);final key = event.logicalKey;if (key == LogicalKeyboardKey.escape) {Navigator.of(context).pop();@@ -149,7 +163,7 @@ class _MovePanePaletteState extends State<_MovePanePalette> {@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);- final destinations = _destinationsFor(widget.notifier);+ final destinations = _destinationsFor(widget.notifier, widget.sourceId);final cursor = _cursor.clamp(0, destinations.length - 1);return Focus(focusNode: _keys,diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex a6af1500e..9a79d00c9 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -449,6 +449,7 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {upload: session.uploadProgress,focused: app.isPaneFocused(pane.id),focusRequest: app.isPaneFocused(pane.id) ? app.paneFocusRequest : 0,+ focusByUser: app.paneFocusByUser,single: app.panes.length == 1,pinned: app.isPanePinned(pane),zoomed: app.zoomedPaneId == pane.id,@@ -1540,7 +1541,7 @@ class _PaneContent extends StatelessWidget {notifier.toggleZoomPane();}: null,- onRendererFocus: () => notifier.focusPane(pane.id),+ onRendererFocus: () => notifier.focusPaneFromRenderer(pane.id),paneDrag: single? null: PaneDragHandle(diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 44030e930..1af32014b 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -753,7 +753,18 @@ class _TerminalPanelState extends State<TerminalPanel>/// there is the "called during build" error the crash log was full of./// Deferred one frame, the retake lands on a built tree.void _autoTakeControlAfterBuild() {- WidgetsBinding.instance.addPostFrameCallback((_) => _autoTakeControl());+ final session = widget.session;+ final request = widget.focusRequest;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted ||+ !widget.focused ||+ !widget.focusByUser ||+ widget.focusRequest != request ||+ !identical(widget.session, session)) {+ return;+ }+ _autoTakeControl();+ });}/// A keystroke was typed into a pane that cannot take it. Flash the bannerdiff --git a/desktop/test/agent_pause_state_test.dart b/desktop/test/agent_pause_state_test.dartindex 10e492752..e21d62c70 100644--- a/desktop/test/agent_pause_state_test.dart+++ b/desktop/test/agent_pause_state_test.dart@@ -67,6 +67,66 @@ void main() {expect(connection.checks, isEmpty);});+ test(+ 'a resume that never reached the daemon can retry the same receipt',+ () async {+ app.stateOf('m')!.agents = [+ Agent.fromJson((inventory()['agents'] as List).single),+ ];+ final first = app.resumeAgent('m', 'a0');+ final creationId = connection.requests.single['creationId'] as String;+ connection.restartReplies.single.completeError(+ const WsRequestTimeout('agent_resume'),+ );+ expect((await first).error, contains('Still waiting'));++ final retry = app.resumeAgent('m', 'a0');+ connection.checkReplies.single.complete({+ 'creationId': creationId,+ 'state': 'missing',+ });+ await Future<void>.delayed(Duration.zero);++ expect(connection.types, ['agent_resume', 'agent_resume']);+ expect(+ connection.requests.last,+ connection.requests.first,+ reason: 'replay the same durable intent so a delayed original cannot launch twice',+ );+ connection.restartReplies.last.complete(+ restartReceipt(creationId, sessionId: source.sessionId),+ );+ expect((await retry).error, isNull);+ expect(app.stateOf('m')!.agents.single.sessionId, source.sessionId);+ },+ );++ for (final state in ['pending', 'unconfirmed', 'wrong receipt']) {+ test(+ 'an uncertain resume ($state) does not issue another launch',+ () async {+ app.stateOf('m')!.agents = [+ Agent.fromJson((inventory()['agents'] as List).single),+ ];+ final first = app.resumeAgent('m', 'a0');+ final creationId = connection.requests.single['creationId'];+ connection.restartReplies.single.completeError(+ const WsRequestTimeout('agent_resume'),+ );+ await first;+ final retry = app.resumeAgent('m', 'a0');+ connection.checkReplies.single.complete({+ 'creationId': state == 'wrong receipt'+ ? 'another-intent'+ : creationId,+ 'state': state == 'wrong receipt' ? 'missing' : state,+ });+ expect((await retry).error, isNotNull);+ expect(connection.types, ['agent_resume']);+ },+ );+ }+test('a confirmed pause remains in inventory when its refresh fails',() async {diff --git a/desktop/test/desk_sync_test.dart b/desktop/test/desk_sync_test.dartindex 5ab451f2b..b5e88c9c1 100644--- a/desktop/test/desk_sync_test.dart+++ b/desktop/test/desk_sync_test.dart@@ -13,6 +13,7 @@ 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/terminal/terminal_session.dart';import 'swarm_state_test.dart' show MemoryStore, createApp;@@ -198,6 +199,105 @@ void main() {});group('the window and the desk', () {+ for (final destinationFirst in [false, true]) {+ for (final closeSource in [false, true]) {+ test(+ 'a remote pane move preserves its terminal (destination first: $destinationFirst, source closed: $closeSource)',+ () async {+ final api = _DeskApi();+ final app = createApp()..api = api;+ addTearDown(app.dispose);+ final sent = <String>[];+ final session =+ TerminalSession(+ machineId: 'm',+ agentId: 'a0',+ agentName: 'Agent 0',+ engineId: 'codex',+ send: (type, _) async {+ sent.add(type);+ return true;+ },+ sendBinary: (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 'existing-stream';+ session.terminal.write('output before the move');+ final moved = app.adoptSessionForTest(session);+ final source = app.activeSwarm;+ app.newSwarm(name: 'Destination');+ final destination = app.activeSwarm;+ app.selectSwarm(source.id);+ await app.deskStartForTest();+ final tabs = [+ if (!closeSource) tab(source.id),+ tab(+ destination.id,+ name: 'Destination',+ custom: true,+ agents: ['a0'],+ ),+ ];+ api.doc = DeskDoc(+ revision: api.doc!.revision + 1,+ tabs: destinationFirst ? tabs.reversed.toList() : tabs,+ );++ await app.deskFetchForTest();++ expect(destination.panes.single, same(moved));+ expect(moved.session, same(session));+ expect(session.streamId, 'existing-stream');+ expect(+ session.terminal.buffer.getText(),+ contains('output before the move'),+ );+ expect(+ sent.where(+ (type) => type == 'terminal_close' || type == 'terminal_open',+ ),+ isEmpty,+ );+ },+ );+ }+ }++ test(+ 'a remote move changing the focused pane does not claim terminal control',+ () async {+ final api = _DeskApi();+ final app = createApp()..api = api;+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ await app.addAgentToSwarm('m', 'a1');+ final source = app.activeSwarm;+ app.newSwarm(name: 'Destination');+ final destination = app.activeSwarm;+ app.selectSwarm(source.id);+ app.focusPane(source.panes.first.id);+ await app.deskStartForTest();+ expect(app.paneFocusByUser, isTrue);+ api.doc = DeskDoc(+ revision: api.doc!.revision + 1,+ tabs: [+ tab(source.id, agents: ['a1']),+ tab(+ destination.id,+ name: 'Destination',+ custom: true,+ agents: ['a0'],+ ),+ ],+ );++ await app.deskFetchForTest();++ expect(app.focusedPane?.agentId, 'a1');+ expect(app.paneFocusByUser, isFalse);+ },+ );+test('joins the desk: its own tabs get desk ids and are seeded, the desk\'s tabs appear as intent', () async {final api = _DeskApi()..doc = DeskDoc(diff --git a/desktop/test/move_pane_palette_test.dart b/desktop/test/move_pane_palette_test.dartindex 92e163f38..721e2c70b 100644--- a/desktop/test/move_pane_palette_test.dart+++ b/desktop/test/move_pane_palette_test.dart@@ -77,7 +77,10 @@ void main() {});testWidgets('a digit takes the row it numbers', (tester) async {- final (app, source) = await _open(tester, others: const ['Second', 'Third']);+ final (app, source) = await _open(+ tester,+ others: const ['Second', 'Third'],+ );await tester.sendKeyEvent(LogicalKeyboardKey.digit2);await tester.pumpAndSettle();@@ -87,6 +90,33 @@ void main() {expect(_agentsOf(app, source), ['a1']);});+ testWidgets('the palette moves the pane it opened for after focus changes', (+ tester,+ ) async {+ final (app, source) = await _open(tester);+ app.focusPane(1);+ await tester.tap(find.text('Second'));+ await tester.pumpAndSettle();++ expect(_agentsOf(app, source), ['a1']);+ expect(_agentsOf(app, app.activeSwarmId), ['a0']);+ });++ testWidgets(+ 'changing tabs keeps the palette source and destinations stable',+ (tester) async {+ final (app, source) = await _open(tester);+ final destination = app.swarms.firstWhere((s) => s.name == 'Second').id;+ app.selectSwarm(destination);+ await tester.sendKeyEvent(LogicalKeyboardKey.digit1);+ await tester.pumpAndSettle();++ expect(_agentsOf(app, source), ['a1']);+ expect(_agentsOf(app, destination), ['a0']);+ expect(app.activeSwarmId, destination);+ },+ );+testWidgets('the arrows walk the list and Enter takes it', (tester) async {final (app, _) = await _open(tester, others: const ['Second', 'Third']);@@ -98,6 +128,22 @@ void main() {expect(_agentsOf(app, third), ['a0']);});+ testWidgets(+ 'a pane removed while the palette is open does not move its neighbour',+ (tester) async {+ final (app, source) = await _open(tester);+ await app.closePane(0);+ await tester.tap(find.text('Second'));+ await tester.pumpAndSettle();+ expect(app.activeSwarmId, source);+ expect(_agentsOf(app, source), ['a1']);+ expect(+ _agentsOf(app, app.swarms.firstWhere((s) => s.name == 'Second').id),+ isEmpty,+ );+ },+ );+testWidgets('the last row opens a tab of its own', (tester) async {final (app, source) = await _open(tester);final before = app.swarms.length;diff --git a/desktop/test/pane_move_terminal_test.dart b/desktop/test/pane_move_terminal_test.dartnew file mode 100644index 000000000..f6e4fe577--- /dev/null+++ b/desktop/test/pane_move_terminal_test.dart@@ -0,0 +1,133 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/widgets/terminal_panel.dart';++import 'swarm_interactions_test.dart' show chord;+import 'swarm_screen_test.dart' show mount;+import 'swarm_state_test.dart' show createApp;++void main() {+ testWidgets('renderer focus changes focus without claiming terminals', (+ tester,+ ) async {+ final app = createApp();+ final sent = <String>[];+ final sessions = [+ for (var i = 0; i < 2; i++)+ TerminalSession(+ machineId: 'm',+ agentId: 'a$i',+ agentName: 'Agent $i',+ engineId: 'codex',+ send: (type, _) async {+ sent.add(type);+ return true;+ },+ sendBinary: (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 'stream-$i',+ ];+ final first = app.adoptSessionForTest(sessions.first);+ final second = app.adoptSessionForTest(sessions.last);+ app.focusPane(first.id);+ app.stateOf('m')!+ ..nodeOnline = true+ ..terminalCapabilityAvailable = true;+ try {+ await mount(tester, app);+ sessions.last.status = TerminalSessionStatus.takenOver;+ sent.clear();+ tester+ .widget<TerminalPanel>(+ find.byWidgetPredicate(+ (w) => w is TerminalPanel && w.session == sessions.last,+ ),+ )+ .onRendererFocus!();+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 50));++ expect(app.focusedPane, same(second));+ expect(app.paneFocusByUser, isFalse);+ expect(sessions.last.status, TerminalSessionStatus.takenOver);+ expect(sent.where((type) => type == 'terminal_open'), isEmpty);+ expect(tester.takeException(), isNull);+ } finally {+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ }+ });++ testWidgets(+ 'Cmd-Shift-M keeps the stream and does not reclaim destination terminals',+ (tester) async {+ final app = createApp();+ final sent = <String>[];+ TerminalSession session(String id) =>+ TerminalSession(+ machineId: 'm',+ agentId: id,+ agentName: id,+ engineId: 'codex',+ send: (type, _) async {+ sent.add('$id:$type');+ return true;+ },+ sendBinary: (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 'stream-$id';+ final moving = session('a0');+ moving.terminal.write('preserve this output');+ final pane = app.adoptSessionForTest(moving);+ final source = app.activeSwarm;+ app.newSwarm(name: 'Destination');+ final destination = app.activeSwarm;+ final other = session('a1')..status = TerminalSessionStatus.takenOver;+ app.adoptSessionForTest(other);+ app.selectSwarm(source.id);+ app.stateOf('m')!+ ..nodeOnline = true+ ..terminalCapabilityAvailable = true;+ try {+ await mount(tester, app);+ final panel = find.byWidgetPredicate(+ (w) => w is TerminalPanel && w.session == moving,+ );+ final before = tester.state(panel);+ sent.clear();++ await chord(tester, LogicalKeyboardKey.keyM, shift: true);+ await tester.pump(const Duration(milliseconds: 300));+ await tester.tap(find.text('Destination').last);+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 300));++ expect(app.activeSwarm, same(destination));+ expect(destination.panes, contains(same(pane)));+ expect(pane.session, same(moving));+ expect(tester.state(panel), same(before));+ expect(+ moving.terminal.buffer.getText(),+ contains('preserve this output'),+ );+ expect(+ sent.where(+ (type) =>+ type.endsWith('terminal_open') ||+ type.endsWith('terminal_close'),+ ),+ isEmpty,+ );+ expect(other.status, TerminalSessionStatus.takenOver);+ expect(tester.takeException(), isNull);+ } finally {+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ }+ },+ );+}diff --git a/desktop/tool/pane_move_review.dart b/desktop/tool/pane_move_review.dartnew file mode 100644index 000000000..7a1945653--- /dev/null+++ b/desktop/tool/pane_move_review.dart@@ -0,0 +1,163 @@+// Interactive native regression fixture. Launch with FLUTTER_TEST=1:+// flutter run -d macos -t tool/pane_move_review.dart+// Move Alpha/Beta with Cmd-Shift-M; Focus contains a terminal owned elsewhere.+// Input echoes locally. No daemon, agent process, or persisted layout is used.+// PANE_MOVE_REVIEW_STATE optionally names a JSON evidence file.+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/test_run.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/ws/local_cli_discovery.dart';+import 'package:window_manager/window_manager.dart';++Future<void> main() async {+ if (!kUnderTest) throw StateError('Requires FLUTTER_TEST=1');+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ WidgetsFlutterBinding.ensureInitialized();+ await windowManager.ensureInitialized();+ await const MethodChannel('harness/swarm_tabs').invokeMethod('configure', {+ 'palette': grid.AppTheme.palette.value.nativeColors,+ });+ await windowManager.setSize(const Size(1200, 800));+ await windowManager.setTitle('Pane move regression review');++ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ )..hasNavigationRail = false;+ const machine = Machine(+ machineId: 'review',+ name: 'Isolated review',+ authMode: MachineAuthMode.remote,+ );+ const names = ['Alpha', 'Beta', 'Remote-owned'];+ app.machines = [machine];+ app.machineStates[machine.machineId] = MachineState(machine)+ ..nodeOnline = true+ ..terminalCapabilityAvailable = true+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..localEndpoint = LocalCliEndpoint(+ computerId: 'pane-move-review',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ )+ ..agents = [+ for (final name in names)+ Agent(id: name, name: name, engine: 'codex', terminalAvailable: true),+ ];+ final controls = <String>[];+ final inputs = <String>[];+ final keys = <Map<String, Object>>[];+ HardwareKeyboard.instance.addHandler((event) {+ keys.add({+ 'key': event.logicalKey.keyLabel,+ 'type': event.runtimeType.toString(),+ 'meta': HardwareKeyboard.instance.isMetaPressed,+ 'shift': HardwareKeyboard.instance.isShiftPressed,+ });+ return false;+ });+ final sessions = <String, TerminalSession>{};+ for (final name in names) {+ late final TerminalSession session;+ session =+ TerminalSession(+ machineId: machine.machineId,+ agentId: name,+ agentName: name,+ engineId: 'codex',+ send: (type, _) async {+ if (type == 'terminal_open' || type == 'terminal_close') {+ controls.add('$name:$type');+ }+ return true;+ },+ sendBinary: (frame) async {+ if (frame.kind == TerminalBinaryKind.input) {+ final text = utf8.decode(frame.bytes, allowMalformed: true);+ inputs.add('$name:$text');+ session.terminal.write(text);+ }+ return true;+ },+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 'review-$name';+ session.terminal.write(+ '$name — original session\r\n'+ 'Preserve this scrollback and connection across every move.\r\n'+ 'Cmd-Shift-M moves this pane; typed input echoes here.\r\n\r\n> ',+ );+ sessions[name] = session;+ if (name == names.last) app.newSwarm(name: 'Focus');+ // This entrypoint is guarded and never runs against real sessions.+ // ignore: invalid_use_of_visible_for_testing_member+ app.adoptSessionForTest(session);+ }+ final source = app.swarms.first;+ app.renameSwarm(source.id, 'Source');+ app.selectSwarm(source.id);+ app.focusPane(source.panes.first.id);+ sessions[names.last]!.status = TerminalSessionStatus.takenOver;+ final originals = {for (final pane in app.allPanes) pane.agentId: pane};+ final output = Platform.environment['PANE_MOVE_REVIEW_STATE'];+ void record() {+ if (output == null) return;+ File(output).writeAsStringSync(+ jsonEncode({+ 'activeTab': app.activeSwarm.name,+ 'focusedAgent': app.focusedPane?.agentId,+ 'focusByUser': app.paneFocusByUser,+ 'tabs': [+ for (final tab in app.swarms)+ {+ 'name': tab.name,+ 'agents': tab.panes.map((p) => p.agentId).toList(),+ },+ ],+ 'panes': [+ for (final pane in app.allPanes)+ {+ 'agent': pane.agentId,+ 'samePane': identical(pane, originals[pane.agentId]),+ 'sameSession': identical(pane.session, sessions[pane.agentId]),+ 'stream': pane.session?.streamId,+ 'status': pane.session?.status.name,+ 'hasOriginalOutput': pane.session?.terminal.buffer+ .getText()+ .contains('${pane.agentId} — original session'),+ },+ ],+ 'controls': controls,+ 'inputs': inputs,+ 'keys': keys,+ }),+ );+ }++ app.addListener(record);+ Timer.periodic(const Duration(milliseconds: 500), (_) => record());+ runApp(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: SwarmScreen(notifier: app, nativeTabs: true),+ ),+ );+ await windowManager.show();+ await windowManager.focus();+}