import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/chat/screen.dart'; import 'package:pipelines_app/shell/adaptive_shell.dart'; import 'package:pipelines_app/shell/destination.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; import 'package:pipelines_app/features/chat/ui/sessions/session_actions.dart'; import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; import 'conversation/chat_thread_fixtures.dart'; class _Gateway extends FakeChatGateway { @override Future call(String type, [JsonMap fields = const {}]) { if (type == 'chat_sessions') { return Future.value({ 'chat_sessions': [ for (final id in ['a', 'b', 'c']) {'id': id, 'title': 'Chat $id'}, ], }); } if (type == 'chat_shells') return Future.value({'chat_shells': []}); return super.call(type, fields); } } Finder _thread(String id, {bool offstage = false}) => find.byWidgetPredicate( (widget) => widget is ChatThreadView && widget.sessionId == id, skipOffstage: !offstage, ); Finder _input(String id, {bool offstage = false}) => find.descendant( of: find.byKey(ValueKey('chat-composer-$id'), skipOffstage: !offstage), matching: find.byType(EditableText, skipOffstage: !offstage), skipOffstage: !offstage, ); Widget _app(_Gateway gateway, {int sync = 0}) => MaterialApp( home: Scaffold( body: ChatScreen(gateway: gateway, syncToken: sync), ), ); Future<_Gateway> _setup(WidgetTester tester, {bool inShell = false}) async { SharedPreferences.setMockInitialValues({}); tester.view.physicalSize = const Size(1800, 1000); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final gateway = _Gateway() ..history = (fields) async { final id = (fields['chat_query'] as Map)['session_id']; return chatPage([ chatMessage( '$id-history', 'assistant', parts: [ {'type': 'text', 'text': 'History for $id'}, ], ), ]); }; addTearDown(gateway.close); await tester.pumpWidget( inShell ? MaterialApp( home: AdaptiveShell( destination: AppDestination.chat, destinationBodies: { AppDestination.chat: (_) => ChatScreen(gateway: gateway), AppDestination.runs: (_) => const Center(child: Text('Runs destination')), }, ), ) : _app(gateway), ); await tester.pumpAndSettle(); await tester.tap(find.text('Chat a').first); await tester.pumpAndSettle(); return gateway; } Future _split(WidgetTester tester, String id, String action) async { await tester.tap( find.byWidgetPredicate( (widget) => widget is SessionActionsButton && widget.session['id'] == id, ), ); await tester.pumpAndSettle(); await tester.tap(find.text(action)); await tester.pumpAndSettle(); } void main() { testWidgets( 'compact navigation reaches Runs and returns without losing draft', (tester) async { await _setup(tester, inShell: true); final state = tester.state(_thread('a')); await tester.enterText(_input('a'), 'Keep compact draft'); await tester.drag( find.byKey(const ValueKey('list-detail-divider')), const Offset(-500, 0), ); await tester.pumpAndSettle(); expect(find.text('Menu'), findsOneWidget); await tester.tap(find.text('Menu')); await tester.pumpAndSettle(); await tester.tap(find.text('Runs')); await tester.pumpAndSettle(); expect(find.text('Runs destination'), findsOneWidget); await tester.tap(find.byTooltip('Chat')); await tester.pumpAndSettle(); expect(find.text('Menu'), findsOneWidget); expect(tester.state(_thread('a')), same(state)); expect( tester.widget(_input('a')).controller.text, 'Keep compact draft', ); expect(tester.takeException(), isNull); }, ); testWidgets('phone peeks fit a small keyboard viewport at large text', ( tester, ) async { SharedPreferences.setMockInitialValues({}); tester.view.physicalSize = const Size(560, 700); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final gateway = _Gateway()..history = (_) async => chatPage([]); addTearDown(gateway.close); await tester.pumpWidget( MaterialApp( builder: (context, child) => MediaQuery( data: MediaQuery.of( context, ).copyWith(textScaler: TextScaler.linear(2)), child: child!, ), home: Scaffold(body: ChatScreen(gateway: gateway)), ), ); await tester.pumpAndSettle(); await tester.tap(find.text('Chat a').first); await tester.pumpAndSettle(); final controller = tester .widget(find.byType(ChatWorkspace)) .controller; controller.splitActive('b', ChatSplitAxis.vertical); await tester.pumpAndSettle(); tester.view.viewInsets = const FakeViewPadding(bottom: 300); await tester.pumpAndSettle(); expect(_thread('a'), findsOneWidget); expect(_thread('b'), findsOneWidget); expect(tester.takeException(), isNull); }); testWidgets('phone can add a second chat without losing its first draft', ( tester, ) async { SharedPreferences.setMockInitialValues({}); tester.view.physicalSize = const Size(560, 1000); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final gateway = _Gateway()..history = (_) async => chatPage([]); addTearDown(gateway.close); await tester.pumpWidget(_app(gateway)); await tester.pumpAndSettle(); await tester.tap(find.text('Chat a').first); await tester.pumpAndSettle(); expect(find.byTooltip('Back').hitTestable(), findsOneWidget); expect( tester .widget(find.byType(BackButton).hitTestable()) .onPressed, isNull, ); final stateA = tester.state(_thread('a')); await tester.enterText(_input('a'), 'Phone draft A'); await tester.pumpAndSettle(); final add = find.byTooltip('Add chat pane').hitTestable(); if (add.evaluate().isEmpty) { await tester.tap(find.byTooltip('More actions').first); await tester.pumpAndSettle(); await tester.tap(find.text('Add chat pane')); } else { await tester.tap(add); } await tester.pumpAndSettle(); await tester.tap(find.text('Chat b')); await tester.pumpAndSettle(); expect(_thread('a'), findsOneWidget); expect(_thread('b'), findsOneWidget); expect(tester.state(_thread('a')), same(stateA)); expect( tester.widget(_input('a', offstage: true)).controller.text, 'Phone draft A', ); final workspace = tester.widget(find.byType(ChatWorkspace)); expect(workspace.controller.paneCount, 2); expect( (workspace.controller.root as ChatWorkspaceSplit).axis, ChatSplitAxis.horizontal, ); expect(workspace.controller.activePane?.sessionId, 'b'); final first = workspace.controller.panes.first.id; await tester.tap(find.byKey(ValueKey('chat-peek-$first'))); await tester.pumpAndSettle(); expect(workspace.controller.activePane?.sessionId, 'a'); expect( tester .widget(_input('b', offstage: true)) .focusNode .hasFocus, isFalse, ); expect(tester.state(_thread('a')), same(stateA)); tester.view.physicalSize = const Size(880, 1000); await tester.pumpAndSettle(); final aRect = tester.getRect( find.byKey( ValueKey('chat-workspace-${workspace.controller.panes.first.id}'), ), ); final bRect = tester.getRect( find.byKey( ValueKey('chat-workspace-${workspace.controller.panes.last.id}'), ), ); expect(aRect.top, bRect.top); expect(aRect.right, lessThan(bRect.left)); expect(tester.state(_thread('a')), same(stateA)); expect( tester.widget(_input('a')).controller.text, 'Phone draft A', ); expect(tester.takeException(), isNull); }); testWidgets( 'drag compacts and expands sidebar without losing panes or drafts', (tester) async { await _setup(tester); await _split(tester, 'b', 'Open to the right'); final stateA = tester.state(_thread('a')); final stateB = tester.state(_thread('b')); await tester.enterText(_input('a'), 'Keep this draft'); final divider = find.byKey(const ValueKey('list-detail-divider')); final originalLeft = tester.getRect(_thread('a')).left; final gesture = await tester.startGesture(tester.getCenter(divider)); await gesture.moveBy(const Offset(-250, 0)); await tester.pumpAndSettle(); expect(find.byTooltip('Expand chat list'), findsOneWidget); expect(tester.getRect(_thread('a')).left, lessThan(originalLeft)); expect(tester.state(_thread('a')), same(stateA)); expect(tester.state(_thread('b')), same(stateB)); // The same drag can reverse across the threshold without dropping capture. await gesture.moveBy(const Offset(250, 0)); await tester.pumpAndSettle(); expect(find.byTooltip('Expand chat list'), findsNothing); expect(tester.getRect(_thread('a')).left, closeTo(originalLeft, 1)); await gesture.up(); await tester.drag(divider, const Offset(-500, 0)); await tester.pumpAndSettle(); expect(find.byTooltip('Expand chat list'), findsOneWidget); await tester.tap(find.byTooltip('Expand chat list')); await tester.pumpAndSettle(); expect(find.byTooltip('Expand chat list'), findsNothing); expect( tester.widget(_input('a')).controller.text, 'Keep this draft', ); await tester.drag(divider, const Offset(-500, 0)); await tester.pumpAndSettle(); await tester.drag(divider, const Offset(250, 0)); await tester.pumpAndSettle(); expect(find.byTooltip('Expand chat list'), findsNothing); expect(tester.state(_thread('b')), same(stateB)); await tester.tap(find.byTooltip('More actions').hitTestable().first); await tester.pumpAndSettle(); expect(find.text('Chat list layout'), findsNothing); await tester.pumpWidget(const SizedBox()); }, ); testWidgets( 'nested splits preserve drafts, resize, collapse and narrow restore', (tester) async { final gateway = await _setup(tester); final stateA = tester.state(_thread('a')); await tester.enterText(_input('a'), 'Draft A'); await _split(tester, 'b', 'Open to the right'); final stateB = tester.state(_thread('b')); await tester.enterText(_input('b'), 'Draft B'); await _split(tester, 'c', 'Open below'); final workspace = tester.widget( find.byType(ChatWorkspace), ); expect(workspace.controller.paneCount, 3); expect(tester.state(_thread('a')), same(stateA)); expect(tester.state(_thread('b')), same(stateB)); expect( tester.getCenter(_thread('a')).dx, lessThan(tester.getCenter(_thread('b')).dx), ); expect( tester.getCenter(_thread('b')).dy, lessThan(tester.getCenter(_thread('c')).dy), ); final root = workspace.controller.root as ChatWorkspaceSplit; final divider = find.byKey(ValueKey('chat-workspace-${root.id}')); final width = tester.getSize(_thread('a')).width; await tester.drag(divider, const Offset(80, 0)); await tester.pumpAndSettle(); expect(tester.getSize(_thread('a')).width, greaterThan(width)); expect(tester.state(_thread('a')), same(stateA)); tester.view.physicalSize = const Size(560, 1000); await tester.pumpAndSettle(); expect(_thread('c'), findsOneWidget); expect(find.byType(ChatThreadView), findsNWidgets(2)); tester.view.physicalSize = const Size(390, 844); await tester.pumpAndSettle(); expect(_thread('c'), findsOneWidget); expect(find.byType(ChatThreadView), findsNWidgets(2)); expect(tester.state(_thread('a', offstage: true)), same(stateA)); tester.view.physicalSize = const Size(1800, 1000); await tester.pumpAndSettle(); expect(tester.state(_thread('a')), same(stateA)); expect( tester.widget(_input('a')).controller.text, 'Draft A', ); expect( tester.widget(_input('b')).controller.text, 'Draft B', ); final closePane = find .descendant(of: _thread('c'), matching: find.byTooltip('Close pane')) .hitTestable(); if (closePane.evaluate().isEmpty) { await tester.tap( find .descendant( of: _thread('c'), matching: find.byTooltip('More actions'), ) .hitTestable(), ); await tester.pumpAndSettle(); await tester.tap(find.text('Close pane')); } else { await tester.tap(closePane); } await tester.pumpAndSettle(); expect(workspace.controller.paneCount, 2); expect(_thread('c'), findsNothing); expect(tester.state(_thread('b')), same(stateB)); expect( gateway.calls.where( (call) => [ 'chat_prompt', 'chat_close', 'chat_interrupt', ].contains(call.type), ), isEmpty, ); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); }, ); testWidgets('pane keyboard focus, session-isolated streams and reconnects', ( tester, ) async { final gateway = await _setup(tester); await _split(tester, 'b', 'Open to the right'); await tester.tap(_input('b')); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pumpAndSettle(); expect( tester.widget(_input('a')).focusNode.hasPrimaryFocus, isTrue, ); gateway.emitEvent( chatTextFrame('Alpha only', session: 'a', messageId: 'live-a'), ); gateway.emitEvent( chatTextFrame('Beta only', session: 'b', messageId: 'live-b'), ); await tester.pumpAndSettle(); expect( find.descendant(of: _thread('a'), matching: find.text('Alpha only')), findsOneWidget, ); expect( find.descendant(of: _thread('b'), matching: find.text('Alpha only')), findsNothing, ); expect( find.descendant(of: _thread('b'), matching: find.text('Beta only')), findsOneWidget, ); final states = [tester.state(_thread('a')), tester.state(_thread('b'))]; final subscriptions = gateway.calls .where((call) => call.type == 'chat_subscribe') .length; await tester.pumpWidget(_app(gateway, sync: 1)); await tester.pumpAndSettle(); expect(tester.state(_thread('a')), same(states[0])); expect(tester.state(_thread('b')), same(states[1])); expect( gateway.calls.where((call) => call.type == 'chat_subscribe').length, subscriptions + 2, ); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); }); testWidgets( 'route focus and asynchronous new sessions affect the owning pane', (tester) async { final gateway = await _setup(tester); final route = ValueNotifier('a'); addTearDown(route.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: ValueListenableBuilder( valueListenable: route, builder: (_, id, _) => ChatScreen( gateway: gateway, initialSessionId: id, onSessionSelected: (id) => route.value = id, onBack: () => route.value = null, ), ), ), ), ); await tester.pumpAndSettle(); await _split(tester, 'b', 'Open to the right'); await _split(tester, 'c', 'Open below'); expect(route.value, 'c'); final stateA = tester.state(_thread('a')); final stateC = tester.state(_thread('c')); final finishedNew = tester .widget(_thread('b')) .onNewSession!; await tester.tap(_input('a')); await tester.pumpAndSettle(); expect(route.value, 'a'); finishedNew('b', {'id': 'b-new', 'title': 'Fresh B'}, 'Started fresh'); await tester.pumpAndSettle(); expect(route.value, 'a'); expect(_thread('b'), findsNothing); expect(_thread('b-new'), findsOneWidget); expect(tester.state(_thread('a')), same(stateA)); expect(tester.state(_thread('c')), same(stateC)); tester.view.physicalSize = const Size(560, 1000); await tester.pumpAndSettle(); await tester.binding.handlePopRoute(); await tester.pumpAndSettle(); expect(route.value, isNull); expect(find.text('Chat a'), findsOneWidget); expect( gateway.calls.where( (call) => ['chat_close', 'chat_interrupt'].contains(call.type), ), isEmpty, ); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); }, ); testWidgets( 'background new-session completion never navigates away from Search', (tester) async { final gateway = await _setup(tester); final opened = []; await tester.pumpWidget( MaterialApp( home: AdaptiveShell( destination: AppDestination.chat, destinationBodies: { AppDestination.chat: (_) => ChatScreen(gateway: gateway, onSessionSelected: opened.add), AppDestination.search: (_) => const Text('Search destination'), }, ), ), ); await tester.pumpAndSettle(); await tester.tap(find.text('Chat a').first); await tester.pumpAndSettle(); await _split(tester, 'b', 'Open to the right'); final finishedNew = tester .widget(_thread('b')) .onNewSession!; final before = opened.length; await tester.tap(find.byKey(const ValueKey('shell.destination.search'))); await tester.pumpAndSettle(); finishedNew('b', {'id': 'b-new', 'title': 'Fresh B'}, 'Started fresh'); await tester.pumpAndSettle(); expect(find.text('Search destination'), findsOneWidget); expect(opened.length, before); await tester.tap(find.byKey(const ValueKey('shell.destination.chat'))); await tester.pumpAndSettle(); expect(_thread('a'), findsOneWidget); expect(_thread('b-new'), findsOneWidget); expect(opened.last, 'b-new'); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); }, ); }