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: automatically retake taken-over terminal panes on user app interaction

0xken15af717ea32f98
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 900aad6ec..b30e97313 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -9366,6 +9366,30 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// A person acted on this app — clicked a tile, brought the window forward
+ /// — so every stream another client took from it comes back, not only the
+ /// tile they touched: being at this app is a fact about the app, not about
+ /// one pane. Every tab, since a tile parked behind another tab is this
+ /// app's too. Only ever from a user gesture — see
+ /// `_TerminalPanelState._autoTakeControl` for why a session or focus
+ /// callback must never call this.
+ ///
+ /// Reopens in place, as `selectAgent` does for a dead pane; `reopen` itself
+ /// skips a pane already `opening`. A pane the daemon would refuse
+ /// (`_canAttachPane`: machine offline, agent gone) keeps its band. Focus is
+ /// not moved — the tile the person is on stays the one they are on.
+ Future<void> retakeTakenOverPanes() async {
+ final reopening = <Future<void>>[];
+ for (final pane in allPanes) {
+ final session = pane.session;
+ if (session == null || session.readOnly) continue;
+ if (session.status != TerminalSessionStatus.takenOver) continue;
+ if (!_canAttachPane(pane)) continue;
+ reopening.add(session.reopen());
+ }
+ await Future.wait(reopening);
+ }
+
bool _canAttachPane(TerminalPane pane) {
if (_disposed || !allPanes.contains(pane)) return false;
final machine = machineStates[pane.machineId];
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 83dd4d855..0d086d49b 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -214,6 +214,7 @@ class _TerminalPanelState extends State<TerminalPanel>
_focusNode.addListener(_handleFocusChange);
_composerFocus.addListener(_handleComposerFocusChange);
WidgetsBinding.instance.addObserver(this);
+ _lastLifecycle = WidgetsBinding.instance.lifecycleState;
widget.session.attachViewport(this);
widget.session.addListener(_onSessionChanged);
terminalFontStore.addListener(_onFontChanged);
@@ -252,8 +253,24 @@ class _TerminalPanelState extends State<TerminalPanel>
}
@override
- void didChangeAppLifecycleState(AppLifecycleState state) =>
- _syncCursorBlink();
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ _syncCursorBlink();
+ // The window came back to the front (⌘-Tab, a click on it): that is a
+ // person returning, and the tile they left focused takes its stream back.
+ // `inactive → resumed` only — the first `resumed` of a launch is nobody
+ // coming back, and a restored pane is not taken over at that point anyway.
+ final returned =
+ state == AppLifecycleState.resumed &&
+ _lastLifecycle != null &&
+ _lastLifecycle != AppLifecycleState.resumed;
+ _lastLifecycle = state;
+ if (returned && widget.focused) _autoTakeControl();
+ }
+
+ /// Seeded from the binding at mount, so a tile opened while the window was
+ /// in the background still sees the `inactive → resumed` that brings it
+ /// forward, rather than mistaking it for the launch's first `resumed`.
+ AppLifecycleState? _lastLifecycle;
@override
void didUpdateWidget(TerminalPanel oldWidget) {
@@ -298,6 +315,11 @@ class _TerminalPanelState extends State<TerminalPanel>
(!oldWidget.visible || oldWidget.paneLocation != widget.paneLocation)) {
_afterTerminalMounted();
}
+ // Shown again (a tab switched to, a zoom undone) while it is the tile the
+ // person left focused: they are back on it.
+ if (widget.visible && !oldWidget.visible && widget.focused) {
+ _autoTakeControl();
+ }
if (oldWidget.viewportSize != widget.viewportSize ||
oldWidget.layoutRequest != widget.layoutRequest) {
// Geometry can change while a resize handle or another control owns
@@ -307,6 +329,8 @@ class _TerminalPanelState extends State<TerminalPanel>
if (widget.focused &&
(!oldWidget.focused || oldWidget.focusRequest != widget.focusRequest)) {
_claimFocusAfterFrame();
+ // ⌘1–9, ⌘], an attention jump, a click: the person chose this tile.
+ _autoTakeControl();
}
// Showing or hiding the box changes how many rows the terminal has. Re-measure so the remote
// grid is resized to what is actually on screen.
@@ -391,6 +415,14 @@ class _TerminalPanelState extends State<TerminalPanel>
_keyboardIsOursOrIdle) {
_claimFocusAfterFrame();
}
+ // Retaken from outside this tile (another tile's gesture, through
+ // `retakeTakenOverPanes`): keep the band up through the handshake exactly
+ // as this tile's own ⏎ would, rather than dropping it a beat early.
+ if (_wasBlocked &&
+ !_retakingControl &&
+ widget.session.status == TerminalSessionStatus.opening) {
+ setState(() => _retakingControl = true);
+ }
_wasBlocked = _inputBlocked;
// A pane can open BEFORE its screen exists: over the relay it mounts empty
// and the retained scrollback is replayed a moment later, so the jump in
@@ -628,11 +660,16 @@ class _TerminalPanelState extends State<TerminalPanel>
/// Retakes the stream, the same path as the header chip: `selectAgent` on a
/// dead pane is `reopen()`, and a repeat while it is already `opening` only
/// re-focuses the tile, so a held ⏎ sends one `terminal_open`.
+ ///
+ /// Every caller is a person acting on this app (⏎, the band's button, the
+ /// header chip, [_autoTakeControl]), so every other tile the same client
+ /// took comes back with this one — one gesture, the whole app.
Future<void> _takeControl() async {
final session = widget.session;
if (_inputBlocked && !_retakingControl) {
setState(() => _retakingControl = true);
}
+ unawaited(widget.notifier.retakeTakenOverPanes());
await widget.notifier.selectAgent(session.machineId, session.agentId);
// `selectAgent` declines quietly when the pane cannot be attached (machine
// gone offline meanwhile, agent withdrawn). No status change means no
@@ -646,6 +683,28 @@ class _TerminalPanelState extends State<TerminalPanel>
}
}
+ /// A person came back to this app, at this pane. Every stream another
+ /// client took from the app comes back — this tile through its own path
+ /// (which keeps its band up as "Taking control…"), the rest through
+ /// `retakeTakenOverPanes` — whether or not THIS tile was one of them: a
+ /// click into a pane that is working fine is still the person being here.
+ /// The band stays for what this cannot cover (an attach the daemon declines).
+ ///
+ /// ⚠️ Only ever from a USER gesture — a click, a key that focused the tile, a
+ /// tab switched to, the window brought to the front — never from a session
+ /// or focus-node callback. Those fire on BOTH ends of a takeover: this app's
+ /// pane pulls the keyboard into its terminal the moment it loses the stream
+ /// (`_onSessionChanged`), and a retake on that would have two apps trading
+ /// the one stream forever.
+ void _autoTakeControl() {
+ if (!mounted || !widget.visible) return;
+ if (_inputBlocked) {
+ unawaited(_takeControl());
+ } else {
+ unawaited(widget.notifier.retakeTakenOverPanes());
+ }
+ }
+
/// A keystroke was typed into a pane that cannot take it. Flash the banner
/// and say so for a moment, rather than letting the key vanish in silence.
void _nudgeControlBanner() {
@@ -1483,115 +1542,124 @@ class _TerminalPanelState extends State<TerminalPanel>
// [PhoneHeader], and keeping this one would stack two.
if (widget.showHeader) Divider(height: 1, color: AppColors.border),
Expanded(
- child: Stack(
- children: [
- Positioned.fill(
- child: MouseRegion(
- onEnter: (event) => _hoverLink(event.position),
- onHover: (event) => _hoverLink(event.position),
- onExit: (_) => _hoverLink(null),
- child: Tooltip(
- message: _hoveredLink == null
- ? ''
- : '${defaultTargetPlatform == TargetPlatform.macOS ? '⌘' : 'Ctrl'}-click to open\n$_hoveredLink',
- child: TerminalView(
- session.terminal,
- key: _terminalViewKey,
- controller: _controller,
- autoResize: widget.visible && !session.readOnly,
- resizeBuffer: false,
- renderingEnabled: widget.visible,
- outputRepaintInterval: widget.outputRepaintInterval,
- scrollController: _scrollController,
- focusNode: _focusNode,
- autofocus: widget.focused && !showComposer,
- readOnly: widget.readOnly || !session.acceptsInput,
- theme: terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
+ // Any press into the pane's body — the terminal, the band, its
+ // scrollbar; not the header, which is chrome — is the person
+ // coming back to it, and takes the stream back when it was
+ // taken. Translucent: the press still reaches what it landed on.
+ child: Listener(
+ behavior: HitTestBehavior.translucent,
+ onPointerDown: (_) => _autoTakeControl(),
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: MouseRegion(
+ onEnter: (event) => _hoverLink(event.position),
+ onHover: (event) => _hoverLink(event.position),
+ onExit: (_) => _hoverLink(null),
+ child: Tooltip(
+ message: _hoveredLink == null
+ ? ''
+ : '${defaultTargetPlatform == TargetPlatform.macOS ? '⌘' : 'Ctrl'}-click to open\n$_hoveredLink',
+ child: TerminalView(
+ session.terminal,
+ key: _terminalViewKey,
+ controller: _controller,
+ autoResize: widget.visible && !session.readOnly,
+ resizeBuffer: false,
+ renderingEnabled: widget.visible,
+ outputRepaintInterval: widget.outputRepaintInterval,
+ scrollController: _scrollController,
+ focusNode: _focusNode,
+ autofocus: widget.focused && !showComposer,
+ readOnly: widget.readOnly || !session.acceptsInput,
+ theme: terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ ),
+ padding: const EdgeInsets.all(10),
+ textStyle: terminalFontStore.value,
+ // The chosen point size already sizes each terminal cell.
+ // Applying the OS text scale again would change rows/cols
+ // and resize the remote terminal unexpectedly.
+ textScaler: TextScaler.noScaling,
+ onKeyEvent: _onTerminalKey,
+ onTapDown: _onLinkTapDown,
+ onTapUp: _onLinkTapUp,
+ mouseCursor:
+ _hoveredLink != null && _linkModifierPressed
+ ? SystemMouseCursors.click
+ // An I-beam invites typing; a blocked pane does not.
+ : _inputBlocked
+ ? SystemMouseCursors.basic
+ : SystemMouseCursors.text,
+ onSecondaryTapDown: (_, _) => _copyOrPaste(),
+
+ onAltBufferScroll: session.scrollViaTmuxCopyMode
+ ? (up) => session.sendScrollCommand(up, 1)
+ : null,
),
- padding: const EdgeInsets.all(10),
- textStyle: terminalFontStore.value,
- // The chosen point size already sizes each terminal cell.
- // Applying the OS text scale again would change rows/cols
- // and resize the remote terminal unexpectedly.
- textScaler: TextScaler.noScaling,
- onKeyEvent: _onTerminalKey,
- onTapDown: _onLinkTapDown,
- onTapUp: _onLinkTapUp,
- mouseCursor:
- _hoveredLink != null && _linkModifierPressed
- ? SystemMouseCursors.click
- // An I-beam invites typing; a blocked pane does not.
- : _inputBlocked
- ? SystemMouseCursors.basic
- : SystemMouseCursors.text,
- onSecondaryTapDown: (_, _) => _copyOrPaste(),
-
- onAltBufferScroll: session.scrollViaTmuxCopyMode
- ? (up) => session.sendScrollCommand(up, 1)
- : null,
),
),
),
- ),
- // Keep the control notice beside the work. This band covers the
- // frozen output itself, where the eyes already are, and
- // stays through `opening` so the pane does not jump when
- // it is answered.
- if (_inputBlocked ||
- (_retakingControl &&
- session.status == TerminalSessionStatus.opening))
- Positioned(
- top: 0,
- left: 0,
- right: 0,
- child: _ControlBanner(
- busy: !_inputBlocked,
- nudged: _controlNudged,
- nudge: _controlNudge,
- takerName: session.takenOverBy?.label(
- (id) =>
- widget.notifier.stateOf(id)?.machine.displayName,
+ // Keep the control notice beside the work. This band covers the
+ // frozen output itself, where the eyes already are, and
+ // stays through `opening` so the pane does not jump when
+ // it is answered.
+ if (_inputBlocked ||
+ (_retakingControl &&
+ session.status == TerminalSessionStatus.opening))
+ Positioned(
+ top: 0,
+ left: 0,
+ right: 0,
+ child: _ControlBanner(
+ busy: !_inputBlocked,
+ nudged: _controlNudged,
+ nudge: _controlNudge,
+ takerName: session.takenOverBy?.label(
+ (id) => widget.notifier
+ .stateOf(id)
+ ?.machine
+ .displayName,
+ ),
+ onTakeControl: _inputBlocked
+ ? () => unawaited(_takeControl())
+ : null,
),
- onTakeControl: _inputBlocked
- ? () => unawaited(_takeControl())
- : null,
- onFocusTerminal: () =>
- _laidOutTerminalView()?.requestKeyboard(),
),
- ),
- if (session.uploadProgress != null ||
- _previewProgress != null)
- Positioned(
- left: 14,
- right: 14,
- bottom: 12,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- if (session.uploadProgress != null)
- _TransferProgressBadge(
- label:
- 'Uploading ${session.uploadProgress!.label}',
- fraction: session.uploadProgress!.percent,
- onCancel: () => unawaited(session.cancelUpload()),
- ),
- if (session.uploadProgress != null &&
- _previewProgress != null)
- const SizedBox(height: 8),
- if (_previewProgress != null)
- _TransferProgressBadge(
- label: _previewProgress!.totalBytes == null
- ? 'Preparing preview…'
- : 'Downloading ${_previewProgress!.filename}',
- fraction: _previewProgress!.fraction,
- onCancel: () => _previewCancellation?.cancel(),
- ),
- ],
+ if (session.uploadProgress != null ||
+ _previewProgress != null)
+ Positioned(
+ left: 14,
+ right: 14,
+ bottom: 12,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (session.uploadProgress != null)
+ _TransferProgressBadge(
+ label:
+ 'Uploading ${session.uploadProgress!.label}',
+ fraction: session.uploadProgress!.percent,
+ onCancel: () =>
+ unawaited(session.cancelUpload()),
+ ),
+ if (session.uploadProgress != null &&
+ _previewProgress != null)
+ const SizedBox(height: 8),
+ if (_previewProgress != null)
+ _TransferProgressBadge(
+ label: _previewProgress!.totalBytes == null
+ ? 'Preparing preview…'
+ : 'Downloading ${_previewProgress!.filename}',
+ fraction: _previewProgress!.fraction,
+ onCancel: () => _previewCancellation?.cancel(),
+ ),
+ ],
+ ),
),
- ),
- ],
+ ],
+ ),
),
),
// The grip is shown whether or not the box is: collapsed, it is the only way back.
@@ -2174,10 +2242,6 @@ class _ControlBanner extends StatelessWidget {
final int nudge;
final VoidCallback? onTakeControl;
- /// A click on the band's text puts the keyboard in the terminal, so ⏎ works
- /// even when the person reached the pane with the mouse.
- final VoidCallback? onFocusTerminal;
-
/// Who has the terminal now, when the daemon said (`terminal_closed.takenBy`
/// — the fleet's current name for that machine when this app knows it);
/// null from an older daemon or a taker that did not introduce itself.
@@ -2188,7 +2252,6 @@ class _ControlBanner extends StatelessWidget {
required this.nudged,
required this.nudge,
required this.onTakeControl,
- required this.onFocusTerminal,
this.takerName,
});
@@ -2201,7 +2264,7 @@ class _ControlBanner extends StatelessWidget {
String? get detail {
if (busy) return null;
if (nudged) return 'Keys are ignored — press ⏎ to take control.';
- return 'Typing is paused. Press ⏎ or click Take control to type here again.';
+ return 'Typing is paused. Click here or press ⏎ to take control.';
}
@override
@@ -2289,20 +2352,17 @@ class _ControlBanner extends StatelessWidget {
],
],
);
- // The text is a click target too: it hands the terminal the
- // keyboard, which is what makes the ⏎ it promises true.
+ // A press anywhere on the band takes the stream back (the
+ // panel's Listener over the whole body); the text needs no
+ // gesture of its own.
final prose = MouseRegion(
cursor: SystemMouseCursors.basic,
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: onFocusTerminal,
- child: Row(
- children: [
- lead,
- const SizedBox(width: 10),
- Expanded(child: text),
- ],
- ),
+ child: Row(
+ children: [
+ lead,
+ const SizedBox(width: 10),
+ Expanded(child: text),
+ ],
),
);
final button = busy
diff --git a/desktop/test/retake_taken_over_panes_test.dart b/desktop/test/retake_taken_over_panes_test.dart
new file mode 100644
index 000000000..8341bff09
--- /dev/null
+++ b/desktop/test/retake_taken_over_panes_test.dart
@@ -0,0 +1,119 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/terminal/terminal_session.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+/// One gesture on the app takes back every stream another client took from
+/// it — and nothing else: a pane that is fine, one that closed on its own, a
+/// shared read-only view, or one the daemon would refuse are all left alone.
+void main() {
+ late AppNotifier app;
+ final sent = <String, List<String>>{};
+
+ TerminalSession session(
+ String id, {
+ String machineId = 'm',
+ TerminalSessionStatus status = TerminalSessionStatus.takenOver,
+ bool readOnly = false,
+ }) {
+ sent[id] = [];
+ return TerminalSession(
+ machineId: machineId,
+ agentId: id,
+ agentName: 'Session $id',
+ engineId: 'codex',
+ readOnly: readOnly,
+ send: (type, _) async {
+ sent[id]!.add(type);
+ return true;
+ },
+ sendBinary: (_) async => true,
+ )..status = status;
+ }
+
+ List<String> opens(String id) =>
+ sent[id]!.where((t) => t == 'terminal_open').toList();
+
+ setUp(() {
+ sent.clear();
+ app = createApp();
+ app.stateOf('m')!
+ ..nodeOnline = true
+ ..terminalCapabilityAvailable = true;
+ });
+
+ tearDown(() => app.dispose());
+
+ test(
+ 'reopens every taken-over pane the daemon would accept, and only those',
+ () async {
+ app.adoptSessionForTest(session('a0'));
+ app.adoptSessionForTest(
+ session('a1', status: TerminalSessionStatus.controlling),
+ );
+ // closed/error are the auto-reattach's business, not a person's return.
+ app.adoptSessionForTest(
+ session('a2', status: TerminalSessionStatus.closed),
+ );
+ app.adoptSessionForTest(session('a3', readOnly: true));
+
+ await app.retakeTakenOverPanes();
+
+ expect(opens('a0'), ['terminal_open']);
+ expect(opens('a1'), isEmpty);
+ expect(opens('a2'), isEmpty);
+ expect(opens('a3'), isEmpty);
+ expect(
+ app.paneOfAgent('m', 'a0')!.session!.status,
+ TerminalSessionStatus.opening,
+ );
+
+ // Already opening: a second gesture sends nothing more.
+ await app.retakeTakenOverPanes();
+ expect(opens('a0'), ['terminal_open']);
+ },
+ );
+
+ test('a pane behind another tab is this app\'s too', () async {
+ app.adoptSessionForTest(session('a0'));
+ app.newSwarm();
+ app.adoptSessionForTest(session('a1'));
+ expect(app.activeSwarm.panes.map((p) => p.agentId), ['a1']);
+
+ await app.retakeTakenOverPanes();
+ expect(opens('a0'), ['terminal_open']);
+ expect(opens('a1'), ['terminal_open']);
+ });
+
+ test('a pane the daemon would refuse keeps its band', () async {
+ const offline = Machine(
+ machineId: 'm2',
+ authMode: MachineAuthMode.remote,
+ name: 'Away',
+ );
+ app.machines = [...app.machines, offline];
+ app.machineStates['m2'] = MachineState(offline)
+ ..nodeOnline = false
+ ..terminalCapabilityAvailable = true
+ ..agents = const [
+ Agent(
+ id: 'b0',
+ name: 'Away agent',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ ];
+ app.adoptSessionForTest(session('b0', machineId: 'm2'));
+ app.adoptSessionForTest(session('a0'));
+
+ await app.retakeTakenOverPanes();
+ expect(opens('a0'), ['terminal_open']);
+ expect(opens('b0'), isEmpty);
+ expect(
+ app.paneOfAgent('m2', 'b0')!.session!.status,
+ TerminalSessionStatus.takenOver,
+ );
+ });
+}
diff --git a/desktop/test/terminal_control_banner_test.dart b/desktop/test/terminal_control_banner_test.dart
index f7f5c4d14..1605f212f 100644
--- a/desktop/test/terminal_control_banner_test.dart
+++ b/desktop/test/terminal_control_banner_test.dart
@@ -6,6 +6,7 @@ import 'package:harness/state/app_state.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/terminal_panel.dart';
+import 'package:xterm/xterm.dart';
import 'swarm_state_test.dart' show createApp;
@@ -17,6 +18,11 @@ void main() {
late List<String> sent;
late List<TerminalBinaryFrame> input;
+ /// A second tile of the same app, adopted but (unless a test mounts it)
+ /// not on screen: what a gesture on `session`'s tile does to the REST.
+ late TerminalSession other;
+ late List<String> sentOther;
+
setUp(() {
app = createApp();
app.stateOf('m')!
@@ -42,6 +48,24 @@ void main() {
..status = TerminalSessionStatus.controlling
..streamId = 'stream-a0';
app.adoptSessionForTest(session);
+ sentOther = [];
+ other =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a1',
+ agentName: 'Session a1',
+ engineId: 'codex',
+ send: (type, _) async {
+ sentOther.add(type);
+ return true;
+ },
+ sendBinary: (_) async => true,
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream-a1';
+ app.adoptSessionForTest(other);
+ // The tile under test is the focused one; the other is just present.
+ app.focusPane(app.paneOfAgent('m', 'a0')!.id);
});
// The app owns the adopted session and disposes it with itself. Done inside
@@ -49,6 +73,9 @@ void main() {
// binding checks for pending timers before tearDown runs.
var finished = false;
Future<void> finish(WidgetTester tester) async {
+ // A tap into a live terminal arms xterm's double-tap recognizer; let it
+ // lapse before the binding checks for stray timers.
+ await tester.pump(const Duration(milliseconds: 400));
await tester.pumpWidget(const SizedBox());
app.dispose();
finished = true;
@@ -65,6 +92,9 @@ void main() {
TerminalNotice? notice,
bool composerVisible = false,
bool compactHeader = false,
+ bool focused = true,
+ bool visible = true,
+ int focusRequest = 0,
double width = 900,
Widget? beside,
}) async {
@@ -81,7 +111,9 @@ void main() {
child: TerminalPanel(
notifier: app,
session: session,
- focused: true,
+ focused: focused,
+ visible: visible,
+ focusRequest: focusRequest,
readOnly: readOnly,
notice: notice,
composerVisible: composerVisible,
@@ -101,6 +133,16 @@ void main() {
/// Mounting measures the grid and sends a resize; only the opens matter here.
List<String> opens() => sent.where((t) => t == 'terminal_open').toList();
+ List<String> opensOther() =>
+ sentOther.where((t) => t == 'terminal_open').toList();
+
+ void takeOverOther() {
+ other.handleFrame('terminal_closed', {
+ 'streamId': 'stream-a1',
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'reason': 'Another client connected to this terminal.',
+ });
+ }
void takeOver() {
session.handleFrame('terminal_closed', {
@@ -136,7 +178,7 @@ void main() {
});
}
- final hint = find.textContaining('Press ⏎');
+ final hint = find.textContaining('press ⏎');
testWidgets('the banner names who took control when the daemon said', (
tester,
@@ -365,29 +407,329 @@ void main() {
await finish(tester);
});
- testWidgets('clicking the band\'s text focuses the terminal for ⏎', (
+ // ── Coming back to the pane takes the stream back ─────────────────────────
+ //
+ // A person returning to a taken-over tile — by mouse, by key, by switching to
+ // its tab, by bringing the window forward — gets it back without being asked.
+ // The one thing these must never do is fire on the takeover itself: both
+ // apps see that, and two panes retaking on each other's notifications would
+ // trade the stream forever. The first test below pins that.
+
+ testWidgets('losing the stream on its own never retakes it', (tester) async {
+ // The focused, visible tile has the keyboard pulled into it on takeover;
+ // that pull is the app's doing, not the person's, and must not retake —
+ // neither this tile nor any other the same client took.
+ await pump(tester);
+ takeOver();
+ takeOverOther();
+ for (var i = 0; i < 4; i++) {
+ await tester.pump();
+ }
+ expect(session.status, TerminalSessionStatus.takenOver);
+ expect(other.status, TerminalSessionStatus.takenOver);
+ expect(opens(), isEmpty);
+ expect(opensOther(), isEmpty);
+ await finish(tester);
+ });
+
+ // ── One gesture brings the whole app back ─────────────────────────────────
+
+ testWidgets('a click into a pane that is fine retakes the others', (
tester,
) async {
+ await pump(tester);
+ takeOverOther();
+ await tester.pump();
+ expect(takenOverTitle, findsNothing, reason: 'this tile is not taken');
+
+ await tester.tapAt(tester.getCenter(find.byType(TerminalView)));
+ await tester.pump();
+ expect(opensOther(), ['terminal_open']);
+ expect(opens(), isEmpty, reason: 'nothing to reopen on the tile clicked');
+ await finish(tester);
+ });
+
+ testWidgets('⏎ on one taken tile retakes every taken tile', (tester) async {
+ await pump(tester);
+ takeOver();
+ takeOverOther();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ expect(opensOther(), ['terminal_open']);
+ expect(find.text('Taking control…'), findsOneWidget);
+ await finish(tester);
+ });
+
+ testWidgets('the window coming back retakes the others too', (tester) async {
+ await pump(tester);
+ takeOverOther();
+ await tester.pump();
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ await tester.pump();
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
+ await tester.pump();
+ expect(opensOther(), ['terminal_open']);
+ await finish(tester);
+ });
+
+ testWidgets('a tile the daemon would refuse is left with its band', (
+ tester,
+ ) async {
+ // The other tile's machine is offline: nothing can be reopened there.
+ app.stateOf('m')!.nodeOnline = false;
+ await pump(tester);
+ takeOverOther();
+ await tester.pump();
+ await tester.tapAt(tester.getCenter(find.byType(TerminalView)));
+ await tester.pump();
+ expect(opensOther(), isEmpty);
+ expect(other.status, TerminalSessionStatus.takenOver);
+ await finish(tester);
+ });
+
+ testWidgets('a tile retaken by another tile\'s gesture keeps its band up', (
+ tester,
+ ) async {
+ // Both tiles on screen; the other's band should say "Taking control…"
+ // through the handshake, exactly as its own ⏎ would, not vanish early.
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Row(
+ children: [
+ Expanded(
+ child: TerminalPanel(
+ notifier: app,
+ session: session,
+ focused: true,
+ ),
+ ),
+ Expanded(
+ child: TerminalPanel(
+ notifier: app,
+ session: other,
+ focused: false,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ takeOverOther();
+ await tester.pump();
+ expect(takenOverTitle, findsOneWidget);
+
+ await tester.tapAt(tester.getCenter(find.byType(TerminalView).first));
+ await tester.pump();
+ expect(opensOther(), ['terminal_open']);
+ expect(find.text('Taking control…'), findsOneWidget);
+ expect(takenOverTitle, findsNothing);
+
+ other
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream-a1-2'
+ ..notifyListeners();
+ await tester.pump();
+ expect(find.text('Taking control…'), findsNothing);
+ await finish(tester);
+ });
+
+ testWidgets('a click into the pane takes control back, once', (tester) async {
final elsewhere = FocusNode();
addTearDown(elsewhere.dispose);
await pump(tester, beside: TextField(focusNode: elsewhere));
takeOver();
await tester.pump();
- await tester.pump();
- // Wander off again after the pull, then come back by mouse.
elsewhere.requestFocus();
await tester.pump();
- expect(elsewhere.hasFocus, isTrue);
+ await tester.tapAt(tester.getCenter(find.byType(TerminalView)));
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ expect(session.status, TerminalSessionStatus.opening);
+ // A second press while the handshake is under way sends nothing more.
+ await tester.tapAt(tester.getCenter(find.byType(TerminalView)));
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ await finish(tester);
+ });
+
+ testWidgets('a click on the band itself takes control back', (tester) async {
+ await pump(tester);
+ takeOver();
+ await tester.pump();
await tester.tap(takenOverTitle);
await tester.pump();
- expect(elsewhere.hasFocus, isFalse);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ expect(opens(), ['terminal_open']);
+ await finish(tester);
+ });
+
+ testWidgets('a click into a shared read-only view takes nothing', (
+ tester,
+ ) async {
+ // A shared view's session is itself read only (`shared_harness_panel`):
+ // neither its own band path nor the app-wide retake has anything there.
+ final sentShared = <String>[];
+ final shared =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a2',
+ agentName: 'Shared a2',
+ engineId: 'codex',
+ readOnly: true,
+ send: (type, _) async {
+ sentShared.add(type);
+ return true;
+ },
+ sendBinary: (_) async => true,
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream-a2';
+ app.adoptSessionForTest(shared);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: TerminalPanel(
+ notifier: app,
+ session: shared,
+ focused: true,
+ readOnly: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ shared.handleFrame('terminal_closed', {
+ 'streamId': 'stream-a2',
+ 'code': 'TERMINAL_TAKEN_OVER',
+ });
+ await tester.pump();
+ await tester.tapAt(tester.getCenter(find.byType(TerminalView)));
+ await tester.pump();
+ expect(sentShared.where((t) => t == 'terminal_open'), isEmpty);
+ expect(takenOverTitle, findsNothing);
+ await finish(tester);
+ });
+
+ testWidgets('a click into a noticed pane takes nothing', (tester) async {
+ // Offline: the pane carries a notice instead of the band, and the daemon
+ // would refuse an open, so the app-wide retake skips it as well.
+ app.stateOf('m')!.nodeOnline = false;
+ await pump(
+ tester,
+ notice: (
+ label: 'Offline',
+ icon: Icons.cloud_off,
+ detail: 'Test host is offline.',
+ ),
+ );
+ takeOver();
+ await tester.pump();
+ await tester.tapAt(tester.getCenter(find.byType(TerminalView)));
+ await tester.pump();
+ expect(opens(), isEmpty);
+ expect(takenOverTitle, findsNothing);
+ await finish(tester);
+ });
+
+ testWidgets('focusing the tile by key takes control back', (tester) async {
+ // ⌘1–9 / ⌘] / an attention jump: the grid flips `focused` on this tile.
+ await pump(tester, focused: false);
+ takeOver();
+ await tester.pump();
+ expect(opens(), isEmpty);
+ await pump(tester, focused: true);
+ expect(opens(), ['terminal_open']);
+ await finish(tester);
+ });
+
+ testWidgets('re-focusing an already focused tile takes control back', (
+ tester,
+ ) async {
+ // ⌘1 on the tile that is already focused bumps `focusRequest` instead.
+ await pump(tester);
+ takeOver();
+ await tester.pump();
+ expect(opens(), isEmpty);
+ await pump(tester, focusRequest: 1);
+ expect(opens(), ['terminal_open']);
+ await finish(tester);
+ });
+
+ testWidgets(
+ 'a tile shown again takes control back only if it is the focused one',
+ (tester) async {
+ await pump(tester, visible: false);
+ takeOver();
+ await tester.pump();
+ expect(opens(), isEmpty);
+ await pump(tester, visible: true);
+ expect(opens(), ['terminal_open']);
+ await finish(tester);
+ },
+ );
+
+ testWidgets('a tile shown again unfocused stays as it is', (tester) async {
+ await pump(tester, visible: false, focused: false);
+ takeOver();
+ await tester.pump();
+ await pump(tester, visible: true, focused: false);
+ expect(opens(), isEmpty);
+ await finish(tester);
+ });
+
+ testWidgets('the window coming back to the front takes control back', (
+ tester,
+ ) async {
+ await pump(tester);
+ takeOver();
+ await tester.pump();
+ // The launch's own first `resumed` is nobody coming back.
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
+ await tester.pump();
+ expect(opens(), isEmpty);
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ await tester.pump();
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pump();
expect(opens(), ['terminal_open']);
await finish(tester);
});
+ testWidgets(
+ 'a tile opened while the window was behind still sees it return',
+ (tester) async {
+ // Mounted with the window already inactive: the very next `resumed` IS
+ // the person coming back, not the launch's first one.
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ await pump(tester);
+ takeOver();
+ await tester.pump();
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ await finish(tester);
+ },
+ );
+
+ testWidgets('the window coming back leaves an unfocused tile alone', (
+ tester,
+ ) async {
+ await pump(tester, focused: false);
+ takeOver();
+ await tester.pump();
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ await tester.pump();
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
+ await tester.pump();
+ expect(opens(), isEmpty);
+ await finish(tester);
+ });
+
testWidgets('a narrow tile stacks the button under the title', (
tester,
) async {