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: add in-pane control banner for terminal session takeover and reconnection

0xken15c85fea20e759
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index b6adf2610..730d8f6b4 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -186,6 +186,23 @@ class _TerminalPanelState extends State<TerminalPanel>
Object? _headerPresentation;
Widget? _header;
+ /// Set while the in-pane control banner is answering a keystroke that went
+ /// nowhere (see [_nudgeControlBanner]); cleared by [_controlNudgeTimer].
+ bool _controlNudged = false;
+ int _controlNudge = 0;
+ Timer? _controlNudgeTimer;
+
+ /// Set when THIS pane asked for the stream back, so the banner can stay up
+ /// through `opening` saying so. A first open, or a resync, is not that and
+ /// shows nothing.
+ bool _retakingControl = false;
+ TerminalSessionStatus? _retakingFrom;
+
+ /// The status the last frame was built for. The grid normally rebuilds this
+ /// panel on every session change, but the banner must not depend on that.
+ TerminalSessionStatus? _builtStatus;
+ bool _wasBlocked = false;
+
@override
void initState() {
super.initState();
@@ -317,6 +334,7 @@ class _TerminalPanelState extends State<TerminalPanel>
terminalThemeStore.removeListener(_onFontChanged);
_cancelDialInertia();
_cursorBlinkTimer?.cancel();
+ _controlNudgeTimer?.cancel();
_focusNode.removeListener(_handleFocusChange);
_composerFocus.removeListener(_handleComposerFocusChange);
_controller.dispose();
@@ -349,6 +367,32 @@ class _TerminalPanelState extends State<TerminalPanel>
void _onSessionChanged() {
if (!mounted) return;
_syncCursorBlink();
+ if (_controlNudged && !_inputBlocked) {
+ _controlNudgeTimer?.cancel();
+ _controlNudgeTimer = null;
+ setState(() => _controlNudged = false);
+ }
+ if (_retakingControl &&
+ widget.session.status != TerminalSessionStatus.opening) {
+ setState(() => _retakingControl = false);
+ } else if (_builtStatus != widget.session.status) {
+ setState(() {});
+ }
+ // The band promises ⏎, so the focused tile puts the keyboard in its
+ // terminal the moment the stream is lost: a composer being disabled drops
+ // it on the floor, and a pane reached by mouse may never have held it —
+ // either way the focused tile would be the one place ⏎ did nothing.
+ // Only when the keyboard is this pane's or nobody's, though: a person
+ // mid-word in the command dock or a rename field keeps it, and the band's
+ // text is there to click when they come back.
+ if (_inputBlocked &&
+ !_wasBlocked &&
+ widget.focused &&
+ widget.visible &&
+ _keyboardIsOursOrIdle) {
+ _claimFocusAfterFrame();
+ }
+ _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
// `_afterTerminalMounted` lands on nothing and the screen then fills in
@@ -540,10 +584,14 @@ class _TerminalPanelState extends State<TerminalPanel>
bar.focusSearch(selectAll: false);
return true;
}
- if (_composerFocus.hasFocus) return true;
// On a remote pane the box gets the caret, not the terminal. Landing in the terminal would
// hand the user the per-keystroke path by default — the exact cost the box exists to avoid.
- if (_showsComposer && !widget.readOnly) {
+ // Except while the pane has lost control: the box is being disabled (it
+ // may still hold focus this frame, and drops it on the next) and the
+ // terminal is where ⏎ takes control back (see [_onTerminalKey]), so the
+ // keyboard is moved there rather than left to fall to the route.
+ if (_composerFocus.hasFocus && !_inputBlocked) return true;
+ if (_showsComposer && !widget.readOnly && !_inputBlocked) {
if (widget.session.acceptsInput && _composerFocus.canRequestFocus) {
_composerFocus.requestFocus();
return true;
@@ -555,6 +603,74 @@ class _TerminalPanelState extends State<TerminalPanel>
return true;
}
+ /// Whether pulling focus into the terminal would take it from nobody: the
+ /// keyboard is already in this pane (terminal or composer) or has fallen
+ /// back to a scope with no field under it.
+ bool get _keyboardIsOursOrIdle {
+ final primary = FocusManager.instance.primaryFocus;
+ return primary == null ||
+ primary is FocusScopeNode ||
+ identical(primary, _focusNode) ||
+ identical(primary, _composerFocus);
+ }
+
+ /// The pane cannot take input and a person can do something about it:
+ /// another client took the stream ([TerminalSessionStatus.takenOver]) or it
+ /// closed/errored, and the header's chip would offer Take control /
+ /// Reconnect. Not `opening`/`resyncing` (the pane is already recovering on
+ /// its own) and not a pane-level [TerminalPanel.notice] (offline, unlinked —
+ /// nothing here would help), and never a shared read-only view.
+ bool get _inputBlocked {
+ if (widget.readOnly || widget.notice != null) return false;
+ return switch (widget.session.status) {
+ TerminalSessionStatus.takenOver ||
+ TerminalSessionStatus.closed ||
+ TerminalSessionStatus.error => true,
+ TerminalSessionStatus.opening ||
+ TerminalSessionStatus.resyncing ||
+ TerminalSessionStatus.controlling => false,
+ };
+ }
+
+ /// 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`.
+ Future<void> _takeControl() async {
+ final session = widget.session;
+ if (_inputBlocked && !_retakingControl) {
+ setState(() {
+ _retakingControl = true;
+ _retakingFrom = session.status;
+ });
+ }
+ 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
+ // listener call, so the flag is taken back here rather than left armed
+ // for an `opening` this pane never asked for.
+ if (mounted &&
+ _retakingControl &&
+ identical(widget.session, session) &&
+ session.status != TerminalSessionStatus.opening) {
+ setState(() => _retakingControl = false);
+ }
+ }
+
+ /// 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() {
+ if (!mounted) return;
+ _controlNudgeTimer?.cancel();
+ _controlNudgeTimer = Timer(const Duration(seconds: 2), () {
+ _controlNudgeTimer = null;
+ if (mounted) setState(() => _controlNudged = false);
+ });
+ setState(() {
+ _controlNudged = true;
+ _controlNudge++;
+ });
+ }
+
bool get _canClaimInput =>
mounted &&
_focusNode.canRequestFocus &&
@@ -1022,10 +1138,29 @@ class _TerminalPanelState extends State<TerminalPanel>
/// so agent image paste follows the same path. Linux reserves Ctrl-V for
/// the terminal program and uses Ctrl-Shift-V for its clipboard.
KeyEventResult _onTerminalKey(FocusNode node, KeyEvent event) {
+ final keyboard = HardwareKeyboard.instance;
+ // A pane that lost control still gets the keys (xterm's read-only mode
+ // keeps the focus node, it only stops opening an input connection), and
+ // dropping them silently is how people sit typing into a frozen pane. ⏎
+ // takes control back; any other plain key nudges the banner that says so.
+ // ⌘/⌃ chords are left alone: they are the app's and the pane's shortcuts.
+ if (event is KeyDownEvent &&
+ _inputBlocked &&
+ !keyboard.isMetaPressed &&
+ !keyboard.isControlPressed) {
+ if (event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter) {
+ unawaited(_takeControl());
+ return KeyEventResult.handled;
+ }
+ if (_isTypingKey(event)) {
+ _nudgeControlBanner();
+ return KeyEventResult.ignored;
+ }
+ }
if (event is! KeyDownEvent || event.logicalKey != LogicalKeyboardKey.keyV) {
return KeyEventResult.ignored;
}
- final keyboard = HardwareKeyboard.instance;
if (keyboard.isAltPressed) return KeyEventResult.ignored;
final apple =
defaultTargetPlatform == TargetPlatform.macOS ||
@@ -1043,6 +1178,28 @@ class _TerminalPanelState extends State<TerminalPanel>
return KeyEventResult.handled;
}
+ /// A key that would have put something into the terminal: a character, or
+ /// one of the editing/navigation keys a prompt answers. Not a bare modifier
+ /// or a function key, which nobody expects to echo.
+ static bool _isTypingKey(KeyEvent event) {
+ final character = event.character;
+ if (character != null && character.isNotEmpty) return true;
+ return _editingKeys.contains(event.logicalKey);
+ }
+
+ // Not const: LogicalKeyboardKey overrides `==`, which a const set refuses.
+ static final Set<LogicalKeyboardKey> _editingKeys = {
+ LogicalKeyboardKey.backspace,
+ LogicalKeyboardKey.delete,
+ LogicalKeyboardKey.tab,
+ LogicalKeyboardKey.escape,
+ LogicalKeyboardKey.space,
+ LogicalKeyboardKey.arrowUp,
+ LogicalKeyboardKey.arrowDown,
+ LogicalKeyboardKey.arrowLeft,
+ LogicalKeyboardKey.arrowRight,
+ };
+
bool get _linkModifierPressed {
final keyboard = HardwareKeyboard.instance;
if (keyboard.isAltPressed || keyboard.isShiftPressed) return false;
@@ -1204,6 +1361,7 @@ class _TerminalPanelState extends State<TerminalPanel>
grid.AppTheme.watch(context);
final session = widget.session;
_syncTerminal(session.terminal);
+ _builtStatus = session.status;
final machineState = widget.notifier.stateOf(session.machineId);
final remote = machineState != null && !machineState.isLocalMachine;
final showComposer = _showsComposer;
@@ -1342,6 +1500,9 @@ class _TerminalPanelState extends State<TerminalPanel>
mouseCursor:
_hoveredLink != null && _linkModifierPressed
? SystemMouseCursors.click
+ // An I-beam invites typing; a blocked pane does not.
+ : _inputBlocked
+ ? SystemMouseCursors.basic
: SystemMouseCursors.text,
onSecondaryTapDown: (_, _) => _copyOrPaste(),
@@ -1352,6 +1513,33 @@ class _TerminalPanelState extends State<TerminalPanel>
),
),
),
+ // The header's status chip is 11pt in a corner; a person
+ // mid-sentence never sees it. This band sits over 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(
+ status: _inputBlocked
+ ? session.status
+ : _retakingFrom ?? session.status,
+ busy: !_inputBlocked,
+ errorMessage: session.errorMessage,
+ nudged: _controlNudged,
+ nudge: _controlNudge,
+ onTakeControl: _inputBlocked
+ ? () => unawaited(_takeControl())
+ : null,
+ onFocusTerminal: () =>
+ _laidOutTerminalView()?.requestKeyboard(),
+ ),
+ ),
if (session.uploadProgress != null ||
_previewProgress != null)
Positioned(
@@ -1467,6 +1655,7 @@ class _TerminalPanelState extends State<TerminalPanel>
onDelete: widget.onDelete == null
? null
: () => widget.onDelete?.call(),
+ onReconnect: () => unawaited(_takeControl()),
composerVisible: widget.composerVisible,
onToggleComposer: widget.onToggleComposer == null
? null
@@ -1490,6 +1679,10 @@ class _TerminalHeader extends StatelessWidget {
/// Ends the agent (with a confirmation), as the rail's row menu does. Null
/// where the pane cannot name a live agent to end.
final VoidCallback? onDelete;
+
+ /// Retakes a dead or taken-over stream. Falls back to `selectAgent` when
+ /// the panel did not supply one, which is the same call.
+ final VoidCallback? onReconnect;
final bool compact;
final VoidCallback? onToggleZoom;
final bool zoomed;
@@ -1515,6 +1708,7 @@ class _TerminalHeader extends StatelessWidget {
this.onRestart,
this.onFork,
this.onDelete,
+ this.onReconnect,
this.compact = false,
this.onToggleZoom,
this.zoomed = false,
@@ -1574,6 +1768,9 @@ class _TerminalHeader extends StatelessWidget {
(session.status == TerminalSessionStatus.error ||
session.status == TerminalSessionStatus.closed ||
session.status == TerminalSessionStatus.takenOver);
+ void reconnect() =>
+ (onReconnect ??
+ () => notifier.selectAgent(session.machineId, session.agentId))();
final machine = notifier.stateOf(session.machineId);
final agent = machine?.agents
.where((a) => a.id == session.agentId)
@@ -1679,12 +1876,7 @@ class _TerminalHeader extends StatelessWidget {
message: '${status.label}: ${status.detail}',
child: IconButton(
tooltip: status.label,
- onPressed: canReconnect
- ? () => notifier.selectAgent(
- session.machineId,
- session.agentId,
- )
- : null,
+ onPressed: canReconnect ? reconnect : null,
icon: Icon(status.icon, size: 14),
style: IconButton.styleFrom(
foregroundColor: color,
@@ -1712,12 +1904,7 @@ class _TerminalHeader extends StatelessWidget {
child: Tooltip(
message: status.detail,
child: TextButton(
- onPressed: canReconnect
- ? () => notifier.selectAgent(
- session.machineId,
- session.agentId,
- )
- : null,
+ onPressed: canReconnect ? reconnect : null,
style: TextButton.styleFrom(
foregroundColor: color,
disabledForegroundColor: AppColors.textSoft,
@@ -1942,6 +2129,266 @@ class _LinkModeMark extends StatelessWidget {
}
}
+/// The band over a pane whose stream is not this app's to type into: another
+/// client took it, or it closed. It says what happened, that keys go nowhere,
+/// and how to get it back — the header's chip carries the same fact, but at
+/// 11pt in a corner it was being read by nobody, and people sat typing.
+///
+/// ⏎ is named on the button itself and in the line under the title, always:
+/// the first cut showed it only once the terminal held focus and hid the line
+/// on a compact header, which is every pane in swarm mode — so the one thing
+/// a person needed to know was the one thing the band left out.
+///
+/// [status] is the state that put the banner up, never `opening`: while the
+/// pane is retaking the stream [busy] is set and the band keeps its place with
+/// the button swapped for a spinner, so answering it does not jump the layout.
+class _ControlBanner extends StatelessWidget {
+ final TerminalSessionStatus status;
+ final String? errorMessage;
+ final bool busy;
+
+ /// A key was just typed into the pane; see [_TerminalPanelState._nudgeControlBanner].
+ final bool nudged;
+ 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;
+
+ const _ControlBanner({
+ required this.status,
+ required this.errorMessage,
+ required this.busy,
+ required this.nudged,
+ required this.nudge,
+ required this.onTakeControl,
+ required this.onFocusTerminal,
+ });
+
+ bool get _takenOver => status == TerminalSessionStatus.takenOver;
+
+ String get title {
+ if (busy) return _takenOver ? 'Taking control…' : 'Reconnecting…';
+ return _takenOver
+ ? 'Another app took control of this terminal'
+ : 'This terminal is disconnected';
+ }
+
+ String get action => _takenOver ? 'Take control' : 'Reconnect';
+
+ String? get detail {
+ if (busy) return null;
+ final verb = _takenOver ? 'take control' : 'reconnect';
+ if (nudged) return 'Keys are ignored — press ⏎ to $verb.';
+ if (_takenOver) {
+ return 'Typing is paused. Press ⏎ or click Take control to type here again.';
+ }
+ final reason = errorMessage ?? 'Retained output is read only.';
+ return '$reason Press ⏎ to reconnect.';
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final ink = switch (status) {
+ TerminalSessionStatus.takenOver => AppColors.warning,
+ TerminalSessionStatus.error => AppColors.danger,
+ _ => AppColors.mutedStrong,
+ };
+ final icon = busy
+ ? null
+ : _takenOver
+ ? Icons.lock_outline
+ : Icons.refresh;
+ final detail = this.detail;
+ final reduceMotion = MediaQuery.disableAnimationsOf(context);
+ // Composited over the pane's own ground, as [UpdateNotice] is over the
+ // window's: the terminal theme behind this band may be any colour, and a
+ // bare 12% wash would read differently on each of them.
+ return Semantics(
+ container: true,
+ liveRegion: true,
+ child: Stack(
+ children: [
+ // The flash is the ground only. Re-keyed per nudge so each ignored
+ // key restarts it from full, and kept OUT of the content's ancestry
+ // so the button is not remounted (and does not lose focus or hover)
+ // on every keystroke.
+ Positioned.fill(
+ child: TweenAnimationBuilder<double>(
+ key: ValueKey(nudge),
+ tween: Tween(begin: 1, end: 0),
+ duration: reduceMotion
+ ? Duration.zero
+ : const Duration(milliseconds: 450),
+ curve: Curves.easeOut,
+ builder: (context, flash, _) {
+ final wash = ink.withValues(alpha: 0.12 + 0.18 * flash);
+ return DecoratedBox(
+ decoration: BoxDecoration(
+ color: Color.alphaBlend(wash, grid.AppPalette.panelBg),
+ border: Border(
+ bottom: BorderSide(color: ink.withValues(alpha: 0.55)),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(14, 10, 12, 10),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ // A quarter-width tile at large text cannot seat the sentence
+ // and the button on one line; there the button takes a line of
+ // its own under the title rather than running off the edge.
+ final narrow = constraints.maxWidth < 340;
+ final lead = icon != null
+ ? Icon(icon, size: 16, color: ink)
+ : SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: ink,
+ ),
+ );
+ final text = Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppColors.text,
+ fontFamily: AppFonts.sans,
+ fontSize: 12,
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ if (detail != null) ...[
+ const SizedBox(height: 2),
+ Text(
+ detail,
+ maxLines: narrow ? 1 : 2,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: nudged ? ink : AppColors.textSoft,
+ fontFamily: AppFonts.sans,
+ fontSize: 11,
+ height: 1.3,
+ ),
+ ),
+ ],
+ ],
+ );
+ // The text is a click target too: it hands the terminal the
+ // keyboard, which is what makes the ⏎ it promises true.
+ final prose = MouseRegion(
+ cursor: SystemMouseCursors.basic,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onFocusTerminal,
+ child: Row(
+ children: [
+ lead,
+ const SizedBox(width: 10),
+ Expanded(child: text),
+ ],
+ ),
+ ),
+ );
+ final button = busy
+ ? null
+ : _ControlBannerButton(
+ label: action,
+ onPressed: onTakeControl,
+ );
+ if (narrow) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ prose,
+ if (button != null) ...[
+ const SizedBox(height: 8),
+ Align(
+ alignment: Alignment.centerRight,
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: button,
+ ),
+ ),
+ ],
+ ],
+ );
+ }
+ return Row(
+ children: [
+ Expanded(child: prose),
+ if (button != null) ...[const SizedBox(width: 12), button],
+ ],
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// `Take control ⏎` — the action with its key drawn on it, in the button's own
+/// ink rather than [KeyCap]'s well fill, which would sit as a grey square on
+/// the accent.
+class _ControlBannerButton extends StatelessWidget {
+ final String label;
+ final VoidCallback? onPressed;
+ const _ControlBannerButton({required this.label, required this.onPressed});
+
+ @override
+ Widget build(BuildContext context) {
+ final onAccent = Theme.of(context).colorScheme.onPrimary;
+ return FilledButton(
+ onPressed: onPressed,
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(0, 28),
+ padding: const EdgeInsets.fromLTRB(12, 0, 8, 0),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ visualDensity: VisualDensity.compact,
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ label,
+ style: TextStyle(
+ fontFamily: AppFonts.sans,
+ fontSize: 12,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(width: 8),
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
+ decoration: BoxDecoration(
+ border: Border.all(color: onAccent.withValues(alpha: 0.6)),
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: Semantics(
+ label: 'Return',
+ child: Icon(Icons.keyboard_return, size: 12, color: onAccent),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
/// Image/file transfer progress with a cancel action, kept in the pane's corner.
class _TransferProgressBadge extends StatelessWidget {
final String label;
diff --git a/desktop/test/terminal_control_banner_test.dart b/desktop/test/terminal_control_banner_test.dart
new file mode 100644
index 000000000..f16c979c2
--- /dev/null
+++ b/desktop/test/terminal_control_banner_test.dart
@@ -0,0 +1,350 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+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 'swarm_state_test.dart' show createApp;
+
+/// The band over a pane that lost its stream: what it says, that ⏎ takes the
+/// stream back, and that a stray keystroke is answered rather than dropped.
+void main() {
+ late AppNotifier app;
+ late TerminalSession session;
+ late List<String> sent;
+ late List<TerminalBinaryFrame> input;
+
+ setUp(() {
+ app = createApp();
+ app.stateOf('m')!
+ ..nodeOnline = true
+ ..terminalCapabilityAvailable = true;
+ sent = [];
+ input = [];
+ session =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a0',
+ agentName: 'Session a0',
+ engineId: 'codex',
+ send: (type, _) async {
+ sent.add(type);
+ return true;
+ },
+ sendBinary: (frame) async {
+ if (frame.kind == TerminalBinaryKind.input) input.add(frame);
+ return true;
+ },
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream-a0';
+ app.adoptSessionForTest(session);
+ });
+
+ // The app owns the adopted session and disposes it with itself. Done inside
+ // the test body: a reopen arms the session's handshake timers, and the
+ // binding checks for pending timers before tearDown runs.
+ var finished = false;
+ Future<void> finish(WidgetTester tester) async {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ finished = true;
+ }
+
+ tearDown(() {
+ if (!finished) app.dispose();
+ finished = false;
+ });
+
+ Future<void> pump(
+ WidgetTester tester, {
+ bool readOnly = false,
+ TerminalNotice? notice,
+ bool composerVisible = false,
+ bool compactHeader = false,
+ double width = 900,
+ Widget? beside,
+ }) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Column(
+ children: [
+ ?beside,
+ Center(
+ child: SizedBox(
+ width: width,
+ height: 400,
+ child: TerminalPanel(
+ notifier: app,
+ session: session,
+ focused: true,
+ readOnly: readOnly,
+ notice: notice,
+ composerVisible: composerVisible,
+ compactHeader: compactHeader,
+ onToggleComposer: () {},
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.pump();
+ }
+
+ /// Mounting measures the grid and sends a resize; only the opens matter here.
+ List<String> opens() => sent.where((t) => t == 'terminal_open').toList();
+
+ void takeOver() {
+ session.handleFrame('terminal_closed', {
+ 'streamId': 'stream-a0',
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'reason': 'Another client connected to this terminal.',
+ });
+ }
+
+ final banner = find.widgetWithText(FilledButton, 'Take control');
+ final takenOverTitle = find.text('Another app took control of this terminal');
+
+ final hint = find.textContaining('Press ⏎');
+
+ testWidgets('the banner appears over a taken-over pane and only there', (
+ tester,
+ ) async {
+ // Swarm mode hands every pane a compact header; the band must not read
+ // that as permission to drop the one line that says what to press.
+ await pump(tester, compactHeader: true);
+ expect(takenOverTitle, findsNothing);
+ expect(banner, findsNothing);
+
+ takeOver();
+ await tester.pump();
+ expect(session.status, TerminalSessionStatus.takenOver);
+ expect(takenOverTitle, findsOneWidget);
+ expect(banner, findsOneWidget);
+ expect(hint, findsOneWidget);
+ expect(
+ find.descendant(of: banner, matching: find.byIcon(Icons.keyboard_return)),
+ findsOneWidget,
+ reason: 'the key is drawn on the button itself',
+ );
+
+ // A shared read-only view has nothing to take.
+ await pump(tester, readOnly: true);
+ expect(takenOverTitle, findsNothing);
+
+ // A pane-level notice (offline, unlinked) already explains itself.
+ await pump(
+ tester,
+ notice: (
+ label: 'Offline',
+ icon: Icons.cloud_off,
+ detail: 'Test host is offline.',
+ ),
+ );
+ expect(takenOverTitle, findsNothing);
+ await finish(tester);
+ });
+
+ testWidgets('⏎ in the terminal takes control back, once', (tester) async {
+ await pump(tester);
+ takeOver();
+ await tester.pump();
+ expect(opens(), isEmpty);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ expect(input, isEmpty);
+ expect(session.status, TerminalSessionStatus.opening);
+ // The band stays through the handshake, saying so, without a button.
+ expect(find.text('Taking control…'), findsOneWidget);
+ expect(banner, findsNothing);
+
+ // A held or repeated ⏎ does not send a second open.
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+
+ session
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream-a0-2'
+ ..notifyListeners();
+ await tester.pump();
+ expect(find.text('Taking control…'), findsNothing);
+ expect(takenOverTitle, findsNothing);
+ await finish(tester);
+ });
+
+ testWidgets('a keystroke into a taken-over pane is answered, not dropped', (
+ tester,
+ ) async {
+ await pump(tester);
+ takeOver();
+ await tester.pump();
+ final nudge = find.text('Keys are ignored — press ⏎ to take control.');
+ expect(nudge, findsNothing);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyA);
+ await tester.pump();
+ expect(input, isEmpty);
+ expect(opens(), isEmpty);
+ expect(nudge, findsOneWidget);
+
+ // The message steps back once the person stops typing.
+ await tester.pump(const Duration(seconds: 3));
+ expect(nudge, findsNothing);
+
+ // ⌘ chords are the app's, not an attempt to type.
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyC);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+ await tester.pump();
+ expect(nudge, findsNothing);
+ expect(opens(), isEmpty);
+ await finish(tester);
+ });
+
+ testWidgets('the button takes control too', (tester) async {
+ await pump(tester);
+ takeOver();
+ await tester.pump();
+ await tester.tap(banner);
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ expect(find.text('Taking control…'), findsOneWidget);
+ await finish(tester);
+ });
+
+ testWidgets('a closed stream gets the same band, worded as a reconnect', (
+ tester,
+ ) async {
+ await pump(tester);
+ session.handleFrame('terminal_closed', {
+ 'streamId': 'stream-a0',
+ 'reason': 'Session exited.',
+ });
+ await tester.pump();
+ expect(session.status, TerminalSessionStatus.closed);
+ expect(find.text('This terminal is disconnected'), findsOneWidget);
+ expect(find.widgetWithText(FilledButton, 'Reconnect'), findsOneWidget);
+ expect(find.textContaining('Session exited.'), findsOneWidget);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ expect(find.text('Reconnecting…'), findsOneWidget);
+ await finish(tester);
+ });
+
+ testWidgets('a shared read-only view ignores ⏎', (tester) async {
+ await pump(tester, readOnly: true);
+ takeOver();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opens(), isEmpty);
+ await finish(tester);
+ });
+
+ testWidgets('with the composer showing, the terminal still takes ⏎', (
+ tester,
+ ) async {
+ // The composer is disabled while the pane has no stream and refuses focus;
+ // the keyboard has to land on the terminal for ⏎ to mean anything.
+ await pump(tester, composerVisible: true);
+ takeOver();
+ await tester.pump();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ await finish(tester);
+ });
+
+ testWidgets('losing the stream pulls an idle keyboard into the tile', (
+ tester,
+ ) async {
+ // Nothing in the window held the keyboard (it had fallen back to the
+ // route's scope). The band promises ⏎, so the focused tile takes it.
+ await pump(tester);
+ FocusManager.instance.primaryFocus?.unfocus();
+ await tester.pump();
+ expect(FocusManager.instance.primaryFocus, isA<FocusScopeNode>());
+
+ takeOver();
+ await tester.pump();
+ await tester.pump();
+ expect(hint, findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ await finish(tester);
+ });
+
+ testWidgets('losing the stream never steals the keyboard from a field', (
+ tester,
+ ) async {
+ // Mid-word in the command dock, a rename box, anything: that stays put.
+ final elsewhere = FocusNode();
+ addTearDown(elsewhere.dispose);
+ await pump(tester, beside: TextField(focusNode: elsewhere));
+ elsewhere.requestFocus();
+ await tester.pump();
+ expect(elsewhere.hasFocus, isTrue);
+
+ takeOver();
+ await tester.pump();
+ await tester.pump();
+ expect(elsewhere.hasFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opens(), isEmpty);
+ await finish(tester);
+ });
+
+ testWidgets('clicking the band\'s text focuses the terminal for ⏎', (
+ 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.tap(takenOverTitle);
+ await tester.pump();
+ expect(elsewhere.hasFocus, isFalse);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opens(), ['terminal_open']);
+ await finish(tester);
+ });
+
+ testWidgets('a narrow tile stacks the button under the title', (
+ tester,
+ ) async {
+ await pump(tester, width: 240);
+ takeOver();
+ await tester.pump();
+ expect(takenOverTitle, findsOneWidget);
+ expect(banner, findsOneWidget);
+ expect(hint, findsOneWidget, reason: 'the hint stays, on one line');
+ expect(tester.takeException(), isNull);
+ final title = tester.getRect(takenOverTitle);
+ final button = tester.getRect(banner);
+ expect(button.top, greaterThanOrEqualTo(title.bottom));
+ await finish(tester);
+ });
+}
diff --git a/desktop/test/terminal_find_test.dart b/desktop/test/terminal_find_test.dart
index 0d13e4cc1..8f3ad9aa4 100644
--- a/desktop/test/terminal_find_test.dart
+++ b/desktop/test/terminal_find_test.dart
@@ -808,7 +808,9 @@ void main() {
await tester.pump();
expect(session.status, TerminalSessionStatus.takenOver);
expect(find.text('TERMINAL FROZEN'), findsNothing);
- expect(find.text('Take control'), findsOneWidget);
+ // Header chip and the in-pane banner both offer it; neither typed anything.
+ expect(find.widgetWithText(TextButton, 'Take control'), findsOneWidget);
+ expect(find.widgetWithText(FilledButton, 'Take control'), findsOneWidget);
expect(input, isEmpty);
await tester.pumpWidget(const SizedBox());
app.dispose();
diff --git a/desktop/test/terminal_offline_view_test.dart b/desktop/test/terminal_offline_view_test.dart
index a546386b6..ba38ec8b7 100644
--- a/desktop/test/terminal_offline_view_test.dart
+++ b/desktop/test/terminal_offline_view_test.dart
@@ -78,7 +78,10 @@ void main() {
app.dismissError();
await tester.pump();
expect(terminalView(tester, session), same(view));
- expect(find.text('Reconnect'), findsOneWidget);
+ // Offered twice once the machine is back: the header chip and the
+ // in-pane banner over the retained output.
+ expect(find.widgetWithText(TextButton, 'Reconnect'), findsOneWidget);
+ expect(find.widgetWithText(FilledButton, 'Reconnect'), findsOneWidget);
expect(session.status, TerminalSessionStatus.error);
await tester.pumpWidget(const SizedBox());
selection.dispose();
diff --git a/desktop/test/terminal_panel_header_test.dart b/desktop/test/terminal_panel_header_test.dart
index 57a6ece89..3386ce60e 100644
--- a/desktop/test/terminal_panel_header_test.dart
+++ b/desktop/test/terminal_panel_header_test.dart
@@ -99,7 +99,9 @@ void main() {
session.status = status;
await pump(tester, session);
final nameRect = tester.getRect(find.text('Desktop'));
- final statusRect = tester.getRect(find.text(label));
+ final statusRect = tester.getRect(
+ find.widgetWithText(TextButton, label),
+ );
expect(statusRect.left, greaterThan(nameRect.right));
expect(statusRect.right, lessThan(projectRect.left));
expect(tester.getRect(project), projectRect);
diff --git a/desktop/test/terminal_panel_presentation_test.dart b/desktop/test/terminal_panel_presentation_test.dart
index d9ce2da45..a01535fc6 100644
--- a/desktop/test/terminal_panel_presentation_test.dart
+++ b/desktop/test/terminal_panel_presentation_test.dart
@@ -89,7 +89,12 @@ void main() {
session.status = TerminalSessionStatus.takenOver;
revision.value = 3;
await tester.pump();
- expect(find.text('Take control'), findsOneWidget);
+ expect(find.widgetWithText(TextButton, 'Take control'), findsOneWidget);
+ expect(
+ find.widgetWithText(FilledButton, 'Take control'),
+ findsOneWidget,
+ reason: 'the in-pane banner offers it too',
+ );
expect(
find.byTooltip(
'Read only: another app controls this terminal. Take control moves input ownership to this app.',