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
@@ -1,4 +1,5 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../../../core/servers/server_scope.dart';
import 'notification_ledger.dart';
@@ -21,7 +22,9 @@ abstract interface class NotificationStore {
/// documented [notificationStorageKey] is touched, never the attention key or the
/// legacy web key.
class SharedPreferencesNotificationStore implements NotificationStore {
const SharedPreferencesNotificationStore();
const SharedPreferencesNotificationStore({this.serverId = ''});
final String serverId;
String get _key => scopedServerKey(notificationStorageKey, serverId);
Future<SharedPreferences?> _preferences() async {
try {
@@ -36,7 +39,7 @@ class SharedPreferencesNotificationStore implements NotificationStore {
final preferences = await _preferences();
if (preferences == null) return null;
try {
return preferences.getString(notificationStorageKey);
return preferences.getString(_key);
} catch (_) {
return null;
}
@@ -47,7 +50,7 @@ class SharedPreferencesNotificationStore implements NotificationStore {
final preferences = await _preferences();
if (preferences == null) return false;
try {
return await preferences.setString(notificationStorageKey, value);
return await preferences.setString(_key, value);
} catch (_) {
return false;
}
@@ -1,4 +1,5 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../../../core/servers/server_scope.dart';
import '../domain/attention_models.dart';
@@ -20,7 +21,9 @@ abstract interface class AttentionStore {
/// disk returns null/false instead of throwing into the caller's frame. Only the
/// documented [attentionStorageKey] is touched, never the legacy web key.
class SharedPreferencesAttentionStore implements AttentionStore {
const SharedPreferencesAttentionStore();
const SharedPreferencesAttentionStore({this.serverId = ''});
final String serverId;
String get _key => scopedServerKey(attentionStorageKey, serverId);
Future<SharedPreferences?> _preferences() async {
try {
@@ -35,7 +38,7 @@ class SharedPreferencesAttentionStore implements AttentionStore {
final preferences = await _preferences();
if (preferences == null) return null;
try {
return preferences.getString(attentionStorageKey);
return preferences.getString(_key);
} catch (_) {
return null;
}
@@ -46,7 +49,7 @@ class SharedPreferencesAttentionStore implements AttentionStore {
final preferences = await _preferences();
if (preferences == null) return false;
try {
return await preferences.setString(attentionStorageKey, value);
return await preferences.setString(_key, value);
} catch (_) {
return false;
}
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../../../core/servers/server_scope.dart';
import '../data/chat_repository.dart';
import 'chat_draft_store.dart';
@@ -47,7 +48,11 @@ class ChatComposerController extends ChangeNotifier {
this.onOptimistic,
this.onRejected,
this.newOperationId,
}) : _drafts = drafts ?? const SharedPreferencesChatDraftStore() {
}) : _drafts =
drafts ??
SharedPreferencesChatDraftStore(
serverId: serverStorageScope(serverIdentity(gateway)),
) {
_subscription = gateway.frames.listen(_onFrame);
}
@@ -1,4 +1,5 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../../../core/servers/server_scope.dart';
/// One conversation's persisted composer draft, keyed by session id.
///
@@ -25,7 +26,10 @@ const String chatDraftKeyPrefix = 'pipelines.next.chatDraft.v1.';
/// Reads are tolerant and a write reports failure instead of throwing, so the
/// composer can keep the in-memory draft and say plainly that it was not saved.
class SharedPreferencesChatDraftStore implements ChatDraftStore {
const SharedPreferencesChatDraftStore();
const SharedPreferencesChatDraftStore({this.serverId = ''});
final String serverId;
String _key(String sessionId) =>
scopedServerKey('$chatDraftKeyPrefix$sessionId', serverId);
Future<SharedPreferences?> _preferences() async {
try {
@@ -40,7 +44,7 @@ class SharedPreferencesChatDraftStore implements ChatDraftStore {
final preferences = await _preferences();
if (preferences == null) return '';
try {
return preferences.getString('$chatDraftKeyPrefix$sessionId') ?? '';
return preferences.getString(_key(sessionId)) ?? '';
} catch (_) {
return '';
}
@@ -51,7 +55,7 @@ class SharedPreferencesChatDraftStore implements ChatDraftStore {
final preferences = await _preferences();
if (preferences == null) return false;
try {
final key = '$chatDraftKeyPrefix$sessionId';
final key = _key(sessionId);
if (text.isEmpty) return await preferences.remove(key);
return await preferences.setString(key, text);
} catch (_) {
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../core/servers/server_scope.dart';
/// Whether a new chat starts with a prompt, and which, for one harness and
/// directory: the last choice made there.
@@ -13,10 +14,13 @@ abstract interface class ChatCreatePromptStore {
}
class SharedPreferencesChatCreatePromptStore implements ChatCreatePromptStore {
const SharedPreferencesChatCreatePromptStore();
const SharedPreferencesChatCreatePromptStore({this.serverId = ''});
final String serverId;
static String _key(String backend, String directory) =>
'pipelines.chat.createPrompt.v1.$backend|$directory';
String _key(String backend, String directory) => scopedServerKey(
'pipelines.chat.createPrompt.v1.$backend|$directory',
serverId,
);
@override
Future<ChatCreatePrompt?> read(String backend, String directory) async {
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../core/servers/server_scope.dart';
/// Device-local list preferences, mirroring the web client's C13 behaviour:
/// hidden ids and the newest session recency this device has read.
@@ -124,7 +125,9 @@ abstract interface class ChatSessionLocalStore {
/// `shared_preferences`-backed storage; unavailable storage degrades to the
/// in-memory choice instead of failing the list.
class SharedPreferencesChatSessionLocalStore implements ChatSessionLocalStore {
const SharedPreferencesChatSessionLocalStore();
const SharedPreferencesChatSessionLocalStore({this.serverId = ''});
final String serverId;
String get _key => scopedServerKey(key, serverId);
static const key = 'pipelines.chat.local.v1';
@@ -140,7 +143,7 @@ class SharedPreferencesChatSessionLocalStore implements ChatSessionLocalStore {
Future<ChatSessionLocal> load() async {
final preferences = await _preferences();
try {
return ChatSessionLocal.decode(preferences?.getString(key));
return ChatSessionLocal.decode(preferences?.getString(_key));
} catch (_) {
return const ChatSessionLocal();
}
@@ -150,7 +153,7 @@ class SharedPreferencesChatSessionLocalStore implements ChatSessionLocalStore {
Future<void> save(ChatSessionLocal state) async {
final preferences = await _preferences();
try {
await preferences?.setString(key, state.encode());
await preferences?.setString(_key, state.encode());
} catch (_) {
// Storage may be unavailable; the in-memory choice still applies.
}
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../../core/api_gateway.dart';
import '../../../../core/servers/server_scope.dart';
import '../../../../core/transport/connection_state.dart';
import '../../data/chat_repository.dart';
import '../../domain/chat_sessions.dart';
@@ -17,7 +18,10 @@ import 'chat_session_local.dart';
class ChatSessionsController extends ChangeNotifier {
ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore})
: _localStore =
localStore ?? const SharedPreferencesChatSessionLocalStore() {
localStore ??
SharedPreferencesChatSessionLocalStore(
serverId: serverStorageScope(serverIdentity(repository.gateway)),
) {
_listenFrames();
}
@@ -4,6 +4,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../../../core/servers/server_scope.dart';
import '../../data/chat_create_prompt_store.dart';
import '../../data/chat_repository.dart';
import '../../domain/chat_commands.dart';
@@ -42,8 +43,7 @@ Future<JsonMap?> showChatCreateDialog(
required String operationId,
required Future<JsonMap> Function(ChatDraft draft, String operationId)
onSubmit,
ChatCreatePromptStore prompts =
const SharedPreferencesChatCreatePromptStore(),
ChatCreatePromptStore? prompts,
}) {
final dialog = CreateChatDialog(
repository: repository,
@@ -62,11 +62,11 @@ class CreateChatDialog extends StatefulWidget {
required this.repository,
required this.operationId,
required this.onSubmit,
this.prompts = const SharedPreferencesChatCreatePromptStore(),
this.prompts,
});
/// The last first-prompt choice per harness and directory.
final ChatCreatePromptStore prompts;
final ChatCreatePromptStore? prompts;
final ChatRepository repository;
final String operationId;
@@ -77,6 +77,11 @@ class CreateChatDialog extends StatefulWidget {
}
class _CreateChatDialogState extends State<CreateChatDialog> {
late final ChatCreatePromptStore _prompts =
widget.prompts ??
SharedPreferencesChatCreatePromptStore(
serverId: serverStorageScope(serverIdentity(widget.repository.gateway)),
);
final _instructions = TextEditingController(
text: chatDefaultSessionInstructions,
);
@@ -161,7 +166,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
_name.text = defaultChatName(directory, chatBackendLabel(backend));
}
final recall = ++_recall;
final saved = await widget.prompts.read(backend, directory);
final saved = await _prompts.read(backend, directory);
if (!mounted || recall != _recall) return;
if (_promptEdited) return;
setState(() {
@@ -193,7 +198,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
);
// Next time in this folder with this harness, the same choice.
unawaited(
widget.prompts.write(backend, directory, (
_prompts.write(backend, directory, (
send: _sendPrompt,
text: _instructions.text,
)),
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import '../../core/session/server_session.dart';
import '../../core/transport/server_url.dart';
import '../../core/servers/server_probe.dart';
import '../../ui/adaptive/host.dart';
/// Reaches a server and reports what it says about this device's session.
@@ -22,6 +23,8 @@ class OnboardingFlow extends StatefulWidget {
this.check = ServerSession.check,
this.signIn = ServerSession.signIn,
this.saveServer,
this.savedServers,
this.serverAddresses = const [],
});
/// Called with the signed-in server's endpoint.
@@ -35,6 +38,8 @@ class OnboardingFlow extends StatefulWidget {
final ServerCheck check;
final ServerSignIn signIn;
final Future<void> Function(String url)? saveServer;
final Widget? savedServers;
final List<Uri> serverAddresses;
@override
State<OnboardingFlow> createState() => _OnboardingFlowState();
@@ -87,7 +92,18 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
_busy = true;
_error = null;
});
final state = await widget.check(endpoint);
final candidates = [
endpoint,
if (widget.serverAddresses.contains(endpoint))
...widget.serverAddresses.where((candidate) => candidate != endpoint),
];
final result = await probeServerAddresses(
candidates,
check: widget.check,
isCurrent: () => mounted,
);
endpoint = result.endpoint;
final state = result.state;
if (!mounted) return;
if (state == SessionState.unreachable) {
setState(() {
@@ -96,7 +112,17 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
});
return;
}
await widget.saveServer?.call(endpoint.toString());
try {
await widget.saveServer?.call(endpoint.toString());
} catch (error) {
if (mounted) {
setState(() {
_busy = false;
_error = '$error';
});
}
return;
}
if (!mounted) return;
if (state == SessionState.signedIn) {
widget.onDone(endpoint);
@@ -225,6 +251,10 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
child: const Text('Change server'),
),
],
if (widget.savedServers != null) ...[
const SizedBox(height: 24),
widget.savedServers!,
],
],
),
),
+7 -1
View File
@@ -30,6 +30,7 @@ class PipelinesScreen extends StatefulWidget {
super.key,
required this.gateway,
this.endpoint = '',
this.legacyEndpoints = const [],
this.embedded = false,
this.syncToken = 0,
this.onRunStarted,
@@ -45,6 +46,7 @@ class PipelinesScreen extends StatefulWidget {
/// Validated websocket endpoint used to isolate stored launch intents.
final String endpoint;
final List<String> legacyEndpoints;
/// True under the application shell, which owns the single navigation bar.
final bool embedded;
@@ -103,7 +105,10 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
super.initState();
_controller = PipelinesController(
PipelinesRepository(widget.gateway),
pendingRunStore: SharedPreferencesPendingRunStore(widget.endpoint),
pendingRunStore: SharedPreferencesPendingRunStore(
widget.endpoint,
legacyEndpoints: widget.legacyEndpoints,
),
)..load();
final id = widget.initialPipelineId;
if (id != null) {
@@ -134,6 +139,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
PipelinesRepository(widget.gateway),
pendingRunStore: SharedPreferencesPendingRunStore(
widget.endpoint,
legacyEndpoints: widget.legacyEndpoints,
),
)
..load()
@@ -3,6 +3,7 @@ import '../../schedules/domain/editor/schedule_draft.dart';
import '../../schedules/ui/pipeline/schedule_pipeline_editor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/servers/server_scope.dart';
import '../../../core/api_gateway.dart';
import '../../settings/settings_store.dart';
@@ -119,9 +120,9 @@ class _RunPipelineDialogState extends State<_RunPipelineDialog> {
}
Future<void> _loadDirectories(RunPipelineIntent? restored) async {
final savedWorkspace = const SharedPreferencesSettingsStore().load().then(
(settings) => settings.workspace,
);
final savedWorkspace = SharedPreferencesSettingsStore(
serverId: serverStorageScope(serverIdentity(_gateway)),
).load().then((settings) => settings.workspace);
try {
final reply = await _gateway.call('chat_directories');
final value = reply['chat_directories'];
@@ -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;
}