Files
pipelines/app/test/features/chat/shell/chat_shell_terminal_test.dart
T
alan c3458d8a7f Terminals: one active client per terminal; keystrokes skip the request queue
Several clients drawing one terminal (machine terminal or chat terminal
command) no longer interfere. The server tracks, per terminal, the
connections drawing it, most recently active first: the active client
(the opener, then whoever last typed or focused it) owns the PTY size and
is the only one whose emulator's automatic query answers reach the
process; other clients' answers are acknowledged and dropped, and their
sizes recorded but not applied. When the active connection closes the next
most recent client's size is applied.

Protocol (backwards compatible; all new fields optional):
- terminal_input / chat_shell_input: reply (emulator answer), cols/rows
  (the typist's size, applied before the input).
- terminal_resize / chat_shell_resize: activate (the client focused it).

Latency: PipelinesClient sends terminal_input, terminal_resize,
chat_shell_input and chat_shell_resize at once rather than behind the
previous request's reply. The server reads those onto a per-connection
terminal lane handled in order beside the ordinary request loop, and
terminal_open (up to 5 s waiting for su) now runs off the read loop.

Client: ChatShellTerminalSession routes what the emulator emits while
drawing output to onReply and reports focus through activate();
ChatShellInputPipe keeps answers and typing in separate requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:37:16 +00:00

371 lines
13 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),
);
}
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');
});
}