Sync Needs-you dismissals and chat read state across devices

This commit is contained in:
2026-10-31 12:47:25 +00:00
parent f4b3ef17cc
commit d1aa36163a
12 changed files with 1164 additions and 14 deletions
@@ -0,0 +1,110 @@
import 'dart:convert';
import '../../../core/api_gateway.dart';
/// The server-shared "I have seen this" state (`attention_acks` on the wire):
/// dismissed Needs-you identities (`{runId}:{kind}`) and per-chat-session
/// read watermarks in epoch milliseconds.
///
/// The set only grows — dismissals are added and watermarks only advance — so
/// merging is a union/maximum and applying a frame twice or out of order is
/// harmless. The same shape is used for the whole set, a pushed delta and the
/// offline queue of acknowledgements not yet accepted by the server.
class AttentionAcks {
const AttentionAcks({this.dismissed = const {}, this.chatSeen = const {}});
final Set<String> dismissed;
final Map<String, int> chatSeen;
bool get isEmpty => dismissed.isEmpty && chatSeen.isEmpty;
int get length => dismissed.length + chatSeen.length;
/// The union of both sets, keeping the larger watermark per session.
/// Returns this instance when [other] adds nothing.
AttentionAcks merge(AttentionAcks other) {
final addsDismissal = !dismissed.containsAll(other.dismissed);
final advances = other.chatSeen.entries.any(
(entry) => entry.value > (chatSeen[entry.key] ?? 0),
);
if (!addsDismissal && !advances) return this;
final seen = {...chatSeen};
other.chatSeen.forEach((id, at) {
if (at > (seen[id] ?? 0)) seen[id] = at;
});
return AttentionAcks(
dismissed: {...dismissed, ...other.dismissed},
chatSeen: seen,
);
}
/// What remains of this queue after [sent] was accepted: a dismissal is
/// gone once sent, a watermark only when no newer value was queued since.
AttentionAcks without(AttentionAcks sent) => AttentionAcks(
dismissed: dismissed.difference(sent.dismissed),
chatSeen: {
for (final entry in chatSeen.entries)
if (entry.value > (sent.chatSeen[entry.key] ?? 0))
entry.key: entry.value,
},
);
/// The wire body of `ack_attention` / the stored queue.
JsonMap toJson() {
final keys = dismissed.toList()..sort();
return {'dismissed': keys, 'chat_seen': chatSeen};
}
String encode() => jsonEncode(toJson());
/// Total decode of a wire or stored value: unreadable members are skipped
/// and a malformed value is the empty set, never an exception.
static AttentionAcks fromJson(Object? value) {
if (value is! Map) return const AttentionAcks();
final dismissed = value['dismissed'];
final chatSeen = value['chat_seen'];
return AttentionAcks(
dismissed: {
if (dismissed is List)
for (final key in dismissed)
if (key is String && key.isNotEmpty) key,
},
chatSeen: {
if (chatSeen is Map)
for (final entry in chatSeen.entries)
if (entry.key is String &&
entry.value is num &&
(entry.value as num) > 0)
entry.key as String: (entry.value as num).toInt(),
},
);
}
static AttentionAcks decode(String? stored) {
final text = (stored ?? '').trim();
if (text.isEmpty) return const AttentionAcks();
try {
return fromJson(jsonDecode(text));
} catch (_) {
return const AttentionAcks();
}
}
}
/// The server's bound on one `ack_attention`; a larger queue is sent in parts.
const maxAttentionAckItems = 500;
/// The first [limit] items of [acks], dismissals first, for one request.
AttentionAcks attentionAckBatch(
AttentionAcks acks, {
int limit = maxAttentionAckItems,
}) {
if (acks.length <= limit) return acks;
final keys = acks.dismissed.toList()..sort();
final dismissed = keys.take(limit).toSet();
final room = limit - dismissed.length;
return AttentionAcks(
dismissed: dismissed,
chatSeen: Map.fromEntries(acks.chatSeen.entries.take(room)),
);
}
@@ -0,0 +1,66 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../../../core/servers/server_scope.dart';
/// Persistence for acknowledgements made while the server could not take
/// them (offline, or a server without `ack_attention`). The value is the
/// opaque string from `AttentionAcks.encode`; both directions may fail, and a
/// failure only means the queue lives in memory for this session.
abstract interface class AttentionAckQueueStore {
Future<String?> read();
Future<bool> write(String value);
}
/// `shared_preferences` storage scoped to the server, like the other device
/// caches. An unavailable plugin returns null/false instead of throwing.
class SharedPreferencesAttentionAckQueue implements AttentionAckQueueStore {
const SharedPreferencesAttentionAckQueue({this.serverId = ''});
static const key = 'pipelines.next.attention.pending_acks.v1';
final String serverId;
String get _key => scopedServerKey(key, serverId);
Future<SharedPreferences?> _preferences() async {
try {
return await SharedPreferences.getInstance();
} catch (_) {
return null;
}
}
@override
Future<String?> read() async {
try {
return (await _preferences())?.getString(_key);
} catch (_) {
return null;
}
}
@override
Future<bool> write(String value) async {
try {
return await (await _preferences())?.setString(_key, value) ?? false;
} catch (_) {
return false;
}
}
}
/// An in-memory queue for tests and isolated fixtures.
class MemoryAttentionAckQueue implements AttentionAckQueueStore {
MemoryAttentionAckQueue({this.stored});
String? stored;
@override
Future<String?> read() async => stored;
@override
Future<bool> write(String value) async {
stored = value;
return true;
}
}
@@ -0,0 +1,239 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../../../core/transport/connection_state.dart';
import '../domain/attention_acks.dart';
import 'attention_ack_queue.dart';
/// Keeps this device's attention acknowledgements in step with the server so
/// clearing on one device clears everywhere.
///
/// [acks] is everything known to be acknowledged: the server's set, every
/// pushed `attention_acks_changed` delta and this device's own acknowledgements
/// (applied at once, before the server answers). Listeners — the Needs-you
/// controller and the chat list — fold it into their own state.
///
/// An acknowledgement the server has not accepted yet stays in a persisted
/// queue and is re-sent on the next [connected]. A server refusal drops the
/// refused batch (it can never succeed); a server that does not know
/// `ack_attention` keeps the queue for a later upgrade and this device falls
/// back to its local state.
///
/// With [sendOnly] (the app passes the socket's own send-only path, as the
/// run watch does) requests are not queued behind the transport's serialized
/// request/reply calls, so a connect-time read never delays the first screen's
/// list; the reply is matched by id from the pushed frames.
class AttentionAckSync extends ChangeNotifier {
AttentionAckSync({
required this.gateway,
required this.queue,
this.sendOnly,
this.replyTimeout = const Duration(seconds: 30),
}) {
_frames = gateway.frames.listen(_onFrame);
}
final ApiGateway gateway;
final AttentionAckQueueStore queue;
final String Function(String type, JsonMap fields)? sendOnly;
final Duration replyTimeout;
late final StreamSubscription<JsonMap> _frames;
final Map<String, Completer<JsonMap>> _replies = {};
AttentionAcks _acks = const AttentionAcks();
AttentionAcks _pending = const AttentionAcks();
Future<void>? _loading;
Future<void>? _flushing;
bool _supported = true;
bool _disposed = false;
/// Everything acknowledged on any device, as far as this device knows.
AttentionAcks get acks => _acks;
/// Acknowledgements made here that the server has not accepted yet.
AttentionAcks get pending => _pending;
/// False after the server answered `attention_acks` with something else
/// (an older server); reset on the next [connected].
bool get supported => _supported;
/// Reads the persisted offline queue once.
Future<void> load() => _loading ??= _load();
Future<void> _load() async {
String? stored;
try {
stored = await queue.read();
} catch (_) {
stored = null;
}
if (_disposed) return;
final queued = AttentionAcks.decode(stored);
_pending = queued.merge(_pending);
_apply(queued);
}
/// Records an acknowledgement made on this device: it applies here at once
/// and is sent to the server (now, or on the next [connected]).
Future<void> acknowledge({
Iterable<String> dismissed = const [],
Map<String, int> chatSeen = const {},
}) async {
final ack = AttentionAcks(
dismissed: {
for (final key in dismissed)
if (key.trim().isNotEmpty) key,
},
chatSeen: {
for (final entry in chatSeen.entries)
if (entry.key.isNotEmpty && entry.value > 0) entry.key: entry.value,
},
);
if (_disposed || ack.isEmpty) return;
await load();
if (_disposed) return;
_pending = _pending.merge(ack);
_apply(ack);
await _persist();
await flush();
}
/// Called on every connected transition of the shared socket: send what was
/// queued while disconnected, then read the server's whole set.
Future<void> connected() async {
if (_disposed) return;
_supported = true;
// Replies still awaited belong to the replaced socket and never arrive;
// fail them now so a stalled flush does not hold up this connection.
_failReplies(StateError('Connection replaced'));
await load();
await flush();
if (_disposed || !_supported) return;
try {
final reply = await _request('attention_acks');
_accept(reply);
} catch (_) {
// Offline or refused: the local state still applies; the next
// connection reads again.
}
}
/// Sends the queue in bounded batches, one request at a time.
Future<void> flush() => _flushing ??= _flush().whenComplete(() {
_flushing = null;
});
Future<void> _flush() async {
while (!_disposed && _supported && !_pending.isEmpty) {
final batch = attentionAckBatch(_pending);
try {
final reply = await _request('ack_attention', {
'attention_acks': batch.toJson(),
});
if (!_accept(reply)) return;
} on ProtocolError {
// The server refused this batch; it will never be accepted.
} catch (_) {
return; // Not connected or timed out: keep it for the next connection.
}
_pending = _pending.without(batch);
await _persist();
}
}
/// Folds an `attention_acks` reply; false when the server answered with
/// another type, i.e. it does not support shared acknowledgements.
bool _accept(JsonMap reply) {
if (reply['type'] != 'attention_acks') {
_supported = false;
return false;
}
_apply(AttentionAcks.fromJson(reply['attention_acks']));
return true;
}
void _onFrame(JsonMap frame) {
final id = frame['id'];
final reply = id is String ? _replies.remove(id) : null;
if (reply != null) {
if (frame['type'] == 'error') {
final reason = '${frame['error'] ?? ''}'.trim();
reply.completeError(
ProtocolError(reason.isEmpty ? 'server error' : reason),
);
} else {
reply.complete(frame);
}
return;
}
if (frame['type'] != 'attention_acks_changed') return;
_apply(AttentionAcks.fromJson(frame['attention_acks']));
}
/// One request: through [sendOnly] when available (reply matched by id),
/// else the gateway's ordinary request/reply call.
Future<JsonMap> _request(String type, [JsonMap fields = const {}]) {
final send = sendOnly;
if (send == null) return gateway.call(type, fields);
final String id;
try {
id = send(type, fields);
} catch (error) {
return Future.error(error);
}
final reply = Completer<JsonMap>();
_replies[id] = reply;
return reply.future.timeout(
replyTimeout,
onTimeout: () {
_replies.remove(id);
throw TimeoutException('$type timed out', replyTimeout);
},
);
}
void _apply(AttentionAcks incoming) {
if (_disposed) return;
final next = _acks.merge(incoming);
if (identical(next, _acks)) return;
_acks = next;
notifyListeners();
}
Future<void> _persist() async {
try {
await queue.write(_pending.encode());
} catch (_) {
// The queue still lives in memory for this session.
}
}
@override
void dispose() {
_disposed = true;
unawaited(_frames.cancel());
_failReplies(StateError('Attention sync disposed'));
super.dispose();
}
void _failReplies(Object error) {
final waiting = _replies.values.toList();
_replies.clear();
for (final reply in waiting) {
reply.completeError(error);
}
}
}
final _syncs = Expando<AttentionAckSync>('attention acknowledgement sync');
/// Makes [sync] the acknowledgement channel of [gateway], so feature
/// controllers created later for the same socket (the chat list) share it.
void bindAttentionAckSync(ApiGateway gateway, AttentionAckSync? sync) {
_syncs[gateway] = sync;
}
/// The acknowledgement channel bound to [gateway], if the app bound one.
AttentionAckSync? attentionAckSyncOf(ApiGateway gateway) => _syncs[gateway];
@@ -6,6 +6,7 @@ import '../../../core/api_gateway.dart';
import '../../runs/domain/run_events.dart';
import '../domain/attention_models.dart';
import '../domain/attention_transitions.dart';
import 'attention_ack_sync.dart';
import 'attention_store.dart';
/// The live `Needs you` state behind the Runs-list bell.
@@ -20,11 +21,22 @@ import 'attention_store.dart';
/// [AttentionStore] without blocking the caller. A failed read or write leaves
/// the in-memory set in force for this session; neither direction can throw into
/// the UI.
///
/// With a [sync], dismissals are shared with every device: Dismiss and Clear
/// all are also acknowledged to the server, and identities dismissed elsewhere
/// (the server's set and pushed deltas) are folded in and cached locally, so
/// the local store doubles as the offline copy.
class AttentionController extends ChangeNotifier {
AttentionController({required this.store, DateTime Function()? now})
: _now = now ?? DateTime.now;
AttentionController({
required this.store,
this.sync,
DateTime Function()? now,
}) : _now = now ?? DateTime.now {
sync?.addListener(_syncChanged);
}
final AttentionStore store;
final AttentionAckSync? sync;
final DateTime Function() _now;
final AttentionTransitionDetector _detector = AttentionTransitionDetector();
final List<AttentionTransition> _transitions = [];
@@ -75,6 +87,16 @@ class AttentionController extends ChangeNotifier {
// older stored value; the in-memory set is the operator's latest intent.
if (!_dirty) _dismissed = stored;
notifyListeners();
_syncChanged();
}
/// Folds identities acknowledged on any device into this set. A change is
/// cached in the local store; nothing is sent back to the server.
void _syncChanged() {
final shared = sync?.acks.dismissed;
if (_disposed || !_loaded || shared == null) return;
if (_dismissed.containsAll(shared)) return;
unawaited(_commit({..._dismissed, ...shared}));
}
/// Replaces the drawn rows with an authoritative read.
@@ -149,12 +171,25 @@ class AttentionController extends ChangeNotifier {
/// The in-memory set and the bell update before the store is touched, so a
/// slow or failed write never blocks the sheet. The returned future reports
/// whether the write succeeded; callers that do not need it may ignore it.
Future<bool> dismiss(AttentionEntry entry) =>
_commit(attentionDismiss(_dismissed, entry.key));
Future<bool> dismiss(AttentionEntry entry) {
_share([entry.key]);
return _commit(attentionDismiss(_dismissed, entry.key));
}
/// Applies only the identities captured when the sheet opened.
Future<bool> clearAll(Iterable<AttentionEntry> snapshot) =>
_commit(attentionDismissAll(_dismissed, snapshot));
Future<bool> clearAll(Iterable<AttentionEntry> snapshot) {
final entries = snapshot.toList();
_share([for (final entry in entries) entry.key]);
return _commit(attentionDismissAll(_dismissed, entries));
}
/// Acknowledges [keys] to every device. The sync queues them while offline,
/// and sending never blocks or fails the local dismissal.
void _share(List<String> keys) {
final shared = sync;
if (_disposed || shared == null || keys.isEmpty) return;
unawaited(shared.acknowledge(dismissed: keys));
}
Future<bool> _commit(Set<String> next) async {
final unchanged =
@@ -174,6 +209,7 @@ class AttentionController extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
sync?.removeListener(_syncChanged);
super.dispose();
}
}
@@ -1,10 +1,12 @@
import 'dart:async';
import 'dart:math';
import 'package:flutter/foundation.dart';
import '../../../../core/api_gateway.dart';
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_sessions.dart';
import 'chat_session_local.dart';
@@ -16,18 +18,40 @@ import 'session_attention.dart';
/// discarded, so a slow reply can never replace fresher state. Accepted
/// mutations always re-read the server list; only this device's hidden ids and
/// 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
/// device's own clears the chat's New badge here. The local store remains the
/// offline cache of both.
class ChatSessionsController extends ChangeNotifier {
ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore})
: _localStore =
localStore ??
SharedPreferencesChatSessionLocalStore(
serverId: serverStorageScope(serverIdentity(repository.gateway)),
) {
ChatSessionsController(
this.repository, {
ChatSessionLocalStore? localStore,
AttentionAckSync? ackSync,
int Function()? nowMillis,
this.activeAckDelay = const Duration(milliseconds: 1500),
}) : _localStore =
localStore ??
SharedPreferencesChatSessionLocalStore(
serverId: serverStorageScope(serverIdentity(repository.gateway)),
),
_nowMillis = nowMillis ?? _wallClockMillis {
_listenFrames();
_bindAckSync(ackSync ?? attentionAckSyncOf(repository.gateway));
}
static int _wallClockMillis() => DateTime.now().millisecondsSinceEpoch;
/// 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;
ChatRepository repository;
final ChatSessionLocalStore _localStore;
final int Function() _nowMillis;
AttentionAckSync? _ackSync;
Timer? _activeAck;
ChatSessionLocal _local = const ChatSessionLocal();
final Map<String, String> _actionErrors = {};
List<JsonMap> _sessions = const [];
@@ -59,6 +83,59 @@ class ChatSessionsController extends ChangeNotifier {
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);
}
void _bindAckSync(AttentionAckSync? sync) {
if (identical(sync, _ackSync)) return;
_ackSync?.removeListener(_ackChanged);
_ackSync = sync;
sync?.addListener(_ackChanged);
_ackChanged();
}
/// Content arriving in the chat this device has open is read here, so it is
/// acknowledged to the other devices once the stream goes quiet.
void _scheduleActiveAck(String id) {
if (_ackSync == null) return;
_activeAck?.cancel();
_activeAck = Timer(activeAckDelay, () {
if (_disposed || id != activeSessionId) return;
unawaited(_acknowledgeSeen(id, 0));
});
}
/// 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.
void _ackChanged() {
final seen = _ackSync?.acks.chatSeen;
if (_disposed || !_localLoaded || seen == null) return;
var next = _local;
seen.forEach((id, at) {
if (at > next.watermark(id)) next = next.read(id, at);
});
if (identical(next, _local)) return;
_local = next;
_notify();
unawaited(_persist());
}
/// Marks [id] read up to now here and acknowledges it to every device. The
/// value is at least the row's own recency; the server lifts it further to
/// the session's registry recency.
Future<void> _acknowledgeSeen(String id, int updatedAt) async {
await _ensureLocal();
if (_disposed) return;
final at = max(updatedAt, _nowMillis());
final next = _local.read(id, at);
if (!identical(next, _local)) {
_local = next;
_notify();
await _persist();
}
if (_disposed) return;
await _ackSync?.acknowledge(chatSeen: {id: at});
}
void _setRunning(String id, bool running) {
@@ -126,6 +203,7 @@ class ChatSessionsController extends ChangeNotifier {
repository = next;
_runningFrames.clear();
_listenFrames();
_bindAckSync(attentionAckSyncOf(next.gateway) ?? _ackSync);
refresh();
}
@@ -242,7 +320,9 @@ class ChatSessionsController extends ChangeNotifier {
activeSessionId = id;
await _ensureLocal();
if (_disposed) return;
final next = _local.read(id, chatSessionMillis(session['updated_at']));
final updatedAt = chatSessionMillis(session['updated_at']);
if (_ackSync != null) return _acknowledgeSeen(id, updatedAt);
final next = _local.read(id, updatedAt);
if (identical(next, _local)) return;
_local = next;
_notify();
@@ -313,6 +393,7 @@ class ChatSessionsController extends ChangeNotifier {
}
_localLoaded = true;
_seedLocal();
_ackChanged();
_notify();
}
@@ -351,6 +432,8 @@ class ChatSessionsController extends ChangeNotifier {
_disposed = true;
_generation++;
unawaited(_frameSubscription?.cancel());
_activeAck?.cancel();
_ackSync?.removeListener(_ackChanged);
super.dispose();
}
}