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().map(JsonMap.from).toList() + : const []; + final visits = visitsByStage(list)[stageKey] ?? const []; + if (visits.isEmpty) return const StageRunFacts(visits: 0); + final latest = visits.last; + final status = _text(latest['status']); + final seconds = durationSeconds( + _text(latest['started_at']), + _text(latest['finished_at']), + ); + var tokens = 0; + var tokensKnown = false; + var cost = 0.0; + var costKnown = false; + for (final visit in visits) { + final usage = stageTokenUsage(visit); + if (usage == null) continue; + tokens += usage.total; + tokensKnown = true; + final visitCost = usage.cost; + if (visitCost != null) { + cost += visitCost; + costKnown = true; + } + } + final verdict = latest['verdict']; + String? verdictText; + if (verdict is Map) { + final option = _text(verdict['option']); + final reason = _firstLine(verdict['reason']); + verdictText = [?option, ?reason].join(': '); + if (verdictText.isEmpty) verdictText = null; + } + final failed = status != null && _failed(status); + return StageRunFacts( + visits: visits.length, + status: status, + duration: seconds == null ? null : formatDuration(seconds), + usage: tokensKnown || costKnown + ? [ + if (tokensKnown) '${formatTokenCount(tokens)} tok', + if (costKnown) '\$${cost.toStringAsFixed(2)}', + ].join(' · ') + : null, + verdict: verdictText, + handoff: _firstLine(latest['output']), + failure: failed ? _firstLine(latest['diagnostic']) : null, + ); +} + +bool _failed(String status) { + final word = status.trim().toLowerCase(); + return word == 'failed' || word == 'error' || word == 'blocked'; +} + +String? _text(dynamic value) { + final text = '${value ?? ''}'.trim(); + return text.isEmpty ? null : text; +} + +String? _firstLine(dynamic value) { + final text = _text(value); + if (text == null) return null; + for (final line in text.split('\n')) { + final trimmed = line.trim().replaceFirst(RegExp(r'^#+\s*'), ''); + if (trimmed.isNotEmpty) return trimmed; + } + return null; +} diff --git a/app/lib/features/graph/domain/stage_summary.dart b/app/lib/features/graph/domain/stage_summary.dart new file mode 100644 index 00000000..ef1db230 --- /dev/null +++ b/app/lib/features/graph/domain/stage_summary.dart @@ -0,0 +1,246 @@ +import 'dart:convert'; + +import 'check_stage.dart'; +import 'graph_definition.dart'; +import 'graph_protocol.dart'; +import 'stage_definition.dart'; + +/// The kind of stage a popover names in its type chip. +enum StageKind { model, check, deliveryGate, findings, human, other, terminal } + +/// The tool set a model stage runs with when it declares no `tools` block: the +/// server's legacy bundle (`legacyTools` in `internal/stage/tools.go`). +const List defaultStageTools = [ + 'read', + 'glob', + 'grep', + 'edit', + 'shell', +]; + +/// One declared outgoing route: `outcome → target`. +typedef StageRoute = ({String outcome, String target}); + +/// A compact, read-only digest of one stage declaration for the graph's stage +/// popover. Pure data: built from the stage JSON the definition graph carries; +/// a field the declaration omits stays empty rather than guessed. +class StageSummary { + const StageSummary({ + required this.key, + required this.kind, + required this.typeLabel, + this.meta = const [], + this.tools = const [], + this.toolsDefault = false, + this.permissions = const [], + this.skills = const [], + this.prompt, + this.commands = const [], + this.gate = const [], + this.limits = const [], + this.routes = const [], + }); + + final String key; + final StageKind kind; + + /// The type chip's word: `Model`, `Check`, `Findings gate`, ... + final String typeLabel; + + /// Short configuration chips in reading order: harness, model, effort, + /// timeout, retries, budget. + final List meta; + + /// The model stage's tools, in declared order. + final List tools; + + /// True when [tools] is the server default because no block was declared. + final bool toolsDefault; + + /// Permission allow-lists as `edit: path, path` lines. + final List permissions; + + final List skills; + + /// A model stage's prompt or a human stage's operator instructions. + final String? prompt; + + /// A check stage's commands, one per line. + final List commands; + + /// A findings gate's severity and origin facts. + final List gate; + + /// Limit facts: `max 3 visits`, `on fail`, `exhausted: decide`. + final List limits; + + /// Declared routes, for a terminal the routes into it. + final List routes; +} + +/// The digest of [key] in [graph], or null when the version does not declare +/// it (a terminal is summarised by its incoming routes instead). +StageSummary? stageSummaryFor(dynamic graph, String key) { + if (isTerminalTarget(key)) { + return StageSummary( + key: key, + kind: StageKind.terminal, + typeLabel: 'End', + routes: [ + for (final edge in graphEdges(graph)) + if (edge.target == key) + (outcome: edge.label, target: nodeDisplayLabel(edge.source)), + ], + ); + } + final stage = stageDefinitionFor(graph, key); + if (stage == null) return null; + final type = effectiveStageType(stage['type']).trim(); + final kind = switch (type) { + 'model' => StageKind.model, + 'check' => isDeliveryGate(stage) ? StageKind.deliveryGate : StageKind.check, + 'findings' => StageKind.findings, + 'human' => StageKind.human, + _ => StageKind.other, + }; + final configs = _strings(stage['configs']); + final blocks = _strings(stage['blocks']); + final declaredTools = blocks['tools']; + final tools = kind != StageKind.model + ? const [] + : declaredTools == null + ? defaultStageTools + : _lines(declaredTools); + final prompt = (blocks['prompt'] ?? _text(stage['prompt'])).trim(); + return StageSummary( + key: key, + kind: kind, + typeLabel: stageKindLabel(kind, type), + meta: _meta(kind, configs), + tools: tools, + toolsDefault: kind == StageKind.model && declaredTools == null, + permissions: _permissions(blocks['permissions']), + skills: _lines(blocks['skills'] ?? ''), + prompt: + (kind == StageKind.model || + kind == StageKind.human || + kind == StageKind.other) && + prompt.isNotEmpty + ? prompt + : null, + commands: kind == StageKind.check || kind == StageKind.deliveryGate + ? checkCommands(stage) + : const [], + gate: kind == StageKind.findings + ? [ + 'min severity ${configs['severity'] ?? 'important'}', + 'origin ${configs['origin'] ?? 'introduced'}', + ] + : const [], + limits: _limits(stage['limits']), + routes: [ + for (final edge in graphEdges({ + 'stages': [stage], + })) + (outcome: edge.label, target: nodeDisplayLabel(edge.target)), + ], + ); +} + +/// The type chip's word for [kind]; an unknown type keeps its own name. +String stageKindLabel(StageKind kind, [String type = '']) => switch (kind) { + StageKind.model => 'Model', + StageKind.check => 'Check', + StageKind.deliveryGate => 'Delivery gate', + StageKind.findings => 'Findings gate', + StageKind.human => 'Human', + StageKind.terminal => 'End', + StageKind.other => + type.isEmpty ? 'Stage' : '${type[0].toUpperCase()}${type.substring(1)}', +}; + +/// A model id without its vendor prefix and date stamp: +/// `anthropic/claude-sonnet-4-5-20250929` reads `claude-sonnet-4-5`. +String shortModelName(String model) { + var name = model.trim(); + final slash = name.lastIndexOf('/'); + if (slash >= 0) name = name.substring(slash + 1); + return name.replaceFirst(RegExp(r'-\d{8}$'), ''); +} + +List _meta(StageKind kind, Map configs) { + String? config(String key) { + final value = configs[key]?.trim(); + return value == null || value.isEmpty ? null : value; + } + + final harness = config('harness'); + final provider = config('provider'); + final model = config('model'); + final effort = config('reasoning_effort'); + final timeout = config('timeout') ?? config('command_timeout'); + final retries = config('retries'); + final budget = config('budget_usd'); + final tokens = config('budget_tokens'); + return [ + ?harness, + if (model != null) + shortModelName(model) + else if (provider != null && harness == null) + provider, + if (effort != null) '$effort effort', + if (timeout != null) '$timeout timeout', + if (retries != null) retries == '1' ? '1 retry' : '$retries retries', + if (budget != null) '\$$budget budget', + if (tokens != null) '$tokens tokens max', + if (config('keep_going') == 'true') 'keep going', + ]; +} + +List _permissions(String? text) { + if (text == null || text.trim().isEmpty) return const []; + try { + final decoded = jsonDecode(text); + if (decoded is! Map) return [text.trim()]; + return [ + for (final entry in decoded.entries) + '${entry.key}: ${entry.value is List && (entry.value as List).isEmpty + ? 'denied' + : entry.value is List + ? (entry.value as List).join(', ') + : _text(entry.value)}', + ]; + } on FormatException { + return [text.trim()]; + } +} + +List _limits(dynamic limits) { + if (limits is! Map) return const []; + final maxVisits = int.tryParse(_text(limits['max_visits'])); + final on = limits['on']; + final exhausted = _text(limits['on_exhausted']).trim(); + return [ + if (maxVisits != null && maxVisits > 0) + maxVisits == 1 ? 'max 1 visit' : 'max $maxVisits visits', + if (on is List && on.isNotEmpty) 'on ${on.map(_text).join(', ')}', + if (exhausted.isNotEmpty) 'when exhausted: $exhausted', + ]; +} + +Map _strings(dynamic value) => value is Map + ? {for (final entry in value.entries) _text(entry.key): _text(entry.value)} + : const {}; + +List _lines(String text) => [ + for (final line in text.split('\n')) + if (line.trim().isNotEmpty) line.trim(), +]; + +String _text(dynamic value) { + if (value == null) return ''; + if (value is num && value == value.roundToDouble()) { + return value.toInt().toString(); + } + return '$value'; +} diff --git a/app/lib/features/graph/painting/run_graph_edge_layer.dart b/app/lib/features/graph/painting/run_graph_edge_layer.dart new file mode 100644 index 00000000..5fe6c2f0 --- /dev/null +++ b/app/lib/features/graph/painting/run_graph_edge_layer.dart @@ -0,0 +1,145 @@ +import 'package:flutter/foundation.dart' show listEquals; +import 'package:flutter/material.dart'; + +import '../routing/route_models.dart'; +import 'graph_edge_layer.dart'; + +/// The run graph's route painting: the landed `GraphEdgePainter` geometry +/// (paths and arrowheads) with the two route classes run evidence needs on one +/// passive layer. No route is re-routed and no style is assumed here. + +/// A passive canvas that draws taken routes as solid, arrowed strokes and +/// untaken routes as dashed, arrowless strokes behind them. +/// +/// The caller supplies the already-routed [executedRoutes] and +/// [untakenRoutes], the graph-space [canvasSize] and its native theme colours. +/// The layer never takes pointer input, so nodes and labels keep their gestures. +class RunGraphEdgeLayer extends StatelessWidget { + const RunGraphEdgeLayer({ + super.key, + required this.executedRoutes, + required this.untakenRoutes, + required this.canvasSize, + required this.executedColor, + required this.untakenColor, + required this.strokeWidth, + }); + + final List executedRoutes; + final List untakenRoutes; + final Size canvasSize; + final Color executedColor; + final Color untakenColor; + final double strokeWidth; + + @override + Widget build(BuildContext context) => CustomPaint( + size: canvasSize, + painter: RunGraphEdgePainter( + executedRoutes: executedRoutes, + untakenRoutes: untakenRoutes, + executedColor: executedColor, + untakenColor: untakenColor, + strokeWidth: strokeWidth, + ), + ); +} + +/// Paints a [RunGraphEdgeLayer]. +/// +/// Executed routes reuse the landed [GraphEdgePainter] path and arrow geometry; +/// untaken routes are the same polyline broken into native-sized dashes and +/// never receive an arrowhead. Public so the compositor and its tests share one +/// decision about which class of route gets an arrow. +class RunGraphEdgePainter extends CustomPainter { + RunGraphEdgePainter({ + required this.executedRoutes, + required this.untakenRoutes, + required this.executedColor, + required this.untakenColor, + required this.strokeWidth, + }) : assert(strokeWidth > 0), + _executed = GraphEdgePainter( + routes: executedRoutes, + color: executedColor, + strokeWidth: strokeWidth, + ), + _executedLine = Paint() + ..color = executedColor + ..strokeWidth = strokeWidth + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round, + _untakenLine = Paint() + ..color = untakenColor + ..strokeWidth = strokeWidth + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round, + _arrow = Paint() + ..color = executedColor + ..style = PaintingStyle.fill; + + final List executedRoutes; + final List untakenRoutes; + final Color executedColor; + final Color untakenColor; + final double strokeWidth; + + final GraphEdgePainter _executed; + final Paint _executedLine; + final Paint _untakenLine; + final Paint _arrow; + + /// Dash and gap lengths in graph space; a dash never becomes a route style. + static const double dashLength = 12; + static const double dashGap = 8; + + @override + void paint(Canvas canvas, Size size) { + if (executedRoutes.isEmpty && untakenRoutes.isEmpty) return; + canvas.save(); + canvas.clipRect(Offset.zero & size); + for (final route in untakenRoutes) { + if (route.points.length < 2) continue; + canvas.drawPath(dashedPath(route), _untakenLine); + } + for (final route in executedRoutes) { + if (route.points.length < 2) continue; + canvas.drawPath(_executed.linePath(route), _executedLine); + } + for (final route in executedRoutes) { + if (route.points.length < 2) continue; + canvas.drawPath(_executed.arrowPath(route), _arrow); + } + canvas.restore(); + } + + /// The route's polyline split into [dashLength] segments separated by + /// [dashGap], following every orthogonal bend without smoothing. + Path dashedPath(EdgeRoute route) { + final source = _executed.linePath(route); + final dashed = Path(); + for (final metric in source.computeMetrics()) { + var start = 0.0; + while (start < metric.length) { + final end = start + dashLength < metric.length + ? start + dashLength + : metric.length; + dashed.addPath(metric.extractPath(start, end), Offset.zero); + start = end + dashGap; + } + } + return dashed; + } + + /// Passive like the landed edge layer: every point misses. + @override + bool hitTest(Offset position) => false; + + @override + bool shouldRepaint(RunGraphEdgePainter oldDelegate) => + oldDelegate.executedColor != executedColor || + oldDelegate.untakenColor != untakenColor || + oldDelegate.strokeWidth != strokeWidth || + !listEquals(oldDelegate.executedRoutes, executedRoutes) || + !listEquals(oldDelegate.untakenRoutes, untakenRoutes); +} diff --git a/app/lib/features/graph/painting/stage_edges_highlight.dart b/app/lib/features/graph/painting/stage_edges_highlight.dart new file mode 100644 index 00000000..8265e182 --- /dev/null +++ b/app/lib/features/graph/painting/stage_edges_highlight.dart @@ -0,0 +1,89 @@ +import 'package:flutter/material.dart'; + +import '../routing/route_models.dart'; +import 'graph_edge_layer.dart'; + +/// Softly emphasises every route into or out of one stage (the stage whose +/// popover is open): a translucent wider stroke under the plain edges' own +/// lines. Quieter than a hovered edge, which still paints above it. +class StageEdgesHighlightPainter extends CustomPainter { + StageEdgesHighlightPainter({ + required this.routes, + required this.color, + required this.strokeWidth, + }); + + final List routes; + final Color color; + final double strokeWidth; + + @override + void paint(Canvas canvas, Size size) { + if (routes.isEmpty) return; + final geometry = GraphEdgePainter( + routes: routes, + color: color, + strokeWidth: strokeWidth, + ); + final halo = Paint() + ..color = color.withValues(alpha: 0.16) + ..strokeWidth = strokeWidth * 5 + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round + ..strokeCap = StrokeCap.round; + final line = Paint() + ..color = color.withValues(alpha: 0.7) + ..strokeWidth = strokeWidth * 1.5 + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round; + for (final route in routes) { + if (route.points.length < 2) continue; + final path = geometry.linePath(route); + canvas.drawPath(path, halo); + canvas.drawPath(path, line); + } + } + + @override + bool hitTest(Offset position) => false; + + @override + bool shouldRepaint(StageEdgesHighlightPainter oldDelegate) => + oldDelegate.color != color || + oldDelegate.strokeWidth != strokeWidth || + oldDelegate.routes.length != routes.length || + !_same(oldDelegate.routes, routes); + + static bool _same(List a, List b) { + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; + } +} + +/// The soft highlight for [stage]'s routes, or nothing when none is open. +Widget graphStageEdgesHighlight({ + required BuildContext context, + required GraphRouting routing, + required String? stage, + required double edgeWidth, +}) { + if (stage == null) return const SizedBox.shrink(); + final routes = [ + for (final route in routing.routes) + if (route.source == stage || route.target == stage) route, + ]; + if (routes.isEmpty) return const SizedBox.shrink(); + return IgnorePointer( + child: CustomPaint( + key: ValueKey('graph-stage-edges:$stage'), + size: Size(routing.width, routing.height), + painter: StageEdgesHighlightPainter( + routes: routes, + color: Theme.of(context).colorScheme.primary, + strokeWidth: edgeWidth, + ), + ), + ); +} diff --git a/app/lib/features/graph/viewport/graph_viewport.dart b/app/lib/features/graph/viewport/graph_viewport.dart index 7465462f..d5776b11 100644 --- a/app/lib/features/graph/viewport/graph_viewport.dart +++ b/app/lib/features/graph/viewport/graph_viewport.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../ui/adaptive/glass_pill.dart'; import 'graph_viewport_controller.dart'; +import 'graph_viewport_scope.dart'; /// The fit control's web wording (`Fit graph to view`). const String graphFitLabel = 'Fit graph to view'; @@ -46,6 +47,7 @@ class GraphViewport extends StatefulWidget { } class _GraphViewportState extends State { + final GlobalKey _viewportKey = GlobalKey(debugLabel: 'graph-viewport-box'); Size? _scheduledViewport; Size? _scheduledContent; @@ -97,20 +99,26 @@ class _GraphViewportState extends State { fit: StackFit.expand, children: [ Positioned.fill( - child: InteractiveViewer( - key: const Key('graph-viewport'), - transformationController: widget.controller.transformation, - constrained: false, - // The graph owns its own bounds (fit and the visible-pan clamp), - // so the viewer must not impose a second, cover-the-viewport - // boundary that would fight the fit scale. - boundaryMargin: const EdgeInsets.all(double.infinity), - minScale: widget.controller.minScale, - maxScale: widget.controller.maxScale, - clipBehavior: Clip.hardEdge, - child: SizedBox.fromSize( - size: widget.contentSize, - child: widget.child, + key: _viewportKey, + child: GraphViewportScope( + transform: widget.controller.transformation, + viewportKey: _viewportKey, + viewportSize: viewport, + child: InteractiveViewer( + key: const Key('graph-viewport'), + transformationController: widget.controller.transformation, + constrained: false, + // The graph owns its own bounds (fit and the visible-pan clamp), + // so the viewer must not impose a second, cover-the-viewport + // boundary that would fight the fit scale. + boundaryMargin: const EdgeInsets.all(double.infinity), + minScale: widget.controller.minScale, + maxScale: widget.controller.maxScale, + clipBehavior: Clip.hardEdge, + child: SizedBox.fromSize( + size: widget.contentSize, + child: widget.child, + ), ), ), ), diff --git a/app/lib/features/graph/viewport/graph_viewport_scope.dart b/app/lib/features/graph/viewport/graph_viewport_scope.dart new file mode 100644 index 00000000..40300383 --- /dev/null +++ b/app/lib/features/graph/viewport/graph_viewport_scope.dart @@ -0,0 +1,34 @@ +import 'package:flutter/widgets.dart'; + +/// What a graph canvas can learn about the pan/zoom viewport around it: the +/// transform it follows and the visible box it must stay inside. +/// +/// [GraphViewport] provides it; a canvas drawn without one (a still preview, +/// a test) has no scope and uses its overlay's bounds instead. +class GraphViewportScope extends InheritedWidget { + const GraphViewportScope({ + super.key, + required this.transform, + required this.viewportKey, + required this.viewportSize, + required super.child, + }); + + /// Notifies on every pan, zoom and fit. + final Listenable transform; + + /// The key of the visible viewport box, for its on-screen origin. + final GlobalKey viewportKey; + + /// The visible viewport's extent. + final Size viewportSize; + + static GraphViewportScope? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType(); + + @override + bool updateShouldNotify(GraphViewportScope oldWidget) => + oldWidget.transform != transform || + oldWidget.viewportKey != viewportKey || + oldWidget.viewportSize != viewportSize; +} diff --git a/app/lib/features/graph/widgets/definition_graph_canvas.dart b/app/lib/features/graph/widgets/definition_graph_canvas.dart index e346b6c8..4592ec4b 100644 --- a/app/lib/features/graph/widgets/definition_graph_canvas.dart +++ b/app/lib/features/graph/widgets/definition_graph_canvas.dart @@ -1,21 +1,28 @@ import 'package:flutter/material.dart'; +import '../../../core/api_gateway.dart'; import '../domain/graph_definition.dart'; +import '../domain/stage_summary.dart'; import '../layout/layout_models.dart'; import '../painting/graph_edge_layer.dart'; +import '../painting/stage_edges_highlight.dart'; import '../routing/route_models.dart'; import 'graph_canvas_style.dart'; import 'graph_edge_hover.dart'; import 'graph_stage_node.dart'; +import 'graph_stage_popover.dart'; +import 'stage_popover_card.dart'; /// The measured definition canvas at any viewport size and selection. /// /// Used by both the inline [GraphViewport] and the expanded presentation: the -/// passive edge layer paints behind the native nodes and outcome labels, and -/// every node reports selection through [onSelected]. +/// passive edge layer paints behind the native nodes and outcome labels. +/// Tapping a node opens its stage popover (the declaration at a glance); the +/// popover's "Open definition" reports the node through [onSelected]. class DefinitionGraphCanvas extends StatelessWidget { const DefinitionGraphCanvas({ super.key, + required this.graph, required this.nodes, required this.layout, required this.routing, @@ -24,6 +31,8 @@ class DefinitionGraphCanvas extends StatelessWidget { required this.onSelected, }); + /// The definition the nodes came from, for each stage's declaration. + final JsonMap graph; final List nodes; final GraphLayout layout; final GraphRouting routing; @@ -37,12 +46,34 @@ class DefinitionGraphCanvas extends StatelessWidget { for (final node in nodes) node.key: node, }; final size = Size(routing.width, routing.height); - return GraphEdgeHover( - layout: layout, - routing: routing, - describe: describeGraphEdge, - builder: (context, highlighted, select) => - _canvas(context, nodesByKey, size, highlighted, select), + return GraphStagePopover( + nodeRects: { + for (final box in layout.nodes) + box.key: Rect.fromLTWH(box.x, box.y, box.width, box.height), + }, + cardBuilder: (context, stage, close) => StagePopoverCard( + label: nodesByKey[stage]?.label ?? stage, + summary: stageSummaryFor(graph, stage), + onClose: close, + onOpenDefinition: () { + close(); + onSelected(stage); + }, + ), + builder: (context, open, toggle) => GraphEdgeHover( + layout: layout, + routing: routing, + describe: describeGraphEdge, + builder: (context, highlighted, select) => _canvas( + context, + nodesByKey, + size, + highlighted, + select, + open, + toggle, + ), + ), ); } @@ -52,6 +83,8 @@ class DefinitionGraphCanvas extends StatelessWidget { Size size, int? highlighted, ValueChanged select, + String? open, + ValueChanged toggle, ) { return Stack( clipBehavior: Clip.none, @@ -66,6 +99,14 @@ class DefinitionGraphCanvas extends StatelessWidget { strokeWidth: style.edgeWidth, ), ), + Positioned.fill( + child: graphStageEdgesHighlight( + context: context, + routing: routing, + stage: open, + edgeWidth: style.edgeWidth, + ), + ), Positioned.fill( child: graphEdgeHighlight( context: context, @@ -83,8 +124,8 @@ class DefinitionGraphCanvas extends StatelessWidget { height: box.height, child: GraphStageNode( node: nodesByKey[box.key]!, - selected: box.key == selectedStage, - onSelected: onSelected, + selected: box.key == selectedStage || box.key == open, + onSelected: toggle, ), ), for (final label in routing.labels) diff --git a/app/lib/features/graph/widgets/definition_graph_view.dart b/app/lib/features/graph/widgets/definition_graph_view.dart index 7eed93ee..587c6c4c 100644 --- a/app/lib/features/graph/widgets/definition_graph_view.dart +++ b/app/lib/features/graph/widgets/definition_graph_view.dart @@ -107,6 +107,7 @@ class _DefinitionGraphViewState extends State { edges: edges, extents: extents, labelExtents: labelExtents, + metrics: graphMetricsOf(context), ); return (layout, routing); } @@ -175,6 +176,7 @@ class _DefinitionGraphViewState extends State { contentSize: size, onExpand: () => _openExpanded(nodes, layout, routing, size), child: DefinitionGraphCanvas( + graph: widget.graph, nodes: nodes, layout: layout, routing: routing, @@ -215,6 +217,7 @@ class _DefinitionGraphViewState extends State { selectedStage: widget.selectedStage, onSelected: widget.onSelected, canvasBuilder: (context, selected, onSelected) => DefinitionGraphCanvas( + graph: widget.graph, nodes: nodes, layout: layout, routing: routing, diff --git a/app/lib/features/graph/widgets/graph_canvas_style.dart b/app/lib/features/graph/widgets/graph_canvas_style.dart index 03347dce..ace7b433 100644 --- a/app/lib/features/graph/widgets/graph_canvas_style.dart +++ b/app/lib/features/graph/widgets/graph_canvas_style.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; +import '../../../ui/theme/app_design_tokens.dart'; import '../layout/layout_models.dart'; +import '../layout/linear_graph_layout.dart'; import '../routing/route_models.dart'; /// Centralized graph spacing, not component dimensions. Rank separation follows @@ -27,6 +29,25 @@ RoutingConfig graphCanvasRoutingConfig() => RoutingConfig( boundsPadding: 12, ); +/// The drawing's spacings under the design at [context]: the web's metrics, +/// or a dense design's tighter gaps, lanes and padding (Compact), so its +/// smaller nodes are not left adrift in a comfortable layout. +LinearGraphMetrics graphMetricsOf(BuildContext context) => + AppDesignTokens.of(context).density.dense + ? _denseGraphMetrics + : const LinearGraphMetrics(); + +const LinearGraphMetrics _denseGraphMetrics = LinearGraphMetrics( + hGap: 32, + pad: 16, + laneSpacing: 20, + terminalGap: 16, + trackStep: 16, + portSpacing: 8, + labelPadding: 6, + labelGap: 2, +); + /// The native theme roles one definition graph canvas needs. /// /// No palette, font family or size is defined here: every value comes from the diff --git a/app/lib/features/graph/widgets/graph_stage_node.dart b/app/lib/features/graph/widgets/graph_stage_node.dart index e33ecc11..ee446ef0 100644 --- a/app/lib/features/graph/widgets/graph_stage_node.dart +++ b/app/lib/features/graph/widgets/graph_stage_node.dart @@ -1,6 +1,9 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import '../../../ui/status/run_status_icon.dart'; +import '../../../ui/theme/app_design_tokens.dart'; import '../domain/graph_definition.dart'; /// One content-sized stage node as an ordinary native control. @@ -56,7 +59,7 @@ class GraphStageNode extends StatelessWidget { button: true, selected: selected, label: _label, - child: _materialCard(onPressed, content), + child: _materialCard(context, onPressed, content), ), ); return active ? StageActivityHalo(child: control) : control; @@ -66,13 +69,29 @@ class GraphStageNode extends StatelessWidget { /// which assumes one line and cuts into a wrapped label's first and last /// line. A card keeps the rounded-rectangle surface the web node uses, and /// [selected] only chooses between two stock emphasis levels. - Widget _materialCard(VoidCallback onPressed, Widget content) { + Widget _materialCard( + BuildContext context, + VoidCallback onPressed, + Widget content, + ) { + // A dense design draws a smaller node: half the inset and a 32px + // least height on a pointer device (40px on touch). + final density = AppDesignTokens.of(context).density; final body = InkWell( onTap: onPressed, child: ConstrainedBox( - constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + constraints: BoxConstraints( + minHeight: density.dense + ? math.max(32, density.minTouchRow) + : kMinInteractiveDimension, + ), child: Padding( - padding: _contentPadding, + padding: density.dense + ? EdgeInsets.symmetric( + horizontal: density.space(_contentPadding.left) + 4, + vertical: density.space(_contentPadding.top), + ) + : _contentPadding, child: Align( // A terminal box widens to give each incoming route its own port; // its label stays centred in it. diff --git a/app/lib/features/graph/widgets/graph_stage_popover.dart b/app/lib/features/graph/widgets/graph_stage_popover.dart new file mode 100644 index 00000000..57713dd9 --- /dev/null +++ b/app/lib/features/graph/widgets/graph_stage_popover.dart @@ -0,0 +1,271 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../ui/theme/app_design_tokens.dart'; +import '../viewport/graph_viewport_scope.dart'; +import 'stage_popover_position.dart'; + +/// Builds the canvas with [openStage] (or null) and the node tap handler. +typedef GraphStagePopoverCanvasBuilder = + Widget Function( + BuildContext context, + String? openStage, + ValueChanged toggle, + ); + +/// Builds one stage's popover content; [close] dismisses it. +typedef GraphStagePopoverCardBuilder = + Widget Function(BuildContext context, String stage, VoidCallback close); + +/// Below this viewport width (or height) the card cannot sit beside a node +/// with room to read, so the stage opens in a bottom sheet instead. +const double graphStagePopoverMinWidth = 440; +const double graphStagePopoverMinHeight = 300; + +/// A stage popover over a graph canvas: tapping (or pressing Enter on) a node +/// opens a small card anchored to it, with a nub pointing at the node. +/// +/// The card is built only while open, in the overlay, and lays out against +/// the live pan/zoom transform so it follows its node; it stays inside the +/// viewport. A tap outside it (a tap, not a pan: a drag still pans the graph +/// under it), Escape, or tapping the same node again closes it. On a narrow +/// or short viewport the same content opens in a bottom sheet instead. +class GraphStagePopover extends StatefulWidget { + const GraphStagePopover({ + super.key, + required this.nodeRects, + required this.cardBuilder, + required this.builder, + }); + + /// Every openable node's box in canvas (graph) space. + final Map nodeRects; + final GraphStagePopoverCardBuilder cardBuilder; + final GraphStagePopoverCanvasBuilder builder; + + @override + State createState() => _GraphStagePopoverState(); +} + +class _GraphStagePopoverState extends State { + final OverlayPortalController _portal = OverlayPortalController(); + final GlobalKey _canvasKey = GlobalKey(debugLabel: 'graph-popover-canvas'); + final GlobalKey _cardKey = GlobalKey(debugLabel: 'graph-popover-card'); + final FocusNode _cardFocus = FocusNode(debugLabel: 'graph-stage-popover'); + FocusNode? _returnFocus; + String? _open; + bool _routed = false; + final Map _downs = {}; + + @override + void didUpdateWidget(GraphStagePopover oldWidget) { + super.didUpdateWidget(oldWidget); + final open = _open; + if (open != null && !widget.nodeRects.containsKey(open)) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) _close(); + }); + } + } + + @override + void dispose() { + _unroute(); + _cardFocus.dispose(); + super.dispose(); + } + + bool _useSheet() { + final scope = GraphViewportScope.maybeOf(context); + final size = scope?.viewportSize ?? MediaQuery.sizeOf(context); + return size.width < graphStagePopoverMinWidth || + size.height < graphStagePopoverMinHeight; + } + + void _toggle(String stage) { + if (_open == stage) { + _close(); + return; + } + if (!widget.nodeRects.containsKey(stage)) return; + if (Overlay.maybeOf(context) == null || _useSheet()) { + _openSheet(stage); + return; + } + _returnFocus ??= FocusManager.instance.primaryFocus; + setState(() => _open = stage); + _portal.show(); + _route(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _open != null) _cardFocus.requestFocus(); + }); + } + + void _close() { + if (_open == null) return; + final hadFocus = _cardFocus.hasFocus; + setState(() => _open = null); + _portal.hide(); + _unroute(); + final back = _returnFocus; + _returnFocus = null; + if (hadFocus && back != null && back.context != null) back.requestFocus(); + } + + Future _openSheet(String stage) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + showDragHandle: true, + useSafeArea: true, + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.85, + ), + builder: (sheet) => Padding( + key: const Key('graph-stage-sheet'), + padding: const EdgeInsets.only(bottom: 8), + child: widget.cardBuilder( + sheet, + stage, + // Synchronous, so an action that pops or pushes next (Open visit + // from a full-screen graph page) acts on the page under the sheet. + () => Navigator.of(sheet).pop(), + ), + ), + ); + } + + // A global route sees every pointer while the card is open: a tap (down and + // up within touch slop) outside the card and outside its own node closes + // it; a drag never does, so panning keeps the card on its node. + void _route() { + if (_routed) return; + GestureBinding.instance.pointerRouter.addGlobalRoute(_onPointer); + _routed = true; + } + + void _unroute() { + if (!_routed) return; + GestureBinding.instance.pointerRouter.removeGlobalRoute(_onPointer); + _routed = false; + _downs.clear(); + } + + void _onPointer(PointerEvent event) { + if (event is PointerDownEvent) { + _downs[event.pointer] = event.position; + } else if (event is PointerCancelEvent) { + _downs.remove(event.pointer); + } else if (event is PointerUpEvent) { + final down = _downs.remove(event.pointer); + if (down == null) return; + if ((event.position - down).distance > kTouchSlop) return; + if (_contains(_cardKey, event.position) || _onOpenNode(event.position)) { + return; + } + _close(); + } + } + + bool _contains(GlobalKey key, Offset global) { + final box = key.currentContext?.findRenderObject(); + if (box is! RenderBox || !box.attached || !box.hasSize) return false; + return (Offset.zero & box.size).contains(box.globalToLocal(global)); + } + + bool _onOpenNode(Offset global) { + final rect = widget.nodeRects[_open]; + final box = _canvasKey.currentContext?.findRenderObject(); + if (rect == null || box is! RenderBox || !box.attached) return false; + return rect.contains(box.globalToLocal(global)); + } + + RenderBox? _box(GlobalKey key) { + final box = key.currentContext?.findRenderObject(); + return box is RenderBox ? box : null; + } + + @override + Widget build(BuildContext context) { + final canvas = KeyedSubtree( + key: _canvasKey, + child: widget.builder(context, _open, _toggle), + ); + if (Overlay.maybeOf(context) == null) return canvas; + return OverlayPortal( + controller: _portal, + overlayChildBuilder: _overlay, + child: canvas, + ); + } + + Widget _overlay(BuildContext context) { + final stage = _open; + final rect = stage == null ? null : widget.nodeRects[stage]; + if (stage == null || rect == null) return const SizedBox.shrink(); + final scope = GraphViewportScope.maybeOf(context); + final surface = stagePopoverSurface(context); + return StagePopoverPosition( + key: const Key('graph-stage-popover'), + anchorBox: () => _box(_canvasKey), + anchorRect: rect, + boundsBox: () => scope == null ? null : _box(scope.viewportKey), + boundsSize: scope?.viewportSize, + safeArea: MediaQuery.paddingOf(this.context), + relayout: scope?.transform, + fill: surface.fill, + border: surface.border, + radius: surface.radius, + elevation: surface.elevation, + shadowColor: surface.shadow, + child: Focus( + focusNode: _cardFocus, + onKeyEvent: (node, event) { + if (event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.escape) { + _close(); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + }, + child: FocusTraversalGroup( + child: Material( + key: _cardKey, + color: surface.fill, + elevation: surface.elevation, + shadowColor: surface.shadow, + shape: RoundedRectangleBorder( + side: surface.border, + borderRadius: BorderRadius.circular(surface.radius), + ), + clipBehavior: Clip.antiAlias, + child: widget.cardBuilder(context, stage, _close), + ), + ), + ), + ); + } +} + +/// The popover's surface in the current design: Classic floats a raised card +/// with a hairline; a flat design (Terminal, Paper, Compact) draws its own +/// panel fill and frame with no shadow, at the design's corner radius. +({Color fill, BorderSide border, double radius, double elevation, Color shadow}) +stagePopoverSurface(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final tokens = AppDesignTokens.of(context); + final flat = tokens.flat; + return ( + fill: flat + ? tokens.panelFill(colors, colors.surfaceContainer) + : colors.surfaceContainerHigh, + border: + tokens.frameSide ?? + BorderSide(color: colors.outlineVariant.withValues(alpha: 0.7)), + radius: tokens.radius ?? 14, + elevation: flat ? 0 : (theme.popupMenuTheme.elevation ?? 3).toDouble() + 3, + shadow: theme.popupMenuTheme.shadowColor ?? colors.shadow, + ); +} diff --git a/app/lib/features/graph/widgets/run_graph_canvas.dart b/app/lib/features/graph/widgets/run_graph_canvas.dart index d47a7206..f6e059e0 100644 --- a/app/lib/features/graph/widgets/run_graph_canvas.dart +++ b/app/lib/features/graph/widgets/run_graph_canvas.dart @@ -1,158 +1,22 @@ -import 'package:flutter/foundation.dart' show listEquals; import 'package:flutter/material.dart'; +import '../../../core/api_gateway.dart'; import '../domain/graph_definition.dart'; import '../domain/run_graph_state.dart'; +import '../domain/stage_run_facts.dart'; +import '../domain/stage_summary.dart'; import '../layout/layout_models.dart'; -import '../painting/graph_edge_layer.dart'; +import '../painting/run_graph_edge_layer.dart'; +import '../painting/stage_edges_highlight.dart'; import '../routing/route_models.dart'; import 'graph_canvas_style.dart'; import 'graph_edge_hover.dart'; -import 'graph_stage_node.dart'; -import 'measured_child.dart'; +import 'graph_stage_popover.dart'; +import 'run_graph_parts.dart'; +import 'stage_popover_card.dart'; -/// The run graph's canvas primitives: split route painting and measurement of -/// the exact status-bearing nodes the run renderer places. -/// -/// This keeps the landed `GraphEdgePainter` geometry (paths and arrowheads) and -/// adds only what run evidence needs: two route classes on one passive layer. -/// No node is invented, no route is re-routed and no style is assumed here. - -/// A passive canvas that draws taken routes as solid, arrowed strokes and -/// untaken routes as dashed, arrowless strokes behind them. -/// -/// The caller supplies the already-routed [executedRoutes] and -/// [untakenRoutes], the graph-space [canvasSize] and its native theme colours. -/// The layer never takes pointer input, so nodes and labels keep their gestures. -class RunGraphEdgeLayer extends StatelessWidget { - const RunGraphEdgeLayer({ - super.key, - required this.executedRoutes, - required this.untakenRoutes, - required this.canvasSize, - required this.executedColor, - required this.untakenColor, - required this.strokeWidth, - }); - - final List executedRoutes; - final List untakenRoutes; - final Size canvasSize; - final Color executedColor; - final Color untakenColor; - final double strokeWidth; - - @override - Widget build(BuildContext context) => CustomPaint( - size: canvasSize, - painter: RunGraphEdgePainter( - executedRoutes: executedRoutes, - untakenRoutes: untakenRoutes, - executedColor: executedColor, - untakenColor: untakenColor, - strokeWidth: strokeWidth, - ), - ); -} - -/// Paints a [RunGraphEdgeLayer]. -/// -/// Executed routes reuse the landed [GraphEdgePainter] path and arrow geometry; -/// untaken routes are the same polyline broken into native-sized dashes and -/// never receive an arrowhead. Public so the compositor and its tests share one -/// decision about which class of route gets an arrow. -class RunGraphEdgePainter extends CustomPainter { - RunGraphEdgePainter({ - required this.executedRoutes, - required this.untakenRoutes, - required this.executedColor, - required this.untakenColor, - required this.strokeWidth, - }) : assert(strokeWidth > 0), - _executed = GraphEdgePainter( - routes: executedRoutes, - color: executedColor, - strokeWidth: strokeWidth, - ), - _executedLine = Paint() - ..color = executedColor - ..strokeWidth = strokeWidth - ..style = PaintingStyle.stroke - ..strokeJoin = StrokeJoin.round, - _untakenLine = Paint() - ..color = untakenColor - ..strokeWidth = strokeWidth - ..style = PaintingStyle.stroke - ..strokeJoin = StrokeJoin.round, - _arrow = Paint() - ..color = executedColor - ..style = PaintingStyle.fill; - - final List executedRoutes; - final List untakenRoutes; - final Color executedColor; - final Color untakenColor; - final double strokeWidth; - - final GraphEdgePainter _executed; - final Paint _executedLine; - final Paint _untakenLine; - final Paint _arrow; - - /// Dash and gap lengths in graph space; a dash never becomes a route style. - static const double dashLength = 12; - static const double dashGap = 8; - - @override - void paint(Canvas canvas, Size size) { - if (executedRoutes.isEmpty && untakenRoutes.isEmpty) return; - canvas.save(); - canvas.clipRect(Offset.zero & size); - for (final route in untakenRoutes) { - if (route.points.length < 2) continue; - canvas.drawPath(dashedPath(route), _untakenLine); - } - for (final route in executedRoutes) { - if (route.points.length < 2) continue; - canvas.drawPath(_executed.linePath(route), _executedLine); - } - for (final route in executedRoutes) { - if (route.points.length < 2) continue; - canvas.drawPath(_executed.arrowPath(route), _arrow); - } - canvas.restore(); - } - - /// The route's polyline split into [dashLength] segments separated by - /// [dashGap], following every orthogonal bend without smoothing. - Path dashedPath(EdgeRoute route) { - final source = _executed.linePath(route); - final dashed = Path(); - for (final metric in source.computeMetrics()) { - var start = 0.0; - while (start < metric.length) { - final end = start + dashLength < metric.length - ? start + dashLength - : metric.length; - dashed.addPath(metric.extractPath(start, end), Offset.zero); - start = end + dashGap; - } - } - return dashed; - } - - /// Passive like the landed edge layer: every point misses. - @override - bool hitTest(Offset position) => false; - - @override - bool shouldRepaint(RunGraphEdgePainter oldDelegate) => - oldDelegate.executedColor != executedColor || - oldDelegate.untakenColor != untakenColor || - oldDelegate.strokeWidth != strokeWidth || - !listEquals(oldDelegate.executedRoutes, executedRoutes) || - !listEquals(oldDelegate.untakenRoutes, untakenRoutes); -} +export '../painting/run_graph_edge_layer.dart'; +export 'run_graph_parts.dart'; /// The run canvas: split route classes behind status-bearing native nodes, with /// outcome labels only for routes the run actually took. @@ -160,9 +24,16 @@ class RunGraphEdgePainter extends CustomPainter { /// [layout] and [routing] are the caller's measured geometry. The canvas never /// changes them and never assumes a node size; the caller supplies the pan/zoom /// viewport around this content. +/// +/// Tapping a stage opens its popover: the declaration with what the run +/// recorded for it. "Open visit" reports a visited stage through +/// [onStageSelected]; "Open definition" reports it through [onOpenDefinition]. class RunGraphCanvas extends StatelessWidget { const RunGraphCanvas({ super.key, + required this.graph, + required this.run, + required this.onOpenDefinition, required this.nodes, required this.layout, required this.routing, @@ -173,6 +44,10 @@ class RunGraphCanvas extends StatelessWidget { this.selectedStage, }); + /// The run's pinned definition and the run detail, for the popover. + final JsonMap graph; + final JsonMap run; + final ValueChanged onOpenDefinition; final List nodes; final GraphLayout layout; final GraphRouting routing; @@ -204,6 +79,63 @@ class RunGraphCanvas extends StatelessWidget { route, taken: state.routeOrder(route.source, route.outcome, route.target).length, ); + return GraphStagePopover( + nodeRects: { + for (final box in layout.nodes) + if (!(nodesByKey[box.key]?.terminal ?? true)) + box.key: Rect.fromLTWH(box.x, box.y, box.width, box.height), + }, + cardBuilder: (context, stage, close) => + _card(nodesByKey[stage]?.label ?? stage, stage, close), + builder: (context, open, toggle) => _hover( + context, + nodesByKey, + executed, + untaken, + executedIds, + size, + activeStage, + executedColor, + describe, + open, + toggle, + ), + ); + } + + Widget _card(String label, String stage, VoidCallback close) { + final visited = state.isStageVisited(stage); + return StagePopoverCard( + label: label, + summary: stageSummaryFor(graph, stage), + facts: stageRunFacts(run, stage), + onClose: close, + onOpenDefinition: () { + close(); + onOpenDefinition(stage); + }, + onOpenVisit: !visited + ? null + : () { + close(); + onStageSelected(stage); + }, + ); + } + + Widget _hover( + BuildContext context, + Map nodesByKey, + List executed, + List untaken, + Set executedIds, + Size size, + String? activeStage, + Color executedColor, + String Function(EdgeRoute) describe, + String? open, + ValueChanged toggle, + ) { return GraphEdgeHover( layout: layout, routing: routing, @@ -221,6 +153,14 @@ class RunGraphCanvas extends StatelessWidget { strokeWidth: style.edgeWidth, ), ), + Positioned.fill( + child: graphStageEdgesHighlight( + context: context, + routing: routing, + stage: open, + edgeWidth: style.edgeWidth, + ), + ), Positioned.fill( child: graphEdgeHighlight( context: context, @@ -239,6 +179,8 @@ class RunGraphCanvas extends StatelessWidget { highlighted, select, describe, + open, + toggle, ), ], ), @@ -254,6 +196,8 @@ class RunGraphCanvas extends StatelessWidget { int? highlighted, ValueChanged select, String Function(EdgeRoute) describe, + String? open, + ValueChanged toggle, ) { return [ for (final box in layout.nodes) @@ -265,11 +209,10 @@ class RunGraphCanvas extends StatelessWidget { child: RunGraphNode( node: nodesByKey[box.key]!, recordedStatus: recordedStatuses[box.key], - selected: box.key == selectedStage, + selected: box.key == selectedStage || box.key == open, active: box.key == activeStage, - opensVisit: - !nodesByKey[box.key]!.terminal && state.isStageVisited(box.key), - onSelected: onStageSelected, + interactive: !nodesByKey[box.key]!.terminal, + onSelected: toggle, ), ), // A run labels only the routes that actually happened, and the route @@ -312,184 +255,3 @@ class RunGraphCanvas extends StatelessWidget { color: color, ); } - -/// A taken route's label led by its place in the run (`2`, or `2, 5` for a -/// loop), so the path reads in order. -/// -/// The canvas places this widget and [RunGraphMeasurements] measures the same -/// one, so the routed label box covers the order badge as well as the text. -class RunRouteLabel extends StatelessWidget { - const RunRouteLabel({ - super.key, - required this.edgeId, - required this.label, - required this.order, - required this.style, - required this.color, - }); - - final int edgeId; - final String label; - final List order; - final TextStyle style; - final Color color; - - @override - Widget build(BuildContext context) { - final text = Text(label, style: style); - if (order.isEmpty) return text; - return Row( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - key: ValueKey('run-route-order:$edgeId'), - padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), - decoration: BoxDecoration( - color: color, - borderRadius: BorderRadius.circular(8), - ), - child: Text( - order.join(', '), - style: const TextStyle( - color: Color(0xFFFFFFFF), - fontSize: 10, - fontWeight: FontWeight.w700, - ), - ), - ), - const SizedBox(width: 4), - text, - ], - ); - } -} - -/// One placed run node. A visited stage is the native control with its recorded -/// status; an unvisited node and a terminal are labels with no tap target or -/// button semantics, because neither owns a recorded visit to open. [active] -/// marks the run's recorded current stage while it executes; it only adds the -/// live halo, never a visit or a control. -class RunGraphNode extends StatelessWidget { - const RunGraphNode({ - super.key, - required this.node, - required this.recordedStatus, - required this.opensVisit, - required this.onSelected, - this.selected = false, - this.active = false, - }); - - final GraphNode node; - final String? recordedStatus; - final bool opensVisit; - final bool selected; - final bool active; - final ValueChanged onSelected; - - @override - Widget build(BuildContext context) { - final status = recordedStatus; - if (opensVisit) { - return GraphStageNode( - node: node, - recordedStatus: status, - selected: selected, - active: active, - onSelected: onSelected, - ); - } - return Semantics( - container: true, - label: graphNodeSemanticsLabel(node, status), - child: ExcludeSemantics( - child: IgnorePointer( - child: GraphStageNode( - node: node, - recordedStatus: status, - active: active, - onSelected: (_) {}, - ), - ), - ), - ); - } -} - -/// Measures the status-bearing run nodes and every route label offstage. -/// -/// A visited node is taller than the same node without its recorded status, so -/// the measurement must use the exact widget the canvas places. Sizes are -/// reported after layout and callers schedule the placement frame. -class RunGraphMeasurements extends StatelessWidget { - const RunGraphMeasurements({ - super.key, - required this.nodes, - required this.edges, - required this.maxNodeWidth, - required this.labelStyle, - required this.recordedStatuses, - required this.state, - required this.onNodeSize, - required this.onLabelSize, - }); - - final List nodes; - final List edges; - final double maxNodeWidth; - final TextStyle labelStyle; - final Map recordedStatuses; - - /// The run whose route order badges lead the taken labels. - final RunGraphState state; - final void Function(String, Size) onNodeSize; - - /// Receives each edge's label size keyed by its edge id, because two edges - /// with the same outcome can carry different order badges. - final void Function(int, Size) onLabelSize; - - @override - Widget build(BuildContext context) => Offstage( - child: OverflowBox( - alignment: Alignment.topLeft, - minWidth: 0, - maxWidth: double.infinity, - minHeight: 0, - maxHeight: double.infinity, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - for (final node in nodes) - MeasuredChild( - key: ValueKey( - 'run-node:${node.key}:${node.label}:' - '${recordedStatuses[node.key] ?? ''}', - ), - onSize: (size) => onNodeSize(node.key, size), - child: ConstrainedBox( - constraints: BoxConstraints(maxWidth: maxNodeWidth), - child: GraphStageNode( - node: node, - recordedStatus: recordedStatuses[node.key], - onSelected: (_) {}, - ), - ), - ), - for (final edge in edges) - MeasuredChild( - key: ValueKey('run-label:${edge.id}'), - onSize: (size) => onLabelSize(edge.id, size), - child: RunRouteLabel( - edgeId: edge.id, - label: edge.label, - order: state.routeOrder(edge.source, edge.outcome, edge.target), - style: labelStyle, - color: const Color(0x00000000), - ), - ), - ], - ), - ), - ); -} diff --git a/app/lib/features/graph/widgets/run_graph_parts.dart b/app/lib/features/graph/widgets/run_graph_parts.dart new file mode 100644 index 00000000..6a678172 --- /dev/null +++ b/app/lib/features/graph/widgets/run_graph_parts.dart @@ -0,0 +1,190 @@ +import 'package:flutter/material.dart'; + +import '../domain/graph_definition.dart'; +import '../domain/run_graph_state.dart'; +import 'graph_stage_node.dart'; +import 'measured_child.dart'; + +/// The run canvas's placed pieces: taken-route labels, run nodes and the +/// offstage measurement of exactly those widgets. + +/// A taken route's label led by its place in the run (`2`, or `2, 5` for a +/// loop), so the path reads in order. +/// +/// The canvas places this widget and [RunGraphMeasurements] measures the same +/// one, so the routed label box covers the order badge as well as the text. +class RunRouteLabel extends StatelessWidget { + const RunRouteLabel({ + super.key, + required this.edgeId, + required this.label, + required this.order, + required this.style, + required this.color, + }); + + final int edgeId; + final String label; + final List order; + final TextStyle style; + final Color color; + + @override + Widget build(BuildContext context) { + final text = Text(label, style: style); + if (order.isEmpty) return text; + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + key: ValueKey('run-route-order:$edgeId'), + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(8), + ), + child: Text( + order.join(', '), + style: const TextStyle( + color: Color(0xFFFFFFFF), + fontSize: 10, + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(width: 4), + text, + ], + ); + } +} + +/// One placed run node. A stage is the native control with its recorded status +/// (none when unvisited) and opens its popover; a terminal is a label with no +/// tap target or button semantics, because it has no declaration. [active] +/// marks the run's recorded current stage while it executes; it only adds the +/// live halo, never a visit or a control. +class RunGraphNode extends StatelessWidget { + const RunGraphNode({ + super.key, + required this.node, + required this.recordedStatus, + required this.interactive, + required this.onSelected, + this.selected = false, + this.active = false, + }); + + final GraphNode node; + final String? recordedStatus; + final bool interactive; + final bool selected; + final bool active; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + final status = recordedStatus; + if (interactive) { + return GraphStageNode( + node: node, + recordedStatus: status, + selected: selected, + active: active, + onSelected: onSelected, + ); + } + return Semantics( + container: true, + label: graphNodeSemanticsLabel(node, status), + child: ExcludeSemantics( + child: IgnorePointer( + child: GraphStageNode( + node: node, + recordedStatus: status, + active: active, + onSelected: (_) {}, + ), + ), + ), + ); + } +} + +/// Measures the status-bearing run nodes and every route label offstage. +/// +/// A visited node is taller than the same node without its recorded status, so +/// the measurement must use the exact widget the canvas places. Sizes are +/// reported after layout and callers schedule the placement frame. +class RunGraphMeasurements extends StatelessWidget { + const RunGraphMeasurements({ + super.key, + required this.nodes, + required this.edges, + required this.maxNodeWidth, + required this.labelStyle, + required this.recordedStatuses, + required this.state, + required this.onNodeSize, + required this.onLabelSize, + }); + + final List nodes; + final List edges; + final double maxNodeWidth; + final TextStyle labelStyle; + final Map recordedStatuses; + + /// The run whose route order badges lead the taken labels. + final RunGraphState state; + final void Function(String, Size) onNodeSize; + + /// Receives each edge's label size keyed by its edge id, because two edges + /// with the same outcome can carry different order badges. + final void Function(int, Size) onLabelSize; + + @override + Widget build(BuildContext context) => Offstage( + child: OverflowBox( + alignment: Alignment.topLeft, + minWidth: 0, + maxWidth: double.infinity, + minHeight: 0, + maxHeight: double.infinity, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final node in nodes) + MeasuredChild( + key: ValueKey( + 'run-node:${node.key}:${node.label}:' + '${recordedStatuses[node.key] ?? ''}', + ), + onSize: (size) => onNodeSize(node.key, size), + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxNodeWidth), + child: GraphStageNode( + node: node, + recordedStatus: recordedStatuses[node.key], + onSelected: (_) {}, + ), + ), + ), + for (final edge in edges) + MeasuredChild( + key: ValueKey('run-label:${edge.id}'), + onSize: (size) => onLabelSize(edge.id, size), + child: RunRouteLabel( + edgeId: edge.id, + label: edge.label, + order: state.routeOrder(edge.source, edge.outcome, edge.target), + style: labelStyle, + color: const Color(0x00000000), + ), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/graph/widgets/run_graph_view.dart b/app/lib/features/graph/widgets/run_graph_view.dart index c87c577b..2287aece 100644 --- a/app/lib/features/graph/widgets/run_graph_view.dart +++ b/app/lib/features/graph/widgets/run_graph_view.dart @@ -13,6 +13,7 @@ import '../viewport/graph_viewport_controller.dart'; import 'graph_canvas_style.dart'; import 'run_graph_canvas.dart'; import 'run_graph_header.dart'; +import 'stage_definition_view.dart'; export 'run_graph_header.dart' show runGraphExecuted, runGraphNotExecuted; @@ -140,6 +141,7 @@ class _RunGraphViewState extends State { edges: edges, extents: extents, labelExtents: labelExtents, + metrics: graphMetricsOf(context), ); return (layout, routing); } @@ -326,6 +328,9 @@ class _RunGraphViewState extends State { required String? selectedStage, required ValueChanged onStageSelected, }) => RunGraphCanvas( + graph: widget.graph ?? const {}, + run: widget.run, + onOpenDefinition: _openDefinition, nodes: nodes, layout: layout, routing: routing, @@ -336,6 +341,23 @@ class _RunGraphViewState extends State { onStageSelected: onStageSelected, ); + /// The full definition page for [stage], pinned to this run's version. + void _openDefinition(String stage) { + final graph = widget.graph; + if (graph == null) return; + final id = widget.run['pipeline_id']; + final version = widget.run['version']; + final name = '${widget.run['name'] ?? ''}'.trim(); + openStageDefinition( + context, + graph: graph, + stageKey: stage, + pipelineId: id is num ? id.toInt() : 0, + pipelineName: name, + version: version is num ? version.toInt() : 0, + ); + } + void _openExpanded( List nodes, GraphLayout layout, diff --git a/app/lib/features/graph/widgets/stage_popover_card.dart b/app/lib/features/graph/widgets/stage_popover_card.dart new file mode 100644 index 00000000..7a4526c2 --- /dev/null +++ b/app/lib/features/graph/widgets/stage_popover_card.dart @@ -0,0 +1,290 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/status/run_status_icon.dart'; +import '../domain/stage_run_facts.dart'; +import '../domain/stage_summary.dart'; +import 'graph_stage_node.dart'; +import 'stage_popover_parts.dart'; + +/// The undeclared-stage line, when this version has no declaration for a node. +const String stagePopoverUndeclared = + 'This stage is not declared in this pipeline version.'; + +/// The compact content of one stage's popover: a header with the stage's name, +/// type and (for a run) its recorded status, then the declaration's facts, the +/// prompt or its type's equivalent, limits and routes, and the actions. +/// +/// Built only while the popover is open. Nothing here is fetched: [summary] is +/// the pinned declaration and [facts] what the run recorded, if anything. +class StagePopoverCard extends StatelessWidget { + const StagePopoverCard({ + super.key, + required this.label, + required this.summary, + required this.onClose, + required this.onOpenDefinition, + this.facts, + this.onOpenVisit, + }); + + final String label; + final StageSummary? summary; + final StageRunFacts? facts; + final VoidCallback onClose; + final VoidCallback onOpenDefinition; + + /// Opens the stage's latest recorded visit; null when it has none. + final VoidCallback? onOpenVisit; + + @override + Widget build(BuildContext context) { + final summary = this.summary; + final facts = this.facts; + final sections = [ + if (facts != null && facts.visits > 0) ..._runSections(context, facts), + if (summary == null) + Text(stagePopoverUndeclared, style: popoverMuted(context)) + else + ..._definitionSections(context, summary), + ]; + return Semantics( + container: true, + explicitChildNodes: true, + label: '$label details', + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _header(context, summary, facts), + if (sections.isNotEmpty) + Flexible( + child: SingleChildScrollView( + key: const Key('stage-popover-body'), + padding: const EdgeInsets.fromLTRB(16, 4, 16, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var i = 0; i < sections.length; i++) ...[ + if (i > 0) const SizedBox(height: 12), + sections[i], + ], + ], + ), + ), + ), + _actions(context), + ], + ), + ); + } + + Widget _header( + BuildContext context, + StageSummary? summary, + StageRunFacts? facts, + ) { + final theme = Theme.of(context); + final status = facts?.status; + final chips = [ + if (summary != null) + PopoverChip( + key: const Key('stage-popover-type'), + label: summary.typeLabel, + icon: stageKindIcon(summary.kind), + tone: PopoverChipTone.accent, + ), + if (status != null) + PopoverChip( + key: const Key('stage-popover-status'), + label: status, + dot: runStatusColorOf(context, graphStatusState(status)), + ), + if (facts != null && facts.visits > 0) + PopoverChip( + key: const Key('stage-popover-visits'), + label: '×${facts.visits}', + tooltip: facts.visits == 1 ? '1 visit' : '${facts.visits} visits', + ), + if (facts?.duration case final duration?) + PopoverChip(label: duration, icon: Icons.schedule), + if (facts?.usage case final usage?) PopoverChip(label: usage), + ]; + return Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 4, 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.only(top: 6), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + key: const Key('stage-popover-title'), + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + if (chips.isNotEmpty) ...[ + const SizedBox(height: 6), + Wrap(spacing: 6, runSpacing: 6, children: chips), + ], + ], + ), + ), + ), + IconButton( + key: const Key('stage-popover-close'), + tooltip: 'Close', + visualDensity: VisualDensity.compact, + iconSize: 18, + onPressed: onClose, + icon: const Icon(Icons.close), + ), + ], + ), + ); + } + + List _runSections(BuildContext context, StageRunFacts facts) { + final colors = Theme.of(context).colorScheme; + return [ + if (facts.failure case final failure?) + PopoverNote( + key: const Key('stage-popover-failure'), + icon: Icons.error_outline, + color: colors.error, + text: failure, + ), + if (facts.verdict case final verdict?) + PopoverSection( + label: 'Verdict', + child: Text(verdict, key: const Key('stage-popover-verdict')), + ), + if (facts.handoff case final handoff?) + PopoverSection( + label: 'Handoff', + child: Text( + handoff, + key: const Key('stage-popover-handoff'), + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + ), + ]; + } + + List _definitionSections(BuildContext context, StageSummary s) { + return [ + if (s.meta.isNotEmpty) + Wrap( + key: const Key('stage-popover-meta'), + spacing: 6, + runSpacing: 6, + children: [for (final item in s.meta) PopoverChip(label: item)], + ), + if (s.tools.isNotEmpty) + PopoverSection( + label: s.toolsDefault ? 'Tools · default' : 'Tools', + child: Wrap( + key: const Key('stage-popover-tools'), + spacing: 6, + runSpacing: 6, + children: [ + for (final tool in s.tools) + PopoverChip(label: tool, icon: toolIcon(tool), mono: true), + ], + ), + ), + if (s.permissions.isNotEmpty) PopoverPermissions(lines: s.permissions), + if (s.skills.isNotEmpty) + PopoverSection( + label: 'Skills', + child: Wrap( + spacing: 6, + runSpacing: 6, + children: [for (final skill in s.skills) PopoverChip(label: skill)], + ), + ), + if (s.prompt case final prompt?) + PopoverSection( + label: s.kind == StageKind.human ? 'Operator instructions' : 'Prompt', + child: PopoverPrompt(text: prompt), + ), + if (s.commands.isNotEmpty) + PopoverSection( + label: 'Commands', + child: PopoverCommands(commands: s.commands), + ), + if (s.gate.isNotEmpty) + PopoverSection( + label: 'Gate', + child: Wrap( + key: const Key('stage-popover-gate'), + spacing: 6, + runSpacing: 6, + children: [for (final item in s.gate) PopoverChip(label: item)], + ), + ), + if (s.limits.isNotEmpty) + PopoverSection( + label: 'Limits', + child: Wrap( + key: const Key('stage-popover-limits'), + spacing: 6, + runSpacing: 6, + children: [for (final item in s.limits) PopoverChip(label: item)], + ), + ), + if (s.routes.isNotEmpty) + PopoverSection( + label: s.kind == StageKind.terminal ? 'Routes in' : 'Routes', + child: Wrap( + key: const Key('stage-popover-routes'), + spacing: 6, + runSpacing: 6, + children: [ + for (final route in s.routes) + s.kind == StageKind.terminal + ? PopoverRouteChip(from: route.target, to: route.outcome) + : PopoverRouteChip(from: route.outcome, to: route.target), + ], + ), + ), + ]; + } + + Widget _actions(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return DecoratedBox( + decoration: BoxDecoration( + border: Border(top: BorderSide(color: colors.outlineVariant)), + ), + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 8), + child: Wrap( + alignment: WrapAlignment.end, + spacing: 8, + runSpacing: 4, + children: [ + if (onOpenVisit != null) + TextButton.icon( + key: const Key('stage-popover-open-visit'), + onPressed: onOpenVisit, + icon: const Icon(Icons.history, size: 18), + label: const Text('Open visit'), + ), + FilledButton.tonalIcon( + key: const Key('stage-popover-open-definition'), + onPressed: onOpenDefinition, + icon: const Icon(Icons.description_outlined, size: 18), + label: const Text('Open definition'), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/graph/widgets/stage_popover_chips.dart b/app/lib/features/graph/widgets/stage_popover_chips.dart new file mode 100644 index 00000000..9716cea0 --- /dev/null +++ b/app/lib/features/graph/widgets/stage_popover_chips.dart @@ -0,0 +1,170 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/text/monospace.dart'; +import '../../../ui/theme/app_design_tokens.dart'; +import '../domain/stage_summary.dart'; +import 'graph_stage_node.dart'; + +/// The stage popover's compact facts: chips for configs, tools and routes, +/// and the icons and corners they share. + +TextStyle? popoverMuted(BuildContext context) { + final theme = Theme.of(context); + return theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ); +} + +/// The corners of the popover's inner pieces (chips, blocks): the design's +/// own radius, else a soft 8 (chips 6). +BorderRadius popoverCorners(BuildContext context, double designed) => + AppDesignTokens.of(context).corners(BorderRadius.circular(designed)); + +/// The icon of a stage's type chip. +IconData stageKindIcon(StageKind kind) => switch (kind) { + StageKind.model => Icons.auto_awesome_outlined, + StageKind.check => checkStageIcon(delivery: false), + StageKind.deliveryGate => checkStageIcon(delivery: true), + StageKind.findings => Icons.filter_alt_outlined, + StageKind.human => Icons.person_outline, + StageKind.terminal => Icons.flag_outlined, + StageKind.other => Icons.widgets_outlined, +}; + +/// A tool chip's icon. +IconData toolIcon(String tool) => switch (tool) { + 'read' => Icons.visibility_outlined, + 'glob' => Icons.folder_open_outlined, + 'grep' => Icons.search, + 'edit' => Icons.edit_outlined, + 'shell' => Icons.terminal, + 'websearch' => Icons.travel_explore, + 'webfetch' => Icons.public, + _ when tool.startsWith('mcp:') => Icons.extension_outlined, + _ => Icons.build_outlined, +}; + +enum PopoverChipTone { neutral, accent } + +/// One compact fact: a tinted label, optionally led by an icon or a status dot. +class PopoverChip extends StatelessWidget { + const PopoverChip({ + super.key, + required this.label, + this.icon, + this.dot, + this.tone = PopoverChipTone.neutral, + this.mono = false, + this.tooltip, + }); + + final String label; + final IconData? icon; + final Color? dot; + final PopoverChipTone tone; + final bool mono; + final String? tooltip; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final accent = tone == PopoverChipTone.accent; + final foreground = accent + ? colors.onSecondaryContainer + : colors.onSurfaceVariant; + final base = theme.textTheme.labelMedium ?? const TextStyle(); + final style = base.copyWith( + color: foreground, + fontFamily: mono ? appMonospaceFamily : null, + height: 1.2, + ); + final size = (style.fontSize ?? 12) * 1.15; + Widget chip = DecoratedBox( + decoration: BoxDecoration( + color: accent + ? colors.secondaryContainer + : colors.surfaceContainerHighest, + borderRadius: popoverCorners(context, 6), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (dot != null) ...[ + Container( + width: 7, + height: 7, + decoration: BoxDecoration(color: dot, shape: BoxShape.circle), + ), + const SizedBox(width: 5), + ] else if (icon != null) ...[ + Icon(icon, size: size, color: foreground), + const SizedBox(width: 4), + ], + Flexible(child: Text(label, style: style)), + ], + ), + ), + ); + final tip = tooltip; + if (tip != null) chip = Tooltip(message: tip, child: chip); + return chip; + } +} + +/// One route as `from → to`. The arrow is an icon, not a glyph: a design's +/// interface face may not carry U+2192. +class PopoverRouteChip extends StatelessWidget { + const PopoverRouteChip({super.key, required this.from, required this.to}); + + final String from; + final String to; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final style = (theme.textTheme.labelMedium ?? const TextStyle()).copyWith( + color: colors.onSurfaceVariant, + height: 1.2, + ); + return Semantics( + label: '$from to $to', + excludeSemantics: true, + child: DecoratedBox( + decoration: BoxDecoration( + color: colors.surfaceContainerHighest, + borderRadius: popoverCorners(context, 6), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible(child: Text(from, style: style)), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: Icon( + Icons.arrow_forward, + size: (style.fontSize ?? 12) * 1.1, + color: colors.outline, + ), + ), + Flexible( + child: Text( + to, + style: style.copyWith( + color: colors.onSurface, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/app/lib/features/graph/widgets/stage_popover_parts.dart b/app/lib/features/graph/widgets/stage_popover_parts.dart new file mode 100644 index 00000000..78759f6c --- /dev/null +++ b/app/lib/features/graph/widgets/stage_popover_parts.dart @@ -0,0 +1,308 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/text/monospace.dart'; +import '../../chat/ui/transcript/chat_markdown_view.dart'; +import 'stage_popover_chips.dart'; + +export 'stage_popover_chips.dart'; + +/// The stage popover's larger pieces: labelled sections, the clamped prompt +/// block, the command list and the collapsed permissions line. + +/// A small muted label over its content. +class PopoverSection extends StatelessWidget { + const PopoverSection({super.key, required this.label, required this.child}); + + final String label; + final Widget child; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + label, + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + fontWeight: FontWeight.w600, + letterSpacing: 0.4, + ), + ), + const SizedBox(height: 6), + DefaultTextStyle.merge(style: theme.textTheme.bodyMedium, child: child), + ], + ); + } +} + +/// A one-line notice with an icon, e.g. the recorded failure reason. +class PopoverNote extends StatelessWidget { + const PopoverNote({ + super.key, + required this.icon, + required this.color, + required this.text, + }); + + final IconData icon; + final Color color; + final String text; + + @override + Widget build(BuildContext context) { + final style = Theme.of( + context, + ).textTheme.bodyMedium?.copyWith(color: color); + return DecoratedBox( + decoration: BoxDecoration( + color: color.withValues(alpha: 0.08), + borderRadius: popoverCorners(context, 8), + ), + child: Padding( + padding: const EdgeInsets.fromLTRB(10, 8, 10, 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, size: 18, color: color), + const SizedBox(width: 8), + Expanded(child: Text(text, style: style)), + ], + ), + ), + ); + } +} + +/// The inset block a prompt or command list sits in. +class PopoverBlock extends StatelessWidget { + const PopoverBlock({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return DecoratedBox( + decoration: BoxDecoration( + color: colors.surface, + border: Border.all(color: colors.outlineVariant.withValues(alpha: 0.6)), + borderRadius: popoverCorners(context, 8), + ), + child: Padding(padding: const EdgeInsets.all(12), child: child), + ); + } +} + +/// A prompt as typeset markdown, held to about ten lines with a fade until +/// "Show all" expands it in place. +class PopoverPrompt extends StatefulWidget { + const PopoverPrompt({super.key, required this.text}); + + final String text; + + /// Collapsed height in lines of the body face. + static const int collapsedLines = 10; + + @override + State createState() => _PopoverPromptState(); +} + +class _PopoverPromptState extends State { + bool _expanded = false; + bool _overflows = false; + + bool _onMetrics(ScrollMetricsNotification notification) { + final overflows = notification.metrics.maxScrollExtent > 0.5; + if (overflows != _overflows) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) setState(() => _overflows = overflows); + }); + } + return true; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final body = theme.textTheme.bodyMedium ?? const TextStyle(); + final scaler = MediaQuery.textScalerOf(context); + final line = scaler.scale(body.fontSize ?? 14) * (body.height ?? 1.43); + // Headings a step down from the transcript's: in a compact card a + // prompt's `## Goal` is a label, not a page title. + final text = theme.textTheme; + final heading = text.titleSmall?.copyWith(fontWeight: FontWeight.w700); + final markdown = Theme( + data: theme.copyWith( + textTheme: text.copyWith( + headlineSmall: text.titleMedium?.copyWith( + fontWeight: FontWeight.w700, + ), + titleLarge: heading, + titleMedium: heading, + ), + ), + child: DefaultTextStyle.merge( + style: body, + child: ChatMarkdownView(text: widget.text), + ), + ); + final Widget content = _expanded + ? markdown + : NotificationListener( + onNotification: _onMetrics, + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: line * PopoverPrompt.collapsedLines, + ), + child: _fade( + SingleChildScrollView( + physics: const NeverScrollableScrollPhysics(), + primary: false, + child: markdown, + ), + ), + ), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + PopoverBlock( + child: KeyedSubtree( + key: const Key('stage-popover-prompt'), + child: content, + ), + ), + if (_overflows || _expanded) + Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton( + key: const Key('stage-popover-show-all'), + style: TextButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric(horizontal: 4), + ), + onPressed: () => setState(() => _expanded = !_expanded), + child: Text(_expanded ? 'Show less' : 'Show all'), + ), + ), + ], + ); + } + + Widget _fade(Widget child) { + if (!_overflows) return child; + return ShaderMask( + blendMode: BlendMode.dstIn, + shaderCallback: (bounds) => LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: const [Color(0xFFFFFFFF), Color(0x00FFFFFF)], + stops: [ + bounds.height <= 0 ? 0 : (1 - 36 / bounds.height).clamp(0.0, 1.0), + 1, + ], + ).createShader(bounds), + child: child, + ); + } +} + +/// A check stage's commands, one per line in the monospace face. +class PopoverCommands extends StatelessWidget { + const PopoverCommands({super.key, required this.commands}); + + final List commands; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final style = theme.textTheme.bodySmall?.copyWith( + fontFamily: appMonospaceFamily, + height: 1.5, + ); + final prompt = theme.colorScheme.onSurfaceVariant; + return PopoverBlock( + child: SelectableText.rich( + key: const Key('stage-popover-commands'), + TextSpan( + style: style, + children: [ + for (var i = 0; i < commands.length; i++) ...[ + if (i > 0) const TextSpan(text: '\n'), + TextSpan( + text: r'$ ', + style: TextStyle(color: prompt), + ), + TextSpan(text: commands[i]), + ], + ], + ), + ), + ); + } +} + +/// The permission allow-lists behind one collapsed "Permissions" line. +class PopoverPermissions extends StatefulWidget { + const PopoverPermissions({super.key, required this.lines}); + + final List lines; + + @override + State createState() => _PopoverPermissionsState(); +} + +class _PopoverPermissionsState extends State { + bool _open = false; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final muted = theme.colorScheme.onSurfaceVariant; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + InkWell( + key: const Key('stage-popover-permissions'), + borderRadius: popoverCorners(context, 6), + onTap: () => setState(() => _open = !_open), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + children: [ + Icon( + _open ? Icons.expand_more : Icons.chevron_right, + size: 18, + color: muted, + ), + const SizedBox(width: 2), + Text( + 'Permissions', + style: theme.textTheme.labelSmall?.copyWith( + color: muted, + fontWeight: FontWeight.w600, + letterSpacing: 0.4, + ), + ), + ], + ), + ), + ), + if (_open) + Padding( + padding: const EdgeInsetsDirectional.only(start: 20, top: 4), + child: Text( + widget.lines.join('\n'), + key: const Key('stage-popover-permission-lines'), + style: theme.textTheme.bodySmall?.copyWith( + fontFamily: appMonospaceFamily, + height: 1.5, + ), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/graph/widgets/stage_popover_position.dart b/app/lib/features/graph/widgets/stage_popover_position.dart new file mode 100644 index 00000000..8cf3dd84 --- /dev/null +++ b/app/lib/features/graph/widgets/stage_popover_position.dart @@ -0,0 +1,368 @@ +import 'dart:math' as math; + +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// Where a stage popover sits relative to its node. +enum StagePopoverSide { above, below, right, left, over } + +/// Places one popover card beside an anchor node, inside a bounding box, and +/// paints the nub that points at the node. +/// +/// It fills its overlay but hit-tests only the card, so the graph under it +/// keeps every gesture. The anchor is a rectangle in [anchorBox]'s own space +/// (the graph canvas, inside the pan/zoom transform); it is mapped through the +/// live transform at layout, and [relayout] (the viewport transform) lays the +/// card out again on every pan or zoom, so it follows the node. +class StagePopoverPosition extends SingleChildRenderObjectWidget { + const StagePopoverPosition({ + super.key, + required this.anchorBox, + required this.anchorRect, + required this.boundsBox, + required this.boundsSize, + this.safeArea = EdgeInsets.zero, + required this.relayout, + required this.fill, + required this.border, + required this.radius, + required this.elevation, + required this.shadowColor, + super.child, + }); + + final RenderBox? Function() anchorBox; + final Rect anchorRect; + + /// The visible box the card must stay inside, and its extent; a null box + /// uses the overlay itself. + final RenderBox? Function() boundsBox; + final Size? boundsSize; + + /// Insets of the screen the card must also keep clear of (floating bars + /// drawn over the viewport's edges). + final EdgeInsets safeArea; + final Listenable? relayout; + final Color fill; + final BorderSide border; + final double radius; + final double elevation; + final Color shadowColor; + + @override + RenderStagePopoverPosition createRenderObject(BuildContext context) => + RenderStagePopoverPosition( + anchorBox: anchorBox, + anchorRect: anchorRect, + boundsBox: boundsBox, + boundsSize: boundsSize, + safeArea: safeArea, + relayout: relayout, + fill: fill, + border: border, + radius: radius, + elevation: elevation, + shadowColor: shadowColor, + ); + + @override + void updateRenderObject( + BuildContext context, + RenderStagePopoverPosition renderObject, + ) { + renderObject + ..anchorBox = anchorBox + ..anchorRect = anchorRect + ..boundsBox = boundsBox + ..boundsSize = boundsSize + ..safeArea = safeArea + ..relayout = relayout + ..fill = fill + ..border = border + ..radius = radius + ..elevation = elevation + ..shadowColor = shadowColor; + } +} + +class RenderStagePopoverPosition extends RenderShiftedBox { + RenderStagePopoverPosition({ + required this.anchorBox, + required this._anchorRect, + required this.boundsBox, + required this._boundsSize, + required this._safeArea, + required this._relayout, + required this.fill, + required this.border, + required this.radius, + required this.elevation, + required this.shadowColor, + }) : super(null); + + /// The card's widest extent. + static const double maxCardWidth = 400; + + /// The card's tallest extent; a longer card scrolls its body. + static const double maxCardHeight = 560; + + /// The space kept between the card and the viewport's edges. + static const double margin = 8; + + /// The nub's depth; its base is twice as wide. + static const double nub = 7; + + /// The gap between the node and the nub's tip. + static const double gap = 3; + + RenderBox? Function() anchorBox; + RenderBox? Function() boundsBox; + Color fill; + BorderSide border; + double radius; + double elevation; + Color shadowColor; + + Rect _anchorRect; + set anchorRect(Rect value) { + if (value == _anchorRect) return; + _anchorRect = value; + markNeedsLayout(); + } + + EdgeInsets _safeArea; + set safeArea(EdgeInsets value) { + if (value == _safeArea) return; + _safeArea = value; + markNeedsLayout(); + } + + Size? _boundsSize; + set boundsSize(Size? value) { + if (value == _boundsSize) return; + _boundsSize = value; + markNeedsLayout(); + } + + Listenable? _relayout; + set relayout(Listenable? value) { + if (value == _relayout) return; + if (attached) _relayout?.removeListener(markNeedsLayout); + _relayout = value; + if (attached) _relayout?.addListener(markNeedsLayout); + markNeedsLayout(); + } + + /// Where the card went in the last layout, for tests and the nub. + StagePopoverSide side = StagePopoverSide.above; + bool _visible = false; + Offset _tip = Offset.zero; + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _relayout?.addListener(markNeedsLayout); + } + + @override + void detach() { + _relayout?.removeListener(markNeedsLayout); + super.detach(); + } + + Rect _bounds() { + final whole = _safeArea.deflateRect(Offset.zero & size); + final box = boundsBox(); + final extent = _boundsSize; + if (box == null || !box.attached || extent == null) { + return whole.deflate(margin); + } + final origin = MatrixUtils.transformPoint( + box.getTransformTo(this), + Offset.zero, + ); + return (origin & extent).intersect(whole).deflate(margin); + } + + Rect? _anchor() { + final box = anchorBox(); + if (box == null || !box.attached) return null; + return MatrixUtils.transformRect(box.getTransformTo(this), _anchorRect); + } + + @override + void performLayout() { + size = constraints.biggest; + final card = child; + // Mapping through the ancestors' paint transforms reads their sizes (a + // page transition's translation does); a layout callback is the sanctioned + // scope for that, as it is for a LayoutBuilder. + var mapped = (bounds: Rect.zero, anchor: null as Rect?); + invokeLayoutCallback((_) { + mapped = (bounds: _bounds(), anchor: _anchor()); + }); + final bounds = mapped.bounds; + final anchor = mapped.anchor; + _visible = + card != null && + anchor != null && + bounds.width > 0 && + bounds.height > 0 && + anchor.overlaps(bounds); + if (!_visible || card == null || anchor == null) { + card?.layout(const BoxConstraints.tightFor(width: 0, height: 0)); + return; + } + final width = math.min(maxCardWidth, bounds.width); + var cardSize = _layoutCard( + card, + width, + math.min(maxCardHeight, bounds.height), + ); + final reach = gap + nub; + final above = anchor.top - reach - bounds.top; + final below = bounds.bottom - anchor.bottom - reach; + final right = bounds.right - anchor.right - reach; + final left = anchor.left - reach - bounds.left; + if (cardSize.height <= above) { + side = StagePopoverSide.above; + } else if (cardSize.height <= below) { + side = StagePopoverSide.below; + } else if (cardSize.width <= right) { + side = StagePopoverSide.right; + } else if (cardSize.width <= left) { + side = StagePopoverSide.left; + } else if (math.max(above, below) >= 160) { + // Too tall for either side whole: take the roomier one and scroll. + side = above >= below ? StagePopoverSide.above : StagePopoverSide.below; + cardSize = _layoutCard( + card, + width, + math.min(maxCardHeight, math.max(above, below)), + ); + } else { + side = StagePopoverSide.over; + } + final parentData = card.parentData! as BoxParentData; + double clampX(double x) => x.clamp( + bounds.left, + math.max(bounds.left, bounds.right - cardSize.width), + ); + double clampY(double y) => y.clamp( + bounds.top, + math.max(bounds.top, bounds.bottom - cardSize.height), + ); + final center = anchor.center; + final inset = radius + nub + 2; + switch (side) { + case StagePopoverSide.above: + case StagePopoverSide.below: + final x = clampX(center.dx - cardSize.width / 2); + final y = side == StagePopoverSide.above + ? anchor.top - reach - cardSize.height + : anchor.bottom + reach; + parentData.offset = Offset(x, y); + final tipX = center.dx + .clamp(x + inset, math.max(x + inset, x + cardSize.width - inset)) + .toDouble(); + _tip = Offset( + tipX, + side == StagePopoverSide.above + ? anchor.top - gap + : anchor.bottom + gap, + ); + case StagePopoverSide.right: + case StagePopoverSide.left: + final y = clampY(center.dy - cardSize.height / 2); + final x = side == StagePopoverSide.right + ? anchor.right + reach + : anchor.left - reach - cardSize.width; + parentData.offset = Offset(x, y); + final tipY = center.dy + .clamp(y + inset, math.max(y + inset, y + cardSize.height - inset)) + .toDouble(); + _tip = Offset( + side == StagePopoverSide.right + ? anchor.right + gap + : anchor.left - gap, + tipY, + ); + case StagePopoverSide.over: + parentData.offset = Offset( + clampX(center.dx - cardSize.width / 2), + clampY(center.dy - cardSize.height / 2), + ); + } + } + + Size _layoutCard(RenderBox card, double width, double height) { + card.layout( + BoxConstraints(maxWidth: width, maxHeight: math.max(0, height)), + parentUsesSize: true, + ); + return card.size; + } + + /// The nub as a triangle whose base overlaps the card's edge by the + /// border, so the card's own frame line does not cross it. + Path _nubPath() { + final t = _tip; + final b = border.width; + return switch (side) { + StagePopoverSide.above => + Path() + ..moveTo(t.dx - nub, t.dy - nub - b) + ..lineTo(t.dx, t.dy) + ..lineTo(t.dx + nub, t.dy - nub - b), + StagePopoverSide.below => + Path() + ..moveTo(t.dx - nub, t.dy + nub + b) + ..lineTo(t.dx, t.dy) + ..lineTo(t.dx + nub, t.dy + nub + b), + StagePopoverSide.right => + Path() + ..moveTo(t.dx + nub + b, t.dy - nub) + ..lineTo(t.dx, t.dy) + ..lineTo(t.dx + nub + b, t.dy + nub), + StagePopoverSide.left => + Path() + ..moveTo(t.dx - nub - b, t.dy - nub) + ..lineTo(t.dx, t.dy) + ..lineTo(t.dx - nub - b, t.dy + nub), + StagePopoverSide.over => Path(), + }; + } + + @override + void paint(PaintingContext context, Offset offset) { + final card = child; + if (!_visible || card == null) return; + final hasNub = side != StagePopoverSide.over; + final nubPath = _nubPath().shift(offset); + if (hasNub && elevation > 0) { + context.canvas.drawShadow( + Path.from(nubPath)..close(), + shadowColor, + elevation, + false, + ); + } + super.paint(context, offset); + if (!hasNub) return; + context.canvas.drawPath(Path.from(nubPath)..close(), Paint()..color = fill); + if (border.width > 0 && border.style != BorderStyle.none) { + context.canvas.drawPath( + nubPath, + Paint() + ..color = border.color + ..style = PaintingStyle.stroke + ..strokeWidth = border.width + ..strokeJoin = StrokeJoin.miter, + ); + } + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) => + _visible && super.hitTestChildren(result, position: position); +} diff --git a/app/lib/features/notification_service/notification_service_bridge.dart b/app/lib/features/notification_service/notification_service_bridge.dart index fa0f284d..23717f3d 100644 --- a/app/lib/features/notification_service/notification_service_bridge.dart +++ b/app/lib/features/notification_service/notification_service_bridge.dart @@ -12,8 +12,8 @@ export 'notification_service_status.dart'; /// The app's handle on Android background delivery: a native foreground /// service (android/…/notify/NotificationService.kt) that keeps its own -/// socket to the server and shows the server's notifications, so the ntfy app -/// is not needed. Other platforms have no service ([supported] is false). +/// socket to the server and shows the server's notifications while the app +/// is closed. Other platforms have no service ([supported] is false). abstract interface class NotificationServiceBridge { bool get supported; diff --git a/app/lib/features/runs/ui/run_check_output_view.dart b/app/lib/features/runs/ui/run_check_output_view.dart index 123fcf56..4e3766fe 100644 --- a/app/lib/features/runs/ui/run_check_output_view.dart +++ b/app/lib/features/runs/ui/run_check_output_view.dart @@ -4,6 +4,7 @@ import '../../../ui/status/run_status_icon.dart'; import '../../../ui/text/monospace.dart'; import '../../chat/ui/transcript/chat_markdown_view.dart'; import '../domain/check_step_output.dart'; +import '../../../ui/theme/app_design_tokens.dart'; /// The note under a command whose recorded output the server cut short. const String checkOutputTruncated = @@ -99,7 +100,9 @@ class RunCheckCommandRow extends StatelessWidget { DecoratedBox( decoration: BoxDecoration( color: theme.colorScheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(8), + borderRadius: AppDesignTokens.of( + context, + ).denseCorners(BorderRadius.circular(8)), ), child: Padding( padding: const EdgeInsets.all(12), diff --git a/app/lib/features/runs/ui/run_detail_tab_bodies.dart b/app/lib/features/runs/ui/run_detail_tab_bodies.dart index d898c106..f680f0d3 100644 --- a/app/lib/features/runs/ui/run_detail_tab_bodies.dart +++ b/app/lib/features/runs/ui/run_detail_tab_bodies.dart @@ -12,6 +12,7 @@ import '../../../ui/layout/sticky_section.dart'; import '../../../ui/text/live_elapsed_builder.dart'; import '../../../ui/text/monospace.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../../ui/theme/app_design_tokens.dart'; /// The Summary tab: the run's identity, the recorded facts as one grid, /// the stored original prompt with its copy control and the collapsible Input @@ -231,7 +232,9 @@ Widget _materialBlock(BuildContext context, DetailSummaryRow row) { padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: theme.colorScheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(8), + borderRadius: AppDesignTokens.of( + context, + ).denseCorners(BorderRadius.circular(8)), ), child: SelectableText( row.value, diff --git a/app/lib/features/runs/ui/run_detail_timeline.dart b/app/lib/features/runs/ui/run_detail_timeline.dart index 9da7b78c..abe938e7 100644 --- a/app/lib/features/runs/ui/run_detail_timeline.dart +++ b/app/lib/features/runs/ui/run_detail_timeline.dart @@ -9,6 +9,7 @@ import '../../../ui/text/live_elapsed_builder.dart'; import '../../pipelines/pipeline_format.dart' show formatDuration; import '../domain/run_models.dart'; import 'run_detail_content.dart'; +import '../../../ui/theme/app_design_tokens.dart'; /// The Timeline tab's recorded visits, one shared list row per visit. /// @@ -116,7 +117,9 @@ class RunTimelineRow extends StatelessWidget { padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( color: color.withValues(alpha: 0.14), - borderRadius: BorderRadius.circular(10), + borderRadius: AppDesignTokens.of( + context, + ).denseCorners(BorderRadius.circular(10)), ), child: Text( label, diff --git a/app/lib/features/search/ui/search_result_view.dart b/app/lib/features/search/ui/search_result_view.dart index 4658a658..8d8da89d 100644 --- a/app/lib/features/search/ui/search_result_view.dart +++ b/app/lib/features/search/ui/search_result_view.dart @@ -5,6 +5,7 @@ import '../../../core/transport/pipelines_client.dart' show configuredGatewayEndpoint; import '../../../ui/layout/app_list_avatar.dart'; import '../../../ui/layout/app_overflow_menu.dart'; +import '../../../ui/theme/app_design_tokens.dart'; import '../../artifacts/domain/artifact_kind.dart'; import '../../artifacts/domain/artifact_record.dart'; import '../../artifacts/ui/artifact_tile.dart'; @@ -48,9 +49,11 @@ Widget? searchArtifactThumbnail(BuildContext context, JsonMap hit) { return null; } return ClipRRect( - borderRadius: BorderRadius.circular(8), + borderRadius: AppDesignTokens.of( + context, + ).denseCorners(BorderRadius.circular(8)), child: SizedBox.square( - dimension: kAppListAvatarSize, + dimension: appListAvatarSize(context), child: ArtifactThumbnail( key: ValueKey('search.thumbnail.${hit['target']}'), artifact: record, diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 5161df77..00c3f013 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart'; import '../chat/workspace/chat_center_stage_controller.dart'; import '../chat/workspace/chat_float_shortcut.dart'; import '../chat/workspace/chat_list_hidden_controller.dart'; +import '../chat/workspace/chat_pane_cycle.dart'; import '../terminal/terminal_shortcuts.dart'; import '../../shell/detached/detached_window_scope.dart'; import '../../shell/windows/window_shortcuts.dart'; @@ -197,6 +198,13 @@ class KeyboardShortcutRegistry { action: 'Focus the neighbouring chat pane', keys: _apple ? 'Cmd+Shift+Arrows' : 'Ctrl+Shift+Arrows', ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.chat, + action: 'Next or previous chat pane on screen', + keys: chatPaneCycleShortcutLabel(platform), + caveat: + 'On a wide window with more than one chat shown: the tiled panes left to right, then top to bottom, then the floating chat windows, wrapping around. The pane\'s message input takes the keyboard and its border flashes. No chat opens or closes. In the terminal the keys go to the terminal.', + ), KeyboardShortcutEntry( group: KeyboardShortcutGroup.chat, action: 'Move the active chat pane', diff --git a/app/lib/features/settings/ntfy_settings_controller.dart b/app/lib/features/settings/notification_settings_controller.dart similarity index 73% rename from app/lib/features/settings/ntfy_settings_controller.dart rename to app/lib/features/settings/notification_settings_controller.dart index 9251669a..f12f56c4 100644 --- a/app/lib/features/settings/ntfy_settings_controller.dart +++ b/app/lib/features/settings/notification_settings_controller.dart @@ -2,9 +2,9 @@ import 'package:flutter/foundation.dart'; import '../../core/api_gateway.dart'; -/// One server-side ntfy notification choice, in the server's wire key. -class NtfySetting { - const NtfySetting(this.key, this.label, {this.subtitle}); +/// One server-side notification choice, in the server's wire key. +class NotificationSetting { + const NotificationSetting(this.key, this.label, {this.subtitle}); final String key; final String label; @@ -13,36 +13,30 @@ class NtfySetting { final String? subtitle; } -/// The server's global notification choices, in display order. +/// The server's global notification choices, in display order. They are +/// stored on the server, so they apply to every signed-in device. /// /// `run_finished` (server default off) makes every run end notify; without it /// only runs started with "Notify me" announce their success or failure. -const ntfySettings = [ - NtfySetting( +const notificationSettings = [ + NotificationSetting( 'run_finished', 'Notify when any run ends', subtitle: 'Otherwise only runs started with Notify me', ), - NtfySetting('chat_needs_you', 'Chat needs your answer or approval'), - NtfySetting('chat_reply_finished', 'Chat reply finished'), + NotificationSetting('chat_needs_you', 'Chat needs your answer or approval'), + NotificationSetting('chat_reply_finished', 'Chat reply finished'), ]; -/// The server's switch for also publishing to ntfy. Optional: older servers -/// do not send it, and Settings hides the switch then. -const ntfyEnabledSetting = NtfySetting( - 'ntfy_enabled', - 'Also send to ntfy', - subtitle: 'For devices that still use the ntfy app', -); - -/// Loads and changes the server's ntfy notification settings through the -/// shared gateway (`notification_settings` / `set_notification_settings`). +/// Loads and changes the server's notification settings through the shared +/// gateway (`notification_settings` / `set_notification_settings`). /// /// A toggle shows the new value at once and is reverted, with the server's /// refusal as [error], when the write fails. Every reply carries all keys, so -/// the stored result always replaces the local copy. -class NtfySettingsController extends ChangeNotifier { - NtfySettingsController(this.gateway); +/// the stored result always replaces the local copy. Keys the app does not +/// show (such as a retired one an older server still sends) are ignored. +class NotificationSettingsController extends ChangeNotifier { + NotificationSettingsController(this.gateway); final ApiGateway gateway; @@ -119,15 +113,13 @@ class NtfySettingsController extends ChangeNotifier { throw const FormatException('the reply carried no notification settings'); } final result = {}; - for (final setting in ntfySettings) { + for (final setting in notificationSettings) { final value = raw[setting.key]; if (value is! bool) { throw FormatException('the reply is missing ${setting.key}'); } result[setting.key] = value; } - final ntfy = raw[ntfyEnabledSetting.key]; - if (ntfy is bool) result[ntfyEnabledSetting.key] = ntfy; return result; } diff --git a/app/lib/features/settings/settings_chat_navigation_section.dart b/app/lib/features/settings/settings_chat_navigation_section.dart index 81e611de..03d1e8d3 100644 --- a/app/lib/features/settings/settings_chat_navigation_section.dart +++ b/app/lib/features/settings/settings_chat_navigation_section.dart @@ -27,8 +27,9 @@ class SettingsChatNavigationSection extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Text( - 'Saved on this device. Applies on a phone-width window; a wide ' - 'window keeps the chat list beside the chats.', + 'Saved on this device. Applies on a phone-width window; the ' + 'Chat stack also stays on a wide phone or tablet layout (an ' + 'unfolded foldable), beside the chat list.', ), if (navigation.saveFailed) Text( diff --git a/app/lib/features/settings/settings_design_section.dart b/app/lib/features/settings/settings_design_section.dart index 4e8c5c6e..d761b31e 100644 --- a/app/lib/features/settings/settings_design_section.dart +++ b/app/lib/features/settings/settings_design_section.dart @@ -56,6 +56,7 @@ class SettingsDesignSection extends StatelessWidget { subtitle: Text(design.description), secondary: DesignSwatchPreview( swatch: design.swatch(Theme.of(context).brightness), + lines: design.swatchLines, ), ), ], @@ -64,12 +65,14 @@ class SettingsDesignSection extends StatelessWidget { ); } -/// A design's small preview in the picker: its page with a line of its ink -/// and a dot of its accent, framed by a hairline. +/// A design's small preview in the picker: its page with [lines] lines of +/// its ink (the last one short) and a dot of its accent, framed by a +/// hairline. A dense design draws more, tighter lines in the same page. class DesignSwatchPreview extends StatelessWidget { - const DesignSwatchPreview({super.key, required this.swatch}); + const DesignSwatchPreview({super.key, required this.swatch, this.lines = 2}); final DesignSwatch swatch; + final int lines; @override Widget build(BuildContext context) => ExcludeSemantics( @@ -89,10 +92,14 @@ class DesignSwatchPreview extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Container(height: 2, color: swatch.ink), + for (var line = 1; line < lines; line += 1) + Container(height: lines > 2 ? 1 : 2, color: swatch.ink), FractionallySizedBox( widthFactor: 0.6, - child: Container(height: 2, color: swatch.ink), + child: Container( + height: lines > 2 ? 1 : 2, + color: swatch.ink, + ), ), ], ), diff --git a/app/lib/features/settings/settings_device_delivery_section.dart b/app/lib/features/settings/settings_device_delivery_section.dart index 494b4ecb..5a1bfb27 100644 --- a/app/lib/features/settings/settings_device_delivery_section.dart +++ b/app/lib/features/settings/settings_device_delivery_section.dart @@ -12,8 +12,8 @@ const deviceDeliveryTitle = 'Notifications in Pipelines'; const deviceDeliverySwitchLabel = 'Receive notifications in Pipelines'; const deviceDeliveryNote = 'Pipelines keeps its own connection to the server and shows its ' - 'notifications, so the ntfy app is no longer needed. Android shows a ' - 'quiet "Pipelines is connected" notification while it runs.'; + 'notifications even while the app is closed. Android shows a quiet ' + '"Pipelines is connected" notification while it runs.'; const deviceDeliveryBatteryLabel = 'Allow background delivery'; const deviceDeliveryNotificationsLabel = 'Allow notifications'; const deviceDeliveryWarningTitle = 'Delivery can pause while idle'; diff --git a/app/lib/features/settings/settings_group.dart b/app/lib/features/settings/settings_group.dart index 1923aa04..e618e7d3 100644 --- a/app/lib/features/settings/settings_group.dart +++ b/app/lib/features/settings/settings_group.dart @@ -33,16 +33,17 @@ class SettingsGroup extends StatelessWidget { final footer = this.footer; final theme = Theme.of(context); final tokens = AppDesignTokens.of(context); + final inset = settingsRowInsetOf(context); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (title != null) Padding( - padding: const EdgeInsetsDirectional.fromSTEB( - settingsRowInset, + padding: EdgeInsetsDirectional.fromSTEB( + inset, 0, - settingsRowInset, - settingsTitleGap, + inset, + tokens.density.space(settingsTitleGap), ), child: Semantics( header: true, @@ -74,7 +75,7 @@ class SettingsGroup extends StatelessWidget { Divider( height: 1, thickness: 1, - indent: settingsRowInset, + indent: inset, color: theme.colorScheme.outlineVariant, ), child, @@ -92,11 +93,12 @@ class SettingsGroup extends StatelessWidget { color: Theme.of(context).colorScheme.onSurfaceVariant, ); final text = DefaultTextStyle.merge(style: style, child: footer); + final inset = settingsRowInsetOf(context); return Padding( - padding: const EdgeInsetsDirectional.fromSTEB( - settingsRowInset, - settingsFieldGap + 2, - settingsRowInset, + padding: EdgeInsetsDirectional.fromSTEB( + inset, + AppDesignTokens.of(context).density.space(settingsFieldGap + 2), + inset, 0, ), child: text, @@ -124,8 +126,8 @@ class SettingsGroupItem extends StatelessWidget { width: double.infinity, child: Padding( padding: EdgeInsetsDirectional.symmetric( - horizontal: settingsRowInset, - vertical: 12, + horizontal: settingsRowInsetOf(context), + vertical: AppDesignTokens.of(context).density.space(12), ), child: child, ), diff --git a/app/lib/features/settings/settings_layout.dart b/app/lib/features/settings/settings_layout.dart index 5eb7cade..92ec6dd2 100644 --- a/app/lib/features/settings/settings_layout.dart +++ b/app/lib/features/settings/settings_layout.dart @@ -9,6 +9,10 @@ /// at a reading width beside the section index. library; +import 'package:flutter/widgets.dart'; + +import '../../ui/theme/app_design_tokens.dart'; + /// The widest the column of groups grows on a wide window. const double settingsContentMaxWidth = 720; @@ -50,3 +54,12 @@ const double settingsPreloadViewports = 1; /// How long a changing endpoint must settle before a server section reloads. const Duration settingsEndpointDebounce = Duration(milliseconds: 600); + +/// [settingsSectionGap] under the design at [context] (tighter when dense). +double settingsSectionGapOf(BuildContext context) => + AppDesignTokens.of(context).density.space(settingsSectionGap); + +/// [settingsRowInset] under the design at [context]: a dense design's rows +/// (its ListTiles' 12px padding) and their headers keep the same edge. +double settingsRowInsetOf(BuildContext context) => + AppDesignTokens.of(context).density.inset(settingsRowInset); diff --git a/app/lib/features/settings/settings_ntfy_section.dart b/app/lib/features/settings/settings_notification_settings_section.dart similarity index 64% rename from app/lib/features/settings/settings_ntfy_section.dart rename to app/lib/features/settings/settings_notification_settings_section.dart index b91ae158..3554e24c 100644 --- a/app/lib/features/settings/settings_ntfy_section.dart +++ b/app/lib/features/settings/settings_notification_settings_section.dart @@ -3,35 +3,33 @@ import 'dart:async'; import 'package:flutter/material.dart'; import '../../core/api_gateway.dart'; -import 'ntfy_settings_controller.dart'; +import 'notification_settings_controller.dart'; import 'settings_group.dart'; import 'settings_theme.dart'; -/// The section title for the server's ntfy notification choices. -const ntfySectionTitle = 'Phone notifications'; +/// The section title for the server's notification choices. +const notificationEventsTitle = 'Notification events'; -/// One line explaining where these notifications go. -const ntfySectionSubtitle = - 'Sent through ntfy to the devices subscribed to this server.'; - -/// The subtitle once the server delivers to the app itself (it reports -/// `ntfy_enabled`). -const ntfySectionAppSubtitle = - 'What the server notifies about: shown by the Pipelines app and, when ' - 'enabled, also sent through ntfy.'; +/// One line explaining that these choices are shared. +const notificationEventsSubtitle = + 'What the server notifies about. Stored on the server, so these apply to ' + 'every device signed in to it.'; /// Shown instead of loading while the shared connection is down. -const ntfyOfflineText = 'Connect to a server to change these.'; +const notificationEventsOfflineText = 'Connect to a server to change these.'; -ValueKey ntfySettingKey(String key) => ValueKey('ntfy-$key'); -const ntfyErrorKey = ValueKey('ntfy-settings-error'); +ValueKey notificationSettingKey(String key) => + ValueKey('notification-setting-$key'); +const notificationSettingsErrorKey = ValueKey( + 'notification-settings-error', +); /// The server-side notification checkboxes in Settings: run finished, chat /// needs you and chat reply finished. Values load from the server whenever /// [connected] becomes true and every toggle is written at once; a refusal is /// shown inline and the checkbox reverts. -class SettingsNtfySection extends StatefulWidget { - const SettingsNtfySection({ +class SettingsNotificationSettingsSection extends StatefulWidget { + const SettingsNotificationSettingsSection({ super.key, required this.gateway, required this.connected, @@ -41,13 +39,14 @@ class SettingsNtfySection extends StatefulWidget { final bool connected; @override - State createState() => _SettingsNtfySectionState(); + State createState() => + _SettingsNotificationSettingsSectionState(); } -class _SettingsNtfySectionState extends State { - late NtfySettingsController _controller = NtfySettingsController( - widget.gateway, - ); +class _SettingsNotificationSettingsSectionState + extends State { + late NotificationSettingsController _controller = + NotificationSettingsController(widget.gateway); @override void initState() { @@ -56,11 +55,11 @@ class _SettingsNtfySectionState extends State { } @override - void didUpdateWidget(SettingsNtfySection oldWidget) { + void didUpdateWidget(SettingsNotificationSettingsSection oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.gateway != widget.gateway) { _controller.dispose(); - _controller = NtfySettingsController(widget.gateway); + _controller = NotificationSettingsController(widget.gateway); } if (widget.connected && (!oldWidget.connected || oldWidget.gateway != widget.gateway)) { @@ -84,16 +83,12 @@ class _SettingsNtfySectionState extends State { final values = _controller.values; final enabled = widget.connected && _controller.enabled; final status = !widget.connected - ? ntfyOfflineText + ? notificationEventsOfflineText : _controller.loading && values == null ? 'Loading…' : ''; - final hasNtfySwitch = values?.containsKey(ntfyEnabledSetting.key) ?? false; final tiles = [ - for (final setting in [ - ...ntfySettings, - if (hasNtfySwitch) ntfyEnabledSetting, - ]) + for (final setting in notificationSettings) _tile( setting, values?[setting.key] ?? false, @@ -106,18 +101,18 @@ class _SettingsNtfySectionState extends State { !_controller.loading && (values == null || _controller.loadFailed); return SettingsGroup( - title: ntfySectionTitle, + title: notificationEventsTitle, footer: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Text(hasNtfySwitch ? ntfySectionAppSubtitle : ntfySectionSubtitle), + const Text(notificationEventsSubtitle), if (status.isNotEmpty) Text(status), if (_controller.error.isNotEmpty) Semantics( liveRegion: true, child: Text( _controller.error, - key: ntfyErrorKey, + key: notificationSettingsErrorKey, style: TextStyle(color: settingsErrorColor(context)), ), ), @@ -135,9 +130,13 @@ class _SettingsNtfySectionState extends State { ); } - Widget _tile(NtfySetting setting, bool value, ValueChanged? onChanged) { + Widget _tile( + NotificationSetting setting, + bool value, + ValueChanged? onChanged, + ) { return CheckboxListTile( - key: ntfySettingKey(setting.key), + key: notificationSettingKey(setting.key), title: Text(setting.label), subtitle: setting.subtitle == null ? null : Text(setting.subtitle!), value: value, diff --git a/app/lib/features/settings/settings_page_body.dart b/app/lib/features/settings/settings_page_body.dart index 1b66eaaf..b3008169 100644 --- a/app/lib/features/settings/settings_page_body.dart +++ b/app/lib/features/settings/settings_page_body.dart @@ -34,7 +34,7 @@ class SettingsPageBody extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ for (final (index, child) in children.indexed) ...[ - if (index > 0) const SizedBox(height: settingsSectionGap), + if (index > 0) SizedBox(height: settingsSectionGapOf(context)), child, ], ], diff --git a/app/lib/features/settings/settings_page_sections.dart b/app/lib/features/settings/settings_page_sections.dart index 55e36fe9..dc733bc2 100644 --- a/app/lib/features/settings/settings_page_sections.dart +++ b/app/lib/features/settings/settings_page_sections.dart @@ -151,11 +151,13 @@ extension _SettingsPageSections on _SettingsScreenState { ), ), SettingsSection( - id: 'phone-notifications', - title: ntfySectionTitle, - keywords: 'ntfy push phone run finished chat needs you', + id: 'notification-events', + title: notificationEventsTitle, + keywords: + 'notifications push phone events all devices run finished ' + 'chat needs you reply finished', lazy: true, - builder: (_) => SettingsNtfySection( + builder: (_) => SettingsNotificationSettingsSection( gateway: widget.client, connected: widget.client.state.kind == transport.ConnectionKind.connected, diff --git a/app/lib/features/settings/settings_phone_order.dart b/app/lib/features/settings/settings_phone_order.dart index 79d459a2..cf9f1be2 100644 --- a/app/lib/features/settings/settings_phone_order.dart +++ b/app/lib/features/settings/settings_phone_order.dart @@ -12,7 +12,7 @@ const settingsPhoneFirstIds = [ 'sign-in', 'notifications', 'device-delivery', - 'phone-notifications', + 'notification-events', ]; /// [sections] reordered for a phone: [settingsPhoneFirstIds] first. diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart index 3e7f86b5..8126d70a 100644 --- a/app/lib/features/settings/settings_screen.dart +++ b/app/lib/features/settings/settings_screen.dart @@ -25,7 +25,7 @@ import 'health/settings_health_section.dart'; import 'settings_search_page.dart'; import 'settings_section.dart'; import 'settings_notifications_section.dart'; -import 'settings_ntfy_section.dart'; +import 'settings_notification_settings_section.dart'; import 'settings_device_delivery_section.dart'; import '../notification_service/notification_service_bridge.dart'; import '../notification_service/notification_service_controller.dart'; @@ -44,7 +44,7 @@ import 'settings_keyboard_shortcuts_section.dart'; import 'settings_keys.dart'; import 'settings_row.dart'; import 'settings_read_aloud_section.dart'; -import '../chat/speech/speech_controller.dart'; +import '../chat/speech/speech.dart'; import 'settings_open_in_chat_section.dart'; part 'settings_page_sections.dart'; diff --git a/app/lib/features/settings/settings_search_page.dart b/app/lib/features/settings/settings_search_page.dart index a3c3234e..19f799d6 100644 --- a/app/lib/features/settings/settings_search_page.dart +++ b/app/lib/features/settings/settings_search_page.dart @@ -171,7 +171,7 @@ class _SettingsSearchPageState extends State { ), ], ), - const SizedBox(height: settingsSectionGap), + SizedBox(height: settingsSectionGapOf(context)), Expanded(child: _list(visible, insets)), ], ), @@ -201,7 +201,7 @@ class _SettingsSearchPageState extends State { Widget _list(List visible, EdgeInsets insets) { if (visible.isEmpty) { return Padding( - padding: const EdgeInsets.all(settingsRowInset), + padding: EdgeInsets.all(settingsRowInsetOf(context)), child: Text('No settings match "${_search.text.trim()}".'), ); } @@ -222,7 +222,7 @@ class _SettingsSearchPageState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ for (final (index, section) in visible.indexed) ...[ - if (index > 0) const SizedBox(height: settingsSectionGap), + if (index > 0) SizedBox(height: settingsSectionGapOf(context)), KeyedSubtree( key: _keyFor(section.id), child: _isActive(section) diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index 3e9d1324..b5b3425b 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -354,7 +354,7 @@ class _AdaptiveShellState extends State { child: ShellRailScope( shown: rail, bodyWidth: rail - ? media.size.width - kNavigationRailSpace + ? media.size.width - navigationRailSpaceOf(context) : null, child: scaffold, ), diff --git a/app/lib/shell/navigation_rail.dart b/app/lib/shell/navigation_rail.dart index 376378f6..4a71abec 100644 --- a/app/lib/shell/navigation_rail.dart +++ b/app/lib/shell/navigation_rail.dart @@ -10,6 +10,15 @@ const double kNavigationRailWidth = 96; /// The rail with its divider: what the rail takes from a wide window's width. const double kNavigationRailSpace = kNavigationRailWidth + 1; +/// The rail's width under the design at [context]: [kNavigationRailWidth], +/// or a dense design's narrower, icon-only rail. +double navigationRailWidthOf(BuildContext context) => + AppDesignTokens.of(context).density.railWidth; + +/// The rail with its divider under the design at [context]. +double navigationRailSpaceOf(BuildContext context) => + navigationRailWidthOf(context) + 1; + /// The narrowest window that shows the destination rail: the list-detail /// minimum for the body beside it, plus the rail and its divider (the space the /// shell takes from the window). Narrower windows keep the floating destination @@ -66,6 +75,7 @@ class ShellNavigationRail extends StatelessWidget { Widget build(BuildContext context) { final index = shellTabDestinations.indexOf(selected); final surface = Theme.of(context).colorScheme.surface; + final density = AppDesignTokens.of(context).density; // The surface runs under the top inset too: the padding only moves the // rail's content below the system's top, so no unpainted strip shows above // the rail's background. @@ -75,11 +85,12 @@ class ShellNavigationRail extends StatelessWidget { child: Padding( padding: padding, child: SizedBox( - width: kNavigationRailWidth, + width: density.railWidth, child: LayoutBuilder( builder: (context, constraints) => _rail( index, surface, + density, pinSettings: constraints.maxHeight >= kNavigationRailPinnedSettingsMinHeight, @@ -90,39 +101,46 @@ class ShellNavigationRail extends StatelessWidget { ); } - Widget _rail(int index, Color surface, {required bool pinSettings}) => - NavigationRail( - key: const ValueKey('shell.navigation-rail'), - backgroundColor: surface, - minWidth: kNavigationRailWidth, - labelType: NavigationRailLabelType.all, - selectedIndex: index < 0 ? null : index, - onDestinationSelected: (value) => - onSelected(shellTabDestinations[value]), - destinations: [ - for (final destination in shellTabDestinations) - NavigationRailDestination( - icon: KeyedSubtree( - key: ValueKey('shell.destination.${destination.name}'), - // The bar it replaces named each tab in a tooltip too. - // The destination's label already names it for assistive - // technology; the tooltip must not repeat it. - child: Tooltip( - message: destinationDetails(destination).label, - excludeFromSemantics: true, - child: icon(destination), - ), - ), - label: Text(destinationDetails(destination).label), + Widget _rail( + int index, + Color surface, + DesignDensity density, { + required bool pinSettings, + }) => NavigationRail( + key: const ValueKey('shell.navigation-rail'), + backgroundColor: surface, + minWidth: density.railWidth, + // An icon-only rail names each tab in its tooltip alone. + labelType: density.railLabels + ? NavigationRailLabelType.all + : NavigationRailLabelType.none, + selectedIndex: index < 0 ? null : index, + onDestinationSelected: (value) => onSelected(shellTabDestinations[value]), + destinations: [ + for (final destination in shellTabDestinations) + NavigationRailDestination( + icon: KeyedSubtree( + key: ValueKey('shell.destination.${destination.name}'), + // The bar it replaces named each tab in a tooltip too. + // The destination's label already names it for assistive + // technology; the tooltip must not repeat it. + child: Tooltip( + message: destinationDetails(destination).label, + excludeFromSemantics: true, + child: icon(destination), ), - ], - scrollable: true, - trailingAtBottom: pinSettings, - trailing: _SettingsRailItem( - selected: selected == AppDestination.settings, - onTap: () => onSelected(AppDestination.settings), + ), + label: Text(destinationDetails(destination).label), ), - ); + ], + scrollable: true, + trailingAtBottom: pinSettings, + trailing: _SettingsRailItem( + density: density, + selected: selected == AppDestination.settings, + onTap: () => onSelected(AppDestination.settings), + ), + ); } /// Settings at the rail's foot, drawn as a [NavigationRailDestination] is: an @@ -130,8 +148,13 @@ class ShellNavigationRail extends StatelessWidget { /// It is not a [NavigationRailDestination] itself because the rail's /// destination list is the tabs, and `trailing` is what the rail pins. class _SettingsRailItem extends StatelessWidget { - const _SettingsRailItem({required this.selected, required this.onTap}); + const _SettingsRailItem({ + required this.density, + required this.selected, + required this.onTap, + }); + final DesignDensity density; final bool selected; final VoidCallback onTap; @@ -146,6 +169,33 @@ class _SettingsRailItem extends StatelessWidget { color: foreground, fontWeight: selected ? FontWeight.w600 : FontWeight.w500, ); + final indicator = Container( + width: 56, + height: 32, + alignment: Alignment.center, + decoration: ShapeDecoration( + shape: AppDesignTokens.of(context).shape(const StadiumBorder()), + color: selected ? scheme.secondaryContainer : null, + ), + child: Icon(item.icon, color: foreground), + ); + final Widget mark = density.railLabels + ? Column( + mainAxisSize: MainAxisSize.min, + children: [ + indicator, + const SizedBox(height: 4), + Text(item.label, style: textStyle), + ], + ) + // An icon-only rail names Settings in a tooltip, as its tabs. + : Center( + child: Tooltip( + message: item.label, + excludeFromSemantics: true, + child: indicator, + ), + ); return Semantics( button: true, selected: selected, @@ -155,28 +205,10 @@ class _SettingsRailItem extends StatelessWidget { key: const ValueKey('shell.destination.settings'), onTap: onTap, child: SizedBox( - width: kNavigationRailWidth, + width: density.railWidth, child: Padding( - padding: const EdgeInsets.symmetric(vertical: 12), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - width: 56, - height: 32, - alignment: Alignment.center, - decoration: ShapeDecoration( - shape: AppDesignTokens.of( - context, - ).shape(const StadiumBorder()), - color: selected ? scheme.secondaryContainer : null, - ), - child: Icon(item.icon, color: foreground), - ), - const SizedBox(height: 4), - Text(item.label, style: textStyle), - ], - ), + padding: EdgeInsets.symmetric(vertical: density.space(12)), + child: mark, ), ), ), diff --git a/app/lib/shell/windows/window_frame.dart b/app/lib/shell/windows/window_frame.dart index 74a5f9de..dd82247d 100644 --- a/app/lib/shell/windows/window_frame.dart +++ b/app/lib/shell/windows/window_frame.dart @@ -1,14 +1,25 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import '../../ui/theme/app_design_tokens.dart'; import 'window_kind.dart'; const double windowCornerRadius = 12; +/// A floating window's corners under the design at [context]: +/// [windowCornerRadius], or a dense design's own corners. +BorderRadius windowCorners(BuildContext context) => AppDesignTokens.of( + context, +).denseCorners(const BorderRadius.all(Radius.circular(windowCornerRadius))); + /// The height of a window's title bar: a compact row of icon buttons, taller -/// with larger text. -double windowTitleBarHeight(BuildContext context) => - MediaQuery.textScalerOf(context).scale(40).clamp(40.0, 64.0); +/// with larger text (a dense design's slimmer bar grows the same way). +double windowTitleBarHeight(BuildContext context) { + final height = AppDesignTokens.of(context).density.titleBarHeight; + return MediaQuery.textScalerOf( + context, + ).scale(height).clamp(height, height + 24); +} /// A floating window's card and title bar: the title (drag to move, double /// click to maximise), the kind's actions, then Maximise and the X. The X @@ -45,10 +56,11 @@ class WindowFrame extends StatelessWidget { Widget build(BuildContext context) { final theme = Theme.of(context); final colors = theme.colorScheme; + final dense = AppDesignTokens.of(context).density.dense; return Material( elevation: 8, clipBehavior: Clip.antiAlias, - borderRadius: BorderRadius.circular(windowCornerRadius), + borderRadius: windowCorners(context), color: colors.surfaceContainer, child: Align( alignment: Alignment.topCenter, @@ -63,7 +75,7 @@ class WindowFrame extends StatelessWidget { ), child: Row( children: [ - Expanded(child: _title(theme)), + Expanded(child: _title(theme, dense)), for (final action in actions) IconButton( tooltip: action.label, @@ -91,7 +103,7 @@ class WindowFrame extends StatelessWidget { ); } - Widget _title(ThemeData theme) => MouseRegion( + Widget _title(ThemeData theme, bool dense) => MouseRegion( cursor: maximized ? SystemMouseCursors.basic : SystemMouseCursors.move, child: GestureDetector( key: const ValueKey('window-title'), @@ -104,11 +116,15 @@ class WindowFrame extends StatelessWidget { onPanEnd: maximized ? null : (_) => onMoveEnd(), onDoubleTap: onToggleMaximized, child: Padding( - padding: const EdgeInsetsDirectional.only(start: 12, end: 8), + padding: EdgeInsetsDirectional.only(start: dense ? 8 : 12, end: 8), child: Row( children: [ - Icon(icon, size: 18, color: theme.colorScheme.onSurfaceVariant), - const SizedBox(width: 8), + Icon( + icon, + size: dense ? 16 : 18, + color: theme.colorScheme.onSurfaceVariant, + ), + SizedBox(width: dense ? 6 : 8), Expanded( child: Text( title, @@ -137,7 +153,7 @@ class WindowOutline extends StatelessWidget { child: DecoratedBox( decoration: BoxDecoration( border: Border.all(color: colors.outlineVariant), - borderRadius: BorderRadius.circular(windowCornerRadius), + borderRadius: windowCorners(context), ), child: const SizedBox.expand(), ), diff --git a/app/lib/shell/windows/window_host.dart b/app/lib/shell/windows/window_host.dart index 682d9b4b..e48b33e9 100644 --- a/app/lib/shell/windows/window_host.dart +++ b/app/lib/shell/windows/window_host.dart @@ -133,7 +133,7 @@ class _WindowHostState extends State { // right, so they never sit under the rail. // The shell takes the rail and its divider (kNavigationRailSpace). final leading = widget.reservesRail && showsNavigationRail(context) - ? kNavigationRailSpace + ? navigationRailSpaceOf(context) : 0.0; final bounds = Size( constraints.maxWidth - leading, diff --git a/app/lib/shell/windows/window_navigator.dart b/app/lib/shell/windows/window_navigator.dart index f395517d..7a920ec0 100644 --- a/app/lib/shell/windows/window_navigator.dart +++ b/app/lib/shell/windows/window_navigator.dart @@ -2,11 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'window_frame.dart' - show - WindowOutline, - WindowResizeGrip, - windowCornerRadius, - windowTitleBarHeight; + show WindowOutline, WindowResizeGrip, windowCorners, windowTitleBarHeight; import 'window_scope.dart'; /// A floating window's own page stack. Pages pushed from the window's @@ -122,15 +118,15 @@ class WindowPageBox extends StatelessWidget { Widget build(BuildContext context) { final body = WindowBodyScope.maybeOf(context); if (body == null) return child; - const radius = Radius.circular(windowCornerRadius); + final corners = windowCorners(context); return Stack( children: [ Positioned.fromRect( rect: body, child: ClipRRect( - borderRadius: const BorderRadius.only( - bottomLeft: radius, - bottomRight: radius, + borderRadius: BorderRadius.only( + bottomLeft: corners.bottomLeft, + bottomRight: corners.bottomRight, ), child: MediaQuery( data: MediaQuery.of(context).copyWith( diff --git a/app/lib/ui/adaptive/segmented_bar.dart b/app/lib/ui/adaptive/segmented_bar.dart index 82742723..f3bedde0 100644 --- a/app/lib/ui/adaptive/segmented_bar.dart +++ b/app/lib/ui/adaptive/segmented_bar.dart @@ -423,7 +423,9 @@ class _SegmentedBarState extends State { titleShare ?? (widget.separateActionIslands ? .10 : SegmentedBar.minTitleShare); final besideTitle = - width - (leading == null ? 0 : segmentedPieceHeight() + 8) - 8; + width - + (leading == null ? 0 : segmentedPieceHeight(context) + 8) - + 8; // Actions that cannot move (a model picker) may take the room down // to the title's minimum share; the rest leave for the More menu // before the title goes under its own width. diff --git a/app/lib/ui/adaptive/segmented_bar_pieces.dart b/app/lib/ui/adaptive/segmented_bar_pieces.dart index 9e6952af..939e1dcd 100644 --- a/app/lib/ui/adaptive/segmented_bar_pieces.dart +++ b/app/lib/ui/adaptive/segmented_bar_pieces.dart @@ -1,11 +1,17 @@ import 'package:flutter/material.dart'; +import '../theme/app_design_tokens.dart'; import 'glass_pill.dart'; import 'segmented_bar_motion.dart'; /// The smallest height of every piece of a [SegmentedBar]: the platform's -/// minimum touch target, so a round Back is a circle. -double segmentedPieceHeight() => kMinInteractiveDimension; +/// minimum touch target, so a round Back is a circle. Under a dense design +/// at [context] the pieces are 40px: its 32px controls with a 4px edge, still +/// a comfortable touch target. +double segmentedPieceHeight([BuildContext? context]) => + context != null && AppDesignTokens.of(context).density.dense + ? 40 + : kMinInteractiveDimension; /// One rounded piece of a segmented bar: a [GlassPill] at least the /// platform's touch-target size. @@ -19,7 +25,7 @@ class SegmentedPill extends StatelessWidget { @override Widget build(BuildContext context) { - final height = segmentedPieceHeight(); + final height = segmentedPieceHeight(context); // A stadium whose content is as wide as it is tall is a circle. return GlassPill( fill: fill, @@ -75,6 +81,10 @@ Widget? impliedSegmentedLeading(BuildContext context) { /// The title pill's horizontal padding on each side. const double segmentedTitlePadding = 16; +/// [segmentedTitlePadding] under the design at [context] (12px when dense). +double segmentedTitlePaddingOf(BuildContext context) => + AppDesignTokens.of(context).density.inset(segmentedTitlePadding); + /// The width the title pill needs to show [title] and [subtitle] whole (at /// the text scale at [context]). double segmentedTitleWidth( @@ -113,7 +123,7 @@ double segmentedTitleWidth( measure(' ', subtitleStyle)); final text = measure(title, titleStyle); return (text > subWidth ? text : subWidth).ceilToDouble() + - segmentedTitlePadding * 2; + segmentedTitlePaddingOf(context) * 2; } /// The title, with an optional one-line subtitle, in one pill; pressing it @@ -156,8 +166,8 @@ class SegmentedTitlePill extends StatelessWidget { ); final subtitle = this.subtitle ?? ''; final content = Padding( - padding: const EdgeInsets.symmetric( - horizontal: segmentedTitlePadding, + padding: EdgeInsets.symmetric( + horizontal: segmentedTitlePaddingOf(context), vertical: 4, ), child: Row( diff --git a/app/lib/ui/input/app_search_field.dart b/app/lib/ui/input/app_search_field.dart index 8755d70e..7a714192 100644 --- a/app/lib/ui/input/app_search_field.dart +++ b/app/lib/ui/input/app_search_field.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import '../theme/app_design_tokens.dart'; /// The app's one search field. /// @@ -53,8 +54,10 @@ class AppSearchField extends StatelessWidget { @override Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; - const radius = BorderRadius.all(Radius.circular(28)); - const stadium = OutlineInputBorder( + final radius = AppDesignTokens.of( + context, + ).denseCorners(const BorderRadius.all(Radius.circular(28))); + final stadium = OutlineInputBorder( borderRadius: radius, borderSide: BorderSide.none, ); diff --git a/app/lib/ui/layout/app_list_avatar.dart b/app/lib/ui/layout/app_list_avatar.dart index e24474df..9cf4189e 100644 --- a/app/lib/ui/layout/app_list_avatar.dart +++ b/app/lib/ui/layout/app_list_avatar.dart @@ -5,6 +5,11 @@ import '../theme/app_design_tokens.dart'; /// avatar ([CircleAvatar]'s default). const double kAppListAvatarSize = 40; +/// The leading avatar's size under the design at [context]: +/// [kAppListAvatarSize], or a dense design's smaller one. +double appListAvatarSize(BuildContext context) => + AppDesignTokens.of(context).density.avatarSize; + /// A list row's leading identity: an icon or an initial on a tinted circle, /// with an optional corner badge (a chat's activity indicator). /// @@ -52,16 +57,19 @@ class AppListAvatar extends StatelessWidget { (foreground == null ? Theme.of(context).colorScheme.surfaceContainerHighest : mark.withValues(alpha: 0.14)); + // The mark keeps the same proportion of the circle at every density. + final tokens = AppDesignTokens.of(context); + final size = tokens.density.avatarSize; + final scale = size / kAppListAvatarSize; final initialStyle = (Theme.of(context).textTheme.titleMedium ?? const TextStyle()).copyWith( color: mark, - fontSize: 18, + fontSize: 18 * scale, fontWeight: FontWeight.w700, height: 1, ); // A flat design (Terminal) frames the mark in a square box instead of a // tinted circle. - final tokens = AppDesignTokens.of(context); final decoration = tokens.flat ? BoxDecoration( border: Border.all(color: mark.withValues(alpha: 0.55)), @@ -69,18 +77,18 @@ class AppListAvatar extends StatelessWidget { ) : BoxDecoration(color: fill, shape: BoxShape.circle); final circle = SizedBox.square( - dimension: kAppListAvatarSize, + dimension: size, child: DecoratedBox( decoration: decoration, child: Center( // The glyph is identity, not reading text: it scales down to stay // inside the circle under large text instead of overflowing it. child: Padding( - padding: const EdgeInsets.all(8), + padding: EdgeInsets.all(8 * scale), child: FittedBox( fit: BoxFit.scaleDown, child: IconTheme.merge( - data: IconThemeData(color: mark, size: 22), + data: IconThemeData(color: mark, size: 22 * scale), child: DefaultTextStyle(style: initialStyle, child: child), ), ), diff --git a/app/lib/ui/layout/app_list_row.dart b/app/lib/ui/layout/app_list_row.dart index 3dfadb1a..3798bef7 100644 --- a/app/lib/ui/layout/app_list_row.dart +++ b/app/lib/ui/layout/app_list_row.dart @@ -156,6 +156,7 @@ class AppListRow extends StatelessWidget { selected: selected, emphasized: emphasized, ); + final metrics = _RowMetrics.of(context); return Semantics( container: true, selected: selected, @@ -166,14 +167,16 @@ class AppListRow extends StatelessWidget { final minimal = constraints.maxWidth < kAppListRowMinimalWidth; final showLeading = leading != null && !minimal; final showMenu = menu != null && !minimal; - final start = compact ? 12.0 : kAppListRowInset; - final avatarGap = compact ? _compactAvatarGap : _avatarGap; + final start = compact ? metrics.compactInset : metrics.inset; + final avatarGap = compact + ? metrics.compactAvatarGap + : metrics.avatarGap; final content = Padding( padding: EdgeInsetsDirectional.only( start: start, - end: showMenu ? 4 : kAppListRowInset, - top: kAppListRowVerticalPadding, - bottom: kAppListRowVerticalPadding, + end: showMenu ? 4 : metrics.inset, + top: metrics.vertical, + bottom: metrics.vertical, ), child: Row( children: [ @@ -187,7 +190,7 @@ class AppListRow extends StatelessWidget { padding: EdgeInsetsDirectional.only(end: avatarGap), child: leading, ), - Expanded(child: _text(styles, compact)), + Expanded(child: _text(styles, metrics, compact)), if (showMenu) Padding( padding: const EdgeInsetsDirectional.only(start: 4), @@ -227,7 +230,12 @@ class AppListRow extends StatelessWidget { key: tapKey, onTap: onTap, onLongPress: onLongPress, - child: content, + child: metrics.minHeight > 0 + ? ConstrainedBox( + constraints: BoxConstraints(minHeight: metrics.minHeight), + child: Center(widthFactor: 1, child: content), + ) + : content, ), ); // The colour bar runs the row's whole height, divider included, and @@ -261,7 +269,7 @@ class AppListRow extends StatelessWidget { // not known here, so a selectable row's divider starts at the inset. final textStart = selectionControl != null ? start - : start + (showLeading ? kAppListAvatarSize + avatarGap : 0); + : start + (showLeading ? metrics.avatar + avatarGap : 0); final line = Padding( padding: EdgeInsetsDirectional.only(start: textStart), child: SizedBox( @@ -306,7 +314,7 @@ class AppListRow extends StatelessWidget { ); } - Widget _text(_RowStyles styles, bool compact) { + Widget _text(_RowStyles styles, _RowMetrics metrics, bool compact) { final line = compact ? (compactSubtitle ?? subtitle) : subtitle; final time = _time(styles); final titleLine = LayoutBuilder( @@ -339,7 +347,7 @@ class AppListRow extends StatelessWidget { final detailLine = detail == null || (compact && !compactDetail) ? null : Padding( - padding: const EdgeInsets.only(top: _lineGap), + padding: EdgeInsets.only(top: metrics.lineGap), child: DefaultTextStyle( style: styles.subtitle, maxLines: 1, @@ -354,7 +362,7 @@ class AppListRow extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ titleLine, - const SizedBox(height: _lineGap), + SizedBox(height: metrics.lineGap), timeLine, ], ); @@ -364,7 +372,7 @@ class AppListRow extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ titleLine, - const SizedBox(height: _lineGap), + SizedBox(height: metrics.lineGap), Row( children: [ if (subtitleLeading != null) @@ -394,6 +402,57 @@ class AppListRow extends StatelessWidget { } } +/// The row's spacing under the design's density: the comfortable constants, +/// or a dense design's tighter ones (a 36px single-line row and a ~52px +/// two-line row on a pointer device; at least 40px on touch). +class _RowMetrics { + const _RowMetrics({ + required this.inset, + required this.compactInset, + required this.avatarGap, + required this.compactAvatarGap, + required this.vertical, + required this.lineGap, + required this.avatar, + required this.minHeight, + }); + + factory _RowMetrics.of(BuildContext context) { + final density = AppDesignTokens.of(context).density; + if (!density.dense) return _comfortable; + return _RowMetrics( + inset: density.inset(kAppListRowInset), + compactInset: density.inset(12), + avatarGap: density.space(_avatarGap), + compactAvatarGap: density.space(_compactAvatarGap), + vertical: density.space(kAppListRowVerticalPadding), + lineGap: 0, + avatar: density.avatarSize, + minHeight: density.minTouchRow, + ); + } + + static const _comfortable = _RowMetrics( + inset: kAppListRowInset, + compactInset: 12, + avatarGap: _avatarGap, + compactAvatarGap: _compactAvatarGap, + vertical: kAppListRowVerticalPadding, + lineGap: _lineGap, + avatar: kAppListAvatarSize, + minHeight: 0, + ); + + final double inset; + final double compactInset; + final double avatarGap; + final double compactAvatarGap; + final double vertical; + final double lineGap; + final double avatar; + final double minHeight; +} + /// The row's text styles, from the host's own type scale. class _RowStyles { const _RowStyles(this.title, this.subtitle, this.time, this.divider); diff --git a/app/lib/ui/theme/app_design.dart b/app/lib/ui/theme/app_design.dart index 99494e51..a1f850e1 100644 --- a/app/lib/ui/theme/app_design.dart +++ b/app/lib/ui/theme/app_design.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'app_design_tokens.dart'; import 'app_theme.dart'; +import 'compact_theme.dart'; import 'paper_theme.dart'; import 'terminal_theme.dart'; @@ -49,6 +50,14 @@ enum AppDesign { 'paper', 'Paper', 'Warm paper, serif reading text and ink colours; calm for long reads.', + ), + + /// The Classic look packed tight for a big monitor: smaller type, thin + /// rows, 18px icons, an icon-only rail and modest corners. + compact( + 'compact', + 'Compact', + 'Classic’s Material look, dense: small type, thin rows, more on screen.', ); const AppDesign(this.id, this.label, this.description); @@ -100,8 +109,15 @@ enum AppDesign { (standard, Brightness.dark) => appDarkTheme(fontFamily: fontFamily), (terminal, _) => terminalTheme(brightness), (paper, _) => paperTheme(brightness, fontFamily: fontFamily), + (compact, _) => compactTheme(brightness, fontFamily: fontFamily), }; + /// Whether this design packs the interface densely + /// ([DesignDensity.dense]); its theme hosts switch to and from it without + /// a blend ([AppDesignController.themeAnimationDuration]). + bool get dense => + light().extension()?.density.dense ?? false; + /// Whether the device's interface font applies under this design (Paper /// keeps it for its interface text and sets reading text in its serif). bool get usesInterfaceFont => this != terminal; @@ -111,7 +127,7 @@ enum AppDesign { DesignSwatch swatch(Brightness brightness) { final dark = brightness == Brightness.dark; return switch (this) { - standard => + standard || compact => dark ? const DesignSwatch( Color(0xFF141416), @@ -149,6 +165,10 @@ enum AppDesign { ), }; } + + /// How many lines of ink the picker's preview draws: Compact's packs more + /// into the same page. + int get swatchLines => this == compact ? 4 : 2; } /// A design's three defining colours, for the picker's small preview. diff --git a/app/lib/ui/theme/app_design_controller.dart b/app/lib/ui/theme/app_design_controller.dart index 0dc9ed66..f0b38892 100644 --- a/app/lib/ui/theme/app_design_controller.dart +++ b/app/lib/ui/theme/app_design_controller.dart @@ -1,4 +1,5 @@ import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart' show kThemeAnimationDuration; import 'package:shared_preferences/shared_preferences.dart'; import 'app_design.dart'; @@ -87,7 +88,24 @@ class AppDesignController extends ChangeNotifier { void preview(AppDesign? design) { final shown = this.design; _preview = design; - if (this.design != shown) notifyListeners(); + if (this.design != shown) _shown(shown); + } + + /// How long the theme hosts blend into the current design (their + /// `themeAnimationDuration`): Material's blend between designs of the same + /// density, none for a switch into or out of a dense design. A dense + /// design's sizes (icons, controls) have no value in a comfortable theme to + /// blend from, so a blend would pass every icon through size zero, and in + /// the browser (skwasm) laying out the near-zero icon glyphs could hang. + Duration get themeAnimationDuration => + _snapTheme ? Duration.zero : kThemeAnimationDuration; + bool _snapTheme = false; + + /// The shown design changed from [before]: decide the hosts' blend and + /// tell them. + void _shown(AppDesign before) { + _snapTheme = before.dense || design.dense; + notifyListeners(); } /// The last choice could not be stored on this device. @@ -100,8 +118,9 @@ class AppDesignController extends ChangeNotifier { if (revision != _revision || id == null) return; final design = AppDesign.fromId(id); if (design == _design) return; + final shown = this.design; _design = design; - if (_preview == null) notifyListeners(); + if (_preview == null) _shown(shown); } /// Applies [design] now and stores it. @@ -111,7 +130,7 @@ class AppDesignController extends ChangeNotifier { final shown = this.design; _preview = null; _design = design; - if (design != shown) notifyListeners(); + if (design != shown) _shown(shown); final saved = await _store.save(design.id); if (revision != _revision || saved != _saveFailed) return; _saveFailed = !saved; diff --git a/app/lib/ui/theme/app_design_styles.dart b/app/lib/ui/theme/app_design_styles.dart index ff36b944..e5ccbfbc 100644 --- a/app/lib/ui/theme/app_design_styles.dart +++ b/app/lib/ui/theme/app_design_styles.dart @@ -1,6 +1,8 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; +export 'design_density.dart'; + /// How the chat transcript draws a conversation. Each design picks one; the /// transcript widgets branch on it, never on the design itself. enum TranscriptStyle { @@ -54,6 +56,7 @@ class ReadingType { this.measure, this.scale = 1, this.figureWidth = 0.5, + this.paragraphGap = 0.9, }); /// The reading face; null keeps the theme's body face. @@ -73,6 +76,10 @@ class ReadingType { /// [measure] is worth (half an em for Source Serif's figures). final double figureWidth; + /// The gap between two paragraphs of an answer, in lines of reading text + /// (before text scaling): about a line by default, less for a dense design. + final double paragraphGap; + /// [base] in the reading face, size and line height. TextStyle? apply(TextStyle? base) { if (base == null) return null; @@ -98,8 +105,10 @@ class ReadingType { other.height == height && other.measure == measure && other.scale == scale && - other.figureWidth == figureWidth; + other.figureWidth == figureWidth && + other.paragraphGap == paragraphGap; @override - int get hashCode => Object.hash(family, height, measure, scale, figureWidth); + int get hashCode => + Object.hash(family, height, measure, scale, figureWidth, paragraphGap); } diff --git a/app/lib/ui/theme/app_design_tokens.dart b/app/lib/ui/theme/app_design_tokens.dart index 349fc00b..fdbb7b41 100644 --- a/app/lib/ui/theme/app_design_tokens.dart +++ b/app/lib/ui/theme/app_design_tokens.dart @@ -65,6 +65,7 @@ class AppDesignTokens extends ThemeExtension { this.selectedRow = SelectedRowStyle.tonal, this.reading = const ReadingType(), this.chatColorSaturation = 1, + this.density = DesignDensity.comfortable, }); /// The Classic design: every widget keeps its own shapes. @@ -111,6 +112,10 @@ class AppDesignTokens extends ThemeExtension { /// palette as is, lower to quieten it towards ink. final double chatColorSaturation; + /// How tightly the interface is packed: spacing, icon and avatar sizes, + /// the rail and the window title bar ([DesignDensity.compact] for Compact). + final DesignDensity density; + /// Whether the transcript draws prompt and tool lines rather than bubbles. bool get terminal => transcript == TranscriptStyle.prompt; @@ -132,6 +137,12 @@ class AppDesignTokens extends ThemeExtension { return r == null ? designed : BorderRadius.circular(r); } + /// [designed] corners, or [radius] corners under a dense design: for the + /// surfaces whose own corners the comfortable designs keep (floating + /// windows, search thumbnails), so only a dense design rounds them alike. + BorderRadius denseCorners(BorderRadius designed) => + density.dense ? corners(designed) : designed; + /// [designed] (a widget's own fill) or, under a flat design, its [panel]. Color panelFill(ColorScheme scheme, Color designed) => flat ? panel ?? scheme.surfaceContainerLow : designed; @@ -156,6 +167,7 @@ class AppDesignTokens extends ThemeExtension { SelectedRowStyle? selectedRow, ReadingType? reading, double? chatColorSaturation, + DesignDensity? density, }) => AppDesignTokens( design: design ?? this.design, radius: radius ?? this.radius, @@ -169,6 +181,7 @@ class AppDesignTokens extends ThemeExtension { selectedRow: selectedRow ?? this.selectedRow, reading: reading ?? this.reading, chatColorSaturation: chatColorSaturation ?? this.chatColorSaturation, + density: density ?? this.density, ); // Value equality keeps a rebuilt theme equal to the one it replaces, so @@ -188,7 +201,8 @@ class AppDesignTokens extends ThemeExtension { other.composer == composer && other.selectedRow == selectedRow && other.reading == reading && - other.chatColorSaturation == chatColorSaturation; + other.chatColorSaturation == chatColorSaturation && + other.density == density; @override int get hashCode => Object.hash( @@ -204,6 +218,7 @@ class AppDesignTokens extends ThemeExtension { selectedRow, reading, chatColorSaturation, + density, ); /// Designs switch whole: a theme animation snaps halfway rather than diff --git a/app/lib/ui/theme/compact_controls.dart b/app/lib/ui/theme/compact_controls.dart new file mode 100644 index 00000000..47cc1121 --- /dev/null +++ b/app/lib/ui/theme/compact_controls.dart @@ -0,0 +1,197 @@ +import 'package:flutter/material.dart'; + +import 'compact_theme.dart'; + +const BorderRadius _corners = BorderRadius.all(Radius.circular(compactRadius)); +const RoundedRectangleBorder _rounded = RoundedRectangleBorder( + borderRadius: _corners, +); + +/// [base] with Compact's controls: Default's Material components at dense +/// heights, in [compactRadius] corners, with 4px-grid paddings. Their text +/// keeps each component's own Material role (already at Compact's sizes): +/// a component theme that sets a text-theme style cannot be lerped against +/// Default's unset one, which breaks a live design switch. Floating +/// surfaces (menus, dialogs, sheets, tooltips, snack bars) keep Material's +/// elevation and fills; only their corners and insets change. +ThemeData compactControls(ThemeData base) { + final scheme = base.colorScheme; + const icon = 18.0; + // Buttons: 32px tall under compact density, 12px side padding, 18px icons. + ButtonStyle buttons() => const ButtonStyle( + shape: WidgetStatePropertyAll(_rounded), + padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 12)), + iconSize: WidgetStatePropertyAll(icon), + ); + final menu = MenuStyle( + shape: const WidgetStatePropertyAll(_rounded), + padding: const WidgetStatePropertyAll(EdgeInsets.symmetric(vertical: 4)), + visualDensity: VisualDensity.compact, + ); + return base.copyWith( + filledButtonTheme: FilledButtonThemeData(style: buttons()), + elevatedButtonTheme: ElevatedButtonThemeData(style: buttons()), + outlinedButtonTheme: OutlinedButtonThemeData(style: buttons()), + textButtonTheme: TextButtonThemeData( + style: buttons().copyWith( + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 8), + ), + ), + ), + // Material 3's icon button ignores the theme's density unless its own + // style sets one: 32px drawn, its target padded to 40px on touch. + iconButtonTheme: const IconButtonThemeData( + style: ButtonStyle( + visualDensity: VisualDensity.compact, + iconSize: WidgetStatePropertyAll(icon), + // A square 32px button around its 18px icon. + padding: WidgetStatePropertyAll(EdgeInsets.all(7)), + shape: WidgetStatePropertyAll(_rounded), + ), + ), + segmentedButtonTheme: SegmentedButtonThemeData( + style: buttons().copyWith(visualDensity: VisualDensity.compact), + ), + // A 40px action (Material's small FAB) and a 40px extended one. + floatingActionButtonTheme: FloatingActionButtonThemeData( + shape: _rounded, + iconSize: icon, + sizeConstraints: const BoxConstraints.tightFor(width: 40, height: 40), + // Only a least height: a larger text scale still grows the label. + extendedSizeConstraints: const BoxConstraints( + minHeight: 40, + minWidth: 64, + ), + extendedPadding: const EdgeInsetsDirectional.only(start: 12, end: 16), + extendedIconLabelSpacing: 8, + ), + menuTheme: MenuThemeData(style: menu), + dropdownMenuTheme: DropdownMenuThemeData( + menuStyle: menu, + inputDecorationTheme: const InputDecorationTheme(isDense: true), + ), + menuButtonTheme: MenuButtonThemeData( + style: MenuItemButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 12), + minimumSize: const Size(0, 32), + iconSize: icon, + ), + ), + popupMenuTheme: PopupMenuThemeData( + shape: _rounded, + menuPadding: const EdgeInsets.symmetric(vertical: 4), + ), + dialogTheme: DialogThemeData( + shape: _rounded, + insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), + actionsPadding: const EdgeInsets.fromLTRB(16, 0, 16, 12), + ), + bottomSheetTheme: const BottomSheetThemeData( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.vertical( + top: Radius.circular(compactRadius), + ), + ), + ), + snackBarTheme: SnackBarThemeData( + shape: _rounded, + insetPadding: const EdgeInsets.fromLTRB(12, 4, 12, 12), + ), + tooltipTheme: TooltipThemeData( + decoration: BoxDecoration( + color: scheme.inverseSurface, + borderRadius: _corners, + ), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + waitDuration: const Duration(milliseconds: 400), + ), + // A hairline on every card variant: the theme's shape replaces each + // variant's own, so an outlined card (a graph node) keeps its outline. + cardTheme: CardThemeData( + shape: RoundedRectangleBorder( + borderRadius: _corners, + side: BorderSide(color: scheme.outlineVariant), + ), + margin: const EdgeInsets.all(4), + ), + chipTheme: ChipThemeData( + shape: _rounded, + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + labelPadding: const EdgeInsets.symmetric(horizontal: 4), + iconTheme: const IconThemeData(size: 16), + ), + inputDecorationTheme: const InputDecorationTheme( + isDense: true, + contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + searchBarTheme: SearchBarThemeData( + shape: const WidgetStatePropertyAll(_rounded), + constraints: const BoxConstraints(minWidth: 240, minHeight: 36), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 12), + ), + ), + listTileTheme: const ListTileThemeData( + dense: true, + visualDensity: VisualDensity.compact, + contentPadding: EdgeInsets.symmetric(horizontal: 12), + horizontalTitleGap: 12, + minLeadingWidth: 20, + minVerticalPadding: 6, + shape: _rounded, + ), + expansionTileTheme: const ExpansionTileThemeData( + tilePadding: EdgeInsets.symmetric(horizontal: 12), + childrenPadding: EdgeInsets.symmetric(horizontal: 12), + shape: Border(), + collapsedShape: Border(), + ), + navigationRailTheme: NavigationRailThemeData( + minWidth: 64, + labelType: NavigationRailLabelType.none, + indicatorShape: _rounded, + indicatorColor: scheme.secondaryContainer, + selectedIconTheme: IconThemeData( + size: icon, + color: scheme.onSecondaryContainer, + ), + unselectedIconTheme: IconThemeData( + size: icon, + color: scheme.onSurfaceVariant, + ), + groupAlignment: -1, + ), + navigationBarTheme: NavigationBarThemeData( + height: 64, + indicatorShape: _rounded, + iconTheme: const WidgetStatePropertyAll(IconThemeData(size: icon)), + ), + tabBarTheme: TabBarThemeData( + labelPadding: const EdgeInsets.symmetric(horizontal: 12), + ), + dividerTheme: const DividerThemeData(space: 8, thickness: 1), + badgeTheme: BadgeThemeData( + smallSize: 6, + largeSize: 14, + padding: const EdgeInsets.symmetric(horizontal: 4), + ), + checkboxTheme: const CheckboxThemeData( + visualDensity: VisualDensity.compact, + ), + radioTheme: const RadioThemeData(visualDensity: VisualDensity.compact), + scrollbarTheme: const ScrollbarThemeData( + radius: Radius.circular(3), + thickness: WidgetStatePropertyAll(6), + ), + drawerTheme: const DrawerThemeData( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.horizontal( + right: Radius.circular(compactRadius), + ), + ), + ), + datePickerTheme: const DatePickerThemeData(shape: _rounded), + timePickerTheme: const TimePickerThemeData(shape: _rounded), + ); +} diff --git a/app/lib/ui/theme/compact_theme.dart b/app/lib/ui/theme/compact_theme.dart new file mode 100644 index 00000000..1771db87 --- /dev/null +++ b/app/lib/ui/theme/compact_theme.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; + +import 'app_design.dart'; +import 'app_design_tokens.dart'; +import 'app_theme.dart'; +import 'compact_controls.dart'; +import 'compact_typography.dart'; + +/// Compact's corner radius: every card, field, button, chip, menu, dialog, +/// sheet, tooltip, snack bar, bubble and window takes it. +const double compactRadius = 6; + +/// The Compact design's theme: Default's Material 3 colours and surfaces, +/// packed for a big monitor and long runs and chats. A smaller type scale +/// ([compactTextTheme]), Material's compact visual density, 18px icons, and +/// [compactRadius] corners on every surface. On a touch device controls keep +/// a 40px tap target (Material's padded target under compact density); on a +/// pointer device they shrink to their drawn size. +ThemeData compactTheme(Brightness brightness, {String? fontFamily}) { + final standard = brightness == Brightness.dark + ? appDarkTheme(fontFamily: fontFamily) + : appLightTheme(fontFamily: fontFamily); + final textTheme = compactTextTheme(standard.textTheme); + final themed = standard.copyWith( + visualDensity: VisualDensity.compact, + materialTapTargetSize: DesignDensity.pointerPlatform + ? MaterialTapTargetSize.shrinkWrap + : MaterialTapTargetSize.padded, + textTheme: textTheme, + primaryTextTheme: compactTextTheme(standard.primaryTextTheme), + iconTheme: standard.iconTheme.copyWith( + size: DesignDensity.compact.iconSize, + ), + primaryIconTheme: standard.primaryIconTheme.copyWith( + size: DesignDensity.compact.iconSize, + ), + extensions: const [ + AppDesignTokens( + design: AppDesign.compact, + radius: compactRadius, + reading: compactReading, + density: DesignDensity.compact, + ), + ], + ); + return compactControls(themed); +} diff --git a/app/lib/ui/theme/compact_typography.dart b/app/lib/ui/theme/compact_typography.dart new file mode 100644 index 00000000..d485f140 --- /dev/null +++ b/app/lib/ui/theme/compact_typography.dart @@ -0,0 +1,36 @@ +import 'package:flutter/material.dart'; + +import 'app_design_styles.dart'; + +/// Compact's reading type: the interface face at the dense body size +/// (`bodyLarge`, 14px), a little more line height than the role's so long +/// answers stay easy to follow, and about two thirds of a line between +/// paragraphs. +const ReadingType compactReading = ReadingType(height: 1.5, paragraphGap: 0.6); + +/// [base] (Material 3's type scale, in the device's interface face) at +/// Compact's sizes: body 13px, labels 11-12px, list and dialog titles 14 and +/// 18px. Line heights sit on a 2px step so rows of mixed roles still line up +/// on the 4px grid. Weights, colours, families and tracking stay Material's; +/// text scaling still applies on top. +TextTheme compactTextTheme(TextTheme base) { + TextStyle? sized(TextStyle? style, double size, double line) => + style?.copyWith(fontSize: size, height: line / size); + return base.copyWith( + displayLarge: sized(base.displayLarge, 44, 52), + displayMedium: sized(base.displayMedium, 36, 44), + displaySmall: sized(base.displaySmall, 28, 36), + headlineLarge: sized(base.headlineLarge, 26, 32), + headlineMedium: sized(base.headlineMedium, 22, 28), + headlineSmall: sized(base.headlineSmall, 20, 26), + titleLarge: sized(base.titleLarge, 18, 24), + titleMedium: sized(base.titleMedium, 14, 20), + titleSmall: sized(base.titleSmall, 13, 18), + bodyLarge: sized(base.bodyLarge, 14, 20), + bodyMedium: sized(base.bodyMedium, 13, 18), + bodySmall: sized(base.bodySmall, 11.5, 16), + labelLarge: sized(base.labelLarge, 13, 18), + labelMedium: sized(base.labelMedium, 12, 16), + labelSmall: sized(base.labelSmall, 11, 14), + ); +} diff --git a/app/lib/ui/theme/design_density.dart b/app/lib/ui/theme/design_density.dart new file mode 100644 index 00000000..3e978bb0 --- /dev/null +++ b/app/lib/ui/theme/design_density.dart @@ -0,0 +1,119 @@ +import 'package:flutter/foundation.dart'; + +/// How tightly a design packs the interface: the spacing inside and between +/// components, icon and avatar sizes, the navigation rail's width and labels +/// and the floating window title bar. [comfortable] is the Default look; +/// every widget that reads a density keeps its own value under it, so the +/// comfortable designs draw exactly as before. +/// +/// A dense design sets [spacing] below 1: [space] then scales a widget's own +/// spacing and snaps it to the 4px grid, so every component tightens by the +/// same proportion instead of each picking its own number. +@immutable +class DesignDensity { + const DesignDensity({ + this.spacing = 1, + this.iconSize, + this.avatarSize = 40, + this.railWidth = 96, + this.railLabels = true, + this.titleBarHeight = 40, + }); + + /// The Default density. + static const DesignDensity comfortable = DesignDensity(); + + /// The Compact density: spacing at 60% on the 4px grid, 18px icons, 28px + /// avatars, an icon-only 64px rail and a 32px window title bar. + static const DesignDensity compact = DesignDensity( + spacing: 0.6, + iconSize: 18, + avatarSize: 28, + railWidth: 64, + railLabels: false, + titleBarHeight: 32, + ); + + /// The proportion of a widget's own spacing this density keeps. + final double spacing; + + /// The interface's icon size; null keeps Material's 24. + final double? iconSize; + + /// A list row's leading avatar. + final double avatarSize; + + /// The destination rail's width on a wide window. + final double railWidth; + + /// Whether the rail labels its destinations under their icons; without + /// them the rail shows icons with tooltips. + final bool railLabels; + + /// A floating window's title bar height, before text scaling. + final double titleBarHeight; + + /// Whether this density is tighter than [comfortable]. + bool get dense => spacing < 1; + + /// [comfortable] spacing under this density: unchanged at [spacing] 1, + /// otherwise scaled and snapped to the 4px grid (a gap under 4px keeps a + /// 2px step, so a hairline gap never collapses to nothing). + double space(double comfortable) { + if (spacing == 1 || comfortable <= 0) return comfortable; + final scaled = comfortable * spacing; + if (scaled < 4) return scaled < 3 ? 2 : 4; + return (scaled / 4).round() * 4.0; + } + + /// [comfortable] edge inset (a row's or a panel's side padding) under this + /// density: halfway between [space] and the comfortable value, on the 4px + /// grid, so a dense row's text still keeps clear of the pane's edge + /// (16px becomes 12px at Compact). + double inset(double comfortable) { + if (spacing == 1 || comfortable <= 0) return comfortable; + final scaled = comfortable * (1 + spacing) / 2; + return scaled < 4 ? 4 : (scaled / 4).round() * 4.0; + } + + /// The least height a tappable row keeps under this density: nothing + /// beyond its content when comfortable (its own padding already gives + /// room) or on a pointer device, and 40px on a touch device, so a dense + /// row stays easy to hit with a finger. + double get minTouchRow { + if (!dense) return 0; + return pointerPlatform ? 0 : 40; + } + + /// Whether the device drives the app with a pointer (desktop, including a + /// desktop browser). Reads the device's platform, not the theme's: web + /// themes are pinned to Android. + static bool get pointerPlatform => switch (defaultTargetPlatform) { + TargetPlatform.macOS || + TargetPlatform.linux || + TargetPlatform.windows => true, + TargetPlatform.android || + TargetPlatform.iOS || + TargetPlatform.fuchsia => false, + }; + + @override + bool operator ==(Object other) => + other is DesignDensity && + other.spacing == spacing && + other.iconSize == iconSize && + other.avatarSize == avatarSize && + other.railWidth == railWidth && + other.railLabels == railLabels && + other.titleBarHeight == titleBarHeight; + + @override + int get hashCode => Object.hash( + spacing, + iconSize, + avatarSize, + railWidth, + railLabels, + titleBarHeight, + ); +} diff --git a/app/notes/chat-open-workspace-sync.md b/app/notes/chat-open-workspace-sync.md index cd21250a..b894a3bf 100644 --- a/app/notes/chat-open-workspace-sync.md +++ b/app/notes/chat-open-workspace-sync.md @@ -3,8 +3,12 @@ ## Behaviour The authenticated `/connect` protocol stores one bounded ordered open-chat set -per server scope (`default`). Entries hold only an operator session id and a -floating bit; split ratios, pane ids and window rectangles stay on the device. +per server scope (`default`). Entries hold only an operator session id, a +floating bit and an optional chat stack `group` name (entries sharing a name +form one group; trimmed, printable, at most 80 characters, refused otherwise; +older clients ignore it); split ratios, pane ids and window rectangles stay on +the device. The `group` field needs the server rebuilt and restarted: an +older server drops it. * `chat_open_workspace` without `chat_open_workspace_request` reads the set. With a request it replaces the set as a compare-and-swap on `base_revision`: diff --git a/app/notes/chat-pane-cycle.md b/app/notes/chat-pane-cycle.md new file mode 100644 index 00000000..88e660ff --- /dev/null +++ b/app/notes/chat-pane-cycle.md @@ -0,0 +1,53 @@ +# Cycling the chat panes on screen + +Alt+] and Alt+[ move the keyboard to the next or previous chat pane on screen +(wide layouts only). On macOS and iOS, Cmd+] and Cmd+[ do the same. + +## Keys + +- Alt+Tab and Cmd+Tab belong to the OS window switcher. Ctrl+Tab already + cycles the open chats, and Alt+` cycles the floating windows. + Alt+Y, Alt+K, Alt+L, Alt+T and Ctrl+B are also taken. +- Browsers use Alt+Left and Alt+Right for back and forward. GNOME, Hyprland, + Windows and browsers do not bind Alt+[ or Alt+]. The web build handles the + key, so Flutter calls `preventDefault`. The capture's keydown recorder shows + this (`prevented: true`). +- On a Mac, Option+] and Option+[ type quotes. With Alt, the shortcut matches + the key's position, as Option+Y does. Cmd+] and Cmd+[ are the macOS + next/previous pair, so Option stays free for typing. On the web, Cmd+[ is + Back, and the app prevents that default. +- The shortcut never matches with Shift (Alt+Shift+[ types a brace), Ctrl or + AltGr. AltGr is how several layouts type brackets. +- A focused terminal (any `TypingSurface`) keeps the keys. Alt+[ is its + escape prefix. + +## Behaviour + +- Order: the tiled panes in split-tree order, which is visual order (left + before right, top before bottom; the center stage's row in order). Then + come the shown floating chat windows in the order they were opened. The + cycle wraps around. The shortcut never opens, closes, hides or moves a + chat. +- The target's composer takes focus. If nothing in the pane takes focus, a + pane-level focus node takes it. The pane's border flashes in the chat + colour for 700 ms (`ChatPaneFocusFlash`). The flash uses the design's + corner radius. Under reduced motion it shows for the same time without + fading. +- It does nothing in these cases: one pane on screen, a phone layout (the + stack and the quick switcher handle chats there), a popup or another + destination open, or a focused terminal. +- The shortcut is listed in the keyboard shortcuts list (Settings and the + Ctrl+? cheatsheet) as "Next or previous chat pane on screen". + +## Evidence + +- Tests: `test/features/chat/chat_pane_cycle_test.dart` (three tiles plus a + window, forward, backward and wrapping; two tiles plus a window; no-op + with one pane and on a phone; terminal keeps the keys) and + `test/features/chat/workspace/chat_pane_cycle_test.dart` (key matching, + labels, wrap). +- Capture: `tool/capture/examples/chat-pane-cycle.json` with + `CHROME_PATH=/usr/bin/chromium`, at 1600x900. `chat-pane-cycle/before.png` + shows the left pane focused. `chat-pane-cycle/after-alt-bracket.png` was + taken 120 ms after Alt+]: the right pane (api refactor) is active, its + composer has the caret, and its purple ring is fading. diff --git a/app/notes/chat-pane-cycle/after-alt-bracket.png b/app/notes/chat-pane-cycle/after-alt-bracket.png new file mode 100644 index 00000000..43dfef04 Binary files /dev/null and b/app/notes/chat-pane-cycle/after-alt-bracket.png differ diff --git a/app/notes/chat-pane-cycle/before.png b/app/notes/chat-pane-cycle/before.png new file mode 100644 index 00000000..e609026f Binary files /dev/null and b/app/notes/chat-pane-cycle/before.png differ diff --git a/app/notes/chat-stack.md b/app/notes/chat-stack.md index 2bb27641..417a0f48 100644 --- a/app/notes/chat-stack.md +++ b/app/notes/chat-stack.md @@ -2,27 +2,49 @@ ## Setting -Settings → Mobile chat navigation: Quick switch (default, the next chat's -peek under the current one) or Chat stack. Per device -(`pipelines.mobile-chat-navigation.v1`, `MobileChatNavigationController`, -restored in `bootstrap.dart`), applied live, and only on a phone-width layout -(`!showsListBesideDetail`). A wide window keeps its panes and shows no stack. +Settings → Mobile chat navigation: Chat stack (the default without a stored +choice) or Quick switch (the next chat's peek under the current one). Per +device (`pipelines.mobile-chat-navigation.v1`, `MobileChatNavigationController`, +restored in `bootstrap.dart`; a stored choice is kept), applied live. It +applies on a phone-width layout (`!showsListBesideDetail`); the Chat stack +also stays on a wide layout on Android or iOS (an unfolded foldable, a +tablet, a browser on one), floating above the active pane beside the list +(`chatStackOnMobile`). A wide desktop or web window keeps its panes alone. +Widget tests run as Android: `test/features/chat/flutter_test_config.dart` +starts each chat test on Quick switch (`debugUse`); the stack's tests pick it. ## Behaviour - The stack's chats are the workspace's panes: the same open-chat set the server syncs (`ChatOpenWorkspaceController`). Choosing one opens it as a tap on its list row does (`_openBySelection`); Add chat is the pane menu's Add - chat pane picker (searchable, the list's own rows) titled "Add chat"; - long press removes the chat's pane, with an Undo snack bar that re-adds it - and keeps the chat on screen. + chat pane picker (searchable, the list's own rows) titled "Add chat". +- Drag: in the open column a 300 ms hold (a quicker tap still opens) lifts + a chat with its pill: a medium haptic, 1.1x scale and a deeper shadow + (flat designs: a primary-colour frame instead). Dragged up or down, the + others slide aside (200 ms ease-out) to open its slot, with a selection + tick per slot; dropping commits through `ChatWorkspaceController.movePane` + (the pane order the server syncs as the open-chat order). The close + button at the stack's slot is the remove target while dragging: its "×" + turns the error colour, and over it (a reach of 0.7 slot around its + centre, short of item 0 a pitch above) it grows 1.2x and fills with the + error colour, and the chat shrinks into it. Dropping there removes the pane with the Undo snack bar; Undo re-adds + it at its old index and keeps the chat on screen. A drop far to the side + (more than 1.5 pitches) or Escape or a cancelled pointer puts it back. + Add chat never lifts and is never a slot. Semantics: Move up, Move down, + Remove from open chats as custom actions on each chat. Reduced motion: + neighbours swap at once, the lift and settle are instant, the "×" only + fades and does not grow. - Collapsed: up to four avatars piled with small offsets and turns, the chat on screen on top; a count badge when more are open, and a bell when another open chat waits on the operator. It sits bottom-end in the active chat's transcript area, just above the composer, so it never covers Send; the transcript pads its last line and Jump to latest above it. It hides while the on-screen keyboard is up (the window's view insets). -- Expanded: a scrim, and a column rising from the stack's slot. The chats keep +- Expanded: a scrim; the pile turns into a close button ("×", a quarter + turn and scale in, `ChatStackCloseTarget`) exactly where it was, so a + second tap on the same spot folds the column; the column rises from one + pitch above it. The chats keep the open-chat order bottom-up (stable positions for muscle memory); the chat on screen wears a ring in its colour; each avatar keeps its list badges (waiting, working, background tasks) and has a name pill tinted with its @@ -31,21 +53,84 @@ restored in `bootstrap.dart`), applied live, and only on a phone-width layout - Motion: one controller, 280 ms open (staggered, a slight-overshoot ease), 220 ms fold (top first). Items move through `ChatStackPoseTransition`, a repaint-only transform render object that reuses its matrix and layer; no - per-frame rebuilds, no blur. Reduced motion: a 120 ms plain fade in place. + per-frame rebuilds, no blur. A drag adds `ChatStackDragShift` (same idea, + driven by a per-item notifier, no layer at rest); the column rebuilds only + when a drag starts and ends. Reduced motion: a 120 ms plain fade in place. - Design tokens: circle discs with a short shadow under Default; the design's square corners and no shadow under flat designs (Terminal, Paper); label pills take the design radius and frame. +## Groups + +- A group is a named set of open chats (`ChatStackGroups`, sessionId → name); + it travels with the open-chat set as each entry's `group`, so it persists + and syncs across devices like the order. Two chats at least: one left + alone leaves its group. Its chats stay together in the open-chat order. +- Top level: each group is one item where its first chat is, its chats piled + as the collapsed stack piles (0.88 scale, the chat on screen on top), the + pill showing its name and count, the bell aggregated. A tap opens it: the + top level fades out (no input) and the group's chats rise from its pile + (280 ms, the same motion as the stack), under a header (back arrow, the + name, a ⋯ menu). The header, the scrim, Back and Escape return to the top + level; a second tap outside folds the stack. Folding always ends on the + top level. +- Drag: the middle half of another item is a drop onto it (it grows 1.14x + and rings in the primary colour, a selection tick); its outer quarters + move the gap (`chatStackDropTarget`: the gap holds within half a slot, so + an item sliding aside never lands back under the finger). Chat onto chat: + a new group ("Group N", the name dialog opens at once, selected); chat + onto group: joins, last; group onto chat: takes it in; group onto group: + merges. In an open group a chat dropped on the header leaves the group + (placed right after it), and the close button removes it from the open + chats. A group dropped on the close button is ungrouped, with Undo. +- Menu (header ⋯) and semantic actions on a group: Rename group, Ungroup, + Close all chats in group (with Undo, restoring order and group). On a + chat: Move up / Move down (within its level), Move to group… (when groups + exist), Remove from group (in a group), Remove from open chats. +- Server: `internal/protocol/chat_open_workspace.go` (`Group`), + `internal/pipeline/chat_open_workspace.go` (validation, stored in the + entries JSON, compared as part of the entry), `internal/server` (copied + through). Needs a server restart. + ## Structure -- `lib/features/chat/stack/`: setting, pose, motion, disc/label, column, FAB, +- `lib/features/chat/stack/`: setting, pose, motion, disc/label, column and + its items, drag (session, shift render object, handles, remove target), FAB, anchor (a `LayerLink` the active pane's transcript marks; the one stack above the workspace follows it, so it survives switching chats). -- `lib/features/chat/chat_screen_stack.dart`: entries, open/add/remove. +- Groups: `chat_stack_groups.dart` (model), `chat_stack_node.dart` (top-level + items), `chat_stack_group_ops.dart` (orders after a drop), + `chat_stack_drop_target.dart`, `chat_stack_group_pile.dart`, + `chat_stack_group_dialogs.dart`, `chat_stack_column_groups.dart`. +- `lib/features/chat/chat_screen_stack.dart`: entries, open/add/remove; + `chat_screen_stack_groups.dart`: join/leave/rename/ungroup/close all. - `chat_thread_view.dart`: anchor target, bottom clearance, Jump offset. - `tool/search_selection_probe_entry.dart`: `?chatNav=stack`. +## Floating chats on a phone + +A phone layout (Quick switch or Chat stack) ignores floating: windows are +hidden below `kListDetailMinWidth`, so each floating chat is held as an +ordinary pane (`_phoneDocked` in `chat_screen_workspace.dart`) and the +server's set keeps it `floating`. Widening the window (a foldable opened, a +desktop resized) floats those chats again; closing one on the phone drops +it from the open chats. Tests: `test/features/chat/chat_floating_phone_test.dart`. + +## Captures + +Drag captures use the kit's mouse `drag` with `press: 700`: with Flutter +web semantics on (the kit turns it on), the engine's click debouncer holds a +press on a tappable node for about 200 ms before the framework sees it, so +a 300 ms hold needs about 500 ms in the browser. Not an issue on a device +without a screen reader. + ## Not verified On-device behaviour (Android keyboard insets, haptics) was not run on a device; web captures used Chrome's touch emulation at 390x844. + +Drag limits: no auto-scroll while dragging; when the column is taller than +the screen it scrolls and clips, so a lifted chat cannot leave the clipped +column to reach the "×" there (Move and Remove remain as semantic actions). +The drag captures used the mouse (CDP), not touch; on-device haptics and the +hold feel are unverified. diff --git a/app/notes/design-compact.md b/app/notes/design-compact.md new file mode 100644 index 00000000..de31106f --- /dev/null +++ b/app/notes/design-compact.md @@ -0,0 +1,94 @@ +# Compact design + +Classic's (formerly Default's) Material 3 look, packed tight for a big monitor and long runs and +chats (Settings > Design > Compact). It has the same colours and glass bars +as Default. Type is smaller: body 13px, labels 11-12px, chat reading 14px on a +1.5 line. Spacing sits on a 4px grid. Rows are 36px with one line and about +54px with two. Icons are 18px, avatars 28px, and every corner is 6px. + +## Tokens + +- `density` (`DesignDensity`, `design_density.dart`; `comfortable` for every + other design). It holds `spacing` (0.6), `iconSize` (18), `avatarSize` + (28), `railWidth` (64), `railLabels` (false) and `titleBarHeight` (32). + - `space(v)` scales a widget's own spacing and snaps it to the 4px grid. + - `inset(v)` does the same for side insets, halfway between: 16 becomes 12. + - `minTouchRow` is 40 on touch devices and 0 on pointer devices. + - `dense` and `pointerPlatform` are also available. All of them return the + input unchanged when the density is comfortable, so other designs keep + their numbers. +- `ReadingType.paragraphGap` is the gap between paragraphs of an answer, in + lines. Default is 0.9; Compact is 0.6. +- `AppDesignTokens.denseCorners(r)` gives the design's radius only under a + dense design. It is for surfaces whose own corners the comfortable designs + keep: floating windows (12), search thumbnails, find bars, run detail + boxes and the search field stadium. +- `AppDesign.dense` and `AppDesign.swatchLines` (the picker preview draws 4 + thin lines for Compact). + +## Themed surfaces + +- `compact_theme.dart`, `compact_controls.dart`, `compact_typography.dart`: + - visual density is `compact`; + - the tap target is `shrinkWrap` on desktop and `padded` (40px) on touch; + - Material 3 icon buttons need their own `visualDensity`, otherwise they + ignore the theme's; they are 32px with a padding of 7; + - buttons, chips, fields, the search bar, list tiles, menus, popups, + dialogs, sheets, snack bars, tooltips, FABs (40px), the rail, the + navigation bar, tabs, badges, the scrollbar, date and time pickers all + take 6px corners and dense paddings; + - cards get a hairline, so `Card.outlined` (graph nodes) keeps its outline. +- `AppListRow` / `AppListAvatar`: dense insets, padding and avatar size, plus + the touch minimum. +- `ShellNavigationRail`: 64px wide, icons only with tooltips. Settings uses + the same 56x32 indicator as the tabs. +- The shell and window host read the rail width through + `navigationRailSpaceOf`. +- Chat: + - the operator bubble has 6px corners and 12/8 padding; + - turn gaps and the paragraph gap are tighter; + - the activity line is 28px (40px on touch); + - turn chips, follow-up and automatic-continue cards are tighter; + - code blocks use 8px insets with monospace at 13/14; + - the composer is a 40px pill, and its field padding is 10 because + density takes 4px off each side. +- Top bars: segmented pieces are 40px (`segmentedPieceHeight(context)`) and + title pill padding is 12. Chat bar text buttons have a 32px minimum. +- Floating windows: a 32px title bar with 16px icons and 6px corners on the + frame, outline and page clip. +- Graph: nodes use 12/8 insets with a 32px minimum height. + `graphMetricsOf(context)` tightens the gaps, lanes and padding. +- Settings: `settingsSectionGapOf` and `settingsRowInsetOf` give 16 and 12, + and the group header, footer and item paddings are dense. + +## Live switch + +A switch into or out of a dense design does not blend +(`AppDesignController.themeAnimationDuration` is zero). The reason: +`ThemeData.lerp` takes a component theme's unset size as 0, so every icon +(and any text style set in a component theme) passes through size 0. In +skwasm, laying out glyphs at nearly zero size hung the page. This was +bisected with `tool/perf/design_bench.mjs`, and the pause stack showed +`paragraph_layout`. + +For the same reason, Compact's component themes set no text styles. Each +component keeps its Material role, which is already at Compact's size. +`test/ui/theme/compact_switch_test.dart` checks every frame of a switch. + +Default, Terminal and Paper keep their blend. + +## Perf budget changes + +- `test/perf/design_bench_test.dart` budgets `scrollRebuildsPerRow`, not + per frame. A denser design shows more rows in each 120px step. +- `design_bench.mjs` gives the chat-switch clicks per-design points + (`compact: [x, y]`), checked with `tool/capture`. + +## Still Default + +- Sliders and switches keep their size. +- Tab heights are not themeable. +- The walkthrough's bullet dot sits off the baseline in every design. +- The glass bar margins (`kFloatingBarMargin`) and `GlassBarMetrics` (artifact + viewer, chevron pager) keep 48px. +- Fields that set their own `OutlineInputBorder()` keep 4px corners. diff --git a/app/notes/graph-stage-popover.md b/app/notes/graph-stage-popover.md new file mode 100644 index 00000000..7fc58062 --- /dev/null +++ b/app/notes/graph-stage-popover.md @@ -0,0 +1,54 @@ +# Graph stage popover + +## Change + +- Tapping (or pressing Enter on) a stage in the pipeline graph or the run graph, + inline or full screen, opens a small card anchored to the node with a nub + pointing at it. It no longer navigates straight to the definition page. +- The card shows: the name, a type chip (Model, Check, Delivery gate, Findings + gate, Human, End), config chips (harness, short model name, effort, timeout, + retries, budget), tools as chips (the server's default set is labelled + `Tools · default` when no block is declared), permission allow-lists behind a + collapsed `Permissions` line, skills, then the prompt as markdown clamped to + ten lines with a fade and `Show all`. A check stage lists its commands, a + findings gate its severity and origin, a human stage its operator + instructions. Limits and outgoing routes close it. +- In a run it also shows the latest status, `×N` visits, the latest visit's + duration, reported tokens/cost over all visits, the latest verdict, the first + line of the handoff and the failure diagnostic when the latest visit failed. +- Actions: `Open definition` (the old tap target) and, for a visited run stage, + `Open visit` (the old run-graph tap target). An unvisited run stage now opens + its declaration too; it simply has no `Open visit`. +- The open stage is marked selected and its routes get a soft highlight; edge + hover and the edge tooltip work as before. + +## Decisions + +- Follows the node on pan and zoom instead of closing: the card lays out in + the overlay against the live viewport transform, so a drag, wheel or pinch + keeps it on its node. Only a tap (down and up within touch slop) outside the + card and its node, Escape, the close button or tapping the node again closes + it; tapping another node replaces it. +- Placement: above, else below, else right, else left, else the roomier of + above/below with the body scrolling. The card stays inside the viewport and + clear of floating bars (the canvas's MediaQuery padding); 400 px wide and at + most 560 px tall. +- Below a 440 px wide (or 300 px tall) viewport the same content opens in a + modal bottom sheet. +- Surface follows the design tokens: Classic is a raised card with a hairline + and 14 px corners; flat designs (Terminal, Paper, Compact) use their panel + fill, frame and radius with no shadow. No blur. Route arrows are icons since + the Terminal face has no U+2192. +- Built lazily: nothing is built while closed, and the global pointer route + and transform listener exist only while a card is open. + +Changed paths (under `app/`): `lib/features/graph/{domain/stage_summary.dart, +domain/stage_run_facts.dart, painting/stage_edges_highlight.dart, +painting/run_graph_edge_layer.dart, viewport/graph_viewport_scope.dart, +viewport/graph_viewport.dart, widgets/graph_stage_popover.dart, +widgets/stage_popover_position.dart, widgets/stage_popover_card.dart, +widgets/stage_popover_parts.dart, widgets/stage_popover_chips.dart, +widgets/run_graph_parts.dart, widgets/run_graph_canvas.dart, +widgets/run_graph_view.dart, widgets/definition_graph_canvas.dart, +widgets/definition_graph_view.dart}`, `tool/perf/perf_fixture.dart` (the +`graph=1` fixture now has a prompt, configs, tools and a check stage). diff --git a/app/notes/notification-thread-grouping.md b/app/notes/notification-thread-grouping.md index 353570bc..07aff054 100644 --- a/app/notes/notification-thread-grouping.md +++ b/app/notes/notification-thread-grouping.md @@ -5,7 +5,7 @@ - `android/.../notify/NotificationThreads.kt` (new): `ThreadEntry`, `ThreadHistory` (bounded per-thread entries, bounded thread count, persisted through the ledger's `LedgerStore` under `threads.history`), and naming helpers. Threads are - keyed by the server `group` (`chat:` or `run:`, per `docs/ntfy.md`). + keyed by the server `group` (`chat:` or `run:`, per `docs/notifications.md`). - `NotificationPresenter.kt`: a grouped notification posts one conversation notification per thread with a stable id (`thread:`), the latest 5 lines (sender = chat title, run title for runs), the unread count (`setNumber`), and a diff --git a/app/notes/ntfy-removal.md b/app/notes/ntfy-removal.md new file mode 100644 index 00000000..d78226d5 --- /dev/null +++ b/app/notes/ntfy-removal.md @@ -0,0 +1,32 @@ +# ntfy removal (app side) + +Operator decision: ntfy is removed from Pipelines. Every client gets +notifications from the server's own app notification stream: browser +Notification on web, the "Receive notifications in Pipelines" background +service or the in-app bridge on Android, the in-app bridge on iOS/macOS. + +## Change + +- Settings "Phone notifications" (ntfy) section replaced by **Notification + events** (`lib/features/settings/settings_notification_settings_section.dart`, + controller `notification_settings_controller.dart`; section id + `notification-events`, still in the phone-first order). It shows the three + server-stored switches `run_finished`, `chat_needs_you`, + `chat_reply_finished` with the subtitle "What the server notifies about. + Stored on the server, so these apply to every device signed in to it." +- The `ntfy_enabled` switch is gone; a reply that still carries it is ignored + (only the three known keys are decoded) and writes send only the toggled key. +- Search keywords no longer mention ntfy. +- "Notifications in Pipelines" note no longer mentions the ntfy app. +- Comments in `agent_notice.dart` (docs/notifications.md, priority 1-5), + `notification_service_bridge.dart`, `AndroidManifest.xml`, + `NotificationService.kt`, `NotificationProtocol.kt` drop ntfy. +- `chat_shown_notify_row.dart` still renders a `phone` channel for transcript + entries recorded before the change; new entries only carry `apps`. + +## Checks + +- `tool/analyze.sh`: clean. +- memwatch `test/features/settings`: 216 passed; `test/features/attention`: + 159 passed; `test/features/notification_service`: 11 passed. +- No browser capture taken for the renamed section. diff --git a/app/notes/read-aloud.md b/app/notes/read-aloud.md index 96ccb190..0811ade0 100644 --- a/app/notes/read-aloud.md +++ b/app/notes/read-aloud.md @@ -16,17 +16,52 @@ they are saved on the device. - `flutter_tts_speech_engine.dart`: the `flutter_tts` implementation. The rate is a multiplier (1.0 = normal); Apple platforms get half of it on their 0..1 scale. Linux reports unsupported, so the button and section are hidden. -- `speech_controller.dart`: the app's single reader (`speechController`, a fake - in tests via `debugSpeechController`). State changes notify the controller; - the spoken word is the separate `word` notifier. Stops on `hidden`, `paused` - or `detached` (not `inactive`, which is only a lost focus). +- `speech_controller.dart`: the reader. State changes notify the controller; + the spoken word is the separate `word` notifier and the reading's + conversation (`SpeechReading`: chat id and name) the `reading` notifier. + Stops on `hidden`, `paused` or `detached` (not `inactive`, which is only a + lost focus): the phone app backgrounded keeps that behaviour. +- `app_speech.dart`: the app's single reader (`speechController`, a fake in + tests via `debugSpeechController`), `speechControllerIfCreated` for code that + only stops or relabels, and `speechReading`, the app-level listenable the + avatars and the global control follow. - `speech_document.dart`: Markdown to sentences, with each spoken character's part and source offset. Code blocks (``` and ~~~) are "Code block.", tables "Table." then cells; rules are skipped. - `chat_markdown_speech.dart`: highlight spans and the reveal scroll for `ChatMarkdownView`. -- Reader ids are `/` so a chat that closes or is swapped - for another stops only its own reply (`stopScope`). +- Reader ids are `/`; `SpeechOrigin` (put by the thread + view) gives Read aloud the chat id and name when a reading starts. + +## Keeps reading across chats + +The reader belongs to the app, not the thread view: switching chats or panes, +opening the chat list or another destination keeps the reply reading, and +reopening the chat shows its Pause/Stop again. A reading ends when it is +stopped (the reply's Stop or the global one), finishes, another reply starts, +its chat is closed (`/close`, the row's Close, or a refreshed row closed +elsewhere) or deleted (gone from a successful list read, which includes its +machine being removed), and when the app closes or is backgrounded. + +- Indicator: `chatSessionActivityBadge(speaking:)` draws + `ChatSpeakingGlyph` (three animated bars; a still speaker under reduced + motion) in the avatar's bottom-right badge, ahead of the operator wait, the + running spinner and the background-task count. `ChatSessionAvatar` (list, + quick switch, phone chat stack, pane header) and `ChatCompactAvatar` + (compact sidebar) follow `speechReading`. +- Global stop: `ChatSpeakingControl`, "Speaking · " (or "Paused") with + Stop speaking, sits above the composer of the active pane (`pasteTarget`) + of any chat, so one copy shows whatever the layout. It uses the design's + panel fill, frame and corner tokens. +- Servers: federated chat ids carry their machine, so moving between machines + in the combined list keeps reading. Switching the server profile (native) + remounts `PipelinesApp`, whose dispose stops the reader; on the web a server + switch loads another page, which ends speech. +- Detached windows are separate processes (desktop) or browser windows (web), + each with its own reader: speech belongs to the window that started it, + shows only there, and stops when that window closes. +- Web: the utterance is held by `WebSpeechEngine`, owned by the app reader, + never by a widget. ## Platform notes @@ -49,7 +84,12 @@ Tests (fake engine): `test/features/chat/speech/`, `test/features/chat/ui/transcript/chat_read_aloud_button_test.dart`, `chat_markdown_read_aloud_test.dart`, `test/features/chat/conversation/chat_thread_read_aloud_test.dart`, +`test/features/chat/ui/sessions/chat_speaking_badge_test.dart`, +`chat_sessions_speech_test.dart`, `test/features/settings/settings_read_aloud_section_test.dart`. +Captures (`speech=fake`, Terminal and Classic, wide and phone) show the badge +on the reading chat after switching to another one, and the global control. + Not verified on a device: real speech output, word boundaries and voices on Android, macOS and browsers. diff --git a/app/notes/synced-attention.md b/app/notes/synced-attention.md index 81d655d2..5a180520 100644 --- a/app/notes/synced-attention.md +++ b/app/notes/synced-attention.md @@ -11,7 +11,7 @@ not only on the web and then I have to clear again on mobile." device has open, records a per-session `chat_seen` watermark in epoch ms. ntfy notifications already shown on a phone cannot be retracted (see -`docs/ntfy.md`, "Clearing notifications across devices"). +`docs/notifications.md`, "Clearing notifications across devices"). ## Protocol (server, `internal/protocol/attention_acks.go`) diff --git a/app/test/application/chat_destination_test.dart b/app/test/application/chat_destination_test.dart index aed29da1..abec0299 100644 --- a/app/test/application/chat_destination_test.dart +++ b/app/test/application/chat_destination_test.dart @@ -1,5 +1,6 @@ import 'dart:convert'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/app_session.dart'; @@ -29,6 +30,12 @@ Widget host(AppSession session, {String? initialSessionId}) => MaterialApp( ); void main() { + // These describe the Quick switch layout (the peek of the next chat). + setUp( + () => MobileChatNavigationController.instance.debugUse( + MobileChatNavigation.quickSwitch, + ), + ); testWidgets('nothing is requested before the shared socket is ready', ( tester, ) async { diff --git a/app/test/application/chat_registration_test.dart b/app/test/application/chat_registration_test.dart index c51c348e..1c829d3b 100644 --- a/app/test/application/chat_registration_test.dart +++ b/app/test/application/chat_registration_test.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:convert'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -296,6 +297,12 @@ Future replyChatHistory( } void main() { + // These describe the Quick switch layout (the peek of the next chat). + setUp( + () => MobileChatNavigationController.instance.debugUse( + MobileChatNavigation.quickSwitch, + ), + ); testWidgets( 'a wide /chat/s1 deep link shows that thread beside the list and route Back returns to /chat', (tester) async { diff --git a/app/test/features/chat/chat_floating_phone_test.dart b/app/test/features/chat/chat_floating_phone_test.dart new file mode 100644 index 00000000..2bcd43bf --- /dev/null +++ b/app/test/features/chat/chat_floating_phone_test.dart @@ -0,0 +1,287 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/chat_runtime.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; +import 'package:pipelines_app/features/chat/windows/chat_windows.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/shell/windows/window_host.dart'; +import 'package:pipelines_app/shell/windows/window_kind.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; +import 'package:pipelines_app/shell/windows/window_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +/// A chat server with an open-chat set whose entries may float. +class _Server extends FakeChatGateway { + _Server(this.open, this.floating); + List open; + Set floating; + int revision = 1; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'c']) + {'id': id, 'title': 'Chat $id', 'directory': '/home/$id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + if (type == 'chat_open_workspace') { + final request = fields['chat_open_workspace_request'] as Map?; + var rejected = false; + if (request != null && request['seed'] != true) { + if (request['base_revision'] != revision) { + rejected = true; + } else { + final entries = (request['entries'] as List).cast(); + open = [for (final e in entries) '${e['session_id']}']; + floating = { + for (final e in entries) + if (e['floating'] == true) '${e['session_id']}', + }; + revision++; + } + } + return Future.value({ + 'type': 'chat_open_workspace', + 'chat_open_workspace': _body(rejected), + }); + } + return super.call(type, fields); + } + + JsonMap _body([bool rejected = false]) => { + 'revision': revision, + 'entries': [ + for (final id in open) + {'session_id': id, if (floating.contains(id)) 'floating': true}, + ], + if (rejected) 'rejected': true, + }; + + void change(List ids, Set floats) { + open = ids; + floating = floats; + revision++; + emitRaw({ + 'type': 'chat_open_workspace_changed', + 'chat_open_workspace': _body(), + }); + } +} + +class _Store implements WindowStore { + String? value; + @override + Future read() async => value; + @override + Future write(String record) async { + value = record; + return true; + } +} + +const _wide = Size(1800, 1000); +const _phone = Size(390, 844); + +class _App { + late final _Server server; + late final ChatRuntime runtime; + late final WindowManager manager; + late final ChatWindows windows; + + Future start(WidgetTester tester, {Size size = _wide}) async { + SharedPreferences.setMockInitialValues({}); + _resize(tester, size); + addTearDown(tester.view.reset); + server = _Server(['a', 'b'], {'b'})..history = (_) async => chatPage([]); + bindServerIdentity(server, 'server-a'); + runtime = ChatRuntime(gateway: server, serverKey: 'server-a'); + manager = WindowManager( + kinds: WindowKinds(), + store: _Store(), + server: 'server-a', + ); + windows = ChatWindows( + manager: manager, + runtime: runtime, + openInChat: (_) {}, + )..start(); + await manager.restore(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Stack( + fit: StackFit.expand, + children: [ + ChatScreen( + gateway: server, + persistWorkspace: true, + runtime: runtime, + windows: windows, + ), + Positioned.fill(child: WindowHost(manager: manager)), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future stop(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + windows.dispose(); + runtime.dispose(); + manager.dispose(); + server.close(); + } + + List get floatingWindows => [ + for (final w in windows.windows) w.contentId, + ]; +} + +void _resize(WidgetTester tester, Size size) { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; +} + +List _panes(WidgetTester tester) { + final workspace = find.byType(ChatWorkspace, skipOffstage: false); + if (workspace.evaluate().isEmpty) return const []; + return tester + .widget(workspace) + .controller + .panes + .map((pane) => pane.sessionId) + .toList(); +} + +Finder _shownThread(String id) => find + .byWidgetPredicate((w) => w is ChatThreadView && w.sessionId == id) + .hitTestable(); + +void main() { + final navigation = MobileChatNavigationController.instance; + tearDown(() { + unawaited(navigation.setValue(MobileChatNavigation.quickSwitch)); + }); + + testWidgets('a phone tiles a floating chat; a wide layout floats it again', ( + tester, + ) async { + final app = _App(); + await app.start(tester); + expect(app.floatingWindows, ['b']); + + _resize(tester, _phone); + await tester.pumpAndSettle(); + // No window at phone width: the chat is an open chat like the others, + // and the server still has it floating. + expect(app.floatingWindows, isEmpty); + expect(app.server.floating, {'b'}); + + // The list opens it full screen. + await tester.tap(find.byKey(const Key('chat-row-b'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + expect(_panes(tester), ['a', 'b']); + + _resize(tester, _wide); + await tester.pumpAndSettle(); + expect(app.floatingWindows, ['b']); + expect(_panes(tester), ['a']); + expect(_shownThread('a'), findsOneWidget); + expect(app.server.floating, {'b'}); + expect(app.server.open, ['a', 'b']); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('a floating chat opens from the list on a phone from the start', ( + tester, + ) async { + final app = _App(); + await app.start(tester, size: _phone); + expect(app.floatingWindows, isEmpty); + await tester.tap(find.byKey(const Key('chat-row-b'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + expect(_panes(tester), ['a', 'b']); + expect(app.server.floating, {'b'}); + await app.stop(tester); + }); + + testWidgets('quick switch reaches a floating chat on a phone', ( + tester, + ) async { + final app = _App(); + await app.start(tester, size: _phone); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + expect(_shownThread('a'), findsOneWidget); + final controller = tester + .widget(find.byType(ChatWorkspace)) + .controller; + final b = controller.panes.firstWhere((pane) => pane.sessionId == 'b'); + await tester.tap(find.byKey(ValueKey('chat-peek-${b.id}'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + expect(app.floatingWindows, isEmpty); + await app.stop(tester); + }); + + testWidgets('the chat stack reaches a floating chat on a phone', ( + tester, + ) async { + unawaited(navigation.setValue(MobileChatNavigation.chatStack)); + final app = _App(); + await app.start(tester, size: _phone); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-stack'))); + await tester.pumpAndSettle(); + final controller = tester + .widget(find.byType(ChatWorkspace)) + .controller; + final b = controller.panes.firstWhere((pane) => pane.sessionId == 'b'); + await tester.tap(find.byKey(ValueKey('chat-stack-button-${b.id}'))); + await tester.pumpAndSettle(); + expect(_shownThread('b'), findsOneWidget); + await app.stop(tester); + }); + + testWidgets('a chat another device floats stays tiled on a phone', ( + tester, + ) async { + final app = _App(); + await app.start(tester, size: _phone); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + app.server.change(['a', 'b', 'c'], {'b', 'c'}); + await tester.pumpAndSettle(); + expect(app.floatingWindows, isEmpty); + expect(_panes(tester), ['a', 'b', 'c']); + + // Removing a held chat on the phone drops it from the open chats. + final controller = tester + .widget(find.byType(ChatWorkspace, skipOffstage: false)) + .controller; + controller.close(controller.panes.last.id); + await tester.pumpAndSettle(); + expect(app.server.open, ['a', 'b']); + expect(app.server.floating, {'b'}); + await app.stop(tester); + }); +} diff --git a/app/test/features/chat/chat_pane_cycle_test.dart b/app/test/features/chat/chat_pane_cycle_test.dart new file mode 100644 index 00000000..e18d5a3d --- /dev/null +++ b/app/test/features/chat/chat_pane_cycle_test.dart @@ -0,0 +1,329 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/chat_runtime.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/windows/chat_windows.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_pane_focus_flash.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; +import 'package:pipelines_app/shell/windows/window_host.dart'; +import 'package:pipelines_app/shell/windows/window_kind.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; +import 'package:pipelines_app/shell/windows/window_store.dart'; +import 'package:pipelines_app/ui/input/keyboard_owner.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +const _ids = ['a', 'b', 'c', 'd']; + +class _Gateway extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in _ids) + {'id': id, 'title': 'Chat $id', 'directory': '/home/$id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +class _Store implements WindowStore { + String? value; + @override + Future read() async => value; + @override + Future write(String record) async { + value = record; + return true; + } +} + +Finder _thread(String id) => find.byWidgetPredicate( + (widget) => widget is ChatThreadView && widget.sessionId == id, + skipOffstage: false, +); +Finder _input(String id) => find.descendant( + of: find.byKey(ValueKey('chat-composer-$id'), skipOffstage: false), + matching: find.byType(EditableText, skipOffstage: false), + skipOffstage: false, +); +bool _composerFocused(WidgetTester tester, String id) => + tester.widget(_input(id)).focusNode.hasPrimaryFocus; +ChatWorkspaceController _workspace(WidgetTester tester) => tester + .widget(find.byType(ChatWorkspace, skipOffstage: false)) + .controller; + +/// The chats whose focus ring is showing. +List _flashing(WidgetTester tester) => [ + for (final id in _ids) + if (find + .descendant( + of: find.ancestor( + of: _thread(id), + matching: find.byType(ChatPaneFocusFlash), + ), + matching: find.byKey(const ValueKey('chat-pane-focus-flash')), + ) + .evaluate() + .isNotEmpty) + id, +]; + +/// Saves a horizontal layout of [ids], left to right. +void _saved(List ids) { + final layout = ChatWorkspaceController()..open(ids.first); + for (final id in ids.skip(1)) { + layout.splitActive(id, ChatSplitAxis.horizontal); + } + SharedPreferences.setMockInitialValues({ + scopedServerKey(chatWorkspacePreferenceKey, 'server-a'): layout + .snapshot()! + .encode(), + }); +} + +/// The Chat destination with its floating windows over it, and optionally a +/// terminal that takes typing. +class _App { + final gateway = _Gateway()..history = (_) async => chatPage([]); + late final ChatRuntime runtime; + late final WindowManager manager; + late final ChatWindows windows; + final terminalFocus = FocusNode(debugLabel: 'test terminal'); + final terminalTyped = []; + + Future start( + WidgetTester tester, { + Size size = const Size(1800, 1000), + bool terminal = false, + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + bindServerIdentity(gateway, 'server-a'); + runtime = ChatRuntime(gateway: gateway, serverKey: 'server-a'); + manager = WindowManager( + kinds: WindowKinds(), + store: _Store(), + server: 'server-a', + ); + windows = ChatWindows( + manager: manager, + runtime: runtime, + openInChat: (_) {}, + )..start(); + await manager.restore(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Stack( + fit: StackFit.expand, + children: [ + ChatScreen( + gateway: gateway, + persistWorkspace: true, + runtime: runtime, + windows: windows, + ), + if (terminal) + Positioned( + left: 0, + top: 0, + width: 10, + height: 10, + child: TypingSurface( + child: Focus( + focusNode: terminalFocus, + onKeyEvent: (node, event) { + if (event is KeyDownEvent) { + terminalTyped.add(event.logicalKey); + } + return KeyEventResult.handled; + }, + child: const SizedBox(), + ), + ), + ), + Positioned.fill(child: WindowHost(manager: manager)), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future stop(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + windows.dispose(); + runtime.dispose(); + manager.dispose(); + terminalFocus.dispose(); + gateway.close(); + } + + List get floating => [for (final w in windows.windows) w.contentId]; +} + +/// Floats [session] from its pane menu. +Future _float(WidgetTester tester, String session) async { + await tester.tap( + find + .descendant( + of: _thread(session), + matching: find.byTooltip('More actions'), + ) + .hitTestable(), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Float (Alt+Y)').last); + await tester.pumpAndSettle(); +} + +/// Alt+] (or Alt+[ with [back]), leaving the focus ring mid-flash. +Future _cycle(WidgetTester tester, {bool back = false}) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + final physical = back + ? PhysicalKeyboardKey.bracketLeft + : PhysicalKeyboardKey.bracketRight; + final logical = back + ? LogicalKeyboardKey.bracketLeft + : LogicalKeyboardKey.bracketRight; + await tester.sendKeyDownEvent(logical, physicalKey: physical); + await tester.sendKeyUpEvent(logical, physicalKey: physical); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + for (var i = 0; i < 3; i++) { + await tester.pump(); + } +} + +/// Lets the flash finish. +Future _settle(WidgetTester tester) async { + await tester.pump(chatPaneFlashDuration); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('Alt+] and Alt+[ cycle three tiled panes and a floating ' + 'window, wrapping, each composer focused and its ring flashing', ( + tester, + ) async { + _saved(['a', 'b', 'c', 'd']); + final app = _App(); + await app.start(tester); + await _float(tester, 'd'); + final workspace = _workspace(tester); + expect(workspace.panes.map((p) => p.sessionId), ['a', 'b', 'c']); + expect(app.floating, ['d']); + + await tester.tapAt(tester.getCenter(_input('a'))); + await tester.pumpAndSettle(); + expect(_composerFocused(tester, 'a'), isTrue); + + // Forward: the tiles left to right, then the window, then around. + for (final id in ['b', 'c', 'd', 'a']) { + await _cycle(tester); + expect(_composerFocused(tester, id), isTrue, reason: id); + expect(_flashing(tester), [id]); + if (id != 'd') expect(workspace.activePane?.sessionId, id); + await _settle(tester); + expect(_flashing(tester), isEmpty); + } + + // Back: around to the window, then the tiles right to left. + for (final id in ['d', 'c', 'b', 'a']) { + await _cycle(tester, back: true); + expect(_composerFocused(tester, id), isTrue, reason: id); + expect(_flashing(tester), [id]); + await _settle(tester); + } + + // Nothing opened, closed or moved. + expect(workspace.panes.map((p) => p.sessionId), ['a', 'b', 'c']); + expect(app.floating, ['d']); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('two tiled panes and a floating window cycle in the same order', ( + tester, + ) async { + _saved(['a', 'b', 'c']); + final app = _App(); + await app.start(tester); + await _float(tester, 'c'); + await tester.tapAt(tester.getCenter(_input('b'))); + await tester.pumpAndSettle(); + for (final id in ['c', 'a', 'b']) { + await _cycle(tester); + expect(_composerFocused(tester, id), isTrue, reason: id); + await _settle(tester); + } + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('with one pane on screen the keys do nothing', (tester) async { + _saved(['a']); + final app = _App(); + await app.start(tester); + await tester.tapAt(tester.getCenter(_input('a'))); + await tester.pumpAndSettle(); + await _cycle(tester); + await _cycle(tester, back: true); + expect(_composerFocused(tester, 'a'), isTrue); + expect(_flashing(tester), isEmpty); + expect(_workspace(tester).paneCount, 1); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('on a phone layout the keys do nothing', (tester) async { + _saved(['a', 'b']); + final app = _App(); + await app.start(tester, size: const Size(400, 800)); + final workspace = _workspace(tester); + final active = workspace.activePane?.sessionId; + await _cycle(tester); + await _cycle(tester); + expect(workspace.activePane?.sessionId, active); + expect(_flashing(tester), isEmpty); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('a focused terminal keeps Alt+] and Alt+[', (tester) async { + _saved(['a', 'b']); + final app = _App(); + await app.start(tester, terminal: true); + final workspace = _workspace(tester); + await tester.tapAt(tester.getCenter(_input('a'))); + await tester.pumpAndSettle(); + app.terminalFocus.requestFocus(); + await tester.pumpAndSettle(); + + await _cycle(tester); + await _cycle(tester, back: true); + expect(app.terminalTyped, [ + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.bracketRight, + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.bracketLeft, + ]); + expect(app.terminalFocus.hasPrimaryFocus, isTrue); + expect(workspace.activePane?.sessionId, 'a'); + expect(_flashing(tester), isEmpty); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); +} diff --git a/app/test/features/chat/conversation/chat_thread_read_aloud_test.dart b/app/test/features/chat/conversation/chat_thread_read_aloud_test.dart index 487e1a10..38262ff1 100644 --- a/app/test/features/chat/conversation/chat_thread_read_aloud_test.dart +++ b/app/test/features/chat/conversation/chat_thread_read_aloud_test.dart @@ -2,21 +2,34 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; import 'package:pipelines_app/features/chat/speech/speech.dart'; +import 'package:pipelines_app/features/chat/ui/speech/chat_speaking_control.dart'; import 'package:pipelines_app/features/chat/ui/transcript/chat_read_aloud_button.dart'; import '../speech/fake_speech_engine.dart'; import 'chat_thread_fixtures.dart'; -Widget _thread(FakeChatGateway gateway, String sessionId) => MaterialApp( +Widget _thread( + FakeChatGateway gateway, + String sessionId, { + String title = '', + bool pasteTarget = true, +}) => MaterialApp( theme: ThemeData(platform: TargetPlatform.android), home: Scaffold( - body: ChatThreadView(gateway: gateway, sessionId: sessionId, onBack: () {}), + body: ChatThreadView( + gateway: gateway, + sessionId: sessionId, + title: title, + pasteTarget: pasteTarget, + onBack: () {}, + ), ), ); Future<(FakeSpeechEngine, SpeechController, FakeChatGateway)> _reading( - WidgetTester tester, -) async { + WidgetTester tester, { + String title = 'Alpha', +}) async { tester.view.physicalSize = const Size(800, 1600); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); @@ -33,42 +46,78 @@ Future<(FakeSpeechEngine, SpeechController, FakeChatGateway)> _reading( ], ), ]); - await tester.pumpWidget(_thread(gateway, 's1')); + await tester.pumpWidget(_thread(gateway, 's1', title: title)); await tester.pumpAndSettle(); await tester.tap(find.byTooltip(chatReadAloudLabel)); await tester.pump(); engine.onStart!(); + await tester.pump(); expect(engine.spoken, ['Hello from the agent.']); expect(speech.messageId, startsWith(speechScopePrefix('s1'))); + expect(speech.reading.value, SpeechReading(scope: 's1', title: title)); return (engine, speech, gateway); } void main() { - testWidgets('switching the pane to another chat stops reading', ( + testWidgets('switching the pane to another chat keeps reading', ( tester, ) async { final (engine, speech, gateway) = await _reading(tester); - await tester.pumpWidget(_thread(gateway, 's2')); + await tester.pumpWidget(_thread(gateway, 's2', title: 'Beta')); await tester.pumpAndSettle(); - expect(speech.state, SpeechState.idle); - expect(engine.calls, contains('stop')); + expect(speech.state, SpeechState.speaking); + expect(engine.calls, isNot(contains('stop'))); + expect(speechReading.value?.scope, 's1'); + + // Back in the chat, its reply shows the reading's Pause and Stop again. + await tester.pumpWidget(_thread(gateway, 's1', title: 'Alpha')); + await tester.pumpAndSettle(); + expect(find.byTooltip(chatStopReadingLabel), findsOneWidget); + expect(find.byTooltip(chatPauseReadingLabel), findsOneWidget); }); - testWidgets('closing the chat stops reading', (tester) async { + testWidgets('leaving the conversation keeps its reply reading', ( + tester, + ) async { final (engine, speech, _) = await _reading(tester); await tester.pumpWidget(const MaterialApp(home: SizedBox())); await tester.pumpAndSettle(); - expect(speech.state, SpeechState.idle); - expect(engine.calls.last, 'stop'); - }); - - testWidgets('closing a chat leaves another chat reading', (tester) async { - final (engine, speech, _) = await _reading(tester); - await speech.read(speechMessageId('elsewhere', 'b1'), ['Other reply']); - engine.onStart!(); - await tester.pumpWidget(const MaterialApp(home: SizedBox())); - await tester.pumpAndSettle(); expect(speech.state, SpeechState.speaking); - expect(speech.messageId, speechMessageId('elsewhere', 'b1')); + expect(engine.calls, isNot(contains('stop'))); + }); + + testWidgets('another chat names the reading and its Stop ends it', ( + tester, + ) async { + final (engine, speech, gateway) = await _reading(tester); + expect(find.text('Speaking · Alpha'), findsOneWidget); + + await tester.pumpWidget(_thread(gateway, 's2', title: 'Beta')); + await tester.pumpAndSettle(); + expect(find.text('Speaking · Alpha'), findsOneWidget); + + await tester.tap(find.byTooltip(chatSpeakingStopLabel)); + await tester.pumpAndSettle(); + expect(speech.state, SpeechState.idle); + expect(engine.calls.last, 'stop'); + expect(find.byKey(const Key('chat-speaking-control')), findsNothing); + }); + + testWidgets('the control follows a pause and a rename', (tester) async { + final (_, speech, gateway) = await _reading(tester); + await speech.pause(); + await tester.pump(); + expect(find.text('Paused · Alpha'), findsOneWidget); + + await tester.pumpWidget(_thread(gateway, 's1', title: 'Renamed')); + await tester.pumpAndSettle(); + expect(find.text('Paused · Renamed'), findsOneWidget); + }); + + testWidgets('only the active pane shows the global control', (tester) async { + final (_, _, gateway) = await _reading(tester); + await tester.pumpWidget(_thread(gateway, 's2', pasteTarget: false)); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-speaking-control')), findsNothing); }); } diff --git a/app/test/features/chat/flutter_test_config.dart b/app/test/features/chat/flutter_test_config.dart index 2e3f4e32..85859eac 100644 --- a/app/test/features/chat/flutter_test_config.dart +++ b/app/test/features/chat/flutter_test_config.dart @@ -1,13 +1,23 @@ import 'dart:async'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; /// Functional chat tests settle asynchronous state with reduced motion. Tests /// covering animation explicitly opt back in and pump known frame durations. +/// +/// Tests run as Android, where the Chat stack (the default) also shows on a +/// wide layout. Each test starts on Quick switch, the layout most of them +/// describe; the stack's own tests choose it. Future testExecutable(FutureOr Function() testMain) async { TestWidgetsFlutterBinding.ensureInitialized() .platformDispatcher .accessibilityFeaturesTestValue = const FakeAccessibilityFeatures( disableAnimations: true, ); + setUp( + () => MobileChatNavigationController.instance.debugUse( + MobileChatNavigation.quickSwitch, + ), + ); await testMain(); } diff --git a/app/test/features/chat/speech/speech_controller_test.dart b/app/test/features/chat/speech/speech_controller_test.dart index f71d9d55..8e864641 100644 --- a/app/test/features/chat/speech/speech_controller_test.dart +++ b/app/test/features/chat/speech/speech_controller_test.dart @@ -143,6 +143,29 @@ void main() { expect(speech.state, SpeechState.idle); }); + testWidgets('reading names the conversation until the reply ends', ( + tester, + ) async { + reader(); + await speech.read(speechMessageId('chat-1', 'm1'), ['Hi'], title: 'One'); + expect( + speech.reading.value, + const SpeechReading(scope: 'chat-1', title: 'One'), + ); + speech.retitle('chat-2', 'Other'); + expect(speech.reading.value?.title, 'One'); + speech.retitle('chat-1', 'Renamed'); + expect(speech.reading.value?.title, 'Renamed'); + + // Another reply replaces it; finishing clears it. + await speech.read(speechMessageId('chat-2', 'm1'), ['Yo'], title: 'Two'); + expect(speech.reading.value?.scope, 'chat-2'); + engine.onStart!(); + engine.onCompletion!(); + expect(speech.reading.value, isNull); + expect(speech.state, SpeechState.idle); + }); + testWidgets('voice and rate are applied and persist across a reload', ( tester, ) async { diff --git a/app/test/features/chat/stack/chat_stack_drag_test.dart b/app/test/features/chat/stack/chat_stack_drag_test.dart new file mode 100644 index 00000000..06f62278 --- /dev/null +++ b/app/test/features/chat/stack/chat_stack_drag_test.dart @@ -0,0 +1,323 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_column.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_disc.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_drag.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_close_target.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../conversation/chat_thread_fixtures.dart'; + +/// A chat server keeping the open-chat set, as the sync test's does. +class _Server extends FakeChatGateway { + List open = ['a', 'b', 'c']; + int revision = 1; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'c', 'd']) + {'id': id, 'title': 'Chat $id', 'directory': '/w'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + if (type == 'chat_open_workspace') { + final request = fields['chat_open_workspace_request'] as Map?; + var rejected = false; + if (request != null && request['seed'] != true) { + if (request['base_revision'] != revision) { + rejected = true; + } else { + open = [ + for (final e in (request['entries'] as List).cast()) + '${e['session_id']}', + ]; + revision++; + } + } + return Future.value({ + 'type': 'chat_open_workspace', + 'chat_open_workspace': { + 'revision': revision, + 'entries': [ + for (final id in open) {'session_id': id}, + ], + if (rejected) 'rejected': true, + }, + }); + } + return super.call(type, fields); + } +} + +Future<_Server> _pump(WidgetTester tester, {bool reduced = false}) async { + SharedPreferences.setMockInitialValues({}); + unawaited( + MobileChatNavigationController.instance.setValue( + MobileChatNavigation.chatStack, + ), + ); + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final server = _Server()..history = (_) async => chatPage(const []); + bindServerIdentity(server, 'server-stack'); + addTearDown(server.close); + await tester.pumpWidget( + MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: reduced), + child: child!, + ), + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => + ChatScreen(gateway: server, persistWorkspace: true), + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-stack'))); + await tester.pumpAndSettle(); + return server; +} + +ChatWorkspaceController _workspace(WidgetTester tester) => + tester.widget(find.byType(ChatWorkspace)).controller; + +List _order(WidgetTester tester) => [ + for (final pane in _workspace(tester).panes) pane.sessionId, +]; + +/// Chat [id]'s avatar in the open column. +Finder _button(WidgetTester tester, String id) { + final pane = _workspace( + tester, + ).panes.firstWhere((pane) => pane.sessionId == id); + return find.byKey(ValueKey('chat-stack-button-${pane.id}')); +} + +final _add = find.byKey(const ValueKey('chat-stack-button-add')); +final _target = find.byType(ChatStackCloseTarget); + +/// Holds [finder] until it lifts. +Future _lift(WidgetTester tester, Finder finder) async { + final gesture = await tester.startGesture(tester.getCenter(finder)); + await tester.pump(chatStackLiftDelay + const Duration(milliseconds: 20)); + return gesture; +} + +double _shown(WidgetTester tester) => + tester.widget(_target).armed.value; + +void main() { + final navigation = MobileChatNavigationController.instance; + tearDown(() { + unawaited(navigation.setValue(MobileChatNavigation.quickSwitch)); + }); + + test('movePane moves a pane and keeps the active one', () { + final controller = ChatWorkspaceController()..open('a'); + controller + ..splitActive('b', ChatSplitAxis.horizontal) + ..splitActive('c', ChatSplitAxis.horizontal); + final active = controller.activePaneId; + final a = controller.panes.first.id; + controller.movePane(a, 2); + expect(controller.panes.map((p) => p.sessionId), ['b', 'c', 'a']); + expect(controller.panes.last.id, a); + expect(controller.activePaneId, active); + controller.dispose(); + }); + + testWidgets('hold and drag reorders, and the order reaches the server', ( + tester, + ) async { + final server = await _pump(tester); + expect(_order(tester), ['a', 'b', 'c']); + final b = tester.getCenter(_button(tester, 'b')); + final gesture = await _lift(tester, _button(tester, 'a')); + // Lifted: the remove target comes in. + await tester.pumpAndSettle(); + expect(_shown(tester), 1); + // Up past the middle of c (its middle would group): b and c slide down. + await gesture.moveBy(const Offset(0, -kChatStackPitch * 2.4)); + await tester.pumpAndSettle(); + expect(tester.getCenter(_button(tester, 'b')).dy, b.dy + kChatStackPitch); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['b', 'c', 'a']); + expect(server.open, ['b', 'c', 'a']); + // Everyone settles in the new slots; the column stays open. + expect(tester.getCenter(_button(tester, 'b')).dy, closeTo(b.dy + 56, .5)); + expect(_shown(tester), 0); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('dropping on the × removes; Undo restores the place', ( + tester, + ) async { + final server = await _pump(tester); + final gesture = await _lift(tester, _button(tester, 'b')); + await tester.pumpAndSettle(); + final from = tester.getCenter(_button(tester, 'b')); + await gesture.moveBy(tester.getCenter(_target) - from); + await tester.pumpAndSettle(); + final drag = tester.widget(_target).hover; + expect(drag.value, 1); + await gesture.up(); + await tester.pumpAndSettle(); + expect(find.text('Removed Chat b from open chats'), findsOneWidget); + expect(_order(tester), ['a', 'c']); + expect(server.open, ['a', 'c']); + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + expect(server.open, ['a', 'b', 'c']); + // The chat on screen stays on screen. + expect(_workspace(tester).activePane?.sessionId, 'a'); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Escape, or a drop away from the column, puts the chat back', ( + tester, + ) async { + final server = await _pump(tester); + final home = tester.getCenter(_button(tester, 'a')); + var gesture = await _lift(tester, _button(tester, 'a')); + await gesture.moveBy(const Offset(0, -kChatStackPitch * 2)); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + expect(tester.getCenter(_button(tester, 'a')), home); + // Escape only cancelled the drag: the column is still open. + expect(find.byType(ChatStackColumn), findsOneWidget); + + gesture = await _lift(tester, _button(tester, 'a')); + await gesture.moveBy(const Offset(-200, -kChatStackPitch * 3)); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + expect(server.open, ['a', 'b', 'c']); + expect(tester.getCenter(_button(tester, 'a')), home); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a tap still opens a chat; Add chat does not lift', ( + tester, + ) async { + await _pump(tester); + final add = tester.getCenter(_add); + final gesture = await _lift(tester, _add); + await tester.pumpAndSettle(); + expect(_shown(tester), 0); + await gesture.moveBy(const Offset(0, kChatStackPitch * 2)); + await tester.pumpAndSettle(); + expect(tester.getCenter(_add), add); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + + // A drag that moved off "+" is no tap: the column is still open. + expect(find.byType(ChatStackColumn), findsOneWidget); + await tester.tap(_button(tester, 'c')); + await tester.pumpAndSettle(); + expect( + find + .byWidgetPredicate((w) => w is ChatThreadView && w.sessionId == 'c') + .hitTestable(), + findsOneWidget, + ); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Move up, Move down and Remove are semantic actions', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final server = await _pump(tester); + void act(String id, String label) { + final node = tester.getSemantics(_button(tester, id)); + final action = node + .getSemanticsData() + .customSemanticsActionIds! + .map(CustomSemanticsAction.getAction) + .firstWhere((action) => action!.label == label)!; + tester.binding.renderViews.first.owner!.semanticsOwner!.performAction( + node.id, + SemanticsAction.customAction, + CustomSemanticsAction.getIdentifier(action), + ); + } + + // The bottom chat cannot move down; the top one cannot move up. + final bottom = tester.getSemantics(_button(tester, 'a')); + expect( + bottom.getSemanticsData().customSemanticsActionIds!.map( + (id) => CustomSemanticsAction.getAction(id)!.label, + ), + unorderedEquals([ + ChatStackColumn.moveUpLabel, + ChatStackColumn.removeLabel, + ]), + ); + act('a', ChatStackColumn.moveUpLabel); + await tester.pumpAndSettle(); + expect(server.open, ['b', 'a', 'c']); + act('c', ChatStackColumn.moveDownLabel); + await tester.pumpAndSettle(); + expect(server.open, ['b', 'c', 'a']); + act('b', ChatStackColumn.removeLabel); + await tester.pumpAndSettle(); + expect(server.open, ['c', 'a']); + expect(find.text('Removed Chat b from open chats'), findsOneWidget); + semantics.dispose(); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('reduced motion: neighbours swap at once, the × only fades', ( + tester, + ) async { + await _pump(tester, reduced: true); + final b = tester.getCenter(_button(tester, 'b')); + final gesture = await _lift(tester, _button(tester, 'a')); + expect(_shown(tester), 1); + await gesture.moveBy(const Offset(0, -kChatStackPitch * 1.4)); + await tester.pump(); + expect(tester.getCenter(_button(tester, 'b')).dy, b.dy + kChatStackPitch); + // No turn or growth: the button only fades. + expect( + find.descendant(of: _target, matching: find.byType(RotationTransition)), + findsNothing, + ); + await gesture.up(); + await tester.pump(); + expect(_order(tester), ['b', 'a', 'c']); + expect(_shown(tester), 0); + await tester.pumpAndSettle(); + await tester.pumpWidget(const SizedBox.shrink()); + }); +} diff --git a/app/test/features/chat/stack/chat_stack_fab_test.dart b/app/test/features/chat/stack/chat_stack_fab_test.dart index 6804eb4a..3f0ae77c 100644 --- a/app/test/features/chat/stack/chat_stack_fab_test.dart +++ b/app/test/features/chat/stack/chat_stack_fab_test.dart @@ -1,7 +1,9 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_close_target.dart'; import 'package:pipelines_app/features/chat/stack/chat_stack_column.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_disc.dart'; import 'package:pipelines_app/features/chat/stack/chat_stack_entry.dart'; import 'package:pipelines_app/features/chat/stack/chat_stack_fab.dart'; import 'package:pipelines_app/features/chat/stack/chat_stack_pose.dart'; @@ -103,7 +105,8 @@ void main() { expect(find.text('Chat 0'), findsOneWidget); expect(find.text('Chat 4'), findsOneWidget); expect(find.text(ChatStackColumn.addLabel), findsOneWidget); - // Item 0 sits on the stack; each further item rises one pitch. + // The stack's slot holds the close button; item 0 sits a pitch above + // it and each further item rises one more. final first = tester.getCenter( find.byKey(const ValueKey('chat-stack-button-pane-0')), ); @@ -114,7 +117,11 @@ void main() { find.byKey(const ValueKey('chat-stack-button-add')), ); expect(first.dx, closeTo(slot.center.dx, .5)); - expect(first.dy, closeTo(slot.center.dy, .5)); + expect(first.dy, closeTo(slot.center.dy - kChatStackPitch, .5)); + expect( + tester.getCenter(find.bySemanticsLabel(ChatStackCloseTarget.label)), + slot.center, + ); expect(second.dy, lessThan(first.dy)); expect(add.dy, lessThan(second.dy)); // Outside the column. @@ -126,6 +133,22 @@ void main() { expect(harness.opened, isEmpty); }); + testWidgets('the close button where the pile was folds the column', ( + tester, + ) async { + final harness = await _pump(tester); + final slot = tester.getRect(find.byKey(const Key('chat-stack'))); + await tester.tap(find.byKey(const Key('chat-stack'))); + await _settle(tester); + await tester.tapAt(slot.center); + await tester.pump(); + expect(_state(tester).expanded, isFalse); + await _settle(tester); + expect(find.byType(ChatStackColumn), findsNothing); + expect(harness.opened, isEmpty); + expect(harness.added, 0); + }); + testWidgets('tapping a chat opens it and folds the column', (tester) async { final harness = await _pump(tester); await tester.tap(find.byKey(const Key('chat-stack'))); @@ -145,17 +168,18 @@ void main() { expect(harness.opened, ['s3']); }); - testWidgets('add opens the picker; long press removes', (tester) async { + testWidgets('add opens the picker; a hold alone removes nothing', ( + tester, + ) async { final harness = await _pump(tester); await tester.tap(find.byKey(const Key('chat-stack'))); await _settle(tester); + // A hold lifts the chat for a drag; let go in place, it settles back. await tester.longPress(find.text('Chat 2')); await _settle(tester); - expect(harness.removed, ['s2']); - // Removing folds the column, so a snack bar's Undo is in reach. - expect(find.byType(ChatStackColumn), findsNothing); - await tester.tap(find.byKey(const Key('chat-stack'))); - await _settle(tester); + expect(harness.removed, isEmpty); + expect(harness.opened, isEmpty); + expect(find.byType(ChatStackColumn), findsOneWidget); await tester.tap(find.byKey(const ValueKey('chat-stack-button-add'))); await _settle(tester); expect(harness.added, 1); diff --git a/app/test/features/chat/stack/chat_stack_group_screen_test.dart b/app/test/features/chat/stack/chat_stack_group_screen_test.dart new file mode 100644 index 00000000..c98a650b --- /dev/null +++ b/app/test/features/chat/stack/chat_stack_group_screen_test.dart @@ -0,0 +1,371 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_close_target.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_column.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_disc.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_drag.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_group_dialogs.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../conversation/chat_thread_fixtures.dart'; + +/// A chat server keeping the open-chat set with each entry's group. +class _Server extends FakeChatGateway { + List open = ['a', 'b', 'c']; + Map groups = {}; + int revision = 1; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'c', 'd']) + {'id': id, 'title': 'Chat $id', 'directory': '/w'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + if (type == 'chat_open_workspace') { + final request = fields['chat_open_workspace_request'] as Map?; + var rejected = false; + if (request != null && request['seed'] != true) { + if (request['base_revision'] != revision) { + rejected = true; + } else { + final entries = (request['entries'] as List).cast(); + open = [for (final e in entries) '${e['session_id']}']; + groups = { + for (final e in entries) + if (e['group'] != null) '${e['session_id']}': '${e['group']}', + }; + revision++; + } + } + return Future.value({ + 'type': 'chat_open_workspace', + 'chat_open_workspace': _body(rejected), + }); + } + return super.call(type, fields); + } + + JsonMap _body([bool rejected = false]) => { + 'revision': revision, + 'entries': [ + for (final id in open) + {'session_id': id, if (groups[id] != null) 'group': groups[id]}, + ], + if (rejected) 'rejected': true, + }; + + /// Another device changed the set. + void change(List ids, Map byGroup) { + open = ids; + groups = byGroup; + revision++; + emitRaw({ + 'type': 'chat_open_workspace_changed', + 'chat_open_workspace': _body(), + }); + } +} + +Future<_Server> _pump(WidgetTester tester) async { + SharedPreferences.setMockInitialValues({}); + MobileChatNavigationController.instance.debugUse( + MobileChatNavigation.chatStack, + ); + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final server = _Server()..history = (_) async => chatPage(const []); + bindServerIdentity(server, 'server-groups'); + addTearDown(server.close); + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => + ChatScreen(gateway: server, persistWorkspace: true), + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + await _expand(tester); + return server; +} + +Future _expand(WidgetTester tester) async { + await tester.tap(find.byKey(const Key('chat-stack'))); + await tester.pumpAndSettle(); +} + +ChatWorkspaceController _workspace(WidgetTester tester) => + tester.widget(find.byType(ChatWorkspace)).controller; + +Finder _chat(WidgetTester tester, String id) { + final pane = _workspace( + tester, + ).panes.firstWhere((pane) => pane.sessionId == id); + return find.byKey(ValueKey('chat-stack-button-${pane.id}')); +} + +Finder _group(String name) => + find.byKey(ValueKey('chat-stack-button-group-$name')); +final _header = find.byKey(const ValueKey('chat-stack-button-header')); + +/// Holds [item] until it lifts, moves it by [by], lets go. +Future _drag(WidgetTester tester, Finder item, Offset by) async { + final gesture = await tester.startGesture(tester.getCenter(item)); + await tester.pump(chatStackLiftDelay + const Duration(milliseconds: 20)); + await gesture.moveBy(by); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); +} + +const _up = Offset(0, -kChatStackPitch); + +/// Makes group "Work" of b and a (a dropped onto b), naming it. +Future _makeWork(WidgetTester tester) async { + await _drag(tester, _chat(tester, 'a'), _up); + expect(find.text('Name the group'), findsOneWidget); + await tester.enterText( + find.byKey(const Key('chat-stack-group-name')), + 'Work', + ); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); +} + +void _act(WidgetTester tester, Finder target, String label) { + final node = tester.getSemantics(target); + final action = node + .getSemanticsData() + .customSemanticsActionIds! + .map(CustomSemanticsAction.getAction) + .firstWhere((action) => action!.label == label)!; + tester.binding.renderViews.first.owner!.semanticsOwner!.performAction( + node.id, + SemanticsAction.customAction, + CustomSemanticsAction.getIdentifier(action), + ); +} + +void main() { + tearDown( + () => MobileChatNavigationController.instance.debugUse( + MobileChatNavigation.quickSwitch, + ), + ); + + testWidgets('a chat dropped onto a chat makes a named group that syncs', ( + tester, + ) async { + final server = await _pump(tester); + // Mid-drag over b's middle: b grows (the drop target). + final gesture = await tester.startGesture( + tester.getCenter(_chat(tester, 'a')), + ); + await tester.pump(chatStackLiftDelay + const Duration(milliseconds: 20)); + final b = tester.getSize(_chat(tester, 'b')); + await gesture.moveBy(_up); + await tester.pumpAndSettle(); + expect( + tester.getRect(_chat(tester, 'b')).width, + closeTo(b.width * chatStackOntoScale, .5), + ); + // The dragged chat shrinks onto it, so the target's ring shows around. + expect( + tester.getRect(_chat(tester, 'a')).width, + closeTo(b.width * chatStackLiftScale * chatStackOverRemoveScale, .5), + ); + await gesture.up(); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('chat-stack-group-name')), + 'Work', + ); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(server.open, ['b', 'a', 'c']); + expect(server.groups, {'b': 'Work', 'a': 'Work'}); + expect(_group('Work'), findsOneWidget); + expect(find.text('Work'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a group opens in place; header, Back and outside return', ( + tester, + ) async { + await _pump(tester); + await _makeWork(tester); + await tester.tap(_group('Work')); + await tester.pumpAndSettle(); + expect(_chat(tester, 'a').hitTestable(), findsOneWidget); + expect(_chat(tester, 'b').hitTestable(), findsOneWidget); + expect(_header.hitTestable(), findsOneWidget); + // The top level's chat c is behind: no input. + expect(_chat(tester, 'c').hitTestable(), findsNothing); + await tester.tap(_header); + await tester.pumpAndSettle(); + expect(_group('Work').hitTestable(), findsOneWidget); + + // Outside: out of the group first, then folded. + await tester.tap(_group('Work')); + await tester.pumpAndSettle(); + await tester.tapAt(const Offset(40, 120)); + await tester.pumpAndSettle(); + expect(_group('Work').hitTestable(), findsOneWidget); + await tester.tapAt(const Offset(40, 120)); + await tester.pumpAndSettle(); + expect(find.byType(ChatStackColumn), findsNothing); + + // Back leaves the group, then folds. + await _expand(tester); + await tester.tap(_group('Work')); + await tester.pumpAndSettle(); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(_group('Work').hitTestable(), findsOneWidget); + // A chat in a group opens as any other. + await tester.tap(_group('Work')); + await tester.pumpAndSettle(); + await tester.tap(_chat(tester, 'b')); + await tester.pumpAndSettle(); + expect(_workspace(tester).activePane?.sessionId, 'b'); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a chat joins a group; a group takes a chat in', (tester) async { + final server = await _pump(tester); + await _makeWork(tester); + // Top level: Work (b, a) at the bottom, c above it. c down onto it. + await _drag(tester, _chat(tester, 'c'), -_up); + expect(server.groups, {'b': 'Work', 'a': 'Work', 'c': 'Work'}); + expect(server.open, ['b', 'a', 'c']); + // Leaving from inside the group: drop on its header. + await tester.tap(_group('Work')); + await tester.pumpAndSettle(); + await _drag(tester, _chat(tester, 'c'), _up); + expect(server.groups, {'b': 'Work', 'a': 'Work'}); + expect(server.open, ['b', 'a', 'c']); + // Back on the top level: drag the group onto c. + await tester.tap(_header); + await tester.pumpAndSettle(); + await _drag(tester, _group('Work'), _up); + expect(server.groups, {'b': 'Work', 'a': 'Work', 'c': 'Work'}); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('the last chat left alone dissolves the group', (tester) async { + final server = await _pump(tester); + await _makeWork(tester); + await tester.tap(_group('Work')); + await tester.pumpAndSettle(); + // a is second in the group: one slot up is the header. + await _drag(tester, _chat(tester, 'a'), _up); + expect(server.groups, isEmpty); + // The group is gone: back on the top level. + expect(_header, findsNothing); + expect(_chat(tester, 'a').hitTestable(), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Rename, Ungroup and Close all; each syncs, Undo restores', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final server = await _pump(tester); + await _makeWork(tester); + _act(tester, _group('Work'), ChatStackGroupAction.rename.label); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('chat-stack-group-name')), + 'Personal', + ); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(server.groups, {'b': 'Personal', 'a': 'Personal'}); + + _act(tester, _group('Personal'), ChatStackGroupAction.ungroup.label); + await tester.pumpAndSettle(); + expect(server.groups, isEmpty); + expect(find.text('Ungrouped Personal'), findsOneWidget); + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(server.groups, {'b': 'Personal', 'a': 'Personal'}); + + await _expand(tester); + _act(tester, _group('Personal'), ChatStackGroupAction.closeAll.label); + await tester.pumpAndSettle(); + expect(server.open, ['c']); + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(server.open, ['b', 'a', 'c']); + expect(server.groups, {'b': 'Personal', 'a': 'Personal'}); + semantics.dispose(); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Move to group and Remove from group as semantic actions', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final server = await _pump(tester); + await _makeWork(tester); + _act(tester, _chat(tester, 'c'), ChatStackColumn.moveToGroupLabel); + await tester.pumpAndSettle(); + await tester.tap(find.text('Work').last); + await tester.pumpAndSettle(); + expect(server.groups['c'], 'Work'); + await tester.tap(_group('Work')); + await tester.pumpAndSettle(); + _act(tester, _chat(tester, 'b'), ChatStackColumn.leaveGroupLabel); + await tester.pumpAndSettle(); + expect(server.groups, {'a': 'Work', 'c': 'Work'}); + expect(server.open, ['a', 'c', 'b']); + semantics.dispose(); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a group dropped on the close button is ungrouped', ( + tester, + ) async { + final server = await _pump(tester); + await _makeWork(tester); + final group = tester.getCenter(_group('Work')); + final close = tester.getCenter( + find.bySemanticsLabel(ChatStackCloseTarget.label), + ); + await _drag(tester, _group('Work'), close - group); + expect(server.groups, isEmpty); + expect(server.open, ['b', 'a', 'c']); + expect(find.text('Ungrouped Work'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('groups from another device appear', (tester) async { + final server = await _pump(tester); + server.change(['a', 'b', 'c'], {'a': 'Home', 'c': 'Home'}); + await tester.pumpAndSettle(); + expect(_group('Home'), findsOneWidget); + expect(find.text('Home'), findsOneWidget); + // The group's pill counts its chats. + expect(find.text('2'), findsWidgets); + await tester.pumpWidget(const SizedBox.shrink()); + }); +} diff --git a/app/test/features/chat/stack/chat_stack_groups_test.dart b/app/test/features/chat/stack/chat_stack_groups_test.dart new file mode 100644 index 00000000..af333502 --- /dev/null +++ b/app/test/features/chat/stack/chat_stack_groups_test.dart @@ -0,0 +1,168 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_drop_target.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_entry.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_group_ops.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_groups.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_node.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_gateway.dart'; + +ChatStackEntry _entry(String id, [String? group]) => + ChatStackEntry(paneId: 'p$id', session: {'id': id}, group: group); + +void main() { + group('ChatStackGroups', () { + test('assigns, merges on rename, dissolves a group of one', () { + final groups = ChatStackGroups(); + var changes = 0; + groups.addListener(() => changes++); + // One chat is no group. + groups.assign(['a'], 'Work'); + expect(groups.assignments, isEmpty); + expect(changes, 0); + groups.assign(['a', 'b'], 'Work'); + groups.assign(['c', 'd'], 'Home'); + expect(groups.membersOf('Work'), ['a', 'b']); + expect(groups.nextName(), 'Group 1'); + groups.rename('Home', 'Work'); + expect(groups.membersOf('Work'), ['a', 'b', 'c', 'd']); + groups.unassign(['a', 'b', 'c']); + expect(groups.assignments, isEmpty); + groups.assign(['a', 'b', 'c'], 'Group 1'); + expect(groups.nextName(), 'Group 2'); + groups.retain({'a', 'x'}); + expect(groups.assignments, isEmpty); + expect(changes, greaterThan(0)); + groups.dispose(); + }); + + test('names are trimmed, bounded and never empty', () { + expect(chatStackGroupName(' Work \n'), 'Work'); + expect(chatStackGroupName(' '), isNull); + expect(chatStackGroupName('a\tb'), 'a b'); + expect(chatStackGroupName('x' * 100)!.length, chatStackGroupNameLimit); + }); + }); + + group('nodes and drops', () { + final entries = [ + _entry('a'), + _entry('b', 'Work'), + _entry('c'), + _entry('d', 'Work'), + ]; + final nodes = chatStackNodes(entries); + + test('a group stands where its first chat is', () { + expect(nodes.map((node) => node.key), [ + 'chat:pa', + 'group:Work', + 'chat:pc', + ]); + expect(chatStackOrder(nodes), ['a', 'b', 'd', 'c']); + // A lone member shows as a chat. + expect( + chatStackNodes([_entry('x', 'Solo')]).single, + isA(), + ); + }); + + test('dropping onto a chat or a group joins as expected', () { + final made = chatStackJoined(nodes, 2, 0, () => 'Group 1'); + expect(made.created, isTrue); + expect(made.join, ['a', 'c']); + expect(made.order, ['a', 'c', 'b', 'd']); + final joined = chatStackJoined(nodes, 0, 1, () => 'unused'); + expect((joined.group, joined.created), ('Work', false)); + expect(joined.join, ['a']); + expect(joined.order, ['b', 'd', 'a', 'c']); + final took = chatStackJoined(nodes, 1, 2, () => 'unused'); + expect(took.join, ['c']); + expect(took.order, ['a', 'b', 'd', 'c']); + expect(chatStackLeft(nodes, 'Work', 'b'), ['a', 'd', 'b', 'c']); + expect(chatStackRegrouped(nodes, 'Work', ['d', 'b']), [ + 'a', + 'd', + 'b', + 'c', + ]); + expect(chatStackMoved(nodes, 0, 2), ['b', 'd', 'c', 'a']); + }); + + test('the middle of an item groups, its edges reorder, stably', () { + bool all(int _) => true; + // From slot 0, one slot up: the middle of item 1. + expect( + chatStackDropTarget( + position: 1, + from: 0, + count: 3, + slot: 0, + canDropOnto: all, + ), + (slot: 0, onto: 1), + ); + // Past its middle: the gap moves above it... + expect( + chatStackDropTarget( + position: 1.4, + from: 0, + count: 3, + slot: 0, + canDropOnto: all, + ), + (slot: 1, onto: null), + ); + // ...and holds there while item 1 slides below it. + expect( + chatStackDropTarget( + position: 1.3, + from: 0, + count: 3, + slot: 1, + canDropOnto: all, + ), + (slot: 1, onto: null), + ); + // Below its middle the gap stays below it. + expect( + chatStackDropTarget( + position: .7, + from: 0, + count: 3, + slot: 0, + canDropOnto: all, + ), + (slot: 0, onto: null), + ); + // Without grouping the middle reorders too; the gap never passes + // lastSlot. + expect( + chatStackDropTarget( + position: 2.3, + from: 0, + count: 3, + slot: 1, + lastSlot: 1, + ), + (slot: 1, onto: null), + ); + }); + }); + + test('an entry carries its group over the wire', () { + final entry = ChatOpenWorkspaceEntry.fromJson({ + 'session_id': 'a', + 'group': ' Work ', + })!; + expect(entry.group, 'Work'); + expect(entry.toJson(), {'session_id': 'a', 'group': 'Work'}); + expect(ChatOpenWorkspaceEntry.fromJson({'session_id': 'b'})!.group, isNull); + const snapshot = ChatOpenWorkspaceSnapshot(1, [ + ChatOpenWorkspaceEntry('a'), + ]); + expect( + snapshot.sameEntries([const ChatOpenWorkspaceEntry('a', group: 'W')]), + isFalse, + ); + }); +} diff --git a/app/test/features/chat/stack/chat_stack_screen_test.dart b/app/test/features/chat/stack/chat_stack_screen_test.dart index 0e970e7a..e2412cfb 100644 --- a/app/test/features/chat/stack/chat_stack_screen_test.dart +++ b/app/test/features/chat/stack/chat_stack_screen_test.dart @@ -34,6 +34,15 @@ class _Gateway extends FakeChatGateway { } } +class _Store implements MobileChatNavigationStore { + _Store(this.value); + final String? value; + @override + Future load() async => value; + @override + Future save(String value) async => true; +} + Future _pump(WidgetTester tester, Size size) async { SharedPreferences.setMockInitialValues({}); unawaited( @@ -114,39 +123,53 @@ void main() { await tester.pumpWidget(const SizedBox.shrink()); }); - testWidgets('long press removes a chat, Undo restores it', (tester) async { - await _pump(tester, const Size(390, 844)); - await tester.tap(find.byKey(const Key('chat-row-a'))); - await tester.pumpAndSettle(); - await tester.tap(_stack); - await tester.pumpAndSettle(); - await tester.tap(find.byKey(const ValueKey('chat-stack-button-add'))); - await tester.pumpAndSettle(); - await tester.tap(find.text('Gamma').last); - await tester.pumpAndSettle(); - expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget); - await tester.tap(_stack); - await tester.pumpAndSettle(); - await tester.longPress(find.text('Alpha').last); - await tester.pumpAndSettle(); - expect(find.text('Removed Alpha from open chats'), findsOneWidget); - expect(find.bySemanticsLabel(chatStackLabel(1)), findsOneWidget); - await tester.tap(find.text('Undo')); - await tester.pumpAndSettle(); - // Gamma stays on screen; Alpha is back in the stack. - expect(_thread('c').hitTestable(), findsOneWidget); - expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget); - await tester.pumpWidget(const SizedBox.shrink()); - }); + testWidgets( + 'a wide desktop window keeps its panes and shows no stack', + variant: TargetPlatformVariant.desktop(), + (tester) async { + await _pump(tester, const Size(1280, 800)); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + expect(_thread('a'), findsOneWidget); + expect(_stack, findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); - testWidgets('a wide window keeps its panes and shows no stack', ( - tester, - ) async { - await _pump(tester, const Size(1280, 800)); - await tester.tap(find.byKey(const Key('chat-row-a'))); - await tester.pumpAndSettle(); - expect(_thread('a'), findsOneWidget); - expect(_stack, findsNothing); - await tester.pumpWidget(const SizedBox.shrink()); + testWidgets( + 'a wide phone or tablet layout (an unfolded foldable) keeps the stack', + variant: TargetPlatformVariant({ + TargetPlatform.android, + TargetPlatform.iOS, + }), + (tester) async { + await _pump(tester, const Size(1280, 800)); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + expect(_thread('a'), findsOneWidget); + // The list stays beside the chat, the stack floats over the pane. + expect(find.byKey(const Key('chat-row-b')), findsOneWidget); + expect(_stack.hitTestable(), findsOneWidget); + await tester.tap(_stack); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('chat-stack-button-add'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Beta').last); + await tester.pumpAndSettle(); + expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + + test('Chat stack is the default without a stored choice', () async { + final controller = MobileChatNavigationController(store: _Store(null)); + expect(controller.value, MobileChatNavigation.chatStack); + await controller.restore(); + expect(controller.value, MobileChatNavigation.chatStack); + final chosen = MobileChatNavigationController(store: _Store('quickSwitch')); + await chosen.restore(); + expect(chosen.value, MobileChatNavigation.quickSwitch); + controller.dispose(); + chosen.dispose(); }); } diff --git a/app/test/features/chat/ui/sessions/chat_sessions_speech_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_speech_test.dart new file mode 100644 index 00000000..47be7a72 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_sessions_speech_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/data/chat_repository.dart'; +import 'package:pipelines_app/features/chat/speech/speech.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart'; + +import '../../speech/fake_speech_engine.dart'; +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +JsonMap _row(String id, {bool closed = false}) => { + 'id': id, + 'title': id, + 'directory': '/w', + if (closed) 'closed_at': '2026-12-03T10:00:00Z', +}; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late FakeChatGateway gateway; + late ChatSessionsController controller; + late SpeechController speech; + + setUp(() async { + speech = installFakeSpeech(FakeSpeechEngine()); + gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [_row('s1'), _row('s2')], + } + ..actionHandler = (_, _) async => const {}; + controller = ChatSessionsController( + ChatRepository(gateway), + localStore: MemoryChatSessionLocalStore(), + ); + addTearDown(controller.dispose); + await controller.refresh(); + await speech.read(speechMessageId('s1', 'r1'), ['Hello.']); + expect(speech.state, SpeechState.speaking); + }); + + test('closing the reading chat stops it', () async { + await controller.close('s1'); + await pumpEventQueue(); + expect(speech.state, SpeechState.idle); + }); + + test('closing another chat keeps reading', () async { + await controller.close('s2'); + await pumpEventQueue(); + expect(speech.state, SpeechState.speaking); + }); + + test('a chat closed on another device stops it on the next read', () async { + gateway.sessionsReply = { + 'chat_sessions': [_row('s1', closed: true), _row('s2')], + }; + await controller.refresh(); + await pumpEventQueue(); + expect(speech.state, SpeechState.idle); + }); + + test('a deleted chat stops it; a failed read does not', () async { + gateway.sessionsHandler = () async => throw StateError('offline'); + await controller.refresh(); + await pumpEventQueue(); + expect(speech.state, SpeechState.speaking); + + gateway + ..sessionsHandler = null + ..sessionsReply = { + 'chat_sessions': [_row('s2')], + }; + await controller.refresh(); + await pumpEventQueue(); + expect(speech.state, SpeechState.idle); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_speaking_badge_test.dart b/app/test/features/chat/ui/sessions/chat_speaking_badge_test.dart new file mode 100644 index 00000000..45adfa2f --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_speaking_badge_test.dart @@ -0,0 +1,104 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/speech/speech.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_awaiting.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_compact_avatar.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_row_content.dart'; + +import '../../speech/fake_speech_engine.dart'; + +const _speaking = Key('chat-row-speaking'); + +Widget _avatars({bool reduceMotion = false}) => MaterialApp( + home: MediaQuery( + data: MediaQueryData(disableAnimations: reduceMotion), + child: const Scaffold( + body: Column( + children: [ + ChatSessionAvatar( + key: Key('one'), + session: {'id': 's1', 'title': 'One'}, + running: true, + awaitingOperator: 2, + ), + ChatSessionAvatar( + key: Key('two'), + session: {'id': 's2', 'title': 'Two'}, + ), + ChatCompactAvatar( + key: Key('two-compact'), + sessionId: 's2', + title: 'Two', + color: Colors.blue, + active: false, + visible: false, + running: false, + backgroundTasks: 0, + unread: false, + ), + ], + ), + ), + ), +); + +Finder _badgeOf(String avatar) => find.descendant( + of: find.byKey(Key(avatar)), + matching: find.byKey(_speaking), +); + +Future _read(WidgetTester tester, SpeechController speech, String chat) => + tester.runAsync(() => speech.read(speechMessageId(chat, 'r1'), ['Hi.'])); + +void main() { + testWidgets('the reading chat wears the speaking badge, and it moves', ( + tester, + ) async { + final speech = installFakeSpeech(FakeSpeechEngine()); + await tester.pumpWidget(_avatars()); + expect(find.byKey(_speaking), findsNothing); + + await _read(tester, speech, 's1'); + await tester.pump(); + expect(_badgeOf('one'), findsOneWidget); + expect(_badgeOf('two'), findsNothing); + expect(_badgeOf('two-compact'), findsNothing); + // Speaking outranks the operator wait and the running spinner. + expect(find.byKey(const Key('chat-row-working')), findsNothing); + expect(find.byType(ChatAwaitingBadge), findsNothing); + + await _read(tester, speech, 's2'); + await tester.pump(); + expect(_badgeOf('one'), findsNothing); + expect(_badgeOf('two'), findsOneWidget); + expect(_badgeOf('two-compact'), findsOneWidget); + expect(find.byKey(const Key('chat-speaking-wave')), findsNWidgets(2)); + + await tester.runAsync(speech.stop); + await tester.pump(); + expect(find.byKey(_speaking), findsNothing); + }); + + testWidgets('a Settings voice sample marks no chat', (tester) async { + final speech = installFakeSpeech(FakeSpeechEngine()); + await tester.pumpWidget(_avatars()); + await tester.runAsync(speech.sample); + await tester.pump(); + expect(speech.state, SpeechState.speaking); + expect(find.byKey(_speaking), findsNothing); + }); + + testWidgets('reduced motion shows a still speaker', (tester) async { + final speech = installFakeSpeech(FakeSpeechEngine()); + await tester.pumpWidget(_avatars(reduceMotion: true)); + // The first chat's spinner gives way to the speaking badge. + await _read(tester, speech, 's1'); + await tester.pump(); + expect(_badgeOf('one'), findsOneWidget); + expect(find.byKey(const Key('chat-speaking-still')), findsOneWidget); + expect(find.byKey(const Key('chat-speaking-wave')), findsNothing); + // Nothing ticks: settling finishes with the badge still shown. + await tester.pumpAndSettle(); + expect(_badgeOf('one'), findsOneWidget); + }); +} diff --git a/app/test/features/chat/workspace/chat_pane_cycle_test.dart b/app/test/features/chat/workspace/chat_pane_cycle_test.dart new file mode 100644 index 00000000..ea0caf10 --- /dev/null +++ b/app/test/features/chat/workspace/chat_pane_cycle_test.dart @@ -0,0 +1,122 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_pane_cycle.dart'; + +KeyEvent _down( + PhysicalKeyboardKey physical, + LogicalKeyboardKey logical, { + String? character, +}) => KeyDownEvent( + physicalKey: physical, + logicalKey: logical, + character: character, + timeStamp: Duration.zero, +); + +final _right = _down( + PhysicalKeyboardKey.bracketRight, + LogicalKeyboardKey.bracketRight, +); +final _left = _down( + PhysicalKeyboardKey.bracketLeft, + LogicalKeyboardKey.bracketLeft, +); + +int? _step( + KeyEvent event, + Set held, [ + TargetPlatform platform = TargetPlatform.linux, +]) => chatPaneCycleShortcut(event, _FakeKeyboard(held), platform: platform); + +void main() { + test('Alt+] goes forward and Alt+[ back on every platform', () { + for (final platform in TargetPlatform.values) { + expect(_step(_right, {LogicalKeyboardKey.altLeft}, platform), 1); + expect(_step(_left, {LogicalKeyboardKey.altLeft}, platform), -1); + } + }); + + test('Option+] types a quote on a Mac: it matches by key position', () { + final quote = _down( + PhysicalKeyboardKey.bracketRight, + const LogicalKeyboardKey(0x2018), + character: '‘', + ); + expect(_step(quote, {LogicalKeyboardKey.altLeft}, TargetPlatform.macOS), 1); + }); + + test('Cmd+] and Cmd+[ only on Apple platforms', () { + expect( + _step(_right, {LogicalKeyboardKey.metaLeft}, TargetPlatform.macOS), + 1, + ); + expect(_step(_left, {LogicalKeyboardKey.metaLeft}, TargetPlatform.iOS), -1); + expect(_step(_right, {LogicalKeyboardKey.metaLeft}), isNull); + expect( + _step(_right, {LogicalKeyboardKey.metaLeft}, TargetPlatform.windows), + isNull, + ); + }); + + test('plain brackets type; Shift, Ctrl, AltGr and key-up do not match', () { + expect(_step(_right, {}), isNull); + for (final extra in [ + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.altGraph, + ]) { + expect( + _step(_right, {LogicalKeyboardKey.altLeft, extra}), + isNull, + reason: '$extra', + ); + } + expect( + _step( + const KeyUpEvent( + physicalKey: PhysicalKeyboardKey.bracketRight, + logicalKey: LogicalKeyboardKey.bracketRight, + timeStamp: Duration.zero, + ), + {LogicalKeyboardKey.altLeft}, + ), + isNull, + ); + // A key typing "[" elsewhere on the keyboard is not the chord. + expect( + _step(_down(PhysicalKeyboardKey.digit8, LogicalKeyboardKey.bracketLeft), { + LogicalKeyboardKey.altLeft, + }), + isNull, + ); + }); + + test('labels name the chords this platform answers', () { + expect(chatPaneCycleShortcutLabel(TargetPlatform.linux), 'Alt+], Alt+['); + expect(chatPaneCycleShortcutLabel(TargetPlatform.windows), 'Alt+], Alt+['); + expect( + chatPaneCycleShortcutLabel(TargetPlatform.macOS), + 'Option+], Option+[, Cmd+], Cmd+[', + ); + }); + + test('targets wrap both ways; one entry or none has no target', () { + const order = ['a', 'b', 'c']; + expect(chatPaneCycleTarget(order, 0, 1), 'b'); + expect(chatPaneCycleTarget(order, 2, 1), 'a'); + expect(chatPaneCycleTarget(order, 0, -1), 'c'); + expect(chatPaneCycleTarget(order, 1, -1), 'a'); + expect(chatPaneCycleTarget(order, -1, 1), 'a'); + expect(chatPaneCycleTarget(order, -1, -1), 'c'); + expect(chatPaneCycleTarget(['a'], 0, 1), isNull); + expect(chatPaneCycleTarget([], -1, 1), isNull); + }); +} + +class _FakeKeyboard extends HardwareKeyboard { + _FakeKeyboard(this.pressed); + final Set pressed; + @override + bool isLogicalKeyPressed(LogicalKeyboardKey key) => pressed.contains(key); +} diff --git a/app/test/features/graph/domain/stage_summary_test.dart b/app/test/features/graph/domain/stage_summary_test.dart new file mode 100644 index 00000000..6a6dfc9f --- /dev/null +++ b/app/test/features/graph/domain/stage_summary_test.dart @@ -0,0 +1,84 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/features/graph/domain/stage_run_facts.dart'; +import 'package:pipelines_app/features/graph/domain/stage_summary.dart'; + +void main() { + test('a model stage with no tools block runs the default tools', () { + final summary = stageSummaryFor({ + 'stages': [ + {'key': 'a', 'prompt': 'Do it', 'edges': {}}, + ], + }, 'a')!; + expect(summary.kind, StageKind.model); + expect(summary.tools, defaultStageTools); + expect(summary.toolsDefault, isTrue); + expect(summary.prompt, 'Do it'); + }); + + test('a delivery check reads as the delivery gate with its commands', () { + final summary = stageSummaryFor({ + 'stages': [ + { + 'key': 'land', + 'type': 'check', + 'configs': {'delivery': 'true', 'command_timeout': '10m'}, + 'blocks': {'commands': 'make test\n\nmake lint'}, + 'edges': {'pass': '#success'}, + }, + ], + }, 'land')!; + expect(summary.typeLabel, 'Delivery gate'); + expect(summary.commands, ['make test', 'make lint']); + expect(summary.tools, isEmpty); + expect(summary.prompt, isNull); + expect(summary.meta, ['10m timeout']); + expect(summary.routes.single, (outcome: 'pass', target: 'Success')); + }); + + test('an undeclared stage has no summary; a terminal lists routes in', () { + final graph = { + 'stages': [ + { + 'key': 'a', + 'edges': {'success': '#success'}, + }, + ], + }; + expect(stageSummaryFor(graph, 'missing'), isNull); + final end = stageSummaryFor(graph, '#success')!; + expect(end.kind, StageKind.terminal); + expect(end.routes.single, (outcome: 'success', target: 'a')); + }); + + test('short model names drop the vendor and date', () { + expect( + shortModelName('anthropic/claude-opus-4-1-20250805'), + 'claude-opus-4-1', + ); + expect(shortModelName('gpt-5'), 'gpt-5'); + }); + + test('an unvisited stage has no run facts', () { + final facts = stageRunFacts({'steps': []}, 'a'); + expect(facts.visits, 0); + expect(facts.status, isNull); + }); + + test('a failure reason is read only from a failed latest visit', () { + final facts = stageRunFacts({ + 'steps': [ + {'sequence': 1, 'stage': 'a', 'status': 'failed', 'diagnostic': 'boom'}, + { + 'sequence': 2, + 'stage': 'a', + 'status': 'completed', + 'diagnostic': 'old', + }, + ], + }, 'a'); + expect(facts.visits, 2); + expect(facts.status, 'completed'); + expect(facts.failure, isNull); + }); +} diff --git a/app/test/features/graph/viewport/graph_expanded_view_test.dart b/app/test/features/graph/viewport/graph_expanded_view_test.dart index 84c680e4..c85947fc 100644 --- a/app/test/features/graph/viewport/graph_expanded_view_test.dart +++ b/app/test/features/graph/viewport/graph_expanded_view_test.dart @@ -96,8 +96,13 @@ void main() { // A tap in the larger canvas follows the same transform and updates the // presentation's own selection. + // The tap opens the stage's popover; its "Open definition" reports it. await tester.tap(_inExpanded(_node('plan'))); await tester.pump(); + expect(picked, isEmpty); + expect(find.byKey(const Key('graph-stage-popover')), findsOneWidget); + await tester.tap(find.byKey(const Key('stage-popover-open-definition'))); + await tester.pump(); expect(picked, ['plan']); expect( tester.widget(_inExpanded(_node('plan'))).selected, diff --git a/app/test/features/graph/widgets/definition_graph_view_test.dart b/app/test/features/graph/widgets/definition_graph_view_test.dart index d80fda54..0dee6ec7 100644 --- a/app/test/features/graph/widgets/definition_graph_view_test.dart +++ b/app/test/features/graph/widgets/definition_graph_view_test.dart @@ -98,6 +98,14 @@ Future _tapNode(WidgetTester tester, String key) async { await tester.pump(); } +/// Taps a node, then its popover's "Open definition", which reports the key. +Future _openDefinition(WidgetTester tester, String key) async { + await _tapNode(tester, key); + expect(find.byKey(const Key('graph-stage-popover')), findsOneWidget); + await tester.tap(find.byKey(const Key('stage-popover-open-definition'))); + await tester.pump(); +} + void _expectNoOverlaps(WidgetTester tester) { final rects = [ for (final element in find.byType(GraphStageNode).evaluate()) @@ -148,11 +156,10 @@ void main() { expect(tester.widget(_node('build')).selected, isTrue); expect(tester.widget(_node('plan')).selected, isFalse); - await tester.tap(_node('plan')); - await tester.pump(); + await _openDefinition(tester, 'plan'); expect(picked, ['plan']); - await _tapNode(tester, '#success'); + await _openDefinition(tester, '#success'); expect(picked, ['plan', '#success']); }); @@ -189,7 +196,10 @@ void main() { ); await tester.tapAt(build.center); await tester.pump(); - expect(picked, ['build']); + expect( + tester.widget(find.byKey(const Key('stage-popover-title'))).data, + 'build', + ); }); testWidgets('nodes use measured native sizes and never overlap', ( diff --git a/app/test/features/graph/widgets/graph_stage_popover_test.dart b/app/test/features/graph/widgets/graph_stage_popover_test.dart new file mode 100644 index 00000000..33ca3882 --- /dev/null +++ b/app/test/features/graph/widgets/graph_stage_popover_test.dart @@ -0,0 +1,369 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart'; +import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; +import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart'; +import 'package:pipelines_app/features/graph/widgets/stage_popover_position.dart'; + +/// One stage of every type, with the fields the popover shows. +JsonMap _graph() => { + 'stages': [ + { + 'key': 'implement', + 'type': 'model', + 'prompt': 'Implement the feature.\n\nKeep the change small.', + 'configs': { + 'harness': 'claude', + 'model': 'anthropic/claude-sonnet-4-5-20250929', + 'reasoning_effort': 'high', + 'timeout': '30m', + 'retries': '2', + 'budget_usd': '5', + }, + 'blocks': { + 'tools': 'read\nglob\nedit\nshell\nmcp:pipelines', + 'permissions': '{"edit": ["app/**"], "shell": ["flutter test"]}', + }, + 'limits': { + 'max_visits': 3, + 'on': ['fail'], + 'on_exhausted': 'decide', + }, + 'edges': {'success': 'verify', 'error': '#failure'}, + }, + { + 'key': 'verify', + 'type': 'check', + 'blocks': {'commands': 'flutter analyze\nflutter test'}, + 'edges': { + 'pass': 'triage', + 'fail': 'implement', + 'error': '#failure', + }, + }, + { + 'key': 'triage', + 'type': 'findings', + 'configs': {'severity': 'critical', 'origin': 'any'}, + 'edges': {'open': 'approve', 'clear': '#success'}, + }, + { + 'key': 'approve', + 'type': 'human', + 'prompt': 'Check the screenshots before landing.', + 'edges': {'accept': '#success', 'reject': 'implement'}, + }, + ], +}; + +JsonMap _run() => { + 'id': 7, + 'pipeline_id': 3, + 'name': 'feature', + 'version': 4, + 'steps': [ + { + 'sequence': 1, + 'stage': 'implement', + 'status': 'completed', + 'outcome': 'success', + 'target': 'verify', + 'started_at': '2026-10-21T10:00:00Z', + 'finished_at': '2026-10-21T10:01:00Z', + }, + { + 'sequence': 2, + 'stage': 'verify', + 'status': 'failed', + 'outcome': 'fail', + 'target': 'implement', + 'diagnostic': 'flutter test: 2 failures', + }, + { + 'sequence': 3, + 'stage': 'implement', + 'status': 'completed', + 'outcome': 'success', + 'target': 'verify', + 'started_at': '2026-10-21T10:02:00Z', + 'finished_at': '2026-10-21T10:04:05Z', + 'output': '# Fixed the two failing tests\nmore detail', + 'verdict': {'option': 'success', 'reason': 'All green'}, + }, + ], + 'current_stage': '', + 'executing': false, +}; + +Widget _host(Widget child, {Size size = const Size(1000, 760)}) => MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: size.width, height: size.height, child: child), + ), + ), +); + +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(); + await tester.pump(); +} + +Finder _node(String key) => find.byWidgetPredicate( + (widget) => widget is GraphStageNode && widget.node.key == key, +); + +final Finder _popover = find.byKey(const Key('graph-stage-popover')); + +String _title(WidgetTester tester) => + tester.widget(find.byKey(const Key('stage-popover-title'))).data!; + +Future _view( + WidgetTester tester, { + ValueChanged? onSelected, + Size size = const Size(1000, 760), +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + _host( + DefinitionGraphView(graph: _graph(), onSelected: onSelected ?? (_) {}), + size: size, + ), + ); + await _settle(tester); +} + +void main() { + testWidgets('a model stage shows its type, configs, tools and prompt', ( + tester, + ) async { + await _view(tester); + expect(_popover, findsNothing); + + await tester.tap(_node('implement')); + await tester.pump(); + + expect(_popover, findsOneWidget); + expect(_title(tester), 'implement'); + expect(find.text('Model'), findsOneWidget); + for (final chip in [ + 'claude', + 'claude-sonnet-4-5', + 'high effort', + '30m timeout', + '2 retries', + r'$5 budget', + 'mcp:pipelines', + 'max 3 visits', + 'on fail', + 'when exhausted: decide', + ]) { + expect(find.text(chip), findsOneWidget, reason: chip); + } + for (final route in ['success to verify', 'error to Failure']) { + expect(find.bySemanticsLabel(route), findsOneWidget, reason: route); + } + expect(find.textContaining('Implement the feature.'), findsOneWidget); + // The permission allow-lists stay behind a collapsed line. + expect( + find.byKey(const Key('stage-popover-permission-lines')), + findsNothing, + ); + await tester.tap(find.byKey(const Key('stage-popover-permissions'))); + await tester.pump(); + expect( + tester + .widget(find.byKey(const Key('stage-popover-permission-lines'))) + .data, + 'edit: app/**\nshell: flutter test', + ); + // The node is the open selection while its popover shows. + expect(tester.widget(_node('implement')).selected, isTrue); + }); + + testWidgets('a check stage lists its commands instead of a prompt', ( + tester, + ) async { + await _view(tester); + await tester.tap(_node('verify')); + await tester.pump(); + expect(find.text('Check'), findsWidgets); + expect(find.byKey(const Key('stage-popover-commands')), findsOneWidget); + expect(find.byKey(const Key('stage-popover-prompt')), findsNothing); + final commands = tester.widget( + find.byKey(const Key('stage-popover-commands')), + ); + expect(commands.textSpan!.toPlainText(), contains('flutter analyze')); + expect(find.bySemanticsLabel('fail to implement'), findsOneWidget); + }); + + testWidgets('a findings gate shows severity and origin', (tester) async { + await _view(tester); + await tester.tap(_node('triage')); + await tester.pump(); + expect(find.text('Findings gate'), findsOneWidget); + expect(find.text('min severity critical'), findsOneWidget); + expect(find.text('origin any'), findsOneWidget); + }); + + testWidgets('a human stage shows the operator instructions', (tester) async { + await _view(tester); + await tester.tap(_node('approve')); + await tester.pump(); + expect(find.text('Human'), findsOneWidget); + expect(find.text('Operator instructions'), findsOneWidget); + expect( + find.textContaining('Check the screenshots before landing.'), + findsOneWidget, + ); + }); + + testWidgets('the card sits inside the viewport with its nub on the node', ( + tester, + ) async { + await _view(tester); + await tester.tap(_node('verify')); + await tester.pump(); + final card = tester.getRect(find.byKey(const Key('stage-popover-body'))); + final viewport = tester.getRect(find.byType(InteractiveViewer)); + expect(viewport.inflate(1).contains(card.topLeft), isTrue); + expect(viewport.inflate(1).contains(card.bottomRight), isTrue); + final position = tester.renderObject(_popover); + expect(position.side, isNot(StagePopoverSide.over)); + }); + + testWidgets('an outside tap, Escape and the same node close it', ( + tester, + ) async { + await _view(tester); + await tester.tap(_node('implement')); + await tester.pump(); + expect(_popover, findsOneWidget); + + // Tapping inside the card keeps it open. + await tester.tap(find.byKey(const Key('stage-popover-title'))); + await tester.pump(); + expect(_popover, findsOneWidget); + + // An outside tap on the empty canvas closes it. + final viewport = tester.getRect(find.byType(InteractiveViewer)); + await tester.tapAt(viewport.bottomRight - const Offset(10, 10)); + await tester.pump(); + expect(_popover, findsNothing); + + // A drag pans the graph but keeps the card on its node. + await tester.tap(_node('implement')); + await tester.pump(); + await tester.dragFrom( + viewport.bottomRight - const Offset(40, 40), + const Offset(-60, -20), + ); + await tester.pump(); + expect(_popover, findsOneWidget); + + // Escape closes it. + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(_popover, findsNothing); + + // Tapping the same node again toggles it shut. + await tester.tap(_node('implement')); + await tester.pump(); + expect(_popover, findsOneWidget); + await tester.tap(_node('implement')); + await tester.pump(); + expect(_popover, findsNothing); + + // Another node replaces it. + await tester.tap(_node('triage')); + await tester.pump(); + expect(_title(tester), 'triage'); + await tester.tap(_node('implement')); + await tester.pump(); + expect(_title(tester), 'implement'); + }); + + testWidgets('Open definition reports the stage and closes the card', ( + tester, + ) async { + final opened = []; + await _view(tester, onSelected: opened.add); + await tester.tap(_node('approve')); + await tester.pump(); + await tester.tap(find.byKey(const Key('stage-popover-open-definition'))); + await tester.pump(); + expect(opened, ['approve']); + expect(_popover, findsNothing); + }); + + testWidgets('a focused node opens with Enter', (tester) async { + await _view(tester); + // The node's own focus: the nearest focus above its label. + final label = find + .descendant(of: _node('triage'), matching: find.byType(Text)) + .first; + Focus.of(tester.element(label)).requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + expect(_popover, findsOneWidget); + expect(_title(tester), 'triage'); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(_popover, findsNothing); + }); + + testWidgets('a phone-width graph opens the stage in a bottom sheet', ( + tester, + ) async { + await _view(tester, size: const Size(390, 760)); + await tester.tap(_node('implement')); + await tester.pumpAndSettle(); + expect(_popover, findsNothing); + expect(find.byKey(const Key('graph-stage-sheet')), findsOneWidget); + expect(_title(tester), 'implement'); + expect(find.text('claude-sonnet-4-5'), findsOneWidget); + }); + + testWidgets('the run variant shows status, visits, verdict and failure', ( + tester, + ) async { + tester.view.physicalSize = const Size(1000, 760); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final visits = []; + await tester.pumpWidget( + _host( + RunGraphView(graph: _graph(), run: _run(), onStageSelected: visits.add), + ), + ); + await _settle(tester); + + await tester.tap(_node('implement')); + await tester.pump(); + expect(find.text('completed'), findsWidgets); + expect(find.text('×2'), findsOneWidget); + expect(find.text('2m 5s'), findsOneWidget); + expect(find.text('success: All green'), findsOneWidget); + expect(find.text('Fixed the two failing tests'), findsOneWidget); + await tester.tap(find.byKey(const Key('stage-popover-open-visit'))); + await tester.pump(); + expect(visits, ['implement']); + + await tester.tap(_node('verify')); + await tester.pump(); + expect(find.text('×1'), findsOneWidget); + expect(find.text('flutter test: 2 failures'), findsOneWidget); + + // Open definition pushes the pinned stage definition page. + await tester.tap(find.byKey(const Key('stage-popover-open-definition'))); + await tester.pumpAndSettle(); + expect(find.text('verify definition'), findsOneWidget); + }); +} diff --git a/app/test/features/graph/widgets/run_graph_view_test.dart b/app/test/features/graph/widgets/run_graph_view_test.dart index ac47e2af..280622d8 100644 --- a/app/test/features/graph/widgets/run_graph_view_test.dart +++ b/app/test/features/graph/widgets/run_graph_view_test.dart @@ -260,7 +260,7 @@ void main() { }); testWidgets( - 'a visited stage reports its key and an unvisited node does not', + 'a visited stage opens its visit from the popover; an unvisited one has none', (tester) async { final picked = []; await tester.pumpWidget( @@ -278,28 +278,26 @@ void main() { final visited = tester.getSemantics(_node('plan')).getSemanticsData(); expect(visited.flagsCollection.isButton, isTrue); expect(visited.hasAction(SemanticsAction.tap), isTrue); + // An unvisited stage still opens its declaration, with no status. final unvisited = tester.getSemantics(_node('build')).getSemanticsData(); - expect(unvisited.flagsCollection.isButton, isFalse); - expect(unvisited.hasAction(SemanticsAction.tap), isFalse); + expect(unvisited.flagsCollection.isButton, isTrue); expect(unvisited.label, 'build'); + await tester.tap(_node('plan')); await tester.pump(); + expect(picked, isEmpty); + await tester.tap(find.byKey(const Key('stage-popover-open-visit'))); + await tester.pump(); expect(picked, ['plan']); - // `build` was never recorded in this run: it is a plain label, not a - // button, and tapping it reports nothing (never a fabricated visit). - await tester.tap(_node('build'), warnIfMissed: false); + // `build` was never recorded in this run: its popover offers no visit, + // so nothing is ever fabricated. + await tester.tap(_node('build')); await tester.pump(); + expect(find.byKey(const Key('graph-stage-popover')), findsOneWidget); + expect(find.byKey(const Key('stage-popover-open-visit')), findsNothing); + expect(find.byKey(const Key('stage-popover-status')), findsNothing); expect(picked, ['plan']); - expect( - find.ancestor( - of: _node('build'), - matching: find.byWidgetPredicate( - (widget) => widget is IgnorePointer && widget.ignoring, - ), - ), - findsOneWidget, - ); handle.dispose(); }, ); diff --git a/app/test/features/pipelines/pipeline_graph_expand_test.dart b/app/test/features/pipelines/pipeline_graph_expand_test.dart index 570cda80..23d0f0be 100644 --- a/app/test/features/pipelines/pipeline_graph_expand_test.dart +++ b/app/test/features/pipelines/pipeline_graph_expand_test.dart @@ -30,6 +30,10 @@ Future _tapNode(WidgetTester tester, Finder node) async { await tester.pumpAndSettle(); } await tester.tap(node); + await tester.pump(); // A tap opens the stage's popover (or sheet); "Open definition" opens the + // pinned definition page, as a tap did before the popover. + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('stage-popover-open-definition'))); await tester.pump(); } diff --git a/app/test/features/pipelines/pipeline_graph_tab_test.dart b/app/test/features/pipelines/pipeline_graph_tab_test.dart index c32af319..5e2d7fa8 100644 --- a/app/test/features/pipelines/pipeline_graph_tab_test.dart +++ b/app/test/features/pipelines/pipeline_graph_tab_test.dart @@ -25,6 +25,10 @@ Future _tapNode(WidgetTester tester, String key) async { await tester.pumpAndSettle(); } await tester.tap(_node(key)); + await tester.pump(); // A tap opens the stage's popover (or sheet); "Open definition" opens the + // pinned definition page, as a tap did before the popover. + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('stage-popover-open-definition'))); await tester.pump(); } diff --git a/app/test/features/runs/ui/run_detail_deep_link_test.dart b/app/test/features/runs/ui/run_detail_deep_link_test.dart index d4bcb4ae..bb7e2a83 100644 --- a/app/test/features/runs/ui/run_detail_deep_link_test.dart +++ b/app/test/features/runs/ui/run_detail_deep_link_test.dart @@ -182,7 +182,7 @@ void main() { ) async { await pumpDeepLink(tester, RunDetailTestPlatform.material); await openRunDetailTab(tester, RunDetailTab.graph); - await tapGraphNode(tester, 'plan'); + await openGraphVisit(tester, 'plan'); await tester.pumpAndSettle(); // The web client's graph click takes the last visit in sequence order, not diff --git a/app/test/features/runs/ui/run_detail_graph_support.dart b/app/test/features/runs/ui/run_detail_graph_support.dart index 41ec19e4..b9ea059b 100644 --- a/app/test/features/runs/ui/run_detail_graph_support.dart +++ b/app/test/features/runs/ui/run_detail_graph_support.dart @@ -156,3 +156,11 @@ Future tapGraphNode(WidgetTester tester, String key) async { await tester.pump(); await tester.pump(); } + +/// Opens [key]'s stage popover (or sheet), then its "Open visit". +Future openGraphVisit(WidgetTester tester, String key) async { + await tapGraphNode(tester, key); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('stage-popover-open-visit'))); + await tester.pump(); +} diff --git a/app/test/features/runs/ui/run_detail_graph_tab_test.dart b/app/test/features/runs/ui/run_detail_graph_tab_test.dart index b92a7bf7..a145d8c9 100644 --- a/app/test/features/runs/ui/run_detail_graph_tab_test.dart +++ b/app/test/features/runs/ui/run_detail_graph_tab_test.dart @@ -46,7 +46,7 @@ void main() { ) async { await pumpRunDetail(tester, platform); await openRunDetailTab(tester, RunDetailTab.graph); - await tapGraphNode(tester, 'plan'); + await openGraphVisit(tester, 'plan'); await tester.pumpAndSettle(); // The Graph reports the stage; the exact recorded visit opens as its @@ -76,9 +76,11 @@ void main() { ) async { await pumpRunDetail(tester, platform); await openRunDetailTab(tester, RunDetailTab.graph); - // `audit` was never recorded: its node is not a control and a click must - // leave the detail on the Graph tab. + // `audit` was never recorded: its popover shows the declaration but + // offers no visit, and the detail stays on the Graph tab. await tapGraphNode(tester, 'audit'); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('stage-popover-open-visit')), findsNothing); expect(find.byType(RunGraphView), findsOneWidget); expect( find.byKey(const Key('run-detail-tab-body-timeline')), @@ -96,7 +98,7 @@ void main() { scale: 2, ); await openRunDetailTab(tester, RunDetailTab.graph); - await tapGraphNode(tester, 'plan'); + await openGraphVisit(tester, 'plan'); await tester.pumpAndSettle(); // Leaving the visit page lands on Timeline. At 320/2x the strip diff --git a/app/test/features/settings/keyboard_shortcuts_filter_test.dart b/app/test/features/settings/keyboard_shortcuts_filter_test.dart index 586beb33..ff94aed7 100644 --- a/app/test/features/settings/keyboard_shortcuts_filter_test.dart +++ b/app/test/features/settings/keyboard_shortcuts_filter_test.dart @@ -24,8 +24,13 @@ void main() { }); test('scattered letters in a long note do not match', () { - // `float` occurs only as scattered letters in other entries' notes. - expect(actions('float'), everyElement(contains('floating'))); + // `float` occurs as scattered letters in many entries' notes; only the + // entries that say "floating" match. + final found = [ + for (final match in filterShortcuts(registry.entries, 'float')) + '${match.entry.action} ${match.entry.caveat ?? ''}', + ]; + expect(found, everyElement(contains('floating'))); }); test('keys are searchable with or without the plus', () { diff --git a/app/test/features/settings/settings_chat_navigation_section_test.dart b/app/test/features/settings/settings_chat_navigation_section_test.dart index 994de1ac..1167b8f0 100644 --- a/app/test/features/settings/settings_chat_navigation_section_test.dart +++ b/app/test/features/settings/settings_chat_navigation_section_test.dart @@ -32,19 +32,20 @@ void main() { ), ); expect(find.text(SettingsChatNavigationSection.title), findsOneWidget); - expect(controller.value, MobileChatNavigation.quickSwitch); + // Without a stored choice: the Chat stack. + expect(controller.value, MobileChatNavigation.chatStack); expect( - find.text(MobileChatNavigation.quickSwitch.description), + find.text(MobileChatNavigation.chatStack.description), findsOneWidget, ); await tester.tap( - find.byKey(const ValueKey('settings-chat-navigation-chatStack')), + find.byKey(const ValueKey('settings-chat-navigation-quickSwitch')), ); await tester.pumpAndSettle(); - expect(controller.value, MobileChatNavigation.chatStack); - expect(store.saved, 'chatStack'); + expect(controller.value, MobileChatNavigation.quickSwitch); + expect(store.saved, 'quickSwitch'); expect( - find.text(MobileChatNavigation.chatStack.description), + find.text(MobileChatNavigation.quickSwitch.description), findsOneWidget, ); @@ -52,11 +53,11 @@ void main() { final next = MobileChatNavigationController(store: store); addTearDown(next.dispose); await next.restore(); - expect(next.value, MobileChatNavigation.chatStack); + expect(next.value, MobileChatNavigation.quickSwitch); store.success = false; await tester.tap( - find.byKey(const ValueKey('settings-chat-navigation-quickSwitch')), + find.byKey(const ValueKey('settings-chat-navigation-chatStack')), ); await tester.pumpAndSettle(); expect(find.text('Could not save; applies until reload.'), findsOneWidget); diff --git a/app/test/features/settings/settings_design_section_test.dart b/app/test/features/settings/settings_design_section_test.dart index 7ca1d5bd..74da212b 100644 --- a/app/test/features/settings/settings_design_section_test.dart +++ b/app/test/features/settings/settings_design_section_test.dart @@ -117,4 +117,40 @@ void main() { await next.restore(); expect(next.design, AppDesign.paper); }); + + testWidgets('choosing Compact stores it, densifies the page live, draws ' + 'a denser swatch and is restored on the next launch', (tester) async { + final store = MemoryAppDesignStore(); + final designs = AppDesignController(store: store); + await _pump(tester, designs); + + final swatch = tester.widget( + find.descendant( + of: find.byKey(settingsDesignKey(AppDesign.compact)), + matching: find.byType(DesignSwatchPreview), + ), + ); + expect(swatch.lines, greaterThan(2)); + expect(find.text(AppDesign.compact.description), findsOneWidget); + final before = tester.getSize( + find.byKey(settingsDesignKey(AppDesign.paper)), + ); + + await tester.tap(find.text(AppDesign.compact.label)); + await tester.pumpAndSettle(); + expect(store.id, 'compact'); + expect(designs.design, AppDesign.compact); + final tokens = _tokens(tester); + expect(tokens.density.dense, isTrue); + expect(tokens.transcript, TranscriptStyle.bubbles); + // The rows themselves tighten at once. + final after = tester.getSize( + find.byKey(settingsDesignKey(AppDesign.paper)), + ); + expect(after.height, lessThan(before.height)); + + final next = AppDesignController(store: MemoryAppDesignStore(store.id)); + await next.restore(); + expect(next.design, AppDesign.compact); + }); } diff --git a/app/test/features/settings/settings_device_delivery_section_test.dart b/app/test/features/settings/settings_device_delivery_section_test.dart index 42fba51f..5998ead5 100644 --- a/app/test/features/settings/settings_device_delivery_section_test.dart +++ b/app/test/features/settings/settings_device_delivery_section_test.dart @@ -27,7 +27,7 @@ bool _switchValue(WidgetTester tester) { } void main() { - testWidgets('shows the switch, status and ntfy note', (tester) async { + testWidgets('shows the switch, status and delivery note', (tester) async { final service = FakeNotificationService(); await tester.pumpWidget(_host(service)); await tester.pumpAndSettle(); diff --git a/app/test/features/settings/settings_ntfy_section_test.dart b/app/test/features/settings/settings_notification_settings_section_test.dart similarity index 59% rename from app/test/features/settings/settings_ntfy_section_test.dart rename to app/test/features/settings/settings_notification_settings_section_test.dart index 0b06850a..c45a7279 100644 --- a/app/test/features/settings/settings_ntfy_section_test.dart +++ b/app/test/features/settings/settings_notification_settings_section_test.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/core/transport/connection_state.dart'; -import 'package:pipelines_app/features/settings/settings_ntfy_section.dart'; +import 'package:pipelines_app/features/settings/settings_notification_settings_section.dart'; /// A scripted gateway: records every request and answers from [respond]. class _Gateway implements ApiGateway { @@ -32,24 +32,31 @@ JsonMap _reply(bool run, bool needs, bool reply) => { }, }; -Widget _host(ApiGateway gateway) { +Widget _host(ApiGateway gateway, {bool connected = true}) { final body = SingleChildScrollView( - child: SettingsNtfySection(gateway: gateway, connected: true), + child: SettingsNotificationSettingsSection( + gateway: gateway, + connected: connected, + ), ); return MaterialApp(home: Scaffold(body: body)); } -bool _checked(WidgetTester tester, String key) { - final tile = find.byKey(ntfySettingKey(key)); - return tester.widget(tile).value!; -} +Finder _tile(String key) => find.byKey(notificationSettingKey(key)); + +bool _checked(WidgetTester tester, String key) => + tester.widget(_tile(key)).value!; void main() { - testWidgets('loads the stored values', (tester) async { + testWidgets('shows the three shared switches with stored values', ( + tester, + ) async { final gateway = _Gateway((_, _) => _reply(true, false, true)); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); expect(gateway.calls.single.$1, 'notification_settings'); + expect(find.text(notificationEventsTitle), findsOneWidget); + expect(find.text(notificationEventsSubtitle), findsOneWidget); expect(find.text('Notify when any run ends'), findsOneWidget); expect( find.text('Otherwise only runs started with Notify me'), @@ -57,14 +64,13 @@ void main() { ); expect(find.text('Chat needs your answer or approval'), findsOneWidget); expect(find.text('Chat reply finished'), findsOneWidget); - expect(find.text(ntfySectionSubtitle), findsOneWidget); + expect(find.byType(CheckboxListTile), findsNWidgets(3)); expect(_checked(tester, 'run_finished'), isTrue); expect(_checked(tester, 'chat_needs_you'), isFalse); expect(_checked(tester, 'chat_reply_finished'), isTrue); }); testWidgets('shows the server default: only marked runs', (tester) async { - // The server's defaults: run ends notify only for "Notify me" runs. final gateway = _Gateway((_, _) => _reply(false, true, false)); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); @@ -73,24 +79,53 @@ void main() { expect(_checked(tester, 'chat_reply_finished'), isFalse); }); - testWidgets('toggling writes only that setting', (tester) async { - final gateway = _Gateway((type, fields) { - if (type == 'set_notification_settings') { - return _reply(true, true, true); - } - return _reply(true, true, false); + for (final key in ['run_finished', 'chat_needs_you', 'chat_reply_finished']) { + testWidgets('toggling $key writes only that setting', (tester) async { + final gateway = _Gateway((type, fields) { + if (type == 'set_notification_settings') { + return _reply(true, true, true); + } + return _reply(false, false, false); + }); + await tester.pumpWidget(_host(gateway)); + await tester.pumpAndSettle(); + await tester.tap(_tile(key)); + await tester.pumpAndSettle(); + expect(gateway.calls, hasLength(2)); + expect(gateway.calls.last.$1, 'set_notification_settings'); + expect(gateway.calls.last.$2, { + 'notification_settings': {key: true}, + }); + expect(_checked(tester, key), isTrue); + expect(find.byKey(notificationSettingsErrorKey), findsNothing); }); + } + + testWidgets('a legacy ntfy_enabled key in the reply is ignored', ( + tester, + ) async { + JsonMap legacy() => { + 'type': 'notification_settings', + 'notification_settings': { + ...(_reply(true, true, false)['notification_settings'] as Map), + 'ntfy_enabled': true, + }, + }; + final gateway = _Gateway((_, _) => legacy()); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); - await tester.tap(find.byKey(ntfySettingKey('chat_reply_finished'))); + expect(find.byType(CheckboxListTile), findsNWidgets(3)); + expect(_tile('ntfy_enabled'), findsNothing); + expect(find.textContaining('ntfy'), findsNothing); + expect(find.byKey(notificationSettingsErrorKey), findsNothing); + + // A write after such a reply still sends only the toggled key. + await tester.tap(_tile('chat_reply_finished')); await tester.pumpAndSettle(); - expect(gateway.calls, hasLength(2)); - expect(gateway.calls.last.$1, 'set_notification_settings'); expect(gateway.calls.last.$2, { 'notification_settings': {'chat_reply_finished': true}, }); - expect(_checked(tester, 'chat_reply_finished'), isTrue); - expect(find.byKey(ntfyErrorKey), findsNothing); + expect(find.byType(CheckboxListTile), findsNWidgets(3)); }); testWidgets('failure reverts and shows the refusal', (tester) async { @@ -101,53 +136,50 @@ void main() { }); await tester.pumpWidget(_host(gateway)); await tester.pumpAndSettle(); - await tester.tap(find.byKey(ntfySettingKey('run_finished'))); + await tester.tap(_tile('run_finished')); await tester.pump(); // The change shows at once and the group is disabled while it saves. expect(_checked(tester, 'run_finished'), isFalse); - await tester.tap(find.byKey(ntfySettingKey('chat_needs_you'))); + await tester.tap(_tile('chat_needs_you')); await tester.pump(); expect(gateway.calls, hasLength(2)); pending.completeError(const ProtocolError('settings are read-only')); await tester.pumpAndSettle(); expect(_checked(tester, 'run_finished'), isTrue); expect(_checked(tester, 'chat_needs_you'), isTrue); - expect( - find.text('Could not save: settings are read-only'), - findsOneWidget, - ); + expect(find.text('Could not save: settings are read-only'), findsOneWidget); }); - testWidgets('disabled while loading and offline', (tester) async { + testWidgets('disabled while loading', (tester) async { final pending = Completer(); final gateway = _Gateway((_, _) => pending.future); await tester.pumpWidget(_host(gateway)); await tester.pump(); expect(find.text('Loading…'), findsOneWidget); - await tester.tap(find.byKey(ntfySettingKey('run_finished'))); + await tester.tap(_tile('run_finished')); await tester.pump(); expect(gateway.calls, hasLength(1)); expect( - tester - .widget(find.byKey(ntfySettingKey('run_finished'))) - .onChanged, + tester.widget(_tile('run_finished')).onChanged, isNull, ); pending.complete(_reply(true, true, false)); await tester.pumpAndSettle(); expect(find.text('Loading…'), findsNothing); + }); - final offline = _Gateway((_, _) => _reply(true, true, false)); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: SettingsNtfySection(gateway: offline, connected: false), - ), - ), - ); + testWidgets('offline: no request, the offline text, switches disabled', ( + tester, + ) async { + final gateway = _Gateway((_, _) => _reply(true, true, false)); + await tester.pumpWidget(_host(gateway, connected: false)); await tester.pumpAndSettle(); - expect(offline.calls, isEmpty); - expect(find.text(ntfyOfflineText), findsOneWidget); + expect(gateway.calls, isEmpty); + expect(find.text(notificationEventsOfflineText), findsOneWidget); + expect( + tester.widget(_tile('chat_needs_you')).onChanged, + isNull, + ); }); testWidgets('a load failure is shown with a retry', (tester) async { @@ -165,47 +197,7 @@ void main() { fail = false; await tester.tap(find.text('Retry')); await tester.pumpAndSettle(); - expect(find.byKey(ntfyErrorKey), findsNothing); - expect( - tester - .widget(find.byKey(ntfySettingKey('run_finished'))) - .value, - isFalse, - ); - }); - - group('ntfy_enabled', () { - JsonMap withNtfy(bool ntfy) => { - 'type': 'notification_settings', - 'notification_settings': { - ...(_reply(true, true, false)['notification_settings'] as Map), - 'ntfy_enabled': ntfy, - }, - }; - - testWidgets('hidden when the server does not send it', (tester) async { - final gateway = _Gateway((_, _) => _reply(true, true, false)); - await tester.pumpWidget(_host(gateway)); - await tester.pumpAndSettle(); - expect(find.byKey(ntfySettingKey('ntfy_enabled')), findsNothing); - expect(find.text(ntfySectionSubtitle), findsOneWidget); - }); - - testWidgets('shows and writes it', (tester) async { - final gateway = _Gateway( - (type, _) => withNtfy(type == 'set_notification_settings'), - ); - await tester.pumpWidget(_host(gateway)); - await tester.pumpAndSettle(); - expect(find.text('Also send to ntfy'), findsOneWidget); - expect(find.text(ntfySectionAppSubtitle), findsOneWidget); - expect(_checked(tester, 'ntfy_enabled'), isFalse); - await tester.tap(find.byKey(ntfySettingKey('ntfy_enabled'))); - await tester.pumpAndSettle(); - expect(gateway.calls.last.$2, { - 'notification_settings': {'ntfy_enabled': true}, - }); - expect(_checked(tester, 'ntfy_enabled'), isTrue); - }); + expect(find.byKey(notificationSettingsErrorKey), findsNothing); + expect(_checked(tester, 'run_finished'), isFalse); }); } diff --git a/app/test/features/settings/settings_screen_test.dart b/app/test/features/settings/settings_screen_test.dart index c649123f..f1e592b8 100644 --- a/app/test/features/settings/settings_screen_test.dart +++ b/app/test/features/settings/settings_screen_test.dart @@ -164,8 +164,8 @@ void main() { 'ping', 'notification_settings', ]); - await openSettingsSection(tester, 'Phone notifications'); - _answerNtfySettings(factory.last); + await openSettingsSection(tester, 'Notification events'); + _answerNotificationSettings(factory.last); await tester.pump(); await tester.pump(); expect(factory.last.decodedOutgoing, hasLength(2)); @@ -203,8 +203,8 @@ void main() { expect(find.text(serverDetailsPending), findsNothing); expect(find.text('Server build unavailable'), findsOneWidget); expect(find.text('Server time unavailable'), findsOneWidget); - await openSettingsSection(tester, 'Phone notifications'); - _answerNtfySettings(factory.last); + await openSettingsSection(tester, 'Notification events'); + _answerNotificationSettings(factory.last); await tester.pump(); }); @@ -521,8 +521,8 @@ Future _pump( await openSettingsSection(tester, 'Connection'); } -/// Answers the Settings screen's queued ntfy-settings load on [channel]. -void _answerNtfySettings(FakeChannel channel) { +/// Answers the Settings screen's queued notification-settings load on [channel]. +void _answerNotificationSettings(FakeChannel channel) { final request = channel.decodedOutgoing.last; expect(request['type'], 'notification_settings'); channel.reply({ diff --git a/app/test/features/settings/settings_search_page_test.dart b/app/test/features/settings/settings_search_page_test.dart index cd9defa3..f5f83b61 100644 --- a/app/test/features/settings/settings_search_page_test.dart +++ b/app/test/features/settings/settings_search_page_test.dart @@ -48,7 +48,7 @@ void main() { ..._filler(6), SettingsSection( id: 'server', - title: 'Phone notifications', + title: 'Notification events', lazy: true, builder: (_) => ServerSettingsView( load: load, @@ -60,11 +60,11 @@ void main() { // The local sections are built and the server section is only a skeleton: // no request runs until the list reaches it. expect(find.text('filler body'), findsWidgets); - expect(find.text('Phone notifications'), findsOneWidget); + expect(find.text('Notification events'), findsOneWidget); expect(fetches, 0); expect(tester.takeException(), isNull); - await tester.ensureVisible(find.text('Phone notifications')); + await tester.ensureVisible(find.text('Notification events')); await tester.pump(); await tester.pump(); expect(fetches, 1); @@ -131,8 +131,8 @@ void main() { ..._filler(6), SettingsSection( id: 'server', - title: 'Phone notifications', - keywords: 'ntfy push', + title: 'Notification events', + keywords: 'push devices', lazy: true, builder: (_) => ServerSettingsView( load: load, @@ -144,7 +144,7 @@ void main() { await tester.enterText( find.byKey(const ValueKey('settings.search')), - 'ntfy', + 'devices', ); await tester.pump(); await tester.pump(); diff --git a/app/test/perf/design_bench_test.dart b/app/test/perf/design_bench_test.dart index ee3e5815..8417f9a0 100644 --- a/app/test/perf/design_bench_test.dart +++ b/app/test/perf/design_bench_test.dart @@ -257,6 +257,13 @@ void main() { row['scrollFrameUs'] = watch.elapsedMicroseconds ~/ frames; rebuilds.uninstall(); row['scrollRebuildsPerFrame'] = rebuilds.count / frames; + // A denser design shows more rows in the same 120px, so it builds + // more per frame for the same per-row cost: the budget is per row + // scrolled past (rows over the transcript's whole extent). + final position = controller.position; + final extent = position.maxScrollExtent + position.viewportDimension; + final rowsScrolled = frames * 120 * _rows.length / extent; + row['scrollRebuildsPerRow'] = rebuilds.count / rowsScrolled; row['scrollLayersPerFrame'] = _sum(layers) / frames; row['scrollSaveLayersPerFrame'] = _sum(layers, (k) => !k.startsWith('clip')) / frames; @@ -277,7 +284,7 @@ void main() { // Counts are deterministic: a design may not exceed Default's by more // than a quarter (its own rows are allowed to differ a little). for (final key in [ - 'scrollRebuildsPerFrame', + 'scrollRebuildsPerRow', 'scrollLayersPerFrame', 'scrollSaveLayersPerFrame', 'switchFramesPerSwitch', diff --git a/app/test/ui/layout/app_list_row_test.dart b/app/test/ui/layout/app_list_row_test.dart index 57447ee3..f1375fe4 100644 --- a/app/test/ui/layout/app_list_row_test.dart +++ b/app/test/ui/layout/app_list_row_test.dart @@ -265,6 +265,7 @@ void main() { (AppDesign.standard, false, true), (AppDesign.terminal, true, false), (AppDesign.paper, false, false), + (AppDesign.compact, false, true), ]) { testWidgets('${design.label}: the open row is clearly marked', ( tester, diff --git a/app/test/ui/theme/compact_design_test.dart b/app/test/ui/theme/compact_design_test.dart new file mode 100644 index 00000000..f4234806 --- /dev/null +++ b/app/test/ui/theme/compact_design_test.dart @@ -0,0 +1,199 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_controller.dart'; +import 'package:pipelines_app/ui/theme/app_design_tokens.dart'; +import 'package:pipelines_app/ui/theme/app_theme.dart'; + +ThemeData _theme(AppDesign design, Brightness brightness, {String? font}) => + brightness == Brightness.dark + ? design.dark(fontFamily: font) + : design.light(fontFamily: font); + +BorderRadius? _radiusOf(ShapeBorder? shape) => + (shape as RoundedRectangleBorder?)?.borderRadius as BorderRadius?; + +void main() { + const six = BorderRadius.all(Radius.circular(6)); + + test('Compact is listed with a stable id, a label and one line', () { + expect(AppDesign.fromId('compact'), AppDesign.compact); + expect(AppDesign.compact.label, 'Compact'); + expect(AppDesign.compact.description, isNot(contains('\n'))); + expect(AppDesign.compact.usesInterfaceFont, isTrue); + expect(AppDesign.compact.swatchLines, greaterThan(2)); + for (final design in AppDesign.values) { + if (design != AppDesign.compact) expect(design.swatchLines, 2); + } + }); + + test('Compact tokens: Default chat and composer, tonal rows, 6px corners, ' + 'the compact density and tighter paragraphs', () { + for (final brightness in Brightness.values) { + final tokens = _theme( + AppDesign.compact, + brightness, + ).extension()!; + expect(tokens.design, AppDesign.compact); + expect(tokens.radius, 6); + expect(tokens.flat, isFalse); + expect(tokens.frame, isNull); + expect(tokens.transcript, TranscriptStyle.bubbles); + expect(tokens.composer, ComposerStyle.pill); + expect(tokens.selectedRow, SelectedRowStyle.tonal); + expect(tokens.density, DesignDensity.compact); + expect(tokens.density.dense, isTrue); + expect(tokens.density.iconSize, 18); + expect(tokens.density.railLabels, isFalse); + expect(tokens.density.railWidth, lessThan(96)); + expect(tokens.reading.family, isNull); + expect(tokens.reading.paragraphGap, lessThan(0.9)); + expect(tokens.denseCorners(BorderRadius.circular(12)), six); + } + }); + + test('the comfortable designs keep the comfortable density', () { + for (final design in [AppDesign.terminal, AppDesign.paper]) { + final tokens = design.light().extension()!; + expect(tokens.density, DesignDensity.comfortable); + expect(tokens.reading.paragraphGap, 0.9); + final twelve = BorderRadius.circular(12); + expect(tokens.denseCorners(twelve), twelve); + } + expect(AppDesignTokens.standard.density, DesignDensity.comfortable); + // Default still builds its exact themes, with no tokens at all. + expect(AppDesign.standard.light(), appLightTheme()); + expect(AppDesign.standard.dark(), appDarkTheme()); + }); + + test('density spacing: unchanged when comfortable, 4px grid when dense', () { + const comfortable = DesignDensity.comfortable; + for (final value in [2.0, 4.0, 6.0, 10.0, 13.0, 16.0, 24.0]) { + expect(comfortable.space(value), value); + expect(comfortable.inset(value), value); + } + expect(comfortable.minTouchRow, 0); + const compact = DesignDensity.compact; + expect(compact.space(16), 8); + expect(compact.space(13), 8); + expect(compact.space(12), 8); + expect(compact.space(8), 4); + expect(compact.space(6), 4); + expect(compact.space(4), 2); + expect(compact.space(24), 16); + expect(compact.inset(16), 12); + expect(compact.inset(12), 8); + for (final value in [8.0, 12.0, 16.0, 24.0, 32.0]) { + expect(compact.space(value) % 4, 0, reason: 'on the 4px grid'); + expect(compact.space(value), lessThan(value)); + } + }); + + test('Compact keeps Default colours and packs type, icons and density', () { + for (final brightness in Brightness.values) { + final theme = _theme(AppDesign.compact, brightness, font: 'Inter'); + final standard = _theme(AppDesign.standard, brightness, font: 'Inter'); + expect(theme.colorScheme, standard.colorScheme); + expect(theme.scaffoldBackgroundColor, standard.scaffoldBackgroundColor); + final text = theme.textTheme; + expect(text.bodyMedium?.fontSize, 13); + expect(text.bodyLarge?.fontSize, 14); + expect(text.labelMedium?.fontSize, 12); + expect(text.labelSmall?.fontSize, 11); + expect(text.titleMedium?.fontSize, 14); + for (final style in [text.bodyMedium, text.titleLarge, text.labelLarge]) { + // The device's interface font still applies. + expect(style?.fontFamily, 'Inter'); + expect(style?.fontSize, lessThan(20)); + // Line heights on a 2px step. + expect((style!.fontSize! * style.height!) % 2, closeTo(0, 0.01)); + } + expect(theme.visualDensity, VisualDensity.compact); + expect(theme.iconTheme.size, 18); + expect( + theme.iconButtonTheme.style?.visualDensity, + VisualDensity.compact, + reason: 'Material 3 icon buttons ignore the theme density otherwise', + ); + } + }); + + test('every floating and framed surface takes the same 6px corners', () { + final theme = AppDesign.compact.light(); + expect(_radiusOf(theme.dialogTheme.shape), six); + expect(_radiusOf(theme.popupMenuTheme.shape), six); + expect(_radiusOf(theme.snackBarTheme.shape), six); + expect(_radiusOf(theme.cardTheme.shape), six); + expect(_radiusOf(theme.chipTheme.shape), six); + expect(_radiusOf(theme.floatingActionButtonTheme.shape), six); + expect(_radiusOf(theme.listTileTheme.shape), six); + expect(_radiusOf(theme.navigationRailTheme.indicatorShape), six); + expect(_radiusOf(theme.menuTheme.style?.shape?.resolve(const {})), six); + expect( + _radiusOf(theme.filledButtonTheme.style?.shape?.resolve(const {})), + six, + ); + expect( + _radiusOf(theme.iconButtonTheme.style?.shape?.resolve(const {})), + six, + ); + expect( + (theme.tooltipTheme.decoration as BoxDecoration?)?.borderRadius, + six, + ); + final sheet = _radiusOf(theme.bottomSheetTheme.shape)!; + expect(sheet.topLeft, const Radius.circular(6)); + expect(sheet.bottomLeft, Radius.zero); + // A card keeps its outline under the theme's shape (outlined graph + // nodes would otherwise lose it). + final card = theme.cardTheme.shape! as RoundedRectangleBorder; + expect(card.side.color, theme.colorScheme.outlineVariant); + }); + + test('pointer devices shrink targets; touch devices keep 40px', () { + for (final (platform, pointer) in [ + (TargetPlatform.linux, true), + (TargetPlatform.macOS, true), + (TargetPlatform.windows, true), + (TargetPlatform.android, false), + (TargetPlatform.iOS, false), + ]) { + debugDefaultTargetPlatformOverride = platform; + // Built afresh: the cached theme is the device's, built once. + final theme = AppDesign.compact.build(Brightness.light); + expect( + theme.materialTapTargetSize, + pointer + ? MaterialTapTargetSize.shrinkWrap + : MaterialTapTargetSize.padded, + ); + expect(DesignDensity.compact.minTouchRow, pointer ? 0 : 40); + } + debugDefaultTargetPlatformOverride = null; + }); + + test( + 'a switch into or out of Compact snaps; others keep the blend', + () async { + final designs = AppDesignController(store: MemoryAppDesignStore()); + expect(AppDesign.compact.dense, isTrue); + for (final design in [ + AppDesign.standard, + AppDesign.terminal, + AppDesign.paper, + ]) { + expect(design.dense, isFalse); + } + expect(designs.themeAnimationDuration, kThemeAnimationDuration); + await designs.select(AppDesign.terminal); + expect(designs.themeAnimationDuration, kThemeAnimationDuration); + await designs.select(AppDesign.compact); + expect(designs.themeAnimationDuration, Duration.zero); + await designs.select(AppDesign.paper); + expect(designs.themeAnimationDuration, Duration.zero); + await designs.select(AppDesign.standard); + expect(designs.themeAnimationDuration, kThemeAnimationDuration); + }, + ); +} diff --git a/app/test/ui/theme/compact_rendering_test.dart b/app/test/ui/theme/compact_rendering_test.dart new file mode 100644 index 00000000..c830aa57 --- /dev/null +++ b/app/test/ui/theme/compact_rendering_test.dart @@ -0,0 +1,232 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_bubble.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/navigation_rail.dart'; +import 'package:pipelines_app/shell/windows/window_frame.dart'; +import 'package:pipelines_app/ui/layout/app_list_avatar.dart'; +import 'package:pipelines_app/ui/layout/app_list_row.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_tokens.dart'; + +/// Compact as drawn: thin rows, a narrow icon-only rail, 32px icon buttons +/// (40px targets on touch), tight bubbles, a slim window title bar, and no +/// clipping at a large text scale. +void main() { + tearDown(() => debugDefaultTargetPlatformOverride = null); + + Future pump( + WidgetTester tester, + Widget child, { + AppDesign design = AppDesign.compact, + double textScale = 1, + double width = 560, + }) async { + tester.view.physicalSize = Size(width, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MaterialApp( + // Built afresh, so the platform this test sets is the theme's. + theme: design.build(Brightness.light), + home: MediaQuery( + data: MediaQueryData( + size: Size(width, 900), + textScaler: TextScaler.linear(textScale), + ), + child: Scaffold(body: child), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Widget rows() => ListView( + children: [ + AppListRow( + key: const Key('one'), + title: const Text('Release train'), + time: '09:12', + onTap: () {}, + ), + AppListRow( + key: const Key('two'), + leading: AppListAvatar.initial('Release', color: Colors.teal), + title: const Text('Release notes'), + subtitle: const Text('claude-opus · /workspace/demo'), + time: '10m', + selected: true, + onTap: () {}, + ), + ], + ); + + testWidgets('pointer: a 36px single-line row and a ~52px two-line row', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + await pump(tester, rows()); + // Each row includes its 1px divider. + expect(tester.getSize(find.byKey(const Key('one'))).height, 37); + final two = tester.getSize(find.byKey(const Key('two'))).height; + expect(two, inInclusiveRange(50, 56)); + expect( + tester.getSize(find.byType(AppListAvatar)).height, + DesignDensity.compact.avatarSize, + ); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('touch: rows keep a 40px target', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + await pump(tester, rows()); + expect( + tester.getSize(find.byKey(const Key('one'))).height, + greaterThanOrEqualTo(41), + ); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('Default rows keep their comfortable size', (tester) async { + await pump(tester, rows(), design: AppDesign.standard); + expect( + tester.getSize(find.byKey(const Key('one'))).height, + greaterThan(48), + ); + expect( + tester.getSize(find.byType(AppListAvatar)).height, + kAppListAvatarSize, + ); + }); + + testWidgets('rows and bubbles do not clip at 2x text', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + await pump( + tester, + Column( + children: [ + SizedBox(height: 300, child: rows()), + const ChatUserBubble(child: Text('Summarise the release notes.')), + ], + ), + textScale: 2, + width: 360, + ); + expect(tester.takeException(), isNull); + final one = tester.getSize(find.byKey(const Key('one'))).height; + expect(one, greaterThan(37), reason: 'the row grows with its text'); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('icon buttons: 32px on a pointer device, 40px target on touch', ( + tester, + ) async { + Widget button() => IconButton( + key: const Key('b'), + onPressed: () {}, + icon: const Icon(Icons.add), + ); + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + await pump(tester, Center(child: button())); + expect(tester.getSize(find.byKey(const Key('b'))), const Size(32, 32)); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + await pump(tester, Center(child: button())); + expect(tester.getSize(find.byKey(const Key('b'))), const Size(40, 40)); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('the rail is narrow and icon-only, each icon with a tooltip', ( + tester, + ) async { + await pump( + tester, + Row( + children: [ + ShellNavigationRail( + selected: AppDestination.runs, + icon: (d) => Icon(destinationDetails(d).icon), + onSelected: (_) {}, + ), + const Expanded(child: SizedBox()), + ], + ), + width: 1200, + ); + final rail = find.byKey(const ValueKey('shell.navigation-rail.surface')); + expect(tester.getSize(rail).width, DesignDensity.compact.railWidth); + expect( + tester.widget(find.byType(NavigationRail)).labelType, + NavigationRailLabelType.none, + ); + for (final destination in shellTabDestinations) { + expect( + find.byTooltip(destinationDetails(destination).label), + findsOneWidget, + ); + } + expect(find.byTooltip('Settings'), findsOneWidget); + // Settings' indicator matches the tabs' 56x32 rather than the rail. + final indicator = find.descendant( + of: find.byKey(const ValueKey('shell.destination.settings')), + matching: find.byType(Container), + ); + expect(tester.getSize(indicator.first), const Size(56, 32)); + }); + + testWidgets('the operator bubble is tight, in the design corners', ( + tester, + ) async { + await pump(tester, const ChatUserBubble(child: Text('Ship it'))); + final material = tester.widget( + find.descendant( + of: find.byType(ChatUserBubble), + matching: find.byType(Material), + ), + ); + final shape = material.shape! as RoundedRectangleBorder; + expect(shape.borderRadius, BorderRadius.circular(6)); + final padding = tester.widget( + find.descendant( + of: find.byType(ChatUserBubble), + matching: find.byType(Padding), + ), + ); + expect( + padding.padding, + const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ); + final gap = chatParagraphGap(tester.element(find.text('Ship it')), 14); + expect(gap, closeTo(14 * 0.6, 0.01)); + }); + + testWidgets('a floating window has a 32px title bar and 6px corners', ( + tester, + ) async { + late BuildContext context; + await pump( + tester, + Builder( + builder: (c) { + context = c; + return const SizedBox(); + }, + ), + ); + expect(windowTitleBarHeight(context), 32); + expect(windowCorners(context), BorderRadius.circular(6)); + await pump( + tester, + Builder( + builder: (c) { + context = c; + return const SizedBox(); + }, + ), + design: AppDesign.paper, + ); + expect(windowTitleBarHeight(context), 40); + expect(windowCorners(context), BorderRadius.circular(windowCornerRadius)); + }); +} diff --git a/app/test/ui/theme/compact_switch_test.dart b/app/test/ui/theme/compact_switch_test.dart new file mode 100644 index 00000000..cc34a60e --- /dev/null +++ b/app/test/ui/theme/compact_switch_test.dart @@ -0,0 +1,121 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; + +final _rows = transcriptRows([ + for (var i = 0; i < 6; i++) ...[ + { + 'id': 'u$i', + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'Step $i'}, + ], + }, + { + 'id': 'a$i', + 'role': 'assistant', + 'parts': [ + { + 'type': 'tool', + 'id': 't$i', + 'name': 'Bash', + 'state': { + 'status': 'completed', + 'input': {'command': 'go test'}, + }, + }, + {'type': 'text', 'text': 'Fixed `x`.\n\n- one\n\n```go\nreturn 1\n```'}, + ], + }, + ], +]); + +/// A live design switch to and from Compact animates the theme without an +/// error in any frame. A component theme that set a text-theme style failed +/// to lerp against Default's unset one, and in the browser the broken +/// frames stopped the app drawing. +void main() { + testWidgets('switching to and from Compact lerps every frame cleanly', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + final design = ValueNotifier(AppDesign.compact); + await tester.pumpWidget( + ValueListenableBuilder( + valueListenable: design, + builder: (_, d, _) => MaterialApp( + theme: d.dark(), + darkTheme: d.dark(), + home: Scaffold( + floatingActionButton: FloatingActionButton.extended( + onPressed: () {}, + icon: const Icon(Icons.add), + label: const Text('New run'), + ), + body: Row( + children: [ + NavigationRail( + destinations: const [ + NavigationRailDestination( + icon: Icon(Icons.add), + label: Text('a'), + ), + NavigationRailDestination( + icon: Icon(Icons.add), + label: Text('b'), + ), + ], + selectedIndex: 0, + ), + Expanded( + child: ListView( + children: [ + IconButton(onPressed: () {}, icon: const Icon(Icons.add)), + IconButton.filled( + onPressed: () {}, + icon: const Icon(Icons.add), + ), + Checkbox(value: true, onChanged: (_) {}), + Switch(value: true, onChanged: (_) {}), + const ListTile(title: Text('t'), subtitle: Text('s')), + const TextField(), + Chip(label: const Text('c'), onDeleted: () {}), + SegmentedButton( + segments: const [ + ButtonSegment(value: 1, label: Text('one')), + ButtonSegment(value: 2, label: Text('two')), + ], + selected: const {1}, + ), + for (final row in _rows) ChatMessageView(row: row), + ], + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + for (var round = 0; round < 3; round++) { + for (final other in [ + AppDesign.standard, + AppDesign.terminal, + AppDesign.paper, + AppDesign.compact, + ]) { + design.value = other; + for (var f = 0; f < 20; f++) { + await tester.pump(const Duration(milliseconds: 16)); + final e = tester.takeException(); + if (e != null) fail('to ${other.id} frame $f: $e'); + } + } + } + debugDefaultTargetPlatformOverride = null; + }); +} diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index 5e98e76e..ef62148c 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -85,7 +85,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`. | `grant=clipboard` | let the page read and write the clipboard (`navigator.clipboard` in `eval`) | | `clipboard=read[:label]` / `clipboard=write:` | read or write the browser's clipboard from a scratch page on the loopback origin (a secure context), then bring the page back; JSON `expect` fails the run unless the read text matches. Works for an `--insecure` page, which has no `navigator.clipboard` | | `files=a.ttf[,b.ttf]` | answer the next file chooser the page opens with these files (paths relative to the working directory); put it before the click that opens the picker | -| `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) | +| `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on); JSON `press` holds the finger down that many ms first (a long press), `hold: true` leaves it down for a capture, and the next swipe moves it on from there | | `pinch=>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) | | `tabs=name` | write the open tabs (`{url, type}`) to JSON, e.g. to see a link open a new tab | | `follow=/window/chat/` | move the following steps to the page whose URL contains the text (a window the app opened with `window.open`, at its own size, semantics on); `follow=main` returns to the page the kit opened (`examples/detached-chat-window.json`) | diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index c280a9e5..b1facc78 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -34,7 +34,9 @@ steps: open=[@WxH] wait= shot= click= waitfor= (secondary button: context menus) drag=>, (JSON: drag, dx, dy, steps, gap, hold) - swipe=>, pinch=> (with --touch true) + swipe=>, pinch=> (with --touch true; + JSON swipe: press ms held before moving, hold keeps the finger down + for the next swipe) target: