diff --git a/.env.example b/.env.example
index 94ab12c6..35d686b8 100644
--- a/.env.example
+++ b/.env.example
@@ -1,8 +1,4 @@
# Prefer scripts/configure-compose.py to detect the host timezone automatically.
TZ=Europe/London
-# Replace this with your machine's LAN/VPN address, not localhost on the phone.
-NTFY_BASE_URL=http://192.168.1.20:8090
-# Explicitly expose ntfy on your trusted LAN/VPN; use HTTPS on public networks.
-NTFY_BIND_ADDRESS=0.0.0.0
# Avoid collision while an existing host pipeline server still owns port 8080.
PIPELINES_PORT=8081
diff --git a/README.md b/README.md
index f83253a1..ef2e55a4 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@ Pipelines is a per-user server and CLI for running reusable AI workflows and cha
## Install
-You need Go, Node.js 18+, Python 3.9+, git, curl, a C compiler, a running
+You need Go, Node.js 18+, Python 3.9+, git, curl, a running
Docker (it builds the web app) and [OpenCode](https://opencode.ai) on your
`PATH`; see [docs/install.md](docs/install.md). From this checkout, run:
diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml
index 844805a2..940f4e46 100644
--- a/app/android/app/src/main/AndroidManifest.xml
+++ b/app/android/app/src/main/AndroidManifest.xml
@@ -63,7 +63,7 @@
-
,
val createdAt: String,
diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt
index a029db52..edfcd5b7 100644
--- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt
+++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt
@@ -20,7 +20,7 @@ import java.util.concurrent.TimeUnit
/**
* Keeps one authenticated websocket to the configured Pipelines server while
- * the app is in the background, like ntfy's instant delivery: no Flutter
+ * the app is in the background, for instant delivery: no Flutter
* engine runs here. It subscribes with the replay cursor, posts each pushed
* notification, mirrors cross-device clears and sends the user's own clears.
*
diff --git a/app/lib/application/app.dart b/app/lib/application/app.dart
index 9b97b0d9..fb9ebfa8 100644
--- a/app/lib/application/app.dart
+++ b/app/lib/application/app.dart
@@ -1,5 +1,4 @@
import '../ui/adaptive/window_margins.dart';
-import '../ui/theme/app_design.dart';
import '../ui/theme/app_design_controller.dart';
import '../ui/theme/app_font_controller.dart';
import '../ui/scale/ui_scale.dart';
@@ -55,11 +54,12 @@ class MyApp extends StatelessWidget {
final designs = this.designs ?? AppDesignController.instance;
return ListenableBuilder(
listenable: Listenable.merge([fonts, designs]),
- builder: (context, _) => _host(designs.design, fonts.family),
+ builder: (context, _) => _host(designs, fonts.family),
);
}
- Widget _host(AppDesign design, String? fontFamily) {
+ Widget _host(AppDesignController designs, String? fontFamily) {
+ final design = designs.design;
final router = routerConfig;
if (router != null) {
return MaterialApp.router(
@@ -68,6 +68,7 @@ class MyApp extends StatelessWidget {
builder: _scaled,
theme: design.light(fontFamily: fontFamily),
darkTheme: design.dark(fontFamily: fontFamily),
+ themeAnimationDuration: designs.themeAnimationDuration,
themeMode: ThemeMode.system,
routerConfig: router,
);
@@ -78,6 +79,7 @@ class MyApp extends StatelessWidget {
builder: _scaled,
theme: design.light(fontFamily: fontFamily),
darkTheme: design.dark(fontFamily: fontFamily),
+ themeAnimationDuration: designs.themeAnimationDuration,
themeMode: ThemeMode.system,
home: AdaptiveShell(
destinationBodies: destinationBodies,
diff --git a/app/lib/application/detached/detached_app.dart b/app/lib/application/detached/detached_app.dart
index 7dd3126d..eba946d0 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();
@@ -223,6 +227,7 @@ class _DetachedWindowAppState extends State {
),
theme: designs.design.light(fontFamily: fonts.family),
darkTheme: designs.design.dark(fontFamily: fonts.family),
+ themeAnimationDuration: designs.themeAnimationDuration,
themeMode: ThemeMode.system,
// The window's one page is named by its route, so the address bar
// (and a reload) keeps the detached location instead of `/`.
diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart
index 05aa2c30..c9eb534f 100644
--- a/app/lib/application/pipelines_app.dart
+++ b/app/lib/application/pipelines_app.dart
@@ -84,6 +84,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.
///
@@ -643,6 +644,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/application/pipelines_root.dart b/app/lib/application/pipelines_root.dart
index 0694a204..85697862 100644
--- a/app/lib/application/pipelines_root.dart
+++ b/app/lib/application/pipelines_root.dart
@@ -389,6 +389,7 @@ class _PipelinesRootState extends State {
),
theme: designs.design.light(fontFamily: fonts.family),
darkTheme: designs.design.dark(fontFamily: fonts.family),
+ themeAnimationDuration: designs.themeAnimationDuration,
debugShowCheckedModeBanner: false,
home: flow,
),
diff --git a/app/lib/features/attention/notify/agent_notice.dart b/app/lib/features/attention/notify/agent_notice.dart
index 2428ac6d..aabf0521 100644
--- a/app/lib/features/attention/notify/agent_notice.dart
+++ b/app/lib/features/attention/notify/agent_notice.dart
@@ -1,6 +1,6 @@
/// An agent's own notification: the `chat_notify` app notification the server
/// records when a chat's model calls the `notify` tool, as the notification
-/// stream carries it (see docs/ntfy.md).
+/// stream carries it (see docs/notifications.md).
library;
/// The stream kind of an agent's notify call.
@@ -30,7 +30,7 @@ class AgentNotice {
final String title;
final String message;
- /// The ntfy-style priority: 2 low, 3 default, 4 high.
+ /// The priority, 1-5: 2 low, 3 default, 4 high.
final int priority;
final DateTime? createdAt;
diff --git a/app/lib/features/changes/widgets/diff_search_bar.dart b/app/lib/features/changes/widgets/diff_search_bar.dart
index 4aa57ca9..caf5137c 100644
--- a/app/lib/features/changes/widgets/diff_search_bar.dart
+++ b/app/lib/features/changes/widgets/diff_search_bar.dart
@@ -1,5 +1,6 @@
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
@@ -37,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: Theme.of(context).colorScheme.surfaceContainerHigh,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 4, 4),
diff --git a/app/lib/features/chat/chat_pane_content.dart b/app/lib/features/chat/chat_pane_content.dart
index a5a7a352..19022df2 100644
--- a/app/lib/features/chat/chat_pane_content.dart
+++ b/app/lib/features/chat/chat_pane_content.dart
@@ -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('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('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),
+ ),
),
),
),
diff --git a/app/lib/features/chat/chat_runtime.dart b/app/lib/features/chat/chat_runtime.dart
index f828de14..8197badc 100644
--- a/app/lib/features/chat/chat_runtime.dart
+++ b/app/lib/features/chat/chat_runtime.dart
@@ -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();
diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart
index afc224e3..c38fdb75 100644
--- a/app/lib/features/chat/chat_screen_float.dart
+++ b/app/lib/features/chat/chat_screen_float.dart
@@ -8,7 +8,8 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace {
void _bindWindows() {
final windows = widget.windows;
if (windows == null) return;
- _workspace.showOutside = windows.show;
+ _workspace.showOutside = _showOutside;
+ windows.manager.addListener(_windowsChanged);
windows.tiling = _tiling = ChatTiling(
holds: _workspace.holdsSession,
dock: _dockSession,
@@ -35,9 +36,103 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace {
if (windows != null && identical(windows.tiling, _tiling)) {
windows.tiling = null;
}
+ windows?.manager.removeListener(_windowsChanged);
_workspace.showOutside = null;
}
+ /// A chat out in a window comes to the top on a wide layout. A phone
+ /// ignores floating: the chat leaves its (hidden) window and opens as a
+ /// pane, still floating in the server's set.
+ bool _showOutside(String sessionId) {
+ final windows = widget.windows;
+ if (windows == null) return false;
+ if (!_phoneIgnoresFloat) return windows.show(sessionId);
+ _holdForPhone(windows, sessionId);
+ return false;
+ }
+
+ /// Takes [sessionId] out of its window, to be tiled on this phone layout.
+ void _holdForPhone(ChatWindows windows, String sessionId) {
+ final window = windows.windows
+ .where((window) => window.contentId == sessionId)
+ .firstOrNull;
+ if (window == null) return;
+ _phoneDocked.add(sessionId);
+ windows.manager.close(window.id);
+ }
+
+ /// Whether the last build was a phone's layout, which tiles floating chats.
+ bool? _builtPhoneFloat;
+ bool _followingFloat = false;
+
+ /// Called from build: a change between a phone and a wide layout moves
+ /// the floating chats between panes and windows after the frame.
+ @override
+ void _trackFloatLayout() {
+ // A phone-width window, or the Chat stack on a wide phone or tablet
+ // layout: both navigate one chat at a time and ignore floating.
+ _phoneLayout = !showsListBesideDetail(context) || _stacked(context);
+ if (widget.windows == null) return;
+ final phone = _phoneIgnoresFloat;
+ if (phone == _builtPhoneFloat) return;
+ _builtPhoneFloat = phone;
+ _followFloatLayoutSoon();
+ }
+
+ void _windowsChanged() {
+ if (_builtPhoneFloat == true &&
+ (widget.windows?.windows.isNotEmpty ?? false)) {
+ _followFloatLayoutSoon();
+ }
+ }
+
+ void _followFloatLayoutSoon() {
+ if (_followingFloat) return;
+ _followingFloat = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _followingFloat = false;
+ if (mounted) _followFloatLayout();
+ });
+ }
+
+ /// On a phone every floating chat becomes a pane (the chat on screen
+ /// stays); on a wide layout the chats held that way float again.
+ void _followFloatLayout() {
+ final windows = widget.windows;
+ if (windows == null) return;
+ final phone = _phoneIgnoresFloat;
+ final ids = phone
+ ? windows.floatingSessionIds.toList()
+ : _phoneDocked.toList();
+ if (ids.isEmpty) return;
+ // One write for the whole move: the chats stay floating in the set.
+ _applyingServerWorkspace = true;
+ try {
+ if (phone) {
+ final active = _workspace.activePaneId;
+ for (final id in ids) {
+ _holdForPhone(windows, id);
+ _workspace.dock(id);
+ }
+ if (active != null) _workspace.activate(active);
+ } else {
+ for (final id in ids) {
+ final pane = _workspace.panes
+ .where((pane) => pane.sessionId == id)
+ .firstOrNull;
+ if (pane == null) continue;
+ _workspace.detach(pane.id);
+ windows.float(id);
+ }
+ _phoneDocked.clear();
+ }
+ } finally {
+ _applyingServerWorkspace = false;
+ }
+ _syncOpenWorkspace();
+ if (!phone && _workspace.paneCount == 0) _back();
+ }
+
/// Panes float only on a wide layout, beside the chat list.
bool get _floatsHere =>
widget.windows != null && !_pageOpen && showsListBesideDetail(context);
diff --git a/app/lib/features/chat/chat_screen_pane_cycle.dart b/app/lib/features/chat/chat_screen_pane_cycle.dart
new file mode 100644
index 00000000..dbb470ad
--- /dev/null
+++ b/app/lib/features/chat/chat_screen_pane_cycle.dart
@@ -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, _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 [])
+ _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();
+ }
+}
diff --git a/app/lib/features/chat/chat_screen_stack.dart b/app/lib/features/chat/chat_screen_stack.dart
index 37b067cd..1cc4b876 100644
--- a/app/lib/features/chat/chat_screen_stack.dart
+++ b/app/lib/features/chat/chat_screen_stack.dart
@@ -6,7 +6,14 @@ part of 'screen.dart';
/// workspace's panes, the same open chats the server syncs; choosing one
/// opens it as a tap on its list row does, Add chat is the pane menu's Add
/// chat pane, and removing one closes its pane.
-mixin _ChatScreenStack on State, _ChatScreenWorkspace {
+/// Whether this is a phone or tablet (Android or iOS, also a browser on one).
+bool chatStackOnMobile() => switch (defaultTargetPlatform) {
+ TargetPlatform.android || TargetPlatform.iOS => true,
+ _ => false,
+};
+
+mixin _ChatScreenStack
+ on State, _ChatScreenWorkspace, _ChatScreenStackGroups {
final LayerLink _stackLink = LayerLink();
void _openBySelection(JsonMap session);
@@ -15,10 +22,14 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace {
MobileChatNavigationController get _navigation =>
MobileChatNavigationController.instance;
- /// Whether this layout navigates with the stack rather than the peek.
+ /// Whether this layout navigates with the stack rather than the peek: on
+ /// a phone-width window, and on a phone or tablet at any width (an
+ /// unfolded foldable keeps the stack above the active pane). A wide
+ /// desktop or web window keeps its panes alone.
@override
bool _stacked(BuildContext context) =>
- _navigation.stack && !showsListBesideDetail(context);
+ _navigation.stack &&
+ (!showsListBesideDetail(context) || chatStackOnMobile());
/// Gives the active pane the stack's spot.
@override
@@ -42,6 +53,7 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace {
_rowFor(pane.sessionId) ??
{'id': pane.sessionId},
current: pane.id == active,
+ group: _stackGroups.groupOf(pane.sessionId),
),
];
}
@@ -50,7 +62,11 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace {
/// screen.
@override
Widget _stackOverlay() => ListenableBuilder(
- listenable: Listenable.merge([_workspace, _sessionsForSidebar]),
+ listenable: Listenable.merge([
+ _workspace,
+ _sessionsForSidebar,
+ _stackGroups,
+ ]),
builder: (context, _) => CompositedTransformFollower(
link: _stackLink,
showWhenUnlinked: false,
@@ -59,6 +75,8 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace {
onOpen: (entry) => _openBySelection(entry.session),
onAdd: (context) => _addPane(context, title: ChatStackColumn.addLabel),
onRemove: _removeFromStack,
+ onReorder: _workspace.reorderSessions,
+ groups: _stackGroupActions(),
),
),
);
@@ -66,6 +84,7 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace {
void _removeFromStack(ChatStackEntry entry) {
final messenger = ScaffoldMessenger.maybeOf(context);
final wasActive = _workspace.activePaneId;
+ final index = _workspace.panes.indexWhere((p) => p.id == entry.paneId);
_closePane(entry.paneId);
if (messenger == null) return;
messenger
@@ -75,16 +94,23 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace {
content: Text('Removed ${entry.title} from open chats'),
action: SnackBarAction(
label: 'Undo',
- onPressed: () => _restoreToStack(entry, wasActive),
+ onPressed: () => _restoreToStack(entry, wasActive, index),
),
),
);
}
- void _restoreToStack(ChatStackEntry entry, String? wasActive) {
+ /// Undo: the chat comes back at its old place in the open-chat order.
+ void _restoreToStack(ChatStackEntry entry, String? wasActive, int index) {
if (!mounted || _workspace.holdsSession(entry.sessionId)) return;
_openedSessions[entry.sessionId] = entry.session;
_workspace.splitActive(entry.sessionId, ChatSplitAxis.horizontal);
+ final restored = _workspace.panes
+ .where((pane) => pane.sessionId == entry.sessionId)
+ .firstOrNull;
+ if (restored != null && index >= 0) {
+ _workspace.movePane(restored.id, index);
+ }
// The chat on screen stays on screen unless it was the one removed.
if (wasActive != null && wasActive != entry.paneId) {
final kept = _workspace.panes
diff --git a/app/lib/features/chat/chat_screen_stack_groups.dart b/app/lib/features/chat/chat_screen_stack_groups.dart
new file mode 100644
index 00000000..29e84b8c
--- /dev/null
+++ b/app/lib/features/chat/chat_screen_stack_groups.dart
@@ -0,0 +1,83 @@
+part of 'screen.dart';
+
+/// The chat stack's groups ([ChatStackGroups]): which open chats belong to
+/// which named group. They travel with the open-chat set (each entry's
+/// `group`), so they persist and sync across devices like the order.
+mixin _ChatScreenStackGroups on State, _ChatScreenWorkspace {
+ ChatStackGroupActions _stackGroupActions() => ChatStackGroupActions(
+ join: (sessionIds, group, order) {
+ _workspace.reorderSessions(order);
+ _stackGroups.assign(sessionIds, group);
+ },
+ leave: (sessionIds, order) {
+ _workspace.reorderSessions(order);
+ _stackGroups.unassign(sessionIds);
+ },
+ rename: _stackGroups.rename,
+ ungroup: _ungroupStack,
+ closeAll: _closeStackGroup,
+ );
+
+ void _stackSnack(String message, VoidCallback undo) {
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ if (messenger == null) return;
+ messenger
+ ..hideCurrentSnackBar()
+ ..showSnackBar(
+ SnackBar(
+ content: Text(message),
+ action: SnackBarAction(label: 'Undo', onPressed: undo),
+ ),
+ );
+ }
+
+ /// The group goes; its chats stay open. Undo puts the open ones back.
+ void _ungroupStack(String group) {
+ final members = _stackGroups.membersOf(group);
+ if (members.isEmpty) return;
+ _stackGroups.ungroup(group);
+ _stackSnack('Ungrouped $group', () {
+ if (!mounted) return;
+ _stackGroups.assign(members.where(_workspace.holdsSession), group);
+ });
+ }
+
+ /// Every chat in the group leaves the open chats. Undo opens them again,
+ /// in their places and grouped, keeping the chat on screen.
+ void _closeStackGroup(String group) {
+ final members = _stackGroups.membersOf(group).toSet();
+ if (members.isEmpty) return;
+ final order = [for (final pane in _workspace.panes) pane.sessionId];
+ final rows = {
+ for (final id in members) id: _rowFor(id) ?? {'id': id},
+ };
+ final active = _workspace.activePane?.sessionId;
+ for (final pane in _workspace.panes.toList()) {
+ if (members.contains(pane.sessionId)) _closePane(pane.id);
+ }
+ _stackSnack(
+ 'Closed ${members.length} chats in $group',
+ () => _reopenStackGroup(group, order, rows, active),
+ );
+ }
+
+ void _reopenStackGroup(
+ String group,
+ List order,
+ Map rows,
+ String? active,
+ ) {
+ if (!mounted) return;
+ for (final MapEntry(key: id, value: row) in rows.entries) {
+ if (_workspace.holdsSession(id)) continue;
+ _openedSessions[id] = row;
+ _workspace.splitActive(id, ChatSplitAxis.horizontal);
+ }
+ _workspace.reorderSessions(order);
+ _stackGroups.assign(rows.keys, group);
+ final kept = _workspace.panes
+ .where((pane) => pane.sessionId == active)
+ .firstOrNull;
+ if (kept != null) _workspace.activate(kept.id);
+ }
+}
diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart
index d68d99fc..46de2235 100644
--- a/app/lib/features/chat/chat_screen_workspace.dart
+++ b/app/lib/features/chat/chat_screen_workspace.dart
@@ -114,18 +114,38 @@ mixin _ChatScreenWorkspace on State {
ChatWorkspaceBinding? _workspaceBinding;
String? _workspaceScope;
+ /// Chats that float in windows on a wide layout, held as ordinary panes
+ /// while the layout is a phone's (see `_ChatScreenFloat`). They stay
+ /// floating in the server's set, so a wide layout floats them again.
+ final Set _phoneDocked = {};
+
+ /// The chat stack's groups, sent with the open-chat set.
+ final ChatStackGroups _stackGroups = ChatStackGroups();
+
+ /// Whether the last build laid out for a phone (set in build, so it is
+ /// safe to read from callbacks and initState).
+ bool _phoneLayout = false;
+
+ /// Whether this layout ignores floating: a phone's, where windows are
+ /// hidden and the chats are navigated one at a time.
+ bool get _phoneIgnoresFloat => widget.windows != null && _phoneLayout;
+
Iterable _serverWorkspaceEntries() sync* {
- final floating =
- widget.windows?.floatingSessionIds.toSet() ?? const {};
+ final floating = {...?widget.windows?.floatingSessionIds, ..._phoneDocked};
for (final pane in _workspace.panes) {
yield ChatOpenWorkspaceEntry(
pane.sessionId,
floating: floating.contains(pane.sessionId),
+ group: _stackGroups.groupOf(pane.sessionId),
);
}
for (final sessionId in floating) {
if (!_workspace.holdsSession(sessionId)) {
- yield ChatOpenWorkspaceEntry(sessionId, floating: true);
+ yield ChatOpenWorkspaceEntry(
+ sessionId,
+ floating: true,
+ group: _stackGroups.groupOf(sessionId),
+ );
}
}
}
@@ -232,9 +252,27 @@ mixin _ChatScreenWorkspace on State {
]);
}
_applyingServerWorkspace = true;
+ final phone = _phoneIgnoresFloat;
try {
final windows = widget.windows;
- if (windows != null) {
+ for (final entry in snapshot.entries) {
+ if (!entry.floating) _phoneDocked.remove(entry.sessionId);
+ }
+ _stackGroups.replaceAll({
+ for (final entry in snapshot.entries) entry.sessionId: ?entry.group,
+ });
+ if (windows != null && phone) {
+ // A phone tiles the floating chats too; they float again when the
+ // layout is wide.
+ for (final entry in snapshot.entries.where((e) => e.floating)) {
+ _phoneDocked.add(entry.sessionId);
+ final window = windows.windows
+ .where((window) => window.contentId == entry.sessionId)
+ .firstOrNull;
+ if (window != null) windows.manager.close(window.id);
+ }
+ }
+ if (windows != null && !phone) {
final entriesBySession = {
for (final entry in snapshot.entries) entry.sessionId: entry,
};
@@ -260,7 +298,7 @@ mixin _ChatScreenWorkspace on State {
}
_workspace.reconcileSessions(
snapshot.entries
- .where((entry) => !entry.floating)
+ .where((entry) => phone || !entry.floating)
.map((entry) => entry.sessionId),
);
if (keepInitial) {
@@ -365,6 +403,11 @@ mixin _ChatScreenWorkspace on State {
'${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}';
if (_workspaceSignature == signature) return;
_workspaceSignature = signature;
+ // A phone-held floating chat the operator closed is no longer open.
+ _phoneDocked.removeWhere((id) => !_workspace.holdsSession(id));
+ _stackGroups.retain({
+ for (final entry in _serverWorkspaceEntries()) entry.sessionId,
+ });
_syncOpenWorkspace();
_touchActiveChat();
void update() {
@@ -486,10 +529,12 @@ mixin _ChatScreenWorkspace on State {
Widget _stackScope(BuildContext context, bool active, Widget child);
Widget _stackOverlay();
MobileChatNavigationController get _navigation;
+ void _trackFloatLayout();
Widget _workspaceView() => ListenableBuilder(
listenable: _navigation,
builder: (context, _) {
+ _trackFloatLayout();
final stacked = _stacked(context);
final workspace = _tiledWorkspace(context, stacked: stacked);
if (!stacked) return workspace;
diff --git a/app/lib/features/chat/conversation/chat_bar_control_style.dart b/app/lib/features/chat/conversation/chat_bar_control_style.dart
index 5bd04969..3f108bfb 100644
--- a/app/lib/features/chat/conversation/chat_bar_control_style.dart
+++ b/app/lib/features/chat/conversation/chat_bar_control_style.dart
@@ -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).
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_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart
index 415dc12c..52647aa1 100644
--- a/app/lib/features/chat/conversation/chat_composer_bar.dart
+++ b/app/lib/features/chat/conversation/chat_composer_bar.dart
@@ -1061,7 +1061,15 @@ class _ChatComposerBarState extends State {
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 {
// 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,
+ ),
),
);
}
diff --git a/app/lib/features/chat/conversation/chat_find_bar.dart b/app/lib/features/chat/conversation/chat_find_bar.dart
index 4fbf3461..70d7bca2 100644
--- a/app/lib/features/chat/conversation/chat_find_bar.dart
+++ b/app/lib/features/chat/conversation/chat_find_bar.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'chat_find_controller.dart';
+import '../../../ui/theme/app_design_tokens.dart';
/// The chat's find bar, like the terminal's: the query field, the match
/// count, Match case, the older/newer and close buttons. Matches count from
@@ -68,7 +69,9 @@ class _ChatFindBarState extends State {
child: Material(
elevation: 3,
color: 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(
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/screen.dart b/app/lib/features/chat/screen.dart
index c202e92d..38421b30 100644
--- a/app/lib/features/chat/screen.dart
+++ b/app/lib/features/chat/screen.dart
@@ -14,7 +14,7 @@ import 'dart:async';
import '../../ui/motion/motion.dart';
import '../../ui/motion/container_transform_source.dart';
-import 'package:flutter/foundation.dart' show setEquals;
+import 'package:flutter/foundation.dart' show defaultTargetPlatform, setEquals;
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
@@ -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';
@@ -41,10 +43,12 @@ import 'conversation/chat_quick_switch_dialog.dart';
import 'conversation/chat_sidebar_controls.dart';
import 'ui/sessions/chat_compact_sidebar.dart';
import 'workspace/chat_workspace.dart';
+import 'stack/chat_stack_actions.dart';
import 'stack/chat_stack_anchor.dart';
import 'stack/chat_stack_column.dart';
import 'stack/chat_stack_entry.dart';
import 'stack/chat_stack_fab.dart';
+import 'stack/chat_stack_groups.dart';
import 'stack/mobile_chat_navigation.dart';
import 'workspace/chat_center_stage_action.dart';
import 'workspace/chat_center_stage_controller.dart';
@@ -70,11 +74,13 @@ 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';
part 'chat_screen_quick_switch.dart';
part 'chat_screen_stack.dart';
+part 'chat_screen_stack_groups.dart';
part 'chat_screen_workspace.dart';
/// The Chat destination's list/detail switch.
@@ -137,9 +143,11 @@ class _ChatScreenState extends State
_ChatScreenWorkspace,
_ChatScreenKeys,
_ChatScreenFloat,
+ _ChatScreenPaneCycle,
_ChatScreenPaneMenu,
_ChatScreenQuickSwitch,
_ChatScreenAttention,
+ _ChatScreenStackGroups,
_ChatScreenStack,
_ChatScreenListToggle {
/// The chats' shared state: the list, opened rows, accepted models,
@@ -191,9 +199,11 @@ class _ChatScreenState extends State
_runtime.recency.touch(initial);
}
_workspace.addListener(_workspaceChanged);
+ _stackGroups.addListener(_syncOpenWorkspace);
_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,9 +494,11 @@ class _ChatScreenState extends State
_paneCommands.dispose();
HardwareKeyboard.instance.removeHandler(_cycleChatKey);
HardwareKeyboard.instance.removeHandler(_slashFocusKey);
+ HardwareKeyboard.instance.removeHandler(_paneCycleKey);
_page.dispose();
_workspaceBinding?.dispose();
_openWorkspace?.dispose();
+ _stackGroups.dispose();
_unbindWindows();
_unbindQuickSwitch();
_unbindAttention();
@@ -564,6 +576,7 @@ class _ChatScreenState extends State
(_) => _publishWorkspaceRoute(),
);
}
+ _trackFloatLayout();
_offeredNext = selected != null && _nextAfter(selected) != null;
// A phone opens a chat as a real Navigator page with stock Back. A wide
// window keeps the destination rail and the chat list beside the open
diff --git a/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart b/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart
index 3096fb14..35b0d5da 100644
--- a/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart
+++ b/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'chat_shell_terminal_find.dart';
+import '../../../ui/theme/app_design_tokens.dart';
/// The terminal's find bar: the query field (Enter finds the next match,
/// Shift+Enter the previous, Esc closes), the match count, Match case and
@@ -69,7 +70,9 @@ class _ChatShellTerminalFindBarState extends State {
child: Material(
elevation: 3,
color: 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(
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/stack/chat_stack_actions.dart b/app/lib/features/chat/stack/chat_stack_actions.dart
new file mode 100644
index 00000000..f64a4d67
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_actions.dart
@@ -0,0 +1,28 @@
+/// What the chat stack's groups ask of the workspace that hosts them; each
+/// change syncs with the open-chat set.
+class ChatStackGroupActions {
+ const ChatStackGroupActions({
+ required this.join,
+ required this.leave,
+ required this.rename,
+ required this.ungroup,
+ required this.closeAll,
+ });
+
+ /// Puts [sessionIds] in [group] (making it when new); the open chats then
+ /// take [order].
+ final void Function(List sessionIds, String group, List order)
+ join;
+
+ /// Takes [sessionIds] out of their group; the open chats take [order].
+ final void Function(List sessionIds, List order) leave;
+
+ /// Renames a group (a name in use merges the two).
+ final void Function(String from, String to) rename;
+
+ /// Dissolves a group, its chats staying open, with Undo.
+ final void Function(String group) ungroup;
+
+ /// Closes every chat in a group, with Undo.
+ final void Function(String group) closeAll;
+}
diff --git a/app/lib/features/chat/stack/chat_stack_close_target.dart b/app/lib/features/chat/stack/chat_stack_close_target.dart
new file mode 100644
index 00000000..2a73127b
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_close_target.dart
@@ -0,0 +1,126 @@
+import 'package:flutter/material.dart';
+
+import '../../../ui/theme/app_design_tokens.dart';
+import 'chat_stack_disc.dart';
+
+/// How near the close button's centre a dragged chat's pointer counts as
+/// over it: a little past its rim, as a thumb covers what it drags, and
+/// short of the first chat's slot a pitch above.
+const double kChatStackRemoveReach = kChatStackSlot * .7;
+
+/// How much the button grows while a dragged chat is over it.
+const double chatStackRemoveGrowth = 1.2;
+
+/// The open stack's close button, exactly where the pile was: the pile
+/// turns into a "×" as the column rises above it, and a tap folds the
+/// column back.
+///
+/// While a chat is dragged it is also the remove target: its "×" turns the
+/// error colour ([armed]), and with the chat over it ([hover]) it grows and
+/// fills with the error colour. Dropping there is decided from the
+/// pointer's position, not by this widget.
+///
+/// Everything moves through transitions (fade, turn, scale, decoration), so
+/// opening and dragging repaint it without rebuilding.
+class ChatStackCloseTarget extends StatelessWidget {
+ const ChatStackCloseTarget({
+ super.key,
+ required this.open,
+ required this.armed,
+ required this.hover,
+ required this.reduced,
+ required this.onClose,
+ });
+
+ static const label = 'Close chats';
+
+ /// 0 folded (the pile shows), 1 open.
+ final Animation open;
+
+ /// 0 at rest, 1 while a chat is dragged.
+ final Animation armed;
+
+ /// 0 idle, 1 with a dragged chat over it.
+ final Animation hover;
+
+ /// Fades only: no turn, no growth.
+ final bool reduced;
+ final VoidCallback onClose;
+
+ @override
+ Widget build(BuildContext context) {
+ final tokens = AppDesignTokens.of(context);
+ final scheme = Theme.of(context).colorScheme;
+ final dark = Theme.of(context).brightness == Brightness.dark;
+ final shape = chatStackShape(tokens);
+ final side = tokens.flat
+ ? tokens.frameSide ?? BorderSide(color: scheme.outlineVariant)
+ : BorderSide.none;
+ final idle = ShapeDecoration(
+ color: tokens.panelFill(
+ scheme,
+ dark ? scheme.surfaceContainerHighest : scheme.surface,
+ ),
+ shape: shape.copyWith(side: side),
+ shadows: tokens.flat ? null : chatStackShadows(scheme),
+ );
+ final hot = ShapeDecoration(
+ color: scheme.error,
+ shape: shape.copyWith(
+ side: tokens.flat ? side.copyWith(color: scheme.error) : side,
+ ),
+ shadows: tokens.flat ? null : chatStackShadows(scheme),
+ );
+ Widget icon(Color color, Animation opacity) => FadeTransition(
+ opacity: opacity,
+ child: Icon(Icons.close, color: color),
+ );
+ Widget button = DecoratedBoxTransition(
+ decoration: DecorationTween(begin: idle, end: hot).animate(hover),
+ child: SizedBox.square(
+ dimension: kChatStackDisc,
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ icon(scheme.onSurfaceVariant, ReverseAnimation(armed)),
+ icon(scheme.error, armed),
+ icon(scheme.onError, hover),
+ ],
+ ),
+ ),
+ );
+ final shown = open.drive(CurveTween(curve: Curves.easeOutCubic));
+ if (!reduced) {
+ button = ScaleTransition(
+ scale: Tween(
+ begin: 1,
+ end: chatStackRemoveGrowth,
+ ).chain(CurveTween(curve: Curves.easeOutBack)).animate(hover),
+ child: button,
+ );
+ // The pile's top avatar turns into the "×" a quarter turn.
+ button = RotationTransition(
+ turns: Tween(begin: -.25, end: 0).animate(shown),
+ child: ScaleTransition(
+ scale: Tween(begin: .6, end: 1).animate(shown),
+ child: button,
+ ),
+ );
+ }
+ return Semantics(
+ container: true,
+ button: true,
+ label: label,
+ onTap: onClose,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ excludeFromSemantics: true,
+ onTap: onClose,
+ child: FadeTransition(
+ opacity: shown,
+ child: Center(child: button),
+ ),
+ ),
+ );
+ }
+}
diff --git a/app/lib/features/chat/stack/chat_stack_column.dart b/app/lib/features/chat/stack/chat_stack_column.dart
index 908c9eb9..c823d3e3 100644
--- a/app/lib/features/chat/stack/chat_stack_column.dart
+++ b/app/lib/features/chat/stack/chat_stack_column.dart
@@ -1,46 +1,70 @@
+import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/services.dart';
-import '../../../ui/theme/app_design_tokens.dart';
+import 'chat_stack_actions.dart';
+import 'chat_stack_close_target.dart';
+import 'chat_stack_column_items.dart';
import 'chat_stack_disc.dart';
+import 'chat_stack_drag.dart';
import 'chat_stack_entry.dart';
+import 'chat_stack_group_dialogs.dart';
+import 'chat_stack_group_ops.dart';
+import 'chat_stack_group_pile.dart';
import 'chat_stack_motion.dart';
-import 'chat_stack_pose.dart';
+import 'chat_stack_node.dart';
+
+part 'chat_stack_column_groups.dart';
/// The chat stack fanned out: a scrim over the screen and the open chats in
/// a column rising from the stack's own slot, each avatar with its name in a
/// small pill beside it, and Add chat at the top.
///
-/// Item 0 sits exactly on the collapsed stack, nearest the thumb. The chats
-/// keep the open-chat order (the order the server syncs), so a chat keeps
-/// its place in the column from one visit to the next; the chat on screen
-/// wears a ring in its colour. Add chat is last, at the top: the reachable
-/// bottom slots go to the frequent action (switching), and the rarer one
-/// ends the list where the operator reads "and more".
+/// The stack's own slot turns into a close button ([ChatStackCloseTarget]);
+/// item 0 sits a pitch above it, nearest the thumb. The items keep the
+/// open-chat order (the order the server syncs), so a chat keeps its place
+/// from one visit to the next; the chat on screen wears a ring in its
+/// colour. A group shows as one item, its chats piled; a tap opens it: the
+/// top level fades and the group's chats rise from its pile, under a
+/// header that leads back. Add chat is last, at the top: the reachable
+/// bottom slots go to the frequent action (switching).
+///
+/// A short hold lifts an item ([ChatStackDrag]): dragged up or down it
+/// reorders; dropped on the middle of another it groups them (or joins the
+/// group); dropped on the close button (armed as a remove target while
+/// dragging) a chat leaves the open chats and a group is ungrouped. In an
+/// open group a chat dropped on the header leaves the group. Add chat stays
+/// put. The same moves are semantic actions.
///
/// Nothing here rebuilds per frame: every item moves through
-/// [ChatStackPoseTransition] and fades through [FadeTransition], both
-/// repaint-only.
-class ChatStackColumn extends StatelessWidget {
+/// `ChatStackPoseTransition` and `ChatStackDragShift` and fades through
+/// [FadeTransition], all repaint-only; a drag rebuilds the column only as it
+/// starts and ends.
+class ChatStackColumn extends StatefulWidget {
const ChatStackColumn({
super.key,
required this.motion,
required this.anchor,
- required this.entries,
+ required this.nodes,
required this.depths,
required this.interactive,
required this.onOpen,
required this.onAdd,
required this.onDismiss,
+ required this.group,
this.onRemove,
+ this.onReorder,
+ this.groups,
});
final ChatStackMotion motion;
/// The collapsed stack's slot in this overlay's coordinates.
final Rect anchor;
- final List entries;
+
+ /// The top level: chats and groups in the open-chat order.
+ final List nodes;
/// Each item's layer in the collapsed pile (null when it is not drawn
/// there); the add item last.
@@ -52,12 +76,105 @@ class ChatStackColumn extends StatelessWidget {
final VoidCallback onAdd;
final VoidCallback onDismiss;
- /// Long press removes a chat from the open chats; null when it cannot
- /// (the only open chat).
+ /// The open group's name, or null on the top level; Back sets it null.
+ final ValueNotifier group;
+
+ /// Removes a chat from the open chats; null when it cannot (the only open
+ /// chat).
final ValueChanged? onRemove;
+ /// Puts the open chats in this order (session ids); null when they cannot
+ /// be reordered.
+ final ValueChanged>? onReorder;
+
+ /// Grouping; null when the host keeps no groups.
+ final ChatStackGroupActions? groups;
+
static const removeLabel = 'Remove from open chats';
- static const addLabel = 'Add chat';
+ static const moveUpLabel = 'Move up';
+ static const moveDownLabel = 'Move down';
+ static const moveToGroupLabel = 'Move to group…';
+ static const leaveGroupLabel = 'Remove from group';
+ static const addLabel = ChatStackAddTail.label;
+
+ @override
+ State createState() => _ChatStackColumnState();
+}
+
+class _ChatStackColumnState extends State
+ with TickerProviderStateMixin, _ChatStackColumnGroups {
+ @override
+ late final ChatStackDrag _drag = ChatStackDrag(
+ vsync: this,
+ pitch: kChatStackPitch,
+ )..addListener(_dragChanged);
+
+ /// The remove target's centre in this column's box, from the last layout.
+ Offset? _removeCenter;
+
+ @override
+ void initState() {
+ super.initState();
+ _initGroups();
+ }
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _drag.reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
+ }
+
+ @override
+ void didUpdateWidget(covariant ChatStackColumn oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ // Folding, or the items changing under the finger (another device),
+ // puts the dragged item back.
+ if (!widget.interactive ||
+ (_drag.dragging && !listEquals(_dragOrder(), _drag.order))) {
+ _drag.cancel();
+ }
+ _groupsUpdated(oldWidget);
+ }
+
+ @override
+ void dispose() {
+ _drag.dispose();
+ _disposeGroups();
+ super.dispose();
+ }
+
+ void _dragChanged() {
+ if (mounted) setState(() {});
+ }
+
+ @override
+ void _move(LongPressMoveUpdateDetails details) {
+ if (!_drag.dragging) return;
+ final box = context.findRenderObject() as RenderBox?;
+ final center = _removeCenter;
+ final over =
+ widget.onRemove != null &&
+ box != null &&
+ center != null &&
+ (box.globalToLocal(details.globalPosition) - center).distance <=
+ kChatStackRemoveReach;
+ _drag.move(details.offsetFromOrigin, overRemove: over);
+ }
+
+ void _escape() {
+ if (_drag.dragging) {
+ _drag.cancel();
+ } else if (widget.group.value != null) {
+ widget.group.value = null;
+ } else {
+ widget.onDismiss();
+ }
+ }
+
+ /// A tap on the scrim: out of an open group first, then folded.
+ void _scrim() => widget.group.value != null
+ ? widget.group.value = null
+ : widget.onDismiss();
@override
Widget build(BuildContext context) {
@@ -65,55 +182,72 @@ class ChatStackColumn extends StatelessWidget {
final scheme = Theme.of(context).colorScheme;
final dark = Theme.of(context).brightness == Brightness.dark;
final rtl = Directionality.of(context) == TextDirection.rtl;
+ final anchor = widget.anchor;
return LayoutBuilder(
builder: (context, constraints) {
final size = constraints.biggest;
- final count = motion.count;
- final height = (count - 1) * kChatStackPitch + kChatStackSlot;
+ final open = _openGroupMotion(rtl);
+ final count = open == null || open.count < widget.motion.count
+ ? widget.motion.count
+ : open.count;
+ // The stack's own slot (the close button) and the items above it.
+ final height = count * kChatStackPitch + kChatStackSlot;
final top = media.padding.top + 8;
- final available = anchor.bottom - top;
- final fits = height <= available;
+ final fits = height <= anchor.bottom - top;
// The column's own edge is the stack's; the labels take the rest of
// the row back to a margin at the other side.
final endInset = rtl ? anchor.left : size.width - anchor.right;
const margin = 16.0;
final width = size.width - endInset - margin;
final labelMax = width - kChatStackSlot - kChatStackLabelGap;
- // Paint the pile's order while it opens: hidden layers first, the
- // top of the pile last.
- final order = [for (var i = 0; i < count; i++) i]
- ..sort((a, b) => (depths[b] ?? 99).compareTo(depths[a] ?? 99));
- final items = Stack(
+ // The close button takes the pile's place; while an item is dragged
+ // it is the remove target.
+ _removeCenter = anchor.center;
+ final close = Positioned.fromRect(
+ key: const ValueKey('chat-stack-close'),
+ rect: anchor,
+ child: IgnorePointer(
+ ignoring: _drag.lifted != null,
+ child: ChatStackCloseTarget(
+ open: widget.motion.close,
+ armed: _drag.removeShown,
+ hover: _drag.hover,
+ reduced: _drag.reduced,
+ onClose: widget.onDismiss,
+ ),
+ ),
+ );
+ final layers = Stack(
clipBehavior: Clip.none,
children: [
- for (final i in order) ...[
- _label(context, i, labelMax),
- _item(context, i),
- ],
+ _topLayer(labelMax, inGroup: _openGroup != null),
+ if (open != null) _groupLayer(open, labelMax),
],
);
return CallbackShortcuts(
- bindings: {
- const SingleActivator(LogicalKeyboardKey.escape): onDismiss,
- },
+ bindings: {const SingleActivator(LogicalKeyboardKey.escape): _escape},
child: FocusScope(
autofocus: true,
child: IgnorePointer(
- ignoring: !interactive,
+ ignoring: !widget.interactive,
child: Stack(
children: [
Positioned.fill(
child: FadeTransition(
- opacity: motion.scrim,
+ opacity: widget.motion.scrim,
child: ModalBarrier(
color: scheme.scrim.withValues(alpha: dark ? .5 : .32),
dismissible: true,
- onDismiss: onDismiss,
- semanticsLabel: 'Close chats',
+ onDismiss: _scrim,
+ semanticsLabel: 'Dismiss',
),
),
),
+ // A dragged item is drawn over the button (it shrinks into
+ // it); otherwise the button is on top, to take its tap.
+ if (_drag.lifted != null) close,
PositionedDirectional(
+ key: const ValueKey('chat-stack-column'),
end: endInset,
bottom: size.height - anchor.bottom,
top: top,
@@ -130,12 +264,13 @@ class ChatStackColumn extends StatelessWidget {
container: true,
explicitChildNodes: true,
label: 'Open chats',
- child: items,
+ child: layers,
),
),
),
),
),
+ if (_drag.lifted == null) close,
],
),
),
@@ -145,168 +280,42 @@ class ChatStackColumn extends StatelessWidget {
);
}
- Widget _item(BuildContext context, int i) {
- final entry = i < entries.length ? entries[i] : null;
- return PositionedDirectional(
- key: ValueKey('chat-stack-item-${entry?.paneId ?? 'add'}'),
- end: 0,
- bottom: 0,
- // The transform is outermost: the boxes under it sit at the stack's
- // slot, and only a transform passes hits on to where it paints them.
- child: ChatStackPoseTransition(
- progress: motion.move[i],
- from: motion.from[i],
- to: motion.target[i],
- child: FadeTransition(
- opacity: motion.fade[i],
- child: KeyedSubtree(
- key: ValueKey('chat-stack-button-${entry?.paneId ?? 'add'}'),
- child: entry == null ? _addButton(context) : _chatButton(entry),
- ),
- ),
+ /// The top level: chats, groups and Add chat. Behind an open group it
+ /// fades out and takes no input.
+ Widget _topLayer(double labelMax, {required bool inGroup}) {
+ final nodes = widget.nodes;
+ final depths = widget.depths;
+ final order = [for (var i = 0; i <= nodes.length; i++) i]
+ ..sort((a, b) => (depths[b] ?? 99).compareTo(depths[a] ?? 99));
+ _liftToTop(order, nodes);
+ final items = ChatStackColumnItems(
+ key: const ValueKey('chat-stack-top'),
+ motion: widget.motion,
+ nodes: nodes,
+ tail: const ChatStackAddTail(),
+ order: order,
+ labelMax: labelMax,
+ drag: _drag,
+ draggable: _draggable && !inGroup,
+ onOpen: _openNode,
+ onTail: widget.onAdd,
+ onDragStart: _startTop,
+ onDragMove: _move,
+ onDragEnd: _endTop,
+ actionsFor: _topActions,
+ );
+ return IgnorePointer(
+ ignoring: inGroup,
+ child: ExcludeSemantics(
+ excluding: inGroup,
+ child: FadeTransition(opacity: _topOpacity, child: items),
),
);
}
- Widget _label(BuildContext context, int i, double maxWidth) {
- final entry = i < entries.length ? entries[i] : null;
- return PositionedDirectional(
- key: ValueKey('chat-stack-label-${entry?.paneId ?? 'add'}'),
- end: kChatStackSlot + kChatStackLabelGap,
- bottom: 0,
- height: kChatStackSlot,
- child: ChatStackPoseTransition(
- progress: motion.label[i],
- from: motion.labelFrom[i],
- to: motion.target[i],
- child: ExcludeSemantics(
- child: FadeTransition(
- opacity: motion.label[i],
- child: Align(
- alignment: AlignmentDirectional.centerEnd,
- widthFactor: 1,
- child: ConstrainedBox(
- constraints: BoxConstraints(maxWidth: maxWidth),
- child: GestureDetector(
- onTap: entry == null ? onAdd : () => onOpen(entry),
- onLongPress: entry == null || onRemove == null
- ? null
- : () => onRemove!(entry),
- child: ChatStackLabel(
- text: entry?.title ?? addLabel,
- color: entry?.color(context),
- emphasized: entry?.current ?? false,
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- );
- }
-
- Widget _chatButton(ChatStackEntry entry) => Builder(
- builder: (context) {
- final remove = onRemove;
- final ring = entry.current
- ? entry.color(context) ?? Theme.of(context).colorScheme.primary
- : null;
- return Semantics(
- container: true,
- button: true,
- selected: entry.current,
- label: entry.title,
- hint: entry.current ? 'Open now' : null,
- onTap: () => onOpen(entry),
- customSemanticsActions: remove == null
- ? null
- : {
- const CustomSemanticsAction(label: removeLabel): () =>
- remove(entry),
- },
- child: _Tappable(
- autofocus: entry.current,
- onTap: () => onOpen(entry),
- onLongPress: remove == null ? null : () => remove(entry),
- child: ChatStackDisc(ring: ring, child: chatStackAvatar(entry)),
- ),
- );
- },
- );
-
- Widget _addButton(BuildContext context) {
- final scheme = Theme.of(context).colorScheme;
- final tokens = AppDesignTokens.of(context);
- return Semantics(
- container: true,
- button: true,
- label: addLabel,
- onTap: onAdd,
- child: _Tappable(
- onTap: onAdd,
- child: ChatStackDisc(
- child: DecoratedBox(
- decoration: ShapeDecoration(
- color: tokens.flat ? null : scheme.primaryContainer,
- shape: chatStackShape(tokens).copyWith(
- side: tokens.flat
- ? BorderSide(color: scheme.primary.withValues(alpha: .55))
- : BorderSide.none,
- ),
- ),
- child: Icon(
- Icons.add,
- color: tokens.flat ? scheme.primary : scheme.onPrimaryContainer,
- ),
- ),
- ),
- ),
- );
- }
-}
-
-/// A disc's ink and focus: the splash is drawn over the disc (the disc is
-/// opaque, so ink under it would never show), in the design's shape.
-class _Tappable extends StatelessWidget {
- const _Tappable({
- required this.child,
- required this.onTap,
- this.onLongPress,
- this.autofocus = false,
- });
-
- final Widget child;
- final VoidCallback onTap;
- final VoidCallback? onLongPress;
- final bool autofocus;
-
- @override
- Widget build(BuildContext context) {
- final shape = chatStackShape(AppDesignTokens.of(context));
- return Stack(
- children: [
- child,
- Positioned.fill(
- child: Padding(
- padding: const EdgeInsets.all(
- (kChatStackSlot - kChatStackDisc) / 2,
- ),
- child: Material(
- type: MaterialType.transparency,
- shape: shape,
- clipBehavior: Clip.antiAlias,
- child: InkWell(
- autofocus: autofocus,
- excludeFromSemantics: true,
- customBorder: shape,
- onTap: onTap,
- onLongPress: onLongPress,
- ),
- ),
- ),
- ),
- ],
- );
+ /// Paints a lifted item above the others.
+ void _liftToTop(List order, List nodes) {
+ final lifted = nodes.indexWhere((node) => node.key == _drag.lifted);
+ if (lifted >= 0) order.add(order.removeAt(order.indexOf(lifted)));
}
}
diff --git a/app/lib/features/chat/stack/chat_stack_column_groups.dart b/app/lib/features/chat/stack/chat_stack_column_groups.dart
new file mode 100644
index 00000000..8a695b46
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_column_groups.dart
@@ -0,0 +1,400 @@
+part of 'chat_stack_column.dart';
+
+/// The open column's groups: opening one, dragging and dropping between
+/// items and groups, and the semantic actions that do the same.
+mixin _ChatStackColumnGroups
+ on State, TickerProviderStateMixin {
+ ChatStackDrag get _drag;
+ void _move(LongPressMoveUpdateDetails details);
+
+ /// The group being opened or open; null on the top level.
+ String? _openGroup;
+
+ /// The group drawn (also while it folds back into its pile).
+ ChatStackGroupNode? _shownGroup;
+ int _shownSlot = 0;
+ late final AnimationController _groupOpen = AnimationController(
+ vsync: this,
+ duration: chatStackOpenDuration,
+ reverseDuration: chatStackCloseDuration,
+ animationBehavior: AnimationBehavior.preserve,
+ )..addStatusListener(_groupStatus);
+ late final Animation _topOpacity = ReverseAnimation(
+ _groupOpen.drive(CurveTween(curve: const Interval(0, .6))),
+ );
+ ChatStackMotion? _groupMotion;
+ Object? _groupMotionKey;
+
+ bool get _reduced => _drag.reduced;
+ List get _nodes => widget.nodes;
+ ChatStackGroupActions? get _groups => widget.groups;
+
+ /// A hold lifts an item when there is something to do with it.
+ bool get _draggable =>
+ widget.interactive &&
+ ((widget.onReorder != null && _nodes.length > 1) ||
+ widget.onRemove != null ||
+ (_groups != null && _nodes.length > 1));
+
+ void _initGroups() {
+ widget.group.addListener(_groupChanged);
+ // Folded and opened again: straight back into the open group.
+ final node = switch (widget.group.value) {
+ final name? => _groupNamed(name),
+ null => null,
+ };
+ if (node == null) {
+ widget.group.value = null;
+ return;
+ }
+ _openGroup = node.name;
+ _shownGroup = node;
+ _shownSlot = _nodes.indexOf(node) + 1;
+ _groupOpen.value = 1;
+ }
+
+ void _groupsUpdated(ChatStackColumn oldWidget) {
+ if (!identical(oldWidget.group, widget.group)) {
+ oldWidget.group.removeListener(_groupChanged);
+ widget.group.addListener(_groupChanged);
+ }
+ final open = _openGroup;
+ if (open == null) return;
+ final node = _groupNamed(open);
+ if (node != null) {
+ _shownGroup = node;
+ } else {
+ // The group dissolved (or left on another device): back to the top.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && widget.group.value == open) widget.group.value = null;
+ });
+ }
+ }
+
+ void _disposeGroups() {
+ widget.group.removeListener(_groupChanged);
+ _groupMotion?.dispose();
+ _groupOpen.dispose();
+ }
+
+ ChatStackGroupNode? _groupNamed(String name) => _nodes
+ .whereType()
+ .where((node) => node.name == name)
+ .firstOrNull;
+
+ void _groupChanged() {
+ final name = widget.group.value;
+ _drag.cancel();
+ if (name != null) {
+ final node = _groupNamed(name);
+ if (node == null) {
+ widget.group.value = null;
+ return;
+ }
+ setState(() {
+ _openGroup = name;
+ _shownGroup = node;
+ _shownSlot = _nodes.indexOf(node) + 1;
+ });
+ if (_reduced) {
+ _groupOpen.value = 1;
+ } else {
+ _groupOpen.forward();
+ }
+ } else {
+ setState(() => _openGroup = null);
+ if (_reduced) {
+ _groupOpen.value = 0;
+ } else {
+ _groupOpen.reverse();
+ }
+ }
+ }
+
+ void _groupStatus(AnimationStatus status) {
+ if (status == AnimationStatus.dismissed && _openGroup == null && mounted) {
+ setState(() => _shownGroup = null);
+ }
+ }
+
+ /// The open group's motion: its chats rise from its pile to the column.
+ ChatStackMotion? _openGroupMotion(bool rtl) {
+ final node = _shownGroup;
+ if (node == null) return null;
+ final entries = node.entries;
+ final current = entries.indexWhere((entry) => entry.current);
+ final top = current < 0 ? 0 : current;
+ final n = entries.length;
+ final depths = [
+ for (var i = 0; i < n; i++)
+ if ((i - top) % n case final depth when depth < chatStackGroupLayers)
+ depth
+ else
+ null,
+ null,
+ ];
+ final key = Object.hashAll([_reduced, rtl, _shownSlot, ...depths]);
+ if (_groupMotion != null && key == _groupMotionKey) return _groupMotion;
+ _groupMotion?.dispose();
+ _groupMotionKey = key;
+ return _groupMotion = ChatStackMotion(
+ parent: _groupOpen,
+ depths: depths,
+ reduced: _reduced,
+ rtl: rtl,
+ originSlot: _shownSlot,
+ pileScale: chatStackGroupPileScale,
+ );
+ }
+
+ List get _groupItems => [
+ for (final entry in _shownGroup?.entries ?? const [])
+ ChatStackChatNode(entry),
+ ];
+
+ Widget _groupLayer(ChatStackMotion motion, double labelMax) {
+ final group = _shownGroup!;
+ final items = _groupItems;
+ final order = [for (var i = 0; i <= items.length; i++) i]
+ ..sort(
+ // The pile's deeper (smaller) layers first, its top last.
+ (a, b) => motion.from[a].scale.compareTo(motion.from[b].scale),
+ );
+ final lifted = items.indexWhere((node) => node.key == _drag.lifted);
+ if (lifted >= 0) order.add(order.removeAt(order.indexOf(lifted)));
+ return IgnorePointer(
+ ignoring: _openGroup == null,
+ child: ChatStackColumnItems(
+ key: ValueKey('chat-stack-group-${group.name}'),
+ motion: motion,
+ nodes: items,
+ tail: ChatStackHeaderTail(
+ group,
+ onMenu: _groups == null ? null : (at) => _menu(group.name, at),
+ ),
+ order: order,
+ labelMax: labelMax,
+ drag: _drag,
+ draggable: widget.interactive && _openGroup != null,
+ onOpen: (node) => widget.onOpen(node.entries.single),
+ onTail: () => widget.group.value = null,
+ onDragStart: _startInGroup,
+ onDragMove: _move,
+ onDragEnd: _endInGroup,
+ actionsFor: _inGroupActions,
+ tailActions: _groupActions(group.name),
+ ),
+ );
+ }
+
+ /// The keys of the items a drag moves among, as it started.
+ List _dragOrder() => _openGroup != null
+ ? [for (final node in _groupItems) node.key, ChatStackHeaderTail.key]
+ : [for (final node in _nodes) node.key];
+
+ void _openNode(ChatStackNode node) => switch (node) {
+ ChatStackChatNode(:final entry) => widget.onOpen(entry),
+ ChatStackGroupNode(:final name) => widget.group.value = name,
+ };
+
+ void _startTop(ChatStackNode node) {
+ if (!_draggable) return;
+ _drag.start(
+ node.key,
+ _dragOrder(),
+ canDropOnto: _groups == null ? null : (_) => true,
+ );
+ }
+
+ void _endTop(ChatStackNode dragged) {
+ if (!_drag.dragging) return;
+ final nodes = _nodes;
+ final from = nodes.indexOf(dragged);
+ switch (_drag.end()) {
+ case ChatStackDropMove(:final index):
+ widget.onReorder?.call(chatStackMoved(nodes, from, index));
+ case ChatStackDropOnto(:final index):
+ _join(from, index);
+ case ChatStackDropRemove():
+ switch (dragged) {
+ case ChatStackChatNode(:final entry):
+ widget.onRemove?.call(entry);
+ case ChatStackGroupNode(:final name):
+ _groups?.ungroup(name);
+ }
+ case ChatStackDropBack():
+ break;
+ }
+ }
+
+ void _join(int from, int onto) {
+ final groups = _groups;
+ if (groups == null || from < 0) return;
+ final joined = chatStackJoined(_nodes, from, onto, _nextName);
+ groups.join(joined.join, joined.group, joined.order);
+ // A new group asks for its name at once; the default stands if not.
+ if (joined.created) _rename(joined.group, title: 'Name the group');
+ }
+
+ String _nextName() {
+ final used = {
+ for (final node in _nodes)
+ if (node is ChatStackGroupNode) node.name,
+ };
+ for (var n = 1; ; n++) {
+ if (!used.contains('Group $n')) return 'Group $n';
+ }
+ }
+
+ void _startInGroup(ChatStackNode node) {
+ final order = _dragOrder();
+ _drag.start(
+ node.key,
+ order,
+ canDropOnto: _groups == null ? null : (i) => i == order.length - 1,
+ lastSlot: order.length - 2,
+ );
+ }
+
+ void _endInGroup(ChatStackNode dragged) {
+ if (!_drag.dragging) return;
+ final group = _shownGroup;
+ if (group == null) return;
+ final items = _groupItems;
+ final from = items.indexWhere((node) => node.key == dragged.key);
+ final id = dragged.entries.single.sessionId;
+ switch (_drag.end()) {
+ case ChatStackDropMove(:final index):
+ _regroup(group.name, chatStackMoved(items, from, index));
+ case ChatStackDropOnto():
+ _leave(group.name, id);
+ case ChatStackDropRemove():
+ widget.onRemove?.call(dragged.entries.single);
+ case ChatStackDropBack():
+ break;
+ }
+ }
+
+ void _regroup(String group, List groupOrder) =>
+ widget.onReorder?.call(chatStackRegrouped(_nodes, group, groupOrder));
+
+ void _leave(String group, String sessionId) =>
+ _groups?.leave([sessionId], chatStackLeft(_nodes, group, sessionId));
+
+ Future _rename(String group, {String title = 'Rename group'}) async {
+ final name = await showChatStackRenameDialog(
+ context,
+ current: group,
+ title: title,
+ );
+ if (!mounted || name == null || name == group) return;
+ _groups?.rename(group, name);
+ if (widget.group.value == group) widget.group.value = name;
+ }
+
+ Future _menu(String group, Rect at) async {
+ final action = await showChatStackGroupMenu(context, anchor: at);
+ if (mounted && action != null) _groupAction(group, action);
+ }
+
+ void _groupAction(String group, ChatStackGroupAction action) {
+ final groups = _groups;
+ if (groups == null) return;
+ switch (action) {
+ case ChatStackGroupAction.rename:
+ _rename(group);
+ case ChatStackGroupAction.ungroup:
+ widget.group.value = null;
+ groups.ungroup(group);
+ case ChatStackGroupAction.closeAll:
+ widget.group.value = null;
+ groups.closeAll(group);
+ }
+ }
+
+ Map _groupActions(String group) => {
+ if (_groups != null)
+ for (final action in ChatStackGroupAction.values)
+ CustomSemanticsAction(label: action.label): () =>
+ _groupAction(group, action),
+ };
+
+ /// Up is toward the top of the column: a later place in the order.
+ Map _moves(
+ int index,
+ int count,
+ void Function(int to) move,
+ ) => {
+ if (widget.onReorder != null && index < count - 1)
+ const CustomSemanticsAction(label: ChatStackColumn.moveUpLabel): () =>
+ move(index + 1),
+ if (widget.onReorder != null && index > 0)
+ const CustomSemanticsAction(label: ChatStackColumn.moveDownLabel): () =>
+ move(index - 1),
+ };
+
+ Map _topActions(
+ ChatStackNode node,
+ int index,
+ ) {
+ final nodes = _nodes;
+ final remove = widget.onRemove;
+ final groupNodes = nodes.whereType().toList();
+ return {
+ ..._moves(
+ index,
+ nodes.length,
+ (to) => widget.onReorder?.call(chatStackMoved(nodes, index, to)),
+ ),
+ if (node case ChatStackChatNode(:final entry)) ...{
+ if (_groups != null && groupNodes.isNotEmpty)
+ const CustomSemanticsAction(
+ label: ChatStackColumn.moveToGroupLabel,
+ ): () =>
+ _moveToGroup(index, groupNodes),
+ if (remove != null)
+ const CustomSemanticsAction(label: ChatStackColumn.removeLabel): () =>
+ remove(entry),
+ },
+ if (node case ChatStackGroupNode(:final name)) ..._groupActions(name),
+ };
+ }
+
+ Future _moveToGroup(int index, List groups) async {
+ final name = await showChatStackMoveToGroupDialog(
+ context,
+ groups: [for (final group in groups) group.name],
+ );
+ if (!mounted || name == null) return;
+ final onto = _nodes.indexWhere(
+ (node) => node is ChatStackGroupNode && node.name == name,
+ );
+ if (onto >= 0 && index < _nodes.length) _join(index, onto);
+ }
+
+ Map _inGroupActions(
+ ChatStackNode node,
+ int index,
+ ) {
+ final group = _shownGroup;
+ if (group == null) return const {};
+ final items = _groupItems;
+ final entry = node.entries.single;
+ final remove = widget.onRemove;
+ return {
+ ..._moves(
+ index,
+ items.length,
+ (to) => _regroup(group.name, chatStackMoved(items, index, to)),
+ ),
+ if (_groups != null)
+ const CustomSemanticsAction(
+ label: ChatStackColumn.leaveGroupLabel,
+ ): () =>
+ _leave(group.name, entry.sessionId),
+ if (remove != null)
+ const CustomSemanticsAction(label: ChatStackColumn.removeLabel): () =>
+ remove(entry),
+ };
+ }
+}
diff --git a/app/lib/features/chat/stack/chat_stack_column_items.dart b/app/lib/features/chat/stack/chat_stack_column_items.dart
new file mode 100644
index 00000000..2f44a818
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_column_items.dart
@@ -0,0 +1,371 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/semantics.dart';
+
+import '../../../ui/theme/app_design_tokens.dart';
+import 'chat_stack_disc.dart';
+import 'chat_stack_drag.dart';
+import 'chat_stack_drag_shift.dart';
+import 'chat_stack_entry.dart';
+import 'chat_stack_group_pile.dart';
+import 'chat_stack_handles.dart';
+import 'chat_stack_motion.dart';
+import 'chat_stack_node.dart';
+import 'chat_stack_pose.dart';
+
+/// The item at the top of a column: Add chat on the top level, the group's
+/// header (back to the top level) in an open group.
+sealed class ChatStackTail {
+ const ChatStackTail();
+}
+
+class ChatStackAddTail extends ChatStackTail {
+ const ChatStackAddTail();
+ static const label = 'Add chat';
+}
+
+class ChatStackHeaderTail extends ChatStackTail {
+ const ChatStackHeaderTail(this.group, {this.onMenu});
+ static const key = 'tail:header';
+ final ChatStackGroupNode group;
+
+ /// Opens the group's menu, anchored to the given global rect.
+ final ValueChanged? onMenu;
+}
+
+/// The open column's items (chats and groups) and its tail, each placed at
+/// the stack's slot and moved by the open motion ([ChatStackPoseTransition])
+/// and by a drag ([ChatStackDragShift]), painted in [order].
+class ChatStackColumnItems extends StatelessWidget {
+ const ChatStackColumnItems({
+ super.key,
+ required this.motion,
+ required this.nodes,
+ required this.tail,
+ required this.order,
+ required this.labelMax,
+ required this.drag,
+ required this.draggable,
+ required this.onOpen,
+ required this.onTail,
+ required this.onDragStart,
+ required this.onDragMove,
+ required this.onDragEnd,
+ required this.actionsFor,
+ this.tailActions,
+ });
+
+ final ChatStackMotion motion;
+ final List nodes;
+ final ChatStackTail tail;
+
+ /// Item indices in paint order, the last on top; [nodes.length] is the
+ /// tail.
+ final List order;
+ final double labelMax;
+ final ChatStackDrag drag;
+
+ /// Whether a hold lifts an item.
+ final bool draggable;
+ final ValueChanged onOpen;
+ final VoidCallback onTail;
+ final ValueChanged onDragStart;
+ final ValueChanged onDragMove;
+ final ValueChanged onDragEnd;
+ final Map Function(
+ ChatStackNode node,
+ int index,
+ )
+ actionsFor;
+ final Map? tailActions;
+
+ @override
+ Widget build(BuildContext context) => Stack(
+ clipBehavior: Clip.none,
+ children: [
+ for (final i in order) ...[_label(context, i), _item(context, i)],
+ ],
+ );
+
+ ChatStackNode? _node(int i) => i < nodes.length ? nodes[i] : null;
+
+ String _keyOf(ChatStackNode? node) => switch (node) {
+ ChatStackChatNode(:final entry) => entry.paneId,
+ ChatStackGroupNode(:final name) => 'group-$name',
+ null => tail is ChatStackAddTail ? 'add' : 'header',
+ };
+
+ /// The drag key [i] paints with; Add chat never moves.
+ String? _dragKey(int i) {
+ final node = _node(i);
+ if (node != null) return node.key;
+ return tail is ChatStackHeaderTail ? ChatStackHeaderTail.key : null;
+ }
+
+ Widget _handle(ChatStackNode? node, Widget child) => ChatStackDragHandle(
+ onStart: node == null || !draggable ? null : () => onDragStart(node),
+ onMove: onDragMove,
+ onEnd: node == null ? null : () => onDragEnd(node),
+ onCancel: drag.cancel,
+ child: child,
+ );
+
+ Widget _shift(int i, Widget child, {bool scales = true}) {
+ final key = _dragKey(i);
+ return key == null
+ ? child
+ : ChatStackDragShift(
+ item: drag.item(key),
+ scales: scales,
+ child: child,
+ );
+ }
+
+ /// The lifted look while dragged; the drop-target ring while a dragged
+ /// item would land on it.
+ (Animation?, Color?) _lift(BuildContext context, String? key) {
+ if (key == null) return (null, null);
+ if (key == drag.lifted) return (drag.lift, null);
+ if (!drag.dragging) return (null, null);
+ return (drag.glow(key), Theme.of(context).colorScheme.primary);
+ }
+
+ Widget _item(BuildContext context, int i) {
+ final node = _node(i);
+ final name = _keyOf(node);
+ return PositionedDirectional(
+ key: ValueKey('chat-stack-item-$name'),
+ end: 0,
+ bottom: 0,
+ // The transforms are outermost: the boxes under them sit at the
+ // stack's slot, and only a transform passes hits on to where it paints
+ // them.
+ child: ChatStackPoseTransition(
+ progress: motion.move[i],
+ from: motion.from[i],
+ to: motion.target[i],
+ child: _shift(
+ i,
+ FadeTransition(
+ opacity: motion.fade[i],
+ child: KeyedSubtree(
+ key: ValueKey('chat-stack-button-$name'),
+ child: switch (node) {
+ ChatStackChatNode() => _chatButton(context, node, i),
+ ChatStackGroupNode() => _groupButton(context, node, i),
+ null => _tailButton(context),
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _label(BuildContext context, int i) {
+ final node = _node(i);
+ final (lift, ring) = _lift(context, _dragKey(i));
+ final tail = this.tail;
+ final Widget label = switch (node) {
+ ChatStackChatNode(:final entry) => ChatStackLabel(
+ text: entry.title,
+ color: entry.color(context),
+ emphasized: entry.current,
+ lift: lift,
+ liftRing: ring,
+ ),
+ ChatStackGroupNode(:final name, :final entries) => ChatStackLabel(
+ text: name,
+ detail: '${entries.length}',
+ emphasized: node.current,
+ lift: lift,
+ liftRing: ring,
+ ),
+ null => switch (tail) {
+ ChatStackAddTail() => const ChatStackLabel(
+ text: ChatStackAddTail.label,
+ ),
+ ChatStackHeaderTail(:final group, :final onMenu) => ChatStackLabel(
+ text: group.name,
+ detail: '${group.entries.length}',
+ emphasized: true,
+ lift: lift,
+ liftRing: ring,
+ trailing: onMenu == null ? null : _MenuButton(onMenu: onMenu),
+ ),
+ },
+ };
+ return PositionedDirectional(
+ key: ValueKey('chat-stack-label-${_keyOf(node)}'),
+ end: kChatStackSlot + kChatStackLabelGap,
+ bottom: 0,
+ height: kChatStackSlot,
+ child: ChatStackPoseTransition(
+ progress: motion.label[i],
+ from: motion.labelFrom[i],
+ to: motion.target[i],
+ // The pill moves with its avatar but keeps its size, so the gap
+ // between them stays even.
+ child: _shift(
+ i,
+ scales: false,
+ ExcludeSemantics(
+ child: FadeTransition(
+ opacity: motion.label[i],
+ child: Align(
+ alignment: AlignmentDirectional.centerEnd,
+ widthFactor: 1,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: labelMax),
+ child: _handle(
+ node,
+ GestureDetector(
+ onTap: node == null ? onTail : () => onOpen(node),
+ child: label,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _chatButton(BuildContext context, ChatStackChatNode node, int i) {
+ final entry = node.entry;
+ final ring = entry.current
+ ? entry.color(context) ?? Theme.of(context).colorScheme.primary
+ : null;
+ final (lift, liftRing) = _lift(context, node.key);
+ return _semantics(
+ node,
+ i,
+ label: entry.title,
+ selected: entry.current,
+ hint: entry.current ? 'Open now' : null,
+ child: _handle(
+ node,
+ ChatStackTappable(
+ autofocus: entry.current,
+ onTap: () => onOpen(node),
+ child: ChatStackDisc(
+ ring: ring,
+ lift: lift,
+ liftRing: liftRing,
+ child: chatStackAvatar(entry),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _groupButton(BuildContext context, ChatStackGroupNode node, int i) {
+ final (lift, liftRing) = _lift(context, node.key);
+ return _semantics(
+ node,
+ i,
+ label: '${node.name}, group of ${node.entries.length}',
+ selected: node.current,
+ hint: 'Open group',
+ child: _handle(
+ node,
+ ChatStackTappable(
+ onTap: () => onOpen(node),
+ child: ChatStackGroupPile(
+ entries: node.entries,
+ glow: lift,
+ ring: liftRing,
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _semantics(
+ ChatStackNode node,
+ int i, {
+ required String label,
+ required bool selected,
+ required Widget child,
+ String? hint,
+ }) {
+ final actions = actionsFor(node, i);
+ return Semantics(
+ container: true,
+ button: true,
+ selected: selected,
+ label: label,
+ hint: hint,
+ onTap: () => onOpen(node),
+ customSemanticsActions: actions.isEmpty ? null : actions,
+ child: child,
+ );
+ }
+
+ Widget _tailButton(BuildContext context) {
+ final scheme = Theme.of(context).colorScheme;
+ final tokens = AppDesignTokens.of(context);
+ final tail = this.tail;
+ final header = tail is ChatStackHeaderTail;
+ final (lift, ring) = _lift(context, _dragKey(nodes.length));
+ final actions = tailActions;
+ return Semantics(
+ container: true,
+ button: true,
+ label: switch (tail) {
+ ChatStackAddTail() => ChatStackAddTail.label,
+ ChatStackHeaderTail(:final group) => '${group.name}, back to all chats',
+ },
+ onTap: onTail,
+ customSemanticsActions: actions == null || actions.isEmpty
+ ? null
+ : actions,
+ child: ChatStackTappable(
+ onTap: onTail,
+ child: ChatStackDisc(
+ lift: lift,
+ liftRing: ring,
+ child: DecoratedBox(
+ decoration: ShapeDecoration(
+ color: tokens.flat || header ? null : scheme.primaryContainer,
+ shape: chatStackShape(tokens).copyWith(
+ side: tokens.flat
+ ? BorderSide(color: scheme.primary.withValues(alpha: .55))
+ : BorderSide.none,
+ ),
+ ),
+ child: Icon(
+ header ? Icons.arrow_back : Icons.add,
+ color: tokens.flat || header
+ ? scheme.primary
+ : scheme.onPrimaryContainer,
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// The group header's menu button, inside its pill.
+class _MenuButton extends StatelessWidget {
+ const _MenuButton({required this.onMenu});
+ final ValueChanged onMenu;
+
+ @override
+ Widget build(BuildContext context) => SizedBox.square(
+ dimension: 28,
+ child: IconButton(
+ key: const Key('chat-stack-group-menu'),
+ tooltip: 'Group actions',
+ padding: EdgeInsets.zero,
+ iconSize: 18,
+ onPressed: () {
+ final box = context.findRenderObject() as RenderBox;
+ onMenu(box.localToGlobal(Offset.zero) & box.size);
+ },
+ icon: const Icon(Icons.more_horiz),
+ ),
+ );
+}
diff --git a/app/lib/features/chat/stack/chat_stack_disc.dart b/app/lib/features/chat/stack/chat_stack_disc.dart
index 7f317378..8abad562 100644
--- a/app/lib/features/chat/stack/chat_stack_disc.dart
+++ b/app/lib/features/chat/stack/chat_stack_disc.dart
@@ -22,13 +22,26 @@ const double kChatStackLabelGap = 10;
/// through each other, and its rim separates them. A raised design drops a
/// short shadow; a flat one casts none, and its avatar frames itself.
class ChatStackDisc extends StatelessWidget {
- const ChatStackDisc({super.key, required this.child, this.ring});
+ const ChatStackDisc({
+ super.key,
+ required this.child,
+ this.ring,
+ this.lift,
+ this.liftRing,
+ });
final Widget child;
/// The rim's colour when it marks the current chat; null for the surface.
final Color? ring;
+ /// While dragged (0 at rest, 1 lifted): a deeper shadow, or under a flat
+ /// design a frame in the primary colour.
+ final Animation? lift;
+
+ /// A drop target's ring colour, worn as [lift] runs.
+ final Color? liftRing;
+
@override
Widget build(BuildContext context) {
final tokens = AppDesignTokens.of(context);
@@ -42,16 +55,20 @@ class ChatStackDisc extends StatelessWidget {
);
final ring = this.ring;
final shape = chatStackShape(tokens);
+ final rest = ShapeDecoration(
+ color: ring ?? base,
+ // A flat design's avatar frames itself; the rim stays bare.
+ shape: shape,
+ shadows: !tokens.flat ? chatStackShadows(scheme) : null,
+ );
+ final lift = this.lift;
return SizedBox.square(
dimension: kChatStackSlot,
child: Center(
- child: DecoratedBox(
- decoration: ShapeDecoration(
- color: ring ?? base,
- // A flat design's avatar frames itself; the rim stays bare.
- shape: shape,
- shadows: !tokens.flat ? chatStackShadows(scheme) : null,
- ),
+ child: chatStackLifted(
+ lift,
+ rest,
+ chatStackRaised(rest, tokens, scheme, ring: liftRing),
child: SizedBox.square(
dimension: kChatStackDisc,
child: Center(
@@ -93,6 +110,59 @@ List chatStackShadows(ColorScheme scheme) => [
),
];
+/// A short, close shadow's lifted form: deeper and softer, as a card
+/// picked up off the column.
+List chatStackLiftShadows(ColorScheme scheme) => [
+ BoxShadow(
+ color: scheme.shadow.withValues(alpha: .20),
+ blurRadius: 8,
+ offset: const Offset(0, 4),
+ ),
+ BoxShadow(
+ color: scheme.shadow.withValues(alpha: .14),
+ blurRadius: 22,
+ offset: const Offset(0, 12),
+ ),
+];
+
+/// [rest] as a dragged item wears it: the lifted shadow, or under a flat
+/// design (which casts none) a frame in the primary colour. With [ring] (a
+/// drop target) every design gets a ring in that colour.
+ShapeDecoration chatStackRaised(
+ ShapeDecoration rest,
+ AppDesignTokens tokens,
+ ColorScheme scheme, {
+ Color? ring,
+}) {
+ final shape = rest.shape;
+ final side = ring != null
+ ? BorderSide(color: ring, width: 2)
+ : tokens.flat
+ ? BorderSide(color: scheme.primary, width: 1.5)
+ : null;
+ return ShapeDecoration(
+ color: rest.color,
+ shape: side != null && shape is OutlinedBorder
+ ? shape.copyWith(side: side)
+ : shape,
+ shadows: tokens.flat ? null : chatStackLiftShadows(scheme),
+ );
+}
+
+/// [child] over [rest], or blending to [raised] as [lift] runs: repaints
+/// only.
+Widget chatStackLifted(
+ Animation? lift,
+ ShapeDecoration rest,
+ ShapeDecoration raised, {
+ required Widget child,
+}) => lift == null
+ ? DecoratedBox(decoration: rest, child: child)
+ : DecoratedBoxTransition(
+ decoration: DecorationTween(begin: rest, end: raised).animate(lift),
+ child: child,
+ );
+
/// The name beside an avatar in the open column: a small pill tinted with
/// the chat's colour over an opaque face, one line, ellipsised.
class ChatStackLabel extends StatelessWidget {
@@ -101,12 +171,28 @@ class ChatStackLabel extends StatelessWidget {
required this.text,
this.color,
this.emphasized = false,
+ this.lift,
+ this.liftRing,
+ this.detail,
+ this.trailing,
});
final String text;
+
+ /// A muted note after the text (a group's chat count).
+ final String? detail;
+
+ /// A small control at the end (the group header's menu).
+ final Widget? trailing;
+
+ /// A drop target's ring colour, worn as [lift] runs.
+ final Color? liftRing;
final Color? color;
final bool emphasized;
+ /// While dragged, as [ChatStackDisc.lift].
+ final Animation? lift;
+
@override
Widget build(BuildContext context) {
final tokens = AppDesignTokens.of(context);
@@ -122,26 +208,56 @@ class ChatStackLabel extends StatelessWidget {
color: scheme.onSurface,
fontWeight: emphasized ? FontWeight.w700 : FontWeight.w500,
);
- return DecoratedBox(
- decoration: ShapeDecoration(
- color: fill,
- shape: _labelShape(tokens),
- shadows: tokens.flat ? null : chatStackShadows(scheme),
- ),
+ final rest = ShapeDecoration(
+ color: fill,
+ shape: _labelShape(tokens),
+ shadows: tokens.flat ? null : chatStackShadows(scheme),
+ );
+ return chatStackLifted(
+ lift,
+ rest,
+ chatStackRaised(rest, tokens, scheme, ring: liftRing),
child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
- child: Text(
- text,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- softWrap: false,
- style: style,
+ padding: EdgeInsetsDirectional.only(
+ start: 12,
+ end: trailing == null ? 12 : 2,
+ top: 6,
+ bottom: 6,
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Flexible(
+ child: Text(
+ text,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ softWrap: false,
+ style: style,
+ ),
+ ),
+ if (detail case final detail?) ...[
+ const SizedBox(width: 6),
+ Text(
+ detail,
+ maxLines: 1,
+ style: style.copyWith(
+ color: scheme.onSurfaceVariant,
+ fontWeight: FontWeight.w500,
+ ),
+ ),
+ ],
+ if (trailing case final trailing?) ...[
+ const SizedBox(width: 2),
+ trailing,
+ ],
+ ],
),
),
);
}
- ShapeBorder _labelShape(AppDesignTokens tokens) {
+ OutlinedBorder _labelShape(AppDesignTokens tokens) {
final side = tokens.frameSide ?? BorderSide.none;
final r = tokens.radius;
return r == null
diff --git a/app/lib/features/chat/stack/chat_stack_drag.dart b/app/lib/features/chat/stack/chat_stack_drag.dart
new file mode 100644
index 00000000..c481b8e2
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_drag.dart
@@ -0,0 +1,341 @@
+import 'dart:ui' show lerpDouble;
+
+import 'package:flutter/animation.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+
+import 'chat_stack_drop_target.dart';
+
+part 'chat_stack_drag_types.dart';
+
+/// One drag in the open column: which item is lifted, the slot it would
+/// drop into or the item it would drop onto, whether it is over the remove
+/// target, and the motion of every item. It notifies only when a drag
+/// starts or ends (the column then rebuilds once); each pointer move only
+/// repaints the items that move.
+class ChatStackDrag extends ChangeNotifier {
+ ChatStackDrag({required TickerProvider vsync, required this.pitch})
+ : _vsync = vsync {
+ lift = AnimationController(vsync: vsync, duration: chatStackShiftDuration)
+ ..addListener(_paintLifted);
+ settle =
+ AnimationController(vsync: vsync, duration: chatStackSettleDuration)
+ ..addListener(_paintLifted)
+ ..addStatusListener(_settled);
+ removeShown = AnimationController(
+ vsync: vsync,
+ duration: chatStackRemoveDuration,
+ );
+ hover = AnimationController(vsync: vsync, duration: chatStackHoverDuration)
+ ..addListener(_paintLifted);
+ _ontoAny = AnimationController(
+ vsync: vsync,
+ duration: chatStackHoverDuration,
+ )..addListener(_paintLifted);
+ }
+
+ /// 1 while the item is over another's middle: it shrinks onto it, so the
+ /// target's grown ring shows around it.
+ late final AnimationController _ontoAny;
+
+ final TickerProvider _vsync;
+
+ /// The distance between neighbouring slots.
+ final double pitch;
+
+ /// Under reduced motion neighbours swap at once and nothing slides.
+ bool reduced = false;
+
+ late final AnimationController lift;
+ late final AnimationController settle;
+
+ /// The remove target arming, and its highlight while the item is over it.
+ late final AnimationController removeShown;
+ late final AnimationController hover;
+
+ final Map _items = {};
+ final Map _shifts = {};
+ final Map _glows = {};
+
+ /// The item being dragged or settling; it paints above the others.
+ String? get lifted => _lifted;
+ String? _lifted;
+
+ /// The items' order when the drag started; null when none is dragged.
+ List? get order => _order;
+ List? _order;
+ int _from = 0;
+ int? _slot;
+ int? _onto;
+ bool Function(int index)? _canDropOnto;
+ int? _lastSlot;
+ bool _over = false;
+ Offset _pointer = Offset.zero;
+ Offset _residual = Offset.zero;
+
+ bool get dragging => _order != null;
+ bool get overRemove => _over;
+
+ /// The item the dragged one would drop onto, if any.
+ String? get ontoKey => _onto == null ? null : _order?[_onto!];
+
+ /// Where [key]'s item is painted; created on first use.
+ ChatStackDragItem item(String key) =>
+ _items.putIfAbsent(key, ChatStackDragItem.new);
+
+ /// 0 at rest, 1 while the dragged item is over [key]'s (to drop onto it).
+ Animation glow(String key) => _glows.putIfAbsent(key, () {
+ final glow = AnimationController(
+ vsync: _vsync,
+ duration: chatStackHoverDuration,
+ );
+ glow.addListener(() => _paint(key));
+ return glow;
+ });
+
+ static const _curve = Curves.easeOutCubic;
+
+ /// Lifts [key] out of [order] (the items, without Add chat). A drop on the
+ /// middle of an item [canDropOnto] accepts lands on it; the gap never
+ /// goes past [lastSlot] (an item after it is a target only).
+ void start(
+ String key,
+ List order, {
+ bool Function(int index)? canDropOnto,
+ int? lastSlot,
+ }) {
+ final from = order.indexOf(key);
+ if (from < 0) return;
+ if (_lifted != null) _finishSettle();
+ _order = List.of(order);
+ _from = from;
+ _slot = from;
+ _onto = null;
+ _canDropOnto = canDropOnto;
+ _lastSlot = lastSlot;
+ _over = false;
+ _pointer = Offset.zero;
+ _residual = Offset.zero;
+ _lifted = key;
+ HapticFeedback.mediumImpact();
+ if (reduced) {
+ lift.value = 1;
+ removeShown.value = 1;
+ } else {
+ lift.forward(from: 0);
+ removeShown.forward();
+ }
+ hover.value = 0;
+ notifyListeners();
+ }
+
+ /// The pointer moved [fromOrigin] since the press; [overRemove] says
+ /// whether it is over the remove target.
+ void move(Offset fromOrigin, {required bool overRemove}) {
+ final order = _order;
+ if (order == null) return;
+ _pointer = fromOrigin;
+ if (overRemove != _over) {
+ _over = overRemove;
+ if (overRemove) HapticFeedback.selectionClick();
+ _run(hover, overRemove ? 1 : 0);
+ }
+ // Far to the side of the column, or over the remove target, there is no
+ // slot: the gap closes and a drop there puts the item back.
+ int? slot;
+ int? onto;
+ if (!overRemove && fromOrigin.dx.abs() <= pitch * 1.5) {
+ final target = chatStackDropTarget(
+ position: _from - fromOrigin.dy / pitch,
+ from: _from,
+ count: order.length,
+ slot: _slot ?? _from,
+ canDropOnto: _canDropOnto,
+ lastSlot: _lastSlot,
+ );
+ slot = target.slot;
+ onto = target.onto;
+ }
+ if (onto != _onto) {
+ final before = _onto;
+ _onto = onto;
+ if (onto != null) HapticFeedback.selectionClick();
+ if (before != null) _run(glow(order[before]) as AnimationController, 0);
+ if (onto != null) _run(glow(order[onto]) as AnimationController, 1);
+ _run(_ontoAny, onto == null ? 0 : 1);
+ }
+ if (slot != _slot) {
+ if (slot != null && _slot != null) HapticFeedback.selectionClick();
+ _slot = slot;
+ _shiftNeighbours(animate: !reduced);
+ }
+ _paintLifted();
+ }
+
+ /// Ends the drag and says what the drop does; the motion back (or into
+ /// the new slot) runs from here.
+ ChatStackDrop end() {
+ final order = _order;
+ if (order == null) return const ChatStackDropBack();
+ final slot = _slot;
+ final onto = _onto;
+ final ChatStackDrop drop = _over
+ ? const ChatStackDropRemove()
+ : onto != null
+ ? ChatStackDropOnto(onto)
+ : slot != null && slot != _from
+ ? ChatStackDropMove(slot)
+ : const ChatStackDropBack();
+ _order = null;
+ _slot = null;
+ switch (drop) {
+ case ChatStackDropMove(:final index):
+ // The new order puts the neighbours where they are now drawn; the
+ // dragged item glides from the finger into its new slot.
+ _residual = _pointer + Offset(0, (index - _from) * pitch);
+ _shiftNeighbours(animate: false);
+ case ChatStackDropRemove() || ChatStackDropOnto():
+ // It joins the target (or leaves): no glide back.
+ _residual = Offset.zero;
+ _shiftNeighbours(animate: false);
+ case ChatStackDropBack():
+ _residual = _pointer;
+ _shiftNeighbours(animate: !reduced);
+ }
+ _release(clearGlowAtOnce: drop is ChatStackDropOnto);
+ return drop;
+ }
+
+ /// Puts the item back where it was (Escape, a cancelled pointer, the
+ /// column folding).
+ void cancel() {
+ if (_order == null) return;
+ _order = null;
+ _slot = null;
+ _residual = _pointer;
+ _shiftNeighbours(animate: !reduced);
+ _release();
+ }
+
+ void _release({bool clearGlowAtOnce = false}) {
+ _pointer = Offset.zero;
+ if (_over) HapticFeedback.selectionClick();
+ _over = false;
+ _onto = null;
+ clearGlowAtOnce ? _ontoAny.value = 0 : _run(_ontoAny, 0);
+ for (final glow in _glows.values) {
+ clearGlowAtOnce ? glow.value = 0 : _run(glow, 0);
+ }
+ if (reduced) {
+ hover.value = 0;
+ removeShown.value = 0;
+ lift.value = 0;
+ _residual = Offset.zero;
+ _finishSettle();
+ return;
+ }
+ hover.reverse();
+ removeShown.reverse();
+ lift.reverse();
+ settle.forward(from: 0);
+ }
+
+ void _run(AnimationController controller, double target) {
+ if (reduced) {
+ controller.value = target;
+ } else {
+ controller.animateTo(target, curve: _curve);
+ }
+ }
+
+ void _settled(AnimationStatus status) {
+ if (status == AnimationStatus.completed) _finishSettle();
+ }
+
+ void _finishSettle() {
+ settle.stop();
+ final key = _lifted;
+ _residual = Offset.zero;
+ if (key != null) item(key)._set(Offset.zero, 1);
+ if (_order != null) return;
+ _lifted = null;
+ notifyListeners();
+ }
+
+ void _paintLifted() {
+ final key = _lifted;
+ if (key == null) return;
+ // Over the remove target the item shrinks into it, so the target's lit
+ // rim shows around it.
+ final scale =
+ lerpDouble(1, chatStackLiftScale, _curve.transform(lift.value))! *
+ lerpDouble(1, chatStackOverRemoveScale, hover.value)! *
+ lerpDouble(1, chatStackOverRemoveScale, _ontoAny.value)!;
+ final offset = _order != null
+ ? _pointer
+ : _residual * (1 - _curve.transform(settle.value));
+ item(key)._set(offset, scale);
+ }
+
+ /// Paints a neighbour: slid by its shift, grown by its glow.
+ void _paint(String key) {
+ if (key == _lifted) return;
+ final shift = _shifts[key]?.value ?? 0;
+ final glow = _glows[key]?.value ?? 0;
+ item(
+ key,
+ )._set(Offset(0, shift * pitch), lerpDouble(1, chatStackOntoScale, glow)!);
+ }
+
+ /// Slides each neighbour aside to open the gap at the current slot, or
+ /// back home when there is none.
+ void _shiftNeighbours({required bool animate}) {
+ final order = _order ?? const [];
+ final keys = {...order, ..._shifts.keys};
+ final slot = _slot;
+ for (final key in keys) {
+ if (key == _lifted && _order != null) continue;
+ final i = order.indexOf(key);
+ var target = 0.0;
+ if (slot != null && i >= 0) {
+ // Down (toward the thumb) when the lifted item goes above it, up
+ // when it goes below.
+ if (_from < slot && i > _from && i <= slot) target = 1;
+ if (slot < _from && i >= slot && i < _from) target = -1;
+ }
+ final shift = _shifts.putIfAbsent(key, () {
+ final shift = AnimationController.unbounded(vsync: _vsync);
+ shift.addListener(() => _paint(key));
+ return shift;
+ });
+ if (shift.value == target) continue;
+ if (animate) {
+ shift.animateTo(
+ target,
+ duration: chatStackShiftDuration,
+ curve: _curve,
+ );
+ } else {
+ shift
+ ..stop()
+ ..value = target;
+ }
+ }
+ }
+
+ @override
+ void dispose() {
+ lift.dispose();
+ settle.dispose();
+ removeShown.dispose();
+ hover.dispose();
+ _ontoAny.dispose();
+ for (final controller in [..._shifts.values, ..._glows.values]) {
+ controller.dispose();
+ }
+ for (final item in _items.values) {
+ item.dispose();
+ }
+ super.dispose();
+ }
+}
diff --git a/app/lib/features/chat/stack/chat_stack_drag_shift.dart b/app/lib/features/chat/stack/chat_stack_drag_shift.dart
new file mode 100644
index 00000000..292499a8
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_drag_shift.dart
@@ -0,0 +1,145 @@
+import 'package:flutter/rendering.dart';
+import 'package:flutter/widgets.dart';
+
+import 'chat_stack_drag.dart';
+
+/// Paints [child] where [item] says while a chat of the open column is
+/// dragged: moved, and scaled about its centre when [scales]. A change only
+/// repaints (the matrix and the layer are reused); hit tests follow it. At
+/// rest it paints straight through, with no layer.
+class ChatStackDragShift extends SingleChildRenderObjectWidget {
+ const ChatStackDragShift({
+ super.key,
+ required this.item,
+ this.scales = true,
+ super.child,
+ });
+
+ final ChatStackDragItem item;
+ final bool scales;
+
+ @override
+ RenderChatStackDragShift createRenderObject(BuildContext context) =>
+ RenderChatStackDragShift(item: item, scales: scales);
+
+ @override
+ void updateRenderObject(
+ BuildContext context,
+ RenderChatStackDragShift renderObject,
+ ) {
+ renderObject
+ ..item = item
+ ..scales = scales;
+ }
+}
+
+class RenderChatStackDragShift extends RenderProxyBox {
+ RenderChatStackDragShift({
+ required ChatStackDragItem item,
+ required bool scales,
+ }) {
+ _item = item;
+ _scales = scales;
+ }
+
+ late ChatStackDragItem _item;
+ set item(ChatStackDragItem value) {
+ if (identical(value, _item)) return;
+ if (attached) _item.removeListener(_changed);
+ _item = value;
+ if (attached) _item.addListener(_changed);
+ _changed();
+ }
+
+ late bool _scales;
+ set scales(bool value) {
+ if (value == _scales) return;
+ _scales = value;
+ _changed();
+ }
+
+ final Matrix4 _matrix = Matrix4.identity();
+ final LayerHandle _layer = LayerHandle();
+
+ bool get _moved =>
+ _item.offset != Offset.zero || (_scales && _item.scale != 1);
+
+ bool _wasMoved = false;
+
+ void _changed() {
+ // Entering or leaving rest adds or drops the transform layer.
+ final moved = _moved;
+ if (moved != _wasMoved) {
+ _wasMoved = moved;
+ markNeedsCompositingBitsUpdate();
+ }
+ markNeedsPaint();
+ }
+
+ @override
+ void attach(PipelineOwner owner) {
+ super.attach(owner);
+ _wasMoved = _moved;
+ _item.addListener(_changed);
+ }
+
+ @override
+ void detach() {
+ _item.removeListener(_changed);
+ super.detach();
+ }
+
+ @override
+ void dispose() {
+ _layer.layer = null;
+ super.dispose();
+ }
+
+ @override
+ bool get alwaysNeedsCompositing => child != null && _moved;
+
+ Matrix4 _current() {
+ final offset = _item.offset;
+ final scale = _scales ? _item.scale : 1.0;
+ final cx = size.width / 2;
+ final cy = size.height / 2;
+ return _matrix
+ ..setIdentity()
+ ..translateByDouble(offset.dx + cx, offset.dy + cy, 0, 1)
+ ..scaleByDouble(scale, scale, 1, 1)
+ ..translateByDouble(-cx, -cy, 0, 1);
+ }
+
+ @override
+ void paint(PaintingContext context, Offset offset) {
+ if (child == null) return;
+ if (!_moved) {
+ _layer.layer = null;
+ super.paint(context, offset);
+ return;
+ }
+ _layer.layer = context.pushTransform(
+ needsCompositing,
+ offset,
+ _current(),
+ super.paint,
+ oldLayer: _layer.layer,
+ );
+ }
+
+ @override
+ bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
+ if (!_moved) return super.hitTestChildren(result, position: position);
+ return result.addWithPaintTransform(
+ transform: _current(),
+ position: position,
+ hitTest: (result, position) =>
+ super.hitTestChildren(result, position: position),
+ );
+ }
+
+ @override
+ void applyPaintTransform(RenderBox child, Matrix4 transform) {
+ if (_moved) transform.multiply(_current());
+ }
+}
diff --git a/app/lib/features/chat/stack/chat_stack_drag_types.dart b/app/lib/features/chat/stack/chat_stack_drag_types.dart
new file mode 100644
index 00000000..923e23b0
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_drag_types.dart
@@ -0,0 +1,68 @@
+part of 'chat_stack_drag.dart';
+
+/// How long a press is held before a chat lifts for a drag: long enough
+/// that a tap still opens it, short enough to feel immediate.
+const Duration chatStackLiftDelay = Duration(milliseconds: 300);
+
+/// The lifted avatar's scale.
+const double chatStackLiftScale = 1.1;
+
+/// The lifted avatar's scale, relative to lifted, over the remove target.
+const double chatStackOverRemoveScale = .8;
+
+/// The scale of an item a dragged one would drop onto (to group).
+const double chatStackOntoScale = 1.14;
+
+/// How long the neighbours take to slide aside, and the lifted item to
+/// settle into its slot (or back) after the drop.
+const Duration chatStackShiftDuration = Duration(milliseconds: 200);
+const Duration chatStackSettleDuration = Duration(milliseconds: 220);
+
+/// How long the remove target takes to arm and to light up, and a drop
+/// target to grow.
+const Duration chatStackRemoveDuration = Duration(milliseconds: 180);
+const Duration chatStackHoverDuration = Duration(milliseconds: 140);
+
+/// Where one item of the open column is painted relative to its slot while
+/// another is dragged; a render object repaints when it changes.
+class ChatStackDragItem extends ChangeNotifier {
+ Offset _offset = Offset.zero;
+ double _scale = 1;
+
+ Offset get offset => _offset;
+ double get scale => _scale;
+
+ void _set(Offset offset, double scale) {
+ if (offset == _offset && scale == _scale) return;
+ _offset = offset;
+ _scale = scale;
+ notifyListeners();
+ }
+}
+
+/// What a drop does.
+sealed class ChatStackDrop {
+ const ChatStackDrop();
+}
+
+/// Nothing: the item settles back into its own slot.
+class ChatStackDropBack extends ChatStackDrop {
+ const ChatStackDropBack();
+}
+
+/// The item moves to [index] among the items.
+class ChatStackDropMove extends ChatStackDrop {
+ const ChatStackDropMove(this.index);
+ final int index;
+}
+
+/// The item drops onto the item at [index] (to group the two).
+class ChatStackDropOnto extends ChatStackDrop {
+ const ChatStackDropOnto(this.index);
+ final int index;
+}
+
+/// The item drops on the remove target.
+class ChatStackDropRemove extends ChatStackDrop {
+ const ChatStackDropRemove();
+}
diff --git a/app/lib/features/chat/stack/chat_stack_drop_target.dart b/app/lib/features/chat/stack/chat_stack_drop_target.dart
new file mode 100644
index 00000000..c71ee528
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_drop_target.dart
@@ -0,0 +1,50 @@
+/// Where a dragged item of the open column would land.
+///
+/// [position] is the dragged item's place in slots (its start index, plus
+/// the slots it moved up; fractional), [from] its start index, [count] the
+/// items, and [slot] the gap it opened so far (never past [lastSlot]). The
+/// others are drawn around that gap. The middle half of each one
+/// [canDropOnto] accepts is a drop on it; its outer quarters (or all of one
+/// that accepts none) move the gap before or after it. The
+/// gap itself holds while the item is within half a slot of it, so the
+/// answer is stable: an item that slides aside never lands back under the
+/// finger.
+({int slot, int? onto}) chatStackDropTarget({
+ required double position,
+ required int from,
+ required int count,
+ required int slot,
+ bool Function(int index)? canDropOnto,
+ int? lastSlot,
+}) {
+ final last = lastSlot ?? count - 1;
+ if (count < 2 || (position - slot).abs() <= .5) {
+ return (slot: slot, onto: null);
+ }
+ // The neighbour drawn nearest the position: its index and drawn place.
+ var nearest = -1;
+ var drawn = 0;
+ var distance = double.infinity;
+ for (var i = 0; i < count; i++) {
+ if (i == from) continue;
+ final rank = i < from ? i : i - 1;
+ final place = rank < slot ? rank : rank + 1;
+ final d = (position - place).abs();
+ if (d < distance) {
+ distance = d;
+ nearest = i;
+ drawn = place;
+ }
+ }
+ if (distance <= .25 && (canDropOnto?.call(nearest) ?? false)) {
+ return (slot: slot, onto: nearest);
+ }
+ final int next;
+ if (position < drawn) {
+ // Before it (below, toward the thumb).
+ next = drawn > slot ? drawn - 1 : drawn;
+ } else {
+ next = drawn < slot ? drawn + 1 : drawn;
+ }
+ return (slot: next.clamp(0, last), onto: null);
+}
diff --git a/app/lib/features/chat/stack/chat_stack_entry.dart b/app/lib/features/chat/stack/chat_stack_entry.dart
index 8133c6a3..8827dbcf 100644
--- a/app/lib/features/chat/stack/chat_stack_entry.dart
+++ b/app/lib/features/chat/stack/chat_stack_entry.dart
@@ -15,6 +15,7 @@ class ChatStackEntry {
required this.paneId,
required this.session,
this.current = false,
+ this.group,
});
final String paneId;
@@ -23,6 +24,9 @@ class ChatStackEntry {
/// Whether this is the chat on screen.
final bool current;
+ /// The chat stack group it is in, or null.
+ final String? group;
+
String get sessionId => '${session['id'] ?? ''}';
String get title => chatSessionTitle(session);
diff --git a/app/lib/features/chat/stack/chat_stack_fab.dart b/app/lib/features/chat/stack/chat_stack_fab.dart
index eafa67bb..da23e0f1 100644
--- a/app/lib/features/chat/stack/chat_stack_fab.dart
+++ b/app/lib/features/chat/stack/chat_stack_fab.dart
@@ -3,10 +3,12 @@ import 'package:flutter/material.dart';
import '../../../ui/motion/motion.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../ui/sessions/chat_awaiting.dart';
+import 'chat_stack_actions.dart';
import 'chat_stack_column.dart';
import 'chat_stack_disc.dart';
import 'chat_stack_entry.dart';
import 'chat_stack_motion.dart';
+import 'chat_stack_node.dart';
import 'chat_stack_pose.dart';
/// The phone's chat stack: the open chats' avatars piled up, the chat on
@@ -20,6 +22,8 @@ class ChatStackFab extends StatefulWidget {
required this.onOpen,
required this.onAdd,
this.onRemove,
+ this.onReorder,
+ this.groups,
});
/// The open chats in their synced order; one is [ChatStackEntry.current].
@@ -30,6 +34,13 @@ class ChatStackFab extends StatefulWidget {
final ValueChanged onAdd;
final ValueChanged? onRemove;
+ /// Puts the open chats in this order (session ids): a drag in the open
+ /// column, or its Move up and Move down actions.
+ final ValueChanged>? onReorder;
+
+ /// Grouping the open chats; null when the host keeps no groups.
+ final ChatStackGroupActions? groups;
+
@override
State createState() => ChatStackFabState();
}
@@ -48,6 +59,9 @@ class ChatStackFabState extends State
final _slot = GlobalKey(debugLabel: 'Chat stack slot');
final _focus = FocusNode(debugLabel: 'Chat stack');
+ /// The group open in the column, or null on its top level.
+ final _group = ValueNotifier(null);
+
/// The pile hides the moment the column starts to move; under reduced
/// motion the two cross-fade in place instead.
late final Animation _hiddenWhileOpen = _open.drive(_ShownAtRest());
@@ -94,6 +108,7 @@ class ChatStackFabState extends State
_motion?.dispose();
_open.dispose();
_focus.dispose();
+ _group.dispose();
super.dispose();
}
@@ -128,6 +143,7 @@ class ChatStackFabState extends State
/// Folds the column back into the stack; [immediate] skips the motion.
void collapse({bool immediate = false}) {
if (!_expanded) return;
+ _group.value = null;
setState(() => _expanded = false);
if (immediate) {
_open.value = 0;
@@ -156,6 +172,39 @@ class ChatStackFabState extends State
widget.onAdd(context);
}
+ /// The groups' actions; ungrouping and closing fold the column, so the
+ /// snack bar's Undo is in reach.
+ ChatStackGroupActions? _groupActions() {
+ final groups = widget.groups;
+ if (groups == null) return null;
+ return ChatStackGroupActions(
+ join: groups.join,
+ leave: groups.leave,
+ rename: groups.rename,
+ ungroup: (group) {
+ collapse();
+ groups.ungroup(group);
+ },
+ closeAll: (group) {
+ collapse();
+ groups.closeAll(group);
+ },
+ );
+ }
+
+ /// Each top-level item's layer in the pile: a group's is its top chat's.
+ List _nodeDepths(List nodes, List depths) {
+ final entries = widget.entries;
+ return [
+ for (final node in nodes)
+ node.entries
+ .map((entry) => depths[entries.indexOf(entry)])
+ .whereType()
+ .fold(null, (a, b) => a == null || b < a ? b : a),
+ null,
+ ];
+ }
+
/// Each item's layer in the pile: the chat on screen on top, then the
/// chats after it in order, wrapping; the add item is never in the pile.
List _depths() {
@@ -191,15 +240,23 @@ class ChatStackFabState extends State
Widget build(BuildContext context) {
final entries = widget.entries;
final depths = _depths();
+ final nodes = chatStackNodes(entries);
+ final nodeDepths = _nodeDepths(nodes, depths);
final rtl = Directionality.of(context) == TextDirection.rtl;
- final motion = _motionFor(depths, rtl);
+ final motion = _motionFor(nodeDepths, rtl);
final hidden = _keyboard || entries.isEmpty;
final remove = widget.onRemove;
final canRemove = remove != null && entries.length > 1;
return PopScope(
canPop: !_expanded,
onPopInvokedWithResult: (didPop, _) {
- if (!didPop) collapse();
+ if (didPop) return;
+ // Back leaves an open group first.
+ if (_group.value != null) {
+ _group.value = null;
+ } else {
+ collapse();
+ }
},
child: OverlayPortal(
controller: _portal,
@@ -209,13 +266,16 @@ class ChatStackFabState extends State
return ChatStackColumn(
motion: motion,
anchor: anchor,
- entries: entries,
- depths: depths,
+ nodes: nodes,
+ depths: nodeDepths,
+ group: _group,
interactive: _expanded,
onOpen: _choose,
onAdd: _add,
onDismiss: collapse,
onRemove: canRemove ? _remove : null,
+ onReorder: widget.onReorder,
+ groups: _groupActions(),
);
},
child: AnimatedOpacity(
diff --git a/app/lib/features/chat/stack/chat_stack_group_dialogs.dart b/app/lib/features/chat/stack/chat_stack_group_dialogs.dart
new file mode 100644
index 00000000..0096ef9d
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_group_dialogs.dart
@@ -0,0 +1,109 @@
+import 'package:flutter/material.dart';
+
+import 'chat_stack_groups.dart';
+
+/// The group actions a group offers in its menu and as semantic actions.
+enum ChatStackGroupAction {
+ rename('Rename group'),
+ ungroup('Ungroup'),
+ closeAll('Close all chats in group');
+
+ const ChatStackGroupAction(this.label);
+ final String label;
+}
+
+/// Asks for a group name, starting from [current] (selected, so typing
+/// replaces it); null when cancelled or left empty.
+Future showChatStackRenameDialog(
+ BuildContext context, {
+ required String current,
+ String title = 'Rename group',
+}) => showDialog(
+ context: context,
+ builder: (context) => _RenameDialog(current: current, title: title),
+);
+
+class _RenameDialog extends StatefulWidget {
+ const _RenameDialog({required this.current, required this.title});
+ final String current;
+ final String title;
+
+ @override
+ State<_RenameDialog> createState() => _RenameDialogState();
+}
+
+class _RenameDialogState extends State<_RenameDialog> {
+ late final TextEditingController _name =
+ TextEditingController(text: widget.current)
+ ..selection = TextSelection(
+ baseOffset: 0,
+ extentOffset: widget.current.length,
+ );
+
+ @override
+ void dispose() {
+ _name.dispose();
+ super.dispose();
+ }
+
+ void _save() => Navigator.of(context).pop(chatStackGroupName(_name.text));
+
+ @override
+ Widget build(BuildContext context) => AlertDialog(
+ title: Text(widget.title),
+ content: TextField(
+ key: const Key('chat-stack-group-name'),
+ controller: _name,
+ autofocus: true,
+ maxLength: chatStackGroupNameLimit,
+ decoration: const InputDecoration(labelText: 'Group name'),
+ textInputAction: TextInputAction.done,
+ onSubmitted: (_) => _save(),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(onPressed: _save, child: const Text('Save')),
+ ],
+ );
+}
+
+/// Asks which of [groups] a chat moves to; null when cancelled.
+Future showChatStackMoveToGroupDialog(
+ BuildContext context, {
+ required List groups,
+}) => showDialog(
+ context: context,
+ builder: (context) => SimpleDialog(
+ title: const Text('Move to group'),
+ children: [
+ for (final group in groups)
+ SimpleDialogOption(
+ onPressed: () => Navigator.of(context).pop(group),
+ child: Text(group),
+ ),
+ ],
+ ),
+);
+
+/// The group's menu (Rename, Ungroup, Close all) at [anchor] (global).
+Future showChatStackGroupMenu(
+ BuildContext context, {
+ required Rect anchor,
+}) {
+ final overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
+ final local = Rect.fromPoints(
+ overlay.globalToLocal(anchor.topLeft),
+ overlay.globalToLocal(anchor.bottomRight),
+ );
+ return showMenu(
+ context: context,
+ position: RelativeRect.fromRect(local, Offset.zero & overlay.size),
+ items: [
+ for (final action in ChatStackGroupAction.values)
+ PopupMenuItem(value: action, child: Text(action.label)),
+ ],
+ );
+}
diff --git a/app/lib/features/chat/stack/chat_stack_group_ops.dart b/app/lib/features/chat/stack/chat_stack_group_ops.dart
new file mode 100644
index 00000000..0b74779c
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_group_ops.dart
@@ -0,0 +1,104 @@
+import 'chat_stack_entry.dart';
+import 'chat_stack_node.dart';
+
+/// The open-chat order after the node at [from] moves to [to].
+List chatStackMoved(List nodes, int from, int to) {
+ final next = List.of(nodes);
+ next.insert(to.clamp(0, nodes.length - 1), next.removeAt(from));
+ return chatStackOrder(next);
+}
+
+/// What dropping one node onto another does: [join] chats go into [group]
+/// (a new group when [created]), and the open chats take [order], the
+/// group's chats together where the target was.
+typedef ChatStackJoin = ({
+ List join,
+ String group,
+ bool created,
+ List order,
+});
+
+/// Dropping the node at [from] onto the one at [onto]:
+/// - a chat onto a chat makes a group of the two ([newName]), the target
+/// first;
+/// - a chat onto a group joins it, last;
+/// - a group onto a chat takes the chat in, last;
+/// - a group onto a group merges into the target.
+ChatStackJoin chatStackJoined(
+ List nodes,
+ int from,
+ int onto,
+ String Function() newName,
+) {
+ final dragged = nodes[from];
+ final target = nodes[onto];
+ final String group;
+ final bool created;
+ final List joining;
+ final ChatStackNode host;
+ switch ((dragged, target)) {
+ case (ChatStackChatNode(), ChatStackChatNode()):
+ group = newName();
+ created = true;
+ joining = [...target.entries, ...dragged.entries];
+ host = target;
+ case (_, ChatStackGroupNode(:final name)):
+ group = name;
+ created = false;
+ joining = dragged.entries;
+ host = target;
+ case (ChatStackGroupNode(:final name), ChatStackChatNode()):
+ group = name;
+ created = false;
+ joining = target.entries;
+ host = dragged;
+ }
+ final members = [
+ ...host.entries,
+ for (final entry in [...dragged.entries, ...target.entries])
+ if (!host.entries.contains(entry)) entry,
+ ];
+ // The merged group stands where its host stood.
+ final order = [
+ for (final node in nodes)
+ if (identical(node, host))
+ ...members.map((entry) => entry.sessionId)
+ else if (!identical(node, dragged) && !identical(node, target))
+ ...node.entries.map((entry) => entry.sessionId),
+ ];
+ return (
+ join: [for (final entry in joining) entry.sessionId],
+ group: group,
+ created: created,
+ order: order,
+ );
+}
+
+/// The open-chat order with [group]'s chats in [groupOrder] (session ids).
+List chatStackRegrouped(
+ List nodes,
+ String group,
+ List groupOrder,
+) => [
+ for (final node in nodes)
+ if (node is ChatStackGroupNode && node.name == group)
+ ...groupOrder
+ else
+ ...node.entries.map((entry) => entry.sessionId),
+];
+
+/// The open-chat order with [sessionId] taken out of [group] and placed
+/// right after it (on the top level, beside the group it left).
+List chatStackLeft(
+ List nodes,
+ String group,
+ String sessionId,
+) => [
+ for (final node in nodes)
+ if (node is ChatStackGroupNode && node.name == group) ...[
+ for (final entry in node.entries)
+ if (entry.sessionId != sessionId) entry.sessionId,
+ sessionId,
+ ] else
+ ...node.entries.map((entry) => entry.sessionId),
+];
diff --git a/app/lib/features/chat/stack/chat_stack_group_pile.dart b/app/lib/features/chat/stack/chat_stack_group_pile.dart
new file mode 100644
index 00000000..1b34d2e7
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_group_pile.dart
@@ -0,0 +1,79 @@
+import 'package:flutter/material.dart';
+
+import '../ui/sessions/chat_awaiting.dart';
+import 'chat_stack_disc.dart';
+import 'chat_stack_entry.dart';
+import 'chat_stack_pose.dart';
+
+/// A group's pile is the collapsed stack's, this much smaller, so it keeps
+/// inside its slot.
+const double chatStackGroupPileScale = .88;
+
+/// How many of a group's chats its pile draws.
+const int chatStackGroupLayers = 3;
+
+/// A group in the open column: its first chats piled as the collapsed stack
+/// piles the open ones (smaller, turned), the chat on screen on top when it
+/// is in the group, and the waiting bell when any of them waits on the
+/// operator. Paint-only poses; nothing animates here.
+class ChatStackGroupPile extends StatelessWidget {
+ const ChatStackGroupPile({
+ super.key,
+ required this.entries,
+ this.glow,
+ this.ring,
+ });
+
+ final List entries;
+
+ /// The top layer's lifted look (dragged) or drop-target [ring] (0 to 1).
+ final Animation? glow;
+ final Color? ring;
+
+ @override
+ Widget build(BuildContext context) {
+ final current = entries.indexWhere((entry) => entry.current);
+ final top = current < 0 ? 0 : current;
+ final shown = [
+ for (var depth = 0; depth < entries.length; depth++)
+ entries[(top + depth) % entries.length],
+ ].take(chatStackGroupLayers).toList();
+ final rtl = Directionality.of(context) == TextDirection.rtl;
+ final waiting = entries.fold(0, (sum, e) => sum + e.awaitingOperator);
+ return SizedBox.square(
+ dimension: kChatStackSlot,
+ child: Stack(
+ clipBehavior: Clip.none,
+ children: [
+ for (var depth = shown.length - 1; depth >= 0; depth--)
+ ChatStackPoseTransition(
+ progress: kAlwaysCompleteAnimation,
+ from: _pose(depth, rtl),
+ to: _pose(depth, rtl),
+ child: ChatStackDisc(
+ lift: depth == 0 ? glow : null,
+ liftRing: ring,
+ child: chatStackAvatar(shown[depth], cues: false),
+ ),
+ ),
+ if (waiting > 0)
+ PositionedDirectional(
+ top: -4,
+ end: -4,
+ child: IgnorePointer(child: ChatAwaitingBadge(count: waiting)),
+ ),
+ ],
+ ),
+ );
+ }
+
+ ChatStackPose _pose(int depth, bool rtl) {
+ final layer = chatStackLayers[depth];
+ final pose = ChatStackPose(
+ offset: layer.offset * chatStackGroupPileScale,
+ turn: layer.turn,
+ scale: layer.scale * chatStackGroupPileScale,
+ );
+ return rtl ? pose.mirrored() : pose;
+ }
+}
diff --git a/app/lib/features/chat/stack/chat_stack_groups.dart b/app/lib/features/chat/stack/chat_stack_groups.dart
new file mode 100644
index 00000000..ccd499bb
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_groups.dart
@@ -0,0 +1,94 @@
+import 'package:flutter/foundation.dart';
+
+/// The longest group name, in characters (the server's limit).
+const int chatStackGroupNameLimit = 80;
+
+/// [raw] as a group name: trimmed, without control characters, at most
+/// [chatStackGroupNameLimit] characters; null when nothing is left.
+String? chatStackGroupName(String raw) {
+ final cleaned = raw.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim();
+ if (cleaned.isEmpty) return null;
+ final runes = cleaned.runes.toList();
+ if (runes.length <= chatStackGroupNameLimit) return cleaned;
+ return String.fromCharCodes(runes.take(chatStackGroupNameLimit)).trim();
+}
+
+/// Which open chats belong to which named group in the chat stack.
+///
+/// A group is the set of chats sharing a name; its order is the open-chat
+/// order. A group always has two chats or more: one left alone leaves its
+/// group. The server keeps the names with the open-chat set, so groups sync
+/// across devices; [replaceAll] applies the server's.
+class ChatStackGroups extends ChangeNotifier {
+ final Map _bySession = {};
+
+ /// The group [sessionId] is in, or null.
+ String? groupOf(String sessionId) => _bySession[sessionId];
+
+ /// Every grouped chat and its group.
+ Map get assignments => Map.unmodifiable(_bySession);
+
+ /// The group names in use.
+ Set get names => _bySession.values.toSet();
+
+ /// The chats in [group].
+ List membersOf(String group) => [
+ for (final MapEntry(:key, :value) in _bySession.entries)
+ if (value == group) key,
+ ];
+
+ /// Takes the server's groups (or a restored set) as they are.
+ void replaceAll(Map assignments) => _change(
+ () => _bySession
+ ..clear()
+ ..addAll(assignments),
+ );
+
+ /// Puts [sessionIds] in [group] (joining it, or making it).
+ void assign(Iterable sessionIds, String group) => _change(() {
+ for (final id in sessionIds) {
+ _bySession[id] = group;
+ }
+ });
+
+ /// Takes [sessionIds] out of their groups.
+ void unassign(Iterable sessionIds) => _change(() {
+ sessionIds.forEach(_bySession.remove);
+ });
+
+ /// Renames [from] to [to]; a name already in use merges the two groups.
+ void rename(String from, String to) => _change(() {
+ for (final entry in _bySession.entries.toList()) {
+ if (entry.value == from) _bySession[entry.key] = to;
+ }
+ });
+
+ /// Dissolves [group]: its chats stay open, ungrouped.
+ void ungroup(String group) =>
+ _change(() => _bySession.removeWhere((_, value) => value == group));
+
+ /// Drops chats that are no longer open.
+ void retain(Set open) =>
+ _change(() => _bySession.removeWhere((id, _) => !open.contains(id)));
+
+ /// The first "Group N" not in use.
+ String nextName() {
+ final used = names;
+ for (var n = 1; ; n++) {
+ final name = 'Group $n';
+ if (!used.contains(name)) return name;
+ }
+ }
+
+ void _change(VoidCallback change) {
+ final before = Map.of(_bySession);
+ change();
+ // A group of one is no group.
+ final counts = {};
+ for (final group in _bySession.values) {
+ counts[group] = (counts[group] ?? 0) + 1;
+ }
+ _bySession.removeWhere((_, group) => (counts[group] ?? 0) < 2);
+ if (!mapEquals(before, _bySession)) notifyListeners();
+ }
+}
diff --git a/app/lib/features/chat/stack/chat_stack_handles.dart b/app/lib/features/chat/stack/chat_stack_handles.dart
new file mode 100644
index 00000000..3bb76256
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_handles.dart
@@ -0,0 +1,95 @@
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+
+import '../../../ui/theme/app_design_tokens.dart';
+import 'chat_stack_disc.dart';
+import 'chat_stack_drag.dart';
+
+/// Lifts [child] for a drag after a short hold ([chatStackLiftDelay]); a
+/// quicker tap still reaches [child]'s own tap. Null callbacks leave the
+/// child alone.
+class ChatStackDragHandle extends StatelessWidget {
+ const ChatStackDragHandle({
+ super.key,
+ required this.child,
+ this.onStart,
+ this.onMove,
+ this.onEnd,
+ this.onCancel,
+ });
+
+ final Widget child;
+ final VoidCallback? onStart;
+ final ValueChanged? onMove;
+ final VoidCallback? onEnd;
+ final VoidCallback? onCancel;
+
+ @override
+ Widget build(BuildContext context) {
+ if (onStart == null) return child;
+ return RawGestureDetector(
+ // The items offer moving and removing as semantic actions instead.
+ excludeFromSemantics: true,
+ gestures: {
+ LongPressGestureRecognizer:
+ GestureRecognizerFactoryWithHandlers(
+ () => LongPressGestureRecognizer(
+ duration: chatStackLiftDelay,
+ debugOwner: this,
+ ),
+ (recognizer) {
+ recognizer
+ ..onLongPressStart = ((_) => onStart?.call())
+ ..onLongPressMoveUpdate = onMove
+ ..onLongPressEnd = ((_) => onEnd?.call())
+ ..onLongPressCancel = onCancel;
+ },
+ ),
+ },
+ child: child,
+ );
+ }
+}
+
+/// A disc's ink and focus: the splash is drawn over the disc (the disc is
+/// opaque, so ink under it would never show), in the design's shape.
+class ChatStackTappable extends StatelessWidget {
+ const ChatStackTappable({
+ super.key,
+ required this.child,
+ required this.onTap,
+ this.autofocus = false,
+ });
+
+ final Widget child;
+ final VoidCallback onTap;
+ final bool autofocus;
+
+ @override
+ Widget build(BuildContext context) {
+ final shape = chatStackShape(AppDesignTokens.of(context));
+ return Stack(
+ children: [
+ child,
+ Positioned.fill(
+ child: Padding(
+ padding: const EdgeInsets.all(
+ (kChatStackSlot - kChatStackDisc) / 2,
+ ),
+ child: Material(
+ type: MaterialType.transparency,
+ shape: shape,
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ autofocus: autofocus,
+ excludeFromSemantics: true,
+ customBorder: shape,
+ onTap: onTap,
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/app/lib/features/chat/stack/chat_stack_motion.dart b/app/lib/features/chat/stack/chat_stack_motion.dart
index 25653705..d683d26e 100644
--- a/app/lib/features/chat/stack/chat_stack_motion.dart
+++ b/app/lib/features/chat/stack/chat_stack_motion.dart
@@ -20,24 +20,30 @@ const Curve chatStackRise = Cubic(.22, 1.18, .36, 1);
const Curve chatStackFold = Curves.easeInCubic;
/// Every animation the open column reads, derived once from one controller
-/// when the items change (never per frame). Item 0 is nearest the thumb; the
-/// column rises from there, each item starting a little after the one below
-/// it, and folds back top first.
+/// when the items change (never per frame). Item 0 is nearest the thumb, a
+/// pitch above the stack's slot (where the close button is); the column
+/// rises from there, each item starting a little after the one below it,
+/// and folds back top first.
class ChatStackMotion {
ChatStackMotion({
required Animation parent,
required List depths,
required this.reduced,
required bool rtl,
+ int originSlot = 0,
+ double pileScale = 1,
}) : count = depths.length {
scrim = _curve(parent, const Interval(0, .7, curve: Curves.easeOut));
+ close = reduced ? parent : _curve(parent, const Interval(0, .6));
final span = count <= 1 ? 1.0 : .62;
final step = count <= 1 ? 0.0 : (1 - span) / (count - 1);
for (var i = 0; i < count; i++) {
final start = i * step;
final end = math.min(1.0, start + span);
final depth = depths[i];
- final to = chatStackColumnPose(i, kChatStackPitch);
+ // The stack's own slot holds the close button; the column starts a
+ // pitch above it.
+ final to = chatStackColumnPose(i + 1, kChatStackPitch);
final layer = chatStackLayers[depth ?? chatStackLayers.length - 1];
target.add(to);
if (reduced) {
@@ -48,7 +54,15 @@ class ChatStackMotion {
labelFrom.add(to);
continue;
}
- from.add(rtl ? layer.mirrored() : layer);
+ // From its layer in the pile (a group's smaller pile [originSlot]
+ // slots up the column).
+ final pile = ChatStackPose(
+ offset:
+ layer.offset * pileScale + Offset(0, -originSlot * kChatStackPitch),
+ turn: layer.turn,
+ scale: layer.scale * pileScale,
+ );
+ from.add(rtl ? pile.mirrored() : pile);
move.add(
_curve(
parent,
@@ -75,6 +89,9 @@ class ChatStackMotion {
final int count;
final bool reduced;
late final Animation scrim;
+
+ /// The close button taking the pile's place.
+ late final Animation close;
final List from = [];
final List target = [];
final List> move = [];
diff --git a/app/lib/features/chat/stack/chat_stack_node.dart b/app/lib/features/chat/stack/chat_stack_node.dart
new file mode 100644
index 00000000..c65dd8b4
--- /dev/null
+++ b/app/lib/features/chat/stack/chat_stack_node.dart
@@ -0,0 +1,76 @@
+import 'package:flutter/foundation.dart';
+
+import 'chat_stack_entry.dart';
+
+/// One item of the open column's top level: a chat, or a group of chats.
+@immutable
+sealed class ChatStackNode {
+ const ChatStackNode();
+
+ /// Stable across rebuilds and reorders: keys widgets and drag state.
+ String get key;
+
+ /// The chats it stands for, in order.
+ List get entries;
+
+ /// Whether the chat on screen is in it.
+ bool get current => entries.any((entry) => entry.current);
+
+ /// Unanswered approvals and questions across its chats.
+ int get awaitingOperator =>
+ entries.fold(0, (sum, entry) => sum + entry.awaitingOperator);
+}
+
+/// A chat on its own.
+class ChatStackChatNode extends ChatStackNode {
+ const ChatStackChatNode(this.entry);
+ final ChatStackEntry entry;
+
+ @override
+ String get key => 'chat:${entry.paneId}';
+
+ @override
+ List get entries => [entry];
+}
+
+/// A named group of chats.
+class ChatStackGroupNode extends ChatStackNode {
+ const ChatStackGroupNode(this.name, this.entries);
+ final String name;
+
+ @override
+ final List entries;
+
+ @override
+ String get key => 'group:$name';
+}
+
+/// [entries] (in the open-chat order) as the top level shows them: each
+/// group where its first chat is, holding its chats in order, and the
+/// ungrouped chats on their own.
+List chatStackNodes(List entries) {
+ final groups = >{};
+ for (final entry in entries) {
+ final group = entry.group;
+ if (group != null) (groups[group] ??= []).add(entry);
+ }
+ final nodes = [];
+ final placed = {};
+ for (final entry in entries) {
+ final group = entry.group;
+ final members = group == null ? null : groups[group];
+ if (group == null || members == null || members.length < 2) {
+ nodes.add(ChatStackChatNode(entry));
+ } else if (placed.add(group)) {
+ nodes.add(ChatStackGroupNode(group, List.unmodifiable(members)));
+ }
+ }
+ return nodes;
+}
+
+/// The open-chat order (session ids) [nodes] stand for, each group's chats
+/// together.
+List chatStackOrder(Iterable nodes) => [
+ for (final node in nodes)
+ for (final entry in node.entries) entry.sessionId,
+];
diff --git a/app/lib/features/chat/stack/mobile_chat_navigation.dart b/app/lib/features/chat/stack/mobile_chat_navigation.dart
index b8802dc1..aca18839 100644
--- a/app/lib/features/chat/stack/mobile_chat_navigation.dart
+++ b/app/lib/features/chat/stack/mobile_chat_navigation.dart
@@ -3,7 +3,8 @@ import 'package:shared_preferences/shared_preferences.dart';
const mobileChatNavigationKey = 'pipelines.mobile-chat-navigation.v1';
-/// How a phone-width layout moves between the open chats.
+/// How a phone-width layout (and any layout on a phone or tablet, an unfolded
+/// foldable too, for the Chat stack) moves between the open chats.
enum MobileChatNavigation {
quickSwitch(
'Quick switch',
@@ -59,7 +60,11 @@ class MobileChatNavigationController extends ChangeNotifier {
static final instance = MobileChatNavigationController();
final MobileChatNavigationStore _store;
- MobileChatNavigation _value = MobileChatNavigation.quickSwitch;
+
+ /// Without a stored choice, the Chat stack.
+ static const fallback = MobileChatNavigation.chatStack;
+
+ MobileChatNavigation _value = fallback;
int _revision = 0;
bool _disposed = false;
bool saveFailed = false;
@@ -91,6 +96,16 @@ class MobileChatNavigationController extends ChangeNotifier {
notifyListeners();
}
+ /// Sets [mode] without saving it (a test's starting point).
+ @visibleForTesting
+ void debugUse(MobileChatNavigation mode) {
+ _revision++;
+ saveFailed = false;
+ if (mode == _value) return;
+ _value = mode;
+ notifyListeners();
+ }
+
@override
void dispose() {
_disposed = true;
diff --git a/app/lib/features/chat/ui/sessions/chat_adaptive.dart b/app/lib/features/chat/ui/sessions/chat_adaptive.dart
index 6dcdc415..b8b70c38 100644
--- a/app/lib/features/chat/ui/sessions/chat_adaptive.dart
+++ b/app/lib/features/chat/ui/sessions/chat_adaptive.dart
@@ -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,
);
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..5e1c05ef 100644
--- a/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart
+++ b/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart
@@ -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),
),
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..e73a0b04 100644
--- a/app/lib/features/chat/ui/sessions/session_row_content.dart
+++ b/app/lib/features/chat/ui/sessions/session_row_content.dart
@@ -13,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.
@@ -90,7 +92,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)),
@@ -275,15 +279,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_automated_prompt.dart b/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart
index 23b89ad3..f7693c71 100644
--- a/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart
+++ b/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart
@@ -69,7 +69,9 @@ class ChatAutomatedPromptCard extends StatelessWidget {
],
),
);
- final transcript = AppDesignTokens.of(context).transcript;
+ final tokens = AppDesignTokens.of(context);
+ final density = tokens.density;
+ final transcript = tokens.transcript;
final card = transcript == TranscriptStyle.manuscript
? PaperEditorialNote(
label: label,
@@ -84,11 +86,18 @@ class ChatAutomatedPromptCard extends StatelessWidget {
color: scheme.surfaceContainerLow,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
- borderRadius: const BorderRadius.all(Radius.circular(16)),
+ borderRadius: tokens.corners(
+ const BorderRadius.all(Radius.circular(16)),
+ ),
side: BorderSide(color: scheme.outlineVariant),
),
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,
diff --git a/app/lib/features/chat/ui/transcript/chat_code_hover.dart b/app/lib/features/chat/ui/transcript/chat_code_hover.dart
index b3c7ecfc..f5f1f761 100644
--- a/app/lib/features/chat/ui/transcript/chat_code_hover.dart
+++ b/app/lib/features/chat/ui/transcript/chat_code_hover.dart
@@ -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),
diff --git a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart
index da8f254b..158c0112 100644
--- a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart
+++ b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart
@@ -272,7 +272,9 @@ class _ChatMarkdownViewState extends State {
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 {
/// 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,
diff --git a/app/lib/features/chat/ui/transcript/chat_message_bubble.dart b/app/lib/features/chat/ui/transcript/chat_message_bubble.dart
index 464fba1f..c6340b70 100644
--- a/app/lib/features/chat/ui/transcript/chat_message_bubble.dart
+++ b/app/lib/features/chat/ui/transcript/chat_message_bubble.dart
@@ -55,15 +55,26 @@ class ChatUserBubble extends StatelessWidget {
break;
}
// 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,
Theme.of(context).colorScheme.surfaceContainerHighest,
),
clipBehavior: Clip.antiAlias,
- shape: const RoundedRectangleBorder(borderRadius: _radius),
- child: Padding(padding: _padding, child: child),
+ shape: RoundedRectangleBorder(borderRadius: tokens.corners(_radius)),
+ child: Padding(
+ padding: density.dense
+ ? EdgeInsets.symmetric(
+ horizontal: density.inset(_padding.left),
+ vertical: density.space(_padding.top),
+ )
+ : _padding,
+ child: child,
+ ),
);
}
}
@@ -89,8 +100,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;
}
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..a2b7a32f 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);
@@ -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(
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/chat/ui/transcript/chat_turn_activity_view.dart b/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart
index 0f0ff06f..98dbfcc7 100644
--- a/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart
+++ b/app/lib/features/chat/ui/transcript/chat_turn_activity_view.dart
@@ -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 {
: 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 {
}
// 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 {
child: const ChatResponsePending(),
),
),
- const SizedBox(width: 8),
+ SizedBox(width: density.space(8)),
],
Flexible(
child: Text(
@@ -179,8 +185,13 @@ class _ChatTurnActivityViewState extends State {
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,
),
diff --git a/app/lib/features/chat/ui/transcript/chat_turn_chip.dart b/app/lib/features/chat/ui/transcript/chat_turn_chip.dart
index 98e5b244..af2c94ee 100644
--- a/app/lib/features/chat/ui/transcript/chat_turn_chip.dart
+++ b/app/lib/features/chat/ui/transcript/chat_turn_chip.dart
@@ -109,9 +109,9 @@ class _ChatTurnChipState extends State {
).corners(BorderRadius.circular(8)),
onTap: _show,
child: Padding(
- padding: const EdgeInsets.symmetric(
+ padding: EdgeInsets.symmetric(
horizontal: chatAgentContentInset,
- vertical: 6,
+ vertical: AppDesignTokens.of(context).density.space(6),
),
child: content,
),
diff --git a/app/lib/features/chat/ui/transcript/shown/chat_shown_notify_row.dart b/app/lib/features/chat/ui/transcript/shown/chat_shown_notify_row.dart
index 693da48d..8271fa94 100644
--- a/app/lib/features/chat/ui/transcript/shown/chat_shown_notify_row.dart
+++ b/app/lib/features/chat/ui/transcript/shown/chat_shown_notify_row.dart
@@ -4,8 +4,9 @@ import '../../../../../core/api_gateway.dart';
import 'chat_shown_surface.dart';
/// What a `notify` entry says: where the notification went (the server's
-/// `channels`: the operator's signed-in Pipelines `apps` and/or their `phone`),
-/// or why it was not sent.
+/// `channels`: the operator's signed-in Pipelines `apps`; `phone` appears only
+/// in entries recorded before the server stopped publishing to a phone push
+/// service), or why it was not sent.
String chatShownNotifyText(JsonMap item) {
final title = chatShownTitle(item, 'notification');
if (item['delivered'] == true) return '${_notifiedWhere(item)}: $title';
diff --git a/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart b/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart
index b5bf1df1..d96ceee1 100644
--- a/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart
+++ b/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart
@@ -1,21 +1,33 @@
import '../../../core/api_gateway.dart';
-/// One chat in the server-owned open-chat set: its session and whether it is
-/// floating. Geometry stays on the device.
+/// One chat in the server-owned open-chat set: its session, whether it is
+/// floating, and the chat stack group it belongs to (entries sharing a name
+/// form one group; null when ungrouped). Geometry stays on the device.
class ChatOpenWorkspaceEntry {
- const ChatOpenWorkspaceEntry(this.sessionId, {this.floating = false});
+ const ChatOpenWorkspaceEntry(
+ this.sessionId, {
+ this.floating = false,
+ this.group,
+ });
final String sessionId;
final bool floating;
+ final String? group;
Map toJson() => {
'session_id': sessionId,
if (floating) 'floating': true,
+ if (group != null) 'group': group,
};
static ChatOpenWorkspaceEntry? fromJson(Object? value) {
if (value is! Map) return null;
final id = '${value['session_id'] ?? ''}'.trim();
+ final group = '${value['group'] ?? ''}'.trim();
return id.isEmpty
? null
- : ChatOpenWorkspaceEntry(id, floating: value['floating'] == true);
+ : ChatOpenWorkspaceEntry(
+ id,
+ floating: value['floating'] == true,
+ group: group.isEmpty ? null : group,
+ );
}
}
@@ -37,7 +49,8 @@ class ChatOpenWorkspaceSnapshot {
if (list.length != entries.length) return false;
for (var i = 0; i < list.length; i++) {
if (list[i].sessionId != entries[i].sessionId ||
- list[i].floating != entries[i].floating) {
+ list[i].floating != entries[i].floating ||
+ list[i].group != entries[i].group) {
return false;
}
}
diff --git a/app/lib/features/chat/workspace/chat_pane_cycle.dart b/app/lib/features/chat/workspace/chat_pane_cycle.dart
new file mode 100644
index 00000000..61352bc0
--- /dev/null
+++ b/app/lib/features/chat/workspace/chat_pane_cycle.dart
@@ -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(List 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];
+}
diff --git a/app/lib/features/chat/workspace/chat_pane_focus_flash.dart b/app/lib/features/chat/workspace/chat_pane_focus_flash.dart
new file mode 100644
index 00000000..da4ac6c7
--- /dev/null
+++ b/app/lib/features/chat/workspace/chat_pane_focus_flash.dart
@@ -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 createState() => _ChatPaneFocusFlashState();
+}
+
+class _ChatPaneFocusFlashState extends State
+ 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,
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart
index c6643a71..7acc1e15 100644
--- a/app/lib/features/chat/workspace/chat_workspace_controller.dart
+++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart
@@ -163,6 +163,31 @@ class ChatWorkspaceController extends ChangeNotifier {
_changed();
}
+ /// Moves the pane [paneId] to [index] in the pane order (the open-chat
+ /// order the server syncs). The panes keep their ids and the splits their
+ /// geometry; only the leaves change slots. The active pane stays.
+ void movePane(String paneId, int index) {
+ final order = panes;
+ final from = order.indexWhere((pane) => pane.id == paneId);
+ if (from < 0) return;
+ final to = index.clamp(0, order.length - 1);
+ if (from == to) return;
+ order.insert(to, order.removeAt(from));
+ reorderSessions([for (final pane in order) pane.sessionId]);
+ }
+
+ /// Puts the panes in the order of [sessionIds], as [movePane] does; open
+ /// chats it does not name keep their relative order after them.
+ void reorderSessions(List sessionIds) {
+ final open = [for (final pane in panes) pane.sessionId];
+ final named = sessionIds.where(open.contains).toSet();
+ final order = [...named, ...open.where((id) => !named.contains(id))];
+ final next = reconcileChatWorkspaceTree(_root, order, _id);
+ if (identical(next, _root)) return;
+ _root = next;
+ _changed();
+ }
+
void resize(String splitId, double ratio) {
if (_root == null || !ratio.isFinite) return;
_root = _resize(_root!, splitId, ratio.clamp(.01, .99));
diff --git a/app/lib/features/graph/domain/stage_run_facts.dart b/app/lib/features/graph/domain/stage_run_facts.dart
new file mode 100644
index 00000000..514fc170
--- /dev/null
+++ b/app/lib/features/graph/domain/stage_run_facts.dart
@@ -0,0 +1,115 @@
+import '../../../core/api_gateway.dart';
+import '../../pipelines/pipeline_format.dart';
+import '../../runs/domain/run_tokens.dart';
+import 'stage_visits.dart';
+
+/// What one run recorded for one stage, for the graph's stage popover.
+///
+/// Read from the run detail's own steps only: a stage the run never visited
+/// has [visits] 0 and nothing else, and nothing is estimated.
+class StageRunFacts {
+ const StageRunFacts({
+ required this.visits,
+ this.status,
+ this.duration,
+ this.usage,
+ this.verdict,
+ this.handoff,
+ this.failure,
+ });
+
+ /// How many recorded visits the stage has.
+ final int visits;
+
+ /// The latest visit's recorded status word.
+ final String? status;
+
+ /// The latest visit's duration, when both timestamps were recorded.
+ final String? duration;
+
+ /// Reported tokens and cost summed over every visit (`12.4k tok · $0.31`).
+ final String? usage;
+
+ /// The latest visit's recorded verdict: `option: reason`.
+ final String? verdict;
+
+ /// The first non-blank line of the latest visit's handoff output.
+ final String? handoff;
+
+ /// The latest visit's recorded diagnostic when it failed.
+ final String? failure;
+}
+
+/// The facts [run] recorded for [stageKey].
+StageRunFacts stageRunFacts(JsonMap run, String stageKey) {
+ final steps = run['steps'];
+ final list = steps is List
+ ? steps.whereType