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,198 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_acks.dart';
import 'package:pipelines_app/features/attention/runtime/attention_ack_queue.dart';
import 'package:pipelines_app/features/attention/runtime/attention_ack_sync.dart';
import 'package:pipelines_app/features/attention/runtime/attention_controller.dart';
import 'package:pipelines_app/features/attention/runtime/attention_store.dart';
import 'fake_ack_server.dart';
final _now = DateTime(2026, 10, 22, 12);
Map<String, dynamic> _failed(int id) => {
'id': id,
'name': 'release',
'title': 'Run $id',
'status': 'failed',
'created_at': _now.subtract(const Duration(hours: 1)).toIso8601String(),
'finished_at': _now.subtract(const Duration(minutes: 30)).toIso8601String(),
};
/// One device: its gateway, sync, local stores and Needs-you controller.
class _Device {
_Device(FakeAckServer server)
: client = server.connect(),
store = MemoryAttentionStore(),
queue = MemoryAttentionAckQueue() {
sync = AttentionAckSync(gateway: client, queue: queue);
attention = AttentionController(store: store, sync: sync, now: () => _now);
}
final FakeAckClient client;
final MemoryAttentionStore store;
final MemoryAttentionAckQueue queue;
late final AttentionAckSync sync;
late final AttentionController attention;
Future<void> start(List<Map<String, dynamic>> rows) async {
await sync.load();
await attention.load();
attention.seedRows(rows);
await sync.connected();
}
List<int> get shown => [for (final e in attention.entries) e.runId];
void dispose() {
attention.dispose();
sync.dispose();
}
}
void main() {
late FakeAckServer server;
late _Device web;
late _Device phone;
final rows = [_failed(1), _failed(2), _failed(3)];
setUp(() async {
server = FakeAckServer();
web = _Device(server);
phone = _Device(server);
await web.start(rows);
await phone.start(rows);
});
tearDown(() {
web.dispose();
phone.dispose();
});
test(
'a dismissal on one device disappears on the other via the push',
() async {
expect(phone.shown, [3, 2, 1]);
await web.attention.dismiss(
web.attention.entries.firstWhere((e) => e.runId == 2),
);
await settle();
expect(web.shown, [3, 1]);
expect(phone.shown, [3, 1]);
expect(server.state.dismissed, {'2:Failed'});
// The other device caches the shared identity locally for offline use.
expect(phone.store.stored, contains('2:Failed'));
// The receiving device did not send anything back.
expect(phone.client.count('ack_attention'), 0);
},
);
test('Clear all on the web clears the phone too', () async {
final snapshot = web.attention.entries;
await web.attention.clearAll(snapshot);
await settle();
expect(web.shown, isEmpty);
expect(phone.shown, isEmpty);
expect(server.state.dismissed, {'1:Failed', '2:Failed', '3:Failed'});
});
test('a device that connects later loads the shared set', () async {
await web.attention.dismiss(web.attention.entries.first);
await settle();
final late = _Device(server);
addTearDown(late.dispose);
await late.start(rows);
await settle();
expect(late.shown, [2, 1]);
});
test(
'a dismissal made offline is queued, then synced on reconnect',
() async {
phone.client.online = false;
await phone.attention.dismiss(phone.attention.entries.first);
await settle();
expect(phone.shown, [2, 1]);
expect(web.shown, [3, 2, 1]);
expect(phone.sync.pending.dismissed, {'3:Failed'});
expect(AttentionAcks.decode(phone.queue.stored).dismissed, {'3:Failed'});
// A restarted app reads the persisted queue.
final restarted = AttentionAckSync(
gateway: phone.client,
queue: phone.queue,
);
addTearDown(restarted.dispose);
await restarted.load();
expect(restarted.pending.dismissed, {'3:Failed'});
phone.client.online = true;
await phone.sync.connected();
await settle();
expect(phone.sync.pending.isEmpty, isTrue);
expect(AttentionAcks.decode(phone.queue.stored).isEmpty, isTrue);
expect(web.shown, [2, 1]);
},
);
test('a refused batch is dropped; a legacy server keeps the queue', () async {
server.refuse = 'invalid attention identity';
await web.sync.acknowledge(dismissed: ['9:Failed']);
expect(web.sync.pending.isEmpty, isTrue);
server
..refuse = null
..legacy = true;
await web.sync.connected();
expect(web.sync.supported, isFalse);
await web.attention.dismiss(web.attention.entries.first);
await settle();
expect(web.shown, [2, 1], reason: 'the local dismissal still applies');
expect(web.sync.pending.dismissed, {'3:Failed'});
server.legacy = false;
await web.sync.connected();
await settle();
expect(web.sync.pending.isEmpty, isTrue);
expect(phone.shown, [2, 1]);
});
test('batches stay within the server bound', () {
final big = AttentionAcks(
dismissed: {for (var i = 1; i <= 600; i++) '$i:Failed'},
chatSeen: const {'ses_a': 1},
);
final batch = attentionAckBatch(big);
expect(batch.length, maxAttentionAckItems);
final rest = big.without(batch);
expect(rest.length, big.length - maxAttentionAckItems);
});
test('the send-only path matches replies and refusals by id', () async {
final client = server.connect();
final sync = AttentionAckSync(
gateway: client,
queue: MemoryAttentionAckQueue(),
sendOnly: client.sendOnly,
);
addTearDown(sync.dispose);
await sync.acknowledge(dismissed: ['1:Failed']);
await settle();
expect(sync.pending.isEmpty, isTrue);
expect(phone.shown, [3, 2]);
server.refuse = 'invalid attention identity';
await sync.acknowledge(dismissed: ['2:Failed']);
await settle();
expect(sync.pending.isEmpty, isTrue, reason: 'a refusal is dropped');
server.refuse = null;
await web.attention.dismiss(web.attention.entries.first);
await settle();
await sync.connected();
expect(sync.acks.dismissed, containsAll(['1:Failed', '3:Failed']));
});
}
@@ -0,0 +1,113 @@
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/attention/domain/attention_acks.dart';
/// An in-memory stand-in for the server's `attention_acks` / `ack_attention`
/// protocol with any number of connected clients. Like the Go handler, an ack
/// that changes the set is pushed to every *other* connected client as an
/// `attention_acks_changed` delta.
class FakeAckServer {
AttentionAcks state = const AttentionAcks();
final clients = <FakeAckClient>[];
/// When set, every ack_attention is refused with this reason.
String? refuse;
/// When true the server predates shared acks and answers `pong`.
bool legacy = false;
/// The chat list this server reports, for chat-list controllers.
List<JsonMap> chatSessions = const [];
FakeAckClient connect() {
final client = FakeAckClient(this);
clients.add(client);
return client;
}
JsonMap _reply() => {
'type': 'attention_acks',
'attention_acks': state.toJson(),
};
JsonMap _ack(FakeAckClient from, JsonMap fields) {
final incoming = AttentionAcks.fromJson(fields['attention_acks']);
final delta = AttentionAcks(
dismissed: incoming.dismissed.difference(state.dismissed),
chatSeen: {
for (final entry in incoming.chatSeen.entries)
if (entry.value > (state.chatSeen[entry.key] ?? 0))
entry.key: entry.value,
},
);
state = state.merge(incoming);
if (!delta.isEmpty) {
for (final client in clients) {
if (identical(client, from) || !client.online) continue;
client.pushed.add({
'type': 'attention_acks_changed',
'attention_acks': delta.toJson(),
});
}
}
return _reply();
}
}
class FakeAckClient implements ApiGateway {
FakeAckClient(this.server);
final FakeAckServer server;
final pushed = StreamController<JsonMap>.broadcast();
final calls = <String>[];
bool online = true;
@override
Stream<JsonMap> get frames => pushed.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(type);
if (!online) throw const NotConnectedError();
switch (type) {
case 'attention_acks':
case 'ack_attention':
if (server.legacy) return {'type': 'pong'};
if (type == 'attention_acks') return server._reply();
final reason = server.refuse;
if (reason != null) throw ProtocolError(reason);
return server._ack(this, fields);
case 'chat_sessions':
return {'type': 'chat_sessions', 'chat_sessions': server.chatSessions};
}
return {'type': 'pong'};
}
int count(String type) => calls.where((call) => call == type).length;
var _sequence = 0;
/// The socket's send-only path: the reply (or error) arrives later as a
/// frame carrying the request id, like the real transport.
String sendOnly(String type, JsonMap fields) {
if (!online) throw const NotConnectedError();
final id = 'send-${++_sequence}';
scheduleMicrotask(() async {
try {
pushed.add({...await call(type, fields), 'id': id});
} on ProtocolError catch (error) {
pushed.add({'type': 'error', 'id': id, 'error': error.message});
}
});
return id;
}
}
/// Lets queued microtasks and stream deliveries settle.
Future<void> settle() async {
for (var i = 0; i < 10; i++) {
await Future<void>.delayed(Duration.zero);
}
}
@@ -0,0 +1,167 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/attention/runtime/attention_ack_queue.dart';
import 'package:pipelines_app/features/attention/runtime/attention_ack_sync.dart';
import 'package:pipelines_app/features/chat/data/chat_repository.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_session_local.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart';
import '../../../attention/runtime/fake_ack_server.dart';
import 'chat_test_harness.dart';
JsonMap _text(String id) => {
'type': 'chat_event',
'chat_event': {'session_id': id, 'kind': 'text', 'delta': 'hello'},
};
/// One device's chat list sharing read state through [FakeAckServer].
class _Device {
_Device(FakeAckServer server, {required this.clock})
: client = server.connect(),
local = MemoryChatSessionLocalStore() {
sync = AttentionAckSync(gateway: client, queue: MemoryAttentionAckQueue());
bindAttentionAckSync(client, sync);
list = ChatSessionsController(
ChatRepository(client),
localStore: local,
nowMillis: () => clock(),
activeAckDelay: const Duration(milliseconds: 20),
);
}
final FakeAckClient client;
final MemoryChatSessionLocalStore local;
final int Function() clock;
late final AttentionAckSync sync;
late final ChatSessionsController list;
Future<void> start() async {
await sync.connected();
await list.refresh();
await settle();
}
bool isNew(String id) =>
list.isUnseen(list.sessions.firstWhere((row) => row['id'] == id));
JsonMap row(String id) => list.sessions.firstWhere((row) => row['id'] == id);
void dispose() {
list.dispose();
sync.dispose();
}
}
void main() {
late FakeAckServer server;
late _Device web;
late _Device phone;
var now = 5000;
setUp(() async {
now = 5000;
server = FakeAckServer()
..chatSessions = [
{'id': 'ses_a', 'title': 'A', 'directory': '/w', 'updated_at': 1000},
{'id': 'ses_b', 'title': 'B', 'directory': '/w', 'updated_at': 1000},
];
web = _Device(server, clock: () => now);
phone = _Device(server, clock: () => now);
await web.start();
await phone.start();
});
tearDown(() {
web.dispose();
phone.dispose();
});
void pushToAll(JsonMap frame) {
for (final client in server.clients) {
client.pushed.add(frame);
}
}
test(
'opening a chat on one device clears its New badge everywhere',
() async {
pushToAll(_text('ses_a'));
await settle();
expect(web.isNew('ses_a'), isTrue);
expect(phone.isNew('ses_a'), isTrue);
now = 6000;
await web.list.markOpened(web.row('ses_a'));
await settle();
expect(server.state.chatSeen['ses_a'], 6000);
expect(phone.isNew('ses_a'), isFalse);
expect(phone.local.state?.watermark('ses_a'), 6000);
// Only the opened chat is affected.
pushToAll(_text('ses_b'));
await settle();
expect(phone.isNew('ses_b'), isTrue);
},
);
test('an earlier acknowledgement never clears later content', () async {
now = 6000;
await web.list.markOpened(web.row('ses_a'));
web.list.activeSessionId = null;
await settle();
// New content after the open: the phone marks it New and a reload of the
// same shared watermark must not clear it.
pushToAll(_text('ses_a'));
await settle();
expect(phone.isNew('ses_a'), isTrue);
await phone.sync.connected();
await settle();
expect(phone.isNew('ses_a'), isTrue);
});
test('content arriving in a chat open elsewhere is read there', () async {
now = 6000;
await web.list.markOpened(web.row('ses_a'));
await settle();
now = 7000;
pushToAll(_text('ses_a'));
await settle();
expect(phone.isNew('ses_a'), isTrue);
expect(web.isNew('ses_a'), isFalse);
// The open chat acknowledges once its stream goes quiet (20 ms here).
for (var i = 0; i < 100 && server.state.chatSeen['ses_a'] != 7000; i++) {
await Future<void>.delayed(const Duration(milliseconds: 20));
}
await settle();
expect(server.state.chatSeen['ses_a'], 7000);
expect(phone.isNew('ses_a'), isFalse);
});
test('a chat opened offline is synced and cleared on reconnect', () async {
pushToAll(_text('ses_a'));
await settle();
web.client.online = false;
now = 6000;
await web.list.markOpened(web.row('ses_a'));
await settle();
expect(phone.isNew('ses_a'), isTrue);
expect(web.sync.pending.chatSeen, {'ses_a': 6000});
web.client.online = true;
await web.sync.connected();
await settle();
expect(phone.isNew('ses_a'), isFalse);
// A device that was not connected for the push applies the stored set
// on its next connection.
final late = _Device(server, clock: () => now);
addTearDown(late.dispose);
late.local.state = const ChatSessionLocal(
seenAt: {'ses_a': 1000},
unseen: ['ses_a'],
);
await late.start();
expect(late.isNew('ses_a'), isFalse);
});
}