Files
pipelines/app/test/features/chat/shell/chat_shell_terminal_test.dart
T
2026-11-25 23:38:04 +00:00

474 lines
17 KiB
Dart

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_runs_controller.dart';
import 'package:xterm/xterm.dart';
import 'chat_shell_fixtures.dart';
void main() {
late ShellGateway gateway;
setUp(() => gateway = ShellGateway());
tearDown(() => gateway.close());
/// Everything sent to the process, joined in order.
String typed() => [
for (final body in gateway.bodies('chat_shell_input')) body['data'],
].join();
Future<void> openRunning(WidgetTester tester, {String output = ''}) async {
gateway.runs = [
shellRecord(
'run_t',
command: 'gh auth login',
terminal: true,
output: output,
),
];
await tester.pumpWidget(shellThread(gateway));
await tester.pump();
// Let the transcript settle at its end, so the card (under its day's
// date divider) is scrolled clear of the composer before it is tapped.
await tester.pump(const Duration(milliseconds: 500));
await tester.pump();
}
testWidgets(
'keys typed into a focused desktop terminal reach the process',
(tester) async {
await openRunning(tester, output: 'Paste your token: ');
expect(terminalText(tester), 'Paste your token:');
// A desktop has no soft-keyboard field: the terminal takes typing itself.
expect(find.byKey(const Key('chat-shell-terminal-field')), findsNothing);
await tester.tap(find.byType(TerminalView));
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyG);
await tester.sendKeyEvent(LogicalKeyboardKey.digit7);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyC);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(typed(), 'g7\x1b[A\x03');
// Cmd-V pastes the clipboard into the process.
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async =>
call.method == 'Clipboard.getData' ? {'text': 'tok'} : null,
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyV);
await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
for (var i = 0; i < 5; i++) {
await tester.pump(const Duration(milliseconds: 20));
}
expect(typed(), 'g7\x1b[A\x03tok');
// The chat composer leaves a paste into the terminal alone.
expect(find.text('tok'), findsNothing);
expect(find.byType(EditableText), findsWidgets);
await tester.pump(const Duration(milliseconds: 400));
expect(gateway.bodies('chat_shell_input').first['run_id'], 'run_t');
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
/// What the app wrote to the clipboard.
List<String> copied(WidgetTester tester) {
final texts = <String>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
texts.add('${(call.arguments as Map)['text']}');
}
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
return texts;
}
/// Selects the first [length] cells of the terminal's first line.
void select(WidgetTester tester, int length) {
final view = tester.widget<TerminalView>(find.byType(TerminalView));
final buffer = view.terminal.buffer;
view.controller!.setSelection(
buffer.createAnchor(0, 0),
buffer.createAnchor(length, 0),
);
}
Future<void> press(
WidgetTester tester,
LogicalKeyboardKey key, {
List<LogicalKeyboardKey> modifiers = const [],
String? character,
PhysicalKeyboardKey? physical,
}) async {
for (final modifier in modifiers) {
await tester.sendKeyDownEvent(modifier);
}
await tester.sendKeyDownEvent(
key,
character: character,
physicalKey: physical,
);
await tester.sendKeyUpEvent(key, physicalKey: physical);
for (final modifier in modifiers.reversed) {
await tester.sendKeyUpEvent(modifier);
}
await tester.pump();
}
testWidgets('the focused terminal sends xterm bytes for Alt, Ctrl and '
'modified keys, and the copy and paste keys still work', (tester) async {
await openRunning(tester, output: r'$ ');
await tester.tap(find.byType(TerminalView));
await tester.pump();
const alt = [LogicalKeyboardKey.altLeft];
const ctrl = [LogicalKeyboardKey.controlLeft];
const shift = [LogicalKeyboardKey.shiftLeft];
await press(tester, LogicalKeyboardKey.keyB, modifiers: alt);
await press(tester, LogicalKeyboardKey.keyF, modifiers: alt);
await press(tester, LogicalKeyboardKey.period, modifiers: alt);
await press(
tester,
LogicalKeyboardKey.keyB,
modifiers: [...alt, ...shift],
character: 'B',
);
await press(tester, LogicalKeyboardKey.backspace, modifiers: alt);
await press(tester, LogicalKeyboardKey.slash, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.bracketRight, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.arrowUp, modifiers: shift);
await press(tester, LogicalKeyboardKey.arrowLeft, modifiers: alt);
await press(tester, LogicalKeyboardKey.arrowRight, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.keyT, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.keyX);
expect(
typed(),
'\x1bb\x1bf\x1b.\x1bB\x1b\x7f\x1f\x1d'
'\x1b[1;2A\x1b[1;3D\x1b[1;5C\x14x',
);
// Application cursor keys from the process's own mode switch.
gateway.emitOutput('run_t', '\x1b[?1h', 2);
await tester.pump();
gateway.calls.clear();
await press(tester, LogicalKeyboardKey.arrowUp);
expect(typed(), '\x1bOA');
// Ctrl-V is still paste, not ^V.
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async =>
call.method == 'Clipboard.getData' ? {'text': 'tok'} : null,
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
await press(tester, LogicalKeyboardKey.keyV, modifiers: ctrl);
for (var i = 0; i < 5; i++) {
await tester.pump(const Duration(milliseconds: 20));
}
expect(typed(), '\x1bOAtok');
await tester.pump(const Duration(milliseconds: 400));
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets(
'on a Mac, Option is Meta in the terminal',
(tester) async {
await openRunning(tester, output: r'$ ');
await tester.tap(find.byType(TerminalView));
await tester.pump();
await press(
tester,
LogicalKeyboardKey.keyB,
modifiers: [LogicalKeyboardKey.altLeft],
character: '∫',
);
await press(
tester,
const LogicalKeyboardKey(0x2202),
modifiers: [LogicalKeyboardKey.altLeft],
character: '∂',
physical: PhysicalKeyboardKey.keyD,
);
expect(typed(), '\x1bb\x1bd');
await tester.pump(const Duration(milliseconds: 400));
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets('on Linux, Ctrl-C copies a selection and interrupts without one; '
'Ctrl-Insert copies too', (tester) async {
await openRunning(tester, output: 'Paste your token: ');
final texts = copied(tester);
await tester.tap(find.byType(TerminalView));
await tester.pump();
Future<void> ctrl(LogicalKeyboardKey key) async {
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(key);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
}
select(tester, 5);
await ctrl(LogicalKeyboardKey.keyC);
expect(texts, ['Paste']);
// The process was not interrupted, and the selection is gone.
expect(typed(), isEmpty);
final view = tester.widget<TerminalView>(find.byType(TerminalView));
expect(view.controller!.selection, isNull);
// With nothing selected Ctrl-C is the process's again.
await ctrl(LogicalKeyboardKey.keyC);
expect(typed(), '\x03');
expect(texts, ['Paste']);
select(tester, 10);
await ctrl(LogicalKeyboardKey.insert);
expect(texts, ['Paste', 'Paste your']);
await tester.pump(const Duration(milliseconds: 400));
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets(
"a finished run's output copies its selection by key",
(tester) async {
gateway.runs = [
shellRecord(
'run_done',
command: 'echo done',
terminal: true,
output: 'all done here\r\n',
status: 'exited',
exitCode: 0,
),
];
await tester.pumpWidget(shellThread(gateway));
await tester.pump();
final texts = copied(tester);
await tester.tap(find.byType(TerminalView));
await tester.pump();
select(tester, 8);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyC);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(texts, ['all done']);
await tester.pump(const Duration(milliseconds: 400));
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
testWidgets('Paste types the clipboard text into the process', (
tester,
) async {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async => call.method == 'Clipboard.getData'
? {'text': 'gho_pasted-token'}
: null,
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
await openRunning(tester);
await tester.tap(find.byKey(const Key('chat-shell-key-paste')));
await tester.pump();
await tester.tap(find.byKey(const Key('chat-shell-key-enter')));
await tester.pump();
expect(typed(), 'gho_pasted-token\r');
});
testWidgets('the touch key toolbar and field type into the process', (
tester,
) async {
await openRunning(tester, output: 'Password: ');
for (final key in ['ctrl-c', 'tab', 'esc', 'left', 'down', 'right']) {
await tester.tap(find.byKey(Key('chat-shell-key-$key')));
await tester.pump();
}
expect(typed(), '\x03\t\x1b\x1b[D\x1b[B\x1b[C');
gateway.calls.clear();
final field = find.byKey(const Key('chat-shell-terminal-field'));
expect(field, findsOneWidget);
await tester.tap(find.byKey(const Key('chat-shell-terminal-hide')));
await tester.pump();
expect(tester.widget<TextField>(field).obscureText, isTrue);
await tester.enterText(field, 'hunter2');
await tester.testTextInput.receiveAction(TextInputAction.send);
await tester.pump();
expect(typed(), 'hunter2\r');
// The field forgets the text once it is sent.
expect(tester.widget<TextField>(field).controller!.text, isEmpty);
});
testWidgets(
'tapping the terminal on a phone opens the keyboard and typing reaches '
'the process',
(tester) async {
await openRunning(tester, output: 'Paste your token: ');
expect(tester.testTextInput.isVisible, isFalse);
await tester.tap(find.byType(TerminalView));
await tester.pump();
expect(tester.testTextInput.isVisible, isTrue);
expect(tester.testTextInput.hasAnyClients, isTrue);
gateway.calls.clear();
tester.testTextInput.enterText('tok');
await tester.pump();
await tester.testTextInput.receiveAction(TextInputAction.newline);
await tester.pump();
expect(typed(), startsWith('tok'));
// Close the keyboard connection before the tree goes away.
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump(const Duration(seconds: 1));
},
variant: TargetPlatformVariant.only(TargetPlatform.android),
);
testWidgets('a running terminal is resized to its view; a finished one is '
'read-only', (tester) async {
await openRunning(tester, output: 'working\r\n');
await tester.pump(const Duration(milliseconds: 200));
final resize = gateway.bodies('chat_shell_resize');
expect(resize, hasLength(1));
expect(resize.single['run_id'], 'run_t');
expect(resize.single['rows'], 12);
expect(resize.single['cols'], greaterThan(20));
gateway.emitRun(
shellRecord(
'run_t',
command: 'gh auth login',
status: 'exited',
exitCode: 0,
terminal: true,
output: 'working\r\n',
),
);
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-shell-key-enter')), findsNothing);
expect(
tester.widget<TerminalView>(find.byType(TerminalView)).readOnly,
isTrue,
);
expect(terminalText(tester), 'working');
gateway.calls.clear();
await tester.tap(find.byType(TerminalView));
await tester.sendKeyEvent(LogicalKeyboardKey.keyA);
await tester.pump(const Duration(milliseconds: 400));
expect(gateway.bodies('chat_shell_input'), isEmpty);
});
testWidgets('focusing the terminal claims it at its size; typing carries '
'the size and query answers are marked', (tester) async {
await openRunning(tester, output: 'size? \x1b[6n');
await tester.pump(const Duration(milliseconds: 200));
final laidOut = gateway.bodies('chat_shell_resize').single;
// The replayed query is not answered; nothing was claimed yet.
expect(gateway.bodies('chat_shell_input'), isEmpty);
await tester.tap(find.byType(TerminalView));
await tester.pump();
final claim = gateway.bodies('chat_shell_resize').last;
expect(claim['activate'], isTrue);
expect((claim['cols'], claim['rows']), (laidOut['cols'], laidOut['rows']));
// Typing carries this client's size.
await tester.sendKeyEvent(LogicalKeyboardKey.keyG);
await tester.pump();
var inputs = gateway.bodies('chat_shell_input');
expect(inputs.single['data'], 'g');
expect(inputs.single['reply'], isNull);
expect(
(inputs.single['cols'], inputs.single['rows']),
(laidOut['cols'], laidOut['rows']),
);
// A live query is answered with the answer marked, without a size.
gateway.emitOutput('run_t', '\x1b[6n', 'size? \x1b[6n'.length);
await tester.pump();
await tester.pump();
inputs = gateway.bodies('chat_shell_input');
expect(inputs.last['data'], '\x1b[1;7R');
expect(inputs.last['reply'], isTrue);
expect(inputs.last['cols'], isNull);
// Focusing again after the focus left claims again.
FocusManager.instance.primaryFocus?.unfocus();
await tester.pump();
await tester.tap(find.byType(TerminalView));
await tester.pump();
expect(
gateway.bodies('chat_shell_resize').where((b) => b['activate'] == true),
hasLength(2),
);
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets('coloured output is drawn without its escape codes', (
tester,
) async {
gateway.runs = [
shellRecord(
'run_c',
status: 'exited',
exitCode: 0,
terminal: true,
output: '\x1b[1;31merror\x1b[0m: bad\r\n10%\r100%\r\n',
),
];
await tester.pumpWidget(shellThread(gateway));
await tester.pumpAndSettle();
expect(terminalText(tester), 'error: bad\n100%');
final buffer = tester
.widget<TerminalView>(find.byType(TerminalView))
.terminal
.buffer;
// The red foreground survives as a cell attribute.
expect(
buffer.lines[0].getForeground(0),
isNot(buffer.lines[0].getForeground(7)),
);
});
test('a reconnect resumes the running output from its offset', () async {
gateway.runs = [shellRecord('run_t', terminal: true, output: 'one\r\n')];
final controller = ChatShellRunsController(gateway, 's');
addTearDown(controller.dispose);
await controller.refresh();
final session = controller.terminals.session(controller.run('run_t')!);
expect(session.end, 5);
gateway.runs = [
shellRecord('run_t', terminal: true, output: 'one\r\ntwo\r\n'),
];
gateway.resumeReply = shellRecord(
'run_t',
terminal: true,
output: 'two\r\n',
outputStart: 5,
);
await controller.refresh();
await Future<void>.delayed(Duration.zero);
final resume = gateway.bodies('chat_shell_run_output').single;
expect(resume['after'], 5);
expect(controller.run('run_t')!.output, 'one\r\ntwo\r\n');
expect(controller.run('run_t')!.gap, isFalse);
expect(session.end, 10);
expect(session.terminal.buffer.lines[1].getText().trimRight(), 'two');
});
}