diff --git a/app/lib/features/chat/domain/chat_list_activity.dart b/app/lib/features/chat/domain/chat_list_activity.dart index 138393a2..a1efbb6c 100644 --- a/app/lib/features/chat/domain/chat_list_activity.dart +++ b/app/lib/features/chat/domain/chat_list_activity.dart @@ -1,14 +1,15 @@ import '../../../core/api_gateway.dart'; -/// One chat's live activity as the server observes it: a turn in flight and -/// how many background tasks (shells, background commands, subagents) still -/// run. It rides on each `chat_sessions` row as `activity` and is pushed to +/// One chat's live activity as the server observes it: a turn in flight, how +/// many background tasks (shells, background commands, subagents) still run, +/// and how many approvals or questions wait on the operator. It rides on each `chat_sessions` row as `activity` and is pushed to /// every connection as `chat_activity` on each change. [seq] orders one /// chat's snapshots across the list and the pushes; the larger one is newer. typedef ChatListActivity = ({ String sessionId, bool turnRunning, int backgroundTasks, + int awaitingOperator, int seq, }); @@ -21,11 +22,13 @@ ChatListActivity? chatListActivityOf(Object? value, {String? sessionId}) { final id = sessionId ?? (named is String ? named : ''); if (id.isEmpty) return null; final tasks = value['background_tasks']; + final awaiting = value['awaiting_operator']; final seq = value['seq']; return ( sessionId: id, turnRunning: value['turn_running'] == true, backgroundTasks: tasks is num && tasks > 0 ? tasks.toInt() : 0, + awaitingOperator: awaiting is num && awaiting > 0 ? awaiting.toInt() : 0, seq: seq is num ? seq.toInt() : 0, ); } @@ -34,6 +37,7 @@ ChatListActivity? chatListActivityOf(Object? value, {String? sessionId}) { JsonMap chatListActivityRowFields(ChatListActivity activity) => { 'running': activity.turnRunning, 'background_tasks': activity.backgroundTasks, + 'awaiting_operator': activity.awaitingOperator, }; /// Running background tasks of a list row; 0 when unknown. @@ -41,3 +45,10 @@ int chatSessionBackgroundTasks(JsonMap session) { final tasks = session['background_tasks']; return tasks is int && tasks > 0 ? tasks : 0; } + +/// Approvals and questions a list row's chat holds unanswered; 0 when none or +/// unknown. Above 0 the agent is blocked until the operator replies. +int chatSessionAwaitingOperator(JsonMap session) { + final awaiting = session['awaiting_operator']; + return awaiting is int && awaiting > 0 ? awaiting : 0; +} diff --git a/app/lib/features/chat/ui/sessions/chat_awaiting.dart b/app/lib/features/chat/ui/sessions/chat_awaiting.dart new file mode 100644 index 00000000..96825732 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_awaiting.dart @@ -0,0 +1,166 @@ +import 'package:flutter/material.dart'; + +/// How a chat that is waiting on the operator (an unanswered approval or +/// question; the agent is blocked until they reply) stands out in the chat +/// list: a ringing bell on the avatar, and a pulsing error-coloured row with a +/// solid bar on its leading edge. With reduced motion both hold still. + +/// The accessible name of a waiting chat's bell. +String chatAwaitingLabel(int count) => count == 1 + ? 'Waiting for your reply' + : 'Waiting for your reply ($count requests)'; + +/// The bell badge a waiting chat's avatar wears in place of the spinner. +class ChatAwaitingBadge extends StatefulWidget { + const ChatAwaitingBadge({super.key, required this.count}); + + final int count; + + @override + State createState() => _ChatAwaitingBadgeState(); +} + +class _ChatAwaitingBadgeState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _ring = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1400), + ); + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final still = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + if (still) { + _ring.stop(); + _ring.value = 0; + } else if (!_ring.isAnimating) { + _ring.repeat(); + } + } + + @override + void dispose() { + _ring.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Semantics( + key: const Key('chat-row-awaiting'), + label: chatAwaitingLabel(widget.count), + child: DecoratedBox( + decoration: BoxDecoration( + color: scheme.error, + shape: BoxShape.circle, + border: Border.all(color: scheme.surface, width: 2), + ), + child: Padding( + padding: const EdgeInsets.all(2), + child: AnimatedBuilder( + animation: _ring, + // A bell rings in short swings, then rests for the rest of the beat. + builder: (context, child) { + final t = _ring.value; + final swing = t < 0.4 + ? 0.45 * (1 - t / 0.4) * (t * 10 % 2 < 1 ? 1 : -1) + : 0.0; + return Transform.rotate(angle: swing, child: child); + }, + child: Icon( + Icons.notifications_active, + size: 18, + color: scheme.onError, + ), + ), + ), + ), + ); + } +} + +/// The waiting chat's row: a pulsing error-container tint and a solid error +/// bar on the leading edge, over the row's own content. +class ChatAwaitingHighlight extends StatefulWidget { + const ChatAwaitingHighlight({ + super.key, + required this.waiting, + required this.child, + }); + + final bool waiting; + final Widget child; + + @override + State createState() => _ChatAwaitingHighlightState(); +} + +class _ChatAwaitingHighlightState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _pulse = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1100), + ); + bool _still = false; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _still = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + _sync(); + } + + @override + void didUpdateWidget(ChatAwaitingHighlight oldWidget) { + super.didUpdateWidget(oldWidget); + _sync(); + } + + void _sync() { + if (widget.waiting && !_still) { + if (!_pulse.isAnimating) _pulse.repeat(reverse: true); + } else { + _pulse.stop(); + _pulse.value = 1; + } + } + + @override + void dispose() { + _pulse.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + if (!widget.waiting) return widget.child; + final scheme = Theme.of(context).colorScheme; + return Stack( + children: [ + Positioned.fill( + child: IgnorePointer( + child: RepaintBoundary( + child: AnimatedBuilder( + animation: _pulse, + builder: (context, _) => DecoratedBox( + key: const Key('chat-row-awaiting-highlight'), + decoration: BoxDecoration( + color: scheme.errorContainer.withValues( + alpha: 0.35 + 0.45 * _pulse.value, + ), + border: BorderDirectional( + start: BorderSide(color: scheme.error, width: 5), + ), + ), + ), + ), + ), + ), + ), + widget.child, + ], + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_compact_avatar.dart b/app/lib/features/chat/ui/sessions/chat_compact_avatar.dart index a56f7e42..f47285f2 100644 --- a/app/lib/features/chat/ui/sessions/chat_compact_avatar.dart +++ b/app/lib/features/chat/ui/sessions/chat_compact_avatar.dart @@ -12,12 +12,14 @@ class ChatCompactAvatar extends StatelessWidget { required this.visible, required this.running, required this.backgroundTasks, + this.awaitingOperator = 0, required this.unread, }); final String title; final Color color; final bool active, visible, running, unread; final int backgroundTasks; + final int awaitingOperator; @override Widget build(BuildContext context) => Stack( @@ -46,6 +48,7 @@ class ChatCompactAvatar extends StatelessWidget { if (chatSessionActivityBadge( running: running, backgroundTasks: backgroundTasks, + awaitingOperator: awaitingOperator, ) case final badge?) PositionedDirectional(bottom: -2, end: -3, child: badge), diff --git a/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart b/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart index 015b3548..1e60be0e 100644 --- a/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart +++ b/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart @@ -66,6 +66,7 @@ class ChatCompactSidebar extends StatelessWidget { final unread = controller.isUnseen(row); final running = row['running'] == true; final backgroundTasks = chatSessionBackgroundTasks(row); + final awaitingOperator = chatSessionAwaitingOperator(row); final title = chatSessionTitle(row); final machineName = ServerContext.nameFor(context, '${row['_server_id'] ?? ''}') ?? @@ -97,6 +98,7 @@ class ChatCompactSidebar extends StatelessWidget { active: selected, visible: visible, running: running, + awaitingOperator: awaitingOperator, backgroundTasks: backgroundTasks, unread: unread, ), @@ -141,6 +143,7 @@ class ChatCompactSidebar extends StatelessWidget { active: false, visible: false, running: running, + awaitingOperator: awaitingOperator, backgroundTasks: backgroundTasks, unread: unread, ), diff --git a/app/lib/features/chat/ui/sessions/chat_session_state.dart b/app/lib/features/chat/ui/sessions/chat_session_state.dart index 38744799..edeffed5 100644 --- a/app/lib/features/chat/ui/sessions/chat_session_state.dart +++ b/app/lib/features/chat/ui/sessions/chat_session_state.dart @@ -16,9 +16,11 @@ class ChatSessionStateLine extends StatelessWidget { required this.running, required this.backgroundTasks, required this.unread, + this.awaitingOperator = 0, }); final bool active, visible, running, unread; final int backgroundTasks; + final int awaitingOperator; @override Widget build(BuildContext context) { @@ -32,10 +34,28 @@ class ChatSessionStateLine extends StatelessWidget { (Icons.pending_actions, '$backgroundTasks background'), if (unread) (Icons.mark_chat_unread_outlined, 'New'), ]; + final error = Theme.of(context).colorScheme.error; return Wrap( spacing: 10, runSpacing: 4, children: [ + if (awaitingOperator > 0) + Row( + key: const Key('chat-row-awaiting-label'), + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.notifications_active, size: 16, color: error), + const SizedBox(width: 4), + Flexible( + child: Text( + awaitingOperator == 1 + ? 'Waiting for you' + : 'Waiting for you ($awaitingOperator)', + style: TextStyle(color: error, fontWeight: FontWeight.w800), + ), + ), + ], + ), for (final (icon, label) in entries) Row( mainAxisSize: MainAxisSize.min, @@ -66,10 +86,12 @@ class ChatSessionSubtitle extends StatelessWidget { required this.running, required this.backgroundTasks, required this.unread, + this.awaitingOperator = 0, }); final String metadata; final String? machineName; final bool closed, active, visible, running, unread; + final int awaitingOperator; final int backgroundTasks; @override Widget build(BuildContext context) => Column( @@ -93,7 +115,12 @@ class ChatSessionSubtitle extends StatelessWidget { ), style: TextStyle(color: chatMetadataForeground(context)), ), - if (active || visible || running || backgroundTasks > 0 || unread) + if (active || + visible || + running || + backgroundTasks > 0 || + unread || + awaitingOperator > 0) Padding( padding: const EdgeInsets.only(top: 4), child: ChatSessionStateLine( @@ -102,6 +129,7 @@ class ChatSessionSubtitle extends StatelessWidget { running: running, backgroundTasks: backgroundTasks, unread: unread, + awaitingOperator: awaitingOperator, ), ), ], 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 41c4366d..39b4bb54 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -203,7 +203,8 @@ class ChatSessionsController extends ChangeNotifier { for (final row in _sessions) if ('${row['id'] ?? ''}' == id && (row['running'] != fields['running'] || - row['background_tasks'] != fields['background_tasks'])) + row['background_tasks'] != fields['background_tasks'] || + row['awaiting_operator'] != fields['awaiting_operator'])) () { changed = true; return {...row, ...fields}; diff --git a/app/lib/features/chat/ui/sessions/session_activity_badge.dart b/app/lib/features/chat/ui/sessions/session_activity_badge.dart index a20bafe9..b610c428 100644 --- a/app/lib/features/chat/ui/sessions/session_activity_badge.dart +++ b/app/lib/features/chat/ui/sessions/session_activity_badge.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import '../../../../ui/status/app_spinner.dart'; +import 'chat_awaiting.dart'; /// The corner badge a chat's avatar wears for its live activity: the /// platform's activity indicator while a turn runs; otherwise, while @@ -8,7 +9,10 @@ import '../../../../ui/status/app_spinner.dart'; Widget? chatSessionActivityBadge({ required bool running, required int backgroundTasks, + int awaitingOperator = 0, }) { + // Waiting on the operator outranks everything: the agent is blocked. + if (awaitingOperator > 0) return ChatAwaitingBadge(count: awaitingOperator); if (running) { return Semantics( key: const Key('chat-row-working'), 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 b61e91b5..91ef77bf 100644 --- a/app/lib/features/chat/ui/sessions/session_row_content.dart +++ b/app/lib/features/chat/ui/sessions/session_row_content.dart @@ -17,6 +17,7 @@ import 'session_activity_badge.dart'; import 'session_harness_icon.dart'; import 'session_pane_menu.dart'; import 'session_row_style.dart'; +import 'chat_awaiting.dart'; /// One chat in the list, in the app's shared row on both hosts: the harness /// avatar, the title with its recency, one muted line, and the actions menu. @@ -109,8 +110,10 @@ class ChatSessionRow extends StatelessWidget { final unread = unseen && !closed; final text = chatSessionSubtitle(session); final updatedAt = _chatSessionInstant(session['updated_at']); + final awaiting = closed ? 0 : chatSessionAwaitingOperator(session); final avatar = ChatSessionAvatar( session: session, + awaitingOperator: awaiting, running: session['running'] == true && !unseen, backgroundTasks: session['running'] == true ? 0 @@ -122,78 +125,82 @@ class ChatSessionRow extends StatelessWidget { color: marker, visible: visible, active: selected, - child: AppListRow( - key: Key('chat-row-$id'), - selected: selected, - selectedFill: Colors.transparent, - emphasized: unread, - divider: divider, - onTap: () => onOpen(session), - onLongPress: selectionOnly ? null : onLongPress, - accent: chatColorShade(context, chatSessionColor(session)), - showAccentBorder: false, - leading: avatar, - // The star rides in the title's own text, so a narrow row ellipsises - // them together. - title: Text.rich( - TextSpan( - text: chatSessionTitle(session), - children: [ - if (session['starred'] == true) - WidgetSpan( - alignment: PlaceholderAlignment.middle, - child: Padding( - padding: const EdgeInsetsDirectional.only(start: 4), - child: _Star(color: accent), + child: ChatAwaitingHighlight( + waiting: awaiting > 0, + child: AppListRow( + key: Key('chat-row-$id'), + selected: selected, + selectedFill: Colors.transparent, + emphasized: unread, + divider: divider, + onTap: () => onOpen(session), + onLongPress: selectionOnly ? null : onLongPress, + accent: chatColorShade(context, chatSessionColor(session)), + showAccentBorder: false, + leading: avatar, + // The star rides in the title's own text, so a narrow row ellipsises + // them together. + title: Text.rich( + TextSpan( + text: chatSessionTitle(session), + children: [ + if (session['starred'] == true) + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 4), + child: _Star(color: accent), + ), ), - ), - ], + ], + ), ), - ), - timeWidget: updatedAt == null - ? null - : DefaultTextStyle.merge( - style: TextStyle( - color: unread ? accent : chatMetadataForeground(context), + timeWidget: updatedAt == null + ? null + : DefaultTextStyle.merge( + style: TextStyle( + color: unread ? accent : chatMetadataForeground(context), + ), + child: RelativeTimeLabel(instant: updatedAt), + ), + // `Closed` leads the line of a closed chat, then the model and folder. + subtitle: ChatSessionSubtitle( + machineName: + ServerContext.nameFor( + context, + '${session['_server_id'] ?? ''}', + ) ?? + session['_server_name'] as String?, + metadata: text, + closed: closed, + active: selected, + visible: visible, + running: session['running'] == true, + backgroundTasks: chatSessionBackgroundTasks(session), + awaitingOperator: awaiting, + unread: unread, + ), + subtitleTrailing: unread + ? AppListStatusDot( + key: const Key('chat-row-unread'), + color: accent, + semanticLabel: 'New', + size: 10, + ) + : null, + menu: selectionOnly + ? null + : SessionActionsButton( + key: Key('chat-actions-$id'), + session: session, + duplicateTitles: duplicateTitles, + onSelected: onAction, + allowOpenBeside: onOpenBeside != null, + allowOpenBelow: onOpenBelow != null, + allowFloat: onFloat != null, + paneMenu: paneMenu, ), - child: RelativeTimeLabel(instant: updatedAt), - ), - // `Closed` leads the line of a closed chat, then the model and folder. - subtitle: ChatSessionSubtitle( - machineName: - ServerContext.nameFor( - context, - '${session['_server_id'] ?? ''}', - ) ?? - session['_server_name'] as String?, - metadata: text, - closed: closed, - active: selected, - visible: visible, - running: session['running'] == true, - backgroundTasks: chatSessionBackgroundTasks(session), - unread: unread, ), - subtitleTrailing: unread - ? AppListStatusDot( - key: const Key('chat-row-unread'), - color: accent, - semanticLabel: 'New', - size: 10, - ) - : null, - menu: selectionOnly - ? null - : SessionActionsButton( - key: Key('chat-actions-$id'), - session: session, - duplicateTitles: duplicateTitles, - onSelected: onAction, - allowOpenBeside: onOpenBeside != null, - allowOpenBelow: onOpenBelow != null, - allowFloat: onFloat != null, - paneMenu: paneMenu, - ), ), ); } @@ -233,12 +240,14 @@ class ChatSessionAvatar extends StatelessWidget { required this.session, this.running = false, this.backgroundTasks = 0, + this.awaitingOperator = 0, this.selected = false, }); final JsonMap session; final bool running; final int backgroundTasks; + final int awaitingOperator; final bool selected; @override @@ -266,6 +275,7 @@ class ChatSessionAvatar extends StatelessWidget { badge: chatSessionActivityBadge( running: running, backgroundTasks: backgroundTasks, + awaitingOperator: awaitingOperator, ), child: SessionHarnessIcon(session: session, color: mark), ); diff --git a/app/test/features/chat/ui/sessions/chat_awaiting_test.dart b/app/test/features/chat/ui/sessions/chat_awaiting_test.dart new file mode 100644 index 00000000..443bdb7f --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_awaiting_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_list_activity.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_awaiting.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_activity_badge.dart'; + +void main() { + test('the list activity carries what waits on the operator', () { + final activity = chatListActivityOf({ + 'session_id': 's', + 'turn_running': true, + 'awaiting_operator': 2, + 'seq': 5, + })!; + expect(activity.awaitingOperator, 2); + final row = chatListActivityRowFields(activity); + expect(chatSessionAwaitingOperator(row), 2); + expect(chatSessionAwaitingOperator(const {}), 0); + }); + + testWidgets('waiting on the operator outranks the working spinner', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Center( + child: chatSessionActivityBadge( + running: true, + backgroundTasks: 1, + awaitingOperator: 1, + ), + ), + ), + ); + expect(find.byKey(const Key('chat-row-awaiting')), findsOneWidget); + expect(find.byKey(const Key('chat-row-working')), findsNothing); + expect(find.bySemanticsLabel('Waiting for your reply'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('a waiting row pulses; reduced motion holds it still', ( + tester, + ) async { + Widget host({required bool still}) => MaterialApp( + home: MediaQuery( + data: MediaQueryData(disableAnimations: still), + child: const Scaffold( + body: ChatAwaitingHighlight( + waiting: true, + child: SizedBox(height: 60, child: Text('Caplens PI')), + ), + ), + ), + ); + Color tint() => + ((tester + .widget( + find.byKey(const Key('chat-row-awaiting-highlight')), + ) + .decoration + as BoxDecoration) + .color!); + await tester.pumpWidget(host(still: false)); + final first = tint(); + await tester.pump(const Duration(milliseconds: 550)); + expect(tint(), isNot(first)); + + await tester.pumpWidget(host(still: true)); + await tester.pump(); + final held = tint(); + await tester.pump(const Duration(milliseconds: 550)); + expect(tint(), held); + await tester.pumpWidget(const SizedBox()); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_sessions_activity_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_activity_test.dart index 9e9bd8ae..ff5e4f77 100644 --- a/app/test/features/chat/ui/sessions/chat_sessions_activity_test.dart +++ b/app/test/features/chat/ui/sessions/chat_sessions_activity_test.dart @@ -221,12 +221,19 @@ void main() { 'background_tasks': 2, 'seq': 9, }, sessionId: 's1'), - (sessionId: 's1', turnRunning: true, backgroundTasks: 2, seq: 9), + ( + sessionId: 's1', + turnRunning: true, + backgroundTasks: 2, + awaitingOperator: 0, + seq: 9, + ), ); expect(chatListActivityOf({'session_id': 's2'}), ( sessionId: 's2', turnRunning: false, backgroundTasks: 0, + awaitingOperator: 0, seq: 0, )); expect(chatListActivityOf({'background_tasks': 1}), isNull); diff --git a/app/tool/perf/perf_fixture.dart b/app/tool/perf/perf_fixture.dart index a8aa17d4..74f06bdf 100644 --- a/app/tool/perf/perf_fixture.dart +++ b/app/tool/perf/perf_fixture.dart @@ -61,6 +61,8 @@ JsonMap? _activityFor(int i) { return switch (i) { 0 => {'turn_running': true, 'background_tasks': 1, 'seq': 3}, 1 => {'background_tasks': 2, 'seq': 2}, + // A turn blocked on the operator: an approval and a question unanswered. + 2 => {'turn_running': true, 'awaiting_operator': 2, 'seq': 4}, _ => {'seq': 1}, }; } diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index 537a6fd9..3814160e 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -397,7 +397,10 @@ type ChatActivity struct { SessionID string `json:"session_id,omitempty"` TurnRunning bool `json:"turn_running,omitempty"` BackgroundTasks int `json:"background_tasks,omitempty"` - Seq int64 `json:"seq,omitempty"` + // AwaitingOperator counts the approvals and questions the session holds + // unanswered: the agent is blocked on the operator until they reply. + AwaitingOperator int `json:"awaiting_operator,omitempty"` + Seq int64 `json:"seq,omitempty"` } // Chat export formats accepted by chat_export. diff --git a/internal/server/chat_activity.go b/internal/server/chat_activity.go index 098dd48d..ca4cd8b5 100644 --- a/internal/server/chat_activity.go +++ b/internal/server/chat_activity.go @@ -6,9 +6,10 @@ import ( "git.a-wan.net/alan/pipelines/internal/protocol" ) -// Chat list activity: every listed chat shows whether its turn is running and +// Chat list activity: every listed chat shows whether its turn is running, // whether background tasks (shells, background commands, subagents) are still -// running after the turn. Room frames reach only the connections that opened +// running after the turn, and whether the agent is waiting on the operator (an +// unanswered approval or question). Room frames reach only the connections that opened // that chat, so the hub keeps a small per-session summary and pushes each // change to every connection as chat_activity, and chat_sessions carries the // current summary on each row. @@ -33,6 +34,7 @@ func (h *chatHub) chatActivityLocked(sessionID string) protocol.ChatActivity { } activity.TurnRunning = room.running || room.observedTurn activity.BackgroundTasks = h.backgroundTasksLocked(sessionID) + activity.AwaitingOperator = len(room.pending) + len(room.forms) return activity } @@ -56,7 +58,9 @@ func (h *chatHub) noteActivityLocked(sessionID string) { h.rememberLiveLocked(sessionID) next := h.chatActivityLocked(sessionID) previous := h.activity[sessionID] - if previous.TurnRunning == next.TurnRunning && previous.BackgroundTasks == next.BackgroundTasks { + if previous.TurnRunning == next.TurnRunning && + previous.BackgroundTasks == next.BackgroundTasks && + previous.AwaitingOperator == next.AwaitingOperator { return } if h.activity == nil { diff --git a/internal/server/chat_activity_test.go b/internal/server/chat_activity_test.go index 8ee57b3a..5fa6f2d2 100644 --- a/internal/server/chat_activity_test.go +++ b/internal/server/chat_activity_test.go @@ -185,3 +185,43 @@ func TestChatBackgroundTasksKeepUnattendedRoom(t *testing.T) { } } } + +// An unanswered approval or question is the operator's to act on: the list +// activity counts it, and answering it clears the count. +func TestChatActivityCountsWhatAwaitsTheOperator(t *testing.T) { + h := newChatHub() + defer func() { + h.mu.Lock() + for _, room := range h.rooms { + room.cancel() + } + h.mu.Unlock() + }() + const id = "ses_wait" + awaiting := func() int { + h.mu.Lock() + defer h.mu.Unlock() + return h.activity[id].AwaitingOperator + } + h.mu.Lock() + h.roomLocked(id) + h.mu.Unlock() + + h.pushPermission(id, protocol.ChatPermissionFrame{SessionID: id, RequestID: "perm_1"}) + if got := awaiting(); got != 1 { + t.Fatalf("a pending approval: awaiting=%d", got) + } + h.mu.Lock() + h.applyLocked(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventForm, Form: &protocol.ChatForm{ID: "q_1"}}) + h.mu.Unlock() + if got := awaiting(); got != 2 { + t.Fatalf("an approval and a question: awaiting=%d", got) + } + h.confirmPermission(id, "perm_1", "c", "allow") + h.mu.Lock() + h.applyLocked(protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventForm, Form: &protocol.ChatForm{ID: "q_1", Resolved: true}}) + h.mu.Unlock() + if got := awaiting(); got != 0 { + t.Fatalf("both answered: awaiting=%d", got) + } +} diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index 9c252b37..02636b7a 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -245,6 +245,7 @@ func (h *chatHub) applyLocked(frame protocol.ChatEventFrame) { room.forms = append(room.forms, *frame.Form) } h.rememberLiveLocked(frame.SessionID) + h.noteActivityLocked(frame.SessionID) } return } diff --git a/internal/server/chat_permissions.go b/internal/server/chat_permissions.go index a5a636b8..56d923cc 100644 --- a/internal/server/chat_permissions.go +++ b/internal/server/chat_permissions.go @@ -100,6 +100,7 @@ func (h *chatHub) confirmPermission(sessionID, requestID, client, decision strin break } } + h.noteActivityLocked(sessionID) for _, sub := range room.subs { targets = append(targets, sub) } diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 1d3a46ed..ee123256 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -718,6 +718,7 @@ func (h *chatHub) pushPermission(sessionID string, frame protocol.ChatPermission if len(room.pending) > chatRoomPendingLimit { room.pending = room.pending[len(room.pending)-chatRoomPendingLimit:] } + h.noteActivityLocked(sessionID) for _, sub := range room.subs { targets = append(targets, sub) }