Connect saved machines concurrently in the chat workspace
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import '../core/servers/chat/chat_server_pool.dart';
|
||||
import '../core/servers/chat/chat_server_status.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../features/chat/screen.dart';
|
||||
@@ -18,6 +20,7 @@ class ChatDestination extends StatelessWidget {
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.server,
|
||||
this.pool,
|
||||
this.initialSessionId,
|
||||
this.onSessionSelected,
|
||||
this.onBack,
|
||||
@@ -26,6 +29,7 @@ class ChatDestination extends StatelessWidget {
|
||||
});
|
||||
|
||||
final AppSession session;
|
||||
final ChatServerPool? pool;
|
||||
final ServerEndpoint server;
|
||||
final String? initialSessionId;
|
||||
final ValueChanged<String>? onSessionSelected;
|
||||
@@ -35,9 +39,15 @@ class ChatDestination extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AnimatedBuilder(
|
||||
animation: session,
|
||||
animation: Listenable.merge([session, ?pool]),
|
||||
builder: (context, _) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
if (pool != null && pool!.servers.catalog.servers.isNotEmpty) {
|
||||
return TopBarNotices(
|
||||
notices: [ChatServerStatusBar(pool: pool!)],
|
||||
child: _chatScreen(),
|
||||
);
|
||||
}
|
||||
if ((server.requiresConfiguration || server.error != null) &&
|
||||
session.endpoint == null) {
|
||||
return ConnectionGate(
|
||||
@@ -68,10 +78,12 @@ class ChatDestination extends StatelessWidget {
|
||||
);
|
||||
|
||||
Widget _chatScreen() => ChatScreen(
|
||||
gateway: session.gateway,
|
||||
gateway: pool?.gateway ?? session.gateway,
|
||||
persistWorkspace: true,
|
||||
initialSessionId: initialSessionId,
|
||||
syncToken: session.connectionEpoch,
|
||||
initialSessionId: initialSessionId == null
|
||||
? null
|
||||
: pool?.gateway.normalizeId(initialSessionId!) ?? initialSessionId,
|
||||
syncToken: pool?.revision ?? session.connectionEpoch,
|
||||
onSessionSelected: onSessionSelected,
|
||||
onBack: onBack,
|
||||
onWorkspaceEmpty: onWorkspaceEmpty,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../core/servers/chat/chat_server_pool.dart';
|
||||
import '../core/servers/server_context.dart';
|
||||
import '../ui/adaptive/platform.dart';
|
||||
import 'dart:async';
|
||||
@@ -68,6 +69,7 @@ class PipelinesApp extends StatefulWidget {
|
||||
this.serverAddresses,
|
||||
this.serverId,
|
||||
this.servers,
|
||||
this.chatPool,
|
||||
this.resetRoute = false,
|
||||
this.legacyPendingEndpoints = const [],
|
||||
this.webPlatform = kIsWeb,
|
||||
@@ -95,6 +97,7 @@ class PipelinesApp extends StatefulWidget {
|
||||
final List<Uri>? serverAddresses;
|
||||
final String? serverId;
|
||||
final ServerConnections? servers;
|
||||
final ChatServerPool? chatPool;
|
||||
final bool resetRoute;
|
||||
final List<String> legacyPendingEndpoints;
|
||||
final bool webPlatform;
|
||||
@@ -223,11 +226,19 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
// The comparison includes the query: `?visit=N` is part of the route, while
|
||||
// a dropped or unknown query is canonicalised away.
|
||||
final location = routeLocation(_provider.value.uri);
|
||||
final initial =
|
||||
var initial =
|
||||
widget.servers?.newChatServerId == widget.serverId &&
|
||||
widget.serverId != null
|
||||
? AppRoute.chat
|
||||
: AppRoute.parse(location);
|
||||
if (widget.chatPool != null) {
|
||||
final id = initial.chatSessionId;
|
||||
if (id != null) {
|
||||
initial = AppRoute.chatSession(
|
||||
widget.chatPool!.gateway.normalizeId(id),
|
||||
);
|
||||
}
|
||||
}
|
||||
final nativeDefault =
|
||||
widget.routeInformationProvider == null &&
|
||||
!kIsWeb &&
|
||||
@@ -615,6 +626,14 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
|
||||
void _routeChanged() {
|
||||
final shown = _delegate.route;
|
||||
final id = shown.chatSessionId;
|
||||
if (id != null && widget.chatPool != null) {
|
||||
final scoped = widget.chatPool!.gateway.normalizeId(id);
|
||||
if (scoped != id) {
|
||||
_delegate.goTo(AppRoute.chatSession(scoped));
|
||||
return;
|
||||
}
|
||||
}
|
||||
_tabLocations.record(shown);
|
||||
_rememberBodyRoute(_delegate.shellRoute);
|
||||
_rememberChatRoute(shown);
|
||||
@@ -626,7 +645,10 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
}
|
||||
|
||||
Future<String?> _chatSessionTitle(String id) async {
|
||||
final reply = await _session.gateway.call('chat_sessions');
|
||||
id = widget.chatPool?.gateway.normalizeId(id) ?? id;
|
||||
final reply = await (widget.chatPool?.gateway ?? _session.gateway).call(
|
||||
'chat_sessions',
|
||||
);
|
||||
final sessions = reply['chat_sessions'];
|
||||
if (sessions is! List) return null;
|
||||
for (final value in sessions) {
|
||||
@@ -756,6 +778,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
),
|
||||
),
|
||||
AppDestination.chat: (_) => ChatDestination(
|
||||
pool: widget.chatPool,
|
||||
session: _session,
|
||||
server: widget.server,
|
||||
initialSessionId: chatRoute.chatSessionId,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
import '../core/servers/chat/chat_server_pool.dart';
|
||||
import '../ui/adaptive/platform.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
@@ -34,6 +36,8 @@ class PipelinesRoot extends StatefulWidget {
|
||||
this.web = kIsWeb,
|
||||
this.clientFactory,
|
||||
this.nativeUpdatesSupported,
|
||||
this.federatedChats = true,
|
||||
this.chatPoolFactory,
|
||||
});
|
||||
|
||||
final ServerEndpoint server;
|
||||
@@ -50,6 +54,8 @@ class PipelinesRoot extends StatefulWidget {
|
||||
|
||||
/// Optional capability override for platform hosts and isolated widget tests.
|
||||
final bool? nativeUpdatesSupported;
|
||||
final bool federatedChats;
|
||||
final ChatServerPool Function(ServerConnections)? chatPoolFactory;
|
||||
final PipelinesClient Function()? clientFactory;
|
||||
|
||||
@override
|
||||
@@ -65,6 +71,15 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
int _activation = 0;
|
||||
PipelinesClient? _client;
|
||||
SavedServer? _activeServer;
|
||||
ChatServerPool? _chatPool;
|
||||
void _ensureChatPool() {
|
||||
if (widget.federatedChats && _chatPool == null) {
|
||||
_chatPool =
|
||||
widget.chatPoolFactory?.call(_servers) ??
|
||||
ChatServerPool(_servers, web: widget.web);
|
||||
}
|
||||
}
|
||||
|
||||
late final ServerConnections _servers = ServerConnections(
|
||||
store: widget.catalogStore,
|
||||
onSelected: _selectServer,
|
||||
@@ -87,6 +102,7 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
_servers.restoreNewChatIntent(id);
|
||||
}
|
||||
}
|
||||
_ensureChatPool();
|
||||
setState(() {
|
||||
_booting = false;
|
||||
_onboarding = false;
|
||||
@@ -156,16 +172,20 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
}
|
||||
if (!mounted || token != _activation) return;
|
||||
_activeServer = server;
|
||||
_ensureChatPool();
|
||||
setState(() {
|
||||
_server = ServerEndpoint.resolve(
|
||||
base: Uri.base,
|
||||
web: false,
|
||||
configured: server?.endpoints.first ?? '',
|
||||
);
|
||||
_onboarding =
|
||||
server == null ||
|
||||
(ServerSession.cookie == null &&
|
||||
!(initial && widget.signedIn && server.id == 'legacy-server'));
|
||||
_onboarding = widget.federatedChats
|
||||
? _servers.catalog.servers.isEmpty
|
||||
: server == null ||
|
||||
(ServerSession.cookie == null &&
|
||||
!(initial &&
|
||||
widget.signedIn &&
|
||||
server.id == 'legacy-server'));
|
||||
_refused = false;
|
||||
_generation++;
|
||||
_booting = false;
|
||||
@@ -178,6 +198,11 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
|
||||
/// A kept session the server now refuses asks for the password again.
|
||||
Future<void> _verify(Uri endpoint) async {
|
||||
if (widget.federatedChats &&
|
||||
_chatPool != null &&
|
||||
_servers.catalog.servers.isNotEmpty) {
|
||||
return;
|
||||
}
|
||||
final token = _activation;
|
||||
final result = await probeServerAddresses(
|
||||
[
|
||||
@@ -206,7 +231,9 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
}
|
||||
|
||||
void _done(Uri endpoint) {
|
||||
_ensureChatPool();
|
||||
_activeServer = _servers.catalog.active;
|
||||
if (_activeServer != null) unawaited(_chatPool?.retry(_activeServer!.id));
|
||||
setState(() {
|
||||
_server = ServerEndpoint.resolve(
|
||||
base: Uri.base,
|
||||
@@ -220,16 +247,17 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _saveOnboardingServer(String url) async {
|
||||
Future<void> _saveOnboardingServer(String url, {String? name}) async {
|
||||
final token = _activation;
|
||||
final active = _servers.catalog.active;
|
||||
SavedServer? target;
|
||||
for (final server in _servers.catalog.servers) {
|
||||
if (server.endpoints.contains(url)) target = server;
|
||||
}
|
||||
target ??= SavedServer.validated(
|
||||
id: 'server-${DateTime.now().microsecondsSinceEpoch}',
|
||||
name: active == null ? 'My server' : 'New server',
|
||||
name: name?.trim().isNotEmpty == true
|
||||
? name!.trim()
|
||||
: Uri.parse(url).host,
|
||||
endpoints: [url],
|
||||
);
|
||||
if (!await _servers.save(target, activate: false) ||
|
||||
@@ -250,6 +278,7 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
@override
|
||||
void dispose() {
|
||||
_activation++;
|
||||
_chatPool?.dispose();
|
||||
_servers.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
@@ -280,6 +309,7 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
if (!_onboarding) {
|
||||
return PipelinesApp(
|
||||
androidSupported: widget.nativeUpdatesSupported,
|
||||
chatPool: _chatPool,
|
||||
key: ValueKey(_generation),
|
||||
server: _server,
|
||||
client: _client,
|
||||
@@ -297,6 +327,7 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
initialServer: _server.uri?.toString() ?? widget.buildDefault,
|
||||
startAtPassword: _refused,
|
||||
saveServer: _saveOnboardingServer,
|
||||
saveServerProfile: (url, name) => _saveOnboardingServer(url, name: name),
|
||||
onDone: _done,
|
||||
savedServers: SavedServersSection(connections: _servers),
|
||||
discovery: platformServerDiscovery(web: widget.web),
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import '../server_catalog.dart';
|
||||
import 'browser_peer_stub.dart'
|
||||
if (dart.library.js_interop) 'browser_peer_web.dart'
|
||||
as impl;
|
||||
|
||||
Future<({bool connected, String? error})> registerBrowserPeer(
|
||||
SavedServer server, {
|
||||
String? password,
|
||||
}) => impl.register(server, password: password);
|
||||
Future<void> removeBrowserPeer(String id) => impl.remove(id);
|
||||
Uri browserPeerEndpoint(String id, Uri endpoint, {Uri? page}) {
|
||||
final origin = page ?? Uri.base;
|
||||
return origin.replace(
|
||||
scheme: origin.scheme == 'https' ? 'wss' : 'ws',
|
||||
path: '/peers/${Uri.encodeComponent(id)}/connect',
|
||||
queryParameters: {'endpoint': endpoint.toString()},
|
||||
fragment: null,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import '../server_catalog.dart';
|
||||
|
||||
Future<({bool connected, String? error})> register(
|
||||
SavedServer server, {
|
||||
String? password,
|
||||
}) async =>
|
||||
(connected: false, error: 'Browser relay is unavailable on this platform.');
|
||||
Future<void> remove(String id) async {}
|
||||
@@ -0,0 +1,63 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:js_interop';
|
||||
import '../server_catalog.dart';
|
||||
|
||||
@JS('fetch')
|
||||
external JSPromise<_Response> _fetch(JSString url, _Options options);
|
||||
|
||||
extension type _Options._(JSObject _) implements JSObject {
|
||||
external factory _Options({
|
||||
JSString method,
|
||||
JSString credentials,
|
||||
JSString cache,
|
||||
JSString body,
|
||||
JSObject headers,
|
||||
});
|
||||
}
|
||||
|
||||
extension type _Response._(JSObject _) implements JSObject {
|
||||
external int get status;
|
||||
external JSPromise<JSString> text();
|
||||
}
|
||||
|
||||
Future<({bool connected, String? error})> register(
|
||||
SavedServer server, {
|
||||
String? password,
|
||||
}) async {
|
||||
final response = await _fetch(
|
||||
'/api/peers/${Uri.encodeComponent(server.id)}'.toJS,
|
||||
_Options(
|
||||
method: 'POST'.toJS,
|
||||
credentials: 'same-origin'.toJS,
|
||||
cache: 'no-store'.toJS,
|
||||
headers: {'Content-Type': 'application/json'}.jsify() as JSObject,
|
||||
body: jsonEncode({
|
||||
'endpoints': server.endpoints,
|
||||
'password': ?password,
|
||||
}).toJS,
|
||||
),
|
||||
).toDart.timeout(const Duration(seconds: 20));
|
||||
final body = jsonDecode((await response.text().toDart).toDart);
|
||||
if (response.status == 200 && body is Map && body['connected'] == true) {
|
||||
return (connected: true, error: null);
|
||||
}
|
||||
return (
|
||||
connected: false,
|
||||
error: body is Map && body['needs_password'] == true
|
||||
? 'Sign in to this machine.'
|
||||
: body is Map
|
||||
? '${body['error'] ?? 'Could not connect to this machine.'}'
|
||||
: 'Could not connect to this machine.',
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> remove(String id) async {
|
||||
await _fetch(
|
||||
'/api/peers/${Uri.encodeComponent(id)}'.toJS,
|
||||
_Options(
|
||||
method: 'DELETE'.toJS,
|
||||
credentials: 'same-origin'.toJS,
|
||||
cache: 'no-store'.toJS,
|
||||
),
|
||||
).toDart;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import 'dart:convert';
|
||||
|
||||
/// IDs rendered by the combined chat view always retain their machine origin.
|
||||
String federatedChatId(String server, String native) =>
|
||||
'chat@${base64Url.encode(utf8.encode(jsonEncode([server, native]))).replaceAll('=', '')}';
|
||||
|
||||
({String server, String native})? parseFederatedChatId(String value) {
|
||||
if (!value.startsWith('chat@')) return null;
|
||||
try {
|
||||
final parts = jsonDecode(
|
||||
utf8.decode(base64Url.decode(base64Url.normalize(value.substring(5)))),
|
||||
);
|
||||
if (parts is List &&
|
||||
parts.length == 2 &&
|
||||
parts.every((v) => v is String && v.isNotEmpty)) {
|
||||
return (server: parts[0] as String, native: parts[1] as String);
|
||||
}
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'dart:async';
|
||||
import '../../api_gateway.dart';
|
||||
import '../../session/server_session.dart';
|
||||
import '../../transport/channel_connect.dart';
|
||||
import '../../transport/pipelines_client.dart';
|
||||
import '../server_catalog.dart';
|
||||
import 'browser_peer.dart';
|
||||
|
||||
class ChatMachineConnection {
|
||||
ChatMachineConnection({
|
||||
required this.gateway,
|
||||
required this.endpoint,
|
||||
required this.connected,
|
||||
required this.states,
|
||||
required this.close,
|
||||
required this.retry,
|
||||
this.headers,
|
||||
});
|
||||
final ApiGateway gateway;
|
||||
final Map<String, String> Function(Uri)? headers;
|
||||
final String Function() endpoint;
|
||||
final bool Function() connected;
|
||||
final Stream<ConnectionState> states;
|
||||
final Future<void> Function() close, retry;
|
||||
}
|
||||
|
||||
Future<ChatMachineConnection> connectChatMachine(
|
||||
SavedServer server, {
|
||||
required bool web,
|
||||
}) async {
|
||||
final actual = server.endpoints.map(Uri.parse).toList();
|
||||
var endpoints = actual;
|
||||
Map<String, String> Function(Uri)? headers;
|
||||
if (web) {
|
||||
final local = actual
|
||||
.where(
|
||||
(uri) =>
|
||||
uri
|
||||
.replace(scheme: uri.scheme == 'wss' ? 'https' : 'http')
|
||||
.origin ==
|
||||
Uri.base.origin,
|
||||
)
|
||||
.toList();
|
||||
if (local.isNotEmpty) {
|
||||
endpoints = local;
|
||||
} else {
|
||||
final result = await registerBrowserPeer(server);
|
||||
if (!result.connected) {
|
||||
throw StateError(result.error ?? 'Sign in to this machine.');
|
||||
}
|
||||
endpoints = actual
|
||||
.map((uri) => browserPeerEndpoint(server.id, uri))
|
||||
.toList();
|
||||
}
|
||||
} else {
|
||||
headers = await ServerSession.credentialReader(
|
||||
id: server.id,
|
||||
endpoints: actual,
|
||||
);
|
||||
}
|
||||
final client = PipelinesClient(
|
||||
channelFactory: headers == null
|
||||
? null
|
||||
: (uri) => connectScopedPipelinesChannel(uri, headers!),
|
||||
);
|
||||
await client.connectAny(endpoints);
|
||||
return ChatMachineConnection(
|
||||
gateway: client,
|
||||
headers: headers,
|
||||
endpoint: () => client.endpoint?.toString() ?? '',
|
||||
connected: () => client.state.kind == ConnectionKind.connected,
|
||||
states: client.states,
|
||||
close: client.dispose,
|
||||
retry: () => client.connectAny(endpoints),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import 'dart:async';
|
||||
import '../../api_gateway.dart';
|
||||
import '../../transport/pipelines_client.dart';
|
||||
import '../server_catalog.dart';
|
||||
import '../server_scope.dart';
|
||||
import 'chat_identity.dart';
|
||||
|
||||
/// Machine-bound chat protocol adapter. Tool inputs, user answers, message IDs
|
||||
/// and provider payloads are opaque; only protocol-owned session IDs change.
|
||||
class ChatServerGateway implements ApiGateway, EndpointGateway {
|
||||
ChatServerGateway(this.server, this.gateway, {this.isCurrent}) {
|
||||
bindServerIdentity(this, server.id);
|
||||
}
|
||||
SavedServer server;
|
||||
final ApiGateway gateway;
|
||||
final bool Function()? isCurrent;
|
||||
@override
|
||||
String get configuredEndpoint =>
|
||||
(isCurrent?.call() ?? true) ? configuredGatewayEndpoint(gateway) : '';
|
||||
String id(String native) => federatedChatId(server.id, native);
|
||||
String nativeId(String value) {
|
||||
final parsed = parseFederatedChatId(value);
|
||||
if (parsed == null) {
|
||||
if (value.startsWith('chat@')) {
|
||||
throw StateError('This chat identity is invalid.');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
if (parsed.server != server.id) {
|
||||
throw StateError('This chat belongs to another machine.');
|
||||
}
|
||||
return parsed.native;
|
||||
}
|
||||
|
||||
JsonMap _owner(Map value, {required bool incoming}) {
|
||||
final result = Map<String, dynamic>.from(value);
|
||||
for (final key in ['session_id', 'previous_id']) {
|
||||
if (result[key] case final String value) {
|
||||
if (value.isNotEmpty) {
|
||||
result[key] = incoming ? id(value) : nativeId(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
JsonMap _acks(Map value, {required bool incoming}) {
|
||||
final result = Map<String, dynamic>.from(value);
|
||||
if (result['chat_seen'] case final Map seen) {
|
||||
result['chat_seen'] = {
|
||||
for (final entry in seen.entries)
|
||||
(incoming ? id('${entry.key}') : nativeId('${entry.key}')):
|
||||
entry.value,
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
JsonMap _out(JsonMap fields) => {
|
||||
for (final entry in fields.entries)
|
||||
entry.key: entry.key == 'attention_acks' && entry.value is Map
|
||||
? _acks(entry.value as Map, incoming: false)
|
||||
: entry.key.startsWith('chat_') && entry.value is Map
|
||||
? _owner(entry.value as Map, incoming: false)
|
||||
: entry.value,
|
||||
};
|
||||
JsonMap _message(Map value) => _owner(value, incoming: true);
|
||||
JsonMap _in(JsonMap fields) {
|
||||
final result = Map<String, dynamic>.from(fields);
|
||||
for (final entry in fields.entries) {
|
||||
final key = entry.key, value = entry.value;
|
||||
if (key == 'attention_acks' && value is Map) {
|
||||
result[key] = _acks(value, incoming: true);
|
||||
continue;
|
||||
}
|
||||
if (key == 'chat_sessions' && value is List) {
|
||||
result[key] = value.whereType<Map>().map(_session).toList();
|
||||
continue;
|
||||
}
|
||||
if (key == 'chat_session' && value is Map) {
|
||||
result[key] = _session(value);
|
||||
continue;
|
||||
}
|
||||
if (key == 'chat_messages' && value is List) {
|
||||
result[key] = value.whereType<Map>().map(_message).toList();
|
||||
continue;
|
||||
}
|
||||
if (key.startsWith('chat_') && value is Map) {
|
||||
final body = _owner(value, incoming: true);
|
||||
if (key == 'chat_history') {
|
||||
if (body['messages'] case final List messages) {
|
||||
body['messages'] = messages.whereType<Map>().map(_message).toList();
|
||||
}
|
||||
}
|
||||
if (key == 'chat_event') {
|
||||
if (body['form'] case final Map form) {
|
||||
body['form'] = _owner(form, incoming: true);
|
||||
}
|
||||
}
|
||||
result[key] = body;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
JsonMap _session(Map value) {
|
||||
final row = _owner(value, incoming: true);
|
||||
if (row['id'] case final String native) {
|
||||
row['id'] = id(native);
|
||||
}
|
||||
if (row['activity'] case final Map activity) {
|
||||
row['activity'] = _owner(activity, incoming: true);
|
||||
}
|
||||
row['_server_id'] = server.id;
|
||||
row['_server_name'] = server.name;
|
||||
return row;
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames =>
|
||||
gateway.frames.where((_) => isCurrent?.call() ?? true).map(_in);
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (!(isCurrent?.call() ?? true)) {
|
||||
throw StateError('This machine connection changed. Retry.');
|
||||
}
|
||||
return _in(await gateway.call(type, _out(fields)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import '../../../features/attention/runtime/attention_ack_sync.dart';
|
||||
import '../../../features/attention/runtime/attention_ack_queue.dart';
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../../api_gateway.dart';
|
||||
import 'chat_machine_connection.dart';
|
||||
export 'chat_machine_connection.dart';
|
||||
import '../../session/server_session.dart';
|
||||
import '../../transport/pipelines_client.dart';
|
||||
import '../../../features/settings/server_connections.dart';
|
||||
import '../server_catalog.dart';
|
||||
import 'browser_peer.dart';
|
||||
import 'chat_server_gateway.dart';
|
||||
import 'federated_chat_gateway.dart';
|
||||
|
||||
class ChatMachineStatus {
|
||||
ChatMachineStatus(this.server);
|
||||
SavedServer server;
|
||||
bool connecting = true, connected = false;
|
||||
String? error;
|
||||
ChatMachineConnection? connection;
|
||||
ChatServerGateway? adapter;
|
||||
StreamSubscription<JsonMap>? frames;
|
||||
StreamSubscription<ConnectionState>? states;
|
||||
int generation = 0;
|
||||
}
|
||||
|
||||
/// One independent authenticated socket per saved machine. Aliases are failover
|
||||
/// addresses of that machine, never a fallback to another machine's identity.
|
||||
class ChatServerPool extends ChangeNotifier {
|
||||
ChatServerPool(this.servers, {this.connect, this.web = kIsWeb}) {
|
||||
gateway = FederatedChatGateway(
|
||||
() => {
|
||||
for (final item in _machines.values)
|
||||
if (item.adapter != null) item.server.id: item.adapter!,
|
||||
},
|
||||
() => servers.catalog.active?.id,
|
||||
_frames.stream,
|
||||
catalogIds: () => servers.catalog.servers.map((server) => server.id),
|
||||
);
|
||||
ackSync = AttentionAckSync(
|
||||
gateway: gateway,
|
||||
queue: const SharedPreferencesAttentionAckQueue(
|
||||
serverId: 'all-saved-servers',
|
||||
),
|
||||
);
|
||||
bindAttentionAckSync(gateway, ackSync);
|
||||
_credentials = ServerSession.credentialChanges.listen((id) {
|
||||
if (!_disposed && !_signingIn.contains(id) && _machines.containsKey(id)) {
|
||||
unawaited(retry(id));
|
||||
}
|
||||
});
|
||||
servers.addListener(update);
|
||||
scheduleMicrotask(update);
|
||||
}
|
||||
final ServerConnections servers;
|
||||
final bool web;
|
||||
final Future<ChatMachineConnection> Function(SavedServer)? connect;
|
||||
final _machines = <String, ChatMachineStatus>{};
|
||||
final _frames = StreamController<JsonMap>.broadcast();
|
||||
late final FederatedChatGateway gateway;
|
||||
late final AttentionAckSync ackSync;
|
||||
List<ChatMachineStatus> get machines => List.unmodifiable(_machines.values);
|
||||
int revision = 0;
|
||||
bool _disposed = false;
|
||||
late final StreamSubscription<String> _credentials;
|
||||
final _signingIn = <String>{};
|
||||
|
||||
void update() {
|
||||
if (_disposed) return;
|
||||
final catalog = servers.catalog.servers;
|
||||
final ids = catalog.map((v) => v.id).toSet();
|
||||
for (final id in _machines.keys.where((id) => !ids.contains(id)).toList()) {
|
||||
final old = _machines.remove(id)!;
|
||||
_detach(old);
|
||||
if (web) unawaited(removeBrowserPeer(id).catchError((_) {}));
|
||||
revision++;
|
||||
}
|
||||
for (final server in catalog) {
|
||||
final old = _machines[server.id];
|
||||
if (old == null) {
|
||||
final item = ChatMachineStatus(server);
|
||||
_machines[server.id] = item;
|
||||
unawaited(_open(item));
|
||||
} else if (!listEquals(old.server.endpoints, server.endpoints)) {
|
||||
old.server = server;
|
||||
unawaited(_open(old));
|
||||
} else {
|
||||
old.server = server;
|
||||
old.adapter?.server = server;
|
||||
}
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _detach(ChatMachineStatus item) async {
|
||||
item.generation++;
|
||||
ServerSession.removeReader(item);
|
||||
final frames = item.frames,
|
||||
states = item.states,
|
||||
connection = item.connection;
|
||||
item.frames = null;
|
||||
item.states = null;
|
||||
item.connection = null;
|
||||
item.adapter = null;
|
||||
await frames?.cancel();
|
||||
await states?.cancel();
|
||||
await connection?.close();
|
||||
}
|
||||
|
||||
Future<void> _open(ChatMachineStatus item) async {
|
||||
final generation = item.generation + 1;
|
||||
await _detach(item);
|
||||
if (generation != item.generation) return;
|
||||
if (_disposed || !identical(_machines[item.server.id], item)) return;
|
||||
item.connecting = true;
|
||||
item.connected = false;
|
||||
item.error = null;
|
||||
notifyListeners();
|
||||
try {
|
||||
final connection =
|
||||
await (connect ?? (server) => connectChatMachine(server, web: web))(
|
||||
item.server,
|
||||
);
|
||||
if (_disposed ||
|
||||
generation != item.generation ||
|
||||
!identical(_machines[item.server.id], item)) {
|
||||
await connection.close();
|
||||
return;
|
||||
}
|
||||
item.connection = connection;
|
||||
if (connection.headers case final reader?) {
|
||||
ServerSession.registerReader(item, reader);
|
||||
}
|
||||
late final ChatServerGateway adapter;
|
||||
adapter = ChatServerGateway(
|
||||
item.server,
|
||||
connection.gateway,
|
||||
isCurrent: () =>
|
||||
!_disposed &&
|
||||
generation == item.generation &&
|
||||
identical(item.adapter, adapter),
|
||||
);
|
||||
item.adapter = adapter;
|
||||
item.connected = connection.connected();
|
||||
item.connecting = false;
|
||||
item.error = item.connected
|
||||
? null
|
||||
: 'Could not connect. Retry or sign in.';
|
||||
item.frames = item.adapter!.frames.listen((frame) {
|
||||
if (!_disposed) _frames.add(frame);
|
||||
});
|
||||
item.states = connection.states.listen((state) {
|
||||
if (_disposed) return;
|
||||
final was = item.connected;
|
||||
item.connected = state.kind == ConnectionKind.connected;
|
||||
item.connecting = state.kind == ConnectionKind.connecting;
|
||||
item.error = item.connected ? null : state.reason;
|
||||
if (item.connected && !was) {
|
||||
revision++;
|
||||
unawaited(ackSync.connected());
|
||||
}
|
||||
notifyListeners();
|
||||
});
|
||||
revision++;
|
||||
if (item.connected) unawaited(ackSync.connected());
|
||||
} catch (error) {
|
||||
if (_disposed || generation != item.generation) return;
|
||||
item.connecting = false;
|
||||
item.connected = false;
|
||||
item.error = '$error';
|
||||
}
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> retry(String id) async {
|
||||
final item = _machines[id];
|
||||
if (item != null) await _open(item);
|
||||
}
|
||||
|
||||
Future<String?> signIn(String id, String password) async {
|
||||
final item = _machines[id];
|
||||
if (item == null) return 'This machine was removed.';
|
||||
final endpoints = List<String>.of(item.server.endpoints);
|
||||
final generation = item.generation;
|
||||
bool current() =>
|
||||
!_disposed &&
|
||||
identical(_machines[id], item) &&
|
||||
item.generation == generation &&
|
||||
listEquals(item.server.endpoints, endpoints);
|
||||
_signingIn.add(id);
|
||||
try {
|
||||
if (web) {
|
||||
final result = await registerBrowserPeer(
|
||||
item.server,
|
||||
password: password,
|
||||
);
|
||||
if (!result.connected) return result.error ?? 'Sign-in failed.';
|
||||
} else {
|
||||
final error = await ServerSession.signInProfile(
|
||||
id: id,
|
||||
endpoints: endpoints.map(Uri.parse),
|
||||
password: password,
|
||||
isCurrent: current,
|
||||
);
|
||||
if (error != null) return error;
|
||||
}
|
||||
if (!current()) return 'The machine changed. Retry signing in.';
|
||||
await _open(item);
|
||||
return item.connected
|
||||
? null
|
||||
: item.error ?? 'The machine is not connected.';
|
||||
} finally {
|
||||
_signingIn.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
bindAttentionAckSync(gateway, null);
|
||||
ackSync.dispose();
|
||||
servers.removeListener(update);
|
||||
unawaited(_credentials.cancel());
|
||||
for (final item in _machines.values) {
|
||||
unawaited(_detach(item));
|
||||
}
|
||||
unawaited(_frames.close());
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'chat_server_pool.dart';
|
||||
|
||||
/// Connection problems on one machine never hide healthy machines' chats.
|
||||
class ChatServerStatusBar extends StatelessWidget {
|
||||
const ChatServerStatusBar({super.key, required this.pool});
|
||||
final ChatServerPool pool;
|
||||
Widget _connectButton(BuildContext context, ChatMachineStatus machine) {
|
||||
final label =
|
||||
'${machine.server.name} · ${machine.connecting ? 'Connecting' : 'Sign in'}';
|
||||
final action = machine.connecting
|
||||
? null
|
||||
: () => _showMachineSignIn(
|
||||
context,
|
||||
_MachineSignIn(
|
||||
pool: pool,
|
||||
id: machine.server.id,
|
||||
name: machine.server.name,
|
||||
),
|
||||
);
|
||||
if (usesCupertinoHost(context)) {
|
||||
return CupertinoButton(
|
||||
onPressed: action,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
machine.connecting
|
||||
? CupertinoIcons.arrow_2_circlepath
|
||||
: CupertinoIcons.lock,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(label),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return TextButton.icon(
|
||||
onPressed: action,
|
||||
icon: Icon(machine.connecting ? Icons.sync : Icons.lock_outline),
|
||||
label: Text(label),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
for (final machine in pool.machines)
|
||||
Tooltip(
|
||||
message:
|
||||
machine.error ?? (machine.connected ? 'Connected' : 'Connecting'),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (machine.connected)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Text('${machine.server.name} · Connected'),
|
||||
)
|
||||
else
|
||||
_connectButton(context, machine),
|
||||
if (!machine.connected && !machine.connecting)
|
||||
usesCupertinoHost(context)
|
||||
? CupertinoButton(
|
||||
onPressed: () => pool.retry(machine.server.id),
|
||||
child: const Icon(CupertinoIcons.refresh),
|
||||
)
|
||||
: IconButton(
|
||||
tooltip: 'Retry ${machine.server.name}',
|
||||
onPressed: () => pool.retry(machine.server.id),
|
||||
icon: const Icon(Icons.refresh),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _MachineSignIn extends StatefulWidget {
|
||||
const _MachineSignIn({
|
||||
required this.pool,
|
||||
required this.id,
|
||||
required this.name,
|
||||
});
|
||||
final ChatServerPool pool;
|
||||
final String id, name;
|
||||
@override
|
||||
State<_MachineSignIn> createState() => _MachineSignInState();
|
||||
}
|
||||
|
||||
class _MachineSignInState extends State<_MachineSignIn> {
|
||||
final password = TextEditingController();
|
||||
bool busy = false;
|
||||
String? error;
|
||||
@override
|
||||
void dispose() {
|
||||
password.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> submit() async {
|
||||
setState(() {
|
||||
busy = true;
|
||||
error = null;
|
||||
});
|
||||
try {
|
||||
final problem = await widget.pool.signIn(widget.id, password.text);
|
||||
if (!mounted) return;
|
||||
if (problem == null) {
|
||||
Navigator.pop(context);
|
||||
return;
|
||||
}
|
||||
setState(() => error = problem);
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
setState(
|
||||
() => error = 'Could not sign in. Check the password and connection.',
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final field = cupertino
|
||||
? CupertinoTextField(
|
||||
controller: password,
|
||||
obscureText: true,
|
||||
placeholder: 'Password',
|
||||
onSubmitted: busy ? null : (_) => submit(),
|
||||
)
|
||||
: TextField(
|
||||
controller: password,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(labelText: 'Password'),
|
||||
onSubmitted: busy ? null : (_) => submit(),
|
||||
);
|
||||
final content = Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [field, if (error != null) Text(error!)],
|
||||
);
|
||||
return cupertino
|
||||
? CupertinoAlertDialog(
|
||||
title: Text('Sign in to ${widget.name}'),
|
||||
content: content,
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: busy ? null : () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
onPressed: busy ? null : submit,
|
||||
child: Text(busy ? 'Signing in…' : 'Sign in'),
|
||||
),
|
||||
],
|
||||
)
|
||||
: AlertDialog(
|
||||
title: Text('Sign in to ${widget.name}'),
|
||||
content: content,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: busy ? null : () => Navigator.pop(context),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: busy ? null : submit,
|
||||
child: Text(busy ? 'Signing in…' : 'Sign in'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showMachineSignIn(BuildContext context, Widget dialog) =>
|
||||
usesCupertinoHost(context)
|
||||
? showCupertinoDialog<void>(context: context, builder: (_) => dialog)
|
||||
: showDialog<void>(context: context, builder: (_) => dialog);
|
||||
@@ -0,0 +1,172 @@
|
||||
import 'dart:async';
|
||||
import '../../api_gateway.dart';
|
||||
import '../server_scope.dart';
|
||||
import 'chat_identity.dart';
|
||||
import 'chat_server_gateway.dart';
|
||||
|
||||
/// Lists all machines, but sends every session operation to its original one.
|
||||
class FederatedChatGateway implements ApiGateway {
|
||||
FederatedChatGateway(
|
||||
this.sources,
|
||||
this.primary,
|
||||
this.changes, {
|
||||
this.catalogIds,
|
||||
}) {
|
||||
bindServerIdentity(this, 'all-saved-servers');
|
||||
}
|
||||
final Map<String, ChatServerGateway> Function() sources;
|
||||
final String? Function() primary;
|
||||
final Stream<JsonMap> changes;
|
||||
final Iterable<String> Function()? catalogIds;
|
||||
Iterable<String> get serverIds => catalogIds?.call() ?? sources().keys;
|
||||
final Map<String, List<JsonMap>> _cached = {};
|
||||
@override
|
||||
Stream<JsonMap> get frames => changes;
|
||||
ChatServerGateway forServer(String id) =>
|
||||
sources()[id] ?? (throw StateError('This machine is not connected.'));
|
||||
ApiGateway forChat(String value) {
|
||||
final parsed = parseFederatedChatId(value);
|
||||
if (value.startsWith('chat@') && parsed == null) {
|
||||
return _UnavailableChatGateway('This chat link is invalid.');
|
||||
}
|
||||
final source = parsed?.server ?? primary();
|
||||
return sources()[source] ??
|
||||
_UnavailableChatGateway('This machine is not connected.');
|
||||
}
|
||||
|
||||
String normalizeId(String value) =>
|
||||
value.startsWith('chat@') || primary() == null
|
||||
? value
|
||||
: federatedChatId(primary()!, value);
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (type == 'attention_acks' || type == 'ack_attention') {
|
||||
final seen = <String, dynamic>{};
|
||||
final requested = fields['attention_acks'];
|
||||
final outgoing = requested is Map ? requested['chat_seen'] : null;
|
||||
final replies = await Future.wait(
|
||||
sources().entries.map((entry) async {
|
||||
final subset = outgoing is Map
|
||||
? {
|
||||
for (final item in outgoing.entries)
|
||||
if (parseFederatedChatId('${item.key}')?.server ==
|
||||
entry.key)
|
||||
'${item.key}': item.value,
|
||||
}
|
||||
: <String, dynamic>{};
|
||||
if (type == 'ack_attention' && subset.isEmpty) {
|
||||
return <String, dynamic>{};
|
||||
}
|
||||
try {
|
||||
final reply = await entry.value.call(
|
||||
type,
|
||||
type == 'ack_attention'
|
||||
? {
|
||||
'attention_acks': {
|
||||
'chat_seen': subset,
|
||||
'dismissed': <String>[],
|
||||
},
|
||||
}
|
||||
: const {},
|
||||
);
|
||||
final body = reply['attention_acks'];
|
||||
return body is Map && body['chat_seen'] is Map
|
||||
? Map<String, dynamic>.from(body['chat_seen'])
|
||||
: <String, dynamic>{};
|
||||
} catch (_) {
|
||||
if (type == 'ack_attention') rethrow;
|
||||
return <String, dynamic>{};
|
||||
}
|
||||
}),
|
||||
);
|
||||
for (final reply in replies) {
|
||||
seen.addAll(reply);
|
||||
}
|
||||
return {
|
||||
'type': 'attention_acks',
|
||||
'attention_acks': {'dismissed': <String>[], 'chat_seen': seen},
|
||||
};
|
||||
}
|
||||
if (type == 'chat_sessions') {
|
||||
final current = Map.of(sources());
|
||||
_cached.removeWhere((id, _) => !serverIds.contains(id));
|
||||
final results = await Future.wait(
|
||||
current.entries.map((entry) async {
|
||||
try {
|
||||
final reply = await entry.value.call(type, fields);
|
||||
final list = reply['chat_sessions'];
|
||||
if (list is! List) {
|
||||
throw StateError(
|
||||
'Invalid chat list from ${entry.value.server.name}.',
|
||||
);
|
||||
}
|
||||
if (!serverIds.contains(entry.key) ||
|
||||
!identical(sources()[entry.key], entry.value)) {
|
||||
return false;
|
||||
}
|
||||
_cached[entry.key] = list
|
||||
.whereType<Map>()
|
||||
.map((v) => Map<String, dynamic>.from(v))
|
||||
.toList();
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
);
|
||||
_cached.removeWhere((id, _) => !serverIds.contains(id));
|
||||
if (!results.contains(true) && _cached.isEmpty) {
|
||||
throw StateError('No saved machine is connected.');
|
||||
}
|
||||
return {
|
||||
'type': 'chat_sessions',
|
||||
'chat_sessions': _cached.entries
|
||||
.expand(
|
||||
(entry) => entry.value.map(
|
||||
(row) => {
|
||||
...row,
|
||||
'_server_name':
|
||||
sources()[entry.key]?.server.name ?? row['_server_name'],
|
||||
},
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
};
|
||||
}
|
||||
final ids = <String>{};
|
||||
for (final entry in fields.entries) {
|
||||
if (entry.key.startsWith('chat_') && entry.value is Map) {
|
||||
final session = (entry.value as Map)['session_id'];
|
||||
if (session is String) {
|
||||
if (session.startsWith('chat@') &&
|
||||
parseFederatedChatId(session) == null) {
|
||||
throw StateError('This chat identity is invalid.');
|
||||
}
|
||||
ids.add(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
final machines = ids
|
||||
.map((id) => parseFederatedChatId(id)?.server ?? primary())
|
||||
.toSet();
|
||||
if (machines.length > 1) {
|
||||
throw StateError(
|
||||
'An operation cannot combine chats from different machines.',
|
||||
);
|
||||
}
|
||||
final source = machines.isNotEmpty ? machines.single : primary();
|
||||
if (source == null) throw StateError('Choose a machine first.');
|
||||
return forServer(source).call(type, fields);
|
||||
}
|
||||
}
|
||||
|
||||
class _UnavailableChatGateway implements ApiGateway {
|
||||
_UnavailableChatGateway(this.reason);
|
||||
final String reason;
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) =>
|
||||
Future.error(StateError(reason));
|
||||
}
|
||||
@@ -22,6 +22,26 @@ class ServerContext extends InheritedNotifier<ServerConnections> {
|
||||
return null;
|
||||
}
|
||||
|
||||
static String? nameFor(BuildContext context, String id) {
|
||||
final scope = maybeOf(context);
|
||||
for (final machine
|
||||
in scope?.notifier?.catalog.servers ?? const <dynamic>[]) {
|
||||
if (machine.id == id) return machine.name as String;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static Widget forServer(BuildContext context, String id, Widget child) {
|
||||
final scope = maybeOf(context);
|
||||
return scope == null || id.isEmpty
|
||||
? child
|
||||
: ServerContext(
|
||||
connections: scope.notifier!,
|
||||
serverId: id,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
|
||||
static String metadata(BuildContext context, String detail) =>
|
||||
[?maybeOf(context)?.name, if (detail.isNotEmpty) detail].join(' · ');
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'server_session_stub.dart'
|
||||
@@ -21,6 +22,8 @@ class ServerSession {
|
||||
static final Map<String, int> _versions = {};
|
||||
|
||||
static String? get serverId => _serverId;
|
||||
static final _credentialChanges = StreamController<String>.broadcast();
|
||||
static Stream<String> get credentialChanges => _credentialChanges.stream;
|
||||
|
||||
/// Drop the active trust selection without deleting any server's sign-in.
|
||||
static void clearSelection() {
|
||||
@@ -80,6 +83,10 @@ class ServerSession {
|
||||
static Map<String, String> headersFor(Uri endpoint) {
|
||||
final origin = loginUriFor(endpoint);
|
||||
if (origin == null || !_origins.contains(origin)) {
|
||||
for (final reader in _readers.values) {
|
||||
final scoped = reader(endpoint);
|
||||
if (scoped.isNotEmpty) return scoped;
|
||||
}
|
||||
return const {};
|
||||
}
|
||||
return headers;
|
||||
@@ -107,6 +114,61 @@ class ServerSession {
|
||||
};
|
||||
}
|
||||
|
||||
static final Map<Object, Map<String, String> Function(Uri)> _readers = {};
|
||||
static void registerReader(
|
||||
Object owner,
|
||||
Map<String, String> Function(Uri) reader,
|
||||
) => _readers[owner] = reader;
|
||||
static void removeReader(Object owner) => _readers.remove(owner);
|
||||
|
||||
static final Map<String, int> _profileSignIns = {};
|
||||
static Future<String?> signInProfile({
|
||||
required String id,
|
||||
required Iterable<Uri> endpoints,
|
||||
required String password,
|
||||
bool Function()? isCurrent,
|
||||
}) async {
|
||||
final candidates = endpoints.map(loginUriFor).whereType<Uri>().toList();
|
||||
if (candidates.isEmpty) return 'This machine has no valid address.';
|
||||
final key = _scopeKey(id), version = _versions[_scopeKey(id)];
|
||||
final attempt = (_profileSignIns[id] ?? 0) + 1;
|
||||
_profileSignIns[id] = attempt;
|
||||
String? problem;
|
||||
for (final login in candidates) {
|
||||
final result = await impl.postLogin(login, password);
|
||||
if (_profileSignIns[id] != attempt ||
|
||||
_versions[key] != version ||
|
||||
!(isCurrent?.call() ?? true)) {
|
||||
return 'The sign-in changed. Retry.';
|
||||
}
|
||||
if (result.cookie != null) {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (_profileSignIns[id] != attempt ||
|
||||
_versions[key] != version ||
|
||||
!(isCurrent?.call() ?? true)) {
|
||||
return 'The sign-in changed. Retry.';
|
||||
}
|
||||
final committedVersion = (version ?? 0) + 1;
|
||||
_versions[key] = committedVersion;
|
||||
await prefs.setString(key, result.cookie!);
|
||||
if (_versions[key] != committedVersion) {
|
||||
return 'The sign-in changed. Retry.';
|
||||
}
|
||||
if (!(isCurrent?.call() ?? true)) {
|
||||
_versions[key] = committedVersion + 1;
|
||||
await prefs.setString(key, '');
|
||||
return 'The machine changed. Retry signing in.';
|
||||
}
|
||||
if (_serverId == id) cookie = result.cookie;
|
||||
_credentialChanges.add(id);
|
||||
return null;
|
||||
}
|
||||
problem = result.error ?? 'Sign-in failed.';
|
||||
if (!problem.startsWith('Could not reach')) return problem;
|
||||
}
|
||||
return problem;
|
||||
}
|
||||
|
||||
static Future<void> load() async {
|
||||
final generation = ++_generation;
|
||||
_serverId = null;
|
||||
@@ -122,8 +184,9 @@ class ServerSession {
|
||||
String? value,
|
||||
String key,
|
||||
int generation,
|
||||
int version,
|
||||
) async {
|
||||
int version, {
|
||||
String? profileId,
|
||||
}) async {
|
||||
if (_versions[key] != version) return;
|
||||
if (_generation == generation) cookie = value;
|
||||
try {
|
||||
@@ -137,6 +200,9 @@ class ServerSession {
|
||||
await prefs.setString(key, value ?? '');
|
||||
}
|
||||
} catch (_) {}
|
||||
if (profileId != null && _versions[key] == version) {
|
||||
_credentialChanges.add(profileId);
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs in at the web login beside [endpoint] (its `/login` page) with
|
||||
@@ -149,15 +215,30 @@ class ServerSession {
|
||||
return 'The server address is not a trusted alias of the selected server.';
|
||||
}
|
||||
final generation = _generation;
|
||||
final key = _serverId == null ? _key : _scopeKey(_serverId!);
|
||||
final version = (_versions[key] ?? 0) + 1;
|
||||
final profileId = _serverId;
|
||||
final key = profileId == null ? _key : _scopeKey(profileId);
|
||||
final previous = _versions[key];
|
||||
final version = (previous ?? 0) + 1;
|
||||
_versions[key] = version;
|
||||
final result = await impl.postLogin(login, password);
|
||||
if (result.cookie != null) {
|
||||
if (_serverId == null && _generation == generation) _origins = {login};
|
||||
await _save(result.cookie, key, generation, version);
|
||||
await _save(
|
||||
result.cookie,
|
||||
key,
|
||||
generation,
|
||||
version,
|
||||
profileId: profileId,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (_versions[key] == version) {
|
||||
if (previous == null) {
|
||||
_versions.remove(key);
|
||||
} else {
|
||||
_versions[key] = previous;
|
||||
}
|
||||
}
|
||||
return result.error ?? 'Sign-in failed.';
|
||||
}
|
||||
|
||||
@@ -165,7 +246,7 @@ class ServerSession {
|
||||
final key = _serverId == null ? _key : _scopeKey(_serverId!);
|
||||
final version = (_versions[key] ?? 0) + 1;
|
||||
_versions[key] = version;
|
||||
return _save(null, key, _generation, version);
|
||||
return _save(null, key, _generation, version, profileId: _serverId);
|
||||
}
|
||||
|
||||
/// Whether [endpoint]'s server accepts the kept session.
|
||||
|
||||
@@ -6,3 +6,8 @@ import 'channel_connect_stub.dart'
|
||||
|
||||
/// Opens the server websocket; on a phone it carries the web sign-in.
|
||||
WebSocketChannel connectPipelinesChannel(Uri uri) => impl.connect(uri);
|
||||
|
||||
WebSocketChannel connectScopedPipelinesChannel(
|
||||
Uri uri,
|
||||
Map<String, String> Function(Uri) headers,
|
||||
) => impl.connectScoped(uri, headers);
|
||||
|
||||
@@ -6,11 +6,17 @@ import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import '../session/server_session.dart';
|
||||
|
||||
/// A native socket sends the kept session cookie with the upgrade.
|
||||
WebSocketChannel connect(Uri uri) {
|
||||
WebSocketChannel connect(Uri uri) =>
|
||||
connectScoped(uri, ServerSession.headersFor);
|
||||
|
||||
WebSocketChannel connectScoped(
|
||||
Uri uri,
|
||||
Map<String, String> Function(Uri) headers,
|
||||
) {
|
||||
final client = _HandshakeClient();
|
||||
final socket = WebSocket.connect(
|
||||
uri.toString(),
|
||||
headers: ServerSession.headersFor(uri),
|
||||
headers: headers(uri),
|
||||
customClient: client,
|
||||
).whenComplete(client.close);
|
||||
return IOWebSocketChannel(socket);
|
||||
|
||||
@@ -2,3 +2,8 @@ import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
|
||||
/// The browser sends its own login cookie with the upgrade.
|
||||
WebSocketChannel connect(Uri uri) => WebSocketChannel.connect(uri);
|
||||
|
||||
WebSocketChannel connectScoped(
|
||||
Uri uri,
|
||||
Map<String, String> Function(Uri) headers,
|
||||
) => connect(uri);
|
||||
|
||||
@@ -292,7 +292,14 @@ class PipelinesClient implements ApiGateway {
|
||||
/// Relative artifact and session urls resolve only against this origin; an
|
||||
/// absolute recorded http(s) url still resolves without it. The cast lives here
|
||||
/// so callers never repeat it.
|
||||
abstract interface class EndpointGateway {
|
||||
String get configuredEndpoint;
|
||||
}
|
||||
|
||||
String configuredGatewayEndpoint(ApiGateway gateway) {
|
||||
if (gateway is EndpointGateway) {
|
||||
return (gateway as EndpointGateway).configuredEndpoint;
|
||||
}
|
||||
final client = gateway is PipelinesClient ? gateway : null;
|
||||
return client?.endpoint?.toString() ?? '';
|
||||
}
|
||||
|
||||
@@ -69,6 +69,28 @@ class ServerUrl {
|
||||
);
|
||||
}
|
||||
|
||||
static Uri resourceUri(
|
||||
String configured,
|
||||
String path, {
|
||||
Map<String, String> query = const {},
|
||||
}) {
|
||||
final endpoint = Uri.parse(validate(configured).httpUrl);
|
||||
final relay =
|
||||
endpoint.path.startsWith('/peers/') &&
|
||||
endpoint.path.endsWith('/connect');
|
||||
final prefix = relay
|
||||
? endpoint.path.substring(0, endpoint.path.length - '/connect'.length)
|
||||
: '';
|
||||
return endpoint.replace(
|
||||
path: '$prefix${path.startsWith('/') ? path : '/$path'}',
|
||||
queryParameters: {
|
||||
...(relay ? endpoint.queryParameters : <String, String>{}),
|
||||
...query,
|
||||
},
|
||||
fragment: null,
|
||||
);
|
||||
}
|
||||
|
||||
static Uri? resolveArtifactUrl(String configured, String artifactUrl) {
|
||||
final path = artifactUrl.trim();
|
||||
if (path.isEmpty) return null;
|
||||
@@ -79,6 +101,14 @@ class ServerUrl {
|
||||
}
|
||||
try {
|
||||
final endpoint = validate(configured);
|
||||
if (Uri.parse(endpoint.wsUrl).path.startsWith('/peers/')) {
|
||||
final relative = Uri.parse(path);
|
||||
return resourceUri(
|
||||
configured,
|
||||
relative.path,
|
||||
query: relative.queryParameters,
|
||||
);
|
||||
}
|
||||
final origin = Uri.parse(
|
||||
endpoint.httpUrl,
|
||||
).replace(path: '/', query: null);
|
||||
|
||||
@@ -91,7 +91,11 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
_workspaceScope = scope;
|
||||
_workspaceBinding = ChatWorkspaceBinding(
|
||||
controller: _workspace,
|
||||
store: SharedPreferencesChatWorkspaceStore(serverScope: scope),
|
||||
store: widget.gateway is FederatedChatGateway
|
||||
? FederatedWorkspaceStore(
|
||||
primary: (widget.gateway as FederatedChatGateway).primary(),
|
||||
)
|
||||
: SharedPreferencesChatWorkspaceStore(serverScope: scope),
|
||||
sidebarMode: () => _sidebarMode.name,
|
||||
onRestored: (snapshot) {
|
||||
if (!mounted) return;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../../../core/servers/chat/chat_identity.dart';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
@@ -41,8 +42,15 @@ const String chatUnsentKeyPrefix = 'pipelines.next.chatUnsent.v1.';
|
||||
class SharedPreferencesChatDraftStore implements ChatDraftStore {
|
||||
const SharedPreferencesChatDraftStore({this.serverId = ''});
|
||||
final String serverId;
|
||||
String _native(String sessionId) {
|
||||
final parsed = parseFederatedChatId(sessionId);
|
||||
return parsed != null && serverStorageScope(parsed.server) == serverId
|
||||
? parsed.native
|
||||
: sessionId;
|
||||
}
|
||||
|
||||
String _key(String sessionId) =>
|
||||
scopedServerKey('$chatDraftKeyPrefix$sessionId', serverId);
|
||||
scopedServerKey('$chatDraftKeyPrefix${_native(sessionId)}', serverId);
|
||||
|
||||
Future<SharedPreferences?> _preferences() async {
|
||||
try {
|
||||
@@ -77,7 +85,7 @@ class SharedPreferencesChatDraftStore implements ChatDraftStore {
|
||||
}
|
||||
|
||||
String _unsentKey(String sessionId) =>
|
||||
scopedServerKey('$chatUnsentKeyPrefix$sessionId', serverId);
|
||||
scopedServerKey('$chatUnsentKeyPrefix${_native(sessionId)}', serverId);
|
||||
|
||||
@override
|
||||
Future<List<Object?>> readUnsent(String sessionId) async {
|
||||
|
||||
@@ -28,15 +28,10 @@ FileUrls? fileUrls(String configuredEndpoint, String path) {
|
||||
final value = path;
|
||||
if (value.trim().isEmpty) return null;
|
||||
try {
|
||||
final endpoint = ServerUrl.validate(configuredEndpoint);
|
||||
final base = Uri.parse(
|
||||
endpoint.httpUrl,
|
||||
).replace(path: '/files', query: null, fragment: null);
|
||||
Uri make({required bool download}) => base.replace(
|
||||
queryParameters: <String, String>{
|
||||
'path': value,
|
||||
if (download) 'download': '1',
|
||||
},
|
||||
Uri make({required bool download}) => ServerUrl.resourceUri(
|
||||
configuredEndpoint,
|
||||
'/files',
|
||||
query: <String, String>{'path': value, if (download) 'download': '1'},
|
||||
);
|
||||
return FileUrls(
|
||||
view: make(download: false),
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import 'workspace/federated_workspace_store.dart';
|
||||
import '../../core/servers/chat/chat_identity.dart';
|
||||
import '../../core/servers/chat/federated_chat_gateway.dart';
|
||||
import '../../core/servers/server_context.dart';
|
||||
import '../../shell/destination.dart';
|
||||
import '../../shell/shell_bar.dart';
|
||||
import '../../shell/shell_destination_menu.dart';
|
||||
@@ -449,7 +453,9 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
final start = _startNotice;
|
||||
final thread = ChatThreadView(
|
||||
key: ValueKey<String>('chat-session-$selected'),
|
||||
gateway: widget.gateway,
|
||||
gateway: widget.gateway is FederatedChatGateway
|
||||
? (widget.gateway as FederatedChatGateway).forChat(selected)
|
||||
: widget.gateway,
|
||||
sessionId: selected,
|
||||
title: '${row?['title'] ?? ''}'.trim(),
|
||||
session: row,
|
||||
@@ -504,7 +510,11 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
return ChatComposerFocusScope(
|
||||
sessionId: selected,
|
||||
requests: _composerFocus,
|
||||
child: thread,
|
||||
child: ServerContext.forServer(
|
||||
context,
|
||||
'${row?['_server_id'] ?? parseFederatedChatId(selected)?.server ?? ''}',
|
||||
thread,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../../../../core/servers/chat/federated_chat_gateway.dart';
|
||||
import '../../../../core/servers/server_context.dart';
|
||||
import 'dart:async';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
@@ -77,9 +78,12 @@ class ChatCompactSidebar extends StatelessWidget {
|
||||
final running = row['running'] == true;
|
||||
final backgroundTasks = chatSessionBackgroundTasks(row);
|
||||
final title = chatSessionTitle(row);
|
||||
final machineName =
|
||||
ServerContext.nameFor(context, '${row['_server_id'] ?? ''}') ??
|
||||
row['_server_name'] as String?;
|
||||
final details = [
|
||||
title,
|
||||
?ServerContext.maybeOf(context)?.name,
|
||||
?(machineName ?? ServerContext.maybeOf(context)?.name),
|
||||
if (chatSessionSubtitle(row).isNotEmpty) chatSessionSubtitle(row),
|
||||
if (relativeChatSessionTime(row['updated_at']).isNotEmpty)
|
||||
'Updated ${relativeChatSessionTime(row['updated_at'])} ago',
|
||||
@@ -107,16 +111,29 @@ class ChatCompactSidebar extends StatelessWidget {
|
||||
context,
|
||||
details,
|
||||
ExcludeSemantics(
|
||||
child: ChatCompactAvatar(
|
||||
title: title,
|
||||
color: color,
|
||||
active: selected,
|
||||
visible: visible,
|
||||
running: running,
|
||||
backgroundTasks: backgroundTasks,
|
||||
unread: unread,
|
||||
cupertino:
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ChatCompactAvatar(
|
||||
title: title,
|
||||
color: color,
|
||||
active: selected,
|
||||
visible: visible,
|
||||
running: running,
|
||||
backgroundTasks: backgroundTasks,
|
||||
unread: unread,
|
||||
cupertino:
|
||||
chatControlsStyleOf(context) ==
|
||||
ChatControlsStyle.cupertino,
|
||||
),
|
||||
if (machineName case final name?)
|
||||
Text(
|
||||
name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
() {
|
||||
@@ -148,7 +165,9 @@ class ChatCompactSidebar extends StatelessWidget {
|
||||
: Icons.menu_open,
|
||||
),
|
||||
const Text('Expand', textAlign: TextAlign.center),
|
||||
if (ServerContext.maybeOf(context)?.name case final name?)
|
||||
if (controller.repository.gateway is FederatedChatGateway)
|
||||
const Text('All machines', textAlign: TextAlign.center)
|
||||
else if (ServerContext.maybeOf(context)?.name case final name?)
|
||||
Text(
|
||||
name,
|
||||
maxLines: 2,
|
||||
|
||||
@@ -10,6 +10,7 @@ Future<SavedServer?> chooseChatMachine(BuildContext context) async {
|
||||
final scope = ServerContext.maybeOf(context);
|
||||
final servers = scope?.notifier?.catalog.servers ?? const <SavedServer>[];
|
||||
if (servers.isEmpty) return null;
|
||||
if (servers.length == 1) return servers.single;
|
||||
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
|
||||
return showCupertinoModalPopup<SavedServer>(
|
||||
context: context,
|
||||
|
||||
@@ -65,6 +65,7 @@ class ChatSessionSubtitle extends StatelessWidget {
|
||||
const ChatSessionSubtitle({
|
||||
super.key,
|
||||
required this.metadata,
|
||||
this.machineName,
|
||||
required this.closed,
|
||||
required this.active,
|
||||
required this.visible,
|
||||
@@ -73,6 +74,7 @@ class ChatSessionSubtitle extends StatelessWidget {
|
||||
required this.unread,
|
||||
});
|
||||
final String metadata;
|
||||
final String? machineName;
|
||||
final bool closed, active, visible, running, unread;
|
||||
final int backgroundTasks;
|
||||
@override
|
||||
@@ -88,7 +90,11 @@ class ChatSessionSubtitle extends StatelessWidget {
|
||||
style: TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
if (closed && metadata.isNotEmpty) const TextSpan(text: ' · '),
|
||||
TextSpan(text: ServerContext.metadata(context, metadata)),
|
||||
TextSpan(
|
||||
text: machineName == null
|
||||
? ServerContext.metadata(context, metadata)
|
||||
: '$machineName${metadata.isEmpty ? '' : ' · $metadata'}',
|
||||
),
|
||||
],
|
||||
),
|
||||
style: TextStyle(color: chatMetadataForeground(context)),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import '../../../../core/servers/chat/federated_chat_gateway.dart';
|
||||
import 'federated_chat_session_local.dart';
|
||||
import 'dart:async';
|
||||
import 'dart:math';
|
||||
|
||||
@@ -34,9 +36,15 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
this.activeAckDelay = const Duration(milliseconds: 1500),
|
||||
}) : _localStore =
|
||||
localStore ??
|
||||
SharedPreferencesChatSessionLocalStore(
|
||||
serverId: serverStorageScope(serverIdentity(repository.gateway)),
|
||||
),
|
||||
(repository.gateway is FederatedChatGateway
|
||||
? FederatedChatSessionLocalStore(
|
||||
() => (repository.gateway as FederatedChatGateway).serverIds,
|
||||
)
|
||||
: SharedPreferencesChatSessionLocalStore(
|
||||
serverId: serverStorageScope(
|
||||
serverIdentity(repository.gateway),
|
||||
),
|
||||
)),
|
||||
_nowMillis = nowMillis ?? _wallClockMillis {
|
||||
_listenFrames();
|
||||
_bindAckSync(ackSync ?? attentionAckSyncOf(repository.gateway));
|
||||
@@ -377,13 +385,14 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
/// Creates one session and returns the server's `chat_session`. A reply
|
||||
/// without one is refused rather than opening an invented row.
|
||||
Future<JsonMap> createOrThrow({
|
||||
ChatRepository? targetRepository,
|
||||
required String title,
|
||||
required String directory,
|
||||
required String backend,
|
||||
required String instructions,
|
||||
required String operationId,
|
||||
}) async {
|
||||
final reply = await repository.create(
|
||||
final reply = await (targetRepository ?? repository).create(
|
||||
title: title,
|
||||
directory: directory,
|
||||
backend: backend,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../../../../core/servers/chat/federated_chat_gateway.dart';
|
||||
import '../../../../core/servers/server_context.dart';
|
||||
import 'chat_machine_picker.dart';
|
||||
import '../../../../ui/adaptive/segmented_bar.dart';
|
||||
@@ -197,10 +198,23 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
|
||||
Future<void> _newChat({bool chooseMachine = true}) async {
|
||||
final scope = ServerContext.maybeOf(context);
|
||||
var repository = _controller.repository;
|
||||
if (chooseMachine && scope != null) {
|
||||
final selected = await chooseChatMachine(context);
|
||||
if (!mounted || selected == null) return;
|
||||
if (selected.id != scope.serverId) {
|
||||
if (repository.gateway is FederatedChatGateway) {
|
||||
try {
|
||||
repository = ChatRepository(
|
||||
(repository.gateway as FederatedChatGateway).forServer(selected.id),
|
||||
);
|
||||
} catch (_) {
|
||||
await showChatMachineError(
|
||||
context,
|
||||
'Sign in to ${selected.name} or retry its connection before creating a chat.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
} else if (selected.id != scope.serverId) {
|
||||
final switched = await scope.notifier!.requestNewChat(selected.id);
|
||||
if (!switched && mounted) {
|
||||
await showChatMachineError(
|
||||
@@ -213,11 +227,13 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
}
|
||||
// One id per create intent: a refusal retried in the dialog reuses it.
|
||||
final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}';
|
||||
if (!mounted) return;
|
||||
final session = await showChatCreateDialog(
|
||||
context,
|
||||
repository: _controller.repository,
|
||||
repository: repository,
|
||||
operationId: operationId,
|
||||
onSubmit: (draft, id) => _controller.createOrThrow(
|
||||
targetRepository: repository,
|
||||
title: draft.title,
|
||||
directory: draft.directory,
|
||||
backend: draft.backend,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../../../../core/servers/server_context.dart';
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
@@ -47,11 +48,15 @@ Future<JsonMap?> showChatCreateDialog(
|
||||
onSubmit,
|
||||
ChatCreatePromptStore? prompts,
|
||||
}) {
|
||||
final dialog = CreateChatDialog(
|
||||
repository: repository,
|
||||
operationId: operationId,
|
||||
onSubmit: onSubmit,
|
||||
prompts: prompts,
|
||||
final dialog = ServerContext.forServer(
|
||||
context,
|
||||
serverIdentity(repository.gateway) ?? '',
|
||||
CreateChatDialog(
|
||||
repository: repository,
|
||||
operationId: operationId,
|
||||
onSubmit: onSubmit,
|
||||
prompts: prompts,
|
||||
),
|
||||
);
|
||||
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? showCupertinoDialog<JsonMap>(context: context, builder: (_) => dialog)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../../core/servers/chat/chat_identity.dart';
|
||||
import '../../../../core/servers/server_scope.dart';
|
||||
import 'chat_session_local.dart';
|
||||
|
||||
/// Import old per-machine read/hidden choices into the combined list once.
|
||||
class FederatedChatSessionLocalStore implements ChatSessionLocalStore {
|
||||
FederatedChatSessionLocalStore(this.serverIds);
|
||||
final Iterable<String> Function() serverIds;
|
||||
static const scope = 'all-saved-servers';
|
||||
final combined = const SharedPreferencesChatSessionLocalStore(
|
||||
serverId: scope,
|
||||
);
|
||||
@override
|
||||
Future<ChatSessionLocal> load() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (prefs.containsKey(
|
||||
scopedServerKey(SharedPreferencesChatSessionLocalStore.key, scope),
|
||||
)) {
|
||||
return combined.load();
|
||||
}
|
||||
final hidden = <String>[], unseen = <String>[];
|
||||
final seen = <String, int>{};
|
||||
for (final server in serverIds()) {
|
||||
final old = await SharedPreferencesChatSessionLocalStore(
|
||||
serverId: serverStorageScope(server),
|
||||
).load();
|
||||
String id(String value) => federatedChatId(server, value);
|
||||
hidden.addAll(old.hidden.map(id));
|
||||
unseen.addAll(old.unseen.map(id));
|
||||
seen.addAll({
|
||||
for (final entry in old.seenAt.entries) id(entry.key): entry.value,
|
||||
});
|
||||
}
|
||||
final result = ChatSessionLocal(
|
||||
hidden: hidden,
|
||||
unseen: unseen,
|
||||
seenAt: seen,
|
||||
);
|
||||
await combined.save(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save(ChatSessionLocal state) => combined.save(state);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../../../../core/servers/server_context.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@@ -129,6 +130,12 @@ class ChatSessionRow extends StatelessWidget {
|
||||
),
|
||||
// `Closed` leads the line of a closed chat, then the model and folder.
|
||||
subtitle: ChatSessionSubtitle(
|
||||
machineName:
|
||||
ServerContext.nameFor(
|
||||
context,
|
||||
'${session['_server_id'] ?? ''}',
|
||||
) ??
|
||||
session['_server_name'] as String?,
|
||||
metadata: text,
|
||||
closed: closed,
|
||||
active: selected,
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import '../../../core/servers/chat/chat_identity.dart';
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
import 'chat_workspace_nodes.dart';
|
||||
import 'chat_workspace_snapshot.dart';
|
||||
import 'chat_workspace_store.dart';
|
||||
|
||||
/// Adopt the previous primary-machine layout once, without altering its copy.
|
||||
/// Thereafter all panes live together independently of the pipelines/run default.
|
||||
class FederatedWorkspaceStore implements ChatWorkspaceStore {
|
||||
FederatedWorkspaceStore({
|
||||
required this.primary,
|
||||
ChatWorkspaceStore? combined,
|
||||
ChatWorkspaceStore? legacy,
|
||||
}) : combined =
|
||||
combined ??
|
||||
const SharedPreferencesChatWorkspaceStore(
|
||||
serverScope: 'all-saved-servers',
|
||||
),
|
||||
legacy =
|
||||
legacy ??
|
||||
SharedPreferencesChatWorkspaceStore(
|
||||
serverScope: serverStorageScope(primary),
|
||||
);
|
||||
final String? primary;
|
||||
final ChatWorkspaceStore combined, legacy;
|
||||
@override
|
||||
Future<ChatWorkspaceSnapshot?> read() async {
|
||||
final saved = await combined.read();
|
||||
if (saved != null || primary == null) return saved;
|
||||
final old = await legacy.read();
|
||||
if (old == null) return null;
|
||||
ChatWorkspaceNode map(ChatWorkspaceNode node) => switch (node) {
|
||||
ChatWorkspacePane() => ChatWorkspacePane(
|
||||
node.id,
|
||||
parseFederatedChatId(node.sessionId) == null
|
||||
? federatedChatId(primary!, node.sessionId)
|
||||
: node.sessionId,
|
||||
),
|
||||
ChatWorkspaceSplit() => ChatWorkspaceSplit(
|
||||
node.id,
|
||||
node.axis,
|
||||
map(node.first),
|
||||
map(node.second),
|
||||
ratio: node.ratio,
|
||||
),
|
||||
};
|
||||
final migrated = ChatWorkspaceSnapshot.fromLayout(
|
||||
old.root == null ? null : map(old.root!),
|
||||
old.activePaneId,
|
||||
sidebarMode: old.sidebarMode,
|
||||
mobilePeekFraction: old.mobilePeekFraction,
|
||||
);
|
||||
if (migrated != null) await combined.write(migrated);
|
||||
return migrated;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> write(ChatWorkspaceSnapshot snapshot) =>
|
||||
combined.write(snapshot);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# Concurrent saved-machine chats
|
||||
|
||||
The chat destination now owns independent connections to every saved logical
|
||||
machine. It combines their sessions using namespaced UI identities, retaining
|
||||
native IDs only on each machine's protocol connection. Models, permissions,
|
||||
messages, task/automation metadata, exports, uploads and file browsing stay on
|
||||
the originating connection. A disconnected machine never falls back to another.
|
||||
Cached rows remain visible while a machine retries; removing a profile drops its
|
||||
rows and rejects late responses. Retained adapters are revoked immediately when
|
||||
a connection changes, before asynchronous socket cleanup finishes.
|
||||
|
||||
Browsers keep the hosting-origin socket and register other machines through the
|
||||
authenticated same-origin relay. Peer credentials remain in server memory; native
|
||||
profiles use independent credential snapshots. Successful Settings sign-in/out
|
||||
refreshes only that machine's connection. Failed passwords preserve existing
|
||||
credentials, and late sign-in replies cannot authenticate edited/removed profiles.
|
||||
|
||||
Each row/thread shows its own editable machine alias. Creating a chat with
|
||||
multiple machines loads harnesses/directories from the chosen machine without
|
||||
changing the pipelines/runs default or closing other chat panes. One machine
|
||||
skips the picker. Primary authentication failure no longer hides healthy peers.
|
||||
|
||||
The combined workspace migrates previous primary panes once and then persists
|
||||
independently of the pipelines/runs default. Scoped drafts/unsent intents retain
|
||||
native storage keys, and hidden/read list choices migrate without ID collisions.
|
||||
Protocol-owned session IDs are rewritten; opaque tool input/results and user form
|
||||
answers are preserved verbatim. Read acknowledgements split by machine.
|
||||
|
||||
Verification at source freeze: 47 focused integration tests pass (out.85WaSh),
|
||||
including all previously failing application fixtures, native loopback cookie
|
||||
isolation, late authentication, pool cancellation races, ID collisions, primary
|
||||
auth isolation, machine-first creation and persistence migration. Analyzer clean
|
||||
(8aaMr2). An earlier broad chat/core/application run had 1128 passes and 11
|
||||
failures; callback validation and legacy fixtures were fixed, and all failing
|
||||
areas passed the focused rerun. A final broad rerun and real two-server browser
|
||||
capture are the manager's remaining acceptance checks. No production sessions,
|
||||
services or physical devices were changed here.
|
||||
|
||||
The legacy correlated application fixtures now explicitly answer automation
|
||||
metadata as unavailable and disable native update probes. They previously left
|
||||
those independent requests unanswered, blocking history or leaving timers alive.
|
||||
@@ -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();
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart';
|
||||
import 'package:pipelines_app/core/servers/server_catalog.dart';
|
||||
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
|
||||
import 'package:pipelines_app/features/settings/server_connections.dart';
|
||||
@@ -797,7 +798,7 @@ Future<void> main() async {
|
||||
if (query != null && query.isNotEmpty) _typeSearchWhenShown(query);
|
||||
useAppUrlStrategy();
|
||||
ServerConnections? machines;
|
||||
if (params['machines'] == '1') {
|
||||
if (params['machines'] == '1' || params['federated'] == '1') {
|
||||
machines = ServerConnections(
|
||||
store: MemoryServerCatalogStore(
|
||||
catalog: ServerCatalog(
|
||||
@@ -820,9 +821,29 @@ Future<void> main() async {
|
||||
);
|
||||
await machines.load();
|
||||
}
|
||||
final pool = params['federated'] == '1' && machines != null
|
||||
? ChatServerPool(
|
||||
machines,
|
||||
connect: (machine) async {
|
||||
final client = PipelinesClient(
|
||||
channelFactory: (_) => _FixtureChannel(),
|
||||
);
|
||||
await client.connect(Uri.parse(machine.endpoints.first));
|
||||
return ChatMachineConnection(
|
||||
gateway: client,
|
||||
endpoint: () => client.endpoint.toString(),
|
||||
connected: () => true,
|
||||
states: client.states,
|
||||
close: client.dispose,
|
||||
retry: () => client.connect(Uri.parse(machine.endpoints.first)),
|
||||
);
|
||||
},
|
||||
)
|
||||
: null;
|
||||
final app = PipelinesApp(
|
||||
serverId: machines?.catalog.active?.id,
|
||||
servers: machines,
|
||||
chatPool: pool,
|
||||
server: fixtureServer(params),
|
||||
webPlatform: params['nativeUpdate'] == null ? kIsWeb : false,
|
||||
androidSupported: params['nativeUpdate'] == null ? null : true,
|
||||
|
||||
Reference in New Issue
Block a user