From f4bd8ad44cde8455c4583f44a51e6e91bd329e71 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 22:18:38 +0000 Subject: [PATCH] WIP read aloud keeps playing across chats --- .../application/detached/detached_app.dart | 4 + app/lib/application/pipelines_app.dart | 4 + .../conversation/chat_command_actions.dart | 5 + .../chat/conversation/chat_thread_view.dart | 46 +++++--- app/lib/features/chat/speech/app_speech.dart | 50 +++++++++ app/lib/features/chat/speech/speech.dart | 3 + .../chat/speech/speech_controller.dart | 69 +++++++++--- .../features/chat/speech/speech_origin.dart | 22 ++++ .../features/chat/speech/speech_reading.dart | 18 +++ .../chat/ui/sessions/chat_compact_avatar.dart | 27 +++-- .../ui/sessions/chat_compact_sidebar.dart | 2 + .../ui/sessions/chat_sessions_controller.dart | 19 +++- .../ui/sessions/session_activity_badge.dart | 13 ++- .../chat/ui/sessions/session_row_content.dart | 26 +++-- .../chat/ui/speech/chat_speaking_control.dart | 85 ++++++++++++++ .../chat/ui/speech/chat_speaking_glyph.dart | 95 ++++++++++++++++ .../chat/ui/transcript/chat_message_view.dart | 2 +- .../ui/transcript/chat_read_aloud_button.dart | 16 ++- .../features/settings/settings_screen.dart | 2 +- app/notes/read-aloud.md | 52 ++++++++- .../chat_thread_read_aloud_test.dart | 91 +++++++++++---- .../chat/speech/speech_controller_test.dart | 23 ++++ .../sessions/chat_sessions_speech_test.dart | 78 +++++++++++++ .../ui/sessions/chat_speaking_badge_test.dart | 104 ++++++++++++++++++ 24 files changed, 778 insertions(+), 78 deletions(-) create mode 100644 app/lib/features/chat/speech/app_speech.dart create mode 100644 app/lib/features/chat/speech/speech_origin.dart create mode 100644 app/lib/features/chat/speech/speech_reading.dart create mode 100644 app/lib/features/chat/ui/speech/chat_speaking_control.dart create mode 100644 app/lib/features/chat/ui/speech/chat_speaking_glyph.dart create mode 100644 app/test/features/chat/ui/sessions/chat_sessions_speech_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_speaking_badge_test.dart diff --git a/app/lib/application/detached/detached_app.dart b/app/lib/application/detached/detached_app.dart index 7dd3126d..3ddd8d06 100644 --- a/app/lib/application/detached/detached_app.dart +++ b/app/lib/application/detached/detached_app.dart @@ -27,6 +27,7 @@ import 'detached_route.dart'; import 'detached_terminal.dart'; import 'detached_window_body.dart'; import 'detached_windows.dart'; +import '../../features/chat/speech/app_speech.dart'; /// A detached window's whole app: one item ([route]) over its own /// connection, without the shell (no navigation rail, lists, floating @@ -119,6 +120,9 @@ class _DetachedWindowAppState extends State { @override void dispose() { + // A reply read aloud belongs to this app's server: switching servers (a + // fresh app) or closing the window ends it. + unawaited(speechControllerIfCreated?.stop()); _session.removeListener(_connectionChanged); widget.chatPool?.removeListener(_connectionChanged); _terminals?.dispose(); diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index bfdf0b82..d4eb56ec 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -83,6 +83,7 @@ import 'templates_destination.dart'; import 'tab_locations.dart'; import 'tab_locations_store.dart'; import '../ui/input/keyboard_owner.dart'; +import '../features/chat/speech/app_speech.dart'; /// The application's return-to-foreground policy for the shared socket. /// @@ -642,6 +643,9 @@ class _PipelinesAppState extends State @override void dispose() { + // A reply read aloud belongs to this app's server: switching servers (a + // fresh app) or closing the window ends it. + unawaited(speechControllerIfCreated?.stop()); _stopAsking(); _tabLocations.dispose(); WidgetsBinding.instance.removeObserver(this); diff --git a/app/lib/features/chat/conversation/chat_command_actions.dart b/app/lib/features/chat/conversation/chat_command_actions.dart index 0c3febfa..fdf0324a 100644 --- a/app/lib/features/chat/conversation/chat_command_actions.dart +++ b/app/lib/features/chat/conversation/chat_command_actions.dart @@ -1,8 +1,11 @@ +import 'dart:async'; + import '../../../core/api_gateway.dart'; import '../../../core/error_reason.dart'; import '../../../core/transport/connection_state.dart'; import '../data/chat_repository.dart'; import '../domain/chat_commands.dart'; +import '../speech/app_speech.dart'; /// Shows one local line in the conversation the command ran in. typedef ChatCommandNoticeCallback = void Function(String text, {bool failed}); @@ -105,6 +108,8 @@ class ChatCommandActions { if (!await confirmClose()) return; try { await repository.close(sessionId); + // Closing the chat ends its reply reading aloud. + unawaited(speechControllerIfCreated?.stopScope(sessionId)); onClosed?.call(); } catch (error) { showNotice(_reason(error), failed: true); diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index fba71e0c..7c06e88b 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -78,6 +78,7 @@ import '../../../ui/layout/wheel_scroll_forwarding.dart'; import 'chat_reading_width.dart'; import '../ui/transcript/chat_copy_gutter.dart'; import '../speech/speech.dart'; +import '../ui/speech/chat_speaking_control.dart'; import 'chat_pane_presentation.dart'; import 'chat_thread_header.dart'; import 'chat_transcript_anchor.dart'; @@ -754,11 +755,10 @@ class _ChatThreadViewState extends State with ChatFindHost { @override void didUpdateWidget(covariant ChatThreadView oldWidget) { super.didUpdateWidget(oldWidget); - if (oldWidget.sessionId != widget.sessionId || - oldWidget.gateway != widget.gateway) { - // A pane reused for another conversation stops reading the previous - // one's reply, so neither its audio nor its highlight carries over. - unawaited(speechController.stopScope(oldWidget.sessionId)); + // A reply keeps reading when its pane shows another conversation (the + // reader is the app's); a rename relabels the reading. + if (oldWidget.title != widget.title) { + speechControllerIfCreated?.retitle(widget.sessionId, widget.title.trim()); } if (!identical(oldWidget.paneCommands, widget.paneCommands)) { oldWidget.paneCommands?.removeListener(_takeCommands); @@ -862,9 +862,8 @@ class _ChatThreadViewState extends State with ChatFindHost { @override void dispose() { - // Leaving or closing the conversation stops its reply reading aloud; a - // reply another pane is reading carries on. - unawaited(speechController.stopScope(widget.sessionId)); + // Leaving the conversation keeps its reply reading aloud: the reader is + // the app's, and closing or deleting the chat is what stops it. _persistPosition(); _saveTranscript(widget.transcripts, widget.sessionId, widget.gateway); widget.paneCommands?.removeListener(_takeCommands); @@ -1334,11 +1333,20 @@ class _ChatThreadViewState extends State with ChatFindHost { pasteTarget: widget.pasteTarget, ownsPasteWhenFocused: widget.ownsPasteWhenFocused, runShell: _shellRuns.start, - limitBanner: ChatUsageLimitBanner( - thread: _controller, - composer: _composer, - accounts: _accounts, - autoContinue: widget.autoContinue, + limitBanner: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // The global Stop for a reading reply of any chat, shown + // above the active pane's composer only. + if (widget.pasteTarget) const ChatSpeakingControl(), + ChatUsageLimitBanner( + thread: _controller, + composer: _composer, + accounts: _accounts, + autoContinue: widget.autoContinue, + ), + ], ), backgroundTasks: ChatBackgroundTasks( key: ValueKey('chat-background-tasks-${widget.sessionId}'), @@ -1604,13 +1612,19 @@ class _ChatThreadViewState extends State with ChatFindHost { ], ) : column; - if (!inShellBar) return content; - // The conversation draws its own floating bar; the page shows none. final title = widget.title.trim(); + // Read aloud labels a reading with this conversation. + final origin = SpeechOrigin( + scope: widget.sessionId, + title: title, + child: content, + ); + if (!inShellBar) return origin; + // The conversation draws its own floating bar; the page shows none. return ShellBar( barless: true, title: title.isEmpty ? null : title, - child: content, + child: origin, ); }, ), diff --git a/app/lib/features/chat/speech/app_speech.dart b/app/lib/features/chat/speech/app_speech.dart new file mode 100644 index 00000000..0951c0e6 --- /dev/null +++ b/app/lib/features/chat/speech/app_speech.dart @@ -0,0 +1,50 @@ +import 'package:flutter/foundation.dart'; + +import 'speech_controller.dart'; +import 'speech_reading.dart'; + +/// The app's single reader, owned by the app (this window's engine), never by +/// a conversation view: a reply keeps reading across chat switches, panes and +/// the chat list. Each window (a detached window is its own app) has its own. +SpeechController get speechController => + _speech ??= _bind(SpeechController()); + +/// The app's reader if anything has used it yet. Code that only needs to stop +/// or retitle a reading uses this, so it never creates a platform engine. +SpeechController? get speechControllerIfCreated => _speech; + +/// Replaces the app's reader (a fake engine in tests and capture fixtures); +/// null restores the platform one. +set debugSpeechController(SpeechController? controller) => + _speech = _bind(controller); + +/// The conversation the app's reader is reading, for the speaking indicator +/// and the global Stop. It follows the reader [debugSpeechController] +/// installs, and stays null until a reader exists. +ValueListenable get speechReading => _reading; + +SpeechController? _speech; +final _reading = _AppSpeechReading(); + +T _bind(T controller) { + _reading.bind(controller); + return controller; +} + +class _AppSpeechReading extends ChangeNotifier + implements ValueListenable { + SpeechController? _source; + + @override + SpeechReading? get value => _source?.reading.value; + + void bind(SpeechController? source) { + final before = value; + _source?.reading.removeListener(notifyListeners); + _source = source; + source?.reading.addListener(notifyListeners); + // The reader is created lazily, often while a reply builds: a fresh one + // reads nothing, so it changes nothing and must not notify mid-build. + if (value != before) notifyListeners(); + } +} diff --git a/app/lib/features/chat/speech/speech.dart b/app/lib/features/chat/speech/speech.dart index 7b73f4c7..a8a1d18e 100644 --- a/app/lib/features/chat/speech/speech.dart +++ b/app/lib/features/chat/speech/speech.dart @@ -1,4 +1,7 @@ +export 'app_speech.dart'; export 'speech_controller.dart'; export 'speech_document.dart'; export 'speech_engine.dart'; +export 'speech_origin.dart'; export 'speech_preferences.dart'; +export 'speech_reading.dart'; diff --git a/app/lib/features/chat/speech/speech_controller.dart b/app/lib/features/chat/speech/speech_controller.dart index 7fa314d6..f667bc39 100644 --- a/app/lib/features/chat/speech/speech_controller.dart +++ b/app/lib/features/chat/speech/speech_controller.dart @@ -7,11 +7,18 @@ import 'flutter_tts_speech_engine.dart' import 'speech_document.dart'; import 'speech_engine.dart'; import 'speech_preferences.dart'; +import 'speech_reading.dart'; enum SpeechState { idle, speaking, paused } /// The app-wide reader: one reply speaks at a time. It notifies on state /// changes; the spoken word moves on the separate, frequent [word]. +/// +/// It belongs to the app (see [speechController]), not to the conversation +/// that started it: leaving that chat, switching panes or opening the list +/// keeps the reply reading. It ends when stopped, when it finishes, when +/// another reply starts, when its chat is closed or deleted ([stopScope]), +/// and when the app goes to the background or closes. class SpeechController extends ChangeNotifier with WidgetsBindingObserver { SpeechController({SpeechEngine? engine, SpeechPreferencesStore? store}) : engine = engine ?? createSpeechEngine(), @@ -44,6 +51,10 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver { /// The range of the word being spoken in [document]'s text, or null. final word = ValueNotifier(null); + /// The conversation whose reply is reading (paused included), or null. + /// It changes only when a reading starts, ends or its chat is renamed. + final reading = ValueNotifier(null); + bool get supported => engine.supported; SpeechState get state => _state; String? get messageId => _messageId; @@ -64,12 +75,25 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver { } /// Reads reply [id] made of markdown [parts], stopping any other reading. - Future read(String id, List parts) async { + /// [scope] is the reply's conversation (by default the part of [id] before + /// its first `/`, see [speechMessageId]) and [title] its name, which the + /// speaking indicator and the global Stop show. + Future read( + String id, + List parts, { + String? scope, + String title = '', + }) async { final document = speechDocumentFor(parts); await stop(); await restore(); if (document.text.isEmpty) return; - await _speak(id, document, _voice); + await _speak( + id, + document, + _voice, + SpeechReading(scope: scope ?? speechScopeOf(id), title: title), + ); } /// Speaks a short sample in [voice] (or the chosen one) at the chosen rate. @@ -80,12 +104,19 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver { speechSampleId, speechDocumentFor(['This is how replies will sound when read aloud.']), voice ?? _voice, + null, ); } - Future _speak(String id, SpeechDocument document, SpeechVoice? voice) { + Future _speak( + String id, + SpeechDocument document, + SpeechVoice? voice, + SpeechReading? origin, + ) { _messageId = id; _document = document; + reading.value = origin; _awaitingStart = true; word.value = null; _set(SpeechState.speaking); @@ -131,13 +162,24 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver { _clear(); } - /// Stops reading when the reply being read has an id under [scope]. + /// Stops reading when the reply being read belongs to conversation + /// [scope]: the chat was closed or deleted. Future stopScope(String scope) async { - if (_messageId?.startsWith(speechScopePrefix(scope)) ?? false) { + if (reading.value?.scope == scope || + (_messageId?.startsWith(speechScopePrefix(scope)) ?? false)) { await stop(); } } + /// Follows a rename of the conversation being read. + void retitle(String scope, String title) { + final current = reading.value; + if (current == null || current.scope != scope || current.title == title) { + return; + } + reading.value = SpeechReading(scope: scope, title: title); + } + /// Sets the rate for the next reading; [save] false previews a slider drag. Future setRate(double value, {bool save = true}) async { _rate = value.clamp(minSpeechRate, maxSpeechRate); @@ -219,6 +261,7 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver { _messageId = null; _document = null; word.value = null; + reading.value = null; _state = SpeechState.idle; notifyListeners(); } @@ -247,6 +290,7 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver { ..onProgress = null; if (_state != SpeechState.idle) unawaited(engine.stop().catchError((_) {})); word.dispose(); + reading.dispose(); super.dispose(); } } @@ -260,13 +304,8 @@ String speechScopePrefix(String scope) => '$scope/'; /// A reply's id for the reader, unique across conversations. String speechMessageId(String scope, String rowId) => '$scope/$rowId'; -SpeechController? _speechController; - -/// The app's single reader. -SpeechController get speechController => - _speechController ??= SpeechController(); - -/// Replaces the app's reader (a fake engine in tests and capture fixtures); -/// null restores the platform one. -set debugSpeechController(SpeechController? controller) => - _speechController = controller; +/// The conversation part of a reader id made by [speechMessageId]. +String speechScopeOf(String id) { + final slash = id.indexOf('/'); + return slash < 0 ? id : id.substring(0, slash); +} diff --git a/app/lib/features/chat/speech/speech_origin.dart b/app/lib/features/chat/speech/speech_origin.dart new file mode 100644 index 00000000..92d069d9 --- /dev/null +++ b/app/lib/features/chat/speech/speech_origin.dart @@ -0,0 +1,22 @@ +import 'package:flutter/widgets.dart'; + +/// Names the conversation a subtree's replies belong to, so Read aloud can +/// label the reading (the speaking indicator and the global Stop show it). +/// Looked up when a reading starts; it rebuilds nothing. +class SpeechOrigin extends InheritedWidget { + const SpeechOrigin({ + super.key, + required this.scope, + required this.title, + required super.child, + }); + + final String scope; + final String title; + + static SpeechOrigin? maybeOf(BuildContext context) => + context.getInheritedWidgetOfExactType(); + + @override + bool updateShouldNotify(SpeechOrigin oldWidget) => false; +} diff --git a/app/lib/features/chat/speech/speech_reading.dart b/app/lib/features/chat/speech/speech_reading.dart new file mode 100644 index 00000000..83d955de --- /dev/null +++ b/app/lib/features/chat/speech/speech_reading.dart @@ -0,0 +1,18 @@ +import 'package:flutter/foundation.dart'; + +/// The conversation a reading reply belongs to: [scope] is its chat id (the +/// list row's `id`, a federated id in a combined list) and [title] its name. +@immutable +class SpeechReading { + const SpeechReading({required this.scope, this.title = ''}); + + final String scope; + final String title; + + @override + bool operator ==(Object other) => + other is SpeechReading && other.scope == scope && other.title == title; + + @override + int get hashCode => Object.hash(scope, title); +} diff --git a/app/lib/features/chat/ui/sessions/chat_compact_avatar.dart b/app/lib/features/chat/ui/sessions/chat_compact_avatar.dart index f47285f2..f3ecc015 100644 --- a/app/lib/features/chat/ui/sessions/chat_compact_avatar.dart +++ b/app/lib/features/chat/ui/sessions/chat_compact_avatar.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import '../../speech/app_speech.dart'; import 'chat_session_state.dart'; import 'session_activity_badge.dart'; @@ -14,7 +15,11 @@ class ChatCompactAvatar extends StatelessWidget { required this.backgroundTasks, this.awaitingOperator = 0, required this.unread, + this.sessionId = '', }); + + /// The chat's id; its reply being read aloud shows the speaking badge. + final String sessionId; final String title; final Color color; final bool active, visible, running, unread; @@ -45,13 +50,21 @@ class ChatCompactAvatar extends StatelessWidget { ), ), ), - if (chatSessionActivityBadge( - running: running, - backgroundTasks: backgroundTasks, - awaitingOperator: awaitingOperator, - ) - case final badge?) - PositionedDirectional(bottom: -2, end: -3, child: badge), + PositionedDirectional( + bottom: -2, + end: -3, + child: ValueListenableBuilder( + valueListenable: speechReading, + builder: (context, reading, _) => + chatSessionActivityBadge( + running: running, + backgroundTasks: backgroundTasks, + awaitingOperator: awaitingOperator, + speaking: sessionId.isNotEmpty && reading?.scope == sessionId, + ) ?? + const SizedBox.shrink(), + ), + ), if (unread) PositionedDirectional( top: -2, diff --git a/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart b/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart index 53b2b3d4..bb67e40e 100644 --- a/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart +++ b/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart @@ -102,6 +102,7 @@ class ChatCompactSidebar extends StatelessWidget { awaitingOperator: awaitingOperator, backgroundTasks: backgroundTasks, unread: unread, + sessionId: id, ), if (machineName case final name?) Text( @@ -158,6 +159,7 @@ class ChatCompactSidebar extends StatelessWidget { awaitingOperator: awaitingOperator, backgroundTasks: backgroundTasks, unread: unread, + sessionId: id, ), label: Text(title), ), diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart index 8f375f96..f3788759 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -12,6 +12,7 @@ import '../../../attention/runtime/attention_ack_sync.dart'; import '../../data/chat_repository.dart'; import '../../domain/chat_list_activity.dart'; import '../../domain/chat_sessions.dart'; +import '../../speech/app_speech.dart'; import 'chat_seen_focus.dart'; import 'chat_session_local.dart'; import 'session_attention.dart'; @@ -425,6 +426,7 @@ class ChatSessionsController extends ChangeNotifier { ]; _seedLocal(); _loading = false; + _stopEndedReading(dropped: held.keys.toSet()); _notify(); } catch (error) { if (generation != _generation) return; @@ -646,7 +648,22 @@ class ChatSessionsController extends ChangeNotifier { } void _notify() { - if (!_disposed) notifyListeners(); + if (_disposed) return; + _stopEndedReading(); + notifyListeners(); + } + + /// A reply read aloud ends with its chat: closed here or on another device + /// (a refreshed row), or gone from a list that was read successfully + /// ([dropped]: deleted, or its machine removed). + void _stopEndedReading({Set dropped = const {}}) { + final scope = speechReading.value?.scope; + if (scope == null) return; + final row = _sessions.where((row) => '${row['id'] ?? ''}' == scope); + final ended = row.isEmpty + ? dropped.contains(scope) + : row.first['closed_at'] != null || row.first['closed'] == true; + if (ended) unawaited(speechControllerIfCreated?.stopScope(scope)); } @override diff --git a/app/lib/features/chat/ui/sessions/session_activity_badge.dart b/app/lib/features/chat/ui/sessions/session_activity_badge.dart index b610c428..dd5f2977 100644 --- a/app/lib/features/chat/ui/sessions/session_activity_badge.dart +++ b/app/lib/features/chat/ui/sessions/session_activity_badge.dart @@ -1,16 +1,27 @@ import 'package:flutter/material.dart'; import '../../../../ui/status/app_spinner.dart'; +import '../speech/chat_speaking_glyph.dart'; import 'chat_awaiting.dart'; /// The corner badge a chat's avatar wears for its live activity: the /// platform's activity indicator while a turn runs; otherwise, while /// background tasks still run, a quiet muted glyph (never a second spinner). -/// Null when the chat is idle. +/// Null when the chat is idle. While one of the chat's replies is read aloud +/// ([speaking]) the badge is the speaking glyph instead, above everything +/// else: it is the only place that says which chat is talking. Widget? chatSessionActivityBadge({ required bool running, required int backgroundTasks, int awaitingOperator = 0, + bool speaking = false, }) { + if (speaking) { + return Semantics( + key: const Key('chat-row-speaking'), + label: 'Reading aloud', + child: const _BadgeDisc(child: ChatSpeakingGlyph()), + ); + } // Waiting on the operator outranks everything: the agent is blocked. if (awaitingOperator > 0) return ChatAwaitingBadge(count: awaitingOperator); if (running) { diff --git a/app/lib/features/chat/ui/sessions/session_row_content.dart b/app/lib/features/chat/ui/sessions/session_row_content.dart index be8aebb8..22b43ee7 100644 --- a/app/lib/features/chat/ui/sessions/session_row_content.dart +++ b/app/lib/features/chat/ui/sessions/session_row_content.dart @@ -13,6 +13,7 @@ import 'chat_color_palette.dart'; import 'chat_visibility_marker.dart'; import 'chat_session_state.dart'; import 'session_actions.dart'; +import '../../speech/app_speech.dart'; import 'session_activity_badge.dart'; import 'session_harness_icon.dart'; import 'session_pane_menu.dart'; @@ -275,15 +276,24 @@ class ChatSessionAvatar extends StatelessWidget { : scheme.surfaceContainerHighest; mark = selected ? scheme.onPrimaryContainer : scheme.onSurfaceVariant; } - return AppListAvatar( - foreground: mark, - background: fill, - badge: chatSessionActivityBadge( - running: running, - backgroundTasks: backgroundTasks, - awaitingOperator: awaitingOperator, + final id = '${session['id'] ?? ''}'; + final icon = SessionHarnessIcon(session: session, color: mark); + // The badge follows the app's reader: the chat whose reply is being read + // aloud shows the speaking glyph, wherever its avatar is drawn. + return ValueListenableBuilder( + valueListenable: speechReading, + child: icon, + builder: (context, reading, icon) => AppListAvatar( + foreground: mark, + background: fill, + badge: chatSessionActivityBadge( + running: running, + backgroundTasks: backgroundTasks, + awaitingOperator: awaitingOperator, + speaking: id.isNotEmpty && reading?.scope == id, + ), + child: icon!, ), - child: SessionHarnessIcon(session: session, color: mark), ); } } diff --git a/app/lib/features/chat/ui/speech/chat_speaking_control.dart b/app/lib/features/chat/ui/speech/chat_speaking_control.dart new file mode 100644 index 00000000..873f3540 --- /dev/null +++ b/app/lib/features/chat/ui/speech/chat_speaking_control.dart @@ -0,0 +1,85 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../../../ui/theme/app_design_tokens.dart'; +import '../../speech/speech.dart'; + +const chatSpeakingStopLabel = 'Stop speaking'; + +/// "Speaking · Chat name" and Stop for the reply the app is reading, from any +/// chat: the reader is the app's, so a reply keeps reading after its chat is +/// left, and this is the one place to stop it without going back. Nothing +/// while no reply reads (the Settings voice sample included). +class ChatSpeakingControl extends StatelessWidget { + const ChatSpeakingControl({super.key}); + + @override + Widget build(BuildContext context) => ValueListenableBuilder( + valueListenable: speechReading, + builder: (context, reading, _) { + final speech = speechControllerIfCreated; + if (reading == null || speech == null) return const SizedBox.shrink(); + return ListenableBuilder( + listenable: speech, + builder: (context, _) => _pill(context, speech, reading), + ); + }, + ); + + Widget _pill( + BuildContext context, + SpeechController speech, + SpeechReading reading, + ) { + final scheme = Theme.of(context).colorScheme; + final tokens = AppDesignTokens.of(context); + final state = speech.state == SpeechState.paused ? 'Paused' : 'Speaking'; + final title = reading.title.isEmpty ? 'a chat' : reading.title; + final label = '$state · $title'; + final text = Theme.of(context).textTheme.labelMedium; + return Padding( + padding: const EdgeInsetsDirectional.only(bottom: 8), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: Material( + key: const Key('chat-speaking-control'), + color: tokens.panelFill(scheme, scheme.surfaceContainerHigh), + shape: tokens + .shape(const StadiumBorder()) + .copyWith(side: tokens.frameSide), + clipBehavior: Clip.antiAlias, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 12), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.graphic_eq, size: 16, color: scheme.primary), + const SizedBox(width: 8), + Flexible( + child: Semantics( + liveRegion: true, + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: text?.copyWith(color: scheme.onSurfaceVariant), + ), + ), + ), + IconButton( + key: const Key('chat-speaking-stop'), + tooltip: chatSpeakingStopLabel, + visualDensity: VisualDensity.compact, + iconSize: 18, + onPressed: () => unawaited(speech.stop()), + icon: const Icon(Icons.stop), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/ui/speech/chat_speaking_glyph.dart b/app/lib/features/chat/ui/speech/chat_speaking_glyph.dart new file mode 100644 index 00000000..8798058e --- /dev/null +++ b/app/lib/features/chat/ui/speech/chat_speaking_glyph.dart @@ -0,0 +1,95 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +/// A chat's "speaking" mark: three sound-wave bars that rise and fall while +/// one of its replies is read aloud. Under reduced motion it is a still +/// speaker icon. +class ChatSpeakingGlyph extends StatefulWidget { + const ChatSpeakingGlyph({super.key, this.size = 12, this.color}); + + final double size; + + /// Null takes the theme's primary colour. + final Color? color; + + @override + State createState() => _ChatSpeakingGlyphState(); +} + +class _ChatSpeakingGlyphState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _wave = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 900), + ); + + bool get _still => MediaQuery.maybeDisableAnimationsOf(context) ?? false; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (_still) { + _wave.stop(); + } else if (!_wave.isAnimating) { + _wave.repeat(); + } + } + + @override + void dispose() { + _wave.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final color = widget.color ?? Theme.of(context).colorScheme.primary; + if (_still) { + return Icon( + Icons.volume_up, + key: const Key('chat-speaking-still'), + size: widget.size, + color: color, + ); + } + // Its own layer: the bars repaint every frame without the row. + return RepaintBoundary( + child: CustomPaint( + key: const Key('chat-speaking-wave'), + size: Size.square(widget.size), + painter: _WavePainter(_wave, color), + ), + ); + } +} + +class _WavePainter extends CustomPainter { + _WavePainter(this.wave, this.color) : super(repaint: wave); + + final Animation wave; + final Color color; + + @override + void paint(Canvas canvas, Size size) { + const bars = 3; + final gap = size.width / (bars * 2 + 1); + final paint = Paint() + ..color = color + ..strokeWidth = gap * 1.4 + ..strokeCap = StrokeCap.round; + for (var bar = 0; bar < bars; bar++) { + final phase = (wave.value + bar / bars) * 2 * math.pi; + // Each bar swings between a third and the full height, out of step. + final height = size.height * (0.35 + 0.3 * (1 + math.sin(phase))); + final x = gap * (bar * 2 + 1.5); + final top = (size.height - height) / 2 + paint.strokeWidth / 2; + final bottom = (size.height + height) / 2 - paint.strokeWidth / 2; + canvas.drawLine(Offset(x, top), Offset(x, math.max(top, bottom)), paint); + } + } + + @override + bool shouldRepaint(_WavePainter oldDelegate) => + oldDelegate.color != color || oldDelegate.wave != wave; +} diff --git a/app/lib/features/chat/ui/transcript/chat_message_view.dart b/app/lib/features/chat/ui/transcript/chat_message_view.dart index e14c7062..6b1453bd 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -22,7 +22,7 @@ import 'paper/paper_quote.dart'; import 'terminal/terminal_glyphs.dart'; import 'chat_message_timestamp.dart'; import 'chat_read_aloud_button.dart'; -import '../../speech/speech_controller.dart'; +import '../../speech/speech.dart'; /// Builds an assistant text part; the default keeps the server's text exactly. typedef ChatMessageTextBuilder = Widget Function(BuildContext, String); diff --git a/app/lib/features/chat/ui/transcript/chat_read_aloud_button.dart b/app/lib/features/chat/ui/transcript/chat_read_aloud_button.dart index 57e8c909..27c86e1e 100644 --- a/app/lib/features/chat/ui/transcript/chat_read_aloud_button.dart +++ b/app/lib/features/chat/ui/transcript/chat_read_aloud_button.dart @@ -13,6 +13,8 @@ const chatStopReadingLabel = 'Stop reading'; /// Read aloud for one reply, styled like its Copy button. While this reply /// reads it becomes Pause (or Resume) and Stop, laid out along [direction] /// (a column in the narrow copy gutter). Absent where speech is unsupported. +/// The reader is the app's, so a reply still reading after its chat was left +/// shows Pause and Stop again when the chat is reopened. class ChatReadAloudButton extends StatelessWidget { const ChatReadAloudButton({ super.key, @@ -40,7 +42,19 @@ class ChatReadAloudButton extends StatelessWidget { key: const Key('chat-message-read-aloud'), style: style, tooltip: chatReadAloudLabel, - onPressed: () => unawaited(speech.read(messageId, parts)), + onPressed: () { + // The conversation's name labels the reading wherever it is + // shown (the avatar's indicator, the global Stop). + final origin = SpeechOrigin.maybeOf(context); + unawaited( + speech.read( + messageId, + parts, + scope: origin?.scope, + title: origin?.title ?? '', + ), + ); + }, icon: const Icon(Icons.volume_up_outlined), ); } diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart index 3e7f86b5..838beb5f 100644 --- a/app/lib/features/settings/settings_screen.dart +++ b/app/lib/features/settings/settings_screen.dart @@ -44,7 +44,7 @@ import 'settings_keyboard_shortcuts_section.dart'; import 'settings_keys.dart'; import 'settings_row.dart'; import 'settings_read_aloud_section.dart'; -import '../chat/speech/speech_controller.dart'; +import '../chat/speech/speech.dart'; import 'settings_open_in_chat_section.dart'; part 'settings_page_sections.dart'; diff --git a/app/notes/read-aloud.md b/app/notes/read-aloud.md index 96ccb190..0811ade0 100644 --- a/app/notes/read-aloud.md +++ b/app/notes/read-aloud.md @@ -16,17 +16,52 @@ they are saved on the device. - `flutter_tts_speech_engine.dart`: the `flutter_tts` implementation. The rate is a multiplier (1.0 = normal); Apple platforms get half of it on their 0..1 scale. Linux reports unsupported, so the button and section are hidden. -- `speech_controller.dart`: the app's single reader (`speechController`, a fake - in tests via `debugSpeechController`). State changes notify the controller; - the spoken word is the separate `word` notifier. Stops on `hidden`, `paused` - or `detached` (not `inactive`, which is only a lost focus). +- `speech_controller.dart`: the reader. State changes notify the controller; + the spoken word is the separate `word` notifier and the reading's + conversation (`SpeechReading`: chat id and name) the `reading` notifier. + Stops on `hidden`, `paused` or `detached` (not `inactive`, which is only a + lost focus): the phone app backgrounded keeps that behaviour. +- `app_speech.dart`: the app's single reader (`speechController`, a fake in + tests via `debugSpeechController`), `speechControllerIfCreated` for code that + only stops or relabels, and `speechReading`, the app-level listenable the + avatars and the global control follow. - `speech_document.dart`: Markdown to sentences, with each spoken character's part and source offset. Code blocks (``` and ~~~) are "Code block.", tables "Table." then cells; rules are skipped. - `chat_markdown_speech.dart`: highlight spans and the reveal scroll for `ChatMarkdownView`. -- Reader ids are `/` so a chat that closes or is swapped - for another stops only its own reply (`stopScope`). +- Reader ids are `/`; `SpeechOrigin` (put by the thread + view) gives Read aloud the chat id and name when a reading starts. + +## Keeps reading across chats + +The reader belongs to the app, not the thread view: switching chats or panes, +opening the chat list or another destination keeps the reply reading, and +reopening the chat shows its Pause/Stop again. A reading ends when it is +stopped (the reply's Stop or the global one), finishes, another reply starts, +its chat is closed (`/close`, the row's Close, or a refreshed row closed +elsewhere) or deleted (gone from a successful list read, which includes its +machine being removed), and when the app closes or is backgrounded. + +- Indicator: `chatSessionActivityBadge(speaking:)` draws + `ChatSpeakingGlyph` (three animated bars; a still speaker under reduced + motion) in the avatar's bottom-right badge, ahead of the operator wait, the + running spinner and the background-task count. `ChatSessionAvatar` (list, + quick switch, phone chat stack, pane header) and `ChatCompactAvatar` + (compact sidebar) follow `speechReading`. +- Global stop: `ChatSpeakingControl`, "Speaking · " (or "Paused") with + Stop speaking, sits above the composer of the active pane (`pasteTarget`) + of any chat, so one copy shows whatever the layout. It uses the design's + panel fill, frame and corner tokens. +- Servers: federated chat ids carry their machine, so moving between machines + in the combined list keeps reading. Switching the server profile (native) + remounts `PipelinesApp`, whose dispose stops the reader; on the web a server + switch loads another page, which ends speech. +- Detached windows are separate processes (desktop) or browser windows (web), + each with its own reader: speech belongs to the window that started it, + shows only there, and stops when that window closes. +- Web: the utterance is held by `WebSpeechEngine`, owned by the app reader, + never by a widget. ## Platform notes @@ -49,7 +84,12 @@ Tests (fake engine): `test/features/chat/speech/`, `test/features/chat/ui/transcript/chat_read_aloud_button_test.dart`, `chat_markdown_read_aloud_test.dart`, `test/features/chat/conversation/chat_thread_read_aloud_test.dart`, +`test/features/chat/ui/sessions/chat_speaking_badge_test.dart`, +`chat_sessions_speech_test.dart`, `test/features/settings/settings_read_aloud_section_test.dart`. +Captures (`speech=fake`, Terminal and Classic, wide and phone) show the badge +on the reading chat after switching to another one, and the global control. + Not verified on a device: real speech output, word boundaries and voices on Android, macOS and browsers. diff --git a/app/test/features/chat/conversation/chat_thread_read_aloud_test.dart b/app/test/features/chat/conversation/chat_thread_read_aloud_test.dart index 487e1a10..38262ff1 100644 --- a/app/test/features/chat/conversation/chat_thread_read_aloud_test.dart +++ b/app/test/features/chat/conversation/chat_thread_read_aloud_test.dart @@ -2,21 +2,34 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; import 'package:pipelines_app/features/chat/speech/speech.dart'; +import 'package:pipelines_app/features/chat/ui/speech/chat_speaking_control.dart'; import 'package:pipelines_app/features/chat/ui/transcript/chat_read_aloud_button.dart'; import '../speech/fake_speech_engine.dart'; import 'chat_thread_fixtures.dart'; -Widget _thread(FakeChatGateway gateway, String sessionId) => MaterialApp( +Widget _thread( + FakeChatGateway gateway, + String sessionId, { + String title = '', + bool pasteTarget = true, +}) => MaterialApp( theme: ThemeData(platform: TargetPlatform.android), home: Scaffold( - body: ChatThreadView(gateway: gateway, sessionId: sessionId, onBack: () {}), + body: ChatThreadView( + gateway: gateway, + sessionId: sessionId, + title: title, + pasteTarget: pasteTarget, + onBack: () {}, + ), ), ); Future<(FakeSpeechEngine, SpeechController, FakeChatGateway)> _reading( - WidgetTester tester, -) async { + WidgetTester tester, { + String title = 'Alpha', +}) async { tester.view.physicalSize = const Size(800, 1600); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); @@ -33,42 +46,78 @@ Future<(FakeSpeechEngine, SpeechController, FakeChatGateway)> _reading( ], ), ]); - await tester.pumpWidget(_thread(gateway, 's1')); + await tester.pumpWidget(_thread(gateway, 's1', title: title)); await tester.pumpAndSettle(); await tester.tap(find.byTooltip(chatReadAloudLabel)); await tester.pump(); engine.onStart!(); + await tester.pump(); expect(engine.spoken, ['Hello from the agent.']); expect(speech.messageId, startsWith(speechScopePrefix('s1'))); + expect(speech.reading.value, SpeechReading(scope: 's1', title: title)); return (engine, speech, gateway); } void main() { - testWidgets('switching the pane to another chat stops reading', ( + testWidgets('switching the pane to another chat keeps reading', ( tester, ) async { final (engine, speech, gateway) = await _reading(tester); - await tester.pumpWidget(_thread(gateway, 's2')); + await tester.pumpWidget(_thread(gateway, 's2', title: 'Beta')); await tester.pumpAndSettle(); - expect(speech.state, SpeechState.idle); - expect(engine.calls, contains('stop')); + expect(speech.state, SpeechState.speaking); + expect(engine.calls, isNot(contains('stop'))); + expect(speechReading.value?.scope, 's1'); + + // Back in the chat, its reply shows the reading's Pause and Stop again. + await tester.pumpWidget(_thread(gateway, 's1', title: 'Alpha')); + await tester.pumpAndSettle(); + expect(find.byTooltip(chatStopReadingLabel), findsOneWidget); + expect(find.byTooltip(chatPauseReadingLabel), findsOneWidget); }); - testWidgets('closing the chat stops reading', (tester) async { + testWidgets('leaving the conversation keeps its reply reading', ( + tester, + ) async { final (engine, speech, _) = await _reading(tester); await tester.pumpWidget(const MaterialApp(home: SizedBox())); await tester.pumpAndSettle(); - expect(speech.state, SpeechState.idle); - expect(engine.calls.last, 'stop'); - }); - - testWidgets('closing a chat leaves another chat reading', (tester) async { - final (engine, speech, _) = await _reading(tester); - await speech.read(speechMessageId('elsewhere', 'b1'), ['Other reply']); - engine.onStart!(); - await tester.pumpWidget(const MaterialApp(home: SizedBox())); - await tester.pumpAndSettle(); expect(speech.state, SpeechState.speaking); - expect(speech.messageId, speechMessageId('elsewhere', 'b1')); + expect(engine.calls, isNot(contains('stop'))); + }); + + testWidgets('another chat names the reading and its Stop ends it', ( + tester, + ) async { + final (engine, speech, gateway) = await _reading(tester); + expect(find.text('Speaking · Alpha'), findsOneWidget); + + await tester.pumpWidget(_thread(gateway, 's2', title: 'Beta')); + await tester.pumpAndSettle(); + expect(find.text('Speaking · Alpha'), findsOneWidget); + + await tester.tap(find.byTooltip(chatSpeakingStopLabel)); + await tester.pumpAndSettle(); + expect(speech.state, SpeechState.idle); + expect(engine.calls.last, 'stop'); + expect(find.byKey(const Key('chat-speaking-control')), findsNothing); + }); + + testWidgets('the control follows a pause and a rename', (tester) async { + final (_, speech, gateway) = await _reading(tester); + await speech.pause(); + await tester.pump(); + expect(find.text('Paused · Alpha'), findsOneWidget); + + await tester.pumpWidget(_thread(gateway, 's1', title: 'Renamed')); + await tester.pumpAndSettle(); + expect(find.text('Paused · Renamed'), findsOneWidget); + }); + + testWidgets('only the active pane shows the global control', (tester) async { + final (_, _, gateway) = await _reading(tester); + await tester.pumpWidget(_thread(gateway, 's2', pasteTarget: false)); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-speaking-control')), findsNothing); }); } diff --git a/app/test/features/chat/speech/speech_controller_test.dart b/app/test/features/chat/speech/speech_controller_test.dart index f71d9d55..8e864641 100644 --- a/app/test/features/chat/speech/speech_controller_test.dart +++ b/app/test/features/chat/speech/speech_controller_test.dart @@ -143,6 +143,29 @@ void main() { expect(speech.state, SpeechState.idle); }); + testWidgets('reading names the conversation until the reply ends', ( + tester, + ) async { + reader(); + await speech.read(speechMessageId('chat-1', 'm1'), ['Hi'], title: 'One'); + expect( + speech.reading.value, + const SpeechReading(scope: 'chat-1', title: 'One'), + ); + speech.retitle('chat-2', 'Other'); + expect(speech.reading.value?.title, 'One'); + speech.retitle('chat-1', 'Renamed'); + expect(speech.reading.value?.title, 'Renamed'); + + // Another reply replaces it; finishing clears it. + await speech.read(speechMessageId('chat-2', 'm1'), ['Yo'], title: 'Two'); + expect(speech.reading.value?.scope, 'chat-2'); + engine.onStart!(); + engine.onCompletion!(); + expect(speech.reading.value, isNull); + expect(speech.state, SpeechState.idle); + }); + testWidgets('voice and rate are applied and persist across a reload', ( tester, ) async { diff --git a/app/test/features/chat/ui/sessions/chat_sessions_speech_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_speech_test.dart new file mode 100644 index 00000000..47be7a72 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_sessions_speech_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/data/chat_repository.dart'; +import 'package:pipelines_app/features/chat/speech/speech.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart'; + +import '../../speech/fake_speech_engine.dart'; +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +JsonMap _row(String id, {bool closed = false}) => { + 'id': id, + 'title': id, + 'directory': '/w', + if (closed) 'closed_at': '2026-12-03T10:00:00Z', +}; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late FakeChatGateway gateway; + late ChatSessionsController controller; + late SpeechController speech; + + setUp(() async { + speech = installFakeSpeech(FakeSpeechEngine()); + gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [_row('s1'), _row('s2')], + } + ..actionHandler = (_, _) async => const {}; + controller = ChatSessionsController( + ChatRepository(gateway), + localStore: MemoryChatSessionLocalStore(), + ); + addTearDown(controller.dispose); + await controller.refresh(); + await speech.read(speechMessageId('s1', 'r1'), ['Hello.']); + expect(speech.state, SpeechState.speaking); + }); + + test('closing the reading chat stops it', () async { + await controller.close('s1'); + await pumpEventQueue(); + expect(speech.state, SpeechState.idle); + }); + + test('closing another chat keeps reading', () async { + await controller.close('s2'); + await pumpEventQueue(); + expect(speech.state, SpeechState.speaking); + }); + + test('a chat closed on another device stops it on the next read', () async { + gateway.sessionsReply = { + 'chat_sessions': [_row('s1', closed: true), _row('s2')], + }; + await controller.refresh(); + await pumpEventQueue(); + expect(speech.state, SpeechState.idle); + }); + + test('a deleted chat stops it; a failed read does not', () async { + gateway.sessionsHandler = () async => throw StateError('offline'); + await controller.refresh(); + await pumpEventQueue(); + expect(speech.state, SpeechState.speaking); + + gateway + ..sessionsHandler = null + ..sessionsReply = { + 'chat_sessions': [_row('s2')], + }; + await controller.refresh(); + await pumpEventQueue(); + expect(speech.state, SpeechState.idle); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_speaking_badge_test.dart b/app/test/features/chat/ui/sessions/chat_speaking_badge_test.dart new file mode 100644 index 00000000..45adfa2f --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_speaking_badge_test.dart @@ -0,0 +1,104 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/speech/speech.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_awaiting.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_compact_avatar.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_row_content.dart'; + +import '../../speech/fake_speech_engine.dart'; + +const _speaking = Key('chat-row-speaking'); + +Widget _avatars({bool reduceMotion = false}) => MaterialApp( + home: MediaQuery( + data: MediaQueryData(disableAnimations: reduceMotion), + child: const Scaffold( + body: Column( + children: [ + ChatSessionAvatar( + key: Key('one'), + session: {'id': 's1', 'title': 'One'}, + running: true, + awaitingOperator: 2, + ), + ChatSessionAvatar( + key: Key('two'), + session: {'id': 's2', 'title': 'Two'}, + ), + ChatCompactAvatar( + key: Key('two-compact'), + sessionId: 's2', + title: 'Two', + color: Colors.blue, + active: false, + visible: false, + running: false, + backgroundTasks: 0, + unread: false, + ), + ], + ), + ), + ), +); + +Finder _badgeOf(String avatar) => find.descendant( + of: find.byKey(Key(avatar)), + matching: find.byKey(_speaking), +); + +Future _read(WidgetTester tester, SpeechController speech, String chat) => + tester.runAsync(() => speech.read(speechMessageId(chat, 'r1'), ['Hi.'])); + +void main() { + testWidgets('the reading chat wears the speaking badge, and it moves', ( + tester, + ) async { + final speech = installFakeSpeech(FakeSpeechEngine()); + await tester.pumpWidget(_avatars()); + expect(find.byKey(_speaking), findsNothing); + + await _read(tester, speech, 's1'); + await tester.pump(); + expect(_badgeOf('one'), findsOneWidget); + expect(_badgeOf('two'), findsNothing); + expect(_badgeOf('two-compact'), findsNothing); + // Speaking outranks the operator wait and the running spinner. + expect(find.byKey(const Key('chat-row-working')), findsNothing); + expect(find.byType(ChatAwaitingBadge), findsNothing); + + await _read(tester, speech, 's2'); + await tester.pump(); + expect(_badgeOf('one'), findsNothing); + expect(_badgeOf('two'), findsOneWidget); + expect(_badgeOf('two-compact'), findsOneWidget); + expect(find.byKey(const Key('chat-speaking-wave')), findsNWidgets(2)); + + await tester.runAsync(speech.stop); + await tester.pump(); + expect(find.byKey(_speaking), findsNothing); + }); + + testWidgets('a Settings voice sample marks no chat', (tester) async { + final speech = installFakeSpeech(FakeSpeechEngine()); + await tester.pumpWidget(_avatars()); + await tester.runAsync(speech.sample); + await tester.pump(); + expect(speech.state, SpeechState.speaking); + expect(find.byKey(_speaking), findsNothing); + }); + + testWidgets('reduced motion shows a still speaker', (tester) async { + final speech = installFakeSpeech(FakeSpeechEngine()); + await tester.pumpWidget(_avatars(reduceMotion: true)); + // The first chat's spinner gives way to the speaking badge. + await _read(tester, speech, 's1'); + await tester.pump(); + expect(_badgeOf('one'), findsOneWidget); + expect(find.byKey(const Key('chat-speaking-still')), findsOneWidget); + expect(find.byKey(const Key('chat-speaking-wave')), findsNothing); + // Nothing ticks: settling finishes with the badge still shown. + await tester.pumpAndSettle(); + expect(_badgeOf('one'), findsOneWidget); + }); +}