Read chat replies aloud with word highlighting

An assistant reply gets Read aloud beside Copy; while it reads it becomes
Pause/Resume and Stop, one reply at a time app-wide. The spoken word is
highlighted in the rendered reply (across multi-part replies) and the
transcript scrolls only when that word leaves the viewport. Reading stops
when its chat closes or is swapped, another reply starts, or the app goes
to the background. Markdown is spoken as sentences; code blocks are
announced as "Code block.".

Speech goes through a SpeechEngine seam with a flutter_tts implementation
(Android, macOS, web; hidden on Linux) and a fake for tests. Settings has
a Read aloud section: a voice picker grouped by language (device language
first, a sample per voice), a rate slider and reset, saved per device.

flutter_tts has no Swift package, so macOS/iOS gain the CocoaPods
integration (Podfiles with the Runner deployment targets); Android
declares the TTS_SERVICE query. The capture fixture gains ?speech=fake.
This commit is contained in:
2026-11-13 01:29:04 +00:00
parent 26e68140fd
commit 6367cce68a
40 changed files with 2643 additions and 29 deletions
@@ -1,7 +1,7 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/rendering.dart';
import 'chat_transcript_selection.dart';
import 'chat_code_hover.dart';
@@ -10,7 +10,9 @@ import 'chat_link_launcher.dart';
import 'chat_link_spans.dart';
import 'chat_markdown.dart';
import 'chat_markdown_cache.dart';
import 'chat_markdown_speech.dart';
import 'chat_message_bubble.dart';
import '../../speech/speech.dart';
/// Renders one assistant text part with native text widgets and the host's own
/// theme roles. Links (`http`, `https`, `mailto` and `www.` hosts only) open
@@ -19,9 +21,15 @@ import 'chat_message_bubble.dart';
/// dimension is overridden; code keeps its exact whitespace and scrolls
/// sideways instead of widening the transcript.
class ChatMarkdownView extends StatefulWidget {
const ChatMarkdownView({super.key, required this.text, this.onOpenLink});
const ChatMarkdownView({
super.key,
required this.text,
this.messageId,
this.onOpenLink,
});
final String text;
final String? messageId;
final ValueChanged<String>? onOpenLink;
@override
@@ -44,6 +52,14 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
final _codeHover = ChatCodeHover();
ScrollPosition? _scroll;
ModalRoute<dynamic>? _route;
var _sourceCursor = 0;
/// The source range of [ChatMarkdownView.text] being spoken, while building.
SpeechRange? _highlight;
SpeechRange? _revealed;
final _textKeys = <GlobalKey>[];
var _textCount = 0;
final _segments = <MarkdownSpokenSegment>[];
@override
void didUpdateWidget(ChatMarkdownView oldWidget) {
@@ -77,12 +93,35 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
@override
Widget build(BuildContext context) {
// A new token or usage update elsewhere in the turn must not reparse and
// rebuild every earlier answer part, or disturb its text selection.
if (_rendered != null) return _rendered!;
// Keep the state subscribed to inherited styling even when the cached
// subtree is returned without rebuilding its Markdown spans.
Theme.of(context);
final speech = speechController;
return ListenableBuilder(
listenable: Listenable.merge([speech, speech.word]),
builder: (context, _) {
final range = spokenSourceIn(speech, widget.messageId, widget.text);
if (range == null) {
_revealed = null;
return _rendered ?? _buildRendered(context, null);
}
if (range != _revealed) {
_revealed = range;
WidgetsBinding.instance.addPostFrameCallback((_) => _reveal(range));
}
return _buildRendered(context, range);
},
);
}
Widget _buildRendered(BuildContext context, SpeechRange? range) {
_sourceCursor = 0;
_textCount = 0;
_highlight = range;
_segments.clear();
final gap = chatParagraphGap(context);
final blocks = chatMarkdownCache.blocksFor(widget.text);
return _rendered = Listener(
final rendered = Listener(
onPointerDown: (_) => _codeHover.hide(),
onPointerSignal: (_) => _codeHover.hide(),
child: NotificationListener<ScrollNotification>(
@@ -108,6 +147,8 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
),
),
);
if (range == null) _rendered = rendered;
return rendered;
}
/// Blocks are separated by an empty line of body text, like paragraphs;
@@ -196,6 +237,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
),
);
case MarkdownCode(language: final language, code: final code):
_skipCodeBlock(code);
final labelStyle = _roleStyle(
context,
Theme.of(context).textTheme.labelSmall,
@@ -220,6 +262,14 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
}
}
void _skipCodeBlock(String code) {
_sourceCursor = fencedCodeSpan(
widget.text,
_sourceCursor,
code,
).end.clamp(0, widget.text.length);
}
Widget _cell(BuildContext context, String text, {bool header = false}) {
final style = header
? _roleStyle(context, Theme.of(context).textTheme.labelLarge)
@@ -234,43 +284,77 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
}
Widget _text(BuildContext context, String text, {TextStyle? style}) {
if (text.isEmpty) return const SizedBox.shrink();
final sourceStart = widget.text.indexOf(text, _sourceCursor);
if (sourceStart >= 0) _sourceCursor = sourceStart + text.length;
// Keys follow render order, which is stable for the same text, so the
// revealed word's paragraph can be found after the frame.
if (_textCount == _textKeys.length) _textKeys.add(GlobalKey());
final key = _textKeys[_textCount++];
final source = MarkdownSourceCursor(
widget.text,
sourceStart < 0 ? _sourceCursor : sourceStart,
key,
);
return Builder(
builder: (textContext) => Text.rich(
TextSpan(children: _spans(textContext, parseInline(text))),
key: key,
TextSpan(children: _spans(textContext, parseInline(text), source)),
style: style,
),
);
}
List<InlineSpan> _spans(BuildContext context, List<MarkdownInline> spans) => [
List<InlineSpan> _spans(
BuildContext context,
List<MarkdownInline> spans,
MarkdownSourceCursor source,
) => [
for (final span in spans)
switch (span) {
MarkdownPlain(text: final text) => TextSpan(text: text),
MarkdownInlineCode(text: final text) => _inlineCode(context, text),
MarkdownPlain(text: final text) => _leaf(context, text, source),
MarkdownInlineCode(text: final text) => _inlineCode(
context,
text,
source,
),
MarkdownStrong(spans: final inner) => TextSpan(
style: const TextStyle(fontWeight: FontWeight.bold),
children: _spans(context, inner),
children: _spans(context, inner, source),
),
MarkdownEmphasis(spans: final inner) => TextSpan(
style: const TextStyle(fontStyle: FontStyle.italic),
children: _spans(context, inner),
children: _spans(context, inner, source),
),
MarkdownLink(url: final url, spans: final inner) => _link(
context,
url,
inner,
source,
),
},
];
TextSpan _inlineCode(BuildContext context, String text) {
TextSpan _leaf(
BuildContext context,
String text,
MarkdownSourceCursor source,
) => _highlightedText(context, text, source);
TextSpan _inlineCode(
BuildContext context,
String text,
MarkdownSourceCursor source,
) {
final token = text;
final highlighted = _highlightedText(context, text, source);
return TextSpan(
text: text,
style: TextStyle(
fontFamily: appMonospaceFamily,
backgroundColor: _codeFill(context),
),
text: highlighted.text,
children: highlighted.children,
onEnter: (event) {
if (_route?.isCurrent != false) {
_codeHover.show(context, token, text, event.position);
@@ -284,10 +368,11 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
BuildContext context,
String url,
List<MarkdownInline> spans,
MarkdownSourceCursor source,
) => _links.link(
context,
url,
_spans(context, spans),
_spans(context, spans, source),
onOpen: (uri) {
final onOpenLink = widget.onOpenLink;
if (onOpenLink != null) return onOpenLink(uri.toString());
@@ -295,6 +380,46 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
},
);
/// A leaf's spans, recording where it renders so a spoken word in it can
/// be revealed, with the spoken characters highlighted.
TextSpan _highlightedText(
BuildContext context,
String text,
MarkdownSourceCursor source,
) {
final offsets = source.consume(text);
final renderedStart = source.visibleOffset;
source.visibleOffset += text.length;
if (offsets.isNotEmpty) {
_segments.add(
MarkdownSpokenSegment(
source.key,
offsets.first,
offsets.last + 1,
renderedStart,
source.visibleOffset,
),
);
}
return spokenTextSpan(
text,
offsets,
_highlight,
Theme.of(context).colorScheme.primaryContainer,
);
}
void _reveal(SpeechRange range) {
final scroll = _scroll;
if (!mounted || range != _revealed || scroll == null) return;
revealSpokenWord(
scroll,
_segments,
range,
reduceMotion: MediaQuery.maybeDisableAnimationsOf(context) ?? false,
);
}
/// 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
/// lower-heading treatment, and no level falls back to a body role, so a