Merge branch 'main' into worktree-agent-a3f5466412d4c7d5d

This commit is contained in:
2026-11-26 01:58:57 +00:00
91 changed files with 10011 additions and 320 deletions
@@ -0,0 +1,102 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_bell.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_events.dart';
import 'terminal_view_harness.dart';
const _flash = ValueKey('terminal-bell-flash');
String _osc52(String text) =>
'\x1b]52;c;${base64.encode(utf8.encode(text))}\x07';
void main() {
testWidgets('a bell flashes the border briefly; the setting turns it off', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
expect(find.byKey(_flash), findsNothing);
await harness.write(tester, '\x07');
expect(find.byKey(_flash), findsOneWidget);
await tester.pump(chatShellBellFlash + const Duration(milliseconds: 16));
expect(find.byKey(_flash), findsNothing);
harness.layout.setBell(false);
await tester.pump();
await harness.write(tester, '\x07');
expect(find.byKey(_flash), findsNothing);
});
testWidgets('under reduced motion the bell border holds, then goes', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester, reduceMotion: true);
await harness.write(tester, '\x07');
final border =
tester.widget<DecoratedBox>(find.byKey(_flash)).decoration
as BoxDecoration;
expect((border.border! as Border).top.color.a, 1);
await tester.pump(chatShellBellFlash + const Duration(milliseconds: 16));
expect(find.byKey(_flash), findsNothing);
});
testWidgets('OSC 52 from live output sets the clipboard and says so', (
tester,
) async {
final copied = mockClipboard(tester);
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, _osc52('from vim'));
expect(copied, ['from vim']);
await tester.pump();
expect(find.text('Copied from terminal'), findsOneWidget);
await tester.pump(const Duration(seconds: 3));
await tester.pumpAndSettle();
// A read request (?) is ignored.
await harness.write(tester, '\x1b]52;c;?\x07');
expect(copied, ['from vim']);
});
testWidgets('old output drawn again (a replay) neither copies nor rings', (
tester,
) async {
final copied = mockClipboard(tester);
final harness = TerminalViewHarness();
await harness.pump(tester);
final output = 'old ${_osc52('stale')}\x07done';
harness.session.replay(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': 'running',
'started_at': 1,
'output': output,
'output_bytes': utf8.encode(output).length,
'terminal': true,
})!,
);
await tester.pumpAndSettle();
expect(copied, isEmpty);
expect(harness.session.events.bells.value, 0);
expect(find.byKey(_flash), findsNothing);
});
test('OSC 7 reports the folder as a path', () {
expect(
chatShellWorkingDirectoryPath('file://mac.local/Users/op/src%20x'),
'/Users/op/src x',
);
expect(chatShellWorkingDirectoryPath('file:///tmp'), '/tmp');
expect(chatShellWorkingDirectoryPath('https://example.com/a'), isNull);
expect(chatShellWorkingDirectoryPath('file://host'), '/');
final harness = TerminalViewHarness();
addTearDown(harness.session.dispose);
harness.terminal.write('\x1b]7;file://mac/Users/op/work\x1b\\');
expect(harness.session.events.workingDirectory.value, '/Users/op/work');
});
}
@@ -0,0 +1,127 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_cursor_blink.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_links.dart';
import 'package:xterm/xterm.dart';
import 'terminal_view_harness.dart';
const _phase = chatShellCursorBlinkPhase;
void main() {
bool shown(WidgetTester tester, TerminalViewHarness harness) =>
harness.view(tester).cursorBlinkVisible!.value;
testWidgets('a blinking DECSCUSR cursor blinks while focused and is steady '
'once unfocused, leaving no frames scheduled', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, '\x1b[5 q');
await harness.focus(tester);
expect(shown(tester, harness), isTrue);
await tester.pump(_phase + const Duration(milliseconds: 10));
expect(shown(tester, harness), isFalse);
await tester.pump(_phase);
expect(shown(tester, harness), isTrue);
// Output shows it again and restarts the phase.
await tester.pump(_phase);
expect(shown(tester, harness), isFalse);
await harness.write(tester, 'x');
expect(shown(tester, harness), isTrue);
// Unfocused: steady, and the ticker stopped.
harness.view(tester).focusNode!.unfocus();
await tester.pump();
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('a steady shape (even Ps) does not blink', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, '\x1b[2 q');
await harness.focus(tester);
await tester.pump(_phase * 3);
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('reduced motion keeps a blinking cursor steady', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester, reduceMotion: true);
await harness.write(tester, '\x1b[1 q');
await harness.focus(tester);
await tester.pump(_phase + const Duration(milliseconds: 10));
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('a selection clears when its rows are rewritten, the screen is '
'cleared or the program switches screens', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, 'keep this\r\nother\r\n');
final controller = harness.controller(tester);
final buffer = harness.terminal.buffer;
void select() => controller.setSelection(
buffer.createAnchor(0, 0),
buffer.createAnchor(4, 0),
);
select();
// Output elsewhere leaves it.
await harness.write(tester, 'more output\r\n');
expect(controller.selection, isNotNull);
// Rewriting the selected row clears it.
await harness.write(tester, '\x1b[1;1Hgone');
expect(controller.selection, isNull);
select();
await harness.write(tester, '\x1b[2J');
expect(controller.selection, isNull);
select();
await harness.write(tester, '\x1b[?1049h');
expect(controller.selection, isNull);
});
testWidgets('hovering a web or OSC 8 link shows a pointer and underlines '
'it; a click opens it as before', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'see https://example.com/a now\r\n'
'\x1b]8;;https://example.org/b\x1b\\docs\x1b]8;;\x1b\\ plain',
);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
addTearDown(mouse.removePointer);
await mouse.addPointer(location: harness.cellCentre(tester, 0, 0));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.text);
await mouse.moveTo(harness.cellCentre(tester, 8, 0));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.click);
// The OSC 8 link's text is not an address; its target is.
await mouse.moveTo(harness.cellCentre(tester, 1, 1));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.click);
await mouse.moveTo(harness.cellCentre(tester, 7, 1));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.text);
});
test('the link under a cell: OSC 8 first, then printed addresses', () {
final terminal = Terminal(maxLines: 50)..resize(20, 4);
terminal.write(
'\x1b]8;;https://example.org/long\x1b\\0123456789abcdefghijkl'
'\x1b]8;;\x1b\\ x https://e.com/q).',
);
final hyperlink = chatShellTerminalLinkAt(terminal, const CellOffset(5, 0));
expect(hyperlink!.uri.toString(), 'https://example.org/long');
// It wraps onto the next row.
expect(hyperlink.begin, const CellOffset(0, 0));
expect(hyperlink.end, const CellOffset(2, 1));
final printed = chatShellTerminalLinkAt(terminal, const CellOffset(6, 1));
expect(printed!.uri.toString(), 'https://e.com/q');
expect(printed.begin, const CellOffset(5, 1));
expect(printed.end, const CellOffset(20, 1));
});
}
@@ -0,0 +1,149 @@
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_search.dart';
import 'package:xterm/xterm.dart';
import 'terminal_view_harness.dart';
const _field = ValueKey('terminal-find-field');
String _count(WidgetTester tester) => tester
.widget<Text>(find.byKey(const ValueKey('terminal-find-count')))
.data!;
/// Opens the find bar with the platform's key.
Future<void> _openFind(WidgetTester tester) => isApple()
? chordKeys(tester, LogicalKeyboardKey.keyF, [LogicalKeyboardKey.metaLeft])
: chordKeys(tester, LogicalKeyboardKey.keyF, [
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.shiftLeft,
]);
void main() {
test('search joins wrapped rows, folds case unless asked and maps cells', () {
final terminal = Terminal(maxLines: 100)..resize(10, 4);
terminal.write('abc Needle\r\nxxxxxxxneedle NEEDLE\r\n中文needle');
final all = chatShellTerminalSearch(terminal.buffer, 'needle');
expect(all, hasLength(4));
// "Needle" fills the first row's last six cells.
expect(
all[0],
const ChatShellSearchMatch(CellOffset(4, 0), CellOffset(10, 0)),
);
// The second line wraps: its "needle" spans rows 1 and 2.
expect(
all[1],
const ChatShellSearchMatch(CellOffset(7, 1), CellOffset(3, 2)),
);
expect(all[2].begin, const CellOffset(4, 2));
// Wide characters take two cells each; the match starts after both.
expect(all[3].begin, const CellOffset(4, 3));
final exact = chatShellTerminalSearch(
terminal.buffer,
'needle',
caseSensitive: true,
);
expect(exact, hasLength(2));
expect(chatShellTerminalSearch(terminal.buffer, ''), isEmpty);
expect(
chatShellTerminalSearch(terminal.buffer, 'needle', limit: 2),
hasLength(2),
);
});
testWidgets('the find key opens the bar; matches are counted, highlighted '
'and scrolled to; Esc closes it and the terminal has the keys again', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'first needle\r\n'
'${List.filled(60, 'filler').join('\r\n')}\r\n'
'Needle two\r\n'
'last needle',
);
await harness.focus(tester);
await _openFind(tester);
expect(find.byKey(_field), findsOneWidget);
await tester.pump();
// The field has the keyboard, which the terminal held.
expect(
tester.widget<TextField>(find.byKey(_field)).focusNode!.hasFocus,
isTrue,
);
// The keys went to the find bar, not the shell.
expect(harness.typed, isEmpty);
await tester.enterText(find.byKey(_field), 'needle');
await tester.pump();
// Searching upwards: the current match is the last one.
expect(_count(tester), '3 of 3');
expect(harness.controller(tester).highlights, hasLength(3));
final bottom = harness.scroll(tester).maxScrollExtent;
expect(harness.scroll(tester).pixels, bottom);
// Next wraps to the first match, at the top of the scrollback.
await tester.tap(find.byKey(const ValueKey('terminal-find-next')));
await tester.pump();
expect(_count(tester), '1 of 3');
expect(harness.scroll(tester).pixels, lessThan(bottom));
// Shift+Enter goes back.
await chordKeys(tester, LogicalKeyboardKey.enter, [
LogicalKeyboardKey.shiftLeft,
]);
expect(_count(tester), '3 of 3');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(_count(tester), '1 of 3');
// Match case leaves out "Needle".
await tester.tap(find.byKey(const ValueKey('terminal-find-case')));
await tester.pump();
expect(_count(tester), '2 of 2');
await tester.enterText(find.byKey(_field), 'absent');
await tester.pump();
expect(_count(tester), 'No results');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.byKey(_field), findsNothing);
expect(harness.controller(tester).highlights, isEmpty);
expect(harness.view(tester).focusNode!.hasFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.keyX);
await tester.pump();
expect(harness.typed, 'x');
}, variant: desktops);
testWidgets(
'outside Apple platforms Ctrl+F stays the shell\'s',
(tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.focus(tester);
await chordKeys(tester, LogicalKeyboardKey.keyF, [
LogicalKeyboardKey.controlLeft,
]);
expect(find.byKey(_field), findsNothing);
expect(harness.typed, '\x06');
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
testWidgets(
'output after a search is found by the next step',
(tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, 'one match\r\n');
await harness.focus(tester);
await _openFind(tester);
await tester.enterText(find.byKey(_field), 'match');
await tester.pump();
expect(_count(tester), '1 of 1');
await harness.write(tester, 'two match\r\n');
await tester.tap(find.byKey(const ValueKey('terminal-find-next')));
await tester.pump();
expect(_count(tester), '2 of 2');
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
}
@@ -0,0 +1,112 @@
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'terminal_view_harness.dart';
void main() {
testWidgets('Cmd/Ctrl with =, - and 0 zoom a focused terminal; the size '
'is saved and the process is resized to the new cells', (tester) async {
final store = MemoryStore();
final harness = TerminalViewHarness(layout: TerminalLayout(store: store));
await harness.pump(tester);
await harness.focus(tester);
final base = harness.view(tester).textStyle.fontSize;
final cols = harness.terminal.viewWidth;
final command = commandKey();
await chordKeys(tester, LogicalKeyboardKey.equal, [command]);
await chordKeys(tester, LogicalKeyboardKey.equal, [command]);
expect(harness.layout.fontSize, base.roundToDouble() + 2);
expect(harness.view(tester).textStyle.fontSize, base.roundToDouble() + 2);
// Larger cells: fewer columns, through the normal resize path.
expect(harness.terminal.viewWidth, lessThan(cols));
expect(harness.sizes.last.$1, harness.terminal.viewWidth);
await tester.pump();
expect(jsonDecode(store.saved!)['font_size'], base.roundToDouble() + 2);
await chordKeys(tester, LogicalKeyboardKey.minus, [command]);
expect(harness.layout.fontSize, base.roundToDouble() + 1);
await chordKeys(tester, LogicalKeyboardKey.digit0, [command]);
expect(harness.layout.fontSize, isNull);
expect(harness.view(tester).textStyle.fontSize, base);
expect(harness.terminal.viewWidth, cols);
// None of it reached the shell.
expect(harness.typed, isEmpty);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.fontSize, isNull);
}, variant: desktops);
testWidgets(
'zooming stops at the size limits',
(tester) async {
final harness = TerminalViewHarness();
harness.layout.setFontSize(terminalFontSizeMax - 1);
await harness.pump(tester);
await harness.focus(tester);
for (var i = 0; i < 3; i++) {
await chordKeys(tester, LogicalKeyboardKey.equal, [commandKey()]);
}
expect(harness.layout.fontSize, terminalFontSizeMax);
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
testWidgets('Shift+PgUp/PgDn/Home/End scroll the scrollback locally; on the '
'alternate screen they reach the program', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
List.generate(200, (i) => 'line $i').join('\r\n'),
);
await harness.focus(tester);
final bottom = harness.scroll(tester).maxScrollExtent;
expect(harness.scroll(tester).pixels, bottom);
const shift = [LogicalKeyboardKey.shiftLeft];
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
final page = bottom - harness.scroll(tester).pixels;
expect(page, greaterThan(0));
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
expect(harness.scroll(tester).pixels, closeTo(bottom - 2 * page, 0.01));
await chordKeys(tester, LogicalKeyboardKey.pageDown, shift);
expect(harness.scroll(tester).pixels, closeTo(bottom - page, 0.01));
await chordKeys(tester, LogicalKeyboardKey.home, shift);
expect(harness.scroll(tester).pixels, 0);
await chordKeys(tester, LogicalKeyboardKey.end, shift);
expect(harness.scroll(tester).pixels, bottom);
expect(harness.typed, isEmpty);
// A full-screen program (less, vim) gets them.
await harness.write(tester, '\x1b[?1049h');
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
expect(harness.typed, '\x1b[5;2~');
}, variant: desktops);
testWidgets('the scrollback setting applies to new and open terminals', (
tester,
) async {
final harness = TerminalViewHarness();
expect(harness.layout.scrollback, terminalScrollbackDefault);
expect(harness.terminal.maxLines, 10000);
await harness.pump(tester);
await harness.write(
tester,
List.generate(1500, (i) => 'line $i').join('\r\n'),
);
expect(harness.terminal.buffer.height, 1500);
harness.layout.setScrollback(1000);
await tester.pump();
expect(harness.terminal.maxLines, 1000);
expect(harness.terminal.buffer.height, 1000);
// The newest lines are kept.
final buffer = harness.terminal.buffer;
expect(buffer.lines[buffer.height - 1].getText().trim(), 'line 1499');
expect(buffer.lines[0].getText().trim(), 'line 500');
await harness.write(tester, '\r\nmore');
expect(harness.terminal.buffer.height, 1000);
final next = TerminalViewHarness(layout: harness.layout);
addTearDown(next.session.dispose);
expect(next.terminal.maxLines, 1000);
});
}
@@ -0,0 +1,81 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'terminal_view_harness.dart';
Finder _item(String name) => find.byKey(ValueKey('terminal-menu-$name'));
bool _enabled(WidgetTester tester, String name) =>
tester.widget<PopupMenuItem<Object?>>(_item(name)).enabled;
void main() {
testWidgets('right-click offers Copy with a selection, Paste, Select all, '
'Clear scrollback and Find', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'${List.generate(40, (i) => 'old $i').join('\r\n')}\r\nhello world',
);
final copied = mockClipboard(tester, paste: 'pasted');
final screenTop =
harness.terminal.buffer.height - harness.terminal.viewHeight;
final last = harness.terminal.buffer.height - 1;
await harness.rightClick(tester, 2, last);
expect(_item('copy'), findsOneWidget);
expect(_enabled(tester, 'copy'), isFalse);
for (final name in ['paste', 'selectAll', 'clear', 'find']) {
expect(_item(name), findsOneWidget, reason: name);
}
// Paste types the clipboard into the process.
await tester.tap(_item('paste'));
await tester.pumpAndSettle();
expect(harness.typed, 'pasted');
// Select all takes the scrollback too; Copy copies it.
await harness.rightClick(tester, 2, last);
await tester.tap(_item('selectAll'));
await tester.pumpAndSettle();
final selection = harness.controller(tester).selection!.normalized;
expect(selection.begin.y, 0);
expect(selection.end.y, last);
await harness.rightClick(tester, 2, last);
expect(_enabled(tester, 'copy'), isTrue);
await tester.tap(_item('copy'));
await tester.pumpAndSettle();
expect(copied.single, startsWith('old 0\nold 1'));
expect(copied.single, contains('hello world'));
// Clear scrollback keeps only the screen.
expect(screenTop, greaterThan(0));
await harness.rightClick(tester, 2, last);
await tester.tap(_item('clear'));
await tester.pumpAndSettle();
expect(harness.terminal.buffer.height, harness.terminal.viewHeight);
// Find… opens the find bar.
await harness.rightClick(tester, 2, harness.terminal.viewHeight - 1);
await tester.tap(_item('find'));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('terminal-find-field')), findsOneWidget);
}, variant: desktops);
testWidgets('a program tracking the mouse gets the right button unless '
'Shift is held', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, r'$ ');
// X10/normal tracking with SGR coordinates.
await harness.write(tester, '\x1b[?1000h\x1b[?1006h');
await harness.rightClick(tester, 3, 0);
expect(_item('copy'), findsNothing);
expect(harness.typed, '\x1b[<2;4;1M\x1b[<2;4;1m');
await harness.rightClick(tester, 3, 0, shift: true);
expect(_item('copy'), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets('finished output offers no Paste', (tester) async {
final harness = TerminalViewHarness(live: false);
await harness.pump(tester);
await harness.rightClick(tester, 1, 0);
expect(_item('copy'), findsOneWidget);
expect(_item('paste'), findsNothing);
});
}
@@ -0,0 +1,191 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.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_run.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_view.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'package:xterm/xterm.dart';
/// A terminal layout saved in memory.
class MemoryStore implements TerminalLayoutStore {
String? saved;
@override
Future<String?> load() async => saved;
@override
Future<bool> save(String value) async {
saved = value;
return true;
}
}
/// One live terminal view filling an 800x500 app, with what it sends to the
/// process collected in [sent].
class TerminalViewHarness {
TerminalViewHarness({TerminalLayout? layout, bool live = true})
: layout = layout ?? TerminalLayout(store: MemoryStore()) {
session = ChatShellTerminalSession(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': live ? 'running' : 'exited',
'started_at': 1,
'output': '',
'output_bytes': 0,
'terminal': true,
'cols': 80,
'rows': 24,
})!,
onInput: sent.add,
onResize: (cols, rows) => sizes.add((cols, rows)),
layout: this.layout,
);
}
final TerminalLayout layout;
late final ChatShellTerminalSession session;
final List<String> sent = [];
final List<(int, int)> sizes = [];
Terminal get terminal => session.terminal;
String get typed => sent.join();
Future<void> pump(WidgetTester tester, {bool reduceMotion = false}) async {
tester.view.physicalSize = const Size(800, 500);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
addTearDown(session.dispose);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(disableAnimations: reduceMotion),
child: Scaffold(
body: ChatShellTerminalView(
session: session,
fill: true,
autofocus: true,
),
),
),
),
),
);
await tester.pump();
}
TerminalView view(WidgetTester tester) =>
tester.widget<TerminalView>(find.byType(TerminalView));
TerminalViewState viewState(WidgetTester tester) =>
tester.state<TerminalViewState>(find.byType(TerminalView));
TerminalController controller(WidgetTester tester) =>
view(tester).controller!;
ScrollPosition scroll(WidgetTester tester) =>
view(tester).scrollController!.position;
/// The global centre of buffer cell ([x], [y]).
Offset cellCentre(WidgetTester tester, int x, int y) {
final render = viewState(tester).renderTerminal;
final cell = render.cellSize;
return render.localToGlobal(
render.getOffset(CellOffset(x, y)) +
Offset(cell.width / 2, cell.height / 2),
);
}
/// Writes [text] as live output and lets the view redraw.
Future<void> write(WidgetTester tester, String text) async {
terminal.write(text);
await tester.pump();
}
/// Focuses the emulator.
Future<void> focus(WidgetTester tester) async {
final node = view(tester).focusNode!;
node.requestFocus();
await tester.pump();
}
/// Right-clicks buffer cell ([x], [y]) with a mouse, holding Shift when
/// [shift].
Future<void> rightClick(
WidgetTester tester,
int x,
int y, {
bool shift = false,
}) async {
if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
final gesture = await tester.startGesture(
cellCentre(tester, x, y),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await gesture.up();
if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
await tester.pumpAndSettle();
}
}
/// Presses [key] with [modifiers] held.
Future<void> chordKeys(
WidgetTester tester,
LogicalKeyboardKey key, [
List<LogicalKeyboardKey> modifiers = const [],
]) async {
for (final modifier in modifiers) {
await tester.sendKeyDownEvent(modifier);
}
await tester.sendKeyEvent(key);
for (final modifier in modifiers.reversed) {
await tester.sendKeyUpEvent(modifier);
}
await tester.pump();
}
/// The platform's command key: Cmd on Apple platforms, else Ctrl.
LogicalKeyboardKey commandKey() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS
? LogicalKeyboardKey.metaLeft
: LogicalKeyboardKey.controlLeft;
bool isApple() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
/// Collects what the app writes to the clipboard, answering reads with
/// [paste].
List<String> mockClipboard(WidgetTester tester, {String paste = ''}) {
final texts = <String>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
texts.add('${(call.arguments as Map)['text']}');
}
if (call.method == 'Clipboard.getData') return {'text': paste};
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
return texts;
}
/// Desktop platforms: a Mac and one that is not.
final desktops = TargetPlatformVariant({
TargetPlatform.macOS,
TargetPlatform.linux,
});
@@ -0,0 +1,100 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_terminal_section.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
class _Store implements TerminalLayoutStore {
String? saved;
@override
Future<String?> load() async => saved;
@override
Future<bool> save(String value) async {
saved = value;
return true;
}
}
void main() {
late _Store store;
late TerminalLayout layout;
setUp(() {
store = _Store();
layout = TerminalLayout(store: store);
});
Future<void> pump(WidgetTester tester) async {
tester.view.physicalSize = const Size(900, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: SettingsTerminalSection(layout: layout),
),
),
),
);
}
Map<String, dynamic> saved() =>
jsonDecode(store.saved!) as Map<String, dynamic>;
testWidgets('text size, scrollback and the visual bell are chosen in '
'Settings and saved with the layout', (tester) async {
await pump(tester);
expect(find.text('Text size'), findsOneWidget);
expect(find.text('Scrollback'), findsOneWidget);
await tester.tap(find.byType(DropdownMenu<double>));
await tester.pumpAndSettle();
await tester.tap(find.text('16 pt').last);
await tester.pumpAndSettle();
expect(layout.fontSize, 16);
expect(saved()['font_size'], 16);
await tester.tap(find.byType(DropdownMenu<int>));
await tester.pumpAndSettle();
await tester.tap(find.text('50k lines').last);
await tester.pumpAndSettle();
expect(layout.scrollback, 50000);
expect(saved()['scrollback'], 50000);
await tester.tap(find.byKey(const ValueKey('settings-terminal-bell')));
await tester.pumpAndSettle();
expect(layout.bell, isFalse);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.fontSize, 16);
expect(restored.scrollback, 50000);
expect(restored.bell, isFalse);
// Default text size clears it.
await tester.tap(find.byType(DropdownMenu<double>));
await tester.pumpAndSettle();
await tester.tap(find.text('Default').last);
await tester.pumpAndSettle();
expect(layout.fontSize, isNull);
expect(saved().containsKey('font_size'), isFalse);
});
testWidgets('a zoom from the keyboard shows in the menu at once', (
tester,
) async {
await pump(tester);
layout.setFontSize(17);
await tester.pump();
final menu = tester.widget<DropdownMenu<double>>(
find.byType(DropdownMenu<double>),
);
expect(menu.initialSelection, 17);
});
test('a saved scrollback outside the choices and sizes out of range are '
'not restored as they were', () async {
store.saved = jsonEncode({'scrollback': 7, 'font_size': 400});
await layout.restore();
expect(layout.scrollback, terminalScrollbackDefault);
expect(layout.fontSize, terminalFontSizeMax);
expect(layout.bell, isTrue);
});
}
@@ -28,6 +28,12 @@ class TerminalGateway implements ApiGateway {
/// where runs of invalid bytes became one shorter replacement character).
final Map<String, int> byteShift = {};
/// A terminal's state as the server's snapshot: when set, a read from
/// before [snapshotFrom] gets it (as of the output's end) instead of raw
/// output.
final Map<String, String> snapshots = {};
int snapshotFrom = 1 << 30;
@override
Stream<JsonMap> get frames => _frames.stream;
@@ -56,6 +62,19 @@ class TerminalGateway implements ApiGateway {
final text = output[id] ?? '';
final bytes = utf8.encode(text);
final start = after.clamp(0, bytes.length);
final snapshot = snapshots[id];
if (withOutput && snapshot != null && after < snapshotFrom) {
final end = bytes.length + (byteShift[id] ?? 0);
return {
...terminals[id]!,
'stream': stream,
'output': snapshot,
'output_start': end,
'output_end': end,
'output_snapshot': true,
if (window > 0) 'window': window,
};
}
return {
...terminals[id]!,
'stream': stream,
@@ -0,0 +1,149 @@
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';
/// What the server's emulator (internal/termstate) writes for a 40x8
/// terminal where a shell ran twelve commands and then nvim, which set
/// mouse, bracketed paste and application cursor/keypad modes on the
/// alternate screen.
const _snapshot =
'\x1bc\x1b[3J\x1b]2;nvim notes.txt\x07'
'\$ echo 1\r\n1\r\n\$ echo 2\r\n2\r\n\$ echo 3\r\n3\r\n\$ echo 4\r\n4\r\n'
'\$ echo 5\r\n5\r\n\$ echo 6\r\n6\r\n\$ echo 7\r\n7\r\n\$ echo 8\r\n8\r\n'
'\$ echo 9\r\n9\r\n\$ echo 10\r\n10\r\n\$ echo 11\r\n11\r\n'
'\$ echo 12\r\n12\r\n\$ nvim notes.txt\r\n'
'\x1b[8;1H\x1b[?1049h\x1b[1;1H\x1b[0;1;34mFRAME\x1b[2;1H\x1b[0mline two'
'\x1b[8;1H\x1b[0;7m-- INSERT --\x1b[2;9H\x1b[?1h\x1b=\x1b[?25l'
'\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[0m';
/// What nvim writes as it exits, then the shell.
const _exit =
'\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?1l\x1b>\x1b[?25h\x1b[?1049l'
'\$ ls\r\nnotes.txt\r\n\$ ';
/// The rows on screen (not the scrollback), trailing blanks trimmed.
List<String> rows(Terminal terminal) {
final buffer = terminal.buffer;
final top = buffer.height - terminal.viewHeight;
return [
for (var y = top; y < buffer.height; y++)
buffer.lines[y].getText().trimRight(),
];
}
void main() {
late TerminalGateway mac;
late TerminalHub hub;
setUp(() {
mac = TerminalGateway()..window = 1 << 18;
hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')]));
});
tearDown(() async {
hub.dispose();
await mac.close();
});
Future<void> settle() async {
for (var i = 0; i < 5; i++) {
await Future<void>.delayed(Duration.zero);
}
}
/// A terminal whose stream is longer than the server's tail.
void longTerminal(String raw) {
mac.add('term_a', text: raw);
mac.terminals['term_a']!['cols'] = 40;
mac.terminals['term_a']!['rows'] = 8;
}
void expectNvim(TerminalTab tab) {
final terminal = tab.session.terminal;
expect(terminal.isUsingAltBuffer, isTrue);
expect(rows(terminal), [
'FRAME',
'line two',
'',
'',
'',
'',
'',
'-- INSERT --',
]);
expect(terminal.buffer.cursorX, 8);
expect(terminal.buffer.cursorY, 1);
expect(terminal.mouseMode, MouseMode.upDownScrollDrag);
expect(terminal.mouseReportMode, MouseReportMode.sgr);
expect(terminal.bracketedPasteMode, isTrue);
expect(terminal.cursorKeysMode, isTrue);
expect(terminal.appKeypadMode, isTrue);
expect(terminal.cursorVisibleMode, isFalse);
expect(tab.title, 'nvim notes.txt');
}
void expectShellAfterExit(TerminalTab tab) {
final terminal = tab.session.terminal;
expect(terminal.isUsingAltBuffer, isFalse);
expect(rows(terminal), [
r'$ echo 11',
'11',
r'$ echo 12',
'12',
r'$ nvim notes.txt',
r'$ ls',
'notes.txt',
r'$',
]);
// The shell's history above the screen came back with it.
expect(terminal.buffer.lines[0].getText().trimRight(), r'$ echo 1');
expect(terminal.mouseMode, MouseMode.none);
expect(terminal.bracketedPasteMode, isFalse);
expect(terminal.cursorKeysMode, isFalse);
expect(terminal.cursorVisibleMode, isTrue);
}
test('a reload draws the snapshot: the program on the alternate screen, '
'its modes, and the shell underneath once it exits', () async {
longTerminal('x' * 3000);
mac.snapshots['term_a'] = _snapshot;
hub.activate();
await settle();
final tab = hub.tabs.single;
expect(mac.bodies('terminal_output').single['after'], isNull);
expect(tab.session.end, 3000);
expectNvim(tab);
// No "earlier output was dropped" line: the snapshot misses nothing.
expect(
tab.session.terminal.mainBuffer.lines[0].getText(),
isNot(contains('dropped')),
);
mac.write('term_a', _exit);
await settle();
expectShellAfterExit(tab);
});
test('after a gap the snapshot replaces what the tab drew, modes '
'included', () async {
longTerminal('stale\x1b[?1000h\x1b[?1049h');
hub.activate();
await settle();
final tab = hub.tabs.single;
expect(tab.session.terminal.mouseMode, MouseMode.upDownScroll);
final held = tab.session.end;
// The tab falls behind past the server's tail, which now starts later.
mac.write('term_a', 'y' * 5000, push: false);
mac.snapshots['term_a'] = _snapshot;
mac.snapshotFrom = held + 100;
final end = held + 5000;
mac.pushOutput('term_a', 'z', end, end: end + 1);
await settle();
expect(mac.bodies('terminal_output').last['after'], held);
expectNvim(tab);
mac.write('term_a', _exit);
await settle();
expectShellAfterExit(tab);
});
}
@@ -0,0 +1,90 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'terminal_app.dart';
import 'terminal_fixtures.dart';
const _dot = ValueKey('terminal-tab-bell');
void main() {
late TerminalGateway mac;
late TerminalHub hub;
late TerminalLayout layout;
setUp(() {
mac = TerminalGateway()
..add('term_a', cwd: '/Users/op/src', text: r'$ ')
..add('term_b', cwd: '/Users/op/docs', text: r'$ ');
layout = TerminalLayout(store: MemoryLayoutStore())..visible = true;
hub = TerminalHub(
TestMachines([machine('mac', mac, name: 'Mac')]),
layout: layout,
);
});
tearDown(() async {
hub.dispose();
await mac.close();
});
/// Lets a pushed frame arrive and draw.
Future<void> drain(WidgetTester tester) async {
for (var i = 0; i < 3; i++) {
await tester.pump(const Duration(milliseconds: 1));
}
}
Future<void> open(WidgetTester tester) async {
await pumpTerminalApp(tester, hub: hub, layout: layout);
await tester.pumpAndSettle();
expect(hub.tabs, hasLength(2));
expect(hub.selected!.info.id, 'term_a');
}
testWidgets('a bell in a tab that is not shown dots it until it is '
'selected; the shown tab only flashes', (tester) async {
final semantics = tester.ensureSemantics();
await open(tester);
mac.write('term_b', '\x07');
await drain(tester);
expect(find.byKey(_dot), findsOneWidget);
expect(find.bySemanticsLabel(RegExp(r'\bBell\b')), findsOneWidget);
semantics.dispose();
// The shown terminal flashes instead.
mac.write('term_a', '\x07');
await drain(tester);
expect(find.byKey(const ValueKey('terminal-bell-flash')), findsOneWidget);
expect(find.byKey(_dot), findsOneWidget);
await tester.tap(find.text('docs'));
await tester.pumpAndSettle();
expect(find.byKey(_dot), findsNothing);
// Hidden, every tab dots; turned off, none does.
layout.hide();
await tester.pumpAndSettle();
mac.write('term_b', '\x07');
await drain(tester);
expect(hub.tabs.last.bellUnseen, isTrue);
layout.show();
await tester.pumpAndSettle();
expect(hub.tabs.last.bellUnseen, isFalse);
layout.setBell(false);
mac.write('term_a', '\x07');
await tester.pumpAndSettle();
expect(hub.tabs.first.bellUnseen, isFalse);
});
testWidgets('a folder reported with OSC 7 names an untitled tab and its '
'tooltip; a shell title still wins', (tester) async {
await open(tester);
mac.write('term_a', '\x1b]7;file://mac/Users/op/src/app\x07');
await drain(tester);
expect(find.text('app'), findsOneWidget);
expect(hub.tabs.first.cwd, '/Users/op/src/app');
expect(find.byTooltip('Mac: /Users/op/src/app'), findsOneWidget);
mac.write('term_a', '\x1b]0;vim notes\x07');
await drain(tester);
expect(find.text('vim notes'), findsOneWidget);
expect(find.text('app'), findsNothing);
});
}