feat(app): configure and safely switch multi-address servers

This commit is contained in:
2026-10-24 03:04:53 +01:00
parent 47cfb31e7d
commit b499da304d
38 changed files with 1764 additions and 65 deletions
@@ -0,0 +1,62 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../core/transport/pipelines_client.dart';
import '../../ui/adaptive/host.dart';
import 'settings_controller.dart';
import 'settings_sections.dart';
import 'settings_trust_warning.dart';
/// Status follows the actual attempted address, not just the preferred URL.
class ManagedConnectionSection extends StatelessWidget {
const ManagedConnectionSection({
super.key,
required this.client,
required this.controller,
});
final PipelinesClient client;
final SettingsController controller;
Widget _action(BuildContext context, String text, VoidCallback? press) =>
usesCupertinoHost(context)
? CupertinoButton(onPressed: press, child: Text(text))
: TextButton(onPressed: press, child: Text(text));
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SelectableText('Current address: ${client.endpoint ?? 'Not connected'}'),
const SizedBox(height: 8),
const Text(
'Reconnect tries the preferred address first. A dropped or '
'unreachable connection tries this server’s backup addresses automatically.',
),
if (kIsWeb)
const Text(
'In a browser, the connection stays on this page’s '
'origin. Use a saved server to open its page; native apps use automatic address fallback.',
),
Wrap(
spacing: 8,
children: [
_action(
context,
'Reconnect',
client.endpoints.isEmpty
? null
: () => unawaited(client.connectAny(client.endpoints)),
),
_action(context, 'Disconnect', () => unawaited(client.disconnect())),
],
),
SettingsStatusCard(controller: controller),
const SizedBox(height: 12),
const SettingsTrustWarning(),
if (controller.protocolWarning case final warning?) Text(warning),
],
);
}
@@ -0,0 +1,158 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../core/servers/server_catalog.dart';
import '../../ui/adaptive/host.dart';
Future<SavedServer?> editSavedServer(
BuildContext context, {
SavedServer? server,
}) {
final page = _ServerEditor(server: server);
return Navigator.of(context).push<SavedServer>(
usesCupertinoHost(context)
? CupertinoPageRoute(builder: (_) => page)
: MaterialPageRoute(builder: (_) => page),
);
}
class _ServerEditor extends StatefulWidget {
const _ServerEditor({this.server});
final SavedServer? server;
@override
State<_ServerEditor> createState() => _ServerEditorState();
}
class _ServerEditorState extends State<_ServerEditor> {
late final _name = TextEditingController(text: widget.server?.name ?? '');
late final _addresses = TextEditingController(
text: widget.server?.endpoints.join('\n') ?? '',
);
String? _error;
void _save() {
try {
final server = SavedServer.validated(
id:
widget.server?.id ??
'server-${DateTime.now().microsecondsSinceEpoch}',
name: _name.text,
legacyEndpoint: widget.server?.legacyEndpoint,
endpoints: _addresses.text
.split('\n')
.where((line) => line.trim().isNotEmpty),
);
Navigator.of(context).pop(server);
} catch (error) {
setState(() => _error = '$error');
}
}
@override
void dispose() {
_name.dispose();
_addresses.dispose();
super.dispose();
}
Widget _field(
TextEditingController controller,
String label, {
required String key,
bool multiline = false,
}) {
if (usesCupertinoHost(context)) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(label),
const SizedBox(height: 8),
CupertinoTextField(
key: Key(key),
controller: controller,
placeholder: multiline ? 'wss://server.example/connect' : 'Home',
minLines: multiline ? 3 : 1,
maxLines: multiline ? null : 1,
keyboardType: multiline
? TextInputType.multiline
: TextInputType.text,
autocorrect: !multiline,
),
],
);
}
return TextField(
key: Key(key),
controller: controller,
decoration: InputDecoration(
labelText: label,
border: const OutlineInputBorder(),
),
minLines: multiline ? 3 : 1,
maxLines: multiline ? null : 1,
keyboardType: multiline ? TextInputType.multiline : TextInputType.text,
autocorrect: !multiline,
);
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final title = widget.server == null ? 'Add server' : 'Edit server';
final save = cupertino
? CupertinoButton.filled(
onPressed: _save,
child: const Text('Save server'),
)
: FilledButton(onPressed: _save, child: const Text('Save server'));
final body = SafeArea(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
_field(_name, 'Server name', key: 'server-profile-name'),
const SizedBox(height: 16),
_field(
_addresses,
'Addresses, in preferred order',
key: 'server-profile-addresses',
multiline: true,
),
const SizedBox(height: 8),
const Text(
'One ws:// or wss:// address per line. The first is preferred; '
'the others are backups for this same server, such as its Tailscale and LAN addresses.',
),
const SizedBox(height: 8),
const Text(
'Only group addresses you trust as the same server. They share its saved sign-in. '
'ws:// is unencrypted; use it only on a trusted LAN/VPN.',
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Text(
_error!,
style: TextStyle(
color: cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
),
),
),
const SizedBox(height: 16),
Align(alignment: AlignmentDirectional.centerStart, child: save),
],
),
);
return cupertino
? CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(middle: Text(title)),
child: body,
)
: Scaffold(
appBar: AppBar(title: Text(title)),
body: body,
);
}
}
@@ -0,0 +1,134 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../core/servers/server_catalog.dart';
import '../../ui/adaptive/host.dart';
import 'saved_server_editor.dart';
import 'server_connections.dart';
class SavedServersSection extends StatelessWidget {
const SavedServersSection({super.key, required this.connections});
final ServerConnections connections;
Future<void> _edit(BuildContext context, [SavedServer? server]) async {
final edited = await editSavedServer(context, server: server);
if (edited != null) await connections.save(edited);
}
Future<void> _remove(BuildContext context, SavedServer server) async {
final cupertino = usesCupertinoHost(context);
final confirmed = cupertino
? await showCupertinoDialog<bool>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: Text('Remove ${server.name}?'),
content: const Text(
'This removes the saved configuration, not data on the server.',
),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () => Navigator.pop(context, true),
child: const Text('Remove'),
),
],
),
)
: await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text('Remove ${server.name}?'),
content: const Text(
'This removes the saved configuration, not data on the server.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Remove'),
),
],
),
);
if (confirmed == true) await connections.remove(server.id);
}
Widget _button(BuildContext context, String label, VoidCallback? press) =>
usesCupertinoHost(context)
? CupertinoButton(onPressed: press, child: Text(label))
: TextButton(onPressed: press, child: Text(label));
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: connections,
builder: (context, _) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final server in connections.catalog.servers) ...[
Text(
server.name,
style: const TextStyle(fontWeight: FontWeight.w600),
),
if (server.id == connections.catalog.active?.id)
const Text('Selected server'),
for (final (index, address) in server.endpoints.indexed)
Text('${index == 0 ? 'Preferred' : 'Backup $index'}: $address'),
Wrap(
spacing: 8,
children: [
if (server.id != connections.catalog.active?.id)
_button(
context,
'Use ${server.name}',
connections.busy
? null
: () => unawaited(connections.select(server.id)),
),
_button(
context,
'Edit ${server.name}',
connections.busy
? null
: () => unawaited(_edit(context, server)),
),
_button(
context,
'Remove ${server.name}',
connections.busy
? null
: () => unawaited(_remove(context, server)),
),
],
),
const SizedBox(height: 12),
],
Align(
alignment: AlignmentDirectional.centerStart,
child: _button(
context,
'Add server',
connections.busy ? null : () => unawaited(_edit(context)),
),
),
if (connections.error != null)
Text(
connections.error!,
style: TextStyle(
color: usesCupertinoHost(context)
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
),
),
],
),
);
}
@@ -0,0 +1,126 @@
import 'package:flutter/foundation.dart';
import '../../core/servers/server_catalog.dart';
import '../../core/servers/server_catalog_store.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});
final ServerCatalogStore store;
final Future<void> Function(SavedServer?) onSelected;
ServerCatalog _catalog = ServerCatalog();
bool _busy = false;
String? _error;
bool _disposed = false;
ServerCatalog get catalog => _catalog;
bool get busy => _busy;
String? get error => _error;
/// 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}) => _change(
() => _catalog.select(id),
activate: activate,
rollbackSelection: true,
);
Future<bool> remove(String id) =>
_change(() => _catalog.remove(id), 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();
}
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
+5 -5
View File
@@ -5,8 +5,8 @@ import '../../core/transport/pipelines_client.dart' as transport;
const String serverUrlPlaceholder = 'ws://192.168.1.20:8081/connect';
const String serverUrlHelper =
'ws:// on a trusted LAN/VPN, or wss:// through a proxy/VPN. '
'No authentication is used.';
'ws:// only on a trusted LAN/VPN, or wss:// for TLS. '
'Use the authenticated web proxy’s /connect address when sign-in is required.';
const String workspacePlaceholder = '/Users/you/repos/pipelines';
@@ -22,9 +22,9 @@ const String workspacePathError =
const String trustTitle = 'Trusted LAN/VPN only';
const String trustBody =
'The Pipelines API has no authentication and is not internet-safe. Do not '
'expose it to untrusted networks, and never enter provider credentials '
'here \u2014 the app stores none.';
'Use the authenticated web address for remote access. Direct API access '
'has no authentication and must stay on a trusted LAN/VPN. ws:// traffic '
'is unencrypted; prefer wss://. Never enter provider credentials here.';
/// The workspace draft is valid when it is untouched (empty) or absolute. A
/// relative path is the one rejected value; the execution server resolves the
+34 -7
View File
@@ -19,6 +19,9 @@ import 'settings_updates_section.dart';
import '../updates/app_updates.dart';
import 'settings_store.dart';
import 'settings_templates_section.dart';
import 'server_connections.dart';
import 'saved_servers_section.dart';
import 'managed_connection_section.dart';
/// The Settings destination: the server connection and the server-side
/// workspace, in native Material (native platforms) or Cupertino (iOS) controls.
@@ -41,6 +44,7 @@ class SettingsScreen extends StatefulWidget {
this.notifications,
this.showSignIn = false,
this.showAndroidDownload = false,
this.servers,
});
final transport.PipelinesClient client;
@@ -50,6 +54,7 @@ class SettingsScreen extends StatefulWidget {
/// A browser page links the Android app the server offers.
final bool showAndroidDownload;
final ServerConnections? servers;
/// A fixture/preview seed for the URL field. Persisted settings still load;
/// this value takes precedence for the draft and is never written by itself.
@@ -145,12 +150,24 @@ class _SettingsScreenState extends State<SettingsScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
if (widget.servers != null) ...[
_SettingsSection(
title: 'Servers',
child: SavedServersSection(connections: widget.servers!),
),
const SizedBox(height: settingsSectionGap),
],
_SettingsSection(
title: 'Connection',
child: SettingsConnectionSection(
controller: _controller,
serverUrlField: _serverUrlField,
),
child: widget.servers != null
? ManagedConnectionSection(
client: widget.client,
controller: _controller,
)
: SettingsConnectionSection(
controller: _controller,
serverUrlField: _serverUrlField,
),
),
// A phone signs in at the web login; a browser has its own.
if (widget.showSignIn) ...<Widget>[
@@ -158,10 +175,18 @@ class _SettingsScreenState extends State<SettingsScreen> {
_SettingsSection(
title: 'Sign in',
child: SettingsSignInSection(
endpoint: _controller.serverUrl,
endpoint: widget.servers == null
? _controller.serverUrl
: widget.client.endpoint?.toString() ?? '',
onChanged: () {
final endpoint = widget.client.endpoint;
if (endpoint != null) widget.client.connect(endpoint);
if (endpoint != null) {
widget.client.connectAny(
widget.client.endpoints.isEmpty
? [endpoint]
: widget.client.endpoints,
);
}
},
),
),
@@ -180,7 +205,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
_SettingsSection(
title: 'App updates',
child: SettingsUpdatesSection(
endpoint: _controller.serverUrl,
endpoint: widget.servers == null
? _controller.serverUrl
: widget.client.endpoint?.toString() ?? '',
),
),
],
@@ -1,4 +1,5 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/servers/server_scope.dart';
/// The app's own settings keys. They are deliberately independent of the legacy
/// web/Android storage: no value is imported, migrated or written under an old
@@ -31,7 +32,10 @@ abstract interface class SettingsStore {
/// return false instead of throwing, letting the screen keep the in-memory
/// value while saying plainly that it was not stored.
class SharedPreferencesSettingsStore implements SettingsStore {
const SharedPreferencesSettingsStore();
const SharedPreferencesSettingsStore({this.serverId = ''});
final String serverId;
String get _workspaceKey =>
scopedServerKey(settingsWorkspaceKey, serverStorageScope(serverId));
Future<SharedPreferences?> _preferences() async {
try {
@@ -48,7 +52,7 @@ class SharedPreferencesSettingsStore implements SettingsStore {
try {
return SettingsValues(
serverUrl: preferences.getString(settingsServerUrlKey) ?? '',
workspace: preferences.getString(settingsWorkspaceKey) ?? '',
workspace: preferences.getString(_workspaceKey) ?? '',
);
} catch (_) {
return const SettingsValues();
@@ -71,7 +75,7 @@ class SharedPreferencesSettingsStore implements SettingsStore {
final preferences = await _preferences();
if (preferences == null) return false;
try {
return await preferences.setString(settingsWorkspaceKey, value.trim());
return await preferences.setString(_workspaceKey, value.trim());
} catch (_) {
return false;
}