From 45c933c176762c7d9d4acb7c034c0a9d241abccb Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 3 Nov 2026 19:53:52 +0000 Subject: [PATCH] Chat list: spinner and background-task badge from server activity on every row The list applies chat_activity pushes and each row's activity by seq, so every listed chat shows a running turn, not only the chat open here. An idle chat with running background tasks wears a quiet badge with tooltip and semantics "Background tasks running (N)". Older servers keep the old behaviour. List rows that never changed carry the server's current seq so they order after snapshots kept from an earlier server process. --- .../chat/domain/chat_list_activity.dart | 43 +++ .../ui/sessions/chat_sessions_controller.dart | 67 ++++- .../ui/sessions/session_activity_badge.dart | 93 ++++++ .../chat/ui/sessions/session_row_content.dart | 47 +--- app/notes/session-list-background-tasks.md | 81 ++++-- .../sessions/chat_sessions_activity_test.dart | 264 ++++++++++++++++++ app/tool/perf/perf_fixture.dart | 16 ++ internal/server/chat_activity.go | 13 +- internal/server/chat_activity_test.go | 9 +- 9 files changed, 560 insertions(+), 73 deletions(-) create mode 100644 app/lib/features/chat/domain/chat_list_activity.dart create mode 100644 app/lib/features/chat/ui/sessions/session_activity_badge.dart create mode 100644 app/test/features/chat/ui/sessions/chat_sessions_activity_test.dart diff --git a/app/lib/features/chat/domain/chat_list_activity.dart b/app/lib/features/chat/domain/chat_list_activity.dart new file mode 100644 index 00000000..138393a2 --- /dev/null +++ b/app/lib/features/chat/domain/chat_list_activity.dart @@ -0,0 +1,43 @@ +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 +/// 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 seq, +}); + +/// Reads an `activity` row field or a `chat_activity` body. [sessionId] names +/// the row when the body omits it. Anything malformed is null, so an older +/// server (which sends neither) leaves the list exactly as before. +ChatListActivity? chatListActivityOf(Object? value, {String? sessionId}) { + if (value is! Map) return null; + final named = value['session_id']; + final id = sessionId ?? (named is String ? named : ''); + if (id.isEmpty) return null; + final tasks = value['background_tasks']; + final seq = value['seq']; + return ( + sessionId: id, + turnRunning: value['turn_running'] == true, + backgroundTasks: tasks is num && tasks > 0 ? tasks.toInt() : 0, + seq: seq is num ? seq.toInt() : 0, + ); +} + +/// The row keys the list controller derives from the activity. +JsonMap chatListActivityRowFields(ChatListActivity activity) => { + 'running': activity.turnRunning, + 'background_tasks': activity.backgroundTasks, +}; + +/// Running background tasks of a list row; 0 when unknown. +int chatSessionBackgroundTasks(JsonMap session) { + final tasks = session['background_tasks']; + return tasks is int && tasks > 0 ? tasks : 0; +} 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 1ac13ab6..3cc0b53c 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -8,6 +8,7 @@ import '../../../../core/servers/server_scope.dart'; import '../../../../core/transport/connection_state.dart'; import '../../../attention/runtime/attention_ack_sync.dart'; import '../../data/chat_repository.dart'; +import '../../domain/chat_list_activity.dart'; import '../../domain/chat_sessions.dart'; import 'chat_session_local.dart'; import 'session_attention.dart'; @@ -65,6 +66,9 @@ class ChatSessionsController extends ChangeNotifier { Future _persistTail = Future.value(); int _runningRevision = 0; final Map _runningFrames = {}; + // The newest server activity applied per chat (list row or push), so an + // older snapshot that arrives later never replaces it. + final Map _activity = {}; StreamSubscription? _frameSubscription; String? activeSessionId; @@ -75,6 +79,9 @@ class ChatSessionsController extends ChangeNotifier { void _onFrame(JsonMap frame) { if (frame['type'] == 'chat_session_changed') return _sessionChanged(frame); + if (frame['type'] == 'chat_activity') { + return _activityChanged(frame['chat_activity']); + } final effect = chatSessionFrameEffect(frame); if (effect == null) return; final id = effect.sessionId; @@ -130,6 +137,58 @@ class ChatSessionsController extends ChangeNotifier { if (found) _notify(); } + /// The server pushed a chat's turn state and background-task count. It + /// reaches every connection, so every listed chat's spinner and + /// background-task badge follow it, not only the chat open here. A push + /// older than the snapshot already applied is ignored. + void _activityChanged(Object? body) { + final activity = chatListActivityOf(body); + if (activity == null || _disposed) return; + final id = activity.sessionId; + if (activity.seq <= (_activity[id]?.seq ?? 0)) return; + _activity[id] = activity; + _runningFrames[id] = ( + revision: ++_runningRevision, + running: activity.turnRunning, + ); + final fields = chatListActivityRowFields(activity); + var changed = false; + _sessions = [ + for (final row in _sessions) + if ('${row['id'] ?? ''}' == id && + (row['running'] != fields['running'] || + row['background_tasks'] != fields['background_tasks'])) + () { + changed = true; + return {...row, ...fields}; + }() + else + row, + ]; + if (changed) _notify(); + } + + /// A listed row with the newest activity known for it: the row's own + /// `activity` unless a newer push was already applied, then a turn frame + /// this connection saw during the read. An older server sends no + /// `activity`, so only the turn frames apply, as before. + JsonMap _withActivity(JsonMap row, int runningRevision) { + final id = '${row['id'] ?? ''}'; + var next = row; + final listed = chatListActivityOf(row['activity'], sessionId: id); + if (listed != null) { + final known = _activity[id]; + final activity = known != null && known.seq > listed.seq ? known : listed; + _activity[id] = activity; + next = {...row, ...chatListActivityRowFields(activity)}; + } + final frame = _runningFrames[id]; + if ((frame?.revision ?? 0) > runningRevision) { + next = {...next, 'running': frame!.running}; + } + return next; + } + void _bindAckSync(AttentionAckSync? sync) { if (identical(sync, _ackSync)) return; _ackSync?.removeListener(_ackChanged); @@ -246,6 +305,7 @@ class ChatSessionsController extends ChangeNotifier { if (identical(next.gateway, repository.gateway)) return; repository = next; _runningFrames.clear(); + _activity.clear(); _listenFrames(); _bindAckSync(attentionAckSyncOf(next.gateway) ?? _ackSync); refresh(); @@ -265,12 +325,7 @@ class ChatSessionsController extends ChangeNotifier { final sessions = await repository.sessions(); if (generation != _generation) return; _sessions = [ - for (final row in sessions) - if ((_runningFrames['${row['id'] ?? ''}']?.revision ?? 0) > - runningRevision) - {...row, 'running': _runningFrames['${row['id'] ?? ''}']!.running} - else - row, + for (final row in sessions) _withActivity(row, runningRevision), ]; _seedLocal(); _loading = false; diff --git a/app/lib/features/chat/ui/sessions/session_activity_badge.dart b/app/lib/features/chat/ui/sessions/session_activity_badge.dart new file mode 100644 index 00000000..75a51cf1 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_activity_badge.dart @@ -0,0 +1,93 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +/// The corner badge a chat's avatar wears for its live activity: the +/// platform's activity indicator while a turn runs; otherwise, while +/// background tasks still run, a quiet muted glyph (never a second spinner). +/// Null when the chat is idle. +Widget? chatSessionActivityBadge({ + required bool cupertino, + required bool running, + required int backgroundTasks, +}) { + if (running) { + return Semantics( + key: const Key('chat-row-working'), + label: 'Chat is working', + child: _WorkingBadge(cupertino: cupertino), + ); + } + if (backgroundTasks <= 0) return null; + final label = 'Background tasks running ($backgroundTasks)'; + // Hover shows the tooltip on a pointer device; a touch long press stays the + // row's own gesture. + return Tooltip( + key: const Key('chat-row-background'), + message: label, + triggerMode: TooltipTriggerMode.manual, + excludeFromSemantics: true, + child: Semantics( + label: label, + child: _BackgroundBadge(cupertino: cupertino), + ), + ); +} + +/// The badge's own disc in the surface colour, so it reads over any avatar. +class _BadgeDisc extends StatelessWidget { + const _BadgeDisc({required this.cupertino, required this.child}); + + final bool cupertino; + final Widget child; + + @override + Widget build(BuildContext context) { + final background = cupertino + ? CupertinoColors.systemBackground.resolveFrom(context) + : Theme.of(context).colorScheme.surface; + return DecoratedBox( + decoration: BoxDecoration(color: background, shape: BoxShape.circle), + child: Padding(padding: const EdgeInsets.all(2), child: child), + ); + } +} + +class _WorkingBadge extends StatelessWidget { + const _WorkingBadge({required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) { + return _BadgeDisc( + cupertino: cupertino, + child: cupertino + ? const CupertinoActivityIndicator(radius: 6) + : const SizedBox.square( + dimension: 12, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ); + } +} + +class _BackgroundBadge extends StatelessWidget { + const _BackgroundBadge({required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) { + final color = cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + return _BadgeDisc( + cupertino: cupertino, + child: Icon( + cupertino ? CupertinoIcons.ellipsis_circle_fill : Icons.pending, + size: 12, + color: color, + ), + ); + } +} 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 4bfdea62..4e25f709 100644 --- a/app/lib/features/chat/ui/sessions/session_row_content.dart +++ b/app/lib/features/chat/ui/sessions/session_row_content.dart @@ -6,10 +6,12 @@ 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_list_activity.dart'; import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; import 'chat_color_palette.dart'; import 'session_actions.dart'; +import 'session_activity_badge.dart'; import 'session_harness_icon.dart'; import 'session_row_style.dart'; @@ -68,6 +70,9 @@ class ChatSessionRow extends StatelessWidget { leading: ChatSessionAvatar( session: session, running: session['running'] == true && !unseen, + backgroundTasks: session['running'] == true + ? 0 + : chatSessionBackgroundTasks(session), selected: selected, ), // The star rides in the title's own text, so a narrow row ellipsises @@ -149,17 +154,20 @@ class _Star extends StatelessWidget { /// The chat's harness mark in a filled circle, like a contact avatar. A /// running chat carries a small activity badge on the avatar's corner instead -/// of a line of its own; a selected chat's avatar takes the accent fill. +/// of a line of its own, and an idle chat whose background tasks still run a +/// quieter one; a selected chat's avatar takes the accent fill. class ChatSessionAvatar extends StatelessWidget { const ChatSessionAvatar({ super.key, required this.session, this.running = false, + this.backgroundTasks = 0, this.selected = false, }); final JsonMap session; final bool running; + final int backgroundTasks; final bool selected; @override @@ -192,39 +200,12 @@ class ChatSessionAvatar extends StatelessWidget { return AppListAvatar( foreground: mark, background: fill, - badge: running - ? Semantics( - key: const Key('chat-row-working'), - label: 'Chat is working', - child: _WorkingBadge(cupertino: cupertino), - ) - : null, + badge: chatSessionActivityBadge( + cupertino: cupertino, + running: running, + backgroundTasks: backgroundTasks, + ), child: SessionHarnessIcon(session: session, color: mark), ); } } - -class _WorkingBadge extends StatelessWidget { - const _WorkingBadge({required this.cupertino}); - - final bool cupertino; - - @override - Widget build(BuildContext context) { - final background = cupertino - ? CupertinoColors.systemBackground.resolveFrom(context) - : Theme.of(context).colorScheme.surface; - return DecoratedBox( - decoration: BoxDecoration(color: background, shape: BoxShape.circle), - child: Padding( - padding: const EdgeInsets.all(2), - child: cupertino - ? const CupertinoActivityIndicator(radius: 6) - : const SizedBox.square( - dimension: 12, - child: CircularProgressIndicator(strokeWidth: 2), - ), - ), - ); - } -} diff --git a/app/notes/session-list-background-tasks.md b/app/notes/session-list-background-tasks.md index bd62d7da..ef41a1f6 100644 --- a/app/notes/session-list-background-tasks.md +++ b/app/notes/session-list-background-tasks.md @@ -1,35 +1,58 @@ -# Session list: background-task indicator (blocked on server data) +# Session list: turn and background-task indicators -Request: show a quieter indicator on a chat list row when the turn is not running -but the session still has live background work (shells, Claude background Bash, -subagents). The turn spinner would win. +Request: besides the turn spinner, show a quieter indicator on a chat list row +when the turn is idle but the session still runs background work (shells, +Claude Code background Bash and Agent/Task subagents, Codex command executions, +OpenCode shells). Also make the spinner reliable for every listed chat, not +only chats this connection opened. -Not implemented. The client cannot know this per listed chat without guessing. +Implemented, with an approved server change. -## What exists -- Background work is modelled server-side as shells for all three harnesses - (OpenCode shell API, Codex `commandExecution` items, Claude background Bash - and Agent/Task in `internal/claude/translate.go`). -- `chat_event` kind `shell` frames: sent only to subscribers of that session's - room (`chatHub.emitRoom`, `internal/server/chat_room.go`). The app subscribes - only the chat it opens; subscriptions end when the socket closes. -- `chat_shells` (`handleChatShells`, `internal/server/chat_shell_output.go`): - an on-demand per-session readback. It is not pushed, and for Codex/Claude it - goes through `chatManager.harness`, which can start the harness. +## Server +- `protocol.ChatSession.Activity` (`activity`: `turn_running`, + `background_tasks`, `seq`) is set on every `chat_sessions` row from the hub's + own state (`internal/server/chat_activity.go`, `handleChatSessions`). +- `chat_activity` is pushed to every connection (through `chatSessionChanges`) + when a session's turn starts or ends or its running-shell count changes. It + is computed under the hub mutex at those points only: turn admitted or + finished, step frames, shell frames, shell readback, and room release. Text + and tool chunks never push. `seq` starts from the wall clock in microseconds, + so it orders across a restart. +- Keep-alive: `keepUnattendedLocked` keeps an unwatched room while it holds + running shells, so their exits are seen and the badge clears. When the last + shell exits, the room is released at once (`emitRoom`) or by the reaper. + Bounds: the existing 16-room unattended cap, the 6-hour + `chatUnattendedTurnLimit` (measured from when the room became unattended), + and the harness itself. A Claude Code process exit now reports its running + background tasks as exited (`processExit`, `internal/claude`). A released + room reports 0 tasks rather than a stale count. -## What is missing -- `protocol.ChatSession` (`internal/protocol/chat.go`) has no background field, - and `handleChatSessions` (`internal/server/chat_sessions.go`) sets none. -- No push to every connection when a session's running-shell set changes - (`chat_session_changed` goes to all connections but carries no such field). -- `keepUnattendedLocked` (`internal/server/chat_unattended.go`) does not keep a - room alive for running shells, so after the last viewer leaves the server stops - observing that session's shell exits. +## App +- `ChatSessionsController` applies `chat_activity` and row `activity` by `seq` + (the larger wins), deriving `running` and `background_tasks` on the row. + The list re-reads on reconnect (the existing `syncToken`). A server without + `activity` leaves the list as before. +- `session_activity_badge.dart`: the turn spinner, or, when idle with tasks, + a muted `Icons.pending` / `CupertinoIcons.ellipsis_circle_fill` glyph with + tooltip and semantics "Background tasks running (N)". The tooltip shows on + hover only (`TooltipTriggerMode.manual`), so a touch long press stays the + row's own gesture. +- Fixture: `?chats=N&activity=1` in the capture app lists one running chat, + one with two background tasks and idle chats (`tool/perf/perf_fixture.dart`). -A server change that adds a count to the list row, sends it with -`chat_session_changed` (or a dedicated frame) on each running-set change, and keeps -observing sessions with live shells would let the client draw this accurately -through `chatSessionFrameEffect` and `session_row_content.dart`. +## Evidence +- Go: `chat_activity_test.go` covers the list payload, the pushes on turn start + and end and on task start and exit, unattended keep and release on exit, and + expiry of a task that never reports an exit. `background_tasks_test.go` covers + the Claude process exit. +- Flutter: `test/features/chat/ui/sessions/chat_sessions_activity_test.dart`. +- Captures (fixture app): Material phone 560x1000, Material desktop + 1280x900 with the hover tooltip, and Cupertino dark phone. -The existing turn spinner has the same limit: it follows only rooms this connection -subscribed to. +## Unverified +- Real harness behaviour. Shell start and exit events come from each adapter's + existing translation. Whether a real Codex or OpenCode background command + always reports its exit was not exercised against live harnesses here. +- Background Bash outliving a crashed Claude Code CLI. It is reported exited + on process exit, on the assumption that the CLI's tasks end with it. +- Device (Android/iOS) rendering; only the browser was captured. 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 new file mode 100644 index 00000000..63e95324 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_sessions_activity_test.dart @@ -0,0 +1,264 @@ +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/domain/chat_list_activity.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 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +/// The list shows every chat's live activity from the server: a spinner while +/// a turn runs, a quieter badge while only background tasks run, nothing when +/// idle. `chat_activity` pushes reach chats this device never opened, and an +/// older server (no `activity`) leaves the list as before. +JsonMap _row(String id, {JsonMap? activity}) => { + 'id': id, + 'title': 'Chat $id', + 'directory': '/w', + 'updated_at': 1000, + 'activity': ?activity, +}; + +JsonMap _activity({bool turn = false, int tasks = 0, int seq = 1}) => { + if (turn) 'turn_running': true, + if (tasks > 0) 'background_tasks': tasks, + 'seq': seq, +}; + +JsonMap _push( + String id, { + bool turn = false, + int tasks = 0, + required int seq, +}) => { + 'type': 'chat_activity', + 'chat_activity': { + 'session_id': id, + ..._activity(turn: turn, tasks: tasks, seq: seq), + }, +}; + +/// The row merges its semantics, so the badge's label is part of the row's. +Finder _label(int tasks) => find.bySemanticsLabel( + RegExp(RegExp.escape('Background tasks running ($tasks)')), +); + +Finder _badge(String id) => find.descendant( + of: find.byKey(Key('chat-row-$id')), + matching: find.byKey(const Key('chat-row-background')), +); + +Finder _spinner(String id) => find.descendant( + of: find.byKey(Key('chat-row-$id')), + matching: find.byKey(const Key('chat-row-working')), +); + +Future _pump( + WidgetTester tester, + FakeChatGateway fake, { + bool cupertino = false, +}) async { + final screen = ChatSessionsScreen( + gateway: fake, + onOpen: (_) {}, + localStore: MemoryChatSessionLocalStore(), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: screen) + : MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: screen, + ), + ); + // A spinner never settles, so pump a few frames instead. + for (var i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 50)); + } +} + +Future _frames(WidgetTester tester) async { + await tester.pump(); + await tester.pump(); +} + +void main() { + testWidgets( + 'listed activity draws a spinner, a background badge or nothing', + (tester) async { + final fake = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + _row('run', activity: _activity(turn: true, tasks: 1)), + _row('bg', activity: _activity(tasks: 2)), + _row('idle', activity: _activity()), + ], + }; + await _pump(tester, fake); + + expect(_spinner('run'), findsOneWidget); + expect(_badge('run'), findsNothing, reason: 'the turn spinner wins'); + expect(_spinner('bg'), findsNothing); + expect(_badge('bg'), findsOneWidget); + expect(_spinner('idle'), findsNothing); + expect(_badge('idle'), findsNothing); + expect(_label(2), findsOneWidget); + final tooltip = tester.widget(_badge('bg')); + expect(tooltip.message, 'Background tasks running (2)'); + expect(tooltip.triggerMode, TooltipTriggerMode.manual); + expect( + find.descendant(of: _badge('bg'), matching: find.byIcon(Icons.pending)), + findsOneWidget, + ); + expect( + find.descendant( + of: _badge('bg'), + matching: find.byType(CircularProgressIndicator), + ), + findsNothing, + reason: 'the background badge is not a second spinner', + ); + }, + ); + + testWidgets('pushes move a chat this device never opened', (tester) async { + final fake = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [_row('s1', activity: _activity(seq: 10))], + }; + await _pump(tester, fake); + expect(_spinner('s1'), findsNothing); + + fake.pushed.add(_push('s1', turn: true, seq: 11)); + await _frames(tester); + expect(_spinner('s1'), findsOneWidget); + + fake.pushed.add(_push('s1', tasks: 3, seq: 13)); + await _frames(tester); + expect(_spinner('s1'), findsNothing); + expect(_label(3), findsOneWidget); + + // A push older than the snapshot already applied is ignored. + fake.pushed.add(_push('s1', turn: true, seq: 12)); + await _frames(tester); + expect(_spinner('s1'), findsNothing); + expect(_badge('s1'), findsOneWidget); + + fake.pushed.add(_push('s1', seq: 14)); + await _frames(tester); + expect(_badge('s1'), findsNothing); + expect(_spinner('s1'), findsNothing); + expect(fake.count('chat_sessions'), 1); + }); + + testWidgets('an older server without activity keeps the old spinner', ( + tester, + ) async { + final fake = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [_row('s1')], + }; + await _pump(tester, fake); + expect(_badge('s1'), findsNothing); + expect(_spinner('s1'), findsNothing); + fake.pushed.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'kind': 'step', + 'step': {'status': 'started'}, + }, + }); + await _frames(tester); + expect(_spinner('s1'), findsOneWidget); + expect(_badge('s1'), findsNothing); + }); + + testWidgets('the Cupertino host draws its own glyph', (tester) async { + final fake = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [_row('bg', activity: _activity(tasks: 1))], + }; + await _pump(tester, fake, cupertino: true); + expect( + find.descendant( + of: _badge('bg'), + matching: find.byIcon(CupertinoIcons.ellipsis_circle_fill), + ), + findsOneWidget, + ); + expect(_label(1), findsOneWidget); + }); + + group('controller', () { + late FakeChatGateway fake; + late ChatSessionsController controller; + late List rows; + + setUp(() { + fake = FakeChatGateway(); + fake.sessionsHandler = () async => {'chat_sessions': rows}; + controller = ChatSessionsController( + ChatRepository(fake), + localStore: MemoryChatSessionLocalStore(), + ); + }); + tearDown(() => controller.dispose()); + + JsonMap row() => controller.sessions.single; + + test('a list read older than an applied push keeps the push', () async { + rows = [_row('s1', activity: _activity(seq: 5))]; + await controller.refresh(); + fake.pushed.add(_push('s1', tasks: 2, seq: 7)); + await Future.delayed(Duration.zero); + expect(chatSessionBackgroundTasks(row()), 2); + + rows = [_row('s1', activity: _activity(seq: 6))]; + await controller.refresh(); + expect(chatSessionBackgroundTasks(row()), 2); + expect(row()['running'], false); + }); + + test('a newer list read (a reconnect) replaces the pushed state', () async { + rows = [_row('s1', activity: _activity(seq: 5))]; + await controller.refresh(); + fake.pushed.add(_push('s1', turn: true, tasks: 2, seq: 7)); + await Future.delayed(Duration.zero); + expect(row()['running'], true); + + rows = [_row('s1', activity: _activity(seq: 90))]; + await controller.refresh(); + expect(row()['running'], false); + expect(chatSessionBackgroundTasks(row()), 0); + }); + }); + + test('chatListActivityOf reads rows and pushes and refuses malformed', () { + expect( + chatListActivityOf({ + 'turn_running': true, + 'background_tasks': 2, + 'seq': 9, + }, sessionId: 's1'), + (sessionId: 's1', turnRunning: true, backgroundTasks: 2, seq: 9), + ); + expect(chatListActivityOf({'session_id': 's2'}), ( + sessionId: 's2', + turnRunning: false, + backgroundTasks: 0, + seq: 0, + )); + expect(chatListActivityOf({'background_tasks': 1}), isNull); + expect(chatListActivityOf('nope', sessionId: 's1'), isNull); + expect( + chatListActivityOf({ + 'background_tasks': -4, + }, sessionId: 's1')?.backgroundTasks, + 0, + ); + }); +} diff --git a/app/tool/perf/perf_fixture.dart b/app/tool/perf/perf_fixture.dart index 2e3800ed..c74c31fe 100644 --- a/app/tool/perf/perf_fixture.dart +++ b/app/tool/perf/perf_fixture.dart @@ -10,6 +10,8 @@ // 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; +// `?activity=1` (with `?chats=N`) lists a running chat, one with +// background tasks and idle ones; // `?msgs=`, `?rich=1`, `?older=1`, `?live=N` vary the chat transcripts for // scroll captures (tool/perf/chat_scroll_fixture.dart). // `/new` in a fixture chat moves it to a fresh, empty session @@ -32,6 +34,18 @@ int get _chats => int.tryParse(_params['chats'] ?? '') ?? 0; bool get perfRunGraph => _params['graph'] == '1'; bool get _colors => _params['colors'] == '1'; +/// `?activity=1` (with `?chats=N`): the first chat's turn is running, the +/// second is idle with two background tasks, the rest are idle, as the +/// server's `activity` row field reports them. +JsonMap? _activityFor(int i) { + if (_params['activity'] != '1') return null; + return switch (i) { + 0 => {'turn_running': true, 'background_tasks': 1, 'seq': 3}, + 1 => {'background_tasks': 2, 'seq': 2}, + _ => {'seq': 1}, + }; +} + /// `?colors=1`: titles, directories, stars and colours per chat index. const _colorTitles = [ 'Release notes', @@ -58,6 +72,7 @@ JsonMap _chatRow(int i) { if (_harness != 'opencode') 'backend': _harness, 'resume_command': _resumeCommand(id), 'native_export': _harness == 'claude', + 'activity': ?_activityFor(i), }; } final color = _pickedColors.containsKey(id) @@ -72,6 +87,7 @@ JsonMap _chatRow(int i) { 'updated_at': DateTime.now().millisecondsSinceEpoch - (i + 1) * 600000, if (_colorStarred.contains(i)) 'starred': true, 'color': ?color, + 'activity': ?_activityFor(i), }; } diff --git a/internal/server/chat_activity.go b/internal/server/chat_activity.go index a3e150c7..8e769949 100644 --- a/internal/server/chat_activity.go +++ b/internal/server/chat_activity.go @@ -81,7 +81,10 @@ func (h *chatHub) nextActivitySeqLocked() int64 { } // activitySnapshot returns the current summary of each session in ids, each -// with the sequence of its last recorded change (0 when it never changed). +// with the sequence of its last recorded change. A session that has not +// changed since this server started carries the current sequence instead, so +// it still orders after anything a client kept from a previous server process +// and before any later push. func (h *chatHub) activitySnapshot(ids []string) map[string]protocol.ChatActivity { out := make(map[string]protocol.ChatActivity, len(ids)) if h == nil { @@ -89,9 +92,15 @@ func (h *chatHub) activitySnapshot(ids []string) map[string]protocol.ChatActivit } h.mu.Lock() defer h.mu.Unlock() + if h.activitySeq == 0 { + h.activitySeq = time.Now().UnixMicro() + } for _, id := range ids { activity := h.chatActivityLocked(id) - activity.Seq = h.activity[id].Seq + activity.Seq = h.activitySeq + if recorded, ok := h.activity[id]; ok { + activity.Seq = recorded.Seq + } out[id] = activity } return out diff --git a/internal/server/chat_activity_test.go b/internal/server/chat_activity_test.go index 12fab5a9..0fd72740 100644 --- a/internal/server/chat_activity_test.go +++ b/internal/server/chat_activity_test.go @@ -65,13 +65,16 @@ func TestChatActivityReachesEveryConnection(t *testing.T) { viewer := dialChatConn(t, server.ctx, server.srv) list := dialChatConn(t, server.ctx, server.srv) - if got := listActivity(t, server.ctx, list); got == nil || got.TurnRunning || got.BackgroundTasks != 0 { - t.Fatalf("idle row activity = %+v, want an empty summary", got) + // A session that never changed still carries a sequence (this server's + // current one), so it orders after anything kept from an earlier process. + initial := listActivity(t, server.ctx, list) + if initial == nil || initial.TurnRunning || initial.BackgroundTasks != 0 || initial.Seq == 0 { + t.Fatalf("idle row activity = %+v, want an empty summary with a sequence", initial) } sendPrompt(t, server.ctx, viewer, "p1", "build it", "op-1") started := readActivity(t, server.ctx, list) - if started.SessionID != "ses_1" || !started.TurnRunning || started.BackgroundTasks != 0 || started.Seq == 0 { + if started.SessionID != "ses_1" || !started.TurnRunning || started.BackgroundTasks != 0 || started.Seq <= initial.Seq { t.Fatalf("turn start push = %+v", started) } broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_1"))