From c264f865ffb0a19e032f394bd2e8a6847d4e47b8 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 2 Dec 2026 15:58:28 +0000 Subject: [PATCH] Servers: name a machine after its hostname once it connects A saved server still named by the app ('My server', 'This server', 'Original legacy server' or its address host/IP) takes the hostname the machine reports in get_status the first time the app connects; typed names are kept. New servers (legacy migration, Settings with a blank name, onboarding) start with the address host. A browser on its page origin with no saved profile shows the reported hostname too. No server change: get_status already reports the hostname. Co-Authored-By: Claude Opus 5.5 --- app/lib/application/app_terminals.dart | 6 +- app/lib/application/pipelines_app.dart | 41 ++++- .../core/servers/chat/chat_server_pool.dart | 21 +++ .../core/servers/server_catalog_store.dart | 4 +- app/lib/core/servers/server_context.dart | 3 + app/lib/core/servers/server_naming.dart | 62 +++++++ .../settings/saved_server_editor.dart | 19 +- .../features/settings/server_connections.dart | 45 +++++ .../features/terminal/terminal_machines.dart | 6 +- app/test/application/app_terminals_test.dart | 2 +- .../server_hostname_wiring_test.dart | 123 +++++++++++++ .../servers/chat/chat_server_pool_test.dart | 61 ++++++- .../servers/server_catalog_store_test.dart | 2 +- app/test/core/servers/server_naming_test.dart | 83 +++++++++ .../settings/server_hostname_test.dart | 168 ++++++++++++++++++ app/tool/search_selection_probe_entry.dart | 32 +++- 16 files changed, 654 insertions(+), 24 deletions(-) create mode 100644 app/lib/core/servers/server_naming.dart create mode 100644 app/test/application/server_hostname_wiring_test.dart create mode 100644 app/test/core/servers/server_naming_test.dart create mode 100644 app/test/features/settings/server_hostname_test.dart diff --git a/app/lib/application/app_terminals.dart b/app/lib/application/app_terminals.dart index 3977467a..81c3aed3 100644 --- a/app/lib/application/app_terminals.dart +++ b/app/lib/application/app_terminals.dart @@ -21,7 +21,7 @@ class AppTerminals { required bool Function() connected, required ApiGateway gateway, required String machineId, - required String machineName, + required String Function() machineName, required this.layout, WindowManager? windows, }) : machines = pool != null @@ -29,9 +29,9 @@ class AppTerminals { : SingleTerminalMachines( connection: connection, connected: connected, - machine: TerminalMachine( + machine: () => TerminalMachine( id: machineId, - name: machineName, + name: machineName(), gateway: gateway, ), ) { diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 9f05400b..dc8f289c 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -58,6 +58,7 @@ import '../features/terminal/terminal_layout.dart'; import 'app_route.dart'; import 'app_router.dart'; import 'app_session.dart'; +import '../core/servers/server_naming.dart'; import 'chat_destination.dart'; import 'pipelines_destination.dart'; import 'runs_destination.dart'; @@ -357,16 +358,15 @@ class _PipelinesAppState extends State _session.addListener(_chatSyncChanged); widget.chatPool?.addListener(_chatSyncChanged); _chatSyncChanged(); + _session.addListener(_learnServerHostname); + _learnServerHostname(); _terminals = AppTerminals( pool: widget.chatPool, - connection: _session, + connection: Listenable.merge([_session, ?widget.servers]), connected: () => _session.connected, gateway: _session.gateway, machineId: widget.serverId ?? 'server', - machineName: - widget.servers?.catalog.active?.name ?? - widget.server.uri?.host ?? - 'This server', + machineName: _serverName, layout: widget.terminalLayout ?? TerminalLayout.instance, windows: _windows, ); @@ -605,6 +605,7 @@ class _PipelinesAppState extends State } _terminals.dispose(); _session.removeListener(_chatSyncChanged); + _session.removeListener(_learnServerHostname); widget.chatPool?.removeListener(_chatSyncChanged); _chatWindows.dispose(); _diffWindows.dispose(); @@ -935,6 +936,36 @@ class _PipelinesAppState extends State } /// A replaced socket makes open chats re-subscribe, also in windows. + /// This server's name: its saved name, the hostname a browser's unsaved + /// page origin reported, else its address. + String _serverName() { + final servers = widget.servers; + final saved = servers?.catalog.servers + .where((server) => server.id == widget.serverId) + .firstOrNull; + final host = widget.server.uri?.host ?? ''; + return saved?.name ?? + servers?.originHostname ?? + (host.isEmpty ? 'This server' : host); + } + + bool _hostnameAsked = false; + + /// Asks this server once for its hostname, which names a server the app + /// named by its address. The chat pool already asks every saved machine. + void _learnServerHostname() { + final servers = widget.servers; + if (_hostnameAsked || servers == null || !_session.connected) return; + if (widget.chatPool != null && widget.serverId != null) return; + _hostnameAsked = true; + final serverId = widget.serverId; + unawaited( + fetchServerHostname(_session.gateway).then((hostname) { + if (mounted) unawaited(servers.learnHostname(serverId, hostname)); + }), + ); + } + void _chatSyncChanged() => _chatRuntime.syncToken.value = widget.chatPool?.revision ?? _session.connectionEpoch; diff --git a/app/lib/core/servers/chat/chat_server_pool.dart b/app/lib/core/servers/chat/chat_server_pool.dart index d68b0a1c..aa12752b 100644 --- a/app/lib/core/servers/chat/chat_server_pool.dart +++ b/app/lib/core/servers/chat/chat_server_pool.dart @@ -10,6 +10,7 @@ import '../../transport/pipelines_client.dart'; import '../../../features/settings/server_connections.dart'; import '../machine_access.dart'; import '../server_catalog.dart'; +import '../server_naming.dart'; import 'browser_peer.dart'; import 'chat_server_gateway.dart'; import 'federated_chat_gateway.dart'; @@ -27,6 +28,9 @@ class ChatMachineStatus { /// Why the machine is not connected, once classified; null while unknown. MachineAccessResult? access; + + /// The machine reported its hostname to this pool; asked once per pool. + bool hostnameKnown = false; } /// Probes one saved machine with its own kept sign-in (see @@ -180,6 +184,7 @@ class ChatServerPool extends ChangeNotifier implements MachineAuthenticator { if (item.connected && !was) { revision++; unawaited(ackSync.connected()); + unawaited(_learnHostname(item, generation)); } if (!item.connected && !item.connecting && item.access == null) { unawaited(_classify(item, generation)); @@ -189,6 +194,7 @@ class ChatServerPool extends ChangeNotifier implements MachineAuthenticator { revision++; if (item.connected) { unawaited(ackSync.connected()); + unawaited(_learnHostname(item, generation)); } else { unawaited(_classify(item, generation)); } @@ -207,6 +213,21 @@ class ChatServerPool extends ChangeNotifier implements MachineAuthenticator { if (!_disposed) notifyListeners(); } + /// Names a machine the app named by its address after the hostname it + /// reports (see [ServerConnections.learnHostname]); typed names are kept. + Future _learnHostname(ChatMachineStatus item, int generation) async { + final adapter = item.adapter; + if (item.hostnameKnown || adapter == null) return; + item.hostnameKnown = true; + final hostname = await fetchServerHostname(adapter.gateway); + if (_disposed || generation != item.generation) return; + if (hostname.isEmpty) { + item.hostnameKnown = false; + return; + } + await servers.learnHostname(item.server.id, hostname); + } + /// A native socket that did not open says nothing about why. Ask the web /// login with this machine's own kept sign-in: a form means it wants its /// password, a redirect means the sign-in is fine and the socket failed. diff --git a/app/lib/core/servers/server_catalog_store.dart b/app/lib/core/servers/server_catalog_store.dart index 246d2f6d..f3392e1e 100644 --- a/app/lib/core/servers/server_catalog_store.dart +++ b/app/lib/core/servers/server_catalog_store.dart @@ -4,6 +4,7 @@ import 'dart:math'; import 'package:shared_preferences/shared_preferences.dart'; import 'server_catalog.dart'; +import 'server_naming.dart'; import '../transport/server_url.dart'; const String serverCatalogKey = 'pipelines.next.serverCatalog.v1'; @@ -27,7 +28,8 @@ ServerCatalog _migrate(String legacyEndpoint, [List? binding]) { servers: [ SavedServer.validated( id: id, - name: 'My server', + // Its address names it until the machine reports its hostname. + name: temporaryServerName(legacyEndpoint), endpoints: [legacyEndpoint], legacyEndpoint: canMigrate ? legacyEndpoint : null, ), diff --git a/app/lib/core/servers/server_context.dart b/app/lib/core/servers/server_context.dart index a27cfd05..e1707dcb 100644 --- a/app/lib/core/servers/server_context.dart +++ b/app/lib/core/servers/server_context.dart @@ -15,7 +15,10 @@ class ServerContext extends InheritedNotifier { static ServerContext? maybeOf(BuildContext context) => context.dependOnInheritedWidgetOfExactType(); + /// The machine's name; a browser's unsaved page origin is named by the + /// hostname it reported. String? get name { + if (serverId == null) return notifier!.originHostname; for (final server in notifier!.catalog.servers) { if (server.id == serverId) return server.name; } diff --git a/app/lib/core/servers/server_naming.dart b/app/lib/core/servers/server_naming.dart new file mode 100644 index 00000000..5ebb7f8d --- /dev/null +++ b/app/lib/core/servers/server_naming.dart @@ -0,0 +1,62 @@ +import '../api_gateway.dart'; +import 'server_catalog.dart'; + +/// Names the app itself gave a machine before it knew better. Older builds +/// saved these; a machine named one of them takes its own hostname instead. +const Set placeholderServerNames = { + 'My server', + 'This server', + 'Original legacy server', +}; + +/// The temporary name of a machine reached at [url]: its address's host. +String temporaryServerName(String url) { + final host = Uri.tryParse(url.trim())?.host ?? ''; + return host.isEmpty ? url.trim() : host; +} + +/// Whether [server] still carries a name the app chose: a placeholder, or +/// exactly the host (or IP) of one of its addresses. A name the operator +/// typed is anything else and is never replaced. +bool hasPlaceholderName(SavedServer server) { + final name = server.name.trim(); + if (placeholderServerNames.contains(name)) return true; + final lower = name.toLowerCase(); + return server.endpoints.any( + (url) => temporaryServerName(url).toLowerCase() == lower, + ); +} + +/// [server] renamed to the [hostname] its machine reports, or null when it +/// keeps its name: the name is the operator's, or the hostname is empty or +/// already the name. +SavedServer? renamedToHostname(SavedServer server, String hostname) { + final name = hostname.trim(); + if (name.isEmpty || name == server.name || !hasPlaceholderName(server)) { + return null; + } + return SavedServer.validated( + id: server.id, + name: name, + endpoints: server.endpoints, + legacyEndpoint: server.legacyEndpoint, + ); +} + +/// The machine's own hostname from a `get_status` reply, or '' when absent. +String hostnameFromStatus(JsonMap reply) { + final status = reply['status']; + if (status is! Map) return ''; + final hostname = status['hostname']; + return hostname is String ? hostname.trim() : ''; +} + +/// Asks the machine behind [gateway] for its hostname; '' when it cannot say +/// (an older server, a refused request or a dropped connection). +Future fetchServerHostname(ApiGateway gateway) async { + try { + return hostnameFromStatus(await gateway.call('get_status')); + } catch (_) { + return ''; + } +} diff --git a/app/lib/features/settings/saved_server_editor.dart b/app/lib/features/settings/saved_server_editor.dart index fd88e248..fccec002 100644 --- a/app/lib/features/settings/saved_server_editor.dart +++ b/app/lib/features/settings/saved_server_editor.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../core/servers/machine_access.dart'; import '../../core/servers/server_catalog.dart'; +import '../../core/servers/server_naming.dart'; import '../../ui/adaptive/segmented_bar.dart'; import '../onboarding/discovery/discovered_server.dart'; import '../onboarding/discovery/discovery_panel.dart'; @@ -72,13 +73,19 @@ class _ServerEditorState extends State<_ServerEditor> { Future _save() async { if (_saving) return; try { + final endpoints = _addresses.text + .split('\n') + .where((line) => line.trim().isNotEmpty) + .toList(); + // A blank name is the address's host until the machine reports its + // hostname, which then names it. final server = SavedServer.validated( id: _id, - name: _name.text, + name: _name.text.trim().isEmpty && endpoints.isNotEmpty + ? temporaryServerName(endpoints.first) + : _name.text, legacyEndpoint: widget.server?.legacyEndpoint, - endpoints: _addresses.text - .split('\n') - .where((line) => line.trim().isNotEmpty), + endpoints: endpoints, ); setState(() { _saving = true; @@ -173,6 +180,10 @@ class _ServerEditorState extends State<_ServerEditor> { const SizedBox(height: 16), ], _field(_name, 'Server name', key: 'server-profile-name'), + const SizedBox(height: 8), + const Text( + 'Leave blank to use the machine\'s own name once it connects.', + ), const SizedBox(height: 16), _field( _addresses, diff --git a/app/lib/features/settings/server_connections.dart b/app/lib/features/settings/server_connections.dart index ef485709..1a7afb26 100644 --- a/app/lib/features/settings/server_connections.dart +++ b/app/lib/features/settings/server_connections.dart @@ -1,8 +1,11 @@ +import 'dart:async'; + import 'package:flutter/foundation.dart'; import '../../core/servers/machine_access.dart'; import '../../core/servers/server_catalog.dart'; import '../../core/servers/server_catalog_store.dart'; +import '../../core/servers/server_naming.dart'; /// Saved configurations are committed before switching the app's connection. /// A failed save leaves the old selection and its live socket unchanged. @@ -79,6 +82,47 @@ class ServerConnections extends ChangeNotifier { bool get busy => _busy; String? get error => _error; + String? _originHostname; + + /// The hostname of the page-origin server a browser uses with no saved + /// profile for it; it names that server, which has no catalog entry. + String? get originHostname => _originHostname; + + final _learned = {}; + + /// Records the [hostname] the machine [id] reported. A saved machine still + /// named by the app (see [hasPlaceholderName]) is renamed and saved; a name + /// the operator typed is kept. A null [id] is the unsaved page origin. + /// A change already in progress defers the rename until it finishes. + Future learnHostname(String? id, String hostname) async { + final name = hostname.trim(); + if (_disposed || name.isEmpty) return false; + if (id == null) { + if (_originHostname == name) return false; + _originHostname = name; + _notify(); + return true; + } + _learned[id] = name; + return _applyLearnedNames(); + } + + Future _applyLearnedNames() async { + if (_busy || _disposed || _learned.isEmpty) return false; + final learned = Map.of(_learned); + _learned.clear(); + var next = _catalog; + for (final server in _catalog.servers) { + final hostname = learned[server.id]; + final renamed = hostname == null + ? null + : renamedToHostname(server, hostname); + if (renamed != null) next = next.upsert(renamed); + } + if (identical(next, _catalog)) return false; + return _change(() => next, activate: false); + } + /// Browsers always connect to their page origin, even after Back or a failed /// cross-origin navigation. Do not label another saved profile as active. void alignBrowserOrigin(Uri endpoint) { @@ -181,6 +225,7 @@ class ServerConnections extends ChangeNotifier { } finally { _busy = false; _notify(); + if (_learned.isNotEmpty) scheduleMicrotask(_applyLearnedNames); } } diff --git a/app/lib/features/terminal/terminal_machines.dart b/app/lib/features/terminal/terminal_machines.dart index 409baaeb..b364db76 100644 --- a/app/lib/features/terminal/terminal_machines.dart +++ b/app/lib/features/terminal/terminal_machines.dart @@ -65,11 +65,13 @@ class SingleTerminalMachines extends ValueNotifier> { } final Listenable connection; - final TerminalMachine machine; + + /// The machine as named now; [connection] also notifies a rename. + final TerminalMachine Function() machine; final bool Function() connected; void _update() { - final next = connected() ? [machine] : const []; + final next = connected() ? [machine()] : const []; if (!_same(next, value)) value = next; } diff --git a/app/test/application/app_terminals_test.dart b/app/test/application/app_terminals_test.dart index 6a079cee..148cf547 100644 --- a/app/test/application/app_terminals_test.dart +++ b/app/test/application/app_terminals_test.dart @@ -18,7 +18,7 @@ void main() { connected: () => true, gateway: gateway, machineId: 'mac', - machineName: 'Mac', + machineName: () => 'Mac', layout: TerminalLayout(store: MemoryLayoutStore()), ); }); diff --git a/app/test/application/server_hostname_wiring_test.dart b/app/test/application/server_hostname_wiring_test.dart new file mode 100644 index 00000000..9aa65b0a --- /dev/null +++ b/app/test/application/server_hostname_wiring_test.dart @@ -0,0 +1,123 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/application/pipelines_root.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/core/session/server_session.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +/// Answers the app's `get_status` with [hostname] and refuses every other +/// request: the client sends one request at a time. +Future answerStatus( + WidgetTester tester, + FakeChannel channel, + String hostname, +) async { + final answered = {}; + for (var frame = 0; frame < 24; frame++) { + await tester.pump(const Duration(milliseconds: 20)); + for (final raw in List.of(channel.outgoing)) { + final message = jsonDecode('$raw') as Map; + final id = '${message['id']}'; + if (message['type'] == 'subscribe' || !answered.add(id)) continue; + channel.incoming.add( + jsonEncode( + message['type'] == 'get_status' + ? { + 'type': 'status', + 'id': id, + 'status': {'hostname': hostname}, + } + : {'type': 'error', 'id': id, 'error': 'not in this fixture'}, + ), + ); + } + } +} + +void main() { + testWidgets('connecting renames the legacy "My server" to its hostname', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({ + 'pipelines.session.v2.legacy-server.cookie': 'pipelines_session=x', + }); + await ServerSession.load(); + final legacy = SavedServer.validated( + id: 'legacy-server', + name: 'My server', + endpoints: ['ws://192.168.1.2:8083/connect'], + ); + final store = MemoryServerCatalogStore( + catalog: ServerCatalog(servers: [legacy], selectedId: legacy.id), + ); + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + await tester.pumpWidget( + PipelinesRoot( + federatedChats: false, + nativeUpdatesSupported: false, + server: ServerEndpoint.resolve( + base: Uri.parse('file:///'), + web: false, + configured: legacy.endpoints.first, + ), + catalogStore: store, + check: (_) async => SessionState.signedIn, + clientFactory: () => client, + ), + ); + await answerStatus(tester, channel, 'tank'); + expect(store.catalog!.active!.name, 'tank'); + expect(store.catalog!.active!.id, 'legacy-server'); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); + + testWidgets('a name the operator typed is kept after connecting', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({ + 'pipelines.session.v2.home.cookie': 'pipelines_session=x', + }); + await ServerSession.load(); + final home = SavedServer.validated( + id: 'home', + name: 'Home', + endpoints: ['ws://192.168.1.2:8083/connect'], + ); + final store = MemoryServerCatalogStore( + catalog: ServerCatalog(servers: [home], selectedId: home.id), + ); + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + await tester.pumpWidget( + PipelinesRoot( + federatedChats: false, + nativeUpdatesSupported: false, + server: ServerEndpoint.resolve( + base: Uri.parse('file:///'), + web: false, + configured: home.endpoints.first, + ), + catalogStore: store, + check: (_) async => SessionState.signedIn, + clientFactory: () => client, + ), + ); + await answerStatus(tester, channel, 'tank'); + expect( + channel.outgoing.where((raw) => '$raw'.contains('"get_status"')), + hasLength(1), + ); + expect(store.catalog!.active!.name, 'Home'); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); +} diff --git a/app/test/core/servers/chat/chat_server_pool_test.dart b/app/test/core/servers/chat/chat_server_pool_test.dart index e640f0a8..5925b9e8 100644 --- a/app/test/core/servers/chat/chat_server_pool_test.dart +++ b/app/test/core/servers/chat/chat_server_pool_test.dart @@ -12,11 +12,22 @@ import 'package:pipelines_app/features/settings/server_connections.dart'; class _Gateway implements ApiGateway { final events = StreamController.broadcast(); + String? hostname; + final calls = []; @override Stream get frames => events.stream; @override - Future call(String type, [JsonMap fields = const {}]) async => - type == 'attention_acks' || type == 'ack_attention' + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(type); + return _reply(type); + } + + JsonMap _reply(String type) => type == 'get_status' && hostname != null + ? { + 'type': 'status', + 'status': {'hostname': hostname}, + } + : type == 'attention_acks' || type == 'ack_attention' ? { 'type': 'attention_acks', 'attention_acks': {'chat_seen': {}, 'dismissed': []}, @@ -82,6 +93,52 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); setUp(() => SharedPreferences.setMockInitialValues({})); + test('a connected machine named by its address takes its hostname', () async { + final placeholder = SavedServer.validated( + id: 'one', + name: 'one.test', + endpoints: ['ws://one.test:8083/connect'], + ); + final typed = SavedServer.validated( + id: 'two', + name: 'Laptop', + endpoints: ['ws://two.test:8083/connect'], + ); + final servers = await _servers([placeholder, typed]); + final machines = <_Machine>[]; + final pool = ChatServerPool( + servers, + web: false, + connect: (server) async { + final machine = _Machine(server) + ..gateway.hostname = server.id == 'one' ? 'tank' : 'mac-mini'; + machines.add(machine); + return machine.connection; + }, + ); + try { + await _flush(); + expect(servers.catalog.servers.map((s) => s.name), ['tank', 'Laptop']); + expect(pool.machines.first.adapter!.server.name, 'tank'); + // Asked once per machine, not on every reconnect. + machines.first.states.add( + const ConnectionState(ConnectionKind.connected), + ); + await _flush(); + expect( + machines.first.gateway.calls.where((type) => type == 'get_status'), + hasLength(1), + ); + } finally { + pool.dispose(); + servers.dispose(); + await _flush(); + for (final machine in machines) { + await machine.finish(); + } + } + }); + test('an older async detach cannot close a newer connection', () async { final profile = _server('one'); final servers = await _servers([profile]); diff --git a/app/test/core/servers/server_catalog_store_test.dart b/app/test/core/servers/server_catalog_store_test.dart index 06198efd..65ba525e 100644 --- a/app/test/core/servers/server_catalog_store_test.dart +++ b/app/test/core/servers/server_catalog_store_test.dart @@ -178,7 +178,7 @@ void main() { }); final migrated = await store.load(legacyEndpoint: legacy); expect(migrated.selectedId, 'legacy-server'); - expect(migrated.active!.name, 'My server'); + expect(migrated.active!.name, 'legacy.test'); expect(migrated.active!.endpoints, ['ws://legacy.test/connect']); final preferences = await SharedPreferences.getInstance(); expect(preferences.containsKey(serverCatalogKey), isFalse); diff --git a/app/test/core/servers/server_naming_test.dart b/app/test/core/servers/server_naming_test.dart new file mode 100644 index 00000000..06856716 --- /dev/null +++ b/app/test/core/servers/server_naming_test.dart @@ -0,0 +1,83 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/core/servers/server_naming.dart'; + +SavedServer named(String name, [String url = 'ws://192.168.1.20:8083/ws']) => + SavedServer.validated(id: 'a', name: name, endpoints: [url]); + +void main() { + test('app-chosen names are placeholders; typed names are not', () { + for (final name in [ + 'My server', + 'This server', + 'Original legacy server', + '192.168.1.20', + ]) { + expect(hasPlaceholderName(named(name)), isTrue, reason: name); + } + expect( + hasPlaceholderName(named('Tank.local', 'wss://tank.local/connect')), + isTrue, + ); + // A backup address's host is also a name the app could have chosen. + expect( + hasPlaceholderName( + SavedServer.validated( + id: 'a', + name: '100.64.0.2', + endpoints: ['ws://lan.test/ws', 'ws://100.64.0.2:8083/ws'], + ), + ), + isTrue, + ); + for (final name in ['Home', 'my server', 'tank', '192.168.1.2']) { + expect(hasPlaceholderName(named(name)), isFalse, reason: name); + } + }); + + test('renames only placeholders, only to a nonempty new hostname', () { + final renamed = renamedToHostname( + SavedServer.validated( + id: 'legacy-server', + name: 'My server', + endpoints: ['ws://192.168.1.20:8083/ws'], + legacyEndpoint: 'ws://192.168.1.20:8083/ws', + ), + ' tank ', + )!; + expect(renamed.name, 'tank'); + expect(renamed.id, 'legacy-server'); + expect(renamed.endpoints, ['ws://192.168.1.20:8083/ws']); + expect(renamed.legacyEndpoint, 'ws://192.168.1.20:8083/ws'); + expect(renamedToHostname(named('Home'), 'tank'), isNull); + expect(renamedToHostname(named('My server'), ' '), isNull); + expect(renamedToHostname(named('192.168.1.20'), '192.168.1.20'), isNull); + // The hostname is kept as the server reports it, domain included. + expect( + renamedToHostname(named('This server'), 'tank.lan')!.name, + 'tank.lan', + ); + }); + + test('reads the hostname from a get_status reply', () async { + expect( + hostnameFromStatus({ + 'type': 'status', + 'status': {'hostname': 'tank\n'}, + }), + 'tank', + ); + expect(hostnameFromStatus({'type': 'error', 'error': 'nope'}), ''); + expect(hostnameFromStatus({'type': 'status', 'status': {}}), ''); + }); + + test('a migrated legacy server is named by its address host', () async { + final catalog = await MemoryServerCatalogStore().load( + legacyEndpoint: 'ws://192.168.1.20:8083/ws', + ); + expect(catalog.active!.name, '192.168.1.20'); + expect(hasPlaceholderName(catalog.active!), isTrue); + expect(temporaryServerName('wss://tank.example/connect'), 'tank.example'); + }); +} diff --git a/app/test/features/settings/server_hostname_test.dart b/app/test/features/settings/server_hostname_test.dart new file mode 100644 index 00000000..027e092c --- /dev/null +++ b/app/test/features/settings/server_hostname_test.dart @@ -0,0 +1,168 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/core/servers/server_context.dart'; +import 'package:pipelines_app/features/settings/saved_servers_section.dart'; +import 'package:pipelines_app/features/settings/server_connections.dart'; + +import 'saved_servers_test.dart' show revealSave; + +SavedServer machine(String id, String name, String url) => + SavedServer.validated(id: id, name: name, endpoints: [url]); + +Future connectionsFor(MemoryServerCatalogStore store) async { + final connections = ServerConnections(store: store, onSelected: (_) async {}); + await connections.load(); + return connections; +} + +void main() { + test('a placeholder name becomes the hostname and is saved', () async { + final store = MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [ + machine('legacy-server', 'My server', 'ws://192.168.1.20:8083/ws'), + machine('b', '100.64.0.2', 'ws://100.64.0.2:8083/ws'), + machine('c', 'Laptop', 'ws://laptop.test/ws'), + ], + selectedId: 'b', + ), + ); + final connections = await connectionsFor(store); + addTearDown(connections.dispose); + expect(await connections.learnHostname('legacy-server', 'tank'), isTrue); + expect(await connections.learnHostname('b', 'linux-box'), isTrue); + expect(await connections.learnHostname('c', 'mac-mini'), isFalse); + expect(await connections.learnHostname('b', ''), isFalse); + final names = store.catalog!.servers.map((s) => s.name).toList(); + expect(names, ['tank', 'linux-box', 'Laptop']); + expect(store.catalog!.selectedId, 'b'); + expect(connections.catalog.toJson(), store.catalog!.toJson()); + // Once named, a later hostname does not rename it again. + expect(await connections.learnHostname('legacy-server', 'other'), isFalse); + }); + + test('a rename learned during another change is applied after it', () async { + final store = MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [machine('a', 'This server', 'ws://a.test/ws')], + selectedId: 'a', + ), + ); + final connections = await connectionsFor(store); + addTearDown(connections.dispose); + final persisting = connections.persist(); + expect(connections.busy, isTrue); + expect(await connections.learnHostname('a', 'tank'), isFalse); + await persisting; + await pumpEventQueue(); + expect(store.catalog!.active!.name, 'tank'); + }); + + test('a failed rename save keeps the old name', () async { + final store = MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [machine('a', 'a.test', 'ws://a.test/ws')], + selectedId: 'a', + ), + ); + final connections = await connectionsFor(store); + addTearDown(connections.dispose); + store.failSaves = true; + expect(await connections.learnHostname('a', 'tank'), isFalse); + expect(connections.catalog.active!.name, 'a.test'); + }); + + testWidgets('the unsaved page origin is named by its hostname', ( + tester, + ) async { + final connections = await connectionsFor(MemoryServerCatalogStore()); + addTearDown(connections.dispose); + await tester.pumpWidget( + MaterialApp( + home: ServerContext( + connections: connections, + serverId: null, + child: Builder( + builder: (context) => + Text(ServerContext.metadata(context, '7 stages')), + ), + ), + ), + ); + expect(find.text('7 stages'), findsOneWidget); + expect(await connections.learnHostname(null, 'tank'), isTrue); + await tester.pump(); + expect(find.text('tank · 7 stages'), findsOneWidget); + expect(connections.catalog.servers, isEmpty); + }); + + testWidgets('a saved server row and its metadata follow the rename', ( + tester, + ) async { + final connections = await connectionsFor( + MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [machine('a', 'My server', 'ws://a.test/ws')], + selectedId: 'a', + ), + ), + ); + addTearDown(connections.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ServerContext( + connections: connections, + serverId: 'a', + child: Builder( + builder: (context) => ListView( + children: [ + Text(ServerContext.metadata(context, '7 stages')), + SavedServersSection(connections: connections), + ], + ), + ), + ), + ), + ), + ); + expect(find.text('My server · 7 stages'), findsOneWidget); + await tester.runAsync(() => connections.learnHostname('a', 'tank')); + await tester.pump(); + expect(find.text('tank · 7 stages'), findsOneWidget); + expect(find.text('tank'), findsWidgets); + expect(find.text('My server'), findsNothing); + }); + + testWidgets('Add server with no name uses the address host for now', ( + tester, + ) async { + final connections = await connectionsFor(MemoryServerCatalogStore()); + addTearDown(connections.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: SavedServersSection(connections: connections), + ), + ), + ), + ); + await tester.tap(find.text('Add server')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('server-profile-addresses')), + 'ws://192.168.1.20:8083/ws', + ); + await revealSave(tester); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + expect(connections.catalog.active?.name, '192.168.1.20'); + await tester.runAsync( + () => connections.learnHostname(connections.catalog.active!.id, 'tank'), + ); + expect(connections.catalog.active?.name, 'tank'); + }); +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 4c2d3d35..c9fb7c4e 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -767,7 +767,10 @@ class _FixtureAuthenticator extends ChangeNotifier } class _FixtureChannel implements WebSocketChannel { - _FixtureChannel(); + _FixtureChannel({this.hostname = 'tank'}); + + /// The machine name this fixture server reports in `get_status`. + final String hostname; final _incoming = StreamController(); Timer? _runCompletion; @@ -814,7 +817,13 @@ class _FixtureChannel implements WebSocketChannel { } }); } - final reply = probeReply(decoded); + final reply = decoded['type'] == 'get_status' + ? { + 'id': decoded['id'], + 'type': 'status', + 'status': {'hostname': hostname}, + } + : probeReply(decoded); final followUps = perfChatFollowUps(decoded); final subscribe = decoded['chat_subscribe']; if (subscribe is Map) { @@ -957,6 +966,17 @@ Future main() async { if (query != null && query.isNotEmpty) _typeSearchWhenShown(query); useAppUrlStrategy(); ServerConnections? machines; + // `placeholders=1`: the saved machines still carry names the app chose + // ('My server', an address host); each reports its hostname on connect. + final placeholders = params['placeholders'] == '1'; + // `origin=1`: a browser on its page origin with no saved machine. + if (params['origin'] == '1') { + machines = ServerConnections( + store: MemoryServerCatalogStore(), + onSelected: (_) async {}, + ); + await machines.load(); + } if (params['machines'] == '1' || params['federated'] == '1') { machines = ServerConnections( store: MemoryServerCatalogStore( @@ -964,12 +984,12 @@ Future main() async { servers: [ SavedServer.validated( id: 'mac', - name: 'Alan’s Mac', + name: placeholders ? 'My server' : 'Alan’s Mac', endpoints: ['ws://mac.fixture/connect'], ), SavedServer.validated( id: 'linux', - name: 'Linux desktop', + name: placeholders ? 'linux.fixture' : 'Linux desktop', endpoints: ['ws://linux.fixture/connect'], ), ], @@ -988,7 +1008,9 @@ Future main() async { machines, connect: (machine) async { final client = PipelinesClient( - channelFactory: (_) => _FixtureChannel(), + channelFactory: (_) => _FixtureChannel( + hostname: machine.id == 'mac' ? 'tank' : 'linux-box', + ), ); await client.connect(Uri.parse(machine.endpoints.first)); return ChatMachineConnection(