Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

MCP: log_workout, a session you describe saved through your own server (#739)

matthewjablack47d81fe78da6
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index b005b5fb1..28469f12d 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -253,9 +253,16 @@ jobs:
with:
node-version: ${{ env.NODE_VERSION }}
cache: npm
- cache-dependency-path: mcp/package-lock.json
+ cache-dependency-path: |
+ mcp/package-lock.json
+ api/package-lock.json
- run: npm ci --no-audit --no-fund
working-directory: mcp
+ # log_workout's end-to-end test drives the real api/server.js, so the api's own
+ # dependencies are here too (same install as the api job). Without them that test fails
+ # under CI rather than skipping, so a green run means it ran.
+ - run: npm ci --no-audit --no-fund --omit=optional
+ working-directory: api
- name: MCP tests
working-directory: mcp
run: >
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 27a307c18..d69e16f94 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -202,9 +202,13 @@ test:mcp:
key:
files:
- mcp/package-lock.json
+ - api/package-lock.json
paths:
- mcp/.npm
script:
+ # log_workout's end-to-end test drives the real api/server.js: the api's dependencies too
+ # (as test:api installs them), or that test fails here rather than skipping.
+ - (cd api && npm ci --cache ../mcp/.npm --prefer-offline --omit=optional)
- cd mcp
- npm ci --cache .npm --prefer-offline --ignore-scripts
- npx vitest run
diff --git a/CLAUDE.md b/CLAUDE.md
index b97640e4e..3695ee22a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -23,7 +23,8 @@ api/ Backend: server.js (plain node:http) plus small testable modules bes
web/ Multi-stage Dockerfile (builds frontend, adds catalogue/media, serves with nginx) and
nginx.conf.template (serves the app, proxies /api).
catalogue/ The exercise database: exercises/<id>.json, i18n/, licensed 180 px media/.
-mcp/ Optional read-only stdio MCP server over DATA_DIR. Not in the Docker build.
+mcp/ Optional stdio MCP server: reads DATA_DIR, and its one write tool (log_workout)
+ saves through the api. Not in the Docker build.
scripts/ Build, CI and release helpers (scripts/README.md).
website/ opengym.ch, plain HTML/CSS/JS, deployed separately.
helm/, kubernetes/, contrib/nix/ Other ways to deploy.
@@ -140,9 +141,12 @@ together: `lib/sync-merge.js` and `api/sync-stamps.js` (parity test), `lib/glyph
### MCP server (`mcp/src`)
-Read-only stdio MCP bridge (`@modelcontextprotocol/sdk`) that reads one user's data straight from
-`DATA_DIR`. `state.js` loads and derives the data, `tools.js` defines the tools (zod schemas),
-`labels.js` maps keys to readable labels, `index.js` wires it together. See `mcp/README.md`.
+Stdio MCP bridge (`@modelcontextprotocol/sdk`) that reads one user's data straight from
+`DATA_DIR`. `state.js` loads and derives the data, `tools.js` defines the read tools (zod schemas),
+`labels.js` maps keys to readable labels, `index.js` wires it together. The one write tool,
+`log_workout` (`write-tools.js`), never writes the file: it builds the workout with
+`frontend/src/lib/log-workout.js` and saves it with `PUT /api/data` over a paired-session token
+(`api-client.js`, `scripts/pair.mjs`), the way a device syncs. See `mcp/README.md`.
### Passkeys and self-hosting constraints
diff --git a/README.md b/README.md
index 750736751..55984fed3 100644
--- a/README.md
+++ b/README.md
@@ -131,7 +131,7 @@ if you want to try it before installing anything.
what you logged. You approve every change. It runs on your server with your own provider key
(Anthropic, OpenAI, Gemini or any OpenAI-compatible endpoint, Ollama included).
- An [MCP server](mcp/README.md) so an assistant like Claude Desktop can answer questions about your
- training history. Read-only and local; not part of the Docker build.
+ training history, and log a workout you describe to it. Local; not part of the Docker build.
The full list of what changed release by release is in the [changelog](CHANGELOG.md).
diff --git a/docs/NIX.md b/docs/NIX.md
index 6d1b4caa4..0e16175fd 100644
--- a/docs/NIX.md
+++ b/docs/NIX.md
@@ -16,7 +16,7 @@ managed by your NixOS configuration. This document covers both.
| --- | --- |
| `packages.opengym-frontend` | The React/Vite PWA, built with `buildNpmPackage`. Static files land in `$out/share/opengym`, with the exercise stills and animations from `catalogue/media` in `exercise-media/` next to them. |
| `packages.opengym-api` | The Node.js API (`node server.js`, wrapped as `bin/opengym-api`). |
-| `packages.opengym-mcp` | The read-only MCP server for LLM clients (`bin/opengym-mcp`). |
+| `packages.opengym-mcp` | The MCP server for LLM clients (`bin/opengym-mcp`): read tools, plus `log_workout` once paired (`mcp/README.md`). |
| `packages.default` | Alias for `opengym-frontend`. |
| `apps.opengym` | Runs the **full local stack** — API + frontend (exercise media included) behind a throwaway Caddy (`nix run .#opengym`, default `http://localhost:8080`). |
| `apps.default` | Alias for `opengym`. |
@@ -405,7 +405,7 @@ old `/var/lib/opengym/media` directory is no longer used and can be deleted.
| Option | Type | Default | Description |
| --- | --- | --- | --- |
-| `mcp.enable` | `bool` | `false` | Run the read-only MCP server as a systemd service (reads the same `dataDir`). Off unless you point an LLM client at it. |
+| `mcp.enable` | `bool` | `false` | Run the MCP server as a systemd service (reads the same `dataDir`; its one write tool goes through the api). Off unless you point an LLM client at it. |
| `mcp.uid` | `string \| null` | `null` | The openGym user ID (from `db.json` `"users"[].id`) the MCP server serves. Leave unset to auto-pick when exactly one user exists; with multiple users it must be set (the server otherwise exits listing them). |
### Option → environment mapping
diff --git a/frontend/src/lib/import-csv.js b/frontend/src/lib/import-csv.js
index 1be362f45..f6246f96e 100644
--- a/frontend/src/lib/import-csv.js
+++ b/frontend/src/lib/import-csv.js
@@ -185,7 +185,7 @@ function buildIndex() {
const w = wordsOf(e.n)
const k = w.slice().sort().join(' ')
if (!INDEX.exact.has(k)) INDEX.exact.set(k, e.id)
- INDEX.all.push({ id: e.id, set: new Set(w), n: w.length })
+ INDEX.all.push({ id: e.id, set: new Set(w), n: w.length, k })
})
return INDEX
}
@@ -294,6 +294,47 @@ export function matchExercise(name) {
return ties === 1 ? best : null
}
+/**
+ * What a name could mean, for a caller that must not guess (the MCP's log_workout): the one
+ * catalogue id it names, or every candidate when it names more than one, so the user picks.
+ *
+ * The same steps as matchExercise, which an import keeps using unchanged: there a near miss is
+ * worth a custom exercise the user can fix later, and the first of two same-named entries is as
+ * good as the other. Logging one session by name has no such fallback, so here an exact name the
+ * catalogue spells twice ("lever chest press" is 0576 and 0577) is a question, not an answer.
+ * With nothing close, the entries sharing the most words are offered instead. `kind` says which
+ * step answered: 'alias', 'exact', 'near', or 'none' (nothing close; the candidates only share a word).
+ */
+export function exerciseCandidates(name, limit = 5) {
+ const idx = buildIndex()
+ const w = wordsOf(name)
+ if (!w.length) return { id: null, candidates: [] }
+ const sorted = w.slice().sort().join(' ')
+ const aliased = aliasIndex().get(sorted)
+ if (aliased && EXIDX[aliased]) return { id: canonicalExId(aliased), candidates: [], kind: 'alias' }
+ const uniq = ids => [...new Set(ids.map(canonicalExId))]
+ const exact = uniq(idx.all.filter(c => c.k === sorted).map(c => c.id))
+ if (exact.length === 1) return { id: exact[0], candidates: [], kind: 'exact' }
+ if (exact.length > 1) return { id: null, candidates: exact.slice(0, limit), kind: 'exact' }
+ const q = new Set(w)
+ const near = []
+ for (const c of idx.all) {
+ let ok = true
+ for (const word of q) if (!c.set.has(word)) { ok = false; break }
+ if (ok && c.n - q.size <= 2) near.push(c)
+ }
+ near.sort((a, b) => a.n - b.n)
+ const closest = uniq(near.filter(c => c.n === near[0]?.n).map(c => c.id))
+ if (closest.length === 1) return { id: closest[0], candidates: [], kind: 'near' }
+ if (near.length) return { id: null, candidates: uniq(near.map(c => c.id)).slice(0, limit), kind: 'near' }
+ const shared = idx.all
+ .map(c => ({ id: c.id, hits: w.filter(word => c.set.has(word)).length, n: c.n }))
+ .filter(c => c.hits > 0)
+ .sort((a, b) => b.hits - a.hits || a.n - b.n)
+ // `kind: 'none'`: these only share a word with the name, and are offered as such.
+ return { id: null, candidates: uniq(shared.map(c => c.id)).slice(0, limit), kind: 'none' }
+}
+
/**
* Exact Hevy English title → catalogue id (from the generated title map).
* Used when a CSV is detected as Hevy: same deterministic table as the API import,
diff --git a/frontend/src/lib/import-match.test.js b/frontend/src/lib/import-match.test.js
index 3e01961fc..f90397d33 100644
--- a/frontend/src/lib/import-match.test.js
+++ b/frontend/src/lib/import-match.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { matchExercise, matchHevyTitle, parseWorkoutCSV, detectSource } from './import-csv.js'
+import { matchExercise, matchHevyTitle, parseWorkoutCSV, detectSource, exerciseCandidates } from './import-csv.js'
import { EXIDX } from './exercises.js'
// The names other apps actually export, and the catalogue entry each has to land on.
@@ -180,3 +180,26 @@ describe('Hevy titles land on the exercise Hevy shows', () => {
expect(parsed.workouts[0].entries.map(e => e.id)).toEqual(['0814', '1755'])
})
})
+
+describe('exerciseCandidates: what a name could mean, for a caller that must not guess', () => {
+ it('a curated alias or a unique exact name is the answer', () => {
+ expect(exerciseCandidates('dumbbell curl')).toEqual({ id: '0294', candidates: [], kind: 'alias' })
+ expect(exerciseCandidates('Bench Press (Barbell)')).toEqual({ id: '0025', candidates: [], kind: 'alias' })
+ })
+ it('an exact name the catalogue spells twice is every entry, not the first (matchExercise keeps the first)', () => {
+ expect(exerciseCandidates('lever chest press')).toEqual({ id: null, candidates: ['0576', '0577'], kind: 'exact' })
+ expect(matchExercise('lever chest press')).toBe('0576')
+ })
+ it('several equally near entries are candidates, the closest first', () => {
+ const r = exerciseCandidates('plank')
+ expect(r).toMatchObject({ id: null, kind: 'near' })
+ expect(r.candidates.length).toBeGreaterThan(1)
+ expect(r.candidates.every(id => EXIDX[id].n.includes('plank'))).toBe(true)
+ })
+ it('nothing near: the entries sharing the most words, at most the limit; nothing at all for no words', () => {
+ const r = exerciseCandidates('zercher frobnicate curl', 3)
+ expect(r).toMatchObject({ id: null, kind: 'none' })
+ expect(r.candidates.length).toBeLessThanOrEqual(3)
+ expect(exerciseCandidates(' ')).toMatchObject({ id: null, candidates: [] })
+ })
+})
diff --git a/frontend/src/lib/log-workout.js b/frontend/src/lib/log-workout.js
new file mode 100644
index 000000000..4c44fd538
--- /dev/null
+++ b/frontend/src/lib/log-workout.js
@@ -0,0 +1,316 @@
+// A session described rather than tapped through ("dumbbell curls, 12 kg, 12/12/10") turned into
+// the workout the app would have saved had it been logged on the phone. Written for the MCP
+// server's log_workout tool, which hands it a structured description an LLM read out of what the
+// user said, and kept here, pure and beside its test, because it decides what lands in the history.
+//
+// It follows the finish sheet (sheets.jsx finishWorkout) step for step, not the CSV importer: one
+// session someone just did is the app's own kind of workout, so a session logged for today gets
+// its PR badges and moves the confirmed weights the way Finish does, and one logged into the past
+// is a backfill — badges held against the history around it (rebuildPrHistory), confirmed weights
+// left alone. A common name resolves the way an import resolves it, to the catalogue's default
+// variant ("shoulder press" is the barbell one), and the reply says which; what it does not do is
+// pick between names the catalogue spells alike or invent an exercise: those come back as a
+// problem to put to the user instead of a workout filed under the wrong lift.
+import { EXIDX, canonicalExId, betterWeight, beatsWeight, isCardio } from './exercises.js'
+import { exerciseCandidates, importId, bpFromName } from './import-csv.js'
+import { bestWeightFor, bestWeightForEntry, workoutVolume, EFFORT } from './history.js'
+import { buildCompletedWorkout } from './finish-workout.js'
+import { withMeaning, entryDbLoad } from './dumbbells.js'
+import { isWarmupRow } from './workout-model.js'
+import { insertChronological, backfillStart } from './backfill.js'
+import { rebuildPrHistory } from './workout-date.js'
+import { stampWorkout } from './sync-merge.js'
+import { exerciseMuscleSnapshot } from './muscles.js'
+
+const LB_TO_KG = 0.45359237
+// The importer's bounds (import-csv.js MAX_KG / MAX_REPS): nobody lifts 2 t or does 1,000 reps.
+export const LOG_LIMITS = { maxKg: 2000, maxReps: 1000, maxSec: 6 * 3600, maxSets: 50, maxExercises: 40, maxDurationMin: 24 * 60 }
+export const BODY_PARTS = ['back', 'cardio', 'chest', 'lower arms', 'lower legs', 'neck', 'shoulders', 'upper arms', 'upper legs', 'waist']
+
+// The least a "just did" squeezed in after today's last session lasts.
+const MIN_ROOM_MS = 5 * 60000
+const ISO = /^\d{4}-\d{2}-\d{2}$/
+const HHMM = /^([01]\d|2[0-3]):([0-5]\d)$/
+const localIso = t => {
+ const d = new Date(t)
+ return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
+}
+const nameKey = n => String(n || '').toLowerCase().replace(/\s+/g, ' ').trim()
+// Enough to tell candidates apart when the user is asked: the catalogue spells some names twice.
+const candidateOf = id => ({ id, name: EXIDX[id].n, equipment: EXIDX[id].eq || null, bodyPart: EXIDX[id].bp || null })
+const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null)
+
+/**
+ * The exercise a reference names: a catalogue id (a drawing alias filed under its canonical id,
+ * as the importer does), one of the profile's own exercises by id or by name, else a catalogue
+ * name that means exactly one entry. Anything else is a problem with the candidates to choose from.
+ */
+export function resolveExercise(S, ref) {
+ const text = String(ref ?? '').trim()
+ if (!text) return { problem: 'no exercise named' }
+ const customs = (S.customEx || []).filter(c => c && c.id)
+ const own = customs.find(c => c.id === text)
+ if (own) return { id: own.id, name: own.n, custom: true }
+ // Own keys only: `constructor` or `__proto__` is on every object and names no exercise.
+ const canon = canonicalExId(text)
+ if (Object.hasOwn(EXIDX, text) && Object.hasOwn(EXIDX, canon)) return { id: canon, name: EXIDX[canon].n }
+ const named = customs.filter(c => nameKey(c.n) === nameKey(text))
+ if (named.length === 1) return { id: named[0].id, name: named[0].n, custom: true }
+ if (named.length > 1) {
+ return { problem: 'several of your own exercises have this name; pass one id', candidates: named.map(c => ({ id: c.id, name: c.n })) }
+ }
+ const { id, candidates, kind } = exerciseCandidates(text)
+ if (id && EXIDX[id]) return { id, name: EXIDX[id].n }
+ return {
+ problem: kind === 'none' || !candidates.length
+ ? 'no exercise in the library matches' + (candidates.length ? '; these only share a word with it' : '')
+ : 'more than one exercise matches; pass one id',
+ candidates: candidates.filter(c => EXIDX[c]).map(candidateOf),
+ }
+}
+
+// One described set as the row the app stores, or a reason it cannot be one. `mode` is the
+// exercise's: reps and seconds are two different exercises' worth of meaning, never one row.
+function rowOf(set, mode, toProfile) {
+ const reps = num(set.reps), secs = num(set.seconds), weight = set.weight == null ? 0 : num(set.weight)
+ if (weight == null || weight < 0) return { problem: 'weight must be a number of 0 or more' }
+ const kg = toProfile.toKg(weight)
+ if (kg > LOG_LIMITS.maxKg) return { problem: `weight over ${LOG_LIMITS.maxKg} kg` }
+ const row = mode === 'time'
+ ? { sec: secs, w: toProfile.convert(weight), done: true }
+ : { w: toProfile.convert(weight), r: reps, done: true }
+ if (set.warmup === true) row.phase = 'warmup'
+ if (set.failure === true) {
+ if (set.warmup === true) return { problem: 'a warm-up set is not taken to failure' }
+ row.failure = true
+ }
+ if (set.rir != null || set.rpe != null) {
+ if (mode === 'time') return { problem: 'effort (RIR/RPE) is logged on rep sets only' }
+ if (set.rir != null && set.rpe != null) return { problem: 'give RIR or RPE, not both' }
+ const kind = set.rir != null ? 'rir' : 'rpe'
+ const v = num(set[kind]), e = EFFORT[kind]
+ if (v == null || v < e.min || v > e.max) return { problem: `${e.hd} must be between ${e.min} and ${e.max}` }
+ row[kind] = v
+ }
+ return { row }
+}
+
+/**
+ * Build the workout a description stands for, against profile `S`, without touching it.
+ *
+ * `input`: { date: 'YYYY-MM-DD', start?: 'HH:MM', durationMin?, name?, note?, unit?: 'kg'|'lb',
+ * exercises: [{ exercise, createCustom?, bodyPart?, note?,
+ * sets: [{ reps? | seconds?, weight?, warmup?, failure?, rir? | rpe? }] }] }
+ *
+ * Returns { workout, past, customEx, resolved } or { problems }: every problem in the whole
+ * description at once, so one round trip to the user settles them all.
+ *
+ * `unit` is what a description without its own unit is read in, and `meanings` what each
+ * dumbbell weight means (exercise id → 'as' | 'each' | 'total'). The caller fixes both once per
+ * request, from the profile as it first read it: another device switching kg ↔ lb, or a
+ * dumbbell default from each to total, between two attempts must not change what the same 20 is.
+ */
+export function buildLoggedWorkout(S, input, { now = Date.now(), unit: fallbackUnit, meanings } = {}) {
+ const problems = []
+ const today = localIso(now)
+ const date = input?.date
+ if (typeof date !== 'string' || !ISO.test(date) || localIso(new Date(date + 'T12:00:00')) !== date) {
+ problems.push({ field: 'date', problem: 'must be a real YYYY-MM-DD date' })
+ } else if (date > today) problems.push({ field: 'date', problem: 'is in the future' })
+ if (input?.start != null && !HHMM.test(String(input.start))) problems.push({ field: 'start', problem: 'must be HH:MM (24 h)' })
+ const dur = input?.durationMin
+ if (dur != null && !(num(dur) > 0 && dur <= LOG_LIMITS.maxDurationMin)) problems.push({ field: 'durationMin', problem: `must be 1–${LOG_LIMITS.maxDurationMin} minutes` })
+ const profileUnit = S.unit === 'lb' ? 'lb' : 'kg'
+ const unit = input?.unit == null ? (fallbackUnit === 'lb' || fallbackUnit === 'kg' ? fallbackUnit : profileUnit) : input.unit
+ if (unit !== 'kg' && unit !== 'lb') problems.push({ field: 'unit', problem: "must be 'kg' or 'lb'" })
+ const toProfile = {
+ toKg: w => (unit === 'lb' ? w * LB_TO_KG : w),
+ // Converted only when the description is in the other unit, to the tenth the importer keeps.
+ convert: w => (unit === profileUnit ? w : Math.round((unit === 'lb' ? w * LB_TO_KG : w / LB_TO_KG) * 10) / 10),
+ }
+ const exercises = Array.isArray(input?.exercises) ? input.exercises : []
+ if (!exercises.length) problems.push({ field: 'exercises', problem: 'at least one exercise' })
+ if (exercises.length > LOG_LIMITS.maxExercises) problems.push({ field: 'exercises', problem: `at most ${LOG_LIMITS.maxExercises}` })
+
+ const customEx = []
+ const resolved = []
+ const entries = []
+ exercises.slice(0, LOG_LIMITS.maxExercises).forEach((ex, i) => {
+ const at = `exercises[${i}]`
+ let hit = resolveExercise({ ...S, customEx: [...(S.customEx || []), ...customEx] }, ex?.exercise)
+ if (hit.problem && ex?.createCustom === true && String(ex?.exercise ?? '').trim()) {
+ const name = String(ex.exercise).trim().slice(0, 80)
+ const bp = ex.bodyPart ?? bpFromName(name)
+ if (!BODY_PARTS.includes(bp)) {
+ problems.push({ field: at + '.bodyPart', problem: `needed for a new exercise: one of ${BODY_PARTS.join(', ')}` })
+ return
+ }
+ // From the name, like an import's: the same name logged twice before a sync is one exercise.
+ const c = { id: importId('mc', nameKey(name)), n: name, custom: true, eq: 'custom', tg: '', desc: '', bp }
+ customEx.push(c)
+ hit = { id: c.id, name: c.n, custom: true, created: true }
+ }
+ if (hit.problem) {
+ problems.push({ field: at + '.exercise', exercise: ex?.exercise ?? null, problem: hit.problem, ...(hit.candidates ? { candidates: hit.candidates } : {}) })
+ return
+ }
+ if (isCardio(hit.id) || customEx.find(c => c.id === hit.id)?.bp === 'cardio') {
+ problems.push({ field: at + '.exercise', exercise: ex.exercise, problem: 'cardio (time and speed) cannot be logged this way yet' })
+ return
+ }
+ const sets = Array.isArray(ex.sets) ? ex.sets : []
+ if (!sets.length || sets.length > LOG_LIMITS.maxSets) {
+ problems.push({ field: at + '.sets', problem: `1–${LOG_LIMITS.maxSets} sets` })
+ return
+ }
+ const timed = sets.some(s => s?.seconds != null), counted = sets.some(s => s?.reps != null)
+ if (timed && counted) {
+ problems.push({ field: at + '.sets', problem: 'every set is reps or every set is seconds, not a mix' })
+ return
+ }
+ const mode = timed ? 'time' : 'reps'
+ const rows = []
+ sets.forEach((s, j) => {
+ const where = `${at}.sets[${j}]`
+ const v = mode === 'time' ? num(s?.seconds) : num(s?.reps)
+ const ok = mode === 'time'
+ ? v != null && v >= 1 && v <= LOG_LIMITS.maxSec
+ : Number.isInteger(v) && v >= 1 && v <= LOG_LIMITS.maxReps
+ if (!ok) {
+ problems.push({ field: where, problem: mode === 'time' ? `seconds must be 1–${LOG_LIMITS.maxSec}` : `reps must be a whole number 1–${LOG_LIMITS.maxReps}` })
+ return
+ }
+ const { row, problem } = rowOf(s, mode, toProfile)
+ if (problem) problems.push({ field: where, problem })
+ else rows.push(mode === 'time' ? { ...row, sec: Math.round(v) } : row)
+ })
+ // The meaning of a dumbbell weight is stamped the way a freestyle entry gets it (sheets.jsx
+ // swapActiveWorkoutExercise): the exercise's own default, so "20 each" stays 20 each.
+ const cfg = mode === 'time' ? { id: hit.id, mode: 'time' } : { id: hit.id }
+ const fixed = meanings && Object.hasOwn(meanings, hit.id) ? meanings[hit.id] : null
+ const target = fixed === 'each' || fixed === 'total' ? { ...cfg, dbLoad: fixed } : fixed === 'as' ? cfg : withMeaning(S, cfg, hit.id)
+ const note = String(ex.note ?? '').trim().slice(0, 280)
+ entries.push({ id: hit.id, sets: rows, target, ...(note ? { note } : {}) })
+ resolved.push({ input: ex.exercise, id: hit.id, name: hit.name, mode, ...(target.dbLoad ? { weightMeans: target.dbLoad } : {}), ...(hit.created ? { created: true } : {}) })
+ })
+ if (problems.length) return { problems }
+
+ const past = date < today
+ // A length nobody gave is the backfill's hour (backfill.js), as when a session is logged in the
+ // app. Into the past without a start: the backfill's 18:00. Today without one it is "just did":
+ // it ended now. A length the caller gave is kept as given; the hour that stands in for a missing
+ // one is only as long as fits after today's last session (and after midnight), so a "just did"
+ // lands after the session just logged in the app rather than overlapping it.
+ let start, end
+ if (input.start != null) {
+ start = new Date(`${date}T${input.start}:00`).getTime()
+ end = start + (dur ?? 60) * 60000
+ if (dur == null && !past) end = Math.max(start, Math.min(end, now))
+ } else if (past) {
+ start = backfillStart(date)
+ end = start + (dur ?? 60) * 60000
+ } else {
+ end = now
+ const midnight = new Date(date + 'T00:00:00').getTime()
+ if (dur != null) {
+ start = end - dur * 60000
+ if (start < midnight) return { problems: [{ field: 'durationMin', problem: 'a session that long ending now began yesterday: give the date and start it began on' }] }
+ } else {
+ const lastEnd = Math.max(0, ...(S.workouts || []).filter(w => w?.d === date).map(w => Number(w.end) || Number(w.start) || 0))
+ start = Math.max(end - 60 * 60000, lastEnd, midnight)
+ // Too little room after it — a session on file that ended moments ago, or ends after now
+ // (another device's clock ahead) — would make a session of seconds, read back as "0 min":
+ // the floor instead, overlapping the last minutes of the one before as the app's backfill
+ // allows, and still starting after it began, so it is filed after it as a live finish.
+ // (One that starts later still is jumped, and the chronological rule below handles that.)
+ if (end - start < MIN_ROOM_MS) start = Math.max(end - MIN_ROOM_MS, midnight)
+ }
+ }
+ if (start > now) return { problems: [{ field: 'start', problem: 'is later than now' }] }
+ // As the app's own backfill refuses one (sheets.jsx endsInFuture): a finished session that has
+ // not finished yet would count its whole length into the stats now.
+ if (end > now) return { problems: [{ field: 'durationMin', problem: 'the session would end later than now' }] }
+
+ const name = String(input.name ?? '').trim().slice(0, 80) || 'Workout'
+ const note = String(input.note ?? '').trim().slice(0, 500)
+ // The id is the description's, not the clock's: the same call made again — its answer lost to a
+ // timeout, a client retrying — names the same workout, and appendLoggedWorkout keeps one.
+ // Only what the caller sent goes in, never the start filled in from `now` or a converted weight.
+ const id = importId('mw', JSON.stringify([
+ date, input.start ?? null, dur ?? null, input.name ?? null, input.note ?? null, input.unit ?? null,
+ exercises.map(ex => [ex.exercise, ex.createCustom === true, ex.note ?? null,
+ ex.sets.map(s => [s.reps ?? null, s.seconds ?? null, s.weight ?? null, s.warmup === true, s.failure === true, s.rir ?? null, s.rpe ?? null])]),
+ ]))
+ // A custom exercise's muscles go with the entry, as Finish writes them: a device that deletes
+ // the exercise without ever having seen this workout would otherwise leave its sets crediting
+ // no muscle at all.
+ const customs = [...(S.customEx || []), ...customEx]
+ const workout = buildCompletedWorkout(
+ { id, d: date, start, name, bw: null, routineIds: [], note, entries },
+ { end, prs: [], snapshotFor: e => { const c = customs.find(x => x?.id === e.id); return c ? exerciseMuscleSnapshot(c) : null } },
+ )
+ // finish-workout's whitelist keeps `target`, which a timed hold and a dumbbell meaning need to
+ // read back; volume as Finish stores it (warm-ups out, "each" counted per bell).
+ workout.vol = workoutVolume(workout)
+ return { workout, past, customEx, resolved }
+}
+
+const sameEntries = (a, b) =>
+ JSON.stringify((a || []).map(e => [e.id, e.sets])) === JSON.stringify((b || []).map(e => [e.id, e.sets]))
+
+/**
+ * The workout already in `S` this one repeats: the same request (its id) first, else the same day
+ * with the same sets. `sameRequest` tells the two apart: a repeated request is never filed again,
+ * the same sets are when the caller says it was a second session.
+ */
+export function findDuplicate(S, workout) {
+ const list = (S.workouts || []).filter(Boolean)
+ const own = list.find(w => w.id === workout.id)
+ if (own) return { workout: own, sameRequest: true }
+ const same = list.find(w => w.d === workout.d && sameEntries(w.entries, workout.entries))
+ return same ? { workout: same, sameRequest: false } : null
+}
+
+/**
+ * File a built workout into `S` (mutated): its new custom exercises, the workout in day order,
+ * and — as Finish does — its PR badges and confirmed weights for a session logged today, or for one
+ * logged into the past its badges against the history around it and no confirmed weight moved.
+ * `allowDuplicate` files a session identical to one already there (two real 3×10s on one day).
+ */
+export function appendLoggedWorkout(S, built, { now = Date.now(), allowDuplicate = false } = {}) {
+ const dup = findDuplicate(S, built.workout)
+ // A second session with the same sets has its own id already (its start or name differs, and
+ // both are in the id), so a retry of it is caught by that id like any other.
+ if (dup && (dup.sameRequest || !allowDuplicate)) return { added: false, reason: 'duplicate', workout: dup.workout }
+ const w = JSON.parse(JSON.stringify(built.workout))
+ S.customEx = Array.isArray(S.customEx) ? S.customEx : []
+ const known = new Set(S.customEx.map(c => c?.id))
+ for (const c of built.customEx || []) if (!known.has(c.id) && w.entries.some(e => e.id === c.id)) S.customEx.push({ ...c })
+ S.workouts = Array.isArray(S.workouts) ? S.workouts : []
+ // Filed before a session already logged — an earlier day, or this morning when tonight's is
+ // already in — it is a backfill: a badge it leads with, and one it falsifies on a later session
+ // taken away, which the live-finish rule below would leave standing.
+ const later = S.workouts.some(x => x && (x.d > w.d || (x.d === w.d && (Number(x.start) || 0) > w.start)))
+ if (built.past || later) {
+ stampWorkout(w, now)
+ const touched = [...new Set(w.entries.map(e => e.id))]
+ S.workouts = rebuildPrHistory(insertChronological(S.workouts, w), touched, w)
+ } else {
+ w.prs = []
+ w.entries.forEach(e => {
+ const loads = e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w).filter(x => x > 0)
+ const mx = loads.length ? loads.reduce((a, b) => betterWeight(e.id, a, b)) : 0
+ if (beatsWeight(e.id, mx, bestWeightFor(S, e.id, entryDbLoad(e)))) w.prs.push(e.id)
+ })
+ S.exWeights = S.exWeights && typeof S.exWeights === 'object' ? S.exWeights : {}
+ w.entries.forEach(e => {
+ const mx = bestWeightForEntry(e)
+ if (mx > 0 && beatsWeight(e.id, mx, (S.exWeights[e.id] || {}).w || 0)) S.exWeights[e.id] = { w: mx, d: w.d }
+ })
+ S.workouts = insertChronological(S.workouts, w)
+ }
+ // What a device's own save stamps (useStore persist): a copy restored without its sync marker
+ // compares this, and must not take the server's document for older than its own.
+ S._ts = Math.max(now, (Number(S._ts) || 0) + 1)
+ return { added: true, workout: S.workouts.find(x => x.id === w.id) || w }
+}
diff --git a/frontend/src/lib/log-workout.test.js b/frontend/src/lib/log-workout.test.js
new file mode 100644
index 000000000..b1d39ed0c
--- /dev/null
+++ b/frontend/src/lib/log-workout.test.js
@@ -0,0 +1,380 @@
+import { describe, expect, it } from 'vitest'
+import { buildLoggedWorkout, appendLoggedWorkout, resolveExercise, findDuplicate } from './log-workout.js'
+import { setLabel, workoutVolume, setsDone } from './history.js'
+import { best1RM } from './onerm.js'
+import { mergeStates, stampChange } from './sync-merge.js'
+
+// Pinned to an evening, local time, so "today" and "now" mean the same thing on every machine.
+const NOW = new Date('2026-10-20T19:30:00').getTime()
+const TODAY = '2026-10-20'
+const clone = v => JSON.parse(JSON.stringify(v))
+const profile = (over = {}) => ({ unit: 'kg', workouts: [], routines: [], customEx: [], exWeights: {}, deleted: {}, edited: {}, ...over })
+const curls = (over = {}) => ({
+ date: TODAY,
+ exercises: [{ exercise: 'dumbbell curl', sets: [{ reps: 12, weight: 12 }, { reps: 12, weight: 12 }, { reps: 10, weight: 12 }] }],
+ ...over,
+})
+const build = (S, input, now = NOW) => buildLoggedWorkout(S, input, { now })
+const bench = (d, w, prs = []) => ({
+ id: 'w' + d, d, start: new Date(d + 'T18:00:00').getTime(), end: new Date(d + 'T19:00:00').getTime(),
+ routineIds: [], routineId: null, name: 'Bench', prs,
+ entries: [{ id: '0025', sets: [{ w, r: 5, done: true }], topW: w, target: null }],
+})
+
+describe('what the user said becomes the workout Finish would have saved', () => {
+ it('"dumbbell curls, 12 kg, 12/12/10": three rows, the catalogue curl, the volume Finish stores', () => {
+ const r = build(profile(), curls())
+ expect(r.problems).toBeUndefined()
+ const w = r.workout
+ expect(w.d).toBe(TODAY)
+ expect(w.end).toBe(NOW)
+ expect(w.routineId).toBe(null)
+ expect(w.routineIds).toEqual([])
+ expect(w.entries).toHaveLength(1)
+ expect(w.entries[0].id).toBe('0294')
+ expect(w.entries[0].sets).toEqual([{ w: 12, r: 12, done: true }, { w: 12, r: 12, done: true }, { w: 12, r: 10, done: true }])
+ expect(w.entries[0].topW).toBe(12)
+ expect(w.vol).toBe(workoutVolume(w))
+ expect(w.vol).toBe(12 * 34)
+ expect(setsDone(w)).toBe(3)
+ // the Stats screen's (and estimate_1rm's) estimate finds the session
+ expect(best1RM(profile({ workouts: [w] }), '0294')).toMatchObject({ w: 12, r: 12, d: TODAY })
+ })
+
+ it('a drawing alias id is filed under the exercise it draws, or its history would never find it', () => {
+ const r = build(profile(), { date: TODAY, exercises: [{ exercise: '1019', sets: [{ reps: 5, weight: 50 }] }] })
+ expect(r.workout.entries[0].id).toBe('3841')
+ expect(best1RM(profile({ workouts: [r.workout] }), '3841')).not.toBe(null)
+ })
+
+ it('a name the catalogue spells twice is a question with both answers, not the first of them', () => {
+ const r = build(profile(), { date: TODAY, exercises: [{ exercise: 'lever chest press', sets: [{ reps: 10, weight: 40 }] }] })
+ expect(r.workout).toBeUndefined()
+ expect(r.problems[0].candidates.map(c => c.id)).toEqual(['0576', '0577'])
+ expect(r.problems[0].candidates[0]).toMatchObject({ name: 'lever chest press', equipment: 'leverage machine' })
+ })
+
+ it('a name nothing matches offers the closest entries instead of inventing an exercise', () => {
+ const r = build(profile(), { date: TODAY, exercises: [{ exercise: 'zercher frobnicate', sets: [{ reps: 5 }] }] })
+ expect(r.problems[0].problem).toMatch(/no exercise|more than one/)
+ })
+
+ it("the user's own exercise is found by name, and two of the same name ask which", () => {
+ const own = { id: 'c1', n: 'Grip Trainer', custom: true, bp: 'lower arms' }
+ expect(resolveExercise(profile({ customEx: [own] }), 'grip trainer')).toMatchObject({ id: 'c1', custom: true })
+ const twice = profile({ customEx: [own, { ...own, id: 'c2' }] })
+ expect(resolveExercise(twice, 'Grip Trainer').candidates.map(c => c.id)).toEqual(['c1', 'c2'])
+ })
+
+ it('createCustom makes the exercise, with a body part read off the name or asked for', () => {
+ const made = build(profile(), { date: TODAY, exercises: [{ exercise: 'Zottman curl machine x', createCustom: true, sets: [{ reps: 8, weight: 10 }] }] })
+ expect(made.customEx).toHaveLength(1)
+ expect(made.customEx[0]).toMatchObject({ n: 'Zottman curl machine x', custom: true, bp: 'upper arms' })
+ expect(made.workout.entries[0].id).toBe(made.customEx[0].id)
+ const vague = build(profile(), { date: TODAY, exercises: [{ exercise: 'Frobnicator', createCustom: true, sets: [{ reps: 8 }] }] })
+ expect(vague.problems[0].field).toBe('exercises[0].bodyPart')
+ const told = build(profile(), { date: TODAY, exercises: [{ exercise: 'Frobnicator', createCustom: true, bodyPart: 'back', sets: [{ reps: 8 }] }] })
+ expect(told.customEx[0].bp).toBe('back')
+ })
+
+ it('cardio is refused rather than stored as a rep set at zero speed', () => {
+ const r = build(profile(), { date: TODAY, exercises: [{ exercise: 'treadmill running', sets: [{ reps: 1 }] }] })
+ expect(r.problems).toBeDefined()
+ })
+})
+
+describe('the numbers', () => {
+ it('pounds into a kilo profile and kilos into a pound one, to the tenth the importer keeps', () => {
+ expect(build(profile(), curls({ unit: 'lb', exercises: [{ exercise: '0294', sets: [{ reps: 10, weight: 25 }] }] })).workout.entries[0].sets[0].w).toBe(11.3)
+ expect(build(profile({ unit: 'lb' }), curls({ unit: 'kg', exercises: [{ exercise: '0294', sets: [{ reps: 10, weight: 20 }] }] })).workout.entries[0].sets[0].w).toBe(44.1)
+ expect(build(profile({ unit: 'lb' }), curls({ exercises: [{ exercise: '0294', sets: [{ reps: 10, weight: 25 }] }] })).workout.entries[0].sets[0].w).toBe(25)
+ })
+
+ it('a warm-up is logged as one and stays out of the top weight and the volume', () => {
+ const w = build(profile(), { date: TODAY, exercises: [{ exercise: '0025', sets: [{ reps: 5, weight: 120, warmup: true }, { reps: 5, weight: 100 }] }] }).workout
+ expect(w.entries[0].sets[0]).toMatchObject({ phase: 'warmup' })
+ expect(w.entries[0].topW).toBe(100)
+ expect(w.vol).toBe(500)
+ })
+
+ it('a timed hold keeps its mode on the entry, so it reads back as 1:00 and not as 0 reps', () => {
+ const w = build(profile(), { date: TODAY, exercises: [{ exercise: '0463', sets: [{ seconds: 60 }] }] }).workout
+ const e = w.entries[0]
+ expect(e.sets[0]).toEqual({ sec: 60, w: 0, done: true })
+ expect(e.target.mode).toBe('time')
+ // the MCP's get_workout reads every set through a config built from the target
+ expect(setLabel(e.id, e.sets[0], { ...e.target, id: e.id })).toBe('1:00')
+ })
+
+ it("a dumbbell exercise logged 'each' keeps that meaning, and its volume counts both bells", () => {
+ const S = profile({ dbLoad: { '0289': { mode: 'each', _ts: 1 } } })
+ const w = build(S, { date: TODAY, exercises: [{ exercise: '0289', sets: [{ reps: 10, weight: 20 }] }] }).workout
+ expect(w.entries[0].target.dbLoad).toBe('each')
+ expect(w.vol).toBe(400)
+ expect(build(profile(), { date: TODAY, exercises: [{ exercise: '0289', sets: [{ reps: 10, weight: 20 }] }] }).workout.vol).toBe(200)
+ const total = build(profile({ dbLoad: { '0289': { mode: 'total', _ts: 1 } } }), { date: TODAY, exercises: [{ exercise: '0289', sets: [{ reps: 10, weight: 40 }] }] }).workout
+ expect(total.entries[0].target.dbLoad).toBe('total')
+ expect(total.vol).toBe(400)
+ })
+
+ it('failure, RIR and RPE ride on the row; both scales at once, or effort on a hold, are refused', () => {
+ const w = build(profile(), { date: TODAY, exercises: [{ exercise: '0025', sets: [{ reps: 5, weight: 100, rir: 2 }, { reps: 4, weight: 100, failure: true, rpe: 10 }] }] }).workout
+ expect(w.entries[0].sets).toEqual([{ w: 100, r: 5, done: true, rir: 2 }, { w: 100, r: 4, done: true, failure: true, rpe: 10 }])
+ expect(build(profile(), { date: TODAY, exercises: [{ exercise: '0025', sets: [{ reps: 5, rir: 2, rpe: 8 }] }] }).problems).toBeDefined()
+ expect(build(profile(), { date: TODAY, exercises: [{ exercise: '0463', sets: [{ seconds: 30, rpe: 8 }] }] }).problems).toBeDefined()
+ expect(build(profile(), { date: TODAY, exercises: [{ exercise: '0025', sets: [{ reps: 5, rpe: 3 }] }] }).problems).toBeDefined()
+ })
+
+ it('a set with nothing measured, a mix of reps and seconds, or half a rep is refused, all at once', () => {
+ const r = build(profile(), {
+ date: TODAY,
+ exercises: [
+ { exercise: '0025', sets: [{}] },
+ { exercise: '0025', sets: [{ reps: 5 }, { seconds: 30 }] },
+ { exercise: '0025', sets: [{ reps: 2.5 }] },
+ { exercise: '0025', sets: [] },
+ { exercise: '0025', sets: [{ reps: 5, weight: -5 }] },
+ ],
+ })
+ expect(r.workout).toBeUndefined()
+ expect(r.problems.map(p => p.field)).toEqual(['exercises[0].sets[0]', 'exercises[1].sets', 'exercises[2].sets[0]', 'exercises[3].sets', 'exercises[4].sets[0]'])
+ })
+
+ it('dates: not tomorrow, not 2026-02-30, not a start later than now', () => {
+ expect(build(profile(), curls({ date: '2026-10-21' })).problems[0].field).toBe('date')
+ expect(build(profile(), curls({ date: '2026-02-30' })).problems[0].field).toBe('date')
+ expect(build(profile(), curls({ start: '21:00' })).problems[0].field).toBe('start')
+ expect(build(profile(), curls({ start: '9am' })).problems[0].field).toBe('start')
+ })
+
+ it('times: today ends now; a given start and length are kept; the past gets the backfill 18:00 and hour', () => {
+ const today = build(profile(), curls({ durationMin: 45 })).workout
+ expect([today.start, today.end]).toEqual([NOW - 45 * 60000, NOW])
+ // no length given: the backfill's hour, not a zero-minute session
+ const untimed = build(profile(), curls()).workout
+ expect(untimed.end - untimed.start).toBe(60 * 60000)
+ const given = build(profile(), curls({ start: '17:10', durationMin: 50 })).workout
+ expect(given.start).toBe(new Date('2026-10-20T17:10:00').getTime())
+ expect(given.end - given.start).toBe(50 * 60000)
+ const past = build(profile(), curls({ date: '2026-10-18' }))
+ expect(past.past).toBe(true)
+ expect(past.workout.start).toBe(new Date('2026-10-18T18:00:00').getTime())
+ expect(past.workout.end - past.workout.start).toBe(60 * 60000)
+ })
+})
+
+describe('the same call twice is one workout', () => {
+ it('the id comes from the description, not the clock: a retry minutes later names the same workout', () => {
+ const a = build(profile(), curls()).workout
+ const b = build(profile(), curls(), NOW + 7 * 60000).workout
+ expect(a.end).not.toBe(b.end)
+ expect(b.id).toBe(a.id)
+ })
+
+ it('a retry after the first write landed adds nothing', () => {
+ const S = profile()
+ expect(appendLoggedWorkout(S, build(S, curls()), { now: NOW }).added).toBe(true)
+ const again = appendLoggedWorkout(S, build(S, curls(), NOW + 60000), { now: NOW + 60000 })
+ expect(again).toMatchObject({ added: false, reason: 'duplicate' })
+ expect(S.workouts).toHaveLength(1)
+ })
+
+ it('the same sets reworded (another note) are a duplicate too, unless the caller says it is a second session', () => {
+ const S = profile()
+ appendLoggedWorkout(S, build(S, curls()), { now: NOW })
+ const reworded = build(S, curls({ note: 'felt strong' }))
+ expect(findDuplicate(S, reworded.workout)).not.toBe(null)
+ expect(appendLoggedWorkout(S, reworded, { now: NOW }).added).toBe(false)
+ expect(appendLoggedWorkout(S, reworded, { now: NOW, allowDuplicate: true }).added).toBe(true)
+ expect(new Set(S.workouts.map(w => w.id)).size).toBe(2)
+ })
+})
+
+describe('filed the way Finish files it', () => {
+ it('today: a heavier top set than history is a PR, and becomes the confirmed weight', () => {
+ const S = profile({ workouts: [bench('2026-10-13', 100, ['0025'])], exWeights: { '0025': { w: 100, d: '2026-10-13' } } })
+ const r = appendLoggedWorkout(S, build(S, { date: TODAY, exercises: [{ exercise: '0025', sets: [{ reps: 3, weight: 105 }] }] }), { now: NOW })
+ expect(r.workout.prs).toEqual(['0025'])
+ expect(S.exWeights['0025']).toEqual({ w: 105, d: TODAY })
+ expect(S._ts).toBeGreaterThanOrEqual(NOW)
+ })
+
+ it('today, assisted: less help is the better set, and a warm-up with more help moves nothing', () => {
+ const S = profile({ exWeights: { 1432: { w: 25, d: '2026-10-13' } } })
+ appendLoggedWorkout(S, build(S, { date: TODAY, exercises: [{ exercise: '1432', sets: [{ reps: 8, weight: 35, warmup: true }, { reps: 8, weight: 20 }, { reps: 8, weight: 22.5 }] }] }), { now: NOW })
+ expect(S.exWeights['1432']).toEqual({ w: 20, d: TODAY })
+ })
+
+ it('into the past: confirmed weights stay; badges are held against the history around it', () => {
+ const later = bench('2026-10-15', 100, ['0025'])
+ const S = profile({ workouts: [later], exWeights: { '0025': { w: 100, d: '2026-10-15' } } })
+ const r = appendLoggedWorkout(S, build(S, { date: '2026-10-10', exercises: [{ exercise: '0025', sets: [{ reps: 3, weight: 110 }] }] }), { now: NOW })
+ expect(S.exWeights['0025']).toEqual({ w: 100, d: '2026-10-15' })
+ expect(S.workouts.map(w => w.d)).toEqual(['2026-10-10', '2026-10-15'])
+ expect(r.workout.prs).toEqual(['0025'])
+ expect(r.workout._ts).toBe(NOW)
+ expect(S.workouts[1].prs).toEqual([])
+ })
+
+ it('a new custom exercise is filed with the workout, once', () => {
+ const S = profile()
+ const built = build(S, { date: TODAY, exercises: [{ exercise: 'Frobnicator', createCustom: true, bodyPart: 'back', sets: [{ reps: 8 }] }] })
+ appendLoggedWorkout(S, built, { now: NOW })
+ expect(S.customEx.map(c => c.n)).toEqual(['Frobnicator'])
+ })
+})
+
+describe('what a device does with it on its next sync', () => {
+ it("a phone with its own unsent change keeps the logged workout, and the phone's change", () => {
+ const old = bench('2026-10-13', 100)
+ const server0 = profile({ workouts: [old], routines: [{ id: 'r1', name: 'Push', ex: [], _ts: 1 }], _ts: 1 })
+ // the MCP's write: the server's document plus the workout
+ const server1 = clone(server0)
+ appendLoggedWorkout(server1, build(server1, curls()), { now: NOW })
+ // the phone, offline since server0: renamed a routine and deleted last week's session
+ const phone = clone(server0)
+ phone.routines[0].name = 'Push day'
+ phone.workouts = []
+ phone._ts = stampChange(server0, phone, NOW - 60000)
+ const merged = mergeStates(phone, server1)
+ expect(merged.routines[0].name).toBe('Push day')
+ expect(merged.workouts.map(w => w.entries[0].id)).toEqual(['0294'])
+ })
+})
+
+describe('found in review', () => {
+ it('a description without a unit is read in the unit the caller fixed, and its id does not depend on the profile', () => {
+ const input = { date: TODAY, exercises: [{ exercise: '0025', sets: [{ reps: 5, weight: 100 }] }] }
+ const kg = buildLoggedWorkout(profile(), input, { now: NOW, unit: 'kg' })
+ const nowLb = buildLoggedWorkout(profile({ unit: 'lb' }), input, { now: NOW, unit: 'kg' })
+ expect(nowLb.workout.entries[0].sets[0].w).toBe(220.5)
+ expect(nowLb.workout.id).toBe(kg.workout.id)
+ expect(build(profile({ unit: 'lb' }), input).workout.id).toBe(kg.workout.id)
+ })
+
+ it('a second session with the same sets, allowed once, is not logged a third time by a retry', () => {
+ const S = profile()
+ appendLoggedWorkout(S, build(S, curls({ start: '08:00', durationMin: 30 })), { now: NOW })
+ const second = curls({ start: '17:00', durationMin: 30, name: 'Evening' })
+ expect(appendLoggedWorkout(S, build(S, second), { now: NOW, allowDuplicate: true }).added).toBe(true)
+ const retry = appendLoggedWorkout(S, build(S, second, NOW + 60000), { now: NOW + 60000, allowDuplicate: true })
+ expect(retry).toMatchObject({ added: false, reason: 'duplicate' })
+ expect(S.workouts).toHaveLength(2)
+ })
+
+ it("this morning's session logged after tonight's takes tonight's badge away, as a backfill does", () => {
+ const evening = { ...bench(TODAY, 100, ['0025']), start: new Date(`${TODAY}T18:00:00`).getTime(), end: new Date(`${TODAY}T19:00:00`).getTime() }
+ const S = profile({ workouts: [evening], exWeights: { '0025': { w: 100, d: TODAY } } })
+ const r = appendLoggedWorkout(S, build(S, { date: TODAY, start: '10:00', durationMin: 60, exercises: [{ exercise: '0025', sets: [{ reps: 3, weight: 110 }] }] }), { now: NOW })
+ expect(S.workouts.map(w => w.id)).toEqual([r.workout.id, evening.id])
+ expect(r.workout.prs).toEqual(['0025'])
+ expect(S.workouts[1].prs).toEqual([])
+ })
+
+ it('a session that would end later than now is refused, today or from yesterday', () => {
+ expect(build(profile(), curls({ start: '19:00', durationMin: 120 })).problems[0].field).toBe('durationMin')
+ expect(build(profile(), curls({ date: '2026-10-19', start: '23:00', durationMin: 24 * 60 })).problems[0].field).toBe('durationMin')
+ })
+
+ it("a custom exercise's muscles ride on the entry, so a device deleting it unseen leaves the sets their credit", () => {
+ const own = { id: 'c1', n: 'Landmine press thing', custom: true, eq: 'custom', bp: 'chest', tg: '', desc: '' }
+ const w = build(profile({ customEx: [own] }), { date: TODAY, exercises: [{ exercise: 'c1', sets: [{ reps: 8, weight: 20 }] }] }).workout
+ expect(w.entries[0].muscleSnapshot).toBeTruthy()
+ expect(build(profile(), { date: TODAY, exercises: [{ exercise: '0025', sets: [{ reps: 5 }] }] }).workout.entries[0].muscleSnapshot).toBeUndefined()
+ })
+
+ it('a new custom exercise filed under cardio is refused like built-in cardio', () => {
+ const r = build(profile(), { date: TODAY, exercises: [{ exercise: 'Frobnicator', createCustom: true, bodyPart: 'cardio', sets: [{ reps: 8 }] }] })
+ expect(r.problems[0].problem).toMatch(/cardio/)
+ })
+})
+
+describe('found in review, round 2', () => {
+ it("today with a start and no length is the backfill's hour, not start-until-now", () => {
+ const w = build(profile(), curls({ start: '09:00' })).workout
+ expect(w.end - w.start).toBe(60 * 60000)
+ // and an hour that would run past now ends now
+ const late = build(profile(), curls({ start: '19:00' })).workout
+ expect(late.end).toBe(NOW)
+ })
+
+ it('"just did" after a session logged in the app this past hour is filed after it, as a live finish', () => {
+ const app = { ...bench(TODAY, 100), id: 'w-app', start: new Date(`${TODAY}T18:00:00`).getTime(), end: new Date(`${TODAY}T19:10:00`).getTime(), entries: [{ id: '0025', sets: [{ w: 100, r: 5, done: true }], topW: 100, target: null }] }
+ const S = profile({ workouts: [app], exWeights: { '0294': { w: 10, d: '2026-10-13' } } })
+ const built = build(S, curls())
+ expect(built.workout.start).toBeGreaterThanOrEqual(app.end)
+ const r = appendLoggedWorkout(S, built, { now: NOW })
+ expect(S.workouts.map(w => w.id)).toEqual(['w-app', r.workout.id])
+ expect(S.exWeights['0294']).toEqual({ w: 12, d: TODAY })
+ expect(r.workout._ts).toBeUndefined()
+ })
+
+ it('just after midnight, the default hour does not start yesterday', () => {
+ const at = new Date(`${TODAY}T00:30:00`).getTime()
+ const w = buildLoggedWorkout(profile(), curls(), { now: at }).workout
+ expect(w.start).toBe(new Date(`${TODAY}T00:00:00`).getTime())
+ expect(w.d).toBe(TODAY)
+ })
+
+ it('a key every object has is no exercise', () => {
+ for (const name of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {
+ const r = build(profile(), { date: TODAY, exercises: [{ exercise: name, sets: [{ reps: 8, weight: 20 }] }] })
+ expect(r.workout, name).toBeUndefined()
+ }
+ })
+
+ it('a name nothing is close to says so, even with suggestions', () => {
+ const r = build(profile(), { date: TODAY, exercises: [{ exercise: 'zercher frobnicate', sets: [{ reps: 5 }] }] })
+ expect(r.problems[0].problem).toMatch(/^no exercise in the library matches/)
+ })
+
+ it('the meaning fixed for a request wins over a default changed since', () => {
+ const S = profile({ dbLoad: { '0289': { mode: 'total', _ts: 2 } } })
+ const w = buildLoggedWorkout(S, { date: TODAY, exercises: [{ exercise: '0289', sets: [{ reps: 10, weight: 20 }] }] }, { now: NOW, meanings: { '0289': 'each' } }).workout
+ expect(w.entries[0].target.dbLoad).toBe('each')
+ expect(w.vol).toBe(400)
+ const asIs = buildLoggedWorkout(S, { date: TODAY, exercises: [{ exercise: '0289', sets: [{ reps: 10, weight: 20 }] }] }, { now: NOW, meanings: { '0289': 'as' } }).workout
+ expect(asIs.entries[0].target.dbLoad).toBeUndefined()
+ })
+})
+
+describe('found in review, round 3', () => {
+ const appSession = (start, end, w = 100, prs = []) => ({
+ ...bench(TODAY, w, prs), id: 'w-app', start: new Date(`${TODAY}T${start}`).getTime(), end: new Date(`${TODAY}T${end}`).getTime(),
+ })
+
+ it('a length the caller gave is kept, even when it reaches back past the session just logged', () => {
+ const S = profile({ workouts: [appSession('18:00:00', '19:10:00')] })
+ const r = build(S, curls({ durationMin: 60 }))
+ expect(r.problems).toBeUndefined()
+ expect(r.workout.end - r.workout.start).toBe(60 * 60000)
+ })
+
+ it('a given length that would start yesterday is a question, not a shorter session', () => {
+ const r = buildLoggedWorkout(profile(), curls({ durationMin: 90 }), { now: new Date(`${TODAY}T00:30:00`).getTime() })
+ expect(r.problems[0].field).toBe('durationMin')
+ })
+
+ it('a "just did" seconds after the app session lasts the five-minute floor and is filed after it, as a live finish', () => {
+ for (const [from, to] of [['18:00:00', '19:29:55'], ['18:50:00', '19:27:00']]) {
+ const S = profile({ workouts: [appSession(from, to)] })
+ const built = build(S, curls())
+ expect(built.workout.end - built.workout.start, from).toBe(5 * 60000)
+ const r = appendLoggedWorkout(S, built, { now: NOW })
+ expect(S.workouts.map(w => w.id), from).toEqual(['w-app', r.workout.id])
+ expect(r.workout._ts, from).toBeUndefined()
+ expect(S.exWeights['0294'], from).toEqual({ w: 12, d: TODAY })
+ }
+ })
+
+ it("a session on file newer than now (another device's clock ahead) is not jumped: badges are rebuilt", () => {
+ const ahead = appSession('19:32:00', '19:35:00', 100, ['0025'])
+ const S = profile({ workouts: [ahead] })
+ const built = build(S, { date: TODAY, exercises: [{ exercise: '0025', sets: [{ reps: 3, weight: 110 }] }] })
+ expect(built.workout.end - built.workout.start).toBe(5 * 60000)
+ const r = appendLoggedWorkout(S, built, { now: NOW })
+ expect(S.workouts.map(w => w.id)).toEqual([r.workout.id, 'w-app'])
+ expect(r.workout.prs).toEqual(['0025'])
+ expect(S.workouts[1].prs).toEqual([])
+ })
+})
diff --git a/mcp/README.md b/mcp/README.md
index f03cbb8a1..f53501bf6 100644
--- a/mcp/README.md
+++ b/mcp/README.md
@@ -3,19 +3,19 @@
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.
+self-hosted `./data` directory, and log a workout you describe to it.
-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.
+It runs locally as a stdio process spawned by the LLM client and adds no new container. The
+read tools need no authentication: they read the same `state-<uid>.json` files the openGym api
+already writes, and the LLM never sees passkeys, VAPID keys, or session secrets. The one write
+tool, `log_workout`, is off until you pair it with your server (see
+[Logging workouts](#logging-workouts)).
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.
+> Phase 1 of a multi-phase plan, plus the first write tool. See **Roadmap** below.
## Quick start
@@ -67,7 +67,7 @@ the server's stderr.
## Tools
-Nine read-only tools in v1:
+Nine read-only tools, and one that writes:
| Tool | What it answers |
|---|---|
@@ -80,6 +80,7 @@ Nine read-only tools in v1:
| `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. |
+| `log_workout` | *Writes.* "I did dumbbell curls, 12 kg, 12/12/10" → a logged session in your history, on every device. Needs pairing: [Logging workouts](#logging-workouts). |
`get_routine` and `preview_session` answer two different questions, and confusing them is the
easiest way for a coach to give wrong advice. `get_routine` reports what the routine *stores*.
@@ -93,6 +94,70 @@ Each tool returns JSON the LLM can format as it likes; structured fields (sets,
are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to
re-interpret them.
+## Logging workouts
+
+`log_workout` lets you tell your LLM what you did instead of tapping it in:
+
+> "Log today: dumbbell curls, 12 kg, three sets of 12 except the last was 10. Then planks, 3 × 60 s."
+
+The LLM turns that into exercises and sets; the tool matches the exercises against your library,
+builds the workout the way the app's Finish button does (PR badges, the next suggested weight,
+warm-ups kept out of volume) and saves it through your openGym server, so every signed-in
+device shows it within half a minute. Asking for the same thing twice logs it once.
+
+Exercise names are matched the way a CSV import matches them. A common name resolves to the
+library's default variant ("shoulder press" is the barbell one, "leg press" the 45° sled), and the
+reply shows what it was matched to so the LLM can check with you. What it will not do is pick
+between two entries: "lever chest press" is two in the library, and a name like that, or one that
+matches nothing, comes back as a question with candidates. It only creates one of your own
+exercises when you confirm the library has none.
+
+### Pairing
+
+Writes go through the api rather than straight into `./data`, because the api is what keeps a
+phone's sync and this write from overwriting each other. So the MCP server needs your server's
+address and a sign-in:
+
+1. In the app, signed in as the profile to log into: **Settings → Account → Pair the mobile app**.
+ It shows a one-time code (valid five minutes).
+2. Turn the code into a token:
+
+ ```bash
+ node mcp/scripts/pair.mjs https://gym.example.com ABCD-1234
+ ```
+
+3. Add both to the MCP server's `env` in your client config:
+
+ ```jsonc
+ "env": {
+ "OPENGYM_DATA": "/absolute/path/to/openGym/data",
+ "OPENGYM_URL": "https://gym.example.com",
+ "OPENGYM_TOKEN": "<the token pair.mjs printed>"
+ }
+ ```
+
+Things to know about that token:
+
+- It is a **full sign-in to your profile**, the same kind the paired phone app holds, not a
+ workout-only key. Your client's config file holds it in plain text; treat it like a password.
+- `OPENGYM_URL` has to be `https://` (plain `http://` only to `localhost`), so it never crosses a
+ network in the clear.
+- It lasts `SESSION_DAYS` (90 days by default). **Sign out everywhere** in Settings ends it at
+ once. Either way `log_workout` then says the token was not accepted: pair again.
+- Pairing again gets you a new token but does **not** end the old one. To retire a token you
+ think has leaked, use Sign out everywhere (which also disconnects paired phones).
+- If the MCP server also reads a `./data` directory, the token has to belong to the same profile
+ (`OPENGYM_UID`); a token for another one is refused. The server can be remote: without
+ `OPENGYM_DATA` the read tools have nothing to read, but `log_workout` still works.
+
+### What it does not do (yet)
+
+- Cardio by time and speed, supersets, per-side sets. Log those in the app.
+- Edit or delete a workout. Fix a mistake in the app's History.
+- Complete a routine's session. A logged workout is freestyle: it counts in history, stats,
+ 1RM, PRs and the muscle map, and like any freestyle session it can inform a routine that has
+ no history of its own, but it does not tick off a planned day or a coach week's session.
+
## How it reuses the training logic
The MCP server imports the training helpers under `frontend/src/lib/` directly as Node ESM
@@ -110,10 +175,12 @@ dependencies landed in `frontend/`, no public exports changed.
- **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.
+- **No new auth.** The read tools' boundary is the filesystem — same as `docker compose`
+ running on the user's box. No passkey material, VAPID keys, or session secrets ever cross it.
+ `log_workout` uses the paired-session token the phone app already uses; no new kind of
+ credential, no new api route.
+- **No telemetry.** The read tools make no network call. `log_workout` talks to your own
+ openGym server and nothing else. The process exits when the LLM client disconnects.
## Tests
@@ -128,15 +195,23 @@ missing routine, zero-workout history, no synced state, superset links, three 1R
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`.
+`log_workout` has two more files: `write-tools.test.js` against a stand-in api (conflicts,
+retries, a rejected token, dry runs, duplicates), and `log-workout.e2e.test.js` against the real
+`api/server.js` on a temp data directory, which needs `npm ci` in `api/` (it skips without it on
+a laptop and fails under `CI`). The workout it builds is tested in
+`frontend/src/lib/log-workout.test.js`.
+
## Roadmap
- **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access.
- **Done (Phase 1.5):** `preview_session` — the policy's next prescription, the opening set
rows it produces, and which of plan / confirmed weight / history each number came from.
-- **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 2:** read+write over stdio, in pieces (#116). Writes go through the api's own
+ `PUT /api/data` with the revision they read, as a paired device does, rather than into
+ `state-<uid>.json` directly: the api is the one writer of that file, and its sync stamps are
+ what keep a write from being undone by the next phone that merges.
+ - **Done:** `log_workout`, on the paired-session token (`scripts/pair.mjs`).
+ - Next: `add_bodyweight`, `edit_routine`, `assign_weekday`, `override_day`, log corrections.
- **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.
diff --git a/mcp/package.json b/mcp/package.json
index e1a06ba72..05d370c3c 100644
--- a/mcp/package.json
+++ b/mcp/package.json
@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"type": "module",
- "description": "MCP (Model Context Protocol) bridge for openGym — 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.",
+ "description": "MCP (Model Context Protocol) bridge for openGym — lets an external LLM read your routines, workouts, body-weight log, estimated 1RMs and muscle balance from your self-hosted data, and log a workout you describe through your own server. Stdio transport; no extra container.",
"license": "AGPL-3.0-or-later",
"main": "src/index.js",
"bin": {
diff --git a/mcp/scripts/check-node-loadable.mjs b/mcp/scripts/check-node-loadable.mjs
index 61f2f5623..8058ae2d2 100644
--- a/mcp/scripts/check-node-loadable.mjs
+++ b/mcp/scripts/check-node-loadable.mjs
@@ -22,7 +22,8 @@ const LIB = new URL('../../frontend/src/lib/', import.meta.url)
// 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', 'queue.js'
+ 'history.js', 'muscles.js', 'onerm.js', 'progression.js', 'queue.js',
+ 'import-csv.js', 'log-workout.js', 'finish-workout.js', 'dumbbells.js', 'backfill.js', 'workout-date.js', 'sync-merge.js'
]
let failed = 0
@@ -38,7 +39,7 @@ for (const m of MODULES) {
// 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']) {
+for (const entry of ['../src/state.js', '../src/tools.js', '../src/write-tools.js']) {
try {
await import(new URL(entry, import.meta.url))
console.log(` ok mcp/${entry.replace('../', '')}`)
diff --git a/mcp/scripts/pair.mjs b/mcp/scripts/pair.mjs
new file mode 100644
index 000000000..2ebc23a9b
--- /dev/null
+++ b/mcp/scripts/pair.mjs
@@ -0,0 +1,47 @@
+#!/usr/bin/env node
+/* Turn a pairing code into the token log_workout writes with.
+ *
+ * node scripts/pair.mjs https://gym.example.com ABCD-1234
+ *
+ * The code comes from the app, signed in as the profile to log into: Settings → Account →
+ * "Pair the mobile app". It works once, for five minutes. What comes back is a session like
+ * the phone app's: it lasts SESSION_DAYS (90 by default) and "Sign out everywhere" ends it.
+ * Pairing again gets a new one but does not end the old: to retire a token, sign out
+ * everywhere. Only the token goes to stdout, so it can be piped or captured; everything else is
+ * on stderr. */
+import { apiBase } from '../src/api-client.js'
+
+const [url, code] = process.argv.slice(2)
+if (!url || !code) {
+ console.error('usage: node scripts/pair.mjs <openGym URL> <pairing code>\n the code: Settings → Account → "Pair the mobile app", in the app signed in as your profile')
+ process.exit(2)
+}
+
+let base
+try { base = apiBase(url) } catch (e) { console.error(e.message); process.exit(2) }
+
+let res
+try {
+ res = await fetch(base + '/api/pair/redeem', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ code }),
+ signal: AbortSignal.timeout(15000),
+ // The code is a credential: a redirect would replay it to wherever it points.
+ redirect: 'manual',
+ })
+} catch (e) {
+ console.error(`could not reach ${base}: ${e?.cause?.code || e?.name || 'network error'}`)
+ process.exit(1)
+}
+if (res.status >= 300 && res.status < 400) {
+ console.error(`${base} redirects (${res.status}): use the https address openGym is actually served at`)
+ process.exit(1)
+}
+const data = await res.json().catch(() => null)
+if (!res.ok || !data?.token) {
+ console.error(res.status === 400 ? 'that code is wrong or has expired (they last five minutes): make a new one in the app' : `the server answered ${res.status}`)
+ process.exit(1)
+}
+console.error(`paired with ${data.user?.name || 'your profile'} (${data.user?.id}). Put this in the MCP config as OPENGYM_TOKEN, with OPENGYM_URL=${base}:`)
+console.log(data.token)
diff --git a/mcp/src/api-client.js b/mcp/src/api-client.js
new file mode 100644
index 000000000..c439e9f5f
--- /dev/null
+++ b/mcp/src/api-client.js
@@ -0,0 +1,83 @@
+/* The one way the MCP server writes: through the openGym api, as the app's own devices do.
+ Reads stay on the data directory (state.js). A write goes over HTTP because PUT /api/data is
+ the only place a profile's document is compared and written in one step — a second process
+ renaming the same file underneath it has no lock to take, so a phone's push landing in between
+ would be lost — and because that route is what stamps a change so every device's next merge
+ keeps it (api/sync-stamps.js names "an API client" as one of the writers it stamps for).
+
+ The credential is a paired session (scripts/pair.mjs): the same token the phone app holds,
+ good for SESSION_DAYS and revoked by "Sign out everywhere". It is a full sign-in to the
+ profile, so it only ever travels over https — plain http to this machine aside, the exception
+ passkeys make too — and it is never put into a result or an error message. */
+
+const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])
+// What a session token is made of (api/server.js makeSession: `uid:exp:ver` and a base64url MAC).
+// Checked before it goes into a header, because the header check's own error quotes the value.
+const TOKEN_CHARS = /^[A-Za-z0-9._:~+/=-]+$/
+const TIMEOUT_MS = 15000
+
+function fail(code, message, extra) {
+ const err = new Error(message)
+ err.code = code
+ if (extra) Object.assign(err, extra)
+ return err
+}
+
+/** The server's base URL, checked: https, or http to this machine. Throws ENOCONFIG. */
+export function apiBase(raw) {
+ let u
+ try { u = new URL(String(raw || '').trim()) } catch {
+ throw fail('ENOCONFIG', 'OPENGYM_URL is not a URL — the address you open openGym at, e.g. https://gym.example.com')
+ }
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && LOOPBACK.has(u.hostname))) {
+ throw fail('ENOCONFIG', 'OPENGYM_URL must be https:// (plain http only for localhost): the token it carries is a full sign-in to your profile')
+ }
+ // A subpath install (/gym) keeps its path; the routes hang off it.
+ return u.origin + u.pathname.replace(/\/+$/, '')
+}
+
+/** { base, token } from the environment, or ENOCONFIG saying what to set. */
+export function apiConfig(env = process.env) {
+ const url = (env.OPENGYM_URL || '').trim()
+ const token = (env.OPENGYM_TOKEN || '').trim()
+ if (!url || !token) {
+ throw fail('ENOCONFIG', 'logging workouts writes through your openGym server: set OPENGYM_URL and OPENGYM_TOKEN in this MCP server\'s config (mcp/README.md, "Logging workouts")')
+ }
+ if (!TOKEN_CHARS.test(token)) {
+ throw fail('ENOCONFIG', 'OPENGYM_TOKEN has characters a token never has (a line break or space from copying it?): paste it again as one line')
+ }
+ return { base: apiBase(url), token }
+}
+
+/**
+ * One request. Resolves { status, body } for 2xx and 409 (a conflict is the caller's to merge);
+ * throws EAUTH, ETOOBIG, EAPI otherwise. `fetchImpl` is for tests.
+ */
+export async function apiFetch(cfg, path, { method = 'GET', body, timeoutMs = TIMEOUT_MS, fetchImpl = fetch } = {}) {
+ let res
+ try {
+ res = await fetchImpl(cfg.base + path, {
+ method,
+ headers: { authorization: 'Bearer ' + cfg.token, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ signal: AbortSignal.timeout(timeoutMs),
+ // Never followed: a redirect to http:// or to another host would replay the profile (or,
+ // pairing, the code) there, whatever OPENGYM_URL promised.
+ redirect: 'manual',
+ })
+ } catch (e) {
+ // Only a code or a name, never the exception's text: some of them quote what was sent.
+ const why = e?.name === 'TimeoutError' ? `no answer within ${timeoutMs / 1000} s` : (e?.cause?.code || e?.name || 'network error')
+ throw fail('EAPI', `could not reach the openGym server at ${cfg.base} (${why})`)
+ }
+ if (res.status >= 300 && res.status < 400) {
+ throw fail('EAPI', `the openGym server at ${cfg.base} redirects (${res.status}); set OPENGYM_URL to the https address openGym is actually served at`, { status: res.status })
+ }
+ let data = null
+ try { data = await res.json() } catch { /* an HTML error page from a proxy: the status says enough */ }
+ if (res.ok || res.status === 409) return { status: res.status, body: data }
+ if (res.status === 401) throw fail('EAUTH', 'the openGym server did not accept OPENGYM_TOKEN: it expired or was signed out everywhere. Pair again (node mcp/scripts/pair.mjs) and update the config.')
+ if (res.status === 413) throw fail('ETOOBIG', 'the profile is larger than the server accepts in one write (MAX_BODY); nothing was saved')
+ const said = data && typeof data.error === 'string' ? `: ${data.error.slice(0, 200)}` : ''
+ throw fail('EAPI', `the openGym server answered ${res.status}${said}`, { status: res.status })
+}
diff --git a/mcp/src/index.js b/mcp/src/index.js
index 6c1ff356b..e18109544 100644
--- a/mcp/src/index.js
+++ b/mcp/src/index.js
@@ -1,10 +1,12 @@
#!/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. */
+ No extra container. The read tools make no network call; log_workout, once paired, talks to
+ your own openGym server and nothing else — 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 { WRITE_TOOLS } from './write-tools.js'
import { init, getUser } from './state.js'
const server = new McpServer({
@@ -25,14 +27,15 @@ try {
// env and restarting.
}
-for (const t of TOOLS) {
+for (const t of [...TOOLS, ...WRITE_TOOLS]) {
server.tool(
t.name,
t.description,
t.schema,
async (params) => {
try {
- const result = t.handler(params || {})
+ // log_workout talks to the server, so a handler may answer with a promise.
+ const result = await t.handler(params || {})
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] }
} catch (err) {
const code = err.code || 'ERROR'
diff --git a/mcp/src/state.js b/mcp/src/state.js
index bd45d7dea..20b542bb8 100644
--- a/mcp/src/state.js
+++ b/mcp/src/state.js
@@ -5,6 +5,8 @@ import fs from 'node:fs'
import path from 'node:path'
const DATA_DIR = process.env.OPENGYM_DATA || path.join(process.cwd(), 'data')
+// Whether a data directory was asked for, as opposed to the ./data guess.
+const DATA_SET = !!process.env.OPENGYM_DATA
// null = no state file (brand-new account); undefined = not yet loaded.
let _state = undefined
@@ -152,6 +154,27 @@ export function getUser() {
export const dataDir = () => DATA_DIR
+// The profile this server is set up for, which log_workout holds a token against: OPENGYM_UID
+// when it is given, whether or not its data is readable here, else the one the data directory
+// names. null only when nothing names one: no OPENGYM_UID, no OPENGYM_DATA and no ./data, the
+// remote-server setup. A data directory that was asked for and cannot be read, or that holds
+// several profiles, throws: a broken mount is no licence to write to whichever profile the token is.
+export function localUid() {
+ if (_uid !== null) return _uid
+ const envUid = (process.env.OPENGYM_UID || '').trim()
+ if (envUid) return envUid
+ if (!DATA_SET && !fs.existsSync(DATA_DIR)) return null
+ init()
+ return _uid
+}
+
+// Drop the cached state, so the next read sees a write log_workout just made without waiting for
+// the watcher. Only meaningful when this data directory is the one the server writes.
+export function invalidate() {
+ _state = undefined
+ _loadedMtime = 0
+}
+
// Test-only: work against a passed-in state, not the disk.
export function _seedStateForTests(state) {
_uid = 'test-uid'
diff --git a/mcp/src/tools.js b/mcp/src/tools.js
index 64cb93a78..c2d5d92eb 100644
--- a/mcp/src/tools.js
+++ b/mcp/src/tools.js
@@ -28,7 +28,7 @@ import { buildSessionEntries, startsFromLast } from '../../frontend/src/lib/sess
// as a zod refine that is a -32602 at the SDK boundary instead of a confident wrong answer.
const localIso = d => d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
const todayIso = () => localIso(new Date())
-const isoDate = () => z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'must be YYYY-MM-DD').refine(
+export const isoDate = () => z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'must be YYYY-MM-DD').refine(
v => { const d = new Date(v + 'T12:00:00'); return !Number.isNaN(d.getTime()) && localIso(d) === v },
{ message: 'not a date the calendar has (YYYY-MM-DD)' }
)
@@ -46,12 +46,12 @@ const exerciseOf = (id, S) => customOf(id, S) || exOr(id)
// registers its customs) takes the larger one. It registers the profile's customs for the length
// of one synchronous build and takes them back out in the same call: nothing else, and no other
// profile's read, can run in between.
-function withCustomsIndexed(S, build) {
+export function withCustomsIndexed(S, build) {
registerCustom(Array.isArray(S.customEx) ? S.customEx : [])
try { return build() } finally { registerCustom([]) }
}
-function entryView(e, S) {
+export function entryView(e, S) {
const ex = exerciseOf(e.id, S)
// 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
diff --git a/mcp/src/write-tools.js b/mcp/src/write-tools.js
new file mode 100644
index 000000000..b1c8ae046
--- /dev/null
+++ b/mcp/src/write-tools.js
@@ -0,0 +1,190 @@
+/* The write tool. log_workout files a session the user describes ("dumbbell curls, 12 kg,
+ 12/12/10, last set to failure") into their history, through their own openGym server
+ (api-client.js), as if it had been logged on the phone: every device shows it within the
+ half minute they poll the revision.
+
+ The language is the LLM's job and the arithmetic is the lib's (frontend/src/lib/log-workout.js):
+ the client turns what was said into exercises and sets, and this builds, checks and files them.
+ What the lib will not guess at — a name the library spells twice, an exercise the user has not
+ made yet — comes back as `problems` with candidates, for the LLM to put to the user. */
+import { z } from 'zod'
+import { isoDate, entryView, withCustomsIndexed } from './tools.js'
+import { localUid, invalidate } from './state.js'
+import { apiConfig, apiFetch } from './api-client.js'
+import { buildLoggedWorkout, appendLoggedWorkout, findDuplicate, BODY_PARTS, LOG_LIMITS } from '../../frontend/src/lib/log-workout.js'
+import { friendlyDuration } from './labels.js'
+
+const localIso = d => d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
+const hhmm = t => { const d = new Date(t); return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0') }
+// Two writers racing the same profile resolve in a round or two; past that something keeps
+// writing, and the user is better told than retried at.
+const MAX_ATTEMPTS = 3
+
+function fail(code, message) {
+ const err = new Error(message)
+ err.code = code
+ return err
+}
+
+// The tool's snake_case parameters as the lib's description.
+const inputOf = p => ({
+ date: p.date,
+ start: p.start,
+ durationMin: p.duration_min,
+ name: p.name,
+ note: p.note,
+ unit: p.unit,
+ exercises: (p.exercises || []).map(ex => ({
+ exercise: ex.exercise,
+ createCustom: ex.create_custom,
+ bodyPart: ex.body_part,
+ note: ex.note,
+ sets: (ex.sets || []).map(s => ({ reps: s.reps, seconds: s.seconds, weight: s.weight, warmup: s.warmup, failure: s.failure, rir: s.rir, rpe: s.rpe })),
+ })),
+})
+
+// What was (or would be) saved, read back the way get_workout reads a session, so the user can
+// check it in the words the app uses ("12 × 12 kg", "1:00").
+function viewOf(w, S, resolved) {
+ const withCustoms = { ...S, customEx: [...(S.customEx || []), ...resolved.customEx] }
+ return {
+ workout_id: w.id,
+ date: w.d,
+ start: hhmm(w.start),
+ duration: w.end > w.start ? friendlyDuration(w.end - w.start) : null,
+ name: w.name,
+ unit: S.unit === 'lb' ? 'lb' : 'kg',
+ volume: w.vol,
+ ...(w.note ? { note: w.note } : {}),
+ prs: (w.prs || []).map(id => resolved.resolved.find(r => r.id === id)?.name || id),
+ exercises: w.entries.map(e => {
+ const v = entryView(e, withCustoms)
+ const r = resolved.resolved.find(x => x.id === e.id)
+ return {
+ id: e.id,
+ name: v.name,
+ ...(r?.input !== undefined && r.input !== v.name ? { you_said: r.input } : {}),
+ ...(r?.created ? { new_custom_exercise: true } : {}),
+ ...(r?.weightMeans ? { weight_means: r.weightMeans === 'each' ? 'per dumbbell' : 'both dumbbells together' } : {}),
+ // The numbers spelled out next to the app's own label ("12×10 F": 12 kg, 10 reps, to
+ // failure), so reading it back to the user cannot swap the weight and the reps.
+ sets: e.sets.map((row, i) => ({
+ label: v.sets[i].label,
+ weight: Number(row.w) || 0,
+ ...(row.sec != null ? { seconds: row.sec } : { reps: row.r }),
+ ...(row.phase === 'warmup' ? { warmup: true } : {}),
+ ...(row.failure ? { failure: true } : {}),
+ ...(row.rir != null ? { rir: row.rir } : {}),
+ ...(row.rpe != null ? { rpe: row.rpe } : {}),
+ })),
+ ...(e.note ? { note: e.note } : {}),
+ }
+ }),
+ }
+}
+
+const setSchema = z.object({
+ reps: z.number().int().min(1).max(LOG_LIMITS.maxReps).optional().describe('Reps done. Give reps for a rep exercise, or seconds for a hold — never both in one exercise.'),
+ seconds: z.number().min(1).max(LOG_LIMITS.maxSec).optional().describe('Seconds held, for a timed exercise (plank, hang, wall sit).'),
+ weight: z.number().min(0).optional().describe('Load in `unit`. Omit or 0 for bodyweight. On an assistance machine it is the help (less is better). For dumbbells: as the profile logs that exercise — see weight_means in the reply.'),
+ warmup: z.boolean().optional().describe('A warm-up set: kept out of volume, PRs and the next suggested weight.'),
+ failure: z.boolean().optional().describe('Taken to failure.'),
+ rir: z.number().min(0).max(10).optional().describe('Reps in reserve, if the user said it. Not with rpe.'),
+ rpe: z.number().min(6).max(10).optional().describe('RPE, if the user said it. Not with rir.'),
+})
+
+export const logWorkout = {
+ name: 'log_workout',
+ description: [
+ 'Log a workout the user describes into their openGym history (it syncs to all their devices). Turn what they said into exercises and one entry per set:',
+ '"curls, 12 kg, 12/12/10" is three sets of {reps, weight: 12}; "3 sets of 12, except the last was 10" is 12, 12, 10.',
+ 'Ask instead of assuming when the weight, the number of sets or the reps are unclear.',
+ 'Exercises are matched against the user\'s library by name or id. A common name resolves to the library\'s default variant ("shoulder press" is the barbell one): when the reply\'s `name` differs from `you_said` and the variant matters (dumbbell vs barbell, machine vs cable), confirm with the user, or pass an id. If a name matches several exercises, or none, nothing is saved and `problems` lists candidates: ask the user which one, then call again with its id.',
+ 'Only set create_custom for an exercise the user confirms is not in the library.',
+ 'Call with dry_run: true first when you had to interpret anything, show the user the preview, and log it once they agree.',
+ 'Calling again with the same description does not log it twice. Cardio (time and speed) and supersets are not supported here.',
+ ].join(' '),
+ schema: {
+ date: isoDate().optional().describe('YYYY-MM-DD the session was done; defaults to today. Not in the future.'),
+ start: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'HH:MM, 24 h').optional().describe('Start time HH:MM, if the user said it. Without it a session logged today ends now; one in the past starts at 18:00.'),
+ duration_min: z.number().min(1).max(LOG_LIMITS.maxDurationMin).optional().describe('How long the session took, in minutes, if known.'),
+ name: z.string().max(80).optional().describe('A name for the session, e.g. "Arms" or "Push day". Defaults to "Workout".'),
+ note: z.string().max(500).optional().describe('A note on the whole session.'),
+ unit: z.enum(['kg', 'lb']).optional().describe('The unit the user gave weights in; defaults to the profile\'s. Converted when it differs.'),
+ exercises: z.array(z.object({
+ exercise: z.string().min(1).max(120).describe('Exercise name as the user said it ("dumbbell curl"), or an exercise id from an earlier answer.'),
+ create_custom: z.boolean().optional().describe('Create this as the user\'s own exercise when the library has nothing matching. Only after the user confirms.'),
+ body_part: z.enum(BODY_PARTS).optional().describe('Body part of a new custom exercise, when its name does not say.'),
+ note: z.string().max(280).optional().describe('A note on this exercise today.'),
+ sets: z.array(setSchema).min(1).max(LOG_LIMITS.maxSets),
+ })).min(1).max(LOG_LIMITS.maxExercises),
+ dry_run: z.boolean().optional().describe('Build and return the preview without saving anything.'),
+ allow_duplicate: z.boolean().optional().describe('Log it even though the same sets are already logged that day (a genuine second session). Give it a different start or name too.'),
+ },
+ handler: async (params, { env = process.env, fetchImpl } = {}) => {
+ const cfg = apiConfig(env)
+ const opts = fetchImpl ? { fetchImpl } : {}
+ // One clock for every attempt: a retry after a conflict files the same workout, not a later one.
+ const now = Date.now()
+ const input = inputOf({ ...params, date: params.date || localIso(new Date(now)) })
+
+ const me = await apiFetch(cfg, '/api/me', opts)
+ const uid = me.body?.user?.id
+ // A guard that cannot read whose token this is refuses rather than steps aside.
+ if (typeof uid !== 'string' || !uid) throw fail('EAPI', 'the openGym server did not say which profile OPENGYM_TOKEN belongs to (GET /api/me); nothing was saved')
+ const local = localUid()
+ if (local && local !== uid) {
+ // The ids go to the operator on stderr, not into the model's context (state.js ambiguousUid).
+ console.error(`[opengym-mcp] OPENGYM_TOKEN is for profile ${uid}, this server reads ${local}`)
+ throw fail('EPROFILE', 'OPENGYM_TOKEN belongs to another profile than the one this server reads: pair again from the right profile, or set OPENGYM_UID to match (the ids are on the server\'s stderr)')
+ }
+
+ let got = await apiFetch(cfg, '/api/data', opts)
+ // A description without a unit is in the profile's, as the profile was when first read: a
+ // retry after another device switched kg ↔ lb reads the same numbers the same way.
+ let unit = null, meanings = null
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
+ const doc = got.body?.state
+ if (!doc || typeof doc !== 'object') {
+ throw fail('ENOSTATE', 'this profile has no synced data on the server yet: open openGym and sign in on a device once, then try again')
+ }
+ // The document exactly as the server sent it, plus the workout: anything else in the PUT —
+ // a default filled in here — would be stamped as an edit made now and land on every device.
+ const S = structuredClone(doc)
+ unit = unit || (S.unit === 'lb' ? 'lb' : 'kg')
+ // The profile's own exercises indexed for the build, as the app has them: a custom one-arm
+ // dumbbell press counts one bell, a custom assisted machine folds towards less help.
+ const built = withCustomsIndexed(S, () => buildLoggedWorkout(S, input, { now, unit, meanings }))
+ if (built.problems) {
+ return { logged: false, problems: built.problems, next: 'Nothing was saved. Settle these with the user (pick a candidate id, fix a set) and call again.' }
+ }
+ // What each dumbbell weight meant on the first read stays what it means on a retry.
+ meanings = meanings || Object.fromEntries(built.workout.entries.map(e => [e.id, e.target?.dbLoad || 'as']))
+ const preview = viewOf(built.workout, S, built)
+ if (params.dry_run) {
+ const dup = findDuplicate(S, built.workout)
+ return { logged: false, dry_run: true, would_log: preview, ...(dup && (dup.sameRequest || !params.allow_duplicate) ? { duplicate_of: dup.workout.id } : {}) }
+ }
+ const added = withCustomsIndexed({ customEx: [...(S.customEx || []), ...built.customEx] }, () =>
+ appendLoggedWorkout(S, built, { now, allowDuplicate: params.allow_duplicate === true }))
+ if (!added.added) {
+ return { logged: false, duplicate: true, workout_id: added.workout.id, date: added.workout.d, message: 'This session is already in the history; nothing was added. If it really was a second session, call again with allow_duplicate: true and a different start or name.' }
+ }
+ const put = await apiFetch(cfg, '/api/data', { ...opts, method: 'PUT', body: { state: S, baseRev: got.body.rev ?? 0, ...(typeof doc._wid === 'string' ? { baseWid: doc._wid } : {}) } })
+ if (put.status !== 409) {
+ invalidate()
+ return { logged: true, ...viewOf(added.workout, S, built), revision: put.body?.rev ?? null }
+ }
+ // Another device wrote in between: the server sent its current document back with the 409,
+ // so the workout is built again on top of that one. A 409 without one (a proxy's page) is
+ // not something to build on.
+ if (!put.body?.state || typeof put.body.state !== 'object' || typeof put.body.rev !== 'number') {
+ throw fail('EAPI', 'the openGym server answered 409 without the current profile; nothing was saved')
+ }
+ got = { status: 200, body: { state: put.body.state, rev: put.body.rev } }
+ }
+ throw fail('ECONFLICT', `the profile kept changing on the server (${MAX_ATTEMPTS} attempts); nothing was saved — try again in a moment`)
+ },
+}
+
+export const WRITE_TOOLS = [logWorkout]
diff --git a/mcp/test/log-workout.e2e.test.js b/mcp/test/log-workout.e2e.test.js
new file mode 100644
index 000000000..305c1b744
--- /dev/null
+++ b/mcp/test/log-workout.e2e.test.js
@@ -0,0 +1,159 @@
+// log_workout against the real api/server.js in a child process, on a temp data directory: what
+// the server stores when the MCP writes, read back off disk and through the server's own routes.
+// Needs api/'s dependencies (`npm ci` in api/). Without them it skips on a laptop and fails in CI,
+// so a green run there always means it ran.
+import { describe, test, expect, beforeAll, afterAll } from 'vitest'
+import crypto from 'node:crypto'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { spawn } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+
+const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'api')
+const HAVE_API = fs.existsSync(path.join(API, 'node_modules', '@simplewebauthn', 'server'))
+if (!HAVE_API && process.env.CI) throw new Error('api/node_modules is missing: run `npm ci` in api/ before the MCP tests in CI')
+
+const SECRET = crypto.randomBytes(32).toString('hex')
+const UID = 'u_mcp_1'
+const mint = uid => {
+ const payload = `${uid}:${Date.now() + 86400000}:0`
+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url')
+}
+const TOKEN = mint(UID)
+const at = (d, hh) => new Date(`${d}T${hh}:00`).getTime()
+// A document the way a device leaves it: settings, a routine, a workout, the records of edits.
+const DOC = {
+ unit: 'kg', restSec: 120, effort: 'rir', targetW: 80,
+ routines: [{ id: 'r1', name: 'Push', ex: [{ id: '0025', sets: 3, reps: 5, weight: 100, mode: 'reps' }], _ts: 1000 }],
+ week: { 1: ['r1'] },
+ workouts: [{ id: 'w-old', d: '2026-10-13', start: at('2026-10-13', '18:00'), end: at('2026-10-13', '19:00'), routineIds: ['r1'], routineId: 'r1', name: 'Push', prs: [], entries: [{ id: '0025', sets: [{ w: 100, r: 5, done: true }], topW: 100, target: null }] }],
+ exWeights: { '0025': { w: 100, d: '2026-10-13' } },
+ customEx: [], bodyweight: [{ d: '2026-10-13', w: 80, t: 1000 }],
+ deleted: {}, edited: { restSec: 900, effort: 900 },
+ _rev: 5, _wid: 'w-seed', _ts: 1000,
+}
+
+let child, dataDir, base, log = ''
+const get = async p => (await fetch(base + p, { headers: { authorization: 'Bearer ' + TOKEN } })).json()
+const stored = () => JSON.parse(fs.readFileSync(path.join(dataDir, `state-${UID}.json`), 'utf8'))
+
+describe.skipIf(!HAVE_API)('log_workout against the real api', () => {
+ let logWorkout, getState, TOOLS
+ beforeAll(async () => {
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-mcp-e2e-'))
+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 })
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: UID, name: 'Matt', created: new Date().toISOString() }], creds: [], subs: [], invites: [] }))
+ fs.writeFileSync(path.join(dataDir, `state-${UID}.json`), JSON.stringify(DOC))
+ child = spawn(process.execPath, ['server.js'], {
+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' },
+ })
+ child.stderr.on('data', d => { log += d })
+ // The boot line names the port the child bound (api/test/helpers.mjs boundPort): address and
+ // readiness signal at once.
+ const port = await new Promise((resolve, reject) => {
+ const give = setTimeout(() => reject(new Error('server never announced a port:\n' + log)), 20000)
+ child.stdout.on('data', d => {
+ log += d
+ const m = /gym-api on :(\d+)/.exec(log)
+ if (m) { clearTimeout(give); resolve(+m[1]) }
+ })
+ child.once('exit', code => { clearTimeout(give); reject(new Error(`server exited (${code}):\n${log}`)) })
+ })
+ base = `http://127.0.0.1:${port}`
+ // The read tools read the same directory the server writes, as on a real install.
+ process.env.OPENGYM_DATA = dataDir
+ process.env.OPENGYM_UID = UID
+ ;({ logWorkout } = await import('../src/write-tools.js'))
+ ;({ getState } = await import('../src/state.js'))
+ ;({ TOOLS } = await import('../src/tools.js'))
+ }, 30000)
+ afterAll(() => {
+ child?.kill('SIGKILL')
+ if (dataDir) fs.rmSync(dataDir, { recursive: true, force: true })
+ })
+
+ const env = () => ({ OPENGYM_URL: base, OPENGYM_TOKEN: TOKEN })
+ const CURLS = { exercises: [{ exercise: 'dumbbell curl', sets: [{ reps: 12, weight: 12 }, { reps: 12, weight: 12 }, { reps: 10, weight: 12 }] }] }
+
+ test('stored: the device document as it was, plus one workout, one revision on', async () => {
+ // read the revision first, so the stat cache holds rev 5 when the write lands
+ expect((await get('/api/data/rev')).rev).toBe(5)
+ const r = await logWorkout.handler(CURLS, { env: env() })
+ expect(r.logged).toBe(true)
+
+ const after = stored()
+ expect(after._rev).toBe(6) // +1: the server found nothing to restamp
+ expect((await get('/api/data/rev')).rev).toBe(6) // and the cached revision moved with it
+ expect(after._wids).toContain('w-seed')
+ expect(after.workouts.map(w => w.id)).toEqual(['w-old', r.workout_id])
+ expect(after.edited).toEqual(DOC.edited)
+ for (const k of ['unit', 'restSec', 'effort', 'targetW', 'routines', 'week', 'bodyweight', 'customEx']) expect(after[k]).toEqual(DOC[k])
+ expect(after.deleted ?? {}).toEqual({}) // no removal on record (an empty map is not kept)
+ // the server added only its own bookkeeping, and nothing a device would read as a setting
+ const extra = Object.keys(after).filter(k => !(k in DOC))
+ expect(extra.filter(k => !k.startsWith('_'))).toEqual([])
+ const w = after.workouts[1]
+ expect(w.entries[0]).toMatchObject({ id: '0294', sets: [{ w: 12, r: 12, done: true }, { w: 12, r: 12, done: true }, { w: 12, r: 10, done: true }] })
+ })
+
+ test('read back by the read tools, from the same directory, straight away', async () => {
+ const S = getState()
+ expect(S.workouts).toHaveLength(2)
+ const list = TOOLS.find(t => t.name === 'list_workouts').handler({ limit: 5 })
+ expect(JSON.stringify(list)).toContain('Workout')
+ })
+
+ test('the same call again stores nothing', async () => {
+ const r = await logWorkout.handler(CURLS, { env: env() })
+ expect(r).toMatchObject({ logged: false, duplicate: true })
+ expect(stored()._rev).toBe(6)
+ })
+
+ test('a backup restored in between (same revision, another write id) is merged, not written over', async () => {
+ let restored = false
+ const fetchImpl = async (url, opts) => {
+ if (opts?.method === 'PUT' && !restored) {
+ restored = true
+ // the operator puts back a copy whose counter happens to match: only the write id differs
+ const cur = stored()
+ fs.writeFileSync(path.join(dataDir, `state-${UID}.json`), JSON.stringify({ ...cur, targetW: 77, _wid: 'w-restored' }))
+ }
+ return fetch(url, opts)
+ }
+ const r = await logWorkout.handler({ date: '2026-10-12', exercises: [{ exercise: '0025', sets: [{ reps: 5, weight: 95 }] }] }, { env: env(), fetchImpl })
+ expect(r.logged).toBe(true)
+ const after = stored()
+ expect(after.targetW).toBe(77)
+ expect(after._wids).toContain('w-restored')
+ expect(after.workouts.some(w => w.d === '2026-10-12')).toBe(true)
+ })
+
+ test('a phone pushing in between: both its change and the workout survive', async () => {
+ const phonePush = async () => {
+ const cur = await get('/api/data')
+ const next = { ...cur.state, restSec: 75 }
+ const res = await fetch(base + '/api/data', {
+ method: 'PUT', headers: { authorization: 'Bearer ' + TOKEN, 'content-type': 'application/json' },
+ body: JSON.stringify({ state: next, baseRev: cur.rev, baseWid: cur.state._wid }),
+ })
+ expect(res.status).toBe(200)
+ }
+ let pushed = false
+ // the phone's write lands after the MCP read the document and before it writes
+ const fetchImpl = async (url, opts) => {
+ if (opts?.method === 'PUT' && !pushed) { pushed = true; await phonePush() }
+ return fetch(url, opts)
+ }
+ const r = await logWorkout.handler({ date: '2026-10-14', exercises: [{ exercise: '0025', sets: [{ reps: 5, weight: 102.5 }] }] }, { env: env(), fetchImpl })
+ expect(r.logged).toBe(true)
+ const after = stored()
+ expect(after.restSec).toBe(75)
+ const days = after.workouts.map(w => w.d)
+ expect(days).toContain('2026-10-14')
+ expect(days).toEqual([...days].sort())
+ // into the past: a backfill, so the confirmed weight stays where the device left it
+ expect(after.exWeights['0025']).toEqual(DOC.exWeights['0025'])
+ })
+})
diff --git a/mcp/test/write-tools.test.js b/mcp/test/write-tools.test.js
new file mode 100644
index 000000000..9de19fe3c
--- /dev/null
+++ b/mcp/test/write-tools.test.js
@@ -0,0 +1,267 @@
+// log_workout against a stand-in for the api: a node:http server that answers /api/me and
+// /api/data the way api/server.js does, and records what it is sent. What the real server does
+// with the write is log-workout.e2e.test.js; the arithmetic is frontend/src/lib/log-workout.test.js.
+import { describe, test, expect, beforeEach, afterEach } from 'vitest'
+import http from 'node:http'
+import { logWorkout } from '../src/write-tools.js'
+import { apiBase, apiConfig } from '../src/api-client.js'
+import { _seedStateForTests } from '../src/state.js'
+
+const TOKEN = 'tok.secret-value'
+const UID = 'u1'
+const today = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0') }
+
+let api
+// `script.put` answers each PUT in turn; past the end it accepts.
+function stubApi(doc, script = {}) {
+ const s = { doc: structuredClone(doc), rev: 7, puts: [], gets: 0, auth: [], script }
+ const server = http.createServer(async (req, res) => {
+ s.auth.push(req.headers.authorization)
+ const send = (code, body) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)) }
+ if (req.headers.authorization !== 'Bearer ' + TOKEN) return send(401, { error: 'not signed in' })
+ if (req.url === '/api/me') return send(200, { user: { id: script.uid || UID, name: 'Matt' }, token: 'renewed.secret' })
+ if (req.url === '/api/data' && req.method === 'GET') { s.gets++; return send(200, { state: s.doc, rev: s.rev }) }
+ if (req.url === '/api/data' && req.method === 'PUT') {
+ let raw = ''
+ for await (const c of req) raw += c
+ const body = JSON.parse(raw)
+ s.puts.push(body)
+ const next = (script.put || [])[s.puts.length - 1]
+ if (next) return next(send, s)
+ if (body.baseRev !== s.rev) return send(409, { error: 'conflict', rev: s.rev, state: s.doc })
+ s.doc = body.state
+ s.rev++
+ return send(200, { ok: true, rev: s.rev })
+ }
+ send(404, { error: 'not found' })
+ })
+ return new Promise(resolve => server.listen(0, '127.0.0.1', () => {
+ s.server = server
+ s.env = { OPENGYM_URL: `http://127.0.0.1:${server.address().port}`, OPENGYM_TOKEN: TOKEN }
+ resolve(s)
+ }))
+}
+afterEach(() => api?.server.close())
+
+const DOC = () => ({ unit: 'kg', workouts: [], routines: [{ id: 'r1', name: 'Push', ex: [] }], customEx: [], exWeights: {}, edited: { restSec: 5 }, restSec: 120, _wid: 'w-abc', _ts: 1 })
+const CURLS = { exercises: [{ exercise: 'dumbbell curl', sets: [{ reps: 12, weight: 12 }, { reps: 12, weight: 12 }, { reps: 10, weight: 12, failure: true }] }] }
+const call = (params, env = api.env) => logWorkout.handler(params, { env })
+
+describe('log_workout writes through the server', () => {
+ beforeEach(async () => { api = await stubApi(DOC()) })
+
+ test('the document the server sent, plus the workout, with the revision and write id it was read at', async () => {
+ const r = await call(CURLS)
+ expect(r.logged).toBe(true)
+ expect(r.date).toBe(today())
+ expect(r.exercises[0]).toMatchObject({ id: '0294', you_said: 'dumbbell curl' })
+ expect(r.exercises[0].sets).toHaveLength(3)
+ expect(r.exercises[0].sets.map(x => x.label)).toEqual(['12×12', '12×12', '12×10 F'])
+ expect(r.exercises[0].sets[2]).toMatchObject({ weight: 12, reps: 10, failure: true })
+ expect(api.puts).toHaveLength(1)
+ const put = api.puts[0]
+ expect(put).toMatchObject({ baseRev: 7, baseWid: 'w-abc' })
+ expect(put.stamped).toBeUndefined()
+ // nothing the server did not send: no defaults (lang, theme…) for it to stamp as edits
+ const { workouts, _ts, ...rest } = put.state
+ const { workouts: w0, _ts: t0, ...rest0 } = DOC()
+ expect(rest).toEqual({ ...rest0, exWeights: { '0294': { w: 12, d: today() } } })
+ expect(workouts).toHaveLength(1)
+ expect(_ts).toBeGreaterThan(t0)
+ expect(r.revision).toBe(8)
+ })
+
+ test('dry_run builds the preview and writes nothing', async () => {
+ const r = await call({ ...CURLS, dry_run: true })
+ expect(r).toMatchObject({ logged: false, dry_run: true })
+ expect(r.would_log.exercises[0].name).toBeTruthy()
+ expect(api.puts).toHaveLength(0)
+ })
+
+ test('a name with several matches comes back as problems with candidates, and nothing is written', async () => {
+ const r = await call({ exercises: [{ exercise: 'lever chest press', sets: [{ reps: 10, weight: 40 }] }] })
+ expect(r.logged).toBe(false)
+ expect(r.problems[0].candidates.length).toBeGreaterThan(1)
+ expect(api.puts).toHaveLength(0)
+ })
+
+ test('the same call again is the same workout: no second write', async () => {
+ expect((await call(CURLS)).logged).toBe(true)
+ const again = await call(CURLS)
+ expect(again).toMatchObject({ logged: false, duplicate: true })
+ expect(api.puts).toHaveLength(1)
+ expect(api.doc.workouts).toHaveLength(1)
+ })
+
+ test('a 409 is merged on the document it carries and written again, once', async () => {
+ // a phone pushes between the MCP's read and its write
+ api.script.put = [(send, s) => {
+ s.doc = { ...s.doc, restSec: 90, routines: [...s.doc.routines, { id: 'r2', name: 'Pull', ex: [] }], _wid: 'w-phone' }
+ s.rev = 8
+ send(409, { error: 'conflict', rev: s.rev, state: s.doc })
+ }]
+ const r = await call(CURLS)
+ expect(r.logged).toBe(true)
+ expect(api.puts).toHaveLength(2)
+ expect(api.puts[1]).toMatchObject({ baseRev: 8, baseWid: 'w-phone' })
+ expect(api.doc.restSec).toBe(90)
+ expect(api.doc.routines.map(x => x.id)).toEqual(['r1', 'r2'])
+ expect(api.doc.workouts).toHaveLength(1)
+ // the retry files the same workout, not one stamped a moment later
+ expect(api.puts[1].state.workouts[0].id).toBe(api.puts[0].state.workouts[0].id)
+ })
+
+ test('a profile that never stops changing gives up after three tries, saying so', async () => {
+ const conflict = (send, s) => { s.rev++; send(409, { error: 'conflict', rev: s.rev, state: s.doc }) }
+ api.script.put = [conflict, conflict, conflict]
+ await expect(call(CURLS)).rejects.toMatchObject({ code: 'ECONFLICT' })
+ })
+
+ test('a rejected token says what to do, and never repeats the token or the renewed one', async () => {
+ const err = await call(CURLS, { ...api.env, OPENGYM_TOKEN: 'wrong' }).catch(e => e)
+ expect(err.code).toBe('EAUTH')
+ expect(err.message).toMatch(/pair again/i)
+ expect(err.message).not.toContain('wrong')
+ const ok = JSON.stringify(await call(CURLS))
+ expect(ok).not.toContain('secret')
+ })
+
+ test('a server error and an unreachable server are errors with the status, not a silent no-op', async () => {
+ api.script.put = [send => send(500, { error: 'disk full' })]
+ await expect(call(CURLS)).rejects.toMatchObject({ code: 'EAPI', message: expect.stringContaining('500: disk full') })
+ await expect(call(CURLS, { ...api.env, OPENGYM_URL: 'http://127.0.0.1:1' })).rejects.toMatchObject({ code: 'EAPI' })
+ })
+
+ test('a profile with nothing synced yet is told to sign in once, not given a document of one workout', async () => {
+ api.doc = null
+ await expect(call(CURLS)).rejects.toMatchObject({ code: 'ENOSTATE' })
+ expect(api.puts).toHaveLength(0)
+ })
+})
+
+describe('found in review', () => {
+ beforeEach(async () => { api = await stubApi(DOC()) })
+
+ test('a 409 from a profile just switched to lb reads the same numbers in the unit first read, as the same workout', async () => {
+ api.script.put = [(send, s) => {
+ s.doc = { ...s.doc, unit: 'lb', _wid: 'w-lb' }
+ s.rev = 8
+ send(409, { error: 'conflict', rev: s.rev, state: s.doc })
+ }]
+ const r = await call({ exercises: [{ exercise: '0025', sets: [{ reps: 5, weight: 100 }] }] })
+ expect(r.logged).toBe(true)
+ const [first, second] = api.puts.map(p => p.state.workouts[0])
+ expect(first.entries[0].sets[0].w).toBe(100)
+ expect(second.entries[0].sets[0].w).toBe(220.5)
+ expect(second.id).toBe(first.id)
+ })
+
+ test("the profile's own exercises count as the app counts them: a one-arm dumbbell press logged 'each' is one bell", async () => {
+ const own = { id: 'c-oa', n: 'single arm dumbbell press', custom: true, eq: 'dumbbell', bp: 'shoulders', tg: '', desc: '' }
+ api.doc = { ...DOC(), customEx: [own], dbLoad: { 'c-oa': { mode: 'each', _ts: 1 } } }
+ const r = await call({ exercises: [{ exercise: 'c-oa', sets: [{ reps: 10, weight: 20 }] }] })
+ expect(r.logged).toBe(true)
+ expect(api.doc.workouts[0].vol).toBe(200)
+ })
+
+ test('a custom assisted machine folds towards less help: more help is not a new confirmed weight', async () => {
+ const own = { id: 'c-dip', n: 'Assisted Dip (mine)', custom: true, eq: 'custom', bp: 'chest', assisted: true, tg: '', desc: '' }
+ api.doc = { ...DOC(), customEx: [own], exWeights: { 'c-dip': { w: 20, d: '2026-10-01' } } }
+ const r = await call({ exercises: [{ exercise: 'c-dip', sets: [{ reps: 8, weight: 30 }] }] })
+ expect(r.logged).toBe(true)
+ expect(api.doc.exWeights['c-dip']).toEqual({ w: 20, d: '2026-10-01' })
+ })
+
+ test("a 409 after another device switched a dumbbell default keeps the meaning first read", async () => {
+ api.doc = { ...DOC(), dbLoad: { '0289': { mode: 'each', _ts: 1 } } }
+ api.script.put = [(send, s) => {
+ s.doc = { ...s.doc, dbLoad: { '0289': { mode: 'total', _ts: 2 } }, _wid: 'w-total' }
+ s.rev = 8
+ send(409, { error: 'conflict', rev: s.rev, state: s.doc })
+ }]
+ const r = await call({ exercises: [{ exercise: '0289', sets: [{ reps: 10, weight: 20 }] }] })
+ expect(r.logged).toBe(true)
+ const [first, second] = api.puts.map(p => p.state.workouts[0])
+ expect(second.entries[0].target.dbLoad).toBe('each')
+ expect(second.vol).toBe(first.vol)
+ expect(api.doc.dbLoad['0289'].mode).toBe('total') // the device's new default itself is kept
+ })
+
+ test('an /api/me that does not say whose token it is stops the write', async () => {
+ const odd = http.createServer((req, res) => {
+ if (req.url === '/api/me') { res.writeHead(200, { 'content-type': 'text/html' }); return res.end('<html>') }
+ res.writeHead(500); res.end()
+ })
+ await new Promise(r => odd.listen(0, '127.0.0.1', r))
+ const err = await call(CURLS, { OPENGYM_URL: `http://127.0.0.1:${odd.address().port}`, OPENGYM_TOKEN: TOKEN }).catch(e => e)
+ odd.close()
+ expect(err).toMatchObject({ code: 'EAPI', message: expect.stringContaining('/api/me') })
+ })
+
+ test('a 409 without the current profile in it is an error, not "sign in once"', async () => {
+ api.script.put = [send => send(409, { error: 'conflict' })]
+ await expect(call(CURLS)).rejects.toMatchObject({ code: 'EAPI', message: expect.stringContaining('409') })
+ })
+
+ test('a token pasted with a line break is refused without being repeated, before any request', async () => {
+ const err = await call(CURLS, { ...api.env, OPENGYM_TOKEN: 'abc.def\nsecret-tail' }).catch(e => e)
+ expect(err.code).toBe('ENOCONFIG')
+ expect(err.message).not.toContain('secret-tail')
+ expect(api.auth).toHaveLength(0)
+ })
+
+ test('a redirect is not followed: the profile is never replayed to where it points', async () => {
+ let followed = 0
+ const elsewhere = http.createServer((req, res) => { followed++; res.end('{}') })
+ await new Promise(r => elsewhere.listen(0, '127.0.0.1', r))
+ const to = `http://127.0.0.1:${elsewhere.address().port}`
+ const redirecting = http.createServer((req, res) => { res.writeHead(307, { location: to + req.url }); res.end() })
+ await new Promise(r => redirecting.listen(0, '127.0.0.1', r))
+ const err = await call(CURLS, { OPENGYM_URL: `http://127.0.0.1:${redirecting.address().port}`, OPENGYM_TOKEN: TOKEN }).catch(e => e)
+ redirecting.close(); elsewhere.close()
+ expect(err).toMatchObject({ code: 'EAPI', message: expect.stringContaining('redirects (307)') })
+ expect(followed).toBe(0)
+ })
+
+ test('an OPENGYM_UID that names another profile than the token is refused even when its data is not readable here', async () => {
+ api = await stubApi(DOC(), { uid: 'someone-else' })
+ process.env.OPENGYM_UID = 'expected-profile'
+ try {
+ await expect(call(CURLS)).rejects.toMatchObject({ code: 'EPROFILE' })
+ } finally { delete process.env.OPENGYM_UID }
+ expect(api.puts).toHaveLength(0)
+ })
+})
+
+describe('configuration', () => {
+ test('missing config is ENOCONFIG naming both variables', async () => {
+ await expect(logWorkout.handler(CURLS, { env: {} })).rejects.toMatchObject({ code: 'ENOCONFIG', message: expect.stringContaining('OPENGYM_TOKEN') })
+ })
+
+ test('https, or http only to this machine: the token is a full sign-in', () => {
+ expect(apiBase('https://gym.example.com/')).toBe('https://gym.example.com')
+ expect(apiBase('https://example.com/gym/')).toBe('https://example.com/gym')
+ expect(apiBase('http://localhost:8080')).toBe('http://localhost:8080')
+ expect(apiBase('http://127.0.0.1:8080')).toBe('http://127.0.0.1:8080')
+ expect(apiBase('http://[::1]:8080')).toBe('http://[::1]:8080')
+ expect(() => apiBase('http://gym.lan:8080')).toThrow(/https/)
+ expect(() => apiBase('http://192.168.1.5')).toThrow(/https/)
+ expect(() => apiBase('not a url')).toThrow(/not a URL/)
+ expect(() => apiConfig({ OPENGYM_URL: 'http://gym.lan', OPENGYM_TOKEN: 'x' })).toThrow(/https/)
+ })
+})
+
+// Last: seeding gives state.js a profile of its own for the rest of this file.
+describe('the token has to belong to the profile being read', () => {
+ test('a token for another profile is refused before anything is read or written', async () => {
+ api = await stubApi(DOC(), { uid: 'someone-else' })
+ _seedStateForTests(DOC())
+ const err = await call(CURLS).catch(e => e)
+ expect(err.code).toBe('EPROFILE')
+ // the account ids are the operator's (stderr), not the model's
+ expect(err.message).not.toContain('someone-else')
+ expect(err.message).not.toContain('test-uid')
+ expect(api.gets).toBe(0)
+ expect(api.puts).toHaveLength(0)
+ })
+})