Compare commits

...
36 Commits
Author SHA1 Message Date
Duarte Santos 551b072c54 MCP: die zweite Einheit an einem Tag ist erreichbar, und ein leeres 1RM sagt warum
Zwei Befunde aus dem Parity-Durchlauf gegen echte Daten. Die Arithmetik stimmte
ueberall (rund 120 Werte gegen eine unabhaengige Nachrechnung, null Abweichung)
— diese beiden nicht.

get_workout nahm `.find(x => x.d === date)`. Wer morgens hebt und abends laeuft,
hat zwei Einheiten am selben Datum, und die zweite war ueber gar keinen Weg
erreichbar: es gab nirgends eine id, und die Frage nach dem Lauf bekam die
Zahlen des Zugtrainings — vollkommen selbstbewusst vorgetragen. list_workouts
liefert jetzt `id`, get_workout nimmt `workout_id` oder `date`, und bei zwei
Treffern am selben Tag antwortet es mit beiden zur Auswahl statt zu raten.

Und `best: null` hatte zwei gegensaetzliche Ursachen in einer Form: nie
trainiert, oder immer ueber der 12-Wiederholungs-Grenze. Eine Wade, die seit
Monaten mit 15ern im Log steht, las sich damit als "keine Aufzeichnungen".
no_estimate_reason unterscheidet die beiden, und formula_note steht jetzt auch
auf diesem Zweig — bisher gab es die Erklaerung nur in der PR-Tabelle.

Drei Regressionstests dazu (36 statt 33), mcp/README zu get_workout nachgezogen.
2026-08-04 17:48:52 +02:00
Duarte Santos e007f76d43 MCP: CI laeuft ueberhaupt erstmal, und der Server ueberlebt seinen Client nicht
Fuer mcp/ gab es keinen CI-Job — weder die 33 Tests noch sonst irgendwas lief je
auf GitHub. Jetzt laeuft beides bei jedem PR, der mcp/ oder frontend/ anfasst.

Dazu der Check, den die Testsuite prinzipiell nicht machen kann: vitest loest
ueber Vite auf, also gehen dort import.meta.glob, ?raw und .jsx anstandslos
durch. Genau so kam ein Vite-only-Import in ein gemeinsames Lib-Modul und liess
33 gruene Tests ueber einem Server stehen, der beim Start starb.
check-node-loadable.mjs laeuft deshalb unter nacktem node — dass es ausserhalb
von vitest laeuft, IST der Test. Gegengeprueft: Bug wieder eingebaut → Exit 1
und history.js/progression.js/tools.js namentlich gemeldet; sauber → Exit 0.

Und der fs.watch-Handle haelt die Event-Loop offen, sobald es eine State-Datei
zu beobachten gibt — der Prozess ueberlebt damit den Client, der ihn gestartet
hat, obwohl die mcp/README genau das Gegenteil verspricht. Ein unref() reicht;
nachgemessen: mit State-Datei vorher Exit 124 (haengt), jetzt Exit 0, und der
Watcher invalidiert den Cache unveraendert weiter.
2026-08-04 16:40:03 +02:00
Duarte Santos e28345dd13 Release v1.2.5: der MCP-Server, und sonst nichts an der App
Letztes publiziertes Release war v1.2.4, also ist das hier v1.2.5 — alles seit
dem Release in EINE Nummer. Inhalt ist genau eine Sache: der optionale
MCP-Server aus PR #19 nebst dem i18n-Kern-Split, der ihn ueberhaupt erst unter
reinem Node ladbar macht.

An der App selbst aendert sich nichts. Wer keinen KI-Client benutzt, merkt von
diesem Release ueberhaupt nichts: nichts wandert in den Docker-Build, die
docker-compose.yml bleibt unberuehrt.

Kein neues APK — der Bundle-Hash bewegt sich zwar (der Modulgraph haengt jetzt
direkt am i18n-Kern), aber verhalten tut sich die App identisch. Die
Download-Zeile auf der Website bleibt deshalb bei v1.2.4.
2026-08-04 16:35:34 +02:00
Duarte Santos ba412cb36d MCP: die Lib bleibt unter reinem Node ladbar, und die Testwerte stimmen wieder
Der MCP-Server ist ein nacktes `node src/index.js` — kein Vite, kein React. PR 19
hatte dafuer den reinen Kern nach i18n-core.js gezogen; v1.2.4 hat danach in
history.js `t` wieder aus i18n.js geholt, und damit import.meta.glob ueber die
Locale-Packs plus useSyncExternalStore in einen Prozess, der beides nicht hat.
Der Server starb beim Import:

  TypeError: (intermediate value).glob is not a function

Die Testsuite konnte das nicht sehen: vitest transformiert import.meta.glob, also
liefen 33 gruene Tests gegen ein Binary, das nie startet. i18n.js re-exportiert
ohnehin genau dieses `t` aus dem Kern — history.js, mobile.js und plan-share.js
holen es jetzt direkt von dort, und mitgeschleppt wird nichts mehr.

Dazu die Werte, die der v1.2.4-Seed verschoben hat: Volumen 18500 → 18412.5
(Handsumme w×r ueber die zwanzig erledigten Saetze), Koerpergewicht 78.6 → 78.4,
Wiegung 78.5/1.5 → 78.3/1.3, Dauer 51 min → 1h 11m — samt der Zusicherung, die
sich das "N min"-Format noch fest verdrahtet hatte. Jeder Wert nachgerechnet,
nicht aus einem roten Lauf abgeschrieben.

Und das FORMULAS aus Punkt 2 des Reviews, das als einziges stehengeblieben war.
2026-08-04 16:30:34 +02:00
Duarte Santos f554b6b004 Merge pull request #19 from Pengboi/feat/mcp-server
MCP: read-only stdio server for LLM apps to query workout history

Ein Node-Prozess, den der LLM-Client selbst startet und der dieselben reinen
Helfer aus frontend/src/lib benutzt wie die Stats-Seite — also stehen dort
dieselben Zahlen. Read-only, kein Container, kein zusaetzliches Auth, nichts
verlaesst die Box. Wer keinen KI-Client benutzt, merkt nichts davon.
2026-08-04 16:30:14 +02:00
Pengboi 09949686c2 MCP: fixes from review (cardio mode, dead code, Stryker drop, docs)
· entryView was passing `e.target || { id: e.id }` to modeOf, which
   doesn't put id on the target when target exists — so a cardio config
   saved as {sets, min, speed} (no mode, no id) fell through to 'reps'
   and the label came back as "0×0". Now uses the same pattern every
   app call site uses (Workout.jsx, Stats.jsx, progression.js):
   modeOf({ ...(e.target || {}), id: e.id }). Same fix applied to the
   setLabel call right below. Added a regression test using a real
   cardio exercise id with a target that has no mode key — would have
   caught the original bug.

 · requireIso/ISO/fmt/friendlyDate/MUSCLES were unused (zod regexes
   cover ISO validation at the SDK layer). Removed, along with the
   misplaced comment that described requireIso but sat above entryView.

 · estimate_1rm's exercise_id schema description referenced
   search_exercises (v1.5) which doesn't exist yet — an LLM reading
   the schema would try to call it. Dropped the reference; the
   Roadmap section in mcp/README.md drops the same mention.

 · resolveUid threw "set OPENGYM_UID to one of: " (empty list) when
   there were zero state files but multiple users in db.json — the
   files array was empty so files.join(', ') rendered nothing. Now
   falls back to the db.json user ids in that branch.

 · Dropped Stryker entirely. The MCP SDK's 93 transitive runtime
   packages are tolerable since mcp/ is opt-in and never enters
   Docker, but a second test toolchain for a 39% mutation score
   wasn't carrying its weight next to the plain vitest suite.
   Removed .stryker.conf.json, the two Stryker devDeps, the
   mutation:test script, the .gitignore entries, and the README
   section. mcp/ now has a single devDep (vitest); 0 vulnerabilities
   (was 2 moderate).

 · CONTRIBUTING.md layout block + a one-line cross-reference in
   README.md's Tech section pointing at mcp/README.md, so people can
   actually find it.

92 frontend + 33 MCP tests pass.
2026-08-02 19:42:36 +01:00
Duarte Santos 7c69e57b4f Website: the download is v1.2.4
The APK on opengym.duarte-santos.ch is the 1.2.4 build (versionCode 5, same
signing key, so it installs over 1.2.3). The meta line said 1.2.3.
2026-08-01 17:09:28 +02:00
Duarte Santos 663e0b3987 Release v1.2.4: the effort stats, and bodyweight training that knows it is
v1.2.3 is published, so this is the next patch and everything since it belongs in
this one version: the Effort card and the readings built on it, the bodyweight and
per-side work from issues #31/#32/#33, and two fixes worth naming.

Versions bumped in frontend, api and the Android module (versionCode 5). CHANGELOG
gets the release heading and a Fixed section, README two feature bullets.
2026-08-01 17:07:17 +02:00
Duarte Santos 5a0345c905 Merge bodyweight: issues #31, #32, #33 2026-08-01 17:06:31 +02:00
Duarte Santos 1e86d6ace2 Config sheet: a stepper is not a list-row accessory
Added weight sat inside a list row next to its label, which is fine for a switch
and wrong for a stepper: the control took the width it needed and left the text
column wrapping one word per line. It now gets the same full-width treatment as
sets and reps, with the explanation underneath, and reuses the "Added (kg)" label
the set table already uses.

Also stops a long value overlapping its own title in a list row — flex:none meant
"Follow the routine (Linear progression)" ran straight through "Rule", since the
title's column was already free to shrink to nothing. The value shrinks and
ellipsises instead. Pre-existing, visible in every settings row with a long value.
2026-08-01 17:00:30 +02:00
Duarte Santos a5e360cde5 Settings can register on an invite-only instance too
The sign-in screen asks for an invite code when the server says it needs one. The
same registration reached from Settings never did: it collected a name, called
passkeyRegister without the second argument, and the server refused it. On an
invite-only instance that path could not succeed at all, with nothing on screen to
explain why.

It now reads /api/config and shows the code field on the same terms, reusing the
sign-in screen's own strings so nothing new needs translating.
2026-08-01 16:52:30 +02:00
Duarte Santos 00b4f543a3 Per side stays on reps work, where reps exist
Switching a per-side exercise to Time carried `side` onto the hold: the config
sheet hides the toggle in that mode but still saved the flag, and the workout
badge then halved a rep count a timed set does not have, reading "0 per side".

Dropped at all three points it could get through — the config sheet no longer
writes it outside reps mode, the badge no longer renders outside it, and the plan
serialiser refuses it on a hold so an older file cannot bring it back.
2026-08-01 16:48:57 +02:00
Duarte Santos 4afffcb248 Per side: log the total, show the split
Feedback on #31: a rep count that sometimes means one side and sometimes both is
the ambiguity, not the fix for it. So the logged number is the total — 16 — the
same as every other set in the app, and the split is derived for planning: "8 per
side" on the exercise, "3 × 16 · 8/side" on the plan line and the printed sheet.

Unilateral targets step in twos. 16 → 18 → 20, in the config stepper, the set-row
stepper and the bodyweight rep progression, because half of an odd total is a rep
one side never gets. Turning the flag on rounds an existing target up to even, and
a saved target is stored even for the same reason. An odd total that arrives some
other way still displays honestly, as 8.5 per side, since that is what it means.

Volume loses its per-side case: both sides are already in the number logged.
2026-08-01 16:47:44 +02:00
Duarte Santos c33ff15d9d Bodyweight work, logged the way it is done
A push-up has no weight to type and the app asked for one anyway, on a quarter of
the catalogue. Issues #31, #32 and #33 are the same gap seen from three sides: the
app assumed progress lived in the load.

Two flags on the exercise config rather than two new modes, because "bodyweight"
and "per side" are equally true of a rep set and a timed hold:

  bodyweight — seeded from the equipment the dataset already records. The weight
               column is gone, the set row is one stepper, and the working-weight
               prompt stops asking about a weight that was never there. A belt
               weight reads as an addition and hands progression back to the
               normal policies, because now there is something to add.
  side       — 8 logged is 8 per side. The total is spelled out where there is
               width for it, and volume counts both sides so a routine that moved
               to single-arm work no longer halves itself on the chart.

Bodyweight progression grows reps, and now sets: a rep ceiling sends the reps back
to the bottom and adds a set instead of climbing forever, stopping at six with the
advice it should have given all along. No ceiling keeps the old behaviour exactly.

Both flags are written to a plan only when they disagree with the catalogue, and
absent reads as false, so every existing plan, workout and backup is read
unchanged.
2026-08-01 16:37:52 +02:00
Duarte Santos 8de55ce0d9 Merge pull request #29 from DuarteSantos8/dependabot/npm_and_yarn/frontend/frontend-120fce7b1d
Bump react-router-dom from 7.18.1 to 7.18.2 in /frontend in the frontend group
2026-08-01 14:49:40 +01:00
Duarte Santos aefb13b544 Merge pull request #30 from DuarteSantos8/dependabot/github_actions/actions-6382876e44
Bump docker/login-action from 4.5.2 to 4.6.0 in the actions group
2026-08-01 14:49:21 +01:00
dependabot[bot] 7354b1ca0c Bump docker/login-action from 4.5.2 to 4.6.0 in the actions group
Bumps the actions group with 1 update: [docker/login-action](https://github.com/docker/login-action).


Updates `docker/login-action` from 4.5.2 to 4.6.0
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v4.5.2...v4.6.0)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 00:45:03 +00:00
dependabot[bot] f5562febca Bump react-router-dom in /frontend in the frontend group
Bumps the frontend group in /frontend with 1 update: [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom).


Updates `react-router-dom` from 7.18.1 to 7.18.2
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router-dom@7.18.2/packages/react-router-dom/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@7.18.2/packages/react-router-dom)

---
updated-dependencies:
- dependency-name: react-router-dom
  dependency-version: 7.18.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: frontend
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 00:44:33 +00:00
Duarte Santos 1f40230727 Dependabot: majors arrive on their own, and Capacitor waits
Grouping by ecosystem cut the noise, which was the point, but it also let a
Capacitor 7 → 8 migration turn up as "the frontend group, 7 updates" — six
routine siblings and one native-platform migration, indistinguishable in the
list. CI would have gone green on it too: the test workflow builds the web app
and never touches the mobile flavour, so the check would have been reassuring
about something it had not looked at.

Minor and patch stay grouped and quiet. Majors get their own PR per ecosystem,
where being alone is the signal.

Capacitor majors are ignored outright for now: Capacitor 8 declares Node >= 22
and the build host runs 20, and frontend/android and frontend/ios are committed,
so the upgrade also means migrating Gradle/AGP and the Podfile. That is a piece
of work to schedule, not a PR to merge. The comment says to drop the ignore once
the build host moves to Node 22.
2026-07-31 20:35:12 +02:00
Duarte Santos de65e1099a Merge pull request #28 from DuarteSantos8/dependabot/github_actions/actions-d8aa18c958 2026-07-31 19:30:56 +01:00
dependabot[bot] be2fb2dd1d Bump the actions group across 1 directory with 10 updates
Bumps the actions group with 10 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [actions/checkout](https://github.com/actions/checkout) | `4` | `7` |
| [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) | `3` | `4` |
| [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) | `3` | `4` |
| [docker/login-action](https://github.com/docker/login-action) | `3` | `4.5.2` |
| [docker/metadata-action](https://github.com/docker/metadata-action) | `5` | `6` |
| [docker/build-push-action](https://github.com/docker/build-push-action) | `6` | `7` |
| [actions/setup-node](https://github.com/actions/setup-node) | `4` | `7` |
| [actions/configure-pages](https://github.com/actions/configure-pages) | `5` | `6` |
| [actions/upload-pages-artifact](https://github.com/actions/upload-pages-artifact) | `3` | `5` |
| [actions/deploy-pages](https://github.com/actions/deploy-pages) | `4` | `5` |



Updates `actions/checkout` from 4 to 7
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v7)

Updates `docker/setup-qemu-action` from 3 to 4
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/v3...v4)

Updates `docker/setup-buildx-action` from 3 to 4
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v3...v4)

Updates `docker/login-action` from 3 to 4.5.2
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v3...v4.5.2)

Updates `docker/metadata-action` from 5 to 6
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/v5...v6)

Updates `docker/build-push-action` from 6 to 7
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v6...v7)

Updates `actions/setup-node` from 4 to 7
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v7)

Updates `actions/configure-pages` from 5 to 6
- [Release notes](https://github.com/actions/configure-pages/releases)
- [Commits](https://github.com/actions/configure-pages/compare/v5...v6)

Updates `actions/upload-pages-artifact` from 3 to 5
- [Release notes](https://github.com/actions/upload-pages-artifact/releases)
- [Commits](https://github.com/actions/upload-pages-artifact/compare/v3...v5)

Updates `actions/deploy-pages` from 4 to 5
- [Release notes](https://github.com/actions/deploy-pages/releases)
- [Commits](https://github.com/actions/deploy-pages/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/configure-pages
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/deploy-pages
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/setup-node
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/upload-pages-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/build-push-action
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/login-action
  dependency-version: 4.5.2
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/metadata-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/setup-buildx-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/setup-qemu-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-31 17:34:50 +00:00
Duarte Santos 611987545a Dependabot: don't chase Node majors that were never LTS
The first run offered node:22-alpine → 25-alpine in both Dockerfiles. Odd
majors are Current, not LTS, and stop getting fixes about six months in — for
an image other people self-host that trades stability for nothing. Even majors
are still proposed, so 22 → 24 will show up as a PR, which is the move actually
worth reviewing.
2026-07-31 19:32:57 +02:00
Duarte Santos accc3c1038 Sessions you can actually end, and invite codes worth guessing at
SECURITY.md documented three weaknesses two hours ago. Documented is better than
hidden; fixed is better than documented.

Sessions were a signed cookie the server trusted for a year, and /api/logout
only cleared it in the browser you clicked it in — a copy left on a shared
machine stayed good until it expired, and the only way to end it was deleting
./data/secret and signing out the entire instance. The cookie payload now
carries the user's session version, and POST /api/logout/all bumps it, which
kills every cookie that account ever had. Settings grows a "Sign out
everywhere" row for it.

Cookies already in the wild have no version field. They read as version 0 and
match a user who has never bumped, so nobody is signed out by this deploy and
db.json needs no migration — sv appears lazily on the first bump. Verified
against a server running the new code with a db.json shaped like the live one.

Session default drops from 365 days to 90, overridable with SESSION_DAYS. The
expiry is baked into each cookie when issued, so lowering it never cuts an
existing session short.

Invite codes go from 32 to 64 bits. The app has no rate limiting by design and
/api/register/options answers whether a code is valid, so the code itself has to
be the part not worth guessing. Existing codes still work — validation is an
exact string compare. Unused old ones are worth revoking and reissuing.

What did not change: no rate limiting, still the reverse proxy's job, still the
first caveat in SECURITY.md. requireUserVerification stays false — raising it
could refuse passkeys that already exist, which is a lockout, not a fix.
2026-07-31 19:32:57 +02:00
Duarte Santos 1574811af0 Wake-lock test: stop assigning to a global Node now owns
The first CI run found this, which is the point of having one. Node 21+ defines
globalThis.navigator itself as a getter with no setter, so `globalThis.navigator
= {...}` throws under ESM strict mode. This box runs Node 20, where the global
does not exist and the assignment is fine — the test has never failed locally
and never would.

Only the first test failed: its afterEach deletes the built-in accessor, so
every later test assigned cleanly against the hole it left. defineProperty works
on both runtimes.

Production images are node:22-alpine (web/Dockerfile, api/Dockerfile), so the
version CI runs is the right one and the test was what needed fixing.
2026-07-31 19:21:03 +02:00
Duarte Santos b45dbca2a6 Demo: rate the sets, so the demo shows the effort stats
The live demo is the shop window, and it was the one place the new Effort card
could not appear — demoSeed fabricated twelve weeks of training with no ratings
at all, so every chart that reads effort rendered empty or absent.

The seed now rates about 82% of finished sets, deterministically as before:
effort tracks position in the session and the block's progression, one deload
week sits well away from failure, the first three weeks are written in RPE as if
imported from another app, and one exercise stays unrated throughout so the
partial-coverage case is visible rather than theoretical. Only reps-mode sets
are rated — a reps-in-reserve number on a cardio set would be nonsense.
2026-07-31 19:12:18 +02:00
Duarte Santos 3a120df205 A security policy, and dependency updates that stay quiet
openGym ships passkeys, a signed session cookie and an admin dashboard, and
people run it on the open internet. Until now someone finding a hole had no
option but a public issue.

SECURITY.md documents the model as it actually is, verified against server.js
rather than described from memory: what the session cookie is and how long it
lasts, that it cannot be revoked individually, that ./data is unencrypted and
its holder can mint a session for any account, that there is no rate limiting,
and what changing RP_ID costs. A self-hoster deciding whether to run this for
other people deserves that list up front.

Dependabot is monthly and grouped one PR per ecosystem — a default setup on a
solo project produces noise that stops being read, which is the opposite of the
point. Android/iOS are left out on purpose: Capacitor pins those to the npm
packages, so bumping them separately breaks the mobile build.

Also: api/ has had two dependencies since notifications landed. CONTRIBUTING
still claimed one.
2026-07-31 19:12:18 +02:00
Duarte Santos 051a37abbf CI: actually run the tests, and hold the locales to one key set
There are 159 unit tests and nothing ran them. Both existing workflows fire on
push to main only, so the two outside pull requests merged so far were reviewed
by eye alone. This runs the suite, the build and a locale check on every pull
request.

The locale check exists because of a bug that shipped last week: a feature added
17 strings to de.js only, and the other ten languages fell back to English
mid-sentence with nothing failing anywhere. The checker compares every locale
against the union of all keys, so a string added to one file flags the other ten
instead of passing unnoticed.
2026-07-31 19:12:18 +02:00
Duarte Santos 8440cf3546 Changelog: the effort stats, under Unreleased
v1.2.3 is published, so this is the start of the next version rather than an
amendment to that one — it stays under Unreleased until there is a release to
fold it into.
2026-07-31 19:00:42 +02:00
Duarte Santos b0d176aba3 Merge branch 'effort-stats': the effort ratings, read back as statistics
Sets have carried an RIR/RPE rating since v1.2.3, but nothing ever read it
back — the number lived in the set label and nowhere else. This is the other
half: a trend per week, the spread across the scale, the share of sets taken
near failure, a hard-sets mode on the muscle map, and the rating riding along
on each exercise's own curve.
2026-07-31 18:49:41 +02:00
Duarte Santos 42ac8c8513 Send questions to Discussions, and put a Sponsor button on the repo
Discussions has been enabled since the start and empty since the start, so
every question arrives as an issue — the tracker is carrying design debates and
"how do I" alongside actual bugs, and the answers end up buried in closed
issues where the next person searching won't find them.

The "New issue" screen now offers Q&A, Ideas and Show-and-tell before the
templates, which is where that traffic gets intercepted; README and CONTRIBUTING
say the same thing in a table.

FUNDING.yml does nothing until the account is enrolled in GitHub Sponsors —
GitHub simply doesn't render the button. Stated plainly next to it: openGym is
AGPL, there is no paid tier and nothing is held back for sponsors. A project
that starts selling access to its maintainer stops being the thing people
starred.
2026-07-31 18:43:15 +02:00
Duarte Santos f232b5ba7e Effort stats: the other ten languages, and drop what nothing calls
The card shipped translated into German only, so every other UI language fell
back to the English source strings mid-sentence — the locale files have been
key-for-key identical until now, and they are again (607 each).

exerciseEffort() had no caller: Stats builds its per-exercise curve from the
points it already has, which are filtered by training mode, so the library
version would have drawn a different set of sessions. Removed with its tests
rather than left as a second answer to the same question.
2026-07-31 16:55:21 +02:00
Duarte Santos caaf61d91e Stats: read the effort back — trend, distribution, hard sets, per exercise
Rating a set only paid off inside the set label until now: Stats never looked at
rir/rpe at all. It reads them now, in four places.

lib/effort.js aggregates everything in RIR and converts back to whichever scale the
profile reads. A history that mixes the two — own logs in RIR, an imported file in
RPE — has to average as one series or every chart draws half the data, and RIR is the
internal unit because its zero is real where RPE's floor of 6 is a convention.

- an Effort card: average and share of sets taken near failure, the week-by-week curve
  with the week's volume in the tooltip, and where the sets land on the scale
- the muscle map gains a hard-sets mode: a muscle can lead on volume and still never
  be trained near failure
- Exercise progress carries effort on the top-set dots and as a curve of its own — the
  same weight with more left in the tank is progress a weight-only line draws flat
- LineChart learns an inverted axis (RIR counts down as it gets harder) and per-point marks

Every number carries how much of the training it speaks for: rating is optional and off
by default, so an unrated set is left out rather than read as failure, and an average
waits for five rated sets before it claims to be one.
2026-07-31 16:17:08 +02:00
Pengboi 6aaf2a3eea Comments: trim to the established cadence
The MCP code came in with 5–8 line file headers, JSDoc on every
one-line wrapper, and inline explanations that referenced the PR
itself ("so the MCP server can reuse it") — none of which matches
api/server.js or frontend/src/lib/, where comments are one-line,
fact-shaped and never mention the change that introduced them.

Trimmed across mcp/src/*.js, i18n-core.js, i18n.js, exercises.js,
format.js, mcp/test/tools.test.js, mcp/vitest.config.js and
mcp/README.md. Tool prefaces lost their numbers; duplicate fs.watch
rationale folded into one; the ASCII import diagram in the README
replaced with a paragraph; the cross-references and self-references
removed. Also fixed two real defects: a corrupted Cyrillic word in a
state.js comment and a missing space in a tools.test.js comment.

No code changes; 92 frontend + 32 MCP tests still pass.
2026-07-26 19:47:52 +01:00
Pengboi 4143ab8676 Tests: Stryker mutation testing on the MCP handlers
Adds Stryker 9.6.1 as a devDep and a .stryker.conf.json scoped to the three MCP-only
modules (src/state.js, src/labels.js, src/tools.js). The reused pure lib in
frontend/src/lib/ is deliberately excluded — it has its own 92-test vitest suite, and
mutating it here would just re-test it under a different label.

Two non-obvious config choices, both learned the hard way:
 · inPlace: true. Stryker's default copies the project to a sandbox, but the MCP test
   file imports "../../frontend/src/lib/*.js" — a relative path that breaks the moment
   the source is moved. inPlace mutates files where they live, keeps a backup in
   .stryker-tmp/backup-*/ during the run, and restores on exit. Verified: after the
   run, `git diff` shows no changes and all 92+32 tests still pass.
 · vitest.related: false. The vitest runner's related-files mode uses static import
   analysis to pick which tests to run per mutant; it can't see the cross-directory
   imports and reported "no tests were found". Disabling it means every mutant runs
   the full suite — slower (~54s for 847 mutants) but accurate.

Baseline first run: 39.32% mutation score (333 killed, 330 survived, 184 no-coverage).
Most of the survivors are zod schema string literals (the unit suite bypasses the SDK's
validation by calling handlers directly), and the bulk of the no-coverage debt lives in
state.js — file watching, multi-user resolution and the mtime fallback paths. The HTML
report at mcp/reports/mutation/mutation.html (gitignored, regenerated per run) shows
each survived mutant inline.

Run with `npm run mutation:test` from mcp/.
2026-07-26 19:34:15 +01:00
Pengboi 92914dea43 MCP: read-only stdio server for LLM apps to query workout history
A Model Context Protocol bridge that lets an external LLM application (Claude Desktop,
Cursor, Cline, Continue, …) read a user's openGym profile directly from ./data — no new
container, no extra auth, no third-party service. The LLM client spawns the server
locally as a stdio process (per the official MCP model); reads the same state-<uid>.json
the api server writes; reuses the pure training helpers from frontend/src/lib/*.js so
the numbers it answers with match what the Stats screen shows exactly.

Eight tools in v1, all read-only:
 · list_routines, get_routine — names + exercise counts + per-exercise targets
 · get_week_plan — Mo/We/Fr assignments and today's routine, accounting for any
   date-specific overrides (a "rest" override cancels the day)
 · list_workouts, get_workout — newest-first session summaries + per-set breakdown
 · get_bodyweight — weigh-ins with the goal line and signed deltas vs goal
 · estimate_1rm — Epley/Brzycki/Lombardi formulas, all-time best + trend per exercise,
   or a PR table across all reps-mode exercises
 · muscle_balance — which muscles are trained vs neglected over a week/month/all window

State is read with fs.watch (mtime fallback for platforms where watchers are flaky) so
the server reflects a session the web UI just finished without a restart. No passkey
material, VAPID keys, or session secrets ever cross the boundary — handlers only ever
serialize fields from the state object plus the user's name from db.json.

The MCP server has exactly one runtime dependency beyond the SDK: none. zod is the SDK's
transitive; vitest and Stryker are devDeps only. Tests run against the demo seed fixture
(demoSeed.js) — 32 cases pinning the JSON shape and the most user-facing edge cases
(empty state, missing routine, rest-day override, zero-workout muscle_balance, three
1RM formulas, superset links, timed/cardio set labels).
2026-07-26 19:34:09 +01:00
Pengboi fadeb17b6c i18n: split the pure core out so the lib is Node-loadable
The pure training helpers (history, progression, onerm, muscles, format, exercises) are
deliberately self-contained — that is what lets them ship with their own vitest suites and
got them reused across the React and mobile builds. They were one Vite-only call away from
being loadable from plain Node too: `import.meta.glob` for the lazy locale packs, run at the
top of i18n.js. Anything that imported `t` or `dateLocale` via the chain (i.e. every helper
in src/lib) inherited the dependency.

Splitting the runtime-agnostic state, constants and readers (t, dateLocale, instrFor, getLang,
LANGS, INSTR_LANGS, DATE_LOCALES) into i18n-core.js lets plain Node require them. i18n.js
keeps the Vite-only bits (the async setLang that lazy-loads locale packs via import.meta.glob
and the React subscription hook useLang) and re-exports everything from core, so none of the
23 existing import sites change.

exercises.js had one direct `import.meta.env` access for IMG_BASE/GIF_BASE — guarded with
`?.` so the module resolves without Vite present. format.js and exercises.js import i18n-core
directly; everything else still imports i18n.js.

No public exports changed. 92/92 vitest tests pass; vite build still code-splits the locale
packs the same way.
2026-07-26 19:34:01 +01:00
62 changed files with 6015 additions and 168 deletions

No files matched your search

+10
View File
@@ -34,6 +34,16 @@ RP_NAME=openGym
#
# INVITE_ONLY=1
# ── Session length (optional) ──────────────────────────────────────────────
# How long a sign-in lasts, in days. Default 90 — long enough that people who
# train regularly never see a login screen, short enough that a stolen cookie
# doesn't stay good forever. Lower it for an instance on the open internet,
# raise it for a private one. Only affects new sign-ins; cookies already handed
# out keep the lifetime they were issued with. Users can end every session on
# every device themselves with "Sign out everywhere" in Settings.
#
# SESSION_DAYS=90
# ── Notifications (optional) ───────────────────────────────────────────────
# Push works out of the box — nothing to set. VAPID keys are generated on first
# run and saved to ./data/vapid.json. Each user's browser reports its own
+4
View File
@@ -0,0 +1,4 @@
# Puts a "Sponsor" button on the repo header. The GitHub entry only works once the account is
# enrolled in GitHub Sponsors (github.com/sponsors — identity check, Stripe payout account and
# a tax form); until then the button is simply not shown.
github: DuarteSantos8
+11 -2
View File
@@ -1,5 +1,14 @@
blank_issues_enabled: false
contact_links:
- name: Questions & contributing
- name: Question or self-hosting help
url: https://github.com/DuarteSantos8/openGym/discussions/categories/q-a
about: Login/passkey trouble, reverse proxies, Docker, "how do I…" — ask in Q&A, not in an issue.
- name: Idea or feature request to talk through
url: https://github.com/DuarteSantos8/openGym/discussions/categories/ideas
about: Not sure it belongs in the app yet? Float it in Ideas first — issues are for agreed work.
- name: Show your setup
url: https://github.com/DuarteSantos8/openGym/discussions/categories/show-and-tell
about: Running openGym somewhere interesting, or built something on top of it? Show it off.
- name: Contributing guide
url: https://github.com/DuarteSantos8/openGym/blob/main/CONTRIBUTING.md
about: Read the project layout, dev setup, and guidelines before opening an issue.
about: Project layout, dev setup and guidelines before you open a PR.
+102
View File
@@ -0,0 +1,102 @@
# Dependency updates, deliberately quiet.
#
# openGym is dependency-light on purpose: the frontend is React + Router + Zustand, and api/
# has two runtime dependencies. A default Dependabot setup would still open a PR per package
# per week, which on a solo project means the alerts stop being read — the opposite of what
# this is for. So: monthly, everything in an ecosystem grouped into a single PR, and a low
# cap on open PRs. Security advisories are unaffected by any of this; GitHub raises those
# regardless of schedule.
#
# Only manifests that actually exist here are listed. Deliberately NOT covered:
# - gradle (frontend/android) and cocoapods (frontend/ios) — Capacitor generates those shells
# and pins the native versions to the @capacitor/* npm packages. Bumping them independently
# desyncs the two and breaks the mobile build; they follow the npm update instead.
version: 2
updates:
# Frontend app — frontend/package.json
- package-ecosystem: npm
directory: /frontend
schedule:
interval: monthly
open-pull-requests-limit: 3
groups:
# Routine bumps arrive as one PR. Runtime and build tooling move together anyway (a Vite
# bump usually wants its plugin bumped), and splitting them doubles the review without
# splitting the risk.
frontend:
patterns: ['*']
update-types: ['minor', 'patch']
# Majors get their own PR. The first grouped run bundled a Capacitor 7 → 8 migration in
# with six siblings, where it read as housekeeping — and CI would have gone green on it,
# because the test workflow builds the web app and never touches the mobile flavour. A
# major that lands alone is at least obviously a decision.
frontend-major:
patterns: ['*']
update-types: ['major']
ignore:
# Capacitor 8 needs Node >= 22 (its own `engines` field) and the build host is on 20, and
# `frontend/android` + `frontend/ios` are committed, so a major also means migrating the
# native projects — Gradle/AGP, the Podfile. That is a deliberate piece of work, not a
# dependency bump. Drop this ignore once the build host is on Node 22 and you want it.
- dependency-name: '@capacitor/*'
update-types: ['version-update:semver-major']
# Backend — api/package.json (@simplewebauthn/server, web-push)
- package-ecosystem: npm
directory: /api
schedule:
interval: monthly
open-pull-requests-limit: 3
groups:
api:
patterns: ['*']
update-types: ['minor', 'patch']
# Two dependencies, but one of them verifies passkeys — a major there is worth reading on
# its own rather than alongside anything else.
api-major:
patterns: ['*']
update-types: ['major']
# Base images — api/Dockerfile (node:22-alpine)
- package-ecosystem: docker
directory: /api
schedule:
interval: monthly
open-pull-requests-limit: 1
ignore:
# Odd-numbered Node majors are "Current", never LTS — they stop getting fixes in about
# six months. Dependabot's first run offered 22 → 25, which for something other people
# self-host is a stability downgrade for nothing. Even majors (22 → 24 → 26) still get
# proposed, which is the move actually worth reviewing.
- dependency-name: node
versions: ['25.x', '27.x', '29.x', '31.x', '33.x']
# Base images — web/Dockerfile (node:22-alpine build stage + nginx:alpine)
- package-ecosystem: docker
directory: /web
schedule:
interval: monthly
open-pull-requests-limit: 1
ignore:
- dependency-name: node
versions: ['25.x', '27.x', '29.x', '31.x', '33.x']
# Workflow actions — everything under .github/workflows/
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
open-pull-requests-limit: 2
groups:
# These are all first-party actions/* and docker/* pinned to a major tag; they update
# in lockstep and none of them is worth a PR of its own.
actions:
patterns: ['*']
update-types: ['minor', 'patch']
# Action majors are usually a runner or Node-version change and usually harmless — but
# these workflows publish the ghcr images and deploy the live demo, so the blast radius
# is real. Separate PR, so a failure has an obvious cause.
actions-major:
patterns: ['*']
update-types: ['major']
+6 -6
View File
@@ -23,22 +23,22 @@ jobs:
context: .
file: ./web/Dockerfile
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Lowercase owner (registry names must be lowercase)
id: repo
run: echo "owner=$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- uses: docker/setup-qemu-action@v4
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v3
- uses: docker/login-action@v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/metadata-action@v5
- uses: docker/metadata-action@v6
id: meta
with:
images: ghcr.io/${{ steps.repo.outputs.owner }}/opengym-${{ matrix.image }}
@@ -47,7 +47,7 @@ jobs:
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- uses: docker/build-push-action@v6
- uses: docker/build-push-action@v7
with:
context: ${{ matrix.context }}
file: ${{ matrix.file }}
+5 -5
View File
@@ -30,8 +30,8 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
@@ -44,8 +44,8 @@ jobs:
VITE_DEMO: '1'
VITE_IMG_BASE: ${{ env.DATASET }}/images/
VITE_GIF_BASE: ${{ env.DATASET }}/videos/
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
- uses: actions/configure-pages@v6
- uses: actions/upload-pages-artifact@v5
with:
path: frontend/dist
@@ -57,4 +57,4 @@ jobs:
url: ${{ steps.deploy.outputs.page_url }}
steps:
- id: deploy
uses: actions/deploy-pages@v4
uses: actions/deploy-pages@v5
+65
View File
@@ -0,0 +1,65 @@
# Runs on pull requests too — the other two workflows only fire on push to main, so
# contributed changes used to reach main without anything ever having been run.
name: Tests
on:
pull_request:
paths:
- 'frontend/**'
- 'mcp/**'
- '.github/workflows/test.yml'
push:
branches: [main]
paths:
- 'frontend/**'
- 'mcp/**'
- '.github/workflows/test.yml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: test-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
# node:22-alpine in web/Dockerfile and api/Dockerfile — CI must match production.
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
- run: npm ci
working-directory: frontend
- run: npm test
working-directory: frontend
# A broken import or bad JSX fails the build long before any test covers it.
- run: npm run build
working-directory: frontend
- run: node scripts/check-locales.mjs
working-directory: frontend
mcp:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
cache-dependency-path: mcp/package-lock.json
- run: npm ci
working-directory: mcp
- run: npm test
working-directory: mcp
# The one check the vitest suite structurally cannot make. The MCP server is a bare node
# process, but vitest runs its tests through Vite — import.meta.glob, .jsx imports and
# ?raw all resolve happily there. That is how a Vite-only import reached a shared lib
# module with 33 green tests standing over a server that died on startup.
- run: npm run check:node-loadable
working-directory: mcp
+112
View File
@@ -1,5 +1,117 @@
# Changelog
## v1.2.5 — 2026-08-04
Nothing in the app itself changed. This release adds an optional side door: a small server that
lets an AI assistant you already run — Claude Desktop, Cursor, Cline — answer questions about
your own training, off the same files your instance already writes. If you don't use one, this
release is invisible to you.
### Ask an AI about your training, without the data leaving your box (#19)
- 🤖 **An MCP server (`mcp/`)** — opt-in, read-only, and not part of the Docker build. Your LLM
client spawns it as a local process, it reads `./data` directly, and it exits when the client
disconnects. No new container, no extra auth on the api, no third-party service, nothing over
the network. *"What did I bench last week?", "what's my estimated 1RM on deadlift?", "which
muscles have I been neglecting?"*
- **The answers match the Stats screen because they are the same numbers.** The server calls the
very functions in `frontend/src/lib/` the app already computes with, rather than reimplementing
them. Eight tools: routines, the week plan, workouts, one session in detail, body weight,
estimated 1RM and muscle balance.
- **Read-only on purpose.** Logging a workout from an assistant needs a long-lived token the api
does not have yet, plus a lock against the web UI's read-modify-write. Until both exist, the
server answers questions and does nothing else. It never reads passkey material, VAPID keys or
session state — only the profile it was pointed at.
- `docker-compose.yml` is untouched and nothing new enters the image, so an instance that ignores
this ships exactly what it shipped before. Setup is in [mcp/README.md](mcp/README.md).
### Under the hood
- The pure half of `i18n.js` — the language state, the constants, the readers — moved into
`i18n-core.js`, so the helpers under `frontend/src/lib/` can be loaded by a plain Node process
and not only by Vite. `i18n.js` keeps the Vite-only parts (the locale-pack loader, the React
hook) and re-exports the rest, so nothing that imports it had to change.
- The shared lib modules that only need `t` now take it from the core directly. A Vite-only
import inside a shared module is invisible under vitest, which transforms it, and fatal to the
MCP server, which does not — so the shared half stays clear of the bundler half by
construction rather than by remembering to.
- `npm run check:node-loadable` in `mcp/` walks the server's import graph under a bare `node`,
which is the one thing the test suite cannot do from inside Vite. CI runs it, alongside the
MCP tests — neither had ever run there before.
The MCP server was contributed by [@Pengboi](https://github.com/Pengboi) — the first feature in
openGym written by someone other than me. Thank you.
## v1.2.4 — 2026-08-01
The effort ratings you have been recording since v1.2.3 now answer questions, and bodyweight
training stops being treated as barbell training with the weight left at zero. Plus: creating a
profile from Settings works on an invite-only instance, which it never has.
### The effort ratings, read back as statistics
v1.2.3 let you rate how hard a set was. Nothing then read that rating back — it lived in the set
label and nowhere else. Stats now answers the question the number was recorded for.
- 📊 **An Effort card in Stats** over 30d / 90d / 1Y / all time: average effort, the share of sets
taken close to failure, and — always alongside them — how much of your training was rated at
all. Rating is optional and off by default, so a partly rated history is normal; an average
without its denominator would quietly speak for sets you never rated.
- **Week by week.** The weekly average with that week's set count in the tooltip, because the
pair is the reading: volume up with effort up is fatigue accumulating, volume up with effort
flat is the adaptation you were training for. Weeks resting on a single rated set are dropped
rather than drawn.
- **Where the sets land.** The spread across the scale, not just the middle of it. Half your sets
at failure and half in warm-up territory average out to a healthy-looking number; this is the
chart that shows it.
- 🔥 **Hard-sets mode on the muscle map.** The same body diagram, counting only sets taken near
failure — "where did the stimulus go" rather than "where did the volume go". A muscle can lead
on set count and still never be trained hard.
- **Effort on the exercise curve.** Each session's dot on the top-set chart fills in as less is
left in the tank, so the same weight moved with more in reserve stops reading as a flat line.
Exercises with enough ratings also get an Effort curve of their own.
- **One history, whichever scale you use.** Everything aggregates internally in RIR and converts
back for display, so a history that mixes your own RIR logs with imported RPE averages as one
series instead of two half-empty ones. RIR charts count downward on the axis, so harder sets
sit higher.
- Translated into all 12 UI languages.
### Bodyweight training, logged the way it is done
A push-up has no weight to type, and the app asked for one anyway — every set, on a quarter of
the catalogue. Three reports (#31, #32, #33) turned out to be the same gap: the app assumed
progress lived in the load. It doesn't, for the exercises most people actually start with.
- 💪 **Exercises know they are bodyweight.** Seeded from the equipment the dataset already
records, so push-ups, pull-ups, dips and 300-odd others arrive marked. The weight column is
not shown, the set row is one stepper instead of two, and the "confirm your working weight"
prompt at the end of an exercise stops asking about a weight that was never there. (#32)
- **Added weight when there is any.** A dip belt or a weighted vest is entered once in the
exercise settings and reads as an addition — "+10 × 8", not "10×8" — everywhere it is shown
back. With load on the belt the normal progression rules take over again, because now there
is something to add.
- 📈 **Reps and sets are the progression.** Clean session, one more rep. Set a top of the range
and reaching it adds a set and starts the reps over instead of climbing forever; at six sets
it says what it should have said all along, which is that it is time for weight or a harder
variation. No ceiling set keeps the old behaviour exactly. (#33)
- ↔️ **Reps per side.** For lunges, single-arm rows and every other unilateral movement. You
log what you did — 16, the total — and the app shows the split, "8 per side", so the set in
front of you is unambiguous without the rep count meaning one thing here and another there.
The target steps in twos, 16 → 18 → 20, because half of an odd total is a rep one side never
gets. (#31)
- Both settings travel with a shared plan, and are written to a plan file only when they
disagree with the catalogue — every existing plan, workout and backup is read unchanged and
none of it needs migrating.
- Translated into all 12 UI languages.
### Fixed
- **Creating a profile from Settings on an invite-only instance.** The sign-in screen asks for
the invite code when the server needs one; the same registration reached from Settings never
did, so it was refused with nothing on screen explaining why. It now asks on the same terms.
- **A long value no longer runs through its own label** in a settings row — "Follow the routine
(Linear progression)" overlapped "Rule" rather than shortening itself.
## v1.2.3 — 2026-07-31
How hard a set was, in whichever of the two scales you already think in — and the ratings your
+17 -1
View File
@@ -12,6 +12,9 @@ api/ backend — server.js (Node, no framework), one dependency (@simplewe
web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf (serves app, proxies /api).
media/ exercise img/gif (gitignored, fetched at runtime).
docs/ self-hosting guide.
mcp/ optional Model Context Protocol server — read-only stdio bridge for LLM apps
(Claude Desktop, Cursor, …) to query a user's workouts/1RM/muscle balance. Not in
the Docker build; only runs when an LLM client spawns it. See mcp/README.md.
```
## Running for development
@@ -28,7 +31,8 @@ cd frontend && npm test
## Guidelines
- **Keep it dependency-light.** The frontend uses React + Router + Zustand and nothing else;
new deps (front or back) are a hard sell. `api/` has exactly one dependency — keep it that way.
new deps (front or back) are a hard sell. `api/` has two (`@simplewebauthn/server` for passkeys,
`web-push` for notifications) — keep it near that.
- **Match the style.** Small components, clear names, comments only where the "why" isn't obvious.
State lives in the Zustand store (`src/store`); pure helpers in `src/lib`.
- **Don't commit** the exercise media (`media/`) or `data/` — they're gitignored.
@@ -47,6 +51,18 @@ cd frontend && npm test
`src/lib/progression.js` — the policy interface is already there
- Accessibility passes on the workout and chart screens
## Where to ask what
| You have | Goes to |
| --- | --- |
| A question, or self-hosting that won't behave | [Discussions → Q&A](https://github.com/DuarteSantos8/openGym/discussions/categories/q-a) |
| An idea you're not sure about yet | [Discussions → Ideas](https://github.com/DuarteSantos8/openGym/discussions/categories/ideas) |
| A reproducible bug | [Issues](https://github.com/DuarteSantos8/openGym/issues) |
| A change you've already built | A pull request |
An answered question in Q&A is worth more than the same answer buried in a closed issue — the
next person searching "passkey login fails behind my reverse proxy" actually finds it.
## Reporting bugs
Open an issue with: what you did, what you expected, what happened, and your browser/OS. If it's
+23
View File
@@ -66,6 +66,8 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 📈 **Progression that follows a rule** — pick one per routine, override it per exercise: linear, **Greyskull LP** (AMRAP top set, double jumps, 10 % resets), double progression through a rep range, or adding time. Your weights are already right when the session opens, and every target says *why* it's that number. Missed reps never advance the load, stalls trigger a deload, and bodyweight exercises progress in reps instead
- 💪 **Estimated 1RM** — per exercise, from your best eligible set (it names which one), with its own progress curve and a calculator for sets you haven't done. Won't guess above 12 reps
- 🎯 **Effort per set, in your scale** — an optional third column rating how hard a set was, as **RIR** (reps left in the tank) or **RPE** (the same judgement on a 10-point scale). Off by default; each set keeps the scale it was logged with, and nothing else reads the value — your progression and 1RM are unaffected
- 💪 **Bodyweight exercises, logged as bodyweight** — push-ups, pull-ups, dips and 300-odd others arrive knowing they carry no load, so there's no weight column and no working-weight prompt: one stepper, log the reps. Add a dip belt and it reads as an addition, and progression goes back to following the weight. Without one, reps climb — and past a ceiling you set, a set is added instead of a rep, up to the point where the honest advice is load or a harder variation
- ↔️ **Reps per side** — for lunges, single-arm rows and the rest. You log the total, the app shows the split ("8 per side"), and the target steps in twos so it never lands on a number one side can't have
- 🏃 **Cardio** — log time + speed, not just weight × reps
- 📤 **Share a plan** — send someone your routines and week schedule as a small file (no workouts, no weigh-ins), or print it as a clean PDF. Importing merges, so their plan is never overwritten
- 🔧 **Filter by equipment** — narrow the library to what you actually own; the options adapt to what you've picked, so every combination on screen has results behind it
@@ -79,6 +81,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 🌍 **12 languages** — full UI translation (EN, DE, ES, FR, IT, PT, PL, TR, RU, ZH, KO, HI); exercise instructions localized in 10 of them, loaded on demand so the app stays fast
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy**, or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped
- 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry**
- 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there
- 📱 **Standalone Android app** — the whole tracker as a sideloadable APK: no account, no server, data on the phone, native workout reminders ([download](https://opengym.duarte-santos.ch))
## Quick start (self-host)
@@ -182,11 +185,31 @@ lives in pure functions under `frontend/src/lib/` with tests next to them: `npm
`frontend/`. Vitest is a dev dependency; the app itself ships no runtime dependencies beyond
React, the router and Zustand.
The same pure helpers power an optional MCP server (`mcp/`) that lets an LLM client like
Claude Desktop read your data over stdio — see [mcp/README.md](mcp/README.md). Opt-in, not
in the Docker build.
## Community
- **[Q&A](https://github.com/DuarteSantos8/openGym/discussions/categories/q-a)** — self-hosting
help, passkey/login trouble, "how do I…". Most login problems turn out to be an `RP_ID`/`ORIGIN`
mismatch.
- **[Ideas](https://github.com/DuarteSantos8/openGym/discussions/categories/ideas)** — features
worth talking through before anyone writes code.
- **[Show and tell](https://github.com/DuarteSantos8/openGym/discussions/categories/show-and-tell)**
— your setup, your plan templates, whatever you built on top.
- **[Issues](https://github.com/DuarteSantos8/openGym/issues)** — bugs, and work that's already
been agreed on.
## Contributing
Issues and PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Good first issues: more starter
plans, exercise-data languages, import from other trackers. **A ⭐ helps more people find it.**
openGym is free and stays free: AGPL, no subscription, no paid tier, nothing held back for
sponsors. If it replaced a paid tracker for you and you want to chip in, the Sponsor button at the
top of the page is there — a star, a bug report or a PR is worth just as much.
## License
[GNU AGPL v3.0](LICENSE) — free and open source. You can self-host, use, modify and share it;
+149
View File
@@ -0,0 +1,149 @@
# Security policy
openGym is a self-hosted app: you run the server, you hold the data. This file says which
versions get fixes, how to report something privately, and — the part most people actually
need — what the app protects you from and what it doesn't.
## Supported versions
Only the **latest release**. Releases are semver tags (`v1.0.0` → `v1.2.3`, see
[CHANGELOG.md](CHANGELOG.md)); there is no LTS or maintenance branch and older tags are never
patched. A fix ships in the next release and in the `latest` images on ghcr.io.
Updating a self-hosted instance:
```bash
git pull && docker compose pull && docker compose up -d
```
## Reporting a vulnerability
Use GitHub's private vulnerability reporting — repo **Security** tab → **Report a vulnerability**:
<https://github.com/DuarteSantos8/openGym/security/advisories/new>
> Private reporting has to be switched on in the repository settings for that link to work
> (Settings → Advanced Security → Private vulnerability reporting). If it 404s, open a normal
> issue saying only *"I need a private channel for a security report"* — no details, no repro —
> and it will be enabled.
Please don't put a working exploit in a public issue if it can be used against other people's
instances. Everything else (a crash you can only trigger on your own box, a scanner warning)
is fine as a normal issue.
Useful in a report: the version or commit, whether you're running the prebuilt images or a
source build, your `RP_ID`/`ORIGIN` and what sits in front of the app, steps to reproduce, and
what an attacker gets out of it.
**On response times:** this is a hobby project maintained by one person alongside school. There
is no SLA and no bounty. Expect days rather than hours, and longer during exam periods. If a
week goes by with no reply, comment on the advisory thread — it's more likely to be a missed
notification than a decision. If a report goes unfixed and you want to disclose publicly, say so
in the thread; there's no objection, and no request to sit on it indefinitely.
## In scope
- **`api/server.js`** — forging or replaying a session cookie, bypassing passkey verification,
reading or writing another user's data through `/api/data`, reaching `/api/admin/*` without
being an admin, or creating a profile without a valid code while `INVITE_ONLY=1`.
- **Frontend** — XSS in the React app, or anything that lets a page on another origin read or
change a signed-in user's data.
- **Shipped deployment config** — `docker-compose.yml`, `web/nginx.conf`, the two Dockerfiles:
a default that exposes something a self-hoster wouldn't expect to be exposed.
- **The published images** `ghcr.io/duartesantos8/opengym-api` and `-web`.
## Out of scope
- Anything that already assumes access to the host, to `./data`, or to the Docker socket. The
operator is trusted by design — see the security model below.
- Admins reading their users' workout history. That is the documented purpose of the admin
dashboard, not a leak.
- **Missing rate limiting**, brute force, or "I sent 100k requests and it got slow". The app
has no rate limiting at all and doesn't pretend to; that belongs in the reverse proxy you put
in front of it. Genuine amplification (one small request causing unbounded work) *is* in scope.
- **Missing security headers** (CSP, HSTS, X-Frame-Options) — `web/nginx.conf` sets none; TLS
and headers are the reverse proxy's job. A concrete attack that headers would have stopped is
still worth reporting.
- Instances served over plain `http://` on a LAN IP. Unsupported: passkeys don't work there and
the session cookie isn't marked `Secure`.
- Scanner output with no working exploit, and `npm audit` findings in build-time
devDependencies (Vite, Vitest, Capacitor CLI) that never reach a running instance.
- The GitHub Pages demo build — it has no backend at all, everything stays in that browser.
- Third-party content: the exercise image/GIF dataset and the CDN it's fetched from.
## Security model
Read this before hosting openGym for anyone other than yourself.
### What it does
- **Passkeys only.** No passwords, no email addresses, no reset flow. Registration and login are
verified server-side by `@simplewebauthn/server` against `expectedOrigin: ORIGIN` and
`expectedRPID: RP_ID`, and the authenticator's signature counter is stored and updated on every
login (`api/server.js:292-318`, `api/server.js:338-358`).
- **Sessions are a signed cookie.** `gymsid` carries `<uid>:<expiry>:<version>` plus an
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:148-161`). The key is 32
random bytes generated on first run and written to `./data/secret` with mode `0600`
(`api/server.js:34-36`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
when `ORIGIN` starts with `https:`** (`api/server.js:29`, `api/server.js:198-201`).
- **Any user can end every session they have.** `POST /api/logout/all` increments that account's
session version, and every authenticated request checks the version in the cookie against the
one on the user record (`api/server.js:167`, `api/server.js:187-188`), so every cookie ever
issued for the account — on every device, including a copy someone walked off with — stops
verifying at once. Passkeys are untouched; signing back in works immediately.
- **Data is isolated per user by the session's uid.** `GET`/`PUT /api/data` only ever touch
`state-<uid>.json` for the caller (`api/server.js:375-392`); no route lets a normal user name
another user.
- **Disabling an account takes effect immediately.** Every authenticated request and every login
is rejected for a disabled user (`api/server.js:184`, `api/server.js:357`).
### What it does not do
- **Nothing in `./data` is encrypted.** It holds `db.json` (users, passkey public keys, push
subscriptions, invite codes), one `state-<uid>.json` per user with their complete workout
history and body-weight log, `secret`, and `vapid.json`. Anyone who can read that folder — you,
whoever holds the backups, whoever gets into the host — can read every user's data, and with
`secret` can mint a valid session cookie for any account. **If you host openGym for other
people, they are trusting you exactly as much as they'd trust any server operator.**
- **Admins can read everything.** A user listed in `ADMIN_UIDS` (or flagged `admin: true` in
`db.json`) gets every user's full history and body weight, can disable accounts, and can create
or revoke invite codes (`api/server.js:460-540`). Off by default — a fresh instance has no admin.
- **Sessions can't be revoked one device at a time.** Revocation is per *account*, not per
session: `POST /api/logout/all` kills all of them at once and there is no device list to pick
from. `POST /api/logout` on its own only clears the cookie in that one browser
(`api/server.js:361`) — a copy taken beforehand keeps working. Sessions last **90 days** by
default, settable with `SESSION_DAYS` (`api/server.js:26`); each cookie carries the lifetime it
was issued with, so changing the setting doesn't reach cookies that are already out. Deleting
`./data/secret` and restarting still works as the instance-wide reset, and disabling an account
still locks out one user completely.
- **CSRF protection is `SameSite=Lax` and nothing else.** There are no CSRF tokens.
- **User verification is preferred, not required.** Both handshakes pass
`requireUserVerification: false` (`api/server.js:297`, `api/server.js:343`), so a passkey
released without a biometric or PIN is still accepted. In practice: unlocked device ≈ account
access.
- **One passkey per profile, and no recovery.** Every successful registration creates a *new*
profile (`api/server.js:309-319`); there is no route to attach a second passkey to an existing
one, and no email or reset path. Lose the passkey and that profile is unreachable — only direct
surgery on `./data` gets it back.
- **Disabling someone isn't a ban.** They can still register a fresh profile with a new passkey
unless `INVITE_ONLY=1` is set.
- **HTTPS is required and the app doesn't provide it.** The API container speaks plain HTTP and
nginx listens on `:80` (`web/nginx.conf`); TLS is your reverse proxy's job. Without it,
browsers won't do passkeys at all (except on `http://localhost`) and the session cookie is sent
in the clear.
- **No rate limiting anywhere.** Nothing throttles logins, registrations or writes, and
`POST /api/register/options` still answers whether an invite code is valid
(`api/server.js:272`), so an invite-only instance on the open internet should have a rate limit
in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:525`) — which
makes guessing one impractical even unthrottled; codes generated by earlier versions are 8
characters / 32 bits and still work, so revoke and reissue any that are still unused. The only
hard limit
in the app is a 5 MB request body (`api/server.js:27`).
- **A few endpoints answer without a session:** `/api/health` (which includes the total user
count), `/api/config` (whether invite-only is on), `/api/push/public-key`, and the
register/login handshakes.
- **Changing `RP_ID` invalidates every existing passkey.** They were bound to the old hostname
and will fail verification against the new one. The data stays on disk but is unreachable until
each user registers again — as a *new* profile. Choose your hostname before anyone registers.
- **Guest mode never reaches the backend.** That data lives unencrypted in the browser's
`localStorage` and is gone when the browser storage is cleared.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gym-api",
"version": "1.2.3",
"version": "1.2.5",
"private": true,
"type": "module",
"main": "server.js",
+41 -10
View File
@@ -19,7 +19,11 @@ const RP_NAME = process.env.RP_NAME || 'openGym';
// code the admin generates. Both default off so a fresh self-hosted instance stays open.
const ADMIN_UIDS = (process.env.ADMIN_UIDS || '').split(',').map(s => s.trim()).filter(Boolean);
const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || '');
const SESSION_DAYS = 365;
// 90 days keeps someone who trains a few times a week permanently signed in without a stolen
// cookie staying good for a year. Overridable because a family instance and one on the open
// internet don't want the same number. Only affects cookies minted from now on — the expiry is
// baked into each cookie when it's issued, so lowering this never cuts an existing session short.
const SESSION_DAYS = Math.max(1, +(process.env.SESSION_DAYS || 90) || 90);
const MAX_BODY = 5 * 1024 * 1024;
// Secure cookies require HTTPS; over plain http://localhost the flag would drop the cookie
const SECURE = /^https:/i.test(ORIGIN) ? ' Secure;' : '';
@@ -155,9 +159,15 @@ function verifySig(token) {
} catch { return null; }
return payload;
}
function makeSession(uid) {
// Session payload is `<uid>:<expiry>:<version>`, where the version is the user's `sv` counter.
// Bumping `sv` (POST /api/logout/all) makes every cookie ever handed out for that account stop
// verifying, which is the only revocation there was before short of deleting ./data/secret and
// signing out the whole instance. Cookies minted before `sv` existed have no third field and are
// read as version 0, matching a user who has never bumped — they stay valid until they expire.
const sessionVersion = user => user.sv || 0;
function makeSession(user) {
const exp = Date.now() + SESSION_DAYS * 86400000;
return sign(uid + ':' + exp);
return sign(user.id + ':' + exp + ':' + sessionVersion(user));
}
function readSession(req) {
const cookies = Object.fromEntries((req.headers.cookie || '').split(';').map(c => {
@@ -167,10 +177,15 @@ function readSession(req) {
if (!tok) return null;
const payload = verifySig(tok);
if (!payload) return null;
const [uid, exp] = payload.split(':');
const [uid, exp, ver] = payload.split(':');
if (!uid || +exp < Date.now()) return null;
const user = db.users.find(u => u.id === uid) || null;
if (user && user.disabled) return null; // disabled accounts are locked out everywhere
if (!user) return null;
if (user.disabled) return null; // disabled accounts are locked out everywhere
// Missing third field = pre-versioning cookie = version 0. Anything non-numeric is a malformed
// payload (it still had to pass the HMAC, so this is belt-and-braces) and is refused outright.
const claimed = ver === undefined ? 0 : Number(ver);
if (!Number.isInteger(claimed) || claimed !== sessionVersion(user)) return null;
return user;
}
// Guard for /api/admin/* — resolves the caller and 401/403s if they aren't an admin.
@@ -180,8 +195,8 @@ function requireAdmin(req, res) {
if (!isAdmin(user)) { json(res, 403, { error: 'forbidden' }); return null; }
return user;
}
function sessionCookie(uid) {
return `gymsid=${makeSession(uid)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
function sessionCookie(user) {
return `gymsid=${makeSession(user)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
}
const clearCookie = `gymsid=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
@@ -301,7 +316,7 @@ const routes = {
transports: body.credential?.response?.transports || []
});
saveDb();
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
},
'POST /api/login/options': async (req, res) => {
@@ -340,11 +355,23 @@ const routes = {
const user = db.users.find(u => u.id === cred.userId);
if (!user) return json(res, 500, { error: 'user missing' });
if (user.disabled) return json(res, 403, { error: 'this account has been disabled' });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
},
'POST /api/logout': async (req, res) => json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }),
// "Sign out everywhere" — bumps this user's session version, which invalidates every cookie
// ever issued for the account, on every device, including a copy someone else walked off with.
// The caller's own cookie is cleared here too, so the browser doing it doesn't sit on a token
// it no longer accepts. Passkeys are untouched: signing back in works immediately.
'POST /api/logout/all': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
user.sv = sessionVersion(user) + 1;
saveDb();
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
},
'GET /api/data': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
@@ -491,7 +518,11 @@ const routes = {
const admin = requireAdmin(req, res); if (!admin) return;
const body = await readBody(req);
let code;
do { code = crypto.randomBytes(4).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
// 16 hex chars = 64 bits, up from 8 chars / 32 bits. The app has no rate limiting by design
// (that's the reverse proxy's job) and /api/register/options tells a caller whether a code is
// good, so the code itself has to be the thing that isn't worth guessing. Codes already in
// db.json keep working — validation is an exact string compare, never a length or format check.
do { code = crypto.randomBytes(8).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
db.invites.push(invite);
saveDb();
+2 -2
View File
@@ -7,8 +7,8 @@ android {
applicationId "ch.duartesantos.opengym"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 4
versionName "1.2.3"
versionCode 6
versionName "1.2.5"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
+15 -11
View File
@@ -1,12 +1,12 @@
{
"name": "opengym-frontend",
"version": "1.2.3",
"version": "1.2.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opengym-frontend",
"version": "1.2.3",
"version": "1.2.5",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/core": "^7.6.8",
@@ -15,7 +15,7 @@
"@capacitor/share": "^7.0.4",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1",
"react-router-dom": "^7.18.2",
"zustand": "^5.0.14"
},
"devDependencies": {
@@ -2504,6 +2504,7 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
"license": "MIT",
"engines": {
"node": ">=18"
},
@@ -4757,9 +4758,10 @@
}
},
"node_modules/react-router": {
"version": "7.18.1",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.1.tgz",
"integrity": "sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg==",
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.2.tgz",
"integrity": "sha512-aUVMjFm3GAPTTZL7oYr5E7ETiqfQCHRLH+B+5afnICvf0r7kkK4eR6SMuwbSTJw/7t+12khT/Kahij49fqOCIg==",
"license": "MIT",
"dependencies": {
"cookie": "^1.0.1",
"set-cookie-parser": "^2.6.0"
@@ -4778,11 +4780,12 @@
}
},
"node_modules/react-router-dom": {
"version": "7.18.1",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.1.tgz",
"integrity": "sha512-KaZh+X/6UtEp28x51AUYZDMg9NGoz2ja3dNHa+ta/tk40vCzKhQ/RypCWBMLbmDr6//E24Vv5uPsrqXFozdkAg==",
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.2.tgz",
"integrity": "sha512-AIKJ/jgGlFb3EbfCXk5Gzshiwt+l3mqbCrNjmEWMMjqQxNJ3svBa6bgzFyCC2Sw3RA0VWF1kg3uQf2OFhxb8hw==",
"license": "MIT",
"dependencies": {
"react-router": "7.18.1"
"react-router": "7.18.2"
},
"engines": {
"node": ">=20.0.0"
@@ -5201,7 +5204,8 @@
"node_modules/set-cookie-parser": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
"license": "MIT"
},
"node_modules/sharp": {
"version": "0.32.6",
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.2.3",
"version": "1.2.5",
"type": "module",
"scripts": {
"dev": "vite",
@@ -19,7 +19,7 @@
"@capacitor/share": "^7.0.4",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.1",
"react-router-dom": "^7.18.2",
"zustand": "^5.0.14"
},
"devDependencies": {
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env node
// Guards the one invariant every locale in src/locales/ shares: the same key set.
// English is the source language and has no locale file, so a key that exists in only
// some locales falls back to English silently, mid-sentence, with nothing failing
// anywhere. This catches that at review time instead of in the app.
//
// node scripts/check-locales.mjs
//
// The reference is the union of all locales, not one blessed file: a key added to a
// single locale then flags the other ten instead of passing unnoticed.
import { readdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const localesDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'locales')
const files = readdirSync(localesDir).filter(f => f.endsWith('.js')).sort()
if (!files.length) {
console.error(`No locale files found in ${localesDir}`)
process.exit(1)
}
const locales = new Map()
for (const file of files) {
const { default: dict } = await import(pathToFileURL(join(localesDir, file)).href)
if (!dict || typeof dict !== 'object') {
console.error(`${file}: no default-exported object`)
process.exit(1)
}
locales.set(file.replace(/\.js$/, ''), new Set(Object.keys(dict)))
}
// How many locales carry each key — 1 means the key was added to a single file only,
// which is the usual shape of the bug and worth naming separately from plain gaps.
const seen = new Map()
for (const keys of locales.values()) for (const k of keys) seen.set(k, (seen.get(k) || 0) + 1)
const union = [...seen.keys()]
let failed = false
for (const [lang, keys] of locales) {
const missing = union.filter(k => !keys.has(k))
const orphans = union.filter(k => keys.has(k) && seen.get(k) === 1)
if (missing.length || orphans.length) {
failed = true
console.error(`\n${lang}.js: ${keys.size}/${union.length} keys`)
for (const k of missing) console.error(` missing: ${JSON.stringify(k)}`)
for (const k of orphans) console.error(` only here: ${JSON.stringify(k)}`)
}
}
if (failed) {
console.error('\nLocale key sets differ. Every locale must carry the same keys.')
process.exit(1)
}
console.log(`${locales.size} locales, ${union.length} keys each — in sync.`)
+18 -5
View File
@@ -4,8 +4,15 @@ import { t } from '../lib/i18n.js'
const W = 340 // viewBox width; the svg stretches to its container, height comes from `h`
// points: [{ t: ms, y: num, d?: iso }] sorted by t. opts: { h, unit, color, axes, goal }
export default function LineChart({ points, h = 150, unit = '', color = 'var(--acc)', axes = true, goal = null }) {
// points: [{ t: ms, y: num, d?: iso, m?: 0..1, note?: str }] sorted by t.
// m marks the point — a second reading carried by the same dot (bigger and more solid =
// more of it). Used for effort on the weight curve, where the two belong on one line:
// the same weight with less left in the tank is not the same session.
// note extra text for that point's tooltip.
// opts: { h, unit, color, axes, goal, invert }
// invert flips the y axis, for a scale that counts down as it gets harder (RIR). Without it
// a curve of reps-in-reserve reads upside down, with the hardest sets at the floor.
export default function LineChart({ points, h = 150, unit = '', color = 'var(--acc)', axes = true, goal = null, invert = false }) {
const svgRef = useRef(null)
const wrapRef = useRef(null)
const tipRef = useRef(null)
@@ -42,7 +49,10 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
const pad = (ymax - ymin) * 0.12; ymin -= pad; ymax += pad
const t0 = pts[0].t, t1 = pts[pts.length - 1].t || t0 + 1
const X = t => (t1 === t0 ? (P.l + W - P.r) / 2 : P.l + (t - t0) / (t1 - t0) * (W - P.l - P.r))
const Y = y => P.t + (1 - (y - ymin) / (ymax - ymin)) * (H - P.t - P.b)
const Y = y => {
const f = (y - ymin) / (ymax - ymin)
return P.t + (invert ? f : 1 - f) * (H - P.t - P.b)
}
const gridlines = []
if (axes) {
@@ -81,7 +91,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
const poly = pts.map(p => X(p.t).toFixed(1) + ',' + Y(p.y).toFixed(1)).join(' ')
const last = pts[pts.length - 1]
const gid = 'g' + Math.round(t0 % 1e7) + '_' + H
const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y }))
const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y, note: p.note }))
const marked = points.some(p => p.m != null)
const onMove = e => {
const c = e.touches ? e.touches[0] : e
@@ -111,6 +122,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
</>}
<polygon points={`${P.l},${H - P.b} ${poly} ${X(last.t).toFixed(1)},${H - P.b}`} fill={`url(#${gid})`} />
<polyline points={poly} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
{marked && pts.map((p, i) => (p.m == null ? null :
<circle key={'m' + i} cx={X(p.t)} cy={Y(p.y)} r={2.4 + p.m * 3} fill={color} opacity={0.3 + p.m * 0.7} />))}
<circle cx={X(last.t)} cy={Y(last.y)} r="4" fill={color} />
{hover && <g>
<line className="cvl" x1={hover.x} y1={P.t} x2={hover.x} y2={H - P.b} stroke="var(--label-3)" strokeWidth="1" strokeDasharray="3 3" />
@@ -119,7 +132,7 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
</g>}
</svg>
{hover && <div className="ctip" ref={tipRef}>
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}{hover.note ? ' · ' + hover.note : ''}
</div>}
</div>
)
+8 -1
View File
@@ -233,7 +233,11 @@ h4.sec{
.lrow-m{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}
.lrow-t{font-size:17px;letter-spacing:-.012em;line-height:1.25}
.lrow-s{font-size:13px;color:var(--label-2);line-height:1.3}
.lrow-v{color:var(--label-2);font-size:17px;letter-spacing:-.012em;flex:none}
/* flex:none would let a long value ("Follow the routine (Linear progression)") run straight
through the title next to it, since the title's column is already free to shrink to nothing.
Letting the value shrink and ellipsise instead keeps the two out of each other's way. */
.lrow-v{color:var(--label-2);font-size:17px;letter-spacing:-.012em;flex:0 1 auto;min-width:0;
overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:right}
.lrow-c{color:var(--label);font-size:15px;flex:none;--icon-stroke:2.4}
.lrow-k{color:var(--acc);font-size:17px;flex:none;--icon-stroke:2.4}
.lrow.danger,.lrow.danger .lrow-t{color:var(--red)}
@@ -784,6 +788,9 @@ h4.sec{
.mrow .bar{width:74px;height:5px;border-radius:3px;background:var(--surface-2);flex:none;overflow:hidden}
.mrow .bar i{display:block;height:100%;background:var(--acc);border-radius:3px}
.mrow .v{font-size:12px;color:var(--label-2);min-width:52px;text-align:right;flex:none}
/* A headline number inside a card — tile weight without a tile around it, for the pair of
readings at the top of the effort card. */
.stat-v{font-size:26px;font-weight:600;letter-spacing:-.026em;line-height:1.1}
.mchips{display:flex;flex-wrap:wrap;gap:6px;margin-top:4px}
.mchip{font-size:12px;padding:4px 9px;border-radius:99px;background:var(--surface-2);color:var(--label-2)}
.mchip.miss{background:color-mix(in srgb,var(--orange) 16%,transparent);color:var(--orange)}
+58 -5
View File
@@ -2,6 +2,7 @@
// out of the bundle self-hosters ship.
import { isoOf, uid } from './format.js'
import { starterRoutines } from './starter.js'
import { modeOf } from './history.js'
// Starting weight and weekly increment per exercise of the starter plan (kg).
// Chest dips are body-weight only here, so they log reps at 0 added weight.
@@ -14,6 +15,30 @@ const WEEKS = 12 // how much history to fabricate
const BW_FROM = 82.4, BW_TO = 78.3 // body-weight trend across those weeks
const TARGET_W = 77
// --- Effort -----------------------------------------------------------------------------
// The demo has to show the effort stats, not just the volume ones, so the history carries
// ratings. Flat ratings would draw a flat trend and prove nothing, so this fabricates the
// shape the charts exist to make visible: a block grinding toward failure, a deload jumping
// back off it, another block going a little deeper than the first.
const DELOAD_WEEK = 5
// Reps left in the tank the block is aiming for, by week.
const weekTarget = wk =>
wk === DELOAD_WEEK ? 4.5
: wk < DELOAD_WEEK ? 2.8 - wk * 0.3
: 2.6 - (wk - DELOAD_WEEK - 1) * 0.26
// Leg day is trained further from failure than the upper body — deliberate, so the muscle
// map's "hard sets" mode shows a different picture from its all-sets mode.
const EASY = new Set(['0043', '0085', '0739', '0585', '0586'])
// One exercise nobody ever rates: partial coverage is the normal case (rating is optional and
// off by default), and it shows the per-exercise Effort toggle correctly staying away.
const NEVER_RATED = '0605'
const UNRATED = 0.1 // …plus this share of the remaining sets, at random
// The first weeks are logged in RPE, as if they came out of another app before the profile
// switched to RIR. A set is never rewritten (see history.js), so the stats have to average a
// mixed history as one series — the demo should be showing that, not hiding it.
const RPE_UNTIL = 3
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
// Deterministic PRNG — the demo should look the same on every visit and in screenshots.
function rng(seed) {
let a = seed >>> 0
@@ -26,9 +51,14 @@ function rng(seed) {
}
const round = (w, step) => Math.round(w / step) * step
const at = (date, h, m) => { const d = new Date(date); d.setHours(h, m, 0, 0); return d.getTime() }
// The Monday of a date. The effort trend is plotted per calendar week, so the training block
// has to run on calendar weeks too — a deload counted off the first day of the history would
// straddle two points and average itself away in both.
const monday = date => { const d = new Date(date); d.setDate(d.getDate() - ((d.getDay() + 6) % 7)); d.setHours(12, 0, 0, 0); return +d }
// A full example profile: 12 weeks of Mon/Wed/Fri sessions on the starter plan, with linear
// progression, the odd missed session, and twice-weekly weigh-ins trending toward the goal.
// progression, the odd missed session, twice-weekly weigh-ins trending toward the goal, and
// per-set effort ratings on most (not all) of it.
export function buildDemoState() {
const rnd = rng(20260723)
const [push, pull, legs] = starterRoutines()
@@ -61,15 +91,35 @@ export function buildDemoState() {
if (iso === isoOf(today) && nowH < 18) continue // leave today's session to try out, unless it's already evening
const prs = []
const entries = routine.ex.map(cfg => {
const blockWk = Math.round((monday(day) - monday(start)) / (7 * 86400000))
const rir0 = weekTarget(blockWk)
const scale = blockWk < RPE_UNTIL ? 'rpe' : 'rir'
const entries = routine.ex.map((cfg, exIdx) => {
const [base, inc] = PROG[cfg.id] || [20, 0.5]
const step = base >= 40 ? 2.5 : 1.25
const w = base ? Math.max(step, round(base + inc * weekIdx, step)) : 0
// The deload pulls the weight back too — effort dropping on its own would look like the
// same session suddenly got easy.
const back = blockWk === DELOAD_WEEK ? 0.88 : 1
const w = base ? Math.max(step, round((base + inc * weekIdx) * back, step)) : 0
const rateable = modeOf(cfg) === 'reps' && cfg.id !== NEVER_RATED
const sets = []
for (let i = 0; i < cfg.sets; i++) {
// last set is where reps usually start slipping
const drop = i === cfg.sets - 1 && rnd() < 0.55 ? (rnd() < 0.4 ? 2 : 1) : 0
sets.push({ w, r: Math.max(4, cfg.reps - drop), done: true })
const s = { w, r: Math.max(4, cfg.reps - drop), done: true }
const rir = clamp(round(rir0
+ (cfg.sets - 1 - i) * 0.6 // a first set sits further from failure than a last
- exIdx * 0.12 // …and fatigue accumulates across the session
+ (EASY.has(cfg.id) ? 1.2 : 0)
- (drop ? 0.5 : 0) // reps slipping is the set that ran out of room
+ (rnd() - 0.5), 0.5), 0, 6)
if (rateable && rnd() > UNRATED) {
// RPE's floor of 6 is a convention about which sets are worth rating, so an easy
// set logged in RPE genuinely loses the distance it was from failure.
if (scale === 'rpe') s.rpe = clamp(10 - rir, 6, 10)
else s.rir = rir
}
sets.push(s)
}
if (w > (best[cfg.id] || 0)) { best[cfg.id] = w; prs.push(cfg.id) }
exWeights[cfg.id] = { w: Math.max(w, exWeights[cfg.id]?.w || 0), d: iso }
@@ -103,6 +153,9 @@ export function buildDemoState() {
week: { 1: push.id, 3: pull.id, 5: legs.id },
dayPlan,
workouts, bodyweight, exWeights,
targetW: TARGET_W
targetW: TARGET_W,
// The history is rated, so the demo turns the column on and the stats get a scale to
// label their aggregates with instead of guessing one (see displayScale).
effort: 'rir'
}
}
+109
View File
@@ -0,0 +1,109 @@
// The demo build is the only openGym most people ever see, so its seeded history has to
// exercise the stats it is there to show off — including the effort card, which renders as
// dashes on a history that is rated too thinly or not at all.
import { describe, it, expect } from 'vitest'
import { buildDemoState } from './demoSeed.js'
import {
effortSummary, effortWeeks, effortHistogram, hasEffort, displayScale, avgRir,
rirOf, isHardSet, MIN_RATED, HARD_RIR
} from './effort.js'
import { effortOf, modeOf } from './history.js'
const S = buildDemoState()
const eachSet = fn => S.workouts.forEach(w => w.entries.forEach(e => e.sets.forEach(s => fn(s, w, e))))
const sum = effortSummary(S, 0) // 0 = the whole history
describe('demo seed — effort', () => {
it('rates enough of the history to clear every guard in the effort stats', () => {
expect(hasEffort(S)).toBe(true)
expect(sum.done).toBeGreaterThan(400)
expect(sum.rated).toBeGreaterThan(MIN_RATED * 20)
expect(sum.avg).not.toBeNull()
expect(sum.hardPct).not.toBeNull()
// Somewhere between "everything is a grinder" and "nothing ever gets close".
expect(sum.hardPct).toBeGreaterThan(0.3)
expect(sum.hardPct).toBeLessThan(0.9)
})
it('leaves coverage partial, because that is the normal case the UI states a denominator for', () => {
const cov = sum.rated / sum.done
expect(cov).toBeGreaterThan(0.7)
expect(cov).toBeLessThan(0.95)
})
it('never rates a set that has no reps to leave in the tank', () => {
eachSet((s, w, e) => {
if (rirOf(s) != null) expect(modeOf({ ...(e.target || {}), id: e.id })).toBe('reps')
})
})
it('leaves one exercise unrated throughout, so the per-exercise Effort toggle is absent for it', () => {
const rated = {}
eachSet((s, w, e) => { rated[e.id] = (rated[e.id] || 0) + (rirOf(s) != null ? 1 : 0) })
const ids = Object.keys(rated)
expect(ids.filter(id => rated[id] === 0)).toEqual(['0605'])
// …while the rest carry enough rated sessions for a curve of their own (needs 3).
ids.filter(id => id !== '0605').forEach(id => {
const sessions = S.workouts.filter(w => {
const en = w.entries.find(e => e.id === id)
return en && avgRir(en.sets.filter(s => s.done)) != null
})
expect(sessions.length).toBeGreaterThanOrEqual(3)
})
})
it('labels the aggregates in the scale the profile logs', () => {
expect(effortOf(S)).toBe('rir')
expect(displayScale(S)).toBe('rir')
// The oldest block is written in RPE, as if imported — the stats have to average the mix.
let rir = 0, rpe = 0
eachSet(s => { if (s.rir != null) rir++; else if (s.rpe != null) rpe++ })
expect(rir).toBeGreaterThan(0)
expect(rpe).toBeGreaterThan(0)
})
it('draws a weekly trend with a point for every week of the history', () => {
const wks = effortWeeks(S, 0)
expect(wks.length).toBeGreaterThanOrEqual(10)
wks.forEach(w => { expect(w.n).toBeGreaterThanOrEqual(2); expect(w.sets).toBeGreaterThanOrEqual(w.n) })
// Sorted oldest first, one point per calendar week.
expect(wks.map(w => w.t)).toEqual([...wks.map(w => w.t)].sort((a, b) => a - b))
expect(new Set(wks.map(w => w.t)).size).toBe(wks.length)
})
it('makes the deload visible as a genuinely easier week', () => {
const wks = effortWeeks(S, 0)
const easiest = wks.reduce((a, b) => (b.rir > a.rir ? b : a))
const rest = wks.filter(w => w !== easiest)
const restAvg = rest.reduce((a, w) => a + w.rir, 0) / rest.length
expect(easiest.rir - restAvg).toBeGreaterThan(1) // a step, not noise
// and the blocks around it grind toward failure rather than sitting flat
const hardest = wks.reduce((a, b) => (b.rir < a.rir ? b : a))
expect(easiest.rir - hardest.rir).toBeGreaterThan(1.5)
expect(hardest.t).toBeGreaterThan(easiest.t) // the deepest week comes after it
})
it('spreads across the scale instead of piling onto one bucket', () => {
const hist = effortHistogram(S, 0)
expect(hist.reduce((n, b) => n + b.n, 0)).toBe(sum.rated)
expect(hist.filter(b => b.pct > 0.05).length).toBeGreaterThan(2)
expect(Math.max(...hist.map(b => b.pct))).toBeLessThan(0.6)
// both ends occupied: sets taken to (or near) failure and sets left well short of it
expect(hist[0].n + hist[1].n).toBeGreaterThan(0)
expect(hist[hist.length - 1].n).toBeGreaterThan(0)
})
it('has hard sets to filter the muscle map by', () => {
let hard = 0
eachSet(s => { if (isHardSet(s)) hard++ })
expect(hard).toBe(sum.hard)
expect(hard).toBeGreaterThan(50)
eachSet(s => { if (isHardSet(s)) expect(rirOf(s)).toBeLessThanOrEqual(HARD_RIR) })
})
it('is deterministic — two builds produce the same ratings', () => {
const b = buildDemoState()
const flat = st => st.workouts.map(w => w.entries.map(e => e.sets.map(s => `${s.w}x${s.r}/${s.rir ?? ''}/${s.rpe ?? ''}`).join(',')).join('|')).join(';')
expect(flat(b)).toBe(flat(S))
})
})
+139
View File
@@ -0,0 +1,139 @@
// Effort as a statistic: one internal scale, both display scales.
//
// A set carries either `rir` or `rpe` and is never rewritten — switching the setting changes
// what new sets ask for, nothing else (see history.js). For a *chart* that is a problem: a
// history that mixes the two (own logs in RIR, an imported file in RPE) would draw two
// half-empty series. So everything aggregates in RIR and is converted back for display.
// RIR is the internal unit because it has a real zero — a set taken to failure — where RPE's
// floor of 6 is only a convention about which sets are worth rating. RPE 8 == RIR 2.
import { EFFORT, effortOf } from './history.js'
import { weekKey } from './format.js'
// At or below this a set is close enough to failure to be the kind that drives adaptation.
// 3 rather than 2: the line is a convention, and drawn one rep too generously it still
// separates working sets from the ones left in the warm-up range.
export const HARD_RIR = 3
// Below this many rated sets an average is noise. Showing "RIR 1.0" off a single set reads
// like a finding when it is one tap, so the callers show a dash instead.
export const MIN_RATED = 5
/** A set's effort in RIR, or null when it was never rated. 0 is a rating, not "empty". */
export const rirOf = s =>
!s ? null : s.rir != null ? s.rir : s.rpe != null ? 10 - s.rpe : null
/** RIR → the scale being displayed. The reverse of rirOf, for one number. */
export const toScale = (kind, rir) =>
rir == null ? null : Math.round((kind === 'rpe' ? 10 - rir : rir) * 10) / 10
/**
* Which scale to *label* aggregates with. The profile's own setting wins; a profile that
* logs nothing itself but carries rated history (the imported-from-Hevy case) is shown the
* scale that history is actually written in, rather than an RIR it has never seen.
*/
export function displayScale(S) {
const k = effortOf(S)
if (EFFORT[k]) return k
let rir = 0, rpe = 0
eachDoneSet(S, s => { if (s.rir != null) rir++; else if (s.rpe != null) rpe++ })
return rpe > rir ? 'rpe' : 'rir'
}
export const scaleName = kind => EFFORT[kind].hd
// Every finished set in the profile, oldest first. `fn` gets the set plus the workout it
// belongs to, which is what the windowed and per-week views need.
function eachDoneSet(S, fn) {
;(S.workouts || []).forEach(w =>
(w.entries || []).forEach(e =>
(e.sets || []).forEach(s => { if (s.done) fn(s, w, e) })))
}
// A window in days, counted back from now. 0 = everything, which is also what an empty
// history means for every caller here.
const inWindow = (w, days) =>
!days || (w.start || new Date(w.d).getTime()) > Date.now() - days * 86400000
export const avgRir = sets => {
const vs = (sets || []).map(rirOf).filter(v => v != null)
return vs.length ? vs.reduce((a, b) => a + b, 0) / vs.length : null
}
/**
* The headline numbers for a window: how hard, how much of it was hard, and — the part that
* keeps the rest honest — how much of the training was rated at all. Effort is optional and
* off by default, so partial coverage is the normal case; an average without its denominator
* would quietly speak for sets that were never rated.
*/
export function effortSummary(S, days) {
let done = 0, rated = 0, sum = 0, hard = 0
eachDoneSet(S, (s, w) => {
if (!inWindow(w, days)) return
done++
const r = rirOf(s)
if (r == null) return
rated++; sum += r
if (r <= HARD_RIR) hard++
})
return {
done, rated, hard,
avg: rated >= MIN_RATED ? sum / rated : null,
hardPct: rated >= MIN_RATED ? hard / rated : null
}
}
/** Does this profile hold any rated set at all? Decides whether the effort UI exists. */
export function hasEffort(S) {
let any = false
eachDoneSet(S, s => { if (!any && rirOf(s) != null) any = true })
return any
}
/**
* Average effort per calendar week, with the week's set count alongside: the pair is the
* point. Volume up with effort up is fatigue accumulating; volume up with effort flat is the
* adaptation you were training for. Weeks with a single rated set are dropped rather than
* drawn — one tap should not become a peak in the curve.
*/
export function effortWeeks(S, days) {
const wk = new Map()
eachDoneSet(S, (s, w) => {
if (!inWindow(w, days)) return
const k = weekKey(w.d)
let e = wk.get(k)
if (!e) wk.set(k, e = { k, t: mondayOf(w.d), sum: 0, n: 0, sets: 0 })
e.sets++
const r = rirOf(s)
if (r != null) { e.sum += r; e.n++ }
})
return [...wk.values()].filter(e => e.n >= 2).sort((a, b) => a.t - b.t)
.map(e => ({ t: e.t, rir: e.sum / e.n, n: e.n, sets: e.sets }))
}
// The Monday of an ISO date, as ms — the x position a week's point sits at.
function mondayOf(iso) {
const d = new Date(iso + 'T12:00:00')
d.setDate(d.getDate() - ((d.getDay() + 6) % 7))
d.setHours(12, 0, 0, 0)
return +d
}
/**
* How the rated sets spread across the scale, in whole steps with everything past the top
* bucket collapsed into it. This is the chart that answers "am I training too far from
* failure, or leaving nothing for the next session" — an average alone hides both, because
* half the sets at 0 and half at 4 average to a healthy-looking 2.
*/
export const BUCKETS = 4 // 0,1,2,3 and a "4+" tail
export function effortHistogram(S, days) {
const bins = new Array(BUCKETS + 1).fill(0)
let rated = 0
eachDoneSet(S, (s, w) => {
if (!inWindow(w, days)) return
const r = rirOf(s)
if (r == null) return
rated++
bins[Math.min(BUCKETS, Math.max(0, Math.floor(r)))]++
})
return bins.map((n, i) => ({ rir: i, tail: i === BUCKETS, n, pct: rated ? n / rated : 0 }))
}
/** A set that counts as hard — the filter behind the muscle map's "hard sets" mode. */
export const isHardSet = s => { const r = rirOf(s); return r != null && r <= HARD_RIR }
+175
View File
@@ -0,0 +1,175 @@
import { describe, it, expect } from 'vitest'
import {
rirOf, toScale, displayScale, avgRir, effortSummary, hasEffort, effortWeeks,
effortHistogram, isHardSet, HARD_RIR, MIN_RATED
} from './effort.js'
import { isoOf } from './format.js'
const daysAgo = n => { const d = new Date(); d.setDate(d.getDate() - n); return d }
// One workout on a day, with the sets given. Everything here is a finished set unless a set
// says otherwise, because that is what the stats read.
const W = (n, sets) => {
const d = daysAgo(n)
return { id: 'w' + n, d: isoOf(d), start: +d, entries: [{ id: '0025', sets: sets.map(s => ({ w: 60, r: 8, done: true, ...s })) }] }
}
const S = (...workouts) => ({ workouts })
describe('rirOf', () => {
it('reads RIR straight and RPE as its mirror — RPE 8 is RIR 2', () => {
expect(rirOf({ rir: 2 })).toBe(2)
expect(rirOf({ rpe: 8 })).toBe(2)
expect(rirOf({ rpe: 9.5 })).toBe(0.5)
})
it('keeps a rated 0 and rejects everything that only looks like one', () => {
expect(rirOf({ rir: 0 })).toBe(0) // taken to failure — a rating, not "empty"
expect(rirOf({ rpe: 10 })).toBe(0)
expect(rirOf({})).toBe(null)
expect(rirOf({ rir: null })).toBe(null)
expect(rirOf(null)).toBe(null)
})
it('prefers the scale the set itself was logged on when a file wrote both', () => {
expect(rirOf({ rir: 3, rpe: 9 })).toBe(3)
})
})
describe('toScale', () => {
it('converts back to whichever scale is on screen', () => {
expect(toScale('rir', 2)).toBe(2)
expect(toScale('rpe', 2)).toBe(8)
expect(toScale('rpe', 0)).toBe(10)
expect(toScale('rir', null)).toBe(null)
})
it('does not let the round trip produce float dust', () => {
expect(toScale('rpe', 10 - 7.5)).toBe(7.5)
})
})
describe('displayScale', () => {
it('follows the profile setting when it has one', () => {
expect(displayScale({ effort: 'rpe', workouts: [] })).toBe('rpe')
expect(displayScale({ effort: 'rir', workouts: [] })).toBe('rir')
})
it('shows an unrated profile the scale its imported history is written in', () => {
// Effort off, but a file brought RPE with it: labelling that history "RIR" would show a
// number the profile has never entered and mean the opposite of what it says.
expect(displayScale({ effort: 'none', ...S(W(3, [{ rpe: 8 }, { rpe: 9 }])) })).toBe('rpe')
expect(displayScale({ effort: 'none', ...S(W(3, [{ rir: 2 }])) })).toBe('rir')
expect(displayScale({ effort: 'none', workouts: [] })).toBe('rir')
})
})
describe('avgRir', () => {
it('averages the rated sets and ignores the rest', () => {
expect(avgRir([{ rir: 1 }, { rir: 3 }])).toBe(2)
expect(avgRir([{ rir: 1 }, {}, { rpe: 7 }])).toBe(2) // RPE 7 = RIR 3
})
it('is null rather than 0 when nothing was rated', () => {
expect(avgRir([{}, { rir: null }])).toBe(null)
expect(avgRir([])).toBe(null)
expect(avgRir(null)).toBe(null)
})
})
describe('effortSummary', () => {
const st = S(
W(2, [{ rir: 1 }, { rir: 3 }, { rir: 2 }]),
W(4, [{ rir: 0 }, { rpe: 6 }, {}]), // RPE 6 = RIR 4, one set unrated
W(40, [{ rir: 5 }, { rir: 5 }])
)
it('counts rated sets against every finished set, not against itself', () => {
const r = effortSummary(st, 0)
expect(r.done).toBe(8)
expect(r.rated).toBe(7)
})
it('leaves unrated sets out of the average instead of reading them as failure', () => {
const r = effortSummary(S(W(2, [{ rir: 4 }, {}, {}, {}, {}, {}])), 0)
expect(r.rated).toBe(1)
expect(r.avg).toBe(null) // one rating is not an average
})
it('waits for a real sample before reporting a number', () => {
const few = S(W(2, new Array(MIN_RATED - 1).fill({ rir: 2 })))
expect(effortSummary(few, 0).avg).toBe(null)
const enough = S(W(2, new Array(MIN_RATED).fill({ rir: 2 })))
expect(effortSummary(enough, 0).avg).toBe(2)
})
it('counts the sets taken close to failure', () => {
const r = effortSummary(st, 0)
expect(r.hard).toBe(4) // 1, 3, 2, 0 — the 4 and the two 5s are not
expect(r.hardPct).toBeCloseTo(4 / 7)
})
it('honours the window', () => {
const r = effortSummary(st, 7)
expect(r.rated).toBe(5) // the 40-day-old session is out
expect(effortSummary(st, 3).rated).toBe(3)
})
it('survives a profile with no training at all', () => {
expect(effortSummary({ workouts: [] }, 30)).toEqual({ done: 0, rated: 0, hard: 0, avg: null, hardPct: null })
})
})
describe('hasEffort', () => {
it('decides whether the effort UI exists at all', () => {
expect(hasEffort(S(W(2, [{ rir: 0 }])))).toBe(true)
expect(hasEffort(S(W(2, [{ rpe: 8 }])))).toBe(true)
expect(hasEffort(S(W(2, [{}, { rir: null }])))).toBe(false)
expect(hasEffort({ workouts: [] })).toBe(false)
})
it('ignores sets that were never finished', () => {
expect(hasEffort(S(W(2, [{ rir: 2, done: false }])))).toBe(false)
})
})
describe('effortWeeks', () => {
it('averages per calendar week and carries the week volume alongside', () => {
const pts = effortWeeks(S(W(1, [{ rir: 1 }, { rir: 3 }, {}])), 0)
expect(pts).toHaveLength(1)
expect(pts[0].rir).toBe(2)
expect(pts[0].n).toBe(2) // rated
expect(pts[0].sets).toBe(3) // trained
})
it('drops a week that rests on a single tap', () => {
expect(effortWeeks(S(W(1, [{ rir: 1 }])), 0)).toEqual([])
})
it('comes back oldest first, whatever order the workouts arrived in', () => {
const pts = effortWeeks(S(W(2, [{ rir: 1 }, { rir: 1 }]), W(30, [{ rir: 3 }, { rir: 3 }])), 0)
expect(pts.map(p => p.rir)).toEqual([3, 1])
expect(pts[0].t).toBeLessThan(pts[1].t)
})
})
describe('effortHistogram', () => {
it('bins by whole steps and collapses the far end into a tail', () => {
const h = effortHistogram(S(W(2, [{ rir: 0 }, { rir: 1.5 }, { rir: 4 }, { rir: 7 }])), 0)
expect(h.map(b => b.n)).toEqual([1, 1, 0, 0, 2])
expect(h[4].tail).toBe(true)
expect(h[0].pct).toBe(0.25)
})
it('is all zeroes, not NaN, when nothing is rated', () => {
const h = effortHistogram(S(W(2, [{}])), 0)
expect(h.every(b => b.n === 0 && b.pct === 0)).toBe(true)
})
})
describe('isHardSet', () => {
it('draws the line at the effort that actually drives adaptation', () => {
expect(isHardSet({ rir: HARD_RIR })).toBe(true)
expect(isHardSet({ rir: HARD_RIR + 0.5 })).toBe(false)
expect(isHardSet({ rpe: 10 })).toBe(true)
expect(isHardSet({})).toBe(false) // unrated is not hard, and not easy either
})
})
+13 -4
View File
@@ -1,5 +1,5 @@
import { EXDB } from './exercises-data.js'
import { t } from './i18n.js'
import { t } from './i18n-core.js'
export { EXDB }
export const EXIDX = {}
@@ -28,15 +28,24 @@ export const allExercises = st => [...(st.customEx || []), ...EXDB]
// Media normally sits next to the app (img/ and gif/, mounted into the web container).
// A build can point them somewhere else — the demo build pulls them off a CDN instead of
// shipping ~140 MB of images into the deployment.
const IMG_BASE = import.meta.env.VITE_IMG_BASE || 'img/'
const GIF_BASE = import.meta.env.VITE_GIF_BASE || 'gif/'
// shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain
// Node; the guard keeps this module loadable without Vite.
const ENV = import.meta.env || {}
const IMG_BASE = ENV.VITE_IMG_BASE || 'img/'
const GIF_BASE = ENV.VITE_GIF_BASE || 'gif/'
export const imgSrc = ex => IMG_BASE + ex.img
export const gifSrc = ex => GIF_BASE + ex.gif
// Cardio exercises log time + speed instead of weight × reps.
export const isCardio = idOrEx => (typeof idOrEx === 'string' ? EXIDX[idOrEx] : idOrEx)?.bp === 'cardio'
// Exercises the dataset already knows carry no external load (issue #32) — a quarter of the
// catalogue. This seeds the `bw` flag on a fresh config so a push-up never asks for a weight
// nobody was going to enter. It is only the default: the flag lives on the config, so a dip
// done with a belt can turn it off and a custom exercise can turn it on.
export const isBodyweightEq = idOrEx =>
(typeof idOrEx === 'string' ? EXIDX[idOrEx] : idOrEx)?.eq === 'body weight'
// An id that resolves to nothing — a plan file built against a different exercise dataset,
// a custom exercise deleted on another device before the sync arrived — still has to
// render. A placeholder keeps it visible (and removable) instead of taking the whole view
+1 -1
View File
@@ -1,5 +1,5 @@
// Formatting + date helpers (ported from the vanilla app, unit taken from the store where needed).
import { dateLocale, t } from './i18n.js'
import { dateLocale, t } from './i18n-core.js'
export const todayISO = () => {
const d = new Date()
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
+52 -7
View File
@@ -1,6 +1,11 @@
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
import { isCardio } from './exercises.js'
import { isCardio, isBodyweightEq } from './exercises.js'
// i18n-core, not i18n: this file is imported by mcp/, which is plain Node with no Vite and no
// React. i18n.js is the Vite half — import.meta.glob over the locale packs, useSyncExternalStore
// for the hook — and it re-exports this very `t` from core, so nothing changes here except what
// gets dragged along behind it.
import { t } from './i18n-core.js'
// How an exercise is logged (issue #16). This used to be derived from the body part alone,
// which meant a plank or a farmer's carry could only be timed by filing it under cardio.
@@ -17,6 +22,28 @@ export function modeOf(cfg) {
}
export const isTimed = cfg => modeOf(cfg) === 'time'
// Two flags that ride on top of a mode rather than making new ones (issues #31/#32), because
// "bodyweight" and "per side" are true of a rep set and of a timed hold alike:
// bodyweight — the exercise carries no load of its own, so `w` means *added* weight and is
// asked for only once you say there is some. Seeded from the equipment field.
// Spelled out rather than `bw`, which a workout already uses for the weigh-in
// it was logged at — two different things one letter apart is a bug waiting.
// side — the exercise is unilateral. You still log what you did: 16, the total across
// both sides. The split is derived for planning ("8 per side"), never entered
// — a number that sometimes means one side and sometimes both is the thing
// that made this ambiguous in the first place, and one rep count that always
// means the same thing beats two that need a legend.
// Both are absent on every plan, workout and backup written before they existed, and absent
// reads as false, so nothing needs migrating.
export const isBw = cfg => (cfg && cfg.bodyweight != null ? !!cfg.bodyweight : isBodyweightEq(cfg && cfg.id))
export const isPerSide = cfg => !!(cfg && cfg.side)
// What one side did, for display only. Half of an odd total is shown as it falls (8.5) rather
// than rounded away: it means the sides were not even, which is worth seeing.
export const sideReps = reps => (reps || 0) / 2
// Unilateral work moves in pairs, so its rep target steps by two — 16, 18, 20 — and a total
// that stayed odd would put a rep on one side and not the other.
export const repStep = cfg => (isPerSide(cfg) ? 2 : 1)
// mm:ss for a work duration — seconds alone read badly past a minute ("90 s" vs "1:30").
export function fmtSec(sec) {
const n = Math.max(0, Math.round(Number(sec) || 0))
@@ -69,27 +96,43 @@ const effortTail = s => {
// One-line summary of a logged set. `cfg` carries the mode when the caller has it (a routine
// entry or a workout entry); passing an id alone keeps the old body-part behaviour.
export function setLabel(id, s, cfg) {
const mode = modeOf(cfg || { id })
const c = cfg || { id }
const mode = modeOf(c)
if (mode === 'cardio') return `${s.min || 0} min @ ${fmtNum(s.speed || 0)} km/h`
if (mode === 'time') return fmtSec(s.sec) + (s.w > 0 ? ` · ${fmtNum(s.w)}` : '')
return `${fmtNum(s.w || 0)}×${s.r || 0}` + effortTail(s)
// Bodyweight reads as what you did — "12", or "+10 × 12" once there is a belt involved —
// rather than "0×12", which says a set was performed with no weight and means nothing.
// A per-side set needs no mark here: the number logged is the total, the same as every
// other set in the app.
const reps = s.r || 0
if (isBw({ ...c, id: c.id ?? id })) {
const load = s.w > 0 ? `+${fmtNum(s.w)} × ` : ''
return `${load}${reps}` + effortTail(s)
}
return `${fmtNum(s.w || 0)}×${reps}` + effortTail(s)
}
// Default config for a freshly added exercise.
export function defaultConfig(id, mode) {
const m = mode || modeOf({ id })
if (m === 'cardio') return { sets: 1, min: 20, speed: 8 }
if (m === 'time') return { sets: 3, sec: 45, weight: 0, mode: 'time' }
return { sets: 3, reps: 10, weight: 0, mode: 'reps' }
// Written only when it is true, so a barbell config is byte-for-byte what it was before
// the flag existed and a plan file gains nothing it does not need.
const bw = isBodyweightEq(id) ? { bodyweight: true } : {}
if (m === 'time') return { sets: 3, sec: 45, weight: 0, mode: 'time', ...bw }
return { sets: 3, reps: 10, weight: 0, mode: 'reps', ...bw }
}
// One-line summary of a planned exercise ("3 × 10 · 60 kg"), shared by the routine editor
// and the plan export so a mode is described the same way everywhere.
export function exLine(cfg, unit) {
const mode = modeOf(cfg)
const n = cfg.sets || 1
const load = cfg.weight ? ' · ' + fmtNum(cfg.weight) + ' ' + unit : ''
// Added weight reads as added: "+10 kg" on a dip belt, "60 kg" on a barbell.
const load = cfg.weight ? ' · ' + (isBw(cfg) ? '+' : '') + fmtNum(cfg.weight) + ' ' + unit : ''
if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h`
if (mode === 'time') return `${n} × ${fmtSec(cfg.sec || 45)}${load}`
return `${n} × ${cfg.reps}${load}`
// This is the line with room for it, so the split is spelled out: "3 × 16 · 8/side".
const split = isPerSide(cfg) ? ' · ' + t('{0}/side', fmtNum(sideReps(cfg.reps))) : ''
return `${n} × ${cfg.reps}${load}${split}`
}
// Drop superset ids that no longer have an adjacent partner (after unlink/reorder/remove).
@@ -166,6 +209,8 @@ export function buildSets(S, cfg) {
}
export function workoutVolume(w) {
let v = 0
// No special case for unilateral work: a per-side set logs its total, so both sides are
// already in the rep count that arrives here.
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0) }))
return v
}
+79 -2
View File
@@ -1,10 +1,13 @@
import { describe, it, expect } from 'vitest'
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, exLine, workoutVolume, effortOf, stepEffort, capEffort } from './history.js'
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep } from './history.js'
import { EXDB } from './exercises.js'
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
const CARDIO = EXDB.find(e => e.bp === 'cardio').id
const LIFT = EXDB.find(e => e.bp !== 'cardio').id
// A *loaded* lift: the catalogue's first non-cardio entry is a sit-up, which since issue #32
// defaults to bodyweight and would quietly send every label test down the other path.
const LIFT = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id
const BW = EXDB.find(e => e.eq === 'body weight').id
describe('modeOf', () => {
it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => {
@@ -255,9 +258,73 @@ describe('defaultConfig', () => {
expect(defaultConfig(CARDIO)).toEqual({ sets: 1, min: 20, speed: 8 })
expect(defaultConfig(LIFT, 'time')).toEqual({ sets: 3, sec: 45, weight: 0, mode: 'time' })
})
it('seeds the bodyweight flag from the catalogue, and only when it is true', () => {
expect(defaultConfig(BW)).toEqual({ sets: 3, reps: 10, weight: 0, mode: 'reps', bodyweight: true })
expect(defaultConfig(BW, 'time')).toEqual({ sets: 3, sec: 45, weight: 0, mode: 'time', bodyweight: true })
expect('bodyweight' in defaultConfig(LIFT)).toBe(false)
})
})
/* ---------- bodyweight and per side (issues #31/#32/#33) ---------- */
describe('isBw', () => {
it('defaults from the catalogue so an existing plan needs no flag', () => {
expect(isBw({ id: BW })).toBe(true)
expect(isBw({ id: LIFT })).toBe(false)
})
it('lets the config win in both directions — a belt on a dip, a flag on a machine', () => {
expect(isBw({ id: BW, bodyweight: false })).toBe(false)
expect(isBw({ id: LIFT, bodyweight: true })).toBe(true)
})
})
describe('sideReps', () => {
it('halves the logged total, because the total is what was logged', () => {
expect(sideReps(16)).toBe(8)
expect(sideReps(0)).toBe(0)
})
it('shows an odd total as it falls rather than rounding the imbalance away', () => {
expect(sideReps(17)).toBe(8.5)
})
})
describe('exLine — per side never reaches a timed hold', () => {
it('ignores a stale side flag on a hold, which has no reps to split', () => {
expect(exLine({ id: LIFT, sets: 3, sec: 45, mode: 'time', side: true }, 'kg')).toBe('3 × 0:45')
})
})
describe('repStep', () => {
it('steps unilateral work in twos so the total stays splittable', () => {
expect(repStep({ side: true })).toBe(2)
expect(repStep({})).toBe(1)
expect(repStep(null)).toBe(1)
})
})
describe('setLabel — bodyweight', () => {
it('reads as reps alone, because "0×12" describes nothing', () => {
expect(setLabel(BW, { w: 0, r: 12 }, { id: BW })).toBe('12')
})
it('spells out a belt as an addition', () => {
expect(setLabel(BW, { w: 10, r: 8 }, { id: BW })).toBe('+10 × 8')
})
it('logs a per-side set as the plain total, like every other set in the app', () => {
expect(setLabel(BW, { w: 0, r: 16 }, { id: BW, side: true })).toBe('16')
expect(setLabel(LIFT, { w: 20, r: 16 }, { id: LIFT, side: true })).toBe('20×16')
})
it('keeps the effort tail', () => {
expect(setLabel(BW, { w: 0, r: 12, rir: 2 }, { id: BW })).toBe('12 (RIR 2)')
})
})
describe('exLine', () => {
it('shows the split where there is room for it, next to the total you log', () => {
expect(exLine({ id: LIFT, sets: 3, reps: 16, side: true }, 'kg')).toBe('3 × 16 · 8/side')
})
it('marks added weight as added', () => {
expect(exLine({ id: BW, sets: 3, reps: 8, weight: 10 }, 'kg')).toBe('3 × 8 · +10 kg')
})
it('summarises a planned exercise per mode', () => {
expect(exLine({ id: LIFT, sets: 3, reps: 10 }, 'kg')).toBe('3 × 10')
expect(exLine({ id: LIFT, sets: 3, reps: 10, weight: 60 }, 'kg')).toBe('3 × 10 · 60 kg')
@@ -318,4 +385,14 @@ describe('workoutVolume', () => {
] }
expect(workoutVolume(w)).toBe(600)
})
it('needs no per-side case — the logged reps are already both sides (issue #31)', () => {
const w = { entries: [{ id: LIFT, target: { side: true }, sets: [{ w: 20, r: 16, done: true }] }] }
expect(workoutVolume(w)).toBe(320)
})
it('leaves an unloaded bodyweight set at zero volume rather than inventing a number', () => {
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
expect(workoutVolume(w)).toBe(0)
})
})
+44
View File
@@ -0,0 +1,44 @@
// Runtime-agnostic core of the i18n module: state, constants and readers (t, dateLocale,
// instrFor, getLang). Plain Node-loadable — the browser-only pieces (import.meta.glob lazy
// loads, the React subscription hook) live in i18n.js and re-export from here.
export const LANGS = {
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文',
ko: '한국어', hi: 'हिन्दी'
}
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
export const DATE_LOCALES = {
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
}
let lang = 'en' // set only by _setLangState, called from i18n.js setLang
let dict = {} // current locale pack (empty = English fallback)
let instr = null // { exId: [steps] } for the current language, null = English
let version = 0 // bumped on every setLang; drives the React subscription selector
export const getLang = () => lang
export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB'
export const getVersion = () => version
// Translate a source string; {0},{1}… are replaced with args (also on the English fallback).
export function t(s, ...args) {
let v = dict[s] || s
for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i])
return v
}
// Instructions for an exercise in the current language (English steps as fallback).
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
// Called by i18n.js's setLang once the locale pack has been loaded — kept here rather than
// exported as setLang because loading packs requires import.meta.glob, which is Vite-only.
// Both `dict` and `instr` may be null to reset to English.
export function _setLangState(newLang, newDict, newInstr) {
lang = LANGS[newLang] ? newLang : 'en'
dict = lang === 'en' ? {} : (newDict || {})
instr = lang === 'en' || !INSTR_LANGS.includes(lang) ? null : (newInstr || null)
version++
return version
}
+18 -36
View File
@@ -1,56 +1,38 @@
// Tiny dependency-free i18n. English source strings are the keys; locale files in
// src/locales/ map them to translations and are lazy-loaded (Vite code-splits each
// import.meta.glob entry), so the initial bundle stays English-only.
// Exercise instructions come from separately generated packs in src/instr/ (one per
// language, from the upstream dataset) — also lazy-loaded on language switch.
// Browser-only shell of the i18n module. The runtime-agnostic state and readers live
// in i18n-core.js (plain Node-loadable); this file adds the two pieces that genuinely need
// the browser: `setLang` (which lazy-loads locale packs via import.meta.glob) and the React
// subscription hook `useLang`.
import { useSyncExternalStore } from 'react'
import {
LANGS, INSTR_LANGS, DATE_LOCALES,
getLang, dateLocale, t, instrFor, getVersion, _setLangState
} from './i18n-core.js'
// UI languages. de/pt have no instruction pack upstream — instructions fall back to English.
export const LANGS = {
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文',
ko: '한국어', hi: 'हिन्दी'
}
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
const DATE_LOCALES = {
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
}
export { LANGS, INSTR_LANGS, DATE_LOCALES, getLang, dateLocale, t, instrFor }
// Vite code-splits each locale pack into its own chunk via import.meta.glob; instructions use
// the same mechanism in src/instr/. Both are lazy, so the production bundle ships English only.
const localePacks = import.meta.glob('../locales/*.js')
const instrPacks = import.meta.glob('../instr/*.js')
let lang = 'en'
let dict = {}
let instr = null // { exId: [steps] } for the current language, null = English
let version = 0
// React subscription bookkeeping — kept here, not in core, so core has zero React coupling.
const subs = new Set()
const notify = () => { version++; subs.forEach(f => f()) }
export const getLang = () => lang
export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB'
// Translate a source string; {0},{1}… are replaced with args (also on the English fallback).
export function t(s, ...args) {
let v = dict[s] || s
for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i])
return v
}
// Instructions for an exercise in the current language (English steps as fallback).
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
const notify = () => { subs.forEach(f => f()) }
export async function setLang(l) {
if (!LANGS[l]) l = 'en'
if (l === lang && version > 0) return
lang = l
if (l === getLang() && getVersion() > 0) return
let dict = {}, instr = null
try {
dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default
instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default
} catch (e) { dict = {}; instr = null }
_setLangState(l, dict, instr)
notify()
}
// Re-renders the subscribing component (and its children) whenever the language changes.
export function useLang() {
return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, () => version)
return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, getVersion)
}
+1 -1
View File
@@ -9,7 +9,7 @@
//
// Like the demo build, MOBILE is replaced at build time, so all of this folds away in
// web bundles; the Capacitor plugins are only ever imported behind it.
import { t } from './i18n.js'
import { t } from './i18n-core.js'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
+8 -3
View File
@@ -100,10 +100,15 @@ export function loadOf(items) {
return load
}
/** Load for finished workouts (only sets actually ticked off count). */
export const loadOfWorkouts = workouts =>
/**
* Load for finished workouts (only sets actually ticked off count). `pick` narrows that
* further — the map can then answer "where did the *hard* sets go", which is a different
* question from where the sets went: a muscle can lead on volume and still never be trained
* near failure.
*/
export const loadOfWorkouts = (workouts, pick) =>
loadOf((workouts || []).flatMap(w =>
(w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done).length }))))
(w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && (!pick || pick(s))).length }))))
/** Load a routine *would* produce, from its planned set counts. */
export const loadOfRoutine = routine =>
+12 -4
View File
@@ -8,10 +8,10 @@
// 2. A clean, printable page (Save as PDF) where a single exercise never splits across
// a page break — each exercise, and each routine that fits, stays in one place.
import { EXIDX } from './exercises.js'
import { modeOf, fmtSec } from './history.js'
import { EXIDX, isBodyweightEq } from './exercises.js'
import { modeOf, fmtSec, isBw, isPerSide, sideReps } from './history.js'
import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'
import { t } from './i18n.js'
import { t } from './i18n-core.js'
const PLAN_FMT = 1
const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan screen
@@ -33,11 +33,17 @@ function cleanEx(e) {
if (e.reps != null) o.reps = e.reps
if (e.weight) o.weight = e.weight
}
// How the exercise is logged travels too (issues #31/#32) — the bodyweight flag only when
// it disagrees with the catalogue, since agreeing is what the other end already assumes.
if (e.bodyweight != null && e.bodyweight !== isBodyweightEq(e.id)) o.bodyweight = e.bodyweight
// Only on reps work — `side` counts reps, and a timed hold has none to split.
if (e.side && mode !== 'time' && mode !== 'cardio') o.side = true
// Progression settings travel with the plan — a shared Greyskull routine that arrives
// without its rule is just a list of weights.
if (e.prog) o.prog = e.prog
if (e.inc > 0) o.inc = e.inc
if (e.repsMin != null) o.repsMin = e.repsMin
if (e.repsMax != null) o.repsMax = e.repsMax
if (e.sg) o.sg = e.sg
return o
}
@@ -145,7 +151,9 @@ function scheme(e, unit) {
return sets > 1 ? `${sets} × ${body}` : body
}
let s = mode === 'time' ? `${sets} × ${fmtSec(e.sec || 45)}` : `${sets} × ${e.reps ?? 10}`
if (e.weight) s += ` · ${fmtNum(e.weight)} ${unit}`
if (e.weight) s += ` · ${isBw(e) ? '+' : ''}${fmtNum(e.weight)} ${unit}`
// A printed plan is read at the rack, so the split earns its four characters.
if (mode !== 'time' && isPerSide(e)) s += ` · ${t('{0}/side', fmtNum(sideReps(e.reps ?? 10)))}`
return s
}
+40 -14
View File
@@ -16,7 +16,7 @@
// · fewer sets than prescribed → miss
// So a session that fell apart can never advance the load as though it had succeeded.
import { modeOf } from './history.js'
import { modeOf, repStep } from './history.js'
import { EXIDX } from './exercises.js'
export const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time']
@@ -60,6 +60,9 @@ export function defaultIncrement(exId, unit) {
return heavy ? 5 : 2.5
}
export const DEFAULT_SEC_INCREMENT = 5
// Where adding another set of push-ups stops being progress and starts being a way to spend
// an evening. Past this the honest advice is load or a harder variation (issue #33).
export const MAX_BW_SETS = 6
// The policy in force for one exercise: its own override, else the routine's default, else
// the mode's default. Reps keeps behaving the way the app always did (all reps → add a step).
@@ -117,6 +120,7 @@ export function readSession(entry, fallback) {
return {
mode, goal, reps,
weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)),
count: reps.length, // the dimension bodyweight work grows (#33)
low: reps.length ? Math.min(...reps) : 0,
amrap: reps.length ? reps[reps.length - 1] : 0, // Greyskull's final set
ok: goal > 0 && enough && reps.length > 0 && reps.every(r => r >= goal)
@@ -179,14 +183,28 @@ export function nextPrescription(S, cfg, routine) {
const w = last.weight
// Bodyweight work carries no external load, so there is nothing to add or take away —
// "deload your push-ups to 2.5 kg" is not advice. Progress in reps instead. This runs
// ahead of the individual policies because it is true for all of them; a rep range set on
// top of it simply gets passed once you exceed it, which is the right moment to add load
// or move to a harder variation anyway.
// "deload your push-ups to 2.5 kg" is not advice. Progress in reps instead. This runs ahead
// of the individual policies because it is true for all of them. Note the trigger is the
// *logged* weight, not the `bw` flag: a dip done with a belt has a load to progress and
// belongs on the normal policies, and a barbell lift logged at 0 has nothing to add to.
if (w <= 0) {
const goal = last.goal || cfg.reps || 0
if (last.ok && goal > 0) return { policy, kind: 'up', weight: 0, reps: goal + 1, why: ['Bodyweight — every rep last time, so go for {0} this time.', goal + 1] }
return { policy, kind: 'hold', weight: 0, reps: goal || undefined, why: ['Bodyweight — same target again until every set is clean.'] }
if (!last.ok || goal <= 0) return { policy, kind: 'hold', weight: 0, reps: goal || undefined, why: ['Bodyweight — same target again until every set is clean.'] }
// A ceiling turns "+1 rep forever" into a plan (issue #33). Past the top of the range the
// reps go back to the bottom and a set is added instead, which is how bodyweight work
// actually progresses once a set of 30 push-ups stops being a strength stimulus.
const top = cfg.repsMax > 0 ? cfg.repsMax : 0
if (top > 0 && goal >= top) {
const sets = Math.max(1, cfg.sets || last.count || 1) + 1
const bottom = Math.max(1, Math.min(cfg.reps || top, top))
if (sets <= MAX_BW_SETS) return { policy, kind: 'up', weight: 0, reps: bottom, sets, why: ['{0} reps in every set — add a set and go back to {1}.', goal, bottom] }
// Out of sets worth adding: more volume is no longer the answer, load or a harder
// variation is — and that is a decision for a person, not a policy.
return { policy, kind: 'hold', weight: 0, reps: goal, why: ['{0} sets of {1} — time to add weight or move to a harder variation.', sets - 1, goal] }
}
// Unilateral work steps by two, so the total stays even and both sides get the rep.
const next = goal + repStep(cfg)
return { policy, kind: 'up', weight: 0, reps: next, why: ['Bodyweight — every rep last time, so go for {0} this time.', next] }
}
if (policy === 'double') {
const top = cfg.reps || last.goal || 10
@@ -196,7 +214,7 @@ export function nextPrescription(S, cfg, routine) {
const dw = deloadTo(w, inc)
return { policy, kind: 'deload', weight: dw, reps: bottom, why: ['Stalled {0} sessions — deload to {1} {2}.', stalls, dw, unit] }
}
const aim = Math.min(top, Math.max(bottom, last.low + 1))
const aim = Math.min(top, Math.max(bottom, last.low + repStep(cfg)))
return { policy, kind: 'hold', weight: w, reps: aim, why: ['Same weight — aim for {0} reps this time.', aim] }
}
@@ -231,12 +249,20 @@ export function nextPrescription(S, cfg, routine) {
*/
export function applyPrescription(sets, p) {
if (!p || p.kind === 'off' || p.kind === 'first') return sets
return sets.map(s => {
const out = sets.map(s => {
if (s.done) return s
const out = { ...s }
if (p.weight != null) out.w = p.weight
if (p.reps != null) out.r = p.reps
if (p.sec != null) out.sec = p.sec
return out
const o = { ...s }
if (p.weight != null) o.w = p.weight
if (p.reps != null) o.r = p.reps
if (p.sec != null) o.sec = p.sec
return o
})
// A policy that decided on a set count gets to grow the list — bodyweight progression adds
// a set where a barbell would have added a plate. Only ever upwards, and only by copying a
// row that is already there: a session in progress must not lose a set it has logged.
if (p.sets > out.length) {
const seed = out[out.length - 1]
while (out.length < p.sets) out.push({ ...seed, done: false })
}
return out
}
+60 -1
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import {
readSession, sessionsFor, stallCount, nextPrescription, applyPrescription,
policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER
policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
} from './progression.js'
import { EXDB } from './exercises.js'
@@ -189,6 +189,54 @@ describe('bodyweight exercises', () => {
expect(p.reps).toBe(11)
})
/* A ceiling turns "+1 rep forever" into a plan — issue #33. */
it('climbs to the ceiling one rep at a time', () => {
const p = nextPrescription(bw([[0, 10, 10, 10]]), { ...cfg, repsMax: 15 })
expect(p.kind).toBe('up')
expect(p.reps).toBe(11)
expect(p.sets).toBeUndefined()
})
it('adds a set and restarts the range once the ceiling is reached', () => {
const at15 = hist(LIFT, [[0, 15, 15, 15]], { sets: 3, reps: 15 })
const p = nextPrescription(at15, { ...cfg, reps: 10, repsMax: 15 })
expect(p.kind).toBe('up')
expect(p.sets).toBe(4)
expect(p.reps).toBe(10)
expect(p.weight).toBe(0)
})
it('stops adding sets at the cap and says what to do instead', () => {
const at15 = hist(LIFT, [[0, 15, 15, 15]], { sets: 3, reps: 15 })
const p = nextPrescription(at15, { ...cfg, sets: MAX_BW_SETS, reps: 10, repsMax: 15 })
expect(p.kind).toBe('hold')
expect(p.sets).toBeUndefined()
expect(p.why[0]).toMatch(/harder variation/)
})
it('leaves a belted set to the normal policies — there is a load to add now', () => {
const belted = hist(LIFT, [[10, 10, 10, 10]], { sets: 3, reps: 10 })
const p = nextPrescription(belted, { ...cfg, bodyweight: true, repsMax: 15 })
expect(p.kind).toBe('up')
expect(p.weight).toBeGreaterThan(10)
expect(p.sets).toBeUndefined()
})
it('steps a unilateral total by two, so it lands on 16, 18, 20 (issue #31)', () => {
const at16 = hist(LIFT, [[0, 16, 16, 16]], { sets: 3, reps: 16 })
expect(nextPrescription(at16, { ...cfg, reps: 16, side: true }).reps).toBe(18)
// and by one when it is not
expect(nextPrescription(at16, { ...cfg, reps: 16 }).reps).toBe(17)
})
it('keeps climbing reps forever when no ceiling was set — the old behaviour', () => {
const at30 = hist(LIFT, [[0, 30, 30, 30]], { sets: 3, reps: 30 })
const p = nextPrescription(at30, cfg)
expect(p.kind).toBe('up')
expect(p.reps).toBe(31)
expect(p.sets).toBeUndefined()
})
it('applies to every policy, not just linear', () => {
for (const prog of ['linear', 'greyskull', 'double']) {
const p = nextPrescription(bw([[0, 10, 10, 4], [0, 10, 10, 4], [0, 10, 10, 4]]), { ...cfg, prog })
@@ -390,4 +438,15 @@ describe('applyPrescription', () => {
const timed = [{ sec: 45, w: 0, done: false }]
expect(applyPrescription(timed, { kind: 'up', sec: 50 })).toEqual([{ sec: 50, w: 0, done: false }])
})
it('grows the list when the policy added a set (issue #33)', () => {
const three = [{ w: 0, r: 10, done: false }, { w: 0, r: 10, done: false }, { w: 0, r: 10, done: false }]
const out = applyPrescription(three, { kind: 'up', weight: 0, reps: 10, sets: 4 })
expect(out).toHaveLength(4)
expect(out[3]).toEqual({ w: 0, r: 10, done: false })
})
it('never shrinks a session that has already logged sets', () => {
expect(applyPrescription(sets, { kind: 'up', weight: 60, sets: 1 })).toHaveLength(sets.length)
})
})
+10 -3
View File
@@ -5,6 +5,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
// otherwise the tests pass against a one-shot implementation that dies on the first tab switch.
let requests, released, live, listeners, reject
// Node 21+ defines globalThis.navigator itself, as a getter with no setter — a plain
// assignment throws under ESM's strict mode. defineProperty works on both that and the older
// runtimes where the global simply doesn't exist. Production images are node:22-alpine, so
// the tests have to run there too.
const setNavigator = value =>
Object.defineProperty(globalThis, 'navigator', { value, configurable: true, writable: true })
function fakeBrowser() {
requests = 0; released = 0; live = null; reject = false
listeners = new Set()
@@ -13,7 +20,7 @@ function fakeBrowser() {
addEventListener: (type, fn) => { if (type === 'visibilitychange') listeners.add(fn) },
removeEventListener: (type, fn) => { if (type === 'visibilitychange') listeners.delete(fn) },
}
globalThis.navigator = {
setNavigator({
wakeLock: {
request: async () => {
requests++
@@ -24,7 +31,7 @@ function fakeBrowser() {
return s
},
},
}
})
}
const fire = () => listeners.forEach(fn => fn())
const settle = () => new Promise(r => setTimeout(r, 0))
@@ -42,7 +49,7 @@ afterEach(() => { delete globalThis.document; delete globalThis.navigator })
describe('wakeLockSupported', () => {
it('is false when the browser has no wakeLock at all', () => {
globalThis.navigator = {}
setNavigator({})
expect(wakeLockSupported()).toBe(false)
})
it('is true when it does', () => {
+40
View File
@@ -245,6 +245,12 @@ export default {
'Sign out?': 'Abmelden?',
'Your data is synced to your profile first, then cleared from this device.': 'Deine Daten werden erst mit dem Profil synchronisiert, dann von diesem Gerät entfernt.',
'Sign out': 'Abmelden',
'Sign out everywhere?': 'Überall abmelden?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Meldet dieses Profil auf allen Geräten ab, auch auf diesem. Deine Passkeys bleiben gültig — du kannst dich damit jederzeit wieder anmelden.',
'Sign out everywhere': 'Überall abmelden',
'Ends this profile’s sessions on all your devices.': 'Beendet die Sitzungen dieses Profils auf all deinen Geräten.',
'Signed out on all devices': 'Auf allen Geräten abgemeldet',
'Could not sign out everywhere — you are still signed in.': 'Abmelden auf allen Geräten fehlgeschlagen — du bist weiterhin angemeldet.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Gastmodus — Daten liegen nur in diesem Browser. Erstelle ein Passkey-Profil, um sie zu sichern und pro Person zu trennen.',
'Create passkey profile': 'Passkey-Profil erstellen',
'Passkeys not supported in this browser.': 'Passkeys werden in diesem Browser nicht unterstützt.',
@@ -531,4 +537,38 @@ export default {
'Easy — warm-up territory': 'Locker — Aufwärmbereich',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR zählt die Wiederholungen, die du übrig lässt; RPE liest dieselbe Anstrengung auf einer 10er-Skala ab — also RPE ≈ 10 − RIR. Nimm die Skala, in der du ohnehin denkst.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Die hervorgehobene Zeile ist der Bereich, in dem die meisten Arbeitssätze landen. Bereits protokollierte Sätze behalten ihre eigene Skala, und sonst liest den Wert nichts — Progression und geschätztes 1RM bleiben unberührt.',
// --- effort in the stats ---
'Effort': 'Anstrengung',
'how close to failure': 'wie nah am Muskelversagen',
'by hard sets': 'nach harten Sätzen',
'Hard': 'Hart',
'no hard sets': 'keine harten Sätze',
'No hard sets in this period': 'Keine harten Sätze in diesem Zeitraum',
'Every muscle group got at least one hard set in this period.': 'Jede Muskelgruppe hat in diesem Zeitraum mindestens einen harten Satz bekommen.',
'No rated sets in this period.': 'Keine bewerteten Sätze in diesem Zeitraum.',
'average effort': 'durchschnittliche Anstrengung',
'at {0} {1} or harder': 'bei {0} {1} oder härter',
'{0} of {1} finished sets rated': '{0} von {1} erledigten Sätzen bewertet',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Anstrengung pro Satz ist ausgeschaltet — schalte sie in den Einstellungen ein, um weiter zu bewerten.',
'Week by week': 'Woche für Woche',
'Where the sets land': 'Wo die Sätze landen',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Die meisten Arbeitssätze gehören nah ans Muskelversagen, ohne dort zu wohnen — die Hälfte ganz unten und die Hälfte ganz oben mittelt sich zu einem gesund aussehenden Mittelwert.',
'Average effort per workout': 'Durchschnittliche Anstrengung pro Training',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Ein vollerer Punkt heißt: weniger im Tank — dasselbe Gewicht bei niedrigerem {0} ist Fortschritt, den die Linie allein nicht zeigt.',
// --- bodyweight & per side ---
'Bodyweight': 'Körpergewicht',
'No weight to enter — just log the reps.': 'Kein Gewicht einzutragen — nur die Wiederholungen.',
'Ask for a weight on every set.': 'Bei jedem Satz nach dem Gewicht fragen.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Für Dips oder Klimmzüge mit Gürtel. Die Progression folgt dann dem Gewicht.',
'Reps per side': 'Wiederholungen pro Seite',
'For lunges, single-arm rows and the like.': 'Für Ausfallschritte, einarmiges Rudern und Ähnliches.',
'Top of the range': 'Oberes Ende',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Die Wiederholungen steigen um eine, sobald jeder Satz sauber war. Setz ein oberes Ende, damit irgendwann ein Satz dazukommt statt immer mehr Wiederholungen.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Die Wiederholungen steigen bis {0}, dann kommt ein Satz dazu und die Wiederholungen starten neu. Bei {1} Sätzen wird stattdessen nach Zusatzgewicht gefragt.',
'Added ({0})': 'Zusatz ({0})',
'{0}/side': '{0}/Seite',
'{0} reps in every set — add a set and go back to {1}.': '{0} Wiederholungen in jedem Satz — ein Satz kommt dazu, zurück auf {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} Sätze mit {1} — Zeit für Zusatzgewicht oder eine schwerere Variante.',
'{0} per side': '{0} pro Seite',
'You still log the total: {0} is {1} per side.': 'Du trägst weiterhin die Gesamtzahl ein: {0} sind {1} pro Seite.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': '¿Cerrar sesión?',
'Your data is synced to your profile first, then cleared from this device.': 'Tus datos se sincronizan primero con tu perfil y luego se borran de este dispositivo.',
'Sign out': 'Cerrar sesión',
'Sign out everywhere?': '¿Cerrar sesión en todos los dispositivos?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Cierra la sesión de este perfil en todos los dispositivos, incluido este. Tus passkeys siguen funcionando — puedes volver a iniciar sesión con ellas cuando quieras.',
'Sign out everywhere': 'Cerrar sesión en todos los dispositivos',
'Ends this profile’s sessions on all your devices.': 'Termina las sesiones de este perfil en todos tus dispositivos.',
'Signed out on all devices': 'Sesión cerrada en todos los dispositivos',
'Could not sign out everywhere — you are still signed in.': 'No se pudo cerrar la sesión en todos los dispositivos — sigues con la sesión iniciada.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modo invitado — los datos viven solo en este navegador. Crea un perfil con passkey para protegerlos y separarlos por persona.',
'Create passkey profile': 'Crear perfil con passkey',
'Passkeys not supported in this browser.': 'Passkeys no compatibles con este navegador.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Fácil — zona de calentamiento',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'El RIR cuenta las repeticiones que dejas; el RPE lee ese mismo esfuerzo en una escala de 10 — así que RPE ≈ 10 − RIR. Elige la que ya usas para pensar.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La fila resaltada es donde cae la mayoría de las series efectivas. Las series ya registradas conservan su escala, y nada más lee el valor: la progresión y el 1RM estimado no cambian.',
// --- effort in the stats ---
'Effort': 'Esfuerzo',
'how close to failure': 'qué tan cerca del fallo',
'by hard sets': 'por series duras',
'Hard': 'Duras',
'no hard sets': 'sin series duras',
'No hard sets in this period': 'Sin series duras en este periodo',
'Every muscle group got at least one hard set in this period.': 'Todos los grupos musculares recibieron al menos una serie dura en este periodo.',
'No rated sets in this period.': 'Ninguna serie valorada en este periodo.',
'average effort': 'esfuerzo medio',
'at {0} {1} or harder': 'a {0} {1} o más duro',
'{0} of {1} finished sets rated': '{0} de {1} series completadas valoradas',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'El esfuerzo por serie está desactivado — actívalo en Ajustes para seguir valorando.',
'Week by week': 'Semana a semana',
'Where the sets land': 'Dónde caen las series',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'La mayoría de las series efectivas van cerca del fallo sin vivir allí — la mitad abajo y la mitad arriba dan una media que solo parece sana.',
'Average effort per workout': 'Esfuerzo medio por entrenamiento',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Un punto más lleno significa menos reserva — el mismo peso con un {0} más bajo es progreso que la línea por sí sola no muestra.',
// --- bodyweight & per side ---
'Bodyweight': 'Peso corporal',
'No weight to enter — just log the reps.': 'No hay peso que introducir — solo registra las reps.',
'Ask for a weight on every set.': 'Pedir un peso en cada serie.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Para fondos o dominadas con cinturón. La progresión sigue entonces el peso.',
'Reps per side': 'Reps por lado',
'For lunges, single-arm rows and the like.': 'Para zancadas, remo a una mano y similares.',
'Top of the range': 'Tope del rango',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Las reps suben de una en una cuando todas las series salen limpias. Fija un tope para añadir series en vez de reps para siempre.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Las reps suben hasta {0}, luego se añade una serie y las reps vuelven a empezar. Con {1} series te pedirá añadir peso.',
'Added ({0})': 'Extra ({0})',
'{0}/side': '{0}/lado',
'{0} reps in every set — add a set and go back to {1}.': '{0} reps en todas las series: añade una serie y vuelve a {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} series de {1}: toca añadir peso o pasar a una variante más difícil.',
'{0} per side': '{0} por lado',
'You still log the total: {0} is {1} per side.': 'Sigues registrando el total: {0} son {1} por lado.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Se déconnecter ?',
'Your data is synced to your profile first, then cleared from this device.': 'Tes données sont d’abord synchronisées avec ton profil, puis effacées de cet appareil.',
'Sign out': 'Se déconnecter',
'Sign out everywhere?': 'Se déconnecter partout ?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Déconnecte ce profil sur tous les appareils, y compris celui-ci. Tes passkeys restent valides — tu peux te reconnecter avec elles à tout moment.',
'Sign out everywhere': 'Se déconnecter partout',
'Ends this profile’s sessions on all your devices.': 'Met fin aux sessions de ce profil sur tous tes appareils.',
'Signed out on all devices': 'Déconnecté sur tous les appareils',
'Could not sign out everywhere — you are still signed in.': 'Impossible de se déconnecter partout — tu es toujours connecté.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Mode invité — les données ne vivent que dans ce navigateur. Crée un profil passkey pour les protéger et les séparer par personne.',
'Create passkey profile': 'Créer un profil passkey',
'Passkeys not supported in this browser.': 'Passkeys non prises en charge par ce navigateur.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Facile — zone d’échauffement',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'Le RIR compte les répétitions qu’il te restait ; le RPE lit le même effort sur une échelle de 10 — donc RPE ≈ 10 − RIR. Prends celle dans laquelle tu penses déjà.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La ligne mise en avant est celle où tombent la plupart des séries de travail. Les séries déjà enregistrées gardent leur échelle, et rien d’autre ne lit la valeur — la progression et le 1RM estimé ne changent pas.',
// --- effort in the stats ---
'Effort': 'Effort',
'how close to failure': 'à quel point près de l’échec',
'by hard sets': 'par séries dures',
'Hard': 'Dures',
'no hard sets': 'aucune série dure',
'No hard sets in this period': 'Aucune série dure sur cette période',
'Every muscle group got at least one hard set in this period.': 'Chaque groupe musculaire a eu au moins une série dure sur cette période.',
'No rated sets in this period.': 'Aucune série notée sur cette période.',
'average effort': 'effort moyen',
'at {0} {1} or harder': 'à {0} {1} ou plus dur',
'{0} of {1} finished sets rated': '{0} séries notées sur {1} terminées',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'L’effort par série est désactivé — active-le dans les Réglages pour continuer à noter.',
'Week by week': 'Semaine par semaine',
'Where the sets land': 'Où tombent les séries',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'La plupart des séries de travail se placent près de l’échec sans y vivre — la moitié tout en bas et la moitié tout en haut donnent une moyenne qui n’a l’air saine que sur le papier.',
'Average effort per workout': 'Effort moyen par séance',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Un point plus plein veut dire moins de réserve — le même poids à un {0} plus bas, c’est un progrès que la ligne seule ne montre pas.',
// --- bodyweight & per side ---
'Bodyweight': 'Poids du corps',
'No weight to enter — just log the reps.': 'Pas de poids à saisir — note simplement les répétitions.',
'Ask for a weight on every set.': 'Demander un poids à chaque série.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Pour les dips ou les tractions avec une ceinture. La progression suit alors le poids.',
'Reps per side': 'Reps par côté',
'For lunges, single-arm rows and the like.': 'Pour les fentes, les rowings à un bras et compagnie.',
'Top of the range': 'Haut de la fourchette',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Les répétitions montent d’une dès que toutes les séries sont propres. Fixe un plafond pour ajouter une série au lieu de monter les répétitions sans fin.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Les répétitions montent jusqu’à {0}, puis une série est ajoutée et les répétitions repartent du bas. À {1} séries, c’est du poids qu’il te demande d’ajouter.',
'Added ({0})': 'Ajouté ({0})',
'{0}/side': '{0}/côté',
'{0} reps in every set — add a set and go back to {1}.': '{0} répétitions sur toutes les séries — une série en plus, retour à {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — il est temps d’ajouter du poids ou de passer à une variante plus dure.',
'{0} per side': '{0} par côté',
'You still log the total: {0} is {1} per side.': 'Tu notes toujours le total : {0}, c’est {1} par côté.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'साइन आउट करें?',
'Your data is synced to your profile first, then cleared from this device.': 'डेटा पहले प्रोफ़ाइल से सिंक होता है, फिर इस डिवाइस से हटता है।',
'Sign out': 'साइन आउट',
'Sign out everywhere?': 'हर जगह साइन आउट करें?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'इस डिवाइस सहित सभी डिवाइस पर इस प्रोफ़ाइल को साइन आउट करता है। आपकी पासकी काम करती रहेंगी — उनसे कभी भी दोबारा साइन इन करें।',
'Sign out everywhere': 'हर जगह साइन आउट करें',
'Ends this profile’s sessions on all your devices.': 'आपके सभी डिवाइस पर इस प्रोफ़ाइल के सेशन खत्म करता है।',
'Signed out on all devices': 'सभी डिवाइस पर साइन आउट हो गया',
'Could not sign out everywhere — you are still signed in.': 'हर जगह साइन आउट नहीं हो सका — आप अभी भी साइन इन हैं।',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'गेस्ट मोड — डेटा केवल इस ब्राउज़र में रहता है। सुरक्षित रखने और हर व्यक्ति के लिए अलग रखने हेतु पासकी प्रोफ़ाइल बनाएँ।',
'Create passkey profile': 'पासकी प्रोफ़ाइल बनाएँ',
'Passkeys not supported in this browser.': 'इस ब्राउज़र में पासकी समर्थित नहीं।',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'आसान — वॉर्म-अप का दायरा',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR बचे हुए रेप्स गिनता है; RPE उसी मेहनत को 10 के पैमाने पर पढ़ता है — यानी RPE ≈ 10 − RIR. वही चुनें जिसमें आप पहले से सोचते हैं।',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'हाइलाइट की गई पंक्ति वह है जहाँ ज़्यादातर वर्किंग सेट आते हैं। पहले दर्ज किए सेट अपना पैमाना बनाए रखते हैं, और इस मान को और कुछ नहीं पढ़ता — प्रोग्रेशन और अनुमानित 1RM अछूते रहते हैं।',
// --- effort in the stats ---
'Effort': 'मेहनत',
'how close to failure': 'फेलियर के कितने पास',
'by hard sets': 'कठिन सेट के हिसाब से',
'Hard': 'कठिन',
'no hard sets': 'कोई कठिन सेट नहीं',
'No hard sets in this period': 'इस अवधि में कोई कठिन सेट नहीं',
'Every muscle group got at least one hard set in this period.': 'इस अवधि में हर मांसपेशी समूह को कम से कम एक कठिन सेट मिला।',
'No rated sets in this period.': 'इस अवधि में कोई आँका गया सेट नहीं।',
'average effort': 'औसत मेहनत',
'at {0} {1} or harder': '{0} {1} या उससे कठिन',
'{0} of {1} finished sets rated': '{1} पूरे किए सेट में से {0} आँके गए',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'हर सेट की मेहनत बंद है — आँकना जारी रखने के लिए सेटिंग्स में चालू करें।',
'Week by week': 'हफ़्ते दर हफ़्ते',
'Where the sets land': 'सेट कहाँ गिरते हैं',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'ज़्यादातर वर्किंग सेट फेलियर के पास होने चाहिए, पर वहीं बसे नहीं — आधे सबसे नीचे और आधे सबसे ऊपर मिलकर एक ऐसा औसत बनाते हैं जो सिर्फ़ देखने में सेहतमंद लगता है।',
'Average effort per workout': 'हर वर्कआउट की औसत मेहनत',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'ज़्यादा भरा बिंदु मतलब टंकी में कम बचा — वही वज़न कम {0} पर उठाना वह प्रगति है जो अकेली लाइन नहीं दिखाती।',
// --- bodyweight & per side ---
'Bodyweight': 'बॉडीवेट',
'No weight to enter — just log the reps.': 'कोई वज़न नहीं डालना — बस रेप्स दर्ज करें।',
'Ask for a weight on every set.': 'हर सेट पर वज़न पूछें।',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'बेल्ट के साथ डिप्स या पुल-अप्स के लिए। फिर प्रोग्रेशन वज़न के हिसाब से चलता है।',
'Reps per side': 'प्रति तरफ़ रेप्स',
'For lunges, single-arm rows and the like.': 'लंजेस, सिंगल-आर्म रो और ऐसे व्यायामों के लिए।',
'Top of the range': 'रेंज का ऊपरी सिरा',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'हर सेट साफ़ रहने पर रेप्स एक-एक बढ़ते हैं। ऊपरी सीमा तय करें ताकि रेप्स हमेशा बढ़ने के बजाय एक सेट जुड़ जाए।',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'रेप्स {0} तक बढ़ते हैं, फिर एक सेट जुड़ता है और रेप्स दोबारा शुरू होते हैं। {1} सेट पर यह वज़न बढ़ाने को कहता है।',
'Added ({0})': 'अतिरिक्त ({0})',
'{0}/side': '{0}/तरफ़',
'{0} reps in every set — add a set and go back to {1}.': 'हर सेट में {0} रेप्स — एक सेट जोड़ें और वापस {1} पर।',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} रेप्स के {0} सेट — अब वज़न बढ़ाने या किसी कठिन वैरिएशन पर जाने का समय।',
'{0} per side': 'प्रति तरफ़ {0}',
'You still log the total: {0} is {1} per side.': 'आप कुल ही दर्ज करते हैं: {0} यानी प्रति तरफ़ {1}।',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Uscire?',
'Your data is synced to your profile first, then cleared from this device.': 'I dati vengono prima sincronizzati col profilo, poi rimossi da questo dispositivo.',
'Sign out': 'Esci',
'Sign out everywhere?': 'Uscire ovunque?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Esce da questo profilo su tutti i dispositivi, incluso questo. Le tue passkey restano valide — puoi rientrare con loro quando vuoi.',
'Sign out everywhere': 'Esci ovunque',
'Ends this profile’s sessions on all your devices.': 'Chiude le sessioni di questo profilo su tutti i tuoi dispositivi.',
'Signed out on all devices': 'Uscito da tutti i dispositivi',
'Could not sign out everywhere — you are still signed in.': 'Impossibile uscire ovunque — sei ancora connesso.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modalità ospite — i dati vivono solo in questo browser. Crea un profilo passkey per proteggerli e separarli per persona.',
'Create passkey profile': 'Crea profilo passkey',
'Passkeys not supported in this browser.': 'Passkey non supportate in questo browser.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Facile — zona riscaldamento',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'Il RIR conta le ripetizioni che ti restavano; l’RPE legge lo stesso sforzo su una scala da 10 — quindi RPE ≈ 10 − RIR. Scegli quella con cui già ragioni.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La riga evidenziata è dove finisce la maggior parte delle serie di lavoro. Le serie già registrate mantengono la loro scala, e nient’altro legge il valore: progressione e 1RM stimato non cambiano.',
// --- effort in the stats ---
'Effort': 'Sforzo',
'how close to failure': 'quanto vicino al cedimento',
'by hard sets': 'per serie dure',
'Hard': 'Dure',
'no hard sets': 'nessuna serie dura',
'No hard sets in this period': 'Nessuna serie dura in questo periodo',
'Every muscle group got at least one hard set in this period.': 'Ogni gruppo muscolare ha avuto almeno una serie dura in questo periodo.',
'No rated sets in this period.': 'Nessuna serie valutata in questo periodo.',
'average effort': 'sforzo medio',
'at {0} {1} or harder': 'a {0} {1} o più duro',
'{0} of {1} finished sets rated': '{0} di {1} serie completate valutate',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Lo sforzo per serie è disattivato — attivalo nelle Impostazioni per continuare a valutare.',
'Week by week': 'Settimana per settimana',
'Where the sets land': 'Dove cadono le serie',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'La maggior parte delle serie di lavoro sta vicino al cedimento senza viverci — metà in fondo e metà in cima danno una media che sembra sana solo all’apparenza.',
'Average effort per workout': 'Sforzo medio per allenamento',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Un punto più pieno significa meno riserva — lo stesso peso con un {0} più basso è progresso che la linea da sola non mostra.',
// --- bodyweight & per side ---
'Bodyweight': 'Corpo libero',
'No weight to enter — just log the reps.': 'Nessun peso da inserire — registra solo le ripetizioni.',
'Ask for a weight on every set.': 'Chiedi un peso a ogni serie.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Per dip o trazioni con la cintura. La progressione segue poi il peso.',
'Reps per side': 'Ripetizioni per lato',
'For lunges, single-arm rows and the like.': 'Per affondi, rematori a un braccio e simili.',
'Top of the range': 'Massimo dell\'intervallo',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Le ripetizioni salgono di una ogni volta che tutte le serie sono pulite. Imposta un massimo per aggiungere serie invece di ripetizioni all\'infinito.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Le ripetizioni salgono fino a {0}, poi viene aggiunta una serie e le ripetizioni ripartono da capo. A {1} serie ti chiede invece di aggiungere peso.',
'Added ({0})': 'Aggiunto ({0})',
'{0}/side': '{0}/lato',
'{0} reps in every set — add a set and go back to {1}.': '{0} ripetizioni in ogni serie — aggiungi una serie e torna a {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} serie da {1} — è ora di aggiungere peso o passare a una variante più difficile.',
'{0} per side': '{0} per lato',
'You still log the total: {0} is {1} per side.': 'Registri sempre il totale: {0} sono {1} per lato.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': '로그아웃할까요?',
'Your data is synced to your profile first, then cleared from this device.': '데이터를 먼저 프로필에 동기화한 뒤 이 기기에서 지웁니다.',
'Sign out': '로그아웃',
'Sign out everywhere?': '모든 기기에서 로그아웃할까요?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': '이 기기를 포함해 모든 기기에서 이 프로필을 로그아웃합니다. 패스키는 그대로 사용할 수 있어 언제든 다시 로그인할 수 있습니다.',
'Sign out everywhere': '모든 기기에서 로그아웃',
'Ends this profile’s sessions on all your devices.': '모든 기기에서 이 프로필의 세션을 종료합니다.',
'Signed out on all devices': '모든 기기에서 로그아웃했습니다',
'Could not sign out everywhere — you are still signed in.': '모든 기기에서 로그아웃하지 못했습니다 — 아직 로그인 상태입니다.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': '게스트 모드 — 데이터가 이 브라우저에만 저장됩니다. 패스키 프로필을 만들어 안전하게 보관하고 사람별로 분리하세요.',
'Create passkey profile': '패스키 프로필 만들기',
'Passkeys not supported in this browser.': '이 브라우저는 패스키를 지원하지 않습니다.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': '가벼움 — 웜업 구간',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR은 남긴 횟수를 세고, RPE는 같은 노력을 10점 척도로 읽습니다 — 즉 RPE ≈ 10 − RIR. 평소에 쓰던 쪽을 고르세요.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': '강조된 줄은 대부분의 본세트가 들어가는 구간입니다. 이미 기록한 세트는 원래 척도를 그대로 유지하며, 이 값을 읽는 곳은 없습니다 — 프로그레션과 예상 1RM은 영향을 받지 않습니다.',
// --- effort in the stats ---
'Effort': '강도',
'how close to failure': '실패 지점에 얼마나 가까운지',
'by hard sets': '힘든 세트 기준',
'Hard': '힘든 세트',
'no hard sets': '힘든 세트 없음',
'No hard sets in this period': '이 기간에 힘든 세트 없음',
'Every muscle group got at least one hard set in this period.': '이 기간에 모든 근육군이 최소 한 세트는 힘들게 훈련했습니다.',
'No rated sets in this period.': '이 기간에 평가된 세트가 없습니다.',
'average effort': '평균 강도',
'at {0} {1} or harder': '{0} {1} 이상',
'{0} of {1} finished sets rated': '완료한 {1}세트 중 {0}세트 평가됨',
'Effort per set is switched off — turn it on in Settings to keep rating.': '세트당 강도가 꺼져 있습니다 — 계속 평가하려면 설정에서 켜세요.',
'Week by week': '주별 변화',
'Where the sets land': '세트가 몰리는 곳',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': '대부분의 본세트는 실패 지점 가까이에 있어야 하지만 거기 머물면 안 됩니다 — 절반은 바닥에 절반은 꼭대기에 있으면 평균만 건강해 보입니다.',
'Average effort per workout': '운동당 평균 강도',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': '점이 진할수록 남은 여력이 적다는 뜻입니다 — 같은 무게를 더 낮은 {0}로 든 것은 선만 봐서는 알 수 없는 발전입니다.',
// --- bodyweight & per side ---
'Bodyweight': '맨몸 운동',
'No weight to enter — just log the reps.': '입력할 무게 없음 — 횟수만 기록합니다.',
'Ask for a weight on every set.': '세트마다 무게를 물어봅니다.',
'For dips or pull-ups with a belt. Progression then follows the weight.': '벨트를 차고 하는 딥스나 풀업용. 그러면 점진적 증가가 무게를 따라갑니다.',
'Reps per side': '한쪽당 횟수',
'For lunges, single-arm rows and the like.': '런지, 한팔 로우 같은 운동용.',
'Top of the range': '범위 상한',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': '모든 세트가 깔끔하면 횟수가 하나씩 올라갑니다. 상한을 정하면 횟수를 계속 늘리는 대신 세트를 추가합니다.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': '횟수가 {0}회까지 오르면 세트가 하나 추가되고 횟수는 처음부터 다시 시작합니다. {1}세트가 되면 대신 무게를 올리라고 안내합니다.',
'Added ({0})': '추가 ({0})',
'{0}/side': '한쪽 {0}회',
'{0} reps in every set — add a set and go back to {1}.': '모든 세트 {0}회 달성 — 세트를 추가하고 {1}회로 돌아갑니다.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1}회 {0}세트 — 이제 무게를 올리거나 더 어려운 동작으로 넘어가세요.',
'{0} per side': '한쪽당 {0}회',
'You still log the total: {0} is {1} per side.': '기록은 그대로 합계로 합니다: {0}회는 한쪽당 {1}회입니다.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Wylogować?',
'Your data is synced to your profile first, then cleared from this device.': 'Dane najpierw synchronizują się z profilem, potem są usuwane z urządzenia.',
'Sign out': 'Wyloguj',
'Sign out everywhere?': 'Wylogować wszędzie?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Wylogowuje ten profil na wszystkich urządzeniach, także na tym. Twoje passkey nadal działają — możesz się nimi zalogować w każdej chwili.',
'Sign out everywhere': 'Wyloguj wszędzie',
'Ends this profile’s sessions on all your devices.': 'Kończy sesje tego profilu na wszystkich Twoich urządzeniach.',
'Signed out on all devices': 'Wylogowano na wszystkich urządzeniach',
'Could not sign out everywhere — you are still signed in.': 'Nie udało się wylogować wszędzie — nadal jesteś zalogowany.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Tryb gościa — dane żyją tylko w tej przeglądarce. Utwórz profil passkey, aby je zabezpieczyć i rozdzielić na osoby.',
'Create passkey profile': 'Utwórz profil passkey',
'Passkeys not supported in this browser.': 'Passkey nieobsługiwane w tej przeglądarce.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Lekko — poziom rozgrzewki',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR liczy powtórzenia, które zostały w zapasie; RPE odczytuje ten sam wysiłek w skali 10 — czyli RPE ≈ 10 − RIR. Wybierz tę, w której już myślisz.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Wyróżniony wiersz to miejsce, w które trafia większość serii roboczych. Zapisane wcześniej serie zachowują swoją skalę, a wartości nic więcej nie czyta — progresja i szacowany 1RM pozostają bez zmian.',
// --- effort in the stats ---
'Effort': 'Wysiłek',
'how close to failure': 'jak blisko upadku',
'by hard sets': 'wg ciężkich serii',
'Hard': 'Ciężkie',
'no hard sets': 'brak ciężkich serii',
'No hard sets in this period': 'Brak ciężkich serii w tym okresie',
'Every muscle group got at least one hard set in this period.': 'Każda grupa mięśniowa dostała w tym okresie co najmniej jedną ciężką serię.',
'No rated sets in this period.': 'Brak ocenionych serii w tym okresie.',
'average effort': 'średni wysiłek',
'at {0} {1} or harder': 'przy {0} {1} lub ciężej',
'{0} of {1} finished sets rated': 'ocenione serie: {0} z {1} ukończonych',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Wysiłek na serię jest wyłączony — włącz go w Ustawieniach, aby dalej oceniać.',
'Week by week': 'Tydzień po tygodniu',
'Where the sets land': 'Gdzie lądują serie',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Większość serii roboczych należy blisko upadku, ale nie na nim — połowa na dole i połowa na górze uśrednia się do zdrowo wyglądającego środka.',
'Average effort per workout': 'Średni wysiłek na trening',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Pełniejsza kropka znaczy mniej zapasu — ten sam ciężar przy niższym {0} to postęp, którego sama linia nie pokazuje.',
// --- bodyweight & per side ---
'Bodyweight': 'Masa własna',
'No weight to enter — just log the reps.': 'Nie podajesz ciężaru — zapisujesz tylko powtórzenia.',
'Ask for a weight on every set.': 'Pytaj o ciężar przy każdej serii.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Do dipów albo podciągania z pasem. Progresja idzie wtedy za ciężarem.',
'Reps per side': 'Powtórzenia na stronę',
'For lunges, single-arm rows and the like.': 'Do wykroków, wiosłowania jednorącz i podobnych.',
'Top of the range': 'Górna granica zakresu',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Powtórzenia rosną o jedno, gdy każda seria jest czysta. Ustaw górną granicę, aby zamiast powtórzeń w nieskończoność dochodziły serie.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Powtórzenia rosną do {0}, potem dochodzi seria, a powtórzenia zaczynają od nowa. Przy {1} seriach aplikacja poprosi zamiast tego o dodanie ciężaru.',
'Added ({0})': 'Dodane ({0})',
'{0}/side': '{0}/str.',
'{0} reps in every set — add a set and go back to {1}.': 'Wszystkie serie po {0} powt. — dodaj serię i wróć do {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} powt. — czas dodać ciężar albo przejść na trudniejszy wariant.',
'{0} per side': '{0} na stronę',
'You still log the total: {0} is {1} per side.': 'Nadal zapisujesz łączną liczbę: {0} to {1} na stronę.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Terminar sessão?',
'Your data is synced to your profile first, then cleared from this device.': 'Os teus dados são primeiro sincronizados com o perfil e depois apagados deste dispositivo.',
'Sign out': 'Terminar sessão',
'Sign out everywhere?': 'Terminar sessão em todos os dispositivos?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Termina a sessão deste perfil em todos os dispositivos, incluindo este. As tuas passkeys continuam a funcionar — podes voltar a entrar com elas quando quiseres.',
'Sign out everywhere': 'Terminar sessão em todos os dispositivos',
'Ends this profile’s sessions on all your devices.': 'Termina as sessões deste perfil em todos os teus dispositivos.',
'Signed out on all devices': 'Sessão terminada em todos os dispositivos',
'Could not sign out everywhere — you are still signed in.': 'Não foi possível terminar a sessão em todos os dispositivos — continuas com sessão iniciada.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modo convidado — os dados vivem só neste navegador. Cria um perfil com passkey para os proteger e separar por pessoa.',
'Create passkey profile': 'Criar perfil com passkey',
'Passkeys not supported in this browser.': 'Passkeys não suportadas neste navegador.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Fácil — zona de aquecimento',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'O RIR conta as repetições que deixaste; o RPE lê o mesmo esforço numa escala de 10 — ou seja, RPE ≈ 10 − RIR. Escolhe aquela em que já pensas.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'A linha destacada é onde cai a maioria das séries de trabalho. As séries já registadas mantêm a sua escala, e mais nada lê o valor — a progressão e o 1RM estimado não mudam.',
// --- effort in the stats ---
'Effort': 'Esforço',
'how close to failure': 'quão perto da falha',
'by hard sets': 'por séries duras',
'Hard': 'Duras',
'no hard sets': 'sem séries duras',
'No hard sets in this period': 'Sem séries duras neste período',
'Every muscle group got at least one hard set in this period.': 'Todos os grupos musculares tiveram pelo menos uma série dura neste período.',
'No rated sets in this period.': 'Nenhuma série avaliada neste período.',
'average effort': 'esforço médio',
'at {0} {1} or harder': 'a {0} {1} ou mais duro',
'{0} of {1} finished sets rated': '{0} de {1} séries concluídas avaliadas',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'O esforço por série está desligado — liga-o nas Definições para continuares a avaliar.',
'Week by week': 'Semana a semana',
'Where the sets land': 'Onde caem as séries',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'A maioria das séries de trabalho fica perto da falha sem viver lá — metade no fundo e metade no topo dão uma média que só parece saudável.',
'Average effort per workout': 'Esforço médio por treino',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Um ponto mais cheio significa menos margem — o mesmo peso com um {0} mais baixo é progresso que a linha sozinha não mostra.',
// --- bodyweight & per side ---
'Bodyweight': 'Peso do corpo',
'No weight to enter — just log the reps.': 'Sem peso para introduzir — regista só as repetições.',
'Ask for a weight on every set.': 'Pedir um peso em cada série.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Para dips ou pull-ups com cinto. A progressão passa então a seguir o peso.',
'Reps per side': 'Reps por lado',
'For lunges, single-arm rows and the like.': 'Para afundos, remadas a um braço e afins.',
'Top of the range': 'Topo do intervalo',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'As repetições sobem uma sempre que todas as séries saem limpas. Define um limite para acrescentar séries em vez de repetições para sempre.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'As repetições sobem até {0}, depois acrescenta-se uma série e as repetições recomeçam. Com {1} séries passa a pedir-te peso extra.',
'Added ({0})': 'Extra ({0})',
'{0}/side': '{0}/lado',
'{0} reps in every set — add a set and go back to {1}.': '{0} repetições em todas as séries — acrescenta uma série e volta a {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — hora de acrescentar peso ou passar a uma variação mais difícil.',
'{0} per side': '{0} por lado',
'You still log the total: {0} is {1} per side.': 'Continuas a registar o total: {0} são {1} por lado.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Выйти?',
'Your data is synced to your profile first, then cleared from this device.': 'Данные сначала синхронизируются с профилем, затем удаляются с устройства.',
'Sign out': 'Выйти',
'Sign out everywhere?': 'Выйти на всех устройствах?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Завершает сеансы этого профиля на всех устройствах, включая это. Ключи доступа продолжают работать — по ним можно войти снова в любой момент.',
'Sign out everywhere': 'Выйти на всех устройствах',
'Ends this profile’s sessions on all your devices.': 'Завершает сеансы этого профиля на всех твоих устройствах.',
'Signed out on all devices': 'Выход выполнен на всех устройствах',
'Could not sign out everywhere — you are still signed in.': 'Не удалось выйти на всех устройствах — ты всё ещё в системе.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Гостевой режим — данные живут только в этом браузере. Создай профиль с ключом доступа, чтобы защитить их и разделить по людям.',
'Create passkey profile': 'Создать профиль с ключом доступа',
'Passkeys not supported in this browser.': 'Ключи доступа не поддерживаются в этом браузере.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Легко — разминочная зона',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR считает повторения, оставшиеся в запасе; RPE читает то же усилие по 10-балльной шкале — то есть RPE ≈ 10 − RIR. Выберите ту, в которой вы уже думаете.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Выделенная строка — это диапазон, в который попадает большинство рабочих подходов. Уже записанные подходы сохраняют свою шкалу, и больше это значение нигде не используется: прогрессия и расчётный 1ПМ не меняются.',
// --- effort in the stats ---
'Effort': 'Усилие',
'how close to failure': 'насколько близко к отказу',
'by hard sets': 'по тяжёлым подходам',
'Hard': 'Тяжёлые',
'no hard sets': 'нет тяжёлых подходов',
'No hard sets in this period': 'Нет тяжёлых подходов за этот период',
'Every muscle group got at least one hard set in this period.': 'За этот период каждая группа мышц получила хотя бы один тяжёлый подход.',
'No rated sets in this period.': 'Нет оценённых подходов за этот период.',
'average effort': 'среднее усилие',
'at {0} {1} or harder': 'при {0} {1} или тяжелее',
'{0} of {1} finished sets rated': 'оценено {0} из {1} выполненных подходов',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Усилие в подходе выключено — включи его в настройках, чтобы продолжать оценивать.',
'Week by week': 'Неделя за неделей',
'Where the sets land': 'Куда попадают подходы',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Большинство рабочих подходов должны идти близко к отказу, но не жить на нём — половина внизу и половина вверху дают среднее, которое лишь выглядит здоровым.',
'Average effort per workout': 'Среднее усилие за тренировку',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Более плотная точка означает меньше запаса — тот же вес при меньшем {0} это прогресс, которого одна линия не показывает.',
// --- bodyweight & per side ---
'Bodyweight': 'Собственный вес',
'No weight to enter — just log the reps.': 'Вес вводить не нужно — записывай только повторения.',
'Ask for a weight on every set.': 'Спрашивать вес в каждом подходе.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Для отжиманий на брусьях или подтягиваний с поясом. Тогда прогрессия идёт по весу.',
'Reps per side': 'Повторения на сторону',
'For lunges, single-arm rows and the like.': 'Для выпадов, тяг одной рукой и тому подобного.',
'Top of the range': 'Верх диапазона',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Повторения растут на одно, когда все подходы чистые. Задай потолок, чтобы вместо бесконечного роста повторений добавлялся подход.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Повторения растут до {0}, затем добавляется подход и повторения начинаются заново. Дойдя до {1} подходов, приложение предложит вместо этого добавить вес.',
'Added ({0})': 'Доп. ({0})',
'{0}/side': '{0}/стор.',
'{0} reps in every set — add a set and go back to {1}.': 'Во всех подходах {0} повт. — добавь подход и вернись к {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} — пора добавить вес или перейти к более сложному варианту.',
'{0} per side': '{0} на сторону',
'You still log the total: {0} is {1} per side.': 'Ты по-прежнему записываешь общее число: {0} — это {1} на сторону.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Çıkış yapılsın mı?',
'Your data is synced to your profile first, then cleared from this device.': 'Verilerin önce profiline eşitlenir, sonra bu cihazdan silinir.',
'Sign out': 'Çıkış yap',
'Sign out everywhere?': 'Her yerden çıkış yapılsın mı?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Bu profili, bu cihaz dahil tüm cihazlarda oturumdan çıkarır. Geçiş anahtarların çalışmaya devam eder — istediğin zaman onlarla tekrar giriş yapabilirsin.',
'Sign out everywhere': 'Her yerden çıkış yap',
'Ends this profile’s sessions on all your devices.': 'Bu profilin tüm cihazlarındaki oturumlarını sonlandırır.',
'Signed out on all devices': 'Tüm cihazlarda çıkış yapıldı',
'Could not sign out everywhere — you are still signed in.': 'Her yerden çıkış yapılamadı — hâlâ giriş yapmış durumdasın.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Misafir modu — veriler sadece bu tarayıcıda yaşar. Güvende tutmak ve kişi başına ayırmak için geçiş anahtarlı profil oluştur.',
'Create passkey profile': 'Geçiş anahtarlı profil oluştur',
'Passkeys not supported in this browser.': 'Bu tarayıcıda geçiş anahtarları desteklenmiyor.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Kolay — ısınma bölgesi',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR yedekte bıraktığın tekrarları sayar; RPE aynı eforu 10’luk ölçekte okur — yani RPE ≈ 10 − RIR. Zaten hangisiyle düşünüyorsan onu seç.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Vurgulanan satır, çalışma setlerinin çoğunun denk geldiği yerdir. Daha önce kaydettiğin setler kendi ölçeğini korur ve bu değeri başka hiçbir şey okumaz — ilerleme ve tahmini 1RM etkilenmez.',
// --- effort in the stats ---
'Effort': 'Zorluk',
'how close to failure': 'tükenmeye ne kadar yakın',
'by hard sets': 'zor setlere göre',
'Hard': 'Zor',
'no hard sets': 'zor set yok',
'No hard sets in this period': 'Bu dönemde zor set yok',
'Every muscle group got at least one hard set in this period.': 'Bu dönemde her kas grubu en az bir zor set aldı.',
'No rated sets in this period.': 'Bu dönemde puanlanmış set yok.',
'average effort': 'ortalama zorluk',
'at {0} {1} or harder': '{0} {1} veya daha zor',
'{0} of {1} finished sets rated': '{1} tamamlanan setin {0} tanesi puanlandı',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Set başına zorluk kapalı — puanlamaya devam etmek için Ayarlar’dan aç.',
'Week by week': 'Hafta hafta',
'Where the sets land': 'Setler nereye düşüyor',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Çalışma setlerinin çoğu tükenmeye yakın olmalı ama orada yaşamamalı — yarısı en altta yarısı en üstte, ortalaması sağlıklı görünür.',
'Average effort per workout': 'Antrenman başına ortalama zorluk',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Daha dolu bir nokta depoda daha az kaldı demek — aynı ağırlığı daha düşük {0} ile kaldırmak, çizginin tek başına göstermediği bir ilerlemedir.',
// --- bodyweight & per side ---
'Bodyweight': 'Vücut ağırlığı',
'No weight to enter — just log the reps.': 'Girilecek ağırlık yok — sadece tekrarları kaydet.',
'Ask for a weight on every set.': 'Her sette ağırlık sorulsun.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Kemerle yapılan dips veya barfiks için. İlerleme o zaman ağırlığı izler.',
'Reps per side': 'Taraf başına tekrar',
'For lunges, single-arm rows and the like.': 'Lunge, tek kol çekiş ve benzeri hareketler için.',
'Top of the range': 'Aralığın üst sınırı',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Her set temiz çıktığında tekrarlar birer artar. Sonsuza kadar tekrar eklemek yerine set eklemek için bir üst sınır belirle.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Tekrarlar {0} değerine çıkar, sonra bir set eklenir ve tekrarlar baştan başlar. {1} sette ise bunun yerine ağırlık eklemen istenir.',
'Added ({0})': 'Ek ({0})',
'{0}/side': '{0}/taraf',
'{0} reps in every set — add a set and go back to {1}.': 'Her sette {0} tekrar — bir set ekle ve {1} tekrara dön.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} tekrarlık {0} set — ağırlık ekleme ya da daha zor bir varyasyona geçme zamanı.',
'{0} per side': 'Taraf başına {0}',
'You still log the total: {0} is {1} per side.': 'Toplamı kaydetmeye devam ediyorsun: {0}, taraf başına {1} demek.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': '退出登录?',
'Your data is synced to your profile first, then cleared from this device.': '数据会先同步到档案,然后从本设备清除。',
'Sign out': '退出登录',
'Sign out everywhere?': '在所有设备上退出登录?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': '让此档案在所有设备上退出登录,包括这台。通行密钥不受影响——随时可以用它们重新登录。',
'Sign out everywhere': '在所有设备上退出登录',
'Ends this profile’s sessions on all your devices.': '结束此档案在你所有设备上的会话。',
'Signed out on all devices': '已在所有设备上退出登录',
'Could not sign out everywhere — you are still signed in.': '无法在所有设备上退出登录——你仍处于登录状态。',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': '访客模式——数据只保存在此浏览器。创建通行密钥档案以保护数据并按人区分。',
'Create passkey profile': '创建通行密钥档案',
'Passkeys not supported in this browser.': '此浏览器不支持通行密钥。',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': '轻松——热身区间',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR 数的是你还留了几次;RPE 把同样的吃力程度换成 10 分制来读——所以 RPE ≈ 10 − RIR。选你习惯的那一种。',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': '高亮那一行是大多数正式组落在的位置。已经记录的组保留原来的标度,而且这个值不会被别处读取——进阶计划和预估 1RM 都不受影响。',
// --- effort in the stats ---
'Effort': '强度',
'how close to failure': '离力竭有多近',
'by hard sets': '按硬组',
'Hard': '硬组',
'no hard sets': '没有硬组',
'No hard sets in this period': '此期间没有硬组',
'Every muscle group got at least one hard set in this period.': '此期间每个肌群都至少练了一个硬组。',
'No rated sets in this period.': '此期间没有已评分的组。',
'average effort': '平均强度',
'at {0} {1} or harder': '{0} {1} 或更硬',
'{0} of {1} finished sets rated': '{1} 个已完成组中有 {0} 个已评分',
'Effort per set is switched off — turn it on in Settings to keep rating.': '每组强度已关闭——在设置中打开即可继续评分。',
'Week by week': '逐周变化',
'Where the sets land': '组都落在哪里',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': '大多数正式组应该接近力竭,但不要一直待在那里——一半在最底、一半在最顶,平均下来只是看着健康。',
'Average effort per workout': '每次训练的平均强度',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': '点越实,油箱里剩得越少——同样的重量配上更低的 {0},是曲线本身看不出的进步。',
// --- bodyweight & per side ---
'Bodyweight': '徒手动作',
'No weight to enter — just log the reps.': '无需输入重量——只记录次数。',
'Ask for a weight on every set.': '每组都询问重量。',
'For dips or pull-ups with a belt. Progression then follows the weight.': '用于系负重腰带做双杠臂屈伸或引体向上。此时进阶方式跟随重量。',
'Reps per side': '每侧次数',
'For lunges, single-arm rows and the like.': '用于弓步蹲、单臂划船之类的动作。',
'Top of the range': '次数上限',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': '每组都做干净,次数就加一。设置上限后,达到上限会加一组,而不是一直加次数。',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': '次数升到 {0} 后加一组,次数重新开始。到 {1} 组时会改为提示你加重量。',
'Added ({0})': '负重({0})',
'{0}/side': '{0}/侧',
'{0} reps in every set — add a set and go back to {1}.': '每组都做到 {0} 次——加一组,次数回到 {1}。',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} 组 × {1} 次——该加重量或换更难的变式了。',
'{0} per side': '每侧 {0} 次',
'You still log the total: {0} is {1} per side.': '你记录的仍然是总数:{0} 表示每侧 {1} 次。',
}
+62 -10
View File
@@ -1,9 +1,9 @@
import { useEffect, useRef, useState } from 'react'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, allExercises, equipmentOf } from './lib/exercises.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf } from './lib/exercises.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf } from './lib/history.js'
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps } from './lib/history.js'
import { beep, vibrate } from './lib/sound.js'
import { t, instrFor, getLang, INSTR_LANGS } from './lib/i18n.js'
import { nav } from './lib/nav.js'
@@ -11,14 +11,14 @@ import { starterRoutines } from './lib/starter.js'
import Media, { Thumb } from './components/Media.jsx'
import Stepper from './components/Stepper.jsx'
import Icon from './components/Icon.jsx'
import { Button, Slider, Switch, Segmented, SelectRow } from './components/ui.jsx'
import { Button, Slider, Switch, Segmented, SelectRow, Row } from './components/ui.jsx'
import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
import BodyMap from './components/BodyMap.jsx'
import { loadOfWorkouts } from './lib/muscles.js'
import { parseImport, mergeImport } from './lib/import-csv.js'
import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC } from './lib/progression.js'
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js'
import { MOBILE, shareExport } from './lib/mobile.js'
const S = () => useStore.getState().S
@@ -489,6 +489,9 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
// Cardio keeps its own duration+speed form; the reps/time choice (issue #16) is offered for
// everything else, which is where the gap was — planks, hangs, wall sits, loaded carries.
const mode = cardio ? 'cardio' : modeOf({ ...c, id: ex.id })
// Both default from the dataset and are then whatever the config says — see isBw.
const bw = !cardio && isBw({ ...c, id: ex.id })
const perSide = isPerSide(c)
// Keep whatever the other mode already had (sets, weight) and fill only what is missing.
const setMode = m => setC(x => ({ ...defaultConfig(ex.id, m), ...x, mode: m }))
const save = () => {
@@ -499,12 +502,24 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
const prog = {}
if (c.prog) prog.prog = c.prog
if (c.inc > 0) prog.inc = c.inc
// Written only when it differs from what the dataset already says, so a barbell config
// stays exactly the shape it was before these flags existed.
// `bodyweight` is true of a hold as much as of a set of reps; `side` is not — it counts
// reps, and a timed hold has none. Switching an exercise to Time therefore drops it
// rather than carrying a flag nothing downstream can read.
const flags = {}
if (bw !== isBodyweightEq(ex.id)) flags.bodyweight = bw
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8) })
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...prog })
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog })
else {
const reps = Math.max(1, Math.round(c.reps) || 10)
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...prog }
// A unilateral target is stored even: the split has to divide, and a typed 15 would
// otherwise plan seven reps on one side and eight on the other, every session.
const typed = Math.max(1, Math.round(c.reps) || 10)
const reps = perSide ? Math.ceil(typed / 2) * 2 : typed
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog }
if (policyFor({ ...c, id: ex.id }, routine, 'reps') === 'double') out.repsMin = Math.min(reps, Math.max(1, Math.round(c.repsMin) || Math.max(1, reps - 2)))
// A ceiling below the working reps would tell you to add a set on day one.
if (bw && !(out.weight > 0) && c.repsMax > 0) out.repsMax = Math.max(reps, Math.round(c.repsMax))
onSave(out)
}
}
@@ -531,13 +546,50 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
<Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
</> : <>
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
<Stepper label={t('Reps')} value={c.reps} step={1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
<Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
<Stepper label={t('Reps')} value={c.reps} step={perSide ? 2 : 1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
{/* On bodyweight work the weight stepper is the click #32 is about, so it is not here
until there is a belt to describe — see the added-weight row below. */}
{!bw && <Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />}
</>}
</div>
{mode === 'time' && <div className="small dim" style={{ marginBottom: 18 }}>
{mode === 'time' && !bw && <div className="small dim" style={{ marginBottom: 18 }}>
{t('A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.')}
</div>}
{/* ---------- bodyweight + per side (issues #31/#32/#33) ---------- */}
{!cardio && <div className="sect-b" style={{ marginBottom: 8 }}>
<Row icon="figureStrength" iconTint="var(--acc)" title={t('Bodyweight')}
subtitle={bw ? t('No weight to enter — just log the reps.') : t('Ask for a weight on every set.')}>
<Switch checked={bw} onChange={v => setC(x => ({ ...x, bodyweight: v, weight: v ? 0 : x.weight }))} />
</Row>
{mode === 'reps' && <Row icon="shuffle" iconTint="var(--blue)" title={t('Reps per side')}
subtitle={perSide ? t('You still log the total: {0} is {1} per side.', c.reps || 0, fmtNum(sideReps(c.reps))) : t('For lunges, single-arm rows and the like.')}>
{/* Turning it on rounds the target up to an even number, since half of an odd
total is a rep one side does not get. */}
<Switch checked={perSide} onChange={v => setC(x => ({ ...x, side: v || undefined, reps: v ? Math.ceil((x.reps || 0) / 2) * 2 : x.reps }))} />
</Row>}
</div>}
{/* A stepper is too wide to sit in a list row next to a label — it squeezes the text to
one word per line — so added weight gets the same full-width treatment as sets and
reps, with its explanation underneath. */}
{bw && <>
<div className="row cfgrow" style={{ marginBottom: 8 }}>
<Stepper label={t('Added ({0})', st.unit)} value={c.weight || 0} step={2.5}
onChange={v => setC(x => ({ ...x, weight: v }))} />
</div>
<div className="small dim" style={{ marginBottom: 18 }}>
{t('For dips or pull-ups with a belt. Progression then follows the weight.')}
</div>
</>}
{/* The rep ceiling only means something when there is no load to add instead. */}
{mode === 'reps' && bw && !(c.weight > 0) && <div className="row cfgrow" style={{ marginBottom: 18 }}>
<Stepper label={t('Top of the range')} value={c.repsMax || 0} step={1} decimal={false}
onChange={v => setC(x => ({ ...x, repsMax: v }))} />
</div>}
{mode === 'reps' && bw && !(c.weight > 0) && <div className="small dim" style={{ marginTop: -10, marginBottom: 18 }}>
{c.repsMax > 0
? t('Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.', c.repsMax, MAX_BW_SETS)
: t('Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.')}
</div>}
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} />
<Button variant="primary" onClick={save}>{existing ? t('Save') : t('Add to routine')}</Button>
{ex.custom && <><div style={{ height: 8 }} /><Button icon="pencil" onClick={() => { close(); customExSheet(ex) }}>{t('Edit or delete this exercise')}</Button></>}
+21 -5
View File
@@ -70,6 +70,15 @@ export const useStore = create((set, get) => {
}
})
// Everything a sign-out leaves behind on this device, whichever way it was triggered.
const clearLocalSession = () => {
get().setUser(null)
localStorage.removeItem('gym_guest')
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
}
return {
S: (() => { const s = loadState(); registerCustom(s.customEx); return s })(),
user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),
@@ -114,11 +123,18 @@ export const useStore = create((set, get) => {
async signOut() {
try { await get().pushState(); await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { /* */ }
get().setUser(null)
localStorage.removeItem('gym_guest')
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
clearLocalSession()
},
// "Sign out everywhere": the server bumps this profile's session version, which kills every
// session it has on any device — this browser included, so the app has to end up exactly
// where a normal signOut leaves it. Unlike signOut the request is NOT swallowed: if it fails
// the sessions elsewhere are all still valid, and wiping this device's copy of the data
// would sign the user out of the one place the bump didn't reach. Caller reports the error.
async signOutAll() {
await get().pushState() // never throws — stores gym_dirty and moves on when offline
await api('/api/logout/all', { method: 'POST', body: '{}' })
clearLocalSession()
},
// Demo build only: drop the seeded example profile back in (Settings → "Reset demo data").
+29 -3
View File
@@ -4,7 +4,7 @@ import { useStore, DEF, hasData } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO, localTZ } from '../lib/format.js'
import { effortOf } from '../lib/history.js'
import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
import { wakeLockSupported } from '../lib/wakelock.js'
import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
@@ -18,7 +18,7 @@ export default function Settings() {
const nav = useNavigate()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const { update, replaceState, setUser, pullState, pushState, signOut, resetDemo } = useStore()
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo } = useStore()
const toast = useUI(s => s.toast)
const fileRef = useRef(null)
const importRef = useRef(null)
@@ -53,6 +53,18 @@ export default function Settings() {
catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Sign-in failed')) }
}
const registerHere = () => useUI.getState().openSheet(close => <RegisterInline close={close} setUser={setUser} pushState={pushState} pullState={pullState} toast={toast} />)
// Ends the profile's sessions on every device — this one included, so on success it lands in
// the same place as the plain sign-out above (home, local data cleared). On failure nothing
// local is touched: still signed in here, and say so rather than leaving a half-signed-out app.
const signOutEverywhere = () => confirmSheet({
title: t('Sign out everywhere?'),
message: t('Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.'),
confirmText: t('Sign out everywhere'), danger: true,
onConfirm: async () => {
try { await signOutAll(); nav('/home'); toast(t('Signed out on all devices')) }
catch (e) { toast(t('Could not sign out everywhere — you are still signed in.')) }
},
})
return <div className="narrow">
<div className="hdr">
@@ -76,6 +88,7 @@ export default function Settings() {
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Signed in with passkey — data syncs to this profile.')} />
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
<Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })} />
<Row icon="shield" iconTint="var(--red)" title={t('Sign out everywhere')} subtitle={t('Ends this profile’s sessions on all your devices.')} danger onClick={signOutEverywhere} />
</> : webauthnOK() ? <>
<Row icon="sparkles" iconTint="var(--acc)" title={t('Create passkey profile')} subtitle={t('Keeps your data safe and separate per person.')} accessory="chevron" onClick={registerHere} />
<Row icon="person" iconTint="var(--blue)" title={t('Sign in with passkey')} accessory="chevron" onClick={signInHere} />
@@ -314,13 +327,20 @@ function PushCard({ S, update, toast }) {
</>
}
// The same registration as the sign-in screen's, reached from Settings instead. It asks for
// the invite code on the same terms: an invite-only instance rejects a registration without
// one, so a form that cannot collect it is a form that cannot succeed.
function RegisterInline({ close, setUser, pushState, pullState, toast }) {
const nameRef = useRef(null)
const [code, setCode] = useState('')
const [inviteOnly, setInviteOnly] = useState(false)
useEffect(() => { api('/api/config').then(c => setInviteOnly(!!c.invite_only)).catch(() => {}) }, [])
const go = async () => {
const n = (nameRef.current.value || '').trim()
if (!n) { toast(t('Enter a name')); return }
if (inviteOnly && !code.trim()) { toast(t('An invite code is required')); return }
try {
const u = await passkeyRegister(n); setUser(u); close()
const u = await passkeyRegister(n, code.trim()); setUser(u); close()
if (hasData(useStore.getState().S)) { await pushState(); toast(t('Profile created — data moved into it')) }
else { await pullState(); toast(t('Welcome, {0}', u.name)) }
} catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Registration failed')) }
@@ -329,6 +349,12 @@ function RegisterInline({ close, setUser, pushState, pullState, toast }) {
<h3>{t('Create your profile')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>{t('Pick a name, then confirm with your device.')}</div>
<TextField ref={nameRef} placeholder={t('Your name')} maxLength={40} />
{inviteOnly && <>
<div style={{ height: 10 }} />
<input className="input" placeholder={t('Invite code')} maxLength={40} value={code}
onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />
<div className="dim small" style={{ marginTop: 6 }}>{t('This app is invite-only — enter the code you were given.')}</div>
</>}
<div style={{ height: 12 }} /><Button variant="primary" onClick={go}>{t('Create passkey')}</Button>
</>
}
+111 -13
View File
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
import { lastBW, streakWeeks, setLabel, modeOf } from '../lib/history.js'
import { lastBW, streakWeeks, setLabel, modeOf, effortOf } from '../lib/history.js'
import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
@@ -12,26 +12,41 @@ import Icon from '../components/Icon.jsx'
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
import { loadOfWorkouts, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
import { e1rmSeries, best1RM } from '../lib/onerm.js'
import {
hasEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,
effortHistogram, isHardSet, HARD_RIR
} from '../lib/effort.js'
import { Button, Segmented, SelectRow } from '../components/ui.jsx'
// Which muscles the training in a window actually hit — and, the point of the card,
// which ones it keeps missing. Shading is relative within the window (lib/muscles.js).
function MuscleBalance({ S }) {
const [win, setWin] = useState(7)
const [hard, setHard] = useState(false)
const [sel, setSel] = useState(null)
const now = Date.now()
const inWin = S.workouts.filter(w =>
win === 0 ? true
: win === 7 ? weekKey(w.d) === weekKey(todayISO())
: (w.start || new Date(w.d).getTime()) > now - win * 86400000)
const load = loadOfWorkouts(inWin)
// Counting only the sets taken near failure turns the map from "where did the volume go"
// into "where did the stimulus go" — a muscle can lead on sets and still never be trained
// hard. Offered only when the window holds ratings at all, since with none the hard map
// would just be empty and read as "you trained nothing".
const rated = inWin.some(w => w.entries.some(e => e.sets.some(s => s.done && isHardSet(s))))
const on = hard && rated
const load = loadOfWorkouts(inWin, on ? isHardSet : null)
const { worked, missed } = rankOf(load)
const top = worked.slice(0, 4)
const max = worked.length ? load[worked[0]] : 0
const sets = m => Math.round((load[m] || 0) * 10) / 10
return <div className="card">
<h2>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('by sets worked')}</span></h2>
<div className="row between" style={{ marginBottom: 8 }}>
<h2 style={{ margin: 0 }}>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {on ? t('by hard sets') : t('by sets worked')}</span></h2>
{rated && <Button size="sm" icon="flame" style={on ? { color: 'var(--yellow)' } : undefined}
onClick={() => { setHard(h => !h); setSel(null) }}>{on ? t('Hard') : t('All')}</Button>}
</div>
<Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
{inWin.length ? <>
@@ -40,23 +55,80 @@ function MuscleBalance({ S }) {
<BodyMapLegend />
{sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
<span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : t('not trained')}</span>
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')}</span>
</div>}
{!sel && top.map(m => <div key={m} className="mrow">
<span className="nm">{t(MUSCLE_NAME[m])}</span>
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%' }} /></span>
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%', background: on ? 'var(--yellow)' : undefined }} /></span>
<span className="v">{t('{0} sets', sets(m))}</span>
</div>)}
{missed.length > 0 && <>
<h4 className="sec" style={{ marginTop: 12 }}>{t('Not trained in this period')}</h4>
<h4 className="sec" style={{ marginTop: 12 }}>{on ? t('No hard sets in this period') : t('Not trained in this period')}</h4>
<div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
</>}
{!missed.length && worked.length > 0 &&
<div className="muted small" style={{ marginTop: 10 }}>{t('Every muscle group got some work in this period.')}</div>}
<div className="muted small" style={{ marginTop: 10 }}>{on
? t('Every muscle group got at least one hard set in this period.')
: t('Every muscle group got some work in this period.')}</div>}
</> : <div className="muted small">{t('No workouts in this period yet.')}</div>}
</div>
}
// How hard the training was — the half of the picture a volume chart cannot show. Everything
// is computed in RIR (lib/effort.js) and converted to whichever scale this profile reads.
// Every number carries how much of the training it speaks for: rating is optional and off by
// default, so a partly rated history is the normal case, and an average without its
// denominator would quietly speak for sets that were never rated.
function EffortCard({ S }) {
const [win, setWin] = useState(90)
const kind = displayScale(S)
const hd = scaleName(kind)
const sum = effortSummary(S, win)
const weeks = effortWeeks(S, win)
const hist = effortHistogram(S, win)
const maxBin = Math.max(1, ...hist.map(b => b.n))
// The week's set count rides along in the tooltip, because the pair is the reading:
// volume up with effort up is fatigue piling up, volume up with effort flat is adaptation.
const pts = weeks.map(w => ({ t: w.t, y: toScale(kind, w.rir), note: t('{0} sets', w.sets) }))
// Bins run hardest-first in both scales: RIR 0 and RPE 10 are the same set.
const binLabel = b => kind === 'rpe' ? (b.tail ? '≤ 6' : String(10 - b.rir)) : (b.tail ? b.rir + '+' : String(b.rir))
return <div className="card">
<h2>{t('Effort')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('how close to failure')}</span></h2>
<Segmented className="seg-range" value={win} onChange={setWin}
options={[{ value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 365, label: '1Y' }, { value: 0, label: t('All') }]} />
{sum.rated === 0 ? <div className="muted small">{t('No rated sets in this period.')}</div> : <>
<div className="row between" style={{ alignItems: 'flex-end', gap: 12 }}>
<div>
<div className="stat-v">{sum.avg == null ? '—' : fmtNum(toScale(kind, sum.avg)) + ' ' + hd}</div>
<div className="small dim">{t('average effort')}</div>
</div>
<div style={{ textAlign: 'right' }}>
<div className="stat-v" style={{ color: 'var(--yellow)' }}>{sum.hardPct == null ? '—' : Math.round(sum.hardPct * 100) + '%'}</div>
<div className="small dim">{t('at {0} {1} or harder', hd, fmtNum(toScale(kind, HARD_RIR)))}</div>
</div>
</div>
<div className="small dim" style={{ marginTop: 8 }}>{t('{0} of {1} finished sets rated', sum.rated, sum.done)}</div>
{effortOf(S) === 'none' && <div className="small" style={{ color: 'var(--yellow)', marginTop: 4 }}>
{t('Effort per set is switched off — turn it on in Settings to keep rating.')}
</div>}
{pts.length > 1 && <>
<h4 className="sec" style={{ marginTop: 12 }}>{t('Week by week')}</h4>
<div className="chart"><LineChart points={pts} h={140} unit={hd} color="var(--yellow)" invert={kind === 'rir'} /></div>
</>}
<h4 className="sec" style={{ marginTop: 12 }}>{t('Where the sets land')}</h4>
{hist.map(b => <div key={b.rir} className="mrow">
<span className="nm">{hd} {binLabel(b)}</span>
<span className="bar"><i style={{ width: Math.round(b.n / maxBin * 100) + '%', background: b.rir <= HARD_RIR ? 'var(--yellow)' : 'var(--label-3)' }} /></span>
<span className="v">{b.n ? b.n + ' · ' + Math.round(b.pct * 100) + '%' : '—'}</span>
</div>)}
<div className="small dim" style={{ marginTop: 8 }}>
{t('Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.')}
</div>
</>}
</div>
}
// Stats = the analytics hub: all charts, progress and history live here.
export default function Stats() {
const nav = useNavigate()
@@ -65,6 +137,9 @@ export default function Stats() {
const [exId, setExId] = useState(null)
const [exMetric, setExMetric] = useState('top')
const now = Date.now()
const anyEffort = hasEffort(S)
const kind = displayScale(S)
const hd = scaleName(kind)
const bwPts = S.bodyweight.filter(b => range === 0 || (b.t || new Date(b.d).getTime()) > now - range * 86400000)
.map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
@@ -101,7 +176,23 @@ export default function Stats() {
const e1Pts = curEx ? e1rmSeries(S, curEx) : []
const e1Best = curEx ? best1RM(S, curEx) : null
const showE1 = e1Pts.length > 0
// Effort on this exercise, per session. It rides on the top-set curve as well as having a
// curve of its own, because the two only mean something together: the same weight moved
// with more left in the tank is progress a weight-only chart draws as a flat line.
const exRir = exPts.map(p => avgRir(p.sets))
const showEff = exRir.filter(v => v != null).length >= 3
const effPts = exPts.map((p, i) => (exRir[i] == null ? null : { t: p.t, y: toScale(kind, exRir[i]), d: p.d })).filter(Boolean)
const onE1 = showE1 && exMetric === 'e1rm'
const onEff = showEff && exMetric === 'effort'
const topPts = exPts.map((p, i) => ({
t: p.t, y: p.y, d: p.d,
// 0 RIR (nothing left) is a full dot, 4+ a faint one; unrated sessions keep the plain line.
m: exRir[i] == null ? null : 1 - Math.min(4, Math.max(0, exRir[i])) / 4,
note: exRir[i] == null ? undefined : hd + ' ' + fmtNum(toScale(kind, exRir[i]))
}))
const exOpts = [{ value: 'top', label: t('Top set') }]
if (showE1) exOpts.push({ value: 'e1rm', label: t('Est. 1RM') })
if (showEff) exOpts.push({ value: 'effort', label: t('Effort') })
return <>
<div className="hdr"><div><h1>{t('Stats')}</h1><div className="sub">{t('Progress & history')}</div></div>
@@ -120,6 +211,7 @@ export default function Stats() {
</div>
{S.workouts.length > 0 && <MuscleBalance S={S} />}
{anyEffort && <EffortCard S={S} />}
<div className="cols">
<div className="card">
@@ -142,18 +234,24 @@ export default function Stats() {
<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId}
options={exHist.map(id => ({ value: id, label: EXIDX[id].n }))} />
</div>
{showE1 && <Segmented className="seg-range" value={exMetric} onChange={setExMetric}
options={[{ value: 'top', label: t('Top set') }, { value: 'e1rm', label: t('Est. 1RM') }]} />}
<div className="chart"><LineChart points={(onE1 ? e1Pts : exPts).map(p => ({ t: p.t, y: p.y, d: p.d }))} h={150} unit={exUnit} color="var(--blue)" /></div>
{exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}
<div className="chart">
{onEff
? <LineChart points={effPts} h={150} unit={hd} color="var(--yellow)" invert={kind === 'rir'} />
: <LineChart points={onE1 ? e1Pts.map(p => ({ t: p.t, y: p.y, d: p.d })) : topPts} h={150} unit={exUnit} color="var(--blue)" />}
</div>
<div style={{ marginTop: 8 }}>{exList.map((p, i) => <div key={i} className="row between small" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}>
<span className="muted">{fmtDate(p.d, true)}</span><span>{p.sets.map(s => setLabel(curEx, s, p.target)).join(' ')}</span></div>)}</div>
<div className="small dim" style={{ marginTop: 8 }}>
{onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')} · {t('Best:')}
{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b>
{onEff ? t('Average effort per workout') : onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')}
{onEff ? '' : <> · {t('Best:')}{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b></>}
</div>
{showE1 && <div className="small dim" style={{ marginTop: 4 }}>
{onE1 && <div className="small dim" style={{ marginTop: 4 }}>
{t('Best estimate from {0} on {1} — an estimate, not a tested max.', fmtNum(e1Best.w) + ' ' + S.unit + ' × ' + e1Best.r, fmtDate(e1Best.d, true))}
</div>}
{!onEff && !onE1 && showEff && <div className="small dim" style={{ marginTop: 4 }}>
{t('A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.', hd)}
</div>}
</> : <div className="muted small">{t('Finish your first workout to see progress curves here.')}</div>}
</div>
</div>
+24 -9
View File
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, EFFORT, effortOf, stepEffort, capEffort } from '../lib/history.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t } from '../lib/i18n.js'
@@ -69,12 +69,22 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// What the progression policy decided for this session, and why (issue #17). Computed when
// the session was built so the reason matches the numbers already in the rows.
const plan = entry.plan
// A bodyweight set has no weight to type, so the column is not there (issue #32) — one
// stepper instead of two, which is the whole point of the flag. Adding a belt weight in the
// config brings it back, now labelled as the addition it is.
const cfg = { ...(entry.target || {}), id: entry.id }
const bw = !cardio && isBw(cfg)
const added = bw && entry.sets.some(s => s.w > 0)
const loadCol = { f: 'w', step: 2.5, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) }
// The reps column is the total in every mode, unilateral included — the stepper walks in
// twos there so the number you land on is one you can actually split evenly.
const repCol = { f: 'r', step: repStep(cfg), dec: false, hd: t('Reps') }
const col1 = cardio ? { f: 'min', step: 1, dec: false, hd: t('Duration (min)') }
: timed ? { f: 'sec', step: 5, dec: false, hd: t('Seconds') }
: { f: 'w', step: 2.5, dec: true, hd: t('Weight ({0})', S.unit) }
: (bw && !added) ? repCol : loadCol
const col2 = cardio ? { f: 'speed', step: 0.5, dec: true, hd: t('Speed (km/h)') }
: timed ? { f: 'w', step: 2.5, dec: true, hd: t('Weight ({0})', S.unit) }
: { f: 'r', step: 1, dec: false, hd: t('Reps') }
: timed ? ((bw && !added) ? null : loadCol)
: (bw && !added) ? null : repCol
// Effort (RIR or RPE, whichever the profile logs) only makes sense for weighted rep sets,
// not cardio/timed holds, and is opt-in since it adds a third stepper to every row. `opt`
// because an unlogged effort is not the same as 0 — RIR 0 says the set went to failure.
@@ -106,6 +116,9 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
</div>
<div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}
{/* You log the total; this is the split, so the set in front of you is unambiguous
without the rep count having to mean two different things (issue #31). */}
{!cardio && !timed && isPerSide(cfg) && <span className="tag acc nocap"><Icon name="shuffle" />{t('{0} per side', fmtNum(sideReps(entry.sets.find(s => !s.done)?.r ?? entry.sets[0]?.r)))}</span>}
{(ex.tg || ex.bp) && <span className="tag">{t(ex.tg || ex.bp)}</span>}
{ex.eq && <span className="tag">{t(ex.eq)}</span>}
{best > 0 && <span className="tag nocap">{t('Best:')} {fmtNum(best)} {S.unit}</span>}
@@ -117,11 +130,11 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
</div>}
<div className="card" style={{ marginTop: 10, marginBottom: 0 }}>
{/* the header carries the same eff3 sizing as the rows, or the labels drift off their columns */}
<div className={'sethead' + (col3 ? ' eff3' : '')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span><span className="r-sp">{col2.hd}</span>{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>
<div className={'sethead' + (col3 ? ' eff3' : '')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span>{col2 && <span className="r-sp">{col2.hd}</span>}{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>
{entry.sets.map((s, i) => <div key={i} className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<div className="n">{i + 1}</div>
{cell(s, i, col1, 'w')}
{cell(s, i, col2, 'r')}
{col2 && cell(s, i, col2, 'r')}
{col3 && cell(s, i, col3, 'eff')}
{/* A timed set is started, not typed: the timer counts the hold down and checks the
set off itself. The checkbox stays for anyone who timed it on their own watch. */}
@@ -196,9 +209,11 @@ function ActiveWorkout() {
if (isLastExInUnit && !unitDone) startRest(S.restSec)
else if (unitDone) stopRest()
if (unitDone && isLastUnit) workoutDone = true // last exercise's last set → done
// Only reps training has a "working weight" worth confirming — a bodyweight plank
// has nothing to put in that slider.
if (e.sets.every(x => x.done)) { exJustDone = true; if (m === 'reps' && !e.asked) { e.asked = true; askTop = true } }
// Only loaded reps training has a "working weight" worth confirming — a bodyweight
// plank has nothing to put in that slider, and neither does a set of push-ups
// (issue #32: the fewest taps that still record what happened).
const loaded = m === 'reps' && !(isBw({ ...(e.target || {}), id: e.id }) && !e.sets.some(x => x.w > 0))
if (e.sets.every(x => x.done)) { exJustDone = true; if (loaded && !e.asked) { e.asked = true; askTop = true } }
}
})
// reps: topWeight first (it chains into the finish/continue prompt on the last unit).
+136
View File
@@ -0,0 +1,136 @@
# openGym MCP server
A [Model Context Protocol](https://modelcontextprotocol.io) bridge that lets an external LLM
application (Claude Desktop, Cursor, Cline, Continue, etc.) read your openGym profile —
routines, workouts, body-weight log, estimated 1RMs, and muscle balance — directly from your
self-hosted `./data` directory.
It is read-only, runs locally as a stdio process spawned by the LLM client, adds no new
container, and requires no extra authentication. The LLM never sees passkeys, VAPID keys, or
session secrets — it can only read the same `state-<uid>.json` files the openGym api already
writes.
The numbers it answers with are computed by the **same pure functions the React UI uses**
(`frontend/src/lib/*.js`) — `estimate1RM`, `loadOfWorkouts`, `effectiveRoutine`, etc. — so a
"what's my bench 1RM?" answer matches the Stats screen exactly.
> Phase 1 of a multi-phase plan. Read-only today; long-lived token auth + write tools are
> planned but not shipped yet. See **Roadmap** below.
## Quick start
### 1. Install
```bash
cd mcp
npm install
```
### 2. Point it at your data
The MCP server reads the same `./data` directory `docker compose up` creates. Pick the profile
to answer for — its user id is in `./data/db.json` under `users[].id`:
```bash
# single-user instance (the common self-hosted case) — auto-detected:
node src/index.js
# multi-user instance, or just to be explicit:
OPENGYM_UID=<your-uid> OPENGYM_DATA=/path/to/openGym/data node src/index.js
```
### 3. Register with your LLM client
Add the server to your LLM client's MCP config. For Claude Desktop, edit
`claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`):
```jsonc
{
"mcpServers": {
"opengym": {
"command": "node",
"args": ["/absolute/path/to/openGym/mcp/src/index.js"],
"env": {
"OPENGYM_DATA": "/absolute/path/to/openGym/data",
"OPENGYM_UID": "<your-uid>" // optional — auto-detected if you have one profile
}
}
}
}
```
For Cursor and other MCP-compatible clients, see the client's MCP docs — the same `command` +
`args` + `env` shape is what every stdio MCP server expects.
Restart the client; you should see the openGym tools appear with "serving profile \<name\>" on
the server's stderr.
## Tools
Eight read-only tools in v1:
| Tool | What it answers |
|---|---|
| `list_routines` | What routines are saved in my profile? (names + exercise counts) |
| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) |
| `get_week_plan` | What's on my plan this week, including today with any date-specific override? |
| `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. |
| `get_workout` | Full set-by-set breakdown of one session, by `workout_id` or by date. On a day with two sessions the date alone returns both ids to pick from rather than guessing at one. |
| `get_bodyweight` | Weigh-ins with the latest weight, the goal line, and deltas vs goal. |
| `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. |
| `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. |
Each tool returns JSON the LLM can format as it likes; structured fields (sets, dates, levels)
are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to
re-interpret them.
## How it reuses the training logic
The MCP server imports the training helpers under `frontend/src/lib/` directly as Node ESM
and calls the same functions the React UI does (`history.js`, `onerm.js`, `muscles.js`,
`exercises.js`). The numbers it returns match what the Stats screen shows, because they are
the same code.
The one lib file that wasn't Node-safe was `i18n.js` (Vite's `import.meta.glob` at module
top level) — split into `i18n-core.js` (pure, Node-safe) + `i18n.js` (Vite/React bits,
re-exports from core). `exercises.js` got a one-line `import.meta.env || {}` guard. No new
dependencies landed in `frontend/`, no public exports changed.
## Design constraints honoured
- **One runtime dependency beyond the MCP SDK:** none. No database driver, no HTTP framework.
- **No new container.** stdio transport is spawned by the LLM client; nothing to add to
`docker-compose.yml`.
- **No new auth.** The filesystem is the boundary — same as `docker compose` running on the
user's box. No passkey material, VAPID keys, or session secrets ever cross it.
- **No telemetry, no network.** Reads `./data/*.json` and exits when the LLM client
disconnects.
## Tests
```bash
cd mcp && npm test
```
32 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture
the public demo runs on). Pins JSON shape and the user-facing edge cases: rest-day override,
missing routine, zero-workout history, no synced state, superset links, three 1RM formulas.
"Today" is pinned via `vi.useFakeTimers({ now: ..., toFake: ['Date'] })` so date-dependent
tools see consistent values regardless of when the suite runs. The pure lib functions have
their own 92 tests in `frontend/src/lib/*.test.js`.
## Roadmap
- **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access.
- **Phase 1.5:** a `progression_next` tool (what does the policy prescribe next?). No new
deps; small surface area.
- **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the
admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify-
write of `state-<uid>.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`,
`assign_weekday`, `override_day`.
- **Phase 3:** Streamable HTTP transport, opt-in 4th container in `docker-compose.yml`. Same
tool implementations, second transport — the MCP SDK supports both behind one tool registration.
## License
AGPL-3.0-or-later, same as openGym.
+2465
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "opengym-mcp",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "MCP (Model Context Protocol) bridge for openGym \u2014 lets an external LLM read your routines, workouts, body-weight log, estimated 1RMs and muscle balance from your self-hosted data. Read-only, stdio transport; no extra container.",
"license": "AGPL-3.0-or-later",
"main": "src/index.js",
"bin": {
"opengym-mcp": "src/index.js"
},
"scripts": {
"start": "node src/index.js",
"test": "vitest run",
"check:node-loadable": "node scripts/check-node-loadable.mjs"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.4",
"zod": "^3.23.8"
},
"devDependencies": {
"vitest": "^4.1.10"
}
}
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env node
/* Does the server's import graph still load under plain node?
*
* This exists because the test suite cannot answer that question. `npm test` runs vitest, and
* vitest resolves modules through Vite — `import.meta.glob`, `?raw`, a stray `.jsx` import all
* work there. The server does not run under Vite. So a Vite-only import can land in a shared
* lib module, leave all 33 tests green, and still kill the server at startup. That is exactly
* what happened once: `history.js` began importing `t` from `i18n.js` (import.meta.glob over
* the locale packs, plus React), and the server died on `import` with the suite none the wiser.
*
* Run by bare `node` on purpose — being outside vitest IS the check. Do not port this to a
* vitest test file; that would make it pass unconditionally.
*
* Importing the two entry modules is enough on its own: everything the server touches hangs off
* them, so a lib module that grows a browser-only dependency next year fails here without this
* list being updated. The named list below only exists to point at the culprit instead of at a
* stack trace ten frames deep.
*/
const LIB = new URL('../../frontend/src/lib/', import.meta.url)
// Every frontend/src/lib module the server reaches today. Named individually so a failure says
// which one, rather than which import chain.
const MODULES = [
'i18n-core.js', 'format.js', 'exercises.js', 'exercises-data.js',
'history.js', 'muscles.js', 'onerm.js', 'progression.js'
]
let failed = 0
for (const m of MODULES) {
try {
await import(new URL(m, LIB))
console.log(` ok ${m}`)
} catch (e) {
failed++
console.error(` FAIL ${m} — ${e.message}`)
}
}
// The real assertion: the server's own entry points, which pull the whole graph transitively.
// A module added to the graph later is covered by this even if the list above never learns it.
for (const entry of ['../src/state.js', '../src/tools.js']) {
try {
await import(new URL(entry, import.meta.url))
console.log(` ok mcp/${entry.replace('../', '')}`)
} catch (e) {
failed++
console.error(` FAIL mcp/${entry.replace('../', '')} — ${e.message}`)
}
}
if (failed) {
console.error(`\n${failed} module(s) do not load under plain node — the MCP server would not start.`)
process.exit(1)
}
console.log('\nthe whole MCP import graph loads under plain node.')
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env node
/* openGym MCP server — stdio transport. The LLM client (Claude Desktop, Cursor, …) spawns
this process locally, talks JSON-RPC over stdin/stdout, tears it down when the session ends.
No extra container, no new outbound network — your data stays in a folder you control. */
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { TOOLS } from './tools.js'
import { init, getUser } from './state.js'
const server = new McpServer({
name: 'opengym',
version: '0.1.0'
})
// Fail fast on bad config so a misnamed OPENGYM_DATA doesn't silently answer every call with
// the no-state sentinel. Always register every tool so the LLM sees the full list at
// handshake, even when state didn't resolve.
try {
init()
const u = getUser()
console.error(`[opengym-mcp] serving profile ${u.name} (${u.id})`)
} catch (e) {
console.error(`[opengym-mcp] ${e.message}`)
// Don't exit — keep the tool listings up so the user sees a useful error after fixing their
// env and restarting.
}
for (const t of TOOLS) {
server.tool(
t.name,
t.description,
t.schema,
async (params) => {
try {
const result = t.handler(params || {})
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] }
} catch (err) {
const code = err.code || 'ERROR'
return {
isError: true,
content: [{ type: 'text', text: `${code}: ${err.message}` }]
}
}
}
)
}
const transport = new StdioServerTransport()
await server.connect(transport)
// Process stays alive serving JSON-RPC over stdio until the LLM client disconnects.
+47
View File
@@ -0,0 +1,47 @@
// Formatting glue between lib helpers (which speak {0}/{1} templates) and the JSON returned
// to the LLM.
import { MUSCLE_NAME, MUSCLES } from '../../frontend/src/lib/muscles.js'
import { modeOf, fmtSec, setLabel } from '../../frontend/src/lib/history.js'
import { POLICY_NAME } from '../../frontend/src/lib/progression.js'
import { fmtDate, fmtNum, fmtDur } from '../../frontend/src/lib/format.js'
// Apply {0},{1},… substitutions to the template strings the lib returns.
export function fmt(template, args) {
let v = template
for (let i = 0; i < (args || []).length; i++) v = v.replaceAll('{' + i + '}', String(args[i]))
return v
}
export { setLabel }
export function exLine(cfg, unit) {
const mode = modeOf(cfg)
const n = cfg.sets || 1
const load = cfg.weight ? ' · ' + fmtNum(cfg.weight) + ' ' + unit : ''
if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h`
if (mode === 'time') return `${n} × ${fmtSec(cfg.sec || 45)}${load}`
return `${n} × ${cfg.reps}${load}`
}
export function muscleName(slug) {
return MUSCLE_NAME[slug] || slug
}
export function policyName(policy) {
return POLICY_NAME[policy] || policy
}
export function friendlyDate(iso) {
if (!iso) return null
return fmtDate(iso)
}
export function friendlyDuration(ms) {
return ms ? fmtDur(ms) : null
}
export function ratio(done, total) {
return `${done}/${total}`
}
export function muscleOrder() { return MUSCLES.slice() }
+137
View File
@@ -0,0 +1,137 @@
/* opengym-mcp state — reads ./data/state-<uid>.json + db.json (read-only). Cached with an
fs.watch + mtime fallback so a session the api server just wrote is visible on the next
tool call without a restart. */
import fs from 'node:fs'
import path from 'node:path'
const DATA_DIR = process.env.OPENGYM_DATA || path.join(process.cwd(), 'data')
// null = no state file (brand-new account); undefined = not yet loaded.
let _state = undefined
let _db = undefined
let _uid = null
let _watcher = null
let _loadedMtime = 0 // mtimeMs we last read at — used to catch watcher omissions
function readJsonOrNull(file) {
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
}
function reloadDb() { _db = readJsonOrNull(path.join(DATA_DIR, 'db.json')) || { users: [], creds: [], subs: [], invites: [] } }
function stateFile(uid) {
return path.join(DATA_DIR, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json')
}
// Pick the uid: OPENGYM_UID env, else the only state-* file, else the only user in db.json.
// Throws listing the options if ambiguous. The sanitiser on stateFile() keeps a sneaky
// '..' in OPENGYM_UID harmless.
function resolveUid() {
const envUid = (process.env.OPENGYM_UID || '').trim()
if (envUid) {
if (!/^[a-zA-Z0-9_-]+$/.test(envUid)) throw new Error(`OPENGYM_UID contains characters that aren't safe in a filename: ${JSON.stringify(envUid)}`)
return envUid
}
const files = fs.readdirSync(DATA_DIR)
.filter(f => /^state-[a-zA-Z0-9_-]+\.json$/.test(f))
.map(f => f.replace(/^state-/, '').replace(/\.json$/, ''))
if (files.length === 1) return files[0]
if (files.length === 0) {
reloadDb()
if (_db.users.length === 1) return _db.users[0].id
if (_db.users.length === 0) throw new Error(`no openGym users found in ${path.join(DATA_DIR, 'db.json')} — sign in at least once on a device`)
// Multiple users in db.json but no state files yet — list their ids, not the (empty)
// files list. Hit when accounts exist but none has signed in on a device.
throw new Error(
`multiple openGym users found — set OPENGYM_UID to one of: ${_db.users.map(u => u.id).join(', ')}\n` +
` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`
)
}
throw new Error(
`multiple openGym users found — set OPENGYM_UID to one of: ${files.join(', ')}\n` +
` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`
)
}
// Idempotent. Picks the uid, loads db.json, attaches the watcher, primes state.
export function init() {
if (_uid !== null) return
if (!fs.existsSync(DATA_DIR)) throw new Error(`OPENGYM_DATA dir does not exist: ${DATA_DIR}`)
_uid = resolveUid()
reloadDb()
const file = stateFile(_uid)
if (fs.existsSync(file)) {
_state = readJsonOrNull(file)
if (_state) _state = Object.assign({}, defaultsShape(), _state)
try { _loadedMtime = fs.statSync(file).mtimeMs } catch {}
}
if (_watcher) _watcher.close()
// fs.watch is best-effort: the api server's atomic write at PUT /api/data is the source of
// truth, and a stale read just gets corrected on the next change or the next tool call.
try {
_watcher = fs.watch(file, () => {
// On change, simply clear the cache — the next getState() will re-read. Avoids reading
// twice if the watcher fires multiple events for one atomic-write (rename + create).
_state = undefined
_loadedMtime = 0
})
// Unref'd, or the watcher alone holds the event loop open and the process outlives the
// client that spawned it — "exits when the LLM client disconnects" stops being true the
// moment there is a state file to watch. Most clients kill the child anyway, but one that
// merely closes the pipe would leak a process per session. Watching is unaffected: the
// stdio transport is what keeps the loop alive while a client is actually attached.
_watcher.unref()
} catch { /* fs.watch unsupported on this platform; tools will re-read on mtime change */ }
}
// Returns the state object, or null for a fresh account that never signed in on a device.
export function getState() {
init()
const file = stateFile(_uid)
// Re-read if the file's mtime changed since our last load — covers watcher omissions and
// platforms with no fs.watch.
let mtime
try { mtime = fs.statSync(file).mtimeMs } catch {
return _state === undefined ? null : _state
}
if (_state === undefined || mtime !== _loadedMtime) {
const fresh = readJsonOrNull(file)
if (fresh) {
// Same shape the frontend builds on pullState — defaults merged with stored state so any
// field the app added since the snapshot was last saved shows up undefined-safe.
_state = Object.assign({}, defaultsShape(), fresh)
_loadedMtime = mtime
} else if (_state === undefined) {
_state = null // no state file at all — never signed in on a device
}
}
return _state
}
// Returns the user record (id + name). No passkey material, no VAPID keys, no push subs.
export function getUser() {
init()
const u = _db.users.find(x => x.id === _uid) || { id: _uid, name: 'Profile', created: null }
return { id: u.id, name: u.name, created: u.created || null }
}
export const dataDir = () => DATA_DIR
// Test-only: work against a passed-in state, not the disk.
export function _seedStateForTests(state) {
_uid = 'test-uid'
_db = { users: [{ id: _uid, name: 'Test', created: '2026-07-26T00:00:00.000Z' }], creds: [], subs: [], invites: [] }
_state = state
_loadedMtime = Number.MAX_SAFE_INTEGER // never re-read from disk in a test
if (_watcher) { _watcher.close(); _watcher = null }
}
function defaultsShape() {
return {
unit: 'kg', restSec: 90, sound: true, lang: 'en',
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], customEx: [], gifSize: 'full',
reminder: { on: false, time: '08:00', tz: null }
}
}
+389
View File
@@ -0,0 +1,389 @@
/* The eight read-only tools. Each handler returns JSON; labels.js pre-substitutes any
{0}/{1} template the lib returns so the LLM gets final text, not template strings.
ISO dates are validated on the way in; the handlers never see 'yesterday'. */
import { z } from 'zod'
import { getState, getUser } from './state.js'
import {
setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder
} from './labels.js'
import {
modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId
} from '../../frontend/src/lib/history.js'
import { EXIDX, exOr } from '../../frontend/src/lib/exercises.js'
import {
estimate1RM, best1RM, e1rmSeries, DEFAULT_FORMULA, REP_CAP
} from '../../frontend/src/lib/onerm.js'
import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js'
/* ---------- helpers ---------- */
function entryView(e, S) {
const ex = exOr(e.id)
// Spread id into the cfg the way every call site in the app does (Workout.jsx, Stats.jsx,
// progression.js) — the sheet saves a cardio target as {sets, min, speed} with no id and no
// mode, so modeOf needs the id to fall through to isCardio(id).
const cfg = { ...(e.target || {}), id: e.id }
const mode = modeOf(cfg)
return {
id: e.id,
name: ex.n,
body_part: ex.bp || null,
mode,
target: e.target || null,
sets: (e.sets || []).map(s => ({
done: !!s.done,
label: setLabel(e.id, { ...s, done: undefined }, cfg),
w: Number(s.w) || 0,
r: Number(s.r) || 0,
sec: Number(s.sec) || 0,
min: Number(s.min) || 0,
speed: Number(s.speed) || 0
}))
}
}
// Best estimate per exercise, mirroring the UI's PR table: every eligible set across history, biggest wins.
function prTable(S, formula) {
const byId = new Map()
for (const w of (S.workouts || [])) {
for (const e of (w.entries || [])) {
for (const s of (e.sets || [])) {
if (!s.done) continue
const est = estimate1RM(s.w, s.r, formula)
if (est == null) continue
const ex = exOr(e.id)
const prev = byId.get(e.id)
if (!prev || est > prev.est) {
// exId as well as exName: the consumer needs an id, not a name — exOr() treats any
// string as both, so passing exName where exId belongs would silently "work" wrong.
byId.set(e.id, { exId: e.id, exName: ex.n, bp: ex.bp || null, est, w: Number(s.w), r: Math.round(Number(s.r)), date: w.d })
}
}
}
}
return [...byId.values()].sort((a, b) => b.est - a.est)
}
/* ---------- the 8 tools ---------- */
/** list_routines — names + counts of each routine in the user's plan. */
export const listRoutines = {
name: 'list_routines',
description: 'List the workout routines saved in the user\'s openGym profile (the same list the Plan screen shows). Each routine is a named set of exercises with set/rep targets. Use this to discover the plan structure before diving into a specific routine or today\'s workout.',
schema: {},
handler: () => {
const S = getState()
if (!S) return noState()
return {
unit: S.unit || 'kg',
routines: (S.routines || []).map(r => ({
id: r.id,
name: r.name,
emoji: r.emoji || null,
exercise_count: (r.ex || []).length,
superset_groups: [...new Set((r.ex || []).map(e => e.sg).filter(Boolean))].length || 0,
policy: r.policy || 'off'
}))
}
}
}
/** get_routine — the full exercise list for one routine, including set/rep targets. */
export const getRoutine = {
name: 'get_routine',
description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.',
schema: { routine_id: z.string().min(1) },
handler: ({ routine_id }) => {
const S = getState()
if (!S) return noState()
const r = (S.routines || []).find(x => x.id === routine_id)
if (!r) { const e = new Error(`no routine with id ${JSON.stringify(routine_id)}`); e.code = 'ENOENT'; throw e }
return {
id: r.id,
name: r.name,
emoji: r.emoji || null,
policy: r.policy || 'off',
policy_name: policyName(r.policy || 'off'),
unit: S.unit || 'kg',
exercises: (r.ex || []).map((cfg, i) => {
const ex = exOr(cfg.id)
const mode = modeOf(cfg)
return {
position: i + 1,
id: cfg.id,
name: ex.n,
body_part: ex.bp || null,
mode,
sets: cfg.sets || 1,
reps: mode === 'reps' ? (cfg.reps || 0) : undefined,
reps_min: mode === 'reps' && cfg.repsMin != null ? cfg.repsMin : undefined,
sec: mode === 'time' ? (cfg.sec || 0) : undefined,
min: mode === 'cardio' ? (cfg.min || 0) : undefined,
speed: mode === 'cardio' ? (cfg.speed || 0) : undefined,
weight: cfg.weight != null ? cfg.weight : undefined,
increment: cfg.inc != null ? cfg.inc : undefined,
policy_override: cfg.policy || null,
superset_group: cfg.sg || null,
summary: exLine(cfg, S.unit || 'kg')
}
})
}
}
}
/** get_week_plan — what's scheduled each weekday + today. */
export const getWeekPlan = {
name: 'get_week_plan',
description: 'Show the user\'s weekly plan: which routine (if any) is assigned to each weekday, keyed by JS getDay() (Sunday=0, Monday=1, … Saturday=6 — the same convention the openGym state file uses). Also reports today\'s date and what routine applies today, accounting for one-off overrides the user may have set for a specific date (a "rest" override cancels the day).',
schema: {},
handler: () => {
const S = getState()
if (!S) return noState()
const today = new Date()
const isoToday = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0')
const todayWd = today.getDay()
return {
today: isoToday,
weekdays: [0, 1, 2, 3, 4, 5, 6].map(d => {
const rid = S.week?.[d] || null
const r = rid ? (S.routines || []).find(x => x.id === rid) : null
// Surface today's override only (not the whole dayPlan dict — usually empty, but might
// have grown from repeated "move this day" actions).
const overrideForToday = d === todayWd ? (S.dayPlan?.[isoToday] ?? null) : null
return {
weekday: d,
weekday_name: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d],
routine_id: rid,
routine_name: r?.name || null,
routine_emoji: r?.emoji || null,
override_for_today_or_null: overrideForToday
}
}),
today_routine_id: effectiveRoutineId(S, isoToday),
today_routine_name: effectiveRoutine(S, isoToday)?.name || null
}
}
}
/** list_workouts — newest-first summary of recent sessions. */
export const listWorkouts = {
name: 'list_workouts',
description: 'List recent finished workouts, newest first. Each item summarises the date, exercise count, sets done / planned, total volume (in the user\'s unit), duration and whether PRs were set. Use this before drilling into a specific date with get_workout.',
schema: {
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD. Defaults to no lower bound (list most recent).'),
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.'),
limit: z.number().int().min(1).max(200).optional().describe('Max items to return. Defaults to 25.')
},
handler: ({ from, to, limit }) => {
const S = getState()
if (!S) return noState()
const lim = Math.min(Math.max(limit || 25, 1), 200)
const all = (S.workouts || []).slice().sort((a, b) => (b.d || '').localeCompare(a.d || ''))
const filtered = all.filter(w => {
if (from && w.d < from) return false
if (to && w.d > to) return false
return true
}).slice(0, lim)
return {
unit: S.unit || 'kg',
total_count: all.length,
returned_count: filtered.length,
workouts: filtered.map(w => ({
// The only thing that identifies a session uniquely. Two workouts on one day is
// ordinary — a lifting session and an evening run — and without an id here the second
// one cannot be asked about at all.
id: w.id || null,
date: w.d,
routine_id: w.routineId || null,
routine_name: w.name || null,
exercise_count: (w.entries || []).length,
sets_done: setsDone(w),
sets_planned: plannedSets(w),
sets_ratio: ratio(setsDone(w), plannedSets(w)),
volume: workoutVolume(w),
duration_ms: w.end && w.start ? (w.end - w.start) : null,
duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null,
prs: (w.prs || []).length,
bodyweight_at_workout: w.bw || null
}))
}
}
}
function plannedSets(w) {
let n = 0
;(w.entries || []).forEach(e => { n += (e.sets || []).length })
return n
}
/** get_workout — full entry/set breakdown for one date. */
export const getWorkout = {
name: 'get_workout',
description: 'Get the full breakdown of one workout: every exercise, its mode (reps/time/cardio), the target, and per-set labels (e.g. "5 @ 60 kg", "1:30 · 20 kg"). Identify it by workout_id (from list_workouts) or by date. Use list_workouts first if you don\'t know either.',
schema: {
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('The workout date as YYYY-MM-DD. If two sessions share that date, the answer lists them instead and asks for a workout_id.'),
workout_id: z.string().min(1).optional().describe('The id from list_workouts. Preferred: it names one session even on a day with two.')
},
handler: ({ date, workout_id }) => {
const S = getState()
if (!S) return noState()
const workouts = S.workouts || []
let w
if (workout_id) {
w = workouts.find(x => x.id === workout_id)
if (!w) { const e = new Error(`no workout with id ${workout_id}`); e.code = 'ENOENT'; throw e }
} else if (date) {
const sameDay = workouts.filter(x => x.d === date)
if (!sameDay.length) { const e = new Error(`no workout on ${date}`); e.code = 'ENOENT'; throw e }
// Answering with the first of two is how a question about the evening run gets the
// morning's lifting numbers, stated with total confidence. Say there are two instead.
if (sameDay.length > 1) {
return {
ambiguous: true,
date,
message: `${sameDay.length} workouts were logged on ${date} — call get_workout again with one of these workout_id values.`,
workouts: sameDay.map(x => ({
id: x.id || null,
routine_name: x.name || null,
sets_done: setsDone(x),
volume: workoutVolume(x),
duration: x.end && x.start ? friendlyDuration(x.end - x.start) : null
}))
}
}
w = sameDay[0]
} else {
const e = new Error('get_workout needs either workout_id or date'); e.code = 'EINVAL'; throw e
}
return {
id: w.id || null,
date: w.d,
routine_id: w.routineId || null,
routine_name: w.name || null,
unit: S.unit || 'kg',
bodyweight_at_workout: w.bw || null,
volume: workoutVolume(w),
sets_done: setsDone(w),
sets_planned: plannedSets(w),
duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null,
prs: (w.prs || []).map(id => EXIDX[id]?.n || id),
entries: (w.entries || []).map(e => entryView(e, S))
}
}
}
/** get_bodyweight — recent weigh-ins with the goal line. */
export const getBodyweight = {
name: 'get_bodyweight',
description: 'Get the body-weight log: chronological weigh-ins with weights, current goal, deltas vs goal (signed positive = above goal), and a latest summary. Useful for "am I trending toward my weight goal?" questions.',
schema: {
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD.'),
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.')
},
handler: ({ from, to }) => {
const S = getState()
if (!S) return noState()
const goal = S.targetW || null
const bw = (S.bodyweight || []).filter(b => {
if (from && b.d < from) return false
if (to && b.d > to) return false
return true
}).sort((a, b) => (a.d || '').localeCompare(b.d || ''))
const latest = bw.length ? bw[bw.length - 1] : null
return {
unit: S.unit || 'kg',
goal,
count: bw.length,
latest: latest ? { date: latest.d, weight: latest.w, delta_vs_goal: goal != null ? Math.round((latest.w - goal) * 10) / 10 : null } : null,
entries: bw.map(b => ({
date: b.d,
weight: b.w,
delta_vs_goal: goal != null ? Math.round((b.w - goal) * 10) / 10 : null
}))
}
}
}
/** estimate_1rm — best-ever 1RM for one exercise or a PR table across all reps-mode exercises. */
export const estimate1rm = {
name: 'estimate_1rm',
description: `Estimate one-rep max using Epley, Brzycki or Lombardi formulas. If an exercise_id is given, returns the all-time best estimate for that exercise with the source set (weight × reps + date) and the trend across history. If no exercise_id is given, returns a PR table across all reps-mode exercises (sorted highest first). Refuses to guess above ${REP_CAP} reps — above that, formulas diverge past 10% and "work capacity" is read instead of "maximal strength".`,
schema: {
exercise_id: z.string().optional().describe('An exercise id from list_routines or get_workout entries. If omitted, returns a full PR table.'),
formula: z.enum(['epley', 'brzycki', 'lombardi']).optional().describe(`Formula to use. Defaults to ${DEFAULT_FORMULA}.`)
},
handler: ({ exercise_id, formula }) => {
const S = getState()
if (!S) return noState()
const f = formula || DEFAULT_FORMULA
if (exercise_id) {
const ex = exOr(exercise_id)
const best = best1RM(S, exercise_id, f)
const series = e1rmSeries(S, exercise_id, f)
// A null best has two very different causes: never trained, or trained only above the
// rep cap. Without saying which, an exercise logged for years at 15 reps reads as "no
// records for calf raise" — a confident statement about the opposite of the truth.
const trainedAtAll = (S.workouts || []).some(w =>
(w.entries || []).some(e => e.id === exercise_id && (e.sets || []).some(s => s.done)))
// w/r (not weight/reps) matches pr_table and entry-view — every set in the API surface uses the same couple.
return {
exercise: { id: exercise_id, name: ex.n, body_part: ex.bp || null },
formula: f,
formula_note: `Estimates use the ${f} formula. Cap at ${REP_CAP} reps applies; r=1 is treated as the measurement, not an estimate.`,
best: best ? { est: best.est, w: best.w, r: best.r, date: best.d } : null,
no_estimate_reason: best ? null
: trainedAtAll
? `This exercise has logged sets, but none of them qualify: every set was above the ${REP_CAP}-rep cap, or carried no weight. That is not the same as never having trained it.`
: 'No completed sets logged for this exercise.',
trend: series.map(p => ({ date: p.d, est: p.y, w: p.w, r: p.r }))
}
}
return {
formula: f,
formula_note: `Estimates use the ${f} formula. Cap at ${REP_CAP} reps applies; r=1 is treated as the measurement, not an estimate.`,
pr_table: prTable(S, f)
}
}
}
/** muscle_balance — training distribution per muscle over a period (week/month/all). */
export const muscleBalance = {
name: 'muscle_balance',
description: 'Show which muscles the user has trained in a period, ranked by "effective sets" (volume in kg is intentionally not used — 100 kg leg press vs 12 kg lateral raise say nothing about which muscle worked harder). Reports worked muscles with a 0-4 relative level (1 = some work, 4 = most worked) and the muscles trained zero times in that period — useful for "what am I neglecting?" questions.',
schema: {
period: z.enum(['week', 'month', 'all']).describe('window: last 7 days, last 30 days, or all-time')
},
handler: ({ period }) => {
const S = getState()
if (!S) return noState()
const now = Date.now()
const cutoff = period === 'week' ? now - 7 * 86400000
: period === 'month' ? now - 30 * 86400000
: Number.NEGATIVE_INFINITY
const workouts = (S.workouts || []).filter(w => (w.start || new Date(w.d + 'T12:00:00').getTime()) >= cutoff)
const load = loadOfWorkouts(workouts)
const { worked, missed } = rankOf(load)
const levels = levelsOf(load)
return {
period,
cutoff_iso: period === 'all' ? null : new Date(cutoff).toISOString().slice(0, 10),
workouts_in_period: workouts.length,
worked: worked.map(slug => ({ slug, name: muscleName(slug), level: levels[slug], effective_sets: Math.round((load[slug] || 0) * 10) / 10 })),
neglected: missed.map(slug => ({ slug, name: muscleName(slug) })),
muscle_order_head_to_toe: muscleOrder()
}
}
}
/* ---------- registration list ---------- */
export const TOOLS = [
listRoutines, getRoutine, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
]
function noState() {
return {
error: 'no synced state yet — sign in at least once from a device so the openGym api can save a state file for this profile',
unit: 'kg'
}
}
+535
View File
@@ -0,0 +1,535 @@
// Tool-layer tests for mcp/src/tools.js, seeded from frontend/src/lib/demoSeed.js — the same
// deterministic fixture the public demo runs on. The pure lib functions have their own 92
// tests in frontend/src/lib/*.test.js; here we pin JSON shape + the user-facing edge cases
// (rest-day override, missing routine, zero-workout history, no synced state, superset links).
import { describe, beforeAll, afterAll, beforeEach, test, expect, vi } from 'vitest'
import { buildDemoState } from '../../frontend/src/lib/demoSeed.js'
import { EXDB } from '../../frontend/src/lib/exercises.js'
import { _seedStateForTests } from '../src/state.js'
import { TOOLS } from '../src/tools.js'
// Re-stated here so the assertions stand alone without reaching into lib internals to learn
// the demo state's exact values.
const FAKE_TODAY_ISO = '2026-07-27' // Monday — Push Day is scheduled
const GOAL_WEIGHT = 77
// Re-pinned against the v1.2.4 seed, which moved when the demo learned about bodyweight work
// and effort. Hand-checked rather than copied off a failing run: 18412.5 is the sum of w×r
// over the twenty completed sets, and 1.3 is 78.3 − 77.
const NEWEST_WORKOUT = { date: '2026-07-24', name: 'Leg Day', volume: 18412.5, bw: 78.4, sets_done: 20, sets_total: 20, duration: '1h 11m' }
const LATEST_BW = { date: '2026-07-27', weight: 78.3, delta: 1.3 }
const LEG_PRESS_ID = '0739' // sled 45° leg press in the demo data
const LEG_PRESS_BEST = { w: 152.5, r: 12, epley: 213.5, brzycki: 219.6 }
const byName = Object.fromEntries(TOOLS.map(t => [t.name, t.handler]))
let S = null
function call(name, params = {}) {
const h = byName[name]
if (!h) throw new Error(`unknown tool ${name}`)
return h(params)
}
function freshState() {
const s = buildDemoState()
s.unit = 'kg'
return s
}
// Pin "today" before building state so dayPlan/week alignment matches the assertions below.
// `toFake: ['Date']` only — keeps fs.watch and the rest of the event loop real.
beforeAll(() => {
vi.useFakeTimers({ now: new Date(FAKE_TODAY_ISO + 'T12:00:00Z'), toFake: ['Date'] })
S = freshState()
_seedStateForTests(S)
})
afterAll(() => {
vi.useRealTimers()
})
// Fresh state per test — tests that mutate dayPlan can't leak into siblings.
beforeEach(() => {
S = freshState()
_seedStateForTests(S)
})
/* ---------- list_routines ---------- */
describe('list_routines', () => {
test('returns the three starter routines with names + counts', () => {
const r = call('list_routines')
expect(r.unit).toBe('kg')
expect(r.routines.length).toBe(3)
expect(r.routines.map(x => x.name).sort()).toEqual(['Leg Day', 'Pull Day', 'Push Day'])
r.routines.forEach(rn => {
expect(typeof rn.id).toBe('string')
expect(rn.exercise_count).toBeGreaterThan(0)
expect(typeof rn.superset_groups).toBe('number')
expect(['off', 'linear', 'greyskull', 'double', 'time']).toContain(rn.policy)
})
})
test('list_routines entries line up with get_routine (no id drift)', () => {
const list = call('list_routines').routines
list.forEach(summary => {
const detail = call('get_routine', { routine_id: summary.id })
expect(detail.id).toBe(summary.id)
expect(detail.name).toBe(summary.name)
expect(detail.exercises.length).toBe(summary.exercise_count)
})
})
})
/* ---------- get_routine ---------- */
describe('get_routine', () => {
test('returns the full exercise list for Push Day with per-exercise summaries', () => {
const push = call('list_routines').routines.find(x => x.name === 'Push Day')
const r = call('get_routine', { routine_id: push.id })
expect(r.name).toBe('Push Day')
expect(r.exercises.length).toBe(push.exercise_count)
expect(r.policy_name).toBeTruthy()
r.exercises.forEach(e => {
expect(['reps', 'time', 'cardio']).toContain(e.mode)
// Every summary has "N × M" with a non-ASCII × (the lib uses U+00D7, not ASCII 'x')
expect(e.summary).toMatch(/\d+\s*×\s*\d+/)
expect(e.superset_group === null || typeof e.superset_group === 'string').toBe(true)
})
})
test('throws ENOENT on a bogus routine id', () => {
expect(() => call('get_routine', { routine_id: 'bogus' })).toThrow()
})
test('reports superset links when an adjacent pair shares an sg id', () => {
// Inject a superset pair into a clone, since the starter plan has none.
S.routines[0].ex[0].sg = 'A'
S.routines[0].ex[1].sg = 'A'
const r = call('get_routine', { routine_id: S.routines[0].id })
expect(r.exercises[0].superset_group).toBe('A')
expect(r.exercises[1].superset_group).toBe('A')
expect(r.exercises[2].superset_group).toBeNull()
})
test('preserves mode + per-mode fields for a timed entry and a cardio entry', () => {
// Append synthetic entries the starter plan doesn't ship: a timed plank (sec, no w) and a
// cardio treadmill block (min + speed). These exercise ids don't exist in EXDB, so exOr
// returns a placeholder named "Unknown exercise" — that's fine, we test the cfg fields.
const push = S.routines.find(r => r.name === 'Push Day')
push.ex.push({ id: 'synth-plank', sets: 3, sec: 60, weight: 0, mode: 'time' })
push.ex.push({ id: 'synth-treadmill', sets: 1, min: 20, speed: 8, mode: 'cardio' })
const r = call('get_routine', { routine_id: push.id })
const t = r.exercises[r.exercises.length - 2]
const c = r.exercises[r.exercises.length - 1]
expect(t.mode).toBe('time')
expect(t.sec).toBe(60)
expect(t.reps).toBeUndefined()
expect(c.mode).toBe('cardio')
expect(c.min).toBe(20)
expect(c.speed).toBe(8)
})
})
/* ---------- get_week_plan ---------- */
describe('get_week_plan', () => {
test('reports each weekday in getDay() order (Sunday=0 … Saturday=6) with names', () => {
const r = call('get_week_plan')
expect(r.weekdays.length).toBe(7)
expect(r.weekdays.map(d => d.weekday)).toEqual([0, 1, 2, 3, 4, 5, 6])
expect(r.weekdays.map(d => d.weekday_name))
.toEqual(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
})
test('today is the pinned Monday, and Push Day is scheduled', () => {
const r = call('get_week_plan')
expect(r.today).toBe(FAKE_TODAY_ISO)
const push = S.routines.find(x => x.name === 'Push Day')
expect(r.today_routine_id).toBe(push.id)
expect(r.today_routine_name).toBe('Push Day')
})
test('week[1]/[3]/[5] map to Push/Pull/Leg, other weekdays are rest', () => {
const r = call('get_week_plan')
const byWd = Object.fromEntries(r.weekdays.map(d => [d.weekday, d]))
expect(byWd[1].routine_name).toBe('Push Day')
expect(byWd[3].routine_name).toBe('Pull Day')
expect(byWd[5].routine_name).toBe('Leg Day')
;[0, 2, 4, 6].forEach(wd => {
expect(byWd[wd].routine_id).toBeNull()
expect(byWd[wd].routine_name).toBeNull()
})
})
test('a "rest" override on today cancels the scheduled routine', () => {
// Sanity check first — without the override, today has a routine.
const before = call('get_week_plan')
expect(before.today_routine_id).not.toBeNull()
S.dayPlan[FAKE_TODAY_ISO] = 'rest'
const after = call('get_week_plan')
expect(after.today_routine_id).toBeNull()
expect(after.today_routine_name).toBeNull()
// The override is surfaced on the matching weekday entry.
const todayWd = new Date(FAKE_TODAY_ISO + 'T12:00:00Z').getDay()
expect(after.weekdays.find(d => d.weekday === todayWd).override_for_today_or_null).toBe('rest')
})
test('a routine-id override on today replaces the weekday default', () => {
const legs = S.routines.find(r => r.name === 'Leg Day')
S.dayPlan[FAKE_TODAY_ISO] = legs.id
const r = call('get_week_plan')
expect(r.today_routine_id).toBe(legs.id)
expect(r.today_routine_name).toBe('Leg Day')
})
test('empty week + no override → today has no routine (a quiet Sunday)', () => {
S.week = {}
S.dayPlan = {}
const r = call('get_week_plan')
expect(r.today_routine_id).toBeNull()
expect(r.today_routine_name).toBeNull()
r.weekdays.forEach(d => expect(d.routine_id).toBeNull())
})
})
/* ---------- list_workouts ---------- */
describe('list_workouts', () => {
test('newest first, with computed volume/duration matching hand-calculated values', () => {
const r = call('list_workouts', {})
expect(r.returned_count).toBeGreaterThan(0)
expect(r.total_count).toBeGreaterThanOrEqual(r.returned_count)
// newest-first check
const dates = r.workouts.map(w => w.date)
expect([...dates].sort().reverse()).toEqual(dates)
// The newest workout is the Friday before the pinned Monday today.
expect(r.workouts[0].date).toBe(NEWEST_WORKOUT.date)
expect(r.workouts[0].routine_name).toBe(NEWEST_WORKOUT.name)
expect(r.workouts[0].volume).toBe(NEWEST_WORKOUT.volume)
expect(r.workouts[0].sets_done).toBe(NEWEST_WORKOUT.sets_done)
expect(r.workouts[0].sets_planned).toBe(NEWEST_WORKOUT.sets_total)
expect(r.workouts[0].sets_ratio).toBe(`${NEWEST_WORKOUT.sets_done}/${NEWEST_WORKOUT.sets_total}`)
// Past the hour the lib switches format, so the expectation carries the rendered string
// rather than assuming a "N min" shape that only held while the session was shorter.
expect(r.workouts[0].duration).toBe(NEWEST_WORKOUT.duration)
expect(r.workouts[0].bodyweight_at_workout).toBe(NEWEST_WORKOUT.bw)
r.workouts.forEach(w => {
expect(w.sets_done).toBeLessThanOrEqual(w.sets_planned)
expect(typeof w.volume).toBe('number')
expect(w.sets_ratio).toMatch(/^\d+\/\d+$/)
})
})
test('date range filter narrows results (closed interval, both endpoints inclusive)', () => {
const all = call('list_workouts')
expect(all.workouts.length).toBeGreaterThan(2)
const earliest = all.workouts[all.workouts.length - 1].date
// closed on both ends — earliest's own date should still appear
const restricted = call('list_workouts', { from: earliest, to: earliest })
expect(restricted.returned_count).toBe(1)
expect(restricted.workouts[0].date).toBe(earliest)
})
test('a from > to range yields zero workouts (not an error, not silently everything)', () => {
const r = call('list_workouts', { from: '2026-07-27', to: '2026-01-01' })
expect(r.returned_count).toBe(0)
expect(r.workouts).toEqual([])
expect(r.total_count).toBeGreaterThan(0) // total still reflects the real history
})
test('respects limit (caps returned_count, never total_count)', () => {
const r = call('list_workouts', { limit: 3 })
expect(r.returned_count).toBeLessThanOrEqual(3)
expect(r.total_count).toBeGreaterThanOrEqual(r.returned_count)
})
})
/* ---------- get_workout ---------- */
describe('get_workout', () => {
test('matches the newest workout from list_workouts, every set has a readable label', () => {
const list = call('list_workouts', {}).workouts
const w = call('get_workout', { date: list[0].date })
expect(w.date).toBe(list[0].date)
expect(w.entries.length).toBe(list[0].exercise_count)
expect(w.volume).toBe(list[0].volume)
w.entries.forEach(e => {
expect(['reps', 'time', 'cardio']).toContain(e.mode)
e.sets.forEach(s => {
expect(typeof s.label).toBe('string')
expect(s.label.length).toBeGreaterThan(0)
})
})
})
test('throws ENOENT on a date with no workout', () => {
expect(() => call('get_workout', { date: '1900-01-01' })).toThrow()
})
test('two sessions on one day are both reachable, and the date alone never picks one silently', () => {
// Lifting in the morning, a run in the evening: ordinary, and it used to make the second
// session unreachable while questions about it were answered with the first one's numbers.
const day = '2026-07-26'
S.workouts.push(
{ id: 'w-morning', d: day, name: 'Pull', start: 1000, end: 1000 + 40 * 60000, vol: 0, prs: [], entries: [] },
{ id: 'w-evening', d: day, name: 'Cardio', start: 2000, end: 2000 + 55 * 60000, vol: 0, prs: [], entries: [] }
)
_seedStateForTests(S)
const amb = call('get_workout', { date: day })
expect(amb.ambiguous).toBe(true)
expect(amb.workouts.map(w => w.id).sort()).toEqual(['w-evening', 'w-morning'])
// Each is retrievable by the id the ambiguous answer handed back.
expect(call('get_workout', { workout_id: 'w-evening' }).routine_name).toBe('Cardio')
expect(call('get_workout', { workout_id: 'w-morning' }).routine_name).toBe('Pull')
// And list_workouts carries the id, or nothing above could ask for one.
expect(call('list_workouts', {}).workouts.every(w => 'id' in w)).toBe(true)
})
test('an unknown workout_id is an error, not the wrong workout', () => {
expect(() => call('get_workout', { workout_id: 'nope' })).toThrow()
expect(() => call('get_workout', {})).toThrow()
})
test('renders reps/time/cardio set labels in the lib format on a synthetic workout', () => {
// The starter routine has only reps-mode exercises — synthesise a workout that includes a
// timed plank and a cardio row so the label rendering is actually exercised.
S.workouts = [{
id: 'synth-1', d: '2026-07-25', start: 0, end: 1800000, routineId: 'x', name: 'Synth',
bw: 78, vol: 0, prs: [],
entries: [
{ id: 'squat', target: { mode: 'reps' }, sets: [{ w: 60, r: 5, done: true }] },
{ id: 'plank', target: { mode: 'time' }, sets: [{ sec: 90, w: 0, done: true }] },
{ id: 'plank-w', target: { mode: 'time' }, sets: [{ sec: 90, w: 20, done: true }] },
{ id: 'row', target: { mode: 'cardio' }, sets: [{ min: 20, speed: 8, done: true }] }
]
}]
const w = call('get_workout', { date: '2026-07-25' })
expect(w.entries[0].sets[0].label).toBe('60×5') // reps
// 90 sec → 1 min 30 sec → mm:ss label is "1:30" (fmtSec in history.js)
expect(w.entries[1].sets[0].label).toBe('1:30') // 90 s in mm:ss, no weight
expect(w.entries[2].sets[0].label).toBe('1:30 · 20') // weighted plank
expect(w.entries[3].sets[0].label).toBe('20 min @ 8 km/h') // cardio
})
test('infers cardio mode from the exercise id when the target has no mode key', () => {
// Reproduces the review bug: the sheet saves a cardio target as {sets, min, speed} with
// no mode and no id. modeOf must fall through to isCardio(id), which needs the id on the
// cfg — entryView has to spread id into the cfg the way every app call site does.
const CARDIO_ID = EXDB.find(e => e.bp === 'cardio').id
S.workouts = [{
id: 'synth-cardio', d: '2026-07-25', start: 0, end: 1800000, routineId: 'x', name: 'Synth',
bw: 78, vol: 0, prs: [],
entries: [
{ id: CARDIO_ID, target: { sets: 1, min: 20, speed: 8 }, sets: [{ min: 20, speed: 8, done: true }] }
]
}]
const w = call('get_workout', { date: '2026-07-25' })
expect(w.entries[0].mode).toBe('cardio')
expect(w.entries[0].sets[0].label).toBe('20 min @ 8 km/h')
})
})
/* ---------- get_bodyweight ---------- */
describe('get_bodyweight', () => {
test('returns weigh-ins with the goal, the latest entry, and exact delta vs goal', () => {
const r = call('get_bodyweight')
expect(r.goal).toBe(GOAL_WEIGHT)
expect(r.entries.length).toBeGreaterThan(0)
// Newest is the LATEST_BW entry (deterministic from the demo seed at the pinned time).
expect(r.latest).toBeTruthy()
expect(r.latest.date).toBe(LATEST_BW.date)
expect(r.latest.weight).toBe(LATEST_BW.weight)
expect(r.latest.delta_vs_goal).toBe(LATEST_BW.delta)
// entries are chronological
const dates = r.entries.map(e => e.date)
expect([...dates].sort()).toEqual(dates)
})
test('closed date range returns a single matching entry on the boundary', () => {
const all = call('get_bodyweight')
expect(all.entries.length).toBeGreaterThan(1)
const earliest = all.entries[0].date
const restricted = call('get_bodyweight', { from: earliest, to: earliest })
expect(restricted.entries.length).toBe(1)
expect(restricted.entries[0].date).toBe(earliest)
})
test('no goal set → delta_vs_goal is null, not NaN, not zero', () => {
S.targetW = null
const r = call('get_bodyweight')
expect(r.goal).toBeNull()
r.entries.forEach(e => expect(e.delta_vs_goal).toBeNull())
expect(r.latest.delta_vs_goal).toBeNull()
})
})
/* ---------- estimate_1rm ---------- */
describe('estimate_1rm', () => {
test('PR table across all reps-mode exercises; epley formula is the default', () => {
const r = call('estimate_1rm', {})
expect(r.formula).toBe('epley')
expect(Array.isArray(r.pr_table)).toBe(true)
expect(r.pr_table.length).toBeGreaterThan(0)
r.pr_table.forEach(p => {
expect(typeof p.est).toBe('number')
expect(p.est).toBeGreaterThan(0)
expect(typeof p.exName).toBe('string')
expect(typeof p.exId).toBe('string') // exId surfaced (regression test for the bug where callers passed exName as id)
})
// sort order: descending by est
for (let i = 1; i < r.pr_table.length; i++) {
expect(r.pr_table[i].est).toBeLessThanOrEqual(r.pr_table[i - 1].est)
}
})
test('top-of-table values exactly match the hand-computed Epley for the demo seed', () => {
const r = call('estimate_1rm', {})
const top = r.pr_table[0]
// Demo seed's hardest set: sled 45° leg press at 152.5×12 (r=12 hits estimate1RM's REP_CAP).
expect(top.exId).toBe(LEG_PRESS_ID)
expect(top.w).toBe(LEG_PRESS_BEST.w)
expect(top.r).toBe(LEG_PRESS_BEST.r)
expect(top.est).toBeCloseTo(LEG_PRESS_BEST.epley, 1)
})
test('per-exercise trend + best, with formula honours (Epley vs Brzycki numbers diverge)', () => {
const epley = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: 'epley' })
expect(epley.exercise.id).toBe(LEG_PRESS_ID)
expect(epley.formula).toBe('epley')
expect(Array.isArray(epley.trend)).toBe(true)
expect(epley.best).toBeTruthy()
expect(epley.best.w).toBe(LEG_PRESS_BEST.w)
expect(epley.best.r).toBe(LEG_PRESS_BEST.r)
expect(epley.best.est).toBeCloseTo(LEG_PRESS_BEST.epley, 1)
const brz = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: 'brzycki' })
expect(brz.formula).toBe('brzycki')
expect(brz.best.est).toBeCloseTo(LEG_PRESS_BEST.brzycki, 1)
// Distinct formulas must produce distinct estimates for this set.
expect(epley.best.est).not.toBeCloseTo(brz.best.est, 1)
})
test('exercises with no reps-mode history get null best + empty trend (not a 0 estimate)', () => {
S.workouts = []
_seedStateForTests(S)
const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID })
expect(r.best).toBeNull()
expect(r.trend).toEqual([])
const table = call('estimate_1rm', {}).pr_table
expect(table).toEqual([])
})
test('a null estimate says which kind of null it is', () => {
// "Never trained" and "trained, but always above the rep cap" are opposite facts that both
// arrive as best: null. Undistinguished, the second one reads as the first and an assistant
// reports "no records" for an exercise in the log every week.
S.workouts = [{
id: 'w-highrep', d: '2026-07-26', name: 'Accessories', start: 1000, end: 1000 + 20 * 60000,
vol: 0, prs: [],
entries: [{
id: LEG_PRESS_ID, target: { sets: 2, reps: 20, mode: 'reps' },
sets: [{ w: 40, r: 20, done: true }, { w: 40, r: 18, done: true }]
}]
}]
_seedStateForTests(S)
const capped = call('estimate_1rm', { exercise_id: LEG_PRESS_ID })
expect(capped.best).toBeNull()
expect(capped.no_estimate_reason).toMatch(/above the \d+-rep cap/)
// An exercise that genuinely has no sets must not borrow that explanation.
const never = call('estimate_1rm', { exercise_id: '0684' })
expect(never.best).toBeNull()
expect(never.no_estimate_reason).toMatch(/No completed sets/)
// And the cap is stated on this branch at all, which it never used to be.
expect(capped.formula_note).toMatch(/Cap at/)
})
test('all three formulas are accepted', () => {
['epley', 'brzycki', 'lombardi'].forEach(f => {
const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: f })
expect(r.formula).toBe(f)
expect(r.best).not.toBeNull()
})
})
})
/* ---------- muscle_balance ---------- */
describe('muscle_balance', () => {
test('reports worked + neglected muscles in head-to-toe order over all time', () => {
const r = call('muscle_balance', { period: 'all' })
expect(r.period).toBe('all')
expect(r.workouts_in_period).toBeGreaterThan(0)
expect(Array.isArray(r.worked)).toBe(true)
expect(Array.isArray(r.neglected)).toBe(true)
expect(r.muscle_order_head_to_toe[0]).toBe('trapezius')
expect(r.muscle_order_head_to_toe.at(-1)).toBe('tibialis')
r.worked.forEach(w => {
expect(w.level).toBeGreaterThanOrEqual(1)
expect(w.level).toBeLessThanOrEqual(4)
expect(typeof w.name).toBe('string')
expect(typeof w.effective_sets).toBe('number')
})
})
test('worked + neglected partition every muscle exactly once', () => {
const r = call('muscle_balance', { period: 'all' })
const all = new Set(r.muscle_order_head_to_toe)
const worked = new Set(r.worked.map(w => w.slug))
const neg = new Set(r.neglected.map(n => n.slug))
expect(worked.size + neg.size).toBe(all.size)
expect([...worked].every(s => all.has(s))).toBe(true)
expect([...neg].every(s => all.has(s))).toBe(true)
})
test('period windows are inclusive: week ≤ month ≤ all', () => {
const all = call('muscle_balance', { period: 'all' }).workouts_in_period
const month = call('muscle_balance', { period: 'month' }).workouts_in_period
const week = call('muscle_balance', { period: 'week' }).workouts_in_period
expect(week).toBeLessThanOrEqual(month)
expect(month).toBeLessThanOrEqual(all)
})
test('zero-workout state still returns all 18 muscles as neglected (not empty)', () => {
S.workouts = []
const r = call('muscle_balance', { period: 'all' })
expect(r.workouts_in_period).toBe(0)
expect(r.worked).toEqual([])
expect(r.neglected.length).toBe(r.muscle_order_head_to_toe.length)
expect(r.neglected.length).toBe(18)
})
})
/* ---------- shared: no-state fallback ---------- */
describe('shared: no-state fallback', () => {
test('every tool answers gracefully when state is null (fresh account, never signed in)', () => {
_seedStateForTests(null)
// Each tool gets the minimum args its zod schema mandates; under real LLM-client use the
// SDK rejects missing ones before the handler runs, so we only test the post-validation path.
const calls = {
list_routines: {},
get_routine: { routine_id: '0031' },
get_week_plan: {},
list_workouts: {},
get_workout: { date: '2026-07-26' },
get_bodyweight: {},
estimate_1rm: {},
muscle_balance: { period: 'all' }
}
for (const t of TOOLS) {
const r = t.handler(calls[t.name] || {})
expect(r).toHaveProperty('error')
}
})
// Restore state after the no-state detour so a future test that forgets to seed sees the
// failure rather than inherits null silently.
afterAll(() => { _seedStateForTests(S = freshState()) })
})
+12
View File
@@ -0,0 +1,12 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['test/**/*.test.js'],
globals: false,
environment: 'node',
pool: 'forks',
isolate: true,
reporters: ['default']
}
})
+1 -1
View File
@@ -126,7 +126,7 @@
<li class="no">No cross-device sync</li>
</ul>
<a class="btn" href="openGym.apk" download>Download for Android</a>
<p class="meta">v1.2.3 · 4.3 MB · Android 6.0+ · signed APK, sideload (your browser will ask — that's normal outside the Play Store)</p>
<p class="meta">v1.2.4 · 4.3 MB · Android 6.0+ · signed APK, sideload (your browser will ask — that's normal outside the Play Store)</p>
<p class="meta"><b>iPhone?</b> Apple doesn't allow installs outside the App Store — use the
self-hosted version as a home-screen app instead, or see <a href="docs.html#iphone">the docs</a>.</p>
</div>