Find LAN servers from browser and review discovered machine names

This commit is contained in:
2026-11-08 21:50:27 +00:00
parent 828227f549
commit ae8fe49e41
12 changed files with 371 additions and 12 deletions
@@ -0,0 +1,3 @@
Future<String> fetchDiscovery() => Future.error(
UnsupportedError('Browser discovery requires the web client.'),
);
@@ -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<JSString> text();
}
Future<String> 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;
}
@@ -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<String> Function()? fetch})
: _fetch = fetch ?? impl.fetchDiscovery;
final Future<String> Function() _fetch;
@override
Stream<List<DiscoveredServer>> 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 = <Uri, DiscoveredServer>{};
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();
}
}
@@ -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<DiscoveryPanel> {
(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<DiscoveryPanel> {
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),
],
@@ -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();
@@ -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<void> Function(String url)? saveServer;
final Future<void> Function(String url, String name)? saveServerProfile;
final Widget? savedServers;
final List<Uri> 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<OnboardingFlow> {
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<OnboardingFlow> {
void dispose() {
_server.dispose();
_password.dispose();
_name.dispose();
super.dispose();
}
@@ -120,7 +124,14 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
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<OnboardingFlow> {
}
void _useDiscovered(DiscoveredServer server) {
_server.text = server.endpoint.toString();
_continue();
setState(() {
_server.text = server.endpoint.toString();
_name.text = server.name;
_error = null;
});
}
Future<void> _signIn() async {
@@ -241,6 +255,16 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
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(
@@ -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<SavedServer?> editSavedServer(
BuildContext context, {
SavedServer? server,
ServerDiscovery? discovery,
Future<void> 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<SavedServer>(
usesCupertinoHost(context)
? CupertinoPageRoute(builder: (_) => page)
@@ -21,7 +29,8 @@ Future<SavedServer?> 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<void> 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<void> _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(
+16
View File
@@ -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.
@@ -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<FormatException>()),
);
}
});
test(
'network failure is surfaced instead of pretending no machines exist',
() async {
await expectLater(
BrowserServerDiscovery(
fetch: () async => throw StateError('offline'),
).scan(),
emitsError(isA<StateError>()),
);
},
);
}
@@ -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);
});
}
@@ -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')]);
});
@@ -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<TextField>(find.byKey(const Key('server-profile-name')))
.controller!
.text,
'Linux laptop',
);
expect(
tester
.widget<TextField>(
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<TextField>(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);
});
}