Serialize open-chat sync writes by server revision and fan out prunes

Server: chat_open_workspace is a compare-and-swap on base_revision; a stale
write is refused and answered with the current snapshot (rejected: true).
Each stored change increments the revision; identical writes store nothing.
A request with no body reads the set. Seeds apply only to a never-stored set.
Validation uses the operator registry (recorded, not closed). chat_close and
connection-time pruning store a new revision and push it to every
connection; otherwise a new connection gets the current set to catch up.

App: ChatOpenWorkspaceController keeps one write in flight, coalesces later
changes, sends from the last replied revision and ignores lower revisions;
pushes and rejected replies win over unsent changes. It starts after the
local layout restores (seed or read), keeps a deep-linked chat, and is
disposed on server/gateway rebind. Remote membership is applied by
reconcileChatWorkspaceTree, keeping pane ids and split sizes. Federated
lists keep their local layout.

Tests: Go store/handler fan-out tests; app controller, reconcile and screen
sync tests. Notes record a live two-client scratch check.
This commit is contained in:
2026-11-12 03:23:22 +00:00
parent f8e081825f
commit 4f8e99f316
20 changed files with 1333 additions and 276 deletions
@@ -0,0 +1,205 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/server_scope.dart';
import 'package:pipelines_app/features/chat/screen.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'conversation/chat_thread_fixtures.dart';
/// A chat server that keeps the open-chat set with the real revision rules:
/// a seed applies only to a never-stored set, a write from a stale base is
/// refused with the current set.
class _Server extends FakeChatGateway {
_Server({this.revision = 0, List<String> open = const []})
: open = List.of(open);
int revision;
List<String> open;
final writes = <List<String>>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_sessions') {
return Future.value({
'chat_sessions': [
for (final id in ['a', 'b', 'c', 'd'])
{'id': id, 'title': 'Chat $id'},
],
});
}
if (type == 'chat_shells') return Future.value({'chat_shells': []});
if (type == 'chat_open_workspace') return Future.value(_workspace(fields));
return super.call(type, fields);
}
JsonMap _workspace(JsonMap fields) {
final request = fields['chat_open_workspace_request'] as Map?;
var rejected = false;
if (request != null) {
final ids = [
for (final entry in request['entries'] as List)
'${entry['session_id']}',
];
writes.add(ids);
if (request['seed'] == true) {
if (revision == 0) {
open = ids;
revision = 1;
}
} else if (request['base_revision'] != revision) {
rejected = true;
} else {
open = ids;
revision++;
}
}
return {
'type': 'chat_open_workspace',
'chat_open_workspace': _body(rejected),
};
}
JsonMap _body([bool rejected = false]) => {
'revision': revision,
'entries': [
for (final id in open) {'session_id': id},
],
if (rejected) 'rejected': true,
};
/// Another device (or the server) changed the set.
void change(List<String> ids) {
open = List.of(ids);
revision++;
emitRaw({
'type': 'chat_open_workspace_changed',
'chat_open_workspace': _body(),
});
}
}
ChatWorkspaceController _workspace(WidgetTester tester) =>
tester.widget<ChatWorkspace>(find.byType(ChatWorkspace)).controller;
List<String> _open(WidgetTester tester) =>
_workspace(tester).panes.map((pane) => pane.sessionId).toList();
Future<void> _mount(WidgetTester tester, _Server server) async {
await tester.pumpWidget(
MaterialApp(
home: AdaptiveShell(
destination: AppDestination.chat,
destinationBodies: {
AppDestination.chat: (_) =>
ChatScreen(gateway: server, persistWorkspace: true),
},
),
),
);
await tester.pumpAndSettle();
}
_Server _server(
String identity, {
int revision = 0,
List<String> open = const [],
}) {
final server = _Server(revision: revision, open: open)
..history = (_) async => chatPage([]);
bindServerIdentity(server, identity);
addTearDown(server.close);
return server;
}
void _saveLocal(String identity, List<String> ids) {
final saved = ChatWorkspaceController()..open(ids.first);
for (final id in ids.skip(1)) {
saved.splitActive(id, ChatSplitAxis.horizontal);
}
SharedPreferences.setMockInitialValues({
scopedServerKey(chatWorkspacePreferenceKey, identity): saved
.snapshot()!
.encode(),
});
}
void main() {
testWidgets(
'the local layout seeds a new server and remote removal drops its pane',
(tester) async {
tester.view.physicalSize = const Size(1800, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
_saveLocal('server-a', ['a', 'b']);
final server = _server('server-a');
await _mount(tester, server);
expect(server.revision, 1);
expect(server.open, ['a', 'b']);
expect(_open(tester), ['a', 'b']);
server.change(['b']);
await tester.pumpAndSettle();
expect(_open(tester), ['b']);
// Applying the server's change is not written back.
expect(server.writes, hasLength(1));
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpAndSettle();
},
);
testWidgets('an existing server set wins over an old local snapshot', (
tester,
) async {
tester.view.physicalSize = const Size(1800, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
_saveLocal('server-a', ['a']);
final server = _server('server-a', revision: 3, open: ['b', 'c']);
await _mount(tester, server);
expect(_open(tester), ['b', 'c']);
expect(server.open, ['b', 'c']);
expect(server.revision, 3);
// A local change is sent from the server's revision and accepted.
_workspace(tester).close(_workspace(tester).panes.first.id);
await tester.pumpAndSettle();
expect(server.open, ['c']);
expect(server.revision, 4);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpAndSettle();
});
testWidgets('rebinding to another server disposes the old sync', (
tester,
) async {
tester.view.physicalSize = const Size(1800, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
SharedPreferences.setMockInitialValues({});
final first = _server('server-a', revision: 1, open: ['a']);
final second = _server('server-b', revision: 1, open: ['c']);
await _mount(tester, first);
expect(_open(tester), ['a']);
await _mount(tester, second);
expect(_open(tester), ['c']);
// The old server's pushes no longer reach this screen.
first.change(['a', 'b', 'd']);
await tester.pumpAndSettle();
expect(_open(tester), ['c']);
// The new server's do, and local changes go only to it.
second.change(['c', 'd']);
await tester.pumpAndSettle();
expect(_open(tester), ['c', 'd']);
final firstWrites = first.writes.length;
_workspace(tester).close(_workspace(tester).panes.last.id);
await tester.pumpAndSettle();
expect(second.open, ['c']);
expect(first.writes, hasLength(firstWrites));
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpAndSettle();
});
}
@@ -0,0 +1,211 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_controller.dart';
import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_gateway.dart';
/// Answers each chat_open_workspace call only when the test completes it.
class _Gateway implements ApiGateway {
final requests = <({JsonMap fields, Completer<JsonMap> reply})>[];
final _frames = StreamController<JsonMap>.broadcast();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
final reply = Completer<JsonMap>();
requests.add((fields: fields, reply: reply));
return reply.future;
}
@override
Stream<JsonMap> get frames => _frames.stream;
void push(int revision, List<String> ids) => _frames.add({
'type': 'chat_open_workspace_changed',
'chat_open_workspace': _snapshot(revision, ids),
});
void answer(
int index,
int revision,
List<String> ids, {
bool rejected = false,
}) => requests[index].reply.complete({
'type': 'chat_open_workspace',
'chat_open_workspace': _snapshot(revision, ids, rejected: rejected),
});
List<String> sentIds(int index) => [
for (final entry
in (requests[index].fields['chat_open_workspace_request']
as Map)['entries']
as List)
'${entry['session_id']}',
];
int base(int index) =>
(requests[index].fields['chat_open_workspace_request']
as Map)['base_revision'];
}
JsonMap _snapshot(int revision, List<String> ids, {bool rejected = false}) => {
'revision': revision,
'entries': [
for (final id in ids) {'session_id': id},
],
if (rejected) 'rejected': true,
};
List<ChatOpenWorkspaceEntry> _entries(List<String> ids) => [
for (final id in ids) ChatOpenWorkspaceEntry(id),
];
Future<(ChatOpenWorkspaceController, _Gateway, List<List<String>>)> _started({
int revision = 1,
List<String> ids = const ['a'],
}) async {
final gateway = _Gateway();
final applied = <List<String>>[];
final controller = ChatOpenWorkspaceController(gateway: gateway)
..onChanged = (snapshot) =>
applied.add(snapshot.entries.map((e) => e.sessionId).toList());
final started = controller.start(local: _entries(ids));
await pumpEventQueue();
expect(gateway.requests.single.fields['chat_open_workspace_request'], {
'entries': [
for (final id in ids) {'session_id': id},
],
'base_revision': 0,
'seed': true,
});
gateway.answer(0, revision, ids);
await started;
return (controller, gateway, applied);
}
void main() {
test('reads instead of seeding when the device has no chats', () async {
final gateway = _Gateway();
final controller = ChatOpenWorkspaceController(gateway: gateway);
final started = controller.start();
await pumpEventQueue();
expect(gateway.requests.single.fields, isEmpty);
gateway.answer(0, 4, ['x']);
await started;
expect(controller.revision, 4);
expect(controller.ready, isTrue);
});
test(
'serializes writes and sends the latest from the replied revision',
() async {
final (controller, gateway, _) = await _started();
controller.replace(_entries(['a', 'b']));
controller.replace(_entries(['a', 'b', 'c']));
controller.replace(_entries(['c', 'a', 'b']));
await pumpEventQueue();
// One write in flight; the two later ones coalesced behind it.
expect(gateway.requests, hasLength(2));
expect(gateway.sentIds(1), ['a', 'b']);
expect(gateway.base(1), 1);
gateway.answer(1, 2, ['a', 'b']);
await pumpEventQueue();
expect(gateway.requests, hasLength(3));
expect(gateway.sentIds(2), ['c', 'a', 'b']);
expect(gateway.base(2), 2);
gateway.answer(2, 3, ['c', 'a', 'b']);
await pumpEventQueue();
expect(controller.revision, 3);
// An unchanged set is not sent again.
controller.replace(_entries(['c', 'a', 'b']));
await pumpEventQueue();
expect(gateway.requests, hasLength(3));
},
);
test('a late reply never overwrites a newer pushed revision', () async {
final (controller, gateway, applied) = await _started();
controller.replace(_entries(['a', 'b']));
await pumpEventQueue();
// Another device's change (revision 3) is pushed before this write's
// reply (revision 2) arrives.
gateway.push(3, ['z']);
await pumpEventQueue();
gateway.answer(1, 2, ['a', 'b']);
await pumpEventQueue();
expect(controller.revision, 3);
expect(applied.last, ['z']);
// Older and repeated pushes are ignored.
gateway.push(2, ['a', 'b']);
gateway.push(3, ['z']);
await pumpEventQueue();
expect(applied, [
['a'],
['z'],
]);
});
test(
'a refused stale write applies the server state and drops queued ones',
() async {
final (controller, gateway, applied) = await _started();
controller.replace(_entries(['a', 'b']));
await pumpEventQueue();
controller.replace(_entries(['a', 'b', 'c']));
gateway.answer(1, 5, ['q'], rejected: true);
await pumpEventQueue();
expect(applied.last, ['q']);
expect(controller.revision, 5);
expect(gateway.requests, hasLength(2));
// The next change is derived from the server's state.
controller.replace(_entries(['q', 'r']));
await pumpEventQueue();
expect(gateway.base(2), 5);
},
);
test('a push applied while writing replaces the queued write', () async {
final (controller, gateway, applied) = await _started();
controller.replace(_entries(['a', 'b']));
await pumpEventQueue();
controller.replace(_entries(['a', 'b', 'c']));
gateway.push(4, ['b']);
await pumpEventQueue();
expect(applied.last, ['b']);
gateway.answer(1, 4, ['b'], rejected: true);
await pumpEventQueue();
expect(gateway.requests, hasLength(2));
});
test('dispose stops pushes and writes', () async {
final (controller, gateway, applied) = await _started();
controller.dispose();
gateway.push(9, ['late']);
controller.replace(_entries(['x']));
await pumpEventQueue();
expect(applied, [
['a'],
]);
expect(gateway.requests, hasLength(1));
});
test(
'stays local-only when the server does not answer the request',
() async {
final gateway = _Gateway();
final controller = ChatOpenWorkspaceController(gateway: gateway);
final started = controller.start(local: _entries(['a']));
await pumpEventQueue();
gateway.requests.single.reply.completeError(StateError('unknown type'));
await started;
expect(controller.ready, isFalse);
controller.replace(_entries(['a', 'b']));
await pumpEventQueue();
expect(gateway.requests, hasLength(1));
// A server push (a reconnect) brings it up to date and enables writes.
gateway.push(2, ['a']);
await pumpEventQueue();
expect(controller.ready, isTrue);
},
);
}
@@ -11,7 +11,10 @@ void main() {
],
});
expect(snapshot?.revision, 7);
expect(snapshot?.entries.map((entry) => entry.sessionId), ['ses_a', 'ses_b']);
expect(snapshot?.entries.map((entry) => entry.sessionId), [
'ses_a',
'ses_b',
]);
expect(snapshot?.entries.first.floating, isTrue);
});
@@ -0,0 +1,56 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart';
List<String> _sessions(ChatWorkspaceController c) =>
c.panes.map((pane) => pane.sessionId).toList();
ChatWorkspaceController _three() {
final c = ChatWorkspaceController()..open('a');
c.splitActive('b', ChatSplitAxis.vertical);
c.splitActive('c', ChatSplitAxis.horizontal);
c.resize(c.root!.id, .3);
return c;
}
void main() {
test('a remote removal drops only that pane and keeps the geometry', () {
final c = _three();
final paneA = c.panes.first.id;
final paneC = c.panes.last.id;
c.reconcileSessions(['a', 'c']);
expect(_sessions(c), ['a', 'c']);
expect(c.panes.map((pane) => pane.id), [paneA, paneC]);
expect((c.root as ChatWorkspaceSplit).ratio, .3);
});
test('a reorder moves panes with their ids and keeps the splits', () {
final c = _three();
final ids = {for (final pane in c.panes) pane.sessionId: pane.id};
final splitId = c.root!.id;
c.reconcileSessions(['c', 'a', 'b']);
expect(_sessions(c), ['c', 'a', 'b']);
expect(c.panes.map((pane) => pane.id), [ids['c'], ids['a'], ids['b']]);
expect(c.root!.id, splitId);
expect((c.root as ChatWorkspaceSplit).ratio, .3);
});
test('new chats split off and an unchanged set notifies nothing', () {
final c = ChatWorkspaceController()..open('a');
c.reconcileSessions(['a', 'b']);
expect(_sessions(c), ['a', 'b']);
var notified = 0;
c.addListener(() => notified++);
c.reconcileSessions(['a', 'b']);
expect(notified, 0);
c.reconcileSessions(const []);
expect(c.panes, isEmpty);
expect(c.activePane, isNull);
});
test('the active pane moves on when its chat is removed', () {
final c = _three();
expect(c.activePane?.sessionId, 'c');
c.reconcileSessions(['b']);
expect(c.activePane?.sessionId, 'b');
});
}