diff --git a/stronglift_replacement/workout_app/lib/screens/settings_screen.dart b/stronglift_replacement/workout_app/lib/screens/settings_screen.dart index f8d93f4..2c3461f 100644 --- a/stronglift_replacement/workout_app/lib/screens/settings_screen.dart +++ b/stronglift_replacement/workout_app/lib/screens/settings_screen.dart @@ -10,6 +10,7 @@ import 'package:http/http.dart' as http; import 'package:url_launcher/url_launcher.dart'; import 'package:workout_app/models/exercise.dart'; import 'package:workout_app/models/workout_plan.dart'; +import 'package:workout_app/services/firebase_backend.dart'; import 'package:workout_app/services/github_device_auth.dart'; import 'package:workout_app/services/storage_service.dart'; import 'package:workout_app/services/sync_settings.dart'; @@ -21,12 +22,33 @@ enum _SyncStatusKind { success, pending, error } /// Screen for editing per-exercise thresholds and manual weight overrides. class SettingsScreen extends StatefulWidget { /// Creates a [SettingsScreen]. - const SettingsScreen({super.key, this.httpClient}); + const SettingsScreen({ + super.key, + this.httpClient, + this.firebaseFactory, + this.accountLoader, + this.accountSaver, + this.accountClearer, + }); /// Injectable HTTP client; tests pass a `MockClient` so the device-flow /// requests never hit the real network. final http.Client? httpClient; + /// Builds the Firebase client. Injected so tests need no platform channel. + final Future Function()? firebaseFactory; + + /// Keystore accessors for the Firebase account. Injected as a group so the + /// connect/disconnect flows are testable without a platform channel -- + /// `flutter test` has no binding for one. + final Future Function()? accountLoader; + + /// Persists the account. See [accountLoader]. + final Future Function(FirebaseAccount)? accountSaver; + + /// Forgets the account and any cached session. See [accountLoader]. + final Future Function()? accountClearer; + @override State createState() => _SettingsScreenState(); } @@ -42,6 +64,10 @@ class _SettingsScreenState extends State { final Map _weightTimers = {}; final _tokenController = TextEditingController(); + final _emailController = TextEditingController(); + final _passwordController = TextEditingController(); + bool _firebaseConnected = false; + bool _firebaseBusy = false; // Persistent (not a transient SnackBar) so the result of Connect GitHub / // Save is still visible if the user looks back at the screen later -- @@ -60,6 +86,67 @@ class _SettingsScreenState extends State { void initState() { super.initState(); unawaited(_load()); + unawaited(_loadFirebaseAccount()); + } + + /// Reflects a previously-stored account, so a returning user sees the real + /// state instead of an empty form that looks unconfigured. + Future _loadFirebaseAccount() async { + final account = await (widget.accountLoader ?? loadAccount)(); + if (!mounted) return; + if (account != null) _emailController.text = account.email; + setState(() => _firebaseConnected = account != null); + } + + /// Stores the typed account and signs in immediately, so a typo surfaces + /// here rather than as a silent background failure on the next push. + /// + /// Without this the app could never reach Firebase at all: `openFirebase()` + /// would read an account nothing had ever written. + Future _connectFirebase() async { + final email = _emailController.text.trim(); + final password = _passwordController.text; + if (email.isEmpty || password.isEmpty) { + _setSyncStatus( + 'Enter the sync account email and password.', + _SyncStatusKind.error, + ); + return; + } + setState(() => _firebaseBusy = true); + await (widget.accountSaver ?? saveAccount)( + FirebaseAccount(email: email, password: password), + ); + final client = await (widget.firebaseFactory ?? openFirebase)(); + if (!mounted) return; + if (client == null) { + await (widget.accountClearer ?? clearAccount)(); + if (!mounted) return; + setState(() { + _firebaseBusy = false; + _firebaseConnected = false; + }); + _setSyncStatus( + 'Firebase rejected that account.', + _SyncStatusKind.error, + ); + return; + } + _passwordController.clear(); + setState(() { + _firebaseBusy = false; + _firebaseConnected = true; + }); + _setSyncStatus('Connected to Firebase.', _SyncStatusKind.success); + } + + Future _disconnectFirebase() async { + await (widget.accountClearer ?? clearAccount)(); + if (!mounted) return; + _emailController.clear(); + _passwordController.clear(); + setState(() => _firebaseConnected = false); + _setSyncStatus('Firebase disconnected.', _SyncStatusKind.pending); } @override @@ -68,6 +155,8 @@ class _SettingsScreenState extends State { t.cancel(); } _tokenController.dispose(); + _emailController.dispose(); + _passwordController.dispose(); super.dispose(); } @@ -340,12 +429,16 @@ class _SettingsScreenState extends State { ); }), const SizedBox(height: 20), - const _SectionHeader('GITHUB SYNC'), + const _SectionHeader('SYNC'), const SizedBox(height: 4), Text( - 'Authorize in your browser -- no token to paste. Syncs to ' - '$syncRepoOwner/$syncRepoName. Workouts push automatically ' - 'on completion.', + _firebaseConnected + ? 'Connected. Workouts go to Firebase first, and still ' + 'mirror to GitHub until every device has moved.' + : 'Not connected -- syncing over GitHub only. Enter the ' + 'shared sync account to move this device over. ' + 'The password is kept in the device keystore, ' + 'never in the app or the repo.', style: TextStyle( color: colorScheme.onSurfaceVariant, fontSize: AppTextSize.caption, @@ -356,15 +449,53 @@ class _SettingsScreenState extends State { _SyncStatusBadge(text: _syncStatus!, kind: _syncStatusKind), const SizedBox(height: 12), ], - ElevatedButton.icon( - onPressed: _connectGitHub, - icon: const Icon(Icons.login), - label: const Text('Connect GitHub'), - ), + // Once connected the account is read-only text: an editable + // email box beside an empty password box reads as "you still + // have to enter this", making a connected device look + // unconfigured. + if (_firebaseConnected) + Row( + children: [ + const Icon(Icons.cloud_done, size: 20), + const SizedBox(width: 8), + Expanded(child: Text(_emailController.text)), + TextButton( + onPressed: _firebaseBusy ? null : _disconnectFirebase, + child: const Text('Disconnect'), + ), + ], + ) + else ...[ + TextField( + controller: _emailController, + keyboardType: TextInputType.emailAddress, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'Sync account email', + ), + ), + const SizedBox(height: 8), + TextField( + controller: _passwordController, + obscureText: true, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'Sync account password', + ), + ), + const SizedBox(height: 12), + ElevatedButton.icon( + onPressed: _firebaseBusy ? null : _connectFirebase, + icon: const Icon(Icons.cloud_done), + label: const Text('Connect Firebase'), + ), + ], const SizedBox(height: 8), + // GitHub is the cutover mirror, not a choice competing with + // Firebase, so its connect button moves in here too. ExpansionTile( title: Text( - 'Advanced: paste a token instead', + 'Advanced (GitHub mirror)', style: TextStyle( color: colorScheme.onSurfaceVariant, fontSize: AppTextSize.label, @@ -373,8 +504,31 @@ class _SettingsScreenState extends State { collapsedIconColor: colorScheme.onSurfaceVariant, iconColor: colorScheme.onSurfaceVariant, tilePadding: EdgeInsets.zero, - childrenPadding: const EdgeInsets.only(top: 8, bottom: 8), children: [ + Align( + alignment: Alignment.centerLeft, + child: Text( + 'Authorize in your browser -- no token to paste. ' + 'Syncs to $syncRepoOwner/$syncRepoName.', + style: TextStyle( + color: colorScheme.onSurfaceVariant, + fontSize: AppTextSize.caption, + ), + ), + ), + const SizedBox(height: 12), + Align( + alignment: Alignment.centerLeft, + child: ElevatedButton.icon( + onPressed: _connectGitHub, + icon: const Icon(Icons.login), + label: const Text('Connect GitHub'), + ), + ), + const SizedBox(height: 12), + // The PAT fallback lives inside the mirror section too: + // two sibling "Advanced" disclosures made it look like + // there were two independent things to configure. _SyncTokenField( controller: _tokenController, onSave: _saveToken, diff --git a/stronglift_replacement/workout_app/lib/services/workout_sync_service.dart b/stronglift_replacement/workout_app/lib/services/workout_sync_service.dart index 7ce5f4b..2b36f8a 100644 --- a/stronglift_replacement/workout_app/lib/services/workout_sync_service.dart +++ b/stronglift_replacement/workout_app/lib/services/workout_sync_service.dart @@ -57,6 +57,12 @@ class WorkoutSyncService { Future _openFirebase() => (firebaseFactory ?? openFirebase)(); + /// Whether this device has been set up for Firebase. + /// + /// Cheap on the common path: [openFirebase] reuses a cached refresh token + /// and only signs in when there is none. + Future _hasFirebaseAccount() async => await _openFirebase() != null; + /// The revision cache, defaulting to a file beside the app's data. Future _openStateStore() async => stateStore ?? await openSyncStateStore(); @@ -73,7 +79,10 @@ class WorkoutSyncService { /// configured; logs (but does not rethrow) any [GitHubSyncError]. Future push(WorkoutSession session) async { final settings = await SyncSettings.load(); - if (!settings.isConfigured) return; + // Either backend counts. Gating on the GitHub token alone silently + // dropped every push from a device connected only to Firebase -- and + // once the mirror is retired that would be every device. + if (!settings.isConfigured && !await _hasFirebaseAccount()) return; final github = GitHubClient( owner: owner, @@ -121,7 +130,7 @@ class WorkoutSyncService { /// failure contract as [push]. Future pushManual(Record record) async { final settings = await SyncSettings.load(); - if (!settings.isConfigured) return; + if (!settings.isConfigured && !await _hasFirebaseAccount()) return; final github = GitHubClient( owner: owner, @@ -178,9 +187,9 @@ class WorkoutSyncService { Future>> _readMergedPayloads({String? kind}) async { final settings = await SyncSettings.load(); - if (!settings.isConfigured) { + if (!settings.isConfigured && !await _hasFirebaseAccount()) { debugPrint( - 'WorkoutSyncService: NOT reading synced workouts — no sync token/repo ' + 'WorkoutSyncService: NOT reading synced workouts — no sync backend ' 'configured in Settings, so this phone cannot see the PC history.', ); return const []; diff --git a/stronglift_replacement/workout_app/test/screens/settings_screen_test.dart b/stronglift_replacement/workout_app/test/screens/settings_screen_test.dart index 58e85a9..90e5d64 100644 --- a/stronglift_replacement/workout_app/test/screens/settings_screen_test.dart +++ b/stronglift_replacement/workout_app/test/screens/settings_screen_test.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:io'; +import 'package:crdt_sync/crdt_sync.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -60,11 +61,44 @@ void main() { await tester.pump(); } - Widget _wrap({http.Client? httpClient}) => MaterialApp( + Widget _wrap({ + http.Client? httpClient, + Future Function()? firebaseFactory, + Future Function()? accountLoader, + Future Function(FirebaseAccount)? accountSaver, + Future Function()? accountClearer, + }) => MaterialApp( theme: buildAppTheme(), - home: SettingsScreen(httpClient: httpClient), + home: SettingsScreen( + httpClient: httpClient, + // Injected so the widget never reaches the OS keystore, which + // `flutter test` has no platform-channel binding for. + firebaseFactory: firebaseFactory ?? () async => null, + accountLoader: accountLoader ?? () async => null, + accountSaver: accountSaver, + accountClearer: accountClearer, + ), ); + /// Expands the "Advanced (GitHub mirror)" section. + /// + /// GitHub is the cutover mirror rather than a choice the user makes, so + /// everything GitHub-facing -- the connect button and the PAT fallback -- + /// is collapsed by default. + Future openAdvanced(WidgetTester tester) async { + // The ListView builds lazily, so the tile has to be scrolled into the + // viewport before it exists to tap. Name the outer Scrollable: once the + // tile is built there is more than one. + await tester.scrollUntilVisible( + find.text('Advanced (GitHub mirror)'), + 300, + scrollable: find.byType(Scrollable).first, + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Advanced (GitHub mirror)')); + await tester.pumpAndSettle(); + } + /// Drains the device flow's real `Future.delayed` poll (GitHubDeviceAuth /// injects no test delay, so under `runAsync` it is a genuine Timer, not /// the fake-clock one `tester.pump(duration)` advances) by interleaving @@ -85,10 +119,13 @@ void main() { /// viewport (+ cache extent) even for a plain `children:` list, so it must /// be scrolled into view before `find` can see it. Future _scrollToGitHubSync(WidgetTester tester) async { + // Scroll to the SYNC header rather than "Connect GitHub": the latter now + // lives inside a collapsed disclosure, and once that tile is built there + // is more than one Scrollable, so the finder must name the outer list. await tester.scrollUntilVisible( - find.text('Connect GitHub'), + find.text('Advanced (GitHub mirror)'), 500, - scrollable: find.byType(Scrollable), + scrollable: find.byType(Scrollable).first, ); } @@ -195,12 +232,130 @@ void main() { expect(state!.weight, workoutA.first.weight); }); - testWidgets('shows GITHUB SYNC section with a Connect GitHub button', ( + testWidgets('Connect Firebase with empty fields asks for credentials', ( + tester, + ) async { + var saved = false; + await _pump(tester, _wrap(accountSaver: (_) async => saved = true)); + await _scrollToGitHubSync(tester); + + await tester.ensureVisible(find.text('Connect Firebase')); + await tester.pump(); + await tester.tap(find.text('Connect Firebase')); + await tester.pump(); + + expect( + find.textContaining('Enter the sync account email and password'), + findsOneWidget, + ); + expect(saved, isFalse); + }); + + testWidgets('Connect Firebase stores the account and reports success', ( + tester, + ) async { + FirebaseAccount? saved; + await _pump( + tester, + _wrap( + accountSaver: (a) async => saved = a, + firebaseFactory: () async => _stubFirebaseClient(), + ), + ); + await _scrollToGitHubSync(tester); + + await tester.enterText( + find.widgetWithText(TextField, 'Sync account email'), + 'sync@example.com', + ); + await tester.enterText( + find.widgetWithText(TextField, 'Sync account password'), + 'pw', + ); + await tester.ensureVisible(find.text('Connect Firebase')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Connect Firebase')); + await tester.pumpAndSettle(); + + // saveAccount must actually be called: without it openFirebase() reads an + // account nothing ever wrote, and Firebase is a silent no-op forever. + expect(saved?.email, 'sync@example.com'); + expect(find.text('Connected to Firebase.'), findsOneWidget); + expect(find.text('sync@example.com'), findsOneWidget); + }); + + testWidgets('a rejected account is cleared rather than left half-stored', ( + tester, + ) async { + var cleared = false; + await _pump( + tester, + _wrap( + accountSaver: (_) async {}, + accountClearer: () async => cleared = true, + firebaseFactory: () async => null, + ), + ); + await _scrollToGitHubSync(tester); + + await tester.enterText( + find.widgetWithText(TextField, 'Sync account email'), + 'wrong@example.com', + ); + await tester.enterText( + find.widgetWithText(TextField, 'Sync account password'), + 'bad', + ); + await tester.ensureVisible(find.text('Connect Firebase')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Connect Firebase')); + await tester.pumpAndSettle(); + + expect(cleared, isTrue); + expect(find.text('Firebase rejected that account.'), findsOneWidget); + }); + + testWidgets('a stored account shows as connected, and disconnects', ( + tester, + ) async { + var cleared = false; + await _pump( + tester, + _wrap( + accountLoader: () async => + const FirebaseAccount(email: 'stored@example.com', password: 'pw'), + accountClearer: () async => cleared = true, + ), + ); + await _scrollToGitHubSync(tester); + + expect(find.text('stored@example.com'), findsOneWidget); + + // Explicit pumps, not pumpAndSettle: the token-verification path this + // screen kicks off on open keeps a timer alive, so settling never + // completes (same pitfall the device-flow tests work around). + await tester.ensureVisible(find.text('Disconnect')); + await tester.pump(); + await tester.tap(find.text('Disconnect')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + + expect(cleared, isTrue); + expect(find.text('Firebase disconnected.'), findsOneWidget); + }); + + testWidgets('leads with Firebase and hides GitHub behind Advanced', ( tester, ) async { await _pump(tester, _wrap()); await _scrollToGitHubSync(tester); - expect(find.text('GITHUB SYNC'), findsOneWidget); + + // GitHub is the cutover mirror, not a peer choice. + expect(find.text('SYNC'), findsOneWidget); + expect(find.text('Connect Firebase'), findsOneWidget); + expect(find.text('Connect GitHub'), findsNothing); + + await openAdvanced(tester); expect(find.text('Connect GitHub'), findsOneWidget); }); @@ -247,22 +402,27 @@ void main() { await _scrollToGitHubSync(tester); expect(find.text('Save'), findsNothing); - await tester.tap(find.text('Advanced: paste a token instead')); - await tester.pumpAndSettle(); + await openAdvanced(tester); - expect(find.widgetWithText(TextField, ''), findsOneWidget); + // The Firebase email/password fields are empty too, so scope the + // assertion to the PAT field's own Save button instead of counting + // empty TextFields. expect(find.text('Save'), findsOneWidget); }); testWidgets('saving a pasted token shows a confirmation', (tester) async { await _pump(tester, _wrap()); await _scrollToGitHubSync(tester); - await tester.tap(find.text('Advanced: paste a token instead')); - await tester.pumpAndSettle(); + await openAdvanced(tester); await tester.ensureVisible(find.widgetWithText(ElevatedButton, 'Save')); await tester.pumpAndSettle(); - await tester.enterText(find.byType(TextField), 'a-pasted-token'); + // Three TextFields exist now (Firebase email/password + the PAT), so + // pick the PAT field by its hint rather than by type. + await tester.enterText( + find.widgetWithText(TextField, 'GitHub PAT'), + 'a-pasted-token', + ); await tester.tap(find.text('Save')); await tester.pump(); expect(find.text('Sync token saved.'), findsOneWidget); @@ -276,6 +436,9 @@ void main() { await tester.pump(); await _scrollToGitHubSync(tester); + await openAdvanced(tester); + await tester.ensureVisible(find.text('Connect GitHub')); + await tester.pumpAndSettle(); await tester.tap(find.text('Connect GitHub')); await _pumpUntil( tester, @@ -324,6 +487,9 @@ void main() { await tester.pump(); await _scrollToGitHubSync(tester); + await openAdvanced(tester); + await tester.ensureVisible(find.text('Connect GitHub')); + await tester.pumpAndSettle(); await tester.tap(find.text('Connect GitHub')); await _pumpUntil( tester, @@ -389,6 +555,9 @@ void main() { await tester.pump(); await _scrollToGitHubSync(tester); + await openAdvanced(tester); + await tester.ensureVisible(find.text('Connect GitHub')); + await tester.pumpAndSettle(); await tester.tap(find.text('Connect GitHub')); await _pumpUntil( tester, @@ -517,6 +686,9 @@ void main() { await tester.pump(); await _scrollToGitHubSync(tester); + await openAdvanced(tester); + await tester.ensureVisible(find.text('Connect GitHub')); + await tester.pumpAndSettle(); await tester.tap(find.text('Connect GitHub')); await _pumpUntil( tester, @@ -561,6 +733,9 @@ void main() { await tester.pump(); await _scrollToGitHubSync(tester); + await openAdvanced(tester); + await tester.ensureVisible(find.text('Connect GitHub')); + await tester.pumpAndSettle(); await tester.tap(find.text('Connect GitHub')); await _pumpUntil( tester, @@ -604,6 +779,9 @@ void main() { await tester.pump(); await _scrollToGitHubSync(tester); + await openAdvanced(tester); + await tester.ensureVisible(find.text('Connect GitHub')); + await tester.pumpAndSettle(); await tester.tap(find.text('Connect GitHub')); await _pumpUntil( tester, @@ -660,3 +838,10 @@ void main() { }, ); } + +/// A real [FirebaseRestClient] that is never called: the settings screen only +/// checks it for null, so no network or keystore is touched. +FirebaseRestClient _stubFirebaseClient() => FirebaseRestClient( + databaseUrl: 'https://example.invalid', + auth: FirebaseTokenProvider(apiKey: 'k', store: InMemoryCredentialStore()), +);