import 'dart:async'; 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()? automations; 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_automations': return automations == null ? { 'chat_automations': {'status': 'unavailable'}, } : automations!(); 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, {int syncToken = 0}) { final child = ChatBackgroundTasks( gateway: gateway, sessionId: 's', syncToken: syncToken, ); 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 { if (find.byKey(const Key('chat-background-tasks-modal')).evaluate().isEmpty) { await _openTasks(tester); } final row = find.byKey(ValueKey('chat-bg-task-$id')); await tester.ensureVisible(row); await tester.pumpAndSettle(); await tester.tap(row); await tester.pumpAndSettle(); } Future _openTasks(WidgetTester tester) async { await tester.tap(find.byKey(const Key('chat-background-tasks-button'))); 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('1 task'), findsOneWidget); expect(find.text('go test ./...'), findsNothing); await _openTasks(tester); 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( 'shows an automation-only count and its native report in inspector', (tester) async { final gateway = _TasksGateway() ..automations = () async => { 'chat_automations': { 'session_id': 's', 'provider': 'claude', 'status': 'supported', 'active_count': 1, 'observed_at_ms': 1700000000000, }, }; addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); expect(find.text('1 automation'), findsOneWidget); await _openTasks(tester); expect(find.text('1 automation'), findsNWidgets(2)); expect(find.textContaining('Last reported:'), findsOneWidget); expect(gateway.fieldsFor('chat_automations'), [ { 'chat_query': {'session_id': 's'}, }, { 'chat_query': {'session_id': 's'}, }, ]); }, ); testWidgets('an empty snapshot shows no task control, never "0 tasks"', ( tester, ) async { final gateway = _TasksGateway(); addTearDown(gateway.close); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); expect(find.text('0 tasks'), findsNothing); expect(find.textContaining('task'), findsNothing); expect(find.byKey(const Key('chat-background-tasks-button')), 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('1 task'), findsOneWidget); await _openTasks(tester); 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('No background tasks running.'), findsOneWidget); gateway.emitShell('other', 'running', session: 'other-session'); await tester.pumpAndSettle(); expect(find.text('No background tasks running.'), findsOneWidget); }); testWidgets('more than three tasks are contained in a scrollable modal', ( 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(); await _openTasks(tester); expect(find.text('4 running'), findsOneWidget); expect(find.byType(Dialog), findsOneWidget); expect(find.byType(SingleChildScrollView), findsWidgets); 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'), findsNothing); expect(find.text('Task identity'), findsOneWidget); expect(find.text('sh1'), findsOneWidget); expect(find.text('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(find.text('Retry'), findsNothing); }); 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.text('0 tasks'), findsNothing); await _openTasks(tester); 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 clears selected output while the modal stays open', ( 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('No background tasks running.'), findsOneWidget); }); 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(); await _openTasks(tester); expect(find.text('1 running'), findsOneWidget); gateway.shells = () async => _snapshot(const []); await tester.pumpWidget(_host(gateway, syncToken: 1)); await tester.pumpAndSettle(); expect(find.text('No background tasks running.'), findsOneWidget); expect(gateway.fieldsFor('chat_shells'), hasLength(2)); }); 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(); final before = tester.getRect( find.byKey(const ValueKey('chat-composer-s')), ); await _tapTask(tester, 'sh1'); // Output stays bounded and scrollable inside the modal. expect(tester.takeException(), isNull); final outputFinder = find.byKey(const Key('chat-bg-task-output')); final output = tester.getRect(outputFinder); final modal = tester.getRect( find.byKey(const Key('chat-background-tasks-modal')), ); expect(output.height, lessThanOrEqualTo(modal.height)); expect(modal.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'), ); await tester.ensureVisible(outputFinder); await tester.pumpAndSettle(); 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)); await tester.tap(find.text('Done')); await tester.pumpAndSettle(); expect( tester.getRect(find.byKey(const ValueKey('chat-composer-s'))), before, ); }); 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(); final before = tester.getRect( find.byKey(const ValueKey('chat-composer-s')), ); await _tapTask(tester, 'sh1'); // Native dialog scrolling contains the task list and its selected output. expect(tester.takeException(), isNull); final modal = tester.getRect( find.byKey(const Key('chat-background-tasks-modal')), ); expect(modal.height, lessThanOrEqualTo(568)); expect(modal.width, lessThanOrEqualTo(320)); await tester.tap(find.text('Done')); await tester.pumpAndSettle(); expect( tester.getRect(find.byKey(const ValueKey('chat-composer-s'))), before, ); }); 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); // Task details stay in the modal at large text scale, not in the chat body. expect(tester.takeException(), isNull); final modal = tester.getRect( find.byKey(const Key('chat-background-tasks-modal')), ); expect(modal.bottom, lessThanOrEqualTo(568)); await tester.tap(find.text('Done')); await tester.pumpAndSettle(); final composer = tester.getRect( find.byKey(const ValueKey('chat-composer-s')), ); expect(composer.bottom, lessThanOrEqualTo(568)); }); testWidgets('the conversation mounts only the live task badge', ( 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-button')), findsOneWidget, ); expect(find.text('1 task'), findsOneWidget); expect(find.byKey(const Key('chat-background-tasks')), findsNothing); expect(find.text('go test ./...'), findsNothing); }); testWidgets('the task control sits inside the composer pill beside Send', ( tester, ) async { final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1')]); addTearDown(gateway.close); await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); final button = find.byKey(const Key('chat-background-tasks-button')); expect( find.descendant( of: find.byKey(const Key('chat-composer-pill')), matching: button, ), findsOneWidget, ); final tasks = tester.getRect(button); final send = tester.getRect(find.byKey(const Key('chat-composer-primary'))); expect(tasks.right, lessThanOrEqualTo(send.left)); expect(tasks.bottom, greaterThan(send.top)); expect(tasks.top, lessThan(send.bottom)); // Neutral, not the primary tint. final style = tester.widget(button).style!; final theme = Theme.of(tester.element(button)); expect( style.foregroundColor!.resolve({}), theme.colorScheme.onSurfaceVariant, ); }); testWidgets('a conversation without tasks shows no task caption', ( tester, ) async { final gateway = _TasksGateway(); addTearDown(gateway.close); await tester.pumpWidget(_thread(gateway)); await tester.pumpAndSettle(); expect(find.text('0 tasks'), findsNothing); expect(find.byKey(const Key('chat-background-tasks-button')), findsNothing); expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget); }); testWidgets( 'combined caption leaves a usable input on a narrow running chat', (tester) async { tester.view.physicalSize = const Size(360, 800); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); final gateway = _TasksGateway(); gateway.shells = () async => _snapshot([_running('sh1'), _running('sh2')]); gateway.automations = () async => { 'chat_automations': { 'session_id': 's', 'status': 'supported', 'active_count': 12, }, }; addTearDown(gateway.close); await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android), builder: (context, child) => MediaQuery( data: MediaQuery.of( context, ).copyWith(textScaler: TextScaler.linear(2)), child: child!, ), home: Scaffold( body: ChatThreadView( gateway: gateway, sessionId: 's', onBack: () {}, ), ), ), ); await tester.pumpAndSettle(); gateway._frames.add({ 'type': 'chat_event', 'chat_event': { 'session_id': 's', 'kind': 'step', 'step': { 'status': 'started', 'turn_id': 'turn', 'intermediate': false, }, }, }); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(find.byTooltip('Background tasks (2 running)'), findsOneWidget); final counter = find.byKey(const Key('chat-background-tasks-button')); // The compact caption carries the count; the gear has none of its own. expect( find.byKey(const Key('chat-background-tasks-count')), findsNothing, ); expect( find.descendant(of: counter, matching: find.text('2')), findsOneWidget, ); expect( find.descendant(of: counter, matching: find.text('12')), findsOneWidget, ); expect(tester.getSize(find.byType(EditableText)).width, greaterThan(64)); expect(tester.takeException(), isNull); }, ); }