Sync Needs-you dismissals and chat read state across devices
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user