feat(app): configure and safely switch multi-address servers

This commit is contained in:
2026-10-24 03:04:53 +01:00
parent 47cfb31e7d
commit b499da304d
38 changed files with 1764 additions and 65 deletions
@@ -69,6 +69,7 @@ void main() {
AppRoute.runsForPipeline(3),
AppRoute.chat,
AppRoute.settings,
AppRoute.search,
]) {
testWidgets('${root.path} root exit expires and navigation clears it', (
tester,
@@ -5,6 +5,8 @@ import 'package:pipelines_app/application/server_endpoint.dart';
import 'package:pipelines_app/core/session/server_session.dart';
import 'package:pipelines_app/features/onboarding/onboarding_flow.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import 'package:pipelines_app/core/servers/server_catalog_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
class _Store implements SettingsStore {
@override
@@ -24,6 +26,10 @@ ServerEndpoint _server(String url) => ServerEndpoint.resolve(
);
void main() {
setUp(() async {
SharedPreferences.setMockInitialValues({});
await ServerSession.load();
});
testWidgets(
'a first launch starts at the server, pre-filled from the build',
(tester) async {
@@ -33,6 +39,7 @@ void main() {
buildDefault: 'wss://build.example/connect',
check: (_) async => SessionState.signedOut,
settingsStore: _Store(),
catalogStore: MemoryServerCatalogStore(),
),
);
await tester.pumpAndSettle();
@@ -52,6 +59,7 @@ void main() {
signedIn: false,
check: (_) async => SessionState.signedOut,
settingsStore: _Store(),
catalogStore: MemoryServerCatalogStore(),
),
);
await tester.pumpAndSettle();
@@ -285,7 +285,7 @@ void main() {
final session = AppSession(endpoint: server.uri, client: client);
addTearDown(session.dispose);
session.start();
final starting = session.start();
await tester.pumpWidget(
CupertinoApp(
home: CupertinoPageScaffold(
@@ -298,5 +298,8 @@ void main() {
expect(find.byType(CupertinoActivityIndicator), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.byType(Material), findsNothing);
session.dispose();
await starting;
await tester.pump();
});
}
@@ -0,0 +1,87 @@
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/pipelines_app.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/servers/server_scope.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;
void main() {
testWidgets(
'native root tries same-server backup without changing logical identity',
(tester) async {
SharedPreferences.setMockInitialValues({
'pipelines.session.v2.home.cookie': 'pipelines_session=home',
});
await ServerSession.load();
final home = SavedServer.validated(
id: 'home',
name: 'Home',
endpoints: ['wss://tail.test/connect', 'ws://192.168.1.2:8083/connect'],
);
final other = SavedServer.validated(
id: 'other',
name: 'Other',
endpoints: ['wss://other.test/connect'],
);
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(servers: [home, other], selectedId: home.id),
);
final attempts = <Uri>[];
final client = PipelinesClient(
backoffBase: const Duration(milliseconds: 10),
channelFactory: (uri) {
attempts.add(uri);
final channel = FakeChannel();
if (uri.host == 'tail.test') {
channel.readyCompleter.completeError(
StateError('Tailscale unreachable'),
);
} else {
channel.readyCompleter.complete();
}
return channel;
},
);
await tester.pumpWidget(
PipelinesRoot(
server: ServerEndpoint.resolve(
base: Uri.parse('file:///'),
web: false,
configured: home.endpoints.first,
),
catalogStore: store,
check: (_) async => SessionState.signedIn,
clientFactory: () => client,
),
);
for (var frame = 0; frame < 16; frame++) {
await tester.pump(const Duration(milliseconds: 20));
}
expect(attempts.map((uri) => uri.toString()), home.endpoints);
expect(client.endpoint.toString(), home.endpoints.last);
expect(client.state.kind, ConnectionKind.connected);
expect(serverIdentity(client), home.id);
expect(store.catalog?.selectedId, home.id);
expect(
tester.widget<PipelinesApp>(find.byType(PipelinesApp)).serverId,
home.id,
);
expect(ServerSession.headersFor(Uri.parse(home.endpoints.last)), {
'Cookie': 'pipelines_session=home',
});
expect(
ServerSession.headersFor(Uri.parse(other.endpoints.first)),
isEmpty,
);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
},
);
}
@@ -0,0 +1,220 @@
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_app.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 'package:pipelines_app/features/settings/settings_store.dart';
import 'package:pipelines_app/features/settings/saved_servers_section.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
SavedServer saved(String id, List<String> endpoints) =>
SavedServer.validated(id: id, name: id, endpoints: endpoints);
Future<void> frames(WidgetTester tester) async {
for (var frame = 0; frame < 12; frame++) {
await tester.pump(const Duration(milliseconds: 20));
}
}
void main() {
setUp(() async {
SharedPreferences.setMockInitialValues({
'pipelines.session.v2.home.cookie': 'pipelines_session=home',
'pipelines.session.v2.work.cookie': 'pipelines_session=work',
});
await ServerSession.load();
});
testWidgets(
'catalog reset to another saved URL cannot reuse original scoped login',
(tester) async {
final store = const SharedPreferencesServerCatalogStore();
final original = await store.load(
legacyEndpoint: 'wss://original.test/connect',
);
expect(await store.save(original), isTrue);
final preferences = await SharedPreferences.getInstance();
await preferences.setString(
'pipelines.session.cookie',
'pipelines_session=original',
);
await preferences.setString(
'pipelines.session.v2.legacy-server.cookie',
'pipelines_session=original',
);
await preferences.remove(serverCatalogKey);
await ServerSession.load();
await tester.pumpWidget(
PipelinesRoot(
server: ServerEndpoint.resolve(
base: Uri.parse('file:///'),
web: false,
configured: 'wss://different.test/connect',
),
signedIn: true,
catalogStore: store,
settingsStore: MemorySettingsStore(),
check: (_) async => SessionState.signedOut,
clientFactory: () => throw StateError(
'Must not connect before signing in to the new server',
),
),
);
await frames(tester);
expect(find.byType(PipelinesApp), findsNothing);
expect(ServerSession.cookie, isNull);
expect(
ServerSession.headersFor(Uri.parse('wss://different.test/connect')),
isEmpty,
);
final recovered = await store.load();
expect(recovered.active?.id, isNot('legacy-server'));
expect(recovered.active?.legacyEndpoint, isNull);
await tester.pumpWidget(const SizedBox.shrink());
},
);
testWidgets(
'switch closes old socket, resets app and persists selected profile',
(tester) async {
final home = saved('home', [
'wss://home.test/connect',
'ws://192.168.1.2:8083/connect',
]);
final work = saved('work', ['wss://work.test/connect']);
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(servers: [home, work], selectedId: home.id),
);
final clients = <PipelinesClient>[];
final channels = <FakeChannel>[];
final attempted = <Uri>[];
PipelinesClient factory() {
final channel = FakeChannel()..readyCompleter.complete();
channels.add(channel);
final client = PipelinesClient(
channelFactory: (uri) {
attempted.add(uri);
return channel;
},
);
clients.add(client);
return client;
}
final server = ServerEndpoint.resolve(
base: Uri.parse('file:///'),
web: false,
configured: home.endpoints.first,
);
await tester.pumpWidget(
PipelinesRoot(
server: server,
catalogStore: store,
clientFactory: factory,
settingsStore: MemorySettingsStore(),
check: (_) async => SessionState.signedIn,
),
);
await frames(tester);
final app = tester.widget<PipelinesApp>(find.byType(PipelinesApp));
expect(app.serverId, 'home');
expect(app.serverAddresses?.map((uri) => uri.toString()), home.endpoints);
final oldKey = app.key;
final oldClient = clients.single;
final request = expectLater(
oldClient.call('chat_prompt', const {
'chat_prompt': {'session_id': 'same-id', 'text': 'do not replay'},
}),
throwsA(isA<StateError>()),
);
final switched = app.servers!.select('work');
await frames(tester);
expect(await switched, isTrue);
await request;
final selected = tester.widget<PipelinesApp>(find.byType(PipelinesApp));
expect(selected.serverId, 'work');
expect(selected.key, isNot(oldKey));
expect(selected.resetRoute, isTrue);
expect(store.catalog?.selectedId, 'work');
expect(attempted.map((uri) => uri.host), ['home.test', 'work.test']);
expect(
ServerSession.headersFor(Uri.parse(home.endpoints.first)),
isEmpty,
);
expect(ServerSession.headersFor(Uri.parse(work.endpoints.first)), {
'Cookie': 'pipelines_session=work',
});
expect(
channels.last.outgoing
.map((frame) => jsonDecode(frame as String))
.where((frame) => frame['type'] == 'chat_prompt'),
isEmpty,
);
await expectLater(
oldClient.connect(Uri.parse(home.endpoints.first)),
throwsStateError,
);
await tester.pumpWidget(const SizedBox.shrink());
},
);
testWidgets(
'removing selected server never selects another or revives legacy login',
(tester) async {
SharedPreferences.setMockInitialValues({
'pipelines.session.cookie': 'pipelines_session=old-home',
});
await ServerSession.load();
final home = saved('legacy-server', ['wss://old-home.test/connect']);
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(servers: [home], selectedId: home.id),
);
await tester.pumpWidget(
PipelinesRoot(
server: ServerEndpoint.resolve(
base: Uri.parse('file:///'),
web: false,
configured: home.endpoints.first,
),
catalogStore: store,
settingsStore: MemorySettingsStore(),
check: (_) async => SessionState.signedIn,
clientFactory: () => PipelinesClient(
channelFactory: (_) => FakeChannel()..readyCompleter.complete(),
),
),
);
await frames(tester);
final connections = tester
.widget<PipelinesApp>(find.byType(PipelinesApp))
.servers!;
final removed = connections.remove(home.id);
await frames(tester);
expect(await removed, isTrue);
expect(connections.catalog.active, isNull);
expect(find.byType(PipelinesApp), findsNothing);
expect(find.byType(SavedServersSection), findsOneWidget);
final added = connections.save(
saved('new-work', ['wss://new-work.test/connect']),
);
await frames(tester);
expect(await added, isTrue);
expect(ServerSession.cookie, isNull);
expect(
ServerSession.headersFor(Uri.parse('wss://new-work.test/connect')),
isEmpty,
);
expect(find.byType(PipelinesApp), findsNothing);
expect(find.text('wss://new-work.test/connect'), findsWidgets);
await tester.pumpWidget(const SizedBox.shrink());
},
);
}
@@ -0,0 +1,78 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/servers/server_scope.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/data/chat_create_prompt_store.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_session_local.dart';
import 'package:pipelines_app/features/settings/settings_store.dart';
import 'package:pipelines_app/features/attention/runtime/attention_store.dart';
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
void main() {
setUp(() => SharedPreferences.setMockInitialValues({}));
test(
'server-local drafts, read marks, workspace and alerts stay isolated',
() async {
const homeDrafts = SharedPreferencesChatDraftStore(serverId: 'home');
const workDrafts = SharedPreferencesChatDraftStore(serverId: 'work');
await homeDrafts.write('same-session-id', 'private home draft');
expect(await workDrafts.read('same-session-id'), '');
const homePrompts = SharedPreferencesChatCreatePromptStore(
serverId: 'home',
);
const workPrompts = SharedPreferencesChatCreatePromptStore(
serverId: 'work',
);
await homePrompts.write('opencode', '/same-path', (
send: true,
text: 'private instructions',
));
expect(await workPrompts.read('opencode', '/same-path'), isNull);
await workDrafts.write('same-session-id', 'work draft');
expect(await homeDrafts.read('same-session-id'), 'private home draft');
const homeLocal = SharedPreferencesChatSessionLocalStore(
serverId: 'home',
);
const workLocal = SharedPreferencesChatSessionLocalStore(
serverId: 'work',
);
await homeLocal.save(const ChatSessionLocal(hidden: ['same-session-id']));
expect((await workLocal.load()).hidden, isEmpty);
const homeSettings = SharedPreferencesSettingsStore(serverId: 'home');
const workSettings = SharedPreferencesSettingsStore(serverId: 'work');
await homeSettings.saveWorkspace('/home-project');
expect((await workSettings.load()).workspace, '');
const homeAttention = SharedPreferencesAttentionStore(serverId: 'home');
const workAttention = SharedPreferencesAttentionStore(serverId: 'work');
await homeAttention.write('home dismissals');
expect(await workAttention.read(), isNull);
const homeNotifications = SharedPreferencesNotificationStore(
serverId: 'home',
);
const workNotifications = SharedPreferencesNotificationStore(
serverId: 'work',
);
await homeNotifications.write('home ledger');
expect(await workNotifications.read(), isNull);
},
);
test(
'migrated original server retains legacy local data; new servers do not',
() async {
await const SharedPreferencesChatDraftStore().write(
's',
'existing draft',
);
final old = SharedPreferencesChatDraftStore(
serverId: serverStorageScope('legacy-server'),
);
expect(await old.read('s'), 'existing draft');
expect(
await const SharedPreferencesChatDraftStore(serverId: 'new').read('s'),
'',
);
},
);
}
@@ -4,6 +4,76 @@ import 'package:pipelines_app/core/session/server_session.dart';
import 'package:pipelines_app/features/onboarding/onboarding_flow.dart';
void main() {
testWidgets('sign-in uses a reachable backup within the selected server', (
tester,
) async {
final primary = Uri.parse('wss://tail.example/connect');
final backup = Uri.parse('ws://192.168.1.2:8083/connect');
final checked = <Uri>[];
final signedIn = <Uri>[];
final saved = <String>[];
await tester.pumpWidget(
MaterialApp(
home: OnboardingFlow(
initialServer: primary.toString(),
serverAddresses: [primary, backup],
check: (uri) async {
checked.add(uri);
return uri == primary
? SessionState.unreachable
: SessionState.signedOut;
},
signIn: (uri, _) async {
signedIn.add(uri);
return null;
},
saveServer: (url) async => saved.add(url),
onDone: (_) {},
),
),
);
await tester.tap(find.byKey(const Key('onboarding-next')));
await tester.pumpAndSettle();
expect(checked, [primary, backup]);
expect(saved, [backup.toString()]);
await tester.enterText(
find.byKey(const Key('onboarding-password')),
'fixture-password',
);
await tester.tap(find.byKey(const Key('onboarding-next')));
await tester.pump();
await tester.pump();
expect(signedIn, [backup]);
});
testWidgets(
'typing a different server does not try another profile backups',
(tester) async {
final primary = Uri.parse('wss://tail.example/connect');
final checked = <Uri>[];
await tester.pumpWidget(
MaterialApp(
home: OnboardingFlow(
initialServer: primary.toString(),
serverAddresses: [primary, Uri.parse('ws://192.168.1.2/connect')],
check: (uri) async {
checked.add(uri);
return SessionState.unreachable;
},
onDone: (_) {},
),
),
);
await tester.enterText(
find.byKey(const Key('onboarding-server')),
'wss://different.example/connect',
);
await tester.tap(find.byKey(const Key('onboarding-next')));
await tester.pumpAndSettle();
expect(checked, [Uri.parse('wss://different.example/connect')]);
},
);
testWidgets('server, then password; both kept, then the app opens', (
tester,
) async {
@@ -0,0 +1,192 @@
import 'package:flutter/cupertino.dart';
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/features/settings/saved_servers_section.dart';
import 'package:pipelines_app/features/settings/server_connections.dart';
SavedServer profile(String id, List<String> urls) =>
SavedServer.validated(id: id, name: id, endpoints: urls);
void main() {
test(
'browser Back aligns active identity with the actual page; failed switch restores selection',
() async {
final home = profile('Home', ['wss://home.test/connect']);
final work = profile('Work', ['wss://work.test/connect']);
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(servers: [home, work], selectedId: 'Work'),
);
final controller = ServerConnections(
store: store,
onSelected: (_) async => throw StateError('Navigation failed'),
);
addTearDown(controller.dispose);
await controller.load();
controller.alignBrowserOrigin(Uri.parse('wss://home.test/connect'));
expect(controller.catalog.active?.id, 'Home');
expect(await controller.select('Work'), isFalse);
expect(controller.catalog.active?.id, 'Home');
expect(store.catalog?.active?.id, 'Home');
controller.alignBrowserOrigin(
Uri.parse('wss://unconfigured.test/connect'),
);
expect(controller.catalog.active, isNull);
},
);
test(
'selection and address edits persist before activation; failed saves keep selection',
() async {
final home = profile('Home', [
'wss://home.test/connect',
'ws://192.168.1.2:8083/connect',
]);
final work = profile('Work', ['wss://work.test/connect']);
final store = MemoryServerCatalogStore(
catalog: ServerCatalog(servers: [home, work], selectedId: home.id),
);
final activated = <String?>[];
final controller = ServerConnections(
store: store,
onSelected: (server) async {
expect(store.catalog?.selectedId, server?.id);
activated.add(server?.id);
},
);
addTearDown(controller.dispose);
await controller.load();
expect(await controller.select(work.id), isTrue);
expect(activated, ['Work']);
store.failSaves = true;
expect(await controller.select(home.id), isFalse);
expect(controller.catalog.active?.id, 'Work');
expect(activated, ['Work']);
expect(controller.error, contains('could not be saved'));
store.failSaves = false;
expect(await controller.remove('Work'), isTrue);
expect(controller.catalog.active, isNull);
expect(activated, ['Work', null]);
expect(controller.catalog.servers.single.id, 'Home');
},
);
test(
'first explicit add selects its server but adding another does not switch',
() async {
final calls = <String?>[];
final controller = ServerConnections(
store: MemoryServerCatalogStore(),
onSelected: (s) async => calls.add(s?.id),
);
addTearDown(controller.dispose);
await controller.load();
expect(
await controller.save(profile('Home', ['wss://home.test'])),
isTrue,
);
expect(controller.catalog.active?.id, 'Home');
expect(
await controller.save(profile('Work', ['wss://work.test'])),
isTrue,
);
expect(controller.catalog.active?.id, 'Home');
expect(calls, ['Home']);
},
);
for (final cupertino in [false, true]) {
testWidgets('add, edit and select ordered server aliases ($cupertino)', (
tester,
) async {
final calls = <String?>[];
final connections = ServerConnections(
store: MemoryServerCatalogStore(),
onSelected: (s) async => calls.add(s?.id),
);
addTearDown(connections.dispose);
await connections.load();
final body = SingleChildScrollView(
child: SavedServersSection(connections: connections),
);
await tester.pumpWidget(
cupertino
? CupertinoApp(
home: CupertinoPageScaffold(child: SafeArea(child: body)),
)
: MaterialApp(home: Scaffold(body: body)),
);
await tester.tap(find.text('Add server'));
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('server-profile-name')),
'Home',
);
await tester.enterText(
find.byKey(const Key('server-profile-addresses')),
'wss://tail.example/connect\nws://192.168.1.2:8083/connect',
);
await tester.ensureVisible(find.text('Save server'));
await tester.pumpAndSettle();
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
expect(connections.catalog.active?.name, 'Home');
expect(connections.catalog.active?.endpoints, [
'wss://tail.example/connect',
'ws://192.168.1.2:8083/connect',
]);
expect(
find.text('Backup 1: ws://192.168.1.2:8083/connect'),
findsOneWidget,
);
await tester.tap(find.text('Edit Home'));
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('server-profile-name')),
'My home',
);
await tester.ensureVisible(find.text('Save server'));
await tester.pumpAndSettle();
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
expect(connections.catalog.active?.name, 'My home');
expect(calls, hasLength(2));
expect(calls.first, calls.last);
expect(tester.takeException(), isNull);
});
testWidgets('invalid server addresses stay in editor ($cupertino)', (
tester,
) async {
final connections = ServerConnections(
store: MemoryServerCatalogStore(),
onSelected: (_) async {},
);
addTearDown(connections.dispose);
final body = SavedServersSection(connections: connections);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: body))
: MaterialApp(home: Scaffold(body: body)),
);
await tester.tap(find.text('Add server'));
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('server-profile-name')),
'Home',
);
await tester.enterText(
find.byKey(const Key('server-profile-addresses')),
'not-a-url',
);
await tester.ensureVisible(find.text('Save server'));
await tester.pumpAndSettle();
await tester.tap(find.text('Save server'));
await tester.pumpAndSettle();
expect(find.byKey(const Key('server-profile-addresses')), findsOneWidget);
expect(connections.catalog.servers, isEmpty);
expect(find.textContaining('valid URL'), findsOneWidget);
});
}
}