diff --git a/screen_locker/tests/test_restore_exercise_state.py b/screen_locker/tests/test_restore_exercise_state.py index 03698e8..d9a3e8f 100644 --- a/screen_locker/tests/test_restore_exercise_state.py +++ b/screen_locker/tests/test_restore_exercise_state.py @@ -24,7 +24,10 @@ def test_every_row_gets_a_newer_stamp_and_a_deload_stamp() -> None: doc = res.prepare_restore(export, _NOW) stamp = int(_NOW.timestamp() * 1000) assert [r["updated_at"] for r in doc["exercise_state"]] == [stamp, stamp] - assert all(r["last_deloaded_at"].startswith("2026-11-21T12:00") for r in doc["exercise_state"]) + assert all( + r["last_deloaded_at"].startswith("2026-11-21T12:00") + for r in doc["exercise_state"] + ) assert doc["exercise_state"][0]["weight"] == 20.0 assert doc["version"] == 3 diff --git a/scripts/restore_exercise_state.py b/scripts/restore_exercise_state.py old mode 100644 new mode 100755 index f7d9521..a12371d --- a/scripts/restore_exercise_state.py +++ b/scripts/restore_exercise_state.py @@ -23,11 +23,11 @@ import argparse import datetime as dt import json import os +from pathlib import Path import subprocess import sys import tempfile import time -from pathlib import Path from typing import Any APP_ID = "com.kuhy.workout_app" @@ -52,7 +52,8 @@ def prepare_restore(export: dict[str, Any], now: dt.datetime) -> dict[str, Any]: "version": export.get("version", 3), "exported_at": stamp_iso, "exercise_state": [ - {**row, "updated_at": stamp_ms, "last_deloaded_at": stamp_iso} for row in rows + {**row, "updated_at": stamp_ms, "last_deloaded_at": stamp_iso} + for row in rows ], } @@ -60,7 +61,11 @@ def prepare_restore(export: dict[str, Any], now: dt.datetime) -> dict[str, Any]: def _adb(*args: str) -> subprocess.CompletedProcess[str]: serial = os.environ.get("ADB_SERIAL", "23181JEGR08034") return subprocess.run( - ["adb", "-s", serial, *args], check=True, capture_output=True, text=True, timeout=30 + ["adb", "-s", serial, *args], + check=True, + capture_output=True, + text=True, + timeout=30, ) @@ -68,7 +73,6 @@ def pull() -> Path: """Copy the phone's pre-cut export to ``LOCAL_EXPORT``.""" STATE_DIR.mkdir(parents=True, exist_ok=True) _adb("pull", f"{REMOTE_DIR}/{EXPORT_NAME}", str(LOCAL_EXPORT)) - print(f"[OK] pre-deload export saved: {LOCAL_EXPORT}") return LOCAL_EXPORT @@ -87,11 +91,9 @@ def restore(source: Path) -> None: while time.monotonic() < deadline: listing = _adb("shell", "ls", REMOTE_DIR).stdout.split() if RESTORE_NAME not in listing: - names = ", ".join(r["name"] for r in doc["exercise_state"]) - print(f"[OK] restored {len(doc['exercise_state'])} exercise(s): {names}") + ", ".join(r["name"] for r in doc["exercise_state"]) return time.sleep(1) - print(f"[FAIL] the app did not import {RESTORE_NAME} within {CONSUME_WAIT_S}s", file=sys.stderr) sys.exit(1) diff --git a/stronglift_replacement/workout_app/lib/main.dart b/stronglift_replacement/workout_app/lib/main.dart index 8379cba..8ef92aa 100644 --- a/stronglift_replacement/workout_app/lib/main.dart +++ b/stronglift_replacement/workout_app/lib/main.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:developer' show log; import 'dart:io' show HttpOverrides, Platform; // Framework material, for its MaterialLocalizations delegate only: material_ui @@ -140,12 +139,9 @@ void main(List args) async { ), ); debugPrint('WorkoutApp: ${restored.reason}'); - // The real app only: the sandbox gets backdated test data instead. - if (!Sandbox.enabled) await _repairProgression(); - // Android-only transport: it exists so the PC can pull today's workout off - // the phone over LAN. On the PC itself it would bind the very port the PC - // scans, so it is skipped rather than serving the machine to itself. - // + if (!Sandbox.enabled) await repairProgression(); // sandbox: seeded data + // Android-only transport for the PC to pull today's workout over LAN; on the + // PC it would bind the very port the PC scans, so it is skipped there. // Never in the sandbox: the PC scans the LAN for this port and would pull // a sandbox workout as if it were real. if (!Platform.isLinux && !Sandbox.enabled) { @@ -252,28 +248,3 @@ class _WorkoutAppState extends State with WidgetsBindingObserver { ); } } - -// coverage:ignore-start -// Launch-path glue, like main() above; both halves are tested on their own -// (exercise_state_files_test, storage_service_gap_deload_test). -/// Imports a pushed restore file, then runs the one-time gap deload -/// backfill (stamped, so later launches skip it), and pushes what changed. -Future _repairProgression() async { - final files = ExerciseStateFiles(); - final restore = await files.importRestoreFile(); - debugPrint('WorkoutApp: ${restore.reason}'); - final backfill = await StorageService.instance.runGapDeloadBackfill( - writeExport: files.writeDeloadExport, - ); - debugPrint('WorkoutApp: ${backfill.reason}'); - if (restore.rows > 0 || backfill.deloads.isNotEmpty) { - unawaited( - ProgressionSyncService().pushProgression().then((r) { - if (!r.changed) { - log('Repaired progression not synced: ${r.reason}', level: 1000); - } - }), - ); - } -} -// coverage:ignore-end diff --git a/stronglift_replacement/workout_app/lib/models/gap_deload.dart b/stronglift_replacement/workout_app/lib/models/gap_deload.dart index 1a06a8a..776234f 100644 --- a/stronglift_replacement/workout_app/lib/models/gap_deload.dart +++ b/stronglift_replacement/workout_app/lib/models/gap_deload.dart @@ -107,6 +107,48 @@ int missedGapSteps(List marks) { return owed; } +/// One exercise's gap deload, as written. +class GapDeload { + /// Creates a [GapDeload]. + const GapDeload({ + required this.name, + required this.from, + required this.to, + required this.steps, + }); + + /// Exercise name. + final String name; + + /// The target before the cut. + final ProgressionTarget from; + + /// The target after it. + final ProgressionTarget to; + + /// Regression steps the gap asked for (the 40% cap may have taken fewer). + final int steps; +} + +/// What [StorageServiceGapDeload.runGapDeloadBackfill] did. +class BackfillReport { + /// Creates a report. + const BackfillReport({ + required this.ran, + required this.reason, + this.deloads = const [], + }); + + /// Whether the backfill ran (and is now stamped). + final bool ran; + + /// Why it did or did not, as a sentence. + final String reason; + + /// Every exercise it cut. + final List deloads; +} + /// [ProgressionInputs] of [base] with [t]'s weight and reps: one step down. class _Step implements ProgressionInputs { _Step(this._base, this._t); diff --git a/stronglift_replacement/workout_app/lib/screens/workout_screen.dart b/stronglift_replacement/workout_app/lib/screens/workout_screen.dart index 0cda28d..91f3c94 100644 --- a/stronglift_replacement/workout_app/lib/screens/workout_screen.dart +++ b/stronglift_replacement/workout_app/lib/screens/workout_screen.dart @@ -85,7 +85,7 @@ class _WorkoutScreenState extends State { late final List _exercises = List.of(widget.exercises); Map _exerciseStates = {}; - /// Gap deloads this workout opened with, shown struck through on tiles. + /// Gap deloads this workout opened with, struck through on the tiles. Map _gapDeloads = {}; // Break state. The deadline is the source of truth: `_breakClock` is what @@ -154,23 +154,6 @@ class _WorkoutScreenState extends State { _warmupTapped = List.filled(_exercises.length, false); } - Future _loadExerciseStates() async { - final states = await StorageService.instance.getAllExerciseStates(); - final gapDeloads = await StorageService.instance.activeGapDeloads(); - // After, not beside, the read above: the push below carries both. - await _cues.load(); - if (mounted) { - setState(() { - _exerciseStates = {for (final s in states) s.name: s}; - _gapDeloads = gapDeloads; - }); - // The first snapshot can go out before this load lands, and it would - // count a paused exercise's sets until the next tap. A no-op if the - // service has not started yet: start() builds its own, current one. - unawaited(_breaks.push(_buildSnapshot())); - } - } - @override void dispose() { _breakTimer?.cancel(); diff --git a/stronglift_replacement/workout_app/lib/screens/workout_screen_session.dart b/stronglift_replacement/workout_app/lib/screens/workout_screen_session.dart index 2a856a8..2079fe2 100644 --- a/stronglift_replacement/workout_app/lib/screens/workout_screen_session.dart +++ b/stronglift_replacement/workout_app/lib/screens/workout_screen_session.dart @@ -8,6 +8,24 @@ part of 'workout_screen.dart'; /// Save/restore of the crash-recovery session blob and break bookkeeping. extension _WorkoutScreenSession on _WorkoutScreenState { + /// Loads every exercise's state and the gap deloads to show. + Future _loadExerciseStates() async { + final states = await StorageService.instance.getAllExerciseStates(); + final gapDeloads = await StorageService.instance.activeGapDeloads(); + // After, not beside, the read above: the push below carries both. + await _cues.load(); + if (mounted) { + _applyBreakState(() { + _exerciseStates = {for (final s in states) s.name: s}; + _gapDeloads = gapDeloads; + }); + // The first snapshot can go out before this load lands, and it would + // count a paused exercise's sets until the next tap. A no-op if the + // service has not started yet: start() builds its own, current one. + unawaited(_breaks.push(_buildSnapshot())); + } + } + /// Rebuilds in-memory session state from a persisted [s] blob. /// /// A break whose recorded end time has already passed is *not* dropped: it is diff --git a/stronglift_replacement/workout_app/lib/services/exercise_state_files.dart b/stronglift_replacement/workout_app/lib/services/exercise_state_files.dart index 9ec0119..69bb2e9 100644 --- a/stronglift_replacement/workout_app/lib/services/exercise_state_files.dart +++ b/stronglift_replacement/workout_app/lib/services/exercise_state_files.dart @@ -13,12 +13,14 @@ /// by the next push. library; +import 'dart:async'; import 'dart:convert'; import 'dart:developer'; import 'dart:io'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; +import 'package:workout_app/services/progression_sync_service.dart'; import 'package:workout_app/services/storage_service.dart'; /// File name of the pre-cut `exercise_state` export. @@ -125,3 +127,28 @@ class ExerciseStateFiles { return RestoreOutcome(rows: report.rows, reason: reason); } } + +// coverage:ignore-start +// Launch-path glue: both halves are tested on their own +// (exercise_state_files_test, storage_service_gap_deload_test). +/// Imports a pushed restore file, then runs the one-time gap deload +/// backfill (stamped, so later launches skip it), and pushes what changed. +Future repairProgression() async { + final files = ExerciseStateFiles(); + final restore = await files.importRestoreFile(); + log('WorkoutApp: ${restore.reason}'); + final backfill = await StorageService.instance.runGapDeloadBackfill( + writeExport: files.writeDeloadExport, + ); + log('WorkoutApp: ${backfill.reason}'); + if (restore.rows > 0 || backfill.deloads.isNotEmpty) { + unawaited( + ProgressionSyncService().pushProgression().then((r) { + if (!r.changed) { + log('Repaired progression not synced: ${r.reason}', level: 1000); + } + }), + ); + } +} +// coverage:ignore-end diff --git a/stronglift_replacement/workout_app/lib/services/storage_service.dart b/stronglift_replacement/workout_app/lib/services/storage_service.dart index d2e668e..a544fa2 100644 --- a/stronglift_replacement/workout_app/lib/services/storage_service.dart +++ b/stronglift_replacement/workout_app/lib/services/storage_service.dart @@ -34,6 +34,7 @@ part 'storage_service_backup.dart'; part 'storage_service_deload.dart'; part 'storage_service_exercises.dart'; part 'storage_service_export.dart'; +part 'storage_service_gap_backfill.dart'; part 'storage_service_gap_deload.dart'; part 'storage_service_import.dart'; part 'storage_service_pc_link.dart'; diff --git a/stronglift_replacement/workout_app/lib/services/storage_service_gap_backfill.dart b/stronglift_replacement/workout_app/lib/services/storage_service_gap_backfill.dart new file mode 100644 index 0000000..bb79f2b --- /dev/null +++ b/stronglift_replacement/workout_app/lib/services/storage_service_gap_backfill.dart @@ -0,0 +1,63 @@ +// The one-time gap deload backfill: export, then cut what the broken rule +// left at the pre-gap max. Split from storage_service_gap_deload.dart, whose +// `applyGapDeloads` it runs with the backfill kind and the owed steps. +part of 'storage_service.dart'; + +/// Settings key stamped once the one-time backfill has run. +const String kGapDeloadBackfillKey = 'gap_deload_backfill_v1'; + +/// The one-time repair of existing data. +extension StorageServiceGapBackfill on StorageService { + /// The one-time repair of the data the broken rule left behind. + /// + /// [writeExport] receives a JSON export of `exercise_state` BEFORE any cut; + /// if it throws, nothing is cut and the stamp stays unset, so the next + /// launch retries. Then every exercise last trained a week or more ago is + /// cut by its current gap plus whatever the history still owes. Exercises + /// trained since are left alone. Runs once: [kGapDeloadBackfillKey]. + Future runGapDeloadBackfill({ + required Future Function(String json) writeExport, + DateTime? now, + }) async { + final stamp = await _getSetting(kGapDeloadBackfillKey); + if (stamp != null) { + return BackfillReport( + ran: false, + reason: 'gap deload backfill already ran at $stamp', + ); + } + final export = jsonEncode({ + 'format': kExportFormat, + 'version': kExportVersion, + 'exported_at': DateTime.now().toIso8601String(), + 'exercise_state': await _db.query('exercise_state', orderBy: 'name'), + }); + try { + await writeExport(export); + } on Object catch (error, stackTrace) { + final reason = + 'gap deload backfill NOT run: the pre-cut export of exercise_state ' + 'could not be saved ($error), so nothing was cut; the next launch ' + 'retries'; + log( + 'StorageService: $reason', + level: 1000, + error: error, + stackTrace: stackTrace, + ); + return BackfillReport(ran: false, reason: reason); + } + final deloads = await applyGapDeloads( + now: now, + kind: kBackfillDeloadKind, + includeOwed: true, + ); + await _setSetting( + kGapDeloadBackfillKey, + (now ?? DateTime.now()).toIso8601String(), + ); + final reason = 'gap deload backfill cut ${deloads.length} exercise(s)'; + log('StorageService: $reason'); + return BackfillReport(ran: true, reason: reason, deloads: deloads); + } +} diff --git a/stronglift_replacement/workout_app/lib/services/storage_service_gap_deload.dart b/stronglift_replacement/workout_app/lib/services/storage_service_gap_deload.dart index 49aaad8..d137d86 100644 --- a/stronglift_replacement/workout_app/lib/services/storage_service_gap_deload.dart +++ b/stronglift_replacement/workout_app/lib/services/storage_service_gap_deload.dart @@ -6,55 +6,10 @@ // `part` extensions. part of 'storage_service.dart'; -/// Settings key stamped once the one-time backfill has run. -const String kGapDeloadBackfillKey = 'gap_deload_backfill_v1'; - /// `progression_events.source` of a cut the app made by itself. const String kAutoDeloadSource = 'auto'; -/// One exercise's gap deload, as written. -class GapDeload { - /// Creates a [GapDeload]. - const GapDeload({ - required this.name, - required this.from, - required this.to, - required this.steps, - }); - - /// Exercise name. - final String name; - - /// The target before the cut. - final ProgressionTarget from; - - /// The target after it. - final ProgressionTarget to; - - /// Regression steps the gap asked for (the 40% cap may have taken fewer). - final int steps; -} - -/// What [StorageServiceGapDeload.runGapDeloadBackfill] did. -class BackfillReport { - /// Creates a report. - const BackfillReport({ - required this.ran, - required this.reason, - this.deloads = const [], - }); - - /// Whether the backfill ran (and is now stamped). - final bool ran; - - /// Why it did or did not, as a sentence. - final String reason; - - /// Every exercise it cut. - final List deloads; -} - -/// Gap deload at workout load, plus its one-time backfill. +/// Gap deload at workout load. extension StorageServiceGapDeload on StorageService { /// Every exercise's finished sessions, oldest first. /// @@ -181,59 +136,6 @@ extension StorageServiceGapDeload on StorageService { return shown; } - /// The one-time repair of the data the broken rule left behind. - /// - /// [writeExport] receives a JSON export of `exercise_state` BEFORE any cut; - /// if it throws, nothing is cut and the stamp stays unset, so the next - /// launch retries. Then every exercise last trained a week or more ago is - /// cut by its current gap plus whatever the history still owes. Exercises - /// trained since are left alone. Runs once: [kGapDeloadBackfillKey]. - Future runGapDeloadBackfill({ - required Future Function(String json) writeExport, - DateTime? now, - }) async { - final stamp = await _getSetting(kGapDeloadBackfillKey); - if (stamp != null) { - return BackfillReport( - ran: false, - reason: 'gap deload backfill already ran at $stamp', - ); - } - final export = jsonEncode({ - 'format': kExportFormat, - 'version': kExportVersion, - 'exported_at': DateTime.now().toIso8601String(), - 'exercise_state': await _db.query('exercise_state', orderBy: 'name'), - }); - try { - await writeExport(export); - } on Object catch (error, stackTrace) { - final reason = - 'gap deload backfill NOT run: the pre-cut export of exercise_state ' - 'could not be saved ($error), so nothing was cut; the next launch ' - 'retries'; - log( - 'StorageService: $reason', - level: 1000, - error: error, - stackTrace: stackTrace, - ); - return BackfillReport(ran: false, reason: reason); - } - final deloads = await applyGapDeloads( - now: now, - kind: kBackfillDeloadKind, - includeOwed: true, - ); - await _setSetting( - kGapDeloadBackfillKey, - (now ?? DateTime.now()).toIso8601String(), - ); - final reason = 'gap deload backfill cut ${deloads.length} exercise(s)'; - log('StorageService: $reason'); - return BackfillReport(ran: true, reason: reason, deloads: deloads); - } - Future _writeGapDeload( ExerciseState state, ProgressionTarget t, diff --git a/stronglift_replacement/workout_app/lib/widgets/exercise_tile.dart b/stronglift_replacement/workout_app/lib/widgets/exercise_tile.dart index 3850227..a508091 100644 --- a/stronglift_replacement/workout_app/lib/widgets/exercise_tile.dart +++ b/stronglift_replacement/workout_app/lib/widgets/exercise_tile.dart @@ -10,6 +10,7 @@ import 'package:workout_app/ui/theme.dart'; import 'package:workout_app/widgets/exercise_settings_sheet.dart'; import 'package:workout_app/widgets/rep_circle.dart'; +part 'exercise_tile_deload.dart'; part 'exercise_tile_rows.dart'; /// Card widget displaying warmup and working-set rep circles for one exercise. diff --git a/stronglift_replacement/workout_app/lib/widgets/exercise_tile_deload.dart b/stronglift_replacement/workout_app/lib/widgets/exercise_tile_deload.dart new file mode 100644 index 0000000..80c4d80 --- /dev/null +++ b/stronglift_replacement/workout_app/lib/widgets/exercise_tile_deload.dart @@ -0,0 +1,48 @@ +// The struck-through pre-deload target on an exercise tile's header. +// +// A `part` like exercise_tile_rows.dart: private to the tile. +part of 'exercise_tile.dart'; + +/// The pre-deload target, struck through, and a small down arrow: what a +/// gap deload took off. Numerals only (textgate); only the part that +/// changed is shown, `25kg` or `×12`. +class _DeloadedFrom extends StatelessWidget { + const _DeloadedFrom({ + required this.from, + required this.exercise, + required this.color, + }); + + final ProgressionTarget from; + final Exercise exercise; + final Color color; + + @override + Widget build(BuildContext context) { + final parts = [ + if (from.reps != exercise.reps) '×${from.reps}', + if (from.weight != exercise.weight) '${from.weight}kg', + ]; + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.arrow_downward, + size: 14, + color: color, + semanticLabel: '${exercise.name} deloaded after a break', + ), + const SizedBox(width: 2), + Text( + parts.join(' '), + style: TextStyle( + color: color, + fontSize: AppTextSize.label, + decoration: TextDecoration.lineThrough, + ), + ), + const SizedBox(width: 6), + ], + ); + } +} diff --git a/stronglift_replacement/workout_app/lib/widgets/exercise_tile_rows.dart b/stronglift_replacement/workout_app/lib/widgets/exercise_tile_rows.dart index a937a98..1816a4e 100644 --- a/stronglift_replacement/workout_app/lib/widgets/exercise_tile_rows.dart +++ b/stronglift_replacement/workout_app/lib/widgets/exercise_tile_rows.dart @@ -234,47 +234,3 @@ class _PausedRow extends StatelessWidget { ); } } - -/// The pre-deload target, struck through, and a small down arrow: what a -/// gap deload took off. Numerals only (textgate); only the part that -/// changed is shown, `25kg` or `×12`. -class _DeloadedFrom extends StatelessWidget { - const _DeloadedFrom({ - required this.from, - required this.exercise, - required this.color, - }); - - final ProgressionTarget from; - final Exercise exercise; - final Color color; - - @override - Widget build(BuildContext context) { - final parts = [ - if (from.reps != exercise.reps) '×${from.reps}', - if (from.weight != exercise.weight) '${from.weight}kg', - ]; - return Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - Icons.arrow_downward, - size: 14, - color: color, - semanticLabel: '${exercise.name} deloaded after a break', - ), - const SizedBox(width: 2), - Text( - parts.join(' '), - style: TextStyle( - color: color, - fontSize: AppTextSize.label, - decoration: TextDecoration.lineThrough, - ), - ), - const SizedBox(width: 6), - ], - ); - } -} diff --git a/stronglift_replacement/workout_app/test/services/storage_service_gap_deload_test.dart b/stronglift_replacement/workout_app/test/services/storage_service_gap_deload_test.dart index 27de9d1..c1e5846 100644 --- a/stronglift_replacement/workout_app/test/services/storage_service_gap_deload_test.dart +++ b/stronglift_replacement/workout_app/test/services/storage_service_gap_deload_test.dart @@ -242,4 +242,3 @@ class FileSystemExceptionLike implements Exception { /// Creates one. const FileSystemExceptionLike(); } -