Merge: clickable links in chat

This commit is contained in:
2026-11-03 16:17:54 +00:00
16 changed files with 1081 additions and 113 deletions
@@ -0,0 +1,14 @@
import 'chat_link_browser_menu_stub.dart'
if (dart.library.js_interop) 'chat_link_browser_menu_web.dart'
as impl;
/// Whether a link's right-click opens the app's own "Copy link" menu: on the
/// web the browser shows its own menu over text, so the link handles the
/// secondary click itself. Elsewhere the selection menu carries "Copy link".
const bool linkOwnsSecondaryClick = impl.linkOwnsSecondaryClick;
/// While [overLink] is true, the browser's own context menu is suppressed so a
/// right-click on a link shows only the app's menu. This blocks the DOM event
/// alone; it never toggles `BrowserContextMenu`, which would rebuild every
/// selectable region (remounting its subtree and dropping its selection).
void suppressBrowserMenuOverLink(bool overLink) => impl.suppress(overLink);
@@ -0,0 +1,3 @@
const bool linkOwnsSecondaryClick = false;
void suppress(bool overLink) {}
@@ -0,0 +1,18 @@
import 'dart:js_interop';
import 'package:web/web.dart' as web;
const bool linkOwnsSecondaryClick = true;
bool _overLink = false;
JSFunction? _listener;
void suppress(bool overLink) {
_overLink = overLink;
if (_listener != null) return;
final listener = ((web.Event event) {
if (_overLink) event.preventDefault();
}).toJS;
_listener = listener;
web.window.addEventListener('contextmenu', listener, true.toJS);
}
@@ -0,0 +1,41 @@
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
/// Opens one already-filtered link target; true when the platform accepted it.
typedef ChatLinkLauncher = Future<bool> Function(Uri uri);
/// Opens [uri] outside the app: the system browser or mail client natively, a
/// new tab on the web.
Future<bool> launchChatLinkExternally(Uri uri) =>
launchUrl(uri, mode: LaunchMode.externalApplication);
/// Supplies the launcher transcript links use; tests install a fake. Without a
/// scope, links open with [launchChatLinkExternally].
class ChatLinkScope extends InheritedWidget {
const ChatLinkScope({
super.key,
required this.launcher,
required super.child,
});
final ChatLinkLauncher launcher;
static ChatLinkLauncher of(BuildContext context) =>
context.getInheritedWidgetOfExactType<ChatLinkScope>()?.launcher ??
launchChatLinkExternally;
@override
bool updateShouldNotify(ChatLinkScope oldWidget) =>
launcher != oldWidget.launcher;
}
/// Launches [uri] with the scope's launcher, reporting a refusal or a failed
/// platform call instead of letting it escape as an unhandled error.
Future<void> openChatLink(BuildContext context, Uri uri) async {
final launcher = ChatLinkScope.of(context);
try {
if (!await launcher(uri)) debugPrint('Link not opened: $uri');
} on Object catch (error) {
debugPrint('Link not opened: $uri ($error)');
}
}
@@ -0,0 +1,175 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../../ui/adaptive/host.dart';
import 'chat_link_browser_menu.dart';
import 'chat_links.dart';
/// The link spans of one selectable text block, and the selection area that
/// hosts them. A tap opens the link. A long press (or a native right-click)
/// shows the selection menu with "Copy link" added; on the web, where the
/// browser owns the right-click menu over text, a right-click on a link opens
/// a "Copy link" menu instead. None of this consumes the text selection
/// gestures, so links never break selecting a message.
///
/// The owner calls [dispose], and rebuilds its spans when [onChanged] fires
/// (hover emphasis is a paint-only style change, which keeps a selection).
class ChatLinkSpans {
ChatLinkSpans({required this.onChanged});
/// Tests set this to exercise the web right-click path on the VM.
@visibleForTesting
static bool? debugOwnsSecondaryClick;
final VoidCallback onChanged;
final Map<String, TapGestureRecognizer> _recognizers = {};
final ContextMenuController _linkMenu = ContextMenuController();
String? _hovered;
String? _pressed;
String? _menuLink;
bool _disposed = false;
bool get _ownsSecondaryClick =>
debugOwnsSecondaryClick ?? linkOwnsSecondaryClick;
/// [label] styled as a link to [target] and opened through [onOpen]. An
/// unsafe target keeps its label as plain text.
InlineSpan link(
BuildContext context,
String target,
List<InlineSpan> label, {
required ValueChanged<Uri> onOpen,
}) {
final uri = chatLinkUri(target);
if (uri == null) return TextSpan(children: label);
final url = uri.toString();
final recognizer = _recognizers.putIfAbsent(url, TapGestureRecognizer.new)
..onTapDown = (_) {
_pressed = url;
}
..onTap = () {
_pressed = null;
onOpen(uri);
}
..onSecondaryTapUp = _ownsSecondaryClick
? (details) => _showLinkMenu(context, details.globalPosition, url)
: null;
// The host's primary colour: a Material app's colour scheme primary, a
// Cupertino app's tint.
final color = CupertinoTheme.of(context).primaryColor;
return _leaves(
TextSpan(
style: TextStyle(
color: color,
decoration: TextDecoration.underline,
decorationColor: color,
decorationThickness: _hovered == url ? 2.5 : 1,
),
children: label,
),
recognizer,
url,
);
}
/// The native [SelectionArea] around [child], with "Copy link" in its menu
/// when the press that opened the menu was on a link. A Cupertino-only app
/// 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 area = Listener(
onPointerDown: (event) {
_menuLink = event.buttons == kSecondaryMouseButton ? _hovered : null;
_pressed = null;
},
child: SelectionArea(contextMenuBuilder: _selectionMenu, child: 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(BuildContext context, SelectableRegionState state) {
// A touch long press opens the menu after the link's tap-down recorded it.
final link = _menuLink ??= _pressed;
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: state.contextMenuAnchors,
buttonItems: [
if (link != null) _copyItem(link, state.hideToolbar),
...state.contextMenuButtonItems,
],
);
}
void _showLinkMenu(BuildContext context, Offset position, String url) {
_linkMenu.show(
context: context,
contextMenuBuilder: (_) => TapRegion(
onTapOutside: (_) => _linkMenu.remove(),
child: AdaptiveTextSelectionToolbar.buttonItems(
anchors: TextSelectionToolbarAnchors(primaryAnchor: position),
buttonItems: [_copyItem(url, _linkMenu.remove)],
),
),
);
}
ContextMenuButtonItem _copyItem(String url, VoidCallback done) =>
ContextMenuButtonItem(
label: 'Copy link',
onPressed: () {
Clipboard.setData(ClipboardData(text: url));
done();
},
);
void dispose() {
_disposed = true;
if (_hovered != null) suppressBrowserMenuOverLink(false);
_linkMenu.remove();
for (final recognizer in _recognizers.values) {
recognizer.dispose();
}
}
void _hover(String? url) {
if (_disposed || _hovered == url) return;
suppressBrowserMenuOverLink(url != null);
_hovered = url;
onChanged();
}
/// A `TextSpan` only dispatches a recognizer or hover when it also owns
/// text, so the link's handlers are copied onto its text leaves. The style
/// stays on the shared parent.
InlineSpan _leaves(
InlineSpan span,
TapGestureRecognizer recognizer,
String url,
) {
if (span is! TextSpan) return span;
final children = span.children;
final leaf = span.text != null;
return TextSpan(
text: span.text,
style: span.style,
recognizer: leaf ? recognizer : null,
mouseCursor: leaf ? SystemMouseCursors.click : null,
onEnter: leaf ? (_) => _hover(url) : null,
onExit: leaf ? (_) => _hover(null) : null,
semanticsLabel: span.semanticsLabel,
children: children == null
? null
: [for (final child in children) _leaves(child, recognizer, url)],
);
}
}
@@ -0,0 +1,60 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'chat_link_launcher.dart';
import 'chat_link_spans.dart';
import 'chat_links.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].
class ChatLinkText extends StatefulWidget {
const ChatLinkText(this.text, {super.key});
final String text;
@override
State<ChatLinkText> createState() => _ChatLinkTextState();
}
class _ChatLinkTextState extends State<ChatLinkText> {
late final ChatLinkSpans _links = ChatLinkSpans(
onChanged: () => setState(() {}),
);
late List<ChatTextLink> _found = findTextLinks(widget.text);
@override
void didUpdateWidget(ChatLinkText oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.text != oldWidget.text) _found = findTextLinks(widget.text);
}
@override
void dispose() {
_links.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final text = widget.text;
if (_found.isEmpty) return SelectableText(text);
final spans = <InlineSpan>[];
var at = 0;
for (final link in _found) {
if (link.start > at) {
spans.add(TextSpan(text: text.substring(at, link.start)));
}
spans.add(
_links.link(context, link.target, [
TextSpan(text: text.substring(link.start, link.end)),
], onOpen: (uri) => unawaited(openChatLink(context, uri))),
);
at = link.end;
}
if (at < text.length) spans.add(TextSpan(text: text.substring(at)));
return _links.selectionArea(context, Text.rich(TextSpan(children: spans)));
}
}
@@ -0,0 +1,149 @@
/// Link detection for transcript text: bare URLs, `<autolinks>` and the
/// scheme filter every activated target passes through. Pure string logic.
library;
/// One bare link found in plain text: the visible range and its target.
final class ChatTextLink {
const ChatTextLink(this.start, this.end, this.target);
final int start;
final int end;
final String target;
@override
bool operator ==(Object other) =>
other is ChatTextLink &&
other.start == start &&
other.end == end &&
other.target == target;
@override
int get hashCode => Object.hash(start, end, target);
@override
String toString() => 'ChatTextLink($start, $end, $target)';
}
final RegExp _boundary = RegExp(r'[\p{L}\p{N}_@./\-]', unicode: true);
final RegExp _whitespace = RegExp(r'\s');
final RegExp _wwwHost = RegExp(
r'^www\.[\p{L}\p{N}-]+\.[\p{L}\p{N}]',
unicode: true,
caseSensitive: false,
);
final RegExp _email = RegExp(r'^[^\s@<>()]+@[^\s@<>()]+\.[^\s@<>()]+$');
final RegExp _autolinkScheme = RegExp(
r'^(?:https?://|mailto:)[^\s<>]+$',
caseSensitive: false,
);
const _trailingPunctuation = '.,;:!?*_~\'"';
const _closers = {')': '(', ']': '[', '}': '{'};
/// The activatable target for [url], or null. Only `http`/`https` with a host
/// and `mailto` with an address pass; a `www.` host is opened over https. The
/// transcript is untrusted model output, so `javascript:`, `data:`, `file:` and
/// relative targets never activate.
Uri? chatLinkUri(String url) {
var value = url.trim();
if (value.toLowerCase().startsWith('www.')) value = 'https://$value';
final uri = Uri.tryParse(value);
if (uri == null) return null;
switch (uri.scheme.toLowerCase()) {
case 'http' || 'https':
return uri.host.isEmpty ? null : uri;
case 'mailto':
return uri.path.trim().isEmpty ? null : uri;
default:
return null;
}
}
/// A bare `http(s)://` or `www.` link starting exactly at [index], with
/// trailing sentence punctuation and unbalanced closing brackets trimmed. A
/// link never starts in the middle of a word, path or address.
String? bareLinkAt(String text, int index) {
if (index > 0 && _boundary.hasMatch(text[index - 1])) return null;
final head = text
.substring(index, (index + 8).clamp(0, text.length))
.toLowerCase();
final www = head.startsWith('www.');
final prefix = head.startsWith('https://')
? 8
: head.startsWith('http://')
? 7
: www
? 4
: 0;
if (prefix == 0) return null;
var end = index;
while (end < text.length &&
!_whitespace.hasMatch(text[end]) &&
!'<>"\'`'.contains(text[end])) {
end += 1;
}
final url = trimLinkEnd(text.substring(index, end));
if (url.length <= prefix) return null;
if (www && !_wwwHost.hasMatch(url)) return null;
return chatLinkUri(url) == null ? null : url;
}
/// Drops trailing sentence punctuation, and a closing bracket only when the
/// link does not open it too, so `(see https://x.com/a)` ends before `)` while
/// `https://en.wikipedia.org/wiki/Dart_(language)` keeps it.
String trimLinkEnd(String url) {
var value = url;
while (value.isNotEmpty) {
final last = value[value.length - 1];
final opener = _closers[last];
if (_trailingPunctuation.contains(last)) {
value = value.substring(0, value.length - 1);
} else if (opener != null && _count(value, opener) < _count(value, last)) {
value = value.substring(0, value.length - 1);
} else {
break;
}
}
return value;
}
int _count(String text, String char) => char.allMatches(text).length;
/// The target of an `<autolink>` body: an `http(s)`/`mailto` URL or a bare
/// email address. Anything else (HTML such as `<b>`) is not a link.
String? autolinkTarget(String inner) {
if (_autolinkScheme.hasMatch(inner)) {
return chatLinkUri(inner) == null ? null : inner;
}
if (_email.hasMatch(inner)) return 'mailto:$inner';
return null;
}
/// Bare links in plain (non-markdown) text, outside `` `code` `` spans and
/// ```` ``` ```` fences, so an operator's pasted command is never linkified.
List<ChatTextLink> findTextLinks(String text) {
final links = <ChatTextLink>[];
var i = 0;
while (i < text.length) {
if (text.startsWith('```', i)) {
final close = text.indexOf('```', i + 3);
if (close < 0) break;
i = close + 3;
continue;
}
if (text[i] == '`') {
final close = text.indexOf('`', i + 1);
if (close > i) {
i = close + 1;
continue;
}
}
final url = bareLinkAt(text, i);
if (url != null) {
links.add(ChatTextLink(i, i + url.length, url));
i += url.length;
} else {
i += 1;
}
}
return links;
}
@@ -4,4 +4,5 @@ library;
export 'markdown_blocks.dart';
export 'markdown_entities.dart';
export 'chat_links.dart';
export 'markdown_inline.dart';
@@ -1,18 +1,21 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import '../../../../ui/adaptive/host.dart';
import '../../../../ui/layout/wheel_scroll_forwarding.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_link_launcher.dart';
import 'chat_link_spans.dart';
import 'chat_markdown.dart';
import 'chat_markdown_cache.dart';
import 'chat_message_bubble.dart';
/// Renders one assistant text part with native text widgets and the host's own
/// theme roles. Link activation is the caller's job: [onOpenLink] receives only
/// an `http`/`https` target. No font family, size, colour or component
/// theme roles. Links (`http`, `https`, `mailto` and `www.` hosts only) open
/// through [onOpenLink] when given, else the [ChatLinkScope] launcher, which by
/// default opens them outside the app. No font family, size, colour or component
/// dimension is overridden; code keeps its exact whitespace and scrolls
/// sideways instead of widening the transcript.
class ChatMarkdownView extends StatefulWidget {
@@ -34,14 +37,15 @@ Widget chatMarkdownText(
}) => ChatMarkdownView(text: text, onOpenLink: onOpenLink);
class _ChatMarkdownViewState extends State<ChatMarkdownView> {
final Map<String, TapGestureRecognizer> _links = {};
late final ChatLinkSpans _links = ChatLinkSpans(
onChanged: () => setState(() => _rendered = null),
);
Widget? _rendered;
@override
void didUpdateWidget(ChatMarkdownView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.text != oldWidget.text ||
(widget.onOpenLink == null) != (oldWidget.onOpenLink == null)) {
if (widget.text != oldWidget.text) {
_rendered = null;
}
}
@@ -56,9 +60,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
@override
void dispose() {
for (final recognizer in _links.values) {
recognizer.dispose();
}
_links.dispose();
super.dispose();
}
@@ -71,7 +73,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final gap = chatParagraphGap(context);
final blocks = chatMarkdownCache.blocksFor(widget.text);
return _rendered = _selectable(
return _rendered = _links.selectionArea(
context,
Column(
mainAxisSize: MainAxisSize.min,
@@ -94,23 +96,6 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
double _gapAfter(MarkdownBlock previous, double paragraphGap) =>
previous is MarkdownHeading ? 8 : paragraphGap;
/// Selection is provided by the native [SelectionArea]. A Cupertino-only app
/// has no `MaterialLocalizations`, which `SelectionArea` asserts on, so one
/// English default localization scope is added there for its context menu.
Widget _selectable(BuildContext context, Widget child) {
final area = SelectionArea(child: 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 _block(BuildContext context, MarkdownBlock block, bool cupertino) {
switch (block) {
case MarkdownHeading(level: final level, text: final text):
@@ -303,38 +288,16 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
String url,
List<MarkdownInline> spans,
bool cupertino,
) {
final children = _spans(context, spans, cupertino);
final onOpenLink = widget.onOpenLink;
if (!isSafeMarkdownLink(url) || onOpenLink == null) {
return TextSpan(children: children);
}
final recognizer = _links.putIfAbsent(url, TapGestureRecognizer.new);
recognizer.onTap = () => widget.onOpenLink?.call(url);
return _withRecognizer(
TextSpan(
style: const TextStyle(decoration: TextDecoration.underline),
children: children,
),
recognizer,
);
}
/// A `TextSpan` only dispatches a recognizer when it also owns text, not when
/// it only owns children, so a link's recognizer is copied onto its text
/// leaves. The underline stays on the shared parent.
InlineSpan _withRecognizer(InlineSpan span, TapGestureRecognizer recognizer) {
if (span is! TextSpan) return span;
final children = span.children;
return TextSpan(
text: span.text,
style: span.style,
recognizer: span.text == null ? span.recognizer : recognizer,
children: children == null
? null
: [for (final child in children) _withRecognizer(child, recognizer)],
);
}
) => _links.link(
context,
url,
_spans(context, spans, cupertino),
onOpen: (uri) {
final onOpenLink = widget.onOpenLink;
if (onOpenLink != null) return onOpenLink(uri.toString());
unawaited(openChatLink(context, uri));
},
);
/// Heading roles are a non-increasing sequence from the host's own text
/// theme. H3–H6 share one title role, matching the web renderer's flat
@@ -9,6 +9,7 @@ import '../sessions/chat_adaptive.dart';
import 'chat_attachment_gallery.dart';
import '../../domain/chat_tool_calls.dart';
import 'chat_copy_button.dart';
import 'chat_link_text.dart';
import 'chat_message_bubble.dart';
import 'chat_turn_activity_view.dart';
import 'native_disclosure.dart';
@@ -150,7 +151,7 @@ class ChatMessageView extends StatelessWidget {
.map((part) => '${part['text'] ?? ''}')
.join('\n');
final widgets = <Widget>[
if (text.trim().isNotEmpty) SelectableText(text),
if (text.trim().isNotEmpty) ChatLinkText(text),
for (final part in parts.where(_isFile))
if (!chatPartIsThumbnail(part)) _attachment(context, part),
for (final part in parts)
@@ -1,6 +1,8 @@
/// Inline markdown spans for assistant prose (the web subset).
library;
import 'chat_links.dart';
// ---- Inline -----------------------------------------------------------------
/// One inline markdown span.
@@ -35,11 +37,11 @@ final class MarkdownLink extends MarkdownInline {
}
final RegExp _wordChar = RegExp(r'[\p{L}\p{N}]', unicode: true);
final RegExp _whitespace = RegExp(r'\s');
/// Parses inline markup into a flat span tree. Handles `` `code` ``,
/// `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)` and bare
/// `http(s)://` autolinks; everything else stays plain text. Underscore
/// `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)`,
/// `<https://…>` / `<mailto:…>` autolinks and bare `http(s)://` / `www.` links;
/// everything else stays plain text. Underscore
/// emphasis requires word boundaries so `snake_case` is never italicised.
List<MarkdownInline> parseInline(String? text) {
final source = text ?? '';
@@ -87,27 +89,37 @@ List<MarkdownInline> parseInline(String? text) {
}
} else if (c == '[') {
final close = source.indexOf(']', i + 1);
if (close > i && close + 1 < source.length && source[close + 1] == '(') {
final urlEnd = source.indexOf(')', close + 2);
final url = urlEnd > close
? source.substring(close + 2, urlEnd).trim()
: '';
if (url.isNotEmpty) {
flush();
spans.add(
MarkdownLink(url, parseInline(source.substring(i + 1, close))),
);
i = urlEnd + 1;
} else {
buffer.write(c);
i += 1;
}
final destination =
close > i && close + 1 < source.length && source[close + 1] == '('
? _destination(source, close + 2)
: null;
if (destination != null) {
flush();
spans.add(
MarkdownLink(
destination.url,
parseInline(source.substring(i + 1, close)),
),
);
i = destination.end;
} else {
buffer.write(c);
i += 1;
}
} else if (c == '<') {
final close = source.indexOf('>', i + 1);
final inner = close > i ? source.substring(i + 1, close) : '';
final target = inner.isEmpty ? null : autolinkTarget(inner);
if (target != null) {
flush();
spans.add(MarkdownLink(target, [MarkdownPlain(inner)]));
i = close + 1;
} else {
buffer.write(c);
i += 1;
}
} else {
final url = _autolinkAt(source, i);
final url = bareLinkAt(source, i);
if (url != null) {
flush();
spans.add(MarkdownLink(url, [MarkdownPlain(url)]));
@@ -122,30 +134,30 @@ List<MarkdownInline> parseInline(String? text) {
return spans;
}
/// A bare `http(s)://` URL starting exactly at [index], with trailing
/// punctuation trimmed.
String? _autolinkAt(String text, int index) {
if (!text.startsWith('http://', index) &&
!text.startsWith('https://', index)) {
return null;
/// A `(destination)` starting at [start] (just after the `(`): parentheses
/// inside it must balance, and an optional `"title"` after whitespace is
/// dropped. Null when it is empty or never closes.
({String url, int end})? _destination(String source, int start) {
var depth = 0;
for (var i = start; i < source.length; i += 1) {
final c = source[i];
if (c == '\n') return null;
if (c == '(') depth += 1;
if (c == ')') {
if (depth == 0) {
final url = source.substring(start, i).trim().split(' ').first;
return url.isEmpty ? null : (url: url, end: i + 1);
}
depth -= 1;
}
}
var end = index;
while (end < text.length &&
!_whitespace.hasMatch(text[end]) &&
!'<>"\''.contains(text[end])) {
end += 1;
}
var url = text.substring(index, end);
while (url.isNotEmpty && '.,;:!?)]}'.contains(url[url.length - 1])) {
url = url.substring(0, url.length - 1);
}
return url.length > 'https://'.length ? url : null;
return null;
}
/// Only `http`/`https` link targets may be activated; the transcript is
/// untrusted model output, so `javascript:`/`data:` stay plain labels.
bool isSafeMarkdownLink(String url) =>
RegExp(r'^https?://', caseSensitive: false).hasMatch(url);
/// Only `http`/`https`/`mailto` targets (and `www.` hosts) may be activated;
/// the transcript is untrusted model output, so `javascript:`/`data:`/`file:`
/// stay plain labels.
bool isSafeMarkdownLink(String url) => chatLinkUri(url) != null;
/// The label a fenced code block shows: its language, or `code` when unnamed.
String markdownCodeLabel(String language) {