Merge main (Compact design) into Glass

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 23:22:56 +00:00
93 changed files with 4110 additions and 313 deletions
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The find-in-diff field `/` opens: the query, "3 of 12", previous and next
/// match, and close. Enter goes to the next match, Shift+Enter to the
/// previous one, Escape closes.
@@ -38,7 +38,9 @@ class DiffSearchBar extends StatelessWidget {
: '$position of $count';
return Material(
elevation: 3,
borderRadius: BorderRadius.circular(28),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(28)),
color: AppDesignTokens.of(
context,
).solidFill(Theme.of(context).colorScheme.surfaceContainerHigh),
+54 -46
View File
@@ -8,7 +8,10 @@ import 'chat_runtime.dart';
import 'conversation/chat_seen_interaction.dart';
import 'conversation/chat_thread_view.dart';
import 'conversation/composer_focus_request.dart';
import 'domain/chat_colors.dart';
import 'ui/sessions/chat_color_palette.dart';
import 'workspace/chat_pane_commands.dart';
import 'workspace/chat_pane_focus_flash.dart';
/// Where an open chat is shown and what that place alone decides: its Back,
/// its pane menu, whether it takes pastes, and what follows `/new` and
@@ -81,54 +84,59 @@ Widget buildChatPaneContent({
builder: (context) {
final row = runtime.rowFor(sessionId);
final start = runtime.startNotice;
return ChatComposerFocusScope(
return ChatPaneFocusFlash(
sessionId: sessionId,
requests: runtime.composerFocus,
child: ServerContext.forServer(
context,
runtime.serverIdFor(sessionId),
ChatSeenInteraction(
sessionId: sessionId,
onInteract: () => runtime.sessions.reportInteraction(sessionId),
child: ChatThreadView(
key: ValueKey<String>('chat-session-$sessionId'),
gateway: runtime.gatewayFor(sessionId),
requests: runtime.paneFlash,
color: chatColorShade(context, chatSessionColor(row)),
child: ChatComposerFocusScope(
sessionId: sessionId,
requests: runtime.composerFocus,
child: ServerContext.forServer(
context,
runtime.serverIdFor(sessionId),
ChatSeenInteraction(
sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(),
session: row,
initialDraft: runtime.pendingDrafts.remove(sessionId),
syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts,
initialNotice: start != null && start.id == sessionId
? start.notice
: null,
onBack: placement.onBack,
onModelChanged: (applied) =>
runtime.modelChanged(sessionId, applied),
onModeChanged: (mode, name) =>
runtime.acceptMode(sessionId, mode, name),
onEffortChanged: (state) =>
runtime.acceptEffort(sessionId, state),
onNewSession: placement.onNewSession,
onSessionRenamed: (title) =>
runtime.acceptRename(sessionId, title),
onSessionClosed: placement.onSessionClosed,
onColorSelected: (color) =>
runtime.sessions.setColor(sessionId, color),
onNextChat: placement.onNextChat,
useNativeBack: placement.useNativeBack,
pasteTarget: placement.pasteTarget,
ownsPasteWhenFocused: placement.ownsPasteWhenFocused,
showBackButton: placement.showBackButton,
paneControls: placement.paneControls?.call(context) ?? const [],
leadingControl: placement.leadingControl?.call(context),
paneCommands: placement.paneCommands,
onComposerFocus: placement.onComposerFocus,
onComposerReady: (composer) =>
runtime.registerComposer(sessionId, composer),
onComposerDisposed: (composer) =>
runtime.unregisterComposer(sessionId, composer),
onInteract: () => runtime.sessions.reportInteraction(sessionId),
child: ChatThreadView(
key: ValueKey<String>('chat-session-$sessionId'),
gateway: runtime.gatewayFor(sessionId),
sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(),
session: row,
initialDraft: runtime.pendingDrafts.remove(sessionId),
syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts,
initialNotice: start != null && start.id == sessionId
? start.notice
: null,
onBack: placement.onBack,
onModelChanged: (applied) =>
runtime.modelChanged(sessionId, applied),
onModeChanged: (mode, name) =>
runtime.acceptMode(sessionId, mode, name),
onEffortChanged: (state) =>
runtime.acceptEffort(sessionId, state),
onNewSession: placement.onNewSession,
onSessionRenamed: (title) =>
runtime.acceptRename(sessionId, title),
onSessionClosed: placement.onSessionClosed,
onColorSelected: (color) =>
runtime.sessions.setColor(sessionId, color),
onNextChat: placement.onNextChat,
useNativeBack: placement.useNativeBack,
pasteTarget: placement.pasteTarget,
ownsPasteWhenFocused: placement.ownsPasteWhenFocused,
showBackButton: placement.showBackButton,
paneControls: placement.paneControls?.call(context) ?? const [],
leadingControl: placement.leadingControl?.call(context),
paneCommands: placement.paneCommands,
onComposerFocus: placement.onComposerFocus,
onComposerReady: (composer) =>
runtime.registerComposer(sessionId, composer),
onComposerDisposed: (composer) =>
runtime.unregisterComposer(sessionId, composer),
),
),
),
),
+5
View File
@@ -17,6 +17,7 @@ import 'data/chat_recency.dart';
import 'data/chat_repository.dart';
import 'ui/sessions/chat_sessions_body.dart';
import 'ui/sessions/chat_sessions_controller.dart';
import 'workspace/chat_pane_focus_flash.dart';
/// What open chats share for one server, wherever they are shown (the Chat
/// destination's tiling or a floating window): the session list, the rows
@@ -134,6 +135,9 @@ class ChatRuntime extends ChangeNotifier {
/// Puts the keyboard in an opened chat's composer once it is built.
final ChatComposerFocusRequests composerFocus = ChatComposerFocusRequests();
/// Flashes the focus ring of the pane the keyboard just moved to.
final ChatPaneFlashRequests paneFlash = ChatPaneFlashRequests();
/// The Chat destination's quick switcher, toggled by Ctrl+K / Alt+K there.
final ChatQuickSwitchRequests quickSwitch = ChatQuickSwitchRequests();
@@ -296,6 +300,7 @@ class ChatRuntime extends ChangeNotifier {
sessions.dispose();
folds.dispose();
composerFocus.dispose();
paneFlash.dispose();
composers.clear();
_pendingAppends.clear();
super.dispose();
@@ -0,0 +1,86 @@
part of 'screen.dart';
/// A chat pane the keyboard can move to: a tiled pane or a floating window.
class _PaneCycleTarget {
const _PaneCycleTarget.pane(this.paneId, this.sessionId) : window = null;
_PaneCycleTarget.window(WindowEntry this.window)
: paneId = null,
sessionId = window.contentId;
final String? paneId;
final WindowEntry? window;
final String sessionId;
}
/// Alt+] and Alt+[ (also Cmd+] and Cmd+[ on Apple platforms, see
/// [chatPaneCycleShortcut]) move the keyboard to the next or previous chat
/// pane on screen: the tiled panes in their visual order (left to right,
/// then top to bottom, as the split tree lays them out; the center stage's
/// row in order), then the shown floating chat windows in the order they
/// were opened, wrapping around. The pane's composer takes the keyboard and
/// its focus ring flashes in the chat's colour. Nothing opens or closes.
///
/// It does nothing with one pane on screen, on a phone layout (the chat
/// stack and the quick switcher own moving between chats there), over a
/// popup or another destination, and while a terminal has the keyboard,
/// which keeps its Alt keys. Handled before the focus tree, so it works from
/// a composer and the web build stops the browser's own use of the keys.
mixin _ChatScreenPaneCycle on State<ChatScreen>, _ChatScreenWorkspace {
ChatRuntime get _runtime;
bool _paneCycleKey(KeyEvent event) {
final step = chatPaneCycleShortcut(event, HardwareKeyboard.instance);
if (step == null ||
!mounted ||
primaryFocusIsTypingSurface() ||
!_workspaceVisible ||
!showsListBesideDetail(context) ||
!_chatOwnsKeyboard()) {
return false;
}
final order = _paneCycleOrder();
final target = chatPaneCycleTarget(order, _paneCycleCurrent(order), step);
if (target == null) return false;
// A held chord is swallowed; only its first press moves.
if (event is KeyDownEvent) _focusPaneCycleTarget(target);
return true;
}
/// The panes on screen, in cycling order.
List<_PaneCycleTarget> _paneCycleOrder() {
final visible = _visibleSidebarSessions;
return [
for (final pane in _workspace.panes)
if (visible.contains(pane.sessionId))
_PaneCycleTarget.pane(pane.id, pane.sessionId),
for (final window
in widget.windows?.shownInOpenOrder() ?? const <WindowEntry>[])
_PaneCycleTarget.window(window),
];
}
/// Where the keyboard is in [order]: the floating chat window holding it,
/// otherwise the active tiled pane (also while the chat list has it).
int _paneCycleCurrent(List<_PaneCycleTarget> order) {
final window = keyboardWindow()?.entry;
if (window != null && window.kind == chatWindowKind) {
return order.indexWhere((target) => target.window?.id == window.id);
}
final active = _workspace.activePaneId;
return order.indexWhere((target) => target.paneId == active);
}
void _focusPaneCycleTarget(_PaneCycleTarget target) {
final window = target.window;
final windows = widget.windows;
if (window != null && windows != null) {
windows.manager.raise(window.id);
windows.kind.focusContent(window);
} else if (target.paneId case final paneId?) {
_workspace.activate(paneId);
_composerFocus.request(target.sessionId);
}
_runtime.paneFlash.flash(target.sessionId);
WidgetsBinding.instance.ensureVisualUpdate();
}
}
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import '../../../ui/theme/app_design_tokens.dart';
import 'chat_bar_tint.dart';
/// The conversation bar's model and mode controls read as the bar's other
@@ -18,7 +19,13 @@ ButtonStyle chatBarTextButtonStyle(
// The same 12 px each side as an icon button's glyph inside its 48 px
// target, so text sits off its hover/press shape as it does top and bottom.
padding: compact ? null : chatBarButtonPadding,
minimumSize: compact ? null : const Size.square(kMinInteractiveDimension),
minimumSize: compact
? null
: Size.square(
AppDesignTokens.of(context).density.dense
? 32
: kMinInteractiveDimension,
),
);
/// Horizontal padding inside the bar's text buttons (model, mode).
@@ -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);
@@ -1061,7 +1061,15 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
builder: (context, constraints) => Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_attach(context),
// A dense design's 32px attach centres
// on the 40px send button's line.
if (AppDesignTokens.of(context).density.dense)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: _attach(context),
)
else
_attach(context),
Expanded(
child: Focus(
canRequestFocus: false,
@@ -1329,7 +1337,12 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
// The pill draws the field's surface; the field adds no border.
border: InputBorder.none,
isDense: true,
contentPadding: const EdgeInsets.symmetric(vertical: 12),
// A dense design's slim composer: one line as tall as the 40px send
// button (every design pins it), so the pill is 48px. Its compact
// density takes 4px off each of these 14.
contentPadding: EdgeInsets.symmetric(
vertical: AppDesignTokens.of(context).density.dense ? 14 : 12,
),
),
);
}
@@ -71,7 +71,9 @@ class _ChatFindBarState extends State<ChatFindBar> {
color: AppDesignTokens.of(
context,
).solidFill(scheme.surfaceContainerHigh),
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
child: ListenableBuilder(
@@ -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<ChatThreadView> 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<ChatThreadView> 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<ChatThreadView> 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<ChatThreadView> 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,
);
},
),
+6
View File
@@ -23,11 +23,13 @@ import '../../core/api_gateway.dart';
import '../../core/servers/server_context.dart';
import '../../core/servers/server_scope.dart';
import '../../shell/detached/detached_window_scope.dart';
import '../../shell/windows/window_entry.dart';
import '../../shell/windows/window_scope.dart';
import 'shell/chat_shell_dismiss.dart';
import '../terminal/terminal_open_action.dart';
import 'ui/sessions/session_pane_menu.dart';
import 'workspace/chat_pane_commands.dart';
import 'workspace/chat_pane_cycle.dart';
import 'workspace/chat_float_shortcut.dart';
import 'workspace/chat_workspace_binding.dart';
import 'workspace/chat_workspace_snapshot.dart';
@@ -70,6 +72,7 @@ import '../../ui/input/keyboard_owner.dart';
part 'chat_screen_attention.dart';
part 'chat_screen_float.dart';
part 'chat_screen_pane_cycle.dart';
part 'chat_screen_pane_menu.dart';
part 'chat_screen_keys.dart';
part 'chat_screen_list_toggle.dart';
@@ -137,6 +140,7 @@ class _ChatScreenState extends State<ChatScreen>
_ChatScreenWorkspace,
_ChatScreenKeys,
_ChatScreenFloat,
_ChatScreenPaneCycle,
_ChatScreenPaneMenu,
_ChatScreenQuickSwitch,
_ChatScreenAttention,
@@ -194,6 +198,7 @@ class _ChatScreenState extends State<ChatScreen>
_bindWorkspacePersistence();
HardwareKeyboard.instance.addHandler(_cycleChatKey);
HardwareKeyboard.instance.addHandler(_slashFocusKey);
HardwareKeyboard.instance.addHandler(_paneCycleKey);
// Seen from now on, so the press that chooses the first chat counts.
LastPointerKind.instance;
_sessions.addListener(_nextChanged);
@@ -484,6 +489,7 @@ class _ChatScreenState extends State<ChatScreen>
_paneCommands.dispose();
HardwareKeyboard.instance.removeHandler(_cycleChatKey);
HardwareKeyboard.instance.removeHandler(_slashFocusKey);
HardwareKeyboard.instance.removeHandler(_paneCycleKey);
_page.dispose();
_workspaceBinding?.dispose();
_openWorkspace?.dispose();
@@ -72,7 +72,9 @@ class _ChatShellTerminalFindBarState extends State<ChatShellTerminalFindBar> {
color: AppDesignTokens.of(
context,
).solidFill(scheme.surfaceContainerHigh),
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
child: ListenableBuilder(
@@ -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>(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<SpeechReading?> get speechReading => _reading;
SpeechController? _speech;
final _reading = _AppSpeechReading();
T _bind<T extends SpeechController?>(T controller) {
_reading.bind(controller);
return controller;
}
class _AppSpeechReading extends ChangeNotifier
implements ValueListenable<SpeechReading?> {
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();
}
}
+3
View File
@@ -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';
@@ -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<SpeechRange?>(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<SpeechReading?>(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<void> read(String id, List<String> 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<void> read(
String id,
List<String> 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<void> _speak(String id, SpeechDocument document, SpeechVoice? voice) {
Future<void> _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<void> 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<void> 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);
}
@@ -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<SpeechOrigin>();
@override
bool updateShouldNotify(SpeechOrigin oldWidget) => false;
}
@@ -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);
}
@@ -1,6 +1,7 @@
import '../../../../ui/adaptive/segmented_bar_overflow.dart';
import 'package:flutter/material.dart';
import '../../../../ui/status/app_spinner.dart';
import '../../../../ui/theme/app_design_tokens.dart';
class ChatBarAction extends StatelessWidget implements SegmentedOverflowable {
const ChatBarAction({
@@ -220,7 +221,9 @@ class ChatUndoBar extends StatelessWidget {
);
return Material(
elevation: 3,
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: content,
);
@@ -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,
@@ -14,6 +14,7 @@ import 'session_row_style.dart';
import '../../domain/chat_list_activity.dart';
import 'chat_sessions_body.dart';
import 'chat_sessions_controller.dart';
import '../../../../ui/theme/app_design_tokens.dart';
/// A small, scrollable device-local rail. Full titles remain accessible.
class ChatCompactSidebar extends StatelessWidget {
@@ -102,6 +103,7 @@ class ChatCompactSidebar extends StatelessWidget {
awaitingOperator: awaitingOperator,
backgroundTasks: backgroundTasks,
unread: unread,
sessionId: id,
),
if (machineName case final name?)
Text(
@@ -147,7 +149,9 @@ class ChatCompactSidebar extends StatelessWidget {
data: row,
feedback: Material(
elevation: 4,
borderRadius: BorderRadius.circular(20),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(20)),
child: Chip(
avatar: ChatCompactAvatar(
title: title,
@@ -158,6 +162,7 @@ class ChatCompactSidebar extends StatelessWidget {
awaitingOperator: awaitingOperator,
backgroundTasks: backgroundTasks,
unread: unread,
sessionId: id,
),
label: Text(title),
),
@@ -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<String> 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
@@ -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) {
@@ -6,7 +6,6 @@ import '../../../../ui/layout/app_list_avatar.dart';
import '../../../../ui/layout/app_list_row.dart';
import '../../../../ui/text/relative_time_label.dart';
import '../../../../ui/motion/container_transform_source.dart';
import '../../../../ui/theme/app_design_tokens.dart';
import '../../domain/chat_colors.dart';
import '../../domain/chat_list_activity.dart';
import '../../domain/chat_sessions.dart';
@@ -14,11 +13,13 @@ 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';
import 'session_row_style.dart';
import 'chat_awaiting.dart';
import '../../../../ui/theme/app_design_tokens.dart';
/// One chat in the list, in the app's shared row on both hosts: the harness
/// avatar, the title with its recency, one muted line, and the actions menu.
@@ -93,7 +94,9 @@ class ChatSessionRow extends StatelessWidget {
data: session,
feedback: Material(
elevation: 4,
borderRadius: BorderRadius.circular(20),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(20)),
child: Chip(
avatar: ChatSessionAvatar(session: session),
label: Text(chatSessionTitle(session)),
@@ -278,15 +281,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),
);
}
}
@@ -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),
),
],
),
),
),
),
);
}
}
@@ -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<ChatSpeakingGlyph> createState() => _ChatSpeakingGlyphState();
}
class _ChatSpeakingGlyphState extends State<ChatSpeakingGlyph>
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<double> 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;
}
@@ -71,8 +71,10 @@ class ChatAutomatedPromptCard extends StatelessWidget {
],
),
);
final transcript = AppDesignTokens.of(context).transcript;
final glass = AppDesignTokens.of(context).glass;
final tokens = AppDesignTokens.of(context);
final density = tokens.density;
final transcript = tokens.transcript;
final glass = tokens.glass;
final card = transcript == TranscriptStyle.manuscript
? PaperEditorialNote(
label: label,
@@ -90,16 +92,21 @@ class ChatAutomatedPromptCard extends StatelessWidget {
// edge.
shape: glass == null
? RoundedRectangleBorder(
borderRadius: _noteCorners,
borderRadius: tokens.corners(_noteCorners),
side: BorderSide(color: scheme.outlineVariant),
)
: GlassBorder(
borderRadius: _noteCorners,
borderRadius: tokens.corners(_noteCorners),
highlight: glass.highlight,
edge: glass.edge,
),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 8, 14, 10),
padding: EdgeInsets.fromLTRB(
density.inset(14),
density.space(8),
density.inset(14),
density.space(10),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -166,7 +166,11 @@ class ChatCodeCopyRegion extends StatelessWidget {
key: const Key('chat-code-header'),
color: headerFill(context),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
// Its label starts at the code's own inset (tighter when dense).
padding: EdgeInsetsDirectional.only(
start: AppDesignTokens.of(context).density.space(12),
end: 4,
),
child: Row(
children: [
Expanded(child: label),
@@ -272,7 +272,9 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
code: code,
label: Text(markdownCodeLabel(language), style: labelStyle),
child: Padding(
padding: const EdgeInsets.all(12),
padding: EdgeInsets.all(
AppDesignTokens.of(context).density.space(12),
),
child: ChatTranscriptHorizontalScrollView(
label: 'code block',
child: Text.rich(
@@ -570,9 +572,15 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
/// a tighter line, as a technical book does.
TextStyle _codeStyle(BuildContext context) {
const mono = TextStyle(fontFamily: appMonospaceFamily);
final reading = AppDesignTokens.of(context).reading;
if (reading.family == null) return mono;
final tokens = AppDesignTokens.of(context);
final reading = tokens.reading;
final size = DefaultTextStyle.of(context).style.fontSize ?? 16;
// A dense design sets code at its body size (13 beside 14px prose): the
// monospace runs wider than the prose face.
if (reading.family == null && tokens.density.dense) {
return mono.copyWith(fontSize: size * 13 / 14, height: 1.4);
}
if (reading.family == null) return mono;
return mono.copyWith(
fontSize: size * 0.82,
height: 1.45,
@@ -59,7 +59,10 @@ class ChatUserBubble extends StatelessWidget {
// scrolls, so it never filters what is behind it).
final glass = AppDesignTokens.of(context).glass;
// A Material surface (not a bare DecoratedBox) so a disclosure ListTile
// inside the bubble keeps its ink and background.
// inside the bubble keeps its ink and background. A dense design draws
// a tighter bubble in its own corners.
final tokens = AppDesignTokens.of(context);
final density = tokens.density;
return Material(
color: chatBubbleFill(
context,
@@ -67,13 +70,21 @@ class ChatUserBubble extends StatelessWidget {
),
clipBehavior: Clip.antiAlias,
shape: glass == null
? const RoundedRectangleBorder(borderRadius: _radius)
? RoundedRectangleBorder(borderRadius: tokens.corners(_radius))
: GlassBorder(
borderRadius: _radius,
borderRadius: tokens.corners(_radius),
highlight: glass.highlight,
edge: glass.edge,
),
child: Padding(padding: _padding, child: child),
child: Padding(
padding: density.dense
? EdgeInsets.symmetric(
horizontal: density.inset(_padding.left),
vertical: density.space(_padding.top),
)
: _padding,
child: child,
),
);
}
}
@@ -99,8 +110,10 @@ TextStyle? chatMessageTextStyle(BuildContext context) => AppDesignTokens.of(
/// The empty-line gap between two paragraphs of a reply: about one line of
/// body text at [fontSize] (else the ambient text size), scaled by the
/// operator's text scaling, so chunks read as separate paragraphs.
/// operator's text scaling, so chunks read as separate paragraphs. A design
/// may set a tighter gap ([ReadingType.paragraphGap]).
double chatParagraphGap(BuildContext context, [double? fontSize]) {
final size = fontSize ?? DefaultTextStyle.of(context).style.fontSize ?? 14;
return MediaQuery.textScalerOf(context).scale(size) * 0.9;
return MediaQuery.textScalerOf(context).scale(size) *
AppDesignTokens.of(context).reading.paragraphGap;
}
@@ -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);
@@ -83,7 +83,8 @@ class ChatMessageView extends StatelessWidget {
// A terminal or manuscript transcript reads top to bottom: the
// operator's prompt line or block quote starts at the same edge as the
// answer and spans its column.
final transcript = AppDesignTokens.of(context).transcript;
final tokens = AppDesignTokens.of(context);
final transcript = tokens.transcript;
final trailingUser =
user && !automated && transcript == TranscriptStyle.bubbles;
// No visible role label: side and surface say who spoke and the row's
@@ -104,9 +105,12 @@ class ChatMessageView extends StatelessWidget {
label: '$role message',
child: Padding(
// A manuscript leaves a little more air between turns, as a page
// spaces its paragraphs, since no bubble sets them apart.
// spaces its paragraphs, since no bubble sets them apart; a dense
// design a little less.
padding: EdgeInsets.symmetric(
vertical: transcript == TranscriptStyle.manuscript ? 12 : 6,
vertical: transcript == TranscriptStyle.manuscript
? 12
: tokens.density.space(6),
),
child: LayoutBuilder(
builder: (context, constraints) => Align(
@@ -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),
);
}
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
@@ -123,7 +124,8 @@ class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
: DateTime.now().difference(started);
final seconds = duration.inSeconds.clamp(0, 2147483647);
final label = '${data.label}${widget.streaming ? ' ${seconds}s' : ''}';
switch (AppDesignTokens.of(context).transcript) {
final tokens = AppDesignTokens.of(context);
switch (tokens.transcript) {
case TranscriptStyle.prompt:
return TerminalActivityRows(
data: data,
@@ -145,8 +147,12 @@ class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
}
// Desktop hover hugs the label; phones keep the full-width touch row.
final compact = prefersCompactHitTargets(context);
// A dense design draws the line slimmer on a pointer device; a touch
// device keeps a 40px target.
final density = tokens.density;
final dense = density.dense;
final content = ConstrainedBox(
constraints: const BoxConstraints(minHeight: 32),
constraints: BoxConstraints(minHeight: dense ? 20 : 32),
child: Row(
mainAxisSize: compact ? MainAxisSize.min : MainAxisSize.max,
children: [
@@ -157,7 +163,7 @@ class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
child: const ChatResponsePending(),
),
),
const SizedBox(width: 8),
SizedBox(width: density.space(8)),
],
Flexible(
child: Text(
@@ -179,8 +185,13 @@ class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
final button = TextButton(
key: const Key('chat-turn-activity'),
style: TextButton.styleFrom(
minimumSize: const Size(0, 48),
padding: const EdgeInsets.all(chatAgentContentInset),
minimumSize: Size(0, dense ? math.max(28, density.minTouchRow) : 48),
padding: dense
? const EdgeInsets.symmetric(
horizontal: chatAgentContentInset,
vertical: 4,
)
: const EdgeInsets.all(chatAgentContentInset),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignment: AlignmentDirectional.centerStart,
),
@@ -113,9 +113,9 @@ class _ChatTurnChipState extends State<ChatTurnChip> {
borderRadius: corners,
onTap: _show,
child: Padding(
padding: const EdgeInsets.symmetric(
padding: EdgeInsets.symmetric(
horizontal: chatAgentContentInset,
vertical: 6,
vertical: AppDesignTokens.of(context).density.space(6),
),
child: content,
),
@@ -0,0 +1,76 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// The step Alt+] (1) or Alt+[ (-1) moves the keyboard between the chat
/// panes on screen, or null for any other key. On Apple platforms Cmd+] and
/// Cmd+[ do the same.
///
/// Why these keys:
/// - Alt+Tab and Cmd+Tab are the system's window switchers, Ctrl+Tab cycles
/// the open chats (and the browser keeps it), and Alt+` already cycles the
/// floating windows.
/// - Browsers use Alt+Left/Right for back and forward; nothing on GNOME,
/// Hyprland, Windows or a browser binds Alt+[ or Alt+].
/// - Option+] and Option+[ type quotes on a Mac, so with Alt the key is
/// matched by its position (also catching layouts whose bracket keys type
/// something else). Cmd+] and Cmd+[ are the Mac's own next/previous pair
/// and leave Option free for typing.
/// - AltGr is how several layouts type brackets, so it never matches.
///
/// Shift never matches: Alt+Shift+[ types braces. A focused terminal keeps
/// these keys (Alt+[ is its escape prefix); the caller checks that.
int? chatPaneCycleShortcut(
KeyEvent event,
HardwareKeyboard keyboard, {
TargetPlatform? platform,
}) {
if (event is KeyUpEvent ||
keyboard.isShiftPressed ||
keyboard.isControlPressed ||
keyboard.isLogicalKeyPressed(LogicalKeyboardKey.altGraph)) {
return null;
}
final alt = keyboard.isAltPressed;
final meta = keyboard.isMetaPressed;
final int? step;
if (alt && !meta) {
step = switch (event.physicalKey) {
PhysicalKeyboardKey.bracketRight => 1,
PhysicalKeyboardKey.bracketLeft => -1,
_ => null,
};
} else if (meta && !alt && _apple(platform ?? defaultTargetPlatform)) {
step =
event.logicalKey == LogicalKeyboardKey.bracketRight ||
event.physicalKey == PhysicalKeyboardKey.bracketRight
? 1
: event.logicalKey == LogicalKeyboardKey.bracketLeft ||
event.physicalKey == PhysicalKeyboardKey.bracketLeft
? -1
: null;
} else {
step = null;
}
return step;
}
bool _apple(TargetPlatform platform) =>
platform == TargetPlatform.macOS || platform == TargetPlatform.iOS;
/// The forward and backward chords as this platform reads them, for the
/// shortcuts list.
String chatPaneCycleShortcutLabel([TargetPlatform? platform]) =>
_apple(platform ?? defaultTargetPlatform)
? 'Option+], Option+[, Cmd+], Cmd+['
: 'Alt+], Alt+[';
/// The entry [step] places from [current] in [order], wrapping around; null
/// when there is no other entry to move to. A [current] outside [order]
/// starts from the first entry going forward and the last going back.
T? chatPaneCycleTarget<T>(List<T> order, int current, int step) {
if (order.length < 2 || step == 0) return null;
if (current < 0 || current >= order.length) {
return step > 0 ? order.first : order.last;
}
return order[(current + step) % order.length];
}
@@ -0,0 +1,147 @@
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// Asks the chat pane showing a session to flash its focus ring, once the
/// keyboard moved there by the pane-cycling chord (see
/// [chatPaneCycleShortcut]). Shared by the tiling and the floating windows.
class ChatPaneFlashRequests extends ChangeNotifier {
String? _sessionId;
int _serial = 0;
/// The session last asked to flash.
String? get sessionId => _sessionId;
/// Advances on every request, so asking the same pane again flashes again.
int get serial => _serial;
void flash(String sessionId) {
_sessionId = sessionId;
_serial++;
notifyListeners();
}
}
/// How long the ring shows before it is gone.
const chatPaneFlashDuration = Duration(milliseconds: 700);
/// The ring's width, in logical pixels.
const chatPaneFlashWidth = 2.0;
/// One chat pane's focus cue: a ring in the chat's [color] drawn over the
/// pane, fading out, when [requests] names [sessionId]. Under reduced motion
/// the ring shows for the same time without fading. It also holds a focus
/// node around the pane: when nothing inside the pane took the keyboard
/// (the composer is not there or cannot be focused), the pane itself does.
class ChatPaneFocusFlash extends StatefulWidget {
const ChatPaneFocusFlash({
super.key,
required this.sessionId,
required this.requests,
required this.color,
required this.child,
});
final String sessionId;
final ChatPaneFlashRequests requests;
final Color? color;
final Widget child;
@override
State<ChatPaneFocusFlash> createState() => _ChatPaneFocusFlashState();
}
class _ChatPaneFocusFlashState extends State<ChatPaneFocusFlash>
with SingleTickerProviderStateMixin {
late final AnimationController _ring = AnimationController(
vsync: this,
duration: chatPaneFlashDuration,
);
final FocusNode _pane = FocusNode(
debugLabel: 'Chat pane',
skipTraversal: true,
);
int _seen = 0;
@override
void initState() {
super.initState();
_seen = widget.requests.serial;
widget.requests.addListener(_requested);
}
@override
void didUpdateWidget(ChatPaneFocusFlash oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.requests != widget.requests) {
oldWidget.requests.removeListener(_requested);
widget.requests.addListener(_requested);
_seen = widget.requests.serial;
}
}
@override
void dispose() {
widget.requests.removeListener(_requested);
_ring.dispose();
_pane.dispose();
super.dispose();
}
void _requested() {
final requests = widget.requests;
if (requests.serial == _seen) return;
_seen = requests.serial;
if (requests.sessionId != widget.sessionId) return;
_ring.forward(from: 0);
// The composer takes its request after a frame; look a frame later.
SchedulerBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
SchedulerBinding.instance
..addPostFrameCallback((_) {
if (mounted && !_pane.hasFocus) _pane.requestFocus();
})
..ensureVisualUpdate();
});
}
@override
Widget build(BuildContext context) {
final color = widget.color ?? Theme.of(context).colorScheme.primary;
final still = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
final radius = AppDesignTokens.of(context).radius ?? 0;
return Focus(
focusNode: _pane,
child: Stack(
fit: StackFit.passthrough,
children: [
widget.child,
Positioned.fill(
child: IgnorePointer(
child: AnimatedBuilder(
animation: _ring,
builder: (context, _) {
if (!_ring.isAnimating) return const SizedBox.shrink();
final fade = still
? 1.0
: 1 - Curves.easeIn.transform(_ring.value);
return DecoratedBox(
key: const ValueKey('chat-pane-focus-flash'),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(radius),
border: Border.all(
color: color.withValues(alpha: color.a * fade),
width: chatPaneFlashWidth,
),
),
);
},
),
),
),
],
),
);
}
}
@@ -107,6 +107,7 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
edges: edges,
extents: extents,
labelExtents: labelExtents,
metrics: graphMetricsOf(context),
);
return (layout, routing);
}
@@ -1,6 +1,8 @@
import 'package:flutter/material.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../layout/layout_models.dart';
import '../layout/linear_graph_layout.dart';
import '../routing/route_models.dart';
/// Centralized graph spacing, not component dimensions. Rank separation follows
@@ -27,6 +29,25 @@ RoutingConfig graphCanvasRoutingConfig() => RoutingConfig(
boundsPadding: 12,
);
/// The drawing's spacings under the design at [context]: the web's metrics,
/// or a dense design's tighter gaps, lanes and padding (Compact), so its
/// smaller nodes are not left adrift in a comfortable layout.
LinearGraphMetrics graphMetricsOf(BuildContext context) =>
AppDesignTokens.of(context).density.dense
? _denseGraphMetrics
: const LinearGraphMetrics();
const LinearGraphMetrics _denseGraphMetrics = LinearGraphMetrics(
hGap: 32,
pad: 16,
laneSpacing: 20,
terminalGap: 16,
trackStep: 16,
portSpacing: 8,
labelPadding: 6,
labelGap: 2,
);
/// The native theme roles one definition graph canvas needs.
///
/// No palette, font family or size is defined here: every value comes from the
@@ -1,6 +1,9 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../../ui/status/run_status_icon.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../domain/graph_definition.dart';
/// One content-sized stage node as an ordinary native control.
@@ -56,7 +59,7 @@ class GraphStageNode extends StatelessWidget {
button: true,
selected: selected,
label: _label,
child: _materialCard(onPressed, content),
child: _materialCard(context, onPressed, content),
),
);
return active ? StageActivityHalo(child: control) : control;
@@ -66,13 +69,29 @@ class GraphStageNode extends StatelessWidget {
/// which assumes one line and cuts into a wrapped label's first and last
/// line. A card keeps the rounded-rectangle surface the web node uses, and
/// [selected] only chooses between two stock emphasis levels.
Widget _materialCard(VoidCallback onPressed, Widget content) {
Widget _materialCard(
BuildContext context,
VoidCallback onPressed,
Widget content,
) {
// A dense design draws a smaller node: half the inset and a 32px
// least height on a pointer device (40px on touch).
final density = AppDesignTokens.of(context).density;
final body = InkWell(
onTap: onPressed,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: kMinInteractiveDimension),
constraints: BoxConstraints(
minHeight: density.dense
? math.max(32, density.minTouchRow)
: kMinInteractiveDimension,
),
child: Padding(
padding: _contentPadding,
padding: density.dense
? EdgeInsets.symmetric(
horizontal: density.space(_contentPadding.left) + 4,
vertical: density.space(_contentPadding.top),
)
: _contentPadding,
child: Align(
// A terminal box widens to give each incoming route its own port;
// its label stays centred in it.
@@ -140,6 +140,7 @@ class _RunGraphViewState extends State<RunGraphView> {
edges: edges,
extents: extents,
labelExtents: labelExtents,
metrics: graphMetricsOf(context),
);
return (layout, routing);
}
@@ -4,6 +4,7 @@ import '../../../ui/status/run_status_icon.dart';
import '../../../ui/text/monospace.dart';
import '../../chat/ui/transcript/chat_markdown_view.dart';
import '../domain/check_step_output.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The note under a command whose recorded output the server cut short.
const String checkOutputTruncated =
@@ -99,7 +100,9 @@ class RunCheckCommandRow extends StatelessWidget {
DecoratedBox(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
),
child: Padding(
padding: const EdgeInsets.all(12),
@@ -12,6 +12,7 @@ import '../../../ui/layout/sticky_section.dart';
import '../../../ui/text/live_elapsed_builder.dart';
import '../../../ui/text/monospace.dart';
import '../../../ui/adaptive/floating_bar_layout.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The Summary tab: the run's identity, the recorded facts as one grid,
/// the stored original prompt with its copy control and the collapsible Input
@@ -231,7 +232,9 @@ Widget _materialBlock(BuildContext context, DetailSummaryRow row) {
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
),
child: SelectableText(
row.value,
@@ -9,6 +9,7 @@ import '../../../ui/text/live_elapsed_builder.dart';
import '../../pipelines/pipeline_format.dart' show formatDuration;
import '../domain/run_models.dart';
import 'run_detail_content.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The Timeline tab's recorded visits, one shared list row per visit.
///
@@ -116,7 +117,9 @@ class RunTimelineRow extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(10),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(10)),
),
child: Text(
label,
@@ -5,6 +5,7 @@ import '../../../core/transport/pipelines_client.dart'
show configuredGatewayEndpoint;
import '../../../ui/layout/app_list_avatar.dart';
import '../../../ui/layout/app_overflow_menu.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../../artifacts/domain/artifact_kind.dart';
import '../../artifacts/domain/artifact_record.dart';
import '../../artifacts/ui/artifact_tile.dart';
@@ -48,9 +49,11 @@ Widget? searchArtifactThumbnail(BuildContext context, JsonMap hit) {
return null;
}
return ClipRRect(
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
child: SizedBox.square(
dimension: kAppListAvatarSize,
dimension: appListAvatarSize(context),
child: ArtifactThumbnail(
key: ValueKey('search.thumbnail.${hit['target']}'),
artifact: record,
@@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
import '../chat/workspace/chat_center_stage_controller.dart';
import '../chat/workspace/chat_float_shortcut.dart';
import '../chat/workspace/chat_list_hidden_controller.dart';
import '../chat/workspace/chat_pane_cycle.dart';
import '../terminal/terminal_shortcuts.dart';
import '../../shell/detached/detached_window_scope.dart';
import '../../shell/windows/window_shortcuts.dart';
@@ -197,6 +198,13 @@ class KeyboardShortcutRegistry {
action: 'Focus the neighbouring chat pane',
keys: _apple ? 'Cmd+Shift+Arrows' : 'Ctrl+Shift+Arrows',
),
KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat,
action: 'Next or previous chat pane on screen',
keys: chatPaneCycleShortcutLabel(platform),
caveat:
'On a wide window with more than one chat shown: the tiled panes left to right, then top to bottom, then the floating chat windows, wrapping around. The pane\'s message input takes the keyboard and its border flashes. No chat opens or closes. In the terminal the keys go to the terminal.',
),
KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat,
action: 'Move the active chat pane',
@@ -56,6 +56,7 @@ class SettingsDesignSection extends StatelessWidget {
subtitle: Text(design.description),
secondary: DesignSwatchPreview(
swatch: design.swatch(Theme.of(context).brightness),
lines: design.swatchLines,
),
),
],
@@ -64,12 +65,14 @@ class SettingsDesignSection extends StatelessWidget {
);
}
/// A design's small preview in the picker: its page with a line of its ink
/// and a dot of its accent, framed by a hairline.
/// A design's small preview in the picker: its page with [lines] lines of
/// its ink (the last one short) and a dot of its accent, framed by a
/// hairline. A dense design draws more, tighter lines in the same page.
class DesignSwatchPreview extends StatelessWidget {
const DesignSwatchPreview({super.key, required this.swatch});
const DesignSwatchPreview({super.key, required this.swatch, this.lines = 2});
final DesignSwatch swatch;
final int lines;
@override
Widget build(BuildContext context) => ExcludeSemantics(
@@ -89,10 +92,14 @@ class DesignSwatchPreview extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(height: 2, color: swatch.ink),
for (var line = 1; line < lines; line += 1)
Container(height: lines > 2 ? 1 : 2, color: swatch.ink),
FractionallySizedBox(
widthFactor: 0.6,
child: Container(height: 2, color: swatch.ink),
child: Container(
height: lines > 2 ? 1 : 2,
color: swatch.ink,
),
),
],
),
+13 -11
View File
@@ -33,16 +33,17 @@ class SettingsGroup extends StatelessWidget {
final footer = this.footer;
final theme = Theme.of(context);
final tokens = AppDesignTokens.of(context);
final inset = settingsRowInsetOf(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
if (title != null)
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
settingsRowInset,
padding: EdgeInsetsDirectional.fromSTEB(
inset,
0,
settingsRowInset,
settingsTitleGap,
inset,
tokens.density.space(settingsTitleGap),
),
child: Semantics(
header: true,
@@ -74,7 +75,7 @@ class SettingsGroup extends StatelessWidget {
Divider(
height: 1,
thickness: 1,
indent: settingsRowInset,
indent: inset,
color: theme.colorScheme.outlineVariant,
),
child,
@@ -92,11 +93,12 @@ class SettingsGroup extends StatelessWidget {
color: Theme.of(context).colorScheme.onSurfaceVariant,
);
final text = DefaultTextStyle.merge(style: style, child: footer);
final inset = settingsRowInsetOf(context);
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
settingsRowInset,
settingsFieldGap + 2,
settingsRowInset,
padding: EdgeInsetsDirectional.fromSTEB(
inset,
AppDesignTokens.of(context).density.space(settingsFieldGap + 2),
inset,
0,
),
child: text,
@@ -124,8 +126,8 @@ class SettingsGroupItem extends StatelessWidget {
width: double.infinity,
child: Padding(
padding: EdgeInsetsDirectional.symmetric(
horizontal: settingsRowInset,
vertical: 12,
horizontal: settingsRowInsetOf(context),
vertical: AppDesignTokens.of(context).density.space(12),
),
child: child,
),
@@ -9,6 +9,10 @@
/// at a reading width beside the section index.
library;
import 'package:flutter/widgets.dart';
import '../../ui/theme/app_design_tokens.dart';
/// The widest the column of groups grows on a wide window.
const double settingsContentMaxWidth = 720;
@@ -50,3 +54,12 @@ const double settingsPreloadViewports = 1;
/// How long a changing endpoint must settle before a server section reloads.
const Duration settingsEndpointDebounce = Duration(milliseconds: 600);
/// [settingsSectionGap] under the design at [context] (tighter when dense).
double settingsSectionGapOf(BuildContext context) =>
AppDesignTokens.of(context).density.space(settingsSectionGap);
/// [settingsRowInset] under the design at [context]: a dense design's rows
/// (its ListTiles' 12px padding) and their headers keep the same edge.
double settingsRowInsetOf(BuildContext context) =>
AppDesignTokens.of(context).density.inset(settingsRowInset);
@@ -34,7 +34,7 @@ class SettingsPageBody extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
for (final (index, child) in children.indexed) ...<Widget>[
if (index > 0) const SizedBox(height: settingsSectionGap),
if (index > 0) SizedBox(height: settingsSectionGapOf(context)),
child,
],
],
@@ -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';
@@ -171,7 +171,7 @@ class _SettingsSearchPageState extends State<SettingsSearchPage> {
),
],
),
const SizedBox(height: settingsSectionGap),
SizedBox(height: settingsSectionGapOf(context)),
Expanded(child: _list(visible, insets)),
],
),
@@ -201,7 +201,7 @@ class _SettingsSearchPageState extends State<SettingsSearchPage> {
Widget _list(List<SettingsSection> visible, EdgeInsets insets) {
if (visible.isEmpty) {
return Padding(
padding: const EdgeInsets.all(settingsRowInset),
padding: EdgeInsets.all(settingsRowInsetOf(context)),
child: Text('No settings match "${_search.text.trim()}".'),
);
}
@@ -222,7 +222,7 @@ class _SettingsSearchPageState extends State<SettingsSearchPage> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
for (final (index, section) in visible.indexed) ...<Widget>[
if (index > 0) const SizedBox(height: settingsSectionGap),
if (index > 0) SizedBox(height: settingsSectionGapOf(context)),
KeyedSubtree(
key: _keyFor(section.id),
child: _isActive(section)