Merge commit '5639e5cb057836100683e8f0c06c1bb70cd71bf0' into pipelines/run-20261113-1605-esc-keeps-background-tasks-stop-tasks-faa1

This commit is contained in:
2026-11-13 16:47:49 +00:00
27 changed files with 803 additions and 54 deletions
@@ -10,6 +10,7 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
bool _chatOwnsKeyboard();
JsonMap? _rowFor(String id);
void _back();
void _openRouted(String id);
bool get _pageOpen;
Widget _thread(ChatWorkspacePane pane);
@@ -185,6 +186,17 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
_usedWorkspace = true;
_workspaceVisible = _workspace.paneCount > 0;
});
// A route can arrive while the local workspace is being restored.
// Re-apply it after restore so the saved active pane cannot overwrite
// an explicit notification or Search selection.
final id = widget.initialSessionId;
if (id != null &&
id.isNotEmpty &&
_workspace.activePane?.sessionId != id) {
_workspaceVisible = true;
_publishedWorkspaceSession = id;
_openRouted(id);
}
_publishWorkspaceRoute();
},
);
+29 -11
View File
@@ -357,6 +357,7 @@ class _ChatScreenState extends State<ChatScreen>
/// Opens the chat the route names. A chat opened for work from elsewhere
/// (Open in chat) goes beside the active chat on a wide layout instead of
/// replacing it, and takes the keyboard once its composer is built.
@override
void _openRouted(String id) {
if (!_runtime.openedForWork.remove(id)) {
_workspace.open(id);
@@ -400,17 +401,34 @@ class _ChatScreenState extends State<ChatScreen>
void didUpdateWidget(covariant ChatScreen oldWidget) {
super.didUpdateWidget(oldWidget);
final reboundWorkspace = _updateWorkspacePersistence(oldWidget);
if (!reboundWorkspace &&
oldWidget.initialSessionId != widget.initialSessionId) {
_workspaceBinding?.changed();
final id = widget.initialSessionId;
if (id != null && id.isNotEmpty) {
_workspaceVisible = true;
_publishedWorkspaceSession = id;
_openRouted(id);
} else if (widget.onSessionSelected != null) {
_workspaceVisible = false;
}
final id = widget.initialSessionId;
final routeChanged = oldWidget.initialSessionId != id;
final targetIsNotActive =
id != null &&
id.isNotEmpty &&
(_workspace.activePane?.sessionId != id || !_workspaceVisible);
if (!reboundWorkspace && (routeChanged || targetIsNotActive)) {
// The parent is rebuilding while didUpdateWidget runs. Opening a pane
// notifies the workspace's ListenableBuilder, which must happen after
// this build rather than during it.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final currentId = widget.initialSessionId;
_workspaceBinding?.changed();
if (currentId != null && currentId.isNotEmpty) {
if (_workspace.activePane?.sessionId == currentId &&
_workspaceVisible) {
return;
}
setState(() {
_workspaceVisible = true;
_publishedWorkspaceSession = currentId;
});
_openRouted(currentId);
} else if (routeChanged && widget.onSessionSelected != null) {
setState(() => _workspaceVisible = false);
}
});
}
// Transcripts read through another gateway belong to that server.
_runtime.gateway = widget.gateway;
@@ -22,6 +22,12 @@ class FlutterTtsSpeechEngine extends SpeechEngine {
TargetPlatform.linux || TargetPlatform.fuchsia => false,
};
@override
bool get supportsVoiceDownloadHint =>
!kIsWeb &&
(defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.macOS);
/// AVSpeechSynthesizer's normal rate is 0.5 on a 0..1 scale; Android's
/// TextToSpeech and the Web Speech API use 1.0 as normal.
bool get _appleScale =>
@@ -106,7 +112,7 @@ class FlutterTtsSpeechEngine extends SpeechEngine {
return [
for (final item in raw is List ? raw : const [])
if (item is Map && item['name'] != null && item['locale'] != null)
SpeechVoice(name: '${item['name']}', locale: '${item['locale']}'),
SpeechVoice.fromPlatform(item.cast<Object?, Object?>()),
];
}
}
@@ -90,7 +90,12 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
_set(SpeechState.speaking);
return _guard(() async {
await engine.setRate(_rate);
await engine.setVoice(voice);
final selected = voice ??
bestSpeechVoice(
await engine.voices(),
WidgetsBinding.instance.platformDispatcher.locale.languageCode,
);
await engine.setVoice(selected);
await engine.speak(document.text);
});
}
@@ -3,13 +3,63 @@ import 'package:flutter/foundation.dart';
/// One platform voice. [locale] is a BCP 47 tag such as `en-GB`.
@immutable
class SpeechVoice {
const SpeechVoice({required this.name, required this.locale});
const SpeechVoice({
required this.name,
required this.locale,
this.qualityRank = 0,
this.networkRequired = false,
});
final String name;
final String locale;
/// A platform-independent quality score: 0 is unknown/compact and 3 is
/// premium, very high, or a browser's natural voice.
final int qualityRank;
final bool networkRequired;
/// The primary language subtag (`en` for `en-GB`), lower case.
String get language => locale.split(RegExp('[-_]')).first.toLowerCase();
bool get isNatural => qualityRank >= 2;
bool get isNovelty => _noveltyVoice.hasMatch(name);
/// Converts the maps returned by flutter_tts on Apple, Android, and web.
factory SpeechVoice.fromPlatform(Map<Object?, Object?> raw) {
final name = '${raw['name'] ?? ''}';
final locale = '${raw['locale'] ?? ''}';
final quality = '${raw['quality'] ?? ''}'.toLowerCase();
final identifier = '${raw['identifier'] ?? ''}'.toLowerCase();
final network = '${raw['network_required'] ?? ''}'.toLowerCase();
var rank = switch (quality) {
'3' => 3,
'2' => 2,
'1' || '0' => 1,
'premium' || 'very high' || 'very_high' => 3,
'enhanced' || 'high' => 2,
'default' ||
'normal' ||
'standard' ||
'low' ||
'very low' ||
'very_low' => 1,
_ => 0,
};
if (identifier.contains('premium') ||
name.toLowerCase().contains(RegExp(r'\b(natural|online|neural)\b')) ||
name.toLowerCase().contains('google ')) {
rank = 3;
} else if (identifier.contains('enhanced')) {
rank = 2;
} else if (identifier.contains('compact')) {
rank = 1;
}
return SpeechVoice(
name: name,
locale: locale,
qualityRank: rank,
networkRequired: network == '1' || network == 'true',
);
}
@override
bool operator ==(Object other) =>
@@ -19,6 +69,32 @@ class SpeechVoice {
int get hashCode => Object.hash(name, locale);
}
final _noveltyVoice = RegExp(
r'\b(bells|bubbles|zarvox|whisper|boing|cellos|good news|jester|organ|superstar|trinoids)\b',
caseSensitive: false,
);
/// Picks the best automatic voice without consulting platform APIs.
SpeechVoice? bestSpeechVoice(List<SpeechVoice> voices, String language) {
final matching = voices.where(
(voice) => voice.language == language.toLowerCase(),
);
if (matching.isEmpty) return null;
final ranked = [...matching]..sort(compareSpeechVoices);
return ranked.first;
}
int compareSpeechVoices(SpeechVoice a, SpeechVoice b) {
final quality = b.qualityRank.compareTo(a.qualityRank);
if (quality != 0) return quality;
final offline = a.networkRequired ? 1 : 0;
final offlineOther = b.networkRequired ? 1 : 0;
if (offline != offlineOther) return offline.compareTo(offlineOther);
if (a.isNovelty != b.isNovelty) return a.isNovelty ? 1 : -1;
final name = a.name.compareTo(b.name);
return name != 0 ? name : a.locale.compareTo(b.locale);
}
/// The platform text-to-speech service the [SpeechController] drives.
///
/// [setRate] takes a multiplier where 1.0 is the platform's normal speed; an
@@ -30,6 +106,12 @@ abstract class SpeechEngine {
/// Whether this platform can speak at all; the UI hides read aloud if not.
bool get supported;
/// Whether this engine can offer the Apple voice-download guidance.
///
/// This is deliberately false by default: only Apple engines have the
/// matching System Settings destination.
bool get supportsVoiceDownloadHint => false;
VoidCallback? onStart;
VoidCallback? onPause;
VoidCallback? onResume;
@@ -23,11 +23,13 @@ class SettingsReadAloudSection extends StatefulWidget {
class _SettingsReadAloudSectionState extends State<SettingsReadAloudSection> {
SpeechController get _speech => widget.controller ?? speechController;
late final Future<List<SpeechVoice>> _voices;
@override
void initState() {
super.initState();
unawaited(_speech.restore());
_voices = _speech.voices();
}
Future<void> _pickVoice() async {
@@ -65,12 +67,13 @@ class _SettingsReadAloudSectionState extends State<SettingsReadAloudSection> {
title: const Text('Voice'),
subtitle: Text(
voice == null
? 'System default'
? 'Automatic (most natural)'
: '${voice.name} · ${voice.locale}',
),
chevron: true,
onTap: () => unawaited(_pickVoice()),
),
_voiceDownloadHint(context),
SettingsGroupItem(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -131,4 +134,38 @@ class _SettingsReadAloudSectionState extends State<SettingsReadAloudSection> {
);
},
);
Widget _voiceDownloadHint(BuildContext context) {
return FutureBuilder<List<SpeechVoice>>(
future: _voices,
builder: (context, snapshot) {
if (!snapshot.hasData ||
!needsSpeechVoiceHint(
snapshot.data!,
View.of(context).platformDispatcher.locale.languageCode,
supportsVoiceDownloadHint:
_speech.engine.supportsVoiceDownloadHint,
)) {
return const SizedBox.shrink();
}
const hint =
'For a more natural voice, download one in System Settings > '
'Accessibility > Spoken Content > System voice > Manage voices.';
return SettingsGroupItem(
key: const Key('settings-read-aloud-voice-hint'),
child: Tooltip(
message: hint,
child: Text(
hint,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
);
},
);
}
}
@@ -4,6 +4,17 @@ import 'package:flutter/material.dart';
import '../chat/speech/speech.dart';
bool needsSpeechVoiceHint(
List<SpeechVoice> voices,
String language, {
bool supportsVoiceDownloadHint = false,
}) {
if (!supportsVoiceDownloadHint) return false;
return voices
.where((voice) => voice.language == language.toLowerCase())
.every((voice) => !voice.isNatural);
}
/// The picker's answer: a voice, or null for the system default.
typedef SpeechVoiceChoice = ({SpeechVoice? voice});
@@ -22,7 +33,7 @@ Future<SpeechVoiceChoice?> showSpeechVoicePicker(
}
/// Voices grouped by language subtag, the [device] language first and the
/// rest by name; voices within a group by name.
/// rest by name; natural voices and offline voices come first within a group.
List<({String language, List<SpeechVoice> voices})> groupSpeechVoices(
List<SpeechVoice> voices,
String device,
@@ -41,11 +52,7 @@ List<({String language, List<SpeechVoice> voices})> groupSpeechVoices(
for (final language in languages)
(
language: language,
voices: groups[language]!
..sort((a, b) {
final name = a.name.compareTo(b.name);
return name != 0 ? name : a.locale.compareTo(b.locale);
}),
voices: groups[language]!..sort(compareSpeechVoices),
),
];
}
@@ -113,7 +120,10 @@ class _VoicePickerDialogState extends State<_VoicePickerDialog> {
contentPadding: const EdgeInsets.symmetric(vertical: 16),
// A list needs a definite width; keep it to a readable dialog measure.
content: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 560),
constraints: BoxConstraints(
maxWidth: 560,
maxHeight: MediaQuery.sizeOf(context).height * .6,
),
child: SizedBox(
width: double.maxFinite,
child: FutureBuilder<List<SpeechVoice>>(
@@ -122,6 +132,17 @@ class _VoicePickerDialogState extends State<_VoicePickerDialog> {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.all(24),
child: Text(
'Voices could not be loaded. You can cancel and try again.',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
);
}
final voices = snapshot.data ?? const <SpeechVoice>[];
return _list(context, groupSpeechVoices(voices, device));
},
@@ -154,9 +175,12 @@ class _VoicePickerDialogState extends State<_VoicePickerDialog> {
Navigator.of(context).pop((voice: voice));
},
child: ListView(
shrinkWrap: true,
primary: false,
children: [
const RadioListTile<String>(value: '', title: Text('System default')),
const RadioListTile<String>(
value: '',
title: Text('Automatic (most natural)'),
),
if (groups.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
@@ -181,7 +205,23 @@ class _VoicePickerDialogState extends State<_VoicePickerDialog> {
Expanded(
child: RadioListTile<String>(
value: _keyOf(voice),
title: Text(voice.name),
title: Row(
children: [
Flexible(child: Text(voice.name)),
if (voice.isNatural)
Padding(
padding: const EdgeInsetsDirectional.only(
start: 8,
),
child: Text(
'Natural',
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.primary,
),
),
),
],
),
subtitle: Text(voice.locale),
),
),