diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 202f3ef2..03dbb0ae 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -128,6 +128,7 @@ class _ChatScreenState extends State { syncToken: widget.syncToken, onOpen: _open, onSessions: _adoptRows, + activeSessionId: selected, ), ), if (selected != null) diff --git a/app/lib/features/chat/ui/sessions/chat_session_local.dart b/app/lib/features/chat/ui/sessions/chat_session_local.dart index cd5904d1..3a64733d 100644 --- a/app/lib/features/chat/ui/sessions/chat_session_local.dart +++ b/app/lib/features/chat/ui/sessions/chat_session_local.dart @@ -7,18 +7,38 @@ import 'package:shared_preferences/shared_preferences.dart'; /// /// Titles, stars and the closed state are server-owned and deliberately absent. class ChatSessionLocal { - const ChatSessionLocal({this.hidden = const [], this.seenAt = const {}}); + const ChatSessionLocal({ + this.hidden = const [], + this.seenAt = const {}, + this.unseen = const [], + }); final List hidden; final Map seenAt; + final List unseen; bool isHidden(String id) => hidden.contains(id); int watermark(String id) => seenAt[id] ?? 0; + bool isUnseen(String id) => unseen.contains(id); + + ChatSessionLocal markUnseen(String id) { + if (id.trim().isEmpty || unseen.contains(id)) return this; + return ChatSessionLocal( + hidden: hidden, + seenAt: seenAt, + unseen: [...unseen, id], + ); + } + ChatSessionLocal hide(String id) { if (id.isEmpty || hidden.contains(id)) return this; - return ChatSessionLocal(hidden: [...hidden, id], seenAt: seenAt); + return ChatSessionLocal( + hidden: [...hidden, id], + seenAt: seenAt, + unseen: unseen, + ); } ChatSessionLocal restore(String id) { @@ -26,14 +46,23 @@ class ChatSessionLocal { return ChatSessionLocal( hidden: hidden.where((entry) => entry != id).toList(), seenAt: seenAt, + unseen: unseen, ); } /// Advances only for a strictly newer recency, so a stale list read can never /// mark newer activity as already seen. ChatSessionLocal read(String id, int updatedAt) { - if (id.isEmpty || updatedAt <= watermark(id)) return this; - return ChatSessionLocal(hidden: hidden, seenAt: {...seenAt, id: updatedAt}); + final nextUnseen = unseen.where((entry) => entry != id).toList(); + if (id.isEmpty || + (updatedAt <= watermark(id) && nextUnseen.length == unseen.length)) { + return this; + } + return ChatSessionLocal( + hidden: hidden, + seenAt: updatedAt > watermark(id) ? {...seenAt, id: updatedAt} : seenAt, + unseen: nextUnseen, + ); } /// The first sight of a session baselines it, so pre-existing chats are not @@ -46,12 +75,14 @@ class ChatSessionLocal { next = ChatSessionLocal( hidden: next.hidden, seenAt: {...next.seenAt, row.id: row.updatedAt}, + unseen: next.unseen, ); } return next; } - String encode() => jsonEncode({'hidden': hidden, 'seenAt': seenAt}); + String encode() => + jsonEncode({'hidden': hidden, 'seenAt': seenAt, 'unseen': unseen}); static ChatSessionLocal decode(Object? value) { try { @@ -59,6 +90,7 @@ class ChatSessionLocal { if (parsed is! Map) return const ChatSessionLocal(); final hidden = parsed['hidden']; final seenAt = parsed['seenAt']; + final unseen = parsed['unseen']; return ChatSessionLocal( hidden: hidden is List ? hidden.whereType().where((id) => id.isNotEmpty).toList() @@ -70,6 +102,13 @@ class ChatSessionLocal { '${entry.key}': entry.value as int, } : const {}, + unseen: unseen is List + ? unseen + .whereType() + .where((id) => id.trim().isNotEmpty) + .toSet() + .toList() + : const [], ); } catch (_) { return const ChatSessionLocal(); 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 0b688782..57662c41 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -17,7 +17,9 @@ import 'chat_session_local.dart'; class ChatSessionsController extends ChangeNotifier { ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore}) : _localStore = - localStore ?? const SharedPreferencesChatSessionLocalStore(); + localStore ?? const SharedPreferencesChatSessionLocalStore() { + _listenFrames(); + } ChatRepository repository; final ChatSessionLocalStore _localStore; @@ -31,6 +33,42 @@ class ChatSessionsController extends ChangeNotifier { Future? _localLoading; bool _disposed = false; int _generation = 0; + StreamSubscription? _frameSubscription; + String? activeSessionId; + + void _listenFrames() { + _frameSubscription?.cancel(); + _frameSubscription = repository.gateway.frames.listen(_onFrame); + } + + 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)); + } + + Future _markUnseen(String id) async { + await _ensureLocal(); + final next = _local.markUnseen(id); + if (identical(next, _local)) return; + _local = next; + _notify(); + await _persist(); + } List get sessions => [ for (final session in _sessions) @@ -48,6 +86,7 @@ class ChatSessionsController extends ChangeNotifier { bool isUnseen(JsonMap session) { final id = '${session['id'] ?? ''}'; + if (id == activeSessionId) return false; // Closed chats keep their recency from the close, but they are not new // work: both the web list and the Android list suppress unseen there. if (!_localLoaded || @@ -57,6 +96,7 @@ class ChatSessionsController extends ChangeNotifier { session['closed'] == true) { return false; } + if (_local.isUnseen(id)) return true; final updatedAt = chatSessionMillis(session['updated_at']); return updatedAt > 0 && updatedAt > _local.watermark(id); } @@ -64,6 +104,7 @@ class ChatSessionsController extends ChangeNotifier { void replaceRepository(ChatRepository next) { if (identical(next.gateway, repository.gateway)) return; repository = next; + _listenFrames(); refresh(); } @@ -145,6 +186,7 @@ class ChatSessionsController extends ChangeNotifier { Future markOpened(JsonMap session) async { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; + activeSessionId = id; await _ensureLocal(); final next = _local.read(id, chatSessionMillis(session['updated_at'])); if (identical(next, _local)) return; @@ -236,6 +278,7 @@ class ChatSessionsController extends ChangeNotifier { void dispose() { _disposed = true; _generation++; + unawaited(_frameSubscription?.cancel()); super.dispose(); } } 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 6f262d06..8cd7e123 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -23,6 +23,7 @@ class ChatSessionsScreen extends StatefulWidget { this.syncToken = 0, this.onSessions, this.localStore, + this.activeSessionId, }); final ApiGateway gateway; final void Function(JsonMap session) onOpen; @@ -39,6 +40,10 @@ class ChatSessionsScreen extends StatefulWidget { /// title and model facts as a tapped row without a second list request. final ValueChanged>? onSessions; + /// The conversation open above this list, or null when the list is showing. + /// Pushed activity for it is being read, so it never raises a New mark. + final String? activeSessionId; + /// Overrides the device-local hidden/read store in tests. final ChatSessionLocalStore? localStore; @@ -47,10 +52,13 @@ class ChatSessionsScreen extends StatefulWidget { } class _ChatSessionsScreenState extends State { - late final ChatSessionsController _controller = ChatSessionsController( - ChatRepository(widget.gateway), - localStore: widget.localStore, - )..refresh(); + late final ChatSessionsController _controller = + ChatSessionsController( + ChatRepository(widget.gateway), + localStore: widget.localStore, + ) + ..activeSessionId = widget.activeSessionId + ..refresh(); final _search = TextEditingController(); Timer? _undoTimer; @@ -73,6 +81,7 @@ class _ChatSessionsScreenState extends State { @override void didUpdateWidget(covariant ChatSessionsScreen oldWidget) { super.didUpdateWidget(oldWidget); + _controller.activeSessionId = widget.activeSessionId; if (oldWidget.gateway != widget.gateway) { _controller.replaceRepository(ChatRepository(widget.gateway)); } else if (oldWidget.syncToken != widget.syncToken) { 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 new file mode 100644 index 00000000..ce4b7a16 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_sessions_live_new_test.dart @@ -0,0 +1,87 @@ +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_sessions_screen.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +Future _pump( + WidgetTester tester, + FakeChatGateway gateway, { + String? active, +}) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: ChatSessionsScreen( + gateway: gateway, + onOpen: (_) {}, + localStore: _store, + activeSessionId: active, + ), + ), + ); + await tester.pumpAndSettle(); +} + +late MemoryChatSessionLocalStore _store; + +JsonMap _event(String id, {String kind = 'text'}) => { + 'type': 'chat_event', + 'chat_event': {'session_id': id, 'kind': kind}, +}; + +void main() { + setUp(() => _store = MemoryChatSessionLocalStore()); + + FakeChatGateway gateway() => FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + {'id': 's1', 'title': 'First', 'directory': '/w', 'updated_at': 1000}, + ], + }; + + testWidgets('a pushed event marks a background chat New without a refresh', ( + tester, + ) async { + final fake = gateway(); + await _pump(tester, fake); + expect(find.text('New'), findsNothing); + + fake.pushed.add(_event('s1')); + await tester.pumpAndSettle(); + expect(find.text('New'), findsOneWidget); + expect(fake.count('chat_sessions'), 1); + + await tester.tap(find.byKey(const Key('chat-row-s1'))); + await tester.pumpAndSettle(); + expect(find.text('New'), findsNothing); + }); + + testWidgets('usage frames and the open chat never raise New', (tester) async { + final fake = gateway(); + await _pump(tester, fake, active: 's1'); + fake.pushed.add(_event('s1')); + fake.pushed.add(_event('s1', kind: 'usage')); + await tester.pumpAndSettle(); + expect(find.text('New'), findsNothing); + }); + + testWidgets('leaving the conversation lets later activity mark it New', ( + tester, + ) async { + final fake = gateway(); + await _pump(tester, fake); + await tester.tap(find.byKey(const Key('chat-row-s1'))); + await _pump(tester, fake, active: 's1'); + await _pump(tester, fake); + + fake.pushed.add({ + 'type': 'chat_permission', + 'chat_permission': {'session_id': 's1'}, + }); + await tester.pumpAndSettle(); + expect(find.text('New'), findsOneWidget); + }); +} diff --git a/app/test/features/chat/ui/sessions/fake_chat_gateway.dart b/app/test/features/chat/ui/sessions/fake_chat_gateway.dart index dfe51f74..280adc7d 100644 --- a/app/test/features/chat/ui/sessions/fake_chat_gateway.dart +++ b/app/test/features/chat/ui/sessions/fake_chat_gateway.dart @@ -19,8 +19,11 @@ class FakeChatGateway implements ApiGateway { Future Function()? directoriesHandler; Future Function()? backendsHandler; + /// Server-pushed frames; tests add `chat_event` or `chat_permission` here. + final pushed = StreamController.broadcast(); + @override - Stream get frames => const Stream.empty(); + Stream get frames => pushed.stream; @override Future call(String type, [JsonMap fields = const {}]) {