feat(app): configure and safely switch multi-address servers
This commit is contained in:
@@ -94,6 +94,7 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> 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<AppRoute> 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<AppRoute> with ChangeNotifier {
|
||||
Future<void> setNewRoutePath(AppRoute configuration) async {
|
||||
if (configuration == _route) return;
|
||||
_rootExit.clear();
|
||||
_searchTransient = false;
|
||||
_route = configuration;
|
||||
notifyListeners();
|
||||
}
|
||||
@@ -239,7 +243,7 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
|
||||
Future<bool> 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<AppRoute> with ChangeNotifier {
|
||||
AppRouteKind.runs ||
|
||||
AppRouteKind.chat ||
|
||||
AppRouteKind.settings => true,
|
||||
AppRouteKind.search => searchBuilder == null && !_searchTransient,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
@@ -306,6 +311,7 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
|
||||
void goTo(AppRoute route) {
|
||||
if (route == _route) return;
|
||||
_rootExit.clear();
|
||||
_searchTransient = false;
|
||||
_route = route;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -25,7 +25,9 @@ class AppSession extends ChangeNotifier {
|
||||
required Uri? endpoint,
|
||||
PipelinesClient? client,
|
||||
bool knownServer = false,
|
||||
List<Uri>? 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<Uri>? _initialAddresses;
|
||||
final PipelinesClient _client;
|
||||
late final StreamSubscription<ConnectionState> _states;
|
||||
late final StreamSubscription<JsonMap> _frames;
|
||||
@@ -69,7 +72,10 @@ class AppSession extends ChangeNotifier {
|
||||
/// so this is a no-op rather than a guessed endpoint.
|
||||
Future<void> 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
|
||||
|
||||
@@ -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<void> 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,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<Uri>? serverAddresses;
|
||||
final String? serverId;
|
||||
final ServerConnections? servers;
|
||||
final bool resetRoute;
|
||||
final List<String> legacyPendingEndpoints;
|
||||
|
||||
@override
|
||||
State<PipelinesApp> createState() => _PipelinesAppState();
|
||||
@@ -97,7 +110,9 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
/// 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<PipelinesApp>
|
||||
/// `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<JsonMap>? _attentionFrames;
|
||||
int _attentionEpoch = 0;
|
||||
@@ -123,12 +140,16 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
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<PipelinesApp>
|
||||
);
|
||||
}
|
||||
_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<PipelinesApp>
|
||||
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<AppRoute>(
|
||||
@@ -432,6 +457,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
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<PipelinesApp>
|
||||
showAndroidDownload: kIsWeb,
|
||||
initialEndpoint: _session.endpoint,
|
||||
embedded: true,
|
||||
servers: widget.servers,
|
||||
store: SharedPreferencesSettingsStore(
|
||||
serverId: widget.serverId ?? '',
|
||||
),
|
||||
onOpenTemplates: _delegate.openTemplates,
|
||||
notifications: _notifications,
|
||||
),
|
||||
|
||||
@@ -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<String> 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,
|
||||
|
||||
@@ -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<PipelinesRoot> createState() => _PipelinesRootState();
|
||||
@@ -41,24 +54,148 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
||||
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<void> _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<void> _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<void> _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<void> _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<PipelinesRoot> {
|
||||
_onboarding = false;
|
||||
_refused = false;
|
||||
_generation++;
|
||||
_client = widget.clientFactory?.call();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _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(
|
||||
|
||||
@@ -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<Uri> addresses, {
|
||||
required Future<SessionState> 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);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import '../api_gateway.dart';
|
||||
|
||||
final _identities = Expando<String>('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)}';
|
||||
@@ -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';
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
|
||||
import 'notification_ledger.dart';
|
||||
|
||||
@@ -21,7 +22,9 @@ abstract interface class NotificationStore {
|
||||
/// documented [notificationStorageKey] is touched, never the attention key or the
|
||||
/// legacy web key.
|
||||
class SharedPreferencesNotificationStore implements NotificationStore {
|
||||
const SharedPreferencesNotificationStore();
|
||||
const SharedPreferencesNotificationStore({this.serverId = ''});
|
||||
final String serverId;
|
||||
String get _key => scopedServerKey(notificationStorageKey, serverId);
|
||||
|
||||
Future<SharedPreferences?> _preferences() async {
|
||||
try {
|
||||
@@ -36,7 +39,7 @@ class SharedPreferencesNotificationStore implements NotificationStore {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return null;
|
||||
try {
|
||||
return preferences.getString(notificationStorageKey);
|
||||
return preferences.getString(_key);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
@@ -47,7 +50,7 @@ class SharedPreferencesNotificationStore implements NotificationStore {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return false;
|
||||
try {
|
||||
return await preferences.setString(notificationStorageKey, value);
|
||||
return await preferences.setString(_key, value);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
|
||||
import '../domain/attention_models.dart';
|
||||
|
||||
@@ -20,7 +21,9 @@ abstract interface class AttentionStore {
|
||||
/// disk returns null/false instead of throwing into the caller's frame. Only the
|
||||
/// documented [attentionStorageKey] is touched, never the legacy web key.
|
||||
class SharedPreferencesAttentionStore implements AttentionStore {
|
||||
const SharedPreferencesAttentionStore();
|
||||
const SharedPreferencesAttentionStore({this.serverId = ''});
|
||||
final String serverId;
|
||||
String get _key => scopedServerKey(attentionStorageKey, serverId);
|
||||
|
||||
Future<SharedPreferences?> _preferences() async {
|
||||
try {
|
||||
@@ -35,7 +38,7 @@ class SharedPreferencesAttentionStore implements AttentionStore {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return null;
|
||||
try {
|
||||
return preferences.getString(attentionStorageKey);
|
||||
return preferences.getString(_key);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
@@ -46,7 +49,7 @@ class SharedPreferencesAttentionStore implements AttentionStore {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return false;
|
||||
try {
|
||||
return await preferences.setString(attentionStorageKey, value);
|
||||
return await preferences.setString(_key, value);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import 'chat_draft_store.dart';
|
||||
|
||||
@@ -47,7 +48,11 @@ class ChatComposerController extends ChangeNotifier {
|
||||
this.onOptimistic,
|
||||
this.onRejected,
|
||||
this.newOperationId,
|
||||
}) : _drafts = drafts ?? const SharedPreferencesChatDraftStore() {
|
||||
}) : _drafts =
|
||||
drafts ??
|
||||
SharedPreferencesChatDraftStore(
|
||||
serverId: serverStorageScope(serverIdentity(gateway)),
|
||||
) {
|
||||
_subscription = gateway.frames.listen(_onFrame);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
|
||||
/// One conversation's persisted composer draft, keyed by session id.
|
||||
///
|
||||
@@ -25,7 +26,10 @@ const String chatDraftKeyPrefix = 'pipelines.next.chatDraft.v1.';
|
||||
/// Reads are tolerant and a write reports failure instead of throwing, so the
|
||||
/// composer can keep the in-memory draft and say plainly that it was not saved.
|
||||
class SharedPreferencesChatDraftStore implements ChatDraftStore {
|
||||
const SharedPreferencesChatDraftStore();
|
||||
const SharedPreferencesChatDraftStore({this.serverId = ''});
|
||||
final String serverId;
|
||||
String _key(String sessionId) =>
|
||||
scopedServerKey('$chatDraftKeyPrefix$sessionId', serverId);
|
||||
|
||||
Future<SharedPreferences?> _preferences() async {
|
||||
try {
|
||||
@@ -40,7 +44,7 @@ class SharedPreferencesChatDraftStore implements ChatDraftStore {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return '';
|
||||
try {
|
||||
return preferences.getString('$chatDraftKeyPrefix$sessionId') ?? '';
|
||||
return preferences.getString(_key(sessionId)) ?? '';
|
||||
} catch (_) {
|
||||
return '';
|
||||
}
|
||||
@@ -51,7 +55,7 @@ class SharedPreferencesChatDraftStore implements ChatDraftStore {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return false;
|
||||
try {
|
||||
final key = '$chatDraftKeyPrefix$sessionId';
|
||||
final key = _key(sessionId);
|
||||
if (text.isEmpty) return await preferences.remove(key);
|
||||
return await preferences.setString(key, text);
|
||||
} catch (_) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
|
||||
/// Whether a new chat starts with a prompt, and which, for one harness and
|
||||
/// directory: the last choice made there.
|
||||
@@ -13,10 +14,13 @@ abstract interface class ChatCreatePromptStore {
|
||||
}
|
||||
|
||||
class SharedPreferencesChatCreatePromptStore implements ChatCreatePromptStore {
|
||||
const SharedPreferencesChatCreatePromptStore();
|
||||
const SharedPreferencesChatCreatePromptStore({this.serverId = ''});
|
||||
final String serverId;
|
||||
|
||||
static String _key(String backend, String directory) =>
|
||||
'pipelines.chat.createPrompt.v1.$backend|$directory';
|
||||
String _key(String backend, String directory) => scopedServerKey(
|
||||
'pipelines.chat.createPrompt.v1.$backend|$directory',
|
||||
serverId,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<ChatCreatePrompt?> read(String backend, String directory) async {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../../../core/servers/server_scope.dart';
|
||||
|
||||
/// Device-local list preferences, mirroring the web client's C13 behaviour:
|
||||
/// hidden ids and the newest session recency this device has read.
|
||||
@@ -124,7 +125,9 @@ abstract interface class ChatSessionLocalStore {
|
||||
/// `shared_preferences`-backed storage; unavailable storage degrades to the
|
||||
/// in-memory choice instead of failing the list.
|
||||
class SharedPreferencesChatSessionLocalStore implements ChatSessionLocalStore {
|
||||
const SharedPreferencesChatSessionLocalStore();
|
||||
const SharedPreferencesChatSessionLocalStore({this.serverId = ''});
|
||||
final String serverId;
|
||||
String get _key => scopedServerKey(key, serverId);
|
||||
|
||||
static const key = 'pipelines.chat.local.v1';
|
||||
|
||||
@@ -140,7 +143,7 @@ class SharedPreferencesChatSessionLocalStore implements ChatSessionLocalStore {
|
||||
Future<ChatSessionLocal> load() async {
|
||||
final preferences = await _preferences();
|
||||
try {
|
||||
return ChatSessionLocal.decode(preferences?.getString(key));
|
||||
return ChatSessionLocal.decode(preferences?.getString(_key));
|
||||
} catch (_) {
|
||||
return const ChatSessionLocal();
|
||||
}
|
||||
@@ -150,7 +153,7 @@ class SharedPreferencesChatSessionLocalStore implements ChatSessionLocalStore {
|
||||
Future<void> save(ChatSessionLocal state) async {
|
||||
final preferences = await _preferences();
|
||||
try {
|
||||
await preferences?.setString(key, state.encode());
|
||||
await preferences?.setString(_key, state.encode());
|
||||
} catch (_) {
|
||||
// Storage may be unavailable; the in-memory choice still applies.
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../../../core/servers/server_scope.dart';
|
||||
import '../../../../core/transport/connection_state.dart';
|
||||
import '../../data/chat_repository.dart';
|
||||
import '../../domain/chat_sessions.dart';
|
||||
@@ -17,7 +18,10 @@ import 'chat_session_local.dart';
|
||||
class ChatSessionsController extends ChangeNotifier {
|
||||
ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore})
|
||||
: _localStore =
|
||||
localStore ?? const SharedPreferencesChatSessionLocalStore() {
|
||||
localStore ??
|
||||
SharedPreferencesChatSessionLocalStore(
|
||||
serverId: serverStorageScope(serverIdentity(repository.gateway)),
|
||||
) {
|
||||
_listenFrames();
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../../../core/servers/server_scope.dart';
|
||||
import '../../data/chat_create_prompt_store.dart';
|
||||
import '../../data/chat_repository.dart';
|
||||
import '../../domain/chat_commands.dart';
|
||||
@@ -42,8 +43,7 @@ Future<JsonMap?> showChatCreateDialog(
|
||||
required String operationId,
|
||||
required Future<JsonMap> Function(ChatDraft draft, String operationId)
|
||||
onSubmit,
|
||||
ChatCreatePromptStore prompts =
|
||||
const SharedPreferencesChatCreatePromptStore(),
|
||||
ChatCreatePromptStore? prompts,
|
||||
}) {
|
||||
final dialog = CreateChatDialog(
|
||||
repository: repository,
|
||||
@@ -62,11 +62,11 @@ class CreateChatDialog extends StatefulWidget {
|
||||
required this.repository,
|
||||
required this.operationId,
|
||||
required this.onSubmit,
|
||||
this.prompts = const SharedPreferencesChatCreatePromptStore(),
|
||||
this.prompts,
|
||||
});
|
||||
|
||||
/// The last first-prompt choice per harness and directory.
|
||||
final ChatCreatePromptStore prompts;
|
||||
final ChatCreatePromptStore? prompts;
|
||||
|
||||
final ChatRepository repository;
|
||||
final String operationId;
|
||||
@@ -77,6 +77,11 @@ class CreateChatDialog extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
late final ChatCreatePromptStore _prompts =
|
||||
widget.prompts ??
|
||||
SharedPreferencesChatCreatePromptStore(
|
||||
serverId: serverStorageScope(serverIdentity(widget.repository.gateway)),
|
||||
);
|
||||
final _instructions = TextEditingController(
|
||||
text: chatDefaultSessionInstructions,
|
||||
);
|
||||
@@ -161,7 +166,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
_name.text = defaultChatName(directory, chatBackendLabel(backend));
|
||||
}
|
||||
final recall = ++_recall;
|
||||
final saved = await widget.prompts.read(backend, directory);
|
||||
final saved = await _prompts.read(backend, directory);
|
||||
if (!mounted || recall != _recall) return;
|
||||
if (_promptEdited) return;
|
||||
setState(() {
|
||||
@@ -193,7 +198,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
|
||||
);
|
||||
// Next time in this folder with this harness, the same choice.
|
||||
unawaited(
|
||||
widget.prompts.write(backend, directory, (
|
||||
_prompts.write(backend, directory, (
|
||||
send: _sendPrompt,
|
||||
text: _instructions.text,
|
||||
)),
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/session/server_session.dart';
|
||||
import '../../core/transport/server_url.dart';
|
||||
import '../../core/servers/server_probe.dart';
|
||||
import '../../ui/adaptive/host.dart';
|
||||
|
||||
/// Reaches a server and reports what it says about this device's session.
|
||||
@@ -22,6 +23,8 @@ class OnboardingFlow extends StatefulWidget {
|
||||
this.check = ServerSession.check,
|
||||
this.signIn = ServerSession.signIn,
|
||||
this.saveServer,
|
||||
this.savedServers,
|
||||
this.serverAddresses = const [],
|
||||
});
|
||||
|
||||
/// Called with the signed-in server's endpoint.
|
||||
@@ -35,6 +38,8 @@ class OnboardingFlow extends StatefulWidget {
|
||||
final ServerCheck check;
|
||||
final ServerSignIn signIn;
|
||||
final Future<void> Function(String url)? saveServer;
|
||||
final Widget? savedServers;
|
||||
final List<Uri> serverAddresses;
|
||||
|
||||
@override
|
||||
State<OnboardingFlow> createState() => _OnboardingFlowState();
|
||||
@@ -87,7 +92,18 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
|
||||
_busy = true;
|
||||
_error = null;
|
||||
});
|
||||
final state = await widget.check(endpoint);
|
||||
final candidates = [
|
||||
endpoint,
|
||||
if (widget.serverAddresses.contains(endpoint))
|
||||
...widget.serverAddresses.where((candidate) => candidate != endpoint),
|
||||
];
|
||||
final result = await probeServerAddresses(
|
||||
candidates,
|
||||
check: widget.check,
|
||||
isCurrent: () => mounted,
|
||||
);
|
||||
endpoint = result.endpoint;
|
||||
final state = result.state;
|
||||
if (!mounted) return;
|
||||
if (state == SessionState.unreachable) {
|
||||
setState(() {
|
||||
@@ -96,7 +112,17 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
|
||||
});
|
||||
return;
|
||||
}
|
||||
await widget.saveServer?.call(endpoint.toString());
|
||||
try {
|
||||
await widget.saveServer?.call(endpoint.toString());
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_error = '$error';
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
if (state == SessionState.signedIn) {
|
||||
widget.onDone(endpoint);
|
||||
@@ -225,6 +251,10 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
|
||||
child: const Text('Change server'),
|
||||
),
|
||||
],
|
||||
if (widget.savedServers != null) ...[
|
||||
const SizedBox(height: 24),
|
||||
widget.savedServers!,
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -30,6 +30,7 @@ class PipelinesScreen extends StatefulWidget {
|
||||
super.key,
|
||||
required this.gateway,
|
||||
this.endpoint = '',
|
||||
this.legacyEndpoints = const [],
|
||||
this.embedded = false,
|
||||
this.syncToken = 0,
|
||||
this.onRunStarted,
|
||||
@@ -45,6 +46,7 @@ class PipelinesScreen extends StatefulWidget {
|
||||
|
||||
/// Validated websocket endpoint used to isolate stored launch intents.
|
||||
final String endpoint;
|
||||
final List<String> legacyEndpoints;
|
||||
|
||||
/// True under the application shell, which owns the single navigation bar.
|
||||
final bool embedded;
|
||||
@@ -103,7 +105,10 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
|
||||
super.initState();
|
||||
_controller = PipelinesController(
|
||||
PipelinesRepository(widget.gateway),
|
||||
pendingRunStore: SharedPreferencesPendingRunStore(widget.endpoint),
|
||||
pendingRunStore: SharedPreferencesPendingRunStore(
|
||||
widget.endpoint,
|
||||
legacyEndpoints: widget.legacyEndpoints,
|
||||
),
|
||||
)..load();
|
||||
final id = widget.initialPipelineId;
|
||||
if (id != null) {
|
||||
@@ -134,6 +139,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
|
||||
PipelinesRepository(widget.gateway),
|
||||
pendingRunStore: SharedPreferencesPendingRunStore(
|
||||
widget.endpoint,
|
||||
legacyEndpoints: widget.legacyEndpoints,
|
||||
),
|
||||
)
|
||||
..load()
|
||||
|
||||
@@ -3,6 +3,7 @@ import '../../schedules/domain/editor/schedule_draft.dart';
|
||||
import '../../schedules/ui/pipeline/schedule_pipeline_editor.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../core/servers/server_scope.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../settings/settings_store.dart';
|
||||
@@ -119,9 +120,9 @@ class _RunPipelineDialogState extends State<_RunPipelineDialog> {
|
||||
}
|
||||
|
||||
Future<void> _loadDirectories(RunPipelineIntent? restored) async {
|
||||
final savedWorkspace = const SharedPreferencesSettingsStore().load().then(
|
||||
(settings) => settings.workspace,
|
||||
);
|
||||
final savedWorkspace = SharedPreferencesSettingsStore(
|
||||
serverId: serverStorageScope(serverIdentity(_gateway)),
|
||||
).load().then((settings) => settings.workspace);
|
||||
try {
|
||||
final reply = await _gateway.call('chat_directories');
|
||||
final value = reply['chat_directories'];
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/transport/pipelines_client.dart';
|
||||
import '../../ui/adaptive/host.dart';
|
||||
import 'settings_controller.dart';
|
||||
import 'settings_sections.dart';
|
||||
import 'settings_trust_warning.dart';
|
||||
|
||||
/// Status follows the actual attempted address, not just the preferred URL.
|
||||
class ManagedConnectionSection extends StatelessWidget {
|
||||
const ManagedConnectionSection({
|
||||
super.key,
|
||||
required this.client,
|
||||
required this.controller,
|
||||
});
|
||||
final PipelinesClient client;
|
||||
final SettingsController controller;
|
||||
|
||||
Widget _action(BuildContext context, String text, VoidCallback? press) =>
|
||||
usesCupertinoHost(context)
|
||||
? CupertinoButton(onPressed: press, child: Text(text))
|
||||
: TextButton(onPressed: press, child: Text(text));
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
SelectableText('Current address: ${client.endpoint ?? 'Not connected'}'),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'Reconnect tries the preferred address first. A dropped or '
|
||||
'unreachable connection tries this server’s backup addresses automatically.',
|
||||
),
|
||||
if (kIsWeb)
|
||||
const Text(
|
||||
'In a browser, the connection stays on this page’s '
|
||||
'origin. Use a saved server to open its page; native apps use automatic address fallback.',
|
||||
),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
_action(
|
||||
context,
|
||||
'Reconnect',
|
||||
client.endpoints.isEmpty
|
||||
? null
|
||||
: () => unawaited(client.connectAny(client.endpoints)),
|
||||
),
|
||||
_action(context, 'Disconnect', () => unawaited(client.disconnect())),
|
||||
],
|
||||
),
|
||||
SettingsStatusCard(controller: controller),
|
||||
const SizedBox(height: 12),
|
||||
const SettingsTrustWarning(),
|
||||
if (controller.protocolWarning case final warning?) Text(warning),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/servers/server_catalog.dart';
|
||||
import '../../ui/adaptive/host.dart';
|
||||
|
||||
Future<SavedServer?> editSavedServer(
|
||||
BuildContext context, {
|
||||
SavedServer? server,
|
||||
}) {
|
||||
final page = _ServerEditor(server: server);
|
||||
return Navigator.of(context).push<SavedServer>(
|
||||
usesCupertinoHost(context)
|
||||
? CupertinoPageRoute(builder: (_) => page)
|
||||
: MaterialPageRoute(builder: (_) => page),
|
||||
);
|
||||
}
|
||||
|
||||
class _ServerEditor extends StatefulWidget {
|
||||
const _ServerEditor({this.server});
|
||||
final SavedServer? server;
|
||||
|
||||
@override
|
||||
State<_ServerEditor> createState() => _ServerEditorState();
|
||||
}
|
||||
|
||||
class _ServerEditorState extends State<_ServerEditor> {
|
||||
late final _name = TextEditingController(text: widget.server?.name ?? '');
|
||||
late final _addresses = TextEditingController(
|
||||
text: widget.server?.endpoints.join('\n') ?? '',
|
||||
);
|
||||
String? _error;
|
||||
|
||||
void _save() {
|
||||
try {
|
||||
final server = SavedServer.validated(
|
||||
id:
|
||||
widget.server?.id ??
|
||||
'server-${DateTime.now().microsecondsSinceEpoch}',
|
||||
name: _name.text,
|
||||
legacyEndpoint: widget.server?.legacyEndpoint,
|
||||
endpoints: _addresses.text
|
||||
.split('\n')
|
||||
.where((line) => line.trim().isNotEmpty),
|
||||
);
|
||||
Navigator.of(context).pop(server);
|
||||
} catch (error) {
|
||||
setState(() => _error = '$error');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
_addresses.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Widget _field(
|
||||
TextEditingController controller,
|
||||
String label, {
|
||||
required String key,
|
||||
bool multiline = false,
|
||||
}) {
|
||||
if (usesCupertinoHost(context)) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(label),
|
||||
const SizedBox(height: 8),
|
||||
CupertinoTextField(
|
||||
key: Key(key),
|
||||
controller: controller,
|
||||
placeholder: multiline ? 'wss://server.example/connect' : 'Home',
|
||||
minLines: multiline ? 3 : 1,
|
||||
maxLines: multiline ? null : 1,
|
||||
keyboardType: multiline
|
||||
? TextInputType.multiline
|
||||
: TextInputType.text,
|
||||
autocorrect: !multiline,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return TextField(
|
||||
key: Key(key),
|
||||
controller: controller,
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
minLines: multiline ? 3 : 1,
|
||||
maxLines: multiline ? null : 1,
|
||||
keyboardType: multiline ? TextInputType.multiline : TextInputType.text,
|
||||
autocorrect: !multiline,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final title = widget.server == null ? 'Add server' : 'Edit server';
|
||||
final save = cupertino
|
||||
? CupertinoButton.filled(
|
||||
onPressed: _save,
|
||||
child: const Text('Save server'),
|
||||
)
|
||||
: FilledButton(onPressed: _save, child: const Text('Save server'));
|
||||
final body = SafeArea(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
_field(_name, 'Server name', key: 'server-profile-name'),
|
||||
const SizedBox(height: 16),
|
||||
_field(
|
||||
_addresses,
|
||||
'Addresses, in preferred order',
|
||||
key: 'server-profile-addresses',
|
||||
multiline: true,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'One ws:// or wss:// address per line. The first is preferred; '
|
||||
'the others are backups for this same server, such as its Tailscale and LAN addresses.',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'Only group addresses you trust as the same server. They share its saved sign-in. '
|
||||
'ws:// is unencrypted; use it only on a trusted LAN/VPN.',
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Text(
|
||||
_error!,
|
||||
style: TextStyle(
|
||||
color: cupertino
|
||||
? CupertinoColors.systemRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Align(alignment: AlignmentDirectional.centerStart, child: save),
|
||||
],
|
||||
),
|
||||
);
|
||||
return cupertino
|
||||
? CupertinoPageScaffold(
|
||||
navigationBar: CupertinoNavigationBar(middle: Text(title)),
|
||||
child: body,
|
||||
)
|
||||
: Scaffold(
|
||||
appBar: AppBar(title: Text(title)),
|
||||
body: body,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/servers/server_catalog.dart';
|
||||
import '../../ui/adaptive/host.dart';
|
||||
import 'saved_server_editor.dart';
|
||||
import 'server_connections.dart';
|
||||
|
||||
class SavedServersSection extends StatelessWidget {
|
||||
const SavedServersSection({super.key, required this.connections});
|
||||
final ServerConnections connections;
|
||||
|
||||
Future<void> _edit(BuildContext context, [SavedServer? server]) async {
|
||||
final edited = await editSavedServer(context, server: server);
|
||||
if (edited != null) await connections.save(edited);
|
||||
}
|
||||
|
||||
Future<void> _remove(BuildContext context, SavedServer server) async {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final confirmed = cupertino
|
||||
? await showCupertinoDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => CupertinoAlertDialog(
|
||||
title: Text('Remove ${server.name}?'),
|
||||
content: const Text(
|
||||
'This removes the saved configuration, not data on the server.',
|
||||
),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
isDestructiveAction: true,
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('Remove'),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text('Remove ${server.name}?'),
|
||||
content: const Text(
|
||||
'This removes the saved configuration, not data on the server.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('Remove'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed == true) await connections.remove(server.id);
|
||||
}
|
||||
|
||||
Widget _button(BuildContext context, String label, VoidCallback? press) =>
|
||||
usesCupertinoHost(context)
|
||||
? CupertinoButton(onPressed: press, child: Text(label))
|
||||
: TextButton(onPressed: press, child: Text(label));
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: connections,
|
||||
builder: (context, _) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
for (final server in connections.catalog.servers) ...[
|
||||
Text(
|
||||
server.name,
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
if (server.id == connections.catalog.active?.id)
|
||||
const Text('Selected server'),
|
||||
for (final (index, address) in server.endpoints.indexed)
|
||||
Text('${index == 0 ? 'Preferred' : 'Backup $index'}: $address'),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
if (server.id != connections.catalog.active?.id)
|
||||
_button(
|
||||
context,
|
||||
'Use ${server.name}',
|
||||
connections.busy
|
||||
? null
|
||||
: () => unawaited(connections.select(server.id)),
|
||||
),
|
||||
_button(
|
||||
context,
|
||||
'Edit ${server.name}',
|
||||
connections.busy
|
||||
? null
|
||||
: () => unawaited(_edit(context, server)),
|
||||
),
|
||||
_button(
|
||||
context,
|
||||
'Remove ${server.name}',
|
||||
connections.busy
|
||||
? null
|
||||
: () => unawaited(_remove(context, server)),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: _button(
|
||||
context,
|
||||
'Add server',
|
||||
connections.busy ? null : () => unawaited(_edit(context)),
|
||||
),
|
||||
),
|
||||
if (connections.error != null)
|
||||
Text(
|
||||
connections.error!,
|
||||
style: TextStyle(
|
||||
color: usesCupertinoHost(context)
|
||||
? CupertinoColors.systemRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../core/servers/server_catalog.dart';
|
||||
import '../../core/servers/server_catalog_store.dart';
|
||||
|
||||
/// Saved configurations are committed before switching the app's connection.
|
||||
/// A failed save leaves the old selection and its live socket unchanged.
|
||||
class ServerConnections extends ChangeNotifier {
|
||||
ServerConnections({required this.store, required this.onSelected});
|
||||
|
||||
final ServerCatalogStore store;
|
||||
final Future<void> Function(SavedServer?) onSelected;
|
||||
ServerCatalog _catalog = ServerCatalog();
|
||||
bool _busy = false;
|
||||
String? _error;
|
||||
bool _disposed = false;
|
||||
|
||||
ServerCatalog get catalog => _catalog;
|
||||
bool get busy => _busy;
|
||||
String? get error => _error;
|
||||
|
||||
/// Browsers always connect to their page origin, even after Back or a failed
|
||||
/// cross-origin navigation. Do not label another saved profile as active.
|
||||
void alignBrowserOrigin(Uri endpoint) {
|
||||
String origin(Uri uri) =>
|
||||
uri.replace(scheme: uri.scheme == 'wss' ? 'https' : 'http').origin;
|
||||
final current = origin(endpoint);
|
||||
String? matched;
|
||||
for (final server in _catalog.servers) {
|
||||
if (server.endpoints.any((url) {
|
||||
final candidate = Uri.parse(url);
|
||||
return origin(candidate) == current &&
|
||||
candidate.path == endpoint.path &&
|
||||
candidate.query == endpoint.query;
|
||||
})) {
|
||||
matched = server.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
_catalog = ServerCatalog(servers: _catalog.servers, selectedId: matched);
|
||||
_notify();
|
||||
}
|
||||
|
||||
Future<bool> persist() => _change(() => _catalog, activate: false);
|
||||
|
||||
Future<void> load({String legacyEndpoint = ''}) async {
|
||||
try {
|
||||
final loaded = await store.load(legacyEndpoint: legacyEndpoint);
|
||||
if (!_disposed) _catalog = loaded;
|
||||
} catch (error) {
|
||||
if (!_disposed) _error = 'Saved servers could not be read: $error';
|
||||
}
|
||||
_notify();
|
||||
}
|
||||
|
||||
Future<bool> save(SavedServer server, {bool activate = true}) => _change(
|
||||
() {
|
||||
final next = _catalog.upsert(server);
|
||||
return _catalog.active == null ? next.select(server.id) : next;
|
||||
},
|
||||
activate:
|
||||
activate &&
|
||||
(_catalog.active?.id == server.id || _catalog.active == null),
|
||||
);
|
||||
|
||||
Future<bool> select(String id, {bool activate = true}) => _change(
|
||||
() => _catalog.select(id),
|
||||
activate: activate,
|
||||
rollbackSelection: true,
|
||||
);
|
||||
|
||||
Future<bool> remove(String id) =>
|
||||
_change(() => _catalog.remove(id), activate: _catalog.active?.id == id);
|
||||
|
||||
Future<bool> _change(
|
||||
ServerCatalog Function() change, {
|
||||
required bool activate,
|
||||
bool rollbackSelection = false,
|
||||
}) async {
|
||||
if (_busy || _disposed) return false;
|
||||
// A corrupt catalog is never silently replaced by an empty configuration.
|
||||
if (_error?.startsWith('Saved servers could not be read:') ?? false) {
|
||||
return false;
|
||||
}
|
||||
_busy = true;
|
||||
final previous = _catalog;
|
||||
_error = null;
|
||||
_notify();
|
||||
try {
|
||||
final next = change();
|
||||
if (!await store.save(next)) {
|
||||
throw StateError('The server configuration could not be saved.');
|
||||
}
|
||||
if (_disposed) return false;
|
||||
_catalog = next;
|
||||
_notify();
|
||||
if (activate) {
|
||||
try {
|
||||
await onSelected(next.active);
|
||||
} catch (_) {
|
||||
if (rollbackSelection && await store.save(previous) && !_disposed) {
|
||||
_catalog = previous;
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!_disposed) _error = '$error';
|
||||
return false;
|
||||
} finally {
|
||||
_busy = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -5,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
|
||||
|
||||
@@ -19,6 +19,9 @@ import 'settings_updates_section.dart';
|
||||
import '../updates/app_updates.dart';
|
||||
import 'settings_store.dart';
|
||||
import 'settings_templates_section.dart';
|
||||
import 'server_connections.dart';
|
||||
import 'saved_servers_section.dart';
|
||||
import 'managed_connection_section.dart';
|
||||
|
||||
/// The Settings destination: the server connection and the server-side
|
||||
/// workspace, in native Material (native platforms) or Cupertino (iOS) controls.
|
||||
@@ -41,6 +44,7 @@ class SettingsScreen extends StatefulWidget {
|
||||
this.notifications,
|
||||
this.showSignIn = false,
|
||||
this.showAndroidDownload = false,
|
||||
this.servers,
|
||||
});
|
||||
|
||||
final transport.PipelinesClient client;
|
||||
@@ -50,6 +54,7 @@ class SettingsScreen extends StatefulWidget {
|
||||
|
||||
/// A browser page links the Android app the server offers.
|
||||
final bool showAndroidDownload;
|
||||
final ServerConnections? servers;
|
||||
|
||||
/// A fixture/preview seed for the URL field. Persisted settings still load;
|
||||
/// this value takes precedence for the draft and is never written by itself.
|
||||
@@ -145,12 +150,24 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
if (widget.servers != null) ...[
|
||||
_SettingsSection(
|
||||
title: 'Servers',
|
||||
child: SavedServersSection(connections: widget.servers!),
|
||||
),
|
||||
const SizedBox(height: settingsSectionGap),
|
||||
],
|
||||
_SettingsSection(
|
||||
title: 'Connection',
|
||||
child: SettingsConnectionSection(
|
||||
controller: _controller,
|
||||
serverUrlField: _serverUrlField,
|
||||
),
|
||||
child: widget.servers != null
|
||||
? ManagedConnectionSection(
|
||||
client: widget.client,
|
||||
controller: _controller,
|
||||
)
|
||||
: SettingsConnectionSection(
|
||||
controller: _controller,
|
||||
serverUrlField: _serverUrlField,
|
||||
),
|
||||
),
|
||||
// A phone signs in at the web login; a browser has its own.
|
||||
if (widget.showSignIn) ...<Widget>[
|
||||
@@ -158,10 +175,18 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_SettingsSection(
|
||||
title: 'Sign in',
|
||||
child: SettingsSignInSection(
|
||||
endpoint: _controller.serverUrl,
|
||||
endpoint: widget.servers == null
|
||||
? _controller.serverUrl
|
||||
: widget.client.endpoint?.toString() ?? '',
|
||||
onChanged: () {
|
||||
final endpoint = widget.client.endpoint;
|
||||
if (endpoint != null) widget.client.connect(endpoint);
|
||||
if (endpoint != null) {
|
||||
widget.client.connectAny(
|
||||
widget.client.endpoints.isEmpty
|
||||
? [endpoint]
|
||||
: widget.client.endpoints,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -180,7 +205,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_SettingsSection(
|
||||
title: 'App updates',
|
||||
child: SettingsUpdatesSection(
|
||||
endpoint: _controller.serverUrl,
|
||||
endpoint: widget.servers == null
|
||||
? _controller.serverUrl
|
||||
: widget.client.endpoint?.toString() ?? '',
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../core/servers/server_scope.dart';
|
||||
|
||||
/// The app's own settings keys. They are deliberately independent of the legacy
|
||||
/// web/Android storage: no value is imported, migrated or written under an old
|
||||
@@ -31,7 +32,10 @@ abstract interface class SettingsStore {
|
||||
/// return false instead of throwing, letting the screen keep the in-memory
|
||||
/// value while saying plainly that it was not stored.
|
||||
class SharedPreferencesSettingsStore implements SettingsStore {
|
||||
const SharedPreferencesSettingsStore();
|
||||
const SharedPreferencesSettingsStore({this.serverId = ''});
|
||||
final String serverId;
|
||||
String get _workspaceKey =>
|
||||
scopedServerKey(settingsWorkspaceKey, serverStorageScope(serverId));
|
||||
|
||||
Future<SharedPreferences?> _preferences() async {
|
||||
try {
|
||||
@@ -48,7 +52,7 @@ class SharedPreferencesSettingsStore implements SettingsStore {
|
||||
try {
|
||||
return SettingsValues(
|
||||
serverUrl: preferences.getString(settingsServerUrlKey) ?? '',
|
||||
workspace: preferences.getString(settingsWorkspaceKey) ?? '',
|
||||
workspace: preferences.getString(_workspaceKey) ?? '',
|
||||
);
|
||||
} catch (_) {
|
||||
return const SettingsValues();
|
||||
@@ -71,7 +75,7 @@ class SharedPreferencesSettingsStore implements SettingsStore {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return false;
|
||||
try {
|
||||
return await preferences.setString(settingsWorkspaceKey, value.trim());
|
||||
return await preferences.setString(_workspaceKey, value.trim());
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user