Connect saved machines concurrently in the chat workspace

This commit is contained in:
2026-11-08 22:21:17 +00:00
parent 663d5fb5c9
commit e4904395f0
44 changed files with 2574 additions and 60 deletions
@@ -35,13 +35,38 @@ Map<String, dynamic>? requestOf(
.skip(index)
.firstOrNull;
final _fixtureAutomationReplies = Expando<Set<String>>();
Future<Map<String, dynamic>> waitForRequest(
WidgetTester tester,
FakeChannel channel,
String type, {
int index = 0,
}) async {
final replied = _fixtureAutomationReplies[channel] ??= <String>{};
for (var attempt = 0; attempt < 80; attempt++) {
// Automation metadata is independently requested before history. This
// fixture has no provider schedules; answer unavailable rather than leave
// the correlated transport blocked behind an unanswered request.
if (type != 'chat_automations') {
for (final raw in channel.outgoing.toList()) {
final metadata = jsonDecode(raw as String) as Map<String, dynamic>;
if (metadata['type'] == 'chat_automations' &&
replied.add('${metadata['id']}')) {
channel.incoming.add(
jsonEncode({
'id': metadata['id'],
'type': 'chat_automations',
'chat_automations': {
'session_id': metadata['chat_query']['session_id'],
'provider': 'fixture',
'status': 'unavailable',
},
}),
);
}
}
}
final request = requestOf(channel, type, index: index);
if (request != null) return request;
await tester.pump(const Duration(milliseconds: 5));
@@ -226,6 +251,7 @@ void main() {
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: cupertino,
@@ -351,6 +377,7 @@ void main() {
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: false,
@@ -559,6 +586,7 @@ void main() {
addTearDown(client.dispose);
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: false,
@@ -641,6 +669,7 @@ void main() {
addTearDown(client.dispose);
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: false,
@@ -710,6 +739,7 @@ void main() {
addTearDown(client.dispose);
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: false,
@@ -35,6 +35,7 @@ void main() {
(tester) async {
await tester.pumpWidget(
PipelinesRoot(
federatedChats: false,
nativeUpdatesSupported: false,
server: _server(''),
buildDefault: 'wss://build.example/connect',
@@ -55,6 +56,7 @@ void main() {
) async {
await tester.pumpWidget(
PipelinesRoot(
federatedChats: false,
nativeUpdatesSupported: false,
server: _server('wss://home.example/connect'),
// A saved server with no kept session goes to onboarding directly.
@@ -336,6 +336,7 @@ Future<void> pumpApp(
}) async {
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
cupertino: cupertino,
@@ -51,6 +51,8 @@ void main() {
);
await tester.pumpWidget(
PipelinesRoot(
federatedChats: false,
nativeUpdatesSupported: false,
server: ServerEndpoint.resolve(
base: Uri.parse('file:///'),
web: false,
@@ -57,6 +57,7 @@ void main() {
await ServerSession.load();
await tester.pumpWidget(
PipelinesRoot(
federatedChats: false,
nativeUpdatesSupported: false,
server: ServerEndpoint.resolve(
base: Uri.parse('file:///'),
@@ -120,6 +121,7 @@ void main() {
);
await tester.pumpWidget(
PipelinesRoot(
federatedChats: false,
nativeUpdatesSupported: false,
server: server,
catalogStore: store,
@@ -209,6 +211,7 @@ void main() {
);
await tester.pumpWidget(
PipelinesRoot(
federatedChats: false,
nativeUpdatesSupported: false,
server: ServerEndpoint.resolve(
base: Uri.parse('file:///'),
@@ -0,0 +1,174 @@
import 'dart:convert';
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/session/server_session.dart';
import 'package:pipelines_app/core/servers/chat/chat_machine_connection.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test(
'simultaneous native sockets use their own profile cookies without selecting them',
() async {
final previous = HttpOverrides.current;
HttpOverrides.global = null;
final first = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final second = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final cookies = <int, String?>{};
final sockets = <WebSocket>[];
void serve(HttpServer server) {
server.listen((request) async {
cookies[server.port] = request.headers.value('cookie');
final socket = await WebSocketTransformer.upgrade(request);
sockets.add(socket);
socket.listen((raw) {
final value = jsonDecode(raw as String) as Map;
socket.add(
jsonEncode({
'id': value['id'],
'type': 'chat_sessions',
'chat_sessions': [
{'id': 'same', 'title': 'Fixture'},
],
}),
);
});
});
}
serve(first);
serve(second);
final a = SavedServer.validated(
id: 'native-a',
name: 'A',
endpoints: ['ws://127.0.0.1:${first.port}/connect'],
);
final b = SavedServer.validated(
id: 'native-b',
name: 'B',
endpoints: ['ws://127.0.0.1:${second.port}/connect'],
);
SharedPreferences.setMockInitialValues({
'pipelines.session.v2.native-a.cookie': 'session=first',
'pipelines.session.v2.native-b.cookie': 'session=second',
'pipelines.session.v2.selected.cookie': 'session=selected',
});
await ServerSession.activateServer(
id: 'selected',
endpoints: [Uri.parse('ws://selected.test/connect')],
);
ChatMachineConnection? one, two;
try {
final opened = await Future.wait([
connectChatMachine(a, web: false),
connectChatMachine(b, web: false),
]);
one = opened[0];
two = opened[1];
await one.gateway.call('chat_sessions');
await two.gateway.call('chat_sessions');
expect(cookies, {
first.port: 'session=first',
second.port: 'session=second',
});
expect(ServerSession.serverId, 'selected');
expect(ServerSession.cookie, 'session=selected');
final owner = Object();
ServerSession.registerReader(
owner,
await ServerSession.credentialReader(
id: b.id,
endpoints: b.endpoints.map(Uri.parse),
),
);
try {
expect(ServerSession.headersFor(Uri.parse(b.endpoints.first)), {
'Cookie': 'session=second',
});
} finally {
ServerSession.removeReader(owner);
}
} finally {
await one?.close();
await two?.close();
for (final socket in sockets) {
await socket.close();
}
await first.close(force: true);
await second.close(force: true);
HttpOverrides.global = previous;
ServerSession.clearSelection();
}
},
);
test('failed password preserves existing scoped cookie readers', () async {
final previous = HttpOverrides.current;
HttpOverrides.global = null;
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen((request) async {
request.response.statusCode = 401;
await request.response.close();
});
final endpoint = Uri.parse('ws://127.0.0.1:${server.port}/connect');
SharedPreferences.setMockInitialValues({
'pipelines.session.v2.kept.cookie': 'session=kept',
});
final headers = await ServerSession.credentialReader(
id: 'kept',
endpoints: [endpoint],
);
try {
expect(
await ServerSession.signInProfile(
id: 'kept',
endpoints: [endpoint],
password: 'wrong',
),
contains('Wrong password'),
);
expect(headers(endpoint), {'Cookie': 'session=kept'});
} finally {
await server.close(force: true);
HttpOverrides.global = previous;
}
});
test(
'late password reply cannot authenticate a retargeted machine',
() async {
final previous = HttpOverrides.current;
HttpOverrides.global = null;
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final request = Completer<HttpRequest>();
server.listen(request.complete);
final endpoint = Uri.parse('ws://127.0.0.1:${server.port}/connect');
SharedPreferences.setMockInitialValues({});
var current = true;
try {
final signing = ServerSession.signInProfile(
id: 'retargeted',
endpoints: [endpoint],
password: 'password',
isCurrent: () => current,
);
final received = await request.future;
current = false;
received.response.statusCode = 302;
received.response.cookies.add(
Cookie('pipelines_session', 'old-server'),
);
await received.response.close();
expect(await signing, contains('changed'));
final prefs = await SharedPreferences.getInstance();
expect(
prefs.getString('pipelines.session.v2.retargeted.cookie'),
isNull,
);
} finally {
await server.close(force: true);
HttpOverrides.global = previous;
}
},
);
}
@@ -0,0 +1,282 @@
import 'dart:async';
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/session/server_session.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/settings/server_connections.dart';
class _Gateway implements ApiGateway {
final events = StreamController<JsonMap>.broadcast();
@override
Stream<JsonMap> get frames => events.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async =>
type == 'attention_acks' || type == 'ack_attention'
? {
'type': 'attention_acks',
'attention_acks': {'chat_seen': {}, 'dismissed': []},
}
: {
'type': 'chat_sessions',
'chat_sessions': [
{'id': 'same', 'title': 'Fixture chat'},
],
};
}
class _Machine {
_Machine(this.server, {Completer<void>? cancelGate}) {
states = cancelGate == null
? StreamController<ConnectionState>.broadcast()
: StreamController<ConnectionState>(onCancel: () => cancelGate.future);
connection = ChatMachineConnection(
gateway: gateway,
endpoint: () => server.endpoints.first,
connected: () => true,
states: states.stream,
close: () async {
closes++;
},
retry: () async {},
);
}
final SavedServer server;
final gateway = _Gateway();
late StreamController<ConnectionState> states;
late ChatMachineConnection connection;
int closes = 0;
Future<void> finish() async {
await gateway.events.close();
await states.close();
}
}
SavedServer _server(String id, {String? host}) => SavedServer.validated(
id: id,
name: id,
endpoints: ['ws://${host ?? id}.test:8083/connect'],
);
Future<void> _flush() async {
for (var i = 0; i < 12; i++) {
await Future<void>.delayed(Duration.zero);
}
}
Future<ServerConnections> _servers(List<SavedServer> profiles) async {
final server = ServerConnections(
store: MemoryServerCatalogStore(
catalog: ServerCatalog(servers: profiles, selectedId: profiles.first.id),
),
onSelected: (_) async {},
);
await server.load();
return server;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() => SharedPreferences.setMockInitialValues({}));
test('an older async detach cannot close a newer connection', () async {
final profile = _server('one');
final servers = await _servers([profile]);
final cancellation = Completer<void>();
final machines = <_Machine>[];
final pool = ChatServerPool(
servers,
web: false,
connect: (server) async {
final machine = _Machine(
server,
cancelGate: machines.isEmpty ? cancellation : null,
);
machines.add(machine);
return machine.connection;
},
);
try {
await _flush();
expect(machines, hasLength(1));
final olderRetry = pool.retry(profile.id);
await _flush(); // Old state subscription's cancellation remains pending.
expect(machines, hasLength(1));
await pool.retry(
profile.id,
); // A newer generation wins while old detach waits.
await _flush();
expect(machines, hasLength(2));
expect(pool.machines.single.connected, isTrue);
cancellation.complete();
await olderRetry;
await _flush();
expect(machines.first.closes, 1);
expect(machines.last.closes, 0);
expect(pool.machines.single.adapter, isNotNull);
expect(pool.machines.single.connection, same(machines.last.connection));
} finally {
if (!cancellation.isCompleted) cancellation.complete();
pool.dispose();
servers.dispose();
await _flush();
for (final machine in machines) {
await machine.finish();
}
}
});
test(
'a late connection for a removed profile is closed rather than resurrected',
() async {
final profile = _server('one');
final servers = await _servers([profile]);
final pending = Completer<ChatMachineConnection>();
final machine = _Machine(profile);
final pool = ChatServerPool(
servers,
web: false,
connect: (_) => pending.future,
);
try {
await _flush();
expect(pool.machines, hasLength(1));
expect(await servers.remove(profile.id), isTrue);
pending.complete(machine.connection);
await _flush();
expect(pool.machines, isEmpty);
expect(machine.closes, 1);
await expectLater(pool.gateway.call('chat_sessions'), throwsStateError);
} finally {
pool.dispose();
servers.dispose();
await _flush();
await machine.finish();
}
},
);
test(
'replacing endpoints discards a late old result and keeps the new socket',
() async {
final oldProfile = _server('one', host: 'old');
final newProfile = _server('one', host: 'new');
final servers = await _servers([oldProfile]);
final pending = Completer<ChatMachineConnection>();
final old = _Machine(oldProfile), next = _Machine(newProfile);
var calls = 0;
final pool = ChatServerPool(
servers,
web: false,
connect: (_) {
return calls++ == 0 ? pending.future : Future.value(next.connection);
},
);
try {
await _flush();
expect(await servers.save(newProfile, activate: false), isTrue);
await _flush();
expect(pool.machines.single.connection, same(next.connection));
pending.complete(old.connection);
await _flush();
expect(old.closes, 1);
expect(next.closes, 0);
expect(
pool.machines.single.adapter!.server.endpoints,
newProfile.endpoints,
);
} finally {
pool.dispose();
servers.dispose();
await _flush();
await old.finish();
await next.finish();
}
},
);
test(
'retrying one machine leaves the other machine and primary selection intact',
() async {
final one = _server('one'), two = _server('two');
final servers = await _servers([one, two]);
final machines = <_Machine>[];
final pool = ChatServerPool(
servers,
web: false,
connect: (profile) async {
final machine = _Machine(profile);
machines.add(machine);
return machine.connection;
},
);
try {
await _flush();
final untouched = machines.singleWhere((m) => m.server.id == 'two');
await pool.retry('one');
await _flush();
expect(untouched.closes, 0);
expect(
pool.machines.singleWhere((m) => m.server.id == 'two').connection,
same(untouched.connection),
);
expect(servers.catalog.selectedId, 'one');
final list =
(await pool.gateway.call('chat_sessions'))['chat_sessions'] as List;
expect(list, hasLength(2));
expect(list[0]['id'], isNot(list[1]['id']));
} finally {
pool.dispose();
servers.dispose();
await _flush();
for (final machine in machines) {
await machine.finish();
}
}
},
);
test(
'global settings sign-out refreshes only the selected machine',
() async {
final one = _server('settings-one'), two = _server('settings-two');
final servers = await _servers([one, two]);
await ServerSession.activateServer(
id: one.id,
endpoints: one.endpoints.map(Uri.parse),
);
ServerSession.cookie = 'fixture=one';
final machines = <_Machine>[];
final pool = ChatServerPool(
servers,
web: false,
connect: (profile) async {
final machine = _Machine(profile);
machines.add(machine);
return machine.connection;
},
);
try {
await _flush();
final untouched = machines.singleWhere((m) => m.server.id == two.id);
await ServerSession.signOut();
await _flush();
expect(machines.where((m) => m.server.id == one.id), hasLength(2));
expect(untouched.closes, 0);
expect(
pool.machines.singleWhere((m) => m.server.id == two.id).connection,
same(untouched.connection),
);
} finally {
pool.dispose();
servers.dispose();
ServerSession.clearSelection();
await _flush();
for (final machine in machines) {
await machine.finish();
}
}
},
);
}
@@ -0,0 +1,339 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/chat/chat_identity.dart';
import 'package:pipelines_app/core/servers/chat/chat_server_gateway.dart';
import 'package:pipelines_app/core/servers/chat/federated_chat_gateway.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
import 'package:pipelines_app/core/transport/server_url.dart';
import 'package:pipelines_app/features/chat/files/files_urls.dart';
class Machine implements ApiGateway {
final events = StreamController<JsonMap>.broadcast();
final calls = <(String, JsonMap)>[];
bool fail = false;
Completer<JsonMap>? pendingSessions;
@override
Stream<JsonMap> get frames => events.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type, fields));
if (fail) throw StateError('offline');
if (type == 'chat_sessions') {
if (pendingSessions != null) return pendingSessions!.future;
return {
'chat_sessions': [
{'id': 'collision', 'title': 'Same title'},
],
};
}
if (type == 'attention_acks' || type == 'ack_attention') {
return {
'type': 'attention_acks',
'attention_acks': {
'chat_seen': {'collision': 12},
'dismissed': ['7:failed'],
},
};
}
return {
'chat_session': {'id': 'collision'},
'chat_messages': [
{
'id': 'message',
'session_id': 'collision',
'parts': [
{'id': 'part'},
],
},
],
};
}
}
SavedServer server(String id) => SavedServer.validated(
id: id,
name: 'Machine $id',
endpoints: ['ws://$id.test/connect'],
);
void main() {
test(
'colliding native IDs remain distinct, mutations and replies stay on source',
() async {
final a = Machine(), b = Machine();
final sources = {
'a': ChatServerGateway(server('a'), a),
'b': ChatServerGateway(server('b'), b),
};
final all = FederatedChatGateway(
() => sources,
() => 'a',
const Stream.empty(),
);
final rows = (await all.call('chat_sessions'))['chat_sessions'] as List;
expect(rows.map((r) => r['id']).toSet(), {
federatedChatId('a', 'collision'),
federatedChatId('b', 'collision'),
});
final remote = federatedChatId('b', 'collision');
for (final type in [
'chat_messages',
'chat_models',
'chat_mode',
'chat_reply',
'chat_answer',
'chat_shell_output',
'chat_automations',
'chat_export',
'chat_interrupt',
'chat_close',
'chat_new_session',
'chat_unqueue',
]) {
final reply = await all.call(type, {
'chat_query': {
'session_id': remote,
'shell_id': 'shell',
'request_id': 'permission',
'operation_id': 'operation',
},
});
expect(b.calls.last.$2['chat_query'], {
'session_id': 'collision',
'shell_id': 'shell',
'request_id': 'permission',
'operation_id': 'operation',
});
expect((reply['chat_session'] as Map)['_server_name'], 'Machine b');
expect((reply['chat_messages'] as List).single['id'], 'message');
expect((reply['chat_messages'] as List).single['session_id'], remote);
}
expect(a.calls.length, 1);
b.fail = true;
await expectLater(
all.call('chat_prompt', {
'chat_prompt': {'session_id': remote},
}),
throwsStateError,
);
expect(a.calls.length, 1);
sources.remove('b');
await expectLater(
all.call('chat_prompt', {
'chat_prompt': {'session_id': remote},
}),
throwsStateError,
);
await a.events.close();
await b.events.close();
},
);
test(
'offline source retains cached rows while healthy source still lists',
() async {
final a = Machine(), b = Machine();
final sources = {
'a': ChatServerGateway(server('a'), a),
'b': ChatServerGateway(server('b'), b),
};
final all = FederatedChatGateway(
() => sources,
() => 'a',
const Stream.empty(),
);
await all.call('chat_sessions');
b.fail = true;
expect((await all.call('chat_sessions'))['chat_sessions'], hasLength(2));
sources.remove('b');
expect((await all.call('chat_sessions'))['chat_sessions'], hasLength(1));
await a.events.close();
await b.events.close();
},
);
test(
'events and read acknowledgements namespace only chat identities',
() async {
final machine = Machine(),
source = ChatServerGateway(server('b'), Machine());
final live = ChatServerGateway(server('b'), machine);
final frame = live.frames.first;
machine.events.add({
'type': 'chat_event',
'chat_event': {
'session_id': 'collision',
'id': 'event',
'part': {
'id': 'tool',
'state': {
'input': {'session_id': 'user-owned', 'id': 'tool-input'},
},
},
},
});
final event = (await frame)['chat_event'] as Map;
expect(event['session_id'], federatedChatId('b', 'collision'));
expect(event['id'], 'event');
expect(event['part']['id'], 'tool');
expect(event['part']['state']['input'], {
'session_id': 'user-owned',
'id': 'tool-input',
});
final all = FederatedChatGateway(
() => {'b': source},
() => 'b',
const Stream.empty(),
);
final reply = await all.call('ack_attention', {
'attention_acks': {
'chat_seen': {federatedChatId('b', 'collision'): 42},
'dismissed': [],
},
});
expect(reply['attention_acks']['chat_seen'], {
federatedChatId('b', 'collision'): 12,
});
expect(
(source.gateway as Machine)
.calls
.single
.$2['attention_acks']['chat_seen'],
{'collision': 42},
);
await machine.events.close();
await (source.gateway as Machine).events.close();
},
);
test(
'files, upload and artifacts retain browser relay and chosen endpoint',
() {
final actual = 'ws://linux.test:8083/connect';
final relay = Uri(
scheme: 'wss',
host: 'page.test',
path: '/peers/linux/connect',
queryParameters: {'endpoint': actual},
).toString();
final files = fileUrls(relay, '/home/operator/image.png')!;
expect(files.view.path, '/peers/linux/files');
expect(files.view.queryParameters['endpoint'], actual);
expect(files.view.queryParameters['path'], '/home/operator/image.png');
expect(
ServerUrl.resolveArtifactUrl(relay, '/chat-uploads')!.path,
'/peers/linux/chat-uploads',
);
expect(
ServerUrl.resolveArtifactUrl(relay, '/artifacts/7/2/file')!.path,
'/peers/linux/artifacts/7/2/file',
);
},
);
test('late removed-source response never reintroduces its chats', () async {
final a = Machine(), b = Machine();
final sources = {
'a': ChatServerGateway(server('a'), a),
'b': ChatServerGateway(server('b'), b),
};
final catalog = {'a', 'b'};
final all = FederatedChatGateway(
() => sources,
() => 'a',
const Stream.empty(),
catalogIds: () => catalog,
);
await all.call('chat_sessions');
b.pendingSessions = Completer<JsonMap>();
final pending = all.call('chat_sessions');
await Future<void>.delayed(Duration.zero);
sources.remove('b');
catalog.remove('b');
b.pendingSessions!.complete({
'chat_sessions': [
{'id': 'late', 'title': 'Removed machine'},
],
});
final rows = (await pending)['chat_sessions'] as List;
expect(rows, hasLength(1));
expect(rows.single['_server_id'], 'a');
await a.events.close();
await b.events.close();
});
test(
'retry detachment keeps cached chats while the profile still exists',
() async {
final a = Machine(), b = Machine();
final sources = {
'a': ChatServerGateway(server('a'), a),
'b': ChatServerGateway(server('b'), b),
};
final all = FederatedChatGateway(
() => sources,
() => 'a',
const Stream.empty(),
catalogIds: () => ['a', 'b'],
);
await all.call('chat_sessions');
sources.remove('b');
expect((await all.call('chat_sessions'))['chat_sessions'], hasLength(2));
await a.events.close();
await b.events.close();
},
);
test('opaque form answers cannot redirect a chat operation', () async {
final a = Machine(), b = Machine();
final sources = {
'a': ChatServerGateway(server('a'), a),
'b': ChatServerGateway(server('b'), b),
};
final all = FederatedChatGateway(
() => sources,
() => 'a',
const Stream.empty(),
);
final opaque = {
'session_id': federatedChatId('a', 'other'),
'id': 'user-answer',
};
await all.call('chat_answer', {
'chat_answer': {
'session_id': federatedChatId('b', 'collision'),
'answers': opaque,
},
});
expect(a.calls, isEmpty);
expect(b.calls.single.$2['chat_answer']['answers'], opaque);
await expectLater(
all.call('chat_prompt', {
'chat_prompt': {'session_id': 'chat@malformed!'},
}),
throwsStateError,
);
expect(a.calls, isEmpty);
await a.events.close();
await b.events.close();
});
test(
'retained adapter fails closed as soon as its connection is replaced',
() async {
final machine = Machine();
var current = true;
final source = ChatServerGateway(
server('a'),
machine,
isCurrent: () => current,
);
current = false;
await expectLater(
source.call('chat_prompt', {
'chat_prompt': {
'session_id': federatedChatId('a', 'collision'),
'text': 'must not send',
},
}),
throwsStateError,
);
expect(machine.calls, isEmpty);
expect(source.configuredEndpoint, isEmpty);
await machine.events.close();
},
);
}
@@ -0,0 +1,118 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/servers/chat/chat_identity.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/workspace/federated_workspace_store.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_snapshot.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_nodes.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_session_local.dart';
import 'package:pipelines_app/features/chat/ui/sessions/federated_chat_session_local.dart';
class MemoryWorkspace implements ChatWorkspaceStore {
ChatWorkspaceSnapshot? value;
@override
Future<ChatWorkspaceSnapshot?> read() async => value;
@override
Future<bool> write(ChatWorkspaceSnapshot snapshot) async {
value = snapshot;
return true;
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() => SharedPreferences.setMockInitialValues({}));
test(
'legacy panes migrate once and survive changing the default server',
() async {
final old = MemoryWorkspace()
..value = ChatWorkspaceSnapshot.fromLayout(
const ChatWorkspaceSplit(
'split',
ChatSplitAxis.horizontal,
ChatWorkspacePane('a', 'native1'),
ChatWorkspacePane('b', 'native2'),
ratio: .3,
),
'b',
sidebarMode: 'compact',
mobilePeekFraction: .08,
);
final combined = MemoryWorkspace();
final migrated = (await FederatedWorkspaceStore(
primary: 'mac',
combined: combined,
legacy: old,
).read())!;
final root = migrated.root as ChatWorkspaceSplit;
expect(
(root.first as ChatWorkspacePane).sessionId,
federatedChatId('mac', 'native1'),
);
expect(
(root.second as ChatWorkspacePane).sessionId,
federatedChatId('mac', 'native2'),
);
expect(migrated.activePaneId, 'b');
expect(root.ratio, .3);
expect(migrated.mobilePeekFraction, .08);
expect(
(await FederatedWorkspaceStore(
primary: 'linux',
combined: combined,
legacy: MemoryWorkspace(),
).read())!.encode(),
migrated.encode(),
);
expect(
(old.value!.root as ChatWorkspaceSplit).first,
isA<ChatWorkspacePane>(),
);
expect(
((old.value!.root as ChatWorkspaceSplit).first as ChatWorkspacePane)
.sessionId,
'native1',
);
},
);
test('composer keeps original scoped drafts and unsent intents', () async {
const mac = SharedPreferencesChatDraftStore(serverId: 'mac');
const linux = SharedPreferencesChatDraftStore(serverId: 'linux');
await mac.write('same', 'Mac draft');
await linux.write('same', 'Linux draft');
await mac.writeUnsent('same', [
{'operation_id': 'one', 'session_id': 'same'},
]);
expect(await mac.read(federatedChatId('mac', 'same')), 'Mac draft');
expect(await linux.read(federatedChatId('linux', 'same')), 'Linux draft');
expect((await mac.readUnsent(federatedChatId('mac', 'same'))).single, {
'operation_id': 'one',
'session_id': 'same',
});
await mac.write(federatedChatId('mac', 'same'), 'changed');
expect(await mac.read('same'), 'changed');
expect(await linux.read('same'), 'Linux draft');
});
test(
'per-machine hidden and read choices migrate without ID collisions',
() async {
await const SharedPreferencesChatSessionLocalStore(
serverId: 'mac',
).save(const ChatSessionLocal(hidden: ['same'], seenAt: {'same': 10}));
await const SharedPreferencesChatSessionLocalStore(
serverId: 'linux',
).save(const ChatSessionLocal(unseen: ['same'], seenAt: {'same': 20}));
final store = FederatedChatSessionLocalStore(() => ['mac', 'linux']);
final value = await store.load();
expect(value.hidden, [federatedChatId('mac', 'same')]);
expect(value.unseen, [federatedChatId('linux', 'same')]);
expect(value.seenAt, {
federatedChatId('mac', 'same'): 10,
federatedChatId('linux', 'same'): 20,
});
await store.save(value.restore(federatedChatId('mac', 'same')));
expect((await store.load()).hidden, isEmpty);
},
);
}
@@ -0,0 +1,190 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/application/pipelines_root.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/application/server_endpoint.dart';
import 'package:pipelines_app/core/servers/chat/chat_identity.dart';
import 'package:pipelines_app/core/servers/chat/chat_server_gateway.dart';
import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart';
import 'package:pipelines_app/core/servers/chat/federated_chat_gateway.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
import 'package:pipelines_app/core/servers/server_context.dart';
import 'package:pipelines_app/core/session/server_session.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
import 'package:pipelines_app/features/onboarding/onboarding_flow.dart';
import 'package:pipelines_app/features/settings/server_connections.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import '../../../features/chat/ui/sessions/fake_chat_gateway.dart';
import '../../../features/chat/ui/sessions/chat_test_harness.dart';
import '../../transport/pipelines_client_test.dart' show FakeChannel;
import 'federated_chat_gateway_test.dart' show Machine;
SavedServer machine(String id) => SavedServer.validated(
id: id,
name: id == 'mac' ? 'Mac' : 'Linux',
endpoints: ['ws://$id.test/connect'],
);
Future<void> frames(WidgetTester tester) async {
for (var i = 0; i < 16; i++) {
await tester.pump(const Duration(milliseconds: 20));
}
}
void main() {
setUp(() => SharedPreferences.setMockInitialValues({}));
testWidgets(
'one machine skips selection and opens its harness dialog directly',
(tester) async {
final gateway = FakeChatGateway();
final connections = ServerConnections(
store: MemoryServerCatalogStore(
catalog: ServerCatalog(servers: [machine('mac')], selectedId: 'mac'),
),
onSelected: (_) async {},
);
await connections.load();
await tester.pumpWidget(
ServerContext(
connections: connections,
serverId: 'mac',
child: MaterialApp(
home: ChatSessionsScreen(
gateway: gateway,
onOpen: (_) {},
localStore: MemoryChatSessionLocalStore(),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-new-chat')));
await tester.pumpAndSettle();
expect(find.text('New chat on…'), findsNothing);
expect(find.byKey(const Key('chat-create-confirm')), findsOneWidget);
expect(gateway.count('chat_backends'), 1);
await tester.pumpWidget(const SizedBox());
connections.dispose();
await gateway.pushed.close();
},
);
testWidgets(
'new chat uses chosen machine without switching primary or closing other chats',
(tester) async {
final a = FakeChatGateway(),
b = FakeChatGateway()
..backendsHandler = () async => {
'chat_backends': ['claude'],
};
var selections = 0;
final connections = ServerConnections(
store: MemoryServerCatalogStore(
catalog: ServerCatalog(
servers: [machine('mac'), machine('linux')],
selectedId: 'mac',
),
),
onSelected: (_) async {
selections++;
},
);
await connections.load();
final sources = {
'mac': ChatServerGateway(machine('mac'), a),
'linux': ChatServerGateway(machine('linux'), b),
};
final gateway = FederatedChatGateway(
() => sources,
() => 'mac',
const Stream.empty(),
);
String? opened;
await tester.pumpWidget(
ServerContext(
connections: connections,
serverId: 'mac',
child: MaterialApp(
home: ChatSessionsScreen(
gateway: gateway,
onOpen: (row) => opened = row['id'] as String,
localStore: MemoryChatSessionLocalStore(),
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-new-chat')));
await tester.pumpAndSettle();
await tester.tap(find.text('Linux'));
await tester.pumpAndSettle();
expect(connections.catalog.active?.id, 'mac');
expect(selections, 0);
expect(a.count('chat_backends'), 0);
expect(b.count('chat_backends'), 1);
expect(find.text('Linux · Start a chat'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-create-confirm')));
await tester.pumpAndSettle();
expect(b.count('chat_create'), 1);
expect(a.count('chat_create'), 0);
expect(opened, federatedChatId('linux', 'created'));
await tester.pumpWidget(const SizedBox());
connections.dispose();
await a.pushed.close();
await b.pushed.close();
},
);
testWidgets(
'missing primary password keeps secondary chat connection available',
(tester) async {
final servers = [machine('mac'), machine('linux')];
final a = Machine()..fail = true, b = Machine();
await tester.pumpWidget(
PipelinesRoot(
server: ServerEndpoint.resolve(
base: Uri.parse('file:///'),
web: false,
configured: servers.first.endpoints.first,
),
nativeUpdatesSupported: false,
settingsStore: MemorySettingsStore(),
catalogStore: MemoryServerCatalogStore(
catalog: ServerCatalog(servers: servers, selectedId: 'mac'),
),
check: (_) async => SessionState.signedOut,
clientFactory: () => PipelinesClient(
channelFactory: (_) => FakeChannel()..readyCompleter.complete(),
),
chatPoolFactory: (connections) => ChatServerPool(
connections,
connect: (server) async => ChatMachineConnection(
gateway: server.id == 'mac' ? a : b,
endpoint: () => server.endpoints.first,
connected: () => server.id == 'linux',
states: const Stream.empty(),
close: () async {},
retry: () async {},
),
),
),
);
await frames(tester);
expect(find.byType(OnboardingFlow), findsNothing);
expect(find.byType(PipelinesApp), findsOneWidget);
final app = tester.widget<PipelinesApp>(find.byType(PipelinesApp));
final rows =
(await app.chatPool!.gateway.call('chat_sessions'))['chat_sessions']
as List;
expect(rows.single['_server_id'], 'linux');
expect(
app.chatPool!.machines.where((m) => m.connected).single.server.id,
'linux',
);
await tester.pumpWidget(const SizedBox());
await frames(tester);
await a.events.close();
await b.events.close();
},
);
}