Fix web transcript cross-message selection

This commit is contained in:
2026-11-05 16:34:58 +00:00
parent 3a9ba55277
commit 9e7140449f
10 changed files with 929 additions and 117 deletions
@@ -19,6 +19,7 @@ import '../ui/sessions/chat_color_picker.dart';
import '../ui/sessions/session_actions.dart';
import '../ui/transcript/chat_markdown_view.dart';
import '../ui/transcript/chat_message_view.dart';
import '../ui/transcript/chat_transcript_selection.dart';
import '../ui/transcript/chat_injected_rows.dart';
import '../ui/transcript/chat_task_notices_group.dart';
import '../../artifacts/actions/artifact_file_bridge.dart';
@@ -999,117 +1000,119 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// the viewport itself ends above the composer.
// Bottom-anchored at the split row, the newest rows are
// laid out first and older ones only when scrolled to.
ChatTranscriptScrollView(
key: ValueKey<String>(
'chat-thread-${widget.sessionId}',
ChatTranscriptSelectionArea(
child: ChatTranscriptScrollView(
key: ValueKey<String>(
'chat-thread-${widget.sessionId}',
),
controller: _scroll,
splitAfter: split < 0
? null
: ValueKey<String>(keys[split]),
padding: EdgeInsets.fromLTRB(
side,
media.top + 8,
side,
8,
),
children: [
if (initialLoad)
Padding(
key: const Key('chat-thread-loading'),
padding: const EdgeInsets.all(16),
child: Center(
child: cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
),
),
if (_controller.hasMore)
Padding(
key: const Key('chat-load-older'),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _controller.loading
? null
: _controller.loadOlder,
child: const Text('Load older'),
)
: TextButton(
onPressed: _controller.loading
? null
: _controller.loadOlder,
child: const Text('Load older'),
),
),
),
if (historyNotice != null)
_ChatNoticeLine(
key: const Key('chat-history-error'),
notice: historyNotice,
onDismiss: _dismiss,
onRetry: _controller.load,
),
if (liveNotice != null)
_ChatNoticeLine(
key: const Key('chat-live-error'),
notice: liveNotice,
onDismiss: _dismiss,
onRetry: _controller.resync,
),
if (_controller.loaded &&
allRows.isEmpty &&
allNotices.isEmpty &&
_commandNotices.isEmpty &&
_controller.error == null)
const Padding(
key: Key('chat-thread-empty'),
padding: EdgeInsets.all(16),
child: Text('No messages in this chat yet.'),
),
...transcript,
// Messages the server holds queued (one sent before
// a reload, or from another device) follow the
// transcript: none has reached the harness yet.
for (final prompt
in _controller.queuedOutsideTranscript)
Padding(
key: ValueKey<String>(
'chat-queued-${prompt['operation_id']}',
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: _queuedRow(prompt, cupertino),
),
// Messages the server has not accepted follow the
// transcript until they are retried or edited.
for (final send in _composer.deliveries.unsent)
Padding(
key: ValueKey<String>(
'chat-unsent-${send.operationId}',
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: _unsentRow(send, cupertino),
),
// The conversation's own command lines sit after the
// turns, as on the web; they are never bubbles.
for (final notice in _commandNotices)
_ChatNoticeLine(
key: ValueKey<String>(
'chat-command-notice-${notice.condition}',
),
notice: notice,
onDismiss: _dismiss,
),
],
),
controller: _scroll,
splitAfter: split < 0
? null
: ValueKey<String>(keys[split]),
padding: EdgeInsets.fromLTRB(
side,
media.top + 8,
side,
8,
),
children: [
if (initialLoad)
Padding(
key: const Key('chat-thread-loading'),
padding: const EdgeInsets.all(16),
child: Center(
child: cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
),
),
if (_controller.hasMore)
Padding(
key: const Key('chat-load-older'),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _controller.loading
? null
: _controller.loadOlder,
child: const Text('Load older'),
)
: TextButton(
onPressed: _controller.loading
? null
: _controller.loadOlder,
child: const Text('Load older'),
),
),
),
if (historyNotice != null)
_ChatNoticeLine(
key: const Key('chat-history-error'),
notice: historyNotice,
onDismiss: _dismiss,
onRetry: _controller.load,
),
if (liveNotice != null)
_ChatNoticeLine(
key: const Key('chat-live-error'),
notice: liveNotice,
onDismiss: _dismiss,
onRetry: _controller.resync,
),
if (_controller.loaded &&
allRows.isEmpty &&
allNotices.isEmpty &&
_commandNotices.isEmpty &&
_controller.error == null)
const Padding(
key: Key('chat-thread-empty'),
padding: EdgeInsets.all(16),
child: Text('No messages in this chat yet.'),
),
...transcript,
// Messages the server holds queued (one sent before
// a reload, or from another device) follow the
// transcript: none has reached the harness yet.
for (final prompt
in _controller.queuedOutsideTranscript)
Padding(
key: ValueKey<String>(
'chat-queued-${prompt['operation_id']}',
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: _queuedRow(prompt, cupertino),
),
// Messages the server has not accepted follow the
// transcript until they are retried or edited.
for (final send in _composer.deliveries.unsent)
Padding(
key: ValueKey<String>(
'chat-unsent-${send.operationId}',
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: _unsentRow(send, cupertino),
),
// The conversation's own command lines sit after the
// turns, as on the web; they are never bubbles.
for (final notice in _commandNotices)
_ChatNoticeLine(
key: ValueKey<String>(
'chat-command-notice-${notice.condition}',
),
notice: notice,
onDismiss: _dismiss,
),
],
),
if (showJump)
PositionedDirectional(
@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';
import '../../../../ui/adaptive/host.dart';
import 'chat_link_browser_menu.dart';
import 'chat_links.dart';
import 'chat_transcript_selection.dart';
/// A link's tap recognizer. A primary mouse press on a link belongs to the
/// link, as a press on a web page's anchor does: otherwise the selection area
@@ -67,6 +68,7 @@ class ChatLinkSpans {
final recognizer = _recognizers.putIfAbsent(url, _LinkTapRecognizer.new)
..onTapDown = (_) {
_pressed = url;
ChatTranscriptSelectionScope.maybeOf(context)?.menuLink = url;
}
..onTap = () {
_pressed = null;
@@ -98,14 +100,20 @@ class ChatLinkSpans {
/// has no `MaterialLocalizations`, which `SelectionArea` asserts on, so one
/// English default localization scope is added there for its context menu.
Widget selectionArea(BuildContext context, Widget child) {
final transcriptSelection = ChatTranscriptSelectionScope.maybeOf(context);
final area = Listener(
onPointerDown: (event) {
_menuLink = event.buttons == kSecondaryMouseButton ? _hovered : null;
transcriptSelection?.menuLink = _menuLink;
_pressed = null;
},
child: SelectionArea(contextMenuBuilder: _selectionMenu, child: child),
child: transcriptSelection == null
? SelectionArea(contextMenuBuilder: _selectionMenu, child: child)
: child,
);
if (!usesCupertinoHost(context)) return area;
if (transcriptSelection != null || !usesCupertinoHost(context)) {
return area;
}
return Localizations(
locale: Localizations.maybeLocaleOf(context) ?? const Locale('en'),
delegates: const [
@@ -5,11 +5,12 @@ import 'package:flutter/material.dart';
import 'chat_link_launcher.dart';
import 'chat_link_spans.dart';
import 'chat_links.dart';
import 'chat_transcript_selection.dart';
/// Plain selectable text with its bare links made tappable: the operator's
/// own message keeps every character exactly as typed (no markdown), and only
/// `http(s)://`/`www.` runs outside `` `code` `` become links. Text without a
/// link stays a plain [SelectableText].
/// link stays a plain [SelectableText] outside a shared transcript document.
class ChatLinkText extends StatefulWidget {
const ChatLinkText(this.text, {super.key});
@@ -40,7 +41,11 @@ class _ChatLinkTextState extends State<ChatLinkText> {
@override
Widget build(BuildContext context) {
final text = widget.text;
if (_found.isEmpty) return SelectableText(text);
if (_found.isEmpty) {
return ChatTranscriptSelectionScope.maybeOf(context) == null
? SelectableText(text)
: Text(text);
}
final spans = <InlineSpan>[];
var at = 0;
for (final link in _found) {
@@ -4,7 +4,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import '../../../../ui/layout/wheel_scroll_forwarding.dart';
import 'chat_transcript_selection.dart';
import '../../../../ui/text/monospace.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_link_launcher.dart';
@@ -170,7 +170,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
),
);
case MarkdownTable(header: final header, rows: final rows):
return HorizontalScrollView(
return ChatTranscriptHorizontalScrollView(
child: Table(
defaultColumnWidth: const IntrinsicColumnWidth(),
border: TableBorder.all(color: _dividerColor(context, cupertino)),
@@ -210,7 +210,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
decoration: BoxDecoration(color: _codeFill(context, cupertino)),
child: Padding(
padding: const EdgeInsets.all(12),
child: HorizontalScrollView(
child: ChatTranscriptHorizontalScrollView(
child: Text(
code,
style: const TextStyle(fontFamily: appMonospaceFamily),
@@ -0,0 +1,169 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/rendering.dart';
import '../../../../ui/adaptive/host.dart';
import '../../../../ui/layout/wheel_scroll_forwarding.dart';
/// The selection controller shared by all link spans in one transcript.
///
/// A transcript has one [SelectionArea], but links still need to contribute
/// their link-aware context menu item to that area's menu.
class ChatTranscriptSelectionController {
String? menuLink;
}
class ChatTranscriptSelectionScope extends InheritedWidget {
const ChatTranscriptSelectionScope({
super.key,
required this.controller,
required super.child,
});
final ChatTranscriptSelectionController controller;
static ChatTranscriptSelectionController? maybeOf(BuildContext context) =>
context
.dependOnInheritedWidgetOfExactType<ChatTranscriptSelectionScope>()
?.controller;
@override
bool updateShouldNotify(ChatTranscriptSelectionScope oldWidget) =>
controller != oldWidget.controller;
}
/// One native selection document for a transcript. The composer is deliberately
/// outside this widget, so dragging into it cannot extend the transcript copy.
class ChatTranscriptSelectionArea extends StatefulWidget {
const ChatTranscriptSelectionArea({super.key, required this.child});
/// Allows the web-only document to be exercised by VM widget tests.
@visibleForTesting
static bool? debugEnabled;
final Widget child;
@override
State<ChatTranscriptSelectionArea> createState() =>
_ChatTranscriptSelectionAreaState();
}
class _ChatTranscriptSelectionAreaState
extends State<ChatTranscriptSelectionArea> {
final _controller = ChatTranscriptSelectionController();
@override
Widget build(BuildContext context) {
// The shared document is a web-only behavior. On native platforms each
// message keeps its existing SelectionArea and native link menu behavior.
if (!(ChatTranscriptSelectionArea.debugEnabled ?? kIsWeb)) {
return widget.child;
}
final area = ChatTranscriptSelectionScope(
controller: _controller,
child: Listener(
// A new selection starts without a remembered link. Link recognizers
// can set it again on tap-down/long-press; plain text never reuses a
// previous link's Copy link item.
onPointerDown: (_) => _controller.menuLink = null,
child: SelectionArea(
contextMenuBuilder: (context, state) =>
_selectionMenu(_controller, state),
child: widget.child,
),
),
);
if (!usesCupertinoHost(context)) return area;
return Localizations(
locale: Localizations.maybeLocaleOf(context) ?? const Locale('en'),
delegates: const [
DefaultWidgetsLocalizations.delegate,
DefaultMaterialLocalizations.delegate,
DefaultCupertinoLocalizations.delegate,
],
child: area,
);
}
Widget _selectionMenu(
ChatTranscriptSelectionController controller,
SelectableRegionState state,
) => AdaptiveTextSelectionToolbar.buttonItems(
anchors: state.contextMenuAnchors,
buttonItems: [
if (controller.menuLink case final link?)
ContextMenuButtonItem(
label: 'Copy link',
onPressed: () {
Clipboard.setData(ClipboardData(text: link));
state.hideToolbar();
},
),
...state.contextMenuButtonItems,
],
);
}
/// Horizontal code/table viewports remain part of the transcript document.
/// Flutter's nested scrollable treats an outside point as before its content
/// if either coordinate is negative, and after it if either exceeds its size.
/// For a horizontal viewport in a vertical document, a point below-left must
/// mean after, not before. Give the vertical position priority outside its
/// height, while keeping normal horizontal selection and scrolling inside.
class ChatTranscriptHorizontalScrollView extends StatefulWidget {
const ChatTranscriptHorizontalScrollView({super.key, required this.child});
final Widget child;
@override
State<ChatTranscriptHorizontalScrollView> createState() =>
_ChatTranscriptHorizontalScrollViewState();
}
class _ChatTranscriptHorizontalScrollViewState
extends State<ChatTranscriptHorizontalScrollView> {
final _delegate = _HorizontalViewportSelectionDelegate();
@override
void dispose() {
_delegate.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final view = HorizontalScrollView(child: widget.child);
if (ChatTranscriptSelectionScope.maybeOf(context) == null) return view;
return SelectionContainer(delegate: _delegate, child: view);
}
}
class _HorizontalViewportSelectionDelegate
extends StaticSelectionContainerDelegate {
@override
SelectionResult handleSelectionEdgeUpdate(SelectionEdgeUpdateEvent event) {
final transform = getTransformTo(null);
final local = MatrixUtils.transformPoint(
Matrix4.inverted(transform),
event.globalPosition,
);
if (local.dy < 0 || local.dy > containerSize.height) {
final position = MatrixUtils.transformPoint(
transform,
Offset(containerSize.width / 2, local.dy),
);
event = event.type == SelectionEventType.startEdgeUpdate
? SelectionEdgeUpdateEvent.forStart(
globalPosition: position,
granularity: event.granularity,
)
: SelectionEdgeUpdateEvent.forEnd(
globalPosition: position,
granularity: event.granularity,
);
}
return super.handleSelectionEdgeUpdate(event);
}
}
+67
View File
@@ -0,0 +1,67 @@
# Web transcript selection acceptance
The web transcript now has one SelectionArea around the real transcript scroll
view, with the composer outside it. Operator text without links participates
as Text rather than a nested SelectableText. Markdown and linked operator text
reuse the document registrar, while link-aware Copy link is supplied to the
shared menu. Native/standalone renderers retain their previous selection areas.
A new pointer selection clears remembered link context before a link recognizer
can supply the touched URL, so plain text never offers an old link's menu item.
The first Mobile candidate only tested structure and left the plain-user branch
isolated. Actual forward/backward clipboard tests failed: forward copied only
`User question`; backward copied only `Assistant answer.`. Baseline evidence:
`/tmp/memwatch/out.JDbEfN` (0 passed, 2 failed). Those same assertions pass after
the participation fix. Tests now assert clipboard contents, not widget counts
or an untouched mock value.
Acceptance also found an unrelated-code leak while selecting a later paragraph:
`Read here now` copied `earlierCode();latestCode();Read here now`, even without
slivers (`/tmp/memwatch/out.qSXIK1`). A point below-left of a horizontal code
viewport has both positive-outside Y and negative X. Flutter's nested scrollable
checks negative coordinates first, treating that selection start as before its
content, then treats the drag end as after it. The viewport's full code leaks
into a range that never crosses it.
The shared-web markdown horizontal viewport now gives vertical before/after
meaning priority when the point is outside its height, normalizing only X for
that edge event before forwarding to Flutter. Inside-viewport horizontal
selection/scrolling remains Flutter's own behavior. This wrapper is used for
code and tables only under the shared transcript scope. It does not invent or
rewrite copied text. Exact later-paragraph copying and intentionally crossed
multiline code both pass, in both directions.
Verification:
- 145 focused transcript, actual ChatThreadView, existing link/native controls,
and stream-rebuild performance tests pass via memory watchdog; peak 1341 MB,
21 seconds (`/tmp/memwatch/out.PCzk3H`).
- Real ChatThreadView tests retain a non-null splitAfter by using long earlier
history. The newest plain user precedes the centre split, its answer follows;
forward/backward copied text is in visual order and excludes earlier history
and the real composer's unchanged draft.
- Tests include precise multiline code, composer-native editing after selection,
retained copied selection after an unrelated update, desktop activation and
context Copy link, touch Copy link and plain-context reset, native fallback.
- Focused analyze clean (`flutter-analyze.8WpzRq`). Fixture web build and Wasm
dry run passed. No full app suite or deployment was run in this repair lane.
Final real Chrome captures, all eleven PNGs inspected:
- `/tmp/transcript-selection-final-wide/`: 1100x1000, links=0, forward/backward
plain-user cross-message selection, through-code range, composer exclusion.
- `/tmp/transcript-selection-final-narrow/`: same assertions at 560x1000.
- `/tmp/transcript-selection-final-link-range/`: links=1, paragraph-only range;
its observed copy is `Read the release notes or https:/`, with no other code
or message included. The earlier browser failure copied three code blocks.
- `/tmp/transcript-selection-final-links/`: links=1, a drifting link click opens
the intended URL once, and dragging from plain text across it opens nothing.
The wide/narrow/range scripts observe navigator.clipboard.writeText arguments
from actual Command+C interactions and assert their bytes; selection behavior
itself is not mocked. This does not claim OS clipboard persistence, real Safari
behavior, or physical-device touch verification. Capture-owned Chrome instances
and isolated loopback servers exited normally.
Known follow-up, deliberately separate: Flutter concatenates semantic block and
message text when copying (for example `Question 2Answer 3Some...`). Code's
internal newlines remain exact. Paragraph/message copy separators were not
bundled into this selection-range change.
@@ -5,9 +5,12 @@ 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/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),
@@ -20,6 +23,99 @@ Widget cupertinoHost(Widget child) => CupertinoApp(
);
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),
);
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 {
@@ -0,0 +1,162 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_link_launcher.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_link_spans.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_link_text.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_transcript_selection_support.dart';
const _paragraph = 'go here now';
const _url = 'https://x.test/link';
void main() {
late List<String> copied;
late List<Uri> opened;
setUp(() {
ChatTranscriptSelectionArea.debugEnabled = true;
copied = recordTranscriptClipboard();
opened = [];
});
tearDown(() {
ChatTranscriptSelectionArea.debugEnabled = null;
ChatLinkSpans.debugOwnsSecondaryClick = null;
});
Future<void> pump(WidgetTester tester) async {
await tester.pumpWidget(
ChatLinkScope(
launcher: (uri) async {
opened.add(uri);
return true;
},
child: MaterialApp(
home: Scaffold(
body: ChatTranscriptSelectionArea(
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ChatLinkText('Plain question'),
SizedBox(height: 24),
ChatMarkdownView(text: 'go [here](https://x.test/link) now'),
],
),
),
),
),
),
);
await tester.pumpAndSettle();
}
testWidgets(
'shared document links still activate with a drifting mouse click',
(tester) async {
await pump(tester);
final link = transcriptWord(tester, _paragraph, 'here');
await dragTranscriptSelection(tester, link, link + const Offset(3, 0));
expect(opened.map((uri) => '$uri'), [_url]);
expect(copied, isEmpty);
},
);
testWidgets(
'desktop link context copy and ordinary selection copy both work',
(tester) async {
ChatLinkSpans.debugOwnsSecondaryClick = true;
await pump(tester);
final link = transcriptWord(tester, _paragraph, 'here');
final mouse = await tester.startGesture(
link,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await mouse.up();
await tester.pumpAndSettle();
await mouse.removePointer();
expect(find.text('Copy link'), findsOneWidget);
await tester.tap(find.text('Copy link'));
await tester.pumpAndSettle();
expect(copied.single, _url);
expect(opened, isEmpty);
await dragTranscriptSelection(
tester,
transcriptBoundary(tester, _paragraph),
transcriptBoundary(tester, _paragraph, end: true),
);
await copyTranscriptSelection(tester);
expect(copied.last, _paragraph);
expect(opened, isEmpty);
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets(
'touch Copy link uses touched URL and plain selection clears link context',
(tester) async {
ChatLinkSpans.debugOwnsSecondaryClick = false;
await pump(tester);
await tester.longPressAt(transcriptWord(tester, _paragraph, 'here'));
await tester.pumpAndSettle();
expect(find.text('Copy link'), findsOneWidget);
await tester.tap(find.text('Copy link'));
await tester.pumpAndSettle();
expect(copied.single, _url);
expect(opened, isEmpty);
await tester.longPressAt(
transcriptWord(tester, 'Plain question', 'Plain'),
);
await tester.pumpAndSettle();
expect(find.text('Copy link'), findsNothing);
expect(find.text('Copy'), findsOneWidget);
await tester.tap(find.text('Copy'));
await tester.pumpAndSettle();
expect(copied.last, contains('Plain'));
expect(copied.last, isNot(contains(_url)));
expect(opened, isEmpty);
},
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
);
testWidgets(
'selecting later paragraph never includes unrelated scrollable code',
(tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: ChatTranscriptSelectionArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ChatMarkdownView(text: '```dart\nearlierCode();\n```'),
ChatLinkText('Second question'),
ChatMarkdownView(
text:
'```dart\nlatestCode();\n```\n\nRead [here](https://x.test/link) now',
),
],
),
),
),
),
);
await tester.pumpAndSettle();
await dragTranscriptSelection(
tester,
transcriptBoundary(tester, 'Read here now'),
transcriptBoundary(tester, 'Read here now', end: true),
);
await copyTranscriptSelection(tester);
expect(copied.single, 'Read here now');
await dragTranscriptSelection(
tester,
transcriptBoundary(tester, 'Read here now', end: true),
transcriptBoundary(tester, 'Read here now'),
);
await copyTranscriptSelection(tester);
expect(copied.last, 'Read here now');
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
}
@@ -0,0 +1,83 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> dragTranscriptSelection(
WidgetTester tester,
Offset start,
Offset end,
) async {
final mouse = await tester.startGesture(start, kind: PointerDeviceKind.mouse);
await tester.pump();
for (var step = 1; step <= 20; step++) {
await mouse.moveTo(Offset.lerp(start, end, step / 20)!);
await tester.pump();
}
await mouse.up();
await tester.pumpAndSettle();
await mouse.removePointer();
}
Future<void> copyTranscriptSelection(WidgetTester tester) async {
await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyC);
await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
await tester.pump();
}
RenderParagraph transcriptParagraph(WidgetTester tester, String text) =>
tester.renderObject<RenderParagraph>(
find
.byWidgetPredicate(
(widget) => widget is RichText && widget.text.toPlainText() == text,
)
.first,
);
Offset transcriptBoundary(
WidgetTester tester,
String text, {
bool end = false,
}) {
final paragraph = transcriptParagraph(tester, text);
final offset = end ? text.length - 1 : 0;
final box = paragraph
.getBoxesForSelection(
TextSelection(baseOffset: offset, extentOffset: offset + 1),
)
.first
.toRect();
return paragraph.localToGlobal(
Offset(end ? box.right - 0.1 : box.left + 0.1, box.center.dy),
);
}
Offset transcriptWord(WidgetTester tester, String text, String word) {
final paragraph = transcriptParagraph(tester, text);
final offset = text.indexOf(word);
final box = paragraph
.getBoxesForSelection(
TextSelection(baseOffset: offset, extentOffset: offset + word.length),
)
.first
.toRect();
return paragraph.localToGlobal(box.center);
}
List<String> recordTranscriptClipboard() {
final copied = <String>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'Clipboard.setData') {
copied.add((call.arguments as Map)['text'] as String);
}
return null;
});
addTearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null),
);
return copied;
}
@@ -0,0 +1,219 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_link_text.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_transcript_selection_support.dart';
Widget _host(Widget child) => MaterialApp(home: Scaffold(body: child));
void main() {
late List<String> copied;
setUp(() {
ChatTranscriptSelectionArea.debugEnabled = true;
copied = recordTranscriptClipboard();
});
tearDown(() {
ChatTranscriptSelectionArea.debugEnabled = null;
});
for (final reverse in [false, true]) {
testWidgets(
'plain user and assistant cross-copy ${reverse ? 'backward' : 'forward'}',
(tester) async {
await tester.pumpWidget(
_host(
const ChatTranscriptSelectionArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ChatLinkText('User question'),
SizedBox(height: 24),
ChatMarkdownView(text: 'Assistant answer.'),
],
),
),
),
);
await tester.pumpAndSettle();
final user = tester.getRect(find.text('User question'));
final answer = tester.getRect(find.text('Assistant answer.'));
final start = user.topLeft + Offset(1, user.height / 2);
final end = answer.bottomRight - Offset(1, answer.height / 2);
await dragTranscriptSelection(
tester,
reverse ? end : start,
reverse ? start : end,
);
await copyTranscriptSelection(tester);
expect(copied, hasLength(1));
expect(copied.single, contains('User question'));
expect(copied.single, contains('Assistant answer.'));
expect(
copied.single.indexOf('User question'),
lessThan(copied.single.indexOf('Assistant answer.')),
);
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
}
testWidgets(
'selection includes exact multiline code across message blocks',
(tester) async {
await tester.pumpWidget(
_host(
const ChatTranscriptSelectionArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ChatLinkText('Question with code'),
ChatMarkdownView(
text:
'Reply before code.\n\n```dart\nfinal a = 1;\nfinal b = 2;\n```\n\nReply after code.',
),
],
),
),
),
);
await tester.pumpAndSettle();
await dragTranscriptSelection(
tester,
transcriptBoundary(tester, 'Question with code'),
transcriptBoundary(tester, 'Reply after code.', end: true),
);
await copyTranscriptSelection(tester);
expect(copied.single, contains('Question with code'));
expect(copied.single, contains('final a = 1;\nfinal b = 2;'));
expect(copied.single, contains('Reply after code.'));
await dragTranscriptSelection(
tester,
transcriptBoundary(tester, 'Reply after code.', end: true),
transcriptBoundary(tester, 'Question with code'),
);
await copyTranscriptSelection(tester);
expect(copied.last, copied.first);
await dragTranscriptSelection(
tester,
transcriptBoundary(tester, 'final a = 1;\nfinal b = 2;'),
transcriptBoundary(tester, 'final a = 1;\nfinal b = 2;', end: true),
);
await copyTranscriptSelection(tester);
expect(copied.last, 'final a = 1;\nfinal b = 2;');
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets(
'dragging into composer does not copy or alter its draft',
(tester) async {
final draft = TextEditingController(text: 'COMPOSER DRAFT');
addTearDown(draft.dispose);
await tester.pumpWidget(
_host(
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const ChatTranscriptSelectionArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ChatLinkText('User question'),
ChatMarkdownView(text: 'Assistant answer.'),
],
),
),
TextField(controller: draft),
],
),
),
);
await tester.pumpAndSettle();
await dragTranscriptSelection(
tester,
transcriptBoundary(tester, 'User question'),
tester.getCenter(find.byType(TextField)),
);
await copyTranscriptSelection(tester);
expect(copied.single, contains('User question'));
expect(copied.single, contains('Assistant answer.'));
expect(copied.single, isNot(contains('COMPOSER DRAFT')));
expect(draft.text, 'COMPOSER DRAFT');
await tester.tap(find.byType(TextField));
await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyA);
await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
await copyTranscriptSelection(tester);
expect(copied.last, 'COMPOSER DRAFT');
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets(
'unrelated transcript update preserves actual copied selection',
(tester) async {
late StateSetter refresh;
var revision = 0;
await tester.pumpWidget(
_host(
StatefulBuilder(
builder: (context, setState) {
refresh = setState;
return ChatTranscriptSelectionArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const ChatLinkText('User question'),
const ChatMarkdownView(text: 'Assistant answer.'),
Text('Activity revision $revision'),
],
),
);
},
),
),
);
await tester.pumpAndSettle();
await dragTranscriptSelection(
tester,
transcriptBoundary(tester, 'User question'),
transcriptBoundary(tester, 'Assistant answer.', end: true),
);
await copyTranscriptSelection(tester);
final before = copied.single;
refresh(() => revision++);
await tester.pumpAndSettle();
await copyTranscriptSelection(tester);
expect(copied.last, before);
expect(copied.last, contains('User question'));
expect(copied.last, contains('Assistant answer.'));
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets(
'disabled shared scope preserves standalone native selection',
(tester) async {
ChatTranscriptSelectionArea.debugEnabled = false;
await tester.pumpWidget(
_host(
const ChatTranscriptSelectionArea(
child: ChatLinkText('Standalone user message'),
),
),
);
await tester.pumpAndSettle();
final text = tester.getRect(find.text('Standalone user message'));
await dragTranscriptSelection(
tester,
text.centerLeft + const Offset(1, 0),
text.centerRight - const Offset(1, 0),
);
await copyTranscriptSelection(tester);
expect(copied.single, 'Standalone user message');
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
}