import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/core/transport/connection_state.dart'; import 'package:pipelines_app/features/chat/conversation/chat_background_tasks.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; import 'package:pipelines_app/features/chat/domain/chat_shells.dart'; /// A gateway that scripts the session snapshot and bounded output reads and can /// push a shell frame for the selected conversation. class _TasksGateway implements ApiGateway { final calls = <({String type, JsonMap fields})>[]; final _frames = StreamController.broadcast(); Future Function()? shells; Future Function(JsonMap fields)? output; @override Stream get frames => _frames.stream; @override Future call(String type, [JsonMap fields = const {}]) async { calls.add((type: type, fields: fields)); switch (type) { case 'chat_shells': return shells == null ? {'chat_shells': const []} : shells!(); case 'chat_shell_output': return output == null ? {'chat_shell_output': const {}} : output!(fields); case 'chat_subscribe': return {}; case 'chat_messages': return { 'chat_history': { 'messages': const [], 'next_cursor': '', 'has_more': false, }, }; } return {}; } List fieldsFor(String type) => [ for (final call in calls) if (call.type == type) call.fields, ]; void emitShell( String id, String status, { String command = '', String session = 's', }) => _frames.add({ 'type': 'chat_event', 'chat_event': { 'session_id': session, 'kind': 'shell', 'shell': {'id': id, 'status': status, 'command': command}, }, }); void close() => _frames.close(); } JsonMap _running(String id, {String command = 'go test ./...'}) => { 'id': id, 'status': 'running', 'command': command, }; JsonMap _snapshot(List shells) => {'chat_shells': shells}; /// A realistically long recorded page (200 shell lines, more than one screen). List _pageLines() => [ for (var index = 0; index < 200; index++) 'line $index', ]; Widget _host( _TasksGateway gateway, { bool cupertino = false, int syncToken = 0, }) { final child = ChatBackgroundTasks( gateway: gateway, sessionId: 's', syncToken: syncToken, ); if (cupertino) { return CupertinoApp( home: CupertinoPageScaffold(child: SingleChildScrollView(child: child)), ); } return MaterialApp( theme: ThemeData(platform: TargetPlatform.android), home: Scaffold(body: SingleChildScrollView(child: child)), ); } Widget _thread(_TasksGateway gateway) => MaterialApp( theme: ThemeData(platform: TargetPlatform.android), home: Scaffold( body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), ), ); Future _tapTask(WidgetTester tester, String id) async { await tester.tap(find.byKey(ValueKey('chat-bg-task-$id'))); await tester.pumpAndSettle(); } void main() { testWidgets('shows only the session snapshot tasks that are still running', ( tester, ) async { final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([ _running('sh1'), {'id': 'sh2', 'status': 'exited', 'command': 'pnpm build'}, {'id': '', 'status': 'running', 'command': 'no identity'}, ]); addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); expect(find.text('Background tasks'), findsOneWidget); expect(find.text('1 running'), findsOneWidget); expect(find.text('Running'), findsOneWidget); expect(find.text('go test ./...'), findsOneWidget); expect(find.text('pnpm build'), findsNothing); expect(find.text('no identity'), findsNothing); expect(gateway.fieldsFor('chat_shells'), [ { 'chat_query': {'session_id': 's'}, }, ]); }); testWidgets('an honest empty snapshot draws no task surface', (tester) async { final gateway = _TasksGateway(); addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); expect(find.byKey(const Key('chat-background-tasks')), findsNothing); expect(find.text('Background tasks'), findsNothing); expect(gateway.fieldsFor('chat_shells'), hasLength(1)); }); testWidgets('pushed shell frames add and remove this session tasks', ( tester, ) async { final gateway = _TasksGateway(); addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); expect(find.text('Background tasks'), findsNothing); gateway.emitShell('sh1', 'running', command: 'tail -f server.log'); await tester.pumpAndSettle(); expect(find.text('Background tasks'), findsOneWidget); expect(find.text('1 running'), findsOneWidget); expect(find.text('tail -f server.log'), findsOneWidget); gateway.emitShell('sh1', 'exited'); await tester.pumpAndSettle(); expect(find.text('Background tasks'), findsNothing); gateway.emitShell('other', 'running', session: 'other-session'); await tester.pumpAndSettle(); expect(find.text('Background tasks'), findsNothing); }); testWidgets('more than three running tasks scroll inside the bar', ( tester, ) async { final gateway = _TasksGateway() ..shells = () async => _snapshot([ for (var index = 0; index < 4; index++) _running('sh$index'), ]); addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); expect(find.text('4 running'), findsOneWidget); expect(find.byKey(const Key('chat-bg-task-list')), findsOneWidget); expect( tester.getRect(find.byKey(const Key('chat-bg-task-list'))).height, lessThanOrEqualTo(kMinInteractiveDimension * backgroundTaskVisibleRows), ); for (var index = 0; index < 4; index++) { expect( find.byKey(ValueKey('chat-bg-task-sh$index')), findsOneWidget, ); } }); testWidgets('selecting a task reads one bounded session-linked page', ( tester, ) async { final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1')]); gateway.output = (fields) async => { 'chat_shell_output': { 'shell': _running('sh1'), 'output': 'ok example\n--- PASS: TestOne\n', 'cursor': 0, 'size': 8192, 'truncated': true, }, }; addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); await _tapTask(tester, 'sh1'); expect(gateway.fieldsFor('chat_shell_output'), [ { 'chat_shell_output_query': { 'session_id': 's', 'shell_id': 'sh1', 'cursor': 0, 'limit': chatShellOutputLimit, }, }, ]); expect(find.byKey(const Key('chat-bg-task-detail')), findsOneWidget); expect(find.text('Command'), findsOneWidget); expect(find.text('Task identity'), findsOneWidget); expect(find.text('sh1'), findsOneWidget); expect(find.text('Status: running'), findsOneWidget); expect(find.text('Output'), findsOneWidget); expect( tester .widget(find.byKey(const Key('chat-bg-task-output'))) .data, 'ok example\n--- PASS: TestOne\n', ); expect(find.text('Output is bounded to 64 KiB.'), findsOneWidget); expect(find.text('Refresh'), findsOneWidget); // Selecting the open task again closes its detail without another read. await _tapTask(tester, 'sh1'); expect(find.byKey(const Key('chat-bg-task-detail')), findsNothing); expect(gateway.fieldsFor('chat_shell_output'), hasLength(1)); }); testWidgets('the output pane reports empty, unavailable and a refusal', ( tester, ) async { final gateway = _TasksGateway() ..shells = () async => _snapshot([_running('sh1')]); addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); // A reply with no page at all is unavailable, not "No output yet.". gateway.output = (_) async => const {}; await _tapTask(tester, 'sh1'); expect(find.text('Output unavailable for this task.'), findsOneWidget); gateway.output = (_) async => { 'chat_shell_output': {'shell': _running('sh1')}, }; await _tapTask(tester, 'sh1'); await _tapTask(tester, 'sh1'); expect(find.text('No output yet.'), findsOneWidget); gateway.output = (_) async => { 'chat_shell_output': {'shell': _running('sh1'), 'unavailable': true}, }; await _tapTask(tester, 'sh1'); await _tapTask(tester, 'sh1'); expect(find.text('Output unavailable for this task.'), findsOneWidget); gateway.output = (_) async => throw ProtocolError('output refused'); await _tapTask(tester, 'sh1'); await _tapTask(tester, 'sh1'); expect(find.byKey(const Key('chat-bg-task-output-error')), findsOneWidget); expect(find.text('output refused'), findsOneWidget); expect(find.text('Retry'), findsOneWidget); gateway.output = (_) async => { 'chat_shell_output': {'shell': _running('sh1'), 'output': 'fresh output'}, }; await tester.tap(find.text('Retry')); await tester.pumpAndSettle(); expect(find.byKey(const Key('chat-bg-task-output-error')), findsNothing); expect( tester .widget(find.byKey(const Key('chat-bg-task-output'))) .data, 'fresh output', ); }); testWidgets('a refused snapshot is reported and Retry rereads it', ( tester, ) async { final gateway = _TasksGateway() ..shells = () async => throw ProtocolError('server down'); addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); expect( find.textContaining('Background tasks unavailable. server down'), findsOneWidget, ); expect(find.text('0 running'), findsNothing); gateway.shells = () async => _snapshot([_running('sh1')]); await tester.tap(find.text('Retry')); await tester.pumpAndSettle(); expect(find.byKey(const Key('chat-background-tasks-error')), findsNothing); expect(find.text('Background tasks'), findsOneWidget); expect(find.text('1 running'), findsOneWidget); expect(gateway.fieldsFor('chat_shells'), hasLength(2)); }); testWidgets('an exit closes the selected pane and the bar', (tester) async { final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1')]); gateway.output = (_) async => { 'chat_shell_output': { 'shell': _running('sh1'), 'output': 'still running', }, }; addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); await _tapTask(tester, 'sh1'); expect(find.byKey(const Key('chat-bg-task-detail')), findsOneWidget); gateway.emitShell('sh1', 'exited'); await tester.pumpAndSettle(); expect(find.byKey(const Key('chat-bg-task-detail')), findsNothing); expect(find.text('Background tasks'), findsNothing); }); testWidgets('a replaced socket drops held tasks and re-learns the snapshot', ( tester, ) async { final gateway = _TasksGateway() ..shells = () async => _snapshot([_running('sh1')]); addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); expect(find.text('1 running'), findsOneWidget); gateway.shells = () async => _snapshot(const []); await tester.pumpWidget(_host(gateway, syncToken: 1)); await tester.pumpAndSettle(); expect(find.text('Background tasks'), findsNothing); expect(gateway.fieldsFor('chat_shells'), hasLength(2)); }); testWidgets('the Cupertino host keeps native buttons and the same facts', ( tester, ) async { final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1')]); gateway.output = (_) async => { 'chat_shell_output': { 'shell': _running('sh1'), 'output': 'native output', }, }; addTearDown(gateway.close); await tester.pumpWidget(_host(gateway, cupertino: true)); await tester.pumpAndSettle(); expect(find.byType(CupertinoButton), findsWidgets); expect(find.text('1 running'), findsOneWidget); await _tapTask(tester, 'sh1'); expect(find.text('Command'), findsOneWidget); expect(find.text('Status: running'), findsOneWidget); expect( tester .widget(find.byKey(const Key('chat-bg-task-output'))) .data, 'native output', ); }); testWidgets('a long output page scrolls inside a bounded pane', ( tester, ) async { tester.view.physicalSize = const Size(400, 700); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); final lines = [for (var index = 0; index < 200; index++) 'line $index']; final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1')]); gateway.output = (_) async => { 'chat_shell_output': { 'shell': _running('sh1'), 'output': '${lines.join('\n')}\n', }, }; addTearDown(gateway.close); await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); await _tapTask(tester, 'sh1'); // A real shell tail is bounded: the transcript and composer stay in the // viewport instead of being pushed out by the whole page. expect(tester.takeException(), isNull); final outputFinder = find.byKey(const Key('chat-bg-task-output')); final output = tester.getRect(outputFinder); expect(output.height, lessThanOrEqualTo(210)); final detail = tester.getRect(find.byKey(const Key('chat-bg-task-detail'))); final composer = tester.getRect( find.byKey(const ValueKey('chat-composer-s')), ); expect(detail.bottom, lessThanOrEqualTo(composer.top)); expect(composer.bottom, lessThanOrEqualTo(700)); // The page scrolls through the host's own text control to its last line. expect( tester.widget(outputFinder).data, contains('line 199'), ); final scrollable = tester.state( find.descendant(of: outputFinder, matching: find.byType(Scrollable)), ); expect(scrollable.position.maxScrollExtent, greaterThan(0)); await tester.drag(outputFinder, const Offset(0, -300)); await tester.pumpAndSettle(); expect(scrollable.position.pixels, greaterThan(0)); }); testWidgets('three tasks and an open page fit a 320px phone', (tester) async { tester.view.physicalSize = const Size(320, 568); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1'), _running('sh2'), _running('sh3')]); gateway.output = (_) async => { 'chat_shell_output': { 'shell': _running('sh1'), 'output': '${_pageLines().join('\n')}\n', }, }; addTearDown(gateway.close); await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); await _tapTask(tester, 'sh1'); // Three rows plus the whole detail can no longer take the viewport: the bar // keeps its share, scrolls its own body, and the composer stays reachable. expect(tester.takeException(), isNull); final bar = tester.getRect(find.byKey(const Key('chat-background-tasks'))); final composer = tester.getRect( find.byKey(const ValueKey('chat-composer-s')), ); final transcript = tester.getRect( find.byKey(const ValueKey('chat-thread-s')), ); expect( bar.height, lessThanOrEqualTo(568 * backgroundTaskViewportShare + 0.5), ); expect(bar.bottom, lessThanOrEqualTo(composer.top)); expect(composer.bottom, lessThanOrEqualTo(568)); expect(transcript.height, greaterThan(0)); expect( find.byKey(const Key('chat-background-tasks-scroll')), findsOneWidget, ); }); testWidgets('one open task at 2x text keeps the composer on screen', ( tester, ) async { tester.view.physicalSize = const Size(320, 568); tester.view.devicePixelRatio = 1; tester.platformDispatcher.textScaleFactorTestValue = 2; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1')]); gateway.output = (_) async => { 'chat_shell_output': { 'shell': _running('sh1'), 'output': '${_pageLines().join('\n')}\n', }, }; addTearDown(gateway.close); await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); await _tapTask(tester, 'sh1'); expect(find.byKey(const Key('chat-bg-task-detail')), findsOneWidget); // The row labels and the detail are laid out at twice the text size without // overflowing, and the bar's bound still leaves the composer on screen. expect(tester.takeException(), isNull); final bar = tester.getRect(find.byKey(const Key('chat-background-tasks'))); final composer = tester.getRect( find.byKey(const ValueKey('chat-composer-s')), ); expect(bar.bottom, lessThanOrEqualTo(composer.top)); expect(composer.bottom, lessThanOrEqualTo(568)); }); testWidgets('the Cupertino row elides its labels instead of overflowing', ( tester, ) async { tester.view.physicalSize = const Size(320, 568); tester.view.devicePixelRatio = 1; tester.platformDispatcher.textScaleFactorTestValue = 2; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([ _running('sh1', command: 'go test ./... -run TestSomethingLongEnough'), ]); gateway.output = (_) async => { 'chat_shell_output': { 'shell': _running('sh1'), 'output': 'native output', }, }; addTearDown(gateway.close); await tester.pumpWidget(_host(gateway, cupertino: true)); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); await _tapTask(tester, 'sh1'); expect(tester.takeException(), isNull); expect(find.text('Details'), findsOneWidget); }); testWidgets('the conversation mounts the session task surface', ( tester, ) async { final gateway = _TasksGateway() ..shells = () async => _snapshot([_running('sh1')]); addTearDown(gateway.close); await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); expect(find.byKey(const Key('chat-background-tasks')), findsOneWidget); expect(find.text('Background tasks'), findsOneWidget); expect(find.text('1 running'), findsOneWidget); }); testWidgets('the conversation bar leads, above the task bar', (tester) async { final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1')]); addTearDown(gateway.close); await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); final header = tester.getRect(find.byKey(const Key('chat-thread-header'))); final tasks = tester.getRect( find.byKey(const Key('chat-background-tasks')), ); final list = tester.getRect( find.byKey(const ValueKey('chat-thread-s')), ); expect(header.top, 0); expect(tasks.top, greaterThanOrEqualTo(header.bottom)); // The bar sits outside the transcript's scroller, as the web's chat-bar. expect(list.top, greaterThanOrEqualTo(tasks.bottom)); }); }