import 'dart:async'; import 'package:flutter/material.dart' hide ConnectionState; import 'package:flutter_test/flutter_test.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/api_gateway.dart'; import 'package:pipelines_app/core/servers/chat/chat_server_pool.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/onboarding/onboarding_flow.dart'; import 'package:pipelines_app/features/settings/settings_store.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../core/transport/pipelines_client_test.dart' show FakeChannel; class _Gateway implements ApiGateway { final events = StreamController.broadcast(); @override Stream get frames => events.stream; @override Future call(String type, [JsonMap fields = const {}]) async => switch (type) { 'attention_acks' || 'ack_attention' => { 'type': 'attention_acks', 'attention_acks': {'chat_seen': {}, 'dismissed': []}, }, _ => {'type': 'chat_sessions', 'chat_sessions': []}, }; } ChatMachineConnection _connection(SavedServer server) { final states = StreamController.broadcast(); return ChatMachineConnection( gateway: _Gateway(), endpoint: () => server.endpoints.first, connected: () => true, states: states.stream, close: states.close, retry: () async {}, ); } SavedServer saved(String id) => SavedServer.validated( id: id, name: id, endpoints: ['wss://$id.test/connect'], ); Future 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.mac.cookie': 'pipelines_session=mac', 'pipelines.session.v2.tank.cookie': 'pipelines_session=tank', }); await ServerSession.load(); }); testWidgets( 'removing the primary, then the last machine, returns to Add server', (tester) async { final store = MemoryServerCatalogStore( catalog: ServerCatalog( servers: [saved('mac'), saved('tank')], selectedId: 'mac', ), ); PipelinesClient factory() => PipelinesClient( channelFactory: (_) => FakeChannel()..readyCompleter.complete(), ); await tester.pumpWidget( PipelinesRoot( nativeUpdatesSupported: false, server: ServerEndpoint.resolve( base: Uri.parse('file:///'), web: false, configured: 'wss://mac.test/connect', ), signedIn: true, catalogStore: store, clientFactory: factory, settingsStore: MemorySettingsStore(), check: (_) async => SessionState.signedIn, chatPoolFactory: (servers) => ChatServerPool( servers, web: false, connect: (server) async => _connection(server), probeProfile: ({required id, required endpoints}) async => const ServerProbeResult(SessionState.signedIn), ), ), ); await frames(tester); final app = tester.widget(find.byType(PipelinesApp)); expect(app.serverId, 'mac'); expect(app.servers!.authenticator, isNotNull); // The primary goes: the other machine takes over pipelines and runs // instead of the app losing its endpoint. // Activation waits for a frame, so pump while the removal runs. final removedPrimary = app.servers!.remove('mac'); await frames(tester); expect(await removedPrimary, isTrue); final remaining = tester.widget(find.byType(PipelinesApp)); expect(remaining.serverId, 'tank'); expect(remaining.server.uri, Uri.parse('wss://tank.test/connect')); expect(remaining.server.requiresConfiguration, isFalse); expect(find.text('Server endpoint not configured'), findsNothing); // The last machine goes: Add server comes back, nothing is deleted. final removedLast = remaining.servers!.remove('tank'); await frames(tester); expect(await removedLast, isTrue); expect(find.byType(PipelinesApp), findsNothing); expect(find.byType(OnboardingFlow), findsOneWidget); expect(find.byKey(const Key('onboarding-server')), findsOneWidget); expect(find.byKey(const Key('discovery-scan')), findsOneWidget); expect(store.catalog?.servers, isEmpty); // Both sign-ins survive for when the machines are added again. final preferences = await SharedPreferences.getInstance(); expect( preferences.getString('pipelines.session.v2.mac.cookie'), 'pipelines_session=mac', ); await tester.pumpWidget(const SizedBox.shrink()); }, ); testWidgets('removing a non-primary last machine also recovers', ( tester, ) async { // The pre-fix path: the catalog ends up with a machine that is not the // primary (a browser-aligned or stale selection), and removing it never // activated anything. final store = MemoryServerCatalogStore( catalog: ServerCatalog(servers: [saved('mac'), saved('tank')]), ); PipelinesClient factory() => PipelinesClient( channelFactory: (_) => FakeChannel()..readyCompleter.complete(), ); await tester.pumpWidget( PipelinesRoot( nativeUpdatesSupported: false, server: ServerEndpoint.resolve( base: Uri.parse('file:///'), web: false, configured: '', ), signedIn: true, catalogStore: store, clientFactory: factory, settingsStore: MemorySettingsStore(), check: (_) async => SessionState.signedIn, chatPoolFactory: (servers) => ChatServerPool( servers, web: false, connect: (server) async => _connection(server), probeProfile: ({required id, required endpoints}) async => const ServerProbeResult(SessionState.signedIn), ), ), ); await frames(tester); final app = tester.widget(find.byType(PipelinesApp)); expect(app.serverId, isNull); final removedFirst = app.servers!.remove('mac'); await frames(tester); expect(await removedFirst, isTrue); final removedLast = app.servers!.remove('tank'); await frames(tester); expect(await removedLast, isTrue); expect(find.byType(OnboardingFlow), findsOneWidget); expect(find.text('Server endpoint not configured'), findsNothing); await tester.pumpWidget(const SizedBox.shrink()); }); }