diff --git a/stronglift_replacement/workout_app/lib/services/backup_service.dart b/stronglift_replacement/workout_app/lib/services/backup_service.dart index 477eae4..9ea749f 100644 --- a/stronglift_replacement/workout_app/lib/services/backup_service.dart +++ b/stronglift_replacement/workout_app/lib/services/backup_service.dart @@ -26,6 +26,14 @@ const String kBackupPath = '$kBackupDir/backup.json'; /// Path where the GitHub sync token is mirrored on external storage. const String kSyncTokenBackupPath = '$kBackupDir/sync_token'; +/// Path where the IN-PROGRESS session is mirrored on external storage. +/// +/// The active session (which set you are on, and the reps done so far) lives +/// in app-private SQLite, which an uninstall or `pm clear` wipes — losing the +/// workout you are standing in the middle of. Mirroring it here means even a +/// full app-data wipe resumes on the exact set and rep. +const String kActiveSessionBackupPath = '$kBackupDir/active_session.json'; + /// Handles exporting and importing the workout database (and the GitHub /// sync token) as files on external storage, which persist across app /// uninstalls. @@ -53,6 +61,8 @@ class BackupService { String get _backupPath => '$_baseDir/backup.json'; String get _syncTokenPath => '$_baseDir/sync_token'; + String get _activeSessionPath => '$_baseDir/active_session.json'; + // ── Permission ───────────────────────────────────────────────────────────── // coverage:ignore-start @@ -130,6 +140,40 @@ class BackupService { } } + /// Mirrors the IN-PROGRESS session (or clears it when [data] is null). + /// + /// Best-effort like [export]. Called on every set/rep change, so a wipe of + /// app-private storage — an uninstall, or `pm clear` — no longer costs the + /// user the workout they are standing in the middle of. + Future exportActiveSession(Map? data) async { + try { + final f = File(_activeSessionPath); + if (data == null) { + if (f.existsSync()) await f.delete(); + return; + } + final dir = Directory(_baseDir); + if (!dir.existsSync()) { + dir.createSync(recursive: true); + } + await f.writeAsString(jsonEncode(data)); + } on Exception { + // Backup is best-effort; never throw mid-workout. + } + } + + /// Returns the mirrored in-progress session, or null if none / unreadable. + Future?> readActiveSession() async { + try { + final f = File(_activeSessionPath); + if (!f.existsSync()) return null; + final decoded = jsonDecode(await f.readAsString()); + return decoded is Map ? decoded : null; + } on Exception { + return null; + } + } + /// Returns the mirrored sync token, or null if none exists / unreadable. Future readSyncToken() async { try { diff --git a/stronglift_replacement/workout_app/lib/services/storage_service.dart b/stronglift_replacement/workout_app/lib/services/storage_service.dart index 4643bf5..17a3da5 100644 --- a/stronglift_replacement/workout_app/lib/services/storage_service.dart +++ b/stronglift_replacement/workout_app/lib/services/storage_service.dart @@ -223,24 +223,46 @@ class StorageService { // ── Active session (crash / exit recovery) ───────────────────────────────── /// Persists [data] as the currently active (in-progress) session. + /// + /// Also mirrored to external storage: this table is app-private, so an + /// uninstall or `pm clear` wipes it and the user loses the set they are + /// standing on. The mirror survives both. Future saveActiveSession(Map data) async { await _db.insert( 'active_session', {'id': 1, 'json': jsonEncode(data)}, conflictAlgorithm: ConflictAlgorithm.replace, ); + unawaited(BackupService.instance.exportActiveSession(data)); } /// Returns the saved active session, or null if none exists. + /// + /// Falls back to the external mirror (re-seeding the table from it) when the + /// table is empty — which is exactly the state right after an app-data wipe, + /// so the workout resumes on the same set and rep instead of vanishing. Future?> loadActiveSession() async { final rows = await _db.query('active_session', where: 'id = 1'); - if (rows.isEmpty) return null; - return jsonDecode(rows.first['json']! as String) as Map; + if (rows.isNotEmpty) { + return jsonDecode(rows.first['json']! as String) as Map; + } + final mirrored = await BackupService.instance.readActiveSession(); + if (mirrored == null) return null; + await _db.insert( + 'active_session', + {'id': 1, 'json': jsonEncode(mirrored)}, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + return mirrored; } /// Removes the active session record (called after a session is committed). + /// + /// Clears the external mirror too, so a finished workout cannot be + /// resurrected by the next [loadActiveSession]. Future clearActiveSession() async { await _db.delete('active_session', where: 'id = 1'); + await BackupService.instance.exportActiveSession(null); } // ── Exercise state ───────────────────────────────────────────────────────── diff --git a/stronglift_replacement/workout_app/test/services/backup_service_test.dart b/stronglift_replacement/workout_app/test/services/backup_service_test.dart index ca5162e..b09c2e1 100644 --- a/stronglift_replacement/workout_app/test/services/backup_service_test.dart +++ b/stronglift_replacement/workout_app/test/services/backup_service_test.dart @@ -101,4 +101,37 @@ void main() { asDir.createSync(); expect(await BackupService.instance.readSyncToken(), isNull); }); + + test('exportActiveSession then readActiveSession round-trips', () async { + await BackupService.instance.exportActiveSession({ + 'workoutType': 'B', + 'doneReps': [ + [5, 4], + ], + }); + final got = await BackupService.instance.readActiveSession(); + expect(got!['workoutType'], 'B'); + expect((got['doneReps'] as List).first, [5, 4]); + }); + + test('readActiveSession returns null when nothing was exported', () async { + expect(await BackupService.instance.readActiveSession(), isNull); + }); + + test('exportActiveSession(null) deletes the mirror', () async { + await BackupService.instance.exportActiveSession({'workoutType': 'A'}); + await BackupService.instance.exportActiveSession(null); + expect(await BackupService.instance.readActiveSession(), isNull); + }); + + test('a corrupt mirror is ignored, not thrown', () async { + // A truncated write (battery death mid-set) must not brick the resume. + File('${tempDir.path}/active_session.json').writeAsStringSync('{not json'); + expect(await BackupService.instance.readActiveSession(), isNull); + }); + + test('a non-object mirror is ignored', () async { + File('${tempDir.path}/active_session.json').writeAsStringSync('[1,2]'); + expect(await BackupService.instance.readActiveSession(), isNull); + }); } diff --git a/stronglift_replacement/workout_app/test/services/storage_service_test.dart b/stronglift_replacement/workout_app/test/services/storage_service_test.dart index 49ddc21..8b7077c 100644 --- a/stronglift_replacement/workout_app/test/services/storage_service_test.dart +++ b/stronglift_replacement/workout_app/test/services/storage_service_test.dart @@ -53,6 +53,59 @@ void main() { expect(loaded!['workoutType'], 'A'); }); + test('survives a full app-data wipe via the external mirror', () async { + // Regression: `pm clear` (or an uninstall) wipes app-private SQLite, + // which is where active_session lives — the user lost the exact set and + // reps they were standing on mid-workout. The mirror must bring it back. + final tmp = Directory.systemTemp.createTempSync('mw_active_wipe'); + BackupService.baseDirForTesting = tmp.path; + addTearDown(() { + BackupService.baseDirForTesting = kBackupDir; + tmp.deleteSync(recursive: true); + }); + + await _svc.saveActiveSession({ + 'workoutType': 'B', + 'tapped': [ + [true, true, false], + ], + 'doneReps': [ + [5, 4, 0], + ], + }); + // Give the unawaited mirror write a turn to land. + await Future.delayed(Duration.zero); + + // Simulate the wipe: app-private DB gone, external mirror untouched. + StorageService.resetForTesting(); + await StorageService.init(); + + final recovered = await _svc.loadActiveSession(); + expect(recovered, isNotNull, reason: 'the in-progress set must survive'); + expect(recovered!['workoutType'], 'B'); + expect((recovered['doneReps'] as List).first, [5, 4, 0]); + // And it re-seeded the table, so the next read needs no mirror. + expect(await _svc.loadActiveSession(), isNotNull); + }); + + test('clearActiveSession also clears the mirror', () async { + // Otherwise a finished workout would be resurrected on next launch. + final tmp = Directory.systemTemp.createTempSync('mw_active_clear'); + BackupService.baseDirForTesting = tmp.path; + addTearDown(() { + BackupService.baseDirForTesting = kBackupDir; + tmp.deleteSync(recursive: true); + }); + + await _svc.saveActiveSession({'workoutType': 'A'}); + await Future.delayed(Duration.zero); + await _svc.clearActiveSession(); + + StorageService.resetForTesting(); + await StorageService.init(); + expect(await _svc.loadActiveSession(), isNull); + }); + test('saveActiveSession replaces previous entry', () async { await _svc.saveActiveSession({'v': 1}); await _svc.saveActiveSession({'v': 2});