From 985cc35516772d4107378420fda3241a90a2678d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 28 Oct 2026 16:32:33 +0000 Subject: [PATCH] Fix chat session unread attention state --- .../ui/sessions/chat_sessions_controller.dart | 65 +++-- .../chat/ui/sessions/session_attention.dart | 87 +++++++ .../ui/sessions/session_list_cupertino.dart | 1 + .../ui/sessions/session_list_material.dart | 1 + .../chat/ui/sessions/session_row_content.dart | 23 ++ .../chat/ui/sessions/session_row_style.dart | 7 +- .../chat_session_local_state_test.dart | 6 +- .../chat_session_row_layout_test.dart | 4 +- .../sessions/chat_sessions_live_new_test.dart | 240 +++++++++++++++++- .../sessions/session_harness_icon_test.dart | 1 - 10 files changed, 395 insertions(+), 40 deletions(-) create mode 100644 app/lib/features/chat/ui/sessions/session_attention.dart 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 511f6f76..c3477ed1 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/transport/connection_state.dart'; import '../../data/chat_repository.dart'; import '../../domain/chat_sessions.dart'; import 'chat_session_local.dart'; +import 'session_attention.dart'; /// Owns the session list, its refresh generation and the shared row actions. /// @@ -37,6 +38,7 @@ class ChatSessionsController extends ChangeNotifier { Future? _localLoading; bool _disposed = false; int _generation = 0; + Future _persistTail = Future.value(); StreamSubscription? _frameSubscription; String? activeSessionId; @@ -46,27 +48,35 @@ class ChatSessionsController extends ChangeNotifier { } void _onFrame(JsonMap frame) { - final type = frame['type']; - String? id; - if (type == 'chat_event') { - final event = frame['chat_event']; - if (event is! Map || event['kind'] == 'usage') return; - id = event['session_id'] is String ? event['session_id'] as String : null; - } else if (type == 'chat_permission') { - final permission = frame['chat_permission']; - if (permission is! Map) return; - id = permission['session_id'] is String - ? permission['session_id'] as String - : null; - } else { - return; - } - if (id == null || id.isEmpty || id == activeSessionId) return; - unawaited(_markUnseen(id)); + final effect = chatSessionFrameEffect(frame); + if (effect == null) return; + final id = effect.sessionId; + final session = _sessions.where((row) => '${row['id'] ?? ''}' == id); + if (session.isEmpty) return; + final row = session.first; + if (row['closed_at'] != null || row['closed'] == true) return; + if (effect.running != null) _setRunning(id, effect.running!); + if (effect.attention && id != activeSessionId) unawaited(_markUnseen(id)); + } + + void _setRunning(String id, bool running) { + if (_disposed) return; + var changed = false; + _sessions = _sessions.map((session) { + if ('${session['id'] ?? ''}' != id || session['running'] == running) { + return session; + } + changed = true; + return {...session, 'running': running}; + }).toList(); + if (changed) _notify(); } Future _markUnseen(String id) async { await _ensureLocal(); + // Loading device preferences may race an operator opening this chat. The + // open is authoritative even when the triggering frame arrived first. + if (_disposed || id == activeSessionId) return; final next = _local.markUnseen(id); if (identical(next, _local)) return; _local = next; @@ -100,14 +110,12 @@ class ChatSessionsController extends ChangeNotifier { // work: both the web list and the Android list suppress unseen there. if (!_localLoaded || id.isEmpty || - session['running'] == true || session['closed_at'] != null || session['closed'] == true) { return false; } if (_local.isUnseen(id)) return true; - final updatedAt = chatSessionMillis(session['updated_at']); - return updatedAt > 0 && updatedAt > _local.watermark(id); + return false; } void replaceRepository(ChatRepository next) { @@ -221,6 +229,7 @@ class ChatSessionsController extends ChangeNotifier { if (id.isEmpty) return; activeSessionId = id; await _ensureLocal(); + if (_disposed) return; final next = _local.read(id, chatSessionMillis(session['updated_at'])); if (identical(next, _local)) return; _local = next; @@ -309,12 +318,16 @@ class ChatSessionsController extends ChangeNotifier { unawaited(_persist()); } - Future _persist() async { - try { - await _localStore.save(_local); - } catch (_) { - // The in-memory choice still applies for this session. - } + Future _persist() { + final snapshot = _local; + _persistTail = _persistTail.then((_) async { + try { + await _localStore.save(snapshot); + } catch (_) { + // The in-memory choice still applies for this session. + } + }); + return _persistTail; } void _notify() { diff --git a/app/lib/features/chat/ui/sessions/session_attention.dart b/app/lib/features/chat/ui/sessions/session_attention.dart new file mode 100644 index 00000000..279a001a --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_attention.dart @@ -0,0 +1,87 @@ +import '../../../../core/api_gateway.dart'; + +typedef ChatSessionFrameEffect = ({ + String sessionId, + bool attention, + bool? running, +}); + +/// Interprets only authoritative content/action and activity fields from a +/// pushed frame. Recency and unrelated metadata are deliberately not signals. +ChatSessionFrameEffect? chatSessionFrameEffect(JsonMap frame) { + final type = frame['type']; + String? id; + var attention = false; + bool? running; + if (type == 'chat_event') { + final event = frame['chat_event']; + if (event is! Map) return null; + id = event['session_id'] is String ? event['session_id'] as String : null; + final kind = event['kind']; + // A badge means content to read, not transport/activity churn: assistant + // text, another client's user message, a returned tool result, or a pending + // form. Reasoning, starts, steps, shells, compaction and usage are not unread. + if (kind == 'text') { + attention = '${event['delta'] ?? ''}'.isNotEmpty; + } else if (kind == 'user') { + attention = true; + } else if (kind == 'tool') { + final part = event['part']; + final state = part is Map ? part['state'] : null; + if (state is Map) { + final status = state['status']; + attention = + (status == 'completed' || status == 'error') && + ((state['content'] is List && + (state['content'] as List).isNotEmpty) || + state['error'] != null); + if (status == 'running' || status == 'streaming') running = true; + } + } else if (kind == 'form') { + final form = event['form']; + attention = + form is Map && + form['resolved'] != true && + form['cancelled'] != true && + '${form['status'] ?? ''}' != 'resolved' && + '${form['status'] ?? ''}' != 'cancelled'; + } else if (kind == 'step') { + final step = event['step']; + if (step is Map) { + if (step['status'] == 'started' || step['status'] == 'streamed') { + running = true; + } else if (step['status'] == 'ended' && step['intermediate'] != true) { + running = false; + } + } + } else if (kind == 'compaction') { + final compaction = event['compaction']; + if (compaction is Map) { + if (compaction['status'] == 'running') running = true; + if (compaction['status'] == 'completed' || + compaction['status'] == 'failed') { + running = false; + } + } + } else if (kind == 'shell') { + final shell = event['shell']; + if (shell is Map) { + if (shell['status'] == 'running') running = true; + if (shell['status'] == 'exited') running = false; + } + } + } else if (type == 'chat_permission') { + final permission = frame['chat_permission']; + if (permission is! Map) return null; + id = permission['session_id'] is String + ? permission['session_id'] as String + : null; + attention = + permission['resolved'] != true && + '${permission['decision'] ?? ''}'.trim().isEmpty; + } else { + return null; + } + if (id == null || id.isEmpty) return null; + return (sessionId: id, attention: attention, running: running); +} 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 6822264d..3a2621c1 100644 --- a/app/lib/features/chat/ui/sessions/session_list_cupertino.dart +++ b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart @@ -198,6 +198,7 @@ class _CupertinoSessionRow extends StatelessWidget { color: secondary, ), statusStyle: statusStyle, + loading: session['running'] == true && !unseen, ), subtitle: null, onTap: () => onOpen(session), 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 7c2efaa8..fbb31507 100644 --- a/app/lib/features/chat/ui/sessions/session_list_material.dart +++ b/app/lib/features/chat/ui/sessions/session_list_material.dart @@ -200,6 +200,7 @@ class _MaterialSessionRow extends StatelessWidget { theme.textTheme.bodySmall?.copyWith(color: secondary) ?? TextStyle(color: secondary), statusStyle: statusStyle, + loading: session['running'] == true && !unseen, ), subtitle: null, onTap: () => onOpen(session), 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 ba2851cc..f1d74983 100644 --- a/app/lib/features/chat/ui/sessions/session_row_content.dart +++ b/app/lib/features/chat/ui/sessions/session_row_content.dart @@ -18,6 +18,7 @@ class ChatSessionRowContent extends StatelessWidget { required this.titleStyle, required this.metaStyle, required this.statusStyle, + this.loading = false, this.leading, this.actions = const [], }); @@ -29,6 +30,7 @@ class ChatSessionRowContent extends StatelessWidget { final TextStyle titleStyle; final TextStyle metaStyle; final TextStyle statusStyle; + final bool loading; final Widget? leading; final List actions; @@ -80,6 +82,7 @@ class ChatSessionRowContent extends StatelessWidget { children: [ if (status != null) _StatusLabel(status: status!, style: statusStyle), + if (status == null && loading) _LoadingStatus(), for (final line in meta) Text( line, @@ -119,6 +122,26 @@ class ChatSessionRowContent extends StatelessWidget { } } +class _LoadingStatus extends StatelessWidget { + @override + Widget build(BuildContext context) { + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return const Align( + alignment: AlignmentDirectional.centerStart, + child: CupertinoActivityIndicator(radius: 7), + ); + } + return const Align( + alignment: AlignmentDirectional.centerStart, + child: SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ); + } +} + class _StatusLabel extends StatelessWidget { const _StatusLabel({required this.status, required this.style}); diff --git a/app/lib/features/chat/ui/sessions/session_row_style.dart b/app/lib/features/chat/ui/sessions/session_row_style.dart index fac0ddac..11490407 100644 --- a/app/lib/features/chat/ui/sessions/session_row_style.dart +++ b/app/lib/features/chat/ui/sessions/session_row_style.dart @@ -61,15 +61,12 @@ List chatSessionRowMetaLines(JsonMap session, {DateTime? now}) => [ ...chatSessionMetaLines(session), ].where((part) => part.isNotEmpty).toList(); -/// The word on the row's trailing edge while the session has news or a state: -/// `Closed` from the row, otherwise `New`. A streaming session deliberately -/// says nothing, as on the web, where the row's activity logo carries it. +/// The row's attention/state word: `Closed` takes precedence, otherwise only +/// actually unread content is `New`. Loading activity is rendered separately. String? chatSessionRowStatus(JsonMap session, {required bool unseen}) { if (session['closed_at'] != null || session['closed'] == true) { return 'Closed'; } - // Streaming has no word, as on the web; the row's activity icon carries it. - if (session['running'] == true) return null; return unseen ? 'New' : null; } diff --git a/app/test/features/chat/ui/sessions/chat_session_local_state_test.dart b/app/test/features/chat/ui/sessions/chat_session_local_state_test.dart index 09dc3819..a7d61b54 100644 --- a/app/test/features/chat/ui/sessions/chat_session_local_state_test.dart +++ b/app/test/features/chat/ui/sessions/chat_session_local_state_test.dart @@ -39,9 +39,7 @@ void main() { ); }); - testWidgets('New appears only for a recency newer than this device read', ( - tester, - ) async { + testWidgets('updated recency alone does not create New', (tester) async { final gateway = FakeChatGateway(); var updatedAt = 1000; gateway.sessionsHandler = () async => { @@ -60,7 +58,7 @@ void main() { updatedAt = 2000; await tester.tap(find.byKey(const Key('chat-refresh'))); await tester.pumpAndSettle(); - expect(find.text('New'), findsOneWidget); + expect(find.text('New'), findsNothing); await tester.tap(find.byKey(const Key('chat-row-s1'))); await tester.pumpAndSettle(); diff --git a/app/test/features/chat/ui/sessions/chat_session_row_layout_test.dart b/app/test/features/chat/ui/sessions/chat_session_row_layout_test.dart index 7111ceef..dff13697 100644 --- a/app/test/features/chat/ui/sessions/chat_session_row_layout_test.dart +++ b/app/test/features/chat/ui/sessions/chat_session_row_layout_test.dart @@ -129,8 +129,8 @@ void main() { expect(chatSessionRowStatus({}, unseen: false), isNull); expect(chatSessionRowStatus({}, unseen: true), 'New'); - // The web suppresses the streaming word; the row's activity icon carries it. - expect(chatSessionRowStatus({'running': true}, unseen: true), isNull); + // Running never hides an unread message; the native spinner is separate. + expect(chatSessionRowStatus({'running': true}, unseen: true), 'New'); expect(chatSessionRowStatus({'running': true}, unseen: false), isNull); expect( chatSessionRowStatus({'closed_at': '2026-01-01'}, unseen: true), diff --git a/app/test/features/chat/ui/sessions/chat_sessions_live_new_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_live_new_test.dart index ce4b7a16..6d8cafc1 100644 --- a/app/test/features/chat/ui/sessions/chat_sessions_live_new_test.dart +++ b/app/test/features/chat/ui/sessions/chat_sessions_live_new_test.dart @@ -1,7 +1,12 @@ +import 'dart:async'; + +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/ui/sessions/chat_session_local.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 'chat_test_harness.dart'; import 'fake_chat_gateway.dart'; @@ -25,11 +30,42 @@ Future _pump( await tester.pumpAndSettle(); } +Future _pumpCupertino( + WidgetTester tester, + FakeChatGateway gateway, +) async { + await tester.pumpWidget( + CupertinoApp( + home: ChatSessionsScreen( + gateway: gateway, + onOpen: (_) {}, + localStore: _store, + ), + ), + ); + await tester.pumpAndSettle(); +} + late MemoryChatSessionLocalStore _store; -JsonMap _event(String id, {String kind = 'text'}) => { +class _DeferredStore implements ChatSessionLocalStore { + final loaded = Completer(); + ChatSessionLocal? saved; + + @override + Future load() => loaded.future; + + @override + Future save(ChatSessionLocal state) async => saved = state; +} + +JsonMap _event(String id, {String kind = 'text', String? delta}) => { 'type': 'chat_event', - 'chat_event': {'session_id': id, 'kind': kind}, + 'chat_event': { + 'session_id': id, + 'kind': kind, + if (kind == 'text') 'delta': delta ?? 'hello', + }, }; void main() { @@ -84,4 +120,204 @@ void main() { await tester.pumpAndSettle(); expect(find.text('New'), findsOneWidget); }); + + testWidgets('step and reasoning churn show loading, not New', (tester) async { + final fake = gateway(); + await _pump(tester, fake); + fake.pushed.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'kind': 'step', + 'step': {'status': 'started'}, + }, + }); + await tester.pump(); + await tester.pump(); + expect(find.text('New'), findsNothing); + expect( + tester + .widget(find.byType(ChatSessionRowContent)) + .loading, + isTrue, + ); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + + fake.pushed.add(_event('s1', kind: 'reasoning', delta: 'thinking')); + await tester.pump(); + await tester.pump(); + expect(find.text('New'), findsNothing); + expect(fake.count('chat_sessions'), 1); + + fake.pushed.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'kind': 'step', + 'step': {'status': 'ended'}, + }, + }); + await tester.pump(); + await tester.pump(); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(find.text('New'), findsNothing); + }); + + testWidgets('an unread visible answer remains New while running', ( + tester, + ) async { + final fake = gateway(); + await _pump(tester, fake); + fake.pushed.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'kind': 'step', + 'step': {'status': 'started'}, + }, + }); + fake.pushed.add(_event('s1')); + await tester.pumpAndSettle(); + expect(find.text('New'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + + testWidgets('tool starts are loading; returned tool results are unread', ( + tester, + ) async { + final fake = gateway(); + await _pump(tester, fake); + fake.pushed.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'kind': 'tool', + 'part': { + 'type': 'tool', + 'state': {'status': 'running'}, + }, + }, + }); + await tester.pump(); + await tester.pump(); + expect(find.text('New'), findsNothing); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + + fake.pushed.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'kind': 'tool', + 'part': { + 'type': 'tool', + 'state': { + 'status': 'completed', + 'content': [ + {'type': 'text', 'text': 'command output'}, + ], + }, + }, + }, + }); + await tester.pumpAndSettle(); + expect(find.text('New'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + + testWidgets('only unresolved permission requests mark New', (tester) async { + final fake = gateway(); + await _pump(tester, fake); + fake.pushed.add({ + 'type': 'chat_permission', + 'chat_permission': { + 'session_id': 's1', + 'request_id': 'p1', + 'resolved': true, + 'decision': 'once', + }, + }); + await tester.pumpAndSettle(); + expect(find.text('New'), findsNothing); + fake.pushed.add({ + 'type': 'chat_permission', + 'chat_permission': {'session_id': 's1', 'request_id': 'p2'}, + }); + await tester.pumpAndSettle(); + expect(find.text('New'), findsOneWidget); + }); + + testWidgets('updated_at alone never manufactures unread state', ( + tester, + ) async { + final fake = gateway(); + await _pump(tester, fake); + fake.sessionsReply = { + 'chat_sessions': [ + {'id': 's1', 'title': 'First', 'directory': '/w', 'updated_at': 2000}, + ], + }; + // A server refresh may report newer recency without telling us what arrived. + await tester.tap(find.byKey(const Key('chat-refresh'))); + await tester.pumpAndSettle(); + fake.pushed.add(_event('unknown')); + await tester.pumpAndSettle(); + expect(find.text('New'), findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + fake.pushed.add(_event('s1')); + await tester.pump(); + }); + + testWidgets('opening wins over an event waiting for local-store load', ( + tester, + ) async { + final fake = gateway(); + final delayed = _DeferredStore(); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: ChatSessionsScreen( + gateway: fake, + onOpen: (_) {}, + localStore: delayed, + ), + ), + ); + await tester.pump(); + await tester.pump(); + fake.pushed.add(_event('s1')); + await tester.pump(); + await tester.tap(find.byKey(const Key('chat-row-s1'))); + delayed.loaded.complete(const ChatSessionLocal()); + await tester.pump(); + await tester.pump(); + expect(find.text('New'), findsNothing); + expect(delayed.saved?.isUnseen('s1'), isFalse); + }); + + testWidgets('Cupertino rows load, mark a real answer New, then read it', ( + tester, + ) async { + final fake = gateway(); + await _pumpCupertino(tester, fake); + fake.pushed.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'kind': 'step', + 'step': {'status': 'started'}, + }, + }); + await tester.pump(); + await tester.pump(); + expect(find.byType(CupertinoActivityIndicator), findsOneWidget); + expect(find.text('New'), findsNothing); + + fake.pushed.add(_event('s1')); + await tester.pumpAndSettle(); + expect(find.text('New'), findsOneWidget); + await tester.tap(find.byKey(const Key('chat-row-s1'))); + await tester.pump(); + await tester.pump(); + expect(find.text('New'), findsNothing); + }); } diff --git a/app/test/features/chat/ui/sessions/session_harness_icon_test.dart b/app/test/features/chat/ui/sessions/session_harness_icon_test.dart index af6763e9..95ef8772 100644 --- a/app/test/features/chat/ui/sessions/session_harness_icon_test.dart +++ b/app/test/features/chat/ui/sessions/session_harness_icon_test.dart @@ -23,7 +23,6 @@ void main() { 'title': 'Harness chat', 'backend': backend, 'starred': starred, - 'running': true, }, ], ),