diff --git a/app/lib/application/app_route.dart b/app/lib/application/app_route.dart index d684e3a8..8b83c29a 100644 --- a/app/lib/application/app_route.dart +++ b/app/lib/application/app_route.dart @@ -4,7 +4,15 @@ part 'app_route_codec.dart'; /// /// The set mirrors [AppDestination] but stays free of widget imports so the /// parser and serialiser can be exercised without a Flutter host. -enum AppRouteKind { pipelines, runs, chat, search, settings, templates, schedules } +enum AppRouteKind { + pipelines, + runs, + chat, + search, + settings, + templates, + schedules, +} /// One page route: a destination plus the detail, pane and query it opens. /// diff --git a/app/lib/core/error_reason.dart b/app/lib/core/error_reason.dart index 39e9c249..a13f28ce 100644 --- a/app/lib/core/error_reason.dart +++ b/app/lib/core/error_reason.dart @@ -5,10 +5,7 @@ /// reason itself, never a Dart diagnostic, so those prefixes are stripped while /// deliberate protocol/refusal messages stay untouched. [fallback] is the /// honest sentence for a failure that carries no text at all. -String describeErrorReason( - Object error, { - required String fallback, -}) { +String describeErrorReason(Object error, {required String fallback}) { final raw = switch (error) { StateError(:final message) => message.toString(), _ => '$error', diff --git a/app/lib/features/attention/notify/chat_question_notices.dart b/app/lib/features/attention/notify/chat_question_notices.dart index fc4b3fdb..1e54f5c8 100644 --- a/app/lib/features/attention/notify/chat_question_notices.dart +++ b/app/lib/features/attention/notify/chat_question_notices.dart @@ -32,10 +32,14 @@ class ChatQuestionNotices { if (event is! Map || event['kind'] != 'form') return; final sessionId = event['session_id']; final form = event['form']; - if (sessionId is! String || sessionId.isEmpty || - form is! Map || form['kind'] != 'question' || - form['resolved'] == true || form['cancelled'] == true || - form['id'] == null || !canNotify() || + if (sessionId is! String || + sessionId.isEmpty || + form is! Map || + form['kind'] != 'question' || + form['resolved'] == true || + form['cancelled'] == true || + form['id'] == null || + !canNotify() || activeChatSessionId() == sessionId) { return; } diff --git a/app/lib/features/chat/conversation/chat_color_wash.dart b/app/lib/features/chat/conversation/chat_color_wash.dart new file mode 100644 index 00000000..6daf4553 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_color_wash.dart @@ -0,0 +1,47 @@ +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/chat_colors.dart'; +import '../ui/sessions/chat_color_palette.dart'; + +/// The open chat's colour as a faint wash behind the top of the page: it +/// shows through the glass bar and fades out just below it, so even without +/// the list beside it the chat carries a gentle reminder of which one it is. +/// It sits under the transcript and takes no taps, so text contrast and +/// hit-testing are untouched. Nothing is drawn for a chat with no colour. +class ChatColorWash extends StatelessWidget { + const ChatColorWash({super.key, required this.session}); + + final JsonMap? session; + + @override + Widget build(BuildContext context) { + final color = chatColorShade(context, chatSessionColor(session)); + if (color == null) return const SizedBox.shrink(); + final strength = chatColorDarkSurface(context) ? 0.24 : 0.2; + // The bar's height arrives as top padding; the wash reaches a little + // past it so the fade reads under the bar, not as an edge at it. + final height = MediaQuery.paddingOf(context).top + 96; + return Positioned( + top: 0, + left: 0, + right: 0, + height: height, + child: IgnorePointer( + child: DecoratedBox( + key: const Key('chat-color-wash'), + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + color.withValues(alpha: strength), + color.withValues(alpha: 0), + ], + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 767ca708..07491e6f 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -11,8 +11,10 @@ import '../data/chat_repository.dart'; import '../domain/chat_activity_detail.dart'; import '../domain/chat_notice.dart'; import '../domain/chat_attachment_picker.dart'; +import '../domain/chat_colors.dart'; import '../domain/chat_transcript.dart'; import '../ui/sessions/chat_adaptive.dart'; +import '../ui/sessions/chat_color_picker.dart'; import '../ui/sessions/session_actions.dart'; import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_message_view.dart'; @@ -23,6 +25,7 @@ import 'chat_account_usage_section.dart'; import 'chat_export_controller.dart'; import 'chat_session_section.dart'; import 'chat_background_tasks.dart'; +import 'chat_color_wash.dart'; import 'chat_command_actions.dart'; import 'chat_composer_bar.dart'; import 'chat_composer_controller.dart'; @@ -80,9 +83,14 @@ class ChatThreadView extends StatefulWidget { this.onSessionRenamed, this.onSessionClosed, this.fileBridge = const ArtifactFileBridge(), + this.onColorSelected, }); final ApiGateway gateway; + + /// Sets the chat's shared colour (a palette name, null for none) from the + /// information sheet; null leaves the sheet without the Colour choice. + final ValueChanged? onColorSelected; final String sessionId; final VoidCallback onBack; @@ -370,6 +378,8 @@ class _ChatThreadViewState extends State { controller: _controller, handoff: handoff, exporter: exporter, + color: chatSessionColor(widget.session), + onColorSelected: widget.onColorSelected, ); if (cupertino) { await showCupertinoModalPopup( @@ -962,6 +972,8 @@ class _ChatThreadViewState extends State { _rowWidgets.prune(); return Stack( children: [ + // Behind everything: the chat's colour under the bar. + ChatColorWash(session: widget.session), // At rest the first item starts below the floating bar // and the last one ends above the floating composer. // Bottom-anchored at the split row, the newest rows are @@ -1580,11 +1592,15 @@ class _ChatInfoSheet extends StatelessWidget { required this.controller, required this.handoff, required this.exporter, + this.color, + this.onColorSelected, }); final ChatThreadController controller; final ChatSessionHandoff handoff; final ChatExportController exporter; + final String? color; + final ValueChanged? onColorSelected; @override Widget build(BuildContext context) { @@ -1603,6 +1619,8 @@ class _ChatInfoSheet extends StatelessWidget { cupertino: cupertino, doneKey: const Key('chat-info-close'), ), + if (onColorSelected case final onSelected?) + ChatColorSection(selected: color, onSelected: onSelected), for (final metric in _chatInfoMetrics(controller.usage)) _ChatInfoRow(metric: metric, cupertino: cupertino), ChatAccountUsageSection( diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart index a11d3b1f..a765ebff 100644 --- a/app/lib/features/chat/data/chat_repository.dart +++ b/app/lib/features/chat/data/chat_repository.dart @@ -196,6 +196,12 @@ class ChatRepository { gateway.call('chat_star', { 'chat_query': {'session_id': sessionId, 'starred': starred}, }); + + /// Sets the shared highlight colour by palette name; null clears it. + Future setColor(String sessionId, String? color) => + gateway.call('chat_color', { + 'chat_query': {'session_id': sessionId, 'color': color}, + }); Future close(String sessionId) => gateway.call('chat_close', { 'chat_query': {'session_id': sessionId}, }); diff --git a/app/lib/features/chat/domain/chat_colors.dart b/app/lib/features/chat/domain/chat_colors.dart new file mode 100644 index 00000000..a453ceef --- /dev/null +++ b/app/lib/features/chat/domain/chat_colors.dart @@ -0,0 +1,23 @@ +/// The fixed palette of shared chat highlight colours, by the names the +/// server stores, in picker order. Each host renders its own tuned shade. +const chatColorNames = [ + 'red', + 'orange', + 'amber', + 'green', + 'teal', + 'blue', + 'purple', + 'pink', +]; + +/// The session's highlight name, or null when it has none (or one this +/// client does not know). +String? chatSessionColor(Map? session) { + final name = '${session?['color'] ?? ''}'.trim(); + return chatColorNames.contains(name) ? name : null; +} + +/// The colour's name as a person reads it. +String chatColorLabel(String name) => + name.isEmpty ? name : name[0].toUpperCase() + name.substring(1); diff --git a/app/lib/features/chat/domain/chat_sessions.dart b/app/lib/features/chat/domain/chat_sessions.dart index fdefd8e6..e6660b1e 100644 --- a/app/lib/features/chat/domain/chat_sessions.dart +++ b/app/lib/features/chat/domain/chat_sessions.dart @@ -34,6 +34,62 @@ List<({String directory, List sessions})> groupChatSessions( .toList(); } +/// The list's sections in on-screen order: Starred (open chats, by name, so +/// each keeps its place), Chats (open, server recency) and Closed (server +/// recency). Empty sections are left out. +List<({String title, List sessions})> chatSessionSections( + List visible, +) { + bool closed(JsonMap s) => s['closed_at'] != null; + bool starred(JsonMap s) => s['starred'] == true && !closed(s); + final sections = [ + ( + title: 'Starred', + sessions: sortStarredChatSessions(visible.where(starred)), + ), + ( + title: 'Chats', + sessions: visible.where((s) => !starred(s) && !closed(s)).toList(), + ), + (title: 'Closed', sessions: visible.where(closed).toList()), + ]; + return [ + for (final section in sections) + if (section.sessions.isNotEmpty) section, + ]; +} + +/// Starred chats alphabetically by their shown title, ignoring case; equal +/// titles keep a fixed order by id. +List sortStarredChatSessions(Iterable sessions) => + sessions.toList()..sort((a, b) { + final byTitle = chatSessionTitle( + a, + ).toLowerCase().compareTo(chatSessionTitle(b).toLowerCase()); + if (byTitle != 0) return byTitle; + return '${a['id'] ?? ''}'.compareTo('${b['id'] ?? ''}'); + }); + +/// Whether a section's rows are split under directory headings. Starred keeps +/// its alphabetical order whole, so a name is always in the same place. +bool chatSectionGroupsByDirectory(String title) => title != 'Starred'; + +/// The rows of [sections] in the order the list draws them: each open +/// section's rows, directory group by directory group. A folded section +/// draws no rows. +List chatSessionsInListOrder( + List<({String title, List sessions})> sections, { + required bool Function(String title) isOpen, +}) => [ + for (final section in sections) + if (isOpen(section.title)) + if (chatSectionGroupsByDirectory(section.title)) + for (final group in groupChatSessions(section.sessions)) + ...group.sessions + else + ...section.sessions, +]; + String chatSessionActivity({required bool running, required bool unseen}) => running ? 'streaming' diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 42da11fe..9f71430e 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -252,6 +252,7 @@ class _ChatScreenState extends State { onCreatedSession: _openCreated, onSessionRenamed: (title) => _renamed(selected, title), onSessionClosed: _closed, + onColorSelected: (color) => _sessions.setColor(selected, color), ); } diff --git a/app/lib/features/chat/ui/sessions/chat_color_palette.dart b/app/lib/features/chat/ui/sessions/chat_color_palette.dart new file mode 100644 index 00000000..655b0e5c --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_color_palette.dart @@ -0,0 +1,49 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../domain/chat_colors.dart'; +import 'chat_adaptive.dart'; + +/// The host's own shade for a chat colour name, tuned for the current +/// brightness: Cupertino's dynamic system colours, and Material's standard +/// swatches (a deeper tone on light surfaces, a lighter one on dark), so the +/// mark keeps its contrast in both. Null for no (or an unknown) colour. +Color? chatColorShade(BuildContext context, String? name) { + if (name == null || !chatColorNames.contains(name)) return null; + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + final CupertinoDynamicColor color = switch (name) { + 'red' => CupertinoColors.systemRed, + 'orange' => CupertinoColors.systemOrange, + 'amber' => CupertinoColors.systemYellow, + 'green' => CupertinoColors.systemGreen, + 'teal' => CupertinoColors.systemTeal, + 'blue' => CupertinoColors.systemBlue, + 'purple' => CupertinoColors.systemPurple, + _ => CupertinoColors.systemPink, + }; + return color.resolveFrom(context); + } + final dark = Theme.of(context).brightness == Brightness.dark; + final MaterialColor swatch = switch (name) { + 'red' => Colors.red, + 'orange' => Colors.orange, + 'amber' => Colors.amber, + 'green' => Colors.green, + 'teal' => Colors.teal, + 'blue' => Colors.blue, + 'purple' => Colors.purple, + _ => Colors.pink, + }; + if (dark) return swatch.shade300; + return switch (name) { + 'orange' || 'amber' => swatch.shade800, + 'red' || 'teal' || 'purple' || 'pink' => swatch.shade600, + _ => swatch.shade700, + }; +} + +/// Whether the surrounding theme is dark, on either host. +bool chatColorDarkSurface(BuildContext context) => + chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? CupertinoTheme.brightnessOf(context) == Brightness.dark + : Theme.of(context).brightness == Brightness.dark; diff --git a/app/lib/features/chat/ui/sessions/chat_color_picker.dart b/app/lib/features/chat/ui/sessions/chat_color_picker.dart new file mode 100644 index 00000000..d58dc092 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_color_picker.dart @@ -0,0 +1,192 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../ui/layout/app_sheet_header.dart'; +import '../../domain/chat_colors.dart'; +import 'chat_adaptive.dart'; +import 'chat_color_palette.dart'; + +/// The chat colour choices: None, then the palette, as the host's own icon +/// buttons. The chosen one shows a check. It keeps its own selection, so a +/// pick shows at once inside a sheet that the list's rebuild cannot reach. +class ChatColorSwatches extends StatefulWidget { + const ChatColorSwatches({ + super.key, + required this.selected, + required this.onSelected, + }); + + /// The current colour name, or null for none. + final String? selected; + final ValueChanged onSelected; + + @override + State createState() => _ChatColorSwatchesState(); +} + +class _ChatColorSwatchesState extends State { + late String? _selected = widget.selected; + + @override + void didUpdateWidget(covariant ChatColorSwatches oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.selected != widget.selected) _selected = widget.selected; + } + + void _pick(String? name) { + setState(() => _selected = name); + widget.onSelected(name); + } + + @override + Widget build(BuildContext context) { + return Wrap( + spacing: 4, + runSpacing: 4, + children: [ + _swatch(context, null), + for (final name in chatColorNames) _swatch(context, name), + ], + ); + } + + Widget _swatch(BuildContext context, String? name) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final selected = _selected == name; + final label = name == null ? 'No colour' : chatColorLabel(name); + final muted = cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + final color = chatColorShade(context, name) ?? muted; + final IconData icon = name == null + ? (cupertino ? CupertinoIcons.nosign : Icons.block) + : selected + ? (cupertino + ? CupertinoIcons.checkmark_circle_fill + : Icons.check_circle) + : (cupertino ? CupertinoIcons.circle_fill : Icons.circle); + final glyph = Icon(icon, color: color, size: 32); + // The None choice has no fill to check, so its selection is a ring. + final mark = name == null && selected + ? DecoratedBox( + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: color, width: 2), + ), + child: Padding(padding: const EdgeInsets.all(2), child: glyph), + ) + : glyph; + final button = cupertino + ? CupertinoButton( + padding: const EdgeInsets.all(4), + minimumSize: const Size.square(kMinInteractiveDimensionCupertino), + onPressed: () => _pick(name), + child: mark, + ) + : IconButton( + tooltip: label, + isSelected: selected, + onPressed: () => _pick(name), + icon: mark, + ); + return Semantics( + key: Key('chat-color-${name ?? 'none'}'), + button: true, + selected: selected, + label: label, + excludeSemantics: true, + onTap: () => _pick(name), + child: button, + ); + } +} + +/// A titled "Colour" section: the heading, then the swatches. +class ChatColorSection extends StatelessWidget { + const ChatColorSection({ + super.key, + required this.selected, + required this.onSelected, + this.padding = const EdgeInsetsDirectional.fromSTEB(24, 6, 24, 6), + }); + + final String? selected; + final ValueChanged onSelected; + final EdgeInsetsGeometry padding; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final labelStyle = + (cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodySmall) + ?.copyWith( + color: cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant, + ); + return Padding( + key: const Key('chat-color-section'), + padding: padding, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Colour', style: labelStyle), + const SizedBox(height: 4), + ChatColorSwatches(selected: selected, onSelected: onSelected), + ], + ), + ); + } +} + +/// Lets the operator pick [title]'s colour in a sheet. Each pick applies at +/// once through [onSelected]; Done closes the sheet. +Future showChatColorPicker( + BuildContext context, { + required String title, + required String? selected, + required ValueChanged onSelected, +}) async { + final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + Widget content(BuildContext sheet) => Column( + key: const Key('chat-color-sheet'), + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + AppSheetHeader( + title: 'Colour for $title', + cupertino: cupertino, + doneKey: const Key('chat-color-done'), + ), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(20, 4, 20, 20), + child: ChatColorSwatches(selected: selected, onSelected: onSelected), + ), + ], + ); + if (cupertino) { + await showCupertinoModalPopup( + context: context, + builder: (sheet) => Align( + alignment: Alignment.bottomCenter, + child: SafeArea( + child: CupertinoPopupSurface( + child: SingleChildScrollView(child: content(sheet)), + ), + ), + ), + ); + return; + } + await showModalBottomSheet( + context: context, + showDragHandle: true, + isScrollControlled: true, + useSafeArea: true, + builder: (sheet) => SingleChildScrollView(child: content(sheet)), + ); +} 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 bb2d7b5f..f214fe95 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_body.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_body.dart @@ -9,6 +9,17 @@ import 'session_row_style.dart'; typedef ChatSessionSection = ({String title, List sessions}); +/// Which list sections are folded away, kept by the list's screen so the +/// keyboard shortcuts count only rows on screen. Closed starts folded. +class ChatSectionFolds { + final Set _folded = {'Closed'}; + + bool isOpen(String title) => !_folded.contains(title); + + void set(String title, bool open) => + open ? _folded.remove(title) : _folded.add(title); +} + /// Groups the visible sessions the way the server reports them. class ChatSessionsBody extends StatelessWidget { const ChatSessionsBody({ @@ -22,14 +33,17 @@ class ChatSessionsBody extends StatelessWidget { required this.onClose, required this.onReopen, required this.onStar, + this.onColor, required this.onHide, required this.onClearSearch, required this.isUnseen, required this.errorFor, + this.folds, this.activeSessionId, this.onDismissError, }); + final ChatSectionFolds? folds; final List sessions; final String? activeSessionId; final String query; @@ -40,6 +54,7 @@ class ChatSessionsBody extends StatelessWidget { final ValueChanged onClose; final ValueChanged onReopen; final ValueChanged onStar; + final ValueChanged? onColor; final ValueChanged onHide; final VoidCallback onClearSearch; final bool Function(JsonMap) isUnseen; @@ -49,27 +64,7 @@ class ChatSessionsBody extends StatelessWidget { @override Widget build(BuildContext context) { final visible = filterChatSessions(sessions, query); - final sections = [ - if (visible.any((s) => s['starred'] == true && s['closed_at'] == null)) - ( - title: 'Starred', - sessions: visible - .where((s) => s['starred'] == true && s['closed_at'] == null) - .toList(), - ), - if (visible.any((s) => s['starred'] != true && s['closed_at'] == null)) - ( - title: 'Chats', - sessions: visible - .where((s) => s['starred'] != true && s['closed_at'] == null) - .toList(), - ), - if (visible.any((s) => s['closed_at'] != null)) - ( - title: 'Closed', - sessions: visible.where((s) => s['closed_at'] != null).toList(), - ), - ]; + final sections = chatSessionSections(visible); final emptyMessage = sessions.isEmpty ? error == null ? 'No chat sessions on this server yet.' @@ -82,6 +77,7 @@ class ChatSessionsBody extends StatelessWidget { if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { return CupertinoSessionList( sections: sections, + folds: folds, activeSessionId: activeSessionId, emptyMessage: visible.isEmpty ? emptyMessage : null, duplicateTitles: duplicateTitles, @@ -90,6 +86,7 @@ class ChatSessionsBody extends StatelessWidget { onClose: onClose, onReopen: onReopen, onStar: onStar, + onColor: onColor, onHide: onHide, onClearSearch: clearSearch, isUnseen: isUnseen, @@ -99,6 +96,7 @@ class ChatSessionsBody extends StatelessWidget { } return MaterialSessionList( sections: sections, + folds: folds, activeSessionId: activeSessionId, emptyMessage: visible.isEmpty ? emptyMessage : null, duplicateTitles: duplicateTitles, @@ -107,6 +105,7 @@ class ChatSessionsBody extends StatelessWidget { onClose: onClose, onReopen: onReopen, onStar: onStar, + onColor: onColor, onHide: onHide, onClearSearch: clearSearch, isUnseen: isUnseen, diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart index e11afd84..7bb2d724 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -74,6 +74,7 @@ class ChatSessionsController extends ChangeNotifier { } void _onFrame(JsonMap frame) { + if (frame['type'] == 'chat_session_changed') return _sessionChanged(frame); final effect = chatSessionFrameEffect(frame); if (effect == null) return; final id = effect.sessionId; @@ -86,6 +87,38 @@ class ChatSessionsController extends ChangeNotifier { if (effect.attention && id == activeSessionId) _scheduleActiveAck(id); } + /// Another device changed a chat's shared colour, star or title: the row + /// takes the server's values at once, with no re-list. Each field the + /// registry row omits is cleared, since omitted means unset on the wire. + void _sessionChanged(JsonMap frame) { + final changed = frame['chat_session']; + if (changed is! Map) return; + final id = '${changed['id'] ?? ''}'; + if (id.isEmpty || _disposed) return; + var found = false; + _sessions = [ + for (final row in _sessions) + if ('${row['id'] ?? ''}' == id) + () { + found = true; + final next = {...row}; + for (final key in const ['color', 'starred', 'starred_at']) { + if (changed.containsKey(key)) { + next[key] = changed[key]; + } else { + next.remove(key); + } + } + final title = '${changed['title'] ?? ''}'.trim(); + if (title.isNotEmpty) next['title'] = title; + return next; + }() + else + row, + ]; + if (found) _notify(); + } + void _bindAckSync(AttentionAckSync? sync) { if (identical(sync, _ackSync)) return; _ackSync?.removeListener(_ackChanged); @@ -245,6 +278,13 @@ class ChatSessionsController extends ChangeNotifier { patch: {'starred': starred}, ); + /// Sets [sessionId]'s shared colour (a palette name, null for none). + Future setColor(String sessionId, String? color) => _mutate( + sessionId, + () => repository.setColor(sessionId, color), + patch: {'color': color}, + ); + Future close(String sessionId) => _mutate( sessionId, () => repository.close(sessionId), 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 c9146548..de3b201b 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -8,8 +8,12 @@ import '../../../../ui/layout/content_width.dart'; import '../../../../core/api_gateway.dart'; import '../../../../shell/shell_bar.dart'; +import '../../../../shell/shell_list_shortcuts.dart'; import '../../data/chat_repository.dart'; +import '../../domain/chat_colors.dart'; +import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; +import 'chat_color_picker.dart'; import 'chat_session_local.dart'; import 'chat_sessions_body.dart'; import 'chat_sessions_controller.dart'; @@ -76,6 +80,7 @@ class _ChatSessionsScreenState extends State { ..activeSessionId = widget.activeSessionId ..refresh(); final _search = TextEditingController(); + final _folds = ChatSectionFolds(); Timer? _undoTimer; String? _markedActiveSessionId; @@ -182,6 +187,26 @@ class _ChatSessionsScreenState extends State { void _star(JsonMap session) => _controller.star(_sessionId(session), session['starred'] != true); + Future _color(JsonMap session) => showChatColorPicker( + context, + title: chatSessionTitle(session), + selected: chatSessionColor(session), + onSelected: (color) => _controller.setColor(_sessionId(session), color), + ); + + /// Ctrl+N: opens the Nth row the list draws (Starred first, then Chats by + /// directory, then Closed while it is unfolded), searched as shown. + bool _openIndex(int index) { + final visible = filterChatSessions(_controller.sessions, _search.text); + final rows = chatSessionsInListOrder( + chatSessionSections(visible), + isOpen: _folds.isOpen, + ); + if (index < 0 || index >= rows.length) return false; + _open(rows[index]); + return true; + } + Future _hide(JsonMap session) async { await _controller.hide(_sessionId(session)); _undoTimer?.cancel(); @@ -235,7 +260,9 @@ class _ChatSessionsScreenState extends State { onClose: _close, onReopen: _reopen, onStar: _star, + onColor: _color, onHide: _hide, + folds: _folds, onClearSearch: () { _search.clear(); setState(() {}); @@ -278,7 +305,7 @@ class _ChatSessionsScreenState extends State { child: ShellBadge( kind: ShellBadgeKind.unread, count: _controller.sessions.where(_controller.isUnseen).length, - child: body, + child: ShellListShortcut(onOpenIndex: _openIndex, child: body), ), ); } diff --git a/app/lib/features/chat/ui/sessions/session_actions.dart b/app/lib/features/chat/ui/sessions/session_actions.dart index 3bec0fb4..f792eebd 100644 --- a/app/lib/features/chat/ui/sessions/session_actions.dart +++ b/app/lib/features/chat/ui/sessions/session_actions.dart @@ -7,7 +7,7 @@ import 'chat_adaptive.dart'; import 'session_row_style.dart'; import '../../../../ui/layout/app_overflow_menu.dart'; -enum SessionAction { star, rename, close, reopen, hide } +enum SessionAction { star, color, rename, close, reopen, hide } /// The close confirmation's body, matching the web client's explanation. String closeChatConfirmation(String title) => @@ -50,6 +50,7 @@ List<({SessionAction action, String label})> _items(JsonMap session) { action: SessionAction.star, label: session['starred'] == true ? 'Unstar' : 'Star', ), + (action: SessionAction.color, label: 'Colour…'), (action: SessionAction.rename, label: 'Rename…'), isClosed ? (action: SessionAction.reopen, label: 'Reopen') diff --git a/app/lib/features/chat/ui/sessions/session_list_cupertino.dart b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart index 650e942a..66c77225 100644 --- a/app/lib/features/chat/ui/sessions/session_list_cupertino.dart +++ b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart @@ -17,15 +17,18 @@ class CupertinoSessionList extends StatelessWidget { required this.onClose, required this.onReopen, required this.onStar, + this.onColor, required this.onHide, required this.onClearSearch, required this.isUnseen, required this.errorFor, + this.folds, this.activeSessionId, this.onDismissError, }); final List sections; + final ChatSectionFolds? folds; final String? activeSessionId; final String? emptyMessage; final Set duplicateTitles; @@ -34,6 +37,7 @@ class CupertinoSessionList extends StatelessWidget { final ValueChanged onClose; final ValueChanged onReopen; final ValueChanged onStar; + final ValueChanged? onColor; final ValueChanged onHide; final VoidCallback? onClearSearch; final bool Function(JsonMap) isUnseen; @@ -71,6 +75,7 @@ class CupertinoSessionList extends StatelessWidget { Widget _section(ChatSessionSection section) => chatSessionSection( section: section, + folds: folds ?? ChatSectionFolds(), directoryHeader: _DirectoryHeader.new, row: (session, {required divider}) => chatSessionRowItem( session, @@ -80,6 +85,7 @@ class CupertinoSessionList extends StatelessWidget { isUnseen: isUnseen, onOpen: onOpen, onStar: onStar, + onColor: onColor, onRename: onRename, onClose: onClose, onReopen: onReopen, diff --git a/app/lib/features/chat/ui/sessions/session_list_items.dart b/app/lib/features/chat/ui/sessions/session_list_items.dart index 6423b6ab..d856ea71 100644 --- a/app/lib/features/chat/ui/sessions/session_list_items.dart +++ b/app/lib/features/chat/ui/sessions/session_list_items.dart @@ -15,13 +15,16 @@ typedef SessionListItem = ({Key key, WidgetBuilder build}); /// screen. Material and Cupertino supply their own directory header. Widget chatSessionSection({ required ChatSessionSection section, + required ChatSectionFolds folds, required Widget Function(String directory) directoryHeader, required SessionListItem Function(JsonMap session, {required bool divider}) row, required String? Function(String sessionId) errorFor, required ValueChanged? onDismissError, }) { - final groups = groupChatSessions(section.sessions); + final groups = chatSectionGroupsByDirectory(section.title) + ? groupChatSessions(section.sessions) + : [(directory: '', sessions: section.sessions)]; final items = [ for (final group in groups) ...[ if (groups.length > 1) @@ -67,7 +70,8 @@ Widget chatSessionSection({ key: ValueKey('chat-section-${section.title}'), title: section.title, count: section.sessions.length, - initiallyOpen: section.title != 'Closed', + initiallyOpen: folds.isOpen(section.title), + onOpenChanged: (open) => folds.set(section.title, open), itemCount: items.length, itemKey: (index) => items[index].key, itemBuilder: (context, index) => items[index].build(context), @@ -83,6 +87,7 @@ SessionListItem chatSessionRowItem( required bool Function(JsonMap) isUnseen, required ValueChanged onOpen, required ValueChanged onStar, + required ValueChanged? onColor, required ValueChanged onRename, required ValueChanged onClose, required ValueChanged onReopen, @@ -99,6 +104,7 @@ SessionListItem chatSessionRowItem( divider: divider, onOpen: onOpen, onStar: onStar, + onColor: onColor, onRename: onRename, onClose: onClose, onReopen: onReopen, diff --git a/app/lib/features/chat/ui/sessions/session_list_material.dart b/app/lib/features/chat/ui/sessions/session_list_material.dart index eee6adbf..1857e382 100644 --- a/app/lib/features/chat/ui/sessions/session_list_material.dart +++ b/app/lib/features/chat/ui/sessions/session_list_material.dart @@ -16,15 +16,18 @@ class MaterialSessionList extends StatelessWidget { required this.onClose, required this.onReopen, required this.onStar, + this.onColor, required this.onHide, required this.onClearSearch, required this.isUnseen, required this.errorFor, + this.folds, this.activeSessionId, this.onDismissError, }); final List sections; + final ChatSectionFolds? folds; final String? activeSessionId; final String? emptyMessage; final Set duplicateTitles; @@ -33,6 +36,7 @@ class MaterialSessionList extends StatelessWidget { final ValueChanged onClose; final ValueChanged onReopen; final ValueChanged onStar; + final ValueChanged? onColor; final ValueChanged onHide; final VoidCallback? onClearSearch; final bool Function(JsonMap) isUnseen; @@ -80,6 +84,7 @@ class MaterialSessionList extends StatelessWidget { final heading = SectionHeadingStyle.of(context); return chatSessionSection( section: section, + folds: folds ?? ChatSectionFolds(), directoryHeader: (directory) => ListTile( dense: true, leading: const Icon(Icons.folder_outlined), @@ -96,6 +101,7 @@ class MaterialSessionList extends StatelessWidget { isUnseen: isUnseen, onOpen: onOpen, onStar: onStar, + onColor: onColor, onRename: onRename, onClose: onClose, onReopen: onReopen, diff --git a/app/lib/features/chat/ui/sessions/session_row_content.dart b/app/lib/features/chat/ui/sessions/session_row_content.dart index fa775be0..7dbdc00d 100644 --- a/app/lib/features/chat/ui/sessions/session_row_content.dart +++ b/app/lib/features/chat/ui/sessions/session_row_content.dart @@ -5,8 +5,10 @@ import '../../../../core/api_gateway.dart'; import '../../../../ui/layout/app_list_avatar.dart'; import '../../../../ui/layout/app_list_row.dart'; import '../../../../ui/text/relative_time_label.dart'; +import '../../domain/chat_colors.dart'; import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; +import 'chat_color_palette.dart'; import 'session_actions.dart'; import 'session_harness_icon.dart'; import 'session_row_style.dart'; @@ -16,8 +18,10 @@ import 'session_row_style.dart'; /// /// An unread chat is emphasised (heavier title, accent time) with an accent /// dot ending its line; a starred chat shows a small star after its title; a -/// running chat carries an activity badge on its avatar. A narrow pane drops -/// the avatar and time but keeps the menu, the list's only way to its actions. +/// running chat carries an activity badge on its avatar. A chat with a colour +/// wears it as a bar on the row's leading edge, a faint row tint and a +/// coloured avatar. A narrow pane drops the avatar and time but keeps the +/// colour bar and the menu, the list's only way to its actions. class ChatSessionRow extends StatelessWidget { const ChatSessionRow({ super.key, @@ -28,10 +32,12 @@ class ChatSessionRow extends StatelessWidget { this.unseen = false, this.divider = true, this.duplicateTitles = const {}, + this.onLongPress, }); final JsonMap session; final ValueChanged onOpen; + final VoidCallback? onLongPress; final ValueChanged onAction; final bool selected; final bool unseen; @@ -58,6 +64,8 @@ class ChatSessionRow extends StatelessWidget { divider: divider, keepMenuWhenCompact: true, onTap: () => onOpen(session), + onLongPress: onLongPress, + accent: chatColorShade(context, chatSessionColor(session)), leading: ChatSessionAvatar( session: session, running: session['running'] == true && !unseen, @@ -161,7 +169,15 @@ class ChatSessionAvatar extends StatelessWidget { chatControlsStyleOf(context) == ChatControlsStyle.cupertino; final Color fill; final Color mark; - if (cupertino) { + final color = chatColorShade(context, chatSessionColor(session)); + if (color != null) { + // The chat's colour is its identity, selected or not; the row's own + // fill marks the selection. + mark = color; + fill = color.withValues( + alpha: chatColorDarkSurface(context) ? 0.26 : 0.16, + ); + } else if (cupertino) { final primary = CupertinoTheme.of(context).primaryColor; fill = selected ? primary.withValues(alpha: 0.2) diff --git a/app/lib/features/chat/ui/sessions/session_row_memo.dart b/app/lib/features/chat/ui/sessions/session_row_memo.dart index 40914040..f35a9f7e 100644 --- a/app/lib/features/chat/ui/sessions/session_row_memo.dart +++ b/app/lib/features/chat/ui/sessions/session_row_memo.dart @@ -19,6 +19,7 @@ Widget memoChatSessionRow({ required bool divider, required ValueChanged onOpen, required ValueChanged onStar, + required ValueChanged? onColor, required ValueChanged onRename, required ValueChanged onClose, required ValueChanged onReopen, @@ -34,6 +35,7 @@ Widget memoChatSessionRow({ divider, onOpen, onStar, + onColor, onRename, onClose, onReopen, @@ -46,8 +48,11 @@ Widget memoChatSessionRow({ unseen: unseen, divider: divider, onOpen: onOpen, + // A long-press is the touch way to the colour, the row's quick mark. + onLongPress: onColor == null ? null : () => onColor(session), onAction: (action) => switch (action) { SessionAction.star => onStar(session), + SessionAction.color => onColor?.call(session), SessionAction.rename => onRename(session), SessionAction.close => onClose(session), SessionAction.reopen => onReopen(session), diff --git a/app/lib/features/pipelines/ui/run_pipeline_wording.dart b/app/lib/features/pipelines/ui/run_pipeline_wording.dart index 531fba87..74685289 100644 --- a/app/lib/features/pipelines/ui/run_pipeline_wording.dart +++ b/app/lib/features/pipelines/ui/run_pipeline_wording.dart @@ -44,7 +44,9 @@ const runPipelineActionKey = ValueKey('run-pipeline-action'); const runPipelinePromptKey = ValueKey('run-pipeline-prompt'); const runPipelineWorkspaceKey = ValueKey('run-pipeline-workspace'); const runPipelineNotifyKey = ValueKey('run-pipeline-notify'); -const runPipelineOutputFormatKey = ValueKey('run-pipeline-output-format'); +const runPipelineOutputFormatKey = ValueKey( + 'run-pipeline-output-format', +); const runPipelineCancelKey = ValueKey('run-pipeline-cancel'); const runPipelineConfirmKey = ValueKey('run-pipeline-confirm'); const runPipelineErrorKey = ValueKey('run-pipeline-error'); diff --git a/app/lib/features/pipelines/widgets/pipeline_list_panel.dart b/app/lib/features/pipelines/widgets/pipeline_list_panel.dart index e234bcb9..b4cac27a 100644 --- a/app/lib/features/pipelines/widgets/pipeline_list_panel.dart +++ b/app/lib/features/pipelines/widgets/pipeline_list_panel.dart @@ -3,6 +3,7 @@ import '../../../ui/layout/app_list_row.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import '../../../shell/shell_list_shortcuts.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/status/run_status_icon.dart'; import '../pipeline_format.dart'; @@ -53,7 +54,18 @@ class PipelineListPanel extends StatelessWidget { child: PipelineProgress(label: 'Refreshing pipelines'), ), ]; - return _content(context, header); + // Ctrl+1…Ctrl+9 open the Nth pipeline shown, filtered and sorted. + return ShellListShortcut( + onOpenIndex: (index) { + if (!controller.pipelinesLoaded) return false; + final items = controller.visiblePipelines; + if (index >= items.length) return false; + final pipeline = items[index]; + controller.openPipeline(pipeline.id, version: pipeline.version); + return true; + }, + child: _content(context, header), + ); } /// A state without rows: the controls stay at the top, below the bar. diff --git a/app/lib/features/runs/actions/retry_wording.dart b/app/lib/features/runs/actions/retry_wording.dart index b5e9edcc..97c6616a 100644 --- a/app/lib/features/runs/actions/retry_wording.dart +++ b/app/lib/features/runs/actions/retry_wording.dart @@ -29,7 +29,5 @@ String restartDialogTitle(num runId) => 'Restart run $runId?'; /// The server's refusal, verbatim. Only a blank error gets a generic sentence /// so the prompt never claims a retry that did not happen. -String describeRetryError(Object error) => describeErrorReason( - error, - fallback: 'The server did not retry the run.', -); +String describeRetryError(Object error) => + describeErrorReason(error, fallback: 'The server did not retry the run.'); diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index ef3d7083..83cb4be6 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -12,6 +12,7 @@ import '../../attention/runtime/attention_store.dart'; import '../../attention/ui/needs_you_runs_heading.dart'; import '../domain/run_models.dart'; import '../../../shell/shell_bar.dart'; +import '../../../shell/shell_list_shortcuts.dart'; import 'run_list_row.dart'; import 'runs_controller.dart'; import 'runs_filter_options.dart'; @@ -79,7 +80,7 @@ class RunsList extends StatelessWidget { title: bar.title, subtitle: bar.subtitle, actions: bar.actions, - child: _list(context), + child: _shortcutList(context), ); } final actions = [ @@ -110,11 +111,26 @@ class RunsList extends StatelessWidget { child: ShellBadge( kind: ShellBadgeKind.running, count: controller.runs.where((run) => run['executing'] == true).length, - child: _list(context), + child: _shortcutList(context), ), ); } + /// The list under the shell's Ctrl+1…Ctrl+9, which open the Nth run shown + /// (filtered and sorted as on screen). Select mode keeps keys for itself. + Widget _shortcutList(BuildContext context) => ShellListShortcut( + onOpenIndex: (index) { + if (controller.selection.active) return false; + final runs = controller.visibleRuns; + if (index >= runs.length) return false; + final id = runs[index]['id']; + if (id is! num) return false; + onSelected(id); + return true; + }, + child: _list(context), + ); + Widget _ownBar(BuildContext context, List bar) => Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index d8e50210..ad473460 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -11,6 +11,7 @@ import 'destination.dart'; import 'list_detail.dart'; import 'list_pane_widths.dart'; import 'shell_bar.dart'; +import 'shell_list_shortcuts.dart'; class AdaptiveShell extends StatefulWidget { const AdaptiveShell({ @@ -232,7 +233,15 @@ class _AdaptiveShellState extends State { /// Handles this before focused text controls can insert or traverse on /// Ctrl+Tab. The handler is scoped to the shell's lifetime, not onboarding. + /// + /// Ctrl+1…Ctrl+9 open the Nth item of the open tab's list the same way, in + /// the list's on-screen order; a page (Settings) has no list. bool _handleDestinationKeyEvent(KeyEvent event) { + final listIndex = shellListShortcutIndex(event, HardwareKeyboard.instance); + if (listIndex != null) { + if (!shellTabDestinations.contains(_selected)) return false; + return _bar.lists.open(_selected, listIndex); + } if (event is! KeyDownEvent || event.logicalKey != LogicalKeyboardKey.tab || !HardwareKeyboard.instance.isControlPressed) { diff --git a/app/lib/shell/shell_bar.dart b/app/lib/shell/shell_bar.dart index 1324e64c..1e297a46 100644 --- a/app/lib/shell/shell_bar.dart +++ b/app/lib/shell/shell_bar.dart @@ -1,6 +1,7 @@ import 'package:flutter/widgets.dart'; import 'destination.dart'; +import 'shell_list_shortcuts.dart'; /// What the open screen of a tab puts in the app bar: its title, a Back /// control and its actions. Absent, the bar shows the tab's own name. @@ -65,6 +66,9 @@ class ShellBarRegistry extends ChangeNotifier { final _Notifier _bar = _Notifier(); final _Notifier _badgeNotifier = _Notifier(); + /// How each tab's list opens its Nth item (Ctrl+1…Ctrl+9). + final ShellListShortcuts lists = ShellListShortcuts(); + /// The destination whose bar is on screen; null treats every destination /// as shown. Bar changes of other destinations are kept without notifying: /// the host rebuilds when it changes the focus. diff --git a/app/lib/shell/shell_list_shortcuts.dart b/app/lib/shell/shell_list_shortcuts.dart new file mode 100644 index 00000000..680f29c5 --- /dev/null +++ b/app/lib/shell/shell_list_shortcuts.dart @@ -0,0 +1,98 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import 'destination.dart'; +import 'shell_bar.dart'; + +/// Opens the Nth item of a tab's list: what each tab's list screen published +/// for Ctrl+1…Ctrl+9. One opener per tab; the latest mounted list wins. +class ShellListShortcuts { + final Map _openers = {}; + + /// Opens the item at [index] (0-based, on-screen order) of [destination]'s + /// list; false when the tab publishes no list or has no such item. + bool open(AppDestination destination, int index) => + _openers[destination]?.$2(index) ?? false; + + void _set( + AppDestination destination, + Object owner, + bool Function(int) open, + ) => _openers[destination] = (owner, open); + + void _clear(AppDestination destination, Object owner) { + if (_openers[destination]?.$1 == owner) _openers.remove(destination); + } +} + +/// The 0-based list index a Ctrl+1…Ctrl+9 key event names, or null for any +/// other event. Shift, Alt and Meta must be up, so system and browser chords +/// built on the digits are left alone. +int? shellListShortcutIndex(KeyEvent event, HardwareKeyboard keyboard) { + if (event is! KeyDownEvent || + !keyboard.isControlPressed || + keyboard.isShiftPressed || + keyboard.isAltPressed || + keyboard.isMetaPressed) { + return null; + } + final index = _digits.indexOf(event.logicalKey); + return index < 0 ? null : index; +} + +const _digits = [ + LogicalKeyboardKey.digit1, + LogicalKeyboardKey.digit2, + LogicalKeyboardKey.digit3, + LogicalKeyboardKey.digit4, + LogicalKeyboardKey.digit5, + LogicalKeyboardKey.digit6, + LogicalKeyboardKey.digit7, + LogicalKeyboardKey.digit8, + LogicalKeyboardKey.digit9, +]; + +/// Publishes, while mounted, how its tab's list opens its Nth item, so the +/// shell's Ctrl+1…Ctrl+9 open it from anywhere in the tab (also while a text +/// field has focus). [onOpenIndex] reads the list at key time, in on-screen +/// order, and reports whether an item was opened. Outside a shell it does +/// nothing. +class ShellListShortcut extends StatefulWidget { + const ShellListShortcut({ + super.key, + required this.onOpenIndex, + required this.child, + }); + + final bool Function(int index) onOpenIndex; + final Widget child; + + @override + State createState() => _ShellListShortcutState(); +} + +class _ShellListShortcutState extends State { + final Object _owner = Object(); + ShellBarScope? _scope; + + bool _open(int index) => mounted && widget.onOpenIndex(index); + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final scope = ShellBarScope.maybeOf(context); + if (scope == _scope) return; + _scope?.registry.lists._clear(_scope!.destination, _owner); + _scope = scope; + scope?.registry.lists._set(scope.destination, _owner, _open); + } + + @override + void dispose() { + _scope?.registry.lists._clear(_scope!.destination, _owner); + super.dispose(); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/app/lib/ui/layout/app_list_row.dart b/app/lib/ui/layout/app_list_row.dart index e9f9d026..1579d11d 100644 --- a/app/lib/ui/layout/app_list_row.dart +++ b/app/lib/ui/layout/app_list_row.dart @@ -16,6 +16,11 @@ const double _avatarGap = 12; /// Keys on a row's highlight surface and inset divider, for tests. const appListRowSurfaceKey = ValueKey('app-list-row-surface'); const appListRowDividerKey = ValueKey('app-list-row-divider'); +const appListRowAccentKey = ValueKey('app-list-row-accent'); + +bool _darkSurface(BuildContext context, bool cupertino) => cupertino + ? CupertinoTheme.brightnessOf(context) == Brightness.dark + : Theme.of(context).brightness == Brightness.dark; /// The app's one list row (runs, pipelines, chats, search results, /// schedules), on both hosts. @@ -55,8 +60,14 @@ class AppListRow extends StatelessWidget { this.keepMenuWhenCompact = false, this.compactWidth = kAppListRowCompactWidth, this.cupertino, + this.accent, }); + /// The item's own colour (a chat's highlight): a bar on the row's leading + /// edge and a faint tint under an unselected row. The selected fill still + /// marks the open row, so the two never read as one another. + final Color? accent; + final Widget title; final Widget? leading; final String? time; @@ -143,19 +154,23 @@ class AppListRow extends StatelessWidget { ], ), ); + final tint = accent?.withValues( + alpha: _darkSurface(context, cupertino) ? 0.12 : 0.07, + ); final surface = cupertino ? _CupertinoRowSurface( tapKey: tapKey, onTap: onTap, onLongPress: onLongPress, selected: selected, + tint: tint, child: content, ) : Material( key: appListRowSurfaceKey, color: selected ? selectedColor(context, cupertino: false) - : Colors.transparent, + : tint ?? Colors.transparent, child: InkWell( key: tapKey, onTap: onTap, @@ -163,28 +178,49 @@ class AppListRow extends StatelessWidget { child: content, ), ); - if (!divider) return surface; + // The colour bar runs the row's whole height, divider included, and + // the tint fills the divider's inset too, so coloured rows read as + // one band each. + Widget marked(Widget row) => accent == null + ? row + : DecoratedBox( + key: appListRowAccentKey, + position: DecorationPosition.foreground, + decoration: BoxDecoration( + border: BorderDirectional( + start: BorderSide(color: accent!, width: 4), + ), + ), + child: row, + ); + if (!divider) return marked(surface); // The divider stays under the text column; a checkbox's width is // not known here, so a selectable row's divider starts at the inset. final textStart = selectionControl != null ? start : start + (showLeading ? kAppListAvatarSize + _avatarGap : 0); - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - surface, - Padding( - padding: EdgeInsetsDirectional.only(start: textStart), - child: SizedBox( - key: appListRowDividerKey, - height: cupertino - ? 1 / MediaQuery.devicePixelRatioOf(context) - : 1, - child: ColoredBox(color: styles.divider), - ), - ), - ], + final line = Padding( + padding: EdgeInsetsDirectional.only(start: textStart), + child: SizedBox( + key: appListRowDividerKey, + height: cupertino + ? 1 / MediaQuery.devicePixelRatioOf(context) + : 1, + child: ColoredBox(color: styles.divider), + ), + ); + return marked( + Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + surface, + if (tint != null && !selected) + ColoredBox(color: tint, child: line) + else + line, + ], + ), ); }, ), @@ -324,9 +360,13 @@ class _CupertinoRowSurface extends StatefulWidget { required this.onTap, required this.selected, this.onLongPress, + this.tint, required this.child, }); + /// The unselected row's tint, transparent when null. + final Color? tint; + final Key? tapKey; final VoidCallback? onTap; final VoidCallback? onLongPress; @@ -350,7 +390,7 @@ class _CupertinoRowSurfaceState extends State<_CupertinoRowSurface> { ? CupertinoColors.systemGrey4.resolveFrom(context) : widget.selected ? AppListRow.selectedColor(context, cupertino: true) - : const Color(0x00000000); + : widget.tint ?? const Color(0x00000000); final enabled = widget.onTap != null; return GestureDetector( key: widget.tapKey, diff --git a/app/lib/ui/layout/collapsible_list_section.dart b/app/lib/ui/layout/collapsible_list_section.dart index 976ec477..184162ba 100644 --- a/app/lib/ui/layout/collapsible_list_section.dart +++ b/app/lib/ui/layout/collapsible_list_section.dart @@ -22,11 +22,15 @@ class SliverCollapsibleListSection extends StatefulWidget { this.itemKey, this.count, this.initiallyOpen = true, + this.onOpenChanged, }); final String title; final int? count; final bool initiallyOpen; + + /// Reports the operator opening or folding the section. + final ValueChanged? onOpenChanged; final int itemCount; final IndexedWidgetBuilder itemBuilder; @@ -131,5 +135,8 @@ class _SliverCollapsibleListSectionState ); } - void _toggle() => setState(() => _open = !_open); + void _toggle() { + setState(() => _open = !_open); + widget.onOpenChanged?.call(_open); + } } diff --git a/app/test/features/attention/notify/chat_question_notices_test.dart b/app/test/features/attention/notify/chat_question_notices_test.dart index 6b0b1b87..6392980c 100644 --- a/app/test/features/attention/notify/chat_question_notices_test.dart +++ b/app/test/features/attention/notify/chat_question_notices_test.dart @@ -65,37 +65,43 @@ void main() { await gateway.controller.close(); }); - test('notifies titled and unknown sessions; tap opens the chat route', () async { - gateway.controller.add(_event()); - await Future.delayed(Duration.zero); - gateway.controller.add(_event(id: 'form-2', session: 'unknown')); - await Future.delayed(Duration.zero); + test( + 'notifies titled and unknown sessions; tap opens the chat route', + () async { + gateway.controller.add(_event()); + await Future.delayed(Duration.zero); + gateway.controller.add(_event(id: 'form-2', session: 'unknown')); + await Future.delayed(Duration.zero); - expect(bridge.shown.map((message) => message.title), [ - 'Design chat needs your answer', - 'Chat needs your answer', - ]); - expect(bridge.shown.first.body, 'Choose an option'); - expect(bridge.shown.first.tag, 'chat-question:form-1'); - bridge.taps.first?.call(); - expect(opened, [AppRoute.chatSession('session_1')]); - }); + expect(bridge.shown.map((message) => message.title), [ + 'Design chat needs your answer', + 'Chat needs your answer', + ]); + expect(bridge.shown.first.body, 'Choose an option'); + expect(bridge.shown.first.tag, 'chat-question:form-1'); + bridge.taps.first?.call(); + expect(opened, [AppRoute.chatSession('session_1')]); + }, + ); - test('suppresses active, unavailable, resolved, cancelled and non-question frames', () async { - active = 'session_1'; - gateway.controller.add(_event()); - await Future.delayed(Duration.zero); - active = null; - allowed = false; - gateway.controller.add(_event(id: 'form-2')); - await Future.delayed(Duration.zero); - allowed = true; - gateway.controller.add(_event(id: 'form-3', resolved: true)); - await Future.delayed(Duration.zero); - gateway.controller.add(_event(id: 'form-4', cancelled: true)); - await Future.delayed(Duration.zero); - gateway.controller.add(_event(id: 'form-5', kind: 'approval')); - await Future.delayed(Duration.zero); - expect(bridge.shown, isEmpty); - }); + test( + 'suppresses active, unavailable, resolved, cancelled and non-question frames', + () async { + active = 'session_1'; + gateway.controller.add(_event()); + await Future.delayed(Duration.zero); + active = null; + allowed = false; + gateway.controller.add(_event(id: 'form-2')); + await Future.delayed(Duration.zero); + allowed = true; + gateway.controller.add(_event(id: 'form-3', resolved: true)); + await Future.delayed(Duration.zero); + gateway.controller.add(_event(id: 'form-4', cancelled: true)); + await Future.delayed(Duration.zero); + gateway.controller.add(_event(id: 'form-5', kind: 'approval')); + await Future.delayed(Duration.zero); + expect(bridge.shown, isEmpty); + }, + ); } diff --git a/app/test/features/chat/chat_list_shortcuts_test.dart b/app/test/features/chat/chat_list_shortcuts_test.dart new file mode 100644 index 00000000..1d11ff10 --- /dev/null +++ b/app/test/features/chat/chat_list_shortcuts_test.dart @@ -0,0 +1,189 @@ +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/chat/screen.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'; + +/// Recency order puts the plain chat first; the starred ones lead the list +/// alphabetically all the same. +class _Gateway extends FakeChatGateway { + final rows = [ + {'id': 'r', 'title': 'Recent', 'directory': '/w'}, + {'id': 'z', 'title': 'Zed', 'directory': '/w', 'starred': true}, + { + 'id': 'a', + 'title': 'apple', + 'directory': '/w', + 'starred': true, + 'color': 'green', + }, + ]; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final row in rows) {...row}, + ], + }); + } + if (type == 'chat_color') { + final query = fields['chat_query'] as JsonMap; + final row = rows.firstWhere((r) => r['id'] == query['session_id']); + row['color'] = query['color']; + calls.add((type: type, fields: fields)); + return Future.value({'chat_session': row}); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +Future<_Gateway> _pumpShell( + WidgetTester tester, + Size size, { + TargetPlatform platform = TargetPlatform.android, + Brightness brightness = Brightness.light, +}) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage(const []); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: platform, brightness: brightness), + home: AdaptiveShell( + cupertino: platform == TargetPlatform.iOS, + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => ChatScreen(gateway: gateway), + }, + ), + ), + ); + await tester.pumpAndSettle(); + return gateway; +} + +Future _ctrl(WidgetTester tester, LogicalKeyboardKey digit) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(digit); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); +} + +Finder _thread(String id) => find.byKey(ValueKey('chat-thread-$id')); + +void main() { + testWidgets('starred chats lead the list alphabetically', (tester) async { + await _pumpShell(tester, const Size(1280, 800)); + final apple = tester.getTopLeft(find.byKey(const Key('chat-row-a'))).dy; + final zed = tester.getTopLeft(find.byKey(const Key('chat-row-z'))).dy; + final recent = tester.getTopLeft(find.byKey(const Key('chat-row-r'))).dy; + expect(apple, lessThan(zed)); + expect(zed, lessThan(recent)); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Ctrl+N opens the Nth chat shown, also from the composer', ( + tester, + ) async { + await _pumpShell(tester, const Size(1280, 800)); + await _ctrl(tester, LogicalKeyboardKey.digit1); + expect(_thread('a'), findsOneWidget, reason: 'Starred apple is first'); + await _ctrl(tester, LogicalKeyboardKey.digit3); + expect(_thread('r'), findsOneWidget); + + // Typing in the composer: the chord still switches chats and types + // nothing. + final field = find.descendant( + of: find.byKey(const ValueKey('chat-composer-r')), + matching: find.byType(EditableText), + ); + await tester.tap(field); + await tester.enterText(field, 'draft'); + await tester.pump(); + expect(tester.widget(field).focusNode.hasFocus, isTrue); + await _ctrl(tester, LogicalKeyboardKey.digit2); + expect(_thread('z'), findsOneWidget); + expect(_thread('r'), findsNothing); + + // Past the end nothing changes. + await _ctrl(tester, LogicalKeyboardKey.digit9); + expect(_thread('z'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Ctrl+N opens the chat as its own page on a phone', ( + tester, + ) async { + await _pumpShell(tester, const Size(390, 844)); + await _ctrl(tester, LogicalKeyboardKey.digit2); + expect(_thread('z'), findsOneWidget); + final navigator = tester.state( + find.byType(Navigator).first, + ); + expect(navigator.canPop(), isTrue); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + for (final platform in [TargetPlatform.android, TargetPlatform.iOS]) { + for (final brightness in Brightness.values) { + final host = + '${platform == TargetPlatform.iOS ? 'Cupertino' : 'Material'} ' + '${brightness.name}'; + testWidgets('$host: a coloured chat washes its top; the info sheet ' + 'changes the colour', (tester) async { + final gateway = await _pumpShell( + tester, + const Size(1280, 800), + platform: platform, + brightness: brightness, + ); + await _ctrl(tester, LogicalKeyboardKey.digit1); + expect(_thread('a'), findsOneWidget); + expect(find.byKey(const Key('chat-color-wash')), findsOneWidget); + final washRect = tester.getRect( + find.byKey(const Key('chat-color-wash')), + ); + final pane = tester.getRect( + find.byKey(const ValueKey('chat-detail-pane')), + ); + expect(washRect.top, pane.top); + expect(washRect.height, lessThan(pane.height / 4)); + final box = tester.widget( + find.byKey(const Key('chat-color-wash')), + ); + final gradient = + (box.decoration as BoxDecoration).gradient! as LinearGradient; + expect(gradient.colors.first.a, lessThanOrEqualTo(0.25)); + expect(gradient.colors.last.a, 0); + + // A plain chat has none. + await _ctrl(tester, LogicalKeyboardKey.digit3); + expect(find.byKey(const Key('chat-color-wash')), findsNothing); + + await tester.tap(find.byKey(const Key('chat-info'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-color-section')), findsOneWidget); + await tester.tap(find.byKey(const Key('chat-color-blue'))); + await tester.pumpAndSettle(); + expect(gateway.calls.last.fields, { + 'chat_query': {'session_id': 'r', 'color': 'blue'}, + }); + await tester.tap(find.byKey(const Key('chat-info-close'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-color-wash')), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); + } + } +} diff --git a/app/test/features/chat/domain/chat_session_sections_test.dart b/app/test/features/chat/domain/chat_session_sections_test.dart new file mode 100644 index 00000000..59d98c68 --- /dev/null +++ b/app/test/features/chat/domain/chat_session_sections_test.dart @@ -0,0 +1,72 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/domain/chat_colors.dart'; +import 'package:pipelines_app/features/chat/domain/chat_sessions.dart'; + +List _ids(Iterable rows) => [ + for (final row in rows) '${row['id']}', +]; + +void main() { + // Server recency order: the newest first. + final rows = [ + {'id': 'c1', 'title': 'zeta', 'directory': '/b', 'starred': true}, + {'id': 'c2', 'title': 'Recent', 'directory': '/a'}, + {'id': 'c3', 'title': 'Alpha', 'directory': '/b', 'starred': true}, + {'id': 'c4', 'title': 'Older', 'directory': '/b'}, + {'id': 'c6', 'title': 'beta', 'directory': '/a', 'starred': true}, + {'id': 'c5', 'title': 'Beta', 'directory': '/c', 'starred': true}, + {'id': 'c7', 'title': 'Oldest', 'directory': '/a'}, + {'id': 'c8', 'title': 'Done', 'closed_at': 1, 'starred': true}, + ]; + + test('starred chats are alphabetical, ignoring case, ties by id', () { + final sections = chatSessionSections(rows); + expect(sections.map((s) => s.title), ['Starred', 'Chats', 'Closed']); + expect(_ids(sections[0].sessions), ['c3', 'c5', 'c6', 'c1']); + // The other sections keep the server's recency order. + expect(_ids(sections[1].sessions), ['c2', 'c4', 'c7']); + expect(_ids(sections[2].sessions), ['c8']); + }); + + test('a starred chat keeps its place when another is used', () { + final used = [rows[2], ...rows.where((r) => r['id'] != 'c3')]; + expect( + _ids(chatSessionSections(used).first.sessions), + _ids(chatSessionSections(rows).first.sessions), + ); + }); + + test( + 'list order: starred whole, then chats by directory, folded skipped', + () { + final sections = chatSessionSections(rows); + expect( + _ids(chatSessionsInListOrder(sections, isOpen: (t) => t != 'Closed')), + ['c3', 'c5', 'c6', 'c1', 'c2', 'c7', 'c4'], + ); + expect(_ids(chatSessionsInListOrder(sections, isOpen: (_) => true)), [ + 'c3', + 'c5', + 'c6', + 'c1', + 'c2', + 'c7', + 'c4', + 'c8', + ]); + expect( + _ids(chatSessionsInListOrder(sections, isOpen: (t) => t == 'Chats')), + ['c2', 'c7', 'c4'], + ); + }, + ); + + test('only palette names are colours', () { + expect(chatSessionColor({'color': 'teal'}), 'teal'); + expect(chatSessionColor({'color': '#ff0000'}), isNull); + expect(chatSessionColor({}), isNull); + expect(chatSessionColor(null), isNull); + expect(chatColorNames, hasLength(8)); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_color_test.dart b/app/test/features/chat/ui/sessions/chat_color_test.dart new file mode 100644 index 00000000..812ba330 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_color_test.dart @@ -0,0 +1,269 @@ +import 'package:flutter/cupertino.dart'; +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/data/chat_repository.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_row_content.dart'; +import 'package:pipelines_app/ui/layout/app_list_avatar.dart'; +import 'package:pipelines_app/ui/layout/app_list_row.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +/// A server whose list keeps each accepted colour, as the registry does. +FakeChatGateway _gateway() { + final rows = [ + {'id': 's1', 'title': 'Teal chat', 'directory': '/w', 'color': 'teal'}, + {'id': 's2', 'title': 'Plain chat', 'directory': '/w'}, + ]; + final gateway = FakeChatGateway(); + gateway.sessionsHandler = () async => { + 'chat_sessions': [ + for (final row in rows) {...row}, + ], + }; + gateway.actionHandler = (type, fields) async { + if (type != 'chat_color') return const {}; + final query = fields['chat_query'] as JsonMap; + final row = rows.firstWhere((r) => r['id'] == query['session_id']); + final color = query['color']; + color == null ? row.remove('color') : row['color'] = color; + return {'chat_session': row}; + }; + return gateway; +} + +Future _pump( + WidgetTester tester, + FakeChatGateway gateway, { + required bool cupertino, + required Brightness brightness, +}) async { + final screen = ChatSessionsScreen( + gateway: gateway, + onOpen: (_) {}, + localStore: MemoryChatSessionLocalStore(), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + theme: CupertinoThemeData(brightness: brightness), + home: MediaQuery( + data: MediaQueryData(platformBrightness: brightness), + child: screen, + ), + ) + : MaterialApp( + theme: ThemeData( + platform: TargetPlatform.android, + brightness: brightness, + ), + home: screen, + ), + ); + await tester.pumpAndSettle(); +} + +Finder _accent(String id) => find.descendant( + of: find.byKey(Key('chat-row-$id')), + matching: find.byKey(appListRowAccentKey), +); + +Color _accentColor(WidgetTester tester, String id) { + final box = tester.widget(_accent(id)); + final border = (box.decoration as BoxDecoration).border as BorderDirectional; + return border.start.color; +} + +void main() { + for (final cupertino in [false, true]) { + for (final brightness in Brightness.values) { + final host = '${cupertino ? 'Cupertino' : 'Material'} ${brightness.name}'; + + testWidgets('$host: a coloured chat wears its colour, a plain one none', ( + tester, + ) async { + await _pump( + tester, + _gateway(), + cupertino: cupertino, + brightness: brightness, + ); + expect(_accent('s1'), findsOneWidget); + expect(_accent('s2'), findsNothing); + final accent = _accentColor(tester, 's1'); + // The avatar takes the same colour as the bar. + final avatar = tester.widget( + find.descendant( + of: find.byKey(const Key('chat-row-s1')), + matching: find.byType(AppListAvatar), + ), + ); + expect(avatar.foreground, accent); + // A teal shade, not the host's accent or a grey. + expect(accent.g, greaterThan(accent.r)); + expect(accent.b, greaterThan(accent.r)); + // The row tint is faint: the selected fill stays the stronger mark. + final tint = cupertino + ? tester + .widget( + find.descendant( + of: find.byKey(const Key('chat-row-s1')), + matching: find.byKey(appListRowSurfaceKey), + ), + ) + .color + : tester + .widget( + find.descendant( + of: find.byKey(const Key('chat-row-s1')), + matching: find.byKey(appListRowSurfaceKey), + ), + ) + .color!; + expect(tint.a, inInclusiveRange(0.05, 0.13)); + // Shades are tuned per brightness. + final shade = accent.computeLuminance(); + if (brightness == Brightness.dark) { + expect(shade, greaterThan(0.2)); + } else { + expect(shade, lessThan(0.55)); + } + }); + + testWidgets('$host: the row menu sets and clears the colour', ( + tester, + ) async { + final gateway = _gateway(); + await _pump( + tester, + gateway, + cupertino: cupertino, + brightness: brightness, + ); + await tester.tap( + find.descendant( + of: find.byKey(const Key('chat-actions-s2')), + matching: find.byType(cupertino ? CupertinoButton : IconButton), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Colour…')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-color-sheet')), findsOneWidget); + await tester.tap(find.byKey(const Key('chat-color-purple'))); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_color'), { + 'chat_query': {'session_id': 's2', 'color': 'purple'}, + }); + // The row shows it at once, before the list re-reads. + expect(_accent('s2'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-color-none'))); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_color'), { + 'chat_query': {'session_id': 's2', 'color': null}, + }); + await tester.tap(find.byKey(const Key('chat-color-done'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-color-sheet')), findsNothing); + }); + } + } + + testWidgets('a long-press on a row opens the colour choice', (tester) async { + final gateway = _gateway(); + await _pump( + tester, + gateway, + cupertino: false, + brightness: Brightness.light, + ); + await tester.longPress(find.text('Plain chat')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-color-sheet')), findsOneWidget); + await tester.tap(find.byKey(const Key('chat-color-red'))); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_color'), { + 'chat_query': {'session_id': 's2', 'color': 'red'}, + }); + }); + + testWidgets('the selected coloured row keeps its colour and selection', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold( + body: ChatSessionRow( + session: const {'id': 's1', 'title': 'T', 'color': 'amber'}, + selected: true, + onOpen: (_) {}, + onAction: (_) {}, + ), + ), + ), + ); + final surface = tester.widget(find.byKey(appListRowSurfaceKey)); + final context = tester.element(find.byType(ChatSessionRow)); + expect( + surface.color, + AppListRow.selectedColor(context, cupertino: false), + reason: 'The selected fill, not the tint, marks the open row', + ); + expect(find.byKey(appListRowAccentKey), findsOneWidget); + }); + + group('controller', () { + late FakeChatGateway gateway; + late ChatSessionsController controller; + + setUp(() async { + gateway = _gateway(); + controller = ChatSessionsController( + ChatRepository(gateway), + localStore: MemoryChatSessionLocalStore(), + ); + await controller.refresh(); + }); + tearDown(() => controller.dispose()); + + JsonMap row(String id) => + controller.sessions.firstWhere((s) => s['id'] == id); + + test('another device\'s change arrives live without a re-list', () async { + final lists = gateway.count('chat_sessions'); + gateway.pushed.add({ + 'type': 'chat_session_changed', + 'chat_session': { + 'id': 's2', + 'title': 'Plain chat', + 'color': 'pink', + 'starred': true, + 'starred_at': 5, + }, + }); + await pumpEventQueue(); + expect(row('s2')['color'], 'pink'); + expect(row('s2')['starred'], isTrue); + // An omitted colour is a cleared one. + gateway.pushed.add({ + 'type': 'chat_session_changed', + 'chat_session': {'id': 's1', 'title': 'Teal chat'}, + }); + await pumpEventQueue(); + expect(row('s1').containsKey('color'), isFalse); + expect(gateway.count('chat_sessions'), lists); + }); + + test('a refused colour is undone and the reason shown', () async { + gateway.failures['chat_color'] = 'unknown chat colour'; + await controller.setColor('s2', 'blue'); + expect(row('s2')['color'], isNull); + expect(controller.errorFor('s2'), contains('unknown chat colour')); + }); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart b/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart index 4ceadd6f..f596f4f4 100644 --- a/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart +++ b/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart @@ -56,9 +56,7 @@ void main() { findsOneWidget, ); expect( - find.text( - "New chats start with the server's default model.", - ), + find.text("New chats start with the server's default model."), findsOneWidget, ); expect(find.text('Start in ~'), findsOneWidget); diff --git a/app/test/features/chat/ui/sessions/chat_session_dialog_layout_test.dart b/app/test/features/chat/ui/sessions/chat_session_dialog_layout_test.dart index 5926d093..63451946 100644 --- a/app/test/features/chat/ui/sessions/chat_session_dialog_layout_test.dart +++ b/app/test/features/chat/ui/sessions/chat_session_dialog_layout_test.dart @@ -68,10 +68,14 @@ void main() { await tester.tap(find.byKey(const Key('chat-new-chat'))); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); - await tester.ensureVisible(find.byKey(const Key('chat-create-send-prompt'))); + await tester.ensureVisible( + find.byKey(const Key('chat-create-send-prompt')), + ); await tester.tap(find.byKey(const Key('chat-create-send-prompt'))); await tester.pumpAndSettle(); - await tester.ensureVisible(find.byKey(const Key('chat-create-server-directory'))); + await tester.ensureVisible( + find.byKey(const Key('chat-create-server-directory')), + ); await tester.tap(find.byKey(const Key('chat-create-server-directory'))); await tester.pumpAndSettle(); diff --git a/app/test/shell/list_shortcuts_test.dart b/app/test/shell/list_shortcuts_test.dart new file mode 100644 index 00000000..e2f6072f --- /dev/null +++ b/app/test/shell/list_shortcuts_test.dart @@ -0,0 +1,70 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/shell_list_shortcuts.dart'; + +void main() { + testWidgets('Ctrl+1…9 reach only the open tab\'s list; other chords pass', ( + tester, + ) async { + final opened = <(AppDestination, int)>[]; + final field = FocusNode(); + addTearDown(field.dispose); + Widget list(AppDestination destination) => ShellListShortcut( + onOpenIndex: (index) { + if (index > 4) return false; + opened.add((destination, index)); + return true; + }, + child: TextField(focusNode: field), + ); + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.runs, + destinationBodies: { + AppDestination.runs: (_) => list(AppDestination.runs), + AppDestination.pipelines: (_) => list(AppDestination.pipelines), + }, + ), + ), + ); + await tester.pumpAndSettle(); + field.requestFocus(); + await tester.pump(); + + Future press( + LogicalKeyboardKey key, { + List held = const [LogicalKeyboardKey.controlLeft], + }) async { + for (final modifier in held) { + await tester.sendKeyDownEvent(modifier); + } + await tester.sendKeyEvent(key); + for (final modifier in held.reversed) { + await tester.sendKeyUpEvent(modifier); + } + await tester.pump(); + } + + await press(LogicalKeyboardKey.digit1); + await press(LogicalKeyboardKey.digit5); + expect(opened, [(AppDestination.runs, 0), (AppDestination.runs, 4)]); + + opened.clear(); + await press( + LogicalKeyboardKey.digit2, + held: [LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.shiftLeft], + ); + await press( + LogicalKeyboardKey.digit2, + held: [LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.metaLeft], + ); + await press(LogicalKeyboardKey.digit2, held: const []); + await press(LogicalKeyboardKey.digit0); + expect(opened, isEmpty); + expect(field.hasFocus, isTrue); + }); +} diff --git a/app/test/ui/text/relative_time_label_test.dart b/app/test/ui/text/relative_time_label_test.dart index f3071240..75b84afa 100644 --- a/app/test/ui/text/relative_time_label_test.dart +++ b/app/test/ui/text/relative_time_label_test.dart @@ -81,7 +81,10 @@ void main() { addTearDown(() => debugOnRebuildDirtyWidget = null); await tester.pump(const Duration(minutes: 1)); expect(labelBuilds, 0); - expect(find.descendant(of: label, matching: find.text('4m')), findsOneWidget); + expect( + find.descendant(of: label, matching: find.text('4m')), + findsOneWidget, + ); await tester.pumpWidget(app(true)); expect(find.text('5m'), findsOneWidget); diff --git a/app/tool/chat_approvals_probe.dart b/app/tool/chat_approvals_probe.dart index fdf5d34b..27e2d398 100644 --- a/app/tool/chat_approvals_probe.dart +++ b/app/tool/chat_approvals_probe.dart @@ -98,10 +98,7 @@ class _ApprovalsGateway implements ApiGateway { 'session_id': 'probe-session', 'request_id': 'probe-permission', 'action': 'bash', - 'resources': [ - 'command: rm -rf build', - 'cwd: /workspace/demo', - ], + 'resources': ['command: rm -rf build', 'cwd: /workspace/demo'], 'message': 'This deletes the build output.', 'source': {'type': 'tool'}, }; diff --git a/app/tool/perf/perf_fixture.dart b/app/tool/perf/perf_fixture.dart index 9d8713e7..685023e0 100644 --- a/app/tool/perf/perf_fixture.dart +++ b/app/tool/perf/perf_fixture.dart @@ -8,6 +8,8 @@ // `?graph=1` run 7 carries its pinned graph (plan -> build); // `?quota=claude|opencode` (with `?chats=N`) pushes a usage frame with // that harness's account quota after a chat subscribes. +// `?colors=1` (with `?chats=N`) names the chats, stars and colours some of +// them, and keeps colours picked with chat_color; // `?msgs=`, `?rich=1`, `?older=1`, `?live=N` vary the chat transcripts for // scroll captures (tool/perf/chat_scroll_fixture.dart). import 'package:pipelines_app/core/api_gateway.dart'; @@ -25,6 +27,50 @@ void configurePerfFixture(Map params) { int get _hits => int.tryParse(_params['hits'] ?? '') ?? 0; int get _chats => int.tryParse(_params['chats'] ?? '') ?? 0; bool get perfRunGraph => _params['graph'] == '1'; +bool get _colors => _params['colors'] == '1'; + +/// `?colors=1`: titles, directories, stars and colours per chat index. +const _colorTitles = [ + 'Release notes', + 'api refactor', + 'Billing bug', + 'Docs pass', + 'Flaky test', + 'Onboarding', + 'Perf sweep', + 'Search UX', +]; +const _colorStarred = {0, 1, 3}; +const _colorNames = ['teal', 'purple', null, 'amber', 'red', null, 'blue']; +final Map _pickedColors = {}; + +JsonMap _chatRow(int i) { + final id = 'perf-chat-$i'; + if (!_colors) { + return { + 'id': id, + 'title': 'Fixture chat ${i + 1}', + 'directory': '/workspace/demo', + // Server-shaped handoff facts (chat_sessions rows carry them). + if (_harness != 'opencode') 'backend': _harness, + 'resume_command': _resumeCommand(id), + 'native_export': _harness == 'claude', + }; + } + final color = _pickedColors.containsKey(id) + ? _pickedColors[id] + : _colorNames[i % _colorNames.length]; + return { + 'id': id, + 'title': _colorTitles[i % _colorTitles.length], + 'directory': i.isEven ? '/workspace/demo' : '/workspace/site', + 'model': 'claude-opus', + 'backend': 'claude', + 'updated_at': DateTime.now().millisecondsSinceEpoch - (i + 1) * 600000, + if (_colorStarred.contains(i)) 'starred': true, + 'color': ?color, + }; +} /// `?harness=claude|codex` makes the chats that harness's (default OpenCode), /// with the resume command the server would send for it. @@ -146,18 +192,20 @@ JsonMap? perfChatReply(JsonMap request) { return { 'id': id, 'type': 'chat_sessions', - 'chat_sessions': [ - for (var i = 0; i < _chats; i++) - { - 'id': 'perf-chat-$i', - 'title': 'Fixture chat ${i + 1}', - 'directory': '/workspace/demo', - // Server-shaped handoff facts (chat_sessions rows carry them). - if (_harness != 'opencode') 'backend': _harness, - 'resume_command': _resumeCommand('perf-chat-$i'), - 'native_export': _harness == 'claude', - }, - ], + 'chat_sessions': [for (var i = 0; i < _chats; i++) _chatRow(i)], + }; + case 'chat_color': + final query = request['chat_query']; + final session = query is Map ? '${query['session_id'] ?? ''}' : ''; + final color = query is Map ? query['color'] as String? : null; + _pickedColors[session] = color; + final index = int.tryParse(session.replaceFirst('perf-chat-', '')) ?? 0; + final row = _chatRow(index); + return { + 'id': id, + 'type': 'chat_color', + 'chat_session': row, + 'chat_sessions': [row], }; case 'chat_export': final body = request['chat_export']; diff --git a/internal/pipeline/operator_sessions.go b/internal/pipeline/operator_sessions.go index a1a0e49c..83beecc0 100644 --- a/internal/pipeline/operator_sessions.go +++ b/internal/pipeline/operator_sessions.go @@ -37,6 +37,10 @@ type OperatorSession struct { // or 0 while unstarred. It lives on the server so the starred group is shared // by every browser and device. StarredAt int64 + // Color is the operator's shared highlight for this chat: one of + // protocol.ChatColors by name, or "" for none. The name, not a shade, is + // stored so every client renders its own theme-tuned colour. + Color string } // ChatCreateBootstrap is the durable progress record for one chat_create @@ -66,6 +70,7 @@ func (s *Store) initOperatorSessions() error { session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '', tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL, closed_at INTEGER NOT NULL DEFAULT 0, starred_at INTEGER NOT NULL DEFAULT 0, +color TEXT NOT NULL DEFAULT '', backend TEXT NOT NULL DEFAULT 'opencode', ephemeral INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`) if err != nil { @@ -152,6 +157,10 @@ func (s *Store) migrateOperatorSessions() error { if err := s.addColumnIfMissing("operator_sessions", "starred_at", "INTEGER NOT NULL DEFAULT 0"); err != nil { return err } + // color records the shared highlight name. Existing sessions have none. + if err := s.addColumnIfMissing("operator_sessions", "color", "TEXT NOT NULL DEFAULT ''"); err != nil { + return err + } // backend records which harness owns the session so a restart can route a // chat without guessing from its id. Existing rows are OpenCode. if err := s.addColumnIfMissing("operator_sessions", "backend", "TEXT NOT NULL DEFAULT 'opencode'"); err != nil { @@ -310,14 +319,22 @@ func (s *Store) SetOperatorSessionStar(ctx context.Context, sessionID string, st return err } +// SetOperatorSessionColor records the shared highlight name in one UPDATE; "" +// clears it. The caller validates the name. Like the star, it never touches +// last_used_at, and a session id that is not an operator session updates no row. +func (s *Store) SetOperatorSessionColor(ctx context.Context, sessionID, color string) error { + _, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET color=? WHERE session_id=?", color, sessionID) + return err +} + // OperatorSession returns one operator session by id. found is false when the id // is not a recorded operator session (so a pipeline-owned run session is never // returned). It is one indexed lookup and never mutates the row. func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) { var session OperatorSession - row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at + row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID) - if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil { + if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color); err != nil { if errors.Is(err, sql.ErrNoRows) { return OperatorSession{}, false, nil } @@ -336,7 +353,7 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID) // operator can still see and reopen what they finished. It is one bounded // statement; recency is never mutated here. func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) { - rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at + rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit) if err != nil { return nil, err @@ -345,7 +362,7 @@ FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at D sessions := []OperatorSession{} for rows.Next() { var session OperatorSession - if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil { + if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color); err != nil { return nil, err } sessions = append(sessions, session) diff --git a/internal/pipeline/operator_sessions_color_test.go b/internal/pipeline/operator_sessions_color_test.go new file mode 100644 index 00000000..e84cb73d --- /dev/null +++ b/internal/pipeline/operator_sessions_color_test.go @@ -0,0 +1,56 @@ +package pipeline + +import ( + "context" + "path/filepath" + "testing" +) + +// TestOperatorSessionColorPersistsAcrossReopen proves the shared colour is a +// durable registry field: it survives closing and reopening the database, is +// listed, does not reorder recency, and clears back to none. +func TestOperatorSessionColorPersistsAcrossReopen(t *testing.T) { + ctx := context.Background() + path := filepath.Join(t.TempDir(), "color.db") + store, err := Open(path) + if err != nil { + t.Fatal(err) + } + if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "A", "operator"); err != nil { + t.Fatal(err) + } + before, _, err := store.OperatorSession(ctx, "ses_a") + if err != nil { + t.Fatal(err) + } + if before.Color != "" { + t.Fatalf("a new chat has colour %q", before.Color) + } + if err := store.SetOperatorSessionColor(ctx, "ses_a", "purple"); err != nil { + t.Fatal(err) + } + store.Close() + + store, err = Open(path) + if err != nil { + t.Fatal(err) + } + defer store.Close() + listed, err := store.OperatorSessions(ctx) + if err != nil { + t.Fatal(err) + } + if len(listed) != 1 || listed[0].Color != "purple" { + t.Fatalf("listed = %+v", listed) + } + if listed[0].UpdatedAt != before.UpdatedAt { + t.Fatalf("colouring changed recency: %d -> %d", before.UpdatedAt, listed[0].UpdatedAt) + } + if err := store.SetOperatorSessionColor(ctx, "ses_a", ""); err != nil { + t.Fatal(err) + } + cleared, _, err := store.OperatorSession(ctx, "ses_a") + if err != nil || cleared.Color != "" { + t.Fatalf("cleared = %+v err=%v", cleared, err) + } +} diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index 5dfefb30..3ea827ab 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -68,6 +68,14 @@ const ( // device shows the same starred group. It takes a ChatQuery with SessionID // and Starred, and echoes the updated session like close/reopen. ChatStar = "chat_star" + // ChatColor records the operator's shared highlight colour for one chat. It + // takes a ChatQuery with SessionID and Color (a ChatColors name; null or "" + // clears it) and echoes the updated session like chat_star. + ChatColor = "chat_color" + // ChatSessionChanged is pushed to every other open connection when a chat's + // shared list metadata (colour, star, title) changes, carrying the updated + // registry row in ChatSession, so each device's list updates live. + ChatSessionChanged = "chat_session_changed" // ChatSubscribe attaches a connection to one session's shared live stream so // it receives every frame any client's turn produces (its own and the other // devices'), not only the frames of a turn it prompted itself. Any number of @@ -295,6 +303,9 @@ type ChatSession struct { // NativeExport says chat_export with format "native" can return the // harness's own session file (today: Claude Code's JSONL transcript). NativeExport bool `json:"native_export,omitempty"` + // Color is the operator's shared highlight, a ChatColors name; omitted when + // none is set. Clients map the name to their own theme-tuned shade. + Color string `json:"color,omitempty"` } // Chat export formats accepted by chat_export. @@ -323,6 +334,19 @@ type ChatExportFile struct { Truncated bool `json:"truncated,omitempty"` } +// ChatColors is the fixed palette of chat highlight names, in picker order. +var ChatColors = []string{"red", "orange", "amber", "green", "teal", "blue", "purple", "pink"} + +// ValidChatColor reports whether name is one of ChatColors. +func ValidChatColor(name string) bool { + for _, color := range ChatColors { + if color == name { + return true + } + } + return false +} + // ChatCloseResult reports the outcome of a chat_close: the session id, the // epoch-millisecond time the closed state was recorded, and whether an // in-flight turn was interrupted to stop it. It is the record that a running @@ -380,7 +404,9 @@ type ChatQuery struct { SessionID string `json:"session_id"` // Starred is set by chat_star; nil means the command did not name a state. Starred *bool `json:"starred,omitempty"` - Limit int `json:"limit,omitempty"` + // Color is set by chat_color: a ChatColors name, or nil/"" to clear. + Color *string `json:"color,omitempty"` + Limit int `json:"limit,omitempty"` // Cursor is the opaque continuation returned by OpenCode's descending // message listing. It is deliberately not interpreted by the broker. Cursor string `json:"cursor,omitempty"` diff --git a/internal/server/chat.go b/internal/server/chat.go index efbada1f..fa11989b 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -127,6 +127,7 @@ type operatorRegistry interface { CloseOperatorSession(ctx context.Context, sessionID string) error ReopenOperatorSession(ctx context.Context, sessionID string) error SetOperatorSessionStar(ctx context.Context, sessionID string, starred bool) error + SetOperatorSessionColor(ctx context.Context, sessionID, color string) error SetOperatorSessionTitle(ctx context.Context, sessionID, title string) error SetOperatorSessionBackend(ctx context.Context, sessionID, backend string) error } @@ -201,10 +202,13 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker handleChatReopen(ctx, request, registry, write) return true case protocol.ChatStar: - handleChatStar(ctx, request, registry, write) + handleChatStar(ctx, request, registry, hub.changes(), clientID, write) + return true + case protocol.ChatColor: + handleChatColor(ctx, request, registry, hub.changes(), clientID, write) return true case protocol.ChatRename: - handleChatRename(ctx, request, registry, write) + handleChatRename(ctx, request, registry, hub.changes(), clientID, write) return true case protocol.ChatExport: handleChatExport(ctx, request, broker, registry, write) diff --git a/internal/server/chat_close.go b/internal/server/chat_close.go index 76d0211a..e15695b3 100644 --- a/internal/server/chat_close.go +++ b/internal/server/chat_close.go @@ -148,5 +148,6 @@ func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSess out.Starred = true out.StarredAt = session.StarredAt } + out.Color = session.Color return withChatHandoff(out) } diff --git a/internal/server/chat_color.go b/internal/server/chat_color.go new file mode 100644 index 00000000..c14100e0 --- /dev/null +++ b/internal/server/chat_color.go @@ -0,0 +1,50 @@ +package server + +import ( + "context" + "strings" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// handleChatColor records the operator's shared highlight colour for one +// operator chat. The colour is a palette name (protocol.ChatColors), never a +// shade, so every client renders its own theme-tuned colour; null or "" clears +// it. An unknown name or a session that is not an operator chat is refused +// before anything is written. The reply echoes the updated session and every +// other connection receives it as chat_session_changed. +func handleChatColor(ctx context.Context, request protocol.Message, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { + if registry == nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"}) + return + } + query := request.ChatQuery + if query == nil || !validChatSessionID(query.SessionID) { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"}) + return + } + color := "" + if query.Color != nil { + color = *query.Color + } + if color != "" && !protocol.ValidChatColor(color) { + if len(color) > 40 { + color = color[:40] + "…" + } + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "unknown chat colour \"" + color + "\"; choose one of " + strings.Join(protocol.ChatColors, ", ") + " or none"}) + return + } + sessionID := query.SessionID + if _, found, err := registry.OperatorSession(ctx, sessionID); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } else if !found { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is not an operator chat session"}) + return + } + if err := registry.SetOperatorSessionColor(ctx, sessionID, color); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + echoOperatorSession(ctx, request, sessionID, protocol.ChatColor, registry, changes, clientID, write) +} diff --git a/internal/server/chat_color_test.go b/internal/server/chat_color_test.go new file mode 100644 index 00000000..2c177808 --- /dev/null +++ b/internal/server/chat_color_test.go @@ -0,0 +1,140 @@ +package server + +import ( + "context" + "strings" + "testing" + + "github.com/coder/websocket" + "github.com/coder/websocket/wsjson" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func chatColorRequest(id, session string, color *string) protocol.Message { + return protocol.Message{Type: protocol.ChatColor, ID: id, ChatQuery: &protocol.ChatQuery{SessionID: session, Color: color}} +} + +func readMessage(t *testing.T, ctx context.Context, conn *websocket.Conn) protocol.Message { + t.Helper() + var message protocol.Message + if err := wsjson.Read(ctx, conn, &message); err != nil { + t.Fatal(err) + } + return message +} + +// TestChatColorSetsListsBroadcastsAndClears is the shared-colour evidence: a +// chat_color names a palette colour, the reply echoes it, the registry keeps +// it, chat_sessions lists it, every other connection receives the row as +// chat_session_changed, and a null colour clears it again. +func TestChatColorSetsListsBroadcastsAndClears(t *testing.T) { + store := newOperatorStore(t) + broker := scriptedChat() + broker.sessions = []protocol.ChatSession{{ID: "ses_1", Title: "A", Directory: "/work/a"}} + ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 2) + if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + // A round trip on the watcher proves its connection is attached before the + // change is made. + if err := wsjson.Write(ctx, conns[1], protocol.Message{Type: protocol.Ping, ID: "p1"}); err != nil { + t.Fatal(err) + } + if pong := readMessage(t, ctx, conns[1]); pong.ID != "p1" { + t.Fatalf("ping reply = %+v", pong) + } + + teal := "teal" + if err := wsjson.Write(ctx, conns[0], chatColorRequest("c1", "ses_1", &teal)); err != nil { + t.Fatal(err) + } + reply := readMessage(t, ctx, conns[0]) + if reply.Type != protocol.ChatColor || reply.ID != "c1" || reply.ChatSession == nil || reply.ChatSession.Color != "teal" { + t.Fatalf("chat_color reply = %+v", reply) + } + pushed := readMessage(t, ctx, conns[1]) + if pushed.Type != protocol.ChatSessionChanged || pushed.ChatSession == nil || pushed.ChatSession.ID != "ses_1" || pushed.ChatSession.Color != "teal" { + t.Fatalf("watcher push = %+v", pushed) + } + row, found, err := store.OperatorSession(ctx, "ses_1") + if err != nil || !found || row.Color != "teal" { + t.Fatalf("registry row = %+v found=%v err=%v", row, found, err) + } + + if err := wsjson.Write(ctx, conns[0], protocol.Message{Type: protocol.ChatSessions, ID: "l1"}); err != nil { + t.Fatal(err) + } + listed := readMessage(t, ctx, conns[0]) + if len(listed.ChatSessions) != 1 || listed.ChatSessions[0].Color != "teal" { + t.Fatalf("chat_sessions = %+v", listed.ChatSessions) + } + + if err := wsjson.Write(ctx, conns[0], chatColorRequest("c2", "ses_1", nil)); err != nil { + t.Fatal(err) + } + cleared := readMessage(t, ctx, conns[0]) + if cleared.Type != protocol.ChatColor || cleared.ChatSession == nil || cleared.ChatSession.Color != "" { + t.Fatalf("clear reply = %+v", cleared) + } + if pushed := readMessage(t, ctx, conns[1]); pushed.Type != protocol.ChatSessionChanged || pushed.ChatSession.Color != "" { + t.Fatalf("clear push = %+v", pushed) + } + if row, _, _ := store.OperatorSession(ctx, "ses_1"); row.Color != "" { + t.Fatalf("clear not persisted: %+v", row) + } +} + +// TestChatColorRefusesUnknownColourAndForeignSession proves nothing is written +// for a colour outside the palette or a session that is not an operator chat. +func TestChatColorRefusesUnknownColourAndForeignSession(t *testing.T) { + store := newOperatorStore(t) + ctx, _, conn := dialChatOptions(t, Options{Chat: scriptedChat(), OperatorRegistry: store}) + if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + for _, color := range []string{"#ff0000", "Teal", "magenta"} { + value := color + if err := wsjson.Write(ctx, conn, chatColorRequest("bad", "ses_1", &value)); err != nil { + t.Fatal(err) + } + reply := readMessage(t, ctx, conn) + if reply.Type != protocol.Error || !strings.Contains(reply.Error, "unknown chat colour") { + t.Fatalf("colour %q reply = %+v", color, reply) + } + } + if row, _, _ := store.OperatorSession(ctx, "ses_1"); row.Color != "" { + t.Fatalf("a refused colour was written: %+v", row) + } + blue := "blue" + if err := wsjson.Write(ctx, conn, chatColorRequest("x", "ses_unknown", &blue)); err != nil { + t.Fatal(err) + } + if reply := readMessage(t, ctx, conn); reply.Type != protocol.Error || !strings.Contains(reply.Error, "not an operator chat") { + t.Fatalf("foreign session reply = %+v", reply) + } +} + +// TestChatStarBroadcastsToOtherConnections proves the star, like the colour, +// reaches the other devices' lists live. +func TestChatStarBroadcastsToOtherConnections(t *testing.T) { + store := newOperatorStore(t) + ctx, _, conns := dialChatConns(t, Options{Chat: scriptedChat(), OperatorRegistry: store}, 2) + if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + if err := wsjson.Write(ctx, conns[1], protocol.Message{Type: protocol.Ping, ID: "p1"}); err != nil { + t.Fatal(err) + } + readMessage(t, ctx, conns[1]) + starred := true + if err := wsjson.Write(ctx, conns[0], protocol.Message{Type: protocol.ChatStar, ID: "s1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1", Starred: &starred}}); err != nil { + t.Fatal(err) + } + if reply := readMessage(t, ctx, conns[0]); reply.Type != protocol.ChatStar || !reply.ChatSession.Starred { + t.Fatalf("chat_star reply = %+v", reply) + } + if pushed := readMessage(t, ctx, conns[1]); pushed.Type != protocol.ChatSessionChanged || !pushed.ChatSession.Starred { + t.Fatalf("watcher push = %+v", pushed) + } +} diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index ab9394d8..d68feabd 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -61,6 +61,8 @@ type chatHub struct { // unattended holds the unattended-observation timings (chat_unattended.go), // fixed when the hub is built. unattended chatUnattendedTimings + // sessionChanges pushes shared list metadata changes to every connection. + sessionChanges chatSessionChanges } // chatPart is the retained form of one part. Text and reasoning deltas append to diff --git a/internal/server/chat_rename.go b/internal/server/chat_rename.go index 54a8a3c0..4fa5fc78 100644 --- a/internal/server/chat_rename.go +++ b/internal/server/chat_rename.go @@ -18,7 +18,7 @@ const chatTitleLimit = 200 // browser and device lists the same name. The OpenCode session, its transcript // and its generated title are untouched, and a session that is not an operator // chat is refused before anything is written. -func handleChatRename(ctx context.Context, request protocol.Message, registry operatorRegistry, write func(protocol.Message) error) { +func handleChatRename(ctx context.Context, request protocol.Message, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { if registry == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"}) return @@ -48,20 +48,5 @@ func handleChatRename(ctx context.Context, request protocol.Message, registry op _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) return } - session, found, err := registry.OperatorSession(ctx, rename.SessionID) - if err != nil { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) - return - } - if !found { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + rename.SessionID + " is no longer an operator session"}) - return - } - wire := chatSessionFromOperator(session) - write(protocol.Message{ - Type: protocol.ChatRename, - ID: request.ID, - ChatSession: &wire, - ChatSessions: []protocol.ChatSession{wire}, - }) + echoOperatorSession(ctx, request, rename.SessionID, protocol.ChatRename, registry, changes, clientID, write) } diff --git a/internal/server/chat_session_changes.go b/internal/server/chat_session_changes.go new file mode 100644 index 00000000..114c7dcb --- /dev/null +++ b/internal/server/chat_session_changes.go @@ -0,0 +1,87 @@ +package server + +import ( + "context" + "sync" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// chatSessionChanges fans a chat's shared list metadata (colour, star, title) +// out to every open connection, so a change on one device updates the chat +// list on the others live. Unlike a chat room it is not keyed by session: every +// connection shows the list. It holds each connection's serialized write +// function, never the socket. The zero value is ready to use. +type chatSessionChanges struct { + mu sync.Mutex + clients map[string]func(protocol.Message) error +} + +func (c *chatSessionChanges) attach(clientID string, write func(protocol.Message) error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.clients == nil { + c.clients = map[string]func(protocol.Message) error{} + } + c.clients[clientID] = write +} + +func (c *chatSessionChanges) detach(clientID string) { + c.mu.Lock() + defer c.mu.Unlock() + delete(c.clients, clientID) +} + +// changes returns the hub's connection fan-out; nil for a nil hub, which +// broadcasts nothing. +func (h *chatHub) changes() *chatSessionChanges { + if h == nil { + return nil + } + return &h.sessionChanges +} + +// broadcast pushes the updated row to every connection except the sender, +// which already has it in its reply. Each write runs on its own goroutine +// (bounded by the connection's write timeout), so a slow client cannot delay +// the sender or the others. +func (c *chatSessionChanges) broadcast(sender string, session protocol.ChatSession) { + c.mu.Lock() + targets := make([]func(protocol.Message) error, 0, len(c.clients)) + for id, write := range c.clients { + if id != sender { + targets = append(targets, write) + } + } + c.mu.Unlock() + for _, write := range targets { + row := session + go func() { + _ = write(protocol.Message{Type: protocol.ChatSessionChanged, ChatSession: &row}) + }() + } +} + +// echoOperatorSession answers a metadata change with the updated registry row +// and pushes the same row to every other connection. +func echoOperatorSession(ctx context.Context, request protocol.Message, sessionID, reply string, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { + session, found, err := registry.OperatorSession(ctx, sessionID) + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + if !found { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is no longer an operator session"}) + return + } + wire := chatSessionFromOperator(session) + _ = write(protocol.Message{ + Type: reply, + ID: request.ID, + ChatSession: &wire, + ChatSessions: []protocol.ChatSession{wire}, + }) + if changes != nil { + changes.broadcast(clientID, wire) + } +} diff --git a/internal/server/chat_sessions.go b/internal/server/chat_sessions.go index 531b864a..22df7edf 100644 --- a/internal/server/chat_sessions.go +++ b/internal/server/chat_sessions.go @@ -83,6 +83,7 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch session.Starred = operator.StarredAt > 0 session.StarredAt = operator.StarredAt session = withChatHandoff(session) + session.Color = operator.Color response.ChatSessions = append(response.ChatSessions, session) } _ = write(response) diff --git a/internal/server/chat_star.go b/internal/server/chat_star.go index a38ff6d6..1011c3b0 100644 --- a/internal/server/chat_star.go +++ b/internal/server/chat_star.go @@ -13,7 +13,7 @@ import ( // session is refused before anything is written, so a pipeline-owned run session // is never touched. The request body is a ChatQuery carrying SessionID and the // desired Starred value; the reply echoes the updated session. -func handleChatStar(ctx context.Context, request protocol.Message, registry operatorRegistry, write func(protocol.Message) error) { +func handleChatStar(ctx context.Context, request protocol.Message, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { if registry == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"}) return @@ -39,20 +39,5 @@ func handleChatStar(ctx context.Context, request protocol.Message, registry oper _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) return } - session, found, err := registry.OperatorSession(ctx, sessionID) - if err != nil { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) - return - } - if !found { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is no longer an operator session"}) - return - } - wire := chatSessionFromOperator(session) - write(protocol.Message{ - Type: protocol.ChatStar, - ID: request.ID, - ChatSession: &wire, - ChatSessions: []protocol.ChatSession{wire}, - }) + echoOperatorSession(ctx, request, sessionID, protocol.ChatStar, registry, changes, clientID, write) } diff --git a/internal/server/websocket.go b/internal/server/websocket.go index abd42103..1f6da9bf 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -210,6 +210,10 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // the welcome frame so a push never precedes it. acks.attach(clientID, write) defer acks.detach(clientID) + // Shared chat-list metadata (colour, star, title) reaches every open + // connection the same way. + hub.sessionChanges.attach(clientID, write) + defer hub.sessionChanges.detach(clientID) if notes != nil { defer notes.detach(clientID) }