Connect saved machines concurrently in the chat workspace

This commit is contained in:
2026-11-08 22:21:17 +00:00
parent 663d5fb5c9
commit e4904395f0
44 changed files with 2574 additions and 60 deletions
+16 -4
View File
@@ -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,
+25 -2
View File
@@ -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,
+38 -7
View File
@@ -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));
}
+20
View File
@@ -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(' · ');
}
+87 -6
View File
@@ -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() ?? '';
}
+30
View File
@@ -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 {
+4 -9
View File
@@ -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),
+12 -2
View File
@@ -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);
}