diff --git a/app/lib/features/settings/default_endpoint.dart b/app/lib/features/settings/default_endpoint.dart new file mode 100644 index 00000000..993bc713 --- /dev/null +++ b/app/lib/features/settings/default_endpoint.dart @@ -0,0 +1,24 @@ +import 'package:flutter/foundation.dart'; + +/// The websocket endpoint the web build offers by default: the page's own +/// origin, upgraded to ws/wss, at the server's `/connect` path. +/// +/// The web client is served by a same-origin proxy, so this is a configurable +/// starting value, not a baked host: it is derived from the page the operator +/// actually loaded. Native builds have no such origin and start blank, so no +/// server host or production endpoint is compiled into the app. +/// +/// `web` and `base` are injectable only so the rule can be tested without a +/// browser; production callers use the platform defaults. +String defaultServerUrl({bool? web, Uri? base}) { + if (!(web ?? kIsWeb)) return ''; + final origin = base ?? Uri.base; + if (origin.host.isEmpty) return ''; + final secure = origin.scheme.toLowerCase() == 'https'; + return Uri( + scheme: secure ? 'wss' : 'ws', + host: origin.host, + port: origin.hasPort ? origin.port : null, + path: '/connect', + ).toString(); +} diff --git a/app/lib/features/settings/settings.dart b/app/lib/features/settings/settings.dart new file mode 100644 index 00000000..06abe08e --- /dev/null +++ b/app/lib/features/settings/settings.dart @@ -0,0 +1,12 @@ +/// Public API the manager needs to register the Settings destination. +/// +/// The screen receives the shared `PipelinesClient`; it never creates, replaces +/// or disposes one. `SettingsController` is exposed for previews and focused +/// tests, not for the shell to construct separately. +library; + +export 'default_endpoint.dart'; +export 'settings_controller.dart' show PingCallback, SettingsController; +export 'settings_copy.dart'; +export 'settings_screen.dart'; +export 'settings_store.dart'; diff --git a/app/lib/features/settings/settings_controller.dart b/app/lib/features/settings/settings_controller.dart new file mode 100644 index 00000000..bbbebdd5 --- /dev/null +++ b/app/lib/features/settings/settings_controller.dart @@ -0,0 +1,278 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../core/transport/pipelines_client.dart' as transport; +import '../../core/transport/server_url.dart'; +import 'settings_copy.dart'; +import 'settings_store.dart'; + +/// The ping request the status card makes once per connection. The default is +/// the shared client's own `ping` request; tests inject a recorded callback. +typedef PingCallback = Future> Function(); + +/// Owns the Settings screen's draft text, validation and the actions that drive +/// the shared [transport.PipelinesClient]. +/// +/// The feature never owns the client: it subscribes to the client's state and +/// calls connect/disconnect, but never calls `dispose()` on it, and it never +/// opens a connection by itself. One controller is created per screen, not per +/// rebuild, so rebuilding Settings cannot start a second connection. +class SettingsController extends ChangeNotifier { + SettingsController({ + required this.client, + required this.store, + this.initialEndpoint, + String defaultEndpoint = '', + PingCallback? ping, + }) : _defaultServerUrl = defaultEndpoint, + _ping = ping ?? (() => client.call('ping')), + _connection = client.state { + _lastKind = _connection.kind; + _subscription = client.states.listen(_onConnectionState); + } + + final transport.PipelinesClient client; + final SettingsStore store; + final Uri? initialEndpoint; + final String _defaultServerUrl; + final PingCallback _ping; + + late final StreamSubscription _subscription; + + transport.ConnectionState _connection; + transport.ConnectionKind _lastKind = transport.ConnectionKind.idle; + String _serverUrl = ''; + String _urlError = ''; + String _workspaceDraft = ''; + String _savedWorkspace = ''; + String _workspaceSaveError = ''; + String _endpointSaveError = ''; + String _actionError = ''; + String _buildVersion = ''; + String _buildCommit = ''; + String _serverTime = ''; + String _pingError = ''; + bool _pingInFlight = false; + bool _pingRequestedForConnected = false; + int _pingToken = 0; + bool _initialized = false; + bool _serverUrlEdited = false; + bool _workspaceEdited = false; + bool _disposed = false; + + transport.ConnectionState get connection => _connection; + String get serverUrl => _serverUrl; + String get urlError => _urlError; + String get workspaceDraft => _workspaceDraft; + String get savedWorkspace => _savedWorkspace; + String get workspaceError => validateWorkspacePath(_workspaceDraft) ?? ''; + String get workspaceSaveError => _workspaceSaveError; + String get endpointSaveError => _endpointSaveError; + String get actionError => _actionError; + String get buildVersion => _buildVersion; + String get buildCommit => _buildCommit; + String get serverTime => _serverTime; + String get pingError => _pingError; + bool get pingInFlight => _pingInFlight; + + bool get connectionActive => + _connection.kind == transport.ConnectionKind.connected || + _connection.kind == transport.ConnectionKind.connecting; + + String get primaryActionLabel => connectionActive ? 'Disconnect' : 'Connect'; + String get secondaryActionLabel => connectionActive ? 'Connect' : 'Reconnect'; + + List get connectionLines => connectionCardLines( + _connection, + buildVersion: _buildVersion, + buildCommit: _buildCommit, + serverTime: _serverTime, + pingError: _pingError, + pingInFlight: _pingInFlight, + ); + + /// Reads the feature's own persisted values once. A draft the operator has + /// already typed into is never overwritten by the asynchronous read. + Future initialize() async { + if (_initialized) return; + _initialized = true; + final values = await store.load(); + if (_disposed) return; + if (!_serverUrlEdited) { + final saved = values.serverUrl.trim(); + _serverUrl = + initialEndpoint?.toString() ?? + (saved.isNotEmpty ? saved : _defaultServerUrl); + } + if (!_workspaceEdited) { + _workspaceDraft = values.workspace; + _savedWorkspace = values.workspace.trim(); + } + // The screen may be opened while the shared client is already connected; + // find out what that server is. This never opens a connection. + if (_connection.kind == transport.ConnectionKind.connected) _requestPing(); + _notify(); + } + + void updateServerUrl(String value) { + _serverUrlEdited = true; + _serverUrl = value; + _urlError = ''; + _actionError = ''; + _notify(); + } + + void updateWorkspace(String value) { + _workspaceEdited = true; + _workspaceDraft = value; + _workspaceSaveError = ''; + _notify(); + } + + /// Validates the draft, persists the endpoint and connects the shared client. + /// An invalid draft names the problem on the field and touches no socket. + Future connect() async { + final raw = _serverUrl; + String wsUrl; + try { + wsUrl = ServerUrl.validate(raw).wsUrl; + } on FormatException catch (error) { + _urlError = error.message.toString(); + _notify(); + return; + } + _urlError = ''; + _actionError = ''; + if (_serverUrl != wsUrl) _serverUrl = wsUrl; + final stored = await store.saveServerUrl(wsUrl); + if (_disposed) return; + _endpointSaveError = stored + ? '' + : 'The server URL could not be saved; it applies to this session only.'; + _notify(); + try { + await client.connect(Uri.parse(wsUrl)); + } catch (error) { + if (_disposed) return; + _actionError = 'Could not connect: ${_describe(error)}'; + _notify(); + } + } + + /// Re-opening the validated endpoint is the same client operation as + /// connecting; only the label differs, matching the web/Android settings. + Future reconnect() => connect(); + + /// Closes this screen's connection through the shared client. It never + /// disposes the client: other features keep using the same instance. + Future disconnect() async { + _actionError = ''; + try { + await client.disconnect(); + } catch (error) { + if (_disposed) return; + _actionError = 'Could not disconnect: ${_describe(error)}'; + } + if (!_disposed) _notify(); + } + + /// Persists the trimmed absolute workspace. Only a stored value updates the + /// `Saved workspace:` line; a failed write says so instead of claiming one. + Future saveWorkspace() async { + if (!canSaveWorkspace(_workspaceDraft)) { + _notify(); + return; + } + final value = _workspaceDraft.trim(); + final stored = await store.saveWorkspace(value); + if (_disposed) return; + _workspaceDraft = value; + if (stored) { + _savedWorkspace = value; + _workspaceSaveError = ''; + } else { + _workspaceSaveError = + 'The workspace could not be saved; it is not stored on this device.'; + } + _notify(); + } + + void _onConnectionState(transport.ConnectionState state) { + if (_disposed) return; + final previous = _lastKind; + _connection = state; + _lastKind = state.kind; + if (state.kind == transport.ConnectionKind.connected) { + _requestPing(); + } else { + // Never keep one server's build/time while another connection, or no + // connection, is being shown. + _clearPingDetails(); + if (previous == transport.ConnectionKind.connected) _pingToken++; + } + _notify(); + } + + void _requestPing() { + if (_disposed || _pingRequestedForConnected) return; + _pingRequestedForConnected = true; + _pingError = ''; + _pingInFlight = true; + final token = ++_pingToken; + unawaited(_runPing(token)); + } + + Future _runPing(int token) async { + try { + final reply = await _ping(); + if (!_isCurrentPing(token)) return; + final build = reply['build']; + _buildVersion = build is Map + ? '${build['version'] ?? ''}'.trim() + : '${build ?? ''}'.trim(); + _buildCommit = build is Map ? '${build['commit'] ?? ''}'.trim() : ''; + _serverTime = '${reply['time'] ?? ''}'.trim(); + _pingError = ''; + } catch (error) { + if (!_isCurrentPing(token)) return; + _pingError = 'Server details unavailable: ${_describe(error)}'; + } finally { + if (_isCurrentPing(token)) { + _pingInFlight = false; + _notify(); + } + } + } + + bool _isCurrentPing(int token) => + !_disposed && token == _pingToken && _pingRequestedForConnected; + + void _clearPingDetails() { + _pingRequestedForConnected = false; + _pingInFlight = false; + _pingError = ''; + _buildVersion = ''; + _buildCommit = ''; + _serverTime = ''; + } + + String _describe(Object error) { + final text = error.toString().trim(); + return text.isEmpty ? 'unknown error' : text; + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + if (_disposed) return; + _disposed = true; + _pingToken++; + _subscription.cancel(); + // The shared client outlives this screen; it is deliberately not disposed. + super.dispose(); + } +} diff --git a/app/lib/features/settings/settings_controls.dart b/app/lib/features/settings/settings_controls.dart new file mode 100644 index 00000000..d82f703d --- /dev/null +++ b/app/lib/features/settings/settings_controls.dart @@ -0,0 +1,209 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'settings_layout.dart'; + +/// Whether the current platform expects Cupertino controls. The app's theme is +/// the single source of the platform answer, so dark mode and platform overrides +/// stay consistent with the rest of the shell. +bool usesCupertinoControls(BuildContext context) => + Theme.of(context).platform == TargetPlatform.iOS; + +/// A native text field with a label and one supporting line. Both platforms lay +/// the label out as wrapping text above the field; Material uses an outlined +/// [TextField] and iOS a [CupertinoTextField]. Labels and helper/error copy are +/// never line-capped, so large text cannot truncate them. No font sizes, heights +/// or colours are fixed here. +class SettingsTextField extends StatelessWidget { + const SettingsTextField({ + super.key, + required this.controller, + required this.label, + required this.placeholder, + required this.helper, + required this.onChanged, + this.error = '', + }); + + final TextEditingController controller; + final String label; + final String placeholder; + final String helper; + final ValueChanged onChanged; + final String error; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final hasError = error.trim().isNotEmpty; + // The label is laid out as normal wrapping text on both platforms. A + // Material floating label is single-line and ellipsizes the workspace label + // at narrow widths or large text, dropping required words. + final labelWidget = ExcludeSemantics( + child: Text(label, style: theme.textTheme.titleSmall), + ); + if (!usesCupertinoControls(context)) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + labelWidget, + const SizedBox(height: settingsFieldGap), + Semantics( + label: label, + child: TextField( + controller: controller, + onChanged: onChanged, + keyboardType: TextInputType.url, + autocorrect: false, + enableSuggestions: false, + textInputAction: TextInputAction.done, + decoration: InputDecoration( + hintText: placeholder, + // `helperText`/`errorText` single-line-ellipsize unless capped + // by `helperMaxLines`/`errorMaxLines`. Widgets wrap with no line + // cap, so the full instructions stay readable at 2x. + helper: hasError + ? null + : Text( + helper, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + error: hasError + ? Text( + error, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ) + : null, + border: const OutlineInputBorder(), + ), + ), + ), + ], + ); + } + final supportingColor = hasError + ? theme.colorScheme.error + : theme.colorScheme.onSurfaceVariant; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + labelWidget, + const SizedBox(height: settingsFieldGap), + Semantics( + label: label, + child: CupertinoTextField( + controller: controller, + onChanged: onChanged, + placeholder: placeholder, + keyboardType: TextInputType.url, + autocorrect: false, + enableSuggestions: false, + clearButtonMode: OverlayVisibilityMode.editing, + textInputAction: TextInputAction.done, + ), + ), + const SizedBox(height: settingsFieldGap), + Text( + hasError ? error : helper, + style: theme.textTheme.bodySmall?.copyWith(color: supportingColor), + ), + ], + ); + } +} + +/// The filled primary and outlined secondary settings actions. Buttons wrap on +/// a narrow window (or with large text) instead of overflowing. +class SettingsActions extends StatelessWidget { + const SettingsActions({ + super.key, + required this.primaryLabel, + required this.secondaryLabel, + required this.onPrimary, + required this.onSecondary, + this.primaryKey, + this.secondaryKey, + }); + + final String primaryLabel; + final String secondaryLabel; + final VoidCallback onPrimary; + final VoidCallback onSecondary; + final Key? primaryKey; + final Key? secondaryKey; + + @override + Widget build(BuildContext context) { + if (usesCupertinoControls(context)) { + return Wrap( + spacing: settingsControlGap, + runSpacing: settingsControlGap, + children: [ + CupertinoButton.filled( + key: primaryKey, + onPressed: onPrimary, + child: Text(primaryLabel), + ), + CupertinoButton( + key: secondaryKey, + onPressed: onSecondary, + child: Text(secondaryLabel), + ), + ], + ); + } + return Wrap( + spacing: settingsControlGap, + runSpacing: settingsControlGap, + children: [ + FilledButton( + key: primaryKey, + onPressed: onPrimary, + child: Text(primaryLabel), + ), + OutlinedButton( + key: secondaryKey, + onPressed: onSecondary, + child: Text(secondaryLabel), + ), + ], + ); + } +} + +/// One standard settings card: a Material [Card] or an inset-grouped Cupertino +/// section, both using theme surfaces and native corner/padding defaults. +class SettingsCard extends StatelessWidget { + const SettingsCard({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + if (usesCupertinoControls(context)) { + return CupertinoListSection.insetGrouped( + margin: EdgeInsets.zero, + children: [ + SizedBox( + width: double.infinity, + child: Padding( + padding: const EdgeInsets.all(settingsCardPadding), + child: child, + ), + ), + ], + ); + } + return Card( + margin: EdgeInsets.zero, + child: Padding( + padding: const EdgeInsets.all(settingsCardPadding), + child: child, + ), + ); + } +} diff --git a/app/lib/features/settings/settings_copy.dart b/app/lib/features/settings/settings_copy.dart new file mode 100644 index 00000000..37c6c29f --- /dev/null +++ b/app/lib/features/settings/settings_copy.dart @@ -0,0 +1,113 @@ +import '../../core/transport/pipelines_client.dart' as transport; + +/// Field and explanatory copy, matching the current web Settings destination +/// (web/src/settings.js) and the Android SettingsScreen it quotes. +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.'; + +const String workspacePlaceholder = '/Users/you/repos/pipelines'; + +const String workspaceHelper = + 'An absolute directory that already exists on the execution server. For ' + 'Docker, mount the host directory at the same absolute path with its ' + "owner's UID/GID. This is not the phone's storage."; + +const String workspacePathError = + 'The workspace must be an absolute path that exists on the execution ' + 'server.'; + +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.'; + +/// 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 +/// path, so the phone's filesystem is irrelevant. +String? validateWorkspacePath(String value) { + final trimmed = value.trim(); + if (trimmed.isEmpty) return null; + if (!trimmed.startsWith('/')) return workspacePathError; + return null; +} + +/// Saving requires a real absolute path, not just "no error": the web Settings +/// page deliberately refuses a blank field and records that strictness. +bool canSaveWorkspace(String value) { + final trimmed = value.trim(); + return trimmed.isNotEmpty && validateWorkspacePath(trimmed) == null; +} + +/// The persisted workspace line. An absent value is named, never rendered as a +/// zero or an empty gap. +String savedWorkspaceLine(String value) { + final trimmed = value.trim(); + return 'Saved workspace: ${trimmed.isEmpty ? '(none)' : trimmed}'; +} + +/// The exact shared connecting sentence used by the banner and status card. +String connectingLabel(int attempt) => 'Connecting (attempt $attempt)\u2026'; + +/// `Server build {version} ({commit})`, with whichever parts the ping reported. +String serverBuildLabel({String? version, String? commit}) { + final v = (version ?? '').trim(); + final c = (commit ?? '').trim(); + final parts = [if (v.isNotEmpty) v, if (c.isNotEmpty) '($c)']; + if (parts.isEmpty) return ''; + return 'Server build ${parts.join(' ')}'; +} + +/// The pending sentence shown between `Connected` and the ping reply. It is a +/// request in flight, not a missing value. +const String serverDetailsPending = 'Loading server details\u2026'; + +/// The status card's lines in the web/Android order. While the ping is in +/// flight the card says it is loading. A completed reply names the build and +/// time, saying "unavailable" only when that reply omitted them; a failed ping +/// is one explicit line instead of two "unavailable" lines plus the error. +List connectionCardLines( + transport.ConnectionState state, { + String? buildVersion, + String? buildCommit, + String? serverTime, + String pingError = '', + bool pingInFlight = false, +}) { + switch (state.kind) { + case transport.ConnectionKind.connected: + final build = serverBuildLabel( + version: buildVersion, + commit: buildCommit, + ); + final time = (serverTime ?? '').trim(); + final failure = pingError.trim(); + if (pingInFlight && build.isEmpty && time.isEmpty && failure.isEmpty) { + return const ['Connected', serverDetailsPending]; + } + if (failure.isNotEmpty && build.isEmpty && time.isEmpty) { + return ['Connected', failure]; + } + return [ + 'Connected', + build.isEmpty ? 'Server build unavailable' : build, + time.isEmpty ? 'Server time unavailable' : 'Server time $time', + if (failure.isNotEmpty) failure, + ]; + case transport.ConnectionKind.connecting: + return [connectingLabel(state.attempt)]; + case transport.ConnectionKind.disconnected: + final reason = state.reason.trim(); + return [ + 'Disconnected', + if (reason.isNotEmpty) reason, + if (state.retrying) 'Retrying with backoff\u2026', + ]; + case transport.ConnectionKind.idle: + return const ['Not connected']; + } +} diff --git a/app/lib/features/settings/settings_keys.dart b/app/lib/features/settings/settings_keys.dart new file mode 100644 index 00000000..47575721 --- /dev/null +++ b/app/lib/features/settings/settings_keys.dart @@ -0,0 +1,12 @@ +import 'package:flutter/material.dart'; + +/// The keys the screen and its widget tests share. They name controls, not +/// dimensions or copy. +abstract final class SettingsKeys { + static const serverUrl = ValueKey('settings.serverUrl'); + static const connect = ValueKey('settings.connect'); + static const disconnect = ValueKey('settings.disconnect'); + static const reconnect = ValueKey('settings.reconnect'); + static const workspace = ValueKey('settings.workspace'); + static const saveWorkspace = ValueKey('settings.saveWorkspace'); +} diff --git a/app/lib/features/settings/settings_layout.dart b/app/lib/features/settings/settings_layout.dart new file mode 100644 index 00000000..dd9a59cf --- /dev/null +++ b/app/lib/features/settings/settings_layout.dart @@ -0,0 +1,27 @@ +/// The one place the Settings screen keeps its necessary layout constraints. +/// +/// Everything else (control heights, font sizes, colours, button padding) comes +/// from the active Material or Cupertino theme, so text scaling and platform +/// defaults are never overridden here. +library; + +/// A comfortable reading width on wide windows; the body is centred inside it. +const double settingsContentMaxWidth = 720; + +/// Space between the Settings sections. +const double settingsSectionGap = 24; + +/// Space between a section title and its controls. +const double settingsTitleGap = 12; + +/// Space between a field and its supporting text. +const double settingsFieldGap = 6; + +/// Space between wrapped action buttons. +const double settingsControlGap = 8; + +/// Padding around the page body on narrow windows. +const double settingsPagePadding = 16; + +/// Padding inside a standard Material card / Cupertino inset row. +const double settingsCardPadding = 16; diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart new file mode 100644 index 00000000..425fccda --- /dev/null +++ b/app/lib/features/settings/settings_screen.dart @@ -0,0 +1,148 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../core/transport/pipelines_client.dart' as transport; +import 'default_endpoint.dart'; +import 'settings_controller.dart'; +import 'settings_controls.dart'; +import 'settings_layout.dart'; +import 'settings_sections.dart'; +import 'settings_store.dart'; + +/// The Settings destination: the server connection and the server-side +/// workspace, in native Material (native platforms) or Cupertino (iOS) controls. +/// +/// The shared [transport.PipelinesClient] is supplied by the shell. This screen +/// subscribes to it, connects/disconnects it and pings it on connected, but it +/// never opens a connection on its own and never disposes the client. One +/// controller is created in [initState], so rebuilding the screen cannot start +/// a second connection. +class SettingsScreen extends StatefulWidget { + const SettingsScreen({ + super.key, + required this.client, + this.initialEndpoint, + this.store, + this.ping, + }); + + final transport.PipelinesClient client; + + /// 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. + final Uri? initialEndpoint; + + /// The feature's own persistence. Defaults to the `pipelines.next` keys. + final SettingsStore? store; + + /// Test seam for the exact ping request. Production uses `client.call('ping')`. + final PingCallback? ping; + + @override + State createState() => _SettingsScreenState(); +} + +class _SettingsScreenState extends State { + final TextEditingController _serverUrlField = TextEditingController(); + final TextEditingController _workspaceField = TextEditingController(); + late final SettingsController _controller; + + @override + void initState() { + super.initState(); + _controller = SettingsController( + client: widget.client, + store: widget.store ?? const SharedPreferencesSettingsStore(), + initialEndpoint: widget.initialEndpoint, + defaultEndpoint: defaultServerUrl(), + ping: widget.ping, + ); + _controller.addListener(_onSettingsChanged); + unawaited(_controller.initialize()); + } + + void _onSettingsChanged() { + if (!mounted) return; + _syncField(_serverUrlField, _controller.serverUrl); + _syncField(_workspaceField, _controller.workspaceDraft); + setState(() {}); + } + + /// Follow the controller's value (a restored value or the normalised URL) + /// without disturbing a field the operator is already typing in. + void _syncField(TextEditingController field, String value) { + if (field.text == value) return; + field.value = TextEditingValue( + text: value, + selection: TextSelection.collapsed(offset: value.length), + ); + } + + @override + void dispose() { + _controller.removeListener(_onSettingsChanged); + _controller.dispose(); + _serverUrlField.dispose(); + _workspaceField.dispose(); + // The shared client is owned by the shell and deliberately outlives this + // screen, so it is not disposed here. + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final content = SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(settingsPagePadding), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints( + maxWidth: settingsContentMaxWidth, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const _SectionTitle('Connection'), + const SizedBox(height: settingsTitleGap), + SettingsConnectionSection( + controller: _controller, + serverUrlField: _serverUrlField, + ), + const SizedBox(height: settingsSectionGap), + const _SectionTitle('Workspace'), + const SizedBox(height: settingsTitleGap), + SettingsWorkspaceSection( + controller: _controller, + workspaceField: _workspaceField, + ), + ], + ), + ), + ), + ), + ); + if (usesCupertinoControls(context)) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Settings')), + child: content, + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Settings')), + body: content, + ); + } +} + +class _SectionTitle extends StatelessWidget { + const _SectionTitle(this.title); + + final String title; + + @override + Widget build(BuildContext context) { + return Text(title, style: Theme.of(context).textTheme.titleMedium); + } +} diff --git a/app/lib/features/settings/settings_sections.dart b/app/lib/features/settings/settings_sections.dart new file mode 100644 index 00000000..270fcb40 --- /dev/null +++ b/app/lib/features/settings/settings_sections.dart @@ -0,0 +1,210 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../core/transport/pipelines_client.dart' as transport; +import 'settings_controller.dart'; +import 'settings_controls.dart'; +import 'settings_copy.dart'; +import 'settings_keys.dart'; +import 'settings_trust_warning.dart'; +import 'settings_layout.dart'; + +/// Connection controls: the editable endpoint, the truthful connection card and +/// the trusted-network warning. Every action goes through the shared client the +/// controller was given; nothing here opens a second connection. +class SettingsConnectionSection extends StatelessWidget { + const SettingsConnectionSection({ + super.key, + required this.controller, + required this.serverUrlField, + }); + + final SettingsController controller; + final TextEditingController serverUrlField; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SettingsTextField( + controller: serverUrlField, + key: SettingsKeys.serverUrl, + label: 'Server URL', + placeholder: serverUrlPlaceholder, + helper: serverUrlHelper, + error: controller.urlError, + onChanged: controller.updateServerUrl, + ), + const SizedBox(height: settingsTitleGap), + SettingsActions( + primaryLabel: controller.primaryActionLabel, + secondaryLabel: controller.secondaryActionLabel, + primaryKey: controller.connectionActive + ? SettingsKeys.disconnect + : SettingsKeys.connect, + secondaryKey: controller.connectionActive + ? SettingsKeys.connect + : SettingsKeys.reconnect, + onPrimary: () => unawaited( + controller.connectionActive + ? controller.disconnect() + : controller.connect(), + ), + onSecondary: () => unawaited( + controller.connectionActive + ? controller.connect() + : controller.reconnect(), + ), + ), + if (controller.endpointSaveError.isNotEmpty) ...[ + const SizedBox(height: settingsFieldGap), + Text( + controller.endpointSaveError, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + ], + if (controller.actionError.isNotEmpty) ...[ + const SizedBox(height: settingsFieldGap), + Text( + controller.actionError, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + ], + const SizedBox(height: settingsTitleGap), + SettingsStatusCard(controller: controller), + const SizedBox(height: settingsTitleGap), + const SettingsTrustWarning(), + ], + ); + } +} + +/// The status card's first line is the state; the remaining lines are the +/// build/time/reason/backoff facts. Missing ping values stay explicit. +class SettingsStatusCard extends StatelessWidget { + const SettingsStatusCard({super.key, required this.controller}); + + final SettingsController controller; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final state = controller.connection; + final lines = controller.connectionLines; + final title = lines.isEmpty ? '' : lines.first; + final details = lines.length > 1 ? lines.sublist(1) : const []; + final titleColor = switch (state.kind) { + transport.ConnectionKind.connected => theme.colorScheme.primary, + transport.ConnectionKind.disconnected => theme.colorScheme.error, + _ => theme.colorScheme.onSurface, + }; + final titleWidget = Text( + title, + style: theme.textTheme.titleMedium?.copyWith(color: titleColor), + ); + return SettingsCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (state.kind == transport.ConnectionKind.connecting) + Row( + children: [ + if (usesCupertinoControls(context)) + const CupertinoActivityIndicator() + else + const CircularProgressIndicator(strokeWidth: 2), + const SizedBox(width: settingsControlGap), + Expanded(child: titleWidget), + ], + ) + else + titleWidget, + for (final line in details) ...[ + const SizedBox(height: settingsFieldGap), + Text( + line, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ], + ), + ); + } +} + +/// Workspace controls. The path is resolved by the execution server, and the +/// helper says so explicitly; an empty saved value is named "(none)". +class SettingsWorkspaceSection extends StatelessWidget { + const SettingsWorkspaceSection({ + super.key, + required this.controller, + required this.workspaceField, + }); + + final SettingsController controller; + final TextEditingController workspaceField; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final saveError = controller.workspaceSaveError; + final canSave = canSaveWorkspace(controller.workspaceDraft); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SettingsTextField( + controller: workspaceField, + key: SettingsKeys.workspace, + label: 'Workspace path (on the server)', + placeholder: workspacePlaceholder, + helper: workspaceHelper, + error: controller.workspaceError, + onChanged: controller.updateWorkspace, + ), + const SizedBox(height: settingsTitleGap), + Align( + alignment: AlignmentDirectional.centerStart, + child: usesCupertinoControls(context) + ? CupertinoButton.filled( + key: SettingsKeys.saveWorkspace, + onPressed: canSave + ? () => unawaited(controller.saveWorkspace()) + : null, + child: const Text('Save workspace'), + ) + : FilledButton( + key: SettingsKeys.saveWorkspace, + onPressed: canSave + ? () => unawaited(controller.saveWorkspace()) + : null, + child: const Text('Save workspace'), + ), + ), + const SizedBox(height: settingsFieldGap), + Text( + savedWorkspaceLine(controller.savedWorkspace), + style: theme.textTheme.bodyMedium, + ), + if (saveError.isNotEmpty) ...[ + const SizedBox(height: settingsFieldGap), + Text( + saveError, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + ], + ], + ); + } +} diff --git a/app/lib/features/settings/settings_store.dart b/app/lib/features/settings/settings_store.dart new file mode 100644 index 00000000..84f2562e --- /dev/null +++ b/app/lib/features/settings/settings_store.dart @@ -0,0 +1,107 @@ +import 'package:shared_preferences/shared_preferences.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 +/// key, and nothing but the endpoint and the server workspace is persisted. +const String settingsServerUrlKey = 'pipelines.next.serverUrl.v1'; +const String settingsWorkspaceKey = 'pipelines.next.workspace.v1'; + +/// The persisted settings, read as a pair. Both values are trimmed strings; an +/// absent or unreadable value is empty rather than an error. +class SettingsValues { + const SettingsValues({this.serverUrl = '', this.workspace = ''}); + + final String serverUrl; + final String workspace; +} + +/// The persistence seam used by the screen and its tests. Saves report whether +/// the value is actually stored, so the UI never claims a save that failed. +abstract interface class SettingsStore { + Future load(); + + Future saveServerUrl(String value); + + Future saveWorkspace(String value); +} + +/// `shared_preferences`-backed storage under the `pipelines.next` keys. +/// +/// Reads are tolerant (an unavailable store means "nothing saved yet"). Saves +/// 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(); + + Future _preferences() async { + try { + return await SharedPreferences.getInstance(); + } catch (_) { + return null; + } + } + + @override + Future load() async { + final preferences = await _preferences(); + if (preferences == null) return const SettingsValues(); + try { + return SettingsValues( + serverUrl: preferences.getString(settingsServerUrlKey) ?? '', + workspace: preferences.getString(settingsWorkspaceKey) ?? '', + ); + } catch (_) { + return const SettingsValues(); + } + } + + @override + Future saveServerUrl(String value) async { + final preferences = await _preferences(); + if (preferences == null) return false; + try { + return await preferences.setString(settingsServerUrlKey, value.trim()); + } catch (_) { + return false; + } + } + + @override + Future saveWorkspace(String value) async { + final preferences = await _preferences(); + if (preferences == null) return false; + try { + return await preferences.setString(settingsWorkspaceKey, value.trim()); + } catch (_) { + return false; + } + } +} + +/// An in-memory store for previews and tests. It never touches the platform +/// store, so no production preference can be mutated by a fixture. +class MemorySettingsStore implements SettingsStore { + MemorySettingsStore({this.serverUrl = '', this.workspace = ''}); + + String serverUrl; + String workspace; + bool failSaves = false; + + @override + Future load() async => + SettingsValues(serverUrl: serverUrl, workspace: workspace); + + @override + Future saveServerUrl(String value) async { + if (failSaves) return false; + serverUrl = value.trim(); + return true; + } + + @override + Future saveWorkspace(String value) async { + if (failSaves) return false; + workspace = value.trim(); + return true; + } +} diff --git a/app/lib/features/settings/settings_trust_warning.dart b/app/lib/features/settings/settings_trust_warning.dart new file mode 100644 index 00000000..d3149b72 --- /dev/null +++ b/app/lib/features/settings/settings_trust_warning.dart @@ -0,0 +1,49 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'settings_controls.dart'; +import 'settings_copy.dart'; +import 'settings_layout.dart'; + +/// The trusted-network warning, using the app's exact web/Android copy. It is a +/// card, not a dialog: no confirmation is required to read it. +class SettingsTrustWarning extends StatelessWidget { + const SettingsTrustWarning({super.key}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final icon = usesCupertinoControls(context) + ? CupertinoIcons.exclamationmark_triangle + : Icons.warning_amber_rounded; + return SettingsCard( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, color: theme.colorScheme.error), + const SizedBox(width: settingsControlGap), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + trustTitle, + style: theme.textTheme.titleSmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + const SizedBox(height: settingsFieldGap), + Text( + trustBody, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/app/notes/N1.md b/app/notes/N1.md new file mode 100644 index 00000000..194247de --- /dev/null +++ b/app/notes/N1.md @@ -0,0 +1,130 @@ +# N1 Settings + +The Settings destination for the Flutter client: server connection and the +server-side workspace, in native Material controls and Cupertino controls on iOS. + +## Files + +- `lib/features/settings/settings_screen.dart` — `SettingsScreen`. +- `lib/features/settings/settings_controller.dart` — draft/validation, shared + client actions, ping-on-connected, workspace persistence, dispose ownership. +- `lib/features/settings/settings_store.dart` — `SettingsStore`, + `SharedPreferencesSettingsStore`, `MemorySettingsStore`. +- `lib/features/settings/settings_copy.dart` — the web/Android words, workspace + validation, connection-card lines. +- `lib/features/settings/default_endpoint.dart` — same-origin web default. +- `lib/features/settings/settings_controls.dart`, `settings_sections.dart`, + `settings_trust_warning.dart`, `settings_layout.dart`, `settings_keys.dart`. +- `lib/features/settings/settings.dart` — public barrel for manager registration. +- `test/features/settings/*` — copy, persistence, controller and widget tests. +- `tool/settings_probe.dart`, `tool/settings_probe_server.dart`, + `tool/settings_probe_capture.dart` — isolated browser fixture/capture entry. + +## Manager registration + +```dart +import 'package:pipelines_app/features/settings/settings.dart'; + +SettingsScreen(client: sharedPipelinesClient) +// optional: initialEndpoint: Uri?, store: SettingsStore?, ping: PingCallback? +``` + +`SettingsScreen` takes the shell's single `PipelinesClient`. It subscribes to +`client.states`, sends `ping` once per connected transition (plus once when the +screen opens against an already-connected client), and offers Connect / +Disconnect / Reconnect. It never calls `client.dispose()` and never opens a +connection on construction, so registering/rebuilding the screen cannot start a +second socket or tear down another feature's connection. + +While connected it shows `Server build {version} ({commit})` and +`Server time {time}` from the ping reply. Until that reply arrives the card says +`Loading server details…`, so a request in flight is never reported as an +unavailable value. Only a completed reply that omits a field renders `Server +build unavailable` / `Server time unavailable`; a failed ping renders one +explicit `Server details unavailable: …` line instead of repeating both +"unavailable" lines. No zero or stale value is substituted. Disconnect and +reconnect clear the previous server's details. + +Connection card copy and state lines follow `web/src/settings.js` and +`SettingsScreen.kt`: `Not connected`, `Connecting (attempt N)…`, `Connected`, +`Disconnected` + reason + `Retrying with backoff…`, plus the trusted-LAN/VPN +warning. A dropped socket's attempt/backoff state comes from the transport. + +Workspace validation is the web rule: blank is untouched (no error), a relative +path is rejected, Save is enabled only for a trimmed absolute path. The saved +line is `Saved workspace: /path` or `Saved workspace: (none)`, and the helper +states that the path is an absolute directory on the execution server, not the +phone's storage. Save failures keep the previous saved value and say so. + +## Persistence + +`shared_preferences` keys are owned by this feature: + +- `pipelines.next.serverUrl.v1` +- `pipelines.next.workspace.v1` + +No legacy Android/web key (`server_url`, `workspace`, +`pipelines.web.serverUrl.v2`, `pipelines.web.workspace.v1`, notification keys) +is read, migrated or written. The endpoint is validated and persisted before +`client.connect` is attempted, matching the web's write-before-connect +behaviour; a value that fails to connect stays stored. When the store write +itself fails, the screen still connects and says the value applies to this +session only. Credentials in a URL are rejected before any write or socket. +Only those two strings are stored; nothing else. + +The web `shared_preferences` implementation may namespace its keys internally; +the logical keys above are the independent feature keys and tests assert the +legacy keys stay untouched. + +## Web default endpoint + +`defaultServerUrl()` returns `''` on native builds. On web it derives +`ws(s):///connect` from `Uri.base` (`kIsWeb`, no `dart:html`), +so the screen starts from the configurable same-origin proxy and no server host +or production endpoint is baked into the app. The field remains editable and +only the validated value is persisted. + +## Verification + +- `flutter test test/features/settings` — 39 tests pass (copy/default endpoint, + persistence keys/legacy isolation, controller connect/validation/ping/ + disconnect/reconnect/backoff/dispose ownership/workspace errors, Material and + Cupertino widgets, invalid URL, pending vs completed-empty ping, failed-ping + single line, field labels in semantics, narrow + 2× text with full labels and + helper copy, unmount ownership). +- `flutter test` (full app) — 52 tests pass. +- `flutter analyze` — no issues; `dart format --set-exit-if-changed` clean on the + 19 Dart settings/test/tool files. +- `flutter build web` (main) and `flutter build web -t tool/settings_probe.dart` + — both built. +- Real browser evidence from an isolated loopback probe server (`/connect` + answers `ping` with `probe-1.2.3`/`abc1234`/time), headless Chrome over CDP: + `settings-idle`, `settings-connected`, `settings-validation` (clicked Connect + after an `http://` draft), `settings-workspace` (typed `/srv/pipelines`, + clicked Save), `settings-dark`, `settings-ios`, `settings-narrow` (390×844, + 1.6× text). See `public/settings-captures/manifest.md`. +- Fix verification with a 6 s delayed pong: at 1.5 s the card shows + `Connected` + `Loading server details…` (no "unavailable"), and after the pong + it shows the real build/time. At 320×700/2× and 390×844/2× the full + `Server URL`/`Workspace path (on the server)` labels and the complete helper + and error sentences render (no ellipsis or line cap). See + `public/settings-fix-captures/manifest.md`. +- The 20 candidate paths are new and currently **untracked** (`??`, none + ignored); landing must `git add` them. The candidate is left uncommitted per + the stage instruction. + +## Gaps / not done + +- Notifications are not part of this screen yet. The queue item names them, but + the task scope here was connection/workspace and the project has no + notification plugin; adding one needs a dependency decision. +- No Templates card: navigation into the templates feature is shell/feature + registration work owned elsewhere. +- No protocol-mismatch warning (the web page shows one); it needs a shared + protocol-version constant not present in the app yet. +- Mobile builds/devices and the real production server were not used. The + Cupertino rendering is shown through the web probe with an iOS platform theme, + not on an actual iOS device. +- The probe's `connected` capture is an automatic fixture connect; validation + and workspace-save captures use actual browser clicks/typing. The main web + entry (`lib/main.dart`) is still the scaffold and was not modified. diff --git a/app/test/features/settings/fake_channel.dart b/app/test/features/settings/fake_channel.dart new file mode 100644 index 00000000..e7eabde4 --- /dev/null +++ b/app/test/features/settings/fake_channel.dart @@ -0,0 +1,115 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:web_socket_channel/web_socket_channel.dart'; + +/// A deterministic websocket channel for the Settings tests. It records every +/// outgoing request and lets the test complete readiness and deliver replies. +class FakeChannel implements WebSocketChannel { + FakeChannel(this.uri); + + final Uri uri; + final StreamController incoming = StreamController(); + final List outgoing = []; + final Completer readyCompleter = Completer(); + bool _closed = false; + + void markReady() { + if (!readyCompleter.isCompleted) readyCompleter.complete(); + } + + void reply(Map message) { + if (!incoming.isClosed) incoming.add(jsonEncode(message)); + } + + void fail(String message) { + if (!incoming.isClosed) incoming.addError(StateError(message)); + } + + void closeStream() { + if (!incoming.isClosed) { + _closed = true; + incoming.close(); + } + } + + List> get decodedOutgoing => outgoing + .map((item) => jsonDecode(item) as Map) + .toList(growable: false); + + @override + Stream get stream => incoming.stream; + + @override + WebSocketSink get sink => _FakeSink(this); + + @override + Future get ready => readyCompleter.future; + + @override + String? get protocol => null; + + @override + int? get closeCode => _closed ? 1000 : null; + + @override + String? get closeReason => null; + + @override + noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _FakeSink implements WebSocketSink { + _FakeSink(this.channel); + + final FakeChannel channel; + + @override + void add(dynamic event) { + if (event is String) channel.outgoing.add(event); + } + + @override + void addError(Object error, [StackTrace? stackTrace]) => throw error; + + @override + Future addStream(Stream stream) async { + await for (final item in stream) { + add(item); + } + } + + @override + Future close([int? closeCode, String? closeReason]) async { + channel.closeStream(); + } + + @override + Future get done async {} + + @override + noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +/// Records every channel the client asks for, so tests can prove that a rebuild +/// or an invalid URL opened no socket at all. +class FakeChannelFactory { + final List channels = []; + final List uris = []; + + FakeChannel get last => channels.last; + + WebSocketChannel call(Uri uri) { + uris.add(uri); + final channel = FakeChannel(uri); + channels.add(channel); + return channel; + } +} + +/// Let queued microtasks (state events, request sends, replies) run. +Future settle() async { + for (var i = 0; i < 4; i++) { + await Future.delayed(Duration.zero); + } +} diff --git a/app/test/features/settings/settings_controller_test.dart b/app/test/features/settings/settings_controller_test.dart new file mode 100644 index 00000000..bf03672e --- /dev/null +++ b/app/test/features/settings/settings_controller_test.dart @@ -0,0 +1,440 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart' + as transport; +import 'package:pipelines_app/features/settings/settings_controller.dart'; +import 'package:pipelines_app/features/settings/settings_copy.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; + +import 'fake_channel.dart'; + +void main() { + test('initializes without opening a connection', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final controller = SettingsController( + client: client, + store: MemorySettingsStore( + serverUrl: 'ws://saved.test/connect', + workspace: '/srv/pipelines', + ), + ); + addTearDown(controller.dispose); + + await controller.initialize(); + await settle(); + + expect(controller.serverUrl, 'ws://saved.test/connect'); + expect(controller.workspaceDraft, '/srv/pipelines'); + expect(controller.savedWorkspace, '/srv/pipelines'); + expect(factory.channels, isEmpty); + expect(controller.connectionLines, ['Not connected']); + }); + + test( + 'an initial endpoint seeds the draft but is not persisted by itself', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final store = MemorySettingsStore(serverUrl: 'ws://saved.test/connect'); + final controller = SettingsController( + client: client, + store: store, + initialEndpoint: Uri.parse('ws://initial.test:9000'), + ); + addTearDown(controller.dispose); + + await controller.initialize(); + + expect(controller.serverUrl, 'ws://initial.test:9000'); + expect(store.serverUrl, 'ws://saved.test/connect'); + }, + ); + + test('a native/default endpoint seeds an empty store', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + defaultEndpoint: 'ws://page.test/connect', + ); + addTearDown(controller.dispose); + + await controller.initialize(); + + expect(controller.serverUrl, 'ws://page.test/connect'); + }); + + test('an invalid URL names the field error and opens no socket', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final store = MemorySettingsStore(); + final controller = SettingsController(client: client, store: store); + addTearDown(controller.dispose); + await controller.initialize(); + + controller.updateServerUrl('http://example.test'); + await controller.connect(); + await settle(); + + expect(controller.urlError, contains('Unsupported scheme')); + expect(factory.channels, isEmpty); + expect(store.serverUrl, ''); + }); + + test('a URL with credentials is rejected before it is persisted', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final store = MemorySettingsStore(); + final controller = SettingsController(client: client, store: store); + addTearDown(controller.dispose); + await controller.initialize(); + + controller.updateServerUrl('ws://operator:secret@example.test/connect'); + await controller.connect(); + await settle(); + + expect(controller.urlError, contains('Credentials are not supported')); + expect(factory.channels, isEmpty); + expect(store.serverUrl, ''); + }); + + test( + 'connect validates, normalizes, persists and pings exactly once', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final store = MemorySettingsStore(); + final controller = SettingsController(client: client, store: store); + await controller.initialize(); + + controller.updateServerUrl(' ws://example.test:8123 '); + final connecting = controller.connect(); + await settle(); + expect(factory.uris.single.toString(), 'ws://example.test:8123/connect'); + expect(controller.serverUrl, 'ws://example.test:8123/connect'); + expect(store.serverUrl, 'ws://example.test:8123/connect'); + + factory.last.markReady(); + await connecting; + await settle(); + + final outgoing = factory.last.decodedOutgoing; + expect(outgoing, hasLength(1)); + expect(outgoing.single['type'], 'ping'); + expect(controller.connection.kind, transport.ConnectionKind.connected); + + factory.last.reply({ + 'id': outgoing.single['id'], + 'type': 'pong', + 'build': {'version': 'v9', 'commit': 'deadbee'}, + 'time': '2026-10-21T12:00:00Z', + }); + await settle(); + + expect(controller.buildVersion, 'v9'); + expect(controller.buildCommit, 'deadbee'); + expect(controller.serverTime, '2026-10-21T12:00:00Z'); + expect(controller.connectionLines, [ + 'Connected', + 'Server build v9 (deadbee)', + 'Server time 2026-10-21T12:00:00Z', + ]); + + // Rebuilding or notifying must not send another ping for this connection. + await settle(); + expect(factory.last.decodedOutgoing, hasLength(1)); + + controller.dispose(); + await client.dispose(); + }, + ); + + test( + 'the card is pending until the ping answers, then names missing values', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final reply = Completer>(); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ping: () => reply.future, + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + + expect(controller.pingInFlight, isTrue); + expect(controller.connectionLines, [ + 'Connected', + serverDetailsPending, + ]); + + reply.complete({'type': 'pong'}); + await settle(); + + expect(controller.pingInFlight, isFalse); + expect(controller.connectionLines, [ + 'Connected', + 'Server build unavailable', + 'Server time unavailable', + ]); + + controller.dispose(); + await client.dispose(); + }, + ); + + test( + 'a ping failure is one explicit line, not two unavailable values', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ping: () async => throw StateError('probe failed'), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + + expect(controller.pingError, startsWith('Server details unavailable:')); + expect(controller.pingError, contains('probe failed')); + expect(controller.pingInFlight, isFalse); + expect(controller.connectionLines, [ + 'Connected', + startsWith('Server details unavailable:'), + ]); + expect(controller.connection.kind, transport.ConnectionKind.connected); + + controller.dispose(); + await client.dispose(); + }, + ); + + test( + 'disconnect clears server details and leaves the shared client alive', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + factory.last.reply({ + 'id': factory.last.decodedOutgoing.single['id'], + 'type': 'pong', + 'build': {'version': 'v9'}, + 'time': '2026-10-21T12:00:00Z', + }); + await settle(); + expect(controller.buildVersion, 'v9'); + + await controller.disconnect(); + await settle(); + + expect(controller.connection.kind, transport.ConnectionKind.idle); + expect(controller.buildVersion, ''); + expect(controller.serverTime, ''); + expect(controller.connectionLines, ['Not connected']); + + controller.dispose(); + await client.dispose(); + }, + ); + + test('reconnect opens one new connection after a disconnect', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + + await controller.disconnect(); + await settle(); + final reconnecting = controller.reconnect(); + await settle(); + expect(factory.channels, hasLength(2)); + factory.last.markReady(); + await reconnecting; + await settle(); + expect(controller.connection.kind, transport.ConnectionKind.connected); + + controller.dispose(); + await client.dispose(); + }); + + test( + 'disposing the screen does not dispose or disconnect the shared client', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + + controller.dispose(); + await settle(); + + expect( + client.state.kind, + transport.ConnectionKind.connected, + reason: 'the feature must not disconnect a client it does not own', + ); + await client.dispose(); + }, + ); + + test('opening while already connected pings that connection once', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final connecting = client.connect(Uri.parse('ws://example.test:8123')); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + expect(factory.last.outgoing, isEmpty); + + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + await settle(); + + expect(factory.last.decodedOutgoing, hasLength(1)); + expect(factory.last.decodedOutgoing.single['type'], 'ping'); + + controller.dispose(); + await client.dispose(); + }); + + test( + 'a failed endpoint write still connects but says it is session-only', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final store = MemorySettingsStore()..failSaves = true; + final controller = SettingsController(client: client, store: store); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + + expect(factory.channels, hasLength(1)); + expect(store.serverUrl, ''); + expect(controller.endpointSaveError, isNotEmpty); + + factory.last.markReady(); + await connecting; + await settle(); + expect(controller.connection.kind, transport.ConnectionKind.connected); + + controller.dispose(); + await client.dispose(); + }, + ); + + test('a dropped connection exposes the reason and retry backoff', () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final controller = SettingsController( + client: client, + store: MemorySettingsStore(), + ); + await controller.initialize(); + controller.updateServerUrl('ws://example.test:8123'); + final connecting = controller.connect(); + await settle(); + factory.last.markReady(); + await connecting; + await settle(); + + factory.last.fail('socket gone'); + await settle(); + + expect(controller.connection.kind, transport.ConnectionKind.disconnected); + expect(controller.connection.reason, contains('socket gone')); + expect(controller.connection.retrying, isTrue); + expect( + controller.connectionLines, + containsAll(['Disconnected', 'Retrying with backoff\u2026']), + ); + + // Cancel the client's scheduled retry before the test ends. + await client.disconnect(); + controller.dispose(); + await client.dispose(); + }); + + test( + 'workspace save persists only an absolute path and reports failures', + () async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + final store = MemorySettingsStore(); + final controller = SettingsController(client: client, store: store); + await controller.initialize(); + + controller.updateWorkspace('relative/path'); + expect(controller.workspaceError, workspacePathError); + await controller.saveWorkspace(); + expect(store.workspace, ''); + expect(controller.savedWorkspace, ''); + + controller.updateWorkspace(' /srv/pipelines '); + await controller.saveWorkspace(); + expect(store.workspace, '/srv/pipelines'); + expect(controller.savedWorkspace, '/srv/pipelines'); + expect(controller.workspaceDraft, '/srv/pipelines'); + + store.failSaves = true; + controller.updateWorkspace('/other/path'); + await controller.saveWorkspace(); + expect(controller.savedWorkspace, '/srv/pipelines'); + expect(controller.workspaceSaveError, isNotEmpty); + + controller.dispose(); + await client.dispose(); + }, + ); +} diff --git a/app/test/features/settings/settings_copy_test.dart b/app/test/features/settings/settings_copy_test.dart new file mode 100644 index 00000000..2fca897b --- /dev/null +++ b/app/test/features/settings/settings_copy_test.dart @@ -0,0 +1,160 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart' + as transport; +import 'package:pipelines_app/features/settings/default_endpoint.dart'; +import 'package:pipelines_app/features/settings/settings_copy.dart'; + +void main() { + group('workspace validation', () { + test('blank is untouched, relative is rejected, absolute is accepted', () { + expect(validateWorkspacePath(''), isNull); + expect(validateWorkspacePath(' '), isNull); + expect(validateWorkspacePath('repos/pipelines'), workspacePathError); + expect(validateWorkspacePath('/Users/you/repos/pipelines'), isNull); + expect( + validateWorkspacePath(' /srv/pipelines '), + isNull, + reason: 'trimmed before validating', + ); + }); + + test('Save needs a trimmed absolute path, never a blank field', () { + expect(canSaveWorkspace(''), isFalse); + expect(canSaveWorkspace(' '), isFalse); + expect(canSaveWorkspace('relative/path'), isFalse); + expect(canSaveWorkspace('/srv/pipelines'), isTrue); + expect(canSaveWorkspace(' /srv/pipelines '), isTrue); + }); + + test('the saved line names an empty value instead of showing nothing', () { + expect(savedWorkspaceLine(''), 'Saved workspace: (none)'); + expect( + savedWorkspaceLine(' /srv/pipelines '), + 'Saved workspace: /srv/pipelines', + ); + }); + }); + + group('server build and connection card', () { + test('build label includes only the reported parts', () { + expect(serverBuildLabel(), ''); + expect(serverBuildLabel(version: 'v1.2.3'), 'Server build v1.2.3'); + expect( + serverBuildLabel(version: 'v1.2.3', commit: 'abc1234'), + 'Server build v1.2.3 (abc1234)', + ); + expect(serverBuildLabel(commit: 'abc1234'), 'Server build (abc1234)'); + }); + + test('idle, connecting and disconnected states keep the app words', () { + expect( + connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.idle), + ), + ['Not connected'], + ); + expect( + connectionCardLines( + const transport.ConnectionState( + transport.ConnectionKind.connecting, + attempt: 3, + ), + ), + ['Connecting (attempt 3)\u2026'], + ); + expect( + connectionCardLines( + const transport.ConnectionState( + transport.ConnectionKind.disconnected, + reason: 'Connection closed', + retrying: true, + ), + ), + [ + 'Disconnected', + 'Connection closed', + 'Retrying with backoff\u2026', + ], + ); + expect( + connectionCardLines( + const transport.ConnectionState( + transport.ConnectionKind.disconnected, + ), + ), + ['Disconnected'], + ); + }); + + test('connected names unavailable build/time instead of zero', () { + final lines = connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.connected), + ); + expect(lines, [ + 'Connected', + 'Server build unavailable', + 'Server time unavailable', + ]); + }); + + test('connected reports the ping fields and an explicit ping error', () { + final lines = connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.connected), + buildVersion: 'v9', + buildCommit: 'deadbee', + serverTime: '2026-10-21T12:00:00Z', + pingError: 'Server details unavailable: timed out', + ); + expect(lines, [ + 'Connected', + 'Server build v9 (deadbee)', + 'Server time 2026-10-21T12:00:00Z', + 'Server details unavailable: timed out', + ]); + }); + + test( + 'connected while the ping is pending says loading, not unavailable', + () { + final lines = connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.connected), + pingInFlight: true, + ); + expect(lines, ['Connected', serverDetailsPending]); + expect(lines.any((line) => line.contains('unavailable')), isFalse); + }, + ); + + test('a failed ping is one explicit line, not two unavailable values', () { + final lines = connectionCardLines( + const transport.ConnectionState(transport.ConnectionKind.connected), + pingError: 'Server details unavailable: timed out', + ); + expect(lines, [ + 'Connected', + 'Server details unavailable: timed out', + ]); + }); + }); + + group('same-origin default endpoint', () { + test('native builds bake no endpoint', () { + expect(defaultServerUrl(web: false), ''); + }); + + test('web uses the page origin, upgraded to ws/wss', () { + expect( + defaultServerUrl(web: true, base: Uri.parse('http://127.0.0.1:8123/')), + 'ws://127.0.0.1:8123/connect', + ); + expect( + defaultServerUrl( + web: true, + base: Uri.parse('https://pipelines.example.test/pipelines'), + ), + 'wss://pipelines.example.test/connect', + ); + expect(defaultServerUrl(web: true, base: Uri.parse('about:blank')), ''); + }); + }); +} diff --git a/app/test/features/settings/settings_screen_test.dart b/app/test/features/settings/settings_screen_test.dart new file mode 100644 index 00000000..66d4d2d1 --- /dev/null +++ b/app/test/features/settings/settings_screen_test.dart @@ -0,0 +1,314 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart' + as transport; +import 'package:pipelines_app/features/settings/settings_copy.dart'; +import 'package:pipelines_app/features/settings/settings_keys.dart'; +import 'package:pipelines_app/features/settings/settings_screen.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; + +import 'fake_channel.dart'; + +void main() { + testWidgets('renders idle settings without opening a connection', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump( + tester, + client, + store: MemorySettingsStore( + serverUrl: 'ws://saved.test/connect', + workspace: '/srv/pipelines', + ), + ); + + expect(find.text('Settings'), findsOneWidget); + expect(find.text('Connection'), findsOneWidget); + expect(find.text('Workspace'), findsOneWidget); + expect(find.text('Not connected'), findsOneWidget); + expect(find.text('Saved workspace: /srv/pipelines'), findsOneWidget); + expect( + tester.widget(find.byType(TextField).first).controller?.text, + 'ws://saved.test/connect', + ); + expect(find.byKey(SettingsKeys.connect), findsOneWidget); + expect(find.byKey(SettingsKeys.reconnect), findsOneWidget); + + await tester.pump(); + expect(factory.channels, isEmpty); + }); + + testWidgets('an invalid URL shows the field error and opens no socket', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + await tester.enterText(find.byType(TextField).first, 'http://example.test'); + await tester.pump(); + await tester.tap(find.byKey(SettingsKeys.connect)); + await tester.pump(); + await tester.pump(); + + expect(find.textContaining('Unsupported scheme'), findsOneWidget); + expect(factory.channels, isEmpty); + }); + + testWidgets('connect pings once and shows the reported build and time', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + await tester.enterText( + find.byType(TextField).first, + 'ws://example.test:8123', + ); + await tester.pump(); + await tester.tap(find.byKey(SettingsKeys.connect)); + await tester.pump(); + await tester.pump(); + + expect(factory.channels, hasLength(1)); + expect(factory.uris.single.toString(), 'ws://example.test:8123/connect'); + expect(find.text('Connecting (attempt 1)\u2026'), findsOneWidget); + + factory.last.markReady(); + await tester.pump(); + await tester.pump(); + final outgoing = factory.last.decodedOutgoing; + expect(outgoing, hasLength(1)); + expect(outgoing.single['type'], 'ping'); + + factory.last.reply({ + 'id': outgoing.single['id'], + 'type': 'pong', + 'build': {'version': 'v9', 'commit': 'deadbee'}, + 'time': '2026-10-21T12:00:00Z', + }); + await tester.pump(); + await tester.pump(); + + expect(find.text('Connected'), findsOneWidget); + expect(find.text('Server build v9 (deadbee)'), findsOneWidget); + expect(find.text('Server time 2026-10-21T12:00:00Z'), findsOneWidget); + expect(find.byKey(SettingsKeys.disconnect), findsOneWidget); + expect(find.byKey(SettingsKeys.connect), findsOneWidget); + expect(factory.last.decodedOutgoing, hasLength(1)); + }); + + testWidgets('connected without a ping reply names unavailable values', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + await tester.enterText( + find.byType(TextField).first, + 'ws://example.test:8123', + ); + await tester.pump(); + await tester.tap(find.byKey(SettingsKeys.connect)); + await tester.pump(); + await tester.pump(); + factory.last.markReady(); + await tester.pump(); + await tester.pump(); + expect(factory.last.decodedOutgoing.single['type'], 'ping'); + + expect(find.text('Connected'), findsOneWidget); + expect(find.text(serverDetailsPending), findsOneWidget); + expect(find.text('Server build unavailable'), findsNothing); + + factory.last.reply({ + 'id': factory.last.decodedOutgoing.single['id'], + 'type': 'pong', + }); + await tester.pump(); + await tester.pump(); + + expect(find.text(serverDetailsPending), findsNothing); + expect(find.text('Server build unavailable'), findsOneWidget); + expect(find.text('Server time unavailable'), findsOneWidget); + }); + + testWidgets( + 'workspace validation gates Save and only a save updates the line', + (tester) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + final store = MemorySettingsStore(); + + await _pump(tester, client, store: store); + final workspace = find.byType(TextField).at(1); + await tester.enterText(workspace, 'relative/path'); + await tester.pump(); + + expect(find.textContaining('must be an absolute path'), findsOneWidget); + expect( + tester + .widget(find.byKey(SettingsKeys.saveWorkspace)) + .onPressed, + isNull, + ); + expect(find.text('Saved workspace: (none)'), findsOneWidget); + + await tester.enterText(workspace, ' /srv/pipelines '); + await tester.pump(); + await tester.tap(find.byKey(SettingsKeys.saveWorkspace)); + await tester.pump(); + await tester.pump(); + + expect(find.text('Saved workspace: /srv/pipelines'), findsOneWidget); + expect(store.workspace, '/srv/pipelines'); + }, + ); + + testWidgets('iOS uses Cupertino fields, buttons and navigation', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client, platform: TargetPlatform.iOS); + + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.byType(CupertinoTextField), findsNWidgets(2)); + expect(find.byType(TextField), findsNothing); + expect(find.byType(FilledButton), findsNothing); + expect(find.byKey(SettingsKeys.connect), findsOneWidget); + expect(find.text('Trusted LAN/VPN only'), findsOneWidget); + }); + + testWidgets('narrow window with large text scrolls without overflow', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client, textScale: 2, size: const Size(320, 640)); + + expect(tester.takeException(), isNull); + await tester.scrollUntilVisible( + find.byKey(SettingsKeys.saveWorkspace), + 200, + scrollable: find.byType(Scrollable).first, + ); + expect(find.byKey(SettingsKeys.saveWorkspace), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('large text keeps the full labels and supporting copy', ( + tester, + ) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client, textScale: 2, size: const Size(320, 640)); + + expect(find.text('Workspace path (on the server)'), findsOneWidget); + expect(find.text('Server URL'), findsOneWidget); + for (final copy in [ + 'Workspace path (on the server)', + serverUrlHelper, + workspaceHelper, + ]) { + final text = tester.widget(find.text(copy)); + expect(text.maxLines, isNull, reason: 'no line cap on $copy'); + final paragraph = tester.renderObject(find.text(copy)); + expect( + paragraph.didExceedMaxLines, + isFalse, + reason: 'the whole copy is laid out for $copy', + ); + } + expect(tester.takeException(), isNull); + }); + + testWidgets('the text fields expose their labels to accessibility', ( + tester, + ) async { + final handle = tester.ensureSemantics(); + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + + final labels = [ + tester + .getSemantics(find.byType(TextField).at(0)) + .getSemanticsData() + .label, + tester + .getSemantics(find.byType(TextField).at(1)) + .getSemanticsData() + .label, + ]; + expect(labels[0], contains('Server URL')); + expect(labels[1], contains('Workspace path (on the server)')); + handle.dispose(); + }); + + testWidgets('unmounting leaves the shared client usable', (tester) async { + final factory = FakeChannelFactory(); + final client = transport.PipelinesClient(channelFactory: factory.call); + addTearDown(client.dispose); + + await _pump(tester, client); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + + final connecting = client.connect(Uri.parse('ws://example.test:8123')); + await tester.pump(); + expect(factory.channels, hasLength(1)); + factory.last.markReady(); + await tester.pump(); + await connecting; + }); +} + +Future _pump( + WidgetTester tester, + transport.PipelinesClient client, { + SettingsStore? store, + TargetPlatform platform = TargetPlatform.android, + double textScale = 1, + Size size = const Size(800, 1200), +}) async { + await tester.binding.setSurfaceSize(size); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: platform), + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child ?? const SizedBox.shrink(), + ), + home: SettingsScreen( + client: client, + store: store ?? MemorySettingsStore(), + ), + ), + ); + await tester.pump(); + await tester.pump(); +} diff --git a/app/test/features/settings/settings_store_test.dart b/app/test/features/settings/settings_store_test.dart new file mode 100644 index 00000000..216967a4 --- /dev/null +++ b/app/test/features/settings/settings_store_test.dart @@ -0,0 +1,68 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + SharedPreferences.setMockInitialValues({}); + }); + + test('starts blank when nothing is stored', () async { + const store = SharedPreferencesSettingsStore(); + final values = await store.load(); + expect(values.serverUrl, ''); + expect(values.workspace, ''); + }); + + test('writes only the feature-owned pipelines.next keys', () async { + const store = SharedPreferencesSettingsStore(); + expect(await store.saveServerUrl(' ws://127.0.0.1:8081/connect '), isTrue); + expect(await store.saveWorkspace(' /srv/pipelines '), isTrue); + + final preferences = await SharedPreferences.getInstance(); + expect( + preferences.getString(settingsServerUrlKey), + 'ws://127.0.0.1:8081/connect', + ); + expect(preferences.getString(settingsWorkspaceKey), '/srv/pipelines'); + expect(preferences.getKeys(), { + settingsServerUrlKey, + settingsWorkspaceKey, + }); + expect(settingsServerUrlKey, startsWith('pipelines.next.')); + expect(settingsWorkspaceKey, startsWith('pipelines.next.')); + + final reloaded = await store.load(); + expect(reloaded.serverUrl, 'ws://127.0.0.1:8081/connect'); + expect(reloaded.workspace, '/srv/pipelines'); + }); + + test('never reads or writes legacy web/Android preference keys', () async { + SharedPreferences.setMockInitialValues({ + 'pipelines.web.serverUrl.v2': 'ws://legacy.test/connect', + 'pipelines.web.workspace.v1': '/legacy/workspace', + 'server_url': 'ws://android.test/connect', + 'workspace': '/android/workspace', + }); + const store = SharedPreferencesSettingsStore(); + final values = await store.load(); + expect(values.serverUrl, ''); + expect(values.workspace, ''); + + await store.saveServerUrl('ws://new.test/connect'); + await store.saveWorkspace('/new/workspace'); + final preferences = await SharedPreferences.getInstance(); + expect( + preferences.getString('pipelines.web.serverUrl.v2'), + 'ws://legacy.test/connect', + ); + expect( + preferences.getString('pipelines.web.workspace.v1'), + '/legacy/workspace', + ); + expect(preferences.getString('server_url'), 'ws://android.test/connect'); + expect(preferences.getString('workspace'), '/android/workspace'); + }); +} diff --git a/app/tool/settings_probe.dart b/app/tool/settings_probe.dart new file mode 100644 index 00000000..4c954dbe --- /dev/null +++ b/app/tool/settings_probe.dart @@ -0,0 +1,71 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/settings/settings.dart'; + +/// A fixture entry point for browser captures of the Settings screen. It does +/// not change `main.dart` or the shell, and it never uses the production +/// preferences store: all persisted values live in a [MemorySettingsStore]. +/// +/// Query parameters: +/// endpoint=ws://127.0.0.1:PORT/connect seed the URL field / connect target +/// workspace=/srv/pipelines seed the saved workspace +/// connect=1 explicitly connect after first frame +/// platform=ios render the Cupertino controls +/// theme=dark dark Material theme +/// scale=1.5 large-text check +void main() { + final params = Uri.base.queryParameters; + final endpoint = params['endpoint']?.trim(); + final client = PipelinesClient(); + final store = MemorySettingsStore( + workspace: params['workspace']?.trim() ?? '', + ); + final isIOS = params['platform'] == 'ios'; + final isDark = params['theme'] == 'dark'; + final scale = double.tryParse(params['scale'] ?? '') ?? 1; + + runApp( + MaterialApp( + title: 'Pipelines Settings probe', + theme: ThemeData( + platform: isIOS ? TargetPlatform.iOS : TargetPlatform.android, + brightness: isDark ? Brightness.dark : Brightness.light, + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.blue, + brightness: isDark ? Brightness.dark : Brightness.light, + ), + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: child ?? const SizedBox.shrink(), + ), + home: SettingsScreen( + client: client, + initialEndpoint: (endpoint == null || endpoint.isEmpty) + ? null + : Uri.tryParse(endpoint), + store: store, + ), + ), + ); + + if (params['connect'] == '1') { + final target = (endpoint == null || endpoint.isEmpty) + ? defaultServerUrl() + : endpoint; + if (target.isNotEmpty) { + WidgetsBinding.instance.addPostFrameCallback((_) { + unawaited( + client.connect(Uri.parse(target)).catchError((Object _) { + // The screen renders the client's truthful state; an invalid + // fixture endpoint must not take the probe down. + }), + ); + }); + } + } +} diff --git a/app/tool/settings_probe_capture.dart b/app/tool/settings_probe_capture.dart new file mode 100644 index 00000000..f15d6803 --- /dev/null +++ b/app/tool/settings_probe_capture.dart @@ -0,0 +1,318 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +/// Drives the Settings probe in real headless Chrome through the DevTools +/// protocol and writes PNG captures. It only talks to the local probe origin +/// passed with `--url`; it never contacts the production server. +/// +/// Usage: +/// dart run tool/settings_probe_capture.dart \ +/// --url http://127.0.0.1:PORT/ --out /path/to/captures +/// +/// Set CHROME_PATH if Chrome is not at the default macOS location. +Future main(List arguments) async { + final url = _argument(arguments, '--url'); + final outPath = _argument(arguments, '--out'); + if (url == null || outPath == null) { + stderr.writeln('usage: ... --url URL --out DIRECTORY'); + exitCode = 64; + return; + } + final out = Directory(outPath)..createSync(recursive: true); + final chromePath = + Platform.environment['CHROME_PATH'] ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; + final profile = await Directory.systemTemp.createTemp('settings-probe-'); + final chrome = await Process.start(chromePath, [ + '--headless=new', + '--disable-gpu', + '--hide-scrollbars', + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=0', + '--user-data-dir=${profile.path}', + 'about:blank', + ]); + final stderrLines = chrome.stderr + .transform(utf8.decoder) + .transform(const LineSplitter()) + .asBroadcastStream(); + try { + final browserWs = await stderrLines + .firstWhere((line) => line.contains('DevTools listening on ')) + .timeout(const Duration(seconds: 20)); + final browserUrl = browserWs.substring(browserWs.indexOf('ws://')); + final parsed = Uri.parse(browserUrl); + final pageWs = await _pageTarget(parsed); + final cdp = Cdp(await WebSocket.connect(pageWs)); + await cdp.send('Page.enable'); + await cdp.send('Runtime.enable'); + + final scenarios = [ + 'idle', + 'connected', + 'validation', + 'workspace', + 'dark', + 'ios', + 'narrow', + ]; + for (final scenario in scenarios) { + await _runScenario(cdp, url, out, scenario); + stdout.writeln('captured $scenario'); + } + await cdp.close(); + } finally { + chrome.kill(ProcessSignal.sigterm); + await profile.delete(recursive: true).catchError((_) => profile); + } +} + +Future _runScenario( + Cdp cdp, + String base, + Directory out, + String scenario, +) async { + var target = base; + var width = 1200; + var height = 900; + switch (scenario) { + case 'idle': + break; + case 'connected': + target = '$base?connect=1'; + break; + case 'validation': + target = '$base?endpoint=http%3A%2F%2Fexample.test'; + break; + case 'workspace': + target = '$base?connect=1'; + break; + case 'dark': + target = '$base?connect=1&theme=dark'; + break; + case 'ios': + target = '$base?connect=1&platform=ios'; + break; + case 'narrow': + width = 390; + height = 844; + target = '$base?connect=1&scale=1.6'; + } + await cdp.send('Emulation.setDeviceMetricsOverride', { + 'width': width, + 'height': height, + 'deviceScaleFactor': 1, + 'mobile': false, + }); + await cdp.send('Page.navigate', {'url': target}); + await Future.delayed(const Duration(seconds: 4)); + if (scenario == 'validation' || scenario == 'workspace') { + await _enableSemantics(cdp); + if (scenario == 'validation') { + await _click(cdp, 'Connect'); + await Future.delayed(const Duration(milliseconds: 800)); + } else { + await _typeWorkspace(cdp, '/srv/pipelines'); + await _click(cdp, 'Save workspace'); + await Future.delayed(const Duration(milliseconds: 800)); + } + } + final shot = await cdp.send('Page.captureScreenshot', { + 'format': 'png', + 'captureBeyondViewport': false, + }); + final data = (shot['result'] as Map)['data'] as String; + File( + '${out.path}/settings-$scenario.png', + ).writeAsBytesSync(base64Decode(data)); +} + +Future _enableSemantics(Cdp cdp) async { + await cdp.evaluate(''' + (() => { + const placeholder = document.querySelector('flt-semantics-placeholder'); + if (placeholder) { + placeholder.click(); + return 'semantics requested'; + } + return 'no placeholder'; + })() + '''); + await Future.delayed(const Duration(milliseconds: 900)); + if (Platform.environment['DUMP_DOM'] == '1') { + stdout.writeln( + await cdp.evaluate( + "document.querySelector('flt-semantics-host')?.innerHTML ?? 'none'", + ), + ); + } +} + +Future _click(Cdp cdp, String label) async { + final result = await cdp.evaluate(''' + (() => { + const byLabel = [...document.querySelectorAll('[aria-label]')] + .find((element) => element.getAttribute('aria-label') === ${jsonEncode(label)}); + const byRole = [...document.querySelectorAll('[role="button"]')] + .find((element) => (element.textContent || '').trim() === ${jsonEncode(label)}); + const target = byLabel || byRole; + if (!target) { + return 'missing; labels=' + [...document.querySelectorAll('[aria-label]')] + .map((element) => element.getAttribute('aria-label')).join('|') + + '; roles=' + [...document.querySelectorAll('[role="button"]')] + .map((element) => (element.textContent || '').trim()).join('|'); + } + target.click(); + return 'clicked ' + target.tagName + ' ' + (target.getAttribute('role') || ''); + })() + '''); + stdout.writeln('click "$label": $result'); +} + +Future _typeWorkspace(Cdp cdp, String value) async { + final found = await cdp.evaluate(''' + (() => { + const target = [...document.querySelectorAll('[aria-label]')] + .find((element) => (element.getAttribute('aria-label') || '') + .startsWith('Workspace path')); + if (!target) return 'missing'; + target.click(); + target.focus(); + return 'focused ' + target.tagName; + })() + '''); + stdout.writeln('workspace field: $found'); + await Future.delayed(const Duration(milliseconds: 400)); + final rect = await cdp.evaluate(''' + (() => { + const target = [...document.querySelectorAll('[aria-label]')] + .find((element) => (element.getAttribute('aria-label') || '') + .startsWith('Workspace path')); + if (!target) return null; + const r = target.getBoundingClientRect(); + return {x: r.left + r.width / 2, y: r.top + r.height / 2}; + })() + '''); + if (rect != 'null') { + final match = RegExp(r'x: ([0-9.]+), y: ([0-9.]+)').firstMatch(rect); + if (match != null) { + final x = double.parse(match.group(1)!); + final y = double.parse(match.group(2)!); + for (final type in ['mousePressed', 'mouseReleased']) { + await cdp.send('Input.dispatchMouseEvent', { + 'type': type, + 'x': x, + 'y': y, + 'button': 'left', + 'clickCount': 1, + }); + } + await Future.delayed(const Duration(milliseconds: 300)); + } + } + await cdp.send('Input.insertText', {'text': value}); + await Future.delayed(const Duration(milliseconds: 300)); + final typed = await cdp.evaluate(''' + (() => { + const el = document.activeElement; + if (!el) return 'no active element'; + if (el.value === ${jsonEncode(value)}) return 'insertText worked'; + el.value = ${jsonEncode(value)}; + el.dispatchEvent(new InputEvent('input', { + bubbles: true, + inputType: 'insertText', + data: ${jsonEncode(value)}, + })); + el.dispatchEvent(new Event('change', {bubbles: true})); + return 'dispatched input; value=' + el.value; + })() + '''); + stdout.writeln('workspace input: $typed'); + await Future.delayed(const Duration(milliseconds: 500)); +} + +Future _pageTarget(Uri browserWs) async { + final client = HttpClient(); + try { + final request = await client.getUrl( + Uri( + scheme: 'http', + host: browserWs.host, + port: browserWs.port, + path: '/json/list', + ), + ); + final response = await request.close(); + final body = await response.transform(utf8.decoder).join(); + final targets = jsonDecode(body) as List; + final page = targets.cast>().firstWhere( + (target) => target['type'] == 'page', + ); + return page['webSocketDebuggerUrl'] as String; + } finally { + client.close(force: true); + } +} + +String? _argument(List arguments, String name) { + final index = arguments.indexOf(name); + if (index < 0 || index + 1 >= arguments.length) return null; + return arguments[index + 1]; +} + +class Cdp { + Cdp(this._socket) { + _socket.listen(_onMessage); + } + + final WebSocket _socket; + final Map>> _pending = {}; + int _next = 0; + + Future> send( + String method, [ + Map params = const {}, + ]) { + final id = ++_next; + final completer = Completer>(); + _pending[id] = completer; + _socket.add( + jsonEncode({ + 'id': id, + 'method': method, + 'params': params, + }), + ); + return completer.future.timeout(const Duration(seconds: 30)); + } + + Future evaluate(String expression) async { + final reply = await send('Runtime.evaluate', { + 'expression': expression, + 'returnByValue': true, + 'awaitPromise': true, + }); + final result = reply['result'] as Map; + return '${result['result']?['value']}'; + } + + void _onMessage(dynamic data) { + if (data is! String) return; + final message = jsonDecode(data) as Map; + final id = message['id']; + if (id is! int) return; + final completer = _pending.remove(id); + if (completer == null) return; + final error = message['error']; + if (error != null) { + completer.completeError(StateError('$error')); + } else { + completer.complete(message); + } + } + + Future close() => _socket.close(); +} diff --git a/app/tool/settings_probe_server.dart b/app/tool/settings_probe_server.dart new file mode 100644 index 00000000..af2a564f --- /dev/null +++ b/app/tool/settings_probe_server.dart @@ -0,0 +1,103 @@ +import 'dart:convert'; +import 'dart:io'; + +/// An isolated loopback fixture for the Settings browser probe. +/// +/// It serves the probe's `build/web` output and upgrades `/connect` to a +/// websocket that answers `ping` with a deterministic pong (build + time), so +/// the screen can be exercised in a real browser without the production server, +/// authentication changes or any deployment. It binds loopback on an OS-assigned +/// port unless `--port` is given. +/// +/// Usage: +/// dart run tool/settings_probe_server.dart --root build/probe_web +Future main(List arguments) async { + var rootPath = 'build/probe_web'; + var port = 0; + for (var i = 0; i < arguments.length; i++) { + if (arguments[i] == '--root' && i + 1 < arguments.length) { + rootPath = arguments[++i]; + } else if (arguments[i] == '--port' && i + 1 < arguments.length) { + port = int.parse(arguments[++i]); + } + } + final root = Directory(rootPath).absolute; + if (!root.existsSync()) { + stderr.writeln('Probe build not found at ${root.path}'); + exitCode = 2; + return; + } + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, port); + stdout.writeln('http://127.0.0.1:${server.port}/'); + await for (final request in server) { + unawaited(_handle(request, root)); + } +} + +Future _handle(HttpRequest request, Directory root) async { + if (request.uri.path == '/connect' && + WebSocketTransformer.isUpgradeRequest(request)) { + final socket = await WebSocketTransformer.upgrade(request); + stdout.writeln('connect'); + socket.listen((data) { + if (data is! String) return; + final Object? decoded; + try { + decoded = jsonDecode(data); + } on FormatException { + return; + } + if (decoded is! Map) return; + if (decoded['type'] != 'ping') return; + stdout.writeln('ping'); + socket.add( + jsonEncode({ + 'id': decoded['id'], + 'type': 'pong', + 'protocol': 1, + 'build': { + 'version': 'probe-1.2.3', + 'commit': 'abc1234', + }, + 'time': '2026-10-21T12:00:00Z', + }), + ); + }); + return; + } + + var relative = request.uri.path; + if (relative.isEmpty || relative == '/') relative = '/index.html'; + final file = File('${root.path}${relative.replaceAll('..', '')}'); + if (!file.existsSync()) { + request.response.statusCode = HttpStatus.notFound; + await request.response.close(); + return; + } + request.response.headers.contentType = _contentType(relative); + request.response.headers.set('Cache-Control', 'no-store'); + await request.response.addStream(file.openRead()); + await request.response.close(); +} + +ContentType _contentType(String path) { + final extension = path.split('.').last.toLowerCase(); + return switch (extension) { + 'html' => ContentType.html, + 'js' || 'mjs' => ContentType('text', 'javascript', charset: 'utf-8'), + 'css' => ContentType('text', 'css', charset: 'utf-8'), + 'json' || 'map' => ContentType.json, + 'png' => ContentType('image', 'png'), + 'svg' => ContentType('image', 'svg+xml'), + 'ico' => ContentType('image', 'x-icon'), + 'wasm' => ContentType('application', 'wasm'), + 'ttf' || 'otf' => ContentType('font', 'ttf'), + _ => ContentType.binary, + }; +} + +void unawaited(Future future) { + future.catchError((Object error, StackTrace stack) { + stderr.writeln('probe server: $error'); + }); +}