diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml index 53f7c6c9..3ac1b307 100644 --- a/app/android/app/src/main/AndroidManifest.xml +++ b/app/android/app/src/main/AndroidManifest.xml @@ -4,9 +4,12 @@ + with ChangeNotifier { /// The destination that was open before Search, restored on close. AppRoute _searchReturn; + bool _searchTransient = false; /// The Settings route the Templates page closes back to. AppRoute _templatesReturn; @@ -210,10 +211,12 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { if (searchOpen) return; _searchReturn = _route; goTo(AppRoute.search); + _searchTransient = true; } void closeSearch() { if (!searchOpen) return; + _searchTransient = false; goTo(_searchReturn); } @@ -227,6 +230,7 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { Future setNewRoutePath(AppRoute configuration) async { if (configuration == _route) return; _rootExit.clear(); + _searchTransient = false; _route = configuration; notifyListeners(); } @@ -239,7 +243,7 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { Future popRoute() async { final navigator = _navigatorKey.currentState; if (navigator != null && await navigator.maybePop()) return true; - if (searchOpen) { + if (searchOpen && (searchBuilder != null || _searchTransient)) { closeSearch(); return true; } @@ -264,6 +268,7 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { AppRouteKind.runs || AppRouteKind.chat || AppRouteKind.settings => true, + AppRouteKind.search => searchBuilder == null && !_searchTransient, _ => false, }; @@ -306,6 +311,7 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { void goTo(AppRoute route) { if (route == _route) return; _rootExit.clear(); + _searchTransient = false; _route = route; notifyListeners(); } diff --git a/app/lib/application/app_session.dart b/app/lib/application/app_session.dart index 0c2d31ff..83d062b4 100644 --- a/app/lib/application/app_session.dart +++ b/app/lib/application/app_session.dart @@ -25,7 +25,9 @@ class AppSession extends ChangeNotifier { required Uri? endpoint, PipelinesClient? client, bool knownServer = false, + List? addresses, }) : _initialEndpoint = endpoint, + _initialAddresses = addresses, _client = client ?? PipelinesClient(), _everConnected = knownServer { _states = _client.states.listen(_onState); @@ -33,6 +35,7 @@ class AppSession extends ChangeNotifier { } final Uri? _initialEndpoint; + final List? _initialAddresses; final PipelinesClient _client; late final StreamSubscription _states; late final StreamSubscription _frames; @@ -69,7 +72,10 @@ class AppSession extends ChangeNotifier { /// so this is a no-op rather than a guessed endpoint. Future start() async { if (_disposed || endpoint == null) return; - await _client.connect(endpoint!); + final addresses = _client.endpoints.isNotEmpty + ? _client.endpoints + : _initialAddresses ?? [endpoint!]; + await _client.connectAny(addresses); } /// Retries now: reopens a disconnected socket, or repeats a refused watch on diff --git a/app/lib/application/bootstrap.dart b/app/lib/application/bootstrap.dart index f5d1283c..eb9bd8af 100644 --- a/app/lib/application/bootstrap.dart +++ b/app/lib/application/bootstrap.dart @@ -3,7 +3,6 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'app_url_strategy.dart'; -import 'pipelines_app.dart'; import 'pipelines_root.dart'; import 'server_endpoint.dart'; import '../features/settings/settings_store.dart'; @@ -55,12 +54,10 @@ Future runPipelinesApp({ settingsStore: settingsStore, ); runApp( - kIsWeb - ? PipelinesApp(server: server) - : PipelinesRoot( - server: server, - buildDefault: configured, - signedIn: ServerSession.cookie != null, - ), + PipelinesRoot( + server: server, + buildDefault: configured, + signedIn: kIsWeb || ServerSession.cookie != null, + ), ); } diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index f3169c29..1c33021c 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -5,6 +5,7 @@ import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import '../core/api_gateway.dart'; +import '../core/servers/server_scope.dart'; import '../core/transport/pipelines_client.dart'; import '../shell/adaptive_shell.dart'; import '../shell/destination.dart'; @@ -16,6 +17,8 @@ import '../features/attention/runtime/attention_store.dart'; import '../features/runs/ui/run_search_selection.dart'; import '../features/search/domain/search_target.dart'; import '../features/settings/settings_screen.dart'; +import '../features/settings/settings_store.dart'; +import '../features/settings/server_connections.dart'; import 'app.dart'; import 'app_route.dart'; import 'app_router.dart'; @@ -49,6 +52,11 @@ class PipelinesApp extends StatefulWidget { this.cupertino, this.routeInformationProvider, this.knownServer = false, + this.serverAddresses, + this.serverId, + this.servers, + this.resetRoute = false, + this.legacyPendingEndpoints = const [], }); final ServerEndpoint server; @@ -60,6 +68,11 @@ class PipelinesApp extends StatefulWidget { /// The device has signed in to [server] before (see [AppSession]). final bool knownServer; + final List? serverAddresses; + final String? serverId; + final ServerConnections? servers; + final bool resetRoute; + final List legacyPendingEndpoints; @override State createState() => _PipelinesAppState(); @@ -97,7 +110,9 @@ class _PipelinesAppState extends State /// One notification capability for the app: the Runs attention surface /// publishes live transitions and Settings renders the same permission. late final NotificationController _notifications = NotificationController( - store: const SharedPreferencesNotificationStore(), + store: SharedPreferencesNotificationStore( + serverId: serverStorageScope(widget.serverId), + ), ); ChatQuestionNotices? _chatQuestionNotices; @@ -107,7 +122,9 @@ class _PipelinesAppState extends State /// `run_event` frames are folded here so the count moves while another /// destination is shown, and a replaced socket drops the status baseline. late final AttentionController _attention = AttentionController( - store: const SharedPreferencesAttentionStore(), + store: SharedPreferencesAttentionStore( + serverId: serverStorageScope(widget.serverId), + ), ); StreamSubscription? _attentionFrames; int _attentionEpoch = 0; @@ -123,12 +140,16 @@ class _PipelinesAppState extends State endpoint: widget.server.uri, client: widget.client, knownServer: widget.knownServer, + addresses: widget.serverAddresses, ); + bindServerIdentity(_session.gateway, widget.serverId); _ownsProvider = widget.routeInformationProvider == null; _provider = widget.routeInformationProvider ?? PlatformRouteInformationProvider( - initialRouteInformation: initialRouteInformation(), + initialRouteInformation: widget.resetRoute + ? RouteInformation(uri: Uri.parse('/pipelines')) + : initialRouteInformation(), ); // A malformed or unknown boot path renders Pipelines, so make the address // bar agree with the rendered destination instead of showing a dead link. @@ -143,7 +164,9 @@ class _PipelinesAppState extends State ); } _cupertino = widget.cupertino ?? _platformIsCupertino; - _notifications.onOpenRun = (id) => _delegate.goTo(AppRoute.run(id)); + _notifications.onOpenRun = (id) { + if (mounted) _delegate.goTo(AppRoute.run(id)); + }; unawaited(_notifications.load()); unawaited(_attention.load()); _attentionFrames = _session.gateway.frames @@ -171,7 +194,9 @@ class _PipelinesAppState extends State return route.kind == AppRouteKind.chat ? route.chatSessionId : null; }, sessionTitle: _chatSessionTitle, - openChat: (id) => _delegate.goTo(AppRoute.chatSession(id)), + openChat: (id) { + if (mounted) _delegate.goTo(AppRoute.chatSession(id)); + }, bridge: _notifications.bridge, ); _config = RouterConfig( @@ -432,6 +457,7 @@ class _PipelinesAppState extends State AppDestination.pipelines: (_) => PipelinesDestination( session: _session, server: widget.server, + legacyPendingEndpoints: widget.legacyPendingEndpoints, refreshToken: _pipelinesRefresh, onRunStarted: _runStarted, onViewPipelineRuns: (id) => @@ -501,6 +527,10 @@ class _PipelinesAppState extends State showAndroidDownload: kIsWeb, initialEndpoint: _session.endpoint, embedded: true, + servers: widget.servers, + store: SharedPreferencesSettingsStore( + serverId: widget.serverId ?? '', + ), onOpenTemplates: _delegate.openTemplates, notifications: _notifications, ), diff --git a/app/lib/application/pipelines_destination.dart b/app/lib/application/pipelines_destination.dart index 2321984e..c389f53d 100644 --- a/app/lib/application/pipelines_destination.dart +++ b/app/lib/application/pipelines_destination.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import '../core/servers/server_scope.dart'; import '../features/pipelines/screen.dart'; import '../ui/adaptive/host.dart'; @@ -25,6 +26,7 @@ class PipelinesDestination extends StatelessWidget { this.initialPipelineId, this.initialVersion = 0, this.initialStageKey, + this.legacyPendingEndpoints = const [], }); final AppSession session; @@ -47,6 +49,7 @@ class PipelinesDestination extends StatelessWidget { /// The definition stage a deep link names, or null for no stage request. final String? initialStageKey; + final List legacyPendingEndpoints; @override Widget build(BuildContext context) => AnimatedBuilder( @@ -81,7 +84,10 @@ class PipelinesDestination extends StatelessWidget { Widget _pipelinesScreen() => PipelinesScreen( gateway: session.gateway, - endpoint: server.uri?.toString() ?? '', + endpoint: serverIdentity(session.gateway) == null + ? server.uri?.toString() ?? '' + : 'profile:${serverIdentity(session.gateway)}', + legacyEndpoints: legacyPendingEndpoints, embedded: true, onRunStarted: onRunStarted, onViewPipelineRuns: onViewPipelineRuns, diff --git a/app/lib/application/pipelines_root.dart b/app/lib/application/pipelines_root.dart index 572b6184..34dc8d29 100644 --- a/app/lib/application/pipelines_root.dart +++ b/app/lib/application/pipelines_root.dart @@ -1,9 +1,16 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; import '../core/session/server_session.dart'; +import '../core/servers/server_catalog.dart'; +import '../core/servers/server_catalog_store.dart'; +import '../core/servers/server_probe.dart'; +import '../core/transport/pipelines_client.dart'; import '../features/onboarding/onboarding_flow.dart'; +import '../features/settings/server_connections.dart'; +import '../features/settings/saved_servers_section.dart'; import '../features/settings/settings_store.dart'; import '../ui/theme/app_theme.dart'; import 'pipelines_app.dart'; @@ -20,6 +27,9 @@ class PipelinesRoot extends StatefulWidget { this.signedIn = false, this.check = ServerSession.check, this.settingsStore = const SharedPreferencesSettingsStore(), + this.catalogStore = const SharedPreferencesServerCatalogStore(), + this.web = kIsWeb, + this.clientFactory, }); final ServerEndpoint server; @@ -31,6 +41,9 @@ class PipelinesRoot extends StatefulWidget { final bool signedIn; final ServerCheck check; final SettingsStore settingsStore; + final ServerCatalogStore catalogStore; + final bool web; + final PipelinesClient Function()? clientFactory; @override State createState() => _PipelinesRootState(); @@ -41,24 +54,148 @@ class _PipelinesRootState extends State { late bool _onboarding = widget.server.uri == null || !widget.signedIn; bool _refused = false; int _generation = 0; + bool _booting = true; + int _activation = 0; + PipelinesClient? _client; + SavedServer? _activeServer; + late final ServerConnections _servers = ServerConnections( + store: widget.catalogStore, + onSelected: _selectServer, + ); @override void initState() { super.initState(); - if (!_onboarding) _verify(widget.server.uri!); + _loadServers(); + } + + Future _loadServers() async { + await _servers.load(legacyEndpoint: widget.server.uri?.toString() ?? ''); + if (!mounted) return; + if (widget.web) { + if (widget.server.uri != null) { + _servers.alignBrowserOrigin(widget.server.uri!); + } + setState(() { + _booting = false; + _onboarding = false; + _client = widget.clientFactory?.call(); + }); + return; + } + final persisted = + _servers.catalog.active == null || await _servers.persist(); + if (!mounted) return; + if (!persisted) { + ServerSession.clearSelection(); + setState(() { + _booting = false; + _onboarding = true; + }); + return; + } + await _activate(_servers.catalog.active, initial: true); + } + + Future _selectServer(SavedServer? server) async { + if (widget.web) { + if (server == null) return; + final endpoint = Uri.parse(server.endpoints.first); + if (endpoint == _server.uri) { + _servers.alignBrowserOrigin(endpoint); + return; + } + final page = endpoint.replace( + scheme: endpoint.scheme == 'wss' ? 'https' : 'http', + path: '/', + query: null, + fragment: null, + ); + if (!await launchUrl(page, webOnlyWindowName: '_self')) { + if (_server.uri != null) _servers.alignBrowserOrigin(_server.uri!); + throw StateError('Could not open the selected server.'); + } + return; + } + if (server != null && + server.id == _activeServer?.id && + listEquals(server.endpoints, _activeServer?.endpoints)) { + _activeServer = server; + return; + } + await _activate(server); + } + + Future _activate(SavedServer? server, {bool initial = false}) async { + final token = ++_activation; + if (!initial) { + setState(() => _booting = true); + // Dispose the old app/socket before changing the credential namespace. + await WidgetsBinding.instance.endOfFrame; + } + if (!mounted || token != _activation) return; + if (server == null) { + ServerSession.clearSelection(); + } else { + await ServerSession.activateServer( + id: server.id, + endpoints: server.endpoints.map(Uri.parse), + migrateLegacy: server.id == 'legacy-server', + ); + } + if (!mounted || token != _activation) return; + _activeServer = server; + 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')); + _refused = false; + _generation++; + _booting = false; + _client = _onboarding ? null : widget.clientFactory?.call(); + }); + if (!_onboarding && _server.uri != null) { + _verify(_server.uri!); + } } /// A kept session the server now refuses asks for the password again. Future _verify(Uri endpoint) async { - final state = await widget.check(endpoint); - if (!mounted || state != SessionState.signedOut) return; + final token = _activation; + final result = await probeServerAddresses( + [ + endpoint, + ...?_activeServer?.endpoints + .map(Uri.parse) + .where((uri) => uri != endpoint), + ], + check: widget.check, + isCurrent: () => mounted && token == _activation, + ); + if (!mounted || + token != _activation || + result.state != SessionState.signedOut) { + return; + } setState(() { _refused = true; _onboarding = true; + _server = ServerEndpoint.resolve( + base: Uri.base, + web: false, + configured: result.endpoint.toString(), + ); }); } void _done(Uri endpoint) { + _activeServer = _servers.catalog.active; setState(() { _server = ServerEndpoint.resolve( base: Uri.base, @@ -68,27 +205,93 @@ class _PipelinesRootState extends State { _onboarding = false; _refused = false; _generation++; + _client = widget.clientFactory?.call(); }); } + Future _saveOnboardingServer(String url) 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', + endpoints: [url], + ); + if (!await _servers.save(target, activate: false) || + !await _servers.select(target.id, activate: false)) { + throw StateError(_servers.error ?? 'Could not save the server.'); + } + if (!mounted || token != _activation) { + throw StateError('The selected server changed.'); + } + await ServerSession.activateServer( + id: target.id, + endpoints: target.endpoints.map(Uri.parse), + migrateLegacy: target.id == 'legacy-server', + ); + await widget.settingsStore.saveServerUrl(url); + } + + @override + void dispose() { + _activation++; + _servers.dispose(); + super.dispose(); + } + bool get _cupertino => defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS; @override Widget build(BuildContext context) { + if (_booting) { + // A temporary App/Navigator would replace the browser's deep-link URL + // before the real Router reads it. Loading must not own navigation. + return MediaQuery.fromView( + view: View.of(context), + child: Directionality( + textDirection: TextDirection.ltr, + child: _cupertino + ? const CupertinoTheme( + data: appCupertinoTheme, + child: Center(child: CupertinoActivityIndicator()), + ) + : Theme( + data: appLightTheme(), + child: const Center(child: CircularProgressIndicator()), + ), + ), + ); + } if (!_onboarding) { return PipelinesApp( key: ValueKey(_generation), server: _server, + client: _client, knownServer: true, + serverAddresses: widget.web + ? null + : _servers.catalog.active?.endpoints.map(Uri.parse).toList(), + serverId: _servers.catalog.active?.id, + servers: _servers, + legacyPendingEndpoints: [?_servers.catalog.active?.legacyEndpoint], + resetRoute: !widget.web && _generation > 1, ); } final flow = OnboardingFlow( initialServer: _server.uri?.toString() ?? widget.buildDefault, startAtPassword: _refused, - saveServer: widget.settingsStore.saveServerUrl, + saveServer: _saveOnboardingServer, onDone: _done, + savedServers: SavedServersSection(connections: _servers), + serverAddresses: + _servers.catalog.active?.endpoints.map(Uri.parse).toList() ?? + const [], ); return _cupertino ? CupertinoApp( diff --git a/app/lib/core/servers/server_probe.dart b/app/lib/core/servers/server_probe.dart new file mode 100644 index 00000000..37b655c3 --- /dev/null +++ b/app/lib/core/servers/server_probe.dart @@ -0,0 +1,23 @@ +import '../session/server_session.dart'; + +/// Probe only the selected profile's explicit aliases, with a bounded wait. +/// Never send a mutation or discover/switch logical servers. +Future<({Uri endpoint, SessionState state})> probeServerAddresses( + List addresses, { + required Future Function(Uri) check, + required bool Function() isCurrent, +}) async { + if (addresses.isEmpty) throw ArgumentError('No server addresses to probe.'); + for (final endpoint in addresses) { + if (!isCurrent()) break; + final state = await check(endpoint).timeout( + const Duration(seconds: 5), + onTimeout: () => SessionState.unreachable, + ); + if (!isCurrent()) break; + if (state != SessionState.unreachable) { + return (endpoint: endpoint, state: state); + } + } + return (endpoint: addresses.first, state: SessionState.unreachable); +} diff --git a/app/lib/core/servers/server_scope.dart b/app/lib/core/servers/server_scope.dart new file mode 100644 index 00000000..78329adb --- /dev/null +++ b/app/lib/core/servers/server_scope.dart @@ -0,0 +1,17 @@ +import '../api_gateway.dart'; + +final _identities = Expando('logical server identity'); + +/// Aliases share an identity; switching profiles creates a fresh app/gateway. +void bindServerIdentity(ApiGateway gateway, String? id) { + _identities[gateway] = id; +} + +String? serverIdentity(ApiGateway gateway) => _identities[gateway]; + +/// Existing local data belongs only to the migrated original server. +String serverStorageScope(String? id) => + id == null || id == 'legacy-server' ? '' : id; + +String scopedServerKey(String key, String scope) => + scope.isEmpty ? key : '$key.server.${Uri.encodeComponent(scope)}'; diff --git a/app/lib/core/session/server_session.dart b/app/lib/core/session/server_session.dart index 800fff3d..ea4e0e39 100644 --- a/app/lib/core/session/server_session.dart +++ b/app/lib/core/session/server_session.dart @@ -22,6 +22,14 @@ class ServerSession { static String? get serverId => _serverId; + /// Drop the active trust selection without deleting any server's sign-in. + static void clearSelection() { + _generation++; + _serverId = null; + _origins = {}; + cookie = null; + } + static String _scopeKey(String id) => 'pipelines.session.v2.${Uri.encodeComponent(id)}.cookie'; diff --git a/app/lib/features/attention/notify/notification_store.dart b/app/lib/features/attention/notify/notification_store.dart index 27b53806..3bebd13a 100644 --- a/app/lib/features/attention/notify/notification_store.dart +++ b/app/lib/features/attention/notify/notification_store.dart @@ -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 _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; } diff --git a/app/lib/features/attention/runtime/attention_store.dart b/app/lib/features/attention/runtime/attention_store.dart index fe9d4095..88c614d1 100644 --- a/app/lib/features/attention/runtime/attention_store.dart +++ b/app/lib/features/attention/runtime/attention_store.dart @@ -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 _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; } diff --git a/app/lib/features/chat/conversation/chat_composer_controller.dart b/app/lib/features/chat/conversation/chat_composer_controller.dart index 63e1caa6..307eaf8f 100644 --- a/app/lib/features/chat/conversation/chat_composer_controller.dart +++ b/app/lib/features/chat/conversation/chat_composer_controller.dart @@ -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); } diff --git a/app/lib/features/chat/conversation/chat_draft_store.dart b/app/lib/features/chat/conversation/chat_draft_store.dart index 3cb29151..529073dc 100644 --- a/app/lib/features/chat/conversation/chat_draft_store.dart +++ b/app/lib/features/chat/conversation/chat_draft_store.dart @@ -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 _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 (_) { diff --git a/app/lib/features/chat/data/chat_create_prompt_store.dart b/app/lib/features/chat/data/chat_create_prompt_store.dart index 7d4322b3..6fe9284d 100644 --- a/app/lib/features/chat/data/chat_create_prompt_store.dart +++ b/app/lib/features/chat/data/chat_create_prompt_store.dart @@ -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 read(String backend, String directory) async { diff --git a/app/lib/features/chat/ui/sessions/chat_session_local.dart b/app/lib/features/chat/ui/sessions/chat_session_local.dart index 3a64733d..d2070bae 100644 --- a/app/lib/features/chat/ui/sessions/chat_session_local.dart +++ b/app/lib/features/chat/ui/sessions/chat_session_local.dart @@ -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 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 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. } diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart index f4de453a..511f6f76 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -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(); } diff --git a/app/lib/features/chat/ui/sessions/create_chat_dialog.dart b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart index 643fd106..1d430948 100644 --- a/app/lib/features/chat/ui/sessions/create_chat_dialog.dart +++ b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart @@ -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 showChatCreateDialog( required String operationId, required Future 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 { + 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 { _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 { ); // 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, )), diff --git a/app/lib/features/onboarding/onboarding_flow.dart b/app/lib/features/onboarding/onboarding_flow.dart index a8f4d7ba..f453cfd7 100644 --- a/app/lib/features/onboarding/onboarding_flow.dart +++ b/app/lib/features/onboarding/onboarding_flow.dart @@ -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 Function(String url)? saveServer; + final Widget? savedServers; + final List serverAddresses; @override State createState() => _OnboardingFlowState(); @@ -87,7 +92,18 @@ class _OnboardingFlowState extends State { _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 { }); 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 { child: const Text('Change server'), ), ], + if (widget.savedServers != null) ...[ + const SizedBox(height: 24), + widget.savedServers!, + ], ], ), ), diff --git a/app/lib/features/pipelines/screen.dart b/app/lib/features/pipelines/screen.dart index 413f8b09..fa84463b 100644 --- a/app/lib/features/pipelines/screen.dart +++ b/app/lib/features/pipelines/screen.dart @@ -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 legacyEndpoints; /// True under the application shell, which owns the single navigation bar. final bool embedded; @@ -103,7 +105,10 @@ class _PipelinesScreenState extends State { 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 { PipelinesRepository(widget.gateway), pendingRunStore: SharedPreferencesPendingRunStore( widget.endpoint, + legacyEndpoints: widget.legacyEndpoints, ), ) ..load() diff --git a/app/lib/features/pipelines/ui/run_pipeline_dialog.dart b/app/lib/features/pipelines/ui/run_pipeline_dialog.dart index e3883dc5..b13fb001 100644 --- a/app/lib/features/pipelines/ui/run_pipeline_dialog.dart +++ b/app/lib/features/pipelines/ui/run_pipeline_dialog.dart @@ -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 _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']; diff --git a/app/lib/features/settings/managed_connection_section.dart b/app/lib/features/settings/managed_connection_section.dart new file mode 100644 index 00000000..d07cb0c8 --- /dev/null +++ b/app/lib/features/settings/managed_connection_section.dart @@ -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), + ], + ); +} diff --git a/app/lib/features/settings/saved_server_editor.dart b/app/lib/features/settings/saved_server_editor.dart new file mode 100644 index 00000000..772aa9af --- /dev/null +++ b/app/lib/features/settings/saved_server_editor.dart @@ -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 editSavedServer( + BuildContext context, { + SavedServer? server, +}) { + final page = _ServerEditor(server: server); + return Navigator.of(context).push( + 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, + ); + } +} diff --git a/app/lib/features/settings/saved_servers_section.dart b/app/lib/features/settings/saved_servers_section.dart new file mode 100644 index 00000000..9896d417 --- /dev/null +++ b/app/lib/features/settings/saved_servers_section.dart @@ -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 _edit(BuildContext context, [SavedServer? server]) async { + final edited = await editSavedServer(context, server: server); + if (edited != null) await connections.save(edited); + } + + Future _remove(BuildContext context, SavedServer server) async { + final cupertino = usesCupertinoHost(context); + final confirmed = cupertino + ? await showCupertinoDialog( + 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( + 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, + ), + ), + ], + ), + ); +} diff --git a/app/lib/features/settings/server_connections.dart b/app/lib/features/settings/server_connections.dart new file mode 100644 index 00000000..eb33f072 --- /dev/null +++ b/app/lib/features/settings/server_connections.dart @@ -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 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 persist() => _change(() => _catalog, activate: false); + + Future 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 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 select(String id, {bool activate = true}) => _change( + () => _catalog.select(id), + activate: activate, + rollbackSelection: true, + ); + + Future remove(String id) => + _change(() => _catalog.remove(id), activate: _catalog.active?.id == id); + + Future _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(); + } +} diff --git a/app/lib/features/settings/settings_copy.dart b/app/lib/features/settings/settings_copy.dart index 37c6c29f..b3cd1a7d 100644 --- a/app/lib/features/settings/settings_copy.dart +++ b/app/lib/features/settings/settings_copy.dart @@ -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 diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart index 8dac2371..a35e5c0c 100644 --- a/app/lib/features/settings/settings_screen.dart +++ b/app/lib/features/settings/settings_screen.dart @@ -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 { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + 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) ...[ @@ -158,10 +175,18 @@ class _SettingsScreenState extends State { _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 { _SettingsSection( title: 'App updates', child: SettingsUpdatesSection( - endpoint: _controller.serverUrl, + endpoint: widget.servers == null + ? _controller.serverUrl + : widget.client.endpoint?.toString() ?? '', ), ), ], diff --git a/app/lib/features/settings/settings_store.dart b/app/lib/features/settings/settings_store.dart index 84f2562e..209a714a 100644 --- a/app/lib/features/settings/settings_store.dart +++ b/app/lib/features/settings/settings_store.dart @@ -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 _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; } diff --git a/app/notes/multiple-servers.md b/app/notes/multiple-servers.md new file mode 100644 index 00000000..4242da0d --- /dev/null +++ b/app/notes/multiple-servers.md @@ -0,0 +1,54 @@ +# Multiple servers and double-back home exit + +User selected automatic fallback: named logical servers each have ordered +preferred/backup addresses. Switching logical servers is explicit, never an +automatic response to a network failure. User also requested two Android Back +presses at home to exit; details/dialogs still use one normal pop. + +| Item | Source | Verification | Landing | Deployment | +| --- | --- | --- | --- | --- | +| Immutable saved profiles/migration | 289a971b + afb97c75 | Roundtrip, ordered aliases, validation, failed writes, catalog-reset binding | Merged main | Pending | +| Ordered socket fallback | b2e5606c | 22 transport tests; bounded connect, cancellation, stale callbacks, no mutation replay | Merged main | Pending | +| Per-profile sign-in and trusted origins | ae72e0fc + integration clearSelection | 30 focused tests; aliases share only explicitly trusted cookies; sign-out and async login races isolated | Merged main | Pending | +| Native/root/settings integration | Manager integration | Root switch/dispose/reset and cache-isolation tests; full acceptance pending | Pending commit | Pending | +| Stable launch recovery across aliases | afb97c75 + manager wiring | Original request key survives legacy storage migration and preferred address changes | Merged + integration pending | Pending | +| Double-back home exit | 4e6771aa + Search-tab integration | First Android root Back hints; second within 2s falls to platform; navigation/dialogs/expiry clear window; iOS/web unaffected | Merged + integration pending | Pending | + +## Behavior and preservation + +- Settings → Servers: add/edit/remove named configurations, one address per line + in preferred order; explicitly select a different server. +- Root disposes the previous app/socket before activating the new credential + namespace, resets routes and remounts feature state. Alias fallback retains + the same logical server identity and never replays outstanding/queued mutations. +- Cookie, chat draft/instructions/read marks, workspace and notification/dismissal + storage are isolated per server. Existing original local data stays with the + migrated original server; legacy keys are retained for rollback. +- Legacy credential identity is bound before connection and cannot be rebound to + another server merely by deleting the catalog. The original endpoint pointer + is preserved solely to recover old pending-launch keys, never as a network alias. +- Browser sockets stay on their page origin. Selecting another browser server + opens its page; browser Back/reload reconciles selection to the actual origin. + Native builds provide automatic primary/backup address fallback. +- Explicit ws:// LAN profiles are allowed by Android, with cleartext/trusted-link + warnings. No TLS downgrade, server discovery or cross-profile cookie forwarding. + +## Evidence so far + +- 61 focused integration/profile/onboarding/migration tests pass; an additional + native-root fallback regression is included for final acceptance. +- Browser normal-app profile flow passes 8 checks/5 captures on each host: + `build/server-profiles-material/`, `build/server-profiles-cupertino/`. + Covers existing-address migration, alias editing, add without auto-switch, + reload, cross-origin page navigation, Back restoring actual selection, removal. +- Browser discovery: a temporary loading MaterialApp reset deep-link URLs before + the real Router mounted. Loading no longer owns an App/Navigator. +- Full suite caught two regressions and they were corrected: the isolated gate + test explicitly disposes its now-time-bounded connection before teardown; the + explicit openSearch API still restores its return route, while the Search tab + participates in home double-back. All 32 focused application regressions pass. +- Read-only security review identified three concrete issues (legacy identity + rebinding, browser selection mismatch, migrated pending-launch key changes); + fixes were re-reviewed with no remaining findings in that scope. +- No backend edits, production chat/run mutations, device use or phone installation. + Actual Android device behavior remains unverified. diff --git a/app/test/application/app_router_test.dart b/app/test/application/app_router_test.dart index e0272c70..e817682d 100644 --- a/app/test/application/app_router_test.dart +++ b/app/test/application/app_router_test.dart @@ -69,6 +69,7 @@ void main() { AppRoute.runsForPipeline(3), AppRoute.chat, AppRoute.settings, + AppRoute.search, ]) { testWidgets('${root.path} root exit expires and navigation clears it', ( tester, diff --git a/app/test/application/pipelines_root_test.dart b/app/test/application/pipelines_root_test.dart index e1c932bc..2bea8b50 100644 --- a/app/test/application/pipelines_root_test.dart +++ b/app/test/application/pipelines_root_test.dart @@ -5,6 +5,8 @@ import 'package:pipelines_app/application/server_endpoint.dart'; import 'package:pipelines_app/core/session/server_session.dart'; import 'package:pipelines_app/features/onboarding/onboarding_flow.dart'; import 'package:pipelines_app/features/settings/settings_store.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; class _Store implements SettingsStore { @override @@ -24,6 +26,10 @@ ServerEndpoint _server(String url) => ServerEndpoint.resolve( ); void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + await ServerSession.load(); + }); testWidgets( 'a first launch starts at the server, pre-filled from the build', (tester) async { @@ -33,6 +39,7 @@ void main() { buildDefault: 'wss://build.example/connect', check: (_) async => SessionState.signedOut, settingsStore: _Store(), + catalogStore: MemoryServerCatalogStore(), ), ); await tester.pumpAndSettle(); @@ -52,6 +59,7 @@ void main() { signedIn: false, check: (_) async => SessionState.signedOut, settingsStore: _Store(), + catalogStore: MemoryServerCatalogStore(), ), ); await tester.pumpAndSettle(); diff --git a/app/test/application/runs_destination_test.dart b/app/test/application/runs_destination_test.dart index 977a3482..8d9150f8 100644 --- a/app/test/application/runs_destination_test.dart +++ b/app/test/application/runs_destination_test.dart @@ -285,7 +285,7 @@ void main() { final session = AppSession(endpoint: server.uri, client: client); addTearDown(session.dispose); - session.start(); + final starting = session.start(); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( @@ -298,5 +298,8 @@ void main() { expect(find.byType(CupertinoActivityIndicator), findsOneWidget); expect(find.byType(CircularProgressIndicator), findsNothing); expect(find.byType(Material), findsNothing); + session.dispose(); + await starting; + await tester.pump(); }); } diff --git a/app/test/application/server_fallback_wiring_test.dart b/app/test/application/server_fallback_wiring_test.dart new file mode 100644 index 00000000..9ef61b5e --- /dev/null +++ b/app/test/application/server_fallback_wiring_test.dart @@ -0,0 +1,87 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/application/pipelines_root.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/core/session/server_session.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +void main() { + testWidgets( + 'native root tries same-server backup without changing logical identity', + (tester) async { + SharedPreferences.setMockInitialValues({ + 'pipelines.session.v2.home.cookie': 'pipelines_session=home', + }); + await ServerSession.load(); + final home = SavedServer.validated( + id: 'home', + name: 'Home', + endpoints: ['wss://tail.test/connect', 'ws://192.168.1.2:8083/connect'], + ); + final other = SavedServer.validated( + id: 'other', + name: 'Other', + endpoints: ['wss://other.test/connect'], + ); + final store = MemoryServerCatalogStore( + catalog: ServerCatalog(servers: [home, other], selectedId: home.id), + ); + final attempts = []; + final client = PipelinesClient( + backoffBase: const Duration(milliseconds: 10), + channelFactory: (uri) { + attempts.add(uri); + final channel = FakeChannel(); + if (uri.host == 'tail.test') { + channel.readyCompleter.completeError( + StateError('Tailscale unreachable'), + ); + } else { + channel.readyCompleter.complete(); + } + return channel; + }, + ); + await tester.pumpWidget( + PipelinesRoot( + server: ServerEndpoint.resolve( + base: Uri.parse('file:///'), + web: false, + configured: home.endpoints.first, + ), + catalogStore: store, + check: (_) async => SessionState.signedIn, + clientFactory: () => client, + ), + ); + for (var frame = 0; frame < 16; frame++) { + await tester.pump(const Duration(milliseconds: 20)); + } + expect(attempts.map((uri) => uri.toString()), home.endpoints); + expect(client.endpoint.toString(), home.endpoints.last); + expect(client.state.kind, ConnectionKind.connected); + expect(serverIdentity(client), home.id); + expect(store.catalog?.selectedId, home.id); + expect( + tester.widget(find.byType(PipelinesApp)).serverId, + home.id, + ); + expect(ServerSession.headersFor(Uri.parse(home.endpoints.last)), { + 'Cookie': 'pipelines_session=home', + }); + expect( + ServerSession.headersFor(Uri.parse(other.endpoints.first)), + isEmpty, + ); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }, + ); +} diff --git a/app/test/application/server_selection_test.dart b/app/test/application/server_selection_test.dart new file mode 100644 index 00000000..56e50c8d --- /dev/null +++ b/app/test/application/server_selection_test.dart @@ -0,0 +1,220 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/pipelines_root.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/core/session/server_session.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; +import 'package:pipelines_app/features/settings/saved_servers_section.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +SavedServer saved(String id, List endpoints) => + SavedServer.validated(id: id, name: id, endpoints: endpoints); + +Future frames(WidgetTester tester) async { + for (var frame = 0; frame < 12; frame++) { + await tester.pump(const Duration(milliseconds: 20)); + } +} + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({ + 'pipelines.session.v2.home.cookie': 'pipelines_session=home', + 'pipelines.session.v2.work.cookie': 'pipelines_session=work', + }); + await ServerSession.load(); + }); + + testWidgets( + 'catalog reset to another saved URL cannot reuse original scoped login', + (tester) async { + final store = const SharedPreferencesServerCatalogStore(); + final original = await store.load( + legacyEndpoint: 'wss://original.test/connect', + ); + expect(await store.save(original), isTrue); + final preferences = await SharedPreferences.getInstance(); + await preferences.setString( + 'pipelines.session.cookie', + 'pipelines_session=original', + ); + await preferences.setString( + 'pipelines.session.v2.legacy-server.cookie', + 'pipelines_session=original', + ); + await preferences.remove(serverCatalogKey); + await ServerSession.load(); + await tester.pumpWidget( + PipelinesRoot( + server: ServerEndpoint.resolve( + base: Uri.parse('file:///'), + web: false, + configured: 'wss://different.test/connect', + ), + signedIn: true, + catalogStore: store, + settingsStore: MemorySettingsStore(), + check: (_) async => SessionState.signedOut, + clientFactory: () => throw StateError( + 'Must not connect before signing in to the new server', + ), + ), + ); + await frames(tester); + expect(find.byType(PipelinesApp), findsNothing); + expect(ServerSession.cookie, isNull); + expect( + ServerSession.headersFor(Uri.parse('wss://different.test/connect')), + isEmpty, + ); + final recovered = await store.load(); + expect(recovered.active?.id, isNot('legacy-server')); + expect(recovered.active?.legacyEndpoint, isNull); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + + testWidgets( + 'switch closes old socket, resets app and persists selected profile', + (tester) async { + final home = saved('home', [ + 'wss://home.test/connect', + 'ws://192.168.1.2:8083/connect', + ]); + final work = saved('work', ['wss://work.test/connect']); + final store = MemoryServerCatalogStore( + catalog: ServerCatalog(servers: [home, work], selectedId: home.id), + ); + final clients = []; + final channels = []; + final attempted = []; + PipelinesClient factory() { + final channel = FakeChannel()..readyCompleter.complete(); + channels.add(channel); + final client = PipelinesClient( + channelFactory: (uri) { + attempted.add(uri); + return channel; + }, + ); + clients.add(client); + return client; + } + + final server = ServerEndpoint.resolve( + base: Uri.parse('file:///'), + web: false, + configured: home.endpoints.first, + ); + await tester.pumpWidget( + PipelinesRoot( + server: server, + catalogStore: store, + clientFactory: factory, + settingsStore: MemorySettingsStore(), + check: (_) async => SessionState.signedIn, + ), + ); + await frames(tester); + final app = tester.widget(find.byType(PipelinesApp)); + expect(app.serverId, 'home'); + expect(app.serverAddresses?.map((uri) => uri.toString()), home.endpoints); + final oldKey = app.key; + final oldClient = clients.single; + final request = expectLater( + oldClient.call('chat_prompt', const { + 'chat_prompt': {'session_id': 'same-id', 'text': 'do not replay'}, + }), + throwsA(isA()), + ); + final switched = app.servers!.select('work'); + await frames(tester); + expect(await switched, isTrue); + await request; + final selected = tester.widget(find.byType(PipelinesApp)); + expect(selected.serverId, 'work'); + expect(selected.key, isNot(oldKey)); + expect(selected.resetRoute, isTrue); + expect(store.catalog?.selectedId, 'work'); + expect(attempted.map((uri) => uri.host), ['home.test', 'work.test']); + expect( + ServerSession.headersFor(Uri.parse(home.endpoints.first)), + isEmpty, + ); + expect(ServerSession.headersFor(Uri.parse(work.endpoints.first)), { + 'Cookie': 'pipelines_session=work', + }); + expect( + channels.last.outgoing + .map((frame) => jsonDecode(frame as String)) + .where((frame) => frame['type'] == 'chat_prompt'), + isEmpty, + ); + await expectLater( + oldClient.connect(Uri.parse(home.endpoints.first)), + throwsStateError, + ); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + + testWidgets( + 'removing selected server never selects another or revives legacy login', + (tester) async { + SharedPreferences.setMockInitialValues({ + 'pipelines.session.cookie': 'pipelines_session=old-home', + }); + await ServerSession.load(); + final home = saved('legacy-server', ['wss://old-home.test/connect']); + final store = MemoryServerCatalogStore( + catalog: ServerCatalog(servers: [home], selectedId: home.id), + ); + await tester.pumpWidget( + PipelinesRoot( + server: ServerEndpoint.resolve( + base: Uri.parse('file:///'), + web: false, + configured: home.endpoints.first, + ), + catalogStore: store, + settingsStore: MemorySettingsStore(), + check: (_) async => SessionState.signedIn, + clientFactory: () => PipelinesClient( + channelFactory: (_) => FakeChannel()..readyCompleter.complete(), + ), + ), + ); + await frames(tester); + final connections = tester + .widget(find.byType(PipelinesApp)) + .servers!; + final removed = connections.remove(home.id); + await frames(tester); + expect(await removed, isTrue); + expect(connections.catalog.active, isNull); + expect(find.byType(PipelinesApp), findsNothing); + expect(find.byType(SavedServersSection), findsOneWidget); + final added = connections.save( + saved('new-work', ['wss://new-work.test/connect']), + ); + await frames(tester); + expect(await added, isTrue); + expect(ServerSession.cookie, isNull); + expect( + ServerSession.headersFor(Uri.parse('wss://new-work.test/connect')), + isEmpty, + ); + expect(find.byType(PipelinesApp), findsNothing); + expect(find.text('wss://new-work.test/connect'), findsWidgets); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); +} diff --git a/app/test/core/servers/server_local_scope_test.dart b/app/test/core/servers/server_local_scope_test.dart new file mode 100644 index 00000000..b43ceb22 --- /dev/null +++ b/app/test/core/servers/server_local_scope_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/data/chat_create_prompt_store.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_session_local.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + test( + 'server-local drafts, read marks, workspace and alerts stay isolated', + () async { + const homeDrafts = SharedPreferencesChatDraftStore(serverId: 'home'); + const workDrafts = SharedPreferencesChatDraftStore(serverId: 'work'); + await homeDrafts.write('same-session-id', 'private home draft'); + expect(await workDrafts.read('same-session-id'), ''); + const homePrompts = SharedPreferencesChatCreatePromptStore( + serverId: 'home', + ); + const workPrompts = SharedPreferencesChatCreatePromptStore( + serverId: 'work', + ); + await homePrompts.write('opencode', '/same-path', ( + send: true, + text: 'private instructions', + )); + expect(await workPrompts.read('opencode', '/same-path'), isNull); + await workDrafts.write('same-session-id', 'work draft'); + expect(await homeDrafts.read('same-session-id'), 'private home draft'); + const homeLocal = SharedPreferencesChatSessionLocalStore( + serverId: 'home', + ); + const workLocal = SharedPreferencesChatSessionLocalStore( + serverId: 'work', + ); + await homeLocal.save(const ChatSessionLocal(hidden: ['same-session-id'])); + expect((await workLocal.load()).hidden, isEmpty); + const homeSettings = SharedPreferencesSettingsStore(serverId: 'home'); + const workSettings = SharedPreferencesSettingsStore(serverId: 'work'); + await homeSettings.saveWorkspace('/home-project'); + expect((await workSettings.load()).workspace, ''); + const homeAttention = SharedPreferencesAttentionStore(serverId: 'home'); + const workAttention = SharedPreferencesAttentionStore(serverId: 'work'); + await homeAttention.write('home dismissals'); + expect(await workAttention.read(), isNull); + const homeNotifications = SharedPreferencesNotificationStore( + serverId: 'home', + ); + const workNotifications = SharedPreferencesNotificationStore( + serverId: 'work', + ); + await homeNotifications.write('home ledger'); + expect(await workNotifications.read(), isNull); + }, + ); + + test( + 'migrated original server retains legacy local data; new servers do not', + () async { + await const SharedPreferencesChatDraftStore().write( + 's', + 'existing draft', + ); + final old = SharedPreferencesChatDraftStore( + serverId: serverStorageScope('legacy-server'), + ); + expect(await old.read('s'), 'existing draft'); + expect( + await const SharedPreferencesChatDraftStore(serverId: 'new').read('s'), + '', + ); + }, + ); +} diff --git a/app/test/features/onboarding/onboarding_flow_test.dart b/app/test/features/onboarding/onboarding_flow_test.dart index 4b006ebd..871b7780 100644 --- a/app/test/features/onboarding/onboarding_flow_test.dart +++ b/app/test/features/onboarding/onboarding_flow_test.dart @@ -4,6 +4,76 @@ import 'package:pipelines_app/core/session/server_session.dart'; import 'package:pipelines_app/features/onboarding/onboarding_flow.dart'; void main() { + testWidgets('sign-in uses a reachable backup within the selected server', ( + tester, + ) async { + final primary = Uri.parse('wss://tail.example/connect'); + final backup = Uri.parse('ws://192.168.1.2:8083/connect'); + final checked = []; + final signedIn = []; + final saved = []; + await tester.pumpWidget( + MaterialApp( + home: OnboardingFlow( + initialServer: primary.toString(), + serverAddresses: [primary, backup], + check: (uri) async { + checked.add(uri); + return uri == primary + ? SessionState.unreachable + : SessionState.signedOut; + }, + signIn: (uri, _) async { + signedIn.add(uri); + return null; + }, + saveServer: (url) async => saved.add(url), + onDone: (_) {}, + ), + ), + ); + await tester.tap(find.byKey(const Key('onboarding-next'))); + await tester.pumpAndSettle(); + expect(checked, [primary, backup]); + expect(saved, [backup.toString()]); + await tester.enterText( + find.byKey(const Key('onboarding-password')), + 'fixture-password', + ); + await tester.tap(find.byKey(const Key('onboarding-next'))); + await tester.pump(); + await tester.pump(); + expect(signedIn, [backup]); + }); + + testWidgets( + 'typing a different server does not try another profile backups', + (tester) async { + final primary = Uri.parse('wss://tail.example/connect'); + final checked = []; + await tester.pumpWidget( + MaterialApp( + home: OnboardingFlow( + initialServer: primary.toString(), + serverAddresses: [primary, Uri.parse('ws://192.168.1.2/connect')], + check: (uri) async { + checked.add(uri); + return SessionState.unreachable; + }, + onDone: (_) {}, + ), + ), + ); + await tester.enterText( + find.byKey(const Key('onboarding-server')), + 'wss://different.example/connect', + ); + await tester.tap(find.byKey(const Key('onboarding-next'))); + await tester.pumpAndSettle(); + expect(checked, [Uri.parse('wss://different.example/connect')]); + }, + ); + testWidgets('server, then password; both kept, then the app opens', ( tester, ) async { diff --git a/app/test/features/settings/saved_servers_test.dart b/app/test/features/settings/saved_servers_test.dart new file mode 100644 index 00000000..6ecb689f --- /dev/null +++ b/app/test/features/settings/saved_servers_test.dart @@ -0,0 +1,192 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/features/settings/saved_servers_section.dart'; +import 'package:pipelines_app/features/settings/server_connections.dart'; + +SavedServer profile(String id, List urls) => + SavedServer.validated(id: id, name: id, endpoints: urls); + +void main() { + test( + 'browser Back aligns active identity with the actual page; failed switch restores selection', + () async { + final home = profile('Home', ['wss://home.test/connect']); + final work = profile('Work', ['wss://work.test/connect']); + final store = MemoryServerCatalogStore( + catalog: ServerCatalog(servers: [home, work], selectedId: 'Work'), + ); + final controller = ServerConnections( + store: store, + onSelected: (_) async => throw StateError('Navigation failed'), + ); + addTearDown(controller.dispose); + await controller.load(); + controller.alignBrowserOrigin(Uri.parse('wss://home.test/connect')); + expect(controller.catalog.active?.id, 'Home'); + expect(await controller.select('Work'), isFalse); + expect(controller.catalog.active?.id, 'Home'); + expect(store.catalog?.active?.id, 'Home'); + controller.alignBrowserOrigin( + Uri.parse('wss://unconfigured.test/connect'), + ); + expect(controller.catalog.active, isNull); + }, + ); + + test( + 'selection and address edits persist before activation; failed saves keep selection', + () async { + final home = profile('Home', [ + 'wss://home.test/connect', + 'ws://192.168.1.2:8083/connect', + ]); + final work = profile('Work', ['wss://work.test/connect']); + final store = MemoryServerCatalogStore( + catalog: ServerCatalog(servers: [home, work], selectedId: home.id), + ); + final activated = []; + final controller = ServerConnections( + store: store, + onSelected: (server) async { + expect(store.catalog?.selectedId, server?.id); + activated.add(server?.id); + }, + ); + addTearDown(controller.dispose); + await controller.load(); + expect(await controller.select(work.id), isTrue); + expect(activated, ['Work']); + store.failSaves = true; + expect(await controller.select(home.id), isFalse); + expect(controller.catalog.active?.id, 'Work'); + expect(activated, ['Work']); + expect(controller.error, contains('could not be saved')); + store.failSaves = false; + expect(await controller.remove('Work'), isTrue); + expect(controller.catalog.active, isNull); + expect(activated, ['Work', null]); + expect(controller.catalog.servers.single.id, 'Home'); + }, + ); + + test( + 'first explicit add selects its server but adding another does not switch', + () async { + final calls = []; + final controller = ServerConnections( + store: MemoryServerCatalogStore(), + onSelected: (s) async => calls.add(s?.id), + ); + addTearDown(controller.dispose); + await controller.load(); + expect( + await controller.save(profile('Home', ['wss://home.test'])), + isTrue, + ); + expect(controller.catalog.active?.id, 'Home'); + expect( + await controller.save(profile('Work', ['wss://work.test'])), + isTrue, + ); + expect(controller.catalog.active?.id, 'Home'); + expect(calls, ['Home']); + }, + ); + + for (final cupertino in [false, true]) { + testWidgets('add, edit and select ordered server aliases ($cupertino)', ( + tester, + ) async { + final calls = []; + final connections = ServerConnections( + store: MemoryServerCatalogStore(), + onSelected: (s) async => calls.add(s?.id), + ); + addTearDown(connections.dispose); + await connections.load(); + final body = SingleChildScrollView( + child: SavedServersSection(connections: connections), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: body)), + ) + : MaterialApp(home: Scaffold(body: body)), + ); + await tester.tap(find.text('Add server')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('server-profile-name')), + 'Home', + ); + await tester.enterText( + find.byKey(const Key('server-profile-addresses')), + 'wss://tail.example/connect\nws://192.168.1.2:8083/connect', + ); + await tester.ensureVisible(find.text('Save server')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + expect(connections.catalog.active?.name, 'Home'); + expect(connections.catalog.active?.endpoints, [ + 'wss://tail.example/connect', + 'ws://192.168.1.2:8083/connect', + ]); + expect( + find.text('Backup 1: ws://192.168.1.2:8083/connect'), + findsOneWidget, + ); + await tester.tap(find.text('Edit Home')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('server-profile-name')), + 'My home', + ); + await tester.ensureVisible(find.text('Save server')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + expect(connections.catalog.active?.name, 'My home'); + expect(calls, hasLength(2)); + expect(calls.first, calls.last); + expect(tester.takeException(), isNull); + }); + + testWidgets('invalid server addresses stay in editor ($cupertino)', ( + tester, + ) async { + final connections = ServerConnections( + store: MemoryServerCatalogStore(), + onSelected: (_) async {}, + ); + addTearDown(connections.dispose); + final body = SavedServersSection(connections: connections); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: body)) + : MaterialApp(home: Scaffold(body: body)), + ); + await tester.tap(find.text('Add server')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('server-profile-name')), + 'Home', + ); + await tester.enterText( + find.byKey(const Key('server-profile-addresses')), + 'not-a-url', + ); + await tester.ensureVisible(find.text('Save server')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('server-profile-addresses')), findsOneWidget); + expect(connections.catalog.servers, isEmpty); + expect(find.textContaining('valid URL'), findsOneWidget); + }); + } +} diff --git a/app/tool/server_profiles_probe.mjs b/app/tool/server_profiles_probe.mjs new file mode 100644 index 00000000..d522564e --- /dev/null +++ b/app/tool/server_profiles_probe.mjs @@ -0,0 +1,108 @@ +// Profile editing/persistence and cross-origin browser switching, loopback only. +// PROBE_PLATFORM=material node tool/server_profiles_probe.mjs +import assert from 'node:assert/strict'; +import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'; +import { once } from 'node:events'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { startFixture } from './runs_probe_server.mjs'; +import { launchChrome, waitForPort, waitForPage, connect, sleep } from './pipelines_probe_cdp_lib.mjs'; +import { axNodes, enableSemantics, waitFor, capture, assertName, clickAt } from './pipelines_probe_cdp_input.mjs'; + +const root = resolve(process.argv[2] ?? 'build/server_profiles_web'); +const output = resolve(process.argv[3] ?? 'build/server-profiles-evidence'); +await mkdir(output, { recursive: true }); +const home = await startFixture({ root }); +const backup = await startFixture({ root }); +const other = await startFixture({ root }); +const ws = url => url.replace('http:', 'ws:') + '/connect'; +const profile = await mkdtemp(join(tmpdir(), 'server-profiles-')); +const chrome = launchChrome('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', profile, 'about:blank'); +const log = { checks: [], captures: [] }; +let c; +try { + c = await connect((await waitForPage(await waitForPort(join(profile, 'DevToolsActivePort')))).webSocketDebuggerUrl); + await c.send('Page.enable'); + if (process.env.PROBE_PLATFORM === 'material') await c.send('Emulation.setUserAgentOverride', { + userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36', platform: 'Win32', + }); + await c.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true }); + const semantics = async () => { + assert.ok(await waitFor(() => c.evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), 12000)); + await enableSemantics(c); + }; + const click = async label => { + for (let step = 0; step < 6; step++) { + const target = (await axNodes(c)).find(node => node.name?.value === label && node.backendDOMNodeId && ['button', 'tab', 'link'].includes(node.role?.value)); + if (target) { + const { model } = await c.send('DOM.getBoxModel', { backendNodeId: target.backendDOMNodeId }); + const [x1, y1, , , x3, y3] = model.content; + if (y1 >= 0 && y3 <= 844) return clickAt(c, (x1 + x3) / 2, (y1 + y3) / 2); + } + await c.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 500, deltaX: 0, deltaY: 350 }); + await sleep(200); + } + throw new Error(`Control not found/in view: ${label}`); + }; + const type = async (index, text) => { + const node = (await axNodes(c)).filter(node => node.role?.value === 'textbox')[index]; + assert.ok(node, `text field ${index}`); + const { model } = await c.send('DOM.getBoxModel', { backendNodeId: node.backendDOMNodeId }); + const [x1, y1, , , x3, y3] = model.content; + await clickAt(c, (x1 + x3) / 2, (y1 + y3) / 2); + await c.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 4, commands: ['selectAll'] }); + await c.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 4 }); + await c.send('Input.insertText', { text }); + await sleep(300); + }; + await c.send('Page.navigate', { url: home.url + '/settings' }); + await semantics(); + await assertName(c, 'My server', 'existing server migrated into profiles', log); + await click('Edit My server'); + await type(0, 'Home'); + await type(1, `${ws(home.url)}\n${ws(backup.url)}`); + await capture(c, output, log, 'edit-home-addresses'); + await click('Save server'); + await assertName(c, `Backup 1: ${ws(backup.url)}`, 'ordered backup address saved', log); + await capture(c, output, log, 'home-with-backup'); + await click('Add server'); + await type(0, 'Other'); + await type(1, ws(other.url)); + await click('Save server'); + await assertName(c, 'Use Other', 'adding another server does not switch', log); + assert.equal(await c.evaluate('location.origin'), home.url); + await capture(c, output, log, 'two-saved-servers'); + await c.send('Page.reload'); + await semantics(); + await assertName(c, `Backup 1: ${ws(backup.url)}`, 'aliases persist after reload', log); + await assertName(c, 'Use Other', 'second server persists after reload', log); + await click('Use Other'); + assert.ok(await waitFor(async () => await c.evaluate('location.origin') === other.url, 12000)); + log.checks.push('browser server switch navigates origin, never crosses socket credentials'); + await semantics(); + await c.evaluate('history.back()'); + assert.ok(await waitFor(async () => await c.evaluate('location.origin') === home.url, 12000)); + await semantics(); + await assertName(c, 'Use Other', 'browser Back restores actual Home selection', log); + assert.ok(!(await axNodes(c)).some(node => node.name?.value === 'Use Home')); + await capture(c, output, log, 'back-restores-home-selection'); + await click('Remove Other'); + await click('Remove'); + await sleep(300); + assert.ok(!(await axNodes(c)).some(node => node.name?.value === 'Use Other')); + log.checks.push('remove configuration leaves selected server intact'); + await capture(c, output, log, 'other-removed'); + console.log(JSON.stringify(log, null, 2)); +} catch (error) { + if (c) { + await capture(c, output, log, 'failure'); + await writeFile(join(output, 'failure-ax.json'), JSON.stringify(await axNodes(c), null, 2)); + await writeFile(join(output, 'failure-storage.json'), JSON.stringify(await c.evaluate('Object.entries(localStorage)'), null, 2)); + } + throw error; +} finally { + await writeFile(join(output, 'result.json'), JSON.stringify(log, null, 2)); + c?.close(); + const exited = once(chrome, 'exit'); chrome.kill(); await exited; + await Promise.all([home.close(), backup.close(), other.close()]); +}