From e79a120ac7d9a010c733c7d45ede7e04c0b6e07a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 9 Nov 2026 21:55:29 +0000 Subject: [PATCH] Terminal surface: lazy activation, settings mode choice, open in terminal, tests --- app/lib/features/terminal/terminal_float.dart | 4 + app/lib/features/terminal/terminal_hub.dart | 23 +- app/lib/features/terminal/terminal_panel.dart | 7 +- .../features/terminal/terminal_surface.dart | 9 + .../features/terminal/terminal_fixtures.dart | 151 +++++++++++ .../features/terminal/terminal_hub_test.dart | 193 ++++++++++++++ .../terminal/terminal_surface_test.dart | 252 ++++++++++++++++++ 7 files changed, 633 insertions(+), 6 deletions(-) create mode 100644 app/test/features/terminal/terminal_fixtures.dart create mode 100644 app/test/features/terminal/terminal_hub_test.dart create mode 100644 app/test/features/terminal/terminal_surface_test.dart diff --git a/app/lib/features/terminal/terminal_float.dart b/app/lib/features/terminal/terminal_float.dart index 7dd64e9b..1d7cfd37 100644 --- a/app/lib/features/terminal/terminal_float.dart +++ b/app/lib/features/terminal/terminal_float.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:flutter/cupertino.dart'; +import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'terminal_body.dart'; @@ -153,6 +154,8 @@ class TerminalFloat extends StatelessWidget { child: GestureDetector( key: const ValueKey('terminal-float-title'), behavior: HitTestBehavior.opaque, + // The window follows the pointer from where it went down. + dragStartBehavior: DragStartBehavior.down, onPanUpdate: (details) => _move(details.delta), onPanEnd: (_) => unawaited(layout.save()), onDoubleTap: () => layout.setMaximized(!layout.maximized), @@ -212,6 +215,7 @@ class TerminalFloat extends StatelessWidget { child: GestureDetector( key: const ValueKey('terminal-float-resize'), behavior: HitTestBehavior.opaque, + dragStartBehavior: DragStartBehavior.down, onPanUpdate: (details) => _resize(details.delta), onPanEnd: (_) => unawaited(layout.save()), child: Padding( diff --git a/app/lib/features/terminal/terminal_hub.dart b/app/lib/features/terminal/terminal_hub.dart index 0a42753f..32f41efc 100644 --- a/app/lib/features/terminal/terminal_hub.dart +++ b/app/lib/features/terminal/terminal_hub.dart @@ -16,13 +16,11 @@ import 'terminal_tab.dart'; /// restart) its terminals are listed, new ones get a tab, and every tab /// resumes its output from the last byte it holds. class TerminalHub extends ChangeNotifier { - TerminalHub(this.machines) { - machines.addListener(_machinesChanged); - _machinesChanged(); - } + TerminalHub(this.machines); final TerminalMachines machines; final Map _links = {}; + bool _active = false; final List _tabs = []; String? _selected; bool _disposed = false; @@ -43,6 +41,20 @@ class TerminalHub extends ChangeNotifier { connected.length > 1 || _tabs.map((tab) => tab.machineId).toSet().length > 1; + /// Starts following the machines: their terminals are listed now and on + /// every reconnect. The surface calls it the first time the terminal is + /// shown, so an app that never shows it sends no terminal requests (each + /// connection sends one request at a time; the first screen's read goes + /// first). + void activate() { + if (_active || _disposed) return; + _active = true; + machines.addListener(_machinesChanged); + _machinesChanged(); + } + + bool get active => _active; + void select(TerminalTab tab) { if (_selected == tab.key) return; _selected = tab.key; @@ -56,6 +68,7 @@ class TerminalHub extends ChangeNotifier { /// Opens a shell on [machineId] (the first connected machine when null) /// in [cwd] (home when empty) and selects its tab. Returns the refusal. Future open({String? machineId, String cwd = ''}) async { + activate(); final machine = machineId == null ? connected.firstOrNull : machineFor(machineId); @@ -209,7 +222,7 @@ class TerminalHub extends ChangeNotifier { @override void dispose() { _disposed = true; - machines.removeListener(_machinesChanged); + if (_active) machines.removeListener(_machinesChanged); for (final link in _links.values) { link.cancel(); } diff --git a/app/lib/features/terminal/terminal_panel.dart b/app/lib/features/terminal/terminal_panel.dart index 68486520..5cf17548 100644 --- a/app/lib/features/terminal/terminal_panel.dart +++ b/app/lib/features/terminal/terminal_panel.dart @@ -62,6 +62,9 @@ class _TerminalPanelState extends State { save: save, ); + String _describe(double height) => + '${terminalPanelHeight(height, widget.available).round()} pixels'; + KeyEventResult _key(FocusNode _, KeyEvent event) { if (event is! KeyDownEvent && event is! KeyRepeatEvent) { return KeyEventResult.ignored; @@ -84,7 +87,9 @@ class _TerminalPanelState extends State { label: 'Terminal height', hint: 'Drag, or use the arrow keys, to resize the terminal', slider: true, - value: '${height.round()} pixels', + value: _describe(height), + increasedValue: _describe(height + terminalPanelKeyStep), + decreasedValue: _describe(height - terminalPanelKeyStep), onIncrease: () => _resize(height + terminalPanelKeyStep), onDecrease: () => _resize(height - terminalPanelKeyStep), child: Focus( diff --git a/app/lib/features/terminal/terminal_surface.dart b/app/lib/features/terminal/terminal_surface.dart index 46ef1628..10d78e95 100644 --- a/app/lib/features/terminal/terminal_surface.dart +++ b/app/lib/features/terminal/terminal_surface.dart @@ -55,14 +55,22 @@ class _TerminalSurfaceState extends State void initState() { super.initState(); HardwareKeyboard.instance.addHandler(_key); + widget.layout.addListener(_layoutChanged); + // A terminal left shown before a reload reattaches at once. + WidgetsBinding.instance.addPostFrameCallback((_) => _layoutChanged()); } @override void dispose() { HardwareKeyboard.instance.removeHandler(_key); + widget.layout.removeListener(_layoutChanged); super.dispose(); } + void _layoutChanged() { + if (mounted && widget.layout.visible && !_narrow) widget.hub.activate(); + } + bool get _narrow => MediaQuery.sizeOf(context).width < terminalNarrowWidth; /// The shortcut is handled before the focused widget, so it toggles even @@ -98,6 +106,7 @@ class _TerminalSurfaceState extends State } Future _openPage() async { + widget.hub.activate(); if (_pageOpen) return; _pageOpen = true; try { diff --git a/app/test/features/terminal/terminal_fixtures.dart b/app/test/features/terminal/terminal_fixtures.dart new file mode 100644 index 00000000..4ff78fbf --- /dev/null +++ b/app/test/features/terminal/terminal_fixtures.dart @@ -0,0 +1,151 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/terminal/terminal_layout.dart'; +import 'package:pipelines_app/features/terminal/terminal_machines.dart'; + +/// One machine's terminals as a server holds them, answering the terminal +/// requests and pushing frames like the real one. +class TerminalGateway implements ApiGateway { + TerminalGateway({this.stream = 's1'}); + + final _frames = StreamController.broadcast(); + final List requests = []; + final Map terminals = {}; + final Map output = {}; + String stream; + int _next = 0; + + /// When set, requests of this type fail with this message. + final Map refuse = {}; + + @override + Stream get frames => _frames.stream; + + List bodies(String type) => [ + for (final request in requests) + if (request['type'] == type) + Map.from(request['terminal_request'] as Map? ?? {}), + ]; + + JsonMap add(String id, {String cwd = '/Users/op', String text = ''}) { + final record = { + 'id': id, + 'cwd': cwd, + 'shell': '/bin/zsh', + 'status': 'running', + 'tmux': 'pipelines-$id', + 'cols': 80, + 'rows': 24, + 'created_at': 1, + }; + terminals[id] = record; + output[id] = text; + return record; + } + + JsonMap _record(String id, {bool withOutput = false, int after = 0}) { + final text = output[id] ?? ''; + final bytes = utf8.encode(text); + final start = after.clamp(0, bytes.length); + return { + ...terminals[id]!, + 'stream': stream, + 'output_end': bytes.length, + if (withOutput) 'output': utf8.decode(bytes.sublist(start)), + if (withOutput) 'output_start': start, + }; + } + + /// The shell writes [text]: it is retained and pushed. + void write(String id, String text, {bool push = true}) { + final offset = utf8.encode(output[id] ?? '').length; + output[id] = (output[id] ?? '') + text; + if (push) { + pushOutput(id, text, offset); + } + } + + void pushOutput(String id, String text, int offset) => _frames.add({ + 'type': 'terminal_event', + 'terminal_event': { + 'terminal_id': id, + 'output': text, + 'offset': offset, + 'end': offset + utf8.encode(text).length, + }, + }); + + void lifecycle(String id, Map changes) { + terminals[id] = {...terminals[id]!, ...changes}; + _frames.add({ + 'type': 'terminal_event', + 'terminal_event': {'terminal_id': id, 'terminal': _record(id)}, + }); + } + + @override + Future call(String type, [JsonMap fields = const {}]) async { + requests.add({'type': type, ...fields}); + final refusal = refuse[type]; + if (refusal != null) throw StateError(refusal); + final body = (fields['terminal_request'] as Map?) ?? const {}; + final id = '${body['terminal_id'] ?? ''}'; + switch (type) { + case 'terminal_list': + return { + 'type': type, + 'terminals': [for (final id in terminals.keys) _record(id)], + }; + case 'terminal_open': + final next = 'term_${++_next}'; + final cwd = '${body['cwd'] ?? ''}'; + add(next, cwd: cwd.isEmpty ? '/Users/op' : cwd, text: r'$ '); + return {'type': type, 'terminal': _record(next)}; + case 'terminal_output': + return { + 'type': type, + 'terminal': _record( + id, + withOutput: true, + after: (body['after'] as num?)?.toInt() ?? 0, + ), + }; + case 'terminal_close': + final record = {..._record(id), 'status': 'closed'}; + terminals.remove(id); + return {'type': type, 'terminal': record}; + case 'terminal_input': + return {'type': type}; + case 'terminal_resize': + return {'type': type, 'terminal': _record(id)}; + } + throw StateError('unexpected $type'); + } + + Future close() => _frames.close(); +} + +/// A machine list tests change by hand. +class TestMachines extends ValueNotifier> { + TestMachines(super.value); +} + +TerminalMachine machine(String id, TerminalGateway gateway, {String? name}) => + TerminalMachine(id: id, name: name ?? id, gateway: gateway); + +/// A layout store kept in memory. +class MemoryLayoutStore implements TerminalLayoutStore { + String? saved; + int saves = 0; + @override + Future load() async => saved; + @override + Future save(String value) async { + saved = value; + saves++; + return true; + } +} diff --git a/app/test/features/terminal/terminal_hub_test.dart b/app/test/features/terminal/terminal_hub_test.dart new file mode 100644 index 00000000..c855a06a --- /dev/null +++ b/app/test/features/terminal/terminal_hub_test.dart @@ -0,0 +1,193 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/terminal/terminal_hub.dart'; +import 'package:pipelines_app/features/terminal/terminal_tab.dart'; +import 'package:xterm/core.dart'; + +import 'terminal_fixtures.dart'; + +String screen(TerminalTab tab) { + final buffer = tab.session.terminal.buffer; + return [ + for (var y = 0; y < buffer.height; y++) + buffer.lines[y].getText().trimRight(), + ].where((line) => line.isNotEmpty).join('\n'); +} + +void main() { + late TerminalGateway mac; + late TestMachines machines; + late TerminalHub hub; + + setUp(() { + mac = TerminalGateway(); + machines = TestMachines([machine('mac', mac, name: 'Mac')]); + hub = TerminalHub(machines); + }); + tearDown(() async { + hub.dispose(); + await mac.close(); + }); + + Future settle() => Future.delayed(Duration.zero); + + test('nothing is requested until the terminal is first shown', () async { + mac.add('term_a', text: 'hello\r\n'); + await settle(); + expect(mac.requests, isEmpty); + hub.activate(); + await settle(); + await settle(); + expect(mac.requests.map((r) => r['type']), [ + 'terminal_list', + 'terminal_output', + ]); + expect(hub.tabs.single.title, '~'); + expect(screen(hub.tabs.single), 'hello'); + }); + + test('live output appends in order; a gap reads the tail again', () async { + mac.add('term_a', text: r'$ '); + hub.activate(); + await settle(); + await settle(); + final tab = hub.tabs.single; + mac.write('term_a', 'ls\r\nREADME\r\n'); + await settle(); + expect(screen(tab), '\$ ls\nREADME'); + // A frame the client missed: the next one starts after its end. + mac.write('term_a', 'missed\r\n', push: false); + mac.write('term_a', 'after\r\n'); + await settle(); + await settle(); + expect(screen(tab), '\$ ls\nREADME\nmissed\nafter'); + final reads = mac.bodies('terminal_output'); + expect(reads.last['after'], greaterThan(0)); + }); + + test('a reconnect resumes after the held end; a restarted server ' + '(new stream) is read again from its start', () async { + mac.add('term_a', text: 'one\r\n'); + hub.activate(); + await settle(); + await settle(); + final tab = hub.tabs.single; + machines.value = []; + await settle(); + expect(tab.connected, isFalse); + mac.write('term_a', 'two\r\n', push: false); + final again = TerminalGateway() + ..terminals.addAll(mac.terminals) + ..output.addAll(mac.output); + machines.value = [machine('mac', again, name: 'Mac')]; + await settle(); + await settle(); + expect(identical(hub.tabs.single, tab), isTrue); + expect(tab.connected, isTrue); + expect(again.bodies('terminal_output').single['after'], 5); + expect(screen(tab), 'one\ntwo'); + // The server restarted: the tmux client redrew the screen into a new + // stream starting at zero. + machines.value = []; + await settle(); + final restarted = TerminalGateway(stream: 's2') + ..terminals.addAll(mac.terminals) + ..output['term_a'] = 'one\r\ntwo\r\n\$ '; + machines.value = [machine('mac', restarted, name: 'Mac')]; + await settle(); + await settle(); + await settle(); + expect( + restarted.bodies('terminal_output').last.containsKey('after'), + isFalse, + ); + expect(screen(tab), 'one\ntwo\n\$'); + await again.close(); + await restarted.close(); + }); + + test('open selects a new tab; close removes it; another client\'s ' + 'terminal appears and its close removes it', () async { + expect(await hub.open(cwd: '/Users/op/src'), isNull); + await settle(); + expect(mac.bodies('terminal_open').single['cwd'], '/Users/op/src'); + final first = hub.selected!; + expect(first.title, 'src'); + expect(await hub.open(), isNull); + await settle(); + expect(hub.tabs, hasLength(2)); + expect(hub.selected, isNot(first)); + hub.select(first); + expect(hub.selected, first); + expect(await hub.close(first), isNull); + expect(hub.tabs, hasLength(1)); + mac.add('term_other'); + mac.lifecycle('term_other', {}); + await settle(); + await settle(); + expect(hub.tabs, hasLength(2)); + mac.lifecycle('term_other', {'status': 'closed'}); + await settle(); + expect(hub.tabs, hasLength(1)); + }); + + test( + 'the shell title wins over the folder; an ended terminal says why', + () async { + mac.add('term_a', text: '\x1b]0;vim notes.md\x07'); + hub.activate(); + await settle(); + await settle(); + final tab = hub.tabs.single; + expect(tab.title, 'vim notes.md'); + expect(tab.session.live, isTrue); + mac.lifecycle('term_a', { + 'status': 'exited', + 'reason': + 'The Pipelines server restarted and this shell ended with it.', + }); + await settle(); + expect(tab.session.live, isFalse); + expect(tab.info.endedText, contains('ended with it')); + }, + ); + + test('typed input and the laid-out size go to the server', () async { + mac.add('term_a'); + hub.activate(); + await settle(); + await settle(); + final tab = hub.tabs.single; + tab.session.terminal.textInput('ls'); + tab.session.terminal.keyInput(TerminalKey.enter); + await settle(); + expect( + mac.bodies('terminal_input').map((body) => body['data']).join(), + 'ls\r', + ); + }); + + test('several machines: New terminal opens on the chosen one, tabs name ' + 'their machine', () async { + final linux = TerminalGateway(); + machines.value = [ + machine('mac', mac, name: 'Mac'), + machine('linux', linux, name: 'Linux'), + ]; + hub.activate(); + await settle(); + expect(hub.multiMachine, isTrue); + expect(await hub.open(machineId: 'linux'), isNull); + expect(linux.bodies('terminal_open'), hasLength(1)); + expect(mac.bodies('terminal_open'), isEmpty); + expect(hub.selected!.machineName, 'Linux'); + expect(await hub.open(machineId: 'gone'), contains('No machine')); + await linux.close(); + }); + + test('a refused open is kept for the surface to show', () async { + mac.refuse['terminal_open'] = 'this machine already has 8 open terminals'; + expect(await hub.open(), contains('8 open terminals')); + expect(hub.error, contains('8 open terminals')); + expect(hub.tabs, isEmpty); + }); +} diff --git a/app/test/features/terminal/terminal_surface_test.dart b/app/test/features/terminal/terminal_surface_test.dart new file mode 100644 index 00000000..b4b55b52 --- /dev/null +++ b/app/test/features/terminal/terminal_surface_test.dart @@ -0,0 +1,252 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_keys.dart'; +import 'package:pipelines_app/features/settings/settings_terminal_section.dart'; +import 'package:pipelines_app/features/terminal/terminal_float.dart'; +import 'package:pipelines_app/features/terminal/terminal_hub.dart'; +import 'package:pipelines_app/features/terminal/terminal_layout.dart'; +import 'package:pipelines_app/features/terminal/terminal_surface.dart'; +import 'package:pipelines_app/features/terminal/terminal_toggle_button.dart'; +import 'package:xterm/xterm.dart'; + +import 'terminal_fixtures.dart'; + +void main() { + late TerminalGateway mac; + late TerminalHub hub; + late MemoryLayoutStore store; + late TerminalLayout layout; + + setUp(() { + mac = TerminalGateway() + ..add('term_a', cwd: '/Users/op/src', text: 'alpha\r\n') + ..add('term_b', cwd: '/Users/op/docs', text: 'beta\r\n'); + hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')])); + store = MemoryLayoutStore(); + layout = TerminalLayout(store: store); + }); + tearDown(() async { + hub.dispose(); + await mac.close(); + }); + + Future pumpApp( + WidgetTester tester, { + Size size = const Size(1200, 800), + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + home: TerminalSurface( + hub: hub, + layout: layout, + cupertino: false, + child: Scaffold( + appBar: AppBar( + title: const Text('App'), + actions: [TerminalToggleButton(layout: layout, cupertino: false)], + ), + body: const TextField(key: Key('app-field')), + ), + ), + ), + ); + await tester.pump(); + } + + Future ctrlBacktick(WidgetTester tester) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.backquote); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); + } + + Map saved() => + jsonDecode(store.saved!) as Map; + + testWidgets('Ctrl+` and the bar button toggle the bottom panel; hiding ' + 'keeps every shell', (tester) async { + await pumpApp(tester); + expect(find.byKey(const ValueKey('terminal-panel')), findsNothing); + await ctrlBacktick(tester); + expect(find.byKey(const ValueKey('terminal-panel')), findsOneWidget); + expect(find.text('src'), findsOneWidget); + expect(find.text('docs'), findsOneWidget); + expect(saved()['visible'], isTrue); + // The terminal has the keyboard, yet the shortcut still hides it. + await tester.tap(find.byType(TerminalView)); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyX); + await tester.pump(); + expect(mac.bodies('terminal_input').last['data'], 'x'); + await ctrlBacktick(tester); + expect(find.byKey(const ValueKey('terminal-panel')), findsNothing); + expect(hub.tabs, hasLength(2)); + expect(mac.bodies('terminal_close'), isEmpty); + await tester.tap(find.byTooltip(TerminalToggleButton.label)); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('terminal-panel')), findsOneWidget); + // Reopening draws the same emulator, output and all. + expect(find.byType(TerminalView), findsOneWidget); + }); + + testWidgets('the panel resizes from its top edge and remembers its height', ( + tester, + ) async { + await pumpApp(tester); + await ctrlBacktick(tester); + final before = tester + .getSize(find.byKey(const ValueKey('terminal-panel'))) + .height; + expect(before, terminalPanelDefaultHeight); + await tester.drag( + find.byKey(const ValueKey('terminal-panel-resize')), + const Offset(0, -120), + ); + await tester.pumpAndSettle(); + final after = tester + .getSize(find.byKey(const ValueKey('terminal-panel'))) + .height; + expect(after, closeTo(before + 120, 1)); + expect(saved()['panel_height'], closeTo(after, 1)); + // The app above shrinks rather than hiding under it. + final field = tester.getRect(find.byType(Scaffold).first); + expect(field.bottom, closeTo(800 - after, 1)); + final restored = TerminalLayout(store: store); + await restored.restore(); + expect(restored.panelHeight, closeTo(after, 1)); + expect(restored.visible, isTrue); + // The resized terminal tells the server its new size. + await tester.pump(const Duration(milliseconds: 200)); + expect(mac.bodies('terminal_resize'), isNotEmpty); + }); + + testWidgets('the floating window moves, resizes, minimises and maximises', ( + tester, + ) async { + layout + ..setMode(TerminalMode.float) + ..show(); + await pumpApp(tester); + await tester.pump(); + final window = find.byKey(const ValueKey('terminal-float')); + expect(window, findsOneWidget); + final start = layout.floatRect; + await tester.drag( + find.byKey(const ValueKey('terminal-float-title')), + const Offset(60, 40), + ); + await tester.pumpAndSettle(); + expect(layout.floatRect.topLeft, start.topLeft + const Offset(60, 40)); + await tester.drag( + find.byKey(const ValueKey('terminal-float-resize')), + const Offset(80, 50), + ); + await tester.pumpAndSettle(); + expect(layout.floatRect.size, start.size + const Offset(80, 50)); + expect(saved()['float'][2], closeTo(start.width + 80, 1)); + await tester.tap(find.byTooltip('Minimise')); + await tester.pumpAndSettle(); + expect(find.byType(TerminalView), findsNothing); + expect(hub.tabs, hasLength(2)); + await tester.tap(find.byTooltip('Restore')); + await tester.pumpAndSettle(); + expect(find.byType(TerminalView), findsOneWidget); + await tester.tap(find.byTooltip('Maximise')); + await tester.pumpAndSettle(); + expect( + tester.getRect( + find.descendant(of: window, matching: find.byType(Material)).first, + ), + const Rect.fromLTWH(0, 0, 1200, 800).deflate(terminalFloatMargin), + ); + await tester.tap(find.byTooltip('Restore size')); + await tester.pumpAndSettle(); + expect(layout.maximized, isFalse); + }); + + testWidgets('tabs select and close their terminals; New terminal opens one', ( + tester, + ) async { + layout.show(); + await pumpApp(tester); + await tester.pumpAndSettle(); + expect(hub.selected!.info.id, 'term_a'); + await tester.tap(find.text('docs')); + await tester.pumpAndSettle(); + expect(hub.selected!.info.id, 'term_b'); + await tester.tap(find.byTooltip('New terminal')); + await tester.pumpAndSettle(); + expect(mac.bodies('terminal_open'), hasLength(1)); + expect(hub.tabs, hasLength(3)); + expect(hub.selected!.info.id, 'term_1'); + await tester.tap(find.byTooltip('Close terminal').first); + await tester.pumpAndSettle(); + expect(mac.bodies('terminal_close').single['terminal_id'], 'term_a'); + expect(find.text('src'), findsNothing); + }); + + testWidgets('the options menu switches between panel and window', ( + tester, + ) async { + layout.show(); + await pumpApp(tester); + await tester.tap(find.byTooltip('Terminal options')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('terminal-mode-float'))); + await tester.pumpAndSettle(); + expect(layout.mode, TerminalMode.float); + expect(find.byKey(const ValueKey('terminal-float')), findsOneWidget); + expect(find.byKey(const ValueKey('terminal-panel')), findsNothing); + expect(saved()['mode'], 'float'); + await tester.tap(find.byTooltip('Terminal options')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('terminal-hide'))); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('terminal-float')), findsNothing); + }); + + testWidgets('Settings chooses the mode', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: SettingsTerminalSection(layout: layout), + ), + ), + ), + ); + expect(find.text('Terminal'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('settings-terminal-float'))); + await tester.pumpAndSettle(); + expect(layout.mode, TerminalMode.float); + await tester.tap(find.byKey(const ValueKey('settings-terminal-panel'))); + await tester.pumpAndSettle(); + expect(layout.mode, TerminalMode.panel); + }); + + testWidgets('a narrow window opens the terminal full screen with the key ' + 'toolbar', (tester) async { + layout.show(); + await pumpApp(tester, size: const Size(390, 800)); + // The panel is not drawn on a phone even when left shown. + expect(find.byKey(const ValueKey('terminal-panel')), findsNothing); + await tester.tap(find.byTooltip(TerminalToggleButton.label)); + await tester.pumpAndSettle(); + expect(find.widgetWithText(AppBar, 'Terminal'), findsOneWidget); + expect(find.byType(TerminalView), findsOneWidget); + expect(find.byType(ChatShellTerminalKeys), findsOneWidget); + await tester.tap(find.byKey(const Key('chat-shell-key-ctrl-c'))); + await tester.pump(); + expect(mac.bodies('terminal_input').last['data'], '\x03'); + await tester.pageBack(); + await tester.pumpAndSettle(); + expect(find.byType(TerminalView), findsNothing); + expect(hub.tabs, hasLength(2)); + }); +}