Mark chats seen after user interaction
Prevent passive open, restored, or unfocused chats from clearing notifications. Track qualifying focused interactions and cover passive and active seen-watermark behavior with tests and notes.
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// Whether the app window is focused and visible: the only state in which a
|
||||
/// chat can be read. A backgrounded or unfocused window never marks a chat
|
||||
/// seen, so a reply that arrives there stays New until the user interacts.
|
||||
class ChatSeenFocus extends ChangeNotifier {
|
||||
ChatSeenFocus({bool focused = true}) {
|
||||
_focused = focused;
|
||||
}
|
||||
|
||||
/// The app's own focus, driven by the framework's lifecycle state. A null
|
||||
/// lifecycle state (before the first report) counts as focused, so a window
|
||||
/// that starts visible is not stuck unread.
|
||||
static final ChatSeenFocus app = ChatSeenFocus._observingApp();
|
||||
|
||||
factory ChatSeenFocus._observingApp() {
|
||||
final focus = ChatSeenFocus(
|
||||
focused: _isFocusedState(WidgetsBinding.instance.lifecycleState),
|
||||
);
|
||||
WidgetsBinding.instance.addObserver(_LifecycleFocus(focus));
|
||||
return focus;
|
||||
}
|
||||
|
||||
late bool _focused;
|
||||
bool get focused => _focused;
|
||||
|
||||
set focused(bool value) {
|
||||
if (value == _focused) return;
|
||||
_focused = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
static bool _isFocusedState(AppLifecycleState? state) =>
|
||||
state == null || state == AppLifecycleState.resumed;
|
||||
}
|
||||
|
||||
class _LifecycleFocus with WidgetsBindingObserver {
|
||||
_LifecycleFocus(this._focus);
|
||||
|
||||
final ChatSeenFocus _focus;
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
_focus.focused = ChatSeenFocus._isFocusedState(state);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ 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_seen_focus.dart';
|
||||
import 'chat_session_local.dart';
|
||||
import 'session_attention.dart';
|
||||
|
||||
@@ -23,8 +24,10 @@ import 'session_attention.dart';
|
||||
/// read watermark are local.
|
||||
///
|
||||
/// With an [AttentionAckSync] (bound to the gateway by the app, or passed in),
|
||||
/// reading is shared: opening a chat acknowledges a `chat_seen` watermark to
|
||||
/// every device, and a watermark acknowledged elsewhere that is newer than this
|
||||
/// reading is shared: a user interaction with a chat (opening it, or acting in
|
||||
/// its pane while the window is focused, see [reportInteraction]) acknowledges
|
||||
/// a `chat_seen` watermark to every device. Being visible, restored or
|
||||
/// receiving a reply never does. A watermark acknowledged elsewhere that is newer than this
|
||||
/// device's own clears the chat's New badge here. The local store remains the
|
||||
/// offline cache of both.
|
||||
class ChatSessionsController extends ChangeNotifier {
|
||||
@@ -33,8 +36,10 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
ChatSessionLocalStore? localStore,
|
||||
AttentionAckSync? ackSync,
|
||||
int Function()? nowMillis,
|
||||
ChatSeenFocus? seenFocus,
|
||||
this.activeAckDelay = const Duration(milliseconds: 1500),
|
||||
}) : _localStore =
|
||||
}) : _focus = seenFocus ?? ChatSeenFocus.app,
|
||||
_localStore =
|
||||
localStore ??
|
||||
(repository.gateway is FederatedChatGateway
|
||||
? FederatedChatSessionLocalStore(
|
||||
@@ -46,12 +51,27 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
),
|
||||
)),
|
||||
_nowMillis = nowMillis ?? _wallClockMillis {
|
||||
_focus.addListener(_focusChanged);
|
||||
_listenFrames();
|
||||
_bindAckSync(ackSync ?? attentionAckSyncOf(repository.gateway));
|
||||
}
|
||||
|
||||
static int _wallClockMillis() => DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
final ChatSeenFocus _focus;
|
||||
|
||||
/// The open chat the user has interacted with while the window was focused.
|
||||
/// Only such a chat acknowledges new content as it arrives; any other reply
|
||||
/// in the open chat stays New until the next interaction. Cleared when the
|
||||
/// window loses focus or another chat becomes the open one.
|
||||
final Set<String> _engaged = {};
|
||||
|
||||
void _focusChanged() {
|
||||
if (_focus.focused) return;
|
||||
_engaged.clear();
|
||||
_cancelPendingActiveAck();
|
||||
}
|
||||
|
||||
/// How long the open chat stays quiet before its new content is
|
||||
/// acknowledged to the other devices; streaming text arrives in many frames.
|
||||
final Duration activeAckDelay;
|
||||
@@ -61,6 +81,8 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
final int Function() _nowMillis;
|
||||
AttentionAckSync? _ackSync;
|
||||
Timer? _activeAck;
|
||||
// The chat whose quiet-period acknowledgement [_activeAck] is waiting on.
|
||||
String? _pendingAckId;
|
||||
ChatSessionLocal _local = const ChatSessionLocal();
|
||||
final Map<String, String> _actionErrors = {};
|
||||
List<JsonMap> _sessions = const [];
|
||||
@@ -78,7 +100,17 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
// older snapshot that arrives later never replaces it.
|
||||
final Map<String, ChatListActivity> _activity = {};
|
||||
StreamSubscription<JsonMap>? _frameSubscription;
|
||||
String? activeSessionId;
|
||||
String? _activeSessionId;
|
||||
|
||||
/// The chat open above the list. Opening another chat ends the engagement
|
||||
/// with the previous one; setting the same id changes nothing.
|
||||
String? get activeSessionId => _activeSessionId;
|
||||
set activeSessionId(String? id) {
|
||||
if (id == _activeSessionId) return;
|
||||
_activeSessionId = id;
|
||||
_engaged.clear();
|
||||
_cancelPendingActiveAck();
|
||||
}
|
||||
|
||||
void _listenFrames() {
|
||||
_frameSubscription?.cancel();
|
||||
@@ -98,8 +130,14 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
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));
|
||||
if (effect.attention && id == activeSessionId) _scheduleActiveAck(id);
|
||||
if (!effect.attention) return;
|
||||
if (id == activeSessionId && _focus.focused && _engaged.contains(id)) {
|
||||
_scheduleActiveAck(id);
|
||||
} else {
|
||||
// Passive: the window is unfocused, or the chat was open with no
|
||||
// interaction since, so the reply is New until the user acts.
|
||||
unawaited(_markUnseen(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Another device changed a chat's shared colour, star or title: the row
|
||||
@@ -210,12 +248,45 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
void _scheduleActiveAck(String id) {
|
||||
if (_ackSync == null) return;
|
||||
_activeAck?.cancel();
|
||||
_pendingAckId = id;
|
||||
_activeAck = Timer(activeAckDelay, () {
|
||||
if (_disposed || id != activeSessionId) return;
|
||||
_activeAck = null;
|
||||
_pendingAckId = null;
|
||||
// Losing focus or the chat during the quiet period ends the engagement;
|
||||
// [_cancelPendingActiveAck] has already marked the reply New by then.
|
||||
if (_disposed || id != activeSessionId || !_engaged.contains(id)) return;
|
||||
unawaited(_acknowledgeSeen(id, 0));
|
||||
});
|
||||
}
|
||||
|
||||
/// Ends a quiet period that has not fired yet. The reply it was waiting on
|
||||
/// arrived while the user was engaged, but the engagement ends before the
|
||||
/// quiet period does, so that reply is marked New here rather than dropped.
|
||||
void _cancelPendingActiveAck() {
|
||||
final pending = _pendingAckId;
|
||||
if (pending == null) return;
|
||||
_activeAck?.cancel();
|
||||
_activeAck = null;
|
||||
_pendingAckId = null;
|
||||
unawaited(_markUnseen(pending));
|
||||
}
|
||||
|
||||
/// The user acted in [id]: a click, tap, scroll, key press in its pane, or
|
||||
/// opening it. Only while the window is focused; a passive state is ignored.
|
||||
/// Everything up to the latest message is marked seen and acknowledged to
|
||||
/// every device. Repeated interactions (every scroll tick) send nothing once
|
||||
/// the chat is engaged and has no unread content.
|
||||
void reportInteraction(String id) {
|
||||
if (_disposed || id.isEmpty || !_focus.focused) return;
|
||||
final firstInChat = id == activeSessionId && _engaged.add(id);
|
||||
if (!firstInChat && !_local.isUnseen(id)) return;
|
||||
final row = _sessions.where((row) => '${row['id'] ?? ''}' == id);
|
||||
final updatedAt = row.isEmpty
|
||||
? 0
|
||||
: chatSessionMillis(row.first['updated_at']);
|
||||
unawaited(_acknowledgeSeen(id, updatedAt));
|
||||
}
|
||||
|
||||
/// Applies watermarks acknowledged on any device: one newer than this
|
||||
/// device's own marks the chat read here (clearing its New badge) and raises
|
||||
/// the local watermark, so a later badge is not cleared by the same ack.
|
||||
@@ -265,9 +336,9 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
|
||||
Future<void> _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;
|
||||
// Loading device preferences may race an operator engaging this chat. The
|
||||
// interaction is authoritative even when the triggering frame arrived first.
|
||||
if (_disposed || (id == activeSessionId && _engaged.contains(id))) return;
|
||||
final next = _local.markUnseen(id);
|
||||
if (identical(next, _local)) return;
|
||||
_local = next;
|
||||
@@ -443,11 +514,15 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Records that this device has read [session]'s current recency.
|
||||
/// Records that this device has read [session]'s current recency. Called
|
||||
/// only for the user's own open (a list row, a shortcut, a notification), so
|
||||
/// it also engages the chat. Showing a chat that was already open, such as a
|
||||
/// restored layout, never calls this.
|
||||
Future<void> markOpened(JsonMap session) async {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
if (id.isEmpty) return;
|
||||
activeSessionId = id;
|
||||
if (_focus.focused) _engaged.add(id);
|
||||
await _ensureLocal();
|
||||
if (_disposed) return;
|
||||
final updatedAt = chatSessionMillis(session['updated_at']);
|
||||
@@ -564,6 +639,7 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
unawaited(_frameSubscription?.cancel());
|
||||
_activeAck?.cancel();
|
||||
_ackSync?.removeListener(_ackChanged);
|
||||
_focus.removeListener(_focusChanged);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +112,6 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
final _search = TextEditingController();
|
||||
late final ChatSectionFolds _folds = widget.folds ?? ChatSectionFolds();
|
||||
Timer? _undoTimer;
|
||||
String? _markedActiveSessionId;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -123,7 +122,6 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
/// Reports the loaded rows at the end of the frame: the destination learns a
|
||||
/// routed row without this screen calling back inside its own build.
|
||||
void _reportSessions() {
|
||||
_markActiveSessionRead();
|
||||
if (widget.onSessions == null) return;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
@@ -131,28 +129,10 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
});
|
||||
}
|
||||
|
||||
void _markActiveSessionRead() {
|
||||
final id = widget.activeSessionId;
|
||||
if (id == null) {
|
||||
_markedActiveSessionId = null;
|
||||
return;
|
||||
}
|
||||
if (id == _markedActiveSessionId) return;
|
||||
for (final session in _controller.sessions) {
|
||||
if (_sessionId(session) != id) continue;
|
||||
// Mark synchronously so row activation and subsequent list notifications
|
||||
// cannot write the same read watermark twice.
|
||||
_markedActiveSessionId = id;
|
||||
unawaited(_controller.markOpened(session));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
_controller.activeSessionId = widget.activeSessionId;
|
||||
_markActiveSessionRead();
|
||||
if (oldWidget.gateway != widget.gateway) {
|
||||
_controller.replaceRepository(ChatRepository(widget.gateway));
|
||||
} else if (oldWidget.syncToken != widget.syncToken) {
|
||||
@@ -252,10 +232,8 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
if (session != null && mounted) widget.onOpen(session);
|
||||
}
|
||||
|
||||
void _markOpened(JsonMap session) {
|
||||
_markedActiveSessionId = _sessionId(session);
|
||||
unawaited(_controller.markOpened(session));
|
||||
}
|
||||
void _markOpened(JsonMap session) =>
|
||||
unawaited(_controller.markOpened(session));
|
||||
|
||||
void _openBeside(JsonMap session) {
|
||||
_markOpened(session);
|
||||
|
||||
Reference in New Issue
Block a user