From ae8fe49e41cb5ab9d1dc5ae6029c58ebb88347b9 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 8 Nov 2026 21:50:27 +0000 Subject: [PATCH] Find LAN servers from browser and review discovered machine names --- .../browser_discovery_fetch_stub.dart | 3 + .../browser_discovery_fetch_web.dart | 30 +++++ .../discovery/browser_server_discovery.dart | 59 +++++++++ .../onboarding/discovery/discovery_panel.dart | 9 ++ .../discovery/server_discovery.dart | 7 +- .../features/onboarding/onboarding_flow.dart | 32 ++++- .../settings/saved_server_editor.dart | 29 +++- app/notes/browser-network-discovery.md | 16 +++ .../browser_server_discovery_test.dart | 60 +++++++++ .../discovery/discovered_server_test.dart | 4 +- .../discovery/discovery_panel_test.dart | 10 +- .../settings/saved_server_discovery_test.dart | 124 ++++++++++++++++++ 12 files changed, 371 insertions(+), 12 deletions(-) create mode 100644 app/lib/features/onboarding/discovery/browser_discovery_fetch_stub.dart create mode 100644 app/lib/features/onboarding/discovery/browser_discovery_fetch_web.dart create mode 100644 app/lib/features/onboarding/discovery/browser_server_discovery.dart create mode 100644 app/notes/browser-network-discovery.md create mode 100644 app/test/features/onboarding/discovery/browser_server_discovery_test.dart create mode 100644 app/test/features/settings/saved_server_discovery_test.dart diff --git a/app/lib/features/onboarding/discovery/browser_discovery_fetch_stub.dart b/app/lib/features/onboarding/discovery/browser_discovery_fetch_stub.dart new file mode 100644 index 00000000..9b4d5458 --- /dev/null +++ b/app/lib/features/onboarding/discovery/browser_discovery_fetch_stub.dart @@ -0,0 +1,3 @@ +Future fetchDiscovery() => Future.error( + UnsupportedError('Browser discovery requires the web client.'), +); diff --git a/app/lib/features/onboarding/discovery/browser_discovery_fetch_web.dart b/app/lib/features/onboarding/discovery/browser_discovery_fetch_web.dart new file mode 100644 index 00000000..79b74617 --- /dev/null +++ b/app/lib/features/onboarding/discovery/browser_discovery_fetch_web.dart @@ -0,0 +1,30 @@ +import 'dart:js_interop'; + +@JS('fetch') +external JSPromise<_Response> _fetch(JSString url, _Options options); + +extension type _Options._(JSObject _) implements JSObject { + external factory _Options({JSString credentials, JSString cache}); +} + +extension type _Response._(JSObject _) implements JSObject { + external int get status; + external JSPromise text(); +} + +Future fetchDiscovery() async { + final response = await _fetch( + '/api/discovery'.toJS, + _Options(credentials: 'same-origin'.toJS, cache: 'no-store'.toJS), + ).toDart; + if (response.status == 401 || response.status == 403) { + throw StateError('Sign in to this server before searching the network.'); + } + if (response.status == 404) { + throw StateError('Update this server to enable browser network discovery.'); + } + if (response.status != 200) { + throw StateError('Network discovery failed (HTTP ${response.status}).'); + } + return (await response.text().toDart).toDart; +} diff --git a/app/lib/features/onboarding/discovery/browser_server_discovery.dart b/app/lib/features/onboarding/discovery/browser_server_discovery.dart new file mode 100644 index 00000000..48bf6ab4 --- /dev/null +++ b/app/lib/features/onboarding/discovery/browser_server_discovery.dart @@ -0,0 +1,59 @@ +import 'dart:convert'; +import '../../../core/transport/server_url.dart'; +import 'discovered_server.dart'; +import 'server_discovery.dart'; +import 'browser_discovery_fetch_stub.dart' + if (dart.library.js_interop) 'browser_discovery_fetch_web.dart' + as impl; + +/// The authenticated web front door browses its LAN on the browser's behalf. +class BrowserServerDiscovery implements ServerDiscovery { + BrowserServerDiscovery({Future Function()? fetch}) + : _fetch = fetch ?? impl.fetchDiscovery; + final Future Function() _fetch; + + @override + Stream> scan() async* { + final body = await _fetch().timeout(const Duration(seconds: 8)); + if (body.length > 262144) { + throw const FormatException('Discovery response is too large.'); + } + final envelope = jsonDecode(body); + if (envelope is! Map || envelope['discovered_servers'] is! List) { + throw const FormatException( + 'This server did not return network discovery results.', + ); + } + final servers = {}; + for (final item in (envelope['discovered_servers'] as List).take(256)) { + if (item is! Map || + item['endpoint'] is! String || + item['name'] is! String) { + continue; + } + try { + final validated = ServerUrl.validate(item['endpoint'] as String); + final uri = Uri.parse(validated.wsUrl); + final name = (item['name'] as String).trim(); + if (name.isEmpty || + name.length > 256 || + uri.hasQuery || + uri.hasFragment) { + continue; + } + servers[uri] = DiscoveredServer( + name: name, + host: uri.host, + port: validated.port, + secure: uri.scheme == 'wss', + path: uri.path, + passwordRequired: item['auth'] != 'none', + version: item['version'] is String ? item['version'] as String : null, + ); + } on FormatException { + // One malformed announcement must not hide other machines. + } + } + yield servers.values.toList(); + } +} diff --git a/app/lib/features/onboarding/discovery/discovery_panel.dart b/app/lib/features/onboarding/discovery/discovery_panel.dart index 8010a3e7..67597227 100644 --- a/app/lib/features/onboarding/discovery/discovery_panel.dart +++ b/app/lib/features/onboarding/discovery/discovery_panel.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import '../../../ui/adaptive/host.dart'; import 'discovered_server.dart'; +import 'browser_server_discovery.dart'; import 'server_discovery.dart'; enum _Phase { idle, scanning, done, failed } @@ -62,6 +63,12 @@ class _DiscoveryPanelState extends State { (servers) { if (mounted) setState(() => _servers = servers); }, + onDone: () { + _timer?.cancel(); + if (mounted && _phase == _Phase.scanning) { + setState(() => _phase = _Phase.done); + } + }, onError: (Object error) { _stop(); if (mounted) { @@ -126,6 +133,8 @@ class _DiscoveryPanelState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ button, + if (widget.discovery is BrowserServerDiscovery) + const Text('Searches this server’s local network.'), ?status, for (final server in _servers) _row(context, cupertino, server), ], diff --git a/app/lib/features/onboarding/discovery/server_discovery.dart b/app/lib/features/onboarding/discovery/server_discovery.dart index 3e8d41ac..033a1e7c 100644 --- a/app/lib/features/onboarding/discovery/server_discovery.dart +++ b/app/lib/features/onboarding/discovery/server_discovery.dart @@ -1,6 +1,7 @@ import 'package:flutter/foundation.dart'; import 'bonsoir_server_discovery.dart'; +import 'browser_server_discovery.dart'; import 'discovered_server.dart'; /// Finds Pipelines servers on the local network. @@ -12,7 +13,7 @@ abstract interface class ServerDiscovery { /// The discovery this platform supports, or null where there is none. /// -/// Browsers cannot send mDNS, and the web app is served by the server it -/// talks to, so web has no scan. +/// Browsers ask their authenticated front door to browse its LAN. Native +/// clients browse directly through the platform DNS-SD service. ServerDiscovery? platformServerDiscovery({bool web = kIsWeb}) => - web ? null : BonsoirServerDiscovery(); + web ? BrowserServerDiscovery() : BonsoirServerDiscovery(); diff --git a/app/lib/features/onboarding/onboarding_flow.dart b/app/lib/features/onboarding/onboarding_flow.dart index d0954f52..228084d4 100644 --- a/app/lib/features/onboarding/onboarding_flow.dart +++ b/app/lib/features/onboarding/onboarding_flow.dart @@ -26,6 +26,7 @@ class OnboardingFlow extends StatefulWidget { this.check = ServerSession.check, this.signIn = ServerSession.signIn, this.saveServer, + this.saveServerProfile, this.savedServers, this.serverAddresses = const [], this.discovery, @@ -42,10 +43,11 @@ class OnboardingFlow extends StatefulWidget { final ServerCheck check; final ServerSignIn signIn; final Future Function(String url)? saveServer; + final Future Function(String url, String name)? saveServerProfile; final Widget? savedServers; final List serverAddresses; - /// LAN discovery; null hides the scan (web, or no platform support). + /// Network discovery; null hides the scan when no service was supplied. final ServerDiscovery? discovery; @override @@ -57,6 +59,7 @@ class _OnboardingFlowState extends State { text: widget.initialServer, ); final TextEditingController _password = TextEditingController(); + final TextEditingController _name = TextEditingController(); late bool _passwordStep = widget.startAtPassword; Uri? _endpoint; bool _busy = false; @@ -72,6 +75,7 @@ class _OnboardingFlowState extends State { void dispose() { _server.dispose(); _password.dispose(); + _name.dispose(); super.dispose(); } @@ -120,7 +124,14 @@ class _OnboardingFlowState extends State { return; } try { - await widget.saveServer?.call(endpoint.toString()); + if (widget.saveServerProfile != null) { + await widget.saveServerProfile!( + endpoint.toString(), + _name.text.trim().isEmpty ? endpoint.host : _name.text.trim(), + ); + } else { + await widget.saveServer?.call(endpoint.toString()); + } } catch (error) { if (mounted) { setState(() { @@ -143,8 +154,11 @@ class _OnboardingFlowState extends State { } void _useDiscovered(DiscoveredServer server) { - _server.text = server.endpoint.toString(); - _continue(); + setState(() { + _server.text = server.endpoint.toString(); + _name.text = server.name; + _error = null; + }); } Future _signIn() async { @@ -241,6 +255,16 @@ class _OnboardingFlowState extends State { Text(lead), const SizedBox(height: 24), field, + if (!_passwordStep) ...[ + const SizedBox(height: 12), + _field( + cupertino, + key: const Key('onboarding-server-name'), + controller: _name, + hint: 'Machine name', + onSubmitted: _continue, + ), + ], if (_error != null) ...[ const SizedBox(height: 8), Text( diff --git a/app/lib/features/settings/saved_server_editor.dart b/app/lib/features/settings/saved_server_editor.dart index 373cfa36..c2728eab 100644 --- a/app/lib/features/settings/saved_server_editor.dart +++ b/app/lib/features/settings/saved_server_editor.dart @@ -4,15 +4,23 @@ import 'package:flutter/material.dart'; import '../../ui/adaptive/segmented_bar.dart'; import '../../core/servers/server_catalog.dart'; import '../../ui/adaptive/host.dart'; +import '../onboarding/discovery/discovered_server.dart'; +import '../onboarding/discovery/discovery_panel.dart'; +import '../onboarding/discovery/server_discovery.dart'; /// When supplied, [onSave] must finish successfully before the route closes. /// Throwing keeps the draft open and displays the error for a retry. Future editSavedServer( BuildContext context, { SavedServer? server, + ServerDiscovery? discovery, Future Function(SavedServer)? onSave, }) { - final page = _ServerEditor(server: server, onSave: onSave); + final page = _ServerEditor( + server: server, + onSave: onSave, + discovery: discovery ?? platformServerDiscovery(), + ); return Navigator.of(context).push( usesCupertinoHost(context) ? CupertinoPageRoute(builder: (_) => page) @@ -21,7 +29,8 @@ Future editSavedServer( } class _ServerEditor extends StatefulWidget { - const _ServerEditor({this.server, this.onSave}); + const _ServerEditor({this.server, this.onSave, this.discovery}); + final ServerDiscovery? discovery; final SavedServer? server; final Future Function(SavedServer)? onSave; @@ -41,6 +50,14 @@ class _ServerEditorState extends State<_ServerEditor> { String? _error; bool _saving = false; + void _useDiscovered(DiscoveredServer server) { + setState(() { + _name.text = server.name; + _addresses.text = server.endpoint.toString(); + _error = null; + }); + } + Future _save() async { if (_saving) return; try { @@ -136,6 +153,14 @@ class _ServerEditorState extends State<_ServerEditor> { child: ListView( padding: const EdgeInsets.all(16), children: [ + if (widget.server == null && widget.discovery != null) ...[ + DiscoveryPanel( + discovery: widget.discovery!, + enabled: !_saving, + onSelect: _useDiscovered, + ), + const SizedBox(height: 16), + ], _field(_name, 'Server name', key: 'server-profile-name'), const SizedBox(height: 16), _field( diff --git a/app/notes/browser-network-discovery.md b/app/notes/browser-network-discovery.md new file mode 100644 index 00000000..86837493 --- /dev/null +++ b/app/notes/browser-network-discovery.md @@ -0,0 +1,16 @@ +# Browser discovery and machine names + +Browser discovery uses the authenticated same-origin `/api/discovery` endpoint, +which browses the hosting server's LAN. Native discovery still uses Bonjour. +Malformed announcements cannot hide valid machines; failed/unsupported discovery +is reported instead of being shown as an empty successful scan. Finite browser +scans stop their progress indicator when the reply arrives. + +Add server now includes discovery, prefills an editable machine name/address, +and saves only after explicit review. Onboarding likewise reviews and persists +the discovered name before probing/signing in. Root wires saveServerProfile. + +Verification: 34 focused discovery/onboarding/saved-server tests passed, including +name editing, no premature connection, browser errors/duplicates/default ports, +and native discovery regressions. Browser captures follow after fixture build; +this note does not yet claim rendered or deployed evidence. diff --git a/app/test/features/onboarding/discovery/browser_server_discovery_test.dart b/app/test/features/onboarding/discovery/browser_server_discovery_test.dart new file mode 100644 index 00000000..3c22d0f0 --- /dev/null +++ b/app/test/features/onboarding/discovery/browser_server_discovery_test.dart @@ -0,0 +1,60 @@ +import 'dart:convert'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/onboarding/discovery/browser_server_discovery.dart'; + +void main() { + test( + 'browser parses names, default ports, auth and deduplicates endpoints', + () async { + final scan = BrowserServerDiscovery( + fetch: () async => jsonEncode({ + 'discovered_servers': [ + { + 'name': 'Linux', + 'endpoint': 'ws://192.168.1.5:8083/connect', + 'auth': 'password', + 'version': 'v1', + }, + { + 'name': 'Linux', + 'endpoint': 'ws://192.168.1.5:8083/connect', + 'auth': 'password', + }, + { + 'name': 'Mac', + 'endpoint': 'wss://mac.local/connect', + 'auth': 'none', + }, + {'name': 'Bad', 'endpoint': 'ws://password@host/connect'}, + {'name': '', 'endpoint': 'ws://host/connect'}, + {'name': 'Fragment', 'endpoint': 'ws://host/connect#secret'}, + ], + }), + ); + final values = await scan.scan().single; + expect(values.map((s) => s.name), ['Linux', 'Mac']); + expect(values.first.passwordRequired, isTrue); + expect(values.last.passwordRequired, isFalse); + expect(values.last.port, 443); + }, + ); + test('unknown and malformed discovery responses report failure', () async { + for (final body in ['not json', '{}', '{"discovered_servers":null}']) { + await expectLater( + BrowserServerDiscovery(fetch: () async => body).scan(), + emitsError(isA()), + ); + } + }); + test( + 'network failure is surfaced instead of pretending no machines exist', + () async { + await expectLater( + BrowserServerDiscovery( + fetch: () async => throw StateError('offline'), + ).scan(), + emitsError(isA()), + ); + }, + ); +} diff --git a/app/test/features/onboarding/discovery/discovered_server_test.dart b/app/test/features/onboarding/discovery/discovered_server_test.dart index 9f2d7099..e3bc3412 100644 --- a/app/test/features/onboarding/discovery/discovered_server_test.dart +++ b/app/test/features/onboarding/discovery/discovered_server_test.dart @@ -61,8 +61,8 @@ void main() { ); }); - test('web has no discovery; native platforms do', () { - expect(platformServerDiscovery(web: true), isNull); + test('web and native platforms provide discovery', () { + expect(platformServerDiscovery(web: true), isNotNull); expect(platformServerDiscovery(web: false), isNotNull); }); } diff --git a/app/test/features/onboarding/discovery/discovery_panel_test.dart b/app/test/features/onboarding/discovery/discovery_panel_test.dart index b95650b6..8dbb2780 100644 --- a/app/test/features/onboarding/discovery/discovery_panel_test.dart +++ b/app/test/features/onboarding/discovery/discovery_panel_test.dart @@ -90,7 +90,7 @@ void main() { expect(find.text('Search again'), findsOneWidget); }); - testWidgets('tapping a server fills the address and connects', ( + testWidgets('tapping a server reviews its name before connecting', ( tester, ) async { await tester.pumpWidget(host(flow(discoverer: discovery))); @@ -101,6 +101,10 @@ void main() { await tester.tap(find.byKey(const Key('discovered-192.168.1.20:8083'))); await tester.pumpAndSettle(); + expect(checked, isEmpty); + await tester.ensureVisible(find.byKey(const Key('onboarding-next'))); + await tester.tap(find.byKey(const Key('onboarding-next'))); + await tester.pumpAndSettle(); final endpoint = Uri.parse('ws://192.168.1.20:8083/connect'); expect(checked, [endpoint]); expect(saved, [endpoint.toString()]); @@ -151,6 +155,10 @@ void main() { expect(find.byType(CupertinoListTile), findsOneWidget); await tester.tap(find.byKey(const Key('discovered-192.168.1.30:8080'))); await tester.pumpAndSettle(); + expect(checked, isEmpty); + await tester.ensureVisible(find.byKey(const Key('onboarding-next'))); + await tester.tap(find.byKey(const Key('onboarding-next'))); + await tester.pumpAndSettle(); expect(checked, [Uri.parse('ws://192.168.1.30:8080/connect')]); }); diff --git a/app/test/features/settings/saved_server_discovery_test.dart b/app/test/features/settings/saved_server_discovery_test.dart new file mode 100644 index 00000000..96797829 --- /dev/null +++ b/app/test/features/settings/saved_server_discovery_test.dart @@ -0,0 +1,124 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/features/settings/saved_server_editor.dart'; +import 'package:pipelines_app/features/onboarding/discovery/browser_server_discovery.dart'; +import 'package:pipelines_app/features/onboarding/onboarding_flow.dart'; +import 'package:pipelines_app/core/session/server_session.dart'; + +BrowserServerDiscovery discovery() => BrowserServerDiscovery( + fetch: () async => jsonEncode({ + 'discovered_servers': [ + { + 'name': 'Linux laptop', + 'endpoint': 'ws://192.168.1.5:8083/connect', + 'auth': 'password', + }, + ], + }), +); + +void main() { + testWidgets( + 'choosing a discovered machine prefills editable name and address', + (tester) async { + SavedServer? saved; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => editSavedServer( + context, + discovery: discovery(), + onSave: (value) async { + saved = value; + }, + ), + child: const Text('Add server'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Add server')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Linux laptop')); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byKey(const Key('server-profile-name'))) + .controller! + .text, + 'Linux laptop', + ); + expect( + tester + .widget( + find.byKey(const Key('server-profile-addresses')), + ) + .controller! + .text, + 'ws://192.168.1.5:8083/connect', + ); + expect(saved, isNull); + await tester.enterText( + find.byKey(const Key('server-profile-name')), + 'My Linux', + ); + await tester.ensureVisible(find.text('Save server')); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + expect(saved!.name, 'My Linux'); + expect(saved!.endpoints, ['ws://192.168.1.5:8083/connect']); + }, + ); + testWidgets('onboarding reviews and persists machine name before sign-in', ( + tester, + ) async { + var checks = 0; + String? alias; + await tester.pumpWidget( + MaterialApp( + home: OnboardingFlow( + onDone: (_) {}, + discovery: discovery(), + check: (_) async { + checks++; + return SessionState.signedOut; + }, + saveServerProfile: (url, name) async { + alias = name; + }, + ), + ), + ); + await tester.ensureVisible(find.byKey(const Key('discovery-scan'))); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.text('Linux laptop')); + await tester.tap(find.text('Linux laptop')); + await tester.pumpAndSettle(); + expect(checks, 0); + expect( + tester + .widget(find.byKey(const Key('onboarding-server-name'))) + .controller! + .text, + 'Linux laptop', + ); + await tester.enterText( + find.byKey(const Key('onboarding-server-name')), + 'Workstation', + ); + await tester.ensureVisible(find.byKey(const Key('onboarding-next'))); + await tester.tap(find.byKey(const Key('onboarding-next'))); + await tester.pumpAndSettle(); + expect(checks, 1); + expect(alias, 'Workstation'); + expect(find.byKey(const Key('onboarding-password')), findsOneWidget); + }); +}