Files
pipelines/app/test/features/chat/conversation/chat_thread_view_test.dart
T
alan fa92b9a1a0 Group each transcript row's text into one selectable
The transcript's scroll view kept every text run of every mounted row as
its own selectable and merged newly mounted runs into that list by
comparing global transforms, which dominated slow scroll frames at 4K.
Each row now wraps its content in a SelectionContainer, so the scroll
view orders rows and each row orders only its own runs once on mount.
Cross-row selection and copy order are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:21:28 +00:00

495 lines
16 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.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/conversation/chat_transcript_scroll_view.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_transcript_selection.dart';
import 'chat_thread_fixtures.dart';
import '../ui/transcript/chat_transcript_selection_support.dart';
Widget host(Widget child) => MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
void main() {
for (final reverse in [false, true]) {
testWidgets(
'web thread split slivers copy in visual order ${reverse ? 'backward' : 'forward'}',
(tester) async {
ChatTranscriptSelectionArea.debugEnabled = true;
addTearDown(() => ChatTranscriptSelectionArea.debugEnabled = null);
final copied = recordTranscriptClipboard();
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage([
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': 'First question'},
],
),
chatMessage(
'a1',
'assistant',
parts: [
{
'type': 'text',
'text': [
'First answer.',
...List.filled(30, 'Earlier context.'),
].join('\n\n'),
},
],
),
chatMessage(
'u2',
'user',
parts: [
{'type': 'text', 'text': 'Second question'},
],
),
chatMessage(
'a2',
'assistant',
parts: [
{'type': 'text', 'text': 'Last answer.'},
],
),
]);
await tester.pumpWidget(
host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})),
);
await tester.pumpAndSettle();
// The actual thread uses two centre-anchored slivers: the most recent
// user row is before their split and the answer is after it.
final transcript = tester.widget<ChatTranscriptScrollView>(
find.byType(ChatTranscriptScrollView),
);
expect(transcript.splitAfter, isNotNull);
expect(
tester.getTopLeft(find.text('Second question')).dy,
lessThan(tester.getTopLeft(find.text('Last answer.')).dy),
);
// Each row is one selectable of the scroll view's document: its text
// registers with the row's container, so scrolling re-sorts rows
// rather than every text run of the transcript.
SelectionRegistrar? registrar(String text) =>
SelectionContainer.maybeOf(tester.element(find.text(text).first));
SelectionContainerDelegate? rowDelegate(String text) => tester
.widget<SelectionContainer>(
find
.descendant(
of: find.ancestor(
of: find.text(text).first,
matching: find.byType(ChatTranscriptRowSelection),
),
matching: find.byType(SelectionContainer),
)
.first,
)
.delegate;
for (final text in ['Second question', 'Last answer.']) {
expect(registrar(text), isNotNull);
expect(registrar(text), same(rowDelegate(text)));
}
expect(
registrar('Second question'),
isNot(same(registrar('Last answer.'))),
);
final composer = find.descendant(
of: find.byKey(const ValueKey('chat-composer-s')),
matching: find.byType(EditableText),
);
await tester.enterText(composer, 'COMPOSER DRAFT');
await tester.pumpAndSettle();
final start = transcriptBoundary(tester, 'Second question');
final end = transcriptBoundary(tester, 'Last answer.', end: true);
await dragTranscriptSelection(
tester,
reverse ? end : start,
reverse ? start : end,
);
await copyTranscriptSelection(tester);
expect(copied, hasLength(1));
expect(copied.single, contains('Second question'));
expect(copied.single, contains('Last answer.'));
expect(
copied.single.indexOf('Second question'),
lessThan(copied.single.indexOf('Last answer.')),
);
expect(copied.single, isNot(contains('First question')));
expect(copied.single, isNot(contains('COMPOSER DRAFT')));
expect(
tester.widget<EditableText>(composer).controller.text,
'COMPOSER DRAFT',
);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
}
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<JsonMap>();
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 keepsControl in [true, false]) {
testWidgets(
'a folded assistant turn counts every reasoning step across paging (keeps Load older: $keepsControl)',
(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(
host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})),
);
await tester.pumpAndSettle();
// The folded turn has one stable activity control, not one chip per
// category. Its summary stays generic when only reasoning is known.
expect(find.byKey(const Key('chat-turn-activity')), findsOneWidget);
expect(find.text('Reasoning'), findsOneWidget);
await tester.tap(find.text('Load older'));
await tester.pumpAndSettle();
expect(find.text('Reasoning'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-turn-activity')));
await tester.pumpAndSettle();
for (var index = 1; index <= 4; index++) {
final disclosure = find.text('Reasoning $index');
if (tester.any(disclosure)) {
await tester.tap(disclosure);
await tester.pumpAndSettle();
}
}
for (final body in [
'NEWEST folded reasoning body.',
'OLDEST folded reasoning body.',
]) {
expect(
find.descendant(
of: find.byType(AlertDialog),
matching: find.text(body),
),
findsOneWidget,
reason: body,
);
}
await tester.tap(find.text('Done'));
await tester.pumpAndSettle();
expect(find.text('OLDEST folded reasoning body.'), findsNothing);
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.
testWidgets(
'assistant history renders markdown while user text stays exact',
(tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
const userText =
'Keep **these** characters [as-is](javascript:alert) <b>literal</b>.';
const answer =
'## Stored answer\n'
'\n'
'- first item\n'
'- second item\n'
'\n'
'```dart\n'
'final answer = 42;\n'
'```\n'
'\n'
'Literal <b>markup</b> 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(
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 <b>markup</b> 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,
);
},
);
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);
});
}
/// The paged-history fixture shape: a page of consecutive assistant messages,
/// each with its own reasoning and text part.
JsonMap assistantFoldPage(
List<String> ids,
List<String> 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,
);