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:
2026-11-12 02:25:09 +00:00
parent e4f3ebdcab
commit 746e23788d
10 changed files with 1013 additions and 65 deletions
+3 -1
View File
@@ -374,7 +374,9 @@ class _PipelinesAppState extends State<PipelinesApp>
},
sessionTitle: _chatSessionTitle,
openChat: (id) {
if (mounted) _delegate.goTo(AppRoute.chatSession(id));
if (!mounted) return;
widget.servers?.requestChatOpen(id);
_delegate.goTo(AppRoute.chatSession(id));
},
bridge: _notifications.bridge,
);
+36 -29
View File
@@ -5,6 +5,7 @@ import '../../core/servers/server_context.dart';
import '../../shell/destination.dart';
import '../../shell/detail_page.dart';
import 'chat_runtime.dart';
import 'conversation/chat_seen_interaction.dart';
import 'conversation/chat_thread_view.dart';
import 'conversation/composer_focus_request.dart';
import 'workspace/chat_pane_commands.dart';
@@ -79,36 +80,42 @@ Widget buildChatPaneContent({
child: ServerContext.forServer(
context,
runtime.serverIdFor(sessionId),
ChatThreadView(
key: ValueKey<String>('chat-session-$sessionId'),
gateway: runtime.gatewayFor(sessionId),
ChatSeenInteraction(
sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(),
session: row,
syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts,
initialNotice: start != null && start.id == sessionId
? start.notice
: null,
onBack: placement.onBack,
onModelChanged: (applied) =>
runtime.modelChanged(sessionId, applied),
onModeChanged: (mode, name) =>
runtime.acceptMode(sessionId, mode, name),
onEffortChanged: (state) => runtime.acceptEffort(sessionId, state),
onNewSession: placement.onNewSession,
onSessionRenamed: (title) => runtime.acceptRename(sessionId, title),
onSessionClosed: placement.onSessionClosed,
onColorSelected: (color) =>
runtime.sessions.setColor(sessionId, color),
onNextChat: placement.onNextChat,
useNativeBack: placement.useNativeBack,
pasteTarget: placement.pasteTarget,
ownsPasteWhenFocused: placement.ownsPasteWhenFocused,
showBackButton: placement.showBackButton,
paneControls: placement.paneControls?.call(context) ?? const [],
paneCommands: placement.paneCommands,
onInteract: () => runtime.sessions.reportInteraction(sessionId),
child: ChatThreadView(
key: ValueKey<String>('chat-session-$sessionId'),
gateway: runtime.gatewayFor(sessionId),
sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(),
session: row,
syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts,
initialNotice: start != null && start.id == sessionId
? start.notice
: null,
onBack: placement.onBack,
onModelChanged: (applied) =>
runtime.modelChanged(sessionId, applied),
onModeChanged: (mode, name) =>
runtime.acceptMode(sessionId, mode, name),
onEffortChanged: (state) =>
runtime.acceptEffort(sessionId, state),
onNewSession: placement.onNewSession,
onSessionRenamed: (title) =>
runtime.acceptRename(sessionId, title),
onSessionClosed: placement.onSessionClosed,
onColorSelected: (color) =>
runtime.sessions.setColor(sessionId, color),
onNextChat: placement.onNextChat,
useNativeBack: placement.useNativeBack,
pasteTarget: placement.pasteTarget,
ownsPasteWhenFocused: placement.ownsPasteWhenFocused,
showBackButton: placement.showBackButton,
paneControls: placement.paneControls?.call(context) ?? const [],
paneCommands: placement.paneCommands,
),
),
),
);
@@ -0,0 +1,128 @@
import 'package:flutter/rendering.dart' show ScrollDirection;
import 'package:flutter/services.dart'
show HardwareKeyboard, KeyDownEvent, KeyEvent;
import 'package:flutter/widgets.dart';
import '../../../core/servers/server_context.dart';
import '../../settings/server_connections.dart';
/// Reports the user's own actions in one open chat, so the chat can be read.
///
/// Counted: a pointer press anywhere in the pane (click or tap, which also
/// makes it the active pane), a user-driven scroll of its transcript, a key
/// press while focus is inside it (typing, Tab), focus arriving in it from a
/// key press outside it (Tab into the pane), and a notification tap that
/// opened it. Showing the pane, rebuilding it, receiving content, or focus
/// moved in code with no key press does not report anything. [onInteract]
/// decides whether the window is focused.
class ChatSeenInteraction extends StatefulWidget {
const ChatSeenInteraction({
super.key,
required this.sessionId,
required this.onInteract,
required this.child,
});
final String sessionId;
final VoidCallback onInteract;
final Widget child;
@override
State<ChatSeenInteraction> createState() => _ChatSeenInteractionState();
}
class _ChatSeenInteractionState extends State<ChatSeenInteraction> {
ServerConnections? _connections;
/// True from a key-down until the next frame. Focus changes are applied in a
/// microtask queued by the key dispatch, which runs before that frame, so a
/// focus change caused by the key sees the flag. A focus change with no key
/// press (restoration, code-driven focus) never does.
bool _keyDownInProgress = false;
@override
void initState() {
super.initState();
HardwareKeyboard.instance.addHandler(_onKeyEvent);
}
bool _onKeyEvent(KeyEvent event) {
if (event is KeyDownEvent && !_keyDownInProgress) {
_keyDownInProgress = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_keyDownInProgress = false;
});
WidgetsBinding.instance.scheduleFrame();
}
return false;
}
void _onFocusChange(bool hasFocus) {
if (hasFocus && _keyDownInProgress) widget.onInteract();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final connections = ServerContext.maybeOf(context)?.notifier;
if (identical(connections, _connections)) return;
_connections?.removeListener(_takeNotificationOpen);
_connections = connections;
connections?.addListener(_takeNotificationOpen);
_takeNotificationOpen();
}
@override
void didUpdateWidget(covariant ChatSeenInteraction oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.sessionId != widget.sessionId) _takeNotificationOpen();
}
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_onKeyEvent);
_connections?.removeListener(_takeNotificationOpen);
super.dispose();
}
/// A notification tap that named this chat is the user opening it. It is
/// reported after the frame, so the list has taken the chat as active first.
void _takeNotificationOpen() {
final connections = _connections;
if (connections == null ||
!connections.takeChatOpenIntent(widget.sessionId)) {
return;
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) widget.onInteract();
});
}
static bool _userScrolled(ScrollNotification notification) =>
(notification is UserScrollNotification &&
notification.direction != ScrollDirection.idle) ||
(notification is ScrollStartNotification &&
notification.dragDetails != null);
@override
Widget build(BuildContext context) => Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) => widget.onInteract(),
child: NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (_userScrolled(notification)) widget.onInteract();
return false;
},
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onFocusChange: _onFocusChange,
onKeyEvent: (node, event) {
if (event is KeyDownEvent) widget.onInteract();
return KeyEventResult.ignored;
},
child: widget.child,
),
),
);
}
@@ -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);
@@ -46,6 +46,23 @@ class ServerConnections extends ChangeNotifier {
return true;
}
String? _chatOpenId;
/// A chat the user opened from a notification. The tap is the user's own
/// interaction, so the chat it opens is read; a route restored without a tap
/// never sets this.
void requestChatOpen(String sessionId) {
_chatOpenId = sessionId;
notifyListeners();
}
/// Consumes the notification open of [sessionId], once.
bool takeChatOpenIntent(String sessionId) {
if (sessionId.isEmpty || sessionId != _chatOpenId) return false;
_chatOpenId = null;
return true;
}
/// Keep the intent outside the app that selecting another machine disposes.
Future<bool> requestNewChat(String id) async {
if (_busy || _disposed) return false;