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 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 15:58:28 +00:00
parent 3e817a189b
commit c264f865ff
16 changed files with 654 additions and 24 deletions
+3 -3
View File
@@ -21,7 +21,7 @@ class AppTerminals {
required bool Function() connected, required bool Function() connected,
required ApiGateway gateway, required ApiGateway gateway,
required String machineId, required String machineId,
required String machineName, required String Function() machineName,
required this.layout, required this.layout,
WindowManager? windows, WindowManager? windows,
}) : machines = pool != null }) : machines = pool != null
@@ -29,9 +29,9 @@ class AppTerminals {
: SingleTerminalMachines( : SingleTerminalMachines(
connection: connection, connection: connection,
connected: connected, connected: connected,
machine: TerminalMachine( machine: () => TerminalMachine(
id: machineId, id: machineId,
name: machineName, name: machineName(),
gateway: gateway, gateway: gateway,
), ),
) { ) {
+36 -5
View File
@@ -58,6 +58,7 @@ import '../features/terminal/terminal_layout.dart';
import 'app_route.dart'; import 'app_route.dart';
import 'app_router.dart'; import 'app_router.dart';
import 'app_session.dart'; import 'app_session.dart';
import '../core/servers/server_naming.dart';
import 'chat_destination.dart'; import 'chat_destination.dart';
import 'pipelines_destination.dart'; import 'pipelines_destination.dart';
import 'runs_destination.dart'; import 'runs_destination.dart';
@@ -357,16 +358,15 @@ class _PipelinesAppState extends State<PipelinesApp>
_session.addListener(_chatSyncChanged); _session.addListener(_chatSyncChanged);
widget.chatPool?.addListener(_chatSyncChanged); widget.chatPool?.addListener(_chatSyncChanged);
_chatSyncChanged(); _chatSyncChanged();
_session.addListener(_learnServerHostname);
_learnServerHostname();
_terminals = AppTerminals( _terminals = AppTerminals(
pool: widget.chatPool, pool: widget.chatPool,
connection: _session, connection: Listenable.merge([_session, ?widget.servers]),
connected: () => _session.connected, connected: () => _session.connected,
gateway: _session.gateway, gateway: _session.gateway,
machineId: widget.serverId ?? 'server', machineId: widget.serverId ?? 'server',
machineName: machineName: _serverName,
widget.servers?.catalog.active?.name ??
widget.server.uri?.host ??
'This server',
layout: widget.terminalLayout ?? TerminalLayout.instance, layout: widget.terminalLayout ?? TerminalLayout.instance,
windows: _windows, windows: _windows,
); );
@@ -605,6 +605,7 @@ class _PipelinesAppState extends State<PipelinesApp>
} }
_terminals.dispose(); _terminals.dispose();
_session.removeListener(_chatSyncChanged); _session.removeListener(_chatSyncChanged);
_session.removeListener(_learnServerHostname);
widget.chatPool?.removeListener(_chatSyncChanged); widget.chatPool?.removeListener(_chatSyncChanged);
_chatWindows.dispose(); _chatWindows.dispose();
_diffWindows.dispose(); _diffWindows.dispose();
@@ -935,6 +936,36 @@ class _PipelinesAppState extends State<PipelinesApp>
} }
/// A replaced socket makes open chats re-subscribe, also in windows. /// 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 = void _chatSyncChanged() => _chatRuntime.syncToken.value =
widget.chatPool?.revision ?? _session.connectionEpoch; widget.chatPool?.revision ?? _session.connectionEpoch;
@@ -10,6 +10,7 @@ import '../../transport/pipelines_client.dart';
import '../../../features/settings/server_connections.dart'; import '../../../features/settings/server_connections.dart';
import '../machine_access.dart'; import '../machine_access.dart';
import '../server_catalog.dart'; import '../server_catalog.dart';
import '../server_naming.dart';
import 'browser_peer.dart'; import 'browser_peer.dart';
import 'chat_server_gateway.dart'; import 'chat_server_gateway.dart';
import 'federated_chat_gateway.dart'; import 'federated_chat_gateway.dart';
@@ -27,6 +28,9 @@ class ChatMachineStatus {
/// Why the machine is not connected, once classified; null while unknown. /// Why the machine is not connected, once classified; null while unknown.
MachineAccessResult? access; 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 /// 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) { if (item.connected && !was) {
revision++; revision++;
unawaited(ackSync.connected()); unawaited(ackSync.connected());
unawaited(_learnHostname(item, generation));
} }
if (!item.connected && !item.connecting && item.access == null) { if (!item.connected && !item.connecting && item.access == null) {
unawaited(_classify(item, generation)); unawaited(_classify(item, generation));
@@ -189,6 +194,7 @@ class ChatServerPool extends ChangeNotifier implements MachineAuthenticator {
revision++; revision++;
if (item.connected) { if (item.connected) {
unawaited(ackSync.connected()); unawaited(ackSync.connected());
unawaited(_learnHostname(item, generation));
} else { } else {
unawaited(_classify(item, generation)); unawaited(_classify(item, generation));
} }
@@ -207,6 +213,21 @@ class ChatServerPool extends ChangeNotifier implements MachineAuthenticator {
if (!_disposed) notifyListeners(); 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<void> _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 /// 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 /// 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. /// password, a redirect means the sign-in is fine and the socket failed.
@@ -4,6 +4,7 @@ import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'server_catalog.dart'; import 'server_catalog.dart';
import 'server_naming.dart';
import '../transport/server_url.dart'; import '../transport/server_url.dart';
const String serverCatalogKey = 'pipelines.next.serverCatalog.v1'; const String serverCatalogKey = 'pipelines.next.serverCatalog.v1';
@@ -27,7 +28,8 @@ ServerCatalog _migrate(String legacyEndpoint, [List<String>? binding]) {
servers: [ servers: [
SavedServer.validated( SavedServer.validated(
id: id, id: id,
name: 'My server', // Its address names it until the machine reports its hostname.
name: temporaryServerName(legacyEndpoint),
endpoints: [legacyEndpoint], endpoints: [legacyEndpoint],
legacyEndpoint: canMigrate ? legacyEndpoint : null, legacyEndpoint: canMigrate ? legacyEndpoint : null,
), ),
+3
View File
@@ -15,7 +15,10 @@ class ServerContext extends InheritedNotifier<ServerConnections> {
static ServerContext? maybeOf(BuildContext context) => static ServerContext? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<ServerContext>(); context.dependOnInheritedWidgetOfExactType<ServerContext>();
/// The machine's name; a browser's unsaved page origin is named by the
/// hostname it reported.
String? get name { String? get name {
if (serverId == null) return notifier!.originHostname;
for (final server in notifier!.catalog.servers) { for (final server in notifier!.catalog.servers) {
if (server.id == serverId) return server.name; if (server.id == serverId) return server.name;
} }
+62
View File
@@ -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<String> 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<String> fetchServerHostname(ApiGateway gateway) async {
try {
return hostnameFromStatus(await gateway.call('get_status'));
} catch (_) {
return '';
}
}
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import '../../core/servers/machine_access.dart'; import '../../core/servers/machine_access.dart';
import '../../core/servers/server_catalog.dart'; import '../../core/servers/server_catalog.dart';
import '../../core/servers/server_naming.dart';
import '../../ui/adaptive/segmented_bar.dart'; import '../../ui/adaptive/segmented_bar.dart';
import '../onboarding/discovery/discovered_server.dart'; import '../onboarding/discovery/discovered_server.dart';
import '../onboarding/discovery/discovery_panel.dart'; import '../onboarding/discovery/discovery_panel.dart';
@@ -72,13 +73,19 @@ class _ServerEditorState extends State<_ServerEditor> {
Future<void> _save() async { Future<void> _save() async {
if (_saving) return; if (_saving) return;
try { 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( final server = SavedServer.validated(
id: _id, id: _id,
name: _name.text, name: _name.text.trim().isEmpty && endpoints.isNotEmpty
? temporaryServerName(endpoints.first)
: _name.text,
legacyEndpoint: widget.server?.legacyEndpoint, legacyEndpoint: widget.server?.legacyEndpoint,
endpoints: _addresses.text endpoints: endpoints,
.split('\n')
.where((line) => line.trim().isNotEmpty),
); );
setState(() { setState(() {
_saving = true; _saving = true;
@@ -173,6 +180,10 @@ class _ServerEditorState extends State<_ServerEditor> {
const SizedBox(height: 16), const SizedBox(height: 16),
], ],
_field(_name, 'Server name', key: 'server-profile-name'), _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), const SizedBox(height: 16),
_field( _field(
_addresses, _addresses,
@@ -1,8 +1,11 @@
import 'dart:async';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import '../../core/servers/machine_access.dart'; import '../../core/servers/machine_access.dart';
import '../../core/servers/server_catalog.dart'; import '../../core/servers/server_catalog.dart';
import '../../core/servers/server_catalog_store.dart'; import '../../core/servers/server_catalog_store.dart';
import '../../core/servers/server_naming.dart';
/// Saved configurations are committed before switching the app's connection. /// Saved configurations are committed before switching the app's connection.
/// A failed save leaves the old selection and its live socket unchanged. /// A failed save leaves the old selection and its live socket unchanged.
@@ -79,6 +82,47 @@ class ServerConnections extends ChangeNotifier {
bool get busy => _busy; bool get busy => _busy;
String? get error => _error; 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 = <String, String>{};
/// 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<bool> 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<bool> _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 /// Browsers always connect to their page origin, even after Back or a failed
/// cross-origin navigation. Do not label another saved profile as active. /// cross-origin navigation. Do not label another saved profile as active.
void alignBrowserOrigin(Uri endpoint) { void alignBrowserOrigin(Uri endpoint) {
@@ -181,6 +225,7 @@ class ServerConnections extends ChangeNotifier {
} finally { } finally {
_busy = false; _busy = false;
_notify(); _notify();
if (_learned.isNotEmpty) scheduleMicrotask(_applyLearnedNames);
} }
} }
@@ -65,11 +65,13 @@ class SingleTerminalMachines extends ValueNotifier<List<TerminalMachine>> {
} }
final Listenable connection; final Listenable connection;
final TerminalMachine machine;
/// The machine as named now; [connection] also notifies a rename.
final TerminalMachine Function() machine;
final bool Function() connected; final bool Function() connected;
void _update() { void _update() {
final next = connected() ? [machine] : const <TerminalMachine>[]; final next = connected() ? [machine()] : const <TerminalMachine>[];
if (!_same(next, value)) value = next; if (!_same(next, value)) value = next;
} }
+1 -1
View File
@@ -18,7 +18,7 @@ void main() {
connected: () => true, connected: () => true,
gateway: gateway, gateway: gateway,
machineId: 'mac', machineId: 'mac',
machineName: 'Mac', machineName: () => 'Mac',
layout: TerminalLayout(store: MemoryLayoutStore()), layout: TerminalLayout(store: MemoryLayoutStore()),
); );
}); });
@@ -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<void> answerStatus(
WidgetTester tester,
FakeChannel channel,
String hostname,
) async {
final answered = <String>{};
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<String, dynamic>;
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();
});
}
@@ -12,11 +12,22 @@ import 'package:pipelines_app/features/settings/server_connections.dart';
class _Gateway implements ApiGateway { class _Gateway implements ApiGateway {
final events = StreamController<JsonMap>.broadcast(); final events = StreamController<JsonMap>.broadcast();
String? hostname;
final calls = <String>[];
@override @override
Stream<JsonMap> get frames => events.stream; Stream<JsonMap> get frames => events.stream;
@override @override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async => Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
type == 'attention_acks' || type == 'ack_attention' 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', 'type': 'attention_acks',
'attention_acks': {'chat_seen': {}, 'dismissed': []}, 'attention_acks': {'chat_seen': {}, 'dismissed': []},
@@ -82,6 +93,52 @@ void main() {
TestWidgetsFlutterBinding.ensureInitialized(); TestWidgetsFlutterBinding.ensureInitialized();
setUp(() => SharedPreferences.setMockInitialValues({})); 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 { test('an older async detach cannot close a newer connection', () async {
final profile = _server('one'); final profile = _server('one');
final servers = await _servers([profile]); final servers = await _servers([profile]);
@@ -178,7 +178,7 @@ void main() {
}); });
final migrated = await store.load(legacyEndpoint: legacy); final migrated = await store.load(legacyEndpoint: legacy);
expect(migrated.selectedId, 'legacy-server'); 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']); expect(migrated.active!.endpoints, ['ws://legacy.test/connect']);
final preferences = await SharedPreferences.getInstance(); final preferences = await SharedPreferences.getInstance();
expect(preferences.containsKey(serverCatalogKey), isFalse); expect(preferences.containsKey(serverCatalogKey), isFalse);
@@ -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');
});
}
@@ -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<ServerConnections> 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');
});
}
+27 -5
View File
@@ -767,7 +767,10 @@ class _FixtureAuthenticator extends ChangeNotifier
} }
class _FixtureChannel implements WebSocketChannel { 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<dynamic>(); final _incoming = StreamController<dynamic>();
Timer? _runCompletion; 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 followUps = perfChatFollowUps(decoded);
final subscribe = decoded['chat_subscribe']; final subscribe = decoded['chat_subscribe'];
if (subscribe is Map) { if (subscribe is Map) {
@@ -957,6 +966,17 @@ Future<void> main() async {
if (query != null && query.isNotEmpty) _typeSearchWhenShown(query); if (query != null && query.isNotEmpty) _typeSearchWhenShown(query);
useAppUrlStrategy(); useAppUrlStrategy();
ServerConnections? machines; 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') { if (params['machines'] == '1' || params['federated'] == '1') {
machines = ServerConnections( machines = ServerConnections(
store: MemoryServerCatalogStore( store: MemoryServerCatalogStore(
@@ -964,12 +984,12 @@ Future<void> main() async {
servers: [ servers: [
SavedServer.validated( SavedServer.validated(
id: 'mac', id: 'mac',
name: 'Alan’s Mac', name: placeholders ? 'My server' : 'Alan’s Mac',
endpoints: ['ws://mac.fixture/connect'], endpoints: ['ws://mac.fixture/connect'],
), ),
SavedServer.validated( SavedServer.validated(
id: 'linux', id: 'linux',
name: 'Linux desktop', name: placeholders ? 'linux.fixture' : 'Linux desktop',
endpoints: ['ws://linux.fixture/connect'], endpoints: ['ws://linux.fixture/connect'],
), ),
], ],
@@ -988,7 +1008,9 @@ Future<void> main() async {
machines, machines,
connect: (machine) async { connect: (machine) async {
final client = PipelinesClient( final client = PipelinesClient(
channelFactory: (_) => _FixtureChannel(), channelFactory: (_) => _FixtureChannel(
hostname: machine.id == 'mac' ? 'tank' : 'linux-box',
),
); );
await client.connect(Uri.parse(machine.endpoints.first)); await client.connect(Uri.parse(machine.endpoints.first));
return ChatMachineConnection( return ChatMachineConnection(