Chat: highlighted, clickable links in messages

Markdown links, autolinks and bare http(s)/www. URLs open externally through
url_launcher (http, https and mailto only) in assistant markdown and operator
messages; code is never linkified. Links use the host primary colour with an
underline that thickens on hover, and offer Copy link on long press and
right-click without breaking text selection.
This commit is contained in:
2026-11-03 16:17:26 +00:00
parent 5f51bbf53b
commit 9bfd16c6e5
16 changed files with 1081 additions and 113 deletions
@@ -0,0 +1,331 @@
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';
import 'package:pipelines_app/features/chat/domain/chat_transcript.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_message_view.dart';
import 'chat_markdown_test_support.dart';
const _reply = '''
Read [the docs](https://example.com/docs) or <https://example.com/auto>.
Bare https://example.com/bare. and www.example.org too.
Never [this](javascript:alert(1)) or `https://example.com/inline`.
```sh
curl https://example.com/fenced
```
''';
Widget _host(Widget child, List<Uri> opened, {bool cupertino = false}) =>
ChatLinkScope(
launcher: (uri) async {
opened.add(uri);
return true;
},
child: markdownHost(child, cupertino: cupertino),
);
TextSpan _leaf(WidgetTester tester, String text) =>
spansOf(tester, text).firstWhere((span) => span.text == text);
Future<void> _tapText(WidgetTester tester, String text) async {
final paragraph = tester
.renderObjectList<RenderParagraph>(find.byType(RichText))
.firstWhere((render) => render.text.toPlainText().contains(text));
final start = paragraph.text.toPlainText().indexOf(text);
final box = paragraph.getBoxesForSelection(
TextSelection(baseOffset: start, extentOffset: start + 2),
);
final point = paragraph.localToGlobal(box.first.toRect().center);
await tester.tapAt(point);
await tester.pump();
}
void main() {
testWidgets('assistant links open through the launcher; code stays plain', (
tester,
) async {
await phoneViewport(tester);
final opened = <Uri>[];
await tester.pumpWidget(
_host(const ChatMarkdownView(text: _reply), opened),
);
await tester.pumpAndSettle();
final primary = Theme.of(
tester.element(find.byType(ChatMarkdownView)),
).colorScheme.primary;
final docs = spansOf(tester, 'the docs').firstWhere(
(span) => span.children != null && span.toPlainText() == 'the docs',
);
expect(docs.style?.color, primary);
expect(docs.style?.decoration, TextDecoration.underline);
expect(_leaf(tester, 'the docs').mouseCursor, SystemMouseCursors.click);
for (final text in [
'the docs',
'https://example.com/auto',
'https://example.com/bare',
'www.example.org',
]) {
expect(_leaf(tester, text).recognizer, isA<TapGestureRecognizer>());
}
expect(_leaf(tester, 'this').recognizer, isNull);
expect(_leaf(tester, 'https://example.com/inline').recognizer, isNull);
expect(
find.byWidgetPredicate(
(widget) =>
widget is Text &&
widget.data == 'curl https://example.com/fenced' &&
widget.textSpan == null,
),
findsOneWidget,
);
await _tapText(tester, 'the docs');
await _tapText(tester, 'www.example.org');
await _tapText(tester, 'https://example.com/inline');
await _tapText(tester, 'this');
expect(opened.map((uri) => '$uri'), [
'https://example.com/docs',
'https://www.example.org',
]);
});
testWidgets(
'hovering a link thickens its underline; a click opens it',
(tester) async {
await phoneViewport(tester);
final semantics = tester.ensureSemantics();
final opened = <Uri>[];
await tester.pumpWidget(
_host(
const ChatMarkdownView(text: 'go [here](https://x.com) now'),
opened,
),
);
await tester.pumpAndSettle();
double? thickness() => spansOf(tester, 'here')
.firstWhere(
(span) => span.children != null && span.toPlainText() == 'here',
)
.style
?.decorationThickness;
expect(thickness(), 1);
final paragraph = tester.renderObject<RenderParagraph>(
find.byType(RichText).first,
);
final box = paragraph.getBoxesForSelection(
const TextSelection(baseOffset: 4, extentOffset: 6),
);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
addTearDown(mouse.removePointer);
await mouse.addPointer(location: Offset.zero);
await mouse.moveTo(paragraph.localToGlobal(box.first.toRect().center));
await tester.pump();
expect(thickness(), 2.5);
await mouse.down(paragraph.localToGlobal(box.first.toRect().center));
await tester.pump();
await mouse.up();
await tester.pump();
expect(opened.map((uri) => '$uri'), ['https://x.com']);
await mouse.moveTo(Offset.zero);
await tester.pump();
expect(thickness(), 1);
expect(tester.takeException(), isNull);
semantics.dispose();
},
variant: TargetPlatformVariant.all(),
);
testWidgets('a long press on a link offers Copy link and opens nothing', (
tester,
) async {
await phoneViewport(tester);
final opened = <Uri>[];
String? copied;
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
copied = (call.arguments as Map)['text'] as String?;
}
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
await tester.pumpWidget(
_host(
const ChatMarkdownView(text: 'go [here](https://x.com/a) now'),
opened,
),
);
await tester.pumpAndSettle();
final paragraph = tester.renderObject<RenderParagraph>(
find.byType(RichText).first,
);
final box = paragraph.getBoxesForSelection(
const TextSelection(baseOffset: 4, extentOffset: 6),
);
await tester.longPressAt(
paragraph.localToGlobal(box.first.toRect().center),
);
await tester.pumpAndSettle();
expect(opened, isEmpty);
expect(find.text('Copy link'), findsOneWidget);
await tester.tap(find.text('Copy link'));
await tester.pumpAndSettle();
expect(copied, 'https://x.com/a');
expect(find.text('Copy link'), findsNothing);
expect(opened, isEmpty);
});
for (final web in [false, true]) {
testWidgets(
'a right-click on a link offers Copy link (web: $web)',
(tester) async {
ChatLinkSpans.debugOwnsSecondaryClick = web;
addTearDown(() => ChatLinkSpans.debugOwnsSecondaryClick = null);
await phoneViewport(tester);
final copied = <String?>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
copied.add((call.arguments as Map)['text'] as String?);
}
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
final opened = <Uri>[];
await tester.pumpWidget(
_host(
const ChatMarkdownView(text: 'go [here](https://x.com/r) now'),
opened,
),
);
await tester.pumpAndSettle();
final paragraph = tester.renderObject<RenderParagraph>(
find.byType(RichText).first,
);
final box = paragraph.getBoxesForSelection(
const TextSelection(baseOffset: 4, extentOffset: 6),
);
final at = paragraph.localToGlobal(box.first.toRect().center);
final mouse = await tester.createGesture(
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await mouse.addPointer(location: at);
await tester.pump();
await mouse.down(at);
await tester.pump();
await mouse.up();
await tester.pumpAndSettle();
expect(find.text('Copy link'), findsOneWidget);
await tester.tap(find.text('Copy link'));
await tester.pumpAndSettle();
expect(copied, ['https://x.com/r']);
expect(find.text('Copy link'), findsNothing);
expect(opened, isEmpty);
await mouse.removePointer();
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
}
testWidgets('a long press on plain text offers no Copy link', (tester) async {
await phoneViewport(tester);
await tester.pumpWidget(
_host(
const ChatMarkdownView(text: 'plain words [here](https://x.com)'),
[],
),
);
await tester.pumpAndSettle();
final paragraph = tester.renderObject<RenderParagraph>(
find.byType(RichText).first,
);
final box = paragraph.getBoxesForSelection(
const TextSelection(baseOffset: 0, extentOffset: 3),
);
await tester.longPressAt(
paragraph.localToGlobal(box.first.toRect().center),
);
await tester.pumpAndSettle();
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Copy link'), findsNothing);
});
testWidgets('the operator message keeps its text and links bare URLs', (
tester,
) async {
await phoneViewport(tester);
final opened = <Uri>[];
const typed =
'Check [x](https://example.com/md) and `https://code.com`, '
'then https://example.com/bare.';
final row = transcriptRows([
{
'id': 'u1',
'role': 'user',
'parts': [
{'type': 'text', 'text': typed},
],
},
]).single;
for (final cupertino in [false, true]) {
opened.clear();
await tester.pumpWidget(
_host(ChatMessageView(row: row), opened, cupertino: cupertino),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.byType(ChatLinkText), findsOneWidget);
expect(allText(tester), contains(typed));
expect(
_leaf(tester, 'https://example.com/md').recognizer,
isA<TapGestureRecognizer>(),
);
expect(_leaf(tester, 'https://example.com/bare').recognizer, isNotNull);
expect(
spansOf(tester, 'https://code.com')
.where((span) => span.text?.contains('https://code.com') ?? false)
.single
.recognizer,
isNull,
);
await _tapText(tester, 'https://example.com/bare');
expect(opened.map((uri) => '$uri'), ['https://example.com/bare']);
}
});
testWidgets('an operator message without a link stays SelectableText', (
tester,
) async {
await phoneViewport(tester);
await tester.pumpWidget(
_host(const ChatLinkText('no links, just example.com text'), []),
);
await tester.pumpAndSettle();
expect(find.byType(SelectableText), findsOneWidget);
expect(find.byType(SelectionArea), findsNothing);
});
}
@@ -0,0 +1,143 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown.dart';
List<String> _targets(String text) => [
for (final link in findTextLinks(text)) link.target,
];
void main() {
group('bare URL detection', () {
test('finds http, https and www. links in prose', () {
expect(
_targets('a http://x.com/a b https://y.org/b?q=1#h c www.z.net/c'),
['http://x.com/a', 'https://y.org/b?q=1#h', 'www.z.net/c'],
);
});
test('trims trailing sentence punctuation', () {
for (final suffix in ['.', ',', ';', ':', '!', '?', '...', '."', "'"]) {
expect(_targets('see https://x.com/a$suffix'), [
'https://x.com/a',
], reason: suffix);
}
});
test('trims an unbalanced closing bracket but keeps a balanced one', () {
expect(_targets('(see https://x.com/a)'), ['https://x.com/a']);
expect(_targets('[https://x.com/a]'), ['https://x.com/a']);
expect(_targets('https://en.wikipedia.org/wiki/Dart_(language).'), [
'https://en.wikipedia.org/wiki/Dart_(language)',
]);
expect(_targets('(https://x.com/Foo_(bar))'), [
'https://x.com/Foo_(bar)',
]);
});
test('reports exact ranges', () {
const text = 'go to www.example.com.';
expect(findTextLinks(text), [
const ChatTextLink(6, 21, 'www.example.com'),
]);
});
test('never starts inside a word, path or address', () {
expect(_targets('xhttps://x.com'), isEmpty);
expect(_targets('mail@www.example.com'), isEmpty);
expect(_targets('a/www.example.com'), isEmpty);
expect(_targets('node.www.example.com'), isEmpty);
});
test('rejects a scheme or www. without a host', () {
expect(_targets('https:// and http://'), isEmpty);
expect(_targets('www. and www.example'), isEmpty);
});
test('skips inline code and fenced code', () {
expect(_targets('run `curl https://x.com/a` then https://y.com/b'), [
'https://y.com/b',
]);
expect(_targets('```\ncurl https://x.com/a\n```\nhttps://y.com/b'), [
'https://y.com/b',
]);
expect(_targets('```\nunclosed https://x.com'), isEmpty);
});
test('a markdown link in plain text links its target in place', () {
const text = '[docs](https://x.com/d)';
expect(findTextLinks(text), [
const ChatTextLink(7, 22, 'https://x.com/d'),
]);
});
});
group('scheme filter', () {
test('allows http, https, mailto and www. hosts', () {
expect(chatLinkUri('https://x.com')?.toString(), 'https://x.com');
expect(chatLinkUri('HTTP://x.com')?.host, 'x.com');
expect(chatLinkUri('mailto:a@b.com')?.scheme, 'mailto');
expect(chatLinkUri('www.x.com/a')?.toString(), 'https://www.x.com/a');
});
test('neutralises every other scheme or a missing host', () {
for (final unsafe in [
'javascript:alert(1)',
'JavaScript:alert(1)',
'data:text/html,<h1>x</h1>',
'file:///etc/passwd',
'ftp://x.com',
'vbscript:msgbox',
'mailto:',
'https://',
'//x.com',
'/artifacts/a.txt',
'x.com',
]) {
expect(chatLinkUri(unsafe), isNull, reason: unsafe);
expect(isSafeMarkdownLink(unsafe), isFalse, reason: unsafe);
}
});
});
group('markdown inline links', () {
List<MarkdownLink> links(String text) =>
parseInline(text).whereType<MarkdownLink>().toList();
test('angle-bracket autolinks show their body without brackets', () {
final found = links('<https://x.com/a> and <me@x.com> and <b>');
expect(found.map((link) => link.url), [
'https://x.com/a',
'mailto:me@x.com',
]);
expect(
(found.first.spans.single as MarkdownPlain).text,
'https://x.com/a',
);
});
test(
'a markdown destination keeps balanced parentheses and drops a title',
() {
expect(
links(
'[w](https://x.org/Dart_(language)) and [t](https://x.com "T")',
).map((link) => link.url),
['https://x.org/Dart_(language)', 'https://x.com'],
);
},
);
test('bare www. and trimmed URLs become links outside inline code', () {
final spans = parseInline(
'see www.x.com, `https://code.com` (https://y.com).',
);
expect(spans.whereType<MarkdownLink>().map((link) => link.url), [
'www.x.com',
'https://y.com',
]);
expect(
spans.whereType<MarkdownInlineCode>().single.text,
'https://code.com',
);
});
});
}
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/gestures.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_markdown_view.dart';
void main() {
@@ -107,19 +108,26 @@ void main() {
});
testWidgets(
'an unchanged link invokes the latest callback and becomes inert when disabled',
'an unchanged link invokes the latest callback, else the scope launcher',
(tester) async {
final version = ValueNotifier<int>(0);
addTearDown(version.dispose);
final opened = <int>[];
final launched = <Uri>[];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ValueListenableBuilder<int>(
valueListenable: version,
builder: (_, value, _) => ChatMarkdownView(
text: '[Link](https://example.test)',
onOpenLink: value == 2 ? null : (_) => opened.add(value),
ChatLinkScope(
launcher: (uri) async {
launched.add(uri);
return true;
},
child: MaterialApp(
home: Scaffold(
body: ValueListenableBuilder<int>(
valueListenable: version,
builder: (_, value, _) => ChatMarkdownView(
text: '[Link](https://example.test)',
onOpenLink: value == 2 ? null : (_) => opened.add(value),
),
),
),
),
@@ -143,9 +151,13 @@ void main() {
await tester.pump();
link()!.onTap!();
expect(opened, [0, 1]);
expect(launched, isEmpty);
version.value = 2;
await tester.pump();
expect(link(), isNull);
link()!.onTap!();
await tester.pump();
expect(opened, [0, 1]);
expect(launched, [Uri.parse('https://example.test')]);
},
);
}