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
@@ -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);