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/features/chat/conversation/chat_thread_view.dart'; import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart'; import 'chat_thread_fixtures.dart'; Widget host(Widget child) => MaterialApp( theme: ThemeData(platform: TargetPlatform.android), home: Scaffold(body: child), ); Widget cupertinoHost(Widget child) => CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.dark), home: CupertinoPageScaffold(child: child), ); void main() { testWidgets('live-subscription refusal is separate from readable history', ( tester, ) async { final gateway = FakeChatGateway(); addTearDown(gateway.close); gateway.subscribe = () async => throw StateError('live watch refused'); gateway.history = (_) async => chatPage([ chatMessage( 'u1', 'user', parts: [ {'type': 'text', 'text': 'History still renders.'}, ], ), ]); await tester.pumpWidget( host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})), ); await tester.pumpAndSettle(); expect(find.text('History still renders.'), findsOneWidget); expect(find.byKey(const Key('chat-live-error')), findsOneWidget); expect(find.textContaining('Live updates unavailable'), findsOneWidget); expect(find.textContaining('live watch refused'), findsOneWidget); expect(find.byKey(const Key('chat-history-error')), findsNothing); // A later resync that attaches clears only the live notice. gateway.subscribe = () async => const {}; gateway.history = (_) async => chatPage([ chatMessage( 'u1', 'user', parts: [ {'type': 'text', 'text': 'History still renders.'}, ], ), ]); var attempts = 0; for ( var i = 0; i < 80 && find.byKey(const Key('chat-live-error')).evaluate().isNotEmpty; i++ ) { if (attempts == 0) { await tester.tap(find.text('Retry').last); attempts++; } await tester.pump(const Duration(milliseconds: 5)); } expect(find.byKey(const Key('chat-live-error')), findsNothing); }); testWidgets('Load older passes the server cursor back and shows older text', ( tester, ) async { final gateway = FakeChatGateway(); addTearDown(gateway.close); gateway.history = (_) async => chatPage( [ chatMessage( 'a2', 'assistant', parts: [ {'type': 'text', 'text': 'Newest reply.'}, ], ), ], cursor: 'opaque/next?x=1', hasMore: true, ); await tester.pumpWidget( host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})), ); await tester.pumpAndSettle(); expect(find.text('Newest reply.'), findsOneWidget); expect(find.text('Load older'), findsOneWidget); final older = Completer(); gateway.history = (_) => older.future; await tester.tap(find.text('Load older')); await tester.pump(); expect(gateway.calls.last.fields['chat_query'], { 'session_id': 's', 'limit': 200, 'cursor': 'opaque/next?x=1', }); older.complete( chatPage( [ chatMessage( 'a1', 'assistant', parts: [ {'type': 'text', 'text': 'Older stored reply.'}, ], ), ], cursor: '', hasMore: false, ), ); await tester.pumpAndSettle(); expect(find.text('Older stored reply.'), findsOneWidget); expect(find.text('Newest reply.'), findsOneWidget); expect(find.text('Load older'), findsNothing); }); for (final cupertino in [false, true]) { for (final keepsControl in [true, false]) { testWidgets( 'a folded assistant turn counts every reasoning step across paging ' '(keeps Load older: $keepsControl, $cupertino)', (tester) async { final gateway = FakeChatGateway(); addTearDown(gateway.close); var reads = 0; gateway.history = (_) async => ++reads == 1 ? assistantFoldPage( const ['msg_6', 'msg_4'], const [ 'NEWEST folded reasoning body.', 'FOURTH folded reasoning body.', ], cursor: 'opaque/fold', hasMore: true, ) : assistantFoldPage( const ['msg_2', 'msg_0'], const [ 'SECOND folded reasoning body.', 'OLDEST folded reasoning body.', ], cursor: keepsControl ? 'opaque/fold-2' : '', hasMore: keepsControl, ); await tester.pumpWidget( (cupertino ? cupertinoHost : host)( ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), ), ); await tester.pumpAndSettle(); // The turn's reasoning is one chip below its answer; it counts the // steps of every message folded into the turn. expect(find.text('Reasoning · 2 steps'), findsOneWidget); await tester.tap(find.text('Load older')); await tester.pumpAndSettle(); expect(find.text('Reasoning · 4 steps'), findsOneWidget); await tester.tap(find.text('Reasoning · 4 steps')); await tester.pumpAndSettle(); for (final body in [ 'NEWEST folded reasoning body.', 'OLDEST folded reasoning body.', ]) { expect(find.text(body), findsOneWidget, reason: body); } Navigator.of(tester.element(find.text('NEWEST folded reasoning body.'))).pop(); await tester.pumpAndSettle(); expect( find.text('Load older'), keepsControl ? findsOneWidget : findsNothing, ); }, ); } } // Assistant prose goes through the landed markdown renderer; the user's // message keeps the server's characters byte-for-byte. for (final cupertino in [false, true]) { testWidgets('assistant history renders markdown while user text stays exact ' '(${cupertino ? 'cupertino' : 'material'})', (tester) async { final gateway = FakeChatGateway(); addTearDown(gateway.close); const userText = 'Keep **these** characters [as-is](javascript:alert) literal.'; const answer = '## Stored answer\n' '\n' '- first item\n' '- second item\n' '\n' '```dart\n' 'final answer = 42;\n' '```\n' '\n' 'Literal markup and [unsafe](javascript:alert) stay inert.'; gateway.history = (_) async => chatPage([ chatMessage( 'u1', 'user', parts: [ {'type': 'text', 'text': userText}, ], ), chatMessage( 'a1', 'assistant', parts: [ {'type': 'text', 'text': answer}, ], ), ]); await tester.pumpWidget( (cupertino ? cupertinoHost : host)( ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), ), ); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); expect(find.byType(ChatMarkdownView), findsOneWidget); // Stored assistant prose is parsed into native blocks. expect(find.text('Stored answer'), findsOneWidget); expect(find.text('first item'), findsOneWidget); expect(find.text('second item'), findsOneWidget); // A fenced block keeps its language label and exact code. expect(find.text('dart'), findsOneWidget); expect(find.text('final answer = 42;'), findsOneWidget); // The subset's raw markers never reach the screen. expect(find.textContaining('## Stored answer'), findsNothing); expect(find.textContaining('```'), findsNothing); // HTML stays literal and an unsafe link keeps only its label. expect( find.text( 'Literal markup and unsafe stay inert.', findRichText: true, ), findsOneWidget, ); expect( find.textContaining('javascript:alert'), findsOneWidget, reason: 'only the user text keeps the unsafe target verbatim', ); // The user message is the server's exact plain text, not markdown. expect(find.text(userText), findsOneWidget); expect( find.text('Keep these characters as-is literal.', findRichText: true), findsNothing, ); // No Material control is introduced into the Cupertino host. if (cupertino) { expect(find.byType(Material), findsNothing); } }); } testWidgets('a live assistant text frame renders formatted markdown', ( tester, ) async { final gateway = FakeChatGateway(); addTearDown(gateway.close); gateway.history = (_) async => chatPage(const []); await tester.pumpWidget( host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})), ); await tester.pumpAndSettle(); expect(find.byKey(const Key('chat-thread-empty')), findsOneWidget); gateway.emitEvent( chatTextFrame('### Live answer\n\n1. first\n2. second\n\n`live code`'), ); await tester.pump(); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); expect(find.byType(ChatMarkdownView), findsOneWidget); expect(find.text('Live answer'), findsOneWidget); expect(find.text('1.'), findsOneWidget); expect(find.text('2.'), findsOneWidget); expect(find.text('first'), findsOneWidget); expect(find.text('second'), findsOneWidget); expect(find.text('live code'), findsOneWidget); expect(find.textContaining('### Live answer'), findsNothing); expect(find.textContaining('`live code`'), findsNothing); expect(find.byKey(const Key('chat-running')), findsNothing); }); testWidgets('formatted assistant output fits 320px at 2x in dark Cupertino', ( tester, ) async { tester.view.physicalSize = const Size(640, 1200); tester.view.devicePixelRatio = 2; tester.platformDispatcher.textScaleFactorTestValue = 2; tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); final gateway = FakeChatGateway(); addTearDown(gateway.close); gateway.history = (_) async => chatPage([ chatMessage( 'a1', 'assistant', parts: [ { 'type': 'text', 'text': '## A long answer heading that wraps inside a narrow phone\n' '\n' 'A paragraph long enough to wrap onto several lines without ' 'clipping any words at twice the host text size.\n' '\n' '| Step | State |\n' '| --- | --- |\n' '| build | ok |\n' '\n' '```dart\n' 'final value = "a code line that scrolls sideways";\n' '```', }, ], ), ]); await tester.pumpWidget( cupertinoHost( ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), ), ); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); expect( find.text('A long answer heading that wraps inside a narrow phone'), findsOneWidget, ); expect(find.text('build'), findsOneWidget); expect(find.text('dart'), findsOneWidget); expect(find.byType(Material), findsNothing); }); } /// The paged-history fixture shape: a page of consecutive assistant messages, /// each with its own reasoning and text part. JsonMap assistantFoldPage( List ids, List reasoning, { required String cursor, required bool hasMore, }) => chatPage( [ for (var index = 0; index < ids.length; index++) chatMessage( ids[index], 'assistant', parts: [ { 'type': 'reasoning', 'id': 'r-${ids[index]}', 'text': reasoning[index], }, { 'type': 'text', 'id': 't-${ids[index]}', 'text': 'Answer stored as ${ids[index]}.', }, ], ), ], cursor: cursor, hasMore: hasMore, ); /// A newest page with one user prompt and one answer carrying [reasoning]. JsonMap pagedChatPage( String answerId, String reasoning, { required String cursor, required bool hasMore, }) => chatPage( [ chatMessage( 'u-$answerId', 'user', parts: [ {'type': 'text', 'text': 'A question for $answerId.'}, ], ), chatMessage( answerId, 'assistant', parts: [ {'type': 'reasoning', 'text': reasoning}, {'type': 'text', 'text': 'The answer stored as $answerId.'}, ], ), ], cursor: cursor, hasMore: hasMore, );