Files
pipelines/app/lib/features/settings/server_connections.dart
T
alan c264f865ff Servers: name a machine after its hostname once it connects
A saved server still named by the app ('My server', 'This server',
'Original legacy server' or its address host/IP) takes the hostname the
machine reports in get_status the first time the app connects; typed
names are kept. New servers (legacy migration, Settings with a blank
name, onboarding) start with the address host. A browser on its page
origin with no saved profile shows the reported hostname too. No server
change: get_status already reports the hostname.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:58:28 +00:00

242 lines
7.4 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../core/servers/machine_access.dart';
import '../../core/servers/server_catalog.dart';
import '../../core/servers/server_catalog_store.dart';
import '../../core/servers/server_naming.dart';
/// Saved configurations are committed before switching the app's connection.
/// A failed save leaves the old selection and its live socket unchanged.
class ServerConnections extends ChangeNotifier {
ServerConnections({
required this.store,
required this.onSelected,
this.replaceRemovedPrimary = false,
});
final ServerCatalogStore store;
final Future<void> Function(SavedServer?) onSelected;
/// Native hosts need a pipelines/runs machine: removing the primary hands
/// that role to the next saved machine instead of leaving the app without
/// an endpoint. Browsers keep following their page origin instead.
final bool replaceRemovedPrimary;
/// Signs saved machines in independently; set by the app root when the
/// chat pool exists. Settings asks a new machine for its own password.
MachineAuthenticator? authenticator;
ServerCatalog _catalog = ServerCatalog();
bool _busy = false;
String? _error;
bool _disposed = false;
ServerCatalog get catalog => _catalog;
String? _newChatServerId;
String? get newChatServerId => _newChatServerId;
/// A browser navigation may carry only this non-secret create intent.
void restoreNewChatIntent(String id) {
if (id == _catalog.active?.id) _newChatServerId = id;
}
bool takeNewChatIntent(String? id) {
if (id == null || id != _newChatServerId || id != _catalog.active?.id) {
return false;
}
_newChatServerId = null;
return true;
}
String? _chatOpenId;
/// A chat the user opened from a notification. The tap is the user's own
/// interaction, so the chat it opens is read; a route restored without a tap
/// never sets this.
void requestChatOpen(String sessionId) {
_chatOpenId = sessionId;
notifyListeners();
}
/// Consumes the notification open of [sessionId], once.
bool takeChatOpenIntent(String sessionId) {
if (sessionId.isEmpty || sessionId != _chatOpenId) return false;
_chatOpenId = null;
return true;
}
/// Keep the intent outside the app that selecting another machine disposes.
Future<bool> requestNewChat(String id) async {
if (_busy || _disposed) return false;
_newChatServerId = id;
final selected = await _change(
() => _catalog.select(id),
activate: true,
rollbackSelection: true,
);
if (!selected) _newChatServerId = null;
return selected;
}
bool get busy => _busy;
String? get error => _error;
String? _originHostname;
/// The hostname of the page-origin server a browser uses with no saved
/// profile for it; it names that server, which has no catalog entry.
String? get originHostname => _originHostname;
final _learned = <String, String>{};
/// Records the [hostname] the machine [id] reported. A saved machine still
/// named by the app (see [hasPlaceholderName]) is renamed and saved; a name
/// the operator typed is kept. A null [id] is the unsaved page origin.
/// A change already in progress defers the rename until it finishes.
Future<bool> learnHostname(String? id, String hostname) async {
final name = hostname.trim();
if (_disposed || name.isEmpty) return false;
if (id == null) {
if (_originHostname == name) return false;
_originHostname = name;
_notify();
return true;
}
_learned[id] = name;
return _applyLearnedNames();
}
Future<bool> _applyLearnedNames() async {
if (_busy || _disposed || _learned.isEmpty) return false;
final learned = Map.of(_learned);
_learned.clear();
var next = _catalog;
for (final server in _catalog.servers) {
final hostname = learned[server.id];
final renamed = hostname == null
? null
: renamedToHostname(server, hostname);
if (renamed != null) next = next.upsert(renamed);
}
if (identical(next, _catalog)) return false;
return _change(() => next, activate: false);
}
/// Browsers always connect to their page origin, even after Back or a failed
/// cross-origin navigation. Do not label another saved profile as active.
void alignBrowserOrigin(Uri endpoint) {
String origin(Uri uri) =>
uri.replace(scheme: uri.scheme == 'wss' ? 'https' : 'http').origin;
final current = origin(endpoint);
String? matched;
for (final server in _catalog.servers) {
if (server.endpoints.any((url) {
final candidate = Uri.parse(url);
return origin(candidate) == current &&
candidate.path == endpoint.path &&
candidate.query == endpoint.query;
})) {
matched = server.id;
break;
}
}
_catalog = ServerCatalog(servers: _catalog.servers, selectedId: matched);
_notify();
}
Future<bool> persist() => _change(() => _catalog, activate: false);
Future<void> load({String legacyEndpoint = ''}) async {
try {
final loaded = await store.load(legacyEndpoint: legacyEndpoint);
if (!_disposed) _catalog = loaded;
} catch (error) {
if (!_disposed) _error = 'Saved servers could not be read: $error';
}
_notify();
}
Future<bool> save(SavedServer server, {bool activate = true}) => _change(
() {
final next = _catalog.upsert(server);
return _catalog.active == null ? next.select(server.id) : next;
},
activate:
activate &&
(_catalog.active?.id == server.id || _catalog.active == null),
);
Future<bool> select(String id, {bool activate = true}) {
if (_busy || _disposed) return Future.value(false);
_newChatServerId = null;
return _change(
() => _catalog.select(id),
activate: activate,
rollbackSelection: true,
);
}
Future<bool> remove(String id) => _change(() {
final removedPrimary = _catalog.active?.id == id;
var next = _catalog.remove(id);
if (replaceRemovedPrimary && removedPrimary && next.servers.isNotEmpty) {
next = next.select(next.servers.first.id);
}
return next;
}, activate: _catalog.active?.id == id);
Future<bool> _change(
ServerCatalog Function() change, {
required bool activate,
bool rollbackSelection = false,
}) async {
if (_busy || _disposed) return false;
// A corrupt catalog is never silently replaced by an empty configuration.
if (_error?.startsWith('Saved servers could not be read:') ?? false) {
return false;
}
_busy = true;
final previous = _catalog;
_error = null;
_notify();
try {
final next = change();
if (!await store.save(next)) {
throw StateError('The server configuration could not be saved.');
}
if (_disposed) return false;
_catalog = next;
_notify();
if (activate) {
try {
await onSelected(next.active);
} catch (_) {
if (rollbackSelection && await store.save(previous) && !_disposed) {
_catalog = previous;
}
rethrow;
}
}
return true;
} catch (error) {
if (!_disposed) _error = '$error';
return false;
} finally {
_busy = false;
_notify();
if (_learned.isNotEmpty) scheduleMicrotask(_applyLearnedNames);
}
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}