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
+1 -1
View File
@@ -18,7 +18,7 @@ void main() {
connected: () => true,
gateway: gateway,
machineId: 'mac',
machineName: 'Mac',
machineName: () => 'Mac',
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 {
final events = StreamController<JsonMap>.broadcast();
String? hostname;
final calls = <String>[];
@override
Stream<JsonMap> get frames => events.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async =>
type == 'attention_acks' || type == 'ack_attention'
Future<JsonMap> 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]);
@@ -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);
@@ -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');
});
}