Check pocketid_sub before hashed_password so users with a linked
passkey (and hence a null hash) get the helpful message rather than
"Invalid credentials".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- /token: reject password auth with a clear message if pocketid_sub is
set on the account — passkey-linked users must sign in via PocketID
- Link callback + auto-link-by-email: null out hashed_password when the
passkey is attached so the old hash can't be used even if the check
above were bypassed
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
New /activities/{id}/route-leaderboard endpoint ranks the user's timed
efforts on the same route; frontend RouteLeaderboard card sits beside
Laps, showing this activity's time/rank/gap and the top 10 (current
effort highlighted green, also surfaced if outside the top 10).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Garmin Connect sync:
- Incremental syncs now re-fetch only a 1-day buffer (yesterday + today)
instead of the full lookback window every run. Full lookback applies on
the first sync only. Cuts steady-state API calls ~10x.
- Beat interval is now configurable via GARMIN_SYNC_INTERVAL_MINUTES and
surfaced to the UI; the sync toggle is relabelled to the real cadence.
Frontend:
- Collapsible sidebar; clearer logged-in user + role display.
- Unified Body Battery colouring between dashboard and health (shared util).
- Sleep score trend chart on health page.
- Segments + medals on the dashboard's most-recent activity.
- Segments tab on the Records page.
Repo hygiene: add .gitignore, untrack committed __pycache__/*.pyc.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Garmin sync: read sleepScores from dailySleepDTO (Garmin nests it there),
so sleep score is actually stored instead of always null
- Dashboard: pass YYYY-MM-DD to the intraday endpoint (was a full ISO
timestamp), so the body-battery tile populates
- Segment matching: follow the segment in its created direction with a
path-length sanity check, so out-and-back routes no longer match an early
start pass to a late finish (the >1h bogus segment times)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Lap bests: compare against OTHER activities on the route (exclude self),
so single-activity routes no longer show every lap as "best"
- Segment create: POST to trailing-slash URL (was a 307 that dropped the body);
surface errors in the UI
- PR splits: scale GPS distance stream to the activity's official distance so
over-measured GPS no longer yields bogus split PRs
- Speed route colours: red->orange->green->blue->purple (slow->fast) with smooth
interpolation + a Slow/Fast gradient key under the map
- Health body battery: snap activity highlight to the categorical axis;
white tooltip text + % suffix
- Health weight: y-min = lowest weight - 20kg; st/lb hover shows total lbs too
- Health sleep: move 8h/avg reference labels into the right margin
- Dashboard: Health-today pulls latest non-null values (sleep score, VO2 max);
body battery tile renders a condensed colour-graded intraday graph
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Fixes:
- Dashboard: featured most-recent activity card with map + stats
- Maps default to Street; preferCanvas + larger tile buffer for smoother pan/zoom
- Running cadence as colour-banded dots + 165 spm guide line
- Routes: inline row expansion, rename (PATCH /routes/{id}), podium + deltas, tiled map
- Records: remove reversed pace Y-axis
- Profile: remove resting HR; add goal weight
- Health: snapshot weight carry-forward; VO2 trend axis 30-70;
weight goal line + kg/st-lb toggle + axis max; sleep 8h/avg lines
- Garmin sync progress moved to global store with persistent floating bar
Features:
- Speed-coloured activity route (default) with Speed/Solid toggle
- GPS-geometry segments: draw on map, match across all activities,
1st/2nd/3rd leaderboard + podium badges (replaces old distance segments)
- Lap bests: best time per lap across a route + delta column
- Body Battery: highlight activity time windows
Schema: users.goal_weight_kg ALTER; new segments/segment_efforts tables.
Removes RouteSegment, the Segments page, and segment-bests endpoints.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signing in by passkey on a fresh install created a new empty account because
the seeded admin has no email to match on. Add canonical SSO-style linking: an
authenticated user starts an OIDC flow whose `state` is a signed, short-lived
"link to user N" token (purpose=pocketid-link). The callback detects that state
and attaches the returned identity to that account instead of creating/matching
one — no reliance on emails lining up, and no group gating (the initiator is
already authorised; this is identity linking, not access control).
- auth.py: _make_link_state/_decode_link_state, GET /pocketid/link-url, callback
handles state (rejects if the passkey is already on another account →
auth_error=passkey_in_use). Expose has_passkey on /auth/me.
- Profile: "Passkey sign-in" section for all users — shows linked state or a
"Link a passkey to this account" button; success banner on return.
- Login: messages for passkey_in_use / link_failed.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
_get_pocketid_config / _get_allowed_group selected an admin row with an
unordered LIMIT 1. With more than one admin (e.g. the seeded password admin
plus a passkey-linked admin), this non-deterministically returned an admin
without PocketID config — making the passkey button disappear (available=false)
and group gating inconsistent. Add _config_admin() which prefers the admin that
actually has an issuer set, then falls back to the lowest-id admin.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
save_pocketid_config cleared the stored client secret whenever the form was
submitted with a blank secret field — but the UI hint says blank means "keep
existing". Re-saving config (e.g. to set the allowed group) therefore wiped the
secret and broke token exchange ("Token exchange failed"). Now a blank field
keeps the existing secret; only a non-empty value overwrites it.
Also log PocketID's actual token-endpoint response body on failure so the cause
(invalid_client, redirect_uri mismatch, etc.) is visible in backend logs.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
PocketID OIDC already auto-provisioned users keyed by pocketid_sub, and the
data layer was already fully user-scoped. This adds the missing pieces for
running real multi-user:
- auth.py callback: link by email to an existing un-linked account (so the
admin keeps their data when first signing in by passkey), collision-safe
username generation, and request the `groups` scope.
- Group gating: optional pocketid_allowed_group (admin-config or
POCKETID_ALLOWED_GROUP env); users lacking the group are rejected at the
callback and redirected to /login?auth_error=not_authorized.
- New admin users API (app/api/users.py): list users, promote/demote admin
(guards against demoting/locking out the last admin or yourself), and delete
a user with ordered bulk deletes of all their data + on-disk files.
- ProfilePage: allowed-group field; LoginPage: rejected-login message;
Layout: admin-only Users nav; new UsersPage.
Resync milevault_export to current source (it had drifted many features behind
— missing garmin_sync, npm-ci Dockerfile and @polyline-codec that broke its own
CI) and add POCKETID_ALLOWED_GROUP to .env.example.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
garmin.get_stats() never returns averageHeartRate — avg_hr_day is only computable
from intraday HR which Garmin's API only serves for recent dates (~90-120 days).
The dead lookup gave false confidence that historical backfill would work.
Also populate max_hr_day from the Garmin export's UDS daily summaries (maxHeartRate
field is present for the full history), so historical max HR is available after
re-importing the export.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The previous query used >= on start_time with no upper bound, so it matched
ALL activities of that sport type starting after the given minute on that day —
crashing with MultipleResultsFound whenever two such activities existed.
Fix: bound the window to ±60s from start_time and use .scalars().first()
so the query returns at most one Activity rather than raising on duplicates.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Garmin Connect exports use UDSFile_*.json (not DailyMetrics) for daily
wellness summaries, and pack activity FIT files inside nested sub-zips
under DI-Connect-Uploaded-Files/ rather than at the top level.
- process_garmin_health_zip: match UDSFile_*.json instead of DailyMetrics,
handle list-of-records format, extract stress from allDayStress.aggregatorList,
convert floorsAscendedInMeters to floor count
- upload_garmin_export: recurse into nested .zip files to find and queue
individual activity FIT files
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Previously the tip was sitting just outside the outer edge of the track,
making it hard to see exactly where it pointed. Now tipR=r (centre of the
coloured band) so the tip is precisely at the value's position, with a
narrow 5° spread for better precision.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Replace ACSM estimates with exact Garmin/Cooper Institute values for 6 age
brackets (20-29 through 70+) for both male and female
- Add Superior (≥95th percentile) as the top category in purple; rename
Very Poor → removed, categories are now Poor/Fair/Good/Excellent/Superior
- Update getVo2Category to use lower-bound logic (count thresholds met)
matching how Garmin publishes the data
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Segments covering >50% of the gauge range were getting large=1, causing
the SVG to draw a 234°+ arc going the wrong way around, producing a
spurious lobe on the right side of the widget.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Remove the filled arc from MIN to value (was overpainting the coloured bands)
- Category bands are now full-brightness with no opacity reduction
- White triangular arrow: base outside the track, tip touching the outer edge,
pointing inward at the exact value position
- Dark background track slightly wider than colour bands for clean border effect
- Adjusted cy/viewBox height to give the arrow room above the arc
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
sweep=0 in SVG is counter-clockwise which goes through the bottom of the
circle. sweep=1 (clockwise) correctly traces left→top→right.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Rewrote the SVG arc math — sweep=0 (counter-clockwise) correctly draws the
upper semicircle from left (30) over the top to right (70). The gauge now:
- Spans a fixed VO2 range of 30–70 across 180°
- Shows dimmed age/sex-specific ACSM category bands as background
- Fills a bright arc from 30 to the current value in the category colour
- Has a small triangular arrow pointer at the value position on the arc
- Shows the value number centred in the dome, coloured for its category
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Increased le=1000 → le=2000 to allow the 5Y trend (1826 days) and the
allDays snapshot navigation query (limit 2000) to succeed.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add biological_sex field to User model, profile API, and ProfilePage toggle (male/female) — used to select the correct ACSM VO2 max threshold table
- Replace simple VO2 max number in daily snapshot with a colour-coded SVG radial gauge (Very Poor=red, Poor=orange, Fair=green, Good=blue, Excellent=purple) driven by sex- and age-appropriate thresholds
- Shrink Sleep widget to half-width, expand Heart & HRV to half-width; reorganise Heart & HRV internals into a 2×2 grid to reduce vertical height
- Add connectNulls + showDots to VO2 Max trend chart so sparse readings connect with a continuous line
- Add 3Y and 5Y range options to the Trends selector; increase allDays limit to 2000 for full 5yr snapshot navigation
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The maxmet/daily range query returns entries shaped as:
{"generic": {"calendarDate": "...", "vo2MaxPreciseValue": 42.7, ...}, ...}
The extractor was looking at the top level of each entry, finding nothing, and
falling through to the single-point training_status fallback every time.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The previous code used `if not mm_history:` to decide whether to fall back to
get_training_status(). If the maxmet API returned a non-empty list with no valid
vo2max values (or a non-list type), the fallback was skipped and nothing stored.
Changes:
- Normalise mm_raw: only use it if it's a list (handles dict/None responses)
- Check valid_from_range: fall back to training_status whenever no usable value
was found in the range query, regardless of whether it returned entries
- Upgrade all related log lines to INFO so the result is visible without debug mode
- Guard the entry loop against non-dict items
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Instead of storing only the most recent measurement, query the maxmet
endpoint with the full sync window (start_date to today) to populate
one row per measurement date. Falls back to training_status most-recent
value if the range query returns nothing.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Correct path confirmed from live API response. Store against the actual
measurement date (calendarDate from the VO2 max record) rather than
today, so the carry-forward logic shows the right value from the correct
day. Also store fitnessAge from the fitnessage endpoint alongside it.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
fitnessage endpoint contains fitness age only, not VO2 max. The maxmet
endpoint (/metrics-service/metrics/maxmet/daily) is the correct source.
Keep debug logging temporarily to confirm key names from live API.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
get_stats() does not include VO2 max. Switch to get_fitnessage_data()
which hits /fitnessage-service/fitnessage and returns the current VO2
max estimate and fitness age. Called once per sync (today only) since
VO2 max is a slow-changing metric; the frontend carry-forward shows it
on older days. Remove the incorrect stats.get() attempt from _parse_day.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Show the most recently known VO2 max value on days where Garmin has
not produced a new estimate (it only updates after certain activities).
Fix the sync lookback days input resetting to the server value during
polling — the form now initialises from the server once on first load
and is not overwritten by background refetches.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Sleep: store per-epoch stage timestamps in new sleep_stages JSON column;
DailySnapshot now renders a proper 4-lane hypnogram (Awake/REM/Light/Deep)
instead of the old proportional flat bar
- Body battery: replace grey background bars + white line with per-minute bars
coloured by inferred type (sleep=indigo, rest=teal, active=orange, stable=grey)
derived from sleep window + battery direction; Y-axis fixed 0-100
- Routes: convert sidebar list to tile grid sorted by most completions; tiles
colour-bordered by sport type (blue=running, orange=cycling); completion count
shown on each tile; detail panel displays below the grid when a tile is clicked
- Segments on activity detail: add column headers (This run / Best / Δ) and
show signed time delta vs best, green when faster, red when slower
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Pace: FIT 0xFFFF sentinel (65.535 m/s) was stored as avg_speed_ms on every
activity and lap; add _sanitize_speed() to parser falling back to dist/dur,
plus a startup SQL migration that fixed 120 activities and 688 laps in-place
- Records: remove swimming from Distance PRs; Route Records rows are clickable
(navigate to activity), View button removed, small SVG route map per row;
Segment Records uses same tiled route-card layout as Segments page
- Segments: replace route dropdown with responsive tile grid showing SVG map
thumbnails; selecting a tile reveals the segment management panel below
- RouteMiniMap: new pure-SVG component (no Leaflet) for route thumbnails,
decodes polyline and normalises coords into a fixed viewBox
- Health: rename "Avg Heart Rate (day)" → "Heart Rate"; weight chart now
filters to non-null rows and enables connectNulls + dots for sparse data
- Dashboard: 4-col layout at lg breakpoint so Body Battery sits between weekly
chart and Health Today; Body Battery card gains a 24-hr sparkline from the
values[] already present in the health summary response
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Guard bb variable scope and filter None entries from bodyBatteryValuesArray
before subtraction in _compute_body_battery_hires.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Body battery: replace circular ring with compact full-height colored bar chart,
level as line overlay, legend shows only types present in data
- Dashboard: add mini body battery summary card above health today panel
- Profile: remove editable resting HR and manual weight log; show 7-day avg
resting HR and latest Garmin weight as read-only
- Backend: add GET /routes/{id}/segment-bests bulk endpoint (fetches all matched
activity data points in one query, computes best segment time per segment)
- Backend: add GET /records/routes for fastest activity per named route
- Routes page: add Segments panel to route detail (grouped as 1km splits vs
hills/turns, best times, delete, theoretical best)
- Activity detail page: show segment times computed client-side from data points,
🏆 badge if new best
- Records page: add Route Records and Segment Records tabs alongside Distance PRs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Segments page: new /segments route with auto-generate (1km splits, turn
detection, hill detection), manual segment creation, per-segment performance
times across matched activities; fixed auth on existing segment endpoints
- YTD distance: new /activities/stats/ytd endpoint; Dashboard replaces
'Total distance' with 'Running this year' + 'Cycling this year'; Activities
page shows YTD stats row
- Weekly chart click: clicking a Dashboard bar navigates to Activities filtered
to that week; Activities reads from/to query params with dismissable chip
- Route matching: add ±2.5% distance gate + 3% relative DTW threshold
(was flat 80m); tighten candidate pre-filter from 80/120% to 95/105%
- Body battery layout: HR chart and body battery now side-by-side at same
height on large screens instead of stacked full-width
- Pace display fix: MetricTimeline clamps GPS speed outliers before computing
Y-axis domain; tick formatter guards against v<=0 or v>25 m/s
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Previously, once last_sync_at was set the incremental path always used
since-1d as start_date, ignoring lookback_days entirely. Increasing the
lookback setting had no effect on already-synced instances.
Fix: take min(since-1d, today-lookback_days) so the window always covers
at least the configured lookback period, whether or not a prior sync ran.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Parses Garmin Connect get_body_battery() per day, storing charged/drained/
start+end levels and the fine-grained [[ts_ms, level, type, stress]] values
array in a new body_battery JSONB column on health_metrics.
Frontend adds:
- BatteryRing SVG gauge (color-scaled 0–100)
- BodyBatteryChart: ComposedChart with type-colored bars (REST/ACTIVE/SLEEP/
STRESS) and battery level overlay line, matching Garmin's layout
- Body battery trend chart in the Trends section (end_level per day)
Also adds avg_hr_day and weight data which now correctly sync with the
intraday_hr JSON serialization fix from the previous commit.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
psycopg2 treats Python lists as PostgreSQL arrays (bigint[]) rather than JSON,
causing a DatatypeMismatch error on the json/jsonb column. Serializing with
json.dumps() before the raw SQL INSERT fixes the type error.
Also wrap per-day INSERT in try/except+rollback so one bad day doesn't abort
the entire session, and add db.rollback() in tasks.py after sync_wellness
failure so the final status-update commit can always succeed.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The useQuery for intradayData referenced selectedDay (a useMemo) before it
was declared in the function body, causing ReferenceError on every render
and breaking the health page entirely.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Backend:
- main.py: add ADD COLUMN IF NOT EXISTS migrations for avg_hr_day, max_hr_day,
and intraday_hr (JSONB) on health_metrics — these columns were in the model
but missing from existing DB instances, silently dropping all avg/max HR data.
- models/user.py: add intraday_hr JSON column to HealthMetric.
- garmin_connect_sync.py: fetch body composition (weight, BMI, body fat, muscle
mass) via get_body_composition() per day, with stats.bodyWeight as fallback.
Fetch intraday heart rate via get_heart_rates() and store non-null
[epoch_ms, bpm] pairs in intraday_hr.
- health.py: add GET /health-metrics/intraday?date=YYYY-MM-DD endpoint that
returns the stored intraday_hr array for a specific day.
Frontend (HealthPage):
- Add IntradayHrChart component: AreaChart rendering the 24-hour HR trace
with time-of-day x-axis.
- DailySnapshot: show 24-hour HR chart (when intraday data present) above
the activity strip; add weight + body fat % to the Heart & HRV card;
show max HR alongside avg HR.
- HealthPage: query /intraday for the selected day and pass data down.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Backend:
- Change beat schedule from 3600s (hourly) to 1800s (30 minutes)
- Emit intermediate last_sync_status DB commits at each phase of
sync_garmin_connect_user ("Connecting to Garmin...", "Syncing activities...",
"Syncing wellness data...") so the frontend can reflect live progress.
Snapshot config fields upfront to avoid reading expired ORM attrs after commits.
Frontend (ProfilePage):
- Replace blind 3-second timeout with 2s polling loop that reads the live
last_sync_status from /garmin-sync/config after triggering a sync.
- Wait until an in-progress status is observed before declaring completion,
avoiding a false-finish on the previous terminal status.
- Show an animated progress bar that advances through the sync phases with
the current status text below it. Safety timeout stops polling after 10 min.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- garmin_connect_sync: revert to garth.loads() for token auth — login(tokenstore=)
dispatches on len>512, treating compact tokens as filesystem paths and forcing a
full re-login on every sync. Explicitly set display_name from the embedded profile.
- garmin_connect_sync: restore incremental sync for both activities and wellness —
always re-fetching the full lookback window was generating ~270 Garmin API calls
per wellness sync run, risking rate-limits. Now uses since-1d when since is set.
Add 0.25s per-day sleep in sync_wellness as an additional rate-limit guard.
- models/user.py: replace the dropped uq_pr_current UniqueConstraint in
PersonalRecord.__table_args__ with the partial Index the DB actually has,
so the model and live schema no longer permanently diverge.
- models/user.py: add ondelete="SET NULL" to Activity.named_route_id FK so the
DB cascade handles unlinks if routes are deleted outside the API endpoint.
- main.py: add startup migration to re-add activities_named_route_id_fkey with
ON DELETE SET NULL on existing deployments.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>