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 4137d756..ef2e55a4 100644 --- a/README.md +++ b/README.md @@ -4,18 +4,32 @@ Pipelines is a per-user server and CLI for running reusable AI workflows and cha ## Install -From this checkout, run: +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: ```sh ./install ``` -If `pipelines` is not already on your `PATH`, add it: +The installer asks you to choose a web sign-in password. If `pipelines` is not +already on your `PATH`, add it: ```sh export PATH="$HOME/.local/share/pipelines/bin:$PATH" ``` +## First steps + +1. Open the address the installer printed (by default `http://localhost:8082/`) + and sign in with the password you chose. +2. Set up the harnesses you use (below). OpenCode is already the default. +3. Start a chat, or run one of the example pipelines a new installation starts + with: `pipelines list`, then `pipelines run ""`. + +If the CLI says it cannot reach the server, run `pipelines start` +(`pipelines doctor` shows what is wrong). + ## Set up harnesses Run the command for each harness you want to use: 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/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 186a773a..c9eb534f 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -1219,6 +1219,7 @@ class _PipelinesAppState extends State onViewPipelineRuns: (id) => _delegate.goTo(AppRoute.runsForPipeline(id)), onOpenSchedules: _delegate.openSchedules, + onOpenTemplates: _delegate.openTemplates, onOpenSettings: () => _delegate.goTo(AppRoute.settings), onOpenInChat: (context, detail, run) => _openPipelineInChat(context, detail, run), diff --git a/app/lib/application/pipelines_destination.dart b/app/lib/application/pipelines_destination.dart index 004c5777..a5f6603d 100644 --- a/app/lib/application/pipelines_destination.dart +++ b/app/lib/application/pipelines_destination.dart @@ -24,6 +24,7 @@ class PipelinesDestination extends StatelessWidget { this.onRunStarted, this.onViewPipelineRuns, this.onOpenSchedules, + this.onOpenTemplates, this.onOpenSettings, this.onSelectionChanged, this.initialPipelineId, @@ -50,6 +51,9 @@ class PipelinesDestination extends StatelessWidget { final ValueChanged? onViewPipelineRuns; final VoidCallback? onOpenSchedules; + /// Opens the Templates gallery, offered by an empty pipeline list. + final VoidCallback? onOpenTemplates; + /// Opens Settings as a page from the Pipelines bar's gear. final VoidCallback? onOpenSettings; final ValueChanged? onSelectionChanged; @@ -96,6 +100,7 @@ class PipelinesDestination extends StatelessWidget { onRunStarted: onRunStarted, onViewPipelineRuns: onViewPipelineRuns, onOpenSchedules: onOpenSchedules, + onOpenTemplates: onOpenTemplates, onOpenSettings: onOpenSettings, onSelectionChanged: onSelectionChanged, onOpenInChat: onOpenInChat, diff --git a/app/lib/application/templates_destination.dart b/app/lib/application/templates_destination.dart index 8be0a3ff..eab3656f 100644 --- a/app/lib/application/templates_destination.dart +++ b/app/lib/application/templates_destination.dart @@ -119,6 +119,7 @@ class _TemplatesDestinationState extends State { embedded: true, onCreated: widget.onCreated, initialKey: widget.initialKey, + reloadToken: session.connectionEpoch, ), ); } diff --git a/app/lib/core/error_advice.dart b/app/lib/core/error_advice.dart index 3ca4ccbd..abdd1040 100644 --- a/app/lib/core/error_advice.dart +++ b/app/lib/core/error_advice.dart @@ -4,7 +4,16 @@ import 'error_reason.dart'; import 'transport/connection_state.dart'; /// The common kinds of failure an operator can act on. -enum ErrorAdviceKind { notConnected, serverTooOld, permission, timeout } +enum ErrorAdviceKind { + notConnected, + serverTooOld, + permission, + timeout, + + /// The server has no agent harness to run a chat or a stage with: a setup + /// step on the server, not a failure of this app. + noHarness, +} /// What to do about a failure, as one sentence, and the raw detail it came /// from (kept available behind the sentence, never replaced by it). @@ -29,6 +38,7 @@ ErrorAdviceKind? errorAdviceKind(Object error) { return ErrorAdviceKind.permission; } final text = '$error'.toLowerCase(); + if (needsHarnessSetup(text)) return ErrorAdviceKind.noHarness; if (_tooOld.hasMatch(text)) return ErrorAdviceKind.serverTooOld; if (_permission.hasMatch(text)) return ErrorAdviceKind.permission; if (_timeout.hasMatch(text)) return ErrorAdviceKind.timeout; @@ -49,8 +59,23 @@ String errorAdviceSentence(ErrorAdviceKind kind) => switch (kind) { ErrorAdviceKind.timeout => 'The server did not answer in time. Check the connection, then try ' 'again.', + ErrorAdviceKind.noHarness => + 'No agent harness is set up on the server yet. In a terminal on the ' + 'server, run `pipelines harness setup ` (claude, codex, ' + 'opencode or pi), then try again.', }; +/// Whether [error] says the server has no usable agent harness: chat is not +/// configured, or a stage could not start its harness's CLI. Such a server is +/// new, not broken, so callers show the setup step instead of an error. +bool needsHarnessSetup(Object? error) => + error != null && _noHarness.hasMatch('$error'.toLowerCase()); + +final _noHarness = RegExp( + r'chat is not configured|harness unreachable|' + r'cannot run the selected \w+ cli', +); + final _tooOld = RegExp( r'unknown (command|message|request)|unsupported (command|message|request)', ); diff --git a/app/lib/core/servers/chat/federated_chat_gateway.dart b/app/lib/core/servers/chat/federated_chat_gateway.dart index 51a830ae..47ef6b6b 100644 --- a/app/lib/core/servers/chat/federated_chat_gateway.dart +++ b/app/lib/core/servers/chat/federated_chat_gateway.dart @@ -91,11 +91,18 @@ class FederatedChatGateway implements ApiGateway { if (type == 'chat_sessions') { final current = Map.of(sources()); _cached.removeWhere((id, _) => !serverIds.contains(id)); + // The first machine's own refusal, kept so a list that no machine + // could read says why (chat not set up there, say) instead of + // claiming that nothing is connected. + Object? firstFailure; final results = await Future.wait( current.entries.map((entry) async { try { final reply = await entry.value.call(type, fields); - final list = reply['chat_sessions']; + // A server with no chats leaves the empty list out of its reply. + final list = + reply['chat_sessions'] ?? + (reply['type'] == 'chat_sessions' ? const [] : null); if (list is! List) { throw StateError( 'Invalid chat list from ${entry.value.server.name}.', @@ -110,13 +117,15 @@ class FederatedChatGateway implements ApiGateway { .map((v) => Map.from(v)) .toList(); return true; - } catch (_) { + } catch (error) { + firstFailure ??= error; return false; } }), ); _cached.removeWhere((id, _) => !serverIds.contains(id)); if (!results.contains(true) && _cached.isEmpty) { + if (firstFailure case final failure?) throw failure; throw StateError('No saved machine is connected.'); } return { 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/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_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_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 52647aa1..5a6c7b67 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -34,6 +34,7 @@ import 'composer_focus_request.dart'; import 'composer_focus_restore.dart'; import 'chat_bar_tint.dart'; import 'composer_focus_ring.dart'; +import 'composer_cell.dart'; import 'composer_underline.dart'; import '../../../ui/theme/app_design_tokens.dart'; import 'composer_running_border.dart'; @@ -1128,6 +1129,14 @@ class _ChatComposerBarState extends State { child: child, ); } + if (tokens.composer == ComposerStyle.cell) { + return ComposerCell( + focus: _focus, + accent: accent, + running: widget.running, + child: child, + ); + } final shape = tokens.shape(_pillShape); return Stack( children: [ diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 7c06e88b..4d82f4ad 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -13,6 +13,7 @@ import '../../../shell/list_detail_policy.dart'; import '../data/chat_attachment_images.dart'; import '../data/chat_repository.dart'; import '../domain/chat_activity_detail.dart'; +import '../domain/chat_cell_numbers.dart'; import '../domain/chat_notice.dart'; import '../domain/chat_harness_commands.dart'; import '../domain/chat_attachment_picker.dart'; @@ -31,6 +32,8 @@ import '../ui/transcript/chat_find_highlight.dart'; import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_message_bubble.dart'; import '../ui/transcript/chat_message_view.dart'; +import '../ui/transcript/notebook/notebook_gutter.dart'; +import '../../../ui/theme/app_design_tokens.dart'; import '../ui/transcript/chat_message_timestamp.dart'; import '../ui/transcript/chat_turn_activity_view.dart'; import '../domain/chat_transcript_days.dart'; @@ -307,6 +310,10 @@ class _ChatThreadViewState extends State with ChatFindHost { final _sentEntrances = ChatSentEntrances(); final _rowWidgets = ChatRowWidgets(); + /// Under a notebook transcript, each turn's cell number by row key + /// ([chatCellNumbers]); empty under every other transcript. + Map _cellNumbers = const {}; + /// The floating bar and composer, reused while their inputs hold so a /// streamed delta does not rebuild the conversation's chrome. final _chrome = ChatRowWidgets(); @@ -1246,6 +1253,9 @@ class _ChatThreadViewState extends State with ChatFindHost { ), _controller.turnDiffs, ); + final cells = + AppDesignTokens.of(context).transcript == TranscriptStyle.cells; + _cellNumbers = cells ? chatCellNumbers(allRows) : const {}; // A transcript held from before a socket gap may still say a compaction is // running even when the repair's read is refused. That running state is // stale, so no compaction notice is derived from it until a fresh read or @@ -1423,17 +1433,21 @@ class _ChatThreadViewState extends State with ChatFindHost { child: Builder( builder: (_) => _entering( rows[index], - _transcriptRow( + _inNotebookGutter( + cells, rows[index], - keys[index], - onDismissCompaction: - compactionNotice != null && - chatNoticeActivityCondition( - rows[index], - ) == - compactionNotice.condition - ? () => _dismiss(compactionNotice) - : null, + _transcriptRow( + rows[index], + keys[index], + onDismissCompaction: + compactionNotice != null && + chatNoticeActivityCondition( + rows[index], + ) == + compactionNotice.condition + ? () => _dismiss(compactionNotice) + : null, + ), ), ), ), @@ -1944,10 +1958,12 @@ class _ChatThreadViewState extends State with ChatFindHost { // write, never mutated, so a deep-equal row is the same content. Permission // chips carry objects that compare by identity, so a row with chips is // always rebuilt. + final cell = _cellNumbers['${row['key'] ?? ''}']; return _rowWidgets.widgetFor( key, row, [ + cell, delivery, onRemove != null, sendAt, @@ -1958,6 +1974,7 @@ class _ChatThreadViewState extends State with ChatFindHost { ], () => ChatMessageView( row: row, + cell: cell, speechScope: widget.sessionId, scheduleShown: sendAt != null, // The same reader id as the reply's Read aloud button, so the spoken @@ -1983,6 +2000,16 @@ class _ChatThreadViewState extends State with ChatFindHost { ); } + /// Under a notebook transcript, a row that is not a cell (a shell run, a + /// notice, an activity group) behind an empty gutter, so it keeps to the + /// cells' column; a cell draws its own gutter. + Widget _inNotebookGutter(bool cells, JsonMap row, Widget child) { + if (!cells) return child; + final kind = row['kind']; + if (kind == 'user' || kind == 'assistant') return child; + return NotebookGutterRow(child: child); + } + /// A user row in the entrance a just-sent message plays; every user row is /// wrapped, so its server copy replacing it keeps the same element. Widget _entering(JsonMap row, Widget child) { diff --git a/app/lib/features/chat/conversation/composer_cell.dart b/app/lib/features/chat/conversation/composer_cell.dart new file mode 100644 index 00000000..a93cb242 --- /dev/null +++ b/app/lib/features/chat/conversation/composer_cell.dart @@ -0,0 +1,94 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/glass_bar.dart'; +import '../../../ui/theme/app_design_tokens.dart'; +import '../ui/transcript/notebook/notebook_cell_frame.dart'; +import '../ui/transcript/notebook/notebook_gutter.dart'; +import 'composer_focus_ring.dart'; + +/// The composer under a design whose composer is a notebook cell +/// ([ComposerStyle.cell], Notebook): the next, empty input cell, `In [ ]:` +/// in the gutter beside a light grey cell holding the field and its +/// controls. The cell's frame and bar take [accent] while the field has +/// focus; while a turn runs a thin moving line runs along its foot. It +/// floats over the transcript, so it stands on the page's own colour. +class ComposerCell extends StatelessWidget { + const ComposerCell({ + super.key, + required this.focus, + required this.accent, + required this.running, + required this.child, + }); + + final FocusNode focus; + + /// The chat's focus colour (the host's primary for a chat with none). + final Color accent; + + /// Whether a turn is running. + final bool running; + final Widget child; + + /// The cell's padding: the pill's edge gap and, past it, the same 3px + /// the usage ring keeps from the send button, so the ring never meets + /// the cell's hairline. + static const double _inset = GlassBarMetrics.fieldEdgeGap + 3; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final cell = ListenableBuilder( + listenable: focus, + child: Padding(padding: const EdgeInsets.all(_inset), child: child), + builder: (context, field) { + final focused = focus.hasFocus; + return NotebookCellFrame( + key: const Key('chat-composer-cell-frame'), + fill: scheme.surfaceContainerLow, + border: focused ? accent : scheme.outlineVariant, + bar: focused ? accent : scheme.outline, + padding: const EdgeInsetsDirectional.only(start: notebookCellBar), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + field!, + if (running) + Padding( + padding: const EdgeInsetsDirectional.only( + start: notebookCellTextInset - notebookCellBar, + end: notebookCellTextInset, + bottom: 1, + ), + child: LinearProgressIndicator( + key: const Key('chat-composer-running-rule'), + minHeight: ComposerFocusRing.ringWidth, + color: accent, + backgroundColor: scheme.outlineVariant, + ), + ), + ], + ), + ); + }, + ); + return Material( + key: const Key('chat-composer-cell'), + // The page itself, so the cell reads as the next one on the sheet. + color: Theme.of(context).scaffoldBackgroundColor, + child: Padding( + padding: const EdgeInsets.only(top: 4), + child: NotebookGutterRow( + label: notebookInLabel(null), + color: notebookInColor(scheme), + // The label on the field's first line: the cell's padding, then + // the field's own. + top: _inset + 16, + inline: false, + child: cell, + ), + ), + ); + } +} diff --git a/app/lib/features/chat/domain/chat_cell_numbers.dart b/app/lib/features/chat/domain/chat_cell_numbers.dart new file mode 100644 index 00000000..881c3efe --- /dev/null +++ b/app/lib/features/chat/domain/chat_cell_numbers.dart @@ -0,0 +1,25 @@ +import '../../../core/api_gateway.dart'; + +/// A notebook transcript's cell numbers by row key: each operator turn +/// (a `user` row, typed or sent on the operator's behalf) takes the next +/// number from 1 in transcript order, and every agent row (`assistant`) that +/// follows takes its prompt's number, so `In [n]:` and `Out [n]:` pair up. +/// +/// Derived from the turn's position, never stored: the same history always +/// numbers the same way, so a reload keeps every cell's number. An agent +/// row before any operator turn has none (`Out [ ]:`). +Map chatCellNumbers(Iterable rows) { + final numbers = {}; + var turn = 0; + for (final row in rows) { + final key = '${row['key'] ?? ''}'; + switch (row['kind']) { + case 'user': + turn++; + if (key.isNotEmpty) numbers[key] = turn; + case 'assistant': + if (turn > 0 && key.isNotEmpty) numbers[key] = turn; + } + } + return numbers; +} diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index d7b26d37..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'; @@ -43,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'; @@ -78,6 +80,7 @@ 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. @@ -144,6 +147,7 @@ class _ChatScreenState extends State _ChatScreenPaneMenu, _ChatScreenQuickSwitch, _ChatScreenAttention, + _ChatScreenStackGroups, _ChatScreenStack, _ChatScreenListToggle { /// The chats' shared state: the list, opened rows, accepted models, @@ -195,6 +199,7 @@ class _ChatScreenState extends State _runtime.recency.touch(initial); } _workspace.addListener(_workspaceChanged); + _stackGroups.addListener(_syncOpenWorkspace); _bindWorkspacePersistence(); HardwareKeyboard.instance.addHandler(_cycleChatKey); HardwareKeyboard.instance.addHandler(_slashFocusKey); @@ -493,6 +498,7 @@ class _ChatScreenState extends State _page.dispose(); _workspaceBinding?.dispose(); _openWorkspace?.dispose(); + _stackGroups.dispose(); _unbindWindows(); _unbindQuickSwitch(); _unbindAttention(); @@ -570,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/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 604adfbc..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,172 +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( - // A design with a contrast floor frames it in the full - // accent at its own stroke. - side: !tokens.flat - ? BorderSide.none - : tokens.minContrast != null - ? BorderSide(color: scheme.primary, width: tokens.stroke) - : BorderSide(color: scheme.primary.withValues(alpha: .55)), - ), - ), - 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..d7486c42 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_column_items.dart @@ -0,0 +1,375 @@ +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( + // A design with a contrast floor frames it in the full + // accent at its own stroke. + side: !tokens.flat + ? BorderSide.none + : tokens.minContrast != null + ? BorderSide(color: scheme.primary, width: tokens.stroke) + : BorderSide(color: scheme.primary.withValues(alpha: .55)), + ), + ), + 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 550f6227..7c2e87b5 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); @@ -125,29 +211,59 @@ class ChatStackLabel extends StatelessWidget { color: scheme.onSurface, fontWeight: emphasized ? FontWeight.w700 : FontWeight.w500, ); - return DecoratedBox( - decoration: ShapeDecoration( - color: fill, - shape: _labelShape( - tokens, - outlined ? BorderSide(color: color, width: 3) : null, - ), - shadows: tokens.flat ? null : chatStackShadows(scheme), + final rest = ShapeDecoration( + color: fill, + shape: _labelShape( + tokens, + outlined ? BorderSide(color: color, width: 3) : null, ), + 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, BorderSide? outline) { + OutlinedBorder _labelShape(AppDesignTokens tokens, [BorderSide? outline]) { final side = outline ?? 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_harness_setup_state.dart b/app/lib/features/chat/ui/sessions/chat_harness_setup_state.dart new file mode 100644 index 00000000..19be11a3 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_harness_setup_state.dart @@ -0,0 +1,36 @@ +import 'package:flutter/material.dart'; + +import '../../../../ui/status/empty_state.dart'; +import '../../../walkthrough/walkthrough_harness_command.dart'; + +/// The chat list's state on a server without an agent harness: chat is not +/// configured there yet, which is a setup step rather than an error. It names +/// the step (the setup command for the agent the operator picks, ready to +/// copy) and offers Refresh for after the command has run. +const chatHarnessSetupKey = ValueKey('chat-harness-setup'); + +class ChatHarnessSetupState extends StatelessWidget { + const ChatHarnessSetupState({super.key, this.onRefresh}); + + /// Reads the chat list again once the harness is set up. + final VoidCallback? onRefresh; + + @override + Widget build(BuildContext context) { + final refresh = onRefresh; + return EmptyState( + key: chatHarnessSetupKey, + dense: true, + icon: Icons.build_circle_outlined, + title: 'Set up an agent to start chatting', + message: + 'Chats run on a coding agent on your server, and none is set up ' + 'yet. Run the setup command for the agent you use in a terminal on ' + 'the server, then refresh.', + action: refresh == null + ? null + : emptyStateAction('Refresh', refresh, icon: Icons.refresh), + child: const WalkthroughHarnessCommand(), + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_body.dart b/app/lib/features/chat/ui/sessions/chat_sessions_body.dart index 9a9f6a43..447336aa 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_body.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_body.dart @@ -1,12 +1,18 @@ import 'package:flutter/material.dart'; import '../../../../core/api_gateway.dart'; +import '../../../../core/error_advice.dart'; +import '../../../../ui/status/empty_state.dart'; import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; +import 'chat_harness_setup_state.dart'; import 'session_list_material.dart'; import 'session_pane_menu.dart'; import 'session_row_style.dart'; +/// The chat list's state when the server has no chats yet. +const chatListEmptyKey = ValueKey('chat-list-empty'); + typedef ChatSessionSection = ({String title, List sessions}); /// Which list sections are folded away, kept by the list's screen so the @@ -52,8 +58,16 @@ class ChatSessionsBody extends StatelessWidget { this.onDismissError, this.selectionOnly = false, this.emptyMessageOverride, + this.onNewChat, + this.onRefresh, }); + /// Starts a chat; an empty list offers it as its next step. + final VoidCallback? onNewChat; + + /// Reads the list again; the harness setup state offers it. + final VoidCallback? onRefresh; + /// Reuse list presentation for a picker without mutation menus or gestures. final bool selectionOnly; final String? emptyMessageOverride; @@ -94,6 +108,35 @@ class ChatSessionsBody extends StatelessWidget { : 'No chats match "${query.trim()}".'); if (loading && sessions.isEmpty) return const ChatLoadingIndicator(); + // The list's own first-run states. A picker (selectionOnly or an + // override) keeps its one-line message. + final firstRun = + !selectionOnly && + emptyMessageOverride == null && + sessions.isEmpty && + query.trim().isEmpty; + if (firstRun && needsHarnessSetup(error)) { + return ChatHarnessSetupState(onRefresh: onRefresh); + } + if (firstRun && error == null) { + final start = onNewChat; + return EmptyState( + key: chatListEmptyKey, + dense: true, + icon: Icons.forum_outlined, + title: 'No chats yet', + message: + 'Talk with a coding agent on your server. Each chat works in a ' + 'folder you choose and keeps its history here.', + action: start == null + ? null + : emptyStateAction( + 'Start a chat', + start, + icon: Icons.add_comment_outlined, + ), + ); + } final clearSearch = query.trim().isEmpty ? null : onClearSearch; final duplicateTitles = duplicateChatTitles(visible); return MaterialSessionList( diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart index 7e49ea09..b85df151 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -9,6 +9,7 @@ import 'package:flutter/material.dart'; import '../../../../ui/layout/content_width.dart'; import '../../../../core/api_gateway.dart'; +import '../../../../core/error_advice.dart'; import '../../../../shell/shell_bar.dart'; import '../../../../shell/shell_list_shortcuts.dart'; import '../../../terminal/terminal_open_action.dart'; @@ -16,7 +17,9 @@ import '../../data/chat_repository.dart'; import '../../domain/chat_colors.dart'; import '../../domain/chat_cycle.dart'; import '../../domain/chat_sessions.dart'; +import '../../../../ui/adaptive/app_popups.dart'; import 'chat_adaptive.dart'; +import 'chat_harness_setup_state.dart'; import 'chat_color_picker.dart'; import 'chat_session_local.dart'; import 'chat_sessions_body.dart'; @@ -194,6 +197,20 @@ class ChatSessionsScreenState extends State { } Future _newChat({bool chooseMachine = true}) async { + // Without an agent harness the create form could only be refused: show + // the setup step instead, with Refresh to read the list once it is done. + if (needsHarnessSetup(_controller.error)) { + await showAppDetails( + context, + builder: (sheet) => ChatHarnessSetupState( + onRefresh: () { + Navigator.of(sheet).pop(); + unawaited(_controller.refresh()); + }, + ), + ); + return; + } final scope = ServerContext.maybeOf(context); var repository = _controller.repository; if (chooseMachine && scope != null) { @@ -241,6 +258,13 @@ class ChatSessionsScreenState extends State { if (session != null && mounted) widget.onOpen(session); } + /// The list failure shown above the list. A server without an agent + /// harness is not a failure: the list itself shows that setup step. + String? get _listError { + final error = _controller.error; + return error == null || needsHarnessSetup(error) ? null : error; + } + /// Starts the same machine picker and create dialog used by the list action. Future newChat() => _newChat(); @@ -316,20 +340,20 @@ class ChatSessionsScreenState extends State { children: [ // A notice above the list starts below the floating bar; the list // under it then needs no inset of its own. - if (_controller.error != null) + if (_listError != null) Padding( padding: EdgeInsets.only( top: MediaQuery.paddingOf(context).top, ), child: ChatErrorNotice( - message: _controller.error!, + message: _listError!, onRetry: _controller.refresh, ), ), Expanded( child: MediaQuery.removePadding( context: context, - removeTop: _controller.error != null, + removeTop: _listError != null, child: Stack( children: [ ContentWidth( @@ -340,6 +364,8 @@ class ChatSessionsScreenState extends State { query: _search.text, loading: _controller.loading, error: _controller.error, + onNewChat: _newChat, + onRefresh: _controller.refresh, onOpen: _open, onOpenBeside: widget.onOpenBeside == null ? null 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 c7b49671..6cb5f1f3 100644 --- a/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart +++ b/app/lib/features/chat/ui/transcript/chat_automated_prompt.dart @@ -6,6 +6,8 @@ import '../../conversation/chat_schedule_time.dart'; import '../../domain/chat_prompt_origin.dart'; import 'chat_copy_button.dart'; import 'chat_hover_actions.dart'; +import 'notebook/notebook_cell_frame.dart'; +import 'notebook/notebook_input_cell.dart'; import 'paper/paper_editorial_note.dart'; import 'paper/paper_quote.dart'; import 'terminal/terminal_glyphs.dart'; @@ -18,6 +20,13 @@ String chatAutomatedPromptLabel(ChatPromptOrigin origin) => switch (origin) { _ => '', }; +/// A notebook cell's tag for an automated prompt: a follow-up or an +/// auto-continue was scheduled; a switch of account continues at once. +String chatAutomatedPromptTag(ChatPromptOrigin origin) => switch (origin) { + ChatPromptOrigin.autoSwitch => 'switched', + _ => 'scheduled', +}; + IconData _icon(ChatPromptOrigin origin) => switch (origin) { ChatPromptOrigin.followup => Icons.update, ChatPromptOrigin.autoContinue => Icons.autorenew, @@ -72,7 +81,15 @@ class ChatAutomatedPromptCard extends StatelessWidget { final tokens = AppDesignTokens.of(context); final density = tokens.density; final transcript = tokens.transcript; - final card = transcript == TranscriptStyle.manuscript + final card = transcript == TranscriptStyle.cells + ? NotebookScheduledCell( + tag: chatAutomatedPromptTag(prompt.origin), + label: label, + detail: detail, + body: body, + hasBody: prompt.body.trim().isNotEmpty, + ) + : transcript == TranscriptStyle.manuscript ? PaperEditorialNote( label: label, detail: detail, @@ -131,6 +148,7 @@ class ChatAutomatedPromptCard extends StatelessWidget { final footerInset = switch (transcript) { TranscriptStyle.prompt => 8 + terminalGlyphColumn(context), TranscriptStyle.manuscript => paperQuoteTextInset, + TranscriptStyle.cells => notebookCellTextInset, TranscriptStyle.bubbles || TranscriptStyle.boxed => 14.0, }; return ChatHoverRegion( 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 02bf69f8..a6798182 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_bubble.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_bubble.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../../../../ui/theme/app_design_tokens.dart'; import '../sessions/chat_color_palette.dart'; import 'boxed/boxed_quote.dart'; +import 'notebook/notebook_input_cell.dart'; import 'paper/paper_quote.dart'; import 'terminal/terminal_prompt_line.dart'; @@ -54,6 +55,8 @@ class ChatUserBubble extends StatelessWidget { return PaperQuote(child: child); case TranscriptStyle.boxed: return BoxedQuote(child: child); + case TranscriptStyle.cells: + return NotebookInputCell(child: child); case TranscriptStyle.bubbles: break; } 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 84c86742..dd63c27f 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -19,6 +19,9 @@ import 'chat_message_bubble.dart'; import 'chat_turn_activity_view.dart'; import 'native_disclosure.dart'; import 'boxed/boxed_quote.dart'; +import 'notebook/notebook_cell_frame.dart'; +import 'notebook/notebook_gutter.dart'; +import 'notebook/notebook_tool_cell.dart'; import 'paper/paper_quote.dart'; import 'terminal/terminal_glyphs.dart'; import 'chat_message_timestamp.dart'; @@ -39,8 +42,14 @@ class ChatMessageView extends StatelessWidget { this.images, this.speechScope = 'chat', this.scheduleShown = false, + this.cell, }); + /// The turn's number under a notebook transcript (`In [n]:` and + /// `Out [n]:`, see [chatCellNumbers]); null for a prompt not yet run or + /// an answer without one. Other transcripts ignore it. + final int? cell; + /// Whether [footer] already says the message is scheduled (its delivery /// line reads "Scheduled · sends at …"), so the operator's own scheduled /// message needs no second mark. @@ -88,6 +97,7 @@ class ChatMessageView extends StatelessWidget { final transcript = tokens.transcript; final trailingUser = user && !automated && transcript == TranscriptStyle.bubbles; + final cells = transcript == TranscriptStyle.cells; // No visible role label: side and surface say who spoke and the row's // semantics label names the role. The operator's turn is a neutral bubble // that shrinks to its content; the agent's answer sits on the page with no @@ -107,13 +117,18 @@ class ChatMessageView extends StatelessWidget { child: Padding( // A manuscript leaves a little more air between turns, as a page // spaces its paragraphs, since no bubble sets them apart; a dense - // design a little less. - padding: EdgeInsets.symmetric( - vertical: switch (transcript) { - TranscriptStyle.manuscript || TranscriptStyle.boxed => 12, - _ => tokens.density.space(6), - }, - ), + // design a little less. A notebook keeps a turn's In and Out cells + // close and sets the next turn further off, so each prompt and its + // answer read as one. + padding: cells + ? EdgeInsets.only(top: user ? 6 : 3, bottom: user ? 3 : 6) + : EdgeInsets.symmetric( + vertical: + transcript == TranscriptStyle.manuscript || + transcript == TranscriptStyle.boxed + ? 12 + : tokens.density.space(6), + ), child: LayoutBuilder( builder: (context, constraints) => Align( alignment: trailingUser @@ -124,14 +139,28 @@ class ChatMessageView extends StatelessWidget { // sides read as a conversation; the answer keeps a readable // measure on a wide pane. constraints: BoxConstraints( + // A notebook's cells span the reading column, edge to edge + // with the composer's input cell. maxWidth: trailingUser ? (constraints.maxWidth * 0.85).clamp(0, 560).toDouble() + : cells + ? double.infinity : 720 + gutter, ), child: automated - ? _automatedTurn(origin, content) + ? _inCell( + context, + _automatedTurn(origin, content), + line: Theme.of(context).textTheme.labelMedium, + enabled: cells, + ) : user - ? _userTurn(content, body, origin, transcript: transcript) + ? _inCell( + context, + _userTurn(content, body, origin, transcript: transcript), + line: chatMessageTextStyle(context), + enabled: cells, + ) : _agentRow( context, content, @@ -145,6 +174,27 @@ class ChatMessageView extends StatelessWidget { ); } + /// Under a notebook, the operator's turn in its gutter: `In [n]:` on the + /// input cell's first line. + Widget _inCell( + BuildContext context, + Widget turn, { + required TextStyle? line, + required bool enabled, + }) { + if (!enabled) return turn; + final thumbnails = _partsOf( + _userMessage, + ).any((part) => _isFile(part) && chatPartIsThumbnail(part)); + return NotebookGutterRow( + label: notebookInLabel(cell), + color: notebookInColor(Theme.of(context).colorScheme), + top: thumbnails ? 0 : notebookCellPadding.top, + line: thumbnails ? null : line, + child: turn, + ); + } + Color _secondaryColor(BuildContext context) => Theme.of(context).colorScheme.onSurfaceVariant; @@ -197,7 +247,14 @@ class ChatMessageView extends StatelessWidget { const SizedBox(height: 2), Padding( // Under a manuscript the line starts at the quoted text. - padding: EdgeInsetsDirectional.only(start: _quoteInset(transcript)), + padding: EdgeInsetsDirectional.only( + start: switch (transcript) { + TranscriptStyle.manuscript => paperQuoteTextInset, + TranscriptStyle.cells => notebookCellTextInset, + TranscriptStyle.boxed => boxedQuoteTextInset, + _ => 0, + }, + ), child: Wrap( key: const Key('chat-message-footer'), spacing: 8, @@ -297,7 +354,11 @@ class ChatMessageView extends StatelessWidget { ), ], ); - if (gutter <= 0) { + // A notebook keeps its Out cell's top on the In cell's rhythm: its + // actions trail the footer line, and the Copy gutter stays empty. + final cells = + AppDesignTokens.of(context).transcript == TranscriptStyle.cells; + if (gutter <= 0 || cells) { // Without a gutter the actions trail the footer line; a pointer device // shows them while the answer is hovered or one has focus. final row = actions(Axis.horizontal); @@ -312,9 +373,15 @@ class ChatMessageView extends StatelessWidget { child: child!, ), ); - return ChatHoverRegion( + final region = ChatHoverRegion( child: _agentTurn(context, content, answer, reveal), ); + return gutter <= 0 + ? region + : Padding( + padding: EdgeInsetsDirectional.only(start: gutter), + child: region, + ); } // The gutter is one button wide: Read aloud stacks above Copy, and stays // shown on a desktop while this reply reads. @@ -350,7 +417,11 @@ class ChatMessageView extends StatelessWidget { for (final part in parts) if (isChatToolPart(part)) part, ]; - final terminal = AppDesignTokens.of(context).terminal; + final transcript = AppDesignTokens.of(context).transcript; + final terminal = transcript == TranscriptStyle.prompt; + final cells = transcript == TranscriptStyle.cells; + // A notebook's answer text starts in the cells' text column. + final inset = cells ? notebookCellTextInset : chatAgentContentInset; final model = '${row['model'] ?? ''}'.trim(); // The metadata line: the model that answered and the time, muted; the // actions (when not in the gutter) trail it. @@ -364,14 +435,18 @@ class ChatMessageView extends StatelessWidget { if (chatMessageCreatedAt(row) case final time?) ChatMessageTimestamp(createdAt: time), ]; - return Column( + final activity = + row['streaming'] == true || + reasoning.isNotEmpty || + tools.isNotEmpty || + (row['activityRecords'] as List? ?? const []).isNotEmpty; + final turn = Column( mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: cells + ? CrossAxisAlignment.stretch + : CrossAxisAlignment.start, children: [ - if (row['streaming'] == true || - reasoning.isNotEmpty || - tools.isNotEmpty || - (row['activityRecords'] as List? ?? const []).isNotEmpty) + if (activity) ChatTurnActivityView( key: const Key('chat-stable-turn-activity'), parts: [ @@ -386,9 +461,7 @@ class ChatMessageView extends StatelessWidget { if (content.isNotEmpty) const SizedBox(height: 6), if (content.isNotEmpty) Padding( - padding: const EdgeInsets.symmetric( - horizontal: chatAgentContentInset, - ), + padding: EdgeInsets.symmetric(horizontal: inset), child: terminal ? _terminalAnswer(context, answer) : answer, ), // Settled permissions, questions and changes: meta rows that, like @@ -409,8 +482,7 @@ class ChatMessageView extends StatelessWidget { padding: EdgeInsetsDirectional.only( start: meta.isEmpty ? 0 - : chatAgentContentInset + - (terminal ? terminalGlyphColumn(context) : 0), + : inset + (terminal ? terminalGlyphColumn(context) : 0), end: chatAgentContentInset, ), child: Wrap( @@ -422,6 +494,32 @@ class ChatMessageView extends StatelessWidget { ), ], ); + if (!cells) return turn; + // A notebook's Out cell: `Out [n]:` on the first sub-cell's line (or + // the answer's), and while the turn runs Jupyter's `[*]` beneath it. + final scheme = Theme.of(context).colorScheme; + return NotebookGutterRow( + label: notebookOutLabel(cell), + color: notebookOutColor(scheme), + top: activity ? 4 : 0, + line: activity + ? notebookToolStyle(context) + : chatMessageTextStyle(context), + marker: row['streaming'] == true + ? Semantics( + label: 'Running', + child: Text( + '[*]', + key: const Key('chat-notebook-busy'), + style: notebookGutterStyle( + context, + AppDesignTokens.of(context).ansi?.yellow ?? scheme.primary, + ).copyWith(fontWeight: FontWeight.w700), + ), + ) + : null, + child: turn, + ); } /// The answer under a terminal design: a dot in the glyph column, as a 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 94126360..1c040d6c 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 @@ -11,6 +11,7 @@ import 'chat_response_pending.dart'; import 'chat_turn_activity_details.dart'; import 'chat_turn_chip.dart'; import 'boxed/boxed_activity_rows.dart'; +import 'notebook/notebook_tool_cells.dart'; import 'paper/paper_activity_note.dart'; import 'terminal/terminal_activity_rows.dart'; @@ -150,6 +151,14 @@ class _ChatTurnActivityViewState extends State { streaming: widget.streaming, onOpen: _open, ); + case TranscriptStyle.cells: + return NotebookToolCells( + data: data, + status: label, + streaming: widget.streaming, + seconds: seconds, + onOpen: _open, + ); case TranscriptStyle.bubbles: break; } diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_cell_frame.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_cell_frame.dart new file mode 100644 index 00000000..eaa75c8f --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_cell_frame.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; + +import '../../../../../ui/theme/app_design_tokens.dart'; + +/// The width of an input cell's accent bar along its leading edge. +const double notebookCellBar = 3; + +/// Where a cell's text starts from its leading edge: past the bar, then a +/// gap. Output text, footers and the composer's field start here too, so +/// every cell's text shares one column. +const double notebookCellTextInset = 12; + +/// The padding of a cell's content: [notebookCellTextInset] at the start, +/// a little less above and below. +const EdgeInsetsDirectional notebookCellPadding = + EdgeInsetsDirectional.fromSTEB( + notebookCellTextInset, + 8, + notebookCellTextInset, + 8, + ); + +/// The corner radius cells take: the design's, else a notebook's 5px. +double notebookCellRadius(BuildContext context) => + AppDesignTokens.of(context).radius ?? 5; + +/// A notebook cell's frame: a [fill] in the design's corners inside a +/// hairline [border], and an optional accent [bar] along the leading edge +/// clipped to the corners. Painted in one pass, with no layer, so a long +/// transcript of cells costs one picture per cell. +class NotebookCellFrame extends StatelessWidget { + const NotebookCellFrame({ + super.key, + required this.fill, + required this.border, + this.bar, + this.padding = notebookCellPadding, + this.width, + required this.child, + }); + + /// A fixed width (`double.infinity` to span a column that would shrink + /// the cell to its content); null to size to the parent's constraints. + final double? width; + + final Color fill; + final Color border; + final Color? bar; + final EdgeInsetsGeometry padding; + final Widget child; + + @override + Widget build(BuildContext context) => CustomPaint( + painter: NotebookCellPainter( + fill: fill, + border: border, + bar: bar, + radius: notebookCellRadius(context), + direction: Directionality.of(context), + ), + child: SizedBox( + width: width, + child: Padding(padding: padding, child: child), + ), + ); +} + +/// Paints [NotebookCellFrame]: fill, leading bar and a 1px border. +class NotebookCellPainter extends CustomPainter { + NotebookCellPainter({ + required this.fill, + required this.border, + required this.bar, + required this.radius, + required this.direction, + }); + + final Color fill; + final Color border; + final Color? bar; + final double radius; + final TextDirection direction; + + @override + void paint(Canvas canvas, Size size) { + final rect = Offset.zero & size; + final rounded = RRect.fromRectAndRadius(rect, Radius.circular(radius)); + canvas.drawRRect(rounded, Paint()..color = fill); + final accent = bar; + if (accent != null) { + final left = direction == TextDirection.ltr + ? 0.0 + : size.width - notebookCellBar; + canvas + ..save() + ..clipRRect(rounded) + ..drawRect( + Rect.fromLTWH(left, 0, notebookCellBar, size.height), + Paint()..color = accent, + ) + ..restore(); + } + canvas.drawRRect( + rounded.deflate(0.5), + Paint() + ..color = border + ..style = PaintingStyle.stroke + ..strokeWidth = 1, + ); + } + + @override + bool shouldRepaint(NotebookCellPainter old) => + old.fill != fill || + old.border != border || + old.bar != bar || + old.radius != radius || + old.direction != direction; +} diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_glyph.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_glyph.dart new file mode 100644 index 00000000..7a054584 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_glyph.dart @@ -0,0 +1,83 @@ +import 'package:flutter/material.dart'; + +/// The small marks a notebook's sub-cells draw: the collapse chevron and the +/// call's status. +enum NotebookGlyphKind { collapsed, expanded, done, failed, running } + +/// One [NotebookGlyphKind] stroked in [color] in a [size] square. Painted, +/// not an [Icon] (which builds five widgets), so a long transcript of tool +/// cells stays as cheap to scroll as the other designs'. +class NotebookGlyph extends StatelessWidget { + const NotebookGlyph( + this.kind, { + super.key, + required this.color, + this.size = 16, + }); + + final NotebookGlyphKind kind; + final Color color; + final double size; + + @override + Widget build(BuildContext context) => CustomPaint( + size: Size.square(size), + painter: _GlyphPainter(kind, color, Directionality.of(context)), + ); +} + +class _GlyphPainter extends CustomPainter { + const _GlyphPainter(this.kind, this.color, this.direction); + + final NotebookGlyphKind kind; + final Color color; + final TextDirection direction; + + @override + void paint(Canvas canvas, Size size) { + final s = size.width; + final stroke = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = (s / 10).clamp(1.2, 2.0) + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round; + // Points on a unit square, mirrored for a right-to-left chevron. + Offset p(double x, double y) => Offset( + (kind == NotebookGlyphKind.collapsed && direction == TextDirection.rtl + ? 1 - x + : x) * + s, + y * s, + ); + Path line(List points) { + final path = Path()..moveTo(points.first.dx, points.first.dy); + for (final point in points.skip(1)) { + path.lineTo(point.dx, point.dy); + } + return path; + } + + switch (kind) { + case NotebookGlyphKind.collapsed: + canvas.drawPath(line([p(.4, .28), p(.62, .5), p(.4, .72)]), stroke); + case NotebookGlyphKind.expanded: + canvas.drawPath(line([p(.28, .4), p(.5, .62), p(.72, .4)]), stroke); + case NotebookGlyphKind.done: + canvas.drawPath(line([p(.22, .52), p(.42, .7), p(.78, .3)]), stroke); + case NotebookGlyphKind.failed: + canvas + ..drawLine(p(.28, .28), p(.72, .72), stroke) + ..drawLine(p(.72, .28), p(.28, .72), stroke); + case NotebookGlyphKind.running: + final dot = Paint()..color = color; + for (final x in [.25, .5, .75]) { + canvas.drawCircle(p(x, .5), s / 14, dot); + } + } + } + + @override + bool shouldRepaint(_GlyphPainter old) => + old.kind != kind || old.color != color || old.direction != direction; +} diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_gutter.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_gutter.dart new file mode 100644 index 00000000..1d29e051 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_gutter.dart @@ -0,0 +1,187 @@ +import 'package:flutter/material.dart'; + +import '../../../../../ui/text/monospace.dart'; +import '../chat_message_bubble.dart'; + +/// Below this width a cell's gutter collapses: its label sits inline above +/// the cell instead of beside it, so a phone keeps the whole width for text. +const double notebookCompactWidth = 600; + +/// The gap between a gutter label's end and its cell. +const double notebookGutterGap = 8; + +/// An input cell's label: `In [n]:`, or `In [ ]:` for one not yet run. +String notebookInLabel(int? number) => 'In [${number ?? ' '}]:'; + +/// An output cell's label: `Out [n]:`, or `Out [ ]:` without a prompt. +String notebookOutLabel(int? number) => 'Out [${number ?? ' '}]:'; + +/// The style of gutter labels: the bundled monospace a step under the +/// reading size, in [color]. +TextStyle notebookGutterStyle(BuildContext context, Color color) => TextStyle( + fontFamily: appMonospaceFamily, + fontSize: (chatMessageTextStyle(context)?.fontSize ?? 15) * 0.8, + height: 1.2, + letterSpacing: 0, + color: color, +); + +/// The gutter's fixed width: ten monospace characters (`Out [123]:`) at the +/// label size, scaled with the operator's text, and the gap. Every cell +/// shares it, so labels right-align to one column. +double notebookGutterWidth(BuildContext context) { + final size = (chatMessageTextStyle(context)?.fontSize ?? 15) * 0.8; + // RobotoMono advances 0.6 em per character. + return MediaQuery.textScalerOf(context).scale(size) * 0.6 * 10 + + notebookGutterGap; +} + +/// The muted colour of an `In` label: the accent pulled towards the +/// secondary ink, as a notebook tints its input prompt. +Color notebookInColor(ColorScheme scheme) => + Color.lerp(scheme.onSurfaceVariant, scheme.primary, 0.55)!; + +/// The muted colour of an `Out` label: the tertiary (a notebook's output +/// orange) pulled towards the secondary ink. +Color notebookOutColor(ColorScheme scheme) => + Color.lerp(scheme.onSurfaceVariant, scheme.tertiary, 0.55)!; + +/// Marks a subtree already inside a cell gutter, so a row nested in another +/// (an activity group's folded turns) does not indent twice. +class NotebookGutterScope extends InheritedWidget { + const NotebookGutterScope({super.key, required super.child}); + + static bool inside(BuildContext context) => + context.getInheritedWidgetOfExactType() != null; + + @override + bool updateShouldNotify(NotebookGutterScope old) => false; +} + +/// One transcript row in a notebook: a fixed-width gutter holding [label] +/// right-aligned (with an optional [marker] beneath it), then the cell. +/// [line] is the style of the cell's first line: the label sits on that +/// line's baseline, [top] below the row's top. Without a label the gutter +/// is empty, so rows that are not cells still keep to the cells' column. +/// Narrower than [notebookCompactWidth], the label moves inline above the +/// cell and the gutter goes. +class NotebookGutterRow extends StatelessWidget { + const NotebookGutterRow({ + super.key, + this.label, + this.color, + this.top = 0, + this.line, + this.marker, + this.inline = true, + required this.child, + }); + + /// Whether a narrow row shows the label inline above the cell; false + /// drops it there (the composer, whose cell needs no number on a phone). + final bool inline; + + final String? label; + final Color? color; + final double top; + final TextStyle? line; + final Widget? marker; + final Widget child; + + @override + Widget build(BuildContext context) { + if (NotebookGutterScope.inside(context)) return child; + final scheme = Theme.of(context).colorScheme; + final style = notebookGutterStyle( + context, + color ?? scheme.onSurfaceVariant, + ); + final text = label; + // Only an empty gutter can hold other rows (an activity group's folded + // turns), so only it marks its subtree. + final row = LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth < notebookCompactWidth) { + if (text == null || !inline) return child; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.only(start: 2, bottom: 3), + child: Row( + children: [ + _label(text, style, null, TextAlign.start), + if (marker case final marker?) ...[ + const SizedBox(width: 6), + marker, + ], + ], + ), + ), + child, + ], + ); + } + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: notebookGutterWidth(context), + child: text == null + ? null + : Padding( + padding: EdgeInsetsDirectional.only( + top: top, + end: notebookGutterGap, + ), + child: marker == null + ? _label(text, style, line, TextAlign.end) + : Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + _label(text, style, line, TextAlign.end), + ?marker, + ], + ), + ), + ), + Expanded(child: child), + ], + ); + }, + ); + return text == null ? NotebookGutterScope(child: row) : row; + } + + /// The label, kept out of a transcript selection (a copied answer has no + /// prompt numbers in it) and out of semantics (the row already names + /// whose message it is). On [line]'s strut it shares that line's + /// baseline. + Widget _label( + String text, + TextStyle style, + TextStyle? line, + TextAlign align, + ) => ExcludeSemantics( + child: SelectionContainer.disabled( + child: Text( + text, + key: const Key('chat-notebook-gutter-label'), + textAlign: align, + maxLines: 1, + softWrap: false, + style: style, + strutStyle: line == null + ? null + : StrutStyle( + fontFamily: line.fontFamily, + fontFamilyFallback: line.fontFamilyFallback, + fontSize: line.fontSize, + height: line.height, + forceStrutHeight: true, + ), + ), + ), + ); +} diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_input_cell.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_input_cell.dart new file mode 100644 index 00000000..55c69e6f --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_input_cell.dart @@ -0,0 +1,150 @@ +import 'package:flutter/material.dart'; + +import '../../sessions/chat_color_palette.dart'; +import '../chat_message_bubble.dart'; +import 'notebook_cell_frame.dart'; + +/// How strongly a coloured chat's shade tints its input cells over the +/// cell grey: a hint of the colour, not a wash. +const double notebookInputTint = 0.07; + +/// The operator's turn under a notebook transcript: an input cell in the +/// light cell grey (tinted faintly by the chat's colour), framed by a +/// hairline, with a thin accent bar in the chat's colour (the accent for a +/// chat with none) along its leading edge. It spans the reading column. +class NotebookInputCell extends StatelessWidget { + const NotebookInputCell({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final shade = chatColorShade(context, ChatBubbleColor.of(context)); + final base = scheme.surfaceContainerLow; + return Material( + key: const Key('chat-notebook-input-cell'), + type: MaterialType.transparency, + child: NotebookCellFrame( + fill: shade == null + ? base + : Color.alphaBlend( + shade.withValues(alpha: notebookInputTint), + base, + ), + border: scheme.outlineVariant, + bar: shade ?? scheme.primary, + child: child, + ), + ); + } +} + +/// A prompt the agent or the server sent (a follow-up, an auto-continue, a +/// switch of account) under a notebook transcript: an input cell like the +/// operator's, its bar in the muted outline rather than the chat's colour, +/// headed by a small [tag] ("scheduled") and the [detail] of when; the +/// prompt's [body] beneath. +class NotebookScheduledCell extends StatelessWidget { + const NotebookScheduledCell({ + super.key, + required this.tag, + required this.label, + this.detail, + required this.body, + required this.hasBody, + }); + + /// The tag's word: `scheduled`, `auto-continue` or `switched`. + final String tag; + + /// What sent it, e.g. `Follow-up from agent`. + final String label; + final String? detail; + final Widget body; + final bool hasBody; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final muted = theme.textTheme.labelMedium?.copyWith( + color: scheme.onSurfaceVariant, + ); + final header = SelectionContainer.disabled( + child: Wrap( + key: const Key('chat-automated-prompt-header'), + spacing: 6, + runSpacing: 2, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + NotebookTag(tag, key: const Key('chat-notebook-scheduled-tag')), + Text(label, style: muted?.copyWith(fontWeight: FontWeight.w600)), + if (detail != null) Text('· $detail', style: muted), + ], + ), + ); + // A cell spans the column, as the operator's own do. + return Material( + key: const Key('chat-automated-prompt'), + type: MaterialType.transparency, + child: NotebookCellFrame( + width: double.infinity, + fill: scheme.surfaceContainerLow, + border: scheme.outlineVariant, + bar: scheme.outline, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + header, + if (hasBody) ...[ + const SizedBox(height: 4), + DefaultTextStyle.merge( + style: chatMessageTextStyle( + context, + )?.copyWith(color: scheme.onSurfaceVariant), + child: body, + ), + ], + ], + ), + ), + ); + } +} + +/// A notebook's small tag: a word in a hairline box in 3px corners, the +/// cell grey a step darker, as an IDE marks a cell's state. +class NotebookTag extends StatelessWidget { + const NotebookTag(this.text, {super.key, this.color}); + + final String text; + + /// The tag's ink; the secondary ink by default. + final Color? color; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return DecoratedBox( + decoration: BoxDecoration( + color: scheme.surfaceContainerHigh, + border: Border.all(color: scheme.outlineVariant), + borderRadius: const BorderRadius.all(Radius.circular(3)), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), + child: Text( + text, + style: theme.textTheme.labelSmall?.copyWith( + color: color ?? scheme.onSurfaceVariant, + letterSpacing: 0.2, + height: 1.3, + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cell.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cell.dart new file mode 100644 index 00000000..a6413d83 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cell.dart @@ -0,0 +1,296 @@ +import 'package:flutter/material.dart'; + +import '../../../../../core/api_gateway.dart'; +import '../../../../../ui/text/monospace.dart'; +import '../../../../../ui/theme/app_design_tokens.dart'; +import '../../../domain/chat_tool_calls.dart'; +import '../chat_message_bubble.dart'; +import 'notebook_cell_frame.dart'; +import 'notebook_glyph.dart'; + +/// How many lines of a call's output its collapsed sub-cell previews. +const int notebookToolPreviewLines = 1; + +/// The most lines an expanded sub-cell draws in place; the rest stay in the +/// activity details. +const int notebookToolExpandedLines = 400; + +/// Where a sub-cell's text starts: past the collapse chevron, so the +/// preview and the output line up under the tool's name. +const double notebookToolTextInset = 26; + +/// The monospace style of a tool sub-cell at the reading size's step down. +TextStyle notebookToolStyle(BuildContext context) => TextStyle( + fontFamily: appMonospaceFamily, + fontSize: (chatMessageTextStyle(context)?.fontSize ?? 15) * 0.82, + height: 1.4, + letterSpacing: 0, + color: Theme.of(context).colorScheme.onSurface, +); + +/// The first [notebookToolPreviewLines] non-blank lines of [text] and how +/// many lines follow them. +({String preview, int more}) notebookToolPreview(String text) { + final lines = text.trimRight().split('\n'); + var start = 0; + while (start < lines.length && lines[start].trim().isEmpty) { + start++; + } + final end = (start + notebookToolPreviewLines).clamp(0, lines.length); + return ( + preview: lines.sublist(start, end).map((l) => l.trimRight()).join('\n'), + more: lines.length - end, + ); +} + +/// One tool call as a notebook sub-cell: a header with the collapse +/// chevron, the tool's name and arguments, and its duration and status on +/// the right; beneath it, collapsed, the first lines of the output with +/// "+N lines", or, expanded in place, the call's input and output. The +/// expanded body is built only once opened. +class NotebookToolCell extends StatefulWidget { + const NotebookToolCell({super.key, required this.call}); + + final JsonMap call; + + @override + State createState() => _NotebookToolCellState(); +} + +class _NotebookToolCellState extends State { + bool _expanded = false; + + // The preview of the last output seen, so a running turn's ticking + // rebuilds do not split a long output again. + String? _source; + ({String preview, int more}) _preview = (preview: '', more: 0); + + void _toggle() => setState(() => _expanded = !_expanded); + + ({String preview, int more}) _previewOf(String text) { + if (!identical(text, _source) && text != _source) { + _source = text; + _preview = notebookToolPreview(text); + } + return _preview; + } + + @override + Widget build(BuildContext context) { + final call = widget.call; + final scheme = Theme.of(context).colorScheme; + final ansi = AppDesignTokens.of(context).ansi; + final style = notebookToolStyle(context); + final muted = style.copyWith(color: scheme.onSurfaceVariant); + final failed = chatToolFailed(call); + final running = chatToolRunning(call); + final name = chatToolLabel(call); + final detail = chatToolDetail(call); + final millis = chatToolDurationMillis(call); + final output = running + ? '' + : failed + ? chatToolErrorText(call) + : chatToolOutputText(call); + final (statusGlyph, statusColor, statusWord) = failed + ? (NotebookGlyphKind.failed, ansi?.red ?? scheme.error, 'failed') + : running + ? ( + NotebookGlyphKind.running, + ansi?.yellow ?? scheme.tertiary, + 'running', + ) + : (NotebookGlyphKind.done, ansi?.green ?? scheme.primary, 'done'); + final header = Semantics( + button: true, + expanded: _expanded, + label: [ + name, + ?detail, + if (millis != null) formatChatToolDuration(millis), + statusWord, + ].join(', '), + excludeSemantics: true, + onTap: _toggle, + // A plain tap target with the pointer's click cursor rather than an + // InkWell: a transcript holds many sub-cells, and an InkWell's focus, + // actions and ink would double what each costs to build. + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + key: const Key('chat-notebook-tool-header'), + behavior: HitTestBehavior.opaque, + onTap: _toggle, + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(6, 4, 10, 4), + child: Row( + children: [ + NotebookGlyph( + _expanded + ? NotebookGlyphKind.expanded + : NotebookGlyphKind.collapsed, + size: 18, + color: scheme.onSurfaceVariant, + ), + const SizedBox(width: 2), + Expanded( + child: Text.rich( + TextSpan( + children: [ + TextSpan( + text: name, + style: const TextStyle(fontWeight: FontWeight.w700), + ), + if (detail != null) + TextSpan(text: ' $detail', style: muted), + ], + ), + style: style, + maxLines: 1, + softWrap: false, + overflow: TextOverflow.ellipsis, + ), + ), + if (millis != null) ...[ + const SizedBox(width: 12), + Text( + formatChatToolDuration(millis), + key: const Key('chat-notebook-tool-duration'), + style: muted, + ), + ], + const SizedBox(width: 8), + NotebookGlyph( + statusGlyph, + key: const Key('chat-notebook-tool-status'), + size: 15, + color: statusColor, + ), + ], + ), + ), + ), + ), + ); + final body = _expanded + ? _expandedBody(call, style, muted, failed ? statusColor : null) + : _collapsedBody(output, style, muted, failed ? statusColor : null); + return NotebookCellFrame( + key: const Key('chat-notebook-tool-cell'), + fill: scheme.surfaceContainerLow, + border: scheme.outlineVariant, + padding: EdgeInsets.zero, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [header, ?body], + ), + ); + } + + Widget? _collapsedBody( + String output, + TextStyle style, + TextStyle muted, + Color? error, + ) { + if (output.trim().isEmpty) return null; + final (:preview, :more) = _previewOf(output); + if (preview.isEmpty) return null; + // The first line, and how many follow it at the line's end, under the + // duration: one line per collapsed call, as a notebook folds an output. + return _section( + Row( + key: const Key('chat-notebook-tool-preview'), + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: Text( + preview, + maxLines: notebookToolPreviewLines, + softWrap: false, + overflow: TextOverflow.ellipsis, + style: error == null ? muted : muted.copyWith(color: error), + ), + ), + if (more > 0) const SizedBox(width: 12), + if (more > 0) + Text( + '+$more ${more == 1 ? 'line' : 'lines'}', + key: const Key('chat-notebook-tool-more'), + style: muted.copyWith( + fontStyle: FontStyle.italic, + color: Theme.of(context).colorScheme.outline, + ), + ), + ], + ), + ); + } + + Widget _expandedBody( + JsonMap call, + TextStyle style, + TextStyle muted, + Color? error, + ) { + final input = chatToolInputText(call).trimRight(); + final running = chatToolRunning(call); + final output = running + ? 'running…' + : error != null + ? chatToolErrorText(call) + : chatToolOutputText(call); + final lines = output.trimRight().split('\n'); + final cut = lines.length > notebookToolExpandedLines; + final shown = cut + ? lines.take(notebookToolExpandedLines).join('\n') + : output.trimRight(); + final heading = muted.copyWith( + fontSize: (muted.fontSize ?? 12) * 0.9, + fontWeight: FontWeight.w600, + ); + return _section( + Column( + key: const Key('chat-notebook-tool-output'), + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (input.isNotEmpty) ...[ + Text('input', style: heading), + Text(input, style: muted), + const SizedBox(height: 6), + ], + Text(error != null ? 'error' : 'output', style: heading), + Text( + shown, + style: error == null ? style : style.copyWith(color: error), + ), + if (cut) + Text( + '… ${lines.length - notebookToolExpandedLines} more lines ' + 'in the activity details', + style: muted.copyWith(fontStyle: FontStyle.italic), + ), + ], + ), + ); + } + + /// A body section under the header's hairline, its text under the name. + Widget _section(Widget child) => DecoratedBox( + decoration: BoxDecoration( + border: Border( + top: BorderSide(color: Theme.of(context).colorScheme.outlineVariant), + ), + ), + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB( + notebookToolTextInset, + 4, + 10, + 5, + ), + child: child, + ), + ); +} diff --git a/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cells.dart b/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cells.dart new file mode 100644 index 00000000..8d5cd7f0 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/notebook/notebook_tool_cells.dart @@ -0,0 +1,163 @@ +import 'package:flutter/material.dart'; + +import '../../../../../core/api_gateway.dart'; +import '../../../../../ui/theme/app_design_tokens.dart'; +import '../../../domain/chat_turn_activity.dart'; +import '../chat_response_pending.dart'; +import 'notebook_glyph.dart'; +import 'notebook_tool_cell.dart'; + +/// How many of a turn's calls the Out cell lists before folding the earlier +/// ones behind "Show N earlier". +const int notebookToolMaxCalls = 8; + +/// The gap between two sub-cells. +const double notebookSubCellGap = 4; + +/// A turn's activity under a notebook transcript: each tool call as a +/// collapsible sub-cell ([NotebookToolCell]), the latest +/// [notebookToolMaxCalls] shown and the rest behind one "Show N earlier" +/// line, then the turn's status line: while it runs, what it is doing and +/// for how long in the accent; once settled, its summary ("Used 3 tools"). +/// The status line opens the activity details, as every design's does. +class NotebookToolCells extends StatefulWidget { + const NotebookToolCells({ + super.key, + required this.data, + required this.status, + required this.streaming, + required this.onOpen, + this.seconds = 0, + }); + + final ChatTurnActivityData data; + final String status; + final bool streaming; + final VoidCallback onOpen; + final int seconds; + + @override + State createState() => _NotebookToolCellsState(); +} + +class _NotebookToolCellsState extends State { + bool _all = false; + + @override + Widget build(BuildContext context) { + final calls = widget.data.tools; + final shown = _all || calls.length <= notebookToolMaxCalls + ? calls + : calls.sublist(calls.length - notebookToolMaxCalls); + final hidden = calls.length - shown.length; + return Column( + key: const Key('chat-notebook-tool-cells'), + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (hidden > 0) _earlier(context, hidden), + for (var index = 0; index < shown.length; index++) + Padding( + key: ValueKey('chat-notebook-tool-${_id(shown[index])}'), + padding: const EdgeInsets.only(bottom: notebookSubCellGap), + child: NotebookToolCell(call: shown[index]), + ), + _statusLine(context), + ], + ); + } + + String _id(JsonMap call) => '${call['id'] ?? identityHashCode(call)}'; + + Widget _earlier(BuildContext context, int hidden) { + final scheme = Theme.of(context).colorScheme; + return Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton( + key: const Key('chat-notebook-tool-earlier'), + style: TextButton.styleFrom( + minimumSize: const Size(0, 28), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + foregroundColor: scheme.onSurfaceVariant, + textStyle: notebookToolStyle(context), + ), + onPressed: () => setState(() => _all = true), + child: Text( + 'Show $hidden earlier tool ${hidden == 1 ? 'call' : 'calls'}', + ), + ), + ); + } + + /// The turn's status: the pending dots and the live label while it runs, + /// else the muted summary with a chevron. Opens the activity details. + Widget _statusLine(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final accent = AppDesignTokens.of(context).ansi?.yellow ?? scheme.primary; + final failed = widget.data.failed && !widget.streaming; + final color = widget.streaming + ? accent + : failed + ? scheme.error + : scheme.onSurfaceVariant; + final style = notebookToolStyle(context).copyWith(color: color); + final text = widget.streaming + ? '${widget.data.label}… ${widget.seconds}s' + : widget.status; + return Semantics( + button: true, + label: '${widget.status}, expand for details', + excludeSemantics: true, + onTap: widget.onOpen, + child: Align( + alignment: AlignmentDirectional.centerStart, + widthFactor: 1, + // A plain tap target, as the sub-cells' headers are (see + // NotebookToolCell): cheap to build in a long transcript. + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + key: const Key('chat-turn-activity'), + behavior: HitTestBehavior.opaque, + onTap: widget.onOpen, + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 24), + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(6, 2, 8, 2), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.streaming) + ExcludeSemantics( + child: DefaultTextStyle.merge( + style: TextStyle(color: accent), + child: const ChatResponsePending(), + ), + ) + else + NotebookGlyph( + NotebookGlyphKind.collapsed, + size: 18, + color: color, + ), + const SizedBox(width: 2), + Flexible( + child: Text( + text, + key: const Key('chat-notebook-status'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: style, + ), + ), + ], + ), + ), + ), + ), + ), + ), + ); + } +} 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_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 77a3722b..587c6c4c 100644 --- a/app/lib/features/graph/widgets/definition_graph_view.dart +++ b/app/lib/features/graph/widgets/definition_graph_view.dart @@ -176,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, @@ -216,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_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 f03be1ed..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; @@ -327,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, @@ -337,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/pipelines/pipeline_filter.dart b/app/lib/features/pipelines/pipeline_filter.dart index 29658e8a..2e29c6d3 100644 --- a/app/lib/features/pipelines/pipeline_filter.dart +++ b/app/lib/features/pipelines/pipeline_filter.dart @@ -157,8 +157,11 @@ PipelineEmptyState? pipelineListEmptyState( if (items.isNotEmpty) return null; if (all.isEmpty) { return const PipelineEmptyState( - 'No pipelines yet.', - detail: 'Create one from a template in Templates.', + 'No pipelines yet', + detail: + 'A pipeline is a workflow you define once and run on many tasks. ' + 'Start from a template, or create one with `pipelines new` on the ' + 'server.', ); } final name = filters.name; diff --git a/app/lib/features/pipelines/screen.dart b/app/lib/features/pipelines/screen.dart index e60eebe6..808f7dad 100644 --- a/app/lib/features/pipelines/screen.dart +++ b/app/lib/features/pipelines/screen.dart @@ -40,6 +40,7 @@ class PipelinesScreen extends StatefulWidget { this.onViewPipelineRuns, this.onSelectionChanged, this.onOpenSchedules, + this.onOpenTemplates, this.onOpenSettings, this.initialPipelineId, this.initialVersion = 0, @@ -77,6 +78,9 @@ class PipelinesScreen extends StatefulWidget { /// Opens every schedule; shown in the bar while the list is visible. final VoidCallback? onOpenSchedules; + /// Opens the Templates gallery from the empty list. + final VoidCallback? onOpenTemplates; + /// Opens Settings as a page; a gear in the bar while the list is visible. final VoidCallback? onOpenSettings; @@ -278,6 +282,7 @@ class _PipelinesScreenState extends State { controller: _controller, onOpenInChat: widget.onOpenPipelineInChat, onRun: _runFromList, + onOpenTemplates: widget.onOpenTemplates, ), ); } @@ -287,6 +292,7 @@ class _PipelinesScreenState extends State { controller: _controller, onOpenInChat: widget.onOpenPipelineInChat, onRun: _runFromList, + onOpenTemplates: widget.onOpenTemplates, ), ), detailIdentity: _controller.selectedId, diff --git a/app/lib/features/pipelines/widgets/pipeline_list_panel.dart b/app/lib/features/pipelines/widgets/pipeline_list_panel.dart index fdf89b16..3e2b4b79 100644 --- a/app/lib/features/pipelines/widgets/pipeline_list_panel.dart +++ b/app/lib/features/pipelines/widgets/pipeline_list_panel.dart @@ -6,6 +6,7 @@ import 'package:flutter/material.dart'; import '../../../shell/shell_list_shortcuts.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/segmented_bar_overflow.dart'; +import '../../../ui/status/empty_state.dart'; import '../../../ui/status/run_status_icon.dart'; import '../pipeline_format.dart'; import '../pipeline_models.dart'; @@ -22,14 +23,21 @@ import 'pipeline_row_actions.dart'; const double kPipelineListInset = 12; /// The left/top pane: filter and sort controls, then the truthful list states. +/// The state a server without any pipeline shows. +const pipelinesEmptyKey = ValueKey('pipelines-empty'); + class PipelineListPanel extends StatelessWidget { const PipelineListPanel({ super.key, required this.controller, this.onOpenInChat, this.onRun, + this.onOpenTemplates, }); + /// Opens the Templates gallery; an empty server offers it as the next step. + final VoidCallback? onOpenTemplates; + final PipelinesController controller; final Future Function(BuildContext, PipelineSummary, PipelineRun?)? onOpenInChat; @@ -194,34 +202,31 @@ class PipelineListPanel extends StatelessWidget { } Widget _empty(BuildContext context, PipelineEmptyState empty) { - return Center( - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - empty.message, - textAlign: TextAlign.center, - style: _mutedStyle(context), + // A filter that hides every row is not an empty server: name it and + // offer the way back. + if (empty.clearAction case final clear?) { + return EmptyState( + dense: true, + icon: Icons.filter_alt_off_outlined, + title: empty.message, + message: empty.detail, + action: emptyStateAction(clear, controller.clearFilters), + ); + } + final templates = onOpenTemplates; + return EmptyState( + key: pipelinesEmptyKey, + dense: true, + icon: Icons.account_tree_outlined, + title: empty.message, + message: empty.detail, + action: templates == null + ? null + : emptyStateAction( + 'Browse templates', + templates, + icon: Icons.library_add_outlined, ), - if (empty.detail != null) - Padding( - padding: const EdgeInsets.only(top: 4), - child: Text( - empty.detail!, - textAlign: TextAlign.center, - style: _mutedStyle(context), - ), - ), - if (empty.clearAction != null) - PipelineTextButton( - label: empty.clearAction!, - onPressed: controller.clearFilters, - ), - ], - ), - ), ); } @@ -339,13 +344,6 @@ class PipelineListPanel extends StatelessWidget { ].join(' · '); } - TextStyle? _mutedStyle(BuildContext context) { - final theme = Theme.of(context); - return theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ); - } - /// The pipeline's initial on a tint picked from its id, so neighbouring /// pipelines are told apart at a glance. Widget _pipelineIdentityIcon(BuildContext context, PipelineSummary pipeline) { diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index 47867977..763bf2b4 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -377,6 +377,7 @@ class _RunsScreenState extends State { attention: widget.attention, onOpenInChat: widget.onOpenInChat, onRunAgain: _runAgain, + onNewRun: _startNewRun, ), ), ); diff --git a/app/lib/features/runs/ui/run_failure_banner.dart b/app/lib/features/runs/ui/run_failure_banner.dart index 863fffeb..51a85cb8 100644 --- a/app/lib/features/runs/ui/run_failure_banner.dart +++ b/app/lib/features/runs/ui/run_failure_banner.dart @@ -1,9 +1,13 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; +import '../../../core/error_advice.dart'; import '../domain/run_outcome_line.dart'; import '../../../ui/theme/app_design_tokens.dart'; +/// The setup step a run that failed for want of an agent harness shows. +const runFailureHarnessHintKey = ValueKey('run-failure-harness-hint'); + /// The run Summary's prominent "Why it failed" note: a failed run's recorded /// failure reason (else its diagnostic), selectable, at the top of the /// Summary so the reason is read before the facts. Nothing for other runs. @@ -61,6 +65,19 @@ class RunFailureBanner extends StatelessWidget { color: scheme.onErrorContainer, ), ), + // A server without an agent harness is a setup step: + // say which, beside the raw reason. + if (needsHarnessSetup(outcome.full)) ...[ + const SizedBox(height: 8), + Text( + errorAdviceSentence(ErrorAdviceKind.noHarness), + key: runFailureHarnessHintKey, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onErrorContainer, + fontWeight: FontWeight.w600, + ), + ), + ], if (actions case final actions?) ...[ const SizedBox(height: 8), actions, diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 1504eac8..8631cdb5 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -18,10 +18,14 @@ import 'runs_filter_options.dart'; import 'runs_selection_bar.dart'; import 'runs_stats_page.dart'; import 'runs_filters.dart'; +import '../../../ui/status/empty_state.dart'; import '../../../ui/status/error_notice.dart'; export 'run_list_row.dart'; +/// The state a server with no runs at all shows. +const runsEmptyKey = ValueKey('runs-empty'); + class RunsList extends StatelessWidget { const RunsList({ super.key, @@ -35,8 +39,12 @@ class RunsList extends StatelessWidget { this.active = true, this.onOpenInChat, this.onRunAgain, + this.onNewRun, }); + /// Starts a new run; the empty list offers it as its next step. + final VoidCallback? onNewRun; + /// False while a run detail covers the list; the bar is then the run's. final bool active; final Future Function(BuildContext, JsonMap)? onOpenInChat; @@ -184,12 +192,21 @@ class RunsList extends StatelessWidget { ...header, Expanded( child: noRunsAtAll - ? _state( - context, - icon: const Icon(Icons.inbox_outlined), - title: 'No runs yet.', - subtitle: - 'Start one from Pipelines and its runs appear here.', + ? EmptyState( + key: runsEmptyKey, + dense: true, + icon: Icons.play_circle_outline, + title: 'No runs yet', + message: + 'A run is a pipeline working on one task. Start one ' + 'and follow its progress and results here.', + action: onNewRun == null + ? null + : emptyStateAction( + 'Start your first run', + onNewRun!, + icon: Icons.add, + ), ) : _state( context, diff --git a/app/lib/features/schedules/ui/list/schedule_list_view.dart b/app/lib/features/schedules/ui/list/schedule_list_view.dart index 370b8e00..0a17ba33 100644 --- a/app/lib/features/schedules/ui/list/schedule_list_view.dart +++ b/app/lib/features/schedules/ui/list/schedule_list_view.dart @@ -7,9 +7,13 @@ import '../../domain/saved_schedule.dart'; import 'schedule_list_controller.dart'; import 'schedule_list_row.dart'; import 'schedule_list_toolbar.dart'; +import '../../../../ui/status/empty_state.dart'; import '../../../../ui/status/error_notice.dart'; const scheduleListKey = ValueKey('schedule-list'); + +/// The state a server without any saved schedule shows. +const schedulesEmptyKey = ValueKey('schedules-empty'); const scheduleRetryKey = ValueKey('schedule-retry'); const scheduleToolbarKey = ValueKey('schedule-toolbar'); @@ -75,9 +79,13 @@ class SchedulesListView extends StatelessWidget { } if (controller.schedules.isEmpty) { return BelowTopBar( - child: _emptyState( - 'No schedules yet.', - detail: 'Saved run configurations, not pipeline definitions.', + child: const EmptyState( + key: schedulesEmptyKey, + icon: Icons.event_repeat_outlined, + title: 'No schedules yet', + message: + 'A schedule runs a pipeline for you on a timetable. Open a ' + "pipeline's Run form and choose Schedule… to add one.", ), ); } @@ -140,29 +148,8 @@ class SchedulesListView extends StatelessWidget { ); } - Widget _emptyState(String message, {String? detail}) { - return Center( - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text(message, textAlign: TextAlign.center), - if (detail != null) - Builder( - builder: (context) => Text( - detail, - textAlign: TextAlign.center, - style: TextStyle( - color: Theme.of(context).colorScheme.onSurfaceVariant, - ), - ), - ), - ], - ), - ), - ); - } + Widget _emptyState(String message) => + EmptyState(icon: Icons.search_off_outlined, title: message, dense: true); Widget _failureState(BuildContext context, ScheduleListFailure failure) { return Center( 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_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_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_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 838beb5f..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'; diff --git a/app/lib/features/templates/screen.dart b/app/lib/features/templates/screen.dart index 9c80ab1f..fbf272ea 100644 --- a/app/lib/features/templates/screen.dart +++ b/app/lib/features/templates/screen.dart @@ -52,9 +52,15 @@ class TemplatesScreen extends StatefulWidget { this.embedded = false, this.onCreated, this.initialKey, + this.reloadToken = 0, }); final ApiGateway gateway; + + /// Advances when the shared connection is (re)established. A gallery that + /// could not be read (opened before the app had connected, or while it was + /// offline) reads again then, instead of keeping the failure until Retry. + final int reloadToken; final bool embedded; final ValueChanged? onCreated; @@ -88,7 +94,13 @@ class _TemplatesScreenState extends State { if (oldWidget.initialKey != widget.initialKey) { _selectedKey = widget.initialKey; } - if (oldWidget.gateway == widget.gateway) return; + if (oldWidget.gateway == widget.gateway) { + if (oldWidget.reloadToken != widget.reloadToken && + (_error != null || !_loaded)) { + unawaited(_load()); + } + return; + } // A different gateway is a different server: never keep this one's rows or // selection while the replacement is read. _repository = TemplateRepository(widget.gateway); diff --git a/app/lib/features/walkthrough/walkthrough_gate.dart b/app/lib/features/walkthrough/walkthrough_gate.dart index 5fb6e7c2..2b5b822c 100644 --- a/app/lib/features/walkthrough/walkthrough_gate.dart +++ b/app/lib/features/walkthrough/walkthrough_gate.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:flutter/widgets.dart'; import '../../core/api_gateway.dart'; +import '../../core/error_advice.dart'; import 'first_run_walkthrough.dart'; import 'walkthrough_store.dart'; @@ -11,19 +12,31 @@ import 'walkthrough_store.dart'; /// triggers the walkthrough. Future serverHasNoWorkYet(ApiGateway? gateway) async { if (gateway == null) return null; + // A server leaves an empty list out of its reply. + Future?> list(String type, String key, [JsonMap? fields]) => + gateway.call(type, fields ?? const {}).then((reply) { + final value = reply[key] ?? const []; + return value is List ? List.from(value) : null; + }); + Future?> chats() async { + try { + return await list('chat_sessions', 'chat_sessions'); + } catch (error) { + // A server without a chat harness has no chats yet; that is the newest + // server of all, not an unreadable one. + if (needsHarnessSetup(error)) return const []; + rethrow; + } + } + try { - final replies = await Future.wait(>[ - gateway.call('list_pipelines', {'include_archived': true}), - gateway.call('list_runs'), - gateway.call('chat_sessions'), + final lists = await Future.wait(?>>[ + list('list_pipelines', 'pipelines', {'include_archived': true}), + list('list_runs', 'runs'), + chats(), ]); - final lists = [ - replies[0]['pipelines'], - replies[1]['runs'], - replies[2]['chat_sessions'], - ]; - if (lists.any((list) => list is! List)) return null; - return lists.every((list) => (list as List).isEmpty); + if (lists.any((list) => list == null)) return null; + return lists.every((list) => list!.isEmpty); } catch (_) { return null; } @@ -55,8 +68,13 @@ class FirstRunWalkthroughGate extends StatefulWidget { required this.connected, this.gateway, this.onOpenConnection, + this.connectWait = const Duration(seconds: 3), }); + /// How long the first offer waits for a connection before it shows the + /// walkthrough with its connect page. + final Duration connectWait; + /// Opens Settings' Connection from the walkthrough's connect page. final VoidCallback? onOpenConnection; @@ -115,6 +133,7 @@ class _FirstRunWalkthroughGateState extends State { @override void dispose() { + _endConnectionWait(); widget.connection.removeListener(_onConnectionChanged); super.dispose(); } @@ -170,6 +189,10 @@ class _FirstRunWalkthroughGateState extends State { if (!_active) return; if (!seen) { _decided = true; + // The app usually connects within a moment of its first frame (always + // on the web, which is served by the server). Wait briefly so a + // connected app is not told to connect. + if (!widget.connected()) await _connection(widget.connectWait); await _showIfActive(); return; } @@ -190,6 +213,31 @@ class _FirstRunWalkthroughGateState extends State { await _showIfActive(); } + /// The first offer's wait for a connection; ended early by [dispose]. + Timer? _connectTimer; + Completer? _connectWaiting; + + /// Completes when the session connects or after [limit], whichever is + /// first, or as soon as the gate is disposed. + Future _connection(Duration limit) { + final done = _connectWaiting = Completer(); + void check() { + if (widget.connected()) _endConnectionWait(); + } + + final listenable = widget.connection..addListener(check); + _connectTimer = Timer(limit, _endConnectionWait); + return done.future.whenComplete(() => listenable.removeListener(check)); + } + + void _endConnectionWait() { + _connectTimer?.cancel(); + _connectTimer = null; + final waiting = _connectWaiting; + _connectWaiting = null; + if (waiting != null && !waiting.isCompleted) waiting.complete(); + } + Future _showIfActive() async { if (!_active) return; await _show(); diff --git a/app/lib/ui/status/empty_state.dart b/app/lib/ui/status/empty_state.dart new file mode 100644 index 00000000..6e87a19e --- /dev/null +++ b/app/lib/ui/status/empty_state.dart @@ -0,0 +1,143 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_design_tokens.dart'; + +/// One button of an [EmptyState]: a label, an optional icon and its action. +typedef EmptyStateAction = ({ + String label, + IconData? icon, + VoidCallback onPressed, +}); + +/// Builds an [EmptyStateAction]; a named constructor reads better at call +/// sites than a record literal. +EmptyStateAction emptyStateAction( + String label, + VoidCallback onPressed, { + IconData? icon, +}) => (label: label, icon: icon, onPressed: onPressed); + +/// What a list shows when it has nothing yet: never an error, always a next +/// step. One look on every screen: a large icon on a tonal disc, a short +/// title, one muted line of explanation and up to two actions (the primary +/// one filled). [child] adds content under the message, such as a command to +/// copy. The whole state scrolls in a short pane instead of overflowing. +/// +/// Shapes follow the active design: the disc takes the design's corner +/// radius (square under Terminal, round under Classic and Paper). +class EmptyState extends StatelessWidget { + const EmptyState({ + super.key, + required this.icon, + required this.title, + this.message, + this.action, + this.secondaryAction, + this.child, + this.dense = false, + }); + + final IconData icon; + final String title; + final String? message; + final EmptyStateAction? action; + final EmptyStateAction? secondaryAction; + final Widget? child; + + /// A smaller icon and tighter spacing, for narrow list panes. + final bool dense; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final tokens = AppDesignTokens.of(context); + final disc = dense ? 56.0 : 72.0; + final primary = action; + final secondary = secondaryAction; + return Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Semantics( + container: true, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + DecoratedBox( + decoration: BoxDecoration( + color: scheme.secondaryContainer, + borderRadius: tokens.corners( + BorderRadius.circular(disc / 2), + ), + ), + child: SizedBox.square( + dimension: disc, + child: Icon( + icon, + size: disc / 2, + color: scheme.onSecondaryContainer, + ), + ), + ), + SizedBox(height: dense ? 12 : 16), + Text( + title, + textAlign: TextAlign.center, + style: theme.textTheme.titleMedium, + ), + if (message case final message?) ...[ + const SizedBox(height: 6), + Text( + message, + textAlign: TextAlign.center, + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ], + if (child case final child?) ...[ + const SizedBox(height: 16), + child, + ], + if (primary != null || secondary != null) ...[ + SizedBox(height: dense ? 16 : 20), + Wrap( + alignment: WrapAlignment.center, + spacing: 8, + runSpacing: 8, + children: [ + if (primary != null) + primary.icon == null + ? FilledButton( + onPressed: primary.onPressed, + child: Text(primary.label), + ) + : FilledButton.icon( + onPressed: primary.onPressed, + icon: Icon(primary.icon), + label: Text(primary.label), + ), + if (secondary != null) + secondary.icon == null + ? TextButton( + onPressed: secondary.onPressed, + child: Text(secondary.label), + ) + : TextButton.icon( + onPressed: secondary.onPressed, + icon: Icon(secondary.icon), + label: Text(secondary.label), + ), + ], + ), + ], + ], + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/ui/theme/app_design.dart b/app/lib/ui/theme/app_design.dart index c604d47e..c6772871 100644 --- a/app/lib/ui/theme/app_design.dart +++ b/app/lib/ui/theme/app_design.dart @@ -4,6 +4,7 @@ import 'app_design_tokens.dart'; import 'app_theme.dart'; import 'compact_theme.dart'; import 'high_contrast_theme.dart'; +import 'notebook_theme.dart'; import 'paper_theme.dart'; import 'terminal_theme.dart'; @@ -61,6 +62,14 @@ enum AppDesign { 'Classic’s Material look, dense: small type, thin rows, more on screen.', ), + /// A notebook IDE look: the chat as numbered In/Out cells with tool calls + /// as collapsible sub-cells, light grey cells and hairline borders. + notebook( + 'notebook', + 'Notebook', + 'Numbered In/Out cells, like Jupyter; tidy for tool-heavy work.', + ), + /// An accessible look: pure black or white, larger type, 2px borders, /// 48px targets and a thick focus ring; readable in sunlight. highContrast( @@ -121,6 +130,7 @@ enum AppDesign { (terminal, _) => terminalTheme(brightness), (paper, _) => paperTheme(brightness, fontFamily: fontFamily), (compact, _) => compactTheme(brightness, fontFamily: fontFamily), + (notebook, _) => notebookTheme(brightness, fontFamily: fontFamily), (highContrast, _) => highContrastTheme(brightness, fontFamily: fontFamily), }; @@ -175,6 +185,18 @@ enum AppDesign { Color(0xFF221E19), Color(0xFF2C4F86), ), + notebook => + dark + ? const DesignSwatch( + Color(0xFF17181A), + Color(0xFFE4E5E7), + Color(0xFF7FB0F0), + ) + : const DesignSwatch( + Color(0xFFFFFFFF), + Color(0xFF1F2124), + Color(0xFF1F5FBF), + ), highContrast => dark ? const DesignSwatch( diff --git a/app/lib/ui/theme/app_design_controller.dart b/app/lib/ui/theme/app_design_controller.dart index f0b38892..b57c719e 100644 --- a/app/lib/ui/theme/app_design_controller.dart +++ b/app/lib/ui/theme/app_design_controller.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart' show kThemeAnimationDuration; import 'package:shared_preferences/shared_preferences.dart'; import 'app_design.dart'; +import 'app_design_tokens.dart'; /// The device's design choice. It lives in this device's (or browser's) own /// preferences and is never sent to a server. @@ -93,10 +94,17 @@ class AppDesignController extends ChangeNotifier { /// 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 + /// density, none for a switch into or out of a dense design or one that + /// asks to snap ([AppDesignTokens.snapSwitch]). 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. + /// A design whose switches snap: a dense one, or one whose tokens ask to + /// ([AppDesignTokens.snapSwitch], High contrast). + static bool _snaps(AppDesign design) => + design.dense || + (design.light().extension()?.snapSwitch ?? false); + Duration get themeAnimationDuration => _snapTheme ? Duration.zero : kThemeAnimationDuration; bool _snapTheme = false; @@ -104,7 +112,7 @@ class AppDesignController extends ChangeNotifier { /// The shown design changed from [before]: decide the hosts' blend and /// tell them. void _shown(AppDesign before) { - _snapTheme = before.dense || design.dense; + _snapTheme = _snaps(before) || _snaps(design); notifyListeners(); } diff --git a/app/lib/ui/theme/app_design_styles.dart b/app/lib/ui/theme/app_design_styles.dart index c5bfb030..40ccaf45 100644 --- a/app/lib/ui/theme/app_design_styles.dart +++ b/app/lib/ui/theme/app_design_styles.dart @@ -24,6 +24,11 @@ enum TranscriptStyle { /// answers as plain text on the page and activity as bordered rows that /// name each tool's status in words (High contrast). boxed, + + /// A notebook: each operator prompt an "In [n]:" input cell and each + /// answer its "Out [n]:" cell, numbered per turn in a fixed-width gutter, + /// with tool calls as collapsible sub-cells (Notebook). + cells, } /// How the chat composer frames its writing area. @@ -35,6 +40,10 @@ enum ComposerStyle { /// An open writing area on the page with a rule beneath it that takes /// the accent while the field has focus. underline, + + /// A notebook's empty input cell, "In [ ]:" in the gutter beside a light + /// grey cell whose frame takes the accent while the field has focus. + cell, } /// How a list (AppListRow) marks the row that is open. Every style keeps diff --git a/app/lib/ui/theme/app_design_tokens.dart b/app/lib/ui/theme/app_design_tokens.dart index b5df34ff..031aec77 100644 --- a/app/lib/ui/theme/app_design_tokens.dart +++ b/app/lib/ui/theme/app_design_tokens.dart @@ -71,6 +71,7 @@ class AppDesignTokens extends ThemeExtension { this.largeTargets = false, this.minContrast, this.windowRadius, + this.snapSwitch = false, this.density = DesignDensity.comfortable, }); @@ -143,6 +144,12 @@ class AppDesignTokens extends ThemeExtension { /// The corner radius of floating windows; null keeps the windows' own. final double? windowRadius; + /// Whether a live switch into or out of this design snaps rather than + /// blending: High contrast's half-blended frames would be low-contrast + /// grey on grey, and its larger component sizes have no value in other + /// designs to blend from ([AppDesignController.themeAnimationDuration]). + final bool snapSwitch; + /// 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; @@ -217,6 +224,7 @@ class AppDesignTokens extends ThemeExtension { bool? largeTargets, double? minContrast, double? windowRadius, + bool? snapSwitch, DesignDensity? density, }) => AppDesignTokens( design: design ?? this.design, @@ -237,6 +245,7 @@ class AppDesignTokens extends ThemeExtension { largeTargets: largeTargets ?? this.largeTargets, minContrast: minContrast ?? this.minContrast, windowRadius: windowRadius ?? this.windowRadius, + snapSwitch: snapSwitch ?? this.snapSwitch, density: density ?? this.density, ); @@ -264,6 +273,7 @@ class AppDesignTokens extends ThemeExtension { other.largeTargets == largeTargets && other.minContrast == minContrast && other.windowRadius == windowRadius && + other.snapSwitch == snapSwitch && other.density == density; @override @@ -286,6 +296,7 @@ class AppDesignTokens extends ThemeExtension { largeTargets, minContrast, windowRadius, + snapSwitch, density, ); diff --git a/app/lib/ui/theme/high_contrast_theme.dart b/app/lib/ui/theme/high_contrast_theme.dart index 5bd213bb..212be6a5 100644 --- a/app/lib/ui/theme/high_contrast_theme.dart +++ b/app/lib/ui/theme/high_contrast_theme.dart @@ -91,6 +91,7 @@ ThemeData highContrastTheme(Brightness brightness, {String? fontFamily}) { largeTargets: true, minContrast: highContrastMinimum, windowRadius: highContrastRadius, + snapSwitch: true, ), ], ); diff --git a/app/lib/ui/theme/notebook_controls.dart b/app/lib/ui/theme/notebook_controls.dart new file mode 100644 index 00000000..f66b225d --- /dev/null +++ b/app/lib/ui/theme/notebook_controls.dart @@ -0,0 +1,159 @@ +import 'package:flutter/material.dart'; + +import 'notebook_theme.dart'; + +const Color _clear = Color(0x00000000); + +// Kept per colour: a tab indicator and a resolver compare by identity, so +// fresh ones would make a rebuilt theme unequal to the last +// (test/perf/design_bench_test.dart). +final Map _tabIndicators = {}; +final Map<(Color, Color), WidgetStateBorderSide> _checkboxSides = {}; + +/// [base] with Notebook's controls: buttons, menus, chips, fields, search +/// bars, tabs, segmented buttons, switches, checkboxes, sliders, badges and +/// progress in [notebookRadius] corners with hairline outlines, no +/// elevation and the IDE blue; fields are boxed. +ThemeData notebookControls(ThemeData base, NotebookSurfaces surfaces) { + final scheme = base.colorScheme; + const rounded = NotebookSurfaces.rounded; + ButtonStyle buttons(ButtonStyle? style) => + (style ?? const ButtonStyle()).copyWith( + shape: const WidgetStatePropertyAll(rounded), + elevation: const WidgetStatePropertyAll(0), + shadowColor: const WidgetStatePropertyAll(_clear), + ); + final outline = WidgetStatePropertyAll(BorderSide(color: scheme.outline)); + final menu = MenuStyle( + backgroundColor: WidgetStatePropertyAll(surfaces.floating), + elevation: const WidgetStatePropertyAll(NotebookSurfaces.floatElevation), + shadowColor: WidgetStatePropertyAll(surfaces.shadow), + surfaceTintColor: const WidgetStatePropertyAll(_clear), + shape: WidgetStatePropertyAll(surfaces.framed), + padding: const WidgetStatePropertyAll(EdgeInsets.symmetric(vertical: 4)), + ); + final field = OutlineInputBorder( + borderRadius: NotebookSurfaces.corners, + borderSide: BorderSide(color: scheme.outlineVariant), + ); + return base.copyWith( + menuTheme: MenuThemeData(style: menu), + dropdownMenuTheme: DropdownMenuThemeData(menuStyle: menu), + menuButtonTheme: MenuButtonThemeData( + style: MenuItemButton.styleFrom(shape: rounded), + ), + filledButtonTheme: FilledButtonThemeData( + style: buttons(base.filledButtonTheme.style), + ), + elevatedButtonTheme: ElevatedButtonThemeData( + style: buttons(base.elevatedButtonTheme.style).copyWith( + backgroundColor: WidgetStatePropertyAll(scheme.surfaceContainerLow), + side: WidgetStatePropertyAll(surfaces.hairline), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: buttons(base.outlinedButtonTheme.style).copyWith(side: outline), + ), + textButtonTheme: TextButtonThemeData( + style: buttons(base.textButtonTheme.style), + ), + iconButtonTheme: IconButtonThemeData( + style: buttons(base.iconButtonTheme.style), + ), + segmentedButtonTheme: SegmentedButtonThemeData( + style: buttons( + base.segmentedButtonTheme.style, + ).copyWith(side: WidgetStatePropertyAll(surfaces.hairline)), + ), + floatingActionButtonTheme: FloatingActionButtonThemeData( + elevation: 0, + focusElevation: 0, + hoverElevation: 0, + highlightElevation: 0, + backgroundColor: scheme.surfaceContainerLow, + foregroundColor: scheme.primary, + shape: RoundedRectangleBorder( + borderRadius: NotebookSurfaces.corners, + side: BorderSide(color: scheme.outline), + ), + ), + // A chip is a small grey tag in the cell's grey, hairline framed. + chipTheme: ChipThemeData( + backgroundColor: scheme.surfaceContainerLow, + selectedColor: scheme.primaryContainer, + shape: surfaces.framed, + side: surfaces.hairline, + elevation: 0, + pressElevation: 0, + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + ), + // A field is a boxed cell in the design's corners. Only the base border: + // a field that sets `InputBorder.none` (the composer, which draws its + // own input cell) keeps none in every state. + inputDecorationTheme: InputDecorationTheme(isDense: true, border: field), + searchBarTheme: SearchBarThemeData( + elevation: const WidgetStatePropertyAll(0), + shape: const WidgetStatePropertyAll(rounded), + side: WidgetStatePropertyAll(surfaces.hairline), + backgroundColor: WidgetStatePropertyAll(scheme.surfaceContainerLow), + surfaceTintColor: const WidgetStatePropertyAll(_clear), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 12), + ), + ), + listTileTheme: const ListTileThemeData(shape: rounded), + expansionTileTheme: const ExpansionTileThemeData( + shape: Border(), + collapsedShape: Border(), + ), + tabBarTheme: TabBarThemeData( + dividerColor: scheme.outlineVariant, + labelColor: scheme.onSurface, + unselectedLabelColor: scheme.onSurfaceVariant, + indicatorSize: TabBarIndicatorSize.tab, + indicator: _tabIndicators[scheme.primary] ??= UnderlineTabIndicator( + borderSide: BorderSide(color: scheme.primary, width: 2), + ), + ), + checkboxTheme: CheckboxThemeData( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(3)), + ), + side: _checkboxSides[(scheme.primary, scheme.outline)] ??= + WidgetStateBorderSide.resolveWith( + (states) => states.contains(WidgetState.selected) + ? BorderSide(color: scheme.primary, width: 1.5) + : BorderSide(color: scheme.outline, width: 1.5), + ), + ), + sliderTheme: SliderThemeData( + trackHeight: 3, + activeTrackColor: scheme.primary, + inactiveTrackColor: scheme.outlineVariant, + thumbColor: scheme.primary, + thumbShape: const RoundSliderThumbShape( + enabledThumbRadius: 7, + elevation: 0, + pressedElevation: 0, + ), + overlayShape: const RoundSliderOverlayShape(overlayRadius: 16), + valueIndicatorColor: scheme.inverseSurface, + valueIndicatorTextStyle: TextStyle(color: scheme.onInverseSurface), + ), + badgeTheme: BadgeThemeData( + backgroundColor: scheme.primary, + textColor: scheme.onPrimary, + padding: const EdgeInsets.symmetric(horizontal: 4), + ), + progressIndicatorTheme: ProgressIndicatorThemeData( + color: scheme.primary, + linearTrackColor: scheme.outlineVariant, + circularTrackColor: _clear, + linearMinHeight: 2, + ), + scrollbarTheme: const ScrollbarThemeData( + radius: Radius.circular(3), + thickness: WidgetStatePropertyAll(6), + ), + ); +} diff --git a/app/lib/ui/theme/notebook_palette.dart b/app/lib/ui/theme/notebook_palette.dart new file mode 100644 index 00000000..f06fdaa6 --- /dev/null +++ b/app/lib/ui/theme/notebook_palette.dart @@ -0,0 +1,107 @@ +import 'package:flutter/material.dart'; + +import 'app_design_tokens.dart'; + +/// Notebook's status accents on its white page: a notebook IDE's clear +/// status colours, a step darker so they read on a light grey cell. +const AnsiAccents notebookLightAccents = AnsiAccents( + green: Color(0xFF2E7D32), + cyan: Color(0xFF00838F), + yellow: Color(0xFFA15C00), + red: Color(0xFFC62828), + magenta: Color(0xFF8E3A8A), + blue: Color(0xFF1F5FBF), +); + +/// Notebook's status accents on its dark page. +const AnsiAccents notebookDarkAccents = AnsiAccents( + green: Color(0xFF86C98A), + cyan: Color(0xFF6FCFDA), + yellow: Color(0xFFF0B35E), + red: Color(0xFFF08C86), + magenta: Color(0xFFD29BD6), + blue: Color(0xFF7FB0F0), +); + +/// Notebook's colour scheme: a white page (a neutral charcoal in dark) with +/// light grey cells a step off it, near-black ink with a mid-grey secondary +/// ink, hairline borders and one clear IDE blue. The tertiary role is the +/// warm orange a notebook gives its output prompt ("Out [n]:"). +ColorScheme notebookColorScheme(Brightness brightness) { + if (brightness == Brightness.dark) { + return const ColorScheme( + brightness: Brightness.dark, + primary: Color(0xFF7FB0F0), + onPrimary: Color(0xFF0A2A52), + primaryContainer: Color(0xFF1D3553), + onPrimaryContainer: Color(0xFFD3E5FB), + secondary: Color(0xFFA7B6C0), + onSecondary: Color(0xFF1B2A33), + secondaryContainer: Color(0xFF2B3338), + onSecondaryContainer: Color(0xFFDCE6EC), + tertiary: Color(0xFFEFA07C), + onTertiary: Color(0xFF4A1A08), + tertiaryContainer: Color(0xFF47291D), + onTertiaryContainer: Color(0xFFFBDCCD), + error: Color(0xFFF08C86), + onError: Color(0xFF4D0E0B), + errorContainer: Color(0xFF5A1E1B), + onErrorContainer: Color(0xFFFAD8D5), + surface: Color(0xFF17181A), + onSurface: Color(0xFFE4E5E7), + onSurfaceVariant: Color(0xFFA2A5AB), + surfaceDim: Color(0xFF131416), + surfaceBright: Color(0xFF3A3B3F), + surfaceContainerLowest: Color(0xFF121315), + surfaceContainerLow: Color(0xFF1F2023), + surfaceContainer: Color(0xFF232427), + surfaceContainerHigh: Color(0xFF2A2B2F), + surfaceContainerHighest: Color(0xFF313236), + outline: Color(0xFF5C5F66), + outlineVariant: Color(0xFF333539), + shadow: Color(0xFF000000), + scrim: Color(0xFF000000), + inverseSurface: Color(0xFFE4E5E7), + onInverseSurface: Color(0xFF232427), + inversePrimary: Color(0xFF1F5FBF), + surfaceTint: Color(0x00000000), + ); + } + return const ColorScheme( + brightness: Brightness.light, + primary: Color(0xFF1F5FBF), + onPrimary: Color(0xFFFFFFFF), + primaryContainer: Color(0xFFE3ECFA), + onPrimaryContainer: Color(0xFF0B3470), + secondary: Color(0xFF52626D), + onSecondary: Color(0xFFFFFFFF), + secondaryContainer: Color(0xFFE9EEF2), + onSecondaryContainer: Color(0xFF1F2D35), + tertiary: Color(0xFFC0532A), + onTertiary: Color(0xFFFFFFFF), + tertiaryContainer: Color(0xFFFBE9E1), + onTertiaryContainer: Color(0xFF4A1A08), + error: Color(0xFFC62828), + onError: Color(0xFFFFFFFF), + errorContainer: Color(0xFFFDECEA), + onErrorContainer: Color(0xFF5F1212), + surface: Color(0xFFFFFFFF), + onSurface: Color(0xFF1F2124), + onSurfaceVariant: Color(0xFF5F6368), + surfaceDim: Color(0xFFE6E7E9), + surfaceBright: Color(0xFFFFFFFF), + surfaceContainerLowest: Color(0xFFFFFFFF), + surfaceContainerLow: Color(0xFFF7F7F8), + surfaceContainer: Color(0xFFF2F3F4), + surfaceContainerHigh: Color(0xFFECEDEF), + surfaceContainerHighest: Color(0xFFE5E6E8), + outline: Color(0xFFB4B7BC), + outlineVariant: Color(0xFFE1E3E6), + shadow: Color(0xFF1B1D21), + scrim: Color(0xFF000000), + inverseSurface: Color(0xFF2B2D31), + onInverseSurface: Color(0xFFF2F3F4), + inversePrimary: Color(0xFF7FB0F0), + surfaceTint: Color(0x00000000), + ); +} diff --git a/app/lib/ui/theme/notebook_theme.dart b/app/lib/ui/theme/notebook_theme.dart new file mode 100644 index 00000000..30c8318e --- /dev/null +++ b/app/lib/ui/theme/notebook_theme.dart @@ -0,0 +1,208 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import 'app_design.dart'; +import 'app_design_tokens.dart'; +import 'app_theme.dart'; +import 'notebook_controls.dart'; +import 'notebook_palette.dart'; + +/// Notebook's corner radius: cells, cards, fields, menus, dialogs, chips and +/// buttons all take it, a notebook IDE's small soft corner. +const double notebookRadius = 5; + +/// Notebook's reading type: the interface sans a step under the body size on +/// an airy line, as a notebook sets its markdown cells. +const ReadingType notebookReading = ReadingType(height: 1.5, scale: 15 / 16); + +/// Notebook's surfaces: a white page, light grey cells, hairline borders and +/// a faint shadow only under the pieces that float (menus, dialogs, sheets, +/// snack bars), as an IDE draws its popups. +class NotebookSurfaces { + NotebookSurfaces(this.scheme); + + final ColorScheme scheme; + + static const BorderRadius corners = BorderRadius.all( + Radius.circular(notebookRadius), + ); + + /// A floating piece's elevation: just enough shadow to lift it. + static const double floatElevation = 2; + + Color get shadow => scheme.shadow.withValues( + alpha: scheme.brightness == Brightness.dark ? 0.55 : 0.18, + ); + + BorderSide get hairline => BorderSide(color: scheme.outlineVariant); + + /// The page white (or the dark page's raised grey) a floating piece takes. + Color get floating => scheme.brightness == Brightness.dark + ? scheme.surfaceContainerHigh + : scheme.surfaceContainerLowest; + + RoundedRectangleBorder get framed => + RoundedRectangleBorder(borderRadius: corners, side: hairline); + + static const RoundedRectangleBorder rounded = RoundedRectangleBorder( + borderRadius: corners, + ); +} + +/// The Notebook design's theme: a clean light page (a charcoal one in dark) +/// with light grey cells, hairline borders, [notebookRadius] corners, the +/// device's interface sans for chrome and the bundled monospace for code +/// and the cells' gutter labels; the chat is drawn as numbered In/Out cells +/// ([TranscriptStyle.cells]) with an input cell for the composer. +ThemeData notebookTheme(Brightness brightness, {String? fontFamily}) { + final scheme = notebookColorScheme(brightness); + final surfaces = NotebookSurfaces(scheme); + final dark = brightness == Brightness.dark; + final base = ThemeData( + platform: kIsWeb ? TargetPlatform.android : null, + colorScheme: scheme, + fontFamily: fontFamily, + scaffoldBackgroundColor: scheme.surface, + canvasColor: scheme.surface, + pageTransitionsTheme: appPageTransitions, + dividerColor: scheme.outlineVariant, + shadowColor: surfaces.shadow, + extensions: [ + AppDesignTokens( + design: AppDesign.notebook, + radius: notebookRadius, + flat: true, + frame: scheme.outlineVariant, + panel: dark + ? scheme.surfaceContainerLow + : scheme.surfaceContainerLowest, + ansi: dark ? notebookDarkAccents : notebookLightAccents, + transcript: TranscriptStyle.cells, + composer: ComposerStyle.cell, + selectedRow: SelectedRowStyle.washed, + reading: notebookReading, + chatColorSaturation: 0.7, + ), + ], + ); + final text = notebookTextTheme(base.textTheme); + final floatingShape = surfaces.framed; + return notebookControls( + base.copyWith( + textTheme: text, + primaryTextTheme: notebookTextTheme(base.primaryTextTheme), + // A toolbar: the page colour, a hairline beneath and a compact title. + appBarTheme: AppBarTheme( + backgroundColor: scheme.surface, + foregroundColor: scheme.onSurface, + surfaceTintColor: const Color(0x00000000), + elevation: 0, + scrolledUnderElevation: 0, + titleTextStyle: text.titleMedium?.copyWith(color: scheme.onSurface), + shape: Border(bottom: surfaces.hairline), + ), + cardTheme: CardThemeData( + elevation: 0, + shadowColor: const Color(0x00000000), + surfaceTintColor: const Color(0x00000000), + shape: surfaces.framed, + ), + dialogTheme: DialogThemeData( + backgroundColor: surfaces.floating, + surfaceTintColor: const Color(0x00000000), + elevation: NotebookSurfaces.floatElevation, + shadowColor: surfaces.shadow, + shape: floatingShape, + titleTextStyle: text.titleMedium?.copyWith(color: scheme.onSurface), + ), + bottomSheetTheme: BottomSheetThemeData( + backgroundColor: surfaces.floating, + modalBackgroundColor: surfaces.floating, + surfaceTintColor: const Color(0x00000000), + elevation: NotebookSurfaces.floatElevation, + modalElevation: NotebookSurfaces.floatElevation, + shadowColor: surfaces.shadow, + shape: RoundedRectangleBorder( + borderRadius: const BorderRadius.vertical( + top: Radius.circular(notebookRadius), + ), + side: surfaces.hairline, + ), + dragHandleColor: scheme.outline, + ), + popupMenuTheme: PopupMenuThemeData( + color: surfaces.floating, + surfaceTintColor: const Color(0x00000000), + elevation: NotebookSurfaces.floatElevation, + shadowColor: surfaces.shadow, + shape: floatingShape, + menuPadding: const EdgeInsets.symmetric(vertical: 4), + ), + snackBarTheme: SnackBarThemeData( + backgroundColor: scheme.inverseSurface, + contentTextStyle: text.bodyMedium?.copyWith( + color: scheme.onInverseSurface, + ), + actionTextColor: scheme.inversePrimary, + elevation: NotebookSurfaces.floatElevation, + shape: NotebookSurfaces.rounded, + ), + tooltipTheme: TooltipThemeData( + decoration: BoxDecoration( + color: scheme.inverseSurface, + borderRadius: const BorderRadius.all(Radius.circular(4)), + ), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + textStyle: text.bodySmall?.copyWith(color: scheme.onInverseSurface), + ), + dividerTheme: DividerThemeData( + color: scheme.outlineVariant, + thickness: 1, + space: 1, + ), + navigationRailTheme: NavigationRailThemeData( + backgroundColor: scheme.surface, + elevation: 0, + indicatorColor: scheme.primaryContainer, + indicatorShape: NotebookSurfaces.rounded, + ), + navigationBarTheme: NavigationBarThemeData( + backgroundColor: scheme.surface, + elevation: 0, + indicatorColor: scheme.primaryContainer, + indicatorShape: NotebookSurfaces.rounded, + surfaceTintColor: const Color(0x00000000), + ), + drawerTheme: DrawerThemeData( + backgroundColor: scheme.surface, + surfaceTintColor: const Color(0x00000000), + elevation: NotebookSurfaces.floatElevation, + shadowColor: surfaces.shadow, + shape: const RoundedRectangleBorder(), + ), + textSelectionTheme: TextSelectionThemeData( + cursorColor: scheme.primary, + selectionColor: scheme.primary.withValues(alpha: dark ? 0.32 : 0.2), + selectionHandleColor: scheme.primary, + ), + ), + surfaces, + ); +} + +/// [base] for Notebook: the interface sans throughout with titles a little +/// tighter and semibold, as an IDE heads its panes, and no added tracking on +/// labels. +TextTheme notebookTextTheme(TextTheme base) { + TextStyle? title(TextStyle? style, double size) => style?.copyWith( + fontSize: size, + fontWeight: FontWeight.w600, + letterSpacing: 0, + ); + return base.copyWith( + headlineSmall: title(base.headlineSmall, 22), + titleLarge: title(base.titleLarge, 19), + titleMedium: title(base.titleMedium, 15), + titleSmall: base.titleSmall?.copyWith(fontWeight: FontWeight.w600), + ); +} 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-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-notebook.md b/app/notes/design-notebook.md new file mode 100644 index 00000000..c8832d0b --- /dev/null +++ b/app/notes/design-notebook.md @@ -0,0 +1,99 @@ +# Notebook design + +A notebook IDE look (Settings > Design > Notebook, id `notebook`): the chat +as numbered Jupyter-style In/Out cells with tool calls as collapsible +sub-cells, a white page (neutral charcoal in dark), light grey cells, +hairline borders, 5px corners, the device's interface sans for chrome and +the bundled RobotoMono for code, tool sub-cells and gutter labels. + +## Tokens and modes + +`notebookTheme()` (`lib/ui/theme/notebook_theme.dart`, palette and controls +beside it) sets: + +- `transcript: TranscriptStyle.cells` (new). Other designs never take it. +- `composer: ComposerStyle.cell` (new): `composer_cell.dart`. +- `selectedRow: washed` (left accent bar plus a light fill), `radius: 5`, + `flat`, `frame: outlineVariant`, `panel`: white (raised grey in dark), + Notebook ANSI accents, `chatColorSaturation: 0.7`. +- `reading`: the interface sans at 15/16 of `bodyLarge`, line height 1.5. + +Both new enum values are additions; every existing design keeps its own +value, so nothing else changes. Exhaustive switches on `TranscriptStyle` +gained a `cells` case (bubble, activity view, automated prompt). + +## The cells transcript + +`lib/features/chat/ui/transcript/notebook/`: + +- `notebook_gutter.dart`: `NotebookGutterRow`, a fixed-width gutter (ten + monospace characters at 0.8 of the reading size, scaled with text, plus an + 8px gap) holding the right-aligned label on the cell's first-line strut, so + it shares that line's baseline. Below 600px of row width (a phone) the label moves + inline above the cell. Rows that are not cells (shell runs, notices, + activity groups) get an empty gutter (`chat_thread_view.dart`), and a + `NotebookGutterScope` stops nested rows indenting twice. +- `notebook_input_cell.dart`: the operator's `In [n]:` cell (cell grey, 7% + of the chat colour, 3px bar in the chat colour, else the accent); the + scheduled cell for follow-ups, auto-continues (tag `scheduled`) and account + switches (tag `switched`) with an outline bar; `NotebookTag`. +- `notebook_tool_cells.dart` / `notebook_tool_cell.dart`: each tool call a + sub-cell: chevron, bold name and dim arguments, duration and a status icon + on the right (painted `NotebookGlyph`s, not Icons); collapsed it previews + the output's first line with "+N lines" at that line's end; the header + expands it in place (input and up to 400 output + lines, built only when open). The latest 8 calls show, earlier ones behind + "Show N earlier tool calls". The status line under them ("Used 6 tools · + 1 failed", or the live label and seconds) opens Activity details. +- `notebook_cell_frame.dart`: one `CustomPainter` per cell (fill, clipped + leading bar, 1px border), no layers. +- Sub-cell headers and the status line are a `GestureDetector` with the + click cursor and a Semantics button, not an `InkWell`: an InkWell per + sub-cell roughly doubled the elements a tool-heavy row builds and put the + design over the per-row rebuild budget. Keyboard users reach the same + content through Activity details; no hover ink on headers. + +Numbering: `chatCellNumbers()` (`domain/chat_cell_numbers.dart`) numbers +operator turns from 1 in transcript order and gives each following answer +its prompt's number. It is derived, not stored, so a reload numbers the same; +with older history not yet loaded, numbering starts at the oldest loaded +turn (the server sends no absolute turn index). Queued or unsent prompts read +`In [ ]:`. A running answer shows `[*]` under its `Out [n]:`. The thread view +passes the number into `ChatMessageView.cell` (and the row cache's deps), +only under the cells transcript. + +Under cells, answers keep their Read aloud/Copy on the footer line (shown on +hover) rather than the left Copy gutter, so short Out cells keep the +In/Out rhythm: 6px above an In cell, 3px between In and Out, 6px under an +Out cell. + +## Composer + +`ComposerCell`: `In [ ]:` in the same gutter, the field in a cell-grey frame +whose border and bar take the chat's accent on focus; a 2px running line at +its foot while a turn runs. Padding is the pill's 4px edge gap plus 3px, so +the usage ring (40px send button, 3px gap, following the 5px radius) clears +the cell's hairline. The send keys are unchanged. + +## Still default + +Markdown inside answers (headings, lists, code blocks) uses the standard +transcript styling in the interface font; chips, permission cards, task +cards, the chat stack discs and the graph follow the generic flat/radius/ +panel/frame tokens with no Notebook-specific code. Typography is Material's +apart from semibold, tighter titles. + +## Perf + +Widget bench (`test/perf/design_bench_test.dart`): scrollRebuildsPerRow +about 99 against Default's 83.5 (budget 105.3); layers 8.2/frame, no +clipPath or saveLayer beyond Default's opacity count. Browser bench +(`design_bench.mjs --designs notebook`, skwasm CPU): PASS, notebook's +build/raster means below Default's in every scenario. The per-frame theme +switch test (`compact_switch_test.dart`) includes Notebook. + +No `saveLayer`, blur or clip layers: cells paint in one picture each; the +expanded output is built only when opened; a tool cell memoises its preview +so a running turn's one-second tick does not resplit outputs. The theme is +value-equal on rebuild (identity-compared resolvers and indicators cached +per colour). Run the design budget (tool/perf/README.md) after changes. 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/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/core/servers/chat/federated_chat_gateway_test.dart b/app/test/core/servers/chat/federated_chat_gateway_test.dart index 31bb57ff..b2750086 100644 --- a/app/test/core/servers/chat/federated_chat_gateway_test.dart +++ b/app/test/core/servers/chat/federated_chat_gateway_test.dart @@ -5,6 +5,7 @@ import 'package:pipelines_app/core/servers/chat/chat_identity.dart'; import 'package:pipelines_app/core/servers/chat/chat_server_gateway.dart'; import 'package:pipelines_app/core/servers/chat/federated_chat_gateway.dart'; import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; import 'package:pipelines_app/core/transport/server_url.dart'; import 'package:pipelines_app/features/chat/files/files_urls.dart'; @@ -12,6 +13,8 @@ class Machine implements ApiGateway { final events = StreamController.broadcast(); final calls = <(String, JsonMap)>[]; bool fail = false; + Object? failure; + JsonMap? sessionsReply; Completer? pendingSessions; @override Stream get frames => events.stream; @@ -19,6 +22,8 @@ class Machine implements ApiGateway { Future call(String type, [JsonMap fields = const {}]) async { calls.add((type, fields)); if (fail) throw StateError('offline'); + if (failure case final failure?) throw failure; + if (type == 'chat_sessions' && sessionsReply != null) return sessionsReply!; if (type == 'chat_sessions') { if (pendingSessions != null) return pendingSessions!.future; return { @@ -57,6 +62,40 @@ SavedServer server(String id) => SavedServer.validated( endpoints: ['ws://$id.test/connect'], ); void main() { + group('a server with no chats or no chat harness', () { + FederatedChatGateway federated(Machine machine) { + final sources = {'a': ChatServerGateway(server('a'), machine)}; + return FederatedChatGateway( + () => sources, + () => 'a', + const Stream.empty(), + ); + } + + test('an omitted empty list reads as no chats, not a failure', () async { + final machine = Machine()..sessionsReply = {'type': 'chat_sessions'}; + final reply = await federated(machine).call('chat_sessions'); + expect(reply['chat_sessions'], isEmpty); + }); + + test('the server\'s own refusal is kept when no machine answers', () { + final machine = Machine() + ..failure = const ProtocolError( + 'chat is not configured on this server', + ); + expect( + federated(machine).call('chat_sessions'), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'chat is not configured on this server', + ), + ), + ); + }); + }); + test( 'colliding native IDs remain distinct, mutations and replies stay on source', () 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/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/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_ios_material_test.dart b/app/test/features/chat/ui/sessions/chat_ios_material_test.dart index 6643b588..4f0bc11c 100644 --- a/app/test/features/chat/ui/sessions/chat_ios_material_test.dart +++ b/app/test/features/chat/ui/sessions/chat_ios_material_test.dart @@ -17,7 +17,7 @@ void main() { expect(find.byType(Scaffold), findsWidgets); - const message = 'No chats yet. Use New chat to start one.'; + const message = 'No chats yet'; expect(find.text(message), findsOneWidget); expectNormalTextStyle(tester, message); }); @@ -39,7 +39,7 @@ void main() { 'for this operator'; expect(find.text(message), findsOneWidget); expectNormalTextStyle(tester, message); - expect(find.text('No chats yet. Use New chat to start one.'), findsNothing); + expect(find.text('No chats yet'), findsNothing); expect( find.ancestor( of: find.text('Retry'), diff --git a/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart index c40846a4..2b5f77ce 100644 --- a/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart +++ b/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart @@ -3,6 +3,8 @@ 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/transport/connection_state.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_harness_setup_state.dart'; import 'chat_test_harness.dart'; import 'fake_chat_gateway.dart'; @@ -91,13 +93,29 @@ void main() { ) async { final gateway = FakeChatGateway(); await pumpMaterialChat(tester, gateway); - expect( - find.text('No chats yet. Use New chat to start one.'), - findsOneWidget, - ); + expect(find.text('No chats yet'), findsOneWidget); + expect(find.text('Start a chat'), findsOneWidget); expect(find.textContaining('No chats match'), findsNothing); }); + testWidgets('a server without a chat harness shows the setup step', ( + tester, + ) async { + usePhoneSurface(tester); + final gateway = FakeChatGateway() + ..sessionsHandler = () => Future.error( + const ProtocolError('chat is not configured on this server'), + ); + await pumpMaterialChat(tester, gateway); + + expect(find.byKey(chatHarnessSetupKey), findsOneWidget); + expect(find.text('pipelines harness setup claude'), findsOneWidget); + // Not a failure: no error notice, no raw server text. + expect(find.textContaining('not configured'), findsNothing); + expect(find.text('No chats yet'), findsNothing); + expect(find.text('Refresh'), findsWidgets); + }); + testWidgets('load failure wraps the reason and hides the empty message', ( tester, ) async { @@ -114,7 +132,7 @@ void main() { 'Bad state: server unavailable while listing chat sessions ' 'for this operator'; expect(find.text(message), findsOneWidget); - expect(find.text('No chats yet. Use New chat to start one.'), findsNothing); + expect(find.text('No chats yet'), findsNothing); final messageBox = tester.renderObject(find.text(message)); expect( messageBox.size.height, diff --git a/app/test/features/chat/ui/transcript/notebook_transcript_test.dart b/app/test/features/chat/ui/transcript/notebook_transcript_test.dart new file mode 100644 index 00000000..cc762e36 --- /dev/null +++ b/app/test/features/chat/ui/transcript/notebook_transcript_test.dart @@ -0,0 +1,283 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/domain/chat_cell_numbers.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_bubble.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/notebook/notebook_input_cell.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/notebook/notebook_tool_cell.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/notebook/notebook_tool_cells.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/paper/paper_quote.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/terminal/terminal_activity_rows.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/terminal/terminal_prompt_line.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; + +JsonMap _row(JsonMap message) => transcriptRows([message]).single; + +final JsonMap _operator = _row({ + 'id': 'u1', + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'Fix the Windows paths.'}, + ], +}); + +JsonMap _tool(String id, String name, String status, {String output = ''}) => { + 'type': 'tool', + 'id': id, + 'name': name, + 'time': {'created': 1000, 'completed': 2200}, + 'state': { + 'status': status, + 'input': {'command': 'go test ./...'}, + if (output.isNotEmpty) + 'content': [ + {'type': 'text', 'text': output}, + ], + if (status == 'error') 'error': {'message': 'exit status 1'}, + }, +}; + +const String _longOutput = 'ok pkg/a\nok pkg/b\nok pkg/c\nok pkg/d\nPASS'; + +JsonMap _agent({bool streaming = false}) => { + ..._row({ + 'id': 'a1', + 'role': 'assistant', + 'parts': [ + _tool('t1', 'Bash', 'completed', output: _longOutput), + _tool('t2', 'Read', 'error'), + {'type': 'text', 'text': 'Fixed the separators.'}, + ], + }), + if (streaming) 'streaming': true, +}; + +final JsonMap _followup = _row({ + 'id': 'f1', + 'role': 'user', + 'origin': 'followup', + 'client': 'Agent follow-up', + 'parts': [ + {'type': 'text', 'text': 'Check whether run 42 finished.'}, + ], +}); + +Widget _host( + AppDesign design, + List<(JsonMap, int?)> rows, { + double width = 900, +}) => MaterialApp( + theme: design.light(), + home: Scaffold( + body: Center( + child: SizedBox( + width: width, + child: ListView( + children: [ + for (final (row, cell) in rows) + ChatMessageView( + row: row, + cell: cell, + textBuilder: chatMarkdownText, + ), + ], + ), + ), + ), + ), +); + +Finder _label(String text) => find.byWidgetPredicate( + (widget) => + widget is Text && + widget.key == const Key('chat-notebook-gutter-label') && + widget.data == text, +); + +void main() { + test('cells number each operator turn and pair its answers', () { + final rows = [ + {'kind': 'assistant', 'key': 'early'}, + {'kind': 'user', 'key': 'u1'}, + {'kind': 'assistant', 'key': 'a1'}, + {'kind': 'system_notice', 'key': 'n1'}, + {'kind': 'assistant', 'key': 'a1b'}, + {'kind': 'user', 'key': 'f1'}, + {'kind': 'assistant', 'key': 'chat-pending-response'}, + ]; + expect(chatCellNumbers(rows), { + 'u1': 1, + 'a1': 1, + 'a1b': 1, + 'f1': 2, + 'chat-pending-response': 2, + }); + // Derived from the turn order alone: the same history numbers the same. + expect(chatCellNumbers(rows), chatCellNumbers([...rows])); + }); + + testWidgets('Notebook: In and Out cells with right-aligned gutter labels', ( + tester, + ) async { + await tester.pumpWidget( + _host(AppDesign.notebook, [(_operator, 3), (_agent(), 3)]), + ); + expect(find.byType(NotebookInputCell), findsOneWidget); + expect(find.byType(TerminalPromptLine), findsNothing); + expect(find.byType(PaperQuote), findsNothing); + final inLabel = _label('In [3]:'); + final outLabel = _label('Out [3]:'); + expect(inLabel, findsOneWidget); + expect(outLabel, findsOneWidget); + // One gutter: both labels end in the same column, left of the cells. + expect( + tester.getTopRight(inLabel).dx, + closeTo(tester.getTopRight(outLabel).dx, 0.5), + ); + final cell = find.byType(NotebookInputCell); + expect( + tester.getTopRight(inLabel).dx, + lessThan(tester.getTopLeft(cell).dx), + ); + // The prompt's and the answer's text share one column. + expect( + tester.getTopLeft(find.text('Fix the Windows paths.')).dx, + closeTo(tester.getTopLeft(find.text('Fixed the separators.')).dx, 0.5), + ); + // The label sits on the prompt's first line. + final labelBox = tester.getRect(inLabel); + final textBox = tester.getRect(find.text('Fix the Windows paths.')); + expect(labelBox.bottom, closeTo(textBox.bottom, 3)); + }); + + testWidgets('Notebook: a prompt not yet run reads In [ ]:', (tester) async { + await tester.pumpWidget(_host(AppDesign.notebook, [(_operator, null)])); + expect(_label('In [ ]:'), findsOneWidget); + }); + + testWidgets('Notebook: tool calls are collapsed sub-cells that expand in ' + 'place', (tester) async { + await tester.pumpWidget(_host(AppDesign.notebook, [(_agent(), 1)])); + expect(find.byType(NotebookToolCells), findsOneWidget); + expect(find.byType(TerminalActivityRows), findsNothing); + final cells = find.byType(NotebookToolCell); + expect(cells, findsNWidgets(2)); + // Collapsed: the first lines of the output, "+N lines", the duration and + // the status on the right. + expect(find.byKey(const Key('chat-notebook-tool-preview')), findsWidgets); + expect(find.text('+4 lines'), findsOneWidget); + expect(find.text('1.2s'), findsNWidgets(2)); + expect(find.byKey(const Key('chat-notebook-tool-output')), findsNothing); + expect(find.textContaining('PASS'), findsNothing); + + await tester.tap(find.byKey(const Key('chat-notebook-tool-header')).first); + await tester.pump(); + expect(find.byKey(const Key('chat-notebook-tool-output')), findsOneWidget); + expect(find.textContaining('PASS'), findsOneWidget); + expect(find.text('+4 lines'), findsNothing); + + await tester.tap(find.byKey(const Key('chat-notebook-tool-header')).first); + await tester.pump(); + expect(find.byKey(const Key('chat-notebook-tool-output')), findsNothing); + + // The status line still opens the activity details. + await tester.tap(find.byKey(const Key('chat-turn-activity'))); + await tester.pumpAndSettle(); + expect(find.text('Activity details'), findsOneWidget); + }); + + testWidgets('Notebook: a long turn folds its earlier calls', (tester) async { + final row = _row({ + 'id': 'a9', + 'role': 'assistant', + 'parts': [ + for (var i = 0; i < notebookToolMaxCalls + 3; i++) + _tool('t$i', 'Read', 'completed', output: 'line $i'), + ], + }); + await tester.pumpWidget(_host(AppDesign.notebook, [(row, 1)])); + expect(find.byType(NotebookToolCell), findsNWidgets(notebookToolMaxCalls)); + await tester.tap(find.byKey(const Key('chat-notebook-tool-earlier'))); + await tester.pump(); + expect( + find.byType(NotebookToolCell), + findsNWidgets(notebookToolMaxCalls + 3), + ); + }); + + testWidgets('Notebook: a running turn shows Jupyter\'s [*] busy marker', ( + tester, + ) async { + await tester.pumpWidget( + _host(AppDesign.notebook, [(_agent(streaming: true), 2)]), + ); + expect(_label('Out [2]:'), findsOneWidget); + final busy = find.byKey(const Key('chat-notebook-busy')); + expect(busy, findsOneWidget); + expect(tester.widget(busy).data, '[*]'); + expect( + tester.getTopLeft(busy).dy, + greaterThan(tester.getTopLeft(_label('Out [2]:')).dy), + ); + await tester.pumpWidget(_host(AppDesign.notebook, [(_agent(), 2)])); + expect(find.byKey(const Key('chat-notebook-busy')), findsNothing); + }); + + testWidgets('Notebook: a follow-up is an In cell with a scheduled tag', ( + tester, + ) async { + await tester.pumpWidget(_host(AppDesign.notebook, [(_followup, 4)])); + expect(_label('In [4]:'), findsOneWidget); + expect(find.byType(NotebookScheduledCell), findsOneWidget); + final tag = find.byKey(const Key('chat-notebook-scheduled-tag')); + expect( + find.descendant(of: tag, matching: find.text('scheduled')), + findsOneWidget, + ); + expect(find.text('Follow-up from agent'), findsOneWidget); + expect(find.text('Check whether run 42 finished.'), findsOneWidget); + }); + + testWidgets('Notebook: at phone width the gutter collapses to an inline ' + 'label above the cell', (tester) async { + await tester.pumpWidget( + _host(AppDesign.notebook, [(_operator, 1), (_agent(), 1)], width: 380), + ); + final label = _label('In [1]:'); + final cell = find.byType(NotebookInputCell); + expect( + tester.getBottomLeft(label).dy, + lessThanOrEqualTo(tester.getTopLeft(cell).dy), + ); + expect(tester.getTopLeft(label).dx, closeTo(tester.getTopLeft(cell).dx, 4)); + }); + + for (final design in [ + AppDesign.standard, + AppDesign.terminal, + AppDesign.paper, + ]) { + testWidgets('${design.label} is unchanged: no cells, even with a number', ( + tester, + ) async { + await tester.pumpWidget( + _host(design, [ + (_operator, 1), + (_agent(streaming: true), 1), + (_followup, 2), + ]), + ); + expect(find.byKey(const Key('chat-notebook-gutter-label')), findsNothing); + expect(find.byType(NotebookInputCell), findsNothing); + expect(find.byType(NotebookToolCells), findsNothing); + expect(find.byType(NotebookScheduledCell), findsNothing); + expect(find.byKey(const Key('chat-notebook-busy')), findsNothing); + if (design == AppDesign.standard) { + expect(find.byType(ChatUserBubble), findsOneWidget); + } + }); + } +} 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_filter_test.dart b/app/test/features/pipelines/pipeline_filter_test.dart index 18e5e34f..27cee804 100644 --- a/app/test/features/pipelines/pipeline_filter_test.dart +++ b/app/test/features/pipelines/pipeline_filter_test.dart @@ -132,7 +132,7 @@ void main() { const [], const PipelineFilters(), )?.message, - 'No pipelines yet.', + 'No pipelines yet', ); expect(pipelineListEmptyState(all, all, const PipelineFilters()), isNull); }); 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/pipelines/pipelines_empty_server_test.dart b/app/test/features/pipelines/pipelines_empty_server_test.dart index 8c85ff51..7a911e7d 100644 --- a/app/test/features/pipelines/pipelines_empty_server_test.dart +++ b/app/test/features/pipelines/pipelines_empty_server_test.dart @@ -1,6 +1,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/pipelines/screen.dart'; +import 'package:pipelines_app/features/pipelines/widgets/pipeline_list_panel.dart'; + import 'fixtures.dart'; import 'test_helpers.dart'; @@ -20,11 +23,8 @@ void main() { (tester) async { await pumpWide(tester, emptyServerGateway()); - expect(find.text('No pipelines yet.'), findsOneWidget); - expect( - find.text('Create one from a template in Templates.'), - findsOneWidget, - ); + expect(find.text('No pipelines yet'), findsOneWidget); + expect(find.textContaining('Start from a template'), findsOneWidget); expect(find.text('Loading pipelines…'), findsNothing); expect(find.byKey(const Key('pipeline-list')), findsNothing); expect(find.textContaining('not defined'), findsNothing); @@ -33,6 +33,28 @@ void main() { }, ); + testWidgets('the empty state opens Templates as its next step', ( + tester, + ) async { + tester.view.physicalSize = const Size(1100, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + var opened = 0; + await tester.pumpWidget( + MaterialApp( + home: PipelinesScreen( + gateway: emptyServerGateway(), + onOpenTemplates: () => opened++, + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byKey(pipelinesEmptyKey), findsOneWidget); + await tester.tap(find.text('Browse templates')); + expect(opened, 1); + }); + testWidgets( 'a failed list stays an error and never reads as an empty server', (tester) async { @@ -42,7 +64,7 @@ void main() { ); expect(find.textContaining('server offline'), findsOneWidget); - expect(find.text('No pipelines yet.'), findsNothing); + expect(find.text('No pipelines yet'), findsNothing); expect(find.text('Loading pipelines…'), findsNothing); expect(tester.takeException(), isNull); }, diff --git a/app/test/features/pipelines/pipelines_screen_filter_test.dart b/app/test/features/pipelines/pipelines_screen_filter_test.dart index 347bc54c..766458ea 100644 --- a/app/test/features/pipelines/pipelines_screen_filter_test.dart +++ b/app/test/features/pipelines/pipelines_screen_filter_test.dart @@ -104,11 +104,8 @@ void main() { MaterialApp(home: PipelinesScreen(gateway: emptyGateway)), ); await tester.pumpAndSettle(); - expect(find.text('No pipelines yet.'), findsOneWidget); - expect( - find.text('Create one from a template in Templates.'), - findsOneWidget, - ); + expect(find.text('No pipelines yet'), findsOneWidget); + expect(find.textContaining('Start from a template'), findsOneWidget); }); testWidgets('a detail refusal keeps the selection and offers retry', ( 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/runs/ui/run_list_row_outcome_test.dart b/app/test/features/runs/ui/run_list_row_outcome_test.dart index 06b7869c..32dbc459 100644 --- a/app/test/features/runs/ui/run_list_row_outcome_test.dart +++ b/app/test/features/runs/ui/run_list_row_outcome_test.dart @@ -146,4 +146,34 @@ void main() { ); expect(find.text('Why it failed'), findsNothing); }); + + testWidgets('a run that found no agent harness names the setup step', ( + tester, + ) async { + const reason = + 'environment problem: model stage research: HARNESS TRANSPORT: ' + 'harness unreachable: cannot run the selected OpenCode CLI: exec: ' + '"opencode": executable file not found in \$PATH'; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunFailureBanner( + run: _run('failed', {'failure_reason': reason}), + ), + ), + ), + ); + expect(find.byKey(runFailureHarnessHintKey), findsOneWidget); + expect(find.textContaining('pipelines harness setup'), findsOneWidget); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunFailureBanner( + run: _run('failed', {'diagnostic': 'exit status 2'}), + ), + ), + ), + ); + expect(find.byKey(runFailureHarnessHintKey), findsNothing); + }); } diff --git a/app/test/features/runs/ui/runs_list_widget_test.dart b/app/test/features/runs/ui/runs_list_widget_test.dart index 607228b7..e5c465cc 100644 --- a/app/test/features/runs/ui/runs_list_widget_test.dart +++ b/app/test/features/runs/ui/runs_list_widget_test.dart @@ -9,6 +9,7 @@ import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; import 'package:pipelines_app/features/runs/ui/runs_filters.dart'; import 'package:pipelines_app/ui/status/run_status_icon.dart'; import 'package:pipelines_app/features/runs/ui/runs_list.dart'; +import 'package:pipelines_app/ui/status/error_notice.dart'; class _Gateway implements ApiGateway { final framesController = StreamController.broadcast(); @@ -162,8 +163,10 @@ void main() { gateway.reply = {'runs': []}; await controller.load(); await tester.pumpAndSettle(); - expect(find.text('No runs yet.'), findsOneWidget); - expect(find.textContaining('Start one from Pipelines'), findsOneWidget); + expect(find.text('No runs yet'), findsOneWidget); + expect(find.textContaining('A run is a pipeline'), findsOneWidget); + // No New run seam in this fixture: the state offers no dead button. + expect(find.text('Start your first run'), findsNothing); expect(find.text('No runs found.'), findsNothing); expect(find.textContaining('offline'), findsNothing); expect(tester.takeException(), isNull); @@ -173,7 +176,7 @@ void main() { controller.setStatus('failed'); await tester.pumpAndSettle(); expect(find.text('No runs found.'), findsOneWidget); - expect(find.text('No runs yet.'), findsNothing); + expect(find.text('No runs yet'), findsNothing); expect( find.text('Try changing or clearing the filters.'), findsOneWidget, @@ -183,6 +186,32 @@ void main() { variant: TargetPlatformVariant.only(TargetPlatform.android), ); + testWidgets('an empty server offers the first run as the next step', ( + tester, + ) async { + gateway.failure = null; + gateway.gate = null; + gateway.reply = {'runs': []}; + await controller.load(); + var started = 0; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunsList( + controller: controller, + onSelected: (_) {}, + onNewRun: () => started++, + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byKey(runsEmptyKey), findsOneWidget); + expect(find.byType(ErrorNotice), findsNothing); + await tester.tap(find.text('Start your first run')); + expect(started, 1); + }); + testWidgets( 'an empty server with a search query reads as no match, not no runs', (tester) async { @@ -200,7 +229,7 @@ void main() { ); await tester.pumpAndSettle(); expect(find.text('No runs found.'), findsOneWidget); - expect(find.text('No runs yet.'), findsNothing); + expect(find.text('No runs yet'), findsNothing); expect( find.text('Try changing or clearing the filters.'), findsOneWidget, diff --git a/app/test/features/schedules/ui/list/schedules_screen_test.dart b/app/test/features/schedules/ui/list/schedules_screen_test.dart index dad741b1..002c884e 100644 --- a/app/test/features/schedules/ui/list/schedules_screen_test.dart +++ b/app/test/features/schedules/ui/list/schedules_screen_test.dart @@ -88,7 +88,7 @@ void main() { (type, fields) async => {'type': 'schedules'}, ); await pumpSchedules(tester, gateway: empty); - expect(find.text('No schedules yet.'), findsOneWidget); + expect(find.text('No schedules yet'), findsOneWidget); expect(find.byKey(scheduleRetryKey), findsNothing); final unsupported = FakeSchedulesGateway( @@ -100,7 +100,7 @@ void main() { findsOneWidget, ); expect(find.byKey(scheduleRetryKey), findsOneWidget); - expect(find.text('No schedules yet.'), findsNothing); + expect(find.text('No schedules yet'), findsNothing); final failed = FakeSchedulesGateway( (type, fields) async => throw StateError('socket closed'), 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_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/features/templates/ui/template_gallery_screen_test.dart b/app/test/features/templates/ui/template_gallery_screen_test.dart index 71ee0e76..bb593c8a 100644 --- a/app/test/features/templates/ui/template_gallery_screen_test.dart +++ b/app/test/features/templates/ui/template_gallery_screen_test.dart @@ -3,6 +3,7 @@ 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/transport/connection_state.dart'; import 'package:pipelines_app/features/templates/screen.dart'; import 'package:pipelines_app/features/templates/ui/template_detail.dart'; import 'package:pipelines_app/features/templates/ui/template_gallery.dart' @@ -122,6 +123,29 @@ void main() { expect(find.text('Release workflow'), findsOneWidget); }); + testWidgets('a gallery opened before the connection reads again on connect', ( + tester, + ) async { + var connected = false; + final gateway = GalleryGateway((type, fields) async { + if (!connected) throw const NotConnectedError(); + if (type == 'list_templates') return templatesReply(galleryTemplates); + throw StateError('unexpected $type'); + }); + Widget screen(int token) => MaterialApp( + home: TemplatesScreen(gateway: gateway, reloadToken: token), + ); + await tester.pumpWidget(screen(0)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesErrorKey), findsOneWidget); + + connected = true; + await tester.pumpWidget(screen(1)); + await tester.pumpAndSettle(); + expect(find.byKey(templatesErrorKey), findsNothing); + expect(find.text('Release workflow'), findsOneWidget); + }); + testWidgets('refresh re-reads the catalogue and keeps the selection', ( tester, ) async { diff --git a/app/test/features/walkthrough/walkthrough_gate_test.dart b/app/test/features/walkthrough/walkthrough_gate_test.dart index c82d5aca..80f29599 100644 --- a/app/test/features/walkthrough/walkthrough_gate_test.dart +++ b/app/test/features/walkthrough/walkthrough_gate_test.dart @@ -108,6 +108,37 @@ Future _finishWalkthrough(WidgetTester tester) async { } void main() { + testWidgets( + 'first launch waits briefly for the connection before welcoming', + (tester) async { + final store = MemoryWalkthroughStore(); + final link = ValueNotifier(false); + await tester.pumpWidget(_host(store: store, link: link)); + await tester.pump(); + expect(find.text(_welcome), findsNothing); + + // The app connects a moment later: the welcome is the connected one, + // with no connect directions. + link.value = true; + await tester.pumpAndSettle(); + expect(find.text(_welcome), findsOneWidget); + expect(find.textContaining('start by connecting'), findsNothing); + }, + ); + + testWidgets( + 'first launch without a connection still offers the connect page', + (tester) async { + final store = MemoryWalkthroughStore(); + final link = ValueNotifier(false); + await tester.pumpWidget(_host(store: store, link: link)); + await tester.pump(const Duration(seconds: 3)); + await tester.pumpAndSettle(); + expect(find.text(_welcome), findsOneWidget); + expect(find.textContaining('start by connecting'), findsOneWidget); + }, + ); + testWidgets('first launch shows the walkthrough once per device', ( tester, ) async { diff --git a/app/test/ui/status/error_notice_test.dart b/app/test/ui/status/error_notice_test.dart index f464b6b1..3974e351 100644 --- a/app/test/ui/status/error_notice_test.dart +++ b/app/test/ui/status/error_notice_test.dart @@ -35,6 +35,23 @@ void main() { errorAdviceKind(TimeoutException('request timed out after 30000ms')), ErrorAdviceKind.timeout, ); + expect( + errorAdviceKind( + const ProtocolError('chat is not configured on this server'), + ), + ErrorAdviceKind.noHarness, + ); + expect( + errorAdviceKind( + 'HARNESS TRANSPORT: harness unreachable: cannot run the selected ' + 'OpenCode CLI', + ), + ErrorAdviceKind.noHarness, + ); + expect( + errorAdviceSentence(ErrorAdviceKind.noHarness), + contains('pipelines harness setup'), + ); expect(errorAdviceKind('pipeline 4 has no stage review'), isNull); final advice = errorAdvice(StateError('Connection closed')); expect(advice?.detail, 'Connection closed'); diff --git a/app/test/ui/theme/compact_switch_test.dart b/app/test/ui/theme/compact_switch_test.dart index cc34a60e..8c0b3710 100644 --- a/app/test/ui/theme/compact_switch_test.dart +++ b/app/test/ui/theme/compact_switch_test.dart @@ -106,6 +106,8 @@ void main() { AppDesign.standard, AppDesign.terminal, AppDesign.paper, + AppDesign.notebook, + AppDesign.highContrast, AppDesign.compact, ]) { design.value = other; diff --git a/app/test/ui/theme/high_contrast_design_test.dart b/app/test/ui/theme/high_contrast_design_test.dart index d8226a3a..d4820b86 100644 --- a/app/test/ui/theme/high_contrast_design_test.dart +++ b/app/test/ui/theme/high_contrast_design_test.dart @@ -5,6 +5,7 @@ import 'package:pipelines_app/features/chat/domain/chat_colors.dart'; import 'package:pipelines_app/features/chat/ui/sessions/chat_color_palette.dart'; import 'package:pipelines_app/ui/adaptive/platform.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'; import 'package:pipelines_app/ui/theme/high_contrast_palette.dart'; @@ -54,6 +55,7 @@ void main() { expect(tokens.largeTargets, isTrue); expect(tokens.minContrast, highContrastMinimum); expect(tokens.windowRadius, 6); + expect(tokens.snapSwitch, isTrue); expect(tokens.ansi, isNotNull); } }, @@ -253,6 +255,7 @@ void main() { expect(tokens.largeTargets, isFalse, reason: design.id); expect(tokens.minContrast, isNull, reason: design.id); expect(tokens.windowRadius, isNull, reason: design.id); + expect(tokens.snapSwitch, isFalse, reason: design.id); expect(tokens.transcript, isNot(TranscriptStyle.boxed)); expect(tokens.selectedRow, isNot(SelectedRowStyle.inverted)); final frame = tokens.frame; @@ -265,6 +268,18 @@ void main() { }); }); + test('a switch into or out of High contrast snaps; Paper to Terminal ' + 'still blends', () async { + final designs = AppDesignController(store: MemoryAppDesignStore()); + await designs.select(AppDesign.paper); + await designs.select(AppDesign.terminal); + expect(designs.themeAnimationDuration, kThemeAnimationDuration); + await designs.select(AppDesign.highContrast); + expect(designs.themeAnimationDuration, Duration.zero); + await designs.select(AppDesign.paper); + expect(designs.themeAnimationDuration, Duration.zero); + }); + testWidgets('touch targets on a desktop only under High contrast', ( tester, ) async { diff --git a/app/test/ui/theme/notebook_design_test.dart b/app/test/ui/theme/notebook_design_test.dart new file mode 100644 index 00000000..c02f0f6f --- /dev/null +++ b/app/test/ui/theme/notebook_design_test.dart @@ -0,0 +1,128 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/notebook/notebook_cell_frame.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_tokens.dart'; + +import '../../features/chat/conversation/chat_composer_bar_fixtures.dart'; + +ThemeData _theme(Brightness brightness, {String? font}) => + brightness == Brightness.dark + ? AppDesign.notebook.dark(fontFamily: font) + : AppDesign.notebook.light(fontFamily: font); + +Widget _thread(ComposerBarGateway gateway, AppDesign design) => MaterialApp( + theme: design.light(), + home: Scaffold( + body: ChatThreadView( + gateway: gateway, + sessionId: 's', + session: const {'id': 's', 'directory': '/Users/ada/repos/tank'}, + syncToken: 0, + onBack: () {}, + drafts: MemoryChatDraftStore(), + ), + ), +); + +void main() { + test('Notebook is listed with a stable id, a label and one line', () { + expect(AppDesign.fromId('notebook'), AppDesign.notebook); + expect(AppDesign.notebook.label, 'Notebook'); + expect(AppDesign.notebook.description, isNot(contains('\n'))); + expect(AppDesign.notebook.usesInterfaceFont, isTrue); + }); + + test('Notebook tokens: cells transcript, cell composer, washed row, ' + '4-6px corners, hairlines, flat', () { + for (final brightness in Brightness.values) { + final theme = _theme(brightness); + final tokens = theme.extension()!; + expect(tokens.design, AppDesign.notebook); + expect(tokens.transcript, TranscriptStyle.cells); + expect(tokens.terminal, isFalse); + expect(tokens.composer, ComposerStyle.cell); + expect(tokens.selectedRow, SelectedRowStyle.washed); + expect(tokens.radius, inInclusiveRange(4, 6)); + expect(tokens.flat, isTrue); + expect(tokens.frame, theme.colorScheme.outlineVariant); + expect(tokens.ansi, isNotNull); + // Reading text keeps the interface sans. + expect(tokens.reading.family, isNull); + } + }); + + test('Notebook pages: white by day, neutral charcoal by night, cells a ' + 'step off the page', () { + final light = _theme(Brightness.light); + expect(light.scaffoldBackgroundColor, const Color(0xFFFFFFFF)); + final dark = _theme(Brightness.dark); + expect( + dark.scaffoldBackgroundColor.computeLuminance(), + inExclusiveRange(0.005, 0.03), + ); + for (final theme in [light, dark]) { + final scheme = theme.colorScheme; + expect(scheme.surfaceContainerLow, isNot(scheme.surface)); + expect(scheme.onSurface, isNot(scheme.onSurfaceVariant)); + } + }); + + test('Notebook keeps the interface font and caches its themes', () { + expect( + _theme(Brightness.light, font: 'Inter').textTheme.bodyLarge?.fontFamily, + 'Inter', + ); + expect(identical(_theme(Brightness.dark), _theme(Brightness.dark)), isTrue); + expect( + AppDesign.notebook.build(Brightness.light), + _theme(Brightness.light), + ); + }); + + testWidgets('Notebook: the composer is an In [ ]: input cell whose frame ' + 'takes the accent on focus', (tester) async { + final gateway = ComposerBarGateway(); + addTearDown(gateway.close); + await tester.pumpWidget(_thread(gateway, AppDesign.notebook)); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-composer-pill')), findsNothing); + expect(find.byKey(const Key('chat-composer-underline')), findsNothing); + final cell = find.byKey(const Key('chat-composer-cell')); + expect(cell, findsOneWidget); + expect( + find.descendant(of: cell, matching: find.text('In [ ]:')), + findsOneWidget, + ); + for (final key in [ + 'chat-composer-attach', + 'chat-composer-field', + 'chat-composer-primary', + ]) { + expect( + find.descendant(of: cell, matching: find.byKey(Key(key))), + findsOneWidget, + ); + } + final scheme = Theme.of(tester.element(cell)).colorScheme; + Color frame() { + final paint = tester.widget( + find + .descendant( + of: find.byKey(const Key('chat-composer-cell-frame')), + matching: find.byType(CustomPaint), + ) + .first, + ); + return (paint.painter! as NotebookCellPainter).border; + } + + expect(frame(), scheme.outlineVariant); + await tester.tap(find.byKey(const Key('chat-composer-field'))); + await tester.pumpAndSettle(); + expect(frame(), scheme.primary); + }); +} 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: