diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index 1693c79..900a666 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -1,6 +1,7 @@ # Exercise Tracker current state - Last updated: 2026-11-11 +- TASK-019: Complete following Captain acceptance and explicit commit/local codex merge authorization on 2026-11-11. Persistent reconstruction is in `.task-worktrees/task-019`, branch `task/019-previous-availability-rebuild`, base `6ea3f7b`. - TASK-020: Complete following Captain acceptance and explicit commit/local codex merge authorization. Its tooling is already integrated in `0cf0515`; dedicated branch completion records are documentation only. - TASK-016: Complete following Captain acceptance and explicit commit/local codex merge authorization on 2026-11-11. Includes reconstructed compact-input styling and testtask tooling prerequisites. - Source worktree: `.task-worktrees/task-016`, branch `task/016-dark-theme-rebuild`; integration target `codex`, base `922d1f6`. Verify resulting refs with Git. @@ -8,6 +9,14 @@ Code/configuration take precedence over this summary. +## Accepted TASK-019 reconstruction — 2026-11-11 + +Captain requested finishing TASK-019. New implementation is in persistent `.task-worktrees/task-019`, branch `task/019-previous-availability-rebuild`, based on codex `6ea3f7b`. Status: Complete following Captain acceptance and explicit commit/local codex merge authorization. The original `/tmp` source remains missing; this is a rebuild, not recovery. Captain authorized integration of the candidate into local codex; verify resulting commit/refs with Git. + +The previous-session action appears only after the existing compatibility query finds applicable earlier completed data. Shared keyed/cancellable availability covers regular reps/holds/hang, aggregate EMOM and original minute editors, using saved definitions and format. Unknown/empty/failed lookups remain hidden; a lookup-only error/retry preserves current input. Late old-context results cannot enable the wrong button. No auto-application, writes, data migrations or changes to compatibility/Save/history semantics. + +Fresh checks: 180/180 tests across 15 files with one worker, lint/build, home source preflight 019, context validation (0 warnings), whitespace and base diff review pass. Captain explicitly accepted TASK-019 and authorized its commit/local codex merge. No agent runner/browser/server/snapshot launch; no push/deploy or cleanup authorized. Exact test handoff is in HANDOFF. Prior statements below that TASK-019 still requires rebuilding are historical and superseded by this available candidate. + ## TASK-016 rebuild — 2026-11-11 Captain reported that `scripts/testtask.sh 016` still failed after the tooling repair. Rebuilt TASK-016 in persistent `.task-worktrees/task-016`, branch `task/016-dark-theme-rebuild`, base `922d1f6`. It is new implementation from the accepted task, not a recovery of the lost candidate. Captain accepted this candidate and authorized its commit/local codex merge on 2026-11-11; the resulting integration includes these application changes at project home. @@ -38,7 +47,7 @@ TASK-017 replaces normal EMOM minute tables with exactly Weight (kg) and Total r Per-side exercises, including preacher curls and bird-dog holds, now use one Reps (each side) or Seconds (each side) input per set. Explicit edits write both stored side values together. Unequal/partial historical values remain intact on read and untouched Save, displayed as text until replaced. Equipment, prescribed side guidance and historical per-side calculation semantics remain compatible. Zero is explicit; blanks remain incomplete. No schema migration or programme change. -TASK-016 integration adds the accepted dark theme and compact numeric inputs. No timers/audio, dog walks, full history/progress, routine editor, backup UI or offline-release work is added. TASK-015 remains Complete. Conditional previous-session visibility (TASK-019) is not included; its original candidate is missing. TASK-005 and TASK-008 remain accepted future work; other task statuses are in TASKS. +TASK-016 integration adds the accepted dark theme and compact numeric inputs. No timers/audio, dog walks, full history/progress, routine editor, backup UI or offline-release work is added. TASK-015 remains Complete. TASK-019 reconstruction now supplies conditional previous-session visibility; its original `/tmp` candidate remains missing. TASK-005 and TASK-008 remain accepted future work; other task statuses are in TASKS. ## Storage @@ -64,3 +73,8 @@ Project-home `scripts/testtask.sh TASK_ID` now resolves the corresponding checke Captain accepted TASK-020 and authorized its commit/local codex merge. Duplicate tooling and older context from `.task-worktrees/task-020` were preserved in a named safety stash, then its branch was fast-forwarded to `0cf0515` before a context-only completion commit. No application/tooling implementation differs from accepted TASK-016 integration. All available completed application work is integrated in local codex. Every existing task branch commit was already a codex ancestor at audit time; TASK-020 completion is integrated from its dedicated branch. Original TASK-018 code was lost, but its accepted compact-input requirements were reconstructed and integrated in `0cf0515`. TASK-019 remains accepted/rebuild-required; its previous uncommitted source is absent and is not part of integrated code. Stashes preserve duplicate/older context, not a recovered TASK-019 implementation. No push/deploy, branch/worktree removal, registration pruning or test-session cleanup occurred. + + +## TASK-019 completion integration — 2026-11-11 + +Captain explicitly accepted TASK-019 and authorized its commit/local codex merge. The current persistent source contains the validated replacement for the lost implementation. All available completed task application/tooling work is integrated after this merge; no uncommitted candidate work remains. Three safety stashes preserve only duplicate/older tooling/context from earlier integrations, including home's pre-acceptance 019 context. Missing original `/tmp` registrations and all persistent implementation worktrees remain untouched. Earlier audit notes that TASK-019 was missing/rebuild-required are historical and superseded by this accepted reconstruction. Future implementation remains limited to explicitly accepted tasks. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 20c80bd..e1fbb17 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,26 +3,26 @@ > Replaceable snapshot; repository code and maintained context take precedence. - Updated: 2026-11-11. -- TASK-020: Complete. Captain explicitly stated “task 020 complete. commit and merge”. -- Source: `.task-worktrees/task-020`, branch `task/020-testtask-repair`, completion base `0cf0515`; target local `codex`. Verify final commit/refs with Git. -- TASK-016 remains Complete and integrated as `0cf0515`, including dark theme, reconstructed TASK-018 compact inputs and TASK-020 launcher tooling. TASK-020 completion adds context only; no runtime implementation changes. +- TASK-019: Complete. Captain explicitly stated “task-019 complete. commit and merge”, accepting the reconstruction and authorizing local integration. +- Source: `.task-worktrees/task-019`, branch `task/019-previous-availability-rebuild`, base codex `6ea3f7b`; target local `codex`. Verify final commit/refs with Git. +- All available completed task implementation is integrated after this merge. No push/deployment or worktree/session cleanup authorized. -## Integration and remaining work +## Delivered and validated -All available completed application/tooling work is integrated in local codex. All task branch commits are codex ancestors after this completion integration. Project home and both persistent implementation worktrees should be clean; verify with Git before continuing. +Previous-session action is offered only for compatible earlier completed data, across regular reps/holds/hang, aggregate EMOM and original minute-history editors. Unknown, empty or failed lookups stay hidden. Shared keyed/cancellable results use the loaded saved definition/format and owning parent context; separate failure/retry preserves typed values. Existing compatibility, explicit click, Save/completion, zero/blank/draft handling, populated-entry protection and historical isolation remain unchanged. -TASK-019 is not Complete: its previous-session availability implementation was uncommitted in a missing `/tmp` worktree. It remains accepted but requires rebuilding. It is not included in TASK-016/020. TASK-018's original uncommitted source was also lost, but its accepted requirements were reconstructed and merged with TASK-016. Do not claim byte-identical recovery. +180/180 tests across 15 files pass with `npm test -- --maxWorkers=1`; lint/build, no-launch source preflight, context validation (0 warnings), whitespace and diff review against `6ea3f7b` pass. Includes real IndexedDB read-only/eligibility/data-preservation cases and controlled asynchronous race/retry/parent-context checks. Captain acceptance is recorded without claiming an independent agent browser/console/network review. Application implementation is unchanged during acceptance/commit preparation, so tests are not rerun solely for completion text. -Two named safety stashes preserve pre-integration duplicate tooling/older context: the home copy saved before TASK-016 integration and TASK-020's old worktree copy saved before reconciliation. They contain superseded/duplicate files, not unique pending application work. Retain them unless Captain authorizes cleanup; applying them wholesale would reintroduce stale documentation. +No storage/schema, compatibility-policy, seed/programme, layout/theme or dependency changes. This is a reconstruction, not byte-identical recovery of the missing original source. -Original `/tmp` worktree registrations remain prunable evidence; no branches/worktrees/stashes/snapshots are deleted. No push or deployment authorized. No testing session is stopped. +## Git state and retained evidence -## Validation +TASK-016 dark theme and reconstructed TASK-018 compact inputs were integrated in `0cf0515`; TASK-020 completion in `6ea3f7b`. TASK-019 completion is integrated from its persistent dedicated branch. Home and all persistent task worktrees should be clean; verify Git before new work. -TASK-020: 10 stub-runner routing/runtime tests, shell syntax, no-launch `--check 016`/`--check 020`, context validation (0 warnings), whitespace/diff review. No real runner/browser/server is launched for this integration. Existing implementation is identical to `0cf0515`, so application checks are not rerun for documentation-only completion. +Three named safety stashes retain duplicate/older context/tooling: home before TASK-016 integration, old TASK-020 worktree copies before reconciliation, and home's pre-acceptance TASK-019 context. They contain no unique pending application changes. Applying them wholesale would reintroduce stale documentation; retain pending Captain cleanup authority. -Retained TASK-016 evidence: 143/143 tests across 13 files pass with `npm test -- --maxWorkers=1`; default-parallel run had two timing failures. Final lint/build, contrast measurements and Captain acceptance are recorded without claiming an independent agent browser pass. No application JS, storage/schema, programme or dependency changes occurred. +Original missing `/tmp` registrations remain prunable evidence. No branches, worktrees, stashes or snapshots are removed, and no Captain testing sessions are stopped. No remote push or deployment. ## Testtask -From project home, `./scripts/testtask.sh TASK_ID` selects the corresponding persistent task source and Node automatically. `--check TASK_ID` validates source/runtime/dependencies without launching. Captain alone runs/stops real sessions; snapshots stay separate under the selected source's `.test-worktrees` and must not be edited. Persistent implementation worktrees remain under `.task-worktrees`. +Captain alone runs/stops real sessions. From project home, `./scripts/testtask.sh 019` selects the persistent 019 source and Node automatically. `--check 019` validates without launch. Snapshots are exact-state test evidence under the source's `.test-worktrees`, never editing sources; completion documentation may require the supported runner to refresh on Captain's next launch. diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md index ce8fc62..5c5bd12 100644 --- a/docs/PROJECT_OVERVIEW.md +++ b/docs/PROJECT_OVERVIEW.md @@ -6,7 +6,7 @@ This is a newly initialized repository. The user calls the planned product "Work ## Product -Workout Tracker is a personal local workout app with actual-date navigation, exclusive Morning/Afternoon views, a persistent local-time clock and no workout timers. Seed v8 contains 30 versioned exercise definitions with equipment/measurement metadata. Reusable logging shows only relevant reps, durations and equipment-specific loads, with one shared measurement input for per-side work, supports completed rows, partial drafts and explicit previous-session suggestions, and records EMOM with one weight and one total-reps input. Earlier minute records remain separately accessible. Daily hangs have an editable continuous target, independent attempts, longest continuous and cumulative totals. Monday/Friday stretch routines have headings but no invented exercises. Dog walks remain excluded; their latest classification is bodyweight-only reference context. +Workout Tracker is a personal local workout app with actual-date navigation, exclusive Morning/Afternoon views, a persistent local-time clock and no workout timers. Seed v8 contains 30 versioned exercise definitions with equipment/measurement metadata. Reusable logging shows only relevant reps, durations and equipment-specific loads, with one shared measurement input for per-side work, supports completed rows, partial drafts and explicit previous-session suggestions offered only when compatible earlier completed data exists, and records EMOM with one weight and one total-reps input. Earlier minute records remain separately accessible. Daily hangs have an editable continuous target, independent attempts, longest continuous and cumulative totals. Monday/Friday stretch routines have headings but no invented exercises. Dog walks remain excluded; their latest classification is bodyweight-only reference context. Exercise definition, workout prescription and dated performance are independent. New performance retains definition/prescription snapshots, while original aggregate, rep-set and weight-only history stays readable separately. Exercise details expose available notes and placeholders; reviewed technique/muscle content and local illustrations remain future work. The application uses a single dark green theme with coordinated Bootstrap/native controls and compact numeric inputs. History/progress screens, routine editing, backup interface and offline reload remain separate tasks. SPEC defines behavior and WORKOUT_ROUTINE the authoritative initial programme. diff --git a/docs/TASKS.md b/docs/TASKS.md index d87f34a..313fe52 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -4,7 +4,7 @@ This file holds accepted, scoped implementation work. It is not a speculative ba ## Proposed implementation sequence -Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TASK-012–018 and TASK-020 are Complete. TASK-006 is Superseded; TASK-005 and TASK-008 are Accepted. TASK-019 requires rebuilding because its original uncommitted source is missing; it is not implementation-ready. Remaining tasks are Proposed. Completed application work is integrated in local codex, including reconstructed TASK-018 compact inputs within TASK-016. Implement one task per isolated branch/worktree under `docs/WORKFLOW.md`. Preserve the authoritative programme and historical storage semantics. +Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TASK-012–018 and TASK-020 are Complete. TASK-006 is Superseded; TASK-005 and TASK-008 are Accepted. TASK-019 is Complete following Captain acceptance on 2026-11-11; its persistent reconstruction is integrated, while the original `/tmp` source remains missing. Remaining tasks are Proposed. Completed application work is integrated in local codex, including reconstructed TASK-018 compact inputs within TASK-016. Implement one task per isolated branch/worktree under `docs/WORKFLOW.md`. Preserve the authoritative programme and historical storage semantics. ### TASK-001: Application foundation and responsive shell @@ -297,14 +297,14 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TA ### TASK-019: Hide previous-session action when no applicable data exists -- Status: Accepted / requires rebuild — prior implementation-ready candidate in `/tmp/exercise-tracker-task-019` is missing. Its branch contains no candidate commit. TASK-019 is not included in `0cf0515` or the TASK-020 completion; prior validation records below are historical evidence only. +- Status: Complete — Captain explicitly accepted TASK-019 and authorized commit/local codex merge on 2026-11-11. Source: persistent `.task-worktrees/task-019`, branch `task/019-previous-availability-rebuild`, base `6ea3f7b`. New reconstruction, not recovery of the missing `/tmp` source. - Requested: 2026-11-08. - Objective: Show “Use previous session” only when there is compatible previous-session data that can be applied. - Scope: Conditional visibility in regular set/hold/hang and EMOM performance editors, including preserved detailed historical editors where the action exists. Resolve availability using the existing previous-performance compatibility rules: same exercise, period and format, compatible saved definition, earlier actual date and completed source rows. Empty, draft-only, incompatible, current-date or future records do not qualify. Preserve aggregate/minute separation and explicit user-triggered application. - Acceptance criteria: The action is absent when no qualifying source exists, including a fresh database; visible when qualifying data exists. Keep it absent while availability is unknown or lookup fails; surface lookup failure with a retry path. Re-evaluate on date, period, exercise or saved-definition/format changes without stale results or button flashes. Checking availability writes nothing and never applies data automatically. Preserve current-entry protection, zero values, partial drafts, suggestions requiring review/Save, saved data and historical isolation. Existing populated-entry behavior is otherwise unchanged; this task does not broaden when suggestions may overwrite current work. - Relevant areas: `src/DetailedPerformanceEditor.jsx`, `src/EmomTotalEditor.jsx`, `src/performanceStorage.js` and corresponding UI/storage tests. - Required validation: Fresh/empty store, compatible completed source, zero-valued source, draft-only and incompatible sources, current/future exclusion, date/period/exercise changes, stale async responses, storage failure/retry, and existing-entry preservation. Run full tests, lint, build, context validation and `git diff --check`; review against confirmed integration base. Captain manual verification of hidden/visible states and keyboard access through testtask 019 is required before Complete. Captain alone runs testtask. -- Dependencies: Existing `previousPerformance` rules and ADR-019/020/021 govern compatibility and history. TASK-018 is Complete but uncommitted in its own worktree. TASK-019 starts from confirmed codex `922d1f6` with accepted TASK-018 CSS copied as a prerequisite. TASK-016 contains a copy of the TASK-019 candidate for the shared Captain test pass. +- Dependencies: Existing `previousPerformance` rules and ADR-019/020/021 govern compatibility and history. Rebuild starts from codex `6ea3f7b`, which already includes accepted TASK-016 dark theme, reconstructed TASK-018 compact inputs and TASK-020 launcher. This is an independent TASK-019 candidate, not the former combined UI snapshot. - Non-goals: Automatically applying suggestions, changing compatibility or history semantics, overwriting current entries, new history screens, layout redesign, storage migrations or unrelated refactoring. - TASK-018 completion evidence (2026-11-08): Captain explicitly stated “task-018 complete”, satisfying the Captain acceptance gate. Agent checks passed 143 tests, lint, build, context validation and whitespace review. No independent agent browser pass is claimed. Implementation remains uncommitted on `task/018-compact-inputs` in `/tmp/exercise-tracker-task-018`; commit and integration require separate Captain instruction. @@ -358,3 +358,15 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TA - Preserved the dedicated worktree's duplicate tooling and older context in a named safety stash, then fast-forwarded `task/020-testtask-repair` to codex before recording completion. This avoids reintroducing stale task state. The completion commit contains context changes only. - Revalidated 10 stub-runner routing/runtime tests, no-launch preflight for 016/020, shell syntax, context validation and whitespace review. No runner/browser/session launched or stopped. Previous TASK-016 interaction/lint/build evidence remains unchanged. - Audit: all task branch commits are ancestors of local codex. All completed available application/tooling work is integrated, including reconstructed TASK-018 compact-input requirements. TASK-019 is not Complete and its missing source is not merged/recovered. Prior `/tmp` registrations and safety stashes remain preserved; no push/deploy or destructive cleanup authorized. + + +#### TASK-019 reconstruction — 2026-11-11 + +- Captain requested finishing TASK-019. Rebuilt from clean codex `6ea3f7b` in `.task-worktrees/task-019` on `task/019-previous-availability-rebuild`; prior missing implementation is not recovered or reused. +- A shared cancellable/keyed read uses existing `previousPerformance` compatibility rules to show the action only when compatible earlier completed history exists. Regular reps/holds/hangs, EMOM totals and original historical-minute editors are covered. Unknown/empty/failed availability stays hidden. Saved definition and format drive compatibility; parent context must finish loading before lookup. Context keys prevent old-context button flashes and stale async responses. +- Separate failure message and lookup-only retry preserve current inputs and do not reload or write the entry. Applying suggestions remains explicit and retains the existing current-entry protection and Save/completion semantics. No storage/schema, compatibility-policy, programme, theme/layout or dependency changes. +- Fresh validation: 180/180 tests across 15 files with `npm test -- --maxWorkers=1`, lint/build, no-launch home `--check 019`, context validation (0 warnings), whitespace and diff review against `6ea3f7b` pass. Added real IndexedDB eligibility/read-only/preservation cases plus delayed-response/race/retry tests; existing suggestion tests wait for asynchronous availability. New test count supersedes historical missing-candidate evidence. +- Captain runs `./scripts/testtask.sh 019` from project home. Verify a fresh database hides the action, compatible regular/EMOM history shows it on a later date in the same period, click-only unsaved suggestions, current-entry protection, draft-only exclusion, date/period changes and keyboard access. No runner/browser/server or manual snapshot launched by the agent. Captain acceptance required before Complete. No commit/merge/push/deploy authorized for this reconstruction. + + +- TASK-019 completion (2026-11-11): Captain explicitly stated “task-019 complete. commit and merge”, satisfying the acceptance gate and authorizing commit/local codex integration of the validated persistent reconstruction. Existing 180/180 tests across 15 files with one worker, lint/build, source preflight and base diff review remain valid; completion changes only context. No independent agent browser review claimed. All completed available task work is integrated after this merge. Home's duplicate pre-acceptance context is saved in a safety stash rather than overwritten. No push/deploy, worktree/branch/stash removal, registration pruning or Captain-session cleanup authorized. diff --git a/src/DetailedPerformanceEditor.jsx b/src/DetailedPerformanceEditor.jsx index 47bdba6..a4e2bf7 100644 --- a/src/DetailedPerformanceEditor.jsx +++ b/src/DetailedPerformanceEditor.jsx @@ -3,10 +3,13 @@ import { Button } from 'react-bootstrap' import { blankRow, copy, loadColumns, measurementColumns, newPerformance, performanceError, performanceTotals, preparePerformanceForSave, signature } from './performanceModel.js' import { previousPerformance, readPerformance, writePerformance } from './performanceStorage.js' import { readStrengthEntry } from './strengthStorage.js' +import usePreviousAvailability from './usePreviousAvailability.js' import StrengthEntryEditor from './StrengthEntryEditor.jsx' export default function DetailedPerformanceEditor({ dateKey, period, definition, prescription, goalSeconds, historicalOnly = false }) { const id = useId() + const contextKey = JSON.stringify([dateKey, period, definition]) + const [loadedContext, setLoadedContext] = useState(null) const [record, setRecord] = useState(() => newPerformance(dateKey, period, definition, prescription)) const [legacy, setLegacy] = useState(null) const [hasSaved, setHasSaved] = useState(false) @@ -19,10 +22,12 @@ export default function DetailedPerformanceEditor({ dateKey, period, definition, const [dirty, setDirty] = useState(false) useEffect(() => { let active = true + setLoadedContext(null) setLoading(true) Promise.all([readPerformance(dateKey, period, definition.id), period === 'morning' ? readStrengthEntry(dateKey, definition.id) : Promise.resolve(null)]) .then(([saved, old]) => { if (!active) return + setLoadedContext(contextKey) setRecord(saved ?? newPerformance(dateKey, period, definition, prescription)) setLegacy(old) setHasSaved(Boolean(saved)) @@ -34,6 +39,10 @@ export default function DetailedPerformanceEditor({ dateKey, period, definition, return () => { active = false } }, [dateKey, period, definition, retry]) + const previousAvailability = usePreviousAvailability({ + dateKey, period, record, contextKey, + enabled: loadedContext === contextKey && !loading && !readFailed, + }) function change(next) { setRecord(next); setDirty(true); setNotice(''); setError('') } function update(index, group, key, raw, sharedKeys) { const value = raw === '' ? null : Number(raw) @@ -98,9 +107,13 @@ export default function DetailedPerformanceEditor({ dateKey, period, definition,
{record.format !== 'emom' && } - + {previousAvailability.available && }
+ {previousAvailability.error &&
+

Could not check previous sessions. {previousAvailability.error}

+ +
} {readFailed && }

{dirty ? 'Unsaved changes. ' : ''}{notice}

{error && } diff --git a/src/EmomTotalEditor.jsx b/src/EmomTotalEditor.jsx index add3ba7..dc7def6 100644 --- a/src/EmomTotalEditor.jsx +++ b/src/EmomTotalEditor.jsx @@ -3,10 +3,13 @@ import { Button } from 'react-bootstrap' import { copy, newPerformance, performanceError, preparePerformanceForSave } from './performanceModel.js' import { previousPerformance, readPerformance, writePerformance } from './performanceStorage.js' import { readStrengthEntry } from './strengthStorage.js' +import usePreviousAvailability from './usePreviousAvailability.js' import DetailedPerformanceEditor from './DetailedPerformanceEditor.jsx' export default function EmomTotalEditor({ dateKey, period, definition, prescription, ...rest }) { const id = useId() + const contextKey = JSON.stringify([dateKey, period, definition]) + const [loadedContext, setLoadedContext] = useState(null) const [record, setRecord] = useState(null) const [historyOpen, setHistoryOpen] = useState(false) const [historical, setHistorical] = useState(false) @@ -18,15 +21,21 @@ export default function EmomTotalEditor({ dateKey, period, definition, prescript const [saved, setSaved] = useState(false) useEffect(() => { let active = true + setLoadedContext(null) setHistoryOpen(false); setBusy(true); setNotice(''); setError(''); setFailed(false); setRecord(null) Promise.all([readPerformance(dateKey, period, definition.id, 'emom-total'), readPerformance(dateKey, period, definition.id), period === 'morning' ? readStrengthEntry(dateKey, definition.id) : null]) .then(([total, detailed, legacy]) => { if (!active) return + setLoadedContext(contextKey) setRecord(total ?? newPerformance(dateKey, period, definition, prescription, 'emom-total')) setSaved(Boolean(total)); setHistorical(Boolean(detailed || legacy)); setBusy(false) }).catch((failure) => { if (active) { setError(failure.message); setFailed(true); setBusy(false) } }) return () => { active = false } }, [dateKey, period, definition, retry]) + const previousAvailability = usePreviousAvailability({ + dateKey, period, record, contextKey, + enabled: loadedContext === contextKey && !failed && Boolean(record), + }) function update(group, key, raw) { setRecord({ ...record, rows: [{ ...record.rows[0], completed: false, [group]: { ...record.rows[0][group], [key]: raw === '' ? null : Number(raw) } }] }) setNotice('Unsaved changes.'); setError('') @@ -60,9 +69,13 @@ export default function EmomTotalEditor({ dateKey, period, definition, prescript
- + {previousAvailability.available && }
+ {previousAvailability.error &&
+

Could not check previous sessions. {previousAvailability.error}

+ +
} {failed && }

{notice}

{error && } diff --git a/src/EmomTotalEditor.test.jsx b/src/EmomTotalEditor.test.jsx index 733e19c..b89f054 100644 --- a/src/EmomTotalEditor.test.jsx +++ b/src/EmomTotalEditor.test.jsx @@ -80,10 +80,10 @@ it('suggests only aggregate history without saving or overwriting current input' prior.rows[0] = { values: { reps: 34 }, load: { vestKg: 6 }, completed: true } await writePerformance(prior) render(); await ready() - fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })); await screen.findByText(/Suggested from/) + fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' })); await screen.findByText(/Suggested from/) expect(screen.getByLabelText('Total reps').value).toBe('34') expect(await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).toBeNull() - fill('Total reps', '35'); fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })); await screen.findByText('Current entries kept.') + fill('Total reps', '35'); fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' })); await screen.findByText('Current entries kept.') expect(screen.getByLabelText('Total reps').value).toBe('35') }) it('opens original minute history for explicit edits without changing the aggregate', async () => { diff --git a/src/PerformanceEditor.test.jsx b/src/PerformanceEditor.test.jsx index ca07a40..f6883df 100644 --- a/src/PerformanceEditor.test.jsx +++ b/src/PerformanceEditor.test.jsx @@ -95,13 +95,13 @@ it('applies previous-session suggestions only to empty drafts and never marks co const p = props('front-plank'); memory.previous = newPerformance('2026-10-29', p.period, p.definition, p.prescription) memory.previous.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true } render(); await ready() - fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })) + fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' })) await screen.findByText(/Suggested from 2026-10-29/) expect(screen.getByLabelText('Set 1 seconds').value).toBe('45') expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy() expect(memory.records.size).toBe(0) fill('Set 1 vest (kg)', 9) - fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })) + fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' })) await screen.findByText(/Current entries kept/) expect(screen.getByLabelText('Set 1 vest (kg)').value).toBe('9') }) diff --git a/src/PreviousAvailability.test.jsx b/src/PreviousAvailability.test.jsx new file mode 100644 index 0000000..e98feb1 --- /dev/null +++ b/src/PreviousAvailability.test.jsx @@ -0,0 +1,143 @@ +import { IDBFactory } from 'fake-indexeddb' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import PerformanceEditor from './PerformanceEditor.jsx' +import DetailedPerformanceEditor from './DetailedPerformanceEditor.jsx' +import { exerciseDefinitions } from './data/index.js' +import { newPerformance } from './performanceModel.js' +import * as storage from './performanceStorage.js' +import { exportBackup } from './backupStorage.js' + +const cases = [ + ['reps', 'dumbbell-floor-fly', 'sets', 'Set 1 reps'], + ['hold', 'front-plank', 'sets', 'Set 1 seconds'], + ['hang', 'daily-hang', 'attempts', 'Attempt 1 seconds'], + ['EMOM total', 'pull-up', 'emom-total', 'Total reps'], +] +function props(id, format = 'sets') { + return { dateKey: '2026-11-10', period: 'morning', definition: exerciseDefinitions.find((d) => d.id === id), prescription: { kind: format.startsWith('emom') ? 'emom' : 'sets', rounds: 10 }, goalSeconds: 120 } +} +function completed(p, format, date = '2026-11-03') { + const entry = newPerformance(date, p.period, p.definition, p.prescription, format) + const row = entry.rows[0] + for (const key of Object.keys(row.values)) row.values[key] = 0 + for (const key of Object.keys(row.load)) if (key !== 'dumbbellCount') row.load[key] = 0 + row.completed = true + return entry +} +const action = () => screen.queryByRole('button', { name: 'Use previous session' }) +async function settledLookup(spy) { + await waitFor(() => expect(spy).toHaveBeenCalled()) + await act(async () => { await spy.mock.results.at(-1).value }) +} +beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory())) +afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) + +it.each(cases)('keeps the action absent in fresh %s editors and never writes during lookup', async (_, id, format) => { + const p = props(id, format) + const before = await exportBackup() + const lookup = vi.spyOn(storage, 'previousPerformance') + render() + expect(action()).toBeNull() + await settledLookup(lookup) + expect(action()).toBeNull() + expect(await exportBackup()).toBe(before) +}) + +it.each(cases)('offers compatible zero-valued %s history without applying or saving it automatically', async (_, id, format, label) => { + const p = props(id, format) + const prior = completed(p, format) + await storage.writePerformance(prior) + const before = await exportBackup() + render() + const button = await screen.findByRole('button', { name: 'Use previous session' }) + expect(screen.getByLabelText(label).value).toBe('') + expect(await exportBackup()).toBe(before) + fireEvent.click(button) + await screen.findByText(/Suggested from/) + expect(screen.getByLabelText(label).value).toBe('0') + expect(await exportBackup()).toBe(before) + // Existing entry protection remains even though history is available. + fireEvent.change(screen.getByLabelText(label), { target: { value: '17' } }) + fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' })) + await screen.findByText(/Current entries kept/) + expect(screen.getByLabelText(label).value).toBe('17') + expect(await exportBackup()).toBe(before) +}) + +it.each(['draft', 'current', 'future', 'incompatible', 'other period', 'other exercise'])('ignores %s regular history', async (kind) => { + const p = props('front-plank') + const source = completed(p, 'sets') + if (kind === 'draft') source.rows[0].completed = false + if (kind === 'current') source.date = p.dateKey + if (kind === 'future') source.date = '2026-11-11' + if (kind === 'incompatible') { source.definition.equipment = ['bodyweight']; source.rows[0].load = {} } + if (kind === 'other period') source.period = 'afternoon' + if (kind === 'other exercise') { source.exerciseId = 'side-plank'; source.definition.id = 'side-plank' } + await storage.writePerformance(source) + const lookup = vi.spyOn(storage, 'previousPerformance') + render() + await settledLookup(lookup) + expect(action()).toBeNull() +}) + +it.each(['draft', 'current', 'future', 'minute format'])('ignores %s EMOM history', async (kind) => { + const p = props('pull-up', 'emom-total') + const source = completed(p, kind === 'minute format' ? 'emom' : 'emom-total') + if (kind === 'draft') source.rows[0].completed = false + if (kind === 'current') source.date = p.dateKey + if (kind === 'future') source.date = '2026-11-11' + await storage.writePerformance(source) + const lookup = vi.spyOn(storage, 'previousPerformance') + render() + await settledLookup(lookup) + expect(action()).toBeNull() +}) + +it('checks a saved historical definition instead of reinterpreting it using the current definition', async () => { + const p = props('front-plank') + await storage.writePerformance(completed(p, 'sets')) + const saved = newPerformance(p.dateKey, p.period, p.definition, p.prescription) + await storage.writePerformance(saved) + render() + expect(await screen.findByRole('button', { name: 'Use previous session' })).toBeTruthy() + expect(screen.getByLabelText('Set 1 vest (kg)').value).toBe('') + expect(await storage.readPerformance(p.dateKey, p.period, p.definition.id)).toEqual(saved) +}) + +it('keeps minute-history availability separate from aggregate history', async () => { + const p = props('pull-up', 'emom-total') + await storage.writePerformance(completed(p, 'emom-total')) + const minute = completed(p, 'emom', p.dateKey) + await storage.writePerformance(minute) + const lookup = vi.spyOn(storage, 'previousPerformance') + render() + await settledLookup(lookup) + expect(action()).toBeNull() + expect(screen.getByLabelText('Minute 1 reps').value).toBe('0') +}) + +it('copies completed source rows only, leaving newer partial source values out of suggestions', async () => { + const p = props('front-plank') + const source = completed(p, 'sets') + source.rows.push({ values: { seconds: 99 }, load: { vestKg: null }, completed: false }) + await storage.writePerformance(source) + render() + fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' })) + await screen.findByText(/Suggested from/) + expect(screen.getByLabelText('Set 1 seconds').value).toBe('0') + expect(screen.queryByLabelText('Set 2 seconds')).toBeNull() + expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy() + expect(await storage.readPerformance(source.date, p.period, p.definition.id)).toEqual(source) + expect(await storage.readPerformance(p.dateKey, p.period, p.definition.id)).toBeNull() +}) + +it('offers compatible minute history in its original editor without applying aggregate data', async () => { + const p = props('pull-up', 'emom-total') + await storage.writePerformance(completed(p, 'emom')) + await storage.writePerformance(completed(p, 'emom', p.dateKey)) + render() + expect(await screen.findByRole('button', { name: 'Use previous session' })).toBeTruthy() + expect(screen.getByLabelText('Minute 1 reps').value).toBe('0') + expect(await storage.readPerformance(p.dateKey, p.period, p.definition.id, 'emom-total')).toBeNull() +}) diff --git a/src/PreviousAvailabilityAsync.test.jsx b/src/PreviousAvailabilityAsync.test.jsx new file mode 100644 index 0000000..130466c --- /dev/null +++ b/src/PreviousAvailabilityAsync.test.jsx @@ -0,0 +1,125 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { useLayoutEffect } from 'react' +const storage = vi.hoisted(() => ({ read: vi.fn(), lookup: vi.fn(), write: vi.fn() })) +vi.mock('./performanceStorage.js', () => ({ + readPerformance: storage.read, previousPerformance: storage.lookup, writePerformance: storage.write, +})) +vi.mock('./strengthStorage.js', () => ({ readStrengthEntry: vi.fn(async () => null) })) +import DetailedPerformanceEditor from './DetailedPerformanceEditor.jsx' +import EmomTotalEditor from './EmomTotalEditor.jsx' +import { exerciseDefinitions } from './data/index.js' +import { newPerformance } from './performanceModel.js' + +const editors = [ + ['regular', DetailedPerformanceEditor, 'front-plank', 'Set 1 seconds'], + ['EMOM', EmomTotalEditor, 'pull-up', 'Total reps'], +] +const definition = (id) => exerciseDefinitions.find((d) => d.id === id) +const props = (id) => ({ dateKey: '2026-11-10', period: 'morning', definition: definition(id), prescription: { kind: id === 'pull-up' || id === 'chin-up' ? 'emom' : 'sets', rounds: 10 } }) +const action = () => screen.queryByRole('button', { name: 'Use previous session' }) +function deferred() { + let resolve + let reject + const promise = new Promise((yes, no) => { resolve = yes; reject = no }) + return { promise, resolve, reject } +} +async function flush(job, value, reject = false) { + await act(async () => { job[reject ? 'reject' : 'resolve'](value); await job.promise.catch(() => {}) }) +} +beforeEach(() => { + vi.resetAllMocks() + storage.read.mockResolvedValue(null) + storage.lookup.mockResolvedValue(null) + storage.write.mockResolvedValue(undefined) +}) +afterEach(cleanup) + +it.each(editors)('keeps unknown %s availability hidden, without blocking manual entry', async (_, Editor, id, label) => { + const job = deferred() + storage.lookup.mockReturnValue(job.promise) + render() + expect(action()).toBeNull() + await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(1)) + expect(screen.getByLabelText(label).disabled).toBe(false) + fireEvent.change(screen.getByLabelText(label), { target: { value: '19' } }) + expect(action()).toBeNull() + await flush(job, { date: '2026-11-03' }) + expect(action()).toBeTruthy() + expect(screen.getByLabelText(label).value).toBe('19') + expect(storage.write).not.toHaveBeenCalled() +}) + +it.each(editors)('retries a %s lookup failure without reloading or losing typed values', async (_, Editor, id, label) => { + storage.lookup.mockRejectedValueOnce(new Error('Lookup unavailable')).mockResolvedValue({ date: '2026-11-03' }) + render() + expect((await screen.findByRole('alert')).textContent).toMatch(/Could not check previous sessions.*Lookup unavailable/) + expect(action()).toBeNull() + fireEvent.change(screen.getByLabelText(label), { target: { value: '23' } }) + const reads = storage.read.mock.calls.length + fireEvent.click(screen.getByRole('button', { name: 'Retry previous-session lookup' })) + expect(await screen.findByRole('button', { name: 'Use previous session' })).toBeTruthy() + expect(screen.queryByRole('alert')).toBeNull() + expect(screen.getByLabelText(label).value).toBe('23') + expect(storage.read).toHaveBeenCalledTimes(reads) + expect(storage.write).not.toHaveBeenCalled() +}) + +for (const [name, Editor, id] of editors) { + it.each(['date', 'period', 'exercise', 'definition'])(`ignores stale ${name} lookup results after a %s change`, async (dimension) => { + const first = deferred() + const second = deferred() + storage.lookup.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise) + const p = props(id) + const view = render() + await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(1)) + const next = { ...p } + if (dimension === 'date') next.dateKey = '2026-11-11' + if (dimension === 'period') next.period = 'afternoon' + if (dimension === 'exercise') next.definition = definition(id === 'pull-up' ? 'chin-up' : 'deep-squat-hold') + if (dimension === 'definition') next.definition = { ...p.definition, version: p.definition.version + 1 } + view.rerender() + expect(action()).toBeNull() + await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(2)) + await flush(second, null) + await flush(first, { date: '2026-11-03' }) + expect(action()).toBeNull() + expect(storage.lookup.mock.calls[1]).toEqual([next.dateKey, next.period, next.definition, id === 'pull-up' ? 'emom-total' : 'sets']) + }) +} + +it.each(editors)('never flashes old %s availability while a new saved definition loads', async (_, Editor, id) => { + storage.lookup.mockResolvedValue({ date: '2026-11-03' }) + const observations = [] + function Probe({ p }) { + useLayoutEffect(() => { observations.push(Boolean(action())) }) + return + } + const p = props(id) + const view = render() + await screen.findByRole('button', { name: 'Use previous session' }) + const job = deferred() + storage.read.mockReturnValue(job.promise) + const next = { ...p, definition: { ...p.definition, version: p.definition.version + 1 } } + view.rerender() + expect(observations.at(-1)).toBe(false) + expect(action()).toBeNull() + expect(storage.lookup).toHaveBeenCalledTimes(1) + await flush(job, null) + await screen.findByRole('button', { name: 'Use previous session' }) + expect(storage.lookup.mock.calls.at(-1)[2]).toEqual(next.definition) +}) + +it('rechecks a loaded historical format when the date changes, without mixing minutes and totals', async () => { + const p = props('pull-up') + storage.read.mockResolvedValueOnce(newPerformance(p.dateKey, p.period, p.definition, p.prescription, 'emom')) + const view = render() + await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(1)) + expect(storage.lookup.mock.calls.at(-1)[3]).toBe('emom') + const nextDate = '2026-11-11' + storage.read.mockResolvedValueOnce(newPerformance(nextDate, p.period, p.definition, p.prescription, 'sets')) + view.rerender() + await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(2)) + expect(storage.lookup.mock.calls.at(-1)[3]).toBe('sets') + expect(action()).toBeNull() +}) diff --git a/src/SideEntry.test.jsx b/src/SideEntry.test.jsx index ae2f0d1..a52a652 100644 --- a/src/SideEntry.test.jsx +++ b/src/SideEntry.test.jsx @@ -52,7 +52,7 @@ it('records a hold through one seconds input and suggests both sides as an unsav await writePerformance(prior) const view = render(); await ready() expect(screen.getAllByRole('spinbutton')).toHaveLength(1) - fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })); await screen.findByText(/Suggested from/) + fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' })); await screen.findByText(/Suggested from/) expect(screen.getByLabelText('Set 1 seconds (each side)').value).toBe('25') expect(await readPerformance(p.dateKey, p.period, p.definition.id)).toBeNull() fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved') diff --git a/src/usePreviousAvailability.js b/src/usePreviousAvailability.js new file mode 100644 index 0000000..e6975c0 --- /dev/null +++ b/src/usePreviousAvailability.js @@ -0,0 +1,30 @@ +import { useEffect, useState } from 'react' +import { previousPerformance } from './performanceStorage.js' + +// Key both the loaded saved definition and its owning editor context. Never +// expose the previous context's result while the next read/effect is pending. +export default function usePreviousAvailability({ dateKey, period, record, contextKey, enabled }) { + const key = JSON.stringify([contextKey, dateKey, period, record?.definition, record?.format]) + const [attempt, setAttempt] = useState(0) + const [result, setResult] = useState(null) + useEffect(() => { + setResult(null) + if (!enabled) return + let active = true + const [, date, sessionPeriod, definition, format] = JSON.parse(key) + previousPerformance(date, sessionPeriod, definition, format) + .then((previous) => { + if (active) setResult({ key, attempt, available: Boolean(previous), error: '' }) + }) + .catch((failure) => { + if (active) setResult({ key, attempt, available: false, error: failure.message || 'Previous-session lookup failed.' }) + }) + return () => { active = false } + }, [key, enabled, attempt]) + const current = enabled && result?.key === key && result.attempt === attempt ? result : null + return { + available: current?.available ?? false, + error: current?.error ?? '', + retry: () => setAttempt((value) => value + 1), + } +}