Compare commits

..

8 Commits

Author SHA1 Message Date
c4dc30502b Cover gap deload launch, seed and edge rows
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze,dependency-freshness) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:57:40 +01:00
218e84e04a Make the v10 migration idempotent
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:40:44 +01:00
394ff70dc5 Load gap deload marks after the snapshot push
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:27:44 +01:00
9b50d95386 Resolve adb path in restore script; trim header
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:22:24 +01:00
1cbb310ff7 Split gap deload files under the 250-line cap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:20:28 +01:00
be15e1c083 Docstrings for restore script tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:15:54 +01:00
a5ec96f1b8 Fix gap deload tile test label lookup
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:11:54 +01:00
bc4e590822 workout_app: deload after a training gap at load
The old break rule ran at finish after the session was saved, so
daysSince was always 0 and it never fired. Now the gap deload cuts
by tier (7-13d 1 step, 14-20d 2, +1/week, 40% cap) when the workout
loads, stamps last_deloaded_at (shared with manual deload, synced),
logs progression_events, and shows the old target struck through.
One-time backfill with pre-cut export + restore script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:11:54 +01:00
37 changed files with 1723 additions and 75 deletions

View File

@ -0,0 +1,38 @@
"""Restore of the pre-gap-deload export (scripts/restore_exercise_state.py)."""
from __future__ import annotations
import datetime as dt
import pytest
from scripts import restore_exercise_state as res
_NOW = dt.datetime(2026, 11, 21, 12, 0, tzinfo=dt.UTC)
def test_every_row_gets_a_newer_stamp_and_a_deload_stamp() -> None:
"""Each row wins the import and is shielded from a second auto cut."""
export = {
"format": "workout_app-export",
"version": 3,
"exercise_state": [
{"name": "Dumbbell Lunge", "weight": 20.0, "updated_at": 5},
{"name": "Situp", "weight": 10.0, "updated_at": 0},
],
}
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 doc["exercise_state"][0]["weight"] == 20.0
assert doc["version"] == 3
def test_an_empty_export_is_refused() -> None:
"""An export with no rows is refused instead of restoring nothing."""
with pytest.raises(ValueError, match="nothing to restore"):
res.prepare_restore({"exercise_state": []}, _NOW)

View File

@ -101,6 +101,24 @@ desktop() {
ok "restarted ${UNITS[*]}"
}
# The app's one-time gap deload backfill saves the pre-cut exercise_state on
# its first start after install; keep a PC copy so restore works without the
# phone's dir. The app needs a few seconds after launch, hence the retries;
# a miss only warns, `restore_exercise_state.py pull` fetches it later.
deload_export() {
local tries
[[ -f "$HOME/.local/state/screen-locker/exercise_state_pre_gap_deload.json" ]] && return 0
for tries in 1 2 3 4 5 6 7 8 9 10; do
if python3 "$LIVE/scripts/restore_exercise_state.py" pull >/dev/null 2>&1; then
ok "pre-gap-deload export copied to ~/.local/state/screen-locker/"
return 0
fi
sleep 2
done
echo "deploy: WARN: no pre-gap-deload export pulled after $tries tries;" \
"run: python3 $LIVE/scripts/restore_exercise_state.py pull" >&2
}
phone() {
local rc=0 tree
tree="$(git -C "$LIVE" rev-parse "HEAD:$APP_DIR")" || die "no $APP_DIR tree at $LIVE HEAD"
@ -114,6 +132,7 @@ phone() {
mkdir -p "$(dirname "$PHONE_APP_MARKER")"
printf '%s\n' "$tree" > "$PHONE_APP_MARKER"
ok "workout app release build installed on the phone (tree ${tree:0:10})"
deload_export
;;
46) die "phone_deploy protect guard (exit 46) refused com.kuhy.workout_app;" \
"kuhy runs: PHONE_PROTECT_ALLOW=com.kuhy.workout_app bash $LIVE/scripts/deploy.sh" \

120
scripts/restore_exercise_state.py Executable file
View File

@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Pull or restore the workout app's pre-gap-deload ``exercise_state`` export.
The phone's one-time gap deload backfill saves the pre-cut weights as
``exercise_state_pre_gap_deload.json`` in the app's external files dir
before it cuts anything.
restore_exercise_state.py pull # copy it to ~/.local/state/screen-locker/
restore_exercise_state.py restore # put those weights back on the phone
``restore`` stamps every row with a newer ``updated_at`` (so the app's import
lets it win) and a fresh ``last_deloaded_at`` (so the gap deload does not cut
the restored weights again before the next session), pushes it as
``restore_exercise_state.json``, restarts the app, and checks that the app
consumed the file. The app then pushes the restored state to Firebase.
Restore goes through the phone, not Firebase: after its first reconcile the
phone never pulls progression, so a Firebase-side write would never land.
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import time
from typing import Any
APP_ID = "com.kuhy.workout_app"
REMOTE_DIR = f"/sdcard/Android/data/{APP_ID}/files"
EXPORT_NAME = "exercise_state_pre_gap_deload.json"
RESTORE_NAME = "restore_exercise_state.json"
STATE_DIR = Path.home() / ".local/state/screen-locker"
LOCAL_EXPORT = STATE_DIR / EXPORT_NAME
CONSUME_WAIT_S = 20
def prepare_restore(export: dict[str, Any], now: dt.datetime) -> dict[str, Any]:
"""Return an import document that makes every exported row win."""
rows = export.get("exercise_state")
if not isinstance(rows, list) or not rows:
msg = "export has no exercise_state rows; nothing to restore"
raise ValueError(msg)
stamp_ms = int(now.timestamp() * 1000)
stamp_iso = now.replace(tzinfo=None).isoformat(timespec="microseconds")
return {
"format": export.get("format", "workout_app-export"),
"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
],
}
def _adb(*args: str) -> subprocess.CompletedProcess[str]:
serial = os.environ.get("ADB_SERIAL", "23181JEGR08034")
adb = shutil.which("adb")
if adb is None:
msg = "adb is not on PATH (sudo pacman -S android-tools)"
raise FileNotFoundError(msg)
return subprocess.run(
[adb, "-s", serial, *args],
check=True,
capture_output=True,
text=True,
timeout=30,
)
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))
return LOCAL_EXPORT
def restore(source: Path) -> None:
"""Push ``source`` back to the phone and confirm the app imported it."""
export = json.loads(source.read_text(encoding="utf-8"))
doc = prepare_restore(export, dt.datetime.now().astimezone())
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / RESTORE_NAME
path.write_text(json.dumps(doc), encoding="utf-8")
_adb("push", str(path), f"{REMOTE_DIR}/{RESTORE_NAME}")
# Force-stop keeps the app's data; the next start imports the file.
_adb("shell", "am", "force-stop", APP_ID)
_adb("shell", "monkey", "-p", APP_ID, "-c", "android.intent.category.LAUNCHER", "1")
deadline = time.monotonic() + CONSUME_WAIT_S
while time.monotonic() < deadline:
listing = _adb("shell", "ls", REMOTE_DIR).stdout.split()
if RESTORE_NAME not in listing:
", ".join(r["name"] for r in doc["exercise_state"])
return
time.sleep(1)
sys.exit(1)
def main(argv: list[str] | None = None) -> None:
"""Parse the command line and run ``pull`` or ``restore``."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("pull", help="copy the phone's pre-deload export to the PC")
rest = sub.add_parser("restore", help="write the exported weights back")
rest.add_argument("--file", type=Path, default=LOCAL_EXPORT)
args = parser.parse_args(argv)
if args.cmd == "pull":
pull()
else:
restore(args.file)
if __name__ == "__main__":
main()

View File

@ -16,6 +16,7 @@ import 'package:workout_app/sandbox/sandbox_log.dart';
import 'package:workout_app/screens/home_screen.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/break_service_controller.dart';
import 'package:workout_app/services/exercise_state_files.dart';
import 'package:workout_app/services/foreground_break_client_flutter.dart';
import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/http_server_service.dart';
@ -138,10 +139,9 @@ void main(List<String> args) async {
),
);
debugPrint('WorkoutApp: ${restored.reason}');
// 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) {

View File

@ -49,6 +49,7 @@ class ExerciseState implements ProgressionInputs {
required this.restSuccessSecs,
required this.restFailSecs,
required this.restWarmupSecs,
this.lastDeloadedAt,
});
/// The state a never-trained [ex] starts from.
@ -128,6 +129,13 @@ class ExerciseState implements ProgressionInputs {
/// Rest after the warmup set, in seconds.
final int restWarmupSecs;
/// When the target was last cut by a deload -- manual, gap or backfill --
/// or null if never. One shared stamp: the gap deload skips an exercise
/// deloaded after its last session, so nothing is cut twice. Optional
/// (unlike the rest) because only deloads write it; every other rebuild
/// carries it through [copyWith].
final DateTime? lastDeloadedAt;
/// Whether the exercise is paused at [now].
bool isPausedAt(DateTime now) {
final until = pausedUntil;
@ -150,6 +158,7 @@ class ExerciseState implements ProgressionInputs {
int? restSuccessSecs,
int? restFailSecs,
int? restWarmupSecs,
DateTime? lastDeloadedAt,
bool resume = false,
}) => ExerciseState(
name: name,
@ -169,6 +178,7 @@ class ExerciseState implements ProgressionInputs {
restSuccessSecs: restSuccessSecs ?? this.restSuccessSecs,
restFailSecs: restFailSecs ?? this.restFailSecs,
restWarmupSecs: restWarmupSecs ?? this.restWarmupSecs,
lastDeloadedAt: lastDeloadedAt ?? this.lastDeloadedAt,
);
}

View File

@ -0,0 +1,176 @@
/// The gap deload: how far a training break cuts an exercise's target.
///
/// Applied when the workout loads, not when it finishes. The old rule lived
/// in `applyProgression` and could never fire: finishing saves the session
/// first, so "days since the last workout" was always 0. It also only ever
/// took one step, so a two-week break started from the pre-gap max.
///
/// Pure on purpose: the storage layer decides *whether* an exercise is due
/// (stamp, history) and these functions decide *how much*.
library;
import 'package:workout_app/models/progression.dart';
/// Shortest break, in calendar days, that costs a step.
const int kGapDeloadMinDays = 7;
/// Every further week of break costs one more step.
const int kGapDeloadDaysPerStep = 7;
/// The most a gap deload may take off the pre-gap weight (or reps, in reps
/// mode): a hard cap, however long the break.
const double kGapDeloadMaxLoss = 0.4;
/// `progression_events.kind` of a deload a training gap caused at load.
const String kGapDeloadKind = 'gap_deload';
/// `progression_events.kind` of the one-time repair of existing data.
const String kBackfillDeloadKind = 'backfill_deload';
/// Calendar days from [from] to [to]: 23:00 to 01:00 next day is one day.
///
/// Built from UTC dates so a DST change inside the gap cannot shave an hour
/// off and turn 7 days into 6.
int gapCalendarDays(DateTime from, DateTime to) => DateTime.utc(
to.year,
to.month,
to.day,
).difference(DateTime.utc(from.year, from.month, from.day)).inDays;
/// Regression steps a break of [gapDays] calendar days costs: under 7 none,
/// 7-13 one, 14-20 two, then one more per extra week.
int gapDeloadSteps(int gapDays) => gapDays < kGapDeloadMinDays
? 0
: 1 + (gapDays - kGapDeloadMinDays) ~/ kGapDeloadDaysPerStep;
/// [s]'s target after [steps] regression steps, each one
/// [targetAfterFailure], stopping before any step that would take more than
/// [kGapDeloadMaxLoss] off [s]'s weight (or, in reps mode, its reps).
///
/// A step that alone breaks the cap is not taken: 5 kg -> 2.5 kg is a 50%
/// loss, so a 5 kg exercise keeps 5 kg. Double progression caps on weight
/// only; its rep drops within one weight are the small steps of the ladder.
ProgressionTarget gapDeloadTarget(ProgressionInputs s, int steps) {
final weightFloor = s.weight * (1 - kGapDeloadMaxLoss);
final repsFloor = (s.reps * (1 - kGapDeloadMaxLoss)).ceil();
var cur = s;
for (var i = 0; i < steps; i++) {
final t = targetAfterFailure(cur);
if (t.weight == cur.weight && t.reps == cur.reps) break;
// A tiny epsilon: 0.6 * 12.5 is 7.499999... in binary.
if (t.weight < weightFloor - 1e-9) break;
if (s.mode == ProgressionMode.reps && t.reps < repsFloor) break;
cur = _Step(s, t);
}
return ProgressionTarget(cur.weight, cur.reps);
}
/// One finished session of one exercise: when it ended and its target.
class SessionMark {
/// Creates a [SessionMark].
const SessionMark({
required this.endedAt,
required this.weight,
required this.reps,
});
/// When the session ended (local time).
final DateTime endedAt;
/// The target weight the session was done at, in kg.
final double weight;
/// The target reps the session was done at.
final int reps;
}
/// Steps the history still owes: the replay (part c) of the backfill.
///
/// Replays [marks] (oldest first) with the new rule. Each gap of a week or
/// more between two sessions should have cut the next one's target; when the
/// next session ran at the SAME target, that cut never happened and its
/// steps are owed. Any target change afterwards (a fail-streak deload, a
/// success step, a hand edit) re-anchors the replay on what was really
/// lifted, so the debt clears. That is kuhy's case: failed after a 7-day
/// break at the pre-gap weight, then a second break on top.
int missedGapSteps(List<SessionMark> marks) {
var owed = 0;
for (var i = 1; i < marks.length; i++) {
final prev = marks[i - 1];
final cur = marks[i];
if (cur.weight != prev.weight || cur.reps != prev.reps) {
owed = 0;
continue;
}
owed += gapDeloadSteps(gapCalendarDays(prev.endedAt, cur.endedAt));
}
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<GapDeload> deloads;
}
/// [ProgressionInputs] of [base] with [t]'s weight and reps: one step down.
class _Step implements ProgressionInputs {
_Step(this._base, this._t);
final ProgressionInputs _base;
final ProgressionTarget _t;
@override
double get weight => _t.weight;
@override
int get reps => _t.reps;
@override
double get maxWeight => _base.maxWeight;
@override
ProgressionMode get mode => _base.mode;
@override
int get repsHigh => _base.repsHigh;
@override
int get repsLow => _base.repsLow;
}

View File

@ -13,6 +13,7 @@ import 'package:workout_app/screens/settings_screen.dart';
import 'package:workout_app/screens/workout_screen.dart';
import 'package:workout_app/services/done_today.dart';
import 'package:workout_app/services/lock_mode.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_status.dart';
import 'package:workout_app/services/workout_sync_service.dart';
@ -90,8 +91,12 @@ class _HomeScreenState extends State<HomeScreen> {
Future<void> _load() async {
final storage = StorageService.instance;
final nextType = await storage.getNextWorkoutType();
final exercises = await storage.getCurrentExercises(nextType);
final saved = await storage.loadActiveSession();
// The gap deload runs before the targets are read, so the workout opens
// at the cut weight. Never under a saved session: that workout already
// started at its own targets. Stamped per exercise, so a reload is a no-op.
if (saved == null) await _applyGapDeloads(storage);
final exercises = await storage.getCurrentExercises(nextType);
final lastDate = await storage.getLastWorkoutDate();
final today = DateTime.now();
final doneLocally =

View File

@ -81,4 +81,23 @@ extension _HomeScreenLaunch on _HomeScreenState {
return false;
}
}
/// Cuts every exercise a training break made due, then pushes the cut to
/// Firebase so other devices see it. The phone is the only place this
/// runs; the PC only reads workouts and never cuts.
Future<void> _applyGapDeloads(StorageService storage) async {
final done = await storage.applyGapDeloads();
if (done.isEmpty) return;
SandboxLog.event('gap deload', {
for (final d in done) d.name: '${d.from.weight}x${d.from.reps}'
'->${d.to.weight}x${d.to.reps}',
});
unawaited(
ProgressionSyncService().pushProgression().then((r) {
if (!r.changed) {
log('Gap deload not synced: ${r.reason}', level: 1000);
}
}),
);
}
}

View File

@ -50,6 +50,11 @@ class _SandboxSectionState extends State<_SandboxSection> {
);
}
Future<void> _seedGaps() async {
await StorageService.instance.seedGapScenarios();
_report('Seeded backdated sessions; open the workout to see the cuts.');
}
Future<void> _saveRest() async {
final secs = int.tryParse(_rest.text.trim());
if (secs == null || secs < 1) {
@ -98,6 +103,13 @@ class _SandboxSectionState extends State<_SandboxSection> {
semanticLabel: 'Mark today not done',
),
),
ElevatedButton(
onPressed: () => unawaited(_seedGaps()),
child: const Icon(
Icons.history,
semanticLabel: 'Seed gap deload cases',
),
),
],
),
const SizedBox(height: 12),

View File

@ -85,6 +85,9 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
late final List<Exercise> _exercises = List.of(widget.exercises);
Map<String, ExerciseState> _exerciseStates = {};
/// Gap deloads this workout opened with, struck through on the tiles.
Map<String, ProgressionEvent> _gapDeloads = {};
// Break state. The deadline is the source of truth: `_breakClock` is what
// survives the app being backgrounded, and everything else is derived from
// it. See services/break_clock.dart for why a tick counter could not be.
@ -151,21 +154,6 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
_warmupTapped = List.filled(_exercises.length, false);
}
Future<void> _loadExerciseStates() async {
final states = await StorageService.instance.getAllExerciseStates();
// 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};
});
// 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();
@ -226,6 +214,7 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
child: _WorkoutBody(
exercises: _exercises,
exerciseStates: _exerciseStates,
gapDeloads: _gapDeloads,
tapped: _tapped,
doneReps: _doneReps,
warmupTapped: _warmupTapped,

View File

@ -33,8 +33,12 @@ class _WorkoutBody extends StatelessWidget {
required this.onTapWarmup,
required this.onSettingsChanged,
required this.onDeload,
this.gapDeloads = const {},
});
/// Gap deloads no session has followed yet, by exercise name.
final Map<String, ProgressionEvent> gapDeloads;
/// The exercises in this session, in display order.
final List<Exercise> exercises;
@ -145,6 +149,10 @@ class _WorkoutBody extends StatelessWidget {
onTapWarmup: () => onTapWarmup(i),
onSettingsChanged: onSettingsChanged,
onDeload: () => onDeload(i),
deloadedFrom: switch (gapDeloads[ex.name]) {
null => null,
final e => ProgressionTarget(e.fromWeight, e.fromReps),
},
);
}
}

View File

@ -85,13 +85,11 @@ extension _WorkoutScreenFinish on _WorkoutScreenState {
json: session.toJsonString(),
);
final lastDate = await storage.getLastWorkoutDate() ?? _startTime;
await storage.applyProgression(
succeededExercises: {
for (int i = 0; i < _exercises.length; i++)
_exercises[i].name: results[i].succeeded,
},
lastWorkoutDate: lastDate,
);
await storage.setLastWorkoutType(widget.workoutType);
await storage.clearActiveSession();

View File

@ -8,6 +8,27 @@ 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, then the gap deloads to show.
Future<void> _loadExerciseStates() async {
final storage = StorageService.instance;
final states = await storage.getAllExerciseStates();
// After, not beside, the read above: the push below carries both.
await _cues.load();
if (!mounted) return;
_applyBreakState(() {
_exerciseStates = {for (final s in states) s.name: s};
});
// 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()));
// Last, and only for the tiles: the struck-through pre-deload targets.
final gapDeloads = await storage.activeGapDeloads();
if (mounted && gapDeloads.isNotEmpty) {
_applyBreakState(() => _gapDeloads = gapDeloads);
}
}
/// Rebuilds in-memory session state from a persisted [s] blob.
///
/// A break whose recorded end time has already passed is *not* dropped: it is

View File

@ -0,0 +1,154 @@
/// The files around the one-time gap deload backfill: its pre-cut export
/// and the restore file `scripts/restore_exercise_state.py` pushes back.
///
/// Both live in the app's external files dir
/// (`/sdcard/Android/data/<package>/files`), the one place `adb` can reach on
/// a release build without storage permission. The export is also written
/// to the internal support dir, a second copy that survives a cleared
/// external dir.
///
/// The restore goes through the phone's own stamped import, not Firebase:
/// after its first reconcile the phone never pulls progression again (local
/// wins), so a PC-side Firebase write would never land and be overwritten
/// 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.
const String kDeloadExportFileName = 'exercise_state_pre_gap_deload.json';
/// File name the restore script pushes.
const String kRestoreFileName = 'restore_exercise_state.json';
/// What [ExerciseStateFiles.importRestoreFile] did.
class RestoreOutcome {
/// Creates an outcome.
const RestoreOutcome({required this.rows, required this.reason});
/// Rows the import wrote; 0 when no file was there or it was unusable.
final int rows;
/// Why, as a sentence.
final String reason;
}
// coverage:ignore-start
// Android-only plugin calls; the suite injects directories instead.
Future<List<Directory>> _defaultExportDirs() async => [
await getApplicationSupportDirectory(),
if (Platform.isAndroid) ?await getExternalStorageDirectory(),
];
Future<Directory?> _defaultRestoreDir() async =>
Platform.isAndroid ? await getExternalStorageDirectory() : null;
// coverage:ignore-end
/// Writes the backfill export and imports a pushed restore file.
class ExerciseStateFiles {
/// Creates the helper; the arguments are test seams.
ExerciseStateFiles({
Future<List<Directory>> Function()? exportDirs,
Future<Directory?> Function()? restoreDir,
}) : _exportDirs = exportDirs ?? _defaultExportDirs,
_restoreDir = restoreDir ?? _defaultRestoreDir;
final Future<List<Directory>> Function() _exportDirs;
final Future<Directory?> Function() _restoreDir;
/// Writes [json] to every export dir. Throws when none could be written,
/// which stops the backfill before it cuts anything.
Future<void> writeDeloadExport(String json) async {
var written = 0;
final failures = <String>[];
for (final dir in await _exportDirs()) {
try {
await dir.create(recursive: true);
await File(p.join(dir.path, kDeloadExportFileName)).writeAsString(json);
written++;
log('ExerciseStateFiles: pre-deload export saved in ${dir.path}');
} on FileSystemException catch (error) {
failures.add('${dir.path}: $error');
log(
'ExerciseStateFiles: pre-deload export NOT saved in ${dir.path} '
'($error).',
level: 900,
);
}
}
if (written == 0) {
throw FileSystemException(
'no copy of the pre-deload export could be written: '
'${failures.isEmpty ? 'no export directory' : failures.join('; ')}',
);
}
}
/// Imports [kRestoreFileName] if the restore script pushed one, then
/// renames it so the next launch does not import it again.
Future<RestoreOutcome> importRestoreFile() async {
final dir = await _restoreDir();
if (dir == null) {
return const RestoreOutcome(
rows: 0,
reason: 'no external files dir on this platform',
);
}
final file = File(p.join(dir.path, kRestoreFileName));
if (!file.existsSync()) {
return const RestoreOutcome(rows: 0, reason: 'no restore file pushed');
}
final ImportReport report;
try {
final data = jsonDecode(await file.readAsString());
report = await StorageService.instance.importDataReport(
data as Map<String, dynamic>,
);
} on Object catch (error) {
final reason =
'restore file ${file.path} is not a workout_app export ($error); '
'left in place, nothing restored';
log('ExerciseStateFiles: $reason', level: 1000);
return RestoreOutcome(rows: 0, reason: reason);
}
final done = '${file.path}.done-${DateTime.now().millisecondsSinceEpoch}';
await file.rename(done);
final reason =
'restore file imported ${report.rows} row(s); kept as $done';
log('ExerciseStateFiles: $reason', level: 900);
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<void> 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

View File

@ -111,6 +111,7 @@ class ProgressionSyncService {
'rest_success_secs': s.restSuccessSecs,
'rest_fail_secs': s.restFailSecs,
'rest_warmup_secs': s.restWarmupSecs,
'last_deloaded_at': s.lastDeloadedAt?.toIso8601String(),
};
// Every field after fail_threshold is lenient: records pushed before it
@ -135,6 +136,10 @@ class ProgressionSyncService {
(j['rest_fail_secs'] as num?)?.toInt() ?? kDefaultRestFailSecs,
restWarmupSecs:
(j['rest_warmup_secs'] as num?)?.toInt() ?? kDefaultRestWarmupSecs,
lastDeloadedAt: switch (j['last_deloaded_at']) {
final String raw => DateTime.tryParse(raw),
_ => null,
},
);
/// The remote path holding [name]'s progression record.

View File

@ -13,6 +13,7 @@ import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_state.dart';
import 'package:workout_app/models/gap_deload.dart';
import 'package:workout_app/models/manual_deload.dart';
import 'package:workout_app/models/progression.dart';
import 'package:workout_app/models/run_record.dart';
@ -23,8 +24,7 @@ import 'package:workout_app/services/manual_workout_port.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/services/progression_sync_service.dart';
// Re-exported: ExerciseState was defined here until it moved to models/, and
// every caller still reaches it through this import.
// Re-exported: callers reach ExerciseState etc. through this import.
export 'package:workout_app/models/exercise_state.dart';
export 'package:workout_app/models/manual_deload.dart';
export 'package:workout_app/models/progression.dart';
@ -33,6 +33,8 @@ 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';
part 'storage_service_runs.dart';
@ -100,7 +102,7 @@ class StorageService {
// coverage:ignore-end
_db = await openDatabase(
dbPath,
version: 9,
version: 10,
onCreate: _createSchema,
onUpgrade: _migrateSchema,
// In tests resetForTesting() reopens a ':memory:' DB per test; sqflite's

View File

@ -42,6 +42,9 @@ extension StorageServiceDeload on StorageService {
);
}
// One stamp for manual and gap deloads: the gap deload skips an
// exercise deloaded since its last session.
final at = DateTime.now();
final changed = await _db.transaction((txn) async {
final rows = await txn.update(
'exercise_state',
@ -50,6 +53,7 @@ extension StorageServiceDeload on StorageService {
'reps': t.reps,
'success_streak': 0,
'fail_streak': 0,
'last_deloaded_at': at.toIso8601String(),
'updated_at': _nowMs(),
},
where: 'name = ?',
@ -59,7 +63,7 @@ extension StorageServiceDeload on StorageService {
// must not leave an event describing a deload nobody received.
if (rows != 1) return false;
await txn.insert('progression_events', {
'at': DateTime.now().toIso8601String(),
'at': at.toIso8601String(),
'exercise': name,
'kind': kManualDeloadKind,
'source': source.storageKey,
@ -86,6 +90,7 @@ extension StorageServiceDeload on StorageService {
reps: t.reps,
successStreak: 0,
failStreak: 0,
lastDeloadedAt: at,
),
reason: reason,
);

View File

@ -35,6 +35,7 @@ extension StorageServiceExercises on StorageService {
restSuccessSecs: r['rest_success_secs']! as int,
restFailSecs: r['rest_fail_secs']! as int,
restWarmupSecs: r['rest_warmup_secs']! as int,
lastDeloadedAt: _parseDeloadStamp(r['last_deloaded_at']),
);
}
@ -153,6 +154,7 @@ extension StorageServiceExercises on StorageService {
'has_warmup': state.hasWarmup ? 1 : 0,
'paused_until': _pauseColumn(state),
..._restColumnValues(state),
'last_deloaded_at': state.lastDeloadedAt?.toIso8601String(),
'updated_at': _nowMs(),
}, conflictAlgorithm: ConflictAlgorithm.replace);
}

View File

@ -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<BackfillReport> runGapDeloadBackfill({
required Future<void> 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);
}
}

View File

@ -0,0 +1,218 @@
// The gap deload: cut a target after a training break, once, at load.
//
// Its own part next to storage_service_deload.dart: both write a target
// change plus its `progression_events` row in one transaction and share the
// `last_deloaded_at` stamp. See storage_service_backup.dart for why these are
// `part` extensions.
part of 'storage_service.dart';
/// `progression_events.source` of a cut the app made by itself.
const String kAutoDeloadSource = 'auto';
/// Gap deload at workout load.
extension StorageServiceGapDeload on StorageService {
/// Every exercise's finished sessions, oldest first.
///
/// Read from `workout_history`, which also holds sessions synced from other
/// devices. Manual logs (table tennis, "other") name no exercise, so they
/// cannot move a per-exercise gap.
Future<Map<String, List<SessionMark>>> sessionMarks() async {
final rows = await _db.query('workout_history', columns: ['date', 'json']);
final marks = <String, List<SessionMark>>{};
for (final row in rows) {
final payload = StorageServiceSessions._decodeJson(row['json']);
if (payload == null) continue;
final ended = _sessionEnd(payload, row['date']);
if (ended == null) {
log(
'StorageService: a session row has no readable end_time, '
'start_time or date — it does not count toward any training gap.',
level: 900,
);
continue;
}
final exercises = payload['exercises'];
if (exercises is! List) continue;
for (final ex in exercises) {
if (ex is! Map || ex['name'] is! String) continue;
marks
.putIfAbsent(ex['name']! as String, () => [])
.add(
SessionMark(
endedAt: ended,
// -1: an old row with no target breaks every replay chain
// instead of matching another unknown one.
weight: (ex['targetWeight'] as num?)?.toDouble() ?? -1,
reps: (ex['targetReps'] as num?)?.toInt() ?? -1,
),
);
}
}
for (final list in marks.values) {
list.sort((a, b) => a.endedAt.compareTo(b.endedAt));
}
return marks;
}
/// Cuts every exercise whose last session is a week or more before [now].
///
/// Skips an exercise deloaded (manually or by an earlier run of this)
/// after its last session, so reopening the workout never cuts twice.
/// With [includeOwed] (the backfill) the history's unpaid gaps are added
/// on top -- see [missedGapSteps] -- and the lower of the two results wins.
/// Every cut zeroes both streaks, stamps `last_deloaded_at` and logs a
/// `progression_events` row of [kind], in one transaction.
Future<List<GapDeload>> applyGapDeloads({
DateTime? now,
String kind = kGapDeloadKind,
bool includeOwed = false,
}) async {
final at = now ?? DateTime.now();
final marks = await sessionMarks();
final done = <GapDeload>[];
for (final state in await getAllExerciseStates()) {
final history = marks[state.name];
if (history == null || history.isEmpty) continue;
final last = history.last.endedAt;
final stamp = state.lastDeloadedAt;
if (stamp != null && stamp.isAfter(last)) continue;
final steps = gapDeloadSteps(gapCalendarDays(last, at));
if (steps == 0) continue;
var t = gapDeloadTarget(state, steps);
var total = steps;
if (includeOwed) {
final owed = missedGapSteps(history);
final replay = gapDeloadTarget(state, steps + owed);
if (_lower(replay, t)) {
t = replay;
total = steps + owed;
}
}
if (t.weight == state.weight && t.reps == state.reps) {
log(
'StorageService: ${state.name} is due $steps gap step(s) but '
'already sits where the 40% cap stops them; left as is.',
);
continue;
}
if (await _writeGapDeload(state, t, at, kind)) {
done.add(
GapDeload(
name: state.name,
from: ProgressionTarget(state.weight, state.reps),
to: t,
steps: total,
),
);
log(
'StorageService: $kind ${state.name} after '
'${gapCalendarDays(last, at)} days: '
'${_deloadKg(state.weight)} kg × ${state.reps} → '
'${_deloadKg(t.weight)} kg × ${t.reps}',
);
}
}
if (done.isNotEmpty) unawaited(_backupNow());
return done;
}
/// The newest gap or backfill deload per exercise that no session has
/// followed yet: what the tile shows struck through.
Future<Map<String, ProgressionEvent>> activeGapDeloads() async {
final events = [
for (final e in await getProgressionEvents())
if (e.kind == kGapDeloadKind || e.kind == kBackfillDeloadKind) e,
];
// The usual case: no gap deload ever, so no history scan.
if (events.isEmpty) return const {};
final marks = await sessionMarks();
final shown = <String, ProgressionEvent>{};
for (final e in events) {
if (shown.containsKey(e.exercise)) continue; // newest first
final history = marks[e.exercise];
if (history != null &&
history.isNotEmpty &&
!history.last.endedAt.isBefore(e.at)) {
continue;
}
shown[e.exercise] = e;
}
return shown;
}
Future<bool> _writeGapDeload(
ExerciseState state,
ProgressionTarget t,
DateTime at,
String kind,
) => _db.transaction((txn) async {
final rows = await txn.update(
'exercise_state',
{
'weight': t.weight,
'reps': t.reps,
'success_streak': 0,
'fail_streak': 0,
'last_deloaded_at': at.toIso8601String(),
'updated_at': _nowMs(),
},
where: 'name = ?',
whereArgs: [state.name],
);
// Only a concurrent delete between the read and this write lands here;
// no test can interleave one inside the transaction.
// coverage:ignore-start
if (rows != 1) {
log(
'StorageService: ${state.name} vanished from exercise_state during '
'its gap deload; nothing was cut or logged.',
level: 900,
);
return false;
}
// coverage:ignore-end
await txn.insert('progression_events', {
'at': at.toIso8601String(),
'exercise': state.name,
'kind': kind,
'source': kAutoDeloadSource,
'from_weight': state.weight,
'from_reps': state.reps,
'to_weight': t.weight,
'to_reps': t.reps,
});
return true;
});
}
/// Whether [a] is a lighter target than [b]: weight first, then reps.
bool _lower(ProgressionTarget a, ProgressionTarget b) =>
a.weight < b.weight || (a.weight == b.weight && a.reps < b.reps);
/// When a session payload ended: `end_time`, else `start_time`, else the
/// row's `date`.
DateTime? _sessionEnd(Map<String, dynamic> payload, Object? rowDate) {
for (final raw in [payload['end_time'], payload['start_time'], rowDate]) {
if (raw is String) {
final parsed = DateTime.tryParse(raw);
if (parsed != null) return parsed;
}
}
return null;
}
/// Reads a stored `last_deloaded_at`; anything unreadable is reported and
/// treated as "never", which lets the gap rule decide.
DateTime? _parseDeloadStamp(Object? raw) {
if (raw == null) return null;
final parsed = raw is String ? DateTime.tryParse(raw) : null;
if (parsed == null) {
log(
'StorageService: unreadable last_deloaded_at "$raw" — treating the '
'exercise as never deloaded.',
level: 900,
);
}
return parsed;
}

View File

@ -67,4 +67,71 @@ extension StorageServiceSandbox on StorageService {
/// Persists the speed-up the sandbox replays its GPS run at.
Future<void> setSandboxReplayFactor(int factor) =>
_setSetting(kSandboxReplayFactorKey, '$factor');
/// Wipes, then backdates finished sessions so the next workout load runs
/// every gap-deload case at once (sandbox only, never the real app):
/// Lunge 8 days (one step), Bench 15 days (two), Row 5 days (none), Curl
/// 40 days (stops at the 40% cap); in workout B, Romanian Deadlift in reps
/// mode and Overhead Press in double progression, both 14 days.
Future<void> seedGapScenarios([DateTime? now]) async {
final at = now ?? DateTime.now();
await wipeAll();
Future<void> seed(
String name,
int daysAgo, {
required double weight,
required int reps,
ProgressionMode mode = ProgressionMode.weight,
}) async {
await _db.update(
'exercise_state',
{'weight': weight, 'reps': reps, 'progression_mode': mode.storageKey},
where: 'name = ?',
whereArgs: [name],
);
final end = at.subtract(Duration(days: daysAgo));
final start = end.subtract(const Duration(hours: 1));
final day = start.toIso8601String().substring(0, 10);
await _db.insert('workout_history', {
'date': day,
'workout_type': 'A',
'duration_seconds': 3600,
'succeeded': 1,
'json': jsonEncode({
'date': day,
'start_time': start.toIso8601String(),
'end_time': end.toIso8601String(),
'exercises': [
{
'name': name,
'targetWeight': weight,
'targetReps': reps,
'succeeded': true,
},
],
}),
});
}
await seed('Dumbbell Lunge', 8, weight: 20, reps: 12);
await seed('Dumbbell Bench Press', 15, weight: 22.5, reps: 12);
await seed('Dumbbell Row', 5, weight: 22.5, reps: 6);
await seed('Dumbbell Curl', 40, weight: 12.5, reps: 12);
await seed(
'Dumbbell Romanian Deadlift',
14,
weight: 27.5,
reps: 10,
mode: ProgressionMode.reps,
);
await seed(
'Dumbbell Overhead Press',
14,
weight: 7.5,
reps: 8,
mode: ProgressionMode.doubleProgression,
);
// Last was B, so the home screen offers A with the four A cases.
await _setSetting('last_workout_type', 'B');
}
}

View File

@ -34,6 +34,9 @@ const _progressionEventsTable = '''
/// stamped import row beats it.
const _updatedAtColumn = 'updated_at INTEGER NOT NULL DEFAULT 0';
/// The v10 shared deload stamp (local ISO-8601), NULL = never deloaded.
const _lastDeloadedColumn = 'last_deloaded_at TEXT';
/// Milliseconds since the epoch, UTC: the value every user write stamps.
int _nowMs() => DateTime.now().toUtc().millisecondsSinceEpoch;
@ -56,7 +59,8 @@ extension StorageServiceSchema on StorageService {
has_warmup INTEGER,
paused_until TEXT,
$_restColumns,
$_updatedAtColumn
$_updatedAtColumn,
$_lastDeloadedColumn
)
''');
await db.execute('''
@ -155,6 +159,18 @@ extension StorageServiceSchema on StorageService {
await db.execute(ddl);
}
}
if (oldVersion < 10) {
// NULL for every existing row: no deload before v10 stamped anything,
// and the gap deload reads NULL as "due if the gap says so".
// Checked first: a DB rewound to an older user_version (a test, a
// hand repair) can already carry the column, and ADD would fail.
final cols = await db.rawQuery('PRAGMA table_info(exercise_state)');
if (!cols.any((c) => c['name'] == 'last_deloaded_at')) {
await db.execute(
'ALTER TABLE exercise_state ADD COLUMN $_lastDeloadedColumn',
);
}
}
}
Future<void> _seedDefaultsIfNeeded() async {

View File

@ -12,29 +12,20 @@ extension StorageServiceSessions on StorageService {
///
/// The step itself comes from [targetAfterSuccess] / [targetAfterFailure],
/// the same functions the workout screen previews with, so what the tile
/// promises is what finishing does.
/// promises is what finishing does. A training break is NOT handled here:
/// the gap deload already cut the target when the workout loaded
/// (`applyGapDeloads`), so finishing never cuts a second time. The old
/// break branch here could not fire anyway: the session is saved before
/// this runs, so "days since the last workout" was always 0.
Future<void> applyProgression({
required Map<String, bool> succeededExercises,
required DateTime lastWorkoutDate,
}) async {
final daysSince = DateTime.now().difference(lastWorkoutDate).inDays;
final hadBreak = daysSince > 7;
for (final entry in succeededExercises.entries) {
final state = await getExerciseState(entry.key);
if (state == null) continue;
final Map<String, Object> update;
if (hadBreak) {
// A week off is one regression step, in whatever mode is active.
final t = targetAfterFailure(state);
update = {
'weight': t.weight,
'reps': t.reps,
'success_streak': 0,
'fail_streak': 0,
};
} else if (entry.value) {
if (entry.value) {
final newStreak = state.successStreak + 1;
final step = newStreak >= state.successThreshold;
final t = step

View File

@ -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.
@ -31,8 +32,13 @@ class ExerciseTile extends StatelessWidget {
required this.onSettingsChanged,
required this.onDeload,
super.key,
this.deloadedFrom,
});
/// The target a gap deload cut this exercise from, until the next
/// session: shown struck through beside the new one, with a down arrow.
final ProgressionTarget? deloadedFrom;
/// The exercise definition to display (this session's targets).
final Exercise exercise;
@ -126,6 +132,14 @@ class ExerciseTile extends StatelessWidget {
onTap: () => showExerciseSettings(context),
),
const SizedBox(width: 8),
if (deloadedFrom case final from?
when from.weight != exercise.weight ||
from.reps != exercise.reps)
_DeloadedFrom(
from: from,
exercise: exercise,
color: onHeaderMuted,
),
Text(
'${exercise.sets}×${exercise.reps}×${exercise.weight}kg',
style: TextStyle(

View File

@ -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),
],
);
}
}

View File

@ -0,0 +1,99 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/gap_deload.dart';
import 'package:workout_app/models/progression.dart';
import '../services/_deload_test_fixtures.dart';
DateTime _d(int day) => DateTime(2026, 11, day, 18);
void main() {
group('gapCalendarDays', () {
test('counts calendar days, not 24 h blocks', () {
expect(gapCalendarDays(DateTime(2026, 11, 1, 23), DateTime(2026, 11, 8, 1)), 7);
expect(gapCalendarDays(_d(8), _d(8)), 0);
});
});
group('gapDeloadSteps', () {
test('tiers: <7 none, 7-13 one, 14-20 two, +1 per week', () {
expect(gapDeloadSteps(0), 0);
expect(gapDeloadSteps(6), 0);
expect(gapDeloadSteps(7), 1);
expect(gapDeloadSteps(13), 1);
expect(gapDeloadSteps(14), 2);
expect(gapDeloadSteps(20), 2);
expect(gapDeloadSteps(21), 3);
expect(gapDeloadSteps(60), 8);
});
});
group('gapDeloadTarget', () {
test('weight mode: one step per tier', () {
final t = gapDeloadTarget(deloadState(weight: 100), 2);
expect(t.weight, 95);
expect(t.reps, 5);
});
test('weight mode: stops at a hard 40% loss', () {
// 10 kg: 7.5 is 25% off, 5 would be 50% -> stop at 7.5.
expect(gapDeloadTarget(deloadState(weight: 10), 8).weight, 7.5);
// 100 kg with 20 steps would be 50 kg; the floor is 60.
expect(gapDeloadTarget(deloadState(weight: 100), 20).weight, 60);
});
test('one step that alone exceeds the cap means no cut', () {
final t = gapDeloadTarget(deloadState(weight: 5), 1);
expect(t.weight, 5);
});
test('reps mode: same steps, same 40% cap on reps', () {
final s = deloadState(weight: 0, reps: 10, mode: ProgressionMode.reps);
expect(gapDeloadTarget(s, 2).reps, 8);
expect(gapDeloadTarget(s, 10).reps, 6);
});
test('double progression: reps first, weight capped at 40%', () {
final s = deloadState(
weight: 20,
reps: 8,
mode: ProgressionMode.doubleProgression,
);
final two = gapDeloadTarget(s, 2);
expect((two.weight, two.reps), (20.0, 6));
final three = gapDeloadTarget(s, 3);
expect((three.weight, three.reps), (17.5, 12));
expect(gapDeloadTarget(s, 99).weight, greaterThanOrEqualTo(12));
});
test('zero steps is the saved target', () {
final t = gapDeloadTarget(deloadState(weight: 50), 0);
expect((t.weight, t.reps), (50.0, 5));
});
});
group('missedGapSteps', () {
SessionMark m(int day, double w, {int reps = 5}) =>
SessionMark(endedAt: _d(day), weight: w, reps: reps);
test('a gap followed by an unchanged target is owed', () {
// 7-day gap (1 step), trained again at the same weight.
expect(missedGapSteps([m(1, 50), m(8, 50)]), 1);
});
test('debts add up while the target never moved', () {
expect(missedGapSteps([m(1, 50), m(8, 50), m(10, 50)]), 1);
expect(missedGapSteps([m(1, 50), m(8, 50), m(22, 50)]), 3);
});
test('any target change after the gap clears the debt', () {
expect(missedGapSteps([m(1, 50), m(8, 50), m(10, 52.5)]), 0);
expect(missedGapSteps([m(1, 50), m(8, 47.5)]), 0);
});
test('no history, one session or short gaps owe nothing', () {
expect(missedGapSteps([]), 0);
expect(missedGapSteps([m(1, 50)]), 0);
expect(missedGapSteps([m(1, 50), m(4, 50)]), 0);
});
});
}

View File

@ -0,0 +1,78 @@
// The gap deload end to end on launch: home cuts the lift before it reads
// the targets, and the auto-opened workout shows the old weight struck
// through next to the new one.
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/screens/home_screen.dart';
import 'package:workout_app/screens/workout_screen.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
import '../fake_audio_platform.dart';
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
installFakeAudioPlatform();
});
testWidgets('an 8-day gap opens the workout one step lighter', (
tester,
) async {
final lift = workoutA.first.name;
final end = DateTime.now().subtract(const Duration(days: 8));
await tester.runAsync(() async {
final svc = StorageService.instance;
await svc.setExerciseWeight(lift, 25);
await svc.saveSession(
date: end.toIso8601String().substring(0, 10),
// B last, so the next workout is A and holds the lift.
workoutType: 'B',
durationSeconds: 3600,
succeeded: true,
json: jsonEncode({
'end_time': end.toIso8601String(),
'exercises': [
{'name': lift, 'targetWeight': 25, 'targetReps': 5},
],
}),
);
});
await tester.runAsync(() async {
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: HomeScreen(configuredProbe: () async => false),
),
);
await Future<void>.delayed(const Duration(milliseconds: 300));
await tester.pump(); // fire the post-frame auto-open
await Future<void>.delayed(const Duration(milliseconds: 500));
});
await tester.pump();
// The workout's own load (targets, then the deload marks) on the real
// loop too.
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 500)),
);
await tester.pump();
expect(find.byType(WorkoutScreen), findsOneWidget);
final s = await tester.runAsync(
() => StorageService.instance.getExerciseState(lift),
);
expect(s!.weight, 22.5);
expect(find.byIcon(Icons.arrow_downward), findsOneWidget);
});
}

View File

@ -167,4 +167,14 @@ void main() {
await tapReal(tester, iconLabeled('Wipe sandbox data'));
expect(Sandbox.runReplayFactor, Sandbox.defaultReplayFactor);
});
testWidgets('seed gap cases backdates sessions and says so', (tester) async {
await pump(tester);
await tapReal(tester, iconLabeled('Seed gap deload cases'));
expect(iconLabelContaining('Seeded backdated'), findsOneWidget);
final next = await tester.runAsync(
StorageService.instance.getNextWorkoutType,
);
expect(next, 'A');
});
}

View File

@ -0,0 +1,104 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/exercise_state_files.dart';
import 'package:workout_app/services/storage_service.dart';
void main() {
late Directory tmp;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
tmp = Directory.systemTemp.createTempSync('esf_');
});
tearDown(() => tmp.deleteSync(recursive: true));
group('writeDeloadExport', () {
test('writes every dir it can', () async {
final a = Directory(p.join(tmp.path, 'a'));
final b = Directory(p.join(tmp.path, 'b'));
await ExerciseStateFiles(
exportDirs: () async => [a, b],
).writeDeloadExport('{"x":1}');
for (final d in [a, b]) {
expect(
File(p.join(d.path, kDeloadExportFileName)).readAsStringSync(),
'{"x":1}',
);
}
});
test('one unwritable dir is tolerated, none is fatal', () async {
final blocker = File(p.join(tmp.path, 'file'))..writeAsStringSync('');
final bad = Directory(p.join(blocker.path, 'sub'));
final good = Directory(p.join(tmp.path, 'good'));
await ExerciseStateFiles(
exportDirs: () async => [bad, good],
).writeDeloadExport('{}');
await expectLater(
ExerciseStateFiles(
exportDirs: () async => [bad],
).writeDeloadExport('{}'),
throwsA(isA<FileSystemException>()),
);
await expectLater(
ExerciseStateFiles(exportDirs: () async => []).writeDeloadExport('{}'),
throwsA(isA<FileSystemException>()),
);
});
});
group('importRestoreFile', () {
final lift = workoutA.first.name;
test('imports a pushed file once and keeps it renamed', () async {
final row = Map<String, Object?>.of(
(await StorageService.instance.exportData())['exercise_state']
.cast<Map<String, Object?>>()
.firstWhere((Map<String, Object?> r) => r['name'] == lift),
);
row['weight'] = 12.5;
row['updated_at'] = DateTime.now().millisecondsSinceEpoch + 1000;
File(p.join(tmp.path, kRestoreFileName)).writeAsStringSync(
jsonEncode({
'version': 3,
'exercise_state': [row],
}),
);
final files = ExerciseStateFiles(restoreDir: () async => tmp);
final r = await files.importRestoreFile();
expect(r.rows, 1);
expect((await StorageService.instance.getExerciseState(lift))!.weight, 12.5);
expect(File(p.join(tmp.path, kRestoreFileName)).existsSync(), isFalse);
expect((await files.importRestoreFile()).rows, 0);
});
test('a broken file is left in place', () async {
final f = File(p.join(tmp.path, kRestoreFileName))
..writeAsStringSync('not json');
final r = await ExerciseStateFiles(
restoreDir: () async => tmp,
).importRestoreFile();
expect(r.rows, 0);
expect(f.existsSync(), isTrue);
});
test('no dir on this platform', () async {
final r = await ExerciseStateFiles(
restoreDir: () async => null,
).importRestoreFile();
expect(r.rows, 0);
});
});
}

View File

@ -6,6 +6,7 @@ import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/manual_deload.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
@ -110,4 +111,26 @@ void main() {
);
},
);
test('the shared deload stamp syncs and pulls back (C8)', () async {
final storage = StorageService.instance;
await storage.manualDeload('Situp', source: DeloadSource.settings);
final stamp = (await storage.getExerciseState('Situp'))!.lastDeloadedAt!;
await markSynced();
await sync.pushProgression();
expect(_payload(store, 'Situp')['last_deloaded_at'], stamp.toIso8601String());
StorageService.resetForTesting();
await StorageService.init();
await sync.pullProgression();
final pulled = (await storage.getExerciseState('Situp'))!;
expect(pulled.lastDeloadedAt, stamp);
});
test('a record without the stamp pulls as never deloaded', () async {
seedRemote(store, 'Situp', weight: 5, reps: 31, maxWeight: 10);
await sync.pullProgression();
final s = (await StorageService.instance.getExerciseState('Situp'))!;
expect(s.lastDeloadedAt, isNull);
});
}

View File

@ -32,11 +32,9 @@ void main() {
// Default success threshold is 3 — three straight successes trigger a
// progression, which at the cap increments reps instead of weight.
final today = DateTime.now();
for (var i = 0; i < 3; i++) {
await _svc.applyProgression(
succeededExercises: {name: true},
lastWorkoutDate: today,
);
}

View File

@ -0,0 +1,67 @@
// Gap deload inputs the happy-path tests never produce: a history row with
// no readable time, and a stored stamp that is not a date.
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/storage_service.dart';
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
final lift = workoutA.first.name;
test('a row with no readable time counts toward no gap', () async {
StorageService.resetForTesting();
await StorageService.init();
final svc = StorageService.instance;
await svc.saveSession(
date: 'not a date',
workoutType: 'A',
durationSeconds: 1,
succeeded: true,
json: jsonEncode({
'exercises': [
{'name': lift},
],
}),
);
expect((await svc.sessionMarks())[lift], isNull);
expect(await svc.applyGapDeloads(now: DateTime(2026, 11, 20)), isEmpty);
});
test('an unreadable stamp reads as never deloaded', () async {
final dir = await Directory.systemTemp.createTemp('gap_stamp');
addTearDown(() => dir.delete(recursive: true));
final path = p.join(dir.path, 'w.db');
StorageService.resetForTesting(dbPath: path);
await StorageService.init();
final svc = StorageService.instance;
await svc.setExerciseWeight(lift, 25);
// A second connection to the same file: the service exposes no raw
// write, and a sync pull always parses the stamp first.
final raw = await databaseFactoryFfi.openDatabase(path);
await raw.update(
'exercise_state',
{'last_deloaded_at': 'garbage'},
where: 'name = ?',
whereArgs: [lift],
);
await raw.close();
expect((await svc.getExerciseState(lift))!.lastDeloadedAt, isNull);
});
test('the sandbox seed defaults to the real clock', () async {
StorageService.resetForTesting();
await StorageService.init();
final svc = StorageService.instance;
await svc.seedGapScenarios();
expect(await svc.applyGapDeloads(), isNotEmpty);
});
}

View File

@ -0,0 +1,244 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/gap_deload.dart';
import 'package:workout_app/models/manual_deload.dart';
import 'package:workout_app/models/progression.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/storage_service.dart';
StorageService get _svc => StorageService.instance;
final _now = DateTime(2026, 11, 20, 18);
/// Saves a finished session of [names] that ended [daysAgo] days before
/// [_now], at the given target.
Future<void> _session(
List<String> names, {
required int daysAgo,
double weight = 25,
int reps = 5,
bool succeeded = true,
}) async {
final end = _now.subtract(Duration(days: daysAgo));
final start = end.subtract(const Duration(hours: 1));
await _svc.saveSession(
date: start.toIso8601String().substring(0, 10),
workoutType: 'A',
durationSeconds: 3600,
succeeded: succeeded,
json: jsonEncode({
'date': start.toIso8601String().substring(0, 10),
'start_time': start.toIso8601String(),
'end_time': end.toIso8601String(),
'exercises': [
for (final n in names)
{
'name': n,
'targetWeight': weight,
'targetReps': reps,
'succeeded': succeeded,
},
],
}),
);
}
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
});
final lift = workoutA.first.name;
Future<void> at(double w) => _svc.setExerciseWeight(lift, w);
group('applyGapDeloads', () {
test('8-day gap: one step down, streaks zeroed, stamped, logged', () async {
await at(25);
await _session([lift], daysAgo: 8);
final done = await _svc.applyGapDeloads(now: _now);
expect(done.map((d) => d.name), [lift]);
final s = (await _svc.getExerciseState(lift))!;
expect(s.weight, 22.5);
expect((s.successStreak, s.failStreak), (0, 0));
expect(s.lastDeloadedAt, _now);
final events = await _svc.getProgressionEvents(exercise: lift);
expect(events.single.kind, kGapDeloadKind);
expect((events.single.fromWeight, events.single.toWeight), (25.0, 22.5));
});
test('15-day gap: two steps', () async {
await at(25);
await _session([lift], daysAgo: 15);
await _svc.applyGapDeloads(now: _now);
expect((await _svc.getExerciseState(lift))!.weight, 20);
});
test('5-day gap: untouched', () async {
await at(25);
await _session([lift], daysAgo: 5);
expect(await _svc.applyGapDeloads(now: _now), isEmpty);
expect((await _svc.getExerciseState(lift))!.weight, 25);
});
test('never trained: no gap, no cut', () async {
expect(await _svc.applyGapDeloads(now: _now), isEmpty);
});
test('reopening never cuts twice', () async {
await at(25);
await _session([lift], daysAgo: 8);
await _svc.applyGapDeloads(now: _now);
final later = _now.add(const Duration(minutes: 5));
expect(await _svc.applyGapDeloads(now: later), isEmpty);
// Not even a week later with no session in between.
expect(
await _svc.applyGapDeloads(now: _now.add(const Duration(days: 7))),
isEmpty,
);
expect((await _svc.getExerciseState(lift))!.weight, 22.5);
});
test('a manual deload since the last session skips the auto cut', () async {
await at(25);
await _session([lift], daysAgo: 8);
final m = await _svc.manualDeload(lift, source: DeloadSource.settings);
expect(m.state!.lastDeloadedAt, isNotNull);
expect(await _svc.applyGapDeloads(now: _now), isEmpty);
expect((await _svc.getExerciseState(lift))!.weight, 22.5);
});
test('a session after a deload makes the next gap due again', () async {
await at(25);
await _session([lift], daysAgo: 30);
await _svc.applyGapDeloads(now: _now.subtract(const Duration(days: 20)));
await _session([lift], daysAgo: 9, weight: 20);
final done = await _svc.applyGapDeloads(now: _now);
expect(done, hasLength(1));
});
test('reps mode: two steps on reps', () async {
final s = (await _svc.getExerciseState(lift))!;
await _svc.setExerciseSettings(s.copyWith(mode: ProgressionMode.reps));
await _svc.setExerciseReps(lift, 10);
await _session([lift], daysAgo: 14);
await _svc.applyGapDeloads(now: _now);
expect((await _svc.getExerciseState(lift))!.reps, 8);
});
test('activeGapDeloads: shown until the next session', () async {
await at(25);
await _session([lift], daysAgo: 8);
await _svc.applyGapDeloads(now: _now);
final shown = await _svc.activeGapDeloads();
expect(shown[lift]!.fromWeight, 25);
await _session([lift], daysAgo: 0, weight: 22.5);
expect(await _svc.activeGapDeloads(), isEmpty);
});
});
group('runGapDeloadBackfill', () {
test('exports before cutting, cuts stale lifts, never twice', () async {
final fresh = workoutA[1].name;
await at(25);
await _svc.setExerciseWeight(fresh, 40);
// kuhy's case: 7-day break, failed at the same weight, then 15 days.
await _session([lift], daysAgo: 30);
await _session([lift], daysAgo: 22, succeeded: false);
await _session([lift], daysAgo: 16, succeeded: false);
await _session([fresh], daysAgo: 2, weight: 40);
final exports = <String>[];
final r = await _svc.runGapDeloadBackfill(
now: _now,
writeExport: (json) async {
// The export must hold the PRE-cut weights.
final rows = (jsonDecode(json) as Map)['exercise_state'] as List;
expect(
rows.firstWhere((r) => r['name'] == lift)['weight'],
25,
);
exports.add(json);
},
);
expect(r.ran, isTrue);
expect(exports, hasLength(1));
// Gap now: 16 days = 2 steps; owed from the 8-day gap = 1 step.
expect((await _svc.getExerciseState(lift))!.weight, 17.5);
expect((await _svc.getExerciseState(fresh))!.weight, 40);
final ev = await _svc.getProgressionEvents(exercise: lift);
expect(ev.single.kind, kBackfillDeloadKind);
final again = await _svc.runGapDeloadBackfill(
now: _now,
writeExport: (json) async => exports.add(json),
);
expect(again.ran, isFalse);
expect(exports, hasLength(1));
expect((await _svc.getExerciseState(lift))!.weight, 17.5);
});
test('a failed export cuts nothing and leaves the stamp unset', () async {
await at(25);
await _session([lift], daysAgo: 15);
final r = await _svc.runGapDeloadBackfill(
now: _now,
writeExport: (_) async => throw const FileSystemExceptionLike(),
);
expect(r.ran, isFalse);
expect((await _svc.getExerciseState(lift))!.weight, 25);
final retry = await _svc.runGapDeloadBackfill(
now: _now,
writeExport: (_) async {},
);
expect(retry.ran, isTrue);
});
test('never raises a weight', () async {
await at(5);
await _session([lift], daysAgo: 40, weight: 5);
await _svc.runGapDeloadBackfill(now: _now, writeExport: (_) async {});
expect((await _svc.getExerciseState(lift))!.weight, 5);
});
});
group('sandbox seed', () {
test('seeds every gap case for the next workout load', () async {
await _svc.seedGapScenarios(_now);
expect(await _svc.getNextWorkoutType(), 'A');
final done = {
for (final d in await _svc.applyGapDeloads(now: _now)) d.name: d.to,
};
expect(done['Dumbbell Lunge']!.weight, 17.5);
expect(done['Dumbbell Bench Press']!.weight, 17.5);
expect(done.containsKey('Dumbbell Row'), isFalse);
expect(done['Dumbbell Curl']!.weight, 7.5);
expect(done['Dumbbell Romanian Deadlift']!.reps, 8);
expect(done['Dumbbell Overhead Press']!.reps, 6);
});
});
group('finish no longer deloads', () {
test('a session after a long break progresses normally', () async {
await at(22.5);
await _session([lift], daysAgo: 0, weight: 22.5);
await _svc.applyProgression(succeededExercises: {lift: true});
expect((await _svc.getExerciseState(lift))!.weight, 22.5);
expect((await _svc.getExerciseState(lift))!.successStreak, 1);
});
});
}
/// A stand-in I/O failure for the export writer.
class FileSystemExceptionLike implements Exception {
/// Creates one.
const FileSystemExceptionLike();
}

View File

@ -34,7 +34,6 @@ void main() {
final before = await _svc.getExerciseState(name);
await _svc.applyProgression(
succeededExercises: {name: true},
lastWorkoutDate: DateTime.now().subtract(const Duration(days: 1)),
);
final after = await _svc.getExerciseState(name);
expect(after!.successStreak, (before!.successStreak + 1));
@ -50,7 +49,6 @@ void main() {
final before = await _svc.getExerciseState(name);
await _svc.applyProgression(
succeededExercises: {name: true},
lastWorkoutDate: DateTime.now().subtract(const Duration(days: 1)),
);
final after = await _svc.getExerciseState(name);
// Weight should increase (if below maxWeight) or reps increase
@ -71,7 +69,6 @@ void main() {
final before = await _svc.getExerciseState(name);
await _svc.applyProgression(
succeededExercises: {name: false},
lastWorkoutDate: DateTime.now().subtract(const Duration(days: 1)),
);
final after = await _svc.getExerciseState(name);
expect(after!.failStreak, (before!.failStreak + 1));
@ -87,28 +84,14 @@ void main() {
final before = await _svc.getExerciseState(name);
await _svc.applyProgression(
succeededExercises: {name: false},
lastWorkoutDate: DateTime.now().subtract(const Duration(days: 1)),
);
final after = await _svc.getExerciseState(name);
expect(after!.weight, lessThanOrEqualTo(before!.weight));
});
test('reduces weight after long break (> 7 days)', () async {
final name = workoutA.first.name;
await _svc.setExerciseWeight(name, 20.0);
final before = await _svc.getExerciseState(name);
await _svc.applyProgression(
succeededExercises: {name: true},
lastWorkoutDate: DateTime.now().subtract(const Duration(days: 10)),
);
final after = await _svc.getExerciseState(name);
expect(after!.weight, lessThan(before!.weight));
});
test('skips unknown exercise gracefully', () async {
await _svc.applyProgression(
succeededExercises: {'Ghost Exercise': true},
lastWorkoutDate: DateTime.now().subtract(const Duration(days: 1)),
);
// No exception thrown — that's the test.
});

View File

@ -7,7 +7,6 @@ import 'package:workout_app/services/storage_service.dart';
StorageService get _svc => StorageService.instance;
final _yesterday = DateTime.now().subtract(const Duration(days: 1));
void main() {
setUpAll(() {
@ -71,7 +70,6 @@ void main() {
ProgressionMode mode, {
required bool success,
required int reps,
DateTime? last,
}) async {
final name = workoutA.first.name;
final s = (await _svc.getExerciseState(name))!;
@ -82,7 +80,6 @@ void main() {
await _svc.setExerciseWeight(name, 10);
await _svc.applyProgression(
succeededExercises: {name: success},
lastWorkoutDate: last ?? _yesterday,
);
return (await _svc.getExerciseState(name))!;
}
@ -114,15 +111,5 @@ void main() {
);
expect((s.weight, s.reps), (7.5, 12));
});
test('a week off is one regression step in the active mode', () async {
final s = await run(
ProgressionMode.reps,
success: true,
reps: 10,
last: DateTime.now().subtract(const Duration(days: 9)),
);
expect((s.weight, s.reps, s.successStreak, s.failStreak), (10, 9, 0, 0));
});
});
}

View File

@ -162,7 +162,6 @@ void main() {
() => expectStamped(
() => _svc.applyProgression(
succeededExercises: {name: true},
lastWorkoutDate: DateTime.now(),
),
),
);

View File

@ -0,0 +1,56 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/exercise_state.dart';
import 'package:workout_app/models/progression.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/exercise_tile.dart';
const _exercise = Exercise(name: 'Squat', sets: 3, reps: 5, weight: 17.5);
Widget _tile(ProgressionTarget? from) => MaterialApp(
theme: buildAppTheme(),
home: Scaffold(
body: ExerciseTile(
exercise: _exercise,
state: ExerciseState.initial(_exercise),
tapped: const [false, false, false],
doneReps: const [5, 5, 5],
warmupTapped: false,
onTapCircle: (_) {},
onLongPressCircle: (_) {},
onTapWarmup: () {},
onSettingsChanged: (_) {},
onDeload: () async => null,
deloadedFrom: from,
),
),
);
TextDecoration? _decoration(WidgetTester tester, String text) =>
tester.widget<Text>(find.text(text)).style?.decoration;
void main() {
testWidgets('a gap deload shows the old weight struck through + arrow', (
tester,
) async {
await tester.pumpWidget(_tile(const ProgressionTarget(20, 5)));
expect(find.byIcon(Icons.arrow_downward), findsOneWidget);
expect(_decoration(tester, '20.0kg'), TextDecoration.lineThrough);
expect(find.textContaining('3×5×17.5kg'), findsOneWidget);
final arrow = tester.widget<Icon>(find.byIcon(Icons.arrow_downward));
expect(arrow.semanticLabel, 'Squat deloaded after a break');
});
testWidgets('a reps-only cut strikes the old reps', (tester) async {
await tester.pumpWidget(_tile(const ProgressionTarget(17.5, 7)));
expect(_decoration(tester, '×7'), TextDecoration.lineThrough);
});
testWidgets('no deload, or one already undone: no arrow', (tester) async {
await tester.pumpWidget(_tile(null));
expect(find.byIcon(Icons.arrow_downward), findsNothing);
await tester.pumpWidget(_tile(const ProgressionTarget(17.5, 5)));
expect(find.byIcon(Icons.arrow_downward), findsNothing);
});
}